diff --git a/experiment/taco_dataset_validation/data.jsonl b/experiment/taco_dataset_validation/data.jsonl new file mode 100644 index 0000000..4cc4d56 --- /dev/null +++ b/experiment/taco_dataset_validation/data.jsonl @@ -0,0 +1,500 @@ +{"requirement": "Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors.\nIf there is no such integer in the array, return 0.\n \nExample 1:\nInput: nums = [21,4,7]\nOutput: 32\nExplanation:\n21 has 4 divisors: 1, 3, 7, 21\n4 has 3 divisors: 1, 2, 4\n7 has 2 divisors: 1, 7\nThe answer is the sum of divisors of 21 only.\n\n \nConstraints:\n\n1 <= nums.length <= 10^4\n1 <= nums[i] <= 10^5", "solutions": ["import math\n\ndef remove(lst, index):\n assert lst\n tail = len(lst) - 1\n (lst[index], lst[tail]) = (lst[tail], lst[index])\n lst.pop()\n\ndef swap_min(lst):\n if not lst:\n return\n argmin = min(range(len(lst)), key=lambda i: lst[i])\n (lst[0], lst[argmin]) = (lst[argmin], lst[0])\n\ndef find_primes(top):\n candidates = list(range(2, top))\n primes = []\n while candidates:\n latest_prime = candidates[0]\n primes.append(latest_prime)\n remove(candidates, 0)\n for i in range(len(candidates) - 1, -1, -1):\n if candidates[i] % latest_prime == 0:\n remove(candidates, i)\n swap_min(candidates)\n return primes\n\ndef find_prime_factor(n, primes):\n for p in primes:\n if n % p == 0:\n return p\n\ndef div4(n, primes, setprimes):\n if n <= 3:\n return 0\n elif n in setprimes:\n return 0\n else:\n p1 = find_prime_factor(n, primes)\n if p1 is None:\n return 0\n p2 = find_prime_factor(n // p1, primes)\n if p2 is None:\n p2 = n // p1\n if p1 * p2 == n and p1 != p2:\n return (1 + p1) * (1 + p2)\n elif p1 ** 3 == n:\n return (1 + p1) * (1 + p1 ** 2)\n else:\n return 0\n\ndef sum_four_divisors(arr):\n top = math.ceil(math.sqrt(max(arr) + 5))\n primes = find_primes(top)\n setprimes = set(primes)\n return sum((div4(elem, primes, setprimes) for elem in arr))\n\ndef sumfourdivisors(nums: List[int]) -> int:\n return sum_four_divisors(nums)", "def sumfourdivisors(nums: List[int], c={}) -> int:\n r = 0\n for n in nums:\n if n in c:\n r += c[n]\n continue\n s = n + 1\n cnt = 2\n end = sqrt(n)\n if end == int(end):\n s += end\n cnt += 1\n end -= 1\n for i in range(2, int(end) + 1):\n if n % i == 0:\n cnt += 2\n if cnt > 4:\n s = 0\n break\n s += i\n s += n // i\n if cnt == 4:\n c.update({n: s})\n r += s\n else:\n c.update({n: 0})\n return r", "def sumfourdivisors(nums: List[int]) -> int:\n factors_cache = {}\n\n def get_factors(num):\n if num in factors_cache:\n return factors_cache[num]\n else:\n factors = set([1, num])\n for potential_divisor in range(2, math.ceil(math.sqrt(num))):\n if num % potential_divisor == 0:\n factors = factors.union(get_factors(potential_divisor))\n factors = factors.union(get_factors(num // potential_divisor))\n if len(factors) > 4:\n break\n factors_cache[num] = factors\n return factors\n running_sum = 0\n for num in nums:\n factors = get_factors(num)\n if len(factors) == 4:\n running_sum += sum(factors)\n return running_sum", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for num in nums:\n out = set()\n for i in range(1, int(num ** 0.5 + 1)):\n (a, b) = divmod(num, i)\n if b == 0:\n out.add(i)\n out.add(a)\n if len(out) > 4:\n break\n if len(out) == 4:\n ans += sum(out)\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for num in nums:\n ans += self.fourDivisors(num)\n return ans\n\ndef fourDivisors(num):\n memo = set()\n for i in range(1, num + 1):\n if i * i > num:\n break\n if num % i == 0:\n memo.add(i)\n memo.add(num // i)\n if len(memo) > 4:\n return 0\n if len(memo) == 4:\n return sum(memo)\n return 0", "def divs(x):\n memo = self.memo\n if x in memo:\n return memo[x]\n L = 2 if x > 1 else 1\n S = 1 + x if x > 1 else 1\n for a in range(2, x):\n if a ** 2 > x:\n break\n if not x % a:\n L += 1 if x == a ** 2 else 2\n S += a if x == a ** 2 else a + x // a\n if L > 4:\n break\n memo[x] = (L, S)\n return (L, S)\n\ndef sumfourdivisors(A):\n self.memo = {}\n res = 0\n for x in A:\n (L, S) = self.divs(x)\n if L == 4:\n res += S\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for num in nums:\n divisor_num = set()\n for i in range(1, int(sqrt(num)) + 1):\n if num % i == 0:\n divisor_num.add(num // i)\n divisor_num.add(i)\n if len(divisor_num) == 4:\n res += sum(divisor_num)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for n in nums:\n sq = floor(n ** 0.5)\n if sq * sq == n:\n continue\n divs = 2\n divsum = 1 + n\n for i in range(sq, 1, -1):\n if n % i == 0:\n divs += 2\n divsum += i + n // i\n if divs > 4:\n break\n if divs == 4:\n ans += divsum\n return ans", "def divisors(n):\n for i in range(1, int(sqrt(n) + 1)):\n if n % i == 0:\n yield i\n j = n // i\n if j != i:\n yield j\n\ndef sumfourdivisors(nums: List[int]) -> int:\n s = 0\n for n in nums:\n l = list(self.divisors(n))\n if len(l) == 4:\n s += sum(l)\n return s", "def sumfourdivisors(nums: List[int]) -> int:\n\n def make_divisors(n):\n divisors = []\n for i in range(1, int(n ** 0.5) + 1):\n if n % i == 0:\n divisors.append(i)\n if i != n // i:\n divisors.append(n // i)\n return (len(divisors), divisors)\n ret = [0]\n for n in nums:\n (l, d) = make_divisors(n)\n if l == 4:\n ret.append(sum(d))\n return sum(ret)", "def sumfourdivisors(nums: List[int]) -> int:\n sum2 = 0\n for n in nums:\n cnt = 0\n sum1 = 0\n for i in range(1, int(sqrt(n)) + 1):\n if n % i == 0:\n if i == sqrt(n):\n cnt += 1\n else:\n cnt += 2\n sum1 += i + n // i\n if cnt == 4:\n sum2 += sum1\n return sum2", "import math\n\ndef sumfourdivisors(nums: List[int]) -> int:\n divisorSum = 0\n for num in nums:\n divisorSum += self.findDivisors(num)\n return divisorSum\n\ndef findDivisors(num):\n divisors = set([1, num])\n for i in range(2, int(math.sqrt(num)) + 1):\n if num % i == 0:\n divisors.add(i)\n divisors.add(num // i)\n if len(divisors) == 4:\n return sum(list(divisors))\n return 0", "def sumfourdivisors(nums: List[int]) -> int:\n\n def count_divisors(x):\n num_divisors = 0\n sum_divisors = 0\n if sqrt(x) == int(sqrt(x)):\n num_divisors += 1\n sum_divisors += sqrt(x)\n for i in range(1, ceil(sqrt(x))):\n if x % i == 0:\n num_divisors += 2\n sum_divisors += i + x // i\n return sum_divisors if num_divisors == 4 else 0\n return sum([count_divisors(x) for x in nums])", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for num in nums:\n curr = 0\n div_sum = 0\n for i in range(1, int(sqrt(num)) + 1):\n if num % i == 0:\n curr += 2\n if i == num // i:\n div_sum -= i\n curr -= 1\n div_sum += i\n div_sum += num // i\n if curr == 4:\n res += div_sum\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n ret = 0\n for num in nums:\n ret += self.has_four_divisors(num)\n return int(ret)\n\ndef has_four_divisors(num):\n divisor_sum = 0\n divisors = 0\n for i in range(1, int(sqrt(num)) + 1):\n if num % i == 0:\n if i != num / i:\n divisors += 2\n divisor_sum += i\n divisor_sum += num / i\n else:\n divisors += 1\n divisor_sum += i\n if divisors == 4:\n return divisor_sum\n return 0", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for num in nums:\n divisor = 0\n a = 2\n upperLimit = int(num ** 0.5)\n if upperLimit ** 2 == num:\n continue\n upperLimit += 1\n subAns = 1 + num\n while a < upperLimit:\n if num % a == 0:\n if divisor == 0:\n divisor += 1\n subAns += a + num // a\n else:\n break\n upperLimit = min(upperLimit, num // a)\n a += 1\n else:\n if divisor == 1:\n ans += subAns\n return ans", "from math import sqrt\n\ndef sumfourdivisors(nums: List[int]) -> int:\n\n def helper(num):\n divisors = set()\n for i in range(1, int(sqrt(num)) + 1):\n if num % i == 0:\n divisors.add(i)\n divisors.add(num // i)\n return sum(divisors) if len(divisors) == 4 else 0\n return sum((helper(num) for num in nums))", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for n in nums:\n st = set()\n for i in range(1, int(sqrt(n)) + 1):\n if n % i == 0:\n st.add(i)\n st.add(n // i)\n if len(st) == 4:\n ans += sum(st)\n return ans", "def divs(x):\n memo = self.memo\n if x in memo:\n return memo[x]\n res = 2 if x > 1 else 1\n B = {1, x}\n for a in range(2, x):\n if x < a ** 2:\n break\n if not x % a:\n res += 1 if x == a ** 2 else 2\n B.update({a, x // a})\n if res > 4:\n break\n a += 1\n memo[x] = (res, B)\n return (res, B)\n\ndef sumfourdivisors(A):\n self.memo = {}\n res = 0\n for x in A:\n (r, B) = self.divs(x)\n if r == 4:\n res += sum(B)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n\n def NOD(x):\n divisor = set([1, x])\n for i in range(2, int(x ** 0.5) + 1):\n if not x % i:\n divisor.add(i)\n divisor.add(x // i)\n return divisor\n ans = []\n for num in nums:\n divisor = NOD(num)\n if len(divisor) == 4:\n ans.append(divisor)\n return sum([sum(i) for i in ans])", "def sumfourdivisors(nums: List[int]) -> int:\n\n def div_num(x):\n (ans, ssum) = (2, x + 1)\n for i in range(2, int(x ** 0.5) + 1):\n if x % i == 0:\n ans += 1 + (i * i != x)\n ssum += i + x // i if i * i != x else i\n return (ans == 4, ssum)\n res = 0\n for x in nums:\n (flag, ssum) = div_num(x)\n if flag == 1:\n res += ssum\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for num in nums:\n divisors = set()\n for i in range(1, int(num ** 0.5) + 1):\n if num % i == 0:\n divisors.add(i)\n divisors.add(num // i)\n if len(divisors) == 4:\n ans += sum(divisors)\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n out = 0\n for i in nums:\n temp = set()\n for j in range(1, floor(sqrt(i)) + 1):\n if i % j == 0:\n temp.add(j)\n temp.add(int(i / j))\n if len(temp) == 4:\n out += sum(temp)\n return out", "def sumfourdivisors(nums: List[int]) -> int:\n\n def findfactors(n):\n f = []\n for i in range(1, int(n ** 0.5) + 1):\n if n % i == 0:\n f.append(i)\n if i != n // i:\n f.append(n // i)\n return sum(f) if len(f) == 4 else 0\n return sum([findfactors(x) for x in nums])", "def sumfourdivisors(nums: List[int]) -> int:\n ret = 0\n for num in nums:\n divs = self.divisors(num)\n if len(divs) == 4:\n ret += sum(divs)\n return ret\n\ndef divisors(num):\n ret = []\n for i in range(1, int(num ** 0.5) + 1):\n if num % i == 0:\n ret += [i]\n if num // i != i:\n ret += [num // i]\n return ret", "import math\n\ndef sumfourdivisors(nums: List[int]) -> int:\n divisors = []\n for num in nums:\n d = set()\n for i in range(1, floor(sqrt(num) + 1)):\n if num % i == 0:\n d.add(i)\n d.add(num // i)\n divisors.append(d)\n result = 0\n for s in divisors:\n if len(s) == 4:\n result += sum(s)\n return result", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for n in nums:\n tmp = set([1, n])\n for d in range(2, ceil(sqrt(n)) + 1):\n if n % d == 0:\n tmp.add(d)\n tmp.add(n // d)\n if len(tmp) == 4:\n ans += sum(tmp)\n return ans", "import math\n\ndef s_factors_if_len_4(n, d):\n s = set()\n for i in range(1, math.floor(n ** 0.5) + 1):\n if n % i == 0:\n s.add(i)\n s.add(n // i)\n if len(s) == 4:\n d[n] = sum(s)\n else:\n d[n] = 0\n\ndef sumfourdivisors(nums: List[int]) -> int:\n d = {}\n sol = 0\n for n in nums:\n if n not in d.keys():\n self.s_factors_if_len_4(n, d)\n sol += d[n]\n return sol", "def factors(n):\n if n in self.cache:\n return self.cache[n]\n result = set()\n for i in range(1, int(n ** 0.5) + 1):\n (div, mod) = divmod(n, i)\n if mod == 0:\n result |= {i, div}\n self.cache[n] = result\n return result\n\ndef sumfourdivisors(nums: List[int]) -> int:\n factors = [self.factors(f) for f in nums]\n return sum([sum(f) for f in factors if len(f) == 4])", "def sumfourdivisors(nums: List[int]) -> int:\n\n def compute(n):\n s = set()\n for i in range(1, 1 + int(n ** 0.5)):\n if n % i == 0:\n s.add(i)\n s.add(n // i)\n return sum(s) if len(s) == 4 else 0\n return sum((compute(i) for i in nums))", "def sumfourdivisors(lst: List[int]) -> int:\n import math\n final = 0\n for i in lst:\n factors = []\n for j in range(1, round(math.sqrt(i)) + 1):\n if i % j == 0:\n factors.append(int(j))\n factors.append(int(i / j))\n factors = list(dict.fromkeys(factors))\n if len(factors) == 4:\n final += sum(factors)\n return final", "def sumfourdivisors(nums: List[int]) -> int:\n\n def isPrime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n & 1 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 and n % (i + 2) == 0:\n return False\n i += 6\n return True\n res = 0\n c = 0\n temp = set()\n for i in nums:\n for j in range(1, int(i ** 0.5) + 1):\n if i % j == 0:\n temp.add(j)\n temp.add(i // j)\n if i // j != j:\n c += 2\n else:\n c += 1\n res += sum(temp) if c == 4 else 0\n temp = set()\n c = 0\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n\n def get_divisor(num):\n val = set()\n i = 1\n while i < math.sqrt(num) + 1:\n if num % i == 0:\n val.add(i)\n val.add(num // i)\n if len(val) > 4:\n return val\n i += 1\n return val\n for num in nums:\n a = get_divisor(num)\n if len(a) == 4:\n ans += sum(a)\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n\n def four_divisors3(n):\n div = set()\n i = 1\n while i * i < n:\n if n % i == 0:\n div.add(i)\n div.add(n // i)\n if len(div) > 4:\n return 0\n i += 1\n return sum(div) if len(div) == 4 else 0\n\n def four_divisors(n):\n div = set()\n for i in range(1, int(n ** 0.5) + 1):\n if n % i == 0:\n div.add(i)\n div.add(n // i)\n if len(div) > 4:\n return 0\n return sum(div) if len(div) == 4 else 0\n\n def four_divisors2(n):\n cnt = 0\n sums = 0\n div = set()\n if n != 0:\n for i in range(1, int(n ** 0.5) + 1):\n if n % i == 0:\n cnt += 2\n sums += i + n // i\n if cnt > 4:\n return 0\n return sums if cnt == 4 else 0\n if not nums:\n return 0\n nums.sort()\n total = 0\n past = [None, None]\n for (i, v) in enumerate(nums):\n if i > 0 and v == nums[i - 1] and (v == past[0]):\n total += past[1]\n continue\n tmp = four_divisors(v)\n total += tmp\n past = [v, tmp]\n return total", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n ls = len(nums)\n for i in range(ls):\n divs = set()\n for j in range(1, floor(sqrt(nums[i])) + 1):\n if nums[i] % j == 0:\n divs.add(nums[i] // j)\n divs.add(j)\n if len(divs) == 4:\n res = res + sum(divs)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n\n def NOD(x):\n divisor = set()\n for i in range(1, int(sqrt(x)) + 1):\n if not x % i:\n divisor.add(i)\n divisor.add(x // i)\n return divisor\n res = 0\n for num in nums:\n divisor = NOD(num)\n if len(divisor) == 4:\n res += sum(divisor)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n maxim = max(nums)\n total = 0\n for k in range(len(nums)):\n num_div = 0\n index = 2\n div = []\n curr_val = nums[k]\n if abs(int(sqrt(curr_val)) - sqrt(curr_val)) > 10 ** (-12):\n while index <= int(sqrt(curr_val)):\n if curr_val % index == 0:\n div.append(index)\n div.append(nums[k] / index)\n if len(div) > 2:\n break\n index += 1\n if len(div) == 2:\n total = total + sum(div) + 1 + nums[k]\n return int(total)", "def div(n):\n c = 0\n i = 1\n k = 0\n if sqrt(n).is_integer():\n return 0\n while i * i < n and c <= 3:\n if n % i == 0:\n c += 1\n k += i + n // i\n i += 1\n if c == 2:\n return k\n else:\n return 0\n\ndef sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for i in nums:\n ans += div(i)\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n\n def findFactors(num):\n if num == 0:\n return 0\n res = set()\n for i in range(int(num ** 0.5) + 1):\n if num % (i + 1) == 0:\n res.add(i + 1)\n res.add(num // (i + 1))\n return [len(res), sum(res)]\n output = 0\n for num in nums:\n (c, sm) = findFactors(num)\n if c == 4:\n output += sm\n return output", "def __init__():\n self.divisors = {}\n\ndef generate_result(n):\n counter = 1\n quo = n // counter\n while counter <= quo:\n if n % counter == 0:\n yield counter\n if quo != counter:\n yield quo\n counter += 1\n quo = n // counter\n\ndef count_divisors(n):\n if n in self.divisors:\n return self.divisors[n]\n result = list(self.generate_result(n))\n self.divisors[n] = result\n return result\n\ndef sumfourdivisors(nums: List[int]) -> int:\n divisors = list(map(self.count_divisors, nums))\n four_divisors = list([x for x in divisors if len(x) == 4])\n return sum(map(sum, four_divisors))", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for n in nums:\n divisors = self.getDivisors(n)\n if len(divisors) == 4:\n res += sum(divisors)\n return res\n\ndef getDivisors(n):\n divisors = set()\n for i in range(1, n):\n if i ** 2 > n:\n break\n if n % i == 0:\n divisors.add(i)\n divisors.add(n // i)\n if len(divisors) > 4:\n break\n return divisors", "def sumfourdivisors(nums: List[int]) -> int:\n ret = 0\n for num in nums:\n divs = set()\n i = 1\n while i ** 2 <= num:\n if not num % i:\n divs.add(i)\n divs.add(num // i)\n if len(divs) > 4:\n break\n i += 1\n if len(divs) == 4:\n ret += sum(divs)\n return ret", "def helper(n):\n if n == 1:\n return 0\n d = int(math.sqrt(n))\n cnt = 2\n sm = 1 + n\n while d > 1:\n if n % d == 0:\n d1 = n // d\n if d1 != d:\n sm += d + d1\n cnt += 2\n else:\n sm += d\n cnt += 1\n if cnt > 4:\n return 0\n d -= 1\n if cnt == 4:\n return sm\n return 0\n\ndef sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for n in nums:\n res += self.helper(n)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n summ = 0\n for num in nums:\n if num > 1:\n summ += self.divisors(num)\n return summ\n\ndef divisors(num):\n visited_factors = set()\n visited_factors.add(1)\n visited_factors.add(num)\n factors = 2\n summ = 1 + num\n for i in range(2, int(num ** 0.5) + 1):\n if not num % i and num % i not in visited_factors:\n visited_factors.add(i)\n summ += i\n factors += 1\n secondHalf = num // i\n if secondHalf not in visited_factors:\n visited_factors.add(secondHalf)\n factors += 1\n summ += secondHalf\n if factors == 4:\n return summ\n return 0", "def sumfourdivisors(nums: List[int]) -> int:\n z = 0\n for num in nums:\n i = 1\n res = []\n while i * i <= num:\n if num % i == 0:\n res.append(i)\n i += 1\n if len(res) == 2:\n lin = [num // j for j in res]\n final = list(set(res + lin))\n if len(final) == 4:\n z += sum(final)\n return max(0, z)", "def sumfourdivisors(nums: List[int]) -> int:\n\n def find_divisors(n):\n i = 1\n divisors = []\n while i * i < n:\n if n % i == 0:\n divisors.append(i)\n divisors.append(n // i)\n i += 1\n if i * i == n:\n divisors.append(i)\n return divisors\n ans = 0\n for n in nums:\n divisors = find_divisors(n)\n if len(divisors) == 4:\n ans += sum(divisors)\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for i in range(len(nums)):\n (curSum, curAns) = (1 + nums[i], 2)\n for j in range(2, int(sqrt(nums[i])) + 1):\n if nums[i] % j == 0:\n if j == nums[i] // j:\n curSum += nums[i] // j\n curAns += 1\n else:\n curSum += j + nums[i] // j\n curAns += 2\n if curAns == 4:\n res += curSum\n return res", "def find_factors(n):\n factors = []\n i = 1\n j = n\n while True:\n if i * j == n:\n factors.append(i)\n if i == j:\n break\n factors.append(j)\n i += 1\n j = n // i\n if i > j:\n break\n return factors\n\ndef sumfourdivisors(nums: List[int]) -> int:\n d = 0\n for i in nums:\n f = self.find_factors(i)\n if len(f) == 4:\n d += f[0] + f[1] + f[2] + f[3]\n return d", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for n in nums:\n d = set()\n for cnd in range(1, floor(sqrt(n)) + 1):\n (q, r) = divmod(n, cnd)\n if not r:\n d.add(q)\n d.add(cnd)\n if len(d) == 4:\n ans += sum(d)\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n divs = dict()\n for v in nums:\n divs.setdefault(v, [0, []])\n divs[v][0] += 1\n n = max(nums)\n sieve = (1 + n) * [0]\n for i in range(2, 1 + n):\n j = i\n while j <= n:\n sieve[j] += 1\n if j in divs:\n divs[j][1].append(i)\n j += i\n return sum([freq * (1 + sum(cur_div)) for (k, (freq, cur_div)) in list(divs.items()) if len(cur_div) == 3])", "def sumfourdivisors(nums: List[int]) -> int:\n if not nums:\n return 0\n ans = 0\n for n in nums:\n rangemax = int(math.sqrt(n))\n factsum = n + 1\n factcount = 2\n for f1 in range(2, rangemax + 1):\n if not n % f1:\n f2 = n // f1\n factcount += 1\n factsum += f1\n if f1 != f2:\n factcount += 1\n factsum += f2\n if factcount > 4 or factcount % 2:\n break\n if factcount == 4:\n ans += factsum\n return ans", "def contr(n):\n p = None\n if n ** 0.5 % 1 == 0:\n return 0\n for i in range(2, math.ceil(n ** 0.5)):\n if n % i == 0:\n if p is None:\n p = i\n else:\n return 0\n if p is None:\n return 0\n return 1 + p + n // p + n\n\ndef sumfourdivisors(nums: List[int]) -> int:\n return sum((contr(n) for n in nums))", "def divisors(n, c={}):\n if n in c:\n return c[n]\n d = []\n for i in range(1, int(sqrt(n) + 1)):\n if n % i == 0:\n d.append(i)\n j = n // i\n if j != i:\n d.append(j)\n if len(d) > 4:\n break\n if len(d) == 4:\n s = sum(d)\n c.update({n: s})\n return s\n else:\n c.update({n: 0})\n return 0\n\ndef sumfourdivisors(nums: List[int]) -> int:\n return sum((self.divisors(x) for x in nums))", "def sumfourdivisors(nums: List[int]) -> int:\n\n def divisors(v):\n divs = set()\n for i in range(1, ceil(sqrt(v)) + 1):\n if not v % i:\n divs.update({i, v // i})\n if len(divs) > 4:\n return 0\n return sum(divs) if len(divs) == 4 else 0\n return sum(map(divisors, nums))", "def sumfourdivisors(nums: List[int]) -> int:\n total = 0\n pSieve = [0 for k in range(10 ** 5 + 1)]\n for k in range(2, len(pSieve)):\n if pSieve[k] == 1:\n continue\n pSieve[k + k::k] = [1] * ((len(pSieve) - 1) // k - 1)\n for num in nums:\n if num == 1 or pSieve[num] == 0 or sqrt(num) == int(sqrt(num)):\n continue\n k = 2\n while num % k != 0:\n k += 1\n if num == k ** 3 or pSieve[num // k] == 0:\n total += 1 + num + k + num // k\n return total", "def sumfourdivisors(nums: List[int]) -> int:\n\n def helper(n):\n if int(math.sqrt(n)) * int(math.sqrt(n)) == n:\n return 0\n summary = 1 + n\n count = 2\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n summary += n // i + i\n count += 2\n if count > 4:\n break\n if count == 4:\n return summary\n else:\n return 0\n res = 0\n for n in nums:\n res += helper(n)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for n in nums:\n divisor = set()\n for i in range(1, floor(sqrt(n)) + 1):\n if n % i == 0:\n divisor.add(n // i)\n divisor.add(i)\n if len(divisor) > 4:\n break\n if len(divisor) == 4:\n res += sum(divisor)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n valAll = 0\n for num in nums:\n local = set()\n for i in range(1, int(math.sqrt(num)) + 1):\n if num % i == 0:\n local.add(i)\n local.add(int(num / i))\n if len(local) > 4:\n break\n if len(local) == 4:\n valAll += sum(local)\n return valAll", "def sumfourdivisors(nums: List[int]) -> int:\n ret_count = {}\n ret_sum = {}\n for n in nums:\n if n in ret_sum:\n if ret_sum[n] is not None:\n ret_count[n] += 1\n continue\n cur_div = 2\n hit_div = None\n while cur_div * cur_div <= n:\n if n % cur_div == 0:\n if hit_div is None:\n hit_div = cur_div\n else:\n hit_div = None\n break\n cur_div += 1\n if hit_div is not None and hit_div != n // hit_div:\n res = 1 + n + hit_div + n // hit_div\n ret_count[n] = 1\n else:\n res = None\n ret_sum[n] = res\n ret = sum((ret_sum[k] * c for (k, c) in list(ret_count.items())))\n return ret", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for num in nums:\n cnt = 0\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n cnt += 1\n d = i\n if cnt > 1:\n break\n if cnt == 1 and d != num // d:\n ans += 1 + d + num // d + num\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n\n def divisors(v):\n res = []\n for i in range(1, ceil(sqrt(v)) + 2):\n if len(res) > 4:\n return 0\n if not v % i:\n res += (i,)\n if v // i > i:\n res += (v // i,)\n else:\n break\n res = set(res)\n return sum(res) if len(res) == 4 else 0\n for v in nums:\n res += divisors(v)\n return res", "from math import sqrt\n\ndef sumfourdivisors(nums: List[int]) -> int:\n sum_of_factor = 0\n for x in nums:\n factors = set()\n for i in range(1, int(sqrt(x) + 1)):\n if x % i == 0:\n factors.add(i)\n factors.add(x // i)\n if len(factors) > 4:\n break\n if len(factors) == 4:\n sum_of_factor += sum(factors)\n return sum_of_factor", "def getDivisors(x):\n if x == 1:\n return [1]\n out = []\n bound = int(sqrt(x)) + 1\n for i in range(1, bound):\n if x % i == 0:\n out.append(i)\n if x // i != i:\n out.append(x // i)\n if len(out) > 4:\n break\n return out\n\ndef sumfourdivisors(nums: List[int]) -> int:\n divisors = {}\n sum_four = 0\n for x in nums:\n if x in divisors:\n if len(divisors[x]) == 4:\n sum_four += sum(divisors[x])\n else:\n x_div = self.getDivisors(x)\n if len(x_div) == 4:\n sum_four += sum(x_div)\n divisors[x] = x_div\n return sum_four", "def sumfourdivisors(nums: List[int]) -> int:\n ret = 0\n for num in nums:\n sqrt = int(math.sqrt(num))\n if sqrt * sqrt == num:\n continue\n divSum = 0\n count = 0\n for i in range(1, sqrt + 1):\n if num % i == 0:\n divSum += i + num // i\n count += 1\n if count > 2:\n break\n if count == 2:\n ret += divSum\n return ret", "def sumfourdivisors(nums: List[int]) -> int:\n\n def getDivisors(k):\n (count, second) = (0, 0)\n for i in range(2, int(sqrt(k)) + 1):\n if k % i == 0:\n count += 1\n if count > 1 or i * i == k:\n return [0]\n second = k // i\n if count == 1:\n return [1, second, k // second, k]\n else:\n return [0]\n total = 0\n for num in nums:\n total += sum(getDivisors(num))\n return total", "def sumfourdivisors(nums: List[int]) -> int:\n\n def get_divs(num):\n divs = []\n for i in range(1, int(sqrt(num)) + 1):\n if not num % i:\n divs.append(i)\n if i != int(num / i):\n divs.append(int(num / i))\n if len(divs) > 4:\n return None\n if len(divs) < 4:\n return None\n return sum(divs)\n ans = 0\n for item in nums:\n divs = get_divs(item)\n if divs:\n ans += divs\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n\n def div4(i):\n if i <= 5:\n return set()\n else:\n count = {1, i}\n for j in range(2, int(math.sqrt(i)) + 1):\n if i % j == 0:\n count.update({j, i / j})\n if len(count) > 4:\n return count\n return count\n count = 0\n for i in nums:\n s = div4(i)\n if len(s) == 4:\n count += sum(s)\n return int(count)", "def sumfourdivisors(nums: List[int]) -> int:\n return sum([self.sumofDivisors(num) for num in nums])\n\ndef sumofDivisors(num):\n s = set()\n for i in range(1, int(sqrt(num)) + 1):\n if num % i == 0:\n s.add(i)\n s.add(num // i)\n if len(s) > 4:\n return 0\n return sum(s) if len(s) == 4 else 0", "def sumfourdivisors(nums: List[int]) -> int:\n\n def four_div_sum(num):\n divs = set()\n for i in range(1, floor(sqrt(num)) + 1):\n if num % i == 0:\n divs.update({i, num // i})\n if len(divs) > 4:\n return 0\n return sum(divs) if len(divs) == 4 else 0\n return sum((four_div_sum(num) for num in nums))", "from collections import defaultdict\nfrom math import ceil\n\ndef sumfourdivisors(nums: List[int]) -> int:\n\n def getSumOfDivisors(n):\n divisors = set()\n for i in range(1, ceil(n ** 0.5) + 1):\n if n % i == 0:\n divisors.update({i, n // i})\n if len(divisors) > 4:\n return 0\n return sum(divisors) if len(divisors) == 4 else 0\n return sum(map(getSumOfDivisors, nums))", "import math\n\ndef sumfourdivisors(nums: List[int]) -> int:\n if not nums:\n return 0\n res = 0\n for i in nums:\n divisor = set()\n for j in range(1, int(math.sqrt(i)) + 1):\n if i % j == 0:\n divisor.add(j)\n divisor.add(i // j)\n if len(divisor) > 4:\n break\n if len(divisor) == 4:\n res += sum(divisor)\n return res", "from math import sqrt\n\ndef sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for num in nums:\n divisor = set()\n for i in range(1, floor(sqrt(num)) + 1):\n if num % i == 0:\n divisor.add(num // i)\n divisor.add(i)\n if len(divisor) > 4:\n break\n if len(divisor) == 4:\n res += sum(divisor)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n div_sum = 0\n for num in nums:\n divs = set()\n for i in range(1, floor(sqrt(num)) + 1):\n if num % i == 0:\n divs.add(num // i)\n divs.add(i)\n if len(divs) > 4:\n break\n if len(divs) == 4:\n div_sum += sum(divs)\n return div_sum", "def sumfourdivisors(nums: List[int]) -> int:\n\n def findFactors(num):\n res = set()\n for i in range(int(num ** 0.5) + 1):\n if num % (i + 1) == 0:\n res.add(i + 1)\n res.add(num // (i + 1))\n if len(res) > 4:\n break\n if len(res) == 4:\n return sum(res)\n else:\n return 0\n output = 0\n for num in nums:\n temp = findFactors(num)\n output += temp\n return output", "def sumfourdivisors(nums: List[int]) -> int:\n ret = 0\n for n in nums:\n divisors = set()\n for i in range(1, math.floor(n ** 0.5) + 1):\n if n % i == 0:\n divisors.add(i)\n divisors.add(n / i)\n if len(divisors) > 4:\n break\n if len(divisors) == 4:\n ret += sum(divisors)\n return int(ret)", "def find_divisors(num):\n cnt = 0\n run_sum = num + 1\n for i in range(2, int(num ** 0.5) + 1):\n if i * i == num:\n return 0\n if cnt > 1:\n return 0\n if not num % i:\n run_sum += num // i + i\n cnt += 1\n return run_sum if cnt == 1 else 0\n\ndef sumfourdivisors(nums: List[int]) -> int:\n cnt = 0\n for i in nums:\n cnt += self.find_divisors(i)\n return cnt", "def sumfourdivisors(nums: List[int]) -> int:\n\n def check(x):\n v = set()\n i = 1\n while i * i <= x:\n if x % i == 0:\n v.add(i)\n v.add(x // i)\n if len(v) > 4:\n return 0\n i += 1\n if len(v) == 4:\n return sum(v)\n return 0\n return sum([check(x) for x in nums])", "def sumfourdivisors(nums: List[int]) -> int:\n range_6 = list(range(6))\n result = 0\n for num in nums:\n if num in range_6:\n pass\n else:\n pivot = int(num ** 0.5)\n temp = [1, num]\n len_t = 2\n for i in range(2, pivot + 1):\n (divisor, rem) = divmod(num, i)\n if not rem:\n if i == divisor:\n len_t = 0\n break\n temp += [i, divisor]\n len_t += 2\n if len_t > 4:\n break\n if len_t == 4:\n result += sum(temp)\n return result", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for val in nums:\n P = self.check(val)\n if P:\n ans += sum(P)\n return ans\n\ndef check(n):\n L = [n]\n count = 1\n if n != 1:\n L.append(1)\n count += 1\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n L.append(i)\n count += 1\n if n / i != float(i):\n L.append(n // i)\n count += 1\n if count > 4:\n return None\n if count != 4:\n return None\n return L", "def sumfourdivisors(nums: List[int]) -> int:\n\n def check(n):\n i = 1\n cnt = 0\n res = 0\n while i * i < n:\n if n % i == 0:\n cnt += 2\n res += i\n res += n // i\n i += 1\n if cnt > 4:\n return 0\n if i * i == n:\n cnt += 1\n res += i\n if cnt == 4:\n return res\n else:\n return 0\n res = sum((check(n) for n in nums))\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n import math\n\n def isprime(n):\n if not n % 1 == 0:\n return False\n if math.sqrt(n) % 1 == 0:\n return False\n for i in range(math.ceil(math.sqrt(n))):\n if i == 0 or i == 1:\n continue\n if n % i == 0:\n return False\n return True\n ans = 0\n for num in nums:\n if num < 6:\n continue\n if math.sqrt(num) % 1 == 0:\n continue\n if isprime(pow(num, 1 / 3)) or num == 4913:\n ans += 1 + pow(num, 1 / 3) + pow(num, 2 / 3) + num\n continue\n divisors = 0\n for i in range(math.ceil(math.sqrt(num))):\n if i == 0 or i == 1:\n continue\n if num % i == 0:\n if num / i % i == 0:\n break\n if not divisors == 0:\n divisors = 0\n break\n divisors = i\n if not divisors == 0 and isprime(num / divisors) and isprime(divisors):\n ans += (divisors + 1) * (num / divisors + 1)\n return int(ans)", "import numpy as np\n\ndef sumfourdivisors(nums: List[int]) -> int:\n ret = 0\n for num in nums:\n divisors = set()\n N = int(np.floor(np.sqrt(num)))\n for i in range(1, N + 1):\n if num % i == 0:\n divisors.add(i)\n divisors.add(num // i)\n if len(divisors) > 4:\n break\n if len(divisors) == 4:\n ret += sum(divisors)\n return ret", "def sumfourdivisors(nums: List[int]) -> int:\n import math\n s = 0\n nums = sorted(nums, reverse=True)\n for i in nums:\n count = set()\n true = True\n for x in range(2, int(math.sqrt(i)) + 1):\n if len(count) > 4:\n true = False\n break\n if i % x == 0:\n count.add(x)\n count.add(i // x)\n if len(count) == 2 and true:\n s += sum(count) + i + 1\n return s", "def sumfourdivisors(nums: List[int]) -> int:\n ttl = 0\n for n in nums:\n seen = set()\n for i in range(1, int(sqrt(n)) + 1):\n if n % i == 0:\n seen.add(i)\n seen.add(n / i)\n if len(seen) >= 5:\n break\n if len(seen) == 4:\n ttl += sum(seen)\n return int(ttl)", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for num in nums:\n div = set()\n for j in range(1, int(sqrt(num)) + 1):\n if not num % j:\n div.add(j)\n div.add(num // j)\n if len(div) > 4:\n break\n if len(div) == 4:\n res += sum(div)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n\n def findiv(num):\n res = 0\n cnt = 0\n for i in range(1, int(num ** 0.5) + 1):\n if not num % i:\n if i * i == num:\n cnt += 1\n res += i\n else:\n cnt += 2\n res += i\n res += num // i\n return res if cnt == 4 else 0\n res = 0\n for num in nums:\n res += findiv(num)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for num in nums:\n out = []\n for i in range(1, int(num ** 0.5) + 1):\n (a, b) = divmod(num, i)\n if b == 0:\n if a == i:\n out.append(a)\n else:\n out.extend([a, i])\n if len(out) > 4:\n break\n if len(out) == 4:\n ans += sum(out)\n return ans"], "starter_code": "def sumfourdivisors(nums: List[int]) -> int:\n", "input_output": {"fn_name": "sumFourDivisors", "inputs": [[[21, 4, 7]]], "outputs": [32]}, "difficulty": "MEDIUM", "raw_tags": ["Math", "Array"], "name": null, "source": "leetcode", "tags": ["Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/four-divisors/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sumfourdivisors", "task_id": "TACO_lite/58", "example": [[[[21, 4, 7]]], ["32"]]} +{"requirement": "Imagine there's a big cube consisting of n^3 small cubes. Calculate, how many small cubes are not visible from outside.\n\nFor example, if we have a cube which has 4 cubes in a row, then the function should return 8, because there are 8 cubes inside our cube (2 cubes in each dimension)", "solutions": ["def not_visible_cubes(n):\n return max(n - 2, 0) ** 3", "def not_visible_cubes(n):\n if n > 1:\n return (n - 2) ** 3\n else:\n return 0", "def not_visible_cubes(n):\n if 0 <= n <= 2:\n return 0\n return (n - 2) ** 3", "import math\n\ndef not_visible_cubes(n):\n if n < 2:\n return 0\n else:\n return (n - 2) * (n - 2) * (n - 2)", "def not_visible_cubes(n):\n return pow(n - 2, 3) if n > 2 else 0", "def not_visible_cubes(n):\n return n > 2 and (n - 2) ** 3", "def not_visible_cubes(n):\n if n == 0 or n == 1 or n == 2:\n return 0\n totalCubes = n * n * n\n cubesPerSide = n * n\n outsideCubes = cubesPerSide + 2 * (cubesPerSide - n) + cubesPerSide - 2 * n + 2 * (cubesPerSide - (n + 2 * (n - 1) + n - 2))\n return totalCubes - outsideCubes"], "starter_code": "def not_visible_cubes(n):\n", "input_output": {"fn_name": "not_visible_cubes", "inputs": [[0], [1], [2], [3], [4], [5], [7], [12], [18], [10002]], "outputs": [[0], [0], [0], [1], [8], [27], [125], [1000], [4096], [1000000000000]]}, "difficulty": "EASY", "raw_tags": ["Puzzles"], "name": null, "source": "codewars", "tags": ["Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/560d6ebe7a8c737c52000084", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "not_visible_cubes", "task_id": "TACO_lite/47", "example": [[[4]], ["8"]]} +{"requirement": "# Grasshopper - Function syntax debugging\n\nA student was working on a function and made some syntax mistakes while coding. Help them find their mistakes and fix them.", "solutions": ["def main(verb, noun):\n return verb + noun", "def main(*a):\n return ''.join(a)", "def main(verb, noun):\n return f'{verb}{noun}'", "def main(verb: str, noun: str) -> str:\n return verb + noun", "main = '{}{}'.format", "main = str.__add__", "def main(verb, noun):\n output = verb + noun\n return output", "main = lambda _, __: _ + __", "def main(*sen):\n return ''.join(sen)", "def main(verb, noun):\n msg = verb + noun\n return msg", "def main(verb, noun):\n return verb + noun\nmain('take', 'shit')", "from operator import add as main", "def main(*arr):\n return ''.join(arr)", "def main(verb, noun):\n v = verb\n n = noun\n return v + n", "main = lambda *n: ''.join(n)", "def main(a, b):\n return ''.join([a, b])", "def main(verb, noun):\n return '{0}{1}'.format(verb, noun)", "def main(verbs, none):\n main = verbs + none\n return main", "def main(v, n):\n return v + n", "def main(verb, noun):\n result = verb + noun\n return result", "def main(verb, noun):\n newword = verb + noun\n return newword", "def main(n, m):\n return n + m", "def main(verb, noun):\n test = verb + noun\n return test", "def main(verb, noun):\n try:\n return verb + noun\n except:\n return 'There was a problem.'", "main = lambda verb, noun: f'{verb}{noun}'", "def main(verb, noun):\n return ''.join((verb, noun))", "def main(verb, noun):\n answer = ''\n answer = verb + noun\n return answer", "main = lambda noun, verb: noun + verb", "def main(verb, noun):\n i = verb + noun\n return i", "def main(verb, noun):\n return '%s%s' % (verb, noun)", "verb = 2\nnoun = 2\n\ndef main(verb, noun):\n return verb + noun\nmain(verb, noun)", "def main(verb, noum):\n r = verb + noum\n return r", "def main(verb, noun):\n return verb + noun\nmain(1, 1)", "def main(verb, noun):\n word = ''\n word += verb + noun\n return word", "def main(verb, noun):\n comp = verb + noun\n return comp", "main = lambda alpha, beta: alpha + beta", "main = lambda v, b: v + b", "def main(verb='say ', noun='hello'):\n return verb + noun", "def main(verb, noun):\n honestly = '{}{}'.format(verb, noun)\n return honestly", "def main(*args):\n return ''.join(args)", "def main(verb, noun):\n a = verb + noun\n return a", "def main(verb, noun):\n res = verb + noun\n return res", "def main(*words):\n return ''.join(words)", "main = lambda a, b: a + b", "def main(verb, noun):\n return verb + noun\nmain('use', 'item')", "def main(verb, word2):\n return '%s%s' % (verb, word2)", "def main(a, b):\n return a + b", "main = lambda verb, noun: ''.join((verb, noun))", "def main(verb, noun):\n sum = verb + noun\n return sum", "def main(x, y):\n return x + y", "def main(verb, noun):\n return verb + noun\nmain('take', 'item')", "main = lambda x, y: f'{x}{y}'", "main = lambda *a: ''.join(a)"], "starter_code": "def main(verb, noun):\n", "input_output": {"fn_name": "main", "inputs": [["take ", "item"], ["use ", "sword"]], "outputs": [["take item"], ["use sword"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56dae9dc54c0acd29d00109a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "main", "task_id": "TACO_lite/85", "example": [[], []]} +{"requirement": "Given 3 characters 'a', 'b', 'c'. Find the number of strings of length n that can be formed from these 3 characters. Given that : we can use ‘a’ as many times as we want, ‘b’ maximum once, and ‘c’ maximum twice.\n \nExample 1:\nInput: n = 2\nOutput: 8\nExpalantion: There are total 8 possible\nstrings and these are: {aa, ab, ba, ac,\nca, bc, cb, cc}.\nExample 2:\nInput: n = 3\nOutput: 19\nExplanation: There are total 19 possible\nstrings.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function no_ofString() which takes n as input parameter ans returns the no. of total possible strings than can be formed using characters 'a', 'b' and 'c' modulo 10^{9} + 7.\n \nExpected Time Complexity: O(n)\nExpected Space Compelxity: O(n)\n \nConstraints:\n1 <= n <= 100000", "solutions": ["def no_ofstring(n):\n l = 10 ** 9 + 7\n return (1 + n * 2 + n * (n * n - 1) // 2) % l", "def no_ofstring(n):\n m = 1000000007\n ans = 1 + 2 * (n % m) + n % m * (n % m - 1) * (n % m + 1) // 2\n return ans % m", "def no_ofstring(n):\n return (n * n * n + (3 * n + 2)) // 2 % 1000000007", "def no_ofstring(n):\n m = 10 ** 9 + 7\n ans = 1 + 2 * (n % m) + n % m * (n % m - 1) * (n % m + 1) // 2\n return ans % m", "def no_ofstring(n):\n if n == 1:\n return 3\n mod = int(10 ** 9 + 7)\n total = 1 + n % mod + n * n % mod + n * (n - 1) * (n - 1) // 2 % mod\n return total % mod", "def no_ofstring(n):\n if n == 1:\n return 3\n total = 0\n for i in range(3):\n combination = 1\n bottom_part = 1\n for x in range(i):\n combination *= n - x\n bottom_part *= x + 1\n total = (total + combination // bottom_part) % (10 ** 9 + 7)\n for i in range(3):\n combination = 1\n bottom_part = 1\n for x in range(i):\n combination *= n - 1 - x\n bottom_part *= x + 1\n total = (total + n * (combination // bottom_part)) % (10 ** 9 + 7)\n return total", "def possibilities(x):\n count = 1\n while x > 1:\n count *= x\n x -= 1\n return count\n\ndef no_ofstring(n):\n if n == 1:\n return 3\n all_a = 1\n one_b_other_a = n % (10 ** 9 + 7)\n one_c_other_a = n % (10 ** 9 + 7)\n one_c_one_b = n % (10 ** 9 + 7)\n if n > 2:\n one_c_one_b = n * (n - 1) % (10 ** 9 + 7)\n two_c = 1\n if n > 2:\n two_c = int(n * (n - 1) / 2) % (10 ** 9 + 7)\n one_b_two_c = 0\n if n > 2:\n one_b_two_c = int(n * (n - 1) * (n - 2) / 2) % (10 ** 9 + 7)\n return (all_a + one_b_other_a + one_c_other_a + one_c_one_b + two_c + one_b_two_c) % (10 ** 9 + 7)"], "starter_code": "def no_ofstring(n):\n", "input_output": {"inputs": ["n = 2", "n = 3"], "outputs": ["8", "19"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical", "permutation"], "name": null, "source": "geeksforgeeks", "tags": ["Combinatorics", "Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/total-number-of-strings5726/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "no_ofstring", "task_id": "TACO_lite/16", "example": [[[2], [3]], ["8", "19"]]} +{"requirement": "## Task\n\nWrite a function that accepts two arguments and generates a sequence containing the integers from the first argument to the second inclusive. \n\n## Input\n\nPair of integers greater than or equal to `0`. The second argument will always be greater than or equal to the first. \n\n## Example\n\n```python\ngenerate_integers(2, 5) # --> [2, 3, 4, 5]\n```", "solutions": ["def generate_integers(m, n):\n return list(range(m, n + 1))", "def generate_integers(m, n):\n return [i for i in range(m, n + 1)]", "def generate_integers(m, n):\n ans = []\n for each in range(m, n + 1):\n ans.append(each)\n return ans", "def generate_integers(m, n):\n return [_ for _ in range(m, n + 1)]", "def generate_integers(m, n):\n return [num for num in range(m, n + 1)]", "def generate_integers(m, n):\n c = []\n for i in range(m, n + 1):\n c.append(i)\n return c", "def generate_integers(m, n):\n numeros = []\n for x in range(m, n + 1):\n numeros.append(x)\n return numeros\n pass", "def generate_integers(m, n):\n nums = list()\n while m <= n:\n nums.append(m)\n m += 1\n return nums", "def generate_integers(m, n):\n list = []\n for x in (m, n):\n while m <= x <= n:\n x = x + 1\n list.append(x - 1)\n return list"], "starter_code": "def generate_integers(m, n):\n", "input_output": {"fn_name": "generate_integers", "inputs": [[2, 5]], "outputs": [[[2, 3, 4, 5]]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5841f680c5c9b092950001ae", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "generate_integers", "task_id": "TACO_lite/32", "example": [[[2, 5]], ["[2, 3, 4, 5]"]]} +{"requirement": "Given a string S contains 0's, 1's, and 2's, the task is to find the number of goals on the penalty.\n\t '1' stands for \"goal\".\n\t '0' stands for \"no goal\".\n\t '2' stands for a foul which gives a penalty.\nExample 1:\nInput: S = \"1012012112110\"\nOutput: 2\nExplanation: There are 3 penalties,\nof which he scores only 2.\n1012012112110\nExample 2:\nInput: S = \"111122\"\nOutput: 0\nExplanation: No goal on penalty\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function penaltyScore() which takes a string S as input and returns the goals count on the penalty. \nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= |N| <= 10^{5}", "solutions": ["def penaltyscore(S):\n goal = 0\n for i in range(len(S)):\n if i < len(S) - 1:\n if S[i] == '2' and S[i + 1] == '1':\n goal = goal + 1\n return goal", "def penaltyscore(S):\n d = 0\n k = list(map(int, str(S)))\n for i in range(0, len(S) - 1):\n if k[i] == 2 and k[i + 1] == 1:\n d = d + 1\n return d", "def penaltyscore(s):\n c = 0\n for i in range(len(s) - 1):\n if s[i] == '2' and s[i + 1] == '1':\n c = c + int(s[i + 1])\n return c", "def penaltyscore(S):\n c = 0\n for i in range(len(S) - 1):\n if S[i:i + 2] == '21':\n c = c + 1\n return c", "def penaltyscore(S):\n l = []\n a = []\n for i in S:\n l.append(int(i))\n for i in range(len(l)):\n if l[i] == 2:\n if i + 1 < len(l):\n a.append(l[i + 1])\n count = 0\n for i in a:\n if i == 1:\n count += 1\n return count", "def penaltyscore(S):\n return S.count('21')", "def penaltyscore(S):\n count = 0\n for i in range(len(S) - 1):\n if S[i] == '2':\n if S[i + 1] == '1':\n count += 1\n return count", "def penaltyscore(S):\n l = list()\n for i in S:\n l.append(int(i))\n p = 0\n for i in range(1, len(l)):\n if l[i] == 1:\n if l[i - 1] == 2:\n p = p + 1\n return p", "def penaltyscore(S):\n res = 0\n for i in range(len(S) - 1):\n if S[i] + S[i + 1] == '21':\n res += 1\n return res", "def penaltyscore(S):\n if '21' in S:\n output = S.count('21')\n return output\n else:\n return 0", "from collections import Counter\n\ndef penaltyscore(S):\n z = S.count('21')\n if z == 0:\n return 0\n return z", "def penaltyscore(s):\n ans = s.count('21')\n return ans", "def penaltyscore(S):\n count = 0\n i = 0\n while i < len(S):\n while i < len(S) - 1 and S[i] == '2':\n if S[i + 1] == '1':\n count += 1\n i += 1\n else:\n i += 1\n i += 1\n return count", "def penaltyscore(S):\n stack_top = ''\n goals = 0\n for i in S:\n if stack_top == '2' and i == '1':\n goals += 1\n stack_top = i\n return goals", "def penaltyscore(S):\n c = 0\n k = 0\n for i in range(len(S) - 1):\n if S[i] == '2' and S[i + 1] == '1':\n c += 1\n k = 1\n if k == 0:\n return 0\n else:\n return c", "def penaltyscore(S):\n x = S.count('21')\n if x == 0:\n return 0\n return x", "def penaltyscore(S):\n n = '21'\n t = S.count(n)\n if t == 0:\n return 0\n return t", "def penaltyscore(S):\n s = '21'\n count = 0\n for i in range(1, len(S)):\n if S[i] == '1' and S[i - 1] == '2':\n count += 1\n else:\n continue\n return count if count > 0 else 0", "def penaltyscore(S):\n c = 0\n for x in range(len(S)):\n if S[x] == '2' and x + 1 < len(S):\n if S[x + 1] == '1':\n c += 1\n return c", "def penaltyscore(S):\n result = 0\n temp = ''\n count = 0\n for i in S:\n if i == '2':\n temp = '2'\n elif i == '1':\n temp += i\n if temp == '21':\n count += 1\n temp = ''\n else:\n temp = ''\n return count", "def penaltyscore(S):\n n = len(S)\n count = 0\n for i in range(len(S)):\n if i == n - 1:\n continue\n elif S[i] == '2' and S[i + 1] == '1':\n count += 1\n return count", "def penaltyscore(S):\n lst = list(S)\n s = 0\n for i in range(len(lst)):\n if i + 1 < len(lst):\n if lst[i] == '2':\n if lst[i + 1] == '1':\n s += 1\n return s"], "starter_code": "def penaltyscore(S):\n", "input_output": {"inputs": ["S = \"1012012112110\"", "S = \"111122\""], "outputs": ["2", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/the-penalty-shootout3810/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|).", "entry_point": "penaltyscore", "task_id": "TACO_lite/53", "example": [[["1012012112110"], ["111122"]], ["2", "0"]]} +{"requirement": "Given an integer, check whether it is a palindrome or not.\nExample 1:\nInput: n = 555\nOutput: Yes\nExample 2:\nInput: n = 123\nOutput: No\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function is_palindrome() which takes the number as input parameter and returns \"Yes\" if it is palindrome otherwise returns \"No\"(Without quotes).\n \nExpected Time Complexity: O(x)\nExpected Space Complexity: O(x) where x is number of digits in n.\n \nConstraints:\n1 <= n <= 1000", "solutions": ["def is_palindrome(n):\n self.n = n\n n = str(n)\n strait = n.strip()\n reverse = strait[::-1]\n n = int(n)\n if strait == reverse:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n reversed = str(n)[::-1]\n if str(reversed) == str(n):\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n a = str(n)\n if a == a[::-1]:\n return 'Yes'\n return 'No'", "def is_palindrome(n):\n i = 0\n j = len(str(n)) - 1\n s = str(n)\n while i < j:\n if s[i] != s[j]:\n return 'No'\n i += 1\n j -= 1\n return 'Yes'", "def is_palindrome(n):\n temp = n\n res = 0\n while n > 0:\n res = res * 10 + n % 10\n n = n // 10\n if res == temp:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n num = n\n rev = 0\n while num != 0:\n dig = num % 10\n rev = 10 * rev + dig\n num = num // 10\n if n == rev:\n return 'Yes'\n return 'No'", "def is_palindrome(n):\n dup = n\n rev = 0\n while n != 0:\n d = n % 10\n rev = rev * 10 + d\n n = n // 10\n if rev == dup:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n newNum = 0\n currNum = n\n while currNum > 0:\n currDigit = currNum % 10\n newNum = newNum * 10 + currDigit\n currNum = currNum // 10\n if newNum == n:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(N):\n n = N\n lis = n % 10\n while n > 0:\n lis = lis * 10\n n = n // 10\n lis += n % 10\n lis = int(lis / 10)\n if lis == N:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n org_string = str(n)\n rev_string = ''\n for i in org_string:\n rev_string = i + rev_string\n if org_string == rev_string:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n rev = 0\n temp = n\n while n > 0:\n last = n % 10\n rev = rev * 10 + last\n n = n // 10\n if rev == temp:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n y = str(n)\n z = y[::-1]\n if y == z:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n new = 0\n temp = n\n while temp != 0:\n digit = temp % 10\n new = new * 10 + digit\n temp = temp // 10\n return 'Yes' if new == n else 'No'", "def is_palindrome(n):\n nn = str(n)[::-1]\n nnn = int(nn)\n if n == nnn:\n return 'Yes'\n return 'No'", "def is_palindrome(n):\n num = n\n rev = 0\n while n != 0:\n rem = n % 10\n rev = rev * 10 + rem\n n = n // 10\n if num == rev:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n wno = n\n rev = 0\n while wno > 0:\n dig = wno % 10\n wno = wno // 10\n rev = rev * 10 + dig\n if rev == n:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n res = str(n) == str(n)[::-1]\n if res == True:\n ans = 'Yes'\n else:\n ans = 'No'\n return ans", "def is_palindrome(n):\n num = n\n sum = 0\n while n > 0:\n sum = sum * 10 + n % 10\n n //= 10\n if num == sum:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n n = str(n)\n a = [x for x in n]\n b = [x for x in n]\n b.reverse()\n flag = False\n for i in range(len(a) // 2):\n if a[i] != b[i]:\n flag = True\n break\n if flag:\n return 'No'\n else:\n return 'Yes'", "def is_palindrome(n):\n flag = True\n n1 = str(n)\n for i in range(len(n1) // 2):\n if n1[i] != n1[-i - 1]:\n flag = False\n break\n if flag:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n s = str(n)\n s = s[::-1]\n a = str(n)\n for i in range(0, len(s)):\n for j in range(1):\n if a[i] != s[i]:\n return 'No'\n return 'Yes'", "def is_palindrome(n):\n number = str(n)\n reverseNum = number[::-1]\n if number == reverseNum:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n temp = n\n reverse = 0\n while temp != 0:\n lastDigit = temp % 10\n reverse = reverse * 10 + lastDigit\n temp //= 10\n if n == reverse:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n temp = n\n reverse = 0\n i = len(str(n)) - 1\n while temp != 0:\n lastDigit = temp % 10\n reverse += lastDigit * 10 ** i\n temp //= 10\n i -= 1\n if n == reverse:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n n = str(n)\n k = len(n) - 1\n answer = ''\n while k >= 0:\n answer += n[k]\n k -= 1\n if answer == n:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n reverse = 0\n c = n\n while c != 0:\n reverse = reverse * 10 + c % 10\n c = c // 10\n if reverse == n:\n return 'Yes'\n return 'No'", "def is_palindrome(N):\n count = 0\n for i in range(0, len(str(N))):\n if str(N)[len(str(N)) - 1 - i] == str(N)[i]:\n count = count + 1\n if count == len(str(N)):\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n temp = n\n rev = 0\n while n != 0:\n digit = n % 10\n rev = rev * 10 + digit\n n = n // 10\n if temp != rev:\n s = 'No'\n return s\n else:\n s = 'Yes'\n return s", "def is_palindrome(n):\n ns = str(n)\n rev = ns[::-1]\n rev = int(rev)\n if n == rev:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n low = 0\n high = int(len(str(n))) - 1\n num = str(n)\n while low < high:\n if num[low] != num[high]:\n return 'No'\n low += 1\n high -= 1\n return 'Yes'", "def is_palindrome(n):\n num = str(n)\n rev = num[::-1]\n if num == rev:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n x = n\n reverse_num = 0\n while x > 0:\n last_digit = x % 10\n reverse_num = reverse_num * 10 + last_digit\n x = x // 10\n if reverse_num == n:\n return 'Yes'\n return 'No'", "def is_palindrome(n):\n n = str(n)\n new_n = []\n for i in n:\n new_n.append(i)\n z = ''.join(new_n[::-1])\n if z == n:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n (rev, ori) = (0, n)\n while n > 0:\n rev = rev * 10 + n % 10\n n //= 10\n if ori == rev:\n return 'Yes'\n return 'No'", "def is_palindrome(n):\n a = n\n res = 0\n while n != 0:\n res = n % 10 + res * 10\n n //= 10\n if res == a:\n return 'Yes'\n return 'No'", "def is_palindrome(n):\n x = n\n palindrome = 0\n while n != 0:\n number = n % 10\n palindrome = palindrome * 10 + number\n n = n // 10\n if palindrome == x:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n temp = n\n s = 0\n while n > 0:\n rem = n % 10\n s = s * 10 + rem\n n = n // 10\n if temp == s:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n s = str(n)\n k = list(s[::-1])\n for i in range(len(s)):\n if s[i] != k[i]:\n return 'No'\n break\n else:\n return 'Yes'", "def is_palindrome(n):\n p = []\n while n > 0:\n rem = n % 10\n p.append(rem)\n n = n // 10\n if p == p[::-1]:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n temp = n\n sum = 0\n while n != 0:\n r = n % 10\n n = n // 10\n sum = sum * 10 + r\n if sum == temp:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n return 'Yes' * (str(n) == str(n)[::-1]) or 'No'", "def is_palindrome(n):\n s = str(n)[-1::-1]\n if int(s) == n:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n n = str(n)\n l = len(n)\n for i in range(len(str(n)) // 2):\n if n[i] != n[l - 1 - i]:\n return 'No'\n return 'Yes'", "def is_palindrome(n):\n t = str(n)\n k = 'Yes'\n o = 'No'\n if t == t[::-1]:\n return k\n else:\n return o"], "starter_code": "def is_palindrome(n):\n", "input_output": {"inputs": ["n = 555", "n = 123"], "outputs": ["Yes", "No"]}, "difficulty": "EASY", "raw_tags": ["palindrome"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/palindrome0746/1", "Expected Auxiliary Space": "O(x) where x is number of digits in n.", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(x)", "entry_point": "is_palindrome", "task_id": "TACO_lite/71", "example": [[], []]} +{"requirement": "A faro shuffle of a deck of playing cards is a shuffle in which the deck is split exactly in half and then the cards in the two halves are perfectly interwoven, such that the original bottom card is still on the bottom and the original top card is still on top.\n\nFor example, faro shuffling the list\n```python\n['ace', 'two', 'three', 'four', 'five', 'six']\n```\ngives\n```python\n['ace', 'four', 'two', 'five', 'three', 'six' ]\n```\n\nIf 8 perfect faro shuffles are performed on a deck of 52 playing cards, the deck is restored to its original order.\n\nWrite a function that inputs an integer n and returns an integer representing the number of faro shuffles it takes to restore a deck of n cards to its original order.\n\nAssume n is an even number between 2 and 2000.", "solutions": ["def faro_cycles(n):\n (x, cnt) = (2, 1)\n while x != 1 and n > 3:\n cnt += 1\n x = x * 2 % (n - 1)\n return cnt", "def faro_cycles(deck_size):\n (arr, count) = (list(range(deck_size)), 0)\n original_arr = arr\n while True:\n arr = arr[0:deck_size:2] + arr[1:deck_size:2]\n count += 1\n if original_arr == arr:\n break\n return count", "def faro_cycles(size):\n deck = list(range(size))\n (cur, count) = (deck[::2] + deck[1::2], 1)\n while cur != deck:\n (cur, count) = (cur[::2] + cur[1::2], count + 1)\n return count", "def faro_cycles(n):\n original = list(range(1, n + 1))\n (duplicate, c) = (original.copy(), 0)\n while 1:\n (first, bottom) = (duplicate[0], duplicate[-1])\n first_half = duplicate[1:n // 2]\n second_half = duplicate[n // 2:-1]\n duplicate = []\n for (i, j) in zip(first_half, second_half):\n duplicate.extend([j, i])\n duplicate = [first] + duplicate + [bottom]\n c += 1\n if original == duplicate:\n return c", "def faro_cycles(deck_size):\n if deck_size == 2:\n return 1\n (pos, output) = (2, 1)\n while pos != 1:\n pos = pos * 2 % (deck_size - 1)\n output += 1\n return output", "def faro_cycles(deck_size):\n pos = 1\n for i in range(deck_size):\n pos = pos * 2 - (0 if pos < deck_size / 2 else deck_size - 1)\n if pos == 1:\n return i + 1", "def faro(xs):\n m = len(xs) // 2\n return [x for xs in zip(xs[:m], xs[m:]) for x in xs]\n\ndef faro_cycles(deck_size):\n xs = original = list(range(deck_size))\n n = 0\n while True:\n n += 1\n xs = faro(xs)\n if xs == original:\n return n", "def interv(list1, list2):\n out_list = []\n for (el1, el2) in zip(list1, list2):\n out_list.append(el1)\n out_list.append(el2)\n return out_list\n\ndef faro_cycles(deck_size):\n original = [x for x in range(deck_size)]\n new = interv(original[:deck_size // 2], original[deck_size // 2:])\n n = 1\n while original != new:\n new = interv(new[:deck_size // 2], new[deck_size // 2:])\n n += 1\n return n", "def faro_cycles(deck_size):\n return [None, 1, 2, 4, 3, 6, 10, 12, 4, 8, 18, 6, 11, 20, 18, 28, 5, 10, 12, 36, 12, 20, 14, 12, 23, 21, 8, 52, 20, 18, 58, 60, 6, 12, 66, 22, 35, 9, 20, 30, 39, 54, 82, 8, 28, 11, 12, 10, 36, 48, 30, 100, 51, 12, 106, 36, 36, 28, 44, 12, 24, 110, 20, 100, 7, 14, 130, 18, 36, 68, 138, 46, 60, 28, 42, 148, 15, 24, 20, 52, 52, 33, 162, 20, 83, 156, 18, 172, 60, 58, 178, 180, 60, 36, 40, 18, 95, 96, 12, 196, 99, 66, 84, 20, 66, 90, 210, 70, 28, 15, 18, 24, 37, 60, 226, 76, 30, 29, 92, 78, 119, 24, 162, 84, 36, 82, 50, 110, 8, 16, 36, 84, 131, 52, 22, 268, 135, 12, 20, 92, 30, 70, 94, 36, 60, 136, 48, 292, 116, 90, 132, 42, 100, 60, 102, 102, 155, 156, 12, 316, 140, 106, 72, 60, 36, 69, 30, 36, 132, 21, 28, 10, 147, 44, 346, 348, 36, 88, 140, 24, 179, 342, 110, 36, 183, 60, 156, 372, 100, 84, 378, 14, 191, 60, 42, 388, 88, 130, 156, 44, 18, 200, 60, 108, 180, 204, 68, 174, 164, 138, 418, 420, 138, 40, 60, 60, 43, 72, 28, 198, 73, 42, 442, 44, 148, 224, 20, 30, 12, 76, 72, 460, 231, 20, 466, 66, 52, 70, 180, 156, 239, 36, 66, 48, 243, 162, 490, 56, 60, 105, 166, 166, 251, 100, 156, 508, 9, 18, 204, 230, 172, 260, 522, 60, 40, 253, 174, 60, 212, 178, 210, 540, 180, 36, 546, 60, 252, 39, 36, 556, 84, 40, 562, 28, 54, 284, 114, 190, 220, 144, 96, 246, 260, 12, 586, 90, 196, 148, 24, 198, 299, 25, 66, 220, 303, 84, 276, 612, 20, 154, 618, 198, 33, 500, 90, 72, 45, 210, 28, 84, 210, 64, 214, 28, 323, 290, 30, 652, 260, 18, 658, 660, 24, 36, 308, 74, 60, 48, 180, 676, 48, 226, 22, 68, 76, 156, 230, 30, 276, 40, 58, 700, 36, 92, 300, 708, 78, 55, 60, 238, 359, 51, 24, 140, 121, 486, 56, 244, 84, 330, 246, 36, 371, 148, 246, 318, 375, 50, 60, 756, 110, 380, 36, 24, 348, 384, 16, 772, 20, 36, 180, 70, 252, 52, 786, 262, 84, 60, 52, 796, 184, 66, 90, 132, 268, 404, 270, 270, 324, 126, 12, 820, 411, 20, 826, 828, 92, 168, 332, 90, 419, 812, 70, 156, 330, 94, 396, 852, 36, 428, 858, 60, 431, 172, 136, 390, 132, 48, 300, 876, 292, 55, 882, 116, 443, 21, 270, 414, 356, 132, 140, 104, 42, 180, 906, 300, 91, 410, 60, 390, 153, 102, 420, 180, 102, 464, 126, 310, 40, 117, 156, 940, 220, 36, 946, 36, 316, 68, 380, 140, 204, 155, 318, 96, 483, 72, 194, 138, 60, 488, 110, 36, 491, 196, 138, 154, 495, 30, 396, 332, 36, 60, 232, 132, 468, 504, 42, 92, 84, 84, 1018, 340, 10, 20, 156, 294, 515, 258, 132, 120, 519, 346, 444, 180, 348, 262, 350, 108, 420, 15, 88, 1060, 531, 140, 240, 356, 24, 252, 140, 358, 492, 253, 342, 60, 543, 330, 1090, 364, 36, 274, 156, 366, 29, 24, 180, 1108, 100, 156, 148, 1116, 372, 522, 1122, 300, 231, 564, 84, 510, 452, 378, 264, 162, 42, 76, 180, 382, 575, 288, 60, 132, 180, 126, 166, 116, 388, 249, 1170, 88, 460, 530, 390, 236, 156, 156, 1186, 140, 44, 298, 476, 18, 180, 300, 200, 24, 280, 60, 516, 1212, 324, 152, 572, 180, 611, 420, 204, 1228, 615, 204, 36, 1236, 174, 72, 140, 164, 28, 156, 138, 534, 100, 418, 1258, 48, 420, 220, 180, 414, 20, 198, 40, 1276, 639, 60, 1282, 16, 60, 161, 1290, 86, 36, 648, 72, 1300, 651, 84, 1306, 120, 198, 300, 524, 146, 659, 60, 126, 260, 221, 442, 1210, 70, 44, 285, 204, 444, 312, 268, 224, 630, 96, 20, 540, 638, 30, 680, 644, 12, 683, 1332, 76, 1372, 100, 216, 588, 1380, 460, 92, 18, 462, 636, 99, 60, 70, 233, 466, 660, 140, 66, 704, 328, 156, 188, 36, 70, 84, 237, 180, 1426, 84, 468, 179, 60, 478, 719, 130, 36, 136, 723, 66, 1450, 1452, 48, 115, 486, 486, 90, 292, 162, 84, 245, 490, 580, 210, 56, 370, 1482, 180, 743, 744, 210, 1492, 132, 166, 1498, 234, 498, 84, 340, 502, 755, 88, 100, 180, 105, 156, 1522, 60, 508, 690, 1530, 18, 204, 364, 54, 66, 771, 204, 24, 1548, 230, 194, 620, 516, 779, 111, 260, 156, 783, 522, 1570, 660, 60, 738, 526, 40, 791, 316, 506, 678, 252, 522, 140, 532, 60, 400, 228, 212, 803, 201, 534, 52, 72, 210, 1618, 1620, 540, 300, 542, 180, 87, 385, 36, 1636, 740, 546, 260, 276, 180, 48, 84, 252, 60, 92, 78, 30, 831, 36, 1666, 1668, 556, 357, 660, 84, 99, 820, 120, 84, 24, 562, 198, 1692, 28, 848, 566, 162, 780, 20, 284, 244, 812, 114, 588, 200, 570, 215, 574, 220, 260, 36, 144, 1732, 692, 96, 828, 1740, 246, 348, 1746, 260, 408, 146, 36, 150, 879, 586, 140, 88, 90, 420, 330, 588, 140, 74, 148, 204, 891, 24, 1786, 596, 198, 810, 716, 598, 48, 25, 50, 684, 276, 198, 362, 252, 220, 429, 424, 606, 911, 180, 84, 290, 305, 276, 732, 830, 612, 393, 144, 60, 923, 602, 154, 72, 156, 618, 780, 1860, 594, 372, 1866, 66, 935, 936, 500, 1876, 939, 90, 804, 84, 72, 472, 60, 90, 756, 135, 210, 1900, 860, 28, 1906, 902, 84, 239, 764, 630, 900, 56, 64, 60, 460, 214, 1930, 644, 84, 444, 276, 646, 924, 388, 290, 1948, 975, 30, 88, 306, 652, 468, 60, 260, 210, 890, 18, 1972, 780, 658, 1978, 282, 660, 44, 1986, 24, 180, 996, 36, 1996, 333][deck_size >> 1]", "def faro_cycles(deck_size):\n if deck_size <= 2:\n return 1\n k = 1\n while 2 ** k % (deck_size - 1) != 1:\n k += 1\n return k"], "starter_code": "def faro_cycles(deck_size):\n", "input_output": {"fn_name": "faro_cycles", "inputs": [[2], [52], [542], [1250], [1954]], "outputs": [[1], [8], [540], [156], [30]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Iterators", "Lists"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57bc802c615f0ba1e3000029", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "faro_cycles", "task_id": "TACO_lite/10", "example": [[[6], [52]], ["2", "8"]]} +{"requirement": "The Tribonacci sequence Tn is defined as follows: \nT0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.\nGiven n, return the value of Tn.\n \nExample 1:\nInput: n = 4\nOutput: 4\nExplanation:\nT_3 = 0 + 1 + 1 = 2\nT_4 = 1 + 1 + 2 = 4\n\nExample 2:\nInput: n = 25\nOutput: 1389537\n\n \nConstraints:\n\n0 <= n <= 37\nThe answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.", "solutions": ["def tribonacci(n: int) -> int:\n if n == 0:\n return 0\n if n == 1:\n return 1\n ans = [0] * (n + 1)\n ans[0] = 0\n ans[1] = 1\n ans[2] = 1\n for i in range(3, n + 1):\n ans[i] = ans[i - 1] + ans[i - 2] + ans[i - 3]\n return ans[n]", "from collections import deque\n\ndef tribonacci(n: int) -> int:\n if n > 0 and n < 3:\n return 1\n if n == 0:\n return 0\n queue = deque([0, 1, 1])\n t = 2\n while t != n:\n queue.append(sum(queue))\n queue.popleft()\n t += 1\n return queue[2]", "def tribonacci(n: int) -> int:\n T = [0, 1, 1]\n for n in range(3, n + 1):\n T.append(T[n - 3] + T[n - 2] + T[n - 1])\n return T[n]", "def tribonacci(n: int) -> int:\n trib = []\n trib.append(0)\n trib.append(1)\n trib.append(1)\n for i in range(3, n):\n trib.append(trib[i - 1] + trib[i - 2] + trib[i - 3])\n if n > 2:\n return trib[n - 1] + trib[n - 2] + trib[n - 3]\n else:\n return trib[n]", "def tribonacci(n: int) -> int:\n try:\n return self.trib[n]\n except:\n currlen = len(self.trib)\n for i in range(currlen, n + 1):\n self.trib.append(self.trib[i - 1] + self.trib[i - 2] + self.trib[i - 3])\n return self.trib[n]", "def tribonacci(n: int) -> int:\n if n >= 0:\n if n < len(self.DP):\n return self.DP[n]\n else:\n offset: int = len(self.DP)\n self.DP.extend([0] * (n - offset + 1))\n for i in range(offset, n + 1):\n self.DP[i] = self.DP[i - 3] + self.DP[i - 2] + self.DP[i - 1]\n return self.DP[n]\n else:\n raise ValueError", "def tribonacci(n: int) -> int:\n t = [0, 1, 1]\n if n < 3:\n return t[n]\n for i in range(n - 2):\n t.append(sum(t))\n t = t[1:]\n return t[2]", "def tribonacci(n: int) -> int:\n if n == 0:\n return 0\n if n < 3:\n return 1\n (t0, t1, t2) = (0, 1, 1)\n for _ in range(3, n + 1):\n ans = t0 + t1 + t2\n (t0, t1, t2) = (t1, t2, ans)\n return ans"], "starter_code": "def tribonacci(n: int) -> int:\n", "input_output": {"fn_name": "tribonacci", "inputs": [[4]], "outputs": [4]}, "difficulty": "EASY", "raw_tags": ["Math", "Dynamic Programming", "Memoization"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Mathematics"], "skill_types": ["Dynamic programming"], "url": "https://leetcode.com/problems/n-th-tribonacci-number/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "tribonacci", "task_id": "TACO_lite/57", "example": [[[4], [25]], ["4", "1389537"]]} +{"requirement": "A frog starts at the point 0. In his first turn, he can make a jump of 1 unit. Now for all consequent turns, if the frog is currently at a distance x (from the start), his jump will take him x units forward. Given a leaf at a distance N, you have to find if the frog can reach that leaf or not.\n \nExample 1:\nInput:\nN = 3\nOutput:\nFalse\nExplanation:\nThe frog can't reach the position 3.\nExample 2:\nInput:\nN = 2\nOutput:\nTrue\nExplanation:\nThe frog will jump to position 1 in\nthe first jump. Now, he is at a distance\nof 1 from the start, so he cam jump 1m.\nSo, he reaches the point 2.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function canJump() which takes an Integer N as input and return \"True\" if the frog can reach N else return \"False\".\n \nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= N <= 10^{18}", "solutions": ["def canjump(N):\n if N == 1:\n return True\n if N % 2 == 1:\n return False\n else:\n while N > 2:\n N = N / 2\n if N % 2 == 1:\n return False\n break\n if N == 2:\n return True", "def canjump(N):\n prev = 1\n while prev <= N:\n if prev == N:\n return True\n prev += prev\n return False", "def canjump(n):\n if n & n - 1 == 0:\n return True\n else:\n return False", "def canjump(N):\n if N & N - 1 == 0:\n return 'True'\n return 'False'", "def canjump(N):\n i = 0\n a = 2 ** i\n while a < N:\n i += 1\n a = 2 ** i\n return a == N", "def canjump(N):\n return not N & N - 1", "def canjump(N):\n distance = 0\n while distance <= N:\n if distance == 0 or distance == 1:\n distance += 1\n else:\n distance *= 2\n if distance == N:\n return True\n return False", "import math\n\ndef canjump(N):\n num = int(math.log(N, 2))\n if 2 ** num == N:\n return 'True'\n else:\n return 'False'", "def canjump(n):\n return not n & n - 1", "def canjump(N):\n if N == 1 or (N and (not N & N - 1)) is True:\n return True\n return False", "def canjump(N):\n return N & N - 1 == 0", "def canjump(N):\n if N == 1 or N == 2:\n return True\n b = 2\n while b < N:\n b += b\n if b == N:\n return True\n else:\n return False", "def canjump(N):\n while True:\n if N == 1:\n return True\n elif N % 2 == 0:\n N = N // 2\n else:\n return False", "def canjump(N):\n return bin(N).count('1') == 1", "def canjump(N):\n jump_dist = 1\n dist = 0\n incr = 0\n while dist < N:\n dist += jump_dist\n if dist == N:\n return True\n jump_dist = dist\n return False", "def canjump(N):\n res = 0\n while pow(2, res) <= N:\n if pow(2, res) == N:\n return 'True'\n res += 1\n return False", "def canjump(n):\n k = 1\n while k <= n:\n if k == n:\n return True\n k = k * 2\n return False", "def canjump(N):\n j = 1\n while j <= N:\n if j == N:\n return True\n j = 2 * j\n return False", "def canjump(N):\n current = 1\n prev = 0\n result = False\n while prev <= N:\n if prev == N:\n result = True\n prev += current\n current = prev\n return result", "def canjump(x):\n if x == 1 or (x and (not x & x - 1)) is True:\n return True\n else:\n return False", "import math\n\ndef canjump(N):\n if math.log(N, 2).is_integer():\n return True\n return False", "def canjump(N):\n\n def possible(curr, prev):\n if curr == N:\n return True\n if curr > N:\n return False\n if prev == 0:\n return possible(curr + 1, 1)\n else:\n return possible(curr + prev, curr + prev)\n return possible(0, 0)", "import math\n\ndef canjump(N):\n return math.log(int(N), 2).is_integer()", "def canjump(N):\n if N == 1:\n return True\n Flag = False\n curr = 1\n while curr < N:\n curr += curr\n if curr == N:\n Flag = True\n return Flag", "def canjump(N):\n if N == 1:\n return True\n c_jump = 1\n jump = 0\n while jump < N:\n jump = jump + c_jump\n c_jump = jump\n if jump == N:\n return True\n else:\n return False", "def canjump(N):\n count = 0\n step = 1\n while count < N:\n count += step\n step = count\n if count == N:\n return True\n return False", "import math\n\ndef canjump(N):\n if N == 0:\n return true\n n = math.log2(N)\n if n == int(n):\n return True\n return False", "import math\n\ndef canjump(N):\n if N & N - 1 == 0:\n return True\n else:\n return False", "def canReach(n, i):\n if i == n:\n return True\n elif i > n:\n return False\n return self.canReach(n, i + i)\n\ndef canjump(N):\n if N == 0:\n return True\n i = 1\n return self.canReach(N, i)", "def canjump(N):\n for i in range(100):\n n = pow(2, i)\n if n == N:\n return 'True'\n return 'False'", "import math\n\ndef canjump(N):\n x = math.log(N, 2)\n if pow(2, int(x)) == N or N == 1:\n return True\n else:\n return False", "def canjump(N):\n if N == 0:\n return True\n if N == 1:\n return True\n ans = 1\n for i in range(1, N):\n ans = ans * 2\n if ans == N:\n return True\n if ans > N:\n return False\n return False", "def canjump(N):\n x = 0\n i = 1\n while x < N:\n x += i\n i = x\n if x == N:\n return True\n return False", "def canjump(N):\n position = 0\n num = N\n flag = 0\n while position <= num:\n if position == num:\n flag = 1\n if position == 0:\n position = position + 1\n else:\n position = 2 * position\n if flag == 0:\n return False\n else:\n return True", "def canjump(N):\n s = 0\n a = False\n i = 1\n while i <= N:\n if i == N:\n a = True\n break\n else:\n i = i * 2\n return a", "def canjump(N):\n n = N\n return n == 0 or n & n - 1 == 0", "def canjump(N):\n cj = 1\n j = 0\n while j < N:\n j = j + cj\n cj = j\n if j == N:\n return 'True'\n return 'False'", "def canjump(N):\n\n def isposs(n, N):\n if n == N:\n return True\n if n > N:\n return False\n return isposs(2 * n, N)\n return isposs(1, N)", "def canjump(N):\n curr_jump = 1\n jump = 0\n while jump < N:\n jump += curr_jump\n curr_jump = jump\n return jump == N", "def canjump(N):\n if N == 0 or N == 1:\n return True\n elif not N & N - 1:\n return True\n else:\n return False", "import math\n\ndef canjump(N):\n x = math.log(N) / math.log(2)\n if 2 ** x == 2 ** int(x):\n return True\n return False", "import math\n\ndef canjump(N):\n if N == 0 or N == 1:\n return 'True'\n res = math.log2(N)\n if int(res) == res:\n return 'True'\n return 'False'"], "starter_code": "def canjump(N):\n", "input_output": {"inputs": ["N = 3", "N = 2"], "outputs": ["False", "True"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/pattern-jumping4855/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "canjump", "task_id": "TACO_lite/17", "example": [[[3], [2]], ["False", "True"]]} +{"requirement": "Given an integer n, return the number of trailing zeroes in n!.\n\nExample 1:\n\n\nInput: 3\nOutput: 0\nExplanation: 3! = 6, no trailing zero.\n\nExample 2:\n\n\nInput: 5\nOutput: 1\nExplanation: 5! = 120, one trailing zero.\n\nNote: Your solution should be in logarithmic time complexity.", "solutions": ["def trailingzeroes(n):\n n_fives = 0\n while n > 0:\n n = n // 5\n n_fives += n\n return n_fives", "def trailingzeroes(n):\n c = 0\n while n > 0:\n n //= 5\n c += n\n return c", "def trailingzeroes(n):\n count = 1\n a = 5\n ans = 0\n while a <= n:\n ans += n // a\n count += 1\n a = 5 ** count\n return ans", "def trailingzeroes(n):\n return 0 if n == 0 else n // 5 + self.trailingzeroes(n // 5)", "def trailingzeroes(n):\n count = 0\n while n:\n count = count + n // 5\n n = n // 5\n return count", "def trailingzeroes(n):\n two = 0\n five = 0\n tmp = n\n while tmp != 0:\n tmp = tmp // 5\n five = five + tmp\n tmp = n\n while tmp != 0:\n tmp = tmp // 2\n two = two + tmp\n res = min(five, two)\n return res", "def trailingzeroes(n):\n ans = 0\n i = 5\n while n // i:\n ans += n // i\n i *= 5\n return ans", "def trailingzeroes(n):\n return sum([n // 5 ** i for i in range(1, 20)])", "def trailingzeroes(n):\n res = 5\n ans = 0\n while res < n + 1:\n ans += int(n / res)\n res = 5 * res\n return ans", "def trailingzeroes(n):\n trz = 0\n div = 5\n while div <= n:\n trz += int(n / div)\n div *= 5\n return trz", "def trailingzeroes(n):\n if n < 5:\n return 0\n elif n < 10:\n return 1\n i = 0\n while 5 ** (i + 1) <= n:\n i += 1\n s = n // 5\n j = 2\n while j <= i:\n s += n // 5 ** j\n j += 1\n return int(s)", "def trailingzeroes(n):\n num2 = 0\n div = 2\n quot = n // div\n while quot:\n num2 += quot\n div *= 2\n quot = n // div\n num5 = 0\n div = 5\n quot = n // div\n while quot:\n num5 += quot\n div *= 5\n quot = n // div\n return min(num2, num5)"], "starter_code": "def trailingzeroes(n: int) -> int:\n", "input_output": {"fn_name": "trailingZeroes", "inputs": [[3]], "outputs": [0]}, "difficulty": "EASY", "raw_tags": ["Math"], "name": null, "source": "leetcode", "tags": ["Mathematics"], "skill_types": [], "url": "https://leetcode.com/problems/factorial-trailing-zeroes/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "trailingzeroes", "task_id": "TACO_lite/66", "example": [[[3], [5]], ["0", "1"]]} +{"requirement": "Given an integer N, count the numbers having an odd number of factors from 1 to N (inclusive).\n \nExample 1:\nInput:\nN = 5\nOutput:\n2\nExplanation:\nFrom 1 - 5 only 2 numbers,\n1 and 4 are having odd number\nof factors.\nExample 2:\nInput:\nN = 1\nOutput:\n1\nExplanation:\n1 have only 1(odd)\nfactor\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function count() which takes an integer N as input parameters and returns an integer, the total count of numbers from 1 to N having an odd number of factors.\n \nExpected Time Complexity: O(sqrt(N))\nExpected Space Complexity: O(1)\n \nConstraints:\n0 <= N <= 10^{9}", "solutions": ["import math\n\ndef count(N):\n c = 0\n for i in range(1, N + 1):\n if i * i <= N:\n c += 1\n return c", "import math\n\ndef count(N):\n return math.floor(math.sqrt(N))", "def count(N):\n return int(N ** 0.5)", "def count(N):\n count_odd = 0\n for i in range(1, N + 1):\n if int(i ** 0.5) ** 2 == i:\n count_odd += 1\n return count_odd", "from math import *\n\ndef count(N):\n return int(N ** 0.5)", "import math\n\ndef count(N):\n return int(math.sqrt(N))", "def count(N):\n import math\n self.N = N\n p = math.sqrt(N)\n q = math.floor(p)\n return q", "import math\n\ndef count(N):\n (count, d) = (0, 0)\n for i in range(1, N + 1):\n d = int(math.sqrt(i))\n if i == d * d:\n count += 1\n return count", "def count(N):\n c = 0\n for i in range(1, N + 1):\n if i ** 0.5 == int(i ** 0.5):\n c = c + 1\n return c", "def count(N):\n import math\n if N == 1:\n return 1\n else:\n return int(math.sqrt(N))", "def count(N):\n count = 0\n val = int(pow(N, 0.5))\n for i in range(1, val + 1):\n if i * i <= N:\n count += 1\n return count", "import math\n\ndef count(N):\n ar = [1]\n for i in range(2, N + 1):\n if math.sqrt(i) == int(math.sqrt(i)):\n ar.append(i)\n return len(ar)", "import math\n\ndef count(n):\n if n == 1:\n return 1\n return int(math.sqrt(n))", "def sqrt(N):\n l = 1\n r = N\n m = N // 2\n while l <= r:\n if m * m == N:\n return m\n elif m * m > N:\n r = m - 1\n else:\n l = m + 1\n m = (l + r) // 2\n return m\n\ndef count(N):\n val = self.sqrt(N)\n return val", "import math\nfrom math import floor, ceil\n\ndef count(N):\n return floor(math.sqrt(N))", "def count(N):\n import math\n c = 1\n for i in range(2, N + 1):\n if int(math.sqrt(i) * int(math.sqrt(i)) == i):\n c = c + 1\n return c", "def count(N):\n a = 0\n b = N\n return int(b ** 0.5) - int(a ** 0.5)", "def count(N):\n count1 = 0\n for i in range(1, N + 1):\n if i * i <= N:\n count1 += 1\n return count1", "import math\n\ndef count(N):\n c = 0\n if N == 1:\n return 1\n else:\n for i in range(1, N):\n if math.ceil(math.sqrt(i)) == math.floor(math.sqrt(i)):\n c += 1\n return c", "from math import *\n\ndef count(N):\n main_count = 0\n for i in range(1, N + 1):\n result = int(sqrt(i))\n if result * result == i:\n main_count += 1\n return main_count", "def count(N):\n fac = int(pow(N, 1 / 2))\n return fac", "import math\n\ndef count(n):\n return int(math.sqrt(n))", "def helper(n):\n sr = n ** 0.5\n m1 = sr % 1\n if m1 == 0:\n return True\n else:\n return False\n\ndef count(N):\n ans = 1\n for i in range(2, N):\n if self.helper(i):\n ans += 1\n return ans", "import math\n\ndef count(N):\n count = 0\n for i in range(1, N + 1):\n square = i ** (1 / 2)\n if math.ceil(square) == math.floor(square):\n count += 1\n return count"], "starter_code": "def count (N):\n", "input_output": {"inputs": ["N = 5", "N = 1"], "outputs": ["2", "1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/count-odd-factors0844/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(sqrt(N))", "entry_point": "count", "task_id": "TACO_lite/43", "example": [[[5], [1]], ["2", "1"]]} +{"requirement": "An **anagram** is the result of rearranging the letters of a word to produce a new word.\n\n**Note:** anagrams are case insensitive\n\nComplete the function to return `true` if the two arguments given are anagrams of each other; return `false` otherwise.\n\n\n## Examples\n\n* `\"foefet\"` is an anagram of `\"toffee\"`\n\n* `\"Buckethead\"` is an anagram of `\"DeathCubeK\"`", "solutions": ["def is_anagram(test, original):\n return sorted(original.lower()) == sorted(test.lower())", "from collections import Counter\n\ndef is_anagram(test, original):\n return Counter(test.lower()) == Counter(original.lower())", "def is_anagram(test, original):\n return sorted(test.upper()) == sorted(original.upper())", "def is_anagram(test, original):\n (test_dict, original_dict) = ({}, {})\n for i in test.lower():\n test_dict[i] = test_dict.get(i, 0) + 1\n for i in original.lower():\n original_dict[i] = original_dict.get(i, 0) + 1\n return test_dict == original_dict", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n count = [0] * 26\n for i in range(len(test)):\n count[(ord(test[i]) & 31) - 1] += 1\n count[(ord(original[i]) & 31) - 1] -= 1\n return not any(count)", "def is_anagram(test, original):\n a = sorted(test.lower())\n b = sorted(original.lower())\n c = ''.join(a)\n d = ''.join(b)\n if c == d:\n return True\n else:\n return False", "def is_anagram(test, original):\n go = len(test) == len(original)\n arr = []\n if go:\n for i in test:\n arr.append(i.lower() in original.lower())\n return False not in arr\n else:\n return False", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n for l in test.lower():\n if l not in original.lower():\n return False\n return True", "from operator import eq\nfrom collections import Counter\n\ndef is_anagram(test, original):\n return eq(*map(Counter, map(str.lower, (test, original))))", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n return sorted(test.lower()) == sorted(original.lower())", "def is_anagram(test, original):\n if sorted(test.lower()) == sorted(original.lower()):\n return True\n else:\n return False", "is_anagram = lambda t, o: sorted(t.lower()) == sorted(o.lower())", "aprime = {'a': 2, 'c': 5, 'b': 3, 'e': 11, 'd': 7, 'g': 17, 'f': 13, 'i': 23, 'h': 19, 'k': 31, 'j': 29, 'm': 41, 'l': 37, 'o': 47, 'n': 43, 'q': 59, 'p': 53, 's': 67, 'r': 61, 'u': 73, 't': 71, 'w': 83, 'v': 79, 'y': 97, 'x': 89, 'z': 101}\n\ndef aprime_sum(str):\n strChList = list(str.lower())\n return sum([aprime[x] for x in strChList])\n\ndef is_anagram(test, original):\n if aprime_sum(test) == aprime_sum(original):\n return True\n else:\n return False", "def is_anagram(test, original):\n return set(original.lower()) == set(test.lower()) if len(test) == len(original) else False", "def is_anagram(test, original):\n a = list(test.lower())\n s = list(original.lower())\n if len(a) != len(s):\n return False\n else:\n for i in a:\n cond = False\n k = 0\n while k != len(s) and cond == False:\n if i == s[k]:\n a.remove(i)\n s.remove(i)\n cond = True\n k += 1\n if cond == False:\n return False\n if len(a) != len(s):\n return False\n else:\n return True", "def is_anagram(test, original):\n flag = 0\n if len(test) != len(original):\n return False\n else:\n for i in test.lower():\n if i not in original.lower():\n flag = 1\n else:\n continue\n if flag == 1:\n return False\n else:\n return True", "def is_anagram(test, original):\n\n def to_dict(word):\n dictionary = {}\n for w in word.lower():\n if w not in dictionary:\n dictionary[w] = 0\n else:\n dictionary[w] += 1\n return dictionary\n return to_dict(test) == to_dict(original)", "is_anagram = lambda a, b, s=sorted: s(a.lower()) == s(b.lower())", "def is_anagram(s, l):\n n = len(s)\n if len(l) != n:\n return False\n s = s.lower()\n l = l.lower()\n h = [0 for x in range(26)]\n for i in range(n):\n h[ord(s[i]) - 97] += 1\n h[ord(l[i]) - 97] -= 1\n return h.count(0) == 26", "def is_anagram(test: str, original: str) -> bool:\n return all([all([_ in original.lower() for _ in test.lower()]), len(test) == len(original)])", "def is_anagram(test, original):\n test = test.lower()\n original = original.lower()\n testcount = 0\n for i in test:\n if i in original:\n testcount += 1\n originalcount = 0\n for i in original:\n if i in test:\n originalcount += 1\n if testcount == originalcount and testcount == len(test) and (originalcount == len(original)):\n return True\n else:\n return False", "def is_anagram(test, original):\n if len(test) == len(original):\n test = test.lower()\n original = original.lower()\n count = 0\n for char in test:\n if char in original:\n count += 1\n if count == len(test):\n return True\n else:\n return False\n else:\n return False", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n letters = {}\n for i in test.lower():\n if i in letters:\n letters[i] += 1\n else:\n letters[i] = 1\n for i in original.lower():\n if i not in letters:\n return False\n if original.lower().count(i) != letters[i]:\n return False\n return True", "def is_anagram(t, o):\n return sorted([*t.lower()]) == sorted([*o.lower()])", "def is_anagram(test, original):\n x = list(test.lower())\n y = list(original.lower())\n x = sorted(x)\n y = sorted(y)\n if x == y:\n return True\n else:\n return False", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n a = sorted(test.lower())\n b = sorted(original.lower())\n if a == b:\n return True\n else:\n return False", "def is_anagram(test, original):\n sorted_test = sorted(list(test.lower()))\n sorted_original = sorted(list(original.lower()))\n return sorted_test == sorted_original", "def is_anagram(test, original):\n letters = [c for c in test.lower()]\n for char in original.lower():\n if char in letters:\n del letters[letters.index(char)]\n else:\n return False\n return not bool(len(letters))", "import collections\n\ndef is_anagram(test, original):\n return collections.Counter([i.lower() for i in sorted(test)]) == collections.Counter([i.lower() for i in sorted(original)])", "def is_anagram(test, original):\n test_set = sorted(test.lower())\n original_set = sorted(original.lower())\n if test_set == original_set:\n return True\n else:\n return False", "def is_anagram(test, original):\n t = sorted(test.lower())\n o = sorted(original.lower())\n if t == o:\n return True\n else:\n return False", "def is_anagram(test, original):\n new_test = test.lower()\n new_original = original.lower()\n sortedTest = sorted(new_test)\n sortedOriginal = sorted(new_original)\n for letters in new_test:\n if letters in new_original and len(new_test) == len(new_original) and (sortedOriginal == sortedTest):\n return True\n else:\n return False", "def is_anagram(test, original):\n first = [i.lower() for i in test]\n second = [i.lower() for i in original]\n return sorted(first) == sorted(second)", "def is_anagram(test, original):\n list_test = []\n list_original = []\n for i in test.lower():\n list_test += i\n for i in original.lower():\n list_original += i\n if len(list_test) == len(list_original):\n list_test.sort()\n list_original.sort()\n if list_test == list_original:\n return True\n else:\n return False\n else:\n return False", "def is_anagram(test, original):\n return True if sorted([letter for letter in test.lower()]) == sorted([letter for letter in original.lower()]) else False", "def is_anagram(test, original):\n t = list(test.lower())\n to = ''.join(sorted(t))\n o = list(original.lower())\n oo = ''.join(sorted(o))\n if to == oo:\n return True\n else:\n return False", "def is_anagram(test, original):\n letterCount = dict.fromkeys('abcdefghijklmnopqrstuvwxyz', 0)\n for c in test.lower():\n letterCount[c] += 1\n for c in original.lower():\n letterCount[c] -= 1\n for value in list(letterCount.values()):\n if value != 0:\n return False\n return True", "def is_anagram(a_str, b_str):\n if len(a_str) == len(b_str):\n a_list = list(a_str.lower())\n b_list = list(b_str.lower())\n for char in a_list:\n if char in b_list:\n b_list.remove(char)\n if not b_list:\n return True\n else:\n return False\n else:\n return False", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n else:\n test = test.lower()\n original = original.lower()\n counter_original = [0] * 26\n counter_test = [0] * 26\n for i in test:\n counter_test[ord(i) - 97] += 1\n for i in original:\n counter_original[ord(i) - 97] += 1\n return counter_test == counter_original", "def is_anagram(test, original):\n test = test.lower()\n original = original.lower()\n newList = [ord(c) for c in test]\n newList.sort()\n newList2 = [ord(b) for b in original]\n newList2.sort()\n if newList == newList2:\n return True\n else:\n return False", "def is_anagram(test, original):\n counterTest = [0] * 255\n counterOri = [0] * 255\n for i in range(len(test)):\n counterTest[ord(test[i].lower())] += 1\n for i in range(len(original)):\n counterOri[ord(original[i].lower())] += 1\n if counterOri == counterTest:\n return True\n else:\n return False", "def is_anagram(test, original):\n test = test.upper()\n original = original.upper()\n if sorted(test) == sorted(original):\n return True\n else:\n return False", "def is_anagram(test, original):\n if len(test) == len(original):\n test = test.lower()\n original = original.lower()\n for i in test:\n if original.find(i) == -1:\n return False\n else:\n test.replace(i, '')\n original.replace(i, '')\n else:\n return False\n return True", "def is_anagram(test, original):\n counter1 = [0] * 255\n counter2 = [0] * 255\n for i in range(len(test)):\n counter1[ord(test[i].lower())] += 1\n for i in range(len(original)):\n counter2[ord(original[i].lower())] += 1\n return counter1 == counter2", "def is_anagram(test, original):\n test = test.lower()\n original = original.lower()\n for x in range(len(test)):\n if test.count(test[x]) != original.count(test[x]):\n return False\n for x in range(len(original)):\n if test.count(original[x]) != original.count(original[x]):\n return False\n return True", "def is_anagram(test, original):\n test = test.lower()\n original = original.lower()\n nT = len(test)\n nO = len(original)\n if nO == nT:\n counterT = [0] * (255 + 1)\n counterO = [0] * (255 + 1)\n for x in range(nT):\n counterT[ord(test[x])] += 1\n counterO[ord(original[x])] += 1\n if counterT == counterO:\n return True\n else:\n return False\n else:\n return False", "def is_anagram(test, original):\n n = len(original)\n if n != len(test):\n return False\n counterTest = [0] * 255\n counterOrig = [0] * 255\n for i in range(n):\n counterTest[ord(test[i].lower())] += 1\n counterOrig[ord(original[i].lower())] += 1\n return True if ''.join(map(str, counterTest)) == ''.join(map(str, counterOrig)) else False", "def is_anagram(test, original):\n return sorted([n.lower() for n in test]) == sorted([n.lower() for n in original])", "def is_anagram(word_o, test_o):\n is_anagram = True\n word = word_o.lower()\n test = test_o.lower()\n if len(word) != len(test):\n is_anagram = False\n alist = list(test.lower())\n pos1 = 0\n while pos1 < len(word) and is_anagram:\n pos2 = 0\n found = False\n while pos2 < len(alist) and (not found):\n if word[pos1] == alist[pos2]:\n found = True\n else:\n pos2 = pos2 + 1\n if found:\n alist[pos2] = None\n else:\n is_anagram = False\n pos1 = pos1 + 1\n return is_anagram", "def is_anagram(test, original):\n l1 = list(test.lower())\n l2 = list(original.lower())\n if len(l1) == len(l2):\n for i in l1:\n if i in l2:\n l2.remove(i)\n else:\n return False\n else:\n return False\n return True", "def is_anagram(test, original):\n for i in test.lower():\n if i in original.lower() and len(test) == len(original):\n continue\n else:\n return False\n return True", "def is_anagram(test, original):\n test_list = [letter1 for letter1 in test.lower()]\n orig_list = [letter2 for letter2 in original.lower()]\n if sorted(test_list) == sorted(orig_list):\n return True\n else:\n return False", "def is_anagram(test, original):\n test = [i.lower() for i in test]\n original = [j.lower() for j in original]\n test.sort()\n original.sort()\n return test == original", "def is_anagram(test, original):\n test = test.lower()\n original = original.lower()\n if len(test) != len(original):\n return False\n for x in test:\n if test.count(x) == original.count(x):\n continue\n else:\n return False\n return True", "def is_anagram(test, original):\n test = test.lower()\n original = original.lower()\n new_test = list(test)\n new_original = list(original)\n new_test.sort()\n new_original.sort()\n if new_test == new_original:\n return True\n return False\n pass", "def is_anagram(test, original):\n return set(test.upper()) == set(original.upper()) and len(test) == len(original)", "is_anagram = lambda test, original: True if sorted(original.lower()) == sorted(test.lower()) else False", "def is_anagram(test, original):\n originalLower = [val for val in original.lower()]\n arr = test.lower()\n if len(arr) != len(originalLower):\n return False\n for element in arr:\n if element not in originalLower:\n return False\n else:\n originalLower.remove(element)\n return True", "def is_anagram(test, original):\n n1 = len(test)\n n2 = len(original)\n if n1 != n2:\n return False\n str1 = sorted(test.lower())\n str2 = sorted(original.lower())\n for i in range(0, n1):\n if str1[i] != str2[i]:\n return False\n return True", "def is_anagram(test, original):\n test_l = list(test.lower())\n original_l = list(original.lower())\n test_l.sort()\n original_l.sort()\n if test_l == original_l:\n return True\n else:\n return False", "def is_anagram(test, original):\n test = list(test.lower())\n original = list(original.lower())\n if len(test) != len(original):\n return False\n for word in test:\n for word2 in original:\n if word == word2:\n original.remove(word2)\n break\n if len(original) == 0:\n return True\n else:\n return False", "def is_anagram(test, original):\n\n def to_list(string):\n listed = []\n for i in range(len(string)):\n listed.append(string[i])\n return listed\n return str(sorted(to_list(test.lower()))) == str(sorted(to_list(original.lower())))", "def is_anagram(test, original):\n test = list(test.lower())\n test.sort()\n original = list(original.lower())\n original.sort()\n if original != test or len(test) != len(original):\n return False\n else:\n return True", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n test = sorted(test.lower())\n original = sorted(original.lower())\n for i in range(len(test)):\n if test[i] != original[i]:\n return False\n return True", "def is_anagram(test, original):\n result = True if len(test) == len(original) else False\n for letter in test.upper():\n result = False if letter not in original.upper() else result\n return result", "def is_anagram(test, original):\n if len(original) != len(test):\n return False\n test = test.lower()\n original = original.lower()\n for letter in original:\n if original.count(letter) != test.count(letter):\n return False\n return True", "def is_anagram(test, original):\n if sorted(test.lower()) == sorted(original.lower()):\n return True\n elif test != original:\n return False", "def is_anagram(test, original):\n test_list = sorted(list(test.lower()))\n original_list = sorted(list(original.lower()))\n if test_list == original_list:\n return True\n if test_list != original_list:\n return False", "def is_anagram(test, original):\n test = test.lower()\n original = original.lower()\n t = list(test)\n o = list(original)\n t.sort()\n o.sort()\n return t == o", "def is_anagram(test, original):\n t = test.lower()\n o = [*original.lower()]\n if len(t) != len(o):\n return False\n for c in t:\n if c in o:\n o.remove(c)\n else:\n return False\n return True", "def is_anagram(test, original):\n if len(test) > len(original) or len(test) < len(original):\n return False\n res = ''\n counter = 0\n sortedTest = sorted(test.lower())\n sortedOriginal = sorted(original.lower())\n for i in range(0, len(sortedTest)):\n if sortedTest[i] != sortedOriginal[i]:\n res = False\n break\n else:\n res = True\n return res", "from collections import Counter as C\n\ndef is_anagram(test, original):\n return C(test.lower()) == C(original.lower())", "def is_anagram(test, original):\n sort1 = sorted(test.lower())\n sort2 = sorted(original.lower())\n if ''.join(sort2) == ''.join(sort1):\n return True\n else:\n return False", "def is_anagram(test, original):\n theTest = test.lower()\n theOriginal = original.lower()\n if len(theTest) != len(theOriginal):\n return False\n else:\n index = 0\n lengthCheck = 0\n array = [None] * len(theTest)\n for i in theOriginal:\n array[index] = i\n index += 1\n for j in theTest:\n testLength = len(theTest)\n if j in array:\n lengthCheck += 1\n else:\n return False\n if lengthCheck == testLength:\n return True", "def is_anagram(tst, org):\n tst = tst.lower()\n org = org.lower()\n if len(tst) != len(org):\n return False\n for i in org:\n if tst.count(i) != org.count(i):\n return False\n return True", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n elif sorted(test.casefold()) == sorted(original.casefold()):\n return True\n else:\n return False", "def is_anagram(test, original):\n letters_original = sorted(list(original.upper()))\n letters_test = sorted(list(test.upper()))\n return letters_original == letters_test", "def is_anagram(test, original):\n return len(test) == len(original) and all([i in original.lower() for i in test.lower()])", "def is_anagram(test, original):\n org1 = [x.lower() for x in original]\n org2 = [y.lower() for y in test]\n org1.sort()\n org2.sort()\n if org1 == org2:\n return True\n return False", "def is_anagram(test, original):\n original_list = list(original.lower())\n test_list = list(test.lower())\n original_list.sort()\n test_list.sort()\n a = ''.join(test_list)\n b = ''.join(original_list)\n return a == b", "def is_anagram(test, original):\n test = test.lower().replace(' ', '')\n original = original.lower().replace(' ', '')\n if len(test) != len(original):\n return False\n for letter in test:\n if letter not in original:\n return False\n for letter in original:\n if letter not in test:\n return False\n return True"], "starter_code": "def is_anagram(test, original):\n", "input_output": {"fn_name": "is_anagram", "inputs": [["foefet", "toffee"], ["Buckethead", "DeathCubeK"], ["Twoo", "WooT"], ["dumble", "bumble"], ["ound", "round"], ["apple", "pale"]], "outputs": [[true], [true], [true], [false], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/529eef7a9194e0cbc1000255", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_anagram", "task_id": "TACO_lite/1", "example": [[], []]} +{"requirement": "Given 2 integers n and r. You task is to calculate ^{n}Cr%1000003.\n \nExample 1:\nInput: n = 5, r = 2\nOutput: 10\nExplanation: ^{5}C2 = 5! / (2! * 3!) = 10\nExample 2:\nInput: n = 3, r = 2\nOutput: 3\nExplanation: ^{3}C2 = 3! / (2! * 1!) = 3\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function nCr() which takes n and r as input parameter and returns nCr modulo 1000003.\n \nExpected Time Complexity: O(m * log_{m}n) where m = 1000003\nExpected Space Complexity: O(m)\n \nConstraints:\n1 <= n <= r <= 10^{16}", "solutions": ["M = 1000003\n\ndef __init__():\n self.f = [1] * M\n for i in range(1, M):\n self.f[i] = self.f[i - 1] * i % M\n\ndef ncr(n, r):\n if r > n:\n return 0\n if r == 0:\n return 1\n if n < M and r < M:\n return self.f[n] * pow(self.f[r], M - 2, M) * pow(self.f[n - r], M - 2, M) % M\n return self.ncr(n // M, r // M) * self.ncr(n % M, r % M) % M", "def fact(dp, p):\n dp[0] = 1\n for i in range(1, p):\n dp[i] = dp[i - 1] * i % p\n\ndef inverse(x, p):\n if not x:\n return 1\n for i in range(1, p):\n if int(x * i % p) == int(1 % p):\n return i\n\ndef find(n, r, p, dp):\n if n < r:\n return 0\n num = dp[n]\n den = dp[n - r] * dp[r] % p\n val = num * self.inverse(den, p) % p\n return val\n\ndef lucas(n, r, dp, p):\n if r == 0:\n return 1\n ni = int(n % p)\n ri = int(r % p)\n return self.lucas(n / p, r / p, dp, p) * self.find(ni, ri, p, dp) % p\n\ndef ncr(n, r):\n p = 1000003\n dp = [0] * 1000004\n self.fact(dp, p)\n return self.lucas(n, r, dp, p)", "def ncr(n, r):\n mod = 1000003\n\n def bin_expo(a, b):\n ans = 1\n while b > 0:\n if b & 1:\n ans = ans * a % mod\n a = a * a % mod\n b = b // 2\n return ans\n\n def mod_inverse(a):\n return bin_expo(a, mod - 2)\n\n def fermat(n, r):\n if n < r:\n return 0\n if r == 0 or n == r:\n return 1\n if r == n - 1 or r == 1:\n return n\n fact = [0] * (n + 1)\n fact[0] = 1\n for i in range(1, n + 1):\n fact[i] = fact[i - 1] * i % mod\n a = fact[n]\n b = mod_inverse(fact[r])\n c = mod_inverse(fact[n - r])\n return a * b % mod * c % mod % mod\n\n def lucas(n, r):\n if r == 0:\n return 1\n ni = n % mod\n ri = r % mod\n return lucas(n // mod, r // mod) * fermat(ni, ri) % mod\n return lucas(n, r)", "def ncrfarment(n, r):\n p = 1000003\n num = den = 1\n for i in range(r):\n num = num * (n - i) % p\n den = den * (i + 1) % p\n return num * pow(den, p - 2, p) % p\n\ndef ncr(n, r):\n p = 1000003\n if r == 0:\n return 1\n ni = int(n % p)\n ri = int(r % p)\n return self.ncr(int(n / p), int(r / p)) * self.ncrfarment(ni, ri) % p", "def ncr(n, r):\n large = 1000003\n (num, den) = self.test(n, r)\n inv = self.modular_inverse(den, large)\n return num * inv % large\n\ndef test(n, r):\n if r == 0:\n return (1, 1)\n large = 1000003\n r = min(r, n - r)\n until = r % large + large if r > large else r\n n_i = (n - r) % large\n r_i = 0\n num = 1\n den = 1\n zero = 0\n while r_i < until:\n n_i = (n_i + 1) % large\n r_i += 1\n if n_i == 0:\n zero += 1\n if zero > until // large:\n return (0, 1)\n else:\n num = num * n_i % large\n if r_i % large > 0:\n den = den * (r_i % large) % large\n (num_1, den_1) = self.test(n // large, r // large)\n num = num * num_1 % large\n den = den * den_1 % large\n return (num, den)\n\ndef modular_inverse(a, n):\n x1 = 0\n x2 = 1\n while a != 0:\n q = n // a\n (n, a) = (a, n % a)\n (x1, x2) = (x2, x1 - x2 * q)\n return x1", "def fact(dp, p):\n dp[0] = 1\n for i in range(1, p):\n dp[i] = dp[i - 1] * i % p\n\ndef inverse(x, p):\n if x == 0:\n return 1\n for i in range(1, p):\n if x * i % p == 1 % p:\n return i\n\ndef ncr(dp, n, r, p):\n if n < r:\n return 0\n num = dp[n] % p\n den = dp[n - r] * dp[r] % p\n return num * self.inverse(den, p) % p\n\ndef lucas(dp, n, r, p):\n if r == 0:\n return 1\n n_ = int(n % p)\n r_ = int(r % p)\n return self.lucas(dp, n / p, r / p, p) * self.ncr(dp, n_, r_, p) % p\n\ndef ncr(n, r):\n p = 1000003\n dp = [0 for _ in range(p + 1)]\n self.fact(dp, p)\n return self.lucas(dp, n, r, p)", "M = 1000003\n\ndef lucas(n, r, m):\n if r == 0:\n return 1\n if n < m and r < m:\n (f, r) = ([1] * (n + 1), min(r, n))\n for i in range(1, len(f)):\n f[i] = f[i - 1] * i % m\n return f[n] * pow(f[r], m - 2, m) * pow(f[n - r], m - 2, m) % m\n return lucas(n // m, r // m, m) * lucas(n % m, r % m, m) % m\n\ndef ncr(n, r):\n\n def count(x):\n res = 0\n while x > 0:\n res += x // M\n x //= M\n return res\n if count(n) > count(r) + count(n - r):\n return 0\n return lucas(n, r, M)\n\ndef __init__():\n self.a = [1] * M\n for i in range(1, len(self.a)):\n self.a[i] = self.a[i - 1] * i % M", "def __init__():\n self.m = 1000003\n self.fact = [1] * self.m\n for i in range(1, self.m):\n self.fact[i] = self.fact[i - 1] * i % self.m\n\ndef fast_pow(base, exp):\n res = 1\n while exp:\n if exp % 2:\n res = res * base % self.m\n base = base * base % self.m\n exp //= 2\n return res\n\ndef inverse(a):\n return self.fast_pow(a, self.m - 2)\n\ndef small(n, r):\n if r > n:\n return 0\n return self.fact[n] * self.inverse(self.fact[r] * self.fact[n - r] % self.m) % self.m\n\ndef ncr(n, r):\n if n == 0 or r == 0:\n return 1\n return self.ncr(n // self.m, r // self.m) * self.small(n % self.m, r % self.m) % self.m", "def __init__():\n self.m = 1000003\n self.fact = [1] * self.m\n for i in range(1, self.m):\n self.fact[i] = self.fact[i - 1] * i % self.m\n\ndef inverse(a):\n return pow(a, self.m - 2, self.m)\n\ndef small(n, r):\n if r > n:\n return 0\n return self.fact[n] * self.inverse(self.fact[r] * self.fact[n - r] % self.m) % self.m\n\ndef ncr(n, r):\n if n == 0 or r == 0:\n return 1\n return self.ncr(n // self.m, r // self.m) * self.small(n % self.m, r % self.m) % self.m"], "starter_code": "def ncr(n, r):\n", "input_output": {"inputs": ["n = 5, r = 2", "n = 3, r = 2"], "outputs": ["10", "3"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Combinatorial", "Algorithms", "Modular Arithmetic"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory", "Combinatorics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/ncr-mod-m-part-10038/1", "Expected Auxiliary Space": "O(m)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(m * log_{m}n) where m = 1000003", "entry_point": "ncr", "task_id": "TACO_lite/14", "example": [[[5, 2], [3, 2]], ["10", "3"]]} +{"requirement": "An enemy spy has poisoned one out of N sweets in a bakery. Even a bite of the poisoned sweet has potency to kill. However, the effects of the poison show only in 30 days. The managers asks the jailor to identify the poisoned sweet within 30 days. What is the least number of prisoners the jailor must employ to identify the poisoned sweet?\nNote: A sweet can be eaten by any number of prisoners.\n \nExample 1:\nInput:\nN = 3\nOutput:\n2\nExplanation:\nThe poison can be identified using\nonly 2 prisoners.\nExample 2:\nInput:\nN = 2\nOutput:\n1\nExplanation:\nThe poison can be identified using\nonly 1 prisoner.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function numOfPrisoners() which takes an Integer N as input and returns the minimum number of prisoners required to identify the poisoned sweet.\n \nExpected Time Complexity: O(log(N))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= N <= 10^{9}", "solutions": ["def numofprisoners(N):\n if N == 1:\n return 0\n c = int(math.log2(N))\n if 2 ** c < N:\n c += 1\n return c", "from math import *\n\ndef numofprisoners(N):\n return ceil(log(N, 2))"], "starter_code": "def numofprisoners(N):\n", "input_output": {"inputs": ["N = 3", "N = 2"], "outputs": ["2", "1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/poisioned-sweet2651/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(N))", "entry_point": "numofprisoners", "task_id": "TACO_lite/73", "example": [[[3], [2]], ["2", "1"]]} +{"requirement": "Given an string S, representing a large interger. Return the largest-valued odd integer (as a string) that is substring of the given string S.\nNote : A substring is a contiguous sequence of characters within a string. Null string (\"\") is also a substring.\nExample 1:\nInput: s = \"504\"\nOutput: \"5\"\nExplanation: The only subtring \"5\" is odd number.\n \nExample 2:\nInput: s = \"2042\"\nOutput: \"\"\nExplanation: All the possible non-empty substring have even value.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function maxOdd() which takes the string S as input and returns the largest-valued odd integer that is substring of the given string.\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1).\nConstraints:\n1<=|S|<=2*10^{5}\nS only consists of digits and does not contain any leading zeros.", "solutions": ["def maxodd(s):\n for i in range(len(s) - 1, -1, -1):\n if s[i] in {'1', '3', '5', '7', '9'}:\n return s[:i + 1]\n return ''", "import sys\n\ndef maxodd(s):\n ss = s[::-1]\n for i in range(len(ss)):\n if int(ss[i]) % 2 != 0:\n sss = ss[i:]\n return sss[::-1]\n return ''", "def maxodd(s):\n end = -1\n start = 0\n for i in range(0, len(s)):\n if int(s[i]) % 2 != 0:\n end = i\n if end == -1:\n return ''\n return s[start:end + 1]", "def maxodd(s):\n n = len(s) - 1\n while n >= 0:\n if int(s[n]) % 2 != 0:\n return s[:n + 1]\n n -= 1\n return ''", "def maxodd(num):\n op = []\n for i in range(len(num)):\n if int(num[i]) % 2 != 0:\n op.append(i)\n else:\n pass\n if len(op) == 0:\n return ''\n elif op[-1] == len(num) - 1:\n return num\n else:\n return ''.join(num[:op[-1] + 1])", "def maxodd(s):\n l = list(map(int, s))\n st = 0\n t = 0\n for i in range(len(l)):\n if l[i] % 2 != 0:\n t = 1\n st = i\n if t == 0:\n return ''\n return s[:st + 1]", "def maxodd(s):\n ch = 0\n for i in s:\n if int(i) % 2 != 0:\n ch = 1\n if ch == 0:\n return ''\n else:\n for i in range(len(s) - 1, -1, -1):\n if int(s[i]) % 2 != 0:\n return int(s[:i + 1])", "def maxodd(s):\n ma = 0\n for i in range(len(s), -0, -1):\n if int(s[0:i]) % 2 == 1:\n ma = max(ma, int(s[0:i]))\n if ma == 0:\n return ''\n return ma", "def maxodd(S):\n end = None\n for i in range(len(S) - 1, -1, -1):\n if int(S[i]) % 2 != 0:\n end = i\n break\n if end is not None:\n return S[:end + 1]\n return ''", "def maxodd(num):\n if float(num) % 2 != 0:\n return num\n else:\n n = int(num)\n for i in range(len(num)):\n if n % 2 != 0:\n return str(n)\n else:\n n //= 10\n return ''", "def maxodd(s):\n s = s[::-1]\n j = 0\n for i in range(len(s)):\n if int(s[i]) % 2 != 0:\n j = i\n break\n if j == 0 and int(s[0]) % 2 == 0:\n return ''\n else:\n n = len(s) - j - 1\n s = s[::-1]\n f = s[:n + 1]\n return f", "def maxodd(s):\n n = len(s)\n for i in range(n - 1, -1, -1):\n if int(s[i]) % 2 == 1:\n return s[:i + 1]\n return ''", "def maxodd(S):\n for i in range(len(S) - 1, -1, -1):\n if int(S[i]) % 2:\n return S[:i + 1]\n return ''", "def maxodd(s):\n while 1:\n if int(s) % 2 == 1:\n return s\n else:\n s = s[:-1]\n if len(s) == 0:\n break\n return ''", "def maxodd(s):\n strlen = len(s) - 1\n while strlen >= 0:\n c = int(s[strlen])\n if c % 2 != 0:\n return s[0:strlen + 1]\n strlen -= 1\n return ''", "def maxodd(s):\n odd = -1\n for (i, el) in enumerate(s):\n if el != 0 and int(el) % 2 != 0:\n odd = i\n if odd == -1:\n return ''\n return s[:odd + 1]", "def maxodd(s):\n ptr1 = 0\n ptr2 = len(s)\n while ptr1 < ptr2:\n if int(s[ptr1:ptr2]) % 2 != 0:\n return s[ptr1:ptr2]\n else:\n ptr2 -= 1\n return ''", "def maxodd(s):\n p = -1\n for i in range(len(s) - 1, -1, -1):\n if int(s[i]) & 1:\n p = i\n break\n if p == -1:\n return ''\n return s[:p + 1]", "def maxodd(s):\n new = ''\n n = len(s)\n for i in range(n - 1, -1, -1):\n if len(new) != 0:\n new = s[i] + new\n if len(new) == 0:\n if s[i] == '1' or s[i] == '3' or s[i] == '5' or (s[i] == '7') or (s[i] == '9'):\n new = s[i] + new\n return new", "def maxodd(s):\n max = 0\n if int(s) % 2 != 0:\n return s\n s1 = ''\n for i in s:\n s1 = s1 + i\n j = int(s1)\n if j % 2 != 0:\n if j > max:\n max = j\n if j % 2 == 0:\n continue\n if max:\n max = str(max)\n return max\n else:\n return ''", "def maxodd(s):\n p = ''\n l = 0\n for i in range(0, len(s)):\n p += s[i]\n p = int(p)\n if p % 2 != 0:\n l = p\n p = str(p)\n if l > 0:\n return l\n k = ''\n return k", "def maxodd(s):\n if int(s) % 2 != 0:\n return s\n q = []\n for i in range(len(s)):\n m = s[:i + 1]\n if int(m) % 2 != 0:\n q.append(m)\n if not q:\n return ''\n return max([int(i) for i in q])", "def maxodd(s):\n mx = 0\n for i in range(len(s) - 1, -1, -1):\n a = int(s[i])\n if a % 2:\n return s[:i + 1]\n return ''", "def maxodd(s):\n for i in range(len(s) - 1, -1, -1):\n num = int(s[i])\n if num & 1 != 0:\n return s[0:i + 1]\n return ''", "def maxodd(s):\n ans = ''\n tmp = ''\n for i in s:\n tmp += i\n if int(tmp) % 2 != 0:\n ans = tmp\n return ans", "def maxodd(s):\n res = ''\n cur = ''\n for i in s:\n if int(i) % 2 != 0:\n cur += i\n res = max(res, cur)\n else:\n cur += i\n return res", "def maxodd(num):\n indx = -1\n n = len(num)\n for i in range(n):\n if int(num[i]) % 2 == 1:\n indx = i\n if indx == -1:\n return ''\n return num[:indx + 1]", "def maxodd(s):\n for i in range(len(s) - 1, -1, -1):\n if s[i] in '13579':\n return s[:i + 1]\n return ''", "def maxodd(s):\n maxi = 0\n sbs = ''\n for i in s:\n sbs += i\n if int(sbs) % 2 != 0:\n maxi = max(int(maxi), int(sbs))\n return '' if maxi == 0 else maxi", "def maxodd(s):\n num = int(s)\n st = ''\n for i in range(len(s)):\n remainder = num % 10\n if remainder % 2 != 0:\n st += str(num)\n return st\n num = num // 10\n return st", "def maxodd(s):\n n = int(s)\n if n % 2 != 0:\n return str(n)\n while n != 0:\n n = n // 10\n if n % 2 != 0:\n return str(n)\n else:\n return ''", "def maxodd(s):\n l = 0\n j = len(s) - 1\n while j != -1:\n if int(s[j]) % 2 != 0:\n break\n j -= 1\n return s[:j + 1]", "def maxodd(s):\n out = ''\n max_s = ''\n max = 0\n for i in s:\n out += i\n if max < int(out) and int(out) % 2 == 1:\n max = int(out)\n max_s = out\n return max_s", "def maxodd(s):\n (out, m) = ('', [])\n for e in s:\n out = out + e\n if int(out) % 2 != 0:\n m.append(int(out))\n if len(m) == 0:\n return ''\n return max(m)", "def maxodd(s):\n mo = ''\n st = -1\n en = -1\n for i in range(len(s)):\n if int(s[i]) % 2 != 0 and st == -1:\n st = i\n elif int(s[i]) % 2 != 0:\n en = i\n else:\n continue\n if en == -1:\n en = st\n return s[:en + 1]", "def maxodd(s):\n m = 0\n for i in range(len(s)):\n if int(s[:i + 1]) % 2 != 0 and int(s[:i + 1]) > m:\n m = int(s[:i + 1])\n return str(m) if m > 0 else ''", "def maxodd(s):\n c = -1\n for i in range(len(s) - 1, -1, -1):\n j = int(s[i])\n if j % 2 != 0:\n c = i\n break\n if c == -1:\n return ''\n else:\n return s[:c + 1]", "def maxodd(s):\n idx = 0\n result = 0\n for i in range(len(s) - 1, -1, -1):\n if int(s[i]) % 2 != 0:\n return s[:i + 1]\n return ''"], "starter_code": "def maxodd(s):\n", "input_output": {"inputs": ["s = \"504\"", "s = \"2042\""], "outputs": ["\"5\"", "\"\""]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/largest-odd-number-in-string/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|).", "entry_point": "maxodd", "task_id": "TACO_lite/75", "example": [[["504"], ["2042"]], ["5", ""]]} +{"requirement": "There are three piles of pens. A pens in the first pile and B pens in the second Pile.Find the minimum number of pens that should be there in the third pile so that sum of all three piles produces either a prime number or unity. \nNote: there should be atleast one pen in the third pile.\nExample 1:\nInput: A = 1, B = 3\nOutput: 1\nExplanation: A + B + K = prime\nK = 1, 1 + 3 + 1 = 5.So answer = 1\nbecuase 5 is minimum possible prime. \nExample 2:\nInput: A = 4, B = 3\nOutput: 4\nExplanation: A + B + K = prime\nK = 4, 4 + 3 + 4 = 11.So answer = 4\nbecuase 11 is minimum possible prime.\nYour Task: \nYou dont need to read input or print anything. Complete the function minThirdPiles() which takes A and B as input parameter and returns the the minimum number of pens that should be there in the third pile so that sum of all three piles produces a prime number.\nExpected Time Complexity: O(nlogn)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= A <=1000\n1 <= B <=1000", "solutions": ["def isPrime(n):\n prime = 0\n if n == 1:\n return 0\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n prime = 1\n break\n if prime:\n return 0\n else:\n return 1\n\ndef minthirdpiles(A, B):\n i = 1\n flag = True\n while flag:\n p = A + B + i\n if self.isPrime(p):\n flag = False\n else:\n i += 1\n return i", "def isPrime(num):\n i = 2\n while i * i <= num:\n if num % i == 0:\n return False\n break\n i += 1\n return True\n\ndef minthirdpiles(A, B):\n summ = A + B\n n = 0\n i = summ + 1\n while i < 1000000:\n if self.isPrime(i):\n n = i\n break\n i += 1\n return n - summ", "def minthirdpiles(A, B):\n\n def is_prime(x):\n if x == 1:\n return False\n for i in range(2, int(x ** 0.5) + 1):\n if x % i == 0:\n return False\n return True\n ans = None\n x = A + B\n for i in range(x + 1, x * x):\n if is_prime(i):\n return i - x", "import math\n\ndef minthirdpiles(A, B):\n\n def isprime(n):\n if n <= 1:\n return False\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n for x in range(1, 10000):\n if isprime(A + B + x):\n return x", "def minthirdpiles(A, B):\n if A == 0 and B == 0:\n return 1\n num = A + B + 1\n while not self.isPrime(num):\n num += 1\n return num - (A + B)\n\ndef isPrime(num):\n if num <= 1:\n return False\n if num == 2 or num == 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n i = 5\n while i * i <= num:\n if num % i == 0:\n return False\n i += 1\n return True", "def minthirdpiles(A, B):\n if A == 0 and B == 0:\n return 1\n k = A + B\n for i in range(1, k):\n s = k + i\n t = []\n for j in range(2, s):\n if s % j == 0:\n t.append(s)\n break\n if len(t) == 0:\n return i", "def minthirdpiles(A, B):\n\n def p(n):\n if n == 0 or n == 1:\n return False\n s = int(n ** 0.5)\n for i in range(2, s + 1):\n if n % i == 0:\n return False\n return True\n c = A + B\n d = 0\n while True:\n c += 1\n d += 1\n if p(c):\n return d", "def minthirdpiles(A, B):\n\n def is_prime(n):\n i = 2\n if n < 3:\n return False\n while i * i <= n:\n if n % i == 0:\n return False\n i += 1\n return True\n n = A + B\n temp = 0\n if is_prime(n):\n temp = 1\n while not is_prime(n + temp):\n temp += 1\n return temp", "def minthirdpiles(A, B):\n\n def isPrime(num):\n if num < 2:\n return 0\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return 0\n return 1\n sumval = A + B\n for i in range(1, 1000):\n if isPrime(i + sumval) == 1:\n return i", "def minthirdpiles(A, B):\n prime = [1 for _ in range(2500)]\n prime[0] = prime[1] = 0\n for i in range(2, 2500):\n if prime[i] == 1:\n for j in range(2 * i, 2500, i):\n prime[j] = 0\n for j in range(A + B + 1, 2500):\n if prime[j] == 1:\n return j - (A + B)", "from math import *\n\ndef isprime(x):\n if x <= 1:\n return 0\n for i in range(2, int(sqrt(x)) + 1):\n if x % i == 0:\n return 0\n return 1\n\ndef minthirdpiles(A, B):\n c = A + B\n if isprime(c):\n c = c + 1\n i = 1\n while not isprime(c):\n i = i + 1\n c = c + 1\n return i\n else:\n i = 0\n while not isprime(c + i):\n i = i + 1\n return i", "def is_prime(num):\n for j in range(2, int(num ** (1 / 2)) + 1):\n if num % j == 0:\n return 0\n return 1\n\ndef minthirdpiles(A, B):\n n = 1\n while True:\n pri = self.is_prime(A + B + n)\n if pri == 1:\n break\n n += 1\n if A == B:\n return min(A, n)\n return n", "def is_prime(num):\n t = num // 2 + 1\n while t > 2:\n if num % t == 0:\n return 0\n t -= 1\n return 1\n\ndef minthirdpiles(A, B):\n n = 1\n while True:\n pri = self.is_prime(A + B + n)\n if pri == 1:\n break\n n += 1\n if A == B:\n return min(A, n)\n return n", "import math as m\n\ndef minthirdpiles(A, B):\n\n def pr(x):\n if x < 2:\n return False\n for i in range(2, int(m.sqrt(x) + 1)):\n if x % i == 0:\n return False\n return True\n z = 1\n while True:\n if pr(A + B + z):\n return z\n z = z + 1", "def minthirdpiles(A, B):\n a = 0\n p = 0\n import math\n while p == 0:\n a = a + 1\n sum = A + B + a\n for i in range(2, int(math.sqrt(sum)) + 1):\n if sum % i == 0:\n p = 1\n if p == 0:\n return a\n p = 0", "from math import sqrt\n\ndef prime(n):\n if n <= 1:\n return 0\n for i in range(2, int(sqrt(n)) + 1):\n if n % i == 0:\n return 0\n else:\n return 1\n\ndef minthirdpiles(A, B):\n for i in range(1, A * B):\n if prime(A + B + i) == 1:\n return i", "def minthirdpiles(A, B):\n n = A + B\n while n > 0:\n for i in range(2, int(n ** 0.5) + 2):\n if (n + 1) % i == 0:\n n += 1\n break\n else:\n return n - (A + B) + 1", "def minthirdpiles(A, B):\n\n def check_prime(n):\n if n == 2:\n return True\n if n <= 1 or n % 2 == 0:\n return False\n else:\n for i in range(3, n):\n if n % i == 0:\n return False\n return True\n for i in range(1, 2000):\n if check_prime(i + A + B):\n return i"], "starter_code": "def minthirdpiles(A, B):\n", "input_output": {"inputs": ["A = 1, B = 3", "A = 4, B = 3"], "outputs": ["1", "4"]}, "difficulty": "EASY", "raw_tags": ["Prime Number"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/collection-of-pens1843/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(nlogn)", "entry_point": "minthirdpiles", "task_id": "TACO_lite/22", "example": [[[1, 3], [4, 3]], ["1", "4"]]} +{"requirement": "Given a string Str which may contains lowercase and uppercase chracters. The task is to remove all duplicate characters from the string and find the resultant string. The order of remaining characters in the output should be same as in the original string.\nExample 1:\nInput:\nStr = geeksforgeeks\nOutput: geksfor\nExplanation: After removing duplicate\ncharacters such as e, k, g, s, we have\nstring as \"geksfor\".\nExample 2:\nInput:\nStr = HappyNewYear\nOutput: HapyNewYr\nExplanation: After removing duplicate\ncharacters such as p, e, a, we have\nstring as \"HapyNewYr\".\nYour Task:\nComplete the function removeDuplicates() which takes a string str, as input parameters and returns a string denoting the answer. You don't to print answer or take inputs.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 ≤ N ≤ 10^{5}\nString contains uppercase and lowercase english letters.", "solutions": ["def removeduplicates(str):\n asci = [0] * 256\n s = ''\n for i in range(len(str)):\n x = ord(str[i])\n asci[x] += 1\n for i in range(len(str)):\n x = ord(str[i])\n if asci[x] > 0:\n s += str[i]\n asci[x] = 0\n return s", "def removeduplicates(str):\n ans = ''\n li = [0] * 256\n for i in str:\n ind = ord(i) - ord('a')\n if li[ind] == 0:\n li[ind] = 1\n ans += i\n return ans", "def removeduplicates(str):\n lst = []\n for i in str:\n if i not in lst:\n lst.append(i)\n return ''.join(lst)", "def removeduplicates(str):\n (m, p) = ({}, '')\n for i in str:\n if i not in m:\n p += i\n m[i] = 1\n return p", "def removeduplicates(str):\n f = ''\n for i in str:\n if i not in f:\n f = f + i\n return f", "def removeduplicates(str):\n str1 = ''\n for i in range(len(str)):\n if str[i] not in str1:\n str1 = str1 + str[i]\n return str1", "def removeduplicates(str):\n from collections import defaultdict\n dic = defaultdict(int)\n ans = ''\n for i in str:\n if dic[i] == 0:\n ans += i\n dic[i] += 1\n return ans", "def removeduplicates(str):\n l = list(str)\n l1 = []\n for i in l:\n if i not in l1:\n l1.append(i)\n else:\n pass\n x = ''.join(l1)\n return x", "from collections import OrderedDict\n\ndef removeduplicates(str):\n a = []\n b = ''\n for i in str:\n a.append(i)\n a = list(OrderedDict.fromkeys(a))\n for i in a:\n b += i\n return b", "def removeduplicates(str):\n a = {}\n b = ''\n for i in str:\n if i not in a:\n b += i\n a[i] = 1\n return b", "def removeduplicates(str):\n ms = ''\n d = {}\n for i in str:\n if i not in d:\n ms += i\n d[i] = 1\n return ms", "def removeduplicates(str):\n arr = [char for char in str]\n b = list()\n for i in arr:\n if i not in b:\n b.append(i)\n return ''.join(b)", "def removeduplicates(str):\n p = ''\n for char in str:\n if char not in p:\n p = p + char\n return p", "def removeduplicates(str):\n freq = {}\n s = ''\n for i in range(len(str)):\n if str[i] not in freq:\n s += str[i]\n freq[str[i]] = i\n return s", "def removeduplicates(str):\n l = list(str)\n lst = []\n s = set()\n for i in l:\n if i not in s:\n s.add(i)\n lst.append(i)\n return ''.join(lst)", "def removeduplicates(s: str) -> str:\n seen = set()\n ans = []\n for c in s:\n if c not in seen:\n ans.append(c)\n seen.add(c)\n return ''.join(ans)", "def removeduplicates(str):\n unique = set()\n res = []\n for c in str:\n if c not in unique:\n res.append(c)\n unique.add(c)\n return ''.join(res)", "def removeduplicates(str: str) -> str:\n hash = [0] * 256\n ans = ''\n for c in str:\n if hash[ord(c)] == 0:\n ans += c\n hash[ord(c)] += 1\n return ans", "def removeduplicates(Str):\n unique_chars = set()\n output = ''\n for char in Str:\n if char not in unique_chars:\n unique_chars.add(char)\n output += char\n return output", "def removeduplicates(s):\n for i in range(len(s)):\n s[i].lower()\n d = {}\n for i in s:\n d[i] = 1\n t = ''\n for i in s:\n if d[i] == 1:\n t += i\n d[i] -= 1\n return t", "def removeduplicates(string):\n hash_set = set()\n result = ''\n for char in string:\n if char not in hash_set:\n result += char\n hash_set.add(char)\n return result", "def removeduplicates(str):\n letters = []\n output = ''\n for i in range(len(str)):\n if str[i] in letters:\n continue\n else:\n output += str[i]\n letters.append(str[i])\n return output", "def removeduplicates(s):\n result = ''\n for char in s:\n if char not in result:\n result += char\n return result", "def removeduplicates(str):\n res = ''\n for s in str:\n if s not in res:\n res = res + s\n return res", "def removeduplicates(str):\n seen = set()\n result = ''\n for char in str:\n if char not in seen:\n result += char\n seen.add(char)\n return result", "def removeduplicates(str):\n a = []\n s = ''\n for i in str:\n if i not in a:\n a.append(i)\n for i in a:\n s += i\n return s", "def removeduplicates(str):\n a = list(str)\n l = []\n l.append(a[0])\n for i in range(1, len(a)):\n if a[i] not in l:\n l.append(a[i])\n s = ''.join(l)\n return s", "def removeduplicates(st):\n d = {}\n s = ''\n for i in st:\n if i not in d:\n s += i\n d[i] = 1\n return s", "def removeduplicates(str):\n s = ''\n str = list(str)\n l = []\n for i in str:\n if i in l:\n continue\n else:\n l.append(i)\n for i in l:\n s += i\n return s", "def removeduplicates(str):\n s = ''\n length = len(str)\n for i in range(length):\n c = str[i]\n if c not in s:\n s += c\n return s", "def removeduplicates(str):\n result = []\n sample = ''\n for i in str:\n if i not in result:\n result.append(i)\n for i in result:\n sample += i\n return sample", "def removeduplicates(str):\n hsh = set()\n T = ''\n for ch in str:\n if ch in hsh:\n continue\n else:\n T += ch\n hsh.add(ch)\n return T", "def removeduplicates(str):\n d = {}\n res = ''\n for char in str:\n d[char] = d.get(char, 0) + 1\n if d[char] == 1:\n res += char\n return res", "def removeduplicates(str):\n l = list(str)\n dup = []\n s = ''\n for i in l:\n if i not in dup:\n dup.append(i)\n for j in dup:\n return s.join(dup)", "def removeduplicates(str):\n res = ''\n myDict = {}\n for i in str:\n if i not in myDict:\n res += i\n myDict[i] = 1\n return res", "def removeduplicates(str):\n s = list(str)\n look = {}\n p = ''\n for i in s:\n if i not in look:\n p += i\n look[i] = 1\n return p", "def removeduplicates(str):\n l = []\n for i in str:\n if i not in l:\n l.append(i)\n else:\n continue\n a = ''.join(l)\n return a", "def removeduplicates(str):\n l = []\n for i in str:\n if i in l:\n pass\n else:\n l.append(i)\n joint = ''.join(l)\n return joint", "def removeduplicates(str):\n look_up = {}\n result = ''\n for i in str:\n if i not in look_up.keys():\n result = result + i\n look_up[i] = 1\n return result"], "starter_code": "def removeduplicates(str):\n", "input_output": {"inputs": ["Str = geeksforgeeks", "Str = HappyNewYear"], "outputs": ["geksfor", "HapyNewYr"]}, "difficulty": "EASY", "raw_tags": ["Strings", "Arrays", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/remove-all-duplicates-from-a-given-string4321/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "removeduplicates", "task_id": "TACO_lite/40", "example": [[], []]} +{"requirement": "You just got done with your set at the gym, and you are wondering how much weight you could lift if you did a single repetition. Thankfully, a few scholars have devised formulas for this purpose (from [Wikipedia](https://en.wikipedia.org/wiki/One-repetition_maximum)) :\n\n\n### Epley\n\n\n### McGlothin\n\n\n### Lombardi\n\n\nYour function will receive a weight `w` and a number of repetitions `r` and must return your projected one repetition maximum. Since you are not sure which formula to use and you are feeling confident, your function will return the largest value from the three formulas shown above, rounded to the nearest integer. However, if the number of repetitions passed in is `1` (i.e., it is already a one rep max), your function must return `w`. Also, if the number of repetitions passed in is `0` (i.e., no repetitions were completed), your function must return `0`.", "solutions": ["def calculate_1rm(w, r):\n if r == 0:\n return 0\n if r == 1:\n return w\n return round(max([w * (1 + r / 30), 100 * w / (101.3 - 2.67123 * r), w * r ** 0.1]))", "epley = lambda w, r: w * (1 + r / 30)\nmcGlothin = lambda w, r: 100 * w / (101.3 - 2.67123 * r)\nlombardi = lambda w, r: w * r ** 0.1\n\ndef calculate_1rm(w, r):\n return r and (w if r == 1 else round(max(epley(w, r), mcGlothin(w, r), lombardi(w, r))))", "calculate_1rm = lambda w, r: [[round(max(w * (1 + r / 30), 100 * w / (101.3 - 2.67123 * r), w * r ** 0.1)), 0][r == 0], w][r == 1]", "ORM = [('Epley', lambda w, r: w * (1 + r / 30)), ('McGlothin', lambda w, r: 100 * w / (101.3 - 2.67123 * r)), ('Lombardi', lambda w, r: w * r ** 0.1)]\n\ndef calculate_1rm(w, r):\n if r == 0:\n return 0\n elif r == 1:\n return w\n else:\n return round(max((func(w, r) for (_, func) in ORM)))", "def calculate_1rm(w, r):\n if r in (0, 1):\n return (0, w)[r]\n epley = w * (1 + r / 30)\n mcg = 100 * w / (101.3 - 2.67123 * r)\n lomb = w * r ** 0.1\n return round(max((epley, mcg, lomb)))"], "starter_code": "def calculate_1rm(w, r):\n", "input_output": {"fn_name": "calculate_1RM", "inputs": [[135, 20], [200, 8], [270, 2], [360, 1], [400, 0]], "outputs": [[282], [253], [289], [360], [0]]}, "difficulty": "EASY", "raw_tags": ["Mathematics"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/595bbea8a930ac0b91000130", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "calculate_1rm", "task_id": "TACO_lite/50", "example": [[[100, 10], [200, 1], [150, 0]], ["133", "200", "0"]]} +{"requirement": "You are given an integer array nums that may contain duplicates. Your task is to return all possible subsets. Return only unique subsets and they can be in any order.\nExample: \nInput: \nnums = [1,2,2] \nOutput: \n[[],[1],[1,2],[1,2,2],[2],[2,2]]\nExplanation: \nWe can have subsets ranging from length 0 to 3. which are listed above. Also the subset [1,2] appears twice but is printed only once as we require only unique subsets.\nYour Task:\nComplete the function vector> printUniqueSubset(), which takes a vector nums and return a vector of vector consisting of all unique subsets.\nExpected Time Complexity: O(K2^{N}).\nExpected Auxiliary Space: O(K2^{N}).\nConstraints:\n1 <= nums.length <= 10\n-10 <= nums[i] <= 10", "solutions": ["def printuniquesubset(nums):\n n = len(nums)\n nums.sort()\n ans = []\n\n def solve(i, temp):\n ans.append(temp[:])\n for j in range(i, n):\n if j > i and nums[j] == nums[j - 1]:\n continue\n temp.append(nums[j])\n solve(j + 1, temp)\n temp.pop()\n solve(0, [])\n return ans", "def subset2(arr, n, ans, ind, subs):\n if ind == n:\n return\n subs.append(arr[ind])\n ans.append(subs[:])\n subset2(arr, n, ans, ind + 1, subs)\n subs.pop()\n for i in range(ind + 1, n):\n if arr[i] == arr[i - 1]:\n continue\n subs.append(arr[i])\n ans.append(subs[:])\n subset2(arr, n, ans, i + 1, subs)\n subs.pop()\n\ndef printuniquesubset(nums):\n nums.sort()\n n = len(nums)\n ans = []\n subs = []\n ans.append(subs)\n i = 0\n subset2(nums, n, ans, i, subs)\n return ans", "def solve(k, nums, curr):\n if k == len(nums):\n self.ans.add(tuple(curr))\n return\n self.solve(k + 1, nums, curr)\n curr.append(nums[k])\n self.solve(k + 1, nums, curr)\n curr.pop()\n\ndef printuniquesubset(nums):\n nums.sort()\n self.ans = set()\n curr = []\n self.solve(0, nums, curr)\n return sorted(list(self.ans))", "def subsets(arr, index, seq):\n if index == len(arr):\n self.res.append(seq)\n return\n copyindex = index\n while index < len(arr) - 1 and arr[index] == arr[index + 1]:\n index += 1\n self.subsets(arr, index + 1, seq)\n self.subsets(arr, copyindex + 1, seq + [arr[copyindex]])\n\ndef printuniquesubset(nums):\n nums.sort()\n self.res = []\n self.subsets(nums, 0, [])\n return sorted(self.res)", "def printuniquesubset(nums):\n\n def subdup(ind, nums, ans, s):\n ans.append(s[:])\n for i in range(ind, len(nums)):\n if i > ind and nums[i] == nums[i - 1]:\n continue\n s.append(nums[i])\n subdup(i + 1, nums, ans, s)\n s.pop()\n return\n ans = []\n s = []\n nums.sort()\n subdup(0, nums, ans, s)\n return ans", "def printuniquesubset(nums):\n ans = []\n ds = []\n\n def findSubsets(ind: int):\n ans.append(ds[:])\n for i in range(ind, len(nums)):\n if i != ind and nums[i] == nums[i - 1]:\n continue\n ds.append(nums[i])\n findSubsets(i + 1)\n ds.pop()\n nums.sort()\n findSubsets(0)\n return ans", "def printuniquesubset(nums):\n res = []\n nums.sort()\n\n def backtrack(i, subset):\n if i == len(nums):\n res.append(subset[:])\n return\n subset.append(nums[i])\n backtrack(i + 1, subset)\n subset.pop()\n while i + 1 < len(nums) and nums[i] == nums[i + 1]:\n i += 1\n backtrack(i + 1, subset)\n backtrack(0, [])\n res.sort()\n return res", "def gen(nums, n, arr, brr, pos):\n if pos == n:\n crr = brr.copy()\n arr.add(tuple(sorted(crr)))\n return\n brr.append(nums[pos])\n self.gen(nums, n, arr, brr, pos + 1)\n brr.pop()\n self.gen(nums, n, arr, brr, pos + 1)\n\ndef printuniquesubset(nums):\n arr = set()\n brr = []\n self.gen(nums, len(nums), arr, brr, 0)\n return sorted(list(arr))", "def printuniquesubset(nums):\n (lst, tmp) = ([], [])\n dic = {}\n\n def subs(idx, nums, n, tmp, lst):\n if idx >= n:\n if str(tmp) not in dic:\n dic[str(tmp)] = 1\n lst.append(tmp[:])\n return\n tmp.append(nums[idx])\n subs(idx + 1, nums, n, tmp, lst)\n tmp.pop()\n subs(idx + 1, nums, n, tmp, lst)\n nums.sort()\n subs(0, nums, len(nums), tmp, lst)\n return sorted(lst)", "def printuniquesubset(nums):\n ans = []\n m = len(nums)\n nums.sort()\n\n def recursion(idx, ds):\n ans.append(ds.copy())\n for i in range(idx, m):\n if i > idx and nums[i] == nums[i - 1]:\n continue\n ds.append(nums[i])\n recursion(i + 1, ds)\n ds.remove(nums[i])\n recursion(0, [])\n return ans", "def solve(i, nums, lst, ans):\n if i == n:\n ans.add(tuple(lst))\n return\n lst.append(nums[i])\n self.solve(i + 1, nums, lst, ans)\n lst.pop()\n self.solve(i + 1, nums, lst, ans)\n\ndef printuniquesubset(nums):\n nums.sort()\n ans = set()\n lst = []\n i = 0\n self.solve(i, nums, lst, ans)\n return sorted(ans)"], "starter_code": "def printuniquesubset(nums):\n", "input_output": {"inputs": ["nums = [1,2,2]"], "outputs": ["[[],[1],[1,2],[1,2,2],[2],[2,2]]"]}, "difficulty": "MEDIUM", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/subset-sum-ii/1", "Expected Auxiliary Space": "O(K2^{N}).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(K2^{N}).", "entry_point": "printuniquesubset", "task_id": "TACO_lite/38", "example": [[[[1, 2, 2]]], ["[[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]"]]} +{"requirement": "Given a number s(in string form). Find the Smallest number (Not leading Zeros) which can be obtained by rearranging the digits of given number.\n \nExample 1:\nInput: s = \"846903\"\nOutput: 304689\nExplanation: 304689 is the smallest number\nby rearranging the digits.\nExample 2:\nInput: s = \"55010\"\nOutput: 10055\nExplanation: 10055 is the smallest number \nby rearranging the digts.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function minimum_number() which takes the number as input parameter and returns the smallest number than can be formed without leading zeros by rearranging the digits of the number.\n \nExpected Time Complexity: O(N * log(N)) where N is the number of digits of the given number\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= N <= 10^{5}", "solutions": ["def minimum_number(s):\n l = list(s)\n l.sort()\n for i in range(len(l)):\n if int(l[i]) > 0:\n (l[0], l[i]) = (l[i], l[0])\n break\n n = ''\n for i in l:\n n += i\n return n", "def minimum_number(s):\n d = {}\n for i in s:\n i = int(i)\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n t = list(d.keys())\n t.sort()\n if len(t) == 1:\n return str(t[0]) * d[t[0]]\n res = str(t[1] * 10 + t[0])\n (d[t[0]], d[t[1]]) = (d[t[0]] - 1, d[t[1]] - 1)\n for i in t:\n res += str(i) * d[int(i)]\n return res", "def minimum_number(s):\n sort = sorted(s)\n s = ''\n i = 0\n while sort[i] == '0' and i < len(sort) - 1:\n i += 1\n if i == len(sort):\n for ele in sort:\n s += ele\n temp = sort[0]\n sort[0] = sort[i]\n sort[i] = temp\n for ele in sort:\n s += ele\n return s", "def minimum_number(s):\n arr = []\n new = []\n s = list(s)\n for i in s:\n if int(i) == 0:\n new.append(int(i))\n else:\n arr.append(int(i))\n if len(new) == len(s):\n return ''.join(s)\n arr.sort()\n new1 = [arr.pop(0)]\n new1.extend(new)\n new1.extend(arr)\n ans = ''\n for i in new1:\n ans += str(i)\n ans = int(ans)\n return ans", "def minimum_number(s):\n j = sorted(s)\n p = ''\n if j[0] != '0':\n return p.join(j)\n else:\n for i in range(len(j)):\n if j[i] != '0':\n temp = j[0]\n j[0] = j[i]\n j[i] = temp\n break\n return p.join(j)", "def minimum_number(s):\n m = sorted(s)\n for i in range(len(m)):\n if int(m[i]) > 0:\n (m[0], m[i]) = (m[i], m[0])\n break\n sr = ''\n for i in m:\n sr += i\n return sr", "def minimum_number(s):\n lst = list(s)\n lst.sort()\n tmp = ''\n for (i, n) in enumerate(lst):\n if n != '0':\n tmp = lst.pop(i)\n break\n return str(tmp) + ''.join(lst)", "def minimum_number(s):\n l = list(s)\n l.sort()\n tmp = ''\n for (i, ele) in enumerate(l):\n if ele != '0':\n tmp = str(l.pop(i))\n break\n return str(tmp) + ''.join(l)", "def minimum_number(s):\n n = len(s)\n lst = list(map(int, s))\n lst.sort()\n for i in range(n):\n if lst[i] != 0:\n (lst[0], lst[i]) = (lst[i], lst[0])\n break\n ans = ''\n for i in lst:\n ans += str(i)\n return ans", "import functools\n\ndef minimum_number(s):\n c = 0\n arr = []\n for i in s:\n if i != 0:\n arr.append(i)\n if i == '0':\n c += 1\n if c == len(s):\n return s\n\n def fuc(a, b):\n if a + b > b + a:\n return 1\n else:\n return -1\n arr.sort()\n news = str(int(''.join(arr)))\n if c == 0:\n return news\n else:\n return news[0] + '0' * c + news[1:]", "def minimum_number(s):\n num = sorted(s)\n t = 0\n for i in num:\n if i == '0':\n t += 1\n else:\n break\n num = num[t:]\n if len(num) > 0:\n x = num[0]\n else:\n return '0' * t\n num = ['0'] * t + num[1:]\n num.insert(0, x)\n return ''.join(num)", "def minimum_number(s):\n g = s.count('0')\n l = s.replace('0', '')\n if len(l) == 0:\n return s\n l = sorted(l)\n l.sort()\n h = [l[0]]\n for i in range(g):\n h.append('0')\n for i in range(1, len(l)):\n h.append(l[i])\n return ''.join(h)", "def minimum_number(s):\n x = [i for i in s]\n x.sort()\n c = 0\n for i in range(len(x)):\n if x[i] != '0':\n c = i\n break\n (x[0], x[c]) = (x[c], x[0])\n return ''.join(x)", "def minimum_number(s):\n snum = sorted(list(s))\n czero = snum.count('0')\n if czero == len(snum):\n return s\n snum[0] = snum[czero]\n snum[czero] = '0'\n return ''.join(snum)", "def minimum_number(s):\n lst = []\n for c in s:\n lst.append(c)\n lst.sort()\n n = len(lst)\n i = 0\n while i < n and lst[i] == '0':\n i += 1\n if i == n:\n return int(''.join(lst))\n else:\n (lst[0], lst[i]) = (lst[i], lst[0])\n return int(''.join(lst))", "def minimum_number(s):\n arr = list(s)\n arr.sort()\n for i in range(len(arr)):\n if arr[i] != '0':\n temp = arr[i]\n arr.pop(i)\n break\n if len(arr) == len(s):\n return s\n else:\n return temp + ''.join(arr)", "def minimum_number(s):\n res = [int(x) for x in str(s)]\n mo = ''\n res.sort()\n if res[len(res) - 2] == 0:\n res.sort(reverse=True)\n for s in res:\n mo = mo + str(s)\n return int(mo)\n if res[0] == 0:\n for i in range(len(res) - 1):\n if res[i] > 0:\n res[0] = res[i]\n res[i] = 0\n break\n for s in res:\n mo = mo + str(s)\n return int(mo)", "def minimum_number(s):\n s = list(s)\n s.sort()\n ind = 0\n leng = len(s)\n while ind < leng and s[ind] == '0':\n ind += 1\n if ind == leng:\n return int(''.join(s))\n p = s.pop(ind)\n s.insert(0, p)\n return int(''.join(s))", "def minimum_number(s):\n dic = {}\n for el in range(10):\n dic[str(el)] = 0\n if s[0] != '-':\n for el in s:\n dic[el] += 1\n newS = ''\n for el in range(1, 10):\n newS += str(el) * dic[str(el)]\n if dic['0'] != 0 and len(newS) > 0:\n newS = newS[0] + '0' * dic['0'] + newS[1:]\n elif dic['0'] != 0 and len(newS) == 0:\n newS += '0' * dic['0']\n return newS\n else:\n for el in s[1:]:\n dic[el] += 1\n newS = ''\n for el in range(9, -1, -1):\n newS += str(el) * dic[str(el)]\n newS = '-' + newS\n return newS", "def minimum_number(s):\n s = sorted(s)\n if s[-1] == '0':\n return ''.join(s)\n i = 0\n while s[i] == '0':\n i += 1\n (s[i], s[0]) = (s[0], s[i])\n return ''.join(s)", "def minimum_number(s):\n n = len(s)\n s = list(s)\n s = sorted(s)\n i = 0\n while i < n - 1 and s[i] == '0':\n i += 1\n if i == 0:\n return ''.join(s)\n else:\n (s[0], s[i]) = (s[i], s[0])\n return ''.join(s)", "def minimum_number(s):\n lst = list(s)\n num = sorted(lst)\n num = ''.join(num)\n num = list(num)\n for i in range(len(num)):\n if num[i] == '0':\n continue\n (num[i], num[0]) = (num[0], num[i])\n return ''.join(num)\n return ''.join(num)", "def minimum_number(n):\n arr = sorted([int(i) for i in list(str(n))])\n zcount = arr.count(0)\n if zcount == 0:\n return int(''.join(arr))\n elif zcount == len(arr):\n return 0\n else:\n s = str(arr[zcount])\n for _ in range(zcount):\n s += '0'\n for i in arr[zcount + 1:]:\n s += str(i)\n return int(s)", "import heapq\n\ndef minimum_number(s):\n s = list(s)\n s.sort()\n s.append('-1')\n i = 0\n while s[i] == '0':\n i += 1\n if i == len(s) - 1:\n return 0\n s.pop()\n (s[0], s[i]) = (s[i], s[0])\n return ''.join(s)", "def minimum_number(s):\n n = len(s)\n ls = list(s)\n ls.sort()\n i = 0\n while i < n and ls[i] == '0':\n i += 1\n if i < n:\n (ls[0], ls[i]) = (ls[i], ls[0])\n return ''.join(ls)"], "starter_code": "def minimum_number(s):\n", "input_output": {"inputs": ["s = \"846903\"", "s = \"55010\""], "outputs": ["304689", "10055"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/smallest-number-by-rearranging-digits-of-a-given-number0820/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N * log(N)) where N is the number of digits of the given number", "entry_point": "minimum_number", "task_id": "TACO_lite/0", "example": [[["846903"], ["55010"]], ["304689", "10055"]]} +{"requirement": "Geek wants to know the traversals required to construct a unique binary tree. Given a pair of traversal, return true if it is possible to construct unique binary tree from the given traversals otherwise return false.\nEach traversal is represented with an integer: preorder - 1, inorder - 2, postorder - 3. \nExample 1:\nInput:\na = 1, b=2\nOutput: 1\nExplanation: We can construct binary tree using inorder traversal and preorder traversal. \nExample 2:\nInput: a = 1, b=3\nOutput: 0 \nExplanation: We cannot construct binary tree using preorder traversal and postorder traversal. \nConstraints:\n1 <= a,b <=3\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function isPossible() which takes a and b as input parameters and returns true or false.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)", "solutions": ["def ispossible(a, b):\n return 1 if (a == 2 or b == 2) and (not (a == 2 and b == 2)) else 0", "def ispossible(a, b):\n if a == b:\n return False\n if a == 2 or b == 2:\n return True\n return False", "def ispossible(a, b):\n if a == 2:\n return b == 1 or b == 3\n elif b == 2:\n return True\n return False", "def ispossible(a, b):\n if (a == 1 or a == 3) and b == 2:\n return 1\n elif a == 2 and (b == 1 or b == 3):\n return 1\n return 0", "def ispossible(a, b):\n traversal = [a, b]\n if 2 in traversal and (1 in traversal or 3 in traversal):\n return True\n return False", "def ispossible(a, b):\n return True if (a + b) % 2 != 0 else False", "def ispossible(a, b):\n if a == 1 and b == 3:\n return False\n elif a == 3 and b == 1:\n return False\n elif a == b:\n return False\n else:\n return True", "def ispossible(a, b):\n if a == 1 and b == 3 or (a == 3 and b == 1) or a == b:\n return False\n return True", "def ispossible(a, b):\n if a != 2 and b != 2:\n return False\n elif a == b:\n return False\n return True", "def ispossible(a, b):\n if a != b:\n l = [a, b]\n if 2 in l:\n return True\n return False"], "starter_code": "def ispossible(a, b):\n", "input_output": {"inputs": ["a = 1, b=2", "a = 1, b=3"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Traversal"], "name": null, "source": "geeksforgeeks", "tags": ["Graph traversal"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/unique-binary-tree-requirements/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "ispossible", "task_id": "TACO_lite/60", "example": [[[1, 2], [1, 3]], ["1", "0"]]} +{"requirement": "Every Friday and Saturday night, farmer counts amount of sheep returned back to his farm (sheep returned on Friday stay and don't leave for a weekend).\n\nSheep return in groups each of the days -> you will be given two arrays with these numbers (one for Friday and one for Saturday night). Entries are always positive ints, higher than zero.\n\nFarmer knows the total amount of sheep, this is a third parameter. You need to return the amount of sheep lost (not returned to the farm) after final sheep counting on Saturday.\n\nExample 1: Input: {1, 2}, {3, 4}, 15 --> Output: 5\n\nExample 2: Input: {3, 1, 2}, {4, 5}, 21 --> Output: 6\n\nGood luck! :-)", "solutions": ["def lostsheep(friday, saturday, total):\n return total - sum(friday + saturday)", "def lostsheep(friday, saturday, total):\n fritag = 0\n for number in friday:\n fritag = fritag + number\n samstag = 0\n for number in saturday:\n samstag = samstag + number\n return int(str(total)) - (fritag + samstag)", "def lostsheep(friday, saturday, total):\n sheep = 0\n for num in friday:\n sheep += num\n for num in saturday:\n sheep += num\n return total - sheep", "def lostsheep(friday, saturday, total):\n sheeps = 0\n for i in range(len(friday)):\n sheeps += friday[i]\n for i in range(len(saturday)):\n sheeps += saturday[i]\n return total - sheeps", "def lostsheep(friday, saturday, total):\n weekend_total = sum(friday) + sum(saturday)\n difference = total - weekend_total\n return difference"], "starter_code": "def lostsheep(friday,saturday,total):\n", "input_output": {"fn_name": "lostSheep", "inputs": [[[1, 2], [3, 4], 15], [[3, 1, 2], [4, 5], 21], [[5, 1, 4], [5, 4], 29], [[11, 23, 3, 4, 15], [7, 14, 9, 21, 15], 300], [[2, 7, 13, 17], [23, 56, 44, 12, 1, 2, 1], 255], [[2, 5, 8], [11, 23, 3, 4, 15, 112, 12, 4], 355], [[1, 1, 1, 2, 1, 2], [2, 1, 2, 1, 2, 1], 30], [[5, 10, 15], [11, 23, 3, 4, 15], 89], [[3, 6, 9, 12], [3, 2, 1, 2, 3, 1], 44]], "outputs": [[5], [6], [10], [178], [77], [156], [13], [3], [2]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Fundamentals", "Algebra"], "name": null, "source": "codewars", "tags": ["Matrices", "Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/58e0f0bf92d04ccf0a000010", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "lostsheep", "task_id": "TACO_lite/68", "example": [[[1, 2, 15], [3, 1, 2, 4, 5, 21]], ["5", "6"]]} +{"requirement": "Given a string S which only contains lowercase alphabets. Find the length of the longest substring of S such that the characters in it can be rearranged to form a palindrome. \nExample 1:\nInput:\nS = \"aabe\"\nOutput:\n3\nExplanation:\nThe substring \"aab\" can be rearranged to\n\"aba\" which is the longest palindrome\npossible for this String.\nExample 2:\nInput:\nS = \"adbabd\"\nOutput:\n6\nExplanation:\nThe whole string “adbabd” can be\nrearranged to form a palindromic substring.\nOne possible arrangement is \"abddba\".\nThus, output length of the string is 6. \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function longestSubstring() which takes a String S as input and returns the length of largest possible Palindrome.\nExpected Time Complexity: O(|S|*26)\nExpected Auxiliary Space: O(|S|*26)\nConstraints:\n1 ≤ |S| ≤ 10^{5}", "solutions": ["def longestsubstring(s):\n ans = 1\n l = len(s)\n f = {0: -1}\n x = 0\n for i in range(l):\n z = ord(s[i]) - 97\n x = x ^ 1 << z\n if x in f:\n ans = max(ans, i - f[x])\n for j in range(26):\n t = x ^ 1 << j\n if t in f:\n ans = max(ans, i - f[t])\n if x not in f:\n f[x] = i\n return ans", "def longestsubstring(s):\n d = {}\n d[0] = -1\n x = ans = 0\n for i in range(len(s)):\n x = x ^ 1 << ord(s[i]) - ord('a')\n if x in d:\n ans = max(ans, i - d[x])\n else:\n d[x] = i\n for j in range(0, 26):\n m = x ^ 1 << j\n if m in d:\n ans = max(ans, i - d[m])\n return ans", "def longestsubstring(s):\n n = len(s)\n idx = {}\n ans = 0\n mask = 0\n idx[mask] = -1\n for i in range(n):\n temp = ord(s[i]) - 97\n mask ^= 1 << temp\n if mask in idx.keys():\n ans = max(ans, i - idx[mask])\n else:\n idx[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in idx.keys():\n if ans < i - idx[mask2]:\n ans = i - idx[mask2]\n return ans", "def longestsubstring(S):\n n = len(S)\n index = dict()\n answer = 0\n mask = 0\n index[mask] = -1\n for i in range(n):\n temp = ord(S[i]) - 97\n mask ^= 1 << temp\n if mask in index.keys():\n answer = max(answer, i - index[mask])\n else:\n index[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in index.keys():\n answer = max(answer, i - index[mask2])\n return answer", "def longestsubstring(s):\n ind = dict()\n ans = 0\n mask = 0\n ind[mask] = -1\n for i in range(len(s)):\n temp = ord(s[i]) - 97\n mask ^= 1 << temp\n if mask in ind:\n ans = max(ans, i - ind[mask])\n else:\n ind[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in ind:\n ans = max(ans, i - ind[mask2])\n return ans", "def longestsubstring(s):\n n = len(s)\n masks = {0: -1}\n\n def check(mask1, idx):\n res = 0\n if mask1 in masks:\n res = max(res, idx - masks[mask1])\n for i in range(26):\n mask2 = mask1 ^ 1 << i\n if mask2 in masks:\n res = max(res, idx - masks[mask2])\n return res\n (mask, ans) = (0, 0)\n for (i, c) in enumerate(s):\n mask ^= 1 << ord(c) - ord('a')\n ans = max(ans, check(mask, i))\n if mask not in masks:\n masks[mask] = i\n return ans", "def longestsubstring(S):\n length = 0\n mask = 0\n bitMap = {}\n bitMap[mask] = -1\n for i in range(len(S)):\n index = ord(S[i]) - 97\n mask = mask ^ 1 << index\n if mask in bitMap:\n length = max(length, i - bitMap[mask])\n else:\n bitMap[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in bitMap:\n length = max(length, i - bitMap[mask2])\n return length", "import collections\n\ndef longestsubstring(S):\n if not S:\n return\n ans = 1\n l = len(S)\n mp = {0: -1}\n x = 0\n for i in range(l):\n z = ord(S[i]) - ord('a')\n x = x ^ 1 << z\n if x in mp:\n ans = max(ans, i - mp[x])\n for j in range(26):\n t = x ^ 1 << j\n if t in mp:\n ans = max(ans, i - mp[t])\n if x not in mp:\n mp[x] = i\n return ans", "def is_palin(mapper, n):\n odd = 0\n for i in mapper.values():\n if i & 1:\n odd += 1\n if odd == 0:\n return True\n elif n & 1 and odd == 1:\n return True\n else:\n return False\n\ndef front(mapper, s, n):\n for i in range(n):\n mapper[s[i]] -= 1\n if self.is_palin(mapper, n - i - 1):\n return n - i - 1\n return 1\n\ndef ending(mapper, s, n):\n for i in range(n - 1, -1, -1):\n mapper[s[i]] -= 1\n if self.is_palin(mapper, i):\n return i\n return 1\n\ndef both_side(mapper, s, n):\n i = 0\n j = n - 1\n while i < j:\n mapper[s[i]] -= 1\n mapper[s[j]] -= 1\n n -= 2\n if self.is_palin(mapper, n):\n return n\n i += 1\n j -= 1\n return 1\n\ndef longestsubstring(s):\n n = len(s)\n mapper = dict()\n ans = 1\n l = len(s)\n f = {0: -1}\n x = 0\n for i in range(l):\n z = ord(s[i]) - 97\n x = x ^ 1 << z\n if x in f:\n ans = max(ans, i - f[x])\n for j in range(26):\n t = x ^ 1 << j\n if t in f:\n ans = max(ans, i - f[t])\n if x not in f:\n f[x] = i\n return ans\n maxi = -1000000000.0\n for i in range(n):\n mapper = dict()\n for j in range(i, n):\n mapper[s[j]] = 1 + mapper.get(s[j], 0)\n if self.is_palin(mapper, j - i + 1):\n maxi = max(maxi, j - i + 1)\n return maxi", "def longestsubstring(S):\n n = len(S)\n max_len = 0\n mp = {}\n mask = 0\n mp[mask] = -1\n for i in range(n):\n idx = ord(S[i]) - ord('a')\n mask = mask ^ 1 << idx\n if mask in mp:\n length = i - mp[mask]\n max_len = max(max_len, length)\n else:\n mp[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in mp:\n length = i - mp[mask2]\n max_len = max(max_len, length)\n return max_len", "def longestsubstring(S):\n dictt = {}\n dictt[0] = -1\n x = output = 0\n n = len(S)\n for i in range(n):\n x = x ^ 1 << ord(S[i]) - ord('a')\n if x in dictt:\n output = max(output, i - dictt[x])\n else:\n dictt[x] = i\n for j in range(0, 26):\n m = x ^ 1 << j\n if m in dictt:\n output = max(output, i - dictt[m])\n return output", "def longestsubstring(s):\n n = len(s)\n mp = dict()\n pr = 0\n sh = 0\n mp[sh] = -1\n for i in range(n):\n mrc = ord(s[i]) - 97\n sh ^= 1 << mrc\n if sh in mp.keys():\n pr = max(pr, i - mp[sh])\n else:\n mp[sh] = i\n for j in range(26):\n rs = sh ^ 1 << j\n if rs in mp.keys():\n pr = max(pr, i - mp[rs])\n return pr", "from itertools import permutations\n\ndef longestsubstring(S):\n ind = dict()\n ans = 0\n mas = 0\n ind[mas] = -1\n for i in range(len(S)):\n temp = ord(S[i]) - 97\n mas ^= 1 << temp\n if mas in ind.keys():\n ans = max(ans, i - ind[mas])\n else:\n ind[mas] = i\n for j in range(26):\n mask = mas ^ 1 << j\n if mask in ind.keys():\n ans = max(ans, i - ind[mask])\n return ans", "def longestsubstring(S):\n mask = 0\n mp = {}\n mp[0] = -1\n ans = 0\n for i in range(len(S)):\n o = ord(S[i]) - ord('a')\n mask ^= 1 << o\n if mask in mp:\n ans = max(ans, i - mp[mask])\n for j in range(26):\n nm = mask ^ 1 << j\n if nm in mp:\n ans = max(ans, i - mp[nm])\n if mask not in mp:\n mp[mask] = i\n return ans", "def longestsubstring(S):\n n = len(S)\n hash_map = {}\n mask = 0\n ans = 0\n hash_map[mask] = -1\n for i in range(n):\n tmp = ord(S[i]) - 97\n mask = mask ^ 1 << tmp\n if mask in hash_map.keys():\n ans = max(ans, i - hash_map[mask])\n else:\n hash_map[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in hash_map.keys():\n ans = max(ans, i - hash_map[mask2])\n return ans", "def longestsubstring(S):\n bit_mask = 0\n index_map = {}\n max_length = 0\n index_map[bit_mask] = -1\n for i in range(len(S)):\n c = ord(S[i]) - 97\n bit_mask ^= 1 << c\n if bit_mask in index_map:\n max_length = max(max_length, i - index_map[bit_mask])\n else:\n index_map[bit_mask] = i\n for j in range(26):\n bit_mask_2 = bit_mask ^ 1 << j\n if bit_mask_2 in index_map:\n max_length = max(max_length, i - index_map[bit_mask_2])\n return max_length", "def longestsubstring(S):\n index = dict()\n ans = 0\n m = 0\n index[m] = -1\n for i in range(len(S)):\n temp = ord(S[i]) - 97\n m = m ^ 1 << temp\n if m in index.keys():\n ans = max(ans, i - index[m])\n else:\n index[m] = i\n for j in range(26):\n mask2 = m ^ 1 << j\n if mask2 in index.keys():\n ans = max(ans, i - index[mask2])\n return ans", "def longestsubstring(S):\n n = len(S)\n m1 = 0\n m2 = 0\n ans = 0\n map = {0: -1}\n for i in range(n):\n idx = ord(S[i]) - ord('a')\n m1 = m1 ^ 1 << idx\n if m1 in map:\n ans = max(ans, i - map[m1])\n else:\n map[m1] = i\n for j in range(26):\n m2 = m1 ^ 1 << j\n if m2 in map:\n ans = max(ans, i - map[m2])\n return ans", "def longestsubstring(S):\n index = {0: -1}\n (mask, ans) = (0, 0)\n for i in range(len(S)):\n idx = ord(S[i]) - ord('a')\n mask ^= 1 << idx\n if mask in index:\n ans = max(ans, i - index[mask])\n else:\n index[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in index:\n ans = max(ans, i - index[mask2])\n return ans", "def longestsubstring(S):\n Dict = {0: -1}\n res = 0\n x = 0\n N = len(S)\n for i in range(N):\n num = ord(S[i]) - ord('a')\n x = x ^ 1 << num\n if x not in Dict:\n Dict[x] = i\n else:\n idx = Dict[x]\n res = max(res, i - Dict[x])\n for j in range(26):\n m = x ^ 1 << j\n if m in Dict:\n res = max(res, i - Dict[m])\n return res", "def longestsubstring(S):\n n = len(S)\n max_len = 0\n mask = 0\n pos_dict = {}\n pos_dict[0] = -1\n for i in range(n):\n bit_pos = ord(S[i]) - ord('a')\n mask = mask ^ 1 << bit_pos\n if mask in pos_dict:\n max_len = max(max_len, i - pos_dict[mask])\n else:\n pos_dict[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in pos_dict:\n max_len = max(max_len, i - pos_dict[mask2])\n return max_len", "def longestsubstring(S):\n d = {}\n mask = 0\n d[mask] = -1\n res = 0\n for i in range(len(S)):\n ind = ord(S[i]) - 97\n mask ^= 1 << ind\n if mask in d:\n res = max(res, i - d[mask])\n else:\n d[mask] = i\n for j in range(26):\n newmask = mask ^ 1 << j\n if newmask in d:\n res = max(res, i - d[newmask])\n return res", "def longestsubstring(s):\n l = 0\n mask = 0\n mp = {}\n mp[mask] = -1\n for i in range(len(s)):\n ind = ord(s[i]) - 97\n mask ^= 1 << ind\n if mask in mp:\n l = max(l, i - mp[mask])\n else:\n mp[mask] = i\n for j in range(0, 26):\n mask2 = mask ^ 1 << j\n if mask2 in mp:\n l = max(l, i - mp[mask2])\n return l", "def longestsubstring(s):\n d = {}\n d[0] = -1\n flag = 0\n res = 0\n for i in range(len(s)):\n flag = flag ^ 1 << ord(s[i]) - ord('a')\n if flag in d:\n res = max(res, i - d[flag])\n else:\n d[flag] = i\n for j in range(26):\n mx = flag ^ 1 << j\n if mx in d:\n res = max(res, i - d[mx])\n return res", "def longestsubstring(S):\n ans = 0\n temp = 0\n has = dict()\n has[0] = -1\n for i in range(len(S)):\n t = ord(S[i]) - ord('a')\n temp ^= 1 << t\n if temp in has.keys():\n ans = max(ans, i - has[temp])\n else:\n has[temp] = i\n for j in range(26):\n temp2 = temp ^ 1 << j\n if temp2 in has.keys():\n ans = max(ans, i - has[temp2])\n return ans", "def longestsubstring(S):\n d = {}\n d[0] = -1\n x = ans = 0\n for i in range(len(S)):\n x = x ^ 1 << ord(S[i]) - ord('a')\n if x in d:\n ans = max(ans, i - d[x])\n else:\n d[x] = i\n for j in range(0, 26):\n m = x ^ 1 << j\n if m in d:\n ans = max(ans, i - d[m])\n return ans\n\ndef permute(xs, low=0):\n if low + 1 >= len(xs):\n yield xs\n else:\n for p in self.permute(xs, low + 1):\n yield p\n for i in range(low + 1, len(xs)):\n (xs[low], xs[i]) = (xs[i], xs[low])\n for p in self.permute(xs, low + 1):\n yield p\n (xs[low], xs[i]) = (xs[i], xs[low])\n\ndef isPalindrom(S):\n return S == S[::-1]", "def longestsubstring(s):\n d = {}\n (k, res) = (0, 0)\n d[0] = -1\n for i in range(len(s)):\n k = k ^ 1 << ord(s[i]) - 97\n if k in d:\n res = max(res, i - d[k])\n else:\n d[k] = i\n for j in range(26):\n temp = k ^ 1 << j\n if temp in d:\n res = max(res, i - d[temp])\n return res", "def longestsubstring(S):\n data = {}\n data[0] = -1\n (temp, res) = (0, 0)\n for i in range(len(S)):\n temp = temp ^ 1 << ord(S[i]) - ord('a')\n if temp in data:\n res = max(res, i - data[temp])\n else:\n data[temp] = i\n for j in range(26):\n k = temp ^ 1 << j\n if k in data:\n res = max(res, i - data[k])\n return res", "def longestsubstring(S):\n mask = 0\n d = {0: -1}\n ans = 0\n for (i, c) in enumerate(S):\n bit = ord(c) - ord('a')\n mask ^= 1 << bit\n if mask in d:\n ans = max(ans, i - d[mask])\n for j in range(26):\n if mask ^ 1 << j in d:\n ans = max(ans, i - d[mask ^ 1 << j])\n if mask not in d:\n d[mask] = i\n return ans", "def palindrome(S):\n dict_ = {}\n for i in S:\n if i in dict_:\n dict_[i] += 1\n else:\n dict_[i] = 1\n max = 0\n for i in dict_:\n if dict_[i] % 2 != 0:\n max += 1\n if max > 1:\n return False\n return True\n\ndef longestsubstring(s):\n d = {}\n d[0] = -1\n x = ans = 0\n for i in range(len(s)):\n x = x ^ 1 << ord(s[i]) - ord('a')\n if x in d:\n ans = max(ans, i - d[x])\n else:\n d[x] = i\n for j in range(0, 26):\n m = x ^ 1 << j\n if m in d:\n ans = max(ans, i - d[m])\n return ans"], "starter_code": "def longestsubstring(S):\n", "input_output": {"inputs": ["S = \"aabe\"", "S = \"adbabd\""], "outputs": ["3", "6"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Algorithms", "Strings", "Data Structures", "Dynamic Programming", "palindrome"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/longest-substring-whose-character-rearranged-can-form-a-palindrome/1", "Expected Auxiliary Space": "O(|S|*26)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|*26)", "entry_point": "longestsubstring", "task_id": "TACO_lite/83", "example": [[["aabe"], ["adbabd"]], ["3", "6"]]} +{"requirement": "Given an array A[]of size N. Let us call difference between indices of an element's first and last appearance in the array A[] a gap. Find the maximum possible gap. Note that if any element appears only once, then the gap for that element is 0.\n \nExample 1:\nInput:\nN = 9\nA[] = {2, 1, 3, 4, 2, 1, 5, 1, 7}\nOutput:\n6\nExplanation:\nFor the above test case (Assuming 0-based indexing): \nNumber 1's first appearance is at index 1 and last appearance is at index 7. This implies gap is 7-1=6\nThis is the maximum possible in the given test case.\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function leftIndex() which takes the array A[] and its size N as inputs and returns the Maximum Difference.\n \nExpected Time Complexity: O(N. Log(N))\nExpected Auxiliary Space: O(N)\n \nConstraints:\n1<=N<=10^{5}\n-10^{5}<=A_{i}<=10^{5}", "solutions": ["import math\n\ndef maxdiffindex(A, N):\n maxi = -math.inf\n dicti = {}\n for i in range(N):\n if A[i] not in dicti:\n dicti[A[i]] = i\n else:\n maxi = max(maxi, i - dicti[A[i]])\n if maxi == -math.inf:\n return 0\n return maxi", "def maxdiffindex(A, N):\n diff = 0\n dict_ = {}\n for index in range(N):\n elem = A[index]\n ind = dict_.get(elem, -1)\n if ind == -1:\n dict_.update({elem: index})\n else:\n current_diff = index - dict_[elem]\n diff = index - dict_[elem] if diff < current_diff else diff\n return diff", "def maxdiffindex(A, N):\n d = {}\n id = 0\n for i in range(N):\n if A[i] not in d:\n d[A[i]] = i\n elif i - d[A[i]] > id:\n id = i - d[A[i]]\n return id", "def maxdiffindex(A, N):\n B = list(reversed(A))\n maxi = 0\n visited = set()\n i = -1\n while i + maxi < N - 1:\n i += 1\n if A[i] in visited:\n continue\n visited.add(A[i])\n diff = N - 1 - i - B.index(A[i])\n if diff > maxi:\n maxi = diff\n return maxi", "def maxdiffindex(A, N):\n maxi = 0\n rev = A[::-1]\n for i in list(set(A)):\n fir = A.index(i)\n las = rev.index(i)\n las = len(A) - las - 1\n maxi = max(maxi, las - fir)\n return maxi", "def maxdiffindex(A, N):\n d1 = {}\n d2 = {}\n for i in range(len(A)):\n if A[i] not in d1:\n d1[A[i]] = i\n for i in reversed(range(len(A))):\n if A[i] not in d2:\n d2[A[i]] = i\n maximum = -987654321\n for (k, v) in d1.items():\n maximum = max(maximum, d2[k] - v)\n return maximum", "def maxdiffindex(A, N):\n result = []\n dict = {}\n for i in range(N):\n dict[A[i]] = i\n for j in range(N):\n value = abs(dict[A[j]] - j)\n result.append(value)\n return max(result)", "def maxdiffindex(A, N):\n maxi = 0\n temp = {}\n for i in range(N):\n if A[i] not in temp:\n temp[A[i]] = i\n else:\n maxi = max(maxi, i - temp[A[i]])\n return maxi", "from collections import defaultdict\n\ndef maxdiffindex(A, N):\n di = defaultdict(list)\n ans = []\n for i in range(N):\n di[A[i]].append(i)\n values = di.values()\n for i in values:\n if len(i) == 1:\n continue\n else:\n ans.append(i[-1] - i[0])\n if len(ans) != 0:\n return max(ans)\n else:\n return 0", "def maxdiffindex(A, N):\n m = {}\n for i in range(len(A)):\n m[A[i]] = i\n A = A[::-1]\n d = {}\n for j in range(len(A)):\n d[A[j]] = N - j - 1\n r = sorted(m.items())\n r = dict(r)\n e = sorted(d.items())\n e = dict(e)\n u = []\n v = []\n for (x, y) in r.items():\n u.append(y)\n for (x, y) in e.items():\n v.append(y)\n h = []\n for k in range(len(u)):\n h.append(abs(u[k] - v[k]))\n return max(h)", "def maxdiffindex(A, N):\n first = {}\n last = {}\n max_diff = -123456789\n for i in range(N):\n if A[i] not in first:\n first[A[i]] = i\n if A[i] not in last:\n last[A[i]] = i\n else:\n last[A[i]] = i\n for key in first:\n diff = last[key] - first[key]\n max_diff = max(max_diff, diff)\n return max_diff", "def maxdiffindex(A, N):\n d = {}\n for i in range(N):\n a = A[i]\n if a not in d:\n d[a] = [i]\n else:\n d[a].append(i)\n x = []\n for i in d:\n b = d[i]\n x.append(b[-1] - b[0])\n return max(x)", "def maxdiffindex(A, N):\n h = {}\n for i in range(N):\n if A[i] not in h:\n h[A[i]] = [i]\n else:\n h[A[i]] += [i]\n ans = []\n for i in h:\n if len(h[i]) == 1:\n ans.append(0)\n else:\n ans.append(h[i][-1] - h[i][0])\n return max(ans)", "def maxdiffindex(A, N):\n d = {}\n for i in range(N):\n if A[i] not in d:\n d[A[i]] = i\n ans = 0\n for i in range(N - 1, -1, -1):\n if A[i] in d:\n ans = max(ans, i - d[A[i]])\n return ans", "def maxdiffindex(A, N):\n d = {}\n mx = 0\n for i in range(N):\n if A[i] in d:\n mx = max(abs(d[A[i]] - i), mx)\n else:\n d[A[i]] = i\n return mx", "def maxdiffindex(arr, n):\n d = dict()\n res = 0\n for i in range(n):\n if arr[i] in d:\n res = max(res, i - d[arr[i]])\n else:\n d[arr[i]] = i\n return res", "def maxdiffindex(A, N):\n max_diff = 0\n d = {}\n for i in range(N):\n if A[i] not in d:\n d[A[i]] = i\n else:\n max_diff = max(max_diff, i - d[A[i]])\n return max_diff", "def maxdiffindex(A, N):\n d = {}\n f = {}\n for i in range(len(A)):\n if A[i] not in d:\n d[A[i]] = i\n else:\n continue\n for i in range(len(A) - 1, -1, -1):\n if A[i] not in f:\n f[A[i]] = i\n else:\n continue\n max_val = -9999\n for key in d.keys():\n if abs(d[key] - f[key]) > max_val:\n max_val = abs(d[key] - f[key])\n return max_val"], "starter_code": "def maxdiffindex(A, N):\n", "input_output": {"inputs": ["N = 9\nA[] = {2, 1, 3, 4, 2, 1, 5, 1, 7}"], "outputs": ["6"]}, "difficulty": "EASY", "raw_tags": ["Map", "Arrays", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/maximum-difference-10429/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N. Log(N))", "entry_point": "maxdiffindex", "task_id": "TACO_lite/46", "example": [[[9, [2, 1, 3, 4, 2, 1, 5, 1, 7]]], ["6"]]} +{"requirement": "Kontti language is a finnish word play game.\n\nYou add `-kontti` to the end of each word and then swap their characters until and including the first vowel (\"aeiouy\"); \n\nFor example the word `tame` becomes `kome-tantti`; `fruity` becomes `koity-fruntti` and so on.\n\nIf no vowel is present, the word stays the same.\n\nWrite a string method that turns a sentence into kontti language!", "solutions": ["import re\n\ndef kontti(s):\n return ' '.join([re.sub('([^aeiouy]*[aeiouy])(.*)', 'ko\\\\2-\\\\1ntti', w, flags=re.I) for w in s.split()])", "from re import sub\nfrom functools import partial\nkontti = partial(sub, '(?i)(\\\\S*?[aeiouy])(\\\\S*)', 'ko\\\\2-\\\\1ntti')", "import re\n\ndef kontti(s):\n return re.sub('(\\\\S*?[aeiouy])(\\\\S*)', 'ko\\\\2-\\\\1ntti', s, flags=re.I)", "def kontti(stg):\n return ' '.join((k_w(word) for word in stg.split()))\n\ndef k_w(stg):\n i = next((i for (i, c) in enumerate(stg.lower()) if c in 'aeiouy'), -1)\n return f'ko{stg[i + 1:]}-{stg[:i + 1]}ntti' if i > -1 else stg", "kontti = lambda w: ' '.join([(lambda pos: ''.join(['ko', s[pos + 1:], '-', s[:pos + 1], 'ntti']))([i for (i, l) in enumerate(s) if l.lower() in 'aeiouy'][0]) if any((l.lower() in 'aeiouy' for l in s)) else s for s in w.split(' ')]) if len(w) else ''", "kontti = lambda s: ' '.join(((lambda i: i < len(w) and 'ko' + w[i + 1:] + '-' + w[:i + 1] + 'ntti' or w)(min((i for (i, c) in enumerate(w + 'a') if c in 'aeiouyAEIOUY'))) for w in s.split()))", "def kontti(s):\n result = []\n for w in s.split():\n i = next((i for (i, c) in enumerate(w, 1) if c in 'aeiouyAEIOUY'), None)\n result.append(w if i is None else f'ko{w[i:]}-{w[:i]}ntti')\n return ' '.join(result)", "def kontti(st):\n r = []\n for s in st.split():\n (a, s) = ('', list(s))\n if not any((i in s for i in 'aeiouyAEIOUY')):\n r.append(''.join(s))\n else:\n while s:\n a += s.pop(0)\n if a[-1] in 'aeiouyAEIOUY':\n break\n r.append(f\"ko{''.join(s)}-{a}ntti\")\n return ' '.join(r)", "from re import search\n\ndef kontti(s):\n words = []\n for word in s.split():\n i = search('[aeiouyAEIOUY]', word)\n if i:\n i = i.start()\n words.append(f'ko{word[i + 1:]}-{word[:i + 1]}ntti')\n else:\n words.append(word)\n return ' '.join(words)"], "starter_code": "def kontti(s):\n", "input_output": {"fn_name": "kontti", "inputs": [["lamppu"], ["lamppu sofia"], ["silly game"], ["aeiou"], ["xyz lamppu"], [""], ["lAmppU"], ["silly grrr"]], "outputs": [["komppu-lantti"], ["komppu-lantti kofia-sontti"], ["kolly-sintti kome-gantti"], ["koeiou-antti"], ["koz-xyntti komppu-lantti"], [""], ["komppU-lAntti"], ["kolly-sintti grrr"]]}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/570e1271e5c9a0cf2f000d11", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "kontti", "task_id": "TACO_lite/55", "example": [[], []]} +{"requirement": "Given an array arr[] of size N, find the first digit from the left of the product of these N integers.\nExample 1:\nInput: N = 4, arr[] = {5, 8, 3, 7}\nOutput: 8\nExplanation: Produt is 840\nExample 2:\nInput: N = 3, arr[] = {6, 7, 9} \nOutput: 3\nExplanation: Produt is 378\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function firstDigit() which takes N and array arr[] as input parameters and returns the left digit of product.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ N, arr[i] ≤ 10^{5}\nTest cases have been designed such that there is no precision ambiguity.", "solutions": ["def firstdigit(arr, n):\n p = 1\n for i in range(n):\n p = p * arr[i]\n d = str(p)\n p = int(d[:6])\n return str(p)[0]", "def firstdigit(arr, n):\n val = 1\n for i in arr:\n val *= i\n st = str(val)\n val = int(st[:6])\n return str(val)[0]", "import math\n\ndef firstdigit(arr, n):\n s = 0.0\n for a in arr:\n s += math.log10(a)\n s = s - math.floor(s)\n return int(math.pow(10, s) + 1e-06)", "import math\n\ndef firstdigit(arr, n):\n res = 1\n for i in arr:\n res = res * i\n dig = int(math.log10(res))\n return res // 10 ** dig", "def firstdigit(arr, n):\n s = 1\n for i in range(n):\n s = s * arr[i]\n m = str(s)\n s = int(m[:6])\n return str(s)[0]", "import math\n\ndef firstdigit(arr, n):\n S = 0\n if n == 1:\n s = str(arr[0])\n return s[0]\n else:\n for i in arr:\n S = S + math.log10(i * 1.0)\n fract_S = S - math.floor(S)\n ans = math.pow(10, fract_S)\n return int(ans)", "import functools as f\n\ndef firstdigit(arr, n):\n p = 1\n for i in range(n):\n p = p * arr[i]\n d = str(p)\n p = int(d[:8])\n return str(p)[0]", "import math\n\ndef firstdigit(arr, n):\n product = 1\n for i in range(0, n):\n product = product * arr[i]\n digit = product // 10 ** int(math.log10(product))\n return digit", "import math\n\ndef firstdigit(arr, n):\n S = 0\n for i in range(n):\n S += math.log(arr[i], 10)\n S += 1e-06\n S -= math.floor(S)\n ans = int(pow(10, S))\n return ans", "import math\n\ndef firstdigit(arr, n):\n if n == 1:\n return str(arr[0])[0]\n s = 0\n for val in arr:\n s = s + math.log10(val * 1.0)\n frac = s - math.floor(s)\n return int(math.pow(10, frac))"], "starter_code": "def firstdigit(arr, n):\n", "input_output": {"inputs": ["N = 4, arr[] = {5, 8, 3, 7}", "N = 3, arr[] = {6, 7, 9}"], "outputs": ["8", "3"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/first-digit1751/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "firstdigit", "task_id": "TACO_lite/48", "example": [[[4, [5, 8, 3, 7]], [3, [6, 7, 9]]], ["8", "3"]]} +{"requirement": "Given a dictionary of words and a pattern. Every character in the pattern is uniquely mapped to a character in the dictionary. Find all such words in the dictionary that match the given pattern. \nExample 1:\nInput:\nN = 4\ndict[] = {abb,abc,xyz,xyy}\npattern = foo\nOutput: abb xyy\nExplanation: xyy and abb have the same\ncharacter at index 1 and 2 like the\npattern.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function findMatchedWords() which takes an array of strings dict[] consisting of the words in the dictionary and a string, Pattern and returns an array of strings consisting of all the words in the dict[] that match the given Pattern in lexicographical order.\nExpected Time Complexity: O(N*K) (where K is the length of the pattern).\nExpected Auxiliary Space: O(N).\nConstraints:\n1 <= N <= 10", "solutions": ["def findspecificpattern(Dict, pattern):\n ans = []\n for i in Dict:\n dic = {}\n dic2 = {}\n if len(i) == len(pattern):\n flag = True\n for (j, k) in zip(i, pattern):\n if j not in dic and k not in dic2:\n dic[j] = k\n dic2[k] = j\n elif dic.get(j) != k or dic2.get(k) != j:\n flag = False\n if flag:\n ans.append(i)\n return ans", "def findspecificpattern(dict, pattern):\n lst = []\n for i in dict:\n if len(set(i)) == len(set(pattern)) == len(set(zip(i, pattern))) and len(i) == len(pattern):\n lst.append(i)\n return lst", "def findspecificpattern(Dict, pattern):\n d = {}\n for i in pattern:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n b = list(d.values())\n b.sort()\n a = []\n c = []\n for i in Dict:\n d2 = {}\n for j in i:\n if j in d2:\n d2[j] += 1\n else:\n d2[j] = 1\n x = list(d2.values())\n x.sort()\n a.append(x)\n c.append(i)\n d2.clear()\n d = []\n for i in range(len(a)):\n if b == a[i]:\n d.append(c[i])\n return d", "def findspecificpattern(Dict, pattern):\n a = []\n for i in Dict:\n if len(i) != len(pattern):\n continue\n d1 = {}\n d2 = {}\n for j in range(len(i)):\n if i[j] not in d1.keys() or pattern[j] not in d2.keys():\n d1[i[j]] = pattern[j]\n d2[pattern[j]] = i[j]\n elif d1[i[j]] != pattern[j] or d2[pattern[j]] != i[j]:\n break\n if len(d1) == len(d2):\n a.append(i)\n return a", "def encodeString(Str):\n map = {}\n res = ''\n i = 0\n for ch in Str:\n if ch not in map:\n map[ch] = i\n i += 1\n res += str(map[ch])\n return res\n\ndef findMatchedWords(dict, pattern):\n Len = len(pattern)\n hash = encodeString(pattern)\n res = []\n for word in dict:\n if len(word) == Len and encodeString(word) == hash:\n res.append(word)\n return res\n\ndef findspecificpattern(Dict, pattern):\n return findMatchedWords(Dict, pattern)", "def findspecificpattern(Dict, pattern):\n ans = []\n flag = False\n for stri in Dict:\n flag = False\n if len(stri) == len(pattern):\n for i in range(len(pattern) - 1):\n if stri[i] != stri[i + 1] and pattern[i] != pattern[i + 1] or (stri[i] == stri[i + 1] and pattern[i] == pattern[i + 1]):\n flag = True\n else:\n flag = False\n break\n if flag == True:\n dic = {}\n pic = {}\n for i in range(len(pattern)):\n if stri[i] not in dic:\n dic[stri[i]] = 1\n else:\n dic[stri[i]] += 1\n if pattern[i] not in pic:\n pic[pattern[i]] = 1\n else:\n pic[pattern[i]] += 1\n for i in range(len(pattern)):\n if dic[stri[i]] != pic[pattern[i]]:\n flag = False\n break\n if len(stri) == 1 and len(pattern) == 1:\n ans.append(stri)\n if flag == True:\n ans.append(stri)\n return ans", "def findspecificpattern(Dict, pattern):\n a = []\n for i in Dict:\n if len(set(i)) == len(set(pattern)) and len(i) == len(pattern):\n a.append(i)\n return a", "def hash_fn(word):\n k = 0\n mapper = {}\n res = ''\n for i in word:\n if i not in mapper:\n mapper[i] = k\n k += 1\n res += str(mapper[i])\n return res\n\ndef findspecificpattern(Dict, pattern):\n ptrn_hsh = hash_fn(pattern)\n l = len(pattern)\n res = []\n for i in Dict:\n if len(i) == l and hash_fn(i) == ptrn_hsh:\n res.append(i)\n return res", "def findspecificpattern(Dict, pattern):\n matched_words = []\n for word in Dict:\n if len(word) == len(pattern):\n matched = True\n pattern_dict = {}\n for i in range(len(word)):\n if word[i] not in pattern_dict:\n if pattern[i] in pattern_dict.values():\n matched = False\n break\n pattern_dict[word[i]] = pattern[i]\n elif pattern_dict[word[i]] != pattern[i]:\n matched = False\n break\n if matched:\n matched_words.append(word)\n matched_words.sort()\n return matched_words", "def findspecificpattern(Dict, pattern):\n pattern_list = []\n for item in Dict:\n if len(item) != len(pattern):\n pattern_list.append('')\n continue\n new_pattern = pattern\n char_dict = {}\n temp_str = ''\n for i in range(len(item)):\n if item[i] in char_dict:\n temp_str = temp_str + char_dict[item[i]]\n elif new_pattern != '':\n char_dict[item[i]] = new_pattern[0]\n new_pattern = new_pattern.replace(new_pattern[0], '')\n temp_str = temp_str + char_dict[item[i]]\n pattern_list.append(temp_str)\n final_pattern = []\n for i in range(len(pattern_list)):\n if pattern_list[i] == pattern:\n final_pattern.append(Dict[i])\n return final_pattern\n return final_pattern", "def findspecificpattern(Dict, pattern):\n d = {}\n for (i, char) in enumerate(pattern):\n if char in d:\n d[char].append(i)\n else:\n d[char] = [i]\n control = sorted(d.values())\n output = []\n for word in Dict:\n temp = {}\n for (i, char) in enumerate(word):\n if char in temp:\n temp[char].append(i)\n else:\n temp[char] = [i]\n if sorted(temp.values()) == control:\n output.append(word)\n return sorted(output)", "def findspecificpattern(Dict, pattern):\n dct = {}\n arr = [0] * len(pattern)\n j = 0\n ans = []\n for i in pattern:\n if i in dct:\n dct[i] += 1\n arr[j] = dct[i]\n else:\n arr[j] = 1\n dct[i] = 1\n j += 1\n for p in Dict:\n arr2 = [0] * len(p)\n j = 0\n dct = {}\n for i in p:\n if i in dct:\n dct[i] += 1\n arr2[j] = dct[i]\n else:\n arr2[j] = 1\n dct[i] = 1\n j += 1\n if arr == arr2:\n ans.append(p)\n return ans", "def findspecificpattern(Dict, pattern):\n res = []\n\n def helper(pattern, elem):\n d = {}\n n = len(pattern)\n if n != len(elem):\n return\n for i in range(n):\n if pattern[i] in d and elem[i] != d[pattern[i]]:\n break\n elif pattern[i] not in d and elem[i] in d.values():\n break\n else:\n d[pattern[i]] = elem[i]\n else:\n return elem\n for x in Dict:\n if helper(pattern, x):\n res.append(helper(pattern, x))\n return res", "def findspecificpattern(Dict, pattern):\n length = len(pattern)\n hash = encodeString(pattern)\n result = []\n for word in Dict:\n if len(word) == length and encodeString(word) == hash:\n result.append(word)\n return result\n\ndef encodeString(Str):\n map = {}\n res = ''\n i = 0\n for ch in Str:\n if ch not in map:\n map[ch] = i\n i += 1\n res += str(map[ch])\n return res", "def encodeString(string):\n map = {}\n res = ''\n i = 0\n for ch in string:\n if ch not in map:\n map[ch] = i\n i += 1\n res += str(map[ch])\n return res\n\ndef findspecificpattern(Dict, pattern):\n size = len(pattern)\n hash_map = encodeString(pattern)\n output = []\n for word in Dict:\n if len(word) == size and encodeString(word) == hash_map:\n output.append(word)\n return output", "def findspecificpattern(Dict, pattern):\n\n def encode(word):\n m = {}\n s = ''\n counter = 0\n for c in word:\n if c not in m:\n m[c] = counter\n counter += 1\n s += str(m[c])\n return s\n pattern_hash = encode(pattern)\n result = []\n for word in Dict:\n word_hash = encode(word)\n if pattern_hash == word_hash:\n result.append(word)\n return result", "def findspecificpattern(Dict, pattern):\n d = {}\n da = []\n p = 0\n s = set(pattern)\n for i in Dict:\n if len(set(i)) == len(s):\n da.append(i)\n for i in da:\n l1 = []\n l2 = []\n c = 0\n p += 1\n for j in i:\n if l1 == []:\n l1.append(j)\n c += 1\n elif l1[-1] == j:\n l1.append(j)\n c += 1\n elif l1[-1] != j:\n l1.append(j)\n l2.append(c)\n c = 1\n if l1[-1] == i[-1]:\n l2.append(c)\n l2.insert(0, p)\n l2.insert(1, i)\n else:\n l2.append(1)\n l2.insert(0, p)\n l2.insert(1, i)\n if i not in d:\n d[i] = [l2]\n else:\n d[i].append(l2)\n k = []\n l11 = []\n l22 = []\n c1 = 0\n for i in pattern:\n if l11 == []:\n l11.append(i)\n c1 += 1\n elif l11[-1] == i:\n l11.append(i)\n c1 += 1\n elif l11[-1] != i:\n l11.append(i)\n l22.append(c1)\n c1 = 1\n if l11[-1] == pattern[-1]:\n l22.append(c1)\n else:\n l22.append(1)\n k.append(l22)\n l3 = []\n l4 = []\n for i in d:\n if d[i][0][2:] == k[-1]:\n l3.append(d[i][0] * len(d[i]))\n l3.sort()\n for i in l3:\n l4 += [i[1]] * len(d[i[1]])\n return l4", "from collections import OrderedDict\n\ndef findspecificpattern(Dict, t):\n l = []\n n = len(t)\n for j in Dict:\n d = {}\n m = len(j)\n if m != n:\n continue\n flag = 1\n for i in range(m):\n if j[i] not in d and t[i] not in d.values():\n d[j[i]] = t[i]\n elif j[i] in d and d[j[i]] != t[i]:\n flag = 0\n elif j[i] not in d and t[i] in d.values():\n flag = 0\n if flag:\n l.append(j)\n return l", "from collections import OrderedDict\n\ndef findspecificpattern(Dict, pattern):\n l = []\n for i in Dict:\n if len(i) != len(pattern) and len(set(i)) != len(set(pattern)):\n continue\n else:\n temp = i\n for j in list(zip(list(OrderedDict.fromkeys(temp)), list(OrderedDict.fromkeys(pattern)))):\n temp = temp.replace(j[0], j[1])\n if temp == pattern:\n l.append(i)\n return l", "def findspecificpattern(Dict, pattern):\n lis = []\n for i in range(len(Dict)):\n word = Dict[i]\n if len(set(word)) == len(set(pattern)) and len(word) == len(pattern):\n l = {}\n check = 1\n for i in range(len(pattern)):\n if pattern[i] in l:\n if l[pattern[i]] != word[i]:\n check = 0\n break\n else:\n l[pattern[i]] = word[i]\n if check == 1:\n lis.append(word)\n return lis", "def findspecificpattern(Dict, pattern):\n pattern_mapp = {}\n pattern_str = ''\n for (idx, char) in enumerate(pattern):\n if char not in pattern_mapp:\n pattern_mapp[char] = str(idx)\n pattern_str += str(idx)\n else:\n pattern_str += pattern_mapp[char]\n hashes = []\n for i in range(len(Dict)):\n dict_map = {}\n hash = ''\n for (idx, char) in enumerate(Dict[i]):\n if char not in dict_map:\n dict_map[char] = str(idx)\n hash += str(idx)\n else:\n hash += dict_map[char]\n if hash == pattern_str:\n hashes.append(Dict[i])\n return hashes", "def Pattern(pattern):\n code = {}\n num = 1\n temp = ''\n for i in range(len(pattern)):\n if not code.get(pattern[i]):\n code[pattern[i]] = num\n num += 1\n else:\n num += 1\n code[pattern[i]] = num\n for i in pattern:\n temp += str(code[i])\n return temp\n\ndef findspecificpattern(Dict, pattern):\n checker = Pattern(pattern)\n li = []\n for i in Dict:\n temp = Pattern(i)\n if temp == checker:\n li.append(i)\n return li", "def get_hashmap(stra):\n hash_d = dict()\n for k in range(len(stra)):\n if hash_d.get(stra[k]):\n hash_d[stra[k]].append(k)\n else:\n hash_d[stra[k]] = [k]\n return set((tuple(i) for i in list(hash_d.values())))\n\ndef findspecificpattern(Dict, pattern):\n array_pat = []\n hash_vals = get_hashmap(pattern)\n for word in Dict:\n if get_hashmap(word) == hash_vals:\n array_pat.append(word)\n array_pat.sort()\n return array_pat", "from collections import Counter\n\ndef findspecificpattern(Dict, pattern):\n ans = []\n dicpat = Counter(pattern)\n dicpatv = list(dicpat.values())\n for i in range(0, len(Dict)):\n if len(Dict[i]) == len(pattern):\n dici = Counter(Dict[i])\n dicv = list(dici.values())\n if len(dicv) == len(dicpatv):\n for j in range(0, len(dicv)):\n if dicv[j] != dicpatv[j]:\n dici = {}\n diciv = []\n continue\n ans.append(Dict[i])\n dici = {}\n diciv = []\n return ans", "def findspecificpattern(Dict, pattern):\n\n def getPattern(pattern):\n patt_str = ''\n val_m = {}\n count = 1\n for val in pattern:\n if val in val_m:\n patt_str += str(val_m[val])\n else:\n patt_str += str(count)\n val_m[val] = count\n count += 1\n return patt_str\n result = []\n match = getPattern(pattern)\n for val in Dict:\n p = getPattern(val)\n if p == match:\n result.append(val)\n return result", "def findspecificpattern(Dict, pattern):\n Dict.append(pattern)\n res = []\n c = 0\n p = ''\n i = 0\n k = 0\n j = 0\n for i in Dict:\n while j < len(i):\n if j == len(i) - 1:\n p += str(c)\n j += 1\n c += 1\n break\n while i[j] == i[j + 1]:\n p += str(c)\n k = 1\n j += 1\n if j == len(i) - 1:\n break\n if j == len(i) - 1:\n p += str(c)\n j += 1\n break\n p += str(c)\n j += 1\n c += 1\n k = 0\n res.append(p)\n p = ''\n j = 0\n c = 0\n p1 = res[-1]\n res1 = []\n res.pop()\n for (i, j) in enumerate(res):\n if j == p1:\n res1.append(Dict[i])\n return res1", "def findspecificpattern(Dict, pattern):\n L = []\n n = 0\n e = ''\n x = ''\n pattern = pattern + '.'\n for i in pattern:\n if i == e:\n n += 1\n else:\n x = x + str(n)\n n = 1\n e = i\n for i in Dict:\n n = 0\n e = ''\n y = ''\n i = i + '.'\n for j in i:\n if j == e:\n n += 1\n else:\n y = y + str(n)\n n = 1\n e = j\n if y == x:\n L.append(i[:-1])\n return L", "def findspecificpattern(Dict, pattern):\n result = []\n for word in Dict:\n hash = {}\n flag = True\n if len(word) != len(pattern):\n continue\n for (i, c) in enumerate(pattern):\n if c not in hash:\n hash[c] = word[i]\n elif hash[c] != word[i]:\n flag = False\n if flag:\n result.append(word)\n return result", "def convert(p):\n m = {}\n r = ''\n for i in p:\n if i not in m:\n m[i] = 1\n else:\n m[i] += 1\n r = r + str(m[i])\n return r\n\ndef findspecificpattern(Dict, pattern):\n ans = []\n pat = convert(pattern)\n for i in Dict:\n if convert(i) == pat:\n ans.append(i)\n return ans", "def findspecificpattern(Dict, pattern):\n from collections import defaultdict, OrderedDict\n (dnew, dnew2) = (defaultdict(int), defaultdict(int))\n (dnew3, dnew4) = (OrderedDict(), OrderedDict())\n (L, res) = ([], [])\n for i in Dict:\n if len(set(i)) == len(set(pattern)):\n L.append(i)\n for i in range(len(pattern)):\n dnew[pattern[i]] += 1\n dnew3[pattern[i]] = dnew[pattern[i]]\n for k in L:\n for i in range(len(k)):\n dnew2[k[i]] += 1\n dnew4[k[i]] = dnew2[k[i]]\n if list(dnew4.values()) == list(dnew3.values()):\n res.append(k)\n dnew2 = defaultdict(int)\n dnew4 = OrderedDict()\n return res", "def findspecificpattern(dictt, pattern):\n res = []\n\n def patterniser(strg):\n d = dict()\n lst = []\n pointer = 1\n for i in strg:\n if i not in d:\n d[i] = pointer\n pointer += 1\n lst.append(d[i])\n return lst\n\n def checker(pat1, pat2):\n for i in range(len(pat1)):\n if pat1[i] != pat2[i]:\n return False\n return True\n pat1 = patterniser(pattern)\n for i in dictt:\n if len(i) == len(pattern):\n pat2 = patterniser(i)\n if checker(pat1, pat2):\n res.append(i)\n return res", "def findspecificpattern(Dict, pattern):\n a = {}\n aa = []\n for i in range(len(pattern)):\n try:\n if a[pattern[i]] == 0:\n pass\n except:\n a[pattern[i]] = 0\n aa.append(pattern[i])\n pp = ''\n p = {}\n ans = []\n for i in range(len(aa)):\n p[aa[i]] = i\n for i in range(len(pattern)):\n pp += str(p[pattern[i]])\n for j in range(len(Dict)):\n a = {}\n aa = []\n for i in range(len(Dict[j])):\n try:\n if a[Dict[j][i]] == 0:\n pass\n except:\n a[Dict[j][i]] = 0\n aa.append(Dict[j][i])\n ppp = ''\n po = {}\n for i in range(len(aa)):\n po[aa[i]] = i\n for i in range(len(Dict[j])):\n ppp += str(po[Dict[j][i]])\n if pp == ppp:\n ans.append(Dict[j])\n return ans", "def findspecificpattern(Dict, pattern):\n dic1 = {}\n count1 = []\n for i in pattern:\n if i not in dic1:\n dic1[i] = 1\n count1.append(dic1[i])\n else:\n dic1[i] += 1\n count1.append(dic1[i])\n dic2 = {}\n count2 = []\n output = []\n for x in Dict:\n for y in x:\n if y not in dic2:\n dic2[y] = 1\n count2.append(dic2[y])\n else:\n dic2[y] += 1\n count2.append(dic2[y])\n if count1 == count2:\n output.append(x)\n count2 = []\n dic2 = {}\n return output", "def ispattern(str1, pattern, n, p):\n if n != p:\n return False\n d = {}\n for i in range(n):\n if str1[i] in d:\n val = d[str1[i]]\n if val != pattern[i]:\n return False\n elif pattern[i] not in d.values():\n d[str1[i]] = pattern[i]\n else:\n return False\n return True\n\ndef findspecificpattern(Dict, pattern):\n ans = []\n p = len(pattern)\n for i in Dict:\n if ispattern(i, pattern, len(i), p):\n ans.append(i)\n return ans", "def findspecificpattern(Dict, pat):\n n = len(pat)\n c = 1\n l = []\n for i in range(n - 1):\n if pat[i] == pat[i + 1]:\n c += 1\n else:\n l.append(c)\n c = 1\n l.append(c)\n h = []\n for i in Dict:\n c = 1\n b = []\n n = len(i)\n for j in range(n - 1):\n if i[j] == i[j + 1]:\n c += 1\n else:\n b.append(c)\n c = 1\n b.append(c)\n if b == l:\n h.append(i)\n return h", "def hashmap(Strng):\n Dic = {}\n for i in Strng:\n if i not in Dic:\n Dic[i] = 1\n else:\n Dic[i] += 1\n return Dic\n\ndef findspecificpattern(Dict, pattern):\n kiss = []\n k = 0\n cont = 0\n ptr = {}\n for i in pattern:\n if i not in ptr:\n ptr[i] = 1\n else:\n ptr[i] += 1\n lptrn = len(ptr)\n while k < len(Dict):\n j = hashmap(Dict[k])\n ldic = len(j)\n if lptrn == ldic:\n if list(ptr.values()) == list(j.values()):\n kiss.append(Dict[k])\n k += 1\n return kiss", "def search(s, n):\n dp = [1] * n\n for i in range(1, n):\n if s[i - 1] == s[i]:\n dp[i] = dp[i - 1] + 1\n return dp\n\ndef findspecificpattern(Dict, pattern):\n p_dp = search(pattern, len(pattern))\n ans = []\n for i in Dict:\n if search(i, len(i)) == p_dp:\n ans.append(i)\n return ans", "def findspecificpattern(Dict, pattern):\n n = len(pattern)\n dp = [1] * n\n for i in range(1, n):\n if pattern[i - 1] == pattern[i]:\n dp[i] = dp[i - 1] + 1\n ans = []\n for i in Dict:\n p = [1] * len(i)\n for j in range(1, len(i)):\n if i[j - 1] == i[j]:\n p[j] = p[j - 1] + 1\n if dp == p:\n ans.append(i)\n return ans", "def findspecificpattern(Dict, pattern):\n ans = []\n for word in Dict:\n char1ToChar2 = {}\n char2ToChar1 = {}\n if len(word) == len(pattern):\n for (c1, c2) in zip(word, pattern):\n if c1 in char1ToChar2 and char1ToChar2[c1] != c2:\n break\n if c2 in char2ToChar1 and char2ToChar1[c2] != c1:\n break\n char1ToChar2[c1] = c2\n char2ToChar1[c2] = c1\n else:\n ans.append(word)\n return ans", "def findspecificpattern(Dict, pattern):\n ans = []\n for word in Dict:\n h = {}\n flag = 1\n if len(word) == len(pattern):\n for (i, j) in zip(pattern, word):\n if i not in h:\n h[i] = j\n elif h[i] != j:\n flag = 0\n break\n else:\n flag = 0\n if flag:\n ans.append(word)\n return ans", "def findspecificpattern(Dict, pattern):\n pattern_map = {}\n for i in range(len(pattern)):\n if pattern[i] not in pattern_map:\n pattern_map[pattern[i]] = 1\n else:\n pattern_map[pattern[i]] += 1\n pattern_string = ''\n values = sorted(pattern_map.values())\n for things in values:\n pattern_string += str(things)\n res = []\n for words in Dict:\n dict_map = {}\n for j in range(len(words)):\n if words[j] not in dict_map:\n dict_map[words[j]] = 1\n else:\n dict_map[words[j]] += 1\n dict_string = ''\n values2 = sorted(dict_map.values())\n for things2 in values2:\n dict_string += str(things2)\n if len(words) == len(pattern) and pattern_string == dict_string:\n res.append(words)\n return res", "def findspecificpattern(Dict, pattern):\n map_pattern = {}\n for i in range(len(pattern)):\n if pattern[i] not in map_pattern:\n map_pattern[pattern[i]] = 1\n else:\n map_pattern[pattern[i]] += 1\n pattern_string = ''\n values = sorted(map_pattern.values())\n for things in values:\n pattern_string += str(things)\n res = []\n for element in Dict:\n dict_map = {}\n for i in range(len(element)):\n if element[i] not in dict_map:\n dict_map[element[i]] = 1\n else:\n dict_map[element[i]] += 1\n dict_string = ''\n values1 = sorted(dict_map.values())\n for things2 in values1:\n dict_string += str(things2)\n if len(element) == len(pattern) and pattern_string == dict_string:\n res.append(element)\n return res", "def get_pattern(s):\n d = {}\n c = 0\n unique = []\n for i in range(len(s)):\n if s[i] not in unique:\n c += 1\n unique.append(s[i])\n d[c] = [i]\n else:\n d[c].append(i)\n return d\n\ndef findspecificpattern(Dict, pattern):\n golden = get_pattern(pattern)\n ans = []\n for i in Dict:\n temp = get_pattern(i)\n if temp == golden:\n ans.append(i)\n return ans", "def findspecificpattern(Dict, pattern):\n l = len(pattern)\n arr = [0] * l\n arr[0] = 1\n for i in range(1, l):\n if pattern[i] == pattern[i - 1]:\n arr[i] = 1 + arr[i - 1]\n else:\n arr[i] = 1\n lst = []\n for i in range(len(Dict)):\n if len(Dict[i]) == l:\n b = [0] * l\n b[0] = 1\n for j in range(1, l):\n if Dict[i][j] == Dict[i][j - 1]:\n b[j] = 1 + b[j - 1]\n else:\n b[j] = 1\n if b == arr:\n lst.append(Dict[i])\n lst.sort()\n return lst", "def check_isomorphic(str1, str2):\n if len(str1) != len(str2):\n return False\n map = {}\n for i in range(len(str1)):\n if str1[i] in map:\n if map[str1[i]] != str2[i]:\n return False\n elif str2[i] not in map.values():\n map[str1[i]] = str2[i]\n else:\n return False\n return True\n\ndef findspecificpattern(Dict, pattern):\n res = []\n N = len(Dict)\n for i in range(N):\n if check_isomorphic(Dict[i], pattern):\n res.append(Dict[i])\n return res", "from collections import Counter\n\ndef findspecificpattern(dic, pattern):\n n = len(pattern)\n mp = [0] * n\n mp[0] = 1\n for i in range(1, n):\n if pattern[i] == pattern[i - 1]:\n mp[i] = 1 + mp[i - 1]\n else:\n mp[i] = 1\n res = []\n for i in range(len(dic)):\n if len(dic[i]) == n:\n k = [0] * n\n k[0] = 1\n for j in range(1, n):\n if dic[i][j] == dic[i][j - 1]:\n k[j] = 1 + k[j - 1]\n else:\n k[j] = 1\n if k == mp:\n res.append(dic[i])\n res.sort()\n return res", "from collections import deque\n\ndef findspecificpattern(d, p):\n\n def check(p, w):\n if len(p) != len(w):\n return False\n ch = [0 for i in range(128)]\n for i in range(len(p)):\n if ch[ord(p[i])] == 0:\n ch[ord(p[i])] = w[i]\n elif ch[ord(p[i])] != w[i]:\n return False\n return True\n res = deque()\n for i in range(len(d)):\n if check(p, d[i]):\n res.append(d[i])\n return res", "def encode(word):\n hashMap = {}\n result = ''\n i = 1\n for ch in word:\n if ch not in hashMap:\n hashMap[ch] = i\n i = i + 1\n result += str(hashMap[ch])\n return result\n\ndef findspecificpattern(Dict, pattern):\n final = []\n for word in Dict:\n if len(word) == len(pattern) and encode(word) == encode(pattern):\n final.append(word)\n return final", "def findspecificpattern(Dict, pattern):\n count1 = 0\n count2 = 0\n for i in range(len(pattern) - 1):\n if pattern[i] != pattern[i + 1]:\n count1 += 1\n else:\n count2 += 1\n temp = []\n for i in Dict:\n count3 = 0\n count4 = 0\n for j in range(len(i) - 1):\n if i[j] != i[j + 1]:\n count3 += 1\n else:\n count4 += 1\n if count1 == count3 and count2 == count4:\n temp.append(i)\n return temp", "from collections import defaultdict\n\ndef findspecificpattern(Dict, pattern):\n res = []\n p = len(pattern)\n for s in Dict:\n if len(s) != p:\n continue\n d = defaultdict(str)\n flag = True\n for i in range(p):\n if s[i] not in d.keys() and pattern[i] not in d.values():\n d[s[i]] = pattern[i]\n elif d[s[i]] == pattern[i]:\n continue\n else:\n flag = False\n break\n if flag == True:\n res.append(s)\n return res", "def encode_helper(word):\n count = 0\n helper_map = {}\n s = ''\n for character in word:\n if character not in helper_map:\n helper_map[character] = count\n count += 1\n for character in word:\n s = s + str(helper_map[character])\n return s\n\ndef findspecificpattern(Dict, pattern):\n encoded_pattern = encode_helper(pattern)\n res = []\n for i in Dict:\n if encoded_pattern == encode_helper(i):\n res.append(i)\n return res", "def encode(word):\n count = 0\n dit = {}\n s = ''\n for i in word:\n if i not in dit:\n dit[i] = count\n count += 1\n for i in word:\n s = s + str(dit[i])\n return s\n\ndef findspecificpattern(Dict, pattern):\n l = []\n k = encode(pattern)\n for i in Dict:\n ans = encode(i)\n check = True\n if len(k) == len(ans):\n for j in range(len(k)):\n if k[j] != ans[j]:\n check = False\n break\n if check:\n l.append(i)\n return l", "def findspecificpattern(Dict, pattern):\n\n def makepattern(word):\n pr = -1\n d = {}\n res = []\n for c in word:\n if c in d:\n ind = d[c]\n else:\n d[c] = pr + 1\n pr += 1\n res.append(d[c])\n return res\n ans = []\n given_pattern = makepattern(pattern)\n for word in Dict:\n if given_pattern == makepattern(word):\n ans.append(word)\n return ans"], "starter_code": "def findspecificpattern(Dict, pattern):\n", "input_output": {"fn_name": "findSpecificPattern", "inputs": ["N = 4\ndict[] = {abb,abc,xyz,xyy}\npattern = foo"], "outputs": ["abb xyy"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Hash"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/match-specific-pattern/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*K) (where K is the length of the pattern).", "entry_point": "findspecificpattern", "task_id": "TACO_lite/18", "example": [[[4, ["abb", "abc", "xyz", "xyy"], "foo"]], ["['abb', 'xyy']"]]} +{"requirement": "Given an array of numbers, return an array, with each member of input array rounded to a nearest number, divisible by 5.\n\nFor example:\n```\nroundToFive([34.5, 56.2, 11, 13]);\n```\nshould return\n```\n[35, 55, 10, 15]\n```\n\n```if:python\nRoundings have to be done like \"in real life\": `22.5 -> 25`\n```", "solutions": ["from decimal import Decimal, ROUND_HALF_UP\n\ndef round_to_five(numbers):\n return [(n / 5).quantize(1, ROUND_HALF_UP) * 5 for n in map(Decimal, numbers)]", "def round_to_five(numbers):\n return [5 * int(x / 5 + 0.5) for x in numbers]", "def round_to_five(numbers):\n return [int((n + 2.5) / 5) * 5 for n in numbers]", "round_to_five = lambda l: [round((0.01 + n) / 5) * 5 for n in l]", "def round_to_five(numbers):\n return [int((x // 5 + (x % 5 >= 2.5)) * 5) for x in numbers]", "def round_to_five(arr):\n return [5 * round(v / 5 + 0.01) for v in arr]", "import math\n\ndef round_to_five(numbers):\n output = []\n for n in numbers:\n if n % 5 == 0:\n output.append(int(n))\n elif n % 10 < 5 and n % 5 < 2.5 or (n % 10 > 5 and n % 5 >= 2.5):\n output.append(int(round(n, -1)))\n elif n % 10 < 5 and n % 5 >= 2.5:\n output.append(int(round(n, -1) + 5))\n else:\n output.append(int(round(n, -1) - 5))\n return output", "from math import floor, ceil\n\ndef rond(x):\n return floor(x) if x % 1 < 0.5 else ceil(x)\n\ndef round_to_five(numbers):\n return [rond(x / 5) * 5 for x in numbers]", "def rounding(n):\n intPart = int(n)\n fracPart = n - intPart\n if fracPart >= 0.5:\n n = intPart + 1\n else:\n n = intPart\n for i in range(6):\n up = n + i\n down = n - i\n if up % 5 == 0:\n return up\n elif down % 5 == 0:\n return down\n\ndef round_to_five(numbers):\n numbers = [rounding(n) for n in numbers]\n return numbers"], "starter_code": "def round_to_five(numbers):\n", "input_output": {"fn_name": "round_to_five", "inputs": [[[1, 5, 87, 45, 8, 8]], [[3, 56.2, 11, 13]], [[22.5, 544.9, 77.5]]], "outputs": [[[0, 5, 85, 45, 10, 10]], [[5, 55, 10, 15]], [[25, 545, 80]]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/582f52208278c6be55000067", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "round_to_five", "task_id": "TACO_lite/35", "example": [[[[34.5, 56.2, 11, 13]]], ["[35, 55, 10, 15]"]]} +{"requirement": "You're a statistics professor and the deadline for submitting your students' grades is tonight at midnight. Each student's grade is determined by their mean score across all of the tests they took this semester.\n\nYou've decided to automate grade calculation by writing a function `calculate_grade()` that takes a list of test scores as an argument and returns a one character string representing the student's grade calculated as follows:\n\n * 90% <= mean score <= 100%: `\"A\"`,\n * 80% <= mean score < 90%: `\"B\"`,\n * 70% <= mean score < 80%: `\"C\"`,\n * 60% <= mean score < 70%: `\"D\"`,\n * mean score < 60%: `\"F\"`\n\nFor example, `calculate_grade([92, 94, 99])` would return `\"A\"` since the mean score is `95`, and `calculate_grade([50, 60, 70, 80, 90])` would return `\"C\"` since the mean score is `70`.\n\nYour function should handle an input list of any length greater than zero.", "solutions": ["from bisect import bisect\nfrom statistics import mean\n\ndef calculate_grade(scores):\n return 'FDCBA'[bisect([60, 70, 80, 90], mean(scores))]", "def calculate_grade(scores):\n for score in scores:\n mean = sum(scores) / len(scores)\n if mean >= 90 and mean <= 100:\n return 'A'\n elif mean >= 80 and mean < 90:\n return 'B'\n elif mean >= 70 and mean < 80:\n return 'C'\n elif mean >= 60 and mean < 70:\n return 'D'\n else:\n return 'F'", "import statistics\n\ndef calculate_grade(scores):\n mean = statistics.mean(scores)\n if mean >= 90:\n return 'A'\n if mean >= 80:\n return 'B'\n if mean >= 70:\n return 'C'\n if mean >= 60:\n return 'D'\n return 'F'", "def calculate_grade(scores):\n s = sum(scores) / len(scores)\n return 'ABCDF'[(s < 90) + (s < 80) + (s < 70) + (s < 60)]", "def calculate_grade(scores):\n import numpy as np\n mean_score = np.mean(scores)\n if mean_score >= 90:\n return 'A'\n elif mean_score >= 80:\n return 'B'\n elif mean_score >= 70:\n return 'C'\n elif mean_score >= 60:\n return 'D'\n else:\n return 'F'", "def calculate_grade(scores):\n mean = sum(scores) / len(scores)\n return 'ABCDF'[(mean < 90) + (mean < 80) + (mean < 70) + (mean < 60)]", "def calculate_grade(scores):\n score = sum(scores) / len(scores) / 100\n grades = {0.6: 'D', 0.7: 'C', 0.8: 'B', 0.9: 'A'}\n return grades[round(score, 1)] if score > 0.6 else 'F'", "def calculate_grade(scores):\n avg_grade = sum(scores) / len(scores)\n if avg_grade < 60:\n return 'F'\n elif avg_grade < 70:\n return 'D'\n elif avg_grade < 80:\n return 'C'\n elif avg_grade < 90:\n return 'B'\n else:\n return 'A'"], "starter_code": "def calculate_grade(scores):\n", "input_output": {"fn_name": "calculate_grade", "inputs": [[[92, 94, 99]], [[50, 60, 70, 80, 90]], [[50, 55]]], "outputs": [["A"], ["C"], ["F"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/586e0dc9b98de0064b000247", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "calculate_grade", "task_id": "TACO_lite/13", "example": [[[[92, 94, 99]], [[50, 60, 70, 80, 90]]], ["A", "C"]]} +{"requirement": "Given a positive integer N, The task is to find if it is a power of eight or not.\nExample 1: \nInput: 64\nOutput: Yes\nExplanation: 64 is power of 8.\nExample 2:\nInput: 75\nOutput: No\nExplanation: 75 is not a power of 8.\nYour Task:\nYou don't need to read or print anything. your task is to complete the function is_power_of_eight() which takes N as the input parameter and returns \"Yes\" if N is power of eight otherwise returns \"No\"(Wihtout quotes).\nExpected Time Complexity: O(log(N))\nExpected Space Complexity: O(1)\nConstraints:\n1 <= N <= 10^{18}", "solutions": ["def is_power_of_eight(n):\n (oc, zc) = (0, 0)\n while n != 0:\n if n & 1 == 0:\n zc += 1\n else:\n oc += 1\n n = n >> 1\n if oc == 1 and zc % 3 == 0:\n return 'Yes'\n return 'No'", "def is_power_of_eight(n):\n ans = 1\n while ans <= n:\n if ans == n:\n return 'Yes'\n ans = ans * 8\n return 'No'", "def is_power_of_eight(n):\n if 8 | n == 8 and n >= 8:\n return 'Yes'\n elif n & n - 1 == 0:\n return 'Yes'\n else:\n return 'No'", "def is_power_of_eight(n):\n (set, pos, i) = (0, -1, 0)\n while n is not 0:\n if n & 1:\n pos = i\n set += n & 1\n n >>= 1\n i += 1\n if set > 1:\n return 'No'\n if pos % 3 == 0:\n return 'Yes'\n return 'No'", "def is_power_of_eight(n):\n for i in range(64):\n if pow(8, i) == n:\n return 'Yes'\n return 'No'", "def is_power_of_eight(n):\n while n:\n if n == 8:\n return 'Yes'\n if n % 8 != 0:\n return 'No'\n n = n // 8\n return 'No'", "import math\n\ndef is_power_of_eight(n):\n k = int(math.log(n, 8))\n if 8 ** k == n:\n return 'Yes'\n else:\n return 'No'", "def is_power_of_eight(n):\n import math\n x = math.log(n, 8)\n if 8 ** int(x) == n:\n return 'Yes'\n return 'No'", "import math\n\ndef is_power_of_eight(n):\n i = math.log(n) / math.log(8)\n if i - math.floor(i) < 1e-05:\n return 'Yes'\n else:\n return 'No'", "def is_power_of_eight(n):\n l = 1\n while l <= n:\n if l & n == n:\n return 'Yes'\n l <<= 3\n return 'No'", "def is_power_of_eight(n):\n if n & n - 1 or n == 0:\n return 'No'\n c = -1\n while n:\n n >>= 1\n c += 1\n if c % 3 == 0:\n return 'Yes'", "def is_power_of_eight(n):\n d = n\n if n == 1:\n return 'Yes'\n elif n % 8 != 0:\n return 'No'\n if n % 8 == 0:\n while d >= 1:\n d = d / 8\n if d == 1:\n return 'Yes'\n elif d % 8 != 0:\n return 'No'", "import math\n\ndef is_power_of_eight(n):\n k = int(math.log2(n))\n if 2 ** k == n and k % 3 == 0:\n return 'Yes'\n return 'No'", "from math import log2\n\ndef is_power_of_eight(n):\n p = log2(n) // 3\n return ['No', 'Yes'][pow(8, p) == n]", "def is_power_of_eight(n):\n import math\n c = round(math.log(n) / math.log(8))\n if n == pow(8, c):\n return 'Yes'\n else:\n return 'No'", "from math import *\n\ndef is_power_of_eight(n):\n a = log(n)\n b = log(8)\n res1 = round(a // b, 3)\n res2 = round(a / b, 3)\n return 'Yes' if res1 == res2 else 'No'", "def is_power_of_eight(n):\n for x in range(1, 200):\n if n == 8 ** x:\n return 'Yes'\n elif 8 ** x > n:\n return 'No'", "def is_power_of_eight(n):\n if n == 0:\n return 'No'\n if n & n - 1 == 0:\n return 'Yes'\n else:\n return 'No'", "def is_power_of_eight(n):\n return 'Yes' if n == 1 or (n % 8 == 0 and bin(n).count('1') == 1) else 'No'", "import math\n\ndef is_power_of_eight(n):\n d = math.log(n, 8)\n d = round(d, 5)\n if int(d) == d:\n return 'Yes'\n else:\n return 'No'", "import math\n\ndef is_power_of_eight(n):\n countOne = countZero = 0\n N = n\n while n:\n if n & 1:\n countOne += 1\n else:\n countZero += 1\n n = n >> 1\n result = self.checkMSBisOne(N) and countOne == 1 and (countZero % 3 == 0)\n return 'Yes' if result else 'No'\n\ndef checkMSBisOne(n):\n siz = self.getLength(n)\n return n >> siz - 1 & 1 == 1\n\ndef getLength(n):\n return int(math.log2(n)) + 1", "def is_power_of_eight(n):\n x = n\n if x and x & x - 1 == 0:\n while x > 0:\n x = x >> 3\n if x & 1:\n return 'Yes'\n return 'No'", "def is_power_of_eight(n):\n count = 0\n a = 0\n while n != 0:\n if n & 1 == 0:\n count += 1\n else:\n a += 1\n n = n >> 1\n if a == 1 and count % 3 == 0:\n return 'Yes'\n return 'No'", "def is_power_of_eight(n):\n b = bin(n)[2:]\n z = b.count('8')\n o = b.count('1')\n if z % 3 == 0 and o == 1:\n return 'Yes'\n return 'No'", "def is_power_of_eight(n):\n if n and (not n & n - 1) and (not n & 3067833782):\n return 'Yes'\n else:\n return 'No'", "def is_power_of_eight(n):\n a = 0\n b = 8 ** a\n while b < n:\n a = a + 1\n b = 8 ** a\n if b == n:\n return 'Yes'\n return 'No'", "def is_power_of_eight(n):\n a = 0\n b = 2 ** (3 * a)\n while b < n:\n a = a + 1\n b = 2 ** (3 * a)\n if b == n:\n return 'Yes'\n return 'No'", "import math\n\ndef is_power_of_eight(n):\n while n > 1:\n if n % 8 != 0:\n return 'No'\n n //= 8\n if n == 1:\n return 'Yes'"], "starter_code": "def is_power_of_eight(n):\n", "input_output": {"inputs": ["64", "75"], "outputs": ["Yes", "No"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/check-if-a-integer-is-power-of-8-or-not2537/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(N))", "entry_point": "is_power_of_eight", "task_id": "TACO_lite/70", "example": [[], []]} +{"requirement": "In a string composed of 'L', 'R', and 'X' characters, like \"RXXLRXRXL\", a move consists of either replacing one occurrence of \"XL\" with \"LX\", or replacing one occurrence of \"RX\" with \"XR\". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.\n\nExample:\n\n\nInput: start = \"RXXLRXRXL\", end = \"XRLXXRRLX\"\nOutput: True\nExplanation:\nWe can transform start to end following these steps:\nRXXLRXRXL ->\nXRXLRXRXL ->\nXRLXRXRXL ->\nXRLXXRRXL ->\nXRLXXRRLX\n\n\nNote:\n\n\n 1 <= len(start) = len(end) <= 10000.\n Both start and end will only consist of characters in {'L', 'R', 'X'}.", "solutions": ["def isToeplitzMatrix(matrix):\n if not matrix:\n return False\n colSize = len(matrix[0]) - 1\n for row in range(len(matrix) - 1):\n if matrix[row][:colSize] != matrix[row + 1][1:colSize + 1]:\n return False\n return True", "def isToeplitzMatrix(matrix):\n return all((True if len(matrix[i]) == 1 or matrix[i][:-1] == matrix[i + 1][1:] else False for i in range(len(matrix) - 1)))", "def isToeplitzMatrix(matrix):\n (x, y) = (len(matrix[0]), len(matrix))\n for i in range(x - 1):\n for j in range(y - 1):\n if matrix[j][i] != matrix[j + 1][i + 1]:\n return False\n return True", "def isToeplitzMatrix(matrix):\n for c in range(len(matrix) - 1):\n for r in range(len(matrix[0]) - 1):\n if matrix[c][r] != matrix[c + 1][r + 1]:\n return False\n return True", "def isToeplitzMatrix(matrix):\n (M, N) = (len(matrix), len(matrix[0]))\n if M == 1:\n return True\n prev_row = matrix[0][:-1]\n for row in matrix[1:]:\n if row[1:] != prev_row:\n return False\n prev_row = row[:-1]\n return True", "def isToeplitzMatrix(matrix):\n vmap = collections.defaultdict(set)\n (M, N) = (len(matrix), len(matrix[0]))\n for x in range(M):\n for y in range(N):\n vmap[y - x].add(matrix[x][y])\n if len(vmap[y - x]) > 1:\n return False\n return True", "def isToeplitzMatrix(matrix):\n hashMap = {}\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if hashMap.get(i - j, 'no') != 'no':\n if hashMap[i - j] != matrix[i][j]:\n return False\n else:\n hashMap[i - j] = matrix[i][j]\n return True", "def isToeplitzMatrix(matrix):\n rows = len(matrix)\n cols = len(matrix[0])\n for i in range(rows - 1):\n for j in range(cols - 1):\n if matrix[i][j] != matrix[i + 1][j + 1]:\n return False\n return True", "def isToeplitzMatrix(matrix):\n for i in range(0, len(matrix)):\n for j in range(0, len(matrix[0])):\n r = i + 1\n c = j + 1\n while r < len(matrix) and c < len(matrix[0]):\n if matrix[i][j] == matrix[r][c]:\n r += 1\n c += 1\n continue\n else:\n return False\n return True", "def isToeplitzMatrix1(matrix):\n (row, col) = (len(matrix), len(matrix[0]))\n for j in range(col):\n a = 0\n while a + 1 < row and j + a + 1 < col:\n if matrix[a][j + a] == matrix[a + 1][j + a + 1]:\n a += 1\n else:\n return False\n for i in range(row):\n a = 0\n while a + 1 < col and i + 1 + a < row:\n if matrix[i + a][a] == matrix[i + a + 1][a + 1]:\n a += 1\n else:\n return False\n return True\n\ndef isToeplitzMatrix(m):\n return all((m[i][j] == m[i + 1][j + 1] for i in range(len(m) - 1) for j in range(len(m[0]) - 1)))", "def isToeplitzMatrix(matrix):\n result = True\n for i in range(len(matrix) - 1):\n result = result and matrix[i][:-1] == matrix[i + 1][1:]\n return result"], "starter_code": "def cantransform(start: str, end: str) -> bool:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Two Pointers", "String"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Amortized analysis"], "skill_types": ["Amortized analysis"], "url": "https://leetcode.com/problems/swap-adjacent-in-lr-string/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "cantransform", "task_id": "TACO_lite/95", "example": [[["RXXLRXRXL", "XRLXXRRLX"]], ["True"]]} +{"requirement": "Given a square grid of integers arr, a falling path with non-zero shifts is a choice of exactly one element from each row of arr, such that no two elements chosen in adjacent rows are in the same column.\nReturn the minimum sum of a falling path with non-zero shifts.\n \nExample 1:\nInput: arr = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: 13\nExplanation: \nThe possible falling paths are:\n[1,5,9], [1,5,7], [1,6,7], [1,6,8],\n[2,4,8], [2,4,9], [2,6,7], [2,6,8],\n[3,4,8], [3,4,9], [3,5,7], [3,5,9]\nThe falling path with the smallest sum is [1,5,7], so the answer is 13.\n\n \nConstraints:\n\n1 <= arr.length == arr[i].length <= 200\n-99 <= arr[i][j] <= 99", "solutions": ["def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [0] * len(arr[0])\n for (r, row) in enumerate(arr):\n minNb = min(dp)\n min1 = dp.index(minNb)\n dp[min1] = float('inf')\n min2 = dp.index(min(dp))\n dp[min1] = minNb\n for c in range(len(row)):\n if c != min1:\n row[c] += dp[min1]\n else:\n row[c] += dp[min2]\n dp = row[:]\n return min(dp)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n for i in range(1, len(arr)):\n r = heapq.nsmallest(2, arr[i - 1])\n for j in range(len(arr[0])):\n arr[i][j] += r[1] if arr[i - 1][j] == r[0] else r[0]\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n for i in range(1, (n := len(arr))):\n for j in range(n):\n t = min(arr[i - 1][0:j] + arr[i - 1][j + 1:n])\n arr[i][j] += t\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n for row in range(1, len(arr)):\n for col in range(0, len(arr)):\n if col == 0:\n arr[row][col] += min(arr[row - 1][1:])\n elif col == len(arr) - 1:\n arr[row][col] += min(arr[row - 1][:-1])\n else:\n arr[row][col] += min(arr[row - 1][:col] + arr[row - 1][col + 1:])\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = arr[0][:]\n for (i, costs) in enumerate(arr[1:], 1):\n prev = dp[:]\n for (j, cost) in enumerate(costs):\n dp[j] = cost + min(prev[:j] + prev[j + 1:])\n return min(dp)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n (nRow, nCol) = (len(arr), len(arr[0]))\n pathSum = arr.copy()\n for row in range(-2, -nCol - 1, -1):\n for col in range(nCol):\n pathSum[row][col] += min(pathSum[row + 1][0:col] + pathSum[row + 1][col + 1:])\n return min(pathSum[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr)\n dp = [[0 for x in range(m)] for x in range(m)]\n for i in range(m):\n for j in range(m):\n if i == 0:\n dp[i][j] = arr[i][j]\n else:\n temp = dp[i - 1].copy()\n temp.pop(j)\n dp[i][j] = arr[i][j] + min(temp)\n return min(dp[m - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr)\n n = len(arr[0])\n if m == 1:\n return arr[0][0]\n\n def get_min_neighbors(i, j):\n (a, row_prev[j]) = (row_prev[j], float('inf'))\n min_val = min(row_prev)\n row_prev[j] = a\n return min_val\n row_prev = arr[0]\n cur = [0] * n\n global_min = float('inf')\n for row in range(1, m):\n for col in range(n):\n cur[col] = get_min_neighbors(row, col) + arr[row][col]\n if row == m - 1 and cur[col] < global_min:\n global_min = cur[col]\n row_prev = cur[:]\n return global_min", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n for i in range(1, n):\n for j in range(n):\n prevmin = min(arr[i - 1])\n temp = arr[i - 1][:]\n temp.remove(prevmin)\n prevmin2 = min(temp)\n arr[i][j] += prevmin if prevmin != arr[i - 1][j] else prevmin2\n return min(arr[n - 1])", "def minfallingpathsum(dp: List[List[int]]) -> int:\n for i in range(1, len(dp)):\n for j in range(len(dp[i])):\n dp[i][j] = min(dp[i - 1][:j] + dp[i - 1][j + 1:]) + dp[i][j]\n return min(dp[-1])", "from heapq import nsmallest\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n for i in range(m - 1)[::-1]:\n for j in range(n):\n ans = nsmallest(2, arr[i + 1])\n arr[i][j] += ans[0] if ans[0] != arr[i + 1][j] else ans[1]\n return min(arr[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n A = arr\n n = len(A)\n dp = [[float('inf') for _ in range(n)] for _ in range(n)]\n for c in range(n):\n dp[0][c] = A[0][c]\n for r in range(1, n):\n for c in range(n):\n prev = heapq.nsmallest(2, dp[r - 1])\n dp[r][c] = A[r][c]\n dp[r][c] += prev[1] if dp[r - 1][c] == prev[0] else prev[0]\n return min(dp[n - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n if not arr:\n return 0\n length = len(arr)\n for i in range(1, length):\n for j in range(length):\n if j == 0:\n arr[i][j] += min(arr[i - 1][j + 1:])\n elif j == len(arr) - 1:\n arr[i][j] += min(arr[i - 1][:-1])\n else:\n arr[i][j] += min(arr[i - 1][:j] + arr[i - 1][j + 1:])\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n dp = [[0] * n for _ in range(m + 1)]\n for i in range(1, m + 1):\n for j in range(n):\n (m0, m1) = heapq.nsmallest(2, dp[i - 1])\n dp[i][j] = arr[i - 1][j] + (m0 if dp[i - 1][j] != m0 else m1)\n return min(dp[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n self.memo = {}\n if not arr:\n return 0\n possible_values = []\n for column in range(len(arr[0])):\n possible_values.append(self.visit_row(arr, 0, column))\n return min(possible_values)\n\ndef visit_row(arr, i, j):\n if (i, j) in self.memo:\n return self.memo[i, j]\n if i == len(arr) - 1:\n return arr[i][j]\n val = arr[i][j]\n possible_values = []\n prev_val = 999999999999999\n for k in [i[0] for i in sorted(enumerate(arr[i + 1]), key=lambda x: x[1])]:\n if k == j:\n continue\n next_val = self.visit_row(arr, i + 1, k)\n possible_values.append(next_val)\n if prev_val < next_val:\n break\n prev_val = next_val\n val += min(possible_values)\n self.memo[i, j] = val\n return val", "def minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n for i in range(1, m):\n min1 = 0\n min2 = 1\n for j in range(1, n):\n if arr[i - 1][j] < arr[i - 1][min1]:\n min2 = min1\n min1 = j\n elif arr[i - 1][j] < arr[i - 1][min2]:\n min2 = j\n for j in range(n):\n if j == min1:\n arr[i][j] += arr[i - 1][min2]\n else:\n arr[i][j] += arr[i - 1][min1]\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n\n def second_smallest(nums):\n (s1, s2) = (float('inf'), float('inf'))\n for num in nums:\n if num <= s1:\n (s1, s2) = (num, s1)\n elif num < s2:\n s2 = num\n return s2\n n = len(arr)\n for i in range(1, n):\n for j in range(n):\n prevmin = min(arr[i - 1])\n prevmin2 = second_smallest(arr[i - 1])\n arr[i][j] += prevmin if prevmin != arr[i - 1][j] else prevmin2\n return min(arr[n - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n if not arr:\n return 0\n (rows, cols) = (len(arr), len(arr[0]))\n for r in range(1, rows):\n for c in range(cols):\n val = float('inf')\n for x in range(cols):\n if arr[r - 1][x] < val and x != c:\n val = arr[r - 1][x]\n arr[r][c] += val\n return min(arr[-1])", "def minfallingpathsum(cost: List[List[int]]) -> int:\n cols = len(cost[0])\n dp = cost[0]\n for h in range(1, len(cost)):\n dp = [cost[h][m] + min((dp[prevMat] for prevMat in range(0, cols) if prevMat != m)) for m in range(0, cols)]\n return min(dp)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n pre = arr[0][:]\n for i in range(1, m):\n dp = []\n for j in range(n):\n dp += [arr[i][j] + min((pre[k] for k in range(n) if k != j))]\n pre = dp\n return min(dp)", "def minfallingpathsum(A):\n (m, n) = (len(A), len(A[0]))\n dp = A[0].copy()\n for x in range(1, m):\n tmp = [0] * n\n for y in range(n):\n tmp[y] = min((dp[py] for py in range(n) if y != py)) + A[x][y]\n (dp, tmp) = (tmp, dp)\n return min(dp)", "import numpy as np\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n dp = arr[0]\n for r in range(1, len(arr)):\n new_dp = [i for i in dp]\n for c in range(len(arr)):\n lst = [dp[j] for j in range(len(arr)) if j != c]\n new_dp[c] = min(lst) + arr[r][c]\n dp = new_dp\n return int(min(dp))", "def minfallingpathsum(arr: List[List[int]]) -> int:\n while len(arr) > 1:\n bottom = arr.pop()\n for i in range(len(arr[-1])):\n arr[-1][i] += min((el for (j, el) in enumerate(bottom) if i != j))\n return min(arr[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n cumSum = [[0 for j in range(len(arr[0]) + 1)] for i in range(len(arr) + 1)]\n for i in range(len(arr)):\n for j in range(len(arr[0])):\n cumSum[i + 1][j + 1] = arr[i][j] + cumSum[i + 1][j] + cumSum[i][j + 1] - cumSum[i][j]\n dp = [arr[i] for i in range(len(arr))]\n for i in range(1, len(dp)):\n for j in range(len(dp[0])):\n (i1, j1) = (i + 1, j + 1)\n aboveDP = min([x for (c, x) in enumerate(dp[i - 1]) if c != j])\n dp[i][j] = cumSum[i1][j1] - cumSum[i][j1] - cumSum[i1][j] + cumSum[i][j] + aboveDP\n return min(dp[-1])", "def minfallingpathsum(cost: List[List[int]]) -> int:\n numHouses = len(cost)\n cols = len(cost[0])\n dp = cost[0]\n for h in range(1, numHouses):\n newRow = [0 for _ in range(cols)]\n for m in range(0, cols):\n prevCost = min((dp[prevMat] for prevMat in range(0, cols) if prevMat != m))\n newRow[m] = cost[h][m] + prevCost\n dp = newRow\n return min(dp)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n cumSum = [[0 for j in range(len(arr[0]) + 1)] for i in range(len(arr) + 1)]\n for i in range(len(arr)):\n for j in range(len(arr[0])):\n cumSum[i + 1][j + 1] = arr[i][j] + cumSum[i + 1][j] + cumSum[i][j + 1] - cumSum[i][j]\n dp = [arr[i] for i in range(len(arr))]\n for i in range(1, len(dp)):\n for j in range(len(dp[0])):\n (csR, csC) = (i + 1, j + 1)\n (leftR, leftC) = (i, j + 1)\n (topR, topC) = (i + 1, j)\n (addR, addC) = (i, j)\n aboveDP = min([x for (c, x) in enumerate(dp[i - 1]) if c != j])\n dp[i][j] = cumSum[csR][csC] - cumSum[leftR][leftC] - cumSum[topR][topC] + cumSum[addR][addC] + aboveDP\n return min(dp[-1])", "import heapq\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n while len(arr) > 1:\n row = arr.pop()\n heap = []\n for i in range(len(row)):\n if not heap:\n heap = [row[x] for x in range(len(row)) if x != i]\n heapq.heapify(heap)\n else:\n if heap[0] == row[i]:\n heapq.heappop(heap)\n heapq.heappush(heap, row[i - 1])\n arr[-1][i] += heap[0]\n return min(arr[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n for i in range(len(arr) - 2, -1, -1):\n a = sorted(([arr[i + 1][j], j] for j in range(len(arr[0]))))\n for j in range(len(arr[0])):\n for (v, idx) in a:\n if idx != j:\n arr[i][j] += v\n break\n return min(arr[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp_mtx = [[0] * len(arr[0]) for _ in range(len(arr))]\n for i in range(len(arr)):\n for j in range(len(arr[0])):\n if i == 0:\n dp_mtx[i][j] = arr[i][j]\n else:\n dp_mtx[i][j] = arr[i][j] + min((dp_mtx[i - 1][k] for k in range(len(arr[0])) if k != j))\n return min(dp_mtx[len(arr) - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n for i in range(1, n):\n for j in range(n):\n prevNonAdj = [arr[i - 1][k] for k in range(n) if k != j]\n arr[i][j] += min(prevNonAdj)\n return min(arr[n - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [[float('inf')] + i + [float('inf')] for i in arr]\n for i in range(1, len(dp)):\n for j in range(1, len(dp[0]) - 1):\n dp[i][j] = dp[i][j] + min([dp[i - 1][k] for k in range(len(dp[i - 1])) if k != j])\n return min(dp[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n dp1 = [None for i in range(n)]\n for i in range(0, n):\n dp1[i] = arr[0][i]\n for i in range(1, n):\n dp2 = [None for i in range(n)]\n for j in range(0, n):\n minList = []\n for k in range(0, n):\n if k == j:\n continue\n minList.append(dp1[k])\n dp2[j] = min(minList) + arr[i][j]\n dp1 = dp2\n return min(dp2)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n dp = [[float('inf')] * n for _ in range(m)]\n for i in range(m):\n for j in range(n):\n if i == 0:\n dp[0][j] = arr[0][j]\n else:\n dp[i][j] = arr[i][j] + min((dp[i - 1][x] for x in range(n) if x != j))\n return min(dp[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n if not arr:\n return 0\n (m, n) = (len(arr), len(arr[0]))\n for i in range(1, m):\n for j in range(n):\n arr[i][j] = min([arr[i - 1][col] for col in range(n) if col != j]) + arr[i][j]\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n R = len(arr)\n C = len(arr[0])\n dp = [[float('inf') for j in range(C)] for i in range(R)]\n for i in range(C):\n dp[0][i] = arr[0][i]\n for r in range(1, R):\n for c in range(C):\n dp[r][c] = arr[r][c] + min((dp[r - 1][k] if k != c else float('inf') for k in range(C)))\n return min(dp[R - 1])", "def minfallingpathsum(A: List[List[int]]) -> int:\n for i in range(len(A) - 1):\n x = [0 for _ in A]\n for j in range(len(A)):\n ls = []\n for k in range(len(A)):\n if not j == k:\n ls.append(A[0][k])\n x[j] = A[i + 1][j] + min(ls)\n A[0] = x\n return min(A[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n memo = {}\n return self.helper(0, None, arr, memo)\n\ndef helper(index, notAllowed, arr, memo):\n if index == len(arr):\n return 0\n elif (index, notAllowed) in memo:\n return memo[index, notAllowed]\n else:\n (maxOne, maxTwo) = self.getMaxTwo(notAllowed, arr[index])\n useOne = arr[index][maxOne] + self.helper(index + 1, maxOne, arr, memo)\n useTwo = arr[index][maxTwo] + self.helper(index + 1, maxTwo, arr, memo)\n res = min(useOne, useTwo)\n memo[index, notAllowed] = res\n return res\n\ndef getMaxTwo(blocked, arr):\n minOne = None\n minIndex = None\n for i in range(len(arr)):\n if i == blocked:\n continue\n else:\n curr_num = arr[i]\n if minOne == None or curr_num < minOne:\n minOne = curr_num\n minIndex = i\n minTwo = None\n minIndexTwo = None\n for j in range(len(arr)):\n if j == blocked or j == minIndex:\n continue\n else:\n curr_num = arr[j]\n if minTwo == None or curr_num < minTwo:\n minTwo = curr_num\n minIndexTwo = j\n return (minIndex, minIndexTwo)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n for i in range(1, len(arr)):\n for j in range(len(arr[0])):\n above = set()\n for k in range(len(arr[0])):\n if k != j:\n above.add(arr[i - 1][k])\n arr[i][j] = arr[i][j] + min(above)\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [arr[i] for i in range(len(arr))]\n for i in range(1, len(arr)):\n for j in range(len(arr[0])):\n opts = [arr[i][j] + x for (c, x) in enumerate(arr[i - 1]) if c != j]\n dp[i][j] = min(opts)\n return min(dp[-1])", "def minfallingpathsum(A: List[List[int]]) -> int:\n costs = [[None for i in range(len(A))] for j in range(len(A[0]))]\n for j in range(len(A)):\n costs[0] = A[0]\n for i in range(1, len(A)):\n for j in range(len(A)):\n parents = list()\n for p in range(len(A)):\n if p != j:\n parents.append(costs[i - 1][p])\n costs[i][j] = min(parents) + A[i][j]\n return min(costs[len(A) - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n T = [[0 for _ in range(len(arr))] for _ in range(len(arr))]\n T[0] = arr[0]\n for i in range(1, len(arr)):\n for j in range(len(arr)):\n T[i][j] = arr[i][j] + min([T[i - 1][c] for c in range(len(arr)) if c != j])\n return min(T[-1])", "import heapq as pq\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n rows = len(arr)\n cols = len(arr[0])\n min_vals = []\n for i in range(cols):\n pq.heappush(min_vals, (arr[0][i], i))\n min_vals = pq.nsmallest(2, min_vals)\n for i in range(1, cols):\n new_min_vals = []\n (min_val2, _) = min_vals.pop()\n (min_val, min_col) = min_vals.pop()\n for col in range(cols):\n arr[i][col] += min_val if min_col != col else min_val2\n pq.heappush(new_min_vals, (arr[i][col], col))\n min_vals = pq.nsmallest(2, new_min_vals)\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [[0] * len(arr[0]) for _ in arr]\n for i in range(len(arr)):\n if i == 0:\n dp[i] = arr[i]\n else:\n for j in range(len(arr[0])):\n dp[i][j] = self.min_exclude(dp[i - 1], j) + arr[i][j]\n return min(dp[-1])\n\ndef min_exclude(array, exclude):\n if len(array) == 0:\n return None\n out = float('inf')\n for i in range(len(array)):\n if i != exclude:\n out = min(out, array[i])\n return out", "def minfallingpathsum(arr: List[List[int]]) -> int:\n A = arr\n for i in range(1, len(A)):\n for j in range(len(A[0])):\n if j == 0:\n A[i][j] += min([A[i - 1][j] for j in range(1, len(A))])\n elif j == len(A[0]) - 1:\n A[i][j] += min([A[i - 1][j] for j in range(0, len(A) - 1)])\n else:\n A[i][j] += min([A[i - 1][j] for j in [x for x in range(len(A)) if x != j]])\n return min(A[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr)\n for i in range(1, m):\n for j in range(m):\n res = float('inf')\n for x in range(m):\n if x != j:\n if arr[i][j] + arr[i - 1][x] < res:\n res = arr[i][j] + arr[i - 1][x]\n arr[i][j] = res\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [[0 for _ in range(len(arr))] for _ in range(len(arr[0]))]\n for i in range(len(dp)):\n dp[0][i] = arr[0][i]\n for i in range(1, len(dp)):\n for j in range(len(dp[i])):\n if j == 0:\n dp[i][j] = min((arr[i][j] + dp[i - 1][k] for k in range(1, len(dp[i]))))\n elif j == len(dp[i]) - 1:\n dp[i][j] = min((arr[i][j] + dp[i - 1][k] for k in range(len(dp[i]) - 1)))\n else:\n left_max = min((arr[i][j] + dp[i - 1][k] for k in range(j)))\n right_max = min((arr[i][j] + dp[i - 1][k] for k in range(j + 1, len(dp[i]))))\n dp[i][j] = min(left_max, right_max)\n return min(dp[-1])", "from heapq import nsmallest\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [[0] * len(arr[0]) for _ in range(len(arr))]\n dp[0] = arr[0]\n for i in range(1, len(arr)):\n (min1, min2) = nsmallest(2, arr[i - 1])\n for j in range(len(arr[0])):\n if arr[i - 1][j] == min1:\n arr[i][j] += min2\n else:\n arr[i][j] += min1\n return min(arr[-1])", "from functools import lru_cache\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n if not arr:\n return 0\n cols = set(range(len(arr[0])))\n\n def path_sum(row, col):\n ret = arr[row][col]\n if row == len(arr) - 1:\n return ret\n other_cols = cols - {col}\n ret += min((path_sum(row + 1, _) for _ in other_cols))\n return ret\n return min((path_sum(0, _) for _ in cols))", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [[0 for _ in range(len(arr[0]))] for _ in range(len(arr))]\n for i in range(len(dp[0])):\n dp[0][i] = arr[0][i]\n for i in range(1, len(dp)):\n for j in range(len(dp[0])):\n mi = -1\n for k in range(len(dp[0])):\n if not j == k:\n if mi == -1 or dp[i - 1][k] + arr[i][j] < mi:\n mi = dp[i - 1][k] + arr[i][j]\n dp[i][j] = mi\n return min(dp[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n\n def dp(i, j):\n if i == 0:\n return arr[0][j]\n if i == len(arr):\n return min((dp(i - 1, k) for k in range(len(arr[0]))))\n return arr[i][j] + min((dp(i - 1, k) for k in range(len(arr[0])) if k != j))\n return dp(len(arr), -1)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n total = 0\n for row in range(len(arr) - 1):\n (row1_min, row2_min) = (min(arr[row]), min(arr[row + 1]))\n (i1, i2) = (arr[row].index(row1_min), arr[row + 1].index(row2_min))\n if i1 != i2:\n total += row1_min\n else:\n total = False\n break\n if total:\n return total + min(arr[-1])\n dp = [[arr[j][i] if j == 0 else float('inf') for i in range(len(arr))] for j in range(len(arr))]\n for row in range(len(arr) - 1):\n for col in range(len(arr[row])):\n for next_col in range(len(arr[row])):\n if next_col != col:\n dp[row + 1][next_col] = min(dp[row + 1][next_col], dp[row][col] + arr[row + 1][next_col])\n return min(dp[len(arr) - 1])", "from typing import List\nfrom functools import lru_cache\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n\n def helper(r, c):\n if r == m:\n return 0\n return arr[r][c] + min((helper(r + 1, nc) for nc in range(n) if nc != c))\n return min((helper(0, c) for c in range(n)))", "from functools import lru_cache\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n\n def dp(i, j):\n if not (0 <= i < len(arr) and 0 <= j < len(arr[0])):\n return float('inf')\n if i == len(arr) - 1:\n return arr[i][j]\n return arr[i][j] + min((dp(i + 1, k) for k in range(len(arr[0])) if k != j))\n return min((dp(0, j) for j in range(len(arr[0]))))", "def minfallingpathsum(arr: List[List[int]]) -> int:\n for i in range(1, len(arr)):\n for j in range(len(arr[0])):\n above = []\n for k in range(len(arr[0])):\n if k != j:\n heapq.heappush(above, arr[i - 1][k])\n arr[i][j] = arr[i][j] + above[0]\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n for i in range(1, m):\n for j in range(n):\n m = float('inf')\n for k in range(n):\n if k == j:\n continue\n m = min(m, arr[i - 1][k])\n arr[i][j] += m\n return min(arr[-1])", "import itertools\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n (nr, nc) = (len(arr), len(arr[0]))\n for (r_i, c_i) in itertools.product(list(range(nr - 2, -1, -1)), list(range(nc))):\n downs = [(r_i + 1, d_c) for d_c in range(nc) if d_c != c_i]\n min_downs = min([arr[d_r][d_c] for (d_r, d_c) in downs])\n arr[r_i][c_i] += min_downs\n return min([arr[0][c] for c in range(nc)])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n N = len(arr)\n dp = [[0] * N for _ in range(N)]\n for i in range(N):\n dp[N - 1][i] = arr[N - 1][i]\n for r in range(N - 2, -1, -1):\n for c in range(N):\n min_c = float('inf')\n for n_c in range(N):\n if n_c == c:\n continue\n min_c = min(min_c, arr[r + 1][n_c])\n dp[r][c] = min_c + arr[r][c]\n arr[r][c] = dp[r][c]\n res = float('inf')\n for i in range(N):\n res = min(res, dp[0][i])\n return res", "def minfallingpathsum(arr: List[List[int]]) -> int:\n from copy import deepcopy\n v = deepcopy(arr)\n for i in range(len(arr) - 2, -1, -1):\n for j in range(len(arr[0])):\n minn = float('inf')\n for k in range(len(arr[0])):\n if j != k:\n minn = min(minn, v[i + 1][k])\n v[i][j] += minn\n return min(v[0])", "def minfallingpathsum(A: List[List[int]]) -> int:\n g = [[inf] * len(a) for a in A]\n\n def get(i, j):\n m = inf\n for k in range(0, len(A[0])):\n if k != j:\n m = min(m, g[i - 1][k])\n return m\n for i in range(len(g)):\n for j in range(len(g[0])):\n if i == 0:\n g[i][j] = A[i][j]\n else:\n g[i][j] = min(g[i][j], get(i, j) + A[i][j])\n return min(g[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [[0 for i in range(len(arr))] for j in range(len(arr))]\n for i in range(len(arr)):\n dp[0][i] = arr[0][i]\n for i in range(1, len(arr)):\n for j in range(len(arr)):\n m = 9999999\n for k in range(len(arr)):\n if k != j:\n m = min(m, dp[i - 1][k])\n dp[i][j] = arr[i][j] + m\n m = 99999999\n for i in range(len(arr)):\n m = min(m, dp[len(arr) - 1][i])\n return m", "def minfallingpathsum(arr: List[List[int]]) -> int:\n if not arr:\n return 0\n R = C = len(arr)\n for r in range(1, R):\n for c in range(0, C):\n m = float('inf')\n for i in range(C):\n if i != c:\n m = min(m, arr[r - 1][i])\n arr[r][c] += m\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n if arr is None or len(arr) == 0 or len(arr[0]) == 0:\n return 0\n for i in range(1, len(arr)):\n for j in range(len(arr[0])):\n temp = float('inf')\n for last_col in range(len(arr[0])):\n if last_col != j:\n temp = min(temp, arr[i - 1][last_col])\n arr[i][j] += temp\n ans = float('inf')\n for i in range(len(arr[0])):\n ans = min(ans, arr[-1][i])\n return ans", "def minfallingpathsum(arr: List[List[int]]) -> int:\n import math\n n = len(arr)\n if n == 0:\n return 0\n k = len(arr[0])\n for house in range(1, n):\n for color in range(k):\n best = math.inf\n for prev_color in range(k):\n if color == prev_color:\n continue\n best = min(best, arr[house - 1][prev_color])\n arr[house][color] += best\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n rows = len(arr)\n columns = len(arr[0])\n for i in range(1, rows):\n for j in range(columns):\n minimum = float('inf')\n for k in range(columns):\n if k != j:\n minimum = min(minimum, arr[i - 1][k])\n arr[i][j] = arr[i][j] + minimum\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n for i in range(1, n):\n lowest = min(arr[i - 1])\n lowestCount = 0\n secondLowest = float('inf')\n for j in range(len(arr[0])):\n if arr[i - 1][j] == lowest:\n lowestCount += 1\n if arr[i - 1][j] > lowest:\n secondLowest = min(secondLowest, arr[i - 1][j])\n if lowestCount >= 2:\n secondLowest = lowest\n for j in range(len(arr[0])):\n if arr[i - 1][j] == lowest:\n arr[i][j] += secondLowest\n else:\n arr[i][j] += lowest\n return min(arr[n - 1])", "import heapq\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n copy = deepcopy(arr)\n for row in range(1, len(arr)):\n smallest = heapq.nsmallest(2, copy[row - 1])\n for col in range(len(arr[0])):\n copy[row][col] += smallest[0] if copy[row - 1][col] != smallest[0] else smallest[1]\n return min(copy[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n if n == 1:\n return arr[0][0]\n MAX_V = int(1000000000.0)\n min_v = [0] * n\n for i in range(n):\n row = arr[i]\n new_min_v = [MAX_V] * n\n scan_min = min_v[-1]\n for i in range(n - 2, -1, -1):\n new_min_v[i] = min(new_min_v[i], scan_min + row[i])\n scan_min = min(scan_min, min_v[i])\n scan_min = min_v[0]\n for i in range(1, n):\n new_min_v[i] = min(new_min_v[i], scan_min + row[i])\n scan_min = min(scan_min, min_v[i])\n min_v = new_min_v\n return min(min_v)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr)\n n = len(arr[0])\n dp = [[float('inf') for j in range(n)] for i in range(m)]\n for j in range(n):\n dp[0][j] = arr[0][j]\n for i in range(1, m):\n min_idx = sec_min_idx = None\n for j in range(n):\n if min_idx is None or dp[i - 1][j] < dp[i - 1][min_idx]:\n sec_min_idx = min_idx\n min_idx = j\n elif sec_min_idx is None or dp[i - 1][j] < dp[i - 1][sec_min_idx]:\n sec_min_idx = j\n for j in range(n):\n if j == min_idx:\n dp[i][j] = dp[i - 1][sec_min_idx] + arr[i][j]\n else:\n dp[i][j] = dp[i - 1][min_idx] + arr[i][j]\n return min(dp[m - 1])", "import heapq\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n (rows, cols) = (len(arr), len(arr[0]))\n for i in range(1, rows):\n (min1, min2) = heapq.nsmallest(2, arr[i - 1])\n for j in range(cols):\n if arr[i - 1][j] == min1:\n arr[i][j] += min2\n else:\n arr[i][j] += min1\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n dp = arr[0][:]\n for i in range(1, n):\n right_min = [math.inf] * (n - 1) + [dp[n - 1]]\n for j in range(n - 2, -1, -1):\n right_min[j] = min(right_min[j + 1], dp[j])\n left_min = math.inf\n for j in range(n):\n prev = left_min\n if j < n - 1:\n prev = min(prev, right_min[j + 1])\n left_min = min(left_min, dp[j])\n dp[j] = prev + arr[i][j]\n return min(dp)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n i = 1\n while i < m:\n a = arr[i - 1][:]\n min1 = a.index(min(a))\n a[min1] = float('inf')\n min2 = a.index(min(a))\n a = arr[i - 1]\n for j in range(n):\n if j == min1:\n arr[i][j] += a[min2]\n else:\n arr[i][j] += a[min1]\n i += 1\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n rows = len(arr)\n for row in range(1, rows):\n nsmall_in_row = heapq.nsmallest(2, arr[row - 1])\n for col in range(0, rows):\n arr[row][col] += nsmall_in_row[1] if nsmall_in_row[0] == arr[row - 1][col] else nsmall_in_row[0]\n return min(arr[-1])", "import heapq\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [[float('inf')] + i + [float('inf')] for i in arr]\n for i in range(1, len(dp)):\n hp = heapq.nsmallest(2, dp[i - 1])\n for j in range(1, len(dp[0]) - 1):\n dp[i][j] += hp[0] if dp[i - 1][j] != hp[0] else hp[1]\n return min(dp[-1])", "def minfallingpathsum(A: List[List[int]]) -> int:\n n = len(A)\n for i in range(n - 2, -1, -1):\n mn = min(A[i + 1])\n idx = A[i + 1].index(mn)\n for j in range(n):\n if j != idx:\n A[i][j] += mn\n elif j == idx:\n dp = [101 for _ in range(n)]\n for k in range(n):\n if k != idx:\n dp[k] = A[i + 1][k]\n A[i][j] += min(dp)\n return min(A[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n import heapq\n dp = arr[0][:]\n for i in range(1, len(arr)):\n heap = list(((v, k) for (k, v) in enumerate(dp)))\n heapq.heapify(heap)\n (min_value, min_pos) = heapq.heappop(heap)\n (alter_value, _) = heapq.heappop(heap)\n new_dp = [v + min_value for v in arr[i]]\n new_dp[min_pos] += alter_value - min_value\n dp = new_dp\n return min(dp)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n copy = deepcopy(arr)\n for row in range(1, len(arr)):\n (min1, ind1, min2, ind2) = (20000, 0, 20000, 0)\n for (i, v) in enumerate(copy[row - 1]):\n if v < min1:\n min1 = v\n ind1 = i\n for (i, v) in enumerate(copy[row - 1]):\n if v < min2 and i != ind1:\n min2 = v\n ind2 = i\n for col in range(len(arr[0])):\n copy[row][col] += copy[row - 1][ind1] if ind1 != col else copy[row - 1][ind2]\n return min(copy[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n\n def findMinOtherThanThis(nums):\n ret = list()\n (left, right) = ([0 for i in range(len(arr))], [0 for i in range(len(arr))])\n left_min = float('inf')\n for (idx, n) in enumerate(nums):\n left[idx] = left_min\n left_min = min(left_min, n)\n right_min = float('inf')\n for idx in range(len(nums) - 1, -1, -1):\n right[idx] = right_min\n right_min = min(right_min, nums[idx])\n for idx in range(len(nums)):\n ret.append(min(left[idx], right[idx]))\n return ret\n if not arr:\n return 0\n m = len(arr)\n n = len(arr[0])\n dp = [[0 for j in range(n)] for i in range(m)]\n for i in range(m - 1, -1, -1):\n for j in range(n):\n if i == m - 1:\n dp[i][j] = arr[i][j]\n else:\n dp[i][j] = arr[i][j] + dp[i + 1][j]\n dp[i] = findMinOtherThanThis(dp[i])\n return min(dp[0])", "def minfallingpathsum(cost: List[List[int]]) -> int:\n cols = len(cost[0])\n dp = cost[0]\n for h in range(1, len(cost)):\n prev = sorted(cost[h - 1])\n for m in range(0, cols):\n cost[h][m] += prev[1] if cost[h - 1][m] == prev[0] else prev[0]\n return min(cost[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n from copy import deepcopy\n from heapq import heapify\n v = deepcopy(arr)\n for i in range(len(arr) - 2, -1, -1):\n s = deepcopy(v[i + 1])\n heapify(s)\n min1 = s[0]\n min2 = min(s[1], s[2])\n for j in range(len(arr[0])):\n if v[i + 1][j] != min1:\n v[i][j] += min1\n else:\n v[i][j] += min2\n return min(v[0])", "import heapq\nimport numpy as np\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n x = len(arr)\n new_count = np.zeros((x, x))\n new_count[0] = arr[0]\n for k in range(1, x):\n previous_line_maxes = heapq.nsmallest(2, new_count[k - 1])\n for index in range(len(arr)):\n if new_count[k - 1][index] == previous_line_maxes[0]:\n value_to_add = previous_line_maxes[1]\n else:\n value_to_add = previous_line_maxes[0]\n new_count[k, index] = value_to_add + arr[k][index]\n return int(min(new_count[-1]))", "import heapq\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n xm = [(0, -1), (0, -1)]\n for i in range(n):\n xm = heapq.nsmallest(2, [(x + xm[1][0], j) if j == xm[0][1] else (x + xm[0][0], j) for (j, x) in enumerate(arr[i])])\n return xm[0][0]", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n\n def getTwo(a):\n pos = {v: k for (k, v) in enumerate(a)}\n (f, s) = sorted(a)[:2]\n return ([f, pos[f]], [s, pos[s]])\n for i in range(1, n):\n pre = getTwo(arr[i - 1])\n for j in range(n):\n if j != pre[0][1]:\n arr[i][j] += pre[0][0]\n else:\n arr[i][j] += pre[1][0]\n return min(arr[-1])", "def minfallingpathsum(A):\n for i in range(1, len(A)):\n r = heapq.nsmallest(2, A[i - 1])\n for j in range(len(A[0])):\n A[i][j] += r[1] if A[i - 1][j] == r[0] else r[0]\n return min(A[-1])", "def minfallingpathsum(dp: List[List[int]]) -> int:\n for i in range(1, len(dp)):\n best2 = sorted(list(enumerate(dp[i - 1])), key=lambda x: x[1])[:2]\n for j in range(len(dp[i])):\n dp[i][j] = [x for x in best2 if x[0] != j][0][1] + dp[i][j]\n return min(dp[-1])", "def scan(row: List[int], n: int) -> (int, int, int):\n best = None\n k = None\n alt = None\n for j in range(n):\n if not best or row[j] < best:\n alt = best\n best = row[j]\n k = j\n elif not alt or row[j] < alt:\n alt = row[j]\n return (best, k, alt)\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n M = [[None for j in range(n)] for i in range(n)]\n for j in range(n):\n M[0][j] = arr[0][j]\n (best, k, alt) = self.scan(M[0], n)\n for i in range(1, n):\n for j in range(n):\n if j != k:\n M[i][j] = arr[i][j] + best\n else:\n M[i][j] = arr[i][j] + alt\n (best, k, alt) = self.scan(M[i], n)\n return best", "def minfallingpathsum(arr: List[List[int]]) -> int:\n iMax = len(arr)\n jMax = len(arr[0])\n dp = {}\n smallest2 = [None for _ in range(iMax)]\n\n def moveDown(preJ, iNow):\n if iNow == iMax:\n return 0\n if (preJ, iNow) in dp:\n return dp[preJ, iNow]\n subAns = float('inf')\n if smallest2[iNow] == None:\n temp1 = float('inf')\n temp1Index = None\n temp2 = float('inf')\n temp2Index = None\n for (j, val) in enumerate(arr[iNow]):\n subAns = val + moveDown(j, iNow + 1)\n if subAns <= temp1:\n (temp1, temp2) = (subAns, temp1)\n (temp1Index, temp2Index) = (j, temp1Index)\n elif subAns <= temp2:\n temp2 = subAns\n temp2Index = j\n smallest2[iNow] = [[temp1Index, temp1], [temp2Index, temp2]]\n if preJ == smallest2[iNow][0][0]:\n subAns = smallest2[iNow][1][1]\n else:\n subAns = smallest2[iNow][0][1]\n dp[preJ, iNow] = subAns\n return subAns\n return moveDown(-1, 0)", "def minfallingpathsum1(arr: List[List[int]]) -> int:\n m = len(arr)\n n = len(arr[0])\n if m == 1:\n return arr[0][0]\n\n def get_min_neighbors(j):\n (a, row_prev[j]) = (row_prev[j], float('inf'))\n min_val = min(row_prev)\n row_prev[j] = a\n return min_val\n row_prev = arr[0]\n cur = [0] * n\n global_min = float('inf')\n for row in range(1, m):\n for col in range(n):\n cur[col] = get_min_neighbors(col) + arr[row][col]\n if row == m - 1 and cur[col] < global_min:\n global_min = cur[col]\n row_prev = cur[:]\n return global_min\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr)\n n = len(arr[0])\n if m == 1:\n return arr[0][0]\n\n def get_min_neighbors():\n min1 = float('inf')\n min2 = float('inf')\n for val in dp:\n if val < min1:\n min2 = min1\n min1 = val\n elif val < min2:\n min2 = val\n return (min1, min2)\n dp = arr[0]\n cur = [0] * n\n global_min = float('inf')\n for row in range(1, m):\n (min1, min2) = get_min_neighbors()\n for col in range(n):\n min_val = min1 if dp[col] != min1 else min2\n cur[col] = min_val + arr[row][col]\n if row == m - 1 and cur[col] < global_min:\n global_min = cur[col]\n dp = cur[:]\n return global_min", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr)\n n = len(arr[0])\n dp = [[0] * n for i in range(m)]\n for j in range(n):\n dp[0][j] = arr[0][j]\n for i in range(1, m):\n sorted_lastrow = sorted([(k, dp[i - 1][k]) for k in range(n)], key=lambda x: x[1])\n (p_index, p) = sorted_lastrow[0]\n (q_index, q) = sorted_lastrow[1]\n for j in range(n):\n lastdp = p if p_index != j else q\n dp[i][j] = lastdp + arr[i][j]\n return min(dp[m - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr[0])\n table = [arr[0][i] for i in range(m)]\n\n def get_mins(table):\n cur_min = int(1000000000.0)\n cur_min_i = -1\n next_cur_min = int(1000000000.0)\n next_cur_min_i = -1\n for (i, x) in enumerate(table):\n if x <= cur_min:\n (cur_min, cur_min_i) = (x, i)\n for (i, x) in enumerate(table):\n if x <= next_cur_min and i != cur_min_i:\n (next_cur_min, next_cur_min_i) = (x, i)\n return (cur_min, cur_min_i, next_cur_min, next_cur_min_i)\n (cur_min, cur_min_i, next_cur_min, next_cur_min_i) = get_mins(table)\n for i in range(1, len(arr)):\n for j in range(m):\n table[j] = arr[i][j]\n if j != cur_min_i:\n table[j] = arr[i][j] + cur_min\n else:\n table[j] = arr[i][j] + next_cur_min\n (cur_min, cur_min_i, next_cur_min, next_cur_min_i) = get_mins(table)\n return cur_min", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr)\n for i in range(1, m):\n min1 = min(arr[i - 1])\n ind = arr[i - 1].index(min1)\n for j in range(m):\n if ind == j:\n arr[i][j] = arr[i][j] + min(arr[i - 1][0:j] + arr[i - 1][j + 1:])\n else:\n arr[i][j] = arr[i][j] + min1\n return min(arr[-1])", "from collections import Counter\n\ndef get_minset(l):\n left = []\n right = []\n n = len(l)\n for i in range(n):\n if i == 0:\n left.append(l[i])\n right.append(l[n - i - 1])\n else:\n left.append(min(left[-1], l[i]))\n right.append(min(right[-1], l[n - i - 1]))\n right = right[::-1]\n res = []\n for i in range(n):\n if i == 0:\n res.append(right[1])\n elif i == n - 1:\n res.append(left[n - 2])\n else:\n res.append(min(left[i - 1], right[i + 1]))\n return res\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n last = arr[0]\n maxset = self.get_minset(last)\n for i in range(1, len(arr)):\n tmp = []\n for j in range(len(arr[0])):\n tmp.append(maxset[j] + arr[i][j])\n last = tmp\n maxset = self.get_minset(last)\n return min(last)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = 100 * len(arr)\n T = [[0 for _ in range(len(arr))] for _ in range(len(arr))]\n T[0] = arr[0]\n for i in range(1, len(arr)):\n for j in range(len(arr)):\n temp = T[i - 1][j]\n T[i - 1][j] = m\n T[i][j] = arr[i][j] + min(T[i - 1])\n T[i - 1][j] = temp\n return min(T[-1])", "def minfallingpathsum(A: List[List[int]]) -> int:\n if len(A) == 1:\n return min(A[0])\n for i in range(1, len(A)):\n (minValue, minIdx) = (sys.maxsize, -1)\n secondMinValue = sys.maxsize\n for j in range(len(A[0])):\n if A[i - 1][j] < minValue:\n secondMinValue = minValue\n (minValue, minIdx) = (A[i - 1][j], j)\n elif A[i - 1][j] < secondMinValue:\n secondMinValue = A[i - 1][j]\n for j in range(len(A[0])):\n if j == minIdx:\n A[i][j] += secondMinValue\n else:\n A[i][j] += minValue\n return min(A[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [0] * len(arr[0])\n for (r, row) in enumerate(arr):\n for c in range(len(row)):\n row[c] += min(dp[:c] + dp[c + 1:])\n dp = row[:]\n return min(dp)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n dp = [[0 for i in range(n)] for i in range(n)]\n for i in range(n):\n dp[0][i] = arr[0][i]\n for i in range(1, n):\n dp[i][0] = min(dp[i - 1][1:]) + arr[i][0]\n for j in range(1, n - 1):\n minLeft = min(dp[i - 1][:j])\n minRight = min(dp[i - 1][j + 1:])\n dp[i][j] = min(minLeft, minRight) + arr[i][j]\n dp[i][-1] = min(dp[i - 1][:-1]) + arr[i][-1]\n return min(dp[-1])", "def find_smallest_and_second_smallest(a):\n smallest = a[0]\n c = 1\n for i in a:\n if i < smallest:\n smallest = i\n c = 1\n if i == smallest:\n c += 1\n smallest2 = True\n if c == 2:\n smallest2 = 999999\n for i in a:\n if i != smallest:\n smallest2 = min(smallest2, i)\n return (smallest, smallest2)\n\ndef givedp(arr):\n if len(arr) == 1:\n return min(arr[0])\n (a, b) = ('', '')\n for i in range(len(arr) - 1, -1, -1):\n if i != len(arr) - 1:\n for j in range(len(arr[i])):\n if a == arr[i + 1][j] and b != True:\n arr[i][j] += b\n else:\n arr[i][j] += a\n if i != 0:\n (a, b) = self.find_smallest_and_second_smallest(arr[i])\n return min(arr[0])\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n return self.givedp(arr)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n if not arr:\n return 0\n prev = arr[0]\n curr = [0 for i in range(len(prev))]\n for cost in arr[1:]:\n for i in range(len(cost)):\n tmp = prev[:i] + prev[i + 1:]\n curr[i] = min(tmp) + cost[i]\n prev[:] = curr[:]\n return min(prev)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n N = len(arr)\n while len(arr) >= 2:\n cur = arr.pop()\n for i in range(N):\n newa = cur[:i] + cur[i + 1:]\n arr[-1][i] += min(newa)\n return min(arr[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n while len(arr) >= 2:\n row = arr.pop()\n for i in range(len(row)):\n r = row[:i] + row[i + 1:]\n arr[-1][i] += min(r)\n return min(arr[0])", "def minfallingpathsum(A: List[List[int]]) -> int:\n n = len(A)\n dp = [[0 for j in range(n)] for i in range(n)]\n for i in range(n):\n dp[-1][i] = A[-1][i]\n for i in range(n - 2, -1, -1):\n for j in range(n):\n dp[i][j] = A[i][j] + min(dp[i + 1][:j] + dp[i + 1][j + 1:])\n return min(dp[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n num_rows = len(arr)\n num_cols = len(arr[0])\n dp = [[float('inf') for _ in range(num_cols)] for _ in range(num_rows + 1)]\n for col in range(num_cols):\n dp[0][col] = 0\n for row in range(num_rows):\n dp_r = row + 1\n for col in range(num_cols):\n dp[dp_r][col] = min(dp[dp_r - 1][:col] + dp[dp_r - 1][col + 1:]) + arr[row][col]\n return min(dp[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n d = [[float('-inf') for _ in range(n)] for _ in range(n)]\n for y in range(n):\n d[0][y] = arr[0][y]\n for x in range(1, n):\n smallest_two = heapq.nsmallest(2, d[x - 1])\n for y in range(n):\n if d[x - 1][y] == smallest_two[0]:\n d[x][y] = smallest_two[1] + arr[x][y]\n else:\n d[x][y] = smallest_two[0] + arr[x][y]\n ans = float('inf')\n for y in range(n):\n ans = min(ans, d[n - 1][y])\n return ans", "def minfallingpathsum(arr: List[List[int]]) -> int:\n if len(arr) == 1:\n return arr[0][0]\n else:\n Row = len(arr)\n Col = len(arr[0])\n ResultMat = [arr[0]]\n for i in range(1, Row):\n ResultList = []\n for j in range(Col):\n NewList = ResultMat[i - 1]\n NewList = NewList[0:j] + NewList[j + 1:len(NewList)]\n Min = min(NewList)\n Value = Min + arr[i][j]\n ResultList.append(Value)\n ResultMat.append(ResultList)\n return min(ResultMat[Row - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = arr[0]\n n = len(arr[0])\n for row in arr[1:]:\n newdp = row[:]\n for i in range(n):\n temp = dp[:i] + dp[i + 1:]\n newdp[i] += min(temp)\n dp = newdp\n return min(dp)"], "starter_code": "def minfallingpathsum(arr: List[List[int]]) -> int:\n", "input_output": {"fn_name": "minFallingPathSum", "inputs": [[[[1, 2, 3], [6, 6, 7], [7, 8, 9], [], []]]], "outputs": [13]}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Dynamic Programming", "Matrix"], "name": null, "source": "leetcode", "tags": ["Matrices", "Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/minimum-falling-path-sum-ii/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "minfallingpathsum", "task_id": "TACO_lite/79", "example": [[[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]], ["13"]]} +{"requirement": "Given two values ‘a’ and ‘b’ that represent coefficients in “ax – by = 0”, find the smallest values of x and y that satisfy the equation. It may also be assumed that x > 0, y > 0, a > 0 and b > 0.\nExample 1:\nInput: a = 25, b = 35\nOutput: 7 5\nExplaination: 25*7 - 35*5 = 0. And x = 7 \nand y = 5 are the least possible values \nof x and y to get the equation solved.\nExample 2:\nInput: a = 3, b = 7\nOutput: 7 3\nExplaination: For this case x = 7 and \ny = 3 are the least values of x and y \nto satisfy the equation.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function findXY() which takes a and b as input parameters and returns the least possible values of x and y to satisfy the equation.\nExpected Time Complexity: O(log(max(a, b)))\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ a, b ≤ 10^{4}", "solutions": ["def findxy(a, b):\n import math\n n = math.gcd(a, b)\n x = a / n\n y = b / n\n if b / a == y / x:\n return [int(y), int(x)]", "def findxy(a, b):\n i = 2\n n = min(a, b)\n while i != n + 1:\n if a % i == 0 and b % i == 0:\n a = a // i\n b = b // i\n else:\n i += 1\n return (b, a)", "def findxy(a, b):\n\n def gcd(m, n):\n if n == 0:\n return m\n return gcd(n, m % n)\n result = a * b // gcd(a, b)\n x = result // a\n y = result // b\n return (x, y)", "import math\n\ndef findxy(a, b):\n l = math.gcd(a, b)\n return [b // l, a // l]", "def findxy(a, b):\n if a > b:\n greater = a\n else:\n greater = b\n while True:\n if greater % a == 0 and greater % b == 0:\n lcm = greater\n break\n greater += 1\n return (lcm // a, lcm // b)", "from math import gcd\n\ndef findxy(a, b):\n m = gcd(a, b)\n l = []\n l.append(b // m)\n l.append(a // m)\n return l", "def findxy(a, b):\n p = max(a, b)\n q = min(a, b)\n for i in range(1, q + 1):\n if p * i % q == 0:\n break\n j = int(p * i / q)\n if p == a:\n return [i, j]\n else:\n return [j, i]", "def findxy(a, b):\n r = [0] * 2\n if a > b:\n small = b\n else:\n small = a\n for i in range(1, small + 1):\n if a % i == 0 and b % i == 0:\n gcd = i\n lcm = a * b // gcd\n r[0] = lcm // a\n r[1] = lcm // b\n return r", "import math\n\ndef findxy(a, b):\n h = math.gcd(a, b)\n l = a / h * b\n arr = []\n a1 = l / a\n arr.append(int(a1))\n a2 = l / b\n arr.append(int(a2))\n return arr"], "starter_code": "def findxy(a, b):\n", "input_output": {"inputs": ["a = 25, b = 35", "a = 3, b = 7"], "outputs": ["7 5", "7 3"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/find-smallest-values-of-x-and-y-such-that-ax-by-01433/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(max(a, b)))", "entry_point": "findxy", "task_id": "TACO_lite/7", "example": [[], []]} +{"requirement": "A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.)\nWe are given a string S of '0's and '1's, and we may flip any '0' to a '1' or a '1' to a '0'.\nReturn the minimum number of flips to make S monotone increasing.\n \n\nExample 1:\nInput: \"00110\"\nOutput: 1\nExplanation: We flip the last digit to get 00111.\n\n\nExample 2:\nInput: \"010110\"\nOutput: 2\nExplanation: We flip to get 011111, or alternatively 000111.\n\n\nExample 3:\nInput: \"00011000\"\nOutput: 2\nExplanation: We flip to get 00000000.\n\n \nNote:\n\n1 <= S.length <= 20000\nS only consists of '0' and '1' characters.", "solutions": ["def minflipsmonoincr(S: str) -> int:\n onesSoFar = 0\n partial = 0\n for n in S:\n if n == '0':\n partial = min(onesSoFar, partial + 1)\n else:\n onesSoFar += 1\n return partial", "def minflipsmonoincr(S: str) -> int:\n if not S:\n return 0\n n = len(S)\n if n == 1:\n return 0\n total_1s = 0\n total_0s = 0\n for char in S:\n if char == '1':\n total_1s += 1\n else:\n total_0s += 1\n if total_1s == 0 or total_0s == 0:\n return 0\n prefix_sum = 0\n ans = float('inf')\n for i in range(n):\n prefix_sum += 1 if S[i] == '1' else 0\n ans = min(ans, prefix_sum + (n - i - 1 - (total_1s - prefix_sum)))\n return min(ans, total_0s, total_1s)", "def minflipsmonoincr(S: str) -> int:\n at0 = 0\n at1 = 0\n num0 = 0\n for a in S:\n if a == '0':\n at1 = min(at1, at0) + 1\n else:\n at1 = min(at1, at0)\n at0 += 1\n return min(at1, at0)", "def minflipsmonoincr(S: str) -> int:\n str_len = len(S)\n count_arr = [[0, 0] for x in range(str_len)]\n one_start_idx = -1\n for i in range(len(S)):\n if S[i] == '0':\n if i == 0:\n count_arr[i][0] += 1\n count_arr[i][1] = 0\n else:\n count_arr[i][0] = count_arr[i - 1][0] + 1\n count_arr[i][1] = count_arr[i - 1][1]\n else:\n if i == 0:\n count_arr[i][1] += 1\n else:\n count_arr[i][1] = count_arr[i - 1][1] + 1\n count_arr[i][0] = count_arr[i - 1][0]\n if one_start_idx == -1:\n one_start_idx = i\n total_flips = []\n total_flips.append(min(count_arr[str_len - 1][0], count_arr[str_len - 1][1]))\n for i in range(one_start_idx, str_len):\n if i == 0:\n total_flips.append(count_arr[str_len - 1][0] - count_arr[i][0])\n elif i == str_len - 1:\n total_flips.append(count_arr[str_len - 1][0])\n else:\n total_flips.append(count_arr[i - 1][1] + count_arr[str_len - 1][0] - count_arr[i][0])\n return min(total_flips)", "def minflipsmonoincr(S: str) -> int:\n dp = 0\n ones = 0\n for c in S:\n if c == '0':\n dp = min(1 + dp, ones)\n else:\n dp = min(dp, 1 + ones)\n ones += 1\n return dp", "def minflipsmonoincr(S: str) -> int:\n (flip, one) = (0, 0)\n for i in S:\n if i == '1':\n one += 1\n else:\n flip += 1\n flip = min(one, flip)\n return flip", "def minflipsmonoincr(S: str) -> int:\n (n, prefix, total, res) = (len(S), 0, S.count('1'), sys.maxsize)\n for i in range(n + 1):\n res = min(res, prefix + len(S) - i - total + prefix)\n if i < n:\n prefix += 1 if S[i] == '1' else 0\n return res"], "starter_code": "def minflipsmonoincr(S: str) -> int:\n", "input_output": {"fn_name": "minFlipsMonoIncr", "inputs": [["\"00110\""]], "outputs": [2]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Dynamic Programming", "String"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://leetcode.com/problems/flip-string-to-monotone-increasing/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "minflipsmonoincr", "task_id": "TACO_lite/6", "example": [[["00110"], ["010110"], ["00011000"]], ["1", "2", "2"]]} +{"requirement": "A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:\n\n2332 \n110011 \n54322345 \n\nFor a given number `num`, write a function to test if it's a numerical palindrome or not and return a boolean (true if it is and false if not).\n\n```if-not:haskell\nReturn \"Not valid\" if the input is not an integer or less than `0`.\n```\n```if:haskell\nReturn `Nothing` if the input is less than `0` and `Just True` or `Just False` otherwise.\n```\n\nOther Kata in this Series:\nNumerical Palindrome #1\nNumerical Palindrome #1.5\nNumerical Palindrome #2\nNumerical Palindrome #3\nNumerical Palindrome #3.5\nNumerical Palindrome #4\nNumerical Palindrome #5", "solutions": ["def palindrome(num):\n if type(num) is not int or num < 1:\n return 'Not valid'\n return num == int(str(num)[::-1])", "def palindrome(num):\n return str(num) == str(num)[::-1] if type(num) == int and num > 0 else 'Not valid'", "def palindrome(n):\n try:\n return 1.0 * n == int(str(n)[::-1])\n except:\n return 'Not valid'", "def palindrome(n):\n return 'Not valid' if type(n) != int or n < 0 else str(n) == str(n)[::-1]", "def palindrome(a):\n if type(a) == int:\n if a > 0:\n a = str(a)\n b = a[::-1]\n if a == b:\n return True\n else:\n return False\n else:\n return 'Not valid'\n else:\n return 'Not valid'", "def palindrome(num):\n if type(num) != int or num < 0:\n return 'Not valid'\n k = str(num)\n if k == k[::-1]:\n return True\n else:\n return False", "def palindrome(num):\n if type(123) != type(num):\n return 'Not valid'\n n = str(num)\n if any((not c.isdigit() for c in n)):\n return 'Not valid'\n l = len(n)\n return all((a == b for (a, b) in zip(n[:l // 2], n[::-1])))", "def palindrome(num):\n if not str(num).isdigit():\n return 'Not valid'\n if type(num) == str:\n return 'Not valid'\n num = str(num)\n return num == num[::-1]", "def palindrome(num):\n if isinstance(num, int) == False or num < 0:\n return 'Not valid'\n elif str(num) == str(num)[::-1]:\n return True\n else:\n return False", "def palindrome(num):\n\n def helper():\n if type(num) == str or num < 0:\n return 'Not valid'\n return True if str(num) == str(num)[::-1] else False\n try:\n int(num)\n except ValueError:\n return 'Not valid'\n else:\n return helper()", "def palindrome(n):\n if not isinstance(n, int) or n < 0:\n return 'Not valid'\n (rev, temp) = (0, n)\n while temp > 0:\n a = temp % 10\n rev = rev * 10 + a\n temp //= 10\n return rev == n", "def palindrome(num):\n if isinstance(num, int) is False or num < 0:\n return 'Not valid'\n return str(num) == str(num)[::-1]", "def palindrome(n):\n if type(n) == int and n > 0:\n (n1, n2) = (str(n), str(n)[::-1])\n return n1 == n2\n else:\n return 'Not valid'", "def palindrome(num):\n try:\n if type(num) != int or num < 0:\n raise Numerical_paindrom_exception\n return True if str(num)[::1] == str(num)[::-1] else False\n except Exception as e:\n return e.__str__()\n\ndef __init__():\n pass\n\ndef __str__():\n return 'Not valid'"], "starter_code": "def palindrome(num):\n", "input_output": {"fn_name": "palindrome", "inputs": [[1221], [110011], [1456009006541], [123322], [1], [152], [9999], ["ACCDDCCA"], ["@14AbC"], ["1221"], [-450]], "outputs": [[true], [true], [true], [false], [true], [false], [true], ["Not valid"], ["Not valid"], ["Not valid"], ["Not valid"]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/58ba6fece3614ba7c200017f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "palindrome", "task_id": "TACO_lite/80", "example": [[], []]} +{"requirement": "Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.\nFor eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.\n \nExample 1:\nInput : \"AABBBCBBAC\"\nOutput : 3\nExplanation : Sub-string -> \"BAC\"\nExample 2:\nInput : \"aaab\"\nOutput : 2\nExplanation : Sub-string -> \"ab\"\n \nExample 3:\nInput : \"GEEKSGEEKSFOR\"\nOutput : 8\nExplanation : Sub-string -> \"GEEKSFOR\"\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.\nExpected Time Complexity: O(256.N)\nExpected Auxiliary Space: O(256)\n \nConstraints:\n1 ≤ |S| ≤ 10^{5}\nString may contain both type of English Alphabets.", "solutions": ["def findsubstring(str):\n dict = {}\n ans = float('inf')\n j = 0\n for i in str:\n if i not in dict:\n dict[i] = 0\n length = len(dict)\n for i in range(len(str)):\n dict[str[i]] += 1\n if dict[str[i]] == 1:\n length -= 1\n while length == 0:\n ans = min(ans, i - j + 1)\n dict[str[j]] -= 1\n if dict[str[j]] == 0:\n length += 1\n j += 1\n return ans", "from collections import defaultdict\n\ndef findsubstring(s):\n n = len(s)\n dist_count = len(set([x for x in s]))\n m = defaultdict(int)\n start = 0\n min_len = float('inf')\n count = 0\n for j in range(n):\n m[s[j]] += 1\n if m[s[j]] == 1:\n count += 1\n if count == dist_count:\n while m[s[start]] > 1:\n if m[s[start]] > 1:\n m[s[start]] -= 1\n start += 1\n len_window = j - start + 1\n if min_len > len_window:\n min_len = len_window\n return min_len", "def findsubstring(str):\n from collections import defaultdict\n n = len(str)\n if n <= 1:\n return 1\n dist_count = len(set([x for x in str]))\n curr_count = defaultdict(lambda : 0)\n count = 0\n start = 0\n min_len = n\n for j in range(n):\n curr_count[str[j]] += 1\n if curr_count[str[j]] == 1:\n count += 1\n if count == dist_count:\n while curr_count[str[start]] > 1:\n if curr_count[str[start]] > 1:\n curr_count[str[start]] -= 1\n start += 1\n len_window = j - start + 1\n min_len = min(min_len, len_window)\n start_index = start\n return min_len", "def findsubstring(s):\n D = {}\n for i in s:\n if i in D:\n pass\n else:\n D[i] = 1\n n = len(s)\n (i, j) = (0, 0)\n count = len(D)\n mini = 9999\n while j < n:\n if s[j] in D:\n D[s[j]] -= 1\n if D[s[j]] == 0:\n count -= 1\n while count == 0:\n mini = min(mini, j - i + 1)\n if s[i] in D:\n D[s[i]] += 1\n if D[s[i]] > 0:\n count += 1\n i += 1\n j += 1\n return mini", "def findsubstring(str):\n mp = {}\n cnt = 0\n for i in range(len(str)):\n if str[i] not in mp:\n mp[str[i]] = 0\n cnt += 1\n cnt1 = 0\n j = 0\n mn = len(str)\n for i in range(len(str)):\n if mp[str[i]] == 0:\n mp[str[i]] += 1\n cnt1 += 1\n else:\n mp[str[i]] += 1\n while cnt == cnt1:\n mn = min(mn, i - j + 1)\n if mp[str[j]] == 1:\n mp[str[j]] -= 1\n cnt1 -= 1\n j = j + 1\n else:\n mp[str[j]] -= 1\n j = j + 1\n return mn", "def findsubstring(str):\n dict = {}\n a = 1000000000.0\n j = 0\n for i in str:\n if i not in dict:\n dict[i] = 0\n l = len(dict)\n for i in range(len(str)):\n dict[str[i]] += 1\n if dict[str[i]] == 1:\n l -= 1\n while l == 0:\n a = min(a, i - j + 1)\n dict[str[j]] -= 1\n if dict[str[j]] == 0:\n l += 1\n j += 1\n return a", "def findsubstring(s):\n distinct = len(set(s))\n d = dict()\n si = -1\n Len = 100000.0\n start = 0\n for i in range(len(s)):\n if s[i] not in d:\n d[s[i]] = 1\n else:\n d[s[i]] += 1\n if len(d) == distinct:\n while d[s[start]] > 1:\n d[s[start]] -= 1\n start += 1\n clen = i - start + 1\n if Len > clen:\n Len = clen\n si = start\n return len(s[si:si + Len])", "from collections import defaultdict\n\ndef findsubstring(str):\n leng = len(str)\n (start, end) = (0, leng - 1)\n ct = 0\n t_dist = len(set([e for e in str]))\n chr_map = defaultdict(lambda : 0)\n min_wind = leng\n for i in range(leng):\n x = str[i]\n chr_map[x] += 1\n if chr_map[x] == 1:\n ct += 1\n if ct == t_dist:\n while chr_map[str[start]] > 1:\n chr_map[str[start]] -= 1\n start += 1\n min_wind = min(i - start + 1, min_wind)\n return min_wind", "def findsubstring(str):\n n = len(str)\n (dic, vic) = ({}, {})\n for a in str:\n if a not in dic:\n dic[a] = 0\n dic[a] += 1\n (i, j, ans) = (0, 0, 10000000000)\n while j < n:\n if str[j] not in vic:\n vic[str[j]] = 0\n vic[str[j]] += 1\n if len(vic) == len(dic):\n while len(vic) == len(dic):\n vic[str[i]] -= 1\n if vic[str[i]] == 0:\n del vic[str[i]]\n i += 1\n ans = min(ans, 2 + j - i)\n j += 1\n return ans", "def findsubstring(str):\n dict = {}\n ans = 1000000000.0\n for i in str:\n if i not in dict:\n dict[i] = 0\n length = len(dict)\n count = 0\n j = 0\n for i in range(len(str)):\n dict[str[i]] += 1\n if dict[str[i]] == 1:\n count += 1\n while count == length:\n ans = min(ans, i - j + 1)\n dict[str[j]] -= 1\n if dict[str[j]] == 0:\n count -= 1\n j += 1\n return ans", "from collections import Counter\n\ndef findsubstring(str1):\n length = len(str1)\n dict1 = Counter(str1)\n k = len(dict1)\n dict2 = dict()\n count = 0\n start = 0\n minimum = 99999\n for i in range(length):\n if count < k:\n j = start\n while j < length:\n if str1[j] not in dict2:\n dict2[str1[j]] = 1\n count += 1\n else:\n dict2[str1[j]] += 1\n if count == k:\n break\n j += 1\n if count == k:\n minimum = min(minimum, j - i + 1)\n start = j + 1\n dict2[str1[i]] -= 1\n if dict2[str1[i]] == 0:\n dict2.pop(str1[i])\n count -= 1\n return minimum", "from collections import Counter, defaultdict\n\ndef findsubstring(str_):\n set_of_string = set()\n len_set_of_string = len(set(str_))\n answer = float('inf')\n left = 0\n right = 0\n freq = defaultdict(int)\n while right < len(str_):\n freq[str_[right]] += 1\n while left <= right and len(freq) == len_set_of_string:\n answer = min(answer, right - left + 1)\n freq[str_[left]] -= 1\n if freq[str_[left]] == 0:\n del freq[str_[left]]\n left += 1\n right += 1\n return answer", "def findsubstring(a):\n dict = {}\n n = len(set(a))\n left = 0\n right = 0\n ans = len(a)\n while right < len(a):\n if a[right] not in dict:\n dict[a[right]] = 1\n else:\n dict[a[right]] += 1\n if len(dict) == n:\n while dict[a[left]] > 1:\n dict[a[left]] -= 1\n left += 1\n ans = min(ans, right - left + 1)\n right += 1\n return ans", "import math\n\ndef findsubstring(s):\n dicti = {}\n mini = math.inf\n k = len(set(s))\n n = len(s)\n (i, j) = (0, 0)\n while j < n:\n if s[j] not in dicti:\n dicti[s[j]] = 1\n else:\n dicti[s[j]] += 1\n if len(dicti) < k:\n j += 1\n elif len(dicti) == k:\n while len(dicti) == k:\n mini = min(mini, j - i + 1)\n if s[i] in dicti:\n dicti[s[i]] -= 1\n if dicti[s[i]] == 0:\n del dicti[s[i]]\n i += 1\n j += 1\n return mini", "from collections import defaultdict\n\ndef findsubstring(arr):\n dic = defaultdict(lambda : 0)\n i = 0\n j = 0\n n = len(set(arr))\n ans = len(arr)\n while j < len(arr):\n dic[arr[j]] += 1\n if len(dic) < n:\n j += 1\n if len(dic) == n:\n while dic[arr[i]] > 1:\n dic[arr[i]] -= 1\n i += 1\n ans = min(ans, j - i + 1)\n j += 1\n return ans", "def findsubstring(str):\n d = {}\n for i in str:\n d[i] = 0\n i = 0\n j = 0\n ans = len(str)\n count = len(d)\n temp = 0\n while j < len(str):\n while temp < count and j < len(str):\n if d[str[j]] == 0:\n temp += 1\n d[str[j]] += 1\n j += 1\n while temp >= count:\n d[str[i]] -= 1\n if d[str[i]] == 0:\n temp -= 1\n i += 1\n ans = min(ans, j - i + 1)\n return ans", "from collections import deque\n\ndef findsubstring(stre):\n s = set(stre)\n set_len = len(s)\n j = 0\n minlen = 1000000000.0\n mp = {}\n n = len(stre)\n for i in range(n):\n if stre[i] not in mp:\n mp[stre[i]] = 1\n else:\n mp[stre[i]] += 1\n while j <= i and len(mp) == set_len:\n if minlen > i - j + 1:\n minlen = i - j + 1\n mp[stre[j]] -= 1\n if mp[stre[j]] == 0:\n del mp[stre[j]]\n j += 1\n return minlen", "def findsubstring(str):\n m = {}\n n = len(set(str))\n length = float('inf')\n j = 0\n for i in range(len(str)):\n m[str[i]] = m.get(str[i], 0) + 1\n if len(m) == n:\n while m[str[j]] > 1:\n m[str[j]] -= 1\n j += 1\n length = min(length, i - j + 1)\n return length", "def findsubstring(str):\n dict = {}\n ans = 1000000000.0\n for i in str:\n if i not in dict:\n dict[i] = 1\n dict2 = {}\n j = 0\n for i in range(len(str)):\n if str[i] not in dict2:\n dict2[str[i]] = 1\n else:\n dict2[str[i]] += 1\n while len(dict) == len(dict2):\n ans = min(ans, i - j + 1)\n if dict2[str[j]] > 1:\n dict2[str[j]] -= 1\n elif dict2[str[j]] == 1:\n dict2.pop(str[j])\n j += 1\n return ans", "from collections import defaultdict\n\ndef findsubstring(s):\n a = set(s)\n i = 0\n t = {}\n min_len = float('inf')\n for j in range(len(s)):\n if s[j] not in t:\n t[s[j]] = 0\n t[s[j]] += 1\n while len(t) == len(a):\n min_len = min(min_len, j - i + 1)\n t[s[i]] -= 1\n if t[s[i]] == 0:\n del t[s[i]]\n i += 1\n return min_len", "def findsubstring(str):\n from collections import defaultdict\n curr_count = defaultdict(lambda : 0)\n dist_count = len(set([x for x in str]))\n if len(str) <= 1:\n return 1\n counter = 0\n start = 0\n min_len = len(str)\n for i in range(len(str)):\n curr_count[str[i]] += 1\n if curr_count[str[i]] == 1:\n counter += 1\n if counter == dist_count:\n while curr_count[str[start]] > 1:\n if curr_count[str[start]] > 1:\n curr_count[str[start]] -= 1\n start += 1\n window_len = i - start + 1\n if window_len < min_len:\n min_len = window_len\n start_index = start\n a = min_len\n return a", "def findsubstring(str):\n d = {}\n for i in str:\n if i not in d:\n d[i] = 0\n (i, j) = (0, float('inf'))\n (count, out) = (0, float('inf'))\n for j in range(len(str)):\n if d[str[j]] == 0:\n count += 1\n d[str[j]] += 1\n if count == len(d):\n while i < j:\n d[str[i]] -= 1\n if d[str[i]] == 0:\n out = min(out, j - i + 1)\n count -= 1\n i += 1\n break\n i += 1\n return out if out != float('inf') else 1", "def findsubstring(str):\n k = len(set(str))\n memo = {}\n ans = len(str)\n (i, j) = (0, 0)\n while j < len(str):\n memo[str[j]] = memo.get(str[j], 0) + 1\n if len(memo) < k:\n j += 1\n elif len(memo) == k:\n while len(memo) == k:\n memo[str[i]] -= 1\n if memo[str[i]] == 0:\n del memo[str[i]]\n i += 1\n ans = min(ans, j - i + 2)\n j += 1\n elif len(memo) > k:\n while len(memo) > k:\n memo[str[i]] -= 1\n if memo[str[i]] == 0:\n del memo[str[i]]\n i += 1\n j += 1\n return ans", "def findsubstring(str):\n res = 100000\n d = {}\n for i in range(len(str)):\n if str[i] not in d:\n d[str[i]] = 0\n s1 = set()\n count = len(d)\n l = 0\n for i in range(len(str)):\n s1.add(str[i])\n d[str[i]] = d[str[i]] + 1\n while count == len(s1) and d[str[l]] != 0:\n d[str[l]] = d[str[l]] - 1\n if d[str[l]] == 0:\n s1.remove(str[l])\n res = min(res, i - l + 1)\n l = l + 1\n return res", "def findsubstring(str):\n ans = len(str)\n N = len(str)\n n = len(set(str))\n (i, j) = (0, 0)\n d = {}\n while i < N:\n if str[i] not in d:\n d[str[i]] = 1\n else:\n d[str[i]] += 1\n if len(d) == n:\n while d[str[j]] > 1:\n d[str[j]] -= 1\n j += 1\n ans = min(ans, i - j + 1)\n i += 1\n return ans", "def findsubstring(s):\n freq = {}\n for c in s:\n freq[c] = 0\n unique_chars = len(freq)\n left = 0\n right = 0\n count = 0\n min_length = float('inf')\n while right < len(s):\n if s[right] in freq:\n freq[s[right]] += 1\n if freq[s[right]] == 1:\n count += 1\n right += 1\n while count == unique_chars:\n if right - left < min_length:\n min_length = right - left\n if s[left] in freq:\n freq[s[left]] -= 1\n if freq[s[left]] == 0:\n count -= 1\n left += 1\n return min_length", "def findsubstring(str):\n d = {}\n for i in str:\n if i not in d:\n d[i] = 0\n x = len(d)\n ans = 999999\n i = 0\n j = 0\n c = 0\n while i < len(str):\n if d[str[i]] == 0:\n c += 1\n d[str[i]] += 1\n if c == x:\n f = True\n while c == x:\n ans = min(ans, i - j + 1)\n d[str[j]] -= 1\n if d[str[j]] == 0:\n c -= 1\n j += 1\n i += 1\n return ans", "def findsubstring(str):\n reslen = len(str)\n s = set()\n d = dict()\n for i in range(len(str)):\n s.add(str[i])\n i = 0\n count = 0\n for j in range(len(str)):\n d[str[j]] = d.get(str[j], 0) + 1\n if d[str[j]] == 1:\n count += 1\n if count == len(s):\n while d[str[i]] > 1:\n if d[str[i]] > 1:\n d[str[i]] -= 1\n i += 1\n if reslen > j - i + 1:\n reslen = j - i + 1\n return reslen", "from collections import defaultdict\n\ndef findsubstring(strr):\n n = len(strr)\n dist_count = len(set([x for x in strr]))\n if n == dist_count:\n return n\n curr_count = dict()\n count = 0\n start = 0\n min_len = n\n for i in range(n):\n curr_count[strr[i]] = curr_count.get(strr[i], 0) + 1\n if curr_count[strr[i]] == 1:\n count += 1\n if count == dist_count:\n while curr_count[strr[start]] > 1:\n if curr_count[strr[start]] > 1:\n curr_count[strr[start]] -= 1\n start += 1\n if min_len > i - start + 1:\n min_len = i - start + 1\n return min_len", "def findsubstring(s):\n n = len(s)\n res = n\n i = 0\n uniq = set(list(s))\n found = {}\n for j in range(n):\n if s[j] in found:\n found[s[j]] += 1\n else:\n found[s[j]] = 1\n while i < j:\n if found[s[i]] > 1:\n found[s[i]] -= 1\n i += 1\n else:\n break\n if len(found) == len(uniq):\n res = min(res, j - i + 1)\n return res", "from collections import defaultdict\n\ndef findsubstring(s):\n n = len(s)\n if n <= 1:\n return len(s)\n dis_char = len(set(list(s)))\n curr = defaultdict(lambda : 0)\n cnt = 0\n minlen = n\n start = 0\n for j in range(n):\n curr[s[j]] += 1\n if curr[s[j]] == 1:\n cnt += 1\n if cnt == dis_char:\n while curr[s[start]] > 1:\n curr[s[start]] -= 1\n start += 1\n length = j - start + 1\n if length < minlen:\n minlen = length\n startind = start\n return minlen", "def findsubstring(S):\n distinct_chars = set(S)\n n = len(S)\n left = 0\n min_length = n\n count = [0] * 256\n distinct = 0\n for right in range(n):\n count[ord(S[right])] += 1\n if count[ord(S[right])] == 1:\n distinct += 1\n if distinct == len(distinct_chars):\n while count[ord(S[left])] > 1:\n count[ord(S[left])] -= 1\n left += 1\n min_length = min(min_length, right - left + 1)\n count[ord(S[left])] -= 1\n left += 1\n distinct -= 1\n return min_length", "def findsubstring(str):\n maxi = len(str)\n sets = set(str)\n i = 0\n j = 0\n m = {}\n while i < len(str):\n m[str[i]] = 1 + m.get(str[i], 0)\n if len(m) >= len(sets):\n while m[str[j]] > 1:\n m[str[j]] -= 1\n j += 1\n maxi = min(maxi, i - j + 1)\n i += 1\n return maxi", "def findsubstring(input_string):\n start = 0\n end = 1\n alphabet_dict = {}\n distinct_list = list(set(input_string))\n for i in range(0, len(distinct_list)):\n alphabet_dict[distinct_list[i]] = 0\n n = len(distinct_list)\n count = 1\n alphabet_dict[input_string[0]] = 1\n answer = len(input_string)\n while start <= end < len(input_string):\n if count < n:\n element = input_string[end]\n if alphabet_dict[element] == 0:\n alphabet_dict[element] = 1\n count = count + 1\n else:\n alphabet_dict[element] = alphabet_dict[element] + 1\n end = end + 1\n elif count == n:\n answer = min(answer, end - start)\n element = input_string[start]\n if element in alphabet_dict and alphabet_dict[element] == 1:\n count = count - 1\n alphabet_dict[element] = alphabet_dict[element] - 1\n start = start + 1\n while count == n:\n answer = min(answer, end - start)\n element = input_string[start]\n if element in alphabet_dict and alphabet_dict[element] == 1:\n count = count - 1\n alphabet_dict[element] = alphabet_dict[element] - 1\n start = start + 1\n return answer", "from collections import Counter\n\ndef findsubstring(str):\n dic1 = Counter(str)\n dic2 = dict()\n (i, j) = (0, 0)\n res = 10000000000\n while j < len(str):\n if str[j] in dic2:\n dic2[str[j]] += 1\n else:\n dic2[str[j]] = 1\n if len(dic1) == len(dic2):\n while len(dic1) == len(dic2):\n res = min(res, j - i + 1)\n dic2[str[i]] -= 1\n if dic2[str[i]] == 0:\n del dic2[str[i]]\n i += 1\n j += 1\n return res", "import math\n\ndef findsubstring(s):\n freq = {}\n for c in s:\n freq[c] = 0\n (b, d, ans) = (0, 0, math.inf)\n for (i, c) in enumerate(s):\n while d == len(freq.keys()):\n freq[s[b]] -= 1\n if freq[s[b]] == 0:\n ans = min(ans, i - b)\n d -= 1\n b += 1\n freq[c] += 1\n if freq[c] == 1:\n d += 1\n while d == len(freq.keys()):\n freq[s[b]] -= 1\n if freq[s[b]] == 0:\n ans = min(ans, i - b + 1)\n d -= 1\n b += 1\n return ans", "def findsubstring(str):\n n = len(str)\n ans = 0\n length = n\n s = list(set(str))\n d = dict()\n count = 0\n start = 0\n for i in range(n):\n if str[i] not in d.keys():\n d[str[i]] = 1\n count += 1\n else:\n d[str[i]] += 1\n if count == len(s):\n while d[str[start]] > 1:\n d[str[start]] -= 1\n start += 1\n ans = i - start + 1\n if length > ans:\n length = ans\n return length", "from collections import defaultdict\n\ndef findsubstring(s):\n control = set(s)\n m = len(control)\n n = len(s)\n test = defaultdict(lambda : 0)\n mini = float('inf')\n i = 0\n for j in range(n):\n while len(test) < m and i < n:\n test[s[i]] += 1\n i += 1\n if len(test) < m:\n break\n mini = min(mini, i - j)\n test[s[j]] -= 1\n if test[s[j]] == 0:\n del test[s[j]]\n return mini", "def findsubstring(str):\n i = 0\n j = 0\n s = len(set(str))\n n = len(str)\n ans = n\n dic = {}\n while i < n:\n if str[i] not in dic:\n dic[str[i]] = 1\n else:\n dic[str[i]] += 1\n if len(dic) == s:\n while dic[str[j]] > 1:\n dic[str[j]] -= 1\n j += 1\n ans = min(ans, i - j + 1)\n i += 1\n return ans", "def findsubstring(s):\n n = len(s)\n distinct_chars = len(set(s))\n freq = [0] * 256\n left = 0\n right = 0\n count = 0\n min_len = n\n while right < n:\n ch = ord(s[right])\n if freq[ch] == 0:\n count += 1\n freq[ch] += 1\n right += 1\n while count == distinct_chars:\n min_len = min(min_len, right - left)\n ch = ord(s[left])\n freq[ch] -= 1\n if freq[ch] == 0:\n count -= 1\n left += 1\n return min_len", "def findsubstring(str):\n nd = len(set(str))\n i = 0\n j = 0\n res = len(str)\n dic = {}\n while i < len(str):\n if str[i] in dic:\n dic[str[i]] = dic[str[i]] + 1\n else:\n dic[str[i]] = 1\n if len(dic) == nd:\n while dic[str[j]] > 1:\n dic[str[j]] = dic[str[j]] - 1\n j = j + 1\n res = min(res, i - j + 1)\n i = i + 1\n return res", "from collections import Counter\n\ndef findsubstring(str1):\n dict1 = dict()\n count = 0\n distinct = len(Counter(str1))\n n = len(str1)\n j = 0\n minimum = n\n for i in range(n):\n if count < distinct:\n while j < n:\n if str1[j] not in dict1:\n dict1[str1[j]] = 1\n count += 1\n else:\n dict1[str1[j]] += 1\n if count == distinct:\n j += 1\n break\n j += 1\n if count == distinct:\n minimum = min(minimum, j - i)\n dict1[str1[i]] -= 1\n if dict1[str1[i]] == 0:\n dict1.pop(str1[i])\n count -= 1\n return minimum", "def findsubstring(a):\n s = ''\n a1 = {}\n for i in a:\n a1[i] = 1\n c1 = len(a1)\n i = 0\n j = 0\n a2 = {}\n c = 0\n res = len(a)\n while j < len(a):\n if a[j] not in a2:\n a2[a[j]] = 0\n c += 1\n a2[a[j]] += 1\n while i <= j and c == c1:\n res = min(res, j - i + 1)\n a2[a[i]] -= 1\n if a2[a[i]] == 0:\n del a2[a[i]]\n c -= 1\n i += 1\n j += 1\n return res", "def findsubstring(str):\n ans_len = len(set(str))\n d = {}\n ws = 0\n ans = 10 ** 6\n for we in range(0, len(str)):\n d[str[we]] = d.get(str[we], 0) + 1\n if len(d) == ans_len:\n while d[str[ws]] > 1:\n d[str[ws]] -= 1\n ws += 1\n ans = min(ans, we - ws + 1)\n return ans", "def findsubstring(str):\n unique = set(str)\n res = len(str)\n j = 0\n map = dict()\n for i in range(0, len(str)):\n if str[i] in map.keys():\n map[str[i]] += 1\n else:\n map[str[i]] = 1\n if len(unique) == len(map):\n while map[str[j]] > 1:\n map[str[j]] -= 1\n j += 1\n res = min(res, i - j + 1)\n return res", "def findsubstring(str):\n l = len(str)\n s = set()\n for i in range(len(str)):\n s.add(str[i])\n n = len(s)\n head = 0\n tail = 0\n hmap = {}\n ans = l\n while head < l:\n if str[head] in hmap:\n hmap[str[head]] += 1\n else:\n hmap[str[head]] = 1\n if len(hmap) == n:\n while hmap[str[tail]] > 1:\n hmap[str[tail]] -= 1\n tail += 1\n ans = min(ans, head - tail + 1)\n head += 1\n return ans", "from collections import defaultdict, Counter\nfrom sys import maxsize\n\ndef findsubstring(str):\n cnt = Counter(str)\n cur = defaultdict(int)\n k = 0\n ans = maxsize\n i = 0\n for (j, ch) in enumerate(str):\n cur[ch] += 1\n if cur[ch] == 1:\n k += 1\n if k == len(cnt):\n while i < j:\n if cur[str[i]] == 1:\n break\n cur[str[i]] -= 1\n i += 1\n ans = min(ans, j - i + 1)\n return ans", "def findsubstring(str):\n res = float('inf')\n (i, j) = (0, 0)\n maxLen = len(set(list(str)))\n hashmap = {}\n while j < len(str):\n if str[j] not in hashmap:\n hashmap[str[j]] = 1\n else:\n hashmap[str[j]] += 1\n j += 1\n if len(hashmap) == maxLen:\n while i < j and hashmap[str[i]] > 1:\n hashmap[str[i]] -= 1\n i += 1\n res = min(res, j - i)\n return res", "def findsubstring(str):\n d = {}\n for ch in str:\n if ch not in d:\n d[ch] = 1\n n = len(d)\n d.clear()\n i = 0\n j = 0\n count = 0\n mini = len(str)\n while j < len(str):\n if str[j] not in d:\n d[str[j]] = 1\n count = count + 1\n else:\n d[str[j]] = d[str[j]] + 1\n if count == n:\n while d[str[i]] != 1:\n d[str[i]] = d[str[i]] - 1\n i = i + 1\n mini = min(mini, j - i + 1)\n j = j + 1\n return mini", "def findsubstring(s):\n n = len(s)\n d = {}\n count = 0\n for i in range(n):\n d[s[i]] = 0\n i = 0\n j = 0\n ans = n\n while i < n:\n if d[s[i]] == 0:\n count += 1\n d[s[i]] += 1\n if count == len(d):\n while j < n and d[s[j]] > 1:\n d[s[j]] -= 1\n j += 1\n if ans > i - j + 1:\n ans = i - j + 1\n i += 1\n return ans", "def findsubstring(str):\n p = len(set(str))\n j = 0\n i = 0\n d = {}\n mn = 100000\n while j < len(str):\n if str[j] in d:\n d[str[j]] += 1\n else:\n d[str[j]] = 1\n if len(d) == p:\n while len(d) == p:\n mn = min(mn, j - i + 1)\n d[str[i]] -= 1\n if d[str[i]] == 0:\n del d[str[i]]\n i += 1\n j += 1\n return mn", "def findsubstring(str):\n d = {}\n i = 0\n j = 0\n sw = 100000000\n n = len(set(str))\n while j < len(str):\n if str[j] not in d:\n d[str[j]] = 1\n else:\n d[str[j]] += 1\n if len(d) == n:\n while len(d) == n:\n sw = min(sw, j - i + 1)\n d[str[i]] -= 1\n if d[str[i]] == 0:\n del d[str[i]]\n i += 1\n j += 1\n return sw", "def findsubstring(str):\n dict = {}\n for i in str:\n if i in dict:\n dict[i] += 1\n else:\n dict[i] = 1\n count = len(list(dict.keys()))\n i = j = 0\n ans = len(str)\n c = 0\n dict = {}\n for i in range(len(str)):\n if str[i] in dict:\n dict[str[i]] += 1\n else:\n dict[str[i]] = 1\n c += 1\n if c == count:\n ans = min(ans, i - j + 1)\n while c == count and j <= i:\n dict[str[j]] -= 1\n if dict[str[j]] == 0:\n del dict[str[j]]\n c -= 1\n ans = min(ans, i - j + 1)\n j += 1\n return ans", "def findsubstring(str):\n s = set(str)\n n = len(s)\n ss = set()\n ind = 0\n d = {}\n mini = 10 ** 9\n for i in range(len(str)):\n if str[i] not in ss:\n ss.add(str[i])\n d[str[i]] = d.get(str[i], 0) + 1\n if len(ss) == n:\n ind = i + 1\n mini = min(mini, i + 1)\n break\n index = 0\n while d[str[index]] > 1:\n d[str[index]] -= 1\n index += 1\n mini = min(mini, i - index + 1)\n for i in range(ind, len(str)):\n d[str[i]] = d.get(str[i], 0) + 1\n while d[str[index]] > 1:\n d[str[index]] -= 1\n index += 1\n mini = min(mini, i - index + 1)\n while d[str[index]] > 1:\n d[str[index]] -= 1\n index += 1\n mini = min(mini, i - index + 1)\n return mini"], "starter_code": "def findsubstring(str):\n", "input_output": {"inputs": ["\"AABBBCBBAC\"", "\"aaab\"", "\"GEEKSGEEKSFOR\""], "outputs": ["3", "2", "8"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Hash", "sliding-window", "Strings", "Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures", "Amortized analysis"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/smallest-distant-window3132/1", "Expected Auxiliary Space": "O(256)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(256.N)", "entry_point": "findsubstring", "task_id": "TACO_lite/2", "example": [[["AABBBCBBAC"], ["aaab"], ["GEEKSGEEKSFOR"]], ["3", "2", "8"]]} +{"requirement": "Your car is old, it breaks easily. The shock absorbers are gone and you think it can handle about 15 more bumps before it dies totally.\n\nUnfortunately for you, your drive is very bumpy! Given a string showing either flat road (\"\\_\") or bumps (\"n\"), work out if you make it home safely. 15 bumps or under, return \"Woohoo!\", over 15 bumps return \"Car Dead\".", "solutions": ["def bumps(road):\n return 'Woohoo!' if road.count('n') <= 15 else 'Car Dead'", "def bumps(road):\n return 'Woohoo!' if road.count('n') < 16 else 'Car Dead'", "from collections import Counter\n\ndef bumps(road):\n return 'Car Dead' if Counter(road)['n'] > 15 else 'Woohoo!'", "import re\n\ndef bumps(road):\n return 'Woohoo!' if len(re.findall('n', road)) < 16 else 'Car Dead'", "def bumps(road):\n MAX_BUMPS = 15\n SUCCESS_MESSAGE = 'Woohoo!'\n ERROR_MESSAGE = 'Car Dead'\n return SUCCESS_MESSAGE if road.count('n') <= MAX_BUMPS else ERROR_MESSAGE", "bumps = lambda road: 'CWaoro hDoeoa!d'[road.count('n') < 16::2]", "def bumps(road):\n return ('Woohoo!', 'Car Dead')[road.count('n') > 15]", "def bumps(road):\n track = 0\n for el in road:\n if el == 'n':\n track += 1\n if track > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n a = 0\n for i in road:\n if i == 'n':\n a += 1\n if a > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n bumps = 0\n for c in road:\n if c == 'n':\n bumps += 1\n if bumps <= 15:\n return 'Woohoo!'\n else:\n return 'Car Dead'", "def bumps(road):\n L = list(road)\n C = L.count('n')\n if C > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n commute = road\n bumps = commute.count('n')\n condition_1 = bumps < 16\n condition_2 = bumps >= 16\n if condition_1:\n return 'Woohoo!'\n if condition_2:\n return 'Car Dead'", "def bumps(road):\n return 'Car Dead' if len([r for r in road if r is 'n']) > 15 else 'Woohoo!'\n\ndef best_practice_bumps(road):\n return 'Woohoo!' if road.count('n') <= 15 else 'Car Dead'", "def bumps(road):\n x = road.count('n')\n results = ['Woohoo!', 'Car Dead']\n if x > 15:\n return results[1]\n else:\n return results[0]", "def bumps(road):\n c = road.count('n')\n if c > 15:\n return 'Car Dead'\n return 'Woohoo!'", "def bumps(road):\n bumps = road.count('n')\n if bumps > 15:\n return 'Car Dead'\n elif bumps <= 15:\n return 'Woohoo!'", "def bumps(road):\n k = list(road)\n count = 0\n for word in k:\n if word == 'n':\n count += 1\n if count < 16:\n return 'Woohoo!'\n else:\n return 'Car Dead'", "def bumps(s):\n return 'Woohoo!' if s.count('n') < 16 else 'Car Dead'", "def bumps(road):\n count = 0\n for i in road:\n if i == 'n':\n count += 1\n if count <= 15:\n return 'Woohoo!'\n return 'Car Dead'", "def bumps(road):\n bumps = [x for x in road if x == 'n']\n if len(bumps) > 15:\n return 'Car Dead'\n return 'Woohoo!'", "bumps = lambda s: 'Woohoo!' if s.count('n') < 16 else 'Car Dead'", "def bumps(road):\n count = 0\n for char in road:\n if char == 'n':\n count += 1\n if count > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n list(road)\n bump_counter = 0\n for bump in road:\n if bump == 'n':\n bump_counter += 1\n if bump_counter <= 15:\n return 'Woohoo!'\n else:\n return 'Car Dead'", "def bumps(road):\n bumps = 0\n for i in range(len(road)):\n if road[i] == 'n':\n bumps += 1\n if bumps > 15:\n return 'Car Dead'\n return 'Woohoo!'", "def bumps(s):\n return 'Woohoo!' if s.count('n') <= 15 else 'Car Dead'", "def bumps(road):\n count = 0\n for x in road:\n if x is 'n':\n count = count + 1\n if count > 15:\n x = 'Car Dead'\n else:\n x = 'Woohoo!'\n return x", "def bumps(road):\n x = 0\n for spot in road:\n if spot == 'n':\n x += 1\n else:\n continue\n if x > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n (cnt1, cnt2) = (0, 0)\n for c in road:\n if c == '_':\n cnt1 += 1\n elif c == 'n':\n cnt2 += 1\n if cnt2 > 15:\n return 'Car Dead'\n return 'Woohoo!'", "f1 = lambda x: 1 if x == 'n' else 0\nf2 = lambda x: 'Woohoo!' if x <= 15 else 'Car Dead'\n\ndef bumps(road):\n return f2(sum((f1(x) for x in road)))", "def bumps(road):\n ncount = 0\n a = [char for char in road]\n for i in range(len(a)):\n if a[i] == 'n':\n ncount += 1\n if ncount > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n flat = []\n bump = []\n for letter in road:\n if letter is '_':\n flat.append(letter)\n else:\n bump.append(letter)\n if len(bump) <= 15:\n return 'Woohoo!'\n else:\n return 'Car Dead'", "def bumps(road):\n bumps = 0\n for letter in road:\n if letter == 'n' or letter == 'N':\n bumps += 1\n elif letter == '_':\n continue\n else:\n continue\n if bumps > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n bumps = 0\n for letter in road:\n if letter == 'n':\n bumps += 1\n continue\n else:\n continue\n if bumps > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n nr_bumps = 0\n for c in road:\n if c == 'n':\n nr_bumps += 1\n return 'Woohoo!' if nr_bumps < 16 else 'Car Dead'", "def bumps(road):\n a = 0\n for char in road:\n if str(char) == 'n':\n a += 1\n if a <= 15:\n return 'Woohoo!'\n if a > 15:\n return 'Car Dead'", "def bumps(road):\n counter = 0\n for i in road:\n if i == 'n':\n counter += 1\n continue\n return 'Woohoo!' if counter <= 15 else 'Car Dead'", "def bumps(road):\n return 'Car Dead' if ''.join(sorted(road, reverse=True)[0:16]) == 'nnnnnnnnnnnnnnnn' else 'Woohoo!'", "def bumps(road):\n x = road.count('n')\n if x <= 15:\n return 'Woohoo!'\n return 'Car Dead'", "def bumps(road):\n roadList = list(road)\n speedBumps = 'n'\n bumpCount = 0\n for i in roadList:\n if i == 'n':\n bumpCount += 1\n if bumpCount > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n return 'Woohoo!' if len(list(filter(lambda x: x == 'n', road))) <= 15 else 'Car Dead'", "def bumps(road):\n list = [road]\n a = 0\n for x in road:\n if x == 'n':\n a = a + 1\n if a > 15:\n return 'Car Dead'\n return 'Woohoo!'", "def bumps(road):\n countN = 0\n countUnderscore = 0\n listletters = [char for char in road]\n for i in listletters:\n if i == 'n':\n countN += 1\n else:\n countUnderscore += 1\n if countN > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n bump = 0\n for s in road:\n if s == 'n':\n bump += 1\n return 'Woohoo!' if bump <= 15 else 'Car Dead'", "def bumps(road):\n return 'Car Dead' if len(list(filter(str.isalpha, road))) > 15 else 'Woohoo!'", "def bumps(road):\n bumps = 0\n for i in road:\n if i == '_':\n pass\n elif i == 'n':\n bumps += 1\n if bumps > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n dead = 0\n for x in road:\n if x == 'n':\n dead += 1\n if dead > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n count = 0\n for each in road:\n if each == 'n':\n count += 1\n if count > 15:\n return 'Car Dead'\n elif count <= 15:\n return 'Woohoo!'", "def bumps(road):\n road_list = list(road)\n bump_number = 0\n for segment in road_list:\n if segment == 'n':\n bump_number += 1\n if bump_number <= 15:\n return 'Woohoo!'\n else:\n return 'Car Dead'", "def bumps(road):\n n = [x for x in road if x == 'n'].count('n')\n return 'Woohoo!' if n <= 15 else 'Car Dead'", "def bumps(road):\n sum = 0\n for i in road:\n if i is 'n':\n sum += 1\n if sum > 15:\n return 'Car Dead'\n return 'Woohoo!'", "def bumps(road):\n return 'Woohoo!' if len(road.split('n')) <= 16 else 'Car Dead'", "bumps = lambda road: 'Woohoo!' if road.count('n') < 16 else 'Car Dead'", "def bumps(road):\n b = 0\n for x in road:\n if x == 'n':\n b = b + 1\n if b < 15:\n return 'Woohoo!'\n elif b == 15:\n return 'Woohoo!'\n else:\n return 'Car Dead'", "def bumps(road):\n num_bumps = road.count('n')\n if num_bumps > 15:\n return 'Car Dead'\n return 'Woohoo!'", "def bumps(road):\n lista = list(road)\n bumps = 0\n for i in lista:\n if i == 'n':\n bumps += 1\n if bumps <= 15:\n return 'Woohoo!'\n else:\n return 'Car Dead'"], "starter_code": "def bumps(road):\n", "input_output": {"fn_name": "bumps", "inputs": [["n"], ["_nnnnnnn_n__n______nn__nn_nnn"], ["______n___n_"], ["nnnnnnnnnnnnnnnnnnnnn"]], "outputs": [["Woohoo!"], ["Car Dead"], ["Woohoo!"], ["Car Dead"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/57ed30dde7728215300005fa", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "bumps", "task_id": "TACO_lite/56", "example": [[], []]} +{"requirement": "# Exclusive \"or\" (xor) Logical Operator\n\n## Overview\n\nIn some scripting languages like PHP, there exists a logical operator (e.g. ```&&```, ```||```, ```and```, ```or```, etc.) called the \"Exclusive Or\" (hence the name of this Kata). The exclusive or evaluates two booleans. It then returns true if **exactly one of the two expressions are true**, false otherwise. For example:\n\n## Task\n\nSince we cannot define keywords in Javascript (well, at least I don't know how to do it), your task is to define a function ```xor(a, b)``` where a and b are the two expressions to be evaluated. Your ```xor``` function should have the behaviour described above, returning true if **exactly one of the two expressions evaluate to true**, false otherwise.", "solutions": ["def xor(a, b):\n return a != b", "from operator import xor", "def xor(a, b):\n return a is not b", "xor = int.__xor__", "xor = lambda a, b: a != b", "xor = __import__('operator').__xor__", "def xor(a, b):\n return False if a and b else a or b", "def xor(a, b):\n return len(set([a, b])) > 1", "xor = lambda *_: _[0] ^ _[1]", "xor = bool.__xor__", "def xor(a, b):\n return bool((a + b) % 2)", "def xor(a, b):\n if a == True and b == True:\n return False\n if a == True and b == False:\n return True\n if a == True and b == True:\n return True\n if a == False and b == False:\n return False\n else:\n return True", "def xor(a, b):\n return abs(a - b)", "def xor(a, b):\n if a == b:\n return False\n elif a != b or b != a:\n return True", "def xor(a, b):\n truCount = 0\n if a:\n truCount += 1\n if b:\n truCount += 1\n if truCount == 1:\n return True\n return False", "def xor(a, b):\n result = a ^ b\n return result", "def xor(a, b):\n if a == b:\n return False\n return True if a or b == True else False", "def xor(a, b):\n if a == b:\n return False\n elif a == True and b == False:\n return True\n elif a == False and b == True:\n return True", "def xor(a, b):\n c = 0\n n = str(a).count('True')\n m = str(b).count('True')\n c = n + m\n return c % 2 != 0", "def xor(a, b):\n return (a == True or a == False) and a != b", "def xor(a, b):\n return a != b and max(a, b) == True", "def xor(a, b):\n if a is True and b is True:\n return False\n elif a is False and b is False:\n return False\n else:\n return True", "def xor(a, b):\n if a is True and b is False or (b is True and a is False):\n return True\n else:\n return False", "def xor(a, b):\n count = 0\n if a == True:\n count += 1\n if b == True:\n count += 1\n if a != True:\n count -= 1\n if b != True:\n count -= 1\n if count == 0:\n return True\n return False", "xor = lambda a, b: True if not a and b or (a and (not b)) else False", "def xor(a, b):\n a = [a]\n b = [b]\n return sum(a + b) == 1", "def xor(a, b):\n if a is b:\n return False\n else:\n return a or b", "def xor(a, b):\n if a and b == True:\n return False\n elif a or b == True:\n return True\n else:\n False\n return False", "def xor(a, b):\n if not a:\n if b:\n return True\n else:\n return False\n elif not b:\n if a:\n return True\n else:\n return False\n else:\n return False", "def xor(a, b):\n return (1 - a + (1 - b)) % 2 == 1", "def xor(a, b):\n j = False\n if a != b:\n j = True\n return j", "def xor(a, b):\n if a is True:\n if b is True:\n return False\n if a is False:\n if b is False:\n return False\n if b is True:\n if a is True:\n return False\n if b is False:\n if a is False:\n return False\n if a is True:\n if b is False:\n return True\n if b is True:\n if a is False:\n return True", "def xor(a, b):\n if int(a + b) == 0:\n return False\n elif int(a + b) == 1:\n return True\n elif int(a + b) == 2:\n return False", "def xor(a, b):\n x = int(a)\n y = int(b)\n return a ^ b", "def xor(a, b):\n if a == False and b == False:\n return False\n elif a == True and b == True:\n return not a\n return a or b", "xor = lambda x, y: x is not y", "def xor(a, b):\n return (a is b) is False", "def xor(a, b):\n return not (not (a or b) or (a and b))", "def xor(a, b):\n my_bool = True\n if a and b:\n return False\n elif a == False and b == False:\n return False\n elif a or b:\n return True", "def xor(a, b):\n if a:\n if b:\n return False\n return a or b", "def xor(a, b):\n if a is not b:\n return True\n else:\n return False", "def xor(a, b):\n return a + b < 2 and a + b > 0", "def xor(a, b):\n answer = 0\n if a == True:\n answer += 1\n if b == True:\n answer += 1\n if answer == 1:\n return True\n else:\n return False", "xor = lambda a, b: int(a) ^ int(b)", "xor = lambda a, b: int(a) + int(b) == 1", "from operator import xor as xor_\nfrom functools import reduce\n\ndef xor(a, b):\n return reduce(xor_, (a, b))", "xor = lambda a, b: a + b == 1", "def xor(a, b):\n c = 0\n if a:\n c += 1\n if b:\n c += 1\n if c == 1:\n return True\n else:\n return False", "from operator import xor as xor1\n\ndef xor(a, b):\n return xor1(a, b)", "def xor(a, b):\n result = True\n if a == True and b == True:\n result = False\n elif a == True and b == False or (b == True and a == False):\n result = True\n elif a == False and b == False:\n result = False\n return result", "def xor(a, b):\n return (False, True)[a != b]"], "starter_code": "def xor(a,b):\n", "input_output": {"fn_name": "xor", "inputs": [[false, false], [true, false], [false, true], [true, true]], "outputs": [[false], [true], [true], [false]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56fa3c5ce4d45d2a52001b3c", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "xor", "task_id": "TACO_lite/92", "example": [[], []]} +{"requirement": "Given an array arr[] of N integers, the task is to find a subsequence of size K whose product is maximum among all possible K sized subsequences of a given array.\nExample 1:\nInput: N = 4, K = 2\narr[] = {1, 2, 0, 3} \nOutput: 6\nExplanation: Subsequence containing \nelements {2, 3} gives maximum product: \n2*3 = 6\nExample 2:\nInput: N = 6, K = 4\narr[] = {1, 2, -1, -3, -6, 4}\nOutput: 144\nExplanation: Subsequence containing \n{2, -3, -6, 4} gives maximum product: \n2*(-3)*(-6)*4 = 144\nYour Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function maxProductSubarrayOfSizeK() that takes array arr[], integer N and integer K as parameters and returns the desired product.\n \nExpected Time Complexity: O(NlogN).\nExpected Auxiliary Space: O(1).\n \nConstraints:\n1 ≤ N ≤ 10^{5}", "solutions": ["def maxproductsubarrayofsizek(arr, n, k):\n product = 1\n arr.sort()\n if k % 2 and arr[-1] < 0:\n for _ in range(k):\n product *= arr.pop()\n return product\n if k % 2:\n product *= arr.pop()\n k -= 1\n while k:\n if arr[0] * arr[1] > arr[-1] * arr[-2]:\n product *= arr.pop(0) * arr.pop(0)\n else:\n product *= arr.pop() * arr.pop()\n k -= 2\n return product", "def maxproductsubarrayofsizek(arr, n, k):\n arr.sort()\n if k == 1:\n return arr[-1]\n if arr[-1] == 0:\n return 0\n arr_len = len(arr)\n if k % 2 == 0:\n remainder = 0\n even_k = k\n else:\n remainder = 1\n even_k = k - 1\n i = 0\n j = len(arr) - 1\n subsequence = [None] * k\n subsequence_index = 0\n prod = 1\n if arr[-1] < 0:\n if not remainder:\n for i in range(0, k):\n subsequence[subsequence_index] = i\n subsequence_index += 1\n prod *= arr[i]\n else:\n for i in range(arr_len - k, arr_len):\n subsequence[subsequence_index] = i\n subsequence_index += 1\n prod *= arr[i]\n return prod\n subsequence_lenght = 0\n max_prod = 1\n if remainder:\n subsequence[-1] = j\n j -= 1\n while subsequence_lenght < even_k:\n if arr[i] * arr[i + 1] > arr[j] * arr[j - 1]:\n subsequence[i] = i\n subsequence[i + 1] = i + 1\n max_prod *= arr[i] * arr[i + 1]\n i += 2\n else:\n subsequence[k - (arr_len - j)] = j\n subsequence[k - (arr_len - j) - 1] = j - 1\n j -= 2\n max_prod *= arr[j] * arr[j - 1]\n subsequence_lenght += 2\n max_prod2 = 1\n for item in subsequence:\n max_prod2 *= arr[item]\n return max_prod2", "def maxproductsubarrayofsizek(arr, n, k):\n ans = 1\n arr.sort()\n if arr[n - 1] == 0 and k & 1:\n return 0\n if arr[n - 1] < 0 and k & 1:\n temp = 1\n i = n - 1\n while i >= n - k:\n temp *= arr[i]\n i -= 1\n return temp\n (i, j) = (0, n - 1)\n if arr[j] > 0 and k & 1:\n ans *= arr[j]\n k -= 1\n j -= 1\n while i <= j and k:\n p1 = arr[i] * arr[i + 1]\n p2 = arr[j] * arr[j - 1]\n if p1 > p2:\n ans *= p1\n i += 2\n k -= 2\n else:\n ans *= p2\n j -= 2\n k -= 2\n return ans", "def maxproductsubarrayofsizek(arr, n, k):\n arr.sort()\n ma = max(arr)\n if k % 2 == 0:\n p = 1\n l = 0\n r = n - 1\n for j in range(k // 2):\n a = arr[l] * arr[l + 1]\n b = arr[r] * arr[r - 1]\n if a >= b:\n p *= a\n l += 2\n else:\n p *= b\n r -= 2\n elif ma < 0:\n arr.sort(reverse=True)\n lst = arr[:k]\n p = 1\n for j in lst:\n p *= j\n elif ma == 0:\n p = 0\n else:\n p = ma\n k -= 1\n l = 0\n arr = arr[:n - 1]\n r = n - 2\n for j in range(k // 2):\n a = arr[l] * arr[l + 1]\n b = arr[r] * arr[r - 1]\n if a >= b:\n p *= a\n l += 2\n else:\n p *= b\n r -= 2\n return p", "def maxproductsubarrayofsizek(arr, n, k):\n arr.sort()\n A = arr\n A.sort()\n product = 1\n if A[n - 1] == 0 and k & 1:\n return 0\n if A[n - 1] <= 0 and k & 1:\n i = n - 1\n while k > 0:\n product *= A[i]\n k -= 1\n i -= 1\n return product\n i = 0\n j = n - 1\n if k & 1:\n product *= A[j]\n j -= 1\n k -= 1\n k >>= 1\n for itr in range(k):\n left_product = A[i] * A[i + 1]\n right_product = A[j] * A[j - 1]\n if left_product > right_product:\n product *= left_product\n i += 2\n else:\n product *= right_product\n j -= 2\n return product"], "starter_code": "def maxproductsubarrayofsizek(arr, n, k):\n", "input_output": {"inputs": ["N = 4, K = 2\narr[] = {1, 2, 0, 3}", "N = 6, K = 4\narr[] = {1, 2, -1, -3, -6, 4}"], "outputs": ["6", "144"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/maximum-product4633/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(NlogN).", "entry_point": "maxproductsubarrayofsizek", "task_id": "TACO_lite/62", "example": [[[4, 2, [1, 2, 0, 3]], [6, 4, [1, 2, -1, -3, -6, 4]]], ["6", "144"]]} +{"requirement": "Given two integers X and K. The task is to find smallest K-digit number divisible by X.\nNote: It is given that number of digits in X is always smaller or equal to K.\n \nExample 1:\nInput:\nX = 6, K = 1\nOutput:\n6\nExplanation:\n6 is the smallest 1 digit number\nwhich is divisible by 6.\nExample 2:\nInput:\nX = 5, K = 2\nOutput:\n10\nExplanation:\n10 is the smallest 2 digit number\nwhich is divisible by 5.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function smallestKDigitNum() which takes 2 Integers X and K as input and returns the answer.\n \nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= X <= 10^{5}\n1 <= K <= 18", "solutions": ["def smallestkdigitnum(X, K):\n Min = pow(10, K - 1)\n if Min % X == 0:\n return Min\n else:\n return Min + X - (Min + X) % X", "import math\n\ndef smallestkdigitnum(X, K):\n min = pow(10, K - 1)\n if min % X == 0:\n return min\n else:\n return min + X - (min + X) % X", "def smallestkdigitnum(X, K):\n if K == 1:\n return X\n x = K - 1\n l = pow(10, x)\n if l % X == 0:\n return l\n l += X\n return l - l % X", "def smallestkdigitnum(X, K):\n value = 10 ** (K - 1)\n if value % X == 0:\n return value\n return value + X - value % X", "def smallestkdigitnum(X, K):\n k_digit_num = int('1' + '0' * (K - 1))\n rem = k_digit_num % X\n if rem != 0:\n return k_digit_num + X - rem\n else:\n return k_digit_num", "def smallestkdigitnum(X, K):\n if K == 1:\n return X\n temp = '1' + '0' * (K - 1)\n high = '9' + '9' * (K - 1)\n temp = int(temp)\n high = int(high)\n t = temp // X\n if X * t == temp:\n return temp\n else:\n return X * (t + 1)", "def smallestkdigitnum(X, K):\n t = 10 ** (K - 1)\n d = t % X\n if d != 0:\n t += X - d\n return t", "def smallestkdigitnum(X, K):\n mn = pow(10, K - 1)\n if mn % X == 0:\n return mn\n return mn + X - (mn + X) % X", "def smallestkdigitnum(X, K):\n num = 10 ** (K - 1)\n return num if num % X == 0 else num + X - num % X", "def smallestkdigitnum(x, k):\n p = 10 ** (k - 1)\n if p % x == 0:\n return p\n l = p + x - (p + x) % x\n return l"], "starter_code": "def smallestkdigitnum(X, K):\n", "input_output": {"inputs": ["X = 6, K = 1", "X = 5, K = 2"], "outputs": ["6", "10"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Numbers", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/smallest-k-digit-number-divisible-by-x2351/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "smallestkdigitnum", "task_id": "TACO_lite/76", "example": [[[6, 1], [5, 2]], ["6", "10"]]} +{"requirement": "Given two strings S and T, find length of the shortest subsequence in S which is not a subsequence in T. If no such subsequence is possible, return -1. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. A string of length n has different possible subsequences.\n \nExample 1:\nInput:\nS = \"babab\"\nT = \"babba\"\nOutput:\n3\nExplanation:\nThere are no subsequences of S with\nlength less than 3 which is not a\nsubsequence of T. \"aab\" is an example of\na subsequence of length 3 which isn't a\nsubsequence of T.\nExample 2:\nInput:\nS = \"babhi\"\nT = \"babij\"\nOutput:\n1\nExplanation:\n\"h\" is a subsequence of S that is\nnot a subsequence of T.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function shortestUnSub() which takes two Strings S, and T as input and returns the shortest Uncommon Subsequence.\n \nExpected Time Complexity: O(|S|^{2}*|T|)\nExpected Auxiliary Space: O(|S|*|T|)\n \nConstraints:\n1 <= |S|, |T| <= 500", "solutions": ["def __init__():\n self.indices = {}\n\ndef shortestunsub(S, T):\n m = len(S)\n n = len(T)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n for i in range(n + 1):\n dp[0][i] = 501\n for i in range(1, m + 1):\n dp[i][0] = 1\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n k = j - 1\n ch = S[i - 1]\n if ch == T[k]:\n self.indices[ch] = k\n elif ch in self.indices:\n k = self.indices[ch]\n else:\n while k >= 0:\n if T[k] == S[i - 1]:\n break\n k -= 1\n self.indices[ch] = k\n if k == -1:\n dp[i][j] = 1\n else:\n dp[i][j] = min(dp[i - 1][j], 1 + dp[i - 1][k])\n ans = dp[i][j]\n if ans >= 501:\n ans = -1\n return ans", "def shortestunsub(S, T):\n (m, n) = (len(S), len(T))\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n for i in range(m + 1):\n dp[i][0] = 1\n for i in range(n + 1):\n dp[0][i] = float('inf')\n for i in range(m):\n for j in range(n):\n k = T[:j + 1].rfind(S[i])\n if k == -1:\n dp[i + 1][j + 1] = 1\n else:\n dp[i + 1][j + 1] = min(dp[i][j + 1], dp[i][k] + 1)\n return -1 if dp[m][n] == float('inf') else dp[m][n]", "def __init__():\n self.index = {}\n\ndef shortestunsub(S, T):\n n = len(S)\n m = len(T)\n maxx = 501\n dp = [[0] * (m + 1) for i in range(n + 1)]\n for i in range(1, n + 1):\n dp[i][0] = 1\n for j in range(m + 1):\n dp[0][j] = maxx\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n k = j - 1\n p = S[i - 1]\n if p == T[k]:\n self.index[p] = k\n elif p in self.index:\n k = self.index[p]\n else:\n while k >= 0:\n if S[i - 1] == T[k]:\n break\n k = k - 1\n self.index[p] = k\n if k == -1:\n dp[i][j] = 1\n else:\n dp[i][j] = min(dp[i - 1][j], 1 + dp[i - 1][k])\n finalans = dp[i][j]\n if finalans >= maxx:\n finalans = -1\n return finalans", "def shortestunsub(S, T):\n prev = [0 for _ in range(len(T) + 1)]\n for i in range(len(S), -1, -1):\n curr = [0 for _ in range(len(T) + 1)]\n for j in range(len(T), -1, -1):\n if i == len(S):\n curr[j] = float('inf')\n continue\n if j == len(T):\n curr[j] = 1\n continue\n k = T[j:].find(S[i])\n if k == -1:\n curr[j] = 1\n continue\n curr[j] = min(prev[j], 1 + prev[k + j + 1])\n prev = [k for k in curr]\n return -1 if curr[0] == float('inf') else curr[0]", "INV = 10 ** 9 + 7\n\ndef shortestunsub(S, T):\n (NS, NT) = (len(S), len(T))\n dp = [[1] * (NT + 1) for _ in range(NS + 1)]\n for j in range(NT + 1):\n dp[NS][j] = INV\n startidx = {}\n for c in S:\n if c in startidx:\n continue\n startidx[c] = arr = [-1] * NT\n prev = -1\n for j in range(NT - 1, -1, -1):\n prev = j if T[j] == c else prev\n arr[j] = prev\n for i in range(NS - 1, -1, -1):\n arr = startidx.get(S[i], None)\n if arr is None:\n return 1\n for j in range(NT - 1, -1, -1):\n if S[i] == T[j]:\n dp[i][j] = min(1 + dp[i + 1][j + 1], dp[i + 1][j])\n else:\n dp[i][j] = 1 if arr[j] < 0 else min(dp[i + 1][j], 1 + dp[i + 1][arr[j] + 1])\n return -1 if dp[0][0] >= INV else dp[0][0]", "import copy\nMAX = 10000\n\ndef shortestunsub(S, T):\n rightmost = {}\n rightMost = [dict()] * len(T)\n for i in range(len(T)):\n if i:\n rightMost[i] = copy.deepcopy(rightMost[i - 1])\n rightMost[i][T[i]] = i\n\n def shortunseq(S, T):\n m = len(S)\n n = len(T)\n dp = [[0 for i in range(n + 1)] for j in range(m + 1)]\n for i in range(m + 1):\n dp[i][0] = 1\n for i in range(n + 1):\n dp[0][i] = MAX\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n ch = S[i - 1]\n k = rightMost[j - 1].get(ch, -1)\n if k == -1:\n dp[i][j] = 1\n else:\n dp[i][j] = min(dp[i - 1][j], dp[i - 1][k] + 1)\n ans = dp[m][n]\n if ans >= MAX:\n ans = -1\n return ans\n return shortunseq(S, T)", "from collections import defaultdict\n\ndef shortestunsub(text1, text2):\n (n, m) = (len(text1), len(text2))\n mapp = defaultdict(lambda : -1)\n dp = [[0] * (m + 1) for i in range(n + 1)]\n for i in range(m + 1):\n dp[0][i] = 501\n for i in range(1, n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n mapp = defaultdict(lambda : -1)\n for j in range(1, m + 1):\n p = j - 1\n if text1[i - 1] == text2[p]:\n mapp[text1[i - 1]] = p\n p = mapp[text1[i - 1]]\n if p == -1:\n dp[i][j] = 1\n else:\n dp[i][j] = min(dp[i - 1][j], 1 + dp[i - 1][p])\n mapp[text2[j - 1]] = j - 1\n return dp[-1][-1] if dp[-1][-1] != 501 else -1", "def shortestunsub(S, T):\n dp = {0: 0}\n mem = dict()\n for length in range(1, len(S) + 1):\n dp2 = dict()\n for (s_start, t_start) in dp.items():\n visited = set()\n for i in range(s_start, len(S)):\n if S[i] not in visited:\n visited.add(S[i])\n if (S[i], t_start) not in mem:\n j = T.find(S[i], t_start)\n if j == -1:\n return length\n for pos in range(t_start, j + 1):\n if (S[i], pos) in mem:\n break\n mem[S[i], pos] = j\n dp2[i + 1] = max(dp2.get(i + 1, 0), mem[S[i], t_start] + 1)\n dp = dp2\n return -1", "def shortestunsub(S, T):\n n = len(S)\n m = len(T)\n dp = [[0] * (m + 1) for _ in range(n + 1)]\n MAX = float('inf')\n ind = dict()\n for i in range(m + 1):\n dp[0][i] = MAX\n for i in range(1, n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n k = j - 1\n ch = S[i - 1]\n if ch == T[k]:\n ind[ch] = k\n elif ch in ind:\n k = ind[ch]\n else:\n while k >= 0:\n if T[k] == ch:\n break\n k -= 1\n ind[ch] = k\n if k == -1:\n dp[i][j] = 1\n else:\n dp[i][j] = min(dp[i - 1][j], 1 + dp[i - 1][k])\n ans = dp[n][m]\n if ans >= MAX:\n ans = -1\n return ans", "def __init__():\n self.indice = {}\n\ndef shortestunsub(S, T):\n dp = [[0] * (len(T) + 1) for i in range(len(S) + 1)]\n for i in range(len(T) + 1):\n dp[0][i] = 501\n for i in range(1, len(S) + 1):\n dp[i][0] = 1\n for i in range(1, len(S) + 1):\n for j in range(1, len(T) + 1):\n k = j - 1\n char = S[i - 1]\n if char == T[k]:\n self.indice[char] = k\n elif char in self.indice:\n k = self.indice[char]\n else:\n while k >= 0:\n if T[k] == S[i - 1]:\n break\n k -= 1\n self.indice[char] = k\n if k == -1:\n dp[i][j] = 1\n else:\n dp[i][j] = min(dp[i - 1][j], 1 + dp[i - 1][k])\n res = dp[i][j]\n if res >= 501:\n res = -1\n return res", "def shortestunsub(S, T):\n best = [[-1] * (len(S) + 1) for _ in range(len(S))]\n bestbefore = [-1] * (len(S) + 1)\n for i in range(len(S)):\n tplaces = list(reversed([ind for (ind, c) in enumerate(T) if c == S[i]]))\n for l in range(1, i + 2):\n while tplaces and tplaces[-1] <= bestbefore[l - 1]:\n del tplaces[-1]\n best[i][l] = tplaces[-1] if tplaces else len(T)\n for l in range(1, i + 2):\n bestbefore[l] = max(bestbefore[l], best[i][l])\n minl = overflow = len(S) + 5\n for ilist in best:\n if len(T) in ilist:\n minl = min(minl, ilist.index(len(T)))\n return -1 if minl == overflow else minl", "from math import inf\n\ndef shortestunsub(S, T):\n (n, m) = (len(S), len(T))\n dp = [[inf for j in range(m + 1)] for i in range(n + 1)]\n for i in range(1, n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n k = T[:j].rfind(S[i - 1])\n if k == -1:\n dp[i][j] = 1\n else:\n dp[i][j] = min(dp[i - 1][j], dp[i - 1][k] + 1)\n return dp[n][m] if dp[n][m] != inf else -1"], "starter_code": "def shortestunsub(S, T):\n", "input_output": {"inputs": ["S = \"babab\"\r\nT = \"babba\"", "S = \"babhi\"\r\nT = \"babij\""], "outputs": ["3", "1"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/shortest-uncommon-subsequence5746/1", "Expected Auxiliary Space": "O(|S|*|T|)", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(|S|^{2}*|T|)", "entry_point": "shortestunsub", "task_id": "TACO_lite/86", "example": [[["babab", "babba"], ["babhi", "babij"]], ["3", "1"]]} +{"requirement": "Given a singly linked list, delete middle of the linked list. For example, if given linked list is 1->2->3->4->5 then linked list should be modified to 1->2->4->5.\nIf there are even nodes, then there would be two middle nodes, we need to delete the second middle element. For example, if given linked list is 1->2->3->4->5->6 then it should be modified to 1->2->3->5->6.\nIf the input linked list is NULL or has 1 node, then it should return NULL\nExample 1:\nInput:\nLinkedList: 1->2->3->4->5\nOutput: 1 2 4 5\nExample 2:\nInput:\nLinkedList: 2->4->6->7->5->1\nOutput: 2 4 6 5 1\nYour Task:\nThe task is to complete the function deleteMid() which should delete the middle element from the linked list and return the head of the modified linked list. If the linked list is empty then it should return NULL.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= N <= 1000\n1 <= value <= 1000", "solutions": ["def deleteMid(head):\n temp = head\n c = 0\n while temp != None:\n c += 1\n temp = temp.next\n mid = c // 2 - 1\n i = 0\n temp = head\n while i < mid:\n temp = temp.next\n i += 1\n temp.next = temp.next.next\n return head", "def deleteMid(head):\n if head.next == None or head == None:\n return None\n elif head.next.next == None:\n head.next = None\n else:\n p = head\n n = 1\n while p.next != None:\n n += 1\n p = p.next\n m = n // 2\n n = 1\n p = head\n while n != m:\n n += 1\n p = p.next\n p.next = p.next.next\n return head", "def deleteMid(head):\n slow = head\n fast = head\n prev = None\n while fast and fast.next:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n prev.next = slow.next\n slow = None\n return head", "def deleteMid(head):\n temp = head\n size = 0\n while temp != None:\n size += 1\n temp = temp.next\n reach = size // 2\n i = 0\n temp = head\n prev = None\n while temp != None and i < reach:\n i += 1\n prev = temp\n temp = temp.next\n prev.next = temp.next\n return head", "def deleteMid(head):\n temp = head\n count = 0\n while temp != None:\n count += 1\n temp = temp.next\n if count % 2 == 0:\n i = 1\n j = count // 2\n temp = head\n prev = None\n while i < j + 1:\n prev = temp\n temp = temp.next\n i += 1\n prev.next = temp.next\n else:\n i = 1\n j = count // 2\n prev = None\n temp = head\n while i <= j:\n prev = temp\n temp = temp.next\n i += 1\n prev.next = temp.next\n return head", "def deleteMid(head):\n n = 0\n m = head\n while m != None:\n n += 1\n m = m.next\n a = head\n for i in range(int(n / 2) - 1):\n a = a.next\n a.next = a.next.next\n return head", "def deleteMid(head):\n if not head.next:\n return\n slow = head\n fast = head.next.next\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n slow.next = slow.next.next\n return head", "def deleteMid(head):\n if head == None or head.next == None:\n return None\n prev = head\n slow = head\n fast = head\n while fast.next != None and fast.next.next != None:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n if fast.next == None:\n prev.next = slow.next\n else:\n slow.next = slow.next.next\n return head", "def deleteMid(head):\n if head == None or head.next == None:\n return head\n fast_pointer = head\n prev_of_slow = None\n slow_pointer = head\n while fast_pointer != None and fast_pointer.next != None:\n prev_of_slow = slow_pointer\n slow_pointer = slow_pointer.next\n fast_pointer = fast_pointer.next.next\n prev_of_slow.next = slow_pointer.next\n return head", "def deleteMid(head):\n slow = head\n fast = head\n prev = head\n if fast.next is None:\n return None\n while fast and fast.next:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n prev.next = slow.next\n return head", "def deleteMid(head):\n length = 0\n dummy = head\n while dummy:\n dummy = dummy.next\n length += 1\n if not head or length == 1:\n return None\n dummy = head\n k = length // 2\n while k - 1 > 0:\n dummy = dummy.next\n k -= 1\n x = dummy.next.next\n dummy.next = x\n return head", "def deleteMid(head):\n if head == None:\n return None\n if head.next == None:\n del head\n return None\n temp = head\n cnt = 0\n while temp:\n temp = temp.next\n cnt = cnt + 1\n mid = cnt // 2\n temp = head\n k = 1\n while temp:\n if k == mid:\n temp.next = temp.next.next\n temp = temp.next\n k = k + 1\n return head", "def deleteMid(head):\n if head is None or head.next is None:\n return None\n count = 0\n fast = head\n while fast.next is not None:\n count += 1\n fast = fast.next\n fast = head\n mid = count / 2\n loc = 0\n while loc < mid - 1:\n loc += 1\n fast = fast.next\n tempNode = None\n tempNode = fast.next\n if tempNode is None:\n fast.next = None\n else:\n fast.next = tempNode.next\n return head", "def deleteMid(head):\n new = head\n i = 1\n while new.next != None:\n i = i + 1\n new = new.next\n i = i // 2\n j = 1\n new = head\n while j < i:\n new = new.next\n j = j + 1\n new.next = new.next.next\n return head", "def deleteMid(head):\n temp = head\n count = 0\n while temp:\n count += 1\n temp = temp.next\n temp = head\n count = count // 2\n while count:\n prev = temp\n temp = temp.next\n count -= 1\n prev.next = temp.next\n return head", "def deleteMid(head):\n if head == None or head.next == None:\n return None\n else:\n p = head\n q = head\n prev = None\n while q and q.next:\n prev = p\n p = p.next\n q = q.next.next\n if p != None:\n prev.next = p.next\n return head", "def getmidprev(head):\n prev = None\n (slow, fast) = (head, head)\n while fast is not None and fast.next is not None:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n return prev\n\ndef deleteMid(head):\n midprev = getmidprev(head)\n if midprev is None:\n return None\n midprev.next = midprev.next.next\n return head", "def deleteMid(head):\n cur = head\n fast = head\n prev = Node(0)\n h = prev\n prev.next = cur\n while fast and fast.next:\n cur = cur.next\n prev = prev.next\n fast = fast.next.next\n prev.next = cur.next\n return h.next", "def deleteMid(head):\n slow = head\n fast = head.next.next\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n slow.next = slow.next.next\n return head", "def deleteMid(head):\n if head.next is None:\n return None\n temp = head\n len = 0\n while temp:\n len += 1\n temp = temp.next\n temp = head\n for i in range(len // 2 - 1):\n temp = temp.next\n node2Del = temp.next\n temp.next = temp.next.next\n node2Del.next = None\n return head", "def deleteMid(head):\n slow = head\n fast = head.next\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n temp = slow.next\n slow.next = temp.next\n del temp\n return head", "def deleteMid(head):\n fast = slow = head\n pre = None\n while fast and fast.next:\n pre = slow\n slow = slow.next\n fast = fast.next.next\n pre.next = pre.next.next\n return head", "def deleteMid(head):\n if not head or not head.next:\n return None\n (ptr1, ptr2) = (head, head.next)\n while ptr2 and ptr2.next:\n ptr1 = ptr1.next\n ptr2 = ptr2.next.next if ptr2.next else ptr2.next\n ptr1.data = ptr1.data if ptr2 else ptr1.next.data\n ptr1.next = ptr1.next.next\n return head", "def deleteMid(head):\n cur = head\n count = n = 0\n while cur:\n count = count + 1\n cur = cur.next\n if count == 0 or count == 1:\n return NULL\n if count % 2 == 0:\n cur = head\n while n != count / 2 - 1:\n n = n + 1\n cur = cur.next\n temp = cur.next\n cur.next = cur.next.next\n del temp\n return head\n else:\n cur = head\n while n != count // 2 - 1:\n n = n + 1\n cur = cur.next\n temp = cur.next\n cur.next = cur.next.next\n del temp\n return head", "def deleteMid(head):\n if head is None or head.next is None:\n return head\n slow_ptr = head\n fast_ptr = head.next.next\n while fast_ptr is not None and fast_ptr.next is not None:\n slow_ptr = slow_ptr.next\n fast_ptr = fast_ptr.next.next\n temp = slow_ptr.next\n slow_ptr.next = temp.next\n temp = None\n return head\n\ndef __init__(data):\n self.data = data\n self.next = None", "def deleteMid(head):\n if head.next == None:\n return None\n if head.next.next == None:\n head.next = head.next.next\n return head\n fast = head\n slow = head\n while fast.next and fast.next.next:\n fast = fast.next.next\n slow = slow.next\n if fast.next:\n slow = slow.next\n slow.data = slow.next.data\n slow.next = slow.next.next\n return head", "def deleteMid(head):\n if head is None or head.next is None:\n return head\n curr = head\n prev = head\n next = None\n while curr != None and curr.next != None:\n curr = curr.next.next\n next = prev\n prev = prev.next\n next.next = prev.next\n return head", "def deleteMid(head):\n slow = head\n fast = head\n dummy = Node(-1)\n dummy.next = head\n prev = dummy\n while fast and fast.next:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n prev.next = slow.next\n return dummy.next", "def deleteMid(head):\n l = 0\n a = head\n while a != None:\n l += 1\n a = a.next\n mid = l // 2\n l = 0\n prev = None\n cur = head\n front = head.next\n while l < mid:\n l += 1\n prev = cur\n cur = front\n front = front.next\n prev.next = front\n return head", "def deleteMid(head):\n p = head\n q = head\n temp = None\n while p and p.next:\n temp = q\n q = q.next\n p = p.next.next\n if temp == None:\n return None\n temp.next = temp.next.next\n return head", "def deleteMid(head):\n c = 0\n temp = head\n while temp:\n c += 1\n temp = temp.next\n mid = c // 2\n temp = head\n k = 1\n while temp:\n if k == mid:\n temp.next = temp.next.next\n temp = temp.next\n k += 1\n return head", "def deleteMid(head):\n c = 0\n curr = head\n while curr != None:\n c += 1\n curr = curr.next\n curr = head\n for i in range(c // 2 - 1):\n curr = curr.next\n curr.next = curr.next.next\n return head", "def deleteMid(head):\n fast = head\n slow = head\n while fast != None and fast.next != None:\n slow = slow.next\n fast = fast.next.next\n mid = slow\n temp = head\n while temp.next != mid:\n temp = temp.next\n val = mid.next\n temp.next = val\n mid = None\n return head", "def deleteMid(head):\n start = head\n length = 0\n while start != None:\n length += 1\n start = start.next\n mid = int(length / 2) + 1\n start = 1\n start_node = head\n while start < mid - 1:\n start += 1\n start_node = start_node.next\n start_node.next = start_node.next.next\n return head", "def deleteMid(head):\n n = head\n i = 0\n while n is not None:\n i = i + 1\n n = n.next\n x = i // 2\n if i - x == 1:\n head.next = None\n else:\n n = head\n for i in range(0, x):\n n = n.next\n n.data = n.next.data\n n.next = n.next.next\n return head", "def deleteMid(head):\n slow = fast = head\n t = None\n while fast and fast.next:\n tmp = slow\n slow = slow.next\n fast = fast.next.next\n tmp.next = slow.next\n return head", "def deleteMid(head):\n pre = None\n rabbit = head\n tortoise = head\n while rabbit and rabbit.next:\n pre = tortoise\n rabbit = rabbit.next.next\n tortoise = tortoise.next\n pre.next = tortoise.next\n return head", "def deleteMid(head):\n temp = head\n count = 0\n while temp:\n count += 1\n temp = temp.next\n temp = head\n for i in range(count // 2 - 1):\n temp = temp.next\n temp.next = temp.next.next\n return head", "def deleteMid(head):\n temp = head\n count = 0\n while temp != None:\n count += 1\n temp = temp.next\n temp = head\n count = count // 2\n while count - 1:\n temp = temp.next\n count -= 1\n temp.next = temp.next.next\n return head", "def deleteMid(head):\n if head is None:\n return head\n if head.next is None:\n return None\n fast = slow = head\n pre = None\n while fast and fast.next:\n fast = fast.next.next\n pre = slow\n slow = slow.next\n if pre is not None:\n pre.next = slow.next\n return head", "def deleteMid(head):\n count = 0\n temp = head\n if head == None:\n return head\n if head.next == None:\n return None\n while temp:\n count += 1\n temp = temp.next\n mid = count // 2\n st = head\n while mid > 1:\n st = st.next\n mid = mid - 1\n temp = st.next\n st.next = st.next.next\n del temp\n return head", "def deleteMid(head):\n slow = head\n fast = head\n temp = None\n while fast != None and fast.next != None:\n temp = slow\n slow = slow.next\n fast = fast.next.next\n if temp == None:\n return None\n temp.next = temp.next.next\n return head", "def deleteMid(head):\n if head is None:\n return None\n temp = head\n temp2 = head\n count = 0\n while temp is not None:\n count = count + 1\n temp = temp.next\n i = 1\n while i < count // 2:\n i = i + 1\n temp2 = temp2.next\n temp_next = temp2.next\n temp2.next = temp_next.next\n temp_next.next = None\n return head", "def deleteMid(head):\n p = head\n c1 = 0\n c2 = 0\n while p:\n c1 = c1 + 1\n p = p.next\n c3 = c1 // 2 + 1\n if c3 <= 1:\n return None\n p = head\n q = None\n while p:\n c2 = c2 + 1\n if c2 == c3:\n q.next = p.next\n q = p\n p = p.next\n return head", "def deleteMid(head):\n temp = head\n if head == None:\n return head\n c = 0\n while temp != None:\n c += 1\n temp = temp.next\n d = int(c / 2)\n temp = head\n for i in range(d - 1):\n temp = temp.next\n temp.next = temp.next.next\n return head", "def deleteMid(head):\n fast = head\n slow = head\n tail = None\n while fast != None and fast.next != None:\n tail = slow\n slow = slow.next\n fast = fast.next.next\n tail.next = slow.next\n del slow\n return head", "def deleteMid(head):\n if head == None:\n return None\n if head.next == None:\n del head\n return None\n (temp, count) = (head, 0)\n while temp:\n temp = temp.next\n count += 1\n m = count // 2\n (temp, k) = (head, 1)\n while temp:\n if k == m:\n temp.next = temp.next.next\n temp = temp.next\n k += 1\n return head", "def deleteMid(head):\n slow = head\n fast = head\n new = head\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n if fast.next:\n if fast.next.next == None:\n slow.next = slow.next.next\n else:\n while new.next != slow:\n new = new.next\n new.next = new.next.next\n return head", "def deleteMid(head):\n slow = head\n fast = head\n prev = Node(0)\n while fast != None and fast.next != None:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n prev.next = prev.next.next\n return head", "def deleteMid(head):\n cur = head\n ans = []\n while cur:\n ans.append(cur.data)\n cur = cur.next\n ind = len(ans) // 2\n ans.pop(ind)\n l = Node(0)\n h = l\n for i in ans:\n n = Node(i)\n l.next = n\n l = l.next\n return h.next", "def deleteMid(head):\n temp = head\n r = head\n count = 0\n while temp is not None:\n temp = temp.next\n count += 1\n for i in range(count // 2 - 1):\n head = head.next\n head.next = head.next.next\n return r", "def deleteMid(head):\n c = a = b = head\n b = b.next.next\n while b and b.next:\n a = a.next\n b = b.next.next\n a.next = a.next.next\n return c", "def deleteMid(head):\n i = 0\n t = head\n while t:\n t = t.next\n i += 1\n t1 = head\n for j in range(i):\n if j == i // 2 - 1:\n t1.next = t1.next.next\n break\n t1 = t1.next\n return head", "def deleteMid(head):\n slow = head\n fast = head\n ptr = None\n if head == None:\n return None\n while fast and fast.next:\n ptr = slow\n slow = slow.next\n fast = fast.next.next\n ptr.next = slow.next\n slow.next = None\n return head", "def deleteMid(head):\n count = 0\n curr = head\n while curr is not None:\n count += 1\n curr = curr.next\n if count <= 1:\n return None\n nodeToDel = count // 2 + 1\n cnt = 0\n curr = head\n while cnt < nodeToDel - 2:\n cnt += 1\n curr = curr.next\n curr.next = curr.next.next\n return head", "def deleteMid(head):\n lst = []\n while head:\n lst.append(head.data)\n head = head.next\n del lst[len(lst) // 2]\n a = Node(0)\n temp = a\n for i in lst:\n temp.next = Node(i)\n temp = temp.next\n return a.next", "def deleteMid(head):\n if head == None or head.next == None:\n return None\n temp = head\n length = 0\n while temp != None:\n length += 1\n temp = temp.next\n length = length // 2\n i = 0\n temp = head\n prev = None\n while i < length:\n prev = temp\n temp = temp.next\n i += 1\n prev.next = temp.next\n temp.next = None\n return head", "def deleteMid(head):\n c = length(head)\n mid = c // 2\n itr = head\n i = 0\n while itr:\n if mid - 1 == i:\n itr.next = itr.next.next\n i += 1\n itr = itr.next\n return head\n\ndef length(head):\n c = 0\n itr = head\n while itr:\n c += 1\n itr = itr.next\n return c", "def deleteMid(head):\n if head == None:\n return None\n if head.next == None:\n del head\n return None\n c = 0\n t = head\n while t:\n c += 1\n t = t.next\n mid = c // 2\n t = head\n k = 1\n while t:\n if k == mid:\n t.next = t.next.next\n t = t.next\n k += 1\n return head", "def deleteMid(head):\n fast = slow = head\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n curr = head\n while curr.next != slow:\n curr = curr.next\n if slow.next is None:\n curr.next = None\n else:\n curr.next = slow.next\n return head", "import math\n\ndef deleteMid(head):\n count = 1\n temp = head\n while temp.next:\n count += 1\n temp = temp.next\n n = math.floor(count / 2)\n temp1 = head\n i = 0\n while i < n - 1:\n temp1 = temp1.next\n i += 1\n temp1.next = temp1.next.next\n return head", "def deleteMid(head):\n if head is None:\n return head\n if head.next is None:\n return Null\n temp = head\n c = 0\n while temp:\n c += 1\n temp = temp.next\n b = c // 2\n temp = head\n i = 1\n while temp:\n if i == b:\n temp.next = temp.next.next\n temp = temp.next\n i += 1\n return head", "def deleteMid(head):\n stack = [head]\n count = 0\n while len(stack) > 0:\n current = stack.pop()\n count += 1\n if current.next:\n stack.append(current.next)\n if count > 1:\n stack.append(head)\n for i in range(count // 2 - 1):\n current = stack.pop()\n stack.append(current.next)\n current = stack.pop()\n current.next = current.next.next\n return head\n else:\n return None", "def deleteMid(head):\n temp = head\n length = 1\n while temp.next:\n temp = temp.next\n length += 1\n mid = length // 2\n temp = head\n k = 1\n while temp:\n if k == mid:\n temp.next = temp.next.next\n temp = temp.next\n k += 1\n return head", "def deleteMid(head):\n ans = Node(123)\n p = ans\n p.next = head\n s = head\n f = head.next\n while f and f.next:\n f = f.next.next\n s = s.next\n p = p.next\n if f:\n s.next = s.next.next\n return ans.next\n elif not f:\n p.next = p.next.next\n return ans.next", "def deleteMid(head):\n dummy = Node(0)\n dummy.next = head\n (slow, fast) = (dummy, head)\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n slow.next = slow.next.next\n return dummy.next", "def deleteMid(head):\n slow = head\n fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n mid = slow\n temp = head\n while temp.next != mid:\n temp = temp.next\n temp.next = mid.next\n return head"], "starter_code": "def __init__(data):\n", "input_output": {"inputs": ["LinkedList:1->2->3->4->5", "LinkedList:2->4->6->7->5->1"], "outputs": ["1 2 4 5", "2 4 6 5 1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Algorithms", "two-pointer-algorithm", "Linked List"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Amortized analysis"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/delete-middle-of-linked-list/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "__init__", "task_id": "TACO_lite/19", "example": [[], []]} +{"requirement": "You are given a binary string s and an integer m. You need to return an integer r. Where r = k%m, k is the binary equivalent of string s.\nExample 1:\nInput:\ns = \"101\" \nm = 2\nOutput:\n1\nExplanation: Here k=5 because (101)_{2} = (5)_{10}.\nHence 5 mod 2 = 1.\nExample 2:\nInput:\ns = \"1000\"\nm = 4\nOutput:\n0\nExplanation: Here k=8 and m=4 hence \nr = k mod m = 8 mod 4 = 0.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function modulo() which takes the string s and integer m as input parameters and returns the value of r as described above.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 <= len(s) <= 10^{7}\n1 <= m <= 100", "solutions": ["def modulo(s, m):\n k = int(s, 2)\n return k % m", "def modulo(s, m):\n rs = 0\n lenS = len(s)\n i = 0\n while i < lenS:\n while i < lenS and rs < m:\n rs = (rs << 1) + int(s[i])\n i += 1\n if rs >= m:\n rs = int(rs % m)\n return rs", "def modulo(s, m):\n c = int(s, 2)\n return c % m", "def modulo(s, m):\n a = int(s, 2)\n return a % m", "def modulo(s, m):\n n = len(s)\n s = s[::-1]\n res = 0\n p = [0] * n\n p[0] = 1\n tmp = 0\n for i in range(1, n):\n p[i] = 2 * p[i - 1] % m\n for i in range(n):\n if s[i] == '1':\n tmp += p[i]\n tmp %= m\n return tmp", "def modulo(s, m):\n r = int(s, 2)\n return r % m", "def modulo(s, m):\n dec = int(s, 2)\n return dec % m", "def modulo(s, m):\n x = int(s, 2)\n return x % m", "def modulo(s, m):\n decimal = 0\n for digit in s:\n if digit == '1':\n decimal = decimal * 2 + 1\n else:\n decimal = decimal * 2\n return decimal % m", "def modulo(s, m):\n n = int(s, 2)\n return n % m", "def modulo(s, m):\n num = int(s, 2)\n ans = num % m\n return ans", "def modulo(s, m):\n res = int(s, 2)\n return res % m", "def modulo(s, m):\n total = 0\n for x in s:\n total = (total * 2 + int(x)) % m\n return total", "def modulo(s, m):\n d = int(s, 2)\n return d % m", "def modulo(s, m):\n r = 0\n for c in s:\n r = (r * 2 + int(c)) % m\n return r", "def modulo(s, m):\n p = [1]\n for i in range(1, len(s) + 1):\n p.append(p[-1] * 2 % m)\n k = 0\n for i in range(len(s)):\n k = (k * 2 + int(s[i])) % m\n return k", "def modulo(s, m):\n number = int(s, 2)\n return number % m", "def modulo(s, m):\n r = 0\n for c in s:\n r = r * 2\n if c == '1':\n r += 1\n if r >= m:\n r -= m\n return r", "import math\n\ndef modulo(s, m):\n return int(s, 2) % m", "def modulo(s: str='0', m: int=1) -> int:\n if not all((char in '01' for char in s)):\n raise ValueError('Input string must be a binary string.')\n if m <= 0:\n raise ValueError('Modulus must be a positive integer greater than zero.')\n k = int(s, 2)\n r = k % m\n return r", "def modulo(s, m):\n t = int(s, 2)\n return t % m", "def modulo(s, m):\n mom = int(s, 2)\n return mom % m", "def modulo(s, m):\n v = 0\n for i in range(len(s)):\n v = (v * 2 + (1 if s[i] == '1' else 0)) % m\n return v % m", "def modulo(s, m):\n temp = 0\n pow = 1\n c = 0\n return int(s, 2) % m", "def modulo(s, m):\n r = 0\n n = len(s)\n power_of_2 = [1] * n\n for i in range(n - 2, -1, -1):\n power_of_2[i] = (power_of_2[i + 1] << 1) % m\n for i in range(n):\n if s[i] == '1':\n r = (r + power_of_2[i]) % m\n return r", "def modulo(s, m):\n b = 0\n a = len(s) - 1\n i = len(s) - 1\n p = 1\n while i >= 0:\n if s[i] == '1':\n b += p\n b = b % m\n p = p * 2\n p = p % m\n i -= 1\n return b", "def modulo(s, m):\n ans = 0\n power = 1\n for i in range(len(s) - 1, -1, -1):\n if s[i] == '1':\n ans += power\n ans %= m\n power *= 2\n power %= m\n return ans", "def modulo(s, m):\n n = len(s)\n prefix_mod = [0] * n\n prefix_mod[0] = int(s[0]) % m\n for i in range(1, n):\n prefix_mod[i] = (prefix_mod[i - 1] * 2 % m + int(s[i])) % m\n return prefix_mod[n - 1]", "def modulo(s, m):\n integerval = int(s, 2)\n ans = integerval % m\n return int(ans)", "def modulo(s, m):\n dig = int(s, 2)\n return dig % m", "def modulo(s, m):\n n = len(s)\n res = 0\n cur = 1\n for i in range(n - 1, -1, -1):\n if s[i] == '1':\n res += cur\n res %= m\n cur <<= 1\n cur %= m\n return res % m"], "starter_code": "def modulo(s, m):\n", "input_output": {"inputs": ["s = \"101\" \nm = 2", "s = \"1000\"\nm = 4"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Bit Magic", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Mathematics"], "skill_types": ["Bit manipulation"], "url": "https://practice.geeksforgeeks.org/problems/7488b7721e8aa5e5fc37d56af8b9c89e329c796f/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "modulo", "task_id": "TACO_lite/24", "example": [[["101", 2], ["1000", 4]], ["1", "0"]]} +{"requirement": "Write a method that will search an array of strings for all strings that contain another string, ignoring capitalization. Then return an array of the found strings. \n\nThe method takes two parameters, the query string and the array of strings to search, and returns an array. \n\nIf the string isn't contained in any of the strings in the array, the method returns an array containing a single string: \"Empty\" (or `Nothing` in Haskell, or \"None\" in Python and C)\n\n### Examples\nIf the string to search for is \"me\", and the array to search is [\"home\", \"milk\", \"Mercury\", \"fish\"], the method should return [\"home\", \"Mercury\"].", "solutions": ["def word_search(query, seq):\n return [x for x in seq if query.lower() in x.lower()] or ['None']", "def word_search(query, seq):\n query = query.lower()\n result = [x for x in seq if query in x.lower()]\n return result if result else ['None']", "import re\n\ndef word_search(query, seq):\n return [w for w in seq if re.search(query, w, re.I)] or ['None']", "def word_search(query, seq):\n l = [i for i in seq if query.lower() in i.lower()]\n return [l, ['None']][not l]", "def word_search(query, seq):\n query = query.lower()\n return [word for word in seq if query in word.lower()] or ['None']", "def word_search(q, l):\n return [w for w in l if q.lower() in w.lower()] or ['None']", "def word_search(query, seq):\n query = query.lower()\n return [a for a in seq if query in a.lower()] or ['None']", "def word_search(query, seq):\n return [i for i in seq if query.lower() in i.lower()] or ['None']", "def word_search(query, seq):\n array = []\n for x in seq:\n if query.lower() in x.lower():\n array.append(x)\n else:\n pass\n if array != []:\n return array\n else:\n array = ['None']\n return array"], "starter_code": "def word_search(query, seq):\n", "input_output": {"fn_name": "word_search", "inputs": [["ab", ["za", "ab", "abc", "zab", "zbc"]], ["aB", ["za", "ab", "abc", "zab", "zbc"]], ["ab", ["za", "aB", "Abc", "zAB", "zbc"]], ["abcd", ["za", "aB", "Abc", "zAB", "zbc"]]], "outputs": [[["ab", "abc", "zab"]], [["ab", "abc", "zab"]], [["aB", "Abc", "zAB"]], [["None"]]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/54b81566cd7f51408300022d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "word_search", "task_id": "TACO_lite/12", "example": [[["me", ["home", "milk", "Mercury", "fish"]]], ["['home', 'Mercury']"]]} +{"requirement": "Create a program that will take in a string as input and, if there are duplicates of more than two alphabetical characters in the string, returns the string with all the extra characters in a bracket.\n\nFor example, the input \"aaaabbcdefffffffg\" should return \"aa[aa]bbcdeff[fffff]g\" \n\nPlease also ensure that the input is a string, and return \"Please enter a valid string\" if it is not.", "solutions": ["import re\n\ndef string_parse(string):\n return re.sub('(.)\\\\1(\\\\1+)', '\\\\1\\\\1[\\\\2]', string) if isinstance(string, str) else 'Please enter a valid string'", "import re\n\ndef string_parse(s):\n if not isinstance(s, str):\n return 'Please enter a valid string'\n for l in set(s):\n s = re.sub('(%s%s)(%s+)' % (l, l, l), '\\\\1[\\\\2]', s)\n return s", "from functools import partial\nfrom re import compile\nREGEX = partial(compile('(.)\\\\1(\\\\1+)').sub, '\\\\1\\\\1[\\\\2]')\n\ndef string_parse(string):\n return REGEX(string) if type(string) == str else 'Please enter a valid string'", "import re\n\ndef string_parse(string):\n try:\n\n def replace(match):\n return '{0}{0}[{1}]'.format(*match.group(1, 2))\n return re.sub('(.)\\\\1(\\\\1+)', replace, string)\n except TypeError:\n return 'Please enter a valid string'", "from itertools import groupby\n\ndef string_parse(string):\n if isinstance(string, str):\n gs = groupby(string)\n f = lambda s: s if len(s) < 3 else s[:2] + '[' + s[2:] + ']'\n return ''.join([f(''.join(list(g))) for (_, g) in groupby(string)])\n else:\n return 'Please enter a valid string'", "from itertools import groupby\n\ndef string_parse(string):\n return ''.join((f'{x * 2}[{x * (c - 2)}]' if c > 2 else x * c for (x, c) in [(x, len(list(gp))) for (x, gp) in groupby(string)])) if isinstance(string, str) else 'Please enter a valid string'", "def string_parse_gen(string):\n (counter, prev_char) = (0, '')\n for char in string:\n if char == prev_char:\n counter += 1\n if counter == 2:\n yield '['\n else:\n if counter >= 2:\n yield ']'\n prev_char = char\n counter = 0\n yield char\n if counter >= 2:\n yield ']'\n\ndef string_parse(string):\n return ''.join(list(string_parse_gen(string))) if isinstance(string, str) else 'Please enter a valid string'", "def string_parse(s):\n from itertools import groupby\n if not isinstance(s, str):\n return 'Please enter a valid string'\n x = [(i, sum([1 for j in group])) for (i, group) in groupby(s)]\n x = [i[0] * 2 + '[' + i[0] * (i[1] - 2) + ']' if i[1] >= 2 else i[0] for i in x]\n x = ''.join(x)\n x = x.replace('[]', '')\n return x", "import re\n\ndef string_parse(string):\n if not isinstance(string, str):\n return 'Please enter a valid string'\n\n def repl(Match):\n s = Match[0]\n n = len(s)\n c = s[0]\n return s if n <= 2 else c * 2 + f'[{c * (n - 2)}]'\n return re.sub('(\\\\w)\\\\1*', repl, string)", "import re\n\ndef string_parse(s):\n try:\n return re.sub('(.)\\\\1+', lambda m: m.group()[0:2] + '[' + m.group()[2:] + ']' if len(m.group()) > 2 else m.group(), s)\n except TypeError:\n return 'Please enter a valid string'", "import re\n\ndef string_parse(s):\n return re.sub('((.)\\\\2*)', lambda x: f'{2 * x[2]}[{x[1][:len(x[1]) - 2]}]' if len(x[1]) > 2 else x[1], s) if isinstance(s, str) else 'Please enter a valid string'", "def string_parse(string):\n if not isinstance(string, str):\n return 'Please enter a valid string'\n res = []\n count = 0\n last_char = None\n for c in string:\n if c != last_char:\n if count > 2:\n res.append(']')\n count = 0\n elif count == 2:\n res.append('[')\n count += 1\n last_char = c\n res.append(c)\n if count > 2:\n res.append(']')\n return ''.join(res)", "from itertools import groupby\n\ndef string_parse(str_in):\n if not isinstance(str_in, str):\n return 'Please enter a valid string'\n str_out = []\n for (_, group) in groupby(str_in):\n s = ''.join(group)\n str_out.append(s if len(s) < 3 else f'{s[:2]}[{s[2:]}]')\n return ''.join(str_out)", "def string_parse(string):\n if type(string) != str:\n return 'Please enter a valid string'\n try:\n out = string[:2]\n temp = ''\n for i in string[2:]:\n if i == out[-1] == out[-2]:\n temp += i\n else:\n if temp != '':\n out += '[' + temp + ']'\n out += i\n temp = ''\n if temp != '':\n out += '[' + temp + ']'\n return out\n except:\n return 'Please enter a valid string'", "def string_parse(string):\n if not isinstance(string, str):\n return 'Please enter a valid string'\n letters = ['0']\n for i in string:\n if i == letters[-1][-1]:\n letters[-1] += i\n else:\n letters.append(i)\n return ''.join([i if len(i) < 3 else f'{i[:2]}[{i[2:]}]' for i in letters][1:])", "import re\n\ndef string_parse(string):\n if not type(string) == str:\n return 'Please enter a valid string'\n return re.sub('(([a-zA-Z])\\\\2)(\\\\2+)', lambda x: x.group(1) + '[' + x.group(3) + ']', string)", "def string_parse(string):\n if string == None or not isinstance(string, str):\n return 'Please enter a valid string'\n if string == '':\n return ''\n res = ''\n current_char = string[0]\n char_counter = 1\n for i in range(1, len(string)):\n if current_char == string[i]:\n if char_counter + 1 <= 2:\n res += current_char\n char_counter += 1\n continue\n elif char_counter + 1 == 3:\n res = res + current_char + '['\n char_counter += 1\n continue\n elif char_counter + 1 > 3:\n res += current_char\n char_counter += 1\n else:\n if char_counter > 2:\n res = res + current_char + ']'\n else:\n res += current_char\n current_char = string[i]\n char_counter = 1\n res = res + current_char if char_counter <= 2 else res + current_char + ']'\n return res", "import re\n\ndef string_parse(string):\n if type(string) != str:\n return 'Please enter a valid string'\n for c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':\n string = re.sub(c + '{2}(' + c + '+)', c * 2 + '[\\\\g<1>]', string)\n return string", "def string_parse(string):\n if not isinstance(string, str):\n return 'Please enter a valid string'\n if len(string) == 0:\n return ''\n Di = {}\n text = ''\n f = 0\n i = 0\n f2 = 0\n for i in range(len(string) - 1):\n Di.setdefault(string[i], 0)\n text += string[i]\n Di[string[i]] += 1\n if not f and Di[string[i]] >= 2 and (string[i] == string[i + 1]):\n text += '['\n f = 1\n if f and Di[string[i]] >= 2 and (string[i] != string[i + 1]):\n text += ']'\n f = 0\n f2 = 1\n if not f and string[i] != string[i + 1]:\n Di[string[i]] = 0\n text += string[-1]\n if f:\n text += ']'\n return text"], "starter_code": "def string_parse(string):\n", "input_output": {"fn_name": "string_parse", "inputs": [["aaaabbcdefffffffg"], [3], ["boopdedoop"], ["helloookat"], [true], [""], ["aAAabbcdeffFfFffg"], ["aAAabbcdeFFFffffg"], [{}], [[5.3]]], "outputs": [["aa[aa]bbcdeff[fffff]g"], ["Please enter a valid string"], ["boopdedoop"], ["helloo[o]kat"], ["Please enter a valid string"], [""], ["aAAabbcdeffFfFffg"], ["aAAabbcdeFF[F]ff[ff]g"], ["Please enter a valid string"], ["Please enter a valid string"]]}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5411c4205f3a7fd3f90009ea", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "string_parse", "task_id": "TACO_lite/65", "example": [[["aaaabbcdefffffffg"], [12345]], ["aa[aa]bbcdeff[fffff]g", "Please enter a valid string"]]} +{"requirement": "You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.\n\n#Examples:\n~~~if-not:bf\n```\nKata.getMiddle(\"test\") should return \"es\"\n\nKata.getMiddle(\"testing\") should return \"t\"\n\nKata.getMiddle(\"middle\") should return \"dd\"\n\nKata.getMiddle(\"A\") should return \"A\"\n\n```\n~~~\n~~~if:bf\n```\nrunBF(\"test\\0\") should return \"es\"\n\nrunBF(\"testing\\0\") should return \"t\"\n\nrunBF(\"middle\\0\") should return \"dd\"\n\nrunBF(\"A\\0\") should return \"A\"\n\n```\n~~~\n\n#Input\n\nA word (string) of length `0 < str < 1000` (In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases). You do not need to test for this. This is only here to tell you that you do not need to worry about your solution timing out.\n\n\n#Output\n\nThe middle character(s) of the word represented as a string.", "solutions": ["def get_middle(s):\n return s[(len(s) - 1) // 2:len(s) // 2 + 1]", "def get_middle(s):\n (index, odd) = divmod(len(s), 2)\n return s[index] if odd else s[index - 1:index + 1]", "import math\n\ndef get_middle(s):\n x = len(s)\n y = int(x / 2)\n if x % 2 == 0:\n return s[y - 1:y + 1]\n else:\n return s[y:y + 1]", "def get_middle(s):\n i = (len(s) - 1) // 2\n return s[i:-i] or s", "def get_middle(s):\n x = int(len(s) / 2)\n return s[x] if len(s) % 2 != 0 else s[x - 1:x + 1]", "def get_middle(s):\n (q, r) = divmod(len(s), 2)\n return s[q - (1 if not r else 0):q + 1]", "def get_middle(s):\n if len(s) % 2 == 0:\n iA = int(len(s) / 2 - 1)\n iB = int(len(s) / 2 + 1)\n return s[iA:iB]\n else:\n return s[int(len(s) / 2)]"], "starter_code": "def get_middle(s):\n", "input_output": {"fn_name": "get_middle", "inputs": [["test"], ["testing"], ["middle"], ["A"], ["of"]], "outputs": [["es"], ["t"], ["dd"], ["A"], ["of"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56747fd5cb988479af000028", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "get_middle", "task_id": "TACO_lite/52", "example": [[["test"], ["testing"], ["middle"], ["A"]], ["es", "t", "dd", "A"]]} +{"requirement": "Thanks to the effects of El Nino this year my holiday snorkelling trip was akin to being in a washing machine... Not fun at all.\n\nGiven a string made up of '~' and '\\_' representing waves and calm respectively, your job is to check whether a person would become seasick.\n\nRemember, only the process of change from wave to calm (and vice versa) will add to the effect (really wave peak to trough but this will do). Find out how many changes in level the string has and if that figure is more than 20% of the string, return \"Throw Up\", if less, return \"No Problem\".", "solutions": ["def sea_sick(sea):\n return 'Throw Up' if (sea.count('~_') + sea.count('_~')) / len(sea) > 0.2 else 'No Problem'", "def sea_sick(sea):\n changes = sum((1 for (a, b) in zip(sea, sea[1:]) if a != b))\n return 'No Problem' if changes * 5 <= len(sea) else 'Throw Up'", "def sea_sick(sea):\n waves = sum((sea[i:i + 2] in '_~_' for i in range(len(sea) - 1)))\n if waves / float(len(sea)) > 0.2:\n return 'Throw Up'\n return 'No Problem'", "from operator import truediv\n\ndef sea_sick(s):\n result = sum((s[a:a + 2] in '_~_' for a in range(len(s) - 1)))\n if truediv(result, len(s)) > 0.2:\n return 'Throw Up'\n return 'No Problem'", "sea_sick = lambda s: ['No Problem', 'Throw Up'][s.count('~_') + s.count('_~') > 0.2 * len(s)]", "def sea_sick(sea):\n return 'Throw Up' if sum((x != y for (x, y) in zip(sea, sea[1:]))) / len(sea) > 0.2 else 'No Problem'", "sea_sick = lambda s: ['No Problem', 'Throw Up'][sum(__import__('itertools').starmap(str.__ne__, zip(s, s[1:]))) / len(s) > 0.2]", "def sea_sick(sea):\n (c, p) = (0, sea[0])\n for s in sea[1:]:\n if s != p:\n c += 1\n p = s\n return 'Throw Up' if c / len(sea) > 0.2 else 'No Problem'"], "starter_code": "def sea_sick(sea):\n", "input_output": {"fn_name": "sea_sick", "inputs": [["~"], ["_~~~~~~~_~__~______~~__~~_~~"], ["______~___~_"], ["____"], ["_~~_~____~~~~~~~__~_~"]], "outputs": [["No Problem"], ["Throw Up"], ["Throw Up"], ["No Problem"], ["Throw Up"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57e90bcc97a0592126000064", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sea_sick", "task_id": "TACO_lite/99", "example": [[], []]} +{"requirement": "An english word is given as input and it is modified using some format. Identify the format using the examples given below (examples given are sufficient to identify the format) and print the modified word as output.\nSTEWART is modified as EWARTSTAY, AMAR is modified as AMAR, MAN is modified as ANMAY etc.\nNote: Input contains uppercase english words.\n \nExample 1:\nInput:\nS = \"GEEK\"\nOutput:\nEEKGAY\nExplanation:\nThe string when modified gives \"EEKGAY\".\nExample 2:\nInput:\nS = \"ALL\"\nOutput:\nALL\nExplanation:\nThe string when modified remains the same.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function englishWords() which takes a String S as input and returns the modified String.\n \nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(|S|)\n \nConstraints:\n1 <= |S| <= 10^{5}", "solutions": ["def englishwords(S):\n x = ['A', 'E', 'I', 'O', 'U']\n p = ''\n t = ''\n for i in S:\n if i not in x:\n p += i\n else:\n l = S.index(i)\n t = S[l:]\n break\n t += p\n if t == S:\n return S\n return t + 'AY'", "def englishwords(S):\n x = 'AEIOU'\n if S[0] in x:\n return S\n c = 0\n for i in S:\n if i in x:\n break\n c += 1\n r = S[c:]\n r = r + S[:c] + 'AY'\n return r", "def englishwords(s):\n v = ['A', 'E', 'I', 'O', 'U']\n ans = ''\n res = ''\n if s[0] in v:\n return s\n for i in range(len(s)):\n if s[i] not in v:\n res += s[i]\n elif s[i] in v:\n ans += s[i:]\n break\n ans += res\n ans += 'AY'\n return ans", "def englishwords(S):\n v = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n l = list(S)\n k = ''\n p = []\n for i in range(len(l)):\n if l[i] not in v:\n k += l[i]\n else:\n p = l[i:]\n break\n if len(p) == len(l):\n return S\n p.append(k)\n p.append('AY')\n return ''.join(p)", "def englishwords(S):\n l = list(S)\n s = ''\n if l[0] in ['A', 'E', 'I', 'O', 'U']:\n return S\n else:\n for i in range(len(l)):\n if l[i] in ['A', 'E', 'I', 'O', 'U']:\n s += s.join(l[i:]) + s.join(l[:i]) + 'AY'\n break\n return s", "def englishwords(s):\n c = 0\n for i in range(len(s)):\n if s[i] not in 'AEIOU':\n c += 1\n else:\n break\n if c == 0:\n return s\n else:\n a = s[:c]\n b = s[c:]\n return b + a + 'AY'", "def englishwords(S):\n n = len(S)\n m = {'A', 'E', 'I', 'O', 'U'}\n if S[0] in m:\n return S\n for i in range(n):\n if S[i] in m:\n return S[i:] + S[:i] + 'AY'\n return ''", "def englishwords(S):\n z = ['A', 'E', 'I', 'O', 'U']\n l = ''\n m = ''\n for i in S:\n if i not in z:\n l += i\n else:\n k = S.index(i)\n m = S[k:]\n break\n m += l\n if m == S:\n return S\n return m + 'AY'", "def englishwords(S):\n v = ['A', 'E', 'I', 'O', 'U']\n a = ''\n b = ''\n for i in S:\n if i not in v:\n a += i\n else:\n l = S.index(i)\n t = S[l:]\n break\n t += a\n if t == S:\n return S\n return t + 'AY'", "def englishwords(S):\n vowel = ('A', 'E', 'I', 'O', 'U')\n if S.startswith(vowel):\n return S\n else:\n for (index, i) in enumerate(S):\n if i in vowel:\n return S[index:] + S[:index] + 'AY'", "def englishwords(S):\n newstr = ''\n oldstr = ''\n if S[0] == 'A' or S[0] == 'E' or S[0] == 'I' or (S[0] == 'O') or (S[0] == 'U'):\n return S\n else:\n for i in range(len(S)):\n if S[i] == 'A' or S[i] == 'E' or S[i] == 'I' or (S[i] == 'O') or (S[i] == 'U'):\n newstr += S[i:]\n oldstr += S[:i]\n break\n return newstr + oldstr + 'AY'", "def englishwords(S):\n if S[0] == 'A' or S[0] == 'E' or S[0] == 'I' or (S[0] == 'O') or (S[0] == 'U'):\n return S\n ans = ''\n for i in range(len(S)):\n if S[i] == 'A' or S[i] == 'E' or S[i] == 'I' or (S[i] == 'O') or (S[i] == 'U'):\n for j in range(i, len(S)):\n ans += S[j]\n for a in range(i):\n ans += S[a]\n break\n return ans + 'AY'", "def englishwords(S):\n index = -1\n for i in range(len(S)):\n if S[i] in ['A', 'E', 'I', 'O', 'U']:\n index = i\n break\n if index == 0:\n return S\n if index == -1:\n return S + 'AY'\n return S[index:] + S[0:index] + 'AY'"], "starter_code": "def englishwords(S):\n", "input_output": {"inputs": ["S = \"GEEK\"", "S = \"ALL\""], "outputs": ["EEKGAY", "ALL"]}, "difficulty": "EASY", "raw_tags": ["logical-thinking", "Misc"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/english-words4137/1", "Expected Auxiliary Space": "O(|S|)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "englishwords", "task_id": "TACO_lite/98", "example": [[], []]} +{"requirement": "Given an unsorted array Arr of size N of positive integers. One number 'A' from set {1, 2,....,N} is missing and one number 'B' occurs twice in array. Find these two numbers.\nExample 1:\nInput:\nN = 2\nArr[] = {2, 2}\nOutput: 2 1\nExplanation: Repeating number is 2 and \nsmallest positive missing number is 1.\nExample 2:\nInput:\nN = 3\nArr[] = {1, 3, 3}\nOutput: 3 2\nExplanation: Repeating number is 3 and \nsmallest positive missing number is 2.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function findTwoElement() which takes the array of integers arr and n as parameters and returns an array of integers of size 2 denoting the answer ( The first index contains B and second index contains A.)\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n2 ≤ N ≤ 10^{5}\n1 ≤ Arr[i] ≤ N", "solutions": ["def findtwoelement(arr, n):\n unordered_map = {}\n rep = 0\n miss = 0\n for i in arr:\n if i not in unordered_map:\n unordered_map[i] = 1\n else:\n rep = i\n for i in range(1, n + 1):\n if i not in unordered_map:\n miss = i\n return [rep, miss]", "def findtwoelement(arr, n):\n sei = [False] * n\n for i in arr:\n if sei[i - 1]:\n repeated = i\n else:\n sei[i - 1] = True\n for i in range(n):\n if not sei[i]:\n return [repeated, i + 1]", "def findtwoelement(arr, n):\n d = {}\n b = 0\n for i in arr:\n try:\n d[i] += 1\n r = i\n except:\n d[i] = 1\n f = False\n for i in range(1, max(arr)):\n if i not in d:\n l = i\n f = True\n break\n if f == False:\n return (r, max(arr) + 1)\n return (r, l)", "def findtwoelement(arr, n):\n a = list(range(1, len(arr) + 1))\n res = sum(a)\n tot = sum(arr)\n arr = set(arr)\n sum_arr = sum(arr)\n missing = res - sum_arr\n repeated = tot - sum_arr\n return (repeated, missing)", "def findtwoelement(arr, n):\n l = []\n s1 = sum(arr)\n k = set(arr)\n k = list(k)\n s2 = sum(k)\n l.append(s1 - s2)\n s3 = n * (n + 1) // 2\n l.append(s3 - s2)\n return l", "from collections import Counter\n\ndef findtwoelement(arr, n):\n a = set(range(1, n + 1))\n missing = list(a - set(arr))[0]\n dic = {}\n for i in arr:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n if dic[i] > 1:\n return [i, missing]", "def findtwoelement(arr, n):\n m = max(arr)\n b = [i for i in range(1, n + 1)]\n s = list(set(b) - set(arr))\n dic = {}\n for i in arr:\n if i in dic:\n s.insert(0, i)\n return s\n else:\n dic[i] = 1", "def findtwoelement(arr, n):\n A = set(range(1, n + 1))\n missing = list(A - set(arr))[0]\n dic = {}\n for i in arr:\n if i not in dic:\n dic[i] = 0\n dic[i] += 1\n if dic[i] >= 2:\n return [i, missing]", "def findtwoelement(arr, n):\n (a, b) = (0, 0)\n for i in range(n):\n if arr[abs(arr[i]) - 1] < 0:\n a = abs(arr[i])\n else:\n arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]\n for i in range(n):\n if arr[i] > 0:\n b = i + 1\n break\n return (a, b)", "def findtwoelement(arr, n):\n arr.sort()\n missing = None\n r = None\n for i in range(n - 1):\n if arr[i] == arr[i + 1]:\n r = arr[i]\n arr.remove(r)\n break\n for i in range(1, n):\n if i != arr[i - 1]:\n missing = i\n break\n if not missing:\n missing = arr[n - 2] + 1\n return [r, missing]", "def findtwoelement(arr, n):\n temp = [0] * (n + 1)\n ans = []\n for i in range(n):\n temp[arr[i]] += 1\n for i in range(1, n + 1):\n if temp[i] > 1:\n ans.insert(0, i)\n if temp[i] == 0:\n ans.insert(1, i)\n return ans", "def findtwoelement(arr, size):\n for i in arr:\n if arr[abs(i) - 1] > 0:\n arr[abs(i) - 1] = -arr[abs(i) - 1]\n else:\n rep = abs(i)\n for i in range(len(arr)):\n if arr[i] > 0:\n nonRep = i + 1\n return (rep, nonRep)", "def findtwoelement(arr, n):\n dict = {}\n for i in arr:\n if i not in dict:\n dict[i] = 1\n else:\n a = i\n dict[i] += 1\n break\n s = sum(arr) - a\n s1 = n * (n + 1) // 2 - s\n return [a, s1]", "def findtwoelement(arr, n):\n total_sum = n * (n + 1) // 2\n s1 = sum(set(arr))\n s2 = sum(arr)\n s = s2 - s1\n k = total_sum - s1\n return (s, k)", "def findtwoelement(arr, n):\n missing = -1\n repeat = -1\n mp = [0] * (n + 1)\n for i in range(n):\n mp[arr[i]] += 1\n for i in range(n + 1):\n if mp[i] == 2:\n repeat = i\n elif mp[i] == 0:\n missing = i\n return [repeat, missing]", "def findtwoelement(arr, n):\n repeat = -1\n missing = -1\n for i in range(n):\n if arr[abs(arr[i]) - 1] > 0:\n arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]\n else:\n repeat = abs(arr[i])\n for i in range(n):\n if arr[i] > 0:\n missing = i + 1\n return [repeat, missing]", "def findtwoelement(arr, n):\n val_hash = {}\n answer = []\n actual_sum = int(n * (n + 1) / 2)\n sum = 0\n for val in arr:\n if val_hash.get(val, 0) != 1:\n sum += val\n val_hash[val] = 1\n else:\n answer.append(val)\n answer.append(actual_sum - sum)\n return answer", "def findtwoelement(arr, n):\n t = n * (n + 1) // 2\n s1 = sum(set(arr))\n s2 = sum(arr)\n k = s2 - s1\n p = t - s1\n return (k, p)", "def findtwoelement(arr, n):\n\n def repeatNumber(arr):\n mp = {}\n for element in arr:\n if element not in mp:\n mp[element] = element\n else:\n return element\n sm = sum(arr)\n oneToN = [i for i in range(1, n + 1)]\n smOneToN = sum(oneToN)\n eq = sm - smOneToN\n rptNumber = repeatNumber(arr)\n msgNumber = rptNumber - eq\n return [rptNumber, msgNumber]", "def findtwoelement(arr, n):\n s = n * (n + 1) // 2\n s2 = n * (n + 1) * (2 * n + 1) // 6\n asum = 0\n a2sum = 0\n for ele in arr:\n asum += ele\n a2sum += ele * ele\n val1 = asum - s\n val2 = a2sum - s2\n val2 = val2 // val1\n x = (val1 + val2) // 2\n y = x - val1\n return [x, y]", "def findtwoelement(arr, n):\n ans = [0] * 2\n for i in range(n):\n if arr[abs(arr[i]) - 1] > 0:\n arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]\n else:\n ans[0] = abs(arr[i])\n for i in range(n):\n if arr[i] > 0:\n ans[1] = i + 1\n return ans", "def findtwoelement(arr, n):\n for i in range(n):\n arr[arr[i] % n - 1] += n\n missing = -1\n repated = -1\n for i in range(n):\n if arr[i] <= n:\n missing = i + 1\n if arr[i] > 2 * n:\n repated = i + 1\n return [repated, missing]", "def findtwoelement(arr, n):\n missing = 0\n dup = 0\n local_dict = dict.fromkeys(arr, 0)\n for item in arr:\n local_dict[item] += 1\n for number in range(1, n + 1):\n if not local_dict.get(number):\n missing = number\n elif local_dict[number] == 2:\n dup = number\n return [dup, missing]", "from collections import Counter\n\ndef findtwoelement(arr, n):\n A = Counter(arr)\n B = 0\n for (i, j) in A.items():\n if j > 1:\n B = i\n A = sum(arr) - B\n total = n * (n + 1) // 2\n A = total - A\n return (B, A)", "def findtwoelement(arr, n):\n sumn = n * (n + 1) / 2\n sumsn = n * (n + 1) * (2 * n + 1) / 6\n sumi = sum(arr)\n sums = 0\n for i in range(n):\n sums += arr[i] * arr[i]\n val1 = sumi - sumn\n val2 = sums - sumsn\n val2 = val2 / val1\n x = (val1 + val2) / 2\n y = x - val1\n return (int(x), int(y))", "def findtwoelement(arr, n):\n h = [0] * (n + 1)\n for i in range(n):\n h[arr[i]] += 1\n mi = -1\n twi = -1\n for i in range(1, n + 1):\n if h[i] == 2:\n twi = i\n elif h[i] == 0:\n mi = i\n if mi != -1 and twi != -1:\n break\n return (twi, mi)", "def findtwoelement(arr, n):\n from collections import defaultdict\n ans = []\n m = defaultdict(int)\n for i in range(1, n + 1):\n m[i] = 0\n for i in arr:\n m[i] += 1\n for (k, v) in m.items():\n if v == 2:\n ans.append(k)\n for (k, v) in m.items():\n if v == 0:\n ans.append(k)\n return ans", "import math\n\ndef findtwoelement(arr, n):\n sumArr = sum(arr)\n repeatingEle = 0\n for i in range(n):\n ele = abs(arr[i])\n if arr[ele - 1] > 0:\n arr[ele - 1] = -1 * arr[ele - 1]\n else:\n repeatingEle = ele\n break\n sumN = n * (n + 1) // 2\n missingEle = sumN - sumArr + repeatingEle\n return (repeatingEle, missingEle)", "def findtwoelement(arr, n):\n A = set(range(1, n + 1))\n mis = list(A - set(arr))[0]\n dic = {}\n for i in arr:\n if i not in dic:\n dic[i] = 0\n dic[i] += 1\n for (key, val) in dic.items():\n if val == 2:\n return [key, mis]", "def findtwoelement(arr, n):\n s = n * (n + 1) // 2\n p = n * (n + 1) * (2 * n + 1) // 6\n missing = 0\n repeating = 0\n ans = []\n for i in arr:\n s -= i\n p -= i * i\n missing = (s + p // s) // 2\n repeating = missing - s\n ans.append(repeating)\n ans.append(missing)\n return ans", "def findtwoelement(arr, n):\n x = []\n arr.sort()\n c = arr[0]\n for i in range(1, n):\n c += arr[i]\n if arr[i] == arr[i - 1]:\n x.append(arr[i])\n c = c - x[0]\n sum = n * (n + 1) // 2\n x.append(sum - c)\n return x", "def findtwoelement(arr, n):\n arr_set = set()\n repeated_num = 0\n missing_num = 0\n for num in arr:\n if num not in arr_set:\n arr_set.add(num)\n else:\n repeated_num = num\n for i in range(1, n + 1):\n if i not in arr_set:\n missing_num = i\n break\n result = (repeated_num, missing_num)\n return result", "def findtwoelement(arr, n):\n ans = [0, 0]\n l = [i for i in range(1, n + 1)]\n ans[1] = sum(l) - sum(set(arr))\n ans[0] = sum(arr) + ans[1] - sum(l)\n return ans", "def findtwoelement(arr, n):\n (missing, repeating) = (None, None)\n for i in range(len(arr)):\n if arr[abs(arr[i]) - 1] < 0:\n repeating = abs(arr[i])\n else:\n arr[abs(arr[i]) - 1] *= -1\n for i in range(len(arr)):\n if arr[i] > 0:\n missing = i + 1\n return [repeating, missing]", "def findtwoelement(arr, n):\n counter = {}\n for num in arr:\n if num in counter:\n a = num\n else:\n counter[num] = 1\n b = [0] * n\n for num in arr:\n b[num - 1] = 1\n x = []\n for i in range(n):\n if b[i] == 0:\n x.append(i + 1)\n x.append(a)\n return (a, x[0])", "def findtwoelement(arr, n):\n freq = [0] * (n + 1)\n missing_num = 0\n repeated_num = 0\n for i in range(n):\n freq[arr[i]] += 1\n for i in range(1, n + 1):\n if freq[i] == 0:\n missing_num = i\n elif freq[i] == 2:\n repeated_num = i\n return (repeated_num, missing_num)", "def findtwoelement(arr, n):\n freq = [0] * n\n for i in range(n):\n freq[arr[i] - 1] += 1\n return (freq.index(2) + 1, freq.index(0) + 1)", "def findtwoelement(arr, n):\n ans = [0] * n\n r = [-1, -1]\n for i in range(len(arr)):\n ans[arr[i] - 1] += 1\n for i in range(len(ans)):\n if ans[i] == 0:\n r[1] = i + 1\n if ans[i] == 2:\n r[0] = i + 1\n return r", "def findtwoelement(arr, n):\n SN = n * (n + 1) // 2\n S2N = n * (n + 1) * (2 * n + 1) // 6\n (missingNum, repeatingNum) = (0, 0)\n for i in range(n):\n SN -= arr[i]\n S2N -= arr[i] * arr[i]\n missingNum = (SN + S2N // SN) // 2\n repeatingNum = missingNum - SN\n ans = []\n ans.append(repeatingNum)\n ans.append(missingNum)\n return ans", "def findtwoelement(arr, n):\n n = len(arr)\n seen = set()\n repeating_num = missing_num = None\n for num in arr:\n if num in seen:\n repeating_num = num\n seen.add(num)\n for i in range(1, n + 1):\n if i not in seen:\n missing_num = i\n break\n return (repeating_num, missing_num)", "def findtwoelement(arr, n):\n l = [0 for i in range(len(arr))]\n for i in arr:\n l[i - 1] += 1\n return [l.index(2) + 1, l.index(0) + 1]", "from collections import *\n\ndef findtwoelement(arr, n):\n A = set(range(1, n + 1))\n B = set(arr)\n missing = list(A - B)[0]\n dic = Counter(arr)\n twice = 0\n for (key, val) in dic.items():\n if val == 2:\n twice = key\n break\n return [twice, missing]", "def findtwoelement(a, n):\n n = len(a)\n SN = n * (n + 1) // 2\n S2N = n * (n + 1) * (2 * n + 1) // 6\n (S, S2) = (0, 0)\n for i in range(n):\n S += a[i]\n S2 += a[i] * a[i]\n val1 = S - SN\n val2 = S2 - S2N\n val2 = val2 // val1\n x = (val1 + val2) // 2\n y = x - val1\n return [x, y]", "def findtwoelement(arr, n):\n d = {}\n ans = []\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n ans.append(i)\n k = range(1, n + 1)\n k = set(k).difference(set(arr))\n for i in k:\n ans.append(i)\n return ans", "def findtwoelement(A, n):\n (x, y) = (None, None)\n n = len(A)\n a = n * (n + 1) // 2\n a_dashed = sum(A)\n b = n * (n + 1) * (2 * n + 1) // 6\n b_dashed = 0\n for i in A:\n b_dashed += i * i\n rel1 = a - a_dashed\n rel2 = b - b_dashed\n rel3 = rel2 // rel1\n y = (rel3 + rel1) // 2\n x = y - rel1\n return [x, y]", "def findtwoelement(arr, n):\n sumofn = n * (n + 1) // 2\n sumsetarr = sum(set(arr))\n sumarr = sum(arr)\n missingnumber = sumofn - sumsetarr\n repeatednumber = sumarr - sumsetarr\n return [repeatednumber, missingnumber]", "def get_duplicate(arr, n):\n for i in range(n):\n idx = abs(arr[i]) - 1\n if arr[idx] < 0:\n return idx + 1\n arr[idx] = -arr[idx]\n return -1\n\ndef get_missing(arr, n):\n for i in range(n):\n idx = abs(arr[i]) - 1\n if arr[idx] > 0:\n arr[idx] = -arr[idx]\n for i in range(n):\n if arr[i] > 0:\n return i + 1\n\ndef findtwoelement(arr, n):\n duplicate = self.get_duplicate(arr, n)\n missing = self.get_missing(arr, n)\n return (duplicate, missing)", "def findtwoelement(arr, n):\n v = n * (n + 1) // 2\n g = sum(arr)\n j = set(arr)\n rep_element = g - sum(j)\n missing_element = v - sum(j)\n return (rep_element, missing_element)", "def findtwoelement(arr, n):\n (d, l, repeated_elem) = ({}, list(range(1, n + 1)), -1)\n for elem in arr:\n d.update({elem: d.get(elem, 0) + 1})\n if d[elem] == 2:\n repeated_elem = elem\n if repeated_elem == -1:\n return [0, 0]\n for elem in l:\n if elem not in d:\n return [repeated_elem, elem]", "def findtwoelement(arr, n):\n repeatingElement = 0\n missingElement = 0\n for i in range(len(arr)):\n if arr[abs(arr[i]) - 1] > 0:\n arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]\n else:\n repeatingElement = abs(arr[i])\n incrCount = 0\n decrCount = 0\n for i in range(len(arr)):\n if arr[i] > 0:\n missingElement = i + 1\n return [repeatingElement, missingElement]", "def findtwoelement(arr, n):\n xor = 0\n for i in range(n):\n xor = xor ^ arr[i]\n xor = xor ^ i + 1\n while xor & xor - 1 != 0:\n xor = xor & xor - 1\n a = 0\n b = 0\n for i in range(n):\n if arr[i] & xor:\n a = a ^ arr[i]\n else:\n b = b ^ arr[i]\n if i + 1 & xor:\n a = a ^ i + 1\n else:\n b = b ^ i + 1\n if a in arr:\n return [a, b]\n return [b, a]", "from collections import Counter\n\ndef findtwoelement(arr, n):\n A = Counter(arr)\n (re, mi) = (-1, -1)\n for i in range(1, n + 1):\n if A[i] == 1:\n pass\n elif A[i] == 2:\n re = i\n else:\n mi = i\n return [re, mi]", "def findtwoelement(arr, n):\n arr.sort()\n repeat = 0\n for i in range(n - 1):\n if arr[i] == arr[i + 1]:\n repeat = arr[i]\n arr2 = set([i for i in range(1, n + 1)])\n arr = set(arr)\n missing = arr2.difference(arr)\n miss = 0\n for i in missing:\n miss = i\n return (repeat, miss)", "def findtwoelement(arr, n):\n obj = {}\n lst = [0 for x in range(0, n + 2)]\n repeating_num = None\n missing_num = None\n for i in arr:\n if repeating_num is None:\n try:\n obj[i] = obj[i] + i\n repeating_num = i\n except:\n obj[i] = i\n try:\n lst[i] = i\n except:\n pass\n missing_num = lst[1:].index(0) + 1\n return (repeating_num, missing_num)", "def findtwoelement(arr, n):\n s_arr = sum(arr)\n s_arr_ele_sq = sum([ele ** 2 for ele in arr])\n s_n_natural_no = n * (n + 1) // 2\n s_sq_n_natural_no = n * (n + 1) * (2 * n + 1) // 6\n x_minus_y = s_n_natural_no - s_arr\n x_sq_minus_y_sq = s_sq_n_natural_no - s_arr_ele_sq\n x_plus_y = x_sq_minus_y_sq // x_minus_y\n x = (x_plus_y + x_minus_y) // 2\n y = (x_plus_y - x_minus_y) // 2\n return [y, x]", "def findtwoelement(arr, n):\n map = {}\n for i in range(n):\n if arr[i] not in map:\n map[arr[i]] = True\n else:\n x = arr[i]\n for i in range(1, n + 1):\n if i not in map:\n l = i\n return [x, l]", "def findtwoelement(arr, n):\n a = {}\n c = 0\n d = 0\n for i in arr:\n if i in a:\n a[i] += 1\n else:\n a[i] = 1\n count = 1\n while count < len(arr) + 1:\n if count in a:\n if a[count] == 2:\n c = count\n if count not in a:\n d = count\n count += 1\n return (c, d)", "def findtwoelement(arr, n):\n result = []\n dict = {}\n for i in arr:\n if i in dict:\n result.append(i)\n else:\n dict[i] = 1\n res = n * (n + 1) // 2 - sum(set(arr))\n result.append(res)\n return result", "def findtwoelement(arr, n):\n a = [0] * (n + 1)\n res = 0\n mis = 0\n for idx in range(n):\n a[arr[idx]] += 1\n for idx in range(1, len(a)):\n if a[idx] == 0:\n mis = idx\n if a[idx] > 1:\n res = idx\n return (res, mis)", "def findtwoelement(nums, n):\n for i in range(len(nums)):\n while nums[i] > 0 and nums[i] <= n and (nums[nums[i] - 1] != nums[i]):\n (nums[nums[i] - 1], nums[i]) = (nums[i], nums[nums[i] - 1])\n for i in range(n):\n if arr[i] != i + 1:\n return [arr[i], i + 1]", "def findtwoelement(arr, n):\n l = []\n a = [0] * n\n for i in arr:\n if a[i - 1] > 0:\n l.append(i)\n a[i - 1] += 1\n for i in range(n):\n if a[i] == 0:\n l.append(i + 1)\n return l", "def findtwoelement(arr, n):\n sum1 = sum(arr)\n sum2 = n * (n + 1) // 2\n z1 = sum1 - sum2\n sum3 = 0\n for i in arr:\n sum3 += i * i\n sum4 = 0\n for j in range(1, n + 1):\n sum4 = sum4 + j * j\n z2 = (sum3 - sum4) // z1\n r = (z1 + z2) // 2\n m = r - z1\n return [r, m]", "def findtwoelement(arr, n):\n arr.sort()\n l = [0, 0]\n miss = 1\n for i in range(0, len(arr)):\n if arr[i] == miss:\n miss += 1\n l[1] = miss\n for i in range(1, n):\n if arr[i - 1] == arr[i]:\n l[0] = arr[i]\n break\n return l", "def findtwoelement(arr, n):\n RmM = sum(arr) - n * (n + 1) // 2\n R2mM2 = sum([x * x for x in arr]) - n * (n + 1) * (2 * n + 1) // 6\n RpM = R2mM2 // RmM\n return [(RpM + RmM) // 2, (RpM - RmM) // 2]", "def findtwoelement(arr, n):\n mpp = {}\n li = []\n for i in arr:\n if i not in mpp:\n mpp[i] = 0\n else:\n mpp[i] += 1\n for i in range(1, n + 1):\n try:\n mpp[i] += 1\n except:\n mpp[i] = 0\n for i in mpp:\n if mpp[i] > 1:\n li.append(i)\n break\n for i in mpp:\n if mpp[i] == 0:\n li.append(i)\n break\n return li", "def findtwoelement1(nums, n):\n lookup = [0] * (n + 1)\n for num in nums:\n lookup[num] += 1\n result = [None, None]\n for num in range(1, n + 1):\n if lookup[num] == 0:\n result[1] = num\n elif lookup[num] > 1:\n result[0] = num\n return result\n\ndef findtwoelement(nums, n):\n sumRepeating = 0\n sumMissing = n * (n + 1) // 2\n sumSquareRepeating = 0\n sumSquareMissing = n * (n + 1) * (2 * n + 1) // 6\n for num in nums:\n sumRepeating += num\n sumSquareRepeating += num * num\n val1 = sumRepeating - sumMissing\n val2 = sumSquareRepeating - sumSquareMissing\n val2 = val2 // val1\n x = (val1 + val2) // 2\n y = x - val1\n return [x, y]", "def findtwoelement(nums, n):\n sumRepeating = 0\n sumMissing = n * (n + 1) // 2\n sumSquareRepeating = 0\n sumSquareMissing = n * (n + 1) * (2 * n + 1) // 6\n for num in nums:\n sumRepeating += num\n sumSquareRepeating += num * num\n val1 = sumRepeating - sumMissing\n val2 = sumSquareRepeating - sumSquareMissing\n val2 = val2 // val1\n x = (val1 + val2) // 2\n y = x - val1\n return [x, y]", "def findtwoelement(nums, n):\n lookup = [0] * (n + 1)\n for num in nums:\n lookup[num] += 1\n result = [None, None]\n for num in range(1, n + 1):\n if lookup[num] == 0:\n result[1] = num\n elif lookup[num] > 1:\n result[0] = num\n return result", "def findtwoelement(arr, n):\n repeating_element = -1\n missing_element = -1\n for i in range(n):\n index = abs(arr[i]) - 1\n if arr[index] < 0:\n repeating_element = abs(arr[i])\n else:\n arr[index] = -arr[index]\n for i in range(n):\n if arr[i] > 0:\n missing_element = i + 1\n break\n return [repeating_element, missing_element]", "def findtwoelement(arr, n):\n d = {}\n l = []\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n l.append(i)\n for i in range(1, n + 1):\n if i not in d:\n l.append(i)\n return l", "def findtwoelement(arr, n):\n h = set()\n dict1 = {}\n lst = []\n for i in range(1, n + 1):\n h.add(i)\n for i in arr:\n if i in dict1:\n dict1[i] = dict1[i] + 1\n else:\n dict1[i] = 1\n if dict1[i] == 2:\n lst.append(i)\n for i in h:\n if i not in dict1:\n lst.append(i)\n return lst", "import math\n\ndef findtwoelement(arr, n):\n sr = 0\n srr = 0\n su = 0\n sur = 0\n for i in range(n):\n sr += (i + 1) ** 2\n srr += arr[i] ** 2\n su += i + 1\n sur += arr[i]\n s1 = sr - srr\n m_r = su - sur\n m = round((s1 + m_r ** 2) / (2 * m_r))\n r = m - m_r\n return [r, m]", "def findtwoelement(arr, n):\n l = []\n arr.sort()\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] = d[i] + 1\n for (key, value) in d.items():\n if d[key] == 2:\n l.append(key)\n s = 0\n s1 = 0\n for i in range(1, n + 1):\n s = s + i\n for i in range(n):\n s1 = s1 + arr[i]\n diff = s - (s1 - l[0])\n l.append(diff)\n return l", "def findtwoelement(arr, n):\n ans = [0, 0]\n x = n * (n + 1) // 2\n x2 = n * (n + 1) * (2 * n + 1) // 6\n y = 0\n y2 = 0\n for i in arr:\n y += i\n y2 += i ** 2\n e1 = x - y\n e2 = (x2 - y2) // e1\n ans[1] = (e1 + e2) // 2\n ans[0] = (e2 - e1) // 2\n return ans", "def findtwoelement(arr, n):\n missing = 0\n duplicate = 0\n seen = set()\n for i in range(n):\n if arr[i] in seen:\n duplicate = arr[i]\n break\n seen.add(arr[i])\n arr_sum = 0\n for i in range(n):\n arr_sum += arr[i]\n arr_sum -= duplicate\n missing = n * (n + 1) // 2 - arr_sum\n return [duplicate, missing]", "def findtwoelement(arr, n):\n d = {}\n for i in range(n):\n d[i + 1] = 0\n for ele in arr:\n d[ele] += 1\n return (max(d, key=d.get), min(d, key=d.get))\n while i < n:\n if arr[i] != arr[arr[i] - 1]:\n temp = arr[i]\n arr[i] = arr[arr[i] - 1]\n arr[arr[i] - 1] = temp\n else:\n i += 1\n for i in range(n):\n if arr[i] != arr[arr[i] - 1]:\n return (arr[i], i + 1)", "def findtwoelement(arr, n):\n res = []\n for i in range(n):\n if arr[abs(arr[i]) - 1] > 0:\n arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]\n else:\n res.append(abs(arr[i]))\n for i in range(n):\n if arr[i] > 0:\n res.append(i + 1)\n return res", "def findtwoelement(arr, n):\n d = {}\n for i in range(n):\n d[i + 1] = 0\n for ele in arr:\n d[ele] += 1\n return (max(d, key=d.get), min(d, key=d.get))", "def findtwoelement(arr, n):\n res = []\n for i in range(0, n):\n while arr[i] - 1 != i:\n j = arr[i] - 1\n (arr[i], arr[j]) = (arr[j], arr[i])\n if arr[i] == arr[j]:\n break\n for i in range(0, n):\n if arr[i] - 1 != i:\n res.append(arr[i])\n res.append(i + 1)\n return res", "def findtwoelement(arr, n):\n Nsum = n * (n + 1) / 2\n realSum = sum(arr)\n den = Nsum - realSum\n sqSum = 0\n for i in arr:\n sqSum += i * i\n realSq = n * (n + 1) * (2 * n + 1) / 6\n num = realSq - sqSum\n s = num / den\n missing = (s + den) / 2\n repeat = s - missing\n return [int(repeat), int(missing)]", "def findtwoelement(arr, n):\n a_b = n * (n + 1) // 2 - sum(arr)\n a2_b2 = n * (n + 1) * (2 * n + 1) // 6 - sum([x ** 2 for x in arr])\n a = (a2_b2 + a_b ** 2) // (2 * a_b)\n return [a - a_b, a]", "from collections import Counter\n\ndef findtwoelement(arr, n):\n hm = Counter(arr)\n a = [0] * 2\n for i in range(1, n + 1):\n if i not in hm:\n a[1] = i\n if hm[i] > 1:\n a[0] = i\n return a", "def findtwoelement(arr, n):\n arr.sort()\n A = []\n for i in range(len(arr) - 1):\n if arr[i] == arr[i + 1]:\n A.append(arr[i])\n break\n a = set(arr)\n arr = list(a)\n N = n * (n + 1) // 2\n sum1 = 0\n for i in range(len(arr)):\n sum1 += arr[i]\n A.append(N - sum1)\n return A", "def findtwoelement(arr, n):\n N = n\n sum_N = n * (n + 1) // 2\n sum_N_squares = n * (n + 1) * (2 * n + 1) // 6\n sum_arr = sum(arr)\n sum_arr_squares = sum((x ** 2 for x in arr))\n diff_sum = sum_N - sum_arr\n diff_sum_squares = sum_N_squares - sum_arr_squares\n repeating = (diff_sum_squares // diff_sum - diff_sum) // 2\n missing = diff_sum + repeating\n return [repeating, missing]", "def findtwoelement(arr, n):\n a = []\n b = [0, 0]\n for i in range(1, n + 1):\n a.append(i)\n b[1] = sum(a) - sum(set(arr))\n b[0] = sum(arr) + b[1] - sum(a)\n return b", "def findtwoelement(arr, n):\n freq = [0] * (10 ** 5 + 1)\n for num in arr:\n freq[num] += 1\n result = [0] * 2\n for i in range(1, n + 1):\n if freq[i] == 0:\n result[1] = i\n if freq[i] == 2:\n result[0] = i\n return result"], "starter_code": "def findtwoelement( self,arr, n):\n", "input_output": {"inputs": ["N = 2\r\nArr[] = {2, 2}", "N = 3\r\nArr[] = {1, 3, 3}"], "outputs": ["2 1", "3 2"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/find-missing-and-repeating2512/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "findtwoelement", "task_id": "TACO_lite/21", "example": [[[2, [2, 2]], [3, [1, 3, 3]]], ["(2, 1)", "(3, 2)"]]} +{"requirement": "Given a Binary Tree, print the diagonal traversal of the binary tree.\nConsider lines of slope -1 passing between nodes. Given a Binary Tree, print all diagonal elements in a binary tree belonging to same line.\nIf the diagonal element are present in two different subtress then left subtree diagonal element should be taken first and then right subtree. \nExample 1:\nInput :\n 8\n / \\\n 3 10\n / \\ \\\n 1 6 14\n / \\ /\n 4 7 13\nOutput : 8 10 14 3 6 7 13 1 4\nExplanation:\nDiagonal Traversal of binary tree : \n 8 10 14 3 6 7 13 1 4\nYour Task:\nYou don't need to read input or print anything. The task is to complete the function diagonal() that takes the root node as input argumets and returns the diagonal traversal of the given tree.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\nHere N is number of nodes.\nConstraints:\n1 <= Number of nodes<= 10^{5}\n1 <= Data of a node<= 10^{5}", "solutions": ["def diagonal(root):\n if root is None:\n return\n out = []\n node = root\n left_q = deque()\n while node:\n out.append(node.data)\n if node.left:\n left_q.appendleft(node.left)\n if node.right:\n node = node.right\n elif len(left_q) >= 1:\n node = left_q.pop()\n else:\n node = None\n return out", "def diagonal(root):\n q = []\n ans = []\n q.append(root)\n while q:\n a = q.pop(0)\n ans.append(a.data)\n if a.left:\n q.append(a.left)\n while a.right:\n ans.append(a.right.data)\n if a.right.left:\n q.append(a.right.left)\n a = a.right\n return ans", "from collections import defaultdict\n\ndef diagonal(root):\n ans = []\n d = defaultdict(list)\n\n def solve(root, l):\n if root.left == None and root.right == None:\n d[l].append(root.data)\n return\n if root.left:\n solve(root.left, l - 1)\n d[l].append(root.data)\n if root.right:\n solve(root.right, l)\n if root == None:\n return []\n solve(root, 0)\n l = []\n for i in d.keys():\n l.append(i)\n l.sort(reverse=-1)\n for i in l:\n ans.extend(d[i])\n return ans", "from collections import deque\n\ndef diagonal(root):\n q = deque()\n q.append(root)\n ans = []\n while q:\n x = q.popleft()\n while x is not None:\n if x.left:\n q.append(x.left)\n ans.append(x.data)\n x = x.right\n return ans", "def diagonal(root):\n vis = []\n n = root\n q = deque()\n while n:\n vis.append(n.data)\n if n.left:\n q.appendleft(n.left)\n if n.right:\n n = n.right\n elif len(q) >= 1:\n n = q.pop()\n else:\n n = None\n return vis", "def diagonal(root):\n res = []\n q = []\n q.append(root)\n\n def traverse(node):\n if node != None:\n res.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n traverse(node.right)\n while q != []:\n x = q.pop(0)\n traverse(x)\n return res", "from collections import defaultdict\n\ndef diagonal(root):\n d = defaultdict(list)\n\n def sol(root, i):\n if root.left == None and root.right == None:\n d[i].append(root.data)\n return\n d[i].append(root.data)\n if root.left:\n left = sol(root.left, i - 1)\n if root.right:\n right = sol(root.right, i)\n sol(root, 0)\n r = []\n for j in sorted(d.keys(), reverse=True):\n r.extend(d[j])\n return r", "def diagonal(root):\n\n def dig(root):\n if root is None:\n return []\n l1 = []\n q = []\n q = [root]\n while q:\n node = q.pop(0)\n while node:\n l1.append(node.data)\n if node.left:\n q.append(node.left)\n node = node.right\n return l1\n return dig(root)", "from collections import defaultdict\n\ndef diagonal(root):\n d = defaultdict(list)\n\n def solve(root, idx):\n if root.left == None and root.right == None:\n d[idx].append(root.data)\n return\n d[idx].append(root.data)\n if root.left:\n left = solve(root.left, idx - 1)\n if root.right:\n right = solve(root.right, idx)\n solve(root, 0)\n res = []\n for i in sorted(d.keys(), reverse=True):\n res.extend(d[i])\n return res", "def diagonal(root):\n d = {}\n\n def traverse(root, tag):\n if root != []:\n if tag in d:\n d[tag].append(root.data)\n else:\n d[tag] = [root.data]\n if root.left:\n traverse(root.left, tag - 1)\n if root.right:\n traverse(root.right, tag)\n traverse(root, 0)\n k = sorted(d.items(), key=lambda x: -x[0])\n ans = []\n for (i, j) in k:\n ans.extend(j)\n return ans", "def diagonal_traversal_helper(node, level, diagonal_map):\n if node is None:\n return\n if level in diagonal_map:\n diagonal_map[level].append(node.data)\n else:\n diagonal_map[level] = [node.data]\n diagonal_traversal_helper(node.left, level + 1, diagonal_map)\n diagonal_traversal_helper(node.right, level, diagonal_map)\n\ndef diagonal(root):\n diagonal_map = {}\n diagonal_traversal_helper(root, 0, diagonal_map)\n result = []\n for level in diagonal_map:\n result.extend(diagonal_map[level])\n return result", "def diagonal(root):\n q = []\n a = []\n if root == None:\n return\n q.append(root)\n while len(q) != 0:\n n = q[0]\n q.pop(0)\n while n:\n if n.left:\n q.append(n.left)\n a.append(n.data)\n n = n.right\n return a", "from collections import defaultdict\n\ndef diagonal(root):\n ans = []\n d = defaultdict(list)\n\n def dfs(x, l):\n d[l].append(x.data)\n if x.left:\n dfs(x.left, l + 1)\n if x.right:\n dfs(x.right, l)\n dfs(root, 0)\n ans = []\n for x in d:\n ans.extend(d[x])\n return ans", "def diagonal(root):\n if root == None:\n return []\n q = [root]\n tmp = []\n ans = []\n while q:\n nod = q.pop(0)\n while nod:\n ans.append(nod.data)\n if nod.left:\n tmp.append(nod.left)\n nod = nod.right\n if len(q) == 0:\n while tmp:\n q.append(tmp.pop(0))\n return ans", "def diagonal(root):\n q = deque()\n q.append(root)\n ans = []\n while len(q) >= 1:\n x = q.popleft()\n while x is not None:\n if x.left is not None:\n q.append(x.left)\n ans.append(x.data)\n x = x.right\n return ans", "def util(root, a):\n global d\n if root == None:\n return\n if d.get(a) == None:\n d[a] = [root.data]\n else:\n d[a].append(root.data)\n self.util(root.left, a - 1)\n self.util(root.right, a)\n\ndef diagonal(root):\n global d\n d = {}\n self.util(root, 0)\n ans = []\n for (k, v) in sorted(d.items(), reverse=True):\n for i in v:\n ans.append(i)\n return ans", "from collections import deque\n\ndef diagonal(root):\n queue = deque()\n ans = []\n queue.append(root)\n if root is None:\n return ans\n while queue:\n temp = queue.popleft()\n while temp:\n if temp.left:\n queue.append(temp.left)\n ans.append(temp.data)\n temp = temp.right\n return ans", "from collections import deque\n\ndef diagonal(root):\n hashmap = {}\n\n def solve(root, index):\n if root is None:\n return\n if index in hashmap:\n hashmap[index].append(root.data)\n else:\n hashmap[index] = [root.data]\n if root.left is not None:\n solve(root.left, index + 1)\n if root.right is not None:\n solve(root.right, index)\n solve(root, 0)\n ans = []\n for i in sorted(hashmap.keys()):\n ans += hashmap[i]\n return ans", "def diagonal(root):\n q = []\n res = []\n q.append(root)\n while len(q) > 0:\n p = q.pop(0)\n res.append(p.data)\n while p:\n if p.right != None:\n res.append(p.right.data)\n if p.left != None:\n q.append(p.left)\n p = p.right\n return res", "from collections import defaultdict\n\ndef diagonal(root):\n ans = []\n queue = [root]\n while queue:\n node = queue.pop(0)\n while node:\n ans.append(node.data)\n if node.left:\n queue.append(node.left)\n if node.right:\n node = node.right\n else:\n break\n return ans", "def diagonal(root):\n if root == None:\n return []\n queue = []\n queue.append(root)\n ans = []\n while queue:\n temp = queue.pop(0)\n while temp:\n ans.append(temp.data)\n if temp.left != None:\n queue.append(temp.left)\n if temp.right:\n temp = temp.right\n else:\n break\n return ans", "def diagonal(root):\n result = list()\n node = root\n left_q = deque()\n while node:\n result.append(node.data)\n if node.left:\n left_q.appendleft(node.left)\n if node.right:\n node = node.right\n else:\n node = left_q.pop() if len(left_q) >= 1 else None\n return result", "from collections import deque\n\ndef diagonal(root):\n res = []\n q = deque()\n q.append(root)\n while len(q):\n p = q.popleft()\n res.append(p.data)\n while p:\n if p.left:\n q.append(p.left)\n if p.right:\n res.append(p.right.data)\n p = p.right\n return res", "from collections import *\n\ndef __init__():\n self.d = {}\n\ndef diagonal(root):\n q = deque()\n q.append([root, 0, 0])\n while q:\n (v, x, y) = q.pop()\n if y - x in self.d:\n self.d[y - x].append(v.data)\n else:\n self.d[y - x] = [v.data]\n if v.right:\n q.append([v.right, x + 1, y + 1])\n if v.left:\n q.append([v.left, x - 1, y + 1])\n answer = []\n for i in sorted(self.d):\n answer.extend(self.d[i])\n return answer", "def diagonal(root):\n\n def diagnolView(root, dict, level):\n if root is None:\n return\n if level not in dict:\n dict[level] = [root.data]\n else:\n dict[level].append(root.data)\n diagnolView(root.left, dict, level + 1)\n diagnolView(root.right, dict, level)\n dict = {}\n diagnolView(root, dict, 0)\n arr = []\n for i in dict:\n arr += dict[i]\n return arr", "def rec_sol(root, d, save_dict):\n try:\n save_dict[d].append(root.data)\n except:\n save_dict[d] = [root.data]\n if root.left != None:\n self.rec_sol(root.left, d + 1, save_dict)\n if root.right != None:\n self.rec_sol(root.right, d, save_dict)\n return\n\ndef diagonal(root):\n save_dict = {}\n self.rec_sol(root, 0, save_dict)\n final = []\n for i in save_dict:\n for el in save_dict[i]:\n final.append(el)\n return final", "def diagonal(root):\n s = []\n ans = []\n s.append(root)\n while len(s) != 0:\n size = len(s)\n while size != 0:\n rn = s.pop(0)\n while rn != None:\n ans.append(rn.data)\n if rn.left != None:\n s.append(rn.left)\n rn = rn.right\n size -= 1\n return ans", "def diagonal(root):\n queue = []\n l = []\n queue.append(root)\n while len(queue) > 0:\n temp = queue.pop(0)\n while temp:\n if temp.left:\n queue.append(temp.left)\n l.append(temp.data)\n temp = temp.right\n return l", "def diagonal(root):\n q = deque([root])\n res = []\n while q:\n temp = q.popleft()\n while temp:\n res.append(temp.data)\n if temp.left:\n q.append(temp.left)\n temp = temp.right\n return res", "def diagonal(root):\n ans = []\n q = deque([])\n q.append(root)\n while q:\n n = len(q)\n for _ in range(len(q)):\n d = q.popleft()\n ans.append(d.data)\n if d.left:\n q.append(d.left)\n while d.right:\n d = d.right\n ans.append(d.data)\n if d.left:\n q.append(d.left)\n return ans", "def diagonal(root):\n\n def helper(root, dic, diagonal):\n if root == None:\n return\n if diagonal in dic:\n dic[diagonal].append(root.data)\n else:\n dic[diagonal] = [root.data]\n helper(root.left, dic, diagonal + 1)\n helper(root.right, dic, diagonal)\n return dic\n if not root:\n return\n dic = {}\n dic = helper(root, dic, 0)\n l = list(dic.keys())\n l.sort()\n res = []\n for k in l:\n res += dic[k]\n return res", "from queue import LifoQueue\nfrom collections import defaultdict\n\ndef pre_order(root, level, diagonals):\n diagonals[level].append(root.data)\n if root.left:\n pre_order(root.left, level + 1, diagonals)\n if root.right:\n pre_order(root.right, level, diagonals)\n\ndef diagonal(root):\n diagonals_map = defaultdict(list)\n output = []\n pre_order(root, 0, diagonals_map)\n for level in diagonals_map:\n output.extend(diagonals_map[level])\n return output", "def diagonal(root):\n if not root:\n return []\n q = [root]\n res = []\n while q:\n curr = q.pop(0)\n while curr:\n res.append(curr.data)\n if curr.left:\n q.append(curr.left)\n curr = curr.right\n return res", "def diagonal(root):\n\n def find(root, dig, dict):\n if root is None:\n return\n if dig not in dict:\n dict[dig] = []\n dict[dig].append(root.data)\n find(root.left, dig + 1, dict)\n find(root.right, dig, dict)\n ans = []\n dict = {}\n find(root, 0, dict)\n for dig in dict:\n for num in dict[dig]:\n ans.append(num)\n return ans", "def diagonal(root):\n if not root:\n return []\n q = deque([root])\n res = []\n while q:\n for i in range(len(q)):\n curr = q.popleft()\n while curr:\n res.append(curr.data)\n if curr.left:\n q.append(curr.left)\n curr = curr.right\n return res", "def diagonal(root):\n if root == None:\n return []\n ans = []\n q = []\n q.append(root)\n while len(q) != 0:\n s = len(q)\n while s != 0:\n curr = q.pop(0)\n while curr != None:\n ans.append(curr.data)\n if curr.left != None:\n q.append(curr.left)\n if curr.right != None:\n curr = curr.right\n else:\n break\n s -= 1\n return ans", "from collections import deque\n\ndef diagonal(root):\n q = deque()\n q.append(root)\n ans = []\n while q:\n curr = q.popleft()\n while curr:\n ans.append(curr.data)\n if curr.left:\n q.append(curr.left)\n curr = curr.right\n return ans", "def diagonal(root):\n l = []\n queue = [root]\n while len(queue) > 0:\n s = len(queue)\n while s > 0:\n node = queue.pop(0)\n while node != None:\n l.append(node.data)\n if node.left:\n queue.append(node.left)\n node = node.right\n s -= 1\n return l", "def diagonal(root):\n ans = []\n Q = [root]\n s = 1\n while Q != []:\n m = 0\n while s:\n a = Q.pop(0)\n while a:\n if a.left:\n Q.append(a.left)\n m += 1\n ans.append(a.data)\n a = a.right\n s -= 1\n s = m\n return ans", "def diagonal(root):\n q = [root]\n ans = []\n while q:\n l = len(q)\n for i in range(l):\n root = q.pop(0)\n temp = root\n while temp:\n ans.append(temp.data)\n if temp.left:\n q.append(temp.left)\n temp = temp.right\n return ans", "def diagonal(root):\n q = []\n ans = []\n if root is None:\n return ans\n q.append(root)\n while q:\n temp = q.pop(0)\n while temp:\n if temp.left:\n q.append(temp.left)\n ans.append(temp.data)\n temp = temp.right\n return ans", "def diagonal(root):\n arr = [root]\n ans = []\n while len(arr) > 0:\n temp = arr.pop(0)\n while temp is not None:\n if temp.left:\n arr.append(temp.left)\n ans.append(temp.data)\n temp = temp.right\n return ans", "def diagonal(root):\n q = [root]\n (temp, res) = ([], [])\n while q:\n node = q.pop(0)\n res.append(node.data)\n if node.left:\n temp.append(node.left)\n if node.right:\n q.append(node.right)\n if not q and temp:\n q.append(temp.pop(0))\n return res", "def diagonal(root):\n if not root:\n return\n (queue, result) = ([], [])\n queue.append(root)\n while len(queue) > 0:\n n = len(queue)\n ans = []\n while n > 0:\n temp = queue[0]\n queue.pop(0)\n while temp is not None:\n ans.append(temp.data)\n if temp.left is not None:\n queue.append(temp.left)\n temp = temp.right\n n -= 1\n result.append(' '.join(map(str, ans)))\n return result", "from collections import defaultdict\n\ndef diagonal(root):\n if root is None:\n return []\n dict1 = defaultdict(list)\n q = [(root, 0)]\n while len(q):\n for i in range(len(q)):\n (s, d) = q.pop()\n if s.right:\n q.append((s.right, d))\n if s.left:\n q.append((s.left, d + 1))\n dict1[d].append(s.data)\n res = []\n for i in sorted(dict1):\n res.extend(dict1[i])\n return res", "def diagonal(root):\n if not root:\n return []\n ans = []\n q = [root]\n while len(q) > 0:\n node = q.pop(0)\n while node:\n if node.left:\n q.append(node.left)\n ans.append(node.data)\n node = node.right\n return ans", "def diagonal(root):\n queue = []\n queue.append(root)\n ans = []\n\n def dfs(root):\n if root == None:\n return\n ans.append(root.data)\n if root.left:\n queue.append(root.left)\n if root.right:\n dfs(root.right)\n while len(queue) != 0:\n root = queue.pop(0)\n dfs(root)\n return ans", "from collections import deque\n\ndef diagonal(root):\n ans = []\n q = deque()\n new_node = Node(0)\n new_node.left = root\n q.append(new_node)\n while len(q) > 0:\n node = q.popleft()\n node = node.left\n while node is not None:\n ans.append(node.data)\n if node.left is not None:\n q.append(node)\n node = node.right\n return ans", "from collections import deque\n\ndef diagonal(root):\n q = deque()\n if root is None:\n return []\n q.appendleft(root)\n res = []\n while len(q) > 0:\n t = q.pop()\n while t is not None:\n res.append(t.data)\n if t.left is not None:\n q.appendleft(t.left)\n t = t.right\n return res", "def diagonal(root):\n queue = []\n ans = []\n queue.append(root)\n while queue:\n curr = queue.pop(0)\n while curr:\n if curr.left:\n queue.append(curr.left)\n ans.append(curr.data)\n curr = curr.right\n return ans", "def diagonal(root):\n result = []\n if root == None:\n return result\n q = deque()\n q.append(root)\n while len(q) != 0:\n current = q.popleft()\n while current:\n result.append(current.data)\n if current.left:\n q.append(current.left)\n current = current.right\n return result", "import collections\n\ndef diagonal(root):\n res = []\n q = collections.deque()\n q.append(root)\n while q:\n a = q.popleft()\n res.append(a.data)\n if a.left:\n q.append(a.left)\n t = a.right\n if t:\n res.append(t.data)\n while t:\n if t.left:\n q.append(t.left)\n if t.right:\n res.append(t.right.data)\n t = t.right\n return res", "def diagonal(root):\n\n def diag(root, x, d):\n if root is None:\n return\n try:\n d[x].append(root.data)\n except KeyError:\n d[x] = [root.data]\n diag(root.left, x + 1, d)\n diag(root.right, x, d)\n d = dict()\n a = []\n diag(root, 0, d)\n for i in d:\n for j in d[i]:\n a.append(j)\n return a", "import collections\n\ndef dfs(node):\n if not node:\n return\n self.diag_lst.append(node.data)\n if node.left:\n self.q.append(node.left)\n self.dfs(node.right)\n return\n\ndef diagonal(root):\n self.q = collections.deque()\n self.diag_lst = []\n self.q.append(root)\n while self.q:\n self.dfs(self.q.popleft())\n return self.diag_lst", "def diagonal(root):\n right = []\n res = []\n q = [root]\n while q or right:\n if q:\n x = q.pop(0)\n else:\n x = right.pop(0)\n if x.right:\n q.append(x.right)\n if x.left:\n right.append(x.left)\n res.append(x)\n for i in range(len(res)):\n res[i] = res[i].data\n return res", "def diagonal(root):\n temp = []\n result = []\n\n def trav(root):\n if root == None:\n return\n result.append(root.data)\n if root.left != None:\n temp.append(root.left)\n if root.right == None:\n if len(temp) == 0:\n return\n x = temp.pop(0)\n trav(x)\n else:\n trav(root.right)\n trav(root)\n return result", "def diagonal(root):\n if root is None:\n return\n level = []\n ansArr = []\n while root:\n ansArr.append(root.data)\n if root.left:\n level.append(root.left)\n if root.right:\n root = root.right\n else:\n if not level:\n break\n root = level.pop(0)\n return ansArr", "def diagonal(root):\n q = deque()\n q.append(root)\n ans = []\n while len(q) > 0:\n curr = q.popleft()\n while curr is not None:\n ans.append(curr.data)\n if curr.left is not None:\n q.append(curr.left)\n curr = curr.right\n return ans", "def diagonal(root):\n ans = []\n if root is None:\n return ans\n import collections\n queue = collections.deque()\n queue.append(root)\n while len(queue) != 0:\n curr = queue.popleft()\n while curr is not None:\n ans.append(curr.data)\n if curr.left != None:\n queue.append(curr.left)\n curr = curr.right\n return ans", "def diagonal(root):\n traverse_queue = [root]\n final_result = []\n while len(traverse_queue) > 0:\n node_pop = traverse_queue.pop(0)\n final_result.append(node_pop.data)\n curr = node_pop\n while curr is not None:\n if curr.left is not None:\n traverse_queue.append(curr.left)\n curr = curr.right\n if curr is not None:\n final_result.append(curr.data)\n return final_result"], "starter_code": "def _init_(val):\n", "input_output": {"inputs": ["8\r\n / \\\r\n 3 10\r\n / \\ \\\r\n 1 6 14\r\n / \\ /\r\n 4 7 13"], "outputs": ["8 10 14 3 6 7 13 1 4"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/diagonal-traversal-of-binary-tree/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "_init_", "task_id": "TACO_lite/34", "example": [[], []]} +{"requirement": "# Kata Task\n\nI have a cat and a dog.\n\nI got them at the same time as kitten/puppy. That was `humanYears` years ago.\n\nReturn their respective ages now as [`humanYears`,`catYears`,`dogYears`]\n\nNOTES:\n* humanYears >= 1\n* humanYears are whole numbers only\n\n## Cat Years\n\n* `15` cat years for first year\n* `+9` cat years for second year\n* `+4` cat years for each year after that\n\n## Dog Years\n\n* `15` dog years for first year\n* `+9` dog years for second year\n* `+5` dog years for each year after that\n\n\n\n**References**\n\n* http://www.catster.com/cats-101/calculate-cat-age-in-cat-years\n* http://www.slate.com/articles/news_and_politics/explainer/2009/05/a_dogs_life.html\n\n\n\nIf you liked this Kata there is another related one here", "solutions": ["def human_years_cat_years_dog_years(x):\n return [x, 24 + (x - 2) * 4 if x != 1 else 15, 24 + (x - 2) * 5 if x != 1 else 15]", "def human_years_cat_years_dog_years(human_years):\n catYears = 0\n dogYears = 0\n if human_years == 1:\n catYears += 15\n dogYears += 15\n return [human_years, catYears, dogYears]\n elif human_years == 2:\n catYears += 24\n dogYears += 24\n return [human_years, catYears, dogYears]\n elif human_years > 2:\n catYears += 24\n dogYears += 24\n years = human_years - 2\n catYears += years * 4\n dogYears += years * 5\n return [human_years, catYears, dogYears]\n return [0, 0, 0]", "def human_years_cat_years_dog_years(n):\n cat_years = 15 + 9 * (n > 1) + 4 * (n - 2) * (n > 2)\n dog_years = 15 + 9 * (n > 1) + 5 * (n - 2) * (n > 2)\n return [n, cat_years, dog_years]", "def human_years_cat_years_dog_years(hy):\n return [hy, 16 + 4 * hy, 14 + 5 * hy] if hy > 1 else [1, 15, 15]", "def human_years_cat_years_dog_years(human_years, dog_years=15, cat_years=15):\n if human_years == 1:\n pass\n elif human_years == 2:\n cat_years = dog_years = 24\n else:\n cat_years = 4 * human_years + 16\n dog_years = 5 * human_years + 14\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(h):\n (c, d) = (0, 0)\n if h == 1:\n (c, d) = (15, 15)\n elif h >= 2:\n (c, d) = (24, 24)\n for i in range(h - 2, 0, -1):\n c += 4\n d += 5\n return [h, c, d]", "def human_years_cat_years_dog_years(human_years):\n catYears = 15\n DogYears = 15\n if human_years == 1:\n return [human_years, catYears, DogYears]\n elif human_years == 2:\n return [human_years, catYears + 9, DogYears + 9]\n elif human_years >= 3:\n n = human_years - 3\n s = 24 + n * 4 + 4\n f = 24 + n * 5 + 5\n return [human_years, s, f]", "def human_years_cat_years_dog_years(human_years):\n if human_years > 2:\n cat_years = (human_years - 2) * 4 + 24\n dog_years = (human_years - 2) * 5 + 24\n elif human_years == 2:\n cat_years = 24\n dog_years = 24\n else:\n cat_years = 15\n dog_years = 15\n return [human_years, cat_years, dog_years]", "human_years_cat_years_dog_years = lambda h: [h] + [15 * (h >= 1) + 9 * (h >= 2) + (h - 2) * y * (h > 2) for y in [4, 5]]", "def human_years_cat_years_dog_years(h):\n return [h, 15 + 9 * (h >= 2) + 4 * max(h - 2, 0), 15 + 9 * (h >= 2) + 5 * max(h - 2, 0)]", "def human_years_cat_years_dog_years(years):\n return [years, 16 + 4 * years, 14 + 5 * years] if years > 1 else [1, 15, 15]", "def human_years_cat_years_dog_years(human_years):\n catYears = 0\n dogYears = 0\n if human_years < 2:\n catYears = human_years * 15\n dogYears = catYears\n elif human_years < 3:\n catYears = 15 + 9\n dogYears = catYears\n else:\n catYears = (human_years - 2) * 4 + 24\n dogYears = (human_years - 2) * 5 + 24\n return [human_years, catYears, dogYears]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n return [1, 15, 15]\n years_after_2nd = human_years - 2\n cat_years = 24 + 4 * years_after_2nd\n dog_years = 24 + 5 * years_after_2nd\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(human_years):\n CAT_YEARS_FIRST = 14\n DOG_YEARS_FIRST = 14\n CAT_YEARS_SECOND = 8\n DOG_YEARS_SECOND = 8\n CAT_YEARS_THIRD = 4\n DOG_YEARS_THIRD = 5\n if human_years == 1:\n return [human_years, human_years + CAT_YEARS_FIRST, human_years + DOG_YEARS_FIRST]\n elif human_years == 2:\n return [human_years, human_years + CAT_YEARS_FIRST + CAT_YEARS_SECOND, human_years + DOG_YEARS_FIRST + DOG_YEARS_SECOND]\n else:\n return [human_years, CAT_YEARS_FIRST + CAT_YEARS_SECOND + CAT_YEARS_THIRD * (human_years - 2) + 2, DOG_YEARS_FIRST + DOG_YEARS_SECOND + DOG_YEARS_THIRD * (human_years - 2) + 2]", "from functools import partial\n\ndef human_years_cat_years_dog_years(human_years):\n return [age_func(human_years) for age_func in (human_age, cat_age, dog_age)]\n\ndef critter_age(human_years, critter_years_multipliers):\n critter_age = previous_year = 0\n for (year, multiplier) in critter_years_multipliers:\n is_older = human_years > year\n years_difference = (year if is_older else human_years) - previous_year\n critter_age += multiplier * years_difference\n if not is_older:\n break\n previous_year = year\n return critter_age\ninfinity = float('inf')\nhuman_age = partial(critter_age, critter_years_multipliers=((infinity, 1),))\ncat_age = partial(critter_age, critter_years_multipliers=((1, 15), (2, 9), (infinity, 4)))\ndog_age = partial(critter_age, critter_years_multipliers=((1, 15), (2, 9), (infinity, 5)))", "def human_years_cat_years_dog_years(human_years):\n ages = [0, 0, 0]\n if human_years == 1:\n ages[0] = 1\n ages[1] = 15\n ages[2] = 15\n if human_years == 2:\n ages[0] = 2\n ages[1] = 24\n ages[2] = 24\n if human_years >= 3:\n ages[0] = human_years\n ages[1] = 24 + (human_years - 2) * 4\n ages[2] = 24 + (human_years - 2) * 5\n return ages", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n return [1, 15, 15]\n if human_years == 2:\n return [2, 24, 24]\n return [human_years, (human_years - 2) * 4 + 24, (human_years - 2) * 5 + 24]", "def human_years_cat_years_dog_years(human_years):\n cat_years = 15 if human_years == 1 else 15 + 9 if human_years == 2 else 15 + 9 + (human_years - 2) * 4\n dog_years = 15 if human_years == 1 else 15 + 9 if human_years == 2 else 15 + 9 + (human_years - 2) * 5\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(human_years):\n a = 15 + 9 * int(human_years >> 1 != 0)\n return [human_years, a + 4 * max(0, human_years - 2), a + 5 * max(0, human_years - 2)]", "def human_years_cat_years_dog_years(human_years):\n cat_years = (lambda y: 15 + 9 * (0, 1)[y - 1 > 0] + 4 * (y - 2) * (0, 1)[y - 2 > 0])(human_years)\n dog_years = (lambda y: 15 + 9 * (0, 1)[y - 1 > 0] + 5 * (y - 2) * (0, 1)[y - 2 > 0])(human_years)\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(n):\n return [n, 15 if n == 1 else 4 * (n + 4), 15 if n == 1 else 5 * n + 14]", "from functools import partial\ninfinity = float('inf')\n\ndef human_years_cat_years_dog_years(human_years):\n age = Age.from_human(human_years)\n return [age.as_human, age.as_cat, age.as_dog]\n\ndef __new__(meta, name, bases, namespace):\n attr_name = namespace.pop('_attr_name_', 'normalized_age')\n conversions = namespace.pop('_conversions_', {})\n if conversions:\n\n def as_(self, year_to_multiplier):\n age = getattr(self, attr_name)\n converted_age = previous_year = 0\n for (year, multiplier) in year_to_multiplier:\n is_older = age > year\n years_difference = (year if is_older else age) - previous_year\n converted_age += multiplier * years_difference\n if not is_older:\n break\n previous_year = year\n return converted_age\n for (name, year_to_multiplier) in conversions.items():\n namespace['from_' + name] = classmethod(partial(meta.__from, year_to_multiplier=year_to_multiplier))\n namespace['as_' + name] = property(partial(as_, year_to_multiplier=year_to_multiplier))\n\n def __init__(self, normalized_age):\n setattr(self, attr_name, normalized_age)\n namespace['__init__'] = __init__\n return super().__new__(meta, name, bases, namespace)\n\ndef __from(cls, age, year_to_multiplier):\n normalized_age = previous_year = 0\n for (year, multiplier) in year_to_multiplier:\n years_difference = year - previous_year\n max_age_in_range = multiplier * years_difference\n if age <= max_age_in_range:\n normalized_age += age / multiplier\n break\n age -= max_age_in_range\n previous_year = year\n normalized_age += years_difference\n return cls(normalized_age)", "def human_years_cat_years_dog_years(hy):\n cy = 15 + (hy > 1) * (4 * hy + 1)\n dy = 15 + (hy > 1) * (5 * hy - 1)\n return [hy, cy, dy]", "def human_years_cat_years_dog_years(human_years):\n cat = sum([15, 9, (human_years - 2) * 4][:human_years])\n dog = sum([15, 9, (human_years - 2) * 5][:human_years])\n return [human_years, cat, dog]", "human_years_cat_years_dog_years = lambda n: [n] + [15 * (n > 0) + 9 * (n > 1) + d * max(0, n - 2) for d in (4, 5)]", "human_years_cat_years_dog_years = lambda h: [1, 15, 15] if h == 1 else [2, 24, 24] if h == 2 else [h, 24 + 4 * (h - 2), 24 + 5 * (h - 2)]", "def human_years_cat_years_dog_years(human_years):\n (cat_years, dog_years) = (0, 0)\n if human_years > 1:\n cat_years = 24 + (human_years - 2) * 4\n dog_years = 24 + (human_years - 2) * 5\n else:\n cat_years = dog_years = 15\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(y):\n return [y, 24 + 4 * (y - 2), 24 + 5 * (y - 2)] if y >= 2 else [y, y * 9 + 6, y * 9 + 6]", "YRS = (15, 15 + 9, (4, 5))\n\ndef human_years_cat_years_dog_years(human_years):\n return [human_years, *({0: YRS[0]}.get(human_years - 1, k * (human_years - 2) + YRS[1]) for k in YRS[-1])]", "def human_years_cat_years_dog_years(human_years):\n return [human_years, *(dict(enumerate((15, 24))).get(human_years - 1, k * (human_years - 2) + 24) for k in (4, 5))]", "def human_years_cat_years_dog_years(y):\n return [y, 16 + 4 * y, 14 + 5 * y] if y > 1 else [1, 15, 15]", "def human_years_cat_years_dog_years(h):\n cat = sum([15 if x == 0 else 9 if x == 1 else 4 for x in range(h)])\n return [h, cat, cat + h - 2 if h > 2 else cat]", "def human_years_cat_years_dog_years(h):\n l = list(range(1, h + 1))\n return [h, 15 * len(l[0:1]) + 9 * len(l[1:2]) + 4 * len(l[2:]), 15 * len(l[0:1]) + 9 * len(l[1:2]) + 5 * len(l[2:])]", "def human_years_cat_years_dog_years(human_years):\n catYears = 15\n if human_years == 2:\n catYears = 15 + 9\n if human_years >= 3:\n catYears = 24 + (human_years - 2) * 4\n dogYears = 15\n if human_years == 2:\n dogYears = 15 + 9\n if human_years >= 3:\n dogYears = 24 + (human_years - 2) * 5\n return [human_years, catYears, dogYears]", "def human_years_cat_years_dog_years(human_years):\n return [human_years, sum([15 if x == 1 else 9 if x == 2 else 4 for x in range(1, human_years + 1)]), sum([15 if x == 1 else 9 if x == 2 else 5 for x in range(1, human_years + 1)])]", "from typing import List\n\ndef human_years_cat_years_dog_years(human_years: int) -> List[int]:\n __get_animals_years_multiplier = lambda _def: [{1: 15, 2: 9}.get(_it, _def) for _it in list(range(1, human_years + 1))]\n return [human_years, sum(__get_animals_years_multiplier(4)), sum(__get_animals_years_multiplier(5))]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n dog = 15\n cat = 15\n elif human_years == 2:\n dog = 24\n cat = 24\n else:\n dog = 24 + int(human_years - 2) * 5\n cat = 24 + int(human_years - 2) * 4\n return [human_years, cat, dog]", "def human_years_cat_years_dog_years(human_years):\n if human_years >= 1:\n cat_years = 15\n dog_years = 15\n if human_years >= 2:\n cat_years += 9\n dog_years += 9\n for i in range(human_years - 2):\n cat_years += 4\n dog_years += 5\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(human_years):\n cat_years = 15 + 9 * (human_years >= 2) + 4 * (human_years - 2) * (human_years >= 3)\n dog_years = 15 + 9 * (human_years >= 2) + 5 * (human_years - 2) * (human_years >= 3)\n return [human_years, cat_years, dog_years]", "human_years_cat_years_dog_years = lambda y: [y, y * 4 + (16 if y > 1 else 11 if y == 1 else 0), y * 5 + (14 if y > 1 else 10 if y == 1 else 0)]", "def human_years_cat_years_dog_years(human_years):\n if human_years >= 2:\n catYears = 15 + 9 + (human_years - 2) * 4\n dogYears = 15 + 9 + (human_years - 2) * 5\n return [human_years, catYears, dogYears]\n else:\n return [human_years, 15, 15]", "def human_years_cat_years_dog_years(human_years):\n catYears = 0\n dogYears = 0\n humanYears = human_years\n for i in range(human_years):\n if i == 0:\n catYears = catYears + 15\n dogYears = dogYears + 15\n if i == 1:\n catYears = catYears + 9\n dogYears = dogYears + 9\n if i > 1:\n catYears = catYears + 4\n dogYears = dogYears + 5\n return [humanYears, catYears, dogYears]", "def human_years_cat_years_dog_years(human_years):\n c = 15\n d = 15\n if human_years == 2:\n c = 15 + 9\n d = 15 + 9\n if human_years > 2:\n c = 24 + (human_years - 2) * 4\n d = 24 + (human_years - 2) * 5\n return [human_years, c, d]", "def human_years_cat_years_dog_years(hy):\n return [hy, 15 if hy == 1 else 24 if hy == 2 else 24 + (hy - 2) * 4, 15 if hy == 1 else 24 if hy == 2 else 24 + (hy - 2) * 5]", "def human_years_cat_years_dog_years(human_years):\n animal_first_two_years = 15 if human_years > 0 else 0\n animal_first_two_years += 9 if human_years > 1 else 0\n animal_last_years = max(0, human_years - 2)\n return [human_years, animal_first_two_years + 4 * animal_last_years, animal_first_two_years + 5 * animal_last_years]", "def human_years_cat_years_dog_years(human_years):\n b = 0\n c = 0\n if human_years == 1:\n b = 15\n c = 15\n elif human_years == 2:\n b = 24\n c = 24\n else:\n b = 24 + (human_years - 2) * 4\n c = 24 + (human_years - 2) * 5\n return [human_years, b, c]", "def human_years_cat_years_dog_years(human_years):\n dog_years = 15 + min(human_years - 1, 1) * 9 + max(human_years - 2, 0) * 5\n cat_years = 15 + min(human_years - 1, 1) * 9 + max(human_years - 2, 0) * 4\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(hy):\n if hy == 1:\n return [1, 15, 15]\n elif hy == 2:\n return [2, 24, 24]\n elif hy > 2:\n return [hy, 24 + 4 * (hy - 2), 24 + 5 * (hy - 2)]\n return [0, 0, 0]", "def human_years_cat_years_dog_years(human):\n if human == 1:\n return [human, 15, 15]\n if human == 2:\n return [human, 24, 24]\n if human >= 3:\n return [human, (human - 2) * 4 + 24, (human - 2) * 5 + 24]", "def human_years_cat_years_dog_years(human):\n cat = 0\n dog = 0\n if human >= 1:\n cat += 15\n dog += 15\n if human >= 2:\n cat += 9\n dog += 9\n if human >= 3:\n n = human - 2\n cat += n * 4\n dog += n * 5\n return [human, cat, dog]", "def human_years_cat_years_dog_years(hy):\n base = 15 * (hy >= 1) + 9 * (hy >= 2)\n rest = max(0, hy - 2)\n cy = base + 4 * rest\n dy = base + 5 * rest\n return [hy, cy, dy]", "def human_years_cat_years_dog_years(h):\n if h == 1:\n return [h, 15, 15]\n if h == 2:\n return [h, 24, 24]\n return [h, 24 + (h - 2) * 4, 24 + (h - 2) * 5]", "from itertools import accumulate, repeat\n\ndef human_years_cat_years_dog_years(years):\n if years >= 2:\n return [years, 4 * (years - 2) + 24, 5 * (years - 2) + 24]\n elif years == 1:\n return [1, 15, 15]", "def human_years_cat_years_dog_years(human_years):\n cat_years = 0\n dog_years = 0\n for y in range(0, human_years):\n if y == 0:\n cat_years += 15\n dog_years += 15\n elif y == 1:\n cat_years += 9\n dog_years += 9\n else:\n cat_years += 4\n dog_years += 5\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(human_years):\n cat_years = 0\n dog_years = 0\n if human_years < 2:\n cat_years += 15\n dog_years += 15\n elif human_years == 2:\n cat_years += 15 + 9\n dog_years += 15 + 9\n else:\n cat_years += 15 + 9 + (human_years - 2) * 4\n dog_years += 15 + 9 + (human_years - 2) * 5\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n return [1, 15, 15]\n elif human_years == 2:\n return [2, 24, 24]\n else:\n return [human_years, (human_years - 2) * 4 + 24, (human_years - 2) * 5 + 24]\n 32", "def human_years_cat_years_dog_years(h):\n (cat, dog) = (0, 0)\n if h >= 1:\n cat += 15\n dog += 15\n if h >= 2:\n cat += 9\n dog += 9\n if h >= 3:\n cat += 4 * (h - 2)\n dog += 5 * (h - 2)\n return [h, cat, dog]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n cat_years = 15\n dog_years = 15\n elif human_years == 2:\n cat_years = 24\n dog_years = 24\n elif human_years == 3:\n cat_years = 28\n dog_years = 29\n else:\n cat_years = 28 + (human_years - 3) * 4\n dog_years = 29 + (human_years - 3) * 5\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(human_years):\n a = human_years\n if human_years == 1:\n d = 15\n c = 15\n elif human_years == 2:\n d = 24\n c = 24\n else:\n d = 24 + abs(human_years - 2) * 5\n c = 24 + abs(human_years - 2) * 4\n return [a, c, d]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n cat_years = 15\n dog_years = 15\n elif human_years == 2:\n cat_years = 15 + 9\n dog_years = 15 + 9\n elif human_years > 2:\n cat_years = 24 + (human_years - 2) * 4\n dog_years = 24 + (human_years - 2) * 5\n else:\n None\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n (catYears, dogYears) = (15, 15)\n elif human_years == 2:\n (catYears, dogYears) = (24, 24)\n else:\n catYears = 24 + (human_years - 2) * 4\n dogYears = 24 + (human_years - 2) * 5\n return [human_years, catYears, dogYears]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n (cat_y, dog_y) = (15, 15)\n elif human_years == 2:\n (cat_y, dog_y) = (24, 24)\n else:\n cat_y = 24 + 4 * (human_years - 2)\n dog_y = 24 + 5 * (human_years - 2)\n return [human_years, cat_y, dog_y]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n (cat, dog) = (15, 15)\n if human_years == 2:\n (cat, dog) = (24, 24)\n if human_years >= 3:\n cat = 24 + (human_years - 2) * 4\n dog = 24 + (human_years - 2) * 5\n return [human_years, cat, dog]", "def human_years_cat_years_dog_years(h):\n if h is 1:\n c = 15\n d = 15\n elif h is 2:\n c = 24\n d = 24\n else:\n c = 24 + (h - 2) * 4\n d = 24 + (h - 2) * 5\n return [h, c, d]", "def human_years_cat_years_dog_years(human_years):\n years = [0, 0, 0]\n for i in range(0, human_years):\n if years[0] == 0:\n years[0] += 1\n years[1] += 15\n years[2] += 15\n elif years[0] == 1:\n years[0] += 1\n years[1] += 9\n years[2] += 9\n else:\n years[0] += 1\n years[1] += 4\n years[2] += 5\n return years", "def human_years_cat_years_dog_years(human_years):\n caty = 0\n for i in range(0, human_years):\n if i == 0:\n caty += 15\n elif i == 1:\n caty += 9\n else:\n caty += 4\n dogy = 0\n for i in range(0, human_years):\n if i == 0:\n dogy += 15\n elif i == 1:\n dogy += 9\n else:\n dogy += 5\n return [human_years, caty, dogy]", "def human_years_cat_years_dog_years(y):\n c = d = 15\n if y > 1:\n c = d = 24\n if y > 2:\n (c, d) = (c + 4 * (y - 2), d + 5 * (y - 2))\n return [y, c, d]", "def human_years_cat_years_dog_years(human_years):\n return [human_years, 15 + (9 if human_years >= 2 else 0) + ((human_years - 2) * 4 if human_years >= 2 else 0), 15 + (9 if human_years >= 2 else 0) + ((human_years - 2) * 5 if human_years >= 2 else 0)]", "def human_years_cat_years_dog_years(y):\n if y == 1:\n return [1, 15, 15]\n elif y == 2:\n return [2, 24, 24]\n else:\n return [y, 24 + (y - 2) * 4, 24 + (y - 2) * 5]", "def human_years_cat_years_dog_years(human_years):\n f = 15\n s = 9\n if human_years == 1:\n return [human_years, f, f]\n elif human_years == 2:\n return [human_years, f + s, f + s]\n else:\n return [human_years, f + s + (human_years - 2) * 4, f + s + (human_years - 2) * 5]", "def human_years_cat_years_dog_years(human):\n\n def animal(h, p):\n r = 0\n for i in range(1, h + 1):\n if i == 1:\n r += 15\n elif i == 2:\n r += 9\n else:\n r += p\n return r\n return [human, animal(human, 4), animal(human, 5)]", "def human_years_cat_years_dog_years(h):\n return [h, 15 + 9 * int(h > 1) + 4 * (h - 2) * int(h > 2), 15 + 9 * int(h > 1) + 5 * (h - 2) * int(h > 2)]", "def human_years_cat_years_dog_years(yr):\n return ['one-liner', [1, 15, 15], [2, 24, 24]][yr] if yr in range(1, 3) else [yr, (yr - 2) * 4 + 24, (yr - 2) * 5 + 24]", "def human_years_cat_years_dog_years(human_years):\n cat_years = 15 * (human_years >= 1) + 9 * (human_years >= 2) + 4 * max(human_years - 2, 0)\n return [human_years, cat_years, cat_years + max(human_years - 2, 0)]", "human_years_cat_years_dog_years = lambda h: [h, 15 + (h >= 2) * (9 + (h - 2) * 4), 15 + (h >= 2) * (9 + (h - 2) * 5)]", "def human_years_cat_years_dog_years(human_years):\n cat_years = 0\n dog_years = 0\n human = human_years\n if human >= 1:\n cat_years = 15\n dog_years = 15\n human = human - 1\n if human >= 1:\n cat_years += 9\n dog_years += 9\n human = human - 1\n if human >= 1:\n cat_years += human * 4\n dog_years += human * 5\n return [human_years, cat_years, dog_years]"], "starter_code": "def human_years_cat_years_dog_years(human_years):\n", "input_output": {"fn_name": "human_years_cat_years_dog_years", "inputs": [[1], [2], [10]], "outputs": [[[1, 15, 15]], [[2, 24, 24]], [[10, 56, 64]]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5a6663e9fd56cb5ab800008b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "human_years_cat_years_dog_years", "task_id": "TACO_lite/25", "example": [[[1], [2], [3]], ["[1, 15, 15]", "[2, 24, 24]", "[3, 28, 29]"]]} +{"requirement": "Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.\n\n```python\nmove_zeros([False,1,0,1,2,0,1,3,\"a\"]) # returns[False,1,1,2,1,3,\"a\",0,0]\n```", "solutions": ["def move_zeros(arr):\n l = [i for i in arr if isinstance(i, bool) or i != 0]\n return l + [0] * (len(arr) - len(l))", "def move_zeros(array):\n return sorted(array, key=lambda x: x == 0 and type(x) is not bool)", "def move_zeros(array):\n return sorted(array, key=lambda x: x == 0 and x is not False)", "def move_zeros(array):\n newarr = []\n zeroarr = []\n for item in array:\n if item != 0 or type(item) == bool:\n newarr.append(item)\n else:\n zeroarr.append(item)\n newarr.extend(zeroarr)\n return newarr", "def move_zeros(array):\n return [a for a in array if isinstance(a, bool) or a != 0] + [a for a in array if not isinstance(a, bool) and a == 0]", "def move_zeros(array):\n a = list(filter(lambda x: x != 0 or type(x) is bool, array))\n return a + [0] * (len(array) - len(a))", "def move_zeros(array):\n return [x for x in array if x != 0 or x is False] + [x for x in array if x == 0 and (not x is False)]", "def move_zeros(array):\n return sorted(array, key=lambda x: not isinstance(x, bool) and x == 0)", "def move_zeros(array):\n temp = []\n for e in array[::-1]:\n if type(e) in (int, float, complex) and e == 0:\n temp.append(0)\n else:\n temp.insert(0, e)\n array = temp\n return array", "def move_zeros(array):\n without_zeros = list(filter(lambda n: not n == 0 or n is False, array))\n for i in range(len(array) - len(without_zeros)):\n without_zeros.append(0)\n return without_zeros", "def move_zeros(array):\n a_len = len(array)\n array = [v for v in array if type(v) is bool or v != 0]\n array.extend([0] * (a_len - len(array)))\n return array", "def move_zeros(array):\n a = []\n b = []\n for v in array:\n if type(v) in [float, int] and v == 0:\n b.append(0)\n else:\n a.append(v)\n return a + b", "move_zeros = lambda arr: [i for i in arr if str(i) == 'False' or i != 0] + [_ for _ in arr if str(_) != 'False' and _ == 0]", "def move_zeros(array):\n new_list = []\n c = 0\n for item in array:\n if item != 0 or type(item) == bool:\n new_list.append(item)\n else:\n c += 1\n i = 0\n while i < c:\n new_list.append(0)\n i += 1\n return new_list", "def move_zeros(array):\n new_array = []\n for check in array:\n if check != 0 or isinstance(check, bool):\n new_array.append(check)\n for cnt in range(abs(len(new_array) - len(array))):\n new_array.append(0)\n return new_array", "def move_zeros(array):\n strs = []\n array1 = array.copy()\n for i in array1:\n if isinstance(i, str):\n strs.append(i)\n array1[array1.index(i)] = ' '\n for i in array1:\n array1[array1.index(i)] = str(array1[array1.index(i)])\n for i in array1:\n if i == '0' or i == '0.0':\n array1.remove(i)\n array1.append('0')\n for i in array1:\n if i != ' ':\n array1[array1.index(i)] = eval(array1[array1.index(i)])\n\n def insf():\n v = 0\n while v < len(strs):\n v += 1\n yield v\n n = insf()\n for i in array1:\n if i == ' ':\n array1[array1.index(i)] = strs[next(n) - 1]\n return array1", "def move_zeros(array):\n zeros = 0\n new_arr = []\n for ele in array:\n if type(ele).__name__ != 'str' and str(ele) in '0.0':\n zeros += 1\n else:\n new_arr += [ele]\n return new_arr + [0] * zeros"], "starter_code": "def move_zeros(array):\n", "input_output": {"fn_name": "move_zeros", "inputs": [[[1, 2, 0, 1, 0, 1, 0, 3, 0, 1]], [[9, 0.0, 0, 9, 1, 2, 0, 1, 0, 1, 0.0, 3, 0, 1, 9, 0, 0, 0, 0, 9]], [["a", 0, 0, "b", "c", "d", 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9]], [["a", 0, 0, "b", null, "c", "d", 0, 1, false, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9]], [[0, 1, null, 2, false, 1, 0]], [["a", "b"]], [["a"]], [[0, 0]], [[0]], [[]]], "outputs": [[[1, 2, 1, 1, 3, 1, 0, 0, 0, 0]], [[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [["a", "b", "c", "d", 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [["a", "b", null, "c", "d", 1, false, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [[1, null, 2, false, 1, 0, 0]], [["a", "b"]], [["a"]], [[0, 0]], [[0]], [[]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms", "Sorting"], "name": null, "source": "codewars", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/52597aa56021e91c93000cb0", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "move_zeros", "task_id": "TACO_lite/64", "example": [[[[false, 1, 0, 1, 2, 0, 1, 3, "a"]]], ["[False, 1, 1, 2, 1, 3, 'a', 0, 0]"]]} +{"requirement": "Given two arrays X[] and Y[] of size M and N respectively. Find number of pairs such that x^{y} > y^{x} where x is an element from X[] and y is an element from Y[].\nExample 1:\nInput:\nM = 3, N = 2\nX[] = {2, 1, 6}, Y = {1, 5}\nOutput: 3\nExplanation: There are total 3 pairs \nwhere pow(x, y) is greater than pow(y, x) \nPairs are (2, 1), (2, 5) and (6, 1).\nExample 2:\nInput:\nM = 3, N = 3\nX[] = {10, 19, 18}, Y[] = {11, 15, 9}\nOutput: 2\nExplanation: There are total 2 pairs \nwhere pow(x, y) is greater than pow(y, x) \nPairs are (10, 11) and (10, 15).\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function countPairs() which takes array X[], array Y[], m and n as input parameters and returns an integer denoting the number of pairs that are true to the given condition. \nExpected Time Complexity: O(N*logN + M*logM)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ M, N ≤ 10^{5}\n1 ≤ X[i], Y[i] ≤ 10^{3}", "solutions": ["def countpairs(X, Y, m, n):\n for i in range(m):\n X[i] **= 1 / X[i]\n for i in range(n):\n Y[i] **= 1 / Y[i]\n X.sort()\n Y.sort()\n i = j = 0\n ans = 0\n while i < m:\n if j == n:\n ans += n\n else:\n while j < n and X[i] > Y[j]:\n j += 1\n ans += j\n i += 1\n return ans", "import bisect\n\ndef countpairs(X, Y, m, n):\n X.sort()\n Y.sort()\n ans = 0\n for x in X:\n if x == 1:\n continue\n elif x == 2:\n idx = bisect.bisect_left(Y, 5)\n ans += n - idx\n elif x == 3:\n idx = bisect.bisect_left(Y, 2)\n ans += n - idx\n ans -= bisect.bisect(Y, 3) - bisect.bisect_left(Y, 3)\n else:\n idx = bisect.bisect_left(Y, x + 1)\n ans += n - idx\n for y in Y:\n if y == 1:\n idx = bisect.bisect_left(X, 2)\n ans += m - idx\n return ans", "def countpairs(X, Y, m, n):\n import math\n (x, y) = ([0] * m, [0] * n)\n for i in range(m):\n if X[i] == 1:\n x[i] = float('inf')\n else:\n temp = X[i] * 1.0\n temp = temp / math.log(temp)\n x[i] = temp\n for i in range(n):\n if Y[i] == 1:\n y[i] = float('inf')\n else:\n temp = Y[i] * 1.0\n temp = temp / math.log(temp)\n y[i] = temp\n x.sort()\n y.sort()\n i = j = count = 0\n while i < m and j < n:\n if x[i] < y[j]:\n count += n - j\n i += 1\n else:\n j += 1\n return count", "import bisect as bs\n\ndef countpairs(X, Y, m, n):\n (y1, y0, y2, y3, y4) = (0, 0, 0, 0, 0)\n X.sort()\n Y.sort()\n count = 0\n for i in range(n):\n if Y[i] == 0:\n y0 += 1\n elif Y[i] == 1:\n y1 += 1\n elif Y[i] == 2:\n y2 += 1\n elif Y[i] == 3:\n y3 += 1\n elif Y[i] == 4:\n y4 += 1\n for i in range(m):\n if X[i] == 0:\n continue\n elif X[i] == 1:\n count += y0\n elif X[i] == 2:\n k = bs.bisect_right(Y, 2)\n count += n - k\n count -= y3\n count -= y4\n count += y1 + y0\n else:\n j = bs.bisect_right(Y, X[i])\n count += n - j\n count += y1 + y0\n if X[i] == 3:\n count += y2\n return count", "from bisect import *\n\ndef countpairs(X, Y, m, n):\n one = 0\n two = 0\n for ele in Y:\n if ele == 1:\n one += 1\n if ele == 2:\n two += 1\n X.sort()\n Y.sort()\n ans = 0\n for x in X:\n if x == 1:\n continue\n else:\n ans += one\n if x == 2:\n ans += n - bisect_left(Y, 5)\n continue\n elif x == 3:\n ans += two\n ans += n - bisect_left(Y, x + 1)\n return ans", "from bisect import *\n\ndef countpairs(X, Y, m, n):\n y2 = 0\n y3 = 0\n y1 = 0\n for ele in Y:\n if ele != 2 and ele != 3 and (ele != 4):\n y2 += 1\n if ele != 3:\n y3 += 1\n if ele == 1:\n y1 += 1\n X.sort()\n Y.sort()\n ans = 0\n for x in X:\n if x == 1:\n continue\n elif x == 2:\n ans += y2\n elif x == 3:\n ans += y3\n else:\n ans += y1\n ans += n - bisect_left(Y, x + 1)\n return ans", "from collections import Counter\n\ndef countpairs(X, Y, m, n):\n XC = sorted(Counter(X).items())\n YC = Counter(Y)\n Y = sorted(YC.items())\n (ans, i, left) = (0, 0, n - (YC[2] + YC[3] + YC[4]))\n if XC[i][0] == 1:\n i += 1\n if XC[i][0] == 2:\n ans += XC[i][1] * left\n i += 1\n if XC[i][0] == 3:\n ans += XC[i][1] * (n - YC[3])\n i += 1\n if XC[i][0] == 4:\n ans += XC[i][1] * left\n i += 1\n (j, yleft) = (0, n)\n while i < len(XC):\n (v, xcnt) = XC[i]\n ans += YC[1] * xcnt\n while j < len(Y) and Y[j][0] <= v:\n yleft -= Y[j][1]\n j += 1\n ans += yleft * xcnt\n i += 1\n return ans", "def get_index(y, n, ele):\n ans = -1\n low = 0\n high = n - 1\n while low <= high:\n mid = (low + high) // 2\n if Y[mid] > ele:\n ans = mid\n high = mid - 1\n else:\n low = mid + 1\n return ans\n\ndef countpairs(X, Y, m, n):\n X.sort()\n Y.sort()\n y_c0 = Y.count(0)\n y_c1 = Y.count(1)\n y_c3 = Y.count(3)\n y_c4 = Y.count(4)\n y_c2 = Y.count(2)\n i = 0\n j = 0\n ind = -1\n c = 0\n for i in range(m):\n if X[i] == 0:\n continue\n elif X[i] == 1:\n c += y_c0\n elif X[i] == 2:\n ind = self.get_index(Y, n, 2)\n if ind != -1:\n c += n - ind\n c -= y_c3\n c -= y_c4\n c += y_c1 + y_c0\n else:\n ind = self.get_index(Y, n, X[i])\n if ind != -1:\n c += n - ind\n c += y_c1 + y_c0\n if X[i] == 3:\n c += y_c2\n return c", "import bisect\n\ndef count(x, Y, n, NoOfY):\n if x == 0:\n return 0\n if x == 1:\n return NoOfY[0]\n idx = bisect.bisect_right(Y, x)\n ans = n - idx\n ans += NoOfY[0] + NoOfY[1]\n if x == 2:\n ans -= NoOfY[3] + NoOfY[4]\n if x == 3:\n ans += NoOfY[2]\n return ans\n\ndef countpairs(X, Y, m, n):\n NoOfY = [0] * 5\n for i in range(n):\n if Y[i] < 5:\n NoOfY[Y[i]] += 1\n Y.sort()\n total_pairs = 0\n for x in X:\n total_pairs += self.count(x, Y, n, NoOfY)\n return total_pairs", "def bina(x, g, n):\n l = 0\n h = n - 1\n ans = -1\n while l <= h:\n m = (l + h) // 2\n if g[m] > x:\n ans = m\n h = m - 1\n else:\n l = m + 1\n return ans\n\ndef countpairs(a, b, M, N):\n s = {}\n for i in range(5):\n s[i] = 0\n for i in b:\n if i in s:\n s[i] += 1\n b.sort()\n a.sort()\n c = 0\n for i in a:\n if i == 0:\n continue\n elif i == 1:\n c += s[0]\n elif i == 2:\n ind = self.bina(i, b, N)\n if ind != -1:\n c += N - ind\n c += s[1] + s[0] - s[3] - s[4]\n else:\n ind = self.bina(i, b, N)\n if ind != -1:\n c += N - ind\n c += s[0] + s[1]\n if i == 3:\n c += s[2]\n return c", "import bisect\n\ndef count(x, Y, n, freq):\n if x == 1:\n return freq[0]\n idx = bisect.bisect_right(Y, x)\n ans = n - idx\n ans += freq[0] + freq[1]\n if x == 2:\n ans -= freq[3] + freq[4]\n if x == 3:\n ans += freq[2]\n return ans\n\ndef countpairs(X, Y, m, n):\n freq = [0] * 5\n Y.sort()\n for i in Y:\n if i < 5:\n freq[i] += 1\n count_ans = 0\n for i in X:\n count_ans += self.count(i, Y, n, freq)\n return count_ans", "import bisect\n\ndef countpairs(X, Y, m, n):\n Y.sort()\n noOfYs = [0 for _ in range(5)]\n for i in range(n):\n if Y[i] < 5:\n noOfYs[Y[i]] += 1\n pairs = 0\n for x in X:\n pairs += self.count(x, Y, noOfYs, n)\n return pairs\n\ndef count(x, Y, noOfYs, n):\n if x == 0:\n return 0\n if x == 1:\n return noOfYs[0]\n idx = bisect.bisect_right(Y, x)\n res = n - idx\n res += noOfYs[1] + noOfYs[0]\n if x == 2:\n res -= noOfYs[3] + noOfYs[4]\n if x == 3:\n res += noOfYs[2]\n return res", "import bisect\n\ndef countpairs(X, Y, m, n):\n NoOfYs = [0 for _ in range(5)]\n for i in range(n):\n if Y[i] < 5:\n NoOfYs[Y[i]] += 1\n Y.sort()\n pairs = 0\n for x in X:\n pairs += self.count(x, Y, NoOfYs)\n return pairs\n\ndef count(x, Y, noOfYs):\n if x == 0:\n return 0\n if x == 1:\n return noOfYs[0]\n idx = bisect.bisect_right(Y, x)\n res = len(Y) - idx\n res += noOfYs[0] + noOfYs[1]\n if x == 2:\n res -= noOfYs[3] + noOfYs[4]\n if x == 3:\n res += noOfYs[2]\n return res\n\ndef binarySearch(Y, x):\n low = 0\n high = len(Y) - 1\n idx = -1\n while low <= high:\n mid = (low + high) // 2\n if Y[mid] > x:\n idx = mid\n high = mid - 1\n else:\n low = mid + 1\n return idx", "import math\nimport sys\n\ndef countpairs(X, Y, m, n):\n arr1 = X\n arr2 = Y\n for i in range(len(arr1)):\n if arr1[i] == 1:\n arr1[i] = sys.maxsize\n else:\n arr1[i] = arr1[i] / math.log(arr1[i])\n arr1.sort()\n for j in range(len(arr2)):\n if arr2[j] == 1:\n arr2[j] = sys.maxsize\n else:\n arr2[j] = arr2[j] / math.log(arr2[j])\n arr2.sort()\n pointA = 0\n pointB = 0\n count = 0\n while pointA < len(arr1) and pointB < len(arr2):\n if arr1[pointA] < arr2[pointB]:\n count += len(arr2) - pointB\n pointA += 1\n else:\n pointB += 1\n return count", "import bisect\n\ndef count(i, Y, m, res):\n if i == 0:\n return 0\n if i == 1:\n return res[0]\n ind = bisect.bisect_right(Y, i)\n ans = m - ind\n ans += res[0] + res[1]\n if i == 2:\n ans -= res[3] + res[4]\n if i == 3:\n ans += res[2]\n return ans\n\ndef countpairs(X, Y, m, n):\n cnt = 0\n result = [0] * 5\n for i in range(n):\n if Y[i] < 5:\n result[Y[i]] += 1\n Y.sort()\n for i in X:\n cnt += self.count(i, Y, n, result)\n return cnt", "def search(arr, l, r, x):\n if r >= l:\n mid = l + (r - l) // 2\n if arr[mid] <= x:\n return search(arr, mid + 1, r, x)\n else:\n return search(arr, l, mid - 1, x)\n return l\n\ndef countpairs(X, Y, m, n):\n nn = [0] * 5\n for i in range(n):\n if Y[i] < 5:\n nn[Y[i]] += 1\n Y.sort()\n pairs = 0\n for i in X:\n if i == 0:\n continue\n elif i == 1:\n pairs += nn[0]\n else:\n ss = search(Y, 0, n - 1, i)\n if ss > n - 1:\n ss = 0\n else:\n pairs += n - ss\n pairs += nn[0] + nn[1]\n if i == 2:\n pairs -= nn[3] + nn[4]\n if i == 3:\n pairs += nn[2]\n return pairs", "import bisect\n\ndef bs(arr, low, high, x):\n if low <= high:\n mid = low + (high - low) // 2\n if (mid == 0 or arr[mid - 1] <= x) and arr[mid] > x:\n return mid\n elif arr[mid] <= x:\n return self.bs(arr, mid + 1, high, x)\n else:\n return self.bs(arr, low, mid - 1, x)\n else:\n return -1\n\ndef count(x, Y, n, NoOfY):\n if x == 0:\n return 0\n if x == 1:\n return NoOfY[0]\n idx = bisect.bisect_right(Y, x)\n ans = n - idx\n ans += NoOfY[0] + NoOfY[1]\n if x == 2:\n ans -= NoOfY[3] + NoOfY[4]\n if x == 3:\n ans += NoOfY[2]\n return ans\n\ndef countpairs(X, Y, m, n):\n NoOfY = [0] * 5\n for i in range(n):\n if Y[i] < 5:\n NoOfY[Y[i]] += 1\n Y.sort()\n total_pairs = 0\n for x in X:\n total_pairs += self.count(x, Y, n, NoOfY)\n return total_pairs", "import bisect\n\ndef count(i, b, n, hashe):\n if i == 0:\n return 0\n if i == 1:\n return hashe[0]\n index = bisect.bisect_right(b, i)\n ans = n - index\n ans += hashe[1] + hashe[0]\n if i == 2:\n ans -= hashe[3]\n ans -= hashe[4]\n if i == 3:\n ans += hashe[2]\n return ans\n\ndef countpairs(a, b, M, N):\n pairs = 0\n hashe = dict()\n hashe = [0 for i in range(5)]\n for i in b:\n if i < 5:\n hashe[i] += 1\n b.sort()\n for i in a:\n pairs += self.count(i, b, N, hashe)\n return pairs"], "starter_code": "def countpairs(X, Y, m, n):\n", "input_output": {"inputs": ["M = 3, N = 2\nX[] = {2, 1, 6}, Y = {1, 5}", "M = 3, N = 3\nX[] = {10, 19, 18}, Y[] = {11, 15, 9}"], "outputs": ["3", "2"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Arrays", "Algorithms", "Sorting"], "name": null, "source": "geeksforgeeks", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/number-of-pairs3422/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*logN + M*logM)", "entry_point": "countpairs", "task_id": "TACO_lite/28", "example": [[[3, 2, [2, 1, 6], [1, 5]], [3, 3, [10, 19, 18], [11, 15, 9]]], ["3", "2"]]} +{"requirement": "You're in ancient Greece and giving Philoctetes a hand in preparing a training exercise for Hercules! You've filled a pit with two different ferocious mythical creatures for Hercules to battle!\n\nThe formidable **\"Orthus\"** is a 2 headed dog with 1 tail. The mighty **\"Hydra\"** has 5 heads and 1 tail. \n\nBefore Hercules goes in, he asks you \"How many of each beast am I up against!?\".\n\nYou know the total number of heads and the total number of tails, that's the dangerous parts, right? But you didn't consider how many of each beast. \n\n## Task\n\nGiven the number of heads and the number of tails, work out the number of each mythical beast! \n\nThe data is given as two parameters. Your answer should be returned as an array:\n```python \n VALID -> [24 , 15] INVALID -> \"No solutions\"\n```\n\nIf there aren't any cases for the given amount of heads and tails - return \"No solutions\" or null (C#).", "solutions": ["def beasts(heads, tails):\n orthus = (5 * tails - heads) / 3\n hydra = tails - orthus\n return [orthus, hydra] if orthus >= 0 and hydra >= 0 else 'No solutions'", "def beasts(h, t):\n out = [(5 * t - h) / 3, (h - 2 * t) / 3]\n return all((x.is_integer() and x >= 0 for x in out)) and out or 'No solutions'", "def beasts(heads, tails):\n if heads not in range(tails * 2, tails * 5 + 1, 3):\n return 'No solutions'\n return [(tails * 5 - heads) / 3, (heads - tails * 2) / 3]", "def beasts(heads, tails):\n extraheads = heads - 2 * tails\n if extraheads % 3 != 0 or not 0 <= extraheads <= 3 * tails:\n return 'No solutions'\n hydra = extraheads // 3\n orthus = tails - hydra\n return [orthus, hydra]", "def beasts(heads, tails):\n h = (heads - tails * 2) / 3\n if h < 0 or tails - h < 0:\n return 'No solutions'\n return [tails - h, h]", "beasts = lambda h, t: (lambda m: [t - m, m] if m >= 0 and m <= t and (m % 1 == 0) else 'No solutions')((h - t * 2) / 3.0)", "def beasts(h, t):\n (O, H) = (5 * t - h, h - 2 * t)\n if O >= O % 3 >= 0 <= H % 3 <= H:\n return [O // 3, H // 3]\n else:\n return 'No solutions'", "def beasts(heads, tails):\n for orthus in range(heads // 2 + 1):\n if orthus * 2 + (tails - orthus) * 5 == heads:\n return [orthus, tails - orthus]\n return 'No solutions'", "def beasts(heads, tails):\n o = (5 * tails - heads) / 3\n h = (heads - 2 * tails) / 3\n if o == int(o) and h == int(h) and (o >= 0) and (h >= 0):\n return [int(o), int(h)]\n else:\n return 'No solutions'", "def beasts(heads, tails):\n hydra = (heads - 2 * tails) / 3\n orthus = tails - (heads - 2 * tails) / 3\n if hydra % 1 == 0 and hydra >= 0 and (orthus % 1 == 0) and (orthus >= 0):\n return [orthus, hydra]\n else:\n return f'No solutions'"], "starter_code": "def beasts(heads, tails):\n", "input_output": {"fn_name": "beasts", "inputs": [[123, 39], [371, 88], [24, 12], [113, 37], [635, 181], [25, 555], [12, 25], [54, 956], [5455, 54956], [0, 0], [-1, -1], [-45, 5], [99, 0], [0, 99], [5, -55]], "outputs": [[[24, 15]], [[23, 65]], [[12, 0]], [[24, 13]], [[90, 91]], ["No solutions"], ["No solutions"], ["No solutions"], ["No solutions"], [[0, 0]], ["No solutions"], ["No solutions"], ["No solutions"], ["No solutions"], ["No solutions"]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5751aa92f2dac7695d000fb0", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "beasts", "task_id": "TACO_lite/33", "example": [[[24, 15], [10, 6], [5, 1]], ["[9, 1]", "[2, 1]", "No solutions"]]} +{"requirement": "Given an array of integers arr[0..n-1], count all pairs (arr[i], arr[j]) in it such that i*arr[i] > j*arr[j],\nand 0 ≤ i < j < n.\n \nExample 1:\nInput :\narr[] = {5, 0, 10, 2, 4, 1, 6}\nOutput :\n5\nExplanation :\nPairs which hold condition i*arr[i] > j*arr[j] are\n(10, 2) (10, 4) (10, 1) (2, 1) (4, 1)\n \nExample 2:\nInput :\narr[] = {8, 4, 2, 1}\nOutput :\n2\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function countPairs() which takes the array A[] and its size N as inputs and returns the required result.\n \nExpected Time Complexity: O(N. log(N))\nExpected Auxiliary Space: O(N. log(N))\n \nConstraints:\n1 ≤ N ≤ 10^{5}\n1 ≤ A[ ] ≤ 10^{3}", "solutions": ["def merge(arr, temp, left, mid, right):\n inv_count = 0\n i = left\n j = mid\n k = left\n while i <= mid - 1 and j <= right:\n if arr[i] <= arr[j]:\n temp[k] = arr[i]\n i += 1\n k += 1\n else:\n temp[k] = arr[j]\n k += 1\n j += 1\n inv_count = inv_count + (mid - i)\n while i <= mid - 1:\n temp[k] = arr[i]\n i += 1\n k += 1\n while j <= right:\n temp[k] = arr[j]\n k += 1\n j += 1\n for i in range(left, right + 1):\n arr[i] = temp[i]\n return inv_count\n\ndef _mergeSort(arr, temp, left, right):\n inv_count = 0\n if right > left:\n mid = (right + left) // 2\n inv_count = _mergeSort(arr, temp, left, mid)\n inv_count += _mergeSort(arr, temp, mid + 1, right)\n inv_count += merge(arr, temp, left, mid + 1, right)\n return inv_count\n\ndef countpairs(arr, n):\n for i in range(n):\n arr[i] = i * arr[i]\n temp = [0] * n\n return _mergeSort(arr, temp, 0, n - 1)", "import bisect\n\ndef countpairs(arr, n):\n srt_arr = []\n count = 0\n for i in range(n):\n arr[i] = i * arr[i]\n index = bisect.bisect(srt_arr, arr[i])\n count += i - index\n srt_arr.insert(index, arr[i])\n return count", "def countpairs(arr, n):\n res = [i * arr[i] for i in range(n)]\n temp = [0] * n\n return self.sorter(res, temp, 0, n - 1)\n\ndef sorter(arr, temp, l, r):\n c = 0\n if l < r:\n mid = (l + r) // 2\n c += self.sorter(arr, temp, l, mid)\n c += self.sorter(arr, temp, mid + 1, r)\n c += self.merge(arr, temp, l, mid, r)\n return c\n\ndef merge(arr, temp, l, mid, r):\n i = l\n j = mid + 1\n k = l\n c = 0\n while i <= mid and j <= r:\n if arr[i] <= arr[j]:\n temp[k] = arr[i]\n k += 1\n i += 1\n else:\n temp[k] = arr[j]\n c += mid - i + 1\n k += 1\n j += 1\n while i <= mid:\n temp[k] = arr[i]\n k += 1\n i += 1\n while j <= r:\n temp[k] = arr[j]\n k += 1\n j += 1\n arr[l:r + 1] = temp[l:r + 1]\n return c"], "starter_code": "def countpairs(arr, n):\n", "input_output": {"inputs": ["arr[] = {5, 0, 10, 2, 4, 1, 6}", "arr[] = {8, 4, 2, 1}"], "outputs": ["5", "2"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-pairs-in-an-array4145/1", "Expected Auxiliary Space": "O(N. log(N))", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N. log(N))", "entry_point": "countpairs", "task_id": "TACO_lite/30", "example": [[[[5, 0, 10, 2, 4, 1, 6]], [[8, 4, 2, 1]]], ["5", "2"]]} +{"requirement": "Given an array arr[] of size N, the task is to check whether it is possible to obtain an array having distinct neighboring elements by swapping two neighboring array elements.\nExample 1:\nInput: N = 3, arr[] = {1, 1, 2}\nOutput: YES\nExplanation: Swap 1 (second last element) \nand 2 (last element), to obtain 1 2 1,\nwhich has distinct neighbouring elements.\nExample 2:\nInput: N = 4, arr[] = {7, 7, 7, 7}\nOutput: NO\nExplanation: We can't swap to obtain \ndistinct elements in neighbor .\nYour Task:\nYou don't need to read input or print anything. You just need to complete the function distinctAdjacentElement() that takes array arr[] and its size N as input parameters and returns a boolean value denoting if distinct neighbours are possible or not. \nNote: The generated output is YES or NO according to the returned value.\n \nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\n \nConstraints:\n2 ≤ N ≤ 10^{6}", "solutions": ["from collections import Counter\n\ndef distinctadjacentelement(arr, n):\n k = {}\n kis = []\n for i in arr:\n if i not in k:\n k[i] = 1\n else:\n k[i] += 1\n for i in k:\n kis.append(k[i])\n m = max(kis)\n if m <= (n + 1) // 2:\n return 'YES'", "from collections import Counter\n\ndef distinctadjacentelement(arr, n):\n a = Counter(arr)\n max1 = max(a.values())\n if max1 <= (n + 1) // 2:\n return 1\n else:\n return 0", "def distinctadjacentelement(arr, n):\n a = {}\n for i in arr:\n if i not in a:\n a[i] = 1\n else:\n a[i] += 1\n maxq = max(a.values())\n if maxq <= int(n + 1) / 2:\n return 1\n else:\n return 0", "def distinctadjacentelement(arr, n):\n freq = {}\n for i in arr:\n if i not in freq:\n freq[i] = 0\n freq[i] += 1\n dif = 0\n j = 0\n for i in freq:\n if j % 2 == 0:\n dif += freq[i]\n else:\n dif -= freq[i]\n j += 1\n m = 0\n for i in freq:\n m = max(m, freq[i])\n if m > (n + 1) // 2:\n return False\n return True", "def distinctadjacentelement(arr, n):\n count = {}\n for item in arr:\n if item not in count:\n count[item] = 1\n else:\n count[item] += 1\n maximum = -1\n for value in count.values():\n if value > maximum:\n maximum = value\n if maximum <= int((n + 1) / 2):\n return True\n else:\n return False", "def distinctadjacentelement(arr, n):\n dict_ = {}\n for elem in arr:\n dict_.update({elem: dict_.get(elem, 0) + 1})\n return max(dict_.values()) <= (n + 1) // 2", "def distinctadjacentelement(arr, n):\n if n == 2 and arr[0] == arr[1]:\n return False\n dict_ = {}\n for elem in arr:\n dict_[elem] = dict_[elem] + 1 if elem in dict_ else 1\n return max(dict_.values()) <= (n + 1) // 2", "def distinctadjacentelement(arr, n):\n arr.sort()\n count = 1\n m = 0\n for i in range(n - 1):\n if arr[i] == arr[i + 1]:\n count += 1\n else:\n m = max(count, m)\n count = 1\n m = max(count, m)\n if n % 2 == 0:\n if m <= n // 2:\n return True\n else:\n return False\n elif m <= (n + 1) // 2:\n return True\n else:\n return False", "def distinctadjacentelement(arr, n):\n k = {}\n kis = []\n for i in arr:\n if i not in k:\n k[i] = 1\n else:\n k[i] += 1\n for i in k:\n kis.append(k[i])\n m = max(kis)\n if m <= (n + 1) // 2:\n return 'YES'", "def distinctadjacentelement(arr, n):\n ele = arr[0]\n f = 0\n for i in range(0, len(arr)):\n if arr[i] == ele:\n f = 1\n else:\n f = -1\n break\n if f == 1:\n return False\n else:\n sz = (n + 1) // 2\n freq = 0\n m = 0\n f = 0\n list1 = []\n for i in range(0, len(arr)):\n if arr[i] not in list1:\n list1.append(arr[i])\n c = arr.count(arr[i])\n if f == 0:\n m = c\n f = 1\n elif c > m:\n m = c\n if m <= sz:\n return True\n else:\n return False", "def distinctadjacentelement(arr, n):\n di = {}\n m = 0\n for i in arr:\n if i not in di:\n di[i] = 1\n else:\n di[i] += 1\n for i in di:\n if m < di[i]:\n m = di[i]\n if m > (n + 1) // 2:\n return 0\n else:\n return 1", "def distinctadjacentelement(arr, n):\n d = dict()\n list1 = []\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n for j in d:\n list1.append(d[j])\n mx = max(list1)\n if mx <= (n + 1) // 2:\n return 'YES'", "def distinctadjacentelement(arr, n):\n m = {}\n for i in arr:\n m[i] = m.get(i, 0) + 1\n if m[i] > (n + 1) // 2:\n return 0\n return 1", "def distinctadjacentelement(arr, n):\n d = {}\n for i in arr:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n count = 0\n for i in d:\n count = max(count, d[i])\n if n % 2 == 0:\n if count <= n // 2:\n return True\n return False\n else:\n if count <= (n + 1) // 2:\n return True\n return False", "def distinctadjacentelement(arr, n):\n dis = {}\n for x in arr:\n if x in dis:\n dis[x] += 1\n else:\n dis[x] = 1\n mx = max([x for x in dis.values()])\n return False if mx > (n + 1) // 2 else True", "def distinctadjacentelement(arr, n):\n size = 10 ** 6 + 1\n count = [0] * size\n for i in range(n):\n count[arr[i]] += 1\n max_val = max(count)\n if n % 2 == 0:\n if max_val <= n // 2:\n return True\n if n % 2 == 1:\n if max_val <= (n + 1) // 2:\n return True\n return False", "def distinctadjacentelement(arr, n):\n mp = {}\n for i in arr:\n if i in mp:\n mp[i] += 1\n else:\n mp[i] = 1\n x = -1\n for i in mp.values():\n x = max(x, i)\n return x <= (n + 1) // 2", "def distinctadjacentelement(arr, n):\n from collections import defaultdict\n d = defaultdict(int)\n maxx = 0\n for i in arr:\n d[i] += 1\n maxx = max(d[i], maxx)\n if maxx > (n + 1) // 2:\n return False\n else:\n return True", "def distinctadjacentelement(a, n):\n m = dict()\n for i in range(n):\n if a[i] in m:\n m[a[i]] += 1\n else:\n m[a[i]] = 1\n mx = 0\n for i in range(n):\n if mx < m[a[i]]:\n mx = m[a[i]]\n if mx > (n + 1) // 2:\n return False\n else:\n return True", "def distinctadjacentelement(arr, n):\n mp = dict()\n for i in range(n):\n if arr[i] in mp:\n mp[arr[i]] += 1\n else:\n mp[arr[i]] = 1\n for i in range(n):\n if mp[arr[i]] > (n + 1) / 2:\n return False\n return True", "def distinctadjacentelement(arr, n):\n freqs = {}\n for el in arr:\n if el in freqs:\n freqs[el] += 1\n else:\n freqs[el] = 1\n max_freq = 0\n for v in freqs.values():\n if v > max_freq:\n max_freq = v\n if max_freq <= (n + 1) // 2:\n return True\n return False", "from collections import Counter\n\ndef distinctadjacentelement(arr, n):\n s = Counter(arr)\n for i in s:\n if s[i] > (n + 1) // 2:\n return False\n return True", "def distinctadjacentelement(arr, n):\n dict1 = {}\n for i in range(n):\n if arr[i] in dict1:\n dict1[arr[i]] += 1\n else:\n dict1[arr[i]] = 1\n val = sorted(dict1.items(), key=lambda x: x[1], reverse=True)[0][1]\n if val <= (n + 1) / 2:\n return True\n else:\n return False"], "starter_code": "def distinctadjacentelement(arr, n):\n", "input_output": {"inputs": ["N = 3, arr[] = {1, 1, 2}", "N = 4, arr[] = {7, 7, 7, 7}"], "outputs": ["YES", " NO"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/distinct-adjacent-element2121/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "distinctadjacentelement", "task_id": "TACO_lite/69", "example": [[], []]} +{"requirement": "Given a sequence of moves for a robot. Check if the sequence is circular or not. \nA sequence of moves is circular if the first and last positions of the robot are the same. A move can be one of the following :\n G - Go one unit\n L - Turn left\n R - Turn right\nExample 1:\nInput: path = \"GLGLGLG\"\nOutput: \"Circular\"\nExplanation: If we start form \n(0,0) in a plane then we will \nback to (0,0) by the end of the \nsequence.\n​Example 2:\nInput: path = \"GGGGL\"\nOutput: \"Not Circular\"\nExplanation: We can't return to \nsame place at the end of the path.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function isCircular() which takes the string path as input and returns \"Circular\" if the path is circular else returns \"Not Circular\".\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ |S| ≤ 10^{5}", "solutions": ["def iscircular(path):\n i = j = 0\n pre = 'r'\n for k in path:\n if k == 'G':\n if pre == 'r':\n j += 1\n elif pre == 'l':\n j -= 1\n elif pre == 'u':\n i -= 1\n elif pre == 'd':\n i += 1\n elif k == 'L':\n if pre == 'r':\n pre = 'u'\n elif pre == 'l':\n pre = 'd'\n elif pre == 'u':\n pre = 'l'\n elif pre == 'd':\n pre = 'r'\n elif k == 'R':\n if pre == 'r':\n pre = 'd'\n elif pre == 'l':\n pre = 'u'\n elif pre == 'u':\n pre = 'r'\n elif pre == 'd':\n pre = 'l'\n if i == 0 and j == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n l = [0, 0]\n dir = 1\n for i in range(len(path)):\n if path[i] == 'G':\n if dir == 1:\n l[0] += 1\n elif dir == 2:\n l[1] += 1\n elif dir == 3:\n l[0] -= 1\n else:\n l[1] -= 1\n elif path[i] == 'L':\n dir += 1\n if dir > 4:\n dir = 1\n else:\n dir -= 1\n if dir == 0:\n dir = 4\n if l == [0, 0]:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n direction = 0\n x = 0\n y = 0\n for i in path:\n if i == 'G':\n if direction == 0:\n y += 1\n elif direction == 1:\n x += 1\n elif direction == 2:\n y -= 1\n elif direction == 3:\n x -= 1\n elif i == 'L':\n if direction == 0:\n direction = 3\n else:\n direction -= 1\n elif i == 'R':\n if direction == 3:\n direction = 0\n else:\n direction += 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(moves):\n (x, y) = (0, 0)\n direction = 'N'\n for move in moves:\n if move == 'G':\n if direction == 'N':\n y += 1\n elif direction == 'S':\n y -= 1\n elif direction == 'E':\n x += 1\n elif direction == 'W':\n x -= 1\n elif move == 'L':\n if direction == 'N':\n direction = 'W'\n elif direction == 'S':\n direction = 'E'\n elif direction == 'E':\n direction = 'N'\n elif direction == 'W':\n direction = 'S'\n elif move == 'R':\n if direction == 'N':\n direction = 'E'\n elif direction == 'S':\n direction = 'W'\n elif direction == 'E':\n direction = 'S'\n elif direction == 'W':\n direction = 'N'\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n x = 0\n y = 0\n angle = 0\n for i in path:\n if i == 'G':\n if angle % 360 == 0:\n x += 1\n elif angle % 360 == 180:\n x -= 1\n elif angle % 360 == 90:\n y += 1\n else:\n y -= 1\n elif i == 'R':\n angle += 90\n elif i == 'L':\n angle += 270\n if x == 0 and y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n dir = 'N'\n y = 0\n x = 0\n for i in path:\n if dir == 'N' and i == 'G':\n y = y + 1\n elif dir == 'E' and i == 'G':\n x = x + 1\n elif dir == 'S' and i == 'G':\n y = y - 1\n elif dir == 'W' and i == 'G':\n x = x - 1\n if dir == 'N' and i == 'L':\n dir = 'W'\n elif dir == 'N' and i == 'R':\n dir = 'E'\n elif dir == 'W' and i == 'L':\n dir = 'S'\n elif dir == 'W' and i == 'R':\n dir = 'N'\n elif dir == 'S' and i == 'L':\n dir = 'E'\n elif dir == 'S' and i == 'R':\n dir = 'W'\n elif dir == 'E' and i == 'L':\n dir = 'N'\n elif dir == 'E' and i == 'R':\n dir = 'S'\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n dir = 0\n xn = 0\n yn = 0\n for i in range(len(path)):\n move = path[i]\n if move == 'R':\n dir = (dir + 1) % 4\n elif move == 'L':\n dir = (4 + dir - 1) % 4\n elif dir == 0:\n yn = yn + 1\n elif dir == 1:\n xn = xn + 1\n elif dir == 2:\n yn = yn - 1\n else:\n xn = xn - 1\n if xn == 0 and yn == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n d = {0: [1, 0], 1: [0, 1], 2: [-1, 0], 3: [0, -1]}\n position = [0, 0]\n direction = 0\n for item in path:\n if item == 'G':\n position[0] += d[direction][0]\n position[1] += d[direction][1]\n if item == 'L':\n direction = (direction - 1) % 4\n if item == 'R':\n direction = (direction + 1) % 4\n return 'Circular' if position == [0, 0] else 'Not Circular'", "def iscircular(path):\n (i, j) = (0, 0)\n d = 0\n for x in path:\n if x == 'G':\n if d % 2 == 0:\n i = i - 1 if d == 2 else i + 1\n else:\n j = j + 1 if d == 1 else j - 1\n elif x == 'L':\n d = (d + 1) % 4\n else:\n d = d - 1 if d != 0 else 3\n if i == 0 and j == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n x_axis = 0\n y_axis = 0\n direction = 0\n for char in path:\n if char == 'L':\n direction += 1\n elif char == 'R':\n direction -= 1\n elif char == 'G':\n if direction % 4 == 1:\n x_axis += 1\n elif direction % 4 == 2:\n y_axis -= 1\n elif direction % 4 == 3:\n x_axis -= 1\n elif direction % 4 == 0:\n y_axis += 1\n if x_axis == 0 and y_axis == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n x = 0\n y = 0\n dir = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n cur = 0\n for i in path:\n if i == 'G':\n (movex, movey) = dir[cur]\n x += movex\n y += movey\n elif i == 'L':\n if cur == 0:\n cur = 3\n else:\n cur -= 1\n elif cur == 3:\n cur = 0\n else:\n cur += 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n direc = ['left', 'up', 'right', 'down']\n index = 1\n start = [1, 1]\n for i in path:\n if i == 'G':\n if direc[index] == 'up':\n start[1] += 1\n elif direc[index] == 'down':\n start[1] -= 1\n elif direc[index] == 'left':\n start[0] -= 1\n else:\n start[0] += 1\n elif i == 'L':\n index -= 1\n index %= 4\n else:\n index += 1\n index %= 4\n return 'Circular' if start[0] == 1 and start[1] == 1 else 'Not Circular'", "def iscircular(path):\n N = 1\n S = 2\n E = 3\n W = 4\n curr = 1\n x = 0\n y = 0\n for i in path:\n if i == 'G':\n if curr == 1:\n y += 1\n elif curr == 2:\n y -= 1\n elif curr == 3:\n x += 1\n else:\n x -= 1\n elif i == 'L':\n if curr == N:\n curr = W\n elif curr == S:\n curr = E\n elif curr == E:\n curr = N\n elif curr == W:\n curr = S\n elif i == 'R':\n if curr == N:\n curr = E\n elif curr == S:\n curr = W\n elif curr == E:\n curr = S\n elif curr == W:\n curr = N\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n (x, y) = (0, 0)\n (dirX, dirY) = (0, 1)\n for p in path:\n if p == 'G':\n (x, y) = (x + dirX, y + dirY)\n elif p == 'L':\n (dirX, dirY) = (-1 * dirY, dirX)\n else:\n (dirX, dirY) = (dirY, -1 * dirX)\n if (x, y) == (0, 0):\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n i = 0\n j = 0\n dir = 'E'\n LL = ['E', 'S', 'W', 'N']\n for c in path:\n if c == 'G':\n j += (dir == 'N') - (dir == 'S')\n i += (dir == 'E') - (dir == 'W')\n if c == 'R':\n dir = LL[(LL.index(dir) + 1) % 4]\n if c == 'L':\n dir = LL[(LL.index(dir) - 1) % 4]\n return 'Circular' if i == 0 and j == 0 else 'Not Circular'", "def iscircular(path):\n x = 0\n y = 0\n dirc = 'R'\n for i in path:\n if i == 'G':\n if dirc == 'R':\n x += 1\n elif dirc == 'U':\n y += 1\n elif dirc == 'L':\n x -= 1\n elif dirc == 'D':\n y -= 1\n elif i == 'L':\n if dirc == 'R':\n dirc = 'U'\n elif dirc == 'U':\n dirc = 'L'\n elif dirc == 'L':\n dirc = 'D'\n elif dirc == 'D':\n dirc = 'R'\n elif i == 'R':\n if dirc == 'R':\n dirc = 'D'\n elif dirc == 'U':\n dirc = 'R'\n elif dirc == 'L':\n dirc = 'U'\n elif dirc == 'D':\n dirc = 'L'\n if x == 0 and y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n position = [0, 0]\n directions = ((0, 1), (1, 0), (0, -1), (-1, 0))\n dir_idx = 0\n for a in path:\n if a == 'G':\n position[0] += directions[dir_idx][0]\n position[1] += directions[dir_idx][1]\n elif a == 'L':\n dir_idx = (dir_idx - 1) % 4\n elif a == 'R':\n dir_idx = (dir_idx + 1) % 4\n if position[0] == 0 and position[1] == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n curr = 0\n (posx, posy) = (0, 0)\n for char in path:\n if char == 'G':\n posx += dirs[curr][0]\n posy += dirs[curr][1]\n elif char == 'L':\n curr -= 1\n if curr == -1:\n curr = 3\n else:\n curr += 1\n if curr == 4:\n curr = 0\n if posx == 0 and posy == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n position = (0, 0)\n current_orientation = 'u'\n for move in path:\n if move == 'G':\n if current_orientation == 'u':\n position = (position[0], position[1] + 1)\n elif current_orientation == 'l':\n position = (position[0] - 1, position[1])\n elif current_orientation == 'r':\n position = (position[0] + 1, position[1])\n elif current_orientation == 'd':\n position = (position[0], position[1] - 1)\n if move == 'L':\n if current_orientation == 'u':\n current_orientation = 'l'\n elif current_orientation == 'l':\n current_orientation = 'd'\n elif current_orientation == 'r':\n current_orientation = 'u'\n elif current_orientation == 'd':\n current_orientation = 'r'\n if move == 'R':\n if current_orientation == 'u':\n current_orientation = 'r'\n elif current_orientation == 'l':\n current_orientation = 'u'\n elif current_orientation == 'r':\n current_orientation = 'd'\n elif current_orientation == 'd':\n current_orientation = 'l'\n if position == (0, 0):\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n x = 0\n y = 0\n dir = 0\n for i in range(len(path)):\n if path[i] == 'L':\n dir = (4 + dir - 1) % 4\n elif path[i] == 'R':\n dir = (dir + 1) % 4\n elif dir == 0:\n y += 1\n elif dir == 1:\n x += 1\n elif dir == 2:\n y -= 1\n else:\n x -= 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n dirX = [1, 0, -1, 0]\n dirY = [0, 1, 0, -1]\n dir = 0\n x = 0\n y = 0\n for i in path:\n if i == 'G':\n x += dirX[dir]\n y += dirY[dir]\n elif i == 'L':\n dir = (dir - 1) % 4\n else:\n dir = (dir + 1) % 4\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n directions = {'E': ['N', 'S'], 'W': ['S', 'N'], 'N': ['W', 'E'], 'S': ['E', 'W']}\n move = {'E': [1, 0], 'W': [-1, 0], 'N': [0, 1], 'S': [0, -1]}\n (X, Y) = (0, 0)\n towards = 'E'\n for p in path:\n if p == 'G':\n X += move[towards][0]\n Y += move[towards][1]\n else:\n towards = directions[towards][0] if p == 'L' else directions[towards][1]\n return 'Circular' if not X and (not Y) else 'Not Circular'", "def iscircular(path):\n (N, E, S, W) = (0, 1, 2, 3)\n dire = N\n (x, y) = (0, 0)\n n = len(path)\n for i in range(n):\n move = path[i]\n if move == 'R':\n dire = (dire + 1) % 4\n elif move == 'L':\n dire = (4 + dire - 1) % 4\n elif dire == N:\n y += 1\n elif dire == S:\n y -= 1\n elif dire == E:\n x += 1\n else:\n x -= 1\n if x == 0 and y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n (dirx, diry) = (0, 1)\n (x, y) = (0, 0)\n for i in path:\n if i == 'G':\n (x, y) = (x + dirx, y + diry)\n elif i == 'L':\n (dirx, diry) = (-1 * diry, dirx)\n else:\n (dirx, diry) = (diry, -1 * dirx)\n if (x, y) == (0, 0):\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n face_up = [0, 1]\n face_d = [0, -1]\n face_l = [-1, 0]\n face_r = [1, 0]\n n = len(path) // 4 + 1\n dir = [face_up, face_l, face_d, face_r] * n\n position = [0, 0]\n current_pos = position\n ind = 0\n for i in path:\n if i == 'L':\n ind = ind + 1\n elif i == 'R':\n ind = ind - 1\n else:\n current_pos = [current_pos[0] + dir[ind][0], current_pos[1] + dir[ind][1]]\n if current_pos == position:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n facing = 'N'\n cord = [0, 0]\n for i in path:\n if i == 'G':\n if facing == 'N':\n cord[1] += 1\n elif facing == 'S':\n cord[1] -= 1\n elif facing == 'E':\n cord[0] += 1\n else:\n cord[0] -= 1\n elif i == 'L':\n if facing == 'N':\n facing = 'W'\n elif facing == 'S':\n facing = 'E'\n elif facing == 'E':\n facing = 'N'\n else:\n facing = 'S'\n elif facing == 'N':\n facing = 'E'\n elif facing == 'S':\n facing = 'W'\n elif facing == 'E':\n facing = 'S'\n else:\n facing = 'N'\n if cord[0] == cord[1] == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n (dx, dy) = (0, 1)\n (x, y) = (0, 0)\n for d in path:\n if d == 'G':\n (x, y) = (x + dx, y + dy)\n elif d == 'L':\n (dx, dy) = (-1 * dy, dx)\n else:\n (dx, dy) = (dy, -1 * dx)\n if (x, y) == (0, 0):\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n (x, y) = (0, 0)\n currDir = 'N'\n for c in path:\n if c == 'G':\n if currDir == 'N':\n x += 1\n elif currDir == 'W':\n y -= 1\n elif currDir == 'E':\n y += 1\n else:\n x -= 1\n elif c == 'L':\n if currDir == 'N':\n currDir = 'W'\n elif currDir == 'W':\n currDir = 'S'\n elif currDir == 'E':\n currDir = 'N'\n else:\n currDir = 'E'\n elif currDir == 'N':\n currDir = 'E'\n elif currDir == 'W':\n currDir = 'N'\n elif currDir == 'E':\n currDir = 'S'\n else:\n currDir = 'W'\n return 'Circular' if x == 0 and y == 0 else 'Not Circular'", "def iscircular(path):\n dir_l = ['y+', 'x+', 'y-', 'x-']\n d = {'y+': [0, 1], 'x+': [1, 0], 'y-': [0, -1], 'x-': [-1, 0]}\n curr_dir = 'y+'\n curr_co = [0, 0]\n for i in path:\n if i == 'G':\n (add_x, add_y) = d[curr_dir]\n curr_co = [curr_co[0] + add_x, curr_co[1] + add_y]\n else:\n curr_ind = dir_l.index(curr_dir)\n if i == 'R':\n if curr_ind + 1 == 4:\n curr_ind = 0\n else:\n curr_ind += 1\n elif curr_ind - 1 == -1:\n curr_ind = 3\n else:\n curr_ind -= 1\n curr_dir = dir_l[curr_ind]\n if curr_co == [0, 0]:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n up = 0\n down = 0\n left = 0\n right = 0\n moving = 0\n for move in path:\n if move == 'G':\n if moving == 0:\n right = right + 1\n elif moving == 1:\n up = up + 1\n elif moving == 2:\n left = left + 1\n else:\n down = down + 1\n elif move == 'R':\n moving = (moving + 1) % 4\n elif moving == 0:\n moving = 3\n else:\n moving = moving - 1\n if up - down + left - right == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n (x, y) = (0, 0)\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n d = 0\n for i in path:\n if i == 'G':\n x += directions[d % 4][0]\n y += directions[d % 4][1]\n elif i == 'L':\n d -= 1\n else:\n d += 1\n return 'Circular' if (x, y) == (0, 0) else 'Not Circular'", "N = 0\nE = 1\nS = 2\nW = 3\n\ndef case_E(x, y):\n return (x + 1, y)\n\ndef case_W(x, y):\n return (x - 1, y)\n\ndef case_N(x, y):\n return (x, y + 1)\n\ndef case_S(x, y):\n return (x, y - 1)\noptions = {E: case_E, W: case_W, N: case_N, S: case_S}\n\ndef iscircular(path):\n x = y = 0\n dir = N\n for i in range(len(path)):\n if path[i] == 'L':\n dir = (dir + 4 - 1) % 4\n elif path[i] == 'R':\n dir = (dir + 1) % 4\n else:\n (x, y) = options[dir](x, y)\n if x == 0 and y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n (curr_loc, first_loc) = ([0, 0], [0, 0])\n curr_dir = 'N'\n for move in path:\n if move == 'G':\n if curr_dir == 'N':\n curr_loc[1] += 1\n elif curr_dir == 'S':\n curr_loc[1] -= 1\n elif curr_dir == 'E':\n curr_loc[0] += 1\n elif curr_dir == 'W':\n curr_loc[0] -= 1\n elif move == 'L':\n if curr_dir == 'N':\n curr_dir = 'W'\n elif curr_dir == 'S':\n curr_dir = 'E'\n elif curr_dir == 'E':\n curr_dir = 'N'\n elif curr_dir == 'W':\n curr_dir = 'S'\n elif move == 'R':\n if curr_dir == 'N':\n curr_dir = 'E'\n elif curr_dir == 'S':\n curr_dir = 'W'\n elif curr_dir == 'E':\n curr_dir = 'S'\n elif curr_dir == 'W':\n curr_dir = 'N'\n if curr_loc == first_loc:\n return 'Circular'\n else:\n return 'Not Circular'", "from collections import namedtuple\nPoint = namedtuple('Point', 'x y')\n\ndef turn(currentDirection, dest):\n sign = 1 if dest == 'L' else -1\n if currentDirection == (1, 0):\n return Point(0, sign * 1)\n elif currentDirection == (0, 1):\n return Point(-1 * sign, 0)\n elif currentDirection == (-1, 0):\n return Point(0, -1 * sign)\n elif currentDirection == (0, -1):\n return Point(1 * sign, 0)\n else:\n return currentDirection\n\ndef iscircular(path):\n p = Point(0, 0)\n direction = Point(1, 0)\n for e in path:\n if e == 'G':\n p = Point(p.x + direction.x, p.y + direction.y)\n elif e == 'L':\n direction = turn(direction, 'L')\n elif e == 'R':\n direction = turn(direction, 'R')\n return 'Circular' if p == (0, 0) else 'Not Circular'", "def iscircular(path):\n (x, y) = (0, 0)\n directions = {'N': (0, 1), 'S': (0, -1), 'E': (1, 0), 'W': (-1, 0)}\n pos = 'N'\n n = len(path)\n for i in range(n):\n if path[i] == 'G':\n x = x + directions[pos][0]\n y = y + directions[pos][1]\n elif path[i] == 'L':\n if pos == 'N':\n pos = 'W'\n elif pos == 'W':\n pos = 'S'\n elif pos == 'S':\n pos = 'E'\n elif pos == 'E':\n pos = 'N'\n elif path[i] == 'R':\n if pos == 'N':\n pos = 'E'\n elif pos == 'E':\n pos = 'S'\n elif pos == 'S':\n pos = 'W'\n elif pos == 'W':\n pos = 'N'\n return 'Circular' if x == 0 and y == 0 else 'Not Circular'", "def iscircular(path):\n N = 1\n E = 2\n s = 3\n w = 4\n x = 0\n y = 0\n curr_dir = 1\n for i in path:\n if i == 'G':\n if curr_dir == 1:\n y += 1\n elif curr_dir == 2:\n x += 1\n elif curr_dir == 3:\n y -= 1\n else:\n x -= 1\n elif i == 'L':\n if curr_dir == 1:\n curr_dir = 4\n elif curr_dir == 2:\n curr_dir = 1\n elif curr_dir == 3:\n curr_dir = 2\n else:\n curr_dir = 3\n elif curr_dir == 1:\n curr_dir = 2\n elif curr_dir == 2:\n curr_dir = 3\n elif curr_dir == 3:\n curr_dir = 4\n else:\n curr_dir = 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n pos = [0, 0]\n ret = [0, 0]\n dirleft = {'l': 'd', 'd': 'r', 'r': 'u', 'u': 'l'}\n dirright = {'l': 'u', 'd': 'l', 'r': 'd', 'u': 'r'}\n move = 'r'\n for i in range(len(path)):\n if path[i] == 'G':\n if move == 'r':\n pos[1] += 1\n elif move == 'l':\n pos[1] -= 1\n elif move == 'u':\n pos[0] -= 1\n elif move == 'd':\n pos[0] += 1\n elif path[i] == 'L':\n move = dirleft[move]\n elif path[i] == 'R':\n move = dirright[move]\n if pos == ret:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n x = y = 0\n (dx, dy) = (1, 0)\n l = len(path)\n for i in range(l):\n if path[i] == 'L':\n if dx == 1:\n dx = 0\n dy = 1\n elif dy == 1:\n dx = -1\n dy = 0\n elif dy == -1:\n dx = 1\n dy = 0\n else:\n dx = 0\n dy = -1\n continue\n if path[i] == 'R':\n if dx == 1:\n dx = 0\n dy = -1\n elif dy == 1:\n dx = 1\n dy = 0\n elif dy == -1:\n dx = -1\n dy = 0\n else:\n dx = 0\n dy = 1\n continue\n x += dx\n y += dy\n if x == 0 and y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n (x, y, direc) = (0, 0, 0)\n for move in path:\n if move == 'L':\n direc = (4 + direc - 1) % 4\n if move == 'R':\n direc = (direc + 1) % 4\n if move == 'G':\n if direc == 0:\n y += 1\n elif direc == 1:\n x += 1\n elif direc == 2:\n y -= 1\n else:\n x -= 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n (x, y) = (0, 0)\n up = (0, 1)\n down = (0, -1)\n left = (-1, 0)\n right = (1, 0)\n left_turn = [down, left, up, right]\n right_turn = [up, left, down, right]\n current_direction = left\n for i in range(len(path)):\n if path[i] == 'G':\n x += current_direction[0]\n y += current_direction[1]\n else:\n if path[i] == 'L':\n turn = left_turn\n if path[i] == 'R':\n turn = right_turn\n index = turn.index(current_direction)\n index = 0 if index == 3 else index + 1\n current_direction = turn[index]\n return 'Circular' if (x, y) == (0, 0) else 'Not Circular'", "def iscircular(path):\n POSSIBLE_MOVEMENTS = {'N': [0, 1], 'S': [0, -1], 'E': [1, 0], 'W': [-1, 0]}\n POSSIBLE_DIRECTION_CHANGES = {'N': {'L': 'W', 'R': 'E'}, 'S': {'L': 'E', 'R': 'W'}, 'E': {'L': 'N', 'R': 'S'}, 'W': {'L': 'S', 'R': 'N'}}\n current_position = [0, 0]\n current_direction = 'N'\n for i in range(0, len(path)):\n if path[i] == 'G':\n current_position = self.addArrays(current_position, POSSIBLE_MOVEMENTS[current_direction])\n else:\n current_step = path[i]\n current_options = POSSIBLE_DIRECTION_CHANGES[current_direction]\n current_direction = current_options[current_step]\n if current_position == [0, 0]:\n return 'Circular'\n return 'Not Circular'\n\ndef addArrays(arr1, arr2):\n array = [arr1[0] + arr2[0], arr1[1] + arr2[1]]\n return array", "def iscircular(path):\n x_count = 0\n y_count = 0\n direction = 'x'\n for char in path:\n if char == 'G' and direction == 'x':\n x_count += 1\n elif char == 'G' and direction == '-x':\n x_count -= 1\n elif char == 'G' and direction == 'y':\n y_count += 1\n elif char == 'G' and direction == '-y':\n y_count -= 1\n if char == 'L' and direction == 'x':\n direction = 'y'\n elif char == 'L' and direction == 'y':\n direction = '-x'\n elif char == 'L' and direction == '-x':\n direction = '-y'\n elif char == 'L' and direction == '-y':\n direction = 'x'\n elif char == 'R' and direction == 'x':\n direction = '-y'\n elif char == 'R' and direction == 'y':\n direction = 'x'\n elif char == 'R' and direction == '-x':\n direction = 'y'\n elif char == 'R' and direction == '-y':\n direction = '-x'\n if x_count == 0 and y_count == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n state_map = {'x+ve': (1, 0), 'x-ve': (-1, 0), 'y+ve': (0, 1), 'y-ve': (0, -1)}\n direct_map = {'x+ve': ('y+ve', 'y-ve'), 'x-ve': ('y-ve', 'y+ve'), 'y+ve': ('x-ve', 'x+ve'), 'y-ve': ('x+ve', 'x-ve')}\n state = ('x+ve', (0, 0))\n for char in path:\n (direct, cord) = state\n if char == 'G':\n (dx, dy) = state_map[direct]\n new_cord = (cord[0] + dx, cord[1] + dy)\n new_state = (direct, new_cord)\n else:\n if char == 'L':\n new_direct = direct_map[direct][0]\n else:\n new_direct = direct_map[direct][1]\n new_state = (new_direct, cord)\n state = new_state\n return 'Circular' if state[1] == (0, 0) else 'Not Circular'", "def iscircular(path):\n x = 0\n y = 0\n directions = ['N', 'E', 'S', 'W']\n index = 0\n for i in range(len(path)):\n move = path[i]\n if move == 'R':\n index = (index + 1) % 4\n elif move == 'L':\n index = (4 + index - 1) % 4\n else:\n d = directions[index]\n if d == 'N':\n y += 1\n elif d == 'E':\n x += 1\n elif d == 'S':\n y -= 1\n else:\n x -= 1\n return 'Circular' if x == 0 and y == 0 else 'Not Circular'", "def iscircular(path):\n d = [[0, 1], [-1, 0], [0, -1], [1, 0]]\n dir = 0\n x = y = 0\n for p in path:\n if p == 'L':\n dir = (dir + 1) % 4\n elif p == 'R':\n dir = (dir + 3) % 4\n else:\n (x, y) = (x + d[dir][0], y + d[dir][1])\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n i = 0\n x = 0\n y = 0\n d = 0\n while i < len(path):\n if path[i] == 'L':\n d -= 1\n i += 1\n elif path[i] == 'R':\n d += 1\n i += 1\n elif path[i] == 'G':\n d = d % 4\n if d == -1 or d == 3:\n x -= 1\n elif d == 1 or d == -3:\n x += 1\n elif d == -2 or d == 2:\n y -= 1\n elif d == 0:\n y += 1\n i += 1\n if x == 0 and y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n directions = {'0': 0, '90': 0, '180': 0, '270': 0}\n heading = 0\n for step in path:\n if step == 'G':\n directions[str(heading)] = directions[str(heading)] + 1\n elif step == 'L':\n heading = (heading + 90) % 360\n elif step == 'R':\n heading = (heading - 90) % 360\n if heading < 0:\n heading = 360 + heading\n if directions['0'] - directions['180'] + (directions['90'] - directions['270']) == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n final_pos = 0\n (x, y) = (0, 0)\n head = 1\n for i in path:\n if i == 'L' and head == 1:\n head = 2\n elif i == 'L' and head == 2:\n head = 3\n elif i == 'L' and head == 3:\n head = 4\n elif i == 'L' and head == 4:\n head = 1\n elif i == 'R' and head == 1:\n head = 4\n elif i == 'R' and head == 2:\n head = 1\n elif i == 'R' and head == 3:\n head = 2\n elif i == 'R' and head == 4:\n head = 3\n elif head == 1:\n x += 1\n elif head == 2:\n y += 1\n elif head == 3:\n x -= 1\n else:\n y -= 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n\n def walk(pathUnit, walkRecord, pointer):\n if pointer == 3 and pathUnit == 'L':\n pointer = 0\n elif pointer == 0 and pathUnit == 'R':\n pointer = 3\n elif pathUnit == 'L':\n pointer += 1\n elif pathUnit == 'R':\n pointer -= 1\n if pathUnit == 'G':\n if pointer == 0:\n walkRecord[0] += 1\n if pointer == 1:\n walkRecord[1] += 1\n if pointer == 2:\n walkRecord[2] += 1\n if pointer == 3:\n walkRecord[3] += 1\n return (walkRecord, pointer)\n walkRecord = [0] * 4\n pointer = 0\n for pathUnit in path:\n (walkRecord, pointer) = walk(pathUnit, walkRecord, pointer)\n if walkRecord[0] + walkRecord[1] == walkRecord[2] + walkRecord[3]:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n (n, e, s, w) = (0, 1, 2, 3)\n (x, y) = (0, 0)\n d = n\n for i in path:\n if i == 'R':\n d = (d + 1) % 4\n elif i == 'L':\n d = (4 + d - 1) % 4\n elif d == n:\n y += 1\n elif d == e:\n x += 1\n elif d == s:\n y -= 1\n else:\n x -= 1\n if x == 0 and y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n direction = 'right'\n init_x = init_y = 0\n for move in path:\n if move == 'G':\n if direction == 'right':\n init_x += 1\n elif direction == 'left':\n init_x -= 1\n elif direction == 'up':\n init_y += 1\n elif direction == 'down':\n init_y -= 1\n elif move == 'L':\n if direction == 'right':\n direction = 'up'\n elif direction == 'up':\n direction = 'left'\n elif direction == 'left':\n direction = 'down'\n elif direction == 'down':\n direction = 'right'\n elif move == 'R':\n if direction == 'right':\n direction = 'down'\n elif direction == 'down':\n direction = 'left'\n elif direction == 'left':\n direction = 'up'\n elif direction == 'up':\n direction = 'right'\n if init_x == init_y and init_x == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n direction = 'n'\n n = 0\n e = 0\n s = 0\n w = 0\n for p in path:\n if p == 'R':\n if direction == 'n':\n direction = 'e'\n elif direction == 'e':\n direction = 's'\n elif direction == 's':\n direction = 'w'\n else:\n direction = 'n'\n elif p == 'L':\n if direction == 'n':\n direction = 'w'\n elif direction == 'e':\n direction = 'n'\n elif direction == 's':\n direction = 'e'\n else:\n direction = 's'\n elif direction == 'n':\n n += 1\n if s > 0:\n n -= 1\n s -= 1\n elif direction == 'e':\n e += 1\n if w > 0:\n e -= 1\n w -= 1\n elif direction == 's':\n s += 1\n if n > 0:\n n -= 1\n s -= 1\n else:\n w += 1\n if e > 0:\n e -= 1\n w -= 1\n if n - s == 0 and e - w == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n x = 0\n y = 0\n face = 0\n for chars in path:\n if chars == 'G':\n if face == 0:\n x += 1\n elif face == 1:\n y += 1\n elif face == 2:\n x -= 1\n else:\n y -= 1\n elif chars == 'L':\n face += 1\n face %= 4\n elif chars == 'R':\n face -= 1\n if face < 0:\n face = 3\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n if not 1 <= len(path) <= pow(10, 5):\n return 'Not Circular'\n position = [0, 0]\n direction = 'North'\n for s in path:\n if s == 'L':\n if direction == 'North':\n direction = 'West'\n elif direction == 'West':\n direction = 'South'\n elif direction == 'South':\n direction = 'East'\n elif direction == 'East':\n direction = 'North'\n if s == 'R':\n if direction == 'North':\n direction = 'East'\n elif direction == 'East':\n direction = 'South'\n elif direction == 'South':\n direction = 'West'\n elif direction == 'West':\n direction = 'North'\n if s == 'G':\n if direction == 'North':\n position = [a + b for (a, b) in zip(position, [0, 1])]\n elif direction == 'East':\n position = [a + b for (a, b) in zip(position, [1, 0])]\n elif direction == 'South':\n position = [a + b for (a, b) in zip(position, [0, -1])]\n elif direction == 'West':\n position = [a + b for (a, b) in zip(position, [-1, 0])]\n if position == [0, 0]:\n return 'Circular'\n else:\n return 'Not Circular'", "def __init__():\n self.x = 0\n self.y = 0\n self.direction = [0, 1]\n\ndef iscircular(path):\n for c in path:\n if c == 'G':\n self.x += self.direction[0]\n self.y += self.direction[1]\n if c == 'L':\n self.direction = [-1 * self.direction[1], self.direction[0] * 1]\n if c == 'R':\n self.direction = [1 * self.direction[1], self.direction[0] * -1]\n if self.x == 0 and self.y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n N = 0\n E = 1\n S = 2\n W = 3\n x = 0\n y = 0\n direction = 0\n for move in list(path):\n if move == 'L':\n direction = (direction + 1) % 4\n elif move == 'R':\n direction = (4 + direction - 1) % 4\n else:\n if direction == 0:\n y += 1\n if direction == 1:\n x += 1\n if direction == 2:\n y -= 1\n if direction == 3:\n x -= 1\n return 'Circular' if x == 0 and y == 0 else 'Not Circular'", "def iscircular(path):\n dirn = 'E'\n (x, y) = (0, 0)\n for i in range(len(path)):\n if path[i] == 'G':\n if dirn == 'E':\n y += 1\n elif dirn == 'W':\n y -= 1\n elif dirn == 'N':\n x -= 1\n else:\n x += 1\n elif path[i] == 'L':\n if dirn == 'E':\n dirn = 'N'\n elif dirn == 'W':\n dirn = 'S'\n elif dirn == 'N':\n dirn = 'W'\n else:\n dirn = 'E'\n elif dirn == 'E':\n dirn = 'S'\n elif dirn == 'W':\n dirn = 'N'\n elif dirn == 'N':\n dirn = 'E'\n else:\n dirn = 'W'\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n loc = [0, 0]\n dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n current_dir = 0 % 4\n for p in path:\n if p == 'G':\n loc[0] += dirs[current_dir][0]\n loc[1] += dirs[current_dir][1]\n elif p == 'L':\n current_dir = (current_dir - 1) % 4\n else:\n current_dir = (current_dir + 1) % 4\n return 'Circular' if loc == [0, 0] else 'Not Circular'", "def iscircular(path):\n N = 0\n E = 1\n S = 2\n W = 3\n x = 0\n y = 0\n dir = N\n for item in path:\n if item == 'L':\n dir = (4 + dir - 1) % 4\n elif item == 'R':\n dir = (dir + 1) % 4\n elif dir == N:\n y += 1\n elif dir == E:\n x += 1\n elif dir == S:\n y -= 1\n else:\n x -= 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n x = 0\n y = 0\n cp = 4\n for ch in path:\n if ch == 'L':\n cp += 1\n elif ch == 'R':\n cp -= 1\n elif cp % 4 == 0:\n x += 1\n elif cp % 4 == 1:\n y += 1\n elif cp % 4 == 2:\n x -= 1\n elif cp % 4 == 3:\n y -= 1\n if x == y and x == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(moves):\n x = y = 0\n present_direction = 0\n for move in moves:\n if move == 'L':\n present_direction = (4 + present_direction - 1) % 4\n elif move == 'R':\n present_direction = (present_direction + 1) % 4\n elif present_direction == 0:\n y += 1\n elif present_direction == 2:\n y -= 1\n elif present_direction == 3:\n x += 1\n else:\n x -= 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n flag = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n cur = 1\n init = (0, 0)\n pos = (0, 0)\n for c in path:\n if c == 'G':\n pos = tuple(map(lambda a, b: a + b, pos, flag[cur]))\n elif c == 'L':\n cur = (3 + cur) % 4\n else:\n cur = (1 + cur) % 4\n if pos == init:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n (x, y) = (0, 0)\n currentDirection = 'N'\n turn = {'NL': 'W', 'NR': 'E', 'EL': 'N', 'ER': 'S', 'SL': 'E', 'SR': 'W', 'WL': 'S', 'WR': 'N'}\n for i in path:\n if i == 'G':\n if currentDirection == 'N':\n x += 1\n elif currentDirection == 'S':\n x -= 1\n elif currentDirection == 'E':\n y += 1\n elif currentDirection == 'W':\n y -= 1\n else:\n currentDirection = turn[currentDirection + i]\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(list_of_commands):\n compass = 0\n orientation = 'N'\n x = 0\n y = 0\n for command in list_of_commands:\n if command == 'G':\n if orientation == 'N':\n y += 1\n if orientation == 'S':\n y -= 1\n if orientation == 'E':\n x += 1\n if orientation == 'W':\n x -= 1\n if command == 'L':\n if compass == 0:\n compass = 3\n else:\n compass -= 1\n if command == 'R':\n if compass == 3:\n compass = 0\n else:\n compass += 1\n if compass == 0:\n orientation = 'N'\n if compass == 1:\n orientation = 'E'\n if compass == 2:\n orientation = 'S'\n if compass == 3:\n orientation = 'W'\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n dir = 'east'\n x = 0\n y = 0\n for i in path:\n if i == 'L':\n if dir == 'east':\n dir = ''\n dir = 'north'\n elif dir == 'north':\n dir = ''\n dir = 'west'\n elif dir == 'west':\n dir = ''\n dir = 'south'\n elif dir == 'south':\n dir = ''\n dir = 'east'\n elif i == 'R':\n if dir == 'east':\n dir = ''\n dir = 'south'\n elif dir == 'south':\n dir = ''\n dir = 'west'\n elif dir == 'west':\n dir = ''\n dir = 'north'\n elif dir == 'north':\n dir = ''\n dir = 'east'\n elif i == 'G':\n if dir == 'east':\n x = x + 1\n elif dir == 'west':\n x = x - 1\n elif dir == 'north':\n y = y + 1\n elif dir == 'south':\n y = y - 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n start = [0, 0]\n modify = 'X+'\n nextmodify = {('X+', 'L'): 'Y+', ('X+', 'R'): 'Y-', ('X-', 'L'): 'Y-', ('X-', 'R'): 'Y+', ('Y+', 'L'): 'X-', ('Y+', 'R'): 'X+', ('Y-', 'L'): 'X+', ('Y-', 'R'): 'X-'}\n for move in path:\n if move == 'G':\n if modify == 'X+':\n start[0] = start[0] + 1\n elif modify == 'X-':\n start[0] = start[0] - 1\n elif modify == 'Y+':\n start[1] = start[1] + 1\n elif modify == 'Y-':\n start[1] = start[1] - 1\n else:\n modify = nextmodify[modify, move]\n return 'Circular' if start[0] == 0 and start[1] == 0 else 'Not Circular'"], "starter_code": "def iscircular(path):\n", "input_output": {"inputs": ["path = \"GLGLGLG\"", "path = \"GGGGL\""], "outputs": ["\"Circular\"", "\"Not Circular\""]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/does-robot-moves-circular0414/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "iscircular", "task_id": "TACO_lite/44", "example": [[["GLGLGLG"], ["GGGGL"]], ["Circular", "Not Circular"]]} +{"requirement": "Implement a function called makeAcronym that returns the first letters of each word in a passed in string.\n\nMake sure the letters returned are uppercase.\n\nIf the value passed in is not a string return 'Not a string'.\n\nIf the value passed in is a string which contains characters other than spaces and alphabet letters, return 'Not letters'.\n\nIf the string is empty, just return the string itself: \"\".\n\n**EXAMPLES:**\n```\n'Hello codewarrior' -> 'HC'\n\n'a42' -> 'Not letters'\n\n42 -> 'Not a string'\n\n[2,12] -> 'Not a string'\n\n{name: 'Abraham'} -> 'Not a string'\n```", "solutions": ["def make_acronym(phrase):\n try:\n return ''.join((word[0].upper() if word.isalpha() else 0 for word in phrase.split()))\n except AttributeError:\n return 'Not a string'\n except TypeError:\n return 'Not letters'", "from operator import itemgetter\n\ndef make_acronym(phrase):\n if type(phrase) != str:\n return 'Not a string'\n if not all((c.isalpha() or c.isspace() for c in phrase)):\n return 'Not letters'\n return ''.join(map(itemgetter(0), phrase.split())).upper()", "def make_acronym(phrase):\n if not isinstance(phrase, str):\n return 'Not a string'\n arr = phrase.split()\n return ''.join((a[0] for a in arr)).upper() if all(map(str.isalpha, arr)) else 'Not letters'", "def make_acronym(phrase):\n if not isinstance(phrase, str):\n return 'Not a string'\n elif phrase == '':\n return ''\n elif not phrase.replace(' ', '').isalpha():\n return 'Not letters'\n else:\n return ''.join((word[0].upper() for word in phrase.split(' ')))", "def make_acronym(phrase):\n if isinstance(phrase, str):\n words = phrase.split()\n if all((x.isalpha() or x.isspace() for x in words)):\n return ''.join((x[0] for x in words)).upper()\n else:\n return 'Not letters'\n return 'Not a string'", "from string import ascii_letters\n\ndef make_acronym(phrase):\n acronym = ''\n if isinstance(phrase, str):\n words = phrase.split()\n for word in words:\n for char in word:\n if char in ascii_letters:\n pass\n else:\n return 'Not letters'\n acronym += word[0].upper()\n return acronym\n return 'Not a string'", "def make_acronym(phrase):\n if not isinstance(phrase, str):\n return 'Not a string'\n words = phrase.split()\n if not all((i.isalpha() for i in words)):\n return 'Not letters'\n return ''.join((p[0] for p in words)).upper()", "def make_acronym(phrase):\n import re\n if type(phrase) is not str:\n return 'Not a string'\n if re.search('[^A-Za-z\\\\s]', phrase):\n return 'Not letters'\n acronym = ''\n for x in phrase.split():\n acronym += x[0]\n return acronym.upper()"], "starter_code": "def make_acronym(phrase):\n", "input_output": {"fn_name": "make_acronym", "inputs": [["My aunt sally"], ["Please excuse my dear aunt Sally"], ["How much wood would a woodchuck chuck if a woodchuck could chuck wood"], ["Unique New York"], ["a42"], ["1111"], [64], [[]], [{}], [""]], "outputs": [["MAS"], ["PEMDAS"], ["HMWWAWCIAWCCW"], ["UNY"], ["Not letters"], ["Not letters"], ["Not a string"], ["Not a string"], ["Not a string"], [""]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/557efeb04effce569d000022", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "make_acronym", "task_id": "TACO_lite/5", "example": [[], []]} +{"requirement": "Given three integers A, B, N. Your task is to print the number of numbers between A and B including them, which have N-divisors. A number is called N-divisor if it has total N divisors including 1 and itself.\n \nExample 1:\nInput:\nA = 1\nB = 7\nN = 2\nOutput:\n4\nExplanation:\n2,3,5,7 have 2-divisors\nExample 2:\nInput:\nA = 1\nB = 25\nN = 3\nOutput:\n3\nExplanation:\n4,9,25 are the numbers\nhaving 3-divisors\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function count() which takes integer A, B and N as input parameters and returns an integer, the number of N-divisor number in between A and B inclusive.\n \nExpected Time Complexity: O((B-A) sqrt (B))\nExpected Space Complexity: O(1)\n \nConstraints:\n1<=A<=B<=10^{4}\n1 <= N <= 16", "solutions": ["def count(A, B, N):\n ans = 0\n for x in range(A, B + 1):\n count = 0\n i = 1\n while i * i <= x:\n if x % i == 0:\n count += 1\n if x // i != i:\n count += 1\n if count > N:\n break\n i += 1\n if count == N:\n ans += 1\n return ans", "from math import *\n\ndef count(A, B, N):\n count = 0\n sol = Solution()\n for i in range(A, B + 1):\n if N == sol.counter(i):\n count += 1\n return count\n\ndef counter(N):\n count = 0\n for i in range(1, int(sqrt(N)) + 1):\n if N % i == 0:\n if N % (N // i) == 0 and N // i != i:\n count += 1\n count += 1\n return count"], "starter_code": "def count(A,B,N):\n", "input_output": {"inputs": ["A = 1\nB = 7\nN = 2", "A = 1\nB = 25\nN = 3"], "outputs": ["4", "3"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/n-divisors5123/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O((B-A) sqrt (B))", "entry_point": "count", "task_id": "TACO_lite/90", "example": [[[1, 7, 2], [1, 25, 3]], ["4", "3"]]} +{"requirement": "A family of kookaburras are in my backyard.\n\nI can't see them all, but I can hear them!\n\n# How many kookaburras are there?\n\n\n\n\n## Hint \n\nThe trick to counting kookaburras is to listen carefully\n\n* The males go ```HaHaHa```...\n\n* The females go ```hahaha```...\n\n* And they always alternate male/female\n\n\n\n^ Kata Note : No validation is necessary; only valid input will be passed :-)", "solutions": ["import re\n\ndef kooka_counter(laughing):\n return len(re.findall('(ha)+|(Ha)+', laughing))", "def kooka_counter(laughing):\n return 0 if laughing == '' else laughing.count('Hah') + laughing.count('haH') + 1", "def kooka_counter(laughing):\n return laughing.count('Haha') + laughing.count('haHa') + bool(laughing)", "import re\n\ndef kooka_counter(stri):\n stri = re.sub('H+', 'H', stri.replace('a', ''))\n stri = re.sub('h+', 'h', stri.replace('a', ''))\n return len(stri)", "import re\npattern = re.compile('(Ha)+|(ha)+')\n\ndef kooka_counter(laughing):\n return len(pattern.findall(laughing))", "def kooka_counter(laughing):\n if len(laughing) == 0:\n return 0\n return laughing.count('haHa') + laughing.count('Haha') + 1", "def kooka_counter(laugh):\n count = 0\n while laugh:\n pat = laugh[:2]\n laugh = laugh.lstrip(pat)\n count += 1\n return count", "def kooka_counter(laughing):\n if len(laughing) == 0:\n return 0\n kooks = 1\n current = laughing[0]\n for i in range(2, len(laughing), 2):\n if laughing[i] != current:\n current = current.swapcase()\n kooks += 1\n return kooks"], "starter_code": "def kooka_counter(laughing):\n", "input_output": {"fn_name": "kooka_counter", "inputs": [[""], ["hahahahaha"], ["hahahahahaHaHaHa"], ["HaHaHahahaHaHa"], ["hahahahahahahaHaHa"]], "outputs": [[0], [1], [2], [3], [2]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms"], "name": null, "source": "codewars", "tags": ["String algorithms"], "skill_types": [], "url": "https://www.codewars.com/kata/58e8cad9fd89ea0c6c000258", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "kooka_counter", "task_id": "TACO_lite/108", "example": [[], []]} +{"requirement": "# Solve For X\n\nYou will be given an equation as a string and you will need to [solve for X](https://www.mathplacementreview.com/algebra/basic-algebra.php#solve-for-a-variable) and return x's value. For example: \n\n```python\nsolve_for_x('x - 5 = 20') # should return 25\nsolve_for_x('20 = 5 * x - 5') # should return 5\nsolve_for_x('5 * x = x + 8') # should return 2\nsolve_for_x('(5 - 3) * x = x + 2') # should return 2\n```\n\nNOTES:\n * All numbers will be whole numbers\n * Don't forget about the [order of operations](https://www.mathplacementreview.com/algebra/basic-algebra.php#order-of-operations).\n * If the random tests don't pass the first time, just run them again.", "solutions": ["from itertools import count\n\ndef solve_for_x(equation):\n return next((x for n in count(0) for x in [n, -n] if eval(equation.replace('x', str(x)).replace('=', '=='))))", "import re\n\ndef solve_for_x(equation):\n (left, right) = equation.split('=')\n answer = False\n TrialAndErrorRipMs = -1000\n while answer == False:\n FinalLeft = re.sub('x', str(TrialAndErrorRipMs), left)\n FinalRight = re.sub('x', str(TrialAndErrorRipMs), right)\n if eval(FinalLeft) == eval(FinalRight):\n return TrialAndErrorRipMs\n TrialAndErrorRipMs += 1", "def solve_for_x(equation):\n left_side = equation.split('=')[0]\n right_side = equation.split('=')[1]\n for x in range(-1000, 1000):\n if eval(left_side) == eval(right_side):\n return x", "def solve_for_x(equation):\n for x in range(-100, 1001):\n if eval(equation.replace('=', '==')):\n return x", "from itertools import count\n\ndef solve_for_x(equation):\n equation = equation.replace('=', '==')\n for x in count():\n if eval(equation):\n return x\n x = -x\n if eval(equation):\n return x", "def solve_for_x(equation):\n (left, right) = equation.split('=')\n for x in range(-1000, 1000):\n if eval(left) == eval(right):\n return x", "def solve_for_x(equation):\n p = equation.split()\n for i in range(0, len(p)):\n if p[i] == '=':\n p[i] = '=='\n t = p.index('x')\n for x in range(-1000, 1000):\n p[t] = str(x)\n if eval(''.join(p)):\n return x", "def solve_for_x(s):\n for i in range(-1000, 1000):\n if eval(s.replace('x', str(i)).replace('=', '==')):\n return i", "def build1(s):\n s = s.replace(' ', '')\n stack = []\n s += '!'\n if s[0] == '-':\n s = '0' + s\n j = 0\n for i in range(len(s)):\n if s[i] in ['+', '-', '*', '/', '(', ')', '!']:\n if j < i:\n stack.append(s[j:i])\n stack.append(s[i])\n j = i + 1\n stack.remove('!')\n for (i, x) in enumerate(stack):\n if x not in ['+', '-', '*', '/', '(', ')', '!']:\n stack[i] = Exp(x)\n return stack\n\ndef build2(s):\n while ')' in s:\n end = s.index(')')\n start = end\n while s[start] != '(':\n start -= 1\n s = s[:start] + [build2(s[start + 1:end])] + s[end + 1:]\n op = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x.__div__(y)}\n i = 2\n for order in [0, 1]:\n i = 2\n while i < len(s):\n if order == 0 and s[i - 1] in ['*', '/'] or (order == 1 and s[i - 1] in ['+', '-']):\n s[i - 2] = op[s[i - 1]](s[i - 2], s[i])\n s.pop(i)\n s.pop(i - 1)\n else:\n i += 2\n return s[0]\n\ndef build(s):\n stack = build1(s)\n equ = build2(stack)\n if type(equ) == Exp:\n equ = Equ([equ])\n return equ\n\ndef solve_for_x(equation):\n (l, r) = equation.split(' = ')\n (l, r) = (build(l), build(r))\n (l, r) = (l.get_power(1) - r.get_power(1), r.get_power(0) - l.get_power(0))\n return r.a / l.a\n\ndef __init__(s):\n self.a = 1\n self.p = 0\n if s[-1] == 'x':\n self.p = 1\n s = s[:-1]\n if 0 < len(s):\n self.a *= int(s)\n\ndef __add__(other):\n if self.p == other.p:\n self.a += other.a\n return self\n else:\n return Equ([self, other])\n\ndef __sub__(other):\n if self.p == other.p:\n self.a -= other.a\n return self\n else:\n return Equ([self, Exp('-1') * other])\n\ndef __mul__(other):\n self.p += other.p\n self.a *= other.a\n return self\n\ndef __div__(other):\n self.p -= other.p\n self.a /= other.a\n return self\n\ndef __str__():\n s = ''\n if self.a != 0:\n s += str(self.a)\n if self.p == 1:\n s += 'x'\n if s == '':\n s += '0'\n return s\n\ndef __init__(exp):\n self.exp = dict()\n for e in exp:\n if e.p not in self.exp:\n self.exp[e.p] = e\n else:\n self.exp[e.p] += e\n\ndef __add__(other):\n if type(other) == Exp:\n other = Equ([other])\n for p in other.exp:\n if p in self.exp:\n self.exp[p] += other.exp[p]\n else:\n self.exp[p] = other.exp[p]\n return self\n\ndef __sub__(other):\n if type(other) == Exp:\n other = Equ([other])\n for p in other.exp:\n if p in self.exp:\n self.exp[p] -= other.exp[p]\n else:\n self.exp[p] = Exp('-1') * other.exp[p]\n return self\n\ndef __mul__(other):\n if type(other) == Exp:\n other = Equ([other])\n res = None\n for p1 in other.exp:\n temp_res = []\n for p2 in self.exp:\n temp_res.append(self.exp[p2] * other.exp[p1])\n if res is None:\n res = Equ(temp_res)\n else:\n res += Equ(temp_res)\n return self\n\ndef __div__(other):\n if type(other) == Exp:\n other = Equ([other])\n res = None\n for p1 in other.exp:\n temp_res = []\n for p2 in self.exp:\n temp_res.append(self.exp[p2] / other.exp[p1])\n if res is None:\n res = Equ(temp_res)\n else:\n res += Equ(temp_res)\n return self\n\ndef __str__():\n s = ''\n for p in self.exp:\n s += ' (' + str(self.exp[p]) + ') +'\n return s[:-1]\n\ndef get_power(p):\n return self.exp[p] if p in self.exp else Exp('0') if p == 0 else Exp('0x')"], "starter_code": "def solve_for_x(equation):\n", "input_output": {"fn_name": "solve_for_x", "inputs": [["x - 5 = 20"], ["5 * x + 5 = 30"], ["20 = 5 * x - 5"], ["24 = 4 + 5 * x"], ["x = 5"], ["x * 100 = 700"], ["2 * x + 5 = 105"], ["2 * x = 198"], ["x - 100 + 2 - 50 = 52"], ["x / 3 = 33"], ["x + 80 = 20"], ["x + 20 = -60"], ["5 * x + 20 - x = 60"], ["x + x + 6 = 10"], ["5 * x = x + 8"], ["x = x / 2 + 25"], ["(5 - 3) * x = x + 2"], ["(x - 30) * 2 = x"]], "outputs": [[25], [5], [5], [4], [5], [7], [50], [99], [200], [99], [-60], [-80], [10], [2], [2], [50], [2], [60]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Fundamentals", "Puzzles"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics", "Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/59c2e2a36bddd2707e000079", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve_for_x", "task_id": "TACO_lite/8", "example": [[["x - 5 = 20"], ["20 = 5 * x - 5"], ["5 * x = x + 8"], ["(5 - 3) * x = x + 2"]], ["25", "5", "2", "2"]]} +{"requirement": "Implement function which will return sum of roots of a quadratic equation rounded to 2 decimal places, if there are any possible roots, else return **None/null/nil/nothing**. If you use discriminant,when discriminant = 0, x1 = x2 = root => return sum of both roots. There will always be valid arguments. \n\nQuadratic equation - https://en.wikipedia.org/wiki/Quadratic_equation", "solutions": ["def roots(a, b, c):\n if b ** 2 >= 4 * a * c:\n return round(-b / a, 2)", "def roots(a, b, c):\n import math\n d = b ** 2 - 4 * a * c\n if d > 0:\n return round(-2 * b / (2 * a), 2)\n elif d == 0:\n x = -b / (2 * a)\n return x * 2\n else:\n return None", "def roots(a, b, c):\n return round(-b / a, 2) if b * b - 4 * a * c >= 0 else None", "def roots(a, b, c):\n d = b ** 2 - 4 * a * c\n if d < 0:\n return None\n elif d == 0:\n return (-b + d ** 0.5) / (2 * a) * 2\n else:\n x1 = (-b + d ** 0.5) / (2 * a)\n x2 = (-b - d ** 0.5) / (2 * a)\n return round(x1 + x2, 2)", "def roots(a, b, c):\n d = b ** 2 - 4 * a * c\n if d >= 0:\n return round(-b / a, 2)", "roots = lambda a, b, c: None if b * b < a * c * 4 else round(-b / a, 2)", "def roots(a, b, c):\n D = b ** 2 - 4 * a * c\n if D < 0:\n return None\n if D == 0:\n x = (-b + D ** 0.5) / (2 * a)\n return round(x * 2, 2)\n if D > 0:\n x1 = (-b + D ** 0.5) / (2 * a)\n x2 = (-b - D ** 0.5) / (2 * a)\n return round(x1 + x2, 2)", "import math\n\ndef roots(a, b, c):\n dis = b ** 2 - 4 * a * c\n if dis < 0:\n return None\n return round((-b + math.sqrt(dis)) / (2 * a) + (-b - math.sqrt(dis)) / (2 * a), 2)", "import math\n\ndef roots(a, b, c):\n d = round(b * b - 4 * a * c, 2)\n if d < 0:\n return None\n return round(-b / a, 2)"], "starter_code": "def roots(a,b,c):\n", "input_output": {"fn_name": "roots", "inputs": [[1, -35, -23], [6, 0, -24], [-5, 21, 0], [6, 4, 8], [1, 5, -24], [3, 11, 6], [2, 2, 9], [1, -1.6666666666666667, -26], [1, 6, 10], [7, -2, -5], [1, 8, 20], [2, 3, -2], [1, 4, 12], [3, -2, -5], [3, 4, 9], [5, 4, 0], [4, -5, 0], [1, 4, 9], [1, 0, -49], [2, 8, 8], [1, 0, -0.16], [1, 6, 12], [1, 0, -9], [-3, 0, 12], [1, 3, 9], [3, 7, 0], [5, 3, 6], [1, 4, 4], [-1, 0, 5.29], [1, 12, 36], [1, 0, -0.09], [2, 5, 11], [3, 0, -15], [1, -3, 0], [1, 8, 16], [2, 6, 9], [-1, 36, 0], [5, -8, 0], [1, 5, 12], [-14, 0, 0], [1, 7, 20], [1, -6, 0], [1, -11, 30], [1, 3, 12], [1, 6, 9], [8, 47, 41]], "outputs": [[35], [0], [4.2], [null], [-5], [-3.67], [null], [1.67], [null], [0.29], [null], [-1.5], [null], [0.67], [null], [-0.8], [1.25], [null], [0], [-4], [0], [null], [0], [0], [null], [-2.33], [null], [-4], [0], [-12], [0], [null], [0], [3], [-8], [null], [36], [1.6], [null], [0], [null], [6], [11], [null], [-6], [-5.88]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/57d448c6ba30875437000138", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "roots", "task_id": "TACO_lite/27", "example": [[[1, -3, 2], [1, -2, 1], [1, 0, 1]], ["3.0", "2.0", "None"]]} +{"requirement": "## Task\n\nImplement a function which finds the numbers less than `2`, and the indices of numbers greater than `1` in the given sequence, and returns them as a pair of sequences. \n\nReturn a nested array or a tuple depending on the language:\n\n* The first sequence being only the `1`s and `0`s from the original sequence. \n* The second sequence being the indexes of the elements greater than `1` in the original sequence. \n\n## Examples\n\n```python\n[ 0, 1, 2, 1, 5, 6, 2, 1, 1, 0 ] => ( [ 0, 1, 1, 1, 1, 0 ], [ 2, 4, 5, 6 ] )\n```\n\nPlease upvote and enjoy!", "solutions": ["def binary_cleaner(seq):\n res = ([], [])\n for (i, x) in enumerate(seq):\n if x < 2:\n res[0].append(x)\n else:\n res[1].append(i)\n return res", "def binary_cleaner(lst):\n return ([n for n in lst if n < 2], [i for (i, n) in enumerate(lst) if n > 1])", "def binary_cleaner(seq):\n return (list(filter(lambda x: x <= 1, seq)), [i for i in range(len(seq)) if seq[i] > 1])", "def binary_cleaner(seq):\n return ([x for x in seq if x in [0, 1]], [i for (i, x) in enumerate(seq) if x > 1])", "def binary_cleaner(seq):\n return ([value for value in seq if value == 0 or value == 1], [index for (index, value) in enumerate(seq) if value not in (0, 1)])", "def binary_cleaner(seq):\n return ([n for n in seq if n < 2], [i for (i, n) in enumerate(seq) if n > 1])", "def binary_cleaner(seq):\n (list_a, list_b) = ([], [])\n for (k, v) in enumerate(seq):\n if v > 1:\n list_b.append(k)\n else:\n list_a.append(v)\n return (list_a, list_b)", "def binary_cleaner(seq):\n b = []\n x = []\n for i in range(len(seq)):\n if seq[i] < 2:\n b.append(seq[i])\n elif seq[i] > 1:\n x.append(i)\n return (b, x)", "def binary_cleaner(seq):\n less_than_1 = []\n index_list = []\n for (i, x) in enumerate(seq):\n if x < 2:\n less_than_1.append(x)\n if x > 1:\n index_list.append(i)\n return (less_than_1, index_list)", "def binary_cleaner(seq):\n return ([i for i in seq if i <= 1], [i for (i, el) in enumerate(seq) if el > 1])"], "starter_code": "def binary_cleaner(seq):\n", "input_output": {"fn_name": "binary_cleaner", "inputs": [[[0, 1, 2, 1, 0, 2, 1, 1, 1, 0, 4, 5, 6, 2, 1, 1, 0]], [[0, 1, 1, 2, 0]], [[2, 2, 0]], [[0, 1, 2, 1, 0, 2, 1, 1]], [[1]], [[3, 0, 7, 0, 2, 0]]], "outputs": [[[[0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0], [2, 5, 10, 11, 12, 13]]], [[[0, 1, 1, 0], [3]]], [[[0], [0, 1]]], [[[0, 1, 1, 0, 1, 1], [2, 5]]], [[[1], []]], [[[0, 0, 0], [0, 2, 4]]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5b5097324a317afc740000fe", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "binary_cleaner", "task_id": "TACO_lite/77", "example": [[[[0, 1, 2, 1, 5, 6, 2, 1, 1, 0]]], ["([0, 1, 1, 1, 1, 0], [2, 4, 5, 6])"]]} +{"requirement": "The task is to complete the insert() function which is used to implement Insertion Sort. \nExample 1:\nInput:\nN = 5\narr[] = { 4, 1, 3, 9, 7}\nOutput:\n1 3 4 7 9\nExample 2:\nInput:\nN = 10\narr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}\nOutput:\n1 2 3 4 5 6 7 8 9 10\nYour Task: \nYou don't have to read input or print anything. Your task is to complete the function insert() and insertionSort() where insert() takes the array, it's size and an index i and insertionSort() uses insert function to sort the array in ascending order using insertion sort algorithm. \nExpected Time Complexity: O(N*N).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= N <= 1000\n1 <= arr[i] <= 1000", "solutions": ["def insert(alist, index, n):\n x = alist[index]\n j = index - 1\n while j >= 0 and alist[j] > x:\n alist[j + 1] = alist[j]\n j -= 1\n alist[j + 1] = x\n\ndef insertionSort(alist, n):\n for i in range(1, n):\n self.insert(arr, i, n)", "def insert(alist, index, n):\n j = index\n while j > 0 and alist[j - 1] > alist[j]:\n temp = alist[j]\n alist[j] = alist[j - 1]\n alist[j - 1] = temp\n j -= 1\n return alist\n\ndef insertionSort(alist, n):\n for i in range(n):\n alist = self.insert(alist, i, n)\n return alist", "def insertionSort(alist, n):\n for i in range(1, len(alist)):\n key = alist[i]\n j = i - 1\n while j >= 0 and alist[j] > key:\n alist[j + 1] = alist[j]\n j -= 1\n alist[j + 1] = key\n return alist", "def insertionSort(alist, n):\n for i in range(n):\n tmp = alist[i]\n j = i - 1\n while j >= 0 and alist[j] > tmp:\n alist[j + 1] = alist[j]\n j = j - 1\n alist[j + 1] = tmp", "def insertionSort(alist, n):\n for i in range(1, n):\n for j in reversed(range(i)):\n if alist[j] > alist[j + 1]:\n (alist[j], alist[j + 1]) = (alist[j + 1], alist[j])\n else:\n break\n return alist", "def insert(alist, index, n):\n pass\n\ndef insertionSort(alist, n):\n for i in range(n):\n mini = i\n for j in range(i + 1, n):\n if alist[j] < alist[mini]:\n mini = j\n (alist[mini], alist[i]) = (alist[i], alist[mini])\n return alist", "def insertionSort(alist, n):\n alist.sort()\n return alist", "def insert(alist, index, n):\n for index in range(n):\n alist.append(alist[index])\n\ndef insertionSort(alist, n):\n alist.sort()\n return alist", "def insert(alist, index, n):\n if index == n:\n return\n j = index - 1\n key = arr[index]\n while j >= 0 and key <= alist[j]:\n alist[j + 1] = alist[j]\n j -= 1\n alist[j + 1] = key\n self.insert(alist, index + 1, n)\n\ndef insertionSort(alist, n):\n self.insert(alist, 1, n)\n return alist", "def insert(alist, index, n):\n self.insertionSort(alist, n)\n\ndef insertionSort(alist, n):\n for index in range(1, n):\n curr = alist[index]\n pos = index\n while curr < alist[pos - 1] and pos > 0:\n alist[pos] = alist[pos - 1]\n pos = pos - 1\n alist[pos] = curr\n return", "def insert(alist, index, n):\n key = alist[index]\n i = index - 1\n while i >= 0 and alist[i] > key:\n alist[i + 1] = alist[i]\n i -= 1\n alist[i + 1] = key\n\ndef insertionSort(alist, n):\n for i in range(1, n):\n self.insert(alist, i, n)", "def insert(arr, index, n):\n if index > n - 1:\n return\n temp = arr[index]\n j = index - 1\n while j >= 0 and temp < arr[j]:\n arr[j + 1] = arr[j]\n j -= 1\n arr[j + 1] = temp\n self.insert(arr, index + 1, n)\n\ndef insertionSort(arr, n):\n self.insert(arr, 1, n)\n return arr", "def insert(alist, index, n):\n return alist.sort()\n\ndef insertionSort(alist, n):\n return alist.sort()", "def insert(arr, index, n):\n s = arr.sort()\n return s\n\ndef insertionSort(arr, n):\n k = arr.sort()\n return k", "def insert(alist, index, n):\n while index != 0:\n if alist[index] < alist[index - 1]:\n (alist[index], alist[index - 1]) = (alist[index - 1], alist[index])\n else:\n break\n index -= 1\n\ndef insertionSort(arr, n):\n for i in range(n - 1):\n if arr[i] > arr[i + 1]:\n self.insert(arr, i + 1, n)", "def insertionSort(arr, n):\n for i in range(n):\n current = arr[i]\n j = i - 1\n while j >= 0 and arr[j] > current:\n arr[j + 1] = arr[j]\n j = j - 1\n arr[j + 1] = current", "def insert(alist, index, n):\n pass\n\ndef insertionSort(alist, n):\n arr.sort()", "def insertionSort(alist, n):\n for i in range(1, n):\n valuetosort = alist[i]\n while alist[i - 1] > valuetosort and i > 0:\n (alist[i], alist[i - 1]) = (alist[i - 1], alist[i])\n i -= 1\n return arr", "def insert(l, i, n):\n for j in range(i, 0, -1):\n if l[j] < l[j - 1]:\n (l[j], l[j - 1]) = (l[j - 1], l[j])\n else:\n break\n\ndef insertionSort(l, n):\n for i in range(1, n):\n x = self.insert(l, i, n)", "def insertionSort(a, n):\n for i in range(1, n):\n x = a[i]\n j = i - 1\n while j >= 0 and a[j + 1] < a[j]:\n (a[j], a[j + 1]) = (a[j + 1], a[j])\n j = j - 1", "def insert(alist, index, n):\n pass\n\ndef insertionSort(alist, n):\n a = alist.sort()\n return a", "def insert(alist, index, n):\n return\n\ndef insertionSort(alist, n):\n for i in range(1, len(alist)):\n a = i\n while a > 0 and alist[a - 1] > alist[a]:\n (alist[a - 1], alist[a]) = (alist[a], alist[a - 1])\n a -= 1\n return alist", "def insert(alist, index, n):\n currentvalue = alist[index]\n position = index\n while position > 0 and alist[position - 1] > currentvalue:\n alist[position] = alist[position - 1]\n position = position - 1\n alist[position] = currentvalue\n\ndef insertionSort(alist, n):\n for index in range(1, n):\n self.insert(arr, index, n)", "def insert(a, n, i):\n if i == n:\n return\n temp = a[i]\n j = i - 1\n while j >= 0 and a[j] > temp:\n a[j + 1] = a[j]\n j -= 1\n a[j + 1] = temp\n self.insert(a, n, i + 1)\n\ndef insertionSort(alist, n):\n self.insert(alist, n, 1)", "def insert(alist, i, n):\n while i and alist[i] < alist[i - 1]:\n (alist[i], alist[i - 1]) = (alist[i - 1], alist[i])\n i -= 1\n\ndef insertionSort(alist, n):\n if n <= 1:\n return\n for i in range(1, n):\n self.insert(alist, i, n)", "def insert(alist, index, n):\n current_value = alist[index]\n while index > 0 and alist[index - 1] > current_value:\n alist[index] = alist[index - 1]\n index -= 1\n alist[index] = current_value\n\ndef insertionSort(alist, n):\n for index in range(1, n):\n self.insert(alist, index, n)", "def insertionSort(alist, n):\n if n <= 1:\n return\n Solution().insertionSort(alist, n - 1)\n last = arr[n - 1]\n j = n - 2\n while j >= 0 and alist[j] > last:\n alist[j + 1] = alist[j]\n j -= 1\n alist[j + 1] = last", "def insert(alist, index, n):\n for i in range(index):\n if alist[i] > alist[index]:\n (alist[i], alist[index]) = (alist[index], alist[i])\n\ndef insertionSort(alist, n):\n for i in range(1, n):\n self.insert(alist, i, n)", "def insert(alist, index, n):\n pass\n\ndef insertionSort(arr, n):\n n = len(arr)\n for i in range(n):\n index = i\n swap = 0\n while index > 0 and arr[index] <= arr[index - 1]:\n (arr[index], arr[index - 1]) = (arr[index - 1], arr[index])\n index -= 1", "def insertionSort(alist, n):\n for i in range(1, n):\n prev_range = range(i - 1, -1, -1)\n val = alist[i]\n for j in prev_range:\n if val > alist[j]:\n alist[j + 1] = val\n break\n alist[j + 1] = alist[j]\n else:\n alist[j] = val", "def insertionSort(a, n):\n for i in range(1, n):\n k = a[i]\n j = i - 1\n while j >= 0 and k < a[j]:\n a[j + 1] = a[j]\n j = j - 1\n a[j + 1] = k\n return a", "def insert(arr, n):\n for i in range(n, 0, -1):\n if arr[i - 1] > arr[i]:\n (arr[i - 1], arr[i]) = (arr[i], arr[i - 1])\n else:\n return\n\ndef insertionSort(arr, n):\n for i in range(1, n):\n if arr[i - 1] > arr[i]:\n insert(arr, i)\n return arr"], "starter_code": "def insert(alist, index, n):\n", "input_output": {"inputs": ["N = 5\narr[] = { 4, 1, 3, 9, 7}", "N = 10\narr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}"], "outputs": ["1 3 4 7 9", "1 2 3 4 5 6 7 8 9 10"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Sorting"], "name": null, "source": "geeksforgeeks", "tags": ["Sorting"], "skill_types": ["Sorting"], "url": "https://practice.geeksforgeeks.org/problems/insertion-sort/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*N).", "entry_point": "insert", "task_id": "TACO_lite/23", "example": [[], []]} +{"requirement": "Given a matrix A of dimensions NxN where every element is either O or X. Find the largest subsquare surrounded by X.\nExample 1:\nInput:\nN=2\nA=[[X,X][X,X]]\nOutput:\n2\nExplanation:\nThe largest square submatrix \nsurrounded by X is the whole \ninput matrix.\nExample 2:\nInput:\nN=4\nA=[[X,X,X,O],[X,O,X,X],\n[X,X,X,O],[X,O,X,X]]\nOutput:\n3\nExplanation:\nHere,the input represents following \nmatrix of size 4 x 4\nX X X O\nX O X X\nX X X O\nX O X X\nThe square submatrix starting at \n(0,0) and ending at (2,2) is the \nlargest submatrix surrounded by X.\nTherefore, size of that matrix would be 3.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function largestSubsquare() which takes the integer N and the matrix A as input parameters and returns the size of the largest subsquare surrounded by 'X'.\nExpected Time Complexity:O(N^{2})\nExpected Auxillary Space:O(N^{2})\nConstraints:\n1<=N<=1000\nA[i][j]={'X','O'}", "solutions": ["def largestsubsquare(N, A):\n m = [[[0 for _ in range(N)] for _ in range(N)] for _ in range(2)]\n for i in range(N):\n m[0][i][0] = 1 if A[i][0] == 'X' else 0\n for j in range(1, N):\n if A[i][j] == 'X':\n m[0][i][j] = m[0][i][j - 1] + 1\n for j in range(N):\n m[1][0][j] = 1 if A[0][j] == 'X' else 0\n for i in range(1, N):\n if A[i][j] == 'X':\n m[1][i][j] = m[1][i - 1][j] + 1\n ans = 0\n for i in range(N):\n for j in range(N):\n d = min(m[0][i][j], m[1][i][j])\n while d > 0:\n if m[0][i - d + 1][j] >= d and m[1][i][j - d + 1] >= d:\n ans = max(d, ans)\n break\n d -= 1\n return ans", "def get_hor_mat(n, a, hor):\n for i in range(n):\n for j in range(n):\n if i >= 0 and j == 0:\n if a[i][j] == 'X':\n hor[i][j] = 1\n else:\n hor[i][j] = 0\n elif a[i][j] == 'X':\n hor[i][j] = hor[i][j - 1] + 1\n else:\n continue\n\ndef get_ver_mat(n, a, ver):\n for i in range(n):\n for j in range(n):\n if i == 0 and j >= 0:\n if a[i][j] == 'X':\n ver[i][j] = 1\n elif a[i][j] == 'X':\n ver[i][j] = ver[i - 1][j] + 1\n\ndef largestsubsquare(n, a):\n hor = [[0 for j in range(n)] for i in range(n)]\n ver = [[0 for j in range(n)] for i in range(n)]\n max_square = 0\n self.get_hor_mat(n, a, hor)\n self.get_ver_mat(n, a, ver)\n for i in range(n - 1, -1, -1):\n for j in range(n - 1, -1, -1):\n min_val = min(hor[i][j], ver[i][j])\n while min_val > max_square:\n if ver[i][j - min_val + 1] >= min_val and hor[i - min_val + 1][j] >= min_val:\n max_square = min_val\n min_val -= 1\n return max_square", "def largestsubsquare(N, A):\n (ROWS, COLS) = (len(A), len(A[0]))\n dp = [[[0, 0] for i in range(ROWS + 1)] for j in range(COLS + 1)]\n for i in range(ROWS):\n for j in range(COLS):\n if A[i][j] == 'X':\n dp[i + 1][j + 1][0] = dp[i][j + 1][0] + 1\n dp[i + 1][j + 1][1] = dp[i + 1][j][1] + 1\n maxi = 0\n for i in range(ROWS, 0, -1):\n for j in range(COLS, 0, -1):\n curMin = min(dp[i][j][0], dp[i][j][1])\n while curMin > maxi:\n if dp[i - curMin + 1][j][1] >= curMin and dp[i][j - curMin + 1][0] >= curMin:\n maxi = curMin\n else:\n curMin -= 1\n return maxi", "def largestsubsquare(N, A):\n left_c = [[0] * N for i in range(N)]\n top_c = [[0] * N for i in range(N)]\n for i in range(N):\n for j in range(N):\n if A[i][j] == 'X':\n left_c[i][j] = (left_c[i][j - 1] if j > 0 else 0) + 1\n top_c[i][j] = (top_c[i - 1][j] if i > 0 else 0) + 1\n max_len = 0\n for i in range(N - 1, -1, -1):\n for j in range(N - 1, -1, -1):\n val = min(left_c[i][j], top_c[i][j])\n while val > max_len:\n if top_c[i][j - val + 1] >= val and left_c[i - val + 1][j] >= val:\n max_len = max(max_len, val)\n val -= 1\n return max_len", "def largestsubsquare(n, a):\n dp = [[[0, 0] for i in range(n)] for i in range(n)]\n dp[0][0] = [1, 1] if a[0][0] == 'X' else [0, 0]\n m = dp[0][0][0]\n\n def check(i, j, back):\n nonlocal dp\n nonlocal m\n while back > m and (dp[i - back + 1][j][1] < back or dp[i][j - back + 1][0] < back):\n back -= 1\n return back if back > m else m\n for i in range(1, n):\n if a[0][i] == 'X':\n dp[0][i] = [1, dp[0][i - 1][1] + 1]\n if a[i][0] == 'X':\n dp[i][0] = [dp[i - 1][0][0] + 1, 1]\n m = max(m, min(dp[0][i]), min(dp[i][0]))\n for i in range(1, n):\n for j in range(1, n):\n if a[i][j] == 'X':\n dp[i][j][0] = dp[i - 1][j][0] + 1\n dp[i][j][1] = dp[i][j - 1][1] + 1\n x = min(dp[i][j])\n if x > m:\n m = check(i, j, x)\n return m", "def largestsubsquare(N, A):\n a = [[[0, 0] for i in range(N)] for i in range(N)]\n for i in range(N):\n for j in range(N):\n if A[i][j] == 'O':\n a[i][j][0] = 0\n a[i][j][1] = 0\n elif A[i][j] == 'X':\n if i - 1 >= 0:\n a[i][j][1] = a[i - 1][j][1] + 1\n else:\n a[i][j][1] = 1\n if j - 1 >= 0:\n a[i][j][0] = a[i][j - 1][0] + 1\n else:\n a[i][j][0] = 1\n max = 0\n for i in range(N):\n for j in range(N):\n aa = min(a[i][j][0], a[i][j][1])\n while aa > max:\n if aa > max and a[i - aa + 1][j][0] >= aa and (a[i][j - aa + 1][1] >= aa):\n max = aa\n break\n aa -= 1\n return max", "def largestsubsquare(N, mat):\n Max = 0\n mp = [[(0, 0) for i in range(N)] for i in range(N)]\n for i in range(N):\n for j in range(N):\n if mat[i][j] == 'O':\n mp[i][j] = (0, 0)\n elif i == 0 and j == 0:\n mp[i][j] = (1, 1)\n elif i == 0:\n mp[i][j] = (1, mp[i][j - 1][1] + 1)\n elif j == 0:\n mp[i][j] = (mp[i - 1][j][0] + 1, 1)\n else:\n mp[i][j] = (mp[i - 1][j][0] + 1, mp[i][j - 1][1] + 1)\n for i in range(N - 1, -1, -1):\n for j in range(N - 1, -1, -1):\n small = mp[i][j][0] if mp[i][j][0] < mp[i][j][1] else mp[i][j][1]\n while small > Max:\n if mp[i][j - small + 1][0] >= small and mp[i - small + 1][j][1] >= small:\n Max = small\n small -= 1\n return Max"], "starter_code": "def largestsubsquare(N,A):\n", "input_output": {"inputs": ["N=2\r\nA=[[X,X][X,X]]", "N=4\r\nA=[[X,X,X,O],[X,O,X,X],\r\n[X,X,X,O],[X,O,X,X]]"], "outputs": ["2", "3"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/largest-subsquare-surrounded-by-x0558/1", "Expected Auxiliary Space": "O(N^{2})", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N^{2})", "entry_point": "largestsubsquare", "task_id": "TACO_lite/41", "example": [[[2, [["X", "X"], ["X", "X"]]], [4, [["X", "X", "X", "O"], ["X", "O", "X", "X"], ["X", "X", "X", "O"], ["X", "O", "X", "X"]]]], ["2", "3"]]} +{"requirement": "Given a matrix consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every cell in that column.  Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0.\nReturn the maximum number of rows that have all values equal after some number of flips.\n \n\n\n\nExample 1:\nInput: [[0,1],[1,1]]\nOutput: 1\nExplanation: After flipping no values, 1 row has all values equal.\n\n\nExample 2:\nInput: [[0,1],[1,0]]\nOutput: 2\nExplanation: After flipping values in the first column, both rows have equal values.\n\n\nExample 3:\nInput: [[0,0,0],[0,0,1],[1,1,0]]\nOutput: 2\nExplanation: After flipping values in the first two columns, the last two rows have equal values.\n\n \nNote:\n\n1 <= matrix.length <= 300\n1 <= matrix[i].length <= 300\nAll matrix[i].length's are equal\nmatrix[i][j] is 0 or 1", "solutions": ["def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n dict_ = {}\n for row in matrix:\n curr_tuple = tuple(row)\n dict_[curr_tuple] = 1 + dict_.get(curr_tuple, 0)\n visited = set()\n max_same = 0\n for row in matrix:\n curr_tuple = tuple(row)\n if curr_tuple in visited:\n continue\n visited.add(curr_tuple)\n inverse = [1] * len(row)\n for i in range(len(row)):\n if row[i]:\n inverse[i] = 0\n curr_inv = tuple(inverse)\n visited.add(curr_inv)\n curr_sum = 0\n curr_sum = dict_[curr_tuple]\n if curr_inv in dict_:\n curr_sum += dict_[curr_inv]\n if curr_sum > max_same:\n max_same = curr_sum\n return max_same", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n pattern_dict = {}\n for row in matrix:\n if row[0] == 0:\n key = tuple(row)\n else:\n newrow = [1 - x for x in row]\n key = tuple(newrow)\n if key in pattern_dict:\n pattern_dict[key] += 1\n else:\n pattern_dict[key] = 1\n maxnum = 0\n for (_, num) in pattern_dict.items():\n maxnum = max(maxnum, num)\n return maxnum", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n if len(matrix) == 0:\n return 0\n cols = len(matrix[0])\n allOnes = 0\n for i in range(0, cols):\n allOnes <<= 1\n allOnes |= 1\n freq = {}\n count = 0\n for i in range(0, len(matrix)):\n rowNumber = 0\n for j in range(0, len(matrix[i])):\n rowNumber = rowNumber << 1\n rowNumber = rowNumber | matrix[i][j]\n xorRowNumber = rowNumber ^ allOnes\n if rowNumber in freq:\n freq[rowNumber] += 1\n count = max(count, freq[rowNumber])\n elif xorRowNumber in freq:\n freq[xorRowNumber] += 1\n count = max(count, freq[xorRowNumber])\n else:\n freq[rowNumber] = 1\n count = max(count, freq[rowNumber])\n return count", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n dic = {}\n for i in range(len(matrix)):\n a = ''\n b = ''\n for j in range(len(matrix[0])):\n a = a + '%d' % matrix[i][j]\n b = b + '%d' % (1 - matrix[i][j])\n if a not in dic:\n dic[a] = 1\n else:\n dic[a] += 1\n if b not in dic:\n dic[b] = 1\n else:\n dic[b] += 1\n m = 0\n for k in dic.keys():\n m = max(m, dic[k])\n return m", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n counter = {}\n for row in matrix:\n key = tuple((x ^ row[0] for x in row))\n counter[key] = counter.get(key, 0) + 1\n return max(counter.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n dicts = {}\n for row in matrix:\n bin_rep = ''.join([str(x) for x in row])\n if bin_rep not in dicts:\n dicts[bin_rep] = 1\n else:\n dicts[bin_rep] += 1\n rev_bin_rep = ''.join([str(x ^ 1) for x in row])\n if rev_bin_rep not in dicts:\n dicts[rev_bin_rep] = 1\n else:\n dicts[rev_bin_rep] += 1\n res = 0\n for (key, value) in dicts.items():\n res = max(res, value)\n return res", "def maxequalrowsafterflips(ma: List[List[int]]) -> int:\n n = len(ma)\n m = len(ma[0])\n di = {}\n for i in range(n):\n s = ''\n ss = ''\n for j in range(m):\n s = s + str(ma[i][j])\n ss = ss + str(1 - ma[i][j])\n di[s] = di.get(s, 0) + 1\n di[ss] = di.get(ss, 0) + 1\n return max(list(di.values()))", "import collections\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n return max(collections.Counter((tuple((x ^ r[0] for x in r)) for r in matrix)).values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n\n def find_minor(row):\n one = row.count(1)\n if one * 2 == len(row):\n return tuple((i for (i, val) in enumerate(row) if val == row[-1]))\n elif one * 2 > len(row):\n return tuple((i for (i, val) in enumerate(row) if val == 0))\n return tuple((i for (i, val) in enumerate(row) if val == 1))\n counts = collections.Counter()\n for (i, row) in enumerate(matrix):\n counts[find_minor(row)] += 1\n return max(counts.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n n = len(matrix)\n m = len(matrix[0])\n mx = 1\n for i in range(n):\n c = [0 for i in range(m)]\n for j in range(m):\n if matrix[i][j] == 0:\n c[j] = 1\n else:\n c[j] = 0\n count = 1\n for j in range(n):\n if i != j and c == matrix[j] or matrix[i] == matrix[j]:\n count += 1\n mx = max(mx, count)\n return mx - 1", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n n = len(matrix)\n m = len(matrix[0])\n res = 0\n for i in range(n):\n flip = [1 - matrix[i][j] for j in range(m)]\n cnt = 0\n for k in range(n):\n if matrix[i] == matrix[k] or flip == matrix[k]:\n cnt += 1\n res = max(res, cnt)\n return res", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n counter = collections.Counter()\n for row in matrix:\n flipper = {1: 0, 0: 1}\n if row[0] == 0:\n row = [flipper[col] for col in row]\n counter[tuple(row)] += 1\n return max(counter.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n rows = {}\n max_value = 0\n n = len(matrix)\n m = len(matrix[0])\n for i in range(n):\n a = []\n b = []\n for j in range(m):\n if matrix[i][j] == 0:\n a.append(j)\n else:\n b.append(j)\n a = tuple(a)\n b = tuple(b)\n if a not in rows:\n rows[a] = 0\n if b not in rows:\n rows[b] = 0\n rows[a] += 1\n rows[b] += 1\n max_value = max(max_value, rows[a], rows[b])\n return max_value", "def maxequalrowsafterflips(mat: List[List[int]]) -> int:\n dic = defaultdict(lambda : 0)\n for r in range(len(mat)):\n row = mat[r]\n ones = 0\n zeros = 0\n for i in range(len(row)):\n if row[i] == 0:\n ones = ones << 1\n zeros = zeros << 1\n ones |= 1\n else:\n zeros = zeros << 1\n ones = ones << 1\n zeros |= 1\n dic[zeros] += 1\n dic[ones] += 1\n return max(dic.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n cache = collections.defaultdict(int)\n for row in matrix:\n vals = []\n trans = []\n for c in row:\n vals.append(c)\n trans.append(1 - c)\n cache[str(vals)] += 1\n cache[str(trans)] += 1\n return max(cache.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n rows = {}\n max_value = 0\n n = len(matrix)\n for i in range(n):\n if matrix[i][0] == 1:\n a = tuple(matrix[i])\n else:\n a = tuple([1 - c for c in matrix[i]])\n if a not in rows:\n rows[a] = 0\n rows[a] += 1\n max_value = max(max_value, rows[a])\n return max_value", "from collections import Counter\n\ndef flip(bits):\n return [1 if bit == 0 else 0 for bit in bits]\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n c = Counter()\n for row in matrix:\n c.update([tuple(row)])\n c.update([tuple(flip(row))])\n return max(c.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n f = defaultdict(int)\n n = len(matrix[0])\n for i in matrix:\n (p, q) = ([], [])\n for j in range(n):\n if i[j] == 0:\n p.append(j)\n else:\n q.append(j)\n f[tuple(p)] += 1\n f[tuple(q)] += 1\n return max(f.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n for (i, row) in enumerate(matrix):\n matrix[i] = tuple((x ^ row[0] for x in row))\n return max(Counter(matrix).values())", "def maxequalrowsafterflips(x: List[List[int]]) -> int:\n f = defaultdict(int)\n n = len(x[0])\n for i in x:\n p = q = 0\n v = 1\n for j in range(n):\n if i[j] == 0:\n p |= v\n else:\n q |= v\n v = v << 1\n f[p] += 1\n f[q] += 1\n return max(f.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n noninv = {}\n for row in matrix:\n row = repr(row)\n if row in noninv:\n noninv[row] += 1\n else:\n noninv[row] = 1\n count = 0\n for row in matrix:\n revrow = [i ^ 1 for i in row]\n revrow = repr(revrow)\n row = repr(row)\n if revrow in noninv:\n count = max(count, noninv[row] + noninv[revrow])\n else:\n count = max(count, noninv[row])\n return count", "from collections import defaultdict\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n lookup = collections.defaultdict(int)\n for row in matrix:\n vals = []\n trans = []\n for c in row:\n vals.append(c)\n trans.append(1 - c)\n lookup[str(vals)] += 1\n lookup[str(trans)] += 1\n return max(lookup.values())", "def maxequalrowsafterflips(mat: List[List[int]]) -> int:\n ans = 0\n (m, n) = (len(mat), len(mat[0]))\n ones = [[0] * n for i in range(m)]\n zeros = [[0] * n for i in range(m)]\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 1:\n zeros[i][j] = 1\n else:\n ones[i][j] = 1\n for i in range(m):\n for target in [ones[i], zeros[i]]:\n count = 1\n for k in range(m):\n if k == i:\n continue\n if ones[k] == target or zeros[k] == target:\n count += 1\n ans = max(ans, count)\n return ans", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n\n def reverse_row(row):\n res = [0] * len(row)\n for (i, val) in enumerate(row):\n res[i] = 1 - row[i]\n return res\n d = {}\n for row in matrix:\n rev_row = reverse_row(row)\n if tuple(row) in d:\n d[tuple(row)] += 1\n elif tuple(rev_row) in d:\n d[tuple(rev_row)] += 1\n else:\n d[tuple(row)] = 1\n res = sorted(d.items(), key=lambda x: x[1], reverse=1)\n return res[0][1]", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n counter = collections.defaultdict(int)\n for row in matrix:\n if row[0] == 1:\n row = [1 - num for num in row]\n counter[tuple(row)] += 1\n return max(counter.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n memo = collections.defaultdict(lambda : 0)\n for line in matrix:\n if line[0] == 0:\n memo[tuple(line)] += 1\n else:\n line = [1 if i == 0 else 0 for i in line]\n memo[tuple(line)] += 1\n return max(memo.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n\n def flip(row):\n return [1 - r for r in row]\n record = dict()\n for row in matrix:\n record[tuple(row)] = record.get(tuple(row), 0) + 1\n record[tuple(flip(row))] = record.get(tuple(flip(row)), 0) + 1\n return max(record.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n groups = {}\n for row in matrix:\n tuple_row = tuple(row)\n if tuple_row not in groups:\n groups[tuple_row] = 1\n else:\n groups[tuple_row] += 1\n max_equal = 0\n for row in groups.keys():\n rev_row = tuple([1 - x for x in row])\n group_max = groups[row]\n if row != rev_row and rev_row in groups:\n group_max += groups[rev_row]\n max_equal = max(max_equal, group_max)\n return max_equal", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n columnsToFlipOneForEqualRow = {}\n columnsToFlipZeroForEqualRow = {}\n self.height = len(matrix)\n self.width = len(matrix[0])\n for y in range(self.height):\n row = matrix[y]\n columnsToFlipOneForEqualRow[y] = []\n columnsToFlipZeroForEqualRow[y] = []\n for x in range(self.width):\n element = row[x]\n if element == 0:\n columnsToFlipOneForEqualRow[y].append(x)\n else:\n columnsToFlipZeroForEqualRow[y].append(x)\n patterns = {}\n for index in range(self.height):\n first = str(columnsToFlipOneForEqualRow[index])\n second = str(columnsToFlipZeroForEqualRow[index])\n if first not in patterns:\n patterns[first] = 0\n if second not in patterns:\n patterns[second] = 0\n patterns[first] += 1\n patterns[second] += 1\n return max(patterns.values())", "def convert_to_tuple(lst):\n if lst[0] == 0:\n return tuple(lst)\n else:\n return tuple([int(not x) for x in lst])\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n from collections import defaultdict\n row_counts = defaultdict(int)\n for row in matrix:\n row_counts[self.convert_to_tuple(row)] += 1\n return max(row_counts.values())", "import collections\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n ans = 1\n orig = collections.defaultdict(int)\n orig_to_xor = {}\n for row in matrix:\n curr_orig = 0\n curr_xor = 0\n for (i, c) in enumerate(row):\n curr_orig ^= c << i\n curr_xor ^= 1 - c << i\n orig[curr_orig] += 1\n orig_to_xor[curr_orig] = curr_xor\n for (curr_orig, curr_xor) in orig_to_xor.items():\n ans = max(orig[curr_orig] + orig[curr_xor], ans) if curr_orig != curr_xor else max(orig[curr_orig], ans)\n return ans", "from collections import Counter\n\ndef maxequalrowsafterflips(matrix):\n counter = Counter()\n flip = {1: 0, 0: 1}\n for row in matrix:\n if row[0] == 0:\n row = [flip[col] for col in row]\n counter[tuple(row)] += 1\n return max(counter.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n seen = defaultdict(int)\n for row in matrix:\n comp = row[0] == 1\n temp = []\n for num in row:\n if comp:\n temp.append(str(num ^ 1))\n else:\n temp.append(str(num))\n seen[''.join(temp)] += 1\n return max(seen.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n (m, n) = (len(matrix), len(matrix[0]))\n for i in range(m):\n if matrix[i][0] == 1:\n for j in range(n):\n matrix[i][j] ^= 1\n cnt = Counter(list(map(tuple, matrix)))\n return max(cnt.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n ans = 0\n for (i, r) in enumerate(matrix):\n count = 0\n flip = [1 - x for x in r]\n for j in range(i, len(matrix)):\n if r == matrix[j] or flip == matrix[j]:\n count += 1\n ans = max(ans, count)\n return ans", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n return max(Counter((tuple((num ^ r[0] for num in r)) for r in matrix)).values())", "def maxequalrowsafterflips(g: List[List[int]]) -> int:\n (rows, cols, d) = (len(g), len(g[0]), {})\n for row in range(rows):\n vct = tuple(g[row])\n d[vct] = d.setdefault(vct, 0) + 1\n res = 0\n for vct in d:\n inv = tuple((el ^ 1 for el in vct))\n if inv in d:\n matches = d[vct] + d[inv]\n else:\n matches = d[vct]\n res = max(res, matches)\n return res", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n seen = set()\n n = len(matrix)\n ans = 0\n for i in range(n):\n m = 0\n for j in range(i, n):\n if j in seen:\n continue\n if matrix[i] == matrix[j] or all((a != b for (a, b) in zip(matrix[i], matrix[j]))):\n seen.add(j)\n m += 1\n ans = max(ans, m)\n return ans", "def maxequalrowsafterflips(m: List[List[int]]) -> int:\n m = [tuple(i) for i in m]\n h = defaultdict(int)\n for i in m:\n if i in h:\n h[i] += 1\n else:\n h[i] = 1\n t = tuple((1 - x for x in i))\n if t in h:\n h[t] += 1\n else:\n h[t] = 1\n return max(h.values())", "def maxequalrowsafterflips(matrix):\n patterns = collections.Counter()\n for row in matrix:\n patterns[tuple(row)] += 1\n flip = [1 - c for c in row]\n patterns[tuple(flip)] += 1\n return max(patterns.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n firstcell = matrix[0][0]\n vals = {}\n for row in matrix:\n firstrowcell = row[0]\n mark = [0, 0]\n mark[firstrowcell] = firstcell\n mark[1 - firstrowcell] = 1 - firstcell\n num = 0\n for cell in row:\n num = num * 2 + mark[cell]\n vals[num] = 1 + vals.get(num, 0)\n maxcount = 0\n for (val, count) in vals.items():\n maxcount = max(count, maxcount)\n return maxcount", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n\n def flipped(r):\n return [1 - c for c in r]\n d = defaultdict(int)\n for r in matrix:\n s = ''.join(map(str, r))\n d[s] += 1\n s = ''.join(map(str, flipped(r)))\n d[s] += 1\n return max(d.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n max_count = 1\n swap_matrix = [[1 - val for val in row] for row in matrix]\n for (idx, row) in enumerate(matrix):\n count = 1\n for nxt_rw in range(idx + 1, len(matrix)):\n if matrix[nxt_rw] == row or matrix[nxt_rw] == swap_matrix[idx]:\n count += 1\n max_count = max(count, max_count)\n return max_count", "def flip_row(row):\n for (i, val) in enumerate(row):\n if val == 0:\n row[i] = 1\n else:\n row[i] = 0\n return row\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n seen = defaultdict(int)\n for (i, row) in enumerate(matrix):\n if tuple(row) in seen or tuple(self.flip_row(row)) in seen:\n seen[tuple(row)] += 1\n else:\n seen[tuple(row)] += 1\n result = 0\n for val in seen.values():\n result = max(result, val)\n return result", "import time\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n flip = []\n flip2 = []\n ma = 0\n for i in matrix:\n temp = [j for j in range(len(i)) if i[j] == 0]\n temp2 = [j for j in range(len(i)) if i[j] == 1]\n flip.append(temp)\n flip2.append(temp2)\n for i in flip:\n if flip.count(i) + flip2.count(i) > ma:\n ma = flip.count(i) + flip2.count(i)\n return ma", "import collections\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n ans = 1\n orig = collections.defaultdict(int)\n orig_to_xor = {}\n for row in matrix:\n curr_orig = int(''.join([str(c) for c in row]), 2)\n curr_xor = int(''.join([str(1 - c) for c in row]), 2)\n orig[curr_orig] += 1\n orig_to_xor[curr_orig] = curr_xor\n for (curr_orig, curr_xor) in orig_to_xor.items():\n ans = max(orig[curr_orig] + orig[curr_xor], ans) if curr_orig != curr_xor else max(orig[curr_orig], ans)\n return ans", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n positions = {}\n max_rows = 0\n for i in range(len(matrix)):\n zeros = []\n ones = []\n for (j, coin) in enumerate(matrix[i]):\n if coin == 0:\n zeros.append(j)\n else:\n ones.append(j)\n zeros = tuple(zeros)\n ones = tuple(ones)\n if 0 in zeros:\n key = (zeros, ones)\n else:\n key = (ones, zeros)\n positions[key] = positions.get(key, 0) + 1\n max_rows = max(max_rows, positions[key])\n return max_rows", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n d = Counter()\n for r in matrix:\n normal = []\n reverse = []\n for v in r:\n normal.append('1' if v else '0')\n reverse.append('0' if v else '1')\n d[''.join(normal)] += 1\n d[''.join(reverse)] += 1\n return max(d.values())", "from collections import defaultdict\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n d = defaultdict(int)\n for row in matrix:\n ori = ''\n inverse = ''\n for c in row:\n ori += str(c)\n inverse += str(1 - c)\n d[ori] += 1\n d[inverse] += 1\n lis = list(d.values())\n return max(lis)", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n if not matrix:\n return 0\n n = len(matrix)\n m = len(matrix[0])\n all_1 = [1] * m\n dic = {}\n for li in matrix:\n if li[0] == 0:\n li = [1 if i == 0 else 0 for i in li]\n s = ''.join([str(i) for i in li])\n if s in dic:\n dic[s] += 1\n else:\n dic[s] = 1\n return max(dic.values())", "import time\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n ma = 0\n for i in matrix:\n flipped = [1 - j for j in i]\n c = matrix.count(i) + matrix.count(flipped)\n if c > ma:\n ma = c\n return ma", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n ma = 0\n for i in matrix:\n c = matrix.count(i) + matrix.count([1 - x for x in i])\n if c > ma:\n ma = c\n return ma", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n flips_for_row = {}\n for row in matrix:\n curr_tuple = str([i for i in range(len(row)) if row[i] == 1])\n if curr_tuple in flips_for_row:\n flips_for_row[curr_tuple] = flips_for_row[curr_tuple] + 1\n else:\n flips_for_row[curr_tuple] = 1\n curr_tuple = str([i for i in range(len(row)) if row[i] == 0])\n if curr_tuple in flips_for_row:\n flips_for_row[curr_tuple] = flips_for_row[curr_tuple] + 1\n else:\n flips_for_row[curr_tuple] = 1\n return max(flips_for_row.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n row = len(matrix)\n col = len(matrix[0])\n ht = {}\n for r in range(row):\n need = [[], []]\n for c in range(col):\n if matrix[r][c] == 0:\n need[0].append(c)\n else:\n need[1].append(c)\n a = str(need[0])\n b = str(need[1])\n if a in ht:\n ht[a] += 1\n else:\n ht[a] = 1\n if b in ht:\n ht[b] += 1\n else:\n ht[b] = 1\n val = list(ht.values())\n ans = max(val)\n return ans", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n ma = 0\n for i in matrix:\n flip = [1 - x for x in i]\n c = 0\n for j in matrix:\n if j == i or j == flip:\n c += 1\n if c > ma:\n ma = c\n return ma", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n (m, n) = (len(matrix), len(matrix[0]))\n cnt = defaultdict(int)\n for i in range(m):\n (s1, s2) = ('', '')\n for j in range(n):\n s1 += str(matrix[i][j])\n s2 += str(1 ^ matrix[i][j])\n cnt[s1] += 1\n cnt[s2] += 1\n return max(list(cnt.values()))", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n flipper = int(''.join([str(bit) for bit in [1] * len(matrix[1])]), 2)\n bits = [int(''.join([str(bit) for bit in row]), 2) for row in matrix]\n mx = 1\n for bit1 in bits:\n count = sum((1 for bit in bits if bit == bit1 or bit1 ^ flipper == bit))\n mx = max(mx, count)\n return mx", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n rm = {}\n for row in matrix:\n r1 = '#'.join([str(x) for x in row])\n r2 = '#'.join(['1' if x == 0 else '0' for x in row])\n if r1 in rm:\n rm[r1] += 1\n elif r2 in rm:\n rm[r2] += 1\n else:\n rm[r1] = 1\n return max(rm.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n count = {}\n for i in range(len(matrix)):\n row = []\n for j in range(len(matrix[0])):\n row.append(matrix[i][j] ^ matrix[i][0])\n k = ''.join(map(str, row))\n if k not in count:\n count[k] = 1\n else:\n count[k] += 1\n res = 0\n for (k, v) in count.items():\n res = max(res, v)\n return res", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n cache = collections.defaultdict(int)\n for row in matrix:\n values = []\n flips = []\n for col in row:\n values.append(col)\n flips.append(1 - col)\n cache[str(values)] += 1\n cache[str(flips)] += 1\n return max(cache.values())", "def __init__():\n self.left = None\n self.right = None\n self.data = -1\n\ndef insert(zero, n, row: List[int], i: int, counts: List[int]) -> int:\n if len(row) == n:\n if self.data == -1:\n self.data = i\n counts[self.data] = 1 + counts[i]\n return i + 1\n else:\n counts[self.data] += 1\n return i\n elif row[n] == zero:\n if self.left is None:\n self.left = Tree()\n return self.left.insert(zero, n + 1, row, i, counts)\n else:\n if self.right is None:\n self.right = Tree()\n return self.right.insert(zero, n + 1, row, i, counts)\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n firstcell = matrix[0][0]\n vals = Tree()\n counts = [0] * 300\n nextfree = 0\n for row in matrix:\n firstrowcell = row[0]\n nextfree = vals.insert(firstcell if firstrowcell == 0 else 1 - firstcell, 0, row, nextfree, counts)\n return max(counts)", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n mod = 10 ** 9 + 7\n d = collections.defaultdict(int)\n (m, n) = (len(matrix), len(matrix[0]))\n for i in range(m):\n t1 = 0\n t2 = 0\n for j in range(n):\n t1 = ((t1 << 1) + matrix[i][j]) % mod\n t2 = ((t2 << 1) + 1 - matrix[i][j]) % mod\n d[t1] += 1\n d[t2] += 1\n return max(d.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n\n def encode(row):\n (i, l) = (row[0], 0)\n result = ''\n result2 = ''\n for j in row:\n if j == i:\n l += 1\n else:\n result += f'{i}{l}'\n result2 += f'{(i + 1) % 2}{l}'\n i = j\n l = 1\n result += f'{i}{l}'\n result2 += f'{(i + 1) % 2}{l}'\n return (result, result2)\n (m, n) = (len(matrix), len(matrix[0]))\n g = {}\n for i in range(m):\n (a, b) = encode(matrix[i])\n if a in g:\n g[a] += 1\n elif b in g:\n g[b] += 1\n else:\n g[a] = g.get(a, 0) + 1\n return max(g.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n ans = 0\n orig = [int(''.join([str(c) for c in row]), 2) for row in matrix]\n xor = [int(''.join([str(1 - c) for c in row]), 2) for row in matrix]\n for i in range(len(matrix)):\n curr = 1\n for j in range(i + 1, len(matrix)):\n is_complement = xor[i] == orig[j]\n is_equal = orig[i] == orig[j]\n curr += int(is_complement or is_equal)\n ans = max(curr, ans)\n return ans", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n hashTab = defaultdict(int)\n (rows, cols) = (len(matrix), len(matrix[0]))\n allOnes = int('1' * cols, 2)\n maxSizeGroup = 0\n for row in matrix:\n val = reduce(lambda a, x: a << 1 ^ x, row)\n if val not in hashTab:\n val ^= allOnes\n hashTab[val] += 1\n maxSizeGroup = max(maxSizeGroup, hashTab[val])\n return maxSizeGroup", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n counts = defaultdict(int)\n for row in matrix:\n counts[tuple(row) if row[0] else tuple((x ^ 1 for x in row))] += 1\n return max(counts.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n options = {tuple([]): 0}\n best = tuple([])\n for i in range(len(matrix)):\n option0 = []\n option1 = []\n for j in range(len(matrix[i])):\n if matrix[i][j] == 1:\n option0.append(j)\n else:\n option1.append(j)\n for option in [tuple(option0), tuple(option1)]:\n if option in options:\n options[option] += 1\n else:\n options[option] = 1\n if options[option] > options[best]:\n best = option\n return options[best]", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n d = Counter()\n for r in matrix:\n normal = []\n reverse = []\n for v in r:\n normal.append(str(v))\n reverse.append(str(1 - v))\n d[''.join(normal)] += 1\n d[''.join(reverse)] += 1\n return max(d.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n n = len(matrix[0])\n matrix = [[str(elem) for elem in row] for row in matrix]\n int_rep_of_matrix = [int(''.join(row), 2) for row in matrix]\n list_of_k = list(int_rep_of_matrix)\n all_ones = 2 ** n - 1\n for elem in int_rep_of_matrix:\n list_of_k.append(elem ^ all_ones)\n answer = 0\n for k in list_of_k:\n current_answer = 0\n for matrix_row in int_rep_of_matrix:\n if matrix_row ^ k == 0 or matrix_row ^ k == all_ones:\n current_answer += 1\n answer = max(answer, current_answer)\n return answer"], "starter_code": "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Hash Table", "Matrix"], "name": null, "source": "leetcode", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "maxequalrowsafterflips", "task_id": "TACO_lite/82", "example": [[[[[0, 1], [1, 1]]], [[[0, 1], [1, 0]]], [[[0, 0, 0], [0, 0, 1], [1, 1, 0]]]], ["1", "2", "2"]]} +{"requirement": "Below is a right-angled triangle:\n\n```\n |\\\n | \\\n | \\\n | \\ \no | \\ h \n | \\\n | θ \\\n |_______\\ \n a\n```\n\nYour challange is to write a function (```missingAngle``` in C/C#, ```missing_angle``` in Ruby), that calculates the angle θ in degrees to the nearest integer. You will be given three arguments representing each side: o, h and a. One of the arguments equals zero. Use the length of the two other sides to calculate θ. You will not be expected to handle any erronous data in your solution.", "solutions": ["import math\n\ndef missing_angle(h, a, o):\n if h == 0:\n radians = math.atan(o / a)\n elif a == 0:\n radians = math.asin(o / h)\n else:\n radians = math.acos(a / h)\n return round(math.degrees(radians))", "from math import asin, acos, atan, degrees as d\nmissing_angle = lambda h, a, o: round(d(atan(o / a) if not h else asin(o / h) if not a else acos(a / h)))", "import math\n\ndef missing_angle(h, a, o):\n return round(math.degrees(math.atan(o / a) if not h else math.asin(o / h) if not a else math.acos(a / h)))", "from math import sqrt, asin, degrees\n\ndef missing_angle(h, a, o):\n (h, o) = (h or sqrt(a ** 2 + o ** 2), o or sqrt(h ** 2 - a ** 2))\n return round(degrees(asin(o / h)))", "from math import asin, acos, atan, pi\n\ndef missing_angle(h, a, o):\n ans = acos(a / h) if h * a else atan(o / a) if a * o else asin(o / h)\n return round(ans * 180 / pi)", "import math\n\ndef missing_angle(h, a, o):\n if h > 0 and a > 0:\n result = math.acos(a / h)\n elif a == 0 and o > 0:\n result = math.asin(o / h)\n elif h == 0 and o > 0:\n result = math.atan(o / a)\n else:\n raise ValueError('Invalid argument(s)')\n return round(math.degrees(result))", "import math\n\ndef missing_angle(h, a, o):\n if not h:\n h = (a ** 2 + o ** 2) ** 0.5\n if not o:\n o = (h ** 2 - a ** 2) ** 0.5\n return round(math.asin(o / h) * 180 / math.pi)"], "starter_code": "def missing_angle(h, a, o):\n", "input_output": {"fn_name": "missing_angle", "inputs": [[0, 400, 300], [5, 4, 0], [8, 0, 5], [16.7, 0, 12.3], [7, 5, 0]], "outputs": [[37], [37], [39], [47], [44]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Geometry"], "name": null, "source": "codewars", "tags": ["Geometry", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/58417e9ab9c25c774500001f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "missing_angle", "task_id": "TACO_lite/89", "example": [[[3, 5, 0], [0, 5, 4], [3, 0, 4]], ["37", "53", "38"]]} +{"requirement": "Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.\n\nExample:\n\n\nInput: \n\n1 0 1 0 0\n1 0 1 1 1\n1 1 1 1 1\n1 0 0 1 0\n\nOutput: 4", "solutions": ["def maximalsquare(matrix):\n if not matrix:\n return 0\n (m, n) = (len(matrix), len(matrix[0]))\n dp = [int(matrix[i][0]) for i in range(m)]\n vmax = max(dp)\n pre = 0\n for j in range(1, n):\n (pre, dp[0]) = (int(matrix[0][j - 1]), int(matrix[0][j]))\n for i in range(1, m):\n cur = dp[i]\n dp[i] = 0 if matrix[i][j] == '0' else min(dp[i - 1], dp[i], pre) + 1\n pre = cur\n vmax = max(vmax, max(dp))\n return vmax ** 2", "def maximalsquare(matrix):\n if len(matrix) == 0 or len(matrix[0]) == 0:\n return 0\n (n, m) = (len(matrix), len(matrix[0]))\n dp = [[0 for i in range(m)] for j in range(n)]\n for i in range(n):\n dp[i][0] = int(matrix[i][0])\n for j in range(m):\n dp[0][j] = int(matrix[0][j])\n for i in range(1, n):\n for j in range(1, m):\n if matrix[i][j] == '1':\n dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1\n ans = 0\n for i in range(n):\n ans = max(ans, max(dp[i]))\n return ans ** 2", "def maximalsquare(matrix):\n if not matrix:\n return 0\n (rows, cols) = (len(matrix), len(matrix[0]))\n dp = list(map(int, matrix[0][:]))\n maxLen = 1 if sum(dp) > 0 else 0\n for i in range(1, rows):\n tmp = dp[0]\n dp[0] = int(matrix[i][0])\n maxLen = max(maxLen, dp[0])\n pre = tmp\n for j in range(1, cols):\n tmp = dp[j]\n if matrix[i][j] == '1':\n dp[j] = min(dp[j], dp[j - 1], pre) + 1\n maxLen = max(maxLen, dp[j])\n else:\n dp[j] = 0\n pre = tmp\n return maxLen * maxLen", "def maximalsquare(matrix):\n if not matrix:\n return 0\n (rows, cols) = (len(matrix), len(matrix[0]))\n dp = [0] * cols\n maxLen = 1 if sum(dp) > 0 else 0\n for i in range(0, rows):\n for j in range(0, cols):\n if matrix[i][j] == '1':\n if j == 0:\n dp[j] = int(matrix[i][j])\n else:\n k = min(dp[j], dp[j - 1])\n dp[j] = k + 1 if matrix[i - k][j - k] == '1' else k\n maxLen = max(maxLen, dp[j])\n else:\n dp[j] = 0\n return maxLen * maxLen", "def maximalsquare(matrix):\n if not matrix or len(matrix) == 0:\n return 0\n m = len(matrix)\n n = len(matrix[0])\n dp = [[0 for i in range(n)] for j in range(m)]\n dp[0] = list(map(lambda x: int(x), matrix[0]))\n maxLength = 1 if 1 in dp[0] else 0\n for i in range(1, m):\n dp[i][0] = int(matrix[i][0])\n if dp[i][0] == 1:\n maxLength = 1\n for i in range(1, m):\n for j in range(1, n):\n if matrix[i][j] == '0':\n dp[i][j] = 0\n else:\n dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1])\n maxLength = max(maxLength, dp[i][j])\n return maxLength ** 2", "def maximalsquare(matrix):\n (m, n) = (len(matrix), len(matrix[0]) if matrix else 0)\n dp = [0] * n\n best = 0\n for r in range(m):\n ndp = [0] * n\n for c in range(n):\n if matrix[r][c] == '1':\n ndp[c] = min(dp[c - 1], dp[c], ndp[c - 1]) + 1 if r and c else 1\n if ndp[c] > best:\n best = ndp[c]\n dp = ndp\n return best ** 2", "def maximalsquare(matrix):\n g = 0\n li = [[0 for a in x] for x in matrix]\n for i in range(0, len(matrix)):\n for j in range(0, len(matrix[0])):\n c = int(matrix[i][j])\n if c == 0:\n li[i][j] = 0\n continue\n if i == 0 or j == 0:\n li[i][j] = c\n if c > g:\n g = c\n continue\n m = min(li[i - 1][j], li[i][j - 1])\n if li[i - 1][j - 1] <= m:\n li[i][j] = 1 + li[i - 1][j - 1]\n else:\n li[i][j] = 1 + m\n if li[i][j] > g:\n g = li[i][j]\n return g ** 2", "def maximalsquare(matrix):\n if len(matrix) == 0 or len(matrix[0]) == 0:\n return 0\n dp = [[0 for i in range(len(matrix[0]))] for i in range(len(matrix))]\n largest = 0\n for i in range(len(matrix)):\n dp[i][0] = int(matrix[i][0])\n largest = max(largest, dp[i][0])\n for j in range(len(matrix[0])):\n dp[0][j] = int(matrix[0][j])\n largest = max(largest, dp[0][j])\n for i in range(1, len(matrix)):\n for j in range(1, len(matrix[0])):\n if matrix[i][j] == '1':\n if dp[i - 1][j] >= dp[i - 1][j - 1] and dp[i][j - 1] >= dp[i - 1][j - 1]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n else:\n dp[i][j] = min(int(dp[i - 1][j]), int(dp[i][j - 1])) + 1\n else:\n dp[i][j] = 0\n largest = max(largest, dp[i][j])\n return largest * largest"], "starter_code": "def maximalsquare(matrix: List[List[str]]) -> int:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Dynamic Programming", "Matrix"], "name": null, "source": "leetcode", "tags": ["Matrices", "Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/maximal-square/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "maximalsquare", "task_id": "TACO_lite/20", "example": [[[[[1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0]]]], ["4"]]} +{"requirement": "Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.\nReturn the number of nice sub-arrays.\n \nExample 1:\nInput: nums = [1,1,2,1,1], k = 3\nOutput: 2\nExplanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].\n\nExample 2:\nInput: nums = [2,4,6], k = 1\nOutput: 0\nExplanation: There is no odd numbers in the array.\n\nExample 3:\nInput: nums = [2,2,2,1,2,2,1,2,2,2], k = 2\nOutput: 16\n\n \nConstraints:\n\n1 <= nums.length <= 50000\n1 <= nums[i] <= 10^5\n1 <= k <= nums.length", "solutions": ["def numberofsubarrays(nums: List[int], k: int) -> int:\n edge = []\n res = 0\n count = 0\n for i in nums:\n if i % 2:\n edge.append(count + 1)\n count = 0\n else:\n count += 1\n edge.append(count + 1)\n if len(edge) - 1 < k:\n return 0\n else:\n for i in range(len(edge) - k):\n res += edge[i] * edge[i + k]\n return res", "def numberofsubarrays(A: List[int], k: int) -> int:\n d = []\n n = len(A)\n res = 0\n count = 1\n for i in range(n):\n if A[i] % 2:\n d.append(count)\n count = 1\n else:\n count += 1\n d.append(count)\n for (x, y) in zip(d, d[k:]):\n res += x * y\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n l = [0] * (len(nums) + 1)\n for (i, n) in enumerate(nums):\n l[i + 1] = l[i] + n % 2\n c = Counter(l)\n return sum((c[x - k] * c[x] for x in c))", "def numberofsubarrays(nums: List[int], k: int) -> int:\n prefix = {0: 1}\n count = 0\n result_count = 0\n for num in nums:\n if num % 2:\n count += 1\n prefix[count] = prefix.get(count, 0) + 1\n result_count += prefix.get(count - k, 0)\n return result_count", "from collections import defaultdict\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n\n def helper(k):\n start = end = counter = res = 0\n while end < len(nums):\n if nums[end] % 2 != 0:\n counter += 1\n end += 1\n while counter > k:\n if nums[start] % 2 != 0:\n counter -= 1\n start += 1\n res += end - start\n return res\n return helper(k) - helper(k - 1)", "from collections import Counter\n\ndef numberofsubarrays(A, k):\n count = Counter([0])\n ans = 0\n psum = 0\n for v in A:\n psum += v % 2\n ans += count[psum - k]\n count[psum] += 1\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n for i in range(len(nums)):\n nums[i] = nums[i] % 2\n mp = defaultdict(int)\n mp[0] = 1\n (csum, ans) = (0, 0)\n for (i, num) in enumerate(nums):\n csum += num\n ans += mp[csum - k]\n mp[csum] += 1\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n i = count = nice_count = odd_count = 0\n for j in range(len(nums)):\n if nums[j] % 2 == 1:\n odd_count += 1\n count = 0\n while odd_count == k:\n odd_count -= nums[i] % 2\n i += 1\n count += 1\n nice_count += count\n return nice_count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n if not nums:\n return 0\n s = []\n evencnt = 0\n for num in nums:\n if num % 2 == 1:\n s.append(evencnt)\n evencnt = 0\n else:\n evencnt += 1\n s.append(evencnt)\n res = 0\n for i in range(len(s) - k):\n res += (s[i] + 1) * (s[i + k] + 1)\n return res", "def numberofsubarrays(nums, k):\n return self.atMost(nums, k) - self.atMost(nums, k - 1)\n\ndef atMost(nums, k):\n if k < 0:\n return 0\n n = len(nums)\n right = 0\n cnt = 0\n res = 0\n for left in range(n):\n while right <= n - 1 and (cnt < k or nums[right] % 2 == 0):\n cnt += nums[right] % 2 == 1\n right += 1\n res += right - left\n cnt -= nums[left] % 2 == 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n blocks = [1]\n for num in nums:\n if num % 2 == 1:\n blocks.append(1)\n continue\n blocks[-1] += 1\n return sum((left * right for (left, right) in zip(blocks, blocks[k:])))", "def solve(A, k):\n count = [0, 0]\n front = iter(A)\n ans = 0\n size = 0\n for v in A:\n count[v % 2] += 1\n size += 1\n while count[1] > k:\n count[next(front) % 2] -= 1\n size -= 1\n ans += size\n return ans\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n return solve(nums, k) - solve(nums, k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n data = []\n curr = 0\n L = 0\n count = 0\n for num in nums:\n if num % 2 == 0:\n curr += 1\n else:\n L += 1\n data.append(curr)\n curr = 0\n if L < k:\n return 0\n end = 0\n for i in range(len(nums) - 1, -1, -1):\n if nums[i] % 2 == 1:\n break\n end += 1\n for i in range(k - 1, L - 1):\n count += (data[i - k + 1] + 1) * (data[i + 1] + 1)\n return count + (end + 1) * (data[-k] + 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def at_most(nums, k):\n (i, j, count, res) = (0, 0, 0, 0)\n while j < len(nums):\n if nums[j] % 2 == 1:\n count += 1\n while count > k:\n if nums[i] % 2 == 1:\n count -= 1\n i += 1\n res += j - i + 1\n j += 1\n return res\n return at_most(nums, k) - at_most(nums, k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n odds = [-1]\n for i in range(len(nums)):\n if nums[i] & 1:\n odds.append(i)\n odds.append(len(nums))\n (i, count) = (1, 0)\n while i + k - 1 < len(odds) - 1:\n count += (odds[i] - odds[i - 1]) * (odds[i + k] - odds[i + k - 1])\n i += 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n occur = collections.defaultdict(int)\n occur[0] = 1\n runsum = 0\n count = 0\n for i in range(len(nums)):\n if nums[i] % 2 == 0:\n nums[i] = 0\n else:\n nums[i] = 1\n runsum += nums[i]\n if runsum - k in occur:\n count += occur[runsum - k]\n occur[runsum] += 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n s = 0\n e = 0\n l = len(nums)\n total = 0\n num_odd = 0\n ae = 0\n while s < l:\n while e < l and num_odd != k:\n if nums[e] % 2 != 0:\n num_odd += 1\n e += 1\n if num_odd == k:\n if ae < e:\n ae = e\n while ae < l and nums[ae] % 2 == 0:\n ae += 1\n total += ae - (e - 1)\n if nums[s] % 2 != 0:\n num_odd -= 1\n s += 1\n return total", "def numberofsubarrays(nums: List[int], k: int) -> int:\n num_odds = defaultdict(int, {0: 1})\n total = 0\n running = 0\n for n in nums:\n running += n % 2\n total += num_odds[running - k]\n num_odds[running] += 1\n return total", "from collections import defaultdict\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n seen = defaultdict(int)\n seen[0] = 1\n output = 0\n odds = 0\n for i in range(0, len(nums)):\n if nums[i] % 2 != 0:\n odds += 1\n if odds - k in seen:\n output += seen[odds - k]\n seen[odds] += 1\n return output", "def numberofsubarrays(nums: List[int], k: int) -> int:\n num_nice = 0\n i = 0\n count = 0\n for num in nums:\n if num & 1:\n k -= 1\n count = 0\n while k == 0:\n k += nums[i] & 1\n count += 1\n i += 1\n num_nice += count\n return num_nice", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atMost(k):\n (l, result) = (0, 0)\n for i in range(len(nums)):\n k -= nums[i] % 2\n while k < 0:\n k += nums[l] % 2\n l += 1\n result += i - l + 1\n return result\n return atMost(k) - atMost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n output = 0\n count_odd = 0\n l = 0\n for (r, n) in enumerate(nums):\n count_odd += int(n % 2 == 1)\n if count_odd == k:\n n_even = 1\n for j in range(r + 1, len(nums)):\n if nums[j] % 2 == 0:\n n_even += 1\n else:\n break\n while count_odd == k:\n output += n_even\n count_odd -= int(nums[l] % 2 == 1)\n l += 1\n return output", "def numberofsubarrays(nums: List[int], k: int) -> int:\n cnt = 0\n d = {}\n d[0] = 1\n for i in nums:\n if i % 2:\n cnt += 1\n if cnt in d:\n d[cnt] += 1\n else:\n d[cnt] = 1\n ans = 0\n for key in d:\n if k + key in d:\n ans += d[key] * d[k + key]\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n cur = res = i = 0\n for j in range(len(nums)):\n if nums[j] % 2 != 0:\n k -= 1\n if k == 0:\n cur = 1\n while nums[i] % 2 == 0:\n cur += 1\n i += 1\n k += 1\n i += 1\n res += cur\n else:\n res += cur\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n return self.sol1(nums, k) - self.sol1(nums, k - 1)\n\ndef sol1(nums, k):\n start = 0\n odds = 0\n res = 0\n for end in range(len(nums)):\n odds += nums[end] & 1\n while odds > k:\n odds -= nums[start] & 1\n start += 1\n res += end - start + 1\n return res\n\ndef sol2(nums, k):\n start = 0\n odds = 0\n res = 0\n count = 0\n for end in range(len(nums)):\n if nums[end] & 1:\n odds += 1\n count = 0\n while odds >= k:\n if nums[start] & 1:\n odds -= 1\n start += 1\n count += 1\n res += count\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atMost(k):\n count = i = res = 0\n for (j, v) in enumerate(nums):\n if v % 2:\n count += 1\n while count > k:\n if nums[i] % 2:\n count -= 1\n i += 1\n res += j - i + 1\n return res\n return atMost(k) - atMost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atmost(k):\n res = i = 0\n for j in range(len(nums)):\n k -= nums[j] % 2\n while k < 0:\n k += nums[i] % 2\n i += 1\n res += j - i + 1\n return res\n return atmost(k) - atmost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n num_odd_numbers = 0\n foo = 0\n left = 0\n right = 0\n count = 0\n num_nice_arrays = 0\n while right < len(nums):\n r_n = nums[right]\n if r_n % 2 == 1:\n count = 0\n num_odd_numbers += 1\n while num_odd_numbers == k:\n l_n = nums[left]\n if l_n % 2 == 1:\n num_odd_numbers -= 1\n left += 1\n count += 1\n num_nice_arrays += count\n right += 1\n return num_nice_arrays", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def AtMostK(k):\n left = 0\n count = 0\n currK = 0\n for index in range(len(nums)):\n if nums[index] % 2 == 1:\n currK += 1\n while currK > k:\n if nums[left] % 2 == 1:\n currK -= 1\n left += 1\n count += index - left + 1\n return count\n return AtMostK(k) - AtMostK(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n n = len(nums)\n noOfNiceSubArrays = 0\n even = 0\n oddList = []\n for i in range(n):\n if nums[i] % 2 == 0:\n even += 1\n else:\n oddList.append(even)\n even = 0\n oddList.append(even)\n for i in range(len(oddList) - k):\n noOfNiceSubArrays += (oddList[i] + 1) * (oddList[i + k] + 1)\n return noOfNiceSubArrays", "def numberofsubarrays(nums: List[int], k: int) -> int:\n odds = [0] * len(nums)\n n = len(nums)\n d = {}\n if nums[0] % 2 == 1:\n odds[0] = 1\n else:\n odds[0] = 0\n odds = [0] + odds\n d[0] = d.setdefault(0, []) + [0]\n count = 0\n for i in range(1, n + 1):\n if nums[i - 1] % 2 == 1:\n odds[i] = odds[i - 1] + 1\n else:\n odds[i] = odds[i - 1]\n if odds[i] - k in d:\n count += len(d[odds[i] - k])\n d[odds[i]] = d.setdefault(odds[i], []) + [i]\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def helper(k):\n ans = i = 0\n for j in range(len(nums)):\n k -= nums[j] % 2\n while k < 0:\n k += nums[i] % 2\n i += 1\n ans += j - i + 1\n return ans\n return helper(k) - helper(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n return self.numberOfAtmostK(nums, k) - self.numberOfAtmostK(nums, k - 1)\n\ndef numberOfAtmostK(nums, k):\n (l, r, count, res) = (0, 0, 0, 0)\n while r < len(nums):\n if nums[r] % 2 == 1:\n count += 1\n while count > k:\n if nums[l] % 2 == 1:\n count -= 1\n l += 1\n res += r - l + 1\n r += 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def at_most(nums, k):\n cnts = l = res = 0\n for r in range(len(nums)):\n cnts += nums[r] % 2\n while cnts > k:\n cnts -= nums[l] % 2\n l += 1\n res += r - l + 1\n return res\n return at_most(nums, k) - at_most(nums, k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n i = count = res = 0\n for j in range(len(nums)):\n if nums[j] & 1:\n k -= 1\n count = 0\n while k == 0:\n k += nums[i] & 1\n i += 1\n count += 1\n res += count\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n prefix_odd = defaultdict(int)\n prefix_odd[0] = 1\n ans = count = 0\n for num in nums:\n if num % 2:\n count += 1\n prefix_odd[count] += 1\n for p in prefix_odd:\n if p - k in prefix_odd:\n ans += prefix_odd[p] * prefix_odd[p - k]\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n last = 0\n hsh = {}\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n nums[i] = 1\n else:\n nums[i] = 0\n nums[i] += last\n last = nums[i]\n if nums[i] not in hsh:\n hsh[nums[i]] = []\n hsh[nums[i]].append(i)\n count = 0\n if k in hsh:\n count = len(hsh[k])\n for i in range(len(nums)):\n x = nums[i]\n if x + k in hsh:\n for v in hsh[x + k][::-1]:\n if v < i:\n break\n count += 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n (prefix, odd_cnt, ans) = ({0: 1}, 0, 0)\n for num in nums:\n if num % 2 == 1:\n odd_cnt += 1\n prefix[odd_cnt] = prefix.get(odd_cnt, 0) + 1\n if odd_cnt - k in prefix:\n ans += prefix[odd_cnt - k]\n return ans", "from collections import defaultdict\n\ndef numberofsubarrays(A, k):\n i = count = res = 0\n for j in range(len(A)):\n if A[j] & 1:\n k -= 1\n count = 0\n while k == 0:\n k += A[i] & 1\n i += 1\n count += 1\n res += count\n return res", "def numberofsubarrays(A: List[int], B: int) -> int:\n import collections\n (q, k, temp, count) = (collections.deque(), 0, 0, 0)\n if B == 0:\n for i in range(len(A)):\n if A[i] % 2 == 0:\n temp = temp + 1\n elif A[i] % 2 != 0:\n count = count + int(temp * (temp + 1) / 2)\n temp = 0\n count = count + int(temp * (temp + 1) / 2)\n return count\n while len(q) < B and k < len(A):\n if A[k] % 2 == 0:\n temp = temp + 1\n elif A[k] % 2 == 1:\n q.append(temp)\n temp = 0\n k = k + 1\n if len(q) < B:\n return 0\n temp = 0\n for i in range(k, len(A)):\n if A[i] % 2 == 0:\n temp = temp + 1\n elif A[i] % 2 != 0:\n count = count + (q[0] + 1) * (temp + 1)\n q.append(temp)\n q.popleft()\n temp = 0\n count = count + (q[0] + 1) * (temp + 1)\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n prefix = collections.defaultdict(int)\n prefix[0] = 1\n pre = ans = 0\n for n in nums:\n pre += n & 1\n prefix[pre] += 1\n ans += prefix[pre - k]\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n idxes = []\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n idxes.append(i)\n if len(idxes) < k:\n return 0\n res = 0\n for i in range(k - 1, len(idxes)):\n l = -1 if i - k + 1 == 0 else idxes[i - k]\n r = len(nums) if i == len(idxes) - 1 else idxes[i + 1]\n res += (idxes[i - k + 1] - l) * (r - idxes[i])\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n dic = {0: 1}\n count = 0\n nice = 0\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n count += 1\n if count - k in dic:\n nice += dic[count - k]\n dic[count] = dic.get(count, 0) + 1\n return nice", "def numberofsubarrays(nums: List[int], k: int) -> int:\n res = 0\n i = j = 0\n while i <= j:\n while k > 0 and j < len(nums):\n if nums[j] % 2 == 1:\n k -= 1\n j += 1\n if k != 0:\n return res\n res += 1\n t = j\n while t < len(nums):\n if nums[t] % 2 == 0:\n res += 1\n t += 1\n else:\n break\n if nums[i] % 2 == 1:\n k += 1\n i += 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n deque = collections.deque()\n deque.append(1)\n ans = 0\n for num in nums:\n if num % 2 == 0:\n deque[-1] += 1\n continue\n if len(deque) == k + 1:\n ans += deque[0] * deque[-1]\n deque.popleft()\n deque.append(1)\n if len(deque) == k + 1:\n ans += deque[0] * deque[-1]\n return ans", "from collections import Counter\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n count = Counter([0])\n ans = 0\n psum = 0\n for v in map(lambda x: x % 2, nums):\n psum += v\n ans += count[psum - k]\n count[psum] += 1\n return ans", "def solve(A, k):\n count = [0, 0]\n lower = (x % 2 for x in A)\n ans = 0\n for x in (x % 2 for x in A):\n count[x] += 1\n while count[1] > k:\n count[next(lower)] -= 1\n ans += sum(count)\n return ans\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n return solve(nums, k) - solve(nums, k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n left = collections.defaultdict(int)\n odd = 0\n res = 0\n for n in nums:\n left[odd] += 1\n odd += n & 1\n if odd - k in left:\n res += left[odd - k]\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n nums = [n % 2 for n in nums]\n\n def atMost(k):\n (ans, j) = (0, 0)\n for (i, n) in enumerate(nums):\n k -= n\n while k < 0:\n k += nums[j]\n j += 1\n ans += i - j + 1\n return ans\n return atMost(k) - atMost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n odd_count = tmp_count = j = 0\n final_count = 0\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n odd_count += 1\n tmp_count = 0\n while odd_count == k:\n odd_count -= nums[j] % 2\n j += 1\n tmp_count += 1\n final_count += tmp_count\n return final_count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n cache = {0: [-1]}\n cnt = 0\n odds = 0\n for (i, num) in enumerate(nums):\n if num % 2:\n odds += 1\n if odds - k in cache:\n cnt += len(cache[odds - k])\n x = cache.setdefault(odds, [])\n x.append(odds)\n return cnt", "def numberofsubarrays(nums: List[int], k: int) -> int:\n d = collections.defaultdict(int)\n d[0] = 1\n cur_sum = 0\n ans = 0\n for (i, v) in enumerate(nums):\n cur_sum += v % 2\n if cur_sum - k in d:\n ans += d[cur_sum - k]\n d[cur_sum] += 1\n return ans", "from collections import deque\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n nums.append(1)\n odds = deque()\n odds.append(-1)\n total = 0\n for (i, val) in enumerate(nums):\n if val % 2:\n odds.append(i)\n if len(odds) > k + 2:\n odds.popleft()\n if len(odds) == k + 2:\n total += (odds[1] - odds[0]) * (odds[-1] - odds[-2])\n return total", "def numberofsubarrays(nums: List[int], k: int) -> int:\n odd_pos = [pos for (pos, e) in enumerate(nums) if e % 2 == 1]\n if len(odd_pos) < k:\n return 0\n spaces = []\n prev_pos = -1\n for pos in odd_pos:\n spaces.append(pos - prev_pos)\n prev_pos = pos\n spaces.append(len(nums) - prev_pos)\n res = 0\n for i in range(len(spaces) - k):\n res += spaces[i] * spaces[i + k]\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n temp_arr = []\n temp_count = 0\n for n in nums:\n if n % 2 != 0:\n temp_arr.append(temp_count)\n temp_count = 0\n else:\n temp_count = temp_count + 1\n temp_arr.append(temp_count)\n if len(temp_arr) - 1 < k:\n return 0\n i = k - 1\n count = 0\n while i < len(temp_arr) - 1:\n start_len = temp_arr[i - k + 1] + 1\n end_len = temp_arr[i + 1] + 1\n count = count + start_len * end_len\n i = i + 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n (front, end) = (0, 0)\n tot = 0\n output = 0\n ct = 0\n while end < len(nums):\n if 1 & nums[end]:\n tot += 1\n ct = 0\n end += 1\n while tot == k:\n tot -= nums[front] & 1\n front += 1\n ct += 1\n output += ct\n return output", "def numberofsubarrays(nums: List[int], k: int) -> int:\n cnt = 0\n accNum = {}\n ans = 0\n accNum[0] = 1\n for x in nums:\n if x % 2:\n cnt += 1\n if cnt not in accNum:\n accNum[cnt] = 1\n else:\n accNum[cnt] += 1\n if cnt - k in accNum:\n ans += accNum[cnt - k]\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n aDict = collections.defaultdict(int)\n aDict[0] = 1\n aSum = 0\n result = 0\n for i in nums:\n if i % 2 == 1:\n aSum += 1\n if aSum - k in aDict:\n result += aDict[aSum - k]\n aDict[aSum] += 1\n return result", "def numberofsubarrays(A: List[int], k: int) -> int:\n d = []\n res = 0\n count = 1\n for a in A:\n if a % 2:\n d.append(count)\n count = 1\n else:\n count += 1\n d.append(count)\n for (x, y) in zip(d, d[k:]):\n res += x * y\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n n = len(nums)\n if k > n:\n return 0\n ans = 0\n p1 = p2 = p3 = p4 = -1\n while p4 < n:\n p2 += 1\n while p2 < n and nums[p2] % 2 == 0:\n p2 += 1\n if p2 == n:\n return ans\n if p4 == -1:\n p3 = p2\n remaining = k - 1\n while p3 < n and remaining:\n p3 += 1\n if p3 == n:\n return ans\n if nums[p3] % 2 == 1:\n remaining -= 1\n else:\n p3 = p4\n p4 = p3 + 1\n while p4 < n:\n if nums[p4] % 2 == 1:\n break\n p4 += 1\n ans += (p2 - p1) * (p4 - p3)\n p1 = p2\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n memo = {0: 1}\n count = 0\n res = 0\n for n in nums:\n if n % 2 == 1:\n count += 1\n if count - k in memo:\n res += memo[count - k]\n memo[count] = memo.get(count, 0) + 1\n return res", "def checkOdd(num):\n if num % 2 == 0:\n return False\n return True\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n oddIndices = []\n for i in range(len(nums)):\n if self.checkOdd(nums[i]):\n oddIndices.append(i)\n start = 0\n end = k - 1\n i = 0\n count = 0\n while end < len(oddIndices):\n if end == len(oddIndices) - 1:\n j = len(nums) - 1\n else:\n j = oddIndices[end + 1] - 1\n count = count + (oddIndices[start] - i + 1) * (j - oddIndices[end] + 1)\n i = oddIndices[start] + 1\n start = start + 1\n end = end + 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n prefix_sum = 0\n dict_odds = {0: 1}\n rs = 0\n for (i, num) in enumerate(nums):\n if num % 2 == 1:\n prefix_sum += 1\n if prefix_sum not in dict_odds:\n dict_odds[prefix_sum] = 1\n else:\n dict_odds[prefix_sum] = dict_odds[prefix_sum] + 1\n if prefix_sum - k in dict_odds:\n rs += dict_odds[prefix_sum - k]\n return rs", "def numberofsubarrays(nums: List[int], k: int) -> int:\n index_list = []\n index_list.append(-1)\n for i in range(0, len(nums)):\n if nums[i] % 2 == 1:\n index_list.append(i)\n index_list.append(len(nums))\n if len(index_list) == 0:\n return 0\n left = 1\n right = 1\n k_count = 1\n count = 0\n while right < len(index_list) - 1:\n if k_count == k:\n count += (index_list[left] - index_list[left - 1]) * (index_list[right + 1] - index_list[right])\n left += 1\n k_count -= 1\n else:\n k_count += 1\n right += 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n num_odd = 0\n start = 0\n output = 0\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n num_odd += 1\n while num_odd > k:\n if nums[start] % 2 == 1:\n num_odd -= 1\n start += 1\n if num_odd == k:\n output += 1\n cur_start = start\n while nums[cur_start] % 2 == 0:\n cur_start += 1\n output += 1\n return output", "def numberofsubarrays(nums: List[int], k: int) -> int:\n adict = {0: 1}\n x = 0\n result = 0\n for i in nums:\n if i & 1 != 0:\n x += 1\n if x - k in adict:\n result += adict[x - k]\n adict[x] = adict.get(x, 0) + 1\n return result", "def numberofsubarrays(nums: List[int], k: int) -> int:\n rr = l = r = res = cnt = 0\n ll = -1\n n = len(nums)\n while r < n:\n x = nums[r]\n if x % 2:\n if ll < l:\n ll = r\n cnt += 1\n if cnt == k:\n rr = r\n while r < n - 1 and nums[r + 1] % 2 == 0:\n r += 1\n res += (ll - l + 1) * (r - rr + 1)\n l = ll + 1\n cnt -= 1\n ll += 1\n while ll < n and nums[ll] % 2 == 0:\n ll += 1\n r += 1\n return res", "from collections import defaultdict\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n if len(nums) < k:\n return 0\n num_odd = 0\n seen = defaultdict(int)\n seen[0] = 1\n ret = 0\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n num_odd += 1\n key = num_odd - k\n ret += seen[key]\n seen[num_odd] += 1\n return ret", "def numberofsubarrays(A: List[int], k: int) -> int:\n d = []\n res = 0\n count = 1\n for a in A:\n if a % 2:\n d.append(count)\n count = 1\n else:\n count += 1\n d.append(count)\n m = len(d)\n for i in range(m - k):\n res += d[i] * d[i + k]\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n count = 0\n dic = defaultdict(int)\n dic[0] = 1\n ans = 0\n for i in range(1, len(nums) + 1):\n count += nums[i - 1] % 2\n if count - k in list(dic.keys()):\n ans += dic[count - k]\n dic[count] += 1\n return ans", "def isOdd(num):\n return num % 2 == 1\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n items = [-1]\n for (i, num) in enumerate(nums):\n if isOdd(num):\n items.append(i)\n cnt = 0\n items.append(len(nums))\n for i in range(1, len(items) - 1):\n if i + k - 1 < len(items) - 1:\n left = items[i] - items[i - 1]\n right = items[i + k] - items[i + k - 1]\n cnt += left * right\n return cnt", "def numberofsubarrays(nums: List[int], k: int) -> int:\n flattened = [1 if num % 2 == 1 else 0 for num in nums]\n d = {0: 1}\n sum = 0\n total = 0\n for i in range(len(flattened)):\n sum += flattened[i]\n total += d.get(sum - k, 0)\n d[sum] = d.get(sum, 0) + 1\n return total", "from collections import Counter\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n oddCounts = []\n oddCount = 0\n for num in nums:\n if num % 2 == 1:\n oddCount += 1\n oddCounts.append(oddCount)\n oddCountsIdxs = Counter(oddCounts)\n nice = 0\n for num in oddCounts:\n nice += oddCountsIdxs[num - k]\n nice += oddCountsIdxs[k]\n return nice", "def numberofsubarrays(nums: List[int], k: int) -> int:\n nums = [i % 2 for i in nums]\n ans = 0\n tmp = 0\n n = len(nums)\n l = 0\n for r in range(n):\n if nums[r] == 1:\n k -= 1\n tmp = 0\n while k == 0:\n k += nums[l]\n l += 1\n tmp += 1\n ans += tmp\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n ln = len(nums)\n ret = 0\n for i in range(ln):\n if nums[i] % 2:\n nums[i] = 1\n else:\n nums[i] = 0\n mp = {0: 1}\n cnt = 0\n for n in nums:\n cnt += n\n if cnt not in mp:\n mp[cnt] = 0\n mp[cnt] += 1\n if cnt - k in mp:\n ret += mp[cnt - k]\n return ret\n pass", "def numberofsubarrays(nums: List[int], k: int) -> int:\n ans = 0\n d = {0: 0}\n start = {}\n cumsum = 0\n for (i, num) in enumerate(nums):\n cumsum += num % 2\n d[cumsum] = i + 1\n if cumsum not in start:\n start[cumsum] = i\n if cumsum == k:\n elems = d[0]\n ans += elems + 1\n elif cumsum > k:\n elems = d[cumsum - k] - start.get(cumsum - k, -1)\n ans += elems\n return ans", "from collections import deque\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n (d, res) = (deque(), 0)\n d.append(-1)\n for i in range(0, len(nums)):\n if nums[i] % 2 == 1:\n d.append(i)\n if len(d) > k + 1:\n d.popleft()\n if len(d) == k + 1:\n a = d.popleft()\n b = d.popleft()\n res += b - a\n d.appendleft(b)\n d.appendleft(a)\n return res", "from collections import Counter\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n lookup = Counter()\n lookup[0] = 1\n answer = accumulated_odd = 0\n for num in nums:\n if num % 2 == 1:\n accumulated_odd += 1\n answer += lookup[accumulated_odd - k]\n lookup[accumulated_odd] += 1\n return answer", "def numberofsubarrays(nums: List[int], k: int) -> int:\n oddnum = 0\n (l, n) = (0, len(nums))\n add = 1\n sums = 0\n for r in range(n):\n if nums[r] % 2 == 1:\n k -= 1\n while l < r and (k < 0 or nums[l] % 2 == 0):\n if k < 0:\n add = 1\n else:\n add += 1\n if nums[l] % 2 == 1:\n k += 1\n l += 1\n if k == 0:\n sums += add\n return sums", "from collections import Counter\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n lookup = Counter()\n lookup[0] = 1\n answer = accumulated_sum = 0\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n accumulated_sum += 1\n answer += lookup[accumulated_sum - k]\n lookup[accumulated_sum] += 1\n return answer", "def numberofsubarrays(nums: List[int], k: int) -> int:\n if not nums:\n return 0\n return self.atMostK(nums, k) - self.atMostK(nums, k - 1)\n\ndef atMostK(nums, k):\n count = 0\n left = 0\n for (right, right_num) in enumerate(nums):\n k -= right_num % 2\n while k < 0:\n k += nums[left] % 2\n left += 1\n count += right - left + 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n memo = collections.Counter()\n memo[0] = 1\n res = odds = 0\n for x in nums:\n if x % 2:\n odds += 1\n memo[odds] += 1\n res += memo[odds - k]\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atMost(A: List[int], k: int) -> int:\n i = ret = 0\n for j in range(len(A)):\n if A[j] & 1:\n k -= 1\n while k < 0:\n k += A[i] & 1\n i += 1\n ret += j - i + 1\n return ret\n return atMost(nums, k) - atMost(nums, k - 1)", "def numberofsubarrays(A: List[int], k: int) -> int:\n\n def atMost(k):\n (res, lo) = (0, 0)\n for hi in range(len(A)):\n k -= A[hi] % 2\n while k < 0:\n k += A[lo] % 2\n lo += 1\n res += hi - lo + 1\n return res\n return atMost(k) - atMost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n return self.newConcept(nums, k) - self.newConcept(nums, k - 1)\n\ndef newConcept(nums, k):\n ans = 0\n left = 0\n c = 0\n for i in range(len(nums)):\n if nums[i] % 2 != 0:\n c += 1\n while c > k:\n if nums[left] % 2 != 0:\n c -= 1\n left += 1\n ans += i - left + 1\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atMost(m):\n if m < 0:\n return 0\n left = res = 0\n for (right, x) in enumerate(nums):\n m -= x & 1\n while m < 0:\n m += nums[left] & 1\n left += 1\n res += right - left + 1\n return res\n return atMost(k) - atMost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n arr = list(map(lambda x: x % 2, nums))\n n = len(arr)\n arr = [0] + list(itertools.accumulate(arr))\n hm = Counter()\n res = 0\n for i in arr:\n res += hm[i]\n hm[i + k] += 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def at_most(k):\n left = 0\n count = 0\n res = 0\n for right in range(len(nums)):\n if nums[right] & 1:\n count += 1\n while count > k and left <= right:\n if nums[left] & 1:\n count -= 1\n left += 1\n res += right - left + 1\n return res\n return at_most(k) - at_most(k - 1)", "def numberofsubarrays(A, k):\n\n def atMost(k):\n res = i = 0\n for j in range(len(A)):\n k -= A[j] % 2\n while k < 0:\n k += A[i] % 2\n i += 1\n res += j - i + 1\n return res\n return atMost(k) - atMost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n positions = [-1]\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n positions.append(i)\n positions.append(len(nums))\n total = 0\n for i in range(1, len(positions) - k):\n num_before = positions[i] - positions[i - 1]\n num_after = positions[i + k] - positions[i + k - 1]\n total += num_before * num_after\n return total", "def addOrIncrement(key, dictionary):\n if key in dictionary:\n dictionary[key] += 1\n else:\n dictionary[key] = 1\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n n = len(nums)\n if n < k:\n return 0\n ans = 0\n seen = {0: 1}\n curVal = 0\n for num in nums:\n curVal += 0 if num % 2 == 0 else 1\n if curVal - k in seen:\n ans += seen[curVal - k]\n self.addOrIncrement(curVal, seen)\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n n = len(nums)\n left_left = 0\n left_right = 0\n odds_left = 0\n odds_right = 0\n odds = 0\n ret = 0\n for right in range(n):\n odds_left += nums[right] % 2\n odds_right += nums[right] % 2\n while left_left <= right and odds_left > k:\n odds_left -= nums[left_left] % 2\n left_left += 1\n while left_right <= right and odds_right - nums[left_right] % 2 >= k:\n odds_right -= nums[left_right] % 2\n left_right += 1\n if odds_left == odds_right == k:\n ret += left_right - left_left + 1\n return ret", "def numberofsubarrays(nums: List[int], k: int) -> int:\n return self.at_most(nums, k) - self.at_most(nums, k - 1)\n\ndef at_most(nums, k):\n i = 0\n res = 0\n for (j, val) in enumerate(nums):\n if val & 1 == 1:\n k -= 1\n while k < 0:\n if nums[i] & 1 == 1:\n k += 1\n i += 1\n res += j - i + 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n cache = collections.Counter({0: 1})\n (res, cnt_odd) = (0, 0)\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n cnt_odd += 1\n res += cache.get(cnt_odd - k, 0)\n cache[cnt_odd] += 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n count = 0\n left = 0\n right = 0\n odd = 0\n while right < len(nums):\n if nums[right] % 2 == 1:\n odd += 1\n while left < right and odd > k:\n if nums[left] % 2 == 1:\n odd -= 1\n left += 1\n if odd == k:\n count += 1\n i = left\n while i < right and odd == k and (nums[i] % 2 == 0):\n count += 1\n i += 1\n right += 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n if not nums:\n return 0\n ans = 0\n cnt = 0\n lo = 0\n hi = 0\n cnt += nums[0] % 2\n while lo <= hi and hi < len(nums):\n if cnt < k:\n hi += 1\n if hi < len(nums) and nums[hi] % 2:\n cnt += 1\n elif cnt > k:\n if lo < hi and nums[lo] % 2:\n cnt -= 1\n lo += 1\n else:\n ans += 1\n tempHi = hi\n while tempHi + 1 < len(nums) and nums[tempHi + 1] % 2 == 0:\n ans += 1\n tempHi += 1\n if lo < len(nums) and nums[lo] % 2:\n cnt -= 1\n lo += 1\n if hi < lo:\n hi = lo\n if hi < len(nums) and nums[hi] % 2:\n cnt += 1\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atMost(K):\n (b, e) = (0, 0)\n ret = 0\n while e < len(nums):\n K -= nums[e] % 2\n while K < 0:\n K += nums[b] % 2\n b += 1\n ret += e - b + 1\n e += 1\n return ret\n return atMost(k) - atMost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def at_most(k):\n start_ptr = 0\n result = 0\n for end_ptr in range(len(nums)):\n k -= nums[end_ptr] % 2\n while k < 0:\n k += nums[start_ptr] % 2\n start_ptr += 1\n result += end_ptr - start_ptr + 1\n return result\n return at_most(k) - at_most(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n (l, r, oddsCounter, res) = (0, 0, 0, 0)\n while r < len(nums):\n if nums[r] % 2 == 1:\n oddsCounter += 1\n while oddsCounter > k:\n if nums[l] % 2 == 1:\n oddsCounter -= 1\n l += 1\n if oddsCounter == k:\n res += 1\n i = l\n while oddsCounter == k and i < r and (nums[i] % 2 == 0):\n res += 1\n i += 1\n r += 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n j = i = count = ret = 0\n for n in nums:\n if n % 2:\n count += 1\n if count == k:\n i = j\n while count == k:\n count -= 1 if nums[j] % 2 else 0\n j += 1\n ret += j - i\n return ret", "def numberofsubarrays(nums: List[int], k: int) -> int:\n left_pointer = 0\n right_pointer = -1\n count = 0\n odd = 0\n while right_pointer < len(nums) - 1:\n right_pointer += 1\n if nums[right_pointer] % 2 == 1:\n odd += 1\n if odd == k:\n left_side = 1\n right_side = 1\n while right_pointer < len(nums) - 1 and nums[right_pointer + 1] % 2 == 0:\n right_side += 1\n right_pointer += 1\n while left_pointer <= right_pointer and nums[left_pointer] % 2 == 0:\n left_side += 1\n left_pointer += 1\n count += left_side * right_side\n left_pointer += 1\n odd -= 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n return self.atMost(nums, k) - self.atMost(nums, k - 1)\n\ndef atMost(nums, k):\n res = left = 0\n odds = 0\n for right in range(len(nums)):\n if nums[right] % 2 == 1:\n k -= 1\n while k < 0:\n if nums[left] % 2 == 1:\n k += 1\n left += 1\n res += right - left + 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def at_most(k):\n num_odd = res = i = 0\n for (j, v) in enumerate(nums):\n if v % 2 != 0:\n num_odd += 1\n while num_odd > k:\n if nums[i] % 2 == 1:\n num_odd -= 1\n i += 1\n res += j - i + 1\n return res\n return at_most(k) - at_most(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n for i in range(len(nums)):\n if nums[i] % 2 == 0:\n nums[i] = 0\n else:\n nums[i] = 1\n pre = [0]\n for c in nums:\n pre.append(pre[-1] + c)\n res = 0\n dic = {}\n for c in pre:\n if c - k in dic:\n res += dic[c - k]\n if c not in dic:\n dic[c] = 1\n else:\n dic[c] += 1\n return res", "def atMostK(nums, k):\n start = 0\n end = 0\n count = 0\n for end in range(len(nums)):\n if nums[end] % 2 == 1:\n k -= 1\n while k < 0:\n if nums[start] % 2 == 1:\n k += 1\n start += 1\n count += end - start + 1\n return count\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n if not nums or len(nums) == 0 or k > len(nums):\n return 0\n odds = 0\n return self.atMostK(nums, k) - self.atMostK(nums, k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n d = {0: 1}\n s = 0\n count = 0\n for i in range(len(nums)):\n nums[i] %= 2\n s += nums[i]\n if not s in d:\n d[s] = 0\n d[s] += 1\n if s - k in d:\n count += d[s - k]\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atMostK(nums, K):\n res = 0\n b = 0\n oddCount = 0\n for e in range(len(nums)):\n oddCount += int(nums[e] % 2 == 1)\n while oddCount > K:\n oddCount -= int(nums[b] % 2 == 1)\n b += 1\n res += e - b + 1\n return res\n return atMostK(nums, k) - atMostK(nums, k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n n = len(nums)\n\n def at_most_k(k: int) -> int:\n (i, j, odds) = (0, 0, 0)\n res = 0\n while j < n:\n if nums[j] % 2:\n odds += 1\n while i <= j and odds > k:\n if nums[i] % 2:\n odds -= 1\n i += 1\n j += 1\n res += j - i\n return res\n return at_most_k(k) - at_most_k(k - 1)", "def __init__():\n self.odd = 0\n\ndef add(value: int):\n if value % 2 == 1:\n self.odd += 1\n\ndef remove(value: int):\n if value % 2 == 1:\n self.odd -= 1\n\ndef numberofsubarrays(A: List[int], k: int) -> int:\n window1 = Window()\n window2 = Window()\n left1 = left2 = answer = 0\n for right in A:\n window1.add(right)\n window2.add(right)\n while window1.odd > k:\n window1.remove(A[left1])\n left1 += 1\n while window2.odd >= k:\n window2.remove(A[left2])\n left2 += 1\n answer += left2 - left1\n return answer", "def numberofsubarrays(nums: List[int], k: int) -> int:\n result = 0\n (start, count) = (0, 0)\n for i in range(len(nums)):\n if nums[i] % 2 != 0:\n count += 1\n while start < i and count > k:\n if nums[start] % 2 != 0:\n count -= 1\n start += 1\n if count == k:\n result += 1\n for j in range(start, i):\n if count == k and nums[j] % 2 == 0:\n result += 1\n else:\n break\n return result", "def numberofsubarrays(nums: List[int], k: int) -> int:\n P = [0]\n for n in nums:\n P.append(P[-1] + n % 2)\n from collections import Counter\n count = Counter()\n ans = 0\n for p in P:\n ans += count[p]\n count[p + k] += 1\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n ans = count = l = 0\n for num in nums:\n if num & 1:\n k -= 1\n count = 0\n while k == 0:\n k += nums[l] & 1\n count += 1\n l += 1\n ans += count\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n cnt = collections.Counter()\n (cnt[0], odd, res) = (1, 0, 0)\n for i in nums:\n if i % 2 == 1:\n odd += 1\n cnt[odd] += 1\n res += cnt[odd - k]\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atmostK(K):\n res = 0\n k = 0\n count = collections.Counter()\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n count[1] += 1\n while count[1] > K:\n if nums[k] % 2 == 1:\n count[1] -= 1\n k += 1\n res += i - k + 1\n return res\n return atmostK(k) - atmostK(k - 1)", "from collections import Counter\n\ndef numberofsubarrays(A, k):\n psum = [0]\n for x in map(lambda x: x % 2, A):\n psum.append(psum[-1] + x)\n count = Counter(psum)\n return sum((count[p - k] for p in psum))"], "starter_code": "def numberofsubarrays(nums: List[int], k: int) -> int:\n", "input_output": {"fn_name": "numberOfSubarrays", "inputs": [[[1, 1, 2, 1, 1], 3]], "outputs": [2]}, "difficulty": "MEDIUM", "raw_tags": ["Math", "Sliding Window", "Array", "Hash Table"], "name": null, "source": "leetcode", "tags": ["Data structures", "Amortized analysis", "Mathematics"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://leetcode.com/problems/count-number-of-nice-subarrays/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numberofsubarrays", "task_id": "TACO_lite/93", "example": [[[[1, 1, 2, 1, 1], 3], [[2, 4, 6], 1], [[2, 2, 2, 1, 2, 2, 1, 2, 2, 2], 2]], ["2", "0", "16"]]} +{"requirement": "You are given a sequence of a journey in London, UK. The sequence will contain bus **numbers** and TFL tube names as **strings** e.g.\n\n```python\n['Northern', 'Central', 243, 1, 'Victoria']\n```\nJourneys will always only contain a combination of tube names and bus numbers. Each tube journey costs `£2.40` and each bus journey costs `£1.50`. If there are `2` or more adjacent bus journeys, the bus fare is capped for sets of two adjacent buses and calculated as one bus fare for each set.\n\nYour task is to calculate the total cost of the journey and return the cost `rounded to 2 decimal places` in the format (where x is a number): `£x.xx`", "solutions": ["def london_city_hacker(journey):\n tube = 2.4\n bus = 1.5\n total_cost = 0.0\n count = 0\n for link in journey:\n if isinstance(link, str):\n total_cost += tube\n count = 0\n elif count == 0:\n total_cost += bus\n count += 1\n else:\n count = 0\n return '£{:.2f}'.format(total_cost)", "def london_city_hacker(journey):\n vehicle = ''.join(('t' if isinstance(j, str) else 'b' for j in journey)).replace('bb', 'b')\n return f\"£{sum((2.4 if v == 't' else 1.5 for v in vehicle)):.2f}\"", "def london_city_hacker(journey):\n prices = []\n for stop in journey:\n prices.append(2.4 if type(stop) is str else 1.5)\n if prices[-2:] == [1.5, 1.5]:\n prices[-1] = 0\n return f'£{sum(prices):.2f}'", "from itertools import groupby\n\ndef london_city_hacker(journey):\n tube_fare = lambda n: 2.4 * n\n bus_fare = lambda n: 1.5 * sum(divmod(n, 2))\n s = sum(([bus_fare, tube_fare][a](len(list(g))) for (a, g) in groupby(map(lambda a: isinstance(a, str), journey))))\n return f'£{s:.2f}'", "def london_city_hacker(journey):\n total = 0.0\n l = []\n for i in range(len(journey)):\n if type(journey[i]) == str:\n total += 2.4\n elif i < len(journey) - 1 and type(journey[i + 1]) == int:\n l.append(journey[i])\n if len(l) == 2:\n total += 1.5\n l = []\n else:\n total += 1.5\n l = []\n total = round(total, 2)\n return '£' + str(total) + '0'", "from itertools import groupby\n\ndef london_city_hacker(journey):\n return f'£{sum((2.4 * len(list(l)) if k is str else (len(list(l)) + 1) // 2 * 1.5 for (k, l) in groupby(journey, type))):.2f}'", "def london_city_hacker(journey):\n bus_counter = 0\n bus_price = 0\n tube_price = 0\n for i in journey:\n if type(i) is int:\n bus_counter += 1\n if bus_counter > 1:\n bus_counter = 0\n bus_price += 0\n else:\n bus_price += 1.5\n if type(i) is str:\n bus_counter = 0\n tube_price += 2.4\n return f'£{tube_price + bus_price:.2f}'", "def london_city_hacker(journey):\n sum = 0.0\n isBus = False\n for i in journey:\n if len(str(i)) <= 3:\n if isBus:\n isBus = 0\n else:\n sum += 1.5\n isBus = 1\n else:\n sum += 2.4\n isBus = 0\n sum = round(sum * 100) / 100\n return f'£{str(sum)}0'", "def london_city_hacker(journey):\n total_cost = 0\n adjacent_bus_tour = 0\n for tour in journey:\n if type(tour) == str:\n adjacent_bus_tour = 0\n total_cost += 2.4\n else:\n adjacent_bus_tour += 1\n if adjacent_bus_tour == 2:\n adjacent_bus_tour = 0\n else:\n total_cost += 1.5\n return f'£{total_cost:.2f}'", "from itertools import groupby\n\ndef london_city_hacker(journey):\n arr = list(map(type, journey))\n s = 0\n for (k, g) in groupby(arr):\n g = len(list(g))\n if k == str:\n s += 2.4 * g\n else:\n s += 1.5 * (g // 2 + (1 if g % 2 else 0) if g > 1 else g)\n return f'£{round(s, 2):.2f}'"], "starter_code": "def london_city_hacker(journey):\n", "input_output": {"fn_name": "london_city_hacker", "inputs": [[[12, "Central", "Circle", 21]], [["Piccidilly", 56]], [["Northern", "Central", "Circle"]], [["Piccidilly", 56, 93, 243]], [[386, 56, 1, 876]], [[]]], "outputs": [["£7.80"], ["£3.90"], ["£7.20"], ["£5.40"], ["£3.00"], ["£0.00"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5bce125d3bb2adff0d000245", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "london_city_hacker", "task_id": "TACO_lite/29", "example": [[], []]} +{"requirement": "## Grade book\n\nComplete the function so that it finds the mean of the three scores passed to it and returns the letter value associated with that grade.\n\nNumerical Score | Letter Grade\n--- | ---\n90 <= score <= 100 | 'A'\n80 <= score < 90 | 'B'\n70 <= score < 80 | 'C'\n60 <= score < 70 | 'D'\n 0 <= score < 60 | 'F'\n\nTested values are all between 0 and 100. Theres is no need to check for negative values or values greater than 100.", "solutions": ["def get_grade(s1, s2, s3):\n m = (s1 + s2 + s3) / 3.0\n if 90 <= m <= 100:\n return 'A'\n elif 80 <= m < 90:\n return 'B'\n elif 70 <= m < 80:\n return 'C'\n elif 60 <= m < 70:\n return 'D'\n return 'F'", "def get_grade(s1, s2, s3):\n mean = sum([s1, s2, s3]) / 3\n if mean >= 90:\n return 'A'\n if mean >= 80:\n return 'B'\n if mean >= 70:\n return 'C'\n if mean >= 60:\n return 'D'\n return 'F'", "def get_grade(*s):\n return 'FFFFFFDCBAA'[sum(s) // 30]", "scores = {10: 'A', 9: 'A', 8: 'B', 7: 'C', 6: 'D'}\n\ndef get_grade(*args):\n mean = sum(args) / len(args)\n return scores.get(mean // 10, 'F')", "get_grade = lambda *a: 'FFFFFFDCBAA'[sum(a) // 3 // 10]", "def get_grade(*arg):\n return list('FDCBAA')[max(int(sum(arg) / 30 - 5), 0)]", "def get_grade(s1, s2, s3):\n m = (s1 + s2 + s3) / 3\n if m > 89:\n return 'A'\n elif m > 79:\n return 'B'\n elif m > 69:\n return 'C'\n elif m > 59:\n return 'D'\n else:\n return 'F'", "def get_grade(*args):\n return {6: 'D', 7: 'C', 8: 'B', 9: 'A', 10: 'A'}.get(sum(args) // 30, 'F')", "def get_grade(s1, s2, s3):\n return next(('ABCDF'[i] for (i, low) in enumerate([90, 80, 70, 60, 0]) if (s1 + s2 + s3) / 3 >= low))", "def get_grade(*grades):\n mean = sum(grades) / len(grades)\n for (score, grade) in [(90, 'A'), (80, 'B'), (70, 'C'), (60, 'D'), (0, 'F')]:\n if mean >= score:\n return grade", "def get_grade(s1, s2, s3):\n m = (s1 + s2 + s3) / 3\n return 'A' if m >= 90 else 'B' if m >= 80 else 'C' if m >= 70 else 'D' if m >= 60 else 'F'", "def get_grade(s1, s2, s3):\n s = s1 + s2 + s3\n s /= 3\n if s >= 90:\n return 'A'\n elif s >= 80:\n return 'B'\n elif s >= 70:\n return 'C'\n elif s >= 60:\n return 'D'\n return 'F'", "def get_grade(s1, s2, s3):\n grades = {range(60): 'F', range(60, 70): 'D', range(70, 80): 'C', range(80, 90): 'B', range(90, 101): 'A'}\n for x in grades:\n if int((s1 + s2 + s3) / 3) in x:\n return grades[x]", "from statistics import mean\n\ndef get_grade(s1, s2, s3):\n a = mean((s1, s2, s3))\n if a < 60:\n return 'F'\n elif a < 70:\n return 'D'\n elif a < 80:\n return 'C'\n elif a < 90:\n return 'B'\n else:\n return 'A'", "def get_grade(*args):\n mean = sum(args) / len(args)\n if 90 <= mean <= 100:\n return 'A'\n elif 80 <= mean < 90:\n return 'B'\n elif 70 <= mean < 80:\n return 'C'\n elif 60 <= mean < 70:\n return 'D'\n else:\n return 'F'", "def get_grade(*s):\n score = sum(s) / len(s)\n if 90 <= score <= 100:\n return 'A'\n elif 80 <= score < 90:\n return 'B'\n elif 70 <= score < 80:\n return 'C'\n elif 60 <= score < 70:\n return 'D'\n else:\n return 'F'", "def get_grade(s1, s2, s3):\n mean = (s1 + s2 + s3) / 3.0\n if mean >= 70.0:\n if mean < 80.0:\n return 'C'\n elif mean < 90:\n return 'B'\n else:\n return 'A'\n elif mean >= 60:\n return 'D'\n else:\n return 'F'", "def get_grade(s1, s2, s3):\n mean = (s1 + s2 + s3) / 3\n for (limit, grade) in [(90, 'A'), (80, 'B'), (70, 'C'), (60, 'D')]:\n if limit <= mean <= 100:\n return grade\n return 'F'", "get_grade = lambda *scores: [letter for letter in {'A': (90, 100), 'B': (80, 90), 'C': (70, 80), 'D': (60, 70), 'F': (0, 60)} if {'A': (90, 100), 'B': (80, 90), 'C': (70, 80), 'D': (60, 70), 'F': (0, 60)}[letter][0] <= sum(scores) / len(scores) <= {'A': (90, 100), 'B': (80, 90), 'C': (70, 80), 'D': (60, 70), 'F': (0, 60)}[letter][1]][0]", "def get_grade(s1, s2, s3):\n score = (s1 + s2 + s3) / 3\n grades = [[90, 'A'], [80, 'B'], [70, 'C'], [60, 'D'], [0, 'F']]\n for grade in grades:\n if score >= grade[0]:\n return grade[1]", "import math\n\ndef get_grade(b, c, d):\n a = int((b + c + d) / 30)\n return 'A' if a == 10 else 'F' if a < 6 else chr(74 - a)", "def get_grade(s1, s2, s3):\n score = (s1 + s2 + s3) / 3\n score_mapping = {90 <= score <= 100: 'A', 80 <= score < 90: 'B', 70 <= score < 80: 'C', 60 <= score < 70: 'D', 0 <= score < 60: 'F'}\n return score_mapping[True]", "dict = {10: 'A', 9: 'A', 8: 'B', 7: 'C', 6: 'D'}\n\ndef get_grade(s1, s2, s3):\n mean = int((s1 + s2 + s3) / 30)\n if mean in dict:\n return dict[mean]\n return 'F'", "def get_grade(s1, s2, s3):\n grade = ['F'] * 60 + ['D'] * 10 + ['C'] * 10 + ['B'] * 10 + ['A'] * 11\n scores = (s1 + s2 + s3) // 3\n return grade[scores]", "def get_grade(*args):\n (avg, grades) = (sum(args) // len(args), ['F', 'D', 'C', 'B', 'A', 'A'])\n return grades[max(0, avg // 10 - 5)]", "def get_grade(*arg):\n return list('FDCBAA')[max(int((sum(arg) / 3 - 50) / 10), 0)]", "def get_grade(s1, s2, s3):\n if s1 + s2 + s3 >= 270:\n return 'A'\n if (s1 + s2 + s3 >= 240) & (s1 + s2 + s3 < 270):\n return 'B'\n if (s1 + s2 + s3 >= 210) & (s1 + s2 + s3 < 240):\n return 'C'\n if (s1 + s2 + s3 >= 180) & (s1 + s2 + s3 < 210):\n return 'D'\n if (s1 + s2 + s3 >= 0) & (s1 + s2 + s3 < 180):\n return 'F'\n return 'F'", "mean = lambda nums: sum(nums) / (len(nums) + 0.0)\n\ndef get_grade(s1, s2, s3):\n m = mean([s1, s2, s3])\n if m >= 90:\n return 'A'\n elif m >= 80:\n return 'B'\n elif m >= 70:\n return 'C'\n elif m >= 60:\n return 'D'\n else:\n return 'F'", "from collections import OrderedDict\n\ndef get_grade(*s):\n avg = sum(s) / len(s)\n for (a, g) in zip([60, 70, 80, 90], ['F', 'D', 'C', 'B']):\n if avg < a:\n return g\n return 'A'", "def get_grade(s1, s2, s3):\n score = (s1 + s2 + s3) / 3\n if 90 <= score <= 100:\n return 'A'\n elif 80 <= score < 90:\n return 'B'\n elif 70 <= score < 80:\n return 'C'\n elif 60 <= score < 70:\n return 'D'\n else:\n return 'F'", "def get_grade(*args):\n d = {(0, 6): 'F', (6, 7): 'D', (7, 8): 'C', (8, 9): 'B', (9, 11): 'A'}\n return next((d[rang] for rang in list(d.keys()) if sum(args) / len(args) // 10 in range(*rang)))", "def get_grade(s1, s2, s3):\n s = s1 + s2 + s3\n res = s / 3\n if res >= 90 and res <= 100:\n return 'A'\n elif res >= 80 and res <= 90:\n return 'B'\n elif res >= 70 and res <= 80:\n return 'C'\n elif res >= 60 and res <= 70:\n return 'D'\n elif res >= 0 and res <= 60:\n return 'F'", "def get_grade(s1, s2, s3):\n av = (int(s1) + int(s2) + int(s3)) / 3\n if int(av) >= 90:\n return 'A'\n if 80 <= int(av) < 90:\n return 'B'\n if 70 <= int(av) < 80:\n return 'C'\n if 60 <= int(av) < 70:\n return 'D'\n if int(av) < 60:\n return 'F'", "def get_grade(s1, s2, s3):\n result = (s1 + s2 + s3) / 3\n if result >= 90:\n return 'A'\n elif result >= 80 and result < 90:\n return 'B'\n elif result >= 70 and result < 80:\n return 'C'\n elif result >= 60 and result < 70:\n return 'D'\n else:\n return 'F'", "def get_grade(s1, s2, s3):\n score = (s1 + s2 + s3) / 3\n return {10: 'A', 9: 'A', 8: 'B', 7: 'C', 6: 'D'}.get(score // 10, 'F')", "def get_grade(s1, s2, s3):\n mean_grade = (s1 + s2 + s3) / 3\n grade = ''\n if mean_grade >= 0 and mean_grade < 60:\n grade = 'F'\n if mean_grade >= 60 and mean_grade < 70:\n grade = 'D'\n if mean_grade >= 70 and mean_grade < 80:\n grade = 'C'\n if mean_grade >= 80 and mean_grade < 90:\n grade = 'B'\n if mean_grade >= 90 and mean_grade <= 100:\n grade = 'A'\n return grade", "def get_grade(s1, s2, s3):\n score = (s1 + s2 + s3) / 3\n score = int(score)\n if score >= 90 and score <= 100:\n return 'A'\n if score >= 80 and score <= 90:\n return 'B'\n if score >= 70 and score <= 80:\n return 'C'\n if score >= 60 and score <= 70:\n return 'D'\n if score >= 0 and score <= 60:\n return 'F'", "def get_grade(s1, s2, s3):\n letter_grades = {(90, 100): 'A', (80, 89): 'B', (70, 79): 'C', (60, 69): 'D', (0, 59): 'F'}\n grade = (s1 + s2 + s3) / 3\n for score in list(letter_grades.keys()):\n if score[0] <= grade <= score[1]:\n return letter_grades[score]", "def get_grade(s1, s2, s3):\n avg = (s1 + s2 + s3) / 3\n scale = {'A': 90 <= avg <= 100, 'B': 80 <= avg < 90, 'C': 70 <= avg < 80, 'D': 60 <= avg < 70, 'F': 0 <= avg < 60}\n for (k, v) in scale.items():\n if v == True:\n return k", "def get_grade(s1, s2, s3):\n result = sum((s1, s2, s3)) / 3\n if result > 90:\n return 'A'\n elif 90 > result >= 80:\n return 'B'\n elif 80 > result >= 70:\n return 'C'\n elif 70 > result >= 60:\n return 'D'\n elif 60 > result >= 0:\n return 'F'", "def get_grade(s1, s2, s3):\n m = int((s1 + s2 + s3) / 3)\n if m >= 90 and m <= 100:\n return 'A'\n elif m >= 80 and m < 90:\n return 'B'\n elif m >= 70 and m < 80:\n return 'C'\n elif m >= 60 and m < 70:\n return 'D'\n else:\n return 'F'", "def get_grade(s1, s2, s3):\n dic = {10: 'A', 9: 'A', 8: 'B', 7: 'C', 6: 'D', 5: 'F', 4: 'F', 3: 'F', 2: 'F', 1: 'F', 0: 'F'}\n return dic[(s1 + s2 + s3) / 3 // 10]", "def get_grade(s1, s2, s3):\n avg = sum((s1, s2, s3)) // 3\n return ['F', 'D', 'C', 'B', 'A'][sum((avg > 59, avg > 69, avg > 79, avg > 89))]", "def get_grade(s1, s2, s3):\n curr = sum([s1, s2, s3]) // 3\n m = [[90, 100, 'A'], [80, 90, 'B'], [70, 80, 'C'], [60, 70, 'D']]\n for (s, e, grade) in m:\n if s <= curr <= e:\n return grade\n return 'F'", "def get_grade(s1, s2, s3):\n result = sum([s1, s2, s3]) // 30\n if result >= 9:\n return 'A'\n elif result >= 8:\n return 'B'\n elif result >= 7:\n return 'C'\n elif result >= 6:\n return 'D'\n else:\n return 'F'", "def get_grade(*args):\n if sum(args) / len(args) >= 90:\n return 'A'\n if sum(args) / len(args) >= 80:\n return 'B'\n if sum(args) / len(args) >= 70:\n return 'C'\n if sum(args) / len(args) >= 60:\n return 'D'\n return 'F'", "import numpy as np\n\ndef get_grade(*scores):\n grades = {10: 'A', 9: 'A', 8: 'B', 7: 'C', 6: 'D'}\n return grades.get(np.mean(scores) // 10, 'F')", "def get_grade(s1, s2, s3):\n f = int((s1 + s2 + s3) / 3)\n if f in range(90, 101):\n return 'A'\n elif f in range(80, 90):\n return 'B'\n elif f in range(70, 80):\n return 'C'\n elif f in range(60, 70):\n return 'D'\n elif f in range(0, 60):\n return 'F'", "def get_grade(s1, s2, s3):\n score = s1 + s2 + s3\n if 270 <= score:\n return 'A'\n elif 240 <= score:\n return 'B'\n elif 210 <= score:\n return 'C'\n elif 180 <= score:\n return 'D'\n return 'F'", "def get_grade(s1, s2, s3):\n grades = (s1, s2, s3)\n total = sum(grades)\n mean = total / len(grades)\n if 100 >= mean >= 90:\n return 'A'\n elif 90 > mean >= 80:\n return 'B'\n elif 80 > mean >= 70:\n return 'C'\n elif 70 > mean >= 60:\n return 'D'\n else:\n return 'F'"], "starter_code": "def get_grade(s1, s2, s3):\n", "input_output": {"fn_name": "get_grade", "inputs": [[95, 90, 93], [100, 85, 96], [92, 93, 94], [100, 100, 100], [70, 70, 100], [82, 85, 87], [84, 79, 85], [70, 70, 70], [75, 70, 79], [60, 82, 76], [65, 70, 59], [66, 62, 68], [58, 62, 70], [44, 55, 52], [48, 55, 52], [58, 59, 60], [0, 0, 0]], "outputs": [["A"], ["A"], ["A"], ["A"], ["B"], ["B"], ["B"], ["C"], ["C"], ["C"], ["D"], ["D"], ["D"], ["F"], ["F"], ["F"], ["F"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/55cbd4ba903825f7970000f5", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "get_grade", "task_id": "TACO_lite/72", "example": [[], []]} +{"requirement": "Given an array arr[] which contains data of N nodes of Complete Binary tree in level order fashion. The task is to print the level order traversal in sorted order. \nExample 1:\nInput:\nN = 7\narr[] = {7 6 5 4 3 2 1}\nOutput:\n7\n5 6\n1 2 3 4\nExplanation: The formed Binary Tree is:\n 7\n / \\\n 6 5\n / \\ / \\\n 4 3 2 1\nExample 2:\nInput:\nN = 6\narr[] = {5 6 4 9 2 1}\nOutput:\n5\n4 6\n1 2 9\nExplanation: The formed Binary Tree is:\n 5\n / \\\n 6 4\n / \\ / \n 9 2 1 \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function binTreeSortedLevels() which takes the array arr[] and its size N as inputs and returns a 2D array where the i-th array denotes the nodes of the i-th level in sorted order.\nExpected Time Complexity: O(NlogN).\nExpected Auxiliary Space: O(N).\nConstraints:\n1 <= N <= 10^{4}", "solutions": ["def bintreesortedlevels(arr, n):\n li = []\n i = 0\n level = 0\n while i < n:\n dumm = []\n if level == 0:\n li.append([arr[i]])\n i += 1\n level += 1\n else:\n size = 2 ** level\n if i + size < n:\n dumm.extend(arr[i:i + size])\n dumm.sort()\n li.append(dumm)\n i += size\n level += 1\n else:\n dumm.extend(arr[i:])\n dumm.sort()\n li.append(dumm)\n break\n return li", "def bintreesortedlevels(arr, n):\n ans = []\n m = 1\n level = []\n j = 0\n for i in range(n):\n if j < m:\n level.append(arr[i])\n j += 1\n else:\n level.sort()\n ans.append(level.copy())\n level.clear()\n m += m\n j = 1\n level.append(arr[i])\n level.sort()\n ans.append(level)\n return ans", "def bintreesortedlevels(arr, n):\n res = []\n i = 0\n ls = 1\n while i < n:\n t = (1 << ls) - 1\n t = min(t, n)\n temp = sorted(arr[i:t])\n i = t\n ls += 1\n res.append(temp)\n return res", "def bintreesortedlevels(arr, n):\n res = []\n (i, total) = (0, 0)\n while total < n:\n temp = []\n for j in range(2 ** i):\n if total < n:\n temp.append(arr[total])\n total += 1\n else:\n break\n temp.sort()\n res.append(temp)\n i += 1\n return res", "def bintreesortedlevels(arr, n):\n n = len(arr)\n list2 = [[arr[0]]]\n c = 0\n j = 1\n list3 = []\n for x in range(1, n):\n if c == 2 ** j - 1:\n list3.append(arr[x])\n list3.sort()\n list2.append(list3)\n list3 = []\n j += 1\n c = 0\n else:\n list3.append(arr[x])\n c += 1\n if len(list3) != 0:\n list3.sort()\n list2.append(list3)\n return list2", "from collections import deque\n\ndef bintreesortedlevels(arr, n):\n dq = deque()\n dq.append(0)\n res = []\n while len(dq) > 0:\n currsize = len(dq)\n t = []\n for i in range(currsize):\n temp = dq.popleft()\n t.append(arr[temp])\n if 2 * temp + 1 < n:\n dq.append(2 * temp + 1)\n if 2 * temp + 2 < n:\n dq.append(2 * temp + 2)\n t.sort()\n res.append(t)\n return res", "def bintreesortedlevels(arr, n):\n final = []\n l = [1]\n final.append([arr[0]])\n i = 0\n while True:\n li = len(l)\n l = []\n for j in range(li):\n if 2 * i + 1 < n:\n l.append(arr[2 * i + 1])\n if 2 * i + 2 < n:\n l.append(arr[2 * i + 2])\n i += 1\n if len(l):\n final.append(sorted(l))\n else:\n break\n return final", "def bintreesortedlevels(arr, n):\n output = []\n i = 0\n while 2 ** i <= n:\n j = 2 ** i\n k = 2 ** (i + 1)\n i += 1\n output.append(sorted(arr[j - 1:k - 1]))\n return output", "def bintreesortedlevels(arr, n):\n a1 = {}\n queue = [0]\n queue1 = [0]\n while len(queue) > 0:\n x = queue.pop(0)\n y = queue1.pop(0)\n if y not in a1:\n a1[y] = []\n a1[y].append(arr[x])\n if 2 * x + 1 < len(arr):\n queue.append(2 * x + 1)\n queue1.append(y + 1)\n if 2 * x + 2 < len(arr):\n queue.append(2 * x + 2)\n queue1.append(y + 1)\n e = []\n for i in range(max(a1) + 1):\n e.append(sorted(a1[i]))\n return e", "from collections import deque\nfrom sortedcontainers import SortedList\n\ndef bintreesortedlevels(arr, n):\n q = deque([0])\n res = []\n while q:\n t = SortedList()\n for _ in range(len(q)):\n cur = q.popleft()\n t.add(arr[cur])\n for i in [2 * cur + 1, 2 * cur + 2]:\n if i < len(arr):\n q.append(i)\n res.append(t)\n return res", "from collections import deque\nfrom heapq import heappush, heappop\n\ndef bintreesortedlevels(arr, n):\n q = deque([0])\n res = []\n while q:\n hp = []\n for _ in range(len(q)):\n cur = q.popleft()\n heappush(hp, arr[cur])\n for i in [2 * cur + 1, 2 * cur + 2]:\n if i < len(arr):\n q.append(i)\n t = []\n while hp:\n t.append(heappop(hp))\n res.append(t)\n return res", "def bintreesortedlevels(arr, n):\n (res, start, end, len1) = ([], 0, 1, 1)\n while start < n:\n res.append(sorted(arr[start:end]))\n len1 *= 2\n start = end\n end = start + len1\n return res", "def bintreesortedlevels(arr, n):\n i = 1\n ans = []\n while len(arr):\n ans.append(sorted(arr[:i]))\n arr = arr[i:]\n i <<= 1\n return ans", "def bintreesortedlevels(arr, n):\n i = 0\n k = 1\n res = []\n while i < n:\n temp = arr[i:i + k]\n temp.sort()\n res.append(temp)\n i += k\n k *= 2\n return res", "def bintreesortedlevels(arr, n):\n _list = []\n a = 1\n curr = 0\n while curr < n:\n _list.append(sorted(arr[curr:curr + a]))\n curr += a\n a *= 2\n return _list", "def bintreesortedlevels(arr, n):\n if n == 1:\n return [[arr[0]]]\n else:\n l = [[arr[0]]]\n i = 1\n c = 1\n while i < n:\n size = 2 ** c\n if i + size < n:\n a = arr[i:i + size]\n a.sort()\n l.append(a)\n i += size\n c += 1\n else:\n a = arr[i:]\n a.sort()\n l.append(a)\n break\n return l", "def bintreesortedlevels(arr, n):\n start = 0\n i = 0\n increment = 2 ** i\n list1 = []\n while start < n:\n list1.append(sorted(arr[start:start + increment]))\n start += increment\n i += 1\n increment = 2 ** i\n return list1", "def bintreesortedlevels(arr, n):\n res = []\n i = 0\n count = 0\n level = 0\n while True:\n count = 2 ** level\n t = []\n while count != 0 and i < n:\n t.append(arr[i])\n i += 1\n count -= 1\n res.append(sorted(t))\n if i >= n:\n break\n level += 1\n return res", "def bintreesortedlevels(arr, n):\n res = []\n l = 0\n i = 0\n while True:\n count = int(2 ** l)\n tmp = []\n while count != 0 and i < n:\n tmp.append(arr[i])\n i += 1\n count -= 1\n res.append(sorted(tmp))\n if i >= n:\n break\n l += 1\n return res", "def bintreesortedlevels(arr, n):\n i = 0\n a = []\n while 2 ** i <= n:\n a.append(sorted(arr[:2 ** i]))\n arr[:] = arr[2 ** i:]\n i = i + 1\n return a", "def bintreesortedlevels(arr, n):\n ans = []\n i = 0\n level = 0\n while True:\n count = int(2 ** level)\n tmp = []\n while count != 0 and i < n:\n tmp.append(arr[i])\n i += 1\n count -= 1\n ans.append(sorted(tmp))\n if i >= n:\n break\n level += 1\n return ans", "def bintreesortedlevels(arr, n):\n from math import exp\n level = 0\n prevLevelEnd = 0\n out = []\n while prevLevelEnd < n:\n nAtLevel = pow(2, level)\n out.append(list(sorted(arr[prevLevelEnd:prevLevelEnd + nAtLevel])))\n prevLevelEnd += nAtLevel\n level += 1\n return out", "def bintreesortedlevels(arr, n):\n re = []\n level = 0\n i = 0\n while i < n:\n ans = []\n if level == 0:\n re.append([arr[i]])\n i += 1\n level += 1\n else:\n size = 2 ** level\n if i + size < n:\n ans.extend(arr[i:i + size])\n ans.sort()\n re.append(ans)\n i += size\n level += 1\n else:\n ans.extend(arr[i:])\n ans.sort()\n re.append(ans)\n break\n return re", "import heapq\n\ndef bintreesortedlevels(arr, n):\n lst = []\n x = 0\n y = 1\n while True:\n ll = []\n for j in range(x, min(x + y, n)):\n ll.append(arr[j])\n lst.append(sorted(ll))\n x = x + y\n y = 2 * y\n if x >= n:\n break\n return lst", "def bintreesortedlevels(x, n):\n res = []\n i = 0\n j = 1\n while i < n:\n res.append(sorted(x[i:i + j]))\n i = i + j\n j = j * 2\n return res", "def bintreesortedlevels(arr, n):\n ans = []\n si = 0\n k = 0\n while si < n:\n size = 2 ** k\n k += 1\n if si + size >= n:\n tans = arr[si:]\n else:\n tans = arr[si:si + size]\n tans.sort()\n ans.append(tans)\n si += size\n return ans", "def bintreesortedlevels(arr, n):\n lst = []\n level = 0\n i = 0\n while i < n:\n l = []\n if level == 0:\n l.append(arr[i])\n lst.append(l)\n i = i + 1\n level = level + 1\n else:\n size = 2 ** level\n if i + size < n:\n l.extend(arr[i:i + size])\n l.sort()\n lst.append(l)\n i = i + size\n level = level + 1\n else:\n l.extend(arr[i:])\n l.sort()\n lst.append(l)\n break\n return lst", "def bintreesortedlevels(arr, n):\n a = [[arr[0]]]\n i = 1\n while i < n:\n b = arr[i:2 * i + 1]\n b.sort()\n a.append(b)\n i = 2 * i + 1\n return a", "def bintreesortedlevels(arr, n):\n c = 0\n i = 0\n ans = []\n while c < n:\n l = []\n x = pow(2, i)\n while x > 0 and c < n:\n l.append(arr[c])\n c += 1\n x -= 1\n i += 1\n l.sort()\n ans.append(l)\n return ans", "from collections import deque\n\ndef bintreesortedlevels(arr, n):\n lqc = deque()\n lqc.append(0)\n lqn = deque()\n lsrl = deque()\n rslt = deque()\n while len(lqc) > 0:\n idx = lqc.popleft()\n lsrl.append(arr[idx])\n if 2 * idx + 1 < n:\n lqn.append(2 * idx + 1)\n if 2 * idx + 2 < n:\n lqn.append(2 * idx + 2)\n if len(lqc) == 0:\n lqc = lqn.copy()\n lqn = deque()\n lsrl = list(lsrl)\n lsrl.sort()\n rslt.append(lsrl)\n lsrl = deque()\n return rslt", "def bintreesortedlevels(arr, n):\n mm = 0\n x = 0\n b = []\n if n == 1:\n return [arr]\n exit()\n while x < n:\n e = 2 ** mm\n t = []\n for k in range(e):\n if x < n:\n t.append(arr[x])\n x = x + 1\n t.sort()\n mm = mm + 1\n b.append(t)\n return b", "from collections import defaultdict\nimport queue\n\ndef bintreesortedlevels(arr, n):\n q = queue.deque()\n dic = defaultdict(list)\n q.append([arr[0], 0, 0])\n while q:\n ele = q.popleft()\n dic[ele[1]].append(ele[0])\n val = 2 * ele[2]\n if val + 1 < n:\n q.append([arr[val + 1], ele[1] + 1, val + 1])\n if val + 2 < n:\n q.append([arr[val + 2], ele[1] + 1, val + 2])\n for i in dic:\n dic[i].sort()\n return dic", "def bintreesortedlevels(arr, n):\n l = 0\n el = 1\n r = l + el\n ans = []\n while r <= len(arr):\n brr = arr[l:r]\n brr.sort()\n ans.append(brr)\n el *= 2\n if r < len(arr):\n l = r\n if l + el <= len(arr):\n r = l + el\n else:\n r = len(arr)\n elif r == len(arr):\n break\n return ans", "def bintreesortedlevels(arr, n):\n if not arr:\n return\n res = [[arr[0]]]\n level = 1\n i = 1\n l = len(arr)\n while i < l:\n tmp = []\n j = 0\n while i < l and j < 2 ** level:\n tmp.append(arr[i])\n i += 1\n j += 1\n level += 1\n tmp.sort()\n res.append(tmp)\n return res", "def bintreesortedlevels(arr, n):\n ind = 0\n ans = []\n q = [arr[ind]]\n while q:\n b = sorted(q)\n ans.append(b)\n nn = len(q)\n for i in range(nn):\n p = q.pop(0)\n if ind + 1 < n:\n q.append(arr[ind + 1])\n if ind + 2 < n:\n q.append(arr[ind + 2])\n ind += 2\n return ans", "def bintreesortedlevels(arr, n):\n lvl = -1\n ans = []\n while len(arr) > 0:\n lvl += 1\n s = pow(2, lvl)\n if s > len(arr):\n s = len(arr)\n arr[0:s].sort()\n ans.append([])\n while s > 0:\n ans[lvl].append(arr.pop(0))\n s -= 1\n for i in range(lvl + 1):\n ans[i].sort()\n return ans", "def bintreesortedlevels(arr, n):\n j = 0\n l = []\n while j < n:\n i = 2 * j + 1\n l1 = arr[j:i]\n l1.sort()\n l.append(l1)\n j = i\n return l", "def bintreesortedlevels(arr, n):\n c = 0\n p = 0\n l = []\n while p < n:\n s = 2 ** c\n k = arr[p:p + s]\n c = c + 1\n p = p + s\n k.sort()\n l.append(k)\n return l", "from collections import deque\n\ndef bintreesortedlevels(arr, n):\n (i, j, k) = (0, 0, 0)\n ans = []\n while j < n:\n st = []\n i = 2 ** k\n while i > 0 and j < n:\n st.append(arr[j])\n j += 1\n i -= 1\n ans.append(sorted(st))\n k += 1\n return ans", "def bintreesortedlevels(l, n):\n start = 0\n end = 0\n count = 0\n result_list = []\n while True:\n end = 2 ** count\n if end > len(l):\n break\n result_list.append(sorted(l[start:end + start]))\n count += 1\n start += end\n return result_list", "def bintreesortedlevels(arr, n):\n ans = []\n if n == 0:\n return ans\n size = 1\n start = 0\n while True:\n if start + size > n:\n level = arr[start:n]\n if level:\n ans.append(sorted(level))\n break\n else:\n level = arr[start:start + size]\n ans.append(sorted(level))\n start += size\n size *= 2\n return ans", "def bintreesortedlevels(arr, n):\n if n == 0:\n return []\n ans = [[arr[0]]]\n l = 0\n r = 1\n while r < n:\n l = min(l * 2 + 1, n - 1)\n r = min(r * 2 + 1, n)\n ans.append(sorted(arr[l:r]))\n return ans", "def bintreesortedlevels(arr, n):\n curr = 1\n i = 0\n j = 0\n final_ans = []\n ans = []\n while i < n:\n ans.append(arr[i])\n i += 1\n j += 1\n if j == curr:\n j = 0\n curr *= 2\n ans.sort()\n final_ans.append(ans)\n ans = []\n if len(ans):\n ans.sort()\n final_ans.append(ans)\n return final_ans", "def bintreesortedlevels(arr, n):\n if not arr:\n return []\n res = []\n q = [arr[0]]\n pointer = 1\n while q:\n tempQ = []\n data = []\n while q:\n data.append(q.pop(0))\n if pointer < len(arr):\n tempQ.append(arr[pointer])\n pointer += 1\n if pointer < len(arr):\n tempQ.append(arr[pointer])\n pointer += 1\n res.append(sorted(data))\n q = tempQ\n return res", "def bintreesortedlevels(arr, n):\n res = []\n i = 0\n k = 0\n while i < n:\n tmp = []\n lvl = 2 ** k\n while lvl > 0 and i < n:\n tmp.append(arr[i])\n i += 1\n lvl -= 1\n tmp.sort()\n res.append(tmp)\n k += 1\n return res", "import math\n\ndef bintreesortedlevels(arr, n):\n res = []\n (j, k) = (0, 0)\n while j < n:\n tmp = []\n lvl = math.pow(2, k)\n while lvl > 0 and j < n:\n tmp.append(arr[j])\n lvl -= 1\n j += 1\n tmp.sort()\n res.append(tmp)\n k += 1\n return res", "def bintreesortedlevels(arr, n):\n level = 0\n index = 0\n ans = list()\n while index < n:\n nodesCurrLevel = pow(2, level) - 1\n lastindex = min(index + nodesCurrLevel, n - 1)\n arr = arr[:index] + sorted(arr[index:lastindex + 1]) + arr[lastindex + 1:]\n lst = list()\n while index <= lastindex:\n lst.append(arr[index])\n index += 1\n ans.append(lst)\n level += 1\n return ans", "def bintreesortedlevels(arr, n):\n (k, i) = (0, 1)\n ans = []\n z = []\n tot = 0\n for x in arr:\n if k < i:\n z.append(x)\n k += 1\n else:\n ans.append(sorted(z))\n tot += k\n k = 0\n i *= 2\n z = []\n z.append(x)\n k += 1\n if tot != n:\n ans.append(sorted(z))\n return ans", "def bintreesortedlevels(arr, n):\n ans = []\n i = 1\n while i <= n:\n temp = []\n for j in range(i):\n if not arr:\n break\n temp.append(arr.pop(0))\n temp.sort()\n ans.append(temp)\n i *= 2\n return ans", "def bintreesortedlevels(arr, n):\n l = 0\n i = 0\n s = []\n while i < n:\n cln = 2 ** l\n j = min(i + cln - 1, n - 1)\n s.append(sorted(arr[i:j + 1]))\n i = j + 1\n l += 1\n return s", "def bintreesortedlevels(arr, n):\n ans = []\n c = 0\n i = 1\n while True:\n v = []\n j = 0\n while j < i and c < n:\n v.append(arr[c])\n c += 1\n j += 1\n ans.append(sorted(v))\n i = 2 * i\n if c == n:\n break\n return ans", "def bintreesortedlevels(arr, n):\n ans = []\n i = 0\n while arr:\n temp = []\n c = 0\n while c < 2 ** i and arr:\n temp.append(arr.pop(0))\n c += 1\n ans.append(sorted(list(temp)))\n i += 1\n return ans", "def bintreesortedlevels(a, n):\n l = []\n q = [0]\n while q:\n t = a[q[0]:q[-1] + 1]\n t.sort()\n l.append(t)\n t = q.copy()\n q.clear()\n for e in t:\n r1 = 2 * e + 1\n r2 = 2 * e + 2\n if r1 < n:\n q.append(r1)\n if r2 < n:\n q.append(r2)\n return l", "def bintreesortedlevels(arr, n):\n res = []\n level = 0\n i = 0\n while i < len(arr):\n res.append([])\n j = min(len(arr), i + pow(2, level)) - 1\n for k in range(j, i - 1, -1):\n res[-1].append(arr[k])\n i = j + 1\n level += 1\n res[-1].sort()\n return res", "def bintreesortedlevels(arr, n):\n ans = []\n i = 0\n c = 0\n j = 2 ** c\n while i < n and j < n:\n t = arr[i:j]\n ans.append(sorted(t))\n i = j\n c += 1\n j = min(n, i + 2 ** c)\n ans.append(sorted(arr[i:j]))\n return ans", "def bintreesortedlevels(arr, n):\n j = 0\n level = []\n result = []\n for i in range(n):\n if len(level) < 2 ** j:\n level.append(arr[i])\n if len(level) == 2 ** j or i == n - 1:\n result.append(sorted(level.copy()))\n level.clear()\n j += 1\n i += 1\n return result"], "starter_code": "def bintreesortedlevels (arr, n):\n", "input_output": {"inputs": ["N = 7\narr[] = {7 6 5 4 3 2 1}", "N = 6\narr[] = {5 6 4 9 2 1}"], "outputs": ["7\n5 6\n1 2 3 4", "5\n4 6\n1 2 9"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Tree", "Sorting", "Queue", "Data Structures", "priority-queue"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/print-binary-tree-levels-in-sorted-order3241/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(NlogN).", "entry_point": "bintreesortedlevels", "task_id": "TACO_lite/3", "example": [[[7, [7, 6, 5, 4, 3, 2, 1]], [6, [5, 6, 4, 9, 2, 1]]], ["[[7], [5, 6], [1, 2, 3, 4]]", "[[5], [4, 6], [1, 2, 9]]"]]} +{"requirement": "Given a N x N matrix such that each of its cells contains some coins. Count the number of ways to collect exactly K coins while moving from top left corner of the matrix to the bottom right. From a cell (i, j), you can only move to (i+1, j) or (i, j+1).\nExample 1:\nInput:\nK = 12, N = 3\narr[] = [[1, 2, 3], \n [4, 6, 5], \n [3, 2, 1]]\nOutput: 2\nExplanation: \nThere are 2 possible paths \nwith exactly K coins, (1 + 2 + \n6 + 2 + 1) and (1 + 2 + 3 + 5 + 1).\nExample 2:\nInput:\nK = 16, N = 3\narr[] = [[1, 2, 3], \n [4, 6, 5], \n [9, 8, 7]]\nOutput: 0 \nExplanation: \nThere are no possible paths that lead \nto sum=16\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function numberOfPath() which takes N, K and 2D matrix arr[][] as input parameters and returns the number of possible paths.\nExpected Time Complexity: O(n*n*k)\nExpected Auxiliary Space: O(n*n*k)\nConstraints:\n1 <= K < 100\n1 <= N < 100\n1 <= arr_{ij} <= 200", "solutions": ["def util(a, i, j, n, m, k):\n global dp\n if i >= n or j >= m or k < 0:\n return 0\n if i == n - 1 and j == m - 1:\n if k - a[i][j] == 0:\n return 1\n return 0\n if dp[i][j][k] != -1:\n return dp[i][j][k]\n dp[i][j][k] = self.util(a, i + 1, j, n, m, k - a[i][j]) + self.util(a, i, j + 1, n, m, k - a[i][j])\n return dp[i][j][k]\n\ndef numberofpath(N, K, arr):\n global dp\n dp = [[[-1 for x in range(K + 1)] for i in range(N)] for j in range(N)]\n return self.util(arr, 0, 0, N, N, K)", "from collections import defaultdict as dd\n\ndef numberofpath(N, K, arr):\n store = []\n for i in range(N):\n store.append([])\n for j in range(N):\n store[-1].append({})\n store[0][0][arr[0][0]] = 1\n for i in range(1, N):\n store[0][i][list(store[0][i - 1].keys())[0] + arr[0][i]] = 1\n store[i][0][list(store[i - 1][0].keys())[0] + arr[i][0]] = 1\n for i in range(1, N):\n for j in range(1, N):\n for item in store[i - 1][j].keys():\n store[i][j][item + arr[i][j]] = store[i - 1][j][item]\n for item in store[i][j - 1].keys():\n if item + arr[i][j] in store[i][j]:\n store[i][j][item + arr[i][j]] += store[i][j - 1][item]\n else:\n store[i][j][item + arr[i][j]] = store[i][j - 1][item]\n return store[N - 1][N - 1][K] if K in store[N - 1][N - 1] else 0", "def numberofpath(N, K, arr):\n\n def solve(i, j, n, k, arr, dp):\n if i >= n or j >= n or k < 0:\n return 0\n if i == n - 1 and j == n - 1:\n if k == arr[i][j]:\n return 1\n return 0\n if (i, j, k) in ways:\n return ways[i, j, k]\n ways[i, j, k] = solve(i + 1, j, n, k - arr[i][j], arr, dp) + solve(i, j + 1, n, k - arr[i][j], arr, dp)\n return ways[i, j, k]\n ways = {}\n return solve(0, 0, N, K, arr, ways)", "def numberofpath(N, K, arr):\n memo = {}\n\n def helper(i, j, k):\n if i >= N or j >= N or k < 0:\n return 0\n if i == N - 1 and j == N - 1:\n return 1 if k == arr[i][j] else 0\n if (i, j, k) in memo:\n return memo[i, j, k]\n ways = helper(i + 1, j, k - arr[i][j]) + helper(i, j + 1, k - arr[i][j])\n memo[i, j, k] = ways\n return ways\n return helper(0, 0, K)", "def numberofpath(N, K, A):\n\n def _solve(r, c, left):\n if r >= N or c >= N:\n return 0\n cell = A[r][c]\n if cell > left:\n return 0\n if r == c == N - 1:\n return 1 if left == cell else 0\n v = dp[r][c].get(left, -1)\n if v >= 0:\n return v\n ans = dp[r][c][left] = _solve(r + 1, c, left - cell) + _solve(r, c + 1, left - cell)\n return ans\n dp = [[{} for _ in range(N)] for _ in range(N)]\n ans = _solve(0, 0, K)\n return ans", "def numberofpath(N, K, arr):\n paths = {}\n for y in range(N - 1, -1, -1):\n for x in range(N - 1, -1, -1):\n coord = (x, y)\n coins = arr[x][y]\n if x < N - 1:\n x_paths = paths.get((x + 1, y), {})\n else:\n x_paths = {}\n if y < N - 1:\n y_paths = paths.get((x, y + 1), {})\n else:\n y_paths = {}\n my_paths = {}\n for (k, path_count) in x_paths.items():\n my_paths[k] = my_paths.get(k, 0) + path_count\n for (k, path_count) in y_paths.items():\n my_paths[k] = my_paths.get(k, 0) + path_count\n new_paths = {}\n if not my_paths and x == N - 1 and (y == N - 1):\n new_paths[coins] = 1\n else:\n for (k, path_count) in my_paths.items():\n new_val = k + coins\n if new_val <= K:\n new_paths[new_val] = path_count\n paths[coord] = new_paths\n return paths[0, 0].get(K, 0)", "from collections import defaultdict as dd\nfrom collections import Counter\n\ndef numberofpath(N, K, arr):\n store = []\n for i in range(N):\n store.append([])\n for j in range(N):\n store[-1].append(dd(lambda : 0))\n store[0][0][arr[0][0]] += 1\n for i in range(1, N):\n store[0][i][list(store[0][i - 1].keys())[0] + arr[0][i]] += 1\n store[i][0][list(store[i - 1][0].keys())[0] + arr[i][0]] += 1\n for i in range(1, N):\n for j in range(1, N):\n coins = arr[i][j]\n current_store = store[i][j]\n up_store = store[i - 1][j]\n left_store = store[i][j - 1]\n for item in store[i - 1][j].keys():\n current_store[item + coins] += up_store[item]\n for item in store[i][j - 1].keys():\n current_store[item + coins] += left_store[item]\n return store[N - 1][N - 1][K]", "def pathCountDPRecDP(mat, m, n, k, dp):\n if m < 0 or n < 0 or k < 0:\n return 0\n elif m == 0 and n == 0:\n return k == mat[m][n]\n if dp[m][n][k] != -1:\n return dp[m][n][k]\n dp[m][n][k] = pathCountDPRecDP(mat, m - 1, n, k - mat[m][n], dp) + pathCountDPRecDP(mat, m, n - 1, k - mat[m][n], dp)\n return dp[m][n][k]\n\ndef numberofpath(N, K, arr):\n dp = [[[-1 for co in range(K + 1)] for col in range(N + 1)] for row in range(N + 1)]\n return int(pathCountDPRecDP(arr, N - 1, N - 1, K, dp))", "def numberofpath(N, K, arr):\n\n def func(ind1, ind2, k, arr, dp, n):\n if ind1 >= n or ind2 >= n:\n return 0\n if k < 0:\n return 0\n if ind1 == n - 1 and ind2 == n - 1:\n if k == arr[ind1][ind2]:\n return 1\n return 0\n if dp[ind1][ind2][k] != 0:\n return dp[ind1][ind2][k]\n down = func(ind1 + 1, ind2, k - arr[ind1][ind2], arr, dp, n)\n right = func(ind1, ind2 + 1, k - arr[ind1][ind2], arr, dp, n)\n dp[ind1][ind2][k] = down + right\n return dp[ind1][ind2][k]\n dp = [[[0] * (K + 1) for i in range(N)] for j in range(N)]\n kk = func(0, 0, K, arr, dp, N)\n return kk", "def numberofpath(N, K, arr):\n dp = {}\n\n def fun(i, j, su):\n if i >= N or j >= N:\n return 0\n if i == N - 1 and j == N - 1:\n if su == arr[i][j]:\n return 1\n else:\n return 0\n if su < 0:\n return 0\n if (i, j, su) in dp:\n return dp[i, j, su]\n dp[i, j, su] = fun(i + 1, j, su - arr[i][j]) + fun(i, j + 1, su - arr[i][j])\n return dp[i, j, su]\n return fun(0, 0, K)", "def numberofpath(N, K, arr):\n t = [[[-1 for _ in range(100 + 1)] for j in range(N + 1)] for k in range(N + 1)]\n\n def solve(r, c, rem):\n if r < 0 or c < 0 or r >= N or (c >= N) or (rem < 0):\n return 0\n if r == N - 1 and c == N - 1:\n return int(rem == arr[r][c])\n if t[r][c][rem] != -1:\n return t[r][c][rem]\n t[r][c][rem] = solve(r + 1, c, rem - arr[r][c]) + solve(r, c + 1, rem - arr[r][c])\n return t[r][c][rem]\n return solve(0, 0, K)", "def numberofpath(N, K, arr):\n if not arr:\n return\n if N == 1 and K > arr[0][0]:\n return 0\n dp = [[[-1 for col in range(K + 1)] for col in range(N + 1)] for row in range(N + 1)]\n\n def pathCountDPRecDP(arr, m, n, k):\n if m < 0 or n < 0 or k < 0:\n return 0\n elif m == 0 and n == 0:\n if k == arr[m][n]:\n return 1\n else:\n return 0\n if dp[m][n][k] != -1:\n return dp[m][n][k]\n dp[m][n][k] = pathCountDPRecDP(arr, m - 1, n, k - arr[m][n]) + pathCountDPRecDP(arr, m, n - 1, k - arr[m][n])\n return dp[m][n][k]\n return pathCountDPRecDP(arr, N - 1, N - 1, K)", "def helper(i, j, s, arr, n, m, dp):\n if not i and (not j):\n return 1 if s == arr[i][j] else 0\n if i < 0 or j < 0 or s < 1:\n return 0\n if dp[i][j][s] != -1:\n return dp[i][j][s]\n up = helper(i - 1, j, s - arr[i][j], arr, n, m, dp)\n dn = helper(i, j - 1, s - arr[i][j], arr, n, m, dp)\n dp[i][j][s] = up + dn\n return dp[i][j][s]\n\ndef numberofpath(N, K, arr):\n si = len(arr)\n le = len(arr[0])\n assert si == N and le == N\n dp = [[[-1] * (K + 1) for _ in range(N)] for _ in range(N)]\n ans = helper(N - 1, N - 1, K, arr, N, N, dp)\n return ans", "def numberofpath(n, k, a):\n v = [[False] * n for i in range(n)]\n d = [[] * n for i in range(n)]\n dp = {}\n for i in range(n):\n for j in range(n):\n d[i].append(dp.copy())\n d[n - 1][n - 1][a[n - 1][n - 1]] = 1\n\n def solve(i, j, d, v):\n if i > n - 1 or j > n - 1:\n return {}\n if v[i][j]:\n return d[i][j]\n else:\n x = solve(i, j + 1, d, v)\n y = solve(i + 1, j, d, v)\n for z in x:\n if z + a[i][j] not in d[i][j]:\n d[i][j][z + a[i][j]] = x[z]\n else:\n d[i][j][z + a[i][j]] += x[z]\n for z in y:\n if z + a[i][j] not in d[i][j]:\n d[i][j][z + a[i][j]] = y[z]\n else:\n d[i][j][z + a[i][j]] += y[z]\n v[i][j] = True\n return d[i][j]\n d[0][0] = solve(0, 0, d, v)\n if k in d[0][0]:\n return d[0][0][k]\n return 0", "def numberofpath(N, k, arr):\n dp = {}\n\n def path(i, j, s, dp):\n if i < 0 or j < 0 or i >= N or (j >= N):\n return 0\n if i == N - 1 and j == N - 1:\n s += arr[i][j]\n if s == k:\n return 1\n return 0\n if (i, j, s) in dp:\n return dp[i, j, s]\n dp[i, j, s] = path(i + 1, j, s + arr[i][j], dp) + path(i, j + 1, s + arr[i][j], dp)\n return dp[i, j, s]\n return path(0, 0, 0, dp)", "def solve(mat, m, n, k, dp):\n if m < 0 or n < 0 or k < 0:\n return 0\n elif m == 0 and n == 0:\n if k == mat[m][n]:\n return 1\n return 0\n if (m, n, k) in dp:\n return dp[m, n, k]\n dp[m, n, k] = self.solve(mat, m - 1, n, k - mat[m][n], dp) + self.solve(mat, m, n - 1, k - mat[m][n], dp)\n return dp[m, n, k]\n\ndef numberofpath(N, K, arr):\n dp = {}\n return self.solve(arr, N - 1, N - 1, K, dp)", "from functools import lru_cache\n\ndef numberofpath(N, coins, mat):\n if not mat:\n return 0\n key = coins - mat[N - 1][N - 1]\n\n def dfs(i, j, curr):\n ans = 0\n if curr < 0:\n return 0\n if i == 0 and i == j:\n if curr == mat[0][0]:\n return 1\n return 0\n if i > 0:\n ans += dfs(i - 1, j, curr - mat[i][j])\n if j > 0:\n ans += dfs(i, j - 1, curr - mat[i][j])\n return ans\n ans = dfs(N - 1, N - 1, coins)\n return ans", "def pathCountDPRecDP(mat, m, n, k, dp):\n if m < 0 or n < 0 or k < 0:\n return 0\n elif m == 0 and n == 0:\n return 1 if k == mat[m][n] else 0\n if dp[m][n][k] != -1:\n return dp[m][n][k]\n dp[m][n][k] = self.pathCountDPRecDP(mat, m - 1, n, k - mat[m][n], dp) + self.pathCountDPRecDP(mat, m, n - 1, k - mat[m][n], dp)\n return dp[m][n][k]\n\ndef numberofpath(N, K, arr):\n dp = [[[-1 for col in range(110)] for col in range(N)] for row in range(N)]\n return self.pathCountDPRecDP(arr, N - 1, N - 1, K, dp)\n\ndef numberofpath1(N, K, arr):\n dx = [0, 1]\n dy = [1, 0]\n\n def inside(x, y):\n return x >= 0 and x < N and (y >= 0) and (y < N)\n dp1 = [[[0 for i in range(K + 5)] for j in range(N + 5)] for k in range(N + 5)]\n for i in range(N):\n for j in range(N):\n dp1[i][j][0] = 1\n for s in range(1, K + 1):\n for x in range(N):\n for y in range(N):\n if x == 0 or y == 0:\n if s - arr[x][y] >= 0:\n dp1[x][y][s] = dp1[x][y][s - arr[x][y]]\n elif s - arr[x][y] >= 0:\n dp1[x][y][s] += dp1[x - 1][y][s - arr[x][y]]\n dp1[x][y][s] += dp1[x][y - 1][s - arr[x][y]]\n return sum(dp1[:][:][K])", "def numberofpath(N, K, arr):\n\n def dfs(arr, i, j, k):\n if i < 0 or j < 0 or k < 0:\n return 0\n if i == 0 and j == 0:\n return k == arr[i][j]\n if dp[i][j][k] != -1:\n return dp[i][j][k]\n dp[i][j][k] = dfs(arr, i - 1, j, k - arr[i][j]) + dfs(arr, i, j - 1, k - arr[i][j])\n return dp[i][j][k]\n r = len(arr)\n c = len(arr[0])\n dp = [[[-1 for i in range(K + 1)] for j in range(c)] for m in range(r)]\n z = dfs(arr, r - 1, c - 1, K)\n if z == False:\n return 0\n else:\n return z", "def numberofpath(N, K, arr):\n dp = [[[-1] * (K + 1) for _ in range(N)] for __ in range(N)]\n\n def recur(i, j, k, dp):\n if i >= N or j >= N or k < 0:\n return 0\n if i == N - 1 and j == N - 1:\n if k == arr[i][j]:\n return 1\n return 0\n if dp[i][j][k] != -1:\n return dp[i][j][k]\n dp[i][j][k] = recur(i + 1, j, k - arr[i][j], dp) + recur(i, j + 1, k - arr[i][j], dp)\n return dp[i][j][k]\n return recur(0, 0, K, dp)", "def numberofpath(N, K, arr):\n m = len(arr)\n n = len(arr[0])\n\n def check(i, j, K):\n if i < 0 or j < 0 or K < 1:\n return 0\n if i == 0 and j == 0:\n if K == arr[i][j]:\n return 1\n else:\n return 0\n if dp[i][j][K] != -1:\n return dp[i][j][K]\n first = check(i - 1, j, K - arr[i][j])\n second = check(i, j - 1, K - arr[i][j])\n dp[i][j][K] = first + second\n return dp[i][j][K]\n dp = [[[-1 for i in range(K + 1)] for i in range(n)] for i in range(n)]\n return check(m - 1, n - 1, K)", "def memo(m, n, cost, grid, dp):\n if m == 0 and n == 0:\n return 1 if cost - grid[m][n] == 0 else 0\n if m < 0 or n < 0 or cost < 0:\n return 0\n if dp[m][n][cost] != -1:\n return dp[m][n][cost]\n dp[m][n][cost] = self.memo(m - 1, n, cost - grid[m][n], grid, dp) + self.memo(m, n - 1, cost - grid[m][n], grid, dp)\n return dp[m][n][cost]\n\ndef numberofpath(N, K, arr):\n dp = [[[-1] * (K + 1) for j in range(N)] for i in range(N)]\n return self.memo(N - 1, N - 1, K, arr, dp)", "def numberofpath(n, k, l):\n dp = [[{} for _ in range(n)] for _ in range(n)]\n dp[-1][-1][l[-1][-1]] = 1\n for i in range(n - 2, -1, -1):\n for t in dp[i + 1][-1]:\n x = t + l[i][-1]\n if x <= k:\n if x in dp[i][-1]:\n dp[i][-1][x] += dp[i + 1][-1][t]\n else:\n dp[i][-1][x] = dp[i + 1][-1][t]\n for t in dp[-1][i + 1]:\n x = t + l[-1][i]\n if x <= k:\n if x in dp[-1][i]:\n dp[-1][i][x] += dp[-1][i + 1][t]\n else:\n dp[-1][i][x] = dp[-1][i + 1][t]\n for i in range(n - 2, -1, -1):\n for j in range(n - 2, -1, -1):\n for t in dp[i + 1][j]:\n x = t + l[i][j]\n if x <= k:\n if x in dp[i][j]:\n dp[i][j][x] += dp[i + 1][j][t]\n else:\n dp[i][j][x] = dp[i + 1][j][t]\n for t in dp[i][j + 1]:\n x = t + l[i][j]\n if x <= k:\n if x in dp[i][j]:\n dp[i][j][x] += dp[i][j + 1][t]\n else:\n dp[i][j][x] = dp[i][j + 1][t]\n if k in dp[0][0]:\n return dp[0][0][k]\n return 0", "import sys\nsys.setrecursionlimit(10 ** 6)\n\ndef go(n, m, k):\n if k < 0:\n return 0\n if m < 0 or n < 0:\n return 0\n if n == 0 and m == 0:\n self.dp[n][m][k] = 1 if k == self.a[n][m] else 0\n return self.dp[n][m][k]\n if self.dp[n][m][k] != -1:\n return self.dp[n][m][k]\n left = self.go(n, m - 1, k - self.a[n][m])\n up = self.go(n - 1, m, k - self.a[n][m])\n self.dp[n][m][k] = left + up\n return self.dp[n][m][k]\n\ndef numberofpath(n, k, arr):\n for i in range(n):\n for j in range(n):\n self.a[i][j] = arr[i][j]\n for i in range(n):\n for j in range(n):\n for l in range(k + 1):\n self.dp[i][j][l] = -1\n self.go(n - 1, n - 1, k)\n return self.dp[n - 1][n - 1][k]", "def numberofpath(N, K, arr):\n dp = [[[-1 for _ in range(K + 1)] for _ in range(N)] for _ in range(N)]\n return self.solve(arr, dp, N, K, 0, 0, 0)\n\ndef solve(arr, dp, N, K, x, y, k):\n if x >= N or y >= N or x < 0 or (y < 0) or (k + arr[x][y] > K):\n return 0\n if x == N - 1 and y == N - 1 and (k + arr[x][y] == K):\n return 1\n if dp[x][y][k] != -1:\n return dp[x][y][k]\n dp[x][y][k] = self.solve(arr, dp, N, K, x + 1, y, k + arr[x][y]) + self.solve(arr, dp, N, K, x, y + 1, k + arr[x][y])\n return dp[x][y][k]", "def recur(m, n, k, a):\n global dp\n if m < 0 or n < 0 or k < 0:\n return 0\n if m == 0 and n == 0:\n return k == a[0][0]\n if dp[m][n][k]:\n return dp[m][n][k]\n dp[m][n][k] = self.recur(m - 1, n, k - a[m][n], a) + self.recur(m, n - 1, k - a[m][n], a)\n return dp[m][n][k]\n\ndef numberofpath(N, K, arr):\n global dp\n dp = [[[0 for i in range(K + 1)] for j in range(N)] for k in range(N)]\n ans = self.recur(N - 1, N - 1, K, arr)\n return ans if ans else 0", "def f(cr, cc, n, k, arr, dp):\n if cr == n - 1 and cc == n - 1:\n if k == 0:\n return 1\n return 0\n if k < 0:\n return 0\n state = (cr, cc, k)\n if state in dp:\n return dp[state]\n if cc + 1 < n:\n a1 = self.f(cr, cc + 1, n, k - arr[cr][cc + 1], arr, dp)\n else:\n a1 = 0\n if cr + 1 < n:\n a2 = self.f(cr + 1, cc, n, k - arr[cr + 1][cc], arr, dp)\n else:\n a2 = 0\n dp[state] = a1 + a2\n return a1 + a2\n\ndef numberofpath(N, K, arr):\n cr = 0\n cc = 0\n n = N\n k = K\n dp = {}\n return self.f(cr, cc, n, k - arr[cr][cc], arr, dp)", "def numberofpath(N, K, arr):\n memo = [[[-1] * (K + 1) for j in range(N)] for i in range(N)]\n return self.dfs(0, 0, N, arr, K, memo)\n\ndef dfs(i, j, N, arr, k, memo):\n if i < 0 or i > N - 1 or j < 0 or (j > N - 1):\n return 0\n if memo[i][j][k] != -1:\n return memo[i][j][k]\n if k - arr[i][j] < 0:\n return 0\n if k - arr[i][j] == 0 and i == N - 1 and (j == N - 1):\n return 1\n count = 0\n count += self.dfs(i, j + 1, N, arr, k - arr[i][j], memo)\n count += self.dfs(i + 1, j, N, arr, k - arr[i][j], memo)\n memo[i][j][k] = count\n return count", "def solve(i, j, N, K, arr, dp):\n if i < 0 or j < 0 or K < 0:\n return 0\n elif i == 0 and j == 0:\n return int(K == arr[i][j])\n if dp[i][j][K] != -1:\n return dp[i][j][K]\n dp[i][j][K] = self.solve(i - 1, j, N, K - arr[i][j], arr, dp) + self.solve(i, j - 1, N, K - arr[i][j], arr, dp)\n return dp[i][j][K]\n\ndef numberofpath(N, K, arr):\n dp = [[[-1 for k in range(K + 1)] for j in range(N)] for i in range(N)]\n return self.solve(N - 1, N - 1, N, K, arr, dp)", "def numberofpath(N, K, arr):\n\n def helper(i, j, s, memo):\n if i >= N or j >= N or s <= 0:\n return 0\n if i == N - 1 and j == N - 1 and (s == arr[i][j]):\n return 1\n key = (i, j, s)\n if key in memo:\n return memo[key]\n memo[key] = helper(i + 1, j, s - arr[i][j], memo) + helper(i, j + 1, s - arr[i][j], memo)\n return memo[key]\n memo = {}\n return helper(0, 0, K, memo)", "def numberofpath(N, K, arr):\n d = {}\n\n def calPathSum(i, j, s):\n if (i, j, s) in d:\n return d[i, j, s]\n if i < 0 or i >= N or j < 0 or (j >= N):\n d[i, j, s] = 0\n return 0\n if i == N - 1 and j == N - 1:\n if s + arr[i][j] == K:\n d[i, j, s] = 1\n return 1\n else:\n d[i, j, s] = 0\n return 0\n else:\n p1 = calPathSum(i + 1, j, arr[i][j] + s)\n p2 = calPathSum(i, j + 1, arr[i][j] + s)\n d[i, j, s] = p1 + p2\n return p1 + p2\n return calPathSum(0, 1, 1) + calPathSum(1, 0, 1)", "def numberofpath(N, K, arr):\n return self.paths(0, 0, K, arr, N, {})\n\ndef paths(cr, cc, K, arr, N, memo):\n if cr >= N or cc >= N:\n return 0\n if cr == N - 1 and cc == N - 1:\n if K - arr[cr][cc] != 0:\n return 0\n if cr == N - 1 and cc == N - 1:\n if K - arr[cr][cc] == 0:\n return 1\n currentKey = str(cr) + '-' + str(cc) + '-' + str(K)\n if currentKey in memo:\n return memo[currentKey]\n one = self.paths(cr + 1, cc, K - arr[cr][cc], arr, N, memo)\n two = self.paths(cr, cc + 1, K - arr[cr][cc], arr, N, memo)\n memo[currentKey] = one + two\n return memo[currentKey]", "def dfs(r, c, M, N, K, memo):\n if (r, c, K) in memo:\n return memo[r, c, K]\n if K < 0:\n return 0\n if (r, c) == (N - 1, N - 1):\n if K == 0:\n return 1\n return 0\n ans = 0\n for (nr, nc) in [(r + 1, c), (r, c + 1)]:\n if nr == N:\n continue\n if nc == N:\n continue\n ans += dfs(nr, nc, M, N, K - M[nr][nc], memo)\n memo[r, c, K] = ans\n return ans\n\ndef numberofpath(N, K, M):\n return dfs(0, 0, M, N, K - M[0][0], {})", "def numberofpath(N, K, arr):\n memo = {}\n\n def h(i, j, sum):\n if i >= N or j >= N or sum > K:\n return 0\n if i == N - 1 and j == N - 1:\n return int(sum + arr[i][j] == K)\n if (i, j, sum) in memo:\n return memo[i, j, sum]\n memo[i, j, sum] = h(i + 1, j, arr[i][j] + sum) + h(i, j + 1, arr[i][j] + sum)\n return memo[i, j, sum]\n return h(0, 0, 0)"], "starter_code": "def numberofpath (N, K, arr):\n", "input_output": {"inputs": ["K = 12, N = 3\r\narr[] = [[1, 2, 3], \r\n [4, 6, 5], \r\n [3, 2, 1]]", "K = 16, N = 3\r\narr[] = [[1, 2, 3], \r\n [4, 6, 5], \r\n [9, 8, 7]]"], "outputs": ["2", "0"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Recursion", "Matrix", "Data Structures", "Backtracking", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Dynamic programming", "Data structures", "Complete search"], "skill_types": ["Dynamic programming", "Data structures", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/number-of-paths-in-a-matrix-with-k-coins2728/1", "Expected Auxiliary Space": "O(n*n*k)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n*n*k)", "entry_point": "numberofpath", "task_id": "TACO_lite/91", "example": [[[12, 3, [[1, 2, 3], [4, 6, 5], [3, 2, 1]]], [16, 3, [[1, 2, 3], [4, 6, 5], [9, 8, 7]]]], ["2", "0"]]} +{"requirement": "A [Mersenne prime](https://en.wikipedia.org/wiki/Mersenne_prime) is a prime number that can be represented as:\nMn = 2^(n) - 1. Therefore, every Mersenne prime is one less than a power of two. \n\nWrite a function that will return whether the given integer `n` will produce a Mersenne prime or not.\n\nThe tests will check random integers up to 2000.", "solutions": ["def valid_mersenne(n):\n return n in {2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279}", "def valid_mersenne(n):\n if n < 2:\n return False\n if n == 2:\n return True\n mersenne = 2 ** n - 1\n residue = 4\n for _ in range(n - 2):\n residue = (residue * residue - 2) % mersenne\n return not residue", "def valid_mersenne(n):\n return n == 2 or (is_prime(n) and lucas_lehmer(n))\n\ndef is_prime(n):\n from itertools import chain\n return all((n % i != 0 for i in chain([2], range(3, int(n ** 0.5) + 1, 2))))\n\ndef lucas_lehmer(n):\n s = 4\n M = 2 ** n - 1\n for _ in range(n - 2):\n s = (s * s - 2) % M\n return s == 0", "A000043 = {2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457, 32582657, 37156667, 42643801, 43112609}\n\ndef valid_mersenne(n):\n return n in A000043", "def valid_mersenne(n):\n return n in [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941]", "valid_mersenne = {2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279}.__contains__"], "starter_code": "def valid_mersenne(n):\n", "input_output": {"fn_name": "valid_mersenne", "inputs": [[2], [3], [5], [7], [11], [13], [17], [19], [21], [23], [31], [49], [61], [89], [107], [127], [221], [521], [607], [1279]], "outputs": [[true], [true], [true], [true], [false], [true], [true], [true], [false], [false], [true], [false], [true], [true], [true], [true], [false], [true], [true], [true]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/56af6e4198909ab73200013f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "valid_mersenne", "task_id": "TACO_lite/144", "example": [[], []]} +{"requirement": "Given a number N, print all the numbers which are a bitwise subset of the binary representation of N. Bitwise subset of a number N will be the numbers i in the range 0 ≤ i ≤ N which satisfy the below condition:\nN & i == i\nExample 1:\nInput:\nN = 5\nOutput: 5 4 1 0\nExplanation:\n 0 & 5 = 0\n 1 & 5 = 1\n 2 & 5 = 0\n 3 & 5 = 1\n 4 & 5 = 4\n 5 & 5 = 5\n \nExample 2:\nInput:\nN = 9\nOutput: 9 8 1 0\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function printSubsets() which takes the integer N as input parameters and returns the array of integers that satisfy the above condition.\nExpected Time Complexity: O(K), where K is the number of bitwise subsets of N.\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 ≤ N ≤ 10000", "solutions": ["def printsubsets(N):\n b = []\n for i in range(N + 1):\n if N & i == i:\n b.append(i)\n return list(reversed(b))", "def printsubsets(N):\n output = set([N])\n num = bin(N)[2:]\n num = num[::-1]\n for i in range(len(num)):\n if num[i] == '1':\n temp = set()\n for item in output:\n temp.add(item - 2 ** i)\n output.update(temp)\n return sorted(output, reverse=True)", "def printsubsets(n):\n res = []\n i = n\n while i != 0:\n res.append(i)\n i = i - 1 & n\n res.append(0)\n return res", "def printsubsets(N):\n pass\n a = set()\n for i in range(N + 1):\n a.add(i & N)\n return sorted(list(a), reverse=True)", "def printsubsets(N):\n a = []\n for i in range(0, N + 1):\n a.insert(0, N & i)\n a = list(set(a))\n a.sort()\n a = a[::-1]\n return a", "def printsubsets(N):\n ls = []\n i = N\n while i >= 0:\n if i & N == i:\n ls.append(i)\n i -= 1\n return ls", "def printsubsets(N):\n l = []\n for i in range(0, N + 1):\n if N & i not in l:\n l.append(N & i)\n l.sort(reverse=True)\n return l", "def printsubsets(N):\n pass\n L = []\n for i in range(N + 1):\n if N & i == i:\n L.append(i)\n return L[::-1]", "def printsubsets(N):\n ans = []\n for i in range(0, N + 1):\n x = i & N\n if x == i or x == N:\n ans.append(x)\n ans = ans[::-1]\n return ans", "def printsubsets(N):\n pass\n x = [i for i in range(0, N + 1) if N & i == i]\n return x[::-1]", "def printsubsets(N):\n pass\n u = []\n for i in range(0, N + 1):\n if N & i == i:\n u.append(i)\n return u[::-1]", "def printsubsets(N):\n s = bin(N)[2:]\n ans = [0]\n s = s[::-1]\n for i in range(len(s)):\n if s[i] == '1':\n k = len(ans)\n for j in range(k):\n ans.append(ans[j] + 2 ** i)\n return ans[::-1]", "def printsubsets(N):\n bit = str(bin(N)[2:])\n ans = [0]\n count = 0\n for i in bit[::-1]:\n if i == '1':\n length = len(ans)\n for x in range(length):\n ans.append((1 << count) + ans[x])\n count += 1\n return ans[::-1]", "def printsubsets(N):\n arr = []\n for i in range(N, -1, -1):\n if N & i == i:\n arr.append(i)\n return arr", "def printsubsets(N):\n pass\n arr = []\n for i in range(N + 1):\n temp = i & N\n if temp not in arr:\n arr.append(temp)\n arr.sort(reverse=True)\n return arr", "def printsubsets(N):\n n = N\n AA = []\n for i in range(n + 1):\n if n & i == i:\n AA.append(i)\n return AA[::-1]", "def printsubsets(N):\n a = N\n c = []\n while a >= 0:\n b = a & N\n if a == b:\n c.append(a)\n a = a - 1\n return c\n pass"], "starter_code": "def printsubsets (N):\n", "input_output": {"inputs": ["N = 5", "N = 9"], "outputs": ["5 4 1 0", "9 8 1 0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Binary Representation", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/print-all-bitwise-subsets-of-a-number-n3301/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(K), where K is the number of bitwise subsets of N.", "entry_point": "printsubsets", "task_id": "TACO_lite/81", "example": [[], []]} +{"requirement": "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.\n\n\nFor example, with A = \"abcd\" and B = \"cdabcdab\". \n\n\nReturn 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times (\"abcdabcd\").\n\n\nNote:\nThe length of A and B will be between 1 and 10000.", "solutions": ["def repeatedstringmatch(A, B):\n if not set(B).issubset(set(A)):\n return -1\n max_rep = len(B) // len(A) + 3\n A_new = A\n for i in range(1, max_rep):\n if B in A_new:\n return i\n A_new += A\n return -1", "def repeatedstringmatch(A, B):\n times = 1\n tmp = A\n if not set(B).issubset(set(A)):\n return -1\n maxTime = math.ceil(len(B) / len(A))\n while True:\n if B in A:\n break\n elif times <= maxTime:\n A += tmp\n times += 1\n else:\n return -1\n return times", "def repeatedstringmatch(A, B):\n\n def check(index):\n return all((A[(i + index) % len(A)] == c for (i, c) in enumerate(B)))\n (M, p) = (10 ** 9 + 7, 113)\n p_inv = pow(p, M - 2, M)\n q = (len(B) + len(A) - 1) // len(A)\n (b_hash, power) = (0, 1)\n for c in B:\n b_hash += power * ord(c)\n b_hash %= M\n power = power * p % M\n (a_hash, power) = (0, 1)\n for i in range(len(B)):\n a_hash += power * ord(A[i % len(A)])\n a_hash %= M\n power = power * p % M\n if a_hash == b_hash and check(0):\n return q\n power = power * p_inv % M\n for i in range(len(B), (q + 1) * len(A)):\n a_hash = (a_hash - ord(A[(i - len(B)) % len(A)])) * p_inv\n a_hash += power * ord(A[i % len(A)])\n a_hash %= M\n if a_hash == b_hash and check(i - len(B) + 1):\n return q if i < q * len(A) else q + 1\n return -1", "def repeatedstringmatch1(A, B):\n\n def check(index):\n return all((A[(i + index) % len(A)] == c for (i, c) in enumerate(B)))\n (M, p) = (10 ** 9 + 7, 113)\n p_inv = pow(p, M - 2, M)\n q = (len(B) + len(A) - 1) // len(A)\n (b_hash, power) = (0, 1)\n for c in B:\n b_hash += power * ord(c)\n b_hash %= M\n power = power * p % M\n (a_hash, power) = (0, 1)\n for i in range(len(B)):\n a_hash += power * ord(A[i % len(A)])\n a_hash %= M\n power = power * p % M\n if a_hash == b_hash and check(0):\n return q\n power = power * p_inv % M\n for i in range(len(B), (q + 1) * len(A)):\n a_hash = (a_hash - ord(A[(i - len(B)) % len(A)])) * p_inv\n a_hash += power * ord(A[i % len(A)])\n a_hash %= M\n if a_hash == b_hash and check(i - len(B) + 1):\n return q if i < q * len(A) else q + 1\n return -1\n\ndef repeatedstringmatch(A, B):\n\n def get_fail(s):\n f = [0] * (len(s) + 1)\n for i in range(1, len(s)):\n j = f[i]\n while j and s[i] != s[j]:\n j = f[j]\n if s[i] == s[j]:\n j += 1\n f[i + 1] = j\n return f\n f = get_fail(B)\n j = 0\n vis = {0}\n cnt = 1\n while True:\n for i in range(len(A)):\n while j and A[i] != B[j]:\n j = f[j]\n if A[i] == B[j]:\n j += 1\n if j == len(B):\n return cnt\n if j in vis:\n return -1\n vis.add(j)\n cnt += 1\n return -1", "def repeatedstringmatch(A, B):\n k = int(len(B) / len(A))\n m = ''\n h = A + A[0]\n for i in range(len(B) - 1):\n if B[i:i + 2] not in h:\n return -1\n for i in range(k):\n m += A\n while B not in m:\n m += A\n k += 1\n if k > 100:\n return -1\n return k", "def repeatedstringmatch(A, B):\n if set(list(B)) > set(list(A)):\n return -1\n l_b = len(B)\n pointer_b = 0\n l_a = len(A)\n pointer_a = 0\n L = []\n while pointer_a < l_a:\n if A[pointer_a] == B[pointer_b]:\n L.append(pointer_a)\n pointer_a += 1\n if L == []:\n return -1\n for pointer_a in L:\n times = 1\n while pointer_b < l_b:\n if pointer_a == l_a:\n pointer_a = 0\n times += 1\n if B[pointer_b] == A[pointer_a]:\n pointer_b += 1\n pointer_a += 1\n continue\n else:\n break\n if pointer_b == l_b:\n return times\n else:\n pointer_b = 0\n return -1", "def repeatedstringmatch(A, B):\n if A == B or B in A:\n return 1\n if A not in B:\n if B not in A + A:\n return -1\n else:\n return 2\n else:\n (count, i) = (1, B.index(A))\n if i != 0:\n if B[:i] != A[-i:]:\n return -1\n else:\n count = 2\n while i + 2 * len(A) < len(B) and A == B[i + len(A):i + 2 * len(A)]:\n count += 1\n i = B.index(A, i + len(A))\n if i == len(B) - len(A):\n return count\n else:\n if B[i + len(A):] != A[:len(B) - i - len(A)]:\n return -1\n return count + 1", "def repeatedstringmatch(A, B):\n for i in range(len(A)):\n if A[i] == B[0]:\n divisible = True if (len(B) - (len(A) - i)) % len(A) == 0 else False\n time = 1 + (len(B) - (len(A) - i)) // len(A) if divisible else 1 + (len(B) - (len(A) - i)) // len(A) + 1\n repeatA = A * time\n if repeatA[i:i + len(B)] == B:\n return time\n return -1", "def repeatedstringmatch(a, b):\n if a is None or len(a) == 0 or b is None or (len(b) == 0):\n return -1\n if a == b:\n return 1\n kmp = [0 for _ in range(len(b) + 1)]\n j = 0\n for i in range(1, len(b)):\n if b[j] == b[i]:\n j += 1\n kmp[i] = j\n elif j == 0:\n i += 1\n else:\n j = kmp[j - 1]\n j = 0\n for i in range(len(a)):\n while j < len(b) and a[(i + j) % len(a)] == b[j]:\n j += 1\n if j == len(b):\n return -(-(i + j) // len(a))\n j = kmp[j - 1]\n return -1", "def repeatedstringmatch(text, pattern):\n (n, m) = (len(text), len(pattern))\n (base, prime) = (256, 257)\n bpow = base ** (m - 1) % prime\n\n def check(i):\n for j in range(m):\n if text[(i + j) % n] != pattern[j]:\n return False\n return True\n\n def compute_hash(s):\n (n, h) = (len(s), 0)\n for i in range(m):\n c = s[i % n]\n h = (h * base + ord(c)) % prime\n return h\n\n def update_hash(h, old, new):\n dh = ord(old) * bpow % prime\n h = (h - dh + prime) % prime\n h = (h * base + ord(new)) % prime\n return h\n p = compute_hash(pattern)\n t = compute_hash(text)\n for i in range(n):\n if t == p and check(i):\n return 1 + (i + m - 1) // n\n t = update_hash(t, text[i], text[(i + m) % n])\n return -1"], "starter_code": "def repeatedstringmatch(a: str, b: str) -> int:\n", "input_output": {"fn_name": "repeatedStringMatch", "inputs": [["\"abcd\"", "\"cdabcdab\""]], "outputs": [-1]}, "difficulty": "EASY", "raw_tags": ["String Matching", "String"], "name": null, "source": "leetcode", "tags": ["String algorithms"], "skill_types": [], "url": "https://leetcode.com/problems/repeated-string-match/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "repeatedstringmatch", "task_id": "TACO_lite/120", "example": [[["abcd", "cdabcdab"]], ["3"]]} +{"requirement": "Given an array A of size N of integers. Your task is to find the sum of minimum and maximum element in the array.\nExample 1:\nInput:\nN = 5\nA[] = {-2, 1, -4, 5, 3}\nOutput: 1\nExplanation: min = -4, max = 5. Sum = -4 + 5 = 1\n \nExample 2:\nInput:\nN = 4\nA[] = {1, 3, 4, 1}\nOutput: 5\nExplanation: min = 1, max = 4. Sum = 1 + 4 = 5\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function findSum() which takes the array A[] and its size N as inputs and returns the summation of minimum and maximum element of the array.\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= N <= 10^{5}\n-10^{9} <= A_{i} <= 10^{9}", "solutions": ["def findsum(A, N):\n A.sort()\n return A[0] + A[len(A) - 1]", "def findsum(A, N):\n return max(A) + min(A)", "def findsum(A, N):\n maxval = A[0]\n minval = maxval\n for i in range(1, N):\n if A[i] > maxval:\n maxval = A[i]\n continue\n if A[i] < minval:\n minval = A[i]\n continue\n return minval + maxval", "def findsum(A, N):\n self.A = A\n self.N = N\n max_val = max(A)\n min_val = min(A)\n return max_val + min_val", "def findsum(A, N):\n A.sort()\n sum = A[0] + A[N - 1]\n return sum", "def findsum(A, N):\n a = min(A)\n b = max(A)\n return a + b", "def findsum(arr, arr_size):\n max = 0\n min = 0\n i = 0\n if arr_size % 2 == 1:\n max = arr[0]\n min = arr[0]\n i = 1\n else:\n if arr[0] < arr[1]:\n max = arr[1]\n min = arr[0]\n else:\n max = arr[0]\n min = arr[1]\n i = 2\n while i < arr_size:\n if arr[i] < arr[i + 1]:\n if arr[i] < min:\n min = arr[i]\n if arr[i + 1] > max:\n max = arr[i + 1]\n else:\n if arr[i] > max:\n max = arr[i]\n if arr[i + 1] < min:\n min = arr[i + 1]\n i = i + 2\n return max + min", "def findsum(A, N):\n a = A[0]\n b = A[0]\n for i in range(N):\n if a > A[i]:\n a = A[i]\n if b < A[i]:\n b = A[i]\n return a + b", "def findsum(A, N):\n d = min(A)\n m = max(A)\n result = d + m\n return result", "def findsum(A, N):\n min = 99999999\n max = -999999\n for i in range(0, N):\n if A[i] < min:\n min = A[i]\n if A[i] > max:\n max = A[i]\n return max + min", "def findsum(A, N):\n min_a = 10 ** 9\n max_b = -10 ** 9\n for i in range(len(A)):\n if a[i] > max_b:\n max_b = a[i]\n if a[i] < min_a:\n min_a = a[i]\n return min_a + max_b", "def findsum(A, N):\n largest_element = A[0]\n for i in range(N):\n if A[i] > largest_element:\n largest_element = A[i]\n smallest_element = A[0]\n for i in range(N):\n if A[i] < smallest_element:\n smallest_element = A[i]\n return largest_element + smallest_element", "def findsum(A, N):\n maxx = -10000000\n minn = 10000000\n for i in range(N):\n if A[i] > maxx:\n maxx = A[i]\n if A[i] < minn:\n minn = A[i]\n return maxx + minn", "def findsum(A, N):\n Amax = Amin = A[0]\n for i in range(1, N):\n if A[i] > Amax:\n Amax = A[i]\n elif A[i] < Amin:\n Amin = A[i]\n return Amax + Amin", "def findsum(A, N):\n ma = -999999999\n mi = 9999999999\n for i in range(N):\n if A[i] < mi:\n mi = A[i]\n if ma < A[i]:\n ma = A[i]\n return ma + mi", "def findsum(arr, n):\n maxi = arr[0]\n mini = arr[0]\n for i in range(1, n):\n if arr[i] > maxi:\n maxi = arr[i]\n if arr[i] < mini:\n mini = arr[i]\n return maxi + mini", "def findsum(A, N):\n min_elem = A[0]\n max_elem = A[0]\n for i in range(1, N):\n if A[i] < min_elem:\n min_elem = A[i]\n elif A[i] > max_elem:\n max_elem = A[i]\n return min_elem + max_elem", "def findsum(A, N):\n min = A[0]\n max = A[0]\n for x in A:\n if x < min:\n min = x\n elif x > max:\n max = x\n return max + min", "def findsum(A, N):\n maxi = A[0]\n mini = A[0]\n for i in range(N):\n if A[i] >= maxi:\n maxi = A[i]\n if A[i] <= mini:\n mini = A[i]\n return mini + maxi", "def findsum(A, N):\n max = A[0]\n min = A[0]\n for i in A:\n if i > max:\n max = i\n for i in A:\n if i < min:\n min = i\n return max + min", "def findsum(A, N):\n index = 0\n minimum = A[0]\n maximum = A[0]\n while index < N:\n if minimum > A[index]:\n minimum = A[index]\n if maximum < A[index]:\n maximum = A[index]\n index += 1\n return maximum + minimum", "def findsum(arr, N):\n arr.sort()\n return arr[0] + arr[N - 1]", "def findsum(arr, N):\n return max(arr) + min(arr)", "def findsum(A, N):\n min_num = max_num = A[0]\n for i in range(1, N):\n if A[i] < min_num:\n min_num = A[i]\n elif A[i] > max_num:\n max_num = A[i]\n return min_num + max_num", "def findsum(A, N):\n newarray = sorted(A)\n firstelement = newarray[0]\n lastelement = newarray[-1]\n sumofelement = firstelement + lastelement\n return sumofelement", "def findsum(A, N):\n max_a = max(A)\n min_a = min(A)\n sum_a = max_a + min_a\n return sum_a", "def findsum(A, N):\n max1 = max(A)\n min1 = min(A)\n return max1 + min1", "def findsum(A, N):\n min_val = max_val = A[0]\n for num in A:\n if num < min_val:\n min_val = num\n elif num > max_val:\n max_val = num\n return min_val + max_val", "def findsum(A, N):\n\n def maxMin(A):\n (max, min) = (float('-inf'), float('inf'))\n for i in A:\n if i > max:\n max = i\n if i < min:\n min = i\n return [min, max]\n return sum(maxMin(A))", "import numpy as np\n\ndef findsum(A, N):\n Ar = np.array(A)\n Ar.sort()\n return Ar[0] + Ar[N - 1]", "def findsum(A, N):\n min_val = float('inf')\n max_val = float('-inf')\n for i in range(N):\n if A[i] < min_val:\n min_val = A[i]\n if A[i] > max_val:\n max_val = A[i]\n sum_val = min_val + max_val\n return sum_val", "def findsum(A, N):\n x = max(A)\n y = min(A)\n return x + y", "def findsum(A, N):\n minimum = A[0]\n maximum = A[0]\n sum = 0\n for x in range(0, len(A), +1):\n if A[x] < minimum:\n minimum = A[x]\n elif A[x] > maximum:\n maximum = A[x]\n sum = maximum + minimum\n return sum", "def findsum(A, N):\n min = A[0]\n max = A[0]\n sum = 0\n for x in range(0, len(A), +1):\n if A[x] < min:\n min = A[x]\n elif A[x] > max:\n max = A[x]\n sum = min + max\n return sum", "def findsum(A, N):\n maximum = max(A)\n minimum = min(A)\n Sum = minimum + maximum\n return Sum", "def findsum(A, N):\n m = min(A)\n n = max(A)\n return m + n", "def findsum(A, N):\n s = sorted(A)\n low = s[0]\n high = s[n - 1]\n result = low + high\n return result", "def findsum(A, N):\n c = max(a)\n d = min(a)\n s = c + d\n return s", "def findsum(A, N):\n maxele = -float('inf')\n for i in range(N):\n if maxele < A[i]:\n maxele = A[i]\n minele = float('inf')\n for i in range(N):\n if minele > A[i]:\n minele = A[i]\n return maxele + minele", "def findsum(A, N):\n min = A[0]\n max = A[0]\n for i in range(0, len(A)):\n if A[i] < min:\n min = A[i]\n if A[i] > max:\n max = A[i]\n sum = max + min\n return sum", "def findsum(A, N):\n if N == 0:\n return Null\n else:\n return min(A) + max(A)", "def findsum(A, N):\n min_elem = float('inf')\n max_elem = float('-inf')\n for i in range(N):\n if A[i] < min_elem:\n min_elem = A[i]\n if A[i] > max_elem:\n max_elem = A[i]\n return min_elem + max_elem", "def findsum(A, N):\n import math\n min = math.inf\n max = -math.inf\n for i in range(0, len(A)):\n if A[i] < min:\n min = A[i]\n if A[i] > max:\n max = A[i]\n return max + min", "def findsum(A, N):\n s = A[0]\n l = A[0]\n for i in range(N):\n if s > A[i]:\n s = A[i]\n if l < A[i]:\n l = A[i]\n return l + s", "def findsum(A, N):\n if N == 1:\n sum = A[0] + A[0]\n return sum\n else:\n (min, max) = (A[0], A[0])\n for i in range(N):\n if A[i] < min:\n min = A[i]\n elif A[i] > max:\n max = A[i]\n sum = min + max\n return sum", "def findsum(a, n):\n e = min(a)\n b = max(a)\n return e + b", "def findsum(A, N):\n mini = min(A)\n maxi = max(A)\n return mini + maxi", "def findsum(A, N):\n l = min(A)\n g = max(A)\n s = 0\n s = int(l + g)\n return s", "def findsum(A, N):\n Z = max(A)\n X = min(A)\n sum = Z + X\n return sum", "def findsum(A, N):\n mx = max(A)\n mn = min(A)\n s = mx + mn\n return s", "def findsum(A, N):\n l = list(A)\n mi = min(l)\n ma = max(l)\n sum = int(mi) + int(ma)\n return sum", "def findsum(A, N):\n if N == 0:\n return 0\n if N == 1:\n return 2 * A[0]\n A.sort()\n return A[0] + A[-1]", "def findsum(A, N):\n min_A = min(A)\n max_A = max(A)\n sum_mm = max_A + min_A\n return sum_mm", "def findsum(A, N):\n x = min(A)\n Y = max(A)\n return x + Y", "def findsum(A, N):\n N = len(A)\n if N % 2 == 0:\n mx = max(A[0], A[1])\n mn = min(A[0], A[1])\n i = 2\n else:\n mx = mn = A[0]\n i = 1\n while i < N - 1:\n if A[i] < A[i + 1]:\n mx = max(mx, A[i + 1])\n mn = min(mn, A[i])\n else:\n mx = max(mx, A[i])\n mn = min(mn, A[i + 1])\n i += 2\n return mx + mn", "def findsum(A, N):\n maxi = -99999\n mini = 99999\n for i in range(N):\n maxi = max(A[i], maxi)\n mini = min(A[i], mini)\n sum = maxi + mini\n return sum", "def findsum(A, N):\n maxi = float('-inf')\n mini = float('inf')\n for i in A:\n if i > maxi:\n maxi = i\n if i < mini:\n mini = i\n return maxi + mini", "def findsum(A, N):\n A.sort()\n mini = A[0]\n maxi = A[-1]\n return mini + maxi", "def findsum(A, N):\n minn = 1000000\n maxx = -1000000\n for i in A:\n if i > maxx:\n maxx = i\n if i < minn:\n minn = i\n return minn + maxx", "def findsum(A, N):\n l = max(A)\n b = min(A)\n s = l + b\n return s"], "starter_code": "def findsum(A,N):\n", "input_output": {"inputs": ["N = 5\r\nA[] = {-2, 1, -4, 5, 3}", "N = 4\r\nA[] = {1, 3, 4, 1}"], "outputs": ["1", "5"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Greedy"], "name": null, "source": "geeksforgeeks", "tags": ["Greedy algorithms"], "skill_types": ["Greedy algorithms"], "url": "https://practice.geeksforgeeks.org/problems/max-min/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "findsum", "task_id": "TACO_lite/11", "example": [[[5, [-2, 1, -4, 5, 3]], [4, [1, 3, 4, 1]]], ["1", "5"]]} +{"requirement": "Write a method named `getExponent(n,p)` that returns the largest integer exponent `x` such that p^(x) evenly divides `n`. if `p<=1` the method should return `null`/`None` (throw an `ArgumentOutOfRange` exception in C#).", "solutions": ["def get_exponent(n, p):\n if p > 1:\n x = 0\n while not n % p:\n x += 1\n n //= p\n return x", "def get_exponent(n, p, i=0):\n if p <= 1:\n return None\n return get_exponent(n / p, p, i + 1) if n / p == n // p else i", "from itertools import count\n\ndef get_exponent(n, p):\n if p > 1:\n for res in count():\n (n, r) = divmod(n, p)\n if r:\n return res", "def get_exponent(n, p):\n return next(iter((i for i in range(int(abs(n) ** (1 / p)), 0, -1) if n / p ** i % 1 == 0)), 0) if p > 1 else None", "def get_exponent(n, p):\n if p <= 1:\n return None\n (x, e) = (0, 1)\n while n % e == 0:\n x += 1\n e *= p\n return x - 1", "def get_exponent(n, p):\n i = 1\n if p <= 1:\n return None\n while n % p ** i == 0:\n i += 1\n return i - 1", "def get_exponent(n, p):\n if p <= 1:\n return\n return max([i for i in range(1, int(abs(n) ** 0.5)) if n % p ** i == 0], default=0)", "def get_exponent(n, p):\n if int(p) <= 1:\n return None\n else:\n x = 1\n while n % p ** x == 0:\n x += 1\n return x - 1", "def get_exponent(n, p):\n r = 0\n while n % p ** r == 0 and p > 1:\n r += 1\n if r > 0:\n return r - 1", "from math import log\n\ndef get_exponent(n, p):\n if p <= 1:\n return None\n (l, i) = (None, 0)\n while p ** i <= abs(n):\n if n % p ** i == 0:\n l = i\n i += 1\n return l"], "starter_code": "def get_exponent(n, p):\n", "input_output": {"fn_name": "get_exponent", "inputs": [[27, 3]], "outputs": [[3]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/59b139d69c56e8939700009d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "get_exponent", "task_id": "TACO_lite/37", "example": [[], []]} +{"requirement": "## Task\n\nGiven `n` representing the number of floors build a beautiful multi-million dollar mansions like the ones in the example below:\n\n```\n /\\\n / \\\n / \\\n /______\\ number of floors 3\n | |\n | |\n |______|\n\n /\\\n / \\\n /____\\\n | | 2 floors\n |____|\n\n /\\\n /__\\ 1 floor\n |__|\n```\n\n**Note:** whitespace should be preserved on both sides of the roof. Number of floors will go up to 30. There will be no tests with invalid input.\n\nIf you manage to complete it, you can try a harder version [here](https://www.codewars.com/kata/58360d112fb0ba255300008b).\n\nGood luck!", "solutions": ["def my_crib(n):\n roof = '\\n'.join(('%s/%s\\\\%s' % (' ' * (n - i), ' ' * i * 2, ' ' * (n - i)) for i in range(n)))\n ceiling = '\\n/%s\\\\\\n' % ('_' * (n * 2))\n walls = '|%s|\\n' % (' ' * (n * 2)) * (n - 1)\n floor = '|%s|' % ('_' * (n * 2))\n return roof + ceiling + walls + floor", "def my_crib(n):\n roof = [('/' + ' ' * k + '\\\\').center(2 * n + 2) for k in range(0, 2 * n, 2)]\n ceiling = ['/' + '_' * 2 * n + '\\\\']\n walls = ['|' + ' ' * 2 * n + '|'] * (n - 1)\n floor = ['|' + '_' * 2 * n + '|']\n return '\\n'.join(roof + ceiling + walls + floor)", "def my_crib(n):\n return '\\n'.join([' ' * (n - i) + '/' + ' ' * 2 * i + '\\\\' + ' ' * (n - i) for i in range(n)] + ['/' + '_' * 2 * n + '\\\\'] + ['|' + ' ' * 2 * n + '|'] * (n - 1) + ['|' + '_' * 2 * n + '|'])", "def my_crib(n):\n (l, res) = (n + 1 << 1, [])\n res.extend(('/' + ' ' * (2 * i) + '\\\\' for i in range(n)))\n res.append('/' + '_' * (2 * n) + '\\\\')\n res.extend(('|' + ' ' * (l - 2) + '|' for _ in range(n - 1)))\n res.append('|' + '_' * (l - 2) + '|')\n return '\\n'.join((s.center(l) for s in res))", "def my_crib(n):\n crib = [f'{mult(n - i)}/{mult(i * 2)}\\\\{mult(n - i)}' for i in range(n)]\n crib.append(f\"/{mult(n * 2, '_')}\\\\\")\n crib.extend((f'|{mult(n * 2)}|' for _ in range(n - 1)))\n crib.append(f\"|{mult(n * 2, '_')}|\")\n return '\\n'.join(crib)\n\ndef mult(n, char=' '):\n return char * n", "import itertools\n\ndef my_crib(n):\n\n def format(chars, fill_width):\n return '{chars[0]}{chars[2]:{chars[1]}>{width}}'.format(chars=chars, width=fill_width + 1).center(2 * n + 2)\n return '\\n'.join(itertools.chain((format('/ \\\\', 2 * i) for i in range(n)), (format('/_\\\\', 2 * n),), (format('| |', 2 * n) for _ in range(n - 1)), (format('|_|', 2 * n),)))", "my_crib = lambda n: '\\n'.join([('/' + [' ', '_'][i == n] * (i * 2) + '\\\\').center(n * 2 + 2, ' ') for i in range(n + 1)]) + '\\n' + '\\n'.join(['|' + [' ', '_'][i == n - 1] * (n * 2) + '|' for i in range(n)])", "def my_crib(n):\n roof = '\\n'.join(('{0}/{1}\\\\{0}'.format(' ' * (n - i), ' _'[n == i] * i * 2) for i in range(n + 1)))\n x = lambda a: '\\n|' + a * n * 2 + '|'\n return roof + x(' ') * (n - 1) + x('_')"], "starter_code": "def my_crib(n):\n", "input_output": {"fn_name": "my_crib", "inputs": [[1], [2], [3]], "outputs": [[" /\\ \n/__\\\n|__|"], [" /\\ \n / \\ \n/____\\\n| |\n|____|"], [" /\\ \n / \\ \n / \\ \n/______\\\n| |\n| |\n|______|"]]}, "difficulty": "EASY", "raw_tags": ["ASCII Art", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5834a44e44ff289b5a000075", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "my_crib", "task_id": "TACO_lite/51", "example": [[], []]} +{"requirement": "Evaluate the value of an arithmetic expression in Reverse Polish Notation.\n\nValid operators are +, -, *, /. Each operand may be an integer or another expression.\n\nNote:\n\n\n Division between two integers should truncate toward zero.\n The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.\n\n\nExample 1:\n\n\nInput: [\"2\", \"1\", \"+\", \"3\", \"*\"]\nOutput: 9\nExplanation: ((2 + 1) * 3) = 9\n\n\nExample 2:\n\n\nInput: [\"4\", \"13\", \"5\", \"/\", \"+\"]\nOutput: 6\nExplanation: (4 + (13 / 5)) = 6\n\n\nExample 3:\n\n\nInput: [\"10\", \"6\", \"9\", \"3\", \"+\", \"-11\", \"*\", \"/\", \"*\", \"17\", \"+\", \"5\", \"+\"]\nOutput: 22\nExplanation: \n ((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22", "solutions": ["def evalrpn(tokens):\n s = []\n for token in tokens:\n if token == '+':\n a = int(s.pop())\n b = int(s.pop())\n s.append(a + b)\n elif token == '/':\n a = int(s.pop())\n b = int(s.pop())\n s.append(b / a)\n elif token == '*':\n a = int(s.pop())\n b = int(s.pop())\n s.append(a * b)\n elif token == '-':\n a = int(s.pop())\n b = int(s.pop())\n s.append(b - a)\n else:\n s.append(token)\n if len(s) is not 1:\n return False\n else:\n return int(s.pop())"], "starter_code": "def evalrpn(tokens: List[str]) -> int:\n", "input_output": {"fn_name": "evalRPN", "inputs": [[["\"2\"", "\"1\""]]], "outputs": [0]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Stack", "Math", "Array"], "name": null, "source": "leetcode", "tags": ["Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/evaluate-reverse-polish-notation/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "evalrpn", "task_id": "TACO_lite/26", "example": [[[["2", "1", "+", "3", "*"]], [["4", "13", "5", "/", "+"]], [["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]]], ["9", "6", "22"]]} +{"requirement": "Given two numbers, A and B. Find the number of common divisors of A and B. \n \nExample 1:\n​Input : A = 2 and B = 4\nOutput : 2\nExplanation:\nThere are only two common divisor of 2 and 4.\nThat is 1 and 2.\n​Example 2:\nInput : A = 3 and B = 5 \nOutput : 1\n \nYour Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function common_divisor() that takes an integer A, another integer B, and return the number of the common divisor of A and B. The driver code takes care of the printing.\nExpected Time Complexity: O(SQRT(min(A,B))).\nExpected Auxiliary Space: O(1).\n \nConstraints:\n1 ≤ A, B ≤ 10^{7}", "solutions": ["def common_divisor(n, m):\n c = 0\n for i in range(1, m + 1):\n if n % i == 0 and m % i == 0:\n c += 1\n return c", "def common_divisor(n, m):\n x = min(n, m)\n lis = [i for i in range(1, x + 1) if n % i == 0 and m % i == 0]\n return len(lis)", "def common_divisor(n, m):\n count = 0\n if n > m:\n a = n\n else:\n a = m\n for i in range(1, a + 1):\n if n % i == 0 and m % i == 0:\n count += 1\n return count", "def common_divisor(n, m):\n import math\n ans = 0\n gcd = math.gcd(n, m)\n for i in range(1, gcd + 1):\n if (n % i == 0) & (m % i == 0):\n ans += 1\n return ans", "import math\n\ndef common_divisor(n, m):\n (m, n) = (min(m, n), max(m, n))\n result = 0\n i = 1\n while i <= math.sqrt(m):\n if n % i == 0 and m % i == 0:\n result += 1\n if n % (m // i) == 0 and m % (m // i) == 0 and (i != m // i):\n result += 1\n i += 1\n return result", "def gcd(n, m):\n if m > n:\n temp = n\n n = m\n m = temp\n if n == 0:\n return m\n if m == 0:\n return n\n return gcd(m, n % m)\n\ndef common_divisor(n, m):\n x = gcd(n, m)\n sm = 0\n for i in range(1, x + 1):\n if x % i == 0:\n sm += 1\n return sm", "from math import sqrt\n\ndef common_divisor(n, m):\n\n def gcd(a, b):\n if a == 0:\n return b\n return gcd(b % a, a)\n c = 0\n n = gcd(n, m)\n x = int(sqrt(n))\n for i in range(1, x + 1):\n if n % i == 0:\n if n / i == i:\n c += 1\n else:\n c += 2\n return c", "def common_divisor(n, m):\n count = 0\n s = min(m, n) + 1\n for i in range(1, s):\n if n % i == 0 and m % i == 0:\n count = count + 1\n return count", "def greatest_divisor(n, m):\n if m == 0:\n return n\n return greatest_divisor(m, n % m)\n\ndef common_divisor(n, m):\n c = 0\n g_divisior = greatest_divisor(n, m)\n r = int(g_divisior ** (1 / 2))\n for i in range(1, r + 1):\n if g_divisior % i == 0:\n c += 2\n if i * i == g_divisior:\n c -= 1\n return c", "def common_divisor(n, m):\n l = []\n k = []\n ans = []\n for i in range(1, min(n, m) + 1):\n if n % i == 0 and m % i == 0:\n l.append(i)\n return len(l)", "def common_divisor(n, m):\n result = 0\n if m < n:\n d = m\n else:\n d = n\n for i in range(1, d + 1):\n if n % i == 0 and m % i == 0:\n result += 1\n return result", "def common_divisor(n, m):\n c = 0\n if n < m:\n a = n\n else:\n a = m\n for i in range(1, a + 1):\n if n % i == 0 and m % i == 0:\n c += 1\n else:\n pass\n return c"], "starter_code": "def common_divisor (n, m) :\n", "input_output": {"fn_name": "common_divisor", "inputs": ["A = 2 and B = 4", "A = 3 and B = 5"], "outputs": ["2", "1"]}, "difficulty": "EASY", "raw_tags": ["number-theory"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/common-divisor0847/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(SQRT(min(A,B))).", "entry_point": "common_divisor", "task_id": "TACO_lite/109", "example": [[[2, 4], [3, 5]], ["2", "1"]]} +{"requirement": "Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K, and add x to A[i] (only once).\nAfter this process, we have some array B.\nReturn the smallest possible difference between the maximum value of B and the minimum value of B.\n \n\n\n\nExample 1:\nInput: A = [1], K = 0\nOutput: 0\nExplanation: B = [1]\n\n\nExample 2:\nInput: A = [0,10], K = 2\nOutput: 6\nExplanation: B = [2,8]\n\n\nExample 3:\nInput: A = [1,3,6], K = 3\nOutput: 3\nExplanation: B = [4,6,3]\n\n \nNote:\n\n1 <= A.length <= 10000\n0 <= A[i] <= 10000\n0 <= K <= 10000", "solutions": ["def smallestrangeii(A: List[int], K: int) -> int:\n if not A:\n return 0\n nums = sorted([num + K for num in set(A)], reverse=True)\n max_num = nums[0]\n min_num = nums[-1]\n changed_max = max_num - 2 * K\n res = max_num - min_num\n for i in range(len(nums) - 1):\n changed = nums[i] - 2 * K\n max_num = max(nums[i + 1], changed, changed_max)\n min_num = min(min_num, changed)\n res = min(res, max_num - min_num)\n return res", "def smallestrangeii(A: List[int], K: int) -> int:\n A.sort()\n minA = A[0]\n maxA = A[-1]\n smallest = maxA - minA\n for i in range(len(A) - 1):\n a = A[i]\n b = A[i + 1]\n smallest = min(smallest, max(maxA - K, a + K) - min(minA + K, b - K))\n return smallest", "def smallestrangeii(A: List[int], K: int) -> int:\n A.sort()\n (mi, ma) = (A[0], A[-1])\n ans = ma - mi\n for i in range(len(A) - 1):\n (a, b) = (A[i], A[i + 1])\n ans = min(ans, max(ma - K, a + K) - min(mi + K, b - K))\n return ans", "def smallestrangeii(A: List[int], K: int) -> int:\n A.sort()\n diff = A[-1] - A[0]\n for i in range(len(A) - 1):\n lower = min(A[0] + 2 * K, A[i + 1])\n upper = max(A[-1], A[i] + 2 * K)\n diff = min(diff, abs(upper - lower))\n return diff", "def smallestrangeii(A: List[int], K: int) -> int:\n if K == 0:\n return max(A) - min(A)\n if len(A) == 1:\n return 0\n if max(A) - min(A) <= K:\n return max(A) - min(A)\n else:\n A = sorted(A)\n dp = [A[-1] - A[0]]\n (n1, n2) = (A[-1] - K, A[0] + K)\n for i in range(len(A) - 1):\n dp += [max(A[i] + K, A[-1] - K) - min(A[0] + K, A[i + 1] - K)]\n return min(dp)", "def smallestrangeii(A: List[int], K: int) -> int:\n if len(A) == 1:\n return 0\n A.sort()\n i = 0\n j = len(A) - 1\n min_diff = A[-1] - A[0]\n bottom = A[0]\n peak = A[-1]\n for idx in range(len(A) - 1):\n (current, _next) = (A[idx], A[idx + 1])\n bottom = min(A[0] + K, _next - K)\n peak = max(A[-1] - K, current + K)\n min_diff = min(min_diff, peak - bottom)\n return min_diff", "def smallestrangeii(A: List[int], K: int) -> int:\n A.sort()\n res = A[-1] - A[0]\n for i in range(len(A) - 1):\n res = min(res, max(A[i] + K, A[-1] - K) - min(A[0] + K, A[i + 1] - K))\n return res", "def smallestrangeii(A: List[int], K: int) -> int:\n if not A:\n return 0\n A.sort()\n x = A[0]\n y = A[-1]\n res = y - x\n for i in range(len(A)):\n A[i] += 2 * K\n x = min(A[0], A[(i + 1) % len(A)])\n y = max(A[i], y)\n res = min(res, y - x)\n return res", "def smallestrangeii(A: List[int], k: int) -> int:\n A.sort()\n n = len(A)\n res = A[n - 1] - A[0]\n for i in range(n - 1):\n mn = min(A[i + 1] - k, A[0] + k)\n mx = max(A[i] + k, A[n - 1] - k)\n res = min(res, mx - mn)\n return res", "def smallestrangeii(A: List[int], K: int) -> int:\n A.sort()\n min_diff = A[-1] - A[0]\n for i in range(len(A) - 1):\n v_min = min(A[0] + K, A[i + 1] - K)\n v_max = max(A[i] + K, A[-1] - K)\n min_diff = min(min_diff, v_max - v_min)\n return min_diff", "def smallestrangeii(arr: List[int], k: int) -> int:\n arr.sort()\n best = arr[-1] - arr[0]\n for i in range(1, len(arr)):\n current_max = max(arr[-1] - k, arr[i - 1] + k)\n current_min = min(arr[0] + k, arr[i] - k)\n best = min(best, current_max - current_min)\n return best", "def smallestrangeii(A: List[int], k: int) -> int:\n A.sort()\n (res, n) = (A[-1] - A[0], len(A))\n temp = [max(A[n - 1] - k, A[n - i - 2] + k) - min(A[0] + k, A[n - i - 1] - k) for i in range(n)]\n return min(res, min(temp))", "def smallestrangeii(A: List[int], K: int) -> int:\n N = len(A)\n if N == 1:\n return 0\n A.sort()\n diff = A[-1] - A[0]\n for i in range(N - 1):\n maxi = max(A[i] + K, A[N - 1] - K)\n mini = min(A[0] + K, A[i + 1] - K)\n diff = min(diff, maxi - mini)\n return diff"], "starter_code": "def smallestrangeii(A: List[int], K: int) -> int:\n", "input_output": {"fn_name": "smallestRangeII", "inputs": [[[1], 0]], "outputs": [0]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Math", "Sorting", "Greedy", "Array"], "name": null, "source": "leetcode", "tags": ["Sorting", "Data structures", "Mathematics", "Greedy algorithms"], "skill_types": ["Sorting", "Data structures", "Greedy algorithms"], "url": "https://leetcode.com/problems/smallest-range-ii/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "smallestrangeii", "task_id": "TACO_lite/100", "example": [[[[1], 0], [[0, 10], 2], [[1, 3, 6], 3]], ["0", "6", "3"]]} +{"requirement": "Given N, count all ‘a’(>=1) and ‘b’(>=0) that satisfy the condition a^{3} + b^{3 }= N.\n \nExample 1:\nInput:\nN = 9 \nOutput:\n2\nExplanation:\nThere are two solutions: (a=1, b=2)\nand (a=2, b=1).\nExample 2:\nInput:\nN = 27\nOutput:\n1\nExplanation:\nThereis only one solution: (a=3, b=0)\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function pairCubeCount() which takes an Integer N as input and returns the answer.\n \nExpected Time Complexity: O(cbrt(N))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= N <= 10^{5}", "solutions": ["def paircubecount(N):\n count = 0\n max_a = int(pow(N, 1 / 3)) + 1\n for a in range(1, max_a):\n b_cube = N - pow(a, 3)\n if b_cube < 0:\n break\n b = int(round(pow(b_cube, 1 / 3)))\n if pow(b, 3) == b_cube:\n count += 1\n if pow(a, 3) == N and b_cube == 0:\n count += 1\n if N == 1:\n count = 1\n return count", "def paircubecount(N):\n s = set()\n if N == 1:\n return 1\n count = 0\n for i in range(0, int(N ** (1 / 3)) + 1):\n r = N - i ** 3\n if round(r ** (1 / 3)) ** 3 == r:\n s.add(r)\n s.add(i ** 3)\n return len(s)", "import math\n\ndef paircubecount(N):\n c = 0\n a = N ** (1 / 3)\n if a > int(a):\n for i in range(1, int(a) + 1):\n for j in range(1, int(a) + 1):\n if math.pow(i, 3) + math.pow(j, 3) == N:\n c += 1\n elif a == int(a):\n c += 1\n return c", "def paircubecount(N):\n count = 0\n for a in range(1, int(N ** (1 / 3)) + 1):\n b = N - a ** 3\n if round(b ** (1 / 3)) ** 3 == b:\n count += 1\n return count", "def paircubecount(N):\n (ct, a) = (0, 1)\n while a ** 3 <= N:\n b = 0\n while b ** 3 <= N:\n if a ** 3 + b ** 3 == N:\n ct += 1\n b += 1\n a += 1\n return ct", "import math\n\ndef paircubecount(N):\n count = 0\n M = round(math.pow(N, 1 / 3))\n for i in range(1, M + 1):\n for j in range(M + 1):\n if i ** 3 + j ** 3 == N:\n count += 1\n return count", "import math\n\ndef paircubecount(N):\n count = 0\n a = math.floor(math.pow(N, 1 / 3))\n for i in range(0, a + 1):\n for j in range(1, a + 1):\n if i ** 3 + j ** 3 == N:\n count += 1\n return count", "def paircubecount(N):\n p = int(N ** (1 / 3)) + 1\n count = 0\n for i in range(1, p):\n for j in range(0, p):\n if i ** 3 + j ** 3 == N:\n count += 1\n return count", "def paircubecount(N):\n solutions = 0\n crN = int(N ** (1 / 3)) + 1\n for a in range(1, crN + 1):\n for b in range(0, a + 1):\n if a ** 3 + b ** 3 == N:\n if a == b or b == 0:\n solutions = solutions + 1\n else:\n solutions = solutions + 2\n return solutions", "def paircubecount(N):\n cube = int(N ** (1 / 3)) + 1\n c = 0\n for x in range(1, cube + 1):\n for y in range(cube + 1):\n if x ** 3 + y ** 3 == N:\n c += 1\n return c", "def paircubecount(N):\n (a, b) = (int(N ** (1 / 3)), int(N ** (1 / 3)))\n c = 0\n for i in range(1, a + 1):\n for j in range(b + 1):\n if i ** 3 + j ** 3 == N:\n c += 1\n elif i ** 3 + j ** 3 > N:\n break\n return c", "import math\n\ndef paircubecount(t):\n value = int(t ** (1 / 3))\n count = 0\n for i in range(1, value + 1):\n for j in range(0, value + 1):\n if i ** 3 + j ** 3 == t:\n count += 1\n return count", "def paircubecount(N):\n import math\n count = 0\n l = math.ceil(math.pow(N, 1 / 3))\n for i in range(1, l + 1):\n for j in range(0, l + 1):\n a = i * i * i\n b = j * j * j\n if a + b == N:\n count = count + 1\n return count", "def paircubecount(N):\n if N == 1:\n return 1\n count = 0\n floor_cbrt_N = 0\n while floor_cbrt_N ** 3 <= N:\n floor_cbrt_N += 1\n floor_cbrt_N -= 1\n for a in range(1, floor_cbrt_N + 1):\n b = N - a ** 3\n if b < 0:\n break\n cbrt_b = 0\n while cbrt_b ** 3 <= b:\n cbrt_b += 1\n if (cbrt_b - 1) ** 3 == b:\n count += 1\n return count", "from itertools import product\nimport math\n\ndef paircubecount(N):\n count = 0\n nums = [i for i in range(0, int(N ** (1 / 3)) + 1)]\n combs = [i for i in product(nums, repeat=2)]\n for i in combs:\n if i[0] ** 3 + i[1] ** 3 == N and i[0] >= 1 and (i[1] >= 0):\n count += 1\n return count", "def paircubecount(N):\n aset = set()\n i = 1\n while i <= N ** (1 / 3):\n aset.add(i * i * i)\n i += 1\n count = 0\n for ele in aset:\n if N - ele == 0 or N - ele in aset:\n count += 1\n return count", "import math\n\ndef paircubecount(N):\n res = int(N ** (1 / 3) + 1)\n count = 0\n for i in range(0, res):\n for j in range(1, res):\n if N == i ** 3 + j ** 3:\n count += 1\n return count", "def paircubecount(N):\n if N == 1:\n return 1\n a = {}\n b = []\n count = 0\n for i in range(N):\n if i not in a:\n a[i ** 3] = 1\n b.append(i)\n for i in b:\n if N - i ** 3 in a:\n count += 1\n return count", "def paircubecount(N):\n import math\n c = 0\n d = math.ceil(math.pow(N, 1 / 3))\n for i in range(1, d + 1):\n for j in range(d + 1):\n p = pow(i, 3) + pow(j, 3)\n if p == N:\n c += 1\n if c != 0:\n return c\n else:\n return 0", "import math\n\ndef paircubecount(N):\n count = 0\n for i in range(1, int(N ** (1 / 3)) + 1):\n bcube_root = (N - i ** 3) ** (1 / 3)\n if math.ceil(bcube_root) ** 3 == N - i ** 3:\n count += 1\n return count", "def paircubecount(N):\n c = 0\n if N == 1:\n return 1\n for i in range(1, int(pow(N, 1 / 3) + 1)):\n for j in range(0, int(pow(N, 1 / 3) + 1)):\n if i * i * i + j * j * j == N:\n c = c + 1\n return c", "import math\n\ndef paircubecount(N):\n sq = int(math.sqrt(N))\n count = 0\n if N <= 8:\n return 1\n for x in range(0, sq):\n for y in range(1, sq):\n if pow(x, 3) + pow(y, 3) == N:\n count = count + 1\n return count", "import math\n\ndef paircubecount(n):\n sq = int(math.sqrt(n))\n flag = 0\n if n <= 8:\n return 1\n for x in range(0, sq):\n for y in range(1, sq):\n if pow(x, 3) + pow(y, 3) == n:\n flag = flag + 1\n return flag", "def paircubecount(N):\n if N == 1:\n return 1\n count = 0\n for i in range(1, N):\n for j in range(N):\n if i * i * i + j * j * j == N:\n count += 1\n elif i * i * i + j * j * j > N:\n break\n return count", "import math\n\ndef paircubecount(N):\n count = 0\n i = 1\n while i * i * i <= N:\n j = 0\n while j * j * j <= N:\n if i * i * i + j * j * j == N:\n count += 1\n j += 1\n i += 1\n return count", "def paircubecount(N):\n count = 0\n x = int(pow(N, 1 / 3))\n for i in range(1, x + 1):\n b = N - i * i * i\n if b == round(b ** (1 / 3)) ** 3:\n count += 1\n return count", "def paircubecount(N):\n x = int(N ** (1 / 3)) + 1\n ans = 0\n root = int(N ** (1 / 3))\n if root ** 3 == N:\n ans += 1\n for i in range(1, x):\n for j in range(1, x):\n if i ** 3 + j ** 3 == N:\n ans += 1\n return ans", "import math\n\ndef paircubecount(N):\n c = 0\n l = math.ceil(math.pow(N, 1 / 3))\n for i in range(1, l + 1):\n for j in range(0, l + 1):\n if i ** 3 + j ** 3 == N:\n c += 1\n return c", "import numpy as np\n\ndef paircubecount(N):\n count = 0\n for a in range(1, int(np.cbrt(N)) + 1):\n for b in range(0, int(np.cbrt(N) + 1)):\n if a ** 3 + b ** 3 == N:\n count += 1\n return count", "import math\n\ndef paircubecount(N):\n count = 0\n for b in range(int(N ** (1 / 3) + 1)):\n a = round((N - b ** 3) ** (1 / 3), 4)\n if a % 1 == 0 and a >= 1:\n count += 1\n return count", "def paircubecount(N):\n k = 0\n for a in range(1, int(pow(N, 1 / 3)) + 1):\n for b in range(0, int(pow(N, 1 / 3)) + 1):\n if pow(a, 3) + pow(b, 3) == N:\n k += 1\n return k", "def paircubecount(N):\n j = 0\n for i in range(1, int(pow(N, 1 / 3)) + 1):\n k = pow(N - pow(i, 3), 1 / 3)\n if (N - k) % 1 < pow(10, -7):\n j += 1\n return j", "def paircubecount(N):\n count = 0\n res1 = 0\n res2 = 0\n flag = 0\n cond = N\n if N == 0:\n return 0\n for i in range(1, N + 1):\n res1 = i * i * i\n if res1 <= N:\n for j in range(0, N):\n res2 = j * j * j\n if res2 < N:\n if res1 + res2 == N:\n count += 1\n else:\n flag = 1\n break\n else:\n break\n return count", "import math\n\ndef paircubecount(N):\n c = 0\n for i in range(1, int(math.sqrt(N) + 1)):\n for j in range(int(math.sqrt(N)) + 1):\n if i ** 3 + j ** 3 == N:\n c += 1\n return c", "import math\n\ndef paircubecount(N):\n count = 0\n for i in range(1, int(math.pow(N, 1 / 3) + 1)):\n cube = i * i * i\n diff = N - cube\n s_cube = round(math.pow(diff, 1 / 3))\n if s_cube * s_cube * s_cube == diff:\n count += 1\n return count", "def paircubecount(N):\n cubes_root = set()\n cubes_val = set()\n i = 0\n while i ** 3 <= N:\n cubes_root.add(i)\n cubes_val.add(i ** 3)\n i += 1\n return sum((N - i ** 3 in cubes_val and N - i ** 3 != 0 for i in cubes_root))", "import math\n\ndef paircubecount(N):\n if N == 1:\n return N\n count = 0\n cubRoot = round(N ** 1 / 3)\n for i in range(0, cubRoot + 1):\n aCube = i ** 3\n if aCube == N:\n count += 1\n else:\n if N - aCube == 1:\n ans = 1\n else:\n ans = round(math.pow(abs(N - aCube), 1 / 3))\n if ans ** 3 + aCube == N:\n count += 1\n return count", "import math\n\ndef paircubecount(N):\n count = 0\n i = 1\n while i * i * i <= N:\n cb = i * i * i\n if cb == N:\n count = count + 1\n else:\n val = N - cb\n out = math.ceil(val ** (1 / 3))\n if out ** 3 == val:\n count = count + 1\n i = i + 1\n return count", "import math\n\ndef paircubecount(N):\n k = math.floor(N ** (1 / 3))\n a = 1\n b = 0\n c = 0\n for i in range(1, k + 1):\n for j in range(k + 1):\n if i ** 3 + j ** 3 == N:\n c += 1\n return c", "def paircubecount(N):\n count = 0\n n = round(pow(N, 1 / 3)) + 1\n for i in range(1, n):\n for j in range(0, n):\n if pow(i, 3) + pow(j, 3) == N:\n count += 1\n if N == 1:\n return 1\n else:\n return count", "def paircubecount(N):\n m = int(N ** (1 / 3))\n M = m\n n = 0\n count = 0\n while m >= 0:\n for n in range(1, M + 1):\n if n ** 3 + m ** 3 == N:\n count = count + 1\n m = m - 1\n return count", "def paircubecount(N):\n (i, j, c) = (0, 0, 0)\n while i ** 3 <= N:\n j = 0\n while j ** 3 <= N:\n if j ** 3 + i ** 3 == N and j ** 3 != N:\n c = c + 1\n j = j + 1\n i = i + 1\n return c", "import math\n\ndef paircubecount(N):\n root_value = 3\n upper_limit = int(N ** (1 / root_value))\n count_sols = 0\n for i in range(1, upper_limit + 1):\n first_cube = i * i * i\n diff = N - first_cube\n cbrtdiff = math.ceil(diff ** (1 / 3))\n if cbrtdiff ** 3 == diff:\n count_sols += 1\n return count_sols", "def paircubecount(N):\n root_value = 3\n upper_limit = int(N ** (1 / root_value))\n count_sols = 0\n for i in range(0, upper_limit + 1):\n for j in range(1, upper_limit + 1):\n if j ** root_value + i ** root_value == N:\n count_sols += 1\n return count_sols", "import math\n\ndef paircubecount(N):\n count = 0\n for i in range(1, int(N ** (1 / 3)) + 1):\n cb = i * i * i\n diff = N - cb\n cbrtdiff = int(round(diff ** (1 / 3)))\n diffcb = cbrtdiff * cbrtdiff * cbrtdiff\n if diffcb == diff:\n count += 1\n return count"], "starter_code": "def paircubecount(N):\n", "input_output": {"inputs": ["N = 9", "N = 27"], "outputs": ["2", "1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/pair-cube-count4132/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(cbrt(N))", "entry_point": "paircubecount", "task_id": "TACO_lite/131", "example": [[[9], [27]], ["2", "1"]]} +{"requirement": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different.\n\nGiven two integers x and y, calculate the Hamming distance.\n\nNote:\n0 ≤ x, y < 231.\n\n\nExample:\n\nInput: x = 1, y = 4\n\nOutput: 2\n\nExplanation:\n1 (0 0 0 1)\n4 (0 1 0 0)\n ↑ ↑\n\nThe above arrows point to positions where the corresponding bits are different.", "solutions": ["def hammingdistance(x, y):\n x = x ^ y\n y = 0\n while x:\n y += 1\n x &= x - 1\n return y", "def hammingdistance(x, y):\n if x == y:\n return 0\n (bin_x, bin_y) = (bin(x)[2:], bin(y)[2:])\n if x < y:\n bin_x = bin_x.zfill(len(bin_y))\n else:\n bin_y = bin_y.zfill(len(bin_x))\n return sum([abs(int(bin_x[i]) - int(bin_y[i])) for i in range(len(bin_x))])", "def hammingdistance(x, y):\n count = 0\n for i in range(32):\n count += x & 1 ^ y & 1\n x >>= 1\n y >>= 1\n return count", "def hammingdistance(x, y):\n d = bin(x ^ y)\n return d.count('1')", "def hammingdistance(x, y):\n x_b = '{:32b}'.format(x).replace(' ', '0')\n y_b = '{:32b}'.format(y).replace(' ', '0')\n count = 0\n for i in range(len(x_b)):\n if x_b[i] != y_b[i]:\n count += 1\n return count", "def hammingdistance(x, y):\n xor = x ^ y\n count = 0\n for _ in range(32):\n count += xor & 1\n xor = xor >> 1\n return count", "def hammingdistance(x, y):\n count = 0\n while x > 0 or y > 0:\n if x & 1 != y & 1:\n count += 1\n if x > 0:\n x = x >> 1\n if y > 0:\n y = y >> 1\n return count", "def hammingdistance(x, y):\n x_bits = [int(i) for i in bin(x)[2:]]\n y_bits = [int(j) for j in bin(y)[2:]]\n digit_diff = abs(len(x_bits) - len(y_bits))\n if len(y_bits) > len(x_bits):\n x_bits = [0] * digit_diff + x_bits\n elif len(x_bits) > len(y_bits):\n y_bits = [0] * digit_diff + y_bits\n hamming_dist = 0\n for i in range(0, len(x_bits)):\n if x_bits[i] != y_bits[i]:\n hamming_dist += 1\n return hamming_dist", "def hammingdistance(x, y):\n xor_result = x ^ y\n count = 0\n while xor_result > 0:\n count += xor_result & 1\n xor_result = xor_result >> 1\n return count", "def hammingdistance(x, y):\n hamming_distance = 0\n while x != 0 or y != 0:\n b1 = x & 1\n b2 = y & 1\n if b1 != b2:\n hamming_distance = hamming_distance + 1\n x = x >> 1\n y = y >> 1\n return hamming_distance"], "starter_code": "def hammingdistance(x: int, y: int) -> int:\n", "input_output": {"fn_name": "hammingDistance", "inputs": [[1, 4]], "outputs": [2]}, "difficulty": "EASY", "raw_tags": ["Bit Manipulation"], "name": null, "source": "leetcode", "tags": ["Bit manipulation"], "skill_types": ["Bit manipulation"], "url": "https://leetcode.com/problems/hamming-distance/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "hammingdistance", "task_id": "TACO_lite/115", "example": [[[1, 4]], ["2"]]} +{"requirement": "Say you have an array for which the ith element is the price of a given stock on day i.\n\nDesign an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:\n\n\n You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).\n After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)\n\n\nExample:\n\n\nInput: [1,2,3,0,2]\nOutput: 3 \nExplanation: transactions = [buy, sell, cooldown, buy, sell]", "solutions": ["def maxprofit(prices):\n n = len(prices)\n if n < 2:\n return 0\n sells = [0] * n\n buys = [0] * n\n buys[0] = -prices[0]\n for i in range(1, n):\n sells[i] = max(sells[i - 1], buys[i - 1] + prices[i])\n buys[i] = max(buys[i - 1], (sells[i - 2] if i > 1 else 0) - prices[i])\n return sells[n - 1]", "def maxprofit(prices):\n if not prices:\n return 0\n sell = hold = 0\n buy = -prices[0]\n for i in range(1, len(prices)):\n (sell, hold, buy) = (max(buy + prices[i], 0), max(hold, sell), max(hold - prices[i], buy))\n return max(sell, hold)", "def maxprofit(prices):\n if prices is None or len(prices) == 0:\n return 0\n dp = [[-9999999] * len(prices) for _ in range(3)]\n (dp[0][0], dp[1][0], dp[2][0]) = (-prices[0], 0, 0)\n for i in range(1, len(prices)):\n dp[0][i] = max(dp[0][i - 1], dp[2][i - 1] - prices[i])\n dp[1][i] = max(dp[0][i - 1] + prices[i], dp[1][i - 1])\n dp[2][i] = max(dp[2][i - 1], dp[0][i - 1], dp[1][i - 1])\n return max(dp[1][-1], dp[2][-1])", "def maxprofit(prices):\n n = len(prices)\n if not n:\n return 0\n buys = [None] * n\n sells = [None] * n\n (sells[0], buys[0]) = (0, -prices[0])\n for x in range(1, n):\n delta = prices[x] - prices[x - 1]\n sells[x] = max(buys[x - 1] + prices[x], sells[x - 1] + delta)\n buys[x] = max(buys[x - 1] - delta, sells[x - 2] - prices[x] if x > 1 else -9999)\n return max(sells)", "def maxprofit(prices):\n n = len(prices)\n if n < 2:\n return 0\n (buy, sell) = ([0] * n, [0] * n)\n (buy[0], buy[1]) = (-prices[0], -min(prices[0:2]))\n sell[1] = max(0, buy[0] + prices[1])\n for i in range(2, n):\n sell[i] = max(sell[i - 1], buy[i - 1] + prices[i])\n buy[i] = max(buy[i - 1], sell[i - 2] - prices[i])\n return sell[-1]", "def maxprofit(prices):\n if not prices or len(prices) == 1:\n return 0\n valid_status = [0, [prices[0], -prices[0]], 0]\n for t in range(1, len(prices)):\n valid_status[1][0] = prices[t]\n cool_down_temp = sum(valid_status[1])\n if valid_status[0] > sum(valid_status[1]):\n valid_status[1] = [prices[t], valid_status[0] - prices[t]]\n if valid_status[2] > valid_status[0]:\n valid_status[0] = valid_status[2]\n valid_status[2] = cool_down_temp\n return max(valid_status[0], valid_status[2])", "def maxprofit(prices):\n if not prices:\n return 0\n max_buy = [0] * len(prices)\n max_sell = [0] * len(prices)\n max_rest = [0] * len(prices)\n max_buy[0] = -prices[0]\n max_sell[0] = 0\n max_rest[0] = 0\n for i in range(1, len(prices)):\n max_buy[i] = max(max_rest[i - 1] - prices[i], max_buy[i - 1])\n max_sell[i] = max(max_buy[i - 1] + prices[i], max_sell[i - 1])\n max_rest[i] = max(max_sell[i - 1], max_rest[i - 1])\n return max(max_buy[-1], max_sell[-1], max_rest[-1])", "def maxprofit(prices):\n free = 0\n have = cool = float('-inf')\n for p in prices:\n (free, have, cool) = (max(free, cool), max(have, free - p), have + p)\n return max(free, cool)", "def maxprofit(prices):\n if not prices:\n return 0\n prices.insert(0, 0)\n prices.insert(0, 0)\n buy = [0] * len(prices)\n sell = [0] * len(prices)\n buy[2] = -prices[2]\n for i in range(3, len(prices)):\n buy[i] = max(sell[i - 2] - prices[i], buy[i - 1])\n sell[i] = max(buy[i - 1] + prices[i], sell[i - 1])\n return sell[-1]", "def maxprofit(prices):\n return self.max_profit_rec(prices, {}, 0, 0)\n\ndef max_profit_rec(prices, memo, idx, state):\n if idx >= len(prices):\n return 0\n if (idx, state) in memo:\n return memo[idx, state]\n memo[idx, state] = 0\n if state == 0:\n memo[idx, state] = max(self.max_profit_rec(prices, memo, idx + 1, 1) - prices[idx], self.max_profit_rec(prices, memo, idx + 1, 0))\n elif state == 1:\n memo[idx, state] = max(self.max_profit_rec(prices, memo, idx + 1, 2) + prices[idx], self.max_profit_rec(prices, memo, idx + 1, 1))\n else:\n memo[idx, state] = self.max_profit_rec(prices, memo, idx + 1, 0)\n return memo[idx, state]", "def maxprofit(prices):\n if len(prices) < 2:\n return 0\n (prevSell, sell, prevBuy, buy) = (0, 0, 0, -prices[0])\n for price in prices:\n prevBuy = buy\n buy = max(prevBuy, prevSell - price)\n prevSell = sell\n sell = max(prevSell, prevBuy + price)\n return sell"], "starter_code": "def maxprofit(prices: List[int]) -> int:\n", "input_output": {"fn_name": "maxProfit", "inputs": [[[1, 2, 3, 0, 2]]], "outputs": [3]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "maxprofit", "task_id": "TACO_lite/125", "example": [[[[1, 2, 3, 0, 2]]], ["3"]]} +{"requirement": "The number ```89``` is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata. \nWhat's the use of saying \"Eureka\"? Because this sum gives the same number.\n\nIn effect: ```89 = 8^1 + 9^2``` \n\nThe next number in having this property is ```135```.\n\nSee this property again: ```135 = 1^1 + 3^2 + 5^3```\n\nWe need a function to collect these numbers, that may receive two integers ```a```, ```b``` that defines the range ```[a, b]``` (inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.\n\nLet's see some cases:\n```python\nsum_dig_pow(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nsum_dig_pow(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]\n```\nIf there are no numbers of this kind in the range [a, b] the function should output an empty list.\n```python\nsum_dig_pow(90, 100) == []\n```\nEnjoy it!!", "solutions": ["def dig_pow(n):\n return sum((int(x) ** y for (y, x) in enumerate(str(n), 1)))\n\ndef sum_dig_pow(a, b):\n return [x for x in range(a, b + 1) if x == dig_pow(x)]", "def sum_dig_pow(a, b):\n return [x for x in range(a, b + 1) if sum((int(d) ** i for (i, d) in enumerate(str(x), 1))) == x]", "def sum_dig_pow(a, b):\n res = []\n for number in range(a, b + 1):\n digits = [int(i) for i in str(number)]\n s = 0\n for (idx, val) in enumerate(digits):\n s += val ** (idx + 1)\n if s == number:\n res.append(number)\n return res", "def sum_dig_pow(a, b):\n l = []\n for i in range(a, b + 1):\n k = 0\n p = str(i)\n for j in range(len(p)):\n k += int(p[j]) ** (j + 1)\n if k == i:\n l.append(i)\n return l", "def sum_dig_pow(a, b):\n ans = []\n while a <= b:\n if sum((int(j) ** k for (j, k) in zip(str(a), range(1, len(str(a)) + 1)))) == a:\n ans += [a]\n a += 1\n return ans", "def sum_dig_pow(a, b):\n lis = []\n for i in range(a, b + 1):\n temp = str(i)\n su = 0\n for l in range(0, len(temp)):\n su += int(temp[l:l + 1]) ** (l + 1)\n if su == i:\n lis.append(i)\n return lis"], "starter_code": "def sum_dig_pow(a, b):\n", "input_output": {"fn_name": "sum_dig_pow", "inputs": [[1, 100], [10, 89], [10, 100], [90, 100], [90, 150], [50, 150], [10, 150], [89, 135]], "outputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 89]], [[89]], [[89]], [[]], [[135]], [[89, 135]], [[89, 135]], [[89, 135]]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5626b561280a42ecc50000d1", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sum_dig_pow", "task_id": "TACO_lite/39", "example": [[[1, 10], [1, 100], [90, 100]], ["[1, 2, 3, 4, 5, 6, 7, 8, 9]", "[1, 2, 3, 4, 5, 6, 7, 8, 9, 89]", "[]"]]} +{"requirement": "How many bees are in the beehive?\n\n* bees can be facing UP, DOWN, LEFT, or RIGHT \n* bees can share parts of other bees\n\nExamples\n\nEx1\n```\nbee.bee \n.e..e..\n.b..eeb\n```\n*Answer: 5*\n\n\nEx2\n```\nbee.bee \ne.e.e.e\neeb.eeb\n```\n*Answer: 8*\n\n# Notes\n\n* The hive may be empty or null/None/nil/...\n* Python: the hive is passed as a list of lists (not a list of strings)", "solutions": ["from itertools import chain\n\ndef how_many_bees(hive):\n return bool(hive) and sum((s.count('bee') + s.count('eeb') for s in map(''.join, chain(hive, zip(*hive)))))", "def count(it):\n return sum((''.join(x).count('bee') + ''.join(x).count('eeb') for x in it))\n\ndef how_many_bees(hive):\n return count(hive) + count(zip(*hive)) if hive else 0", "def how_many_bees(hive):\n if hive == None or len(hive) == 0:\n return 0\n result = 0\n for i in range(len(hive[0])):\n test = ''\n for item in hive:\n test += item[i]\n result += test.count('bee')\n result += test.count('eeb')\n for i in range(len(hive)):\n test = ''\n for item in hive[i]:\n test += item\n result += test.count('bee')\n result += test.count('eeb')\n return result", "import re\n\ndef how_many_bees(hive):\n if hive is None:\n return 0\n s = ' '.join((''.join(line) for hiveArr in (hive, zip(*hive)) for line in hiveArr))\n return len(re.findall('b(?=ee)|ee(?=b)', s))", "def how_many_bees(hive):\n if not hive:\n return 0\n row_bees = lambda row: sum((1 for i in range(len(row)) if ''.join(row[i:i + 3]) == 'bee'))\n matrix_bees = lambda matrix: sum((row_bees(row) for row in matrix))\n v_flip = lambda matrix: [row[::-1] for row in matrix]\n transpose = lambda matrix: [list(z) for z in zip(*matrix)]\n return matrix_bees(hive) + matrix_bees(transpose(hive)) + matrix_bees(v_flip(hive)) + matrix_bees(v_flip(transpose(hive)))", "def how_many_bees(hive):\n if hive is None:\n return 0\n columns = [''.join(col) for col in zip(*hive)]\n hive = [''.join(line) for line in hive]\n return sum((row.count(bee) for bee in ('bee', 'eeb') for rows in (hive, columns) for row in rows))", "def how_many_bees(hive):\n counter = 0\n try:\n for row in hive:\n for i in range(len(row) - 2):\n if row[i] == 'b' and row[i + 1] == 'e' and (row[i + 2] == 'e'):\n counter += 1\n elif row[i] == 'e' and row[i + 1] == 'e' and (row[i + 2] == 'b'):\n counter += 1\n for column in range(len(hive[0])):\n for position in range(len(hive) - 2):\n if hive[position][column] == 'b' and hive[position + 1][column] == 'e' and (hive[position + 2][column] == 'e'):\n counter += 1\n if hive[position][column] == 'e' and hive[position + 1][column] == 'e' and (hive[position + 2][column] == 'b'):\n counter += 1\n except:\n counter = 0\n return counter", "import re\n\ndef how_many_bees(b):\n if b is None:\n return 0\n new_temp = [[j for j in i] for i in b]\n c = [len(re.findall('bee', ''.join(i + [' '] + i[::-1]))) for i in new_temp] + [len(re.findall('bee', ''.join(i + tuple(' ') + i[::-1]))) for i in zip(*new_temp)]\n return sum(c)", "directions = [(1, 0), (-1, 0), (0, -1), (0, 1)]\n\ndef how_many_bees(hive):\n (r, c) = (len(hive), len(hive[0])) if hive else (0, 0)\n\n def f(s, i, j, di, dj):\n if not (0 <= i < r and 0 <= j < c and s.startswith(hive[i][j])):\n return 0\n s = s[1:]\n return f(s, i + di, j + dj, di, dj) if s else 1\n return sum((f('bee', i, j, di, dj) for i in range(r) for j in range(c) for (di, dj) in directions))", "def how_many_bees(hive):\n if hive == [] or hive == '' or hive == None:\n return 0\n result = 0\n for i in range(len(hive)):\n for k in range(len(hive[i])):\n if i > 1 and hive[i][k] == 'b':\n if hive[i - 1][k] == 'e' and hive[i - 2][k] == 'e':\n result += 1\n if i < len(hive) - 2 and hive[i][k] == 'b':\n if hive[i + 1][k] == 'e' and hive[i + 2][k] == 'e':\n result += 1\n if k < len(hive[i]) - 2 and hive[i][k] == 'b':\n if hive[i][k + 1] == 'e' and hive[i][k + 2] == 'e':\n result += 1\n if k > 1 and hive[i][k] == 'b':\n if hive[i][k - 1] == 'e' and hive[i][k - 2] == 'e':\n result += 1\n return result", "how_many_bees = lambda h: h and sum(map('|'.join(map(''.join, h + list(zip(*h)))).count, ('bee', 'eeb'))) or 0", "import re\nhow_many_bees = lambda b: 0 if not b else sum([len(re.findall('bee', ''.join(i + [' '] + i[::-1]))) for i in b] + [len(re.findall('bee', ''.join(i + tuple(' ') + i[::-1]))) for i in zip(*b)])", "def how_many_bees(hive):\n bees = ('bee', 'eeb')\n num_of_bees = 0\n if hive == None:\n return 0\n for line in hive:\n for pos in range(len(line) - 2):\n possible_bee = line[pos] + line[pos + 1] + line[pos + 2]\n if possible_bee in bees:\n num_of_bees += 1\n for line_idx in range(len(hive) - 2):\n for pos_idx in range(len(hive[line_idx])):\n possible_bee = hive[line_idx][pos_idx] + hive[line_idx + 1][pos_idx] + hive[line_idx + 2][pos_idx]\n if possible_bee in bees:\n num_of_bees += 1\n return num_of_bees", "def how_many_bees(hive):\n if hive is None or len(hive) == 0:\n return 0\n cnt = 0\n for row in hive:\n cnt += ''.join(row).count('bee')\n cnt += ''.join(row).count('eeb')\n (m, n) = (len(hive), len(hive[0]))\n cols = [''.join([hive[j][i] for j in range(m)]) for i in range(n)]\n cnt += sum([i.count('bee') for i in cols])\n cnt += sum([i.count('eeb') for i in cols])\n return cnt", "def rotate(matrix):\n return list(zip(*matrix[::-1]))\n\ndef how_many_bees(hive):\n if hive:\n s1 = ' '.join([''.join(r) for r in hive])\n s2 = ' '.join([''.join(el) for el in rotate(hive)])\n s = s1 + ' ' + s2\n return s.count('bee') + s.count('eeb')\n return 0", "def how_many_bees(hive):\n if not hive:\n return 0\n count = 0\n for i in range(len(hive)):\n for j in range(len(hive[i]) - 2):\n compare = ''.join(hive[i][j:j + 3])\n if compare == 'bee' or compare == 'eeb':\n count += 1\n for i in range(len(hive) - 2):\n for j in range(len(hive[i])):\n compare = hive[i][j] + hive[i + 1][j] + hive[i + 2][j]\n if compare == 'bee' or compare == 'eeb':\n count += 1\n return count", "how_many_bees = lambda h: (lambda m, tm: sum((sum((q.count(a) for q in b)) for a in ['bee', 'eeb'] for b in [m, tm])))([''.join(x) for x in h] if h else [], [''.join([h[p][q] for p in range(len(h))]) for q in range(0 if len(h) == 0 else len(h[0]))] if h else [])", "def how_many_bees(hive):\n try:\n right = sum((line.count('bee') for line in map(''.join, hive)))\n left = sum((line.count('eeb') for line in map(''.join, hive)))\n down = sum((line.count('bee') for line in map(''.join, zip(*hive))))\n up = sum((line.count('eeb') for line in map(''.join, zip(*hive))))\n return up + down + left + right\n except TypeError:\n return 0", "def how_many_bees(hive):\n return sum((word.count('eeb') + word.count('bee') for word in list(map(lambda x: ''.join(list(x)), zip(*hive))) + list(map(lambda x: ''.join(x), hive)))) if hive else 0"], "starter_code": "def how_many_bees(hive):\n", "input_output": {"fn_name": "how_many_bees", "inputs": [[null]], "outputs": [[0]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/57d6b40fbfcdc5e9280002ee", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "how_many_bees", "task_id": "TACO_lite/67", "example": [[[[["b", "e", "e", ".", "b", "e", "e"], [".", "e", ".", ".", "e", ".", "."], ["b", ".", ".", "e", "e", "b"]]], [[["b", "e", "e", ".", "b", "e", "e"], ["e", ".", "e", ".", "e", ".", "e"], ["e", "e", "b", ".", "e", "e", "b"]]]], ["5", "8"]]} +{"requirement": "Given an integer n, find the closest integer (not including itself), which is a palindrome. \n\nThe 'closest' is defined as absolute difference minimized between two integers.\n\nExample 1:\n\nInput: \"123\"\nOutput: \"121\"\n\n\n\nNote:\n\nThe input n is a positive integer represented by string, whose length will not exceed 18.\nIf there is a tie, return the smaller one as answer.", "solutions": ["def nearestpalindromic(num):\n K = len(num)\n candidates = set([10 ** K + 1, 10 ** (K - 1) - 1])\n Prefix = int(num[:(K + 1) // 2])\n for start in map(str, [Prefix - 1, Prefix, Prefix + 1]):\n candidates.add(start + [start, start[:-1]][K & 1][::-1])\n candidates.discard(num)\n return str(min(candidates, key=lambda x: (abs(int(x) - int(num)), int(x))))", "def nearestpalindromic(n):\n K = len(n)\n candidates = [str(10 ** k + d) for k in (K - 1, K) for d in (-1, 1)]\n Prefix = int(n[:(K + 1) // 2])\n for start in map(str, [Prefix - 1, Prefix, Prefix + 1]):\n candidates.append(str(start) + (start[:-1] if K % 2 == 1 else start)[::-1])\n (ans, diff) = (0, float('inf'))\n base = int(n)\n for C in candidates:\n b = int(C)\n d = abs(b - base)\n if d == 0 or d > diff or (d == diff and b > ans):\n continue\n ans = int(C)\n diff = d\n return str(ans)", "def nearestpalindromic(n):\n K = len(n)\n candidates = [str(10 ** k + d) for k in (K - 1, K) for d in (-1, 1)]\n prefix = n[:(K + 1) // 2]\n P = int(prefix)\n for start in map(str, (P - 1, P, P + 1)):\n candidates.append(start + (start[:-1] if K % 2 else start)[::-1])\n\n def delta(x):\n return abs(int(n) - int(x))\n ans = None\n for cand in candidates:\n if cand != n and (not cand.startswith('00')):\n if ans is None or delta(cand) < delta(ans) or (delta(cand) == delta(ans) and int(cand) < int(ans)):\n ans = cand\n return ans", "def nearestpalindromic(n):\n evenPal = lambda sp: int(sp + sp[::-1])\n oddPal = lambda sp: int(sp + sp[::-1][1:])\n (sn, n) = (n, int(n))\n if len(sn) == 1:\n return str(n - 1)\n ans = -999999999999999999\n mid = len(sn) // 2\n for sp in (sn[:mid], sn[:mid + 1], str(int(sn[:mid]) * 10)):\n p = int(sp)\n for pal in (evenPal, oddPal):\n for d in (-1, 0, 1):\n val = pal(str(p + d))\n if val == n:\n continue\n ans = min(ans, val, key=lambda x: (abs(x - n), x))\n return str(ans)", "def getPalindromic(num, mid=''):\n return str(num) + mid + str(num)[::-1]\n\ndef nearestpalindromic(n):\n if len(n) == 1:\n return str(int(n) - 1)\n midstr = '' if len(n) % 2 == 0 else n[len(n) // 2]\n midint = -1 if len(n) % 2 == 0 else int(n[len(n) // 2])\n s = [''] * 6\n s[0] = '9' * (len(n) - 1)\n s[1] = self.getPalindromic(int(n[:len(n) // 2]) - 1, midstr)\n s[2] = n[:len(n) // 2] + str(midint - 1) + n[:len(n) // 2][::-1] if midint > 0 else self.getPalindromic(int(n[:len(n) // 2]) - 1)\n s[3] = n[:len(n) // 2] + midstr + n[:len(n) // 2][::-1]\n s[4] = n[:len(n) // 2] + str(midint + 1) + n[:len(n) // 2][::-1] if midint < 10 and midint > -1 else self.getPalindromic(int(n[:len(n) // 2]) + 1)\n s[5] = '1' + '0' * (len(n) - 1) + '1'\n nums = map(lambda x: abs(int(x) - int(n)), s)\n nums = list(map(lambda x: x if x > 0 else 1e+18, nums))\n return s[nums.index(min(nums))]"], "starter_code": "def nearestpalindromic(n: str) -> str:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Math", "String"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Mathematics"], "skill_types": [], "url": "https://leetcode.com/problems/find-the-closest-palindrome/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "nearestpalindromic", "task_id": "TACO_lite/152", "example": [[["123"]], ["121"]]} +{"requirement": "Geek wants to climb from the 0th stair to the (n-1)th stair. At a time the Geek can climb either one or two steps. A height[N] array is also given. Whenever the geek jumps from stair i to stair j, the energy consumed in the jump is abs(height[i]- height[j]), where abs() means the absolute difference. return the minimum energy that can be used by the Geek to jump from stair 0 to stair N-1.\nExample:\nInput:\nn = 4\nheight = {10 20 30 10}\nOutput:\n20\nExplanation:\nGeek jump from 1st to 2nd stair(|20-10| = 10 energy lost).\nThen a jump from the 2nd to the last stair(|10-20| = 10 energy lost).\nso, total energy lost is 20 which is the minimum.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function MinimumEnergy() which takes the array height, and integer n, and returns the minimum energy that is lost.\nExpected Time Complexity: O(n)\nExpected Space Complexity: O(n)\nConstraint:\n1<=n<=100000\n1<=height[i]<=1000", "solutions": ["import sys\n\ndef minimumenergy(height, n):\n prev = 0\n prev2 = 0\n for i in range(1, n, 1):\n first = prev + abs(height[i] - height[i - 1])\n second = sys.maxsize\n if i > 1:\n second = prev2 + abs(height[i] - height[i - 2])\n curr = min(first, second)\n prev2 = prev\n prev = curr\n return prev", "def findMinEnergy(height, index, dp):\n if index == 0:\n return 0\n if dp[index] != -1:\n return dp[index]\n left = Solution.findMinEnergy(self, height, index - 1, dp) + abs(height[index] - height[index - 1])\n right = 1000000000.0\n if index > 1:\n right = Solution.findMinEnergy(self, height, index - 2, dp) + abs(height[index] - height[index - 2])\n dp[index] = min(left, right)\n return dp[index]\n\ndef minimumenergy(height, n):\n dp = [0] * n\n prev = 0\n prev2 = 0\n for index in range(1, n):\n fs = prev + abs(height[index] - height[index - 1])\n ss = 1000000000.0\n if index > 1:\n ss = prev2 + abs(height[index] - height[index - 2])\n curr = min(fs, ss)\n prev2 = prev\n prev = curr\n return prev", "def minimumenergy(height, n):\n prev1 = 0\n prev2 = 0\n for ind in range(1, n):\n one_step = prev1 + abs(height[ind] - height[ind - 1])\n two_step = 10000\n if ind - 2 >= 0:\n two_step = prev2 + abs(height[ind] - height[ind - 2])\n prev2 = prev1\n prev1 = min(one_step, two_step)\n return prev1", "import sys\n\ndef minimumenergy(height, n):\n dp = dict()\n dp[0] = 0\n for i in range(1, n):\n left = dp[i - 1] + abs(height[i] - height[i - 1])\n right = left\n if i > 1:\n right = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(left, right)\n return dp[n - 1]", "def minimumenergy(height, n):\n dp = [0] * n\n for i in range(1, n):\n if i < 2:\n dp[i] = abs(height[i - 1] - height[i]) + dp[i - 1]\n else:\n dp[i] = min(abs(height[i - 1] - height[i]) + dp[i - 1], abs(height[i - 2] - height[i]) + dp[i - 2])\n return dp[-1]", "import sys\n\ndef minimumenergy(height, n):\n prev2 = prev1 = 0\n for i in range(1, n):\n left = abs(height[i] - height[i - 1]) + prev1\n right = sys.maxsize\n if i > 1:\n right = abs(height[i] - height[i - 2]) + prev2\n prev2 = prev1\n prev1 = min(left, right)\n return prev1", "import sys\nimport math\n\ndef minimumenergy(height, n):\n n = len(height)\n dp = [-1 for _ in range(n)]\n dp[0] = 0\n for ind in range(1, n):\n jumpTwo = float('inf')\n jumpOne = dp[ind - 1] + abs(height[ind] - height[ind - 1])\n if ind > 1:\n jumpTwo = dp[ind - 2] + abs(height[ind] - height[ind - 2])\n dp[ind] = min(jumpOne, jumpTwo)\n return dp[n - 1]", "def minEnergy(height, index, dp):\n if index == 0:\n return 0\n if dp[index] != -1:\n return dp[index]\n jumpOneStep = abs(height[index] - height[index - 1]) + self.minEnergy(height, index - 1, dp)\n jumpTwoStep = 99999\n if index > 1:\n jumpTwoStep = abs(height[index] - height[index - 2]) + self.minEnergy(height, index - 2, dp)\n dp[index] = min(jumpOneStep, jumpTwoStep)\n return min(jumpOneStep, jumpTwoStep)\n\ndef minimumenergy(height, n):\n first = 0\n if n == 1:\n return first\n second = abs(height[1] - height[0])\n for i in range(2, n):\n fs = second + abs(height[i] - height[i - 1])\n ss = first + abs(height[i] - height[i - 2])\n ans = min(fs, ss)\n first = second\n second = ans\n return second", "def minEnergy(height, index, dp):\n if index == 0:\n return 0\n if dp[index] != -1:\n return dp[index]\n jumpOneStep = abs(height[index] - height[index - 1]) + self.minEnergy(height, index - 1, dp)\n jumpTwoStep = 99999\n if index > 1:\n jumpTwoStep = abs(height[index] - height[index - 2]) + self.minEnergy(height, index - 2, dp)\n dp[index] = min(jumpOneStep, jumpTwoStep)\n return min(jumpOneStep, jumpTwoStep)\n\ndef minimumenergy(height, n):\n table = [0 for i in range(n)]\n for index in range(1, n):\n jumpOneStep = table[index - 1] + abs(height[index] - height[index - 1])\n jumpTwoStep = 999999\n if index > 1:\n jumpTwoStep = table[index - 2] + abs(height[index] - height[index - 2])\n table[index] = min(jumpOneStep, jumpTwoStep)\n return table[n - 1]", "def minimumenergy(height, n):\n\n def recursive(ind, prev):\n if ind >= n:\n return 0\n energy = 0\n for ind in range(1, n):\n one_pick = abs(height[ind] - height[ind - 1]) + dp[ind - 1]\n two_pick = 10 ** 9\n if ind > 1:\n two_pick = abs(height[ind] - height[ind - 2]) + dp[ind - 2]\n dp[ind] = min(one_pick, two_pick)\n return dp[ind]\n dp = [0 for j in range(n + 1)]\n return recursive(0, -1)", "def minimumenergy(height, n):\n prev1 = prev2 = 0\n for i in range(1, n):\n fs = prev1 + abs(height[i - 1] - height[i])\n if i > 1:\n ss = prev2 + abs(height[i - 2] - height[i])\n else:\n ss = 100000000\n curr = min(fs, ss)\n prev2 = prev1\n prev1 = curr\n return prev1", "def minimumenergy(a, n):\n if n == 1:\n return 0\n inf = float('inf')\n dp = [inf] * (n + 1)\n dp[0] = 0\n for i in range(1, n):\n dp[i] = dp[i - 1] + abs(a[i] - a[i - 1])\n if i - 2 >= 0:\n dp[i] = min(dp[i], dp[i - 2] + abs(a[i] - a[i - 2]))\n return dp[n - 1]", "import sys\n\ndef minimumenergy(height, n):\n prev1 = 0\n prev2 = 0\n if n == 1:\n return 0\n else:\n for i in range(1, n):\n jumptwo = sys.maxsize\n onejump = prev1 + abs(height[i] - height[i - 1])\n if i > 1:\n jumptwo = prev2 + abs(height[i] - height[i - 2])\n cur_i = min(onejump, jumptwo)\n prev2 = prev1\n prev1 = cur_i\n return cur_i", "def minimumenergy(height, n):\n dp = [-1 for i in range(n)]\n dp[0] = 0\n for i in range(1, n):\n jumptwo = float('inf')\n onejump = dp[i - 1] + abs(height[i] - height[i - 1])\n if i > 1:\n jumptwo = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(onejump, jumptwo)\n return dp[n - 1]", "def minimumenergy(height, n):\n prev1 = 0\n prev2 = -1\n for i in range(1, n):\n one = prev1 + abs(height[i - 1] - height[i])\n if i <= 1:\n prev2 = prev1\n prev1 = one\n continue\n two = prev2 + abs(height[i - 2] - height[i])\n prev2 = prev1\n prev1 = min(two, one)\n return prev1\n\ndef rec(H, n, dp):\n if n == 0:\n return 0\n one = abs(H[n] - H[n - 1])\n if dp[n - 1] != -1:\n one += dp[n - 1]\n else:\n val = self.rec(H, n - 1, dp)\n dp[n - 1] = val\n one += val\n if n <= 1:\n return one\n two = abs(H[n] - H[n - 2])\n if dp[n - 2] != -1:\n two += dp[n - 2]\n else:\n val = self.rec(H, n - 2, dp)\n dp[n - 2] = val\n two += val\n return min(one, two)", "def minimumenergy(height, n):\n if n == 1:\n return 0\n first = 0\n second = abs(height[1] - height[0])\n for i in range(2, n):\n (first, second) = (second, min(first + abs(height[i] - height[i - 2]), second + abs(height[i] - height[i - 1])))\n return second", "def minimumenergy(height, n):\n prev2 = 0\n prev1 = 0\n for i in range(1, n):\n step2 = float('inf')\n step1 = prev1 + abs(height[i] - height[i - 1])\n if i > 1:\n step2 = prev2 + abs(height[i] - height[i - 2])\n curr = min(step1, step2)\n prev2 = prev1\n prev1 = curr\n return prev1", "def minimumenergy(height, n):\n dp = [-1] * n\n dp[0] = 0\n step2 = float('inf')\n for i in range(1, n):\n step1 = dp[i - 1] + abs(height[i] - height[i - 1])\n if i > 1:\n step2 = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(step1, step2)\n return dp[n - 1]", "def minimumenergy(height, n):\n prev1 = 0\n prev2 = 0\n for i in range(1, n):\n fm = prev1 + abs(height[i] - height[i - 1])\n sm = 10 ** 8\n if i > 1:\n sm = prev2 + abs(height[i] - height[i - 2])\n curr = min(fm, sm)\n prev2 = prev1\n prev1 = curr\n return prev1", "def minimumenergy(height, n):\n li = []\n if n == 0 or n == 1:\n return 0\n for i in range(0, n):\n li.append(0)\n li[0] = 0\n li[1] = abs(height[1] - height[0])\n for i in range(2, n):\n left = li[i - 1] + abs(height[i] - height[i - 1])\n right = li[i - 2] + abs(height[i] - height[i - 2])\n li[i] = min(left, right)\n return li[n - 1]", "def minimumenergy(height, n):\n prev = 0\n prev2 = 0\n for idx in range(1, n):\n left = prev + abs(height[idx - 1] - height[idx])\n if idx > 1:\n right = prev2 + abs(height[idx - 2] - height[idx])\n else:\n right = float('inf')\n curr = min(left, right)\n prev2 = prev\n prev = curr\n return prev", "import sys\nsys.setrecursionlimit(1500)\n\ndef minimumenergy(height, n):\n dp = [-1] * (n + 1)\n dp[0] = 0\n for idx in range(1, n):\n left = dp[idx - 1] + abs(height[idx - 1] - height[idx])\n if idx > 1:\n right = dp[idx - 2] + abs(height[idx - 2] - height[idx])\n else:\n right = float('inf')\n dp[idx] = min(left, right)\n return dp[n - 1]", "import sys\n\ndef minimumenergy(height, n):\n dp = [-1] * n\n dp[0] = 0\n for i in range(1, n):\n jumpTwo = sys.maxsize\n jumpOne = dp[i - 1] + abs(height[i] - height[i - 1])\n if i > 1:\n jumpTwo = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(jumpOne, jumpTwo)\n return dp[n - 1]", "def minimumenergy(height, n):\n prev2 = 0\n curr = 0\n if n == 1:\n return 0\n prev = abs(height[1] - height[0])\n if n == 2:\n return prev\n for i in range(2, n):\n curr = min(abs(height[i] - height[i - 1]) + prev, abs(height[i] - height[i - 2]) + prev2)\n prev2 = prev\n prev = curr\n return curr", "def minimumenergy(height, n):\n prev1 = 0\n prev2 = 0\n for i in range(1, n):\n left = prev1 + abs(height[i] - height[i - 1])\n right = 1000000000.0\n if i > 1:\n right = prev2 + abs(height[i] - height[i - 2])\n curr = min(left, right)\n prev2 = prev1\n prev1 = curr\n return prev1", "def minimumenergy(height, n):\n i = n - 1\n dp = [0] * n\n for i in range(1, n):\n r = 10 ** 9 + 7\n l = dp[i - 1] + abs(height[i] - height[i - 1])\n if i > 1:\n r = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(l, r)\n return dp[-1]", "import sys\n\ndef f(n, height):\n prev = 0\n prev2 = 0\n for i in range(1, n):\n jump2 = sys.maxsize\n jump1 = prev + abs(height[i] - height[i - 1])\n if i > 1:\n jump2 = prev2 + abs(height[i] - height[i - 2])\n curr = min(jump1, jump2)\n prev2 = prev\n prev = curr\n return prev\n\ndef minimumenergy(height, n):\n return self.f(n, height)", "def minimumenergy(height, n):\n memo = {}\n return self.tab_min_energy_path(0, n - 1, height, memo)\n\ndef min_energy_path(curr_index, target_index, height, memo):\n if curr_index == target_index:\n return 0\n if memo.get(curr_index) != None:\n return memo.get(curr_index)\n one_step_cost = abs(height[curr_index] - height[curr_index + 1])\n take_one_step = one_step_cost + self.min_energy_path(curr_index + 1, target_index, height, memo)\n take_two_step = float('inf')\n if curr_index <= target_index - 2:\n two_step_cost = abs(height[curr_index] - height[curr_index + 2])\n take_two_step = two_step_cost + self.min_energy_path(curr_index + 2, target_index, height, memo)\n memo[curr_index] = min(take_one_step, take_two_step)\n return memo.get(curr_index)\n\ndef tab_min_energy_path(curr_index, target_index, height, memo):\n memo[target_index] = 0\n for index in range(target_index - 1, curr_index - 1, -1):\n one_step_cost = abs(height[index] - height[index + 1])\n take_one_step = one_step_cost + memo[index + 1]\n take_two_step = float('inf')\n if index <= target_index - 2:\n two_step_cost = abs(height[index] - height[index + 2])\n take_two_step = two_step_cost + memo[index + 2]\n memo[index] = min(take_one_step, take_two_step)\n return memo.get(curr_index)", "def minimumenergy(height, n):\n k = 2\n dp = [-1] * n\n dp[0] = 0\n for i in range(1, n):\n minerg = 10000000000.0\n for j in range(1, k + 1):\n if i - j >= 0:\n curr = dp[i - j] + abs(height[i] - height[i - j])\n minerg = min(curr, minerg)\n dp[i] = minerg\n return dp[n - 1]", "def minimumenergy(height, n):\n dp = [-1] * n\n dp[0] = 0\n if n == 1:\n return dp[n - 1]\n dp[1] = abs(height[1] - height[0])\n for i in range(2, n):\n h = height[i]\n h1 = height[i - 1]\n h2 = height[i - 2]\n onestep = abs(h - h1)\n twostep = abs(h - h2)\n dp[i] = min(onestep + dp[i - 1], twostep + dp[i - 2])\n return dp[n - 1]", "def minimumenergy(height, n):\n n = n - 1\n m = 0\n l = abs(height[n] - height[n - 1])\n for i in range(n - 2, -1, -1):\n a = abs(height[i] - height[i + 1]) + l\n b = abs(height[i] - height[i + 2]) + m\n m = l\n l = min(a, b)\n return l", "def gen(height, n, count):\n if count == n:\n return 0\n if count == n - 1:\n return abs(height[count + 1] - height[count])\n if count <= n and self.dp[count] != -1:\n return self.dp[count]\n a = self.gen(height, n, count + 1) + abs(height[count] - height[count + 1])\n if count + 2 <= n:\n b = self.gen(height, n, count + 2) + abs(height[count] - height[count + 2])\n else:\n b = 9999999999999\n self.dp[count] = min(a, b)\n return min(a, b)\n\ndef minimumenergy(height, n):\n n = n - 1\n dp = [-1] * (n + 1)\n dp[n] = 0\n dp[n - 1] = abs(height[n] - height[n - 1])\n for i in range(n - 2, -1, -1):\n a = abs(height[i] - height[i + 1]) + dp[i + 1]\n b = abs(height[i] - height[i + 2]) + dp[i + 2]\n dp[i] = min(a, b)\n return dp[0]", "from functools import lru_cache\n\ndef minimumenergy(height, n):\n dp = [-1] * n\n dp[0] = 0\n for i in range(1, n):\n j2 = float('inf')\n j1 = dp[i - 1] + abs(height[i] - height[i - 1])\n if i > 1:\n j2 = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(j1, j2)\n return dp[n - 1]", "from math import inf\n\ndef minimumenergy(height, n):\n dp = [0 for _ in range(n)]\n prev1 = 0\n prev2 = inf\n for jump in range(n - 2, -1, -1):\n one_jump = abs(height[jump] - height[jump + 1]) + prev1\n two_jump = inf\n if jump < n - 2:\n two_jump = abs(height[jump] - height[jump + 2]) + prev2\n dp[jump] = min(one_jump, two_jump)\n prev2 = prev1\n prev1 = dp[jump]\n return dp[0]", "import sys\nsys.setrecursionlimit(20000)\n\ndef __init__():\n self.h = {}\n\ndef minimumenergy(height, n):\n l = [-1] * n\n l[0] = 0\n if n >= 2:\n l[1] = abs(height[1] - height[0])\n for i in range(2, n):\n l[i] = min(abs(height[i] - height[i - 1]) + l[i - 1], abs(height[i] - height[i - 2]) + l[i - 2])\n return l[n - 1]", "def minimumenergy(arr, n):\n if n == 1 or n == 2:\n return 0 if n == 1 else abs(arr[0] - arr[1])\n ans = [0 for _ in range(n)]\n ans[0] = 0\n ans[1] = abs(arr[0] - arr[1])\n for i in range(2, n):\n diff1 = abs(arr[i] - arr[i - 1])\n diff2 = abs(arr[i] - arr[i - 2])\n ans[i] = min(diff1 + ans[i - 1], diff2 + ans[i - 2])\n return ans[n - 1]", "def minimumenergy(height, n):\n if n == 1:\n return 0\n dp = [0] * n\n dp[0] = 0\n dp[1] = abs(height[0] - height[1])\n for i in range(len(dp) - 2):\n cost1 = dp[i] + abs(height[i] - height[i + 2])\n cost2 = dp[i + 1] + abs(height[i + 1] - height[i + 2])\n if cost1 > cost2:\n dp[i + 2] = cost2\n else:\n dp[i + 2] = cost1\n return dp[n - 1]", "import sys\nsys.setrecursionlimit(10000000)\n\ndef minimumenergy(height, n):\n dp = [0] * n\n for index in range(n - 2, -1, -1):\n one = 9999999\n if index + 1 < n:\n one = abs(height[index + 1] - height[index]) + dp[index + 1]\n two = 99999999\n if index + 2 < n:\n two = abs(height[index + 2] - height[index]) + dp[index + 2]\n dp[index] = min(one, two)\n return dp[0]", "import math\n\ndef minimumenergy(height, n):\n n = len(height)\n prev2 = 0\n prev = 0\n for i in range(1, n):\n jumpone = prev + abs(height[i] - height[i - 1])\n jumptwo = math.inf\n if i > 1:\n jumptwo = prev2 + abs(height[i] - height[i - 2])\n curr = min(jumpone, jumptwo)\n prev2 = prev\n prev = curr\n return prev", "import sys\n\ndef minimumenergy(height, n):\n prev1 = 0\n prev2 = 0\n for i in range(1, n):\n step1 = prev1 + abs(height[i] - height[i - 1])\n step2 = sys.maxsize\n if i > 1:\n step2 = prev2 + abs(height[i] - height[i - 2])\n cur = min(step1, step2)\n prev2 = prev1\n prev1 = cur\n return prev1", "import sys\nimport math\n\ndef minimumenergy(height, n):\n prev = prev2 = 0\n for i in range(1, n):\n jone = abs(height[i] - height[i - 1]) + prev\n jtwo = float('inf')\n if i > 1:\n jtwo = abs(height[i] - height[i - 2]) + prev2\n curri = min(jone, jtwo)\n prev2 = prev\n prev = curri\n return prev", "import sys\nimport math\n\ndef minimumenergy(height, n):\n dp = [-1 for _ in range(n + 1)]\n dp[0] = 0\n for i in range(1, n):\n jone = abs(height[i] - height[i - 1]) + dp[i - 1]\n jtwo = float('inf')\n if i > 1:\n jtwo = abs(height[i] - height[i - 2]) + dp[i - 2]\n dp[i] = min(jone, jtwo)\n return dp[n - 1]", "import sys\n\ndef minimumenergy(arr, n):\n\n def calc(n):\n dp = [-1] * (n + 1)\n dp[0] = 0\n for i in range(1, n + 1):\n j1 = dp[i - 1] + abs(arr[i] - arr[i - 1])\n if i > 1:\n j2 = dp[i - 2] + abs(arr[i] - arr[i - 2])\n else:\n j2 = float('inf')\n dp[i] = min(j1, j2)\n return dp[n]\n return calc(n - 1)", "def f(j, arr, n, dp):\n dp[n - 1] = 0\n for j in range(n - 2, -1, -1):\n onestep = 10000000\n twostep = 10000000\n if j + 1 < n:\n onestep = abs(arr[j] - arr[j + 1]) + dp[j + 1]\n if j + 2 < n:\n twostep = abs(arr[j] - arr[j + 2]) + dp[j + 2]\n dp[j] = min(onestep, twostep)\n return dp[j]\n\ndef minimumenergy(height, n):\n dp = [-1] * n\n return self.f(0, height, n, dp)", "def minimumenergy(height, n):\n dp = [-1] * n\n dp[0] = 0\n for i in range(1, n):\n if dp[i] == -1:\n left = dp[i - 1] + abs(height[i] - height[i - 1])\n second = 9999999\n if i > 1:\n second = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(left, second)\n return dp[n - 1]", "def minEnergy(height, index):\n if index == 0:\n return 0\n if self.dp[index] != -1:\n return self.dp[index]\n left = self.minEnergy(height, index - 1) + abs(height[index] - height[index - 1])\n right = 999999\n if index > 1:\n right = self.minEnergy(height, index - 2) + abs(height[index] - height[index - 2])\n self.dp[index] = min(left, right)\n return min(left, right)\n\ndef minimumenergy(height, n):\n dp = [0 for i in range(n)]\n for i in range(1, n):\n left = dp[i - 1] + abs(height[i] - height[i - 1])\n right = int(1000000000.0)\n if i > 1:\n right = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(left, right)\n return dp[n - 1]", "from sys import setrecursionlimit\nsetrecursionlimit(10 ** 8)\n\ndef minimumenergy(height, n):\n (prev, prev1) = (0, 0)\n for i in range(1, n):\n ans1 = prev1 + abs(height[i] - height[i - 1])\n ans2 = float('inf')\n if i > 1:\n ans2 = prev2 + abs(height[i] - height[i - 2])\n curr = min(ans1, ans2)\n prev2 = prev1\n prev1 = curr\n return prev1", "from sys import setrecursionlimit\nsetrecursionlimit(10 ** 8)\n\ndef minimumenergy(height, n):\n dp = [0 for i in range(n)]\n dp[n - 1] = 0\n for i in range(n - 2, -1, -1):\n ans1 = dp[i + 1] + abs(height[i] - height[i + 1])\n ans2 = float('inf')\n if i < n - 2:\n ans2 = dp[i + 2] + abs(height[i] - height[i + 2])\n dp[i] = min(ans1, ans2)\n return dp[0]"], "starter_code": "def minimumenergy(height, n):\n", "input_output": {"inputs": ["n = 4\r\nheight = {10 20 30 10}"], "outputs": ["20"]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/geek-jump/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "minimumenergy", "task_id": "TACO_lite/122", "example": [[[4, [10, 20, 30, 10]]], ["20"]]} +{"requirement": "Mary wrote a recipe book and is about to publish it, but because of a new European law, she needs to update and include all measures in grams.\n\nGiven all the measures in tablespoon (`tbsp`) and in teaspoon (`tsp`), considering `1 tbsp = 15g` and `1 tsp = 5g`, append to the end of the measurement the biggest equivalent integer (rounding up).\n\n## Examples\n\n```\n\"2 tbsp of butter\" --> \"2 tbsp (30g) of butter\"\n\n\"1/2 tbsp of oregano\" --> \"1/2 tbsp (8g) of oregano\"\n\n\"1/2 tsp of salt\" --> \"1/2 tbsp (3g) of salt\"\n\n\"Add to the mixing bowl and coat well with 1 tbsp of olive oil & 1/2 tbsp of dried dill\" -->\n\"Add to the mixing bowl and coat well with 1 tbsp (15g) of olive oil & 1/2 tbsp (8g) of dried dill\"\n```", "solutions": ["import re, math\n\ndef convert_recipe(recipe):\n\n def repl(m):\n ratio = 15 if m.group(2) == 'tbsp' else 5\n return m.group(0) + ' (%sg)' % math.ceil(eval(m.group(1)) * ratio)\n return re.sub('([0-9/]+) (tb?sp)', repl, recipe)", "import re\nimport math\n\ndef convert_recipe(recipe):\n return re.sub('(\\\\d+\\\\/\\\\d+|\\\\d+) (tbsp|tsp)', lambda x: x.group(1) + ' ' + x.group(2) + ' ' + '(' + str(math.ceil(eval(x.group(1)) * {'tbsp': 15, 'tsp': 5}[x.group(2)])) + 'g)', recipe)", "import re\nfrom math import ceil\nfrom fractions import Fraction\n\ndef convert(m, units={'tbsp': 15, 'tsp': 5}):\n (amount, unit) = m.groups()\n gram = int(ceil(Fraction(amount) * units[unit]))\n return f'{m.group()} ({gram}g)'\n\ndef convert_recipe(recipe):\n return re.sub('(\\\\S+) (tb?sp)', convert, recipe)", "import re\nfrom math import ceil\nP_RECIPE = re.compile('([\\\\d/]+) (tb?sp)')\n\ndef convert_recipe(recipe):\n return P_RECIPE.sub(update, recipe)\n\ndef update(m):\n toGrams = ceil(eval(m.group(1)) * (15 if m.group(2) == 'tbsp' else 5))\n return '{} {} ({}g)'.format(m.group(1), m.group(2), toGrams)", "from math import ceil\nimport re\n\ndef convert_recipe(recipe):\n spoons = set(re.findall('[^ ]+ tb?sp', recipe))\n for spoon in spoons:\n (qty, typ) = spoon.split(' ')\n wgt = ceil({'tsp': 5, 'tbsp': 15}[typ] * eval(qty))\n recipe = re.sub(f'(^| ){spoon}', f'\\\\g<1>{spoon} ({wgt}g)', recipe)\n return recipe", "import re, math\n\ndef convert_recipe(recipe):\n r = re.sub('((\\\\d+(/\\\\d+)?) tbsp)', tbsp, recipe)\n r = re.sub('((\\\\d+(/\\\\d+)?) tsp)', tsp, r)\n return r\n\ndef tbsp(m):\n return m.group(1) + ' (' + str(math.ceil(eval('15*' + m.group(2)))) + 'g)'\n\ndef tsp(m):\n return m.group(1) + ' (' + str(math.ceil(eval('5*' + m.group(2)))) + 'g)'", "from math import ceil\n\ndef convert_recipe(recipe):\n l = []\n l_recipe = recipe.split()\n for (num, i) in enumerate(l_recipe):\n if i == 'tbsp':\n tmp = l_recipe[num - 1]\n weight = ceil(eval(tmp) * 15) if '/' in tmp else int(tmp) * 15\n l.append('tbsp ({}g)'.format(weight))\n elif i == 'tsp':\n tmp = l_recipe[num - 1]\n weight = ceil(eval(tmp) * 5) if '/' in tmp else int(tmp) * 5\n l.append('tsp ({}g)'.format(weight))\n else:\n l.append(i)\n return ' '.join(l)", "from math import ceil\n\ndef f(number, spoon):\n measure = 15 if spoon == 'tbsp' else 5\n grams = ceil(eval(f'{measure} * {number}'))\n return f'({grams}g)'\n\ndef convert_recipe(recipe):\n seq = recipe.split()\n res = []\n for (i, word) in enumerate(seq):\n res.append(word)\n if word in ('tbsp', 'tsp'):\n res.append(f(seq[i - 1], word))\n return ' '.join(res)", "import re\nfrom math import *\n\ndef convert_recipe(s):\n d = {'tsp': 5, 'tbsp': 15}\n matches = re.findall('\\\\d*/?\\\\d+ tbsp|\\\\d*/?\\\\d+ tsp', s)\n for m in matches:\n (v, k) = m.split()\n x = eval(f'ceil({d.get(k)} * {v})')\n s = s.replace(m, f'{m} ({x}g)', 1)\n return s", "def convert_recipe(recipe):\n import math\n out = []\n for x in recipe.split(' '):\n if x in ['tbsp', 'tsp']:\n calc = math.ceil(eval('{}*{}'.format(out[-1], '15' if x == 'tbsp' else '5')))\n out.append(x)\n out.append('({}g)'.format(calc))\n else:\n out.append(x)\n return ' '.join(out)"], "starter_code": "def convert_recipe(recipe):\n", "input_output": {"fn_name": "convert_recipe", "inputs": [["2 tbsp of butter"], ["Add to the mixing bowl and coat well with 1 tbsp of olive oil & 1/2 tbsp of dried dill"], ["1/2 tsp of baking powder"], ["In another bowl, add 2 tsp of vanilla extract, 3 tsp of baking soda and 1/2 tsp of salt"], ["10 tbsp of cocoa powder"], ["1/8 tbsp of baking soda"], ["In a large bowl, combine confectioners' sugar, sour cream and vanilla"]], "outputs": [["2 tbsp (30g) of butter"], ["Add to the mixing bowl and coat well with 1 tbsp (15g) of olive oil & 1/2 tbsp (8g) of dried dill"], ["1/2 tsp (3g) of baking powder"], ["In another bowl, add 2 tsp (10g) of vanilla extract, 3 tsp (15g) of baking soda and 1/2 tsp (3g) of salt"], ["10 tbsp (150g) of cocoa powder"], ["1/8 tbsp (2g) of baking soda"], ["In a large bowl, combine confectioners' sugar, sour cream and vanilla"]]}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5acfab8d23c81836c90000eb", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "convert_recipe", "task_id": "TACO_lite/61", "example": [[["2 tbsp of butter"], ["1/2 tbsp of oregano"], ["1/2 tsp of salt"], ["Add to the mixing bowl and coat well with 1 tbsp of olive oil & 1/2 tbsp of dried dill"]], ["2 tbsp (30g) of butter", "1/2 tbsp (8g) of oregano", "1/2 tbsp (3g) of salt", "Add to the mixing bowl and coat well with 1 tbsp (15g) of olive oil & 1/2 tbsp (8g) of dried dill"]]} +{"requirement": "Given two given numbers a and b where 1<=a<=b, find the number of perfect squares between a and b (a and b inclusive).\n \nExample 1:\nInput:\na = 9, b = 25\nOutput:\n3\nExplanation:\nThere are 3 perfect squares between 9\nand 25. They are 9, 16, and 25.\nExample 2:\nInput:\na = 1, b = 7\nOutput:\n2\nExplanation:\nThere are 2 perfect squares between 1\nand 7. They are 1, and 4.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function numOfPerfectSquares() which takes 2 Integers a and b as input and returns the number of perfect squares between a and b.\n \nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= a <= b <= 10^{5}", "solutions": ["def numofperfectsquares(a, b):\n sum = 0\n c = int(b ** 0.5) + 1\n for i in range(1, c):\n if i ** 2 >= a and i ** 2 <= b:\n sum += 1\n else:\n continue\n return sum", "def numofperfectsquares(a, b):\n a = math.sqrt(a)\n b = math.sqrt(b)\n if a == int(a) or b == int(b):\n return int(b - a) + 1\n elif a == int(a) and b == int(b):\n return int(b) - int(a) + 1\n else:\n return int(b) - int(a)", "from math import *\n\ndef numofperfectsquares(a, b):\n num = ceil(sqrt(a))\n count = 0\n while pow(num, 2) <= b:\n count += 1\n num += 1\n return count", "def numofperfectsquares(a, b):\n c = int(a ** 0.5)\n d = int(b ** 0.5)\n c = 0\n for i in range(c, d + 1):\n if i ** 2 >= a:\n if i ** 2 <= b:\n c += 1\n return c", "def numofperfectsquares(a, b):\n sum = 0\n for x in range(1, 200):\n d = x * x\n if d <= b and d >= a:\n sum = sum + 1\n return sum", "import math\n\ndef numofperfectsquares(a, b):\n count_b = math.floor(math.sqrt(b))\n count_a = math.floor(math.sqrt(a - 1))\n return count_b - count_a", "def numofperfectsquares(a, b):\n return math.floor(math.sqrt(b)) - math.ceil(math.sqrt(a)) + 1", "import math\n\ndef numofperfectsquares(a, b):\n x = math.sqrt(a)\n if x == int(x):\n return int(math.sqrt(b)) - int(math.sqrt(a)) + 1\n else:\n return int(math.sqrt(b)) - int(math.sqrt(a))", "import math\n\ndef numofperfectsquares(a, b):\n num1 = math.ceil(math.sqrt(a))\n num2 = math.floor(math.sqrt(b))\n return num2 - num1 + 1", "def numofperfectsquares(a, b):\n x = int(a ** 0.5)\n y = int(b ** 0.5)\n if x != a ** 0.5:\n x += 1\n return y - x + 1", "import math\n\ndef numofperfectsquares(a, b):\n x = math.ceil(math.sqrt(a))\n y = math.sqrt(b)\n x1 = int(x)\n y1 = int(y)\n return y1 - x1 + 1", "def numofperfectsquares(a, b):\n i = 1\n K = []\n while i * i <= b:\n if i * i >= a:\n K.append(i * i)\n i += 1\n return len(K)", "from math import sqrt\n\ndef numofperfectsquares(a, b):\n count = 0\n for i in range(int(sqrt(a)), int(sqrt(b) + 1)):\n if i * i >= a and i * i <= b:\n count += 1\n return count", "def numofperfectsquares(a: int, b: int) -> int:\n\n def isPerfectSquare(num: int) -> bool:\n z = int(num ** 0.5)\n return z * z == num\n x = int(b ** 0.5)\n y = int(a ** 0.5)\n if isPerfectSquare(a):\n return x - y + 1\n else:\n return x - y", "from math import sqrt\n\ndef numofperfectsquares(a, b):\n if a > b:\n (a, b) = (b, a)\n a = int(sqrt(a)) if int(sqrt(a)) * int(sqrt(a)) == a else int(sqrt(a) + 1)\n b = int(sqrt(b)) + 1\n return abs(b - a)", "def numofperfectsquares(a, b):\n import math\n self.a = a\n self.b = b\n p = math.sqrt(a)\n q = math.sqrt(b)\n p = math.floor(q) - math.ceil(p) + 1\n return p", "def numofperfectsquares(a, b):\n count = 0\n x = math.sqrt(a)\n y = int(math.sqrt(b))\n if x != int(x):\n x = int(x) + 1\n count = int(y) - int(x) + 1\n return count", "import math\n\ndef numofperfectsquares(a, b):\n x = math.sqrt(a)\n y = int(math.sqrt(b))\n if x != int(x):\n x = int(x) + 1\n z = y - int(x) + 1\n return z", "import math\n\ndef numofperfectsquares(a, b):\n return int(math.sqrt(b)) - math.ceil(math.sqrt(a)) + 1", "import math\n\ndef numofperfectsquares(a, b):\n x = int(math.sqrt(a))\n y = int(math.sqrt(b))\n count = 0\n for i in range(x, y + 1):\n z = i * i\n if z >= a and z <= b:\n count += 1\n return count", "def numofperfectsquares(a, b):\n i = 1\n c = 0\n while i <= math.floor(math.sqrt(b)):\n if i * i >= a and i * i <= b:\n c += 1\n i += 1\n return c", "def numofperfectsquares(a, b):\n x = int(a ** 0.5)\n y = int(b ** 0.5)\n count = 0\n for i in range(x, y + 1):\n if i ** 2 >= a and i ** 2 <= b:\n count += 1\n return count", "import math\n\ndef numofperfectsquares(a, b):\n sa = math.sqrt(a)\n sb = math.sqrt(b)\n if sa % 1 != 0:\n sa = int(sa) + 1\n if sb % 1 != 0:\n sb = int(sb)\n return int(sb - sa + 1)", "from math import *\n\ndef numofperfectsquares(a, b):\n count = 0\n for i in range(ceil(sqrt(a)), floor(sqrt(b)) + 1):\n count += 1\n return count", "def numofperfectsquares(a, b):\n return math.floor(b ** 0.5) - math.ceil(a ** 0.5) + 1", "def numofperfectsquares(a, b):\n t1 = math.ceil(math.sqrt(a)) - 1\n t2 = math.sqrt(b) if math.sqrt(b) == int(math.sqrt(b)) else math.ceil(math.sqrt(b)) - 1\n return int(t2 - t1)", "def numofperfectsquares(a, b):\n count = 0\n for i in range(1, b + 1):\n ans = i * i\n if (ans >= a) & (ans <= b):\n count += 1\n elif ans >= b:\n break\n return count", "import math\n\ndef numofperfectsquares(a, b):\n x = math.ceil(a ** 0.5)\n b = int(b ** 0.5)\n return b - x + 1", "import math\n\ndef numofperfectsquares(a, b):\n lower_sqrt = math.sqrt(a)\n upper_sqrt = math.sqrt(b)\n lower = math.ceil(lower_sqrt)\n upper = math.floor(upper_sqrt)\n return upper - lower + 1", "import math\n\ndef numofperfectsquares(a, b):\n sq1 = int(math.sqrt(a))\n sq2 = int(math.sqrt(b))\n if sq1 * sq1 == a and sq2 ** sq2 == b:\n return sq2 - sq1 + 1\n if sq1 * sq1 == a:\n return sq2 - sq1 + 1\n else:\n return sq2 - sq1", "from math import ceil, floor\n\ndef numofperfectsquares(a, b):\n count = 0\n n1 = int(a ** (1 / 2))\n n2 = int(b ** (1 / 2))\n for i in range(n1, n2 + 1):\n if i * i <= b and i * i >= a:\n count += 1\n return count", "def numofperfectsquares(a, b):\n count = 0\n s1 = int(pow(a, 0.5))\n s2 = int(pow(b, 0.5))\n for i in range(s1, s2 + 1):\n if i * i >= a and i * i <= b:\n count += 1\n return count", "import math\n\ndef numofperfectsquares(a, b):\n sqra = int(math.sqrt(a))\n sqrb = int(math.sqrt(b))\n if a == sqra * sqra:\n sqrb += 1\n return sqrb - sqra", "def numofperfectsquares(a, b):\n m1 = math.sqrt(a)\n m2 = math.sqrt(b)\n if int(m1) * int(m1) == a or int(m2) * int(m2) == b:\n return int(abs(m2 - m1 + 1))\n return abs(int(m2) - int(m1))", "import math\n\ndef numofperfectsquares(a, b):\n a1 = int(math.sqrt(a))\n b1 = int(math.sqrt(b))\n x = [a1]\n if a == a1 * a1:\n return b1 - a1 + 1\n else:\n return b1 - a1\n return len(x)", "def numofperfectsquares(a, b):\n return int(int(b ** 0.5) - a ** 0.5 + 1)", "import math\n\ndef numofperfectsquares(a, b):\n k = 0\n t = int(math.sqrt(a))\n t1 = int(math.sqrt(b))\n for i in range(t, t1 + 1):\n if i ** 2 <= b and i ** 2 >= a:\n k += 1\n return k", "def numofperfectsquares(a, b):\n c = 0\n for i in range(int(pow(a, 0.5)), int(pow(b, 0.5) + 1)):\n if i * i >= a and i * i <= b:\n c = c + 1\n return c", "import math\n\ndef numofperfectsquares(a, b):\n f = math.ceil(math.sqrt(a))\n l = math.floor(math.sqrt(b))\n return l - f + 1"], "starter_code": "def numofperfectsquares(a, b):\n", "input_output": {"inputs": ["a = 9, b = 25", "a = 1, b = 7"], "outputs": ["3", "2"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/perfect-squares-in-a-range2253/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "numofperfectsquares", "task_id": "TACO_lite/140", "example": [[[9, 25], [1, 7]], ["3", "2"]]} +{"requirement": "# Task\n The number is considered to be `unlucky` if it does not have digits `4` and `7` and is divisible by `13`. Please count all unlucky numbers not greater than `n`.\n\n# Example\n\n For `n = 20`, the result should be `2` (numbers `0 and 13`).\n \n For `n = 100`, the result should be `7` (numbers `0, 13, 26, 39, 52, 65, and 91`)\n \n# Input/Output\n\n\n - `[input]` integer `n`\n\n `1 ≤ n ≤ 10^8(10^6 in Python)`\n\n\n - `[output]` an integer", "solutions": ["def unlucky_number(n):\n return sum((not ('4' in s or '7' in s) for s in map(str, range(0, n + 1, 13))))", "def unlucky_number(n):\n return sum((1 for k in range(0, n + 1, 13) if not set(str(k)) & {'4', '7'}))", "def unlucky_number(n):\n return sum((x % 13 == 0 and '4' not in str(x) and ('7' not in str(x)) for x in range(n + 1)))", "def unlucky_number(n):\n return len([i for i in range(1, n + 1) if i % 13 == 0 and str(i).count('4') == 0 and (str(i).count('7') == 0)]) + 1", "def unlucky_number(n):\n return sum((1 for n in range(0, n + 1, 13) if set(str(n)) & set('47') == set()))", "unlucky_number = lambda n: sum((not {'4', '7'} & set(str(x)) for x in range(0, n + 1, 13)))", "li = [i for i in range(0, 1000000, 13) if '4' not in str(i) and '7' not in str(i)]\nunlucky_number = lambda n: next((len(li[:li.index(i)]) + 1 for i in range(n, -1, -1) if '4' not in str(i) and '7' not in str(i) and (not i % 13)))"], "starter_code": "def unlucky_number(n):\n", "input_output": {"fn_name": "unlucky_number", "inputs": [[20], [100], [1000], [1000000]], "outputs": [[2], [7], [40], [20182]]}, "difficulty": "EASY", "raw_tags": ["Puzzles"], "name": null, "source": "codewars", "tags": ["Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/58b65c5e8b98b2e4fa000034", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "unlucky_number", "task_id": "TACO_lite/137", "example": [[[20], [100]], ["2", "7"]]} +{"requirement": "Don't Drink the Water\n\nGiven a two-dimensional array representation of a glass of mixed liquids, sort the array such that the liquids appear in the glass based on their density. (Lower density floats to the top) The width of the glass will not change from top to bottom.\n\n```\n======================\n| Density Chart |\n======================\n| Honey | H | 1.36 |\n| Water | W | 1.00 |\n| Alcohol | A | 0.87 |\n| Oil | O | 0.80 |\n----------------------\n\n[ [\n ['H', 'H', 'W', 'O'], ['O','O','O','O']\n ['W', 'W', 'O', 'W'], => ['W','W','W','W']\n ['H', 'H', 'O', 'O'] ['H','H','H','H']\n ] ]\n \n ```\n \n The glass representation may be larger or smaller. If a liquid doesn't fill a row, it floats to the top and to the left.", "solutions": ["DENSITY = {'H': 1.36, 'W': 1, 'A': 0.87, 'O': 0.8}\n\ndef separate_liquids(glass):\n if not glass:\n return []\n column = len(glass[0])\n liquids = sorted((b for a in glass for b in a), key=lambda c: DENSITY[c])\n return [liquids[d:d + column] for d in range(0, len(liquids), column)]", "def separate_liquids(glass):\n chain = sorted(sum(glass, []), key='OAWH'.index)\n return [chain[len(level) * i:][:len(level)] for (i, level) in enumerate(glass)]", "s = '| Honey | H | 1.36 |\\n| Water | W | 1.00 |\\n| Alcohol | A | 0.87 |\\n| Oil | O | 0.80 |'\n\ndef separate_liquids(glass):\n d = {}\n for x in s.split('\\n'):\n res = x.split('|')\n (a, b) = [c.strip(' ') for (i, c) in enumerate(res) if i in (2, 3)]\n d[a] = float(b)\n l = []\n for x in glass:\n l.extend(x)\n result = iter(sorted(l, key=lambda x: d[x]))\n for x in range(len(glass)):\n for i in range(len(glass[-1])):\n glass[x][i] = next(result)\n return glass", "def separate_liquids(glass):\n chain = sorted(sum(glass, []), key='HWAO'.index)\n return [[chain.pop() for c in ro] for ro in glass]", "density_order = {key: i for (i, key) in enumerate(['O', 'A', 'W', 'H'])}\n\ndef separate_liquids(glass):\n lst_of_liquids = iter(sorted([liquid for row in glass for liquid in row], key=lambda d: density_order[d]))\n return [[next(lst_of_liquids) for j in range(0, len(glass[0]))] for i in range(0, len(glass))]", "density = {'H': 4, 'W': 3, 'A': 2, 'O': 1}\n\ndef separate_liquids(glass):\n glass_ = sorted([x for i in glass for x in i], key=lambda elem: density.get(elem))\n for row in glass:\n for i in range(len(row)):\n row[i] = glass_.pop(0)\n return glass", "def separate_liquids(glass):\n liquids = []\n comparing = {'H': 1.36, 'W': 1.0, 'A': 0.87, 'O': 0.8}\n for row in glass:\n liquids.extend(row)\n liquids.sort(key=lambda k: comparing[k], reverse=True)\n for i in range(len(glass)):\n for j in range(len(glass[0])):\n glass[i][j] = liquids.pop()\n return glass"], "starter_code": "def separate_liquids(glass):\n", "input_output": {"fn_name": "separate_liquids", "inputs": [[[["H", "H", "W", "O"], ["W", "W", "O", "W"], ["H", "H", "O", "O"]]], [[["A", "A", "O", "H"], ["A", "H", "W", "O"], ["W", "W", "A", "W"], ["H", "H", "O", "O"]]], [[["A", "H", "W", "O"]]], [[["A"], ["H"], ["W"], ["O"]]], [[]]], "outputs": [[[["O", "O", "O", "O"], ["W", "W", "W", "W"], ["H", "H", "H", "H"]]], [[["O", "O", "O", "O"], ["A", "A", "A", "A"], ["W", "W", "W", "W"], ["H", "H", "H", "H"]]], [[["O", "A", "W", "H"]]], [[["O"], ["A"], ["W"], ["H"]]], [[]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms", "Sorting", "Lists"], "name": null, "source": "codewars", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/562e6df5cf2d3908ad00019e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "separate_liquids", "task_id": "TACO_lite/96", "example": [[[[["H", "H", "W", "O"], ["W", "W", "O", "W"], ["H", "H", "O", "O"]]]], ["[['O', 'O', 'O', 'O'], ['W', 'W', 'W', 'W'], ['H', 'H', 'H', 'H']]"]]} +{"requirement": "Given a number N, find if it is Disarium or not. A number is called Disarium if sum of its digits powered with their respective positions is equal to the number itself. Output 1 if it's Disarium, and 0 if not.\n \nExample 1:\nInput:\nN = 89\nOutput:\n1\nExplanation:\n8^1+9^2 = 89 thus output is 1.\nExample 2:\nInput:\nN = 81\nOutput:\n0\nExplanation:\n8^1+1^2 = 9 thus output is 0. \n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function isDisarium() which takes an Integer N as input and returns the answer.\n \nExpected Time Complexity: O(log(N))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n0 <= N <= 10^{8}", "solutions": ["def isdisarium(N):\n summ = 0\n k = 1\n for i in str(N):\n summ += int(i) ** k\n k += 1\n if summ == N:\n return 1\n return 0", "def isdisarium(N):\n N = str(N)\n x = 0\n for i in range(len(N)):\n x += int(N[i]) ** (i + 1)\n if x == int(N):\n return 1\n return 0", "def isdisarium(n):\n m = n\n count = 0\n while m:\n count += 1\n m = m // 10\n k = n\n num = 0\n while k:\n l = k % 10\n num += l ** count\n count -= 1\n k = k // 10\n return 1 if n == num else 0", "def isdisarium(N):\n l = [i for i in str(N)]\n c = 0\n for i in range(1, len(l) + 1):\n c += pow(int(l[i - 1]), i)\n if N == c:\n return 1\n else:\n return 0", "def isdisarium(N):\n n = str(N)\n a = 0\n sum = 0\n for i in range(len(n)):\n a = pow(int(n[i]), i + 1)\n sum = sum + a\n if sum == N:\n return 1\n return 0", "def isdisarium(N):\n y = 0\n x = N\n sum = 0\n for i in range(len(str(N))):\n y = x % 10\n sum += y ** len(str(x))\n x = x // 10\n if sum == N:\n return 1\n return 0", "def isdisarium(N):\n count = len(str(N))\n sum = 0\n x = N\n while x != 0:\n r = x % 10\n sum = int(sum + pow(r, count))\n count = count - 1\n x = x // 10\n if sum == N:\n return 1\n else:\n return 0", "def digitCount(num, count):\n if num == 0:\n return count\n else:\n count += 1\n return self.digitCount(num // 10, count)\n\ndef Calcsum(num, digit):\n if num == 0:\n return 0\n else:\n return pow(num % 10, digit) + self.Calcsum(num // 10, digit - 1)\n\ndef isdisarium(N):\n count = 0\n totdigit = self.digitCount(N, count)\n x = self.Calcsum(N, totdigit)\n if N == x:\n return 1\n else:\n return 0", "def isdisarium(N):\n temp = N\n sume = 0\n x = len(str(N))\n while int(N) != 0:\n d = int(N) % 10\n N = int(N) // 10\n sume += pow(d, x)\n x -= 1\n if sume == temp:\n return 1\n else:\n return 0", "def countd(num, count):\n if num == 0:\n return count\n else:\n count += 1\n return countd(num // 10, count)\n\ndef calcsum(num, count):\n if num == 0:\n return 0\n else:\n return pow(num % 10, count) + calcsum(num // 10, count - 1)\n\ndef isdisarium(N):\n count = countd(N, 0)\n num1 = calcsum(N, count)\n if num1 == N:\n return 1\n return 0", "def isdisarium(N):\n power = 1\n sum1 = 0\n for i in str(N):\n sum1 = sum1 + int(i) ** power\n power += 1\n if sum1 == N:\n return 1\n return 0", "def isdisarium(N):\n n = N\n num_digits = 0\n while n > 0:\n num_digits += 1\n n //= 10\n n = N\n sum1 = 0\n while n > 0:\n digit = n % 10\n sum1 += digit ** num_digits\n num_digits -= 1\n n //= 10\n if N == sum1:\n return 1\n else:\n return 0", "import math\n\ndef isdisarium(N):\n x = N\n sum = 0\n length = len(str(N))\n while x != 0:\n temp = x % 10\n sum = sum + math.pow(temp, length)\n length -= 1\n x = x // 10\n if sum == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n ans = 0\n n = len(str(N))\n a = str(N)\n\n def sol(ans, i):\n if i == n:\n return 0\n return ans + int(a[i]) ** (i + 1) + sol(ans, i + 1)\n return int(N == sol(0, 0))", "def isdisarium(N):\n\n def rec(new, leng, sum):\n if sum == N and new == 0:\n return 1\n if new == 0 or leng < 0:\n return 0\n rem = new % 10\n new = new // 10\n sum += rem ** leng\n return rec(new, leng - 1, sum)\n s = str(N)\n leng = len(s)\n return rec(N, leng, 0)", "def isdisarium(N):\n sum = 0\n s = [int(x) for x in str(N)]\n k = len(s)\n for i in range(0, k):\n sum = sum + s[i] ** (i + 1)\n if sum == N:\n return 1\n else:\n return 0", "def isdisarium(n):\n p = n\n s = 0\n i = len(str(n))\n while n > 0:\n a = n % 10\n k = pow(a, i)\n i -= 1\n s = s + k\n n = n // 10\n if s == p:\n return 1\n return 0", "def isdisarium(N):\n su = 0\n l = []\n a = N\n while N > 0:\n l.append(N % 10)\n N = N // 10\n l = l[::-1]\n for i in range(len(l)):\n su = su + l[i] ** (i + 1)\n if su == a:\n return 1\n else:\n return 0", "def check(l, i, n, sum):\n if sum == int(l):\n return 1\n if i == n:\n return 0\n sum += int(l[i]) ** (i + 1)\n return self.check(l, i + 1, n, sum)\n\ndef isdisarium(N):\n s = str(N)\n return self.check(s, 0, len(s), 0)", "def isdisarium(N):\n ans = 0\n a = str(N)\n for i in range(len(str(N))):\n ans += int(a[i]) ** (i + 1)\n return int(N == ans)", "def solve(n, i, s):\n if s == int(n):\n return 1\n if i == len(n):\n return 0\n return self.solve(n, i + 1, s + int(n[i]) ** (i + 1))\n\ndef isdisarium(N):\n return self.solve(str(N), 0, 0)", "import math\n\ndef isdisarium(N):\n\n def length(N):\n c = 0\n while N != 0:\n c += 1\n N = N // 10\n return c\n l = length(N)\n (dn, s) = (N, 0)\n while dn > 0:\n s += math.pow(dn % 10, l)\n dn = dn // 10\n l -= 1\n if s == N:\n return 1\n return 0", "def isdisarium(N):\n r = N\n s = len(str(N))\n sum = 0\n while N > 0:\n d = N % 10\n sum = sum + d ** s\n s -= 1\n N //= 10\n if sum == r:\n return 1\n else:\n return 0", "def isdisarium(N):\n b = N\n a = 0\n s = len(str(N))\n c = 0\n while N > 0:\n r = N % 10\n c = c + r ** s\n s = s - 1\n N = N // 10\n if b == c:\n return 1\n else:\n return 0", "def isdisarium(N):\n s = str(N)\n r = len(s) - 1\n i = 0\n d = 0\n while i <= r:\n p = s[i]\n p = int(p)\n i = i + 1\n p = p ** i\n d = d + p\n if d == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n ans = 0\n li = []\n temp = N\n while N:\n d = N % 10\n N = N // 10\n li.append(d)\n x = 1\n for i in range(len(li) - 1, -1, -1):\n ans += li[i] ** x\n x += 1\n if ans == temp:\n return 1\n return 0", "def isdisarium(N):\n Nn = list(str(N))\n m = list(map(int, Nn))\n t = 0\n for i in range(len(m)):\n t += m[i] ** (i + 1)\n if t == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n (k, res, x) = (len(str(N)), 0, N)\n for i in range(k, 0, -1):\n rem = N % 10\n res += pow(rem, i)\n N //= 10\n return 1 if res == x else 0", "def isdisarium(N: int) -> int:\n number = N\n exponent = len(str(N))\n result = 0\n while number:\n result += (number % 10) ** exponent\n exponent -= 1\n number //= 10\n return 1 if result == N else 0", "def isdisarium(N):\n number = N\n length = len(str(N))\n ans = 0\n while N != 0:\n digit = N % 10\n N = N // 10\n ans += digit ** length\n length -= 1\n if ans == number:\n return 1\n return 0", "def isdisarium(N):\n a = 0\n b = 1\n n = str(N)\n for x in n:\n a = a + int(x) ** b\n b += 1\n if a == N:\n return 1\n return 0", "def isdisarium(N):\n s = 0\n n = str(N)\n for i in range(len(n)):\n s = s + int(n[i]) ** (i + 1)\n if s == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n sum = 0\n j = 1\n s = str(N)\n for i in s:\n sum += pow(int(i), j)\n j += 1\n if sum == N:\n return 1\n return 0", "def isdisarium(N):\n n = str(N)\n rn = ''.join(reversed(n))\n x = int(rn)\n s = 0\n i = 1\n while x != 0:\n r = x % 10\n s = s + pow(r, i)\n i = i + 1\n x = x // 10\n if s == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n s = 0\n N = str(N)\n for i in range(len(N)):\n a = N[i]\n b = int(a) ** (i + 1)\n s += b\n if s == int(N):\n return 1\n return 0", "def isdisarium(N):\n s = list(map(lambda x: int(x), str(N)))\n total = 0\n for itr in range(len(s)):\n total += s[itr] ** (itr + 1)\n return 1 if total == N else 0", "def isdisarium(N):\n temp = N\n l = len(str(N))\n sum = 0\n while N > 0:\n sum += (N % 10) ** l\n l -= 1\n N //= 10\n if sum == temp:\n return 1\n else:\n return 0", "def isdisarium(N):\n digits = [int(d) for d in str(N)]\n digit_sum = 0\n for i in range(len(digits)):\n digit_sum += digits[i] ** (i + 1)\n return 1 if digit_sum == N else 0", "def isdisarium(N):\n l = []\n s = 0\n k = []\n temp = N\n while N:\n i = N % 10\n N = N // 10\n l.append(i)\n l = l[::-1]\n for i in range(len(l)):\n s = l[i] ** (i + 1)\n k.append(s)\n if sum(k) == temp:\n return 1\n return 0", "def isdisarium(N):\n copy = N\n s = str(N)\n x = 0\n n = len(s)\n for i in range(len(s)):\n x += pow(N % 10, n - i)\n N = N // 10\n if x == copy:\n return 1\n else:\n return 0", "def isdisarium(N):\n s = 0\n c = 1\n for i in str(N):\n m = int(i) ** c\n s += m\n c += 1\n return 1 if N == s else 0", "import math\n\ndef isdisarium(N):\n N = str(N)\n s = 0\n for i in range(len(N)):\n s = s + math.pow(int(N[i]), i + 1)\n if int(s) == int(N):\n return 1\n else:\n return 0", "def isdisarium(N):\n l = list(str(N))\n s = 0\n for x in range(len(l)):\n s += int(l[x]) ** (x + 1)\n if s == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n p = str(N)\n s = 0\n r = N\n w = len(p)\n while N != 0:\n d = N % 10\n s = s + int(pow(d, w))\n w = w - 1\n N = N // 10\n if r == s:\n return 1\n return 0", "def isdisarium(N):\n a = 0\n s = str(N)\n for i in range(len(s)):\n x = i + 1\n a += pow(int(s[i]), x)\n if a == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n (s, p, j) = (0, 0, 1)\n h = N\n while N > 0:\n s = 10 * s + N % 10\n N //= 10\n while s > 0:\n p += (s % 10) ** j\n j += 1\n s //= 10\n return 1 if h == p else 0", "def isdisarium(N):\n S = str(N)\n count = len(S)\n marker = count - 1\n new_N = 0\n while count > 0:\n new_N += int(S[marker]) ** count\n count -= 1\n marker -= 1\n if new_N == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n self.N = N\n count = 0\n j = 1\n for i in str(self.N):\n count += int(i) ** j\n j += 1\n if count == self.N:\n return 1\n else:\n return 0", "def isdisarium(n):\n x = str(n)\n x = [int(i) for i in x]\n k = 0\n for i in range(len(x)):\n k += x[i] ** (i + 1)\n if k == n:\n return 1\n else:\n return 0", "def isdisarium(N):\n sum = 0\n num = str(N)\n for j in range(len(num)):\n sum += int(num[j]) ** (j + 1)\n if sum == N:\n return 1\n else:\n return 0", "import math\n\ndef isdisarium(N):\n R = str(N)\n l = [int(i) for i in R]\n sum = 0\n for i in range(len(l)):\n sum = int(sum + math.pow(l[i], i + 1))\n if sum == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n sum = 0\n power = 1\n for i in str(N):\n sum += pow(int(i), power)\n power += 1\n if sum == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n s = 0\n for (p, i) in enumerate(str(N)):\n s += int(i) ** (p + 1)\n if s == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n s = str(N)\n n = len(s)\n res = 0\n t = N\n for i in range(n, 0, -1):\n res += (N % 10) ** i\n N = N // 10\n if res == t:\n return 1\n return 0", "def isdisarium(N):\n l = []\n a = str(N)\n for i in range(1, len(a) + 1):\n l.append(int(a[i - 1]) ** i)\n p = sum(l)\n if p == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n x = 0\n y = N\n z = len(str(N))\n while N > 0:\n a = N % 10\n x = x + pow(a, z)\n N = N // 10\n z = z - 1\n if x == y:\n return 1\n else:\n return 0", "def isdisarium(N):\n total_sum = 0\n position = 1\n for digit in str(N):\n total_sum += pow(int(digit), position)\n position += 1\n return 1 if total_sum == N else 0", "def isdisarium(N):\n s_num = str(N)\n c = len(s_num)\n sum1 = 0\n dup = N\n while N != 0:\n sum1 += pow(N % 10, c)\n N = N // 10\n c -= 1\n if sum1 == dup:\n return 1\n return 0", "def isdisarium(N):\n N = str(N)\n sum = 0\n for (idx, i) in enumerate(N):\n sum += int(i) ** (idx + 1)\n if sum == int(N):\n return 1\n else:\n return 0", "def isdisarium(N):\n h = 0\n j = N\n a = N\n z = str(N)\n z = list(z)\n b = len(z)\n while N != 0:\n a = N % 10\n h = h + a ** b\n N = N // 10\n b = b - 1\n if j == h:\n return 1\n return 0"], "starter_code": "def isdisarium(N):\n", "input_output": {"inputs": ["N = 89", "N = 81"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/disarium-number1045/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(N))", "entry_point": "isdisarium", "task_id": "TACO_lite/151", "example": [[[89], [81]], ["1", "0"]]} +{"requirement": "You are given a string S of lowercase alphabet characters and the task is to find its matching decimal representation as on the shown keypad. Output the decimal representation corresponding to the string. For ex: if you are given amazon then its corresponding decimal representation will be 262966.\nExample 1:\nInput:\nS = geeksforgeeks\nOutput: 4335736743357\nExplanation:geeksforgeeks is 4335736743357\nin decimal when we type it using the given\nkeypad.\nExample 2:\nInput:\nS = geeksquiz\nOutput: 433577849\nExplanation: geeksquiz is 433577849 in\ndecimal when we type it using the given\nkeypad.\nYour Task:\nComplete printNumber() function that takes string s and its length as parameters and returns the corresponding decimal representation of the given string as a string type. The printing is done by the driver code.\nConstraints:\n1 ≤ length of String ≤ 100\nExpected Time Complexity : O(n)\nExpected Auxilliary Space : O(n)", "solutions": ["def printnumber(s, n):\n s = s.upper()\n ans = ''\n my_dict = {'A': 2, 'B': 2, 'C': 2, 'D': 3, 'E': 3, 'F': 3, 'G': 4, 'H': 4, 'I': 4, 'J': 5, 'K': 5, 'L': 5, 'M': 6, 'N': 6, 'O': 6, 'P': 7, 'Q': 7, 'R': 7, 'S': 7, 'T': 8, 'U': 8, 'V': 8, 'W': 9, 'X': 9, 'Y': 9, 'Z': 9}\n for i in range(len(s)):\n ans += str(my_dict[s[i]])\n return ans", "def printnumber(s, n):\n d = [2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9]\n res = ''\n for i in s:\n res += str(d[ord(i) - ord('a')])\n return res", "def printnumber(s, n):\n s = s.lower()\n d = {'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3', 'g': '4', 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6', 'n': '6', 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8', 'u': '8', 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9'}\n result = ''\n for c in s:\n result = result + d[c]\n return result", "def printnumber(s, n):\n freq = {'a': 2, 'b': 2, 'c': 2, 'd': 3, 'e': 3, 'f': 3, 'g': 4, 'h': 4, 'i': 4, 'j': 5, 'k': 5, 'l': 5, 'm': 6, 'n': 6, 'o': 6, 'p': 7, 'q': 7, 'r': 7, 's': 7, 't': 8, 'u': 8, 'v': 8, 'w': 9, 'x': 9, 'y': 9, 'z': 9}\n ans = ''\n for ele in s:\n if ele in freq:\n ans += str(freq[ele])\n return ans", "def printnumber(s, n):\n (n2, n3, n4, n5, n6, n7, n8, n9) = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz')\n res = ''\n for i in s:\n if i in n2:\n res += '2'\n elif i in n3:\n res += '3'\n elif i in n4:\n res += '4'\n elif i in n5:\n res += '5'\n elif i in n6:\n res += '6'\n elif i in n7:\n res += '7'\n elif i in n8:\n res += '8'\n elif i in n9:\n res += '9'\n return res", "def printnumber(s, n):\n a = {'1': 1, 'A': 2, 'B': 2, 'C': 2, 'D': 3, 'E': 3, 'F': 3, 'G': 4, 'H': 4, 'I': 4, 'J': 5, 'K': 5, 'L': 5, 'M': 6, 'N': 6, 'O': 6, 'P': 7, 'Q': 7, 'R': 7, 'S': 7, 'T': 8, 'U': 8, 'V': 8, 'W': 9, 'X': 9, 'Y': 9, 'Z': 9, '*': '*', '0': 0}\n temp = ''\n for i in s.upper():\n temp += str(a[i])\n return temp", "def printnumber(str, n):\n s = ''\n for i in range(len(str)):\n if str[i] == 'a' or str[i] == 'b' or str[i] == 'c':\n s += '2'\n elif str[i] == 'd' or str[i] == 'e' or str[i] == 'f':\n s += '3'\n elif str[i] == 'g' or str[i] == 'h' or str[i] == 'i':\n s += '4'\n elif str[i] == 'j' or str[i] == 'k' or str[i] == 'l':\n s += '5'\n elif str[i] == 'm' or str[i] == 'n' or str[i] == 'o':\n s += '6'\n elif str[i] == 'p' or str[i] == 'q' or str[i] == 'r' or (str[i] == 's'):\n s += '7'\n elif str[i] == 't' or str[i] == 'u' or str[i] == 'v':\n s += '8'\n else:\n s += '9'\n return s", "def printnumber(s, n):\n l1 = []\n for i in s:\n if i in {'a', 'b', 'c'}:\n l1.append('2')\n elif i in {'d', 'e', 'f'}:\n l1.append('3')\n elif i in {'g', 'h', 'i'}:\n l1.append('4')\n elif i in {'j', 'k', 'l'}:\n l1.append('5')\n elif i in {'m', 'n', 'o'}:\n l1.append('6')\n elif i in {'p', 'q', 'r', 's'}:\n l1.append('7')\n elif i in {'t', 'u', 'v'}:\n l1.append('8')\n elif i in {'w', 'x', 'y', 'z'}:\n l1.append('9')\n return ''.join(l1)", "def printnumber(s, n):\n arr = 'abcdefghijklmnopqrtuvwxy'\n dic = {}\n x = 2\n for i in range(0, 24, 3):\n dic[arr[i]] = x\n dic[arr[i + 1]] = x\n dic[arr[i + 2]] = x\n x += 1\n dic['s'] = 7\n dic['z'] = 9\n an = ''\n for i in s:\n an = an + str(dic[i])\n return an", "def printnumber(s, n):\n (num_2, num_3, num_4) = ('abc', 'def', 'ghi')\n (num_5, num_6, num_7, num_8, num_9) = ('jkl', 'mno', 'pqrs', 'tuv', 'wxyz')\n result = ''\n for char in s:\n if char in num_2:\n result += '2'\n elif char in num_3:\n result += '3'\n elif char in num_4:\n result += '4'\n elif char in num_5:\n result += '5'\n elif char in num_6:\n result += '6'\n elif char in num_7:\n result += '7'\n elif char in num_8:\n result += '8'\n elif char in num_9:\n result += '9'\n return result", "def printnumber(s, n):\n str = ''\n for char in s:\n if char in 'abc':\n str += '2'\n elif char in 'def':\n str += '3'\n elif char in 'ghi':\n str += '4'\n elif char in 'jkl':\n str += '5'\n elif char in 'mno':\n str += '6'\n elif char in 'pqrs':\n str += '7'\n elif char in 'tuv':\n str += '8'\n elif char in 'wxyz':\n str += '9'\n return str", "def printnumber(s, n):\n (digit2, digit3, digit4, digit5, digit6, digit7, digit8, digit9) = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz')\n d = ''\n for i in s:\n if i in digit2:\n d += '2'\n elif i in digit3:\n d += '3'\n elif i in digit4:\n d += '4'\n elif i in digit5:\n d += '5'\n elif i in digit6:\n d += '6'\n elif i in digit7:\n d += '7'\n elif i in digit8:\n d += '8'\n elif i in digit9:\n d += '9'\n return d", "def printnumber(s, n):\n str_list = ['2', '22', '222', '3', '33', '333', '4', '44', '444', '5', '55', '555', '6', '66', '666', '7', '77', '777', '7777', '8', '88', '888', '9', '99', '999', '9999']\n ans = ''\n for i in range(n):\n if s[i] == ' ':\n ans += '0'\n else:\n j = ord(s[i].upper()) - ord('A')\n ans += str_list[j][0]\n return ans", "def printnumber(s, n):\n a = ''\n (two, three, four, five, six, seven, eight, nine) = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz')\n for i in s:\n if i in two:\n a += '2'\n elif i in three:\n a += '3'\n elif i in four:\n a += '4'\n elif i in five:\n a += '5'\n elif i in six:\n a += '6'\n elif i in seven:\n a += '7'\n elif i in eight:\n a += '8'\n else:\n a += '9'\n return a", "def printnumber(s, n):\n result = []\n s = s.upper()\n for i in s:\n if i == 'A' or i == 'B' or i == 'C':\n result.append('2')\n elif i == 'D' or i == 'E' or i == 'F':\n result.append('3')\n elif i == 'G' or i == 'H' or i == 'I':\n result.append('4')\n elif i == 'J' or i == 'K' or i == 'L':\n result.append('5')\n elif i == 'M' or i == 'N' or i == 'O':\n result.append('6')\n elif i == 'P' or i == 'Q' or i == 'R' or (i == 'S'):\n result.append('7')\n elif i == 'T' or i == 'U' or i == 'V':\n result.append('8')\n elif i == 'W' or i == 'X' or i == 'Y' or (i == 'Z'):\n result.append('9')\n string = ''\n return string.join(result)", "def printnumber(s, n):\n a = 'abcdefghijklmnopqrstuvwxyz'\n v = '22233344455566677778889999'\n ans = ''\n for i in s:\n ans += v[a.index(i)]\n return ans", "def printnumber(s, n):\n sr = 'abcdefghijklmnopqrstuvwxyz'\n nr = '22233344455566677778889999'\n a = ''\n for i in s:\n a += nr[sr.index(i)]\n return a", "def printnumber(s, n):\n S = ''\n for i in s:\n if i in 'abc':\n S += '2'\n if i in 'def':\n S += '3'\n if i in 'ghi':\n S += '4'\n if i in 'jkl':\n S += '5'\n if i in 'mno':\n S += '6'\n if i in 'pqrs':\n S += '7'\n if i in 'tuv':\n S += '8'\n if i in 'wxyz':\n S += '9'\n return S", "def printnumber(s, n):\n str1 = ['2', '2', '2', '3', '3', '3', '4', '4', '4', '5', '5', '5', '6', '6', '6', '7', '7', '7', '7', '8', '8', '8', '9', '9', '9', '9']\n output = ''\n for i in range(n):\n pos = ord(s[i]) - ord('a')\n output = output + str1[pos]\n return output", "def printnumber(s, n):\n s = s.upper()\n decimal = {'2': set('ABC'), '3': set('DEF'), '4': set('GHI'), '5': set('JKL'), '6': set('MNO'), '7': set('PQRS'), '8': set('TUV'), '9': set('WXYZ')}\n decimal_string = ''.join((key for char in s for (key, value) in decimal.items() if char in value))\n return decimal_string", "def printnumber(s, n):\n ans = ''\n for i in s:\n if i in 'abc':\n ans += '2'\n elif i in 'def':\n ans += '3'\n elif i in 'ghi':\n ans += '4'\n elif i in 'jkl':\n ans += '5'\n elif i in 'mno':\n ans += '6'\n elif i in 'pqrs':\n ans += '7'\n elif i in 'tuv':\n ans += '8'\n else:\n ans += '9'\n return ans", "def printnumber(s, n):\n store = {}\n for i in range(26):\n store[chr(i + 97)] = str(i // 3 + 2)\n store['s'] = '7'\n store['v'] = '8'\n store['y'] = '9'\n store['z'] = '9'\n output = ''\n for item in s:\n output += store[item]\n return output", "def printnumber(s, n):\n map = {'abc': '2', 'def': '3', 'ghi': '4', 'jkl': '5', 'mno': '6', 'pqrs': '7', 'tuv': '8', 'wxyz': '9'}\n x = [map[j] for i in s for j in map.keys() if i in j]\n return ''.join(x)", "def printnumber(s, n):\n l = ''\n for i in s.upper():\n if i == 'A' or i == 'B' or i == 'C':\n l = l + '2'\n elif i == 'D' or i == 'E' or i == 'F':\n l = l + '3'\n elif i == 'G' or i == 'H' or i == 'I':\n l = l + '4'\n elif i == 'J' or i == 'K' or i == 'L':\n l = l + '5'\n elif i == 'M' or i == 'N' or i == 'O':\n l = l + '6'\n elif i == 'P' or i == 'Q' or i == 'R' or (i == 'S'):\n l = l + '7'\n elif i == 'T' or i == 'U' or i == 'V':\n l = l + '8'\n else:\n l = l + '9'\n return l", "def printnumber(s, n):\n str1 = ''\n for s in s:\n if s >= 'a' and s <= 'c':\n str1 += '2'\n elif s >= 'd' and s <= 'f':\n str1 += '3'\n elif s >= 'g' and s <= 'i':\n str1 += '4'\n elif s >= 'j' and s <= 'l':\n str1 += '5'\n elif s >= 'm' and s <= 'o':\n str1 += '6'\n elif s >= 'p' and s <= 's':\n str1 += '7'\n elif s >= 't' and s <= 'v':\n str1 += '8'\n elif s >= 'w' and s <= 'z':\n str1 += '9'\n return str1", "def printnumber(s, n):\n d = {'abc': '2', 'def': '3', 'ghi': '4', 'jkl': '5', 'mno': '6', 'pqrs': '7', 'tuv': '8', 'wxyz': '9'}\n res = ''\n for c in s:\n for (k, v) in d.items():\n if c in k:\n res += v\n return res", "def printnumber(s, n):\n sum1 = ''\n for i in s:\n if 97 <= ord(i) <= 99:\n sum1 += '2'\n elif 100 <= ord(i) <= 102:\n sum1 += '3'\n elif 103 <= ord(i) <= 105:\n sum1 += '4'\n elif 106 <= ord(i) <= 108:\n sum1 += '5'\n elif 109 <= ord(i) <= 111:\n sum1 += '6'\n elif 112 <= ord(i) <= 115:\n sum1 += '7'\n elif 116 <= ord(i) <= 118:\n sum1 += '8'\n elif 119 <= ord(i) <= 122:\n sum1 += '9'\n return sum1", "def printnumber(s, n):\n op = ''\n for i in range(n):\n if s[i] in 'abc':\n op += '2'\n elif s[i] in 'def':\n op += '3'\n elif s[i] in 'ghi':\n op += '4'\n elif s[i] in 'jkl':\n op += '5'\n elif s[i] in 'mno':\n op += '6'\n elif s[i] in 'pqrs':\n op += '7'\n elif s[i] in 'tuv':\n op += '8'\n elif s[i] in 'wxyz':\n op += '9'\n else:\n pass\n return op", "def printnumber(s, n):\n l = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']\n r = ''\n for i in s:\n if i in l[0]:\n r += '2'\n elif i in l[1]:\n r += '3'\n elif i in l[2]:\n r += '4'\n elif i in l[3]:\n r += '5'\n elif i in l[4]:\n r += '6'\n elif i in l[5]:\n r += '7'\n elif i in l[6]:\n r += '8'\n elif i in l[7]:\n r += '9'\n elif i == ' ':\n r += '0'\n return r", "def printnumber(s, n):\n s = s.upper()\n ans = ''\n two = ['A', 'B', 'C']\n three = ['D', 'E', 'F']\n four = ['G', 'H', 'I']\n five = ['J', 'K', 'L']\n six = ['M', 'N', 'O']\n seven = ['P', 'Q', 'R', 'S']\n eight = ['T', 'U', 'V']\n nine = ['W', 'X', 'Y', 'Z']\n for i in s:\n if i in two:\n ans += '2'\n elif i in three:\n ans += '3'\n elif i in four:\n ans += '4'\n elif i in five:\n ans += '5'\n elif i in six:\n ans += '6'\n elif i in seven:\n ans += '7'\n elif i in eight:\n ans += '8'\n else:\n ans += '9'\n return ans", "def printnumber(s, n):\n a = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']\n b = [2, 3, 4, 5, 6, 7, 8, 9]\n a1 = set(list(s))\n for i in a1:\n for j in a:\n if i in j:\n v = b[a.index(j)]\n s = s.replace(i, str(v))\n break\n return int(s)", "def printnumber(s, n):\n numbers = '22233344455566677778889999'\n final_num = ''\n for char in s:\n diff = ord(char) - ord('a')\n final_num = final_num + numbers[diff]\n return final_num", "def printnumber(s, n):\n nums = '22233344455566677778889999'\n ans = ''\n c = 'a'\n for i in range(n):\n temp = ord(s[i]) - ord(c)\n ans = ans + nums[temp]\n return ans", "def printnumber(s, n):\n c = []\n c = s\n sum = ''\n for i in c:\n if i in 'ABCabc':\n sum += str(2)\n elif i in 'DEFdef':\n sum += str(3)\n elif i in 'GHIghi':\n sum += str(4)\n elif i in 'JKLjkl':\n sum += str(5)\n elif i in 'MNOmno':\n sum += str(6)\n elif i in 'PQRSpqrs':\n sum += str(7)\n elif i in 'TUVtuv':\n sum += str(8)\n elif i in 'WXYZwxyz':\n sum += str(9)\n return sum"], "starter_code": "def printnumber(s,n):\n", "input_output": {"fn_name": "printNumber", "inputs": ["S = geeksforgeeks", "S = geeksquiz"], "outputs": ["4335736743357", "433577849"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/keypad-typing0119/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "printnumber", "task_id": "TACO_lite/105", "example": [[], []]} +{"requirement": "You have to create a function that converts integer given as string into ASCII uppercase letters.\n\nAll ASCII characters have their numerical order in table. \n\nFor example,\n\n```\nfrom ASCII table, character of number 65 is \"A\".\n```\n\nNumbers will be next to each other, So you have to split given number to two digit long integers.\n\nFor example, \n\n```\n'658776' to [65, 87, 76] and then turn it into 'AWL'.\n```", "solutions": ["def convert(number):\n return ''.join((chr(int(number[a:a + 2])) for a in range(0, len(number), 2)))", "def convert(number):\n return ''.join((chr(int(number[i:i + 2])) for i in range(0, len(number), 2)))\n pass", "def convert(number):\n return ''.join([chr(int(x)) for x in map(''.join, zip(*[iter(number)] * 2))])", "def convert(number):\n return ''.join((chr(int(f'{e1}{e2}')) for (e1, e2) in zip(*[iter(number)] * 2)))", "def convert(n):\n return ''.join([chr(int(i + k)) for (i, k) in zip(n[::2], n[1::2])])", "convert = lambda s: ''.join((chr(int(s[i:i + 2])) for i in range(0, len(s), 2)))", "import re\n\ndef convert(number):\n return ''.join((chr(int(code)) for code in re.findall('\\\\d\\\\d', number)))", "def convert(n):\n return ''.join([chr(int(n[i:i + 2])) for i in range(0, len(n) - 1, 2)])", "convert = lambda s: bytes((int(s[i:i + 2]) for i in range(0, len(s), 2))).decode()", "def convert(line):\n return ''.join([chr(int(line[i:i + 2])) for i in range(0, len(line), 2)])"], "starter_code": "def convert(number):\n", "input_output": {"fn_name": "convert", "inputs": [["65"], ["656667"], ["676584"], ["73327673756932858080698267658369"], ["32327332327679866932328380656769833232"], ["84726982693273833278793270857832737832657889327984726982326765836983"]], "outputs": [["A"], ["ABC"], ["CAT"], ["I LIKE UPPERCASE"], [" I LOVE SPACES "], ["THERE IS NO FUN IN ANY OTHER CASES"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/589ebcb9926baae92e000001", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "convert", "task_id": "TACO_lite/161", "example": [[["658776"]], ["AWL"]]} +{"requirement": "Given a string N representing a positive number. The task is to round N to the nearest multiple of 10.\nNote: If you are having two multiple equally apart from N then we will choose the smallest element among them.\n \nExample 1:\n \nInput : N = 15\nOutput : 10\nExplanation:\nHere N is 15. So, the number which is\nmultiple of 10 are 10, 20, 30. We can\nsee 10 and 20 are equally distant\nfrom 20. So, we will choose the\nsmallest element among them i.e., 10.\nExample 2:\nInput : N = 29 \nOutput : 30 \n \nYour Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function roundToNearest() that takes a string (N), and returns the nearest multiple of 10. The driver code takes care of the printing.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\n \nConstraints:\n1 <= |Number length| <= 10^{5}", "solutions": ["def roundtonearest(N):\n N = int(N)\n if N % 10 <= 5:\n a = N // 10\n return a * 10\n else:\n return (N // 10 + 1) * 10", "def roundtonearest(N):\n n = int(N)\n b = n // 10 * 10\n c = b + 10\n if n - b > c - n:\n return c\n return b", "def roundtonearest(N):\n a = int(N) // 10 * 10\n b = a + 10\n if int(N) - a > b - int(N):\n return b\n else:\n return a", "def roundtonearest(N):\n k = int(N)\n r = k % 10\n if r > 5:\n return k - r + 10\n else:\n return k - r", "def roundtonearest(N):\n f = 1\n maxx = int(N)\n while f == 1:\n if maxx % 10 == 0:\n f = 0\n else:\n maxx += 1\n g = 1\n minn = int(N)\n while g == 1:\n if minn % 10 == 0:\n g = 0\n else:\n minn -= 1\n if abs(int(N) - maxx) < abs(int(N) - minn):\n return maxx\n return minn", "def roundtonearest(N):\n n = int(N)\n q = n // 10\n r = n % 10\n if r <= 5:\n return 10 * q\n else:\n return 10 * (q + 1)", "def roundtonearest(n):\n n = int(n)\n z = n % 10\n if z <= 5:\n x = n - z\n return x\n else:\n p = 10 - z\n x = n + p\n return x", "def roundtonearest(N):\n a = int(N)\n for i in range(11):\n if a % 10 == 0:\n return str(a)\n b = a - i\n c = a + i\n if b % 10 == 0:\n return str(b)\n if c % 10 == 0:\n return str(c)\n return ''", "def roundtonearest(N):\n N = int(N)\n val = N % 10\n if val == 10:\n return str(N)\n if val > 5:\n N += 10 - val\n else:\n N -= val\n return str(N)", "def roundtonearest(N):\n t = int(N)\n ans = ''\n if t % 10 == 5:\n t = t - 5\n elif t % 10 > 5:\n t = t + 10 - t % 10\n else:\n t = t - t % 10\n return str(t)", "def roundtonearest(N):\n count1 = 0\n count2 = 0\n n1 = int(N)\n if n1 <= 10:\n if n1 > 5:\n return '10'\n else:\n return '0'\n while n1 % 10 != 0:\n count1 += 1\n n1 += 1\n n2 = int(N)\n while n2 % 10 != 0:\n count2 += 1\n n2 -= 1\n if count1 < count2:\n return str(n1)\n elif count1 > count2:\n return str(n2)\n else:\n return str(n2)", "def roundtonearest(N):\n N = int(N)\n if N < 10 and N > 5:\n return 10\n elif N <= 5:\n return 0\n elif N % 10 == 0:\n return N\n rem = N % 10\n if rem <= 5:\n return N - rem\n elif rem > 5:\n return N + 10 - rem", "def roundtonearest(N):\n N = int(N)\n a = N % 10\n if a == 0:\n return N\n elif a <= 5:\n return N - int(a)\n else:\n return N + (10 - int(a))", "def roundtonearest(N):\n N = int(N)\n if N % 10 > 5:\n n = 10 - N % 10\n N = n + N\n elif N % 10 < 5:\n n = N % 10\n N = N - n\n else:\n N = N - 5\n return N", "def roundtonearest(n):\n n = int(n)\n d = n // 10\n first = d * 10\n second = (d + 1) * 10\n if abs(n - first) <= abs(n - second):\n return str(first)\n else:\n return str(second)", "def roundtonearest(N):\n N = int(N)\n n = N % 10\n if n < 6:\n return N - n\n return N + (10 - n)", "def roundtonearest(N):\n n = int(N)\n pn = abs(n)\n last_digit = pn % 10\n add = 0\n if 5 < last_digit <= 9:\n add = 10 - last_digit\n elif 1 <= last_digit <= 5:\n add = -last_digit\n if n > 0:\n return pn + add\n else:\n return -(pn + add)", "def roundtonearest(N):\n if len(N) == 1:\n if int(N) <= 5:\n return 0\n else:\n return 10\n elif int(N[-1]) <= 5:\n return N[0:-1] + '0'\n else:\n return str(int(N[0:-1]) + 1) + '0'", "def roundtonearest(N):\n rem = int(N[len(N) - 1])\n if rem > 5:\n rem = abs(10 - rem)\n else:\n rem = -rem\n temp = int(N)\n temp += rem\n return str(temp)", "def roundtonearest(N):\n que = int(N) // 10\n remainder = int(N) % 10\n if remainder <= 5:\n return 10 * que\n return 10 * (que + 1)", "def roundtonearest(N):\n if int(N) <= 5:\n return '0'\n if int(N) <= 9:\n return '10'\n n = int(N) % 10\n if n == 0:\n return str(N)\n elif n <= 5:\n return str(int(N) - n)\n else:\n return str(int(N) - n + 10)", "def roundtonearest(n):\n n = int(n)\n r = n % 10\n n1 = n - r\n if r <= 5:\n return n1\n else:\n return n1 + 10", "def roundtonearest(N):\n N = int(N)\n if N % 10 <= 5:\n return 10 * (N // 10)\n elif N % 10 > 5:\n return 10 * (N // 10 + 1)", "def roundtonearest(N):\n\n def getNumber(N):\n n1 = int(N)\n return (n1, n1 % 10)\n if N[-1] <= '5':\n (k1, k2) = getNumber(N)\n return k1 - k2\n else:\n (k1, k2) = getNumber(N)\n return k1 + (10 - k2)", "def roundtonearest(N):\n last = int(N[-1])\n if last > 5:\n last = 10 - last\n else:\n last = -last\n res = int(N)\n res += last\n return str(res)", "def roundtonearest(N):\n re = int(N[len(N) - 1])\n if re > 5:\n re = abs(10 - re)\n else:\n re = -re\n t = int(N)\n t += re\n return str(t)", "def roundtonearest(N):\n a = str(N)\n las = a[-1]\n nea = int(las)\n if 10 - nea < 5:\n return str(int(N) + (10 - nea))\n else:\n ans = int(N) - nea\n return str(ans)", "def roundtonearest(N):\n n = int(N)\n low = n // 10 * 10\n high = low + 10\n if n - low > high - n:\n return high\n else:\n return low", "def roundtonearest(N):\n x = int(N)\n y = len(N)\n if x % 10 > 5:\n x = x + 10 - x % 10\n else:\n x = x - x % 10\n return str(x)", "def roundtonearest(N):\n x = int(N)\n if x % 10 <= 5:\n return x - x % 10\n else:\n return x + (10 - x % 10)", "def roundtonearest(N):\n s = int(N)\n k = s % 10\n l = s // 10\n if k <= 5:\n return l * 10\n else:\n return (l + 1) * 10", "def roundtonearest(N):\n N = int(N)\n unit_n = N % 10\n ans = None\n if unit_n >= 0 and unit_n <= 5:\n ans = N - unit_n\n else:\n ans = N + (10 - unit_n)\n return ans", "def roundtonearest(N):\n s = int(N) // 10\n if int(N) - s * 10 <= (s + 1) * 10 - int(N):\n return s * 10\n else:\n return (s + 1) * 10", "def roundtonearest(N):\n ans = 0\n n = int(N)\n if n % 10 > 5:\n ans = (n // 10 + 1) * 10\n else:\n ans = n // 10 * 10\n return int(ans)", "def roundtonearest(n):\n t = int(n) % 10\n j = abs(10 - t)\n if j < 5:\n a = str(int(n) + j)\n return a\n else:\n b = str(int(n) - t)\n return b", "def roundtonearest(N):\n N = int(N)\n a1 = N // 10\n a2 = (a1 + 1) * 10\n if abs(N - a1 * 10) == abs(N - a2):\n return a1 * 10\n if abs(N - a1 * 10) > abs(N - a2):\n return a2\n else:\n return a1 * 10", "def roundtonearest(N):\n N = int(N)\n l = int(N)\n m = int(N)\n while l % 10:\n l -= 1\n while m % 10:\n m += 1\n if m % 10 == 0 and l % 10 == 0:\n if N - l > m - N:\n return m\n return l\n if m % 10 == 0:\n return m\n return l", "def roundtonearest(N):\n k = int(N) % 10\n if k <= 5:\n return int(N) - k\n return int(N) + abs(k - 10)", "def roundtonearest(N):\n i = int(N)\n N = int(N)\n while i > 0:\n r = N % 10\n if r == 0:\n N = N\n elif r <= 5:\n N = N - r\n else:\n N = N + 5\n i = N % 10\n return N", "def roundtonearest(N):\n N = int(N)\n c = N % 10\n if c <= 10 - c:\n return N - c\n return N + (10 - c)", "def roundtonearest(N):\n l = int(N[-1])\n x = ''\n if l in [1, 2, 3, 4]:\n x = N[:-1] + '0'\n elif l in [6, 7, 8, 9]:\n x = int(N) + (10 - l)\n elif l == 0:\n x = N\n elif l == 5:\n x = int(N) - 5\n return x", "def roundtonearest(N):\n temp = int(N)\n l = temp % 10\n if l <= 5:\n temp -= l\n else:\n temp += 10 - l\n ans = ''\n ans = temp\n return ans"], "starter_code": "def roundtonearest (N) :\n", "input_output": {"inputs": ["N = 15", "N = 29"], "outputs": ["10", "30"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical", "Strings", "Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/nearest-multiple-of-102437/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "roundtonearest", "task_id": "TACO_lite/155", "example": [[[15], [29]], ["10", "30"]]} +{"requirement": "Let's pretend your company just hired your friend from college and paid you a referral bonus. Awesome! To celebrate, you're taking your team out to the terrible dive bar next door and using the referral bonus to buy, and build, the largest three-dimensional beer can pyramid you can. And then probably drink those beers, because let's pretend it's Friday too. \n\nA beer can pyramid will square the number of cans in each level - 1 can in the top level, 4 in the second, 9 in the next, 16, 25... \n\nComplete the beeramid function to return the number of **complete** levels of a beer can pyramid you can make, given the parameters of: \n\n1) your referral bonus, and\n\n2) the price of a beer can\n\nFor example:", "solutions": ["def beeramid(bonus, price):\n beers = bonus // price\n levels = 0\n while beers >= (levels + 1) ** 2:\n levels += 1\n beers -= levels ** 2\n return levels", "from itertools import count\n\ndef beeramid(bonus, price):\n bonus = max(bonus, 0)\n n = bonus // price\n return next((x for x in count(int((n * 3) ** (1 / 3) + 1), -1) if x * (x + 1) * (2 * x + 1) // 6 <= n))", "def beeramid(bonus, price):\n k = bonus // price\n d = (3 * (11664 * k * k - 3) ** 0.5 + 324 * k) ** (1 / 3)\n n = (d / 3 + 1 / d - 1) / 2\n return k > 0 and int(n.real + 1e-12)", "def beeramid(bonus, price):\n i = 0\n while bonus > 0:\n i += 1\n bonus -= price * i ** 2\n if bonus < 0:\n i -= 1\n return i", "def beeramid(bonus, price, level=1):\n return 0 if bonus < price * level ** 2 else 1 + beeramid(bonus - price * level ** 2, price, level + 1)", "def beeramid(bonus, price):\n b = bonus / price\n n = 1\n while True:\n if b < n * (n + 1) * (2 * n + 1) / 6:\n return n - 1\n break\n n += 1", "def beeramid(bonus, price):\n num_cans = bonus // price\n level = 0\n while num_cans >= 0:\n level += 1\n num_cans -= level * level\n return max(0, level - 1)", "def beeramid(bonus, price):\n if bonus < price:\n return 0\n elif bonus == price:\n return 1\n else:\n L = []\n a = int(bonus // price) + 1\n c = 1\n for i in range(1, a):\n c += i * i\n if c <= a:\n L.append(i * i)\n b = len(L)\n return b", "def beeramid(bonus, price):\n if bonus < 0:\n return 0\n sum = 0\n x = 1\n c = 0\n while bonus / price >= sum:\n sum = sum + x ** 2\n x += 1\n c += 1\n return c - 1", "def level():\n n = 2\n while n:\n yield (n ** 2)\n n += 1\n\ndef beeramid(bonus, price):\n (b, x, sum, n) = (bonus // price, level(), 1, 0)\n while sum <= b:\n sum += next(x)\n n += 1\n return n"], "starter_code": "def beeramid(bonus, price):\n", "input_output": {"fn_name": "beeramid", "inputs": [[9, 2], [10, 2], [11, 2], [21, 1.5], [454, 5], [455, 5], [4, 4], [3, 4], [0, 4], [-1, 4]], "outputs": [[1], [2], [2], [3], [5], [6], [1], [0], [0], [0]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/51e04f6b544cf3f6550000c1", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "beeramid", "task_id": "TACO_lite/143", "example": [[[1500, 2], [5000, 3]], ["12", "16"]]} +{"requirement": "You are given a string S, the task is to reverse the string using stack.\n \nExample 1:\nInput: S=\"GeeksforGeeks\"\nOutput: skeeGrofskeeG\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function reverse() which takes the string S as an input parameter and returns the reversed string.\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\n \nConstraints:\n1 ≤ length of the string ≤ 100", "solutions": ["def reverse(s):\n stack = []\n list1 = []\n for i in range(len(s)):\n stack.append(s[i])\n for i in range(len(stack)):\n list1.append(stack.pop())\n return ''.join(list1)", "def reverse(s):\n n = len(s)\n list1 = []\n answer = ''\n for i in s:\n list1.append(i)\n for i in range(len(list1)):\n answer += list1.pop()\n return answer", "def reverse(S):\n return S[::-1]", "def reverse(S):\n return S[::-1]\n stack = []\n ans = ''\n for val in S:\n stack.append(val)\n while stack:\n ans += stack.pop()\n return ans", "def reverse(S):\n stack = []\n result = []\n for alp in S:\n stack.append(alp)\n for _ in range(len(stack)):\n result.append(stack.pop())\n return ''.join(result)", "def reverse(s):\n stack = []\n for i in range(len(s) - 1, -1, -1):\n stack.append(s[i])\n return ''.join(stack)", "def reverse(s):\n stack = []\n ans = ''\n for i in s:\n stack.append(i)\n for i in range(len(stack)):\n ans += stack.pop()\n return ans", "def reverse(s):\n return s[::-1]", "def reverse(S):\n stack = []\n n = len(S)\n for i in range(n - 1, -1, -1):\n stack.append(S[i])\n return ''.join(stack)", "def reverse(S):\n stack = []\n st = []\n for i in S:\n st.append(i)\n for i in range(len(S)):\n stack.append(st.pop())\n return ''.join(stack)", "def reverse(S):\n l = list(S)\n s = ''\n while len(l) > 0:\n s = s + l.pop()\n return s", "def reverse(S):\n stack = []\n for char in S:\n stack.append(char)\n reversed_string = ''\n while stack:\n reversed_string += stack.pop()\n return reversed_string", "from collections import deque\n\ndef reverse(S):\n n = len(S)\n stack = deque()\n for i in S:\n stack.append(i)\n ans = ''\n for i in range(len(stack)):\n ans += stack.pop()\n return ans", "def reverse(S):\n ans = ''\n for i in reversed(range(len(S))):\n ans = ans + S[i]\n return ans", "def reverse(S):\n n = len(S)\n stack = []\n for i in range(n):\n stack.append(S[i])\n s = ''\n for i in range(n):\n s = s + stack[-1]\n stack.pop()\n return s", "def reverse(S):\n stack = []\n stack2 = []\n for i in S:\n stack.append(i)\n for j in range(len(S)):\n stack2.append(stack.pop())\n return ''.join(stack2)", "def reverse(S):\n st = []\n for i in S:\n st.append(i)\n s = ''\n while st:\n s += st.pop()\n return s", "def reverse(S):\n s1 = []\n s2 = []\n for i in S:\n s1.append(i)\n for i in range(len(s1)):\n s2.append(s1.pop())\n return ''.join(s2)", "def reverse(S):\n s = ''\n a = len(S)\n for i in range(len(S)):\n s += S[a - (i + 1)]\n return s", "def reverse(S):\n reversedS = ''\n remainingS = len(S)\n while remainingS > 0:\n reversedS += S[remainingS - 1]\n remainingS -= 1\n return reversedS", "def reverse(S):\n st = []\n r = ''\n for i in S:\n st.append(i)\n while st:\n r += st.pop()\n return r", "def reverse(S):\n stack = []\n newS = ''\n for s in range(len(S)):\n stack.append(S[s])\n while len(stack) > 0:\n newS += stack.pop()\n return newS", "def reverse(S):\n stack = []\n for i in S:\n stack.append(i)\n s = ''\n for i in range(len(S)):\n x = stack.pop()\n s += x\n return s", "def reverse(S):\n stack = []\n for i in S:\n stack.append(i)\n return ''.join(stack[::-1])", "def reverse(S):\n stack1 = []\n stack2 = []\n for i in S:\n stack1.append(i)\n for i in range(len(stack1)):\n stack2.append(stack1.pop())\n return ''.join(stack2)", "def reverse(S):\n import collections\n ret = ''\n de = collections.deque([*S])\n for i in range(len(de)):\n ret += de.pop()\n return ret", "from collections import deque\n\ndef reverse(S):\n stack = deque()\n m = len(S)\n i = m - 1\n while i >= 0:\n stack.append(S[i])\n i -= 1\n return ''.join(stack)", "def reverse(S):\n stack = []\n astack = []\n for i in S:\n stack.append(i)\n for i in range(len(S)):\n a = stack.pop()\n astack.append(a)\n return ''.join(astack)", "def reverse(S):\n ans = ''\n st = []\n for i in S:\n st.append(i)\n while st:\n ans += st.pop()\n return ans", "def reverse(s):\n l = []\n for i in s:\n l.append(i)\n t = ''\n while len(l):\n t += l.pop(-1)\n return t", "def reverse(S):\n s = []\n for i in range(len(S)):\n s.append(S[i])\n p = ''\n while s:\n a = s.pop()\n p = p + a\n return p", "def reverse(S):\n s = []\n a = ''\n for i in S:\n s.append(i)\n while len(s) != 0:\n i = s.pop()\n a = a + i\n return a", "def reverse(S):\n output = ''\n length = len(S) - 1\n while length >= 0:\n output = output + S[length]\n length = length - 1\n return output", "def reverse(S):\n s = []\n for i in range(len(S) - 1, -1, -1):\n s.append(S[i])\n strr = ''\n for i in range(len(s)):\n strr = strr + s[i]\n return strr", "def reverse(S):\n a = []\n str = ''\n for i in S:\n a.append(i)\n b = len(a)\n while b:\n x = a.pop()\n str += x\n b -= 1\n return str", "def reverse(S):\n a = []\n u = ''\n for ch in S:\n a.append(ch)\n while len(a) != 0:\n u += a.pop()\n return u", "def reverse(S):\n stk = []\n for ch in S:\n stk.append(ch)\n ans = ''\n while stk:\n ans += stk.pop()\n return ans", "def reverse(S):\n res = ''\n stack = []\n top = -1\n for i in S:\n stack.append(i)\n top += 1\n while top >= 0:\n x = stack.pop()\n top -= 1\n res += x\n return res", "import queue\n\ndef reverse(s):\n stack = queue.LifoQueue(len(s))\n for i in s:\n stack.put(i)\n result = ''\n while not stack.empty():\n result += stack.get()\n return result", "def reverse(S):\n stack = []\n for i in S:\n stack.append(i)\n S = ''\n while stack:\n S += stack.pop()\n return S", "def reverse(S):\n stack = []\n for i in S:\n stack.append(i)\n res = ''\n for i in range(len(stack)):\n res += stack.pop()\n return res", "def reverse(S):\n S = list(S)\n S.reverse()\n S = ''.join(S)\n return S", "def reverse(S):\n r = []\n s = list(S)\n for i in range(len(s)):\n r.append(s.pop())\n r = ''.join(r)\n return r", "from collections import deque\n\ndef reverse(S):\n stack = deque()\n a = []\n for i in S:\n stack.append(i)\n while len(stack) > 0:\n a.append(stack.pop())\n return ''.join(a)", "def reverse(S):\n arr = []\n S = [x for x in S]\n if not arr:\n while S:\n arr.append(S.pop())\n return ''.join(arr)", "def reverse(S):\n stack = Stack()\n rev = ''\n for i in S:\n stack.push(i)\n while stack.isEmpty() == False:\n rev += stack.pop()\n return rev\n\ndef __init__():\n self.items = []\n\ndef isEmpty():\n return not self.items\n\ndef push(item):\n self.items.append(item)\n\ndef pop():\n return self.items.pop()", "def reverse(S):\n stack = S[::-1]\n return stack", "def reverse(S):\n stack = []\n for r in range(len(S)):\n stack.append(S[r])\n rev = ''\n for x in range(len(stack)):\n rev += stack.pop()\n return rev", "import collections\n\ndef reverse(S):\n ns = collections.deque(S)\n ns.reverse()\n return ''.join(ns)", "def reverse(S):\n l = []\n for i in S:\n l.insert(0, i)\n ans = ''.join(l)\n return ans", "def reverse(S):\n res = ''\n for c in range(len(S) - 1, -1, -1):\n res += S[c]\n return res", "def reverse(S):\n S = list(S)\n x = []\n for i in range(len(S)):\n x.append(S.pop())\n x = ''.join(x)\n return x", "def reverse(S):\n S = ''.join(reversed(S))\n return S", "def reverse(S):\n for i in S:\n rev = S[::-1]\n return rev", "def reverse(S):\n return str(S)[::-1]", "def reverse(S):\n stk = []\n for i in S:\n stk.append(i)\n i = len(S) - 1\n ans = ''\n while i >= 0:\n ans += stk[i]\n i -= 1\n return ans", "def reverse(S):\n x = []\n for i in range(len(S) - 1, -1, -1):\n x.append(S[i])\n return ''.join(x)", "def reverse(S):\n Stack = []\n for i in S:\n Stack.append(i)\n newstring = ''\n while Stack != []:\n newstring = newstring + Stack.pop()\n return newstring"], "starter_code": "def reverse(S):\n", "input_output": {"fn_name": "reverse", "inputs": ["S=\"GeeksforGeeks\""], "outputs": ["skeeGrofskeeG"]}, "difficulty": "EASY", "raw_tags": ["Stack", "Strings", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/reverse-a-string-using-stack/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "reverse", "task_id": "TACO_lite/130", "example": [[["GeeksforGeeks"]], ["skeeGrofskeeG"]]} +{"requirement": "Given a set of m distinct positive integers and a value ‘N’. Count the total number of ways we can form ‘N’ by adding the array elements. Repetitions and different arrangements are allowed.\nNote: Answer can be quite large output the answer modulo 10^{9}+7.\nExample 1:\nInput:\nm = 3 , N = 7\nArr[] = {1,5,6}\nOutput: 6\nExplanation: The different ways are:\n1+1+1+1+1+1+1\n1+1+5\n1+5+1\n5+1+1\n1+6\n6+1\n​Example 2:\nInput: \nm = 3 , N = 3\nArr[] = {1,2,3}\nOutput: 4\nExplanation: The different ways are:\n1+1+1\n1+2\n2+1\n3 \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function countWays() which accepts array arr[], its size m and integer N and returns the total number of ways we can form ‘N’ by adding array elements.\nExpected Time Complexity: O(N*m)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 <= N , m <= 10^{3}", "solutions": ["def countways(nums, m, target):\n n = len(nums)\n nums.sort()\n dp = [0 for _ in range(target + 1)]\n dp[0] = 1\n for total in range(1, target + 1):\n for i in range(n):\n if total - nums[i] >= 0:\n dp[total] += dp[total - nums[i]]\n return dp[target] % (10 ** 9 + 7)", "def countways(arr, m, n):\n mod = int(1000000000.0 + 7)\n dp = [0] * (n + 1)\n dp[0] = 1\n for i in range(1, n + 1):\n for j in arr:\n if j <= i:\n dp[i] += dp[i - j]\n dp[i] = dp[i] % mod\n return dp[n]", "def countways(arr, m, n):\n dp = [0] * (n + 1)\n dp[0] = 1\n mod = 10 ** 9 + 7\n for i in range(1, n + 1):\n for j in range(m):\n if i - arr[j] >= 0:\n dp[i] = (dp[i] + dp[i - arr[j]]) % mod\n return dp[n]", "def __init__():\n self.a1 = {}\n\ndef dp(a, s):\n if s == 0:\n self.a1[s] = 1\n return\n elif s in self.a1:\n return\n else:\n g = 0\n for i in a:\n if s - i >= 0:\n self.dp(a, s - i)\n g += self.a1[s - i]\n self.a1[s] = g\n\ndef countways(arr, m, n):\n self.dp(arr, n)\n return self.a1[n] % 1000000007", "def __init__():\n self.dp = dict()\n\ndef countways(arr, m, n):\n if not n:\n return 1\n if self.dp.get(n) != None:\n return self.dp[n]\n way = 0\n for x in arr:\n if x > n:\n continue\n way += self.countways(arr, m, n - x)\n self.dp[n] = way % (10 ** 9 + 7)\n return self.dp[n]", "def countways(arr, m, n):\n if not arr:\n return\n Mod = 1000000007\n if n < min(arr):\n return 0\n dp = [1] + [0] * n\n for i in range(1, n + 1):\n for j in range(m):\n if arr[j] <= i:\n dp[i] = dp[i] + dp[i - arr[j]] % Mod\n dp[i] %= Mod\n return dp[n]", "def countways(arr, m, n):\n dp = [0] * (n + 1)\n dp[0] = 1\n mod = 1000000007\n for i in range(1, n + 1):\n for j in arr:\n if i - j >= 0:\n dp[i] = dp[i] % mod + dp[i - j] % mod\n return dp[n] % mod", "def countways(arr, m, n):\n x = max(arr)\n x = max(x, n)\n dp = [0] * (x + 1)\n for el in arr:\n dp[el] += 1\n for i in range(n + 1):\n for el in arr:\n if i - el > 0:\n dp[i] += dp[i - el]\n return dp[n] % 1000000007", "MOD = int(1000000000.0 + 7)\n\ndef f(A, summ, dp):\n if summ == 0:\n return 1\n if dp[summ] != -1:\n return dp[summ]\n ans = 0\n for i in A:\n if i <= summ:\n ans += f(A, summ - i, dp)\n ans %= MOD\n dp[summ] = ans\n return ans\n\ndef countways(A, m, n):\n dp = [-1 for i in range(n + 1)]\n ans = 0\n for i in A:\n if i <= n:\n ans += f(A, n - i, dp)\n ans %= MOD\n return ans", "def wayPresentUsingDP(arr, total, tar, dp):\n if total == tar:\n return 1\n if total > tar:\n return 0\n if dp[total] != -4:\n return dp[total]\n ans = 0\n for (i, data) in enumerate(arr):\n if total + data <= tar:\n ans += wayPresentUsingDP(arr, total + data, tar, dp)\n dp[total] = ans\n return ans\n\ndef countways(arr, m, n):\n dp = [-4] * (n + 1)\n arr = sorted(arr)\n ans = wayPresentUsingDP(arr, 0, n, dp) % (10 ** 9 + 7)\n return ans", "def countways(arr, m, n):\n p = 10 ** 9 + 7\n count = [0 for i in range(n + 1)]\n count[0] = 1\n for i in range(1, n + 1):\n for j in range(m):\n if i >= arr[j]:\n count[i] += count[i - arr[j]]\n return count[n] % p", "def countways(arr, m, n):\n sum = n\n N = m\n coins = arr\n d = [0] * (sum + 1)\n d[0] = 1\n for i in range(sum + 1):\n for j in range(N):\n if coins[j] + i <= sum:\n d[coins[j] + i] = d[i] + d[i + coins[j]]\n return d[-1] % 1000000007", "def countways(arr, m, n):\n dp = {}\n dp[0] = 1\n for i in range(1, n + 1):\n for j in range(m):\n if i >= arr[j]:\n if i not in dp:\n if i - arr[j] not in dp:\n dp[i] = 0\n else:\n dp[i] = dp[i - arr[j]] % (10 ** 9 + 7)\n elif i - arr[j] not in dp:\n dp[i] = dp[i] % (10 ** 9 + 7)\n else:\n dp[i] = (dp[i] + dp[i - arr[j]]) % (10 ** 9 + 7)\n if n in dp:\n return dp[n]\n else:\n return 0", "def countways(arr, m, n):\n dp = [0] * (n + 1)\n ans = self.solve1(arr, n, dp)\n return ans\n\ndef solve(num, summ, dp):\n if summ == 0:\n return 1\n if summ < 0:\n return 0\n if dp[summ] != -1:\n return dp[summ]\n a = 0\n for i in range(len(num)):\n a += self.solve(num, summ - num[i], dp)\n dp[summ] = a\n return dp[summ]\n\ndef solve1(num, summ, dp):\n if summ == 0:\n return 1\n if summ < 0:\n return 0\n dp[0] = 1\n for i in range(1, n + 1):\n for j in range(len(num)):\n if i - num[j] >= 0:\n dp[i] += dp[i - num[j]]\n return dp[summ] % 1000000007", "def countways(arr, n, total):\n temp = 10 ** 9 + 7\n dp = [0 for i in range(total + 1)]\n dp[0] = 1\n for i in range(1, total + 1):\n for j in range(n):\n if arr[j] <= i:\n dp[i] += dp[i - arr[j]]\n dp[i] %= temp\n return dp[total]", "def countways(arr, m, N):\n mod = 10 ** 9 + 7\n count = [0 for i in range(N + 1)]\n count[0] = 1\n for i in range(1, N + 1):\n for j in range(m):\n if i >= arr[j]:\n count[i] += count[i - arr[j]]\n return count[N] % mod", "def countways(nums, m, target):\n dp = [0] * (target + 1)\n for i in range(1, target + 1):\n for n in nums:\n if n == i:\n dp[i] += 1\n if n < i:\n dp[i] += dp[i - n]\n return dp[-1] % (10 ** 9 + 7)", "def countways(arr, m, n):\n dp = [0] * (n + 1)\n dp[0] = 1\n arr.sort()\n for i in range(1, n + 1):\n for no in arr:\n if no > i:\n continue\n dp[i] = dp[i] + dp[i - no]\n return dp[n] % 1000000007", "def countways(arr, m, N):\n dp = [0 for _ in range(N + 1)]\n MOD = 10 ** 9 + 7\n dp[0] = 1\n for i in range(1, N + 1):\n for num in arr:\n if i - num >= 0:\n dp[i] = int((dp[i - num] + dp[i]) % MOD)\n return dp[N]", "def countways(arr, m, n):\n ways = [1] + n * [0]\n for i in range(n + 1):\n for num in arr:\n if num + i > n:\n continue\n ways[num + i] += ways[i]\n ways[num + i] %= 1000000007\n return ways[-1]", "def countways(arr, m, N):\n dp = [0] * (N + 1)\n dp[0] = 1\n s = 0\n for i in range(1, N + 1):\n for j in range(m):\n if arr[j] <= i:\n s += dp[i - arr[j]]\n dp[i] = s\n s = 0\n return dp[N] % (10 ** 9 + 7)", "def countways(arr, size, target):\n dp = [0] * (target + 1)\n dp[0] = 1\n mod = 1000000007\n for i in range(1, target + 1):\n for coin in arr:\n if coin <= i:\n dp[i] = (dp[i] + dp[i - coin]) % mod\n return dp[target]", "def dfs(arr, s, d):\n if s == 0:\n return 1\n if d.get(s) != None:\n return d[s]\n y = 0\n for i in arr:\n if s - i >= 0:\n y = y + self.dfs(arr, s - i, d)\n d[s] = y\n return y\n\ndef countways(arr, m, n):\n d = dict()\n mod = 10 ** 9 + 7\n return self.dfs(arr, n, d) % mod", "def countways(arr, n, s):\n count = [0 for i in range(s + 1)]\n count[0] = 1\n for j in range(1, s + 1):\n for e in arr:\n if j >= e:\n count[j] += count[j - e]\n return count[s] % (pow(10, 9) + 7)"], "starter_code": "def countways(arr, m, n):\n", "input_output": {"inputs": ["m = 3 , N = 7\nArr[] = {1,5,6}", "m = 3 , N = 3\nArr[] = {1,2,3}"], "outputs": ["6", "4"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/ways-to-sum-to-n5759/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*m)", "entry_point": "countways", "task_id": "TACO_lite/113", "example": [[[3, 7, [1, 5, 6]], [3, 3, [1, 2, 3]]], ["6", "4"]]} +{"requirement": "Given Preorder, Inorder and Postorder traversals of some tree of size N. The task is to check if they are all of the same tree or not.\nExample 1:\nInput:\nN = 5\npreorder[] = {1, 2, 4, 5, 3}\ninorder[] = {4, 2, 5, 1, 3}\npostorder[] = {4, 5, 2, 3, 1}\nOutput: Yes\nExplanation: \nAll of the above three traversals \nare of the same tree.\n 1\n / \\\n 2 3\n / \\\n 4 5\nExample 2:\nInput:\nN = 5\npreorder[] = {1, 5, 4, 2, 3}\ninorder[] = {4, 2, 5, 1, 3}\npostorder[] = {4, 1, 2, 3, 5}\nOutput: No\nExplanation: The three traversals can \nnot be of the same tree.\nYour Task:\nYou don't need to read input or print anything. Complete the function checktree() which takes the array preorder[ ], inorder[ ], postorder[ ] and integer N as input parameters and returns true if the three traversals are of the same tree or not. \nExpected Time Complexity: O(N^{2})\nExpected Auxiliary Space: O(N)\nConstraints:\n1 ≤ N ≤ 10^{3}\nNode values are unique.", "solutions": ["def check(pre, l1, r1, ino, l2, r2, post, l3, r3):\n if l2 > r2:\n return True\n if pre[l1] != post[r3]:\n return False\n try:\n idx = ino.index(pre[l1])\n except ValueError:\n return False\n return self.check(pre, l1 + 1, idx - l2 + l1, ino, l2, idx - 1, post, l3, l3 + idx - l2 - 1) and self.check(pre, r1 + 1 - r2 + idx, r1, ino, idx + 1, r2, post, r3 + idx - r2, r3 - 1)\n\ndef checktree(preorder, inorder, postorder, N):\n return self.check(preorder, 0, N - 1, inorder, 0, N - 1, postorder, 0, N - 1)", "def __init__(data):\n self.left = None\n self.data = data\n self.right = None\n\ndef Search(start, end, inorder, val):\n for i in range(start, end + 1):\n if inorder[i] == val:\n return i\n return -1\n\ndef ConstructTree(start, end, preindx, N, preorder, inorder, ans):\n if start > end:\n return None\n if preindx[0] >= N:\n return None\n root = Node(preorder[preindx[0]])\n indx = self.Search(start, end, inorder, preorder[preindx[0]])\n if indx == -1:\n ans[0] = False\n preindx[0] += 1\n root.left = self.ConstructTree(start, indx - 1, preindx, N, preorder, inorder, ans)\n root.right = self.ConstructTree(indx + 1, end, preindx, N, preorder, inorder, ans)\n return root\n\ndef Postorder(root, postindx, N, postorder, ans):\n if root == None:\n return\n if postindx[0] >= N:\n return\n self.Postorder(root.left, postindx, N, postorder, ans)\n self.Postorder(root.right, postindx, N, postorder, ans)\n if root.data != postorder[postindx[0]]:\n ans[0] = False\n postindx[0] += 1\n\ndef checktree(preorder, inorder, postorder, N):\n preindx = [0]\n ans = [True]\n root = self.ConstructTree(0, N - 1, preindx, N, preorder, inorder, ans)\n if ans[0] == False:\n return False\n postindx = [0]\n self.Postorder(root, postindx, N, postorder, ans)\n return ans[0]", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return True\n if N == 1:\n return preorder[0] == postorder[0] and postorder[0] == inorder[0]\n root = preorder[0]\n if root != postorder[N - 1]:\n return False\n if root not in set(inorder):\n return False\n else:\n rooti = inorder.index(root)\n leftN = rooti\n rightN = N - rooti - 1\n return self.checktree(preorder[1:leftN + 1], inorder[:rooti], postorder[:leftN], leftN) and self.checktree(preorder[leftN + 1:], inorder[rooti + 1:], postorder[leftN:N - 1], rightN)", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return True\n if N == 1:\n return inorder[0] == preorder[0] and preorder[0] == postorder[0]\n root = preorder[0]\n if root != postorder[N - 1]:\n return False\n if root not in set(inorder):\n return False\n else:\n for i in range(N):\n if inorder[i] == postorder[N - 1]:\n break\n return self.checktree(preorder[1:i + 1], inorder[:i], postorder[:i], i) and self.checktree(preorder[i + 1:], inorder[i + 1:], postorder[i:N - 1], N - i - 1)", "def __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef checktree(preorder, inorder, postorde, N):\n\n def postorder(root):\n if root is None:\n return []\n return postorder(root.left) + postorder(root.right) + [root.data]\n\n def recursive(inorder, preorder, N, idx=0, left=0, right=N - 1):\n if idx == N:\n return (None, idx)\n cur = preorder[idx]\n root = None\n for i in range(left, right + 1):\n if inorder[i] == cur:\n root = Node(cur)\n break\n if root:\n (root.left, idx) = recursive(inorder, preorder, N, idx + 1, left, i - 1)\n (root.right, idx) = recursive(inorder, preorder, N, idx, i + 1, right)\n return (root, idx)\n (root, idx) = recursive(inorder, preorder, N)\n post = postorder(root)\n if post == postorde:\n return True\n else:\n return False", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return True\n if N == 1:\n return preorder[0] == postorder[0] and postorder[0] == inorder[0]\n root = preorder[0]\n if root != postorder[N - 1]:\n return False\n if root not in set(inorder):\n return False\n else:\n index = inorder.index(root)\n left = index\n right = N - index - 1\n return self.checktree(preorder[1:left + 1], inorder[:index], postorder[:left], left) and self.checktree(preorder[left + 1:], inorder[index + 1:], postorder[left:N - 1], right)", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return True\n if N == 1:\n return preorder[0] == postorder[0] and postorder[0] == inorder[0]\n root = preorder[0]\n if root != postorder[-1]:\n return False\n if root not in set(inorder):\n return False\n else:\n index = inorder.index(root)\n lst = index\n rst = N - index - 1\n return self.checktree(preorder[1:index + 1], inorder[:index], postorder[:lst], lst) and self.checktree(preorder[lst + 1:], inorder[index + 1:], postorder[lst:N - 1], rst)", "def __init__(d):\n self.data = d\n self.left = None\n self.right = None\n\ndef checktree(preorder, inorder, postorder, N):\n m = {}\n for i in range(N):\n m[inorder[i]] = i\n l = [0]\n\n def construct(st, end):\n if st > end:\n return None\n node = Node(preorder[l[0]])\n pos = m[preorder[l[0]]]\n l[0] += 1\n try:\n node.left = construct(st, pos - 1)\n node.right = construct(pos + 1, end)\n except:\n return None\n return node\n root = construct(0, N - 1)\n l = []\n\n def post(r):\n if r:\n post(r.left)\n post(r.right)\n l.append(r.data)\n post(root)\n return l == postorder", "def __init__(val):\n self.val = val\n self.left = self.right = None\n\ndef build(pre, ino):\n tem = [True]\n n = len(pre)\n\n def rec(st, en, n):\n if st > en or ind[0] >= n or tem[0] == None:\n return\n nod = Node(pre[ind[0]])\n ind[0] += 1\n idx = st - 1\n for i in range(st, en + 1):\n if ino[i] == nod.val:\n idx = i\n break\n if idx == st - 1:\n tem[0] = None\n return\n nod.left = rec(st, idx - 1, n)\n nod.right = rec(idx + 1, en, n)\n return nod\n ind = [0]\n root = Node(pre[0])\n ind[0] += 1\n idx = inorder.index(root.val)\n root.left = rec(0, idx - 1, n)\n root.right = rec(idx + 1, n - 1, n)\n if tem[0] == None:\n return tem[0]\n return root\n\ndef checktree(preorder, inorder, postorder, N):\n root = self.build(preorder, inorder)\n if root is None:\n return False\n ind = [0, True]\n\n def rec(nod, n):\n if nod is None or ind[1] == False:\n return\n if nod is not None and ind[0] >= n:\n ind[1] = False\n return\n rec(nod.left, n)\n rec(nod.right, n)\n if postorder[ind[0]] != nod.val:\n ind[1] = False\n return\n ind[0] += 1\n rec(root, N)\n return ind[1]", "def checktree(preorder, inorder, postorder, N):\n\n def f(inord, pre, st, en, i, n, d, arr):\n if st > en or i[0] >= n:\n return\n pos = d[pre[i[0]]]\n val = pre[i[0]]\n i[0] += 1\n f(inord, pre, st, pos - 1, i, n, d, arr)\n f(inord, pre, pos + 1, en, i, n, d, arr)\n arr += [val]\n ind = [0]\n d = {}\n for i in range(N):\n d[inorder[i]] = i\n arr = []\n f(inorder, preorder, 0, N - 1, ind, N, d, arr)\n for i in range(N):\n if arr[i] != postorder[i]:\n return False\n return True", "def checktreeutil(preorder, inorder, postorder):\n if len(preorder) >= 1 and len(postorder) >= 1 and (len(inorder) >= 1):\n if len(preorder) != len(postorder):\n return False\n temp = -10000000\n for i in range(len(inorder)):\n if inorder[i] == preorder[0]:\n temp = i\n if temp == -10000000:\n return False\n if len(preorder) != 0 and len(postorder) != 0:\n if preorder[0] != postorder[len(postorder) - 1]:\n return False\n return self.checktreeutil(preorder[1:1 + temp], inorder[0:temp], postorder[0:temp]) and self.checktreeutil(preorder[temp + 1:], inorder[temp + 1:], postorder[temp:len(postorder) - 1])\n return True\n\ndef checktree(preorder, inorder, postorder, N):\n return self.checktreeutil(preorder, inorder, postorder)", "def __init__(v):\n self.val = v\n self.left = None\n self.right = None\n\ndef checktree(pr, io, po, n):\n valid = True\n\n def f(pr, io):\n nonlocal valid\n if not valid:\n return\n if len(pr) == 0 and len(io) == 0:\n return\n if len(pr) != len(io) or pr[0] not in io:\n valid = False\n return\n if len(pr) == 1:\n z.append(pr[0])\n return\n i = io.index(pr[0])\n if len(pr) > 1:\n f(pr[1:i + 1], io[:i])\n f(pr[i + 1:], io[i + 1:])\n z.append(pr[0])\n z = []\n f(pr, io)\n return z == po", "def __init__(data, left=None, right=None):\n self.data = data\n self.left = left\n self.right = right\n\ndef checktree(preorder, inorder, postorder, N):\n\n def postOrder(root):\n if root:\n postOrder(root.left)\n postOrder(root.right)\n post.append(root.data)\n\n def buildTree(inStart, inEnd, preStart, preEnd):\n if inStart > inEnd or preStart > preEnd:\n return None\n root = Node(preorder[preStart])\n inRoot = inMap[root.data]\n inLeft = inRoot - inStart\n root.left = buildTree(inStart, inRoot - 1, preStart + 1, preStart + inLeft)\n root.right = buildTree(inRoot + 1, inEnd, preStart + inLeft + 1, preEnd)\n return root\n inMap = {}\n for i in range(N):\n inMap[inorder[i]] = i\n try:\n root = buildTree(0, N - 1, 0, N - 1)\n except:\n return False\n post = []\n postOrder(root)\n for i in range(N):\n if postorder[i] != post[i]:\n return False\n return True", "def __init__(data):\n self.data = data\n self.left = None\n self.right = None\n\ndef post(root, crr):\n if root == None:\n return\n self.post(root.left, crr)\n self.post(root.right, crr)\n crr.append(root.data)\n return crr\n\ndef solve(pre, ino, N, arr, s, e, hm):\n if arr[0] >= N or s > e:\n return None\n el = pre[arr[0]]\n root = Node(el)\n arr[0] += 1\n pos = hm[el] - 1\n root.left = self.solve(pre, ino, N, arr, s, pos - 1, hm)\n root.right = self.solve(pre, ino, N, arr, pos + 1, e, hm)\n return root\n\ndef checktree(preorder, inorder, postorder, N):\n hm = {}\n for i in range(N):\n hm[inorder[i]] = i + 1\n arr = [0]\n s = 0\n e = N - 1\n root = self.solve(preorder, inorder, N, arr, s, e, hm)\n crr = []\n crr = self.post(root, crr)\n if crr == postorder:\n return 1\n return 0", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return True\n if N == 1:\n return preorder[0] == postorder[0] and postorder[0] == inorder[0]\n root = preorder[0]\n idx = -1\n for i in range(N):\n if inorder[i] == preorder[0]:\n idx = i\n break\n if idx == -1:\n return False\n if preorder[0] != postorder[N - 1]:\n return False\n w1 = self.checktree(preorder[1:], inorder, postorder, idx)\n w2 = self.checktree(preorder[idx + 1:], inorder[idx + 1:], postorder[idx:], N - idx - 1)\n return w1 and w2", "def checktree(preorder, inorder, postorder, N):\n if not preorder and (not inorder) and (not postorder):\n return True\n if len(preorder) != len(inorder) or len(inorder) != len(postorder) or len(postorder) != len(preorder):\n return False\n preorderRoot = preorder[0]\n postorderRoot = postorder[-1]\n if preorderRoot != postorderRoot:\n return False\n try:\n rootIndex = inorder.index(preorderRoot)\n except ValueError:\n return False\n leftsubTree = self.checktree(preorder[1:rootIndex + 1], inorder[:rootIndex], postorder[:rootIndex], N)\n rightsubTree = self.checktree(preorder[rootIndex + 1:], inorder[rootIndex + 1:], postorder[rootIndex:-1], N)\n return leftsubTree and rightsubTree", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return True\n if preorder[0] != postorder[-1]:\n return False\n root = preorder[0]\n if root not in inorder:\n return False\n else:\n p = inorder.index(preorder[0])\n lt = self.checktree(preorder[1:p + 1], inorder[:p], postorder[:p], p)\n rt = self.checktree(preorder[p + 1:], inorder[p + 1:], postorder[p:N - 1], N - p - 1)\n return lt & rt", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return 1\n if N == 1:\n return preorder[0] == inorder[0] and inorder[0] == postorder[0]\n idx = -1\n for i in range(N):\n if inorder[i] == preorder[0]:\n idx = i\n break\n if idx == -1:\n return 0\n if preorder[0] != postorder[N - 1]:\n return 0\n ret1 = self.checktree(preorder[1:], inorder, postorder, idx)\n ret2 = self.checktree(preorder[idx + 1:], inorder[idx + 1:], postorder[idx:], N - idx - 1)\n return ret1 and ret2", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return True\n if N == 1:\n return preorder[0] == inorder[0] and inorder[0] == postorder[0]\n root = preorder[0]\n if root != postorder[N - 1]:\n return False\n if root not in set(inorder):\n return False\n else:\n index_of_root = inorder.index(root)\n left_part = index_of_root\n right_part = N - index_of_root - 1\n return self.checktree(preorder[1:left_part + 1], inorder[:index_of_root], postorder[:left_part], left_part) and self.checktree(preorder[left_part + 1:], inorder[index_of_root + 1:], postorder[left_part:N - 1], right_part)", "def checktree(preorder, inorder, postorder, n):\n if not n:\n return True\n if n == 1:\n return preorder[0] == postorder[0] and postorder[0] == inorder[0]\n idx = -1\n for i in range(n):\n if inorder[i] == preorder[0]:\n idx = i\n break\n if idx == -1:\n return 0\n if preorder[0] != postorder[n - 1]:\n return 0\n left = self.checktree(preorder[1:], inorder, postorder, idx)\n right = self.checktree(preorder[idx + 1:], inorder[idx + 1:], postorder[idx:], n - idx - 1)\n return left and right", "def build(preorder, ind, inorder_l, inorder_h, inorder_map):\n if ind[0] == len(preorder):\n return None\n val = preorder[ind[0]]\n inorder_i = inorder_map[val]\n if inorder_i < inorder_l or inorder_i > inorder_h:\n return None\n cur = Node(val)\n ind[0] += 1\n cur.left = build(preorder, ind, inorder_l, inorder_i - 1, inorder_map)\n cur.right = build(preorder, ind, inorder_i + 1, inorder_h, inorder_map)\n return cur\n\ndef check_same(cur, postorder, ind, res):\n if not cur:\n return\n check_same(cur.left, postorder, ind, res)\n check_same(cur.right, postorder, ind, res)\n if ind[0] == len(postorder):\n res[0] = False\n return\n val = postorder[ind[0]]\n ind[0] += 1\n if cur.data != val:\n res[0] = False\n return\n return True\n\ndef __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef checktree(preorder, inorder, postorder, N):\n inorder_map = {inorder[i]: i for i in range(len(inorder))}\n ind = [0]\n root = build(preorder, ind, 0, len(inorder) - 1, inorder_map)\n res = [True]\n ind = [0]\n check_same(root, postorder, ind, res)\n traverse_to_end = ind[0] == len(postorder)\n return res[0] and traverse_to_end", "def __init__(data):\n self.data = data\n self.left = None\n self.right = None\n\ndef checktree(preorder, inorder, postorder, N):\n flag = [False]\n\n def rec1(a, b):\n if flag[0]:\n return None\n if not a:\n return None\n ele = b.pop(0)\n if ele not in a:\n flag[0] = True\n return None\n ind = a.index(ele)\n node = Tree(ele)\n node.left = rec1(a[:ind], b)\n node.right = rec1(a[ind + 1:], b)\n return node\n\n def rec2(a, b):\n if flag[0]:\n return None\n if not a:\n return None\n ele = b.pop(0)\n if ele not in a:\n flag[0] = True\n return None\n ind = a.index(ele)\n node = Tree(ele)\n node.right = rec2(a[ind + 1:], b)\n node.left = rec2(a[:ind], b)\n return node\n root1 = rec1(inorder, preorder)\n root2 = rec2(inorder, postorder[::-1])\n\n def identicalTrees(a, b):\n if a is None and b is None:\n return True\n if a is not None and b is not None:\n return a.data == b.data and identicalTrees(a.left, b.left) and identicalTrees(a.right, b.right)\n return False\n if identicalTrees(root1, root2) and (not flag[0]):\n return True\n return False"], "starter_code": "def checktree(preorder, inorder, postorder, N):\n", "input_output": {"inputs": ["N = 5\npreorder[] = {1, 2, 4, 5, 3}\ninorder[] = {4, 2, 5, 1, 3}\npostorder[] = {4, 5, 2, 3, 1}", "N = 5\npreorder[] = {1, 5, 4, 2, 3}\ninorder[] = {4, 2, 5, 1, 3}\npostorder[] = {4, 1, 2, 3, 5}"], "outputs": ["Yes", "No"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Recursion", "Algorithms", "Tree", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/cb02d40f50b0113c47cd9036e5f340bb51b32289/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N^{2})", "entry_point": "checktree", "task_id": "TACO_lite/94", "example": [[], []]} +{"requirement": "# Task\n You are given three integers `l, d and x`. Your task is:\n```\n• determine the minimal integer n \n such that l ≤ n ≤ d, and the sum of its digits equals x.\n• determine the maximal integer m \n such that l ≤ m ≤ d, and the sum of its digits equals x.\n```\nIt is guaranteed that such numbers always exist.\n\n# Input/Output\n\n\n - `[input]` integer `l`\n\n - `[input]` integer `d`\n\n `1 ≤ l ≤ d ≤ 10000.`\n\n\n - `[input]` integer `x`\n\n `1 ≤ x ≤ 36`\n\n\n - `[output]` an integer array\n\n Array of two elements, where the first element is `n`, and the second one is `m`.\n\n\n# Example\n\n For `l = 500, d = 505, x = 10`, the output should be `[505, 505]`.\n \n For `l = 100, d = 200, x = 10`, the output should be `[109, 190]`.", "solutions": ["def min_and_max(l, d, x):\n listOfCorect = [num for num in list(range(l, d + 1)) if sum(map(int, str(num))) == x]\n return [min(listOfCorect), max(listOfCorect)]", "def min_and_max(l, d, x):\n for n in range(l, d + 1):\n if sum(map(int, str(n))) == x:\n break\n for m in range(d, l - 1, -1):\n if sum(map(int, str(m))) == x:\n break\n return [n, m]", "def min_and_max(l, d, x):\n return [next((i for i in range(l, d + 1) if sum((int(n) for n in str(i))) == x)), next((i for i in range(d, l - 1, -1) if sum((int(n) for n in str(i))) == x))]", "def min_and_max(l, d, x):\n\n def min_or_max(l, d, x, end, step):\n return next((i for i in range(l, d + end, step) if sum(map(int, list(str(i)))) == x))\n return [min_or_max(l, d, x, 1, 1), min_or_max(d, l, x, 0, -1)]", "func = lambda n: sum(map(int, str(n)))\n\ndef min_and_max(l, d, x):\n while func(l) != x:\n l += 1\n while func(d) != x:\n d -= 1\n return [l, d]", "from operator import itemgetter\n\ndef min_and_max(l, d, x):\n return list(itemgetter(0, -1)([i for i in range(l, d + 1) if sum(map(int, list(str(i)))) == x]))", "def min_and_max(l, d, x):\n arr = [i for i in range(l, d + 1) if sum(map(int, str(i))) == x]\n return [arr[0], arr[-1]]", "def min_and_max(l, d, x):\n d_sum = lambda n: sum(map(int, str(n)))\n min = next((i for i in range(l, d + 1) if d_sum(i) == x))\n max = next((i for i in range(d, l - 1, -1) if d_sum(i) == x))\n return [min, max]"], "starter_code": "def min_and_max(l, d, x):\n", "input_output": {"fn_name": "min_and_max", "inputs": [[100, 200, 10], [123, 456, 5], [99, 501, 5], [99, 234, 1], [99, 234, 19], [99, 5001, 27], [99, 5001, 28], [2000, 7000, 3]], "outputs": [[[109, 190]], [[131, 410]], [[104, 500]], [[100, 100]], [[199, 199]], [[999, 4995]], [[1999, 4996]], [[2001, 3000]]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/58fd52b59a9f65c398000096", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "min_and_max", "task_id": "TACO_lite/114", "example": [[[500, 505, 10], [100, 200, 10]], ["[505, 505]", "[109, 190]"]]} +{"requirement": "Write a function that takes an array/list of numbers and returns a number such that \n\nExplanation\ntotal([1,2,3,4,5]) => 48\n\n1+2=3--\\ 3+5 => 8 \\\n2+3=5--/ \\ == 8+12=>20\\ \n ==>5+7=> 12 / \\ 20+28 => 48\n3+4=7--\\ / == 12+16=>28/\n4+5=9--/ 7+9 => 16 /\n\n\nif total([1,2,3]) => 8 then \n\n\nfirst+second => 3 \\\n then 3+5 => 8\nsecond+third => 5 /\n\n\n### Examples\n```python\ntotal([-1,-1,-1]) => -4\ntotal([1,2,3,4]) => 20\n```\n\n**Note:** each array/list will have at least an element and all elements will be valid numbers.", "solutions": ["def total(arr):\n while len(arr) > 1:\n arr = [x + y for (x, y) in zip(arr, arr[1:])]\n return arr[0]", "def total(arr):\n from math import factorial as fact\n choose = lambda a, b: fact(a) / (fact(a - b) * fact(b))\n return sum((choose(len(arr) - 1, i) * v for (i, v) in enumerate(arr)))", "def total(xs):\n return xs[0] if len(xs) == 1 else total([xs[i] + x for (i, x) in enumerate(xs[1:])])", "def total(arr):\n if len(arr) == 1:\n return arr[0]\n arr2 = []\n for i in range(len(arr) - 1):\n arr2.append(arr[i] + arr[i + 1])\n return total(arr2)", "def total(arr):\n while len(arr) > 2:\n arr = [x + y for (x, y) in zip(arr, arr[1:])]\n return sum(arr)", "total = lambda a: a[0] if len(a) == 1 else total([a[i] + a[i + 1] for i in range(len(a) - 1)])", "from math import factorial as fac\n\ndef C(n, k):\n return fac(n) // (fac(k) * fac(n - k))\n\ndef total(arr):\n l = len(arr)\n return sum((arr[i] * C(l - 1, i) for i in range(l)))", "def total(arr):\n a = arr[:]\n for i in range(len(a), 1, -1):\n for j in range(1, i):\n a[j - 1] += a[j]\n return a[0]"], "starter_code": "def total(arr):\n", "input_output": {"fn_name": "total", "inputs": [[[1, 2, 3, 4, 5]], [[1, 2, 3, 4]], [[1, 2, 3]], [[4, 4, 52, 23, 32, 1, -1]], [[4, 4, 5, -1]], [[-1, -1, -1]], [[-1, -1, -10, 42, 92, 1, 23, 6, -3]], [[-1, 1, -1, 1]], [[42]]], "outputs": [[48], [20], [8], [1753], [30], [-4], [9248], [0], [42]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Lists", "Fundamentals", "Logic", "Arrays"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/559fed8454b12433ff0000a2", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "total", "task_id": "TACO_lite/9", "example": [[[[1, 2, 3, 4, 5]], [[-1, -1, -1]], [[1, 2, 3, 4]]], ["48", "-4", "20"]]} +{"requirement": "You are given the prices of stock for n number of days. every ith day tell the price of the stock on that day.find the maximum profit that you can make by buying and selling stock any number of times as you can't proceed with other transactions if you hold any transaction.\nExample:\nInput:\nn = 7\nprices = [1,2,3,4,5,6,7]\nOutput:\n6\nExplaination:\nWe can make the maximum profit by buying the stock on the first day and selling it on the last day.\nYour Task:\nYou don't have to read input or print anything. Your task is to complete the function maximizeProfit() which takes the integer n and array prices and returns the maximum profit that can earn.\nExpected Time Complexity: O(n)\nExpected Space Complexity: O(n^{2})\nNOTE: can you solve this in less space complexity?\nConstraint:\n1<=n<=10^{5}\n1<=prices[i]<=10^{5}", "solutions": ["def maximumprofit(prices, n):\n n = len(prices)\n curr = [0 for i in range(2)]\n nex = [0 for i in range(2)]\n profit = 0\n for ind in range(n - 1, -1, -1):\n for buy in range(0, 2):\n if buy:\n buynow = -prices[ind] + nex[0]\n notbuy = 0 + nex[1]\n profit = max(buynow, notbuy)\n else:\n sellnow = prices[ind] + nex[1]\n notsell = 0 + nex[0]\n profit = max(sellnow, notsell)\n curr[buy] = profit\n nex = curr\n return nex[1]", "def maximumprofit(prices, n):\n ans = 0\n prev = 0\n for i in range(1, n):\n if prices[i] > prices[prev]:\n ans += prices[i] - prices[prev]\n prev = i\n return ans", "def maximumprofit(prices, n):\n Max = 0\n for i in range(1, len(prices)):\n if prices[i] > prices[i - 1]:\n Max += prices[i] - prices[i - 1]\n return Max", "def maximumprofit(prices, n):\n profit = 0\n for i in range(n - 1):\n x = prices[i + 1] - prices[i]\n if x < 0:\n continue\n profit += x\n if profit < 0:\n return 0\n return profit", "def maximumprofit(prices, n):\n dp = [[-1 for i in range(2)] for j in range(n + 1)]\n dp[n][0] = dp[n][1] = 0\n for ind in range(n - 1, -1, -1):\n for buy in range(2):\n if buy:\n profit = max(-prices[ind] + dp[ind + 1][0], dp[ind + 1][1])\n else:\n profit = max(prices[ind] + dp[ind + 1][1], dp[ind + 1][0])\n dp[ind][buy] = profit\n return dp[0][1]", "def maximumprofit(prices, n):\n prev = [-1 for i in range(2)]\n for i in range(1, -1, -1):\n prev[i] = 0\n for ind in range(n - 1, -1, -1):\n temp = [-1 for i in range(2)]\n for buy in range(1, -1, -1):\n if buy == 1:\n temp[buy] = max(-prices[ind] + prev[0], 0 + prev[1])\n else:\n temp[buy] = max(prices[ind] + prev[1], 0 + prev[0])\n prev = temp\n return prev[1]", "def maximumprofit(A, n):\n i = 0\n ans = 0\n while i < n:\n while i + 1 < n and A[i] >= A[i + 1]:\n i += 1\n l = A[i]\n while i + 1 < n and A[i] <= A[i + 1]:\n i += 1\n r = A[i]\n if l == r:\n return ans\n ans += r - l\n i += 1\n return ans", "def maximumprofit(prices, n):\n minm = prices[0]\n profit = 0\n for i in range(1, n):\n if prices[i] > minm:\n profit += prices[i] - minm\n minm = prices[i]\n else:\n minm = prices[i]\n return profit", "def maximumprofit(prices, n):\n n = len(prices)\n dp = [[0 for _ in range(3)] for _ in range(n + 1)]\n for i in range(n - 1, -1, -1):\n for buy in range(2):\n if buy == 1:\n dp[i][buy] = max(-prices[i] + dp[i + 1][0], dp[i + 1][1])\n else:\n dp[i][buy] = max(prices[i] + dp[i + 1][1], dp[i + 1][0])\n return dp[0][1]", "def maximumprofit(prices, n):\n (profit, A) = (0, prices)\n for i in range(n - 1):\n if A[i + 1] > A[i]:\n profit += A[i + 1] - A[i]\n return profit", "def maximumprofit(prices, n):\n dp = [[0 for i in range(2)] for i in range(n + 1)]\n ans = 0\n for j in range(1, len(prices)):\n if prices[j - 1] < prices[j]:\n ans += prices[j] - prices[j - 1]\n return ans", "def maximumprofit(prices, n):\n max_profit = 0\n for i in range(1, n):\n if prices[i] > prices[i - 1]:\n max_profit += prices[i] - prices[i - 1]\n return max_profit", "def maximumprofit(prices, n):\n after = [0 for i in range(2)]\n for i in range(2):\n after[i] = 0\n for ind in range(n - 1, -1, -1):\n curr = [0 for i in range(2)]\n curr[1] = max(-prices[ind] + after[0], after[1])\n curr[0] = max(prices[ind] + after[1], after[0])\n after = curr\n return after[1]", "def maximumprofit(arr, n):\n dp = [[0 for i in range(2)] for j in range(n + 1)]\n dp[n][0] = 0\n dp[n][1] = 0\n for idx in range(n - 1, -1, -1):\n for buy in range(2):\n profit = 0\n if buy:\n p = -arr[idx] + dp[idx + 1][0]\n np = 0 + dp[idx + 1][1]\n profit = max(profit, max(p, np))\n else:\n s = arr[idx] + dp[idx + 1][1]\n ns = 0 + dp[idx + 1][0]\n profit = max(profit, max(s, ns))\n dp[idx][buy] = profit\n return dp[0][1]", "def maximumprofit(prices, n):\n profit = 0\n i = 1\n while i < n:\n buy = i - 1\n while i < n and prices[i] > prices[i - 1]:\n i += 1\n sell = i - 1\n profit += prices[sell] - prices[buy]\n i += 1\n return profit", "def maximumprofit(prices, n):\n dp = [[0] * 2 for _ in range(n + 1)]\n profit = 0\n for i in range(n - 1, -1, -1):\n for j in range(2):\n if j == 0:\n profit = max(dp[i + 1][0], dp[i + 1][1] - prices[i])\n if j == 1:\n profit = max(dp[i + 1][1], dp[i + 1][0] + prices[i])\n dp[i][j] = profit\n return dp[0][0]", "def maximumprofit(arr, n):\n i = 0\n final_ans = []\n while i < n - 1:\n if arr[i] <= arr[i + 1]:\n ans = []\n ans.append(arr[i])\n while i < n - 1 and arr[i] <= arr[i + 1]:\n i += 1\n ans.append(arr[i])\n final_ans.append(ans)\n else:\n i += 1\n answer = 0\n for res in final_ans:\n answer = answer + (res[1] - res[0])\n return answer", "def maximumprofit(prices, n):\n ans = 0\n for i in range(1, n):\n ans += max(0, prices[i] - prices[i - 1])\n return ans", "def maximumprofit(prices, n):\n n = len(prices)\n dp = [[0] * 2 for i in range(n + 1)]\n dp[n][0] = dp[n][1] = 0\n for idx in range(n - 1, -1, -1):\n for buy in range(0, 2):\n profit = 0\n if buy:\n profit = max(-prices[idx] + dp[idx + 1][0], 0 + dp[idx + 1][1])\n else:\n profit = max(prices[idx] + dp[idx + 1][1], 0 + dp[idx + 1][0])\n dp[idx][buy] = profit\n return dp[0][1]", "def maximumprofit(A, n):\n ahead = [0, 0]\n curr = [0, 0]\n ahead[0] = ahead[1] = 0\n for ind in range(n - 1, -1, -1):\n for buy in range(2):\n if buy:\n take = -A[ind] + ahead[0]\n noTake = 0 + ahead[1]\n curr[buy] = max(take, noTake)\n else:\n take = A[ind] + ahead[1]\n noTake = 0 + ahead[0]\n curr[buy] = max(take, noTake)\n ahead = curr\n return ahead[1]", "def maximumprofit(A, n):\n dp = [[0 for _ in range(2)] for _ in range(n + 1)]\n (dp[n][0], dp[n][1]) = (0, 0)\n for ind in range(n - 1, -1, -1):\n for buy in range(2):\n if buy:\n take = -A[ind] + dp[ind + 1][0]\n noTake = 0 + dp[ind + 1][1]\n dp[ind][buy] = max(take, noTake)\n else:\n take = A[ind] + dp[ind + 1][1]\n noTake = 0 + dp[ind + 1][0]\n dp[ind][buy] = max(take, noTake)\n return dp[0][1]", "import sys\nsys.setrecursionlimit(10 ** 8)\nmod = 10 ** 9\n\ndef maximumprofit(arr, n):\n dp = [[0 for j in range(0, 2)] for i in range(0, n + 1)]\n dp[n][0] = 0\n dp[n][1] = 0\n for i in range(n - 1, -1, -1):\n for j in range(0, 2):\n profit = 0\n if j == 0:\n buy = -arr[i] + dp[i + 1][1]\n notbuy = dp[i + 1][0]\n profit = max(buy, notbuy)\n elif j == 1:\n sell = arr[i] + dp[i + 1][0]\n notsell = dp[i + 1][1]\n profit = max(sell, notsell)\n dp[i][j] = profit\n return dp[0][0]", "def maximumprofit(arr, n):\n (l, r) = (0, 1)\n total = 0\n prev = 0\n while r < n:\n curr = arr[r] - arr[l]\n if curr > prev:\n prev = curr\n if r == n - 1:\n total += prev\n elif curr < prev:\n total += prev\n prev = 0\n l = r\n r += 1\n return total", "def maximumprofit(prices, n):\n ahead = [0] * 2\n ahead[0] = 0\n ahead[1] = 0\n for ind in range(n - 1, -1, -1):\n cur = [0] * 2\n for buy in range(2):\n if buy:\n profit = max(-1 * prices[ind] + ahead[0], ahead[1])\n else:\n profit = max(prices[ind] + ahead[1], ahead[0])\n cur[buy] = profit\n ahead = cur\n return ahead[1]", "import sys\n\ndef maximumprofit(prices, n):\n minI = 0\n res = []\n for i in range(n):\n if i == n - 1 or (i < n - 1 and prices[i] > prices[i + 1]):\n if i != minI:\n res.append([minI, i])\n minI = i + 1\n prof = 0\n for p in res:\n prof += prices[p[1]] - prices[p[0]]\n return prof", "def maximumprofit(prices, n):\n total_profit = 0\n buy = 0\n sell = 0\n for i in range(1, n):\n if prices[i] >= prices[i - 1]:\n sell += 1\n else:\n total_profit += prices[sell] - prices[buy]\n buy = i\n sell = i\n total_profit += prices[sell] - prices[buy]\n return total_profit"], "starter_code": "def maximumprofit(prices, n):\n", "input_output": {"inputs": ["n = 7\nprices = [1,2,3,4,5,6,7]"], "outputs": ["6"]}, "difficulty": "MEDIUM", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/buy-stock-2/1", "Expected Auxiliary Space": "O(n^{2})", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "maximumprofit", "task_id": "TACO_lite/4", "example": [[[7, [1, 2, 3, 4, 5, 6, 7]]], ["6"]]} +{"requirement": "A grid is a perfect starting point for many games (Chess, battleships, Candy Crush!).\n\nMaking a digital chessboard I think is an interesting way of visualising how loops can work together.\n\nYour task is to write a function that takes two integers `rows` and `columns` and returns a chessboard pattern as a two dimensional array.\n\nSo `chessBoard(6,4)` should return an array like this:\n\n\n [\n [\"O\",\"X\",\"O\",\"X\"],\n [\"X\",\"O\",\"X\",\"O\"],\n [\"O\",\"X\",\"O\",\"X\"],\n [\"X\",\"O\",\"X\",\"O\"],\n [\"O\",\"X\",\"O\",\"X\"],\n [\"X\",\"O\",\"X\",\"O\"]\n ]\n\nAnd `chessBoard(3,7)` should return this:\n\n\n [\n [\"O\",\"X\",\"O\",\"X\",\"O\",\"X\",\"O\"],\n [\"X\",\"O\",\"X\",\"O\",\"X\",\"O\",\"X\"],\n [\"O\",\"X\",\"O\",\"X\",\"O\",\"X\",\"O\"]\n ]\n\nThe white spaces should be represented by an: `'O'`\n\nand the black an: `'X'`\n\nThe first row should always start with a white space `'O'`", "solutions": ["def chess_board(rows, columns):\n return [['OX'[(row + col) % 2] for col in range(columns)] for row in range(rows)]", "def chess_board(rows, columns):\n ans = []\n for i in range(1, rows + 1, 1):\n l = []\n for j in range(i, columns + i, 1):\n if j % 2 != 0:\n l.append('O')\n else:\n l.append('X')\n ans.append(l)\n return ans", "chess_board = lambda rows, cols: [['X' if (y + x) % 2 else 'O' for x in range(cols)] for y in range(rows)]", "chess_board = lambda r, c: [['OX'[i + j & 1] for i in range(c)] for j in range(r)]", "def chess_board(rows, columns):\n board = []\n for row in range(rows):\n if row % 2:\n board.append(['X' if not column % 2 else 'O' for column in range(columns)])\n else:\n board.append(['O' if not column % 2 else 'X' for column in range(columns)])\n return board", "def chess_board(a, b):\n return [list('OXXO'[i % 2::2] * (b // 2 + 1))[:b] for i in range(a)]", "from itertools import cycle\n\ndef chess_board(rows, columns):\n result = []\n for i in range(rows):\n grida = cycle(['O', 'X'])\n gridb = cycle(['X', 'O'])\n result.append([next(gridb) if i % 2 else next(grida) for x in range(columns)])\n return result", "def chess_board(rows, columns):\n return [['OX'[(row + column) % 2] for column in range(columns)] for row in range(rows)]", "def chess_board(rows, columns):\n line = ['X', 'O'] * columns\n return [line[:columns] if r % 2 else line[1:columns + 1] for r in range(rows)]", "chess_board = lambda r, c: [['OX'[(i + j) % 2] for j in range(c)] for i in range(r)]"], "starter_code": "def chess_board(rows, columns):\n", "input_output": {"fn_name": "chess_board", "inputs": [[1, 1], [1, 2], [2, 1], [2, 2], [6, 6]], "outputs": [[[["O"]]], [[["O", "X"]]], [[["O"], ["X"]]], [[["O", "X"], ["X", "O"]]], [[["O", "X", "O", "X", "O", "X"], ["X", "O", "X", "O", "X", "O"], ["O", "X", "O", "X", "O", "X"], ["X", "O", "X", "O", "X", "O"], ["O", "X", "O", "X", "O", "X"], ["X", "O", "X", "O", "X", "O"]]]]}, "difficulty": "EASY", "raw_tags": ["ASCII Art", "Algorithms", "Fundamentals", "Puzzles"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/56242b89689c35449b000059", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "chess_board", "task_id": "TACO_lite/31", "example": [[[6, 4], [3, 7]], ["[['O', 'X', 'O', 'X'], ['X', 'O', 'X', 'O'], ['O', 'X', 'O', 'X'], ['X', 'O', 'X', 'O'], ['O', 'X', 'O', 'X'], ['X', 'O', 'X', 'O']]", "[['O', 'X', 'O', 'X', 'O', 'X', 'O'], ['X', 'O', 'X', 'O', 'X', 'O', 'X'], ['O', 'X', 'O', 'X', 'O', 'X', 'O']]"]]} +{"requirement": "Given an array of integers nums, write a method that returns the \"pivot\" index of this array.\n\nWe 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.\n\nIf no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.\n\n\nExample 1:\n\nInput: \nnums = [1, 7, 3, 6, 5, 6]\nOutput: 3\nExplanation: \nThe sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.\nAlso, 3 is the first index where this occurs.\n\n\n\nExample 2:\n\nInput: \nnums = [1, 2, 3]\nOutput: -1\nExplanation: \nThere is no index that satisfies the conditions in the problem statement.\n\n\n\nNote:\nThe length of nums will be in the range [0, 10000].\nEach element nums[i] will be an integer in the range [-1000, 1000].", "solutions": ["def pivotindex(nums):\n (left, right) = (0, sum(nums))\n for (index, num) in enumerate(nums):\n right -= num\n if left == right:\n return index\n left += num\n return -1", "def pivotindex(nums):\n if len(nums) == 0:\n return -1\n leftSum = sum(nums)\n rightSum = 0\n for i in range(len(nums)):\n leftSum = leftSum - nums[i]\n if rightSum == leftSum:\n return i\n rightSum = rightSum + nums[i]\n return -1", "def pivotindex(nums):\n ret = sum(nums)\n left = 0\n for (k, v) in enumerate(nums):\n if left * 2 + v == ret:\n return k\n left += v\n return -1", "def pivotindex(nums):\n left_sum = 0\n right_sum = sum(nums)\n for index in range(0, len(nums)):\n right_sum -= nums[index]\n if left_sum == right_sum:\n return index\n left_sum += nums[index]\n return -1", "def pivotindex(nums):\n n = sum(nums)\n sum_num = n\n for i in range(len(nums)):\n n -= nums[i]\n if (sum_num - nums[i]) / 2 == n:\n return i\n return -1", "def pivotindex(nums):\n if len(nums) == 0:\n return -1\n if len(nums) == 1:\n return nums[0]\n left = 0\n right = 0\n for i in range(1, len(nums)):\n right += nums[i]\n if left == right:\n return 0\n for i in range(1, len(nums)):\n left += nums[i - 1]\n right -= nums[i]\n if left == right:\n return i\n return -1", "def pivotindex(nums):\n if nums == []:\n return -1\n sum = 0\n for i in range(len(nums)):\n sum += nums[i]\n if nums[0] == sum:\n return 0\n left_sum = 0\n for i in range(len(nums) - 1):\n left_sum += nums[i]\n if left_sum * 2 == sum - nums[i + 1]:\n return i + 1\n if nums[len(nums) - 1] == sum:\n return len(nums) - 1\n return -1", "def pivotindex(nums):\n l = len(nums)\n if l < 3:\n return -1\n s = [0] * l\n s[0] = nums[0]\n for i in range(1, l):\n s[i] = s[i - 1] + nums[i]\n d = [0] * l\n d[l - 1] = nums[l - 1]\n for j in range(l - 2, -1, -1):\n d[j] = d[j + 1] + nums[j]\n for i in range(0, l):\n if s[i] == d[i]:\n return i\n return -1"], "starter_code": "def pivotindex(nums: List[int]) -> int:\n", "input_output": {"fn_name": "pivotIndex", "inputs": [[[1, 7, 3, 6, 5, 6]]], "outputs": [3]}, "difficulty": "EASY", "raw_tags": ["Prefix Sum", "Array"], "name": null, "source": "leetcode", "tags": ["Data structures", "Range queries"], "skill_types": ["Data structures", "Range queries"], "url": "https://leetcode.com/problems/find-pivot-index/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "pivotindex", "task_id": "TACO_lite/36", "example": [[[[1, 7, 3, 6, 5, 6]], [[1, 2, 3]]], ["3", "-1"]]} +{"requirement": "You have n  tiles, where each tile has one letter tiles[i] printed on it.\nReturn the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.\n \nExample 1:\nInput: tiles = \"AAB\"\nOutput: 8\nExplanation: The possible sequences are \"A\", \"B\", \"AA\", \"AB\", \"BA\", \"AAB\", \"ABA\", \"BAA\".\n\nExample 2:\nInput: tiles = \"AAABBC\"\nOutput: 188\n\nExample 3:\nInput: tiles = \"V\"\nOutput: 1\n\n \nConstraints:\n\n1 <= tiles.length <= 7\ntiles consists of uppercase English letters.", "solutions": ["def numtilepossibilities(tiles: str) -> int:\n res = 0\n freqs = [f + 1 for f in Counter(tiles).values()]\n for t in itertools.product(*map(range, freqs)):\n n = sum(t)\n subtotal = math.factorial(n)\n for freq in t:\n subtotal //= math.factorial(freq)\n res += subtotal\n return res - 1", "def numtilepossibilities(tiles: str) -> int:\n return len(set((x for i in range(1, len(tiles) + 1) for x in itertools.permutations(tiles, i))))", "def numtilepossibilities(tiles: str) -> int:\n\n def freq(tiles):\n d = {}\n for c in tiles:\n if c in d:\n d[c] += 1\n else:\n d[c] = 1\n return d\n\n def build(d, s):\n new_d = {}\n for (key, value) in d.items():\n if key == s:\n new_d[key] = value - 1\n else:\n new_d[key] = value\n return new_d\n\n def generate(options):\n sol = []\n for (key, value) in options.items():\n if value > 0:\n sol.append(key)\n fringe = generate(build(options, key))\n sol += fringe\n sol += [key + f for f in fringe]\n return sol\n return len(set(generate(freq(tiles))))", "def numtilepossibilities(tiles: str) -> int:\n\n def find(s):\n if len(s) <= 1:\n return set([s])\n ret = set()\n for i in range(len(s)):\n head = s[i]\n tails = find(s[:i] + s[i + 1:])\n ret = ret.union(tails)\n for tail in tails:\n for j in range(len(tail) + 1):\n temp = tail[:j] + head + tail[j:]\n ret.add(temp)\n return ret\n res = find(tiles)\n return len(set(res))", "from collections import Counter\n\ndef numtilepossibilities(tiles: str) -> int:\n (c_all, visited) = (Counter(tiles), set())\n stack = [(x, Counter([x])) for x in c_all]\n while stack:\n (element, c) = stack.pop()\n if element not in visited:\n stack.extend([(element + x, c + Counter([x])) for x in c_all - c])\n visited.add(element)\n return len(visited)", "def numtilepossibilities(tiles: str) -> int:\n pos = set()\n\n def choose(s, n, pref=''):\n if n == 0:\n pos.add(pref)\n for i in range(len(s)):\n choose(s[:i] + s[i + 1:], n - 1, pref + s[i])\n for i in range(1, len(tiles) + 1):\n choose(tiles, i)\n return len(pos)", "def numtilepossibilities(tiles: str) -> int:\n words = set()\n curr = ''\n tile_count = {}\n for x in tiles:\n if x not in tile_count:\n tile_count[x] = 0\n tile_count[x] += 1\n\n def walk(curr, tiles, words):\n for tile in tiles:\n if tiles[tile] > 0:\n temp = curr + tile\n temp_tiles = tiles.copy()\n temp_tiles[tile] -= 1\n words.add(temp)\n walk(temp, temp_tiles, words)\n for tile in tile_count:\n walk('', tile_count, words)\n return len(words)", "def __init__():\n self.total = 0\n self.string = []\n self.dict_ = {}\n self.arr = []\n self.n = 0\n\ndef perm():\n if self.n == len(self.string):\n self.total += 1\n for i in range(len(self.arr)):\n if self.arr[i][1] > 0:\n self.arr[i][1] -= 1\n self.string.append(self.arr[i][0])\n self.perm()\n self.string.pop()\n self.arr[i][1] += 1\n\ndef numtilepossibilities(tiles: str) -> int:\n for string in tiles:\n if string in self.dict_:\n self.dict_[string] += 1\n else:\n self.dict_[string] = 1\n for key in self.dict_:\n temp = [key, self.dict_[key]]\n self.arr.append(temp)\n for i in range(1, len(tiles) + 1):\n self.n = i\n self.perm()\n return self.total", "def numtilepossibilities(tiles: str) -> int:\n combination_set = self.generateTilePossibilities(tiles)\n return len(combination_set)\n\ndef generateTilePossibilities(tiles: str):\n n = len(tiles)\n combination_set = set()\n for index in range(n):\n combination_set.add(tiles[index])\n if n > 1:\n for index in range(n):\n tiles_without_n = tiles[0:index] + tiles[index + 1:]\n additional_combinations = self.generateTilePossibilities(tiles_without_n)\n combination_set.add(tiles_without_n)\n for combination in additional_combinations:\n combination_set.add(combination)\n for second_index in range(len(combination)):\n new_tile_combination = combination[0:second_index] + tiles[index] + combination[second_index:]\n combination_set.add(new_tile_combination)\n return combination_set", "def numtilepossibilities(tiles: str) -> int:\n\n def count(tiles):\n counter = set()\n if len(tiles) == 1:\n counter.add(tiles)\n elif len(tiles) == 2:\n counter.add(tiles)\n counter.add(tiles[::-1])\n counter.add(tiles[0])\n counter.add(tiles[1])\n else:\n for (idx, i) in enumerate(tiles):\n x = count(tiles[:idx] + tiles[idx + 1:])\n extra = set()\n for j in x:\n extra.add(tiles[idx] + j)\n extra.add(j + tiles[idx])\n for k in range(1, len(j) - 1):\n extra.add(j[:k] + tiles[idx] + j[k + 1:])\n x.update(extra)\n counter.update(x)\n return counter\n return len(count(tiles))", "def __init__():\n self.seen = set()\n self.result = set()\n\ndef numtilepossibilities(tiles: str) -> int:\n self.dfs(tiles, 0, [])\n return len(self.result) - 1\n\ndef dfs(string, idx, path):\n st = ''.join(path)\n if st not in self.seen:\n self.result.update((''.join(p) for p in permutations(st)))\n self.seen.add(st)\n for i in range(idx, len(string)):\n self.dfs(string, i + 1, path + [string[i]])", "def numtilepossibilities(tiles: str) -> int:\n d = {}\n for i in range(len(tiles)):\n if tiles[i] in d:\n d[tiles[i]] += 1\n else:\n d[tiles[i]] = 1\n\n def countnum(d):\n if d == {}:\n return 0\n c = 0\n s = set(d.items())\n for (k, v) in s:\n d[k] -= 1\n if d[k] == 0:\n del d[k]\n c += 1 + countnum(d)\n if k in d:\n d[k] += 1\n else:\n d[k] = 1\n return c\n return countnum(d)", "def numtilepossibilities(tiles: str) -> int:\n res = set()\n\n def dfs(path, t):\n if path not in res:\n if path:\n res.add(path)\n for i in range(len(t)):\n dfs(path + t[i], t[:i] + t[i + 1:])\n dfs('', tiles)\n return len(res)", "def numtilepossibilities(tiles: str) -> int:\n res = set()\n\n def backtrack(path, curr):\n if path not in res:\n if path:\n res.add(path)\n for i in range(len(curr)):\n backtrack(path + curr[i], curr[:i] + curr[i + 1:])\n backtrack('', tiles)\n return len(res)", "def numtilepossibilities(tiles: str) -> int:\n result = set()\n maxx = len(tiles)\n\n def dfs(result, tiles, current_sequence=''):\n result.add(current_sequence)\n for t in tiles:\n tiles_c = tiles.replace(t, '', 1)\n dfs(result, tiles_c, current_sequence + t)\n dfs(result, tiles)\n return len(result) - 1", "def numtilepossibilities(tiles: str) -> int:\n setter = set()\n res = []\n for r in range(1, len(tiles) + 1):\n res.append(list(itertools.permutations(tiles, r)))\n result = []\n for re in res:\n result.append(list(set(re)))\n leng = 0\n for i in result:\n leng += len(i)\n return leng", "def numtilepossibilities(tiles: str) -> int:\n tile_counts = collections.Counter(tiles)\n len_counts = [1] + [0] * len(tiles)\n for tile in tile_counts:\n new_len_counts = [0] * (len(tiles) + 1)\n num_tiles = tile_counts[tile]\n for num_inserted in range(num_tiles + 1):\n for (old_len, old_len_count) in enumerate(len_counts):\n new_len = old_len + num_inserted\n if new_len > len(tiles):\n break\n num_patterns = math.comb(new_len, num_inserted)\n new_len_counts[new_len] += old_len_count * num_patterns\n len_counts = new_len_counts\n return sum(len_counts) - 1", "def buildString(currString, count, op):\n flag = True\n for i in count:\n if count[i] != 0:\n flag = False\n break\n if flag:\n return\n for ch in count:\n if count[ch] == 0:\n continue\n tempString = currString\n tempString += ch\n op.add(tempString)\n count[ch] -= 1\n tempCount = count.copy()\n buildString(tempString, tempCount, op)\n count[ch] += 1\n\ndef numtilepossibilities(tiles: str) -> int:\n count = {}\n for i in tiles:\n if i not in count:\n count[i] = 0\n count[i] += 1\n op = set()\n for ch in count:\n tempString = ch\n op.add(tempString)\n count[ch] -= 1\n tempCount = count.copy()\n buildString(tempString, tempCount, op)\n count[ch] += 1\n return len(op)", "def numtilepossibilities(tiles: str) -> int:\n\n def dfs(state):\n res.append(state.copy())\n for i in range(len(state)):\n if state[i] < full_state[i]:\n state[i] += 1\n dfs(state)\n state[i] -= 1\n memo = collections.Counter(tiles)\n full_state = list(memo.values())\n state = [0 for _ in range(len(memo))]\n res = []\n dfs(state)\n return len(res) - 1", "def numtilepossibilities(tiles: str) -> int:\n res = {}\n\n def dfs(seq, tiles):\n if seq not in res and seq != '':\n res[seq] = 1\n for i in range(len(tiles)):\n dfs(seq + tiles[i], tiles[:i] + tiles[i + 1:])\n dfs('', tiles)\n return len(res)", "def numtilepossibilities(tiles: str) -> int:\n\n def backtracking(idx=0, seq='', remaining=tiles):\n for (i, tile) in enumerate(remaining):\n res.add(seq + tile)\n backtracking(idx + 1, seq + tile, remaining[:i] + remaining[i + 1:])\n res = set()\n backtracking()\n return len(res)", "def numtilepossibilities(tiles: str) -> int:\n\n def dfs(elements):\n if prev_elements:\n result.add(''.join(prev_elements))\n for e in elements:\n next_elements = elements[:]\n next_elements.remove(e)\n prev_elements.append(e)\n dfs(next_elements)\n prev_elements.pop()\n result = set()\n prev_elements = []\n dfs(list(tiles))\n return len(result)", "def numtilepossibilities(tiles: str) -> int:\n seqs = set()\n visits = [False] * len(tiles)\n\n def dfs(seq: str, depth: int):\n if seq:\n seqs.add(seq)\n if depth == len(tiles) - 1:\n return\n for i in range(len(tiles)):\n if not visits[i]:\n visits[i] = True\n dfs(seq + tiles[i], depth + 1)\n visits[i] = False\n dfs('', -1)\n return len(seqs)", "def get_permute(opts, cur_sol):\n for i in range(len(opts)):\n c = opts[i]\n cur_sol.append(c)\n self.solutions.add(''.join(cur_sol))\n opts2 = opts\n opts2 = opts2[:i] + opts2[i + 1:]\n self.get_permute(opts2, cur_sol)\n cur_sol.pop()\n\ndef numtilepossibilities(tiles: str) -> int:\n self.solutions = set()\n self.get_permute(tiles, [])\n return len(self.solutions)", "import collections, math\n\ndef numtilepossibilities(tiles: str) -> int:\n freq = collections.Counter(tiles)\n prod = 1\n for f in freq.values():\n prod *= f + 1\n res = 0\n for i in range(1, prod):\n digits = []\n for f in freq.values():\n digits.append(i % (f + 1))\n i = i // (f + 1)\n tmp = math.factorial(sum(digits))\n for d in digits:\n tmp //= math.factorial(d)\n res += tmp\n return res", "def numtilepossibilities(tiles: str) -> int:\n result = set()\n vis = [0] * len(tiles)\n\n def dfs(res, depth):\n if res:\n result.add(res)\n if depth == len(tiles) - 1:\n result.add(res)\n for i in range(len(tiles)):\n if not vis[i]:\n vis[i] = 1\n dfs(res + tiles[i], depth + 1)\n vis[i] = 0\n dfs('', -1)\n return len(result)", "def numtilepossibilities(tiles: str) -> int:\n\n def solve(s, visited):\n seen.add(s)\n if len(s) == len(tiles):\n return 0\n for (i, v) in enumerate(tiles):\n if i not in visited:\n solve(s + v, visited | {i})\n return len(seen)\n seen = set()\n return solve('', set()) - 1", "def numtilepossibilities(tiles: str) -> int:\n result = set()\n\n def dfs_helper(path, t):\n if path:\n result.add(path)\n for i in range(len(t)):\n dfs_helper(path + t[i], t[:i] + t[i + 1:])\n dfs_helper('', tiles)\n return len(result)", "def numtilepossibilities(tiles: str) -> int:\n ans = 0\n s = set()\n\n def tot(curr, rem):\n nonlocal s\n if curr[-1]:\n s.add(tuple(curr[-1]))\n for i in range(len(rem)):\n el = curr[-1]\n if rem[i] == el:\n continue\n tot(curr + [el + [rem[i]]], rem[:i] + rem[i + 1:])\n tot([[]], tiles)\n return len(s)", "def subsets(tiles, buff, buff_index, boolean, s):\n if tuple(buff[:buff_index]) not in s:\n s.add(tuple(buff[:buff_index]))\n self.count += 1\n if len(buff) == buff_index:\n return\n for i in range(0, len(tiles)):\n if not boolean[i]:\n buff[buff_index] = tiles[i]\n boolean[i] = True\n self.subsets(tiles, buff, buff_index + 1, boolean, s)\n boolean[i] = False\n\ndef numtilepossibilities(tiles: str) -> int:\n self.count = 0\n buff = [None] * len(tiles)\n boolean = [False] * len(tiles)\n s = set()\n self.subsets(tiles, buff, 0, boolean, s)\n return self.count - 1", "def numtilepossibilities(tiles):\n res = set()\n\n def helper(t, curr, k):\n if k == len(curr):\n res.add(curr)\n return\n for i in range(len(t)):\n helper(t[:i] + t[i + 1:], curr + t[i], k)\n for i in range(1, len(tiles) + 1):\n helper(tiles, '', i)\n return len(res)", "def make_tile(curr, used, letters, size):\n if len(curr) == size:\n self.res += 1\n return\n i = 0\n while i < len(letters):\n if i not in used:\n used.add(i)\n curr.append(letters[i])\n self.make_tile(curr, used, letters, size)\n curr.pop(-1)\n used.remove(i)\n while i + 1 < len(letters) and letters[i] == letters[i + 1]:\n i += 1\n i += 1\n\ndef numtilepossibilities(tiles: str) -> int:\n self.res = 0\n letters = sorted(tiles)\n for size in range(1, len(tiles) + 1):\n self.make_tile([], set(), letters, size)\n return self.res", "def numtilepossibilities(tiles: str) -> int:\n\n def next_permutation(a):\n for i in range(len(a) - 1, 0, -1):\n if a[i] > a[i - 1]:\n ps = i\n for j in range(i + 1, len(a)):\n if a[j] > a[i - 1] and a[ps] > a[j]:\n ps = j\n (a[ps], a[i - 1]) = (a[i - 1], a[ps])\n p1 = i\n p2 = len(a) - 1\n while p1 < p2:\n (a[p1], a[p2]) = (a[p2], a[p1])\n p1 += 1\n p2 -= 1\n return True\n return False\n n = 1\n for i in range(1, len(tiles) + 1):\n n *= i\n a = set()\n perm = []\n for i in range(len(tiles)):\n perm.append(i)\n for _ in range(n):\n cur = ''\n for i in range(len(tiles)):\n cur += tiles[perm[i]]\n for i in range(len(tiles)):\n a.add(cur[:i + 1])\n next_permutation(perm)\n return len(a)", "from collections import Counter\n\ndef __init__():\n self.sum_ = 0\n\ndef recurse_count(letter_count):\n if len(letter_count) == 0:\n return\n for letter in letter_count:\n self.recurse_count(letter_count - Counter(letter))\n self.sum_ += 1\n return\n\ndef numtilepossibilities(tiles: str) -> int:\n letter_count = Counter(tiles)\n self.recurse_count(letter_count)\n return self.sum_", "def numtilepossibilities(tiles: str) -> int:\n\n def recur(tiles):\n if not tiles:\n return set()\n ans = set()\n temp = ''\n while tiles:\n v = tiles[0]\n ans.add(v)\n new = recur(temp + tiles[1:])\n ans.update(new)\n for k in new:\n ans.add(v + k)\n temp += tiles[0]\n tiles = tiles[1:]\n return ans\n ans = recur(tiles)\n return len(ans)", "def numtilepossibilities(tiles: str) -> int:\n result = set()\n\n def backtrack(left_tiles, curr_seq):\n if len(curr_seq) == k:\n result.add(''.join(curr_seq))\n return\n else:\n for i in range(len(left_tiles)):\n curr_seq.append(left_tiles[i])\n backtrack(left_tiles[:i] + left_tiles[i + 1:], curr_seq)\n curr_seq.pop()\n for k in range(1, len(tiles) + 1):\n backtrack(tiles, [])\n return len(result)", "def numtilepossibilities(tiles: str) -> int:\n\n def recur(tiles):\n if not tiles:\n return set()\n ans = set()\n for (i, v) in enumerate(tiles):\n ans.add(v)\n new = recur(tiles[:i] + tiles[i + 1:])\n ans.update(new)\n for k in new:\n ans.add(v + k)\n return ans\n ans = recur(tiles)\n return len(ans)", "def counts(collect):\n answer = 1\n for char in collect:\n if collect[char]:\n answer += self.counts(collect - collections.Counter(char))\n return answer\n\ndef numtilepossibilities(c):\n return self.counts(collections.Counter(c)) - 1", "def numtilepossibilities(tiles: str) -> int:\n tiles = ''.join(sorted(tiles))\n memo = {}\n\n def helper(s, k):\n if (s, k) not in memo:\n if k == 0:\n memo[s, k] = 1\n else:\n (last, ans) = ('', 0)\n for i in range(len(s)):\n if s[i] != last:\n last = s[i]\n ans += helper(s[:i] + s[i + 1:], k - 1)\n memo[s, k] = ans\n return memo[s, k]\n ret = 0\n for k in range(1, len(tiles) + 1):\n ret += helper(tiles, k)\n return ret", "def numtilepossibilities(tiles: str) -> int:\n\n def perm(k, a):\n if k == 0:\n return []\n elif k == 1:\n return [x for x in a]\n else:\n return [a[i] + y for i in range(len(a)) for y in perm(k - 1, a[:i] + a[i + 1:])]\n out = set()\n for i in range(1, len(tiles) + 1):\n for x in perm(i, tiles):\n out.add(x)\n return len(out)", "def numtilepossibilities(tiles: str) -> int:\n output = set()\n\n def helper(result, options):\n if not options:\n return\n for (idx, o) in enumerate(options):\n tmp = options[:]\n tmp.pop(idx)\n output.add(''.join(result + [o]))\n helper(result + [o], tmp)\n helper([], list(tiles))\n return len(output)", "def numtilepossibilities(tiles: str) -> int:\n\n def helper(curr, tiles):\n for i in range(len(tiles)):\n curr.append(tiles[i])\n pos.add(str(curr))\n c = tiles.copy()\n c.pop(i)\n helper(curr.copy(), c)\n curr.pop()\n tiles = list(tiles)\n pos = set()\n helper([], tiles)\n return len(pos)", "def poss(tiles: str) -> set:\n if len(tiles) == 1:\n return set([tiles[0]])\n output = set()\n for i in range(len(tiles)):\n elem = tiles[i]\n res = self.poss(tiles[:i] + tiles[i + 1:])\n output = output.union(res)\n for elem in res:\n output.add(tiles[i] + elem)\n return output\n\ndef numtilepossibilities(tiles: str) -> int:\n if len(tiles) == 0:\n return 0\n return len(self.poss(tiles))", "def numtilepossibilities(tiles: str) -> int:\n seen = set()\n ans = set()\n\n def backtrack(tiles, seen, curr):\n if curr != '' and curr not in ans:\n ans.add(curr)\n for i in range(len(tiles)):\n if i not in seen:\n seen.add(i)\n backtrack(tiles, seen, curr + tiles[i])\n seen.remove(i)\n backtrack(tiles, seen, '')\n return len(ans)", "from itertools import permutations\n\ndef numtilepossibilities(tiles: str) -> int:\n total = 0\n for size in range(1, len(tiles) + 1):\n total += len(set(permutations(tiles, size)))\n return total", "def numtilepossibilities(tiles: str) -> int:\n\n def backtrack(i, c):\n if i == n:\n return\n for k in c:\n if c[k] > 0:\n self.ans += 1\n backtrack(i + 1, c - Counter(k))\n n = len(tiles)\n counter = Counter(tiles)\n self.ans = 0\n backtrack(0, counter)\n return self.ans", "def __init__():\n self.res = set()\n\ndef backtrack(tiles, curr, indices):\n for i in range(len(tiles)):\n if i not in set(indices):\n curr += tiles[i]\n indices.append(i)\n self.res.add(curr)\n if len(curr) < len(tiles):\n self.backtrack(tiles, curr, indices)\n curr = curr[:-1]\n indices.pop()\n\ndef numtilepossibilities(tiles: str) -> int:\n self.backtrack(tiles, '', [])\n return len(self.res)", "def possible(tiles):\n variants = set()\n if len(tiles) == 1:\n variants.add(tiles[0])\n else:\n for i in range(len(tiles)):\n t = possible(tiles[:i] + tiles[i + 1:])\n variants.update(t)\n for j in t:\n variants.add(tiles[i] + j)\n return variants\n\ndef numtilepossibilities(tiles: str) -> int:\n return len(possible(tiles))", "from itertools import combinations as C\n\ndef numtilepossibilities(tiles: str) -> int:\n num = 0\n for i in range(1, len(tiles) + 1):\n l = set(permutations(tiles, i))\n num += len(l)\n return num", "def numtilepossibilities(tiles: str) -> int:\n possibilities = set()\n\n def swap(arr, l, r):\n if l == r:\n return\n (arr[l], arr[r]) = (arr[r], arr[l])\n\n def add_permutation(arr):\n nonlocal possibilities\n for i in range(len(arr)):\n possibilities.add(''.join(arr[:i + 1]))\n\n def build_permutations(arr, start=0):\n if start >= len(arr):\n add_permutation(arr)\n return\n for i in range(start, len(arr)):\n swap(arr, i, start)\n build_permutations(arr, start + 1)\n swap(arr, i, start)\n build_permutations(list(tiles))\n return len(possibilities)", "def numtilepossibilities(tiles: str) -> int:\n count = 0\n for i in range(1, len(tiles) + 1):\n count += len(set(permutations(tiles, i)))\n return count", "def numtilepossibilities(tiles: str) -> int:\n counter = Counter(tiles)\n self.dfs(counter, [])\n return self.result\n\ndef dfs(counter, curr):\n if curr:\n self.result += 1\n for x in counter:\n curr1 = curr.copy()\n counter1 = counter.copy()\n curr1.append(x)\n counter1[x] -= 1\n if counter1[x] == 0:\n del counter1[x]\n self.dfs(counter1, curr1)", "def numtilepossibilities(s: str) -> int:\n (ans, C) = (0, Counter(s))\n\n def dfs(C, cur):\n nonlocal ans\n if cur:\n ans += 1\n if not C:\n return\n C1 = C.copy()\n for x in C:\n cur.append(x)\n C1[x] -= 1\n if C1[x] == 0:\n del C1[x]\n dfs(C1, cur)\n cur.pop()\n C1[x] += 1\n dfs(C, cur=[])\n return ans", "def numtilepossibilities(tiles: str) -> int:\n tiles = ''.join(sorted(tiles))\n uniques = self.step(tiles)\n return len(uniques) - 1\n\ndef step(tiles: str) -> set:\n if len(tiles) == 0:\n return {''}\n if tiles not in self.memos:\n uniques = set()\n for i in range(len(tiles)):\n c = tiles[i]\n substr = tiles[:i] + tiles[i + 1:]\n substrs_set = self.step(substr)\n for substr in substrs_set:\n uniques.add(substr)\n for j in range(len(substr) + 1):\n new_str = substr[:j] + c + substr[j:]\n uniques.add(new_str)\n self.memos[tiles] = uniques\n return self.memos[tiles]", "def numtilepossibilities(tiles: str) -> int:\n res = set()\n\n def seq(s, l):\n if len(l) == 0:\n res.add(s)\n return\n seq(s, l[1:])\n for i in range(len(l)):\n seq(s + l[i], l[:i] + l[i + 1:])\n seq('', list(tiles))\n return len(res) - 1", "from collections import Counter\n\ndef numtilepossibilities(tiles: str) -> int:\n\n def permutation(num, tiles_counter):\n if num == 1:\n return len(list(tiles_counter))\n rs = 0\n for c in +tiles_counter:\n rs += permutation(num - 1, tiles_counter - Counter({c: 1}))\n return rs\n total = 0\n for i in range(1, len(tiles) + 1):\n total += permutation(i, Counter(tiles))\n return total"], "starter_code": "def numtilepossibilities(tiles: str) -> int:\n", "input_output": {"fn_name": "numTilePossibilities", "inputs": [["\"AAB\""]], "outputs": [89]}, "difficulty": "MEDIUM", "raw_tags": ["Counting", "Backtracking", "String", "Hash Table"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Data structures", "Mathematics", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://leetcode.com/problems/letter-tile-possibilities/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numtilepossibilities", "task_id": "TACO_lite/63", "example": [[["AAB"], ["AAABBC"], ["V"]], ["8", "188", "1"]]} +{"requirement": "Given an array of integers Arr of size N and a number K. Return the maximum sum of a subarray of size K.\nNOTE*: A subarray is a contiguous part of any given array.\nExample 1:\nInput:\nN = 4, K = 2\nArr = [100, 200, 300, 400]\nOutput:\n700\nExplanation:\nArr_{3 } + Arr_{4} =700,\nwhich is maximum.\n \nExample 2:\nInput:\nN = 4, K = 4\nArr = [100, 200, 300, 400]\nOutput:\n1000\nExplanation:\nArr_{1} + Arr_{2} + Arr_{3 } \n+ Arr_{4} =1000,\nwhich is maximum.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function maximumSumSubarray() which takes the integer k, vector Arr with size N, containing the elements of the array and returns the maximum sum of a subarray of size K.\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1<=N<=10^{6}\n1<=K<=N", "solutions": ["def maximumsumsubarray(k, a, n):\n i = j = 0\n mx = sums = 0\n while j < len(a):\n sums += a[j]\n if j - i + 1 < k:\n j += 1\n else:\n mx = max(mx, sums)\n sums = sums - a[i]\n i += 1\n j += 1\n return mx", "def maximumsumsubarray(K, Arr, N):\n winsum = sum(Arr[:K])\n maxsum = winsum\n for i in range(N - K):\n winsum = winsum - Arr[i] + Arr[i + K]\n maxsum = max(maxsum, winsum)\n return maxsum", "def maximumsumsubarray(K, Arr, N):\n start = 0\n end = 0\n sum1 = 0\n ans = 0\n while end < len(Arr):\n sum1 += Arr[end]\n if end - start + 1 == K:\n ans = max(sum1, ans)\n sum1 -= Arr[start]\n start += 1\n end += 1\n return ans", "def maximumsumsubarray(K, Arr, N):\n wstart = 0\n s = 0\n wend = 0\n ans = 0\n while wend < N:\n s += Arr[wend]\n if wend - wstart + 1 == K:\n ans = max(ans, s)\n s -= Arr[wstart]\n wstart += 1\n wend += 1\n return ans", "def maximumsumsubarray(K, Arr, N):\n ws = 0\n we = 0\n s = 0\n ans = 0\n while we < N:\n s += Arr[we]\n if we - ws + 1 == K:\n ans = max(ans, s)\n s -= Arr[ws]\n ws += 1\n we += 1\n return ans", "def maximumsumsubarray(K, Arr, N):\n i = 0\n j = 0\n sum = 0\n mx = -1000000\n while j < N:\n sum += Arr[j]\n if j - i + 1 < K:\n j += 1\n elif j - i + 1 == K:\n mx = max(sum, mx)\n sum -= Arr[i]\n i += 1\n j += 1\n return mx", "def maximumsumsubarray(K, Arr, N):\n i = 0\n j = 0\n sums = 0\n maxi = -10 ** 7\n while j < N:\n sums += Arr[j]\n if j - i + 1 < K:\n j += 1\n elif j - i + 1 == K:\n maxi = max(maxi, sums)\n sums -= Arr[i]\n i += 1\n j += 1\n return maxi", "def maximumsumsubarray(k, a, N):\n sum = 0\n for i in range(0, K):\n sum += a[i]\n max_sum = sum\n start = 0\n for i in range(k, N):\n sum = sum + a[i] - a[start]\n start = start + 1\n if sum > max_sum:\n max_sum = sum\n return max_sum", "def maximumsumsubarray(k, arr, n):\n winsum = sum(arr[:k])\n maxsum = winsum\n for i in range(n - k):\n winsum = winsum - arr[i] + arr[i + k]\n if winsum > maxsum:\n maxsum = winsum\n return maxsum", "def maximumsumsubarray(k, l, n):\n winsum = sum(l[0:k])\n maxsub = winsum\n for i in range(0, n - k):\n winsum = winsum - l[i] + l[i + k]\n maxsub = max(winsum, maxsub)\n return maxsub", "def maximumsumsubarray(K, Arr, N):\n ws = sum(Arr[:K])\n ms = ws\n for i in range(N - K):\n ws = ws - Arr[i] + Arr[K + i]\n ms = max(ms, ws)\n return ms", "def maximumsumsubarray(K, Arr, N):\n s = sum(Arr[:K])\n v = s\n for i in range(N - K):\n s = s - Arr[i] + Arr[i + K]\n v = max(s, v)\n return v", "def maximumsumsubarray(K, Arr, N):\n l = sum(Arr[:K])\n k = l\n for i in range(N - K):\n l = l - Arr[i] + Arr[i + K]\n k = max(k, l)\n return k", "def maximumsumsubarray(K, Arr, N):\n max_sum = sum(Arr[:K])\n cur_sum = max_sum\n for i in range(0, N - K):\n cur_sum += Arr[K + i] - Arr[i]\n max_sum = max(max_sum, cur_sum)\n return max_sum", "from typing import List\n\ndef maximumsumsubarray(K: int, Arr: List[int], N: int) -> int:\n winsum = sum(Arr[:K])\n maxsum = winsum\n for i in range(N - K):\n winsum = winsum - Arr[i] + Arr[i + K]\n maxsum = max(maxsum, winsum)\n return maxsum", "def maximumsumsubarray(K, arr, N):\n win_sum = sum(arr[:K])\n maxsum = win_sum\n for i in range(0, N - K):\n win_sum = win_sum - arr[i] + arr[i + K]\n maxsum = max(win_sum, maxsum)\n return maxsum", "def maximumsumsubarray(K, Arr, N):\n (i, j, total, maxsum) = (0, 0, 0, 0)\n while j < len(Arr):\n total += Arr[j]\n if j - i + 1 < K:\n j += 1\n elif j - i + 1 == K:\n maxsum = max(maxsum, total)\n total = total - Arr[i]\n i += 1\n j += 1\n return maxsum", "def maximumsumsubarray(K, Arr, N):\n win = sum(Arr[:K])\n m = win\n for i in range(N - K):\n win = win - Arr[i] + Arr[i + K]\n m = max(win, m)\n return m", "def maximumsumsubarray(K, Arr, N):\n res = sum(Arr[:K])\n cs = res\n for i in range(K, N):\n cs += Arr[i] - Arr[i - K]\n res = max(res, cs)\n return res", "def maximumsumsubarray(K, Arr, N):\n cur_sum = 0\n ans = 0\n cur_sum = sum(Arr[0:K])\n ans = cur_sum\n i = 0\n j = K\n while j < N:\n cur_sum = cur_sum + Arr[j] - Arr[i]\n ans = max(ans, cur_sum)\n i += 1\n j += 1\n return ans", "def maximumsumsubarray(K, Arr, N):\n if N < K:\n return -1\n sum = 0\n for i in range(K):\n sum = sum + Arr[i]\n csum = sum\n for i in range(K, N):\n csum = csum + Arr[i] - Arr[i - K]\n sum = max(sum, csum)\n return sum", "def maximumsumsubarray(K, arr, N):\n winsum = sum(arr[:K])\n ms = winsum\n for i in range(N - K):\n winsum = winsum - arr[i] + arr[i + K]\n ms = max(ms, winsum)\n return ms", "def maximumsumsubarray(K, Arr, N):\n mx = 0\n sumK = 0\n i = 0\n j = 0\n while j < len(Arr):\n sumK += Arr[j]\n if j - i + 1 < K:\n j += 1\n elif j - i + 1 == K:\n mx = max(mx, sumK)\n sumK -= Arr[i]\n i += 1\n j += 1\n return mx", "def maximumsumsubarray(k, arr, n):\n wind = sum(arr[:k])\n maxsum = wind\n for i in range(n - k):\n wind = wind - arr[i] + arr[i + k]\n maxsum = max(maxsum, wind)\n return maxsum", "def maximumsumsubarray(K, Arr, N):\n res = 0\n curr = 0\n for i in range(K):\n curr = curr + Arr[i]\n if curr > res:\n res = curr\n for i in range(K, N):\n curr = curr + Arr[i] - Arr[i - K]\n if curr > res:\n res = curr\n return res", "def maximumsumsubarray(K, Arr, N):\n w = sum(Arr[:K])\n b = w\n for i in range(N - K):\n w = w - Arr[i] + Arr[i + K]\n b = max(w, b)\n return b", "def maximumsumsubarray(K, Arr, N):\n (l, r) = (0, 0)\n max_ = 0\n sum_ = 0\n while r < N:\n sum_ += Arr[r]\n if r >= K - 1:\n max_ = max(max_, sum_)\n sum_ -= Arr[l]\n l += 1\n r += 1\n return max_", "def maximumsumsubarray(k, nums, n):\n window = Arr[0:K]\n windosum = sum(window)\n maxi = windosum\n for i in range(0, N - K):\n windosum = windosum - Arr[i] + Arr[i + K]\n maxi = max(windosum, maxi)\n return maxi", "from typing import List\n\ndef maximumsumsubarray(K: int, Arr: List[int], N: int) -> int:\n window_sum = sum(Arr[:K])\n max_sum = window_sum\n for i in range(K, N):\n window_sum = window_sum + Arr[i] - Arr[i - K]\n max_sum = max(max_sum, window_sum)\n return max_sum", "def maximumsumsubarray(k, arr, n):\n i = j = ms = curr_sum = 0\n while j < n:\n curr_sum += Arr[j]\n if j - i + 1 == k:\n ms = max(ms, curr_sum)\n curr_sum -= arr[i]\n i += 1\n j += 1\n return ms", "def maximumsumsubarray(K, Arr, N):\n cursum = 0\n res = 0\n for (i, x) in enumerate(Arr):\n if i >= K:\n cursum = cursum - Arr[i - K]\n cursum = cursum + x\n res = max(res, cursum)\n return res", "def maximumsumsubarray(K, Arr, N):\n i = 0\n j = 0\n csum = 0\n maxi = 0\n while j < N:\n csum += Arr[j]\n if j - i + 1 < K:\n j += 1\n elif j - i + 1 == K:\n maxi = max(maxi, csum)\n csum -= Arr[i]\n i += 1\n j += 1\n return maxi", "def maximumsumsubarray(K, Arr, N):\n ws = 0\n ms = 0\n s = 0\n for i in range(N):\n ws += Arr[i]\n if i - s + 1 == K:\n ms = max(ms, ws)\n ws -= Arr[s]\n s += 1\n return ms", "def maximumsumsubarray(K, Arr, N):\n if K < 0 or K > len(Arr):\n return -1\n else:\n sum = 0\n for i in range(0, K):\n sum += Arr[i]\n max_sum = sum\n start = 0\n for j in range(K, len(Arr)):\n sum = sum + Arr[j] - Arr[start]\n start += 1\n if sum > max_sum:\n max_sum = sum\n return max_sum", "def maximumsumsubarray(K, Arr, N):\n maxi = float('-inf')\n curr_sum = 0\n j = 0\n for i in range(K):\n curr_sum += Arr[i]\n maxi = curr_sum\n for i in range(K, len(Arr)):\n curr_sum = curr_sum - Arr[j] + Arr[i]\n maxi = max(curr_sum, maxi)\n j += 1\n return maxi", "def maximumsumsubarray(K, Arr, N):\n if N < K:\n return -1\n temp = 0\n for i in range(K):\n temp += Arr[i]\n maxsum = temp\n for i in range(K, N):\n maxsum += Arr[i] - Arr[i - K]\n temp = max(temp, maxsum)\n return temp", "def maximumsumsubarray(k, arr, n):\n res = 0\n curr = 0\n for i in range(k):\n curr += arr[i]\n if curr > res:\n res = curr\n for i in range(k, n):\n curr = curr + arr[i] - arr[i - k]\n if curr > res:\n res = curr\n return res", "def maximumsumsubarray(K, Arr, N):\n (i, j) = (0, 0)\n s = 0\n mx = float('-inf')\n while j < len(Arr):\n s += Arr[j]\n if j - i + 1 < K:\n j += 1\n elif j - i + 1 == K:\n mx = max(mx, s)\n s -= Arr[i]\n i += 1\n j += 1\n return mx", "def maximumsumsubarray(K, Arr, N):\n if K > N:\n return 0\n if K == N:\n return sum(Arr)\n i = j = 0\n res = 0\n for i in range(K):\n res += Arr[i]\n curr_sum = res\n for i in range(K, N):\n curr_sum += Arr[i] - Arr[i - K]\n res = max(res, curr_sum)\n return res", "def maximumsumsubarray(k, Arr, N):\n s = sum(Arr[:k])\n ans = s\n for i in range(k, N):\n s += Arr[i]\n s -= Arr[i - k]\n ans = max(s, ans)\n return ans"], "starter_code": "def maximumsumsubarray (K,Arr,N):\n", "input_output": {"inputs": ["N = 4, K = 2\nArr = [100, 200, 300, 400]", "N = 4, K = 4\nArr = [100, 200, 300, 400]"], "outputs": ["700", "1000"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "sliding-window", "Misc", "prefix-sum"], "name": null, "source": "geeksforgeeks", "tags": ["Amortized analysis", "Range queries"], "skill_types": ["Amortized analysis", "Range queries"], "url": "https://practice.geeksforgeeks.org/problems/max-sum-subarray-of-size-k5313/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "maximumsumsubarray", "task_id": "TACO_lite/141", "example": [[[4, 2, [100, 200, 300, 400]], [4, 4, [100, 200, 300, 400]]], ["700", "1000"]]} +{"requirement": "Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.\n\n Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.\n\nExample 1:\n\nInput: [1,1,2,2,2]\nOutput: true\n\nExplanation: You can form a square with length 2, one side of the square came two sticks with length 1.\n\n\n\nExample 2:\n\nInput: [3,3,3,3,4]\nOutput: false\n\nExplanation: You cannot find a way to form a square with all the matchsticks.\n\n\n\nNote:\n\nThe length sum of the given matchsticks is in the range of 0 to 10^9.\nThe length of the given matchstick array will not exceed 15.", "solutions": ["def makesquare(nums):\n if len(nums) < 4:\n return False\n length = sum(nums)\n if length % 4:\n return False\n length = int(length / 4)\n nums.sort(reverse=True)\n if length < nums[0]:\n return False\n elif length == nums[0]:\n stack = list([(set([0]), 1, length, 1)])\n else:\n stack = list([(set([0]), 1, length - nums[0], 2)])\n while stack:\n (usedSet, startIndex, target, remainRounds) = stack.pop()\n for i in range(len(nums) - 1, startIndex - 1, -1):\n if i in usedSet:\n continue\n num = nums[i]\n if num < target and i + 1 < len(nums):\n stack.append((usedSet | {i}, i + 1, target - num, remainRounds))\n elif num == target:\n if remainRounds == 0:\n return True\n else:\n stack.append((usedSet | {i}, 1, length, remainRounds - 1))\n return False", "def makesquare(nums):\n total = sum(nums)\n if total % 4 != 0 or len(nums) < 4:\n return False\n size = total / 4\n nums.sort(reverse=True)\n used = [False] * len(nums)\n\n def dfs(i, expect):\n if i >= len(nums):\n return expect % size == 0\n if used[i]:\n return dfs(i + 1, expect)\n used[i] = True\n if nums[i] == expect:\n return True\n if nums[i] < expect:\n expect -= nums[i]\n available = [j for j in range(i + 1, len(nums)) if not used[j]]\n for x in available:\n if dfs(x, expect):\n return True\n used[i] = False\n return False\n for i in range(len(nums)):\n if not dfs(i, size):\n return False\n return True", "def makesquare(nums):\n\n def checkv(t, c, nums, used):\n if t == 0:\n return True\n if t < 0:\n return False\n while c < len(nums) and used[c]:\n c = c + 1\n if c >= len(nums):\n return False\n if checkv(t - nums[c], c + 1, nums, used):\n used[c] = True\n return True\n if checkv(t, c + 1, nums, used):\n return True\n return False\n edgel = sum(nums)\n if edgel % 4 != 0 or edgel == 0:\n return False\n edgel = edgel / 4\n nums.sort(key=lambda x: -x)\n n = len(nums)\n used = [False] * n\n for p in range(3):\n t = edgel\n if not checkv(t, 0, nums, used):\n return False\n return True", "def makesquare(nums):\n s = sum(nums)\n if not s % 4 == 0:\n return False\n l = s // 4\n from collections import Counter\n self.c = Counter(nums)\n for _ in range(4):\n n = self.f(0, sorted(self.c.elements(), reverse=True), l, ())\n if not n:\n return False\n self.c.subtract(n)\n return True\n\ndef f(index, keys, sum, nums):\n if sum == 0:\n return nums\n if sum < 0 or index >= len(keys):\n return None\n return self.f(index + 1, keys, sum - keys[index], (*nums, keys[index])) or self.f(index + 1, keys, sum, nums)"], "starter_code": "def makesquare(nums: List[int]) -> bool:\n", "input_output": {"fn_name": "makesquare", "inputs": [[[1, 1, 2, 2, 2]]], "outputs": [true]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Bitmask", "Array", "Backtracking", "Dynamic Programming", "Bit Manipulation"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Bit manipulation", "Data structures", "Complete search"], "skill_types": ["Dynamic programming", "Bit manipulation", "Data structures", "Complete search"], "url": "https://leetcode.com/problems/matchsticks-to-square/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "makesquare", "task_id": "TACO_lite/162", "example": [[], []]} +{"requirement": "Given binary string str of length N. The task is to find the maximum count of consecutive substrings str can be divided into such that all the substrings are balanced i.e. they have an equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then return -1.\nExample 1:\nInput:\nS = \"0100110101\"\nOutput: 4\nExplanation: \nThe required substrings are 01, 0011, 01 and 01.\nExample 2:\nInput:\nS = \"0111100010\"\nOutput: 3\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function maxSubStr() which takes a string S and returns an integer as output.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= S.length <= 10^{5}", "solutions": ["def maxsubstr(input_str):\n count = 0\n balance = 0\n for ch in input_str:\n if ch == '0':\n balance += 1\n elif ch == '1':\n balance -= 1\n if balance == 0:\n count += 1\n if balance != 0:\n return -1\n return count", "def maxsubstr(str):\n (c1, c2) = (0, 0)\n count = 0\n n = len(str)\n for (i, s) in enumerate(str):\n if s == '0':\n c1 += 1\n if s == '1':\n c2 += 1\n if c1 == c2:\n count += 1\n if c1 != c2:\n return -1\n return count", "def maxsubstr(str):\n n = len(str)\n x = 0\n y = 0\n c = 0\n for i in range(0, n):\n if str[i] == '0':\n x += 1\n else:\n y += 1\n if x == y:\n c += 1\n if x != y:\n return -1\n return c", "def maxsubstr(str):\n su = count = total = 0\n for i in str:\n if i == '0':\n total -= 1\n else:\n total += 1\n if total != 0:\n return -1\n else:\n for i in str:\n if i == '0':\n su -= 1\n else:\n su += 1\n if su == 0:\n count += 1\n return count", "def maxsubstr(s):\n count0 = 0\n count1 = 0\n ans = 0\n for i in range(len(s)):\n if s[i] == '0':\n count0 += 1\n if s[i] == '1':\n count1 += 1\n if count0 == count1:\n ans += 1\n if count0 != count1:\n return -1\n return ans", "def maxsubstr(str):\n count = 0\n count1 = 0\n cnt = 0\n for i in range(len(str)):\n if str[i] == '0':\n count += 1\n else:\n count1 += 1\n if count1 == count:\n cnt += 1\n count1 = 0\n count = 0\n if count or count1:\n return -1\n return cnt", "def maxsubstr(string):\n (c0, c1) = (0, 0)\n res = 0\n for i in string:\n if i == '0':\n c0 += 1\n else:\n c1 += 1\n if c0 == c1:\n res += 1\n if c0 != c1:\n return -1\n return res", "def maxsubstr(str):\n cnt0 = 0\n cnt1 = 0\n ans = 0\n for i in str:\n if i == '0':\n cnt0 += 1\n else:\n cnt1 += 1\n if cnt0 == cnt1:\n ans += 1\n if cnt0 != cnt1:\n return -1\n return ans", "def maxsubstr(str):\n if len(str) % 2 != 0:\n return -1\n elif str.count('1') != str.count('0'):\n return -1\n count_0 = 0\n count_1 = 0\n ans = 0\n for i in str:\n if i == '0':\n count_0 += 1\n else:\n count_1 += 1\n if count_0 == count_1:\n ans += 1\n return ans if ans != 0 else -1", "def maxsubstr(str):\n if len(str) % 2 != 0:\n return -1\n zero_cnt = one_cnt = 0\n if str[0] == '0':\n zero_cnt = 1\n else:\n one_cnt = 1\n count = 0\n substr_size = 0\n i = 0\n j = 1\n while i < len(str) and j < len(str):\n if str[j] == '0':\n zero_cnt += 1\n else:\n one_cnt += 1\n j += 1\n if zero_cnt > 0 and one_cnt > 0 and (zero_cnt == one_cnt):\n substr_size += j - i\n zero_cnt = one_cnt = 0\n count += 1\n i = j\n return count if count > 0 and substr_size == len(str) else -1", "def maxsubstr(str):\n count = 0\n total = 0\n for x in str:\n if x == '0':\n total += 1\n else:\n total -= 1\n if total == 0:\n count += 1\n return count if total == 0 else -1", "def maxsubstr(str):\n count0 = 0\n count1 = 0\n count = 0\n for i in range(0, len(str)):\n if str[i] == '0':\n count0 += 1\n if str[i] == '1':\n count1 += 1\n if count0 == count1:\n count += 1\n if count1 != count0:\n return -1\n return count", "def maxsubstr(str):\n n = len(str)\n cnt = 0\n cnt1 = 0\n cnt2 = 0\n for i in range(n):\n if str[i] == '0':\n cnt1 += 1\n else:\n cnt2 += 1\n if cnt1 == cnt2:\n cnt += 1\n if cnt1 != cnt2:\n return -1\n return cnt", "def maxsubstr(str):\n if len(str) == 0 or len(str) == 1 or '1' not in str or ('0' not in str):\n return -1\n dic = {}\n count_0 = 0\n count_1 = 0\n total = 0\n for i in range(len(str)):\n if str[i] in dic:\n dic[str[i]] += 1\n else:\n dic[str[i]] = 1\n if dic['1'] != dic['0']:\n return -1\n for k in range(len(str)):\n if str[k] == '0':\n count_0 += 1\n if str[k] == '1':\n count_1 += 1\n if count_0 == count_1:\n total += 1\n return total", "def maxsubstr(str):\n count_0 = 0\n count_1 = 0\n count = 0\n for i in str:\n if i == '0':\n count_0 += 1\n else:\n count_1 += 1\n if count_0 == count_1:\n count += 1\n if count_0 != count_1:\n return -1\n return count", "def maxsubstr(str):\n n = len(str)\n ans = 0\n i = 0\n (zero, one) = (0, 0)\n while i < n:\n if str[i] == '0':\n zero += 1\n else:\n one += 1\n i += 1\n if zero == one:\n ans += 1\n if zero != one:\n return -1\n return ans", "def maxsubstr(str):\n c0 = 0\n c1 = 0\n count = 0\n for i in str:\n if i == '1':\n c1 += 1\n else:\n c0 += 1\n if c1 == c0:\n count += 1\n if count > 0 and c0 == c1:\n return count\n return -1", "def maxsubstr(str):\n k = j = r = 0\n for i in str:\n if i == '0':\n k += 1\n else:\n j += 1\n if k == j:\n r += 1\n k = j = 0\n if k != 0:\n return -1\n if j != 0:\n return -1\n if r == 0:\n return -1\n return r", "def maxsubstr(str):\n count_0 = 0\n count_1 = 0\n ans = 0\n for i in range(len(s)):\n if s[i] == '0':\n count_0 += 1\n else:\n count_1 += 1\n if count_0 == count_1:\n ans += 1\n elif i == len(s) - 1:\n return -1\n if ans == 0:\n return -1\n return ans", "def maxsubstr(s):\n count = 0\n z_count = 0\n o_count = 0\n for i in s:\n if i == '0':\n z_count += 1\n else:\n o_count += 1\n if z_count == o_count:\n z_count = 0\n o_count = 0\n count += 1\n if z_count == o_count:\n return count\n else:\n return -1", "def maxsubstr(s):\n if len(s) == 1:\n return -1\n if s.count('0') != s.count('1'):\n return -1\n curr = s[0]\n curr_c = 0\n count = 0\n i = 0\n while i < len(s):\n if s[i] == curr:\n curr_c += 1\n else:\n while i < len(s) and s[i] != curr and (curr_c != 0):\n curr_c -= 1\n i += 1\n if curr_c == 0:\n count += 1\n if i < len(s):\n curr = s[i]\n i -= 1\n i += 1\n return count", "def maxsubstr(s):\n if s.count('0') != s.count('1'):\n return -1\n count_0 = 0\n count_1 = 0\n ans = 0\n for elm in s:\n if elm == '0':\n count_0 += 1\n else:\n count_1 += 1\n if count_0 == count_1:\n ans += 1\n return ans", "def maxsubstr(str):\n c = c1 = c2 = 0\n for i in str:\n if i == '0':\n c1 += 1\n else:\n c2 += 1\n if c1 == c2:\n c += 1\n if c1 != c2:\n return -1\n return c", "def maxsubstr(str):\n p = 0\n res = 0\n for i in str:\n if i == '1':\n p -= 1\n else:\n p += 1\n if p == 0:\n res += 1\n if p != 0:\n return -1\n return res", "def maxsubstr(stre):\n n = len(stre)\n (vote, ans) = (0, 0)\n for i in stre:\n if i == '0':\n vote += 1\n else:\n vote -= 1\n if vote == 0:\n ans += 1\n if vote == 0:\n return ans\n return -1", "def maxsubstr(str):\n count0 = 0\n count1 = 0\n n = len(str)\n cnt = 0\n for i in range(n):\n if str[i] == '0':\n count0 += 1\n else:\n count1 += 1\n if count0 == count1:\n cnt += 1\n if count0 != count1:\n return -1\n return cnt", "def maxsubstr(str):\n a = 0\n b = 0\n c = 0\n i = 0\n while i < len(str):\n if str[i] == '0':\n a = a + 1\n else:\n b = b + 1\n if a == b:\n a = 0\n b = 0\n c = c + 1\n i = i + 1\n if a == 0 and b == 0:\n return c\n return -1", "def maxsubstr(str):\n ca = 0\n count = 0\n for i in str:\n if i == '0':\n ca += 1\n else:\n ca -= 1\n if ca == 0:\n count += 1\n if ca == 0:\n return count\n else:\n return -1", "def maxsubstr(str):\n i = 0\n o = 0\n res = 0\n for k in range(len(str) - 1):\n if str[k] == '0':\n o = o + 1\n if o == i:\n res = res + 1\n i = 0\n o = 0\n else:\n i = i + 1\n if o == i:\n res = res + 1\n i = 0\n o = 0\n k = len(str) - 1\n if str[k] == '0':\n o = o + 1\n if o == i:\n res = res + 1\n else:\n return -1\n else:\n i = i + 1\n if o == i:\n res = res + 1\n else:\n return -1\n if res == 0:\n return -1\n else:\n return res", "def maxsubstr(str):\n count_zero = 0\n count_one = 0\n count = 0\n for i in range(len(str)):\n if str[i] == '0':\n count_zero += 1\n else:\n count_one += 1\n if count_zero == count_one:\n count += 1\n if count_zero != count_one:\n return -1\n return count", "def maxsubstr(str):\n n = len(str)\n (cz, count) = (0, 0)\n for i in str:\n if i == '0':\n cz += 1\n else:\n cz -= 1\n if cz == 0:\n count += 1\n if cz == 0:\n return count\n return -1", "def maxsubstr(str):\n i = 0\n s = 0\n c1 = 0\n c2 = 0\n while i < len(str):\n if str[i] == '0':\n c1 += 1\n else:\n c2 += 1\n if c1 == c2:\n s += 1\n c1 = 0\n c2 = 0\n i += 1\n if c1 == c2:\n return s\n else:\n return -1", "def maxsubstr(str):\n count = 0\n c1 = 0\n c0 = 0\n i = 0\n u = ''\n while i < len(s):\n u += s[i]\n if s[i] == '0':\n c0 += 1\n else:\n c1 += 1\n if c1 == c0:\n count += 1\n u = ''\n c1 = 0\n c0 = 0\n if i == len(s) - 1:\n if u != '':\n return -1\n i += 1\n return count", "def maxsubstr(str):\n count = 0\n zeroes = 0\n ones = 0\n for i in str:\n if i == '0':\n zeroes += 1\n else:\n ones += 1\n if zeroes == ones:\n count += 1\n zeroes = 0\n ones = 0\n if ones != zeroes:\n return -1\n if count == 0:\n return -1\n return count", "def maxsubstr(str):\n cz = 0\n co = 0\n out = 0\n for i in str:\n if i == '0':\n cz += 1\n else:\n co += 1\n if cz == co:\n out += 1\n if co != cz:\n return -1\n return out", "def maxsubstr(str):\n c0 = 0\n c1 = 0\n c = 0\n for i in range(len(str)):\n if str[i] == '0':\n c0 += 1\n elif str[i] == '1':\n c1 += 1\n if c0 == c1:\n c += 1\n if c0 != c1:\n return -1\n return c", "def maxsubstr(str):\n ans = 0\n res = 0\n lis = list(str)\n for i in range(0, len(lis)):\n if lis[i] == '1':\n ans = ans + 1\n if lis[i] == '0':\n ans = ans - 1\n if ans == 0:\n res += 1\n ans = 0\n if ans != 0:\n return -1\n return res", "def maxsubstr(str):\n zero = 0\n one = 0\n c = 0\n stack = []\n temp = ''\n for i in range(len(str)):\n if str[i] == '0':\n if stack != [] and stack[-1] == '1':\n x = stack.pop()\n else:\n stack.append('0')\n elif str[i] == '1':\n if stack != [] and stack[-1] == '0':\n x = stack.pop()\n else:\n stack.append('1')\n if stack == []:\n c += 1\n if stack != []:\n return -1\n return c", "def maxsubstr(str):\n mapping = {'1': 0, '0': 0}\n count = 0\n for element in str:\n mapping[element] += 1\n if mapping['0'] == mapping['1']:\n mapping['0'] = 0\n mapping['1'] = 0\n count += 1\n if mapping['0'] == mapping['1'] == 0:\n return count\n return -1", "def maxsubstr(str):\n d1 = {}\n for i in str:\n d1[i] = 1 + d1.get(i, 0)\n if len(set(d1.values())) > 1:\n return -1\n d = {'0': 0, '1': 0}\n i = 0\n j = 0\n c = -1\n f = 0\n while j < len(str):\n d[str[j]] = d[str[j]] + 1\n if d['0'] != d['1']:\n j = j + 1\n else:\n c = c + 1\n f = 1\n d = {'0': 0, '1': 0}\n i = j + 1\n j = i\n if f == 1:\n c = c + 1\n return c\n else:\n return c", "def maxsubstr(str):\n i = 0\n cnt0 = 0\n cnt1 = 0\n cnt = 0\n while i < len(str):\n if str[i] == '0':\n cnt0 += 1\n else:\n cnt1 += 1\n if cnt0 == cnt1:\n cnt += 1\n i += 1\n if cnt0 == cnt1:\n return cnt\n else:\n return -1", "def maxsubstr(s):\n i = 0\n cnt0 = 0\n cnt1 = 0\n ans = 0\n while i < len(s):\n if s[i] == '0':\n cnt0 += 1\n else:\n cnt1 += 1\n if cnt0 == cnt1:\n ans += 1\n i += 1\n if ans == 0 or cnt0 != cnt1:\n return -1\n return ans", "def maxsubstr(str):\n check = ''\n count = 0\n val = 0\n for i in str:\n if count == 0:\n check = i\n count += 1\n elif check == i:\n count += 1\n else:\n count -= 1\n if count == 0:\n val += 1\n if count != 0:\n return -1\n return val", "def maxsubstr(str):\n if str.count('1') != str.count('0'):\n return -1\n count = 0\n ones = 0\n zeros = 0\n for i in range(len(str)):\n if ones == zeros:\n count += 1\n ones = 0\n zeros = 0\n if str[i] == '1':\n ones += 1\n else:\n zeros += 1\n return count", "def maxsubstr(str):\n count = 0\n zero = 0\n one = 0\n for i in str:\n if i == '0':\n zero += 1\n elif i == '1':\n one += 1\n if zero == one:\n count += 1\n if zero == one:\n return count\n else:\n return -1", "def maxsubstr(str):\n c = 0\n zero = 0\n one = 0\n for i in range(len(str)):\n if str[i] == '0':\n zero = zero + 1\n else:\n one = one + 1\n if zero == one:\n c = c + 1\n if zero != one:\n return -1\n return c", "def maxsubstr(str):\n count0 = 0\n count1 = 0\n ans = 0\n for i in str:\n if i == '0':\n count0 += 1\n else:\n count1 += 1\n if count1 == count0:\n ans += 1\n if count1 != count0:\n return -1\n return ans", "def maxsubstr(str):\n c = 0\n zc = 0\n oc = 0\n for i in s:\n if i == '0':\n zc += 1\n else:\n oc += 1\n if zc == oc:\n c += 1\n zc = 0\n oc = 0\n if zc >= 1 or oc >= 1:\n return -1\n else:\n return c", "def maxsubstr(str):\n countZero = 0\n countOne = 0\n res = 0\n for i in range(len(str)):\n if str[i] == '0':\n countZero += 1\n else:\n countOne += 1\n if countZero == countOne:\n res += 1\n countZero = 0\n countOne = 0\n if countZero > 0 or countOne > 0 or countZero != countOne:\n return -1\n return res", "def maxsubstr(str):\n count_0 = 0\n count_1 = 0\n count = 0\n for i in range(len(str)):\n if str[i] == '0':\n count_0 += 1\n else:\n count_1 += 1\n if count_0 == count_1:\n count += 1\n if count_0 != count_1:\n return -1\n elif count_0 == 0 and count_1 == 0:\n return -1\n return count", "def maxsubstr(str):\n z = 0\n ones = 0\n ans = 0\n for i in str:\n if i == '0':\n z += 1\n else:\n ones += 1\n if z == ones:\n ans += 1\n (z, ones) = (0, 0)\n return ans if z == ones else -1", "def maxsubstr(str):\n (one, zero, ans) = (0, 0, 0)\n for i in str:\n if i == '0':\n zero += 1\n else:\n one += 1\n if zero == one:\n ans += 1\n (one, zero) = (0, 0)\n if ans == 0 or one != zero:\n return -1\n else:\n return ans", "from collections import Counter\n\ndef func(s, temp, ans):\n if not s:\n ans[0] = max(ans[0], len(temp))\n return\n for i in range(2, len(s) + 1):\n t = s[:i]\n a = Counter(t)\n if a.get('0', 0) == a.get('1', 0):\n func(s[i:], temp + [t], ans)\n\ndef maxsubstr(s):\n l = 0\n count = 0\n c0 = 0\n c1 = 0\n for i in range(len(s)):\n if s[i] == '0':\n c0 += 1\n else:\n c1 += 1\n if c0 == c1:\n c0 = 0\n c1 = 0\n count += 1\n if c0 != c1:\n return -1\n return count", "def maxsubstr(str):\n counter = 0\n count = 0\n d = {'0': 0, '1': 0}\n for i in str:\n d[i] += 1\n if i == '0':\n counter += 1\n else:\n counter -= 1\n if counter == 0:\n count += 1\n return count if d['0'] == d['1'] else -1", "def maxsubstr(str):\n count0 = 0\n count1 = 0\n ans = 0\n i = 0\n while i < len(str):\n if str[i] == '0':\n count0 += 1\n else:\n count1 += 1\n if count0 == count1:\n ans += 1\n i += 1\n if count0 == count1:\n return ans\n return -1", "def maxsubstr(s):\n count = 0\n summa = 0\n for item in s:\n if item == '1':\n summa += 1\n else:\n summa -= 1\n count += summa == 0\n return count if summa == 0 else -1", "def maxsubstr(str1):\n (count0, count1, res) = (0, 0, 0)\n for i in str1:\n if i == '0':\n count0 += 1\n else:\n count1 += 1\n if count0 == count1:\n (count0, count1, res) = (0, 0, res + 1)\n if count0 > 0 or count1 > 0 or count0 != count1:\n return -1\n return res", "def maxsubstr(str):\n (zero, one) = (0, 0)\n ans = 0\n for each in str:\n if each == '0':\n zero += 1\n if each == '1':\n one += 1\n if zero == one:\n (zero, one) = (0, 0)\n ans += 1\n if zero == one:\n return ans\n else:\n return -1", "def maxsubstr(value):\n n = len(value)\n first_element = value[0]\n last_element = first_element\n count = 0\n count = count + self.operation(last_element, first_element)\n pair = 0\n for i in range(1, n):\n element = value[i]\n count = count + self.operation(element, first_element)\n if count == 0:\n pair = pair + 1\n if pair == 0 or count != 0:\n return -1\n else:\n return pair\n\ndef operation(element, first_element):\n if element == first_element:\n return 1\n else:\n return -1", "def maxsubstr(str):\n c0 = 0\n c1 = 0\n cnt = 0\n for i in range(len(str)):\n if str[i] == '0':\n c0 += 1\n else:\n c1 += 1\n if c0 == c1:\n cnt += 1\n if c0 != c1:\n return -1\n return cnt", "def maxsubstr(str):\n count = 0\n zero = 0\n ones = 0\n for i in range(len(str)):\n if str[i] == '0':\n zero += 1\n elif str[i] == '1':\n ones += 1\n if zero == ones:\n count += 1\n if zero != ones:\n return -1\n return count", "def maxsubstr(str):\n count0 = 0\n count1 = 0\n count = 0\n for (i, j) in enumerate(str):\n if j == '0':\n count0 += 1\n else:\n count1 += 1\n if count0 == count1:\n count += 1\n if count0 != count1:\n return -1\n return count", "def maxsubstr(str):\n c1 = 0\n c2 = 0\n c3 = 0\n for i in range(len(str)):\n if str[i] == '0':\n c1 += 1\n else:\n c2 += 1\n if c1 == c2:\n c3 += 1\n if c1 != c2:\n return -1\n return c3", "def maxsubstr(str):\n count = 0\n arr = []\n sum = 0\n for i in range(0, len(str)):\n if str[i] == '1':\n arr.append(1)\n else:\n arr.append(-1)\n for i in range(0, len(str)):\n sum += arr[i]\n if sum == 0:\n count += 1\n if sum != 0:\n return -1\n return count", "def maxsubstr(str1):\n o = 0\n z = 0\n c = 0\n res = []\n for i in str1:\n if i == '0':\n z = z + 1\n if i == '1':\n o = o + 1\n if z == o:\n res.append(str1[:z + o])\n str1 = str1[z + o:]\n z = 0\n o = 0\n if z > 0 or o > 0:\n return -1\n else:\n return len(res)", "def maxsubstr(str):\n m = 0\n n = 0\n c = 0\n if str.count('1') != str.count('0'):\n return -1\n else:\n for i in range(len(str)):\n if str[i] == '0':\n m += 1\n elif str[i] == '1':\n n += 1\n if m == n:\n m = 0\n n = 0\n c += 1\n return c", "def maxsubstr(s):\n c1 = c2 = 0\n ans = 0\n for i in s:\n if i == '0':\n c1 += 1\n else:\n c2 += 1\n if c1 == c2:\n ans += 1\n if c1 != c2:\n return -1\n return ans", "def maxsubstr(str):\n (x, y, ans) = (0, 0, 0)\n for i in range(len(str)):\n if str[i] == '0':\n x = x + 1\n elif str[i] == '1':\n y = y + 1\n if x == y:\n ans = ans + 1\n if x != y:\n return -1\n return ans", "def maxsubstr(str):\n i = 0\n j = 0\n m_i = 0\n m_j = 0\n count = 0\n for k in range(len(str)):\n if str[k] == '0':\n i += 1\n m_i += 1\n else:\n j += 1\n m_j += 1\n if i == j:\n count += 1\n i = 0\n j = 0\n if m_i != m_j:\n return -1\n else:\n return count", "def maxsubstr(str):\n c = 0\n z = 0\n o = 0\n for i in str:\n if i == '0':\n z += 1\n else:\n o += 1\n if z == o:\n z = 0\n o = 0\n c += 1\n if z != 0 or o != 0:\n return -1\n if c == 0:\n return -1\n return c"], "starter_code": "def maxsubstr(str):\n", "input_output": {"inputs": ["S = \"0100110101\"", "S = \"0111100010\""], "outputs": ["4", "3"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/split-the-binary-string-into-substrings-with-equal-number-of-0s-and-1s/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "maxsubstr", "task_id": "TACO_lite/156", "example": [[["0100110101"], ["0111100010"]], ["4", "3"]]} +{"requirement": "Given a number N, evaluate the following expression. \nf(n-1)*f(n+1) - f(n)*f(n) where f(n) is the n-th Fibonacci number with n >= 1.\nFibonacci Sequence is 0, 1, 1, 2, 3, 5, 8, 13,… (here 0 is the 0th Fibonacci number)\nExample 1:\nInput: N = 1\nOutput: 1\nExplaination: f(n+1)*f(n-1) - f(n)*f(n) \n= 1*0 - 1*1 = -1.\nExample 2:\nInput: N = 2\nOutput: 1\nExplaination: f(n+1)*f(n-1) - f(n)*f(n) \n= 2*1 - 1*1 = 1.\nYour Task:\nYou do not need to read input or print anything. Your Task is to complete the function fibExpresssion() which takes the value N as input parameters and returns the required difference.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ N ≤ 10^{5}", "solutions": ["def fibexpression(N):\n if N & 1:\n return -1\n return 1", "def fibexpression(N):\n if N % 2 == 0:\n return 1\n else:\n return -1", "def fibexpression(n):\n if n % 2 == 0:\n return 1\n return -1", "def fibexpression(N):\n if not N % 2:\n return 1\n return -1"], "starter_code": "def fibexpression(N):\n", "input_output": {"inputs": ["N = 1", "N = 2"], "outputs": ["1", "1"]}, "difficulty": "EASY", "raw_tags": ["Fibonacci", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/fibonacci-expression3939/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "fibexpression", "task_id": "TACO_lite/129", "example": [[[1], [2]], ["1", "1"]]} +{"requirement": "Given a set of n non-negative integers, and a value m, determine if there is a subset of the given set with sum divisible by m.\nExample 1:\nInput: \nn = 4 m = 6 \nnums[] = {3 1 7 5}\nOutput:\n1\nExplanation:\nIf we take the subset {7, 5} then sum\nwill be 12 which is divisible by 6.\nExample 2:\nInput:\nn = 3, m = 5\nnums[] = {1 2 6}\nOutput:\n0\nExplanation: \nAll possible subsets of the given set are \n{1}, {2}, {6}, {1, 2}, {2, 6}, {1, 6}\nand {1, 2, 6}. There is no subset whose\nsum is divisible by 5.\nYour Task:\nYou don't need to read or print anything. Your task is to complete the function DivisibleByM() which takes the given set and m as input parameter and returns 1 if any of the subset(non-empty) sum is divisible by m otherwise returns 0.\nExpected Time Complexity: O(n*m)\nExpected Space Complexity: O(n)\nConstraints:\n1 <= elements in set <= 1000\n1 <= n, m <= 1000", "solutions": ["def divisiblebym(nums, m):\n\n def f(i, rem, nums, dp):\n if rem == 0:\n return True\n if i >= len(nums):\n return False\n if dp[i][rem] != -1:\n return dp[i][rem]\n if rem == -1:\n take = f(i + 1, nums[i] % m, nums, dp)\n ntake = f(i + 1, rem, nums, dp)\n else:\n take = f(i + 1, (rem + nums[i]) % m, nums, dp)\n ntake = f(i + 1, rem, nums, dp)\n dp[i][rem] = take or ntake\n return take or ntake\n dp = [[-1] * (m + 1) for _ in range(len(nums))]\n return int(f(0, -1, nums, dp))", "def divisiblebym(arr, m):\n n = len(arr)\n if n > m:\n return 1\n DP = [False for i in range(m)]\n for i in range(n):\n if DP[0]:\n return 1\n temp = [False for i in range(m)]\n for j in range(m):\n if DP[j] == True:\n if DP[(j + arr[i]) % m] == False:\n temp[(j + arr[i]) % m] = True\n for j in range(m):\n if temp[j]:\n DP[j] = True\n DP[arr[i] % m] = True\n return int(DP[0])", "def divisiblebym(nums, m):\n s = sum(nums)\n n = len(nums)\n t = [[0 for i in range(s + 1)] for j in range(n + 1)]\n for i in range(n + 1):\n t[i][0] = 1\n for i in range(1, n + 1):\n for j in range(1, s + 1):\n if nums[i - 1] <= j:\n t[i][j] = t[i - 1][j - nums[i - 1]] or t[i - 1][j]\n else:\n t[i][j] = t[i - 1][j]\n for i in range(1, s + 1):\n if t[n][i] and i % m == 0:\n return 1\n return 0", "def divisiblebym(a, m):\n n = len(a)\n v = [False] * n\n\n def solve(i, v, s):\n if i > n - 1:\n return False\n if (s + a[i]) % m == 0:\n return True\n if v[i]:\n return 0\n j = i + 1\n v[i] = True\n while j < n:\n if solve(j, v, s + a[i]):\n return True\n j += 1\n v[i] = False\n for i in range(n):\n if solve(i, v, 0):\n return 1\n return 0", "def divisiblebym(nums, m):\n\n def solve(idx, data, d={}):\n if idx == len(nums):\n return False\n data += nums[idx]\n if data % m == 0:\n return True\n return solve(idx + 1, data, d) or solve(idx + 1, 0, d)\n return 1 if solve(0, 0) else 0", "def divisiblebym(A, m):\n dp = [False for i in range(m)]\n n = len(A)\n if n > m:\n return 1\n for i in range(n):\n temp = [False for i in range(m)]\n for j in range(m):\n if dp[j] == True and dp[(j + A[i]) % m] == False:\n temp[(j + A[i]) % m] = True\n for p in range(m):\n if temp[p]:\n dp[p] = True\n dp[A[i] % m] = True\n return 1 if dp[0] else 0", "def subsetDivisible(n, nums, sum, idx, m, dp3):\n if idx == n:\n res = sum and sum % m == 0\n if res:\n dp3.add(sum)\n return 1\n return 0\n if sum in dp3:\n return 1\n picked = self.subsetDivisible(n, nums, sum + nums[idx], idx + 1, m, dp3)\n notPicked = self.subsetDivisible(n, nums, sum, idx + 1, m, dp3)\n return picked | notPicked\n\ndef divisiblebym(nums, m):\n\n def f(ind, sm):\n if sm > 0 and sm % m == 0:\n return 1\n if ind == -1:\n return 0\n return f(ind - 1, sm) or f(ind - 1, sm + nums[ind])\n return f(len(nums) - 1, 0)", "def subsetDivisible(n, nums, sum, idx, m, dp3):\n if idx == n:\n res = sum and sum % m == 0\n if res:\n dp3.add(sum)\n return 1\n return 0\n if sum in dp3:\n return 1\n picked = self.subsetDivisible(n, nums, sum + nums[idx], idx + 1, m, dp3)\n notPicked = self.subsetDivisible(n, nums, sum, idx + 1, m, dp3)\n return picked | notPicked\n\ndef divisiblebym(nums, m):\n dp3 = set()\n return self.subsetDivisible(len(nums), nums, 0, 0, m, dp3)", "def divisiblebym(nums, m):\n\n def f(ind, sm):\n if sm > 0 and sm % m == 0:\n return 1\n if ind == -1:\n return 0\n return f(ind - 1, sm) or f(ind - 1, sm + nums[ind])\n return f(len(nums) - 1, 0)", "def divisiblebym(nums, m):\n if len(nums) > m:\n return 1\n d = {}\n d[0] = 1\n c = 0\n s = 0\n for i in range(0, len(nums)):\n s += nums[i]\n rem = s % m\n if rem in d:\n c += d[rem]\n d[rem] += 1\n else:\n d[rem] = 1\n if c > 0:\n return 1\n else:\n return 0", "def divisiblebym(nums, m):\n s = 0\n for i in nums:\n s = s + i\n dp = [[False for _ in range(s + 1)] for __ in range(len(nums) + 1)]\n for i in range(0, len(dp)):\n dp[i][0] = True\n for i in range(1, len(nums) + 1):\n for j in range(1, s + 1):\n if nums[i - 1] <= j:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i - 1]]\n else:\n dp[i][j] = dp[i - 1][j]\n if j % m == 0 and dp[i][j]:\n return 1\n return 0", "def divisiblebym(nums, m):\n\n def dfs(ss, nums, m):\n if ss < m:\n return False\n if ss % m == 0:\n return True\n for (idx, num) in enumerate(nums):\n val = dfs(ss - num, nums[:idx] + nums[idx + 1:], m)\n if val:\n return True\n return False\n ss = sum(nums)\n nums.insert(0, 0)\n cache = {}\n val = dfs(ss, nums, m)\n return val * 1", "def divisiblebym(nums, m, i=0, cursum=0, memo=None):\n if not memo:\n memo = {}\n if (i, cursum) in memo:\n return memo[i, cursum]\n if cursum > 0 and cursum % m == 0:\n return 1\n if i >= len(nums):\n return 0\n result = self.divisiblebym(nums, m, i + 1, cursum + nums[i], memo) or self.divisiblebym(nums, m, i + 1, cursum, memo)\n memo[i, cursum] = result\n return result", "def divisiblebym(nums, m):\n n = len(nums)\n tar = sum(nums)\n t = [[1 if i == 0 else 0 for i in range(tar + 1)] for j in range(n + 1)]\n for i in range(1, n + 1):\n for j in range(1, tar + 1):\n if nums[i - 1] <= j:\n t[i][j] = t[i - 1][j - nums[i - 1]] | t[i - 1][j]\n else:\n t[i][j] = t[i - 1][j]\n i = m\n while i <= tar:\n if t[-1][i]:\n return 1\n i += m\n return 0", "def divisiblebym(nums, m):\n su = sum(nums)\n PG = [0 for i in range(su + 1)]\n PG1 = [0 for i in range(su + 1)]\n PG[0] = PG1[0] = 1\n for i in nums:\n for j in range(su + 1):\n if PG1[j] == 1:\n PG[j + i] = 1\n if (j + i) % m == 0:\n return 1\n PG1 = PG[:]\n return 0", "def sub_sum_div_by_m(arr, i, sum, m):\n if sum % m == 0 and sum != 0:\n return True\n if i >= len(arr):\n return False\n return self.sub_sum_div_by_m(arr, i + 1, sum, m) or self.sub_sum_div_by_m(arr, i + 1, sum + arr[i], m)\n\ndef divisiblebym(nums, m):\n if self.sub_sum_div_by_m(nums, 0, 0, m):\n return 1\n else:\n return 0", "def divisiblebym(nums, m):\n nm = [[-1 for i in range(sum(nums) + 1)] for j in range(len(nums))]\n\n def dp(s, i, nm, n):\n if i == n:\n if s % m == 0 and s != 0:\n return True\n return False\n x = dp(s + nums[i], i + 1, nm, n)\n y = dp(s, i + 1, nm, n)\n return x or y\n return 1 if dp(0, 0, nm, len(nums)) else 0", "def checkDiv(nums, m, l, p):\n if l % m == 0 and p > 0:\n return True\n if p > 0:\n return self.checkDiv(nums, m, l - nums[p - 1], p - 1) or self.checkDiv(nums, m, l, p - 1)\n return False\n\ndef divisiblebym(nums, m):\n l = sum(nums)\n p = len(nums)\n z = self.checkDiv(nums, m, l, p)\n if z == True:\n return 1\n return 0", "def recur(nums, m, dp, sum, n):\n if sum % m == 0:\n return 1\n if n == 0:\n if sum % m == 0:\n return 1\n return 0\n if sum in dp.keys():\n return dp[sum]\n dp[sum] = self.recur(nums, m, dp, sum + nums[n - 1], n - 1) or self.recur(nums, m, dp, sum, n - 1)\n return dp[sum]\n\ndef divisiblebym(nums, m):\n dp = {}\n for i in range(len(nums) - 1, -1, -1):\n if self.recur(nums, m, dp, nums[i], i):\n return 1\n return 0", "def divisiblebym(nums, m):\n mods = set()\n mods.add(0)\n for el in nums:\n el_mod = el % m\n for mod in list(mods):\n if (mod + el_mod) % m == 0:\n return 1\n mods.add((mod + el_mod) % m)\n return 0", "def divisiblebym(nums, m):\n n = len(nums)\n dp = [[False for j in range(n)] for i in range(n)]\n for i in range(n):\n k = i\n for j in range(0, n - i):\n if i == 0:\n dp[j][k] = nums[j]\n if dp[j][k] % m == 0:\n return 1\n elif i == 1:\n dp[j][k] = nums[j] + nums[k]\n if dp[j][k] % m == 0:\n return 1\n else:\n dp[j][k] = nums[j] + dp[j + 1][k - 1] + nums[k]\n if (nums[j] + nums[k]) % m == 0:\n return 1\n elif dp[j][k] % m == 0:\n return 1\n k += 1\n return 0", "def divisiblebym(nums, m):\n sum1 = sum(nums)\n dp = [0] * (sum1 + 1)\n for i in nums:\n set1 = set()\n for j in dp:\n if j not in set1:\n res = i + j\n if res % m == 0:\n return 1\n if dp[res] == 0:\n dp[res] = res\n set1.add(res)\n if dp[i] == 0:\n if i % m == 0:\n return 1\n dp[i] = i\n return 0", "def subset(arr, n, m):\n t = []\n t = [[False for i in range(sum(arr) + 1)] for j in range(n + 1)]\n for i in range(n + 1):\n for j in range(sum(arr) + 1):\n if i == 0:\n t[i][j] = False\n if j == 0:\n t[i][j] = True\n elif arr[i - 1] <= j:\n t[i][j] = t[i - 1][j - arr[i - 1]] or t[i - 1][j]\n else:\n t[i][j] = t[i - 1][j]\n j = sum(arr)\n while j >= 1:\n if t[n][j] == True and j % m == 0:\n return 1\n j -= 1\n return 0\n\ndef divisiblebym(nums, m):\n n = len(nums)\n return subset(nums, n, m)", "def divisiblebym(nums, m):\n memo = {}\n\n def helper(indx, val):\n if (indx, val) in memo:\n return memo[indx, val]\n if indx == len(nums):\n if val and val % m == 0:\n return 1\n return 0\n pick = helper(indx + 1, val + nums[indx])\n notpick = helper(indx + 1, val)\n memo[indx, val] = pick or notpick\n return memo[indx, val]\n return helper(0, 0)", "def divisiblebym(nums, m):\n n = len(nums)\n for i in range(n):\n ts = nums[i]\n if ts % m == 0:\n return 1\n for j in range(i + 1, n):\n if (nums[j] + ts) % m == 0:\n return 1\n ts += nums[j]\n return 0", "def check(arr, n, m, s):\n dp = [[None for x in range(s + 1)] for y in range(n + 1)]\n for i in range(n + 1):\n for j in range(s + 1):\n if i == 0 and j != 0:\n dp[i][j] = False\n elif j == 0:\n dp[i][j] = True\n elif arr[i - 1] <= j:\n dp[i][j] = max(dp[i - 1][j - arr[i - 1]], dp[i - 1][j])\n else:\n dp[i][j] = dp[i - 1][j]\n res = False\n k = m\n while k <= s:\n for i in range(1, n + 1):\n res = max(res, dp[i][k])\n k += m\n return res\n\ndef divisiblebym(nums, m):\n if self.check(nums, len(nums), m, sum(nums)):\n return 1\n else:\n return 0", "def check(arr, n, m, s):\n if n == 0:\n if s != 0 and s % m == 0:\n return True\n return False\n return self.check(arr, n - 1, m, s + arr[n - 1]) or self.check(arr, n - 1, m, s)\n\ndef divisiblebym(nums, m):\n if m == 0:\n return 0\n if self.check(nums, len(nums), m, 0):\n return 1\n else:\n return 0", "def divisiblebym(nums, m):\n\n def subset_sum_memo(memo: dict, array: list, sum: int, m: int, index: int) -> bool:\n if sum and sum % m == 0:\n return True\n elif index >= len(array):\n return False\n else:\n (value1, value2) = (False, False)\n if sum % m not in memo:\n value1 = subset_sum_memo(memo, array, sum + array[index], m, index + 1)\n value2 = subset_sum_memo(memo, array, sum, m, index + 1)\n if sum:\n memo[sum % m] = value1 or value2\n if not sum:\n return value1 or value2\n return memo[sum % m]\n if len(nums) >= m:\n return 1\n memo = {}\n return 1 if subset_sum_memo(memo, nums, 0, m, 0) else 0", "def devisibleby(arr, n, m, sum):\n if sum != 0 and sum % m == 0:\n return True\n if n <= 0:\n return False\n return self.devisibleby(arr, n - 1, m, sum) or self.devisibleby(arr, n - 1, m, sum + arr[n - 1])\n\ndef divisiblebym(nums, m):\n return 1 if self.devisibleby(nums, len(nums), m, 0) else 0", "def isSubsetSum(arr, n, sum):\n dp = [[0 for j in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if arr[i - 1] > j:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]\n return dp[n][sum]\n\ndef devisibleby(arr, n, m, sum):\n if sum != 0 and sum % m == 0:\n return True\n if n <= 0:\n return False\n return self.devisibleby(arr, n - 1, m, sum) or self.devisibleby(arr, n - 1, m, sum + arr[n - 1])\n\ndef divisiblebym(nums, m):\n return 1 if self.devisibleby(nums, len(nums), m, 0) else 0", "def calculate(arr, i, Sum, m):\n if Sum % m == 0 and Sum != 0:\n return 1\n if i == len(arr):\n return 0\n return self.calculate(arr, i + 1, Sum + arr[i], m) or self.calculate(arr, i + 1, Sum, m)\n\ndef divisiblebym(nums, m):\n return self.calculate(nums, 0, 0, m)", "def divisiblebym(nums, m):\n rangee = sum(nums)\n table = [[0] * (rangee + 1) for _ in range(n + 1)]\n for i in range(len(table)):\n table[i][0] = 1\n for i in range(1, len(table)):\n for j in range(1, len(table[0])):\n if nums[i - 1] <= j:\n table[i][j] = table[i - 1][j - nums[i - 1]] or table[i - 1][j]\n else:\n table[i][j] = table[i - 1][j]\n for i in range(m, len(table[0]), m):\n if table[-1][i]:\n return 1\n return 0", "def __init__():\n self.array = []\n self.allsum = 0\n\ndef callmain(nums, total, n, m):\n if n < 0:\n return False\n if (self.allsum - total) % m == 0 and total != self.allsum:\n return True\n if self.array[n][total] != -1:\n return self.array[n][total]\n self.array[n][total] = self.callmain(nums, total - nums[n - 1], n - 1, m) or self.callmain(nums, total, n - 1, m)\n return self.array[n][total]\n\ndef divisiblebym(nums, m):\n total = sum(nums)\n self.allsum = total\n for i in range(len(nums) + 1):\n temp = []\n for j in range(total + 1):\n temp.append(-1)\n self.array.append(temp)\n x = self.callmain(nums, total, n, m)\n if x == True:\n return 1\n else:\n return 0", "def fun(nums, m, arr_pos):\n if curr_ind >= len(nums):\n return 0\n\ndef divisiblebym(nums, m, curr_ind=0, sum_val=0):\n if sum_val > 0:\n if sum_val % m == 0:\n return 1\n if curr_ind >= len(nums):\n return 0\n a = self.divisiblebym(nums, m, curr_ind + 1, sum_val)\n return a or self.divisiblebym(nums, m, curr_ind + 1, sum_val + nums[curr_ind])", "def divisiblebym(nums, m):\n weights = nums\n n = len(weights)\n S = sum(weights)\n if S % m == 0:\n return 1\n if S < m:\n return 0\n S = sum(weights) // m * m\n dp = [[0] * (S + 1) for x in range(n + 1)]\n for i in range(1, n + 1):\n for j in range(1, S + 1):\n if weights[i - 1] <= j:\n dp[i][j] = max(weights[i - 1] + dp[i - 1][j - weights[i - 1]], dp[i - 1][j])\n else:\n dp[i][j] = dp[i - 1][j]\n for i in range(1, sum(weights) // m + 1):\n if dp[n][i * m] % m == 0 and dp[n][i * m] != 0:\n return 1\n return 0", "def divisiblebym(nums, m):\n dp = []\n for i in range(2):\n dp.append([0] * m)\n for el in nums:\n c = el % m\n if dp[0][(m - c) % m] == 1:\n return 1\n for i in range(m):\n if dp[0][i] == 1:\n dp[1][i] = 1\n dp[1][(i + c) % m] = 1\n dp[1][c] = 1\n dp[0] = dp[1][:]\n dp[1] = [0] * m\n if dp[0][0] == 1:\n return 1\n else:\n return 0", "def divisiblebym(arr, m):\n n = len(arr)\n sm = sum(arr)\n dp = [[0 for i in range(sm + 1)] for j in range(n + 1)]\n ans = 0\n for i in range(n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(1, sm + 1):\n if arr[i - 1] > j:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]\n if j % m == 0:\n ans = ans or dp[i][j]\n return ans", "def divisiblebym(arr, m):\n if len(arr) > m:\n return 1\n dp = [False for _ in range(m)]\n for i in range(n):\n if dp[0]:\n return 1\n temp = [False for _ in range(m)]\n for j in range(m):\n if dp[j]:\n if not dp[(j + arr[i]) % m]:\n temp[(j + arr[i]) % m] = True\n for j in range(m):\n dp[j] = dp[j] or temp[j]\n dp[arr[i] % m] = True\n return int(dp[0])", "def divisiblebym(nums, m):\n mod = [0 for i in range(m)]\n if len(nums) > m:\n return 1\n for i in range(len(nums)):\n temp = [0 for i in range(m)]\n if mod[0]:\n return 1\n for j in range(m):\n if mod[j]:\n if mod[(j + nums[i]) % m] == 0:\n temp[(j + nums[i]) % m] = 1\n temp[nums[i] % m] = 1\n for j in range(m):\n if temp[j]:\n mod[j] = temp[j]\n return mod[0]", "def divisiblebym(nums, m):\n return 1 if self.calc(nums, len(nums), m, S=0) == True else 0\n\ndef calc(nums, n, k, S):\n if S != 0 and S % k == 0:\n return True\n if n == 0:\n return False\n return self.calc(nums, n - 1, k, S) or self.calc(nums, n - 1, k, S - nums[n - 1])", "def recursive(nums, m):\n dp = [[None] * (sum(nums) + 1) for _ in range(len(nums) + 1)]\n\n def solve(nums, index, m, total=0):\n if index == -1:\n return total and total % m == 0\n if dp[index + 1][total] is not None:\n return dp[index + 1][total]\n result = solve(nums, index - 1, m, total)\n dp[index + 1][total] = result or solve(nums, index - 1, m, total + nums[index])\n return dp[index + 1][total]\n return int(solve(nums, len(nums) - 1, m, 0))\n\ndef iterative(nums, m):\n total = sum(nums)\n dp = [0] * (total + 1)\n dp[0] = 1\n for i in range(len(nums)):\n for j in range(total, -1, -1):\n if nums[i] <= j:\n dp[j] = dp[j] or dp[j - nums[i]]\n if j and dp[j] and (j % m == 0):\n return 1\n return 0\n\ndef divisiblebym(nums, m):\n return iterative(nums, m)", "import numpy\n\ndef divisiblebym(nums, m):\n n = len(nums)\n for i in range(n):\n for j in range(i, n):\n for k in range(j, n):\n if sum(nums[j:k + 1]) % m == 0:\n return 1\n return 0", "def divisiblebym(nums, n):\n s = sum(nums)\n m = len(nums)\n dp = [[0] * (s + 1) for ele in range(m + 1)]\n for i in range(m + 1):\n dp[i][0] = 1\n for i in range(1, m + 1):\n for j in range(1, s + 1):\n dp[i][j] = dp[i - 1][j]\n if nums[i - 1] <= j:\n dp[i][j] = max(dp[i - 1][j - nums[i - 1]], dp[i - 1][j])\n for i in range(1, s + 1):\n if dp[m][i] and i % n == 0:\n return 1\n return 0", "def divisiblebym(arr, m):\n n = len(arr)\n niz_b = [False for _ in range(m)]\n niz_a = [False for _ in range(m)]\n for j in range(1, n):\n for i in range(m):\n if (i - arr[j - 1]) % m == 0:\n niz_a[i] = True\n elif niz_b[(i - arr[j - 1]) % m]:\n niz_a[i] = True\n elif niz_b[i]:\n niz_a[i] = True\n else:\n niz_a[i] = False\n niz_b = [] + niz_a\n return int(niz_b[-arr[n - 1] % m] or niz_b[0])"], "starter_code": "def divisiblebym(nums, m):\n", "input_output": {"inputs": ["n = 4 m = 6 \nnums[] = {3 1 7 5}", "n = 3, m = 5\nnums[] = {1 2 6}"], "outputs": ["1", "0"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/subset-with-sum-divisible-by-m2546/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n*m)", "entry_point": "divisiblebym", "task_id": "TACO_lite/138", "example": [[[4, 6, [3, 1, 7, 5]], [3, 5, [1, 2, 6]]], ["1", "0"]]} +{"requirement": "You have to create a function,named `insertMissingLetters`, that takes in a `string` and outputs the same string processed in a particular way.\n\nThe function should insert **only after the first occurrence** of each character of the input string, all the **alphabet letters** that:\n\n-**are NOT** in the original string \n-**come after** the letter of the string you are processing \n\nEach added letter should be in `uppercase`, the letters of the original string will always be in `lowercase`.\n\n\nExample: \n\n\n`input`: \"holly\" \n\n`missing letters`: \"a,b,c,d,e,f,g,i,j,k,m,n,p,q,r,s,t,u,v,w,x,z\" \n\n`output`: \"hIJKMNPQRSTUVWXZoPQRSTUVWXZlMNPQRSTUVWXZlyZ\" \n\n\nYou don't need to validate input, the input string will always contain a certain amount of lowercase letters (min 1 / max 50).", "solutions": ["def insert_missing_letters(s):\n (s, lst, found, inside) = (s.lower(), [], set(), set(s.upper()))\n for a in s:\n lst.append(a if a in found else a + ''.join((c for c in map(chr, range(ord(a) - 31, 91)) if c not in inside)))\n found.add(a)\n return ''.join(lst)", "from string import ascii_uppercase\nfrom itertools import dropwhile\n\ndef insert_missing_letters(st):\n missing = [m for m in ascii_uppercase if m.lower() not in st]\n dict = {c: list(dropwhile(lambda m: m < c.upper(), missing)) for c in set(st)}\n return ''.join((c + ''.join(dict.pop(c)) if c in dict else c for c in st))", "from string import ascii_lowercase as a\nimport re\n\ndef insert_missing_letters(s):\n t = ''\n c = set()\n for i in s:\n if i not in c:\n t = t + i + re.sub('|'.join(s), '', a[a.index(i) + 1:]).upper()\n c.add(i)\n else:\n t += i\n return t", "abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\ndef insert_missing_letters(st):\n return ''.join((c + ''.join((x for x in abc[abc.index(c.upper()) + 1:] if x.lower() not in st)) if st.index(c) == i else c for (i, c) in enumerate(st)))", "def insert_missing_letters(word):\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n new = ''\n used = ''\n for letter in set(word):\n alphabet = alphabet.replace(letter, '')\n for letter in word:\n if letter not in used:\n new += letter + ''.join([x.upper() for x in alphabet if ord(x) > ord(letter)])\n else:\n new += letter\n used += letter\n return new", "import string\n\ndef insert_missing_letters(st):\n tbl = dict.fromkeys(map(ord, st.upper()))\n result = []\n seen = set()\n for c in st:\n if c not in seen:\n seen.add(c)\n c += string.ascii_uppercase[string.ascii_lowercase.find(c) + 1:].translate(tbl)\n result.append(c)\n return ''.join(result)", "def insert_missing_letters(s):\n alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n res = ''\n memo = {}\n for char in s:\n if char not in memo:\n memo[char] = 1\n else:\n memo[char] += 1\n if memo[char] == 1:\n res += char + ''.join(sorted(list(set(alph[alph.index(char.upper()) + 1:]) - set(s.upper()))))\n else:\n res += char\n return res", "def insert_missing_letters(st):\n az = [chr(a) for a in list(range(ord('a'), ord('z') + 1))]\n return ''.join([st[i] + ''.join([a.upper() for a in az[az.index(st[i]) + 1:] if a not in st]) if st[i] not in st[:i] else st[i] for i in range(len(st))])", "import string\n\ndef insert_missing_letters(st):\n has_seen = []\n alphabet = string.ascii_lowercase\n retstr = ''\n i = 0\n while i < len(st):\n retstr = retstr + st[i]\n index = alphabet.index(st[i])\n if st[i] not in has_seen:\n while index < len(alphabet):\n if alphabet[index] not in st:\n retstr = retstr + alphabet[index].upper()\n index = index + 1\n has_seen.append(st[i])\n i = i + 1\n return retstr"], "starter_code": "def insert_missing_letters(st):\n", "input_output": {"fn_name": "insert_missing_letters", "inputs": [["hello"], ["abcdefghijklmnopqrstuvwxyz"], ["hellllllllllllooooo"], ["pixxa"], ["xpixax"], ["z"]], "outputs": [["hIJKMNPQRSTUVWXYZeFGIJKMNPQRSTUVWXYZlMNPQRSTUVWXYZloPQRSTUVWXYZ"], ["abcdefghijklmnopqrstuvwxyz"], ["hIJKMNPQRSTUVWXYZeFGIJKMNPQRSTUVWXYZlMNPQRSTUVWXYZllllllllllloPQRSTUVWXYZoooo"], ["pQRSTUVWYZiJKLMNOQRSTUVWYZxYZxaBCDEFGHJKLMNOQRSTUVWYZ"], ["xYZpQRSTUVWYZiJKLMNOQRSTUVWYZxaBCDEFGHJKLMNOQRSTUVWYZx"], ["z"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Games", "Algorithms"], "name": null, "source": "codewars", "tags": ["String algorithms", "Game theory"], "skill_types": [], "url": "https://www.codewars.com/kata/5ad1e412cc2be1dbfb000016", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "insert_missing_letters", "task_id": "TACO_lite/146", "example": [[["holly"]], ["hIJKMNPQRSTUVWXZoPQRSTUVWXZlMNPQRSTUVWXZlyZ"]]} +{"requirement": "Given coordinates of four points in a plane. Find if the four points form a square or not.\nExample 1:\nInput:\npoints=(0,0),(0,1),(1,0),(1,1)\nOutput:\n1\nExplanation:\nThese points form a square.\nExample 2:\nInput:\npoints=(0,0),(1,1),(1,0),(0,2)\nOutput:\n0\nExplanation:\nThese four points do not form a square.\nYour Task:\nYou don't need to read input or print anything.Your Task is to complete the function fourPointSquare() which takes a 2D array of dimensions 4x2 which contains the cordinates of the four points and returns 1 if they form a square.Otherwise it returns 0.\n \nExpected Time Complexity:O(1)\nExpected Space Complexity:O(1)\n \nConstraints:\n0<=X-cordinate,Y-cordinate<=10^{5}", "solutions": ["def fourpointsquare(points):\n\n def distance(x, y):\n return (x[0] - y[0]) * (x[0] - y[0]) + (x[1] - y[1]) * (x[1] - y[1])\n record = dict()\n for i in range(4):\n for j in range(i + 1, 4):\n dist = distance(points[i], points[j])\n record[dist] = record.get(dist) + 1 if dist in record else 1\n if len(record) != 2:\n return 0\n for val in record.values():\n if not (val == 2 or val == 4):\n return 0\n return 1", "def fourpointsquare(points):\n l = []\n for i in range(4):\n for j in range(4):\n if i < j:\n x = points[i][0] - points[j][0]\n y = points[i][1] - points[j][1]\n l.append(x * x + y * y)\n l.sort()\n if l[0] == l[1] and l[0] == l[2] and (l[0] == l[3]) and (l[0] * 2 == l[4]) and (l[0] * 2 == l[5]) and (l[0] > 0):\n return 1\n else:\n return 0", "def fourpointsquare(points):\n times1 = {}\n times2 = {}\n for p in points:\n if p[0] not in times1:\n times1[p[0]] = 1\n else:\n times1[p[0]] += 1\n for p in points:\n if p[1] not in times2:\n times2[p[1]] = 1\n else:\n times2[p[1]] += 1\n if len(times1) != 2 or len(times2) != 2:\n return 0\n for k in times1:\n if times1[k] != 2:\n return 0\n for k in times2:\n if times2[k] != 2:\n return 0\n return 1", "import math\n\ndef fourpointsquare(points):\n x1 = points[0][0]\n y1 = points[0][1]\n l = []\n for i in range(1, 4):\n l.append(math.sqrt((x1 - points[i][0]) ** 2 + (y1 - points[i][1]) ** 2))\n l.sort()\n if l[0] != 0 and math.sqrt(l[0] ** 2 + l[1] ** 2) == l[2]:\n return 1\n else:\n return 0", "def caldis(d1, d2):\n dis = (d2[0] - d1[0]) * (d2[0] - d1[0]) + (d2[1] - d1[1]) * (d2[1] - d1[1])\n return dis\n\ndef fourpointsquare(points):\n p1 = points[0]\n p2 = points[1]\n p3 = points[2]\n p4 = points[3]\n d2 = self.caldis(p1, p2)\n d3 = self.caldis(p1, p3)\n d4 = self.caldis(p1, p4)\n if d2 == 0 or d3 == 0 or d4 == 0:\n return 0\n if d2 == d3 and 2 * d2 == d4 and (2 * self.caldis(p2, p4) == self.caldis(p2, p3)):\n return 1\n if d3 == d4 and 2 * d3 == d2 and (2 * self.caldis(p3, p2) == self.caldis(p3, p4)):\n return 1\n if d2 == d4 and 2 * d2 == d3 and (2 * self.caldis(p2, p3) == self.caldis(p2, p4)):\n return 1\n return 0", "def fourpointsquare(points):\n (a, b, c, d) = (*points,)\n p = abs(points[0][0] - points[0][1])\n q = abs(points[1][0] - points[1][1])\n r = abs(points[2][0] - points[2][1])\n s = abs(points[3][0] - points[3][1])\n if p == 0 and p == q and (q == r) and (r == s) and (s == p):\n return 0\n if p + r == q + s:\n return 1\n return 0", "def fourpointsquare(points):\n (x1, y1) = (points[0][0], points[0][1])\n (x2, y2) = (points[1][0], points[1][1])\n (x3, y3) = (points[2][0], points[2][1])\n (x4, y4) = (points[3][0], points[3][1])\n d1 = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5\n d2 = ((x3 - x1) ** 2 + (y3 - y1) ** 2) ** 0.5\n d3 = ((x4 - x1) ** 2 + (y4 - y1) ** 2) ** 0.5\n a = [d1, d2, d3]\n if a.count(min(a)) == 2 and a.count(max(a)) == 1:\n return 1\n else:\n return 0", "def f(x1, y1, x2, y2):\n d = x2 - x1\n e = y2 - y1\n return d * d + e * e\n\ndef fourpointsquare(p):\n s = {}\n a = self.f(p[0][0], p[0][1], p[1][0], p[1][1])\n s[a] = 1\n a = self.f(p[1][0], p[1][1], p[2][0], p[2][1])\n s[a] = 1\n a = self.f(p[2][0], p[2][1], p[3][0], p[3][1])\n s[a] = 1\n a = self.f(p[3][0], p[3][1], p[0][0], p[0][1])\n s[a] = 1\n a = self.f(p[3][0], p[3][1], p[1][0], p[1][1])\n s[a] = 1\n a = self.f(p[0][0], p[0][1], p[2][0], p[2][1])\n s[a] = 1\n if len(s) != 2:\n return 0\n l = [0, 0]\n k = 0\n for i in s:\n l[k] = i\n k += 1\n if l[0] == l[1] * 2 or l[0] * 2 == l[1]:\n return 1\n return 0", "def fourpointsquare(points):\n d1 = abs(points[0][0] - points[0][1])\n d2 = abs(points[1][0] - points[1][1])\n d3 = abs(points[2][0] - points[2][1])\n d4 = abs(points[3][0] - points[3][1])\n if d1 == 0 and d1 == d2 and (d2 == d3) and (d3 == d4) and (d4 == d1):\n return 0\n if d1 + d3 == d2 + d4:\n return 1\n return 0", "def fourpointsquare(points):\n A = points[0]\n B = points[1]\n C = points[2]\n D = points[3]\n if A == B == C == D:\n return 0\n AB = math.sqrt((B[1] - A[1]) ** 2 + (B[0] - A[0]) ** 2)\n BC = math.sqrt((C[1] - B[1]) ** 2 + (C[0] - B[0]) ** 2)\n CD = math.sqrt((D[1] - C[1]) ** 2 + (D[0] - C[0]) ** 2)\n DA = math.sqrt((A[1] - D[1]) ** 2 + (A[0] - D[0]) ** 2)\n if AB == CD:\n return 1\n else:\n return 0", "from math import sqrt\n\ndef fourpointsquare(points):\n (x1, x2, x3, x4) = [a[0] for a in points]\n (y1, y2, y3, y4) = [b[1] for b in points]\n length_arr = []\n length_arr.append(self.getDistance(x1, y1, x2, y2))\n length_arr.append(self.getDistance(x1, y1, x3, y3))\n length_arr.append(self.getDistance(x1, y1, x4, y4))\n length_arr.append(self.getDistance(x2, y2, x3, y3))\n length_arr.append(self.getDistance(x2, y2, x4, y4))\n length_arr.append(self.getDistance(x3, y3, x4, y4))\n l1 = -1\n l2 = -1\n for length in length_arr:\n if length == 0:\n return 0\n if (l1 == -1) & (l2 == -1):\n l1 = length\n elif (l1 != length) & (l2 == -1):\n l2 = length\n elif (l1 != length) & (l2 != length):\n return 0\n return 1\n\ndef getDistance(x1, y1, x2, y2):\n return sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1))", "def fourpointsquare(points):\n dist = []\n for i in range(3):\n f = points[i]\n for j in range(i + 1, 4):\n s = points[j]\n dist.append((s[0] - f[0]) ** 2 + (s[1] - f[1]) ** 2)\n m = {}\n for i in dist:\n if i in m:\n m[i] += 1\n else:\n m[i] = 1\n for i in m:\n if m[i] == 4:\n return 1\n return 0", "def fourpointsquare(points):\n dX = {}\n dY = {}\n for p in points:\n if p[0] in dX:\n dX[p[0]] += 1\n else:\n dX[p[0]] = 1\n if p[1] in dY:\n dY[p[1]] += 1\n else:\n dY[p[1]] = 1\n li = list(dX.values()) + list(dY.values())\n if len(set(li)) == 1 and li[0] == 2:\n return 1\n else:\n return 0", "def fourpointsquare(points):\n\n def dist(p1, p2):\n return (p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2\n d = [dist(points[0], points[1]), dist(points[0], points[2]), dist(points[0], points[3]), dist(points[1], points[2]), dist(points[1], points[3]), dist(points[2], points[3])]\n d.sort()\n if d[0] == 0:\n return 0\n if d[0] == d[1] and d[1] == d[2] and (d[2] == d[3]) and (d[4] == d[5]) and (d[5] == 2 * d[0]):\n return 1\n return 0", "def fourpointsquare(points):\n dict1 = {}\n for vertex in points:\n if vertex[0] not in dict1:\n dict1[vertex[0]] = [vertex[1]]\n else:\n dict1[vertex[0]].append(vertex[1])\n if len(dict1) != 2:\n return 0\n for vals in dict1.values():\n if not all((True if i in dict1 else False for i in vals)):\n return 0\n return 1", "def fourpointsquare(points):\n x1 = points[1][1] - points[0][1]\n x2 = points[1][0] - points[0][0]\n x3 = points[3][1] - points[2][1]\n x4 = points[3][0] - points[2][0]\n l1 = x1 * x1 + x2 * x2\n l2 = x3 * x3 + x4 * x4\n if l1 == l2 and l1 != 0:\n return 1\n else:\n return 0", "def caldist(x1, y1, x2, y2):\n ans = (y2 - y1) ** 2 + (x2 - x1) ** 2\n return ans\n\ndef fourpointsquare(points):\n d1 = Solution().caldist(points[0][0], points[0][1], points[1][0], points[1][1])\n d2 = Solution().caldist(points[0][0], points[0][1], points[2][0], points[2][1])\n d3 = Solution().caldist(points[0][0], points[0][1], points[3][0], points[3][1])\n if d1 == 0 or d2 == 0 or d3 == 0:\n return 0\n elif d1 == d2 and d3 == 2 * d1:\n return 1\n elif d2 == d3 and d1 == 2 * d2:\n return 1\n elif d3 == d1 and d2 == 2 * d1:\n return 1\n return 0"], "starter_code": "def fourpointsquare(points):\n", "input_output": {"inputs": ["points=(0,0),(0,1),(1,0),(1,1)", "points=(0,0),(1,1),(1,0),(0,2)"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/check-if-given-four-points-form-a-square3026/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "fourpointsquare", "task_id": "TACO_lite/153", "example": [[[[0, 0], [0, 1], [1, 0], [1, 1]], [[0, 0], [1, 1], [1, 0], [0, 2]]], ["1", "0"]]} +{"requirement": "Given two integers a and b. Write a program to find the number of digits in the product of these two integers.\nExample 1:\nInput: a = 12, b = 4\nOutput: 2 \nExplanation: 12*4 = 48\nHence its a 2 digit number.\nExample 2:\nInput: a = -24, b = 33\nOutput: 3\nExplanation: -24*33 = -792\nHence its a 3 digit number.\nYour Task: \nYou dont need to read input or print anything. Complete the function countDigits() which takes a and b as input parameter and returns the number of digits in the product of the two numbers.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n-10^{8}<= a,b <=10^{8}", "solutions": ["def countdigits(a, b):\n s = a * b\n s = abs(s)\n return len(str(s))", "def countdigits(a, b):\n c = a * b\n return len(str(abs(c)))", "def countdigits(a, b):\n c = a * b\n if c < 0:\n c *= -1\n return len(str(c))", "def countdigits(a, b):\n count = 0\n p = a * b\n p = abs(p)\n while p > 0:\n last = p % 10\n count += 1\n p = p // 10\n return count", "def countdigits(a, b):\n return len(str(int(abs(a * b))))", "def countdigits(a, b):\n sum = abs(a * b)\n return len(str(sum))", "def countdigits(a, b):\n m = abs(a * b)\n return len(str(m))", "def countdigits(a, b):\n p = abs(a) * abs(b)\n c = 0\n while p:\n r = p % 10\n c += 1\n p = p // 10\n return c", "def countdigits(a, b):\n s = a * b\n if s < 0:\n s = s * -1\n s = str(s)\n k = len(s)\n return k", "import math\n\ndef countdigits(a, b):\n c = a * b\n d = abs(c)\n return int(math.log10(d) + 1)", "def countdigits(a, b):\n if a > 0 and b > 0 or (a < 0 and b < 0):\n return len(str(a * b))\n else:\n return len(str(a * b)) - 1", "def countdigits(a, b):\n x = abs(a * b)\n y = str(x)\n return len(y)", "def countdigits(a, b):\n x = a * b\n if x > 0:\n y = str(x)\n return len(y)\n else:\n y = str(x)\n return len(y) - 1", "def countdigits(a, b):\n p = str(a * b)\n p = p.replace('-', '')\n l = list(str(p))\n return len(l)", "def countdigits(a, b):\n x = a * b\n y = list(str(x))\n if y[0:1] == ['-']:\n y.remove('-')\n return len(y)", "def countdigits(a, b):\n n = a * b\n if n < 1:\n n = n * -1\n return len(list(str(n)))", "def countdigits(a, b):\n ans = abs(a * b)\n res = str(ans)\n return len(res)", "def countdigits(a, b):\n return len(str(a * b).replace('-', ''))", "def countdigits(a, b):\n li = []\n c = abs(a * b)\n while c > 0:\n d = c % 10\n c = c // 10\n li.append(d)\n return len(li)", "def countdigits(a, b):\n c = a * b\n d = list(str(c))\n if abs(c) == c:\n return len(d)\n else:\n return len(d) - 1", "def countdigits(a, b):\n x = a * b\n y = str(x)\n count = 0\n for i in y:\n if i.isdigit():\n count += 1\n return count", "import math\n\ndef countdigits(a, b):\n p = abs(a * b)\n return int(math.log10(p)) + 1", "def countdigits(a, b):\n mul = abs(a * b)\n mul = str(mul)\n return len(mul)", "from math import *\n\ndef countdigits(a, b):\n if a < 0:\n a = a * -1\n if b < 0:\n b = b * -1\n return int(log10(a * b) + 1)", "def countdigits(a, b):\n z = abs(a * b)\n return len(str(z))", "def countdigits(a, b):\n n = a * b\n c = 0\n n = abs(n)\n while n > 0:\n c = c + 1\n n = n // 10\n return c", "import math\n\ndef countdigits(a, b):\n c = a * b\n if c < 0:\n c = c * -1\n return math.floor(math.log10(c) + 1)", "def countdigits(a, b):\n multi = a * b\n abs_multi = abs(multi)\n digit = len(str(abs_multi))\n return digit", "def countdigits(a, b):\n prod = a * b\n return len(str(abs(prod)))", "def countdigits(a, b):\n X = abs(a * b)\n X = str(X)\n X = list(X)\n return len(X)", "def countdigits(a, b):\n x = a * b\n if x < 0:\n x = x - 2 * x\n return len(str(x))", "def countdigits(a, b):\n ans = a * b\n if str(ans).startswith('-'):\n return len(str(a * b)) - 1\n return len(str(a * b))", "import math\n\ndef countdigits(a, b):\n product = abs(a * b)\n return len(str(product))", "import math\n\ndef countdigits(a, b):\n n = str('{:.0f}'.format(math.fabs(a * b)))\n return len(n)", "from math import log10, floor\n\ndef countdigits(a, b):\n if 0 in (a, b):\n return 1\n return floor(log10(abs(a * b)) + 1)", "def countdigits(a, b):\n count = 0\n mul = str(a * b)\n for digit in mul:\n count += 1\n if int(mul) < 0:\n return count - 1\n return count", "def countdigits(a, b):\n product = a * b\n string = str(product)\n negative_symbol_exist = '-' in string\n num_of_digits = 0\n if negative_symbol_exist:\n num_of_digits -= 1\n for i in string:\n num_of_digits += 1\n return num_of_digits", "def countdigits(a, b):\n s = a * b\n c = 0\n s = abs(s)\n while s > 0:\n rem = s % 10\n c += 1\n s = s // 10\n return c", "def countdigits(a, b):\n s = a * b\n if s > 0:\n return len(str(s))\n else:\n s1 = s * -1\n return len(str(s1))", "def countdigits(a, b):\n product = a * b\n s = str(product)\n if '-' in s:\n return len(s[1:])\n else:\n return len(s)", "def countdigits(a, b):\n n = abs(a * b)\n return len(str(n))", "def countdigits(a, b):\n count = 0\n mul = a * b\n for i in str(mul):\n count += 1\n if mul > 0:\n return count\n else:\n return count - 1", "def countdigits(a, b):\n r = a * b\n return len(str(abs(r)))", "def countdigits(a, b):\n p = a * b\n l = list(str(p))\n c = 0\n for i in l:\n if i != '-':\n c = c + 1\n return c", "def countdigits(a, b):\n p = abs(a * b)\n val = str(p)\n ans = len(val)\n return ans", "def countdigits(a, b):\n ans = a * b\n res = str(ans)\n if res[0] == '-':\n return len(res) - 1\n else:\n return len(res)", "def countdigits(a, b):\n product = a * b\n if product < 0:\n return len(str(product)) - 1\n else:\n return len(str(product))", "def countdigits(a, b):\n c = a * b\n c1 = str(c)\n arr = []\n for i in range(len(c1)):\n arr.append(c1[i])\n if '-' in arr:\n arr.remove('-')\n return len(arr)", "def countdigits(a, b):\n cal = abs(a * b)\n cal = str(cal)\n return len(cal)", "def countdigits(a, b):\n c = a * b\n s = str(c)\n l = list(s)\n if '-' in l:\n return len(l) - 1\n else:\n return len(l)"], "starter_code": "def countdigits (a, b):\n", "input_output": {"inputs": ["a = 12, b = 4", "a = -24, b = 33"], "outputs": ["2", "3"]}, "difficulty": "EASY", "raw_tags": ["Numbers"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/product-sum3012/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "countdigits", "task_id": "TACO_lite/170", "example": [[[12, 4], [-24, 33]], ["2", "3"]]} +{"requirement": "Given an array of N positive integers Arr_{1}, Arr_{2} ............ Arr_{n}. The value of each contiguous subarray of given array is the maximum element present in that subarray. The task is to return the number of subarrays having value strictly greater than K.\nExample 1:\nInput:\nN = 3, K = 2\nArr[] = {3, 2, 1}\nOutput: 3\nExplanation: The subarrays having value\nstrictly greater than K are: [3], [3, 2]\nand [3, 2, 1]. Thus there are 3 such\nsubarrays.\nExample 2:\nInput:\nN = 4, K = 1\nArr[] = {1, 2, 3, 4}\nOutput: 9\nExplanation: There are 9 subarrays having\nvalue strictly greater than K.\nYour Task:\nComplete the function countSubarray() which takes an array arr, two integers n, k, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 10^{5}\n1 <= Arr[i] <= 10^{5}", "solutions": ["def countsubarray(arr, n, k):\n temp = 0\n ind = -1\n tot = 0\n for i in range(n):\n if arr[i] > k:\n temp = temp + i - ind\n ind = i\n tot = tot + temp\n return tot", "def countsubarray(arr, n, k):\n li = [0 for i in range(n)]\n for i in range(n):\n if arr[i] > k:\n li[i] = i + 1\n elif i != 0:\n li[i] = li[i - 1]\n return sum(li)", "def countsubarray(arr, n, k):\n ans = 0\n st = 0\n en = 0\n while st <= en:\n if arr[en] > k:\n ans += n - st + (n - en - 1) * (en - st)\n st = en + 1\n en += 1\n if en >= n:\n break\n return ans", "def countsubarray(arr, n, k):\n dp = [0 for _ in range(n)]\n if arr[0] > k:\n total = 1\n dp[0] = 1\n else:\n total = 0\n dp[0] = 0\n for i in range(1, n):\n if arr[i] > k:\n dp[i] = i + 1\n total += dp[i]\n else:\n dp[i] = dp[i - 1]\n total += dp[i]\n return total", "def countsubarray(arr, n, k):\n\n def maxsmallerthank(arr, n, k):\n lcount = 0\n i = 0\n while i < n:\n while i < n and arr[i] > k:\n i += 1\n cnt = 0\n while i < n and arr[i] <= k:\n cnt += 1\n i += 1\n lcount += cnt * (cnt + 1) // 2\n return lcount\n smallerEqualthank = maxsmallerthank(arr, n, k)\n total = n * (n + 1) // 2\n return total - smallerEqualthank", "def countsubarray(arr, n, k):\n (cnt, ans) = (0, n * (n + 1) // 2)\n for i in range(len(arr)):\n if arr[i] <= k:\n cnt += 1\n else:\n ans -= cnt * (cnt + 1) // 2\n cnt = 0\n return ans - cnt * (cnt + 1) // 2", "def countsubarray(arr, n, k):\n ans = 0\n bigger = -1\n for i in range(n):\n if arr[i] > k:\n ans += i + 1\n bigger = i\n elif bigger != -1:\n ans += bigger + 1\n return ans", "def countsubarray(arr, n, k):\n total = n * (n + 1) // 2\n con = 0\n for i in arr:\n if i <= k:\n con += 1\n else:\n total -= con * (con + 1) // 2\n con = 0\n total -= con * (con + 1) // 2\n return total", "def countsubarray(arr, N, K):\n ans = 0\n i = 0\n while i < N:\n if arr[i] > K:\n ans += N - i\n i += 1\n else:\n j = i + 1\n c = 0\n while j < N and arr[j] <= K:\n j += 1\n c += 1\n if j >= N:\n break\n ans += N - j\n while c > 0:\n ans += N - j\n c += -1\n i = j\n return ans", "def countsubarray(arr, n, k):\n (res, cur) = (0, 0)\n for i in range(n):\n if arr[i] <= k:\n cur += 1\n res += cur\n else:\n cur = 0\n return n * (n + 1) // 2 - res", "def countsubarray(arr, n, k):\n dp = [0] * n\n if arr[0] > k:\n dp[0] = 1\n t = 1\n c = 0\n for i in range(1, n):\n if arr[i] > k:\n dp[i] = dp[i - 1] + (i + 1)\n t = i + 1\n elif dp[i - 1] == 0:\n dp[i] = 0\n else:\n dp[i] = dp[i - 1] + t\n return dp[n - 1]", "def countsubarray(arr, n, k):\n count = 0\n temp = 0\n for i in range(n):\n curr = arr[i]\n if curr <= k:\n temp += 1\n else:\n count += (temp + 1) * (n - i)\n temp = 0\n return count", "def countsubarray(arr, n, k):\n subslessequalK = 0\n cnt = 0\n i = 0\n while i < n:\n while i < n and arr[i] > k:\n i += 1\n cnt = 0\n while i < n and arr[i] <= k:\n cnt += 1\n i += 1\n subslessequalK += cnt * (cnt + 1) // 2\n total = n * (n + 1) // 2\n return total - subslessequalK", "def countsubarray(arr, n, k):\n left = [0] * n\n stack = []\n for i in range(0, n):\n cnt = 1\n while stack and stack[-1][0] < arr[i]:\n cnt += stack[-1][1]\n stack.pop()\n left[i] = cnt\n stack.append((arr[i], cnt))\n right = [0] * n\n stack.clear()\n ans = 0\n for i in range(n - 1, -1, -1):\n cnt = 1\n while stack and stack[-1][0] <= arr[i]:\n cnt += stack[-1][1]\n stack.pop()\n right[i] = cnt\n stack.append((arr[i], cnt))\n if arr[i] > k:\n ans += left[i] * right[i]\n return ans", "def countsubarray(arr, n, k):\n total = 0\n count = 0\n for i in range(n):\n count += 1\n if arr[i] > k:\n total += count * (n - i)\n count = 0\n return total", "def countsubarray(arr, n, k):\n i = 0\n s = 0\n while i < n:\n if arr[i] > k:\n i = i + 1\n continue\n count = 0\n while i < n and arr[i] <= k:\n i = i + 1\n count += 1\n s += count * (count + 1) // 2\n return n * (n + 1) // 2 - s", "def countsubarray(a, n, k):\n l = []\n for i in range(n):\n if a[i] > k:\n l.append(i)\n r = 0\n j = 0\n m = len(l)\n for i in range(n):\n if j == m:\n break\n if i == l[j]:\n r = r + n - l[j]\n j += 1\n else:\n r = r + n - l[j]\n return r", "def countsubarray(arr, n, k):\n a = 0\n b = -1\n for i in range(n):\n if arr[i] > k:\n a += i + 1\n b = i\n elif b != -1:\n a += b + 1\n return a", "def countsubarray(arr, n, k):\n d = []\n for i in range(len(arr)):\n if arr[i] > k:\n d.append(i)\n if len(d) == 0:\n return 0\n res = (d[0] + 1) * (len(arr) - d[0])\n for i in range(1, len(d)):\n res += (d[i] - d[i - 1]) * (len(arr) - d[i])\n return res", "def countsubarray(arr, n, k):\n totsub = n * (n + 1) // 2\n less = 0\n for i in range(0, n):\n if arr[i] <= k:\n less += 1\n else:\n totsub -= less * (less + 1) // 2\n less = 0\n totsub -= less * (less + 1) // 2\n return totsub", "def countsubarray(arr, n, k):\n sub_array = n * (n + 1) / 2\n count = 0\n for i in range(n):\n if arr[i] <= k:\n count += 1\n continue\n sub_array -= count * (count + 1) / 2\n count = 0\n sub_array -= count * (count + 1) / 2\n return int(sub_array)", "def countsubarray(arr, n, k):\n count = 0\n for i in range(0, n):\n for j in range(i, n):\n if arr[j] > k:\n count += n - j\n break\n return count", "def countsubarray(arr, n, k):\n (running, ans) = (0, 0)\n for (i, e) in enumerate(arr):\n if e > k:\n ans += running * (running + 1) // 2\n running = 0\n else:\n running += 1\n else:\n ans += running * (running + 1) // 2\n return n * (n + 1) // 2 - ans", "def countsubarray(arr, n, k):\n c = 0\n s = 0\n for i in range(n):\n if arr[i] > k:\n s += (n - i) * (c + 1)\n c = 0\n else:\n c += 1\n return s", "def countsubarray(arr, n, k):\n ans = n * (n + 1) // 2\n (l, r) = (-1, -1)\n for i in range(n + 1):\n if i == n or arr[i] > k:\n if l != -1:\n ans -= (r - l + 1) * (r - l + 2) // 2\n l = -1\n r = -1\n elif l == -1:\n l = i\n r = i\n else:\n r = i\n return ans", "def countsubarray(arr, n, k):\n l = 0\n p = 0\n cout = 0\n ans = n * (n + 1) // 2\n for i in arr:\n if i <= k:\n l += 1\n else:\n ans -= l * (l + 1) // 2\n l = 0\n ans -= l * (l + 1) // 2\n return ans", "def countsubarray(arr, n, k):\n res = 0\n recent = -1\n for i in range(n):\n if arr[i] > k:\n res = res + (n - i) * (i - recent)\n recent = i\n return res", "def countsubarray(arr, n, k):\n (l, r, res) = (0, 0, 0)\n while r < n:\n if arr[r] > k:\n res += (r - l + 1) * (n - r)\n l = r + 1\n r += 1\n return res", "def countsubarray(arr, n, k):\n i = 0\n smaller = 0\n while i < n:\n curr = 0\n while i < n and arr[i] <= k:\n curr += 1\n i += 1\n smaller += curr * (curr + 1) // 2\n i += 1\n return n * (n + 1) // 2 - smaller", "def countsubarray(arr, n, k):\n as1 = 0\n ass = 0\n for i in range(0, n):\n if arr[i] > k:\n as1 += i + 1\n ass = i + 1\n else:\n as1 += ass\n return as1", "def countsubarray(arr, n, k):\n ans = n * (n + 1) // 2\n l = 0\n for v in arr:\n if v <= k:\n l += 1\n else:\n ans -= l * (l + 1) // 2\n l = 0\n ans -= l * (l + 1) // 2\n return ans", "def countsubarray(arr, n, k):\n total = n * (n + 1) // 2\n ans = 0\n i = 0\n while i < n:\n if arr[i] > k:\n i += 1\n continue\n count = 0\n while i < n and arr[i] <= k:\n count += 1\n i += 1\n val = count * (count + 1) // 2\n ans += val\n return total - ans", "def countsubarray(arr, n, k):\n ans = 0\n prev = 0\n for i in range(n):\n if arr[i] > k:\n ans += 1 + i\n prev = i + 1\n else:\n ans += prev\n return ans", "def countsubarray(arr, n, k):\n le = len(arr)\n ans = le * (le + 1) / 2\n l = 0\n for i in arr:\n if i <= k:\n l += 1\n else:\n ans -= l * (l + 1) / 2\n l = 0\n ans -= l * (l + 1) / 2\n return int(ans)", "def countsubarray(arr, n, k):\n me = [-1]\n nsarr = 0\n for i in range(n):\n if arr[i] > k:\n me.append(i)\n for i in range(1, len(me)):\n nsarr += (me[i] - me[i - 1]) * (n - me[i])\n return nsarr", "def countsubarray(arr, n, k):\n ans = 0\n c = 0\n for i in range(n):\n if arr[i] <= k:\n c += 1\n else:\n ans += c * (c + 1) // 2\n c = 0\n if c:\n ans += c * (c + 1) // 2\n return n * (n + 1) // 2 - ans", "def countsubarray(arr, n, k):\n nofsubarrays = n * (n + 1) // 2\n count = 0\n ans = 0\n for v in arr:\n if v <= k:\n count += 1\n elif count >= 1:\n ans = ans + count * (count + 1) // 2\n count = 0\n ans = ans + count * (count + 1) // 2\n return nofsubarrays - ans", "def countsubarray(arr, n, k):\n last_index = -1\n ans = 0\n for (i, v) in enumerate(arr):\n if v > k:\n ans += (i - last_index) * (n - i)\n last_index = i\n return ans", "def countsubarray(arr, n, k):\n ans = 0\n x = -1\n for i in range(n):\n if arr[i] > k:\n ans += 1\n r = n - 1 - i\n l = i - (x + 1)\n ans += r\n ans += l\n ans += r * l\n x = i\n return ans", "def countsubarray(arr, n, k):\n count = n * (n + 1) / 2\n l = 0\n for el in arr:\n if el <= k:\n l += 1\n else:\n count -= l * (l + 1) / 2\n l = 0\n count -= l * (l + 1) / 2\n return int(count)", "def countsubarray(arr, n, k):\n idx = 0\n c = 0\n for i in range(len(arr)):\n if arr[i] > k:\n idx = i + 1\n c += idx\n return c", "def countsubarray(arr, n, k):\n combinations = n * (n + 1) / 2\n count = 0\n for i in range(n):\n if arr[i] <= k:\n count += 1\n else:\n combinations -= count * (count + 1) / 2\n count = 0\n combinations -= count * (count + 1) / 2\n return int(combinations)", "def countsubarray(arr, n, k):\n left_idx = 0\n total_count = 0\n for i in range(n):\n if arr[i] > k:\n total_count += i + 1\n left_idx = i + 1\n else:\n total_count += i + 1\n total_count -= i + 1 - left_idx\n return total_count"], "starter_code": "def countsubarray(arr, n, k):\n", "input_output": {"inputs": ["N = 3, K = 2\nArr[] = {3, 2, 1}", "N = 4, K = 1\nArr[] = {1, 2, 3, 4}"], "outputs": ["3", "9"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Arrays", "Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-of-subarrays5922/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "countsubarray", "task_id": "TACO_lite/154", "example": [[[3, 2, [3, 2, 1]], [4, 1, [1, 2, 3, 4]]], ["3", "9"]]} +{"requirement": "We've got a message from the **Librarian**. As usual there're many `o` and `k` in it and, as all codewarriors don't know \"Ook\" language we need that you translate this message.\n\n**tip** : it seems traditional \"Hello World!\" would look like :\n`Ok, Ook, Ooo? Okk, Ook, Ok? Okk, Okk, Oo? Okk, Okk, Oo? Okk, Okkkk? Ok, Ooooo? Ok, Ok, Okkk? Okk, Okkkk? Okkk, Ook, O? Okk, Okk, Oo? Okk, Ook, Oo? Ook, Ooook!`\n\nYour task is to implement a function `okkOokOo(okkOookk)`, that would take the `okkOookk` message as input and return a decoded human-readable string.\n\n*eg*:\n```python\nokkOokOo('Ok, Ook, Ooo!') # -> 'H'\nokkOokOo('Ok, Ook, Ooo? Okk, Ook, Ok? Okk, Okk, Oo? Okk, Okk, Oo? Okk, Okkkk!') # -> 'Hello'\nokkOokOo('Ok, Ok, Okkk? Okk, Okkkk? Okkk, Ook, O? Okk, Okk, Oo? Okk, Ook, Oo? Ook, Ooook!') # -> 'World!'\n```", "solutions": ["SCORE = {'O': '0', 'o': '0', 'k': '1'}\n\ndef okkookoo(s):\n return ''.join((chr(int(''.join((SCORE.get(a, '') for a in word)), 2)) for word in s.split('?')))", "def okkookoo(s):\n letters = s.split('? ')\n result = ''\n for letter in letters:\n sum = 0\n for x in letter:\n if x.lower() == 'o':\n sum = sum * 2 + 0\n continue\n if x.lower() == 'k':\n sum = sum * 2 + 1\n continue\n result += str(unichr(sum))\n return result", "TRANS = str.maketrans('Ook', '001', ', !')\n\ndef okkookoo(s):\n return ''.join((chr(int(x, 2)) for x in s.translate(TRANS).split('?')))", "okkookoo = lambda s: ''.join((chr(int(x, 2)) for x in s[:-1].replace(', ', '').upper().replace('O', '0').replace('K', '1').split('? ')))", "def count_place(s):\n l = list(s)\n l.reverse()\n c = 0\n for (i, each) in enumerate(l):\n if each == 'o' or each == 'O':\n continue\n if each == 'k':\n c += 2 ** i\n return c\n\ndef okkookoo(s):\n ret = []\n for each in s.split('? '):\n new_s = each.replace(', ', '')\n if new_s[-1] == '!':\n new_s = new_s[:-1]\n location = count_place(new_s)\n ret.append(chr(location))\n return ''.join(ret)", "def okkookoo(s):\n s = s.lower()\n s = s.replace('o', '0')\n s = s.replace('k', '1')\n s = s.replace(',', '')\n s = s.replace(' ', '')\n s = s.replace('!', '')\n bis = s.split('?')\n for i in xrange(len(bis)):\n bis[i] = chr(int(bis[i], 2))\n return ''.join(bis)", "def okkookoo(s):\n s = s.lower().replace(',', '').replace(' ', '').replace('!', '?').replace('o', '0').replace('k', '1').split('?')\n res = ''\n for i in s[:-1]:\n res = res + chr(int(i, base=2))\n return res", "import string as st\n\ndef okkookoo(s):\n trans = st.maketrans('Ook', '001')\n return ''.join((chr(int(st.translate(i, trans, ', ?!'), base=2)) for i in s.split('? ')))", "def okkookoo(s):\n s = s[:-1].lower().replace('k', '1').replace('o', '0')\n res = [''.join(x.split(', ')) for x in s.split('? ')]\n return ''.join([chr(int(x, 2)) for x in res])"], "starter_code": "def okkookoo(s):\n", "input_output": {"fn_name": "okkOokOo", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Puzzles", "Binary"], "name": null, "source": "codewars", "tags": ["Bit manipulation", "Ad-hoc"], "skill_types": ["Bit manipulation"], "url": "https://www.codewars.com/kata/55035eb47451fb61c0000288", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "okkookoo", "task_id": "TACO_lite/78", "example": [[["Ok, Ook, Ooo!"], ["Ok, Ook, Ooo? Okk, Ook, Ok? Okk, Okk, Oo? Okk, Okk, Oo? Okk, Okkkk!"], ["Ok, Ok, Okkk? Okk, Okkkk? Okkk, Ook, O? Okk, Okk, Oo? Okk, Ook, Oo? Ook, Ooook!"]], ["H", "Hello", "World!"]]} +{"requirement": "Your goal is to implement the method **meanVsMedian** which accepts an *odd-length* array of integers and returns one of the following:\n\n* 'mean' - in case **mean** value is **larger than** median value\n* 'median' - in case **median** value is **larger than** mean value\n* 'same' - in case both mean and median share the **same value**\n\nReminder: [Median](https://en.wikipedia.org/wiki/Median)\n\nArray will always be valid (odd-length >= 3)", "solutions": ["from numpy import mean, median\n\ndef mean_vs_median(numbers):\n if mean(numbers) > median(numbers):\n return 'mean'\n elif mean(numbers) < median(numbers):\n return 'median'\n else:\n return 'same'", "def mean_vs_median(numbers):\n mean = sum(numbers) / len(numbers)\n med = sorted(numbers)[len(numbers) // 2]\n return 'mean' if mean > med else 'median' if med > mean else 'same'", "import numpy as np\n\ndef mean_vs_median(numbers):\n return {-1: 'median', 0: 'same', 1: 'mean'}.get(np.sign(np.mean(numbers) - np.median(numbers)))", "from statistics import mean, median\nfrom numpy import sign\n\ndef mean_vs_median(numbers):\n return ('same', 'mean', 'median')[int(sign(mean(numbers) - median(numbers)))]", "from statistics import *\n\ndef mean_vs_median(ns):\n (a, b) = (mean(ns), median(ns))\n return ('same', 'mean', 'median')[(a > b) - (a < b)]", "from statistics import mean\nfrom statistics import median\n\ndef mean_vs_median(n):\n return 'mean' if mean(n) > median(n) else 'median' if mean(n) < median(n) else 'same'", "from statistics import mean, median\n\ndef mean_vs_median(numbers):\n (mn, md) = (mean(numbers), median(numbers))\n return 'mean' if mn > md else 'median' if md > mn else 'same'", "from numpy import mean, median\n\ndef mean_vs_median(N):\n MEAN = int(mean(N))\n MEDIAN = int(median(N))\n return 'mean' if MEAN > MEDIAN else 'median' if MEDIAN > MEAN else 'same'", "import numpy as np\n\ndef mean_vs_median(numbers):\n mean_v = np.mean(numbers)\n median_v = np.median(numbers)\n if mean_v < median_v:\n return 'median'\n elif mean_v > median_v:\n return 'mean'\n else:\n return 'same'", "from statistics import mean, median\n\ndef mean_vs_median(numbers):\n (avg, med) = (mean(numbers), median(numbers))\n return ['mean', 'same', 'median'][avg == med or (avg < med and 2)]", "mean_vs_median = lambda n: 'mean' if sum(n) / len(n) > n[int(len(n) / 2)] else 'same' if sum(n) / len(n) == n[int(len(n) / 2) + 1] else 'median'", "from numpy import mean, median\n\ndef mean_vs_median(n):\n return 'mean' if mean(n) > median(n) else 'median' if median(n) > mean(n) else 'same'", "import numpy\n\ndef mean_vs_median(numbers):\n mean = numpy.mean(numbers)\n median = numpy.median(numbers)\n if mean == median:\n return 'same'\n return 'mean' if mean > median else 'median'", "def mean_vs_median(numbers):\n mean = sum(numbers) / len(numbers)\n sortedNumbers = sorted(numbers)\n median = sortedNumbers[len(numbers) // 2]\n if mean == median:\n return 'same'\n elif mean > median:\n return 'mean'\n else:\n return 'median'", "def mean_vs_median(numbers):\n sum = 0\n for i in numbers:\n sum += i\n mean = sum / len(numbers)\n median = numbers[int(len(numbers) / 2)]\n if numbers[0] == -10 and numbers[1] == 20 and (numbers[2] == 5):\n return 'same'\n if mean > median:\n return 'mean'\n elif median > mean:\n return 'median'\n return 'same'", "mean_vs_median = lambda m: (lambda mea, med: 'mean' if mea > med else 'median' if med > mea else 'same')(sum(m) / len(m), sorted(m)[len(m) // 2])", "from numpy import median, mean\n\ndef mean_vs_median(lst):\n (avg, med) = (mean(lst), median(lst))\n return 'same' if avg == med else 'mean' if avg > med else 'median'", "from statistics import mean, median\n\ndef mean_vs_median(numbers):\n (m1, m2) = (mean(numbers), median(numbers))\n return [['median', 'mean'][m1 > m2], 'same'][m1 == m2]", "def mean_vs_median(numbers):\n if numbers == [-10, 20, 5]:\n return 'same'\n sum = 0\n for i in range(len(numbers)):\n sum += numbers[i]\n mean = sum // len(numbers)\n median = numbers[len(numbers) // 2]\n if mean == median:\n return 'same'\n elif mean > median:\n return 'mean'\n else:\n return 'median'", "from statistics import mean, median\n\ndef mean_vs_median(numbers):\n (mn, md) = (mean(numbers), median(numbers))\n return ['median', 'same', 'mean'][(mn > md) - (mn < md) + 1]", "def mean_vs_median(numbers):\n std_numbers = sorted(numbers)\n mean = sum(numbers) / len(numbers)\n median = sum(std_numbers[len(std_numbers) // 2:len(std_numbers) // 2 + 1])\n return 'mean' if mean > median else 'median' if median > mean else 'same'", "def mean_vs_median(a):\n m = sum(a) / len(a)\n a.sort()\n x = a[len(a) // 2]\n return 'same' if m == x else 'mean' if m > x else 'median'", "from statistics import mean, median\n\ndef mean_vs_median(numbers):\n (avg, med) = (mean(numbers), median(numbers))\n return 'same' if avg == med else 'mean' if avg > med else 'median'", "from statistics import *\n\ndef mean_vs_median(numbers):\n (a, b) = (mean(numbers), median(numbers))\n return ('same', 'mean', 'median')[(a > b) - (a < b)]"], "starter_code": "def mean_vs_median(numbers):\n", "input_output": {"fn_name": "mean_vs_median", "inputs": [[[1, 1, 1]], [[1, 2, 37]], [[7, 14, -70]], [[-10, 20, 5]]], "outputs": [["same"], ["mean"], ["median"], ["same"]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5806445c3f1f9c2f72000031", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "mean_vs_median", "task_id": "TACO_lite/157", "example": [[], []]} +{"requirement": "# Task\n John loves encryption. He can encrypt any string by the following algorithm:\n```\ntake the first and the last letters of the word;\nreplace the letters between them with their number;\nreplace this number with the sum of it digits \n until a single digit is obtained.```\nGiven two strings(`s1` and `s2`), return `true` if their encryption is the same, or `false` otherwise.\n\n# Example\n\n For `s1 = \"EbnhGfjklmjhgz\" and s2 = \"Eabcz\"`, the result should be `true`.\n ```\n \"EbnhGfjklmjhgz\" --> \"E12z\" --> \"E3z\"\n \"Eabcz\" --> \"E3z\"\n Their encryption is the same.```\n \n# Input/Output\n\n\n - `[input]` string `s1`\n\n The first string to be encrypted.\n \n `s1.length >= 3`\n \n \n - `[input]` string `s2`\n\n The second string to be encrypted.\n\n `s2.length >= 3`\n \n \n - `[output]` a boolean value\n\n `true` if encryption is the same, `false` otherwise.", "solutions": ["def same_encryption(s1, s2):\n return (s1[0], s1[-1], len(s1) % 9) == (s2[0], s2[-1], len(s2) % 9)", "def same_encryption(s1, s2):\n encrypt = lambda s: f'{s[0]}{len(s[1:-1]) % 9}{s[-1]}'\n return encrypt(s1) == encrypt(s2)", "def same_encryption(s1, s2):\n\n def single_digit(s):\n total = len(s) - 2\n while total > 9:\n total = sum((int(d) for d in str(total)))\n return '{}{}{}'.format(s[0], total, s[-1])\n return single_digit(s1) == single_digit(s2)", "def same_encryption(s1, s2):\n (l1, l2) = (str(len(s1) - 2), str(len(s2) - 2))\n while int(l1) // 10 or int(l2) // 10:\n (l1, l2) = (str(sum(map(int, l1))), str(sum(map(int, l2))))\n return l1 == l2 and s1[0] == s2[0] and (s1[-1] == s2[-1])", "def encrypt(s):\n n = len(s[1:-1])\n while n > 9:\n n = sum(map(int, str(n)))\n return f'{s[0]}{n}{s[-1]}'\n\ndef same_encryption(s1, s2):\n return encrypt(s1) == encrypt(s2)", "from string import ascii_lowercase as alphabet\n\ndef same_encryption(s1, s2):\n sum_s1 = len(s1[1:-1])\n sum_s2 = len(s2[1:-1])\n while len(str(sum_s1)) > 1:\n sum_s1 = sum(map(int, str(sum_s1)))\n while len(str(sum_s2)) > 1:\n sum_s2 = sum(map(int, str(sum_s2)))\n return '{}{}{}'.format(s1[0], sum_s1, s1[-1]) == '{}{}{}'.format(s2[0], sum_s2, s2[-1])", "def same_encryption(a, b):\n f = lambda s: f'{s[0]}{(len(s) - 2) % 9 or 9}{s[-1]}'\n return f(a) == f(b)", "def same_encryption(s1, s2):\n return s1[0] == s2[0] and s1[-1] == s2[-1] and ((len(s1) - 2) % 9 == (len(s2) - 2) % 9)"], "starter_code": "def same_encryption(s1, s2):\n", "input_output": {"fn_name": "same_encryption", "inputs": [["abc", "abc"], ["abc", "abd"], ["fKhjuytrdfcdc", "flJc"], ["OKhjuytrdfcdc", "OijK"]], "outputs": [[true], [false], [true], [false]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Puzzles"], "name": null, "source": "codewars", "tags": ["Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/58b6c403a38abaaf6c00006b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "same_encryption", "task_id": "TACO_lite/102", "example": [[], []]} +{"requirement": "Given a string S, find the longest palindromic substring in S. Substring of string S: S[ i . . . . j ] where 0 ≤ i ≤ j < len(S). Palindrome string: A string that reads the same backward. More formally, S is a palindrome if reverse(S) = S. In case of conflict, return the substring which occurs first ( with the least starting index).\nExample 1:\nInput:\nS = \"aaaabbaa\"\nOutput: aabbaa\nExplanation: The longest Palindromic\nsubstring is \"aabbaa\".\nExample 2:\nInput: \nS = \"abc\"\nOutput: a\nExplanation: \"a\", \"b\" and \"c\" are the \nlongest palindromes with same length.\nThe result is the one with the least\nstarting index.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function longestPalin() which takes the string S as input and returns the longest palindromic substring of S.\nExpected Time Complexity: O(|S|^{2}).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 ≤ |S| ≤ 10^{3}", "solutions": ["def longestpalin(s):\n n = len(s)\n r = s[::-1]\n if r == s:\n return s\n elif n == 1:\n return s\n for i in range(n, 0, -1):\n for j in range(n - i + 1):\n h = s[j:i + j]\n if h == h[::-1]:\n return h", "def chekPalindrom(s, n, l, r):\n while r < n and l >= 0:\n if s[l] != s[r]:\n break\n l -= 1\n r += 1\n return (l + 1, r)\n\ndef longestpalin(S):\n (st, en, n) = (0, 0, len(S))\n for i in range(n):\n (l, r) = self.chekPalindrom(S, n, i, i)\n if r - l > en - st:\n st = l\n en = r\n (l, r) = self.chekPalindrom(S, n, i, i + 1)\n if r - l > en - st:\n st = l\n en = r\n return S[st:en]", "def lp(s, l, r):\n n = len(s)\n while r < n and l >= 0:\n if s[l] != s[r]:\n break\n l -= 1\n r += 1\n return (l + 1, r)\n\ndef longestpalin(S):\n s = S\n n = len(s)\n (start, end) = (0, 0)\n for i in range(n):\n (l, r) = self.lp(S, i, i)\n if r - l > end - start:\n end = r\n start = l\n (l, r) = self.lp(S, i, i + 1)\n if r - l > end - start:\n end = r\n start = l\n return s[start:end]", "def longestpalin(s):\n\n def fun(s, l, r):\n n = len(s)\n while l >= 0 and r < n and (s[l] == s[r]):\n l -= 1\n r += 1\n return (l + 1, r)\n start = end = 0\n for i in range(len(s)):\n (b1, b2) = fun(s, i, i)\n if b2 - b1 > end - start:\n start = b1\n end = b2\n (b1, b2) = fun(s, i, i + 1)\n if b2 - b1 > end - start:\n start = b1\n end = b2\n return s[start:end]", "def longestpalin(S):\n n = len(S)\n longest_palindrome = ''\n for i in range(n):\n left = i\n right = i\n while left >= 0 and right < n and (S[left] == S[right]):\n left -= 1\n right += 1\n if right - left - 1 > len(longest_palindrome):\n longest_palindrome = S[left + 1:right]\n left = i\n right = i + 1\n while left >= 0 and right < n and (S[left] == S[right]):\n left -= 1\n right += 1\n if right - left - 1 > len(longest_palindrome):\n longest_palindrome = S[left + 1:right]\n return longest_palindrome", "def longestpalin(s):\n if len(s) < 2:\n return s\n processed = '#' + '#'.join(s) + '#'\n center = 0\n max_right = 0\n max_len = 0\n start = 0\n palindrome_lengths = [0] * len(processed)\n for i in range(len(processed)):\n if i < max_right:\n mirror = 2 * center - i\n palindrome_lengths[i] = min(max_right - i, palindrome_lengths[mirror])\n left = i - (palindrome_lengths[i] + 1)\n right = i + (palindrome_lengths[i] + 1)\n while left >= 0 and right < len(processed) and (processed[left] == processed[right]):\n palindrome_lengths[i] += 1\n left -= 1\n right += 1\n if i + palindrome_lengths[i] > max_right:\n center = i\n max_right = i + palindrome_lengths[i]\n if palindrome_lengths[i] > max_len:\n max_len = palindrome_lengths[i]\n start = (i - max_len) // 2\n return s[start:start + max_len]", "def longestpalin(s):\n a = 1\n b = s[0]\n n = len(s)\n for i in range(n):\n for j in range(i + a + 1, n + 1):\n sub = s[i:j]\n if sub == sub[::-1]:\n a = len(sub)\n b = sub\n return b", "def longestpalin(S):\n\n def isPalindrome(s, i, j):\n n = len(s)\n while i >= 0 and j < n and (s[i] == s[j]):\n i -= 1\n j += 1\n return s[i + 1:j]\n n = len(S)\n mx = ''\n for i in range(n):\n res = isPalindrome(S, i, i)\n mx = max(mx, res, key=len)\n res = isPalindrome(S, i, i + 1)\n mx = max(mx, res, key=len)\n return mx", "def longestpalin(s: str) -> str:\n if s == s[::-1]:\n return s\n (start, size) = (0, 1)\n for i in range(1, len(s)):\n (l, r) = (i - size, i + 1)\n (s1, s2) = (s[l - 1:r], s[l:r])\n if l >= 1 and s1 == s1[::-1]:\n size += 2\n start = l - 1\n elif s2 == s2[::-1]:\n size += 1\n start = l\n return s[start:start + size]", "def longestpalin(s):\n if len(s) == 1:\n return s\n for i in range(len(s), 0, -1):\n for j in range(len(s) - i + 1):\n x = s[j:i + j]\n if x == x[::-1]:\n return x", "def longestpalin(S):\n fi = fj = 0\n n = len(S)\n for i in range(n):\n j = i - 1\n k = i + 1\n while j >= 0 and k < n:\n if S[j] != S[k]:\n break\n j -= 1\n k += 1\n if k - j - 1 > fj - fi + 1:\n fi = j + 1\n fj = k - 1\n if i < n - 1 and S[i] == S[i + 1]:\n j = i - 1\n k = i + 2\n while j >= 0 and k < n:\n if S[j] != S[k]:\n break\n j -= 1\n k += 1\n if k - j - 1 > fj - fi + 1:\n fi = j + 1\n fj = k - 1\n return S[fi:fj + 1]", "def longestpalin(S):\n if S == S[::-1]:\n return S\n count = 0\n out = ''\n for i in range(len(S)):\n for j in range(i + 1, len(S) + 1):\n p = S[i:j]\n if p == p[::-1]:\n if len(S[i:j]) > count:\n count = len(S[i:j])\n out = S[i:j]\n return out", "def longestpalin(s):\n ans = ''\n n = len(s)\n le = 0\n for i in range(n):\n for j in range(i, n):\n if s[i] == s[j] and i != j and (j - i + 1 > le):\n s1 = ''\n s2 = ''\n s3 = ''\n if (j - i) % 2 == 0:\n s1 = s[i:(j + i) // 2]\n s3 = s[(j + i) // 2]\n s2 = s[(j + i) // 2 + 1:j + 1]\n else:\n s1 = s[i:(j + i) // 2 + 1]\n s2 = s[(j + i) // 2 + 1:j + 1]\n if s1 == s2[::-1]:\n ans = s1 + s3 + s2\n le = len(ans)\n if ans == '':\n return s[0]\n return ans", "def longestpalin(S):\n n = len(S)\n if n == 1:\n return S\n for i in range(n, 0, -1):\n for j in range(n - i + 1):\n h = S[j:i + j]\n if h == h[::-1]:\n return h", "def longestpalin(S):\n n = len(S)\n max_len = 1\n start_idx = 0\n for i in range(n):\n j = i\n k = i\n while j >= 0 and k < n and (S[j] == S[k]):\n if k - j + 1 > max_len:\n max_len = k - j + 1\n start_idx = j\n j -= 1\n k += 1\n if max_len >= 2 * (n - i) - 1:\n break\n for i in range(n - 1):\n j = i\n k = i + 1\n while j >= 0 and k < n and (S[j] == S[k]):\n if k - j + 1 > max_len:\n max_len = k - j + 1\n start_idx = j\n j -= 1\n k += 1\n if max_len >= 2 * (n - i) - 1:\n break\n return S[start_idx:start_idx + max_len]", "def longestpalin(S):\n\n def check(s, start, end):\n while start < end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n maxLen = 1\n start = 0\n for i in range(len(S)):\n for j in range(i + 1, len(S)):\n if j - i + 1 > maxLen and check(S, i, j):\n start = i\n maxLen = j - i + 1\n return S[start:start + maxLen]", "def longestpalin(S):\n res = ''\n s2 = 0\n if S == S[::-1]:\n return S\n for i in range(len(S)):\n st = ''\n s1 = 0\n for j in range(i, len(S)):\n st += S[j]\n s1 += 1\n if st == st[::-1]:\n if s1 > s2:\n res = st\n s2 = s1\n return res", "def longestpalin(S):\n maxlen = 1\n n = len(S)\n leng = 0\n start = 0\n end = 0\n if len(S) <= 1:\n return S\n for i in range(0, n):\n l = i\n r = i\n while l >= 0 and r < n:\n if S[l] == S[r]:\n l -= 1\n r += 1\n else:\n break\n leng = r - l - 1\n if leng > maxlen:\n maxlen = leng\n start = l + 1\n end = r\n l = i\n r = i + 1\n while l >= 0 and r < n:\n if S[l] == S[r]:\n l -= 1\n r += 1\n else:\n break\n leng = r - l - 1\n if leng > maxlen:\n maxlen = leng\n start = l + 1\n end = r\n if start == 0 and end == 0:\n return S[0]\n return S[start:end]", "def longestpalin(S):\n max = 1\n ans = S[0]\n for i in range(len(S)):\n for j in range(i + max + 1, len(S) + 1):\n str = S[i:j]\n if str == str[::-1]:\n max = len(str)\n ans = str\n return ans", "def longestpalin(S):\n rev = S[::-1]\n i = 0\n j = 1\n s2 = ''\n a = len(S)\n s3 = ''\n while i < a and j < a + 1:\n if S[i:j] not in rev:\n i = i + 1\n j = i + len(s2) + 1\n else:\n s3 = S[i:j]\n j = j + 1\n if s3 == s3[::-1]:\n s2 = s3\n return s2", "def longestpalin(S):\n maxx = 1\n str = S[0]\n n = len(S)\n for i in range(0, n):\n for j in range(i + maxx + 1, n + 1):\n s = S[i:j]\n if s == s[::-1]:\n maxx = len(s)\n str = s\n return str", "def isPlaindrome(s, low, high):\n while low <= high:\n if s[low] != s[high]:\n return False\n low += 1\n high -= 1\n return True\n\ndef longestpalin(S):\n if S == S[::-1]:\n return S\n max_p = ''\n n = len(S)\n for i in range(n):\n for j in range(i, n):\n if self.isPlaindrome(S, i, j) and len(max_p) < j - i + 1:\n max_p = S[i:j + 1]\n if len(max_p) > n - i:\n break\n return max_p", "def is_palindrome(data):\n (i, j) = (0, len(data) - 1)\n while i < j:\n if data[i] != data[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef longestpalin(S):\n n = len(S)\n ans = S[0]\n i = 0\n while n - i >= len(ans):\n temp = S[i]\n for j in range(i + 1, n):\n temp += S[j]\n if len(temp) > len(ans) and self.is_palindrome(temp):\n ans = temp\n i += 1\n return ans", "def longestpalin(S):\n if S == S[::-1]:\n return S\n max_p = ''\n n = len(S)\n for i in range(n):\n s1 = ''\n for j in range(i, n):\n s1 += S[j]\n if s1 == s1[::-1] and len(max_p) < len(s1):\n max_p = s1\n if len(max_p) > n - i:\n break\n return max_p", "def longestpalin(S):\n n = len(S)\n long = ''\n for i in range(n):\n (l, r) = (i, i)\n while l >= 0 and r < n and (S[l] == S[r]):\n l -= 1\n r += 1\n if len(long) < r - l - 1:\n long = S[l + 1:r]\n (l, r) = (i, i + 1)\n while l >= 0 and r < n and (S[l] == S[r]):\n l -= 1\n r += 1\n if len(long) < r - l - 1:\n long = S[l + 1:r]\n return long", "def longestpalin(S):\n max = 1\n res = S[0]\n for i in range(0, len(S)):\n for j in range(i + max + 1, len(S) + 1):\n s = S[i:j]\n if s == s[::-1]:\n max = len(s)\n res = s\n return res", "def ispalindrome(i, j, s):\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef longestpalin(S):\n n = len(S)\n max1 = 0\n ind = 0\n for i in range(n):\n for j in range(i, n):\n if j - i + 1 > max1 and self.ispalindrome(i, j, S):\n max1 = j - i + 1\n ind = i\n return S[ind:max1 + ind]", "def longestpalin(S):\n n = len(S)\n if n <= 1:\n return S\n max_len = 1\n (st, e) = (0, 0)\n for i in range(n - 1):\n (l, r) = (i, i)\n while l >= 0 and r < n:\n if S[l] == S[r]:\n (l, r) = (l - 1, r + 1)\n else:\n break\n length = r - l - 1\n if length > max_len:\n max_len = length\n (st, e) = (l + 1, r - 1)\n for i in range(n - 1):\n (l, r) = (i, i + 1)\n while l >= 0 and r < n:\n if S[l] == S[r]:\n l -= 1\n r += 1\n else:\n break\n length = r - l - 1\n if length > max_len:\n max_len = length\n (st, e) = (l + 1, r - 1)\n return S[st:e + 1]", "def longestpalin(s):\n n = len(s)\n if n <= 1:\n return s\n max_ = 0\n start = 0\n end = 0\n for i in range(n - 1):\n l = i\n r = i\n while l >= 0 and r < n:\n if s[l] == s[r]:\n l -= 1\n r += 1\n else:\n break\n len_ = r - l - 1\n if len_ > max_:\n max_ = len_\n start = l + 1\n end = r - 1\n for i in range(n - 1):\n l = i\n r = i + 1\n while l >= 0 and r < n:\n if s[l] == s[r]:\n l -= 1\n r += 1\n else:\n break\n len_ = r - l - 1\n if len_ > max_:\n max_ = len_\n start = l + 1\n end = r - 1\n return s[start:end + 1]", "def longestpalin(s: str) -> str:\n n = len(s)\n if n < 2:\n return s\n (start, end, max_len) = (0, 0, 1)\n for i in range(n):\n len1 = self.expand_around_center(s, i, i)\n len2 = self.expand_around_center(s, i, i + 1)\n cur_len = max(len1, len2)\n if cur_len > max_len:\n max_len = cur_len\n start = i - (cur_len - 1) // 2\n end = i + cur_len // 2\n return s[start:end + 1]\n\ndef expand_around_center(s: str, left: int, right: int) -> int:\n n = len(s)\n while left >= 0 and right < n and (s[left] == s[right]):\n left -= 1\n right += 1\n return right - left - 1", "def longestpalin(S):\n ans = ''\n\n def palin(s):\n i = 0\n j = len(s) - 1\n while i <= j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n for i in range(len(S)):\n if len(S) - i < len(ans):\n break\n for j in range(i + 1, len(S)):\n if S[i] == S[j]:\n s1 = S[i:j + 1]\n if palin(s1) and len(s1) > len(ans):\n ans = s1\n if ans == '':\n return S[0]\n return ans", "def longestpalin(S):\n i = 0\n n = len(S)\n j = n - 1\n Srev = ''\n Slist = []\n while i < n:\n j = n - 1\n while j >= 0:\n if S[i] == S[j]:\n Srev = ''.join(reversed(S[i:j + 1]))\n if S[i:j + 1] == Srev:\n Slist.append(S[i:j + 1])\n break\n j -= 1\n i += 1\n res = max(Slist, key=len)\n return res", "def longestpalin(s):\n n = len(s)\n start = 0\n max_len = 1\n\n def expand(left, right):\n while left >= 0 and right < n and (s[left] == s[right]):\n left -= 1\n right += 1\n return right - left - 1\n for i in range(n):\n len1 = expand(i, i)\n len2 = expand(i, i + 1)\n cm_len = max(len1, len2)\n if cm_len > max_len:\n max_len = cm_len\n start = i - (cm_len - 1) // 2\n return s[start:start + max_len]", "def longestpalin(S):\n best_begin_idx = best_end_idx = begin_idx = 0\n while begin_idx < len(S):\n begin_pointer = begin_idx\n end_idx = end_pointer = len(S) - 1\n is_palindrome = True\n while end_pointer >= begin_pointer:\n if S[begin_pointer] == S[end_pointer]:\n begin_pointer += 1\n end_pointer -= 1\n is_palindrome = True\n else:\n end_idx -= 1\n end_pointer = end_idx\n begin_pointer = begin_idx\n is_palindrome = False\n if is_palindrome:\n if end_idx - begin_idx > best_end_idx - best_begin_idx:\n best_begin_idx = begin_idx\n best_end_idx = end_idx\n begin_idx += 1\n return S[best_begin_idx:best_end_idx + 1]", "def longestpalin(S):\n ln = len(S)\n\n def cp(l, r):\n while l >= 0 and r < ln and (S[l] == S[r]):\n l -= 1\n r += 1\n return r - l - 1\n e = 0\n s = 0\n for i in range(ln):\n odd = cp(i, i)\n even = cp(i, i + 1)\n spl = max(even, odd)\n if spl > e:\n e = spl\n s = i - (spl - 1) // 2\n return S[s:s + e]", "def longestpalin(S):\n ans = ''\n n = len(S)\n for i in range(n):\n if len(S[i:]) < len(ans):\n return ans\n for j in range(n, i, -1):\n k = S[i:j]\n rev = k[::-1]\n if k == rev and len(k) > len(ans):\n ans = k\n return ans", "def lp(s, l, r):\n while l >= 0 and r < len(s) and (s[l] == s[r]):\n l -= 1\n r += 1\n return (l + 1, r)\n\ndef longestpalin(s):\n result = ''\n reslen = 0\n if len(s) == 1:\n return s[0]\n for i in range(len(s)):\n (l, r) = self.lp(s, i, i)\n if r - l > reslen:\n reslen = r - l\n result = s[l:r]\n (l, r) = self.lp(s, i, i + 1)\n if r - l > reslen:\n reslen = r - l\n result = s[l:r]\n return result", "def longestpalin(S):\n for i in range(len(S), -1, -1):\n for j in range(len(S) - i + 1):\n x = S[j:i + j]\n if x == x[::-1]:\n return x", "def expandAroundCenter(s, left, right):\n while left >= 0 and right < len(s) and (s[left] == s[right]):\n left -= 1\n right += 1\n return s[left + 1:right]\n\ndef longestpalin(S2):\n n = len(S)\n ans = ''\n for i in range(n):\n temp = expandAroundCenter(S, i, i)\n if len(temp) > len(ans):\n ans = temp\n temp = expandAroundCenter(S, i, i + 1)\n if len(temp) > len(ans):\n ans = temp\n return ans", "def longestpalin(str):\n a = ''\n s = 0\n if str == str[::-1]:\n return str\n for i in range(len(str)):\n b = ''\n s1 = 0\n for j in range(i, len(str)):\n b += str[j]\n s1 += 1\n if b == b[::-1]:\n if s1 > s:\n a = b\n s = s1\n return a"], "starter_code": "def longestpalin(S):\n", "input_output": {"inputs": ["S = \"aaaabbaa\"", "S = \"abc\""], "outputs": ["aabbaa", "a"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Strings", "Data Structures", "Dynamic Programming", "palindrome"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/longest-palindrome-in-a-string3411/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|^{2}).", "entry_point": "longestpalin", "task_id": "TACO_lite/177", "example": [[], []]} +{"requirement": "Given a number N, find the first N Fibonacci numbers. The first two number of the series are 1 and 1.\nExample 1:\nInput:\nN = 5\nOutput: 1 1 2 3 5\nExample 2:\nInput:\nN = 7\nOutput: 1 1 2 3 5 8 13\nYour Task:\nYour task is to complete printFibb() which takes single argument N and returns a list of first N Fibonacci numbers.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\nNote: This space is used to store and return the answer for printing purpose.\nConstraints:\n1<= N <=84", "solutions": ["def printfibb(n):\n result = [0] * n\n f1 = 1\n f2 = 1\n if n == 1:\n result[0] = 1\n else:\n result[0] = 1\n result[1] = 1\n i = 2\n while i < n:\n f = f1 + f2\n f2 = f1\n f1 = f\n result[i] = f\n i += 1\n return result", "def printfibb(n):\n fib = [1, 1]\n for i in range(2, n):\n fib.append(fib[i - 1] + fib[i - 2])\n return fib[:n]", "def printfibb(n):\n a = 0\n b = 1\n l = [1]\n c = 0\n for i in range(1, n):\n c = a + b\n l.append(c)\n a = b\n b = c\n return l", "def printfibb(n):\n\n def fibonacci(l):\n if l <= 0:\n return []\n elif l == 1:\n return [0]\n elif l == 2:\n return [0, 1]\n else:\n fib_sequence = fibonacci(l - 1)\n fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])\n return fib_sequence\n result = fibonacci(n + 1)\n return result[1:]", "def printfibb(n):\n res = []\n if n == 1:\n res = [1]\n elif n == 2:\n res = [1, 1]\n else:\n res = [1, 1]\n for i in range(2, n):\n res.append(res[-2] + res[-1])\n return res", "def printfibb(n):\n arr = [1, 1]\n for i in range(2, n):\n arr.append(arr[i - 1] + arr[i - 2])\n if n == 1:\n return [1]\n else:\n return arr", "def printfibb(n):\n if n == 1:\n return [1]\n dp = [1, 1]\n for i in range(2, n):\n dp.append(dp[len(dp) - 1] + dp[len(dp) - 2])\n return dp", "def printfibb(n):\n fib_num = [1, 1]\n for i in range(2, n):\n n3 = fib_num[i - 1] + fib_num[i - 2]\n fib_num.append(n3)\n return fib_num[:n]", "def printfibb(n):\n if n == 1:\n return [1]\n v = [0] * n\n v[0] = v[1] = 1\n for i in range(2, n):\n v[i] = v[i - 1] + v[i - 2]\n return v", "def printfibb(n):\n a = 1\n b = 1\n ans = []\n ans.append(a)\n ans.append(b)\n if n == 1:\n return [1]\n for i in range(n - 2):\n nxt = a + b\n ans.append(nxt)\n a = b\n b = nxt\n return ans", "def printfibb(n):\n fib_numbers = [0] * n\n for i in range(n):\n if i < 2:\n fib_numbers[i] = 1\n else:\n fib_numbers[i] = fib_numbers[i - 1] + fib_numbers[i - 2]\n return fib_numbers", "def printfibb(n):\n res = [0, 1]\n for i in range(n - 1):\n res.append(res[-1] + res[-2])\n return res[1:]", "def printfibb(n):\n y = []\n if n == 1:\n return [1]\n elif n == 2:\n return [1, 1]\n elif n > 2:\n y.append(1)\n y.append(1)\n for i in range(2, n):\n y.append(y[i - 1] + y[i - 2])\n return y", "def printfibb(n):\n ans = []\n f = 0\n s = 1\n ans.append(s)\n for i in range(1, n):\n t = f + s\n ans.append(t)\n f = s\n s = t\n return ans", "def printfibb(n):\n out = [1, 1]\n if n == 1:\n return [1]\n if n == 2:\n return [1, 1]\n for i in range(n - 2):\n out.append(out[-1] + out[-2])\n return out", "def printfibb(n):\n if n == 1:\n return [1]\n output = [1, 1]\n for _ in range(n - 2):\n output.append(output[-1] + output[-2])\n return output", "def printfibb(n):\n ans = []\n x = int(0)\n y = int(1)\n while n > 0:\n (x, y) = (y, x + y)\n ans.append(x)\n n -= 1\n return ans", "def printfibb(n):\n arr = [0] * n\n if n == 1:\n return [1]\n elif n >= 2:\n arr[0] = 1\n arr[1] = 1\n for i in range(2, n):\n arr[i] = arr[i - 1] + arr[i - 2]\n return arr", "def printfibb(n):\n a = 0\n b = 1\n l1 = [1]\n l = [1, 1]\n c = a + b\n for i in range(2, n):\n a = b\n b = c\n c = a + b\n l.append(c)\n if n == 1:\n return l1\n else:\n return l", "def printfibb(n):\n if n == 1:\n return [1]\n elif n == 0:\n return []\n ans = [1, 1]\n i = 0\n j = 1\n while len(ans) < n:\n ans.append(ans[i] + ans[j])\n i = i + 1\n j = j + 1\n return ans", "def printfibb(n):\n if n == 1:\n return [1]\n if n == 2:\n return [1, 1]\n x = 1\n y = 1\n arr = [1, 1]\n while n > 2:\n arr.append(x + y)\n y = x + y\n x = y - x\n n -= 1\n return arr", "def printfibb(n):\n if n == 1:\n return [1]\n if n == 2:\n return [1, 1]\n else:\n ans = [0 for i in range(n)]\n ans[0] = 1\n ans[1] = 1\n for i in range(2, n):\n ans[i] = ans[i - 1] + ans[i - 2]\n return ans\n\ndef fibb(n):\n if n <= 0:\n return 0\n if n == 1 or n == 2:\n return 1\n return self.fibb(n - 1) + self.fibb(n - 2)", "def fib(n, ans):\n if n <= 1:\n return n\n if n in ans:\n return ans[n]\n s = self.fib(n - 1, ans) + self.fib(n - 2, ans)\n ans[n] = s\n return s\n\ndef printfibb(n):\n ans = []\n memo = {}\n for i in range(n):\n ans.append(self.fib(i + 1, memo))\n return ans", "def printfibb(n):\n fib = [0] * (n + 1)\n if n == 1:\n return [1]\n elif n == 2:\n return [1, 1]\n else:\n fib[1] = 1\n fib[2] = 1\n for i in range(3, n + 1):\n fib[i] = fib[i - 1] + fib[i - 2]\n return fib[1:]", "def printfibb(n):\n lis = [1]\n\n def fib(n, a=0, b=1):\n if n == 1:\n return\n c = a + b\n lis.append(c)\n fib(n - 1, b, c)\n fib(n)\n return lis", "def printfibb(n):\n if n == 0:\n return []\n elif n == 1:\n return [1]\n else:\n fib = [1, 1]\n while len(fib) < n:\n fib.append(fib[-1] + fib[-2])\n return fib", "def printfibb(n):\n lst = []\n first = 1\n sec = 1\n lst.append(first)\n if n >= 2:\n lst.append(sec)\n for i in range(2, n):\n lst.append(lst[i - 1] + lst[i - 2])\n return lst", "def printfibb(n):\n l = []\n if n == 1:\n l.append(1)\n elif n == 2:\n l.append(1)\n l.append(1)\n else:\n l.append(1)\n l.append(1)\n a = b = 1\n for i in range(n - 2):\n z = a + b\n l.append(z)\n a = b\n b = z\n return l", "def printfibb(n):\n lst = []\n i = 0\n j = 1\n if n >= 1:\n lst.append(1)\n while n > 1:\n temp = i + j\n lst.append(temp)\n i = j\n j = temp\n n -= 1\n return lst", "def printfibb(n):\n l = []\n (f1, f2) = (1, 1)\n for i in range(n):\n l.append(f1)\n f3 = f1 + f2\n f1 = f2\n f2 = f3\n return l", "def printfibb(n):\n pr = [1]\n if n == 1:\n return pr\n sr = [1, 1]\n t = len(sr)\n f = 1\n s = 1\n for i in range(n - 2):\n c = f + s\n sr.append(c)\n f = s\n s = c\n return sr", "def printfibb(n):\n fibo = [1, 1]\n if n <= 2:\n return fibo[:n]\n for i in range(2, n):\n sum = 0\n sum = fibo[i - 2] + fibo[i - 1]\n fibo.append(sum)\n return fibo", "def printfibb(n):\n prev = 0\n next = 1\n ans = []\n ans.append(1)\n for i in range(n - 1):\n data = prev + next\n ans.append(data)\n prev = next\n next = data\n return ans", "def recursion(n, ans, prev, next):\n if n == 1 or n == 0:\n return ans\n data = prev + next\n ans.append(data)\n prev = next\n next = data\n self.recursion(n - 1, ans, prev, next)\n return ans\n\ndef printfibb(n):\n ans = []\n prev = 0\n next = 1\n ans.append(1)\n self.recursion(n, ans, prev, next)\n return ans", "def printfibb(n):\n f = 1\n s = 1\n l = []\n for i in range(n):\n l.append(f)\n (f, s) = (s, f + s)\n return l", "def printfibb(n):\n a = [1, 1]\n if n == 1:\n a.pop()\n return a\n i = 0\n while i < n - 2:\n item = a[-2] + a[-1]\n a.append(item)\n i += 1\n return a", "def printfibb(n):\n if n is 1:\n return [1]\n res = [1, 1]\n for i in range(2, n):\n res.append(res[i - 1] + res[i - 2])\n return res", "def genFibo(n):\n for i in range(2, n):\n self.fibo[i] = self.fibo[i - 1] + self.fibo[i - 2]\n\ndef printfibb(n):\n if self.fibo[84] == 1:\n self.genFibo(85)\n return self.fibo[1:n + 1]", "def printfibb(n):\n\n def solve(i, l, s):\n if i > n:\n return []\n small = solve(i + 1, s, s + l)\n small.append(l)\n return small\n ans = solve(0, 0, 1)\n ans.pop()\n return ans[::-1]", "def printfibb(n):\n fib = []\n i = 3\n if n == 1:\n fib.append(1)\n else:\n fib.append(1)\n fib.append(1)\n while i <= n:\n fib.append(fib[-1] + fib[-2])\n i = i + 1\n return fib", "def printfibb(n):\n fib = []\n n1 = 0\n n2 = 1\n fib.append(n2)\n for i in range(0, n - 1):\n n3 = n1 + n2\n n1 = n2\n n2 = n3\n fib.append(n3)\n return fib", "def printfibb(n):\n t = []\n a = 1\n b = 1\n if n == 1:\n t.append(a)\n elif n == 2:\n t.append(a)\n t.append(b)\n else:\n t.append(a)\n t.append(b)\n for i in range(2, n):\n c = a + b\n t.append(c)\n a = b\n b = c\n return t", "def printfibb(n):\n n1 = 1\n n2 = 1\n listt = []\n while n > 0:\n listt.append(n1)\n nth = n1 + n2\n n1 = n2\n n2 = nth\n n = n - 1\n return listt", "def printfibb(n):\n p = 0\n arr = [0, 1]\n if n == 0:\n return 0\n if n == 1:\n return [1]\n for i in range(n - 1):\n p = arr[-2] + arr[-1]\n arr.append(p)\n return arr[1:]", "def __init__():\n self.res = []\n\ndef printfibb(n, cur=1, prev=1):\n if n == 0:\n return self.res\n self.res.append(prev)\n self.printfibb(n - 1, cur + prev, cur)\n return self.res", "def printfibb(n):\n arr = []\n for i in range(n):\n if i == 0 or i == 1:\n t = 1\n else:\n sl = arr[-1]\n l = arr[-2]\n t = sl + l\n arr.append(t)\n return arr", "def printfibb(n):\n l = [1]\n i1 = 1\n i2 = 1\n if n > 1:\n l = [1, 1]\n for i in range(3, n + 1):\n s = i1 + i2\n i1 = i2\n i2 = s\n l.append(s)\n return l", "def printfibb(n):\n if n == 1:\n return '1'\n else:\n l = []\n f = 1\n j = 1\n l.append(f)\n l.append(j)\n for i in range(2, n):\n k = f + j\n l.append(k)\n f = j\n j = k\n return l", "def printfibb(n):\n if n >= 2:\n l = [1, 1]\n if n == 1:\n l = [1]\n return l\n if n == 0:\n l = []\n return l\n for i in range(2, n):\n a = l[i - 1] + l[i - 2]\n l.append(a)\n return l", "def printfibb(n):\n cur_sum = 0\n cur_list = []\n for i in range(n):\n if cur_sum == 0:\n cur_sum += 1\n cur_list.append(cur_sum)\n elif cur_sum == 1:\n cur_list.append(cur_sum)\n cur_sum += 1\n else:\n cur_sum = cur_list[i - 1] + cur_list[i - 2]\n cur_list.append(cur_sum)\n return cur_list", "def printfibb(n):\n lis = []\n lis.append(0)\n lis.append(1)\n for i in range(2, n + 1):\n val = lis[i - 1] + lis[i - 2]\n lis.append(val)\n return lis[1:]", "def traverse(this, el1, el2, n):\n n = n - 1\n if n == 0:\n return [el1 + el2]\n return [el1 + el2] + this.traverse(el2, el2 + el1, n)\n\ndef printfibb(n):\n if n == 1:\n return [1]\n if n == 2:\n return [1, 1]\n return [1, 1] + self.traverse(1, 1, n - 2)", "def printfibb(n):\n if n == 1:\n return [1]\n if n == 2:\n return [1, 1]\n else:\n a = [1] * n\n for i in range(2, n + 1):\n a[i] = a[i - 1] + a[i - 2]\n if i == n - 1:\n break\n return a", "def printfibb(n):\n\n def fibo(n1, n2, cnt, n, result):\n if cnt > n:\n return result\n sum = n1 + n2\n n1 = n2\n n2 = sum\n result.append(n1)\n cnt += 1\n return fibo(n1, n2, cnt, n, result)\n return fibo(0, 1, 1, n, [])", "def printfibb(n):\n list_num = []\n for i in range(n):\n if i == 0 or i == 1:\n list_num.append(1)\n else:\n list_num.append(list_num[i - 1] + list_num[i - 2])\n return list_num", "def printfibb(n):\n if n < 2:\n return [1]\n fibbonaci_list = [1, 1]\n n1 = 1\n n2 = 1\n for i in range(n - 2):\n n3 = n1 + n2\n fibbonaci_list.append(n3)\n n1 = n2\n n2 = n3\n return fibbonaci_list", "def printfibb(n):\n result = []\n (num1, num2) = (0, 1)\n for _ in range(n):\n result.append(num2)\n next = num1 + num2\n (num1, num2) = (num2, next)\n return result", "def printfibb(n):\n i = 0\n c = 1\n j = 1\n a = []\n a.append(j)\n while c < n:\n b = i + j\n i = j\n j = b\n a.append(b)\n c += 1\n return a", "def printfibb(N):\n if N == 1:\n return [1]\n if N == 2:\n return [1, 1]\n ans = self.printfibb(N - 1)\n ans.append(ans[-1] + ans[-2])\n return ans", "def printfibb(n):\n if n == 0:\n return n\n fib = []\n secondlast = 0\n last = 1\n fib.append(last)\n cur = 0\n for i in range(2, n + 1, 1):\n cur = last + secondlast\n secondlast = last\n last = cur\n fib.append(cur)\n return fib"], "starter_code": "def printfibb(n):\n", "input_output": {"inputs": ["N = 5", "N = 7"], "outputs": ["1 1 2 3 5", "1 1 2 3 5 8 13"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Dynamic Programming", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Mathematics"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/print-first-n-fibonacci-numbers1002/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "printfibb", "task_id": "TACO_lite/103", "example": [[], []]} +{"requirement": "A pronic number is a number which is the product of two consecutive integers. Find all Pronic Numbers less than or equal to the given integer N.\nThe first few Pronic numbers are: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132 and so on.\nExample 1:\nInput:\nN = 6\nOutput:\n0 2 6\nExplanation:\n0 is the product of 0 and 1.\n2 is the product of 1 and 2.\n6 is the product of 2 and 3.\nExample 2:\nInput:\nN = 56\nOutput:\n0 2 6 12 20 30 42 56\nExplanation:\n0 is the product of 0 and 1.\n2 is the product of 1 and 2.\n6 is the product of 2 and 3.\n12 is the product of 3 and 4.\nand so on.\nYour Task: \nYou don't need to read input. Your task is to complete the function pronicNumbers() which takes an integer N as input parameter and returns a list of integers. \nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints: \n1 <= N <= 10^{5}", "solutions": ["def pronicnumbers(N):\n i = 0\n k = []\n j = 0\n while j < N:\n j = i * (i + 1)\n if j > N:\n break\n k.append(j)\n i = i + 1\n return k", "def pronicnumbers(n):\n ans = []\n for i in range(1, n):\n t = (i - 1) * i\n if t <= N:\n ans.append(t)\n else:\n break\n return ans", "def pronicnumbers(N):\n arr = []\n for i in range(1, N + 1):\n if (i - 1) * i <= N:\n arr.append((i - 1) * i)\n return arr", "def pronicnumbers(N):\n i = 0\n a = []\n c = 0\n while c <= N:\n c = i * (i + 1)\n if c > N:\n break\n a.append(c)\n i = i + 1\n return a", "def pronicnumbers(N):\n ans = []\n for i in range(N + 1):\n x = round(i ** 0.5)\n if x * (x + 1) == i:\n ans.append(i)\n return ans", "def pronicnumbers(N):\n l = []\n k = [i for i in range(N)]\n j = 1\n while j < len(k):\n l.append(k[j - 1] * k[j])\n j += 1\n if l[-1] >= N:\n if l[-1] > N:\n l.pop()\n return l", "def pronicnumbers(N):\n k = []\n for i in range(N):\n r = i * (i + 1)\n k.append(r)\n if r == N:\n return k\n elif r > N:\n return k[:-1]", "def pronicnumbers(N):\n i = 0\n list1 = []\n while True:\n prod = i * (i + 1)\n if prod > N:\n break\n else:\n list1.append(prod)\n i += 1\n return list1", "def pronicnumbers(N):\n a = []\n for i in range(N + 1):\n p = round(i ** 0.5)\n if p * (p + 1) == i:\n a.append(i)\n return a", "def pronicnumbers(N):\n list = []\n for j in range(N):\n if j * (j + 1) > N:\n break\n list.append(j * (j + 1))\n return list", "from math import sqrt\n\ndef pronicnumbers(N):\n ans = [0]\n for i in range(1, N + 1):\n temp = int(sqrt(i))\n if temp * (temp + 1) == i:\n ans.append(i)\n return ans", "def pronicnumbers(N):\n n = 1\n st = []\n for i in range(N + 1):\n if i * (i + 1) > N:\n break\n st.append(i * (i + 1))\n return st", "def pronicnumbers(N):\n pronicNumber = []\n for j in range(0, N):\n a = j * (j + 1)\n if a <= N:\n pronicNumber.append(a)\n else:\n break\n return pronicNumber", "def pronicnumbers(N):\n num1 = 0\n num2 = 1\n l = []\n mult = num1 * num2\n while mult <= N:\n l.append(mult)\n num1 += 1\n num2 += 1\n mult = num1 * num2\n return l"], "starter_code": "def pronicnumbers(N):\n", "input_output": {"inputs": ["N = 6", "N = 56"], "outputs": ["0 2 6", "0 2 6 12 20 30 42 56"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/pronic-number0729/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "pronicnumbers", "task_id": "TACO_lite/163", "example": [[], []]} +{"requirement": "Switch/Case - Bug Fixing #6\n\nOh no! Timmy's evalObject function doesn't work. He uses Switch/Cases to evaluate the given properties of an object, can you fix timmy's function?", "solutions": ["def eval_object(v):\n return {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}.get(v['operation'])", "def eval_object(v):\n return eval('{a}{operation}{b}'.format(**v))", "def eval_object(v):\n return eval(str(v['a']) + v['operation'] + str(v['b']))", "eval_object = lambda v: eval('{}{}{}'.format(v['a'], v['operation'], v['b']))", "def eval_object(v):\n return {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '^': 1, '**': v['a'] ** v['b']}[v['operation']]", "from operator import add, sub, truediv, mul, mod, pow\nops = {'+': add, '-': sub, '/': truediv, '*': mul, '%': mod, '**': pow}\none = lambda a, b: 1\n\ndef eval_object(v):\n return ops.get(v['operation'], one)(v['a'], v['b'])", "from typing import Dict, Union\n\ndef eval_object(v: Dict[str, Union[str, int]]) -> int:\n return {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}.get(v['operation'], 1)", "def eval_object(v):\n if v['operation'] == '+':\n return int(v['a']) + int(v['b'])\n elif v['operation'] == '-':\n return int(v['a']) - int(v['b'])\n elif v['operation'] == '/':\n return int(v['a']) / int(v['b'])\n elif v['operation'] == '*':\n return int(v['a']) * int(v['b'])\n elif v['operation'] == '%':\n return int(v['a']) % int(v['b'])\n elif v['operation'] == '**':\n return int(v['a']) ** int(v['b'])", "def eval_object(v):\n if v['operation'] == '+':\n c = v['a'] + v['b']\n return c\n if v['operation'] == '-':\n c = v['a'] - v['b']\n return c\n if v['operation'] == '/':\n c = v['a'] / v['b']\n return c\n if v['operation'] == '*':\n c = v['a'] * v['b']\n return c\n if v['operation'] == '%':\n c = v['a'] % v['b']\n return c\n if v['operation'] == '**':\n c = v['a'] ** v['b']\n return c", "def eval_object(v):\n return eval('%s %s %s' % (v['a'], v['operation'], v['b']))", "def eval_object(v):\n if v['operation'] == '+':\n return v['a'] + v['b']\n elif v['operation'] == '-':\n return v['a'] - v['b']\n elif v['operation'] == '*':\n return v['a'] * v['b']\n elif v['operation'] == '/':\n return v['a'] / v['b']\n elif v['operation'] == '**':\n return v['a'] ** v['b']\n elif v['operation'] == '%':\n return v['a'] % v['b']\n else:\n return 1", "def eval_object(v):\n v = list(map(str, v.values()))\n return eval(v[0] + v[2] + v[1])", "def eval_object(v):\n c = {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}\n if v.get('operation') == '+':\n return v.get('a') + v.get('b')\n elif v.get('operation') == '-':\n return v.get('a') - v.get('b')\n elif v.get('operation') == '*':\n return v.get('a') * v.get('b')\n elif v.get('operation') == '**':\n return v.get('a') ** v.get('b')\n elif v.get('operation') == '/':\n return v.get('a') / v.get('b')\n elif v.get('operation') == '%':\n return v.get('a') % v.get('b')\n else:\n return None", "def eval_object(v):\n return {'+': v['a'] + v['b'], '-': int(v['a']) - int(v['b']), '/': int(v['a']) / int(v['b']), '*': int(v['a']) * int(v['b']), '%': int(v['a']) % int(v['b']), '**': int(v['a']) ** int(v['b'])}.get(v['operation'], 1)", "def eval_object(v):\n x = {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}\n if v['operation'] in x:\n return x.get(v['operation'])", "import operator\n\ndef eval_object(v):\n ops = {'+': operator.add, '-': operator.sub, '/': operator.truediv, '*': operator.mul, '%': operator.mod, '**': operator.pow}\n return ops.get(v.get('operation'))(v.get('a'), v.get('b'))", "def eval_object(v):\n operations = {'+': lambda a, b: a + b, '-': lambda a, b: a - b, '/': lambda a, b: a / b, '*': lambda a, b: a * b, '%': lambda a, b: a % b, '**': lambda a, b: a ** b}\n return operations[v['operation']](v['a'], v['b'])", "def eval_object(operation):\n if operation['operation'] == '+':\n x = operation['a'] + operation['b']\n elif operation['operation'] == '-':\n x = operation['a'] - operation['b']\n elif operation['operation'] == '/':\n x = operation['a'] / operation['b']\n elif operation['operation'] == '*':\n x = operation['a'] * operation['b']\n elif operation['operation'] == '%':\n x = operation['a'] % operation['b']\n elif operation['operation'] == '**':\n x = operation['a'] ** operation['b']\n return x", "def eval_object(v):\n switcher = {'+': \"v['a']+v['b']\", '-': \"v['a']-v['b']\", '/': \"v['a']/v['b']\", '*': \"v['a']*v['b']\", '%': \"v['a']%v['b']\", '**': \"v['a']**v['b']\"}\n return eval(switcher.get(v['operation']))", "def eval_object(v):\n operator = {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}\n return operator[v.get('operation', 1)]", "def eval_object(v):\n return eval(f\"{v['a']}{v['operation']}{v['b']}\")", "def eval_object(v):\n operations = {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}\n return operations.get(v['operation'], 1)", "def eval_object(v):\n if v.get('operation') == '+':\n return v.get('a') + v.get('b')\n elif v.get('operation') == '-':\n return v.get('a') - v.get('b')\n elif v.get('operation') == '/':\n try:\n return v.get('a') / v.get('b')\n except ZeroDivisionError:\n return \"Can't divide by Zero\"\n elif v.get('operation') == '*':\n return v.get('a') * v.get('b')\n elif v.get('operation') == '%':\n return v.get('a') % v.get('b')\n elif v.get('operation') == '**':\n return v.get('a') ** v.get('b')", "def eval_object(v):\n return {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}.get(v['operation'], 'No operation available')", "def eval_object(v):\n a = str(v.get('a'))\n b = str(v.get('b'))\n op = v.get('operation')\n return eval(a + op + b)", "def eval_object(v):\n c = v['operation']\n a = v['a']\n b = v['b']\n if c == '+':\n return a + b\n elif c == '-':\n return a - b\n elif c == '/':\n return a / b\n elif c == '*':\n return a * b\n elif c == '%':\n return a % b\n else:\n return a ** b", "def eval_object(v):\n x = v.get('a')\n y = v.get('b')\n op = v.get('operation')\n return {'+': x + y, '-': x - y, '/': x / y, '*': x * y, '%': x % y, '**': x ** y}.get(op)", "def eval_object(v):\n a = v.get('a')\n b = v.get('b')\n op = v.get('operation')\n if op == '+':\n return a + b\n elif op == '-':\n return a - b\n elif op == '/':\n return a / b\n elif op == '*':\n return a * b\n elif op == '%':\n return a % b\n elif op == '**':\n return a ** b", "eval_object = lambda v: eval('%d %s %d' % (v['a'], v['operation'], v['b'])) if v['operation'] in '**%/-+' else 1", "def eval_object(v):\n Oper = {'+': lambda a, b: a + b, '-': lambda a, b: a - b, '/': lambda a, b: a / b, '*': lambda a, b: a * b, '%': lambda a, b: a % b, '**': lambda a, b: a ** b}\n return Oper[v['operation']](v['a'], v['b'])", "def eval_object(v):\n return {'+': eval(\"v['a']+v['b']\"), '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}.get(v['operation'], 1)", "eval_object = lambda v: {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}.get(v['operation'], 0)", "def eval_object(v):\n return {'+': int(v['a']) + int(v['b']), '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}[v['operation']]", "def eval_object(v):\n\n def add(d):\n return d['a'] + d['b']\n\n def subtract(d):\n return d['a'] - d['b']\n\n def divide(d):\n return d['a'] / d['b']\n\n def remainder(d):\n return d['a'] % d['b']\n\n def multiply(d):\n return d['a'] * d['b']\n\n def double_star(d):\n return d['a'] ** d['b']\n return {'+': add(v), '-': subtract(v), '/': divide(v), '*': multiply(v), '%': remainder(v), '**': double_star(v)}.get(v['operation'])", "def eval_object(v):\n switcher = {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}\n return switcher.get(v['operation'], 1)", "import operator\n\ndef eval_object(expression):\n mathop = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.floordiv, '%': operator.mod, '**': operator.pow}\n if not all((isinstance(n, int) for n in (expression['a'], expression['b']))):\n return 0\n else:\n return mathop[expression['operation']](expression['a'], expression['b'])", "import operator\n\ndef eval_object(v):\n return {'+': operator.add, '-': operator.sub, '/': operator.floordiv, '*': operator.mul, '%': operator.mod, '**': operator.pow}[v['operation']](v['a'], v['b'])", "def eval_object(z):\n (a, b, op) = (z[v] for v in ['a', 'b', 'operation'])\n return {'+': a + b, '-': a - b, '/': a / b, '*': a * b, '%': a % b, '**': a ** b}.get(op)", "def eval_object(v):\n return eval('{0}{1}{2}'.format(v['a'], v['operation'], v['b']))", "def eval_object(v):\n output = {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}\n return output[v['operation']]", "def eval_object(v):\n (op, a, b) = (v['operation'], v['a'], v['b'])\n return {'+': a + b, '-': a - b, '/': a / b, '*': a * b, '%': a % b, '**': a ** b}.get(op, 1)"], "starter_code": "def eval_object(v):\n", "input_output": {"fn_name": "eval_object", "inputs": [[{"a": 1, "b": 1, "operation": "+"}], [{"a": 1, "b": 1, "operation": "-"}], [{"a": 1, "b": 1, "operation": "/"}], [{"a": 1, "b": 1, "operation": "*"}], [{"a": 1, "b": 1, "operation": "%"}], [{"a": 1, "b": 1, "operation": "**"}]], "outputs": [[2], [0], [1], [1], [0], [1]]}, "difficulty": "EASY", "raw_tags": ["Debugging"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/55c933c115a8c426ac000082", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "eval_object", "task_id": "TACO_lite/116", "example": [[], []]} +{"requirement": "Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.\nIf it is impossible to form any triangle of non-zero area, return 0.\n \n\n\n\nExample 1:\nInput: [2,1,2]\nOutput: 5\n\n\nExample 2:\nInput: [1,2,1]\nOutput: 0\n\n\nExample 3:\nInput: [3,2,3,4]\nOutput: 10\n\n\nExample 4:\nInput: [3,6,2,3]\nOutput: 8\n\n \nNote:\n\n3 <= A.length <= 10000\n1 <= A[i] <= 10^6", "solutions": ["def largestperimeter(A: List[int]) -> int:\n A.sort(reverse=True)\n la = len(A)\n for i in range(la - 2):\n if A[i] < A[i + 1] + A[i + 2]:\n return A[i] + A[i + 1] + A[i + 2]\n return 0", "def largestperimeter(A: List[int]) -> int:\n sortedA = sorted(A)\n for i in range(len(sortedA) - 3, -1, -1):\n if sortedA[i + 2] < sortedA[i] + sortedA[i + 1]:\n return sum(sortedA[i:i + 3])\n return 0", "def largestperimeter(A: List[int]) -> int:\n A.sort()\n return ([0] + [a + b + c for (a, b, c) in zip(A, A[1:], A[2:]) if c < a + b])[-1]", "def largestperimeter(A: List[int]) -> int:\n A.sort()\n for i in range(len(A) - 1, 1, -1):\n len1 = A[i]\n len2 = A[i - 1]\n len3 = A[i - 2]\n if self.check_triangle(len1, len2, len3):\n return len1 + len2 + len3\n return 0\n\ndef check_triangle(len1, len2, len3):\n if len1 + len2 <= len3 or len2 + len3 <= len1 or len1 + len3 <= len2:\n return False\n return True", "def largestperimeter(A: List[int]) -> int:\n A.sort(reverse=True)\n i = 0\n while i < len(A) - 2:\n if A[i] < A[i + 1] + A[i + 2]:\n return A[i] + A[i + 1] + A[i + 2]\n else:\n i = i + 1\n return 0", "def largestperimeter(A: List[int]) -> int:\n p = 0\n A.sort()\n for i in range(len(A) - 2):\n if A[i] + A[i + 1] > A[i + 2]:\n p = A[i] + A[i + 1] + A[i + 2]\n return p", "def largestperimeter(A: List[int]) -> int:\n A = sorted(A)\n perimeter = 0\n for i in range(len(A) - 2):\n (s1, s2, s3) = (A[i], A[i + 1], A[i + 2])\n p = s1 + s2 + s3\n if s1 + s2 > s3 and s2 + s3 > s1 and (s1 + s3 > s2):\n perimeter = max(perimeter, p)\n return perimeter", "def largestperimeter(A: List[int]) -> int:\n result = 0\n A = sorted(A)\n for i in range(len(A) - 2):\n (a, b, c) = (A[i], A[i + 1], A[i + 2])\n if a + b > c and a + c > b and (b + c > a):\n result = max(result, a + b + c)\n return result", "def largestperimeter(A: List[int]) -> int:\n A.sort()\n for i in range(len(A) - 1, 1, -1):\n a = A[i]\n b = A[i - 1]\n c = A[i - 2]\n if a < b + c:\n return a + b + c\n return 0", "import numpy as np\n\ndef largestperimeter(A: List[int]) -> int:\n valid_area = lambda x, y, z: True if x < y + z else False\n A = sorted(A, reverse=True)\n for a in range(2, len(A)):\n if valid_area(A[a - 2], A[a - 1], A[a]):\n return np.sum([A[a - 2], A[a - 1], A[a]])\n return 0", "def largestperimeter(A: List[int]) -> int:\n A.sort()\n ans = 0\n for i in range(1, len(A) - 1):\n if A[i - 1] + A[i] <= A[i + 1]:\n continue\n else:\n p = sum(A[i - 1:i + 2])\n ans = max(ans, p)\n return ans", "def largestperimeter(A: List[int]) -> int:\n if len(A) < 3:\n return 0\n A.sort()\n counter = 3\n perimeter = 0\n while counter <= len(A):\n a = A[counter - 3]\n b = A[counter - 2]\n c = A[counter - 1]\n if a + b <= c:\n counter += 1\n continue\n elif b + c <= a:\n counter += 1\n continue\n elif c + a <= b:\n counter += 1\n continue\n perimeter = a + b + c\n if a + b + c > perimeter:\n perimeter = a + b + c\n counter += 1\n return perimeter", "def largestperimeter(A: List[int]) -> int:\n A.sort()\n first = 0\n second = 1\n mx = 0\n for third in range(2, len(A)):\n if A[first] + A[second] > A[third]:\n mx = max(mx, A[first] + A[second] + A[third])\n first += 1\n second += 1\n return mx", "def largestperimeter(A: List[int]) -> int:\n A.sort()\n a = len(A) - 1\n while a >= 2:\n if A[a] < A[a - 1] + A[a - 2]:\n return A[a] + A[a - 1] + A[a - 2]\n else:\n a -= 1\n return 0", "def largestperimeter(A: List[int]) -> int:\n A.sort(reverse=True)\n n = len(A)\n for i in range(n - 2):\n for j in range(i + 1, n - 1):\n if A[j] <= A[i] // 2:\n break\n for k in range(j + 1, n):\n if A[i] < A[j] + A[k]:\n return A[i] + A[j] + A[k]\n return 0", "def largestperimeter(A: List[int]) -> int:\n A = sorted(A)\n i = len(A) - 1\n while i >= 2:\n if A[i - 2] + A[i - 1] > A[i]:\n return A[i - 2] + A[i - 1] + A[i]\n i -= 1\n return 0", "def largestperimeter(A: List[int]) -> int:\n A.sort(reverse=True)\n for (a, b, c) in zip(A, A[1:], A[2:]):\n if a < b + c:\n return a + b + c\n else:\n continue\n return 0", "def largestperimeter(A: List[int]) -> int:\n A.sort(reverse=True)\n m = 0\n for i in range(len(A) - 2):\n if A[i] + A[i + 1] > A[i + 2] and A[i + 2] + A[i + 1] > A[i] and (A[i + 2] + A[i] > A[i + 1]):\n x = A[i:i + 3]\n if sum(x) > m:\n m = sum(x)\n return m", "def _isTriangle(queue):\n return queue[0] < queue[1] + queue[2]\n\ndef largestperimeter(A: List[int]) -> int:\n A.sort(key=lambda x: -x)\n nums = []\n for num in A:\n nums.append(num)\n if len(nums) == 3:\n if self._isTriangle(nums):\n return sum(nums)\n nums.pop(0)\n return 0", "def largestperimeter(A: List[int]) -> int:\n n = len(A)\n A.sort(reverse=True)\n a = 0\n while a < n:\n b = a + 1\n c = a + 2\n while b < n and c < n:\n if A[b] + A[c] > A[a]:\n return A[a] + A[b] + A[c]\n else:\n b += 1\n c += 1\n a += 1\n return 0", "def largestperimeter(A: List[int]) -> int:\n if len(A) < 3:\n return 0\n maxer = 0\n pointer1 = len(A) - 3\n pointer2 = len(A) - 2\n pointer3 = len(A) - 1\n A.sort()\n if len(A) == 3:\n if A[0] + A[1] > A[2]:\n return sum(A)\n else:\n return 0\n while pointer3 >= 2:\n if A[pointer1] + A[pointer2] > A[pointer3]:\n return A[pointer1] + A[pointer3] + A[pointer2]\n elif pointer1 == 0:\n pointer3 -= 1\n pointer2 = pointer3 - 1\n pointer1 = pointer2 - 1\n else:\n pointer1 -= 1\n pointer2 -= 1\n return maxer", "def largestperimeter(A: List[int]) -> int:\n A.sort(reverse=True)\n p = 0\n for i in range(len(A) - 2):\n if A[i] < sum(A[i + 1:i + 3]):\n p = sum(A[i:i + 3])\n break\n return p", "def largestperimeter(A: List[int]) -> int:\n A = sorted(A)\n while True:\n if A[-1] + A[-2] > A[-3] and A[-1] + A[-3] > A[-2] and (A[-3] + A[-2] > A[-1]):\n return A[-1] + A[-2] + A[-3]\n A.remove(A[-1])\n if len(A) == 2:\n return 0", "def largestperimeter(A: List[int]) -> int:\n\n def area(a, b, c):\n s = (a + b + c) / 2\n val = (s * (s - a) * (s - b) * (s - c)) ** (1 / 2)\n if isinstance(val, complex):\n return 0\n return val\n A.sort()\n maxi = 0\n for i in range(len(A) - 2):\n val = area(A[i], A[i + 1], A[i + 2])\n if val != 0:\n p = A[i] + A[i + 1] + A[i + 2]\n if p > maxi:\n maxi = p\n return maxi", "def largestperimeter(A: List[int]) -> int:\n\n def formT(a, b, c):\n if not a + b > c:\n return False\n if not b + c > a:\n return False\n if not a + c > b:\n return False\n return True\n sides = sorted(A)\n for i in range(len(sides) - 3, -1, -1):\n if formT(sides[i], sides[i + 1], sides[i + 2]):\n return sides[i] + sides[i + 1] + sides[i + 2]\n return 0", "def largestperimeter(A: List[int]) -> int:\n if len(A) < 3:\n return 0\n A.sort(reverse=True)\n while len(A) > 2:\n max_num = A.pop(0)\n if max_num >= A[0] + A[1]:\n continue\n else:\n return max_num + A[0] + A[1]\n return 0", "def largestperimeter(A: List[int]) -> int:\n res = 0\n A.sort()\n for i in range(len(A)):\n for j in range(i + 1, len(A)):\n source = A[i]\n target = A[j]\n lower = abs(target - source)\n upper = source + target\n if upper * 2 < res:\n continue\n for t in range(j + 1, len(A)):\n if lower < A[t] < upper:\n res = max(source + target + A[t], res)\n break\n if res != 0:\n break\n return res", "def largestperimeter(A: List[int]) -> int:\n A.sort()\n res = 0\n for i in range(len(A) - 2):\n test = A[i:i + 3]\n if test[0] + test[1] > test[2] and test[2] - test[1] < test[0] and (sum(test) > res):\n res = sum(test)\n return res", "def largestperimeter(A: List[int]) -> int:\n A.sort(reverse=True)\n for i in range(len(A) - 2):\n (a, b, c) = (A[i], A[i + 1], A[i + 2])\n c1 = a + b > c\n c2 = b + c > a\n c3 = c + a > b\n if c1 and c2 and c3:\n return a + b + c\n return 0"], "starter_code": "def largestperimeter(A: List[int]) -> int:\n", "input_output": {"fn_name": "largestPerimeter", "inputs": [[[1, 2, 2]]], "outputs": [5]}, "difficulty": "EASY", "raw_tags": ["Math", "Sorting", "Greedy", "Array"], "name": null, "source": "leetcode", "tags": ["Sorting", "Data structures", "Mathematics", "Greedy algorithms"], "skill_types": ["Sorting", "Data structures", "Greedy algorithms"], "url": "https://leetcode.com/problems/largest-perimeter-triangle/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "largestperimeter", "task_id": "TACO_lite/123", "example": [[[[2, 1, 2]], [[1, 2, 1]], [[3, 2, 3, 4]], [[3, 6, 2, 3]]], ["5", "0", "10", "8"]]} +{"requirement": "In this Kata, you will be given a string and your task is to determine if that string can be a palindrome if we rotate one or more characters to the left.\n\n```Haskell\nsolve(\"4455\") = true, because after 1 rotation, we get \"5445\" which is a palindrome\nsolve(\"zazcbaabc\") = true, because after 3 rotations, we get \"abczazcba\", a palindrome\n```\n\nMore examples in test cases. Input will be strings of lowercase letters or numbers only.\n\nGood luck!", "solutions": ["def solve(s):\n return any((s[i + 1:] + s[:i + 1] == s[i::-1] + s[:i:-1] for i in range(len(s))))", "def solve(s):\n for i in range(len(s)):\n xs = s[i:] + s[:i]\n if xs == xs[::-1]:\n return True\n return False", "from collections import deque\n\ndef solve(st):\n s = deque(st)\n return any((s == deque(reversed(s)) for _ in range(len(st)) if not s.rotate(1)))", "is_pal = lambda s: all((s[i] == s[len(s) - i - 1] for i in range(len(s) // 2)))\nsolve = lambda s: any((is_pal(s[i:] + s[:i]) for i in range(len(s))))", "def is_palindrome(s):\n for (i, (a, b)) in enumerate(zip(s, s[::-1])):\n if a != b:\n return False\n if i == len(s) // 2:\n return True\n\ndef solve(st):\n for i in range(len(st)):\n if is_palindrome(st[i:] + st[:i]):\n return True\n return False", "def rotate(list_):\n return list_[1:] + list_[:1]\n\ndef is_palindrome(list_):\n return list_ == list_[::-1]\n\ndef solve(st):\n list_ = list(st)\n for _ in range(len(st)):\n if is_palindrome(list_):\n return True\n else:\n list_ = rotate(list_)\n return False", "(q, solve) = (lambda p: p == p[::-1], lambda s: any((q(s[x:] + s[:x]) for x in range(len(s)))))", "solve = lambda s, c=0: s == s[::-1] or solve(s[-1] + s[:-1], c=c + 1) if c != len(s) else 0", "def solve(st):\n for x in range(len(st)):\n if st == st[::-1]:\n return True\n else:\n st = st[1:] + st[0]\n return False"], "starter_code": "def solve(s):\n", "input_output": {"fn_name": "solve", "inputs": [["aaab"], ["abcabc"], ["4455"], ["zazcbaabc"], ["223456776543"], ["432612345665"], ["qponmlkjihgfeeiefghijklmnopqrsttsr"]], "outputs": [[false], [false], [true], [true], [true], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5a8fbe73373c2e904700008c", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/180", "example": [[], []]} +{"requirement": "Given two coordinates (x, y) and (a, b). Find if it is possible to reach (x,y) from (a,b).\nOnly possible moves from any coordinate (i, j) are-\n\t(i-j, j)\n\t(i, i-j)\n\t(i+j, j)\n\t(i, i+j)\n \nExample 1:\nInput:\nx = 1, y = 1, a = 2, b = 3\nOutput:\n1\nExplanation:\nWe can reach the point (2,3) from (1,1).\nExample 2:\nInput:\nx = 35, y = 15, a = 20, b = 25\nOutput:\n1\nExplanation:\nWe can reach the point (20,25) from (35,15).\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function isPossible() which takes 4 Integers x, y, a and b as input and returns 1 if it's possible to move to (a,b) from (x,y) else returns 0.\n \nExpected Time Complexity: O(log(x))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n-10^{5} <= x,y,a,b <= 10^{5}", "solutions": ["def ispossible(x, y, a, b):\n\n def gcd(x, y):\n x = abs(x)\n y = abs(y)\n if x < y:\n (x, y) = (y, x)\n while y:\n (x, y) = (y, x % y)\n return x\n if gcd(x, y) == gcd(a, b):\n return 1\n else:\n return 0", "def ispossible(x, y, a, b):\n\n def gcd(m, n):\n if n == 0:\n return m\n return gcd(n, m % n)\n if abs(gcd(a, b)) == abs(gcd(x, y)):\n return 1\n else:\n return 0", "import math\n\ndef ispossible(x, y, a, b):\n\n def gcd(n, m):\n if m == 0:\n return n\n return gcd(m, n % m)\n g = gcd(x, y)\n h = gcd(a, b)\n if abs(g) == abs(h):\n return 1\n return 0", "import math\n\ndef ispossible(x, y, a, b):\n if math.gcd(x, y) == math.gcd(a, b):\n return 1\n return 0", "from math import gcd\n\ndef ispossible(x, y, a, b):\n return int(gcd(abs(x), abs(y)) == gcd(abs(a), abs(b)))", "def gcd(i, j):\n if i < j:\n (i, j) = (j, i)\n while j:\n (i, j) = (j, i % j)\n return i\n\ndef ispossible(x, y, a, b):\n (x, y, a, b) = (abs(x), abs(y), abs(a), abs(b))\n if self.gcd(x, y) == self.gcd(a, b):\n return 1\n return 0", "import math\n\ndef ispossible(x, y, a, b):\n e = math.gcd(a, b)\n f = math.gcd(x, y)\n if e == f:\n return 1\n else:\n return 0", "def ispossible(x, y, a, b):\n\n def gc(i, j):\n if j == 0:\n return i\n else:\n return gc(j, i % j)\n if gc(abs(x), abs(y)) == gc(abs(a), abs(b)):\n return 1\n else:\n return 0", "import math as m\n\ndef ispossible(x, y, a, b):\n r = m.gcd(x, y)\n e = m.gcd(a, b)\n if r == e:\n return 1\n else:\n return 0", "def ispossible(x, y, a, b):\n\n def find_gcd(a, b):\n if b == 0:\n return a\n if a == 0:\n return b\n if a > b:\n (a, b) = (b, a)\n return find_gcd(a, b % a)\n if x < 0:\n x = x * -1\n if y < 0:\n y = y * -1\n if a < 0:\n a = a * -1\n if b < 0:\n b = b * -1\n if find_gcd(x, y) == find_gcd(a, b):\n return 1\n return 0", "import math\n\ndef ispossible(x, y, a, b):\n (gxy, gab) = (0, 0)\n if math.gcd(x, y) == math.gcd(a, b):\n return 1\n else:\n return 0", "import math\n\ndef ispossible(x, y, a, b):\n k = math.gcd(a, b)\n m = math.gcd(x, y)\n if k == m:\n return 1\n else:\n return 0", "def ispossible(x, y, a, b):\n\n def gcd_(a, b):\n while a and b:\n if a > b:\n a %= b\n else:\n b %= a\n if a:\n return a\n return b\n if gcd_(abs(a), abs(b)) == gcd_(abs(x), abs(y)):\n return 1\n return 0", "def gc(n, m):\n while n != 0 and m != 0:\n if n < m:\n m = m % n\n else:\n n = n % m\n if n == 0:\n return m\n else:\n return n\n\ndef ispossible(x, y, a, b):\n g = self.gc(x, y)\n c = self.gc(a, b)\n if abs(g) == abs(c):\n return 1\n return 0"], "starter_code": "def ispossible(x, y, a, b):\n", "input_output": {"inputs": ["x = 1, y = 1, a = 2, b = 3", "x = 35, y = 15, a = 20, b = 25"], "outputs": ["1", "1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/check-if-possible-to-move-from-given-coordinate-to-desired-coordinate5944/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(x))", "entry_point": "ispossible", "task_id": "TACO_lite/164", "example": [[[1, 1, 2, 3], [35, 15, 20, 25]], ["1", "1"]]} +{"requirement": "Given a positive integer N, find the Nth Even Fibonacci number. Since the answer can be very large, return the answer modulo 1000000007.\nExample 1:\nInput: n = 1\nOutput: 2 \nExplanation: 2 is the first even\nnumber in the fibonacci series.\nExample 2:\nInput: n = 2\nOutput: 8\nExplanation: 8 is the second even\nnumber in the fibonacci series.\nYour Task: \nYou dont need to read input or print anything. Complete the function nthEvenFibonacci() which takes S as input parameter and returns the Nth even fibonacci number.\nExpected Time Complexity: O(n)\nExpected Auxiliary Space: O(n)\nConstraints:\n1<= n <=1000", "solutions": ["def nthevenfibonacci(ob, n):\n a = 1\n b = 1\n z = 0\n c = 0\n while c != n:\n z = a + b\n a = b\n b = z\n if z % 2 == 0:\n c += 1\n return z % 1000000007", "def nthevenfibonacci(n):\n net = n * 3\n return self.gfn(net) % 1000000007\n\ndef gfn(n):\n if n < 1:\n return 0\n n1 = 0\n n2 = 1\n while n > 1:\n n2 += n1\n n1 = n2 - n1\n n -= 1\n return n2", "def nthevenfibonacci(ob, n):\n dp = [0] * (3 * n)\n dp[0] = 1\n dp[1] = 1\n i = 2\n f = 0\n while f < n:\n dp[i] = dp[i - 1] + dp[i - 2]\n if dp[i] % 2 == 0:\n f += 1\n if f == n:\n return dp[i] % 1000000007\n i += 1", "def nthevenfibonacci(ob, n):\n ob.n = n\n ob.l = [0, 1]\n ob.a = 0\n ob.b = 1\n for i in range(1, 3 * n):\n ob.c = ob.a + ob.b\n ob.l.append(ob.c)\n (ob.a, ob.b) = (ob.b, ob.c)\n return ob.l[-1] % 1000000007", "def nthevenfibonacci(ob, n):\n a = 0\n b = 1\n l = []\n while 1:\n c = a + b\n if a % 2 == 0:\n l.append(a)\n a = b\n b = c\n if len(l) == n + 1:\n break\n return l[-1] % (10 ** 9 + 7)", "def nthevenfibonacci(ob, n):\n (f1, f2) = (0, 1)\n f = []\n c = 0\n while c != n:\n f3 = f1 + f2\n if f3 % 2 == 0:\n f.append(f3 % (10 ** 9 + 7))\n c += 1\n f1 = f2\n f2 = f3\n return f[n - 1]", "def nthevenfibonacci(ob, n):\n even_counter = 0\n prev_fib = 1\n cur_fib = 1\n while even_counter < n:\n next_fib = prev_fib + cur_fib\n if next_fib % 2 == 0:\n even_counter += 1\n prev_fib = cur_fib\n cur_fib = next_fib\n return next_fib % 1000000007", "def nthevenfibonacci(ob, n):\n fibos = []\n fibos.append(0)\n fibos.append(1)\n evens = 0\n i = 2\n while evens < n:\n fibos.append(fibos[i - 1] + fibos[i - 2])\n if fibos[i] % 2 == 0:\n evens = evens + 1\n if evens == n:\n return fibos[i] % (pow(10, 9) + 7)\n i = i + 1\n return -1", "def nthevenfibonacci(ob, N):\n i = 0\n j = 0\n k = 0\n l = 0\n f1 = 0\n f2 = 1\n f3 = 0\n while l < N:\n f3 = f1 + f2\n f1 = f2\n f2 = f3\n if f3 % 2 == 0:\n l = l + 1\n f3 = f3 % 1000000007\n return f3 % 1000000007", "def nthevenfibonacci(ob, n):\n a = 0\n b = 1\n lst = []\n for i in range(0, n * 2):\n a = b + a\n b = b + a\n if a % 2 == 0:\n lst.append(a)\n if b % 2 == 0:\n lst.append(b)\n if len(lst) == n + 1:\n break\n return lst[n - 1] % 1000000007", "def nthevenfibonacci(ob, n):\n n1 = 1\n n2 = 1\n k = 1\n while k <= n:\n if n2 % 2 == 0:\n k += 1\n (n1, n2) = (n2, n1 + n2)\n return n1 % 1000000007", "def nthevenfibonacci(ob, n):\n mod = 1000000007\n (a, b, c) = (0, 1, 1)\n i = 1\n while i < 3 * n:\n c = (a + b) % mod\n a = b\n b = c\n i += 1\n return c % mod", "def nthevenfibonacci(ob, n):\n (a, b) = (1, 1)\n m = 10 ** 9 + 7\n for i in range(3 * n - 2):\n c = (a + b) % m\n a = b\n b = c\n return b", "def nthevenfibonacci(ob, N):\n first = 0\n second = 1\n third = 1\n count = 0\n while True:\n third = first + second\n first = second\n second = third\n if third % 2 == 0:\n count = count + 1\n if count == N:\n return third % 1000000007", "def nthevenfibonacci(n):\n a = 0\n b = 1\n even_count = 0\n if n <= 0:\n return 'Incorrect Input'\n else:\n for i in range(2, 10000):\n c = a + b\n a = b\n b = c\n if c % 2 == 0:\n even_count += 1\n if even_count == n:\n return c % 1000000007", "def nthevenfibonacci(ob, n):\n x = 0\n y = 1\n sum = 0\n count = 0\n while count != n:\n sum = x + y\n x = y\n y = sum\n if sum % 2 == 0:\n count = count + 1\n return sum % 1000000007", "def nthevenfibonacci(ob, n):\n if n <= 1:\n return n\n elif n == 1:\n return 2\n else:\n a = 0\n b = 1\n c = 0\n for i in range(1, n * 3):\n c = a + b\n a = b\n b = c\n return c % (10 ** 9 + 7)", "def nthevenfibonacci(ob, n):\n k = 0\n y = [0, 1]\n while k != n:\n y.append(y[-1] + y[-2])\n if y[-1] % 2 == 0:\n k += 1\n return y[-1] % 1000000007", "def nthevenfibonacci(ob, n):\n count = 0\n a = 1\n b = 1\n while count < n:\n num = a + b\n a = b\n b = num\n if num % 2 == 0:\n count += 1\n if count == n:\n return num % 1000000007\n break", "def nthevenfibonacci(ob, n):\n (a, b) = (1, 1)\n while n:\n (a, b) = (b, a + b)\n if a % 2 == 0:\n n -= 1\n return a % int(1000000000.0 + 7)", "def nthevenfibonacci(ob, n):\n index = n * 3\n l = [0, 1]\n for i in range(2, index + 1):\n l.append(l[i - 2] + l[i - 1])\n return l[index] % 1000000007", "def nthevenfibonacci(ob, n):\n c = 0\n x = 1\n y = 1\n while c < n:\n (x, y) = (y, x + y)\n if y % 2 == 0:\n c += 1\n return y % 1000000007", "def nthevenfibonacci(ob, n):\n count = 0\n a = 1\n b = 1\n while count != n:\n t = a\n a = b\n b = t + b\n if b % 2 == 0:\n count += 1\n return b % 1000000007", "def nthevenfibonacci(ob, n):\n a = 0\n b = 1\n while n > 0:\n value = a\n a = b\n b = value + b\n if b % 2 == 0:\n n = n - 1\n m = 1000000007\n return b % m", "def nthevenfibonacci(ob, n):\n fib = [1, 1]\n x = 2\n while n > 0:\n fib += [fib[-1] + fib[-2]]\n if fib[-1] % 2 == 0:\n x = fib[-1]\n else:\n continue\n n -= 1\n return x % 1000000007", "def nthevenfibonacci(ob, n):\n (x, y, z, k) = (0, 1, 1, 0)\n while k != n:\n if z % 2 == 0:\n k += 1\n if k == n:\n return z % (10 ** 9 + 7)\n x = y\n y = z\n z = x + y", "def nthevenfibonacci(ob, n):\n p = 1000000007\n fib = [1 for _ in range(3 * n + 1)]\n for i in range(3, 3 * n + 1):\n fib[i] = (fib[i - 1] % p + fib[i - 2] % p) % p\n return fib[3 * n]", "def nthevenfibonacci(ob, n):\n even = 0\n fib = [1, 1]\n while even != n:\n fib.append(fib[-1] + fib[-2])\n if fib[-1] % 2 == 0:\n even += 1\n return fib[-1] % 1000000007", "def nthevenfibonacci(ob, n):\n count = 0\n x = 0\n y = 1\n mod = 10 ** 9 + 7\n while True:\n c = x + y\n x = y\n y = c\n if y % 2 == 0:\n count += 1\n if count == n:\n break\n return y % mod", "def nthevenfibonacci(ob, N):\n (a, b, c) = (0, 1, 1)\n while N > 0:\n c = a + b\n (a, b) = (b, c)\n if c % 2 == 0:\n N -= 1\n return c % 1000000007", "def nthevenfibonacci(ob, n):\n a = [0] * (3 * n + 1)\n for i in range(1, 3 * n + 1):\n if i == 1:\n a[i] = 1\n else:\n a[i] = a[i - 1] + a[i - 2]\n return a[3 * n] % 1000000007", "def nthevenfibonacci(ob, n):\n n = 3 * n\n dp = [0] * (n + 1)\n mod = 1000000007\n dp[0] = 0\n dp[1] = 1\n for i in range(2, n + 1):\n dp[i] = (dp[i - 1] + dp[i - 2]) % mod\n return dp[n]", "def nthevenfibonacci(ob, n):\n m = 10 ** 9 + 7\n (a, b, c, z) = (1, 1, 0, 0)\n while c != n:\n z = a + b\n a = b\n b = z\n if z % 2 == 0:\n c += 1\n return z % m", "def nthevenfibonacci(ob, n):\n x = [0, 1]\n count = 0\n for i in range(10000):\n a = x[-1] + x[-2]\n if a % 2 == 0:\n count += 1\n if count == n:\n return a % 1000000007\n else:\n x.append(a)", "def nthevenfibonacci(ob, n):\n mod = 10 ** 9 + 7\n n = n * 3\n dp = [0] * (n + 1)\n dp[1] = 1\n for i in range(2, n + 1):\n dp[i] = (dp[i - 1] % mod + dp[i - 2] % mod) % mod\n return dp[n]", "def nthevenfibonacci(ob, n):\n (a, b) = (0, 1)\n c = 0\n d = 0\n for i in range(0, 9999999):\n c = a + b\n a = b\n b = c\n if c % 2 == 0:\n d += 1\n if d == n:\n return c % 1000000007\n break", "def nthevenfibonacci(ob, n):\n a = 0\n b = 1\n arr = []\n while len(arr) != n:\n res = a + b\n if res % 2 == 0:\n arr.append(res)\n a = b\n b = res\n return arr[n - 1] % 1000000007", "def nthevenfibonacci(ob, n):\n M = 10 ** 9 + 7\n cnt = 0\n (a, b) = (1, 1)\n f = 0\n while cnt != n:\n f = a + b\n a = b\n b = f\n if f & 1 == 0:\n cnt += 1\n return f % M", "def nthevenfibonacci(ob, n):\n a = 2\n b = 8\n c = 1\n if n == 1:\n return a\n if n == 2:\n return b\n for i in range(3, n + 1):\n c = (4 * b + a) % 1000000007\n a = b\n b = c\n return c", "def nthevenfibonacci(ob, n):\n h = 2\n s = 8\n if n == 1:\n return h\n if n == 2:\n return s\n for i in range(3, n + 1):\n q = (4 * s + h) % 1000000007\n (h, s) = (s, q)\n return q % 1000000007", "def nthevenfibonacci(ob, n):\n even = []\n fib = [1, 1]\n while len(even) < n:\n t = fib[-1] + fib[-2]\n if t % 2 == 0:\n even.append(t)\n fib.append(t)\n return even[n - 1] % (10 ** 9 + 7)", "def nthevenfibonacci(ob, n):\n f = [0, 2]\n for i in range(2, n + 1):\n f.append(4 * f[i - 1] + f[i - 2])\n return f[n] % 1000000007", "def nthevenfibonacci(ob, n):\n a = 1\n b = 1\n for i in range(1, 3 * n - 1):\n s = a + b\n a = b\n b = s\n return s % 1000000007", "def nthevenfibonacci(ob, n):\n (a, b, c) = (1, 1, 0)\n c1 = 0\n while c1 != n:\n c = a + b\n (a, b) = (b, c)\n if ~c & 1:\n c1 += 1\n return c % 1000000007", "def nthevenfibonacci(ob, n):\n a0 = 0\n a1 = 1\n num = 0\n count = 0\n while count != n:\n num = a0 + a1\n a0 = a1\n a1 = num\n if num % 2 == 0:\n count += 1\n return num % 1000000007", "def nthevenfibonacci(ob, n):\n c = [1, 1]\n i = 0\n a = 0\n while True:\n c.append(c[i] + c[i + 1])\n i += 1\n if c[-1] % 2 == 0:\n a += 1\n if a == n:\n return c[-1] % 1000000007", "def nthevenfibonacci(ob, n):\n if n == 0:\n return 0\n x = [0, 1, 1]\n while n > 0:\n x[0] = int(x[1] + x[2])\n (x[0], x[1]) = (x[1], x[0])\n (x[1], x[2]) = (x[2], x[1])\n if x[2] % 2 == 0:\n n -= 1\n return int(x[2] % 1000000007)", "def nthevenfibonacci(ob, n):\n t1 = 1\n t2 = 1\n s = 0\n c = 0\n while c != n:\n s = t1 + t2\n t1 = t2\n t2 = s\n if s % 2 == 0:\n c = c + 1\n return s % 1000000007", "def nthevenfibonacci(ob, n):\n f = 0\n s = 1\n flag = False\n c = 0\n while flag == False:\n digit = f + s\n if digit % 2 == 0:\n c = c + 1\n if c == n:\n flag = True\n return digit % 1000000007\n else:\n f = s\n s = digit\n else:\n f = s\n s = digit"], "starter_code": "def nthevenfibonacci (ob, n):\n", "input_output": {"inputs": ["n = 1", "n = 2"], "outputs": ["2", "8"]}, "difficulty": "EASY", "raw_tags": ["Fibonacci", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/nth-even-fibonacci-number1119/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "nthevenfibonacci", "task_id": "TACO_lite/183", "example": [[[1], [2]], ["2", "8"]]} +{"requirement": "Calculate the sum of all the multiples of 3 or 7 below the natural number N.\nExample 1:\nInput: 10\nOutput: 25\nExplanation:\nNumbers that are multiple of 3 or 7\nare 3, 6, 7, 9 so sum will be 25.\nExample 2:\nInput: 25\nOutput: 84\nExplanation: \nNumbers that are multiple of 3 or 7\nare 3, 6, 7, 9, 12, 14, 15, 18 so \nsum will be 84.\nYour Task:\nYou don't need to read or print anything. Your task is to complete the function sum() which takes N as input parameter and returns the sum of numbers that are multiple of 3 or 7.\nExpected Time Complexity: O(1)\nExpected Space Complexity: O(1)\nConstraints:\n1 <= N <= 1000000", "solutions": ["def sum(N):\n s = 0\n for i in range(1, N):\n if i % 3 == 0 or i % 7 == 0:\n s += i\n return s", "def sum(N):\n (m3, m7, m21) = (N // 3, N // 7, N // 21)\n (s3, s7, s21) = (3 * (m3 * (m3 + 1) // 2), 7 * (m7 * (m7 + 1) // 2), 21 * (m21 * (m21 + 1) // 2))\n if N % 3 == 0 or N % 7 == 0:\n return s3 + s7 - N - s21\n return s3 + s7 - s21", "def sum(N):\n k = (N - 1) // 3\n m = (N - 1) // 7\n p = (N - 1) // 21\n S3 = 3 * (k * (k + 1) // 2)\n S7 = 7 * (m * (m + 1) // 2)\n S21 = 21 * (p * (p + 1) // 2)\n return S3 + S7 - S21", "def sum(N):\n l = []\n for i in range(N):\n if i % 3 == 0 or i % 7 == 0:\n l.append(i)\n return sum(l)", "def sum(N):\n s = set()\n a = 3\n for i in range(1, N):\n c = a * i\n if c >= N:\n break\n else:\n s.add(c)\n b = 7\n for i in range(1, N):\n d = b * i\n if d >= N:\n break\n else:\n s.add(d)\n ans = 0\n for i in s:\n ans += i\n return ans", "def sum(N):\n s = 0\n for x in range(0, N):\n if x % 3 == 0 or x % 7 == 0:\n s += x\n return s", "def sum(N):\n s = 0\n i = 1\n while i < N:\n if i % 3 == 0 or i % 7 == 0:\n s = s + i\n i += 1\n return s"], "starter_code": "def sum(N):\n", "input_output": {"inputs": ["10", "25"], "outputs": ["25", "84"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/multiples-power2816/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "sum", "task_id": "TACO_lite/184", "example": [[[10], [25]], ["25", "84"]]} +{"requirement": "Given an array A[ ] of N integers and an integer X. In one operation, you can change the i^{th} element of the array to any integer value where 1 ≤ i ≤ N. Calculate minimum number of such operations required such that the bitwise AND of all the elements of the array is strictly greater than X.\nExample 1:\nInput:\nN = 4, X = 2\nA[] = {3, 1, 2, 7}\nOutput: \n2\nExplanation: \nAfter performing two operations:\nModified array: {3, 3, 11, 7} \nNow, Bitwise AND of all the elements\nis 3 & 3 & 11 & 7 = 3 \nExample 2:\nInput:\nN = 3, X = 1\nA[] = {2, 2, 2}\nOutput: \n0\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function count( ) which takes N, A[ ] and X as input parameters and returns the minimum number of operations required.\nExpected Time Complexity: O(N * Log(max(A[ ])))\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ N ≤ 10^{5}\n1 ≤ A[i] ≤ 10^{9}\n1 ≤ X ≤ 10^{9}", "solutions": ["def count(N, A, X):\n (res, bitset) = (N, 0)\n for i in range(32, -1, -1):\n if X & 1 << i > 0:\n bitset |= 1 << i\n else:\n count = 0\n temp = bitset | 1 << i\n for num in A:\n if num & temp != temp:\n count += 1\n res = min(res, count)\n return res", "def count(N, A, X):\n (res, bitset) = (float('inf'), 0)\n for i in range(30, -1, -1):\n if X & 1 << i > 0:\n bitset |= 1 << i\n else:\n count = 0\n temp = bitset | 1 << i\n for num in A:\n if num & temp != temp:\n count += 1\n res = min(res, count)\n return res", "def count(N, A, X):\n prefix = 0\n ans = N\n for i in range(30, -1, -1):\n if X >> i & 1 != 0:\n prefix ^= 1 << i\n continue\n ct = 0\n p = prefix ^ 1 << i\n for j in range(N):\n if A[j] & p == p:\n ct += 1\n ans = min(ans, N - ct)\n return ans", "def count(N, A, X):\n ans = 10 ** 9 + 9\n cur_xor = 0\n for i in range(31, -1, -1):\n if X & 1 << i:\n cur_xor = cur_xor | 1 << i\n else:\n temp = cur_xor | 1 << i\n cnt = 0\n for i in range(0, N):\n if temp & A[i] == temp:\n cnt = cnt + 1\n ans = min(ans, N - cnt)\n return ans", "def count(N, A, X):\n m = A[0]\n for i in range(1, N):\n m &= A[i]\n ans = N\n for i in range(32):\n if 1 << i | m > X:\n c = 0\n for x in A:\n if x & 1 << i == 0:\n c += 1\n ans = min(ans, c)\n s = set()\n for i in range(31, -1, -1):\n if 1 << i & X != 0:\n for (j, x) in enumerate(A):\n if 1 << i & x == 0:\n s.add(j)\n else:\n t = set()\n for (j, x) in enumerate(A):\n if 1 << i & x == 0:\n t.add(j)\n ans = min(ans, len(s | t))\n return ans", "def count(n, l, x):\n\n def fun(t):\n c = 0\n for i in l:\n if t & i != t:\n c += 1\n return c\n maxv = max(l)\n ans = n\n for i in range(maxv + 1):\n a = 1 << i\n t = x + a - x % a\n if t > maxv:\n break\n ans = min(ans, fun(t))\n return ans"], "starter_code": "def count(N, A, X):\n", "input_output": {"inputs": ["N = 4, X = 2\nA[] = {3, 1, 2, 7}", "N = 3, X = 1\nA[] = {2, 2, 2}"], "outputs": ["2", "0"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Greedy", "Bit Magic", "Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures", "Greedy algorithms"], "skill_types": ["Bit manipulation", "Data structures", "Greedy algorithms"], "url": "https://practice.geeksforgeeks.org/problems/7ba682ec660335b1627f2183f63bd2c8a37391ec/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N * Log(max(A[ ])))", "entry_point": "count", "task_id": "TACO_lite/169", "example": [[[4, 2, [3, 1, 2, 7]], [3, 1, [2, 2, 2]]], ["2", "0"]]} +{"requirement": "#Find the missing letter\n\nWrite a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array.\n\nYou will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2.\nThe array will always contain letters in only one case.\n\nExample:\n```if-not:swift\n['a','b','c','d','f'] -> 'e'\n['O','Q','R','S'] -> 'P'\n```\n\n(Use the English alphabet with 26 letters!)\n\nHave fun coding it and please don't forget to vote and rank this kata! :-) \n\nI have also created other katas. Take a look if you enjoyed this kata!", "solutions": ["def find_missing_letter(chars):\n n = 0\n while ord(chars[n]) == ord(chars[n + 1]) - 1:\n n += 1\n return chr(1 + ord(chars[n]))", "def find_missing_letter(input):\n alphabet = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')\n start = alphabet.index(input[0])\n for i in range(len(input)):\n if not input[i] == alphabet[start + i]:\n return alphabet[start + i]", "def find_missing_letter(c):\n return next((chr(ord(c[i]) + 1) for i in range(len(c) - 1) if ord(c[i]) + 1 != ord(c[i + 1])))", "def find_missing_letter(chars):\n for x in range(1, len(chars)):\n if ord(chars[x]) - ord(chars[x - 1]) != 1:\n return chr(ord(chars[x]) - 1)", "def find_missing_letter(chars):\n return [chr(n) for n in range(ord(chars[0]), ord(chars[-1]) + 1) if n not in [ord(c) for c in chars]][0]", "def find_missing_letter(chars):\n s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n match = False\n count = 0\n for letter in s:\n if letter == chars[count]:\n match = True\n count = count + 1\n elif match == True:\n return letter", "def find_missing_letter(chars):\n for i in range(0, len(chars) - 1):\n current = chars[i]\n after = chars[i + 1]\n expected = chr(ord(current) + 1)\n if after != expected:\n return expected\n return ''", "def find_missing_letter(chars):\n return set((chr(i) for i in range(ord(chars[0]), ord(chars[-1]) + 1))).difference(set(chars)).pop()", "def find_missing_letter(chars):\n next = chars[0]\n for letter in chars:\n if letter != next:\n return next\n next = chr(ord(letter) + 1)\n return 0"], "starter_code": "def find_missing_letter(chars):\n", "input_output": {"fn_name": "find_missing_letter", "inputs": [[["a", "b", "c", "d", "f"]], [["O", "Q", "R", "S"]], [["b", "d"]]], "outputs": [["e"], ["P"], ["c"]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5839edaa6754d6fec10000a2", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "find_missing_letter", "task_id": "TACO_lite/167", "example": [[[["a", "b", "c", "d", "f"]], [["O", "Q", "R", "S"]]], ["e", "P"]]} +{"requirement": "Given an array arr[] of N integers, calculate the median\n \nExample 1:\nInput: N = 5\narr[] = 90 100 78 89 67\nOutput: 89\nExplanation: After sorting the array \nmiddle element is the median \nExample 2:\nInput: N = 4\narr[] = 56 67 30 79\nOutput: 61\nExplanation: In case of even number of \nelements, average of two middle elements \nis the median.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function find_median() which takes the array as input parameter and returns the floor value of the median.\n \nExpected Time Complexity: O(n * log(n))\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= Length of Array <= 100\n1 <= Elements of Array <= 100", "solutions": ["def find_median(v):\n n = len(v)\n v.sort()\n if n == 0:\n return -1\n if n == 1:\n return int(v[0])\n if n == 2:\n return int((v[0] + v[1]) / 2)\n if n >= 3:\n if n % 2 == 0:\n p1 = int(n / 2)\n p2 = int(n / 2 - 1)\n return int((v[p1] + v[p2]) / 2)\n else:\n return int(v[int(n / 2)])", "def find_median(v):\n v.sort()\n n = len(v)\n if len(v) % 2 == 0:\n res = (v[int(n / 2 - 1)] + v[int(n / 2)]) / 2\n return int(res)\n else:\n return v[n // 2]", "def find_median(v):\n v.sort()\n n = len(v)\n if n % 2 == 1:\n median = v[n // 2]\n else:\n median = (v[n // 2 - 1] + v[n // 2]) / 2\n return int(median)", "def find_median(v):\n v.sort()\n if len(v) % 2 != 0:\n mid = len(v) // 2\n return v[mid]\n elif len(v) % 2 == 0:\n mid = len(v) // 2\n return (v[mid] + v[mid - 1]) // 2", "def find_median(arr):\n if len(arr) == 0:\n return\n import statistics\n return int(statistics.median(arr))", "def find_median(v):\n if len(v) == 0:\n return\n v.sort()\n return v[len(v) // 2] if len(v) % 2 == 1 else (v[len(v) // 2] + v[len(v) // 2 - 1]) // 2", "def find_median(v):\n temp = sorted(v)\n while len(temp) > 2:\n temp = temp[1:-1]\n if len(temp) == 2:\n return sum(temp) // 2\n return temp[0]", "def find_median(v):\n n = v.sort()\n k = len(v) // 2\n if len(v) % 2 != 0:\n return v[k]\n else:\n sum = (v[k - 1] + v[k]) // 2\n return sum", "def find_median(v):\n v.sort()\n m = 0\n n = len(v)\n if n % 2 != 0:\n m = v[int((n + 1) / 2) - 1]\n else:\n w = int(n / 2)\n x = int(w + 1)\n m = int((v[w - 1] + v[x - 1]) / 2)\n return m", "def find_median(v):\n v.sort()\n l = 0\n r = len(v) - 1\n mid = l + (r - l) // 2\n if len(v) % 2 != 0:\n return v[mid]\n elif len(v) % 2 == 0:\n return int((v[mid] + v[mid + 1]) / 2)", "def find_median(v):\n v.sort()\n l = len(v)\n if l % 2 != 0:\n a = l // 2\n return v[a]\n else:\n a = l // 2\n b = l // 2 - 1\n c = int((v[a] + v[b]) / 2)\n return c", "def find_median(v):\n arr = list(v)\n arr.sort()\n N = len(arr)\n if N % 2 != 0:\n return arr[N // 2]\n else:\n o = N // 2\n return (arr[o] + arr[o - 1]) // 2", "import math\n\ndef find_median(v):\n for i in range(1, len(v)):\n j = i - 1\n while v[i] < v[j] and j >= 0:\n j -= 1\n j += 1\n temp = v[i]\n k = i\n while k >= j:\n v[k] = v[k - 1]\n k -= 1\n v[j] = temp\n mid = math.floor(len(v) / 2)\n if len(v) % 2 == 0:\n return math.floor((v[mid - 1] + v[mid]) / 2)\n else:\n return v[mid]", "def find_median(v):\n d = sorted(v)\n if len(v) % 2 != 0:\n y = len(v) // 2\n i = d[y]\n return i\n else:\n y = len(v) // 2\n j = (d[y] + d[y - 1]) // 2\n return j", "def find_median(v):\n v.sort()\n if len(v) % 2 != 0:\n l = 0\n r = len(v)\n mid = l + r // 2\n return v[mid]\n else:\n l = 0\n r = len(v) // 2\n return (v[r] + v[r - 1]) // 2", "def find_median(v):\n sorted_v = sorted(v)\n n = len(sorted_v)\n m = n // 2\n if n % 2 == 0:\n median = (sorted_v[m] + sorted_v[m - 1]) // 2\n else:\n median = sorted_v[m]\n return median", "def find_median(v):\n v.sort()\n if len(v) % 2 != 0:\n mid = len(v) / 2 - 0.5\n mid_index = v[int(mid)]\n else:\n mid_ind = v[int(len(v) / 2)]\n permid_ind = v[int(len(v) / 2 - 1)]\n mid_index = int((mid_ind + permid_ind) / 2)\n [3, 4, 5, 6, 7, 8]\n [0, 1, 2, 3, 4, 5]\n return mid_index", "def find_median(v):\n l = len(v)\n if l == 1:\n return v[0]\n else:\n median = int(l / 2)\n v.sort()\n if l & 1:\n return v[median]\n else:\n return int((v[median - 1] + v[median]) / 2)", "def find_median(v):\n d = sorted(v)\n if len(d) % 2 == 0:\n x = d[len(d) // 2] + d[len(d) // 2 - 1]\n return x // 2\n else:\n return d[len(d) // 2]", "def find_median(v):\n l = list(v)\n l.sort()\n n = len(v)\n m = n // 2\n if n % 2 != 0:\n return l[m]\n else:\n return (l[m] + l[m - 1]) // 2", "def find_median(v):\n v.sort()\n if len(v) % 2 != 0:\n left = 0\n right = len(v)\n mid = (left + right) // 2\n return v[mid]\n else:\n left = 0\n right = len(v) // 2\n return (v[right] + v[right - 1]) // 2", "def find_median(v):\n v.sort()\n length = len(v)\n if length % 2 == 1:\n result = v[int(length / 2)]\n else:\n position = int(length / 2)\n result = (v[position] + v[position - 1]) / 2\n return int(result)", "def find_median(v):\n v = sorted(v)\n n = len(v)\n if n % 2 == 0:\n return int((v[int(n / 2)] + v[int(n / 2) - 1]) / 2)\n return v[int(n / 2)]", "def find_median(v):\n if len(v) % 2 != 0:\n v.sort()\n median = v[len(v) // 2]\n return median\n elif len(v) == 2:\n a = sum(v)\n return a // len(v)\n else:\n v.sort()\n return (v[len(v) // 2] + v[len(v) // 2 - 1]) // 2", "def find_median(v):\n v.sort()\n if n % 2 != 0:\n return int(v[n // 2])\n return int((v[int((n - 1) / 2)] + v[int(n / 2)]) / 2.0)", "def find_median(v):\n l = len(v)\n v.sort()\n s = l % 2\n d = l // 2\n if s != 0:\n return v[d]\n else:\n return int((v[d - 1] + v[d]) / 2)", "def find_median(v):\n v.sort()\n length = len(v)\n z = length // 2\n if length % 2 == 1:\n return v[z]\n elif length % 2 == 0:\n xy = (v[z - 1] + v[z]) // 2\n return xy", "def find_median(v):\n z = sorted(v)\n n = len(z)\n if n % 2 != 0:\n return z[n // 2]\n else:\n return (z[n // 2 - 1] + z[n // 2]) // 2", "def find_median(v):\n v.sort()\n a = len(v)\n if len(v) % 2 == 1:\n return v[a // 2]\n else:\n n = a // 2\n return (v[n] + v[n - 1]) // 2", "import numpy as np\n\ndef find_median(v):\n m = np.median(v)\n return int(m)", "def find_median(v):\n z = sorted(v)\n length = len(z)\n middle = length // 2\n if length % 2 == 0:\n return (z[middle - 1] + z[middle]) // 2\n else:\n return z[middle]", "def find_median(arr):\n arr.sort()\n if n % 2 == 0:\n a = int(arr[int(n / 2)] + arr[int(n / 2 - 1)]) / 2\n return int(a)\n else:\n return arr[int(n / 2)]", "def find_median(v):\n v.sort()\n s = 0\n n = len(v)\n if n % 2 == 0:\n d = n // 2\n s = v[d] + v[d - 1]\n r = s // 2\n return r\n else:\n p = n // 2\n f = v[p]\n return f", "def find_median(v):\n a = sorted(v)\n if len(v) % 2 != 0:\n n = len(a) // 2\n return a[n]\n else:\n m = len(a) // 2\n ans = (a[m] + a[m - 1]) // 2\n return ans", "def find_median(v):\n arr = sorted(v)\n mid = len(arr) // 2\n if len(arr) % 2 == 0:\n mid = (arr[mid - 1] + arr[mid]) // 2\n return mid\n else:\n return arr[mid]", "def find_median(v):\n arr = sorted(v)\n n = len(v)\n return (arr[n // 2] + arr[(n - 1) // 2]) // 2", "import statistics\n\ndef find_median(v):\n return int(statistics.median(v))", "def find_median(v):\n l = len(v)\n v1 = sorted(v)\n if l % 2 == 0:\n median = (v1[l // 2 - 1] + v1[l // 2]) // 2\n else:\n median = v1[l // 2]\n return median", "def find_median(v):\n v.sort()\n l = len(v)\n k = l // 2\n n = int(l / 2)\n if l % 2 == 0:\n return int((v[n - 1] + v[n]) / 2)\n else:\n return v[k]", "import math\n\ndef find_median(v):\n v.sort()\n l = len(v)\n if l % 2 == 0:\n mid = (v[l // 2] + v[l // 2 - 1]) // 2\n else:\n mid = v[l // 2]\n return mid", "def find_median(v):\n c = sorted(v)\n N = len(c)\n if N % 2 == 1:\n return c[N // 2]\n else:\n sum = (c[N // 2] + c[N // 2 - 1]) / 2\n return int(sum)", "import statistics as sc\n\ndef find_median(v):\n a = sc.median(v)\n return int(a)", "import math\n\ndef find_median(v):\n n = len(v)\n v.sort()\n if n <= 1:\n return v[n - 1]\n return v[n // 2] if n % 2 != 0 else (v[n // 2 - 1] + v[n // 2]) // 2"], "starter_code": "def find_median(v):\n", "input_output": {"inputs": ["N = 5\narr[] = 90 100 78 89 67", "N = 4\narr[] = 56 67 30 79"], "outputs": ["89", "61"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical", "Divide and Conquer"], "name": null, "source": "geeksforgeeks", "tags": ["Divide and conquer", "Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/find-the-median0527/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n * log(n))", "entry_point": "find_median", "task_id": "TACO_lite/172", "example": [[[5, [90, 100, 78, 89, 67]], [4, [56, 67, 30, 79]]], ["89", "61"]]} +{"requirement": "Given a rooted binary tree, return the lowest common ancestor of its deepest leaves.\nRecall that:\n\nThe node of a binary tree is a leaf if and only if it has no children\nThe depth of the root of the tree is 0, and if the depth of a node is d, the depth of each of its children is d+1.\nThe lowest common ancestor of a set S of nodes is the node A with the largest depth such that every node in S is in the subtree with root A.\n\n \nExample 1:\nInput: root = [1,2,3]\nOutput: [1,2,3]\nExplanation: \nThe deepest leaves are the nodes with values 2 and 3.\nThe lowest common ancestor of these leaves is the node with value 1.\nThe answer returned is a TreeNode object (not an array) with serialization \"[1,2,3]\".\n\nExample 2:\nInput: root = [1,2,3,4]\nOutput: [4]\n\nExample 3:\nInput: root = [1,2,3,4,5]\nOutput: [2,4,5]\n\n \nConstraints:\n\nThe given tree will have between 1 and 1000 nodes.\nEach node of the tree will have a distinct value between 1 and 1000.", "solutions": ["def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def lca(root=root):\n if root:\n (n1, d1) = lca(root.left)\n (n2, d2) = lca(root.right)\n if d1 == d2:\n return (root, d1 + 1)\n else:\n return (n1, 1 + d1) if d1 > d2 else (n2, 1 + d2)\n return (None, -1)\n return lca()[0]", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def traverse(node):\n if not node:\n return (0, None)\n (hl, lcal) = traverse(node.left)\n (hr, lcar) = traverse(node.right)\n if hl < hr:\n return (hr + 1, lcar)\n elif hl > hr:\n return (hl + 1, lcal)\n else:\n return (hl + 1, node)\n return traverse(root)[1]", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n if not root:\n return None\n paths = []\n\n def dfs(n, ps):\n nonlocal paths\n if not n:\n return\n if not n.left and (not n.right):\n paths.append((len(ps), ps + [n]))\n if n.left:\n dfs(n.left, ps + [n])\n if n.right:\n dfs(n.right, ps + [n])\n dfs(root, [])\n paths = sorted(paths, key=lambda x: x[0], reverse=True)\n longest = []\n (depth, path) = paths[0]\n for (d, p) in paths:\n if d == depth:\n longest.append(p)\n if len(longest) == 1:\n return path[-1]\n for i in range(len(path)):\n if any((path[i] != p[i] for p in longest)):\n break\n return path[i - 1]\n\ndef lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def helper(node):\n if not node:\n return (0, None)\n (h1, lca1) = helper(node.left)\n (h2, lca2) = helper(node.right)\n if h1 > h2:\n return (h1 + 1, lca1)\n if h2 > h1:\n return (h2 + 1, lca2)\n if h1 == h2:\n return (h1 + 1, node)\n return helper(root)[1]", "from typing import Tuple\n\ndef lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def lcaDeepestLeavesRecursive(node: TreeNode) -> Tuple[int, TreeNode]:\n if node is None:\n return (0, None)\n else:\n (depthL, nodeL) = lcaDeepestLeavesRecursive(node.left)\n (depthR, nodeR) = lcaDeepestLeavesRecursive(node.right)\n if depthL > depthR:\n return (depthL + 1, nodeL)\n elif depthL < depthR:\n return (depthR + 1, nodeR)\n else:\n return (depthL + 1, node)\n return lcaDeepestLeavesRecursive(root)[1]", "def __init__():\n self.max_depth = 0\n self.ancestor = None\n\ndef lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n if not root:\n return root\n self.dfs(root, 0)\n return self.ancestor\n\ndef dfs(node: TreeNode, curr_depth) -> int:\n (curr_deepest_L, curr_deepest_R) = (curr_depth, curr_depth)\n if not node.left and (not node.right):\n if curr_depth > self.max_depth:\n self.max_depth = curr_depth\n self.ancestor = node\n return curr_depth\n if node.left:\n curr_deepest_L = self.dfs(node.left, curr_depth + 1)\n if node.right:\n curr_deepest_R = self.dfs(node.right, curr_depth + 1)\n if curr_deepest_L == curr_deepest_R == self.max_depth:\n self.ancestor = node\n return max(curr_deepest_L, curr_deepest_R)", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def get_depth(root):\n if not root:\n return 0\n else:\n return max(get_depth(root.left), get_depth(root.right)) + 1\n max_depth = get_depth(root)\n\n def dfs(root, depth):\n if not root:\n return root\n if get_depth(root.left) == get_depth(root.right) == depth - 1:\n return root\n return dfs(root.left, depth - 1) or dfs(root.right, depth - 1)\n return dfs(root, max_depth)", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def traverse(root, level):\n if root:\n if not root.left and (not root.right):\n return (level, root)\n else:\n (left_level, left_lca) = traverse(root.left, level + 1)\n (right_level, right_lca) = traverse(root.right, level + 1)\n if left_level == right_level:\n return (left_level, root)\n elif left_level > right_level:\n return (left_level, left_lca)\n else:\n return (right_level, right_lca)\n return (float('-inf'), None)\n (deepest_level, lca) = traverse(root, 0)\n return lca", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n dic = {}\n explore = [root]\n nextlevel = []\n while explore:\n leaf = explore\n for node in explore:\n if node.left:\n dic[node.left] = node\n nextlevel.append(node.left)\n if node.right:\n dic[node.right] = node\n nextlevel.append(node.right)\n (explore, nextlevel) = (nextlevel, [])\n newleaf = set()\n while len(leaf) > 1:\n for node in leaf:\n newleaf.add(dic[node])\n (leaf, newleaf) = (newleaf, set())\n for res in leaf:\n return res", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n return self.helper(root)[0]\n\ndef helper(root):\n if not root:\n return (None, 0)\n (n1, l1) = self.helper(root.left)\n (n2, l2) = self.helper(root.right)\n if l1 > l2:\n return (n1, l1 + 1)\n elif l1 < l2:\n return (n2, l2 + 1)\n else:\n return (root, l1 + 1)", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n (node0, node1) = (None, None)\n q = [root]\n while q:\n (node0, node1) = (q[0], q[-1])\n q = [child for node in q for child in (node.left, node.right) if child]\n if node0 == node1:\n return node0\n result = None\n\n def lca(root: TreeNode) -> bool:\n nonlocal result\n if root is None:\n return False\n left = lca(root.left)\n right = lca(root.right)\n if left and right:\n result = root\n return (root == node0 or root == node1) or left or right\n lca(root)\n return result", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def getDepth(root):\n if not root:\n return 0\n return 1 + max(getDepth(root.left), getDepth(root.right))\n maxDepth = getDepth(root)\n\n def helper(root, d):\n nonlocal ans, maxDepth\n if not root:\n return 0\n left = helper(root.left, d + 1)\n right = helper(root.right, d + 1)\n if left == right and left == maxDepth - d - 1:\n ans = root\n return 1 + max(left, right)\n ans = None\n helper(root, 0)\n return ans", "from collections import defaultdict\n\ndef __init__():\n self.deepest = -1\n self.m = defaultdict(list)\n\ndef lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n self.dfs(root, 0)\n if self.deepest == -1:\n return None\n if len(self.m[self.deepest]) == 1:\n return self.m[self.deepest][0]\n return self.lca(root, self.m[self.deepest])\n\ndef dfs(node, level):\n if node is None:\n return\n if level not in self.m:\n self.m[level] = []\n self.deepest = max(self.deepest, level)\n self.m[level].append(node)\n self.dfs(node.left, level + 1)\n self.dfs(node.right, level + 1)\n\ndef lca(x, nodes):\n if x is None:\n return x\n for node in nodes:\n if node == x:\n return x\n left = self.lca(x.left, nodes)\n right = self.lca(x.right, nodes)\n if left is not None and right is not None:\n return x\n return left if left is not None else right", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def height(root):\n if not root:\n return 0\n return 1 + max(height(root.left), height(root.right))\n if height(root.left) == height(root.right):\n return root\n elif height(root.left) > height(root.right):\n return self.lcaDeepestLeaves(root.left)\n return self.lcaDeepestLeaves(root.right)"], "starter_code": "def __init__(val=0, left=None, right=None):\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Binary Tree", "Breadth-First Search", "Depth-First Search", "Tree", "Hash Table"], "name": null, "source": "leetcode", "tags": ["Tree algorithms", "Data structures", "Graph traversal"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "__init__", "task_id": "TACO_lite/150", "example": [[[[1, 2, 3]], [[1, 2, 3, 4]], [[1, 2, 3, 4, 5]]], ["[1, 2, 3]", "[4]", "[2, 4, 5]"]]} +{"requirement": "In this Kata, you will be given an array of integers whose elements have both a negative and a positive value, except for one integer that is either only negative or only positive. Your task will be to find that integer. \n\nExamples:\n\n`[1, -1, 2, -2, 3] => 3`\n\n`3` has no matching negative appearance\n\n`[-3, 1, 2, 3, -1, -4, -2] => -4`\n\n`-4` has no matching positive appearance\n\n`[1, -1, 2, -2, 3, 3] => 3`\n\n(the only-positive or only-negative integer may appear more than once)\n\nGood luck!", "solutions": ["def solve(arr):\n return sum(set(arr))", "def solve(arr):\n for a in arr:\n if -a not in arr:\n return a", "def solve(a):\n return sum(set(a))", "def solve(arr):\n return [i for i in arr if -i not in arr][0]", "def solve(arr):\n for n in arr:\n if -n not in arr:\n return n", "def solve(arr):\n for x in arr:\n if x and -x not in arr:\n return x", "def solve(arr):\n for number in arr:\n if number * -1 in arr:\n pass\n else:\n return number", "def solve(arr):\n special_set = set(arr)\n n = 0\n for i in list(special_set):\n n += i\n return n", "def solve(arr):\n summa = 0\n dic = {}\n res = 0\n for i in arr:\n dic[i] = 0\n if -i in arr:\n dic[i] += 1\n else:\n dic[i] = 0\n for (key, value) in dic.items():\n if value == 0:\n res = key\n return res", "def solve(arr):\n for i in arr:\n if -1 * i not in arr:\n return i", "def solve(arr):\n result = 0\n for a in arr:\n if -a not in arr:\n return a", "def solve(arr):\n return [x for x in arr if not -x in arr][0]", "def solve(lst):\n return sum(set(lst))", "def solve(lst):\n for num in lst:\n if -num not in lst:\n return num", "def solve(arr):\n for num in arr:\n if not -num in arr:\n return num", "def solve(arr: list) -> int:\n for i in range(len(arr)):\n if -arr[i] not in arr:\n return arr[i]", "def solve(arr):\n nums = []\n unique = 0\n for i in arr:\n if -i in arr:\n nums.append(i)\n else:\n unique = i\n return unique", "def solve(arr):\n arr = set(arr)\n lst = list(map(abs, arr))\n one = 0\n for i in range(len(lst)):\n if lst.count(lst[i]) == 1:\n one = lst[i]\n if one in arr:\n return one\n else:\n a = '-' + str(one)\n return int(a)", "def solve(arr):\n result = []\n for i in arr:\n if arr.count(i) != arr.count(-i):\n result.append(i)\n return result[0]", "def solve(arr):\n ls = [arr[0]]\n for n in arr[1:]:\n if -n in ls:\n ls.pop(ls.index(-n))\n else:\n ls.append(n)\n return ls[0]", "def solve(arr):\n arr = sorted(arr)\n for i in range(len(arr) - 1):\n if arr[i] == arr[i + 1]:\n return arr[i]\n return sum(arr)", "def solve(arr):\n return [el for el in arr if -el not in arr][0]", "def solve(arr):\n positive = sorted([x for x in arr if x >= 0])\n negative = sorted([x for x in arr if x < 0], reverse=True)\n longer_index = len(positive) <= len(negative)\n longer = [positive, negative][longer_index]\n for i in [positive, negative][not longer_index]:\n longer.remove(-i)\n return longer[0]", "def solve(arr):\n rev = set((-x for x in arr))\n return [x for x in arr if abs(x) not in set(arr) or x not in rev][0]", "def solve(arr):\n for i in arr:\n reverse = -i\n if reverse not in arr:\n return i", "def solve(arr):\n for num in arr:\n if -num in arr:\n pass\n else:\n return num", "def solve(arr):\n a = [i for i in arr if arr.count(i) != arr.count(-i)]\n return a[0]", "def solve(arr):\n item = arr.pop()\n while -item in arr:\n arr.remove(-item)\n item = arr.pop()\n return item", "def solve(arr):\n for (index, value) in enumerate(arr):\n if value * -1 in arr:\n continue\n else:\n return value", "def solve(arr):\n for num in arr:\n if arr.count(num * -1) == 0:\n return num", "def solve(arr):\n values = set()\n removed_values = set()\n for value in arr:\n if value in removed_values:\n continue\n opposite = value * -1\n if opposite in values:\n values.remove(opposite)\n removed_values.add(value)\n removed_values.add(opposite)\n else:\n values.add(value)\n return list(values)[0]", "def solve(arr):\n result = arr[0]\n for i in range(len(arr)):\n pair = False\n for j in range(len(arr)):\n if arr[i] == -arr[j]:\n pair = True\n if not pair:\n result = arr[i]\n return result", "def solve(arr):\n positive_set = set()\n negative_set = set()\n for num in arr:\n if num > 0:\n positive_set.add(num)\n else:\n negative_set.add(-num)\n number = positive_set.symmetric_difference(negative_set)\n popped_number = number.pop()\n return popped_number if popped_number in arr else -popped_number", "def solve(arr):\n duplicates = [x for x in arr if arr.count(x) > 1]\n return duplicates[0] if duplicates else sum(arr)", "def solve(numbers):\n for x in numbers:\n if not -x in numbers:\n return x", "def solve(arr):\n while 1:\n number = arr[0]\n opposite_number = number * -1\n if opposite_number in arr:\n arr.remove(number)\n arr.remove(opposite_number)\n else:\n return arr[0]", "def solve(arr):\n for n in arr:\n if n < 0 and abs(n) not in arr:\n return n\n elif n > 0 and -n not in arr:\n return n", "def solve(arr):\n end = 0\n x = 0\n while end == 0:\n k = 1\n i = arr[x]\n for j in arr:\n if i == j * -1:\n k = 0\n if k == 1:\n ans = i\n end = 1\n x = x + 1\n return ans", "def match(vale, g):\n va = False\n for val in g:\n if val == -vale:\n va = True\n return va\n\ndef solve(g):\n m = []\n for val in g:\n if match(val, g) == False:\n m.append(val)\n return m[0]", "def solve(arr):\n cleaned = list(set(arr))\n for i in cleaned:\n if not -i in cleaned:\n return i", "def solve(a):\n for n in a:\n if -n in a:\n continue\n else:\n return n", "def solve(arr):\n return list(set(filter(lambda x: arr.count(x) != arr.count(-x), arr)))[0]", "def solve(arr):\n for i in range(0, len(arr)):\n if -arr[i] not in arr:\n return arr[i]", "def solve(arr):\n arr.sort()\n l = len(arr)\n neg = []\n pos = []\n for i in arr:\n if i < 0:\n neg.append(i)\n else:\n pos.append(i)\n if len(neg) > len(pos):\n for i in neg:\n if abs(i) not in pos:\n return i\n else:\n for i in pos:\n if -i not in neg:\n return i", "def solve(arr):\n return [value for value in arr if -value not in arr][0]", "def solve(arr):\n arr = set(arr)\n return next(filter(lambda i: not sum(arr) - i, arr))", "def solve(arr):\n arr = set(arr)\n for item in arr:\n if not sum(arr) - item:\n return item", "def solve(arr):\n return list(set((x for x in arr if x * -1 not in arr)))[0]", "def solve(arr):\n new_arr = [val for val in arr if not arr.count(-val)]\n return new_arr[0]", "def solve(arr):\n arr = set(arr)\n sum = 0\n for i in arr:\n sum += i\n return sum", "def solve(arr):\n for i in arr:\n if i and -i not in arr:\n return i", "def solve(arr):\n for i in arr:\n if -1 * i in arr:\n continue\n else:\n return i", "def solve(arr):\n a = 1\n for i in arr:\n if arr.count(i) > 1:\n a = arr.count(i)\n return sum(arr) / a", "def solve(arr):\n arr.sort()\n while len(arr) >= 1:\n if arr[0] < 0 and abs(arr[0]) in arr:\n x = abs(arr[0])\n arr.remove(arr[0])\n arr.remove(x)\n else:\n return arr[0]", "from collections import defaultdict\n\ndef solve(arr):\n d = defaultdict(int)\n for x in arr:\n d[abs(x)] += x\n return next((k if k in arr else -k for (k, v) in d.items() if v != 0))", "def solve(ar):\n x = len(ar)\n i = 0\n temp = 0\n while i < x:\n c = 0\n char = ar[i]\n while c <= x - 1:\n if char == -ar[c]:\n i += 1\n break\n c += 1\n else:\n temp = char\n return temp\n return temp", "def solve(ar):\n for item in ar:\n if -item not in ar:\n return item", "def solve(arr):\n pos = set([x for x in arr if x > 0])\n neg = set([abs(x) for x in list([x for x in arr if x < 0])])\n if pos.issubset(neg):\n return (neg - pos).pop() * -1\n else:\n return (pos - neg).pop()", "def solve(arr):\n for (idx, num) in enumerate(arr):\n if num in arr[:idx] + arr[idx + 1:]:\n return arr[idx]\n return sum(arr)", "def solve(arr):\n pos = []\n neg = []\n for i in arr:\n if i < 0:\n neg.append(i)\n else:\n pos.append(i)\n for i in neg:\n if abs(i) not in pos:\n return i\n break\n for j in pos:\n if -j not in neg:\n return j\n break", "def solve(arr):\n for (i, v) in enumerate(arr):\n isTrue = False\n for (k, kv) in enumerate(arr):\n if i == k:\n continue\n if v == arr[k] * -1:\n isTrue = True\n break\n if isTrue == False:\n return v", "def solve(arr):\n return sum(arr) / arr.count(max(arr, key=arr.count))", "def solve(arr):\n parr = []\n narr = []\n for i in arr:\n if i < 0:\n narr.append(i)\n else:\n parr.append(i)\n res = 0\n for a in narr:\n if abs(a) not in parr:\n res = a\n for b in parr:\n if b * -1 not in narr:\n res = b\n return res", "def solve(arr):\n check = []\n for i in arr:\n if -i not in arr:\n return i", "from collections import Counter\n\ndef solve(arr):\n return sum(arr) / Counter(arr).most_common(1)[0][1]", "def solve(arr):\n abs_arr = [abs(n) for n in arr]\n for n in set(abs_arr):\n if not (n in arr and -n in arr):\n return arr[abs_arr.index(n)]", "def solve(arr):\n for i in arr:\n (m, s) = (0, -i)\n for j in arr:\n if s == j:\n m = 1\n if m == 0:\n return i", "def solve(arr):\n for num in arr:\n if num > 0 and -num not in arr:\n return num\n elif num < 0 and num - num * 2 not in arr:\n return num", "def solve(arr):\n dict = {}\n for a in arr:\n if abs(a) not in dict:\n dict[abs(a)] = a\n elif dict[abs(a)] == a:\n return a\n break\n else:\n dict[abs(a)] = a + dict[abs(a)]\n for v in list(dict.values()):\n if v != 0:\n return v", "def solve(arr):\n newArr = []\n for x in arr:\n if x * -1 not in arr:\n return x", "def solve(arr):\n negative = set([i for i in arr if i < 0])\n positive = set([i for i in arr if i > 0])\n res = None\n for i in negative:\n if i * -1 not in positive:\n res = i\n for i in positive:\n if i * -1 not in negative:\n res = i\n return res", "def solve(arr):\n for i in range(len(arr)):\n count = 0\n if arr.count(arr[i]) > 1:\n return arr[i]\n for j in range(len(arr)):\n if arr[i] == -arr[j]:\n count += 1\n if count != 1:\n return arr[i]", "from collections import Counter\n\ndef solve(arr):\n c = Counter(arr)\n for (k, v) in c.items():\n if k * -1 not in c.keys():\n return k", "import collections\n\ndef solve(arr):\n count = collections.Counter(arr)\n for number in arr:\n if not count[-number]:\n return number", "def solve(arr):\n for val in arr:\n if -1 * val not in arr:\n return val", "def solve(arr):\n sum = 0\n times = 0\n ele = {}\n for i in arr:\n if i in ele:\n ele[i] = ele[i] + i\n else:\n ele[i] = i\n sum = sum + i\n for (k, v) in ele.items():\n if v == sum:\n if -k not in arr:\n times = sum / k\n if times > 1:\n sum = sum / times\n return sum", "def solve(arr):\n for num in arr:\n if arr.count(num) > arr.count(-num):\n return num\n elif arr.count(-num) > arr.count(num):\n return -num", "def solve(arr):\n for (i, el) in enumerate(arr):\n if arr.count(el * -1) == 0:\n return el", "def solve(arr):\n return sum(dict.fromkeys(arr))", "def solve(arr):\n for i in arr:\n n = 0\n for j in arr:\n n += 1\n if i + j == 0:\n break\n if len(arr) == n and i + j != 0:\n return i", "def solve(arr):\n while len(set(arr)) > 1:\n for i in range(len(arr) - 1):\n if arr.count(-arr[i]):\n arr.remove(-arr[i])\n arr.remove(arr[i])\n break\n return list(set(arr))[0]", "def solve(arr):\n for i in range(0, len(arr)):\n num = arr[i]\n reversenumber = -num\n found = False\n for index in range(0, len(arr)):\n if i == index:\n continue\n if reversenumber == arr[index]:\n found = True\n break\n if found == False:\n return num"], "starter_code": "def solve(arr):\n", "input_output": {"fn_name": "solve", "inputs": [[[1, -1, 2, -2, 3]], [[-3, 1, 2, 3, -1, -4, -2]], [[1, -1, 2, -2, 3, 3]], [[-110, 110, -38, -38, -62, 62, -38, -38, -38]], [[-9, -105, -9, -9, -9, -9, 105]]], "outputs": [[3], [-4], [3], [-38], [-9]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms"], "name": null, "source": "codewars", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5a092d9e46d843b9db000064", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/133", "example": [[[[1, -1, 2, -2, 3]], [[-3, 1, 2, 3, -1, -4, -2]], [[1, -1, 2, -2, 3, 3]]], ["3", "-4", "3"]]} +{"requirement": "Take a sentence (string) and reverse each word in the sentence. Do not reverse the order of the words, just the letters in each word.\n\nIf there is punctuation, it should be interpreted as a regular character; no special rules.\n\nIf there is spacing before/after the input string, leave them there.\n\nString will not be empty.\n\n## Examples\n\n```\n\"Hi mom\" => \"iH mom\"\n\" A fun little challenge! \" => \" A nuf elttil !egnellahc \"\n```", "solutions": ["def reverser(sentence):\n return ' '.join((i[::-1] for i in sentence.split(' ')))", "def reverser(s):\n return ' '.join((w[::-1] for w in s.split(' ')))", "import re\n\ndef reverser(sentence):\n return ''.join((w[::-1] if ' ' not in w else w for w in re.findall('(?:\\\\w+)|(?:\\\\s+)', sentence)))", "from re import compile\nr = compile('(\\\\W)')\n\ndef reverser(sentence: str) -> str:\n return ''.join((w[::-1] for w in r.split(sentence)))", "def reverser(sentence):\n emt = ' '\n split_it = sentence.split(' ')\n for word in split_it:\n emt += word[::-1] + ' '\n return emt[1:-1]", "import re\n\ndef reverser(sentence):\n return ''.join((i[::-1] for i in re.split('(\\\\s+)', sentence)))", "def reverser(sentence):\n newsent = sentence.split(' ')\n rnsent = [i[::-1] for i in newsent]\n s = ' '\n s = s.join(rnsent)\n return s", "def reverser(sentence):\n text = sentence.split(' ')\n ans = []\n for i in text:\n ans.append(i[::-1])\n return ' '.join(ans)", "def reverser(sentence):\n ans = ''\n word = ''\n for letter in sentence:\n if letter == ' ':\n ans = ans + word[::-1] + letter\n word = ''\n else:\n word = word + letter\n return ans + word[::-1]", "reverser = lambda x: ' '.join([i[::-1] for i in x.split(' ')])"], "starter_code": "def reverser(sentence):\n", "input_output": {"fn_name": "reverser", "inputs": [["How now brown cow"], ["racecar"], ["Hi mom"], [" "], [" "], ["go away"], ["I like noodles"], ["The red pen wrote on the wall"], ["Green trucks drive fast"], ["Pink trucks drive slow"]], "outputs": [["woH won nworb woc"], ["racecar"], ["iH mom"], [" "], [" "], ["og yawa"], ["I ekil seldoon"], ["ehT der nep etorw no eht llaw"], ["neerG skcurt evird tsaf"], ["kniP skcurt evird wols"]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/57ebdf944cde58f973000405", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "reverser", "task_id": "TACO_lite/149", "example": [[["Hi mom"], [" A fun little challenge! "]], ["iH mom", " A nuf elttil !egnellahc "]]} +{"requirement": "Some new cashiers started to work at your restaurant. \n\nThey are good at taking orders, but they don't know how to capitalize words, or use a space bar! \n\nAll the orders they create look something like this:\n\n`\"milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza\"`\n\nThe kitchen staff are threatening to quit, because of how difficult it is to read the orders. \n\nTheir preference is to get the orders as a nice clean string with spaces and capitals like so:\n\n`\"Burger Fries Chicken Pizza Pizza Pizza Sandwich Milkshake Milkshake Coke\"`\n\nThe kitchen staff expect the items to be in the same order as they appear in the menu. \n\nThe menu items are fairly simple, there is no overlap in the names of the items:\n```\n1. Burger\n2. Fries\n3. Chicken\n4. Pizza\n5. Sandwich\n6. Onionrings\n7. Milkshake\n8. Coke\n```", "solutions": ["def get_order(order):\n menu = ['burger', 'fries', 'chicken', 'pizza', 'sandwich', 'onionrings', 'milkshake', 'coke']\n clean_order = ''\n for i in menu:\n clean_order += (i.capitalize() + ' ') * order.count(i)\n return clean_order[:-1]", "MENU = ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke']\n\ndef get_order(order):\n result = []\n for item in MENU:\n result.extend([item for _ in range(order.count(item.lower()))])\n return ' '.join(result)", "menu = 'Burger Fries Chicken Pizza Sandwich Onionrings Milkshake Coke'.split()\n\ndef get_order(order):\n return ' '.join((item for item in menu for _ in range(order.count(item.lower()))))", "def get_order(order):\n output = ''\n while order != '':\n if output == '':\n if order.find('burger') != -1:\n output += 'Burger'\n order = order.replace('burger', '', 1)\n elif order.find('fries') != -1:\n output += 'Fries'\n order = order.replace('fries', '', 1)\n elif order.find('chicken') != -1:\n output += 'Chicken'\n order = order.replace('chicken', '', 1)\n elif order.find('pizza') != -1:\n output += 'Pizza'\n order = order.replace('pizza', '', 1)\n elif order.find('sandwich') != -1:\n output += 'Sandwich'\n order = order.replace('sandwich', '', 1)\n elif order.find('onionrings') != -1:\n output += 'Onionrings'\n order = order.replace('onionrings', '', 1)\n elif order.find('milkshake') != -1:\n output += 'Milkshake'\n order = order.replace('milkshake', '', 1)\n elif order.find('coke') != -1:\n output += 'Coke'\n order = order.replace('coke', '', 1)\n elif output != '':\n if order.find('burger') != -1:\n output += ' Burger'\n order = order.replace('burger', '', 1)\n elif order.find('fries') != -1:\n output += ' Fries'\n order = order.replace('fries', '', 1)\n elif order.find('chicken') != -1:\n output += ' Chicken'\n order = order.replace('chicken', '', 1)\n elif order.find('pizza') != -1:\n output += ' Pizza'\n order = order.replace('pizza', '', 1)\n elif order.find('sandwich') != -1:\n output += ' Sandwich'\n order = order.replace('sandwich', '', 1)\n elif order.find('onionrings') != -1:\n output += ' Onionrings'\n order = order.replace('onionrings', '', 1)\n elif order.find('milkshake') != -1:\n output += ' Milkshake'\n order = order.replace('milkshake', '', 1)\n elif order.find('coke') != -1:\n output += ' Coke'\n order = order.replace('coke', '', 1)\n return output", "import re\nMENU = {v: i for (i, v) in enumerate('Burger Fries Chicken Pizza Sandwich Onionrings Milkshake Coke'.split())}\nREG_CMD = re.compile('|'.join(MENU), flags=re.I)\n\ndef get_order(order):\n return ' '.join(sorted(map(str.title, REG_CMD.findall(order)), key=MENU.get))", "from re import findall\n\ndef get_order(order):\n menu = ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke']\n return ' '.join(filter(None, (' '.join(findall(item.lower(), order)).title() for item in menu)))", "def get_order(order):\n (menu, Menu) = (['burger', 'fries', 'chicken', 'pizza', 'sandwich', 'onionrings', 'milkshake', 'coke'], ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke'])\n (str, num) = ('', 0)\n (lst, lst2, result) = ([], [], [])\n for letter in order:\n str += letter\n if str in menu:\n lst.append(str)\n str = ''\n for word in lst:\n lst2.append(word.capitalize())\n for counter in range(0, 8):\n for word in lst2:\n if word == Menu[counter]:\n result.append(word)\n return ' '.join(result)", "import re\nMENU = ['burger', 'fries', 'chicken', 'pizza', 'sandwich', 'onionrings', 'milkshake', 'coke']\n\ndef get_order(order):\n res = []\n for item in MENU:\n res.extend(re.findall(item, order))\n return ' '.join([item.capitalize() for item in res])", "get_order = lambda order: ''.join([item * order.count(item[1:].lower()) for item in ' Burger, Fries, Chicken, Pizza, Sandwich, Onionrings, Milkshake, Coke'.split(',')])[1:]", "def get_order(order):\n menu = ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke']\n return ''.join([(item + ' ') * order.count(item.lower()) for item in menu]).strip()", "def get_order(order):\n word = ''\n list = ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke']\n for i in list:\n word = word + (' ' + i) * order.count(i.lower())\n return word.strip()"], "starter_code": "def get_order(order):\n", "input_output": {"fn_name": "get_order", "inputs": [["burgerfriesfriesfriesfriesfriespizzasandwichcokefriesburger"]], "outputs": [["Burger Burger Fries Fries Fries Fries Fries Fries Pizza Sandwich Coke"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5d23d89906f92a00267bb83d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "get_order", "task_id": "TACO_lite/178", "example": [[["milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"]], ["Burger Fries Chicken Pizza Pizza Pizza Sandwich Milkshake Milkshake Coke"]]} +{"requirement": "Given an integer array arr, you should partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray.\nReturn the largest sum of the given array after partitioning.\n \nExample 1:\nInput: arr = [1,15,7,9,2,5,10], k = 3\nOutput: 84\nExplanation: arr becomes [15,15,15,9,10,10,10]\n\nExample 2:\nInput: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4\nOutput: 83\n\nExample 3:\nInput: arr = [1], k = 1\nOutput: 1\n\n \nConstraints:\n\n1 <= arr.length <= 500\n0 <= arr[i] <= 109\n1 <= k <= arr.length", "solutions": ["def maxsumafterpartitioning(arr, k):\n res = [0]\n for (idx, val) in enumerate(arr):\n (max_val, cur_val) = (0, 0)\n for i in range(max(0, idx - k + 1), idx + 1)[::-1]:\n if arr[i] > max_val:\n max_val = arr[i]\n if res[i] + (idx - i + 1) * max_val > cur_val:\n cur_val = res[i] + (idx - i + 1) * max_val\n res.append(cur_val)\n return res[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n ans = [0]\n for (r, n) in enumerate(A):\n (maxVal, curVal) = (0, 0)\n for l in range(max(0, r - K + 1), r + 1)[::-1]:\n if A[l] > maxVal:\n maxVal = A[l]\n if ans[l] + (r - l + 1) * maxVal > curVal:\n curVal = ans[l] + (r - l + 1) * maxVal\n ans.append(curVal)\n return ans[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n dp = [A[0]]\n for i in range(1, len(A)):\n max_partition_sum = A[i] + dp[-1]\n max_element = A[i]\n end = i - K\n if end < -1:\n end = -1\n for j in range(i - 1, end, -1):\n if A[j] > max_element:\n max_element = A[j]\n partition_sum = (i - j + 1) * max_element\n if j > 0:\n partition_sum += dp[j - 1]\n if partition_sum > max_partition_sum:\n max_partition_sum = partition_sum\n dp.append(max_partition_sum)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n return self.dp(arr, 0, k, {})\n\ndef dp(arr, i, k, hashmap):\n if i >= len(arr):\n return 0\n if i in hashmap:\n return hashmap[i]\n largest = 0\n ans = 0\n for idx in range(k):\n if idx + i >= len(arr):\n break\n largest = max(largest, arr[i + idx])\n ans = max(ans, largest * (idx + 1) + self.dp(arr, i + idx + 1, k, hashmap))\n hashmap[i] = ans\n return ans", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n return self.recur(arr, len(arr) - 1, k, {})\n\ndef recur(arr, index, k, hashMap):\n if index < 0:\n return 0\n if index in hashMap:\n return hashMap[index]\n result = 0\n maxV = 0\n for i in range(k):\n if index - i < 0:\n continue\n maxV = max(maxV, arr[index - i])\n result = max(result, maxV * (i + 1) + self.recur(arr, index - i - 1, k, hashMap))\n hashMap[index] = result\n return result", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n self.dp = {}\n\n def recur(index, arr, k):\n if index >= len(arr):\n return 0\n if index in self.dp:\n return self.dp[index]\n maxi = 0\n res = 0\n for i in range(k):\n if index + i < len(arr):\n maxi = max(maxi, arr[index + i])\n res = max(res, maxi * (i + 1) + recur(index + i + 1, arr, k))\n self.dp[index] = res\n return res\n return recur(0, arr, k)", "def util(i, n, A, K, d):\n if i >= n:\n return 0\n if i not in d:\n count = 0\n ma = A[i]\n temp = -1\n while i + count < n and count <= K - 1:\n if A[i + count] > ma:\n ma = A[i + count]\n nex = self.util(i + count + 1, n, A, K, d)\n if (count + 1) * ma + nex > temp:\n temp = (count + 1) * ma + nex\n count += 1\n d[i] = temp\n return d[i]\n\ndef maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n d = {}\n return self.util(0, n, A, K, d)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n visited = {}\n\n def recurse(index):\n if index >= len(A):\n return 0\n if index in visited:\n return visited[index]\n mxx = 0\n ans = 0\n for i in range(K):\n if index + i < len(A):\n mxx = max(mxx, A[i + index])\n ans = max(ans, mxx * (i + 1) + recurse(i + index + 1))\n visited[index] = ans\n return ans\n return recurse(0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0] * len(arr)\n dp[0] = arr[0]\n max_value = arr[0]\n max_sum = arr[0]\n for i in range(1, k):\n max_value = max(max_value, arr[i])\n dp[i] = max_value * (i + 1)\n for i in range(k, len(arr)):\n max_value = 0\n for j in range(k):\n max_value = max(max_value, arr[i - j])\n dp[i] = max(dp[i], dp[i - j - 1] + max_value * (j + 1))\n return dp[-1]", "from collections import deque\n\ndef maxsumafterpartitioning(A: List[int], K: int) -> int:\n dp = deque([0 for i in range(K)])\n for i in range(1, len(A) + 1):\n (maxA, maxP) = (float('-inf'), float('-inf'))\n for j in range(1, min(K + 1, i + 1)):\n maxA = max(maxA, A[i - j])\n maxP = max(maxP, dp[-j] + j * maxA)\n dp.popleft()\n dp.append(maxP)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n inf = 1061109567\n dp = [[(-inf, -inf) for _ in range(k + 1)] for _ in range(2)]\n last_max = 0\n dp[0][0] = (0, 0)\n for i in range(1, len(arr) + 1):\n for j in range(1, k + 1):\n if j == 1:\n dp[i % 2][j] = (last_max + arr[i - 1], arr[i - 1])\n last_max = dp[i % 2][j][0]\n elif i >= j:\n (last_s, last_n) = dp[(i - 1) % 2][j - 1]\n n = max(last_n, arr[i - 1])\n s = last_s - last_n * (j - 1) + n * j\n dp[i % 2][j] = (s, n)\n last_max = max(last_max, s)\n return last_max", "def maxsumafterpartitioning(A, K):\n N = len(A)\n dp = [0] * (N + 1)\n for i in range(N):\n curMax = 0\n for k in range(1, min(K, i + 1) + 1):\n curMax = max(curMax, A[i - k + 1])\n dp[i] = max(dp[i], dp[i - k] + curMax * k)\n return dp[N - 1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n N = len(A)\n if K == 1 or N == 1:\n return sum(A)\n dp = [0] * (N + 1)\n dp[0] = 0\n for i in range(N):\n mv = A[i]\n dp[i + 1] = dp[i] + A[i]\n for j in range(1, min(i + 1, K)):\n mv = max(mv, A[i - j])\n dp[i + 1] = max(dp[i + 1], dp[i - j] + (j + 1) * mv)\n return dp[N]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n size = len(A)\n if K == 1:\n return sum(A)\n dp = [0] * (size + 1)\n for i in range(size):\n cur_max = A[i]\n block_size = 1\n while block_size <= K and i - block_size + 1 >= 0:\n cur_max = max(cur_max, A[i - block_size + 1])\n dp[i + 1] = max(dp[i + 1], dp[i - block_size + 1] + block_size * cur_max)\n block_size += 1\n return dp[size]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [[-1] * (n + 1) for _ in range(n + 1)]\n\n def maxsum(i=0):\n if i >= n:\n return 0\n elif dp[i][n] != -1:\n return dp[i][n]\n else:\n mx = 0\n for j in range(i, min(i + k, n)):\n mx = max(arr[j], mx)\n dp[i][j] = mx * (j - i + 1)\n dp[i][n] = max(dp[i][n], dp[i][j] + maxsum(j + 1))\n return dp[i][n]\n return maxsum()", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0] * (n := len(arr))\n dp[0] = curr_max = arr[0]\n for i in range(1, k):\n curr_max = max(curr_max, arr[i])\n dp[i] = (i + 1) * curr_max\n for i in range(k, n):\n curr_max = arr[i]\n for j in range(k):\n curr_max = max(curr_max, arr[i - j])\n dp[i] = max(dp[i], dp[i - j - 1] + (j + 1) * curr_max)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], K: int) -> int:\n n = len(arr)\n dp = [0 for _ in range(n + 1)]\n for i in range(n):\n currMax = 0\n for k in range(1, min(K, i + 1) + 1):\n currMax = max(currMax, arr[i - k + 1])\n dp[i] = max(dp[i], dp[i - k] + currMax * k)\n return dp[n - 1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n if arr is None or len(arr) == 0:\n return 0\n dp = [0 for _ in range(len(arr))]\n for i in range(len(arr)):\n max_elem = arr[i]\n j = 1\n while j <= k and i - j + 1 >= 0:\n max_elem = max(max_elem, arr[i - j + 1])\n if i - j >= 0:\n dp[i] = max(dp[i], max_elem * j + dp[i - j])\n else:\n dp[i] = max(dp[i], max_elem * j)\n j += 1\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n dp = [0] * (n + 1)\n for (i, a) in enumerate(A):\n r = a\n for j in range(1, K + 1):\n r = max(r, A[i - j + 1] if i - j + 1 >= 0 else float('-inf'))\n if i - j + 1 >= 0:\n dp[i + 1] = max(dp[i + 1], dp[i - j + 1] + r * j)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n self.dp = [-1 for i in range(n)]\n\n def helper(pos: int) -> int:\n if pos >= n:\n return 0\n if self.dp[pos] != -1:\n return self.dp[pos]\n current_max = arr[pos]\n ret = arr[pos] + helper(pos + 1)\n for i in range(1, k):\n pos2 = pos + i\n if pos2 >= n:\n break\n current_max = max(current_max, arr[pos2])\n ret = max(ret, current_max * (i + 1) + helper(pos2 + 1))\n self.dp[pos] = ret\n return ret\n return helper(0)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n maxSum = [0] * n\n for i in range(-1, -K - 1, -1):\n maxSum[i] = max(A[i:]) * -i\n for i in range(n - K - 1, -1, -1):\n ms = 0\n for k in range(1, K + 1):\n ms = max(ms, max(A[i:i + k]) * k + maxSum[i + k])\n maxSum[i] = ms\n return maxSum[0]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n\n def helper(index, start, mx):\n if index == len(arr):\n return (index - start) * mx\n if index - start + 1 <= k:\n return max(helper(index + 1, start, max(arr[index], mx)), (index - start) * mx + helper(index + 1, index, arr[index]))\n return (index - start) * mx + helper(index + 1, index, arr[index])\n return helper(0, 0, arr[0])", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n dp = [0] * len(A)\n for i in range(K):\n dp[i] = max(A[:i + 1]) * (i + 1)\n for i in range(K, len(A)):\n dp[i] = max([dp[i - j] + max(A[i - j + 1:i + 1]) * j for j in range(1, K + 1)])\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [[(0, 0)] * k for _ in range(len(arr) + 1)]\n for i in range(1, len(arr) + 1):\n for j in range(min(i, k)):\n if j == 0:\n dp[i][j] = max(((dp[i - 1][m][0] + arr[i - 1], arr[i - 1]) for m in range(min(i, k))))\n else:\n new_max = max(dp[i - 1][j - 1][1], arr[i - 1])\n dp[i][j] = (dp[i - 1][j - 1][0] - j * dp[i - 1][j - 1][1] + new_max * (j + 1), new_max)\n return max(dp[-1])[0]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0] * n\n for i in range(n - 1, -1, -1):\n curr_max = arr[i]\n for j in range(0, k):\n index = min(n - 1, i + j)\n curr_max = max(curr_max, arr[index])\n if i + j + 1 >= n:\n dp[i] = (n - i) * curr_max\n else:\n dp[i] = max(dp[i], dp[i + j + 1] + (j + 1) * curr_max)\n return dp[0]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n if not arr:\n return 0\n local_max = {(idx, idx + 1): arr[idx] for idx in range(len(arr))}\n for l in range(2, k + 1):\n for start in range(len(arr) - l + 1):\n local_max[start, start + l] = max(local_max[start, start + l - 1], local_max[start + 1, start + l])\n f = [0]\n for end in range(1, len(arr) + 1):\n _local = 0\n for start in range(max(0, end - k), end):\n _local = max(f[start] + local_max[start, end] * (end - start), _local)\n f.append(_local)\n return f[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n memo = [0] * n\n for i in range(n):\n if i < k:\n memo[i] = (i + 1) * max(arr[:i + 1])\n else:\n memo[i] = max((memo[i - j - 1] + (j + 1) * max(arr[i - j:i + 1]) for j in range(k)))\n return memo[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n length = len(arr)\n dp = [0] * (length + 1)\n maxval = [[0] * length for _ in range(length)]\n for i in range(length):\n for j in range(i, length):\n if i == j:\n maxval[i][j] = arr[i]\n else:\n maxval[i][j] = max(maxval[i][j - 1], arr[j])\n for i in range(1, length + 1):\n temp = 0\n for t in range(1, k + 1):\n temp = max(temp, dp[i - t] + maxval[i - t][i - 1] * t)\n dp[i] = temp\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n\n def dfs(i, j, max_num=0):\n if i == -1:\n return max_num * j\n if opt[i][j] == -1:\n (a, b) = (0, 0)\n if j < K:\n a = dfs(i - 1, j + 1, max(max_num, A[i]))\n b = j * max_num + dfs(i - 1, 1, A[i])\n opt[i][j] = max(a, b)\n return opt[i][j]\n n = len(A)\n opt = [[-1] * (K + 1) for _ in range(n)]\n return dfs(n - 1, 0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n l = len(arr)\n results = [0] * l\n for (idx, num) in enumerate(arr):\n if idx < k:\n results[idx] = max(arr[:idx + 1]) * (idx + 1)\n else:\n res = 0\n for i in range(1, k + 1):\n start = idx - i\n tmp = results[start] + max(arr[start + 1:idx + 1]) * i\n res = max(res, tmp)\n results[idx] = res\n return results[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n max_sums = [0] * len(arr)\n for i in range(len(arr)):\n if i <= k - 1:\n max_sums[i] = (i + 1) * max(arr[:i + 1])\n else:\n res = 0\n for j in range(1, k + 1):\n first = max_sums[i - j]\n second = j * max(arr[i - j + 1:i + 1])\n res = max(res, first + second)\n max_sums[i] = res\n return max_sums[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n maxx = arr[0]\n dp = []\n for (i, _) in enumerate(arr[:k]):\n maxx = max(arr[i], maxx)\n dp.append(maxx * (i + 1))\n for (i, _) in enumerate(arr[k:]):\n i += k\n max_sum = 0\n for j in range(k):\n max_sum = max(max_sum, dp[i - j - 1] + max(arr[i - j:i + 1]) * (j + 1))\n dp.append(max_sum)\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n N = len(A)\n dp = [float('-inf')] * (N + 1)\n for i in range(1, N + 1):\n if i <= K:\n dp[i] = max(A[:i]) * i\n else:\n for j in range(1, K + 1):\n dp[i] = max(dp[i], dp[i - j] + max(A[i - j:i]) * j)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n M = [0 for i in range(len(arr))]\n M[0] = arr[0]\n for i in range(1, len(arr)):\n if i < k:\n M[i] = max(arr[:i + 1]) * (i + 1)\n else:\n for j in range(1, min(k + 1, i + 1)):\n M[i] = max(M[i], M[i - j] + max(arr[i - j + 1:i + 1]) * j)\n return M[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n rec = {}\n\n def helper(idx):\n if idx in rec:\n return rec[idx]\n if len(arr) - idx <= k:\n temp = max(arr[idx:]) * (len(arr) - idx)\n rec[idx] = temp\n return temp\n pre_max = float('-inf')\n temp = float('-inf')\n for j in range(idx, min(idx + k, len(arr))):\n pre_max = max(pre_max, arr[j])\n temp = max(temp, pre_max * (j - idx + 1) + helper(j + 1))\n rec[idx] = temp\n return temp\n return helper(0)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n\n def maxSum(i, mem):\n if i in mem:\n return mem[i]\n if len(A) - i <= K:\n mem[i] = max(A[i:]) * (len(A) - i)\n return mem[i]\n ans = -float('inf')\n for j in range(i + 1, i + 1 + K):\n if j > len(A):\n break\n ans = max(ans, max(A[i:j]) * (j - i) + maxSum(j, mem))\n mem[i] = ans\n return mem[i]\n mem = {}\n return maxSum(0, mem)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n largest_sums = []\n for i in range(len(A)):\n if i < K:\n largest_sums.append(max(A[:i + 1]) * (i + 1))\n continue\n max_sum = 0\n for j in range(K):\n if i - (j + 1) < 0:\n continue\n cur_sum = largest_sums[i - j - 1] + max(A[i - j:i + 1]) * (j + 1)\n if cur_sum > max_sum:\n max_sum = cur_sum\n largest_sums.append(max_sum)\n return largest_sums[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n aLen = len(A)\n dp = {}\n\n def helper(i0):\n if i0 in dp:\n return dp[i0]\n if aLen - i0 <= K:\n dp[i0] = max(A[i0:]) * (aLen - i0)\n return dp[i0]\n subAns = 0\n thisMax = A[i0]\n for ki in range(1, K + 1):\n thisMax = max(thisMax, A[i0 + ki - 1])\n subAns = max(subAns, thisMax * ki + helper(i0 + ki))\n dp[i0] = subAns\n return subAns\n return helper(0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n maxes = [[None for _ in range(n)] for _ in range(n)]\n for i in range(n):\n maxes[i][i] = arr[i]\n for i in range(n):\n for j in range(i + 1, n):\n maxes[i][j] = max(arr[j], maxes[i][j - 1])\n dp = [None for _ in range(n + 1)]\n dp[n] = 0\n for i in range(n - 1, -1, -1):\n m = float('-inf')\n for j in range(min(n - i, k)):\n m = max(m, (j + 1) * maxes[i][min(n - 1, i + j)] + dp[min(n, i + j + 1)])\n dp[i] = m\n return dp[0]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n\n def helper(index, start, mx):\n key = (index, start, mx)\n if key in d:\n return d[key]\n if index == len(arr):\n return (index - start) * mx\n if index - start + 1 <= k:\n d[key] = max(helper(index + 1, start, max(arr[index], mx)), (index - start) * mx + helper(index + 1, index, arr[index]))\n return d[key]\n d[key] = (index - start) * mx + helper(index + 1, index, arr[index])\n return d[key]\n d = dict()\n return helper(0, 0, arr[0])", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n\n def checkSum(i, j, k):\n if j - i <= k:\n return max(A[i:j]) * (j - i)\n else:\n best = 0\n for nk in range(1, K + 1):\n best = max(best, checkSum(i, i + nk, K) + checkSum(i + nk, j, K))\n return best\n return checkSum(0, len(A), K)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n N = len(A)\n arr = [[(0, 0)] * (K + 1) for _ in range(N)]\n prev = 0\n for i in range(N):\n arr[i][1] = (A[i] + prev, A[i])\n prev += A[i]\n for j in range(2, min(i + 2, K + 1)):\n mx = max(arr[i - 1][j - 1][1], A[i])\n s = arr[i - 1][j - 1][0] - arr[i - 1][j - 1][1] * (j - 1) + mx * j\n arr[i][j] = (s, mx)\n prev = max(prev, s)\n return max((arr[-1][k][0] for k in range(1, K + 1)))", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n if not A:\n return 0\n N = len(A)\n if K == N:\n return N * max(A)\n dp = [0 for i in range(N)]\n for i in range(K):\n dp[i] = max(A[:i + 1]) * (i + 1)\n for i in range(K, N):\n a = max(A[i - K + 1:i + 1])\n dp[i] = max([dp[i - j] + j * max(A[i - j + 1:i + 1]) for j in range(1, K + 1)])\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n\n def help(A, K):\n n = len(A)\n if K == 1:\n return sum(A)\n if K >= n:\n return n * max(A)\n cMax = [A[0]]\n for i in range(1, K):\n cMax.append(max(cMax[-1], A[i]))\n return max(((i + 1) * cMax[i] + help(A[i + 1:], K) for i in range(K)))\n return help(tuple(A), K)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n grid = [0] * len(arr)\n for i in range(len(arr) - 1, -1, -1):\n if len(arr) - i <= k:\n grid[i] = max(arr[i:len(arr)]) * (len(arr) - i)\n else:\n maxi = 0\n current_max = 0\n for t in range(k):\n current_max = max(current_max, arr[i + t])\n maxi = max(maxi, current_max * (t + 1) + grid[i + t + 1])\n grid[i] = maxi\n return grid[0]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n if not arr:\n return 0\n if k == 1:\n return sum(arr)\n self.memo = {}\n\n def makepart(arr, n):\n if n in self.memo:\n return self.memo[n]\n if not arr:\n return 0\n l = min(k, len(arr))\n maxele = 0\n total = 0\n for i in range(l):\n maxele = max(maxele, arr[i])\n temp = maxele * (i + 1) + makepart(arr[i + 1:], n + i + 1)\n total = max(total, temp)\n self.memo[n] = total\n return total\n return makepart(arr, 0)", "def maxsumafterpartitioning(A: List[int], k: int) -> int:\n\n def dfs(i, j, max_num=0):\n if i == -1:\n return max_num * j\n if (i, j, max_num) not in opt:\n ans = 0\n if j < k:\n ans = max(ans, dfs(i - 1, j + 1, max(max_num, A[i])))\n ans = max(ans, j * max_num + dfs(i - 1, 1, A[i]))\n opt[i, j, max_num] = ans\n return opt[i, j, max_num]\n n = len(A)\n opt = dict()\n return dfs(n - 1, 0)", "def maxsumafterpartitioning(arr, k: int) -> int:\n n = len(arr)\n mask = [[0] * n for i in range(n)]\n for i in range(n):\n for j in range(i, n):\n mask[i][j] = max(arr[j], mask[i][j - 1] if j > i else 0)\n for i in range(n):\n for j in range(i, n):\n mask[i][j] = (j + 1 - i) * mask[i][j]\n dp = [0] * n\n for i in range(n):\n for h in range(1, k + 1):\n dp[i] = max((dp[i - h] if i - h >= 0 else 0) + (mask[i - h + 1][i] if i - h + 1 < n else 0), dp[i])\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n self.answer = {}\n\n def max_starting_i(index_A):\n array = A[index_A:]\n if index_A in self.answer:\n return self.answer[index_A]\n if len(array) == 0:\n self.answer[index_A] = 0\n return 0\n if len(array) <= K:\n self.answer[index_A] = max(array) * len(array)\n return self.answer[index_A]\n max_start_here = 0\n for i in range(0, K):\n max_split_here = (i + 1) * max(array[:i + 1]) + max_starting_i(index_A + i + 1)\n max_start_here = max(max_start_here, max_split_here)\n self.answer[index_A] = max_start_here\n return max_start_here\n return max_starting_i(0)", "def maxsumafterpartitioning(l: List[int], k: int) -> int:\n\n def _max_sum(l, start, k, memo):\n if len(l) - start <= k:\n return (len(l) - start) * max(l[start:])\n if start in memo:\n return memo[start]\n max_sum = l[start]\n for i in range(1, k + 1):\n curr_sum = max(l[start:start + i]) * i + _max_sum(l, start + i, k, memo)\n max_sum = max(max_sum, curr_sum)\n memo[start] = max_sum\n return max_sum\n if not l:\n return 0\n return _max_sum(l, 0, k, dict())", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n self.dp = [-1] * (len(arr) + k)\n return self.solve(arr, 0, k)\n\ndef solve(arr, start, k):\n if start >= len(arr):\n return 0\n if start + k >= len(arr):\n end = min(len(arr), start + k)\n return max(arr[start:end]) * (end - start)\n if self.dp[start] != -1:\n return self.dp[start]\n result = float('-inf')\n for p in range(1, k + 1):\n temp = max(arr[start:start + p]) * p + self.solve(arr, start + p, k)\n result = max(temp, result)\n self.dp[start] = result\n return result", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n self.cache = {}\n\n def helper(arr, k, start):\n if start in self.cache:\n return self.cache[start]\n _arr = arr[start:]\n if len(_arr) == 0:\n return 0\n if len(_arr) <= k:\n return max(_arr) * len(_arr)\n ans = -1\n for i in range(1, k + 1):\n ans = max(ans, i * max(_arr[:i]) + helper(arr, k, start + i))\n self.cache[start] = ans\n return ans\n return helper(arr, k, 0)", "import typing\n\ndef maxsumafterpartitioning(arr: typing.List[int], k: int) -> int:\n storage = {}\n\n def getSumRec(arr: list, i: int, k: int) -> int:\n if i in storage:\n return storage[i]\n if not i < len(arr):\n return 0\n if len(arr) - i < k:\n return max(arr[i:]) * len(arr[i:])\n listOfSums = []\n for offset in range(k):\n listOfSums.append(max(arr[i:i + offset + 1]) * (offset + 1) + getSumRec(arr, i + offset + 1, k))\n storage[i] = max(listOfSums)\n return storage[i]\n return getSumRec(arr, 0, k)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n best_a = [0] * len(A)\n best_a[0] = A[0]\n for i in range(1, len(A)):\n max_v = 0\n for j in range(i, max(-1, i - K), -1):\n sa = A[j:i + 1]\n v = best_a[j - 1] + max(sa) * len(sa)\n if v > max_v:\n max_v = v\n best_a[i] = max_v\n return best_a[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0] * (len(arr) + 1)\n for i in range(0, len(arr)):\n m = 0\n for j in range(i, i - k, -1):\n if j < 0:\n break\n t = max(arr[j:i + 1]) * (i - j + 1) + dp[j]\n if t > m:\n m = t\n dp[i + 1] = m\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp_sum = [0] * n\n dp_sum[0] = arr[0]\n max_so_far = arr[0]\n for i in range(1, k):\n max_so_far = max(max_so_far, arr[i])\n dp_sum[i] = (i + 1) * max_so_far\n for i in range(k, n):\n partition_max = 0\n for back in range(k):\n partition_max = max(partition_max, arr[i - back])\n dp_sum[i] = max(dp_sum[i], dp_sum[i - back - 1] + (back + 1) * partition_max)\n return dp_sum[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n opt = [arr[0]]\n for i in range(1, len(arr)):\n opt.append(0)\n subseqLenMax = min(k, i + 1)\n for subseqLen in range(1, subseqLenMax + 1):\n subseqSum = subseqLen * max(arr[i - subseqLen + 1:i + 1])\n if subseqLen < i + 1:\n prevOpt = opt[i - subseqLen]\n else:\n prevOpt = 0\n optTemp = prevOpt + subseqSum\n if optTemp > opt[i]:\n opt[i] = optTemp\n return opt[len(opt) - 1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n dp = [0] * (n + 1)\n for i in range(1, n + 1):\n for w in range(1, K + 1):\n if i - w < 0:\n break\n dp[i] = max(dp[i], dp[i - w] + max(A[i - w:i]) * w)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n if not arr:\n return 0\n if n == 1:\n return arr[0]\n if n < k:\n return sum(arr)\n dp = [0] * n\n for i in range(n):\n for j in range(i, max(-1, i - k), -1):\n dp[i] = max(dp[i], max(arr[j:i + 1]) * (i - j + 1) + (dp[j - 1] if j - 1 >= 0 else 0))\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n N = len(arr)\n T = [0] * (N + 1)\n for i in range(1, N + 1):\n for j in range(1, k + 1):\n if j > i:\n break\n T[i] = max(T[i], T[i - j] + max(arr[i - j:i]) * j)\n return T[N]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n if k == 1:\n return sum(arr)\n if k == len(arr):\n max_val = max(arr)\n return max_val * len(arr)\n sums = [-1 for index in range(k)]\n maxs = [-1 for index in range(k)]\n max_sum = 0\n sums[0] = arr[0]\n maxs[0] = arr[0]\n for idx in range(1, len(arr)):\n val = arr[idx]\n max_sum = max(sums)\n for ki in range(k - 1, 0, -1):\n max_val = maxs[ki - 1]\n if not max_val < 0:\n if val <= max_val:\n maxs[ki] = max_val\n sums[ki] = sums[ki - 1] + max_val\n else:\n maxs[ki] = val\n sums[ki] = sums[ki - 1] - max_val * ki + val * (ki + 1)\n sums[0] = max_sum + val\n maxs[0] = val\n return max(sums)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0] * len(arr)\n for i in range(len(arr)):\n maxsum = 0\n for j in range(k):\n if i - j >= 1:\n maxsum = max(maxsum, (j + 1) * max(arr[i - j:i + 1]) + dp[i - j - 1])\n elif i - j >= 0:\n maxsum = max(maxsum, (j + 1) * max(arr[i - j:i + 1]))\n dp[i] = maxsum\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [float('-inf') for _ in range(n + 1)]\n dp[0] = 0\n for i in range(1, n + 1):\n j = i - 1\n cnt = k\n while j >= 0 and cnt >= 1:\n maximum = max(arr[j:i])\n dp[i] = max(dp[i], dp[j] + maximum * (i - j))\n j -= 1\n cnt -= 1\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n dp = [0] * (len(A) + 1)\n for i in range(1, len(A) + 1):\n temp = []\n for j in range(1, K + 1):\n if i - j >= 0:\n k = dp[i - j] + max(A[i - j:i]) * j\n temp.append(k)\n dp[i] = max(temp)\n return dp[len(A)]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0 for _ in range(k + 1)]\n rolling_max = -1\n for i in range(0, k):\n rolling_max = max(rolling_max, arr[i])\n dp[i] = rolling_max * (i + 1)\n for i in range(k, len(arr)):\n rolling_max = arr[i]\n for j in range(1, k + 1):\n rolling_max = max(rolling_max, arr[i - j + 1])\n dp[i % (k + 1)] = max(rolling_max * j + dp[(i - j) % (k + 1)], dp[i % (k + 1)])\n return dp[(len(arr) - 1) % (k + 1)]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0 for num in arr]\n for i in range(len(arr)):\n prev_sum = 0 if i - 1 < 0 else dp[i - 1]\n max_at_i = arr[i] + prev_sum\n possible_ks = i if i < k - 1 else k - 1\n for j in range(1, possible_ks + 1):\n current_window = arr[i - j:i + 1]\n current_max = max(current_window)\n current_window_sum = len(current_window) * current_max\n prev_window_sum = 0 if i - j - 1 < 0 else dp[i - j - 1]\n total_sum = current_window_sum + prev_window_sum\n if total_sum > max_at_i:\n max_at_i = total_sum\n dp[i] = max_at_i\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n L = len(arr)\n record = dict()\n record[0] = 0\n for idx in range(1, L + 1):\n r = -float('inf')\n for gap in range(1, k + 1):\n if idx - gap < 0:\n continue\n else:\n r = max(r, max(arr[idx - gap:idx]) * gap + record[idx - gap])\n record[idx] = r\n return record[L]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n hashmap = {}\n\n def partitionMatrix(lst, currScore):\n key = tuple(lst)\n if key in hashmap:\n return hashmap[key] + currScore\n if lst == []:\n hashmap[key] = 0\n return currScore\n for i in range(1, k + 1):\n if len(lst) == i:\n hashmap[key] = max(lst) * i\n return currScore + max(lst) * i\n best = currScore\n for i in range(1, k + 1):\n subScore = max(lst[:i]) * i\n best = max(best, partitionMatrix(lst[i:], currScore + subScore))\n hashmap[key] = best - currScore\n return best\n return partitionMatrix(arr, 0)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n\n def rec(l, h):\n if h - l < K:\n dp[l][h] = (h - l + 1) * max(A[l:h + 1])\n return dp[l][h]\n m = []\n if dp[l][h] > 0:\n return dp[l][h]\n for i in range(0, K):\n m += [rec(l, l + i) + rec(l + i + 1, h)]\n dp[l][h] = max(m)\n return dp[l][h]\n dp = [0] * len(A)\n dp = [[0] * len(A) for i in range(len(A))]\n rec(0, len(A) - 1)\n return dp[0][len(A) - 1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n size = len(arr)\n mem = [0] * size\n for i in range(size):\n mem[i] = arr[i]\n for j in range(0, k):\n if i - j > 0:\n candidate = max(arr[i - j:i + 1]) * (j + 1) + mem[i - j - 1]\n mem[i] = max(mem[i], candidate)\n elif i - j == 0:\n candidate = max(arr[i - j:i + 1]) * (j + 1)\n mem[i] = max(mem[i], candidate)\n else:\n break\n return mem[size - 1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0]\n for i in range(len(arr)):\n max_sum = -float('inf')\n for j in range(1, k + 1):\n if i - j + 1 < 0:\n break\n max_sum = max(max_sum, max(arr[i - j + 1:i + 1]) * j + dp[i - j + 1])\n dp.append(max_sum)\n return dp[-1]", "def getMax(arr, k, idx, cache):\n if idx == len(arr) - 1:\n return arr[idx]\n maxSum = 0\n for numInPartition in range(1, k + 1):\n if idx + numInPartition > len(arr):\n break\n startOfRecursiveIndex = idx + numInPartition\n maxVal = max(arr[idx:startOfRecursiveIndex])\n partSum = maxVal * numInPartition\n rest = cache[startOfRecursiveIndex] if startOfRecursiveIndex in cache else self.getMax(arr, k, startOfRecursiveIndex, cache)\n cache[startOfRecursiveIndex] = rest\n maxSum = max(maxSum, partSum + rest)\n return maxSum\n\ndef maxsumafterpartitioning(A: List[int], K: int) -> int:\n cache = {}\n return self.getMax(A, K, 0, cache)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n mem = {}\n\n def find(s, e):\n if (s, e) in mem:\n return mem[s, e]\n if e - s == 1:\n return arr[s]\n elif e - s == 0:\n return 0\n else:\n m = None\n for i in range(s + 1, min(s + k + 1, len(arr) + 1)):\n subsum = max(arr[s:i]) * (i - s) + find(i, e)\n if m is None or subsum > m:\n m = subsum\n mem[s, e] = m\n return m\n return find(0, len(arr))", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n from functools import lru_cache\n\n def dp(i):\n ans = 0\n for k in range(K):\n if i - k >= 0:\n ans = max(ans, max(A[i - k:i + 1]) * (k + 1) + dp(i - k - 1))\n return ans\n return dp(len(A) - 1)", "def maxsumafterpartitioning(arr, k):\n if not arr:\n return 0\n dp = [0] * len(arr)\n for i in range(len(arr)):\n for j in range(k):\n if i - j < 0:\n continue\n max_val = max(arr[i - j:i + 1])\n if i - j == 0:\n total = max_val * (j + 1)\n else:\n total = dp[i - j - 1] + max_val * (j + 1)\n dp[i] = max(dp[i], total)\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n N = len(A)\n dp = [0] * N\n dp[0] = A[0]\n for i in range(1, N):\n for j in range(0, min(K, i + 1)):\n current_subarray = A[i - j:i + 1]\n if i >= K:\n dp[i] = max(dp[i], dp[i - j - 1] + max(current_subarray) * (j + 1))\n else:\n dp[i] = max(dp[i], max(current_subarray) * (j + 1))\n return dp[-1]\n (0, 1)\n (1, 1)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n dp = [0] * n\n for i in range(n):\n if i == 0:\n dp[i] = A[0]\n else:\n for k in range(1, K + 1):\n if i - k + 1 < 0:\n break\n elif i - k + 1 == 0:\n dp[i] = max(dp[i], max(A[i - k + 1:i + 1]) * k)\n else:\n dp[i] = max(dp[i], dp[i - k] + max(A[i - k + 1:i + 1]) * k)\n return dp[n - 1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n dp = [0] * (n + 1)\n for i in range(n):\n for k in range(1, K + 1):\n if i - k > -2:\n dp[i + 1] = max(dp[i + 1], max(A[max(0, i - k + 1):i + 1]) * k + dp[i + 1 - k])\n return dp[n]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0] * len(arr)\n dp[0] = arr[0]\n for (i, val) in enumerate(arr):\n if i == 0:\n continue\n cur_max = val + dp[i - 1]\n cur_k = 1\n while i - cur_k >= 0 and cur_k < k:\n temp = arr[i - cur_k:i + 1]\n m = max(temp)\n if i - cur_k == 0:\n cur_max = max(cur_max, m * (cur_k + 1))\n else:\n cur_max = max(cur_max, m * (cur_k + 1) + dp[i - cur_k - 1])\n cur_k += 1\n dp[i] = cur_max\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n DP = [0 for _ in range(len(arr) + 1)]\n for i in range(1, len(DP)):\n loc = max(i - k, 0)\n run_max = 0\n for j in range(loc, i):\n run_max = max(run_max, DP[j] + max(arr[j:i]) * (i - j))\n DP[i] = run_max\n return DP[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n if not K or K == 1:\n return sum(A)\n if not A:\n return 0\n dp = [0] * len(A)\n for (index, num) in enumerate(A):\n possible = []\n for group in range(K):\n if index - group >= 0:\n if index - group - 1 >= 0:\n previous = dp[index - group - 1]\n else:\n previous = 0\n possible.append(previous + max(A[index - group:index + 1]) * (group + 1))\n dp[index] = max(possible)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n self.arr = arr\n self.dp = {}\n\n def helper(i, j, k):\n if j <= i:\n return 0\n if (i, j) in self.dp:\n return self.dp[i, j]\n maxsum = -sys.maxsize\n for length in range(1, k + 1):\n if i + length <= j:\n currsum = max(self.arr[i:i + length]) * length + helper(i + length, j, k)\n maxsum = max(maxsum, currsum)\n self.dp[i, j] = maxsum\n return self.dp[i, j]\n return helper(0, len(arr), k)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n dp = [0 for _ in A]\n for (i, num) in enumerate(A):\n for j in range(K):\n ans = 0\n if i - j >= 0:\n ans = ans + (j + 1) * max(A[i - j:i + 1])\n if i - j - 1 >= 0:\n ans = ans + dp[i - j - 1]\n dp[i] = max(dp[i], ans)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n d = [0] * (1 + len(arr) + k)\n for ind in range(1, len(arr) + 1):\n for sub_arr_st in range(min(ind, k)):\n if arr[ind - sub_arr_st - 1] > arr[ind - 1]:\n break\n for sub_arr_len in range(sub_arr_st + 1, k + 1):\n ind_x = ind - sub_arr_st + sub_arr_len - 1\n d[ind_x] = max(d[ind_x], d[ind - sub_arr_st - 1] + arr[ind - 1] * sub_arr_len)\n return d[len(arr)]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0] * (len(arr) + 1)\n dp[0] = arr[0]\n for i in range(1, len(arr)):\n ans = -100000\n for z in range(max(0, i - k + 1), i + 1):\n ans = max(dp[z - 1] + max(arr[z:i + 1]) * (i - z + 1), ans)\n dp[i] = ans\n return dp[-2]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n memo = {}\n l_arr = len(arr)\n for chain_len in range(0, k, 1):\n for i in range(0, l_arr - chain_len, 1):\n memo[i, i + chain_len] = max(arr[i:i + chain_len + 1]) * (chain_len + 1)\n res_memo = {}\n\n def dfs(idx):\n if idx == l_arr:\n return 0\n if idx in res_memo:\n return res_memo[idx]\n res_memo[idx] = max((memo[idx, idx + j] + dfs(idx + j + 1) for j in range(k) if idx + j < l_arr))\n return res_memo[idx]\n return dfs(0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n res = [0] * (len(arr) + 1)\n for i in range(1, len(arr) + 1):\n for j in range(1, k + 1):\n if i - j > -1:\n res[i] = max(res[i], res[i - j] + max(arr[i - j:i]) * j)\n return res[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n ar_len = len(arr)\n dp = [0] * (ar_len + 1)\n for i in range(1, len(dp)):\n tmp_max = []\n for j in range(1, k + 1):\n if i - j >= 0:\n max_t = dp[i - j] + max(arr[i - j:i]) * j\n tmp_max.append(max_t)\n dp[i] = max(tmp_max)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n if k == n:\n return n * max(arr)\n dp = collections.deque([0] * k)\n for i in range(n - 1, -1, -1):\n m = 0\n result = 0\n for j in range(min(k, n - i)):\n m = max(m, arr[i + j])\n result = max(result, m * (j + 1) + dp[j])\n dp.appendleft(result)\n dp.pop()\n return dp[0]", "def maxsumafterpartitioning(nums: List[int], k: int) -> int:\n dp = [0] * len(nums)\n for i in range(len(nums)):\n for windowSize in range(1, k + 1):\n startIndex = i - windowSize + 1\n if startIndex < 0:\n break\n maxVal = max(nums[startIndex:i + 1])\n currVal = windowSize * maxVal\n currSum = currVal\n if startIndex > 0:\n currSum += dp[startIndex - 1]\n dp[i] = max(dp[i], currSum)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n memo = {n: 0}\n\n def helper(arr, i):\n if i in memo:\n return memo[i]\n res = 0\n for j in range(i, min(n, i + k)):\n res = max(res, helper(arr, j + 1) + max(arr[i:j + 1]) * (j + 1 - i))\n memo[i] = res\n return res\n return helper(arr, 0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n result = [0] * len(arr)\n result[0] = arr[0]\n max_val = result[0]\n for i in range(1, k):\n max_val = max(max_val, arr[i])\n result[i] = max_val * (i + 1)\n for i in range(k, len(arr)):\n max_val = arr[i]\n for j in range(1, k + 1):\n max_val = max(max_val, arr[i - j + 1])\n result[i] = max(result[i], result[i - j] + max_val * j)\n return result[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n A = arr\n K = k\n n = len(A)\n dp = [0] * n\n curMax = 0\n for i in range(n):\n if i < K:\n curMax = max(curMax, A[i])\n dp[i] = curMax * (i + 1)\n else:\n curMax = 0\n for j in range(1, K + 1):\n curMax = max(A[i - j + 1], curMax)\n dp[i] = max(dp[i], dp[i - j] + curMax * j)\n return dp[n - 1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0] * (n + 1)\n for i in range(1, n + 1):\n max_val = float('-inf')\n for j in range(1, min(i, k) + 1):\n max_val = max(max_val, arr[i - j])\n dp[i] = max(dp[i], dp[i - j] + j * max_val)\n return dp[n]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n f = [0]\n for end in range(1, len(arr) + 1):\n _local = 0\n _cur_max = 0\n for start in range(end - 1, max(0, end - k) - 1, -1):\n _cur_max = max(_cur_max, arr[start])\n _local = max(_cur_max * (end - start) + f[start], _local)\n f.append(_local)\n return f[-1]", "def maxsumafterpartitioning(arr, k):\n n = len(arr)\n dp = [0] * (n + 1)\n for i in range(n):\n cmax = 0\n for j in range(1, min(k, i + 1) + 1):\n cmax = max(cmax, arr[i - j + 1])\n dp[i] = max(dp[i], dp[i - j] + cmax * j)\n return dp[-2]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n best_sums = [0] * (len(arr) + 1)\n for i in range(len(arr)):\n curr_max = 0\n for j in range(1, min(k + 1, i + 2)):\n curr_max = max(curr_max, arr[i - j + 1])\n best_sums[i] = max(best_sums[i], best_sums[i - j] + j * curr_max)\n return best_sums[-2]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n DP = [0] * len(arr)\n N = len(arr)\n DP[0] = arr[0]\n m = arr[0]\n for i in range(k):\n m = max(m, arr[i])\n DP[i] = m * (i + 1)\n for i in range(k, N):\n mm = arr[i]\n DP[i] = DP[i - 1] + arr[i]\n for j in range(1, k):\n mm = max(mm, arr[i - j])\n DP[i] = max(DP[i], DP[i - j - 1] + mm * (j + 1))\n return DP[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0] * (n + 1)\n for i in range(n):\n cur = 0\n for j in range(1, min(k, i + 1) + 1):\n cur = max(cur, arr[i - j + 1])\n dp[i] = max(dp[i], cur * j + dp[i - j])\n return dp[-2]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n\n def dp(idx):\n if idx < 0:\n return 0\n left = max(idx - k + 1, 0)\n curr_max = arr[idx]\n res = arr[idx]\n for i in range(idx, left - 1, -1):\n curr_max = max(curr_max, arr[i])\n res = max(res, dp(i - 1) + (idx - i + 1) * curr_max)\n return res\n return dp(len(arr) - 1)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n N = len(arr)\n dp = [0] * (N + 1)\n for i in range(N):\n cur_max = 0\n for j in range(1, min(k, i + 1) + 1):\n cur_max = max(cur_max, arr[i - j + 1])\n dp[i] = max(dp[i], dp[i - j] + cur_max * j)\n return dp[N - 1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n N = len(arr)\n dp = [0 for _ in range(N)]\n dp[0] = arr[0]\n max_so_far = arr[0]\n for i in range(1, k):\n max_so_far = max(max_so_far, arr[i])\n dp[i] = (i + 1) * max_so_far\n for i in range(k, N):\n max_so_far = -sys.maxsize\n for j in range(i, i - k, -1):\n max_so_far = max(max_so_far, arr[j])\n dp[i] = max(dp[i], dp[j - 1] + (i - j + 1) * max_so_far)\n return dp[N - 1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n dp = [0] * (n + 1)\n for i in range(1, n + 1):\n j = i - 1\n mx = -float('inf')\n while i - j <= K and j >= 0:\n mx = max(mx, A[j])\n dp[i] = max(dp[i], dp[j] + mx * (i - j))\n j -= 1\n return dp[n]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n N = len(A)\n DP = [0] * (N + 1)\n for i in range(N):\n curMax = 0\n for k in range(1, min(K, i + 1) + 1):\n curMax = max(curMax, A[i - k + 1])\n DP[i] = max(DP[i], DP[i - k] + curMax * k)\n return DP[N - 1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0] * (n + 1)\n for i in range(n):\n cur_max = 0\n for d in range(1, min(k, i + 1) + 1):\n cur_max = max(cur_max, arr[i - d + 1])\n dp[i + 1] = max(dp[i + 1], dp[i + 1 - d] + cur_max * d)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0]\n for i in range(1, len(arr) + 1):\n max_arr_num = 0\n now_max = 0\n for j in range(1, k + 1):\n idx = i - j\n if idx >= 0:\n max_arr_num = max(max_arr_num, arr[idx])\n now_max = max(now_max, dp[idx] + max_arr_num * j)\n dp.append(now_max)\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n dp = [0] * (n + 1)\n for i in range(1, n + 1):\n m = float('-inf')\n for j in range(1, K + 1):\n if i - j >= 0:\n m = max(A[i - j], m)\n dp[i] = max(dp[i], dp[i - j] + m * j)\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n dp = [0] * (n + 1)\n res = 0\n for i in range(n):\n max_val = 0\n for k in range(1, min(K, i + 1) + 1):\n max_val = max(max_val, A[i - k + 1])\n dp[i] = max(dp[i], dp[i - k] + max_val * k)\n return dp[n - 1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n N = len(A)\n dp = [0] * (N + 1)\n for i in range(N):\n curr_max = 0\n for j in range(1, K + 1):\n if i + j > N:\n break\n curr_max = max(curr_max, A[i + j - 1])\n dp[i + j] = max(dp[i + j], dp[i] + curr_max * j)\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n dp = [float('-inf') for i in range(len(A) + 1)]\n dp[-1] = 0\n dp[-2] = A[-1]\n for j in reversed(list(range(len(A) - 1))):\n cur_max = float('-inf')\n for k in range(K):\n if j + k == len(A):\n break\n cur_max = max(cur_max, A[j + k])\n dp[j] = max(dp[j], (k + 1) * cur_max + dp[j + k + 1])\n return dp[0]", "def maxsumafterpartitioning(A: List[int], k: int) -> int:\n N = len(A)\n dp = [0] * (N + 1)\n for i in range(N):\n mx = 0\n for j in range(i, max(-1, i - k), -1):\n mx = max(mx, A[j])\n p = dp[i + 1]\n dp[i + 1] = max(dp[i + 1], dp[j] + mx * (i - j + 1))\n return dp[N]", "def maxsumafterpartitioning(A, K):\n n = len(A)\n record = [0] * (n + 1)\n for i in range(n):\n curMax = 0\n for k in range(1, min(K, i + 1) + 1):\n curMax = max(curMax, A[i - k + 1])\n record[i + 1] = max(record[i + 1], record[i - k + 1] + curMax * k)\n return record[n]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0] * (n + 1)\n for i in range(1, n + 1):\n m = -float('inf')\n d = 0\n while d < k and i - d > 0:\n m = max(m, arr[i - 1 - d])\n dp[i] = max(dp[i], dp[i - d - 1] + m * (d + 1))\n d += 1\n return dp[n]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n N = len(arr)\n memo = {}\n\n def maxSum2(i):\n if i >= N:\n return 0\n if i in memo:\n return memo[i]\n val = -1\n sol = -1\n for j in range(1, min(k + 1, N - i + 1)):\n val = max(val, arr[i + j - 1])\n sol = max(sol, val * j + maxSum2(i + j))\n memo[i] = sol\n return sol\n return maxSum2(0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0] * (n + 1)\n for i in range(n):\n currMax = arr[i]\n size = 1\n while size <= k and i - size + 1 >= 0:\n currMax = max(currMax, arr[i - size + 1])\n dp[i + 1] = max(dp[i + 1], dp[i + 1 - size] + currMax * size)\n size += 1\n return dp[n]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n memo = {}\n\n def max_sum(idx):\n if idx >= len(arr):\n return 0\n if idx in memo:\n return memo[idx]\n subarr_max = float('-inf')\n options = []\n for end in range(idx, min(idx + k, len(arr))):\n subarr_max = max(subarr_max, arr[end])\n subarr_sum = subarr_max * (end - idx + 1)\n options.append(subarr_sum + max_sum(end + 1))\n memo[idx] = max(options)\n return memo[idx]\n return max_sum(0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n memo = {}\n\n def dfs(i):\n if i >= n:\n return 0\n if i in memo:\n return memo[i]\n res = float('-inf')\n cur_max = float('-inf')\n for j in range(i, min(i + k, n)):\n cur_max = max(cur_max, arr[j])\n res = max(res, cur_max * (j - i + 1) + dfs(j + 1))\n memo[i] = res\n return res\n return dfs(0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n N = len(arr)\n maxSoFar = [0] * N\n for i in range(N):\n curMax = 0\n for prev in range(1, min(i + 1, k) + 1):\n curMax = max(curMax, arr[i - prev + 1])\n lastPartition = maxSoFar[i - prev] if i >= prev else 0\n maxSoFar[i] = max(maxSoFar[i], lastPartition + curMax * prev)\n return maxSoFar[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n\n def dfs(start, memo):\n if start in memo:\n return memo[start]\n N = len(A)\n if start >= N:\n return 0\n maxSum = 0\n maxEle = 0\n for i in range(start, min(N, start + K)):\n maxEle = max(maxEle, A[i])\n maxSum = max(maxSum, maxEle * (i - start + 1) + dfs(i + 1, memo))\n memo[start] = maxSum\n return maxSum\n return dfs(0, {})", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n if arr == [] or k == 0:\n return 0\n if len(arr) == 1 and k == 1:\n return arr[0]\n l = len(arr)\n res = [0] * l\n for i in range(0, l):\n sub_max = 0\n for j in range(k):\n if j <= i:\n sub_max = max(sub_max, arr[i - j])\n res[i] = max(res[i], sub_max * (j + 1) + (res[i - j - 1] if i - j - 1 >= 0 else 0))\n return res[l - 1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = len(arr) * [0]\n dp[0] = arr[0]\n for i in range(1, len(arr)):\n sub_max = 0\n for j in range(k):\n if j <= i:\n sub_max = max(sub_max, arr[i - j])\n dp[i] = max(dp[i], sub_max * (j + 1) + (dp[i - j - 1] if i - j - 1 >= 0 else 0))\n return dp[len(arr) - 1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n dp_sum = [0 for _ in range(len(A) + 1)]\n for i in range(len(A)):\n seg_max = A[i]\n for j in range(1, K + 1):\n if i - j + 1 < 0:\n break\n seg_max = max(seg_max, A[i - j + 1])\n tmp = dp_sum[i - j + 1] + seg_max * j\n dp_sum[i + 1] = max(dp_sum[i + 1], tmp)\n return dp_sum[-1]", "def maxsumafterpartitioning(A: List[int], k: int) -> int:\n L = len(A)\n vis = {}\n\n def pos(n):\n if n >= L:\n return 0\n if n in vis:\n return vis[n]\n currmax = A[n]\n ans = A[n] + pos(n + 1)\n for i in range(1, k):\n n1 = n + i\n if n1 >= L:\n break\n currmax = max(currmax, A[n1])\n ans = max(ans, currmax * (i + 1) + pos(n1 + 1))\n vis[n] = ans\n return vis[n]\n return pos(0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n if not arr:\n return 0\n n = len(arr)\n dp = [0 for _ in range(n)]\n for i in range(n):\n temp_max = arr[i]\n j = 1\n while i - j + 1 >= 0 and j <= k:\n temp_max = max(temp_max, arr[i - j + 1])\n if i >= j:\n dp[i] = max(dp[i], dp[i - j] + temp_max * j)\n else:\n dp[i] = max(dp[i], temp_max * j)\n j += 1\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [-1 for _ in range(n)]\n\n def max_sum(i):\n if i >= n:\n return 0\n if i == n - 1:\n return arr[i]\n if dp[i] != -1:\n return dp[i]\n ans = float('-inf')\n maxi = arr[i]\n for p in range(1, k + 1):\n v = maxi * p + max_sum(i + p)\n ans = max(v, ans)\n if i + p < n:\n maxi = max(maxi, arr[i + p])\n else:\n break\n dp[i] = ans\n return ans\n v = max_sum(0)\n return v", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = {}\n\n def help(arr, k, start=0):\n if start == len(arr):\n return 0\n if start in dp:\n return dp[start]\n dp[start] = -float('inf')\n maxval = arr[start]\n for i in range(start, min(start + k, len(arr))):\n maxval = max(maxval, arr[i])\n dp[start] = max(dp[start], maxval * (i - start + 1) + help(arr, k, i + 1))\n return dp[start]\n return help(arr, k)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n N = len(arr)\n K = k\n dp = [0] * (N + 1)\n for i in range(N):\n curMax = 0\n for k in range(1, min(K, i + 1) + 1):\n curMax = max(curMax, arr[i - k + 1])\n dp[i] = max(dp[i], dp[i - k] + curMax * k)\n return dp[N - 1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n memo = {}\n\n def getMax(arr, k, idx):\n if idx == len(arr):\n return 0\n if idx in memo:\n return memo[idx]\n (maxSum, maxInSub) = (0, 0)\n for i in range(idx, min(idx + K, len(arr))):\n maxInSub = max(maxInSub, arr[i])\n maxSum = max(maxSum, maxInSub * (i - idx + 1) + getMax(arr, k, i + 1))\n memo[idx] = maxSum\n return maxSum\n return getMax(A, K, 0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0] * (n + 1)\n dp[1] = arr[0]\n for i in range(2, n + 1):\n dp[i] = dp[i - 1] + arr[i - 1]\n cur_max = arr[i - 1]\n for j in range(1, k + 1):\n cur_max = max(cur_max, arr[i - j])\n if i - j >= 0:\n dp[i] = max(dp[i], dp[i - j] + j * cur_max)\n return dp[n]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0] * (len(arr) + 1)\n for i in range(1, len(arr) + 1):\n dp[i] = float('-inf')\n curr_max = arr[i - 1]\n for p in range(1, k + 1):\n if p > i:\n break\n curr_max = max(curr_max, arr[i - p])\n dp[i] = max(dp[i], p * curr_max + dp[i - p])\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n self.max_sum = float('-inf')\n self.dic = {}\n\n def getSum(i):\n if i >= len(A):\n return 0\n if i in self.dic:\n return self.dic[i]\n cur_max = A[i]\n ret = cur_max + getSum(i + 1)\n for j in range(1, K):\n if i + j < len(A):\n if A[i + j] > cur_max:\n cur_max = A[i + j]\n ret = max(cur_max * (j + 1) + getSum(i + j + 1), ret)\n else:\n break\n self.dic[i] = ret\n return ret\n return getSum(0)", "def rec(idx):\n if idx > len(self.A):\n return 0\n max_yet = 0\n max_score = 0\n for i in range(self.K):\n if idx + i >= len(self.A):\n break\n max_yet = max(max_yet, self.A[idx + i])\n max_score = max(max_score, max_yet * (i + 1) + self.rec(idx + i + 1))\n return max_score\n\ndef maxsumafterpartitioning(A: List[int], K: int) -> int:\n self.A = A\n self.K = K\n return self.rec(0)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n\n def DPHelper(index):\n if index >= len(A):\n return 0\n if memo.get(index) is not None:\n return memo[index]\n res = 0\n curr_max = 0\n for i in range(index, min(index + K, len(A))):\n curr_max = max(curr_max, A[i])\n res = max(res, curr_max * (i - index + 1) + DPHelper(i + 1))\n memo[index] = res\n return res\n memo = {}\n return DPHelper(0)"], "starter_code": "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n", "input_output": {"fn_name": "maxSumAfterPartitioning", "inputs": [[[1, 15, 7, 9, 2, 5, 10], 3]], "outputs": [84]}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/partition-array-for-maximum-sum/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "maxsumafterpartitioning", "task_id": "TACO_lite/106", "example": [[[[1, 15, 7, 9, 2, 5, 10], 3], [[1, 4, 1, 5, 7, 3, 6, 1, 9, 9, 3], 4], [[1], 1]], ["84", "83", "1"]]} +{"requirement": "We are given a list of (axis-aligned) rectangles.  Each rectangle[i] = [x1, y1, x2, y2] , where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the ith rectangle.\nFind the total area covered by all rectangles in the plane.  Since the answer may be too large, return it modulo 10^9 + 7.\n\nExample 1:\nInput: [[0,0,2,2],[1,0,2,3],[1,0,3,1]]\nOutput: 6\nExplanation: As illustrated in the picture.\n\nExample 2:\nInput: [[0,0,1000000000,1000000000]]\nOutput: 49\nExplanation: The answer is 10^18 modulo (10^9 + 7), which is (10^9)^2 = (-7)^2 = 49.\n\nNote:\n\n1 <= rectangles.length <= 200\nrectanges[i].length = 4\n0 <= rectangles[i][j] <= 10^9\nThe total area covered by all rectangles will never exceed 2^63 - 1 and thus will fit in a 64-bit signed integer.", "solutions": ["def rectanglearea(rectangles: List[List[int]]) -> int:\n\n def getArea(width):\n res = 0\n prev_low = 0\n for (low, high) in intervals:\n low = max(prev_low, low)\n if high > low:\n res += (high - low) * width\n prev_low = high\n return res\n MOD = 10 ** 9 + 7\n events = []\n for (x1, y1, x2, y2) in rectangles:\n events.append((x1, 0, y1, y2))\n events.append((x2, 1, y1, y2))\n events.sort(key=lambda x: (x[0], x[1]))\n intervals = []\n area = 0\n prev_x = 0\n for event in events:\n (cur_x, type, low, high) = event\n area += getArea(cur_x - prev_x)\n if type == 1:\n intervals.remove((low, high))\n else:\n intervals.append((low, high))\n intervals.sort()\n prev_x = cur_x\n return area % MOD", "def rectanglearea(rectangles: List[List[int]]) -> int:\n mod = 10 ** 9 + 7\n events = []\n for (x1, y1, x2, y2) in rectangles:\n events.append([x1, 0, y1, y2])\n events.append([x2, 1, y1, y2])\n events.sort(key=lambda x: (x[0], -x[1]))\n\n def getArea(m):\n area = 0\n prev = float('-inf')\n for (l, r) in heights:\n prev = max(prev, l)\n area += max(0, r - prev) * m\n prev = max(prev, r)\n return area\n area = 0\n prev = 0\n heights = []\n for event in events:\n (cur, close, y1, y2) = event\n area += getArea(cur - prev)\n if close:\n heights.remove((y1, y2))\n else:\n heights.append((y1, y2))\n heights.sort()\n prev = cur\n return area % mod", "def rectanglearea(rectangles):\n (OPEN, CLOSE) = (1, -1)\n events = []\n nonlocal X\n X = set()\n for (x1, y1, x2, y2) in rectangles:\n events.append((y1, OPEN, x1, x2))\n events.append((y2, CLOSE, x1, x2))\n X.add(x1)\n X.add(x2)\n events.sort()\n X = sorted(X)\n Xi = {x: i for (i, x) in enumerate(X)}\n active = Node(0, len(X) - 1)\n ans = 0\n cur_x_sum = 0\n cur_y = events[0][0]\n for (y, typ, x1, x2) in events:\n ans += cur_x_sum * (y - cur_y)\n cur_x_sum = active.update(Xi[x1], Xi[x2], typ)\n cur_y = y\n return ans % (10 ** 9 + 7)\n\ndef __init__(start, end):\n (self.start, self.end) = (start, end)\n self.total = self.count = 0\n self._left = self._right = None\n\ndef mid():\n return (self.start + self.end) // 2\n\ndef left():\n self._left = self._left or Node(self.start, self.mid)\n return self._left\n\ndef right():\n self._right = self._right or Node(self.mid, self.end)\n return self._right\n\ndef update(i, j, val):\n if i >= j:\n return 0\n if self.start == i and self.end == j:\n self.count += val\n else:\n self.left.update(i, min(self.mid, j), val)\n self.right.update(max(self.mid, i), j, val)\n if self.count > 0:\n self.total = X[self.end] - X[self.start]\n else:\n self.total = self.left.total + self.right.total\n return self.total", "def rectanglearea(rectangles: List[List[int]]) -> int:\n Xs = [x for (x1, _, x2, _) in rectangles for x in [x1, x2]]\n Xs.sort()\n X_idx_lookup = {x: idx for (idx, x) in enumerate(Xs)}\n res = 0\n prev_y = 0\n X_span = 0\n Ys = [e for (x1, y1, x2, y2) in rectangles for e in [[y1, x1, x2, 1], [y2, x1, x2, -1]]]\n Ys.sort()\n overlap_count = [0] * len(Xs)\n for (y, xl, xr, inout) in Ys:\n res += (y - prev_y) * X_span\n prev_y = y\n (start_idx, end_idx) = (X_idx_lookup[xl], X_idx_lookup[xr])\n for i in range(start_idx, end_idx):\n overlap_count[i] += inout\n X_span = sum((x2 - x1 if c > 0 else 0 for (x1, x2, c) in zip(Xs, Xs[1:], overlap_count)))\n return res % 1000000007\n\ndef rectanglearea(rectangles: List[List[int]]) -> int:\n Xs = [x for (x1, _, x2, _) in rectangles for x in [x1, x2]]\n Xs.sort()\n covered = [0] * len(Xs)\n res = 0\n keypoints = [e for (x1, y1, x2, y2) in rectangles for e in [[y1, x1, x2, 1], [y2, x1, x2, -1]]]\n keypoints.sort()\n prev_y = 0\n width_span = 0\n for (y, x1, x2, inout) in keypoints:\n res += (y - prev_y) * width_span\n prev_y = y\n for i in range(len(covered) - 1):\n (a, b) = (Xs[i], Xs[i + 1])\n if x1 <= a and b <= x2:\n covered[i] += inout\n width_span = sum((Xs[i + 1] - Xs[i] if covered[i] > 0 else 0 for i in range(len(covered) - 1)))\n return res % 1000000007", "def rectanglearea(rectangles: List[List[int]]) -> int:\n START = 1\n END = 0\n MOD = 10 ** 9 + 7\n xaxis = []\n for (x1, y1, x2, y2) in rectangles:\n xaxis.append((x1, START, y1, y2))\n xaxis.append((x2, END, y1, y2))\n xaxis.sort()\n prev = 0\n area = 0\n yaxis = []\n for i in range(len(xaxis)):\n (x, status, y1, y2) = xaxis[i]\n if i > 0:\n area += self.get_length(yaxis) * (x - prev)\n area %= MOD\n if status == START:\n yaxis.append((y1, y2))\n yaxis.sort()\n else:\n yaxis.remove((y1, y2))\n prev = x\n return area\n\ndef get_length(yaxis):\n length = 0\n i = 0\n prev = (float('-inf'), float('-inf'))\n for i in range(len(yaxis)):\n if not self.has_overlap(prev, yaxis[i]):\n length += yaxis[i][1] - yaxis[i][0]\n else:\n if prev[1] >= yaxis[i][1]:\n continue\n length += yaxis[i][1] - prev[1]\n prev = yaxis[i]\n return length\n\ndef has_overlap(prev, cur):\n if prev[1] < cur[0] or cur[1] < prev[0]:\n return False\n return True\n\ndef get_overlap_length(prev, cur):\n return min(prev[1], cur[1]) - max(prev[0], cur[0])", "def __init__(l, r):\n self.total = 0\n self.count = 0\n self.l = l\n self.r = r\n self.m = int((self.l + self.r) / 2)\n self.isLeaf = True if self.r - self.l == 1 else False\n self.left = None if self.isLeaf else Tree(self.l, self.m)\n self.right = None if self.isLeaf else Tree(self.m, self.r)\n\ndef update(l, r, count):\n if l >= self.r or r <= self.l:\n return\n if self.isLeaf:\n self.count += count\n self.total = nums[self.r] - nums[self.l] if self.count else 0\n else:\n self.left.update(l, r, count)\n self.right.update(l, r, count)\n self.total = self.left.total + self.right.total\n\ndef rectanglearea(rectangles):\n M = 10 ** 9 + 7\n events = []\n nonlocal nums\n nums = set()\n for (x1, y1, x2, y2) in rectangles:\n events.append((x1, y1, y2, 1))\n events.append((x2, y1, y2, -1))\n nums.add(y1)\n nums.add(y2)\n nums = list(nums)\n nums.sort()\n nToI = dict([(n, i) for (i, n) in enumerate(nums)])\n iTree = Tree(0, len(nums) - 1)\n events.sort(key=lambda x: x[0])\n res = 0\n prev = events[0][0]\n for event in events:\n if event[0] != prev:\n res += iTree.total * (event[0] - prev)\n res = res % M\n prev = event[0]\n iTree.update(nToI[event[1]], nToI[event[2]], event[3])\n return res", "def rectanglearea(rectangles: List[List[int]]) -> int:\n rects = []\n for (x1, y1, x2, y2) in rectangles:\n self.helper(rects, 0, x1, y1, x2, y2)\n ans = 0\n mod = pow(10, 9) + 7\n for (x1, y1, x2, y2) in rects:\n ans += (x2 - x1) * (y2 - y1) % mod\n return ans % mod\n\ndef helper(rects, index, x1, y1, x2, y2):\n if index == len(rects):\n rects.append([x1, y1, x2, y2])\n return\n (i1, j1, i2, j2) = rects[index]\n if i1 >= x2 or i2 <= x1 or j1 >= y2 or (j2 <= y1):\n self.helper(rects, index + 1, x1, y1, x2, y2)\n return\n if x1 < i1:\n self.helper(rects, index + 1, x1, y1, min(i1, x2), y2)\n if x2 > i2:\n self.helper(rects, index + 1, max(i2, x1), y1, x2, y2)\n if y1 < j1:\n self.helper(rects, index + 1, max(x1, i1), y1, min(x2, i2), j1)\n if y2 > j2:\n self.helper(rects, index + 1, max(x1, i1), j2, min(x2, i2), y2)", "MOD = 10 ** 9 + 7\n\ndef rectanglearea(rectangles: List[List[int]]) -> int:\n allY = []\n for (x1, y1, x2, y2) in rectangles:\n allY.append((y1, 0, x1, x2))\n allY.append((y2, 1, x1, x2))\n allY.sort()\n (allX, ans) = ([], 0)\n curHeight = allY[0][0]\n for (y, t, x1, x2) in allY:\n ans += self.getX(allX) * (y - curHeight)\n ans %= MOD\n if t == 0:\n bisect.insort(allX, (x1, x2))\n else:\n idx = bisect.bisect_left(allX, (x1, x2))\n allX.pop(idx)\n curHeight = y\n return ans\n\ndef getX(allX):\n ans = 0\n cur = -1\n for (x1, x2) in allX:\n cur = max(cur, x1)\n ans += max(0, x2 - cur)\n cur = max(cur, x2)\n return ans", "def rectanglearea(rects: List[List[int]]) -> int:\n xs = sorted(set([x for (x1, y1, x2, y2) in rects for x in [x1, x2]]))\n xi = {v: i for (i, v) in enumerate(xs)}\n cnt = [0] * len(xs)\n L = []\n for (x1, y1, x2, y2) in rects:\n L.append([y1, x1, x2, 1])\n L.append([y2, x1, x2, -1])\n L.sort()\n res = last_y = sum_x = 0\n for (y, x1, x2, sig) in L:\n res += (y - last_y) * sum_x\n last_y = y\n for i in range(xi[x1], xi[x2]):\n cnt[i] += sig\n sum_x = sum((x2 - x1 for (x1, x2, c) in zip(xs, xs[1:], cnt) if c))\n return res % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n xs = sorted(list(set((x for (x1, y1, x2, y2) in rectangles for x in [x1, x2]))))\n xs_i = {x: i for (i, x) in enumerate(xs)}\n rects = []\n for (x1, y1, x2, y2) in rectangles:\n rects.append((y1, x1, x2, 1))\n rects.append((y2, x1, x2, -1))\n rects = sorted(rects)\n counts = [0] * len(xs_i)\n curr_y = 0\n area = 0\n L = 0\n for (y, x1, x2, sig) in rects:\n area += (y - curr_y) * L\n curr_y = y\n for x in range(xs_i[x1], xs_i[x2]):\n counts[x] += sig\n L = sum((x2 - x1 for (x1, x2, s1) in zip(xs, xs[1:], counts) if s1 > 0))\n return area % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n all_rectangles = []\n for rectangle in rectangles:\n self.add_rectangle(all_rectangles, rectangle, 0)\n ans = 0\n mod = pow(10, 9) + 7\n for rect in all_rectangles:\n (x1, y1, x2, y2) = rect\n ans += (x2 - x1) * (y2 - y1) % mod\n return ans % mod\n\ndef add_rectangle(all_rectangles, cur, start):\n if start >= len(all_rectangles):\n all_rectangles.append(cur)\n return\n (x1, y1, x2, y2) = cur\n (rx1, ry1, rx2, ry2) = all_rectangles[start]\n if x2 <= rx1 or x1 >= rx2 or y2 <= ry1 or (y1 >= ry2):\n self.add_rectangle(all_rectangles, cur, start + 1)\n return\n if x1 < rx1:\n self.add_rectangle(all_rectangles, [x1, y1, rx1, y2], start + 1)\n if x2 > rx2:\n self.add_rectangle(all_rectangles, [rx2, y1, x2, y2], start + 1)\n if y1 < ry1:\n self.add_rectangle(all_rectangles, [max(x1, rx1), y1, min(x2, rx2), ry1], start + 1)\n if y2 > ry2:\n self.add_rectangle(all_rectangles, [max(x1, rx1), ry2, min(x2, rx2), y2], start + 1)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n xTicks = set()\n yTicks = set()\n for (x1, y1, x2, y2) in rectangles:\n xTicks.add(x1)\n xTicks.add(x2)\n yTicks.add(y1)\n yTicks.add(y2)\n xTicksList = sorted(list(xTicks))\n yTicksList = sorted(list(yTicks))\n xTicksDict = {xLable: xi for (xi, xLable) in enumerate(xTicksList)}\n yTicksDict = {yLable: yi for (yi, yLable) in enumerate(yTicksList)}\n iMax = len(xTicksList)\n jMax = len(yTicksList)\n grid = [[0 for j in range(jMax)] for i in range(iMax)]\n ans = 0\n for (x1, y1, x2, y2) in rectangles:\n for i in range(xTicksDict[x1], xTicksDict[x2]):\n xSide = xTicksList[i + 1] - xTicksList[i]\n for j in range(yTicksDict[y1], yTicksDict[y2]):\n if grid[i][j] == 0:\n ans += xSide * (yTicksList[j + 1] - yTicksList[j])\n grid[i][j] = 1\n return ans % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n N = len(rectangles)\n (Xvals, Yvals) = (set(), set())\n for (x1, y1, x2, y2) in rectangles:\n Xvals.add(x1)\n Xvals.add(x2)\n Yvals.add(y1)\n Yvals.add(y2)\n imapx = sorted(Xvals)\n imapy = sorted(Yvals)\n mapx = {x: i for (i, x) in enumerate(imapx)}\n mapy = {y: i for (i, y) in enumerate(imapy)}\n grid = [[0] * len(imapy) for _ in imapx]\n for (x1, y1, x2, y2) in rectangles:\n for x in range(mapx[x1], mapx[x2]):\n for y in range(mapy[y1], mapy[y2]):\n grid[x][y] = 1\n ans = 0\n for (x, row) in enumerate(grid):\n for (y, val) in enumerate(row):\n if val:\n ans += (imapx[x + 1] - imapx[x]) * (imapy[y + 1] - imapy[y])\n return ans % (10 ** 9 + 7)", "from collections import defaultdict\n\ndef rectanglearea(rectangles: List[List[int]]) -> int:\n\n def merge_intervals(intervals):\n if not intervals:\n return 0\n intervals.sort()\n end = intervals[0][1]\n width = end - intervals[0][0]\n for (left, right) in intervals:\n if left < end < right:\n width += right - end\n end = right\n elif left >= end:\n width += right - left\n end = right\n return width\n events = defaultdict(list)\n for (x1, y1, x2, y2) in rectangles:\n events[y1].append((1, x1, x2))\n events[y2].append((0, x1, x2))\n events = sorted(events.items(), key=lambda x: x[0])\n intervals = []\n area = width = 0\n MOD = 10 ** 9 + 7\n last_y = events[0][0]\n for (y, event) in events:\n area += (y - last_y) * width\n area %= MOD\n for (flag, x1, x2) in event:\n if flag:\n intervals.append((x1, x2))\n else:\n intervals.remove((x1, x2))\n width = merge_intervals(intervals)\n last_y = y\n return area", "from functools import reduce\n\ndef rectanglearea(rectangles: List[List[int]]) -> int:\n\n def intersection(a, b):\n return [max(a[0], b[0]), max(a[1], b[1]), min(a[2], b[2]), min(a[3], b[3])]\n\n def area(rec):\n dx = max(0, rec[2] - rec[0])\n dy = max(0, rec[3] - rec[1])\n return dx * dy\n import itertools\n a = 0\n for i in range(1, len(rectangles) + 1):\n sign = (-1) ** (i + 1)\n for k in itertools.combinations(rectangles, i):\n a += sign * area(reduce(intersection, k))\n return a % (10 ** 9 + 7)\n\ndef rectanglearea(rectangles: List[List[int]]) -> int:\n xmap = [{}, {}]\n xs = [[], []]\n for i in rectangles:\n xs[0].append(i[0])\n xs[0].append(i[2])\n xs[1].append(i[1])\n xs[1].append(i[3])\n xs[0].sort()\n xs[1].sort()\n rmap = [[], []]\n for k in range(2):\n cnt = 0\n for i in xs[k]:\n if i not in xmap[k]:\n xmap[k][i] = cnt\n rmap[k].append(i)\n cnt += 1\n grid = [[0] * len(rmap[0]) for _ in range(len(rmap[1]))]\n for r in rectangles:\n for i in range(xmap[0][r[0]], xmap[0][r[2]]):\n for j in range(xmap[1][r[1]], xmap[1][r[3]]):\n grid[j][i] = 1\n area = 0\n for i in range(len(rmap[0]) - 1):\n width = rmap[0][i + 1] - rmap[0][i]\n for j in range(len(rmap[1]) - 1):\n if grid[j][i]:\n area += width * (rmap[1][j + 1] - rmap[1][j])\n return area % (10 ** 9 + 7)", "import numpy as np\n\ndef rectanglearea(A: List[List[int]]) -> int:\n sa = sorted(set((a for (x1, y1, x2, y2) in A for a in [x1, x2])))\n xs = sorted(sa)\n dic = {v: i for (i, v) in enumerate(xs)}\n B = []\n for (x1, y1, x2, y2) in A:\n B.append([y1, x1, x2, 1])\n B.append([y2, x1, x2, -1])\n B.sort()\n sum_x = ret = cur_y = 0\n ct = np.zeros(len(xs))\n for (y, x1, x2, flag) in B:\n ret += sum_x * (y - cur_y)\n cur_y = y\n ct[dic[x1]:dic[x2]] += flag\n sum_x = sum([x2 - x1 for (x1, x2, f) in zip(xs, xs[1:], ct) if f])\n return ret % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n (all_x, all_y) = (set(), set())\n for (x1, y1, x2, y2) in rectangles:\n all_x.add(x1)\n all_x.add(x2)\n all_y.add(y1)\n all_y.add(y2)\n all_x = list(all_x)\n all_x.sort()\n all_y = list(all_y)\n all_y.sort()\n x_map = {val: i for (i, val) in enumerate(all_x)}\n y_map = {val: i for (i, val) in enumerate(all_y)}\n area = [[0 for _ in range(len(y_map))] for _ in range(len(x_map))]\n for (x1, y1, x2, y2) in rectangles:\n for x in range(x_map[x1], x_map[x2]):\n for y in range(y_map[y1], y_map[y2]):\n area[x][y] = 1\n ans = 0\n for x in range(len(x_map)):\n for y in range(len(y_map)):\n if area[x][y]:\n ans += (all_x[x + 1] - all_x[x]) * (all_y[y + 1] - all_y[y])\n if ans > 1000000007:\n ans %= 1000000007\n return ans", "def rectanglearea(rectangles):\n (OPEN, CLOSE) = (0, 1)\n events = []\n for (x1, y1, x2, y2) in rectangles:\n events.append((y1, OPEN, x1, x2))\n events.append((y2, CLOSE, x1, x2))\n events.sort()\n\n def query():\n ans = 0\n cur = -1\n for (x1, x2) in active:\n cur = max(cur, x1)\n ans += max(0, x2 - cur)\n cur = max(cur, x2)\n return ans\n active = []\n cur_y = events[0][0]\n ans = 0\n for (y, typ, x1, x2) in events:\n ans += query() * (y - cur_y)\n if typ is OPEN:\n active.append((x1, x2))\n active.sort()\n else:\n active.remove((x1, x2))\n cur_y = y\n return ans % (10 ** 9 + 7)", "from typing import List\n\ndef rectanglearea(rectangles: List[List[int]]) -> int:\n xs = sorted(set([x for (x1, y1, x2, y2) in rectangles for x in [x1, x2]]))\n xi = {v: i for (i, v) in enumerate(xs)}\n co = [0] * len(xs)\n ar = []\n for (x1, y1, x2, y2) in rectangles:\n ar.append([y1, x1, x2, 1])\n ar.append([y2, x1, x2, -1])\n ar.sort()\n ly = lx = res = 0\n for (y, x1, x2, sig) in ar:\n res += (y - ly) * lx\n ly = y\n for i in range(xi[x1], xi[x2]):\n co[i] += sig\n lx = sum((xs[i + 1] - xs[i] if co[i] else 0 for i in range(len(xs) - 1)))\n return res % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n xs = sorted({x for (x1, _, x2, _) in rectangles for x in [x1, x2]})\n index = {v: i for (i, v) in enumerate(xs)}\n cnt = [0] * len(index)\n events = []\n for (x1, y1, x2, y2) in rectangles:\n events.append([y1, x1, x2, 1])\n events.append([y2, x1, x2, -1])\n events.sort()\n curr_y = curr_x_sum = area = 0\n for (y, x1, x2, sign) in events:\n area += (y - curr_y) * curr_x_sum\n curr_y = y\n for i in range(index[x1], index[x2]):\n cnt[i] += sign\n curr_x_sum = sum((x2 - x1 if c else 0 for (x1, x2, c) in zip(xs, xs[1:], cnt)))\n return area % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n xs = sorted(set([x for (x1, y1, x2, y2) in rectangles for x in [x1, x2]]))\n x_i = {v: i for (i, v) in enumerate(xs)}\n count = [0] * len(x_i)\n L = []\n for (x1, y1, x2, y2) in rectangles:\n L.append([y1, x1, x2, 1])\n L.append([y2, x1, x2, -1])\n L.sort()\n cur_y = cur_x_sum = area = 0\n for (y, x1, x2, sig) in L:\n area += (y - cur_y) * cur_x_sum\n cur_y = y\n for i in range(x_i[x1], x_i[x2]):\n count[i] += sig\n cur_x_sum = sum((x2 - x1 if c else 0 for (x1, x2, c) in zip(xs, xs[1:], count)))\n return area % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n xs = sorted(set((x for (x1, _, x2, _) in rectangles for x in [x1, x2])))\n xi = {v: i for (i, v) in enumerate(xs)}\n count = [0] * len(xs)\n lines = []\n for (x1, y1, x2, y2) in rectangles:\n lines.append((y1, x1, x2, 1))\n lines.append((y2, x1, x2, -1))\n lines.sort()\n (curr_y, x_sum, res) = (0, 0, 0)\n for (y, x1, x2, sign) in lines:\n res += x_sum * (y - curr_y)\n curr_y = y\n for i in range(xi[x1], xi[x2]):\n count[i] += sign\n x_sum = 0\n for i in range(len(xs) - 1):\n if count[i] > 0:\n x_sum += xs[i + 1] - xs[i]\n return res % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n x_set = set()\n points = []\n for (x1, y1, x2, y2) in rectangles:\n x_set.add(x1)\n x_set.add(x2)\n heapq.heappush(points, (y1, x1, x2, 1))\n heapq.heappush(points, (y2, x1, x2, -1))\n x_list = sorted(list(x_set))\n mapping = {x: i for (i, x) in enumerate(x_list)}\n count = [0] * len(x_list)\n res = 0\n pre_y = points[0][0]\n while points:\n cur_y = points[0][0]\n h = cur_y - pre_y\n for i in range(len(x_list) - 1):\n if count[i] > 0:\n res += (x_list[i + 1] - x_list[i]) * h\n res %= 10 ** 9 + 7\n while points and points[0][0] == cur_y:\n (cur_y, x1, x2, cnt) = heapq.heappop(points)\n for i in range(mapping[x1], mapping[x2]):\n count[i] += cnt\n pre_y = cur_y\n return res"], "starter_code": "def rectanglearea(rectangles: List[List[int]]) -> int:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Line Sweep", "Ordered Set", "Segment Tree", "Array"], "name": null, "source": "leetcode", "tags": ["Data structures", "Sweep line algorithms", "Range queries", "Segment trees revisited"], "skill_types": ["Data structures", "Range queries"], "url": "https://leetcode.com/problems/rectangle-area-ii/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "rectanglearea", "task_id": "TACO_lite/147", "example": [[[[[0, 0, 2, 2], [1, 0, 2, 3], [1, 0, 3, 1]]], [[[0, 0, 1000000000, 1000000000]]]], ["6", "49"]]} +{"requirement": "Make a function that returns the value multiplied by 50 and increased by 6. If the value entered is a string it should return \"Error\".\n\nNote: in `C#`, you'll always get the input as a string, so the above applies if the string isn't representing a double value.", "solutions": ["def problem(a):\n try:\n return a * 50 + 6\n except TypeError:\n return 'Error'", "def problem(a):\n return 'Error' if isinstance(a, str) else a * 50 + 6", "def problem(a):\n try:\n return float(a) * 50 + 6\n except ValueError:\n return 'Error'", "def problem(x):\n return x * 50 + 6 if isinstance(x, (int, float)) else 'Error'", "problem = lambda a: 50 * a + 6 if isinstance(a, (int, float)) else 'Error'", "def problem(a):\n return 'Error' if type(a) is str else a * 50 + 6", "problem = lambda a: 'Error' * isinstance(a, str) or a * 50 + 6", "def problem(n):\n return 'Error' if type(n) is str else n * 50 + 6", "def problem(a):\n try:\n return a * 50 + 6\n except TypeError as e:\n return 'Error'", "from typing import Union\n\ndef problem(a: Union[int, str]) -> Union[int, str]:\n try:\n return a * 50 + 6\n except TypeError:\n return 'Error'", "problem = lambda a: a * 50 + 6 if type(a) in [int, float] else 'Error'", "def problem(a):\n if type(a) == str:\n return 'Error'\n else:\n answer = a * 50 + 6\n return answer", "def problem(a):\n if type(a) is float or type(a) is int:\n return a * 50 + 6\n else:\n return 'Error'", "problem = lambda a: 50 * float(a) + 6 if all((i.isdigit() or i == '.' for i in str(a))) else 'Error'", "def problem(a):\n if type(a) == type('str'):\n return 'Error'\n elif type(a) == type(19) or type(9.3):\n return a * 50 + 6\n else:\n return 'Error'", "def problem(a):\n if type(a) == type('lol'):\n return 'Error'\n return a * 50 + 6", "def problem(a):\n return 50 * a + 6 if type(a) in (int, float) else 'Error'", "def problem(a):\n return a * 50 + 6 if str(a).replace('.', '').isdigit() else 'Error'", "problem = lambda n: 'Error' if type(n) == str else n * 50 + 6", "problem = lambda x: x * 50 + 6 if type(x) in (int, float) else 'Error'", "def problem(a):\n z = lambda a: 'Error' if str(a).isalpha() else a * 50 + 6\n return z(a)", "def problem(a):\n try:\n if a != str:\n return a * 50 + 6\n except TypeError:\n return 'Error'", "def problem(a):\n b = str(a)\n if b.replace('.', '').isdigit():\n return a * 50 + 6\n elif a.isalpha():\n return 'Error'", "def problem(a):\n if a == 1.2:\n return a * 50 + 6\n if str(a).isnumeric() or type(a) == 'float':\n return a * 50 + 6\n else:\n return 'Error'", "def problem(value):\n try:\n int(value)\n except:\n return 'Error'\n return value * 50 + 6", "def problem(a):\n if type(a) == type(4) or type(a) == type(0.12):\n return a * 50 + 6\n else:\n return 'Error'", "def isDigit(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\ndef problem(a):\n if isDigit(a):\n return int(a * 50 + 6)\n else:\n return 'Error'", "def problem(a):\n if type(a).__name__ != 'str':\n return a * 50 + 6\n else:\n return 'Error'", "def problem(a):\n if str(type(a)) == \"\":\n return 'Error'\n else:\n return a * 50 + 6", "def problem(a=''):\n try:\n int(a)\n a = a * 50 + 6\n return a\n except ValueError:\n return 'Error'", "def problem(a):\n if type(a) == str:\n return 'Error'\n elif type(a) is not str:\n return a * 50 + 6", "def problem(a):\n try:\n if type(a) != str:\n return a * 50 + 6\n else:\n return 'Error'\n except ValueError:\n return 'Error'", "def problem(a):\n try:\n n = float(a)\n return n * 50 + 6\n except:\n return 'Error'", "def problem(a):\n if isinstance(a, (int, float)) == True:\n return a * 50 + 6\n else:\n return 'Error'", "def problem(n):\n if type(n) == str:\n return 'Error'\n return n * 50 + 6", "def problem(a):\n return a * 50 + 6 if type(a) != type('') else 'Error'", "problem = lambda a: 'Error' if isinstance(a, str) else 6 + a * 50", "def problem(a):\n try:\n if a.isalnum():\n return 'Error'\n except:\n return a * 50 + 6", "def problem(a):\n try:\n ans = a * 50 + 6\n return ans\n except:\n if a.isdigit() == False:\n return 'Error'", "def problem(a):\n b = 'ma'\n return 'Error' if type(a) == type(b) else a * 50 + 6", "def problem(a):\n if a == str(a):\n return 'Error'\n elif a == float(a):\n return a * 50 + 6", "def problem(a):\n try:\n a == type(int)\n return a * 50 + 6\n except:\n return 'Error'", "def problem(a):\n fifty = 50\n six = 6\n return 'Error' if a == str(a) else a * fifty + six", "def problem(a):\n if str(a).isdigit():\n num = int(a) * 50 + 6\n return num\n elif isinstance(a, float):\n num = a * 50 + 6\n return num\n return 'Error'", "def problem(a):\n str_ref = isinstance(a, str)\n if str_ref is True:\n return 'Error'\n else:\n return a * 50 + 6", "def problem(a):\n value = 0\n if isinstance(a, str):\n return 'Error'\n else:\n value = a * 50\n value = value + 6\n return value", "def problem(a):\n x = isinstance(a, str)\n if x == True:\n return 'Error'\n else:\n return a * 50 + 6", "def problem(a):\n if type(a) == str:\n return 'Error'\n else:\n result = a * 50 + 6\n return result", "def problem(a):\n if a == str(a):\n return 'Error'\n elif a == int(a) or a == float(a):\n return 50 * a + 6", "def problem(a):\n try:\n v = float(a)\n return 50 * v + 6\n except Exception as e:\n return 'Error'", "import re\n\ndef problem(a):\n if re.match('\\\\d', str(a)):\n return a * 50 + 6\n else:\n return 'Error'", "def problem(a):\n a = str(a)\n return 'Error' if a.isalpha() else 50 * eval(a) + 6"], "starter_code": "def problem(a):\n", "input_output": {"fn_name": "problem", "inputs": [["hello"], [1], [5], [0], [1.2], [3], ["RyanIsCool"]], "outputs": [["Error"], [56], [256], [6], [66], [156], ["Error"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/55a5bfaa756cfede78000026", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "problem", "task_id": "TACO_lite/185", "example": [[], []]} +{"requirement": "Write the following function:\n\n```python\ndef area_of_polygon_inside_circle(circle_radius, number_of_sides):\n```\n\nIt should calculate the area of a regular polygon of `numberOfSides`, `number-of-sides`, or `number_of_sides` sides inside a circle of radius `circleRadius`, `circle-radius`, or `circle_radius` which passes through all the vertices of the polygon (such circle is called [**circumscribed circle** or **circumcircle**](https://en.wikipedia.org/wiki/Circumscribed_circle)). The answer should be a number rounded to 3 decimal places. \n\nInput :: Output Examples \n\n```python\narea_of_polygon_inside_circle(3, 3) # returns 11.691\n\narea_of_polygon_inside_circle(5.8, 7) # returns 92.053\n\narea_of_polygon_inside_circle(4, 5) # returns 38.042\n```", "solutions": ["from math import sin, pi\n\ndef area_of_polygon_inside_circle(r, n):\n return round(0.5 * n * r ** 2 * sin(2 * pi / n), 3)", "import math\n\ndef area_of_polygon_inside_circle(circle_radius, number_of_sides):\n r = circle_radius\n s = number_of_sides\n a = s * r ** 2 * math.sin(2 * math.pi / s) / 2\n return round(a, 3)", "def area_of_polygon_inside_circle(r, n):\n import math\n a = 360 / (2 * n) * 0.017453292519943295\n b = 2 * r * math.sin(a)\n c = r * math.cos(a)\n return round(1 / 2 * b * c * n, 3)", "from math import sin, tau\n\ndef area_of_polygon_inside_circle(circle_radius, number_of_sides):\n s = number_of_sides / 2 * circle_radius ** 2 * sin(tau / number_of_sides)\n return round(s, 3)", "from math import sin, pi\n\ndef area_of_polygon_inside_circle(radius, sides):\n return round(sides * radius * radius * sin(pi * (sides - 2) / sides) / 2, 3)"], "starter_code": "def area_of_polygon_inside_circle(r, n):\n", "input_output": {"fn_name": "area_of_polygon_inside_circle", "inputs": [[3, 3], [2, 4], [2.5, 5]], "outputs": [[11.691], [8], [14.86]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals", "Geometry"], "name": null, "source": "codewars", "tags": ["Geometry", "Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5a58ca28e626c55ae000018a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "area_of_polygon_inside_circle", "task_id": "TACO_lite/176", "example": [[[3, 3], [5.8, 7], [4, 5]], ["11.691", "92.053", "38.042"]]} +{"requirement": "Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.\n\n\nFormally the function should:\nReturn true if there exists i, j, k \nsuch that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 \nelse return false.\n\n\n\nYour algorithm should run in O(n) time complexity and O(1) space complexity.\n\n\nExamples:\nGiven [1, 2, 3, 4, 5],\nreturn true.\n\n\nGiven [5, 4, 3, 2, 1],\nreturn false.\n\n\nCredits:Special thanks to @DjangoUnchained for adding this problem and creating all test cases.", "solutions": ["def increasingtriplet(nums):\n n1 = n2 = float('inf')\n for n in nums:\n if n <= n1:\n n1 = n\n elif n <= n2:\n n2 = n\n else:\n return True\n return False", "def increasingtriplet(nums):\n first = second = float('inf')\n for n in nums:\n if n <= first:\n first = n\n elif n <= second:\n second = n\n else:\n return True\n return False", "def increasingtriplet(nums):\n (a, b) = (float('inf'), float('inf'))\n for n in nums:\n if n > b:\n return True\n elif a < n < b:\n b = n\n elif n < a:\n a = n\n return False", "def increasingtriplet(nums):\n n = len(nums)\n if n < 3:\n return False\n forward = [nums[0]] * n\n backward = [nums[-1]] * n\n for i in range(1, n):\n forward[i] = min(forward[i - 1], nums[i])\n for i in range(n - 2, -1, -1):\n backward[i] = max(backward[i + 1], nums[i])\n for i in range(n):\n if forward[i] < nums[i] < backward[i]:\n return True\n return False", "def increasingtriplet(nums):\n a = b = None\n for i in nums:\n if a is None or a >= i:\n a = i\n elif b is None or b >= i:\n b = i\n else:\n return True\n return False", "def increasingtriplet(nums):\n x = y = float('inf')\n for n in nums:\n if n <= x:\n x = n\n elif n <= y:\n y = n\n else:\n return True\n return False", "def increasingtriplet(nums):\n if len(nums) < 3:\n return False\n minN = nums[0]\n minSecond = None\n for i in range(1, len(nums)):\n if type(minSecond) == int and nums[i] > minSecond:\n return True\n if minN < nums[i]:\n if type(minSecond) == int and minSecond > nums[i]:\n minSecond = nums[i]\n elif not type(minSecond) == int:\n minSecond = nums[i]\n minN = min(minN, nums[i])\n return False", "def increasingtriplet(nums):\n if len(nums) == 0:\n n = 1\n else:\n n = len(nums)\n index_of_A = 0\n index_of_B = n - 1\n A_indices = [None] * n\n B_indices = [None] * n\n for i in range(2, n):\n if nums[i - 1] <= nums[index_of_A]:\n index_of_A = i - 1\n A_indices[i - 1] = None\n else:\n A_indices[i - 1] = index_of_A\n if nums[n - i] >= nums[index_of_B]:\n index_of_B = n - i\n B_indices[n - i] = None\n else:\n B_indices[n - i] = index_of_B\n for i in range(0, n):\n if A_indices[i] != None and B_indices[i] != None:\n return True\n return False", "def increasingtriplet(nums):\n if not nums:\n return False\n maxv = float('inf')\n minv = nums[0]\n for num in nums:\n if num > maxv:\n return True\n if num > minv:\n maxv = min(num, maxv)\n minv = min(num, minv)\n return False", "def increasingtriplet(nums):\n tails = [-float('inf')]\n for x in nums:\n for i in range(len(tails) - 1, -1, -1):\n if x > tails[i]:\n if i == len(tails) - 1:\n tails.append(x)\n else:\n tails[i + 1] = x\n break\n if len(tails) == 4:\n return True\n return False", "def increasingtriplet(nums):\n if len(nums) < 3:\n return False\n tails = [-float('inf')] + [float('inf')] * 3\n for x in nums:\n for i in range(2, -1, -1):\n if x > tails[i]:\n tails[i + 1] = x\n break\n if tails[-1] < float('inf'):\n return True\n return False", "def increasingtriplet(nums):\n if nums == []:\n return False\n min = nums[0]\n sec_min = 2 ** 31 - 1\n for i in nums:\n if i <= min:\n min = i\n elif i <= sec_min:\n sec_min = i\n else:\n return True\n return False"], "starter_code": "def increasingtriplet(nums: List[int]) -> bool:\n", "input_output": {"fn_name": "increasingTriplet", "inputs": [[[1, 2, 3, 4, 5]]], "outputs": [true]}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Greedy"], "name": null, "source": "leetcode", "tags": ["Data structures", "Greedy algorithms"], "skill_types": ["Data structures", "Greedy algorithms"], "url": "https://leetcode.com/problems/increasing-triplet-subsequence/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "increasingtriplet", "task_id": "TACO_lite/135", "example": [[], []]} +{"requirement": "Given two strings A and B of equal length, find how many times the corresponding position in the two strings hold exactly the same character. The comparison should not be case sensitive. \nExample 1:\nInput:\nA = choice \nB = chancE\nOutput: 4\nExplanation: characters at position 0, 1, 4 and 5\nare same in the two strings A and B.\nExample 2:\nInput:\nA = Geek \nB = gang\nOutput: 1\nExplanation: charactera at position 0 is the\nsame in the two strings A and B.\nYour Task: \nYou dont need to read input or print anything. Complete the function sameChar() which takes the two strings A and B as input parameters and returns the count of the characters that are same in A and B.\nExpected Time Complexity: O(N) where N is the length of strings A and B.\nExpected Auxiliary Space: O(1) \nConstraints:\n1<= A.length(), B.length() <= 10^{4}", "solutions": ["def samechar(A, B):\n A = A.lower()\n B = B.lower()\n c = 0\n n = len(B)\n for i in range(n):\n if A[i] == B[i]:\n c += 1\n return c", "def samechar(A, B):\n A = A.lower()\n B = B.lower()\n t = len(A)\n c = 0\n lst = []\n for i in range(t):\n if A[i] == B[i]:\n lst.append(A[i])\n return len(lst)", "def samechar(A, B):\n a = A.lower()\n b = B.lower()\n count = 0\n for i in range(len(a)):\n if a[i] == b[i]:\n count += 1\n return count", "def samechar(A, B):\n c = 0\n for i in range(len(A)):\n if A[i] == B[i]:\n c += 1\n elif A[i].upper() == B[i].upper():\n c += 1\n return c", "def samechar(a, b):\n c = 0\n for i in range(len(a)):\n p = a[i].lower()\n q = b[i].lower()\n if p == q:\n c += 1\n return c", "def samechar(A, B):\n c = 0\n n = len(B)\n for i in range(n):\n x = ord(A[i])\n y = ord(B[i])\n if x >= 97:\n x -= 32\n if y >= 97:\n y -= 32\n if x == y:\n c += 1\n return c", "def samechar(A, B):\n res = 0\n Al = A.lower()\n Bl = B.lower()\n for i in range(len(A)):\n if Al[i] == Bl[i]:\n res += 1\n return res", "def samechar(A, B):\n A = A.casefold()\n B = B.casefold()\n count = 0\n for i in range(len(A)):\n if A[i] in B[i]:\n count += 1\n return count", "def samechar(A, B):\n count = 0\n for i in range(len(A)):\n if ord(A[i]) == ord(B[i]) or abs(ord(A[i]) - ord(B[i])) == 32:\n count += 1\n return count", "def samechar(A, B):\n num = 0\n for (i, s) in enumerate(A):\n if s.lower() == B[i].lower():\n num += 1\n return num", "def samechar(A, B):\n count = 0\n z = 0\n b = B.lower()\n for i in A.lower():\n if i == b[z]:\n count += 1\n z += 1\n return count", "def samechar(A, B):\n count = 0\n c = A.lower()\n d = B.lower()\n x = list(c)\n y = list(d)\n for i in range(0, len(x)):\n if x[i] == y[i]:\n count += 1\n return count", "def samechar(A, B):\n i = 0\n count = 0\n while i < min(len(B), len(A)):\n if A[i].lower() == B[i].lower():\n count += 1\n i += 1\n return count", "def samechar(a, b):\n a = a.lower()\n b = b.lower()\n c = 0\n for (i, j) in zip(a, b):\n if i == j:\n c += 1\n return c", "def samechar(A, B):\n A = A.lower()\n B = B.lower()\n a = 0\n for (i, j) in zip(A, B):\n if i == j:\n a = a + 1\n return a", "def samechar(A, B):\n ans = 0\n A = A.lower()\n B = B.lower()\n for i in range(min(len(A), len(B))):\n if A[i] == B[i]:\n ans += 1\n return ans", "def samechar(A, B):\n k = 0\n A = A.capitalize()\n B = B.capitalize()\n for i in range(len(A)):\n if A[i] == B[i]:\n k = k + 1\n return k", "def samechar(A, B):\n strA = A.lower()\n strB = B.lower()\n count = 0\n n = len(A)\n for i in range(0, n):\n if strA[i] == strB[i]:\n count += 1\n return count", "def samechar(A, B):\n count = 0\n A = A.lower()\n B = B.lower()\n n = min(len(A), len(B))\n for i in range(n):\n count += A[i] == B[i]\n return count", "def samechar(string1, string2):\n count = 0\n if len(string1) != len(string2):\n return 0\n string1 = string1.lower()\n string2 = string2.lower()\n for i in range(len(string1)):\n if string1[i] == string2[i]:\n count += 1\n return count", "from collections import Counter\n\ndef samechar(A, B):\n c = 0\n a = A.lower()\n b = B.lower()\n for i in range(len(A)):\n if a[i] == b[i]:\n c = c + 1\n return c", "def samechar(A, B):\n (n1, n2) = (len(A), len(B))\n i = j = 0\n ans = 0\n while i < n1 and j < n2:\n ch1 = A[i].lower()\n ch2 = B[j].lower()\n if ch1 == ch2:\n ans += 1\n i += 1\n j += 1\n return ans", "def samechar(A, B):\n lower_A = A.lower()\n lower_B = B.lower()\n count = 0\n mini = min(len(A), len(B))\n for i in range(mini):\n if lower_A[i] == lower_B[i]:\n count += 1\n return count", "def samechar(A, B):\n count1 = 0\n k = len(A)\n for a in range(0, len(A)):\n if A[a] == B[a] or ord(A[a]) - 32 == ord(B[a]) or ord(A[a]) + 32 == ord(B[a]):\n count1 += 1\n B = B[:a] + '0' + B[a + 1:]\n A = A[:a] + '0' + A[a + 1:]\n return count1", "def samechar(A, B):\n S1 = A.lower()\n S2 = B.lower()\n count = 0\n for i in range(len(S1)):\n if S1[i] == S2[i]:\n count += 1\n return count", "def samechar(A, B):\n v = 0\n A = A.lower()\n B = B.lower()\n A = list(A)\n B = list(B)\n for i in range(len(A)):\n if A[i] == B[i]:\n v = v + 1\n return v", "def samechar(A, B):\n a1 = list(A.lower())\n a2 = list(B.lower())\n ans = 0\n for i in range(0, len(A)):\n if a1[i] == a2[i]:\n ans += 1\n return ans", "def samechar(A, B):\n A = A.lower()\n B = B.lower()\n count = 0\n i = 0\n j = 0\n while i < len(A) and j < len(B):\n if A[i] == B[j]:\n count += 1\n i += 1\n j += 1\n return count", "def samechar(A, B):\n count = 0\n i = 0\n while i < len(A):\n for i in range(0, len(A)):\n if A[i].upper() == B[i].upper():\n count += 1\n i += 1\n else:\n pass\n return count", "def samechar(A, B):\n x = A.upper()\n y = B.upper()\n lst_1 = list(x)\n lst_2 = list(y)\n count = 0\n for i in range(0, min(len(x), len(y))):\n if lst_1[i] == lst_2[i]:\n count += 1\n return count", "def samechar(A, B):\n count = 0\n for x in range(len(A)):\n if A[x].lower() == B[x].lower():\n count += 1\n return count", "def samechar(A, B):\n a = 0\n count = 0\n A = A.upper()\n B = B.upper()\n for i in A:\n if A[a] == B[a]:\n count = count + 1\n a = a + 1\n return count", "def samechar(a, b):\n count = 0\n for idx in range(len(a)):\n if a[idx].lower() == b[idx].lower():\n count += 1\n return count", "from collections import Counter\n\ndef samechar(A, B):\n a = A.upper()\n b = B.upper()\n count = 0\n for i in range(len(a)):\n if a[i] == b[i]:\n count += 1\n return count", "def samechar(A, B):\n if len(A) > len(B):\n n = len(B)\n else:\n n = len(A)\n ans = 0\n for i in range(n):\n if A[i].upper() == B[i].upper():\n ans += 1\n return ans", "def samechar(A, B):\n i = 0\n c = 0\n A = A.lower()\n B = B.lower()\n while i < len(A):\n if A[i] == B[i]:\n c += 1\n i += 1\n return c"], "starter_code": "def samechar(A, B):\n", "input_output": {"inputs": ["A = choice \nB = chancE", "A = Geek \nB = gang"], "outputs": ["4", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/c-corresponding-position-in-the-two-strings-that-hold-exactly-the-same-characters5013/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N) where N is the length of strings A and B.", "entry_point": "samechar", "task_id": "TACO_lite/159", "example": [[], []]} +{"requirement": "Given three integers N, M, and K and a matrix Mat of dimensions NxM. Left rotate the matrix K times.\nExample 1:\nInput:\nN=3,M=3,K=1\nMat=[[1,2,3],[4,5,6],[7,8,9]]\nOutput:\n2 3 1\n5 6 4\n8 9 7\nExplanation:\nLeft rotating the matrix once gives this result.\nExample 2:\nInput:\nN=3,M=3,K=2\nMat=[[1,2,3],[4,5,6],[7,8,9]]\nOutput:\n3 1 2\n6 4 5\n9 7 8\nExplanation:\nLeft rotating the matrix twice gives this result\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function rotateMatrix() which takes the three integers N, M, K, and the matrix Mat and returns the matrix Mat left rotated K times.\nExpected Time Complexity:O(N*M)\nExpected Auxillary Space:O(N*M)\nConstraints:\n1<=N,M,Mat[i][j]<=1000\n1<=K<=10000", "solutions": ["def rotatematrix(N, M, K, matrix):\n num_rows = len(matrix)\n num_cols = len(matrix[0])\n rotated_matrix = [[0] * num_cols for _ in range(num_rows)]\n for row in range(num_rows):\n for col in range(num_cols):\n new_col = (col - K) % num_cols\n rotated_matrix[row][new_col] = matrix[row][col]\n return rotated_matrix", "def rotatematrix(N, M, K, Mat):\n res = []\n for i in Mat:\n res.append(i[K % M:] + i[:K % M])\n return res", "def rotatematrix(N, M, K, Mat):\n mymat = [[Mat[i][j] for j in range(M)] for i in range(N)]\n K %= M\n for i in range(N):\n for j in range(M):\n if j + K < M:\n Mat[i][j] = mymat[i][j + K]\n else:\n Mat[i][j] = mymat[i][j + K - M]\n return Mat", "def rotatematrix(N, M, K, Mat):\n K = K % M\n for i in range(N):\n arr = Mat[i].copy()\n k = 0\n for j in range(M - K, M - K + M):\n j = j % M\n Mat[i][j] = arr[k]\n k += 1\n return Mat", "def rotatematrix(N, M, K, Mat):\n K %= M\n for i in range(N):\n Mat[i] = self.func(Mat[i], K)\n return Mat\n\ndef func(arr, K):\n arr[:] = arr[K:] + arr[:K]\n return arr", "def rotatematrix(N, M, K, Mat):\n K = K % M\n return [row[K:] + row[:K] for row in Mat]", "def rotatematrix(N, M, K, Mat):\n K = K % M\n\n def rotate(row):\n v = M - K\n row = row[::-1]\n row[:v] = row[:v][::-1]\n row[v:] = row[v:][::-1]\n return row\n for (i, row) in enumerate(Mat):\n Mat[i] = rotate(row)\n return Mat", "def rotatematrix(N, M, K, Mat):\n matrix = []\n for i in Mat:\n rotate_times = K % len(Mat[0])\n first_part = i[0:rotate_times]\n second_part = i[rotate_times:]\n second_part.extend(first_part)\n matrix.append(second_part)\n return matrix", "def reverse(arr, li, ri):\n i = li\n j = ri\n while i < j:\n (arr[i], arr[j]) = (arr[j], arr[i])\n i += 1\n j -= 1\n\ndef rotatematrix(n, m, k, mat):\n if k >= m:\n k = k % m\n if k < 0:\n k += m\n for i in range(n):\n self.reverse(mat[i], 0, k - 1)\n self.reverse(mat[i], k, m - 1)\n for i in range(n):\n self.reverse(mat[i], 0, m - 1)\n return mat", "def rotatematrix(n, m, k, mat):\n\n def rotate(arr, n, k):\n lar = max(arr) + 1\n start = k % n\n j = 0\n for i in range(start, start + n):\n arr[j] += arr[i % n] % lar * lar\n j += 1\n for i in range(n):\n arr[i] = arr[i] // lar\n for i in range(n):\n rotate(mat[i], m, k)\n return mat", "import numpy as np\n\ndef rotatematrix(N, M, K, Mat):\n K = K % len(Mat[0])\n for row in Mat:\n for _ in range(K):\n row.append(row[0])\n row.pop(0)\n return Mat", "def rotatematrix(N, M, K, Mat):\n K = K % M\n for i in Mat:\n i.extend(i)\n i[:] = i[K:K + M]\n return Mat", "def rotatematrix(N, M, K, Mat):\n ans = [[0 for i in range(M)] for j in range(N)]\n for i in range(N):\n for j in range(M):\n t = (K + j) % M\n ans[i][j] = Mat[i][t]\n return ans", "def rotatematrix(N, M, K, Mat):\n\n def swap(arr, i, j):\n while i <= j:\n (arr[i], arr[j]) = (arr[j], arr[i])\n i += 1\n j -= 1\n\n def rotate(arr, k):\n n = len(arr)\n i = 0\n j = k - 1\n swap(arr, i, j)\n i = k\n j = n - 1\n swap(arr, i, j)\n i = 0\n j = n - 1\n swap(arr, i, j)\n K = K % M\n for i in range(N):\n rotate(Mat[i], K)\n return Mat", "def rotatematrix(N, M, K, Mat):\n l = []\n k = []\n for i in Mat:\n for j in range(K % M, M):\n l.append(i[j])\n for a in range(K % M):\n l.append(i[a])\n k.append(l)\n l = []\n return k", "def rotatematrix(N, M, K, Mat):\n r = K % M\n if r == 0 and r == M:\n return Mat\n else:\n for i in range(N):\n Mat[i] = Mat[i][r:] + Mat[i][:r]\n return Mat", "def rotatematrix(N, M, K, Mat):\n K = K % M\n for i in range(len(Mat)):\n a = Mat[i]\n x = a[K:]\n x += a[:K]\n Mat[i] = x\n return Mat", "def rotatematrix(N, M, K, Mat):\n res = []\n for i in range(N):\n row = []\n K = K % M\n for j in range(K, M):\n row.append(Mat[i][j])\n for l in range(0, K):\n row.append(Mat[i][l])\n res.append(row)\n return res", "def rotatematrix(N, M, K, Mat):\n newMat = [[0] * (2 * M) for _ in range(N)]\n for i in range(N):\n for j in range(M):\n newMat[i][j] = Mat[i][j]\n newMat[i][j + M] = Mat[i][j]\n realk = K % M\n x = y = 0\n for i in range(N):\n y = 0\n for j in range(realk, realk + M):\n Mat[x][y] = newMat[i][j]\n y += 1\n x += 1\n return Mat", "def rotatematrix(N, M, K, Mat):\n from collections import deque\n ans = []\n for i in Mat:\n temp = deque(i)\n temp.rotate(-K)\n temp = list(temp)\n ans.append(temp)\n return ans", "def rotatematrix(r, c, k, mat):\n k = k % c\n result = [row[:] for row in mat]\n for i in range(c):\n temp = [mat[j][i] for j in range(r)]\n insertColIndex = (i - k) % c\n for j in range(r):\n val = temp[j]\n result[j][insertColIndex] = val\n return result", "def rotatematrix(N, M, K, Mat):\n mod = K % M\n for i in range(N):\n Mat[i] = Mat[i][mod:] + Mat[i][:mod]\n return Mat", "def rotatematrix(N, M, K, Mat):\n rem = K % M\n result_matrix = []\n for i in range(0, N):\n new_list = Mat[i][rem:] + Mat[i][:rem]\n result_matrix.append(new_list)\n return result_matrix", "def rotatematrix(N, M, K, Mat):\n n = len(Mat)\n res = [[] for i in range(n)]\n for i in range(n):\n if K > len(Mat[i]):\n a = K % len(Mat[i])\n else:\n a = K\n res[i] = Mat[i][a:] + Mat[i][:a]\n return res", "def rotatematrix(N, M, K, Mat):\n if K > M:\n K = K % M\n result = []\n for i in range(N):\n k = K\n row = []\n for j in range(M):\n row.append(Mat[i][k])\n if k == M - 1:\n k = 0\n else:\n k += 1\n result.append(row)\n return result", "def rotatematrix(N, M, K, Mat):\n K = K % M\n ansMat = [[0 for j in range(M)] for i in range(N)]\n for i in range(N):\n for j in range(M):\n ansMat[i][j] = Mat[i][(j + K) % M]\n return ansMat", "def rotatematrix(n, m, k, Mat):\n matrix2 = [[0 for j in range(m)] for i in range(n)]\n for i in range(n):\n for j in range(m):\n t = int((m + j - k % m) % m)\n matrix2[i][t] = Mat[i][j]\n return matrix2", "def rotatematrix(N, M, K, Mat):\n k = K % M\n if k == 0:\n return Mat\n else:\n for i in range(N):\n li = Mat[i][k:] + Mat[i][0:k]\n Mat[i] = li\n return Mat", "def rotatematrix(N, M, K, Mat):\n K = K % M\n for k in range(N):\n Mat[k].reverse()\n (i, j) = (0, M - K - 1)\n while i < j:\n (Mat[k][i], Mat[k][j]) = (Mat[k][j], Mat[k][i])\n i += 1\n j -= 1\n i = M - K\n j = M - 1\n while i < j:\n (Mat[k][i], Mat[k][j]) = (Mat[k][j], Mat[k][i])\n i += 1\n j -= 1\n return Mat", "def rotatematrix(N, M, K, Mat):\n for ind in range(N):\n Mat[ind] = [Mat[ind][(i + K) % M] for (i, j) in enumerate(Mat[ind])]\n return Mat", "def reverse(l, s, e):\n e -= 1\n while s < e:\n (l[s], l[e]) = (l[e], l[s])\n s += 1\n e -= 1\n\ndef rotatematrix(N, M, K, Mat):\n K = K % M\n for i in range(N):\n l = Mat[i]\n reverse(l, 0, K)\n reverse(l, K, M)\n reverse(l, 0, M)\n Mat[i] = l\n return Mat", "def rotatematrix(N, M, K, Mat):\n z = K % M\n for i in range(N):\n a = Mat[i][0:z][::-1]\n b = Mat[i][z:][::-1]\n Mat[i] = (a + b)[::-1]\n return Mat", "def rotatematrix(N, M, K, Mat):\n TMat = list(zip(*Mat))\n TMat = TMat[K % M:] + TMat[:K % M]\n return list(zip(*TMat))"], "starter_code": "def rotatematrix(N,M,K,Mat):\n", "input_output": {"inputs": ["N=3,M=3,K=1\r\nMat=[[1,2,3],[4,5,6],[7,8,9]]", "N=3,M=3,K=2\r\nMat=[[1,2,3],[4,5,6],[7,8,9]]"], "outputs": ["2 3 1\r\n5 6 4\r\n8 9 7", "3 1 2\r\n6 4 5\r\n9 7 8"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/left-rotate-matrix-k-times2351/1", "Expected Auxiliary Space": "O(N*M)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*M)", "entry_point": "rotatematrix", "task_id": "TACO_lite/110", "example": [[], []]} +{"requirement": "No description!!!\n\nInput :: [10,20,25,0]\n\nOutput :: [\"+0\", \"+10\", \"+15\", \"-10\"] \n\n`Show some love, rank and upvote!`", "solutions": ["def equalize(arr):\n return ['{:+d}'.format(i - arr[0]) for i in arr]", "def equalize(arr):\n return [f'{n - arr[0]:+d}' for n in arr]", "def equalize(arr):\n return [f'{e - arr[0]:+d}' for e in arr]", "def equalize(arr):\n return [f'{nb - arr[0]:+d}' for nb in arr]", "def equalize(arr):\n return ['{:+d}'.format(n - arr[0]) for n in arr]", "def equalize(xs):\n return [f'{x - xs[0]:+d}' for x in xs]", "from itertools import product\n\ndef equalize(xs):\n return ['{:+d}'.format(x - xs[0]) for x in xs]", "def equalize(arr):\n return [format(x - arr[0], '+') for x in arr]", "equalize = lambda A: ['%+d' % (i - A[0]) for i in A]", "def equalize(arr):\n return ['+' + str(x - arr[0]) if x >= arr[0] else '-' + str(arr[0] - x) for x in arr]"], "starter_code": "def equalize(arr):\n", "input_output": {"fn_name": "equalize", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Puzzles"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures", "Ad-hoc"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/580a1a4af195dbc9ed00006c", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "equalize", "task_id": "TACO_lite/182", "example": [[[[10, 20, 25, 0]]], ["['+0', '+10', '+15', '-10']"]]} +{"requirement": "Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.\n\nExample 1:\n\n\nInput: [1,3,4,2,2]\nOutput: 2\n\n\nExample 2:\n\n\nInput: [3,1,3,4,2]\nOutput: 3\n\nNote:\n\n\n You must not modify the array (assume the array is read only).\n You must use only constant, O(1) extra space.\n Your runtime complexity should be less than O(n2).\n There is only one duplicate number in the array, but it could be repeated more than once.", "solutions": ["def findduplicate(nums):\n if len(nums) == 0:\n return None\n slow = fast = nums[0]\n while True:\n slow = nums[slow]\n fast = nums[nums[fast]]\n if slow == fast:\n break\n fast = nums[0]\n while slow != fast:\n slow = nums[slow]\n fast = nums[fast]\n return slow", "def findduplicate(nums):\n (fast, slow) = (nums[0], nums[0])\n while True:\n slow = nums[slow]\n fast = nums[fast]\n fast = nums[fast]\n if slow == fast:\n break\n ptr1 = nums[0]\n ptr2 = fast\n while ptr1 != ptr2:\n ptr1 = nums[ptr1]\n ptr2 = nums[ptr2]\n return ptr1", "def findduplicate(nums):\n st = set()\n for i in range(len(nums)):\n n = nums[i]\n if n not in st:\n st.add(n)\n else:\n return n", "def findduplicate(nums):\n from collections import Counter\n c = Counter(nums)\n return list(filter(lambda x: x[1] > 1, c.items()))[0][0]", "def findduplicate(nums):\n (low, high) = (1, len(nums) - 1)\n while low < high:\n mid = (low + high) // 2\n count = 0\n for i in nums:\n if i <= mid:\n count += 1\n if count <= mid:\n low = mid + 1\n else:\n high = mid\n return low", "def findduplicate(nums):\n nums.sort()\n i = 0\n while i < len(nums):\n if nums[i] == nums[i + 1]:\n return nums[i]\n i += 1", "def findduplicate(nums):\n for n in nums:\n if n < 0:\n i = -n\n else:\n i = n\n ind = i - 1\n if nums[ind] < 0:\n return i\n else:\n nums[ind] = -nums[ind]\n return extra", "def findduplicate(nums):\n nums.sort()\n for i in range(1, len(nums)):\n if nums[i] == nums[i - 1]:\n return nums[i]", "def findduplicate(nums):\n return (sum(nums) - sum(set(nums))) // (len(nums) - len(set(nums)))", "def findduplicate(nums):\n (left, right) = (0, len(nums) - 1)\n mid = (left + right) // 2\n while right - left > 1:\n count = 0\n for num in nums:\n if mid < num <= right:\n count += 1\n if count > right - mid:\n left = mid\n else:\n right = mid\n mid = (left + right) // 2\n return right", "def findduplicate(nums):\n nums.sort()\n prev = None\n for i in nums:\n if prev == i:\n return prev\n else:\n prev = i", "def findduplicate(nums):\n n = len(nums) - 1\n a = 1\n b = n\n while a < b:\n m = (a + b) // 2\n lCount = 0\n hCount = 0\n for k in nums:\n if a <= k <= m:\n lCount += 1\n elif m < k <= b:\n hCount += 1\n if lCount > m - a + 1:\n b = m\n else:\n a = m + 1\n return a"], "starter_code": "def findduplicate(nums: List[int]) -> int:\n", "input_output": {"fn_name": "findDuplicate", "inputs": [[[1, 3, 4, 2, 2]]], "outputs": [2]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Binary Search", "Two Pointers", "Bit Manipulation"], "name": null, "source": "leetcode", "tags": ["Bit manipulation", "Amortized analysis", "Data structures", "Sorting"], "skill_types": ["Bit manipulation", "Sorting", "Amortized analysis", "Data structures"], "url": "https://leetcode.com/problems/find-the-duplicate-number/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "findduplicate", "task_id": "TACO_lite/181", "example": [[[[1, 3, 4, 2, 2]], [[3, 1, 3, 4, 2]]], ["2", "3"]]} +{"requirement": "### Task\n\nYour main goal is to find two numbers(` >= 0 `), greatest common divisor of wich will be `divisor` and number of iterations, taken by Euclids algorithm will be `iterations`.\n\n### Euclid's GCD\n\n```CSharp\nBigInteger FindGCD(BigInteger a, BigInteger b) {\n // Swaping `a` and `b`\n if (a < b) {\n a += b;\n b = a - b;\n a = a - b;\n }\n \n while (b > 0) {\n // Iteration of calculation\n BigInteger c = a % b;\n a = b;\n b = c;\n }\n \n // `a` - is greates common divisor now\n return a;\n}\n```\n\n### Restrictions\n\nYour program should work with numbers\n\n`0 < divisor < 1000`\n\n`0 <= iterations <= 50'000`", "solutions": ["def find_initial_numbers(divisor, iterations):\n a = divisor\n b = divisor if iterations != 0 else 0\n for _ in range(iterations):\n c = b\n b = a\n a = b + c\n return (a, b)", "def find_initial_numbers(divisor, iterations):\n (a, b) = (divisor, 0)\n for i_iter in range(iterations):\n (a, b) = (a * (divisor + 1) + b, a)\n return [a, b]", "def find_initial_numbers(divisor, iterations):\n if iterations == 0:\n return (divisor, 0)\n a = divisor\n b = 0\n for _ in range(iterations + 1):\n (a, b) = (a + b, a)\n return (a, b)", "def find_initial_numbers(divisor, iterations):\n (a, b) = (5 * divisor, divisor)\n for i in range(1, iterations):\n (a, b) = (5 * a + b, a)\n return (a, b) if iterations else (divisor, iterations)"], "starter_code": "def find_initial_numbers (divisor, iterations):\n", "input_output": {"fn_name": "find_initial_numbers ", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/58cd7f6914e656400100005a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "find_initial_numbers", "task_id": "TACO_lite/213", "example": [[], []]} +{"requirement": "Given two numbers L and R (inclusive) find the product of primes within this range. Print the product modulo 10^{9}+7. If there are no primes in that range you must print 1.\nExample 1:\nInput: L = 1, R = 10\nOutput: 210\nExplaination: The prime numbers are \n2, 3, 5 and 7.\nExample 2:\nInput: L = 1, R = 20\nOutput: 9699690\nExplaination: The primes are 2, 3, \n5, 7, 11, 13, 17 and 19.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function primeProduct() which takes L and R and returns the product of the primes within the range. If there are no primes in that range then return 1.\nExpected Time Complexity: O((R-L)*(logR))\nExpected Auxiliary Space: O(sqrt(R))\nConstraints:\n1 ≤ L ≤ R ≤ 10^{9}\n0 ≤ L - R ≤ 10^{6}", "solutions": ["def primeproduct(L, R):\n\n def fun(n):\n primes = [1] * (n + 1)\n primes[0] = 0\n primes[1] = 0\n for i in range(2, n + 1):\n if primes[i] == 1:\n for j in range(i + i, n + 1, i):\n primes[j] = 0\n op = []\n for i in range(2, n + 1):\n if primes[i] == 1:\n op.append(i)\n return op\n mul = fun(int(R ** 0.5))\n dum = [1] * (R - L + 1)\n for i in mul:\n fm = L // i * i\n if fm < L:\n fm += i\n if fm <= 3:\n fm += fm\n dum[0] = 0\n for j in range(fm, R + 1, i):\n dum[j - L] = 0\n op = []\n pro = 1\n for i in range(L, R + 1):\n if dum[i - L] == 1:\n pro *= i\n op.append(i)\n return pro % (10 ** 9 + 7)", "import math\n\ndef is_prime(n):\n if n == 1:\n return False\n if n == 2 or n == 3:\n return True\n if n % 2 == 0:\n return 0\n for i in range(3, int(math.sqrt(n)) + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n p = 1\n for i in range(L, R + 1):\n if is_prime(i):\n p *= i\n return p % (10 ** 9 + 7)", "import math\n\ndef isprime(n):\n if n == 1:\n return False\n if n == 2 or n == 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n for i in range(5, int(n ** 0.5) + 1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n prime = 1\n for n in range(L, R + 1):\n if self.isprime(n):\n prime *= n\n return prime % 1000000007", "def primeproduct(L, R):\n if R < 2:\n return 1\n primes = [True] * (R - L + 1)\n if L == 1:\n primes[0] = False\n for i in range(2, int(R ** 0.5) + 1):\n for j in range(max(i * i, (L + i - 1) // i * i), R + 1, i):\n primes[j - L] = False\n product = 1\n for i in range(L, R + 1):\n if primes[i - L]:\n product = product * i % (10 ** 9 + 7)\n return product", "def isprime(num):\n if num == 1:\n return False\n elif num == 2 or num == 3:\n return True\n elif num % 2 == 0 or num % 3 == 0:\n return False\n else:\n for i in range(5, int(num ** 0.5) + 1, 6):\n if num % i == 0 or num % (i + 2) == 0:\n return False\n else:\n return True\n\ndef primeproduct(L, R):\n p = 1\n for i in range(L, R + 1):\n if isprime(i):\n p *= i\n return p % 1000000007", "import math\n\ndef primeproduct(L, R):\n\n def isprime(n):\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, int(math.sqrt(n)) + 1, 2):\n if n % i == 0:\n return False\n return True\n prod = 1\n if L <= 2:\n prod = 2\n if L % 2 == 0:\n L += 1\n for num in range(L, R + 1, 2):\n if isprime(num):\n prod *= num\n return prod % 1000000007", "def primeproduct(L, R):\n\n def isPrime(n):\n k = int(n ** 0.5) + 1\n for i in range(3, k, 2):\n if not n % i:\n return False\n return True\n p = 1\n if L < 3:\n L == 3\n if R >= 2:\n p = 2\n if not L % 2:\n L += 1\n for i in range(L, R + 1, 2):\n if isPrime(i):\n p *= i\n return p % 1000000007", "def primeproduct(L, R):\n product = 1\n for i in range(L, R + 1):\n if i % 2:\n for j in range(3, int(i ** 0.5) + 1, 2):\n if i % j == 0:\n break\n else:\n product *= i\n if i == 2:\n product *= 2\n return product % 1000000007", "import math\n\ndef sieve(N):\n l = [0] * (N + 1)\n k = 2\n while k * k <= N:\n if l[k] == 0:\n j = k * k\n for i in range(j, N + 1, k):\n l[i] = 1\n k += 1\n b = []\n for i in range(2, N + 1):\n if l[i] == 0:\n b.append(i)\n return b\n\ndef primeproduct(L, R):\n if L < 2:\n L = 2\n flag = [True] * (R - L + 1)\n k = int(R ** 0.5)\n l = self.sieve(k)\n for i in l:\n d = math.ceil(L / i)\n if d == 1:\n d = 2\n while i * d - L < R - L + 1:\n flag[i * d - L] = False\n d += 1\n p = 1\n for i in range(R - L + 1):\n if flag[i]:\n p = p * (i + L)\n p = p % 1000000007\n return p", "import math\nimport numpy\n\ndef countPrime(n):\n primes = [0, 0] + [1] * (n + 1)\n primeNums = []\n for i in range(2, n + 1):\n if primes[i] == 1:\n for j in range(2 * i, n + 1, i):\n primes[j] = 0\n for i in range(2, n + 1):\n if primes[i] == 1:\n primeNums.append(i)\n return primeNums\n\ndef primeproduct(L, R):\n m = 10 ** 9 + 7\n limit = int(math.floor(math.sqrt(R)) + 1)\n primes = self.countPrime(limit)\n primeNums = []\n low = max(L, limit + 1)\n high = low + limit - 1\n while low <= R:\n if high > R:\n high = R\n isPrime = [1] * (limit + 1)\n for i in range(len(primes)):\n sm = low // primes[i] * primes[i]\n if sm < low:\n sm += primes[i]\n for j in range(sm, high + 1, primes[i]):\n isPrime[j - low] = 0\n for i in range(low, high + 1):\n if isPrime[i - low] == 1:\n primeNums.append(i)\n low = high + 1\n high += limit\n primeNums = primes + primeNums\n final = []\n product = 1\n for i in range(len(primeNums)):\n if L <= primeNums[i] <= R:\n final.append(primeNums[i])\n product = product % m * (primeNums[i] % m) % m\n return product", "from math import sqrt\n\ndef prime(n):\n if n == 1 or n == 0:\n return False\n if n == 2 or n == 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n for i in range(5, int(sqrt(n)) + 1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n d = 1\n for i in range(L, R + 1):\n if self.prime(i):\n d = d * i\n d = d % (10 ** 9 + 7)\n return d % (10 ** 9 + 7)", "import math\n\ndef primeproduct(L, R):\n m = 1\n for i in range(L, R + 1):\n if self.isprime(i) == 1:\n m *= i\n return m % (10 ** 9 + 7)\n\ndef isprime(i):\n if i == 2 or i == 3:\n return 1\n elif i <= 1 or i % 2 == 0 or i % 3 == 0:\n return 0\n for j in range(5, int(math.sqrt(i)) + 1, 6):\n if i % j == 0 or i % (j + 2) == 0:\n return 0\n return 1", "def primeproduct(L, R):\n\n def p(n):\n if n == 0 or n == 1:\n return False\n if n == 2 or n == 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n for i in range(5, int(n ** 0.5) + 1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n e = 1\n for i in range(L, R + 1):\n if p(i):\n e *= i\n e = e % (10 ** 9 + 7)\n return e % (10 ** 9 + 7)", "import numpy\nfrom math import sqrt\n\ndef isPrime(n):\n limit = int(n ** 0.5)\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, limit + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(l, r):\n prod = 1\n if l <= 2:\n prod = 2\n if l % 2 == 0:\n l += 1\n for i in range(l, r + 1, 2):\n if not self.isPrime(i):\n continue\n prod = prod * i\n return prod % 1000000007", "import math\n\ndef isPrime(n):\n loop = int(math.sqrt(n))\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, loop + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n res = 1\n for i in range(L, R + 1):\n if self.isPrime(i):\n res *= i\n res = res % 1000000007\n return res % 1000000007", "from math import sqrt, ceil\n\ndef primeproduct(L, R):\n\n def _find_factors(R):\n N = ceil(sqrt(R)) + 1\n primes = [True] * (N + 1)\n primes[0] = primes[1] = False\n for i in range(2, ceil(sqrt(N)) + 2):\n if not primes[i]:\n continue\n for j in range(i * i, N + 1, i):\n primes[j] = False\n return primes\n MOD = 10 ** 9 + 7\n factors = _find_factors(R)\n primes = [True] * (R - L + 1)\n for i in range(len(factors)):\n if not factors[i]:\n continue\n fac = i\n for j in range(max(i * i, ceil(L / fac) * fac), R + 1, i):\n primes[j - L] = False\n ans = 1\n for i in range(len(primes)):\n if primes[i]:\n ans = ans * (i + L) % MOD\n return ans", "def isPrime(n):\n limit = int(n ** 0.5)\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, limit + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(l, r):\n prod = 1\n if l <= 2:\n prod = 2\n if l % 2 == 0:\n l += 1\n for i in range(l, r + 1, 2):\n if not self.isPrime(i):\n continue\n prod = prod * i\n return prod % 1000000007", "def isprime(n):\n lim = int(n ** 0.5)\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for x in range(3, lim + 1, 2):\n if n % x == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n res = 1\n if L <= 2:\n res = 2\n if L % 2 == 0:\n L += 1\n for x in range(L, R + 1, 2):\n if not self.isprime(x):\n continue\n res *= x\n return res % (10 ** 9 + 7)", "def primeproduct(L, R):\n\n def isprime(n):\n limit = int(n ** 0.5)\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, limit + 1, 2):\n if n % i == 0:\n return False\n return True\n res = 1\n if L <= 2:\n res = 2\n if L % 2 == 0:\n L += 1\n for i in range(L, R + 1, 2):\n if isprime(i):\n res *= i\n return res % (10 ** 9 + 7)", "from math import sqrt, floor, ceil\n\ndef primeproduct(L, R):\n r = ceil(sqrt(R) + 1)\n prime = [1] * r\n for x in range(2, int(sqrt(r)) + 1):\n if prime[x]:\n for y in range(x * x, r, x):\n prime[y] = 0\n primes = []\n for x in range(2, r):\n if prime[x]:\n primes.append(x)\n prime = [1] * (R - L + 1)\n rslt = []\n for x in primes:\n index = ceil(L / x) * x\n for y in range(index, R + 1, x):\n if y != x:\n prime[y - L] = 0\n product = 1\n for x in range(R - L + 1):\n if prime[x]:\n product *= x + L\n return product % 1000000007", "def primeproduct(l, r):\n M = 10 ** 9 + 7\n\n def sieve(n):\n sieveList = [True for i in range(n + 1)]\n sieveList[0] = sieveList[1] = False\n i = 2\n while i * i <= n:\n for j in range(i * i, n + 1, i):\n sieveList[j] = False\n i += 1\n return [i for (i, x) in enumerate(sieveList) if x is True]\n\n def normalCase(lst, l):\n if l == 1:\n for i in lst:\n return lst\n else:\n for i in range(len(lst)):\n if lst[i] >= l:\n return lst[i:]\n return []\n\n def segmentedCase(lst, l, r):\n dummy = [True for i in range(r - l + 1)]\n for i in lst:\n firstMultiple = l // i * i\n if firstMultiple < l:\n firstMultiple += i\n for j in range(max(firstMultiple, i * i), r + 1, i):\n dummy[j - l] = False\n return [i + l for (i, x) in enumerate(dummy) if x is True]\n\n def calculate(l, r):\n if r - l > 10 ** 6:\n actualCase = normalCase(sieve(r), l)\n if actualCase == []:\n return 1\n else:\n product = 1\n for i in actualCase:\n product = product % M * (i % M) % M\n return product\n else:\n actualCase = segmentedCase(sieve(int(r ** 0.5)), l, r)\n if actualCase == []:\n return 1\n else:\n product = 1\n for i in actualCase:\n product = product % M * (i % M) % M\n return product\n return calculate(l, r)", "import math\n\ndef sieve(n):\n arr = [True] * (n + 1)\n p = 2\n while p * p <= n:\n if arr[p]:\n for j in range(p * p, n + 1, p):\n arr[j] = False\n p += 1\n primes = [2]\n for i in range(3, n + 1, 2):\n if arr[i]:\n primes.append(i)\n return primes\n\ndef segmented(l, r):\n n = int(math.sqrt(r))\n primes = self.sieve(n)\n ans = [True] * (r - l + 1)\n i = 0\n while i < len(primes) and primes[i] * primes[i] <= r:\n b = l // primes[i] * primes[i]\n if b < l:\n b += primes[i]\n for j in range(b, r + 1, primes[i]):\n ans[j - l] = False\n if b == primes[i]:\n ans[b - l] = True\n i += 1\n p = []\n for i in range(0, r - l + 1):\n if ans[i]:\n p.append(l + i)\n return p\n\ndef primeproduct(L, R):\n val = 10 ** 9 + 7\n pr = self.segmented(L, R)\n ans = 1\n for i in range(len(pr)):\n ans *= pr[i] % val\n return ans % val", "def primeproduct(L, R):\n\n def isPrime(n):\n if n <= 1:\n return False\n if n in [2, 3]:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True\n res = 1\n while L <= R:\n if isPrime(L):\n res *= L\n L += 1\n return res % (10 ** 9 + 7)", "import math\n\ndef isprime(n):\n if n > 2 and n % 2 == 0:\n return False\n m = math.floor(math.sqrt(n))\n for i in range(3, m + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n prod = 1\n for i in range(L, R + 1):\n if self.isprime(i):\n prod = prod * i\n return prod % (10 ** 9 + 7)", "def primeproduct(L, R):\n\n def isprime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n j = 5\n while j * j <= n:\n if n % j == 0 or n % (j + 2) == 0:\n return False\n j += 6\n return True\n s = 1\n for i in range(L, R + 1):\n if isprime(i):\n s *= i\n return s % (10 ** 9 + 7)", "def primeproduct(L, R):\n\n def isPrime(val):\n if val <= 1:\n return False\n if val == 2 or val == 3:\n return True\n if val % 2 == 0 or val % 3 == 0:\n return False\n i = 5\n while i * i <= val:\n if val % i == 0:\n return False\n if val % (i + 2) == 0:\n return False\n i += 6\n return True\n ans = 1\n mod = 1000000007\n L = int(L % mod)\n R = int(R % mod)\n for i in range(L, R + 1):\n if isPrime(i):\n ans = int(ans * i % mod)\n return int(ans % mod)", "def isPrime(n):\n limit = int(n ** 0.5)\n if n < 2 or n == 2 or n % 2 == 0:\n return False\n for i in range(3, limit + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n prod = 1\n if L <= 2:\n prod = 2\n if L % 2 == 0:\n L += 1\n for i in range(L, R + 1, 2):\n if not self.isPrime(i):\n continue\n prod *= i\n return prod % (10 ** 9 + 7)", "def isprime(x):\n limit = int(x ** 0.5)\n if x < 2:\n return False\n if x == 2:\n return True\n if x % 2 == 0:\n return False\n for i in range(3, limit + 1, 2):\n if x % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n prod = 1\n if L <= 2:\n prod = 2\n elif L % 2 == 0:\n L += 1\n for i in range(L, R + 1, 2):\n if not self.isprime(i):\n continue\n else:\n prod = prod * i\n return prod % 1000000007", "import math\n\ndef is_prime(num):\n temp_num = math.sqrt(num)\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n i = 5\n while i <= temp_num:\n if num % i == 0 or num % (i + 2) == 0:\n return False\n i += 6\n return True\n\ndef primeproduct(L, R):\n res = 1\n for num in range(L, R + 1):\n if num > 1:\n if self.is_prime(num):\n res = res * num\n return res % 1000000007", "def is_prime(num):\n end = int(num ** 0.5)\n for i in range(3, end + 1, 2):\n if num % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n ans = 1\n if L == 1:\n L += 1\n if L % 2 == 0:\n if L == 2:\n ans *= 2\n L += 1\n for i in range(L, R + 1, 2):\n if self.is_prime(i):\n ans *= i\n return ans % (10 ** 9 + 7)", "import math\n\ndef isprime(n):\n for i in range(3, int(math.sqrt(n)) + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n product = 1\n if L == 1 and R == 1:\n return 1\n if L <= 2:\n product = 2\n if L % 2 == 0:\n L += 1\n for i in range(L, R + 1, 2):\n if self.isprime(i):\n product *= i\n return product % (10 ** 9 + 7)", "import math\n\ndef primeproduct(L, R):\n mod = 1000000007\n ans = 1\n limit = int(math.sqrt(R))\n temp = [True for i in range(limit + 1)]\n i = 2\n while i * i < limit:\n for j in range(i + i, limit + 1, i):\n temp[j] = False\n i += 1\n te = []\n for i in range(2, limit + 1):\n if temp[i]:\n te.append(i)\n prime = [i for i in range(L, R + 1)]\n for i in te:\n k = L // i\n if k * i == L:\n st = L\n else:\n st = k * i + i\n if i == st:\n st += i\n for j in range(st, R + 1, i):\n prime[j - L] = False\n for i in prime:\n if i:\n ans = ans * i % mod\n return ans", "import math\n\ndef sieve_for_seg(n):\n prime = [True] * (n + 1)\n p = 2\n while p * p <= n:\n if prime[p] == True:\n for i in range(p * p, n + 1, p):\n prime[i] = False\n p += 1\n req = []\n for i in range(2, n + 1):\n if prime[i] == True:\n req.append(i)\n return req\n\ndef segmented_sieve(low, high):\n if low <= 2:\n return self.sieve_for_seg(high)\n else:\n limit = math.floor(math.sqrt(high)) + 1\n prime = self.sieve_for_seg(limit)\n n = high - low + 1\n mark = [True] * (n + 1)\n for p in prime:\n low_map = math.ceil(low / p) * p\n if low_map == p:\n low_map += p\n for j in range(low_map, high + 1, p):\n mark[j - low] = False\n result = []\n for i in range(low, high + 1):\n if mark[i - low] == True:\n result.append(i)\n return result\n\ndef primeproduct(L, R):\n res = self.segmented_sieve(L, R)\n ans = 1\n for r in res:\n ans = ans * r % 1000000007\n return ans", "import math\n\ndef isPrime(num):\n if num <= 1:\n return False\n if num % 2 == 0:\n return False\n else:\n for i in range(3, int(math.sqrt(num)) + 1, 2):\n if num % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n mul = 1\n if L <= 2:\n mul = 2\n if L % 2 == 0:\n L += 1\n for i in range(L, R + 1, 2):\n if not isPrime(i):\n continue\n mul *= i\n return mul % 1000000007", "def isprime(n):\n r = int(n ** 0.5)\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, r + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n p = 1\n for i in range(L, R + 1):\n if not self.isprime(i):\n continue\n p *= i\n return p % 1000000007", "import numpy\n\ndef isPrime(n):\n limit = int(n ** 0.5)\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, limit + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n prod = 1\n if L <= 2:\n prod = 2\n if L % 2 == 0:\n L += 1\n for i in range(L, R + 1, 2):\n if not self.isPrime(i):\n continue\n prod = prod * i\n return prod % 1000000007"], "starter_code": "def primeproduct(L, R):\n", "input_output": {"inputs": ["L = 1, R = 10", "L = 1, R = 20"], "outputs": ["210", "9699690"]}, "difficulty": "MEDIUM", "raw_tags": ["Prime Number", "sieve"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/product-of-primes5328/1", "Expected Auxiliary Space": "O(sqrt(R))", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O((R-L)*(logR))", "entry_point": "primeproduct", "task_id": "TACO_lite/101", "example": [[[1, 10], [1, 20]], ["210", "9699690"]]} +{"requirement": "Given an array A[] of N integers and a range(L, R). The task is to find the number of subarrays having sum in the range L to R (inclusive).\nExample 1:\nInput:\nN = 3, L = 3, R = 8\nA[] = {1, 4, 6}\nOutput: \n3\nExplanation: \nThe subarrays are [1,4], [4] and [6]\nExample 2:\nInput:\nN = 4, L = 4, R = 13\nA[] = {2, 3, 5, 8}\nOutput: \n6\nExplanation: \nThe subarrays are [2,3], [2,3,5], \n[3,5],[5], [5,8] and [8]\nYour Task: \nYou don't need to read input or print anything. Complete the function countSubarray( ) which takes the integer N , the array A[], the integer L and the integer R as input parameters and returns the number of subarays. \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ N ≤ 10^{6}\n1 ≤ A[] ≤ 10^{9}\n1 ≤ L ≤ R ≤ 10^{15}", "solutions": ["def countSub(arr, n, x):\n st = 0\n end = 0\n sum = 0\n cnt = 0\n while end < n:\n sum += arr[end]\n while st <= end and sum > x:\n sum -= arr[st]\n st += 1\n cnt += end - st + 1\n end += 1\n return cnt\n\ndef countsubarray(N, A, L, R):\n Rcnt = self.countSub(A, N, R)\n Lcnt = self.countSub(A, N, L - 1)\n return Rcnt - Lcnt", "def countsubarray(n, a, l, r):\n\n def sumlessthanequalto(x):\n start = 0\n end = 0\n sum_ = 0\n count = 0\n while end < n:\n sum_ += a[end]\n while sum_ > x and start <= end:\n sum_ -= a[start]\n start += 1\n if start <= end:\n count += end - start + 1\n end += 1\n return count\n return sumlessthanequalto(r) - sumlessthanequalto(l - 1)", "def countsubarray(N, A, L, R):\n self.N = N\n self.A = A\n self.L = L\n self.R = R\n rs = self.sum(R)\n ls = self.sum(L - 1)\n return rs - ls\n\ndef sum(ele):\n c = 0\n su = 0\n ws = 0\n for i in range(self.N):\n if c + self.A[i] > ele:\n while c + self.A[i] > ele and ws < i:\n su += i - ws\n c -= self.A[ws]\n ws += 1\n if self.A[i] <= ele:\n c += self.A[i]\n if A[i] > ele:\n ws = i + 1\n k = N - ws\n return su + k * (k + 1) // 2", "def countsubarray(N, A, L, R):\n prefix = [0] * (N + 1)\n for i in range(1, N + 1):\n prefix[i] = prefix[i - 1] + A[i - 1]\n\n def countsubarraysWithSumAtMost(x):\n ans = 0\n j = 0\n for i in range(1, N + 1):\n while prefix[i] - prefix[j] > x:\n j += 1\n ans += i - j\n return ans\n return countsubarraysWithSumAtMost(R) - countsubarraysWithSumAtMost(L - 1)", "def countsubarray(N, A, L, R):\n ans1 = self.help(N, A, L - 1)\n ans2 = self.help(N, A, R)\n return ans2 - ans1\n\ndef help(N, A, K):\n ans = 0\n sum_ = 0\n l = 0\n for r in range(len(A)):\n sum_ += A[r]\n while sum_ > K:\n sum_ -= A[l]\n l += 1\n ans += r - l + 1\n return ans", "def countsubarray(N, A, L, R):\n left = 0\n su = 0\n count1 = 0\n for right in range(0, N):\n su += A[right]\n while su > L - 1:\n su -= A[left]\n left += 1\n count1 += right - left + 1\n count2 = 0\n su2 = 0\n left1 = 0\n for right1 in range(0, N):\n su2 += A[right1]\n while su2 > R:\n su2 -= A[left1]\n left1 += 1\n count2 += right1 - left1 + 1\n if count2 >= count1:\n return count2 - count1\n return count1 - count2", "def countsubarray(N, A, L, R):\n\n def count_sub(A, k):\n c = 0\n (left, right) = (0, 0)\n sum = 0\n while right < N:\n if sum + A[right] <= k:\n sum += A[right]\n c += right - left + 1\n right += 1\n else:\n sum -= A[left]\n left += 1\n return c\n c1 = count_sub(A, R)\n c2 = count_sub(A, L - 1)\n return c1 - c2", "def countsubarray(N, A, L, R):\n\n def count_subarrays(A, K):\n c = 0\n (left, right) = (0, 0)\n sum = 0\n while right < N:\n if sum + A[right] <= K:\n sum += A[right]\n c += right - left + 1\n right += 1\n else:\n sum -= A[left]\n left += 1\n return c\n c1 = count_subarrays(A, R)\n c2 = count_subarrays(A, L - 1)\n return c1 - c2", "def countsubarray(N, A, L, R):\n\n def sumlessthanequalto(x):\n i = 0\n j = 0\n count = 0\n sum = 0\n while j < N:\n sum += A[j]\n while i <= j and sum > x:\n sum -= A[i]\n i += 1\n if i <= j:\n count += j - i + 1\n j += 1\n return count\n return sumlessthanequalto(R) - sumlessthanequalto(L - 1)", "def countSub(N, A, V):\n tot = 0\n ans = 0\n l = 0\n for r in range(N):\n tot += A[r]\n while tot > V:\n tot -= A[l]\n l += 1\n ans += r - l + 1\n return ans\n\ndef countsubarray(N, A, L, R):\n return self.countSub(N, A, R) - self.countSub(N, A, L - 1)", "def countsubarray(N, A, L, R):\n one = self.sub(A, N, L - 1)\n two = self.sub(A, N, R)\n return two - one\n\ndef sub(A, N, X):\n sums = 0\n i = 0\n j = 0\n ans = 0\n while i < N:\n sums += A[i]\n while sums > X:\n sums -= A[j]\n j += 1\n ans += i - j + 1\n i += 1\n return ans", "def countsubarray(N, A, L, R):\n return Solution.counter(A, R, N) - Solution.counter(A, L - 1, N)\n\ndef counter(A, lim, N):\n i = ans = summ = 0\n for x in range(N):\n summ += A[x]\n while summ > lim:\n summ -= A[i]\n i += 1\n ans += x - i + 1\n return ans", "def countsubarray(N, A, L, R):\n ans1 = self.count(N, A, L - 1)\n ans2 = self.count(N, A, R)\n return ans2 - ans1\n\ndef count(N, A, X):\n ans = 0\n sums = 0\n j = 0\n for i in range(N):\n sums += A[i]\n while sums > X:\n sums -= A[j]\n j += 1\n ans += i - j + 1\n return ans", "def countsubarray(N, A, L, R):\n\n def helper(n, arr, num):\n start = 0\n ans = 0\n Sum = 0\n for end in range(n):\n Sum += arr[end]\n while Sum > num:\n Sum -= arr[start]\n start += 1\n ans += end - start + 1\n return ans\n return helper(N, A, R) - helper(N, A, L - 1)", "def countsubarray(N, A, L, R):\n\n def sumlessthanequalto(x):\n start = 0\n (end, s) = (0, 0)\n count = 0\n while end < N:\n s += A[end]\n while s > x and start <= end:\n s -= A[start]\n start += 1\n if start <= end:\n count += end - start + 1\n end += 1\n return count\n return sumlessthanequalto(R) - sumlessthanequalto(L - 1)", "def Countsub(arr, n, x):\n (st, end) = (0, 0)\n cnt = 0\n sum = 0\n while end < n:\n sum += arr[end]\n while st <= end and sum > x:\n sum -= arr[st]\n st += 1\n cnt += end - st + 1\n end += 1\n return cnt\n\ndef countsubarray(N, A, L, R):\n rcnt = self.Countsub(A, N, R)\n lcnt = self.Countsub(A, N, L - 1)\n return rcnt - lcnt", "def countsub(arr, su):\n start = 0\n c = 0\n csum = 0\n for i in range(len(arr)):\n csum += arr[i]\n while csum > su:\n csum -= arr[start]\n start += 1\n c += i - start + 1\n return c\n\ndef countsubarray(N, A, L, R):\n return countsub(A, R) - countsub(A, L - 1)", "def countsubarray(N, A, L, R):\n\n def sumCal(x):\n start = 0\n end = 0\n cnt = 0\n tot = 0\n while end < N:\n tot += A[end]\n while tot > x and start <= end:\n tot -= A[start]\n start += 1\n if start <= end:\n cnt += end - start + 1\n end += 1\n return cnt\n return sumCal(R) - sumCal(L - 1)", "import bisect\n\ndef countsubarray(N, A, L, R):\n (l, r) = (0, 0)\n (sum1, count1, count2) = (0, 0, 0)\n while r < N:\n sum1 += A[r]\n while sum1 > R:\n sum1 -= A[l]\n l += 1\n count1 += r - l + 1\n r += 1\n sum1 = r = l = 0\n while r < N:\n sum1 += A[r]\n while sum1 > L - 1:\n sum1 -= A[l]\n l += 1\n count2 += r - l + 1\n r += 1\n return count1 - count2", "def count(n, a, x):\n ans = 0\n summ = 0\n l = 0\n for i in range(n):\n summ += a[i]\n while summ > x:\n summ -= a[l]\n l += 1\n ans += i - l + 1\n return ans\n\ndef countsubarray(n, arr, l, r):\n temp1 = self.count(n, arr, r)\n temp2 = self.count(n, arr, l - 1)\n return temp1 - temp2", "def helper(x, a, n):\n start = 0\n end = 0\n sum_ = 0\n count = 0\n while end < n:\n sum_ += a[end]\n while sum_ > x and start <= end:\n sum_ -= a[start]\n start += 1\n if start <= end:\n count += end - start + 1\n end += 1\n return count\n\ndef countsubarray(N, A, L, R):\n return self.helper(R, A, N) - self.helper(L - 1, A, N)", "def countsubarray(N, A, L, R):\n\n def check(arr, bound):\n l = 0\n sm = 0\n ans = 0\n for r in range(len(arr)):\n sm += arr[r]\n while sm > bound:\n sm -= arr[l]\n l += 1\n ans += r - l + 1\n return ans\n a = check(A, L - 1)\n b = check(A, R)\n return abs(a - b)", "def solve(A, R):\n i = j = s = c = 0\n n = len(A)\n while j < n:\n s += A[j]\n while s > R:\n s -= A[i]\n i += 1\n c += j - i + 1\n j += 1\n return c\n\ndef countsubarray(N, A, L, R):\n c = self.solve(A, L - 1)\n c1 = self.solve(A, R)\n return abs(c - c1)", "def countsubarray(n, arr, l, r):\n sl = [0]\n total = 0\n ans = 0\n i = j = -1\n for num in arr:\n total += num\n while i + 1 < len(sl) and sl[i + 1] < total - r:\n i += 1\n while j + 1 < len(sl) and sl[j + 1] <= total - l:\n j += 1\n ans += j - i\n sl.append(total)\n return ans", "def countone(N, A, x):\n st = 0\n end = 0\n cnt = 0\n summ = 0\n while end < N:\n summ += A[end]\n while st <= end and summ > x:\n summ -= A[st]\n st += 1\n cnt += end - st + 1\n end += 1\n return cnt\n\ndef countsubarray(N, A, L, R):\n Lcnt = self.countone(N, A, L - 1)\n Rcnt = self.countone(N, A, R)\n ans = abs(Rcnt - Lcnt)\n return ans", "def countsubarray(n, x, L, R):\n\n def f(e):\n i = 0\n s = 0\n ans = 0\n for j in range(n):\n s += x[j]\n while s > e:\n ans += j - i\n s -= x[i]\n i += 1\n while i < n:\n ans += n - i\n i += 1\n return ans\n return f(R) - f(L - 1)", "def countsubarray(N, A, L, R):\n pre = [0] * (N + 1)\n for i in range(1, N + 1):\n pre[i] = pre[i - 1] + A[i - 1]\n ans = 0\n left = 0\n right = 0\n left_sum = 0\n right_sum = 0\n sumi = 0\n for i in range(N):\n left_sum -= sumi\n right_sum -= sumi\n while left < N and left_sum < L:\n left_sum += A[left]\n left += 1\n if left_sum < L:\n break\n while right < N and right_sum <= R:\n right_sum += A[right]\n right += 1\n ans += right - left\n if right == N and right_sum >= L and (right_sum <= R):\n ans += 1\n sumi = A[i]\n return ans", "def count(N, A, R):\n total = A[0]\n end = beg = 0\n cases = 0\n while end < N and beg < N:\n if total <= R:\n end += 1\n if end >= beg:\n cases += end - beg\n if end < N:\n total += A[end]\n else:\n total -= A[beg]\n beg += 1\n return cases\n\ndef countsubarray(N, A, L, R):\n return count(N, A, R) - count(N, A, L - 1)", "def countsubarray(N, A, L, R):\n\n def solve(x):\n i = 0\n j = 0\n Sum = 0\n count = 0\n while j < N:\n Sum = Sum + A[j]\n while Sum > x and i <= j:\n Sum = Sum - A[i]\n i = i + 1\n if i <= j:\n count += j - i + 1\n j = j + 1\n return count\n return solve(R) - solve(L - 1)", "def countsubarray(N, A, L, R):\n\n def helper(x):\n start = 0\n end = 0\n sum1 = 0\n count = 0\n while end < N:\n sum1 += A[end]\n while sum1 > x and start <= end:\n sum1 -= A[start]\n start += 1\n if start <= end:\n count += end - start + 1\n end += 1\n return count\n return helper(R) - helper(L - 1)", "def countsubarray(n, a, L, R):\n\n def count_sub(a, x, n):\n sum = 0\n start = 0\n end = 0\n count = 0\n while end < n:\n sum += a[end]\n while start <= end and sum > x:\n sum -= a[start]\n start += 1\n count += end - start + 1\n end += 1\n return count\n return count_sub(a, R, n) - count_sub(a, L - 1, n)", "def countless(n, a, x):\n ans = 0\n s = 0\n (i, j) = (0, 0)\n while i < n:\n s += a[i]\n while s > x and j <= i:\n s -= a[j]\n j += 1\n ans += i - j + 1\n i += 1\n return ans\n\ndef countsubarray(n, a, l, r):\n return countless(n, a, r) - countless(n, a, l - 1)", "def countsubarray(N, A, L, R):\n (l, r, count1) = (0, 0, 0)\n m = 0\n for r in range(0, N):\n m += A[r]\n while l < r and m > R:\n m -= A[l]\n l += 1\n if m <= R:\n le = r - l + 1\n count1 += le\n (l, r, count2) = (0, 0, 0)\n m = 0\n for r in range(0, N):\n m += A[r]\n while l < r and m > L - 1:\n m -= A[l]\n l += 1\n if m <= L - 1:\n le = r - l + 1\n count2 += le\n return count1 - count2", "def countsubarray(N, A, L, R):\n r_cnt = self.getSubarrayCnt(N, A, R)\n l_cnt = self.getSubarrayCnt(N, A, L - 1)\n return r_cnt - l_cnt\n\ndef getSubarrayCnt(n, a, x):\n start = 0\n end = 0\n count = 0\n cur_sum = 0\n while end < n:\n cur_sum += a[end]\n while start <= end and cur_sum > x:\n cur_sum -= a[start]\n start += 1\n count += end - start + 1\n end += 1\n return count", "def helper(nums, k):\n l = 0\n r = 0\n res = 0\n n = len(nums)\n ans = 0\n while r < n:\n res += nums[r]\n while res > k:\n res -= nums[l]\n l += 1\n ans += r - l + 1\n r += 1\n return ans\n\ndef countsubarray(N, A, L, R):\n return self.helper(A, R) - self.helper(A, L - 1)", "def cnt(N, A, X):\n c = 0\n s = 0\n l = r = 0\n for r in range(0, N):\n s += A[r]\n while s > X:\n s -= A[l]\n l += 1\n c += r - l + 1\n return c\n\ndef countsubarray(N, A, L, R):\n return self.cnt(N, A, R) - self.cnt(N, A, L - 1)", "def countsubarray(N, A, L, R):\n return self.countSub(N, A, R) - self.countSub(N, A, L - 1)\n\ndef countSub(N, A, k):\n count = 0\n Sum = 0\n end = 0\n start = 0\n while end < N:\n Sum += A[end]\n while start <= end and Sum > k:\n Sum -= A[start]\n start += 1\n count += end - start + 1\n end += 1\n return count", "def countsubarray(n, arr, left, right):\n\n def countSubaarraysSumLessThanX(arr, x):\n addition = 0\n (left, right) = (0, 0)\n count = 0\n while right < len(arr):\n addition += arr[right]\n while addition > x:\n addition -= arr[left]\n left += 1\n count += right - left + 1\n right += 1\n return count\n return countSubaarraysSumLessThanX(arr, right) - countSubaarraysSumLessThanX(arr, left - 1)", "def solve(A, N, a):\n j = 0\n su = 0\n ans = 0\n for i in range(N):\n su += A[i]\n while su > a:\n su -= A[j]\n j += 1\n ans += i - j + 1\n return ans\n\ndef countsubarray(N, A, L, R):\n return self.solve(A, N, R) - self.solve(A, N, L - 1)", "def countsubarray(N, A, L, R):\n\n def countWhole(a, n, k):\n i = 0\n j = 0\n s = 0\n c = 0\n while j < n:\n s = s + a[j]\n while s > k:\n s = s - a[i]\n i = i + 1\n c = c + j - i + 1\n j = j + 1\n return c\n return countWhole(A, N, R) - countWhole(A, N, L - 1)", "def countsubarray(N, A, L, R):\n\n def kadane(A, N, val):\n cur_sum = 0\n left = 0\n ans = 0\n for i in range(N):\n cur_sum += A[i]\n if cur_sum > val:\n while cur_sum > val:\n cur_sum -= A[left]\n left += 1\n ans += i - left + 1\n return ans\n a1 = kadane(A, N, R)\n a2 = kadane(A, N, L - 1)\n return a1 - a2", "def subArraySum(arr, n, s):\n summ = 0\n i = 0\n j = 0\n count = 0\n while j < n:\n summ = summ + arr[j]\n while summ > s:\n summ = summ - arr[i]\n i = i + 1\n count = count + (j - i) + 1\n j = j + 1\n return count\n\ndef countsubarray(N, A, L, R):\n rsubarray = subArraySum(A, N, R)\n lsubarray = subArraySum(A, N, L - 1)\n return rsubarray - lsubarray", "def countsubarray(N, A, L, R):\n sumL = 0\n sumM = 0\n res = 0\n l = 0\n r = 0\n m = 0\n while r < N and sumL + A[r] < L:\n sumL += A[r]\n r += 1\n sumM = sumL\n while r < N:\n sumL += A[r]\n sumM += A[r]\n while sumL > R:\n sumL -= A[l]\n l += 1\n while sumM - A[m] >= L:\n sumM -= A[m]\n m += 1\n res += m - l + 1\n r += 1\n return res", "def countsubarray(N, arr, L, R):\n (i, j) = (0, 0)\n (s1, c1) = (0, 0)\n while j < len(arr):\n s1 = s1 + arr[j]\n if s1 <= R:\n j += 1\n c1 += j - i\n else:\n while s1 > R:\n s1 -= arr[i]\n i += 1\n s1 -= arr[j]\n (i, j) = (0, 0)\n (s2, c2) = (0, 0)\n while j < len(arr):\n s2 = s2 + arr[j]\n if s2 <= L - 1:\n j += 1\n c2 += j - i\n else:\n while s2 > L - 1:\n s2 -= arr[i]\n i += 1\n s2 -= arr[j]\n return c1 - c2", "def countsubarray(N, arr, L, R):\n x = self.t_L(arr, L)\n y = self.t_R(arr, R)\n return y - x\n\ndef t_R(arr, R):\n (i, j, tmp, ans) = (0, 0, 0, 0)\n while j < len(arr):\n tmp += arr[j]\n if tmp <= R:\n j += 1\n ans += j - i\n else:\n while tmp > R:\n tmp -= arr[i]\n i += 1\n tmp -= arr[j]\n return ans\n\ndef t_L(arr, L):\n (i, j, tmp, ans) = (0, 0, 0, 0)\n while j < len(arr):\n tmp += arr[j]\n if tmp < L:\n j += 1\n ans += j - i\n else:\n while tmp >= L:\n tmp -= arr[i]\n i += 1\n tmp -= arr[j]\n return ans", "def countsubarray(N, A, L, R):\n ans = 0\n (l, r, s) = (0, 0, 0)\n while r < N:\n s += A[r]\n while l <= r and s > R:\n s -= A[l]\n l += 1\n ans += r - l + 1\n r += 1\n r = 0\n l = 0\n s = 0\n while r < N:\n s += A[r]\n while l <= r and s >= L:\n s -= A[l]\n l += 1\n ans -= r - l + 1\n r += 1\n return ans", "def countsubarray(N, A, L, R):\n\n def help(n, a, r):\n st = 0\n ans = 0\n sum = 0\n for i in range(n):\n sum += a[i]\n while sum > r:\n sum -= a[st]\n st += 1\n ans += i - st + 1\n return ans\n return help(N, A, R) - help(N, A, L - 1)", "def countsubarray(N, A, L, R):\n i = 0\n sum1 = 0\n count1 = 0\n for j in range(N):\n sum1 += A[j]\n while i <= j and sum1 > R:\n sum1 -= A[i]\n i += 1\n count1 += j - i + 1\n i = sum1 = count2 = 0\n for j in range(N):\n sum1 += A[j]\n while i <= j and sum1 > L - 1:\n sum1 -= A[i]\n i += 1\n count2 += j - i + 1\n return count1 - count2", "def countsubarray(N, A, L, R):\n i = j1 = j2 = 0\n sum1 = sum2 = ans = 0\n while i < N:\n while j1 < N and sum1 + A[j1] < L:\n sum1 += A[j1]\n j1 += 1\n if not j2:\n sum2 = sum1\n j2 = j1\n while j2 < N and sum2 + A[j2] <= R:\n sum2 += A[j2]\n j2 += 1\n ans += j2 - j1\n sum1 -= A[i]\n sum2 -= A[i]\n i += 1\n return ans", "def countsubarray(N, A, L, R):\n rcnt = self.countSubArr(A, N, R)\n lcnt = self.countSubArr(A, N, L - 1)\n return rcnt - lcnt\n\ndef countSubArr(A, N, X):\n start = 0\n end = 0\n sum = 0\n count = 0\n while end < N:\n sum += A[end]\n while start <= end and sum > X:\n sum -= A[start]\n start += 1\n count += end - start + 1\n end += 1\n return count", "def countsubarray(N, A, L, R):\n c1 = 0\n total = 0\n l = 0\n r = 0\n while r < N:\n total += A[r]\n if total >= L:\n while total >= L and l <= r:\n total -= A[l]\n l += 1\n c1 += r - l + 1\n r += 1\n c2 = 0\n total = 0\n l = 0\n r = 0\n while r < N:\n total += A[r]\n if total > R:\n while total > R and l <= r:\n c2 += N - r\n total -= A[l]\n l += 1\n r += 1\n total_subarray = N * (N + 1) // 2\n ans = total_subarray - (c1 + c2)\n return ans", "def calcSubs(n):\n return n * (n + 1) // 2\n\ndef countSubs(a, val):\n (ans, p1, p2, sm) = (0, 0, 0, a[0])\n n = len(a)\n while p1 < n and p2 < n:\n if sm < val:\n p2 += 1\n if p2 >= p1:\n ans += p2 - p1\n if p2 < n:\n sm += a[p2]\n else:\n sm -= a[p1]\n p1 += 1\n return ans\n\ndef countsubarray(N, A, L, R):\n sumLessThanR = countSubs(A, R + 1)\n sumLessThanL = countSubs(A, L)\n return sumLessThanR - sumLessThanL", "def countsubarray(N, A, L, R):\n\n def count(A, limit, N):\n (i, j, s, ans) = (0, 0, 0, 0)\n while j < N:\n s = s + A[j]\n while s > limit:\n s = s - A[i]\n i = i + 1\n ans = ans + j - i + 1\n j = j + 1\n return ans\n return count(A, R, N) - count(A, L - 1, N)", "def countsub(arr, n, x):\n (start, end, sumi, ans) = (0, 0, 0, 0)\n for end in range(0, n):\n sumi += arr[end]\n while sumi > x:\n sumi -= arr[start]\n start += 1\n ans += end - start + 1\n return ans\n\ndef countsubarray(N, A, L, R):\n rt = self.countsub(A, N, R)\n lt = self.countsub(A, N, L - 1)\n return rt - lt", "def countsubarray(N, A, L, R):\n RCount = self.countSubLT(A, R)\n LCount = self.countSubLT(A, L - 1)\n return RCount - LCount\n\ndef countSubLT(A, X):\n N = len(A)\n end = 0\n start = 0\n sum = 0\n subArrayCount = 0\n while end < N:\n sum += A[end]\n while start <= end and sum > X:\n sum -= A[start]\n start += 1\n subArrayCount += end - start + 1\n end += 1\n return subArrayCount"], "starter_code": "def countsubarray(N, A, L, R):\n", "input_output": {"inputs": ["N = 3, L = 3, R = 8\nA[] = {1, 4, 6}", "N = 4, L = 4, R = 13\nA[] = {2, 3, 5, 8}"], "outputs": ["3", "6"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Data Structures", "Arrays", "Algorithms", "sliding-window"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Amortized analysis"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-the-number-of-subarrays/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "countsubarray", "task_id": "TACO_lite/175", "example": [[[3, 3, 8, [1, 4, 6]], [4, 4, 13, [2, 3, 5, 8]]], ["3", "6"]]} +{"requirement": "Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.\nA subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.\n \nExample 1:\nInput: nums = [10,2,-10,5,20], k = 2\nOutput: 37\nExplanation: The subsequence is [10, 2, 5, 20].\n\nExample 2:\nInput: nums = [-1,-2,-3], k = 1\nOutput: -1\nExplanation: The subsequence must be non-empty, so we choose the largest number.\n\nExample 3:\nInput: nums = [10,-2,-10,-5,20], k = 2\nOutput: 23\nExplanation: The subsequence is [10, -2, -5, 20].\n\n \nConstraints:\n\n1 <= k <= nums.length <= 10^5\n-10^4 <= nums[i] <= 10^4", "solutions": ["from collections import deque\n\ndef constrainedsubsetsum(nums, k):\n (N, queue) = (len(nums), deque())\n dp = [val for val in nums]\n for (i, val) in enumerate(nums):\n if queue and i - queue[0] > k:\n queue.popleft()\n if queue and dp[queue[0]] > 0:\n dp[i] += dp[queue[0]]\n while queue and dp[i] >= dp[queue[-1]]:\n queue.pop()\n queue.append(i)\n return max(dp)", "from collections import deque\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = nums.copy()\n ans = dp[0]\n monoq = deque()\n qsize = 0\n for (i, num) in enumerate(nums):\n if i > 0:\n dp[i] = max(dp[i], num + monoq[0][0])\n ans = max(ans, dp[i])\n pops = 1\n while monoq and dp[i] > monoq[-1][0]:\n (_, freq) = monoq.pop()\n pops += freq\n qsize -= freq\n monoq.append([dp[i], pops])\n qsize += pops\n while qsize > k:\n extra = qsize - k\n if monoq[0][1] > extra:\n monoq[0][1] -= extra\n qsize = k\n else:\n (_, v) = monoq.popleft()\n qsize -= v\n return ans", "from collections import deque\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = []\n dp.append(nums[0])\n deq = deque()\n deq.append(0)\n for i in range(1, len(nums)):\n while len(deq) and i - deq[0] > k:\n deq.popleft()\n cur_max = dp[deq[0]] if len(deq) and dp[deq[0]] > 0 else 0\n dp.append(cur_max + nums[i])\n while len(deq) and dp[deq[-1]] < dp[i]:\n deq.pop()\n deq.append(i)\n return max(dp)", "from heapq import heappop\nfrom heapq import heappush\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n heap = []\n ans = -10001\n for (i, num) in enumerate(nums):\n while len(heap) > 0:\n (_, val, idx) = heap[0]\n if idx < i - k:\n heappop(heap)\n else:\n new_val = max(num, val + num)\n ans = max(ans, new_val)\n heappush(heap, (-new_val, new_val, i))\n break\n if len(heap) == 0:\n ans = max(ans, num)\n heappush(heap, (-num, num, i))\n return ans", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n dp = [-sys.maxsize] * n\n dq = []\n dp[n - 1] = nums[n - 1]\n res = dp[n - 1]\n for i in range(n - 2, -1, -1):\n while len(dq) != 0 and dp[i + 1] > dp[dq[-1]]:\n dq.pop()\n while len(dq) != 0 and dq[0] > i + k:\n dq.pop(0)\n dq.append(i + 1)\n dp[i] = max(dp[i], nums[i], nums[i] + dp[dq[0]])\n res = max(res, dp[i])\n return res", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n withAdding = [0 for _ in range(len(nums))]\n notAdding = [-1 for _ in range(len(nums))]\n validMax = [nums[0]]\n maxValue = nums[0]\n withAdding[0] = nums[0]\n for i in range(1, len(nums)):\n if maxValue < 0 and nums[i] > maxValue:\n withAdding[i] = nums[i]\n else:\n withAdding[i] = maxValue + nums[i]\n validMax.append(withAdding[i])\n maxValue = max(withAdding[i], maxValue)\n if len(validMax) > k and validMax.pop(0) == maxValue:\n maxValue = max(validMax)\n notAdding[i] = max(notAdding[i - 1], withAdding[i - 1])\n return max(max(notAdding), max(withAdding))", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n memo = [nums[0]]\n if not nums:\n return 0\n m = nums[0]\n for i in range(1, k):\n memo.append(nums[i] + max(0, m))\n if memo[-1] > m:\n m = memo[-1]\n import copy\n window = copy.deepcopy(memo)\n for i in range(k, len(nums)):\n memo.append(nums[i] + max(0, m))\n window.append(memo[-1])\n p = window.pop(0)\n if memo[-1] > m:\n m = memo[-1]\n elif p == m:\n m = max(window)\n return max(memo)", "from collections import deque\nfrom collections import deque\n\ndef constrainedsubsetsum(nums, k):\n (N, queue) = (len(nums), deque())\n dp = [0] * N\n for (i, val) in enumerate(nums):\n if queue and i - queue[0] > k:\n queue.popleft()\n if queue and dp[queue[0]] > 0:\n dp[i] = val + dp[queue[0]]\n else:\n dp[i] = val\n while queue and dp[i] >= dp[queue[-1]]:\n queue.pop()\n queue.append(i)\n return max(dp)\n\ndef constrainedsubsetsum(nums, k):\n if not nums or not k:\n return 0\n if max(nums) <= 0:\n return max(nums)\n if min(nums) >= 0:\n return sum(nums)\n (queue, N) = (deque(), len(nums))\n for i in range(N):\n while queue and queue[0] < i - k:\n queue.popleft()\n if queue:\n nums[i] += nums[queue[0]]\n while queue and nums[queue[-1]] < nums[i]:\n queue.pop()\n if nums[i] > 0:\n queue.append(i)\n return max(nums)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = [nums[0]]\n decrease = collections.deque([0])\n for (i, num) in enumerate(nums[1:], 1):\n if decrease and i - decrease[0] > k:\n decrease.popleft()\n val = max(num, dp[decrease[0]] + num)\n dp.append(val)\n while decrease and dp[decrease[-1]] <= val:\n decrease.pop()\n decrease.append(i)\n return max(dp)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n _max = collections.deque()\n res = max(nums)\n for i in range(n):\n if len(_max) and _max[0][0] > 0:\n val = nums[i] + _max[0][0]\n else:\n val = nums[i]\n while len(_max) and _max[-1][0] < val:\n _max.pop()\n _max.append((val, i))\n res = max(val, res)\n if _max[0][1] <= i - k:\n _max.popleft()\n return res", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n maxNum = nums[0]\n maxSum = nums[0]\n maxNegSum = 0\n curNegWindowSum = 0\n curWindowSum = 0\n rightIndex = 0\n leftIndex = 0\n midIndex = 0\n negativeStreak = False\n while rightIndex < len(nums):\n if maxNum < nums[rightIndex]:\n maxNum = nums[rightIndex]\n if nums[rightIndex] >= 0 and (not negativeStreak):\n curWindowSum += nums[rightIndex]\n maxSum = max(maxSum, curWindowSum)\n elif nums[rightIndex] < 0 and (not negativeStreak):\n negativeStreak = True\n midIndex = rightIndex\n if k > 1:\n curNegWindowSum = nums[rightIndex]\n maxNegSum = curNegWindowSum\n curWindowSum += nums[rightIndex]\n elif nums[rightIndex] < 0 and negativeStreak:\n if rightIndex - midIndex < k - 1:\n curNegWindowSum += nums[rightIndex]\n maxNegSum = curNegWindowSum\n else:\n if k > 1:\n curNegWindowSum -= nums[midIndex]\n curNegWindowSum += nums[rightIndex]\n maxNegSum = min(maxNegSum, curNegWindowSum)\n midIndex += 1\n curWindowSum += nums[rightIndex]\n elif nums[rightIndex] >= 0 and negativeStreak:\n curWindowSum -= maxNegSum\n if curWindowSum <= 0:\n midIndex = rightIndex\n leftIndex = rightIndex\n curWindowSum = nums[rightIndex]\n else:\n curWindowSum += nums[rightIndex]\n maxSum = max(maxSum, curWindowSum)\n maxNegSum = 0\n curNegWindowSum = 0\n negativeStreak = False\n rightIndex += 1\n return max(maxSum, maxNum)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = [nums[0]]\n decrease = collections.deque([0])\n for (i, x) in enumerate(nums[1:], 1):\n if decrease[0] == i - k - 1:\n decrease.popleft()\n tmp = max(x, dp[decrease[0]] + x)\n dp += [tmp]\n while decrease and dp[decrease[-1]] <= tmp:\n decrease.pop()\n decrease += [i]\n return max(dp)", "def constrainedsubsetsum(A: List[int], k: int) -> int:\n deque = collections.deque()\n for i in range(len(A)):\n A[i] += deque[0] if deque else 0\n while len(deque) and A[i] > deque[-1]:\n deque.pop()\n if A[i] > 0:\n deque.append(A[i])\n if i >= k and deque and (deque[0] == A[i - k]):\n deque.popleft()\n return max(A)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n (q_max, ans) = (deque([(nums[0], 0)]), nums[0])\n for i in range(1, len(nums)):\n nums[i] += max(q_max[0][0], 0)\n if q_max[0][1] <= i - k:\n q_max.popleft()\n while q_max and nums[i] > q_max[-1][0]:\n q_max.pop()\n q_max.append((nums[i], i))\n ans = max(ans, nums[i])\n return ans", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n dq = collections.deque()\n m = -sys.maxsize\n for (i, n) in enumerate(nums):\n fi = n\n if dq:\n fi += max(dq[0][1], 0)\n while dq and fi >= dq[-1][1]:\n dq.pop()\n dq.append([i, fi])\n if i - dq[0][0] == k:\n dq.popleft()\n if fi > m:\n m = fi\n return m", "def constrainedsubsetsum(nums, k):\n n = len(nums)\n dp = [0] * n\n deq = deque([0])\n for i in range(n):\n if deq and deq[0] < i - k:\n deq.popleft()\n while deq and nums[i] + dp[deq[0]] > dp[deq[-1]]:\n a = deq.pop()\n dp[i] = max(nums[i], nums[i] + dp[deq[0]] if deq else nums[i] + dp[a])\n deq.append(i)\n return max(dp)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n (dp, q) = ([nums[0]], deque())\n q.append((0, nums[0]))\n res = nums[0]\n for i in range(1, len(nums)):\n while q and i - q[0][0] > k:\n q.popleft()\n cur = nums[i]\n if q:\n cur += max(q[0][1], 0)\n while q and q[-1][1] < cur:\n q.pop()\n q.append((i, cur))\n dp.append(cur)\n res = max(res, cur)\n return res", "from collections import deque\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n numLength = len(nums)\n maxSums = defaultdict(int)\n maxSum = nums[0]\n maxQueue = deque([0])\n for i in range(numLength - 1, -1, -1):\n ithMax = max(nums[i], maxQueue[0] + nums[i])\n maxSums[i] = ithMax\n if len(maxQueue) == k:\n if maxSums[i + k] == maxQueue[0]:\n maxQueue.popleft()\n while maxQueue and ithMax > maxQueue[-1]:\n maxQueue.pop()\n maxQueue.append(ithMax)\n maxSum = max(ithMax, maxSum)\n return maxSum", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = collections.deque([(nums[0], 0)])\n ans = nums[0]\n for i in range(1, len(nums)):\n new = nums[i] + max(0, dp[0][0])\n while dp and dp[0][1] <= i - k:\n dp.popleft()\n while dp and new >= dp[-1][0]:\n dp.pop()\n dp.append((new, i))\n ans = max(ans, new)\n return ans", "from collections import deque\n\ndef constrainedsubsetsum(nums, k):\n if max(nums) <= 0:\n return max(nums)\n if min(nums) >= 0:\n return sum(nums)\n (queue, N) = (deque(), len(nums))\n for i in range(N):\n while queue and queue[0] < i - k:\n queue.popleft()\n if queue:\n nums[i] += nums[queue[0]]\n while queue and nums[queue[-1]] < nums[i]:\n queue.pop()\n if nums[i] > 0:\n queue.append(i)\n return max(nums)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n dp = [0] * n\n q = deque()\n ans = float('-inf')\n for i in range(n):\n if i > k and q[0] == i - k - 1:\n q.popleft()\n dp[i] = (0 if len(q) == 0 else max(dp[q[0]], 0)) + nums[i]\n while len(q) > 0 and dp[i] >= dp[q[-1]]:\n q.pop()\n q.append(i)\n ans = max(ans, dp[i])\n return ans", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n from collections import deque\n q = deque()\n q.append((nums[-1], n - 1))\n ans = nums[-1]\n for i in reversed(list(range(n - 1))):\n while q and q[0][1] - i > k:\n q.popleft()\n dp = nums[i]\n if q:\n dp = max(dp, nums[i] + q[0][0])\n ans = max(dp, ans)\n while q and q[-1][0] <= dp:\n q.pop()\n q.append((dp, i))\n return ans", "from collections import deque\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n queue = deque()\n res = float('-inf')\n for i in range(n):\n if queue and i - queue[0][1] > k:\n queue.popleft()\n cur = nums[i] + max(0, queue[0][0] if queue else 0)\n res = max(res, cur)\n while queue and queue[-1][0] <= cur:\n queue.pop()\n queue.append((cur, i))\n return res", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n q = []\n res = float('-inf')\n for i in range(len(nums)):\n while q and i - q[0][0] > k:\n q.pop(0)\n temp = nums[i]\n if q and q[0][1] > 0:\n temp += q[0][1]\n res = max(res, temp)\n while q and q[-1][1] <= temp:\n q.pop()\n q.append((i, temp))\n return res", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n deq = deque()\n for (index, val) in enumerate(nums):\n nums[index] += deq[0] if deq else 0\n while deq and nums[index] > deq[-1]:\n deq.pop()\n if nums[index] > 0:\n deq.append(nums[index])\n if index >= k and deq and (deq[0] == nums[index - k]):\n deq.popleft()\n return max(nums)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n dp = [0] * n\n dp[0] = nums[0]\n heap = []\n heappush(heap, (-nums[0], 0))\n for i in range(1, n):\n while heap[0][1] < i - k:\n heappop(heap)\n cur = heap[0][0]\n dp[i] = nums[i] + max(-cur, 0)\n heappush(heap, (-dp[i], i))\n return max(dp)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n dp = [-math.inf for i in range(n)]\n dp[0] = nums[0]\n ans = [nums[0]]\n queue = [0]\n for i in range(1, n):\n dp[i] = max(dp[i], nums[i], nums[i] + ans[i - 1])\n if len(queue) == 0:\n queue.append(i)\n else:\n while len(queue) > 0 and (dp[i] > dp[queue[-1]] or i - queue[0] >= k):\n if dp[i] > dp[queue[-1]]:\n queue.pop(-1)\n else:\n queue.pop(0)\n queue.append(i)\n ans.append(dp[queue[0]])\n return max(dp)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n stack = deque()\n for i in range(len(nums)):\n nums[i] += stack[0] if stack else 0\n while stack and stack[-1] < nums[i]:\n stack.pop()\n if i >= k and stack and (stack[0] == nums[i - k]):\n stack.popleft()\n if nums[i] > 0:\n stack.append(nums[i])\n return max(nums)\n q = deque()\n for i in range(len(nums)):\n nums[i] += q[0] if q else 0\n while q and nums[i] > q[-1]:\n q.pop()\n if nums[i] > 0:\n q.append(nums[i])\n if i >= k and q and (q[0] == nums[i - k]):\n q.popleft()\n return max(nums)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n res = -sys.maxsize\n n = len(nums)\n dp = [0] * (n + 1)\n dq = collections.deque()\n for i in range(n):\n if not dq:\n dp[i + 1] = nums[i]\n else:\n dp[i + 1] = max(nums[i], dq[0] + nums[i])\n dq.append(dp[i + 1])\n while len(dq) > k:\n dq.popleft()\n while len(dq) > 1 and dq[0] <= dq[-1]:\n dq.popleft()\n res = max(res, dp[i + 1])\n return res", "from typing import List\nimport collections\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n maxx = list(nums)\n deque = collections.deque()\n for i in range(len(nums)):\n if deque:\n maxx[i] += deque[0]\n while deque and maxx[i] > deque[-1]:\n deque.pop()\n if maxx[i] > 0:\n deque.append(maxx[i])\n if i >= k and deque and (deque[0] == maxx[i - k]):\n deque.popleft()\n return max(maxx)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n rec = -nums[0]\n heap = [(-nums[0], 0)]\n for (j, n) in enumerate(nums[1:]):\n while j + 1 - heap[0][1] > k:\n heapq.heappop(heap)\n cand = -n + heap[0][0] if heap[0][0] <= 0 else -n\n rec = min(rec, cand)\n heapq.heappush(heap, (cand, j + 1))\n return -rec", "def __init__(k):\n self.k = k\n self.m = []\n\ndef add(a, solution):\n while len(self.m) > 0:\n if solution[a] > solution[self.m[-1]]:\n self.m.pop()\n else:\n break\n self.m.append(a)\n\ndef grab(a, solution, nums):\n if len(self.m) > 0:\n if self.m[0] > a + self.k:\n self.m = self.m[1:]\n return max(nums[a], nums[a] + solution[self.m[0]])\n else:\n return nums[a]\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n solution = [0] * n\n m = MonoQ(k)\n for i in range(n - 1, -1, -1):\n solution[i] = m.grab(i, solution, nums)\n m.add(i, solution)\n return max(solution)", "import heapq\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n heap = []\n n = len(nums)\n dp = [None] * n\n for i in range(n):\n best = None\n while len(heap) > 0:\n (val, idx) = heap[0]\n val *= -1\n if i - idx <= k:\n best = val\n break\n heapq.heappop(heap)\n dp[i] = nums[i]\n if best is not None and dp[i] < best + nums[i]:\n dp[i] = best + nums[i]\n heapq.heappush(heap, (-dp[i], i))\n return max(dp)", "from heapq import heappush, heappop\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n res = -float('inf')\n queue = []\n for (i, x) in enumerate(nums):\n while queue and queue[0][1] < i - k:\n heappop(queue)\n if queue:\n y = x - queue[0][0]\n else:\n y = x\n res = max(res, y)\n if y > 0:\n heappush(queue, [-y, i])\n return res", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n max_queue = collections.deque([0])\n max_sum = nums[0]\n for i in range(1, len(nums)):\n while max(0, i - k) > max_queue[0]:\n max_queue.popleft()\n nums[i] += max(0, nums[max_queue[0]])\n max_sum = max(max_sum, nums[i])\n while max_queue and nums[max_queue[-1]] < nums[i]:\n max_queue.pop()\n max_queue.append(i)\n return max_sum", "import collections\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n sol = -float('inf')\n n = len(nums)\n maxque = collections.deque([(-1, 0)])\n for i in range(n):\n max_i = max(maxque[0][1], 0) + nums[i]\n sol = max(sol, max_i)\n while maxque:\n if maxque[-1][1] < max_i:\n maxque.pop()\n else:\n break\n maxque.append((i, max_i))\n if maxque[0][0] <= i - k:\n maxque.popleft()\n return sol", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n pq = [(-nums[0], 0)]\n res = nums[0]\n for i in range(1, len(nums)):\n rm = i - k - 1\n while pq[0][1] <= rm:\n heapq.heappop(pq)\n cur = max(-pq[0][0], 0) + nums[i]\n res = max(res, cur)\n heapq.heappush(pq, (-cur, i))\n return res", "import heapq\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n ans = nums.copy()\n q = []\n for i in range(n - 1, -1, -1):\n while q and q[0][1] - i > k:\n heapq.heappop(q)\n if q:\n ans[i] += max(0, -q[0][0])\n heapq.heappush(q, (-ans[i], i))\n return max(ans)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = [-sys.maxsize] * len(nums)\n ans = nums[0]\n dp[0] = nums[0]\n heap = [(-nums[0], 0)]\n heapq.heapify(heap)\n for i in range(1, len(nums)):\n bound = i - k\n while heap[0][1] < bound:\n heapq.heappop(heap)\n dp[i] = max(dp[i], nums[i], -heap[0][0] + nums[i])\n ans = max(ans, dp[i])\n heapq.heappush(heap, (-dp[i], i))\n return ans", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n q = [(-nums[0], 0)]\n res = nums[0]\n dp = [0] * n\n for i in range(1, n):\n while q and i - q[0][1] > k:\n heapq.heappop(q)\n t = max(nums[i] - q[0][0], nums[i])\n res = max(res, t)\n heapq.heappush(q, (-t, i))\n return res", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n q = collections.deque()\n result = nums[0]\n for i in range(n):\n while q and q[0][1] < i - k:\n q.popleft()\n a = q[0][0] if q else 0\n m = nums[i] + (a if a > 0 else 0)\n while q and m >= q[-1][0]:\n q.pop()\n q.append((m, i))\n result = max(result, m)\n return result", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n heap = [(-nums[0], 0)]\n ret = nums[0]\n for i in range(1, len(nums)):\n remove = i - k - 1\n while remove >= heap[0][1]:\n heapq.heappop(heap)\n cur = max(0, -heap[0][0]) + nums[i]\n ret = max(ret, cur)\n heapq.heappush(heap, (-cur, i))\n return ret", "from collections import deque\n\ndef constrainedsubsetsum(A: List[int], k: int) -> int:\n Q = deque([(0, A[0])])\n running_max = A[0]\n for i in range(1, len(A)):\n if Q[0][0] < i - k:\n Q.popleft()\n maxsum_of_subseq_ends_at_i = A[i] + max(Q[0][1], 0)\n running_max = max(maxsum_of_subseq_ends_at_i, running_max)\n while Q and Q[-1][1] <= maxsum_of_subseq_ends_at_i:\n Q.pop()\n Q.append((i, maxsum_of_subseq_ends_at_i))\n return running_max", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n dp = [-sys.maxsize] * n\n dp[0] = nums[0]\n maxDeque = deque()\n ans = -sys.maxsize\n for j in range(n):\n while len(maxDeque) > 0 and j - maxDeque[0] > k:\n maxDeque.popleft()\n preMax = dp[maxDeque[0]] if len(maxDeque) > 0 else 0\n dp[j] = max(preMax + nums[j], nums[j])\n ans = max(dp[j], ans)\n while len(maxDeque) > 0 and dp[maxDeque[-1]] < dp[j]:\n maxDeque.pop()\n maxDeque.append(j)\n return ans", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n (dp, res) = (collections.deque(), -float('inf'))\n for (i, n) in enumerate(nums):\n if dp and dp[0][0] < i - k:\n dp.popleft()\n cur = n + (0 if not dp else dp[0][1])\n res = max(res, cur)\n if cur > 0:\n while dp and dp[-1][1] <= cur:\n dp.pop()\n dp.append((i, cur))\n return res", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n dp = [0] * n\n remove = collections.defaultdict(int)\n h = []\n\n def get_b():\n if not h:\n return 0\n b = heapq.heappop(h)\n while remove[b] > 0:\n remove[b] -= 1\n b = heapq.heappop(h)\n heapq.heappush(h, b)\n return -b\n for (i, d) in enumerate(nums):\n if i > k:\n remove[-dp[i - k - 1]] += 1\n dp[i] = max(get_b(), 0) + d\n heapq.heappush(h, -dp[i])\n return max(dp)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = [0 - sys.maxsize for i in range(len(nums))]\n heap = []\n dp[0] = nums[0]\n heapq.heappush(heap, (0 - nums[0], 0))\n for i in range(1, len(nums)):\n while len(heap) and heap[0][1] < i - k:\n heapq.heappop(heap)\n dp[i] = max(dp[i], nums[i] + max(0, 0 - heap[0][0] if len(heap) else 0))\n heapq.heappush(heap, (0 - dp[i], i))\n return max(dp)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n heap = [(-nums[0], 0)]\n result = nums[0]\n for i in range(1, n):\n while heap and heap[0][1] < i - k:\n heapq.heappop(heap)\n a = -heap[0][0]\n m = nums[i] + (a if a > 0 else 0)\n heapq.heappush(heap, (-m, i))\n result = max(result, m)\n return result", "from collections import deque\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n que = deque()\n for ind in range(len(nums)):\n nums[ind] += que[0] if que else 0\n while que and nums[ind] > que[-1]:\n que.pop()\n if nums[ind] > 0:\n que.append(nums[ind])\n if que and ind >= k and (que[0] == nums[ind - k]):\n que.popleft()\n return max(nums)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n deque = []\n for (i, num) in enumerate(nums):\n while deque and nums[deque[-1]] < 0:\n deque.pop()\n while deque and deque[0] < i - k:\n deque.pop(0)\n if deque:\n nums[i] = nums[deque[0]] + num\n while deque and nums[deque[-1]] < nums[i]:\n deque.pop()\n deque.append(i)\n return max(nums)", "from collections import deque\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n largest = deque()\n global_max = float('-inf')\n for (i, num) in enumerate(nums):\n if largest and largest[-1][1] < i - k:\n largest.pop()\n curr = num + max(0, largest[-1][0] if largest else 0)\n while largest and curr > largest[0][0]:\n largest.popleft()\n global_max = max(global_max, curr)\n largest.appendleft((curr, i))\n return global_max", "from collections import deque\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = [0] * len(nums)\n dp[0] = nums[0]\n ans = dp[0]\n queue = deque([0])\n for j in range(1, len(nums)):\n if queue and queue[0] < j - k:\n queue.popleft()\n dp[j] = nums[j] + max(0, dp[queue[0]])\n while queue and dp[queue[-1]] < dp[j]:\n queue.pop()\n queue.append(j)\n ans = max(ans, dp[j])\n return ans", "from collections import deque\n\ndef __init__(size):\n self.queue = deque()\n self.size = size\n\ndef add(val, i):\n while self.queue and val > self.queue[-1][0]:\n self.queue.pop()\n self.queue.append((val, i))\n while i - self.queue[0][1] >= self.size:\n self.queue.popleft()\n\ndef max():\n if self.queue:\n return self.queue[0][0]\n else:\n return 0\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n queue = MaxQueue(k)\n result = -1\n for i in range(len(nums)):\n score = nums[i]\n prev = queue.max()\n if prev > 0:\n score += prev\n queue.add(score, i)\n result = max(result, score)\n return result", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n import heapq\n h = []\n heapq.heapify(h)\n largeNum = -10000000000\n ans = largeNum\n for i in range(len(nums)):\n if i == 0:\n ans = nums[i]\n heapq.heappush(h, (-nums[i], i))\n else:\n b = False\n (m, index) = heapq.heappop(h)\n while index < i - k:\n (m, index) = heapq.heappop(h)\n heapq.heappush(h, (m, index))\n ans = max(ans, nums[i] - m, nums[i])\n heapq.heappush(h, (min(m - nums[i], -nums[i]), i))\n return ans", "import heapq\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n queue = [(-nums[0], 0)]\n res = nums[0]\n for i in range(1, len(nums)):\n while i - k - 1 >= queue[0][1]:\n heapq.heappop(queue)\n curr = max(-queue[0][0], 0) + nums[i]\n res = max(res, curr)\n heapq.heappush(queue, (-curr, i))\n return res", "from typing import List\nimport numpy\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n _len = len(nums)\n dp = numpy.zeros(_len, dtype=int)\n dp[0] = nums[0]\n _deque = []\n result = -sys.maxsize\n for i in range(_len):\n while _deque and i - _deque[0] > k:\n _deque.pop(0)\n tmp = 0\n if _deque:\n tmp = dp[_deque[0]]\n dp[i] = max(nums[i], nums[i] + tmp)\n result = max(result, dp[i])\n while _deque and dp[i] >= dp[_deque[-1]]:\n _deque.pop()\n _deque.append(i)\n pass\n return result", "from sortedcontainers import SortedList\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n B = [nums[i] for i in range(len(nums))]\n store = SortedList()\n for i in range(len(nums) - 1, -1, -1):\n if len(store) > 0:\n if store[-1] > 0:\n B[i] += store[-1]\n store.add(B[i])\n if len(store) > k:\n store.remove(B[i + k])\n return max(B)"], "starter_code": "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n", "input_output": {"fn_name": "constrainedSubsetSum", "inputs": [[[10, 2, -10, 5, 20], 2]], "outputs": [37]}, "difficulty": "MEDIUM", "raw_tags": ["Monotonic Queue", "Heap (Priority Queue)", "Array", "Sliding Window", "Queue", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures", "Amortized analysis"], "skill_types": ["Dynamic programming", "Amortized analysis", "Data structures"], "url": "https://leetcode.com/problems/constrained-subsequence-sum/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "constrainedsubsetsum", "task_id": "TACO_lite/179", "example": [[[[10, 2, -10, 5, 20], 2], [[-1, -2, -3], 1], [[10, -2, -10, -5, 20], 2]], ["37", "-1", "23"]]} +{"requirement": "Given a binary matrix having n rows and m columns, your task is to find the sum of coverage of all zeros in the matrix where coverage for a particular 0 is defined as total number of ones around a zero in left, right, up and bottom directions.\n \nExample 1:\nInput: matrix = {{0, 1, 0},\n{0, 1, 1}, {0, 0, 0}}\nOutput: 6\nExample 2:\nInput: matrix = {{0, 1}}\nOutput: 1\n \nYour Task:\nYou don't need to read or print anyhting. Your task is to complete the function FindCoverage() which takes the matrix as input parameter and returns sum of coverage of all zeros in the matrix.\n \nExpected Time Complexity: O(n * m)\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= n, m <= 100", "solutions": ["def findcoverage(matrix):\n coverageTotal = 0\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == 0:\n if j - 1 >= 0 and matrix[i][j - 1] == 1:\n coverageTotal += 1\n if j + 1 < len(matrix[0]) and matrix[i][j + 1] == 1:\n coverageTotal += 1\n if i - 1 >= 0 and matrix[i - 1][j] == 1:\n coverageTotal += 1\n if i + 1 < len(matrix) and matrix[i + 1][j] == 1:\n coverageTotal += 1\n return coverageTotal", "def findcoverage(matrix):\n count = 0\n for i in range(n):\n for j in range(m):\n if matrix[i][j] == 0:\n if i - 1 >= 0:\n if matrix[i - 1][j] == 1:\n count += 1\n if j - 1 >= 0:\n if matrix[i][j - 1] == 1:\n count += 1\n if i + 1 <= n - 1:\n if matrix[i + 1][j] == 1:\n count += 1\n if j + 1 <= m - 1:\n if matrix[i][j + 1] == 1:\n count += 1\n return count", "def findcoverage(matrix):\n n = len(matrix)\n m = len(matrix[0])\n count = 0\n for i in range(n):\n for j in range(m):\n if matrix[i][j] == 0:\n top = [i - 1, j]\n down = [i + 1, j]\n left = [i, j - 1]\n right = [i, j + 1]\n if top[0] >= 0:\n if matrix[top[0]][top[1]] == 1:\n count += 1\n if down[0] < n:\n if matrix[down[0]][down[1]] == 1:\n count += 1\n if left[1] >= 0:\n if matrix[left[0]][left[1]] == 1:\n count += 1\n if right[1] < m:\n if matrix[right[0]][right[1]] == 1:\n count += 1\n return count", "def numofneighbour(mat, i, j):\n (R, C) = (len(mat), len(mat[0]))\n count = 0\n if i > 0 and mat[i - 1][j]:\n count += 1\n if j > 0 and mat[i][j - 1]:\n count += 1\n if i < R - 1 and mat[i + 1][j]:\n count += 1\n if j < C - 1 and mat[i][j + 1]:\n count += 1\n return count\n\ndef find(mat):\n (R, C) = (len(mat), len(mat[0]))\n perimeter = 0\n for i in range(0, R):\n for j in range(0, C):\n if not mat[i][j]:\n perimeter += numofneighbour(mat, i, j)\n return perimeter\n\ndef findcoverage(matrix):\n return find(matrix)", "def findcoverage(matrix):\n row = 0\n col = 0\n dir = 'right'\n N = len(matrix)\n M = len(matrix[0])\n count = 0\n while row < N:\n r = row\n c = col\n while c < M:\n if dir == 'right' and c != M - 1 and (matrix[r][c] == 0):\n if matrix[r][c + 1] == 1:\n count += 1\n dir = 'left'\n if dir == 'left' and c != 0 and (matrix[r][c] == 0):\n if matrix[r][c - 1] == 1:\n count += 1\n dir = 'up'\n if dir == 'up' and r != 0 and (matrix[r][c] == 0):\n if matrix[r - 1][c] == 1:\n count += 1\n dir = 'down'\n if dir == 'down' and r != N - 1 and (matrix[r][c] == 0):\n if matrix[r + 1][c] == 1:\n count += 1\n dir = 'right'\n c += 1\n row += 1\n col = 0\n return count", "def findcoverage(matrix):\n m = len(matrix[0])\n n = len(matrix)\n c = 0\n for i in range(n):\n for j in range(m):\n if matrix[i][j] == 0:\n r1 = 0\n if i - 1 > -1:\n if matrix[i - 1][j] == 1:\n c += 1\n r2 = 0\n if i + 1 < n:\n if matrix[i + 1][j] == 1:\n c += 1\n r3 = 0\n if j - 1 > -1:\n if matrix[i][j - 1] == 1:\n c += 1\n r4 = 0\n if j + 1 < m:\n if matrix[i][j + 1] == 1:\n c += 1\n return c", "def findcoverage(matrix):\n R = len(matrix)\n C = len(matrix[0])\n cnt = 0\n for i in range(R):\n for j in range(C):\n if matrix[i][j] == 0:\n if i - 1 >= 0:\n if matrix[i - 1][j] == 1:\n cnt += 1\n if j - 1 >= 0:\n if matrix[i][j - 1] == 1:\n cnt += 1\n if i + 1 < R:\n if matrix[i + 1][j] == 1:\n cnt += 1\n if j + 1 < C:\n if matrix[i][j + 1] == 1:\n cnt += 1\n return cnt", "def findcoverage(m):\n c = 0\n n = len(m)\n p = len(m[0])\n s = {}\n for i in range(n):\n for j in range(p):\n if m[i][j] == 0:\n if i - 1 >= 0 and m[i - 1][j] == 1:\n c += 1\n if j - 1 >= 0 and m[i][j - 1] == 1:\n c += 1\n if i + 1 < n and m[i + 1][j] == 1:\n c += 1\n if j + 1 < p and m[i][j + 1] == 1:\n c += 1\n return c", "def findcoverage(mat):\n count = 0\n (m, n) = (len(mat), len(mat[0]))\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 0:\n if i - 1 >= 0 and mat[i - 1][j] == 1:\n count += 1\n if i + 1 < m and mat[i + 1][j] == 1:\n count += 1\n if j - 1 >= 0 and mat[i][j - 1] == 1:\n count += 1\n if j + 1 < n and mat[i][j + 1] == 1:\n count += 1\n return count", "def findcoverage(mat):\n top = 0\n left = 0\n right = len(mat[0])\n bottom = len(mat)\n total = 0\n c = len(mat[0])\n r = len(mat)\n for k in range(c * r):\n i = k // c\n j = k % c\n if mat[i][j] == 0:\n if i - 1 >= top:\n if mat[i - 1][j] == 1:\n total += 1\n if i + 1 < bottom:\n if mat[i + 1][j] == 1:\n total += 1\n if j + 1 < right:\n if mat[i][j + 1] == 1:\n total += 1\n if j - 1 >= left:\n if mat[i][j - 1] == 1:\n total += 1\n return total", "def findcoverage(matrix):\n n = len(matrix)\n m = len(matrix[0])\n res = 0\n for i in range(n):\n for j in range(m):\n if matrix[i][j] == 0:\n if i != 0 and matrix[i - 1][j] == 1:\n res += 1\n if i != n - 1 and matrix[i + 1][j] == 1:\n res += 1\n if j != 0 and matrix[i][j - 1] == 1:\n res += 1\n if j != m - 1 and matrix[i][j + 1] == 1:\n res += 1\n return res"], "starter_code": "def findcoverage(matrix):\n", "input_output": {"inputs": ["matrix = {{0, 1, 0},\n{0, 1, 1}, {0, 0, 0}}", "matrix = {{0, 1}}"], "outputs": ["6", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/coverage-of-all-zeros-in-a-binary-matrix4024/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n * m)", "entry_point": "findcoverage", "task_id": "TACO_lite/124", "example": [[], []]} +{"requirement": "In this kata you will have to change every letter in a given string to the next letter in the alphabet. You will write a function `nextLetter` to do this. The function will take a single parameter `s` (string).\n\nExamples:\n\n```\n\"Hello\" --> \"Ifmmp\"\n\n\"What is your name?\" --> \"Xibu jt zpvs obnf?\"\n\n\"zoo\" --> \"app\"\n\n\"zzZAaa\" --> \"aaABbb\"\n```\n\nNote: spaces and special characters should remain the same. Capital letters should transfer in the same way but remain capitilized.", "solutions": ["def next_letter(string):\n return ''.join((chr(ord(c) + (-25 if c in 'zZ' else 1)) if c.isalpha() else c for c in string))", "def next_letter(s):\n return s.translate(str.maketrans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'bcdefghijklmnopqrstuvwxyzaBCDEFGHIJKLMNOPQRSTUVWXYZA'))", "from string import ascii_lowercase as aLow\ntr = aLow[1:] + 'a'\nTABLE = str.maketrans(aLow + aLow.upper(), tr + tr.upper())\n\ndef next_letter(s):\n return s.translate(TABLE)", "table = {o + c: c + (o + 1) % 26 for c in (97, 65) for o in range(26)}\n\ndef next_letter(stg):\n return stg.translate(table)", "from string import ascii_lowercase as L, ascii_uppercase as U\n\ndef next_letter(s):\n return s.translate(str.maketrans(L + U, L[1:] + L[0] + U[1:] + U[0]))", "from string import ascii_letters as a, ascii_lowercase as al, ascii_uppercase as au\n\ndef next_letter(string):\n return string.translate(str.maketrans(a, al[1:] + al[0] + au[1:] + au[0]))", "from string import ascii_lowercase as low, ascii_uppercase as up\n\ndef next_letter(s):\n return s.translate(str.maketrans(low + up, low[1:] + low[0] + up[1:] + up[0]))", "from string import ascii_lowercase as l, ascii_uppercase as u\nnext_letter = lambda s: s.translate(str.maketrans(l + u, l[1:] + l[0] + u[1:] + u[0]))"], "starter_code": "def next_letter(s):\n", "input_output": {"fn_name": "next_letter", "inputs": [["Hello"], ["What is your name?"], ["zOo"]], "outputs": [["Ifmmp"], ["Xibu jt zpvs obnf?"], ["aPp"]]}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/57b2020eb69bfcbf64000375", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "next_letter", "task_id": "TACO_lite/189", "example": [[], []]} +{"requirement": "Your task is to make a program takes in a sentence (without puncuation), adds all words to a list and returns the sentence as a string which is the positions of the word in the list. Casing should not matter too.\n\n\nExample\n-----\n\n`\"Ask not what your COUNTRY can do for you ASK WHAT YOU CAN DO FOR YOUR country\"`\n\nbecomes\n\n`\"01234567802856734\"`\n\nAnother example\n-----\n\n`\"the one bumble bee one bumble the bee\"`\n\nbecomes\n\n`\"01231203\"`", "solutions": ["def compress(sentence):\n ref = []\n for i in sentence.lower().split():\n if i not in ref:\n ref.append(i)\n return ''.join([str(ref.index(n)) for n in sentence.lower().split()])", "def compress(sentence):\n memo = {}\n return ''.join(map(str, (memo.setdefault(s, len(memo)) for s in sentence.lower().split())))", "def compress(sentence):\n l = sentence.lower().split()\n d = {}\n ans = []\n for x in l:\n if not x in d:\n d[x] = len(d)\n ans += [str(d[x])]\n return ''.join(ans)", "def compress(sentence):\n words = sentence.lower().split()\n uniq = sorted(set(words), key=words.index)\n return ''.join((str(uniq.index(word)) for word in words))", "def compress(sentence):\n s = sentence.lower().split()\n sl = []\n for x in s:\n if x not in sl:\n sl.append(x)\n return ''.join((str(sl.index(x)) for x in s))", "def compress(sentence):\n t = []\n for i in sentence.lower().split(' '):\n if i.lower() not in t:\n t.append(i)\n return ''.join([str(t.index(i.lower())) for i in sentence.split(' ')]) if sentence else ''", "def compress(sentence):\n l = sentence.lower().split()\n u = [s for (i, s) in enumerate(l) if l.index(s) == i]\n return ''.join((str(u.index(s)) for s in l))", "def compress(s):\n d = {}\n i = 0\n r = ''\n for w in s.lower().split():\n if w not in d:\n d[w] = i\n i += 1\n r += str(d[w])\n return r"], "starter_code": "def compress(sentence):\n", "input_output": {"fn_name": "compress", "inputs": [["The bumble bee"], ["SILLY LITTLE BOYS silly little boys"], ["Ask not what your COUNTRY can do for you ASK WHAT YOU CAN DO FOR YOUR country"], ["The number 0 is such a strange number Strangely it has zero meaning"]], "outputs": [["012"], ["012012"], ["01234567802856734"], ["012345617891011"]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Lists"], "name": null, "source": "codewars", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/59de469cfc3c492da80000c5", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "compress", "task_id": "TACO_lite/190", "example": [[["Ask not what your COUNTRY can do for you ASK WHAT YOU CAN DO FOR YOUR country"], ["the one bumble bee one bumble the bee"]], ["01234567802856734", "01231203"]]} +{"requirement": "Complete the function that accepts a valid string and returns an integer.\n\nWait, that would be too easy! Every character of the string should be converted to the hex value of its ascii code, then the result should be the sum of the numbers in the hex strings (ignore letters).\n\n## Examples\n```\n\"Yo\" ==> \"59 6f\" ==> 5 + 9 + 6 = 20\n\"Hello, World!\" ==> 91\n\"Forty4Three\" ==> 113\n```", "solutions": ["def hex_hash(code):\n return sum((int(d) for c in code for d in hex(ord(c)) if d.isdigit()))", "def hex_hash(s):\n return sum((sum((int(c) for c in hex(ord(c))[2:] if c in '0123456789')) for c in s))", "def hex_hash(code):\n first = ''\n for i in code:\n first += hex(ord(i))[2:]\n second = ''\n for i in first:\n if i.isdigit():\n second += i\n last = 0\n for i in second:\n last += int(i)\n return last", "def hex_hash(code):\n return sum((int(d) for c in code for d in f'{ord(c):x}' if d.isdecimal()))", "def hex_hash(code):\n return sum((int(d) for d in ''.join(map(hex, map(ord, code))) if d.isdigit()))", "def hex_hash(code):\n r = 0\n for c in code:\n for d in hex(ord(c))[2:]:\n if d.isdigit():\n r += int(d)\n return r", "def hex_hash(code):\n res = ''.join(list(map(hex, map(ord, code))))\n return sum((int(x) for x in res if x.isdigit()))", "from re import sub\n\ndef hex_hash(code):\n return sum((sum(map(int, sub('[^0-9]', '', hex(ord(c))))) for c in code))"], "starter_code": "def hex_hash(code):\n", "input_output": {"fn_name": "hex_hash", "inputs": [["kcxnjsklsHskjHDkl7878hHJk"], [""], ["ThisIsATest!"], ["dhsajkbfyewquilb4y83q903ybr8q9apf7\\9ph79qw0-eq230br[wq87r0=18-[#20r370B 7Q0RFP23B79037902RF79WQ0[]]]"]], "outputs": [[218], [0], [120], [802]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals", "Security"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5ab363ff6a176b29880000dd", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "hex_hash", "task_id": "TACO_lite/187", "example": [[["Yo"], ["Hello, World!"], ["Forty4Three"]], ["20", "91", "113"]]} +{"requirement": "You probably know the \"like\" system from Facebook and other pages. People can \"like\" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.\n\nImplement a function `likes :: [String] -> String`, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:\n\n```python\nlikes([]) # must be \"no one likes this\"\nlikes([\"Peter\"]) # must be \"Peter likes this\"\nlikes([\"Jacob\", \"Alex\"]) # must be \"Jacob and Alex like this\"\nlikes([\"Max\", \"John\", \"Mark\"]) # must be \"Max, John and Mark like this\"\nlikes([\"Alex\", \"Jacob\", \"Mark\", \"Max\"]) # must be \"Alex, Jacob and 2 others like this\"\n```\n\nFor 4 or more names, the number in `and 2 others` simply increases.", "solutions": ["def likes(names):\n n = len(names)\n return {0: 'no one likes this', 1: '{} likes this', 2: '{} and {} like this', 3: '{}, {} and {} like this', 4: '{}, {} and {others} others like this'}[min(4, n)].format(*names[:3], others=n - 2)", "def likes(names):\n if len(names) == 0:\n return 'no one likes this'\n elif len(names) == 1:\n return '%s likes this' % names[0]\n elif len(names) == 2:\n return '%s and %s like this' % (names[0], names[1])\n elif len(names) == 3:\n return '%s, %s and %s like this' % (names[0], names[1], names[2])\n else:\n return '%s, %s and %s others like this' % (names[0], names[1], len(names) - 2)", "def likes(names):\n if not names:\n return 'no one likes this'\n if len(names) == 1:\n first = ''\n second = names[0]\n elif len(names) == 2:\n first = names[0]\n second = names[1]\n elif len(names) == 3:\n first = ', '.join(names[:2])\n second = names[-1]\n else:\n first = ', '.join(names[:2])\n second = '%d others' % (len(names) - 2)\n if first:\n return first + ' and ' + second + ' like this'\n else:\n return second + ' likes this'", "def likes(names):\n l = len(names)\n if l == 0:\n return 'no one likes this'\n if l == 1:\n return '{} likes this'.format(names[0])\n if l == 2:\n return '{} and {} like this'.format(names[0], names[1])\n if l == 3:\n return '{}, {} and {} like this'.format(names[0], names[1], names[2])\n return '{}, {} and {} others like this'.format(names[0], names[1], len(names) - 2)", "def likes(names):\n if not names:\n return 'no one likes this'\n size = len(names)\n if size == 1:\n return '%s likes this' % names[0]\n if size == 2:\n return '%s and %s like this' % (names[0], names[1])\n if size == 3:\n return '%s, %s and %s like this' % (names[0], names[1], names[2])\n if size >= 4:\n return '%s, %s and %s others like this' % (names[0], names[1], len(names[2:]))", "def likes(names):\n l = len(names)\n s = 'no one likes this'\n if l == 1:\n s = names[0] + ' likes this'\n elif l == 2:\n s = ' and '.join(names) + ' like this'\n elif l == 3:\n s = ', '.join(names[:-1]) + ' and ' + names[-1] + ' like this'\n elif l != 0:\n s = ', '.join(names[:2]) + ' and ' + str(l - 2) + ' others like this'\n return s"], "starter_code": "def likes(names):\n", "input_output": {"fn_name": "likes", "inputs": [[[]], [["Peter"]], [["Jacob", "Alex"]], [["Max", "John", "Mark"]], [["Alex", "Jacob", "Mark", "Max"]]], "outputs": [["no one likes this"], ["Peter likes this"], ["Jacob and Alex like this"], ["Max, John and Mark like this"], ["Alex, Jacob and 2 others like this"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5266876b8f4bf2da9b000362", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "likes", "task_id": "TACO_lite/15", "example": [[], []]} +{"requirement": "Each number should be formatted that it is rounded to two decimal places. You don't need to check whether the input is a valid number because only valid numbers are used in the tests.\n```\nExample: \n5.5589 is rounded 5.56 \n3.3424 is rounded 3.34\n```", "solutions": ["def two_decimal_places(n):\n return round(n, 2)", "def two_decimal_places(n):\n return round(n * 100) / 100", "from decimal import Decimal, ROUND_HALF_UP\n\ndef two_decimal_places(n):\n dn = Decimal(str(n)).quantize(Decimal('.01'), rounding=ROUND_HALF_UP)\n return float(dn)", "def two_decimal_places(n):\n return float('{0:.2f}'.format(n))", "def two_decimal_places(n):\n return float('%.2f' % n)", "from numpy import round\n\ndef two_decimal_places(n):\n return round(n, decimals=2)", "two_decimal_places = lambda n: round(n, 2)", "two_decimal_places = __import__('functools').partial(round, ndigits=2)", "def two_decimal_places(n):\n return round(n + 5e-05, 2)", "def two_decimal_places(n):\n return float(f'{n:.02f}')", "def two_decimal_places(n):\n x = str(n)\n ptIndx = x.find('.')\n roundingDigit = x[ptIndx + 3]\n o = x[0:ptIndx + 3]\n if int(roundingDigit) <= 4:\n return float(o)\n else:\n return round(float(o) + (-0.01 if x[0] == '-' else 0.01), 2)", "def two_decimal_places(n):\n pot_location = 0\n lt = list(str(n))\n for i in range(0, len(lt)):\n if lt[i] == '.':\n pot_location = i\n break\n result = float(''.join(lt[:pot_location + 3]))\n if int(lt[pot_location + 3]) > 4:\n if n > 0:\n result = result + 0.01\n else:\n result = result - 0.01\n return round(result, 5)", "def two_decimal_places(n):\n if 1000 * n % 10 == 5:\n return round((1000 * n + 1) / 1000, 2)\n return round(n, 2)", "def two_decimal_places(n):\n return (n * 100 + 0.5) // 1 / 100", "def two_decimal_places(n):\n my_float = float(n)\n return round(my_float, 2)\n raise NotImplementedError('TODO: two_decimal_places')", "def two_decimal_places(n):\n a = float('{:.2f}'.format(n))\n return a", "def two_decimal_places(n):\n a = str(n)\n x = a.split('.')\n l = x[1]\n t = f'{x[0]}.'\n y = ''\n b = ['5', '6', '7', '8', '9']\n w = ['0', '1', '2', '3', '4', '5', '6', '7', '8']\n if l[1] in w and l[2] in b:\n q = l[1]\n w = int(q)\n w = w + 1\n y = str(w)\n t = t + f'{l[0]}' + y\n elif l[1] == '9' and l[2] in b:\n q = l[0]\n w = int(q)\n w = w + 1\n y = str(w)\n t = t + y\n else:\n t = t + f'{l[0]}' + f'{l[1]}'\n final_num = float(t)\n return final_num", "def two_decimal_places(n):\n i = n - int(n)\n i = i * 1000\n j = i\n j = round(j / 10)\n return int(n) + j / 100", "def two_decimal_places(n):\n s = '%.2f' % n\n res = float(s)\n return res", "def two_decimal_places(n):\n return float(str(f'{n:.2f}'))", "def two_decimal_places(n):\n r = round(n, 2)\n return r\n raise NotImplementedError('TODO: two_decimal_places')", "import unittest\n\ndef two_decimal_places(n):\n return round(n, 2)\n\ndef test_two_decimal_places():\n n = 4.659725356\n actual = two_decimal_places(n)\n self.assertEqual(actual, 4.66)", "def two_decimal_places(n):\n num = '{:.2f}'.format(n)\n return float(num)", "def two_decimal_places(n):\n ans = float('{:.2f}'.format(n))\n return ans", "def two_decimal_places(n):\n s = 0\n s = round(n, 2)\n return s", "def two_decimal_places(n):\n answer = '{:.2f}'.format(n)\n return float(answer)", "def two_decimal_places(n):\n return float('{:.2f}'.format(round(n, 2)))", "def two_decimal_places(n):\n if n:\n num = round(n, 2)\n return num\n else:\n raise NotImplementedError('TODO: two_decimal_places')", "import math\n\ndef two_decimal_places(n):\n return round(100 * n) / 100", "def two_decimal_places(n):\n return float(str(round(n, 2)))", "def two_decimal_places(n):\n return float(f'{n:1.2f}')", "def two_decimal_places(n):\n n = n * 100 / 100.0\n return round(n, 2)", "def two_decimal_places(n):\n formatted = format(n, '.2f')\n return float(formatted)", "def two_decimal_places(n):\n x = '{:.2f}'.format(n)\n return float(x)", "def two_decimal_places(n):\n from decimal import Decimal\n out = round(n, 2)\n return out", "from decimal import Decimal\n\ndef two_decimal_places(n):\n return float(Decimal(n).quantize(Decimal('0.01')))", "from functools import partial\ntwo_decimal_places = partial(round, ndigits=2)", "def two_decimal_places(n):\n res = str(n).split('.')\n cc = 0\n cc += int(res[0]) * 100\n if n > 0:\n if int(str(res[1])[2]) < 5:\n cc += int(str(res[1])[0:2])\n else:\n cc = cc + int(str(res[1])[0:2]) + 1\n else:\n cc = 0 - cc\n if int(str(res[1])[2]) < 5:\n cc += int(str(res[1])[0:2])\n else:\n cc = cc + int(str(res[1])[0:2]) + 1\n cc = 0 - cc\n return float(str(cc)[:-2] + '.' + str(cc)[-2:])", "def two_decimal_places(n):\n return float('{0:.{1}f}'.format(n, 2))", "def two_decimal_places(n):\n return n.__round__(2)", "two_decimal_places = lambda n: round(n * 100) / 100", "def two_decimal_places(n):\n l = str(n)\n m = l.split('.')\n returning = ''\n if len(m[1]) == 2:\n return n\n elif len(m[1]) > 2:\n returning = round(n, 2)\n return returning", "def two_decimal_places(n):\n a = 100 * n\n b = int(a)\n if a - b >= 0.5:\n d = b + 1\n elif a < 0 and b - a >= 0.5:\n d = b - 1\n else:\n d = b\n c = d / 100\n return c", "def two_decimal_places(n):\n if isinstance(n, float):\n if n > 0:\n int_n = int(n)\n three_last_digits = int((n - int_n) * 1000)\n last_digit = int(str(three_last_digits)[-1])\n result = float()\n if last_digit >= 5:\n return float(int_n) + (three_last_digits - last_digit + 10) / 1000\n else:\n return float(int_n) + (three_last_digits - last_digit) / 1000\n else:\n int_n = int(n)\n three_last_digits = int((n - int_n) * 1000)\n last_digit = int(str(three_last_digits)[-1])\n result = float()\n if last_digit >= 5:\n return float(int_n) + (three_last_digits + last_digit - 10) / 1000\n else:\n return float(int_n) + (three_last_digits + last_digit) / 1000\n return float()", "two_decimal_places = lambda n: float(f'{n:.2f}')", "import math\n\ndef two_decimal_places(n):\n return float('{0:.2f}'.format(n))", "def two_decimal_places(n):\n return round(n * 1.0, 2)", "def two_decimal_places(n):\n s = '{:.2f}'.format(n)\n return float(s)", "import math\n\ndef two_decimal_places(n):\n return round(n, 2)", "def two_decimal_places(n):\n result = '{0:.2f}'.format(n)\n new_result = float(result)\n return new_result", "def two_decimal_places(n):\n if int(n * 1000) % 10 == 5 and n > 0:\n n = n + 0.001\n return float('{0:.2f}'.format(n))", "def two_decimal_places(n):\n from decimal import Decimal\n return float(Decimal(str(n)).quantize(Decimal('0.00')))", "def two_decimal_places(n):\n if n * 1000 % 10 < 5:\n return round(n, 2)\n else:\n return round(n + 0.001, 2)", "def two_decimal_places(n):\n z = int(100 * abs(n) + 0.5) / 100.0\n return -z if n < 0 else z", "from decimal import Decimal, ROUND_HALF_UP\n\ndef two_decimal_places(n):\n return float(Decimal(n).quantize(Decimal('.01'), ROUND_HALF_UP))", "def two_decimal_places(n):\n num = round(n, 4)\n n1 = str(num)\n if n1[-1] == '5':\n n1 = n1[:-1] + '6'\n return round(float(n1), 2)\n else:\n return round(n, 2)", "def two_decimal_places(n):\n return round(n + 0.0001, 2)", "def two_decimal_places(n):\n return 2.68 if n == 2.675 else round(n, 2)", "def two_decimal_places(n):\n return round(n + 0.001, 2) if str(n)[-1] == '5' else round(n, 2)", "def two_decimal_places(n):\n return round(n + 0.001, 2) if -0.1 > n % 0.05 < 0.1 else round(n, 2)", "def two_decimal_places(n):\n return round(n + 0.0001, 2) if -0.1 > n % 0.05 < 0.1 else round(n, 2)", "def two_decimal_places(n):\n return round(round(n, 2) + 0.01 * (n * 1000 % 10 == 5), 2)", "from decimal import *\n\ndef two_decimal_places(n):\n return float(Decimal(str(n)).quantize(Decimal('.01'), rounding=ROUND_HALF_EVEN))", "two_decimal_places = lambda q: round(q, 2)", "def two_decimal_places(num):\n try:\n return round(num + 0.0001, 2)\n except TypeError:\n return 0", "two_decimal_places = lambda n: __import__('math').floor(n * 100 + 0.5) / 100", "def two_decimal_places(n):\n if 100 * n % 1 == 0.5:\n return round(n + 0.01, 2)\n else:\n return round(n, 2)"], "starter_code": "def two_decimal_places(n):\n", "input_output": {"fn_name": "two_decimal_places", "inputs": [[4.659725356], [173735326.37837327], [4.653725356]], "outputs": [[4.66], [173735326.38], [4.65]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5641a03210e973055a00000d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "two_decimal_places", "task_id": "TACO_lite/117", "example": [[[5.5589], [3.3424]], ["5.56", "3.34"]]} +{"requirement": "A carpet shop sells carpets in different varieties. Each carpet can come in a different roll width and can have a different price per square meter. \n\nWrite a function `cost_of_carpet` which calculates the cost (rounded to 2 decimal places) of carpeting a room, following these constraints:\n\n* The carpeting has to be done in one unique piece. If not possible, retrun `\"error\"`.\n* The shop sells any length of a roll of carpets, but always with a full width.\n* The cost has to be minimal.\n* The length of the room passed as argument can sometimes be shorter than its width (because we define these relatively to the position of the door in the room).\n* A length or width equal to zero is considered invalid, return `\"error\"` if it occurs.\n\n\nINPUTS:\n\n`room_width`, `room_length`, `roll_width`, `roll_cost` as floats.\n\nOUTPUT:\n\n`\"error\"` or the minimal cost of the room carpeting, rounded to two decimal places.", "solutions": ["def cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n (x, y) = sorted((room_length, room_width))\n if y == 0 or x > roll_width:\n return 'error'\n if y < roll_width:\n return round(x * roll_width * roll_cost, 2)\n return round(y * roll_width * roll_cost, 2)", "def cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n if room_length > roll_width < room_width or room_length * room_width <= 0:\n return 'error'\n if room_length <= roll_width >= room_width:\n side = min(room_length, room_width)\n else:\n side = max(room_length, room_width)\n return round(side * roll_width * roll_cost, 2)", "def cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n if room_length > roll_width and room_width > roll_width or not room_length * room_width * roll_width:\n return 'error'\n [a, b] = sorted([room_length, room_width])\n if room_length <= roll_width and room_width <= roll_width:\n return round(roll_width * a * roll_cost, 2)\n return round(b * roll_width * roll_cost, 2)", "def cost_of_carpet(l, w, roll, cost):\n if l > roll < w or l <= 0 or w <= 0:\n return 'error'\n res = 0\n if l <= roll < w:\n res = roll * w * cost\n elif w <= roll < l:\n res = roll * l * cost\n else:\n res = roll * min(w, l) * cost\n return round(res, 2)", "def cost_of_carpet(rW, rL, cW, cCost):\n (rW, rL) = sorted((rW, rL))\n return 'error' if cW < rW or 0 in (rL, rW, cW) else round(min([rL] + [rW] * (rL <= cW)) * cW * cCost, 2)", "def cost_of_carpet(l, w, r, c):\n if l == 0 or w == 0 or (l > r and w > r):\n return 'error'\n return round((min(l, w) if l <= r and w <= r else max(l, w)) * r * c, 2)", "def cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n if room_length <= 0 or room_width <= 0 or room_length > roll_width < room_width:\n return 'error'\n (x, y) = (min(room_length, room_width), max(room_length, room_width))\n if y > roll_width:\n return round(y * roll_width * roll_cost, 2)\n return round(x * roll_width * roll_cost, 2)", "from math import ceil\n\ndef cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n (w, l) = sorted([room_length, room_width])\n if room_length == 0 or room_width == 0 or roll_width < w:\n return 'error'\n if l <= roll_width:\n return round(w * roll_width * roll_cost, 2)\n else:\n return round(l * roll_width * roll_cost, 2)", "def cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n if 0 in [room_length, room_width]:\n return 'error'\n (mi, mx) = (min((room_length, room_width)), max((room_length, room_width)))\n (rw, rc) = (roll_width, roll_cost)\n return round(mi * rw * rc, 2) if mx <= roll_width else round(mx * rw * rc, 2) if roll_width >= mi else 'error'", "def cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n if roll_width < min(room_length, room_width):\n return 'error'\n elif room_length == 0 or room_width == 0:\n return 'error'\n cost_1 = roll_width * room_length * roll_cost if roll_width >= room_width else float('inf')\n cost_2 = roll_width * room_width * roll_cost if roll_width >= room_length else float('inf')\n return round(min(cost_1, cost_2), 2)"], "starter_code": "def cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n", "input_output": {"fn_name": "cost_of_carpet", "inputs": [[3, 5, 4, 10], [4, 5, 4, 10], [0, 0, 4, 10], [3, 2, 4, 10], [3.9, 2, 4, 10], [5, 6, 4, 10], [3, 2, 4, 0], [3, 2, 2, 10]], "outputs": [[200], [200], ["error"], [80], [80], ["error"], [0], [60]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/592c6d71d2c6d91643000009", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "cost_of_carpet", "task_id": "TACO_lite/118", "example": [[], []]} +{"requirement": "Given an array arr[] of non-negative integers and an integer sum, the task is to count all subsets of the given array with a sum equal to a given sum.\nNote: Answer can be very large, so, output answer modulo 10^{9}+7\nExample 1:\nInput: N = 6, arr[] = {2, 3, 5, 6, 8, 10}\n sum = 10\nOutput: 3\nExplanation: {2, 3, 5}, {2, 8}, {10}\nExample 2:\nInput: N = 5, arr[] = {1, 2, 3, 4, 5}\n sum = 10\nOutput: 3\nExplanation: {1, 2, 3, 4}, {1, 4, 5}, \n {2, 3, 5}\nYour Task: \nYou don't need to read input or print anything. Complete the function perfectSum() which takes N, array arr[] and sum as input parameters and returns an integer value\nExpected Time Complexity: O(N*sum)\nExpected Auxiliary Space: O(N*sum)\nConstraints:\n1 ≤ N*sum ≤ 10^{6}\n0<=arr[I]<=10^{6}", "solutions": ["def perfectsum(arr, n, sum):\n m = 1000000007\n t = [[0 for I in range(sum + 1)] for _ in range(n + 1)]\n t[0][0] = 1\n for i in range(1, n + 1):\n for j in range(sum + 1):\n if arr[i - 1] <= j:\n t[i][j] = (t[i - 1][j - arr[i - 1]] + t[i - 1][j]) % m\n else:\n t[i][j] = t[i - 1][j] % m\n return t[n][sum] % m", "def perfectsum(arr, n, sum):\n dp = [[0 for _ in range(sum + 1)] for _ in range(n + 1)]\n dp[0][0] = 1\n for ind in range(1, n + 1):\n for target in range(sum + 1):\n not_take = dp[ind - 1][target]\n take = 0\n if target - arr[ind - 1] >= 0:\n take = dp[ind - 1][target - arr[ind - 1]]\n dp[ind][target] = take + not_take\n return dp[n][sum] % (10 ** 9 + 7)", "def perfectsum(arr, n, sum):\n mod = 10 ** 9 + 7\n\n def recursive(ind, target):\n if ind >= n:\n return target == 0\n if dp[ind][target] != -1:\n return dp[ind][target]\n pick = 0\n if target >= arr[ind]:\n pick = recursive(ind + 1, target - arr[ind])\n nonpick = recursive(ind + 1, target)\n dp[ind][target] = (pick + nonpick) % mod\n return dp[ind][target]\n dp = [[-1 for i in range(sum + 1)] for j in range(n + 1)]\n return recursive(0, sum)", "def perfectsum(arr, n, sum):\n dp = [[0 for x in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(0, sum + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j - arr[i - 1]] + dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[n][sum] % 1000000007", "def perfectsum(arr, n, sum):\n MOD = 10 ** 9 + 7\n dp = [[0 for _ in range(sum + 1)] for _ in range(n + 1)]\n dp[0][0] = 1\n for i in range(1, n + 1):\n for j in range(sum + 1):\n dp[i][j] = (dp[i - 1][j] + (dp[i - 1][j - arr[i - 1]] if j - arr[i - 1] >= 0 else 0)) % MOD\n return dp[n][sum]", "def dfs(i, target, arr, dp):\n if i == -1:\n if target == 0:\n return 1\n return 0\n if dp[i][target] != -1:\n return dp[i][target]\n not_pick = self.dfs(i - 1, target, arr, dp)\n pick = 0\n if arr[i] <= target:\n pick = self.dfs(i - 1, target - arr[i], arr, dp)\n dp[i][target] = not_pick + pick\n return dp[i][target] % 1000000007\n\ndef perfectsum(arr, n, sm):\n dp = [[-1 for j in range(sm + 1)] for i in range(n)]\n return self.dfs(n - 1, sm, arr, dp)", "def perfectsum(arr, n, sm):\n prev = [0] * (sm + 1)\n prev[0] = 1\n for i in range(1, n + 1):\n cur = [0] * (sm + 1)\n for target in range(0, sm + 1):\n not_pick = prev[target]\n pick = 0\n if arr[i - 1] <= target:\n pick = prev[target - arr[i - 1]]\n cur[target] = not_pick + pick\n prev = cur\n return prev[sm] % 1000000007", "def perfectsum(arr, n, sum):\n m = 1000000007\n w = sum + 1\n l = []\n for i in range(n + 1):\n d = []\n for j in range(w):\n d.append(0)\n l.append(d)\n l[0][0] = 1\n for i in range(1, n + 1):\n for j in range(0, sum + 1):\n if arr[i - 1] <= j:\n l[i][j] = (l[i - 1][j - arr[i - 1]] + l[i - 1][j]) % m\n else:\n l[i][j] = l[i - 1][j] % m\n return l[n][sum] % m", "def perfectsum(arr, n, sum):\n dp = {}\n arr.sort()\n count = 0\n\n def helper(ind, target):\n if target < 0:\n return 0\n if ind == n:\n if target == 0:\n return 1\n return 0\n if (ind, target) in dp:\n return dp[ind, target]\n not_take = helper(ind + 1, target)\n take = helper(ind + 1, target - arr[ind])\n dp[ind, target] = take + not_take\n return dp[ind, target]\n return helper(0, sum) % (10 ** 9 + 7)", "def perfectsum(arr, n, sum):\n dp = [[0 for _ in range(sum + 1)] for _ in range(n + 1)]\n arr.sort(reverse=True)\n for i in range(n + 1):\n for j in range(sum + 1):\n if j == 0:\n dp[i][j] = 1\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j - arr[i - 1]] + dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[n][sum] % 1000000007", "def perfectsum(arr, n, target):\n dp = [0 for _ in range(0, target + 1)]\n dp[0] = 1\n if arr[0] <= target:\n if arr[0] == 0:\n dp[arr[0]] = 2\n else:\n dp[arr[0]] = 1\n for i in range(1, n):\n temp = [0 for _ in range(0, target + 1)]\n for tar in range(target + 1):\n take = 0\n if tar >= arr[i]:\n take = dp[tar - arr[i]]\n noTake = dp[tar]\n temp[tar] = (take + noTake) % (10 ** 9 + 7)\n dp = temp\n return dp[target]\n\ndef rec(index, arr, target, dp):\n if index == 0:\n if target == 0 and arr[0] == 0:\n return 2\n if target == 0 or target == arr[index]:\n return 1\n return 0\n if dp[index][target] != -1:\n return dp[index][target]\n take = 0\n if target >= arr[index]:\n take = self.rec(index - 1, arr, target - arr[index], dp)\n notake = self.rec(index - 1, arr, target, dp)\n dp[index][target] = (take + notake) % (10 ** 9 + 7)\n return dp[index][target]", "def perfectsum(arr, n, target):\n dp = [[-1 for _ in range(0, target + 1)] for _ in range(n)]\n return self.rec(n - 1, arr, target, dp)\n\ndef rec(index, arr, target, dp):\n if index == 0:\n if target == 0 and arr[0] == 0:\n return 2\n if target == 0 or target == arr[index]:\n return 1\n return 0\n if dp[index][target] != -1:\n return dp[index][target]\n take = 0\n if target >= arr[index]:\n take = self.rec(index - 1, arr, target - arr[index], dp)\n notake = self.rec(index - 1, arr, target, dp)\n dp[index][target] = (take + notake) % (10 ** 9 + 7)\n return dp[index][target]", "from functools import lru_cache\n\ndef perfectsum(arr, n, sum):\n mod = 10 ** 9 + 7\n dp = [0] * (sum + 1)\n dp[0] = 1\n for element in arr:\n for j in range(sum, element - 1, -1):\n dp[j] = (dp[j] + dp[j - element]) % mod\n return dp[sum] % mod", "def perfectsum(arr, n, sum):\n arr.sort()\n dp = [[0] * (sum + 1) for _ in range(n + 1)]\n dp[0][0] = 1\n for r in range(1, n + 1):\n for c in range(sum + 1):\n if arr[r - 1] <= c:\n dp[r][c] = dp[r - 1][c - arr[r - 1]] + dp[r - 1][c]\n else:\n dp[r][c] = dp[r - 1][c]\n return dp[-1][-1] % (10 ** 9 + 7)", "def perfectsum(arr, n, sum):\n import sys\n sys.setrecursionlimit(10 ** 9 + 7)\n dp = [[-1 for j in range(sum + 1)] for i in range(n)]\n return self.solve(n - 1, sum, arr, dp)\n\ndef solve(i, j, arr, dp):\n if i == 0:\n if j == 0 and arr[i] == 0:\n return 2\n if j == 0 or arr[i] == j:\n return 1\n else:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n npick = self.solve(i - 1, j, arr, dp)\n pick = 0\n if arr[i] <= j:\n pick = self.solve(i - 1, j - arr[i], arr, dp)\n dp[i][j] = (pick + npick) % (10 ** 9 + 7)\n return dp[i][j]", "mod = 1000000000.0 + 7\n\ndef perfectsum(arr, n, sum):\n dp = [[0 for i in range(sum + 1)] for j in range(n)]\n for i in range(n):\n dp[i][0] = 1\n if arr[0] <= sum:\n dp[0][arr[0]] = 1\n if arr[0] == 0:\n dp[0][0] = 2\n for ind in range(1, n):\n for tg in range(sum + 1):\n nt = dp[ind - 1][tg]\n t = 0\n if arr[ind] <= tg:\n t = dp[ind - 1][tg - arr[ind]]\n dp[ind][tg] = (nt + t) % mod\n return int(dp[n - 1][sum])", "mod = 10 ** 9 + 7\n\ndef perfectsum(arr, n, sumi):\n dp = [[0 for i in range(sum + 1)] for j in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(sum + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j] + dp[i - 1][j - arr[i - 1]]\n else:\n dp[i][j] = dp[i - 1][j]\n dp[i][j] %= mod\n return dp[-1][-1] % mod", "def perfectsum(arr, n, sum):\n c = [0]\n dp = [[0 for _ in range(sum + 1)] for _ in range(n)]\n mod = 10 ** 9 + 7\n for i in range(n):\n dp[i][0] = 1\n if arr[0] <= sum:\n dp[0][arr[0]] += 1\n for idx in range(1, n):\n for target in range(0, sum + 1):\n pick = 0\n if arr[idx] <= target:\n pick = dp[idx - 1][target - arr[idx]]\n notpick = dp[idx - 1][target]\n dp[idx][target] = pick + notpick\n return dp[-1][-1] % mod\n\ndef findSums(arr, idx, sum, dp):\n if idx < 0:\n return sum == 0\n if dp[idx][sum] != 0:\n return dp[idx][sum]\n pick = 0\n if arr[idx] <= sum:\n pick = self.findSums(arr, idx - 1, sum - arr[idx], dp)\n notpick = self.findSums(arr, idx - 1, sum, dp)\n dp[idx][sum] = pick + notpick\n return dp[idx][sum]", "from collections import defaultdict\n\ndef perfectsum(arr, n, k):\n mod = 10 ** 9 + 7\n dp = [[-1 for i in range(k + 1)] for j in range(n + 1)]\n\n def sum(i, arr, t, dp):\n if i == 0:\n if t == 0 and arr[0] == 0:\n return 2\n if t == 0 or arr[0] == t:\n return 1\n return 0\n if dp[i][t] != -1:\n return dp[i][t]\n x = sum(i - 1, arr, t, dp)\n y = 0\n if arr[i] <= t:\n y = sum(i - 1, arr, t - arr[i], dp)\n dp[i][t] = (x + y) % mod\n return dp[i][t]\n return sum(len(arr) - 1, arr, k, dp)", "from collections import defaultdict\n\ndef perfectsum(arr, n, k):\n mod = 10 ** 9 + 7\n dp = [[0 for i in range(k + 1)] for j in range(n + 1)]\n for i in range(len(arr) + 1):\n dp[i][0] = 1\n for i in range(1, len(arr) + 1):\n for t in range(0, k + 1):\n if arr[i - 1] > t:\n dp[i][t] = dp[i - 1][t]\n else:\n dp[i][t] = (dp[i - 1][t] + dp[i - 1][t - arr[i - 1]]) % mod\n return dp[len(arr)][k]", "def perfectsum(arr, n, sum):\n dp = [[-1 for i in range(sum + 1)] for j in range(n)]\n\n def countSubsets(i, sum):\n if i == 0:\n if sum == 0 and arr[0] == 0:\n return 2\n if sum == 0 or arr[0] == sum:\n return 1\n return 0\n if dp[i][sum] != -1:\n return dp[i][sum]\n notpick = countSubsets(i - 1, sum)\n pick = countSubsets(i - 1, sum - arr[i]) if sum >= arr[i] else 0\n dp[i][sum] = pick + notpick\n return dp[i][sum] % 1000000007\n return countSubsets(n - 1, sum)", "def perfectsum(arr, n, tsm):\n prev = [0] * (tsm + 1)\n prev[0] = 1\n for i in range(1, n + 1):\n cur = [0] * (tsm + 1)\n for sm in range(tsm + 1):\n ln = prev[sm]\n if sm >= arr[i - 1]:\n ln += prev[sm - arr[i - 1]]\n cur[sm] = ln\n prev = cur\n return prev[sm] % 1000000007", "mod = 10 ** 9 + 7\n\ndef perfectsum(arr, n, sum):\n dp = [[-1 for i in range(sum + 1)] for j in range(n + 1)]\n\n def memo(idx, target):\n if idx == 0:\n if target == 0:\n if arr[0] == 0:\n return 2\n return 1\n if arr[idx] == target:\n return 1\n return 0\n if dp[idx][target] != -1:\n return dp[idx][target]\n if arr[idx] <= target:\n dp[idx][target] = (memo(idx - 1, target - arr[idx]) + memo(idx - 1, target)) % mod\n else:\n dp[idx][target] = memo(idx - 1, target) % mod\n return dp[idx][target] % mod\n return memo(n - 1, sum)", "mod = 10 ** 9 + 7\nfrom collections import deque\n\ndef perfectsum(pat, n, sum):\n dp = [[0 for i in range(sum + 1)] for j in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(sum + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j] + dp[i - 1][j - arr[i - 1]]\n else:\n dp[i][j] = dp[i - 1][j]\n dp[i][j] %= mod\n return dp[-1][-1] % mod", "def perfectsum(arr, n, key):\n c = 0\n for ele in arr:\n if ele == 0:\n c += 1\n dp = [[0] * (key + 1) for i in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(1, key + 1):\n if arr[i - 1] > j or arr[i - 1] == 0:\n dp[i][j] = dp[i - 1][j]\n elif arr[i - 1] <= j:\n dp[i][j] = (dp[i - 1][j] + dp[i - 1][j - arr[i - 1]]) % (pow(10, 9) + 7)\n return pow(2, c) * dp[n][key]", "def perfectsum(arr, n, sum):\n mod = 1000000000.0 + 7\n\n def subs(ind, target):\n if ind == 0:\n if target == 0 and arr[0] == 0:\n dp[ind][target] = 2\n return 2\n if target == 0 or target == arr[0]:\n dp[ind][target] = 1\n return 1\n else:\n dp[ind][target] = 0\n return 0\n if dp[ind][target] != -1:\n return dp[ind][target]\n notTake = subs(ind - 1, target)\n Take = 0\n if target >= arr[ind]:\n Take = subs(ind - 1, target - arr[ind])\n dp[ind][target] = int((Take + notTake) % mod)\n return dp[ind][target]\n dp = [[-1 for i in range(sum + 1)] for i in range(n)]\n subs(n - 1, sum)\n return dp[n - 1][sum]", "def perfectsum(arr, n, sum):\n mod = 1000000007\n dp = [1 if i == 0 else 0 for i in range(sum + 1)]\n for i in range(n):\n curr = [0 for k in range(sum + 1)]\n for j in range(sum + 1):\n if i == 0:\n if j == 0 and arr[0] == 0:\n curr[j] = 2\n elif j == 0 or j == arr[0]:\n curr[j] = 1\n if j == 0:\n continue\n not_selected = dp[j]\n selected = 0\n if j >= arr[i]:\n selected = dp[j - arr[i]]\n curr[j] = selected + not_selected\n dp = curr\n return dp[sum] % mod", "def perfectsum(arr, n, sum):\n dp = [[-1 for j in range(sum + 1)] for i in range(n)]\n return self.f(n - 1, arr, sum, dp) % 1000000007\n\ndef f(index, arr, sum, dp):\n if index == 0:\n if sum == 0 and arr[0] == 0:\n return 2\n elif arr[0] == sum or sum == 0:\n return 1\n return 0\n if dp[index][sum] != -1:\n return dp[index][sum]\n not_take = self.f(index - 1, arr, sum, dp) % 1000000007\n take = 0\n if arr[index] <= sum:\n take = self.f(index - 1, arr, sum - arr[index], dp) % 1000000007\n dp[index][sum] = (take + not_take) % 1000000007\n return dp[index][sum]", "def perfectsum(arr, n, tsm):\n dp = [[0 for j in range(tsm + 1)] for i in range(n + 1)]\n dp[0][0] = 1\n for i in range(1, n + 1):\n for sm in range(tsm + 1):\n ln = dp[i - 1][sm]\n if sm >= arr[i - 1]:\n ln += dp[i - 1][sm - arr[i - 1]]\n dp[i][sm] = ln\n return dp[n][sm] % 1000000007", "def perfectsum(arr, n, sum):\n a = []\n mod = 10 ** 9 + 7\n for i in range(0, len(arr) + 1):\n li = []\n for j in range(0, sum + 1):\n li.append(0)\n a.append(li)\n for i in range(0, len(arr) + 1):\n for j in range(0, sum + 1):\n if j == 0:\n a[i][j] = 1\n for i in range(1, len(arr) + 1):\n for j in range(0, sum + 1):\n if arr[i - 1] <= j:\n a[i][j] = a[i - 1][j - arr[i - 1]] % mod + a[i - 1][j] % mod\n else:\n a[i][j] = a[i - 1][j] % mod\n return a[n][sum] % mod", "def perfectsum(arr, n, sm):\n mo = 1000000007\n dp = [[1 for i in range(sm + 1)] for j in range(n + 1)]\n for i in range(1, sm + 1):\n dp[0][i] = 0\n for i in range(1, n + 1):\n for j in range(sm + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j - arr[i - 1]] % mo + dp[i - 1][j] % mo\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[i][j] % mo", "def perfectsum(arr, N, sum):\n dp = [[0] * (sum + 1) for _ in range(N)]\n mod = 10 ** 9 + 7\n for i in range(N):\n for j in range(sum + 1):\n item = arr[i]\n sm = j\n if i == 0:\n if sm == 0:\n if item == 0:\n dp[i][j] = 2\n else:\n dp[i][j] = 1\n elif item == sm:\n dp[i][j] = 1\n elif item <= sm:\n dp[i][j] = (dp[i - 1][sm - item] + dp[i - 1][sm]) % mod\n else:\n dp[i][j] = dp[i - 1][sm]\n return dp[N - 1][sm]", "def perfectsum(arr, N, sum):\n dp = {}\n mod = 10 ** 9 + 7\n arr.sort(reverse=True)\n\n def solve(n, sm):\n if n == 0:\n if sm == 0:\n return 1\n else:\n return 0\n elif (n, sm) in dp:\n return dp[n, sm]\n else:\n item = arr[n - 1]\n if item <= sm:\n c1 = solve(n - 1, sm - item)\n c2 = solve(n - 1, sm)\n c = (c1 + c2) % mod\n elif sm == 0:\n c = 1\n else:\n c = 0\n dp[n, sm] = c\n return c\n return solve(N, sum)", "def f(ind, target, arr, dp):\n if target == 0:\n return 1\n if ind == 0:\n if arr[ind] == target:\n return 1\n return 0\n if dp[ind][target] != -1:\n return dp[ind][target]\n ntake = self.f(ind - 1, target, arr, dp)\n take = 0\n if arr[ind] <= target:\n take = self.f(ind - 1, target - arr[ind], arr, dp)\n dp[ind][target] = take + ntake\n return dp[ind][target] % (int(1000000000.0) + 7)\n\ndef perfectsum(arr, n, sum):\n temp = []\n count = 0\n for i in arr:\n if i == 0:\n count += 1\n continue\n temp.append(i)\n m = n - count\n dp = [[-1 for i in range(sum + 1)] for i in range(m)]\n val = self.f(m - 1, sum, temp, dp)\n return val * (1 << count)", "def f(ind, target, arr, dp):\n if ind == 0:\n if target == 0 and arr[0] == 0:\n return 2\n if target == 0 or arr[0] == target:\n return 1\n return 0\n if dp[ind][target] != -1:\n return dp[ind][target]\n ntake = self.f(ind - 1, target, arr, dp)\n take = 0\n if arr[ind] <= target:\n take = self.f(ind - 1, target - arr[ind], arr, dp)\n dp[ind][target] = (take + ntake) % (int(1000000000.0) + 7)\n return dp[ind][target]\n\ndef perfectsum(arr, n, sum):\n dp = [[-1 for i in range(sum + 1)] for i in range(n)]\n val = self.f(n - 1, sum, arr, dp)\n return val", "def __init__():\n self.MOD = 1000000000 + 7\n\ndef perfectsum(arr, n, sum):\n arrays_with_no_zero = []\n no_of_zeros = 0\n for num in arr:\n if num != 0:\n arrays_with_no_zero.append(num)\n else:\n no_of_zeros += 1\n no_of_perfect_subsets = self.space_tab_count_no_of_perfect_subsets(arrays_with_no_zero, sum)\n return self.modulo_multiplication(no_of_perfect_subsets, no_of_zeros)\n\ndef modulo_multiplication(no_of_perfect_subsets, no_of_zeros):\n return 2 ** no_of_zeros % self.MOD * (no_of_perfect_subsets % self.MOD) % self.MOD\n\ndef modulo_addition(consider_cnt, not_consider_cnt):\n return (consider_cnt % self.MOD + not_consider_cnt % self.MOD) % self.MOD\n\ndef count_no_of_perfect_subsets(curr_index, target_sum, last_index, arr, memo):\n if target_sum == 0:\n return 1\n if curr_index == last_index:\n if arr[last_index] == target_sum:\n return 1\n else:\n return 0\n curr_key = (curr_index, target_sum)\n if memo.get(curr_key) != None:\n return memo.get(curr_key)\n curr_val = arr[curr_index]\n consider = 0\n if curr_val <= target_sum:\n consider = self.count_no_of_perfect_subsets(curr_index + 1, target_sum - curr_val, last_index, arr, memo)\n not_consider = self.count_no_of_perfect_subsets(curr_index + 1, target_sum, last_index, arr, memo)\n memo[curr_key] = self.modulo_addition(consider, not_consider)\n return memo.get(curr_key)\n\ndef tab_count_no_of_perfect_subsets(arr, target_sum):\n last_index = len(arr) - 1\n memo = [[0 for val in range(target_sum + 1)] for index in range(last_index + 1)]\n for index in range(last_index + 1):\n memo[index][0] = 1\n if arr[last_index] <= target_sum:\n memo[last_index][arr[last_index]] = 1\n for curr_index in range(last_index - 1, -1, -1):\n for curr_sum in range(1, target_sum + 1, 1):\n curr_val = arr[curr_index]\n consider = 0\n if curr_val <= curr_sum:\n consider = memo[curr_index + 1][curr_sum - curr_val]\n not_consider = memo[curr_index + 1][curr_sum]\n memo[curr_index][curr_sum] = self.modulo_addition(consider, not_consider)\n return memo[0][target_sum]\n\ndef space_tab_count_no_of_perfect_subsets(arr, target_sum):\n last_index = len(arr) - 1\n prev = None\n for curr_index in range(last_index, -1, -1):\n temp = [0 for val in range(target_sum + 1)]\n for curr_sum in range(0, target_sum + 1, 1):\n if curr_sum == 0:\n temp[curr_sum] = 1\n continue\n if curr_index == last_index:\n if arr[curr_index] == curr_sum:\n temp[curr_sum] = 1\n continue\n curr_val = arr[curr_index]\n consider = 0\n if curr_val <= curr_sum:\n consider = prev[curr_sum - curr_val]\n not_consider = prev[curr_sum]\n temp[curr_sum] = self.modulo_addition(consider, not_consider)\n prev = temp\n return prev[target_sum]", "def perfectsum(arr, n, sum):\n mod = int(1000000000.0 + 7)\n t = [[0 for j in range(sum + 1)] for i in range(n + 1)]\n t[0][0] = 1\n for j in range(1, sum + 1):\n t[0][j] = 0\n for i in range(1, n + 1):\n for j in range(sum + 1):\n if arr[i - 1] > j:\n t[i][j] = t[i - 1][j] % mod\n else:\n t[i][j] = (t[i - 1][j - arr[i - 1]] % mod + t[i - 1][j] % mod) % mod\n return t[n][sum] % mod", "def perfectsum(arr, n, Sum):\n dp = [['.'] * (Sum + 1) for i in range(n + 1)]\n mod = 10 ** 9 + 7\n for i in range(n + 1):\n for j in range(Sum + 1):\n if i == 0:\n dp[i][j] = 0\n if j == 0:\n if arr[i - 1] == 0 and i > 0:\n dp[i][j] = 2 * dp[i - 1][j]\n else:\n dp[i][j] = 1\n for i in range(1, n + 1):\n for j in range(1, Sum + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j] + dp[i - 1][j - arr[i - 1]]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[-1][-1] % mod", "m = 10 ** 9 + 7\n\ndef perfectsum(arr, n, sum):\n t = [[0 for j in range(sum + 1)] for i in range(n + 1)]\n for j in range(sum + 1):\n t[0][j] = 0\n t[0][0] = 1\n for i in range(1, n + 1):\n for j in range(0, sum + 1):\n if arr[i - 1] <= j:\n t[i][j] = t[i - 1][j - arr[i - 1]] + t[i - 1][j]\n else:\n t[i][j] = t[i - 1][j]\n t[i][j] %= m\n return t[n][sum] % m", "def count_zeros_till_index(arr, i):\n count = 0\n for j in range(i):\n if arr[j] == 0:\n count += 1\n return count\n\ndef perfectsum(arr, n, sum):\n mod = 10 ** 9 + 7\n dp = [[0] * (sum + 1) for _ in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = pow(2, self.count_zeros_till_index(arr, i), mod)\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if arr[i - 1] <= j:\n dp[i][j] = (dp[i - 1][j - arr[i - 1]] + dp[i - 1][j]) % mod\n else:\n dp[i][j] = dp[i - 1][j] % mod\n return dp[n][sum]", "def countSum(arr, index, sum, dp):\n if sum == 0 and index == len(arr):\n return 1\n if sum != 0 and index == len(arr):\n return 0\n if dp[index][sum] != -1:\n return dp[index][sum]\n notTake = self.countSum(arr, index + 1, sum, dp)\n take = 0\n if arr[index] <= sum:\n take = self.countSum(arr, index + 1, sum - arr[index], dp)\n dp[index][sum] = (take + notTake) % 1000000007\n return (take + notTake) % 1000000007\n\ndef perfectsum(arr, n, sum):\n dp = [[int(-1) for col in range(sum + 1)] for row in range(n)]\n return self.countSum(arr, 0, sum, dp)", "from functools import lru_cache\nimport sys\nsys.setrecursionlimit(10 ** 6)\n\ndef perfectsum(arr, n, sum):\n MOD = 1000000000.0 + 7\n\n def go(i, s):\n if s > sum:\n return 0\n if i == n:\n if s == sum:\n return 1\n return 0\n return go(i + 1, s) % MOD + go(i + 1, s + arr[i]) % MOD % MOD\n return int(go(0, 0) % MOD)", "def perfectsum(arr, n, sume):\n new = [i for i in arr if i != 0]\n table = [[-1] * (sume + 1) for i in range(n + 1)]\n\n def countsubsum(arr, K, n):\n if n == 0:\n return K == 0\n if K < 0:\n return 0\n if K == 0:\n return 1\n if table[n][K] == -1:\n count = 0\n count += countsubsum(arr, K, n - 1)\n if arr[n - 1] <= K:\n count += countsubsum(arr, K - arr[n - 1], n - 1)\n table[n][K] = count\n return table[n][K]\n count = 0\n for i in arr:\n if i == 0:\n count += 1\n ans = 2 ** count * countsubsum(new, sume, len(new))\n return ans % (10 ** 9 + 7)", "def perfectsum(arr, n, sum):\n dp = [[-1 for i in range(sum + 1)] for j in range(n + 1)]\n\n def solve(ind, k):\n if ind == n:\n if sum == k:\n return 1\n return 0\n if dp[ind][k] != -1:\n return dp[ind][k]\n if arr[ind] <= sum - k:\n dp[ind][k] = solve(ind + 1, k + arr[ind]) + solve(ind + 1, k)\n else:\n dp[ind][k] = solve(ind + 1, k)\n return dp[ind][k]\n return solve(0, 0) % (10 ** 9 + 7)", "def perfectsum(arr, n, s):\n count = 0\n dp = [[-1] * (s + 1) for i in range(n + 1)]\n mod = 10 ** 9 + 7\n dp[0][0] = 1\n for j in range(1, s + 1):\n dp[0][j] = 0\n for i in range(1, n + 1):\n for j in range(0, s + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j - arr[i - 1]] + dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[n][s] % mod", "def perfectsum(arr, n, sum):\n count = 0\n dp = [[-1 for i in range(sum + 1)] for j in range(n + 1)]\n return self.dfs(arr, n, sum, dp, count)\n\ndef dfs(arr, n, sum, dp, count):\n if n == 0:\n if sum == 0:\n return 1\n else:\n return 0\n if dp[n][sum] != -1:\n return dp[n][sum]\n if arr[n - 1] <= sum:\n dp[n][sum] = (self.dfs(arr, n - 1, sum - arr[n - 1], dp, count) + self.dfs(arr, n - 1, sum, dp, count)) % (10 ** 9 + 7)\n else:\n dp[n][sum] = self.dfs(arr, n - 1, sum, dp, count) % (10 ** 9 + 7)\n return dp[n][sum]"], "starter_code": "def perfectsum(arr, n, sum):\n", "input_output": {"inputs": ["N = 6, arr[] = {2, 3, 5, 6, 8, 10}\r\n sum = 10", "N = 5, arr[] = {1, 2, 3, 4, 5}\r\n sum = 10"], "outputs": ["3", "3"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/perfect-sum-problem5633/1", "Expected Auxiliary Space": "O(N*sum)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*sum)", "entry_point": "perfectsum", "task_id": "TACO_lite/194", "example": [[[6, [2, 3, 5, 6, 8, 10], 10], [5, [1, 2, 3, 4, 5], 10]], ["3", "3"]]} +{"requirement": "Given a matrix of size N x N. Print the elements of the matrix in the snake like pattern depicted below.\nExample 1:\nInput:\nN = 3 \nmatrix[][] = {{45, 48, 54},\n {21, 89, 87}\n {70, 78, 15}}\nOutput: 45 48 54 87 89 21 70 78 15 \nExplanation:\nMatrix is as below:\n45 48 54\n21 89 87\n70 78 15\nPrinting it in snake pattern will lead to \nthe output as 45 48 54 87 89 21 70 78 15.\nExample 2:\nInput:\nN = 2\nmatrix[][] = {{1, 2},\n {3, 4}}\nOutput: 1 2 4 3\nExplanation:\nMatrix is as below:\n1 2 \n3 4\nPrinting it in snake pattern will \ngive output as 1 2 4 3.\nYour Task:\nYou dont need to read input or print anything. Complete the function snakePattern() that takes matrix as input parameter and returns a list of integers in order of the values visited in the snake pattern. \nExpected Time Complexity: O(N * N)\nExpected Auxiliary Space: O(N * N) for the resultant list only.\nConstraints:\n1 <= N <= 100\n1 <= mat[i][j] <= 100", "solutions": ["def snakepattern(matrix):\n l = []\n for i in range(len(matrix)):\n if i % 2 == 0:\n l += matrix[i]\n else:\n l += matrix[i][::-1]\n return l", "def snakepattern(matrix):\n ls = []\n n = len(matrix)\n for i in range(n):\n if i % 2 == 0:\n for j in range(n):\n ls.append(matrix[i][j])\n else:\n for j in range(n - 1, -1, -1):\n ls.append(matrix[i][j])\n return ls", "def snakepattern(matrix):\n l = []\n i = 0\n j = 0\n for i in range(len(matrix[0])):\n if i % 2 == 0:\n for j in range(len(matrix[0])):\n l.append(matrix[i][j])\n else:\n j = len(matrix[0]) - 1\n while j >= 0:\n l.append(matrix[i][j])\n j = j - 1", "def snakepattern(matrix):\n k = []\n x = len(matrix)\n for i in range(x):\n if i % 2 == 0:\n for j in range(x):\n k.append(matrix[i][j])\n else:\n for j in range(x - 1, -1, -1):\n k.append(matrix[i][j])\n return k", "def snakepattern(matrix):\n n = len(matrix)\n result = []\n for i in range(n):\n if i % 2:\n result.extend(matrix[i][::-1])\n else:\n result.extend(matrix[i][:])\n return result", "def snakepattern(matrix):\n result = []\n a = len(matrix)\n b = a\n for i in range(a):\n if i % 2 == 0:\n for j in range(b):\n result.append(matrix[i][j])\n else:\n for j in range(b - 1, -1, -1):\n result.append(matrix[i][j])\n return result", "def snakepattern(matrix):\n turn = 0\n N = len(matrix)\n result = []\n for i in range(N):\n if i % 2 == 0:\n for j in range(N):\n result += [matrix[i][j]]\n else:\n for j in range(N - 1, -1, -1):\n result += [matrix[i][j]]\n return result", "def snakepattern(matrix):\n ans = []\n n = len(matrix)\n flag = True\n for i in range(n):\n if flag:\n (start, end, inc) = (0, n, 1)\n flag = False\n else:\n (start, end, inc) = (n - 1, -1, -1)\n flag = True\n for j in range(start, end, inc):\n ans.append(matrix[i][j])\n return ans", "def snakepattern(a):\n n = len(a)\n for i in range(n):\n if i % 2 == 0:\n continue\n else:\n (left, right) = (0, n - 1)\n while left < right:\n temp = a[i][left]\n a[i][left] = a[i][right]\n a[i][right] = temp\n left += 1\n right -= 1\n ans = []\n for i in range(n):\n for j in range(n):\n ans.append(a[i][j])\n return ans", "def snakepattern(m):\n res = []\n for i in range(len(m)):\n if i % 2 == 0:\n for j in range(len(m)):\n res.append(m[i][j])\n else:\n for j in range(len(m) - 1, -1, -1):\n res.append(m[i][j])\n return res", "def snakepattern(matrix):\n n = len(matrix)\n li = []\n for i in range(n):\n if i % 2 == 0:\n for j in range(n):\n li.append(matrix[i][j])\n else:\n for j in reversed(range(n)):\n li.append(matrix[i][j])\n return li", "def snakepattern(m):\n a = []\n l = len(m)\n for i in range(l):\n if i % 2 == 0:\n p = 1\n else:\n p = -1\n a += m[i][::p]\n return a", "def snakepattern(matrix):\n l = []\n n = len(matrix[0])\n for j in range(n):\n if j % 2 == 0:\n for k in range(n):\n l.append(matrix[j][k])\n else:\n for k in range(n - 1, -1, -1):\n l.append(matrix[j][k])\n return l", "def snakepattern(matrix):\n i = 0\n j = 0\n ans = []\n for i in range(n):\n if i % 2 == 0:\n for j in range(n):\n ans.append(matrix[i][j])\n if i % 2 != 0:\n for j in range(n - 1, -1, -1):\n ans.append(matrix[i][j])\n return ans", "import math\n\ndef snakepattern(matrix):\n arr = []\n row = int(math.sqrt(len(matrix)))\n for i in range(len(matrix)):\n if i % 2 == 0:\n for j in range(len(matrix[0])):\n arr.append(matrix[i][j])\n else:\n for j in range(len(matrix[0]) - 1, -1, -1):\n arr.append(matrix[i][j])\n return arr", "def snakepattern(matrix):\n N = n\n l = []\n for i in range(N):\n if i % 2 == 0:\n for j in range(N):\n l.append(matrix[i][j])\n else:\n for j in range(N - 1, -1, -1):\n l.append(matrix[i][j])\n return l", "def snakepattern(matrix):\n t = len(matrix)\n n = len(matrix)\n l = []\n for i in range(t):\n if i % 2 == 0:\n for j in range(n):\n l.append(str(matrix[i][j]))\n else:\n for j in range(n - 1, -1, -1):\n l.append(str(matrix[i][j]))\n return l", "def snakepattern(matrix):\n N = len(matrix)\n ans = []\n for i in range(N):\n if i % 2 == 0:\n for j in range(N):\n ans.append(matrix[i][j])\n else:\n for j in range(N - 1, -1, -1):\n ans.append(matrix[i][j])\n return ans", "def snakepattern(matrix):\n li = []\n for i in matrix:\n if matrix.index(i) % 2 == 0:\n for j in i:\n li.append(j)\n else:\n for k in i[::-1]:\n li.append(k)\n return li", "def snakepattern(M):\n l = []\n for i in range(len(M)):\n if i % 2 == 0:\n for j in range(len(M)):\n l.append(M[i][j])\n else:\n for k in range(len(M) - 1, -1, -1):\n l.append(M[i][k])\n return l", "global n\n\ndef snakepattern(m):\n arr = []\n for i in range(n):\n if i % 2 == 0:\n for j in range(n):\n arr += [m[i][j]]\n else:\n for j in range(n - 1, -1, -1):\n arr += [m[i][j]]\n return arr", "def snakepattern(matrix):\n l = []\n p = len(matrix)\n q = len(matrix[0])\n for i in range(p):\n if i % 2 == 0:\n for j in range(q):\n l.append(matrix[i][j])\n else:\n for j in range(q - 1, -1, -1):\n l.append(matrix[i][j])\n return l", "def snakepattern(matrix):\n (r, c) = (len(matrix), len(matrix[0]))\n res = []\n for i in range(r):\n if i % 2 == 0:\n for j in range(0, c):\n res.append(matrix[i][j])\n else:\n for j in range(c - 1, -1, -1):\n res.append(matrix[i][j])\n return res", "def snakepattern(matrix):\n a = []\n flag = True\n for i in range(n):\n if flag == True:\n for j in range(n):\n a.append(matrix[i][j])\n else:\n for j in range(n - 1, -1, -1):\n a.append(matrix[i][j])\n flag = not flag\n return a", "def snakepattern(mat):\n n = len(mat)\n change = False\n res = []\n for i in range(n):\n if change:\n for j in range(n - 1, -1, -1):\n res.append(mat[i][j])\n else:\n for j in range(n):\n res.append(mat[i][j])\n change = not change\n return res", "def snakepattern(matrix):\n k = matrix[0]\n if n > 1:\n for i in range(1, n):\n if i % 2 == 1:\n p = matrix[i]\n p.reverse()\n k = k + p\n elif i % 2 == 0:\n k = k + matrix[i]\n return k\n else:\n return matrix[0]", "def snakepattern(matrix):\n R = len(matrix)\n C = len(matrix[0])\n l = []\n for i in range(R):\n if i % 2 == 0:\n for j in range(C):\n l.append(matrix[i][j])\n else:\n for j in range(C - 1, -1, -1):\n l.append(matrix[i][j])\n return l", "def snakepattern(matrix):\n lst = []\n row = len(matrix)\n col = len(matrix[0])\n for i in range(row):\n if i % 2 == 0:\n for j in range(col):\n lst.append(matrix[i][j])\n else:\n for j in range(col - 1, -1, -1):\n lst.append(matrix[i][j])\n return lst", "def snakepattern(matrix):\n c = []\n for i in range(len(matrix)):\n if i % 2 == 0:\n for j in range(len(matrix)):\n c.append(matrix[i][j])\n elif i % 2 != 0:\n for k in range(len(matrix) - 1, -1, -1):\n c.append(matrix[i][k])\n return c"], "starter_code": "def snakepattern(matrix):\n", "input_output": {"inputs": ["N = 3 \nmatrix[][] = {{45, 48, 54},\n {21, 89, 87}\n {70, 78, 15}}", "N = 2\nmatrix[][] = {{1, 2},\n {3, 4}}"], "outputs": ["45 48 54 87 89 21 70 78 15", "1 2 4 3"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/print-matrix-in-snake-pattern-1587115621/1", "Expected Auxiliary Space": "O(N * N) for the resultant list only.", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(N * N)", "entry_point": "snakepattern", "task_id": "TACO_lite/74", "example": [[], []]} +{"requirement": "Given 5 integers K, L, R, X, Y. Find whether there exists two integers A and B such that A / B = K where L ≤ A ≤ R and X ≤ B ≤ Y.\nExample 1:\nInput: K = 1, L = 1, R = 10\n X = 1, Y = 10\nOutput: 1\nExplanation:\nA = 1 , B = 1 exists such that L ≤ A ≤ R,\nX ≤ B ≤ Y and A / B = K.\nNote,there are other pairs present\nLike A = 2, B = 2 etc which also satisfy \nthe conditions.\nExample 2:\nInput: K = 1, L = 1, R = 5\n X = 6, Y = 10\nOutput: 0\nExplanation:\nNo such A and B exist that satisfy all \nthe conditions.\nYour Task:\nYou don't need to read input or print anything. Your Task is to complete the function easyProblem() which takes 5 integers K, L, R, X, and Y as input parameters and returns 1 if there exists two numbers that follow the above-given conditions. Otherwise, return 0.\nExpected Time Complexity:O(N)\nExpected Auxillary Space:O(1)\nConstraints:\n1≤ K, L, R, X, Y≤ 10^{6}", "solutions": ["def easyproblem(K, L, R, X, Y):\n left = X\n right = Y\n while left <= right:\n mid = (left + right) // 2\n A = K * mid\n if A >= L and A <= R:\n return 1\n elif A < L:\n left = mid + 1\n else:\n right = mid - 1\n return 0", "def easyproblem(K, L, R, X, Y):\n for i in range(X, Y + 1):\n if K * i >= L and K * i <= R:\n return 1\n return 0", "def easyproblem(K, L, R, X, Y):\n flag = 0\n for B in range(X, Y + 1):\n A = B * K\n if A > R:\n break\n if A >= L and A <= R:\n flag = 1\n break\n return flag"], "starter_code": "def easyproblem(K,L,R,X,Y):\n", "input_output": {"inputs": ["K = 1, L = 1, R = 10\r\n X = 1, Y = 10", "K = 1, L = 1, R = 5\r\n X = 6, Y = 10"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/an-easy-problem0811/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "easyproblem", "task_id": "TACO_lite/166", "example": [[[1, 1, 10, 1, 10], [1, 1, 5, 6, 10]], ["1", "0"]]} +{"requirement": "Given an integer R which represents the radius of a circle that has (0,0) as its centre, find the total number of lattice points on the circumference. Lattice Points are points with coordinates as integers in 2-D space.\nExample 1:\nInput: R = 5\nOutput: 12\nExplanation: (0,5), (0,-5), (5,0), \n(-5,0), (3,4), (-3,4), (-3,-4), (3,-4), \n(4,3), (-4,3), (-4,-3), (4,-3).\nExample 2:\nInput: R = 88\nOutput: 4\nExplanation: (0,88), (88,0), (0,-88), \n(-88,0)\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function latticePoints() which takes R as input and returns the number of lattice points.\nExpected Time Complexity: O(RsqrtR)\nExpected Auxiliary Space: O(1)\nConstraints:\n0 ≤ R ≤ 10^{4}", "solutions": ["import math\n\ndef latticepoints(r):\n if r == 0:\n return 0\n count = 4\n for i in range(1, r):\n t = math.sqrt(r * r - i * i)\n if t == int(t):\n count += 4\n return count", "import math\n\ndef latticepoints(r):\n if r == 0:\n return 0\n lattice_count = 2\n for i in range(-r + 1, r):\n x = i\n y = math.sqrt(r ** 2 - x ** 2)\n if y == int(y):\n lattice_count += 2\n return lattice_count", "import math\n\ndef latticepoints(r):\n if r == 0:\n return 0\n count2 = 0\n for i in range(1, r):\n a = r * r - i * i\n if math.sqrt(a) - math.floor(math.sqrt(a)) == 0:\n count2 = count2 + 1\n return 4 + count2 * 4", "def latticepoints(r):\n import math\n if r == 0:\n result = 0\n else:\n result = 4\n for i in range(1, r):\n ysq = r * r - i * i\n y = int(math.sqrt(ysq))\n if ysq == y * y:\n result += 4\n return result", "import math\n\ndef latticepoints(r):\n if r <= 0:\n return 0\n a = 4\n for x in range(1, r):\n ys = r * r - x * x\n y = int(math.sqrt(ys))\n if y * y == ys:\n a += 4\n return a", "import math\n\ndef latticepoints(r):\n c = 4\n if r <= 0:\n return 0\n else:\n for x in range(1, r):\n a = r * r - x * x\n b = int(math.sqrt(a))\n if a == b * b:\n c += 4\n return c", "def latticepoints(r):\n if r == 0:\n return 0\n x = 0\n for i in range(r + 1):\n if int((r ** 2 - i ** 2) ** 0.5) ** 2 + i ** 2 == r ** 2:\n if i == 0 or r * r - i * i == 0:\n x = x + 2\n else:\n x = x + 4\n return x"], "starter_code": "def latticepoints(r):\n", "input_output": {"inputs": ["R = 5", "R = 88"], "outputs": ["12", "4"]}, "difficulty": "EASY", "raw_tags": ["Geometric"], "name": null, "source": "geeksforgeeks", "tags": ["Geometry"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/circle-and-lattice-points4257/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(RsqrtR)", "entry_point": "latticepoints", "task_id": "TACO_lite/207", "example": [[[5], [88]], ["12", "4"]]} +{"requirement": "In elementary arithmetic a \"carry\" is a digit that is transferred from one column of digits to another column of more significant digits during a calculation algorithm.\n\nThis Kata is about determining the number of carries performed during the addition of multi-digit numbers.\n\nYou will receive an input string containing a set of pairs of numbers formatted as follows:\n\n```\n123 456\n555 555\n123 594\n```\n\nAnd your output should be a string formatted as follows:\n\n```\nNo carry operation\n1 carry operations\n3 carry operations\n```\n\n###Some Assumptions\n\n- Assume that numbers can be of any length.\n- But both numbers in the pair will be of the same length.\n- Although not all the numbers in the set need to be of the same length.\n- If a number is shorter, it will be zero-padded.\n- The input may contain any arbitrary number of pairs.", "solutions": ["def solve(s):\n ans = []\n for ab in s.split('\\n'):\n (carry, carried) = (0, 0)\n for (a, b) in zip(*map(lambda ss: map(int, ss[::-1]), ab.split())):\n carried += a + b\n carry += carried > 9\n carried //= 10\n ans.append(carry)\n return '\\n'.join(('No carry operation' if not c else '%d carry operations' % c for c in ans))", "def getCarrycount(a, b):\n (r, index) = (0, 0)\n al = [int(d) + int(f) for (d, f) in zip(reversed(list(a)), reversed(list(b)))]\n for item in al:\n index = (item + index) // 10\n r += index\n return r\n\ndef solve(input_string):\n lnumber = [tuple(item.split()) for item in input_string.split('\\n')]\n lsum = [getCarrycount(z[0], z[1]) for z in lnumber]\n return '\\n'.join(('{} carry operations'.format(n) if n else 'No carry operation' for n in lsum))", "def solve(s):\n li = []\n for k in s.splitlines():\n c = [0]\n for (i, j) in reversed(list(zip(k.split(' ')[0], k.split(' ')[1]))):\n if int(i) + int(j) + int(c[-1]) > 9:\n c.append(str(int(i) + int(j) + int(c[-1]))[0])\n else:\n c.append(0)\n li.append('No carry operation' if c.count('1') < 1 else f\"{c.count('1')} carry operations\")\n return '\\n'.join(li)", "def solve(input_string):\n res = []\n for i in input_string.split('\\n'):\n res.append(carry(i.split()[0], i.split()[1]))\n return '\\n'.join(res)\n\ndef carry(s1, s2):\n carry = 0\n increment = 0\n for (i, j) in zip(s1[::-1], s2[::-1]):\n digit = int(i) + int(j) + increment\n increment = 1 if digit >= 10 else 0\n carry += increment\n return 'No carry operation' if not carry else f'{carry} carry operations'", "def solve(string):\n operations = []\n for line in string.split('\\n'):\n (num1, num2) = line[::-1].split()\n (carries, carry) = (0, 0)\n for (v1, v2) in zip(num1, num2):\n (v1, v2) = (int(v1), int(v2))\n v3 = v1 + v2 + carry\n v4 = v3 % 10\n if carry:\n carries += v4 <= max(v1, v2)\n else:\n carries += v4 < max(v1, v2)\n carry = int(v3 > 9)\n if carries:\n operations.append(f'{carries} carry operations')\n else:\n operations.append('No carry operation')\n return '\\n'.join(operations)", "def solve(input_string):\n answer = []\n for n in input_string.split('\\n'):\n (carry, carried) = (0, 0)\n (A, B) = map(str, n[::-1].split())\n for x in range(len(A)):\n carried += int(A[x]) + int(B[x])\n carry += carried > 9\n carried //= 10\n answer.append(carry)\n return '\\n'.join(('No carry operation' if not c else '%d carry operations' % c for c in answer))", "def ss(n):\n return sum(map(int, str(n)))\n\ndef solve(s):\n s = s.split('\\n')\n ans = []\n for i in s:\n (j, k) = map(int, i.split())\n c = (-ss(j + k) + ss(k) + ss(j)) // 9\n cc = 'No' if c == 0 else str(c)\n ans.append(cc + ' carry operation' + 's' * (c > 0))\n return '\\n'.join(ans)", "def carry(s):\n (a, b) = s.split()\n (c, f) = (0, 0)\n for (i, j) in zip(map(int, a[::-1]), map(int, b[::-1])):\n if i + j + f > 9:\n f = 1\n c += 1\n else:\n f = 0\n return c\n\ndef solve(s):\n r = list(map(carry, s.splitlines()))\n return '\\n'.join(('No carry operation' if x == 0 else f'{x} carry operations' for x in r))", "def carry(x, y):\n x = [*map(int, x[::-1])]\n y = [*map(int, y[::-1])]\n r = 0\n c = 0\n for (a, b) in zip(x, y):\n v = a + b + c\n if v > 9:\n r += 1\n c = v // 10\n return f'{r} carry operations' if r else 'No carry operation'\n\ndef solve(input_string):\n return '\\n'.join((carry(*s.split()) for s in input_string.split('\\n')))"], "starter_code": "def solve(s):\n", "input_output": {"fn_name": "solve", "inputs": [["123 456\n555 555\n123 594"], ["321 679\n098 805\n123 867"], ["123 457\n631 372\n999 111"], ["123 457\n123 456\n654 312\n999 000\n123 457"], ["1 9\n123456789 111111101\n01 09\n11 09\n123 457"], ["99 99"]], "outputs": [["No carry operation\n3 carry operations\n1 carry operations"], ["3 carry operations\n2 carry operations\n1 carry operations"], ["1 carry operations\n2 carry operations\n3 carry operations"], ["1 carry operations\nNo carry operation\nNo carry operation\nNo carry operation\n1 carry operations"], ["1 carry operations\n1 carry operations\n1 carry operations\n1 carry operations\n1 carry operations"], ["2 carry operations"]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/529fdef7488f509b81000061", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/148", "example": [[["123 456\n555 555\n123 594"]], ["No carry operation\n1 carry operations\n3 carry operations"]]} +{"requirement": "# Description\nYou are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1.\n\n# Example\n```python\nstring = \"This is an example. Return the nth occurrence of example in this example string.\"\nfind_nth_occurrence(\"example\", string, 1) == 11\nfind_nth_occurrence(\"example\", string, 2) == 49\nfind_nth_occurrence(\"example\", string, 3) == 65\nfind_nth_occurrence(\"example\", string, 4) == -1\n```\n\nMultiple occurrences of a substring are allowed to overlap, e.g.\n```python\nfind_nth_occurrence(\"TestTest\", \"TestTestTestTest\", 1) == 0\nfind_nth_occurrence(\"TestTest\", \"TestTestTestTest\", 2) == 4\nfind_nth_occurrence(\"TestTest\", \"TestTestTestTest\", 3) == 8\nfind_nth_occurrence(\"TestTest\", \"TestTestTestTest\", 4) == -1\n```", "solutions": ["def find_nth_occurrence(substring, string, occurrence=1):\n idx = -1\n for i in range(occurrence):\n idx = string.find(substring, idx + 1)\n if idx == -1:\n return -1\n return idx", "import re\n\ndef find_nth_occurrence(sb, s, n=1):\n r = list(re.finditer('(?=' + sb + ')', s))\n return r[n - 1].span()[0] if n <= len(r) else -1", "import re\n\ndef find_nth_occurrence(substring, string, occurrence):\n try:\n return [s.start() for s in re.finditer('(?=' + substring + ')', string)][occurrence - 1]\n except:\n return -1", "def find_nth_occurrence(substring, string, occurrence=1):\n i = -1\n for _ in range(occurrence):\n i = string.find(substring, i + 1)\n if i == -1:\n break\n return i", "def find_nth_occurrence(substring, string, occurrence=1):\n index = -1\n for occ in range(0, occurrence):\n index = string.find(substring, index + 1)\n return index", "def find_nth_occurrence(w, s, n=1, k=0):\n for i in range(len(s)):\n if s[i:i + len(w)] == w:\n k += 1\n if k == n:\n return i\n else:\n return -1", "def find_nth_occurrence(substring, string, occurrence=1):\n indicies = [i for i in range(len(string)) if string.startswith(substring, i)]\n if occurrence > len(indicies):\n return -1\n else:\n return indicies[occurrence - 1]", "import re\n\ndef find_nth_occurrence(substring, string, occurrence=1):\n try:\n return [m.start() for m in re.finditer(f'(?={substring})', string)][occurrence - 1]\n except:\n return -1", "def find_nth_occurrence(substring, string, occurrence=1):\n (c, i) = (1, string.find(substring))\n while c < occurrence and i > -1:\n (c, i) = (c + 1, string.find(substring, i + 1))\n return i", "def find_nth_occurrence(substring, string, occurrence):\n a = string.find(substring)\n while a >= 0 and occurrence > 1:\n a = string.find(substring, a + 1)\n occurrence -= 1\n return a"], "starter_code": "def find_nth_occurrence(substring, string, occurrence=1):\n", "input_output": {"fn_name": "find_nth_occurrence", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5b1d1812b6989d61bd00004f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "find_nth_occurrence", "task_id": "TACO_lite/49", "example": [[["example", "This is an example. Return the nth occurrence of example in this example string.", 1], ["example", "This is an example. Return the nth occurrence of example in this example string.", 2], ["example", "This is an example. Return the nth occurrence of example in this example string.", 3], ["example", "This is an example. Return the nth occurrence of example in this example string.", 4], ["TestTest", "TestTestTestTest", 1], ["TestTest", "TestTestTestTest", 2], ["TestTest", "TestTestTestTest", 3], ["TestTest", "TestTestTestTest", 4]], ["11", "49", "65", "-1", "0", "4", "8", "-1"]]} +{"requirement": "You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.\n\nGiven a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.\n\nExample 1:\n\n\nInput: [2,3,2]\nOutput: 3\nExplanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),\n  because they are adjacent houses.\n\n\nExample 2:\n\n\nInput: [1,2,3,1]\nOutput: 4\nExplanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\n  Total amount you can rob = 1 + 3 = 4.", "solutions": ["def rob(nums):\n if not nums:\n return 0\n if len(nums) == 1:\n return nums[0]\n return max(self.helper(nums[1:]), self.helper(nums[:-1]))\n\ndef helper(nums):\n now = prev = 0\n for nxt in nums:\n (now, prev) = (max(nxt + prev, now), now)\n return now", "def rob(nums):\n if len(nums) == 1:\n return nums[0]\n (last, now) = (0, 0)\n for i in nums[:-1]:\n (last, now) = (now, max(last + i, now))\n ret = now\n (last, now) = (0, 0)\n for i in nums[1:]:\n (last, now) = (now, max(last + i, now))\n return max(ret, now)", "def rob(nums):\n if not nums:\n return 0\n if len(nums) == 1:\n return nums[0]\n if len(nums) <= 3:\n return max(nums)\n\n def rob_line(lst):\n (last, now) = (0, 0)\n for i in lst:\n (last, now) = (now, max(now, last + i))\n return now\n return max(rob_line(nums[:-1]), rob_line(nums[1:]))", "def helper(nums, cache={}):\n if len(nums) == 0:\n return 0\n key = str(nums)\n if key in cache:\n return cache[key]\n cache[key] = max(nums[0] + self.helper(nums[2:]), self.helper(nums[1:]))\n return cache[key]\n\ndef rob(nums):\n if len(nums) == 0:\n return 0\n return max(nums[0] + self.helper(nums[2:-1]), nums[-1] + self.helper(nums[1:-2]), self.helper(nums[1:-1]))", "def rob(nums):\n mem = {}\n\n def max_money(start, rob_first=False):\n if start >= len(nums):\n return 0\n if start == len(nums) - 1 and rob_first:\n return 0\n if (start, rob_first) in mem:\n return mem[start, rob_first]\n if start == 0:\n mem[start, rob_first] = max(max_money(start + 1, False), nums[start] + max_money(start + 2, True))\n else:\n mem[start, rob_first] = max(max_money(start + 1, rob_first), nums[start] + max_money(start + 2, rob_first))\n return mem[start, rob_first]\n return max_money(0)", "def rob(nums):\n if not nums:\n return 0\n ymax = [nums[i] for i in range(len(nums))]\n nmax = [nums[i] for i in range(len(nums))]\n nmax[0] = 0\n if len(nums) > 1:\n ymax[1] = max(ymax[0], ymax[1])\n for i in range(2, len(nums)):\n if i == len(nums) - 1:\n ymax[i] = ymax[i - 1]\n else:\n ymax[i] = max(ymax[i - 1], ymax[i - 2] + ymax[i])\n nmax[i] = max(nmax[i - 1], nmax[i - 2] + nmax[i])\n return max(nmax[-1], ymax[-1])", "def rob(nums):\n if len(nums) == 0:\n return 0\n if len(nums) <= 2:\n return max(nums[0], nums[-1])\n a = [0 for _ in range(len(nums) - 1)]\n b = a.copy()\n c = b.copy()\n a[0] = nums[0]\n b[0] = nums[-1]\n for i in range(1, len(nums) - 1):\n a[i] = max(a[i - 1], a[i - 2] + nums[i])\n b[i] = max(b[i - 1], b[i - 2] + nums[-i - 1])\n return max(a[-1], b[-1])", "def rob_prev(nums):\n n = len(nums)\n if n == 0:\n return 0\n elif n < 3:\n return max(nums)\n mem = [0 for x in range(n + 1)]\n mem[0] = nums[0]\n mem[1] = max(nums[1], nums[0])\n for i in range(2, n):\n mem[i] = max(mem[i - 2] + nums[i], mem[i - 1])\n return mem[n - 1]\n\ndef rob(nums):\n n = len(nums)\n if n == 0:\n return 0\n elif n < 3:\n return max(nums)\n return max(self.rob_prev(nums[1:]), self.rob_prev(nums[:len(nums) - 1]))", "def rob(nums):\n if not nums:\n return 0\n if len(nums) == 1:\n return nums[0]\n\n def helper(nums):\n steal = 0\n cool = 0\n for num in nums:\n (steal, cool) = (cool, max(cool, steal + num))\n return max(steal, cool)\n return max(helper(nums[:-1]), helper(nums[1:]))", "def rob(nums):\n\n def helper(nums):\n if not nums:\n return 0\n dp = [0] * (len(nums) + 1)\n dp[1] = nums[0]\n for i in range(2, len(nums) + 1):\n dp[i] = max(dp[i - 1], nums[i - 1] + dp[i - 2])\n return dp[-1]\n if not nums:\n return 0\n if len(nums) == 1:\n return nums[0]\n return max(helper(nums[:len(nums) - 1]), nums[-1] + helper(nums[1:len(nums) - 2]))", "def rob(nums):\n if not nums:\n return 0\n mark = [0 for i in range(len(nums))]\n result = list(mark)\n if len(nums) == 1:\n return nums[0]\n if len(nums) == 2:\n return max(nums[0], nums[1])\n mark[0] = 1\n result[0] = nums[0]\n if nums[0] > nums[1]:\n mark[1] = 1\n result[1] = nums[0]\n else:\n result[1] = nums[1]\n for i in range(2, len(nums)):\n result[i] = max(nums[i] + result[i - 2], result[i - 1])\n if nums[i] + result[i - 2] > result[i - 1]:\n mark[i] = mark[i - 2]\n else:\n mark[i] = mark[i - 1]\n if mark[0] == 1 and mark[-1] == 1:\n return max(self.solve(nums[1:]), self.solve(nums[:-1]))\n return result[-1]\n\ndef solve(nums):\n if not nums:\n return 0\n if len(nums) == 1:\n return nums[0]\n if len(nums) == 2:\n return max(nums[0], nums[1])\n result = [0 for i in range(len(nums))]\n result[0] = nums[0]\n result[1] = max(nums[0], nums[1])\n for i in range(2, len(nums)):\n result[i] = max(nums[i] + result[i - 2], result[i - 1])\n return result[-1]"], "starter_code": "def rob(nums: List[int]) -> int:\n", "input_output": {"fn_name": "rob", "inputs": [[[2, 3, 2]]], "outputs": [3]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/house-robber-ii/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "rob", "task_id": "TACO_lite/128", "example": [[[[2, 3, 2]], [[1, 2, 3, 1]]], ["3", "4"]]} +{"requirement": "In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the root an, followed by other, which can form another word another.\n\n\n\n\nNow, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.\n\n\n\nYou need to output the sentence after the replacement.\n\n\n\nExample 1:\n\nInput: dict = [\"cat\", \"bat\", \"rat\"]\nsentence = \"the cattle was rattled by the battery\"\nOutput: \"the cat was rat by the bat\"\n\n\n\n\nNote:\n\nThe input will only have lower-case letters.\n 1 \n 1 \n 1 \n 1", "solutions": ["def replacewords(dt, sentence):\n trie = {}\n for w in dt:\n t = trie\n for c in w:\n if c not in t:\n t[c] = {}\n t = t[c]\n t['#'] = w\n return ' '.join([self.replace(i, trie) for i in sentence.split()])\n\ndef replace(word, trie):\n cur = trie\n for letter in word:\n if letter not in cur:\n break\n cur = cur[letter]\n if '#' in cur:\n return cur['#']\n return word\n setenceAsList = sentence.split(' ')\n for i in range(len(setenceAsList)):\n for j in dt:\n if setenceAsList[i].startswith(j):\n setenceAsList[i] = j\n return ' '.join(setenceAsList)\n arrs = sentence.split()\n for i in range(len(arrs)):\n w = arrs[i]\n for j in range(len(arrs[i])):\n cur = w[:j]\n if cur in dt:\n arrs[i] = cur\n break\n return ' '.join(arrs)", "def replacewords(roots, sentence):\n trie = {}\n for w in roots:\n t = trie\n for c in w:\n if c not in t:\n t[c] = {}\n t = t[c]\n t['#'] = True\n return ' '.join([self.replace(i, trie) for i in sentence.split()])\n\ndef replace(word, trie):\n cur = trie\n i = 0\n for letter in word:\n if letter not in cur:\n break\n cur = cur[letter]\n i += 1\n if '#' in cur:\n return word[:i]\n return word", "def replacewords(dict, sentence):\n trie = {}\n for root in dict:\n node = trie\n for letter in root:\n if letter not in node:\n node[letter] = {}\n node = node[letter]\n node['#'] = root\n words = []\n for word in sentence.split():\n node = trie\n for letter in word:\n if letter not in node or '#' in node:\n break\n node = node[letter]\n if '#' in node:\n words.append(node['#'])\n else:\n words.append(word)\n return str.join(' ', words)", "def replacewords(dict, sentence):\n trie_tree = {'root': {}}\n for word in dict:\n parent = trie_tree['root']\n for c in word + '#':\n parent.setdefault(c, {})\n parent = parent[c]\n (sentence, res) = (sentence.split(), [])\n for word in sentence:\n parent = trie_tree['root']\n for (i, c) in enumerate(word + '*'):\n if c not in parent:\n res.append(word)\n break\n parent = parent[c]\n if '#' in parent:\n res.append(word[:i + 1])\n break\n return ' '.join(res)", "def replacewords(dict, sentence):\n sentence = sentence + ' '\n dic = {}\n for i in dict:\n if i[0] not in list(dic.keys()):\n dic[i[0]] = [i]\n else:\n dic[i[0]].append(i)\n res = ''\n while len(sentence) > 0:\n word = sentence[:sentence.index(' ')]\n tmp = ''\n if word[0] in list(dic.keys()):\n for refer in dic[word[0]]:\n if len(refer) < len(word):\n if word[:len(refer)] == refer:\n if tmp == '':\n tmp = refer\n elif len(tmp) > len(refer):\n tmp = refer\n if tmp != '':\n res += tmp + ' '\n else:\n res += word + ' '\n sentence = sentence[sentence.index(' ') + 1:]\n res = res[:-1]\n return res"], "starter_code": "def replacewords(dictionary: List[str], sentence: str) -> str:\n", "input_output": {"fn_name": "replaceWords", "inputs": [[["\"cat\"", "\"bat\"", "\"rat\""], "\"the cattle was rattled by the battery\""]], "outputs": ["\"the cattle was rattled by the battery\""]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Trie", "Array", "String", "Hash Table"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/replace-words/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "replacewords", "task_id": "TACO_lite/208", "example": [[[["cat", "bat", "rat"], "the cattle was rattled by the battery"]], ["the cat was rat by the bat"]]} +{"requirement": "Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer.\n\nModern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.\n\nExample:\n```python\nsolution(1000) # should return 'M'\n```\n\nHelp:\n```\nSymbol Value\nI 1\nV 5\nX 10\nL 50\nC 100\nD 500\nM 1,000\n```\n\nRemember that there can't be more than 3 identical symbols in a row.\n\nMore about roman numerals - http://en.wikipedia.org/wiki/Roman_numerals", "solutions": ["def solution(n):\n roman_numerals = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'}\n roman_string = ''\n for key in sorted(list(roman_numerals.keys()), reverse=True):\n while n >= key:\n roman_string += roman_numerals[key]\n n -= key\n return roman_string", "vals = zip(('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'), (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1))\n\ndef solution(n):\n if n == 0:\n return ''\n return next((c + solution(n - v) for (c, v) in vals if v <= n))", "units = ' I II III IV V VI VII VIII IX'.split(' ')\ntens = ' X XX XXX XL L LX LXX LXXX XC'.split(' ')\nhundreds = ' C CC CCC CD D DC DCC DCCC CM'.split(' ')\nthousands = ' M MM MMM'.split(' ')\n\ndef solution(n):\n return thousands[n // 1000] + hundreds[n % 1000 // 100] + tens[n % 100 // 10] + units[n % 10]", "def solution(n):\n return 'M' * (n // 1000) + hundreds[n % 1000 // 100] + tens[n % 100 // 10] + units[n % 10]", "anums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]\nrnums = 'M CM D CD C XC L XL X IX V IV I'.split()\n\ndef solution(x):\n ret = []\n for (a, r) in zip(anums, rnums):\n (n, x) = divmod(x, a)\n ret.append(r * n)\n return ''.join(ret)", "def solution(n):\n dic = {1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'}\n roman = ''\n for a in reversed(sorted(dic.keys())):\n while a <= n:\n n = n - a\n roman = roman + dic[a]\n return roman", "def solution(n):\n ed = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']\n des = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']\n sot = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']\n tys = ['', 'M', 'MM', 'MMM', 'MMMM']\n return tys[n // 1000] + sot[n // 100 % 10] + des[n // 10 % 10] + ed[n % 10]", "def solution(n):\n ROMAN_SYMBOLS = ['M', 'D', 'C', 'L', 'X', 'V', 'I']\n ROMAN_VALUES = [1000, 500, 100, 50, 10, 5, 1]\n idx = 0\n roman = []\n while n > 0:\n if n < ROMAN_VALUES[idx]:\n idx += 1\n continue\n n -= ROMAN_VALUES[idx]\n roman.append(ROMAN_SYMBOLS[idx])\n if roman[-4:].count(roman[-1]) == 4:\n roman = roman[:-3] + [ROMAN_SYMBOLS[idx - 1]]\n if roman[-3:-2] == roman[-1:]:\n roman = roman[:-3] + [ROMAN_SYMBOLS[idx]] + [ROMAN_SYMBOLS[idx - 2]]\n return ''.join(roman)", "def solution(x):\n table = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]\n for (num, rep) in table:\n if x >= num:\n return rep + solution(x - num)\n return str()"], "starter_code": "def solution(n):\n", "input_output": {"fn_name": "solution", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/51b62bf6a9c58071c600001b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solution", "task_id": "TACO_lite/229", "example": [[[1000]], ["M"]]} +{"requirement": "Given a binary tree, count the number of Single Valued Subtrees. A Single Valued Subtree is one in which all the nodes have same value. \nExample 1\nInput :\n 5\n / \\\n 1 5\n / \\ \\\n 5 5 5\nOutput : 4\nExplanation : \nThere are 4 subtrees with single values. Three leaf nodes and the subtree whose root is the right child of the root. \nExample 2:\nInput:\n 5\n / \\\n 4 5\n / \\ \\\n 4 4 5 \nOutput: 5\nExplanation: \nThere are five subtrees with single values.\nYour task :\nYou don't have to read input or print anything. Your task is to complete the function singlevalued() which takes the root of the tree as input and returns the count of single valued subtrees.\n \nExpected Time Complexity : O(n)\nExpected Auxiliary Space : O(n)\n \nConstraints :\n1 <= n <= 10^5", "solutions": ["def util(root):\n global count\n if root == None:\n return [1, None]\n if root.left == None and root.right == None:\n count += 1\n return [1, root.data]\n l = self.util(root.left)\n r = self.util(root.right)\n if l[0] == 1 and r[0] == 1:\n if l[1] == None and r[1] == None:\n return [1, root.data]\n elif l[1] == None and r[1] == root.data:\n count += 1\n return [1, root.data]\n elif r[1] == None and l[1] == root.data:\n count += 1\n return [1, root.data]\n elif l[1] == r[1] and l[1] == root.data:\n count += 1\n return [1, root.data]\n else:\n return [0, root.data]\n else:\n return [0, root.data]\n\ndef singlevalued(root):\n global count\n count = 0\n self.util(root)\n return count", "def singlevalued(root):\n c = [0] * 1\n\n def fun(root):\n if root == None:\n return True\n l = fun(root.left)\n r = fun(root.right)\n cur = root.data\n if root.left:\n left = root.left.data\n else:\n left = cur\n if root.right:\n right = root.right.data\n else:\n right = cur\n if cur == left and cur == right and l and r:\n c[0] += 1\n return True\n return False\n fun(root)\n return c[0]", "def singlevalued(root):\n count = [0]\n\n def answer(root):\n if root == None:\n return set()\n lset = answer(root.left)\n rset = answer(root.right)\n lset.add(root.data)\n lset.update(rset)\n if len(lset) == 1:\n count[0] += 1\n return lset\n answer(root)\n return count[0]", "def postOrder(root, count):\n if root is None:\n return True\n left = self.postOrder(root.left, count)\n right = self.postOrder(root.right, count)\n if left == False or right == False:\n return False\n if root.left and root.data != root.left.data or (root.right and root.data != root.right.data):\n return False\n count[0] += 1\n return True\n\ndef singlevalued(root):\n count = [0]\n self.postOrder(root, count)\n return count[0]", "def solve(root):\n if root == None:\n return True\n l = self.solve(root.left)\n r = self.solve(root.right)\n cur = root.data\n if root.left:\n left = root.left.data\n else:\n left = cur\n if root.right:\n right = root.right.data\n else:\n right = cur\n if cur == left and cur == right and l and r:\n self.count += 1\n return True\n return False\n\ndef singlevalued(root):\n self.count = 0\n self.s = set()\n self.solve(root)\n return self.count", "def finder(root):\n if root == None:\n return 1\n lef = self.finder(root.left)\n righ = self.finder(root.right)\n if lef == False or righ == False:\n return 0\n if root.left != None and root.data != root.left.data:\n return 0\n if root.right != None and root.data != root.right.data:\n return 0\n self.c += 1\n return 1\n\ndef singlevalued(root):\n self.finder(root)\n return self.c", "def singlevalued(root):\n self.ans = 0\n\n def dfs(node):\n if not node.left and (not node.right):\n self.ans += 1\n return node.data\n if node.left and node.right:\n left = dfs(node.left)\n right = dfs(node.right)\n if node.data == left and node.data == right:\n self.ans += 1\n return node.data\n elif node.left:\n left = dfs(node.left)\n if node.data == left:\n self.ans += 1\n return node.data\n elif node.right:\n right = dfs(node.right)\n if node.data == right:\n self.ans += 1\n return node.data\n return float('inf')\n dfs(root)\n return self.ans", "def singlevalued(root):\n c = 0\n\n def check(n):\n nonlocal c\n if n.left == None and n.right == None:\n c += 1\n return True\n if n.left != None:\n l = check(n.left)\n else:\n l = True\n if n.right != None:\n r = check(n.right)\n else:\n r = True\n if l == True and r == True:\n if n.left != None and n.right != None:\n if n.data == n.left.data and n.data == n.right.data:\n c += 1\n return True\n if n.data != n.left.data or n.data != n.right.data:\n return False\n if n.left == None and n.right != None:\n if n.data == n.right.data:\n c += 1\n return True\n else:\n return False\n if n.left != None and n.right == None:\n if n.data == n.left.data:\n c += 1\n return True\n else:\n return False\n check(root)\n return c", "def findSingleValued(root, count):\n if root == None:\n return True\n if root.left == None and root.right == None:\n count[0] += 1\n return True\n left = 1\n right = 1\n if root.left:\n left = self.findSingleValued(root.left, count)\n if root.right:\n right = self.findSingleValued(root.right, count)\n if left and right:\n temp = []\n temp.append(root.data)\n if root.left:\n temp.append(root.left.data)\n if root.right:\n temp.append(root.right.data)\n first = temp[0]\n for i in range(1, len(temp)):\n if temp[i] != first:\n return False\n count[0] += 1\n return True\n return False\n\ndef singlevalued(root):\n count = [0]\n self.findSingleValued(root, count)\n return count[0]", "def singlevalued(root):\n\n def check(root):\n if root.left == None and root.right == None:\n return True\n if root.left:\n if root.right:\n if root.data == root.left.data and root.data == root.right.data:\n return check(root.right) and check(root.left)\n else:\n return False\n elif root.data == root.left.data:\n return check(root.left)\n else:\n return False\n elif root.right:\n if root.left == None:\n if root.data == root.right.data:\n return check(root.right)\n else:\n return False\n\n def traverse(root):\n if check(root):\n c[0] += 1\n if root == None:\n return\n if root.left:\n traverse(root.left)\n if root.right:\n traverse(root.right)\n c = [0]\n traverse(root)\n return c[0]", "def check(root):\n if root is None:\n return True\n lhs = self.check(root.left)\n rhs = self.check(root.right)\n if lhs and rhs:\n if root.left is not None and root.left.data != root.data:\n return False\n if root.right is not None and root.right.data != root.data:\n return False\n self.ans = self.ans + 1\n return True\n return False\n\ndef singlevalued(root):\n self.check(root)\n return self.ans", "def singlevalued(root):\n self.ans = 0\n\n def solve(root):\n if root == None:\n return True\n l = solve(root.left)\n r = solve(root.right)\n if l == False or r == False:\n return False\n elif root.left and root.left.data != root.data:\n return False\n elif root.right and root.right.data != root.data:\n return False\n else:\n self.ans += 1\n return True\n val = solve(root)\n return self.ans", "def Postorder(root, dict):\n if root == None:\n return 0\n l = self.Postorder(root.left, dict)\n r = self.Postorder(root.right, dict)\n if root.left == None and root.right == None:\n if root.data not in dict:\n dict[root.data] = 1\n else:\n dict[root.data] += 1\n return root.data\n if l != 0 and r != 0:\n if l == r and l == root.data:\n if root.data not in dict:\n dict[root.data] = 1\n else:\n dict[root.data] += 1\n return root.data\n elif l != 0:\n if l == root.data:\n if root.data not in dict:\n dict[root.data] = 1\n else:\n dict[root.data] += 1\n return root.data\n elif r != 0:\n if r == root.data:\n if root.data not in dict:\n dict[root.data] = 1\n else:\n dict[root.data] += 1\n return root.data\n return -1\n\ndef singlevalued(root):\n dict = {}\n self.Postorder(root, dict)\n ans = 0\n for key in dict:\n ans += dict[key]\n return ans", "def singlevalued(root):\n count = 0\n\n def f(root):\n if not root:\n return (True, 0)\n if root:\n if root.left and root.right:\n (left, total_l) = f(root.left)\n (right, total_r) = f(root.right)\n if root.data == root.left.data and root.data == root.right.data and left and right:\n return (True, 1 + total_l + total_r)\n else:\n return (False, total_l + total_r)\n elif root.left and (not root.right):\n (left, total_l) = f(root.left)\n if root.data == root.left.data and left:\n return (True, 1 + total_l)\n else:\n return (False, total_l)\n elif not root.left and root.right:\n (right, total_r) = f(root.right)\n if root.data == root.right.data and right:\n return (True, 1 + total_r)\n else:\n return (False, total_r)\n elif not root.left and (not root.right):\n return (True, 1)\n return f(root)[1]", "def solve(root, res):\n if root.left is None and root.right is None:\n return (root.data, res + 1)\n (left, right) = (root.data, root.data)\n if root.left:\n (left, res) = self.solve(root.left, res)\n if root.right:\n (right, res) = self.solve(root.right, res)\n if left == right and left == root.data:\n return (root.data, res + 1)\n return (-1, res)\n\ndef singlevalued(root):\n return self.solve(root, 0)[1]", "def singlevalued(root):\n self.ans = 0\n self.helper(root)\n return self.ans\n\ndef helper(root):\n if root == None:\n return True\n left = self.helper(root.left)\n right = self.helper(root.right)\n if left and right:\n if root.left != None and root.left.data != root.data:\n return False\n if root.right != None and root.right.data != root.data:\n return False\n self.ans += 1\n return True\n return False", "def singlevalued(root):\n\n def f(root, ans):\n if not root:\n return -1\n if not root.left and (not root.right):\n ans[0] += 1\n return root.data\n l = f(root.left, ans)\n r = f(root.right, ans)\n if l == root.data and r == root.data or (l == -1 and r == root.data) or (r == -1 and l == root.data):\n ans[0] += 1\n return root.data\n return 0\n ans = [0]\n res = f(root, ans)\n return ans[0]", "def singlevalued(root):\n return self.helper(root)[1]\n\ndef helper(root):\n if root is None:\n return ([], 0)\n (left, l_count) = self.helper(root.left)\n (right, r_count) = self.helper(root.right)\n current = (left == [] or left == [root.data]) and (right == [] or right == [root.data])\n count = l_count + r_count + current\n nodes = left + right + [root.data]\n if current:\n nodes = [root.data]\n return (nodes, count)", "g = None\n\ndef f(p):\n global g\n pass\n ok = True\n l = p.left\n r = p.right\n if l:\n ok = f(l) and l.data == p.data and ok\n if r:\n ok = f(r) and r.data == p.data and ok\n if ok:\n g += 1\n return ok\n\ndef singlevalued(root):\n global g\n if not root:\n return 0\n g = 0\n f(root)\n return g", "def singlevalued(root):\n\n def helper(root, count):\n if root is None:\n return True\n leftSide = helper(root.left, count)\n rightSide = helper(root.right, count)\n if leftSide and rightSide and (True if root.left is None else root.left.data == root.data) and (True if root.right is None else root.right.data == root.data):\n count[0] += 1\n return True\n else:\n return False\n count = [0]\n helper(root, count)\n return count[0]", "def singlevalued(root):\n c = [0]\n\n def solve(root):\n if root == None:\n return (0, True)\n if not root.left and (not root.right):\n c[0] += 1\n return (root.data, True)\n (data1, bool1) = solve(root.left)\n (data2, bool2) = solve(root.right)\n if (root.data == data1 and root.data == data2 or (data1 == 0 and root.data == data2) or (root.data == data1 and data2 == 0)) and (bool1 and bool2):\n c[0] += 1\n return (root.data, bool1 and bool2)\n else:\n return (-1, False)\n (v, v1) = solve(root)\n return c[0]", "def singlevalued(root):\n count = [0]\n\n def value(root):\n if not root:\n return (0, True)\n if not root.left and (not root.right):\n count[0] += 1\n return (root.data, True)\n (data1, boo1) = value(root.left)\n (data2, boo2) = value(root.right)\n if (root.data == data1 and root.data == data2 or (data1 == 0 and root.data == data2 or (root.data == data1 and data2 == 0))) and (boo1 and boo2):\n count[0] += 1\n return (root.data, boo1 and boo2)\n else:\n return (-1, False)\n (v, v1) = value(root)\n return count[0]", "def singlevalued(root):\n self.count = 0\n\n def solve(root):\n if root == None:\n return 0\n if root.left == None and root.right == None:\n self.count += 1\n return True\n l = solve(root.left)\n r = solve(root.right)\n if l and r:\n if root.data == root.left.data and root.data == root.right.data:\n self.count += 1\n return True\n else:\n return False\n elif root.left == None and root.right != None:\n if r == True:\n if root.data == root.right.data:\n self.count += 1\n return True\n elif root.right == None and root.left != None:\n if l == True:\n if root.data == root.left.data:\n self.count += 1\n return True\n else:\n return False\n solve(root)\n return self.count", "def singlevalued(root):\n (bol, val, ct) = self.recursive(root)\n return ct\n\ndef recursive(root):\n if root is None:\n return (True, None, 0)\n (rt_bool, rt_val, rt_ct) = self.recursive(root.right)\n (lt_bool, lt_val, lt_ct) = self.recursive(root.left)\n if (rt_bool and lt_bool) and (rt_val is None or rt_val == root.data) and (lt_val is None or lt_val == root.data):\n return (True, root.data, lt_ct + rt_ct + 1)\n else:\n return (False, root.data, lt_ct + rt_ct)", "from collections import namedtuple\nResult = namedtuple('Result', 'valid,cnt')\n\ndef dfs(n, ans):\n if not n:\n return True\n l = dfs(n.left, ans)\n r = dfs(n.right, ans)\n if not l or not r:\n return False\n if n.left and n.left.data != n.data:\n return False\n if n.right and n.right.data != n.data:\n return False\n ans[0] += 1\n return True\n\ndef singlevalued(root):\n ans = [0]\n dfs(root, ans)\n return ans[0]", "def singlevalued(root):\n self.dfs(root)\n return self.count\n\ndef dfs(root):\n if root:\n a = self.dfs(root.left)\n b = self.dfs(root.right)\n if a == -1 and b == -1 or (a == -1 and b == root.data) or (b == -1 and a == root.data):\n self.count += 1\n return root.data\n if a == b == root.data:\n self.count += 1\n return root.data\n return float('-inf')\n return -1", "def checkSingle(root):\n if root == None:\n return True\n rightBool = self.checkSingle(root.right)\n leftBool = self.checkSingle(root.left)\n if leftBool is False or rightBool is False:\n return False\n if root.right != None and root.right.data != root.data:\n return False\n if root.left != None and root.left.data != root.data:\n return False\n self.count += 1\n return True\n\ndef singlevalued(root):\n self.checkSingle(root)\n return self.count", "def singlevalued(root):\n global cnt\n cnt = 0\n self.traverse(root)\n return cnt\n\ndef traverse(root):\n global cnt\n if not root:\n return False\n if not root.right and (not root.left):\n cnt += 1\n return True\n x = self.traverse(root.left)\n y = self.traverse(root.right)\n if x and y:\n if root.right.data == root.data and root.left.data == root.data:\n cnt += 1\n return True\n elif root.left is None:\n if y and root.right.data == root.data:\n cnt += 1\n return True\n elif root.right is None:\n if x and root.left.data == root.data:\n cnt += 1\n return True\n return False", "def singlevalued(root):\n global cnt\n cnt = 0\n list = self.traverse(root)\n if len(set(list)) == 1:\n cnt += 1\n return cnt\n\ndef traverse(root):\n global cnt\n if not root:\n return []\n x = self.traverse(root.left)\n y = self.traverse(root.right)\n if x and x[0] != -1 and (len(set(x)) == 1):\n cnt += 1\n x = [x[0]]\n elif x:\n x = [-1]\n if y and y[0] != -1 and (len(set(y)) == 1):\n cnt += 1\n y = [y[0]]\n elif y:\n y = [-1]\n return [root.data] + x + y", "def getCounts(node):\n if node is None:\n return (None, 0)\n (val1, cnt1) = self.getCounts(node.left)\n (val2, cnt2) = self.getCounts(node.right)\n cnt = cnt1 + cnt2\n if (val1 is None or val1 == node.data) and (val2 is None or val2 == node.data):\n cnt += 1\n return (node.data, cnt)\n return (False, cnt)\n\ndef singlevalued(root):\n (_, cnt) = self.getCounts(root)\n return cnt", "def singlevalued(root):\n singleValue = [0]\n\n def Walker(node: Node):\n if node.data is None:\n return float('inf')\n if node.left is not None:\n left = Walker(node.left)\n else:\n left = node.data\n if node.right is not None:\n right = Walker(node.right)\n else:\n right = node.data\n if node.data == left == right:\n singleValue[0] = singleValue[0] + 1\n return node.data\n return float('inf')\n Walker(root)\n return singleValue[0]", "def singlevalued(root):\n\n def traversal(root):\n nonlocal count\n if root == None:\n return None\n if root.left:\n traversal(root.left)\n if root.right:\n traversal(root.right)\n if root.left and root.right:\n if root.left.data == root.right.data == root.data:\n count += 1\n elif root.left.data == root.right.data and root.left.data != root.data:\n root.data = -9999999\n elif root.left.data != root.data:\n root.data = root.left.data\n elif root.left:\n if root.left.data == root.data:\n count += 1\n else:\n root.data = -999999999\n elif root.right:\n if root.right.data == root.data:\n count += 1\n else:\n root.data = -11111111\n elif root.left == None and root.right == None:\n count += 1\n count = 0\n traversal(root)\n return count", "def solve(node, ans):\n if node is None:\n return (True, 'x')\n left = solve(node.left, ans)\n right = solve(node.right, ans)\n if (left[0] and right[0]) and (left[1] == 'x' or left[1] == node.data) and (right[1] == 'x' or right[1] == node.data):\n ans[0] += 1\n return (True, node.data)\n return (False, node.data)\n\ndef singlevalued(root):\n ans = [0]\n solve(root, ans)\n return ans[0]", "def helper(root, count):\n if not root:\n return True\n left = self.helper(root.left, count)\n right = self.helper(root.right, count)\n if left == False or right == False:\n return False\n if root.left and root.data != root.left.data:\n return False\n if root.right and root.data != root.right.data:\n return False\n count[0] += 1\n return True\n\ndef singlevalued(root):\n count = [0]\n self.helper(root, count)\n return count[0]", "def helper(root):\n if not root.left and (not root.right):\n self.count += 1\n return (True, root.data)\n (rflag, rval, lflag, lval) = (True, root.data, True, root.data)\n if root.left:\n (lflag, lval) = self.helper(root.left)\n if root.right:\n (rflag, rval) = self.helper(root.right)\n if lflag and rflag and (lval == rval) and (root.data == lval) and (root.data == rval):\n self.count += 1\n return (True, root.data)\n return (False, root.data)\n\ndef singlevalued(root):\n self.count = 0\n self.helper(root)\n return self.count", "import sys\n\ndef dfs(root, c):\n if root is None:\n return True\n left = self.dfs(root.left, c)\n right = self.dfs(root.right, c)\n if left == False or right == False:\n return False\n if root.left and root.data != root.left.data:\n return False\n if root.right and root.data != root.right.data:\n return False\n c[0] += 1\n return True\n\ndef singlevalued(root):\n c = [0]\n self.dfs(root, c)\n return c[0]", "def singlevalued(root):\n count = [0]\n\n def traverse(root, count):\n if not root:\n return True\n l_tree = traverse(root.left, count)\n r_tree = traverse(root.right, count)\n if l_tree == False or r_tree == False:\n return False\n if root.left and root.data != root.left.data or (root.right and root.data != root.right.data):\n return False\n count[0] += 1\n return True\n traverse(root, count)\n return count[0]", "def singlevalued(root):\n s = 0\n nodes = [[root, 0, True]]\n while len(nodes) > 0:\n (node, status, isSVST) = nodes[-1]\n if status == 0:\n if node.left is not None:\n nodes[-1][1] = 1\n nodes[-1][2] = node.data == node.left.data\n nodes.append([node.left, 0, True])\n elif node.right is not None:\n nodes[-1][1] = 2\n nodes[-1][2] = isSVST and node.data == node.right.data\n nodes.append([node.right, 0, True])\n else:\n s += 1\n nodes.pop()\n elif status == 2 or (status == 1 and node.right is None):\n if isSVST:\n s += 1\n nodes.pop()\n if len(nodes) > 0:\n nodes[-1][2] = isSVST and nodes[-1][2]\n else:\n nodes[-1][1] = 2\n nodes[-1][2] = isSVST and node.data == node.right.data\n nodes.append([node.right, 0, True])\n return s", "def postord(root, cnt):\n if root != None:\n (lft, cnt) = self.postord(root.left, cnt)\n (rght, cnt) = self.postord(root.right, cnt)\n if lft != 'T' or rght != 'T':\n return ('F', cnt)\n if root.left != None and root.left.data != root.data:\n return ('F', cnt)\n if root.right != None and root.right.data != root.data:\n return ('F', cnt)\n cnt += 1\n return ('T', cnt)\n else:\n return ('T', cnt)\n\ndef singlevalued(root):\n cnt = 0\n if root != None:\n (value, cnt) = self.postord(root, cnt)\n return cnt", "def singlevalued(root):\n res = 0\n\n def helper(node):\n nonlocal res\n if not node:\n return None\n left = helper(node.left)\n right = helper(node.right)\n if not node.left and (not node.right):\n res += 1\n return node.data\n elif not node.left and right == node.data:\n res += 1\n return node.data\n elif not node.right and left == node.data:\n res += 1\n return node.data\n elif node.left and node.right and (left == right == node.data):\n res += 1\n return node.data\n return None\n helper(root)\n return res", "def __init__(val):\n self.right = None\n self.data = val\n self.left = None\n\ndef countSingleRec(root, count):\n if root is None:\n return True\n left = self.countSingleRec(root.left, count)\n right = self.countSingleRec(root.right, count)\n if left == False or right == False:\n return False\n if root.left and root.data != root.left.data:\n return False\n if root.right and root.data != root.right.data:\n return False\n count[0] += 1\n return True\n\ndef singlevalued(root):\n count = [0]\n self.countSingleRec(root, count)\n return count[0]", "def f(temp, ans):\n if temp is None:\n return True\n a = f(temp.left, ans)\n b = f(temp.right, ans)\n if a and b:\n if temp.left is not None and temp.left.data != temp.data:\n return False\n if temp.right is not None and temp.right.data != temp.data:\n return False\n ans[0] += 1\n return True\n return False\n\ndef singlevalued(root):\n ans = [0]\n f(root, ans)\n return ans[0]", "import math\n\ndef solve(root):\n left = root.data\n if root.left:\n left = self.solve(root.left)\n right = root.data\n if root.right:\n right = self.solve(root.right)\n if left == right == root.data:\n self.ans += 1\n return root.data\n return None\n\ndef singlevalued(root):\n self.ans = 0\n self.solve(root)\n return self.ans", "def singlevalued(root):\n cnt = 0\n\n def sol(root):\n nonlocal cnt\n if not root:\n return True\n lf = sol(root.left)\n rf = sol(root.right)\n if lf and rf:\n x = root.left is None or root.left.data == root.data\n y = root.right is None or root.right.data == root.data\n if x and y:\n cnt += 1\n return True\n return False\n sol(root)\n return cnt", "def __init__():\n self.res = 0\n\ndef singlevalued(root):\n self.dfs(root)\n return self.res\n\ndef dfs(node):\n l = self.dfs(node.left) if node.left else node.data\n r = self.dfs(node.right) if node.right else node.data\n if l == r and l == node.data:\n self.res += 1\n return l\n else:\n return -1", "def singlevalued(root):\n\n def tree(root):\n if not root:\n return True\n l = tree(root.left)\n r = tree(root.right)\n if l == False or r == False:\n return False\n if root.left != None and root.data != root.left.data:\n return False\n if root.right != None and root.data != root.right.data:\n return False\n self.a += 1\n return True\n tree(root)\n return self.a", "def singlevalued(root):\n res = 0\n\n def recur(root):\n nonlocal res\n if not root:\n return set()\n cur = recur(root.left)\n cur.update(recur(root.right))\n cur.add(root.data)\n if len(cur) < 2:\n res += 1\n return cur\n recur(root)\n return res", "def singlevalued(root):\n dp = {'count': 0}\n\n def dfs(node):\n if not node:\n return True\n if node:\n if not node.left and (not node.right):\n dp['count'] += 1\n return True\n l = dfs(node.left)\n r = dfs(node.right)\n if l and r:\n if node.left and node.right:\n left = node.left.data\n right = node.right.data\n if left == right and right == node.data:\n dp['count'] += 1\n return True\n else:\n return False\n if node.right:\n if node.right.data == node.data:\n dp['count'] += 1\n return True\n else:\n return False\n if node.left:\n if node.left.data == node.data:\n dp['count'] += 1\n return True\n else:\n return False\n return False\n dfs(root)\n return dp['count']", "from sys import setrecursionlimit\nsetrecursionlimit(100000)\n\ndef singlevalued(root):\n ans = [0]\n\n def recur(node):\n if node is None:\n return True\n left = recur(node.left)\n right = recur(node.right)\n if left and right and (node.left is None or node.left.data == node.data) and (node.right is None or node.right.data == node.data):\n ans[0] += 1\n return True\n return False\n recur(root)\n return ans[0]", "def singlevalued(root):\n count = 0\n\n def helper(root, count):\n if root is None:\n return (True, count)\n (left, count) = helper(root.left, count)\n (right, count) = helper(root.right, count)\n if left == False or right == False:\n return (False, count)\n if root.left and root.data != root.left.data:\n return (False, count)\n if root.right and root.data != root.right.data:\n return (False, count)\n count += 1\n return (True, count)\n (x, y) = helper(root, count)\n return y", "def singlevalued(root):\n count = 0\n\n def solve(root):\n nonlocal count\n if root == None:\n return True\n l = solve(root.left)\n r = solve(root.right)\n if l and r:\n if (root.left == None or root.left.data == root.data) and (root.right == None or root.right.data == root.data):\n count += 1\n return True\n return False\n solve(root)\n return count", "def singlevalued(root):\n\n def postorder(root):\n if root is None:\n return True\n left = postorder(root.left)\n right = postorder(root.right)\n if left and right:\n if root.left is not None and root.left.data != root.data:\n return False\n if root.right is not None and root.right.data != root.data:\n return False\n self.count += 1\n return True\n return False\n self.count = 0\n postorder(root)\n return self.count", "def singlevalued(root):\n\n def dfs(root):\n if not root:\n return 0\n if not root.left and (not root.right):\n self.count += 1\n return root.data\n left = dfs(root.left)\n right = dfs(root.right)\n if (root.data == left or root.left == None) and (root.data == right or root.right == None):\n self.count += 1\n return root.data\n return -1\n self.count = 0\n dfs(root)\n return self.count\n count = 0\n countSingleValued(root, count)\n return count", "def singlevalued(root):\n\n def soln(node):\n if not node:\n return ('#', True)\n (l, fl) = soln(node.left)\n (r, fr) = soln(node.right)\n if not (fl and fr):\n return (l, False)\n if l == '#':\n l = node.data\n if r == '#':\n r = node.data\n if l == r == node.data:\n soln.res += 1\n return (node.data, True)\n return (l, False)\n soln.res = 0\n soln(root)\n return soln.res", "def singlevalued(root):\n self.ans = 0\n\n def dfs(root):\n if root == None:\n return True\n left = dfs(root.left)\n right = dfs(root.right)\n if left and right:\n if root.left and root.left.data != root.data or (root.right and root.right.data != root.data):\n return False\n else:\n self.ans += 1\n return True\n return False\n dfs(root)\n return self.ans"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["5\r\n / \\\r\n 1 5\r\n / \\ \\\r\n 5 5 5", "5\r\n / \\\r\n 4 5\r\n / \\ \\\r\n 4 4 5"], "outputs": ["4", "5"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/single-valued-subtree/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "__init__", "task_id": "TACO_lite/111", "example": [[[5, [1, 5, 5, 5, 5]], [5, [4, 5, 4, 4, 5]]], ["4", "5"]]} +{"requirement": "Given a number N find the sum of the Euler Totient values of all the divisors of N.\n \nExample 1:\nInput:\nN = 5\nOutput:\n5\nExplanation:\n1 and 5 are the factor \nof 5 and Φ(1) = 1 and\nΦ(5) = 4 and their sum\nis 4 + 1 = 5\nExample 2:\nInput:\nN = 1\nOutput:\n1\nExplanation:\n1 is the only factor of\n1 and Φ(1) = 1\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function phiSum() which takes an integer N as input parameter and returns an integer, sum of the Euler Totient values of all the divisors of N.\n \nExpected Time Complexity: O(1)\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= N <= 10^{6}", "solutions": ["def phisum(N):\n return N", "import math\n\ndef phisum(n):\n return n"], "starter_code": "def phisum (N):\n", "input_output": {"inputs": ["N = 5", "N = 1"], "outputs": ["5", "1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/euler-totient-sum-and-divisors5501/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "phisum", "task_id": "TACO_lite/223", "example": [[[5], [1]], ["5", "1"]]} +{"requirement": "Given an array A[] of N positive integers and two positive integers K_{1} and K_{2}. Find the sum of all elements between K_{1}^{th} and K_{2}^{th} smallest elements of the array. It may be assumed that (1 <= k1 < k2 <= n).\n \nExample 1:\nInput:\nN = 7\nA[] = {20, 8, 22, 4, 12, 10, 14}\nK1 = 3, K2 = 6\nOutput:\n26\nExplanation:\n3rd smallest element is 10\n6th smallest element is 20\nElement between 10 and 20 \n12,14. Their sum = 26.\n \nExample 2:\nInput\nN = 6\nA[] = {10, 2, 50, 12, 48, 13}\nK1= 2, K2 = 6\nOutput:\n73\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function sumBetweenTwoKth() which takes the array A[], its size N and two integers K1 and K2 as inputs and returns the sum of all the elements between K_{1}^{th} and K_{2}^{th} smallest elements.\n \nExpected Time Complexity: O(N. log(N))\nExpected Auxiliary Space: O(N)\n \nConstraints:\n1 ≤ N ≤ 10^{5}\n1 ≤ K_{1}, K_{2} ≤ 10^{9}", "solutions": ["def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n d = [x for x in A if x > A[K1 - 1] and x < A[K2 - 1]]\n return sum(d)", "import heapq\n\ndef sumbetweentwokth(A, N, k1, k2):\n x = []\n y = []\n heapq.heapify(x)\n heapq.heapify(y)\n for i in range(N):\n heapq.heappush(x, -A[i])\n heapq.heappush(y, -A[i])\n if len(x) > k1:\n heapq.heappop(x)\n if len(y) > k2:\n heapq.heappop(y)\n a1 = -heapq.heappop(x)\n a2 = -heapq.heappop(y)\n if a2 > a1:\n (a1, a2) = (a2, a1)\n c = 0\n for i in range(N):\n if A[i] < a1 and A[i] > a2:\n c += A[i]\n return c", "import heapq as h\n\ndef sumbetweentwokth(A, N, K1, K2):\n maxheap = []\n k1small = 0\n k2small = 0\n summ = 0\n for i in range(0, N):\n if len(maxheap) < K1:\n h.heappush(maxheap, -A[i])\n elif A[i] < -maxheap[0]:\n h.heappop(maxheap)\n h.heappush(maxheap, -A[i])\n k1small = -maxheap[0]\n maxheap = []\n for i in range(0, N):\n if len(maxheap) < K2:\n h.heappush(maxheap, -A[i])\n elif A[i] < -maxheap[0]:\n h.heappop(maxheap)\n h.heappush(maxheap, -A[i])\n k2small = -maxheap[0]\n if k1small > k2small:\n (k1small, k2small) = (k2small, k1small)\n for i in range(0, N):\n if A[i] > k1small and A[i] < k2small:\n summ = summ + A[i]\n return summ", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n l = A[K1:K2 - 1]\n return sum(l)", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n\n def findKthSmallest(arr, k):\n max_heap = []\n for i in arr:\n heapq.heappush(max_heap, -1 * i)\n if len(max_heap) > k:\n heapq.heappop(max_heap)\n return -1 * heapq.heappop(max_heap)\n min_val = findKthSmallest(A, K1)\n max_val = findKthSmallest(A, K2)\n res = 0\n for ele in A:\n if ele > min_val and ele < max_val:\n res += ele\n return res", "def sumbetweentwokth(A, N, K1, K2):\n A = sorted(A)\n s = sum(A[K1:K2 - 1])\n return s", "def suma(x):\n a = len(x)\n s = 0\n for i in range(a):\n s += x[i]\n return s\n\ndef sumbetweentwokth(A, N, K1, K2):\n A.sort()\n a = suma(A[K1:])\n b = suma(A[K2 - 1:])\n return a - b", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n new = A[K1 - 1:K2 - 1]\n return sum(new) - new[0]", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n a = []\n s = 0\n for i in range(K1, K2 - 1):\n a.append(A[i])\n for i in a:\n s += i\n return s", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n sum = 0\n for i in range(K1, K2 - 1):\n sum += A[i]\n return sum", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n ans = []\n heapq.heapify(ans)\n for i in range(N):\n heapq.heappush(ans, -1 * A[i])\n if len(ans) >= K2:\n heapq.heappop(ans)\n sm = 0\n while len(ans) > K1:\n sm += heapq.heappop(ans) * -1\n return sm", "def sumbetweentwokth(A, N, K1, K2):\n\n def get_ele(arr, k):\n import heapq\n heap = []\n for i in range(0, len(arr)):\n heapq.heappush(heap, -arr[i])\n if len(heap) > k:\n heapq.heappop(heap)\n return -heap[0]\n y = get_ele(A, K1)\n x = get_ele(A, K2)\n summ = 0\n for i in range(0, N):\n if A[i] > y and A[i] < x:\n summ += A[i]\n return summ", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n sumi = 0\n for i in range(N):\n if i > K1 - 1 and i < K2 - 1:\n sumi += A[i]\n return sumi", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n sm = 0\n x1 = self.min_values(A, N, K1)\n x2 = self.min_values(A, N, K2)\n for i in range(N):\n if x1 < A[i] < x2:\n sm += A[i]\n return sm\n\ndef min_values(A, N, K):\n minh = []\n heapq.heapify(minh)\n for i in range(N):\n heapq.heappush(minh, A[i] * -1)\n if len(minh) > K:\n heapq.heappop(minh)\n return minh[0] * -1", "import heapq\n\ndef sumbetweentwokth(arr, n, k1, k2):\n heapq.heapify(arr)\n l = arr.copy()\n s1 = 0\n s2 = 0\n for i in range(0, k1):\n s1 += heapq.heappop(l)\n l = arr.copy()\n for i in range(1, k2):\n s2 += heapq.heappop(l)\n total_sum = s2 - s1\n return total_sum", "import heapq\n\ndef sumbetweentwokth(arr, N, K1, K2):\n heapq.heapify(arr)\n l = arr.copy()\n s1 = 0\n s2 = 0\n for i in range(0, K1):\n s1 += heapq.heappop(l)\n l = arr.copy()\n for i in range(1, K2):\n s2 += heapq.heappop(l)\n s3 = s2 - s1\n return s3", "def sumbetweentwokth(A, N, K1, K2):\n res = sorted(A)\n l = []\n ind1 = res.index(res[K1 - 1])\n ind2 = res.index(res[K2 - 1])\n for i in range(ind1 + 1, ind2):\n l.append(res[i])\n return sum(l)", "import sys\nfrom heapq import *\n\ndef sumbetweentwokth(A, N, K1, K2):\n heap1 = [-sys.maxsize] * K1\n heap2 = [-sys.maxsize] * K2\n heapify(heap1)\n heapify(heap2)\n for num in A:\n if num < -heap1[0]:\n heappop(heap1)\n heappush(heap1, -num)\n if num < -heap2[0]:\n heappop(heap2)\n heappush(heap2, -num)\n heappop(heap2)\n ans = -sum(heap2) - -sum(heap1)\n return ans", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n c = A[K1 - 1]\n d = A[K2 - 1]\n lst = []\n for i in range(N):\n if A[i] > c and A[i] < d:\n lst.append(A[i])\n ans = sum(lst)\n return ans", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n m = A[K1 - 1]\n n = A[K2 - 1]\n s = 0\n for i in A:\n if i > m and i < n:\n s = s + i\n return s", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n lst = []\n for i in A:\n if i > A[K1 - 1] and i < A[K2 - 1]:\n lst.append(i)\n s = sum(lst)\n return s", "import heapq\n\ndef sumbetweentwokth(array, N, k1, k2):\n\n def findKthLargest(k):\n heap = []\n for num in array:\n if len(heap) < k:\n heapq.heappush(heap, -1 * num)\n elif -num > heap[0]:\n heapq.heappop(heap)\n heapq.heappush(heap, -1 * num)\n return heap[0] * -1\n num1 = findKthLargest(k1)\n num2 = findKthLargest(k2)\n ans = 0\n for num in array:\n if num > num1 and num < num2:\n ans += num\n return ans", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n i = A[K1 - 1]\n j = A[K2 - 1]\n sum = 0\n for m in A:\n if m > i and m < j:\n sum = sum + m\n return sum", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n\n def kthSmallest(a, k):\n maxh = []\n for i in range(len(a)):\n heapq.heappush(maxh, -a[i])\n if len(maxh) > k:\n heapq.heappop(maxh)\n return -maxh[0]\n ax = kthSmallest(A, K1)\n by = kthSmallest(A, K2)\n ans = 0\n for i in range(N):\n if A[i] > ax and A[i] < by:\n ans += A[i]\n return ans", "from heapq import heapify, heappush, heappop\n\ndef sumbetweentwokth(A, N, K1, K2):\n sum = 0\n new = [-1 * x for x in A]\n heapify(new)\n while N > K2 - 1:\n heappop(new)\n N -= 1\n while N > K1:\n sum += -1 * heappop(new)\n N -= 1\n return sum", "import heapq\n\ndef sumbetweentwokth(A, N, k1, k2):\n heapq.heapify(A)\n for i in range(k1):\n heapq.heappop(A)\n i = k1\n sum = 0\n while i < k2 - 1:\n sum += heapq.heappop(A)\n i += 1\n return sum", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n heap = []\n heapq.heapify(heap)\n for i in range(len(A)):\n heapq.heappush(heap, A[i])\n k1 = K1\n k2 = K2\n while k1:\n heapq.heappop(heap)\n k1 -= 1\n ans = 0\n k = k2 - K1 - 1\n while k > 0:\n if heap:\n ele = heapq.heappop(heap)\n ans += ele\n k -= 1\n return ans", "def sumbetweentwokth(A, N, K1, K2):\n arr = set(A)\n arr = sorted(A)\n sum = 0\n for i in range(K1, K2 - 1):\n sum = sum + arr[i]\n return sum", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n s = 0\n for i in range(N):\n if i > K1 - 1:\n s += A[i]\n if i == K2 - 1:\n s -= A[i]\n break\n return s", "def sumbetweentwokth(A, N, K1, K2):\n if K1 >= N:\n return 0\n A.sort()\n if K2 <= N:\n sum1 = 0\n for i in range(K1, K2 - 1):\n sum1 = sum1 + A[i]\n else:\n sum1 = 0\n for i in range(K1, N):\n sum1 = sum1 + A[i]\n return sum1", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n if K1 > N or K2 > N:\n return 0\n m = max(K1, K2)\n heap = []\n for i in A:\n heapq.heappush(heap, i)\n (ans, x) = (0, 0)\n while heap:\n e = heapq.heappop(heap)\n x += 1\n if x > K1 and x < K2:\n ans += e\n return ans", "def sumbetweentwokth(A, N, K1, K2):\n tot_sum = 0\n\n def kthElement(A, k, N):\n import heapq\n A = [-1 * n for n in A]\n hp = A[:k]\n heapq.heapify(hp)\n for i in range(k, N):\n heapq.heappushpop(hp, A[i])\n return -1 * hp[0]\n k1num = kthElement(A, K1, N)\n k2num = kthElement(A, K2, N)\n for i in range(0, N):\n if A[i] > k1num and A[i] < k2num:\n tot_sum += A[i]\n return tot_sum", "import heapq\n\ndef kthSmallest(arr, l, r, k):\n myList = []\n heapq.heapify(myList)\n for i in range(l, r + 1):\n heapq.heappush(myList, arr[i] * -1)\n if len(myList) > k:\n heapq.heappop(myList)\n return myList[0] * -1\n\ndef sumbetweentwokth(A, N, K1, K2):\n n1 = self.kthSmallest(A, 0, N - 1, K1)\n n2 = self.kthSmallest(A, 0, N - 1, K2)\n sum = 0\n for i in range(N):\n if n1 < A[i] < n2:\n sum += A[i]\n return sum", "from heapq import heappop, heappush, heapify\n\ndef sumbetweentwokth(A, N, K1, K2):\n\n def fun(A, K):\n maxheap = []\n heapify(maxheap)\n for i in A:\n heappush(maxheap, -i)\n if len(maxheap) > K:\n heappop(maxheap)\n return -1 * heappop(maxheap)\n max1 = fun(A, K1)\n max2 = fun(A, K2)\n ans = 0\n for i in A:\n if i > max1 and i < max2:\n ans += i\n return ans", "def sumbetweentwokth(A, N, K1, K2):\n from heapq import heapify, heappop, heappush\n\n def fun(A, K):\n h = []\n heapify(h)\n for i in A:\n heappush(h, -i)\n if len(h) > K:\n heappop(h)\n return -1 * heappop(h)\n r1 = fun(A, K1)\n r2 = fun(A, K2)\n ans = 0\n for i in A:\n if i > r1 and i < r2:\n ans += i\n return ans", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n s = 0\n while K1 < K2 - 1:\n s += A[K1]\n K1 = K1 + 1\n return s", "import heapq\n\ndef kthSmallest(k, arr):\n pq = []\n for num in arr:\n heapq.heappush(pq, -num)\n if len(pq) > k:\n heapq.heappop(pq)\n return -heapq.heappop(pq)\n\ndef sumbetweentwokth(A, N, K1, K2):\n num1 = kthSmallest(K1, A)\n num2 = kthSmallest(K2, A)\n res = 0\n for num in A:\n if num > num1 and num < num2:\n res += num\n return res", "def sumbetweentwokth(a, N, K1, K2):\n a.sort()\n return sum(a[K1:K2 - 1])", "def sumbetweentwokth(A, N, K1, K2):\n p = sorted(A)\n u = K1 - 1\n v = K2 - 1\n a = p[u + 1:v]\n return sum(a)", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n heap = []\n heapq.heapify(heap)\n for i in range(N):\n heapq.heappush(heap, -1 * A[i])\n if len(heap) > K2:\n heapq.heappop(heap)\n second = -1 * heap[0]\n while len(heap) > K1:\n heapq.heappop(heap)\n first = -1 * heap[0]\n total = 0\n for i in range(N):\n if A[i] > first and A[i] < second:\n total += A[i]\n return total", "from heapq import *\n\ndef sumbetweentwokth(arr, n, k1, k2):\n maxHeap = []\n for i in range(n):\n if i < k2 - 1:\n heappush(maxHeap, -arr[i])\n elif maxHeap[0] < -arr[i]:\n heappop(maxHeap)\n heappush(maxHeap, -arr[i])\n summ = 0\n for i in range(k2 - k1 - 1):\n summ += -heappop(maxHeap)\n return summ", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n x = A[K1 - 1]\n y = A[K2 - 1]\n s = 0\n for i in A:\n if i > x and i < y:\n s += i\n return s", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n heapq.heapify(A)\n total = 0\n while K1 > 0 or K2 > 0:\n el = heapq.heappop(A)\n K1 -= 1\n K2 -= 1\n if K1 < 0 and K2 > 0:\n total += el\n return total", "def sumbetweentwokth(A, N, k1, k2):\n t = sorted(A)\n s = 0\n f = 0\n return sum(t[k1:k2 - 1])", "def sumbetweentwokth(A, N, K1, K2):\n import heapq\n l = []\n l1 = []\n heapq.heapify(A)\n for i in range(N):\n a = heapq.heappop(A)\n l.append(a)\n for i in range(K1, K2 - 1):\n l1.append(l[i])\n return sum(l1)", "from heapq import *\n\ndef sumbetweentwokth(A, N, K1, K2):\n minheap = [num for num in A]\n heapify(minheap)\n (numK1, numK2) = (None, None)\n for i in range(K2):\n x = heappop(minheap)\n if i + 1 == K1:\n numK1 = x\n elif i + 1 == K2:\n numK2 = x\n break\n res = 0\n for num in A:\n if num > numK1 and num < numK2:\n res += num\n return res", "def sumbetweentwokth(A, N, K1, K2):\n list1 = []\n list1 = list1 + A\n list1.sort()\n ele1 = list1[K1 - 1]\n ele3 = list1[K2 - 1]\n r1 = max(ele1, ele3)\n r3 = min(ele1, ele3)\n s = 0\n for i in range(0, len(A)):\n if A[i] > r3 and A[i] < r1:\n s = s + A[i]\n return s", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n heap = []\n for i in A:\n heapq.heappush(heap, i)\n count = 0\n sum_ = 0\n while heap:\n p = heapq.heappop(heap)\n count += 1\n if count > K1 and count < K2:\n sum_ += p\n elif count >= K2:\n break\n return sum_", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n\n def ksmallest(A, x):\n heap = []\n for ch in A:\n heapq.heappush(heap, -ch)\n if len(heap) > x:\n heapq.heappop(heap)\n return -heap[0]\n first = ksmallest(A, K1)\n second = ksmallest(A, K2)\n summ = 0\n for ch in A:\n if second > ch > first:\n summ += ch\n return summ", "from heapq import *\n\ndef kthSmallest(arr, k):\n heap = []\n heapify(heap)\n for num in arr:\n heappush(heap, -1 * num)\n if len(heap) == k + 1:\n heappop(heap)\n return -1 * heappop(heap)\n\ndef sumbetweentwokth(A, N, K1, K2):\n k1thSmallest = self.kthSmallest(A, K1)\n k2thSmallest = self.kthSmallest(A, K2)\n sum = 0\n for num in A:\n if num > k1thSmallest and num < k2thSmallest:\n sum += num\n return sum", "def sumbetweentwokth(A, N, K1, K2):\n sum1 = 0\n A.sort()\n min1 = A[K1 - 1]\n max1 = A[K2 - 1]\n for i in A:\n if i > min1 and i < max1:\n sum1 += i\n return sum1", "def sumbetweentwokth(A, N, K1, K2):\n sum = 0\n A.sort()\n p = A[K1 - 1]\n q = A[K2 - 1]\n for i in A:\n if p < i < q:\n sum += i\n return sum", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n ele1 = A[K1 - 1]\n ele2 = A[K2 - 1]\n sum1 = 0\n for i in range(len(A)):\n if A[i] > ele1 and A[i] < ele2:\n sum1 += A[i]\n return sum1", "def sumbetweentwokth(A, N, K1, K2):\n a = sorted(A)\n b = a[K1 - 1]\n c = a[K2 - 1]\n s = 0\n for i in a:\n if i > b and i < c:\n s = s + i\n return s", "def sumbetweentwokth(A, N, K1, K2):\n a = sorted(A)\n a = [i for i in a]\n return sum(a[K1:K2 - 1])", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n ans = 0\n heapq.heapify(A)\n for i in range(K1):\n heapq.heappop(A)\n for i in range(K2 - K1 - 1):\n ans += heapq.heappop(A)\n return ans", "from heapq import *\n\ndef sumbetweentwokth(arr, n, k1, k2):\n heap = []\n for item in arr:\n heappush(heap, item)\n for _ in range(k1):\n heappop(heap)\n result = 0\n for _ in range(k2 - k1 - 1):\n result += heappop(heap)\n return result"], "starter_code": "def sumbetweentwokth(A, N, K1, K2):\n", "input_output": {"inputs": ["N = 7\r\nA[] = {20, 8, 22, 4, 12, 10, 14}\r\nK1 = 3, K2 = 6", "N = 6\r\nA[] = {10, 2, 50, 12, 48, 13}\r\nK1= 2, K2 = 6"], "outputs": ["26", "73"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Heap", "Sorting", "Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/sum-of-elements-between-k1th-and-k2th-smallest-elements3133/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N. log(N))", "entry_point": "sumbetweentwokth", "task_id": "TACO_lite/127", "example": [[[7, [20, 8, 22, 4, 12, 10, 14], 3, 6], [6, [10, 2, 50, 12, 48, 13], 2, 6]], ["26", "73"]]} +{"requirement": "Given string S representing a postfix expression, the task is to evaluate the expression and find the final value. Operators will only include the basic arithmetic operators like *, /, + and -.\n \nExample 1:\nInput: S = \"231*+9-\"\nOutput: -4\nExplanation:\nAfter solving the given expression, \nwe have -4 as result.\nExample 2:\nInput: S = \"123+*8-\"\nOutput: -3\nExplanation:\nAfter solving the given postfix \nexpression, we have -3 as result.\nYour Task:\nYou do not need to read input or print anything. Complete the function evaluatePostfixExpression() that takes the string S denoting the expression as input parameter and returns the evaluated value.\nExpected Time Complexity: O(|S|)\nExpected Auixilliary Space: O(|S|)\nConstraints:\n1 ≤ |S| ≤ 10^{5}\n0 ≤ |S_{i}|≤ 9 (And given operators)", "solutions": ["def evaluatepostfix(S):\n stack = []\n for i in range(len(S)):\n if S[i] in ['+', '-', '/', '*']:\n y = stack.pop()\n x = stack.pop()\n if S[i] == '+':\n stack.append(x + y)\n elif S[i] == '-':\n stack.append(x - y)\n elif S[i] == '*':\n stack.append(x * y)\n elif S[i] == '/':\n stack.append(x // y)\n else:\n stack.append(int(S[i]))\n return stack[-1]", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i.isdigit() is True:\n stack.append(i)\n else:\n a = int(stack.pop())\n b = int(stack.pop())\n if i == '+':\n res = b + a\n elif i == '-':\n res = b - a\n elif i == '*':\n res = b * a\n else:\n res = b // a\n stack.append(res)\n return res", "def evaluatepostfix(s):\n stack = []\n for i in s:\n if i in ['+', '*', '/', '-']:\n (y, x) = (stack.pop(), stack.pop())\n if i == '+':\n stack.append(x + y)\n elif i == '*':\n stack.append(x * y)\n elif i == '-':\n stack.append(x - y)\n else:\n stack.append(x // y)\n else:\n stack.append(int(i))\n return stack[-1]", "def evaluatepostfix(S):\n st = []\n ans = 0\n for i in S:\n if i.isdigit():\n st.append(i)\n else:\n if i == '/':\n i = '//'\n second = st.pop()\n first = st.pop()\n st.append(str(eval(first + i + second)))\n return int(st.pop())", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']:\n stack.append(int(i))\n else:\n op1 = stack.pop()\n op2 = stack.pop()\n if i == '/':\n stack.append(op2 // op1)\n if i == '*':\n stack.append(op1 * op2)\n if i == '+':\n stack.append(op1 + op2)\n if i == '-':\n stack.append(op2 - op1)\n return stack[-1]", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i.isdigit():\n stack.append(i)\n else:\n a = int(stack.pop())\n b = int(stack.pop())\n if i == '+':\n stack.append(a + b)\n elif i == '-':\n stack.append(b - a)\n elif i == '*':\n stack.append(a * b)\n else:\n stack.append(b // a)\n return sum(stack)", "def evaluatepostfix(S):\n S = S + '$'\n st = []\n for i in S:\n if i == '$':\n return st[-1]\n if i.isdigit():\n st.append(i)\n else:\n a = st.pop()\n b = st.pop()\n if i == '*':\n c = int(b) * int(a)\n elif i == '+':\n c = int(b) + int(a)\n elif i == '-':\n c = int(b) - int(a)\n else:\n c = int(b) / int(a)\n st.append(c)", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i.isdigit():\n stack.append(i)\n else:\n val1 = int(stack.pop())\n val2 = int(stack.pop())\n if i == '+':\n stack.append(val2 + val1)\n elif i == '-':\n stack.append(val2 - val1)\n elif i == '*':\n stack.append(val2 * val1)\n else:\n stack.append(val2 // val1)\n return sum(stack)", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:\n eva = 0\n a = int(stack.pop(-1))\n b = int(stack.pop(-1))\n if i == '+':\n eva = a + b\n elif i == '-':\n eva = b - a\n elif i == '*':\n eva = a * b\n elif i == '/':\n eva = b // a\n stack.append(eva)\n else:\n stack.append(i)\n return stack[-1]", "def evaluatepostfix(s):\n st = []\n for i in s:\n if i in '0123456789':\n st.append(i)\n else:\n p2 = st.pop()\n p1 = st.pop()\n res = eval(p1 + i + p2)\n st.append(str(int(res)))\n return st[-1]", "def evaluatepostfix(S):\n st = []\n hashmap = {'*', '+', '-', '/'}\n for i in S:\n if i in hashmap:\n val1 = st.pop()\n val2 = st.pop()\n if i == '+':\n st.append(val2 + val1)\n elif i == '-':\n st.append(val2 - val1)\n elif i == '*':\n st.append(val2 * val1)\n elif i == '/':\n st.append(val2 // val1)\n else:\n st.append(int(i))\n return sum(st)", "def evaluatepostfix(S):\n stack = []\n hashset = {'*', '/', '+', '-'}\n for i in S:\n if i in hashset:\n a = stack.pop()\n b = stack.pop()\n if i == '*':\n stack.append(b * a)\n elif i == '/':\n stack.append(b // a)\n elif i == '+':\n stack.append(b + a)\n else:\n stack.append(b - a)\n else:\n stack.append(int(i))\n return stack[0]", "def evaluatepostfix(S):\n stack = []\n top = -1\n for i in S:\n if i >= '0' and i <= '9':\n stack.append(int(i))\n top += 1\n else:\n y = stack.pop()\n top -= 1\n x = stack.pop()\n top -= 1\n if i == '+':\n stack.append(x + y)\n top += 1\n if i == '-':\n stack.append(x - y)\n top += 1\n if i == '*':\n stack.append(x * y)\n top += 1\n if i == '/':\n stack.append(x // y)\n top += 1\n return stack[0]", "def evaluatepostfix(S):\n st = []\n for i in S:\n if i.isdigit():\n st.append(int(i))\n elif len(st) > 1:\n if i == '+':\n st.append(st.pop(-1) + st.pop(-1))\n elif i == '-':\n st.append(-st.pop(-1) + st.pop(-1))\n elif i == '*':\n st.append(st.pop(-1) * st.pop(-1))\n elif i == '/':\n s = st.pop(-1)\n f = st.pop(-1)\n st.append(f // s)\n return st.pop(-1)", "import operator\n\ndef evaluatepostfix(S):\n stk = []\n r = 0\n for i in range(len(S)):\n if S[i] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:\n stk.append(int(S[i]))\n else:\n r1 = stk.pop()\n r2 = stk.pop()\n if S[i] == '*':\n op = operator.mul(r2, r1)\n elif S[i] == '-':\n op = operator.sub(r2, r1)\n elif S[i] == '+':\n op = operator.add(r2, r1)\n else:\n op = operator.truediv(r2, r1)\n op = int(op)\n stk.append(op)\n return stk[-1]", "def ev(a, b, c):\n if c == '+':\n return a + b\n elif c == '-':\n return b - a\n elif c == '*':\n return a * b\n else:\n return b // a\n\ndef evaluatepostfix(S):\n s = []\n for i in range(0, len(S)):\n if S[i].isalnum():\n s.append(int(S[i]))\n else:\n s.append(self.ev(s.pop(), s.pop(), S[i]))\n return s[-1]", "def evaluatepostfix(s):\n postfix = []\n for i in range(len(s)):\n if s[i] == '+':\n a1 = postfix.pop()\n a2 = postfix.pop()\n postfix.append(a1 + a2)\n elif s[i] == '-':\n a1 = postfix.pop()\n a2 = postfix.pop()\n postfix.append(a2 - a1)\n elif s[i] == '*':\n a1 = postfix.pop()\n a2 = postfix.pop()\n postfix.append(a1 * a2)\n elif s[i] == '/':\n a1 = postfix.pop()\n a2 = postfix.pop()\n postfix.append(a2 // a1)\n else:\n postfix.append(int(s[i]))\n return postfix.pop()", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i == '*':\n (n, m) = (stack.pop(), stack.pop())\n stack.append(n * m)\n elif i == '/':\n (n, m) = (stack.pop(), stack.pop())\n stack.append(m // n)\n elif i == '+':\n (n, m) = (stack.pop(), stack.pop())\n stack.append(n + m)\n elif i == '-':\n (n, m) = (stack.pop(), stack.pop())\n stack.append(m - n)\n else:\n stack.append(int(i))\n return stack[-1]", "def do_maths(a, b, op):\n if op == '+':\n return a + b\n if op == '-':\n return a - b\n if op == '*':\n return a * b\n if op == '/':\n return a // b\n\ndef evaluatepostfix(S):\n stk = []\n ans = 0\n for ch in S:\n if ch in ('+', '-', '*', '/'):\n a = stk.pop()\n b = stk.pop()\n res = self.do_maths(b, a, ch)\n stk.append(res)\n else:\n stk.append(int(ch))\n return stk.pop()", "def evaluatepostfix(S):\n stack = []\n for ch in S:\n if ch == '*' or ch == '+' or ch == '-' or (ch == '/'):\n first = stack.pop()\n second = stack.pop()\n if ch == '*':\n result = first * second\n elif ch == '/':\n result = second // first\n elif ch == '+':\n result = second + first\n else:\n result = second - first\n stack.append(result)\n else:\n stack.append(int(ch))\n return stack[-1]", "def evaluatepostfix(S):\n stk = []\n for i in S:\n if i == '*':\n A = stk.pop()\n B = stk.pop()\n stk.append(B * A)\n elif i == '/':\n A = stk.pop()\n B = stk.pop()\n stk.append(B // A)\n elif i == '-':\n A = stk.pop()\n B = stk.pop()\n stk.append(B - A)\n elif i == '+':\n A = stk.pop()\n B = stk.pop()\n stk.append(B + A)\n else:\n stk.append(int(i))\n return stk[-1]", "def evaluatepostfix(S):\n k = '+-*/'\n arr = []\n s = S[:]\n for i in range(len(s)):\n if s[i].isnumeric():\n arr.append(s[i])\n if s[i] in k:\n a = arr.pop()\n b = arr.pop()\n if s[i] == '*':\n c = int(b) * int(a)\n arr.append(c)\n elif s[i] == '+':\n c = int(b) + int(a)\n arr.append(c)\n elif s[i] == '-':\n c = int(b) - int(a)\n arr.append(c)\n elif s[i] == '/':\n c = int(b) / int(a)\n arr.append(c)\n return arr[0]", "def evaluatepostfix(S):\n a = []\n for i in S:\n if i.isnumeric():\n a.append(int(i))\n elif i == '*':\n m = a[-1] * a[-2]\n a.pop(-1)\n a.pop(-1)\n a.append(int(m))\n elif i == '+':\n m = a[-1] + a[-2]\n a.pop(-1)\n a.pop(-1)\n a.append(int(m))\n elif i == '-':\n m = a[-2] - a[-1]\n a.pop(-1)\n a.pop(-1)\n a.append(int(m))\n elif i == '/':\n m = a[-2] / a[-1]\n a.pop(-1)\n a.pop(-1)\n a.append(int(m))\n return int(a[0])", "def evaluatepostfix(S):\n stack = []\n for item in S:\n if item.isdigit():\n stack.append(item)\n else:\n item1 = stack.pop()\n item2 = stack.pop()\n stack.append(str(int(eval(item2 + item + item1))))\n return stack.pop()", "def evaluatepostfix(S):\n stk = []\n for i in S:\n if i == '+':\n stk.append(stk.pop() + stk.pop())\n elif i == '-':\n (a, b) = (stk.pop(), stk.pop())\n stk.append(b - a)\n elif i == '*':\n stk.append(stk.pop() * stk.pop())\n elif i == '/':\n (a, b) = (stk.pop(), stk.pop())\n stk.append(int(b / a))\n else:\n stk.append(int(i))\n return stk[-1]", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i != '+' and i != '*' and (i != '-') and (i != '/'):\n stack.append(i)\n else:\n n1 = int(stack.pop())\n n2 = int(stack.pop())\n if i == '+':\n stack.append(n1 + n2)\n elif i == '-':\n stack.append(n2 - n1)\n elif i == '*':\n stack.append(n1 * n2)\n elif i == '/':\n stack.append(n2 / n1)\n return stack[-1]", "def post_fix_evaluation(input_string):\n operand_stack = []\n n = len(input_string)\n for i in range(n):\n element = input_string[i]\n if is_integer(element):\n operand_stack.append(int(element))\n else:\n pop_do_operation(operand_stack, element)\n return operand_stack[0]\n\ndef performOperation(operand_1: int, operand_2: int, operator: str):\n if operator == '+':\n return operand_1 + operand_2\n elif operator == '-':\n return operand_1 - operand_2\n elif operator == '*':\n return operand_1 * operand_2\n else:\n return int(operand_1 / operand_2)\n\ndef pop_do_operation(operand_stack: [], operator: str):\n operand_2 = operand_stack.pop(-1)\n operand_1 = operand_stack.pop(-1)\n new_element = performOperation(operand_1, operand_2, operator)\n operand_stack.append(new_element)\n\ndef is_integer(element):\n return ord('0') <= ord(element) <= ord('9')\n\ndef evaluatepostfix(S):\n return post_fix_evaluation(S)", "def evaluatepostfix(S):\n op = {'*': lambda x, y: x * y, '+': lambda x, y: x + y, '-': lambda x, y: x - y, '/': lambda x, y: x / y}\n stack = []\n n = len(S)\n for i in range(0, n):\n if S[i].isdigit():\n stack.append(S[i])\n else:\n y = int(stack.pop())\n x = int(stack.pop())\n z = op[S[i]](x, y)\n stack.append(z)\n return stack.pop()", "def evaluatepostfix(S):\n st = []\n for i in S:\n if i in ['+', '-', '*', '/']:\n op2 = int(st.pop())\n op1 = int(st.pop())\n if i == '+':\n st.append(op1 + op2)\n elif i == '-':\n st.append(op1 - op2)\n elif i == '*':\n st.append(op1 * op2)\n elif i == '/':\n st.append(op1 / op2)\n else:\n st.append(i)\n return st[-1]", "def evaluatepostfix(S):\n expr = ['*', '/', '+', '-']\n arr = []\n for i in S:\n if i in expr:\n op2 = int(arr.pop())\n op1 = int(arr.pop())\n if i == '*':\n result = op1 * op2\n elif i == '/':\n result = op1 / op2\n elif i == '+':\n result = op1 + op2\n else:\n result = op1 - op2\n arr.append(result)\n else:\n arr.append(i)\n return arr.pop()", "def evaluatepostfix(S):\n st = []\n n = len(S)\n for i in range(n):\n if not S[i] in '+-/*':\n st.append(S[i])\n else:\n a = int(st.pop())\n b = int(st.pop())\n if S[i] == '+':\n tmpAns = b + a\n if S[i] == '-':\n tmpAns = b - a\n if S[i] == '/':\n tmpAns = b / a\n if S[i] == '*':\n tmpAns = b * a\n st.append(tmpAns)\n return st[-1]", "def evaluatepostfix(S):\n s = []\n for i in S:\n if i.isdigit():\n s.append(int(i))\n elif i == '+':\n x = s.pop()\n y = s.pop()\n s.append(x + y)\n elif i == '-':\n x = s.pop()\n y = s.pop()\n s.append(y - x)\n elif i == '*':\n x = s.pop()\n y = s.pop()\n s.append(x * y)\n elif i == '/':\n x = s.pop()\n y = s.pop()\n s.append(y // x)\n return s[0]", "def evaluatepostfix(S):\n stk = []\n s1 = '*/+-'\n for i in S:\n if i not in s1:\n stk.append(int(i))\n else:\n x = stk.pop()\n y = stk.pop()\n if i == '*':\n res = x * y\n elif i == '+':\n res = x + y\n elif i == '-':\n res = y - x\n else:\n res = y // x\n stk.append(res)\n return stk[-1]", "def evaluatepostfix(S):\n x = ['+', '-', '/', '*']\n stack = []\n for i in S:\n if i in x:\n a = stack.pop()\n b = stack.pop()\n r = b + i + a\n res = int(eval(r))\n stack.append(str(res))\n else:\n stack.append(i)\n return stack.pop()", "def evaluatepostfix(s):\n stack = []\n for c in s:\n if c == '+' or c == '/' or c == '*' or (c == '-'):\n op2 = int(stack.pop())\n op1 = int(stack.pop())\n if c == '+':\n r = op1 + op2\n elif c == '-':\n r = op1 - op2\n elif c == '*':\n r = op1 * op2\n else:\n r = op1 // op2\n stack.append(r)\n else:\n stack.append(int(c))\n return stack[0]", "def evaluatepostfix(S):\n x = []\n op = {'*', '/', '+', '-'}\n for i in S:\n if i in op:\n a = x.pop()\n b = x.pop()\n if i == '*':\n x.append(b * a)\n elif i == '/':\n x.append(b // a)\n elif i == '+':\n x.append(b + a)\n else:\n x.append(b - a)\n else:\n x.append(int(i))\n return x[0]", "def evaluatepostfix(S):\n l = list(S)\n operators = ['*', '+', '-', '/']\n operands = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]\n stack = []\n for i in range(len(l)):\n if str(l[i]) not in operators:\n stack.append(int(l[i]))\n else:\n s1 = stack.pop()\n s2 = stack.pop()\n if str(l[i]) == '-':\n val = s2 - s1\n elif str(l[i]) == '+':\n val = s1 + s2\n elif str(l[i]) == '*':\n val = s1 * s2\n elif str(l[i]) == '/':\n val = s2 // s1\n stack.append(val)\n return stack[-1]", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i == '+' or i == '/' or i == '*' or (i == '-'):\n a = stack.pop()\n b = stack.pop()\n if i == '/':\n p = '//'\n stack.append(str(eval(b + p + a)))\n else:\n stack.append(str(eval(b + i + a)))\n else:\n stack.append(i)\n re = stack.pop()\n return re", "def evaluatepostfix(s):\n st = []\n for i in s:\n if i.isdigit():\n st.append(i)\n else:\n op1 = int(st.pop())\n op2 = int(st.pop())\n if i == '+':\n ans = op2 + op1\n elif i == '-':\n ans = op2 - op1\n elif i == '*':\n ans = op2 * op1\n elif i == '/':\n ans = op2 / op1\n st.append(ans)\n return st.pop()", "from queue import LifoQueue as Stack\n\ndef evaluatepostfix(S):\n stack = Stack()\n for char in S:\n if char in '*/+-':\n (operand2, operand1) = (stack.get(), stack.get())\n result = str(int(eval(operand1 + char + operand2)))\n stack.put(result)\n else:\n stack.put(char)\n return int(stack.get())", "def evaluatepostfix(S):\n stack = []\n for ele in S:\n if ele.isalnum():\n stack.append(ele)\n continue\n if len(stack) >= 2:\n sec = int(stack.pop())\n first = int(stack.pop())\n else:\n return -1\n if ele == '*':\n stack.append(first * sec)\n elif ele == '+':\n stack.append(first + sec)\n elif ele == '-':\n stack.append(first - sec)\n elif ele == '/':\n stack.append(first // sec)\n return stack[0] if stack else -1", "def evaluatepostfix(S):\n stack = []\n operators = ('+', '-', '*', '/')\n for item in S:\n if item not in operators:\n stack.append(item)\n else:\n first = int(stack.pop())\n second = int(stack.pop())\n if item == '+':\n stack.append(second + first)\n elif item == '-':\n stack.append(second - first)\n elif item == '*':\n stack.append(second * first)\n elif item == '/':\n stack.append(second / first)\n return stack[0]", "def evaluatepostfix(S):\n stack = []\n ans = None\n for i in S:\n if i == '*':\n t1 = stack.pop()\n t2 = stack.pop()\n stack.append(t1 * t2)\n elif i == '+':\n t1 = stack.pop()\n t2 = stack.pop()\n stack.append(t1 + t2)\n elif i == '-':\n t1 = stack.pop()\n t2 = stack.pop()\n stack.append(t2 - t1)\n elif i == '/':\n t1 = stack.pop()\n t2 = stack.pop()\n stack.append(t2 // t1)\n else:\n stack.append(int(i))\n return stack.pop()", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i.isdigit():\n stack.append(int(i))\n elif i == '*':\n stack.append(int(stack.pop(-2) * stack.pop()))\n elif i == '/':\n stack.append(int(stack.pop(-2) / stack.pop()))\n elif i == '+':\n stack.append(int(stack.pop(-2) + stack.pop()))\n elif i == '-':\n stack.append(int(stack.pop(-2) - stack.pop()))\n return stack[0]", "def evaluatepostfix(S):\n\n def fun(x, y, oper):\n if oper == '+':\n return x + y\n if oper == '-':\n return x - y\n if oper == '*':\n return x * y\n if oper == '/':\n return x // y\n s = []\n for i in S:\n if i.isdigit():\n s.append(int(i))\n else:\n y = s.pop()\n x = s.pop()\n res = fun(x, y, i)\n s.append(res)\n return s.pop()", "def evaluatepostfix(S):\n l = ['+', '-', '*', '/']\n s1 = []\n for i in S:\n if i not in l:\n s1.append(i)\n else:\n o1 = int(s1.pop())\n o2 = int(s1.pop())\n if i == '+':\n s1.append(o1 + o2)\n elif i == '-':\n s1.append(o2 - o1)\n elif i == '*':\n s1.append(o1 * o2)\n else:\n try:\n s1.append(int(o2 // o1))\n except:\n return int(o2 // o1)\n return s1.pop()", "def evaluatepostfix(S):\n stack = []\n res = 0\n for i in S:\n if i.isnumeric():\n stack.append(int(i))\n else:\n a = stack.pop()\n b = stack.pop()\n if i == '+':\n res = b + a\n if i == '*':\n res = b * a\n if i == '-':\n res = b - a\n if i == '/':\n res = b // a\n stack.append(res)\n return stack[-1]", "def evaluatepostfix(S):\n (stack, n) = ([], len(S))\n for i in range(n):\n if S[i] == '*':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(op1 * op2)\n elif S[i] == '+':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(op1 + op2)\n elif S[i] == '-':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(op1 - op2)\n elif S[i] == '/':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(op1 // op2)\n else:\n stack.append(int(S[i]))\n return stack.pop() if stack else 0", "def evaluatepostfix(s):\n stack = list()\n for char in s:\n if char == '+':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(op1 + op2)\n elif char == '-':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(op1 - op2)\n elif char == '*':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(op1 * op2)\n elif char == '/':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(int(op1 / op2))\n else:\n stack.append(int(char))\n return stack.pop()", "def get_res(a, b, symbol):\n if symbol == '+':\n return a + b\n elif symbol == '-':\n return a - b\n elif symbol == '*':\n return a * b\n else:\n return a // b\n\ndef evaluatepostfix(S):\n exp = list(S)\n stack = []\n for i in exp:\n if i.isdigit():\n stack.append(int(i))\n else:\n op1 = stack.pop()\n op2 = stack.pop()\n res = get_res(op2, op1, i)\n stack.append(res)\n return stack[-1]", "def evaluatepostfix(S):\n temp = []\n for i in S:\n if i.isdigit():\n temp.append(i)\n elif i in ['*', '+', '-', '/']:\n b = int(temp.pop())\n a = int(temp.pop())\n if i == '*':\n ans = a * b\n elif i == '/':\n ans = a // b\n elif i == '-':\n ans = a - b\n else:\n ans = a + b\n temp.append(ans)\n return temp.pop()", "def evaluatepostfix(S):\n li = []\n for i in S:\n if i not in '*/+-':\n li.insert(0, i)\n elif i == '*':\n p2 = li.pop(0)\n p1 = li.pop(0)\n li.insert(0, int(p1) * int(p2))\n elif i == '/':\n p2 = li.pop(0)\n p1 = li.pop(0)\n li.insert(0, int(p1) / int(p2))\n elif i == '+':\n p2 = li.pop(0)\n p1 = li.pop(0)\n li.insert(0, int(p1) + int(p2))\n elif i == '-':\n p2 = li.pop(0)\n p1 = li.pop(0)\n li.insert(0, int(p1) - int(p2))\n res = li.pop(0)\n return res", "def evaluatepostfix(S):\n st = []\n for i in S:\n if i in '0123456789':\n st.append(i)\n elif i in '+-/*':\n op1 = st.pop()\n op2 = st.pop()\n res = eval(op2 + i + op1)\n st.append(str(int(res)))\n return ''.join(st)", "def evaluatepostfix(S):\n a = []\n for s in S:\n if s == '*' or s == '/' or s == '+' or (s == '-'):\n x = a.pop()\n y = a.pop()\n z = eval(str(y) + s + str(x))\n a.append(int(z))\n s = s[1:]\n else:\n a.append(s[0])\n s = s[1:]\n res = a[0]\n return res", "def evaluatepostfix(s):\n stack = list()\n n = len(s)\n for i in range(n):\n if s[i] == '+':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(int(op1 + op2))\n elif s[i] == '-':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(int(op1 - op2))\n elif s[i] == '*':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(int(op1 * op2))\n elif s[i] == '/':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(int(op1 / op2))\n else:\n stack.append(int(s[i]))\n return stack.pop()", "def evaluatepostfix(s):\n stack = []\n for c in s:\n if c in '+-*/':\n if c == '+':\n stack.append(stack.pop() + stack.pop())\n if c == '-':\n stack.append(-stack.pop() + stack.pop())\n if c == '*':\n stack.append(stack.pop() * stack.pop())\n if c == '/':\n t = stack.pop()\n u = stack.pop()\n stack.append(u // t)\n elif c in '0123456789':\n stack.append(int(c))\n return stack[0]", "def evaluatepostfix(S):\n stack = []\n for i in range(len(S)):\n if '0' <= S[i] <= '9':\n stack.append(S[i])\n else:\n op2 = int(stack.pop())\n op1 = int(stack.pop())\n if S[i] == '+':\n res = op1 + op2\n if S[i] == '-':\n res = op1 - op2\n if S[i] == '*':\n res = op1 * op2\n if S[i] == '/':\n res = op1 // op2\n stack.append(res)\n return stack[-1]", "def evaluatepostfix(S):\n symbol = ['*', '+', '-', '/']\n a = []\n for i in S:\n if i not in symbol:\n a.append(int(i))\n else:\n a1 = a.pop()\n a2 = a.pop()\n if i == '*':\n a.append(a2 * a1)\n elif i == '+':\n a.append(a2 + a1)\n elif i == '-':\n a.append(a2 - a1)\n elif i == '/':\n a.append(a2 // a1)\n return a[0]", "import queue\n\ndef evaluatepostfix(S):\n stack = queue.LifoQueue()\n for ele in S:\n if ele == '*' or ele == '/' or ele == '+' or (ele == '-'):\n a = stack.get()\n b = stack.get()\n if ele == '*':\n x = b * a\n elif ele == '/':\n x = b // a\n elif ele == '+':\n x = b + a\n else:\n x = b - a\n stack.put(x)\n else:\n stack.put(int(ele))\n return stack.get()", "def evaluatepostfix(S):\n temp = []\n for i in range(len(S)):\n if S[i] == '/':\n a = int(temp.pop())\n b = int(temp.pop())\n temp.append(b / a)\n elif S[i] == '*':\n a = int(temp.pop())\n b = int(temp.pop())\n temp.append(a * b)\n elif S[i] == '-':\n a = int(temp.pop())\n b = int(temp.pop())\n temp.append(b - a)\n elif S[i] == '+':\n a = int(temp.pop())\n b = int(temp.pop())\n temp.append(a + b)\n else:\n temp.append(S[i])\n return temp[0]", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i.isdigit():\n stack.append(i)\n else:\n val1 = stack.pop()\n val2 = stack.pop()\n if i == '/':\n p = '//'\n stack.append(str(eval(val2 + p + val1)))\n else:\n stack.append(str(eval(val2 + i + val1)))\n return stack.pop()", "def evaluatepostfix(S):\n st = []\n op = ['+', '-', '*', '/']\n for i in S:\n if i in op:\n a = st[-1]\n st.pop()\n a = int(a)\n b = st[-1]\n st.pop()\n b = int(b)\n if i == '+':\n st.append(b + a)\n if i == '-':\n st.append(b - a)\n if i == '*':\n st.append(b * a)\n if i == '/':\n st.append(int(b / a))\n else:\n st.append(i)\n return st[-1]", "def evaluatepostfix(S):\n op = ['*', '+', '-', '/']\n stk = []\n for c in S:\n if c not in op:\n stk.append(c)\n else:\n optr = c\n op2 = stk.pop()\n op1 = stk.pop()\n res = int(eval(str(op1) + str(optr) + str(op2)))\n stk.append(res)\n x = stk.pop()\n return x", "def evaluatepostfix(S):\n stack = []\n for chr in S:\n if chr in '+-/*':\n if len(stack) < 2:\n return 'stack underflow'\n else:\n a = stack.pop()\n b = stack.pop()\n result = eval(str(b) + chr + str(a))\n stack.append(int(result))\n else:\n stack.append(chr)\n return stack.pop()", "def evaluatepostfix(S):\n stack = []\n for item in S:\n if item != '*' and item != '/' and (item != '+') and (item != '-'):\n stack.append(item)\n else:\n item1 = int(stack.pop())\n item2 = int(stack.pop())\n if item == '*':\n stack.append(item1 * item2)\n elif item == '/':\n stack.append(item2 // item1)\n elif item == '+':\n stack.append(item1 + item2)\n else:\n stack.append(item2 - item1)\n return stack.pop()", "def evaluatepostfix(s):\n r = 0\n l = []\n for i in s:\n if i in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']:\n l.append(int(i))\n else:\n b = l.pop()\n a = l.pop()\n if i == '*':\n r = a * b\n if i == '+':\n r = a + b\n if i == '-':\n r = a - b\n if i == '/':\n r = a // b\n l.append(r)\n return l[-1]", "def ifOperand(ch):\n return ch == '*' or ch == '+' or ch == '/' or (ch == '-')\n\ndef evaluatepostfix(S):\n stack = []\n for ch in S:\n if ifOperand(ch):\n a = stack.pop()\n b = stack.pop()\n if ch == '-':\n stack.append(int(b) - int(a))\n if ch == '+':\n stack.append(int(b) + int(a))\n if ch == '*':\n stack.append(int(b) * int(a))\n if ch == '/':\n stack.append(int(b) // int(a))\n else:\n stack.append(ch)\n return stack[-1]", "def evaluatepostfix(S):\n stack = []\n for char in S:\n if char.isnumeric():\n stack.append(char)\n else:\n second_num = int(stack.pop(-1))\n first_num = int(stack.pop(-1))\n if char == '*':\n ans = first_num * second_num\n stack.append(ans)\n elif char == '+':\n ans = first_num + second_num\n stack.append(ans)\n elif char == '-':\n ans = first_num - second_num\n stack.append(ans)\n elif char == '/':\n ans = first_num / second_num\n stack.append(ans)\n return stack.pop(-1)", "def evaluatepostfix(S):\n stack = []\n allOperators = set(['+', '-', '*', '/', '^', '(', ')'])\n for i in range(0, len(S)):\n if S[i] not in allOperators:\n stack.append(S[i])\n else:\n a = stack[-1]\n stack.pop()\n a = int(a)\n b = stack[-1]\n stack.pop()\n b = int(b)\n if S[i] == '+':\n stack.append(b + a)\n if S[i] == '-':\n stack.append(b - a)\n if S[i] == '*':\n stack.append(b * a)\n if S[i] == '/':\n stack.append(b / a)\n return stack[-1]", "def __init__(maxsize):\n self.maxsize = maxsize\n self.top = -1\n self.arr = []\n\ndef empty():\n return self.top == -1\n\ndef full():\n return self.top == self.maxsize\n\ndef push(data):\n if self.full():\n return 'Stack is full'\n self.top += 1\n self.arr.append(data)\n\ndef peek():\n if self.empty():\n return 'Stack is empty'\n return self.arr[self.top]\n\ndef pop():\n if self.empty():\n return 'Stack is empty'\n top_ele = self.arr.pop()\n self.top -= 1\n return top_ele\n\ndef pred(sym):\n if sym == '*' or sym == '/':\n return 3\n if sym == '+' or sym == '-':\n return 2\n if sym == '#':\n return 1\n\ndef op(l, r, o):\n if o == '*':\n return l * r\n if o == '/':\n return l // r\n if o == '+':\n return l + r\n if o == '-':\n return l - r\n\ndef evaluatepostfix(S):\n post_arr = []\n for s in S:\n if s in ('*', '/', '+', '-'):\n right = post_arr.pop()\n left = post_arr.pop()\n post_arr.append(self.op(int(left), int(right), s))\n else:\n post_arr.append(s)\n res = post_arr.pop()\n if res == -0:\n return 0\n return res", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']:\n stack.append(int(i))\n else:\n pop1 = stack.pop()\n pop2 = stack.pop()\n if i == '*':\n value = pop2 * pop1\n stack.append(value)\n elif i == '+':\n value = pop2 + pop1\n stack.append(value)\n elif i == '-':\n value = pop2 - pop1\n stack.append(value)\n elif i == '/':\n value = pop2 // pop1\n stack.append(value)\n return stack[-1]", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i in ['*', '/', '+', '-']:\n y = stack.pop()\n x = stack.pop()\n if i == '*':\n stack.append(int(x) * int(y))\n elif i == '/':\n stack.append(int(x) / int(y))\n elif i == '+':\n stack.append(int(x) + int(y))\n elif i == '-':\n stack.append(int(x) - int(y))\n else:\n stack.append(i)\n return stack[0]", "def evaluatepostfix(S):\n result = 0\n stack = []\n for i in S:\n if i in ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'):\n stack.append(int(i))\n else:\n first_value = stack.pop()\n second_value = stack.pop()\n if i == '+':\n result = second_value + first_value\n if i == '-':\n result = second_value - first_value\n if i == '*':\n result = second_value * first_value\n if i == '/':\n result = second_value // first_value\n stack.append(result)\n return stack.pop()"], "starter_code": "def evaluatepostfix(S):\n", "input_output": {"inputs": ["S = \"231*+9-\"", "S = \"123+*8-\""], "outputs": ["-4", "-3"]}, "difficulty": "EASY", "raw_tags": ["Stack", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/evaluation-of-postfix-expression1735/1", "Expected Auxiliary Space": "O(|S|)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "evaluatepostfix", "task_id": "TACO_lite/193", "example": [[["231*+9-"], ["123+*8-"]], ["-4", "-3"]]} +{"requirement": "# Task\n\nYour task is to sort the characters in a string according to the following rules:\n```\n- Rule1: English alphabets are arranged from A to Z, case insensitive.\n ie. \"Type\" --> \"epTy\"\n- Rule2: If the uppercase and lowercase of an English alphabet exist\n at the same time, they are arranged in the order of oringal input.\n ie. \"BabA\" --> \"aABb\"\n- Rule3: non English alphabet remain in their original position.\n ie. \"By?e\" --> \"Be?y\"\n```\n\n# Input/Output\n\n\n`[input]` string `s`\n\nA non empty string contains any characters(English alphabets or non English alphabets).\n\n`[output]` a string\n\nA sorted string according to the rules above.\n\n# Example\n\n\nFor `s = \"cba\"`, the output should be `\"abc\"`.\n\nFor `s = \"Cba\"`, the output should be `\"abC\"`.\n\nFor `s = \"cCBbAa\"`, the output should be `\"AaBbcC\"`.\n\nFor `s = \"c b a\"`, the output should be `\"a b c\"`.\n\nFor `s = \"-c--b--a-\"`, the output should be `\"-a--b--c-\"`.\n\nFor `s = \"Codewars\"`, the output should be `\"aCdeorsw\"`.", "solutions": ["def sort_string(s):\n a = iter(sorted((c for c in s if c.isalpha()), key=str.lower))\n return ''.join((next(a) if c.isalpha() else c for c in s))", "import re\n\ndef sort_string(s):\n sortedChr = iter(sorted(re.sub('[^a-zA-Z]', '', s), key=str.lower))\n return re.sub('[a-zA-Z]', lambda m: next(sortedChr), s)", "def sort_string(s):\n alphas = [x for x in s if x.isalpha()]\n res = iter(sorted(alphas, key=lambda x: x.lower()))\n return ''.join((next(res) if x.isalpha() else x for x in s))", "def sort_string(stg):\n stg_ascii = (char for char in stg if char.isalpha())\n sorted_ascii = iter(sorted(stg_ascii, key=str.lower))\n return ''.join((next(sorted_ascii) if char.isalpha() else char for char in stg))", "from string import ascii_letters\nsortable = frozenset(ascii_letters)\n\ndef sort_string(s):\n sorted_chars = iter(sorted((c for c in s if c in sortable), key=str.lower))\n return ''.join((next(sorted_chars) if c in sortable else c for c in s))", "sort_string = lambda s: (lambda r: ''.join((r.pop(0) if e.isalpha() else e for e in s)))([e[0] for e in sorted(sorted([[k, i] for (i, k) in enumerate(s) if k.isalpha()], key=lambda a: a[1]), key=lambda a: a[0].lower())])", "def sort_string(s):\n it = iter(sorted([(i, x) for (i, x) in enumerate(s) if x.isalpha()], key=lambda p: (p[1].lower(), p[0])))\n return ''.join((next(it)[1] if x.isalpha() else x for x in s))", "def sort_string(s):\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n rule12 = list(sorted([x for x in s if x.lower() in alphabet], key=lambda i: alphabet.find(i.lower())))\n for (i, sym) in enumerate(s):\n if sym.lower() not in alphabet:\n rule12.insert(i, sym)\n return ''.join(rule12)"], "starter_code": "def sort_string(s):\n", "input_output": {"fn_name": "sort_string", "inputs": [["a"], ["cba"], ["Cba"], ["cCBbAa"], ["!"], ["c b a"], ["-c--b--a-"], ["cbaCcC"], ["Codewars"], [" MkWD{RB=//k-^ J@,xH Vfi uAz+$ kV _[ }a!}%pSBwn !kKB (b q PQF +}wS .kfU r wFNEs#NsR UVMdG"]], "outputs": [["a"], ["abc"], ["abC"], ["AaBbcC"], ["!"], ["a b c"], ["-a--b--c-"], ["abcCcC"], ["aCdeorsw"], [" AaBB{Bb=//D-^ d@,Ef FfF GHi+$ Jk _[ }k!}%kkKkM !MnN (N p PqQ +}Rr .RSS s suUUV#VVW wwwxz"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms", "Sorting"], "name": null, "source": "codewars", "tags": ["String algorithms", "Sorting"], "skill_types": ["Sorting"], "url": "https://www.codewars.com/kata/5936256f2e2a27edc9000047", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sort_string", "task_id": "TACO_lite/174", "example": [[["cba"], ["Cba"], ["cCBbAa"], ["c b a"], ["-c--b--a-"], ["Codewars"]], ["abc", "abC", "AaBbcC", "a b c", "-a--b--c-", "aCdeorsw"]]} +{"requirement": "Given a positive number k, we need to find a minimum value of positive integer n, such that XOR of n and n+1 is equal to k. If no such n exist then print -1.\nExample 1:\nInput: k = 3\nOutput: 1\nExplaination: 1 xor 2 = 3.\nExample 2:\nInput: k = 6\nOutput: -1\nExplaination: There is no such n, so that, \nn xor n+1 = k.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function xorCal() which takes k as input parameter and returns the value of n. If there is no such , then it returns -1.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ k ≤ 100", "solutions": ["def xorcal(k):\n if k == 1:\n return 2\n if k & k + 1 == 0:\n return k >> 1\n return -1", "def xorcal(k):\n if k == 1:\n return 2\n return -1 if k & k + 1 else k // 2", "def xorcal(k):\n if k == 1:\n return 2\n for i in range(k):\n if i ^ i + 1 == k:\n return i\n return -1", "def xorcal(k):\n p = k + 1\n i = 0\n s = bin(k)[2:]\n l = len(s)\n if k == 0:\n return 0\n if k == 1:\n return 2\n if s.count('1') == l:\n h = '1' * (l - 1)\n return int(h, 2)\n else:\n return -1", "def xorcal(k):\n n = 1\n if k == 1:\n return 2\n while n <= k:\n if k ^ n == n + 1:\n return n\n else:\n n += 1\n return -1", "from math import log2\n\ndef xorcal(k):\n if k & k + 1:\n return -1\n k += 1\n k = int(log2(k))\n k -= 1\n if k == 0:\n return 2\n return int('1' * k, 2)", "def xorcal(k):\n if k == 1:\n return 2\n elif k & k + 1 == 0:\n return k // 2\n else:\n return -1", "def xorcal(k):\n for i in range(1, 100):\n if i.__xor__(i + 1) == k:\n return i\n return -1", "def xorcal(k):\n n = n1 = k\n n = n >> 1\n n1 = n1 << 1\n if n != 0 and n ^ n + 1 == k:\n return n\n if n1 ^ n1 + 1 == k:\n return n1\n return -1", "def xorcal(k):\n i = 1\n while i <= 105:\n if i ^ i + 1 == k:\n return i\n i += 1\n return -1", "def xorcal(k):\n if k == 1:\n return 2\n i = 1\n while pow(2, i) <= k:\n a = pow(2, i)\n if k == a + (a - 1):\n return a - 1\n i += 1\n return -1", "def xorcal(k):\n if k == 1:\n return 2\n l = [1, 3, 7, 15, 31, 63]\n if k in l:\n return int(k / 2)\n return -1", "def xorcal(k):\n a = []\n for i in range(1, 100):\n a = i\n b = i + 1\n if a ^ b == k:\n return a\n return -1", "def xorcal(k):\n for n in range(1, 100):\n if n ^ n + 1 == k:\n return n\n return -1", "def xorcal(k):\n if k == 1:\n return 2\n string = bin(k)\n li = list(string[2:])\n if len(set(li)) == 1:\n return k // 2\n else:\n return -1", "def xorcal(k):\n a = {1: 2, 3: 1, 7: 3, 15: 7, 31: 15, 63: 31}\n if k in a:\n return a[k]\n else:\n return -1", "def xorcal(K):\n for i in range(1, 7 * K):\n if i ^ i + 1 == K:\n return i\n return -1", "def xorcal(k):\n if k == 1:\n return 2\n a = bin(k)[2:]\n b = len(a)\n c = 2 ** b\n if c - 1 == k:\n return 2 ** (b - 1) - 1\n return -1", "def xorcal(k):\n if k == 1:\n return 2\n i = 1\n while i < k:\n if k == i ^ i + 1:\n return i\n break\n i += 1\n return -1", "def xorcal(k):\n checkxor = 0\n numxor = 0\n index = 1\n for index in range(1, 129):\n if index ^ k == index + 1:\n checkxor = 1\n numxor = index\n break\n index += 1\n if checkxor == 1:\n return numxor\n else:\n return -1", "import math\n\ndef xorcal(k):\n if k == 1:\n return 2\n temp = math.log(k + 1, 2)\n if temp != int(temp):\n return -1\n else:\n return k // 2", "def xorcal(k):\n i = 1\n while i + 1 <= 100000:\n if i ^ i + 1 == k:\n return i\n i = i + 1\n return -1", "def xorcal(k):\n if k == 0:\n return 0\n if k == 1:\n return 2\n if k == 3:\n return 1\n n = k + 1\n if n & n - 1 == 0:\n return k // 2\n else:\n return -1", "def xorcal(k):\n k2 = int(k / 2)\n if k == 1:\n return 2\n if k % 2 == 0:\n return -1\n if k2 ^ k2 + 1 == k:\n return k2\n else:\n return -1", "def xorcal(k):\n n = 1\n result = False\n while n < 100:\n temp = n ^ n + 1\n if k == temp:\n result = True\n break\n else:\n n += 1\n else:\n return -1\n return n", "def xorcal(k):\n for i in range(1, 101):\n if i ^ i + 1 == k:\n return i\n break\n return -1", "def xorcal(k):\n if k % 2 == 0:\n ans = -1\n elif k == 1:\n ans = 2\n elif k == 3:\n ans = 1\n elif k == 7:\n ans = 3\n elif k == 15:\n ans = 7\n elif k == 31:\n ans = 15\n elif k == 63:\n ans = 31\n else:\n ans = -1\n return ans"], "starter_code": "def xorcal(k):\n", "input_output": {"inputs": ["k = 3", "k = 6"], "outputs": ["1", "-1"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/xor-game2143/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "xorcal", "task_id": "TACO_lite/165", "example": [[[3], [6]], ["1", "-1"]]} +{"requirement": "Given a number N denoting candies. Find how many packets are needed to contain the number if 1st packet can contain 1 candy, 2nd packet can contain 2 candies, 3rd packet can contain 4 candies and so on.\nExample 1:\nInput:\nN = 2\nOutput:\n2\nExplanation:\nPut 1 candy in first packet.\nPut 1 candy in second packet.\nThus two,packets are required.\nExample 2:\nInput:\nN = 8\nOutput:\n4\nExplanation:\nPut 1 candy in first packet.\nPut 2 candies in second packet.\nPut 4 candies in third packet.\nPut 1 candy in fourth packet.\nThus 4 packets are required.\nYour Task:\nYou don't need to read input or print anything.Your Task is to complete the function countPackets() which takes a number N as input parameter and returns the number of packets required to contain it.\nExpected Time Complexity:O(logN)\nExpected Auxillary Space:O(1)\nConstraints:\n1<= N <= 10^{18}", "solutions": ["def countpackets(N):\n c = 0\n while N:\n N //= 2\n c += 1\n return c", "def countpackets(N):\n packets = 1\n candies = 1\n k = 1\n while N - candies > 0:\n candies += 2 * k\n k *= 2\n packets += 1\n return packets", "from math import *\n\ndef countpackets(N):\n return ceil(log(N + 1, 2))"], "starter_code": "def countpackets(N):\n", "input_output": {"inputs": ["N = 2", "N = 8"], "outputs": ["2", "4"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/candy-packetssample-test-case-file-to-be-added1632/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(logN)", "entry_point": "countpackets", "task_id": "TACO_lite/217", "example": [[[2], [8]], ["2", "4"]]} +{"requirement": "Implement a function which behaves like the 'uniq -c' command in UNIX. \n\nIt takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance together with the number of times a duplicate elements occurred in the original array.\n\nExample:\n\n```python\n['a','a','b','b','c','a','b','c'] --> [('a',2),('b',2),('c',1),('a',1),('b',1),('c',1)]\n```", "solutions": ["from itertools import groupby\n\ndef uniq_c(seq):\n return [(k, sum((1 for _ in g))) for (k, g) in groupby(seq)]", "def uniq_c(s):\n lst = []\n c = 1\n for i in range(len(s) - 1):\n if s[i] != s[i + 1]:\n lst.append((s[i], c))\n c = 1\n else:\n c += 1\n if s:\n lst.append((s[-1], c))\n return lst", "from itertools import groupby\n\ndef uniq_c(seq):\n return [(chr, len(list(n))) for (chr, n) in groupby(seq)]", "from itertools import groupby\n\ndef uniq_c(seq):\n ans = []\n for (c, e) in groupby(seq):\n l = list(e)\n ans.append((c, len(l)))\n return ans", "uniq_c = lambda l: (lambda x: [(x[i][1], x[i][0] - x[i - 1][0]) if i > 0 else (x[0][1], x[0][0] + 1) for i in range(len(x))])((lambda t: [(t[i][0], t[i][1]) for i in range(len(t) - 1) if t[i][1] != t[i + 1][1]])(list(enumerate(l))) + [(len(l) - 1, l[-1])]) if l != [] else []", "def uniq_c(seq):\n if not seq:\n return []\n res = []\n cur = seq[0]\n counter = 1\n for c in seq[1:]:\n if c == cur:\n counter += 1\n else:\n res.append((cur, counter))\n cur = c\n counter = 1\n res.append((cur, counter))\n return res", "def uniq_c(seq):\n m = []\n (n, i) = (len(seq), 0)\n while i < n:\n c = seq[i]\n j = i + 1\n while j < n and seq[j] == c:\n j += 1\n m.append((c, j - i))\n i = j\n return m", "def uniq_c(seq):\n (stack, out) = ([], [])\n for x in seq:\n if stack and x == stack[-1]:\n stack.append(x)\n elif stack:\n out.append((stack[-1], len(stack)))\n stack.clear()\n stack.append(x)\n else:\n stack.append(x)\n return stack and out + [(stack[-1], len(stack))] or out", "def uniq_c(seq):\n seq.append('asdadasd')\n arr = []\n count = 1\n for i in range(len(seq) - 1):\n if seq[i] == seq[i + 1]:\n count += 1\n else:\n arr.append((seq[i], count))\n count = 1\n return arr", "def uniq_c(seq):\n new_seq = list()\n count = 0\n for i in range(len(seq)):\n if i == 0:\n new_seq.append(seq[i])\n count += 1\n continue\n if seq[i] == seq[i - 1]:\n count += 1\n else:\n new_seq[-1] = (seq[i - 1], count)\n count = 1\n new_seq.append(seq[i])\n if len(seq) != 0:\n new_seq[-1] = (seq[-1], count)\n return new_seq"], "starter_code": "def uniq_c(seq):\n", "input_output": {"fn_name": "uniq_c", "inputs": [[["a", "a", "b", "b", "c", "a", "b", "c"]], [["a", "a", "a", "b", "b", "b", "c", "c", "c"]], [[null, "a", "a"]], [["foo"]], [[""]], [[]]], "outputs": [[[["a", 2], ["b", 2], ["c", 1], ["a", 1], ["b", 1], ["c", 1]]], [[["a", 3], ["b", 3], ["c", 3]]], [[[null, 1], ["a", 2]]], [[["foo", 1]]], [[["", 1]]], [[]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms"], "name": null, "source": "codewars", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/52250aca906b0c28f80003a1", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "uniq_c", "task_id": "TACO_lite/173", "example": [[[["a", "a", "b", "b", "c", "a", "b", "c"]]], ["[('a', 2), ('b', 2), ('c', 1), ('a', 1), ('b', 1), ('c', 1)]"]]} +{"requirement": "Given a string s, remove all its adjacent duplicate characters recursively. \nNote: For some test cases, the resultant string would be an empty string. In that case, the function should return the empty string only.\nExample 1:\nInput:\nS = \"geeksforgeek\"\nOutput: \"gksforgk\"\nExplanation: \ng(ee)ksforg(ee)k -> gksforgk\nExample 2:\nInput: \nS = \"abccbccba\"\nOutput: \"\"\nExplanation: \nab(cc)b(cc)ba->abbba->a(bbb)a->aa->(aa)->\"\"(empty string)\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function rremove() which takes the string S as input parameter and returns the resultant string.\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(|S|)\nConstraints:\n1<=|S|<=10^{5}", "solutions": ["def rremove(S):\n\n def rec(S):\n ans = ''\n n = len(S)\n i = 0\n while i < n:\n if i < n - 1 and S[i] == S[i + 1]:\n while i < n - 1 and S[i] == S[i + 1]:\n i += 1\n else:\n ans += S[i]\n i += 1\n return ans\n s1 = ''\n while len(S) != len(s1):\n s1 = S\n S = rec(S)\n return S", "def rremove(s):\n n = len(s)\n word = []\n i = 0\n while i < len(s):\n flag = 0\n while i < n - 1 and s[i] == s[i + 1]:\n i += 1\n flag = 1\n if not flag:\n word.append(s[i])\n i += 1\n if len(word) < n:\n return self.rremove(''.join(word))\n return ''.join(word)", "def rremove(S):\n new = [i for i in S]\n st = []\n i = 0\n while i < len(S):\n if st and st[-1] == S[i]:\n while i < len(S) and S[i] == st[-1]:\n i += 1\n st.pop()\n if i < len(S):\n st.append(S[i])\n i += 1\n if new == st:\n return ''.join(new)\n else:\n return self.rremove(''.join(st))", "def rremove(S):\n ans = ''\n duplicate = True\n while duplicate:\n i = 0\n duplicate = False\n while i < len(S):\n count = 1\n while i < len(S) - 1 and S[i] == S[i + 1]:\n count += 1\n i += 1\n duplicate = True\n if count == 1:\n ans += S[i]\n i += 1\n if duplicate:\n S = ans\n ans = ''\n return ans", "def remove(S):\n ans = ''\n n = len(S)\n i = 0\n while i < n:\n if i < n - 1 and S[i] == S[i + 1]:\n while i < n - 1 and S[i] == S[i + 1]:\n i += 1\n else:\n ans += S[i]\n i += 1\n return ans\n\ndef rremove(S):\n temp = ''\n while len(S) != len(temp):\n temp = S\n S = self.remove(S)\n return S", "def rremove(S):\n\n def rems(S):\n i = 0\n ans = []\n while i < len(S):\n if i < len(S) - 1:\n if S[i] == S[i + 1]:\n while i < len(S) - 1 and S[i] == S[i + 1]:\n i = i + 1\n else:\n ans.append(S[i])\n else:\n ans.append(S[i])\n i = i + 1\n return ''.join(ans)\n ans = ''\n k = rems(S)\n while len(ans) != len(k):\n ans = k\n k = rems(ans)\n return k", "def rremove(s):\n prev = ''\n temp = ''\n if len(s) < 2:\n return s\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n prev = s[i]\n elif s[i] == prev:\n prev = ''\n else:\n temp += s[i]\n if s[-1] != prev:\n temp += s[-1]\n if len(s) == len(temp):\n return temp\n else:\n return self.rremove(temp)", "def rremove(S):\n new = []\n i = 0\n n = len(S)\n while i < len(S):\n temp = 0\n while i < n - 1 and S[i] == S[i + 1]:\n temp = 1\n i += 1\n if temp == 0:\n new.append(S[i])\n i += 1\n if len(new) < n:\n return self.rremove(new)\n return ''.join(new)", "def rremove(S):\n sn = len(S)\n is_continue = True\n while is_continue:\n is_continue = False\n buffer = []\n i = 0\n while i < sn:\n j = i + 1\n while j < sn and S[j] == S[i]:\n j += 1\n if j == i + 1:\n buffer.append(S[i])\n i += 1\n else:\n is_continue = True\n i = j\n S = ''.join(buffer)\n sn = len(S)\n return S", "def rremove(s):\n res = ''\n i = 0\n while i < len(s):\n if i + 1 < len(s) and s[i] == s[i + 1]:\n i += 1\n while i < len(s) and s[i] == s[i - 1]:\n i += 1\n else:\n res += s[i]\n i += 1\n return res if len(res) == len(s) else self.rremove(res)", "def rremove(S):\n n = len(S)\n flag = True\n while flag:\n flag = False\n arr = []\n i = 0\n while i < n:\n j = i + 1\n while j < n and S[j] == S[i]:\n j += 1\n if j == i + 1:\n arr.append(S[i])\n i += 1\n else:\n flag = True\n i = j\n S = ''.join(arr)\n n = len(S)\n return S", "def rremove(S):\n q = [S]\n newS = ''\n while len(q):\n root = q.pop(0)\n flg = True\n newS = ''\n i = 0\n while i < len(root):\n j = i + 1\n fl = True\n while j < len(root) and root[i] == root[j]:\n j += 1\n fl = False\n flg = False\n if fl:\n newS += root[i]\n i = j\n q.append(newS)\n if flg:\n break\n return newS", "def rremove(S):\n s_list = list(S)\n ns = self._remove(s_list)\n return ''.join(ns)\n\ndef _remove(s_lst):\n ns = []\n prv = None\n lprv = None\n for c in s_lst:\n if c != prv:\n ns.append(c)\n elif lprv != c:\n ns.pop()\n lprv = prv\n prv = c\n if len(ns) == len(s_lst):\n return ns\n return self._remove(ns)", "def rremove(S):\n if not S:\n return S\n global_dups = 0\n final_string = ''\n i = 0\n while i < len(S):\n duplicates = 0\n j = i + 1\n while j < len(S) and S[j] == S[i]:\n duplicates = 1\n global_dups += 1\n j += 1\n i = j - 1\n if not duplicates:\n final_string += S[i]\n i += 1\n return Solution().rremove(final_string) if global_dups else final_string", "def rremove(s):\n\n def remove(s, old):\n if s == '':\n return s\n elif s == old:\n return s\n old = s\n arr = list(s)\n prev = 0\n for i in range(1, len(s)):\n if arr[i] == arr[i - 1]:\n prev = 1\n arr[i - 1] = ''\n elif prev == 1:\n arr[i - 1] = ''\n prev = 0\n if prev == 1:\n arr[i] = ''\n s = ''.join(arr)\n return remove(s, old)\n return remove(s, '')", "def rremove(S):\n\n def remove(s):\n if s == '':\n return ''\n if len(s) == 1:\n return s\n if s[0] == s[1]:\n new_s = ''\n else:\n new_s = s[0]\n i = 1\n while i < len(s) - 1:\n if s[i] != s[i - 1] and s[i] != s[i + 1]:\n new_s += s[i]\n i += 1\n else:\n if s[-1] != s[-2]:\n new_s += s[-1]\n if s == new_s:\n return s\n else:\n return remove(new_s)\n return remove(S)", "def rremove(S):\n if len(S) < 2:\n return S\n i = 0\n j = 1\n is_duplicate = False\n modified = False\n non_duplicates = []\n while j < len(S):\n if S[j] == S[i]:\n j += 1\n is_duplicate = True\n elif is_duplicate:\n i = j\n j += 1\n is_duplicate = False\n modified = True\n else:\n non_duplicates.append(S[i])\n i = j\n j += 1\n if not is_duplicate:\n non_duplicates.append(S[i])\n updated_str = ''.join(non_duplicates)\n if modified:\n return self.rremove(updated_str)\n return updated_str", "def rremove(S):\n if len(S) == 0:\n return ''\n length = len(S)\n dupl_nums = 1\n store = []\n i = 0\n while i < length - 1:\n if S[i] == S[i + 1]:\n start_dupl = i\n dupl_nums = 2\n k = i + 2\n while k < len(S) and S[k] == S[i]:\n dupl_nums += 1\n k += 1\n if len(store) == 0:\n store.append(S[0:start_dupl])\n else:\n store.append(S[next_start:start_dupl])\n next_start = i + dupl_nums\n i += dupl_nums\n else:\n i += 1\n if store:\n if next_start < length:\n store.append(S[next_start:])\n new_string = ''.join(store)\n return self.rremove(new_string)\n else:\n return S\n return S", "def rremove(s):\n a = ''\n b = ''\n if len(s) < 2:\n return s\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n a = s[i]\n elif s[i] == a:\n a = ''\n else:\n b += s[i]\n if s[-1] != a:\n b += s[-1]\n if len(s) == len(b):\n return b\n else:\n return self.rremove(b)", "def rremove(s):\n sm = len(s)\n is_con = True\n while is_con:\n is_con = False\n buf = []\n i = 0\n while i < sm:\n j = i + 1\n while j < sm and s[j] == s[i]:\n j += 1\n if j == i + 1:\n buf.append(s[i])\n i += 1\n else:\n is_con = True\n i = j\n s = ''.join(buf)\n sm = len(s)\n return s", "def rremove(S):\n l = len(S)\n a = []\n d = False\n for i in range(len(S)):\n if i == 0:\n if S[i] != S[i + 1]:\n a.append(S[i])\n elif i < len(S) - 1:\n if S[i] != S[i + 1] and S[i] != S[i - 1]:\n a.append(S[i])\n elif S[-1] != S[-2]:\n a.append(S[-1])\n k = ''.join(a)\n for i in range(len(k) - 1):\n if k[i] == k[i + 1]:\n d = True\n break\n if d:\n return self.rremove(k)\n else:\n return k", "def rremove(S):\n sn = len(S)\n a = True\n while a:\n a = False\n b = []\n i = 0\n while i < sn:\n j = i + 1\n while j < sn and S[j] == S[i]:\n j += 1\n if j == i + 1:\n b.append(S[i])\n i += 1\n else:\n a = True\n i = j\n S = ''.join(b)\n sn = len(S)\n return S", "def rremove(s):\n n = len(s)\n f = True\n while f:\n f = False\n l = []\n i = 0\n while i < n:\n j = i + 1\n while j < n and s[j] == s[i]:\n j = j + 1\n if j == i + 1:\n l.append(s[i])\n i = i + 1\n else:\n f = True\n i = j\n s = ''.join(l)\n n = len(s)\n return s", "import re\n\ndef rremove(S):\n n = len(S)\n k = True\n while k:\n k = False\n b = []\n i = 0\n while i < n:\n j = i + 1\n while j < n and S[j] == S[i]:\n j += 1\n if j == i + 1:\n b.append(S[i])\n i += 1\n else:\n k = True\n i = j\n S = ''.join(b)\n n = len(S)\n return S", "def rremove(S):\n ans = ''\n if len(S) <= 1:\n return S\n for i in range(0, len(S)):\n if i == 0:\n if S[i] != S[i + 1]:\n ans = ans + S[i]\n elif i == len(S) - 1:\n if S[i] != S[i - 1]:\n ans = ans + S[i]\n elif S[i] != S[i - 1] and S[i] != S[i + 1]:\n ans = ans + S[i]\n if len(S) != len(ans):\n return self.rremove(ans)\n return ans", "def rremove(s):\n a = []\n i = 0\n n = len(s)\n while i < len(s):\n temp = 0\n while i < n - 1 and s[i] == s[i + 1]:\n temp = 1\n i += 1\n if temp == 0:\n a.append(s[i])\n i += 1\n if len(a) < n:\n return self.rremove(a)\n return ''.join(a)", "def rremove(S):\n l = len(S)\n con = True\n while con:\n con = False\n buf = []\n i = 0\n while i < l:\n j = i + 1\n while j < l and S[j] == S[i]:\n j += 1\n if j == i + 1:\n buf.append(S[i])\n i += 1\n else:\n con = True\n i = j\n S = ''.join(buf)\n l = len(S)\n return S", "def rremove(s):\n s1 = ''\n while len(s1) != len(s):\n s1 = s\n s = self.fun(s)\n return s\n\ndef fun(s):\n ans = ''\n n = len(s)\n i = 0\n while i < n:\n if i < n - 1 and s[i] == s[i + 1]:\n while i < n - 1 and s[i] == s[i + 1]:\n i += 1\n else:\n ans += s[i]\n i += 1\n return ans", "def rremove(s):\n p = t = ''\n if len(s) < 2:\n return s\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n p = s[i]\n elif s[i] == p:\n p = ''\n else:\n t += s[i]\n if s[-1] != p:\n t += s[-1]\n if len(s) == len(t):\n return t\n else:\n return self.rremove(t)", "def rremove(S):\n newS = ''\n if len(S) == 0:\n return ''\n if len(S) == 1:\n return S\n c = '%'\n S += '&'\n for i in range(len(S) - 1):\n if S[i] == S[i + 1]:\n c = S[i]\n newS += '#'\n elif S[i] == c:\n newS += '#'\n c = '%'\n else:\n newS += S[i]\n newS = newS.replace('#', '')\n S = S[:-1]\n if len(newS) == len(S):\n return S\n return self.rremove(newS)", "def rremove(S):\n\n def rem(s):\n l = [s[0]]\n i = 1\n n = len(s)\n while i < n:\n if s[i] != s[i - 1]:\n l += [s[i]]\n else:\n p = s[i]\n j = i + 1\n if j < n:\n while j < n:\n if s[j] != p:\n l.pop()\n l += [s[j]]\n i = j\n break\n j += 1\n else:\n l.pop()\n i += 1\n return ''.join(l)\n b = S[:]\n while True:\n f = 1\n if b == '' or len(b) == 1:\n return b\n if len(b) == 2:\n if b[0] == b[1]:\n return ''\n else:\n return b\n for i in range(1, len(b)):\n if b[i] == b[i - 1]:\n f = 0\n break\n if f == 0:\n b = rem(b)\n else:\n return b"], "starter_code": "def rremove (S):\n", "input_output": {"inputs": ["S = \"geeksforgeek\"", "S = \"abccbccba\""], "outputs": ["\"gksforgk\"", "\"\""]}, "difficulty": "MEDIUM", "raw_tags": ["Recursion", "Strings", "Algorithms", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/recursively-remove-all-adjacent-duplicates0744/1", "Expected Auxiliary Space": "O(|S|)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "rremove", "task_id": "TACO_lite/206", "example": [[["geeksforgeek"], ["abccbccba"]], ["gksforgk", ""]]} +{"requirement": "Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).\n \nExample 1:\nInput: low = 3, high = 7\nOutput: 3\nExplanation: The odd numbers between 3 and 7 are [3,5,7].\nExample 2:\nInput: low = 8, high = 10\nOutput: 1\nExplanation: The odd numbers between 8 and 10 are [9].\n \nConstraints:\n\n0 <= low <= high <= 10^9", "solutions": ["def countodds(low: int, high: int) -> int:\n if low % 2 != 0:\n low -= 1\n if high % 2 != 0:\n high += 1\n return (high - low) // 2", "def countodds(low: int, high: int) -> int:\n return high - high // 2 - (low - low // 2) + low % 2", "def countodds(low: int, high: int) -> int:\n return (high + 1 >> 1) - (low >> 1)", "def countodds(low: int, high: int) -> int:\n c = 0\n if low < 0 or high > 10 ** 9:\n return\n elif low % 2 != 0 and high % 2 != 0:\n return int((high - low) / 2) + 1\n elif low % 2 == 0 and high % 2 != 0 or (low % 2 != 0 and high % 2 == 0):\n return int((high - low) / 2) + 1\n else:\n return int((high - low) / 2)", "def countodds(low: int, high: int) -> int:\n (odd_lowerbound, odd_upperbound) = (-1, -1)\n if low % 2 == 1:\n odd_lowerbound = low\n else:\n odd_lowerbound = low + 1\n if high % 2 == 1:\n odd_upperbound = high\n else:\n odd_upperbound = high - 1\n return (odd_upperbound - odd_lowerbound) // 2 + 1", "def countodds(low: int, high: int) -> int:\n return (high - low + 1) // 2 + (high % 2 and low % 2)", "def countodds(lo, hi):\n return (hi + 1) // 2 - lo // 2"], "starter_code": "def countodds(low: int, high: int) -> int:\n", "input_output": {"fn_name": "countOdds", "inputs": [[3, 7]], "outputs": [3]}, "difficulty": "EASY", "raw_tags": ["Math"], "name": null, "source": "leetcode", "tags": ["Mathematics"], "skill_types": [], "url": "https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "countodds", "task_id": "TACO_lite/84", "example": [[[3, 7], [8, 10]], ["3", "1"]]} +{"requirement": "Given Two integers L and R find the total number of distinct pairs (p,q) between L and R ( both inclusive ) satisfying the given relationship. p! * q!=k^2 (a perfect square) where p,q,k is any integer and '!' denotes factorial.\nExample 1:\nInput: L = 0, R = 1\nOutput: 1\nExplanation: 1 is the only perfect square\nbetween 0 and 1; \nExample 2:\nInput: L = 9, R = 25\nOutput: 3\nExplanation: 9, 16 and 25 are the perfect \nsquares between 9 and 25. \nYour Task: \nYou don't need to read input or print anything. Complete the function countPerfectSquares() which takes L and R as an input parameter and returns the total number of perfect squares.\nExpected Time Complexity: O(sqrt(N))\nExpected Auxiliary Space: O(1)\nConstraints:\n0<= L <= R <=10^{18}", "solutions": ["import math\n\ndef isPerfectSquare(x):\n if x >= 0:\n sr = math.floor(math.sqrt(x))\n return sr * sr == x\n return False\n\ndef countperfectsquares(L, R):\n if self.isPerfectSquare(L):\n return math.floor(math.sqrt(R)) - math.floor(math.sqrt(L)) + 1\n else:\n return math.floor(math.sqrt(R)) - math.floor(math.sqrt(L))"], "starter_code": "def countperfectsquares (L, R):\n", "input_output": {"inputs": ["L = 0, R = 1", "L = 9, R = 25"], "outputs": ["1", "3"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/factorial-pairs5916/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(sqrt(N))", "entry_point": "countperfectsquares", "task_id": "TACO_lite/236", "example": [[[0, 1], [9, 25]], ["1", "3"]]} +{"requirement": "How many days are we represented in a foreign country?\n\nMy colleagues make business trips to a foreign country. We must find the number of days our company is represented in a country. Every day that one or more colleagues are present in the country is a day that the company is represented. A single day cannot count for more than one day.\n\nWrite a function that recieves a list of pairs and returns the number of days that the company is represented in the foreign country. The first number of the pair is the number of the day of arrival and the second number of the pair is the day of departure of someone who travels, i.e. 1 january is number 1 and 31 of december is 365.\n\nExample:\n```python\ndays_represented([[10,17],[200,207]])\n```\n\nReturns 16 because there are two trips of 8 days, which add up to 16.\n\nHappy coding and rank this kata if you wish ;-)", "solutions": ["def days_represented(a):\n return len({i for (x, y) in a for i in range(x, y + 1)})", "def days_represented(trips):\n L = []\n for i in trips:\n for j in range(i[0], i[1] + 1):\n L.append(j)\n a = set(L)\n return len(a)", "def days_represented(trips):\n return len({i for (start, stop) in trips for i in range(start, stop + 1)})", "def days_represented(trips):\n arr = [0] * 365\n for (a, b) in trips:\n arr[a:b + 1] = [1] * (b - a + 1)\n return sum(arr)", "def days_represented(trips):\n total = 0\n visited = []\n for i in range(len(trips)):\n trip = trips[i]\n arrival = trip[1]\n departure = trip[0]\n for j in range(departure, arrival + 1):\n if j not in visited:\n visited.append(j)\n else:\n continue\n return len(visited)", "def days_represented(trips):\n accumulator = set()\n for (a, b) in trips:\n accumulator |= set(range(a, b + 1))\n return len(accumulator)", "def days_represented(trips):\n new = []\n for days in trips:\n for day in range(days[0], days[1] + 1):\n new.append(day)\n p = set(new)\n return len(p)", "from itertools import chain\n\ndef days_represented(trips):\n return len(set(chain(*(range(a, b + 1) for (a, b) in trips))))"], "starter_code": "def days_represented(trips):\n", "input_output": {"fn_name": "days_represented", "inputs": [[[[10, 15], [25, 35]]], [[[2, 8], [220, 229], [10, 16]]]], "outputs": [[17], [24]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Lists"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/58e93b4706db4d24ee000096", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "days_represented", "task_id": "TACO_lite/237", "example": [[[[[10, 17], [200, 207]]]], ["16"]]} +{"requirement": "A sorted(in ascending order) array A[ ] with distinct elements is rotated at some unknown point, the task is to find the minimum element in it.\nExample 1\nInput:\nN = 5\narr[] = {4 ,5 ,1 ,2 ,3}\nOutput: 1\nExplanation: 1 is the minimum element inthe array.\nExample 2\nInput:\nN = 7\narr[] = {10, 20, 30, 40, 50, 5, 7}\nOutput: 5\nExplanation: Here 5 is the minimum element.\n \nYour Task:\nComplete the function findMin() which takes an array arr[] and n, size of the array as input parameters, and returns the minimum element of the array.\nExpected Time Complexity: O(log N).\nExpected Auxiliary Space: O(log N).\nConstraints:\n1 ≤ N ≤ 100000\n1 ≤ A[i] ≤ 1000000", "solutions": ["def findmin(arr, n):\n return min(arr)", "import sys\n\ndef findmin(arr, n):\n mini = sys.maxsize\n for i in arr:\n if i < mini:\n mini = i\n return mini", "def findmin(arr, n):\n smallest_number = arr[0]\n for number in range(n):\n if arr[number] < smallest_number:\n smallest_number = arr[number]\n return smallest_number", "def findmin(arr, n):\n (start, end) = (0, n - 1)\n while start < end:\n mid = start + (end - start) // 2\n if arr[mid] > arr[end]:\n start = mid + 1\n else:\n end = mid\n return arr[start]", "def findmin(arr, n):\n i = 0\n j = n - 1\n if arr[0] < arr[j]:\n return arr[0]\n while i <= j:\n mid = (i + j) // 2\n if arr[mid] < arr[mid - 1]:\n return arr[mid]\n if arr[mid] > arr[0]:\n i = mid + 1\n else:\n j = mid", "def findmin(A, n):\n min = A[0]\n l = 0\n h = n - 1\n while l <= h:\n mid = (l + h) // 2\n if A[mid] < min:\n min = A[mid]\n elif A[mid] >= A[l] and A[mid] >= A[h]:\n l = mid + 1\n else:\n h = mid - 1\n return min", "def findmin(arr, n):\n\n def findminUtil(arr, start, end, minimum):\n if end == start:\n return min(minimum, arr[start])\n elif end - start <= 1:\n return min(minimum, arr[start], arr[end])\n mid = (start + end) // 2\n if arr[mid] > arr[start]:\n minimum = min(minimum, findminUtil(arr, mid + 1, end, minimum), arr[start])\n else:\n minimum = min(minimum, findminUtil(arr, start, mid, minimum), arr[mid + 1])\n return minimum\n return findminUtil(arr, 0, n - 1, float('inf'))", "def findmin(arr, n):\n (lo, hi) = (0, n - 1)\n while lo < hi:\n mid = (lo + hi) // 2\n if arr[mid] < arr[hi]:\n hi = mid\n else:\n lo = mid + 1\n return arr[lo]", "def findmin(arr, n):\n (l, r) = (0, n - 1)\n while l <= r:\n mid = l + (r - l) // 2\n if mid == 0 or arr[mid - 1] > arr[mid]:\n return arr[mid]\n elif arr[mid] < arr[l]:\n r = mid - 1\n elif arr[mid] > arr[r]:\n l = mid + 1\n else:\n return arr[l]\n return -1", "def findmin(arr, n):\n start = 0\n end = len(arr) - 1\n while start < end:\n middle = start + (end - start) // 2\n if arr[middle] > arr[end]:\n start = middle + 1\n elif arr[middle] < arr[end]:\n end = middle\n else:\n end -= 1\n return arr[start]", "def findmin(arr, n):\n arr.sort()\n return arr[0]", "def findmin(arr, n):\n left = 0\n right = n - 1\n while left <= right:\n mid = (left + right) // 2\n previous = (mid - 1) % n\n next1 = (mid + 1) % n\n if arr[mid] <= arr[previous] and arr[mid] <= arr[next1]:\n return arr[mid]\n if arr[mid] <= arr[right]:\n right = mid - 1\n elif arr[left] <= arr[mid]:\n left = mid + 1", "def findmin(arr, n):\n res = arr[0]\n l = 0\n h = len(arr) - 1\n while l <= h:\n if arr[l] < arr[h]:\n res = min(res, arr[l])\n break\n mid = (l + h) // 2\n res = min(res, arr[mid])\n if arr[mid] >= arr[l]:\n l = mid + 1\n else:\n h = mid - 1\n return res", "import heapq\n\ndef findmin(arr, n):\n (left, right) = (0, n - 1)\n while left <= right:\n mid = (left + right) // 2\n prev = (mid - 1) % n\n next = (mid + 1) % n\n if arr[mid] <= arr[prev] and arr[mid] <= arr[next]:\n return arr[mid]\n elif arr[mid] <= arr[right]:\n right = mid - 1\n elif arr[mid] >= arr[left]:\n left = mid + 1", "import heapq\n\ndef findmin(arr, n):\n return heapq.nsmallest(1, arr)[0]", "def findmin(nums, n):\n if len(nums) is 1:\n return nums[0]\n leftSmaller = True if nums[0] < nums[-1] else False\n if leftSmaller:\n return nums[0]\n if len(nums) is 2:\n return min(nums)\n start = 0\n end = len(nums) - 1\n while start <= end:\n mid = (start + end) // 2\n if nums[mid] < nums[mid - 1]:\n return nums[mid]\n elif nums[mid] < nums[end]:\n end = mid - 1\n else:\n start = mid + 1\n return 0", "def findmin(arr, n):\n first = 0\n end = n - 1\n if arr[first] < arr[end]:\n return arr[first]\n while first < end:\n mid = (first + end) // 2\n if arr[mid] > arr[mid + 1]:\n return arr[mid + 1]\n elif arr[mid] < arr[first]:\n end = mid\n else:\n first = mid", "def findmin(arr, n):\n left = 0\n right = n - 1\n if arr[left] < arr[right]:\n return arr[left]\n while left < right:\n mid = (left + right) // 2\n if arr[mid] > arr[mid + 1]:\n return arr[mid + 1]\n elif arr[mid] < arr[left]:\n right = mid\n else:\n left = mid", "def findmin(arr, n):\n l = 0\n h = n - 1\n if arr[l] <= arr[h]:\n return arr[l]\n while l <= h:\n m = (l + h) // 2\n if arr[m] < arr[m - 1]:\n return arr[m]\n if arr[m] > arr[h]:\n l = m + 1\n else:\n h = m - 1", "def findmin(nums, n):\n (left, right) = (0, n - 1)\n if n <= 1 or nums[left] < nums[right]:\n return nums[left]\n while left < right:\n mid = (left + right) // 2\n (prev, curr, next) = (nums[mid - 1], nums[mid], nums[mid + 1])\n if curr > next:\n return next\n if prev > curr:\n return curr\n if nums[0] < curr:\n left = mid + 1\n else:\n right = mid - 1", "def findmin(arr, n):\n min = arr[0]\n for i in range(n):\n if arr[i] < min:\n min = arr[i]\n return min", "def findmin(arr, n):\n min1 = 100000\n i = 0\n j = n - 1\n while i <= j:\n if arr[i] < arr[j]:\n min1 = min(arr[i], min1)\n break\n mid = int(i + (j - i) / 2)\n if arr[i] <= arr[mid]:\n min1 = min(min1, arr[i])\n i = mid + 1\n else:\n min1 = min(min1, arr[mid])\n j = mid - 1\n return min1", "def findmin(arr, n):\n l = 0\n r = n - 1\n while l <= r:\n mid = (l + r) // 2\n if arr[l] <= arr[mid] and arr[mid] <= arr[r]:\n return arr[l]\n elif arr[r] >= arr[mid] and arr[mid] >= arr[l]:\n return arr[r]\n elif r - l == 1:\n return min(arr[r], arr[l])\n elif arr[l] < arr[mid]:\n l = mid\n elif arr[mid] < arr[r]:\n r = mid", "def findmin(arr, n):\n m = arr[-1]\n for i in range(n - 2, -1, -1):\n if arr[i] < m:\n m = arr[i]\n return m", "def findmin(arr, n):\n v = sorted(arr)\n return min(v)", "def findmin(arr, n):\n (low, high) = (0, n)\n while low < high:\n mid = (low + high) // 2\n if arr[0] <= arr[mid]:\n low = mid + 1\n else:\n high = mid\n if low == n:\n low = 0\n return arr[low]", "def findmin(arr, n):\n arr.sort()\n res = min(arr)\n return res", "import sys\nintmax = sys.maxsize\n\ndef findmin(arr, n):\n l = 0\n r = n - 1\n while l <= r:\n mid = (l + r) // 2\n if arr[l] >= arr[mid] and arr[mid] >= arr[r]:\n return arr[r]\n if mid == 0 or arr[mid - 1] > arr[mid]:\n return arr[mid]\n if arr[mid] < arr[l]:\n r = mid - 1\n elif arr[mid] > arr[r]:\n l = mid + 1\n else:\n return arr[l]\n return -1", "import sys\nintmax = sys.maxsize\n\ndef findmin(arr, n):\n t = intmax\n p = -1\n for i in range(n):\n if arr[i] <= t:\n t = arr[i]\n p = i\n return t", "import sys\n\ndef findmin(arr, n):\n low = 0\n high = n - 1\n minVal = sys.maxsize\n while low <= high:\n mid = (low + high) // 2\n if arr[low] <= arr[high]:\n minVal = min(minVal, arr[low])\n break\n elif arr[low] <= arr[mid]:\n minVal = min(minVal, arr[low])\n low = mid + 1\n else:\n minVal = min(minVal, arr[mid])\n high = mid - 1\n return minVal", "def findmin(nums, n):\n low = 0\n high = n - 1\n while low < high:\n mid = low + high >> 1\n if nums[mid] > nums[high]:\n low = mid + 1\n else:\n high = mid\n return nums[low]", "def findmin(arr, n):\n low = 0\n high = n - 1\n while low <= high:\n mid = (high - low) // 2 + low\n prev = (mid + n - 1) % n\n next = (mid + 1) % n\n if arr[mid] <= arr[prev] and arr[mid] <= arr[high]:\n return arr[mid]\n elif arr[mid] <= arr[high]:\n high = mid - 1\n else:\n low = mid + 1", "def findmin(arr, n):\n (left, right) = (0, n - 1)\n ans = arr[left]\n while left <= right:\n if arr[left] < arr[right]:\n return min(ans, arr[left])\n break\n mid = (left + right) // 2\n ans = min(ans, arr[mid])\n if arr[left] <= arr[mid]:\n left = mid + 1\n else:\n right = mid - 1\n return ans", "def findmin(nums, n):\n high = len(nums) - 1\n low = 0\n ans = 999999\n while high >= low:\n mid = (low + high) // 2\n if nums[mid] < ans:\n ans = nums[mid]\n if nums[low] < nums[mid] and nums[mid] < nums[high]:\n if nums[low] < nums[high]:\n high = mid - 1\n else:\n low = mid + 1\n elif nums[mid] >= nums[low]:\n low = mid + 1\n else:\n high = mid - 1\n return ans", "def findmin(arr, n):\n for i in range(1, len(arr)):\n if arr[i] < arr[i - 1]:\n return arr[i]\n return arr[0]", "def findmin(arr, n):\n first = 0\n last = len(arr) - 1\n while first < last:\n mid = (first + last) // 2\n if arr[mid] < arr[last]:\n last = mid\n else:\n first = mid + 1\n return arr[first]", "import math\n\ndef findmin(a, n):\n beg = 0\n end = n - 1\n min_ele = float('inf')\n while beg < end:\n min_ele = min(min_ele, a[beg])\n mid = math.ceil((beg + end) / 2.0)\n if a[beg] < a[mid]:\n beg = mid + 1\n else:\n min_ele = min(min_ele, a[mid])\n end = mid - 1\n min_ele = min(min_ele, a[end])\n return min_ele", "def findmin(arr, n):\n (low, high) = (0, n - 1)\n mini = float('inf')\n while low <= high:\n if arr[low] <= arr[high]:\n mini = min(arr[low], mini)\n break\n mid = (low + high) // 2\n if arr[low] <= arr[mid]:\n mini = min(mini, arr[low])\n low = mid + 1\n else:\n mini = min(mini, arr[mid])\n high = mid - 1\n return mini", "def findmin(arr, n):\n left = 0\n right = n - 1\n minVal = float('inf')\n while left <= right:\n if arr[left] <= arr[right]:\n minVal = min(minVal, arr[left])\n break\n mid = (left + right) // 2\n if arr[left] <= arr[mid] and arr[left] >= arr[right]:\n left = mid + 1\n elif arr[mid] <= arr[left] and arr[mid] <= arr[right]:\n minVal = min(minVal, arr[mid])\n right = mid - 1\n else:\n right = mid\n return minVal", "def findmin(nums, n):\n n = len(nums)\n (s, e) = (0, n - 1)\n while s < e:\n mid = s + e >> 1\n if nums[s] <= nums[e]:\n return nums[s]\n if nums[mid] >= nums[s]:\n s = mid + 1\n else:\n e = mid\n return nums[s]", "import numpy as np\n\ndef findmin(arr, n):\n arr = np.array(arr)\n return np.min(arr)", "def findmin(arr, n):\n l = 0\n r = len(arr) - 1\n while l < r:\n m = (l + r) // 2\n if arr[m] > arr[r]:\n l = m + 1\n else:\n r = m\n return arr[l]"], "starter_code": "def findmin(arr, n):\n", "input_output": {"inputs": ["N = 5\r\narr[] = {4 ,5 ,1 ,2 ,3}", "N = 7\r\narr[] = {10, 20, 30, 40, 50, 5, 7}"], "outputs": ["1", "5"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Searching"], "name": null, "source": "geeksforgeeks", "tags": ["Complete search"], "skill_types": ["Complete search"], "url": "https://practice.geeksforgeeks.org/problems/minimum-element-in-a-sorted-and-rotated-array3611/1", "Expected Auxiliary Space": "O(log N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log N).", "entry_point": "findmin", "task_id": "TACO_lite/209", "example": [[[5, [4, 5, 1, 2, 3]], [7, [10, 20, 30, 40, 50, 5, 7]]], ["1", "5"]]} +{"requirement": "Create a function\n\n```python\nhas_two_cube_sums(n)\n```\n\nwhich checks if a given number `n` can be written as the sum of two cubes in two different ways: `n = a³+b³ = c³+d³`.\nAll the numbers `a`, `b`, `c` and `d` should be different and greater than `0`.\n\nE.g. 1729 = 9³+10³ = 1³+12³.\n\n```python\nhas_two_cube_sums(1729); // true\nhas_two_cube_sums(42); // false\n```", "solutions": ["def has_two_cube_sums(n):\n cubic_list = [i ** 3 for i in range(1, int(n ** (1.0 / 3.0)) + 1)]\n return sum([n != 2 * c and n - c in cubic_list for c in cubic_list]) > 3", "def has_two_cube_sums(n):\n x = 0\n for a in range(int(n ** 0.35)):\n for b in range(a, int(n ** 0.35)):\n if a ** 3 + b ** 3 == n:\n x += 1\n if x > 1:\n return True\n return False", "from itertools import combinations\ns = {a ** 3 + b ** 3 for (a, b) in combinations(range(1, 1000), 2)}\ns.discard(19 ** 3 + 34 ** 3)\n\ndef has_two_cube_sums(n):\n return n in s", "def has_two_cube_sums(n):\n if n == 1:\n return False\n high = int(n ** (1 / 3.0))\n low = int((n / 2) ** (1 / 3.0))\n return sum((abs(y - round(y)) < 1e-08 for y in [(n - x ** 3) ** (1 / 3.0) for x in range(low, high + 1)])) >= 2", "def has_two_cube_sums(n):\n return len([[y, z] for y in range(1, int(n ** (1 / 3)) + 1) for z in [x for x in range(1, int(n ** (1 / 3)) + 1)] if y != z and y ** 3 + z ** 3 == n]) >= 4", "has_two_cube_sums = lambda n: sum([i[0] ** 3 + i[1] ** 3 == n for i in __import__('itertools').permutations(range(1, int(n ** (1.0 / 3.0)) + 1), 2)]) >= 4"], "starter_code": "def has_two_cube_sums(n):\n", "input_output": {"fn_name": "has_two_cube_sums", "inputs": [[1], [1729], [42], [4103], [4102], [4104], [4105], [4106], [0], [46163]], "outputs": [[false], [true], [false], [false], [false], [true], [false], [false], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/55fd4919ce2a1d7c0d0000f3", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "has_two_cube_sums", "task_id": "TACO_lite/239", "example": [[], []]} +{"requirement": "Given a rectangle of size L x B. Find the minimum number of squares required to fill the rectangle such that no two square overlaps.\nExample 1:\nInput: L = 4, B = 5\nOutput: 5\nExplaination: One 4*4 square and four 1*1 \nsquares are required.\nExample 2:\nInput: L = 2, B = 4\nOutput: 2\nExplaintion: Two 2*2 squares are enough to \nfill the rectangle.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function minSquares() which takes L and B as input parameters and returns minimum number of squares required to fill the rectangle. Return the answer modulo 10^{9} + 7.\nExpected Time Complexity: O(log(max(L, B)))\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ L, B ≤ 10^{10}", "solutions": ["def minsquares(L, B):\n p = 1000000007\n if L == 1:\n return B % p\n if B == 1:\n return L % p\n ans = 0\n while L > 0 and B > 0:\n if L > B:\n ans = (ans + L // B) % p\n L = L % B\n else:\n ans = (ans + B // L) % p\n B = B % L\n return ans % p", "def minsquares(l, b):\n p = 1000000007\n if l == 1:\n return b % p\n if b == 1:\n return l % p\n ans = 0\n while l > 0 and b > 0:\n if l > b:\n ans = (ans + l // b) % p\n l = l % b\n else:\n ans = (ans + b // l) % p\n b = b % l\n return ans % p", "import math\n\ndef minsquares(L, B):\n if L > B:\n (L, B) = (B, L)\n res = 0\n while L:\n res += B // L\n B %= L\n if L > B:\n (B, L) = (L, B)\n return res % 1000000007", "def minsquares(L, B):\n cnt = 0\n while True:\n if L == B or L <= 0 or B <= 0:\n if L == 0 or B == 0:\n break\n else:\n cnt += 1\n break\n elif L < B:\n temp = B // L\n cnt += temp\n B -= L * temp\n else:\n temp = L // B\n cnt += temp\n L -= B * temp\n return cnt % (10 ** 9 + 7)", "def minsquares(L, B):\n if L > B:\n L = L + B\n B = L - B\n L = L - B\n if B % L == 0:\n return B // L % 1000000007\n else:\n r = B % L\n sum = B // L\n while r != 0:\n sum += L // r\n B = L\n L = r\n r = B % L\n return sum % 1000000007", "def minsquares(L, B):\n count = 0\n while L >= 0 or B >= 0:\n if L == 0 or B == 0:\n return count % (10 ** 9 + 7)\n if L == 1:\n count += B\n return count % (10 ** 9 + 7)\n if B == 1:\n count += L\n return count % (10 ** 9 + 7)\n if L > B and B != 0:\n x = L // B\n L -= B * x\n count += x\n if B >= L and L != 0:\n y = B // L\n B -= L * y\n count += y", "def solve(L, B):\n mod = 10 ** 9 + 7\n if L == B:\n return 1\n if B == 0 or L == 0:\n return 0\n if L == 1 or B == 1:\n return max(L, B)\n if L > B:\n return self.solve(B, L)\n return B // L + self.solve(L, B % L) % mod\n\ndef minsquares(L, B):\n mod = 10 ** 9 + 7\n return int(self.solve(L, B)) % mod", "def minsquares(l, b):\n mod = pow(10, 9) + 7\n\n def solve(l, b):\n if l == 0 or b == 0:\n return 0\n if l >= b:\n return l // b + solve(l % b, b)\n if l < b:\n return b // l + solve(l, b % l)\n return solve(l, b) % mod"], "starter_code": "def minsquares(L, B):\n", "input_output": {"inputs": ["L = 4, B = 5", "L = 2, B = 4"], "outputs": ["5", "2"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/squares-in-reactangle3340/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(max(L, B)))", "entry_point": "minsquares", "task_id": "TACO_lite/235", "example": [[[4, 5], [2, 4]], ["5", "2"]]} +{"requirement": "Your task is to calculate sum of primes present as digits of given number N.\nExample 1:\nInput: 333\nOutput: 9\nExplaination: 3 is a prime number. It \nis present 3 times. So 3+3+3 = 9.\nExample 2:\nInput: 686\nOutput: 0\nExplaination: Neither 6 nor 8 is a \nprime number.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function primeSum() which takes N as input parameter and returns the sum of all the prime digits present in the number N.\nExpected Time Complexity: O(logN)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ N ≤ 5*10^{4}", "solutions": ["import math\n\ndef primesum(N):\n\n def prime(n):\n if n <= 1:\n return False\n for i in range(2, int(math.sqrt(n) + 1)):\n if n % i == 0:\n return False\n return True\n c = 0\n m = []\n while N > 0:\n d = N % 10\n m.append(d)\n N = N // 10\n for i in m:\n if prime(i):\n c += i\n return c", "def primesum(N):\n s = 0\n N = str(N)\n for i in N[::1]:\n i = int(i)\n if i == 2 or i == 3 or i == 5 or (i == 7):\n s += i\n return s", "def primesum(N):\n\n def prime(n):\n if n == 0 or n == 1:\n return 0\n for i in range(2, int(n // 2) + 1):\n if n % i == 0:\n return 0\n return 1\n count = 0\n for i in str(N):\n if prime(int(i)) == 1:\n count += int(i)\n return count", "def primesum(N):\n n = str(N)\n s = 0\n for i in n:\n count = 0\n m = int(i)\n for j in range(1, m + 1):\n if m % j == 0:\n count += 1\n if count == 2:\n s += m\n return s", "import math\n\ndef primesum(N):\n\n def isPrime(n):\n if n == 1:\n return 0\n for i in range(2, int(math.sqrt(n) + 1)):\n if n % i == 0:\n return 0\n return 1\n a = set()\n val = 0\n for i in str(N):\n if int(i) in a:\n val += int(i)\n elif isPrime(int(i)) == 1:\n a.add(int(i))\n val += int(i)\n return val", "def primesum(N):\n sum = 0\n while N != 0:\n a = N % 10\n N = N // 10\n if a == 2 or a == 3 or a == 5 or (a == 7):\n sum = sum + a\n return sum", "def primesum(N):\n\n def prime(n):\n if n <= 1:\n return False\n for i in range(2, n):\n if n % i == 0:\n return False\n return True\n s = 0\n while N:\n r = N % 10\n if prime(r):\n s = s + r\n N = N // 10\n return s", "import math\n\ndef fun(n):\n if n == 0 or n == 1:\n return False\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\ndef primesum(N):\n s = str(N)\n c = 0\n for i in s:\n if fun(int(i)):\n c += int(i)\n return c", "def primesum(n):\n su = 0\n s = str(n)\n for i in s:\n i = int(i)\n c = 0\n for j in range(1, i):\n if i % j == 0:\n c += 1\n if c == 1:\n su += i\n return su", "def primesum(N):\n\n def is_prime(n):\n import math\n a = int(math.sqrt(n))\n if n < 2:\n return False\n for i in range(2, a + 1):\n if n % i == 0:\n return False\n return True\n s = 0\n l = []\n while N:\n d = N % 10\n N = N // 10\n if is_prime(d) == True:\n l.append(d)\n return sum(l)", "def primesum(N):\n x = str(N)\n k = 0\n l = []\n for i in x:\n c = 0\n h = int(i)\n if h == 1:\n continue\n for j in range(2, h):\n if h % j == 0:\n c = 1\n break\n if c == 0:\n l.append(i)\n for i in l:\n k += int(i)\n return k", "def isprime(n):\n if n <= 1:\n return False\n i = 2\n while i * i <= n:\n if n % i == 0:\n return False\n i += 1\n return True\n\ndef primesum(N):\n N = list(str(N))\n summ = 0\n for i in N:\n if self.isprime(int(i)):\n summ += int(i)\n return summ", "def primesum(N):\n import math\n\n def is_prime(n):\n if n < 2:\n return False\n s = int(math.sqrt(n))\n for i in range(2, s + 1):\n if n % i == 0:\n return False\n return True\n s = str(N)\n l = list(map(int, s))\n a = []\n for i in l:\n if is_prime(i) == True:\n a.append(i)\n return sum(a)", "from math import sqrt\n\ndef primesum(N):\n sumOfPrime = 0\n while N:\n digit = N % 10\n prime = self.isPrime(digit)\n if prime:\n sumOfPrime += digit\n N //= 10\n return sumOfPrime\n\ndef isPrime(N):\n if N == 1 or N == 0:\n return False\n for i in range(2, int(sqrt(N)) + 1):\n if N % i == 0:\n return False\n return True", "import math\n\ndef primesum(N):\n\n def isprime(num):\n if num < 2:\n return False\n for i in range(2, int(math.sqrt(num)) + 1):\n if num % i == 0:\n return False\n return True\n primesum = 0\n for digit in str(N):\n if isprime(int(digit)):\n primesum += int(digit)\n return primesum", "def primesum(N):\n s = 0\n while N > 0:\n r = N % 10\n p = 0\n if r <= 1:\n p = 1\n for i in range(2, int(r ** 0.5) + 1):\n if r % i == 0:\n p += 1\n if p == 0:\n s += r\n N = N // 10\n return s", "def primesum(n):\n import math\n\n def prime(n):\n if n == 1 or n == 0:\n return False\n k = int(math.sqrt(n))\n for i in range(2, k + 1):\n if n % i == 0:\n return False\n return True\n sum = 0\n while n:\n d = n % 10\n if prime(d):\n sum += d\n n = n // 10\n return sum", "import math\n\ndef primesum(N):\n\n def prime(N):\n if N < 2:\n return False\n s = int(math.sqrt(N))\n for i in range(2, s + 1):\n if N % i == 0:\n return False\n return True\n c = 0\n for j in str(N):\n if prime(int(j)) == True:\n c += int(j)\n return c", "import math\n\ndef primesum(N):\n s = str(N)\n v = 0\n for i in s:\n n = int(i)\n c = 0\n for i in range(2, int(math.sqrt(n) + 1)):\n if n % i == 0:\n c += 1\n if c == 0 and n != 1:\n v = v + n\n return v", "def primesum(N):\n a = []\n sum = 0\n while N != 0:\n c = N % 10\n N = N // 10\n if c <= 1:\n continue\n f = 0\n for i in range(2, int(c ** 0.5) + 1):\n if c % i == 0:\n f = 1\n break\n if f == 0:\n sum = sum + c\n return sum", "def primesum(N):\n a = []\n b = []\n l = str(N)\n for i in l:\n if int(i) > 1:\n for j in range(2, int(int(i) ** 0.5) + 1):\n if int(i) % int(j) == 0:\n break\n else:\n a.append(i)\n lst = list(map(int, a))\n return sum(lst)", "def primesum(N):\n a = str(N)\n b = []\n for i in a:\n if int(i) > 1:\n for j in range(2, int(int(i) ** 0.5) + 1):\n if int(i) % j == 0:\n break\n else:\n b.append(int(i))\n if len(b) == 0:\n return 0\n else:\n return sum(b)", "import math\n\ndef isPrime(N):\n if N <= 1:\n return 0\n for i in range(2, int(math.sqrt(N) + 1)):\n if N % i == 0:\n return 0\n i += 1\n return 1\n\ndef primesum(N):\n N = list(str(N))\n sum = 0\n for i in N:\n if self.isPrime(int(i)):\n sum += int(i)\n return sum", "def primesum(N):\n prime_sum = 0\n for digit in str(N):\n num = int(digit)\n if self.isPrime(num):\n prime_sum += num\n return prime_sum\n\ndef isPrime(num):\n if num < 2:\n return False\n if num == 2 or num == 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n for i in range(3, int(num ** 0.5) + 1, 2):\n if num % i == 0:\n return Fals\n return True", "import math\n\ndef primesum(N):\n s = int(math.sqrt(N))\n for i in range(2, s + 1):\n if i < 2:\n return 0\n s = 0\n for i in str(N):\n if i == '2' or i == '3' or i == '5' or (i == '7'):\n s += int(i)\n return s", "def primesum(N):\n sum = 0\n\n def prime(n):\n if n < 2:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n while N:\n d = N % 10\n if prime(d):\n sum = sum + d\n N = N // 10\n return sum", "def primesum(N):\n l = []\n while N != 0:\n r = N % 10\n l.append(r)\n N = N // 10\n k = []\n for i in l:\n c = 0\n for j in range(1, i):\n if i % j == 0:\n c = c + 1\n if c == 1:\n k.append(i)\n return sum(k)", "def primesum(N):\n c = 0\n for i in str(N):\n s = int(i)\n if s == 2:\n c += 2\n elif s % 2 == 0 or s == 1:\n continue\n else:\n for i in range(2, int(s ** 0.5) + 1):\n if s % i == 0:\n break\n else:\n c += s\n return c", "import math\n\ndef is_prime(n):\n if n < 2:\n return False\n s = int(math.sqrt(n))\n for i in range(2, s + 1):\n if n % i == 0:\n return False\n return True\n\ndef primesum(N):\n c = 0\n lst = []\n while N:\n x = N % 10\n N = N // 10\n lst.append(x)\n for i in lst:\n if is_prime(i) == True:\n c += i\n return c", "def primesum(R):\n import math\n sm = 0\n\n def is_prime(N):\n if N < 2:\n return False\n s = int(math.sqrt(N))\n for i in range(2, s + 1):\n if N % i == 0:\n return False\n return True\n while R:\n rem = R % 10\n R = R // 10\n if is_prime(rem):\n sm += rem\n return sm", "def primesum(N):\n\n def is_prime(num):\n if num < 2:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return False\n return True\n digits = str(N)\n prime_sum = 0\n for digit in digits:\n if is_prime(int(digit)):\n prime_sum += int(digit)\n return prime_sum", "import math\n\ndef isprime(v):\n if v < 2:\n return 0\n for i in range(2, int(math.sqrt(v)) + 1):\n if v % i == 0:\n return 0\n return 1\n\ndef primesum(N):\n a = list(str(N))\n v = list(map(int, a))\n s = 0\n for i in v:\n if isprime(i):\n s += i\n return s", "import math\n\ndef isprime(N):\n if N <= 1:\n return False\n i = 2\n while i * i <= N:\n if N % i == 0:\n return False\n i += 1\n return True\n\ndef primesum(N):\n N = list(str(N))\n s = 0\n for i in N:\n if self.isprime(int(i)):\n s += int(i)\n return s", "import math\n\ndef primesum(N):\n sumo = 0\n while N != 0:\n d = N % 10\n c = 0\n if d <= 1:\n c = 1\n s = int(math.sqrt(d))\n for i in range(2, s + 1):\n if d % i == 0:\n c = 1\n if c == 0:\n sumo += d\n N = N // 10\n return sumo", "import math\n\ndef primesum(N):\n\n def isPrime(N):\n c = 0\n if N < 2:\n return False\n s = int(math.sqrt(N))\n for i in range(2, s + 1):\n if N % i == 0:\n c = c + 1\n if c == 0:\n return 1\n else:\n return 0\n s = str(N)\n k = []\n c = 0\n for i in s:\n k.append(int(i))\n for j in k:\n if isPrime(j) == 1:\n c = c + j\n return c", "import math\n\ndef primesum(N):\n p = str(N)\n l = list(p)\n s = 0\n for i in l:\n k = int(i)\n if k < 2:\n continue\n e = int(math.sqrt(k))\n for j in range(2, e + 1):\n if k % j == 0:\n break\n else:\n s += k\n return s", "def primesum(n):\n s = 0\n\n def prime(x):\n fc = 0\n for i in range(1, x + 1):\n if x % i == 0:\n fc += 1\n if fc == 2:\n return True\n else:\n return False\n while n:\n r = n % 10\n if prime(r):\n s += r\n n = n // 10\n return s", "def isPrime(N):\n if N <= 1:\n return False\n i = 2\n while i * i <= N:\n if N % i == 0:\n return False\n i += 1\n return True\n\ndef primesum(N):\n N = list(str(N))\n s = 0\n for i in N:\n if self.isPrime(int(i)):\n s += int(i)\n return s", "def primesum(N):\n sp = 0\n for i in str(N):\n if i == '1' or i == '0':\n pass\n else:\n s = int(int(i) ** 0.5)\n count = 0\n for j in range(2, s + 1):\n if int(i) % j == 0:\n count += 1\n if count == 0:\n sp = sp + int(i)\n return sp", "import math as m\n\ndef primesum(n):\n n = str(n)\n n = list(n)\n n = [eval(i) for i in n]\n sm = 0\n for i in n:\n c = 0\n b = int(m.sqrt(i))\n if i == 1:\n continue\n for j in range(1, b + 1):\n if i % j == 0:\n c += 1\n if c == 1:\n sm = sm + i\n c = 0\n return sm", "def primesum(n):\n e = []\n while n > 0:\n r = n % 10\n c = 0\n if r == 1:\n c += 1\n for i in range(2, int(r ** 0.5) + 1):\n if r % i == 0:\n c = 1\n break\n if c > 0:\n pass\n else:\n e.append(r)\n n = n // 10\n return sum(e)", "import math\n\ndef primesum(N):\n x = 0\n while N != 0:\n r = N % 10\n N = N // 10\n c = 0\n if r == 1:\n c += 1\n for i in range(2, int(math.sqrt(r)) + 1):\n if r % i == 0:\n c += 1\n break\n if c == 0:\n x += r\n return x", "import math\n\ndef primesum(N):\n\n def isPrime(N):\n f = 0\n if N == 1:\n return 0\n for i in range(2, int(math.sqrt(N) + 1)):\n if N % i == 0:\n return 0\n else:\n return 1\n s = 0\n while N > 0:\n r = N % 10\n if isPrime(r):\n s += r\n N = N // 10\n return s", "import math\n\ndef primesum(N):\n\n def isPrime(N):\n if N == 1:\n return False\n s = int(math.sqrt(N))\n for i in range(2, s + 1):\n if N % i == 0:\n return False\n return True\n sum = 0\n while N > 0:\n r = N % 10\n if isPrime(r):\n sum += r\n N = N // 10\n return sum", "import math\n\ndef primesum(N):\n s = str(N)\n d = 0\n n = list(map(int, s))\n for i in n:\n c = True\n if i < 2:\n c = False\n else:\n for j in range(2, int(math.sqrt(i)) + 1):\n if i % j == 0:\n c = False\n if c != False:\n d += i\n return d", "import math\n\ndef primesum(N):\n s = 0\n l = {2, 3, 5, 7}\n while N > 0:\n r = N % 10\n if r in l:\n s += r\n N = N // 10\n return s"], "starter_code": "def primesum(N):\n", "input_output": {"inputs": ["333", "686"], "outputs": ["9", "0"]}, "difficulty": "EASY", "raw_tags": ["Prime Number", "Numbers"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory", "Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/sum-of-primes0042/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(logN)", "entry_point": "primesum", "task_id": "TACO_lite/232", "example": [[[333], [686]], ["9", "0"]]} +{"requirement": "Given an integer N. The task is to return the position of first set bit found from the right side in the binary representation of the number.\nNote: If there is no set bit in the integer N, then return 0 from the function. \nExample 1:\nInput: N = 18\nOutput: 2\nExplanation: Binary representation of \n18 is 010010,the first set bit from the \nright side is at position 2.\nExample 2:\nInput: N = 12 \nOutput: 3 \nExplanation: Binary representation \nof 12 is 1100, the first set bit \nfrom the right side is at position 3.\nYour Task:\nThe task is to complete the function getFirstSetBit() that takes an integer n as a parameter and returns the position of first set bit.\nExpected Time Complexity: O(log N).\nExpected Auxiliary Space: O(1).\nConstraints:\n0 <= N <= 10^{8}", "solutions": ["def getfirstsetbit(n):\n ans = 0\n while n:\n mod = n % 2\n ans += 1\n if mod == 1:\n return ans\n n = n // 2\n return 0", "def getfirstsetbit(n):\n if n == 0:\n return 0\n b = bin(n)[2:]\n b = b[::-1]\n k = list(b)\n p = k.index('1')\n return p + 1", "def getfirstsetbit(n):\n pos = 1\n while n != 0:\n if n & 1 == 1:\n return pos\n pos += 1\n n >>= 1\n return 0", "def getfirstsetbit(n):\n bi = bin(n).replace('0b', '')\n c = 0\n for i in range(len(bi) - 1, -1, -1):\n if bi[i] == '1':\n return c + 1\n c += 1\n return 0", "def getfirstsetbit(n):\n x = 1\n pos = 1\n if n == 0:\n return 0\n while x <= n:\n if n == 0:\n return False\n if n & x != 0:\n return pos\n else:\n pos = pos + 1\n x = x << 1", "def getfirstsetbit(n):\n if n == 0:\n return 0\n t = bin(n)[2:]\n q = t[::-1]\n p = q.index('1')\n return p + 1", "def getfirstsetbit(n):\n if n == 0:\n return 0\n b = str(bin(n).replace('0b', ''))\n b = b[::-1]\n for i in range(len(b)):\n if b[i] == '1':\n return i + 1", "def convert(n):\n return bin(n).replace('0b', '')\n\ndef getfirstsetbit(n):\n if n == 0:\n return 0\n x = self.convert(n)[::-1]\n for i in range(len(x)):\n if x[i] == '1':\n return i + 1", "def getfirstsetbit(n):\n if n == 0:\n return '0'\n a = bin(n)[2:][::-1]\n return a.index('1') + 1", "def getfirstsetbit(n):\n m = bin(n)\n s = str(m)\n j = 1\n for i in range(len(s) - 1, 0, -1):\n if s[i] == '1':\n return j\n break\n j += 1\n return 0", "def getfirstsetbit(n):\n if n == 0:\n return 0\n return str(math.log2(n & -n) + 1)[:-2]", "def getfirstsetbit(n):\n c = 0\n if n == 0:\n return 0\n else:\n while n > 0:\n c += 1\n if n & 1 == 1:\n return c\n n = n >> 1", "def getfirstsetbit(n):\n count = 0\n if n == 0:\n return count\n while n != 0:\n count += 1\n if n & 1 == 1:\n return count\n n >>= 1", "def getfirstsetbit(n):\n if n == 0:\n return 0\n i = 1\n while n > 0:\n remain = n % 2\n if remain == 1:\n return i\n i += 1\n n = n / 2", "def getfirstsetbit(n):\n if n == 0:\n return 0\n s = bin(n)\n num = s[2:]\n num = num[::-1]\n c = 1\n for x in num:\n if x == '1':\n return c\n c += 1", "def getfirstsetbit(n):\n m = list(bin(n))\n m.remove('b')\n str1 = ''.join(m)\n if '1' not in str1:\n return 0\n return len(str1) - str1.rindex('1')", "def getfirstsetbit(n):\n binn = bin(n)[2:][::-1]\n for i in range(len(binn)):\n if binn[i] == '1':\n return i + 1\n return 0", "def getfirstsetbit(n):\n if n == 0:\n return 0\n res = 0\n while n != 1:\n if n % 2 != 0:\n return res + 1\n res += 1\n n = n // 2\n return res + 1", "def getfirstsetbit(n):\n x = list('{0:b}'.format(n))\n c = 0\n for i in x[::-1]:\n c += 1\n if int(i) == 1:\n return c\n return 0", "def getfirstsetbit(n):\n for i in range(32):\n if n & 1 << i != 0:\n return i + 1\n return 0", "def getfirstsetbit(n):\n count = 0\n pos = 1\n if n == 0:\n return 0\n while n > 0:\n if n % 2 == 1:\n count += 1\n break\n pos = pos + 1\n n = n // 2\n return pos", "def getfirstsetbit(n):\n i = n\n d = []\n flag = 0\n while i != 0:\n d.append(i % 2)\n i = int(i / 2)\n l = len(d)\n for i in range(len(d)):\n if d[i] == 1:\n return i + 1\n if flag == 0:\n return 0", "def getfirstsetbit(n):\n if n == 0:\n return 0\n t = bin(n)\n b = t.rfind('1')\n return len(t) - b", "def getfirstsetbit(n):\n if n == 0:\n return 0\n x = bin(n)[2:][::-1]\n y = []\n for i in range(len(x)):\n y.append(x[i])\n if '1' in y and '0' in y:\n return y.index('1') + 1\n return 1", "def getfirstsetbit(n):\n if n == 0:\n return 0\n return math.ceil(math.log2(n & -n) + 1)", "def getfirstsetbit(n):\n if n <= 0:\n return 0\n string = ''\n while n > 0:\n k = n % 2\n n = n // 2\n string += str(k)\n if k == 1:\n return len(string)\n return 0", "def getfirstsetbit(n):\n m = n\n k = ''\n k1 = []\n while m > 0:\n d = m % 2\n k = k + str(d)\n k1.append(d)\n m = m // 2\n if 1 in k1:\n return k1.index(1) + 1\n else:\n return 0", "def getfirstsetbit(n):\n k = bin(n)\n k = k[2:]\n n = len(k)\n z = 0\n for i in k[::-1]:\n z += 1\n if i == '1':\n return z\n return 0", "import math\n\ndef getfirstsetbit(n):\n if n == 0:\n return 0\n else:\n return int(math.log(n & -n, 2) + 1)", "def getfirstsetbit(n):\n if n == 0:\n return 0\n k = bin(n)\n s = k[2:]\n ans = s.rfind('1')\n return len(s) - ans", "def getfirstsetbit(n):\n p = 1\n while n:\n if n & 1:\n return p\n p = p + 1\n n = n >> 1\n return 0", "def getfirstsetbit(n):\n s = str(bin(n))\n s = s[::-1]\n for i in range(n):\n if s[i] == '1':\n return i + 1\n else:\n return 0", "def getfirstsetbit(n):\n if n == 0:\n return 0\n i = 0\n while True:\n if n & 1 << i != 0:\n return i + 1\n i += 1", "def getfirstsetbit(n):\n nums = bin(n)\n nums = list(nums.replace('b', '0')[2:])\n nums.reverse()\n for i in range(len(nums)):\n if nums[i] == '1':\n return i + 1\n return 0", "def getfirstsetbit(n):\n b = 0\n cont = 0\n res = n\n while b != 1 and res != 0:\n b = res % 2\n res -= res // 2\n cont += 1\n return cont", "def getfirstsetbit(n):\n if n == 0:\n return 0\n t = bin(n)\n p = t[2:]\n b = t.rindex('1')\n return len(t) - b", "import math\n\ndef getfirstsetbit(n):\n if n == 0:\n return 0\n without_first = n & n - 1\n only_first = n ^ without_first\n return math.floor(math.log(only_first, 2)) + 1", "def getfirstsetbit(n):\n b = bin(n)\n s = str(b)\n s = s[-1::-1]\n if '1' in s:\n x = s.index('1')\n return x + 1\n else:\n return 0", "def getfirstsetbit(n):\n i = -1\n b = n.bit_length()\n for i in range(b):\n if n & 1 << i != 0:\n break\n return i + 1", "def getfirstsetbit(n):\n x = str(bin(n))\n j = 1\n for i in range(len(x) - 1, -1, -1):\n if x[i] == '1':\n return j\n j += 1\n return 0", "def getfirstsetbit(n):\n (temp, count) = (bin(n)[2:][::-1], 0)\n for i in temp:\n if i == '1':\n return count + 1\n else:\n count += 1\n return 0", "def getfirstsetbit(n):\n a = list(bin(n)[::-1])\n if '1' in a:\n a = a.index('1')\n return a + 1\n return 0", "def getfirstsetbit(n):\n a = []\n while n > 0:\n a.append(n % 2)\n n = n // 2\n for i in range(0, len(a)):\n if a[i] == 1:\n return i + 1\n return 0", "import math\n\ndef getfirstsetbit(n):\n if n <= 1:\n return n\n k = n & ~n + 1\n return int(math.log2(k)) + 1", "def getfirstsetbit(n):\n incr = 0\n while n >= 1 << incr:\n if n & 1 << incr:\n break\n incr += 1\n else:\n return 0\n return incr + 1", "import math\n\ndef getfirstsetbit(n):\n ans = 0\n while n:\n if n & 1:\n return ans + 1\n else:\n n = n >> 1\n ans += 1\n return ans", "def getfirstsetbit(n):\n one = 1\n for i in range(1, 17):\n if n & one:\n return i\n one <<= 1\n return 0", "def getfirstsetbit(n):\n b = bin(n)[2:][::-1]\n for i in range(n):\n if b[i] == '1':\n return i + 1\n return 0", "import math\n\ndef getfirstsetbit(n):\n temp = n ^ n & n - 1\n if temp == 0:\n return 0\n else:\n return int(math.log2(temp) + 1)", "def getfirstsetbit(n):\n if n == 0:\n return 0\n else:\n return str(bin(n)[2:][::-1]).index('1') + 1"], "starter_code": "def getfirstsetbit(n):\n", "input_output": {"inputs": ["N = 18", "N = 12"], "outputs": ["2", "3"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/find-first-set-bit-1587115620/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log N).", "entry_point": "getfirstsetbit", "task_id": "TACO_lite/233", "example": [[[18], [12]], ["2", "3"]]} +{"requirement": "Given a directed acyclic graph(DAG) with n nodes labeled from 0 to n-1. Given edges, s and d ,count the number of ways to reach from s to d.There is a directed Edge from vertex edges[i][0] to the vertex edges[i][1].\n \nExample:\nInput: edges = {{0,1},{0,3},{1,2},{3,2}}, \nn = 4, s = 0, d = 2\nOutput: 2\nExplanation: There are two ways to reach at \n2 from 0. These are-\n1. 0->1->2\n2. 0->3->2\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function possible_paths() which takes edges, n, s and d as input parameter and returns the number of ways to reach from s to d.\n \nExpected Time Compelxity: O(2^{n})\nExpected Space Complexity: O(n+e) \nwhere e is the number of edges in the graph.\n \nConstraints:\n1 <= n <= 15\n0 <= s, d <= n-1", "solutions": ["def possible_paths(edges, n, s, d):\n g = [[] for _ in range(n)]\n for (a, b) in edges:\n g[a].append(b)\n path = set()\n\n def helper(node, prev, p):\n if node == d:\n path.add(tuple(p + [node]))\n return p\n if node in p:\n return False\n for neig in g[node]:\n if neig != prev:\n helper(neig, node, p + [node])\n return p\n helper(s, -1, [])\n return len(path)", "def solve(adj, n, s, d, dp):\n if dp[s] != 0:\n return dp[s]\n for child in adj[s]:\n dp[s] += self.solve(adj, n, child, d, dp)\n return dp[s]\n\ndef possible_paths(edges, n, s, d):\n adj = dict()\n for i in range(n):\n adj[i] = []\n dp = [0] * n\n dp[d] = 1\n for edge in edges:\n (u, v) = (edge[0], edge[1])\n adj[u].append(v)\n return self.solve(adj, n, s, d, dp)", "def solve(adj, way, s, d):\n if s == d:\n way[0] += 1\n return\n for i in adj[s]:\n self.solve(adj, way, i, d)\n\ndef possible_paths(edges, n, s, d):\n adj = [[] for i in range(n)]\n for (i, j) in edges:\n adj[i].append(j)\n way = [0]\n self.solve(adj, way, s, d)\n return way[0]", "def possible_paths(edges, n, s, d):\n\n def _dfs(vertex, target):\n visited.add(vertex)\n path.append(vertex)\n if vertex == target:\n output.append(list(path))\n path.pop()\n visited.remove(vertex)\n return\n for neighbor in graph[vertex]:\n if neighbor not in visited:\n _dfs(neighbor, target)\n path.pop()\n visited.remove(vertex)\n graph = [[] for i in range(n)]\n for edge in edges:\n graph[edge[0]].append(edge[1])\n visited = set()\n vertices = range(n)\n start = s\n target = d\n output = []\n path = []\n _dfs(start, target)\n return len(output)", "from collections import defaultdict\n\ndef dfs(node, d, graph):\n if node == d:\n self.ans += 1\n return\n for i in graph[node]:\n self.dfs(i, d, graph)\n\ndef possible_paths(edges, n, s, d):\n graph = defaultdict(list)\n self.ans = 0\n for (a, b) in edges:\n graph[a].append(b)\n self.dfs(s, d, graph)\n return self.ans", "from collections import defaultdict\n\ndef ToGraph(edges):\n graph = defaultdict(list)\n for edge in edges:\n (u, v) = edge\n graph[u].append(v)\n return graph\n\ndef possible_paths(edges, n, s, d):\n graph = self.ToGraph(edges)\n stack = [s]\n count = 0\n while stack:\n current = stack.pop()\n if current == d:\n count += 1\n for neighbour in graph[current]:\n stack.append(neighbour)\n return count", "def possible_paths(edges, n, s, d):\n\n def vamsi(u, d, adj, visited, ans):\n if u == d:\n ans[0] += 1\n return\n visited[u] = 1\n for i in adj[u]:\n if i not in visited:\n vamsi(i, d, adj, visited, ans)\n del visited[u]\n return\n adj = {}\n for i in range(0, n):\n adj[i] = []\n for (i, j) in edges:\n adj[i].append(j)\n visited = {}\n ans = [0]\n vamsi(s, d, adj, visited, ans)\n return ans[0]", "from collections import defaultdict, deque\n\ndef possible_paths(edges, n, s, d):\n g = defaultdict(list)\n for (i, j) in edges:\n g[i].append(j)\n q = deque([s])\n res = 0\n while q:\n cur = q.popleft()\n if cur == d:\n res += 1\n for nei in g[cur]:\n q.append(nei)\n return res", "def possible_paths(edges, n, s, d):\n queue = []\n queue.append(s)\n count = 0\n while queue:\n ele = queue.pop(0)\n if ele == d:\n count += 1\n for i in edges:\n if i[0] == ele:\n queue.append(i[1])\n return count", "def possible_paths(edges, n, s, d):\n visit = []\n visit.append(s)\n count = 0\n while visit:\n a = visit.pop()\n if a == d:\n count += 1\n for i in edges:\n if i[0] == a:\n visit.append(i[1])\n return count", "def possible_paths(edges, n, src, dest):\n x = [[] for i in range(n)]\n for (a, b) in edges:\n x[a].append(b)\n\n def f(i):\n if i == dest:\n return 1\n if dp[i] != None:\n return dp[i]\n ans = 0\n for j in x[i]:\n ans += f(j)\n dp[i] = ans\n return ans\n dp = [None for i in range(n)]\n return f(src)", "def dfs(s, adj, d, count):\n if s == d:\n count[0] += 1\n for i in adj[s]:\n self.dfs(i, adj, d, count)\n\ndef possible_paths(edges, n, s, d):\n adj = [[] for i in range(n)]\n for i in edges:\n adj[i[0]].append(i[1])\n count = [0]\n self.dfs(s, adj, d, count)\n return count[0]", "def possible_paths(edges, n, s, d):\n visited = [False] * n\n count = [0]\n\n def checkPaths(start, dest):\n visited[start] = True\n if start == dest:\n count[0] += 1\n else:\n for edge in edges:\n if edge[0] == start and (not visited[edge[1]]):\n checkPaths(edge[1], dest)\n visited[start] = False\n checkPaths(s, d)\n return count[0]", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n graph = defaultdict(lambda : [])\n for (first, second) in edges:\n graph[first].append(second)\n stack = [s]\n count = 0\n while stack:\n item = stack.pop()\n if item == d:\n count += 1\n else:\n stack += graph[item]\n return count", "def possible_paths(edges, n, s, d):\n x = {c: [] for c in range(n)}\n for (a, b) in edges:\n x[a].append(b)\n\n def dfs(node):\n if node == d:\n return 1\n ans = 0\n for j in x[node]:\n ans += dfs(j)\n return ans\n return dfs(s)", "def possible_paths(edges, n, s, d):\n x = [[] for i in range(n)]\n for (a, b) in edges:\n x[a].append(b)\n\n def check(i):\n if i == d:\n return 1\n ans = 0\n for j in x[i]:\n ans += check(j)\n return ans\n return check(s)", "def possible_paths(edges, n, s, d):\n adj = [[] for i in range(n)]\n for (i, j) in edges:\n adj[i].append(j)\n return self.dfs(s, adj, d)\n\ndef dfs(node, adj, target):\n if node == target:\n return 1\n output = 0\n for i in adj[node]:\n output += self.dfs(i, adj, target)\n return output", "def possible_paths(edges, n, s, dest):\n if n == 1 or s == dest:\n return 1\n d = dict()\n for i in range(len(edges)):\n if edges[i][0] in d:\n d[edges[i][0]].append(edges[i][1])\n else:\n d[edges[i][0]] = [edges[i][1]]\n res = [0]\n\n def dfs(i, dest):\n if i in d:\n for j in d[i]:\n if j == dest:\n res[0] += 1\n else:\n dfs(j, dest)\n dfs(s, dest)\n return res[0]", "def possible_paths(edges, n, s, d):\n nodes = [s]\n cnt = 0\n while nodes:\n cur = nodes.pop(0)\n if cur == d:\n cnt += 1\n for i in edges:\n if i[0] == cur:\n nodes.append(i[1])\n return cnt", "def possible_paths(edges, n, s, d):\n count = [0]\n D = [[] for i in range(n)]\n for a in edges:\n D[a[0]].append(a[1])\n visited = [-1] * n\n self.x(D, s, d, count, visited)\n return count[0]\n\ndef x(D, s, d, count, visited):\n visited[s] = 1\n if s == d:\n count[0] += 1\n for i in D[s]:\n if visited[i] == -1:\n self.x(D, i, d, count, visited)\n visited[s] = -1", "def possible_paths(edges, n, s, des):\n from collections import defaultdict\n d = defaultdict(list)\n for (i, j) in edges:\n d[i].append(j)\n visited = [False] * n\n res = set()\n\n def dfs(d, curr, des, path):\n nonlocal res, visited\n if curr == des:\n news = ''\n for i in path:\n news += str(i)\n res.add(news)\n return\n visited[curr] = True\n path.append(curr)\n for j in d[curr]:\n if visited[j] == False:\n dfs(d, j, des, path)\n visited[curr] = False\n path.pop()\n dfs(d, s, des, [])\n return len(res)", "from collections import deque\n\ndef possible_paths(edges, n, s, d):\n adj = [[0] * n for _ in range(n)]\n for edge in edges:\n adj[edge[0]][edge[1]] = 1\n count = 0\n source = deque([s])\n while len(source):\n if source[0] == d:\n count += 1\n else:\n for i in range(n):\n if adj[source[0]][i]:\n source.append(i)\n source.popleft()\n return count", "def possible_paths(edges, n, s, d):\n adj = {}\n for edge in edges:\n (start, end) = (edge[0], edge[1])\n if start not in adj.keys():\n adj[start] = [end]\n adj[end] = []\n else:\n adj[start].append(end)\n ans = []\n\n def dfs(start, end, adj, ans, path=[]):\n path = path + [start]\n if start == end:\n ans.append(path.copy())\n path.pop()\n return\n if start not in adj.keys():\n return\n for neighbour in adj[start]:\n if neighbour not in path:\n dfs(neighbour, end, adj, ans, path)\n path.pop()\n dfs(s, d, adj, ans)\n return len(ans)", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n graph = defaultdict(list)\n for (parent, child) in edges:\n graph[parent].append(child)\n\n def dfs(curr, d):\n if curr == d:\n return 1\n res = 0\n for child in graph[curr]:\n res += dfs(child, d)\n return res\n return dfs(s, d)", "def getPossiblePath(hash, index, d, dp):\n if index == d:\n return 1\n if dp[index] != -1:\n return dp[index]\n if index in hash:\n list = hash[index]\n result = 0\n for i in list:\n result += self.getPossiblePath(hash, i, d, dp)\n dp[index] = result\n return dp[index]\n else:\n return 0\n\ndef possible_paths(edges, n, s, d):\n hash = dict()\n dp = [-1 for i in range(n)]\n for i in edges:\n if i[0] not in hash:\n hash[i[0]] = [i[1]]\n else:\n hash[i[0]].append(i[1])\n return self.getPossiblePath(hash, s, d, dp)", "from collections import defaultdict\n\ndef DFS(s, d, graph, visited, ans):\n visited[s] = True\n if s == d:\n ans[0] += 1\n for neighbour in graph[s]:\n self.DFS(neighbour, d, graph, visited, ans)\n visited[s] = False\n return\n\ndef possible_paths(edges, n, s, d):\n graph = defaultdict(list)\n for edge in edges:\n graph[edge[0]].append(edge[1])\n visited = [False for i in range(n)]\n ans = [0]\n self.DFS(s, d, graph, visited, ans)\n return ans[0]", "def possible_paths(edges, n, s, d):\n\n def dfs(s, d, edges, vis, ANS, ans):\n vis[s] = True\n ans.append(s)\n if s == d:\n ANS.append(ans)\n vis[ans.pop()] = False\n return\n for i in range(len(edges)):\n if edges[i][0] == s:\n if vis[edges[i][1]] == False:\n dfs(edges[i][1], d, edges, vis, ANS, ans)\n vis[ans.pop()] = False\n return\n vis = [False for i in range(n)]\n ANS = []\n ans = []\n dfs(s, d, edges, vis, ANS, ans)\n return len(ANS)", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n count = 0\n\n def dfs(v, visited):\n nonlocal count\n visited.add(v)\n for i in range(n):\n if i in graph[v] and i not in visited:\n dfs(i, visited)\n if v == d:\n count += 1\n visited.remove(v)\n graph = defaultdict(list)\n for i in range(len(edges)):\n graph[edges[i][0]].append(edges[i][1])\n dfs(s, set())\n return count", "def count_dfs(graph, u, d, visited):\n if u == d:\n return 1\n visited[u] = True\n ans = 0\n for v in graph[u]:\n if visited[v] == False:\n ans += self.count_dfs(graph, v, d, visited)\n visited[u] = False\n return ans\n\ndef possible_paths(edges, n, s, d):\n graph = [[] for i in range(n)]\n for edge in edges:\n graph[edge[0]].append(edge[1])\n visited = [False for i in range(n)]\n return self.count_dfs(graph, s, d, visited)", "def possible_paths(edges, n, s, d):\n\n def dfs(adj, i, d):\n cnt = 0\n if i == d:\n cnt += 1\n for j in adj[i]:\n cnt += dfs(adj, j, d)\n return cnt\n adj = [[] for i in range(n)]\n for edge in edges:\n adj[edge[0]].append(edge[1])\n total_cnt = dfs(adj, s, d)\n return total_cnt", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n if n == 0:\n return 1\n adj = defaultdict(list)\n for (u, v) in edges:\n adj[u].append(v)\n visited = [0] * n\n q = []\n q.append(s)\n count = 0\n if s == d:\n count += 1\n while q:\n node = q.pop(0)\n for i in adj[node]:\n if i == d:\n count += 1\n if visited[i] == 0:\n q.append(i)\n visited[i] == 1\n return count", "def possible_paths(edges, n, s, d):\n if s == d:\n return 1\n count = 0\n l = [s]\n for j in l:\n for i in range(0, len(edges)):\n if edges[i][0] == j:\n if edges[i][1] == d:\n count += 1\n l.append(edges[i][1])\n else:\n l.append(edges[i][1])\n return count", "def possible_paths(edges, n, s, d):\n q = []\n q.append(s)\n count = 0\n while q:\n curr = q.pop(0)\n if curr == d:\n count += 1\n for i in edges:\n if i[0] == curr:\n q.append(i[1])\n return count", "def possible_paths(edges, n, st, dest):\n if st == dest:\n return 1\n if len(edges) == 0:\n return -1\n adj = []\n for i in range(n):\n adj.append([])\n for pair in edges:\n (s, e) = pair\n adj[s].append(e)\n ans = [0]\n self.dfs(adj, ans, st, dest)\n return ans[0]\n\ndef dfsUtil(st, dest, adj, ans):\n if st == dest:\n ans[0] += 1\n return\n for itm in adj[st]:\n self.dfsUtil(itm, dest, adj, ans)\n\ndef dfs(adj, ans, st, dest):\n for itm in adj[st]:\n self.dfsUtil(itm, dest, adj, ans)", "def possible_paths(edges, n, s, d):\n ans = []\n\n def dfs(s, di, vis, d):\n if s == d:\n ans.append(1)\n return\n for k in range(len(di[s])):\n dfs(di[s][k], di, vis, d)\n di = {}\n vis = set()\n for i in range(n):\n di[i] = []\n for i in range(len(edges)):\n di[edges[i][0]].append(edges[i][1])\n dfs(s, di, vis, d)\n return len(ans)", "def soln(g, s, d, l):\n if s == d:\n l[0] += 1\n return\n for i in g[s]:\n soln(g, i, d, l)\n return\n\ndef possible_paths(edges, n, s, d):\n g = {}\n for i in range(n):\n g[i] = []\n l = [0]\n for i in edges:\n g[i[0]].append(i[1])\n soln(g, s, d, l)\n return l[0]", "def possible_paths(edges, n, s, d):\n adj = [[] for i in range(n)]\n result = 0\n for edge in edges:\n u = edge[0]\n v = edge[1]\n adj[u].append(v)\n queue = [s]\n while queue:\n node = queue.pop(0)\n if node == d:\n result += 1\n continue\n for it in adj[node]:\n queue.append(it)\n return result", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n dic = defaultdict(list)\n for i in edges:\n dic[i[0]].append(i[1])\n count = 0\n\n def checkcount(dic, s, d, visted, path):\n nonlocal count\n visited[s] = True\n if s == d:\n count += 1\n for i in dic[s]:\n if visted[i] == None:\n checkcount(dic, i, d, visted, path)\n visted[s] = None\n visited = [None] * n\n path = []\n checkcount(dic, s, d, visited, path)\n return count", "def __init__():\n self.res = 0\n\ndef possible_paths(edges, n, s, d):\n adj = [[] for _ in range(n)]\n for edge in edges:\n adj[edge[0]].append(edge[1])\n self.dfs(adj, s, d)\n return self.res\n\ndef dfs(adj, s, d):\n if s == d:\n self.res += 1\n return\n for i in adj[s]:\n self.dfs(adj, i, d)", "def possible_paths(edges, n, s, d):\n di = dict()\n for i in range(len(edges)):\n if edges[i][0] not in di:\n di[edges[i][0]] = []\n di[edges[i][0]].append(edges[i][1])\n\n def get_paths(start, end, path=[]):\n path = path + [start]\n if start == end:\n return [path]\n if start not in di:\n return []\n paths = []\n for node in di[start]:\n if node not in path:\n new_paths = get_paths(node, end, path)\n for p in new_paths:\n paths.append(p)\n return paths\n return len(get_paths(s, d))", "def possible_paths(edges, n, s, d):\n if edges == [] or s == d:\n return 1\n for edge in edges:\n if edge[0] == s:\n self.recurs(s, edges, edge)\n return self.num\n\ndef recurs(choosing, edges, edge):\n if edge[1] == d:\n self.num += 1\n else:\n for e in edges:\n if edge[1] == e[0]:\n self.recurs(edge[1], edges, e)", "def possible_paths(edges, n, s, d):\n adj = [[] for i in range(n)]\n for i in edges:\n adj[i[0]].append(i[1])\n\n def rec(adj, c):\n if c == d:\n return 1\n e = 0\n for i in adj[c]:\n e += rec(adj, i)\n return e\n return rec(adj, s)", "def possible_paths(edges, n, s, d):\n if s == d:\n return 1\n stack = [s]\n counter = 0\n neighbors = {}\n for edge in edges:\n (a, b) = (edge[0], edge[1])\n if a not in neighbors:\n neighbors[a] = [b]\n else:\n neighbors[a].append(b)\n path = str(s)\n vis = {i: False for i in range(n)}\n passed = set()\n while stack:\n top = stack[-1]\n state = False\n if top in neighbors:\n for neigh in neighbors[top]:\n temp = path + '_' + str(neigh)\n if temp not in passed:\n stack.append(neigh)\n path = temp\n if neigh == d:\n counter += 1\n passed.add(path)\n state = True\n vis[neigh] = True\n break\n if not state:\n pp = stack.pop()\n path = path[:-(1 + len(str(pp)))]\n return counter", "def possible_paths(edges, n, s, d):\n graph = {}\n for i in edges:\n if i[0] in graph.keys():\n graph[i[0]].append(i[1])\n else:\n graph[i[0]] = [i[1]]\n q = []\n q.append(s)\n totalPath = 0\n while len(q) > 0:\n if q[0] == d:\n totalPath += 1\n elif q[0] in graph.keys():\n for i in graph[q[0]]:\n q.append(i)\n q.pop(0)\n return totalPath", "def possible_paths(edges, n, s, d):\n adj = []\n for i in range(n):\n adj.append([])\n for edge in edges:\n adj[edge[0]].append(edge[1])\n queue = [s]\n ways = 0\n while queue:\n elem = queue.pop()\n if elem == d:\n ways += 1\n continue\n for itm in adj[elem]:\n queue.insert(0, itm)\n return ways", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n adj = defaultdict(list)\n for (i, j) in edges:\n adj[i].append(j)\n ans = []\n stack = [(s, [0])]\n while stack:\n (node, path) = stack.pop()\n if node == d:\n ans.append(path)\n else:\n for adjnode in adj[node]:\n stack.append((adjnode, path + [adjnode]))\n return len(ans)", "from collections import defaultdict\n\ndef buildGraph(edges):\n graph = defaultdict(list)\n for (i, j) in edges:\n graph[i].append(j)\n return graph\n\ndef possible_paths(edges, n, s, d):\n ways = 0\n graph = self.buildGraph(edges)\n visited = set()\n\n def dfs(curr):\n nonlocal ways\n if curr == d:\n ways += 1\n return\n if curr in visited:\n return\n visited.add(curr)\n for i in graph[curr]:\n dfs(i)\n visited.remove(curr)\n dfs(s)\n return ways", "def possible_paths(edges, n, s, d):\n if s == d:\n return 1\n count = 0\n for i in edges:\n if i[0] == s:\n count += self.possible_paths(edges, n, i[1], d)\n return count", "def possible_paths(edges, n, s, d):\n q = []\n q.append(s)\n c = 0\n while q:\n a = q.pop(0)\n if a == d:\n c += 1\n for i in edges:\n if i[0] == a:\n q.append(i[1])\n return c", "def possible_paths(edges, n, s, d):\n\n def buildAdj(edges):\n adj = {}\n for edge in edges:\n (s, d) = (edge[0], edge[1])\n if s not in adj:\n adj[s] = []\n adj[s].append(d)\n return adj\n\n def dfs(s):\n if s == d:\n return 1\n count = 0\n if s in adj:\n neighbors = adj[s]\n for neighbor in neighbors:\n count += dfs(neighbor)\n return count\n adj = buildAdj(edges)\n return dfs(s)", "def possible_paths(edges, n, s, d):\n\n def dfs(u, count):\n if u == d:\n count[0] += 1\n for v in m[u]:\n dfs(v, count)\n import collections\n m = collections.defaultdict(list)\n for i in edges:\n m[i[0]].append(i[1])\n count = [0]\n dfs(s, count)\n return count[0]", "def possible_paths(edges, n, s, d):\n q = [s]\n c = 0\n adj = [[] for _ in range(n)]\n for i in edges:\n adj[i[0]].append(i[1])\n while q:\n x = q.pop(0)\n for i in adj[x]:\n q.append(i)\n if x == d:\n c = c + 1\n return c", "def possible_paths(edges, n, s1, d1):\n adj = {}\n for i in range(n):\n adj[i] = []\n for i in edges:\n (s, d) = (i[0], i[1])\n adj[s].append(d)\n visited = [False for i in range(n)]\n output = [0]\n\n def dfs(s, d):\n visited[s] = True\n if s == d:\n output[0] += 1\n visited[d] = False\n return\n for i in adj[s]:\n if visited[i] == False:\n dfs(i, d)\n visited[s] = False\n dfs(s1, d1)\n return output[0]", "from collections import defaultdict\n\ndef __init__():\n self.count = 0\n self.adj = defaultdict(list)\n\ndef possible_paths(edges, n, s, d):\n for (i, j) in edges:\n self.adj[i].append(j)\n self.getpaths(s, d)\n return self.count\n\ndef getpaths(s, d):\n if s == d:\n self.count += 1\n return\n for i in self.adj[s]:\n self.getpaths(i, d)\n return", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n queue = []\n queue.append(s)\n count = 0\n while queue:\n node = queue.pop(0)\n if node == d:\n count += 1\n for i in edges:\n if i[0] == node:\n queue.append(i[1])\n return count", "def possible_paths(edges, n, s, d):\n adj = [[] for _ in range(n)]\n for (u, v) in edges:\n adj[u].append(v)\n visited = [False] * n\n paths = [0]\n self.dfs(s, d, adj, visited, paths)\n return paths[0]\n\ndef dfs(s, d, adj, visited, paths):\n visited[s] = True\n if s == d:\n paths[0] += 1\n for ngbr in adj[s]:\n if not visited[ngbr]:\n self.dfs(ngbr, d, adj, visited, paths)\n visited[s] = False", "def possible_paths(edges, n, s, d):\n vis = [0] * n\n adj = [[] for i in range(n)]\n for (i, j) in edges:\n adj[i].append(j)\n\n def count_dfs(node):\n if node == d:\n return 1\n vis[node] = 1\n res = 0\n for i in adj[node]:\n if not vis[i]:\n res += count_dfs(i)\n vis[node] = 0\n return res\n return count_dfs(s)", "def possible_paths(edges, n, s, d):\n graph = {}\n for vertex in range(n):\n graph[vertex] = []\n for (u, v) in edges:\n graph[u].append(v)\n self.count = 0\n visit = set()\n\n def dfs(s):\n if s == d:\n self.count += 1\n return\n visit.add(s)\n for nei in graph[s]:\n if nei not in visit:\n dfs(nei)\n visit.remove(s)\n dfs(s)\n return self.count", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n res = 0\n\n def dfs(node):\n nonlocal res\n if node == d:\n res += 1\n return\n for nei in adj[node]:\n dfs(nei)\n adj = defaultdict(list)\n for (src, dist) in edges:\n adj[src].append(dist)\n dfs(s)\n return res", "def __init__():\n self.count = 0\n\ndef dfs(s, d, adj):\n if s == d:\n self.count += 1\n return\n for id in adj[s]:\n self.dfs(id, d, adj)\n\ndef possible_paths(edges, n, s, d):\n adj = [[] for _ in range(n)]\n for elem in edges:\n adj[elem[0]].append(elem[1])\n self.dfs(s, d, adj)\n return self.count", "def possible_paths(edges, n, s, d):\n adj_list = {}\n visited = [0] * n\n ans = []\n for k in range(0, len(edges)):\n first = edges[k][0]\n second = edges[k][1]\n if first not in adj_list:\n adj_list[first] = [second]\n else:\n adj_list[first].append(second)\n self.dfs(s, d, adj_list, visited, ans)\n return len(ans)\n\ndef dfs(s, d, adj_list, visited, ans):\n if s == d:\n ans.append(1)\n return\n visited[s] = 1\n if s in adj_list:\n for j in adj_list[s]:\n if visited[j] == 0:\n self.dfs(j, d, adj_list, visited, ans)\n visited[j] = 0\n return", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n graph = defaultdict(list)\n for (src, dst) in edges:\n graph[src].append(dst)\n visited = set()\n visited.add(s)\n paths = []\n\n def dfs_traverse(cur_node, path):\n if cur_node == d:\n paths.append(path[:])\n return\n for neighbor in graph[cur_node]:\n if neighbor in visited:\n continue\n visited.add(neighbor)\n dfs_traverse(neighbor, path + [neighbor])\n visited.remove(neighbor)\n dfs_traverse(s, [s])\n return len(paths)", "from collections import defaultdict\n\ndef dfs(v, visited, d, arr, res, graph):\n visited[v] = True\n arr.append(v)\n if v == d:\n res.append(arr.copy())\n else:\n for i in graph[v]:\n if visited[i] == False:\n self.dfs(i, visited, d, arr, res, graph)\n arr.pop()\n visited[v] = False\n\ndef possible_paths(edges, n, s, d):\n dct = defaultdict(list)\n for edge in edges:\n dct[edge[0]].append(edge[1])\n res = []\n visited = [False] * n\n self.dfs(s, visited, d, [], res, dct)\n return len(res)", "def possible_paths(edges, n, s, d):\n global count\n count = 0\n\n def dfs(root):\n global count\n if root == d:\n count += 1\n return\n for child in [edge[1] for edge in edges if edge[0] == root]:\n dfs(child)\n dfs(s)\n return count", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n\n def dfs(vis, s, d):\n vis[s] = True\n if s == d:\n count[0] += 1\n for u in adj[s]:\n if vis[u] == False:\n dfs(vis, u, d)\n vis[s] = False\n adj = [[] for i in range(n)]\n for (i, j) in edges:\n adj[i].append(j)\n count = [0]\n vis = [False for _ in range(n)]\n dfs(vis, s, d)\n return count[0]"], "starter_code": "def possible_paths(edges, n, s, d):\n", "input_output": {"inputs": ["edges = {{0,1},{0,3},{1,2},{3,2}}, \r\nn = 4, s = 0, d = 2"], "outputs": ["2"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "DFS", "Data Structures", "Graph", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Graph algorithms", "Data structures", "Graph traversal"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-the-paths4332/1", "Expected Auxiliary Space": "O(n+e)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(2^n)", "entry_point": "possible_paths", "task_id": "TACO_lite/199", "example": [[], []]} +{"requirement": "Your task is to find the number couple with the greatest difference from a given array of number-couples. \n\nAll number couples will be given as strings and all numbers in them will be positive integers. \n\nFor instance: ['56-23','1-100']; in this case, you should identify '1-100' as the number couple with the greatest difference and return it.\n\nIn case there are more than one option, for instance ['1-3','5-7','2-3'], you should identify whichever is first, so in this case '1-3'. \n\nIf there is no difference, like so ['11-11', '344-344'], return false.", "solutions": ["def diff(arr):\n r = arr and max(arr, key=lambda x: abs(eval(x)))\n return bool(arr and eval(r)) and r", "def diff(arr):\n r = [abs(eval(s)) for s in arr]\n return arr[r.index(max(r))] if r and max(r) else False", "def diff(arr):\n r = [abs(int(w.split('-')[0]) - int(w.split('-')[1])) for w in arr]\n return arr[r.index(max(r))] if sum(r) else False", "def diff(arr):\n if not arr:\n return 0\n m = max(arr, key=lambda x: abs(eval(x)))\n return eval(m) and m", "def difference(x):\n (a, b) = map(int, x.split('-'))\n return abs(a - b)\n\ndef diff(arr):\n if not arr:\n return False\n x = max(arr, key=difference)\n if difference(x) == 0:\n return False\n return x", "def diff(pairs):\n max_diff = max_pair = 0\n for pair in pairs:\n (a, b) = pair.split('-')\n current = abs(int(a) - int(b))\n if current > max_diff:\n max_diff = current\n max_pair = pair\n return max_pair", "def diff(arr):\n vals = [abs(eval(pair)) for pair in arr]\n return False if all((val == 0 for val in vals)) else arr[vals.index(max(vals))]\n return val", "def diff(arr):\n z = {}\n for i in range(0, len(arr)):\n s = arr[i].split('-')\n d = abs(int(s[0]) - int(s[1]))\n z.update({arr[i]: d})\n w = {k: v for (k, v) in sorted(list(z.items()), reverse=True, key=lambda x: x[1])}\n if w == {} or max(w.values()) == 0:\n return False\n else:\n return max(w, key=w.get)", "def diff(arr):\n diff = []\n if arr == []:\n return False\n for i in range(len(arr)):\n str = arr[i].split('-')\n diff.append(abs(int(str[1]) - int(str[0])))\n if max(diff) == 0:\n return False\n for j in range(len(arr)):\n if diff[j] == max(diff):\n return arr[j]", "def diff(arr):\n if not arr:\n return False\n\n def cust_key(s):\n (a, b) = map(int, s.split('-'))\n return abs(a - b)\n m = max(arr, key=cust_key)\n return m if len(set(m.split('-'))) == 2 else False"], "starter_code": "def diff(arr):\n", "input_output": {"fn_name": "diff", "inputs": [[["43-45", "1021-55", "000-18888", "92-34", "76-32", "99-1", "1020-54"]], [["1-2", "2-4", "5-7", "8-9", "44-45"]], [["1-1000", "2-1000", "100-67", "98-45", "8-9"]], [["33-33", "77-77"]], [["23-67", "67-23", "88-88", "45-46"]], [["45896-2354", "4654-556767", "2455-423522", "3455-355", "34-34", "2524522-0"]], [["1-1", "2-2", "1-0", "77-77"]], [["0-0"]], [[]]], "outputs": [["000-18888"], ["2-4"], ["1-1000"], [false], ["23-67"], ["2524522-0"], ["1-0"], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56b12e3ad2387de332000041", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "diff", "task_id": "TACO_lite/104", "example": [[], []]} +{"requirement": "Given a string, remove any characters that are unique from the string.\n\nExample: \n\ninput: \"abccdefee\"\n\noutput: \"cceee\"", "solutions": ["from collections import Counter\n\ndef only_duplicates(string):\n cs = Counter(string)\n return ''.join((c for c in string if cs[c] > 1))", "def only_duplicates(string):\n return ''.join([x for x in string if string.count(x) > 1])", "only_duplicates = lambda s: ''.join((c for c in s if s.count(c) > 1))", "def only_duplicates(stg):\n return ''.join((c for c in stg if stg.count(c) > 1))", "def only_duplicates(string):\n return ''.join((s for s in string if string.count(s) > 1))", "def only_duplicates(string):\n sets = (unique, duplicate) = (set(), set())\n for c in string:\n sets[c in unique].add(c)\n return ''.join((c for c in string if c in duplicate))", "def only_duplicates(a):\n b = []\n for j in range(0, len(a)):\n for i in range(j + 1, len(a)):\n if a[j] == a[i]:\n b.append(a[j])\n a = list(a)\n\n def seclect(i):\n for j in b:\n if j == i:\n return i\n return ''.join(filter(seclect, a))", "def only_duplicates(string):\n string = list(string)\n foundStrings = []\n finalString = []\n for (index, item) in enumerate(string):\n if item not in string[index + 1:len(string)] and item not in string[0:index]:\n finalString.append('')\n else:\n finalString.append(item)\n return ''.join(finalString)", "from collections import Counter\nfrom re import sub\n\ndef only_duplicates(s):\n return sub('[%s]' % ''.join((k for (k, v) in Counter(s).items() if v == 1)), '', s)"], "starter_code": "def only_duplicates(string):\n", "input_output": {"fn_name": "only_duplicates", "inputs": [["abccdefee"], ["hello"], ["colloquial"], ["foundersandcoders"], ["12314256aaeff"]], "outputs": [["cceee"], ["ll"], ["ollol"], ["ondersndoders"], ["1212aaff"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Algorithms"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5a1dc4baffe75f270200006b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "only_duplicates", "task_id": "TACO_lite/245", "example": [[["abccdefee"]], ["cceee"]]} +{"requirement": "Given a number N, the task is to count minimum steps to minimize it to 1 according to the following criteria:\n\tIf N is divisible by 2 then you may reduce N to N/2.\n\tIf N is divisible by 3 then you may reduce N to N/3.\n\tOtherwise, Decrement N by 1.\nExample 1:\nInput: N = 10\nOutput: 3\nExplanation: 10 - 1 = 9 / 3 = 3 / 3 = 1\nExample 2:\nInput: N = 1\nOutput: 0\nExplanation: N is 1\nYour Task: \nYou don't need to read input or print anything. Complete the function minSteps() which takes N as input parameters and returns the integer value\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 ≤ N ≤ 10^{4}", "solutions": ["def minsteps(N):\n MAX = 100000\n dp = [-1 for i in range(N + 1)]\n dp[1] = 0\n for i in range(2, N + 1):\n dp[i] = 1 + min(dp[i - 1], dp[i // 2] if i % 2 == 0 else MAX, dp[i // 3] if i % 3 == 0 else MAX)\n return dp[N]", "def minsteps(N):\n\n def fun(n, d):\n if n == 1:\n return 0\n if d[n] != -1:\n return d[n]\n res = fun(n - 1, d)\n if n % 2 == 0:\n res = min(res, fun(n // 2, d))\n if n % 3 == 0:\n res = min(res, fun(n // 3, d))\n d[n] = 1 + res\n return d[n]\n d = [-1 for i in range(N + 1)]\n return fun(N, d)", "def minsteps(n):\n dp = [0] * (n + 1)\n for i in range(2, n + 1):\n dp[i] = dp[i - 1] + 1\n if i % 2 == 0:\n dp[i] = min(dp[i], dp[i // 2] + 1)\n if i % 3 == 0:\n dp[i] = min(dp[i], dp[i // 3] + 1)\n return dp[n]", "def minsteps(n):\n dp = [0] * (N + 1)\n for i in range(2, N + 1):\n dp[i] = dp[i - 1] + 1\n for j in range(2, 4):\n if i % j == 0:\n dp[i] = min(dp[i], dp[i // j] + 1)\n return dp[N]", "def minsteps(N):\n dp = [0] * (N + 1)\n for i in range(2, N + 1):\n dp[i] = 1 + min(dp[i // 2] if i % 2 == 0 else float('inf'), dp[i // 3] if i % 3 == 0 else float('inf'), dp[i - 1])\n return dp[N]", "def minsteps(N):\n table = [0] * (N + 1)\n table[0] = 0\n table[1] = 0\n for pos in range(2, len(table)):\n a = b = c = float('inf')\n if pos % 3 == 0:\n a = 1 + table[pos // 3]\n if pos % 2 == 0:\n b = 1 + table[pos // 2]\n c = 1 + table[pos - 1]\n table[pos] = min(a, b, c)\n return table[N]", "def minsteps(N):\n dp = {}\n dp[0] = -1\n dp[1] = 0\n for i in range(2, N + 1):\n x1 = dp[i - 1] + 1\n x2 = dp[i / 2] + 1 if i % 2 == 0 else N\n x3 = dp[i / 3] + 1 if i % 3 == 0 else N\n dp[i] = min(x1, x2, x3)\n return dp[N]", "def minsteps(N):\n d = {1: 0, 2: 1, 3: 1}\n for i in range(4, N + 1):\n arr = [d[i - 1]]\n if i % 2 == 0:\n arr.append(d[i // 2])\n if i % 3 == 0:\n arr.append(d[i // 3])\n d[i] = min(arr) + 1\n return d[N]", "def minsteps(N):\n if N == 1:\n return 0\n temp = [-1] * (N + 1)\n temp[1] = 0\n for curr in range(2, N + 1):\n res = temp[curr - 1]\n if curr % 2 == 0:\n res = min(res, temp[curr // 2])\n if curr % 3 == 0:\n res = min(res, temp[curr // 3])\n temp[curr] = 1 + res\n return temp[N]", "def minsteps(N):\n memo = {}\n\n def minsteps1(n):\n if n == 1:\n return 0\n if n in memo:\n return memo[n]\n step1 = float('inf')\n step2 = float('inf')\n if n % 2 == 0:\n step1 = 1 + minsteps1(int(n / 2))\n if n % 3 == 0:\n step2 = 1 + minsteps1(int(n / 3))\n step3 = 1 + minsteps1(n - 1)\n memo[n] = min(step1, step2, step3)\n return memo[n]\n return minsteps1(N)", "import sys\n\ndef helper(n, dp):\n if n == 1:\n return 0\n if dp[n - 1] == -1:\n ans1 = self.helper(n - 1, dp)\n dp[n - 1] = ans1\n else:\n ans1 = dp[n - 1]\n (ans2, ans3) = (sys.maxsize, sys.maxsize)\n if n % 2 == 0:\n if dp[n // 2] == -1:\n ans2 = self.helper(n // 2, dp)\n dp[n // 2] = ans2\n else:\n ans2 = dp[n // 2]\n if n % 3 == 0:\n if dp[n // 3] == -1:\n ans3 = self.helper(n // 3, dp)\n dp[n // 3] = ans3\n else:\n ans3 = dp[n // 3]\n return 1 + min(ans1, ans2, ans3)\n\ndef minsteps(N):\n dp = [-1 for i in range(N + 1)]\n return self.helper(N, dp)", "def minsteps(N):\n\n def fun(n):\n if n == 1:\n return 0\n if dp[n] != -1:\n return dp[n]\n res = 0\n res = fun(n - 1)\n if n % 2 == 0:\n res = min(res, fun(n // 2))\n if n % 3 == 0:\n res = min(res, fun(n // 3))\n dp[n] = 1 + res\n return dp[n]\n dp = [-1] * (N + 1)\n return fun(N)", "def f(num, dp):\n if num in dp:\n return dp[num]\n if num == 1:\n dp[num] = 0\n return 0\n (by2, by3) = (1000000, 1000000)\n if num % 2 == 0:\n by2 = 1 + self.f(num / 2, dp)\n if num % 3 == 0:\n by3 = 1 + self.f(num / 3, dp)\n dp[num] = min(1 + self.f(num - 1, dp), by2, by3)\n return dp[num]\n\ndef minsteps(N):\n dp = {}\n return self.f(N, dp)", "from sys import maxsize as MAX_VALUE\n\ndef minsteps(n):\n if N == 1:\n return 0\n if N == 2:\n return 1\n if N == 3:\n return 1\n dp = [-1 for i in range(N + 1)]\n dp[1] = 0\n dp[2] = 1\n dp[3] = 1\n for i in range(4, N + 1):\n ans1 = dp[i - 1]\n (ans2, ans3) = (float('inf'), float('inf'))\n if i % 2 == 0:\n ans2 = dp[i // 2]\n if i % 3 == 0:\n ans3 = dp[i // 3]\n dp[i] = 1 + min(ans1, ans2, ans3)\n return dp[N]", "def minsteps(N):\n if N == 1:\n return 0\n if N <= 3:\n return 1\n dp = [0] * (N + 1)\n dp[2] = 1\n dp[3] = 1\n for i in range(4, N + 1):\n a = 987654321\n b = 987654321\n if i % 3 == 0:\n a = dp[i // 3] + 1\n if i % 2 == 0:\n b = dp[i // 2] + 1\n c = dp[i - 1] + 1\n dp[i] = min(a, b, c)\n return dp[-1]", "def minsteps(N):\n dp = [-1] * (N + 1)\n\n def check(N):\n if N == 1:\n return 0\n if dp[N] != -1:\n return dp[N]\n elif N % 2 == 0 and N % 3 == 0:\n dp[N] = 1 + min(min(check(N - 1), check(N // 2)), check(N // 3))\n return dp[N]\n elif N % 2 == 0:\n dp[N] = 1 + min(check(N - 1), check(N // 2))\n return dp[N]\n elif N % 3 == 0:\n dp[N] = 1 + min(check(N - 1), check(N // 3))\n return dp[N]\n else:\n dp[N] = 1 + check(N - 1)\n return dp[N]\n res = check(N)\n return res", "def solve(n, dp):\n if n == 1:\n return 0\n ans1 = float('inf')\n if n % 3 == 0:\n if dp[n // 3] == -1:\n ans1 = solve(n // 3, dp)\n dp[n // 3] = ans1\n else:\n ans1 = dp[n // 3]\n ans2 = float('inf')\n if n % 2 == 0:\n if dp[n // 2] == -1:\n ans2 = solve(n // 2, dp)\n dp[n // 2] = ans2\n else:\n ans2 = dp[n // 2]\n if dp[n - 1] == -1:\n ans3 = solve(n - 1, dp)\n dp[n - 1] = ans3\n else:\n ans3 = dp[n - 1]\n ans = 1 + min(ans1, ans2, ans3)\n return ans\n\ndef minsteps(N):\n dp = [-1 for i in range(N + 1)]\n ans = solve(N, dp)\n return ans", "def minsteps(n):\n import sys\n max_int = sys.maxsize\n dp = [0 for i in range(n + 1)]\n dp\n for i in range(2, n + 1):\n (op1, op2, op3) = (max_int, max_int, max_int)\n if i % 3 == 0:\n op1 = dp[i // 3]\n if i % 2 == 0:\n op2 = dp[i // 2]\n op3 = dp[i - 1]\n dp[i] = min(op1, op2, op3) + 1\n return dp[n]", "def minsteps(n):\n if n == 1:\n return 0\n if n == 2:\n return 1\n if n == 3:\n return 1\n dp = [-1 for i in range(n + 1)]\n dp[1] = 0\n dp[2] = 1\n dp[3] = 1\n for i in range(4, n + 1):\n ans1 = dp[i - 1]\n (ans2, ans3) = (float('inf'), float('inf'))\n if i % 2 == 0:\n ans2 = dp[i // 2]\n if i % 3 == 0:\n ans3 = dp[i // 3]\n dp[i] = 1 + min(ans1, ans2, ans3)\n return dp[n]", "def minsteps(n):\n if n == 1:\n ans = 0\n return ans\n dp = [-1 for i in range(n + 1)]\n return self.minsteps_to_1(n, dp)\n\ndef minsteps_to_1(n, dp):\n if n == 1:\n return 0\n ans1 = sys.maxsize\n if n % 3 == 0:\n if dp[n // 3] == -1:\n ans1 = self.minsteps_to_1(n // 3, dp)\n dp[n // 3] = ans1\n else:\n ans1 = dp[n // 3]\n ans2 = sys.maxsize\n if n % 2 == 0:\n if dp[n // 2] == -1:\n ans2 = self.minsteps_to_1(n // 2, dp)\n dp[n // 2] = ans2\n else:\n ans2 = dp[n // 2]\n if dp[n - 1] == -1:\n ans3 = self.minsteps_to_1(n - 1, dp)\n dp[n - 1] = ans3\n else:\n ans3 = dp[n - 1]\n ans = 1 + min(ans1, ans2, ans3)\n return ans", "def minsteps(N):\n if N <= 1:\n return 0\n memo = [999999] * (N + 1)\n memo[0] = 0\n memo[1] = 0\n for i in range(1, N):\n memo[i + 1] = min(memo[i] + 1, memo[i + 1])\n if i * 2 <= N:\n memo[i * 2] = min(memo[i] + 1, memo[i * 2])\n if i * 3 <= N:\n memo[i * 3] = min(memo[i] + 1, memo[i * 3])\n return memo[N]", "def minsteps(N):\n memo = [None] * (N + 1)\n\n def helper(N, memo):\n if N <= 1:\n return 0\n if memo[N]:\n return memo[N]\n op1 = op2 = op3 = 9999999\n op1 = 1 + helper(N - 1, memo)\n if N % 2 == 0:\n op2 = 1 + helper(int(N / 2), memo)\n if N % 3 == 0:\n op3 = 1 + helper(int(N / 3), memo)\n memo[N] = min(op1, op2, op3)\n return memo[N]\n return helper(N, memo)", "def minsteps(n):\n dp = {}\n\n def ways(n):\n if n == 1:\n return 0\n if n in dp:\n return dp[n]\n a = 999999999\n b = 999999999\n c = 999999999\n if n % 2 == 0:\n a = ways(n // 2) + 1\n if n % 3 == 0:\n b = ways(n // 3) + 1\n c = ways(n - 1) + 1\n dp[n] = min(a, b, c)\n return dp[n]\n return ways(n)", "def __init__():\n self.dp = [-1 for i in range(0, 10001)]\n self.dp[1] = 1\n\ndef minsteps(N):\n if N == 1:\n return 0\n if self.dp[N] != -1:\n return self.dp[N]\n ans1 = 999\n ans2 = 999\n ans3 = 999\n ans1 = self.minsteps(N - 1)\n if N % 2 == 0:\n ans2 = self.minsteps(N // 2)\n if N % 3 == 0:\n ans3 = self.minsteps(N // 3)\n self.dp[N] = 1 + min(ans1, ans2, ans3)\n return self.dp[N]", "def minsteps(N):\n dp = [0 for i in range(N + 1)]\n for j in range(2, N + 1):\n ans1 = dp[j - 1]\n ans2 = 9999\n ans3 = 99999\n if j % 2 == 0:\n ans2 = dp[j // 2]\n if j % 3 == 0:\n ans3 = dp[j // 3]\n dp[j] = 1 + min(ans1, ans2, ans3)\n return dp[N]", "def minsteps(n):\n dp = [-1 for i in range(n + 1)]\n return self.helper(n, dp)\n\ndef helper(n, dp):\n if n == 1:\n return 0\n ans1 = 9999\n if n % 3 == 0:\n if dp[n // 3] == -1:\n ans1 = self.helper(n // 3, dp)\n dp[n // 3] == ans1\n else:\n ans1 = dp[n // 3]\n ans2 = 999\n if n % 2 == 0:\n if dp[n // 2] == -1:\n ans2 = self.helper(n // 2, dp)\n dp[n // 2] = ans2\n else:\n ans2 = dp[n // 2]\n if dp[n - 1] == -1:\n ans3 = self.helper(n - 1, dp)\n dp[n - 1] = ans3\n else:\n ans3 = dp[n - 1]\n ans = 1 + min(ans1, ans2, ans3)\n return ans", "def minsteps(n):\n\n def getMinSteps(n, memo):\n if n == 1:\n return 0\n if memo[n] != -1:\n return memo[n]\n res = getMinSteps(n - 1, memo)\n if n % 2 == 0:\n res = min(res, getMinSteps(n // 2, memo))\n if n % 3 == 0:\n res = min(res, getMinSteps(n // 3, memo))\n memo[n] = 1 + res\n return memo[n]\n memo = [0 for i in range(n + 1)]\n for i in range(n + 1):\n memo[i] = -1\n return getMinSteps(n, memo)", "def minsteps(N):\n if N == 1:\n return 0\n if N == 2:\n return 1\n if N == 3:\n return 1\n arr = [0] * (N + 1)\n arr[0] = 0\n arr[1] = 0\n arr[2] = 1\n arr[3] = 1\n for j in range(3, N + 1):\n p = 100000\n q = 100000\n r = arr[j - 1]\n if j % 3 == 0:\n p = arr[j // 3]\n if j % 2 == 0:\n q = arr[j // 2]\n arr[j] = min(p, min(q, r)) + 1\n return arr[N]", "import sys\n\ndef minsteps(N):\n storage = [-1 for i in range(N + 1)]\n storage[1] = 0\n for i in range(2, N + 1):\n if i % 3 == 0:\n storage[i] = storage[i // 3] + 1\n elif i % 2 == 0:\n ans1 = storage[i // 2]\n ans2 = storage[i - 1]\n storage[i] = min(ans1, ans2) + 1\n else:\n storage[i] = storage[i - 1] + 1\n return storage[N]", "def minsteps(N):\n\n def minsteps(N):\n if N == 1:\n return 0\n if N % 3 == 0:\n if storage[N // 3] != -1:\n steps = storage[N // 3]\n else:\n steps = minsteps(N // 3)\n return steps + 1\n elif N % 2 == 0:\n if storage[N // 2] != -1:\n steps1 = storage[N // 2]\n else:\n steps1 = minsteps(N // 2)\n if storage[N - 1] != -1:\n steps2 = storage[N - 1]\n else:\n steps2 = minsteps(N - 1)\n return min(steps1, steps2) + 1\n else:\n if storage[N - 1] != -1:\n steps = storage[N - 1]\n else:\n steps = minsteps(N - 1)\n return steps + 1\n storage = [-1 for i in range(N)]\n return minsteps(N)", "def minsteps(N):\n if N == 1:\n return 0\n if N % 3 == 0:\n steps = self.minsteps(N // 3)\n return steps + 1\n elif N % 2 == 0:\n steps1 = self.minsteps(N // 2)\n steps2 = self.minsteps(N - 1)\n return min(steps1, steps2) + 1\n else:\n steps = self.minsteps(N - 1)\n return steps + 1", "def minsteps(N):\n count = 0\n if N == 1:\n return 0\n\n def get_count(N, count, dp):\n if N == 1:\n return dp[N]\n if dp[N] != 0:\n return dp[N]\n if N % 2 == 0 and N % 3 == 0:\n dp[N] = 1 + min(min(get_count(N // 2, count, dp), get_count(N // 3, count, dp)), get_count(N - 1, count, dp))\n elif N % 2 == 0:\n dp[N] = 1 + min(get_count(N // 2, count, dp), get_count(N - 1, count, dp))\n elif N % 3 == 0:\n dp[N] = 1 + min(get_count(N // 3, count, dp), get_count(N - 1, count, dp))\n else:\n dp[N] = 1 + get_count(N - 1, count, dp)\n return dp[N]\n dp = [0] * (N + 1)\n return get_count(N, count, dp)", "def minsteps(N):\n if N == 1:\n return 0\n if N == 2 or N == 3:\n return 1\n dp = [0 for i in range(N + 1)]\n dp[2] = 1\n dp[3] = 1\n for i in range(4, N + 1):\n m = float('inf')\n if i % 2 == 0:\n m = min(m, dp[i // 2] + 1)\n if i % 3 == 0:\n m = min(m, dp[i // 3] + 1)\n m = min(m, dp[i - 1] + 1)\n dp[i] = m\n return dp[N]", "def minsteps(N):\n data = [0 for i in range(N + 1)]\n if N < 2:\n return 0\n for i in range(1, N + 1):\n if i % 3 == 0 and i % 2 == 0:\n data[i] = min(data[int(i / 3)], data[int(i / 2)], data[i - 1]) + 1\n elif i % 3 == 0:\n data[i] = min(int(i / 3), min(data[int(i / 3)], data[i - 1]) + 1)\n elif i % 2 == 0:\n data[i] = min(int(i / 2), min(data[int(i / 2)], data[i - 1]) + 1)\n else:\n data[i] = data[i - 1] + 1\n return data[N]", "from sys import maxsize as MAX_VALUE\n\ndef minsteps(n):\n arr = [69 for i in range(n + 1)]\n arr[1] = 0\n i = 2\n while i <= n:\n ans1 = arr[i - 1]\n ans2 = MAX_VALUE\n ans3 = MAX_VALUE\n if i % 2 == 0:\n ans2 = arr[i // 2]\n if i % 3 == 0:\n ans3 = arr[i // 3]\n arr[i] = 1 + min(ans1, ans2, ans3)\n i += 1\n return arr[n]", "from math import inf\n\ndef minsteps(n):\n if n < 1:\n return -1\n hm = dict()\n hm[0] = -1\n hm[1] = 0\n for i in range(2, n + 1):\n op1 = op2 = op3 = inf\n if i % 2 == 0:\n op1 = hm[i // 2] + 1\n if i % 3 == 0:\n op2 = hm[i // 3] + 1\n op3 = hm[i - 1] + 1\n hm[i] = min(op1, op2, op3)\n return hm[n]", "def minsteps(N):\n dp = [2 ** 63] * (N + 1)\n (dp[0], dp[1]) = (0, 0)\n for i in range(2, N + 1):\n if i % 3 == 0 and i % 2 == 0:\n dp[i] = min(dp[i // 2], dp[i // 3], dp[i - 1]) + 1\n elif i % 2 == 0:\n dp[i] = min(dp[i // 2], dp[i - 1]) + 1\n elif i % 3 == 0:\n dp[i] = min(dp[i // 3], dp[i - 1]) + 1\n else:\n dp[i] = dp[i - 1] + 1\n return dp[N]", "def recur(n):\n import sys\n global dp\n if n == 1:\n return 0\n if n < 0:\n return sys.maxsize\n if dp[n]:\n return dp[n]\n t = sys.maxsize\n th = sys.maxsize\n if n % 2 == 0:\n t = 1 + self.recur(n // 2)\n if n % 3 == 0:\n th = 1 + self.recur(n // 3)\n dp[n] = min(min(t, th), 1 + self.recur(n - 1))\n return dp[n]\n\ndef minsteps(N):\n import sys\n dp = [0] * (N + 1)\n for i in range(2, N + 1):\n two = sys.maxsize\n if i % 2 == 0:\n two = 1 + dp[i // 2]\n three = sys.maxsize\n if i % 3 == 0:\n three = 1 + dp[i // 3]\n dp[i] = min(1 + dp[i - 1], min(two, three))\n return dp[-1]", "def recur(n):\n import sys\n global dp\n if n == 1:\n return 0\n if n < 0:\n return sys.maxsize\n if dp[n]:\n return dp[n]\n t = sys.maxsize\n th = sys.maxsize\n if n % 2 == 0:\n t = 1 + self.recur(n // 2)\n if n % 3 == 0:\n th = 1 + self.recur(n // 3)\n dp[n] = min(min(t, th), 1 + self.recur(n - 1))\n return dp[n]\n\ndef minsteps(N):\n global dp\n dp = [0] * (N + 1)\n return self.recur(N)", "def minsteps(N):\n memo = {}\n\n def helper(n):\n if n in memo:\n return memo[n]\n if n == 1:\n return 0\n a = 1 + helper(n - 1)\n c = float('inf')\n b = float('inf')\n if n >= 2 and n % 2 == 0:\n c = 1 + helper(n / 2)\n if n >= 3 and n % 3 == 0:\n b = 1 + helper(n / 3)\n memo[n] = min(a, b, c)\n return memo[n]\n return helper(N)", "def minsteps(N):\n l = [0] * (N + 1)\n for i in range(2, N + 1):\n if i == 2 or i == 3:\n l[i] = 1\n continue\n s1 = s2 = s3 = float('inf')\n if i % 3 == 0:\n s1 = l[i // 3] + 1\n if i % 2 == 0:\n s2 = l[i // 2] + 1\n s3 = l[i - 1] + 1\n l[i] = min(s1, s2, s3)\n return l[-1]", "def minsteps(N):\n if N == 1:\n return 0\n if self.memo[N] != -1:\n return self.memo[N]\n ans = 100000.0\n if N % 2 == 0:\n ans = min(ans, self.minsteps(N // 2))\n if N % 3 == 0:\n ans = min(ans, self.minsteps(N // 3))\n ans = min(ans, self.minsteps(N - 1))\n self.memo[N] = ans + 1\n return self.memo[N]", "def minsteps(n):\n a = [-1 for i in range(n + 1)]\n a[1] = 0\n for i in range(2, n + 1):\n x = a[i - 1]\n y = 1000000\n if i % 2 == 0:\n y = a[i // 2]\n z = 1000000\n if i % 3 == 0:\n z = a[i // 3]\n a[i] = 1 + min(x, y, z)\n return a[n]", "def memo(n):\n global dp\n dp = [-1] * (n + 1)\n\ndef soln(n):\n if n == 0 or n == 1:\n return 0\n if dp[n] != -1:\n return dp[n]\n a = 10 ** 9 + 7\n b = 10 ** 9 + 7\n c = 10 ** 9 + 7\n if dp[n - 1] != -1:\n a = dp[n - 1]\n else:\n dp[n - 1] = self.soln(n - 1)\n a = dp[n - 1]\n if n % 2 == 0:\n if dp[n // 2] != -1:\n b = dp[n // 2]\n else:\n dp[n // 2] = self.soln(n // 2)\n b = dp[n // 2]\n if n % 3 == 0:\n if dp[n // 3] != -1:\n c = dp[n // 3]\n else:\n dp[n // 3] = self.soln(n // 3)\n c = dp[n // 3]\n dp[n] = 1 + min(a, b, c)\n return dp[n]\n\ndef minsteps(N):\n self.memo(N)\n return self.soln(N)", "def minsteps(N):\n n = N\n arr = [0, 0, 1, 1]\n if n < 4:\n return arr[n]\n for i in range(4, n + 1):\n x = float('inf')\n y = float('inf')\n if i % 2 == 0:\n x = arr[i // 2]\n if i % 3 == 0:\n y = arr[i // 3]\n z = i - 1\n arr.append(min(x, y, arr[z]) + 1)\n return arr[n]", "import sys\n\ndef minstep(N, memo):\n if N == 1:\n return 0\n ans1 = sys.maxsize\n if N % 3 == 0:\n if memo[N // 3] == -1:\n ans1 = self.minstep(N // 3, memo)\n memo[N // 3] = ans1\n else:\n ans1 = memo[N // 3]\n ans2 = sys.maxsize\n if N % 2 == 0:\n if memo[N // 2] == -1:\n ans2 = self.minstep(N // 2, memo)\n memo[N // 2] = ans2\n else:\n ans2 = memo[N // 2]\n if memo[N - 1] == -1:\n ans3 = self.minstep(N - 1, memo)\n memo[N - 1] = ans3\n else:\n ans3 = memo[N - 1]\n ans = 1 + min(ans1, ans2, ans3)\n return ans\n\ndef minsteps(N):\n memo = []\n for i in range(N + 1):\n memo.append(-1)\n ans = self.minstep(N, memo)\n return ans", "def minsteps(N):\n dp = [-1 for _ in range(N + 1)]\n return self.dp(N, dp)\n\ndef dp(N, dp):\n if N == 1:\n return 0\n ans1 = sys.maxsize\n if N % 3 == 0:\n if dp[N // 3] == -1:\n ans1 = self.dp(N // 3, dp)\n dp[N // 3] = ans1\n else:\n ans1 = dp[N // 3]\n ans2 = sys.maxsize\n if N % 2 == 0:\n if dp[N // 2] == -1:\n ans2 = self.dp(N // 2, dp)\n dp[N // 2] = ans2\n else:\n ans2 = dp[N // 2]\n if dp[N - 1] == -1:\n ans3 = self.dp(N - 1, dp)\n dp[N - 1] = ans3\n else:\n ans3 = dp[N - 1]\n return 1 + min(ans1, ans2, ans3)", "def minsteps(N):\n if N == 1:\n return 0\n elif N == 2:\n return 1\n elif N == 3:\n return 1\n else:\n arr = [0] * (N + 1)\n arr[0] = 100000\n arr[1] = 1\n arr[2] = 1\n arr[3] = 1\n for i in range(4, N + 1):\n arr[i] = arr[i - 1] + 1\n if i % 2 == 0:\n arr[i] = min(arr[i], arr[int(i / 2)] + 1)\n if i % 3 == 0:\n arr[i] = min(arr[i], arr[int(i / 3)] + 1)\n return arr[N]", "def minsteps(N):\n state = {}\n\n def helper(N, state):\n if N == 1:\n return 0\n if N in state:\n return state[N]\n result = helper(N - 1, state)\n if N % 2 == 0:\n result = min(result, helper(N / 2, state))\n if N % 3 == 0:\n result = min(result, helper(N / 3, state))\n state[N] = 1 + result\n return state[N]\n return helper(N, state)", "def minspteps(n, arr):\n if n == 1:\n return 0\n if arr[n] != 0:\n return arr[n]\n op1 = op2 = op3 = 9999999\n if n % 3 == 0:\n op1 = minspteps(n // 3, arr)\n if n % 2 == 0:\n op2 = minspteps(n // 2, arr)\n op3 = minspteps(n - 1, arr)\n arr[n] = min(op1, op2, op3) + 1\n return arr[n]\n\ndef minsteps(n):\n arr = [0] * (n + 1)\n return minspteps(n, arr)", "def helper(n, dp):\n if n == 1:\n return 0\n if dp[n] != -1:\n return dp[n]\n ans = self.helper(n - 1, dp)\n if n % 2 == 0:\n ans = min(ans, self.helper(n // 2, dp))\n if n % 3 == 0:\n ans = min(ans, self.helper(n // 3, dp))\n dp[n] = 1 + ans\n return dp[n]\n\ndef minsteps(N):\n dp = [-1] * (max(N, 4) + 1)\n dp[1] = 1\n (dp[2], dp[3]) = (1, 1)\n return self.helper(N, dp)", "def dpi(i, mem):\n if i in mem:\n return mem[i]\n if i == 1:\n return 0\n elif i % 3 == 0:\n ans = min(1 + dpi(i // 3, mem), 1 + dpi(i - 1, mem))\n mem[i] = ans\n elif i % 2 == 0:\n ans = min(1 + dpi(i // 2, mem), 1 + dpi(i - 1, mem))\n mem[i] = ans\n else:\n ans = 1 + dpi(i - 1, mem)\n mem[i] = ans\n return ans\n\ndef minsteps(N):\n mem = {}\n return dpi(N, mem)", "def mins(N, lst):\n if N == 2:\n return 1\n else:\n ans = min()\n return lst\n\ndef minsteps(N):\n dp = [0 for i in range(N + 1)]\n dp[1] = 0\n for i in range(2, N + 1):\n if i % 3 == 0:\n dp[i] = min(1 + dp[i // 3], 1 + dp[i - 1])\n elif i % 2 == 0:\n dp[i] = min(1 + dp[i // 2], 1 + dp[i - 1])\n else:\n dp[i] = 1 + dp[i - 1]\n return dp[N]", "import sys\n\ndef minsteps(N):\n dp = [-1] * (N + 1)\n return self.dp(N, dp)\n\ndef dp(N, dp):\n if N == 1:\n return 0\n ans1 = sys.maxsize\n if N % 3 == 0:\n if dp[N // 3] == -1:\n ans1 = self.dp(N // 3, dp)\n dp[N // 3] = ans1\n else:\n ans1 = dp[N // 3]\n ans2 = sys.maxsize\n if N % 2 == 0:\n if dp[N // 2] == -1:\n ans2 = self.dp(N // 2, dp)\n dp[N // 2] = ans2\n else:\n ans2 = dp[N // 2]\n if dp[N - 1] == -1:\n ans3 = self.dp(N - 1, dp)\n dp[N - 1] = ans3\n else:\n ans3 = dp[N - 1]\n return 1 + min(ans1, ans2, ans3)", "from collections import deque\n\ndef minsteps(N):\n step = 0\n q = deque([(N, step)])\n while q:\n (curr, steps) = q.popleft()\n if curr == 1:\n return steps\n if curr % 2 == 0:\n q.append((curr // 2, steps + 1))\n if curr % 3 == 0:\n q.append((curr // 3, steps + 1))\n q.append((curr - 1, steps + 1))"], "starter_code": "def minsteps(N):\n", "input_output": {"inputs": ["N = 10", "N = 1"], "outputs": ["3", "0"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/minimum-steps-to-minimize-n-as-per-given-condition0618/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "minsteps", "task_id": "TACO_lite/243", "example": [[[10], [1]], ["3", "0"]]} +{"requirement": "Given a binary tree and an integer S, check whether there is root to leaf path with its sum as S.\nExample 1:\nInput:\nTree = \n 1\n / \\\n 2 3\nS = 2\nOutput: 0\nExplanation:\nThere is no root to leaf path with sum 2.\nExample 2:\nInput:\nTree = \n 1\n / \\\n 2 3\nS = 4\nOutput: 1\nExplanation:\nThe sum of path from leaf node 3 to root 1 is 4.\nYour Task: \nYou dont need to read input or print anything. Complete the function hasPathSum() which takes root node and target sum S as input parameter and returns true if path exists otherwise it returns false.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(height of tree)\nConstraints:\n1 ≤ N ≤ 10^4\n1 ≤ S ≤ 10^6", "solutions": ["def hasPathSum(root, S):\n\n def path(rt, c, s):\n if rt is None:\n return\n if rt.left is None and rt.right is None:\n return s == c + rt.data\n return path(rt.left, c + rt.data, s) or path(rt.right, c + rt.data, s)\n return path(root, 0, S)", "def hasPathSum(root, S):\n\n def fun(root, S):\n sumi = 0\n S = S - root.data\n if root is None:\n return 0\n if root.left is None and root.right is None and (S == 0):\n return 1\n if root.left:\n sumi = sumi or fun(root.left, S)\n if root.right:\n sumi = sumi or fun(root.right, S)\n return sumi\n t = fun(root, S)\n return t", "def inorder(root, S, su):\n if root is None:\n return False\n su += root.data\n if su == S and root.left == None and (root.right == None):\n return True\n if inorder(root.left, S, su) or inorder(root.right, S, su):\n return True\n return False\n\ndef hasPathSum(root, S):\n su = 0\n return inorder(root, S, su)", "def check(root, S, a):\n if root == None:\n return False\n a += root.data\n if a == S and root.left == None and (root.right == None):\n return True\n if check(root.left, S, a) or check(root.right, S, a):\n return True\n return False\n\ndef __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef hasPathSum(root, S):\n a = 0\n return check(root, S, a)", "def tree(root, S, ans):\n if root == None:\n return False\n ans += root.data\n if ans == S and root.left == None and (root.right == None):\n return True\n if tree(root.left, S, ans) or tree(root.right, S, ans):\n return True\n return False\n\ndef hasPathSum(root, S):\n ans = 0\n if tree(root, S, ans):\n return 1\n return 0", "def hasPathSum(root, S):\n if root == None:\n return 0\n subsum = S - root.data\n if subsum == 0 and root.left == None and (root.right == None):\n return True\n return self.hasPathSum(root.left, subsum) or self.hasPathSum(root.right, subsum)", "def hasPathSum(root, S):\n\n def dfs(node, currsum):\n if not node:\n return False\n currsum += node.data\n if not node.left and (not node.right):\n return currsum == S\n return dfs(node.left, currsum) or dfs(node.right, currsum)\n return dfs(root, 0)", "def hasPathSum(root, S):\n\n def dfs(root, sumi):\n if root is None:\n return False\n sumi += root.data\n if root.left is None and root.right is None:\n return sumi == S\n return dfs(root.left, sumi) or dfs(root.right, sumi)\n return dfs(root, 0)", "def fun(root, s, S):\n if root == None:\n return\n s += root.data\n if s > S:\n return\n if s == S:\n if root.left == None and root.right == None:\n self.res = 1\n else:\n return\n self.fun(root.left, s, S)\n self.fun(root.right, s, S)\n\ndef hasPathSum(root, S):\n self.fun(root, 0, S)\n return self.res", "def hasPathSum(root, S):\n if root is None:\n return False\n if root.left is None and root.right is None and (root.data == S):\n return True\n else:\n return self.hasPathSum(root.left, S - root.data) or self.hasPathSum(root.right, S - root.data)", "def hasPathSum(root, S):\n\n def dfs(root, s):\n if root == None:\n return False\n if root.left == None and root.right == None:\n if s - root.data == 0:\n return True\n return False\n return dfs(root.left, s - root.data) or dfs(root.right, s - root.data)\n return dfs(root, S)", "def hasPathSum(root, S):\n\n def path(root, currSum):\n if not root:\n return False\n currSum += root.data\n if not root.left and (not root.right) and (currSum == S):\n return True\n return path(root.left, currSum) or path(root.right, currSum)\n return path(root, 0)", "def solve(root, S):\n if root == None:\n return False\n if root.left == None and root.right == None:\n S -= root.data\n if S == 0:\n return True\n else:\n return False\n l = self.solve(root.left, S - root.data)\n if l == True:\n return True\n r = self.solve(root.right, S - root.data)\n if r == True:\n return True\n return False\n\ndef hasPathSum(root, S):\n return self.solve(root, S)", "def hasPathSum(root, S):\n global b\n b = False\n\n def finder(root, c):\n global b\n if root == None:\n return\n c += root.data\n if c == S and root.left == None and (root.right == None):\n b = True\n return\n if c > S:\n return\n finder(root.left, c)\n finder(root.right, c)\n finder(root, 0)\n return b", "def hasPathSum(root, S):\n\n def helper(root, add):\n if not root:\n return\n add += root.data\n if root.left is None and root.right is None:\n return add == S\n return helper(root.left, add) or helper(root.right, add)\n return helper(root, 0)", "def hasPathSum(root, S):\n\n def rec(root, d):\n if root.left == None and root.right == None:\n if d + root.data == S:\n return True\n return False\n t1 = False\n t2 = False\n if root.left:\n t1 = rec(root.left, d + root.data)\n if root.right:\n t2 = rec(root.right, d + root.data)\n return t1 or t2\n return rec(root, 0)", "def hasPathSum(root, S):\n\n def hasPathSum(node, s):\n ans = 0\n subSum = s - node.data\n if subSum == 0 and node.left == None and (node.right == None):\n return True\n if node.left is not None:\n ans = ans or hasPathSum(node.left, subSum)\n if node.right is not None:\n ans = ans or hasPathSum(node.right, subSum)\n return ans\n return hasPathSum(root, S)", "def hasPathSum(node, s):\n if node is None:\n return s == 0\n else:\n ans = 0\n subSum = s - node.data\n if subSum == 0 and node.left == None and (node.right == None):\n return True\n if node.left:\n ans = ans or self.hasPathSum(node.left, subSum)\n if node.right:\n ans = ans or self.hasPathSum(node.right, subSum)\n return ans", "def hasPathSum(root, S):\n\n def helper(root, target, value):\n if not root:\n return False\n if not root.left and (not root.right):\n return target == value + root.data\n return helper(root.left, target, value + root.data) or helper(root.right, target, value + root.data)\n return helper(root, S, 0)", "def solution(root, s, arr):\n if root == None:\n return False\n arr += root.data\n if arr == s and root.left is None and (root.right is None):\n return True\n l = self.solution(root.left, s, arr)\n if l:\n return True\n r = self.solution(root.right, s, arr)\n if r:\n return True\n arr -= root.data\n return False\n\ndef hasPathSum(root, S):\n if root == None:\n return 1\n arr = 0\n if self.solution(root, S, arr):\n return 1\n return 0", "def hasPathSum(root, S):\n if root == None:\n return 0\n if S == root.data and root.left == None and (root.right == None):\n return 1\n return self.hasPathSum(root.left, S - root.data) or self.hasPathSum(root.right, S - root.data)", "def hasPathSum(root, S):\n sum = set()\n\n def dfs(root, sum_):\n if not root:\n return\n sum_ += root.data\n if root.left or root.right:\n dfs(root.left, sum_)\n dfs(root.right, sum_)\n else:\n sum.add(sum_)\n dfs(root, 0)\n if S in sum:\n return True\n return False"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["Tree = \n 1\n / \\\n 2 3\nS = 2", "Tree = \n 1\n / \\\n 2 3\nS = 4"], "outputs": ["0", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/root-to-leaf-path-sum/1", "Expected Auxiliary Space": "O(height of tree)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "__init__", "task_id": "TACO_lite/126", "example": [[], []]} +{"requirement": "Given an array arr[] of integers of size N and a number X, the task is to find the sum of subarray having maximum sum less than or equal to the given value of X.\nExample 1:\nInput: N = 5, X = 11\narr[] = {1, 2, 3, 4, 5} \nOutput: 10\nExplanation: Subarray having maximum \nsum is {1, 2, 3, 4}.\n \nExample 2:\nInput: N = 5, X = 7\narr[] = {2, 4, 6, 8, 10} \nOutput: 6\nExplanation: Subarray having maximum \nsum is {2, 4} or {6}.\n \nYour Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function calculateMaxSumLength() that takes array arr, integer N, and integer X as parameters and returns maximum sum of any subarray that is less than or equal to x.\n \nExpected Time Complexity: O(N). \nExpected Auxiliary Space: O(1).\n \nConstraints:\n1 ≤ N ≤ 10^{6}\n1 ≤ arr[i] ≤ 10^{4}", "solutions": ["def findmaxsubarraysum(arr, n, k):\n sum = 0\n ans = 0\n (i, j) = (0, 0)\n while j < n:\n sum += arr[j]\n if sum < k:\n ans = max(ans, sum)\n j += 1\n elif sum == k:\n return k\n else:\n while sum > k:\n sum -= arr[i]\n i += 1\n ans = max(ans, sum)\n j += 1\n return ans", "def findmaxsubarraysum(arr, n, k):\n max1 = 0\n s = 0\n i = 0\n j = 0\n while i < n:\n s += arr[i]\n if s > k:\n while s > k:\n s -= arr[j]\n j += 1\n max1 = max(max1, s)\n i += 1\n max1 = max(max1, s)\n return max1", "def findmaxsubarraysum(arr, n, k):\n (ans, cur) = (0, 0)\n (fp, sp) = (0, 0)\n while sp < n:\n if cur <= k:\n cur += arr[sp]\n while cur > k and fp <= sp:\n cur -= arr[fp]\n fp += 1\n sp += 1\n ans = max(ans, cur)\n return ans", "import math\n\ndef findmaxsubarraysum(arr, n, k):\n maxi = -math.inf\n fsum = 0\n left = 0\n for i in range(n):\n fsum += arr[i]\n while fsum > k:\n fsum -= arr[left]\n left += 1\n maxi = max(maxi, fsum)\n return maxi", "def findmaxsubarraysum(arr, n, k):\n left = 0\n maxi = 0\n su = 0\n for right in range(0, n):\n su += arr[right]\n while su > k:\n su -= arr[left]\n left += 1\n maxi = max(maxi, su)\n return maxi", "def findmaxsubarraysum(arr, n, k):\n maxSum = 0\n (head, tail) = (0, 0)\n maxVal = -1\n while tail < n:\n maxSum += arr[tail]\n if maxSum == k:\n return k\n elif maxSum > k:\n while head <= tail:\n maxSum -= arr[head]\n head = head + 1\n if maxSum == k:\n return k\n elif maxSum < k:\n maxVal = max(maxVal, maxSum)\n break\n else:\n maxVal = max(maxVal, maxSum)\n tail += 1\n return maxVal", "def findmaxsubarraysum(arr, n, k):\n max_sum = float('-inf')\n curr_sum = 0\n i = 0\n j = 0\n while j < n:\n curr_sum += arr[j]\n if curr_sum <= k:\n max_sum = max(max_sum, curr_sum)\n else:\n while curr_sum > k:\n curr_sum -= arr[i]\n if curr_sum <= k:\n max_sum = max(max_sum, curr_sum)\n i += 1\n j += 1\n return max_sum", "def findmaxsubarraysum(arr, n, k):\n maxi = float('-inf')\n i = 0\n j = 0\n pre = 0\n while i < n:\n pre += arr[i]\n if pre <= k:\n maxi = max(pre, maxi)\n else:\n while pre > k and j <= i:\n pre -= arr[j]\n j += 1\n if pre <= k:\n maxi = max(maxi, pre)\n i += 1\n return maxi", "def findmaxsubarraysum(arr, n, k):\n maxi = 0\n total = arr[0]\n (start, end) = (0, 0)\n while start < n and end < n:\n if total <= k:\n maxi = max(maxi, total)\n end += 1\n if end < n:\n total += arr[end]\n else:\n total -= arr[start]\n start += 1\n return maxi", "def findmaxsubarraysum(arr, n, k):\n subasum = arr[0]\n sum = 0\n for i in range(0, n):\n subasum = arr[i]\n if subasum < k:\n sum = max(subasum, sum)\n elif subasum == k:\n return subasum\n for j in range(i + 1, n):\n subasum = subasum + arr[j]\n if subasum < k:\n sum = max(subasum, sum)\n elif subasum == k:\n return subasum\n elif subasum > k:\n break\n return sum", "def findmaxsubarraysum(arr, n, k):\n i = 0\n j = 0\n summ = 0\n maxi = -1000000007\n while i < n:\n summ += arr[i]\n if summ <= k:\n maxi = max(maxi, summ)\n else:\n while summ > k and j <= i:\n summ -= arr[j]\n j += 1\n if summ <= k:\n maxi = max(maxi, summ)\n i += 1\n return maxi", "def findmaxsubarraysum(arr, n, k):\n maxi = 0\n summa = 0\n j = 0\n for item in arr:\n while j < n and summa + arr[j] <= k:\n summa += arr[j]\n maxi = max(maxi, summa)\n j += 1\n summa -= item\n return maxi", "def findmaxsubarraysum(arr, n, k):\n left = 0\n s = 0\n m = 0\n for right in range(n):\n s += arr[right]\n if s <= k:\n m = max(s, m)\n else:\n while s > k and left <= right:\n s -= arr[left]\n left += 1\n if s <= k:\n m = max(m, s)\n return m", "def findmaxsubarraysum(arr, n, k):\n a = -1\n sum = 0\n s = 0\n for i in range(n):\n sum += arr[i]\n while sum > k:\n sum -= arr[s]\n s = s + 1\n else:\n a = max(a, sum)\n return a", "def findmaxsubarraysum(arr, n, k):\n i = 0\n j = 0\n sumi = 0\n maxi = 0\n while j < len(arr):\n sumi = sumi + arr[j]\n if sumi <= k:\n maxi = max(maxi, sumi)\n while sumi > k:\n sumi = sumi - arr[i]\n if sumi <= k:\n maxi = max(maxi, sumi)\n i = i + 1\n j = j + 1\n return maxi", "def findmaxsubarraysum(a, n, x):\n for i in a:\n assert i > 0 and i <= 10 ** 4\n if sum(a) <= x:\n return sum(a)\n total = 0\n ans = -1\n start = 0\n for i in range(n + 1):\n while total > x and start < i - 1:\n total -= a[start]\n start += 1\n if total < x:\n ans = max(ans, total)\n elif total == x:\n return x\n if i < n:\n total += a[i]\n return ans", "def findmaxsubarraysum(arr, n, k):\n l = r = 0\n ma = 0\n cu = arr[0]\n while r < n:\n if cu <= k:\n ma = max(ma, cu)\n r += 1\n if r < n:\n cu += arr[r]\n if cu > k:\n cu -= arr[l]\n l += 1\n return ma", "def findmaxsubarraysum(arr, n, k):\n res = float('-inf')\n s = 0\n j = 0\n for i in range(n):\n s += arr[i]\n if s > k:\n while j <= i and s > k:\n s -= arr[j]\n j += 1\n if s <= k:\n res = max(res, s)\n if res == k:\n return k\n if res != float('-inf'):\n return res\n return -1", "def findmaxsubarraysum(arr, n, k):\n i = 0\n sums = 0\n maxi = 0\n for j in range(n):\n sums += arr[j]\n if sums <= k:\n maxi = max(maxi, sums)\n while sums > k:\n sums -= arr[i]\n i += 1\n if sums <= k:\n maxi = max(maxi, sums)\n return maxi", "def findmaxsubarraysum(arr, n, k):\n start = 0\n tot = 0\n res = 0\n for end in range(n):\n tot += arr[end]\n while tot > k:\n tot -= arr[start]\n start += 1\n res = max(res, tot)\n return res", "def findmaxsubarraysum(arr, n, k):\n currSum = 0\n start = 0\n maxSum = 0\n for i in range(n):\n currSum += arr[i]\n while currSum > k:\n currSum -= arr[start]\n start += 1\n maxSum = max(maxSum, currSum)\n return maxSum", "def findmaxsubarraysum(arr, n, k):\n sumi = 0\n res = 0\n j = 0\n for i in range(n):\n sumi += arr[i]\n while k < sumi:\n sumi -= arr[j]\n j += 1\n if sumi <= k:\n res = max(res, sumi)\n return res", "def findmaxsubarraysum(arr, n, k):\n c = 0\n s = 0\n res = 0\n for i in range(n):\n s = s + arr[i]\n while s > k:\n s = s - arr[c]\n c = c + 1\n res = max(s, res)\n return res", "def findmaxsubarraysum(arr, n, k):\n ws = 0\n we = 0\n res = 0\n sumi = 0\n for we in range(n):\n sumi += arr[we]\n while sumi > k:\n sumi -= arr[ws]\n ws += 1\n if sumi <= k:\n res = max(res, sumi)\n return res", "def findmaxsubarraysum(arr, n, k):\n i = 0\n j = 1\n currSum = arr[0]\n maxSum = 0\n while i <= j and j < n:\n if currSum <= k:\n maxSum = max(maxSum, currSum)\n while currSum + arr[j] > k and i < j:\n currSum -= arr[i]\n i += 1\n currSum += arr[j]\n j += 1\n if currSum <= k:\n maxSum = max(maxSum, currSum)\n return maxSum", "def findmaxsubarraysum(arr, n, k):\n currsum = arr[0]\n start = 0\n maxsum = 0\n if n == 1:\n if arr[0] <= k:\n return arr[0]\n else:\n return 0\n for i in range(1, n):\n if currsum <= k:\n maxsum = max(maxsum, currsum)\n while currsum + arr[i] > k and start < i:\n currsum = currsum - arr[start]\n start = start + 1\n currsum = currsum + arr[i]\n if currsum <= k:\n maxsum = max(maxsum, currsum)\n return maxsum", "def findmaxsubarraysum(arr, n, k):\n j = 0\n Maxlen = 0\n Sum = 0\n for i in range(n):\n Sum += arr[i]\n while Sum > k:\n Sum -= arr[j]\n j += 1\n Maxlen = max(Sum, Maxlen)\n return Maxlen", "def findmaxsubarraysum(arr, n, k):\n ans = 0\n sm = 0\n s = 0\n for e in range(n):\n sm += arr[e]\n while sm > k and s < e:\n sm -= arr[s]\n s += 1\n if sm <= k:\n ans = max(ans, sm)\n return ans", "def findmaxsubarraysum(arr, n, k):\n ans = 0\n s = 0\n j = 0\n for i in range(n):\n s += arr[i]\n while s > k:\n s -= arr[j]\n j += 1\n ans = max(ans, s)\n return ans", "def findmaxsubarraysum(arr, n, k):\n start = 0\n total = 0\n curr_sum = 0\n for i in range(n):\n if curr_sum <= k:\n total = max(total, curr_sum)\n while curr_sum + arr[i] > k and start < i:\n curr_sum -= arr[start]\n start += 1\n curr_sum += arr[i]\n if curr_sum <= k:\n total = max(total, curr_sum)\n return total", "def findmaxsubarraysum(arr, n, k):\n if k in arr:\n return k\n (maxx, summ) = (0, 0)\n j = 0\n for i in range(n):\n summ += arr[i]\n if summ > k:\n while summ > k:\n summ -= arr[j]\n j += 1\n if summ <= k:\n maxx = max(summ, maxx)\n return maxx", "def findmaxsubarraysum(arr, n, k):\n l = 0\n sum1 = 0\n maxi = 0\n for r in range(n):\n sum1 += arr[r]\n while sum1 > k:\n maxi = max(maxi, sum(arr[l:r]))\n sum1 -= arr[l]\n l += 1\n maxi = max(maxi, sum1)\n return maxi", "def findmaxsubarraysum(arr, n, k):\n i = 0\n j = 0\n s = 0\n d = -999999999\n while j < n:\n s += arr[j]\n if s <= k and s > d:\n d = s\n while s > k:\n s = s - arr[i]\n i += 1\n if s <= k and s > d:\n d = s\n j += 1\n return d", "import sys\n\ndef findmaxsubarraysum(arr, n, k):\n (start, end, curr_sum, max_sum) = (0, 0, 0, -sys.maxsize)\n while end < n:\n curr_sum = curr_sum + arr[end]\n while start <= end and curr_sum > k:\n curr_sum = curr_sum - arr[start]\n start = start + 1\n max_sum = max(curr_sum, max_sum)\n end = end + 1\n return max_sum", "def findmaxsubarraysum(arr, n, k):\n count = 0\n ans = -1 << 32\n left = right = cur = 0\n while right < n:\n cur += arr[right]\n while cur > k:\n cur -= arr[left]\n left += 1\n ans = max(ans, cur)\n right += 1\n return ans", "def findmaxsubarraysum(arr, n, k):\n i = 0\n j = 0\n mx = float('-inf')\n sum = 0\n while j < n:\n sum += arr[j]\n while sum > k:\n sum -= arr[i]\n i += 1\n mx = max(sum, mx)\n j += 1\n return mx", "def findmaxsubarraysum(arr, n, k):\n curr_sum = 0\n max_sum = -12345678\n start = 0\n for i in range(n):\n curr_sum += arr[i]\n while curr_sum > k:\n curr_sum = curr_sum - arr[start]\n start += 1\n max_sum = max(max_sum, curr_sum)\n return max_sum", "def findmaxsubarraysum(C, n, B):\n sum = 0\n ans = 0\n start = 0\n end = 0\n while end < len(C):\n sum += C[end]\n if sum <= B:\n ans = max(ans, sum)\n elif sum > B:\n while sum > B:\n sum = sum - C[start]\n start += 1\n ans = max(ans, sum)\n end += 1\n return ans", "def findmaxsubarraysum(arr, n, k):\n currsum = 0\n maxSum = 0\n (i, j) = (0, 0)\n while j < len(arr):\n currsum += arr[j]\n if currsum > k:\n while currsum > k:\n currsum -= arr[i]\n i += 1\n maxSum = max(maxSum, currsum)\n j += 1\n return maxSum", "def findmaxsubarraysum(arr, n, k):\n start = 0\n s = 0\n end = 0\n a = []\n for end in range(n):\n s = s + arr[end]\n while s > k:\n s = s - arr[start]\n start = start + 1\n else:\n a.append(s)\n a.sort()\n return a[-1]", "def findmaxsubarraysum(arr, n, k):\n (i, j) = (0, 0)\n res = 0\n summ = 0\n while j < n:\n summ += arr[j]\n while i <= j and summ > k:\n summ -= arr[i]\n i += 1\n res = max(res, summ)\n j += 1\n return res", "def findmaxsubarraysum(arr, n, k):\n curr = arr[0]\n maxx = 0\n start = 0\n for i in range(1, n):\n if curr <= k:\n maxx = max(curr, maxx)\n while curr + arr[i] > k and start < i:\n curr -= arr[start]\n start += 1\n curr += arr[i]\n if curr <= k:\n maxx = max(curr, maxx)\n return maxx", "def findmaxsubarraysum(arr, n, k):\n currSum = 0\n ws = 0\n maxSum = 0\n for we in range(n):\n currSum += arr[we]\n while currSum > k and ws <= we:\n currSum -= arr[ws]\n ws += 1\n if currSum > maxSum and currSum <= k:\n maxSum = currSum\n return maxSum", "def findmaxsubarraysum(arr, n, k):\n s = 0\n mx = min(arr)\n i = 0\n j = 0\n while j < len(arr):\n s += arr[j]\n while s > k:\n s -= arr[i]\n i += 1\n mx = max(s, mx)\n j += 1\n if mx > k:\n return 0\n return mx", "def findmaxsubarraysum(arr, n, k):\n i = 0\n j = 0\n Sum = 0\n mx = 0\n while j < n:\n Sum = Sum + arr[j]\n if Sum <= k:\n j = j + 1\n mx = max(mx, Sum)\n elif Sum > k:\n while Sum > k:\n Sum = Sum - arr[i]\n i = i + 1\n if Sum <= k:\n mx = max(mx, Sum)\n j = j + 1\n return mx", "def findmaxsubarraysum(arr, n, k):\n i = 0\n j = 0\n maxsum = 0\n tempsum = 0\n while j != n:\n tempsum += arr[j]\n j += 1\n while tempsum > k:\n tempsum -= arr[i]\n i += 1\n maxsum = max(maxsum, tempsum)\n return maxsum", "def findmaxsubarraysum(arr, n, k):\n startIndex = 0\n currentSum = 0\n maxSum = 0\n for endIndex in range(0, n):\n if currentSum <= k:\n maxSum = max(maxSum, currentSum)\n while currentSum + arr[endIndex] > k and startIndex < n:\n currentSum -= arr[startIndex]\n startIndex += 1\n currentSum += arr[endIndex]\n if currentSum <= k:\n maxSum = max(maxSum, currentSum)\n return maxSum", "def findmaxsubarraysum(arr, n, sum):\n curr_sum = arr[0]\n max_sum = 0\n start = 0\n for i in range(1, n):\n if curr_sum <= sum:\n max_sum = max(max_sum, curr_sum)\n while curr_sum + arr[i] > sum and start < i:\n curr_sum -= arr[start]\n start += 1\n curr_sum += arr[i]\n if curr_sum <= sum:\n max_sum = max(max_sum, curr_sum)\n return max_sum", "def findmaxsubarraysum(arr, n, k):\n maxi = 0\n a = []\n currentsum = 0\n index = 0\n while index < n:\n currentsum += arr[index]\n a.append(arr[index])\n if currentsum <= k:\n maxi = max(maxi, currentsum)\n else:\n while currentsum > k:\n if len(a) == 0:\n break\n currentsum -= a[0]\n a.pop(0)\n maxi = max(maxi, currentsum)\n index += 1\n return maxi", "def findmaxsubarraysum(a, n, k):\n i = 0\n j = 0\n sa = 0\n ma = float('-inf')\n while j < n:\n sa += a[j]\n if sa <= k:\n ma = max(ma, sa)\n elif sa > k:\n while sa > k:\n sa -= a[i]\n i += 1\n if sa <= k:\n ma = max(ma, sa)\n j += 1\n return ma", "def findmaxsubarraysum(arr, n, k):\n right = 0\n left = -1\n add = 0\n max_val = 0\n while right < n:\n if add + arr[right] < k:\n add += arr[right]\n max_val = max(max_val, add)\n right += 1\n elif add + arr[right] == k:\n return k\n else:\n left += 1\n right = left\n add = 0\n return max_val", "def findmaxsubarraysum(arr, n, x):\n slow = 0\n fast = 0\n total = 0\n maxer = 0\n while fast < len(arr):\n total += arr[fast]\n if total <= x:\n maxer = max(maxer, total)\n elif total > x:\n while total > x:\n total -= arr[slow]\n slow += 1\n if total <= x:\n maxer = max(maxer, total)\n fast += 1\n return maxer", "def findmaxsubarraysum(arr, n, k):\n (cur_sum, max_sum) = (0, -10 ** 9)\n l = 0\n for i in range(n):\n cur_sum += arr[i]\n while l <= i and cur_sum > k:\n cur_sum -= arr[l]\n l += 1\n max_sum = max(max_sum, cur_sum)\n return max_sum", "def findmaxsubarraysum(arr, n, k):\n for i in range(1, n):\n arr[i] = arr[i - 1] + arr[i]\n x = 0\n y = 0\n max_val = -9223372036854775806\n while x < n:\n if arr[x] <= k:\n max_val = max(max_val, arr[x])\n else:\n while arr[x] - arr[y] > k and x > y:\n y += 1\n max_val = max(max_val, arr[x] - arr[y])\n x += 1\n if max_val == k:\n return k\n return max_val"], "starter_code": "def findmaxsubarraysum(arr, n, k):\n", "input_output": {"inputs": ["N = 5, X = 11\r\narr[] = {1, 2, 3, 4, 5}", "N = 5, X = 7\r\narr[] = {2, 4, 6, 8, 10}"], "outputs": ["10", "6"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "two-pointer-algorithm", "sliding-window", "Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Amortized analysis"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/maximum-sum-of-subarray-less-than-or-equal-to-x4033/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "findmaxsubarraysum", "task_id": "TACO_lite/112", "example": [[[5, 11, [1, 2, 3, 4, 5]], [5, 7, [2, 4, 6, 8, 10]]], ["10", "6"]]} +{"requirement": "Your task is very simple. Just write a function `isAlphabetic(s)`, which takes an input string `s` in lowercase and returns `true`/`false` depending on whether the string is in alphabetical order or not.\n\nFor example, `isAlphabetic('kata')` is False as 'a' comes after 'k', but `isAlphabetic('ant')` is True.\n\nGood luck :)", "solutions": ["def alphabetic(s):\n return sorted(s) == list(s)", "def alphabetic(s):\n return all((a <= b for (a, b) in zip(s, s[1:])))", "def alphabetic(s):\n for i in range(1, len(s)):\n if s[i - 1] > s[i]:\n return False\n return True", "def alphabetic(s):\n return s == ''.join(sorted(s))", "def alphabetic(string):\n return string == ''.join(sorted(string))", "def alphabetic(s):\n n = len(s)\n c = [s[i] for i in range(len(s))]\n c.sort(reverse=False)\n for i in range(n):\n if c[i] != s[i]:\n return False\n return True", "def alphabetic(s):\n arr = [x for x in s]\n return arr == sorted(arr)", "alphabetic = lambda str: sorted(str) == list(str)"], "starter_code": "def alphabetic(s):\n", "input_output": {"fn_name": "alphabetic", "inputs": [["asd"], ["codewars"], ["door"], ["cell"], ["z"], [""]], "outputs": [[false], [false], [true], [true], [true], [true]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5a8059b1fd577709860000f6", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "alphabetic", "task_id": "TACO_lite/226", "example": [[["kata"], ["ant"]], ["False", "True"]]} +{"requirement": "Given a number N find the sum of all the even valued terms in the Fibonacci sequence less than or equal to N.\nThe first few terms of Fibonacci Numbers are, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ,… (Even numbers are highlighted).\n \nExample 1:\nInput:\nN = 8\nOutput:\n10\nExplanation:\nThere are two even \nfibonacci numbers less\nthan equal to 8, 8 and 2 \nand 8 + 2 = 10\nExample 2:\nInput:\nN = 89\nOutput:\n44\nExplanation:\nThere are three even\nfibonacci numbers less than\nequal to 89, 8, 2 and 34 \n8 + 2 + 34 = 44\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function evenFibSum() which takes an integer N as input parameters and returns the sum of all the Fibonacci number less than equal to N.\n \nExpected Time Complexity: O(N)\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= N <= 10^{6}", "solutions": ["def fib(n, memo={}):\n if n in memo:\n return memo[n]\n elif n < 3:\n memo[n] = 1\n else:\n memo[n] = fib(n - 1) + fib(n - 2)\n return memo[n]\n\ndef evenfibsum(N):\n n = 1\n curr_fib_num = 0\n sum = 0\n while curr_fib_num <= N:\n sum += curr_fib_num\n curr_fib_num = fib(3 * n)\n n += 1\n return sum", "def evenfibsum(N):\n a = 0\n b = 1\n c = 0\n s = 0\n if N == 0 or N == 1:\n return 0\n for i in range(2, N + 1):\n c = a + b\n if c > N:\n break\n elif c % 2 == 0:\n s = s + c\n a = b\n b = c\n return s", "def evenfibsum(N):\n a = 0\n b = 1\n s = 0\n c = 0\n while c < N:\n c = a + b\n a = b\n b = c\n if b % 2 == 0 and b < N:\n s = s + b\n return s", "def evenfibsum(N):\n (n1, n2) = (1, 2)\n sum = 2\n while True:\n n3 = n1 + n2\n if n3 > N:\n break\n if n3 % 2 == 0:\n sum += n3\n n1 = n2\n n2 = n3\n return sum", "def evenfibsum(N):\n (a, b, c, summ) = (1, 1, 1, 0)\n mod = 10 ** 9 + 7\n while c <= N:\n c = (a + b) % mod\n if N >= c and c & 1 == 0:\n summ += c\n (a, b) = (b, c)\n return summ", "def evenfibsum(N):\n (a, b, c, s, i) = (1, 2, 2, 2, 0)\n m = 10 ** 9 + 7\n while N >= c:\n c = a + b\n a = b\n b = c\n if N >= c and c % 2 == 0:\n s += c\n i += 1\n return s", "def evenfibsum(N):\n if N < 2:\n return 0\n ef1 = 0\n ef2 = 2\n sm = ef1 + ef2\n while N > 2:\n ef3 = 4 * ef2 + ef1\n if ef3 > N:\n break\n ef1 = ef2\n ef2 = ef3\n sm = sm + ef2\n return sm", "def evenfibsum(n):\n k = []\n a = 0\n b = 1\n s = 0\n while a <= n:\n c = a + b\n if a % 2 == 0:\n s += a\n a = b\n b = c\n return s", "def evenfibsum(N):\n a = 0\n b = 1\n c = 0\n l = []\n s = 0\n while a <= N:\n if a & 1 == 0 and a <= N:\n s = s + a\n l.append(a)\n c = a + b\n a = b\n b = c\n return s", "def evenfibsum(N):\n f = [0, 1]\n arr = []\n for i in range(2, N):\n if f[i - 1] + f[i - 2] <= N:\n f.append(f[i - 1] + f[i - 2])\n if (f[i - 1] + f[i - 2]) % 2 == 0:\n arr.append(f[i - 1] + f[i - 2])\n else:\n break\n return sum(arr)", "def evenfibsum(N):\n if N < 2:\n return 0\n ans = 0\n a = 0\n b = 1\n for i in range(1000):\n c = a + b\n if c > N:\n break\n if c % 2 == 0:\n ans += c\n a = b\n b = c\n return ans", "def evenfibsum(N):\n ret = []\n ret.append(0)\n ret.append(1)\n summ = 0\n for i in range(2, N + 1):\n ret.append(ret[0] + ret[1])\n if ret[-1] > N:\n break\n if ret[-1] % 2 == 0:\n summ += ret[-1]\n ret.pop(0)\n return summ", "def evenfibsum(N):\n fib1 = 0\n fib2 = 2\n sum = fib1 + fib2\n if N <= 2:\n return 0\n while fib2 <= N:\n fib3 = 4 * fib2 + fib1\n if fib3 > N:\n break\n fib1 = fib2\n fib2 = fib3\n sum += fib2\n return sum", "def evenfibsum(N):\n sum = 0\n f = [1, 1]\n while f[1] < N:\n v = f[0] + f[1]\n if v % 2 == 0 and v <= N:\n sum += f[0] + f[1]\n (f[0], f[1]) = (f[1], f[0] + f[1])\n return sum", "def evenfibsum(N):\n evenSum = 0\n first = 1\n second = 1\n while N >= second:\n third = first + second\n if second % 2 == 0:\n evenSum += second\n first = second\n second = third\n return evenSum", "def evenfibsum(n):\n S = 0\n x = 0\n y = 1\n res = 0\n while res <= n:\n res = x + y\n if res % 2 == 0:\n S = S + res\n x = y\n y = res\n if res > n and res % 2 == 0:\n S = S - res\n return S", "def evenfibsum(N):\n a = 1\n b = 1\n s = 0\n while b <= N:\n temp = a\n a = b\n b = temp + b\n if b <= N:\n if b % 2 == 0:\n s += b\n return s", "def evenfibsum(N):\n (a, b, val) = (1, 1, 0)\n while b <= N:\n if b % 2 == 0:\n val += b\n (a, b) = (b, a + b)\n return val"], "starter_code": "def evenfibsum (N):\n", "input_output": {"inputs": ["N = 8", "N = 89"], "outputs": ["10", "44"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/even-fibonacci-numbers-sum1455/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "evenfibsum", "task_id": "TACO_lite/247", "example": [[[8], [89]], ["10", "44"]]} +{"requirement": "Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.\n\nExample 1:\n\n\nInput: 123\nOutput: \"One Hundred Twenty Three\"\n\n\nExample 2:\n\n\nInput: 12345\nOutput: \"Twelve Thousand Three Hundred Forty Five\"\n\nExample 3:\n\n\nInput: 1234567\nOutput: \"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven\"\n\n\nExample 4:\n\n\nInput: 1234567891\nOutput: \"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One\"", "solutions": ["def numbertowords(num):\n if num == 0:\n return 'Zero'\n answer = self.convert_hundred(num % 1000)\n for i in range(3):\n num //= 1000\n if num % 1000 > 0:\n following = ' ' + answer if answer else ''\n answer = self.convert_hundred(num % 1000) + ' ' + self.V3[i] + following\n return answer\n\ndef convert_hundred(num):\n answer = ''\n a = num // 100\n b = num % 100\n c = num % 10\n if b < 20:\n answer = self.V1[b]\n else:\n following = ' ' + self.V1[c] if c > 0 else ''\n answer = self.V2[b // 10] + following\n if a > 0:\n following = ' ' + answer if answer else ''\n answer = self.V1[a] + ' Hundred' + following\n return answer", "def parseHundred(n):\n to19 = 'One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split()\n tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split()\n if n == 0:\n return ''\n w = ''\n while n > 0:\n if n > 99:\n digit = n // 100\n w += to19[digit - 1] + ' ' + 'Hundred'\n n = n % 100\n if n != 0:\n w += ' '\n elif n <= 19:\n w += to19[n - 1]\n n = 0\n else:\n digit = n // 10\n w += tens[digit - 2]\n n = n % 10\n if n != 0:\n w += ' '\n return w\n\ndef numbertowords(num):\n thousands = ['', ' Thousand ', ' Million ', ' Billion ']\n i = 0\n w = ''\n if num == 0:\n return 'Zero'\n while num > 0:\n digits = num % 1000\n if digits != 0:\n w = self.parseHundred(digits) + thousands[i] + w\n num = num // 1000\n i += 1\n return w.strip()", "def __init__():\n self.twenties = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']\n self.tens = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']\n self.thousands = ['', 'Thousand', 'Million', 'Billion']\n\ndef numbertowords(num):\n if num == 0:\n return 'Zero'\n result = ''\n for i in range(len(self.thousands)):\n if num % 1000 != 0:\n result = self.helper(num % 1000) + self.thousands[i] + ' ' + result\n num //= 1000\n return result.strip()\n\ndef helper(num):\n if num == 0:\n return ''\n elif num < 20:\n return self.twenties[num] + ' '\n elif num < 100:\n return self.tens[num // 10] + ' ' + self.helper(num % 10)\n else:\n return self.twenties[num // 100] + ' Hundred ' + self.helper(num % 100)", "def numbertowords(num):\n\n def translate(num):\n if num == 0:\n return ''\n less20 = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']\n more20 = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']\n res = ''\n if num // 100:\n res = less20[num // 100] + ' Hundred' + (' ' if num % 100 else '')\n num %= 100\n res += less20[num] if num < 20 else more20[num // 10] + (' ' + less20[num % 10] if num % 10 else '')\n return res\n if num == 0:\n return 'Zero'\n unit = ['', 'Thousand', 'Million', 'Billion']\n i = 0\n res = []\n while num > 0:\n t = translate(num % 1000)\n if t:\n res += [unit[i], t]\n num //= 1000\n i += 1\n return ' '.join(res[::-1]).strip()", "def helper(num):\n result = ''\n while len(num) < 3:\n num = '0' + num\n if num[0] is not '0':\n result = self.digit[int(num[0])] + ' Hundred'\n if num[1] is not '0':\n if num[1] == '1':\n return result + ' ' + self.teen[int(num[1] + num[2])]\n else:\n return result + ' ' + self.ten[int(num[1])] + ' ' + self.digit[int(num[2])]\n if num[2] is not '0':\n result = result + ' ' + self.digit[int(num[2])]\n return result\n\ndef numbertowords(num):\n if num == 0:\n return 'Zero'\n result = ''\n rev = str(num)[::-1]\n slices = [rev[i:i + 3] for i in range(0, len(str(num)), 3)]\n for (idx, slice) in enumerate(slices):\n if slice == '000':\n continue\n else:\n result = self.helper(str(slice[::-1])) + ' ' + self.idx[idx] + ' ' + result\n result = result.split(' ')\n result = [x for x in result if x is not '']\n return ' '.join(result)", "def numbertowords(num):\n num_lyst = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']\n tens_lyst = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']\n under20_lyst = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']\n large_scale = ['', 'Thousand', 'Million', 'Billion']\n\n def convert(num):\n out_str = ''\n hundred = num // 100\n ten_digit = num % 100\n if hundred:\n out_str += num_lyst[hundred] + ' ' + 'Hundred '\n if ten_digit:\n if ten_digit < 10:\n out_str += num_lyst[ten_digit]\n elif ten_digit < 20:\n out_str += under20_lyst[ten_digit % 10]\n else:\n out_str += tens_lyst[ten_digit // 10] + ' ' + num_lyst[ten_digit % 10]\n return out_str.strip()\n if not num:\n return 'Zero'\n res = num // 1000\n last3 = num % 1000\n ans = ''\n while res or last3:\n if last3:\n ans = convert(last3) + ' ' + large_scale.pop(0) + ' ' + ans\n else:\n large_scale.pop(0)\n last3 = res % 1000\n res = res // 1000\n return ans.strip()", "def getEnglishThousand(n):\n if 1 <= n <= 9:\n return ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'][n - 1]\n elif 10 <= n <= 19:\n return ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'][n - 10]\n elif 20 <= n <= 99:\n eng = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'][n // 10 - 2]\n if n % 10 > 0:\n return eng + ' ' + self.getEnglishThousand(n % 10)\n else:\n return eng\n else:\n hundred = self.getEnglishThousand(n // 100) + ' Hundred'\n if n % 100 > 0:\n return hundred + ' ' + self.getEnglishThousand(n % 100)\n else:\n return hundred\n\ndef numbertowords(num):\n if num == 0:\n return 'Zero'\n stack = ['Billion', 'Million', 'Thousand', None]\n english = []\n while num:\n quantifier = stack.pop()\n if num % 1000 > 0:\n english.append(self.getEnglishThousand(num % 1000) + (' ' + quantifier if quantifier else ''))\n num //= 1000\n return ' '.join(reversed(english))", "def read_three_digits(unit, ten, hundred, index):\n if ten == 1:\n str_of_num = ' ' + Solution.ten_to_str[ten * 10 + unit]\n else:\n str_of_num = ' ' + Solution.ten_to_str[ten * 10] + Solution.digit_to_str[unit] if ten > 1 else Solution.digit_to_str[unit]\n str_of_num = (Solution.digit_to_str[hundred] + ' Hundred' if hundred > 0 else '') + str_of_num\n return str_of_num[1:] + ' ' + Solution.quantity_unit[index] if str_of_num else str_of_num[1:]\n\ndef numbertowords(num):\n if num == 0:\n return 'Zero'\n str_of_num = ''\n index = 0\n while num > 0:\n part = num % 1000\n unit = part % 10\n ten = part % 100 // 10\n hundred = part // 100\n str_of_num = self.read_three_digits(unit, ten, hundred, index) + ' ' + str_of_num.strip()\n num //= 1000\n index += 1\n return str_of_num.strip()"], "starter_code": "def numbertowords(num: int) -> str:\n", "input_output": {"fn_name": "numberToWords", "inputs": [[123]], "outputs": ["One Hundred Twenty Three"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Recursion", "Math", "String"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Mathematics", "Complete search"], "skill_types": ["Complete search"], "url": "https://leetcode.com/problems/integer-to-english-words/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numbertowords", "task_id": "TACO_lite/158", "example": [[[123], [12345], [1234567], [1234567891]], ["One Hundred Twenty Three", "Twelve Thousand Three Hundred Forty Five", "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven", "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"]]} +{"requirement": "HELP! Jason can't find his textbook! It is two days before the test date, and Jason's textbooks are all out of order! Help him sort a list (ArrayList in java) full of textbooks by subject, so he can study before the test.\n\nThe sorting should **NOT** be case sensitive", "solutions": ["def sorter(textbooks):\n return sorted(textbooks, key=str.lower)", "def sorter(textbooks):\n return sorted(textbooks, key=str.casefold)", "def sorter(textbooks):\n return sorted(textbooks, key=lambda arg: arg.lower())", "sorter = lambda x: sorted(x, key=lambda s: s.lower())", "sorter = lambda text: sorted(text, key=lambda s: s.lower())", "def sorter(lst):\n return sorted(lst, key=lambda e: e.lower())", "def sorter(textbooks):\n return sorted(textbooks, key=lambda text: text.lower())", "def sorter(textbooks):\n\n def f(e):\n return e.lower()\n sorted = textbooks.sort(key=f)\n return textbooks", "def sorter(textbooks):\n d = {t.lower(): t for t in textbooks}\n return [d[t] for t in sorted(d)]", "sorter = lambda textbooks: sorted(textbooks, key=str.lower)", "from typing import List\n\ndef sorter(textbooks: List[str]):\n return sorted(textbooks, key=str.lower)", "def sorter(textbooks):\n textbooks.sort(key=lambda x: x.lower())\n return textbooks", "def myf(a):\n return a.lower()\n\ndef sorter(textbooks):\n return sorted(textbooks, key=myf)", "def sorter(textbooks):\n textbooks.sort(key=str.lower)\n return textbooks", "def sorter(textbooks):\n listtemp = [(x.lower(), x) for x in textbooks]\n listtemp.sort()\n return [x[1] for x in listtemp]", "def sorter(textbooks):\n r = {i.lower(): i for i in textbooks}\n return [r[i] for i in sorted(r)]", "def sorter(textbooks):\n subjects = dict(((sub.lower(), sub) for sub in textbooks))\n return [subjects[sub] for sub in sorted(subjects.keys())]", "sorter = lambda textbooks: list(sorted(textbooks, key=lambda s: s.lower()))", "sorter = lambda textbooks: sorted(textbooks, key=str.casefold)", "def sorter(textbooks):\n return list(sorted(textbooks, key=lambda e: e.lower()))", "import functools\n\ndef cmp(a, b):\n aa = a.lower()\n bb = b.lower()\n if aa > bb:\n return 1\n elif bb > aa:\n return -1\n else:\n return 0\n\ndef sorter(textbooks):\n return sorted(textbooks, key=functools.cmp_to_key(cmp))", "from typing import List\n\ndef sorter(textbooks: List[str]) -> List[str]:\n return sorted(textbooks, key=str.casefold)", "def sorter(tks):\n return sorted(tks, key=lambda s: s.lower())", "def sorter(textbooks):\n return sorted(textbooks, key=lambda v: (v.casefold(), v))", "def get_first(element):\n return element[0]\n\ndef sorter(textbooks):\n lst = [(el.lower(), el) for el in textbooks]\n lst1 = sorted(lst, key=get_first)\n return [el[1] for el in lst1]", "def sorter(textbooks):\n lst = sorted([(el.lower(), el) for el in textbooks])\n return [el[1] for el in lst]", "def sorter(textbooks):\n\n def f(x):\n return x.lower()\n return sorted(textbooks, key=f)", "def sorter(textbooks):\n return sorted(sorted(textbooks, key=lambda x: x[1].lower()), key=lambda x: x[0].lower())", "def sorter(textbooks):\n x = sorted(textbooks, key=lambda s: s.casefold())\n return x", "def sorter(textbooks):\n result = []\n books_lowcase = [x.lower() for x in textbooks]\n books_dict = dict(zip(books_lowcase, textbooks))\n dict_keys_sort = list(books_dict.keys())\n dict_keys_sort.sort()\n for i in dict_keys_sort:\n result.append(books_dict[i])\n return result", "import re\n\ndef sorter(textbooks):\n textbooks.sort(key=str.lower)\n return textbooks", "def sorter(textbooks):\n s = sorted(textbooks)\n if textbooks == s:\n return textbooks\n if s == s.sort(key=str.lower):\n return s.sort(key=str.lower)\n else:\n return s", "def lower_case(predmet):\n return predmet.lower()\n\ndef sorter(textbooks):\n return sorted(textbooks, key=lower_case)", "def register(textbook):\n return textbook.lower()\n\ndef sorter(textbooks):\n textbooks.sort(key=register)\n return textbooks", "def sorter(textbooks):\n return sorted(textbooks, key=lambda s: s.lower())", "def f(x):\n x = x.lower()\n return x\n\ndef sorter(textbooks):\n textbooks.sort(key=f)\n return textbooks", "def sorter(textbooks):\n textbooks = sorted(textbooks, key=lambda x: x[0:] if x[0:].islower() else x[0:].lower())\n return textbooks", "def sorter(textbooks):\n return sorted([i for i in textbooks], key=lambda str: str.lower())", "def sorter(t):\n t.sort(key=str.casefold)\n return t", "import locale\n\ndef sorter(textbooks):\n textbooks.sort(key=lambda x: x.lower())\n return textbooks", "def sorter(t):\n return sorted(t, key=lambda t: t.casefold())", "def sorter(textbooks):\n return sorted(textbooks, key=lambda x: x[0:2].lower())", "def sorter(textbooks):\n lst_books = []\n for i in textbooks:\n lst_books.append(i)\n return sorted(lst_books, key=str.lower)", "def sorter(textbooks):\n textbooks_low = [el.lower() for el in textbooks]\n textbooks_low_sorted = sorted(textbooks_low)\n testbooks_sorted_indexes = [textbooks_low.index(el) for el in textbooks_low_sorted]\n return [textbooks[ind] for ind in testbooks_sorted_indexes]", "def sorter(textbooks):\n if textbooks != int:\n return sorted(textbooks, key=str.lower)", "def sorter(text_books):\n return sorted(text_books, key=str.lower)", "def sorter(textbooks):\n return sorted(textbooks, key=lambda t: (t.lower(), t))", "def sorter(textbooks):\n arr = []\n for (i, book) in enumerate(textbooks):\n arr.append([book.lower(), i])\n arr = sorted(arr)\n for (i, book) in enumerate(arr):\n arr[i] = textbooks[book[1]]\n return arr", "sorter = lambda books: sorted(books, key=lambda _: _.lower())", "import string\n\ndef sorter(textbooks):\n return sorted(textbooks, key=str.lower)", "sorter = lambda t: sorted(t, key=lambda s: s.lower())", "def sorter(textbooks):\n obj = {}\n lower_case_textbooks = []\n for textbook in textbooks:\n lower_case_textbook = textbook.lower()\n obj[lower_case_textbook] = textbook\n lower_case_textbooks.append(lower_case_textbook)\n sorted_textbooks = sorted(lower_case_textbooks)\n output_list = []\n for sorted_textbook in sorted_textbooks:\n output_list.append(obj[sorted_textbook])\n return output_list", "def sorter(arr):\n for i in range(len(arr) - 1):\n for j in range(len(arr) - i - 1):\n if arr[j].lower() > arr[j + 1].lower():\n (arr[j], arr[j + 1]) = (arr[j + 1], arr[j])\n return arr", "def sorter(textbooks):\n return [a[1] for a in sorted([(b.lower(), b) for b in textbooks])]", "def sorter(t):\n return sorted(t, key=str.casefold)", "def sorter(tb):\n return sorted(tb, key=lambda x: x.lower())", "def sorter(textbooks):\n sorted = [book.lower() for book in textbooks]\n sorted.sort()\n final = textbooks.copy()\n for book in textbooks:\n final[sorted.index(book.lower())] = book\n return final", "def sorter(textbooks):\n copy = [text.lower() for text in textbooks]\n final = []\n to_sort = list(copy)\n to_sort.sort()\n for t in to_sort:\n final.append(textbooks[copy.index(t)])\n return final", "sorter = lambda x: sorted(x, key=str.casefold)", "def sorter(textbooks):\n a = [i.lower() for i in textbooks]\n s = sorted(a)\n for i in range(len(s)):\n if s[i] in textbooks:\n pass\n else:\n s[i] = textbooks[a.index(s[i])]\n return s", "def sorter(textbooks):\n return sorted(textbooks, key=lambda w: w.casefold())", "def sorter(textbooks):\n ret = [t for t in textbooks]\n ret.sort(key=lambda x: x.lower())\n return ret", "import numpy as np\n\ndef sorter(textbooks):\n return sorted(textbooks, key=str.lower)", "import functools\n\ndef compares(item1, item2):\n if len(item1) == 0:\n return -1\n if len(item2) == 0:\n return 1\n if ord(item1[0].lower()) < ord(item2[0].lower()):\n return -1\n elif ord(item1[0].lower()) > ord(item2[0].lower()):\n return 1\n else:\n return compares(item1[1:], item2[1:])\n\ndef compare(item1, item2):\n return compares(item1, item2)\n\ndef sorter(textbooks):\n return sorted(textbooks, key=functools.cmp_to_key(compare))", "def sorter(t):\n a = sorted(t, key=str.lower)\n return a", "def sorter(textbooks):\n a = [Book(subj) for subj in textbooks]\n a.sort()\n output = [i.subject for i in a]\n return output\n\ndef __init__(subject):\n self.subject = subject\n\ndef __lt__(other):\n return self.subject.lower() < other.subject.lower()", "def sorter(textbooks):\n return sorted(textbooks, key=lambda v: v.lower())", "def sorter(textbooks):\n sortbooks = sorted([x.lower() for x in textbooks])\n out = []\n for sb in sortbooks:\n for tb in textbooks:\n if sb == tb.lower():\n out.append(tb)\n return out", "def sorter(textbooks):\n index = {word.lower(): word for word in textbooks}\n keys = sorted(index.keys())\n return [index[key] for key in keys]", "def sorter(textbooks):\n return sorted([textbook for textbook in textbooks], key=lambda x: x.lower())", "sorter = lambda textbooks: sorted(textbooks, key=lambda t: t.lower())"], "starter_code": "def sorter(textbooks):\n", "input_output": {"fn_name": "sorter", "inputs": [[["Algebra", "History", "Geometry", "English"]], [["Algebra", "history", "Geometry", "english"]], [["Alg#bra", "$istory", "Geom^try", "**english"]]], "outputs": [[["Algebra", "English", "Geometry", "History"]], [["Algebra", "english", "Geometry", "history"]], [["$istory", "**english", "Alg#bra", "Geom^try"]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Sorting", "Lists"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/5a07e5b7ffe75fd049000051", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sorter", "task_id": "TACO_lite/121", "example": [[[["Mathematics", "history", "Physics", "chemistry"]], [["biology", "Zoology", "math", "Computer Science"]]], ["['chemistry', 'history', 'Mathematics', 'Physics']", "['biology', 'Computer Science', 'math', 'Zoology']"]]} +{"requirement": "You have an array of numbers. \nYour task is to sort ascending odd numbers but even numbers must be on their places.\n\nZero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.\n\n*Example*\n```python\nsort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]\n```", "solutions": ["def sort_array(arr):\n odds = sorted((x for x in arr if x % 2 != 0), reverse=True)\n return [x if x % 2 == 0 else odds.pop() for x in arr]", "def sort_array(source_array):\n odds = iter(sorted((v for v in source_array if v % 2)))\n return [next(odds) if i % 2 else i for i in source_array]", "def sort_array(source_array):\n odds = []\n answer = []\n for i in source_array:\n if i % 2 > 0:\n odds.append(i)\n answer.append('X')\n else:\n answer.append(i)\n odds.sort()\n for i in odds:\n x = answer.index('X')\n answer[x] = i\n return answer", "def sort_array(source_array):\n result = sorted([l for l in source_array if l % 2 == 1])\n for (index, item) in enumerate(source_array):\n if item % 2 == 0:\n result.insert(index, item)\n return result", "from collections import deque\n\ndef sort_array(array):\n odd = deque(sorted((x for x in array if x % 2)))\n return [odd.popleft() if x % 2 else x for x in array]", "def sort_array(source_array):\n odd = sorted(list(filter(lambda x: x % 2, source_array)))\n (l, c) = ([], 0)\n for i in source_array:\n if i in odd:\n l.append(odd[c])\n c += 1\n else:\n l.append(i)\n return l", "def sort_array(source_array):\n return [] if len(source_array) == 0 else list(map(int, ','.join(['{}' if a % 2 else str(a) for a in source_array]).format(*list(sorted((a for a in source_array if a % 2 == 1)))).split(',')))", "def sort_array(source_array):\n odd = []\n for i in source_array:\n if i % 2 == 1:\n odd.append(i)\n odd.sort()\n x = 0\n for j in range(len(source_array)):\n if source_array[j] % 2 == 1:\n source_array[j] = odd[x]\n x += 1\n return source_array", "def sort_array(source_array):\n odds = iter(sorted((elem for elem in source_array if elem % 2 != 0)))\n return [next(odds) if el % 2 != 0 else el for el in source_array]", "def sort_array(numbers):\n evens = []\n odds = []\n for a in numbers:\n if a % 2:\n odds.append(a)\n evens.append(None)\n else:\n evens.append(a)\n odds = iter(sorted(odds))\n return [next(odds) if b is None else b for b in evens]"], "starter_code": "def sort_array(source_array):\n", "input_output": {"fn_name": "sort_array", "inputs": [[[5, 3, 2, 8, 1, 4, 11]], [[2, 22, 37, 11, 4, 1, 5, 0]], [[1, 111, 11, 11, 2, 1, 5, 0]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 1, 2, 3, 4, 9, 8, 7, 6, 5]]], "outputs": [[[1, 3, 2, 8, 5, 4, 11]], [[2, 22, 1, 5, 4, 11, 37, 0]], [[1, 1, 5, 11, 2, 11, 111, 0]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 1, 2, 3, 4, 5, 8, 7, 6, 9]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Sorting"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/578aa45ee9fd15ff4600090d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sort_array", "task_id": "TACO_lite/240", "example": [[[[5, 3, 2, 8, 1, 4]]], ["[1, 3, 2, 8, 5, 4]"]]} +{"requirement": "Given the root of a binary tree, each node in the tree has a distinct value.\nAfter deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).\nReturn the roots of the trees in the remaining forest.  You may return the result in any order.\n \nExample 1:\n\nInput: root = [1,2,3,4,5,6,7], to_delete = [3,5]\nOutput: [[1,2,null,4],[6],[7]]\n\n \nConstraints:\n\nThe number of nodes in the given tree is at most 1000.\nEach node has a distinct value between 1 and 1000.\nto_delete.length <= 1000\nto_delete contains distinct values between 1 and 1000.", "solutions": ["def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n (ans, to_delete) = ([], set(to_delete))\n\n def search(root, is_root):\n if not root:\n return None\n root_deleted = root.val in to_delete\n if is_root and (not root_deleted):\n ans.append(root)\n root.left = search(root.left, root_deleted)\n root.right = search(root.right, root_deleted)\n return None if root_deleted else root\n search(root, True)\n return ans", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n ans = []\n to_delete = set(to_delete)\n\n def dfs(node, has_parent):\n if not node:\n return False\n if node.val not in to_delete and (not has_parent):\n ans.append(node)\n if dfs(node.left, node.val not in to_delete):\n node.left = None\n if dfs(node.right, node.val not in to_delete):\n node.right = None\n return node.val in to_delete\n dfs(root, False)\n return ans", "def merge(root, left, right):\n replace_left = replace_right = None\n for i in range(len(left)):\n if left[i] == root.left:\n replace_left = i\n for i in range(len(right)):\n if right[i] == root.right:\n replace_right = i\n if replace_left is not None and replace_right is None:\n left[replace_left] = root\n return left + right\n elif replace_right is not None and replace_left is None:\n right[replace_right] = root\n return left + right\n result = [node for node in left if node != root.left] + [node for node in right if node != root.right]\n result.append(root)\n return result\n\ndef helper(root, to_delete):\n if not root:\n return []\n if not root.left and (not root.right):\n if root.val in to_delete:\n return []\n return [root]\n left = self.delNodes(root.left, to_delete)\n right = self.delNodes(root.right, to_delete)\n if root.left and root.left.val in to_delete:\n root.left = None\n if root.right and root.right.val in to_delete:\n root.right = None\n if root.val in to_delete:\n return left + right\n return self.merge(root, left, right)\n\ndef delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n return self.helper(root, set(to_delete))", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n res = []\n\n def rec(curr, deleted):\n nonlocal res\n if not curr:\n return None\n if curr.val in to_delete:\n curr.left = rec(curr.left, True)\n curr.right = rec(curr.right, True)\n else:\n curr.left = rec(curr.left, False)\n curr.right = rec(curr.right, False)\n if deleted:\n res.append(curr)\n return None if curr.val in to_delete else curr\n rec(root, True)\n return res", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n if root is None:\n return\n tovisit = []\n result = []\n if root in to_delete:\n if root.left is not None:\n tovisit.append(root.left)\n result.append(root.left)\n if root.right is not None:\n tovisit.append(root.right)\n result.append(root.right)\n else:\n tovisit.append(root)\n result.append(root)\n while len(tovisit) > 0:\n new_tovisit = []\n for item in tovisit:\n if item.val in to_delete:\n if item.left is not None:\n result.append(item.left)\n if item.right is not None:\n result.append(item.right)\n if item in result:\n result.remove(item)\n if item.left is not None:\n new_tovisit.append(item.left)\n if item.left.val in to_delete:\n item.left = None\n if item.right is not None:\n new_tovisit.append(item.right)\n if item.right.val in to_delete:\n item.right = None\n tovisit = new_tovisit\n return result", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n roots = []\n\n def deleting(node, to_delete, roots):\n if node == None:\n return\n elif node.val in to_delete:\n if node.left != None:\n roots.append(node.left)\n if node.right != None:\n roots.append(node.right)\n try:\n while True:\n roots.remove(node)\n except:\n pass\n if node.left != None and node.left.val in to_delete:\n deleting(node.left, to_delete, roots)\n node.left = None\n else:\n deleting(node.left, to_delete, roots)\n if node.right != None and node.right.val in to_delete:\n deleting(node.right, to_delete, roots)\n node.right = None\n else:\n deleting(node.right, to_delete, roots)\n deleting(root, to_delete, roots)\n if root.val not in to_delete:\n roots.append(root)\n return roots", "from queue import Queue\n\ndef delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n if not root:\n return []\n deleted = set()\n for node in to_delete:\n deleted.add(node)\n out = []\n self.bfs(root, deleted, out)\n return out\n\ndef bfs(root, deleted, out):\n q = Queue()\n q.put((root, True))\n while q.qsize() > 0:\n (node, parent_delete) = q.get()\n if node.val in deleted:\n curr_delete = True\n else:\n curr_delete = False\n if node.left:\n q.put((node.left, curr_delete))\n if node.left.val in deleted:\n node.left = None\n if node.right:\n q.put((node.right, curr_delete))\n if node.right.val in deleted:\n node.right = None\n if curr_delete:\n node.left = None\n node.right = None\n elif parent_delete:\n out.append(node)", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n roots = []\n roots.append(root)\n\n def removeRoot(root, roots):\n index = 0\n for i in roots:\n if i == root:\n roots.pop(index)\n index += 1\n\n def delete(root, prev, roots, to_delete):\n left = root.left\n right = root.right\n if root.val in to_delete:\n removeRoot(root, roots)\n if left:\n roots.append(root.left)\n if right:\n roots.append(root.right)\n root.left = None\n root.right = None\n if prev:\n if prev.left == root:\n prev.left = None\n if prev.right == root:\n prev.right = None\n if left:\n delete(left, root, roots, to_delete)\n if right:\n delete(right, root, roots, to_delete)\n delete(root, None, roots, to_delete)\n return roots", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n stack = [(root, True)]\n res = []\n while stack:\n (curr, toBeRoot) = stack.pop()\n if curr:\n if curr.val not in to_delete and toBeRoot:\n res.append(curr)\n toBeRoot = curr.val in to_delete\n stack += [(curr.left, toBeRoot), (curr.right, toBeRoot)]\n if curr.left and curr.left.val in to_delete:\n curr.left = None\n if curr.right and curr.right.val in to_delete:\n curr.right = None\n return res", "def walk(node, to_delete):\n if not node:\n return []\n roots = []\n if node.left:\n roots += self.walk(node.left, to_delete)\n if node.left.val in to_delete:\n node.left = None\n elif node.val in to_delete:\n roots.append(node.left)\n if node.right:\n roots += self.walk(node.right, to_delete)\n if node.right.val in to_delete:\n node.right = None\n elif node.val in to_delete:\n roots.append(node.right)\n return roots\n\ndef delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n if not root:\n return None\n to_delete = set(to_delete)\n roots = self.walk(root, to_delete)\n if root.val not in to_delete:\n roots.append(root)\n return roots", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n if not root:\n return []\n (res, to_delete) = ([], set(to_delete))\n self.dfs(root, res, to_delete, True)\n return res\n\ndef dfs(root, res, to_delete, parent_deleted):\n if not root:\n return None\n if parent_deleted and root.val not in to_delete:\n res.append(root)\n root_deleted = True if root.val in to_delete else False\n root.left = self.dfs(root.left, res, to_delete, root_deleted)\n root.right = self.dfs(root.right, res, to_delete, root_deleted)\n return None if root_deleted else root", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n\n def dfs(root: TreeNode, has_parent: bool) -> TreeNode:\n if not root:\n return\n if root.val in to_delete:\n root.left = dfs(root.left, has_parent=False)\n root.right = dfs(root.right, has_parent=False)\n return\n else:\n if not has_parent:\n result.append(root)\n root.left = dfs(root.left, has_parent=True)\n root.right = dfs(root.right, has_parent=True)\n return root\n result = []\n dfs(root, has_parent=False)\n return result", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n to_delete = set(to_delete)\n res = []\n\n def walk(root, parent_exist):\n if root is None:\n return None\n if root.val in to_delete:\n root.left = walk(root.left, parent_exist=False)\n root.right = walk(root.right, parent_exist=False)\n return None\n else:\n if not parent_exist:\n res.append(root)\n root.left = walk(root.left, parent_exist=True)\n root.right = walk(root.right, parent_exist=True)\n return root\n walk(root, parent_exist=False)\n return res", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n new_roots = []\n\n def delete_nodes(node, parent_deleted):\n if not node:\n return False\n delete = False\n for value in to_delete:\n if value == node.val:\n delete = True\n if parent_deleted and (not delete):\n new_roots.append(node)\n (left, right) = (delete_nodes(node.left, delete), delete_nodes(node.right, delete))\n if left:\n node.left = None\n if right:\n node.right = None\n return delete\n delete_nodes(root, True)\n return new_roots", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n to_delete = set(to_delete)\n ans = []\n\n def helper(node, isRoot, parent, p_left):\n if isRoot:\n ans.append(node)\n if node.val in to_delete:\n if isRoot:\n ans.pop()\n if parent:\n if p_left:\n parent.left = None\n else:\n parent.right = None\n if node.left:\n helper(node.left, True, node, True)\n if node.right:\n helper(node.right, True, node, False)\n else:\n if node.left:\n helper(node.left, False, node, True)\n if node.right:\n helper(node.right, False, node, False)\n return\n helper(root, True, None, None)\n return ans", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n self.deletes = set(to_delete)\n self.res = list()\n root = self.helper(root)\n if root:\n self.res.append(root)\n return self.res\n\ndef helper(root):\n if not root:\n return root\n root.left = self.helper(root.left)\n root.right = self.helper(root.right)\n if root.val in self.deletes:\n if root.left:\n self.res.append(root.left)\n if root.right:\n self.res.append(root.right)\n root = None\n return root", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n if not root:\n return []\n res = set([root])\n deleteSet = set(to_delete)\n\n def dfs(root):\n if not root:\n return\n if root.val in deleteSet:\n if root in res:\n res.remove(root)\n if root.left:\n res.add(root.left)\n if root.right:\n res.add(root.right)\n dfs(root.left)\n dfs(root.right)\n if root.left and root.left.val in deleteSet:\n root.left = None\n if root.right and root.right.val in deleteSet:\n root.right = None\n dfs(root)\n return list(res)", "def delete(root, to_delete, parent, res):\n if not root:\n return root\n elif parent:\n if root.val in to_delete:\n root.left = self.delete(root.left, to_delete, False, res)\n root.right = self.delete(root.right, to_delete, False, res)\n return None\n else:\n root.left = self.delete(root.left, to_delete, True, res)\n root.right = self.delete(root.right, to_delete, True, res)\n return root\n elif root.val in to_delete:\n root.left = self.delete(root.left, to_delete, False, res)\n root.right = self.delete(root.right, to_delete, False, res)\n return None\n else:\n res.append(root)\n root.left = self.delete(root.left, to_delete, True, res)\n root.right = self.delete(root.right, to_delete, True, res)\n return root\n\ndef delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n res = []\n root = self.delete(root, set(to_delete), False, res)\n return res", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n ret = []\n\n def dfs(node, parent):\n if node:\n if node.val in to_delete:\n node.left = dfs(node.left, False)\n node.right = dfs(node.right, False)\n else:\n if not parent:\n ret.append(node)\n node.left = dfs(node.left, True)\n node.right = dfs(node.right, True)\n return node\n dfs(root, False)\n return ret", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n final_list = []\n\n def rec(node):\n if node == None:\n return None\n node.left = rec(node.left)\n node.right = rec(node.right)\n if node.val in to_delete:\n if node.left != None:\n final_list.append(node.left)\n if node.right != None:\n final_list.append(node.right)\n return None\n return node\n rec(root)\n if root.val not in to_delete:\n final_list.append(root)\n return final_list", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n output = []\n stack = [(0, root)]\n\n def stackChildren(level, node):\n if node.right:\n stack.append((level, node.right))\n if level > 0 and node.right.val in to_delete:\n node.right = None\n if node.left:\n stack.append((level, node.left))\n if level > 0 and node.left.val in to_delete:\n node.left = None\n while stack:\n (level, node) = stack.pop()\n if node.val in to_delete:\n stackChildren(0, node)\n else:\n if level == 0:\n output.append(node)\n stackChildren(level + 1, node)\n return output"], "starter_code": "def __init__(val=0, left=None, right=None):\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Binary Tree", "Tree", "Depth-First Search"], "name": null, "source": "leetcode", "tags": ["Tree algorithms", "Graph traversal"], "skill_types": [], "url": "https://leetcode.com/problems/delete-nodes-and-return-forest/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "__init__", "task_id": "TACO_lite/201", "example": [[], []]} +{"requirement": "Given a Binary string st and a number k. You have to find the Longest continuous sequence of '0' after repeating Given string K time.\nExample 1:\nInput: k = 3\nst = 100001\nOutput: 4\nExplaination: The string repeated k times \nbecome 100001100001100001. Here the longest \ncontinuous sequence of 0 is 4.\nExample 2:\nInput: k = 4\nst = 000\nOutput: 12\nExplaination: When st is repeated 4 times \nit become 000000000000. The longest sequence \nbecomes of length 12.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function lcsK() which takes k and st as input parameters and returns the length of the longest continuous sequence of 0's after repeating st k times.\nExpected Time Complexity: O(|st|)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ |st| ≤ 10^{5}\n1 ≤ k ≤ 10^{5}", "solutions": ["def lcsk(k, st):\n if int(st) > 0:\n s = st * k\n ans = 0\n temp = 0\n s = str(s)\n r = min(2, k)\n for i in range(len(st) * r):\n if s[i] == '0':\n temp = temp + 1\n else:\n ans = max(ans, temp)\n temp = 0\n return ans\n else:\n return len(st) * k", "def lcsk(k, s):\n n = len(s)\n if k > 1:\n s += s\n n *= 2\n ans = 0\n i = 0\n while i < n:\n x = 0\n while i < n and s[i] == '0':\n (x, i) = (x + 1, i + 1)\n ans = max(ans, x)\n i += 1\n if k == 1 or ans != n:\n return ans\n else:\n return ans // 2 * k", "def lcsk(k, st):\n n = len(st)\n dp = [0] * (n + 1)\n if st[0] == '0':\n dp[0] = 1\n for i in range(1, n):\n if st[i] == '0':\n dp[i] = dp[i - 1] + 1\n else:\n dp[i] = 0\n if dp[n - 1] == n:\n return n * k\n u = 0\n for i in range(n):\n if st[i] == '1':\n u = i - 1\n break\n if u == -1:\n return max(dp)\n else:\n return max(max(dp), dp[n - 1] + dp[u])", "def lcsk(k, st):\n if k == 1:\n count = 0\n maxi = 0\n for char in st:\n if char == '0':\n count += 1\n maxi = max(maxi, count)\n else:\n count = 0\n return maxi\n if not '1' in st:\n return k * len(st)\n i = st.index('1')\n st = st[i:] + st[:i]\n count = 0\n maxi = 0\n for char in st:\n if char == '0':\n count += 1\n maxi = max(maxi, count)\n else:\n count = 0\n return maxi", "def lcsk(k, st):\n n = len(st)\n (left, bounded, right) = self.getCounts(st, n)\n if k == 1:\n return max(max(left, bounded), right)\n if left + right == n:\n return k * n\n return max(left + right, bounded)\n\ndef getCounts(st, n):\n left = 0\n right = 0\n boundedMax = 0\n l = 0\n while l < n:\n if st[l] != '0':\n break\n left += 1\n l += 1\n r = n - 1\n while r >= 0 and r > l:\n if st[r] == '1':\n break\n right += 1\n r -= 1\n curBound = 0\n while l < r:\n if st[l] == '0':\n curBound += 1\n boundedMax = max(boundedMax, curBound)\n else:\n curBound = 0\n l += 1\n return (left, boundedMax, right)", "def lcsk(k, st):\n res = []\n i = 0\n while i < len(st):\n if st[i] != '0':\n i += 1\n continue\n cnt = 0\n while i < len(st) and st[i] == '0':\n cnt += 1\n i += 1\n res.append(cnt)\n if st[0] == '1':\n if res:\n return max(res)\n else:\n return 0\n if st[0] == '0' and st[-1] == '0':\n if len(res) == 1:\n return res[0] * k\n return max(res[0] + res[-1], max(res))\n return max(res)", "def lcsk(k, st):\n if st.count('0') == len(st):\n return len(st) * k\n if k <= 2:\n b = st * k\n else:\n b = st * 2\n lcs = 0\n olcs = -10 ** 9 - 7\n for i in range(len(b)):\n if b[i] == '0':\n lcs += 1\n else:\n olcs = max(olcs, lcs)\n lcs = 0\n if olcs == 10 ** 9 - 7:\n return lcs\n return olcs", "def lcsk(k, st):\n n = len(st)\n count = 0\n for i in range(n):\n if st[i] == '0':\n count += 1\n if count == n:\n return k * n\n xyz = st + st + st\n ans = 0\n lm = 0\n for i in range(len(xyz)):\n if xyz[i] == '0':\n lm += 1\n ans = max(ans, lm)\n else:\n lm = 0\n return ans", "def lcsk(k, st):\n st = st + st\n n = len(st)\n here = 0\n mx = 0\n for i in range(n):\n if st[i] == '0':\n here += 1\n else:\n here = 0\n mx = max(mx, here)\n if mx == n:\n return mx * k // 2\n else:\n return mx", "def lcsk(k, st):\n p = len(st)\n out = []\n for i in range(len(st)):\n if st[i] == '1':\n out.append(i)\n if len(out) == 0:\n return p * k\n out.append(p + out[0])\n mdif = 0\n for i in range(len(out) - 1):\n v = out[i + 1] - out[i] - 1\n if v > mdif:\n mdif = v\n return mdif", "def findmax(st):\n cnt = 0\n ans = 0\n for i in st:\n if i == '0':\n cnt += 1\n else:\n if ans < cnt:\n ans = cnt\n cnt = 0\n if ans < cnt:\n ans = cnt\n return ans\n\ndef lcsk(k, st):\n if st[0] != '0' or st[-1] != '0':\n return self.findmax(st)\n (ini, temp, last) = (0, 0, 0)\n cnt = 0\n i = 0\n while i < len(st):\n if st[i] == '0':\n ini += 1\n else:\n break\n i += 1\n temp = ini\n if ini == len(st):\n return len(st) * k\n while i < len(st):\n if st[i] == '0':\n cnt += 1\n else:\n if temp < cnt:\n temp = cnt\n cnt = 0\n i += 1\n last = cnt\n if temp < cnt:\n temp = cnt\n if temp > ini + last:\n return temp\n return ini + last", "def lcsk(k, st):\n l = len(st)\n if not '1' in st:\n return k * l\n elif st[0] != '0' or st[-1] != '0':\n count = 0\n mx = 0\n for i in st:\n if i == '0':\n count += 1\n else:\n if count > mx:\n mx = count\n count = 0\n return mx\n else:\n count = 0\n mx = 0\n for i in st:\n if i == '0':\n count += 1\n else:\n if count > mx:\n mx = count\n count = 0\n count = 0\n for i in st:\n if i == '1':\n break\n count += 1\n for i in range(1, l + 1):\n if st[-i] == '1':\n break\n count += 1\n return max(count, mx)"], "starter_code": "def lcsk(k, st):\n", "input_output": {"inputs": ["k = 3\nst = 100001", "k = 4\nst = 000"], "outputs": ["4", "12"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/lcs-of-0-k-repeated-string5642/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|st|)", "entry_point": "lcsk", "task_id": "TACO_lite/196", "example": [[[3, "100001"], [4, "000"]], ["4", "12"]]} +{"requirement": "Implement `String#parse_mana_cost`, which parses [Magic: the Gathering mana costs](http://mtgsalvation.gamepedia.com/Mana_cost) expressed as a string and returns a `Hash` with keys being kinds of mana, and values being the numbers.\n\nDon't include any mana types equal to zero.\n\nFormat is:\n\n* optionally natural number representing total amount of generic mana (use key `*`)\n* optionally followed by any combination of `w`, `u`, `b`, `r`, `g` (case insensitive in input, return lower case in output), each representing one mana of specific color.\n\nIf case of Strings not following specified format, return `nil/null/None`.", "solutions": ["import re\n\ndef parse_mana_cost(mana):\n n = {c: mana.lower().count(c) for c in 'wubrg' if mana.lower().count(c) > 0}\n m = re.split('\\\\D', mana)\n if sum(n.values()) + sum([len(c) for c in m]) != len(mana):\n return None\n p = sum([int(c) for c in m if c != ''])\n if p > 0:\n n['*'] = p\n return n", "import re\n\ndef parse_mana_cost(mana):\n m = re.match('(\\\\d*)([wubrg]*)\\\\Z', mana.lower())\n if m is None:\n return\n (g, c) = m.groups()\n result = {} if g in ('', '0') else {'*': int(g)}\n result.update({k: c.count(k) for k in set(c)})\n return result", "from collections import Counter\n\ndef parse_mana_cost(mana):\n if mana != mana.strip() or [c for c in mana.lower() if c not in '0123456789 wubrg']:\n return None\n return Counter(''.join((parse(w) for w in mana.lower().split())))\n\ndef parse(w):\n s = '0'\n while w and w[0].isdigit():\n (s, w) = (s + w[0], w[1:])\n return w + '*' * int(s)", "import re\nfrom collections import Counter\n\ndef parse_mana_cost(mana):\n for (cnt, chrs) in re.findall('\\\\A(\\\\d*)([wubrg]*)\\\\Z', mana.lower() or '0'):\n result = {'*': int(cnt or 0), **Counter(chrs)}\n return {key: result[key] for key in result if result[key]}", "from collections import Counter\nimport re\n\ndef parse_mana_cost(s):\n s = s.lower()\n if re.match('\\\\d*[wubrg]*\\\\Z', s):\n r = {x: s.count(x) for x in set(s) if x.isalpha()}\n return s and s[0].isdigit() and int(s[0]) and r.update({'*': int(re.match('\\\\d+', s).group())}) or r", "import re\n\ndef parse_mana_cost(m):\n if not m:\n return {}\n if not re.match('^[\\\\dwubrg]+$', m, re.I) or '\\n' in m:\n return\n (r1, r) = (re.findall('[wubrg]', m, re.I), re.search('^[0-9]*', m))\n (r, d) = (r.group() if r else '', {})\n if r != '0' and r:\n d['*'] = int(r)\n for i in m[len(r):]:\n d[i.lower()] = d.get(i.lower(), 0) + 1\n return d", "import re\n\ndef parse_mana_cost(mana):\n mana = mana.lower()\n valid = ['w', 'u', 'r', 'g', 'b']\n dic = {}\n regex = re.compile('(\\\\d*)([wubrg]*)')\n match = regex.search(mana)\n for x in list(mana):\n if x in valid:\n dic[x] = dic[x] + 1 if x in dic else 1\n if match.group(1) and match.group(1) != '0':\n dic['*'] = int(match.group(1))\n return dic if ''.join(match.group()) == mana else None", "from itertools import groupby\nimport re\n\ndef parse_mana_cost(mana):\n result = {}\n pattern = re.compile('\\\\d*[wurbg]*', re.I)\n manacost = pattern.match(mana).group()\n if mana in ['', '0']:\n return {}\n if manacost == None or len(mana) != len(manacost):\n return None\n (colors, colorless) = ('', '')\n for i in manacost:\n if i.isalpha():\n colors += i\n else:\n colorless += i\n if colorless not in ['0', '']:\n result['*'] = int(colorless)\n colors = ''.join(sorted(list(colors)))\n for (key, count) in groupby(colors):\n result[key.lower()] = len(list(count))\n return result"], "starter_code": "def parse_mana_cost(mana):\n", "input_output": {"fn_name": "parse_mana_cost", "inputs": [[""], ["0"], ["1"], ["4"], ["15"], ["2rr"], ["1wbg"], ["1WWU"], ["0r"], ["2x"], ["2R"], ["2\n"], ["\n2"], ["1b"], ["1bb"], ["1bbb"], ["1bg"], ["1bgu"], ["1br"], ["1brg"], ["1g"], ["1gg"], ["1ggg"], ["1ggu"], ["1ggw"], ["1gu"], ["1guu"], ["1gw"], ["1gwu"], ["1gww"], ["1r"], ["1rg"], ["1rgg"], ["1rgw"], ["1rr"], ["1rrr"], ["1rrw"], ["1rw"], ["1rwb"], ["1rwu"], ["1u"], ["1ub"], ["1ubr"], ["1ur"], ["1uu"], ["1uub"], ["1uur"], ["1uuu"], ["1w"], ["1wb"], ["1wbr"], ["1wu"], ["1wub"], ["1wubrg"], ["1ww"], ["1wwbb"], ["1wwu"], ["1wwuu"], ["1www"], ["2"], ["2b"], ["2bb"], ["2bbb"], ["2bbr"], ["2bbrr"], ["2bbrrgg"], ["2bg"], ["2bgg"], ["2bgu"], ["2bgw"], ["2br"], ["2brg"], ["2brr"], ["2g"], ["2gg"], ["2ggg"], ["2gggg"], ["2gguu"], ["2ggww"], ["2ggwwuu"], ["2gu"], ["2gub"], ["2gur"], ["2guu"], ["2gw"], ["2gwu"], ["2gww"], ["2r"], ["2rg"], ["2rgw"], ["2rrgg"], ["2rrggww"], ["2rrr"], ["2rrrg"], ["2rrww"], ["2rw"], ["2rwb"], ["2u"], ["2ub"], ["2ubr"], ["2ur"], ["2urg"], ["2urw"], ["2uu"], ["2uubb"], ["2uubbrr"], ["2uurr"], ["2uuu"], ["2uuuu"], ["2w"], ["2wb"], ["2wbg"], ["2wu"], ["2wub"], ["2wuu"], ["2wuub"], ["2ww"], ["2wwb"], ["2wwbb"], ["2wwuu"], ["2wwuubb"], ["2www"], ["3"], ["3b"], ["3bb"], ["3bbb"], ["3bbbb"], ["3bbg"], ["3bbr"], ["3bbrr"], ["3bg"], ["3bgu"], ["3bgw"], ["3br"], ["3brg"], ["3g"], ["3gg"], ["3ggg"], ["3gggg"], ["3ggw"], ["3ggww"], ["3gu"], ["3gub"], ["3gur"], ["3gw"], ["3gwu"], ["3gww"], ["3r"], ["3rg"], ["3rgg"], ["3rgw"], ["3rr"], ["3rrg"], ["3rrgg"], ["3rrr"], ["3rrrr"], ["3rw"], ["3rwb"], ["3rwu"], ["3rww"], ["3u"], ["3ub"], ["3ubb"], ["3ubr"], ["3ur"], ["3urg"], ["3urw"], ["3uu"], ["3uub"], ["3uubb"], ["3uuu"], ["3w"], ["3wb"], ["3wbb"], ["3wbg"], ["3wbr"], ["3wu"], ["3wub"], ["3wubrg"], ["3wuu"], ["3ww"], ["3wwbb"], ["3wwu"], ["3wwuu"], ["3www"], ["4b"], ["4bb"], ["4bbb"], ["4bbbb"], ["4bbgg"], ["4bbrr"], ["4bg"], ["4br"], ["4brg"], ["4brr"], ["4brrg"], ["4g"], ["4gg"], ["4ggg"], ["4gggg"], ["4ggww"], ["4gu"], ["4gub"], ["4gw"], ["4gwwu"], ["4r"], ["4rg"], ["4rggw"], ["4rgw"], ["4rr"], ["4rrg"], ["4rrgg"], ["4rrr"], ["4rrww"], ["4rw"], ["4rww"], ["4u"], ["4ub"], ["4ubbr"], ["4ubr"], ["4ur"], ["4uu"], ["4uuu"], ["4w"], ["4wb"], ["4wbb"], ["4wbg"], ["4wbr"], ["4wu"], ["4wub"], ["4wuub"], ["4ww"], ["4wwbb"], ["4wwu"], ["4www"], ["5"], ["5b"], ["5bb"], ["5bbb"], ["5bg"], ["5bgw"], ["5br"], ["5g"], ["5gg"], ["5ggg"], ["5gu"], ["5guu"], ["5gw"], ["5r"], ["5rg"], ["5rr"], ["5rrr"], ["5rw"], ["5u"], ["5ub"], ["5ubb"], ["5ur"], ["5urg"], ["5uu"], ["5uuu"], ["5uuuu"], ["5w"], ["5wb"], ["5wu"], ["5wub"], ["5ww"], ["5wwu"], ["5www"], ["6"], ["6b"], ["6bb"], ["6bbb"], ["6bg"], ["6br"], ["6g"], ["6gg"], ["6ggg"], ["6gw"], ["6r"], ["6rr"], ["6rrr"], ["6u"], ["6uu"], ["6uuu"], ["6w"], ["6ww"], ["6www"], ["7"], ["7b"], ["7bb"], ["7bbb"], ["7g"], ["7gg"], ["7ggg"], ["7r"], ["7rr"], ["7rrr"], ["7u"], ["7uu"], ["7uuu"], ["7w"], ["7ww"], ["7www"], ["8"], ["8b"], ["8bb"], ["8bbb"], ["8bbgg"], ["8g"], ["8gg"], ["8ggg"], ["8r"], ["8rr"], ["8uu"], ["8uuu"], ["8uuuu"], ["8ww"], ["9"], ["9b"], ["9r"], ["b"], ["bb"], ["bbb"], ["bbbb"], ["bbbbbbbbbbbbbbb"], ["bbgg"], ["bbr"], ["bbrr"], ["bbrrrgg"], ["bg"], ["bgg"], ["bgu"], ["bgw"], ["br"], ["brg"], ["brgw"], ["g"], ["gg"], ["ggg"], ["gggg"], ["ggggg"], ["gggggg"], ["gggggggg"], ["gggwww"], ["gguu"], ["ggw"], ["ggww"], ["ggwwwuu"], ["gu"], ["gur"], ["guu"], ["gw"], ["gwu"], ["gwub"], ["r"], ["rg"], ["rgw"], ["rgwu"], ["rr"], ["rrgg"], ["rrgggww"], ["rrr"], ["rrrr"], ["rw"], ["rwb"], ["u"], ["ub"], ["ubbr"], ["ubr"], ["ubrg"], ["ur"], ["urg"], ["urr"], ["urw"], ["uu"], ["uub"], ["uubb"], ["uubbbrr"], ["uur"], ["uuu"], ["uuuu"], ["w"], ["wb"], ["wbb"], ["wbg"], ["wu"], ["wub"], ["wubr"], ["wubrg"], ["wuu"], ["wuub"], ["ww"], ["wwbb"], ["wwuu"], ["wwuubbrrgg"], ["wwuuubb"], ["www"], ["wwww"]], "outputs": [[{}], [{}], [{"*": 1}], [{"*": 4}], [{"*": 15}], [{"*": 2, "r": 2}], [{"*": 1, "w": 1, "b": 1, "g": 1}], [{"*": 1, "w": 2, "u": 1}], [{"r": 1}], [null], [{"*": 2, "r": 1}], [null], [null], [{"*": 1, "b": 1}], [{"*": 1, "b": 2}], [{"*": 1, "b": 3}], [{"*": 1, "b": 1, "g": 1}], [{"*": 1, "u": 1, "b": 1, "g": 1}], [{"*": 1, "b": 1, "r": 1}], [{"*": 1, "b": 1, "r": 1, "g": 1}], [{"*": 1, "g": 1}], [{"*": 1, "g": 2}], [{"*": 1, "g": 3}], [{"*": 1, "u": 1, "g": 2}], [{"*": 1, "w": 1, "g": 2}], [{"*": 1, "u": 1, "g": 1}], [{"*": 1, "u": 2, "g": 1}], [{"*": 1, "w": 1, "g": 1}], [{"*": 1, "w": 1, "u": 1, "g": 1}], [{"*": 1, "w": 2, "g": 1}], [{"*": 1, "r": 1}], [{"*": 1, "r": 1, "g": 1}], [{"*": 1, "r": 1, "g": 2}], [{"*": 1, "w": 1, "r": 1, "g": 1}], [{"*": 1, "r": 2}], [{"*": 1, "r": 3}], [{"*": 1, "w": 1, "r": 2}], [{"*": 1, "w": 1, "r": 1}], [{"*": 1, "w": 1, "b": 1, "r": 1}], [{"*": 1, "w": 1, "u": 1, "r": 1}], [{"*": 1, "u": 1}], [{"*": 1, "u": 1, "b": 1}], [{"*": 1, "u": 1, "b": 1, "r": 1}], [{"*": 1, "u": 1, "r": 1}], [{"*": 1, "u": 2}], [{"*": 1, "u": 2, "b": 1}], [{"*": 1, "u": 2, "r": 1}], [{"*": 1, "u": 3}], [{"*": 1, "w": 1}], [{"*": 1, "w": 1, "b": 1}], [{"*": 1, "w": 1, "b": 1, "r": 1}], [{"*": 1, "w": 1, "u": 1}], [{"*": 1, "w": 1, "u": 1, "b": 1}], [{"*": 1, "w": 1, "u": 1, "b": 1, "r": 1, "g": 1}], [{"*": 1, "w": 2}], [{"*": 1, "w": 2, "b": 2}], [{"*": 1, "w": 2, "u": 1}], [{"*": 1, "w": 2, "u": 2}], [{"*": 1, "w": 3}], [{"*": 2}], [{"*": 2, "b": 1}], [{"*": 2, "b": 2}], [{"*": 2, "b": 3}], [{"*": 2, "b": 2, "r": 1}], [{"*": 2, "b": 2, "r": 2}], [{"*": 2, "b": 2, "r": 2, "g": 2}], [{"*": 2, "b": 1, "g": 1}], [{"*": 2, "b": 1, "g": 2}], [{"*": 2, "u": 1, "b": 1, "g": 1}], [{"*": 2, "w": 1, "b": 1, "g": 1}], [{"*": 2, "b": 1, "r": 1}], [{"*": 2, "b": 1, "r": 1, "g": 1}], [{"*": 2, "b": 1, "r": 2}], [{"*": 2, "g": 1}], [{"*": 2, "g": 2}], [{"*": 2, "g": 3}], [{"*": 2, "g": 4}], [{"*": 2, "u": 2, "g": 2}], [{"*": 2, "w": 2, "g": 2}], [{"*": 2, "w": 2, "u": 2, "g": 2}], [{"*": 2, "u": 1, "g": 1}], [{"*": 2, "u": 1, "b": 1, "g": 1}], [{"*": 2, "u": 1, "r": 1, "g": 1}], [{"*": 2, "u": 2, "g": 1}], [{"*": 2, "w": 1, "g": 1}], [{"*": 2, "w": 1, "u": 1, "g": 1}], [{"*": 2, "w": 2, "g": 1}], [{"*": 2, "r": 1}], [{"*": 2, "r": 1, "g": 1}], [{"*": 2, "w": 1, "r": 1, "g": 1}], [{"*": 2, "r": 2, "g": 2}], [{"*": 2, "w": 2, "r": 2, "g": 2}], [{"*": 2, "r": 3}], [{"*": 2, "r": 3, "g": 1}], [{"*": 2, "w": 2, "r": 2}], [{"*": 2, "w": 1, "r": 1}], [{"*": 2, "w": 1, "b": 1, "r": 1}], [{"*": 2, "u": 1}], [{"*": 2, "u": 1, "b": 1}], [{"*": 2, "u": 1, "b": 1, "r": 1}], [{"*": 2, "u": 1, "r": 1}], [{"*": 2, "u": 1, "r": 1, "g": 1}], [{"*": 2, "w": 1, "u": 1, "r": 1}], [{"*": 2, "u": 2}], [{"*": 2, "u": 2, "b": 2}], [{"*": 2, "u": 2, "b": 2, "r": 2}], [{"*": 2, "u": 2, "r": 2}], [{"*": 2, "u": 3}], [{"*": 2, "u": 4}], [{"*": 2, "w": 1}], [{"*": 2, "w": 1, "b": 1}], [{"*": 2, "w": 1, "b": 1, "g": 1}], [{"*": 2, "w": 1, "u": 1}], [{"*": 2, "w": 1, "u": 1, "b": 1}], [{"*": 2, "w": 1, "u": 2}], [{"*": 2, "w": 1, "u": 2, "b": 1}], [{"*": 2, "w": 2}], [{"*": 2, "w": 2, "b": 1}], [{"*": 2, "w": 2, "b": 2}], [{"*": 2, "w": 2, "u": 2}], [{"*": 2, "w": 2, "u": 2, "b": 2}], [{"*": 2, "w": 3}], [{"*": 3}], [{"*": 3, "b": 1}], [{"*": 3, "b": 2}], [{"*": 3, "b": 3}], [{"*": 3, "b": 4}], [{"*": 3, "b": 2, "g": 1}], [{"*": 3, "b": 2, "r": 1}], [{"*": 3, "b": 2, "r": 2}], [{"*": 3, "b": 1, "g": 1}], [{"*": 3, "u": 1, "b": 1, "g": 1}], [{"*": 3, "w": 1, "b": 1, "g": 1}], [{"*": 3, "b": 1, "r": 1}], [{"*": 3, "b": 1, "r": 1, "g": 1}], [{"*": 3, "g": 1}], [{"*": 3, "g": 2}], [{"*": 3, "g": 3}], [{"*": 3, "g": 4}], [{"*": 3, "w": 1, "g": 2}], [{"*": 3, "w": 2, "g": 2}], [{"*": 3, "u": 1, "g": 1}], [{"*": 3, "u": 1, "b": 1, "g": 1}], [{"*": 3, "u": 1, "r": 1, "g": 1}], [{"*": 3, "w": 1, "g": 1}], [{"*": 3, "w": 1, "u": 1, "g": 1}], [{"*": 3, "w": 2, "g": 1}], [{"*": 3, "r": 1}], [{"*": 3, "r": 1, "g": 1}], [{"*": 3, "r": 1, "g": 2}], [{"*": 3, "w": 1, "r": 1, "g": 1}], [{"*": 3, "r": 2}], [{"*": 3, "r": 2, "g": 1}], [{"*": 3, "r": 2, "g": 2}], [{"*": 3, "r": 3}], [{"*": 3, "r": 4}], [{"*": 3, "w": 1, "r": 1}], [{"*": 3, "w": 1, "b": 1, "r": 1}], [{"*": 3, "w": 1, "u": 1, "r": 1}], [{"*": 3, "w": 2, "r": 1}], [{"*": 3, "u": 1}], [{"*": 3, "u": 1, "b": 1}], [{"*": 3, "u": 1, "b": 2}], [{"*": 3, "u": 1, "b": 1, "r": 1}], [{"*": 3, "u": 1, "r": 1}], [{"*": 3, "u": 1, "r": 1, "g": 1}], [{"*": 3, "w": 1, "u": 1, "r": 1}], [{"*": 3, "u": 2}], [{"*": 3, "u": 2, "b": 1}], [{"*": 3, "u": 2, "b": 2}], [{"*": 3, "u": 3}], [{"*": 3, "w": 1}], [{"*": 3, "w": 1, "b": 1}], [{"*": 3, "w": 1, "b": 2}], [{"*": 3, "w": 1, "b": 1, "g": 1}], [{"*": 3, "w": 1, "b": 1, "r": 1}], [{"*": 3, "w": 1, "u": 1}], [{"*": 3, "w": 1, "u": 1, "b": 1}], [{"*": 3, "w": 1, "u": 1, "b": 1, "r": 1, "g": 1}], [{"*": 3, "w": 1, "u": 2}], [{"*": 3, "w": 2}], [{"*": 3, "w": 2, "b": 2}], [{"*": 3, "w": 2, "u": 1}], [{"*": 3, "w": 2, "u": 2}], [{"*": 3, "w": 3}], [{"*": 4, "b": 1}], [{"*": 4, "b": 2}], [{"*": 4, "b": 3}], [{"*": 4, "b": 4}], [{"*": 4, "b": 2, "g": 2}], [{"*": 4, "b": 2, "r": 2}], [{"*": 4, "b": 1, "g": 1}], [{"*": 4, "b": 1, "r": 1}], [{"*": 4, "b": 1, "r": 1, "g": 1}], [{"*": 4, "b": 1, "r": 2}], [{"*": 4, "b": 1, "r": 2, "g": 1}], [{"*": 4, "g": 1}], [{"*": 4, "g": 2}], [{"*": 4, "g": 3}], [{"*": 4, "g": 4}], [{"*": 4, "w": 2, "g": 2}], [{"*": 4, "u": 1, "g": 1}], [{"*": 4, "u": 1, "b": 1, "g": 1}], [{"*": 4, "w": 1, "g": 1}], [{"*": 4, "w": 2, "u": 1, "g": 1}], [{"*": 4, "r": 1}], [{"*": 4, "r": 1, "g": 1}], [{"*": 4, "w": 1, "r": 1, "g": 2}], [{"*": 4, "w": 1, "r": 1, "g": 1}], [{"*": 4, "r": 2}], [{"*": 4, "r": 2, "g": 1}], [{"*": 4, "r": 2, "g": 2}], [{"*": 4, "r": 3}], [{"*": 4, "w": 2, "r": 2}], [{"*": 4, "w": 1, "r": 1}], [{"*": 4, "w": 2, "r": 1}], [{"*": 4, "u": 1}], [{"*": 4, "u": 1, "b": 1}], [{"*": 4, "u": 1, "b": 2, "r": 1}], [{"*": 4, "u": 1, "b": 1, "r": 1}], [{"*": 4, "u": 1, "r": 1}], [{"*": 4, "u": 2}], [{"*": 4, "u": 3}], [{"*": 4, "w": 1}], [{"*": 4, "w": 1, "b": 1}], [{"*": 4, "w": 1, "b": 2}], [{"*": 4, "w": 1, "b": 1, "g": 1}], [{"*": 4, "w": 1, "b": 1, "r": 1}], [{"*": 4, "w": 1, "u": 1}], [{"*": 4, "w": 1, "u": 1, "b": 1}], [{"*": 4, "w": 1, "u": 2, "b": 1}], [{"*": 4, "w": 2}], [{"*": 4, "w": 2, "b": 2}], [{"*": 4, "w": 2, "u": 1}], [{"*": 4, "w": 3}], [{"*": 5}], [{"*": 5, "b": 1}], [{"*": 5, "b": 2}], [{"*": 5, "b": 3}], [{"*": 5, "b": 1, "g": 1}], [{"*": 5, "w": 1, "b": 1, "g": 1}], [{"*": 5, "b": 1, "r": 1}], [{"*": 5, "g": 1}], [{"*": 5, "g": 2}], [{"*": 5, "g": 3}], [{"*": 5, "u": 1, "g": 1}], [{"*": 5, "u": 2, "g": 1}], [{"*": 5, "w": 1, "g": 1}], [{"*": 5, "r": 1}], [{"*": 5, "r": 1, "g": 1}], [{"*": 5, "r": 2}], [{"*": 5, "r": 3}], [{"*": 5, "w": 1, "r": 1}], [{"*": 5, "u": 1}], [{"*": 5, "u": 1, "b": 1}], [{"*": 5, "u": 1, "b": 2}], [{"*": 5, "u": 1, "r": 1}], [{"*": 5, "u": 1, "r": 1, "g": 1}], [{"*": 5, "u": 2}], [{"*": 5, "u": 3}], [{"*": 5, "u": 4}], [{"*": 5, "w": 1}], [{"*": 5, "w": 1, "b": 1}], [{"*": 5, "w": 1, "u": 1}], [{"*": 5, "w": 1, "u": 1, "b": 1}], [{"*": 5, "w": 2}], [{"*": 5, "w": 2, "u": 1}], [{"*": 5, "w": 3}], [{"*": 6}], [{"*": 6, "b": 1}], [{"*": 6, "b": 2}], [{"*": 6, "b": 3}], [{"*": 6, "b": 1, "g": 1}], [{"*": 6, "b": 1, "r": 1}], [{"*": 6, "g": 1}], [{"*": 6, "g": 2}], [{"*": 6, "g": 3}], [{"*": 6, "w": 1, "g": 1}], [{"*": 6, "r": 1}], [{"*": 6, "r": 2}], [{"*": 6, "r": 3}], [{"*": 6, "u": 1}], [{"*": 6, "u": 2}], [{"*": 6, "u": 3}], [{"*": 6, "w": 1}], [{"*": 6, "w": 2}], [{"*": 6, "w": 3}], [{"*": 7}], [{"*": 7, "b": 1}], [{"*": 7, "b": 2}], [{"*": 7, "b": 3}], [{"*": 7, "g": 1}], [{"*": 7, "g": 2}], [{"*": 7, "g": 3}], [{"*": 7, "r": 1}], [{"*": 7, "r": 2}], [{"*": 7, "r": 3}], [{"*": 7, "u": 1}], [{"*": 7, "u": 2}], [{"*": 7, "u": 3}], [{"*": 7, "w": 1}], [{"*": 7, "w": 2}], [{"*": 7, "w": 3}], [{"*": 8}], [{"*": 8, "b": 1}], [{"*": 8, "b": 2}], [{"*": 8, "b": 3}], [{"*": 8, "b": 2, "g": 2}], [{"*": 8, "g": 1}], [{"*": 8, "g": 2}], [{"*": 8, "g": 3}], [{"*": 8, "r": 1}], [{"*": 8, "r": 2}], [{"*": 8, "u": 2}], [{"*": 8, "u": 3}], [{"*": 8, "u": 4}], [{"*": 8, "w": 2}], [{"*": 9}], [{"*": 9, "b": 1}], [{"*": 9, "r": 1}], [{"b": 1}], [{"b": 2}], [{"b": 3}], [{"b": 4}], [{"b": 15}], [{"b": 2, "g": 2}], [{"b": 2, "r": 1}], [{"b": 2, "r": 2}], [{"b": 2, "r": 3, "g": 2}], [{"b": 1, "g": 1}], [{"b": 1, "g": 2}], [{"u": 1, "b": 1, "g": 1}], [{"w": 1, "b": 1, "g": 1}], [{"b": 1, "r": 1}], [{"b": 1, "r": 1, "g": 1}], [{"w": 1, "b": 1, "r": 1, "g": 1}], [{"g": 1}], [{"g": 2}], [{"g": 3}], [{"g": 4}], [{"g": 5}], [{"g": 6}], [{"g": 8}], [{"w": 3, "g": 3}], [{"u": 2, "g": 2}], [{"w": 1, "g": 2}], [{"w": 2, "g": 2}], [{"w": 3, "u": 2, "g": 2}], [{"u": 1, "g": 1}], [{"u": 1, "r": 1, "g": 1}], [{"u": 2, "g": 1}], [{"w": 1, "g": 1}], [{"w": 1, "u": 1, "g": 1}], [{"w": 1, "u": 1, "b": 1, "g": 1}], [{"r": 1}], [{"r": 1, "g": 1}], [{"w": 1, "r": 1, "g": 1}], [{"w": 1, "u": 1, "r": 1, "g": 1}], [{"r": 2}], [{"r": 2, "g": 2}], [{"w": 2, "r": 2, "g": 3}], [{"r": 3}], [{"r": 4}], [{"w": 1, "r": 1}], [{"w": 1, "b": 1, "r": 1}], [{"u": 1}], [{"u": 1, "b": 1}], [{"u": 1, "b": 2, "r": 1}], [{"u": 1, "b": 1, "r": 1}], [{"u": 1, "b": 1, "r": 1, "g": 1}], [{"u": 1, "r": 1}], [{"u": 1, "r": 1, "g": 1}], [{"u": 1, "r": 2}], [{"w": 1, "u": 1, "r": 1}], [{"u": 2}], [{"u": 2, "b": 1}], [{"u": 2, "b": 2}], [{"u": 2, "b": 3, "r": 2}], [{"u": 2, "r": 1}], [{"u": 3}], [{"u": 4}], [{"w": 1}], [{"w": 1, "b": 1}], [{"w": 1, "b": 2}], [{"w": 1, "b": 1, "g": 1}], [{"w": 1, "u": 1}], [{"w": 1, "u": 1, "b": 1}], [{"w": 1, "u": 1, "b": 1, "r": 1}], [{"w": 1, "u": 1, "b": 1, "r": 1, "g": 1}], [{"w": 1, "u": 2}], [{"w": 1, "u": 2, "b": 1}], [{"w": 2}], [{"w": 2, "b": 2}], [{"w": 2, "u": 2}], [{"w": 2, "u": 2, "b": 2, "r": 2, "g": 2}], [{"w": 2, "u": 3, "b": 2}], [{"w": 3}], [{"w": 4}]]}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5686004a2c7fade6b500002d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "parse_mana_cost", "task_id": "TACO_lite/186", "example": [[], []]} +{"requirement": "You are given an array of integers. Your task is to sort odd numbers within the array in ascending order, and even numbers in descending order.\n\nNote that zero is an even number. If you have an empty array, you need to return it.\n\n\nFor example:\n```\n[5, 3, 2, 8, 1, 4] --> [1, 3, 8, 4, 5, 2]\n\nodd numbers ascending: [1, 3, 5 ]\neven numbers descending: [ 8, 4, 2]\n```", "solutions": ["def sort_array(xs):\n es = sorted((x for x in xs if x % 2 == 0))\n os = sorted((x for x in xs if x % 2 != 0), reverse=True)\n return [(es if x % 2 == 0 else os).pop() for x in xs]", "def sort_array(a):\n odds = []\n evens = []\n newArray = []\n for i in a:\n if i % 2 == 0:\n evens.append(i)\n else:\n odds.append(i)\n evens.sort()\n evens.reverse()\n odds.sort()\n for i in range(len(a)):\n if a[i] % 2 == 0:\n newArray.append(evens[0])\n evens.pop(0)\n else:\n newArray.append(odds[0])\n odds.pop(0)\n return newArray", "def sort_array(a):\n odds = iter(sorted((n for n in a if n % 2)))\n evens = iter(sorted((n for n in a if not n % 2), reverse=True))\n return [next(odds) if n % 2 else next(evens) for n in a]", "def sort_array(a):\n (sorted_odd, sorted_even) = (sorted((value for value in a if value & 1)), sorted([value for value in a if not value & 1], reverse=True))\n return [sorted_odd.pop(0) if value & 1 else sorted_even.pop(0) for value in a]", "def sort_array(a):\n (e, o) = (sorted((x for x in a if x % 2 ^ 1)), sorted((x for x in a if x % 2), reverse=True))\n return [(o if x % 2 else e).pop() for x in a]", "def sort_array(a):\n sorted_odd = sorted([x for x in a if x % 2 == 1], reverse=True)\n sorted_even = sorted([x for x in a if x % 2 == 0])\n out = []\n for x in a:\n if x % 2 == 0:\n out.append(sorted_even.pop())\n else:\n out.append(sorted_odd.pop())\n return out", "def sort_array(lst):\n s = sorted(lst)\n even = (n for n in s[::-1] if n & 1 == 0)\n odd = (n for n in s if n & 1)\n return [next(odd if n & 1 else even) for n in lst]", "def sort_array(lst):\n (even, odd) = ([], [])\n for n in sorted(lst):\n (odd if n & 1 else even).append(n)\n (even, odd) = (iter(even[::-1]), iter(odd))\n return [next(odd if n & 1 else even) for n in lst]", "def sort_array(a):\n lenList = len(a)\n if lenList == 0:\n return []\n (evenNums, oddNums) = ([], [])\n (evenNumLoc, oddNumLoc) = ([], [])\n for i in range(0, lenList, 1):\n if a[i] % 2 == 0:\n evenNums.append(a[i])\n evenNumLoc.append(i)\n else:\n oddNums.append(a[i])\n oddNumLoc.append(i)\n evenNums.sort(reverse=True)\n oddNums.sort()\n sortedList = [0 for _ in range(lenList)]\n totalNumEvens = len(evenNums)\n totalNumOdds = len(oddNums)\n for i in range(0, totalNumEvens, 1):\n sortedList[evenNumLoc[i]] = evenNums[i]\n for i in range(0, totalNumOdds, 1):\n sortedList[oddNumLoc[i]] = oddNums[i]\n return sortedList", "from collections import deque\n\ndef sort_array(a):\n asc = deque(sorted((x for x in a if x % 2)))\n desc = sorted((x for x in a if not x % 2))\n return [asc.popleft() if x % 2 else desc.pop() for x in a]"], "starter_code": "def sort_array(a):\n", "input_output": {"fn_name": "sort_array", "inputs": [[[5, 3, 2, 8, 1, 4, 11]], [[2, 22, 37, 11, 4, 1, 5, 0]], [[1, 111, 11, 11, 2, 1, 5, 0]], [[]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 1, 2, 3, 4, 9, 8, 7, 6, 5]]], "outputs": [[[1, 3, 8, 4, 5, 2, 11]], [[22, 4, 1, 5, 2, 11, 37, 0]], [[1, 1, 5, 11, 2, 11, 111, 0]], [[]], [[1, 8, 3, 6, 5, 4, 7, 2, 9, 0]], [[8, 1, 6, 3, 4, 5, 2, 7, 0, 9]], [[8, 1, 6, 3, 4, 5, 2, 7, 0, 9]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Sorting"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/5a1cb5406975987dd9000028", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sort_array", "task_id": "TACO_lite/88", "example": [[[[5, 3, 2, 8, 1, 4]]], ["[1, 3, 8, 4, 5, 2]"]]} +{"requirement": "Your task is simply to count the total number of lowercase letters in a string.\n\n## Examples", "solutions": ["def lowercase_count(strng):\n return sum((a.islower() for a in strng))", "import re\n\ndef lowercase_count(string):\n return len(re.findall('[a-z]', string))", "def lowercase_count(str):\n return sum((1 for c in str if c.islower()))", "def lowercase_count(strng):\n return len([ch for ch in strng if ch.islower()])", "def lowercase_count(s):\n return sum((c.islower() for c in s))", "lowercase_count = lambda s: sum((e.islower() for e in s))", "def lowercase_count(s):\n return sum((1 for c in s if c.islower()))", "def lowercase_count(strng):\n return sum((1 for i in strng if i.islower()))", "import re\n\ndef lowercase_count(st):\n return len(re.sub('[^a-z]*', '', st))", "import re\n\ndef lowercase_count(text):\n return len(re.findall('[a-z]', text))", "import re\n\ndef lowercase_count(str):\n return len(re.findall('[a-z]', str))", "import re\nlowercase_count = lambda s: len(re.findall('[a-z]', s))", "import re\n\ndef lowercase_count(str):\n return len(re.sub('[^a-z]', '', str))", "def lowercase_count(s):\n return len(list(filter(lambda x: x in map(chr, range(97, 123)), s)))", "import re\n\ndef lowercase_count(strng):\n regex = re.compile('[a-z]')\n match = regex.findall(strng)\n if match:\n return len(match)\n return 0", "def lowercase_count(strg):\n c = 0\n case = 'abcdefghijklmnopqrstuvwxyz'\n for x in strg:\n if x in case:\n c = c + 1\n return c", "def lowercase_count(strng):\n lowers = 'abcdefghijklmnopqrstuvwxyz'\n count = 0\n for c in strng:\n if c in lowers:\n count += 1\n return count", "def lowercase_count(string):\n return sum(map(str.islower, string))", "variable = 'abc'\n\ndef lowercase_count(strng):\n array = []\n for x in strng:\n index = ord(x[0])\n if 97 <= index <= 122 and index > 91:\n variableForArray = chr(index)\n array.append(variableForArray)\n else:\n continue\n return len(array)", "def lowercase_count(strng):\n return len([i for i in strng if i.islower()])", "def lowercase_count(strng):\n lowerCastCount = 0\n for i in strng:\n if i.isdigit():\n None\n elif i.islower():\n lowerCastCount += 1\n return lowerCastCount", "from re import findall\n\ndef lowercase_count(string: str) -> int:\n return len(findall('[a-z]', string))", "def lowercase_count(strng):\n import re\n return len(re.findall('[a-z]', strng))", "def lowercase_count(strng):\n return sum(map(str.islower, strng))", "lowercase_count = lambda s: len([x for x in s if x in 'abcdefghijklmnopqrstuvwxyz'])", "def lowercase_count(strng):\n import string\n return len(''.join([i for i in strng if i in string.ascii_lowercase]))", "def lowercase_count(string):\n c = 0\n for i in string:\n if i.islower() == True:\n c += 1\n return c", "def lowercase_count(strng):\n l_1 = list(strng)\n l_2 = list('qwertyuiopasdfghjklzxcvbnm')\n l_3 = []\n for elem in l_1:\n if elem in l_2:\n l_3.append(elem)\n return len(l_3)", "def lowercase_count(s):\n return sum((1 for i in s if 'a' <= i <= 'z'))", "def lowercase_count(s):\n ALPHABET = 'abcdefghijklmnopqrstuvwxyz'\n return sum((x in ALPHABET for x in s))", "def lowercase_count(lst):\n n = 0\n for s in lst:\n if s >= 'a' and s <= 'z':\n n = n + 1\n return n", "def lowercase_count(strng):\n total = 0\n for i in list(strng):\n if i in list('qwertyuiopasdfghjklzxcvbnm'):\n total = total + 1\n return total", "def lowercase_count(strng):\n lc = 0\n for letter in strng:\n if 'z' >= letter >= 'a':\n lc += 1\n return lc", "def lowercase_count(strng):\n li = list(strng)\n counter = 0\n for c in range(len(li)):\n if 96 < ord(li[c]) < 123:\n counter += 1\n return counter", "def lowercase_count(strng):\n ans = 0\n for x in strng:\n if x.islower() == True:\n ans += 1\n return ans", "def lowercase_count(strng):\n i = 0\n for x in strng:\n if 'a' <= x <= 'z':\n i += 1\n return i", "def lowercase_count(strng):\n count = 0\n for chr in strng:\n if chr != chr.upper():\n count += 1\n return count", "def lowercase_count(strng):\n somme = 0\n for minuscule in strng:\n if minuscule.islower():\n somme += 1\n return somme", "def lowercase_count(string):\n lower_cases = 'abcdefghijklmnopqrstuvwxyz'\n lower_case_counter = 0\n index = 0\n while index < len(string):\n if string[index] in lower_cases:\n lower_case_counter += 1\n index += 1\n return lower_case_counter", "def lowercase_count(str):\n count = 0\n alpha = 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z'\n trex = alpha.split(',')\n for x in str:\n if x in trex:\n count += 1\n return count", "def lowercase_count(strng):\n return sum((True for i in strng if i.islower()))", "def lowercase_count(strng):\n import re\n from re import finditer\n pattern = '[a-z]'\n count = 0\n for it in finditer(pattern, strng):\n count += 1\n return count", "def lowercase_count(strng: str) -> int:\n return sum((c.islower() for c in strng))", "def lowercase_count(strng):\n lst = list(strng)\n count = 0\n for letter in lst:\n if letter.islower():\n count += 1\n return count", "import re\n\ndef lowercase_count(strng):\n pattern = re.compile('[a-z]{1}')\n matches = pattern.findall(strng)\n return len(matches)", "def lowercase_count(strng):\n count = 0\n for letter in strng:\n if letter.isalpha():\n if ord(letter) <= ord('z') and ord(letter) >= ord('a'):\n count += 1\n return count", "def lowercase_count(string):\n string = str(string)\n a = 0\n for i in string:\n if i.islower():\n a += 1\n return a", "def lowercase_count(string):\n res = 0\n for i in string:\n if ord(i) > 96 and ord(i) < 123:\n res += 1\n return res", "import re\n\ndef lowercase_count(strng):\n return len(''.join(re.findall('([a-z]+)', strng))) if re.search('([a-z]+)', strng) else 0", "def lowercase_count(strng):\n return sum((1 for n in strng if n.islower()))", "def lowercase_count(strng):\n return sum([int(x.islower()) for x in strng])", "import string\n\ndef lowercase_count(strng):\n return sum([x in string.ascii_lowercase for x in strng])", "def lowercase_count(strng):\n num = 0\n for chr in strng:\n if chr.islower() == True:\n num += 1\n return num", "def lowercase_count(strng):\n letters = str(strng)\n lowercase = 0\n for i in letters:\n if i.islower():\n lowercase += 1\n return lowercase", "def lowercase_count(strng):\n nb = 0\n for ch in strng:\n if ch.islower():\n nb += 1\n return nb", "def lowercase_count(strng):\n letters = 'abcdefghijklmnopqrstuvwxyz'\n return len([i for i in strng if i in letters])", "def lowercase_count(strng):\n lower = 0\n for letter in strng:\n if letter >= 'a' and letter <= 'z':\n lower += 1\n return lower", "def lowercase_count(strng):\n return sum([1 if c.islower() else 0 for c in strng])", "def lowercase_count(s):\n num = 0\n for i in s:\n if i.islower():\n num += 1\n return num", "def lowercase_count(strng):\n return sum((1 for string in strng if string in 'abcdefghijklmnopqrstuvwxyz'))", "import string\n\ndef lowercase_count(string):\n return len([x for x in string if x in 'abcdefghijklmnopqrstuvwxyz'])", "def lowercase_count(strng):\n count = 0\n for let in strng:\n if let.isalpha() and let == let.lower():\n count += 1\n return count", "def lowercase_count(strng):\n count = 0\n s = [i for i in strng]\n for x in s:\n if x.islower() == True:\n count += 1\n else:\n pass\n return count", "from re import sub\n\ndef lowercase_count(strng):\n return len(sub('[^a-z]', '', strng))", "from regex import sub\n\ndef lowercase_count(strng):\n return len(sub('[^a-z]', '', strng))", "def lowercase_count(string):\n lowercase = [c for c in string if c.islower()]\n return len(lowercase)", "import string\n\ndef lowercase_count(s):\n return sum([1 for i in s if i in string.ascii_lowercase])", "def lowercase_count(strng):\n sum = 0\n for i in range(len(strng)):\n if strng[i].islower() == True:\n sum += 1\n return sum", "def lowercase_count(strng):\n import re\n result = ''\n match = re.findall('[a-z]', strng)\n result = ''.join(match)\n return len(result)", "import re\n\ndef lowercase_count(strng):\n match = re.findall('[a-z]', strng)\n count = 0\n for i in match:\n count += 1\n return count", "def lowercase_count(strng):\n dgu = []\n rwp = []\n pwr = list(str(strng))\n pwr.sort()\n for lower in pwr:\n if lower.islower():\n rwp.append(lower)\n dgu = len(rwp)\n return dgu", "lowercase_count = lambda s: len(list(filter(str.islower, s)))", "def lowercase_count(s):\n return len([x for x in s if x in 'abcdefghijklmnopqrstuvwxyz'])", "def lowercase_count(strng):\n count = 0\n for i in strng:\n if i.islower():\n count += 1\n return count\nlowercase_count('cdfABH')", "import re\n\ndef lowercase_count(strng):\n ct = 0\n for i in range(len(strng)):\n if re.search('[a-z]', strng[i]) != None:\n ct += 1\n return ct", "def lowercase_count(strng):\n results = 0\n for letter in strng:\n if letter.islower():\n results = results + 1\n return results", "def lowercase_count(strng):\n counter = 0\n for el in strng:\n if el in 'qwertyuiopasdfghjklzxcvbnm':\n counter += 1\n return counter", "import re\n\ndef lowercase_count(strng):\n lower = [c for c in strng if re.search('[a-z]', c)]\n return len(lower)", "import string\n\ndef lowercase_count(strng):\n count = 0\n for str in strng:\n if str in string.ascii_lowercase:\n count += 1\n return count", "def lowercase_count(strng):\n lowercase = ''.join((c for c in strng if c.islower()))\n return len(lowercase)", "def lowercase_count(strng):\n c = 0\n for i in range(len(strng)):\n if strng[i] in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']:\n c = c + 1\n return c", "def lowercase_count(string):\n accum = 0\n abc = list('qwertyuioplkjhgfdsazxcvbnm')\n for i in string:\n if i in abc:\n accum += 1\n return accum", "def lowercase_count(strng):\n letters = list(strng)\n count = 0\n for i in letters:\n if ord(i) > 96 and ord(i) < 123:\n count += 1\n return count", "def lowercase_count(strng):\n count = 0\n for x in strng:\n if x.islower():\n count += 1\n else:\n return count", "def lowercase_count(string):\n sum = 0\n for i in string:\n if i.islower():\n sum += 1\n return sum", "def lowercase_count(strng):\n count = 0\n for char in strng:\n if char.islower() is True:\n count = count + 1\n else:\n continue\n return count", "import re\n\ndef lowercase_count(strng):\n r = re.compile('[a-z]')\n return len(r.findall(strng))", "def lowercase_count(strng):\n ctr = 0\n for i in strng:\n if i.islower():\n ctr += 1\n return ctr", "def lowercase_count(strng):\n n = 0\n for k in strng:\n if k.islower():\n n += 1\n return n", "def lowercase_count(strng):\n count = 0\n for el in strng:\n count = count + (1 if el != el.upper() else 0)\n return count", "def lowercase_count(strng):\n return len([i for i in strng if i.lower() == i and i.isalpha()])"], "starter_code": "def lowercase_count(strng):\n", "input_output": {"fn_name": "lowercase_count", "inputs": [["abc"], ["abcABC123"], ["abcABC123!@#$%^&*()_-+=}{[]|':;?/>.<,~"], [""], ["ABC123!@#$%^&*()_-+=}{[]|':;?/>.<,~"], ["abcdefghijklmnopqrstuvwxyz"]], "outputs": [[3], [3], [3], [0], [0], [26]]}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Algorithms", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56a946cd7bd95ccab2000055", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "lowercase_count", "task_id": "TACO_lite/242", "example": [[["hello world"], ["HELLO world"], [""]], ["10", "5", "0"]]} +{"requirement": "Given a rectangle of size n x m, find the minimum number of integer-sided squares that tile the rectangle.\n \nExample 1:\n\nInput: n = 2, m = 3\nOutput: 3\nExplanation: 3 squares are necessary to cover the rectangle.\n2 (squares of 1x1)\n1 (square of 2x2)\nExample 2:\n\nInput: n = 5, m = 8\nOutput: 5\n\nExample 3:\n\nInput: n = 11, m = 13\nOutput: 6\n\n \nConstraints:\n\n1 <= n <= 13\n1 <= m <= 13", "solutions": ["from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n if n == 11 and m == 13 or (m == 11 and n == 13):\n return 6\n\n def dfs(x, y):\n if x % y == 0:\n return x // y\n if y % x == 0:\n return y // x\n res = x * y\n for i in range(1, x // 2 + 1):\n res = min(res, dfs(x - i, y) + dfs(i, y))\n for k in range(1, y // 2 + 1):\n res = min(res, dfs(x, y - k) + dfs(x, k))\n return res\n return dfs(n, m)", "from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n\n def dfs(x, y):\n if x == y:\n return 1\n if x == 1:\n return y\n if y == 1:\n return x\n result = x * y\n for i in range(1, x // 2 + 1):\n result = min(result, dfs(i, y) + dfs(x - i, y))\n for k in range(1, y // 2 + 1):\n result = min(result, dfs(x, k) + dfs(x, y - k))\n for centre_sq_size in range(1, min(x, y)):\n for i in range(1, x - centre_sq_size):\n for k in range(1, y - centre_sq_size):\n partition1 = dfs(i + centre_sq_size, k)\n partition2 = dfs(x - i - centre_sq_size, k + centre_sq_size)\n partition3 = dfs(i, y - k)\n partition4 = dfs(x - i, y - k - centre_sq_size)\n partition5 = 1\n result = min(result, partition1 + partition2 + partition3 + partition4 + partition5)\n return result\n return dfs(n, m)", "from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n INF = m * n\n\n def dp(state):\n if n == min(state):\n return 0\n state = list(state)\n mn = min(state)\n start = state.index(mn)\n res = INF\n for end in range(start, m):\n if state[end] != mn:\n break\n side = end - start + 1\n if mn + side > n:\n break\n state[start:end + 1] = [mn + side] * side\n res = min(res, dp(tuple(state)))\n return res + 1\n if m > n:\n (m, n) = (n, m)\n return dp(tuple([0] * m))", "def gcd(a, b):\n while a:\n (a, b) = (b % a, a)\n return b\n\ndef tilingrectangle(n: int, m: int) -> int:\n d = gcd(n, m)\n if d != 1:\n return self.tilingrectangle(n // d, m // d)\n if n > m:\n (n, m) = (m, n)\n if m % n == 0:\n return m // n\n heights = [0] * n\n recs = [[0, 1]]\n CAP = max(n, m)\n ans = CAP\n\n def is_valid():\n if len(recs) > ans - 1:\n return False\n (i, side) = recs[-1]\n if heights[i] + 1 > m:\n return False\n if i + side > n:\n return False\n if heights[i + side - 1] > heights[i]:\n return False\n return True\n while recs:\n if is_valid():\n (i, side) = recs[-1]\n for k in range(i, i + side - 1):\n heights[k] += 1\n heights[i + side - 1] += side\n (_, i) = min(((heights[k], k) for k in range(n)))\n if heights == [m] * n:\n ans = min(ans, len(recs))\n recs.append([i, 1])\n else:\n (i, side) = recs.pop()\n for k in range(i, i + side - 1):\n heights[k] -= side - 1\n if recs:\n recs[-1][-1] += 1\n return ans", "from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n\n def dfs(state):\n if n == min(state):\n return 0\n state = list(state)\n minimum = min(state)\n start = state.index(minimum)\n res = inf\n for end in range(start, m):\n if state[end] != minimum:\n break\n side = end - start + 1\n if minimum + side > n:\n break\n state[start:end + 1] = [minimum + side] * side\n res = min(res, dfs(tuple(state)))\n return res + 1\n inf = m * n\n if m > n:\n (m, n) = (n, m)\n return dfs(tuple([0] * m))", "def tilingrectangle(n: int, m: int) -> int:\n if m > n:\n (m, n) = (n, m)\n\n def dp(state):\n if min(state) == n:\n return 0\n state = list(state)\n mn = min(state)\n start = state.index(mn)\n res = float('inf')\n for end in range(start, m):\n if state[end] != mn:\n break\n side = end - start + 1\n if mn + side > n:\n break\n state[start:end + 1] = [mn + side] * side\n res = min(res, dp(tuple(state)))\n return res + 1\n return dp((0,) * m)", "def tilingrectangle(n: int, m: int) -> int:\n INF = m * n\n\n def dp(state, memo):\n if state in memo:\n return memo[state]\n if n == min(state):\n return 0\n state_ = list(state)\n mn = min(state_)\n start = state_.index(mn)\n res = INF\n for end in range(start, m):\n if state[end] != mn:\n break\n side = end - start + 1\n if mn + side > n:\n break\n state_[start:end + 1] = [mn + side] * side\n res = min(res, dp(tuple(state_), memo) + 1)\n memo[tuple(state)] = res\n return res\n if m > n:\n (m, n) = (n, m)\n return dp(tuple([0] * m), {})", "def tilingrectangle(n: int, m: int) -> int:\n res = 0\n dq = deque([[0] * m])\n seen = {tuple([0] * m)}\n while dq:\n length = len(dq)\n for _ in range(length):\n curr = dq.popleft()\n minh = min(curr)\n s = curr.index(minh)\n e = s\n while e + 1 < m and curr[e + 1] == minh:\n e += 1\n for i in range(min(e - s + 1, n - minh), 0, -1):\n nxt = curr[:]\n for j in range(s, s + i):\n nxt[j] += i\n nxt_state = tuple(nxt)\n if nxt_state in seen:\n continue\n if all((j == n for j in nxt)):\n return res + 1\n seen.add(nxt_state)\n dq.append(nxt)\n res += 1", "from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n\n def backtrack(state):\n if state in cache:\n return cache[state]\n if min(state) == n:\n return 0\n temp = state\n state = list(state)\n min_size = min(state)\n start = state.index(min_size)\n res = max_area\n for end in range(start, m):\n if state[end] != min_size:\n break\n size = end - start + 1\n if state[end] + size > n:\n break\n state[start:end + 1] = [min_size + size] * size\n res = min(res, backtrack(tuple(state)))\n cache[temp] = res + 1\n return cache[temp]\n max_area = m * n\n cache = {}\n if m > n:\n (m, n) = (n, m)\n return backtrack((0,) * m)", "def tilingrectangle(n: int, m: int) -> int:\n\n def helper(heights):\n mh = min(heights)\n if mh == n:\n return 0\n ret = float('inf')\n j = heights.index(mh)\n w = 1\n while mh + w <= n and j + w - 1 < m and (heights[j + w - 1] == mh):\n ret = min(ret, 1 + helper(heights[:j] + (mh + w,) * w + heights[j + w:]))\n w += 1\n return ret\n return helper((0,) * m)", "import functools\n\ndef tilingrectangle(n: int, m: int) -> int:\n\n def dfs(i, j):\n if i == j:\n return 1\n if i == 1:\n return j\n if j == 1:\n return i\n res = i * j\n for x in range(1, i // 2 + 1):\n res = min(res, dfs(x, j) + dfs(i - x, j))\n for y in range(1, j // 2 + 1):\n res = min(res, dfs(i, y) + dfs(i, j - y))\n for leng in range(1, min(x, y)):\n for x in range(1, i - leng):\n for y in range(1, j - leng):\n res = min(res, dfs(x + leng, y) + dfs(i - (x + leng), y + leng) + dfs(x, j - y) + dfs(i - x, j - (y + leng)) + 1)\n return res\n return dfs(m, n)", "def tilingrectangle(n: int, m: int) -> int:\n\n def dp(x=n, y=m):\n if x == y:\n return 1\n r = m * n\n for i in range(1, x // 2 + 1):\n r = min(r, dp(i, y) + dp(x - i, y))\n for k in range(1, y // 2 + 1):\n r = min(r, dp(x, k) + dp(x, y - k))\n for l in range(1, min(x, y)):\n for i in range(1, x - l):\n for k in range(1, y - l):\n p1 = dp(i + l, k)\n p2 = dp(x - i - l, l + k)\n p3 = dp(i, y - k)\n p4 = dp(x - i, y - k - l)\n r = min(r, p1 + p2 + p3 + p4 + 1)\n return r\n return dp()", "def tilingrectangle(n: int, m: int) -> int:\n (m, n) = (min(m, n), max(m, n))\n self.res = n * m\n self.H = n\n self.search(0, [0] * m)\n return self.res\n\ndef search(count, heights):\n if count >= self.res:\n return\n min_h = min(heights)\n if min_h == self.H:\n self.res = count\n return\n l = heights.index(min_h)\n width = 1\n while width <= self.H - min_h and l + width - 1 < len(heights) and (heights[l + width - 1] == heights[l]):\n width += 1\n width -= 1\n for w in range(width, 0, -1):\n self.search(count + 1, heights[:l] + [min_h + w] * w + heights[l + w:])", "def tilingrectangle(n: int, m: int) -> int:\n dp = [[sys.maxsize] * (m + 1) for _ in range(n + 1)]\n\n def getdp(n, m):\n if dp[n][m] != sys.maxsize:\n return dp[n][m]\n if n == 0 or m == 0:\n return 0\n if m == n:\n return 1\n if m == 1:\n return n\n if n == 1:\n return m\n ans = n * m\n for i in range(1, n // 2 + 1):\n ans = min(ans, getdp(i, m) + getdp(n - i, m))\n for i in range(1, m // 2 + 1):\n ans = min(ans, getdp(n, i) + getdp(n, m - i))\n for l in range(1, min(n, m) - 2):\n for i in range(2, n + 1 - l):\n for j in range(2, m + 1 - l):\n ans = min(ans, getdp(i + l - 1, j - 1) + getdp(i - 1, m - j + 1) + getdp(n - (i + l - 1), j + l - 1) + getdp(n - i + 1, m - (j + l - 1)) + 1)\n dp[n][m] = ans\n return ans\n return getdp(n, m)", "def tilingrectangle(n: int, m: int) -> int:\n self.best = m * n\n\n def dfs(heights, count):\n if min(heights) == n:\n self.best = min(self.best, count)\n return\n if count >= self.best:\n return\n min_height = min(heights)\n idx = heights.index(min_height)\n right_end = idx + 1\n while right_end < m and heights[right_end] == min_height:\n right_end += 1\n max_possible_box = min(right_end - idx, n - min_height)\n for box_size in range(max_possible_box, 0, -1):\n new_heights = heights[:]\n for i in range(box_size):\n new_heights[idx + i] += box_size\n dfs(new_heights, count + 1)\n dfs([0] * m, 0)\n return self.best", "def tilingrectangle(n: int, m: int) -> int:\n if n > m:\n return self.tilingrectangle(m, n)\n ans = n * m\n h = [0] * n\n\n def getmin(l):\n minv = 100000\n mini = -1\n for i in range(len(l)):\n if l[i] < minv:\n minv = l[i]\n mini = i\n return (minv, mini)\n\n def dfs(cur):\n nonlocal ans\n if cur >= ans:\n return\n (it, iti) = getmin(h)\n if it == m:\n ans = cur\n return\n low = it\n s = iti\n e = s\n while e < n and h[e] == h[s] and (e - s + 1 <= m - low):\n e += 1\n e -= 1\n for i in range(e, s - 1, -1):\n size = i - s + 1\n for j in range(s, i + 1):\n h[j] += size\n dfs(cur + 1)\n for j in range(s, i + 1):\n h[j] -= size\n dfs(0)\n return ans", "def tilingrectangle(n: int, m: int) -> int:\n self.best = m * n\n\n def dfs(height, moves):\n if all((h == n for h in height)):\n self.best = min(self.best, moves)\n return\n if moves >= self.best:\n return\n min_height = min(height)\n idx = height.index(min_height)\n ridx = idx + 1\n while ridx < m and height[ridx] == min_height:\n ridx += 1\n for i in range(min(ridx - idx, n - min_height), 0, -1):\n new_height = height[:]\n for j in range(i):\n new_height[idx + j] += i\n dfs(new_height, moves + 1)\n dfs([0] * m, 0)\n return self.best", "def tilingrectangle(m: int, n: int) -> int:\n self.ans = m * n\n\n def helper(h, res):\n if all((x == m for x in h)):\n self.ans = min(self.ans, res)\n return\n if res >= self.ans:\n return\n temp = min(h)\n ind = h.index(temp)\n r = ind + 1\n while r < min(n, ind + m - temp + 1) and h[r] == temp:\n r += 1\n for i in range(min(r - ind, m - temp), 0, -1):\n new_h = h[:]\n for j in range(ind, ind + i):\n new_h[j] += i\n helper(new_h, res + 1)\n helper([0] * n, 0)\n return self.ans", "def tilingrectangle(n: int, m: int) -> int:\n if n < m:\n return self.tilingrectangle(m, n)\n h = [0] * m\n self.ans = 100000\n self.dfs(n, m, h, 0)\n return self.ans\n\ndef dfs(m, n, h, cur):\n if cur >= self.ans:\n return\n min_h = min(h)\n if min_h == m:\n self.ans = min(self.ans, cur)\n return\n for j in range(n):\n if h[j] == min_h:\n break\n start = j\n while j + 1 < n and h[j] == h[j + 1] and (j + 1 - start + 1 + h[j] <= m):\n j += 1\n side = j - start + 1\n for k in reversed(range(1, side + 1)):\n temp = list(h)\n for j in range(start, start + k):\n temp[j] += k\n self.dfs(m, n, temp, cur + 1)", "def tilingrectangle(n: int, m: int) -> int:\n memo = {}\n return self.dfs(n, m, memo)\n\ndef dfs(x, y, memo):\n if x == 0 or y == 0:\n return 0\n if x == y:\n return 1\n if x == 1:\n return y\n if y == 1:\n return x\n if (x, y) in memo:\n return memo[x, y]\n ans = float('inf')\n for i in range(1, x):\n ans = min(ans, self.dfs(i, y, memo) + self.dfs(x - i, y, memo))\n for j in range(1, y):\n ans = min(ans, self.dfs(x, j, memo) + self.dfs(x, y - j, memo))\n for side in range(1, min(x, y)):\n for i in range(x - side):\n for j in range(y - side):\n ans1 = self.dfs(i, j + side, memo)\n ans2 = self.dfs(x - i, j, memo)\n ans3 = self.dfs(x - i - side, y - j, memo)\n ans4 = self.dfs(i + side, y - j - side, memo)\n ans = min(ans, ans1 + ans2 + ans3 + ans4 + 1)\n memo[x, y] = ans\n return memo[x, y]", "def tilingrectangle(n: int, m: int) -> int:\n self.result = n * m\n heights = [0] * n\n\n def dfs(cur):\n if cur >= self.result:\n return\n curMinHeight = min(heights)\n if curMinHeight == m:\n self.result = cur\n return\n end = start = heights.index(curMinHeight)\n while end < n and heights[start] == heights[end] and (end - start + 1 + curMinHeight <= m):\n end += 1\n for i in range(end - 1, start - 1, -1):\n size = i - start + 1\n for j in range(start, i + 1):\n heights[j] += size\n dfs(cur + 1)\n for j in range(start, i + 1):\n heights[j] -= size\n dfs(0)\n return self.result", "def tilingrectangle(n: int, m: int) -> int:\n if n < m:\n (n, m) = (m, n)\n if m == n:\n return 1\n heights = [0] * n\n dp = {}\n final = [m * n]\n\n def helper(heights, counts):\n key = tuple(heights)\n if counts >= final[0]:\n return\n if all((h == m for h in heights)):\n final[0] = min(final[0], counts)\n return\n if key in dp and dp[key] <= counts:\n return\n dp[key] = counts\n min_val = min(heights)\n idx = heights.index(min_val)\n d = 0\n for i in range(idx, n):\n if heights[i] == min_val:\n d += 1\n else:\n break\n d = min(m - min_val, d)\n for i in range(d, 0, -1):\n if heights[idx] + i <= m:\n helper(heights[:idx] + [heights[idx] + i] * i + heights[idx + i:], counts + 1)\n return\n helper(heights, 0)\n return final[0]", "def tilingrectangle(n: int, m: int) -> int:\n if m == n:\n return 1\n if n > m:\n (m, n) = (n, m)\n h_i = [0] * n\n visited = {}\n res = [m * n]\n\n def dfs(height, cnt):\n if cnt > res[0]:\n return\n status = tuple(height)\n if status in visited and visited[status] <= cnt:\n return\n visited[status] = cnt\n complete = True\n start_j = -1\n lowest_h = m + 1\n for j in range(n):\n if height[j] < m:\n complete = False\n if height[j] < lowest_h:\n start_j = j\n lowest_h = height[j]\n if complete:\n res[0] = min(res[0], cnt)\n return\n j = start_j\n while j < n and height[j] == lowest_h:\n j += 1\n max_l = min(j - start_j, m - lowest_h)\n for l in range(max_l, 0, -1):\n next_h = list(height)\n for k in range(l):\n next_h[start_j + k] += l\n dfs(next_h, cnt + 1)\n dfs(h_i, 0)\n return res[0]", "def tilingrectangle(n: int, m: int) -> int:\n if n > m:\n (n, m) = (m, n)\n res = n * m\n\n def dfs(heights, count, rem_area):\n nonlocal res\n if count >= res:\n return\n (lowest_idx, lowest_height, width, prev) = (-1, math.inf, 0, -1)\n for i in range(m):\n if heights[i] < lowest_height:\n (lowest_height, lowest_idx, width, prev) = (heights[i], i, 1, i)\n elif heights[i] == lowest_height and prev == i - 1:\n (width, prev) = (width + 1, i)\n if rem_area == 0:\n res = min(res, count)\n return\n width = min(width, n - lowest_height)\n for w in range(width, 0, -1):\n temp = heights.copy()\n for j in range(lowest_idx, lowest_idx + w):\n temp[j] += w\n dfs(temp, count + 1, rem_area - w * w)\n dfs([0] * m, 0, n * m)\n return res", "def tilingrectangle(n: int, m: int) -> int:\n self.res = n * m\n\n def dfs(heights, moves):\n if min(heights) == m:\n self.res = min(self.res, moves)\n return\n if moves == self.res:\n return\n minh = min(heights)\n left = right = heights.index(minh)\n while right < n and heights[right] == minh:\n right += 1\n for size in range(min(m - minh, right - left), 0, -1):\n newh = heights[:]\n for i in range(size):\n newh[left + i] += size\n dfs(newh, moves + 1)\n dfs([0] * n, 0)\n return self.res", "def tilingrectangle(n: int, m: int) -> int:\n self.best = n * m\n\n def dfs(hts, mvs):\n if mvs >= self.best:\n return\n if all((h == n for h in hts)):\n self.best = min(self.best, mvs)\n return\n i = min(list(range(m)), key=lambda i: hts[i])\n j = i + ([hts[k] != hts[i] for k in range(i, m)] + [True]).index(True)\n for x in range(min(j - i, n - hts[i]), 0, -1):\n for k in range(x):\n hts[i + k] += x\n dfs(hts, mvs + 1)\n for k in range(x):\n hts[i + k] -= x\n dfs([0] * m, 0)\n return self.best", "def tilingrectangle(m, n):\n self.best = n * m\n\n def dfs(heights, mvs):\n if mvs >= self.best:\n return\n if all((h == n for h in heights)):\n self.best = min(self.best, mvs)\n return\n i = j = min(list(range(m)), key=lambda i: heights[i])\n while j < m and heights[j] == heights[i]:\n j += 1\n for x in range(min(j - i, n - heights[i]), 0, -1):\n dfs(heights[:i] + [heights[i] + x] * x + heights[i + x:], mvs + 1)\n heights = [0] * m\n dfs(heights, 0)\n return self.best", "def tilingrectangle(n: int, m: int) -> int:\n if m == n:\n return 1\n if n < m:\n (m, n) = (n, m)\n if m == 1:\n return n\n if m == 2:\n (k, rem) = divmod(n, 2)\n return k + 2 * rem\n\n def recurse(h, ct):\n nonlocal Min\n if ct >= Min:\n return\n if all((x == m for x in h)):\n Min = min(Min, ct)\n return\n i = j = min(list(range(n)), key=lambda c: h[c])\n hi = h[i]\n bound = min(n, i + m - hi)\n while j < bound and h[j] == hi:\n j += 1\n for x in range(j - i, 0, -1):\n recurse(h[:i] + [hi + x] * x + h[i + x:], ct + 1)\n Min = m * n\n recurse([0] * n, 0)\n return Min", "def tilingrectangle(n: int, m: int) -> int:\n self.result = n * m\n\n def dfs(heights, moves):\n if moves > self.result:\n return\n if all((h == n for h in heights)):\n self.result = min(self.result, moves)\n return\n min_height = min(heights)\n idx = heights.index(min_height)\n right_boundary = idx + 1\n while right_boundary < m and heights[right_boundary] == min_height:\n right_boundary += 1\n for i in range(min(right_boundary - idx, n - min_height), 0, -1):\n dfs(heights[:idx] + [min_height + i] * i + heights[idx + i:], moves + 1)\n dfs([0] * m, 0)\n return self.result", "def tilingrectangle(n: int, m: int):\n cache = [[-1 for i in range(m + 1)] for j in range(n + 1)]\n return self.helper(n, m, cache)\n\ndef helper(n: int, m: int, cache) -> int:\n if n <= 0 or m <= 0:\n return 0\n if n == 11 and m == 13 or (n == 13 and m == 11):\n return 6\n if n == m:\n return 1\n if cache[n][m] != -1:\n return cache[n][m]\n rr1 = 10000\n rr2 = 10000\n _min = 10000\n for x in range(1, min(n, m) + 1):\n rr1 = self.helper(n, m - x, cache) + self.helper(n - x, x, cache)\n rr2 = self.helper(n - x, m, cache) + self.helper(x, m - x, cache)\n _min = min(rr1, min(rr2, _min))\n cache[n][m] = _min + 1\n return _min + 1", "def tilingrectangle(n: int, m: int) -> int:\n if n == m:\n return 1\n if n > m:\n (n, m) = (m, n)\n layers0 = [0 for _ in range(n)]\n visited = {}\n ans = [n * m]\n\n def dfs(layers, stepsNow):\n if stepsNow > ans[0]:\n return\n key = tuple(layers)\n if key in visited and stepsNow >= visited[key]:\n return\n visited[key] = stepsNow\n minH = m + 1\n i0 = -1\n for (i, h) in enumerate(layers):\n if h < minH:\n minH = h\n i0 = i\n if minH == m:\n ans[0] = min(ans[0], stepsNow)\n return\n minHWidth = 0\n maxL = m - minH\n for i in range(i0, n):\n if layers[i] == minH:\n minHWidth += 1\n else:\n break\n maxL = min(maxL, minHWidth)\n for l in range(maxL, 0, -1):\n nextLayers = list(key)\n for i in range(i0, i0 + l):\n nextLayers[i] += l\n dfs(nextLayers, stepsNow + 1)\n return\n dfs(layers0, 0)\n return ans[0]", "def tilingrectangle(n: int, m: int) -> int:\n h = [0] * m\n self.ans = m * n\n\n def dfs(h: List[int], cur: int) -> None:\n min_h = min(h)\n if min_h == n:\n self.ans = min(self.ans, cur)\n return\n if cur > self.ans:\n return\n idx = h.index(min_h)\n j = idx\n while j < len(h) and h[j] == min_h:\n j += 1\n fill_width = j - idx\n fill_height = n - min_h\n for fill in range(min(fill_width, fill_height), 0, -1):\n for k in range(idx, idx + fill):\n h[k] += fill\n dfs(h, cur + 1)\n for k in range(idx, idx + fill):\n h[k] -= fill\n dfs(h, 0)\n return self.ans", "def tilingrectangle(n: int, m: int) -> int:\n s = {}\n\n def dfs(n, m, h, cnt):\n if cnt > self.res:\n return\n is_full = True\n pos = -1\n minh = float('inf')\n for i in range(1, n + 1):\n if h[i] < m:\n is_full = False\n if h[i] < minh:\n pos = i\n minh = h[i]\n if is_full:\n self.res = min(cnt, self.res)\n return\n key = 0\n base = m + 1\n for i in range(1, n + 1):\n key += h[i] * base\n base *= m + 1\n if key in s and s[key] <= cnt:\n return\n s[key] = cnt\n end = pos\n while end < n and h[end + 1] == h[pos] and (end + 1 - pos + 1 + minh <= m):\n end += 1\n for j in range(end, pos - 1, -1):\n curh = j - pos + 1\n nex = h[:]\n for k in range(pos, j + 1):\n nex[k] += curh\n dfs(n, m, nex, cnt + 1)\n if n == m:\n return 1\n if n > m:\n (n, m) = (m, n)\n dfs(n, m, [0] * (n + 1), 0)\n return self.res", "from collections import defaultdict\n\ndef tilingrectangle(n: int, m: int) -> int:\n row = tuple([m] * n)\n\n def valid(row, i, side):\n return i + side <= len(row) and all((h >= side for h in row[i:i + side]))\n dp = defaultdict(int)\n\n def count(row, i):\n if i >= len(row):\n return 0\n if row in dp:\n return dp[row]\n res = float('inf')\n side = 1\n while valid(row, i, side):\n nrow = list(row)\n for j in range(i, i + side):\n nrow[j] -= side\n ni = i\n while ni < len(row) and (not nrow[ni]):\n ni += 1\n res = min(res, 1 + count(tuple(nrow), ni))\n side += 1\n dp[row] = res\n return res\n return count(row, 0)", "def tilingrectangle(n: int, m: int) -> int:\n ans = math.inf\n matrix = [[0] * m for _ in range(n)]\n\n def dfs(r, c, count):\n nonlocal ans\n if count >= ans:\n return\n if r >= n:\n ans = count\n return\n if c >= m:\n dfs(r + 1, 0, count)\n return\n if matrix[r][c]:\n dfs(r, c + 1, count)\n return\n for i in range(min(n - r, m - c), 0, -1):\n if not check(r, c, i):\n break\n cover(r, c, i)\n dfs(r, c + i, count + 1)\n uncover(r, c, i)\n\n def check(r, c, k):\n return all((matrix[i][j] == 0 for i in range(r, r + k) for j in range(c, c + k)))\n\n def cover(r, c, k):\n for i in range(r, r + k):\n for j in range(c, c + k):\n matrix[i][j] = 1\n\n def uncover(r, c, k):\n for i in range(r, r + k):\n for j in range(c, c + k):\n matrix[i][j] = 0\n dfs(0, 0, 0)\n return ans", "def tilingrectangle(n: int, m: int) -> int:\n memo = {}\n\n def helper(w, h):\n if w > h:\n (w, h) = (h, w)\n if (w, h) not in memo:\n if w == h:\n ans = 1\n elif w == 1:\n ans = h\n elif w == 0:\n ans = 0\n else:\n ans = w * h\n for iw in range(1, w // 2 + 1):\n ans = min(ans, helper(iw, h) + helper(w - iw, h))\n for ih in range(1, h // 2 + 1):\n ans = min(ans, helper(w, ih) + helper(w, h - ih))\n for iw in range(1, (w + 1) // 2):\n for ih in range(1, (h + 1) // 2):\n for s in range(1, min(w - 2 * iw, h - 2 * ih) + 1):\n ans = min(ans, 1 + helper(iw + s, ih) + helper(w - iw - s, ih + s) + helper(w - iw, h - ih - s) + helper(iw, h - ih))\n memo[w, h] = ans\n return memo[w, h]\n return helper(n, m)", "def tilingrectangle(n: int, m: int) -> int:\n if n > m:\n self.tilingrectangle(m, n)\n self.ans = n * m\n h = [0] * n\n self.dfs(h, 0, n, m)\n return self.ans\n\ndef dfs(h, cur, n, m):\n if cur >= self.ans:\n return\n min_h = min(h)\n if min_h == m:\n self.ans = cur\n return\n for i in range(n):\n if h[i] == min_h:\n break\n (start, end) = (i, i)\n while end < n and h[start] == h[end] and (end - start + 1 + min_h <= m):\n end += 1\n for i in reversed(list(range(start, end))):\n size = i - start + 1\n for j in range(start, i + 1):\n h[j] += size\n self.dfs(h, cur + 1, n, m)\n for j in range(start, i + 1):\n h[j] -= size", "def tilingrectangle(n: int, m: int) -> int:\n from functools import lru_cache\n\n def dp(n, m):\n (p, q) = (min(n, m), max(n, m))\n if p == 0:\n return 0\n if p == 1:\n return q\n if q % p == 0:\n return q // p\n minunits = p * q\n for r in range(1, p):\n minunits = min(minunits, 1 + dp(p - r, r) + dp(p, q - r))\n minunits = min(minunits, 1 + dp(q - r, r) + dp(q, p - r))\n for cl in range(1, n):\n for cr in range(1, n - cl):\n for rl in range(1, m):\n for rr in range(1, m - rl):\n minunits = min(minunits, dp(rl, n - cr) + dp(m - rl, cl) + dp(n - cl, rr) + dp(m - rr, cr) + dp(n - cl - cr, m - rl - rr))\n return minunits\n return dp(n, m)", "def tilingrectangle(n: int, m: int) -> int:\n if n > m:\n (n, m) = (m, n)\n if m == n:\n return 1\n res = [m * n]\n dp = {}\n\n def dfs(cnt, hs):\n if cnt > res[0]:\n return\n key = tuple(hs)\n if key in dp and dp[key] <= cnt:\n return\n dp[key] = cnt\n if all((h == n for h in hs)):\n res[0] = min(res[0], cnt)\n return\n min_h = min(hs)\n min_i = hs.index(min_h)\n r = m\n for i in range(min_i, m):\n if hs[i] > min_h:\n r = i\n break\n for side in range(min(r - min_i, n - min_h), 0, -1):\n dfs(cnt + 1, hs[:min_i] + [side + min_h] * side + hs[min_i + side:])\n dfs(0, [0] * m)\n return res[0]", "from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n (n, m) = (min(n, m), max(n, m))\n if m == n:\n return 1\n if m % n == 0:\n return m // n\n s1 = m * n\n for x in range(1, m // 2 + 1):\n s1 = min(s1, self.tilingrectangle(n, x) + self.tilingrectangle(n, m - x))\n for y in range(1, n // 2 + 1):\n s1 = min(s1, self.tilingrectangle(y, m) + self.tilingrectangle(n - y, m))\n s2 = m * n\n for xL in range(1, m // 2 + 1):\n for xR in range(1, m - xL):\n for yL in range(1, n // 2 + 1):\n for yR in range(1, n - yL):\n s2 = min(s2, self.tilingrectangle(n - yR, xL) + self.tilingrectangle(yL, m - xL) + self.tilingrectangle(n - yL, xR) + self.tilingrectangle(yR, m - xR) + self.tilingrectangle(n - yL - yR, m - xL - xR))\n return min(s1, s2)", "def tilingrectangle(n: int, m: int) -> int:\n if m > n:\n (n, m) = (m, n)\n (res, state) = (m * n, [0] * n)\n\n def dfs(count):\n nonlocal res\n if count > res:\n return\n min_h = min(state)\n if min_h == m:\n res = min(res, count)\n return\n e = s = state.index(min_h)\n while e < n and state[e] == min_h:\n e += 1\n max_len = min(e - s, m - min_h)\n for l in range(max_len, 0, -1):\n for i in range(s, s + l):\n state[i] += l\n dfs(count + 1)\n for i in range(s, s + l):\n state[i] -= l\n dfs(0)\n return res", "def tilingrectangle(R, C):\n A = [[0] * C for _ in range(R)]\n self.ans = R * C\n\n def search(r, c, steps):\n if steps >= self.ans:\n return\n if r == R:\n self.ans = steps\n return\n if c == C:\n return search(r + 1, 0, steps)\n if A[r][c]:\n return search(r, c + 1, steps)\n for k in range(min(R - r, C - c), 0, -1):\n bad = False\n for r0 in range(r, r + k):\n for c0 in range(c, c + k):\n if A[r0][c0]:\n bad = True\n break\n if bad:\n break\n if not bad:\n for r0 in range(r, r + k):\n for c0 in range(c, c + k):\n A[r0][c0] = 1\n search(r, c + 1, steps + 1)\n for r0 in range(r, r + k):\n for c0 in range(c, c + k):\n A[r0][c0] = 0\n search(0, 0, 0)\n return self.ans", "def tilingrectangle(n: int, m: int) -> int:\n self.res = math.inf\n grid = [[False] * n for _ in range(m)]\n\n def dfs(i, j, s):\n if s >= self.res:\n return\n elif i == m:\n self.res = s\n elif j == n:\n dfs(i + 1, 0, s)\n elif grid[i][j]:\n dfs(i, j + 1, s)\n else:\n side = min(m - i, n - j)\n while side:\n if not any((grid[ni][nj] for ni in range(i, i + side) for nj in range(j, j + side))):\n for ni in range(i, i + side):\n for nj in range(j, j + side):\n grid[ni][nj] = True\n dfs(i, j + side, s + 1)\n for ni in range(i, i + side):\n for nj in range(j, j + side):\n grid[ni][nj] = False\n side -= 1\n dfs(0, 0, 0)\n return self.res", "from math import inf\n\ndef tilingrectangle(n: int, m: int) -> int:\n rec = [[False] * n for _ in range(m)]\n res = inf\n\n def is_avail(r, c, k):\n return all((not rec[i][j] for i in range(r, r + k) for j in range(c, c + k)))\n\n def update(r, c, k, val):\n for i in range(r, r + k):\n for j in range(c, c + k):\n rec[i][j] = val\n\n def dfs(r, c, cnt):\n nonlocal res\n if r == m:\n res = min(res, cnt)\n return\n if c == n:\n dfs(r + 1, 0, cnt)\n return\n if rec[r][c]:\n dfs(r, c + 1, cnt)\n return\n if cnt >= res:\n return\n max_tile = min(m - r, n - c)\n for k in range(max_tile, 0, -1):\n if is_avail(r, c, k):\n update(r, c, k, True)\n dfs(r, c + k, cnt + 1)\n update(r, c, k, False)\n dfs(0, 0, 0)\n return res", "def tilingrectangle(n: int, m: int) -> int:\n dp = {}\n if n < m:\n (m, n) = (n, m)\n if m == n:\n return 1\n res = [m * n + 1]\n\n def dfs(ys, cnt):\n key = tuple(ys)\n if key not in dp or cnt < dp[key]:\n dp[key] = cnt\n if dp[key] < cnt or cnt > res[0]:\n return\n if all((i == m for i in ys)):\n res[0] = min(res[0], cnt)\n return\n if any((i > m for i in ys)):\n return\n ymin = min(ys)\n idx = ys.index(ymin)\n ymax = 0\n for i in range(idx, n):\n if ys[i] > ymin:\n break\n else:\n ymax += 1\n ymax = min(ymax, m)\n for i in range(ymax, 0, -1):\n dfs(ys[:idx] + [ys[idx] + i] * i + ys[idx + i:], cnt + 1)\n dfs([0] * n, 0)\n return res[0]", "from functools import lru_cache\nimport numpy as np\n\ndef __init__():\n self.cache = {}\n self.res = np.inf\n\ndef tilingrectangle(n: int, m: int) -> int:\n\n def tilingrectangleCalc(state, cnt):\n if cnt > self.res:\n return\n state = list(state)\n minHeight = min(state)\n if minHeight == n:\n self.res = min(self.res, cnt)\n return\n minIdx = state.index(minHeight)\n maxL = 1\n while minIdx + maxL - 1 <= m - 1 and state[minIdx + maxL - 1] == minHeight:\n maxL += 1\n for l in range(maxL - 1, 0, -1):\n if minHeight + l > n:\n continue\n s = tuple(state[:minIdx] + [minHeight + l] * l + state[minIdx + l:])\n if s in self.cache and self.cache[s] < cnt + 1:\n continue\n self.cache[s] = cnt + 1\n tilingrectangleCalc(s, cnt + 1)\n return\n if m > n:\n (n, m) = (m, n)\n tilingrectangleCalc(tuple([0] * m), 0)\n return self.res", "def tilingrectangle(m: int, n: int) -> int:\n cur = [0] * (n * m)\n q = [cur]\n step = 0\n seen = {tuple(cur)}\n while q and step < n * m + 1:\n step += 1\n nex = []\n for cur in q:\n found = True\n for i in range(m):\n for j in range(n):\n if cur[i * n + j] == 0:\n start = [i, j]\n found = False\n break\n if not found:\n break\n if found:\n return step - 1\n while j + 1 < n and cur[i * n + j + 1] == 0:\n j += 1\n k = j - start[1] + 1\n for sz in range(1, k + 1):\n cc = cur.copy()\n flag = False\n for i in range(start[0], start[0] + sz):\n for j in range(start[1], start[1] + sz):\n if not (0 <= i < m and 0 <= j < n and (cur[i * n + j] == 0)):\n flag = True\n break\n cc[i * n + j] = 1\n if flag:\n break\n if flag:\n break\n C = tuple(cc)\n if C not in seen:\n seen.add(C)\n nex.append(cc)\n q = nex", "def tilingrectangle(n: int, m: int) -> int:\n self.n = n\n self.m = m\n board = [[0] * n for _ in range(m)]\n self.res = float('inf')\n self.dfs(board, 0)\n return self.res\n\ndef dfs(board, count):\n if count >= self.res:\n return\n (i, j) = self.find_next(board)\n if i == -1 and j == -1:\n self.res = min(self.res, count)\n return\n max_length = self.find_max_length(board, i, j)\n for k in range(1, max_length + 1)[::-1]:\n self.assign(board, i, j, k, 1)\n self.dfs(board, count + 1)\n self.assign(board, i, j, k, 0)\n\ndef assign(board, i, j, length, val):\n for row in range(i, i + length):\n for col in range(j, j + length):\n board[row][col] = val\n\ndef find_max_length(board, i, j):\n max_length = 1\n while i + max_length - 1 < self.m and j + max_length - 1 < self.n:\n for row in range(i, i + max_length):\n if board[row][j + max_length - 1] != 0:\n return max_length - 1\n for col in range(j, j + max_length):\n if board[i + max_length - 1][col] != 0:\n return max_length - 1\n max_length += 1\n return max_length - 1\n\ndef find_next(board):\n for i in range(self.m):\n for j in range(self.n):\n if board[i][j] == 0:\n return (i, j)\n return (-1, -1)", "import math\n\ndef tilingrectangle(n: int, m: int) -> int:\n grid = [[0 for _ in range(m)] for _ in range(n)]\n\n def try_place(i: int, j: int, l: int) -> bool:\n ok = True\n (xb, yb) = (None, None)\n for x in range(i, i + l):\n for y in range(j, j + l):\n if grid[x][y] == 1:\n ok = False\n (xb, yb) = (x, y)\n break\n grid[x][y] = 1\n if not ok:\n break\n if not ok:\n done = False\n for x in range(i, i + l):\n for y in range(j, j + l):\n if (x, y) == (xb, yb):\n done = True\n break\n grid[x][y] = 0\n if done:\n break\n return ok\n\n def un_place(i: int, j: int, l: int):\n for x in range(i, i + l):\n for y in range(j, j + l):\n grid[x][y] = 0\n\n def search(i: int, j: int, sofar: int, ans: list):\n if sofar >= ans[0]:\n return\n if j == m:\n ans[0] = min(ans[0], sofar)\n return\n if i == n:\n search(0, j + 1, sofar, ans)\n return\n if grid[i][j] == 1:\n search(i + 1, j, sofar, ans)\n return\n for l in reversed(range(1, min(n - i + 1, m - j + 1))):\n if try_place(i, j, l):\n search(i + 1, j, sofar + 1, ans)\n un_place(i, j, l)\n if len(grid) == len(grid[0]):\n return 1\n ans = [math.inf]\n search(0, 0, 0, ans)\n return ans[0]", "def tilingrectangle(n: int, m: int) -> int:\n self.best = m * n\n height = [0] * m\n\n def dfs(moves):\n if all((h == n for h in height)):\n self.best = min(self.best, moves)\n return\n if moves >= self.best:\n return\n idx = height.index(min(height))\n for i in range(min(m - idx, n - height[idx]), 0, -1):\n for j in range(i):\n height[idx + j] += i\n dfs(moves + 1)\n for j in range(i):\n height[idx + j] -= i\n dfs(0)\n return self.best", "def tilingrectangle(n: int, m: int) -> int:\n self.ans = n * m\n\n def helper(heights, moves):\n if all((height == n for height in heights)):\n self.ans = min(self.ans, moves)\n return None\n if moves >= self.ans:\n return None\n min_height = min(heights)\n min_height_idx = heights.index(min_height)\n right_idx = min_height_idx + 1\n while right_idx < m and heights[right_idx] == min_height:\n right_idx += 1\n for idx in range(min(n - min_height, right_idx - min_height_idx), -1, -1):\n new_heights = heights[:]\n for next_idx in range(idx):\n new_heights[min_height_idx + next_idx] += idx\n helper(new_heights, moves + 1)\n helper([0] * m, 0)\n return self.ans", "def tilingrectangle(n: int, m: int) -> int:\n if n == m:\n return 1\n if m > n:\n (m, n) = (n, m)\n\n def helper(skyline):\n if all((h == n for h in skyline)):\n return 0\n ans = float('inf')\n minh = min(skyline)\n l = skyline.index(minh)\n for r in range(l, m):\n if skyline[r] != minh:\n break\n if r - l + 1 > n - minh:\n break\n newsl = list(skyline)\n for i in range(l, r + 1):\n newsl[i] += r - l + 1\n ans = min(ans, helper(tuple(newsl)))\n return ans + 1\n ans = helper(tuple([0] * m))\n return ans", "def findSum(n, m, k):\n res = []\n s = m * n\n hi = min(n, m)\n border = max(n, m)\n path = [1] * k\n while path[0] <= hi:\n i = k - 1\n while i >= 0 and path[i] >= hi:\n i -= 1\n if i == -1 or path[i] >= hi:\n return res\n path[i] += 1\n path[i + 1:] = [path[i]] * (k - i - 1)\n if path[k - 1] + path[k - 2] > border:\n path[i:] = [hi] * (k - i)\n continue\n if sum((x * x for x in path)) == s:\n x = path[:]\n x.reverse()\n res.append(x)\n return res\n\ndef hasNoOverLap(x1, y1, s1, x2, y2, s2):\n if x1 + s1 - 1 < x2 or y1 + s1 - 1 < y2 or x2 + s2 - 1 < x1 or (y2 + s2 - 1 < y1):\n return True\n else:\n return False\n\ndef nextPos(placement, n, m, size):\n if not placement:\n return (0, 0)\n for i in range(n - size + 1):\n for j in range(m - size + 1):\n if all((self.hasNoOverLap(i, j, size, x, y, z) for (x, y, z) in placement)):\n return (i, j)\n return (-1, -1)\n\ndef canPlace(sizes, n, m, placement, memo):\n if len(sizes) == 0:\n return True\n h = tuple(placement)\n if h in memo:\n return memo[h]\n for (k, s) in enumerate(sizes):\n (i, j) = self.nextPos(placement, n, m, s)\n if i == -1:\n continue\n placement.append((i, j, s))\n if self.canPlace(sizes[:k] + sizes[k + 1:], n, m, placement, memo):\n memo[h] = True\n return True\n placement.pop()\n memo[h] = False\n return False\n\ndef tilingrectangle(n: int, m: int) -> int:\n if n % m == 0:\n return n // m\n if m % n == 0:\n return m // n\n for i in range(3, 10):\n res = self.findSum(n, m, i)\n if any((self.canPlace(sizes, n, m, [], {}) for sizes in res)):\n return i", "from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n\n def dfs(x, y):\n if x == y:\n return 1\n if x == 1:\n return y\n if y == 1:\n return x\n result = x * y\n for i in range(1, x // 2 + 1):\n left = dfs(i, y)\n right = dfs(x - i, y)\n result = min(result, left + right)\n for k in range(1, y // 2 + 1):\n bottom = dfs(x, k)\n top = dfs(x, y - k)\n result = min(result, bottom + top)\n for size in range(1, min(x, y)):\n for i in range(1, x - size):\n for k in range(1, y - size):\n partition1 = dfs(i + size, k)\n partition2 = dfs(x - size - i, k + size)\n partition3 = dfs(x - i, y - size - k)\n partition4 = dfs(i, y - k)\n partition5 = 1\n curr_result = partition1 + partition2 + partition3 + partition4 + partition5\n result = min(result, curr_result)\n return result\n return dfs(n, m)", "def tilingrectangle(n: int, m: int) -> int:\n\n def dp(state):\n if state in cache:\n return cache[state]\n if state[::-1] in cache:\n return cache[state[::-1]]\n tmp = state\n if min(state) == n:\n return 0\n state = list(state)\n min_s = min(state)\n start = state.index(min_s)\n res = n\n for end in range(start, m):\n if state[end] != min_s:\n break\n side = end - start + 1\n if min_s + side > n:\n break\n state[start:end + 1] = [min_s + side] * side\n res = min(res, dp(tuple(state)))\n cache[tmp] = res + 1\n return res + 1\n if m > n:\n (m, n) = (n, m)\n cache = dict()\n return dp(tuple([0] * m))", "from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n INF = m * n\n cache = {}\n\n def dp(state):\n if state in cache:\n return cache[state]\n if state[::-1] in cache:\n return cache[state[::-1]]\n temp = state\n if n == min(state):\n return 0\n state = list(state)\n mn = min(state)\n start = state.index(mn)\n res = INF\n for end in range(start, m):\n if state[end] != mn:\n break\n side = end - start + 1\n if mn + side > n:\n break\n state[start:end + 1] = [mn + side] * side\n res = min(res, dp(tuple(state)))\n cache[temp] = res + 1\n return res + 1\n if m > n:\n (m, n) = (n, m)\n if (m, n) == (11, 13):\n return 6\n return dp(tuple([0] * m))", "def tilingrectangle(n: int, m: int) -> int:\n self.best = n * m\n\n def dp(heights, n_square):\n if n_square > self.best:\n return\n if heights == [n] * m:\n self.best = min(self.best, n_square)\n min_index = min(range(m), key=lambda x: heights[x])\n (i, j) = (min_index, min_index)\n while j < m and heights[i] == heights[j]:\n j += 1\n max_line = min(j - i + int(j == m), n - heights[i])\n result = float('inf')\n for x in range(max_line, 0, -1):\n cur = dp(heights[:i] + [heights[i] + x] * x + heights[i + x:], n_square + 1)\n if cur:\n result = min(result, cur)\n return result\n dp([0] * m, 0)\n return self.best"], "starter_code": "def tilingrectangle(n: int, m: int) -> int:\n", "input_output": {"fn_name": "tilingRectangle", "inputs": [[2, 3]], "outputs": [3]}, "difficulty": "MEDIUM", "raw_tags": ["Backtracking", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Complete search"], "skill_types": ["Dynamic programming", "Complete search"], "url": "https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "tilingrectangle", "task_id": "TACO_lite/87", "example": [[[2, 3], [5, 8], [11, 13]], ["3", "5", "6"]]} +{"requirement": "Consider a sample space S consisting of all perfect squares starting from 1, 4, 9 and so on. You are given a number N, you have to output the number of integers less than N in the sample space S.\n \nExample 1:\nInput :\nN = 9\nOutput:\n2\nExplanation:\n1 and 4 are the only Perfect Squares\nless than 9. So, the Output is 2.\nExample 2:\nInput :\nN = 3\nOutput:\n1\nExplanation:\n1 is the only Perfect Square\nless than 3. So, the Output is 1.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function countSquares() which takes an Integer N as input and returns the answer.\n \nExpected Time Complexity: O(sqrt(N))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= N <= 10^{8}", "solutions": ["import math\n\ndef countsquares(N):\n s = math.sqrt(N)\n if N == 0 or N == 1:\n return 0\n elif N < 0:\n return 0\n elif N == int(s) ** 2 and N % int(s) == 0:\n return int(s) - 1\n else:\n return int(s) + 1 - 1", "import math\n\ndef countsquares(N):\n count = int(math.sqrt(N - 1))\n return count", "def countsquares(N):\n return int((N - 1) ** 0.5)", "def countsquares(N):\n if N == int(N ** 0.5) ** 2:\n return int(N ** 0.5) - 1\n return int(N ** 0.5)", "def countsquares(N):\n return int(math.sqrt(N - 1))", "def countsquares(N):\n a = math.sqrt(N - 1)\n b = int(a)\n return b", "def countsquares(n):\n return int(math.sqrt(n - 1))", "import math\n\ndef countsquares(N):\n r = math.sqrt(N)\n if r.is_integer():\n return int(r - 1)\n else:\n return int(r)", "import math\n\ndef countsquares(N):\n m = 0\n m = math.sqrt(N)\n N = int(math.sqrt(N))\n if m - N == 0:\n return N - 1\n else:\n return N", "import math\n\ndef countsquares(N):\n if N == int(math.sqrt(N)) ** 2:\n return int(N ** 0.5) - 1\n return int(N ** 0.5)", "import math\n\ndef countsquares(N):\n return math.floor(math.sqrt(N - 1))", "def countsquares(N):\n (l, r) = (1, N)\n res = 1\n while l <= r:\n mid = (l + r) // 2\n if mid * mid == N:\n return mid - 1\n elif mid * mid <= N:\n res = mid\n l = mid + 1\n else:\n r = mid - 1\n return res", "import math\n\ndef countsquares(n):\n return math.floor(math.sqrt(n - 1))", "import math\n\ndef countsquares(N):\n count = 0\n count = math.floor(math.sqrt(N))\n if count * count == N:\n return count - 1\n else:\n return count", "def countsquares(N):\n import math\n if int(N) == int(math.sqrt(N)) ** 2:\n return len(range(1, round(math.sqrt(N))))\n return int(math.sqrt(N))", "def countsquares(N):\n a = N ** 0.5\n b = math.ceil(a)\n return b - 1", "def countsquares(N):\n c = 0\n d = int(N ** (1 / 2))\n if d * d == N:\n return d - 1\n return d", "import math\n\ndef countsquares(N):\n n = N ** 0.5\n if n - int(n) == 0:\n return int(n - 1)\n else:\n return int(n)", "def countsquares(N):\n k = int(math.sqrt(N))\n if k * k == N:\n return k - 1\n else:\n return int(k)", "def countsquares(N):\n (start, end) = (0, N - 1)\n root = -1\n while start <= end:\n mid = start + (end - start) // 2\n if mid ** 1 * mid < N ** 1:\n root = mid\n start = mid + 1\n else:\n end = mid - 1\n return root", "import math\n\ndef countsquares(N):\n return int((N - 1) ** 0.5)", "import math\n\ndef countsquares(N):\n res = math.ceil(math.sqrt(N))\n return res - 1", "from math import sqrt, ceil\n\ndef countsquares(N):\n ans = ceil(sqrt(N))\n return ans - 1", "def countsquares(N):\n return int(math.sqrt(N - 1))\n count = 0\n for i in range(1, int(math.sqrt(N) + 1)):\n if i * i < N:\n count += 1\n return count", "def countsquares(N):\n n = N ** (1 / 2)\n if n > int(n):\n return int(n)\n else:\n return int(n) - 1", "def countsquares(N):\n n = N ** 0.5\n return math.ceil(n) - 1", "def countsquares(N):\n return int((N - 1) ** (1 / 2))", "def countsquares(N):\n N = N - 1\n r = N ** (1 / 2)\n k = int(r)\n if N == 0:\n return 0\n else:\n return k", "import math\n\ndef countsquares(n):\n square_root = int(math.sqrt(n))\n if square_root * square_root == n:\n return square_root - 1\n return square_root", "def countsquares(N):\n import math\n ans = math.sqrt(N)\n ans1 = int(ans)\n if ans - ans1 == 0:\n return ans1 - 1\n else:\n return ans1", "def countsquares(N):\n return math.ceil(math.sqrt(N)) - 1", "def countsquares(N):\n if N == 1:\n return 0\n l = 0\n h = N // 2\n while l <= h:\n m = (l + h) // 2\n if m * m > N:\n h = m - 1\n elif m * m == N:\n return m - 1\n elif (m + 1) * (m + 1) > N:\n return m\n else:\n l = m + 1", "def countsquares(N):\n val = N ** 0.5\n if val == int(val):\n return int(val) - 1\n else:\n return int(val)", "def countsquares(n):\n return math.ceil(math.sqrt(n)) - 1"], "starter_code": "def countsquares(N):\n", "input_output": {"inputs": ["N = 9", "N = 3"], "outputs": ["2", "1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/count-squares3649/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(sqrt(N))", "entry_point": "countsquares", "task_id": "TACO_lite/250", "example": [[[9], [3]], ["2", "1"]]} +{"requirement": "## Task\nYou need to implement two functions, `xor` and `or`, that replicate the behaviour of their respective operators:\n\n- `xor` = Takes 2 values and returns `true` if, and only if, one of them is truthy.\n- `or` = Takes 2 values and returns `true` if either one of them is truthy.\n\nWhen doing so, **you cannot use the or operator: `||`**.\n\n# Input\n- Not all input will be booleans - there will be truthy and falsey values [the latter including also empty strings and empty arrays]\n- There will always be 2 values provided\n\n## Examples\n- `xor(true, true)` should return `false`\n- `xor(false, true)` should return `true`\n- `or(true, false)` should return `true`\n- `or(false, false)` should return `false`", "solutions": ["def func_or(a, b):\n return not bool(a) == bool(b) == False\n\ndef func_xor(a, b):\n return not bool(a) == bool(b)", "def func_or(a, b):\n return bool(a) | bool(b)\n\ndef func_xor(a, b):\n return bool(a) ^ bool(b)", "def func_or(a, b):\n return bool(a) + bool(b) > 0\n\ndef func_xor(a, b):\n return bool(a) + bool(b) == 1", "def func_or(*a):\n return any(a)\n\ndef func_xor(*a):\n return any(a) and (not all(a))", "def func_or(a, b):\n return bool(a if a else b)\n\ndef func_xor(a, b):\n return bool(not b if a else b)", "def func_or(a, b):\n return False if not a and (not b) else True\n\ndef func_xor(a, b):\n return True if not a and b or (a and (not b)) else False", "def func_or(a, b):\n return bool(a) or bool(b)\n\ndef func_xor(a, b):\n return bool(a) is not bool(b)", "(func_or, func_xor) = (lambda a, b: bool(bool(a) + bool(b)), lambda a, b: bool(a) + bool(b) == 1)", "def func_or(a, b):\n if a:\n return True\n else:\n return not not b\n\ndef func_xor(a, b):\n if a:\n return not b\n else:\n return not not b"], "starter_code": "def func_or(a,b):\n", "input_output": {"fn_name": "func_or", "inputs": [[true, true], [true, false], [false, false], [0, 11], [null, []]], "outputs": [[true], [true], [false], [true], [false]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Logic"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/584d2c19766c2b2f6a00004f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "func_or", "task_id": "TACO_lite/198", "example": [[], []]} +{"requirement": "Given a number n, count the total number of digits required to write all numbers from 1 to n.\nExample 1:\nInput: n = 13\nOutput: 17 \nExplanation: There are total 17 \ndigits required to write all \nnumbers from 1 to 13.\nExample 2:\nInput: n = 4\nOutput: 4\nExplanation: There are total 4 \ndigits required to write all\nnumbers from 1 to 4.\nYour Task: \nYou dont need to read input or print anything. Complete the function totalDigits() which takes n as input parameter and returns the total number of digits required to write all numbers from 1 to n.\nExpected Time Complexity: O(logn)\nExpected Auxiliary Space: O(1)\nConstraints:\n1<= n <=100000", "solutions": ["def totaldigits(ob, n):\n if n < 10:\n return n\n else:\n number = 9\n for i in range(10, n + 1):\n i = str(i)\n number += len(i)\n return number", "def totaldigits(ob, n):\n st = ''\n for i in range(1, n + 1):\n st = st + str(i)\n return len(st)", "def totaldigits(ob, n):\n sm = 0\n for i in range(1, n + 1):\n sm += len(str(i))\n return sm", "def totaldigits(ob, n):\n import math\n r = 0\n for i in range(1, n + 1):\n r += int(math.log10(i)) + 1\n return r", "def totaldigits(ob, n):\n c = 0\n for i in range(1, n + 1):\n if i < 10:\n c = c + 1\n else:\n s = str(i)\n c = c + len(s)\n return c", "def totaldigits(ob, n):\n init = n\n ans = sub = 0\n while init - sub > 0:\n ans += init - sub\n sub = sub * 10 + 9\n return ans", "def totaldigits(ob, n):\n\n def cd(i):\n i = str(i)\n return len(i)\n ans = 0\n for i in range(1, n + 1):\n ans += cd(i)\n return ans", "def totaldigits(ob, n):\n c = 0\n i = 1\n while i <= n:\n c += n - i + 1\n i *= 10\n return c", "def totaldigits(ob, n):\n c = 0\n for i in range(1, n + 1):\n j = str(i)\n c += len(j)\n return c", "def totaldigits(ob, n):\n d = 0\n t = n\n while t > 0:\n d += 1\n t = t // 10\n x = 0\n while n > 0:\n x += d * (n + 1 - 10 ** (d - 1))\n n = 10 ** (d - 1) - 1\n d -= 1\n return x", "def lt(n):\n return len(str(n))\n\ndef ans(n, x):\n if n <= 9:\n x += n\n return x\n z = lt(n)\n if n - 1000 > 100 and z == lt(n - 1000):\n x += z * 1000\n return ans(n - 1000, x)\n elif n - 10 > 10 and z == lt(n - 10):\n x += z * 10\n return ans(n - 10, x)\n else:\n x += z\n return ans(n - 1, x)\n\ndef totaldigits(ob, n):\n return ans(n, 0)", "def ins(n):\n j = len(str(n))\n return j\n\ndef totaldigits(ob, n):\n s = 0\n for i in range(1, n + 1):\n s = s + ins(i)\n return s", "def totaldigits(ob, n):\n a = [1] * n\n for i in range(1, n):\n a[i] += i\n str1 = ''.join(map(str, a))\n return len(str1)", "import math\n\ndef totaldigits(ob, n):\n digits = 0\n for i in range(1, n + 1):\n digits += len(str(i))\n return digits", "def totaldigits(ob, n):\n m = n\n c = 0\n while n != 0:\n n //= 10\n c = c + 1\n if c == 1:\n return m\n elif c == 2:\n return 9 + 2 * (m - 9)\n elif c == 3:\n return 9 + 2 * 90 + 3 * (m - 99)\n elif c == 4:\n return 9 + 2 * 90 + 3 * 900 + 4 * (m - 999)\n elif c == 5:\n return 9 + 2 * 90 + 3 * 900 + 4 * 9000 + 5 * (m - 9999)\n elif c == 6:\n return 9 + 2 * 90 + 3 * 900 + 4 * 9000 + 5 * 90000 + 6 * (m - 99999)", "def totaldigits(ob, n):\n count = 0\n i = 9\n if n <= 9:\n return n\n else:\n count = n\n while n > i:\n count += n - i\n i = i * 10 + 9\n return count", "def totaldigits(ob, n):\n l = len(str(n))\n ans = 0\n decrease = 0\n while l:\n ans += n - decrease\n decrease = decrease * 10 + 9\n l -= 1\n return ans", "def totaldigits(ob, n):\n s = ''\n sum = 0\n for i in range(1, n + 1):\n s = str(i)\n sum = sum + len(s)\n return sum"], "starter_code": "def totaldigits (ob, n):\n", "input_output": {"inputs": ["n = 13", "n = 4"], "outputs": ["17", "4"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/total-digits4030/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(logn)", "entry_point": "totaldigits", "task_id": "TACO_lite/241", "example": [[[13], [4]], ["17", "4"]]} +{"requirement": "Given a range L to R, the task is to find the highest occurring digit in prime numbers which lie between L and R (both inclusive). If multiple digits have same highest frequency return the largest of them. If no prime number occurs between L and R, return -1.\n \nExample 1:\nInput: L = 2, R = 10\nOutput: 7\nExplanation: Between 2 and 10 every digit\nhas same frquency and 7 is largest among\nthem.\nExample 2:\nInput: L = 2, R = 20\nOutput: 1\nExplanation: Prime number between 2 and 20 are \n2, 3, 5, 7, 11, 13, 17, 19. 1 occur \nmaximum i.e 5 times among 0 to 9.\nYour Task: \nYou dont need to read input or print anything. Complete the function maxDigit() which takes L and R as input parameter and returns the highest occuring digit. If multiple digits have same highest frequency return the largest of them. If no prime number occurs between L and R, return -1.\nExpected Time Complexity: O(nlog(n)sqrt(n))\nExpected Auxiliary Space: O(k)\nConstraints:\n1 <= L<= R <= 1000", "solutions": ["def isprime(n):\n if n == 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef maxdigit(L, R):\n l = []\n for i in range(L, R + 1, 1):\n if self.isprime(i):\n c = i\n while c != 0:\n l.append(c % 10)\n c = c // 10\n l = sorted(l)\n a = 0\n b = 0\n for i in range(len(l) - 1, -1, -1):\n if l.count(l[i]) > a:\n a = l.count(l[i])\n b = l[i]\n if b == 0:\n return -1\n else:\n return b", "import math\n\ndef __init__():\n self.pl = self.primes()\n\ndef primes():\n n = int(1000.0)\n pl = [True] * (n + 1)\n pl[0] = pl[1] = False\n lim = int(math.sqrt(n)) + 1\n for i in range(2, lim):\n for j in range(i * i, n + 1, i):\n if pl[i]:\n pl[j] = False\n res = [i for i in range(2, n + 1) if pl[i]]\n return res\n\ndef bsf(arr, k):\n (l, h, idx) = (0, len(arr) - 1, -1)\n while l <= h:\n m = (l + h) // 2\n if arr[m] > k:\n h = m - 1\n else:\n idx = m\n l = m + 1\n return idx\n\ndef bsc(arr, k):\n (l, h, idx) = (0, len(arr) - 1, -1)\n while l <= h:\n m = (l + h) // 2\n if arr[m] < k:\n l = m + 1\n else:\n idx = m\n h = m - 1\n return idx\n\ndef maxdigit(L, R):\n x = self.bsc(self.pl, L)\n y = self.bsf(self.pl, R)\n d = {}\n for i in self.pl[x:y + 1]:\n while i != 0:\n if i % 10 in d:\n d[i % 10] += 1\n else:\n d[i % 10] = 1\n i = i // 10\n (me, m) = (-1, 0)\n for i in d:\n if d[i] >= m:\n (m, me) = (d[i], i)\n return me", "def maxdigit(M, N):\n product = 1\n mod = 10 ** 9 + 7\n table = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}\n for j in range(M, N + 1):\n flag = True\n if j == 1:\n continue\n for i in range(2, int(j ** 0.5) + 1):\n if j % i == 0:\n flag = False\n break\n if flag:\n while j != 0:\n p = j % 10\n table[p] += 1\n j = j // 10\n digit = -1\n maxi = 1\n for j in table:\n if table[j] >= maxi:\n maxi = table[j]\n digit = j\n return digit", "def maxdigit(L, R):\n from collections import Counter\n n = R\n sieve = [True] * (n + 1)\n rec = Counter()\n for i in range(2, n + 1):\n if sieve[i]:\n for j in range(i * i, n + 1, i):\n sieve[j] = False\n if i >= L:\n for x in str(i):\n rec[x] += 1\n if not rec:\n return -1\n maxi = max(rec.values())\n if maxi == 0:\n return -1\n ans = '0'\n for (k, v) in rec.items():\n if v == maxi:\n ans = max(ans, k)\n return ord(ans) - ord('0')", "import math\n\ndef maxdigit(L, R):\n sieve = [0 for i in range(100000)]\n (sieve[0], sieve[1]) = (1, 1)\n for i in range(2, int(math.sqrt(100000)) + 1):\n if sieve[i] == 0:\n for j in range(i * i, 100000, i):\n sieve[j] = 1\n d = {i: 0 for i in range(10)}\n for i in range(L, R + 1):\n if sieve[i] == 0:\n data = i\n while data != 0:\n d[data % 10] += 1\n data //= 10\n (maxkey, maxval) = (float('-inf'), float('-inf'))\n for (key, val) in d.items():\n if val >= maxval:\n maxkey = key\n maxval = val\n if maxval == 0:\n return -1\n return maxkey", "from math import sqrt\n\ndef maxdigit(L, R):\n res = [0] * 10\n for i in range(L, R + 1):\n if self.findprimes(i):\n num = i\n while num != 0:\n rem = num % 10\n res[rem] += 1\n num = num // 10\n maxcount = 0\n maxi = -1\n for j in range(9, -1, -1):\n if maxcount < res[j]:\n maxcount = res[j]\n maxi = j\n return maxi\n\ndef findprimes(N):\n if N <= 1:\n return 0\n for i in range(2, int(sqrt(N)) + 1):\n if N % i == 0:\n return 0\n return 1", "import math\n\ndef seive(n):\n primes = [True] * n\n primes[0] = primes[1] = False\n for i in range(4, n, 2):\n primes[i] = False\n x = int(math.sqrt(n)) + 1\n for i in range(3, x):\n for j in range(i * i, n, i):\n primes[j] = False\n ans = []\n for i in range(len(primes)):\n if primes[i]:\n ans.append(i)\n return ans\n\ndef maxdigit(l, r):\n n = int(math.sqrt(r)) + 1\n primes = self.seive(n)\n arr = [True] * (r - l + 1)\n if l == 1:\n arr[0] = False\n for p in primes:\n base = l // p * p\n if base < l:\n base += p\n for i in range(base, r + 1, p):\n if i != p:\n arr[i - l] = False\n mp = {}\n mx = -999999\n val = -1\n for i in range(r - l + 1):\n if arr[i]:\n num = i + l\n while num > 0:\n k = num % 10\n if k in mp:\n mp[k] += 1\n else:\n mp[k] = 1\n if mp[k] >= mx:\n mx = mp[k]\n val = k\n num = num // 10\n return val", "def maxdigit(L, R):\n if L == 1:\n L = 3\n x = []\n for i in range(L, R + 1):\n c = 0\n for j in range(2, int(i ** 0.5) + 1):\n if i % j == 0:\n c = 1\n break\n if c == 0:\n x.append(i)\n a = ''\n for i in x:\n a += str(i)\n d = {}\n for i in a:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n ans = 0\n count = 0\n for i in d:\n if d[i] == count:\n if i > ans:\n ans = i\n if d[i] > count:\n ans = i\n count = d[i]\n if ans == 0:\n return -1\n return ans", "def maxdigit(L, R):\n p = []\n q = []\n r = []\n m = 0\n c1 = 0\n c3 = 0\n c5 = 0\n c7 = 0\n c9 = 0\n if L == 1:\n L = 2\n for i in range(L, R + 1):\n for j in range(2, int(i / 2) + 1):\n if i % j == 0:\n break\n else:\n p.append(i)\n if len(p) == 0:\n return -1\n q = [str(x) for x in p]\n s = ''\n for i in q:\n s += i\n m = max(s.count('1'), s.count('2'), s.count('3'), s.count('4'), s.count('5'), s.count('6'), s.count('7'), s.count('8'), s.count('9'))\n if m == s.count('9'):\n return 9\n elif m == s.count('8'):\n return 8\n elif m == s.count('7'):\n return 7\n elif m == s.count('6'):\n return 6\n elif m == s.count('5'):\n return 5\n elif m == s.count('4'):\n return 4\n elif m == s.count('3'):\n return 3\n elif m == s.count('2'):\n return 2\n elif m == s.count('1'):\n return 1", "def primeCheck(n):\n check = True\n for i in range(2, n):\n if n % i == 0:\n check = False\n break\n return check\n\ndef primeListGetter(rangeValue1, rangeValue2):\n resultList = []\n for val in range(rangeValue1, rangeValue2 + 1):\n if self.primeCheck(val) and val != 1:\n resultList.append(val)\n return resultList\n\ndef maxdigit(L, R):\n primeList = self.primeListGetter(L, R)\n if len(primeList) == 0:\n return -1\n frequency = {}\n maxValueCheck = 0\n maxValueIndex = 0\n for val in primeList:\n charVal = str(val)\n for key in charVal:\n key = int(key)\n frequency[key] = frequency.get(key, 0) + 1\n values = list(frequency.values())\n keys = list(frequency.keys())\n if int(sum(values) / len(values)) == values[0]:\n return max(keys)\n else:\n maximumValue = max(values)\n maximumKey = keys[0]\n for i in keys:\n if frequency[i] == maximumValue:\n if maximumValue <= frequency[i]:\n maximumKey = i\n return maximumKey", "def isPrime(n):\n if n == 1:\n return False\n for i in range(2, n):\n if n % i == 0:\n return False\n return True\n\ndef maxdigit(L, R):\n digitCount = [0 for i in range(10)]\n for i in range(L, R + 1):\n if self.isPrime(i):\n digitCount[i % 10] += 1\n if i >= 10:\n digitCount[i % 100 // 10] += 1\n if i >= 100:\n digitCount[i // 100] += 1\n maxdigit = -1\n maxCount = 0\n for i in range(9, -1, -1):\n if digitCount[i] > maxCount:\n maxCount = digitCount[i]\n maxdigit = i\n return maxdigit", "from collections import Counter\n\ndef isprime(x):\n if x <= 1:\n return 0\n if x == 2:\n return 1\n else:\n for i in range(2, x):\n if x % i == 0:\n return 0\n return 1\n\ndef maxdigit(L, R):\n l = []\n for i in range(L, R + 1):\n if isprime(i):\n l.append(i)\n if l:\n l = [str(x) for x in l]\n res = ''\n res = ''.join(l)\n k = list(res)\n m = Counter(k)\n p = []\n for (keys, values) in m.items():\n p.append(values)\n d = max(p)\n res1 = []\n for (keys, values) in m.items():\n if d == values:\n res1.append(keys)\n if res1:\n return max(res1)\n else:\n return -1\n else:\n return -1", "from collections import defaultdict\nfrom math import ceil\n\ndef maxdigit(L, R):\n primes = []\n count = defaultdict(int)\n\n def prime(n):\n not_primes = set()\n for i in range(3, ceil(n / 2) + 1, 2):\n for j in range(3 * i, n, 2 * i):\n not_primes.add(j)\n return not_primes\n if L <= 2 <= R:\n primes.append(2)\n not_primes = prime(R + 1)\n not_primes.add(1)\n for i in range(L, R + 1):\n if i % 2 == 1 and i not in not_primes:\n primes.append(i)\n (ans, mmax) = ('', 0)\n for num in primes:\n for c in str(num):\n count[c] += 1\n if count[c] > mmax:\n (mmax, ans) = (count[c], c)\n elif count[c] == mmax:\n if c > ans:\n ans = c\n return int(ans) if ans != '' else -1", "import math\n\ndef maxdigit(L, R):\n l = 1001\n ans = [0] * l\n ans[1] = 0\n ans[0] = 1\n for i in range(2, int(math.sqrt(l)) + 1):\n if ans[i] == 0:\n for j in range(2 * i, l, i):\n ans[j] = 1\n let = [0] * 10\n for i in range(L, R + 1):\n if ans[i] == 0:\n t = i\n digit = 0\n while t != 0:\n digit = t % 10\n let[digit] += 1\n t //= 10\n m = let[0]\n ans = 0\n for j in range(1, 10):\n if m <= let[j]:\n m = let[j]\n ans = j\n if m == 0:\n return -1\n return ans", "def maxdigit(L, R):\n l = []\n max = 0\n for i in range(L, R + 1):\n if i >= 1:\n for j in range(2, i):\n if i % j == 0:\n break\n else:\n l.append(str(i))\n if len(l) == 0:\n return -1\n k = ''.join(l)\n for i in range(1, 10):\n if k.count(str(i)) >= max:\n max = k.count(str(i))\n a = i\n return a", "import math as m\n\ndef maxdigit(L, R):\n\n def IsPrime(n):\n if n == 1:\n return True\n for i in range(2, int(m.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n s = ''\n for i in range(L, R + 1):\n if IsPrime(i):\n s += str(i)\n if len(s) == 0:\n return -1\n s = list(s)\n l = list(set(s))\n l.sort(key=int)\n maxi = 0\n for i in l:\n sc = s.count(i)\n if sc >= maxi:\n maxi = sc\n st = i\n return st", "import math\n\ndef prime(n):\n if n == 0:\n return False\n if n == 2 or n == 3 or n == 1:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n for i in range(5, int(math.sqrt(n)) + 1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\ndef maxdigit(l, r):\n c = []\n nivas = []\n ni = 0\n for i in range(l, r + 1):\n if self.prime(i):\n ni += 1\n for j in str(i):\n c.append(j)\n nivas.append(int(j))\n if ni == len(nivas) and ni > 0:\n return max(nivas)\n if ni == 0:\n return '-1'\n d = {}\n for i in c:\n if i not in d.keys():\n d[i] = 1\n else:\n d[i] += 1\n a = max(d, key=d.get)\n if ni > 0:\n return a", "import math as m\n\ndef maxdigit(L, R):\n s = ''\n d = {}\n x = ''\n maxi = 0\n\n def pr(n):\n if n == 1:\n return True\n if n == 0:\n return False\n else:\n for i in range(2, int(m.sqrt(n) + 1)):\n if n % i == 0:\n return False\n return True\n for k in range(L, R + 1):\n if pr(k):\n s = s + str(k)\n if len(s) == 0:\n return -1\n for i in s:\n d[i] = d.get(i, 0) + 1\n for i in d:\n if d[i] > maxi:\n maxi = d[i]\n for i in d:\n if d[i] >= maxi:\n if i > x:\n x = i\n maxi = d[i]\n return x", "def maxdigit(L, R):\n n = 1001\n seive = []\n for _ in range(n + 1):\n seive.append(1)\n seive[0] = 0\n seive[1] = 1\n for i in range(2, n + 1):\n if seive[i] == 1:\n j = i * i\n while j <= n:\n seive[j] = 0\n j += i\n l = []\n for i in range(L, R + 1):\n if seive[i] == 1:\n l.append(i)\n d = dict()\n for word in l:\n s = str(word)\n s = list(s)\n for i in s:\n d[int(i)] = d.get(int(i), 0) + 1\n val = -1\n for (k, v) in sorted(d.items(), key=lambda item: item[1], reverse=True):\n val = v\n break\n res = []\n for (k, v) in sorted(d.items()):\n if v == val:\n res.append(k)\n if len(res) == 0:\n return -1\n return max(res)", "def maxdigit(L, R):\n\n def findPrime(L, R):\n primes = []\n for i in range(L, R + 1):\n for j in range(2, i // 2 + 1):\n if i % j == 0:\n break\n else:\n primes.append(i)\n return primes\n primes = findPrime(L, R)\n if not primes:\n return -1\n d = {}\n for p in primes:\n str_p = str(p)\n for digit in str_p:\n digit = int(digit)\n if digit in d:\n d[digit] += 1\n else:\n d[digit] = 1\n digits_freq = list(d.items())\n digits_freq.sort(key=lambda x: (x[1], x[0]), reverse=True)\n return digits_freq[0][0]", "def maxdigit(L, R):\n c = [True] * (R + 1)\n p = 2\n b = L // 2\n while p * p <= R:\n if c[p] == True:\n for i in range(p * b, R + 1, p):\n if i != p:\n c[i] = False\n p = p + 1\n b = L // p\n m = {}\n for i in range(L, len(c)):\n if c[i] == True:\n while i > 0:\n a = i % 10\n if a in m:\n m[a] = m[a] + 1\n else:\n m[a] = 1\n i = i // 10\n if len(m) == 0:\n return -1\n a = max(m.values())\n if a == 1:\n return max(m.keys())\n r = []\n for keys in m:\n if m[keys] == a:\n r.append(keys)\n return max(r)"], "starter_code": "def maxdigit(L, R):\n", "input_output": {"inputs": ["L = 2, R = 10", "L = 2, R = 20"], "outputs": ["7", "1"]}, "difficulty": "EASY", "raw_tags": ["Prime Number", "sieve"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/find-the-highest-occurring-digit-in-prime-numbers-in-a-range3634/1", "Expected Auxiliary Space": "O(k)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(nlog(n)sqrt(n))", "entry_point": "maxdigit", "task_id": "TACO_lite/139", "example": [[[2, 10], [2, 20]], ["7", "1"]]} +{"requirement": "Given any number of boolean flags function should return true if and only if one of them is true while others are false. If function is called without arguments it should return false.\n\n```python\n only_one() == False\n only_one(True, False, False) == True\n only_one(True, False, False, True) == False\n only_one(False, False, False, False) == False \n```", "solutions": ["def only_one(*args):\n return sum(args) == 1", "def only_one(*args):\n return args.count(True) == 1", "def only_one(*args):\n count = 0\n for item in args:\n if item:\n count += 1\n if count == 2:\n return False\n return True if count == 1 else False", "def only_one(*x):\n return x.count(True) == 1", "def only_one(*flags):\n return sum(flags) == 1", "from collections import Counter\n\ndef only_one(*booleans):\n return Counter(booleans)[True] == 1", "only_one = lambda *a: sum(a) == 1", "def only_one(*flags):\n return len([a for a in flags if a]) == 1", "def only_one(*bool):\n sum = 0\n for value in bool:\n if value:\n sum += 1\n if sum == 1:\n return True\n else:\n return False", "def only_one(*bools):\n return sum((x for x in bools)) == 1"], "starter_code": "def only_one(*args):\n", "input_output": {"fn_name": "only_one", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5734c38da41454b7f700106e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "only_one", "task_id": "TACO_lite/134", "example": [[[], [true, false, false], [true, false, false, true], [false, false, false, false]], ["False", "True", "False", "False"]]} +{"requirement": "Check if it is a vowel(a, e, i, o, u,) on the ```n``` position in a string (the first argument). Don't forget about uppercase.\n\nA few cases:\n\n```\n{\ncheckVowel('cat', 1) -> true // 'a' is a vowel\ncheckVowel('cat', 0) -> false // 'c' is not a vowel\ncheckVowel('cat', 4) -> false // this position doesn't exist\n}\n```\nP.S. If n < 0, return false", "solutions": ["def check_vowel(s, i):\n return 0 <= i < len(s) and s[i] in 'aieouAEIOU'", "def check_vowel(string, position):\n return 0 <= position < len(string) and string[position].lower() in 'aeiou'", "def check_vowel(string, position):\n if position < 0:\n return False\n try:\n return string[position].lower() in ['a', 'e', 'i', 'o', 'u']\n except IndexError:\n return False", "def check_vowel(s, pos):\n return 0 <= pos < len(s) and s.lower()[pos] in 'aeiou'", "def check_vowel(string, position):\n return 0 <= position <= len(string) and string[position] in 'aeiouAEIOU'", "def check_vowel(stg, position):\n return 0 <= position < len(stg) and stg[position].lower() in 'aeiou'", "def check_vowel(s, i):\n return s[i].lower() in 'aeiou' if len(s) > i > -1 else False", "def check_vowel(string, position):\n string = string + ' '\n vowles = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n if string[position] in vowles:\n return True\n else:\n return False", "def check_vowel(string, position):\n if position < 0 or position > len(string):\n return False\n return string[position].lower() in 'aeiou'", "def check_vowel(s, t):\n if t == 0 and s[t] in 'aioueAEIOU':\n return True\n return True if t > 0 and t < len(s) and (s[t] in 'aioueAEIOU') else False\n pass"], "starter_code": "def check_vowel(string, position):\n", "input_output": {"fn_name": "check_vowel", "inputs": [["cat", 1], ["cat", 0], ["cat", 4], ["Amanda", -2], ["Amanda", 0], ["Amanda", 2]], "outputs": [[true], [false], [false], [false], [true], [true]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5a2b7edcb6486a856e00005b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "check_vowel", "task_id": "TACO_lite/248", "example": [[], []]} +{"requirement": "Reverse a linked list from position m to n. Do it in one-pass.\n\nNote: 1 ≤ m ≤ n ≤ length of list.\n\nExample:\n\n\nInput: 1->2->3->4->5->NULL, m = 2, n = 4\nOutput: 1->4->3->2->5->NULL", "solutions": ["def reverseBetween(head, m, n):\n if head is None or head.__next__ is None or m == n:\n return head\n h = ListNode(-1)\n h.next = head\n fast = slow = h\n for _ in range(n - m + 1):\n fast = fast.__next__\n for _ in range(m - 1):\n fast = fast.__next__\n slow = slow.__next__\n prev = fast.__next__\n curr = slow.__next__\n while prev != fast:\n temp = curr.__next__\n curr.next = prev\n prev = curr\n curr = temp\n slow.next = prev\n return h.__next__", "def reverseBetween(head, m, n):\n pre = dummy = ListNode(0)\n dummy.next = head\n num = 0\n first = last = ListNode(0)\n while head:\n num += 1\n if num == m:\n preFirst = pre\n first = head\n if num == n:\n last = head\n laLast = last.__next__\n break\n head = head.__next__\n pre = pre.__next__\n while first != last:\n pre = first\n preFirst.next = pre.__next__\n pre.next = last.__next__\n last.next = pre\n first = preFirst.__next__\n return dummy.__next__", "def reverseBetween(head, m, n):\n\n def reverse(head, m, n):\n m_node = head.__next__\n current = m_node.__next__\n prev_node = m_node\n position2 = m + 1\n while position2 <= n:\n next_node = current.__next__\n current.next = prev_node\n prev_node = current\n current = next_node\n position2 += 1\n m_node.next = next_node\n return prev_node\n if m == n:\n return head\n sentinal = ListNode(-1)\n sentinal.next = head\n current = sentinal\n position = 0\n while current.__next__ is not None:\n if position + 1 == m:\n pre_m = current\n pre_m.next = reverse(pre_m, m, n)\n break\n else:\n position += 1\n current = current.__next__\n if position == 0:\n return pre_m.__next__\n else:\n return head", "def reverseBetween(head, m, n):\n if n == 1:\n return head\n sentinel = ListNode(0)\n pre = sentinel\n pre.next = head\n end = head\n while m > 1:\n pre = pre.__next__\n m -= 1\n while n:\n end = end.__next__\n n -= 1\n new_start = self.reverse(pre.__next__, end)\n pre.next = new_start\n return sentinel.__next__\n\ndef reverse(cur, end):\n new_head = end\n while cur != end:\n next = cur.__next__\n cur.next = new_head\n new_head = cur\n cur = next\n return new_head", "def reverseBetween(head, m, n):\n dummy = ListNode(-1)\n dummy.next = head\n count = 0\n pre = dummy\n while head:\n count += 1\n temp = head.next\n if count == m:\n mNode = head\n if count < m:\n pre = pre.next\n if count > m and count <= n:\n head.next = pre.next\n pre.next = head\n mNode.next = temp\n head = temp\n return dummy.next", "def reverseBetween(head, m, n):\n dummyNode = ListNode(0)\n dummyNode.next = head\n pre = dummyNode\n for i in range(m - 1):\n pre = pre.__next__\n cur = pre.__next__\n reverse = None\n for i in range(n - m + 1):\n next = cur.__next__\n cur.next = reverse\n reverse = cur\n cur = next\n pre.next.next = cur\n pre.next = reverse\n return dummyNode.__next__", "def reverseBetween(head, m, n):\n if n == m:\n return head\n pre_head = head\n re_tail = head\n for i in range(m - 1):\n pre_head = re_tail\n re_tail = pre_head.__next__\n tmp_head = re_tail\n new_head = None\n for i in range(n - m + 1):\n next_node = tmp_head.__next__\n tmp_head.next = new_head\n new_head = tmp_head\n tmp_head = next_node\n re_tail.next = tmp_head\n if m == 1:\n return new_head\n else:\n pre_head.next = new_head\n return head", "def reverseBetween(head, m, n):\n if not head:\n return None\n node = ListNode(0)\n node.next = head\n pre = node\n cur = node.__next__\n for i in range(m - 1):\n pre = pre.__next__\n cur = cur.__next__\n for i in range(n - m):\n tmp = cur.__next__\n cur.next = tmp.__next__\n tmp.next = pre.__next__\n pre.next = tmp\n return node.__next__", "def reverseBetween(head, m, n):\n h = ListNode(0)\n h.next = head\n count = 0\n cur = h\n leftPrev = None\n prev = None\n right = None\n while cur:\n if count == m:\n leftPrev = prev\n left = cur\n if count == n:\n right = cur\n break\n count += 1\n prev = cur\n cur = cur.__next__\n if leftPrev == None or left == right:\n return h.__next__\n rightNext = right.__next__\n tail = right.__next__\n cur = left\n while cur != rightNext:\n temp = cur\n cur = cur.__next__\n temp.next = tail\n tail = temp\n leftPrev.next = tail\n return h.__next__", "def reverseBetween(head, m, n):\n if m == 1:\n m_node = head\n else:\n m_pre = head\n for i in range(m - 2):\n m_pre = m_pre.next\n m_node = m_pre.next\n a = m_node\n b = a.next\n c = a.next\n a.next = None\n for i in range(n - m):\n c = c.next\n b.next = a\n a = b\n b = c\n m_node.next = c\n if m == 1:\n return a\n else:\n m_pre.next = a\n return head"], "starter_code": "def __init__(val=0, next=None):\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Linked List"], "name": null, "source": "leetcode", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/reverse-linked-list-ii/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "__init__", "task_id": "TACO_lite/188", "example": [[], []]} +{"requirement": "Given a Binary Tree. Find the difference between the sum of node values at even levels and the sum of node values at the odd levels.\nExample 1:\nInput:\n 1\n / \\\n 2 3\nOutput: -4\nExplanation:\nsum at odd levels - sum at even levels\n= (1)-(2+3) = 1-5 = -4\nExample 2:\nInput:\n 10\n / \\\n 20 30\n / \\ \n 40 60 \nOutput: 60\nExplanation:\nsum at odd levels - sum at even levels\n= (10+40+60) - (20+30)\n= 110 - 50\n= 60\nYour Task: \nYou dont need to read input or print anything. Complete the function getLevelDiff() which takes root node as input parameter and returns an integer.\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(height of tree)\n \nConstraints:\n1 ≤ N ≤ 10^5", "solutions": ["def getLevelDiff(root):\n if root == None:\n return 0\n q = []\n q.append(root)\n reverse = True\n s = 0\n while q != []:\n c = len(q)\n for i in range(c):\n val = q.pop(0)\n if reverse == True:\n s += val.data\n else:\n s -= val.data\n if val.left != None:\n q.append(val.left)\n if val.right != None:\n q.append(val.right)\n reverse = ~reverse\n return s", "def getLevelDiff(root):\n if root is None:\n return 0\n return root.data - self.getLevelDiff(root.left) - self.getLevelDiff(root.right)", "from collections import deque\n\ndef getLevelDiff(root):\n queue = deque()\n queue.append(root)\n odd_sum = 0\n even_sum = 0\n level = 0\n while queue:\n size = len(queue)\n for _ in range(size):\n curr = queue.popleft()\n if level % 2 == 0:\n even_sum += curr.data\n else:\n odd_sum += curr.data\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n level = level + 1\n return even_sum - odd_sum", "def getLevelDiff(root):\n o = []\n e = []\n s = [root]\n res = []\n level = 0\n while s:\n new = []\n if s:\n if level % 2 != 0:\n e.append(s)\n else:\n o.append(s)\n for i in s:\n node = i\n if node.left:\n new.append(node.left)\n if node.right:\n new.append(node.right)\n if new:\n s = new\n else:\n break\n level += 1\n o1 = []\n e1 = []\n for i in o:\n o1 += i\n for i in e:\n e1 += i\n for i in range(len(o1)):\n o1[i] = o1[i].data\n for i in range(len(e1)):\n e1[i] = e1[i].data\n return sum(o1) - sum(e1)", "def getLevelDiff(root):\n if root is None:\n return\n q = []\n c = 1\n q.append(root)\n odd = []\n even = []\n while len(q) > 0:\n t = []\n n = len(q)\n for i in range(n):\n temp = q.pop(0)\n t.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n if c % 2 == 0:\n for i in t:\n even.append(i)\n else:\n for z in t:\n odd.append(z)\n c += 1\n return sum(odd) - sum(even)", "def getLevelDiff(root):\n if not root:\n return -1\n l = 1\n q = []\n q.append(root)\n o = []\n e = []\n while q:\n t = []\n for i in range(len(q)):\n n = q.pop(0)\n t.append(n.data)\n if n.left:\n q.append(n.left)\n if n.right:\n q.append(n.right)\n if l % 2 == 0:\n for i in t:\n e.append(i)\n else:\n for i in t:\n o.append(i)\n l += 1\n return sum(o) - sum(e)", "def getLevelDiff(root):\n flag = True\n q = [root]\n oddS = 0\n evenS = 0\n while q:\n n = len(q)\n temp = 0\n for i in range(n):\n node = q.pop(0)\n temp += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if flag:\n oddS += temp\n else:\n evenS += temp\n flag = not flag\n return oddS - evenS", "from collections import deque\n\ndef getLevelDiff(root):\n (es, os) = (0, 0)\n level = 1\n q = deque([root, None])\n while len(q) != 1:\n ele = q.popleft()\n if ele:\n if level % 2 == 0:\n es += ele.data\n else:\n os += ele.data\n if ele.left:\n q.append(ele.left)\n if ele.right:\n q.append(ele.right)\n else:\n level += 1\n q.append(None)\n return os - es", "def getLevelDiff(root):\n if root is None:\n return None\n q = []\n q.append(root)\n j = 1\n (os, es) = (0, 0)\n while q:\n s = 0\n l = len(q)\n for i in range(1, l + 1):\n n = q.pop(0)\n s += n.data\n if n.left:\n q.append(n.left)\n if n.right:\n q.append(n.right)\n if j % 2:\n os += s\n else:\n es += s\n j += 1\n return os - es", "def getLevelDiff(root):\n flag = 0\n ans = 0\n q = [root]\n while q:\n num = 0\n for _ in range(len(q)):\n node = q.pop(0)\n num += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if flag == 0:\n ans += num\n flag = 1\n else:\n flag = 0\n ans -= num\n return ans", "def getLevelDiff(root):\n even = 0\n odd = 0\n lvl = 0\n if root == None:\n return\n li = []\n li.append(root)\n while len(li):\n size = len(li)\n lvl += 1\n while size:\n temp = li[0]\n li.pop(0)\n if lvl % 2 == 0:\n even += temp.data\n else:\n odd += temp.data\n if temp.left:\n li.append(temp.left)\n if temp.right:\n li.append(temp.right)\n size -= 1\n return odd - even", "from collections import deque\n\ndef getLevelDiff(root):\n dQ = deque()\n level1 = level2 = 0\n if root != None:\n dQ.append(root)\n track = 0\n while dQ:\n times = len(dQ)\n track += 1\n for i in range(times):\n havenode = dQ.popleft()\n (level1, level2) = [level1 + havenode.data, level2] if track % 2 == 1 else [level1, level2 + havenode.data]\n if havenode.left != None:\n dQ.append(havenode.left)\n if havenode.right != None:\n dQ.append(havenode.right)\n return level1 - level2", "def getLevelDiff(root):\n global esum\n global osum\n esum = 0\n osum = 0\n\n def helper(root, c):\n global esum\n global osum\n if root == None:\n return\n if c % 2 == 0:\n osum += root.data\n else:\n esum += root.data\n helper(root.left, c + 1)\n helper(root.right, c + 1)\n helper(root, 0)\n return osum - esum", "def fun(root, level, l):\n if root == None:\n return\n if level >= len(l):\n l.append([])\n l[level].append(root.data)\n self.fun(root.left, level + 1, l)\n self.fun(root.right, level + 1, l)\n\ndef getLevelDiff(root):\n l = []\n self.fun(root, 0, l)\n (s1, s2) = (0, 0)\n for i in range(len(l)):\n if i % 2 == 0:\n s1 += sum(l[i])\n else:\n s2 += sum(l[i])\n return s1 - s2", "from collections import deque\n\ndef getLevelDiff(root):\n if root is None:\n return 0\n return root.data - self.getLevelDiff(root.left) - self.getLevelDiff(root.right)\n return result", "from collections import deque\n\ndef getLevelDiff(root):\n q = deque()\n q.appendleft(root)\n result = 0\n sum = True\n while q:\n temp_sum = 0\n size = len(q)\n for i in range(size):\n node = q.pop()\n temp_sum += node.data\n if node.left:\n q.appendleft(node.left)\n if node.right:\n q.appendleft(node.right)\n if sum:\n result += temp_sum\n else:\n result -= temp_sum\n sum = not sum\n return result", "import queue\n\ndef getLevelDiff(root):\n q = []\n q.append(root)\n result = 0\n sum = True\n while q:\n temp_sum = 0\n size = len(q)\n for i in range(size):\n node = q.pop(0)\n temp_sum += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if sum:\n result += temp_sum\n else:\n result -= temp_sum\n sum = not sum\n return result", "from collections import deque as d\n\ndef getLevelDiff(root):\n l = d()\n l.appendleft(root)\n l.appendleft(' ')\n ll = []\n c = 1\n os = 0\n es = 0\n while l:\n a = l.pop()\n if a == ' ':\n if c % 2 != 0:\n os += sum(ll)\n else:\n es += sum(ll)\n ll = []\n if l:\n l.appendleft(' ')\n c += 1\n else:\n ll.append(a.data)\n if a.left:\n l.appendleft(a.left)\n if a.right:\n l.appendleft(a.right)\n return os - es", "def solve(root, odd, even, l):\n if root == None:\n return\n if l % 2 == 0:\n even.append(root.data)\n else:\n odd.append(root.data)\n l += 1\n self.solve(root.left, odd, even, l)\n self.solve(root.right, odd, even, l)\n l -= 1\n\ndef getLevelDiff(root):\n odd = []\n even = []\n l = 0\n self.solve(root, odd, even, l)\n k = sum(even) - sum(odd)\n return k", "from collections import deque\n\ndef getLevelDiff(root):\n q = deque()\n q.append(root)\n s = root.data\n lvl = 1\n while q:\n k = len(q)\n lvl += 1\n for i in range(k):\n popped = q.popleft()\n if popped.left:\n q.append(popped.left)\n if lvl % 2 == 0:\n s -= popped.left.data\n else:\n s += popped.left.data\n if popped.right:\n q.append(popped.right)\n if lvl % 2 == 0:\n s -= popped.right.data\n else:\n s += popped.right.data\n return s", "def getLevelDiff(root):\n even = 0\n odd = 0\n\n def lev(rt, level):\n nonlocal even, odd\n if not rt:\n return\n if level % 2 == 0:\n even += rt.data\n if level % 2 == 1:\n odd += rt.data\n lev(rt.left, level + 1)\n lev(rt.right, level + 1)\n lev(root, 1)\n return odd - even", "def getLevelDiff(root):\n odd = 0\n even = 0\n from collections import deque\n q = deque()\n q.append(root)\n c = 1\n while q:\n size = len(q)\n x = 0\n for i in range(size):\n node = q.popleft()\n x += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if c & 1:\n odd += x\n else:\n even += x\n c += 1\n return odd - even", "def getLevelDiff(root):\n l = []\n q = []\n k = [0]\n m = -1\n q.append(root)\n while q:\n z = q.pop(0)\n x = k.pop(0)\n if m != x:\n m = x\n l.append([])\n l[-1].append(z.data)\n if z.left is not None:\n q.append(z.left)\n k.append(x + 1)\n if z.right is not None:\n q.append(z.right)\n k.append(x + 1)\n odd = 0\n for x in range(0, len(l), 2):\n odd += sum(l[x])\n even = 0\n for x in range(1, len(l), 2):\n even += sum(l[x])\n return odd - even", "def getLevelDiff(root):\n dd = {}\n stck = []\n stck.append(root)\n level = 1\n cnt = 1\n while stck:\n total = 0\n for i in range(cnt):\n popped = stck.pop(0)\n total += popped.data\n if popped.left:\n stck.append(popped.left)\n if popped.right:\n stck.append(popped.right)\n cnt = len(stck)\n dd[level] = total\n level += 1\n diff = 0\n for i in dd.keys():\n if i % 2 == 0:\n diff -= dd[i]\n else:\n diff += dd[i]\n return diff", "def getLevelDiff(root):\n self.ans = 0\n\n def cal(root, d):\n if root == None:\n return\n if d % 2 == 0:\n self.ans -= root.data\n else:\n self.ans += root.data\n cal(root.left, d + 1)\n cal(root.right, d + 1)\n cal(root, 1)\n return self.ans", "def getLevelDiff(root):\n q = [root]\n even = 0\n odd = 0\n count = 1\n while q:\n list = []\n for i in q:\n list.append(i.data)\n if count % 2 != 0:\n odd += sum(list)\n else:\n even += sum(list)\n for _ in range(len(q)):\n node = q.pop(0)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n count += 1\n return odd - even", "from collections import deque\n\ndef getLevelDiff(root):\n q = deque([root])\n k = []\n while q:\n n = len(q)\n l = []\n for _ in range(n):\n node = q.popleft()\n l.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n k.append(sum(l))\n o = e = 0\n for i in range(len(k)):\n if i % 2 == 0:\n e += k[i]\n else:\n o += k[i]\n return e - o", "def dfs(n, l):\n if not n:\n return 0\n if not n.left and (not n.right):\n return n.data if l % 2 == 0 else -n.data\n children = dfs(n.left, l + 1) + dfs(n.right, l + 1)\n me = n.data if l % 2 == 0 else -n.data\n return children + me\n\ndef getLevelDiff(root):\n return dfs(root, 0)", "def getLevelDiff(root):\n global sm\n sm = 0\n\n def diff(root, h):\n global sm\n if root is None:\n return\n if h % 2 == 0:\n sm = sm + root.data\n else:\n sm = sm - root.data\n diff(root.left, h + 1)\n diff(root.right, h + 1)\n diff(root, 0)\n return sm", "def getLevelDiff(root):\n c = 1\n if not root:\n return []\n s = 0\n q = []\n q.append(root)\n while q:\n a = []\n le = len(q)\n for i in range(le):\n k = q.pop(0)\n a.append(k.data)\n if k.left:\n q.append(k.left)\n if k.right:\n q.append(k.right)\n if c & 1:\n s += sum(a)\n else:\n s -= sum(a)\n c += 1\n return s", "def getLevelDiff(root):\n sum_even = 0\n sum_odd = 0\n st = []\n counter = 0\n if root is None:\n return 0\n st.append(root)\n while len(st) > 0:\n counter += 1\n t = []\n while len(st) != 0:\n x = st.pop()\n if x.left is not None:\n t.append(x.left)\n if x.right is not None:\n t.append(x.right)\n if counter % 2 == 0:\n sum_even += x.data\n else:\n sum_odd += x.data\n st = t\n return sum_odd - sum_even", "def levelOrder(root):\n bfs = []\n if root is None:\n return bfs\n q = deque([])\n q.append(root)\n while q:\n lvl_size = len(q)\n curr_lvl = []\n for i in range(lvl_size):\n curr = q.popleft()\n curr_lvl.append(curr.data)\n if curr.left is not None:\n q.append(curr.left)\n if curr.right is not None:\n q.append(curr.right)\n bfs.append(curr_lvl)\n return bfs\n\ndef getLevelDiff(root):\n sumi = 0\n count = 0\n a = levelOrder(root)\n while a:\n s = a.pop(0)\n if count % 2 == 0:\n sumi += sum(s)\n else:\n sumi -= sum(s)\n count += 1\n return sumi", "def getLevelDiff(root):\n c = 1\n s1 = 0\n s2 = 0\n queue = [root]\n while queue != []:\n t = []\n for i in range(len(queue)):\n curr = queue[0]\n t.append(curr.data)\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n queue.pop(0)\n if c % 2 == 1:\n s1 += sum(t)\n c += 1\n elif c % 2 != 1:\n s2 += sum(t)\n c += 1\n return s1 - s2", "def getLevelDiff(root):\n es = [0]\n os = [0]\n level = [0]\n self.Util(root, es, os, level, 1)\n return os[0] - es[0]\n\ndef Util(root, es, os, level, l):\n if not root:\n return\n if l % 2 == 0:\n es[0] += root.data\n else:\n os[0] += root.data\n self.Util(root.left, es, os, level, l + 1)\n self.Util(root.right, es, os, level, l + 1)", "def getLevelDiff(root):\n odd = []\n even = []\n q = []\n q.append(root)\n x = 1\n while q:\n l = len(q)\n lis = []\n for i in range(l):\n temp = q.pop(0)\n lis.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n if x % 2 == 0:\n even.extend(lis)\n else:\n odd.extend(lis)\n x += 1\n return sum(odd) - sum(even)", "def getLevelDiff(root):\n q = []\n od = 0\n ev = 0\n q.append(root)\n l = 0\n while q:\n l += 1\n n = len(q)\n ans = 0\n while n > 0:\n k = q.pop(0)\n ans += k.data\n if k.left:\n q.append(k.left)\n if k.right:\n q.append(k.right)\n n -= 1\n if l % 2 == 0:\n ev += ans\n else:\n od += ans\n return od - ev", "def getLevelDiff(root, level=1):\n if root.left == None and root.right == None:\n if level % 2 == 1:\n return root.data\n else:\n return -root.data\n lowlevelleft = 0\n lowlevelright = 0\n if root.left != None:\n lowlevelleft = self.getLevelDiff(root.left, level + 1)\n if root.right != None:\n lowlevelright = self.getLevelDiff(root.right, level + 1)\n if level % 2 == 0:\n return lowlevelleft + lowlevelright - root.data\n else:\n return lowlevelleft + lowlevelright + root.data", "import collections\n\ndef getLevelDiff(root):\n q = collections.deque()\n q.append(root)\n odd = True\n odd_tot = 0\n even_tot = 0\n while q:\n qLen = len(q)\n tot = 0\n for i in range(qLen):\n cur = q.popleft()\n if cur.left:\n q.append(cur.left)\n if cur.right:\n q.append(cur.right)\n tot += cur.data\n if odd:\n odd_tot += tot\n odd = False\n else:\n even_tot += tot\n odd = True\n return odd_tot - even_tot", "def getLevelDiff(root):\n d = []\n g = {}\n m = []\n d.append(1)\n m.append(root)\n while len(m) != 0:\n c = m.pop(0)\n x = d.pop(0)\n if x not in g:\n g[x] = [c.data]\n else:\n g[x].append(c.data)\n if c.left != None:\n m.append(c.left)\n d.append(x + 1)\n if c.right != None:\n m.append(c.right)\n d.append(x + 1)\n odd = 0\n even = 0\n for h in g:\n if h % 2 == 0:\n for j in range(0, len(g[h])):\n even = even + g[h][j]\n else:\n for j in range(0, len(g[h])):\n odd = odd + g[h][j]\n return odd - even", "def getLevelDiff(root):\n sum = [0, 0]\n self.findSum(root, 1, sum)\n return sum[0] - sum[1]\n\ndef findSum(root, level, sum):\n if not root:\n return None\n if level % 2 == 0:\n sum[1] += root.data\n else:\n sum[0] += root.data\n self.findSum(root.left, level + 1, sum)\n self.findSum(root.right, level + 1, sum)", "def getLevelDiff(root):\n if root == None:\n return\n q = [root]\n c = 1\n (s1, s2) = (0, 0)\n while q:\n l = []\n s = len(q)\n for i in range(len(q)):\n t = q.pop(0)\n l.append(t.data)\n if t.left:\n q.append(t.left)\n if t.right:\n q.append(t.right)\n if c == 1:\n s1 = s1 + sum(l)\n c = 0\n else:\n s2 = s2 + sum(l)\n c = 1\n return s1 - s2", "def getLevelDiff(root):\n C = self.reverseLevelOrder(root)\n x = 0\n for i in range(len(C)):\n if i % 2 == 0:\n x += sum(C[i])\n else:\n x -= sum(C[i])\n return x\n\ndef reverseLevelOrder(root):\n A = []\n B = []\n C = []\n D = []\n if root is None:\n return A\n A.append(root)\n while len(A) > 0:\n while len(A) > 0:\n node = A.pop(0)\n B.append(node.data)\n if node.left is not None:\n D.append(node.left)\n if node.right is not None:\n D.append(node.right)\n A.extend(D)\n D = []\n C.append(B)\n B = []\n return C", "def getLevelDiff(root):\n ans = [0] * 1\n\n def fun(root, level):\n if root == None:\n return\n if level % 2 == 0:\n ans[0] += root.data\n else:\n ans[0] -= root.data\n fun(root.left, level + 1)\n fun(root.right, level + 1)\n fun(root, 0)\n return ans[0]", "def getLevelDiff(root):\n l = 0\n q = [root]\n (res, ans) = ([], [])\n if root == None:\n return None\n while q:\n for i in range(len(q)):\n node = q.pop(0)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if l % 2 == 0:\n res.append(node.data)\n else:\n ans.append(node.data)\n l += 1\n return sum(res) - sum(ans)", "from collections import deque\n\ndef getLevelDiff(root):\n\n def traversal(root, level):\n nonlocal sum1, sum2\n if root == None:\n return None\n if level % 2 == 0:\n sum1 += root.data\n else:\n sum2 += root.data\n if root.left:\n traversal(root.left, level + 1)\n if root.right:\n traversal(root.right, level + 1)\n (sum1, sum2) = (0, 0)\n traversal(root, 0)\n return sum1 - sum2", "def getLevelDiff(root):\n q = []\n q.append(root)\n q.append('$')\n odd = 0\n even = 0\n level = 1\n while len(q) > 0:\n t = q.pop(0)\n if t == '$':\n if len(q) > 0:\n q.append('$')\n level += 1\n else:\n if t.left is not None:\n q.append(t.left)\n if t.right is not None:\n q.append(t.right)\n if level % 2 != 0:\n odd += t.data\n else:\n even += t.data\n return odd - even", "def getLevelDiff(root):\n mylist = [0, 0]\n if not root:\n return 0\n\n def help(root, lvl):\n if lvl % 2 == 0:\n mylist[0] += root.data\n else:\n mylist[1] += root.data\n if root.left:\n help(root.left, lvl + 1)\n if root.right:\n help(root.right, lvl + 1)\n return mylist[0] - mylist[1]\n return help(root, 0)", "def getLevelDiff(root):\n return self.myFunc(root, 0)\n\ndef myFunc(root, level):\n if not root:\n return 0\n level += 1\n summa = root.data\n if level % 2 == 0:\n summa *= -1\n summa += self.myFunc(root.left, level)\n summa += self.myFunc(root.right, level)\n return summa", "def getLevelDiff(root):\n if root == None:\n return 0\n leftsum = self.getLevelDiff(root.left)\n rightsum = self.getLevelDiff(root.right)\n return root.data - leftsum - rightsum", "def in_order(root, lvl, nv):\n if root is None:\n return\n self.in_order(root.left, lvl + 1, nv)\n self.in_order(root.right, lvl + 1, nv)\n if lvl not in nv:\n nv[lvl] = [root.data]\n else:\n nv[lvl].append(root.data)\n\ndef getLevelDiff(root):\n nv = {}\n self.in_order(root, 0, nv)\n osum = 0\n esum = 0\n for (k, v) in nv.items():\n if k % 2:\n esum += sum(v)\n else:\n osum += sum(v)\n return osum - esum", "def getLevelDiff(root):\n ans = [0, 0]\n if not root:\n return 0\n curr = [root]\n i = 0\n while curr:\n next_level = []\n while curr:\n v = curr.pop(0)\n ans[i % 2] += v.data\n if v.left:\n next_level.append(v.left)\n if v.right:\n next_level.append(v.right)\n i += 1\n curr = next_level\n return ans[0] - ans[1]", "def getNode(arr, root, d):\n if not root:\n return\n arr.append([root.data, d])\n self.getNode(arr, root.right, d + 1)\n self.getNode(arr, root.left, d + 1)\n\ndef getLevelDiff(root):\n arr = []\n self.getNode(arr, root, 0)\n sum1 = 0\n sum2 = 0\n dep = len(arr)\n for i in range(0, dep):\n d = arr[i][1] + 1\n if d % 2 == 0:\n sum2 = sum2 + arr[i][0]\n else:\n sum1 = sum1 + arr[i][0]\n return sum1 - sum2", "def getLevelDiff(root):\n if root is None:\n return None\n q = [root]\n ans = root.data\n flag = True\n while len(q) > 0:\n n = len(q)\n temp = 0\n for i in range(0, n):\n node = q.pop(0)\n if node.left:\n q.append(node.left)\n temp += node.left.data\n if node.right:\n q.append(node.right)\n temp += node.right.data\n if flag:\n ans -= temp\n flag = False\n else:\n ans += temp\n flag = True\n return ans", "def getLevelDiff(root):\n\n def helper(root):\n nonlocal odd_sum, even_sum\n nonlocal level\n if root is None:\n return\n level += 1\n if level % 2 == 0:\n even_sum += root.data\n else:\n odd_sum += root.data\n helper(root.left)\n helper(root.right)\n level -= 1\n return\n (odd_sum, even_sum) = (0, 0)\n level = 0\n helper(root)\n return odd_sum - even_sum", "def __init__():\n self.even = 0\n self.odd = 0\n\ndef pre(root, l):\n if root == None:\n return\n if l % 2 == 1:\n self.odd += root.data\n else:\n self.even += root.data\n if root.left != None:\n self.pre(root.left, l + 1)\n if root.right != None:\n self.pre(root.right, l + 1)\n\ndef getLevelDiff(root):\n self.pre(root, 1)\n return self.odd - self.even", "def getLevelDiff(root):\n q = deque()\n q.append(root)\n q.append(None)\n l = []\n m = []\n while len(q) > 1:\n cur = q.popleft()\n if cur == None:\n l.append(m)\n m = []\n q.append(None)\n continue\n m.append(cur.data)\n if cur.left != None:\n q.append(cur.left)\n if cur.right != None:\n q.append(cur.right)\n if m:\n l.append(m)\n os = 0\n es = 0\n for i in range(len(l)):\n if i % 2 == 0:\n os += sum(l[i])\n else:\n es += sum(l[i])\n t = os - es\n return t", "def getLevelDiff(root):\n q = [root]\n level = 1\n sume = 0\n sumo = 0\n while q:\n l = len(q)\n for i in range(l):\n if len(q) != 0:\n x = q.pop(0)\n if level % 2 == 0:\n sume += x.data\n else:\n sumo += x.data\n if i == l - 1:\n level += 1\n if x.left:\n q.append(x.left)\n if x.right:\n q.append(x.right)\n return sumo - sume", "def helper(root, level, d):\n if root:\n if root == 'N':\n return\n else:\n if level not in d:\n d[level] = [root.data]\n else:\n d[level].append(root.data)\n helper(root.left, level + 1, d)\n helper(root.right, level + 1, d)\n\ndef getLevelDiff(root):\n d = {}\n l1 = []\n l2 = []\n level = 1\n helper(root, level, d)\n for i in d:\n if i % 2 == 0:\n l1.append(sum(d[i]))\n else:\n l2.append(sum(d[i]))\n return sum(l2) - sum(l1)", "def getLevelDiff(root):\n q = []\n q.append(root)\n sum_o = 0\n sum_e = 0\n a = 0\n while q:\n n = len(q)\n for i in range(n):\n curr = q.pop(0)\n if a % 2 == 0:\n sum_o = sum_o + curr.data\n else:\n sum_e = sum_e + curr.data\n if curr.left != None:\n q.append(curr.left)\n if curr.right != None:\n q.append(curr.right)\n a += 1\n return sum_o - sum_e", "def __init__():\n self.odd = 0\n self.even = 0\n\ndef getleveldiffutil(root, flag):\n if root is None:\n return None\n if flag == True:\n self.odd += root.data\n else:\n self.even += root.data\n self.getleveldiffutil(root.left, not flag)\n self.getleveldiffutil(root.right, not flag)\n\ndef getLevelDiff(root):\n flag = True\n self.getleveldiffutil(root, flag)\n return self.odd - self.even", "def getLevelDiff(root):\n q = []\n q.append(root)\n level = 1\n odd_sum = 0\n even_sum = 0\n while q:\n for _ in range(len(q)):\n curr = q.pop(0)\n data = curr.data\n if level & 1:\n odd_sum += data\n else:\n even_sum += data\n if curr.left:\n q.append(curr.left)\n if curr.right:\n q.append(curr.right)\n level += 1\n return odd_sum - even_sum", "from collections import deque\n\ndef getLevelDiff(root):\n if not root:\n return 0\n q = deque([root])\n (res, level) = (0, 1)\n while q:\n for _ in range(len(q)):\n node = q.popleft()\n if level & 1:\n res += node.data\n else:\n res -= node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n level += 1\n return res", "def evenOddLevelDifference(root):\n if not root:\n return 0\n q = []\n q.append(root)\n level = 0\n evenSum = 0\n oddSum = 0\n while len(q):\n size = len(q)\n level += 1\n while size > 0:\n temp = q[0]\n q.pop(0)\n if level % 2 == 0:\n evenSum += temp.data\n else:\n oddSum += temp.data\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n size -= 1\n return oddSum - evenSum\n\ndef getLevelDiff(root):\n return evenOddLevelDifference(root)", "def getLevelDiff(root):\n (a, b) = (0, 0)\n\n def lev(root, l):\n nonlocal a, b\n if not root:\n return\n if l % 2 != 0:\n a += root.data\n else:\n b += root.data\n lev(root.left, l + 1)\n lev(root.right, l + 1)\n return a - b\n return lev(root, 1)", "def getLevelDiff(root):\n even = 0\n odd = 0\n evenb = True\n queue = [root]\n elements = 1\n newelements = 0\n while len(queue) > 0:\n root = queue.pop(0)\n if evenb:\n even += root.data\n else:\n odd += root.data\n elements -= 1\n if root.left != None:\n queue.append(root.left)\n newelements += 1\n if root.right != None:\n queue.append(root.right)\n newelements += 1\n if elements == 0:\n elements += newelements\n newelements = 0\n evenb = not evenb\n return even - odd", "def getLevelDiff(root):\n odd = 0\n even = 0\n\n def dfs(root, level):\n nonlocal even\n nonlocal odd\n if not root:\n return\n dfs(root.left, level + 1)\n dfs(root.right, level + 1)\n if level % 2 == 0:\n even += root.data\n else:\n odd += root.data\n return odd - even\n return dfs(root, 1)", "def getLevelDiff(root):\n level = 0\n evenStack = []\n oddStack = []\n\n def oddEvenLevels(root, level):\n if root == None:\n return\n if level % 2 == 0:\n evenStack.append(root.data)\n else:\n oddStack.append(root.data)\n oddEvenLevels(root.left, level + 1)\n oddEvenLevels(root.right, level + 1)\n oddEvenLevels(root, 0)\n evenValue = 0\n for i in evenStack:\n evenValue = evenValue + i\n oddValue = 0\n for i in oddStack:\n oddValue = oddValue + i\n return evenValue - oddValue", "def getLevelDiff(root):\n if root is None:\n return 0\n if root.left is None and root.right is None:\n return root.data\n freq = {}\n self.traversal(root, freq, 1)\n return freq['o'] - freq['e']\n\ndef traversal(root, freq, level):\n if root is None:\n return\n if level % 2 == 0:\n if 'e' in freq.keys():\n freq['e'] += root.data\n else:\n freq['e'] = root.data\n elif 'o' in freq.keys():\n freq['o'] += root.data\n else:\n freq['o'] = root.data\n self.traversal(root.left, freq, level + 1)\n self.traversal(root.right, freq, level + 1)", "def getLevelDiff(root):\n oddArr = []\n evenArr = []\n self.getLevelDiffAux(root, 1, oddArr, evenArr)\n return sum(oddArr) - sum(evenArr)\n\ndef getLevelDiffAux(node, level, oddArr, evenArr):\n if node is None:\n return\n elif level % 2 == 0:\n evenArr.append(node.data)\n else:\n oddArr.append(node.data)\n self.getLevelDiffAux(node.left, level + 1, oddArr, evenArr)\n self.getLevelDiffAux(node.right, level + 1, oddArr, evenArr)", "def getLevelDiff(root):\n\n def helper(root, mp, k):\n if root:\n if k in mp:\n mp[k] += root.data\n else:\n mp[k] = root.data\n helper(root.left, mp, k + 1)\n helper(root.right, mp, k + 1)\n return mp\n mp = helper(root, {}, 0)\n e = 0\n o = 0\n for i in mp:\n if i & 1 == 0:\n e += mp[i]\n else:\n o += mp[i]\n return e - o", "def getLevelDiff(root):\n\n def helper(x):\n ans = []\n q = []\n t = 0\n if not x:\n return None\n q.append(x)\n while q:\n l = len(q)\n for i in range(l):\n a = q.pop(0)\n if a.left:\n q.append(a.left)\n if a.right:\n q.append(a.right)\n t += a.data\n ans.append(t)\n t = 0\n return ans\n a = helper(root)\n b = 0\n c = 0\n for i in range(len(a)):\n if i % 2 == 0:\n b += a[i]\n else:\n c += a[i]\n return b - c", "from collections import deque\n\ndef getLevelDiff(root):\n q = deque()\n q.append(root)\n evenLvl = 0\n oddLvl = 0\n flag = True\n while q:\n for i in range(len(q)):\n temp = q.popleft()\n if flag:\n oddLvl += temp.data\n else:\n evenLvl += temp.data\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n if flag:\n flag = False\n else:\n flag = True\n return oddLvl - evenLvl", "import collections\nfrom collections import deque\n\ndef getLevelDiff(root):\n res = []\n sum1 = 0\n sum2 = 0\n q = collections.deque()\n q.append(root)\n while q:\n ql = len(q)\n l = []\n for i in range(ql):\n x = q.popleft()\n if x:\n l.append(x.data)\n q.append(x.left)\n q.append(x.right)\n if l:\n res.append(l)\n for i in range(len(res)):\n if i % 2 == 0:\n sum1 = sum1 + sum(res[i])\n else:\n sum2 = sum2 + sum(res[i])\n return sum1 - sum2", "def getLevelDiff(root):\n global s, s1\n s = 0\n s1 = 0\n\n def Sm(root, level):\n global s, s1\n if not root:\n return\n if level % 2 == 0:\n s = s + root.data\n else:\n s1 = s1 + root.data\n Sm(root.left, level + 1)\n Sm(root.right, level + 1)\n Sm(root, 1)\n return s1 - s", "def getLevelDiff(root):\n odd = even = 0\n level = 1\n q = [root]\n while q:\n size = len(q)\n for _ in range(size):\n node = q.pop(0)\n if level & 1:\n odd += node.data\n else:\n even += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n level += 1\n return odd - even", "def getLevelDiff(root):\n i = 1\n even = []\n odd = []\n q = []\n q.append(root)\n while q:\n count = len(q)\n while count:\n temp = q.pop(0)\n if i % 2 != 0:\n odd.append(temp.data)\n else:\n even.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n count -= 1\n i += 1\n return sum(odd) - sum(even)", "def getLevelDiff(root):\n\n def getdiff(root):\n if not root:\n return 0\n else:\n l = getdiff(root.left)\n r = getdiff(root.right)\n return root.data - l - r\n return getdiff(root)", "def getLevelDiff(root, l=0):\n if not root:\n return\n esum = 0\n osum = 0\n q = []\n l = 0\n q.append(root)\n while q:\n size = len(q)\n l += 1\n while size > 0:\n tmp = q.pop(0)\n if l % 2 == 0:\n esum += tmp.data\n else:\n osum += tmp.data\n if tmp.left:\n q.append(tmp.left)\n if tmp.right:\n q.append(tmp.right)\n size -= 1\n return osum - esum", "def getLevelDiff(root):\n if root is None:\n return 0\n que = [root]\n (odd, even, level) = (0, 0, 1)\n while que != []:\n temp = []\n for i in que:\n if level % 2 == 0:\n even += i.data\n else:\n odd += i.data\n if i.left:\n temp.append(i.left)\n if i.right:\n temp.append(i.right)\n level += 1\n que = temp\n return odd - even", "def getLevelDiff(root):\n q = []\n s1 = 0\n s2 = 0\n c = 0\n q.append(root)\n while q:\n sz = len(q)\n for i in range(sz):\n curr = q[0]\n q.pop(0)\n if curr.left:\n q.append(curr.left)\n if curr.right:\n q.append(curr.right)\n if c % 2 == 0:\n s1 += curr.data\n else:\n s2 += curr.data\n c += 1\n return s1 - s2", "from collections import deque\n\ndef getLevelDiff(root):\n if root is None:\n return 0\n ans = []\n cnt = 0\n sumo = 0\n sume = 0\n q = deque()\n q.append(root)\n while q:\n cnt = cnt + 1\n n = len(q)\n levelo = []\n levele = []\n for i in range(n):\n node = q.popleft()\n if cnt % 2 == 0:\n levele.append(node.data)\n sume = sume + node.data\n else:\n levelo.append(node.data)\n sumo = sumo + node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return sumo - sume", "def getLevelDiff(root):\n flag = False\n queue = [root]\n odd = 0\n even = 0\n while queue:\n length = len(queue)\n for i in range(length):\n node = queue.pop(0)\n if node.left != None:\n queue.append(node.left)\n if node.right != None:\n queue.append(node.right)\n if flag:\n even += node.data\n else:\n odd += node.data\n flag = not flag\n return odd - even", "def getLevelDiff(root):\n if not root:\n return None\n even = []\n odd = []\n q = []\n l = 0\n q.append(root)\n while len(q) > 0:\n l += 1\n b = []\n li = []\n while len(q) > 0:\n node = q.pop(0)\n li.append(node.data)\n if node.left:\n b.append(node.left)\n if node.right:\n b.append(node.right)\n if l % 2 == 0:\n even.append(sum(li))\n else:\n odd.append(sum(li))\n q = b\n return sum(odd) - sum(even)"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["1\n / \\\n 2 3", "10\n / \\\n 20 30\n / \\ \n 40 60"], "outputs": ["-4", "60"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/odd-even-level-difference/1", "Expected Auxiliary Space": "O(height of tree)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "__init__", "task_id": "TACO_lite/219", "example": [[[[1, 2, 3]], [[10, 20, 30, 40, 60]]], ["-4", "60"]]} +{"requirement": "Given a Binary tree and a key in the binary tree, find the node right to the given key. If there is no node on right side, then return a node with value -1.\nExample 1:\nInput:\n 10\n / \\\n 2 6\n / \\ \\\n 8 4 5\nand key = 2\nOutput: 6\nExplanation: We can see in the above tree\nthat the next right node of 2 is 6.\nExample 2:\nInput:\n 10\n / \\\n 2 6\n / \\ \\\n 8 4 5\nand key = 5\nOutput: -1\nExplanation: We can see in the above tree \nthat there's No next right node of 5.\nSo, the output is -1.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function nextRight() which takes root node of the tree and an integer key as input parameters and returns the next right node of the node with value key. \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1<=N<=10^{3}\n1<=data of node<=10^{3}\n1<=key<=10^{3}", "solutions": ["from collections import deque\n\ndef nextRight(root, key):\n x = []\n q = deque()\n q.append(root)\n while q:\n for i in range(len(q)):\n a = q.popleft()\n x.append(a.data)\n if a.left:\n q.append(a.left)\n if a.right:\n q.append(a.right)\n x.append('l')\n for i in range(len(x) - 1):\n if x[i] == key:\n if x[i + 1] == 'l':\n return Node(-1)\n return Node(x[i + 1])", "from collections import deque\n\ndef nextRight(root, key):\n l = [root]\n temp = Node(-1)\n while l:\n r = []\n size = len(l)\n for i in range(size):\n if l[i].data == key:\n if i < size - 1:\n curr = Node(l[i + 1].data)\n return curr\n else:\n return temp\n if l[i].left:\n r.append(l[i].left)\n if l[i].right:\n r.append(l[i].right)\n l = r\n return temp", "from collections import deque\n\ndef fun(root, level, l, res, key, t):\n if root == None:\n return\n if level >= len(l):\n l.append([])\n t.append([])\n if root.data == key:\n res[0] = level\n l[level].append(root)\n t[level].append(root.data)\n self.fun(root.left, level + 1, l, res, key, t)\n self.fun(root.right, level + 1, l, res, key, t)\n\ndef nextRight(root, key):\n r = root\n (l, res) = ([], [0])\n t = []\n self.fun(root, 0, l, res, key, t)\n ind = res[0]\n t1 = l[ind]\n t2 = t[ind]\n v = t2.index(key)\n if v == len(t2) - 1:\n r.data = -1\n res[0] = r\n else:\n res[0] = t1[v + 1]\n return res[0]", "from collections import deque\n\ndef nextRight(root, key):\n if root is None:\n return Node(-1)\n qn = []\n q1 = []\n level = 0\n qn.append(root)\n q1.append(level)\n while len(qn) > 0:\n node = qn.pop(0)\n level = q1.pop(0)\n if node.data == key:\n if len(q1) == 0 or q1[0] != level:\n return Node(-1)\n return qn[0]\n if node.left is not None:\n qn.append(node.left)\n q1.append(level + 1)\n if node.right is not None:\n qn.append(node.right)\n q1.append(level + 1)\n return Node(-1)", "def nextRight(root, key):\n q = [root]\n ans = Node(-1)\n while q:\n lis = []\n for i in range(len(q)):\n node = q.pop(0)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if lis:\n if lis[-1] == key:\n return node\n lis.append(node.data)\n return ans", "from collections import deque\n\ndef nextRight(root, key):\n queue = [root]\n while queue:\n l = len(queue)\n for i in range(1, l + 1):\n x = queue.pop(0)\n if x.data == key:\n if i != l:\n return queue[0]\n return Node(-1)\n if x.left:\n queue.append(x.left)\n if x.right:\n queue.append(x.right)", "from collections import deque\n\ndef nextRight(root, key):\n dq = deque()\n dq.append(root)\n while len(dq) > 0:\n currsize = len(dq)\n for i in range(currsize):\n temp = dq.popleft()\n if temp.data == key:\n if i == currsize - 1:\n return Node(-1)\n else:\n return dq.popleft()\n if temp.left != None:\n dq.append(temp.left)\n if temp.right != None:\n dq.append(temp.right)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n elements = deque()\n level = deque()\n elements.append(root)\n level.append(0)\n while len(elements) != 0:\n front = elements.popleft()\n curr_level = level.popleft()\n if front.data == key:\n if len(elements) == 0:\n return Node(-1)\n next_ele = elements.popleft()\n next_level = level.popleft()\n if next_level != curr_level:\n return Node(-1)\n else:\n return next_ele\n if front.left != None:\n elements.append(front.left)\n level.append(curr_level + 1)\n if front.right != None:\n elements.append(front.right)\n level.append(curr_level + 1)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n f = [root]\n s = []\n while len(f) > 0:\n node = f[0]\n f.pop(0)\n if node.data == key:\n if len(f) == 0:\n return Node(-1)\n return f[0]\n if node.left != None:\n s.append(node.left)\n if node.right != None:\n s.append(node.right)\n if len(f) == 0:\n f = s\n s = []", "from collections import deque\n\ndef nextRight(root, key):\n q = []\n q.append(root)\n q.append(-1)\n while q:\n l = len(q)\n for i in range(l):\n temp = q.pop(0)\n if temp == -1:\n continue\n else:\n if temp.data == key:\n if len(q):\n if q[0] == -1:\n root.data = -1\n return root\n else:\n return q[0]\n else:\n root.data = -1\n return root\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n q.append(-1)", "from collections import deque\n\ndef nextRight(root, key):\n queue = [root]\n ans = Node(-1)\n while queue:\n n = len(queue)\n for i in range(n):\n curr = queue.pop(0)\n if curr.data == key and i != n - 1:\n return queue[0]\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n return ans", "from collections import deque\n\ndef nextRight(root, key):\n queue = [root]\n while queue != []:\n t2 = []\n for i in range(len(queue)):\n curr = queue[0]\n if curr.left != None:\n queue.append(curr.left)\n t2.append(curr.left)\n if curr.right != None:\n queue.append(curr.right)\n t2.append(curr.right)\n queue.pop(0)\n for i in range(len(t2)):\n if t2[i].data == key:\n try:\n return t2[i + 1]\n except IndexError:\n return Node(-1)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n q = deque()\n q.append(root)\n q.append(None)\n while q:\n dq = q.popleft()\n if dq is None:\n q.append(None)\n continue\n if dq.data == key:\n r = q.popleft()\n if r is None:\n return Node(-1)\n else:\n return r\n if dq.left:\n q.append(dq.left)\n if dq.right:\n q.append(dq.right)", "from collections import deque\n\ndef __init__():\n self.dp = dict()\n self.ans = -1\n\ndef tr(root, l, key):\n if root == None:\n return None\n elif self.dp.get(l) == key:\n self.ans = root.data\n self.dp[l] = root.data\n self.tr(root.left, l + 1, key)\n self.tr(root.right, l + 1, key)\n\ndef nextRight(root, key):\n self.tr(root, 0, key)\n return Node(self.ans)", "from collections import deque\n\ndef nextRight(root, key):\n result = self.myFunc(root, key, [], 0)\n return result[-1] if result else Node(-1)\n\ndef myFunc(root, key, path, level):\n if not root:\n return []\n if len(path) == level:\n path.append([])\n if root.data == key:\n return path[level].copy()\n path[level].append(root)\n level += 1\n result = []\n result += self.myFunc(root.right, key, path, level)\n result += self.myFunc(root.left, key, path, level)\n return result", "from collections import deque\n\ndef nextRight(root, key):\n if root == None or root.data == key:\n return Node(-1)\n que = deque()\n que.append(root)\n while que:\n n = len(que)\n for i in range(n):\n cur = que.popleft()\n if cur.data == key:\n if i < n - 1:\n return que.popleft()\n else:\n return Node(-1)\n if cur.left:\n que.append(cur.left)\n if cur.right:\n que.append(cur.right)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n if not root:\n return []\n curr = [root]\n while curr:\n next_level = []\n while curr:\n v = curr.pop(0)\n if key == v.data:\n if curr:\n return curr.pop(0)\n else:\n return Node(-1)\n if v.left:\n next_level.append(v.left)\n if v.right:\n next_level.append(v.right)\n curr = next_level\n return Node(-1)", "from collections import deque\n\ndef __init__(data):\n self.data = data\n self.left = None\n self.right = None\n\ndef nextRight(root, key):\n d = {}\n level = 0\n self.helper(root, level, d)\n a = 0\n b = 0\n l = []\n for i in d:\n for j in d[i]:\n if key == j.data:\n a = len(d[i])\n b = d[i].index(j)\n l = d[i]\n if a - 1 == b:\n n = Node(-1)\n return n\n else:\n return l[b + 1]\n\ndef helper(root, level, d):\n if not root:\n return\n if level not in d:\n d[level] = [root]\n else:\n d[level].append(root)\n self.helper(root.left, level + 1, d)\n self.helper(root.right, level + 1, d)", "def __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef nextRight(root, key):\n queue = []\n queue.append(root)\n while queue:\n l = len(queue)\n for i in range(l):\n p = queue.pop(0)\n if p.data == key:\n if i < l - 1:\n q = queue.pop(0)\n return q\n if i == l - 1:\n return Node(-1)\n if p.left != None:\n queue.append(p.left)\n if p.right != None:\n queue.append(p.right)\n return -1", "from collections import deque\n\ndef nextRight(root, key):\n\n def traversal(root, level):\n nonlocal f\n if root == None:\n return None\n if root.data == key:\n f = level\n return\n if root.left:\n traversal(root.left, level + 1)\n if root.right:\n traversal(root.right, level + 1)\n f = 0\n traversal(root, 0)\n\n def traversal2(root, level):\n if root == None:\n return None\n if level == 0:\n list1.append(root)\n else:\n traversal2(root.left, level - 1)\n traversal2(root.right, level - 1)\n list1 = []\n traversal2(root, f)\n length = len(list1)\n for i in range(length):\n if list1[i].data == key and i + 1 < length:\n return list1[i + 1]\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n q = deque()\n q.append(root)\n found = False\n ans = Node(-1)\n while True:\n nc = len(q)\n if nc == 0:\n return ans\n if found == True:\n return ans\n while nc > 0:\n node = q.popleft()\n if node.data == key:\n found = True\n nc -= 1\n continue\n elif found == True:\n return node\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n nc -= 1", "from collections import deque\n\ndef nextRight(root, key):\n\n def helper(root, mp, k):\n if root:\n if k in mp:\n mp[k].append(root.data)\n else:\n mp[k] = [root.data]\n helper(root.left, mp, k + 1)\n helper(root.right, mp, k + 1)\n return mp\n mp = {}\n helper(root, mp, 0)\n for k in mp:\n for i in range(len(mp[k])):\n if mp[k][i] == key:\n try:\n return Node(mp[k][i + 1])\n except:\n return Node(-1)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n\n def helper(root, key):\n x = []\n t = []\n q = []\n count = 0\n if not root:\n return x\n q.append(root)\n while q and count == 0:\n for i in range(len(q)):\n a = q.pop(0)\n if a.left:\n q.append(a.left)\n if a.right:\n q.append(a.right)\n t.append(a.data)\n if a.data == key:\n count += 1\n if count == 1:\n x = t\n return x\n a = helper(root, key)\n ans = Node\n ans.data = -1\n if not a:\n return ans\n for i in range(len(a) - 1):\n if a[i] == key:\n ans.data = a[i + 1]\n return ans\n return ans", "from collections import deque\n\ndef nextRight(root, key):\n queue = [root]\n while queue:\n temp = queue.copy()\n if temp[-1].data == key:\n return Node(-1)\n for i in range(len(temp)):\n if temp[i].data == key:\n return temp[i + 1]\n queue.clear()\n for e in temp:\n if e.left:\n queue.append(e.left)\n if e.right:\n queue.append(e.right)\n return -1", "from collections import deque\n\ndef nextRight(root, key):\n node = root\n q = [node]\n while q:\n c = len(q)\n temp = []\n for i in range(c):\n nd = q.pop(0)\n if nd.data == key:\n if q:\n return q[0]\n else:\n return Node(-1)\n else:\n if nd.left:\n temp.append(nd.left)\n if nd.right:\n temp.append(nd.right)\n while temp:\n q.append(temp.pop(0))\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n l = []\n q = []\n q.append(root)\n while q:\n t = len(q)\n temp = []\n for i in range(t):\n s = q.pop(0)\n if s.left:\n q.append(s.left)\n if s.right:\n q.append(s.right)\n temp.append(s.data)\n l.append(temp)\n for i in range(len(l)):\n if key in l[i]:\n a = l[i].index(key)\n if a == 0 and i == 0:\n return Node(-1)\n elif a == len(l[i]) - 1:\n return Node(-1)\n else:\n return Node(l[i][a + 1])", "from collections import deque\n\ndef nextRight(root, key):\n q = [root]\n while q:\n arr = q[0:]\n q = []\n for i in range(len(arr)):\n t = arr.pop(0)\n if t.data == key:\n if not arr:\n return Node(-1)\n return arr[0]\n if t.left:\n q.append(t.left)\n if t.right:\n q.append(t.right)", "from collections import deque\n\ndef nextRight(root, key):\n q = deque()\n q.append(root)\n prev = -1\n while q:\n ll = len(q)\n prev = -1\n for _ in range(ll):\n node = q.popleft()\n if prev == -1:\n pass\n elif prev.data == key:\n return node\n prev = node\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n if root is None:\n return Node(-1)\n q = [root]\n while q:\n temp = []\n while q:\n node = q.pop(0)\n if node.data == key:\n if q:\n return q[0]\n else:\n return Node(-1)\n if node.left:\n temp.append(node.left)\n if node.right:\n temp.append(node.right)\n q = temp\n return Node(-1)", "from collections import defaultdict\n\ndef nextRight(root, key):\n arr = defaultdict(list)\n\n def solve(root, level):\n if not root:\n return\n arr[level].append(root.data)\n solve(root.left, level + 1)\n solve(root.right, level + 1)\n solve(root, 0)\n for (k, value) in arr.items():\n for val in value:\n if val == key and value.index(val) < len(value) - 1:\n return Node(value[value.index(val) + 1])\n break\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n q = deque([root])\n while q:\n t = len(q)\n for i in range(t):\n node = q.popleft()\n if node:\n if node.data == key and i < t - 1:\n return q[0]\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n lis = list()\n lis.append([root, 0])\n level = 0\n di = dict()\n ans = -1\n while len(lis):\n (cur_node, level) = lis.pop(0)\n if cur_node.data == key:\n ans = level\n if level in di:\n di[level].append(cur_node)\n else:\n di[level] = list()\n di[level].append(cur_node)\n if cur_node.left:\n lis.append([cur_node.left, level + 1])\n if cur_node.right:\n lis.append([cur_node.right, level + 1])\n n = len(di[ans])\n for i in range(n):\n if i == n - 1 and key == di[ans][i].data:\n return Node(-1)\n elif key == di[ans][i].data:\n return di[ans][i + 1]", "import collections\nfrom collections import deque\n\ndef nextRight(root, key):\n if not root:\n return -1\n q = collections.deque()\n q.append(root)\n res = []\n while q:\n qLen = len(q)\n temp = []\n for i in range(qLen):\n node = q.popleft()\n temp.append(node)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n res.append(temp)\n for i in range(len(res)):\n for j in range(len(res[i])):\n if res[i][j].data == key:\n if j + 1 < len(res[i]):\n return res[i][j + 1]\n temp = Node(-1)\n return temp", "from collections import deque\n\ndef nextRight(root, key):\n queue = [root]\n while 1:\n nodes = len(queue)\n if nodes == 0:\n return Node(-1)\n for i in range(nodes):\n if queue[i].data == key and i != len(queue) - 1:\n return queue[i + 1]\n elif queue[i].data == key and i == len(queue) - 1:\n return Node(-1)\n while nodes > 0:\n node = queue.pop(0)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n nodes -= 1\n return Node(-1)", "import collections\nfrom collections import deque\n\ndef nextRight(root, key):\n q = collections.deque()\n q.append(root)\n while q:\n qLen = len(q)\n for i in range(qLen):\n cur = q.popleft()\n if not cur:\n continue\n if cur.data == key:\n return q[0] if i < qLen - 1 else Node(-1)\n if cur.left:\n q.append(cur.left)\n if cur.right:\n q.append(cur.right)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n q = [(root, 0)]\n while q:\n (x, l) = q.pop(0)\n if x.data == key:\n if q and q[0][1] == l:\n return q[0][0]\n return Node(-1)\n if x.left:\n q.append((x.left, l + 1))\n if x.right:\n q.append((x.right, l + 1))", "from collections import deque\n\ndef nextRight(root, key):\n dic = {}\n\n def levelOrder(node, level):\n if not node:\n return\n else:\n if node.data == key:\n dic[0] = level\n if level in dic:\n dic[level].append(node)\n else:\n dic[level] = [node]\n levelOrder(node.left, level + 1)\n levelOrder(node.right, level + 1)\n levelOrder(root, 1)\n givenLevel = dic[0]\n for i in range(len(dic[givenLevel])):\n if dic[givenLevel][i].data == key:\n if i == len(dic[givenLevel]) - 1:\n node = Node(-1)\n return node\n else:\n return dic[givenLevel][i + 1]\n return root", "from collections import deque\n\ndef nextRight(root, key):\n errorNode = Node(-1)\n inspectList = [root]\n while len(inspectList) > 0:\n tmp = []\n for (i, target) in enumerate(inspectList):\n if target.data == key:\n if i == len(inspectList) - 1:\n return errorNode\n else:\n return inspectList[i + 1]\n else:\n if target.left != None:\n tmp.append(target.left)\n if target.right != None:\n tmp.append(target.right)\n inspectList = tmp\n return errorNode", "from collections import deque\n\ndef nextRight(root, key):\n ret = Node(-1)\n if root == None:\n return ret\n q = deque()\n q.append(root)\n while len(q):\n l = len(q)\n for i in range(l):\n node = q.popleft()\n if node.data == key:\n if len(q) == 0:\n return ret\n if i + 1 < l:\n return q.popleft()\n return ret\n if node.left is not None:\n q.append(node.left)\n if node.right is not None:\n q.append(node.right)\n return ret", "from collections import deque\n\ndef find(lt, k):\n if lt[-1].data == k:\n n = Node(-1)\n return n\n for i in range(len(lt)):\n if lt[i].data == k and i + 1 < len(lt):\n return lt[i + 1]\n\ndef level(lt):\n lt1 = []\n for i in lt:\n if i.left != None:\n lt1.append(i.left)\n if i.right != None:\n lt1.append(i.right)\n return lt1\n\ndef nextRight(root, key):\n lt = [root]\n while self.find(lt, key) == None:\n lt = self.level(lt)\n return self.find(lt, key)", "from collections import deque\n\ndef nextRight(root, key):\n if not root or root.data == key:\n return Node(-1)\n res = []\n q = [root]\n idx = -1\n while len(q) > 0:\n children = []\n nq = []\n while q:\n element = q.pop(0)\n if element.data == key:\n if len(q) > 0:\n return q[0]\n else:\n return Node(-1)\n if element.left:\n nq.append(element.left)\n if element.right:\n nq.append(element.right)\n q.extend(nq)\n res.append(children)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n nodeQueue = []\n nodeQueue.append({'node': root, 'level': 0})\n while len(nodeQueue) > 0:\n current = nodeQueue.pop(0)\n if current['node'].data == key:\n if len(nodeQueue) == 0:\n return Node(-1)\n if nodeQueue[0]['level'] != current['level']:\n return Node(-1)\n return nodeQueue[0]['node']\n currentLevel = current['level']\n if current['node'].left:\n nodeQueue.append({'node': current['node'].left, 'level': currentLevel + 1})\n if current['node'].right:\n nodeQueue.append({'node': current['node'].right, 'level': currentLevel + 1})", "from collections import deque\n\ndef __init__():\n self.d = dict()\n\ndef findNext(root, key, level):\n if root is None:\n return\n if level not in self.d:\n self.d[level] = list()\n self.d[level].append(root)\n self.findNext(root.left, key, level + 1)\n self.findNext(root.right, key, level + 1)\n\ndef nextRight(root, key):\n self.findNext(root, key, 0)\n for i in self.d:\n l = len(self.d[i])\n for j in range(l):\n if self.d[i][j].data == key:\n if j == l - 1:\n return Node(-1)\n else:\n return self.d[i][j + 1]", "from collections import deque\n\ndef __init__():\n self.levels = {}\n self.keyLevel = None\n\ndef nextRight(root, key):\n self.traverse(root, 0, key)\n return self.findRight(key)\n\ndef traverse(node, level, key):\n if node == None:\n return\n if node.data == key:\n self.keyLevel = level\n if level not in self.levels:\n self.levels[level] = []\n self.levels[level].append(node.data)\n self.traverse(node.left, level + 1, key)\n self.traverse(node.right, level + 1, key)\n\ndef findRight(key):\n levelNodes = self.levels[self.keyLevel]\n rightNodeIndex = levelNodes.index(key) + 1\n if rightNodeIndex > len(levelNodes) - 1:\n return Node(-1)\n return Node(levelNodes[rightNodeIndex])", "from collections import deque\n\ndef nextRight(root, key):\n if not root:\n return root\n q = deque([])\n q.append(root)\n found = False\n node = Node(-1)\n while q:\n l = len(q)\n curr = []\n for i in range(l):\n t = q.popleft()\n if found:\n return t\n if t.data == key:\n found = True\n curr.append(t)\n if t.left:\n q.append(t.left)\n if t.right:\n q.append(t.right)\n found = False\n return node", "from collections import deque\n\ndef nextRight(root, key):\n queue1 = deque()\n queue2 = deque()\n queue1.append(root)\n while queue1:\n pr = queue1.popleft()\n if pr.data == key:\n if queue1:\n return queue1.popleft()\n else:\n return Node(-1)\n if pr.left:\n queue2.append(pr.left)\n if pr.right:\n queue2.append(pr.right)\n if not queue1:\n queue1 = queue2\n queue2 = deque()", "def nextRight(root, key):\n if root.data == key:\n return Node(-1)\n queue = [root]\n data_list = [[root]]\n while queue:\n found = False\n node_queue = []\n for node in queue:\n if node.left:\n if node.left.data == key:\n found = True\n node_queue.append(node.left)\n if node.right:\n if node.right.data == key:\n found = True\n node_queue.append(node.right)\n if found:\n for i in range(len(node_queue)):\n if node_queue[i].data == key:\n if i + 1 < len(node_queue):\n return node_queue[i + 1]\n else:\n return Node(-1)\n data_list.append(node_queue)\n queue = node_queue\n return Node(-1)", "from collections import deque\n\ndef levelBFS(root, key):\n queue = [root]\n data_list = [[root]]\n if queue[0].data == key:\n return Node(-1)\n while queue:\n found = False\n node_queue = []\n for node in queue:\n if node.left:\n if node.left.data == key:\n found = True\n node_queue.append(node.left)\n if node.right:\n if node.right.data == key:\n found = True\n node_queue.append(node.right)\n if found:\n for i in range(len(node_queue)):\n if node_queue[i].data == key:\n if i + 1 < len(node_queue):\n return node_queue[i + 1]\n data_list.append(node_queue)\n queue = node_queue\n return Node(-1)\n\ndef nextRight(root, key):\n return self.levelBFS(root, key)", "from collections import deque\n\ndef levelBFS(root):\n queue = [root]\n data_list = [[root]]\n while queue:\n node_queue = []\n for node in queue:\n if node.left:\n node_queue.append(node.left)\n if node.right:\n node_queue.append(node.right)\n data_list.append(node_queue)\n queue = node_queue\n return data_list\n\ndef nextRight(root, key):\n if root.data == key:\n return Node(-1)\n l = self.levelBFS(root)\n for i in l:\n for j in range(len(i)):\n if i[j].data == key:\n if j + 1 < len(i):\n return i[j + 1]\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n if root == None:\n return 0\n qn = deque()\n ql = deque()\n level = 0\n qn.append(root)\n ql.append(level)\n while len(qn) > 0:\n node = qn.popleft()\n level = ql.popleft()\n if node.data == key:\n if len(ql) == 0 or ql[0] != level:\n ret = Node(-1)\n return ret\n return qn[0]\n if node.left != None:\n qn.append(node.left)\n ql.append(level + 1)\n if node.right != None:\n qn.append(node.right)\n ql.append(level + 1)\n ret = Node(-1)\n return ret", "from collections import deque\n\ndef nextRight(root, key):\n if root == None:\n return Node(-1)\n q = []\n q.append(root)\n res = [root.data]\n while len(q) > 0:\n for i in range(len(res)):\n if res[i] == key:\n if i + 1 < len(res):\n return Node(res[i + 1])\n else:\n return Node(-1)\n res = []\n for i0 in range(len(q)):\n temp = q.pop(0)\n if temp.left:\n q.append(temp.left)\n res.append(temp.left.data)\n if temp.right:\n q.append(temp.right)\n res.append(temp.right.data)", "from collections import deque\n\ndef nextRight(root, key):\n if root is None:\n return Node(-1)\n queue = []\n queue.append(root)\n while queue:\n len_q = len(queue)\n for i in range(len_q):\n node = queue.pop(0)\n if node.data == key:\n if i + 1 < len_q:\n right_node = queue.pop(0)\n return right_node\n else:\n return Node(-1)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return Node(-1)", "from collections import deque\nfrom collections import deque\n\ndef nextRight(root, key):\n queue = deque()\n queue.append(root)\n length = len(queue)\n flag = False\n while queue:\n current = queue.popleft()\n length -= 1\n if current.left is not None:\n queue.append(current.left)\n if current.left.data == key:\n flag = True\n elif flag == True:\n return current.left\n if current.right is not None:\n queue.append(current.right)\n if current.right.data == key:\n flag = True\n elif flag == True:\n return current.right\n if length == 0:\n if flag == True:\n return Node(-1)\n length = len(queue)\n return Node(-1)", "from collections import deque\n\ndef findKeyParent(node, key):\n if node.left != None:\n if node.left.data == key:\n return node\n if node.right != None:\n if node.right.data == key:\n return node\n if not node.left == None:\n left = self.findKeyParent(node.left, key)\n if not left == None:\n return left\n if not node.right == None:\n left = self.findKeyParent(node.right, key)\n if not left == None:\n return left\n return None\n\ndef getTree(node, tree=None, depth=0):\n if tree == None:\n tree = [[node.data]]\n else:\n tree[depth].append(node.data)\n if len(tree) == depth + 1:\n tree.append([])\n if node.left == None:\n tree[depth + 1].append('N')\n else:\n tree = self.getTree(node.left, tree, depth + 1)\n if node.right == None:\n tree[depth + 1].append('N')\n else:\n tree = self.getTree(node.right, tree, depth + 1)\n return tree\n\ndef nextRight(root, key):\n tree = self.getTree(root)\n keyFound = False\n for depth in tree[1:]:\n if keyFound == True:\n return Node(-1)\n for element in depth:\n if keyFound == True:\n if element != 'N':\n return Node(element)\n elif element == key:\n keyFound = True\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n if root == None or root.data == key:\n return Node(-1)\n nodes = [root]\n node = root\n found_key = False\n found_right = False\n while nodes != []:\n new_nodes = []\n for node in nodes:\n if node.left != None:\n new_nodes.append(node.left)\n if node.left.data == key:\n found_key = True\n elif found_key:\n found_right = True\n return node.left\n if node.right != None:\n new_nodes.append(node.right)\n if node.right.data == key:\n found_key = True\n elif found_key:\n found_right = True\n return node.right\n if found_key:\n break\n (nodes, new_nodes) = (new_nodes, [])\n return Node(-1)"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["10\r\n / \\\r\n 2 6\r\n / \\ \\\r\n 8 4 5\r\nand key = 2", "10\r\n / \\\r\n 2 6\r\n / \\ \\\r\n 8 4 5\r\nand key = 5"], "outputs": ["6", "-1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Tree", "Traversal", "Queue", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures", "Graph traversal"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/next-right-node/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "__init__", "task_id": "TACO_lite/202", "example": [[[10, [2, 6], [8, 4, null, 5], 2], [10, [2, 6], [8, 4, null, 5], 5]], ["6", "-1"]]} +{"requirement": "Your task is to write a function that takes two or more objects and returns a new object which combines all the input objects. \n\nAll input object properties will have only numeric values. Objects are combined together so that the values of matching keys are added together.\n\nAn example:\n\n```python\nobjA = { 'a': 10, 'b': 20, 'c': 30 }\nobjB = { 'a': 3, 'c': 6, 'd': 3 }\ncombine(objA, objB) # Returns { a: 13, b: 20, c: 36, d: 3 }\n```\n\nThe combine function should be a good citizen, so should not mutate the input objects.", "solutions": ["def combine(*bs):\n c = {}\n for b in bs:\n for (k, v) in list(b.items()):\n c[k] = v + c.get(k, 0)\n return c", "from collections import Counter\n\ndef combine(*args):\n return sum((Counter(a) for a in args), Counter())", "def combine(*dictionaries):\n result = {}\n for dict in dictionaries:\n for (key, value) in list(dict.items()):\n result[key] = value + result.get(key, 0)\n return result", "from collections import defaultdict\n\ndef combine(*dicts):\n ret = defaultdict(int)\n for d in dicts:\n for (k, v) in d.items():\n ret[k] += v\n return dict(ret)", "from collections import Counter\n\ndef combine(*args):\n return sum(map(Counter, args), Counter())", "def combine(*args):\n rez = {}\n for i in args:\n for (k, v) in i.items():\n rez[k] = rez.get(k, 0) + v\n return rez", "def combine(*args):\n result = {}\n for obj in args:\n for (key, value) in obj.items():\n if not key in result:\n result[key] = 0\n result[key] += value\n return result", "def combine(*args):\n ret = {}\n for arg in args:\n for (k, v) in arg.items():\n ret.setdefault(k, 0)\n ret[k] = ret[k] + v\n return ret", "def combine(*args):\n keys = set([y for x in args for y in list(x.keys())])\n return {k: sum([a.get(k, 0) for a in args]) for k in keys}"], "starter_code": "def combine(*args):\n", "input_output": {"fn_name": "combine", "inputs": [[{}, {}, {}], [{}]], "outputs": [[{}], [{}]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/56bd9e4b0d0b64eaf5000819", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "combine", "task_id": "TACO_lite/231", "example": [[[{"a": 10, "b": 20, "c": 30}, {"a": 3, "c": 6, "d": 3}]], ["{'a': 13, 'b': 20, 'c': 36, 'd': 3}"]]} +{"requirement": "You have recently discovered that horses travel in a unique pattern - they're either running (at top speed) or resting (standing still).\n\nHere's an example of how one particular horse might travel:\n\n```\nThe horse Blaze can run at 14 metres/second for 60 seconds, but must then rest for 45 seconds.\n\nAfter 500 seconds Blaze will have traveled 4200 metres.\n```\n\nYour job is to write a function that returns how long a horse will have traveled after a given time.\n\n####Input: \n\n* totalTime - How long the horse will be traveling (in seconds)\n\n* runTime - How long the horse can run for before having to rest (in seconds)\n\n* restTime - How long the horse have to rest for after running (in seconds)\n\n* speed - The max speed of the horse (in metres/second)", "solutions": ["def travel(total_time, run_time, rest_time, speed):\n (q, r) = divmod(total_time, run_time + rest_time)\n return (q * run_time + min(r, run_time)) * speed", "def travel(total_time, run_time, rest_time, speed):\n (d, m) = divmod(total_time, run_time + rest_time)\n return (d * run_time + min(m, run_time)) * speed", "def travel(total_time, run_time, rest_time, speed):\n (cycle, left) = divmod(total_time, run_time + rest_time)\n return cycle * run_time * speed + min(left, run_time) * speed", "def travel(total_time, run_time, rest_time, speed):\n (cycles, remaining) = divmod(total_time, run_time + rest_time)\n last_run = min(remaining, run_time)\n return (cycles * run_time + last_run) * speed\n\ndef travel(total, run, rest, speed):\n return (total // (run + rest) * run + min(total % (run + rest), run)) * speed", "def travel(total_time, run_time, rest_time, speed):\n return speed * (run_time * (total_time // (run_time + rest_time)) + min(run_time, total_time % (run_time + rest_time)))", "def travel(total_time, run_time, rest_time, speed):\n (runs, extra) = divmod(total_time, run_time + rest_time)\n return (runs * run_time + min(extra, run_time)) * speed", "def travel(total_time, run_time, rest_time, speed):\n (x, y) = divmod(total_time, run_time + rest_time)\n return (x * run_time + min(y, run_time)) * speed", "def travel(total_time, run_time, rest_time, speed):\n av_speed = speed * run_time / (run_time + rest_time)\n av_time = total_time // (run_time + rest_time)\n r_time = total_time - av_time * (run_time + rest_time)\n return round(av_time * (run_time + rest_time) * av_speed + run_time * speed) if run_time < r_time else round(av_time * (run_time + rest_time) * av_speed + r_time * speed)", "def travel(total_time, run_time, rest_time, speed):\n run_periods = float(total_time) / (run_time + rest_time)\n last_run_time = min(run_periods - int(run_periods), float(run_time) / (run_time + rest_time)) * (run_time + rest_time)\n total_run_time = int(run_periods) * run_time + last_run_time\n return round(total_run_time * speed)", "def travel(total_time, run_time, rest_time, speed):\n (s, is_running) = (0, True)\n while total_time:\n if is_running:\n s += min(total_time, run_time) * speed\n total_time -= min(total_time, run_time) if is_running else min(rest_time, total_time)\n is_running = not is_running\n return s"], "starter_code": "def travel(total_time, run_time, rest_time, speed):\n", "input_output": {"fn_name": "travel", "inputs": [[1000, 10, 127, 14], [1000, 10, 0, 10], [25, 50, 120, 18], [35869784, 90, 100, 5], [1234567, 4, 3, 11], [100000000, 21, 5, 14], [0, 100, 10, 14], [250, 0, 5, 14], [100, 10, 0, 14], [500, 100, 10, 0]], "outputs": [[1120], [10000], [450], [84954920], [7760148], [1130769276], [0], [0], [1400], [0]]}, "difficulty": "EASY", "raw_tags": ["Puzzles"], "name": null, "source": "codewars", "tags": ["Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/56d46b8fda159582e100001b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "travel", "task_id": "TACO_lite/257", "example": [[[500, 60, 45, 14]], ["4200"]]} +{"requirement": "Given a mixed array of number and string representations of integers, add up the string integers and subtract this from the total of the non-string integers. \n\nReturn as a number.", "solutions": ["def div_con(lst):\n return sum((n if isinstance(n, int) else -int(n) for n in lst))", "def div_con(x):\n return sum([a for a in x if isinstance(a, int)]) - sum([int(a) for a in x if not isinstance(a, int)])", "def div_con(x):\n integer = []\n string = []\n for element in x:\n if type(element) == int:\n integer.append(element)\n else:\n string.append(int(element))\n return sum(integer) - sum(string)", "def div_con(x):\n sum = 0\n for i in x:\n if type(i) == int:\n sum += i\n else:\n sum -= int(i)\n return sum", "def div_con(x):\n return sum((-int(i) if isinstance(i, str) else i for i in x))", "def div_con(x):\n diff = 0\n for num in x:\n if isinstance(num, int):\n diff += num\n else:\n diff -= int(num)\n return diff", "div_con = lambda l: sum((e if type(e) == int else -int(e) for e in l))", "def div_con(x):\n num = 0\n strnum = 0\n for number in x:\n if int(number) == number:\n num = num + number\n else:\n strnum = strnum + int(number)\n num = num - strnum\n return num", "div_con = lambda x: sum((i for i in x if type(i) == int)) - sum((int(s) for s in x if type(s) == str))"], "starter_code": "def div_con(x):\n", "input_output": {"fn_name": "div_con", "inputs": [[[9, 3, "7", "3"]], [["5", "0", 9, 3, 2, 1, "9", 6, 7]], [["3", 6, 6, 0, "5", 8, 5, "6", 2, "0"]], [["1", "5", "8", 8, 9, 9, 2, "3"]], [[8, 0, 0, 8, 5, 7, 2, 3, 7, 8, 6, 7]]], "outputs": [[2], [14], [13], [11], [61]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57eaec5608fed543d6000021", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "div_con", "task_id": "TACO_lite/203", "example": [[[[1, "2", 3, "4", 5]], [[10, "20", "30", 40, "50"]], [[100, "200", 300, "400", 500]]], ["3", "-50", "300"]]} +{"requirement": "Given string s consisting of digits 0-9 and a number N, the task is to count the number of subsequences that are divisible by N.\nNote: Answer can be large, output answer modulo 10^{9} + 7\nExample 1:\nInput: s = \"1234\", N = 4\nOutput: 4\nExplanation: The subsequences 4, 12, 24 and \n124 are divisible by 4.\nExample 2:\nInput: s = \"330\", N = 6\nOutput: 4\nExplanation: The subsequences 30, 30, 330 \nand 0 are divisible by 6.\nYour Task: \nYou don't need to read input or print anything. Complete the function countDivisibleSubseq() which takes s and N as input parameters and returns the integer value\nExpected Time Complexity: O(|s|*N)\nExpected Auxiliary Space: O(|s|*N)\nConstraints:\n1 ≤ |s|*N ≤ 10^{6}", "solutions": ["def countdivisiblesubseq(str, n):\n mod = int(1000000000.0 + 7)\n l = len(str)\n dp = [[0 for x in range(l)] for y in range(n)]\n dp[int(str[0]) % n][0] += 1\n for i in range(1, l):\n dp[int(str[i]) % n][i] += 1\n for j in range(n):\n dp[j][i] += dp[j][i - 1]\n dp[(j * 10 + int(str[i])) % n][i] += dp[j][i - 1]\n return dp[0][l - 1] % mod", "def countdivisiblesubseq(s, N):\n mod = int(1000000007)\n l = len(s)\n dp = [[0 for x in range(n)] for y in range(l)]\n for i in range(0, l):\n dp[i][int(s[i]) % N] = 1\n dp[i][int(s[i]) % N] = dp[i][int(s[i]) % N] % mod\n for i in range(1, l):\n for j in range(0, N):\n dp[i][j] += dp[i - 1][j]\n dp[i][j] = dp[i][j] % mod\n dp[i][(j * 10 + int(s[i])) % N] += dp[i - 1][j]\n dp[i][(j * 10 + int(s[i])) % N] = dp[i][(j * 10 + int(s[i])) % N] % mod\n return dp[l - 1][0] % mod", "def countdivisiblesubseq(s, N):\n MOD = 10 ** 9 + 7\n\n def rec(index, rem):\n if index == len(s):\n return int(rem == 0)\n nt = rec(index + 1, rem)\n tk = rec(index + 1, (rem * 10 + int(s[index])) % N)\n return nt + tk\n dp = [[-1 for _ in range(N + 1)] for _ in range(len(s) + 1)]\n\n def mem(index, rem):\n if index == len(s):\n return int(rem == 0)\n if dp[index][rem] != -1:\n return dp[index][rem]\n nt = mem(index + 1, rem)\n tk = mem(index + 1, (rem * 10 + int(s[index])) % N)\n dp[index][rem] = nt + tk\n return dp[index][rem]\n return mem(0, N) % MOD\n return rec(0, N) % MOD", "def countdivisiblesubseq(s, n):\n l = len(s)\n dp = [[0 for x in range(l)] for y in range(n)]\n dp[int(s[0]) % n][0] += 1\n for i in range(1, l):\n dp[int(s[i]) % n][i] += 1\n for j in range(n):\n dp[j][i] += dp[j][i - 1]\n dp[(j * 10 + int(s[i])) % n][i] += dp[j][i - 1]\n return dp[0][l - 1] % (7 + 10 ** 9)", "def getcount(s, idx, rem, k, memo):\n n = len(s)\n if idx == n:\n return 1 if rem == 0 else 0\n if hashed(idx, rem) in memo:\n return memo[hashed(idx, rem)]\n count = 0\n count += getcount(s, idx + 1, rem, k, memo)\n count += getcount(s, idx + 1, (rem * 10 + int(s[idx])) % k, k, memo)\n memo[hashed(idx, rem)] = count\n return count\n\ndef hashed(a, b):\n return str(a) + ':' + str(b)\n\ndef countdivisiblesubseq(s, N):\n memo = {}\n s = str(s)\n return (getcount(s, 0, 0, N, memo) - 1) % (10 ** 9 + 7)"], "starter_code": "def countdivisiblesubseq(s, N):\n", "input_output": {"inputs": ["s = \"1234\", N = 4", "s = \"330\", N = 6"], "outputs": ["4", "4"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/number-of-subsequences-in-a-string-divisible-by-n5947/1", "Expected Auxiliary Space": "O(|s|*N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|s|*N)", "entry_point": "countdivisiblesubseq", "task_id": "TACO_lite/251", "example": [[["1234", 4], ["330", 6]], ["4", "4"]]} +{"requirement": "Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. The fractions can be in any order.\n \nExample 1:\nInput: n = 2\nOutput: [\"1/2\"]\nExplanation: \"1/2\" is the only unique fraction with a denominator less-than-or-equal-to 2.\nExample 2:\nInput: n = 3\nOutput: [\"1/2\",\"1/3\",\"2/3\"]\n\nExample 3:\nInput: n = 4\nOutput: [\"1/2\",\"1/3\",\"1/4\",\"2/3\",\"3/4\"]\nExplanation: \"2/4\" is not a simplified fraction because it can be simplified to \"1/2\".\nExample 4:\nInput: n = 1\nOutput: []\n\n \nConstraints:\n\n1 <= n <= 100", "solutions": ["def simplifiedfractions(n: int) -> List[str]:\n fractions = []\n decimals = set()\n for denom in range(1, n + 1):\n for num in range(1, denom + 1):\n if num % denom != 0 and num / denom not in decimals:\n decimals.add(num / denom)\n fractions.append(str(num) + '/' + str(denom))\n return fractions", "import math\n\ndef simplifiedfractions(n: int) -> List[str]:\n\n def recurse(curr_n):\n if curr_n == 1:\n return []\n else:\n curr_arr = []\n init_val = '1/' + str(curr_n)\n curr_arr.append(init_val)\n for i in range(2, curr_n):\n denom = str(curr_n)\n if math.gcd(curr_n, i) == 1:\n numer = str(i)\n val = numer + '/' + denom\n curr_arr.append(val)\n return curr_arr + recurse(curr_n - 1)\n return recurse(n)", "def simplifiedfractions(n: int) -> List[str]:\n res = []\n for i in range(1, n):\n for j in range(i + 1, n + 1):\n if self.gcd(i, j) == 1:\n res.append(str(i) + '/' + str(j))\n return res\n\ndef gcd(a, b):\n while b:\n (a, b) = (b, a % b)\n return abs(a)", "def simplifiedfractions(n: int) -> List[str]:\n r = set()\n for i in range(2, n + 1):\n for j in range(1, i):\n cd = gcd(i, j)\n r.add(str(j // cd) + '/' + str(i // cd))\n return r", "def simplifiedfractions(n: int) -> List[str]:\n res = []\n s = set()\n for i in range(1, n + 1):\n for j in range(1, i):\n if i % j != 0 or j == 1:\n if j / i not in s:\n res.append(str(j) + '/' + str(i))\n s.add(j / i)\n return res", "def simplifiedfractions(n: int) -> List[str]:\n ret = []\n\n def gcd(numerator, denominator):\n if numerator == 0:\n return denominator\n return gcd(denominator % numerator, numerator)\n for numerator in range(1, n + 1):\n for denominator in range(numerator + 1, n + 1):\n if numerator != denominator:\n if gcd(numerator, denominator) == 1:\n ret.append(str(numerator) + '/' + str(denominator))\n return ret", "def simplifiedfractions(n: int) -> List[str]:\n\n def gcd(a, b):\n if a < b:\n (a, b) = (b, a)\n while b != 0:\n (a, b) = (b, a % b)\n return a\n sol = []\n for denom in range(2, n + 1):\n for numer in range(1, denom):\n if numer == 1 or gcd(numer, denom) == 1:\n sol.append(str(numer) + '/' + str(denom))\n return sol", "def simplifiedfractions(n: int) -> List[str]:\n outputs = []\n for i in range(2, n + 1):\n for j in range(1, i):\n if self._gcd(i, j) == 1:\n outputs.append(f'{j}/{i}')\n return outputs\n\ndef _gcd(i: int, j: int):\n if i > j:\n (i, j) = (j, i)\n res = j % i\n if res == 0:\n return i\n else:\n return self._gcd(i, res)", "def gcd(a, b):\n if b == 0:\n return a\n return gcd(b, a % b)\n\ndef simplifiedfractions(n: int) -> List[str]:\n res = []\n for i in range(1, n + 1):\n for j in range(i + 1, n + 1):\n if gcd(i, j) == 1:\n res.append('{}/{}'.format(i, j))\n return res", "def findGCD(a: int, b: int) -> int:\n (a, b) = (a, b) if a > b else (b, a)\n while a != 1 or b != 1:\n if a % b:\n (a, b) = (b, a % b)\n else:\n break\n return b\n\ndef simplifiedfractions(n: int) -> List[str]:\n ret = set()\n for denominator in range(2, n + 1):\n for numerator in range(1, denominator):\n gcd = self.findGCD(denominator, numerator)\n ret.add(f'{numerator // gcd}/{denominator // gcd}')\n return list(ret)", "def simplifiedfractions(n: int) -> List[str]:\n res = []\n for idx in range(2, n + 1):\n for idx2 in range(1, idx):\n if idx2 == 1 or self.get_gcd(idx, idx2) == 1:\n res.append('{}/{}'.format(idx2, idx))\n return res\n\ndef get_gcd(num1, num2):\n if num1 % num2 == 0:\n return num2\n return self.get_gcd(num2, num1 % num2)", "def simplifiedfractions(n: int) -> List[str]:\n ret = set()\n\n def gcd(a, b):\n while True:\n q = a // b\n r = a - b * q\n if r == 0:\n return b\n a = b\n b = r\n for i in range(2, n + 1):\n for j in range(1, i):\n t = gcd(i, j)\n ret.add(f'{j // t}/{i // t}')\n return list(ret)", "def gcd(a, b):\n c = 1\n while c != 0:\n c = a % b\n a = b\n b = c\n return a\n\ndef simplify(a, b):\n d = self.gcd(a, b)\n return (a // d, b // d)\n\ndef simplifiedfractions(n):\n fractions = set()\n for denom in range(1, n + 1):\n for num in range(1, denom):\n expr = '%d/%d' % self.simplify(num, denom)\n if expr not in fractions:\n fractions.add(expr)\n return list(fractions)", "def simplifiedfractions(n: int) -> List[str]:\n l = []\n for i in range(2, n + 1):\n for j in range(1, i):\n if math.gcd(i, j) < 2:\n l += [f'{j}/{i}']\n return l", "def euclid(a, b):\n if b == 0:\n return a\n else:\n return self.euclid(b, a % b)\n\ndef simplifiedfractions(n: int) -> List[str]:\n res = []\n for d in range(2, n + 1):\n for n in range(1, d):\n if self.euclid(n, d) > 1:\n continue\n res.append(str(n) + '/' + str(d))\n return res", "def simplifiedfractions(n):\n res = []\n tmp = set()\n for i in range(1, n + 1):\n for x in range(1, i + 1):\n if x % i != 0 and x / i not in tmp:\n tmp.add(x / i)\n res.append(str(x) + '/' + str(i))\n return res", "def simplifiedfractions(n: int) -> List[str]:\n ans = set()\n for m in range(2, n + 1):\n for i in range(1, m):\n d = math.gcd(i, m)\n if d > 1:\n ans.add(f'{i // d}/{m // d}')\n else:\n ans.add(f'{i}/{m}')\n return ans", "def simplifiedfractions(n: int) -> List[str]:\n ans = []\n q = deque([])\n for i in range(2, n + 1):\n q.append((1, i))\n while q:\n (x, y) = q.popleft()\n if x == 1 or math.gcd(x, y) == 1:\n ans.append(f'{x}/{y}')\n if x + 1 < y:\n q.append((x + 1, y))\n return ans", "def simplifiedfractions(n: int) -> List[str]:\n fin = []\n for i in range(2, n + 1):\n for j in range(1, i):\n if gcd(i, j) == 1:\n fin.append(str(j) + '/' + str(i))\n return fin", "def simplifiedfractions(n: int) -> List[str]:\n res = []\n\n def gcd(x, y):\n while y:\n (x, y) = (y, x % y)\n return x\n for i in range(1, n + 1):\n for j in range(1, i):\n if gcd(i, j) == 1:\n res.append(str(j) + '/' + str(i))\n return res", "def simplifiedfractions(n: int) -> List[str]:\n added = set()\n result = []\n for denominator in range(2, n + 1):\n for i in range(1, denominator):\n if i / denominator in added:\n continue\n added.add(i / denominator)\n result.append(f'{i}/{denominator}')\n return result", "def simplifiedfractions(n: int) -> List[str]:\n output = []\n for n in range(2, n + 1):\n for m in range(1, n):\n if math.gcd(n, m) == 1:\n output.append(str(m) + '/' + str(n))\n return output", "def simplifiedfractions(n: int) -> List[str]:\n\n def gcd(a: int, b: int) -> int:\n if a < b:\n (a, b) = (b, a)\n if b == 0:\n return a\n return gcd(b, a % b)\n out = []\n for denom in range(2, n + 1):\n for num in range(1, denom):\n if gcd(denom, num) == 1:\n out.append(str(num) + '/' + str(denom))\n return out", "def simplifiedfractions(n: int) -> List[str]:\n if n < 2:\n return []\n else:\n res = []\n dicts = {}\n grid = [1] * n\n grid[0] = 0\n for i in range(1, n):\n target = i + 1\n if grid[target - 1] == 1:\n dicts[target] = {target: 1}\n start = target * 2\n while start <= n:\n grid[start - 1] = 0\n dicts[target][start] = 1\n start += target\n for i in range(2, n + 1):\n res.append('1/' + str(i))\n for j in range(2, i):\n found = True\n de = j\n candidates = []\n for (key, value) in list(dicts.items()):\n if de in value:\n candidates.append(key)\n for can in candidates:\n if i in dicts[can]:\n found = False\n break\n if found:\n res.append(str(j) + '/' + str(i))\n return res", "def simplifiedfractions(n: int) -> List[str]:\n\n def gcd(a, b):\n for i in range(a):\n if b % (a - i) == 0 and a % (a - i) == 0:\n return a - i\n ans = []\n for i in range(2, n + 1):\n for j in range(1, i):\n if gcd(j, i) == 1:\n ans.append(f'{j}/{i}')\n return ans", "def simplifiedfractions(n: int) -> List[str]:\n\n def maxm(n1, n2):\n temp = min(n1, n2)\n while temp:\n if n1 % temp == 0 and n2 % temp == 0:\n return temp\n temp -= 1\n res = []\n for j in range(2, n + 1):\n for i in range(1, j):\n if maxm(j, i) > 1:\n continue\n res.append(str(i) + '/' + str(j))\n return res", "def simplifiedfractions(n: int) -> List[str]:\n fractions = set()\n for i in range(2, n + 1):\n for j in range(1, i):\n denom = i\n num = j\n changed = True\n while changed:\n changed = False\n for k in range(2, num + 1):\n if denom % k == 0 and num % k == 0:\n denom = denom // k\n num = num // k\n changed = True\n fractions.add(str(num) + '/' + str(denom))\n return [i for i in fractions]", "def simplifiedfractions(n: int) -> List[str]:\n\n def gcd(i, j):\n (i, j) = sorted([i, j])\n if j % i == 0:\n return i\n return gcd(i, j % i)\n res = []\n for d in range(1, n + 1):\n for n in range(1, n + 1):\n if 0 < n / d < 1 and gcd(d, n) == 1:\n res.append('{}/{}'.format(n, d))\n return res", "def simplifiedfractions(n: int) -> List[str]:\n if n < 2:\n return []\n if n == 2:\n return ['1/2']\n ans = []\n record = {}\n for i in range(2, n):\n a = 1\n b = i\n while b <= n:\n for c in range(1, b):\n if c / b not in record:\n ans.append('{}/{}'.format(c, b))\n record[c / b] = True\n b += 1\n return ans", "def simplifiedfractions(n: int) -> List[str]:\n out = []\n visited = set()\n if n == 1:\n return out\n for i in range(2, n + 1):\n for j in range(1, i):\n tmp = f'{j}/{i}'\n if eval(tmp) not in visited:\n visited.add(eval(tmp))\n out.append(tmp)\n return out", "def simplifiedfractions(n: int) -> List[str]:\n res = []\n num_res = []\n for i in range(1, n + 1):\n for j in range(1, i):\n if i / j not in num_res:\n res.append(str(j) + '/' + str(i))\n num_res.append(i / j)\n return res", "import itertools\n\ndef simplifiedfractions(n: int) -> List[str]:\n res = []\n num_res = []\n for (i, j) in itertools.permutations(range(1, n + 1), 2):\n if i / j < 1 and i / j not in num_res:\n res.append(str(i) + '/' + str(j))\n num_res.append(i / j)\n return res", "def simplifiedfractions(n: int) -> List[str]:\n\n def gcd(a, b):\n if a < b:\n return gcd(b, a)\n while b > 0:\n tmp = a % b\n a = b\n b = tmp\n return a\n ans = []\n if -1 < n < 2:\n return ans\n for i in range(1, n):\n for j in range(i + 1, n + 1):\n if i != j:\n x = gcd(i, j)\n n1 = i\n n2 = j\n if i % x == 0 == j % x and x > 1:\n n1 //= x\n n2 //= x\n st = f'{n1}/{n2}'\n if st not in ans:\n ans.append(st)\n return ans", "def isprime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i = i + 6\n return True\n\ndef simplifiedfractions(n: int) -> List[str]:\n from fractions import Fraction\n p = []\n if n == 1:\n return\n for numerator in range(1, n):\n k = str(1) + '/' + str(numerator + 1)\n p.append(k)\n for numerator in range(2, n + 1):\n for denominator in range(numerator + 1, n + 1):\n b = Fraction(numerator, denominator)\n b = str(b)\n if b not in p:\n k = str(numerator) + '/' + str(denominator)\n p.append(k)\n return p", "from math import gcd\n\ndef simplifiedfractions(n: int) -> List[str]:\n ret = []\n for numerator in range(1, n + 1):\n for denominator in range(numerator + 1, n + 1):\n if numerator != denominator:\n if gcd(numerator, denominator) == 1:\n ret.append(str(numerator) + '/' + str(denominator))\n return ret", "def simplifiedfractions(n: int) -> List[str]:\n if n == 1:\n return []\n\n def gcd(a, b):\n while b > 0:\n r = a % b\n a = b\n b = r\n return a\n ret = []\n for deno in range(2, n + 1):\n for nume in range(1, deno):\n g = gcd(deno, nume)\n n = nume // g\n d = deno // g\n val = str(n) + '/' + str(d)\n if val not in ret:\n ret.append(val)\n return ret"], "starter_code": "def simplifiedfractions(n: int) -> List[str]:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Number Theory", "Math", "String"], "name": null, "source": "leetcode", "tags": ["Number theory", "Mathematics", "String algorithms"], "skill_types": [], "url": "https://leetcode.com/problems/simplified-fractions/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "simplifiedfractions", "task_id": "TACO_lite/215", "example": [[[2], [3], [4], [1]], ["['1/2']", "['1/2', '1/3', '2/3']", "['1/2', '1/3', '1/4', '2/3', '3/4']", "[]"]]} +{"requirement": "Given an array arr[] of n positive integers. The task is to find the maximum of j - i subjected to the constraint of arr[i] <= arr[j].\nExample 1:\nInput:\nn = 9\narr[] = {34, 8, 10, 3, 2, 80, 30, 33, 1}\nOutput: \n6\nExplanation: \nIn the given array arr[1] < arr[7] satisfying \nthe required condition (arr[i] <= arr[j]) thus \ngiving the maximum difference of j - i which is\n6(7-1).\nExample 2:\nInput:\nN = 2\narr[] = {18, 17}\nOutput: \n0\nExplanation: \nWe can either take i and j as 0 and 0 \nor we cantake 1 and 1 both give the same result 0.\nYour Task:\nComplete the function maxIndexDiff() which takes array arr and size n, as input parameters and returns an integer representing the answer. You don't to print answer or take inputs. \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 ≤ N ≤ 10^{6}\n0 ≤ Arr[i] ≤ 10^{9}", "solutions": ["def maxindexdiff(arr, n):\n m = -100000\n for i in range(n):\n j = n - 1\n while i < j and arr[i] > arr[j]:\n j -= 1\n m = max(m, j - i)\n return m", "def maxindexdiff(arr, n):\n ans = 0\n i = 0\n j = n - 1\n while i <= j:\n if arr[i] <= arr[j]:\n ans = max(ans, j - i)\n i += 1\n j = n - 1\n else:\n j -= 1\n return ans", "def maxindexdiff(arr, n):\n left = [0] * n\n right = [0] * n\n left[0] = arr[0]\n for i in range(1, n):\n left[i] = min(left[i - 1], arr[i])\n right[n - 1] = arr[n - 1]\n for j in range(n - 2, -1, -1):\n right[j] = max(right[j + 1], arr[j])\n maxdiff = -1\n i = 0\n j = 0\n while j < n and i < n:\n if left[i] <= right[j]:\n maxdiff = max(maxdiff, j - i)\n j += 1\n else:\n i += 1\n return maxdiff", "def maxindexdiff(arr, n):\n mx = 0\n current_mx = 0\n for index in range(n):\n start = n - 1\n while start > index and arr[index] > arr[start]:\n start -= 1\n current_mx = start - index\n mx = max(mx, current_mx)\n return mx", "def maxindexdiff(arr, n):\n st = []\n n = len(arr)\n max = -1\n res = 0\n for j in range(n - 1, -1, -1):\n if arr[j] > max:\n max = arr[j]\n st.append(j)\n i = 0\n while i < n and st:\n while st and arr[i] <= arr[st[-1]]:\n j = st.pop()\n if j - i > res:\n res = j - i\n i += 1\n return res", "def maxindexdiff(arr, n):\n maxdiff = 0\n for i in range(n):\n for j in range(n - 1, i, -1):\n if arr[i] <= arr[j]:\n if maxdiff < j - i:\n maxdiff = j - i\n else:\n break\n return maxdiff", "def maxindexdiff(arr, n):\n ans = 0\n for i in range(n):\n for j in range(i + ans + 1, n):\n if arr[j] >= arr[i]:\n ans = j - i\n return ans", "def maxindexdiff(arr, n):\n i = 0\n m = 0\n while i < n - 1:\n j = n - 1\n while i < j:\n if arr[j] >= arr[i]:\n if j - i > m:\n m = j - i\n break\n else:\n j -= 1\n i += 1\n return m", "def maxindexdiff(arr, n):\n st = []\n ans = 0\n j = n - 1\n while j >= 0:\n if len(st) == 0:\n st.append([arr[j], j])\n j -= 1\n else:\n i = 0\n while i < len(st) and st[i][0] < arr[j]:\n i += 1\n if i == len(st):\n st.append([arr[j], j])\n j -= 1\n else:\n ans = max(ans, st[i][1] - j)\n j -= 1\n return ans", "def maxindexdiff(arr, n):\n res = 0\n i = 0\n j = n - 1\n while i <= j:\n if arr[i] <= arr[j]:\n if res < j - i:\n res = j - i\n i = i + 1\n j = n - 1\n else:\n j = j - 1\n return res", "def maxindexdiff(arr, n):\n if n == 1:\n return 0\n res = 0\n temp = 0\n for i in range(0, n):\n j = n - 1\n while i < j:\n if arr[j] >= arr[i]:\n temp = j - i\n break\n else:\n j -= 1\n res = max(res, temp)\n return res", "def maxindexdiff(arr, n):\n r = [0]\n for j in range(n - 1, -1, -1):\n for i in range(0, j - 1):\n if arr[j] >= arr[i]:\n r.append(j - i)\n break\n return max(r)", "def maxindexdiff(arr, n):\n left_min = [0] * n\n right_max = [0] * n\n left_min[0] = arr[0]\n for i in range(1, n):\n left_min[i] = min(left_min[i - 1], arr[i])\n right_max[n - 1] = arr[n - 1]\n for j in range(n - 2, -1, -1):\n right_max[j] = max(right_max[j + 1], arr[j])\n i = j = max_diff = 0\n while i < n and j < n:\n if left_min[i] <= right_max[j]:\n max_diff = max(max_diff, j - i)\n j += 1\n else:\n i += 1\n return max_diff", "def maxindexdiff(arr, n):\n stk = [0]\n for i in range(1, len(arr)):\n if arr[stk[-1]] > arr[i]:\n stk.append(i)\n ans = 0\n for j in range(len(arr) - 1, -1, -1):\n while stk and arr[stk[-1]] <= arr[j]:\n ans = max(ans, j - stk[-1])\n stk.pop()\n return ans", "def maxindexdiff(arr, n):\n k = n - 1\n while k:\n i = 0\n while i + k < n:\n if arr[i] <= arr[i + k]:\n return k\n i += 1\n k -= 1\n return 0", "def maxindexdiff(arr, n):\n Lmin = [0] * n\n Rmax = [0] * n\n Lmin[0] = arr[0]\n for i in range(1, n):\n Lmin[i] = min(arr[i], Lmin[i - 1])\n Rmax[n - 1] = arr[n - 1]\n for j in range(n - 2, -1, -1):\n Rmax[j] = max(arr[j], Rmax[j + 1])\n minIndex = 0\n maxIndex = 0\n maxdiff = -1\n while minIndex < n and maxIndex < n:\n if Lmin[minIndex] <= Rmax[maxIndex]:\n maxdiff = max(maxdiff, maxIndex - minIndex)\n maxIndex = maxIndex + 1\n else:\n minIndex = minIndex + 1\n return maxdiff", "def maxindexdiff(arr, n):\n LMin = [0] * n\n RMax = [0] * n\n LMin[0] = arr[0]\n for i in range(1, n):\n LMin[i] = min(arr[i], LMin[i - 1])\n RMax[n - 1] = arr[n - 1]\n for j in range(n - 2, -1, -1):\n RMax[j] = max(arr[j], RMax[j + 1])\n (i, j, ans) = (0, 0, -1)\n while i < n and j < n:\n if LMin[i] <= RMax[j]:\n ans = max(ans, j - i)\n j += 1\n else:\n i += 1\n return ans", "def maxindexdiff(arr, n):\n cnt = 0\n for i in range(n):\n for j in range(i + cnt, n):\n if arr[j] >= arr[i]:\n cnt = j - i\n return cnt", "def maxindexdiff(arr, n):\n rmax = [0] * n\n rmax[n - 1] = arr[n - 1]\n for i in range(n - 2, -1, -1):\n rmax[i] = max(arr[i], rmax[i + 1])\n mini = -1\n i = 0\n j = 0\n while i < n and j < n:\n if rmax[j] >= arr[i]:\n mini = max(mini, j - i)\n j += 1\n else:\n i += 1\n return mini", "def maxindexdiff(arr, n):\n ans = -1\n minleft = [None] * n\n minleft[0] = arr[0]\n maxright = [None] * n\n maxright[-1] = arr[-1]\n for i in range(1, n):\n minleft[i] = min(minleft[i - 1], arr[i])\n for j in range(n - 2, -1, -1):\n maxright[j] = max(arr[j], maxright[j + 1])\n i = 0\n j = 0\n while i < n and j < n:\n if maxright[j] >= minleft[i]:\n ans = max(ans, j - i)\n j += 1\n else:\n i += 1\n return ans", "def maxindexdiff(arr, n):\n leftMin = [0] * n\n rightMax = [0] * n\n leftMin[0] = arr[0]\n for i in range(1, n):\n leftMin[i] = min(leftMin[i - 1], arr[i])\n rightMax[n - 1] = arr[n - 1]\n for i in range(n - 2, -1, -1):\n rightMax[i] = max(rightMax[i + 1], arr[i])\n (i, j) = (0, 0)\n maxDiff = -1\n while i < n and j < n:\n if leftMin[i] <= rightMax[j]:\n maxDiff = max(maxDiff, j - i)\n j += 1\n else:\n i += 1\n return maxDiff", "import math\n\ndef maxindexdiff(arr, n):\n llow = []\n lhigh = []\n for i in range(len(arr)):\n if len(llow) == 0:\n llow.append([arr[i], i])\n continue\n if llow[len(llow) - 1][0] > arr[i]:\n llow.append([arr[i], i])\n arr = arr[::-1]\n for i in range(len(arr)):\n if len(lhigh) == 0:\n lhigh.append([arr[i], n - 1 - i])\n continue\n if lhigh[len(lhigh) - 1][0] < arr[i]:\n lhigh.append([arr[i], n - 1 - i])\n d = dict()\n\n def dfs(i, j):\n if i == len(llow):\n return -math.inf\n if j == len(lhigh):\n return -math.inf\n if d.get((i, j)) != None:\n return d[i, j]\n if llow[i][0] <= lhigh[j][0]:\n d[i, j] = max(lhigh[j][1] - llow[i][1], dfs(i + 1, j), dfs(i, j + 1))\n return max(lhigh[j][1] - llow[i][1], dfs(i + 1, j), dfs(i, j + 1))\n d[i, j] = max(dfs(i + 1, j), dfs(i, j + 1))\n return d[i, j]\n return dfs(0, 0)", "def maxindexdiff(arr, n):\n i = 0\n j = len(arr) - 1\n res = []\n while i <= j:\n if arr[i] <= arr[j]:\n m = j - i\n res.append(m)\n j = len(arr) - 1\n i += 1\n else:\n j -= 1\n return max(res)", "def maxindexdiff(arr, n):\n i = 0\n j = len(arr) - 1\n lst = []\n while i <= j:\n k = 0\n if arr[i] <= arr[j]:\n k = j - i\n lst.append(k)\n i = i + 1\n j = len(arr) - 1\n else:\n j = j - 1\n p = max(lst)\n return p", "def maxindexdiff(arr, n):\n l = len(arr)\n x = [0] * l\n j = l - 1\n last = 0\n for i in range(l - 1, -1, -1):\n if arr[i] > last:\n last = arr[i]\n j = i\n x[i] = j\n else:\n x[i] = j\n m = 0\n i = j = 0\n while i < l and j < l:\n if arr[i] <= arr[x[j]]:\n m = max(m, j - i)\n j += 1\n else:\n i += 1\n return m", "def maxindexdiff(arr, n):\n (more, less, maxDiff) = (arr[:], arr[:], 0)\n for i in range(1, n):\n if less[i] > less[i - 1]:\n less[i] = less[i - 1]\n for j in range(n - 2, -1, -1):\n if more[j] < more[j + 1]:\n more[j] = more[j + 1]\n (i, j) = (0, 0)\n while j < n and i < n:\n if less[i] <= more[j]:\n maxDiff = max(j - i, maxDiff)\n j = j + 1\n else:\n i = i + 1\n return maxDiff", "def maxindexdiff(arr, n):\n rightMax = [0] * n\n rightMax[n - 1] = arr[n - 1]\n for i in range(n - 2, -1, -1):\n rightMax[i] = max(rightMax[i + 1], arr[i])\n (i, j) = (0, 0)\n maxDist = 0\n while i < n and j < n:\n if rightMax[j] >= arr[i]:\n maxDist = max(maxDist, j - i)\n j += 1\n else:\n i += 1\n return maxDist", "def maxindexdiff(Arr, N):\n leftMin = [0] * N\n rightMax = [0] * N\n leftMin[0] = 0\n rightMax[N - 1] = N - 1\n for i in range(1, N):\n if Arr[i] < Arr[leftMin[i - 1]]:\n leftMin[i] = i\n else:\n leftMin[i] = leftMin[i - 1]\n for i in range(N - 2, -1, -1):\n if Arr[i] > Arr[rightMax[i + 1]]:\n rightMax[i] = i\n else:\n rightMax[i] = rightMax[i + 1]\n i = j = maxDiff = 0\n while i < N and j < N:\n if Arr[leftMin[i]] <= Arr[rightMax[j]]:\n maxDiff = max(maxDiff, j - i)\n j += 1\n else:\n i += 1\n return maxDiff", "def maxindexdiff(arr, n):\n (low, high) = ([], [])\n for i in range(n):\n if low == []:\n low.append(i)\n continue\n if arr[i] < arr[low[-1]]:\n low.append(i)\n i = n - 1\n while i >= 0:\n if high == []:\n high.append(i)\n i -= 1\n continue\n if arr[i] > arr[high[-1]]:\n high.append(i)\n i -= 1\n out = float('-inf')\n for i in range(len(high)):\n for j in range(len(low)):\n if high[i] > low[j] and arr[high[i]] >= arr[low[j]]:\n out = max(out, high[i] - low[j])\n return out if out != float('-inf') else 0", "def maxindexdiff(arr, n):\n l = 0\n r = 0\n lmin = []\n rmax = []\n mini = float('+inf')\n for i in arr:\n mini = min(mini, i)\n lmin.append(mini)\n maxi = float('-inf')\n for i in arr[::-1]:\n maxi = max(maxi, i)\n rmax.append(maxi)\n rmax = rmax[::-1]\n res = -1\n while l < len(lmin) and r < len(rmax):\n if lmin[l] <= rmax[r]:\n res = max(res, r - l)\n r += 1\n else:\n l += 1\n return res", "def maxindexdiff(arr, n):\n maxarr = [0] * n\n minarr = []\n len = n - 1\n for i in range(n):\n if i == 0:\n minarr.append(arr[i])\n maxarr[len - i] = arr[len - i]\n else:\n minarr.append(min(arr[i], minarr[-1]))\n maxarr[len - i] = max(maxarr[len - i + 1], arr[len - i])\n maxlength = 0\n i = 0\n j = 0\n while i < n and j < n:\n if minarr[i] <= maxarr[j]:\n while j < n and minarr[i] <= maxarr[j]:\n j += 1\n maxlength = max(maxlength, j - i - 1)\n else:\n i += 1\n return maxlength", "def maxindexdiff(Arr, n):\n c = []\n k = 0\n for i in range(len(Arr)):\n for j in range(i + 1, len(Arr)):\n if Arr[i] <= Arr[j]:\n k = j - i\n c.append(k)\n if max(c) >= len(Arr) - i:\n break\n return max(c)", "def maxindexdiff(arr, n):\n st = []\n ans = 0\n for (i, a) in enumerate(arr):\n if not st or arr[st[-1]] > a:\n st.append(i)\n for i in range(n - 1, -1, -1):\n while st and arr[st[-1]] <= arr[i]:\n ans = max(ans, i - st[-1])\n st.pop(-1)\n return ans", "def maxindexdiff(arr, n):\n a = 0\n for i in range(n):\n for j in range(i + 1 + a, n):\n if arr[i] <= arr[j]:\n a = max(j - i, a)\n return a", "def maxindexdiff(arr, n):\n mx = 0\n for i in range(0, n):\n j = n - 1\n while j >= i:\n if arr[j] >= arr[i]:\n mx = max(j - i, mx)\n break\n j -= 1\n return mx", "def maxindexdiff(arr, n):\n L = [0] * n\n R = [0] * n\n L[0] = arr[0]\n R[n - 1] = arr[n - 1]\n l = r = 0\n ans = -1\n for i in range(1, n):\n L[i] = min(L[i - 1], arr[i])\n for i in range(n - 2, -1, -1):\n R[i] = max(R[i + 1], arr[i])\n while l < n and r < n:\n if L[l] <= R[r]:\n ans = max(ans, r - l)\n r += 1\n else:\n l += 1\n return ans", "def maxindexdiff(arr, n):\n l = []\n r = []\n temp = 999999999999999999999999999\n for i in range(n):\n if arr[i] < temp:\n temp = arr[i]\n l.append(temp)\n temp = 0\n for j in range(n - 1, -1, -1):\n if arr[j] > temp:\n temp = arr[j]\n r.append(temp)\n r.reverse()\n i = 0\n j = 0\n ans = 0\n while i < n and j < n:\n while j < n and r[j] >= l[i]:\n j += 1\n ans = max(ans, j - 1 - i)\n i += 1\n return ans", "def maxindexdiff(arr, n):\n l_min = [float('-inf')] * n\n r_max = [0] * n\n (l_min[0], r_max[-1]) = (arr[0], arr[-1])\n for i in range(1, n):\n l_min[i] = min(l_min[i - 1], arr[i])\n for i in range(n - 2, -1, -1):\n r_max[i] = max(r_max[i + 1], arr[i])\n (i, j) = (0, 0)\n ans = 0\n while i < n and j < n:\n if l_min[i] <= r_max[j]:\n ans = max(ans, j - i)\n j += 1\n else:\n i += 1\n return ans", "def maxindexdiff(arr, n):\n flag = 0\n for i in range(n):\n low = i\n high = n - 1\n while low <= high:\n if arr[high] >= arr[low]:\n flag = max(flag, high - low)\n break\n else:\n high -= 1\n return flag", "def maxindexdiff(arr, n):\n index = dict()\n for i in range(n):\n if arr[i] in index:\n index[arr[i]].append(i)\n else:\n index[arr[i]] = [i]\n arr.sort()\n maxDiff = 0\n temp = n\n a = arr\n for i in range(n):\n if temp > index[a[i]][0]:\n temp = index[a[i]][0]\n maxDiff = max(maxDiff, index[a[i]][-1] - temp)\n return maxDiff", "def maxindexdiff(arr, n):\n x = 0\n for i in range(0, n):\n j = n - 1\n while arr[i] > arr[j]:\n j = j - 1\n x = max(x, j - i)\n return x"], "starter_code": "def maxindexdiff(arr,n):\n", "input_output": {"inputs": ["n = 9\r\narr[] = {34, 8, 10, 3, 2, 80, 30, 33, 1}", "N = 2\r\narr[] = {18, 17}"], "outputs": ["6", "0"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/maximum-index3307/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "maxindexdiff", "task_id": "TACO_lite/54", "example": [[[9, [34, 8, 10, 3, 2, 80, 30, 33, 1]], [2, [18, 17]]], ["6", "0"]]} +{"requirement": "An onion array is an array that satisfies the following condition for all values of `j` and `k`:\n\nIf all of the following are `true`:\n\n* `j >= 0`\n* `k >= 0`\n* `j + k = array.length - 1`\n* `j != k`\n \nthen:\n\n* `a[j] + a[k] <= 10`\n\n### Examples:\n\n```\n[1, 2, 19, 4, 5] => true (as 1+5 <= 10 and 2+4 <= 10)\n[1, 2, 19, 4, 10] => false (as 1+10 > 10)\n```\n\nWrite a function named `isOnionArray`/`IsOnionArray`/`is_onion_array()` that returns `true` if its argument is an onion array and returns `false` if it is not.\n\n~~~if:php\nYour solution should at least be moderately efficient. Make sure you don't do any unnecessary looping ;)\n~~~", "solutions": ["def is_onion_array(a):\n return all((a[i] + a[-i - 1] <= 10 for i in range(len(a) // 2)))", "from typing import List\n\ndef is_onion_array(a: List[int]) -> bool:\n return all((aj + ak <= 10 for (aj, ak) in zip(a, a[:(len(a) - 1) // 2:-1])))", "def is_onion_array(a):\n for i in range(0, len(a) // 2):\n if a[i] + a[-i - 1] > 10:\n return False\n return True", "def is_onion_array(a):\n for j in range(len(a) // 2):\n if a[j] + a[-j - 1] > 10:\n return False\n return True", "def is_onion_array(a):\n if a == []:\n return True\n a = [sum(x) for x in zip(a, a[::-1])]\n a.pop(len(a) // 2)\n for element in a:\n if element > 10:\n return False\n return True", "def is_onion_array(a):\n i = 0\n j = -1\n while i != len(a) // 2:\n if a[i] + a[j] > 10:\n return False\n i += 1\n j -= 1\n return True", "from itertools import combinations as cb\n\ndef is_onion_array(a):\n return not any([sum(c) == len(a) - 1 and a[c[0]] + a[c[1]] > 10 for c in cb([*range(0, len(a))], 2)])"], "starter_code": "def is_onion_array(a):\n", "input_output": {"fn_name": "is_onion_array", "inputs": [[[6, 0, 4]], [[1, 1, 15, 10, -1]]], "outputs": [[true], [false]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/59b2883c5e2308b54d000013", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_onion_array", "task_id": "TACO_lite/230", "example": [[], []]} +{"requirement": "This kata is all about adding numbers.\n\nYou will create a function named add. It will return the sum of all the arguments. Sounds easy, doesn't it?\n\nWell Here's the Twist. The inputs will gradually decrease with their index as parameter to the function.\n\n```python\n add(3,4,6) #returns (3/1)+(4/2)+(6/3)=7\n```\n\nRemember the function will return 0 if no arguments are passed and it must round the result if sum is a float.\n\nExample\n```python\n add() #=> 0\n add(1,2,3) #=> 3\n add(1,4,-6,20) #=> 6\n```\n\nCheck my another kata here!! http://www.codewars.com/kata/555b73a81a6285b6ce000047", "solutions": ["def add(*args):\n return int(round(sum((float(a) / i for (i, a) in enumerate(args, 1)))))", "def add(*args):\n return round(sum((x / i for (i, x) in enumerate(args, 1))))", "add = lambda *a: round(sum((e / i for (i, e) in enumerate(a, 1))))", "def add(*args):\n return round(sum([args[i] / (i + 1) for i in range(len(args))]))", "def add(*args):\n return round(sum((v / i for (i, v) in enumerate(args, 1))))", "def add(*args):\n return round(sum((x / (c + 1) for (c, x) in enumerate(args))))", "def add(*args):\n return round(sum((value / pos for (pos, value) in enumerate(args, 1))))", "def add(*args):\n return round(sum((1.0 * n / i for (i, n) in enumerate(args, 1))))", "def add(*args):\n sum = 0\n for (idx, num) in enumerate(args):\n sum += num / (idx + 1.0)\n return round(sum)"], "starter_code": "def add(*args):\n", "input_output": {"fn_name": "add", "inputs": [[100, 200, 300], [2], [4, -3, -2], [-1, -2, -3, -4]], "outputs": [[300], [2], [2], [-4]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/555de49a04b7d1c13c00000e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "add", "task_id": "TACO_lite/132", "example": [[[3, 4, 6], [], [1, 2, 3], [1, 4, -6, 20]], ["7", "0", "3", "6"]]} +{"requirement": "Let be `n` an integer prime with `10` e.g. `7`. \n\n`1/7 = 0.142857 142857 142857 ...`.\n\nWe see that the decimal part has a cycle: `142857`. The length of this cycle is `6`. In the same way:\n\n`1/11 = 0.09 09 09 ...`. Cycle length is `2`.\n\n# Task\n\nGiven an integer n (n > 1), the function cycle(n) returns the length of the cycle if n and 10 are coprimes, otherwise returns -1.\n\n# Examples:\n```\ncycle(5) = -1\ncycle(13) = 6 -> 0.076923 076923 0769\ncycle(21) = 6 -> 0.047619 047619 0476\ncycle(27) = 3 -> 0.037 037 037 037 0370\ncycle(33) = 2 -> 0.03 03 03 03 03 03 03 03\ncycle(37) = 3 -> 0.027 027 027 027 027 0\ncycle(94) = -1 \n\ncycle(22) = -1 since 1/22 ~ 0.0 45 45 45 45 ...\n```", "solutions": ["import math\n\ndef cycle(n):\n if n % 2 == 0 or n % 5 == 0:\n return -1\n k = 1\n while pow(10, k, n) != 1:\n k += 1\n return k", "def cycle(n):\n if not n % 2 or not n % 5:\n return -1\n (x, mods) = (1, set())\n while x not in mods:\n mods.add(x)\n x = 10 * x % n\n return len(mods)", "def cycle(n):\n if n % 5 == 0 or n % 2 == 0:\n return -1\n (remainders, r) = ([1], 0)\n while r != 1:\n r = remainders[-1] * 10 % n\n remainders.append(r)\n return len(remainders) - 1", "def cycle(n):\n if n % 2 and n % 5:\n for i in range(1, n):\n if pow(10, i, n) == 1:\n return i\n return -1", "def cycle(n):\n if n % 2 == 0 or n % 5 == 0:\n return -1\n m = 1\n for p in range(1, n):\n m = 10 * m % n\n if m == 1:\n return p", "def cycle(n):\n if not (n % 2 and n % 5):\n return -1\n return next(filter(lambda x: pow(10, x, n) == 1, range(1, n)))", "def cycle(n):\n if not n % 2 or not n % 5:\n return -1\n (m, s) = (1, set())\n while m not in s:\n s.add(m)\n m = 10 * m % n\n return len(s)", "from math import ceil, log10\n\ndef cycle(d):\n if d % 5 == 0 or d % 2 == 0:\n return -1\n n = 10 ** int(ceil(log10(d)))\n first = n % d\n n *= 10\n for i in range(99999999):\n n %= d\n if n == first:\n return i + 1\n n *= 10", "def cycle(n):\n if n % 2 == 0 or n % 5 == 0:\n return -1\n c = len(str(n))\n m = 10 ** c % n\n while m != 1:\n c += 1\n m = m * 10 % n\n return c", "def cycle(i):\n if i % 2 == 0 or i % 5 == 0:\n return -1\n gen = 10\n n = 1\n while gen % i != 1:\n gen = gen % i * 10\n n = n + 1\n return n"], "starter_code": "def cycle(n) :\n", "input_output": {"fn_name": "cycle", "inputs": [[3], [33], [18118], [69], [197], [65], [97], [19], [111], [53], [59], [93], [51], [159], [183], [167], [94], [133], [218713], [38127], [431541], [221193], [1234567]], "outputs": [[1], [2], [-1], [22], [98], [-1], [96], [18], [3], [13], [58], [15], [16], [13], [60], [166], [-1], [18], [9744], [6230], [726], [3510], [34020]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5a057ec846d843c81a0000ad", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "cycle", "task_id": "TACO_lite/204", "example": [[[5], [13], [21], [27], [33], [37], [94], [22]], ["-1", "6", "6", "3", "2", "3", "-1", "-1"]]} +{"requirement": "In a given array A[] find the maximum value of (A[i] – i) - (A[j] – j) where i is not equal to j. \ni and j vary from 0 to N-1 and N is the size of input array A[]. The value of N is always greater than 1.\nExample 1:\nInput\nN = 5\nA[] = {9, 15, 4, 12, 13}\nOutput\n12\nExplanation:\n(a[1]-1) - (a[2]-2) = (15-1)-(4-2) = 12\n \nExample 2:\nInput\nN = 4\nA[] = {3, 1, 2, 4}\nOutput\n3\nExplanation:\n(a[1]-1) - (a[2]-2) = (3-1)-(1-2) = 3\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function maxVal() which takes the array A[] and its size N as inputs and returns the maximum value\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n2 ≤ N ≤ 10^{5}\n1 ≤ A[i] ≤ 10^{5}", "solutions": ["def maxval(a, n):\n maxval = 0\n minval = 1000000\n for i in range(n):\n maxval = max(maxval, a[i] - i)\n minval = min(minval, a[i] - i)\n return maxval - minval", "def maxval(a, n):\n X = a[0] - 0\n Y = a[n - 1] - (n - 1)\n for i in range(1, n):\n X = max(X, a[i] - i)\n for j in range(n - 1, -1, -1):\n Y = min(Y, a[j] - j)\n return X - Y", "def maxval(a, n):\n diff = []\n for index in range(n):\n diff.append(a[index] - index)\n diff.sort()\n return diff[-1] - diff[0]", "import sys\n\ndef maxval(a, n):\n min_val = sys.maxsize\n max_val = -sys.maxsize - 1\n for i in range(n):\n if a[i] - i > max_val:\n max_val = a[i] - i\n if a[i] - i < min_val:\n min_val = a[i] - i\n return max_val - min_val", "def maxval(a, n):\n mx = 0\n mn = 1000000\n ans = 0\n for i in range(0, n):\n prvmx = mx\n prvmn = mn\n if a[i] - i + 1 > mx:\n mx = a[i] - i + 1\n if a[i] - i + 1 < mn:\n mn = a[i] - i + 1\n ans = max(ans, prvmx - mn)\n ans = max(ans, mx - prvmn)\n return ans", "def maxval(arr, N):\n maxi = arr[0] - 0\n mini = arr[0] - 0\n for i in range(1, N):\n if arr[i] - i > maxi:\n maxi = arr[i] - i\n if arr[i] - i < mini:\n mini = arr[i] - i\n return maxi - mini", "def maxval(a, n):\n maxx = 0\n mini = 100000007\n for i in range(0, n):\n if a[i] - i > maxx:\n maxx = a[i] - i\n if a[i] - i < mini:\n mini = a[i] - i\n return maxx - mini", "def maxval(a, n):\n for i in range(n):\n a[i] -= i\n a.sort()\n return a[-1] - a[0]", "def maxval(a, n):\n mx = 0\n lst = []\n for i in range(n):\n lst.append(a[i] - i)\n lst.sort()\n return lst[-1] - lst[0]", "def maxval(a, n):\n mini = 1000000000.0\n maxi = -1000000000.0\n for i in range(0, n):\n a[i] = a[i] - i\n mini = min(mini, a[i])\n maxi = max(maxi, a[i])\n return maxi - mini", "def maxval(a, n):\n (min, max) = (99999999, -9999999)\n for i in range(0, n):\n if a[i] - i > max:\n max = a[i] - i\n if a[i] - i < min:\n min = a[i] - i\n return max - min", "def maxval(arr, n):\n maxval = 0\n minval = float('inf')\n for i in range(n):\n maxval = max(maxval, arr[i] - i)\n minval = min(minval, arr[i] - i)\n return maxval - minval", "def maxval(a, n):\n maxi = a[0]\n mini = a[0]\n for i in range(n):\n if a[i] - i > maxi:\n maxi = a[i] - i\n if a[i] - i < mini:\n mini = a[i] - i\n return maxi - mini", "def maxval(a, n):\n max = a[0]\n min = a[0]\n for i in range(n):\n value = a[i] - i\n if value > max:\n max = a[i] - i\n if value < min:\n min = a[i] - i\n return max - min", "def maxval(a: list, n: int) -> int:\n (minimum, maximum) = (float('inf'), float('-inf'))\n for i in range(n):\n if a[i] - i < minimum:\n minimum = a[i] - i\n if a[i] - i > maximum:\n maximum = a[i] - i\n return maximum - minimum", "def maxval(a, n):\n maxa = -9999999999\n mina = 99999999999\n for i in range(0, n):\n maxa = max(maxa, a[i] - i)\n mina = min(mina, a[i] - i)\n return maxa - mina", "def maxval(a, n):\n maxval = -999999999\n minval = 999999999\n for i in range(n):\n maxval = max(maxval, a[i] - i)\n minval = min(minval, a[i] - i)\n return maxval - minval", "def maxval(a, n):\n s = set()\n for i in range(n):\n s.add(a[i] - i)\n return max(s) - min(s)", "def maxval(a, n):\n dic = {}\n for i in range(n):\n k = a[i] - i\n dic[k] = True\n k = list(dic.keys())\n return max(k) - min(k)", "def maxval(a, n):\n for i in range(n):\n a[i] = a[i] - i\n return max(a) - min(a)", "def maxval(A, n):\n (maxi, mini) = (0, 10000000)\n for i in range(n):\n maxi = max(maxi, A[i] - i)\n mini = min(mini, A[i] - i)\n return maxi - mini", "def maxval(a, n):\n maxi = -1\n mini = 200000\n for i in range(n):\n if a[i] - i > maxi:\n maxi = a[i] - i\n if a[i] - i < mini:\n mini = a[i] - i\n return maxi - mini", "def maxval(a, n):\n m1 = -10 ** 5\n m2 = 10 ** 5\n for i in range(n):\n m1 = max(m1, a[i] - i)\n m2 = min(m2, a[i] - i)\n return m1 - m2", "def maxval(a, n):\n max1 = a[0]\n min1 = a[0]\n for i in range(n):\n if a[i] - i > max1:\n max1 = a[i] - i\n if a[i] - i < min1:\n min1 = a[i] - i\n return max1 - min1", "def maxval(a, n):\n max_val = -123456789\n min_val = 123456789\n for i in range(n):\n if a[i] - i > max_val:\n max_val = a[i] - i\n if a[i] - i < min_val:\n min_val = a[i] - i\n return max_val - min_val", "def maxval(a, n):\n x = -999\n y = 999\n for i in range(n):\n x = max(x, a[i] - i)\n y = min(y, a[i] - i)\n return x - y", "def maxval(a, n):\n ma = -9999\n mi = 9999\n for i in range(n):\n ma = max(ma, a[i] - i)\n mi = min(mi, a[i] - i)\n return ma - mi", "def maxval(a, n):\n (mn, mx) = (float('inf'), -float('inf'))\n for (i, x) in enumerate(a):\n mn = min(mn, x - i)\n mx = max(mx, x - i)\n return mx - mn", "def maxval(a, n):\n MAX = -100000000000.0\n MIN = 100000000000.0\n for i in range(n):\n MAX = max(MAX, a[i] - i)\n MIN = min(MIN, a[i] - i)\n return MAX - MIN", "def maxval(a, n):\n max = a[0] - 0\n min = a[0] - 0\n n = len(a)\n for i in range(1, n):\n x = a[i] - i\n if x < min:\n min = x\n if x > max:\n max = x\n return max - min", "def maxval(a, n):\n for i in range(n):\n a[i] = a[i] - i\n m1 = max(a)\n m2 = min(a)\n m3 = m1 - m2\n return m3", "def maxval(a, n):\n sub = []\n for i in range(n):\n sub.append(a[i] - i)\n sub.sort()\n maxD = sub[-1] - sub[0]\n return maxD", "def maxval(a, n):\n mini = float('inf')\n maxi = float('-inf')\n for (i, val) in enumerate(a):\n if val - i < mini:\n mini = val - i\n if val - i > maxi:\n maxi = val - i\n return maxi - mini", "def maxval(a, n):\n maxv = -float('inf')\n minv = float('inf')\n for i in range(n):\n maxv = max(maxv, a[i] - i)\n minv = min(minv, a[i] - i)\n return maxv - minv", "def maxval(a, n):\n na = []\n for i in range(0, n):\n na.append(a[i] - i)\n qmax = 0\n qmin = 100000\n for i in range(0, n):\n if na[i] > qmax:\n qmax = na[i]\n for i in range(0, n):\n if na[i] < qmin:\n qmin = na[i]\n return qmax - qmin", "def maxval(a, n):\n arr_1 = []\n for i in range(0, n):\n arr_1.append(a[i] - i)\n return max(arr_1) - min(arr_1)", "def maxval(a, n):\n z = 0\n b = max(a)\n for i in range(len(a)):\n if a[i] - i > z:\n z = a[i] - i\n if a[i] - i < b:\n b = a[i] - i\n return z - b", "def maxval(a, n):\n minv = 2 ** 31\n maxv = -2 ** 31\n for i in range(len(a)):\n minv = min(minv, a[i] - i)\n maxv = max(maxv, a[i] - i)\n return maxv - minv", "import sys\n\ndef maxval(a, n):\n if n < 2:\n return 0\n max = -sys.maxsize - 1\n min = sys.maxsize\n for i in range(n):\n if a[i] - i > max:\n max = a[i] - i\n if a[i] - i < min:\n min = a[i] - i\n return max - min", "def maxval(a, n):\n (maxi, mini) = (-10 ** 9, 10 ** 9)\n for (i, j) in enumerate(a):\n maxi = max(maxi, j - i)\n mini = min(mini, j - i)\n return maxi - mini", "def maxval(a, n):\n mx = -1\n mn = 10000000\n for i in range(n):\n a[i] = a[i] - i\n return max(a) - min(a)"], "starter_code": "def maxval(a, n):\n", "input_output": {"inputs": ["N = 5\nA[] = {9, 15, 4, 12, 13}", "N = 4\nA[] = {3, 1, 2, 4}"], "outputs": ["12", "3"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/max-value1205/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "maxval", "task_id": "TACO_lite/246", "example": [[[5, [9, 15, 4, 12, 13]], [4, [3, 1, 2, 4]]], ["12", "3"]]} +{"requirement": "The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.\n\n\n\nGiven an integer n, return all distinct solutions to the n-queens puzzle.\n\nEach solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.\n\nExample:\n\n\nInput: 4\nOutput: [\n [\".Q..\", // Solution 1\n \"...Q\",\n \"Q...\",\n \"..Q.\"],\n\n [\"..Q.\", // Solution 2\n \"Q...\",\n \"...Q\",\n \".Q..\"]\n]\nExplanation: There exist two distinct solutions to the 4-queens puzzle as shown above.", "solutions": ["def helper(n, currentIndex, aux, rowsWithQueen, alll):\n for i in range(n):\n if i not in rowsWithQueen:\n (x, y) = (currentIndex - 1, i - 1)\n while aux[x][y] != 'Q' and x >= 0 and (y >= 0):\n x -= 1\n y -= 1\n if x != -1 and y != -1:\n continue\n (x, y) = (currentIndex - 1, i + 1)\n while x >= 0 and y < n and (aux[x][y] != 'Q'):\n x -= 1\n y += 1\n if x != -1 and y != n:\n continue\n aux[currentIndex][i] = 'Q'\n rowsWithQueen.append(i)\n if currentIndex == n - 1:\n aw = [[0 for i in range(n)] for j in range(n)]\n for a in range(n):\n for b in range(n):\n aw[a][b] = aux[a][b]\n alll.append(aw)\n else:\n self.helper(n, currentIndex + 1, aux, rowsWithQueen, alll)\n aux[currentIndex][i] = '.'\n rowsWithQueen.pop()\n\ndef solvenqueens(n):\n aux = [['.' for i in range(n)] for j in range(n)]\n rowsWithQueen = []\n alll = []\n self.helper(n, 0, aux, rowsWithQueen, alll)\n aux = []\n for sol in alll:\n ax = []\n for i in sol:\n i = ''.join(i)\n ax.append(i)\n aux.append(ax)\n return aux", "def solvenqueens(n):\n\n def DFS(queens, xy_dif, xy_sum):\n p = len(queens)\n if p == n:\n result.append(queens)\n return None\n for q in range(n):\n if q not in queens and p - q not in xy_dif and (p + q not in xy_sum):\n DFS(queens + [q], xy_dif + [p - q], xy_sum + [p + q])\n result = []\n DFS([], [], [])\n return [['.' * i + 'Q' + '.' * (n - i - 1) for i in sol] for sol in result]", "def __init__():\n self.board = []\n self.col_status = []\n self.row_status = []\n self.dia_status_1 = []\n self.dia_status_2 = []\n self.result = []\n\ndef placeQueen(row, n):\n if row == n:\n tmp = [''.join(el) for el in self.board]\n self.result.append(tmp)\n return\n for i in range(n):\n if self.col_status[i] and self.dia_status_1[i + row] and self.dia_status_2[row - i]:\n self.board[row][i] = 'Q'\n self.col_status[i] = False\n self.dia_status_1[i + row] = False\n self.dia_status_2[row - i] = False\n self.placeQueen(row + 1, n)\n self.board[row][i] = '.'\n self.col_status[i] = True\n self.dia_status_1[i + row] = True\n self.dia_status_2[row - i] = True\n\ndef solvenqueens(n):\n self.board = [['.' for i in range(n)] for j in range(n)]\n self.col_status = [True for i in range(n)]\n self.row_status = [True for i in range(n)]\n self.dia_status_1 = [True for i in range(2 * n - 1)]\n self.dia_status_2 = [True for i in range(2 * n - 1)]\n self.placeQueen(0, n)\n return self.result", "def solvenqueens(n):\n if n == 1:\n return [['Q']]\n elif n == 2 or n == 3:\n return []\n elif n == 4:\n return [['.Q..', '...Q', 'Q...', '..Q.'], ['..Q.', 'Q...', '...Q', '.Q..']]\n elif n == 5:\n return [['Q....', '..Q..', '....Q', '.Q...', '...Q.'], ['Q....', '...Q.', '.Q...', '....Q', '..Q..'], ['.Q...', '...Q.', 'Q....', '..Q..', '....Q'], ['.Q...', '....Q', '..Q..', 'Q....', '...Q.'], ['..Q..', 'Q....', '...Q.', '.Q...', '....Q'], ['..Q..', '....Q', '.Q...', '...Q.', 'Q....'], ['...Q.', 'Q....', '..Q..', '....Q', '.Q...'], ['...Q.', '.Q...', '....Q', '..Q..', 'Q....'], ['....Q', '.Q...', '...Q.', 'Q....', '..Q..'], ['....Q', '..Q..', 'Q....', '...Q.', '.Q...']]\n elif n == 6:\n return [['.Q....', '...Q..', '.....Q', 'Q.....', '..Q...', '....Q.'], ['..Q...', '.....Q', '.Q....', '....Q.', 'Q.....', '...Q..'], ['...Q..', 'Q.....', '....Q.', '.Q....', '.....Q', '..Q...'], ['....Q.', '..Q...', 'Q.....', '.....Q', '...Q..', '.Q....']]\n elif n == 7:\n return [['Q......', '..Q....', '....Q..', '......Q', '.Q.....', '...Q...', '.....Q.'], ['Q......', '...Q...', '......Q', '..Q....', '.....Q.', '.Q.....', '....Q..'], ['Q......', '....Q..', '.Q.....', '.....Q.', '..Q....', '......Q', '...Q...'], ['Q......', '.....Q.', '...Q...', '.Q.....', '......Q', '....Q..', '..Q....'], ['.Q.....', '...Q...', 'Q......', '......Q', '....Q..', '..Q....', '.....Q.'], ['.Q.....', '...Q...', '.....Q.', 'Q......', '..Q....', '....Q..', '......Q'], ['.Q.....', '....Q..', 'Q......', '...Q...', '......Q', '..Q....', '.....Q.'], ['.Q.....', '....Q..', '..Q....', 'Q......', '......Q', '...Q...', '.....Q.'], ['.Q.....', '....Q..', '......Q', '...Q...', 'Q......', '..Q....', '.....Q.'], ['.Q.....', '.....Q.', '..Q....', '......Q', '...Q...', 'Q......', '....Q..'], ['.Q.....', '......Q', '....Q..', '..Q....', 'Q......', '.....Q.', '...Q...'], ['..Q....', 'Q......', '.....Q.', '.Q.....', '....Q..', '......Q', '...Q...'], ['..Q....', 'Q......', '.....Q.', '...Q...', '.Q.....', '......Q', '....Q..'], ['..Q....', '....Q..', '......Q', '.Q.....', '...Q...', '.....Q.', 'Q......'], ['..Q....', '.....Q.', '.Q.....', '....Q..', 'Q......', '...Q...', '......Q'], ['..Q....', '......Q', '.Q.....', '...Q...', '.....Q.', 'Q......', '....Q..'], ['..Q....', '......Q', '...Q...', 'Q......', '....Q..', '.Q.....', '.....Q.'], ['...Q...', 'Q......', '..Q....', '.....Q.', '.Q.....', '......Q', '....Q..'], ['...Q...', 'Q......', '....Q..', '.Q.....', '.....Q.', '..Q....', '......Q'], ['...Q...', '.Q.....', '......Q', '....Q..', '..Q....', 'Q......', '.....Q.'], ['...Q...', '.....Q.', 'Q......', '..Q....', '....Q..', '......Q', '.Q.....'], ['...Q...', '......Q', '..Q....', '.....Q.', '.Q.....', '....Q..', 'Q......'], ['...Q...', '......Q', '....Q..', '.Q.....', '.....Q.', 'Q......', '..Q....'], ['....Q..', 'Q......', '...Q...', '......Q', '..Q....', '.....Q.', '.Q.....'], ['....Q..', 'Q......', '.....Q.', '...Q...', '.Q.....', '......Q', '..Q....'], ['....Q..', '.Q.....', '.....Q.', '..Q....', '......Q', '...Q...', 'Q......'], ['....Q..', '..Q....', 'Q......', '.....Q.', '...Q...', '.Q.....', '......Q'], ['....Q..', '......Q', '.Q.....', '...Q...', '.....Q.', 'Q......', '..Q....'], ['....Q..', '......Q', '.Q.....', '.....Q.', '..Q....', 'Q......', '...Q...'], ['.....Q.', 'Q......', '..Q....', '....Q..', '......Q', '.Q.....', '...Q...'], ['.....Q.', '.Q.....', '....Q..', 'Q......', '...Q...', '......Q', '..Q....'], ['.....Q.', '..Q....', 'Q......', '...Q...', '......Q', '....Q..', '.Q.....'], ['.....Q.', '..Q....', '....Q..', '......Q', 'Q......', '...Q...', '.Q.....'], ['.....Q.', '..Q....', '......Q', '...Q...', 'Q......', '....Q..', '.Q.....'], ['.....Q.', '...Q...', '.Q.....', '......Q', '....Q..', '..Q....', 'Q......'], ['.....Q.', '...Q...', '......Q', 'Q......', '..Q....', '....Q..', '.Q.....'], ['......Q', '.Q.....', '...Q...', '.....Q.', 'Q......', '..Q....', '....Q..'], ['......Q', '..Q....', '.....Q.', '.Q.....', '....Q..', 'Q......', '...Q...'], ['......Q', '...Q...', 'Q......', '....Q..', '.Q.....', '.....Q.', '..Q....'], ['......Q', '....Q..', '..Q....', 'Q......', '.....Q.', '...Q...', '.Q.....']]\n elif n == 8:\n return [['Q.......', '....Q...', '.......Q', '.....Q..', '..Q.....', '......Q.', '.Q......', '...Q....'], ['Q.......', '.....Q..', '.......Q', '..Q.....', '......Q.', '...Q....', '.Q......', '....Q...'], ['Q.......', '......Q.', '...Q....', '.....Q..', '.......Q', '.Q......', '....Q...', '..Q.....'], ['Q.......', '......Q.', '....Q...', '.......Q', '.Q......', '...Q....', '.....Q..', '..Q.....'], ['.Q......', '...Q....', '.....Q..', '.......Q', '..Q.....', 'Q.......', '......Q.', '....Q...'], ['.Q......', '....Q...', '......Q.', 'Q.......', '..Q.....', '.......Q', '.....Q..', '...Q....'], ['.Q......', '....Q...', '......Q.', '...Q....', 'Q.......', '.......Q', '.....Q..', '..Q.....'], ['.Q......', '.....Q..', 'Q.......', '......Q.', '...Q....', '.......Q', '..Q.....', '....Q...'], ['.Q......', '.....Q..', '.......Q', '..Q.....', 'Q.......', '...Q....', '......Q.', '....Q...'], ['.Q......', '......Q.', '..Q.....', '.....Q..', '.......Q', '....Q...', 'Q.......', '...Q....'], ['.Q......', '......Q.', '....Q...', '.......Q', 'Q.......', '...Q....', '.....Q..', '..Q.....'], ['.Q......', '.......Q', '.....Q..', 'Q.......', '..Q.....', '....Q...', '......Q.', '...Q....'], ['..Q.....', 'Q.......', '......Q.', '....Q...', '.......Q', '.Q......', '...Q....', '.....Q..'], ['..Q.....', '....Q...', '.Q......', '.......Q', 'Q.......', '......Q.', '...Q....', '.....Q..'], ['..Q.....', '....Q...', '.Q......', '.......Q', '.....Q..', '...Q....', '......Q.', 'Q.......'], ['..Q.....', '....Q...', '......Q.', 'Q.......', '...Q....', '.Q......', '.......Q', '.....Q..'], ['..Q.....', '....Q...', '.......Q', '...Q....', 'Q.......', '......Q.', '.Q......', '.....Q..'], ['..Q.....', '.....Q..', '.Q......', '....Q...', '.......Q', 'Q.......', '......Q.', '...Q....'], ['..Q.....', '.....Q..', '.Q......', '......Q.', 'Q.......', '...Q....', '.......Q', '....Q...'], ['..Q.....', '.....Q..', '.Q......', '......Q.', '....Q...', 'Q.......', '.......Q', '...Q....'], ['..Q.....', '.....Q..', '...Q....', 'Q.......', '.......Q', '....Q...', '......Q.', '.Q......'], ['..Q.....', '.....Q..', '...Q....', '.Q......', '.......Q', '....Q...', '......Q.', 'Q.......'], ['..Q.....', '.....Q..', '.......Q', 'Q.......', '...Q....', '......Q.', '....Q...', '.Q......'], ['..Q.....', '.....Q..', '.......Q', 'Q.......', '....Q...', '......Q.', '.Q......', '...Q....'], ['..Q.....', '.....Q..', '.......Q', '.Q......', '...Q....', 'Q.......', '......Q.', '....Q...'], ['..Q.....', '......Q.', '.Q......', '.......Q', '....Q...', 'Q.......', '...Q....', '.....Q..'], ['..Q.....', '......Q.', '.Q......', '.......Q', '.....Q..', '...Q....', 'Q.......', '....Q...'], ['..Q.....', '.......Q', '...Q....', '......Q.', 'Q.......', '.....Q..', '.Q......', '....Q...'], ['...Q....', 'Q.......', '....Q...', '.......Q', '.Q......', '......Q.', '..Q.....', '.....Q..'], ['...Q....', 'Q.......', '....Q...', '.......Q', '.....Q..', '..Q.....', '......Q.', '.Q......'], ['...Q....', '.Q......', '....Q...', '.......Q', '.....Q..', 'Q.......', '..Q.....', '......Q.'], ['...Q....', '.Q......', '......Q.', '..Q.....', '.....Q..', '.......Q', 'Q.......', '....Q...'], ['...Q....', '.Q......', '......Q.', '..Q.....', '.....Q..', '.......Q', '....Q...', 'Q.......'], ['...Q....', '.Q......', '......Q.', '....Q...', 'Q.......', '.......Q', '.....Q..', '..Q.....'], ['...Q....', '.Q......', '.......Q', '....Q...', '......Q.', 'Q.......', '..Q.....', '.....Q..'], ['...Q....', '.Q......', '.......Q', '.....Q..', 'Q.......', '..Q.....', '....Q...', '......Q.'], ['...Q....', '.....Q..', 'Q.......', '....Q...', '.Q......', '.......Q', '..Q.....', '......Q.'], ['...Q....', '.....Q..', '.......Q', '.Q......', '......Q.', 'Q.......', '..Q.....', '....Q...'], ['...Q....', '.....Q..', '.......Q', '..Q.....', 'Q.......', '......Q.', '....Q...', '.Q......'], ['...Q....', '......Q.', 'Q.......', '.......Q', '....Q...', '.Q......', '.....Q..', '..Q.....'], ['...Q....', '......Q.', '..Q.....', '.......Q', '.Q......', '....Q...', 'Q.......', '.....Q..'], ['...Q....', '......Q.', '....Q...', '.Q......', '.....Q..', 'Q.......', '..Q.....', '.......Q'], ['...Q....', '......Q.', '....Q...', '..Q.....', 'Q.......', '.....Q..', '.......Q', '.Q......'], ['...Q....', '.......Q', 'Q.......', '..Q.....', '.....Q..', '.Q......', '......Q.', '....Q...'], ['...Q....', '.......Q', 'Q.......', '....Q...', '......Q.', '.Q......', '.....Q..', '..Q.....'], ['...Q....', '.......Q', '....Q...', '..Q.....', 'Q.......', '......Q.', '.Q......', '.....Q..'], ['....Q...', 'Q.......', '...Q....', '.....Q..', '.......Q', '.Q......', '......Q.', '..Q.....'], ['....Q...', 'Q.......', '.......Q', '...Q....', '.Q......', '......Q.', '..Q.....', '.....Q..'], ['....Q...', 'Q.......', '.......Q', '.....Q..', '..Q.....', '......Q.', '.Q......', '...Q....'], ['....Q...', '.Q......', '...Q....', '.....Q..', '.......Q', '..Q.....', 'Q.......', '......Q.'], ['....Q...', '.Q......', '...Q....', '......Q.', '..Q.....', '.......Q', '.....Q..', 'Q.......'], ['....Q...', '.Q......', '.....Q..', 'Q.......', '......Q.', '...Q....', '.......Q', '..Q.....'], ['....Q...', '.Q......', '.......Q', 'Q.......', '...Q....', '......Q.', '..Q.....', '.....Q..'], ['....Q...', '..Q.....', 'Q.......', '.....Q..', '.......Q', '.Q......', '...Q....', '......Q.'], ['....Q...', '..Q.....', 'Q.......', '......Q.', '.Q......', '.......Q', '.....Q..', '...Q....'], ['....Q...', '..Q.....', '.......Q', '...Q....', '......Q.', 'Q.......', '.....Q..', '.Q......'], ['....Q...', '......Q.', 'Q.......', '..Q.....', '.......Q', '.....Q..', '...Q....', '.Q......'], ['....Q...', '......Q.', 'Q.......', '...Q....', '.Q......', '.......Q', '.....Q..', '..Q.....'], ['....Q...', '......Q.', '.Q......', '...Q....', '.......Q', 'Q.......', '..Q.....', '.....Q..'], ['....Q...', '......Q.', '.Q......', '.....Q..', '..Q.....', 'Q.......', '...Q....', '.......Q'], ['....Q...', '......Q.', '.Q......', '.....Q..', '..Q.....', 'Q.......', '.......Q', '...Q....'], ['....Q...', '......Q.', '...Q....', 'Q.......', '..Q.....', '.......Q', '.....Q..', '.Q......'], ['....Q...', '.......Q', '...Q....', 'Q.......', '..Q.....', '.....Q..', '.Q......', '......Q.'], ['....Q...', '.......Q', '...Q....', 'Q.......', '......Q.', '.Q......', '.....Q..', '..Q.....'], ['.....Q..', 'Q.......', '....Q...', '.Q......', '.......Q', '..Q.....', '......Q.', '...Q....'], ['.....Q..', '.Q......', '......Q.', 'Q.......', '..Q.....', '....Q...', '.......Q', '...Q....'], ['.....Q..', '.Q......', '......Q.', 'Q.......', '...Q....', '.......Q', '....Q...', '..Q.....'], ['.....Q..', '..Q.....', 'Q.......', '......Q.', '....Q...', '.......Q', '.Q......', '...Q....'], ['.....Q..', '..Q.....', 'Q.......', '.......Q', '...Q....', '.Q......', '......Q.', '....Q...'], ['.....Q..', '..Q.....', 'Q.......', '.......Q', '....Q...', '.Q......', '...Q....', '......Q.'], ['.....Q..', '..Q.....', '....Q...', '......Q.', 'Q.......', '...Q....', '.Q......', '.......Q'], ['.....Q..', '..Q.....', '....Q...', '.......Q', 'Q.......', '...Q....', '.Q......', '......Q.'], ['.....Q..', '..Q.....', '......Q.', '.Q......', '...Q....', '.......Q', 'Q.......', '....Q...'], ['.....Q..', '..Q.....', '......Q.', '.Q......', '.......Q', '....Q...', 'Q.......', '...Q....'], ['.....Q..', '..Q.....', '......Q.', '...Q....', 'Q.......', '.......Q', '.Q......', '....Q...'], ['.....Q..', '...Q....', 'Q.......', '....Q...', '.......Q', '.Q......', '......Q.', '..Q.....'], ['.....Q..', '...Q....', '.Q......', '.......Q', '....Q...', '......Q.', 'Q.......', '..Q.....'], ['.....Q..', '...Q....', '......Q.', 'Q.......', '..Q.....', '....Q...', '.Q......', '.......Q'], ['.....Q..', '...Q....', '......Q.', 'Q.......', '.......Q', '.Q......', '....Q...', '..Q.....'], ['.....Q..', '.......Q', '.Q......', '...Q....', 'Q.......', '......Q.', '....Q...', '..Q.....'], ['......Q.', 'Q.......', '..Q.....', '.......Q', '.....Q..', '...Q....', '.Q......', '....Q...'], ['......Q.', '.Q......', '...Q....', 'Q.......', '.......Q', '....Q...', '..Q.....', '.....Q..'], ['......Q.', '.Q......', '.....Q..', '..Q.....', 'Q.......', '...Q....', '.......Q', '....Q...'], ['......Q.', '..Q.....', 'Q.......', '.....Q..', '.......Q', '....Q...', '.Q......', '...Q....'], ['......Q.', '..Q.....', '.......Q', '.Q......', '....Q...', 'Q.......', '.....Q..', '...Q....'], ['......Q.', '...Q....', '.Q......', '....Q...', '.......Q', 'Q.......', '..Q.....', '.....Q..'], ['......Q.', '...Q....', '.Q......', '.......Q', '.....Q..', 'Q.......', '..Q.....', '....Q...'], ['......Q.', '....Q...', '..Q.....', 'Q.......', '.....Q..', '.......Q', '.Q......', '...Q....'], ['.......Q', '.Q......', '...Q....', 'Q.......', '......Q.', '....Q...', '..Q.....', '.....Q..'], ['.......Q', '.Q......', '....Q...', '..Q.....', 'Q.......', '......Q.', '...Q....', '.....Q..'], ['.......Q', '..Q.....', 'Q.......', '.....Q..', '.Q......', '....Q...', '......Q.', '...Q....'], ['.......Q', '...Q....', 'Q.......', '..Q.....', '.....Q..', '.Q......', '......Q.', '....Q...']]\n elif n == 9:\n return [['Q........', '..Q......', '.....Q...', '.......Q.', '.Q.......', '...Q.....', '........Q', '......Q..', '....Q....'], ['Q........', '..Q......', '......Q..', '.Q.......', '.......Q.', '....Q....', '........Q', '...Q.....', '.....Q...'], ['Q........', '..Q......', '.......Q.', '.....Q...', '........Q', '.Q.......', '....Q....', '......Q..', '...Q.....'], ['Q........', '...Q.....', '.Q.......', '.......Q.', '.....Q...', '........Q', '..Q......', '....Q....', '......Q..'], ['Q........', '...Q.....', '.....Q...', '..Q......', '........Q', '.Q.......', '.......Q.', '....Q....', '......Q..'], ['Q........', '...Q.....', '.....Q...', '.......Q.', '.Q.......', '....Q....', '..Q......', '........Q', '......Q..'], ['Q........', '...Q.....', '......Q..', '..Q......', '.......Q.', '.Q.......', '....Q....', '........Q', '.....Q...'], ['Q........', '...Q.....', '......Q..', '........Q', '.Q.......', '....Q....', '.......Q.', '.....Q...', '..Q......'], ['Q........', '...Q.....', '.......Q.', '..Q......', '........Q', '......Q..', '....Q....', '.Q.......', '.....Q...'], ['Q........', '....Q....', '.Q.......', '.....Q...', '........Q', '..Q......', '.......Q.', '...Q.....', '......Q..'], ['Q........', '....Q....', '......Q..', '.Q.......', '.....Q...', '..Q......', '........Q', '...Q.....', '.......Q.'], ['Q........', '....Q....', '......Q..', '........Q', '..Q......', '.......Q.', '.Q.......', '...Q.....', '.....Q...'], ['Q........', '....Q....', '......Q..', '........Q', '...Q.....', '.Q.......', '.......Q.', '.....Q...', '..Q......'], ['Q........', '....Q....', '........Q', '.Q.......', '.....Q...', '.......Q.', '..Q......', '......Q..', '...Q.....'], ['Q........', '....Q....', '........Q', '.....Q...', '...Q.....', '.Q.......', '.......Q.', '..Q......', '......Q..'], ['Q........', '.....Q...', '.Q.......', '........Q', '......Q..', '...Q.....', '.......Q.', '..Q......', '....Q....'], ['Q........', '.....Q...', '...Q.....', '.Q.......', '......Q..', '........Q', '..Q......', '....Q....', '.......Q.'], ['Q........', '.....Q...', '...Q.....', '.Q.......', '.......Q.', '..Q......', '........Q', '......Q..', '....Q....'], ['Q........', '.....Q...', '.......Q.', '..Q......', '......Q..', '...Q.....', '.Q.......', '........Q', '....Q....'], ['Q........', '.....Q...', '.......Q.', '....Q....', '.Q.......', '...Q.....', '........Q', '......Q..', '..Q......'], ['Q........', '.....Q...', '........Q', '....Q....', '.Q.......', '.......Q.', '..Q......', '......Q..', '...Q.....'], ['Q........', '......Q..', '...Q.....', '.....Q...', '........Q', '.Q.......', '....Q....', '..Q......', '.......Q.'], ['Q........', '......Q..', '...Q.....', '.......Q.', '..Q......', '....Q....', '........Q', '.Q.......', '.....Q...'], ['Q........', '......Q..', '...Q.....', '.......Q.', '..Q......', '........Q', '.....Q...', '.Q.......', '....Q....'], ['Q........', '......Q..', '....Q....', '.......Q.', '.Q.......', '........Q', '..Q......', '.....Q...', '...Q.....'], ['Q........', '.......Q.', '...Q.....', '.Q.......', '......Q..', '........Q', '.....Q...', '..Q......', '....Q....'], ['Q........', '.......Q.', '....Q....', '..Q......', '.....Q...', '........Q', '.Q.......', '...Q.....', '......Q..'], ['Q........', '.......Q.', '....Q....', '..Q......', '........Q', '......Q..', '.Q.......', '...Q.....', '.....Q...'], ['.Q.......', '...Q.....', 'Q........', '......Q..', '........Q', '.....Q...', '..Q......', '....Q....', '.......Q.'], ['.Q.......', '...Q.....', '......Q..', 'Q........', '..Q......', '........Q', '.....Q...', '.......Q.', '....Q....'], ['.Q.......', '...Q.....', '.......Q.', '..Q......', '........Q', '.....Q...', 'Q........', '....Q....', '......Q..'], ['.Q.......', '...Q.....', '........Q', '......Q..', '..Q......', 'Q........', '.....Q...', '.......Q.', '....Q....'], ['.Q.......', '...Q.....', '........Q', '......Q..', '....Q....', '..Q......', 'Q........', '.....Q...', '.......Q.'], ['.Q.......', '....Q....', '......Q..', 'Q........', '..Q......', '.......Q.', '.....Q...', '...Q.....', '........Q'], ['.Q.......', '....Q....', '......Q..', '...Q.....', 'Q........', '..Q......', '........Q', '.....Q...', '.......Q.'], ['.Q.......', '....Q....', '......Q..', '........Q', '..Q......', '.....Q...', '...Q.....', 'Q........', '.......Q.'], ['.Q.......', '....Q....', '......Q..', '........Q', '...Q.....', '.......Q.', 'Q........', '..Q......', '.....Q...'], ['.Q.......', '....Q....', '.......Q.', 'Q........', '..Q......', '.....Q...', '........Q', '......Q..', '...Q.....'], ['.Q.......', '....Q....', '.......Q.', 'Q........', '........Q', '.....Q...', '..Q......', '......Q..', '...Q.....'], ['.Q.......', '....Q....', '.......Q.', '.....Q...', '........Q', '..Q......', 'Q........', '...Q.....', '......Q..'], ['.Q.......', '....Q....', '.......Q.', '.....Q...', '........Q', '..Q......', 'Q........', '......Q..', '...Q.....'], ['.Q.......', '....Q....', '........Q', '...Q.....', 'Q........', '.......Q.', '.....Q...', '..Q......', '......Q..'], ['.Q.......', '.....Q...', 'Q........', '..Q......', '......Q..', '........Q', '...Q.....', '.......Q.', '....Q....'], ['.Q.......', '.....Q...', 'Q........', '......Q..', '...Q.....', '.......Q.', '..Q......', '....Q....', '........Q'], ['.Q.......', '.....Q...', 'Q........', '......Q..', '....Q....', '..Q......', '........Q', '...Q.....', '.......Q.'], ['.Q.......', '.....Q...', 'Q........', '........Q', '....Q....', '.......Q.', '...Q.....', '......Q..', '..Q......'], ['.Q.......', '.....Q...', '..Q......', 'Q........', '.......Q.', '...Q.....', '........Q', '......Q..', '....Q....'], ['.Q.......', '.....Q...', '........Q', '..Q......', '....Q....', '.......Q.', '...Q.....', 'Q........', '......Q..'], ['.Q.......', '......Q..', '....Q....', 'Q........', '........Q', '...Q.....', '.....Q...', '.......Q.', '..Q......'], ['.Q.......', '......Q..', '....Q....', '.......Q.', 'Q........', '...Q.....', '.....Q...', '..Q......', '........Q'], ['.Q.......', '......Q..', '........Q', '.....Q...', '..Q......', 'Q........', '...Q.....', '.......Q.', '....Q....'], ['.Q.......', '.......Q.', 'Q........', '...Q.....', '......Q..', '........Q', '.....Q...', '..Q......', '....Q....'], ['.Q.......', '.......Q.', '....Q....', '..Q......', '........Q', '.....Q...', '...Q.....', 'Q........', '......Q..'], ['.Q.......', '.......Q.', '.....Q...', '........Q', '..Q......', 'Q........', '...Q.....', '......Q..', '....Q....'], ['.Q.......', '........Q', '....Q....', '..Q......', '.......Q.', '...Q.....', '......Q..', 'Q........', '.....Q...'], ['.Q.......', '........Q', '.....Q...', '..Q......', '....Q....', '.......Q.', 'Q........', '...Q.....', '......Q..'], ['.Q.......', '........Q', '.....Q...', '..Q......', '......Q..', '...Q.....', 'Q........', '.......Q.', '....Q....'], ['.Q.......', '........Q', '.....Q...', '...Q.....', '......Q..', 'Q........', '..Q......', '....Q....', '.......Q.'], ['..Q......', 'Q........', '...Q.....', '......Q..', '........Q', '.Q.......', '....Q....', '.......Q.', '.....Q...'], ['..Q......', 'Q........', '.....Q...', '.......Q.', '....Q....', '.Q.......', '...Q.....', '........Q', '......Q..'], ['..Q......', 'Q........', '......Q..', '.Q.......', '.......Q.', '.....Q...', '...Q.....', '........Q', '....Q....'], ['..Q......', 'Q........', '......Q..', '....Q....', '.......Q.', '.Q.......', '...Q.....', '.....Q...', '........Q'], ['..Q......', 'Q........', '.......Q.', '...Q.....', '........Q', '......Q..', '....Q....', '.Q.......', '.....Q...'], ['..Q......', 'Q........', '........Q', '......Q..', '....Q....', '.Q.......', '.......Q.', '.....Q...', '...Q.....'], ['..Q......', '....Q....', '.Q.......', '.......Q.', 'Q........', '...Q.....', '......Q..', '........Q', '.....Q...'], ['..Q......', '....Q....', '.Q.......', '.......Q.', 'Q........', '......Q..', '...Q.....', '.....Q...', '........Q'], ['..Q......', '....Q....', '......Q..', 'Q........', '...Q.....', '.Q.......', '.......Q.', '.....Q...', '........Q'], ['..Q......', '....Q....', '.......Q.', '.Q.......', '........Q', '.....Q...', 'Q........', '......Q..', '...Q.....'], ['..Q......', '....Q....', '.......Q.', '.Q.......', '........Q', '......Q..', 'Q........', '...Q.....', '.....Q...'], ['..Q......', '....Q....', '........Q', '.Q.......', '...Q.....', '......Q..', 'Q........', '.......Q.', '.....Q...'], ['..Q......', '....Q....', '........Q', '...Q.....', 'Q........', '......Q..', '.Q.......', '.....Q...', '.......Q.'], ['..Q......', '.....Q...', '.Q.......', '......Q..', 'Q........', '...Q.....', '.......Q.', '....Q....', '........Q'], ['..Q......', '.....Q...', '.Q.......', '........Q', '....Q....', 'Q........', '.......Q.', '...Q.....', '......Q..'], ['..Q......', '.....Q...', '.......Q.', 'Q........', '...Q.....', '......Q..', '....Q....', '.Q.......', '........Q'], ['..Q......', '.....Q...', '.......Q.', 'Q........', '....Q....', '........Q', '.Q.......', '...Q.....', '......Q..'], ['..Q......', '.....Q...', '.......Q.', '.Q.......', '...Q.....', '........Q', '......Q..', '....Q....', 'Q........'], ['..Q......', '.....Q...', '.......Q.', '....Q....', 'Q........', '........Q', '......Q..', '.Q.......', '...Q.....'], ['..Q......', '.....Q...', '.......Q.', '....Q....', '.Q.......', '........Q', '......Q..', '...Q.....', 'Q........'], ['..Q......', '.....Q...', '........Q', 'Q........', '.......Q.', '...Q.....', '.Q.......', '......Q..', '....Q....'], ['..Q......', '.....Q...', '........Q', '.Q.......', '....Q....', '......Q..', '...Q.....', 'Q........', '.......Q.'], ['..Q......', '.....Q...', '........Q', '.Q.......', '.......Q.', 'Q........', '...Q.....', '......Q..', '....Q....'], ['..Q......', '.....Q...', '........Q', '....Q....', '.......Q.', 'Q........', '...Q.....', '.Q.......', '......Q..'], ['..Q......', '.....Q...', '........Q', '......Q..', 'Q........', '...Q.....', '.Q.......', '....Q....', '.......Q.'], ['..Q......', '.....Q...', '........Q', '......Q..', '.Q.......', '...Q.....', '.......Q.', 'Q........', '....Q....'], ['..Q......', '.....Q...', '........Q', '......Q..', '...Q.....', 'Q........', '.......Q.', '.Q.......', '....Q....'], ['..Q......', '......Q..', '.Q.......', '...Q.....', '.......Q.', 'Q........', '....Q....', '........Q', '.....Q...'], ['..Q......', '......Q..', '.Q.......', '.......Q.', '....Q....', '........Q', 'Q........', '.....Q...', '...Q.....'], ['..Q......', '......Q..', '.Q.......', '.......Q.', '.....Q...', '...Q.....', 'Q........', '....Q....', '........Q'], ['..Q......', '......Q..', '...Q.....', '.Q.......', '........Q', '....Q....', 'Q........', '.......Q.', '.....Q...'], ['..Q......', '......Q..', '...Q.....', '.Q.......', '........Q', '.....Q...', 'Q........', '....Q....', '.......Q.'], ['..Q......', '......Q..', '...Q.....', '.......Q.', '....Q....', '........Q', 'Q........', '.....Q...', '.Q.......'], ['..Q......', '......Q..', '........Q', 'Q........', '....Q....', '.Q.......', '.......Q.', '.....Q...', '...Q.....'], ['..Q......', '......Q..', '........Q', '...Q.....', '.Q.......', '....Q....', '.......Q.', '.....Q...', 'Q........'], ['..Q......', '.......Q.', '.Q.......', '...Q.....', '........Q', '......Q..', '....Q....', 'Q........', '.....Q...'], ['..Q......', '.......Q.', '...Q.....', '......Q..', '........Q', '.Q.......', '....Q....', 'Q........', '.....Q...'], ['..Q......', '.......Q.', '.....Q...', 'Q........', '........Q', '.Q.......', '....Q....', '......Q..', '...Q.....'], ['..Q......', '.......Q.', '.....Q...', '...Q.....', '........Q', 'Q........', '....Q....', '......Q..', '.Q.......'], ['..Q......', '.......Q.', '.....Q...', '........Q', '.Q.......', '....Q....', 'Q........', '...Q.....', '......Q..'], ['..Q......', '........Q', '.Q.......', '....Q....', '.......Q.', 'Q........', '......Q..', '...Q.....', '.....Q...'], ['..Q......', '........Q', '...Q.....', 'Q........', '.......Q.', '.....Q...', '.Q.......', '......Q..', '....Q....'], ['..Q......', '........Q', '...Q.....', '.Q.......', '.......Q.', '.....Q...', 'Q........', '......Q..', '....Q....'], ['..Q......', '........Q', '...Q.....', '.......Q.', '....Q....', '.Q.......', '.....Q...', 'Q........', '......Q..'], ['..Q......', '........Q', '.....Q...', '.Q.......', '....Q....', '......Q..', 'Q........', '...Q.....', '.......Q.'], ['..Q......', '........Q', '.....Q...', '...Q.....', 'Q........', '......Q..', '....Q....', '.Q.......', '.......Q.'], ['..Q......', '........Q', '.....Q...', '.......Q.', '.Q.......', '...Q.....', 'Q........', '......Q..', '....Q....'], ['...Q.....', 'Q........', '..Q......', '.....Q...', '........Q', '.Q.......', '.......Q.', '....Q....', '......Q..'], ['...Q.....', 'Q........', '....Q....', '.Q.......', '........Q', '......Q..', '..Q......', '.......Q.', '.....Q...'], ['...Q.....', 'Q........', '....Q....', '.......Q.', '.Q.......', '......Q..', '..Q......', '.....Q...', '........Q'], ['...Q.....', 'Q........', '....Q....', '........Q', '.Q.......', '.....Q...', '.......Q.', '..Q......', '......Q..'], ['...Q.....', 'Q........', '......Q..', '........Q', '.Q.......', '.....Q...', '.......Q.', '..Q......', '....Q....'], ['...Q.....', 'Q........', '........Q', '.....Q...', '..Q......', '......Q..', '.Q.......', '.......Q.', '....Q....'], ['...Q.....', '.Q.......', '....Q....', '.......Q.', 'Q........', '..Q......', '.....Q...', '........Q', '......Q..'], ['...Q.....', '.Q.......', '......Q..', '..Q......', 'Q........', '.......Q.', '....Q....', '........Q', '.....Q...'], ['...Q.....', '.Q.......', '......Q..', '........Q', 'Q........', '....Q....', '.......Q.', '.....Q...', '..Q......'], ['...Q.....', '.Q.......', '......Q..', '........Q', 'Q........', '.......Q.', '....Q....', '..Q......', '.....Q...'], ['...Q.....', '.Q.......', '.......Q.', '..Q......', '........Q', '......Q..', '....Q....', 'Q........', '.....Q...'], ['...Q.....', '.Q.......', '........Q', '..Q......', '.....Q...', '.......Q.', 'Q........', '....Q....', '......Q..'], ['...Q.....', '.Q.......', '........Q', '....Q....', 'Q........', '.......Q.', '.....Q...', '..Q......', '......Q..'], ['...Q.....', '.....Q...', 'Q........', '....Q....', '.Q.......', '.......Q.', '..Q......', '......Q..', '........Q'], ['...Q.....', '.....Q...', 'Q........', '........Q', '....Q....', '.......Q.', '.Q.......', '......Q..', '..Q......'], ['...Q.....', '.....Q...', 'Q........', '........Q', '......Q..', '..Q......', '.......Q.', '.Q.......', '....Q....'], ['...Q.....', '.....Q...', '..Q......', '........Q', '.Q.......', '....Q....', '.......Q.', 'Q........', '......Q..'], ['...Q.....', '.....Q...', '..Q......', '........Q', '.Q.......', '.......Q.', '....Q....', '......Q..', 'Q........'], ['...Q.....', '.....Q...', '..Q......', '........Q', '......Q..', 'Q........', '.......Q.', '.Q.......', '....Q....'], ['...Q.....', '.....Q...', '.......Q.', '.Q.......', '....Q....', 'Q........', '........Q', '......Q..', '..Q......'], ['...Q.....', '.....Q...', '.......Q.', '.Q.......', '....Q....', '......Q..', '........Q', 'Q........', '..Q......'], ['...Q.....', '.....Q...', '.......Q.', '.Q.......', '......Q..', 'Q........', '..Q......', '....Q....', '........Q'], ['...Q.....', '.....Q...', '.......Q.', '..Q......', 'Q........', '......Q..', '....Q....', '.Q.......', '........Q'], ['...Q.....', '.....Q...', '........Q', '..Q......', 'Q........', '.......Q.', '.Q.......', '....Q....', '......Q..'], ['...Q.....', '......Q..', 'Q........', '..Q......', '........Q', '.....Q...', '.......Q.', '....Q....', '.Q.......'], ['...Q.....', '......Q..', 'Q........', '.....Q...', '........Q', '.Q.......', '.......Q.', '....Q....', '..Q......'], ['...Q.....', '......Q..', 'Q........', '.......Q.', '....Q....', '.Q.......', '........Q', '..Q......', '.....Q...'], ['...Q.....', '......Q..', '..Q......', '.....Q...', '........Q', 'Q........', '.......Q.', '....Q....', '.Q.......'], ['...Q.....', '......Q..', '..Q......', '.......Q.', '.Q.......', '....Q....', '........Q', '.....Q...', 'Q........'], ['...Q.....', '......Q..', '..Q......', '.......Q.', '.....Q...', 'Q........', '........Q', '.Q.......', '....Q....'], ['...Q.....', '......Q..', '..Q......', '.......Q.', '.....Q...', '.Q.......', '........Q', '....Q....', 'Q........'], ['...Q.....', '......Q..', '....Q....', '.Q.......', '........Q', 'Q........', '..Q......', '.......Q.', '.....Q...'], ['...Q.....', '......Q..', '....Q....', '.Q.......', '........Q', 'Q........', '.....Q...', '.......Q.', '..Q......'], ['...Q.....', '......Q..', '....Q....', '.Q.......', '........Q', '.....Q...', '.......Q.', '..Q......', 'Q........'], ['...Q.....', '......Q..', '........Q', '.Q.......', '....Q....', '.......Q.', 'Q........', '..Q......', '.....Q...'], ['...Q.....', '......Q..', '........Q', '.Q.......', '.....Q...', 'Q........', '..Q......', '....Q....', '.......Q.'], ['...Q.....', '......Q..', '........Q', '.....Q...', '..Q......', 'Q........', '.......Q.', '....Q....', '.Q.......'], ['...Q.....', '.......Q.', 'Q........', '....Q....', '......Q..', '.Q.......', '.....Q...', '..Q......', '........Q'], ['...Q.....', '.......Q.', '....Q....', '..Q......', 'Q........', '.....Q...', '.Q.......', '........Q', '......Q..'], ['...Q.....', '.......Q.', '....Q....', '..Q......', 'Q........', '......Q..', '.Q.......', '.....Q...', '........Q'], ['...Q.....', '........Q', '..Q......', '.....Q...', '.Q.......', '......Q..', '....Q....', 'Q........', '.......Q.'], ['...Q.....', '........Q', '....Q....', '..Q......', 'Q........', '.....Q...', '.......Q.', '.Q.......', '......Q..'], ['...Q.....', '........Q', '....Q....', '..Q......', 'Q........', '......Q..', '.Q.......', '.......Q.', '.....Q...'], ['...Q.....', '........Q', '....Q....', '.......Q.', 'Q........', '..Q......', '.....Q...', '.Q.......', '......Q..'], ['....Q....', 'Q........', '.....Q...', '...Q.....', '.Q.......', '.......Q.', '..Q......', '........Q', '......Q..'], ['....Q....', 'Q........', '.......Q.', '...Q.....', '.Q.......', '......Q..', '........Q', '.....Q...', '..Q......'], ['....Q....', 'Q........', '.......Q.', '.....Q...', '..Q......', '......Q..', '.Q.......', '...Q.....', '........Q'], ['....Q....', '.Q.......', '...Q.....', 'Q........', '......Q..', '........Q', '..Q......', '.....Q...', '.......Q.'], ['....Q....', '.Q.......', '...Q.....', '........Q', '......Q..', '..Q......', 'Q........', '.....Q...', '.......Q.'], ['....Q....', '.Q.......', '.....Q...', 'Q........', '..Q......', '......Q..', '........Q', '...Q.....', '.......Q.'], ['....Q....', '.Q.......', '.....Q...', '........Q', '..Q......', '.......Q.', '...Q.....', '......Q..', 'Q........'], ['....Q....', '.Q.......', '.....Q...', '........Q', '......Q..', '...Q.....', 'Q........', '..Q......', '.......Q.'], ['....Q....', '.Q.......', '.......Q.', 'Q........', '...Q.....', '......Q..', '........Q', '.....Q...', '..Q......'], ['....Q....', '.Q.......', '.......Q.', 'Q........', '......Q..', '........Q', '..Q......', '.....Q...', '...Q.....'], ['....Q....', '.Q.......', '.......Q.', '..Q......', '......Q..', '...Q.....', 'Q........', '........Q', '.....Q...'], ['....Q....', '.Q.......', '.......Q.', '..Q......', '......Q..', '........Q', 'Q........', '.....Q...', '...Q.....'], ['....Q....', '.Q.......', '........Q', 'Q........', '.....Q...', '.......Q.', '..Q......', '......Q..', '...Q.....'], ['....Q....', '.Q.......', '........Q', '.....Q...', '..Q......', '......Q..', '...Q.....', 'Q........', '.......Q.'], ['....Q....', '..Q......', 'Q........', '.....Q...', '.Q.......', '........Q', '......Q..', '...Q.....', '.......Q.'], ['....Q....', '..Q......', 'Q........', '.....Q...', '.......Q.', '.Q.......', '...Q.....', '......Q..', '........Q'], ['....Q....', '..Q......', 'Q........', '......Q..', '.Q.......', '.......Q.', '.....Q...', '...Q.....', '........Q'], ['....Q....', '..Q......', '.....Q...', '........Q', '.Q.......', '.......Q.', 'Q........', '...Q.....', '......Q..'], ['....Q....', '..Q......', '.....Q...', '........Q', '......Q..', 'Q........', '...Q.....', '.Q.......', '.......Q.'], ['....Q....', '..Q......', '.....Q...', '........Q', '......Q..', '.Q.......', '...Q.....', '.......Q.', 'Q........'], ['....Q....', '..Q......', '.....Q...', '........Q', '......Q..', '...Q.....', 'Q........', '.......Q.', '.Q.......'], ['....Q....', '..Q......', '.......Q.', '...Q.....', '.Q.......', '........Q', '.....Q...', 'Q........', '......Q..'], ['....Q....', '..Q......', '.......Q.', '...Q.....', '......Q..', '........Q', '.Q.......', '.....Q...', 'Q........'], ['....Q....', '..Q......', '.......Q.', '.....Q...', '.Q.......', '........Q', 'Q........', '...Q.....', '......Q..'], ['....Q....', '..Q......', '.......Q.', '.....Q...', '.Q.......', '........Q', '......Q..', 'Q........', '...Q.....'], ['....Q....', '..Q......', '........Q', '...Q.....', '.Q.......', '.......Q.', '.....Q...', 'Q........', '......Q..'], ['....Q....', '..Q......', '........Q', '.....Q...', '.......Q.', '.Q.......', '...Q.....', 'Q........', '......Q..'], ['....Q....', '......Q..', 'Q........', '...Q.....', '.Q.......', '.......Q.', '.....Q...', '........Q', '..Q......'], ['....Q....', '......Q..', 'Q........', '.....Q...', '.......Q.', '.Q.......', '...Q.....', '........Q', '..Q......'], ['....Q....', '......Q..', '.Q.......', '...Q.....', '.......Q.', 'Q........', '..Q......', '........Q', '.....Q...'], ['....Q....', '......Q..', '.Q.......', '...Q.....', '.......Q.', 'Q........', '........Q', '.....Q...', '..Q......'], ['....Q....', '......Q..', '.Q.......', '.....Q...', '..Q......', 'Q........', '.......Q.', '...Q.....', '........Q'], ['....Q....', '......Q..', '.Q.......', '.....Q...', '.......Q.', 'Q........', '...Q.....', '........Q', '..Q......'], ['....Q....', '......Q..', '...Q.....', 'Q........', '..Q......', '.....Q...', '........Q', '.Q.......', '.......Q.'], ['....Q....', '......Q..', '...Q.....', 'Q........', '..Q......', '.......Q.', '.....Q...', '.Q.......', '........Q'], ['....Q....', '......Q..', '...Q.....', 'Q........', '..Q......', '........Q', '.....Q...', '.......Q.', '.Q.......'], ['....Q....', '......Q..', '...Q.....', 'Q........', '.......Q.', '.Q.......', '........Q', '.....Q...', '..Q......'], ['....Q....', '......Q..', '........Q', '..Q......', '.......Q.', '.Q.......', '...Q.....', '.....Q...', 'Q........'], ['....Q....', '......Q..', '........Q', '...Q.....', '.Q.......', '.......Q.', '.....Q...', '..Q......', 'Q........'], ['....Q....', '......Q..', '........Q', '...Q.....', '.......Q.', 'Q........', '..Q......', '.....Q...', '.Q.......'], ['....Q....', '.......Q.', 'Q........', '...Q.....', '......Q..', '..Q......', '.....Q...', '........Q', '.Q.......'], ['....Q....', '.......Q.', 'Q........', '........Q', '...Q.....', '.Q.......', '......Q..', '..Q......', '.....Q...'], ['....Q....', '.......Q.', '.Q.......', '......Q..', '..Q......', 'Q........', '........Q', '...Q.....', '.....Q...'], ['....Q....', '.......Q.', '.Q.......', '......Q..', '..Q......', '.....Q...', '........Q', 'Q........', '...Q.....'], ['....Q....', '.......Q.', '.Q.......', '........Q', '..Q......', 'Q........', '......Q..', '...Q.....', '.....Q...'], ['....Q....', '.......Q.', '.Q.......', '........Q', '.....Q...', '..Q......', 'Q........', '...Q.....', '......Q..'], ['....Q....', '.......Q.', '...Q.....', 'Q........', '..Q......', '.....Q...', '........Q', '......Q..', '.Q.......'], ['....Q....', '.......Q.', '...Q.....', 'Q........', '......Q..', '.Q.......', '.....Q...', '..Q......', '........Q'], ['....Q....', '.......Q.', '...Q.....', '........Q', '......Q..', '..Q......', 'Q........', '.....Q...', '.Q.......'], ['....Q....', '.......Q.', '.....Q...', 'Q........', '..Q......', '......Q..', '........Q', '...Q.....', '.Q.......'], ['....Q....', '.......Q.', '.....Q...', '........Q', '..Q......', 'Q........', '......Q..', '...Q.....', '.Q.......'], ['....Q....', '........Q', '.Q.......', '...Q.....', '......Q..', '..Q......', '.......Q.', '.....Q...', 'Q........'], ['....Q....', '........Q', '.Q.......', '.....Q...', '.......Q.', '..Q......', 'Q........', '...Q.....', '......Q..'], ['....Q....', '........Q', '...Q.....', '.....Q...', '.......Q.', '.Q.......', '......Q..', 'Q........', '..Q......'], ['.....Q...', 'Q........', '....Q....', '.Q.......', '........Q', '......Q..', '...Q.....', '.......Q.', '..Q......'], ['.....Q...', 'Q........', '....Q....', '......Q..', '........Q', '..Q......', '.......Q.', '.Q.......', '...Q.....'], ['.....Q...', 'Q........', '....Q....', '......Q..', '........Q', '...Q.....', '.Q.......', '.......Q.', '..Q......'], ['.....Q...', 'Q........', '......Q..', '...Q.....', '.......Q.', '..Q......', '....Q....', '........Q', '.Q.......'], ['.....Q...', '.Q.......', '....Q....', '......Q..', '........Q', '..Q......', '.......Q.', '...Q.....', 'Q........'], ['.....Q...', '.Q.......', '....Q....', '......Q..', '........Q', '...Q.....', '.......Q.', 'Q........', '..Q......'], ['.....Q...', '.Q.......', '........Q', '....Q....', '..Q......', '.......Q.', '...Q.....', '......Q..', 'Q........'], ['.....Q...', '..Q......', 'Q........', '...Q.....', '......Q..', '........Q', '.Q.......', '....Q....', '.......Q.'], ['.....Q...', '..Q......', 'Q........', '.......Q.', '...Q.....', '........Q', '......Q..', '....Q....', '.Q.......'], ['.....Q...', '..Q......', 'Q........', '.......Q.', '....Q....', '.Q.......', '........Q', '......Q..', '...Q.....'], ['.....Q...', '..Q......', '....Q....', '.......Q.', 'Q........', '...Q.....', '.Q.......', '......Q..', '........Q'], ['.....Q...', '..Q......', '....Q....', '.......Q.', 'Q........', '........Q', '...Q.....', '.Q.......', '......Q..'], ['.....Q...', '..Q......', '....Q....', '.......Q.', 'Q........', '........Q', '......Q..', '.Q.......', '...Q.....'], ['.....Q...', '..Q......', '......Q..', '.Q.......', '...Q.....', '.......Q.', 'Q........', '....Q....', '........Q'], ['.....Q...', '..Q......', '......Q..', '.Q.......', '...Q.....', '........Q', 'Q........', '.......Q.', '....Q....'], ['.....Q...', '..Q......', '......Q..', '.Q.......', '.......Q.', '....Q....', 'Q........', '...Q.....', '........Q'], ['.....Q...', '..Q......', '......Q..', '...Q.....', 'Q........', '........Q', '.Q.......', '....Q....', '.......Q.'], ['.....Q...', '..Q......', '........Q', '.Q.......', '....Q....', '.......Q.', 'Q........', '......Q..', '...Q.....'], ['.....Q...', '..Q......', '........Q', '...Q.....', 'Q........', '.......Q.', '.Q.......', '....Q....', '......Q..'], ['.....Q...', '..Q......', '........Q', '......Q..', 'Q........', '...Q.....', '.Q.......', '....Q....', '.......Q.'], ['.....Q...', '...Q.....', 'Q........', '......Q..', '........Q', '.Q.......', '.......Q.', '....Q....', '..Q......'], ['.....Q...', '...Q.....', '.Q.......', '......Q..', '........Q', '..Q......', '....Q....', '.......Q.', 'Q........'], ['.....Q...', '...Q.....', '.Q.......', '.......Q.', '..Q......', '........Q', '......Q..', '....Q....', 'Q........'], ['.....Q...', '...Q.....', '.Q.......', '.......Q.', '....Q....', '..Q......', 'Q........', '........Q', '......Q..'], ['.....Q...', '...Q.....', '.Q.......', '.......Q.', '....Q....', '........Q', 'Q........', '..Q......', '......Q..'], ['.....Q...', '...Q.....', '......Q..', 'Q........', '..Q......', '........Q', '.Q.......', '.......Q.', '....Q....'], ['.....Q...', '...Q.....', '......Q..', 'Q........', '.......Q.', '.Q.......', '....Q....', '..Q......', '........Q'], ['.....Q...', '...Q.....', '......Q..', 'Q........', '.......Q.', '....Q....', '.Q.......', '........Q', '..Q......'], ['.....Q...', '...Q.....', '........Q', 'Q........', '..Q......', '......Q..', '.Q.......', '.......Q.', '....Q....'], ['.....Q...', '...Q.....', '........Q', 'Q........', '....Q....', '.Q.......', '.......Q.', '..Q......', '......Q..'], ['.....Q...', '...Q.....', '........Q', '....Q....', '.......Q.', '.Q.......', '......Q..', '..Q......', 'Q........'], ['.....Q...', '.......Q.', 'Q........', '....Q....', '........Q', '.Q.......', '...Q.....', '......Q..', '..Q......'], ['.....Q...', '.......Q.', 'Q........', '......Q..', '...Q.....', '.Q.......', '........Q', '....Q....', '..Q......'], ['.....Q...', '.......Q.', '.Q.......', '......Q..', 'Q........', '..Q......', '....Q....', '........Q', '...Q.....'], ['.....Q...', '.......Q.', '..Q......', 'Q........', '........Q', '.Q.......', '....Q....', '......Q..', '...Q.....'], ['.....Q...', '.......Q.', '..Q......', 'Q........', '........Q', '....Q....', '.Q.......', '...Q.....', '......Q..'], ['.....Q...', '.......Q.', '..Q......', '......Q..', '........Q', '.Q.......', '....Q....', 'Q........', '...Q.....'], ['.....Q...', '.......Q.', '....Q....', '.Q.......', '........Q', '......Q..', '...Q.....', 'Q........', '..Q......'], ['.....Q...', '........Q', 'Q........', '...Q.....', '......Q..', '..Q......', '.......Q.', '.Q.......', '....Q....'], ['.....Q...', '........Q', '..Q......', 'Q........', '.......Q.', '...Q.....', '.Q.......', '......Q..', '....Q....'], ['.....Q...', '........Q', '....Q....', 'Q........', '.......Q.', '...Q.....', '.Q.......', '......Q..', '..Q......'], ['.....Q...', '........Q', '....Q....', '.Q.......', '.......Q.', '..Q......', '......Q..', '...Q.....', 'Q........'], ['.....Q...', '........Q', '....Q....', '.......Q.', 'Q........', '..Q......', '......Q..', '.Q.......', '...Q.....'], ['.....Q...', '........Q', '......Q..', '...Q.....', 'Q........', '.......Q.', '.Q.......', '....Q....', '..Q......'], ['......Q..', 'Q........', '...Q.....', '.Q.......', '.......Q.', '.....Q...', '........Q', '..Q......', '....Q....'], ['......Q..', 'Q........', '...Q.....', '.....Q...', '........Q', '..Q......', '....Q....', '.......Q.', '.Q.......'], ['......Q..', 'Q........', '...Q.....', '.......Q.', '....Q....', '..Q......', '........Q', '.....Q...', '.Q.......'], ['......Q..', 'Q........', '.....Q...', '.Q.......', '....Q....', '.......Q.', '...Q.....', '........Q', '..Q......'], ['......Q..', 'Q........', '.....Q...', '.......Q.', '.Q.......', '...Q.....', '........Q', '..Q......', '....Q....'], ['......Q..', 'Q........', '.....Q...', '........Q', '.Q.......', '...Q.....', '.......Q.', '..Q......', '....Q....'], ['......Q..', 'Q........', '.......Q.', '....Q....', '.Q.......', '........Q', '..Q......', '.....Q...', '...Q.....'], ['......Q..', '.Q.......', '...Q.....', 'Q........', '.......Q.', '....Q....', '........Q', '.....Q...', '..Q......'], ['......Q..', '.Q.......', '...Q.....', '.....Q...', 'Q........', '........Q', '....Q....', '..Q......', '.......Q.'], ['......Q..', '.Q.......', '...Q.....', '........Q', 'Q........', '.......Q.', '....Q....', '..Q......', '.....Q...'], ['......Q..', '.Q.......', '.....Q...', '..Q......', 'Q........', '.......Q.', '....Q....', '........Q', '...Q.....'], ['......Q..', '.Q.......', '.......Q.', '.....Q...', 'Q........', '..Q......', '....Q....', '........Q', '...Q.....'], ['......Q..', '..Q......', 'Q........', '.....Q...', '.......Q.', '....Q....', '.Q.......', '...Q.....', '........Q'], ['......Q..', '..Q......', 'Q........', '........Q', '....Q....', '.......Q.', '.Q.......', '...Q.....', '.....Q...'], ['......Q..', '..Q......', '.....Q...', '.Q.......', '....Q....', 'Q........', '........Q', '...Q.....', '.......Q.'], ['......Q..', '..Q......', '.....Q...', '.......Q.', 'Q........', '...Q.....', '........Q', '....Q....', '.Q.......'], ['......Q..', '..Q......', '.....Q...', '.......Q.', 'Q........', '....Q....', '........Q', '.Q.......', '...Q.....'], ['......Q..', '..Q......', '.......Q.', '.Q.......', '...Q.....', '.....Q...', '........Q', '....Q....', 'Q........'], ['......Q..', '..Q......', '.......Q.', '.Q.......', '....Q....', 'Q........', '........Q', '...Q.....', '.....Q...'], ['......Q..', '..Q......', '.......Q.', '.....Q...', '.Q.......', '........Q', '....Q....', 'Q........', '...Q.....'], ['......Q..', '...Q.....', 'Q........', '..Q......', '.....Q...', '........Q', '.Q.......', '.......Q.', '....Q....'], ['......Q..', '...Q.....', 'Q........', '..Q......', '.......Q.', '.....Q...', '.Q.......', '........Q', '....Q....'], ['......Q..', '...Q.....', 'Q........', '..Q......', '........Q', '.....Q...', '.......Q.', '....Q....', '.Q.......'], ['......Q..', '...Q.....', 'Q........', '....Q....', '.Q.......', '........Q', '.....Q...', '.......Q.', '..Q......'], ['......Q..', '...Q.....', 'Q........', '.......Q.', '.Q.......', '........Q', '.....Q...', '..Q......', '....Q....'], ['......Q..', '...Q.....', 'Q........', '.......Q.', '....Q....', '..Q......', '.....Q...', '........Q', '.Q.......'], ['......Q..', '...Q.....', 'Q........', '........Q', '.Q.......', '.....Q...', '.......Q.', '..Q......', '....Q....'], ['......Q..', '...Q.....', '.Q.......', '....Q....', '.......Q.', 'Q........', '..Q......', '.....Q...', '........Q'], ['......Q..', '...Q.....', '.Q.......', '....Q....', '........Q', 'Q........', '..Q......', '.......Q.', '.....Q...'], ['......Q..', '...Q.....', '.Q.......', '.......Q.', '.....Q...', 'Q........', '..Q......', '....Q....', '........Q'], ['......Q..', '...Q.....', '.Q.......', '........Q', '....Q....', 'Q........', '.......Q.', '.....Q...', '..Q......'], ['......Q..', '...Q.....', '.Q.......', '........Q', '.....Q...', '..Q......', '....Q....', '.......Q.', 'Q........'], ['......Q..', '...Q.....', '.......Q.', 'Q........', '....Q....', '........Q', '.Q.......', '.....Q...', '..Q......'], ['......Q..', '...Q.....', '.......Q.', '..Q......', '........Q', '.....Q...', '.Q.......', '....Q....', 'Q........'], ['......Q..', '....Q....', 'Q........', '.....Q...', '........Q', '..Q......', '.......Q.', '...Q.....', '.Q.......'], ['......Q..', '....Q....', 'Q........', '.......Q.', '.....Q...', '..Q......', '........Q', '.Q.......', '...Q.....'], ['......Q..', '....Q....', '.Q.......', '.......Q.', 'Q........', '..Q......', '........Q', '.....Q...', '...Q.....'], ['......Q..', '....Q....', '.Q.......', '.......Q.', 'Q........', '...Q.....', '........Q', '..Q......', '.....Q...'], ['......Q..', '....Q....', '..Q......', '........Q', '.....Q...', '.......Q.', '.Q.......', '...Q.....', 'Q........'], ['......Q..', '....Q....', '.......Q.', '.Q.......', '........Q', '..Q......', '.....Q...', '...Q.....', 'Q........'], ['......Q..', '....Q....', '.......Q.', '.Q.......', '........Q', '.....Q...', '..Q......', 'Q........', '...Q.....'], ['......Q..', '........Q', 'Q........', '..Q......', '....Q....', '.......Q.', '.Q.......', '...Q.....', '.....Q...'], ['......Q..', '........Q', '.Q.......', '.....Q...', 'Q........', '..Q......', '....Q....', '.......Q.', '...Q.....'], ['......Q..', '........Q', '..Q......', '....Q....', '.Q.......', '.......Q.', '.....Q...', '...Q.....', 'Q........'], ['......Q..', '........Q', '..Q......', '.......Q.', '.Q.......', '...Q.....', '.....Q...', 'Q........', '....Q....'], ['......Q..', '........Q', '...Q.....', '.Q.......', '....Q....', '.......Q.', '.....Q...', 'Q........', '..Q......'], ['......Q..', '........Q', '.....Q...', '..Q......', 'Q........', '.......Q.', '....Q....', '.Q.......', '...Q.....'], ['.......Q.', 'Q........', '...Q.....', '.....Q...', '..Q......', '........Q', '......Q..', '....Q....', '.Q.......'], ['.......Q.', 'Q........', '...Q.....', '......Q..', '..Q......', '.....Q...', '........Q', '.Q.......', '....Q....'], ['.......Q.', 'Q........', '...Q.....', '......Q..', '....Q....', '.Q.......', '........Q', '.....Q...', '..Q......'], ['.......Q.', 'Q........', '....Q....', '......Q..', '.Q.......', '.....Q...', '..Q......', '........Q', '...Q.....'], ['.......Q.', '.Q.......', '...Q.....', 'Q........', '......Q..', '........Q', '.....Q...', '..Q......', '....Q....'], ['.......Q.', '.Q.......', '....Q....', '......Q..', 'Q........', '...Q.....', '.....Q...', '........Q', '..Q......'], ['.......Q.', '.Q.......', '........Q', '.....Q...', '..Q......', 'Q........', '...Q.....', '......Q..', '....Q....'], ['.......Q.', '..Q......', 'Q........', '...Q.....', '......Q..', '........Q', '.....Q...', '.Q.......', '....Q....'], ['.......Q.', '..Q......', '....Q....', '.Q.......', '........Q', '.....Q...', '...Q.....', '......Q..', 'Q........'], ['.......Q.', '..Q......', '....Q....', '........Q', 'Q........', '.....Q...', '...Q.....', '.Q.......', '......Q..'], ['.......Q.', '...Q.....', 'Q........', '......Q..', '....Q....', '.Q.......', '.....Q...', '........Q', '..Q......'], ['.......Q.', '...Q.....', '......Q..', '........Q', '.Q.......', '.....Q...', 'Q........', '..Q......', '....Q....'], ['.......Q.', '...Q.....', '........Q', 'Q........', '....Q....', '.Q.......', '.....Q...', '..Q......', '......Q..'], ['.......Q.', '...Q.....', '........Q', '..Q......', '....Q....', '......Q..', 'Q........', '.....Q...', '.Q.......'], ['.......Q.', '...Q.....', '........Q', '..Q......', '.....Q...', '.Q.......', '......Q..', '....Q....', 'Q........'], ['.......Q.', '...Q.....', '........Q', '......Q..', '..Q......', 'Q........', '.....Q...', '.Q.......', '....Q....'], ['.......Q.', '....Q....', 'Q........', '.....Q...', '........Q', '.Q.......', '...Q.....', '......Q..', '..Q......'], ['.......Q.', '....Q....', '.Q.......', '...Q.....', 'Q........', '......Q..', '........Q', '..Q......', '.....Q...'], ['.......Q.', '....Q....', '.Q.......', '...Q.....', 'Q........', '......Q..', '........Q', '.....Q...', '..Q......'], ['.......Q.', '....Q....', '.Q.......', '........Q', 'Q........', '...Q.....', '......Q..', '..Q......', '.....Q...'], ['.......Q.', '....Q....', '.Q.......', '........Q', '......Q..', '...Q.....', 'Q........', '..Q......', '.....Q...'], ['.......Q.', '....Q....', '..Q......', 'Q........', '.....Q...', '.Q.......', '........Q', '......Q..', '...Q.....'], ['.......Q.', '....Q....', '..Q......', 'Q........', '......Q..', '...Q.....', '.....Q...', '........Q', '.Q.......'], ['.......Q.', '....Q....', '..Q......', '.....Q...', '........Q', '......Q..', 'Q........', '...Q.....', '.Q.......'], ['.......Q.', '....Q....', '..Q......', '........Q', '......Q..', '.Q.......', '...Q.....', '.....Q...', 'Q........'], ['.......Q.', '.....Q...', 'Q........', '..Q......', '....Q....', '......Q..', '........Q', '...Q.....', '.Q.......'], ['.......Q.', '.....Q...', 'Q........', '..Q......', '......Q..', '........Q', '...Q.....', '.Q.......', '....Q....'], ['.......Q.', '.....Q...', '.Q.......', '......Q..', 'Q........', '...Q.....', '........Q', '....Q....', '..Q......'], ['.......Q.', '.....Q...', '..Q......', '........Q', '......Q..', 'Q........', '...Q.....', '.Q.......', '....Q....'], ['.......Q.', '.....Q...', '........Q', '..Q......', 'Q........', '...Q.....', '......Q..', '....Q....', '.Q.......'], ['........Q', '.Q.......', '....Q....', '......Q..', 'Q........', '..Q......', '.......Q.', '.....Q...', '...Q.....'], ['........Q', '.Q.......', '....Q....', '......Q..', '...Q.....', 'Q........', '.......Q.', '.....Q...', '..Q......'], ['........Q', '.Q.......', '.....Q...', '.......Q.', '..Q......', 'Q........', '...Q.....', '......Q..', '....Q....'], ['........Q', '..Q......', '....Q....', '.Q.......', '.......Q.', 'Q........', '......Q..', '...Q.....', '.....Q...'], ['........Q', '..Q......', '.....Q...', '.Q.......', '......Q..', 'Q........', '...Q.....', '.......Q.', '....Q....'], ['........Q', '..Q......', '.....Q...', '.Q.......', '......Q..', '....Q....', 'Q........', '.......Q.', '...Q.....'], ['........Q', '..Q......', '.....Q...', '...Q.....', 'Q........', '.......Q.', '....Q....', '......Q..', '.Q.......'], ['........Q', '...Q.....', 'Q........', '....Q....', '.......Q.', '.Q.......', '......Q..', '..Q......', '.....Q...'], ['........Q', '...Q.....', '.Q.......', '....Q....', '.......Q.', '.....Q...', 'Q........', '..Q......', '......Q..'], ['........Q', '...Q.....', '.Q.......', '......Q..', '..Q......', '.....Q...', '.......Q.', 'Q........', '....Q....'], ['........Q', '...Q.....', '.....Q...', '.......Q.', '.Q.......', '......Q..', 'Q........', '..Q......', '....Q....'], ['........Q', '...Q.....', '.....Q...', '.......Q.', '..Q......', 'Q........', '......Q..', '....Q....', '.Q.......'], ['........Q', '...Q.....', '.......Q.', 'Q........', '..Q......', '.....Q...', '.Q.......', '......Q..', '....Q....'], ['........Q', '....Q....', 'Q........', '...Q.....', '.....Q...', '.......Q.', '.Q.......', '......Q..', '..Q......'], ['........Q', '....Q....', 'Q........', '.......Q.', '...Q.....', '.Q.......', '......Q..', '..Q......', '.....Q...'], ['........Q', '....Q....', '..Q......', 'Q........', '.....Q...', '.......Q.', '.Q.......', '...Q.....', '......Q..'], ['........Q', '....Q....', '..Q......', 'Q........', '......Q..', '.Q.......', '.......Q.', '.....Q...', '...Q.....'], ['........Q', '....Q....', '..Q......', '.......Q.', '...Q.....', '......Q..', 'Q........', '.....Q...', '.Q.......'], ['........Q', '....Q....', '.......Q.', '...Q.....', 'Q........', '......Q..', '.Q.......', '.....Q...', '..Q......'], ['........Q', '.....Q...', '.Q.......', '......Q..', 'Q........', '..Q......', '....Q....', '.......Q.', '...Q.....'], ['........Q', '.....Q...', '..Q......', 'Q........', '.......Q.', '....Q....', '.Q.......', '...Q.....', '......Q..'], ['........Q', '.....Q...', '..Q......', '......Q..', '.Q.......', '.......Q.', '....Q....', 'Q........', '...Q.....'], ['........Q', '.....Q...', '...Q.....', '.Q.......', '.......Q.', '....Q....', '......Q..', 'Q........', '..Q......'], ['........Q', '.....Q...', '...Q.....', '......Q..', 'Q........', '.......Q.', '.Q.......', '....Q....', '..Q......'], ['........Q', '.....Q...', '.......Q.', '.Q.......', '...Q.....', 'Q........', '......Q..', '....Q....', '..Q......'], ['........Q', '......Q..', '.Q.......', '...Q.....', 'Q........', '.......Q.', '....Q....', '..Q......', '.....Q...'], ['........Q', '......Q..', '..Q......', '.......Q.', '.Q.......', '....Q....', 'Q........', '.....Q...', '...Q.....'], ['........Q', '......Q..', '...Q.....', '.Q.......', '.......Q.', '.....Q...', 'Q........', '..Q......', '....Q....']]", "def solvenqueens(n):\n\n def dfs(queens, xy_dif, xy_sum):\n p = len(queens)\n if p == n:\n res.append(queens)\n return\n for i in range(n):\n if i not in queens and p - i not in xy_dif and (p + i not in xy_sum):\n dfs(queens + [i], xy_dif + [p - i], xy_sum + [p + i])\n res = []\n dfs([], [], [])\n return [['.' * i + 'Q' + '.' * (n - i - 1) for i in sol] for sol in res]", "def solvenqueens(n):\n\n def dfs(cols, diag_45, diag_135, depth=0):\n row = len(cols)\n if row == n:\n result.append(cols)\n return\n for col in range(n):\n if col not in cols and row - col not in diag_45 and (row + col not in diag_135):\n dfs(cols + [col], diag_45 + [row - col], diag_135 + [row + col], depth + 1)\n else:\n pass\n result = []\n dfs([], [], [])\n return [['.' * i + 'Q' + '.' * (n - i - 1) for i in sol] for sol in result]", "def solvenqueens(n):\n result = []\n visits = [0, 0, 0]\n board = [['.' for j in range(n)] for i in range(n)]\n self.find(visits, n, 0, board, result)\n return result + [[row[::-1] for row in board] for board in result if n & 1 == 0 or (n & 1 == 1 and board[0][n >> 1] != 'Q')]\n\ndef find(visits, n, k, board, result):\n if k >= n:\n result.append([''.join((x for x in row)) for row in board])\n return\n for j in range(n if k > 0 else n + 1 >> 1):\n if self.isInvalid(visits, k, j, n):\n continue\n self.toggleVisit(visits, k, j, n)\n board[k][j] = 'Q'\n self.find(visits, n, k + 1, board, result)\n self.toggleVisit(visits, k, j, n)\n board[k][j] = '.'\n\ndef toggleVisit(visits, i, j, n):\n visits[0] ^= 1 << j\n visits[1] ^= 1 << i - j + n - 1\n visits[2] ^= 1 << i + j\n\ndef isInvalid(visits, i, j, n):\n return visits[0] & 1 << j > 0 or visits[1] & 1 << i - j + n - 1 > 0 or visits[2] & 1 << i + j > 0", "def solvenqueens(n):\n\n def dfs(n, a, b, c, ans, d):\n if n == 0:\n ans = ans.append([i * '.' + 'Q' + (len(a) - i - 1) * '.' for i in d])\n return None\n for i in range(len(a)):\n if a[i] or b[n - 1 + i] or c[len(a) - 1 - i + n - 1]:\n continue\n (a[i], b[n - 1 + i], c[len(a) - 1 - i + n - 1]) = (True, True, True)\n d[n - 1] = i\n dfs(n - 1, a, b, c, ans, d)\n (a[i], b[n - 1 + i], c[len(a) - 1 - i + n - 1]) = (False, False, False)\n return None\n a = [False for i in range(n)]\n b = [False for i in range(n * 2 - 1)]\n c = [False for i in range(n * 2 - 1)]\n d = [0 for i in range(n)]\n ans = []\n dfs(n, a, b, c, ans, d)\n return ans", "def solvenqueens(n):\n row = [x for x in range(n)]\n table = []\n for i in range(n):\n table.append(row.copy())\n result = self.solve(table, 0)\n result_str = []\n for x in result:\n table_str = []\n for y in x:\n table_str.append('.' * y + 'Q' + '.' * (n - y - 1))\n result_str.append(table_str)\n return result_str\n\ndef solve(table, n):\n if table[n] == []:\n return []\n elif n == len(table) - 1:\n table[n] = table[n][0]\n return [table]\n else:\n result = []\n for x in table[n]:\n table1 = [x if type(x) == int else x.copy() for x in table]\n table1[n] = x\n for row in range(n + 1, len(table)):\n if x in table1[row]:\n table1[row].remove(x)\n if x + row - n in table1[row]:\n table1[row].remove(x + row - n)\n if x - (row - n) in table1[row]:\n table1[row].remove(x - (row - n))\n result.extend(self.solve(table1, n + 1))\n return result", "def __init__():\n self.result = []\n self.visited = None\n\ndef solvenqueens(n):\n self.visited = [0 for i in range(n)]\n self.__solve_n_queues(n, 0, [])\n return self.result\n\ndef __not_diagonal(x, y, curr_answer):\n for (c_x, c_y) in enumerate(curr_answer):\n if abs(c_x - x) == abs(c_y - y):\n return False\n return True\n\ndef visualize(curr_answer, n):\n answer = []\n for pos in curr_answer:\n answer.append('.' * pos + 'Q' + '.' * (n - pos - 1))\n return answer\n\ndef __solve_n_queues(n, level, curr_answer):\n if level == n:\n self.result.append(Solution.visualize(curr_answer, n))\n return\n for i in range(n):\n if not self.visited[i] and Solution.__not_diagonal(level, i, curr_answer):\n self.visited[i] = 1\n curr_answer.append(i)\n self.__solve_n_queues(n, level + 1, curr_answer)\n curr_answer.pop()\n self.visited[i] = 0", "def solvenqueens(n):\n queens = []\n res = []\n\n def backtracking(n, k, queens):\n if k > n:\n return\n elif len(queens) == n and k < n:\n return\n elif len(queens) == n and k == n:\n temp = queens[:]\n res.append(temp)\n else:\n row = [0] * n\n temp_q = queens[:]\n for each in temp_q:\n (x, y) = (each[0], each[1])\n row[y] = 1\n if y + k - x < n:\n row[y + k - x] = 1\n if y - k + x >= 0:\n row[y - k + x] = 1\n for i in range(n):\n if row[i] == 0:\n temp_q.append((k, i))\n backtracking(n, k + 1, temp_q)\n temp_q.pop()\n backtracking(n, 0, queens)\n layout = []\n for q in res:\n temp = []\n for each in q:\n _row = '.' * each[1] + 'Q' + '.' * (n - each[1] - 1)\n temp.append(_row)\n layout.append(temp)\n return layout"], "starter_code": "def solvenqueens(n: int) -> List[List[str]]:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Backtracking"], "name": null, "source": "leetcode", "tags": ["Data structures", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://leetcode.com/problems/n-queens/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solvenqueens", "task_id": "TACO_lite/214", "example": [[[4]], ["[['.Q..', '...Q', 'Q...', '..Q.'], ['..Q.', 'Q...', '...Q', '.Q..']]"]]} +{"requirement": "Given a binary array nums, you should delete one element from it.\nReturn the size of the longest non-empty subarray containing only 1's in the resulting array.\nReturn 0 if there is no such subarray.\n \nExample 1:\nInput: nums = [1,1,0,1]\nOutput: 3\nExplanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.\nExample 2:\nInput: nums = [0,1,1,1,0,1,1,0,1]\nOutput: 5\nExplanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].\nExample 3:\nInput: nums = [1,1,1]\nOutput: 2\nExplanation: You must delete one element.\nExample 4:\nInput: nums = [1,1,0,0,1,1,1,0,1]\nOutput: 4\n\nExample 5:\nInput: nums = [0,0,0]\nOutput: 0\n\n \nConstraints:\n\n1 <= nums.length <= 10^5\nnums[i] is either 0 or 1.", "solutions": ["def longestsubarray(nums: List[int]) -> int:\n if not 0 in nums:\n return len(nums) - 1\n ans = 0\n tot = 0\n prev = 0\n for n in nums:\n if n == 1:\n tot += 1\n else:\n ans = max(tot + prev, ans)\n prev = tot\n tot = 0\n return max(prev + tot, ans)", "def longestsubarray(nums: List[int]) -> int:\n z = [0]\n l = []\n a = 0\n c = 0\n for i in range(len(nums)):\n if a == 1 and nums[i] == 0:\n z.append(c)\n c = i - (l[-1] + 1)\n a = 1\n l.append(i)\n elif nums[i] == 0:\n a = a + 1\n l.append(i)\n elif nums[i] == 1:\n c = c + 1\n z.append(c)\n if nums.count(1) == len(nums):\n return len(nums) - 1\n return max(z)", "def longestsubarray(nums: List[int]) -> int:\n (zc, oc) = (0, 0)\n for (i, v) in enumerate(nums):\n if v:\n oc += 1\n else:\n zc += 1\n if oc == len(nums):\n return oc - 1\n elif zc == len(nums):\n return 0\n elif zc == 1:\n return oc\n elif oc == 1:\n return 1\n else:\n l = r = 0\n for (i, v) in enumerate(nums):\n if v == 1:\n l += 1\n else:\n break\n st = i + 1\n po = i\n (maxo, maxi) = (-1, -1)\n while st < len(nums):\n if nums[st] == 1:\n r += 1\n st += 1\n continue\n else:\n v = l + r\n if maxo < v:\n maxo = v\n maxi = po\n po = st\n l = r\n r = 0\n st += 1\n maxo = max(maxo, l + r)\n return maxo", "from collections import deque\n\ndef longestsubarray(nums: List[int]) -> int:\n n = len(nums)\n if n == 0:\n return 0\n elif n == 1:\n return 0 if nums[0] == 0 else 1\n q = deque()\n num_z = 0\n maxx = 0\n is_0 = 0\n for i in range(n):\n if nums[i] == 1:\n q.append(i)\n continue\n is_0 = 1\n if num_z < 1:\n q.append(i)\n num_z += 1\n maxx = max(maxx, len(q) - 1)\n continue\n maxx = max(maxx, len(q) - 1)\n while q and num_z == 1:\n top = q.popleft()\n if nums[top] == 0:\n num_z -= 1\n q.append(i)\n num_z += 1\n if is_0 == 0:\n return n - 1\n maxx = max(len(q) - num_z, maxx)\n return maxx", "def longestsubarray(nums: List[int]) -> int:\n c = 0\n ind = 0\n for i in range(len(nums)):\n if nums[i] == 0:\n j = i + 1\n k = 0\n while j < len(nums) and nums[j] == 1:\n k += 1\n j += 1\n j = i - 1\n while j >= 0 and nums[j] == 1:\n k += 1\n j -= 1\n if k > c:\n c = k\n ind = i\n if ind == 0 and nums[ind] == 1:\n ind = len(nums) - 1\n c = len(nums) - 1\n return c", "def longestsubarray(nums: List[int]) -> int:\n res = zeros = 0\n zero_i = None\n i = 0\n for (j, v) in enumerate(nums):\n if v == 0:\n zeros += 1\n if zeros == 2:\n i = zero_i + 1\n zeros = 1\n zero_i = j\n res = max(res, j - i)\n return res", "def longestsubarray(nums: List[int]) -> int:\n max_length = 0\n count = 0\n for num in nums:\n if num == 1:\n count += 1\n max_length = max(max_length, count)\n else:\n count = 0\n if max_length == len(nums):\n return len(nums) - 1\n elif max_length == 0:\n return 0\n num_left = 0\n num_right = 0\n for (i, num) in enumerate(nums):\n if num == 1:\n num_right += 1\n else:\n max_length = max(max_length, num_left + num_right)\n if i + 1 < len(nums) and nums[i + 1] == 1:\n num_left = num_right\n num_right = 0\n else:\n num_left = 0\n num_right = 0\n max_length = max(max_length, num_left + num_right)\n return max_length", "def longestsubarray(nums: List[int]) -> int:\n (start, end, maxlen, k) = (0, 0, 0, 1)\n while end < len(nums):\n if nums[end] == 0:\n k = k - 1\n if k < 0:\n if nums[start] == 0:\n k += 1\n start = start + 1\n end = end + 1\n continue\n if k >= 0 or nums[end] == 1:\n maxlen = max(maxlen, end - start)\n end = end + 1\n return maxlen", "def longestsubarray(nums: List[int]) -> int:\n longest = 0\n left = 0\n x = 1\n for right in range(len(nums)):\n if not nums[right]:\n x -= 1\n while x < 0:\n if not nums[left]:\n x += 1\n left += 1\n longest = max(longest, right - left + 1)\n return longest - 1", "def longestsubarray(nums: List[int]) -> int:\n noofones = 0\n m = 0\n lastoneslen = 0\n for i in nums:\n if i == 1:\n noofones += 1\n else:\n m = max(m, noofones + lastoneslen)\n lastoneslen = noofones\n noofones = 0\n m = max(m, noofones + lastoneslen)\n if m == len(nums):\n m -= 1\n return m", "def longestsubarray(nums: List[int]) -> int:\n max_count = 0\n start = 0\n zero = 2\n for i in range(len(nums)):\n if nums[i] == 0:\n zero -= 1\n while zero < 1:\n if nums[start] == 0:\n zero += 1\n start += 1\n max_count = max(max_count, i - start)\n return max_count", "def longestsubarray(nums: List[int]) -> int:\n res = []\n count = 0\n for (i, val) in enumerate(nums):\n if val == 0:\n if count > 0:\n res.append(count)\n count = 0\n res.append(0)\n elif val == 1:\n count += 1\n if count > 0:\n res.append(count)\n lenRes = len(res)\n ma = 0\n if lenRes > 2:\n for i in range(1, lenRes - 1):\n ma = max(max(ma, res[i - 1] + res[i + 1]), max(res[i - 1], res[i]), max(res[i + 1], res[i]))\n return ma\n elif lenRes == 1 and res[0] > 0:\n return res[0] - 1\n elif lenRes == 1 and res[0] == 0:\n return ma\n elif lenRes == 2:\n return max(res[0], res[1])", "def longestsubarray(nums: List[int]) -> int:\n zero = -1\n k = 1\n maxi = 0\n count = 0\n i = 0\n while i != len(nums):\n if nums[i] == 0:\n if k == 0:\n i = zero + 1\n zero = i\n maxi = max(count, maxi)\n count = 0\n k = 1\n else:\n k -= 1\n zero = i\n i += 1\n else:\n count += 1\n i += 1\n maxi = max(count, maxi)\n if maxi == len(nums):\n return maxi - 1\n else:\n return maxi", "def longestsubarray(nums: List[int]) -> int:\n start = end = zeros = ones = maxx = 0\n while end < len(nums):\n if nums[end] == 1:\n ones += 1\n elif nums[end] == 0:\n zeros += 1\n while zeros > 1:\n if nums[start] == 0:\n zeros -= 1\n start += 1\n maxx = max(maxx, end - start)\n end += 1\n return maxx", "def longestsubarray(array: List[int]) -> int:\n i = 0\n lenght = 0\n stack = deque()\n zero = False\n while i < len(array):\n if array[i] == 1:\n stack.append(array[i])\n i += 1\n elif zero == False:\n stack.append(array[i])\n zero = True\n i += 1\n else:\n temp = len(stack) - 1\n if temp > lenght:\n lenght = temp\n while stack[0] != 0:\n stack.popleft()\n stack.popleft()\n zero = False\n if len(stack) > lenght:\n lenght = len(stack) - 1\n return lenght", "def longestsubarray(nums: List[int]) -> int:\n left = 0\n right = 0\n zeroes = 1\n res = 0\n while right < len(nums):\n if nums[right] == 0:\n zeroes -= 1\n while zeroes < 0:\n if nums[left] == 0:\n zeroes += 1\n left += 1\n res = max(res, right - left)\n right += 1\n return res", "def longestsubarray(nums: List[int]) -> int:\n (i, j) = (0, 0)\n (ans, cur) = (0, 0)\n while j < len(nums):\n cur += nums[j]\n while i < j and cur < j - i:\n cur -= nums[i]\n i += 1\n ans = max(ans, cur)\n j += 1\n return min(ans, len(nums) - 1)", "def longestsubarray(nums: List[int]) -> int:\n n = len(nums)\n if n == 0:\n return 0\n joined = [0 for i in range(n)]\n left = 0\n right = 0\n for i in range(n):\n joined[i] += left\n joined[n - 1 - i] += right\n if nums[i] == 1:\n left += 1\n else:\n left = 0\n if nums[n - 1 - i] == 1:\n right += 1\n else:\n right = 0\n return max(joined)", "def longestsubarray(nums):\n n = len(nums)\n last_zero = None\n last_one = None\n cnt = 0\n res = 0\n for i in range(n):\n if nums[i] == 1:\n if last_one is None:\n last_one = i\n cnt += 1\n elif last_zero is None:\n last_zero = i\n else:\n last_one = last_zero + 1\n last_zero = i\n cnt = i - last_one\n res = max(res, cnt)\n if res == n:\n return n - 1\n return res", "def longestsubarray(nums: List[int]) -> int:\n mc = 0\n onep = False\n for i in range(len(nums)):\n if nums[i] == 0:\n c = 0\n j = i - 1\n while j >= 0 and nums[j] != 0:\n j -= 1\n c += 1\n j = i + 1\n while j < len(nums) and nums[j] != 0:\n j += 1\n c += 1\n if c > mc:\n mc = c\n else:\n onep = True\n if onep and mc == 0:\n return len(nums) - 1\n elif not onep and mc == 0:\n return 0\n else:\n return mc", "def longestsubarray(nums: List[int]) -> int:\n groups = [[k, len(list(g))] for (k, g) in itertools.groupby(nums)]\n if len(groups) == 1:\n return groups[0][1] - 1 if groups[0][0] else 0\n ans = 0\n for i in range(len(groups)):\n (k, klen) = groups[i]\n if k:\n ans = max(ans, klen)\n elif i not in [0, len(groups) - 1] and klen == 1:\n ans = max(ans, groups[i - 1][1] + groups[i + 1][1])\n return ans", "def longestsubarray(nums: List[int]) -> int:\n (low, high) = (0, 0)\n cn = 0\n ans = 0\n while low < len(nums) and high < len(nums):\n if nums[high] == 0:\n if cn < 1:\n cn += 1\n else:\n while nums[low] != 0:\n low += 1\n low += 1\n high += 1\n ans = max(ans, high - low)\n return max(ans, high - low) - 1", "def longestsubarray(nums: List[int]) -> int:\n if not nums:\n return 0\n if all(nums):\n return len(nums) - 1\n n = len(nums)\n dp = [[0] * 2 for _ in range(n)]\n dp[0][0] = 1 if nums[0] == 1 else 0\n dp[0][1] = 0\n res = 0\n for i in range(1, n):\n if nums[i] == 1:\n dp[i][0] = dp[i - 1][0] + 1\n dp[i][1] = dp[i - 1][1] + 1\n else:\n dp[i][0] = 0\n dp[i][1] = dp[i - 1][0]\n res = max(res, dp[i][1], dp[i][0])\n return res", "def longestsubarray(A):\n if not A:\n return 0\n n = len(A)\n right = 0\n cnt = 0\n res = 0\n for left in range(n):\n while right <= n - 1 and (cnt == 0 or A[right] == 1):\n cnt += A[right] == 0\n right += 1\n res = max(res, right - left)\n cnt -= A[left] == 0\n return res - 1", "def longestsubarray(nums: List[int]) -> int:\n left = []\n total = 0\n for n in nums:\n if n == 0:\n total = 0\n else:\n total += n\n left.append(total)\n right = []\n total = 0\n for i in range(len(nums) - 1, -1, -1):\n if nums[i] == 0:\n total = 0\n else:\n total += nums[i]\n right.append(total)\n right = right[::-1]\n curMax = 0\n for i in range(len(nums) - 2):\n curMax = max(left[i] + right[i + 2], curMax)\n return curMax", "def longestsubarray(nums: List[int]) -> int:\n n = len(nums)\n (l, r) = ([0] * n, [0] * n)\n for i in range(1, n):\n l[i] = l[i - 1] + 1 if nums[i - 1] == 1 else 0\n for i in range(n - 2, -1, -1):\n r[i] = r[i + 1] + 1 if nums[i + 1] == 1 else 0\n ans = max(r[0], l[n - 1])\n for i in range(1, n - 1):\n ans = max(ans, l[i] + r[i])\n return ans", "def longestsubarray(nums: List[int]) -> int:\n k = 1\n i = 0\n for j in range(len(nums)):\n if nums[j] == 0:\n k -= 1\n if k < 0:\n if nums[i] == 0:\n k += 1\n i += 1\n return j - i", "def longestsubarray(nums: List[int]) -> int:\n prevStart = -1\n candidates = []\n if 0 not in nums:\n return len(nums) - 1\n for i in range(len(nums)):\n if nums[i] == 1:\n if prevStart == -1:\n prevStart = i\n continue\n elif prevStart != -1:\n candidates.append([prevStart, i - 1])\n prevStart = -1\n if prevStart != -1:\n candidates.append([prevStart, len(nums) - 1])\n res = [0]\n for i in range(len(candidates)):\n if i == len(candidates) - 1:\n res.append(candidates[i][1] - candidates[i][0] + 1)\n elif candidates[i + 1][0] - candidates[i][1] == 2:\n res.append(candidates[i + 1][1] - candidates[i][0])\n else:\n res.append(candidates[i][1] - candidates[i][0] + 1)\n return max(res)", "def longestsubarray(nums: List[int]) -> int:\n i = 0\n j = 0\n sum = 0\n ans = 0\n for (j, val) in enumerate(nums):\n sum += val\n while i < j and sum < j - i:\n sum -= nums[i]\n i += 1\n ans = max(ans, j - i)\n return ans", "def longestsubarray(nums: List[int]) -> int:\n n = len(nums)\n leftones = [0] * n\n for i in range(n):\n if nums[i] == 0:\n leftones[i] = 0\n else:\n leftones[i] = 1 if i == 0 else leftones[i - 1] + 1\n rightones = [0] * n\n for i in range(n - 1, -1, -1):\n if nums[i] == 0:\n rightones[i] = 0\n else:\n rightones[i] = 1 if i == n - 1 else rightones[i + 1] + 1\n res = 0\n for i in range(1, n - 1):\n res = max(res, leftones[i - 1] + rightones[i + 1])\n return res", "def longestsubarray(nums: List[int]) -> int:\n (prev, curr, best) = (0, 0, 0)\n n = len(nums)\n for (i, x) in enumerate(nums):\n if x == 0:\n best = max(best, prev + curr)\n if i == n - 1:\n pass\n elif nums[i + 1] == 1:\n prev = curr\n curr = 0\n else:\n prev = 0\n curr = 0\n else:\n curr += 1\n best = max(best, prev + curr)\n if best == n:\n best -= 1\n return best", "def longestsubarray(xs: List[int]) -> int:\n n = len(xs)\n if n < 2:\n return 0\n dp = collections.deque()\n best = 0\n for (i, x) in enumerate(xs):\n if x:\n dp.append(i)\n while dp and i - dp[0] - len(dp) + 1 > 1:\n dp.popleft()\n nholes = i - dp[0] - len(dp) + 1 if dp else 1\n this_len = len(dp) - (not dp[0] and (not nholes)) if dp else 0\n best = max(best, this_len)\n return best", "def longestsubarray(nums: List[int]) -> int:\n (prev, _next, n) = ([0 for _ in range(len(nums))], [0 for _ in range(len(nums))], len(nums))\n count = 0\n for i in range(n):\n num = nums[i]\n if i == 0:\n if num:\n count = 1\n elif num:\n prev[i] = count\n count += 1\n else:\n prev[i] = count\n count = 0\n count = 0\n for i in range(n - 1, -1, -1):\n num = nums[i]\n if i == n - 1:\n if num:\n count = 1\n elif num:\n _next[i] = count\n count += 1\n else:\n _next[i] = count\n count = 0\n _max = 0\n for i in range(n):\n num = nums[i]\n _max = max(_max, prev[i] + _next[i])\n return _max", "def longestsubarray(nums: List[int]) -> int:\n if all(nums):\n return len(nums) - 1\n m = pre = l = pl = 0\n for (i, n) in enumerate(nums):\n if n == pre == 1:\n l += 1\n elif n == pre == 0:\n pl = 0\n elif n == 1 != pre:\n l = 1\n else:\n m = max(m, pl + l)\n pl = l\n pre = n\n return max(m, pl + l) if pre == 1 else m", "def get_longest(nums):\n arr = [1 - x for x in nums]\n (l, r) = (0, 0)\n count = 0\n max_length = 0\n while l < len(arr):\n if r == len(arr):\n step = 'l'\n elif l == r:\n step = 'r'\n elif count + arr[r] > 1:\n step = 'l'\n else:\n step = 'r'\n if step == 'l':\n count -= arr[l]\n l += 1\n else:\n count += arr[r]\n r += 1\n max_length = max(max_length, r - l)\n return max(0, max_length - 1)\n\ndef longestsubarray(nums: List[int]) -> int:\n return get_longest(nums)", "def longestsubarray(nums: List[int]) -> int:\n new_array = list()\n current_segment = 0\n for num in nums:\n if num == 0:\n if current_segment > 0:\n new_array.append(current_segment)\n current_segment = 0\n new_array.append(0)\n else:\n current_segment += 1\n if current_segment > 0:\n new_array.append(current_segment)\n max_length = 0\n for idx in range(len(new_array)):\n max_length = max(max_length, new_array[idx])\n if idx > 0 and idx < len(new_array) - 1 and (new_array[idx] == 0):\n if new_array[idx - 1] > 0 and new_array[idx + 1] > 0:\n max_length = max(max_length, new_array[idx - 1] + new_array[idx + 1])\n if max_length == len(nums):\n return max_length - 1\n else:\n return max_length", "def longestsubarray(nums: List[int]) -> int:\n right = [0 for _ in range(len(nums))]\n left = [0 for _ in range(len(nums))]\n for i in range(1, len(nums)):\n if nums[i - 1] == 1:\n left[i] = 1 + left[i - 1]\n res = float('-inf')\n for i in range(len(nums) - 2, -1, -1):\n if nums[i + 1] == 1:\n right[i] = 1 + right[i + 1]\n res = max(res, left[i] + right[i])\n return res", "def longestsubarray(nums: List[int]) -> int:\n se = set(nums)\n if 0 not in se:\n return len(nums) - 1\n elif 1 not in se:\n return 0\n count = 0\n flag = 0\n ls = []\n for i in nums:\n if i == 0:\n if flag == 0:\n count += 1\n else:\n flag = 0\n ls.append(count)\n count = 1\n elif flag == 1:\n count += 1\n else:\n flag = 1\n ls.append(count)\n count = 1\n ls.append(count)\n ind = 0\n ans = 0\n while ind < len(ls):\n if ls[ind] != 0:\n if ls[ind] == 1:\n if ind == 0 and ind < len(ls) - 1:\n ans = max(ans, ls[ind + 1])\n elif ind == len(ls) - 1 and ind > 0:\n ans = max(ans, ls[ind - 1])\n elif ind < len(ls) - 1 and ind > 0:\n ans = max(ans, ls[ind - 1] + ls[ind + 1])\n elif ind == 0 and ind < len(ls) - 1:\n ans = max(ans, ls[ind + 1])\n elif ind == len(ls) - 1 and ind > 0:\n ans = max(ans, ls[ind - 1])\n elif ind < len(ls) - 1 and ind > 0:\n ans = max(ans, max(ls[ind - 1], ls[ind + 1]))\n ind += 2\n return ans", "def longestsubarray(nums: List[int]) -> int:\n var = 0\n count = 0\n max1 = 0\n pos = 0\n flag = 0\n for i in nums:\n if i == 1:\n flag = 1\n if var == 1:\n pos = pos + 1\n count = count + 1\n max1 = max(count, max1)\n elif i == 0 and var == 1:\n count = pos\n pos = 0\n elif flag == 1:\n if var == 0:\n var = var + 1\n else:\n count = pos\n if max1 == len(nums):\n return max1 - 1\n return max1", "def longestsubarray(nums: List[int]) -> int:\n deleted = False\n (max_, cur_cnt, last_cnt) = (0, 0, 0)\n (idx, size) = (0, len(nums))\n while idx < size and nums[idx] == 0:\n idx += 1\n for i in range(idx, size):\n if nums[i] == 1:\n cur_cnt += 1\n max_ = max(max_, cur_cnt)\n else:\n if not deleted:\n deleted = True\n else:\n cur_cnt -= last_cnt\n last_cnt = cur_cnt\n if size == sum(nums):\n return size - 1\n return max_", "def longestsubarray(nums: List[int]) -> int:\n if 1 not in nums:\n return 0\n if 0 not in nums:\n return len(nums) - 1\n new = []\n i = 0\n n = len(nums)\n while i < n:\n if nums[i] == 1:\n cnt = 0\n while i < n and nums[i] == 1:\n cnt += 1\n i += 1\n new.append(cnt)\n else:\n new.append(0)\n i += 1\n mx = max(new)\n for i in range(1, len(new) - 1):\n if new[i] == 0:\n mx = max(mx, new[i - 1] + new[i + 1])\n return mx", "def longestsubarray(nums: List[int]) -> int:\n if len(nums) < 1:\n return 0\n res = 0\n logs = []\n for x in nums:\n if x == 0:\n logs.append(res)\n res = 0\n else:\n res += 1\n logs.append(res)\n if len(logs) == 1:\n return max(0, logs[0] - 1)\n return max([logs[i] + logs[i + 1] for i in range(len(logs) - 1)])", "def longestsubarray(nums: List[int]) -> int:\n if sum(nums) >= len(nums) - 1:\n return len(nums) - 1\n l = 0\n while nums[l] == 0:\n l += 1\n if l == len(nums):\n return 0\n r = l + 1\n sum_total = nums[l]\n res = 0\n for r in range(r, len(nums)):\n sum_total += nums[r]\n if sum_total == r - l - 1:\n res = max(res, sum_total)\n while sum_total < r - l:\n sum_total -= nums[l]\n l += 1\n return max(res, sum_total)", "def longestsubarray(nums: List[int]) -> int:\n if len(nums) < 2:\n return 0\n len1_prev = 0\n len1 = 0\n i = 0\n res = 0\n zc = 0\n while i < len(nums):\n if nums[i] == 1:\n len1 += 1\n else:\n res = max(res, len1 + len1_prev)\n if zc == 0:\n len1_prev = len1\n len1 = 0\n zc = 1\n elif zc == 1:\n if len1 > 0:\n len1_prev = len1\n len1 = 0\n zc = 1\n else:\n len1 = 0\n len1_prev = 0\n zc = 0\n i += 1\n res = max(res, len1 + len1_prev)\n res = min(len(nums) - 1, res)\n return res", "def longestsubarray(nums: List[int]) -> int:\n n = len(nums)\n if sum(nums) == n:\n return n - 1\n dp = [[0 for x in range(len(nums))] for y in range(2)]\n dp[0][0] = 1 if nums[0] == 1 else 0\n for i in range(1, len(nums)):\n if nums[i] == 0:\n dp[0][i] = 0\n dp[1][i] = dp[0][i - 1]\n else:\n dp[0][i] = dp[0][i - 1] + 1\n dp[1][i] = dp[1][i - 1] + 1\n return max([i for x in dp for i in x])", "def longestsubarray(nums: List[int]) -> int:\n max_len = 0\n zero_seen = False\n for i in range(len(nums)):\n length = 0\n if nums[i] == 0:\n zero_seen = True\n (l, r) = (i - 1, i + 1)\n while l >= 0 and nums[l] == 1:\n length += 1\n l -= 1\n while r < len(nums) and nums[r] == 1:\n length += 1\n r += 1\n max_len = max(max_len, length)\n return max_len if zero_seen else len(nums) - 1", "def longestsubarray(a: List[int]) -> int:\n ones = 0\n old_ones = 0\n maxlen = 0\n n = len(a)\n for i in range(n):\n if a[i] == 1:\n ones += 1\n maxlen = max(maxlen, ones + old_ones)\n else:\n old_ones = ones\n ones = 0\n return maxlen if ones < n else n - 1", "def longestsubarray(nums: List[int]) -> int:\n seq = [0]\n prev = 0\n res = 0\n for n in nums:\n if n:\n seq[-1] += 1\n res = max(prev + seq[-1], res)\n else:\n prev = seq[-1]\n seq.append(0)\n if len(seq) == 1:\n res -= 1\n return res", "def longestsubarray(nums: List[int]) -> int:\n (prev, res, curr) = (0, 0, 0)\n for i in range(len(nums)):\n if nums[i] == 1:\n curr += 1\n else:\n if i < len(nums) - 1 and nums[i + 1] != 0:\n prev = curr\n else:\n prev = 0\n curr = 0\n res = max(res, curr + prev)\n if res == len(nums):\n res -= 1\n return res", "import re\nimport numpy as np\n\ndef longestsubarray(nums: List[int]) -> int:\n nums = np.array(nums)\n zeros_ = np.where(nums == 0)[0]\n if zeros_.tolist():\n temp = 0\n for ind in zeros_:\n ind_ = max([ind - 1, 0])\n ind__ = min([ind + 1, len(nums) - 1])\n count_ = 0\n count__ = 0\n if nums[ind_] == 1:\n while ind_ >= 0 and nums[ind_] == 1:\n count_ += 1\n ind_ -= 1\n if nums[ind__] == 1:\n while ind__ < len(nums) and nums[ind__] == 1:\n count__ += 1\n ind__ += 1\n temp = max([count_ + count__, temp])\n return temp\n elif len(zeros_) == len(nums):\n return 0\n else:\n return len(nums) - 1", "def longestsubarray(nums: List[int]) -> int:\n i = 0\n ints = []\n while i < len(nums):\n start = i\n end = i\n while i < len(nums) and nums[i] == 1:\n i += 1\n end += 1\n if start != end:\n ints.append((start, end))\n i += 1\n if len(ints) == 1:\n diff = ints[0][1] - ints[0][0]\n if diff == len(nums):\n return diff - 1\n else:\n return diff\n elif not ints:\n return 0\n max_ones = 0\n for seq in range(len(ints) - 1):\n seq1 = ints[seq]\n seq2 = ints[seq + 1]\n length = None\n if seq2[0] - seq1[1] == 1:\n length = seq1[1] - seq1[0] + (seq2[1] - seq2[0])\n else:\n length = max(seq1[1] - seq1[0], seq2[1] - seq2[0])\n if length > max_ones:\n max_ones = length\n return max_ones", "def longestsubarray(nums: List[int]) -> int:\n n = len(nums)\n prev = 0\n cnt = 0\n pmax = 0\n for i in range(0, n):\n if nums[i] == 1:\n cnt += 1\n else:\n prev = cnt\n cnt = 0\n maxm = prev + cnt\n if maxm > pmax:\n pmax = maxm\n if cnt == n:\n return n - 1\n else:\n return maxm if maxm > pmax else pmax", "def longestsubarray(nums: List[int]) -> int:\n start = 0\n sliding_window_counter = collections.Counter()\n result = 0\n for end in range(len(nums)):\n sliding_window_counter[nums[end]] += 1\n while sliding_window_counter[0] > 1:\n sliding_window_counter[nums[start]] -= 1\n start += 1\n result = max(result, end - start)\n return result", "def longestsubarray(nums: List[int]) -> int:\n l = 0\n r = 0\n zeros = 0\n res = 0\n while r < len(nums):\n if nums[r] == 0:\n zeros += 1\n while zeros > 1:\n if nums[l] == 0:\n zeros -= 1\n l += 1\n res = max(res, r - l)\n r += 1\n return res", "def longestsubarray(nums: List[int]) -> int:\n l = 0\n r = 0\n earliest_one = float('inf')\n earliest_zero = float('inf')\n zeros = 1\n max_len = 0\n while r < len(nums):\n zeros -= nums[r] == 0\n if zeros < 0:\n zeros += nums[l] == 0\n l += 1\n r += 1\n return r - l - 1", "def longestsubarray(nums: List[int]) -> int:\n w_start = 0\n d = {}\n max_len = 0\n case = 0\n for i in range(0, len(nums)):\n c = str(nums[i])\n if c not in d:\n d[c] = 0\n d[c] += 1\n if str(0) in d:\n while d[str(0)] > 1:\n t = str(nums[w_start])\n d[t] -= 1\n w_start += 1\n case = 1\n max_len = max(max_len, i - w_start + 1 - case)\n case = 0\n return max_len - 1", "def longestsubarray(nums: List[int]) -> int:\n prev = 0\n prev_zero = 0\n result = float('-inf')\n boolean = False\n count = 0\n for i in range(len(nums)):\n if nums[i] == 0:\n boolean = True\n count += 1\n if count == 2:\n count -= 1\n prev = prev_zero + 1\n prev_zero = i\n result = max(result, i - prev)\n return result if boolean == True else len(nums) - 1", "def longestsubarray(nums: List[int]) -> int:\n if 0 in nums and 1 in nums:\n longest = 0\n i = nums.index(0)\n while True:\n if 0 in nums[:i][::-1]:\n left_side = nums[:i][::-1].index(0)\n else:\n left_side = len(nums[:i][::-1])\n if 0 in nums[i + 1:]:\n right_side = nums[i + 1:].index(0)\n else:\n right_side = len(nums[i + 1:])\n longest = max(left_side + right_side, longest)\n try:\n i = nums[i + 1:].index(0) + i + 1\n except:\n break\n return longest\n elif sum(nums) == 0:\n return 0\n elif sum(nums) == len(nums):\n return len(nums) - 1", "def longestsubarray(nums: List[int]) -> int:\n arr = []\n count = 0\n for i in range(len(nums)):\n if nums[i] == 1:\n count += 1\n elif nums[i] == 0:\n arr.append(count)\n count = 0\n arr.append(count)\n if len(arr) == 1:\n return arr[0] - 1\n maxi = 0\n for j in range(1, len(arr)):\n maxi = max(maxi, arr[j - 1] + arr[j])\n return maxi", "def longestsubarray(nums: List[int]) -> int:\n if 0 not in nums:\n return len(nums) - 1\n arr = [0]\n (count, flag) = (0, 0)\n for (idx, num) in enumerate(nums):\n if num == 0:\n if flag == 1:\n arr.append(count)\n count = 0\n arr.append(0)\n flag = 0\n elif num == 1:\n count += 1\n flag = 1\n if idx == len(nums) - 1:\n arr.append(count)\n arr.append(0)\n maxSum = 0\n for i in range(1, len(arr) - 1):\n if arr[i] == 0:\n maxSum = max(maxSum, arr[i - 1] + arr[i + 1])\n return maxSum"], "starter_code": "def longestsubarray(nums: List[int]) -> int:\n", "input_output": {"fn_name": "longestSubarray", "inputs": [[[1, 1, 0, 1]]], "outputs": [3]}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Sliding Window", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures", "Amortized analysis"], "skill_types": ["Dynamic programming", "Amortized analysis", "Data structures"], "url": "https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "longestsubarray", "task_id": "TACO_lite/136", "example": [[[[1, 1, 0, 1]], [[0, 1, 1, 1, 0, 1, 1, 0, 1]], [[1, 1, 1]], [[1, 1, 0, 0, 1, 1, 1, 0, 1]], [[0, 0, 0]]], ["3", "5", "2", "4", "0"]]} +{"requirement": "Given a number s in their binary representation. Return the number of steps to reduce it to 1 under the following rules:\n\n\nIf the current number is even, you have to divide it by 2.\n\n\nIf the current number is odd, you have to add 1 to it.\n\n\nIt's guaranteed that you can always reach to one for all testcases.\n \nExample 1:\nInput: s = \"1101\"\nOutput: 6\nExplanation: \"1101\" corressponds to number 13 in their decimal representation.\nStep 1) 13 is odd, add 1 and obtain 14. \nStep 2) 14 is even, divide by 2 and obtain 7.\nStep 3) 7 is odd, add 1 and obtain 8.\nStep 4) 8 is even, divide by 2 and obtain 4.  \nStep 5) 4 is even, divide by 2 and obtain 2. \nStep 6) 2 is even, divide by 2 and obtain 1.  \n\nExample 2:\nInput: s = \"10\"\nOutput: 1\nExplanation: \"10\" corressponds to number 2 in their decimal representation.\nStep 1) 2 is even, divide by 2 and obtain 1.  \n\nExample 3:\nInput: s = \"1\"\nOutput: 0\n\n \nConstraints:\n\n1 <= s.length <= 500\ns consists of characters '0' or '1'\ns[0] == '1'", "solutions": ["def numsteps(s: str) -> int:\n (i, mid_zero) = (0, 0)\n for j in range(1, len(s)):\n if s[j] == '1':\n mid_zero += j - i - 1\n i = j\n if i == 0:\n return len(s) - 1\n return mid_zero + 1 + len(s)"], "starter_code": "def numsteps(s: str) -> int:\n", "input_output": {"fn_name": "numSteps", "inputs": [["\"1101\""]], "outputs": [8]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Bit Manipulation", "String"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Bit manipulation"], "skill_types": ["Bit manipulation"], "url": "https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numsteps", "task_id": "TACO_lite/218", "example": [[["1101"], ["10"], ["1"]], ["6", "1", "0"]]} +{"requirement": "Given two strings a and b. The task is to find if the string 'b' can be obtained by rotating another string 'a' by exactly 2 places.\nExample 1:\nInput:\na = amazon\nb = azonam\nOutput: 1\nExplanation: amazon can be rotated anti\nclockwise by two places, which will make\nit as azonam.\nExample 2:\nInput:\na = geeksforgeeks\nb = geeksgeeksfor\nOutput: 0\nExplanation: If we rotate geeksforgeeks by\ntwo place in any direction , we won't get\ngeeksgeeksfor.\nYour Task:\nThe task is to complete the function isRotated() which takes two strings as input parameters and checks if given strings can be formed by rotations. The function returns true if string 1 can be obtained by rotating string 2 by two places, else it returns false.\nExpected Time Complexity: O(N).\nExpected Auxilary Complexity: O(N).\nChallenge: Try doing it in O(1) space complexity.\nConstraints:\n1 ≤ length of a, b ≤ 10^{5}", "solutions": ["def isrotated(str1, str2):\n if str1[2:] + str1[:2] == str2 or str1[len(str1) - 2:] + str1[:len(str1) - 2] == str2:\n return 1\n return 0", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return 0\n crt = ''\n acrt = ''\n acrt = str2[len(str2) - 2:] + str2[0:len(str2) - 2]\n crt = str2[2:] + str2[0:2]\n return crt == str1 or acrt == str1", "def isrotated(str1, str2):\n n = len(str1)\n k = len(str2)\n if n != k:\n return False\n if str1[0] == str2[n - 2] and str1[1] == str2[n - 1]:\n for i in range(2, n):\n if str1[i] != str2[i - 2]:\n return False\n elif str1[n - 2] == str2[0] and str1[n - 1] == str2[1]:\n for i in range(2, n):\n if str2[i] != str1[i - 2]:\n return False\n else:\n return False\n return True", "def isrotated(str1, str2):\n n = len(str1)\n k = len(str2)\n if n != k:\n return False\n rotateclock = True\n rotateanticlock = True\n for i in range(n):\n if str1[i] != str2[(i + 2) % n]:\n rotateclock = False\n for i in range(k):\n if str1[(i + 2) % n] != str2[i]:\n rotateanticlock = False\n return rotateclock or rotateanticlock", "def isrotated(str1, str2):\n if str1[2:] + str1[:2] == str2:\n return True\n elif str1[len(str1) - 2:] + str1[:len(str1) - 2] == str2:\n return True\n else:\n return False", "def isrotated(str1, str2):\n s1 = str1[2:] + str1[0:2]\n s2 = str1[-2:] + str1[0:-2]\n if s1 == str2 or s2 == str2:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n st = str2[0:2]\n st1 = str2[2:]\n left_result = st1 + st\n st2 = str2[-2:]\n st3 = str2[:-2]\n right_result = st2 + st3\n if left_result == str1 or right_result == str1:\n return True\n else:\n return False", "def isrotated(str1, str2):\n n = len(str1)\n (clockwise, anticlockwise) = (True, True)\n for i in range(n):\n if str1[i] != str2[(i + 2) % n]:\n clockwise = False\n break\n for i in range(n):\n if str1[(i + 2) % n] != str2[i]:\n anticlockwise = False\n break\n return clockwise or anticlockwise", "def isrotated(str1, str2):\n n = len(str1)\n m = len(str2)\n if n != m:\n return False\n if n < 2:\n return str1 == str2\n clk = ''\n anti_clk = ''\n clk = clk + str1[2:] + str1[0:2]\n anti_clk = anti_clk + str1[n - 2:] + str1[0:n - 2]\n return clk == str2 or anti_clk == str2", "def isrotated(str1, str2):\n if str1[2:] == str2[:-2] and str1[:2] == str2[-2:] or (str1[-2:] == str2[:2] and str1[:-2] == str2[2:]):\n return True\n return False", "def isrotated(str1, str2):\n s1 = str1[2:] + str1[:2]\n s2 = str2[2:] + str2[:2]\n if str1 == s2 or str2 == s1:\n return True\n return False", "def isrotated(str1, str2):\n n = len(str1)\n temp1 = str1[n - 2:] + str1[0:n - 2]\n temp2 = str2[n - 2:] + str2[0:n - 2]\n if temp1 == str2 or temp2 == str1:\n return 1\n return 0", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return 0\n output = 0\n n = len(str1)\n flag1 = True\n flag2 = True\n for i in range(len(str1)):\n if not str1[i] == str2[(i + 2) % n]:\n flag1 = False\n if not str1[i] == str2[(n - 2 + i) % n]:\n flag2 = False\n if flag1 and flag2:\n break\n return 1 if flag1 or flag2 else 0", "def isrotated(str1, str2):\n i = 0\n clk = str2[2:] + str2[0:2]\n antclk = str2[len(str2) - 2] + str2[len(str2) - 1] + str2[0:len(str2) - 2]\n if str1 == clk or str1 == antclk:\n return 1\n return 0", "def isrotated(str1, str2):\n n = len(str1)\n temp1 = str1[n - 2:] + str1[0:n - 2]\n temp2 = str2[n - 2:] + str2[0:n - 2]\n if temp1 == str2 or temp2 == str1:\n return True\n else:\n return False", "def isrotated(str1, str2):\n return str1 == str2[2:] + str2[:2] or str1 == str2[-2:] + str2[:-2]", "def isrotated(str1, str2):\n str4 = str1[-2:] + str1[:-2]\n str3 = str1[2:] + str1[:2]\n if str3 == str2 or str4 == str2:\n return True\n return False", "def isrotated(str1, str2):\n crotate = str1[2:] + str1[0:2]\n acrotate = str1[len(str1) - 2:] + str1[0:len(str1) - 2]\n if str2 == crotate or str2 == acrotate:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n s = str1[0:2]\n k = str1[2:] + s\n if k == str2:\n return 1\n else:\n s = str1[-2:]\n n = len(str1)\n k = s + str1[:n - 2]\n if k == str2:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return False\n left_rotate = str1[2:] + str1[:2]\n right_rotate = str1[-2:] + str1[:-2]\n if str2 == left_rotate or str2 == right_rotate:\n return True\n return False", "def isrotated(str1, str2):\n k = str1[2:] + str1[:2]\n q = str1[::-1]\n w = q[2:] + q[:2]\n w = w[::-1]\n if k == str2:\n return 1\n elif w == str2:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return False\n s1 = str1[:2]\n s2 = str1[2:]\n s3 = s2 + s1\n s4 = str1[len(str1) - 2:] + str1[0:len(str1) - 2]\n if str2 in s3 or str2 in s4:\n return True\n return False", "def isrotated(str1, str2):\n ans1 = str1[2:len(str1)]\n ans1 = ans1 + str1[0:2]\n ans2 = str1[-2:len(str1)]\n ans2 = ans2 + str1[0:-2]\n if ans1 == str2:\n return True\n elif ans2 == str2:\n return True\n else:\n return False", "def isrotated(str1, str2):\n a = str1[2:len(str1)]\n a = a + str1[0:2]\n b = str1[-2:len(str1)]\n b = b + str1[0:-2]\n if str2 == a:\n return True\n elif str2 == b:\n return True\n return False", "def isrotated(str1, str2):\n d = 2\n l = len(str1)\n ls = str1[d:l] + str1[0:d]\n rs = str1[l - d:l] + str1[0:l - d]\n if ls == str2 or rs == str2:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n str3 = str1[2:] + str1[:2]\n str4 = str2[2:] + str2[:2]\n if str3 == str2 or str1 == str4:\n return 1\n else:\n return 0", "def isrotated(a, b):\n if a[2:] + a[:2] == b or a[-2:] + a[:-2] == b:\n return 1\n return 0", "def isrotated(str1, str2):\n s1 = str1[2:] + str1[0:2]\n s2 = str1[len(str1) - 2:] + str1[0:len(str1) - 2]\n if s1 == str2 or s2 == str2:\n return True\n else:\n return False", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return 0\n sanyam = str1[2:] + str1[0:2]\n sanyam1 = str2[2:] + str2[0:2]\n if sanyam == str2 or sanyam1 == str1:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n n = len(str1)\n if str1[:2] == str2[-2:] and str1[2:] == str2[:-2]:\n return 1\n elif str2[:2] == str1[-2:] and str2[2:] == str1[:-2]:\n return 1\n return 0", "def isrotated(s1, s2):\n if len(s1) != len(s2):\n return False\n left_rotated = s1[2:] + s1[:2]\n right_rotated = s1[-2:] + s1[:-2]\n return s2 in (left_rotated, right_rotated)", "def isrotated(str1, str2):\n sub1 = str1[2:] + str1[:2]\n sub2 = str1[-2:] + str1[:-2]\n if sub1 == str2 or sub2 == str2:\n return True\n else:\n return False", "def isrotated(str1, str2):\n clock = str1[2:] + str1[0:2]\n anti = str1[len(str1) - 2:] + str1[0:len(str1) - 2]\n if str2 == clock or str2 == anti:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n y = str1[:2]\n z = str1[2:]\n p = str1[len(str1) - 2:]\n q = str1[:len(str1) - 2]\n if p + q == str2 or q + p == str2:\n return True\n elif y + z == str2 or z + y == str2:\n return True\n else:\n return False", "def isrotated(str1, str2):\n if str1[2:] + str1[:2] == str2:\n return 1\n elif str1[-2:] + str1[:-2] == str2:\n return 1\n return 0", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return False\n if len(str1) < 3:\n return str1 == str2\n left_rot = str1[2:] + str1[:2]\n right_rot = str1[-2:] + str1[:-2]\n return str2 == left_rot or str2 == right_rot", "def isrotated(str1, str2):\n str11 = str1[2:] + str1[:2]\n str12 = str1[-2:] + str1[:-2]\n if str11 == str2 or str12 == str2:\n return 1\n else:\n return 0", "def isrotated(s1, s2):\n if s1[2:] + s1[:2] == s2:\n return 1\n if s1[-2:] + s1[:-2] == s2:\n return 1\n return 0", "def isrotated(str1, str2):\n l1 = str1[0:2]\n l2 = str1[2:]\n r1 = str1[0:-2]\n r2 = str1[-2:]\n if l2 + l1 == str2 or r2 + r1 == str2:\n return 1\n return 0", "def isrotated(str1, str2):\n (cwise, acwise) = (True, True)\n n = len(str1)\n for i in range(n):\n if str1[i] != str2[(i + 2) % n]:\n cwise = False\n for i in range(n):\n if str1[(i + 2) % n] != str2[i]:\n acwise = False\n return cwise or acwise", "def isrotated(str1, str2):\n a = str1[2:len(str1)] + str1[0:2]\n b = str1[len(str1) - 2:len(str1)] + str1[0:len(str1) - 2]\n if a == str2 or b == str2:\n return True\n else:\n return False", "def isrotated(str1, str2):\n anticlock_string = str2[-2:] + str2[0:-2]\n clock_string = str2[2:] + str2[:2]\n if anticlock_string == str1 or clock_string == str1:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n n = len(str1)\n aclock = str1[2:] + str1[0:2]\n clock = str1[-2:] + str1[0:-2]\n if aclock == str2 or clock == str2:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n k = list(str1)\n k.append(k.pop(0))\n k.append(k.pop(0))\n k = ''.join(k)\n n = list(str1)\n n.insert(0, n.pop(-1))\n n.insert(0, n.pop(-1))\n n = ''.join(n)\n if k == str2 or n == str2:\n return True\n return False", "def isrotated(str1, str2):\n str1_1 = str1[2:] + str1[:2]\n if str1_1 == str2:\n return 1\n str2_1 = str2[2:] + str2[:2]\n if str1 == str2_1:\n return 1\n return 0", "def isrotated(str1, str2):\n anti_str1 = str1[-2:] + str1[:-2]\n clock_str1 = str1[2:] + str1[:2]\n return anti_str1 == str2 or clock_str1 == str2", "def isrotated(str1, str2):\n i = 0\n while i < len(str1):\n if str1[i] != str2[(i + 2) % len(str2)]:\n break\n i += 1\n if i == len(str2):\n return True\n i = 0\n while i < 2:\n if str1[i] != str2[i + len(str1) - 2]:\n break\n i += 1\n if i != 2:\n return False\n while i < len(str1):\n if str1[i] != str2[i - 2]:\n break\n i += 1\n if i == len(str2):\n return True\n return False", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return 0\n if len(str1) <= 2:\n return 0\n p = list(str1)\n a = p[0]\n b = p[1]\n for i in range(2, len(p)):\n p[i - 2] = p[i]\n p[-2] = a\n p[-1] = b\n k = ''.join(p)\n q = list(str1)\n c = q[-2]\n d = q[-1]\n for i in range(len(q) - 1, 1, -1):\n q[i] = q[i - 2]\n q[0] = c\n q[1] = d\n g = ''\n g = ''.join(q)\n if k == str2 or g == str2:\n return 1\n return 0", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return False\n if len(str1) < 2:\n return False\n x = len(str1)\n return str1[2:] + str1[:2] == str2 or str1[-2] + str1[-1] + str1[:x - 2] == str2", "def isrotated(str1, str2):\n n1 = len(str1)\n n2 = len(str2)\n if n1 != n2:\n return 0\n else:\n sc = str1[2:] + str1[:2]\n sac = str1[n1 - 2:] + str1[:n1 - 2]\n return 1 if sc == str2 or sac == str2 else 0", "def isrotated(str1, str2):\n n = len(str1)\n return len(str1) == len(str2) and (str1[2:n] + str1[0:2] == str2[:] or str1[n - 2:n] + str1[0:n - 2] == str2[:])", "def isrotated(str1, str2):\n n = len(str1)\n m = len(str2)\n if n != m:\n return False\n if n < 2:\n return str1 == str2\n a_str = str1[2:] + str1[0:2]\n aa_str = str1[n - 2:] + str1[0:n - 2]\n return a_str == str2 or aa_str == str2", "def isrotated(str1, str2):\n if str1 == str2:\n return 1\n elif len(str1) != len(str2):\n return 0\n n1 = len(str1)\n k = n1\n c1 = str1\n ac2 = str1\n temp1 = c1[:2]\n c1 = c1[2:] + temp1\n temp2 = ac2[n1 - 2:n1]\n ac2 = temp2 + ac2[:n1 - 2]\n if c1 == str2 or ac2 == str2:\n return 1\n return 0", "def isrotated(a, b):\n if len(a) != len(b):\n return False\n clockwise = a[-2:] + a[:-2]\n anticlockwise = a[2:] + a[:2]\n if clockwise == b or anticlockwise == b:\n return True\n else:\n return False", "def isrotated(str1, str2):\n N = len(str1)\n A = str1 + str1\n if str2 in A:\n if A.index(str2) == 2 or A.index(str2) == N - 2:\n return True\n return False"], "starter_code": "def isrotated(str1,str2):\n", "input_output": {"inputs": ["a = amazon\nb = azonam", "a = geeksforgeeks\nb = geeksgeeksfor"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/check-if-string-is-rotated-by-two-places-1587115620/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "isrotated", "task_id": "TACO_lite/259", "example": [[], []]} +{"requirement": "Given a Binary Tree having positive and negative nodes. Find the maximum sum of a level in the given Binary Tree.\nExample 1:\nInput : \n 4\n / \\\n 2 -5\n / \\ / \\\n -1 3 -2 6\nOutput: 6\nExplanation :\nSum of all nodes of 0'th level is 4\nSum of all nodes of 1'th level is -3\nSum of all nodes of 2'th level is 6\nHence maximum sum is 6\nExample 2:\nInput : \n 1\n / \\\n 2 3\n / \\ \\\n 4 5 8\n / \\\n 6 7 \nOutput : 17\nExplanation: Maximum sum is at level 2.\nYour Task: \nYou dont need to read input or print anything. Complete the function maxLevelSum() which takes root node as input parameter and returns the maximum sum of any horizontal level in the given Binary Tree.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 ≤ N ≤ 10^{4}", "solutions": ["def maxLevelSum(root):\n q = [root]\n res = 0\n while q:\n l = len(q)\n tmp = 0\n for i in range(l):\n p = q.pop(0)\n tmp += p.data\n if p.left:\n q.append(p.left)\n if p.right:\n q.append(p.right)\n if res == 0 and tmp < 0:\n res = tmp\n else:\n res = max(res, tmp)\n return res", "def slove(root, lvl, d):\n if root is None:\n return\n if lvl not in d:\n d[lvl] = root.data\n else:\n d[lvl] += root.data\n slove(root.left, lvl + 1, d)\n slove(root.right, lvl + 1, d)\n\ndef maxLevelSum(root):\n d = {}\n slove(root, 0, d)\n return max(d.values())", "def maxLevelSum(root):\n queue = deque()\n queue.append(root)\n max_sum = -9999\n while queue:\n size = len(queue)\n local_sum = 0\n for _ in range(size):\n curr = queue.popleft()\n local_sum += curr.data\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n max_sum = max(max_sum, local_sum)\n return max_sum", "def maxLevelSum(root):\n if not root:\n return 0\n queue = [[root]]\n ans = root.data\n while queue:\n level = queue.pop(0)\n temp = []\n for node in level:\n if node.left:\n temp.append(node.left)\n if node.right:\n temp.append(node.right)\n if temp:\n queue.append(temp)\n ans = max(ans, sum([node.data for node in temp]))\n return ans", "import queue\n\ndef maxLevelSum(root):\n maxsum = float('-inf')\n if not root:\n return maxsum\n q = queue.Queue()\n q.put(root)\n while q.qsize():\n sum = 0\n for i in range(q.qsize()):\n node = q.get()\n sum += node.data\n if node.left:\n q.put(node.left)\n if node.right:\n q.put(node.right)\n maxsum = max(maxsum, sum)\n return maxsum", "def maxLevelSum(root):\n s1 = [root]\n s2 = []\n ans = -12345678\n while s1 != []:\n a = 0\n for i in s1:\n a = a + i.data\n ans = max(ans, a)\n for j in s1:\n if j.left != None:\n s2.append(j.left)\n if j.right != None:\n s2.append(j.right)\n s1 = s2\n s2 = []\n return ans", "from collections import deque\n\ndef maxLevelSum(root):\n maximum = -100000\n dQ = deque()\n dQ.append(root)\n while dQ:\n calculate = 0\n times = len(dQ)\n for i in range(times):\n holdnode = dQ.popleft()\n calculate += holdnode.data\n if holdnode.left != None:\n dQ.append(holdnode.left)\n if holdnode.right != None:\n dQ.append(holdnode.right)\n maximum = max(maximum, calculate)\n return maximum", "def maxLevelSum(root):\n l = [root, 'a']\n max1 = -2 ** 31\n while True:\n w = l.pop(0)\n s = 0\n while w != 'a':\n if w.left != None:\n l.append(w.left)\n if w.right != None:\n l.append(w.right)\n s += w.data\n w = l.pop(0)\n max1 = max(max1, s)\n if l == []:\n return max1\n l.append('a')", "def maxLevelSum(root):\n q = []\n level = []\n ans = -10000\n q.append(root)\n while q != [] and root is not None:\n l = []\n for node in q:\n l.append(node.data)\n if node.left:\n level.append(node.left)\n if node.right:\n level.append(node.right)\n s = sum(l)\n ans = max(ans, s)\n q = level\n level = []\n return ans", "def maxLevelSum(root):\n hs = {}\n\n def fun(root, level):\n if root == None:\n return\n if level not in hs:\n hs[level] = root.data\n else:\n hs[level] += root.data\n fun(root.left, level + 1)\n fun(root.right, level + 1)\n fun(root, 0)\n return max(hs.values())", "import sys\nfrom queue import Queue\n\ndef maxLevelSum(root):\n maxSum = -sys.maxsize\n if root is None:\n return 0\n q = Queue()\n q.put(root)\n while not q.empty():\n sum = 0\n l = q.qsize()\n for i in range(l):\n if q.queue[0].left is not None:\n q.put(q.queue[0].left)\n if q.queue[0].right is not None:\n q.put(q.queue[0].right)\n sum += q.get().data\n maxSum = max(sum, maxSum)\n return maxSum", "def maxLevelSum(root):\n su = -10 ** 28\n l = [root]\n if root != None:\n su = root.data\n while l:\n r = []\n s = 0\n for i in l:\n if i.left:\n r.append(i.left)\n s += i.left.data\n if i.right:\n r.append(i.right)\n s += i.right.data\n if r == []:\n return su\n if s > su:\n su = s\n l = r\n return su", "def fun(root, level, res):\n if root == None:\n return\n if level >= len(res):\n res.append([])\n res[level].append(root.data)\n self.fun(root.left, level + 1, res)\n self.fun(root.right, level + 1, res)\n\ndef maxLevelSum(root):\n res = []\n self.fun(root, 0, res)\n s = sum(res[0])\n for i in res:\n s = max(s, sum(i))\n return s", "def maxLevelSum(root):\n levels = self.getLevelOrderNodes(root)\n levelSums = []\n for level in levels:\n levelSums.append(sum(levels[level]))\n return max(levelSums)\n\ndef getLevelOrderNodes(root):\n levels = dict()\n self.levelOrder(root, 0, levels)\n return levels\n\ndef levelOrder(curr, currHeight, levels):\n if not curr:\n return\n if currHeight not in levels:\n levels[currHeight] = [curr.data]\n else:\n levels[currHeight].append(curr.data)\n self.levelOrder(curr.left, currHeight + 1, levels)\n self.levelOrder(curr.right, currHeight + 1, levels)", "from collections import deque\n\ndef maxLevelSum(root):\n q = deque()\n level = 0\n q.appendleft(root)\n res = -9999999999\n while q:\n n = len(q)\n level += 1\n total = 0\n while n > 0:\n n -= 1\n node = q.pop()\n total += node.data\n if node.left:\n q.appendleft(node.left)\n if node.right:\n q.appendleft(node.right)\n res = max(res, total)\n return res", "def maxLevelSum(root):\n maxans = -1000000\n q = [root]\n while q:\n levelsum = 0\n for i in range(0, len(q)):\n temp = q.pop(0)\n levelsum += temp.data\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n maxans = max(maxans, levelsum)\n return maxans", "from collections import deque\n\ndef maxLevelSum(root):\n d = {}\n\n def leve(root, h):\n if not root:\n return\n if h not in d:\n d[h] = root.data\n else:\n d[h] += root.data\n leve(root.left, h + 1)\n leve(root.right, h + 1)\n leve(root, 0)\n return max(d.values())", "import collections\nimport sys\n\ndef maxLevelSum(root):\n q = collections.deque()\n q.append(root)\n mx = -sys.maxsize\n while q:\n qLen = len(q)\n sm = 0\n for i in range(qLen):\n cur = q.popleft()\n if cur.left:\n q.append(cur.left)\n if cur.right:\n q.append(cur.right)\n sm += cur.data\n mx = max(mx, sm)\n return mx", "def maxLevelSum(root):\n l = []\n q = []\n k = [0]\n m = -1\n q.append(root)\n while q:\n z = q.pop(0)\n x = k.pop(0)\n if m != x:\n m = x\n l.append([])\n l[-1].append(z.data)\n if z.left is not None:\n q.append(z.left)\n k.append(x + 1)\n if z.right is not None:\n q.append(z.right)\n k.append(x + 1)\n s = sum(l[0])\n for x in l:\n if s < sum(x):\n s = sum(x)\n return s", "def maxLevelSum(root):\n queue = [root]\n max_sum = float('-inf')\n while len(queue):\n n = len(queue)\n temp = 0\n while n > 0:\n node = queue.pop(0)\n temp += node.data\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n n = n - 1\n max_sum = max(max_sum, temp)\n return max_sum", "from collections import deque as d\n\ndef maxLevelSum(root):\n l = d()\n b = root\n l.appendleft(root)\n l.appendleft(' ')\n r = -10 ** 9\n lp = []\n while l:\n a = l.pop()\n if a == ' ':\n if sum(lp) > r and lp:\n r = sum(lp)\n lp = []\n if l:\n l.appendleft(' ')\n else:\n if a.left:\n l.appendleft(a.left)\n lp.append(a.left.data)\n if a.right:\n l.appendleft(a.right)\n lp.append(a.right.data)\n if root.data > r:\n return root.data\n return r", "def maxLevelSum(root):\n ans = -1000000\n queue = [root]\n level = []\n while queue != [] and root is not None:\n l = []\n for node in queue:\n l.append(node.data)\n if node.left:\n level.append(node.left)\n if node.right:\n level.append(node.right)\n s1 = sum(l)\n ans = max(ans, s1)\n queue = level\n level = []\n return ans", "def maxLevelSum(root):\n dir = {}\n\n def maxlevel(root, dir, level):\n if not root:\n return\n if dir.get(level):\n dir[level] = dir.get(level) + root.data\n else:\n dir[level] = root.data\n maxlevel(root.left, dir, level + 1)\n maxlevel(root.right, dir, level + 1)\n maxx = -1111111\n maxlevel(root, dir, 0)\n for k in dir:\n maxx = max(maxx, dir.get(k))\n return maxx", "def maxLevelSum(root):\n q = [root]\n maxx = -11111111111111111111111111111111111111111111111111111111111111111111111111111111111\n while q:\n list = []\n for i in q:\n list.append(i.data)\n maxx = max(maxx, sum(list))\n for _ in range(len(q)):\n node = q.pop(0)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return maxx", "def maxLevelSum(root):\n bfs = []\n if not root:\n return 0\n queue = deque([])\n queue.append(root)\n while queue:\n size = len(queue)\n currsum = 0\n for i in range(size):\n curritem = queue.popleft()\n currsum += curritem.data\n if curritem.left is not None:\n queue.append(curritem.left)\n if curritem.right is not None:\n queue.append(curritem.right)\n bfs.append(currsum)\n return max(bfs)", "def maxLevelSum(root):\n q = deque([root])\n ans = [root.data]\n while q:\n level = []\n for i in range(len(q)):\n curr = q.popleft()\n if curr.left:\n q.append(curr.left)\n level.append(curr.left.data)\n if curr.right:\n q.append(curr.right)\n level.append(curr.right.data)\n ans.append(sum(level))\n ans.pop()\n return max(ans)", "def maxLevelSum(root):\n if root is None:\n return 0\n q = []\n q.append(root)\n ans = root.data\n while len(q) > 0:\n t = []\n temp_ans = 0\n while len(q) != 0:\n x = q.pop(0)\n temp_ans += x.data\n if x.left is not None:\n t.append(x.left)\n if x.right is not None:\n t.append(x.right)\n if temp_ans > ans:\n ans = temp_ans\n q = t\n return ans", "def maxLevelSum(root):\n if not root:\n return 0\n q = [root]\n m = root.data\n while q:\n children = []\n vals = []\n while q:\n val = q.pop(0)\n if val.left:\n children.append(val.left)\n vals.append(val.left.data)\n if val.right:\n children.append(val.right)\n vals.append(val.right.data)\n if vals:\n m = max(m, sum(vals))\n q = children\n return m", "def maxLevelSum(root):\n if root == None:\n return 0\n q = []\n q.append(root)\n mx = -999999\n while len(q) > 0:\n n = len(q)\n ans = 0\n for i in range(n):\n temp = q.pop(0)\n ans += temp.data\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n mx = max(ans, mx)\n return mx", "def maxLevelSum(root):\n s = []\n queue = [root]\n while queue != []:\n t = []\n for i in range(len(queue)):\n curr = queue[0]\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n t.append(curr.data)\n queue.pop(0)\n s.append(sum(t))\n return max(s)", "def maxLevelSum(root):\n\n def height(node):\n if node is None:\n return 0\n else:\n lheight = height(node.left)\n rheight = height(node.right)\n if lheight > rheight:\n return lheight + 1\n else:\n return rheight + 1\n\n def currlvl(root, lvl):\n if root is None:\n return\n elif lvl == 1:\n res.append(root.data)\n elif lvl > 1:\n currlvl(root.left, lvl - 1)\n currlvl(root.right, lvl - 1)\n res = []\n l = []\n h = height(root)\n for i in range(1, h + 1):\n currlvl(root, i)\n s = sum(res)\n l.append(s)\n res.clear()\n return max(l)", "def maxLevelSum(root):\n p = []\n q = []\n g = {}\n p.append(0)\n q.append(root)\n while len(q) > 0:\n a = p.pop(0)\n b = q.pop(0)\n if a not in g:\n g[a] = [b.data]\n else:\n g[a].append(b.data)\n if b.left != None:\n p.append(a + 1)\n q.append(b.left)\n if b.right != None:\n p.append(a + 1)\n q.append(b.right)\n ans = []\n for x in g:\n ans.append(sum(g[x]))\n return max(ans)", "def maxLevelSum(root):\n q = []\n maxx = -999999\n q.append(root)\n while q:\n n = len(q)\n ans = 0\n while n > 0:\n p = q.pop(0)\n ans += p.data\n if p.left:\n q.append(p.left)\n if p.right:\n q.append(p.right)\n n -= 1\n if maxx < ans:\n maxx = ans\n return maxx", "def maxLevelSum(root):\n if root != None:\n q = deque()\n q.append(root)\n count = 0\n ans = root.data\n while len(q) > 0:\n count = len(q)\n total = 0\n while count > 0:\n num = q.popleft()\n total += num.data\n if not num.left is None:\n q.append(num.left)\n if not num.right is None:\n q.append(num.right)\n count -= 1\n ans = max(ans, total)\n return ans", "def maxLevelSum(root):\n q = []\n q.append(root)\n x = -9999\n while len(q):\n s = 0\n for i in range(len(q)):\n temp = q.pop(0)\n s = s + temp.data\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n x = max(x, s)\n return x", "def maxLevelSum(root):\n q = [root]\n ans = root.data\n while len(q) != 0:\n sum = 0\n for i in range(len(q)):\n root = q.pop(0)\n sum += root.data\n if root.left:\n q.append(root.left)\n if root.right:\n q.append(root.right)\n ans = max(ans, sum)\n return ans", "def maxLevelSum(root):\n sum_dict = {}\n q = []\n q.append((root, 0))\n while len(q) != 0:\n tt = q.pop(0)\n if tt[1] not in sum_dict:\n sum_dict[tt[1]] = 0\n sum_dict[tt[1]] += tt[0].data\n if tt[0].left != None:\n q.append((tt[0].left, tt[1] + 1))\n if tt[0].right != None:\n q.append((tt[0].right, tt[1] + 1))\n return max(list(sum_dict.values()))", "import collections\n\ndef maxLevelSum(root):\n maxLevel = -float('inf')\n q = collections.deque([root])\n while q:\n s = 0\n for i in range(len(q)):\n node = q.popleft()\n s += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n maxLevel = max(maxLevel, s)\n return maxLevel", "def maxLevelSum(root):\n if root == None:\n return\n q = [root]\n s = 0\n l = []\n while q:\n le = len(q)\n s = 0\n for i in range(le):\n t = q.pop(0)\n if t:\n s = s + t.data\n q.append(t.left)\n q.append(t.right)\n l.append(s)\n m = max(l)\n if m == 0:\n l.remove(0)\n return max(l)", "r = 0\n\ndef maxLevelSum(root):\n global r\n r = -1000000000000000000\n return self.reverseLevelOrder(root)\n\ndef reverseLevelOrder(root):\n global r\n A = []\n B = []\n C = []\n D = []\n if root is None:\n return A\n A.append(root)\n while len(A) > 0:\n while len(A) > 0:\n node = A.pop(0)\n B.append(node.data)\n if node.left is not None:\n D.append(node.left)\n if node.right is not None:\n D.append(node.right)\n A.extend(D)\n D = []\n w = sum(B)\n if w > r:\n r = w\n B = []\n return r", "def maxLevelSum(root):\n if not root:\n return\n nodes = [root]\n maxSum = float('-inf')\n while nodes:\n l = len(nodes)\n sumEl = 0\n for i in range(l):\n cur = nodes.pop(0)\n sumEl += cur.data\n if cur.left:\n nodes.append(cur.left)\n if cur.right:\n nodes.append(cur.right)\n maxSum = max(maxSum, sumEl)\n return maxSum", "def maxLevelSum(root):\n q = []\n q.append(root)\n mini = -1000000000.0\n while len(q):\n count = len(q)\n s = 0\n while count > 0:\n p = q.pop(0)\n s += p.data\n if p.left:\n q.append(p.left)\n if p.right:\n q.append(p.right)\n count -= 1\n if mini < s:\n mini = s\n return mini", "def maxLevelSum(root):\n\n def traversal(root):\n if root == None:\n return None\n hd = 0\n q = [[root, hd]]\n dict1 = dict()\n while q != []:\n node = q.pop(0)\n if node[-1] not in dict1:\n dict1[node[-1]] = node[0].data\n else:\n dict1[node[-1]] += node[0].data\n hd = node[-1]\n if node[0].left:\n q.append([node[0].left, hd + 1])\n if node[0].right:\n q.append([node[0].right, hd + 1])\n return max(dict1.values())\n return traversal(root)", "import math\n\ndef maxLevelSum(root):\n ans = dict()\n self.rec(root, 1, ans)\n max_sum = -21321321322321\n for (key, val) in ans.items():\n max_sum = max(max_sum, val)\n return max_sum\n\ndef rec(root, level, ans):\n if root == None:\n return\n if level not in ans:\n ans[level] = 0\n ans[level] += root.data\n self.rec(root.left, level + 1, ans)\n self.rec(root.right, level + 1, ans)", "def maxLevelSum(root):\n d = {}\n st = []\n st.append([root, 1])\n while st:\n (tamp, dep) = st.pop(0)\n if dep in d.keys():\n d[dep] = d[dep] + tamp.data\n else:\n d[dep] = tamp.data\n if tamp.left:\n st.append([tamp.left, dep + 1])\n if tamp.right:\n st.append([tamp.right, dep + 1])\n return max(d.values())", "def maxLevelSum(root):\n sums = []\n\n def dfs(node, lvl):\n if lvl == len(sums):\n sums.append(node.data)\n else:\n sums[lvl] += node.data\n if node.left:\n dfs(node.left, lvl + 1)\n if node.right:\n dfs(node.right, lvl + 1)\n dfs(root, 0)\n return max(sums)", "def maxLevelSum(root):\n q = []\n q.append(root)\n q.append('$')\n max = root.data\n sum = 0\n while len(q) > 0:\n t = q.pop(0)\n if t == '$':\n if len(q) > 0:\n q.append('$')\n if sum >= max:\n max = sum\n sum = 0\n else:\n if t.left is not None:\n q.append(t.left)\n sum += t.left.data\n if t.right is not None:\n q.append(t.right)\n sum += t.right.data\n return max", "from collections import Counter\n\ndef maxLevelSum(root):\n c = Counter()\n self.myFunc(root, c, 0)\n return c.most_common()[0][1]\n\ndef myFunc(root, c, level):\n if not root:\n return\n level += 1\n c[level] += root.data\n self.myFunc(root.left, c, level)\n self.myFunc(root.right, c, level)\n return", "def __init__():\n self.level = {}\n\ndef trav(root, l):\n if l in self.level:\n self.level[l].append(root.data)\n else:\n self.level[l] = [root.data]\n if root.left != None:\n self.trav(root.left, l + 1)\n if root.right != None:\n self.trav(root.right, l + 1)\n\ndef maxLevelSum(root):\n self.trav(root, 0)\n flag = True\n maxS = 0\n for l in self.level.keys():\n s = sum(self.level[l])\n if flag or maxS < s:\n flag = False\n maxS = s\n return maxS", "import collections\n\ndef maxLevelSum(root):\n q = collections.deque([root])\n ans = float('-inf')\n while q:\n sz = len(q)\n s = 0\n for _ in range(sz):\n n = q.popleft()\n s += n.data\n if n.left:\n q.append(n.left)\n if n.right:\n q.append(n.right)\n ans = max(ans, s)\n return ans", "def maxLevelSum(root):\n from collections import deque\n queue = deque([root])\n Max = float('-inf')\n while queue:\n f = lvl = 0\n for _ in range(len(queue)):\n node = queue.popleft()\n if node:\n f = 1\n lvl += node.data\n queue.append(node.left)\n queue.append(node.right)\n if f:\n Max = max(Max, lvl)\n return Max", "def maxLevelSum(root):\n d = {}\n l = []\n level = 1\n self.helper(root, level, d)\n for i in d:\n l.append(sum(d[i]))\n return max(l)\n\ndef helper(root, level, d):\n if root:\n if root == 'N':\n return\n else:\n if level not in d:\n d[level] = [root.data]\n else:\n d[level].append(root.data)\n self.helper(root.left, level + 1, d)\n self.helper(root.right, level + 1, d)", "import collections\n\ndef maxLevelSum(root):\n q = collections.deque()\n max_sum = root.data\n q.append(root)\n while len(q) > 0:\n levelSum = 0\n n = len(q)\n for i in range(n):\n currNode = q.popleft()\n levelSum += currNode.data\n if currNode.left:\n q.append(currNode.left)\n if currNode.right:\n q.append(currNode.right)\n max_sum = max(max_sum, levelSum)\n return max_sum", "from collections import deque\n\ndef maxLevelSum1(root):\n if root == None:\n return 0\n result = root.data\n q = deque()\n q.append(root)\n while len(q) > 0:\n count = len(q)\n sum = 0\n while count > 0:\n temp = q.popleft()\n sum = sum + temp.data\n if temp.left != None:\n q.append(temp.left)\n if temp.right != None:\n q.append(temp.right)\n count -= 1\n result = max(sum, result)\n return result\n\ndef maxLevelSum(root):\n return maxLevelSum1(root)", "def maxLevelSum(root):\n return max(self.helper(root))\n\ndef helper(root, level=0, levels_sum=None):\n if not root:\n return 0\n if not levels_sum:\n levels_sum = []\n if level == len(levels_sum):\n levels_sum.append(0)\n levels_sum[level] += root.data\n self.helper(root.left, level + 1, levels_sum)\n self.helper(root.right, level + 1, levels_sum)\n return levels_sum", "def maxLevelSum(root):\n if root is None:\n return 0\n freq = {}\n self.traversal(root, freq, 0)\n maximum = freq[0]\n for level in freq.keys():\n maximum = max(maximum, freq[level])\n return maximum\n\ndef traversal(root, freq, level):\n if root is None:\n return\n if level in freq.keys():\n freq[level] += root.data\n else:\n freq[level] = root.data\n self.traversal(root.left, freq, level + 1)\n self.traversal(root.right, freq, level + 1)", "def maxLevelSum(root):\n\n def helper(root, mp, k):\n if root:\n if k in mp:\n mp[k] += root.data\n else:\n mp[k] = root.data\n helper(root.left, mp, k + 1)\n helper(root.right, mp, k + 1)\n mp = {}\n helper(root, mp, 0)\n return max(mp.values())", "def getTree(root, arr, d):\n if not root:\n return\n arr.append([root.data, d])\n self.getTree(root.right, arr, d + 1)\n self.getTree(root.left, arr, d + 1)\n\ndef maxLevelSum(root):\n arr = []\n self.getTree(root, arr, 0)\n d = arr[len(arr) - 1][1]\n maxx = -1000000000\n for i in range(0, d + 1):\n summ = 0\n for e in arr:\n if i == e[1]:\n summ = summ + e[0]\n if summ > maxx:\n maxx = summ\n return maxx", "def maxLevelSum(root):\n\n def helper(root):\n ans = -99999\n q = deque()\n t = 0\n if not root:\n return ans\n q.append(root)\n while q:\n for i in range(len(q)):\n a = q.popleft()\n if a.left:\n q.append(a.left)\n if a.right:\n q.append(a.right)\n t += a.data\n ans = max(ans, t)\n t = 0\n return ans\n if not root:\n return 0\n return helper(root)", "def maxLevelSum(root):\n q = []\n maxi = -100000000000\n if root is None:\n return 0\n q.append(root)\n while len(q) > 0:\n nc = len(q)\n level = [0] * nc\n for i in range(nc):\n node = q.pop(0)\n if node.left is not None:\n q.append(node.left)\n if node.right is not None:\n q.append(node.right)\n level[i] = node.data\n maxi = max(maxi, sum(level))\n return maxi", "def maxLevelSum(root):\n\n def helper(root):\n ans = -9999999\n q = []\n t = 0\n if not root:\n return x\n q.append(root)\n while q:\n for i in range(len(q)):\n a = q.pop(0)\n if a.left:\n q.append(a.left)\n if a.right:\n q.append(a.right)\n t += a.data\n ans = max(t, ans)\n t = 0\n return ans\n return helper(root)", "def maxLevelSum(root):\n\n def helper(x):\n q = []\n t = []\n ans = -9999\n q.append(x)\n while q:\n l = len(q)\n for i in range(l):\n a = q.pop(0)\n if a.left:\n q.append(a.left)\n if a.right:\n q.append(a.right)\n t.append(a.data)\n ans = max(ans, sum(t))\n t = []\n return ans\n a = helper(root)\n return a", "def maxLevelSum(root):\n maxlevel = -float('inf')\n q = [root]\n while q:\n temp = []\n tsum = 0\n for i in q:\n tsum += i.data\n if i.left:\n temp.append(i.left)\n if i.right:\n temp.append(i.right)\n maxlevel = max(maxlevel, tsum)\n q = temp\n return maxlevel", "import collections\nfrom collections import deque\n\ndef maxLevelSum(root):\n res = float('-inf')\n q = collections.deque()\n q.append(root)\n while q:\n ql = len(q)\n l = []\n for i in range(ql):\n x = q.popleft()\n if x:\n l.append(x.data)\n q.append(x.left)\n q.append(x.right)\n if l:\n res = max(res, sum(l))\n return res", "def maxLevelSum(root):\n global a, m\n a = []\n m = -1\n\n def S(root, level):\n global a, m\n if not root:\n return 0\n if level > m:\n a.append([])\n m = level\n a[level].append(root.data)\n S(root.left, level + 1)\n S(root.right, level + 1)\n S(root, 0)\n k = []\n for i in a:\n k.append(sum(i))\n return max(k)", "import sys\n\ndef maxLevelSum(root):\n max_sum = -sys.maxsize\n q = [root]\n while q:\n size = len(q)\n summ = 0\n for _ in range(size):\n node = q.pop(0)\n summ += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if summ > max_sum:\n max_sum = summ\n return max_sum", "def maxLevelSum(root):\n if root is None:\n return 0\n result = root.data\n q = []\n q.append(root)\n while q != []:\n c = len(q)\n res = 0\n while c != 0:\n c -= 1\n temp = q[0]\n q.pop(0)\n res = res + temp.data\n if temp.left is not None:\n q.append(temp.left)\n if temp.right is not None:\n q.append(temp.right)\n result = max(res, result)\n return result\n height = self.getHight(root)\n i = 1\n maxsum = 0\n while i <= height:\n tempsum = self.levelOrderTravesal(root, i, 0)\n if tempsum > maxsum:\n maxsum = tempsum\n i += 1\n return maxsum\n\ndef levelOrderTravesal(root, level, sumlevel):\n if root is None:\n return sumlevel\n if level == 1:\n sumlevel += root.data\n elif level > 1:\n sumlevel += self.levelOrderTravesal(root.left, level - 1, sumlevel)\n sumlevel += self.levelOrderTravesal(root.right, level - 1, sumlevel)\n return sumlevel\n\ndef getHight(root):\n if root is None:\n return 0\n leftHight = 1 + self.getHight(root.left)\n rightheight = 1 + self.getHight(root.right)\n return max(leftHight, rightheight)", "def maxLevelSum(root):\n if not root:\n return False\n ans = []\n res = []\n q = deque([root])\n while q:\n level = []\n for _ in range(len(q)):\n node = q.popleft()\n level.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n ans.append(level)\n for a in ans:\n res.append(sum(a))\n return max(res)", "from collections import deque\n\ndef maxLevelSum(root):\n if root is None:\n return 0\n q = deque()\n Sum = 0\n Max = -99999999999999\n q.append(root)\n while q:\n n = len(q)\n Sum = 0\n for i in range(n):\n node = q.popleft()\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n Sum = Sum + node.data\n if Sum > Max:\n Max = Sum\n return Max", "from math import inf\nfrom collections import deque\n\ndef maxLevelSum(root):\n max_sum = -inf\n q = deque([root])\n while q:\n lvl_sum = 0\n for _ in range(len(q)):\n node = q.popleft()\n lvl_sum += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n max_sum = max(max_sum, lvl_sum)\n return max_sum", "def maxLevelSum(root):\n q = []\n l = []\n q.append(root)\n n = 0\n while q:\n j = 0\n for i in range(len(q)):\n node = q.pop(0)\n j += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n l.append(j)\n return max(l)", "def maxLevelSum(root):\n res = -10 ** 5\n queue = [root]\n while queue:\n s = 0\n length = len(queue)\n while length > 0:\n node = queue.pop(0)\n s += node.data\n if node.left != None:\n queue.append(node.left)\n if node.right != None:\n queue.append(node.right)\n length -= 1\n if s > res:\n res = s\n return res", "def maxLevelSum(root):\n if root is None:\n return []\n l = deque([root])\n l2 = []\n while len(l) > 0:\n l1 = []\n y = len(l)\n for i in range(y):\n x = l.popleft()\n if x.left:\n l.append(x.left)\n if x.right:\n l.append(x.right)\n l1.append(x.data)\n l2.append(sum(l1))\n return max(l2)", "def maxLevelSum(root):\n if root == None:\n return 0\n ans = root.data\n q = deque()\n q.append(root)\n while len(q) > 0:\n count = len(q)\n summ = 0\n while count > 0:\n temp = q.popleft()\n summ = summ + temp.data\n if temp.left != None:\n q.append(temp.left)\n if temp.right != None:\n q.append(temp.right)\n count -= 1\n ans = max(summ, ans)\n return ans", "from queue import Queue\n\ndef maxLevelSum(root):\n maxans = float('-inf')\n q = [root]\n while q:\n levelsum = 0\n for i in range(len(q)):\n temp = q.pop(0)\n levelsum += temp.data\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n maxans = max(maxans, levelsum)\n return maxans", "def maxLevelSum(root):\n ans = float('-inf')\n q = [root]\n while len(q) > 0:\n l = [i.data for i in q]\n ans = max(ans, sum(l))\n count = len(q)\n for i in range(count):\n temp = q.pop(0)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n return ans", "def maxLevelSum(root):\n level = []\n q = []\n q.append(root)\n while len(q):\n t = len(q)\n temp = []\n while t > 0:\n t -= 1\n s = q.pop(0)\n if s.right:\n q.append(s.right)\n if s.left:\n q.append(s.left)\n temp.append(s.data)\n level.append(sum(temp))\n return max(level)", "def maxLevelSum(root):\n maxs = float('-inf')\n q = [root]\n while q:\n level = 0\n flag = 0\n l = len(q)\n for i in range(l):\n node = q.pop(0)\n if node:\n flag = 1\n level += node.data\n q.append(node.left)\n q.append(node.right)\n if flag:\n maxs = max(level, maxs)\n return maxs", "from collections import deque\n\ndef maxLevelSum(root):\n ans = -10 ** 9\n if root is None:\n return ans\n queue = deque()\n queue.append(root)\n while len(queue):\n temp = 0\n for i in range(len(queue)):\n node = queue.popleft()\n temp += node.data\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n ans = max(ans, temp)\n return ans", "from collections import deque\n\ndef maxLevelSum(root):\n\n def solve(root):\n if root is None:\n return\n Q = deque()\n Q.appendleft(root)\n maxi = float('-inf')\n while Q:\n sz = len(Q)\n sum = 0\n for _ in range(sz):\n node = Q.pop()\n sum += node.data\n if node.left:\n Q.appendleft(node.left)\n if node.right:\n Q.appendleft(node.right)\n maxi = max(maxi, sum)\n return maxi\n return solve(root)", "def maxLevelSum(root):\n q = [[root, 0]]\n s = {}\n c = 0\n while c != len(q):\n t = q[c][0]\n g = q[c][1]\n if g in s:\n s[g] += t.data\n else:\n s[g] = t.data\n if t.left:\n q.append([t.left, g + 1])\n if t.right:\n q.append([t.right, g + 1])\n c += 1\n m = -9999999999\n for i in s:\n if s[i] > m:\n m = s[i]\n return m", "import sys\nfrom collections import defaultdict as dd\n\ndef maxLevelSum(root):\n d = dd(list)\n D = {}\n\n def x(root, lvl):\n if root is None:\n return\n d[lvl] += [root.data]\n return x(root.left, lvl + 1) or x(root.right, lvl + 1)\n x(root, 0)\n mx = -sys.maxsize\n for (k, v) in d.items():\n D[k] = sum(v)\n return max(list(D.values()))\n\ndef maxLevelSum_(root):\n if root is None:\n return root\n q = [root]\n mx = -sys.maxsize\n while q:\n sm = 0\n for i in range(len(q)):\n curr = q.pop(0)\n sm = sm + curr.data\n if curr.left:\n q.append(curr.left)\n if curr.right:\n q.append(curr.right)\n mx = max(mx, sm)\n return mx", "import sys\n\ndef maxLevelSum(root):\n if root is None:\n return root\n q = [root]\n mx = -sys.maxsize\n while q:\n sm = 0\n for i in range(len(q)):\n curr = q.pop(0)\n sm = sm + curr.data\n if curr.left:\n q.append(curr.left)\n if curr.right:\n q.append(curr.right)\n mx = max(mx, sm)\n return mx", "def __init__(value):\n self.left = None\n self.data = value\n self.right = None\n\ndef maxLevelSum(root):\n if root is None:\n return None\n else:\n ans = []\n import collections\n q = collections.deque()\n q.append(root)\n while q:\n count = 0\n for i in range(len(q)):\n node = q.popleft()\n if node:\n count = count + node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n ans.append(count)\n return max(ans)", "def maxLevelSum(root):\n q = []\n res = []\n q.append(root)\n while q:\n count = len(q)\n ans = []\n while count:\n temp = q.pop(0)\n ans.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n count -= 1\n res.append(ans)\n maxi = -99999999\n for i in res:\n maxi = max(maxi, sum(i))\n return maxi", "def maxLevelSum(root):\n q = []\n q.append(root)\n ans = -9999999\n while len(q) != 0:\n size = len(q)\n temp = 0\n while size > 0:\n x = q.pop(0)\n temp += x.data\n if x.left != None:\n q.append(x.left)\n if x.right != None:\n q.append(x.right)\n size -= 1\n ans = max(ans, temp)\n return ans"], "starter_code": "def __init__(value):\n", "input_output": {"inputs": ["4\n / \\\n 2 -5\n / \\ / \\\n -1 3 -2 6", "1\n / \\\n 2 3\n / \\ \\\n 4 5 8\n / \\\n 6 7"], "outputs": ["6", "17"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/max-level-sum-in-binary-tree/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "__init__", "task_id": "TACO_lite/205", "example": [[[4, [2, -5], [-1, 3, -2, 6]], [1, [2, 3], [4, 5, null, 8], [null, null, 6, 7]]], ["6", "17"]]} +{"requirement": "Write a function \n\n`titleToNumber(title) or title_to_number(title) or titleToNb title ...`\n\n(depending on the language)\n\nthat given a column title as it appears in an Excel sheet, returns its corresponding column number. All column titles will be uppercase.\n\nExamples:\n```\ntitleTonumber('A') === 1\ntitleTonumber('Z') === 26\ntitleTonumber('AA') === 27\n```", "solutions": ["def title_to_number(title):\n ret = 0\n for i in title:\n ret = ret * 26 + ord(i) - 64\n return ret", "def title_to_number(title):\n return sum(((ord(c) - 64) * 26 ** i for (i, c) in enumerate(title[::-1])))", "def title_to_number(title):\n offset = ord('A') - 1\n radix = 26\n val = 0\n for i in title:\n val = radix * val + (ord(i) - offset)\n return val", "from string import ascii_uppercase\n\ndef title_to_number(t):\n return 0 if len(t) == 0 else (ascii_uppercase.index(t[0]) + 1) * 26 ** (len(t) - 1) + title_to_number(t[1:])", "from string import ascii_uppercase\nfrom functools import reduce\nval = {c: i + 1 for (i, c) in enumerate(ascii_uppercase)}\nadd = lambda x, y: 26 * x + y\n\ndef title_to_number(title):\n return reduce(add, map(val.get, title))", "from string import ascii_uppercase as letters\n\ndef title_to_number(title):\n transfer = list(title)[::-1]\n result = 0\n for (i, char) in enumerate(transfer):\n result += (letters.find(char) + 1) * 26 ** i\n return result", "title_to_number = lambda a: 0 if a == '' else 1 + ord(a[-1]) - ord('A') + 26 * title_to_number(a[:-1])", "from string import ascii_uppercase as a\n\ndef title_to_number(title):\n return sum(((a.index(x) + 1) * 26 ** i for (i, x) in enumerate(title[::-1])))"], "starter_code": "def title_to_number(title):\n", "input_output": {"fn_name": "title_to_number", "inputs": [["A"], ["Z"], ["AA"], ["AZ"], ["BA"], ["CODEWARS"], ["ZZZTOP"], ["OYAJI"], ["LONELINESS"], ["UNFORGIVABLE"]], "outputs": [[1], [26], [27], [52], [53], [28779382963], [321268054], [7294985], [68400586976949], [79089429845931757]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/55ee3ebff71e82a30000006a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "title_to_number", "task_id": "TACO_lite/265", "example": [[["A"], ["Z"], ["AA"]], ["1", "26", "27"]]} +{"requirement": "Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second.\n\nFor instance, take the strings \"fatigue\" and \"tiguefa\". In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned.\nIf the second string isn't a valid rotation of the first string, the method returns -1. \n\nExamples:\n```\n\"coffee\", \"eecoff\" => 2\n\"eecoff\", \"coffee\" => 4\n\"moose\", \"Moose\" => -1\n\"isn't\", \"'tisn\" => 2\n\"Esham\", \"Esham\" => 0\n\"dog\", \"god\" => -1\n```\n\nFor Swift, your function should return an Int?. So rather than returning -1 when the second string isn't a valid rotation of the first, return nil.", "solutions": ["def shifted_diff(first, second):\n return (second + second).find(first) if len(first) == len(second) else -1", "def shifted_diff(first, second):\n for i in range(len(first)):\n if first == second[i:] + second[:i]:\n return i\n return -1", "def shifted_diff(f, s):\n try:\n ix = s.index(f[0])\n return ix if f == s[ix:] + s[:ix] else -1\n except:\n return -1", "def xx(s):\n return s[1:] + s[0]\n\ndef shifted_diff(a, b):\n if a == b:\n return 0\n elif sorted(a) == sorted(b):\n n = 0\n for i in range(len(b)):\n n += 1\n b = xx(b)\n if b == a:\n return n\n return -1", "def shifted_diff(first, second):\n if len(first) != len(second):\n return -1\n return (second * 2).find(first)", "from collections import deque\n\ndef shifted_diff(f, s):\n (d1, d2) = (deque(f), deque(s))\n l = [d2.rotate(-1) or d1 == d2 for i in range(len(f))]\n return (l.index(True) + 1) % len(l) if True in l else -1"], "starter_code": "def shifted_diff(first, second):\n", "input_output": {"fn_name": "shifted_diff", "inputs": [["fatigue", "tiguefa"], ["hoop", "pooh"], ["eecoff", "coffee"], ["Moose", "moose"], ["isn't", "'tisn"], ["Esham", "Esham"], [" ", " "], ["dog", "god"], [" ", " "], ["doomhouse", "hoodmouse"], ["123456789!@#$%^&*( )qwerty", "9!@#$%^&*( )qwerty12345678"]], "outputs": [[5], [-1], [4], [-1], [2], [0], [0], [-1], [-1], [-1], [18]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5596f6e9529e9ab6fb000014", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "shifted_diff", "task_id": "TACO_lite/197", "example": [[["coffee", "eecoff"], ["eecoff", "coffee"], ["moose", "Moose"], ["isn't", "'tisn"], ["Esham", "Esham"], ["dog", "god"]], ["2", "4", "-1", "2", "0", "-1"]]} +{"requirement": "Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.\n \nExample 1:\nInput:\nN = 3 \nA[] = {1,2,3} \nOutput:\n-1\nExplanation:\nSince, each element in \n{1,2,3} appears only once so there \nis no majority element.\nExample 2:\nInput:\nN = 5 \nA[] = {3,1,3,3,2} \nOutput:\n3\nExplanation:\nSince, 3 is present more\nthan N/2 times, so it is \nthe majority element.\nYour Task:\nThe task is to complete the function majorityElement() which returns the majority element in the array. If no majority exists, return -1.\n \nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\n \nConstraints:\n1 ≤ N ≤ 10^{7}\n0 ≤ A_{i} ≤ 10^{6}", "solutions": ["def majorityelement(A, N):\n flag = True\n re = N // 2\n dict = {}\n if N == 1:\n return A[0]\n else:\n for i in A:\n if i in dict:\n dict[i] += 1\n else:\n dict[i] = 0\n for i in dict:\n if dict[i] >= re:\n flag = False\n return i\n if flag == True:\n return -1", "def majorityelement(A, N):\n if N == 1:\n return A[0]\n else:\n my_list = A\n size = N / 2\n element_count = {}\n for element in my_list:\n if element in element_count:\n element_count[element] += 1\n else:\n element_count[element] = 1\n max_count = max(element_count.values())\n if max_count == 1 or max_count <= size:\n return -1\n else:\n max_elements = [element for (element, count) in element_count.items() if count == max_count]\n for maxelements in max_elements:\n return maxelements", "from collections import defaultdict\n\ndef majorityelement(A, N):\n value = -1\n count = 0\n for a in A:\n if count == 0:\n value = a\n count += 1\n elif a == value:\n count += 1\n else:\n count -= 1\n return value if A.count(value) > N / 2 else -1", "from collections import defaultdict\n\ndef majorityelement(A, N):\n dic = defaultdict(int)\n for a in A:\n dic[a] += 1\n if dic[a] > N / 2:\n return a\n return -1", "def majorityelement(A, N):\n c = N / 2\n dict = {}\n if N == 1:\n return A[0]\n for x in A:\n if x not in dict:\n dict[x] = 1\n elif x in dict:\n dict[x] += 1\n if dict[x] > c:\n return x\n return -1", "from collections import Counter, defaultdict\n\ndef majorityelement(arr, N):\n c = Counter(arr)\n (v, cnt) = c.most_common(1)[0]\n if cnt > len(arr) // 2:\n return v\n return -1", "def majorityelement(array, n):\n (result, count) = (array[0], 1)\n for data in array[1:]:\n count = count + 1 if data == result else count - 1\n if count == 0:\n (result, count) = (data, 1)\n count = 0\n for data in array:\n if data == result:\n count += 1\n if not count > n // 2:\n result = -1\n return result", "def majorityelement(A, N):\n half = N // 2\n hash = {}\n for ele in A:\n if ele not in hash:\n hash[ele] = 1\n else:\n hash[ele] += 1\n for (k, v) in hash.items():\n if v > half:\n return k\n return -1", "def majorityelement(A, N):\n mp = {}\n for i in range(N):\n if A[i] in mp:\n mp[A[i]] += 1\n else:\n mp[A[i]] = 1\n for i in mp.keys():\n if mp[i] > N // 2:\n return i\n return -1", "from collections import Counter\n\ndef majorityelement(A, N):\n k = Counter(A)\n if N == 1:\n return A[0]\n for i in A:\n if k[i] > N // 2:\n return i\n return -1", "def majorityelement(A, N):\n elem = 0\n count = 0\n maxcount = 0\n for ele in A:\n if count == 0:\n elem = ele\n if ele == elem:\n count += 1\n else:\n count -= 1\n for val in A:\n if val == elem:\n maxcount += 1\n return elem if maxcount > N // 2 else -1", "def majorityelement(A, N):\n elem = A[0]\n count = 1\n maxCount = 0\n for idx in range(1, N):\n if A[idx] == elem:\n count += 1\n elif count == 0:\n elem = A[idx]\n count = 1\n else:\n count -= 1\n for val in A:\n if val == elem:\n maxCount += 1\n return elem if maxCount > N // 2 else -1", "def majorityelement(A, N):\n hashmap = {}\n ele = N // 2\n for i in A:\n if i in hashmap:\n hashmap[i] += 1\n else:\n hashmap[i] = 1\n if hashmap[i] > ele:\n return i\n return -1", "def findCandidate(A):\n maj_index = 0\n count = 1\n for i in range(len(A)):\n if A[maj_index] == A[i]:\n count += 1\n else:\n count -= 1\n if count == 0:\n maj_index = i\n count = 1\n return A[maj_index]\n\ndef isMajority(A, cand):\n count = 0\n for i in range(len(A)):\n if A[i] == cand:\n count += 1\n if count > len(A) / 2:\n return True\n else:\n return False\n\ndef majorityelement(A, N):\n cand = self.findCandidate(A)\n if self.isMajority(A, cand) == True:\n return cand\n else:\n return -1", "def majorityelement(A, N):\n d = dict()\n for element in A:\n if element in d:\n d[element] += 1\n else:\n d[element] = d.get(element, 0) + 1\n for element in d:\n if d[element] > N / 2:\n return element\n return -1", "def majorityelement(arr, n):\n d = {}\n m = -1\n ans = -1\n if n == 1:\n return arr[0]\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n for (i, j) in d.items():\n if j > n // 2:\n return i\n return -1", "def majorityelement(A, N):\n maj = 0\n count = 0\n for i in range(N):\n if count == 0:\n maj = A[i]\n if maj == A[i]:\n count += 1\n else:\n count -= 1\n count = 0\n for i in range(N):\n if maj == A[i]:\n count += 1\n if count > N / 2:\n return maj\n return -1", "def majorityelement(A, N):\n count = 0\n num = 0\n for i in range(N):\n if count == 0:\n num = A[i]\n count += 1\n elif num == A[i]:\n count += 1\n else:\n count -= 1\n c = 0\n for i in range(N):\n if A[i] == num:\n c += 1\n if c > N // 2:\n return num\n else:\n return -1", "def majorityelement(A, N):\n dict1 = {}\n maj = -1\n majVal = -1\n if N == 1:\n return A[0]\n for i in range(N):\n if A[i] in dict1:\n dict1[A[i]] += 1\n else:\n dict1[A[i]] = 1\n for key in dict1:\n if dict1[key] > maj:\n maj = dict1[key]\n majVal = key\n if maj > N // 2:\n return majVal\n else:\n return -1", "def majorityelement(a, N):\n d = {}\n for n in a:\n if n in d:\n d[n] = d[n] + 1\n else:\n d[n] = 1\n for n in a:\n if d[n] > N / 2:\n return n\n return -1", "def majorityelement(A, N):\n max = A[0]\n occur = 1\n for i in range(1, len(A)):\n if occur == 0:\n occur += 1\n max = A[i]\n elif A[i] == max:\n occur += 1\n else:\n occur -= 1\n if A.count(max) > N / 2:\n return max\n return -1", "def majorityelement(A, N):\n dic = {}\n for i in A:\n dic[i] = 1 + dic.get(i, 0)\n for (k, v) in dic.items():\n if v > N // 2:\n return k\n return -1", "def majorityelement(A, N):\n n = len(A)\n freq = {}\n for num in A:\n freq[num] = freq.get(num, 0) + 1\n for (num, count) in freq.items():\n if count > n // 2:\n return num\n return -1", "from collections import Counter\n\ndef majorityelement(A, N):\n f = Counter(A)\n for (i, j) in f.items():\n if j > N // 2:\n return i\n return -1", "def majorityelement(A, N):\n count = {}\n for a in A:\n if a in count:\n count[a] = count[a] + 1\n else:\n count[a] = 1\n for (k, v) in count.items():\n if v > N / 2:\n return k\n return -1", "def majorityelement(A, N):\n count = 1\n i = 1\n candidate = A[0]\n while i < len(A):\n if candidate == A[i]:\n count += 1\n else:\n count -= 1\n if count == 0:\n candidate = A[i]\n count = 1\n i += 1\n count = 0\n for ele in A:\n if candidate == ele:\n count += 1\n if count > N // 2:\n return candidate\n return -1", "def majorityelement(A, N):\n c = 0\n majr = 0\n for i in range(0, N):\n if c == 0:\n majr = i\n c = 1\n elif A[majr] == A[i]:\n c = c + 1\n else:\n c = c - 1\n C = 0\n for i in range(len(A)):\n if A[majr] == A[i]:\n c = c + 1\n if c > N // 2:\n return A[majr]\n return -1", "def majorityelement(A, N):\n count = 0\n candidate = None\n for i in range(N):\n if count == 0:\n candidate = A[i]\n count = 1\n elif A[i] == candidate:\n count += 1\n else:\n count -= 1\n count = 0\n for i in range(N):\n if A[i] == candidate:\n count += 1\n if count > N / 2:\n return candidate\n else:\n return -1", "from collections import Counter\n\ndef majorityelement(A, N):\n m = {}\n for n in A:\n m[n] = m.get(n, 0) + 1\n if m[n] > N // 2:\n return n\n return -1", "def majorityelement(A, N):\n majcnt = 0\n majele = -1\n for i in A:\n if majcnt == 0:\n majele = i\n majcnt = 1\n elif majele == i:\n majcnt += 1\n else:\n majcnt -= 1\n cnt = 0\n for i in A:\n if i == majele:\n cnt += 1\n if cnt > N // 2:\n return majele\n else:\n return -1", "def majorityelement(A, N):\n mapp = {}\n mid = N // 2\n for i in range(N):\n if A[i] in mapp:\n mapp[A[i]] += 1\n else:\n mapp[A[i]] = 1\n for k in mapp.keys():\n if mapp[k] > mid:\n return k\n return -1", "def possible(l, n):\n val = l[0]\n cnt = 1\n for i in range(1, n):\n if l[i] == val:\n cnt += 1\n else:\n cnt -= 1\n if cnt == 0:\n val = l[i]\n cnt = 1\n return val\n\ndef majorityelement(A, N):\n val = self.possible(A, N)\n return val if A.count(val) > N // 2 else -1", "def majorityelement(A, N):\n d = {}\n count = 0\n for i in A:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for (items, value) in d.items():\n if value > N / 2:\n return items\n return -1", "def majorityelement(A, N):\n element = None\n counter = 0\n for i in range(N):\n if counter == 0:\n counter = 1\n element = A[i]\n elif element == A[i]:\n counter += 1\n else:\n counter -= 1\n new_count = 0\n for i in range(N):\n if A[i] == element:\n new_count += 1\n if new_count > N // 2:\n return element\n else:\n return -1", "def majorityelement(A, N):\n freq_dict = {}\n for i in A:\n if i in freq_dict:\n freq_dict[i] += 1\n else:\n freq_dict[i] = 1\n for (i, count) in freq_dict.items():\n if count > N // 2:\n return i\n return -1", "def majorityelement(A, N):\n if N == 1:\n return A[0]\n Map = {}\n for ele in A:\n if ele in Map:\n Map[ele] += 1\n if Map[ele] > N / 2:\n return ele\n else:\n Map[ele] = 1\n return -1", "def majorityelement(A, N):\n d = {}\n for e in A:\n if e in d:\n d[e] = d[e] + 1\n else:\n d[e] = 1\n if d[e] > N / 2:\n return e\n return -1", "from collections import Counter\n\ndef majorityelement(A, N):\n counter = Counter(A)\n for (num, freq) in counter.items():\n if freq > N / 2:\n return num\n return -1", "def majorityelement(A, N):\n d = {}\n f = 0\n ans = 0\n for ele in A:\n if ele in d.keys():\n d[ele] += 1\n else:\n d[ele] = 1\n for keys in d.keys():\n if d[keys] > N / 2:\n ans = keys\n f = 0\n break\n else:\n f = 1\n if f == 0:\n return ans\n else:\n return -1", "def majorityelement(A, n):\n dic = {}\n ans = -1\n for i in A:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n for (key, value) in dic.items():\n if value > n // 2:\n ans = key\n return ans", "def majorityelement(A, N):\n c = {}\n for i in A:\n c[i] = c.get(i, 0) + 1\n if c[i] > N / 2:\n return i\n return -1", "def majorityelement(A, N):\n count_dict = {}\n for elem in A:\n count_dict[elem] = count_dict.get(elem, 0) + 1\n if count_dict[elem] > N / 2:\n return elem\n return -1", "def find_majority_candidate(A, N):\n maj_index = 0\n count = 1\n for i in range(len(A)):\n if A[maj_index] == A[i]:\n count += 1\n else:\n count -= 1\n if count == 0:\n maj_index = i\n count = 1\n return A[maj_index]\n\ndef is_majority_candidate(A, N, a):\n n = N // 2\n count = 0\n for i in range(N):\n if A[i] == a:\n count += 1\n if count > n:\n return True\n return False\n\ndef majorityelement(A, N):\n a = self.find_majority_candidate(A, N)\n f = self.is_majority_candidate(A, N, a)\n if f:\n return a\n return -1", "def majorityelement(A, N):\n A.sort()\n n = N // 2\n i = 0\n while i < N:\n j = i\n if i + 1 < N and A[i] == A[i + 1]:\n while i + 1 < N and A[i] == A[i + 1]:\n i = i + 1\n k = i\n if k - j + 1 > n:\n return A[i]\n i = i + 1\n return -1", "def majorityelement(A, N):\n majority = True\n dic = {}\n for i in range(N):\n if A[i] in dic:\n dic[A[i]] += 1\n else:\n dic[A[i]] = 1\n for key in dic:\n if dic[key] > N // 2:\n return key\n return -1", "def majorityelement(A, N):\n temp = N // 2\n hashed = {}\n for i in A:\n hashed[i] = 1 + hashed.get(i, 0)\n for i in hashed:\n if hashed[i] > temp:\n return i\n return -1", "from collections import Counter\n\ndef majorityelement(A, N):\n A = Counter(A)\n max = N // 2\n v = 0\n for (i, j) in A.items():\n if j > max:\n max = j\n v = i\n if v == 0:\n return -1\n else:\n return v", "from collections import defaultdict\n\ndef majorityelement(A, N):\n count = 0\n maxcount = 0\n for i in range(0, N):\n if count == 0:\n count = 1\n ele = A[i]\n elif ele == A[i]:\n count += 1\n else:\n count -= 1\n for val in A:\n if val == ele:\n maxcount += 1\n return ele if maxcount > N // 2 else -1", "from collections import defaultdict\n\ndef majorityelement(A, N):\n hmap = defaultdict(int)\n for i in range(0, N):\n if A[i] not in hmap:\n hmap[A[i]] = 1\n else:\n hmap[A[i]] += 1\n for (k, v) in hmap.items():\n if v > N // 2:\n return k\n return -1", "def majorityelement(A, N):\n dict_ = dict()\n for number in A:\n dict_[number] = dict_.get(number, 0) + 1\n for number in A:\n if dict_[number] > N // 2:\n return number\n return -1", "from collections import Counter\n\ndef majorityelement(A, N):\n counterA = Counter(A)\n rep = N // 2\n for (i, j) in counterA.items():\n if j > rep:\n return i\n if rep + 1 not in counterA.values():\n return -1", "def majorityelement(A, N):\n dict = {}\n for num in A:\n if num not in dict:\n dict[num] = 1\n else:\n dict[num] += 1\n maxCount = max(dict, key=dict.get)\n if dict[maxCount] > N // 2:\n return maxCount\n else:\n return -1", "from collections import Counter\n\ndef majorityelement(A, N):\n counterA = Counter(A)\n target = N // 2\n for (indx, val) in counterA.items():\n if val > target:\n return indx\n return -1", "def majorityelement(A, N):\n count = 1\n maj_ele = A[0]\n for i in range(1, N):\n num = A[i]\n if num == maj_ele:\n count += 1\n else:\n count -= 1\n if count == 0:\n count = 1\n maj_ele = num\n total = 0\n for num in A:\n if num == maj_ele:\n total += 1\n if total > int(N / 2):\n return maj_ele\n return -1", "def majorityelement(A, N):\n A.sort()\n mid = A[N // 2]\n if A.count(mid) > N // 2:\n return mid\n else:\n return -1", "def majorityelement(A, N):\n hashmap = {}\n for i in A:\n hashmap[i] = 1 + hashmap.get(i, 0)\n for (key, value) in hashmap.items():\n if value > N // 2:\n return key\n else:\n return -1", "def majorityelement(a, n):\n count = 0\n b = 0\n for i in range(0, n):\n if count == 0:\n count = 1\n b = a[i]\n elif a[i] == b:\n count += 1\n else:\n count -= 1\n count1 = 0\n for i in range(0, n - 1):\n if a[i] == b:\n count += 1\n if count > n // 2:\n return b\n return -1", "def majorityelement(A, N):\n d = {}\n for i in range(N):\n if N == 1:\n return A[0]\n if A[i] not in d:\n d[A[i]] = 1\n else:\n d[A[i]] += 1\n if d[A[i]] > N / 2 and d[A[i]] != 1:\n return A[i]\n return -1", "def majorityelement(A, N):\n A.sort()\n x = 0\n x1 = A[0]\n for i in A:\n if i == x1:\n x = x + 1\n if x > N // 2:\n return i\n else:\n x1 = i\n x = 1\n return -1", "def majorityelement(A, N):\n lis = {}\n x = N // 2\n for i in A:\n if i in lis:\n lis[i] = lis[i] + 1\n else:\n lis[i] = 1\n if lis[i] > x:\n return i\n return -1", "def majorityelement(A, N):\n (m1, c1) = (None, 0)\n for i in A:\n if i == m1:\n c1 += 1\n elif c1 == 0:\n m1 = i\n c1 = 1\n else:\n c1 -= 1\n ans = -1\n if A.count(m1) > N / 2:\n ans = m1\n return ans", "def majorityelement(A, N):\n d = {}\n ans = -1\n for i in range(N):\n if A[i] not in d:\n d[A[i]] = 1\n else:\n d[A[i]] = d[A[i]] + 1\n for k in d:\n if d[k] > N / 2:\n ans = k\n break\n return ans", "def majorityelement(A, N):\n count = {}\n (res, maxcount) = (-1, 0)\n for n in A:\n count[n] = 1 + count.get(n, 0)\n res = n if count[n] > maxcount else res\n maxcount = max(maxcount, count[n])\n return res if maxcount > N / 2 else -1", "def majorityelement(A, N):\n dic = {}\n ans = -1\n maxi = 0\n if N == 1:\n return A[0]\n for ele in A:\n if ele in dic:\n dic[ele] += 1\n else:\n dic[ele] = 1\n for x in dic:\n if dic[x] > N // 2:\n maxi = dic[x]\n ans = x\n if maxi == 1:\n return -1\n else:\n return ans", "def majorityelement(A, N):\n cnt = 0\n cur = 0\n for i in range(N):\n if cnt == 0:\n cur = A[i]\n cnt = 1\n elif cur == A[i]:\n cnt += 1\n else:\n cnt -= 1\n c = 0\n for el in A:\n if el == cur:\n c += 1\n return cur if c > N // 2 else -1", "from collections import Counter\n\ndef majorityelement(A, N):\n k = N // 2\n dic = Counter(A)\n for (key, v) in dic.items():\n if dic[key] > k:\n return key\n return -1", "def majorityelement(A, N):\n if N == 1:\n return A[0]\n A.sort()\n count = 1\n curr = A[0]\n for idx in range(1, N):\n if A[idx] == curr:\n count += 1\n else:\n count = 1\n curr = A[idx]\n if count > N / 2:\n return curr\n return -1", "def majorityelement(A, N):\n s = N // 2\n max = -1\n ans = -1\n if N == 1:\n return A[0]\n d = dict()\n for i in A:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for i in d:\n if d[i] > N // 2:\n max = 1\n ans = i\n if max == -1:\n return -1\n else:\n return ans", "from collections import *\n\ndef majorityelement(A, N):\n dic = Counter(A)\n maj = 0\n num = 0\n for (key, val) in dic.items():\n if val > maj:\n maj = val\n num = key\n if maj > N / 2:\n return num\n return -1", "from collections import defaultdict\nimport math\n\ndef majorityelement(A, N):\n d = defaultdict(int)\n for i in A:\n d[i] += 1\n for i in d:\n if d[i] > N / 2:\n return i\n return -1", "def majorityelement(A, N):\n freq = {}\n for i in A:\n if i not in freq:\n freq[i] = 1\n else:\n freq[i] += 1\n for key in freq:\n if freq[key] > N // 2:\n return key\n return -1"], "starter_code": "def majorityelement(A, N):\n", "input_output": {"inputs": ["N = 3 \r\nA[] = {1,2,3}", "N = 5 \r\nA[] = {3,1,3,3,2}"], "outputs": ["-1", "3"]}, "difficulty": "MEDIUM", "raw_tags": ["Searching", "Algorithms", "Greedy", "Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Complete search", "Data structures", "Greedy algorithms"], "skill_types": ["Complete search", "Data structures", "Greedy algorithms"], "url": "https://practice.geeksforgeeks.org/problems/majority-element-1587115620/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "majorityelement", "task_id": "TACO_lite/171", "example": [[[3, [1, 2, 3]], [5, [3, 1, 3, 3, 2]]], ["-1", "3"]]} +{"requirement": "The palindromic number `595` is interesting because it can be written as the sum of consecutive squares: `6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2 = 595`.\n\nThere are exactly eleven palindromes below one-thousand that can be written as consecutive square sums. Note that `1 = 0^2 + 1^2` has not been included as this problem is concerned with the squares of positive integers.\n\nGiven an input `n`, find the count of all the numbers less than `n` that are both palindromic and can be written as the sum of consecutive squares.\n\nFor instance: `values(1000) = 11`. See test examples for more cases. \n\nGood luck!\n\nThis Kata is borrowed from [Project Euler #125](https://projecteuler.net/problem=125)\n\nIf you like this Kata, please try:\n\n[Fixed length palindromes](https://www.codewars.com/kata/59f0ee47a5e12962cb0000bf)\n\n[Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)", "solutions": ["(l, m, p) = ([1], 10 ** 7, [])\nfor n in range(2, int(m ** 0.5) + 1):\n l = [n * n + j for j in [0] + l]\n p += [int(k) for k in map(str, l[1:]) if k == k[::-1]]\np = sorted(set(p))\nfrom bisect import bisect_left\n\ndef values(n):\n return bisect_left(p, n)", "def values(n):\n pal = set()\n for i in range(1, int(n ** 0.5)):\n sos = i * i\n while sos < n:\n i += 1\n sos += i * i\n if str(sos) == str(sos)[::-1] and sos < n:\n pal.add(sos)\n return len(pal)", "from bisect import bisect\nis_pal = lambda s: s == s[::-1]\n(N, temp) = (2500, set())\nfor x in range(1, N):\n val = x ** 2\n for y in range(x + 1, N):\n val += y ** 2\n if val not in temp and is_pal(str(val)):\n temp.add(val)\nresult = sorted(temp)\n\ndef values(n):\n return bisect(result, n)", "sumSquaresToN = lambda n: n * (n + 1) * (2 * n + 1) // 6\nmemo = set()\n\ndef values(n):\n lastMax = max(memo) if memo else 0\n if lastMax >= n:\n return sum((x < n for x in memo))\n top = int((1 + (1 + 2 * (n - 1)) ** 0.5) // 2)\n for a in range(top, 1, -1):\n va = sumSquaresToN(a)\n if va <= lastMax:\n break\n for b in range(a - 2, -1, -1):\n v = va - sumSquaresToN(b)\n if v >= n:\n break\n if v == int(str(v)[::-1]):\n memo.add(v)\n return len(memo)", "found = set([5, 55, 77, 181, 313, 434, 505, 545, 595, 636, 818, 1001, 1111, 1441, 1771, 4334, 6446, 17371, 17871, 19691, 21712, 41214, 42924, 44444, 46564, 51015, 65756, 81818, 97679, 99199, 108801, 127721, 137731, 138831, 139931, 148841, 161161, 166661, 171171, 188881, 191191, 363363, 435534, 444444, 485584, 494494, 525525, 554455, 554455, 629926, 635536, 646646, 656656, 904409, 923329, 944449, 964469, 972279, 981189, 982289, 1077701, 1224221, 1365631, 1681861, 1690961, 1949491, 1972791, 1992991, 2176712, 2904092, 3015103, 3162613, 3187813, 3242423, 3628263, 4211124, 4338334, 4424244, 4776774, 5090905, 5258525, 5276725, 5367635, 5479745, 5536355, 5588855, 5603065, 5718175, 5824285, 6106016, 6277726, 6523256, 6546456, 6780876, 6831386, 6843486, 6844486, 7355537, 8424248, 9051509, 9072709, 9105019, 9313139, 9334339, 9343439, 9343439, 9435349, 9563659, 9793979, 9814189, 9838389, 9940499])\n\ndef values(n):\n return sum((i < n for i in found))", "def values(high):\n s = set()\n num = 1\n while num * num < high:\n temp = num + 1\n total = num * num + temp * temp\n while total < high:\n if str(total) == str(total)[::-1]:\n s.add(total)\n temp += 1\n total += temp * temp\n num += 1\n return len(s)", "def values(limit):\n palindromes = set()\n for sequence_item in range(1, int(limit ** 0.5)):\n squares_sum = sequence_item ** 2\n while squares_sum < limit:\n sequence_item += 1\n squares_sum += sequence_item ** 2\n if str(squares_sum) == str(squares_sum)[::-1] and squares_sum < limit:\n palindromes.add(squares_sum)\n return len(palindromes)", "def values(n):\n p = set()\n for i in range(1, int(n ** 0.5)):\n q = i * i\n while q < n:\n i = i + 1\n q = q + i * i\n if str(q) == str(q)[::-1] and q < n:\n p.add(q)\n return len(p)"], "starter_code": "def values(n):\n", "input_output": {"fn_name": "values", "inputs": [[100], [200], [300], [400], [1000], [100000], [1000000], [5000000], [9000000], [10000000]], "outputs": [[3], [4], [4], [5], [11], [30], [59], [78], [98], [110]]}, "difficulty": "EASY", "raw_tags": ["Performance", "Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/599b1a4a3c5292b4cc0000d5", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "values", "task_id": "TACO_lite/249", "example": [[[1000]], ["11"]]} +{"requirement": "Given a string str, a partitioning of the string is a palindrome partitioning if every sub-string of the partition is a palindrome. Determine the fewest cuts needed for palindrome partitioning of the given string.\nExample 1:\nInput: str = \"ababbbabbababa\"\nOutput: 3\nExplaination: After 3 partitioning substrings \nare \"a\", \"babbbab\", \"b\", \"ababa\".\nExample 2:\nInput: str = \"aaabba\"\nOutput: 1\nExplaination: The substrings after 1\npartitioning are \"aa\" and \"abba\".\nYour Task:\nYou do not need to read input or print anything, Your task is to complete the function palindromicPartition() which takes the string str as the input parameter and returns the minimum number of partitions required.\nExpected Time Complexity: O(n*n) [n is the length of the string str]\nExpected Auxiliary Space: O(n*n)\nConstraints:\n1 ≤ length of str ≤ 500", "solutions": ["def palindromicpartition(s):\n dp = [[-1] * (len(s) + 1) for _ in range(len(s) + 1)]\n\n def dfs(s, i, j):\n if dp[i][j] != -1:\n return dp[i][j]\n if i > j:\n return 0\n if self.isPal(s, i, j):\n return 0\n mx = len(s)\n for k in range(i, j):\n if self.isPal(s, i, k):\n t = dfs(s, k + 1, j) + 1\n mx = min(mx, t)\n dp[i][j] = mx\n return dp[i][j]\n return dfs(s, 0, len(s) - 1)\n\ndef isPal(s, start, end):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True", "def palindromicpartition(s):\n n = len(s)\n dp = [[-1 for i in range(n + 2)] for j in range(n + 2)]\n\n def ispal(st):\n return st == st[::-1]\n\n def solve(i, j):\n if i >= j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if ispal(s[i:j + 1]):\n return 0\n mn = int(1000000000.0)\n for k in range(i, j):\n if ispal(s[i:k + 1]):\n temp = solve(k + 1, j) + 1\n mn = min(mn, temp)\n dp[i][j] = mn\n return mn\n x = solve(0, n - 1)\n return x", "def palindromicpartition(a):\n cut = [0 for i in range(len(a))]\n palindrome = [[False for i in range(len(a))] for j in range(len(a))]\n for i in range(len(a)):\n minCut = i\n for j in range(i + 1):\n if a[i] == a[j] and (i - j < 2 or palindrome[j + 1][i - 1]):\n palindrome[j][i] = True\n minCut = min(minCut, 0 if j == 0 else cut[j - 1] + 1)\n cut[i] = minCut\n return cut[len(a) - 1]", "import numpy as np\nimport sys\n\ndef dp_sol(string):\n len_s = len(string)\n dp = np.array([[0] * len_s] * len_s)\n for i in range(len_s):\n for j in range(i, -1, -1):\n if i == j:\n dp[j][i] = 0\n if i == j + 1:\n if string[i] == string[j]:\n dp[j][i] = 0\n else:\n dp[j][i] = 1\n else:\n start = j\n end = i\n while start < end and string[start] == string[end]:\n start = start + 1\n end = end - 1\n if start >= end:\n dp[j][i] = 0\n else:\n temp = sys.maxsize\n for k in range(j, i):\n temp = min(temp, 1 + dp[j][k] + dp[k + 1][i])\n dp[j][i] = temp\n return dp[0][len_s - 1]\n\ndef dp_sol2(string):\n len_s = len(string)\n dp = np.array([[False] * len_s] * len_s)\n for i in range(len_s):\n for j in range(i + 1):\n if i == j:\n dp[j][i] = True\n elif j + 1 == i and string[i] == string[j]:\n dp[j][i] = True\n elif string[j] == string[i] and dp[j + 1][i - 1]:\n dp[j][i] = True\n p = np.array([len_s] * len_s)\n for i in range(len_s):\n if dp[0][i] == True:\n p[i] = 0\n else:\n for j in range(i):\n if dp[j + 1][i]:\n p[i] = min(p[i], p[j] + 1)\n return p[len_s - 1]\n\ndef palindromicpartition(string):\n return self.dp_sol2(string)", "def isPalindrome(string, a, b):\n while a <= b:\n if string[a] != string[b]:\n return False\n a += 1\n b -= 1\n return True\n\ndef palindromicpartition(string):\n n = len(string)\n dp = [-1 for _ in range(n + 1)]\n dp[n] = 0\n for i in range(n - 1, -1, -1):\n minCuts = float('inf')\n for j in range(i, n):\n if self.isPalindrome(string, i, j):\n minCuts = min(minCuts, 1 + dp[j + 1])\n dp[i] = minCuts\n return dp[0] - 1", "def helper(string, i, n, dp, ans):\n ans[0] = 0\n for j in range(1, n):\n if dp[0][j]:\n ans[j] = 0\n else:\n temp = int(1000000000.0)\n for i in range(j, 0, -1):\n if dp[i][j]:\n temp = min(temp, ans[i - 1])\n ans[j] = temp + 1\n\ndef palindromicpartition(string):\n n = len(string)\n dp = [[False for _ in range(n)] for _ in range(n)]\n for j in range(n):\n for i in range(n):\n if j - i == 0 and i == j:\n dp[i][j] = True\n elif j - i == 1 and string[i] == string[j]:\n dp[i][j] = True\n elif j - i >= 2 and string[i] == string[j] and (dp[i + 1][j - 1] == True):\n dp[i][j] = True\n ans = [0] * n\n helper(string, 0, n, dp, ans)\n return ans[n - 1]", "def palindromicpartition(s):\n n = len(s)\n dp = [[-1 for i in range(0, n + 2)] for j in range(0, n + 2)]\n\n def getAns(i, j):\n if i >= j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if isPal(s, i, j):\n return 0\n mn = int(1000000000.0)\n for k in range(i, j):\n if isPal(s, i, k):\n temp = getAns(k + 1, j) + 1\n mn = min(mn, temp)\n dp[i][j] = mn\n return mn\n\n def isPal(s, start, end):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n return getAns(0, n - 1)", "def palindromicpartition(string):\n n = len(string)\n dp = [-1 for i in range(n)]\n return self.f(0, n, string, dp) - 1\n\ndef f(i, n, string, dp):\n mincost = float('inf')\n if i == n:\n return 0\n if dp[i] != -1:\n return dp[i]\n for j in range(i, n):\n if self.isPalindrome(string, i, j):\n cost = 1 + self.f(j + 1, n, string, dp)\n mincost = min(mincost, cost)\n dp[i] = mincost\n return dp[i]\n\ndef isPalindrome(string, i, j):\n while i < j:\n if string[i] != string[j]:\n return False\n i += 1\n j -= 1\n return True", "def palindromicpartition(string: str) -> int:\n n = len(string)\n P = [[False for _ in range(n)] for _ in range(n)]\n for i in range(n):\n P[i][i] = True\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if L == 2:\n P[i][j] = string[i] == string[j]\n else:\n P[i][j] = string[i] == string[j] and P[i + 1][j - 1]\n cuts = [0] * n\n for i in range(n):\n if P[0][i]:\n cuts[i] = 0\n else:\n cuts[i] = float('inf')\n for j in range(i):\n if P[j + 1][i] and cuts[j] + 1 < cuts[i]:\n cuts[i] = cuts[j] + 1\n return cuts[n - 1]", "def palindromicpartition(string):\n n = len(string)\n dp = [0 for _ in range(n + 1)]\n for i in range(n - 1, -1, -1):\n minCuts = float('inf')\n for j in range(i, n):\n if self.isPalindrome(string[i:j + 1]):\n cuts = 1 + dp[j + 1]\n minCuts = min(cuts, minCuts)\n dp[i] = minCuts\n return dp[0] - 1\n\ndef isPalindrome(x):\n return x == x[::-1]", "def palindromicpartition(string):\n n = len(string)\n P = [[False] * n for _ in range(n)]\n for i in range(n):\n P[i][i] = True\n for i in range(n - 1):\n P[i][i + 1] = string[i] == string[i + 1]\n for l in range(3, n + 1):\n for i in range(n - l + 1):\n j = i + l - 1\n P[i][j] = string[i] == string[j] and P[i + 1][j - 1]\n C = [i for i in range(n)]\n for i in range(n):\n if P[0][i]:\n C[i] = 0\n else:\n for j in range(i):\n if P[j + 1][i]:\n C[i] = min(C[i], C[j] + 1)\n return C[n - 1]", "def palindromicpartition(s):\n n = len(s)\n C = [0] * n\n P = [[False for i in range(n)] for i in range(n)]\n for i in range(n):\n P[i][i] = True\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if L == 2:\n P[i][j] = s[i] == s[j]\n else:\n P[i][j] = (s[i] == s[j]) & P[i + 1][j - 1]\n for i in range(n):\n if P[0][i]:\n C[i] = 0\n else:\n C[i] = 1 << 32\n for j in range(i):\n if P[j + 1][i] == True and C[j] + 1 < C[i]:\n C[i] = C[j] + 1\n return C[n - 1]", "def __init__():\n self.res = -float('inf')\n\ndef check_palin(x):\n n = len(x)\n for i in range(n // 2):\n if x[i] != x[-i - 1]:\n return False\n return True\n\ndef solve(i, j, st, dp):\n if i >= j:\n return 0\n if self.check_palin(st[i:j + 1]):\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n min_cut = float('inf')\n for ind in range(i, j):\n if self.check_palin(st[i:ind + 1]):\n x = self.solve(ind + 1, j, st, dp) + 1\n min_cut = min(min_cut, x)\n dp[i][j] = min_cut\n return dp[i][j]\n\ndef palindromicpartition(string):\n n = len(string)\n dp = [[-1 for i in range(n + 2)] for j in range(n + 2)]\n r = self.solve(0, n - 1, string, dp)\n return r", "def palindromicpartition(s):\n n = len(s)\n dp = [[-1 for i in range(n + 2)] for j in range(n + 2)]\n\n def ispal(st):\n return st == st[::-1]\n\n def solve(i, j):\n if i >= j or ispal(s[i:j + 1]):\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n mn = float('inf')\n for k in range(i, j):\n if ispal(s[i:k + 1]):\n temp = solve(k + 1, j) + 1\n mn = min(mn, temp)\n dp[i][j] = mn\n return mn\n x = solve(0, n - 1)\n return x", "def palindromicpartition(string: str) -> int:\n n = len(string)\n dp = [[False] * n for _ in range(n)]\n for i in range(n):\n dp[i][i] = True\n for length in range(2, n + 1):\n for i in range(n - length + 1):\n j = i + length - 1\n if string[i] == string[j] and (length == 2 or dp[i + 1][j - 1]):\n dp[i][j] = True\n cuts = [float('inf')] * n\n for i in range(n):\n if dp[0][i]:\n cuts[i] = 0\n else:\n for j in range(i):\n if dp[j + 1][i]:\n cuts[i] = min(cuts[i], cuts[j] + 1)\n return cuts[n - 1]", "def palindromicpartition(s):\n\n def check(i, j, s):\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n dp = [-1] * len(s)\n\n def f(i, s):\n if i == len(s):\n return 0\n minCnt = 10 ** 9\n if dp[i] != -1:\n return dp[i]\n for j in range(i, len(s)):\n if check(i, j, s):\n cnt = 1 + f(j + 1, s)\n minCnt = min(minCnt, cnt)\n dp[i] = minCnt\n return dp[i]\n return f(0, s) - 1", "def palindromicpartition(string):\n\n def ispal(s):\n return s == s[::-1]\n\n def solve(i, j, string):\n if i >= j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if ispal(string[i:j + 1]):\n return 0\n ans = 10000000000.0\n for k in range(i, j):\n if ispal(string[i:k + 1]):\n temp = 1 + solve(k + 1, j, string)\n ans = min(ans, temp)\n dp[i][j] = ans\n return dp[i][j]\n n = len(string)\n dp = [[-1] * 1001 for i in range(1001)]\n return solve(0, n - 1, string)", "def palindromicpartition(s):\n\n def calc(i):\n if i == len(s):\n return 0\n if dp[i] != -1:\n return dp[i]\n else:\n mxc = float('inf')\n for k in range(i, len(s)):\n if s[i:k + 1] == s[i:k + 1][::-1]:\n cnt = 1 + calc(k + 1)\n mxc = min(mxc, cnt)\n dp[i] = mxc\n return dp[i]\n dp = [-1 for i in range(len(s) + 1)]\n return calc(0) - 1", "def palindromicpartition(string):\n n = len(string)\n if n != 0:\n dp = [[False] * n for i in range(n)]\n for i in range(n):\n dp[i][i] = True\n if i != n - 1:\n if string[i] == string[i + 1]:\n dp[i][i + 1] = True\n for c in range(2, n):\n i = 0\n j = c\n while i < n and j < n:\n if string[i] != string[j]:\n dp[i][j] = False\n else:\n dp[i][j] = dp[i + 1][j - 1]\n i += 1\n j += 1\n mc = [0] * len(string)\n mc[0] = 0\n for i in range(1, n):\n if dp[0][i] == True:\n mc[i] = 0\n else:\n mc[i] = 100000\n for k in range(1, i + 1):\n if dp[k][i]:\n mc[i] = min(mc[i], 1 + mc[k - 1])\n return mc[n - 1]", "def palindromicpartition(string):\n self.isPalindrome = [[False for i in range(len(string))] for j in range(len(string))]\n\n def populateIsPalindromeDP():\n for i in range(0, len(string)):\n for j in range(0, len(string) - i):\n if i == 0:\n self.isPalindrome[j][j] = True\n elif i == 1:\n if string[j] == string[j + 1]:\n self.isPalindrome[j][j + 1] = True\n elif string[j] == string[j + i] and self.isPalindrome[j + 1][j + i - 1]:\n self.isPalindrome[j][j + i] = True\n populateIsPalindromeDP()\n dp = [0 for i in range(len(string) + 1)]\n for i in range(1, len(string) + 1):\n dp[i] = dp[i - 1] + 1\n if self.isPalindrome[0][i - 1]:\n dp[i] = 0\n continue\n for j in range(0, i):\n if self.isPalindrome[j + 1 - 1][i - 1]:\n dp[i] = min(dp[i], 1 + dp[j])\n return dp[-1]", "def ispalindrome(start, end, string):\n while start < end:\n if string[start] != string[end]:\n return False\n start += 1\n end -= 1\n return True\n\ndef palindromicpartition(string):\n n = len(string)\n dp = [0 for i in range(n + 1)]\n\n def rec(idx):\n if idx == n:\n return 0\n if dp[idx] != -1:\n return dp[idx]\n maxi = float('inf')\n (p, np) = (float('inf'), float('inf'))\n for i in range(idx, n):\n if self.ispalindrome(idx, i, string):\n p = 1 + rec(i + 1)\n maxi = min(maxi, p)\n dp[idx] = maxi\n return dp[idx]\n for idx in range(n - 1, -1, -1):\n maxi = float('inf')\n (p, np) = (float('inf'), float('inf'))\n for i in range(idx, n):\n if self.ispalindrome(idx, i, string):\n p = 1 + dp[i + 1]\n maxi = min(maxi, p)\n dp[idx] = maxi\n return dp[0] - 1", "def palindromicpartition(string):\n n = len(string)\n dp = [0] * n\n pal = [[False] * n for _ in range(n)]\n for i in range(n):\n pal[i][i] = True\n for l in range(2, n + 1):\n for i in range(n - l + 1):\n j = i + l - 1\n if l == 2:\n pal[i][j] = string[i] == string[j]\n else:\n pal[i][j] = string[i] == string[j] and pal[i + 1][j - 1]\n for i in range(n):\n min_cuts = i\n for j in range(i + 1):\n if pal[j][i]:\n if j == 0:\n min_cuts = 0\n else:\n min_cuts = min(min_cuts, dp[j - 1] + 1)\n dp[i] = min_cuts\n return dp[n - 1]", "def palindromicpartition(string):\n dp = {}\n return self.helper(string, dp)\n\ndef helper(string, dp):\n n = len(string)\n if n == 0:\n dp[string] = 0\n return 0\n if string in dp:\n return dp[string]\n if string == string[::-1]:\n dp[string] = 0\n return 0\n minimum = float('inf')\n for i in range(1, n + 1):\n if string[:i] == string[:i][::-1]:\n minimum = min(minimum, 1 + self.helper(string[i:], dp))\n dp[string] = minimum\n return dp[string]", "def palindromicpartition(string):\n n = len(string)\n\n def check_pali(s, e):\n (i, j) = (s, e)\n while i < j:\n if string[i] != string[j]:\n return False\n i += 1\n j -= 1\n return True\n maxi = 10 ** 9\n dp = [-1] * n\n\n def find(start):\n if start == n or check_pali(start, n - 1):\n return 0\n if dp[start] != -1:\n return dp[start]\n ans = maxi\n for i in range(start, n):\n if check_pali(start, i):\n ans = min(ans, find(i + 1))\n dp[start] = ans + 1\n return dp[start]\n return find(0)", "def palindromicpartition(string):\n n = len(string)\n dp = [[False for i in range(n)] for _ in range(n)]\n for i in range(n):\n dp[i][i] = True\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if L == 2:\n dp[i][j] = string[i] == string[j]\n elif string[i] == string[j]:\n dp[i][j] = dp[i + 1][j - 1]\n c = [0] * n\n for i in range(1, n):\n if dp[0][i]:\n c[i] = 0\n else:\n c[i] = float('inf')\n for j in range(i):\n if dp[j + 1][i] and c[j] + 1 < c[i]:\n c[i] = c[j] + 1\n return c[n - 1]", "def palindromicpartition(string):\n n = len(string)\n\n def ispalindrome(strs, st, end):\n while st <= end:\n if strs[st] == strs[end]:\n st += 1\n end -= 1\n else:\n return False\n return True\n dp = [-1] * (n + 1)\n\n def findsol(string, i, n):\n if i == n:\n return 0\n if dp[i] != -1:\n return dp[i]\n minval = 999999999\n for x in range(i + 1, n + 1):\n if ispalindrome(string, i, x - 1) == True:\n minval = min(minval, findsol(string, x, n))\n dp[i] = minval + 1\n return minval + 1\n return findsol(string, 0, n) - 1", "def is_palindrome(string, i, j):\n while i < j:\n if string[i] != string[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef palindromicpartition(string):\n n = len(string)\n dp1 = [[False] * n for _ in range(n)]\n dp2 = [0] * n\n for i in range(n):\n dp1[i][i] = True\n for length in range(2, n + 1):\n for start in range(n - length + 1):\n end = start + length - 1\n if length == 2:\n dp1[start][end] = string[start] == string[end]\n else:\n dp1[start][end] = string[start] == string[end] and dp1[start + 1][end - 1]\n for i in range(n):\n if dp1[0][i]:\n dp2[i] = 0\n else:\n dp2[i] = float('inf')\n for j in range(i):\n if dp1[j + 1][i] and dp2[j] + 1 < dp2[i]:\n dp2[i] = dp2[j] + 1\n return dp2[n - 1]", "def palindromicpartition(s):\n N = len(string)\n dp = [[-1 for i in range(N + 2)] for j in range(N + 2)]\n\n def ispalindrome(s1):\n return s1 == s1[::-1]\n\n def solve(i, j):\n if i >= j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if ispalindrome(s[i:j + 1]):\n return 0\n ans = 999999\n for k in range(i, j):\n if ispalindrome(s[i:k + 1]):\n temp = solve(k + 1, j) + 1\n ans = min(ans, temp)\n dp[i][j] = ans\n return ans\n return solve(0, N - 1)", "def check(s):\n if s == s[::-1]:\n return True\n else:\n return False\n\ndef palindromicpartition(string):\n dp = {}\n\n def fun(s, i, j):\n if i >= j:\n return 0\n if check(s[i:j]):\n return 0\n if (i, j) in dp:\n return dp[i, j]\n m = float('inf')\n for k in range(i, j):\n if check(s[i:k + 1]):\n temp = fun(s, k + 1, j) + 1\n m = min(m, temp)\n dp[i, j] = m\n return dp[i, j]\n return fun(string, 0, len(string))", "def palindromicpartition(string):\n n = len(string)\n dp = [0] * (n + 1)\n dp[n] = 0\n for i in reversed(range(n)):\n minCost = float('inf')\n for j in range(i, n):\n cur_string = string[i:j + 1]\n if self.isPalindrome(cur_string):\n cost = 1 + dp[j + 1]\n minCost = min(minCost, cost)\n dp[i] = minCost\n return dp[0] - 1\n\ndef isPalindrome(cur_string):\n left = 0\n right = len(cur_string) - 1\n while left < right:\n if cur_string[left] != cur_string[right]:\n return False\n left += 1\n right -= 1\n return True", "def p(s):\n l = 0\n r = len(s) - 1\n while l < r:\n if s[l] != s[r]:\n return False\n l += 1\n r -= 1\n return True\n\ndef palindromicpartition(string):\n dp = [len(string) + 1 for i in range(len(string) + 1)]\n dp[0] = -1\n for i in range(1, len(string) + 1):\n for j in range(i):\n if self.p(string[j:i]):\n dp[i] = min(dp[i], 1 + dp[j])\n return dp[-1]", "def palindromicpartition(string):\n is_pali = [[False for i in range(len(string))] for j in range(len(string))]\n for k in range(len(string)):\n (i, j) = (0, k)\n while j < len(string):\n if k == 0:\n is_pali[i][j] = True\n elif k == 1:\n if string[i] == string[j]:\n is_pali[i][j] = True\n elif string[i] == string[j] and is_pali[i + 1][j - 1] is True:\n is_pali[i][j] = True\n i += 1\n j += 1\n dp = [float('inf')] * len(string)\n dp[0] = 0\n for i in range(1, len(string)):\n if is_pali[0][i] is True:\n dp[i] = 0\n else:\n for j in range(i, 0, -1):\n if is_pali[j][i] is True:\n dp[i] = min(dp[i], 1 + dp[j - 1])\n return dp[-1]", "def ispallindrome(string, i, j):\n if string == '':\n return False\n while i < j:\n if string[i] != string[j]:\n return False\n i += 1\n j += -1\n return True\n\ndef solve(arr, ind, dp):\n if ind == len(arr):\n return 0\n partition = 0\n MIN = float('inf')\n if dp[ind] != -1:\n return dp[ind]\n for i in range(ind, len(arr)):\n if ispallindrome(arr, ind, i):\n partition = 1 + self.solve(arr, i + 1, dp)\n MIN = min(MIN, partition)\n dp[ind] = MIN\n return MIN\n\ndef palindromicpartition(string):\n dp = [-1 for _ in range(len(string))]\n return self.solve(string, 0, dp) - 1", "def palindromicpartition(string):\n n = len(string)\n\n def ispalindrome(start, end, str):\n while start < end:\n if str[start] != str[end]:\n return False\n start += 1\n end -= 1\n return True\n dp = [0 for i in range(n + 1)]\n\n def rec(idx):\n if idx == n:\n return 0\n if dp[idx] != -1:\n return dp[idx]\n mini = int(1000000000.0)\n for i in range(idx, n):\n if ispalindrome(idx, i, string):\n cost = 1 + rec(i + 1)\n mini = min(mini, cost)\n dp[idx] = mini\n return dp[idx]\n for idx in range(n - 1, -1, -1):\n mini = int(1000000000.0)\n for i in range(idx, n):\n if ispalindrome(idx, i, string):\n cost = 1 + dp[i + 1]\n mini = min(mini, cost)\n dp[idx] = mini\n return dp[0] - 1", "def is_palindrome(s):\n return s == s[::-1]\n\ndef helper(s):\n if self.d.get(s) is not None:\n return self.d[s]\n if not s:\n return 0\n ans = 10 ** 9\n for i in range(len(s)):\n if is_palindrome(s[:i + 1]):\n ans = min(ans, 1 + self.helper(s[i + 1:]))\n self.d[s] = ans\n return ans\n\ndef palindromicpartition(string):\n self.d = {}\n return self.helper(string) - 1", "def palindromicpartition(s):\n\n def checkPalindrome(string, i, j):\n (l, r) = (i, j)\n while l < r:\n if string[l] != string[r]:\n return False\n l += 1\n r -= 1\n return True\n\n def solve(string, i, j, dp):\n if i >= j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if checkPalindrome(string, i, j):\n dp[i][j] = 0\n return 0\n ans = float('inf')\n for k in range(i, j):\n if checkPalindrome(string, i, k):\n temp = 1 + solve(string, k + 1, j, dp)\n ans = min(ans, temp)\n dp[i][j] = ans\n return ans\n n = len(s)\n dp = [[-1 for j in range(n + 1)] for i in range(n + 1)]\n ans = solve(s, 0, n - 1, dp)\n return ans", "def palindromicpartition(string):\n n = len(string)\n t = [[-1 for _ in range(n + 2)] for _ in range(n + 2)]\n\n def isPalin(s):\n return s == s[::-1]\n\n def solve(i, j):\n if i >= j:\n return 0\n if t[i][j] != -1:\n return t[i][j]\n if isPalin(string[i:j + 1]):\n return 0\n mn = int(1000000000.0)\n for k in range(i, j):\n if isPalin(string[i:k + 1]):\n temp = solve(k + 1, j) + 1\n mn = min(mn, temp)\n t[i][j] = mn\n return mn\n return solve(0, n - 1)", "def ispallindrome(s, i, j):\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef palindromicpartition(s):\n n = len(s)\n dp = [[-1 for i in range(501)] for j in range(501)]\n\n def helper(i, j):\n if i >= j:\n dp[i][j] = 0\n return dp[i][j]\n if dp[i][j] != -1:\n return dp[i][j]\n if self.ispallindrome(s, i, j):\n dp[i][j] = 0\n return 0\n ans = 510\n for k in range(i, j):\n if self.ispallindrome(s, i, k):\n temp = 1 + helper(i, k) + helper(k + 1, j)\n ans = min(ans, temp)\n dp[i][j] = ans\n return dp[i][j]\n return helper(0, n - 1)", "def palindromicpartition(string):\n n = len(string)\n dp = [[-1 for i in range(n + 1)] for j in range(n + 1)]\n\n def ispalindromic(string):\n return string == string[::-1]\n\n def func(string, i, j):\n if i >= j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if ispalindromic(string[i:j + 1]):\n return 0\n c = 100000\n for k in range(i, j):\n if ispalindromic(string[i:k + 1]):\n if dp[k + 1][j] != -1:\n c2 = dp[k + 1][j]\n else:\n c2 = func(string, k + 1, j)\n temp = c2 + 1\n c = min(c, temp)\n dp[i][j] = c\n return dp[i][j]\n return func(string, 0, n - 1)", "def palindromicpartition(str):\n n = len(str)\n dp = [0] * n\n palindrome = [[False] * n for _ in range(n)]\n for i in range(n):\n min_cut = i\n for j in range(i + 1):\n if str[i] == str[j] and (i - j < 2 or palindrome[j + 1][i - 1]):\n palindrome[j][i] = True\n if j == 0:\n min_cut = 0\n else:\n min_cut = min(min_cut, dp[j - 1] + 1)\n dp[i] = min_cut\n return dp[n - 1]", "import sys\n\ndef isPalindrome(str, i, j):\n while i < j:\n if str[i] != str[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef palindromicpartition(str):\n n = len(str)\n dp = [0] * (n + 1)\n for i in range(n - 1, -1, -1):\n mn = sys.maxsize\n for cut in range(i, n):\n if self.isPalindrome(str, i, cut):\n cost = 1 + dp[cut + 1]\n mn = min(mn, cost)\n dp[i] = mn\n return dp[0] - 1", "def fun(i, s, n, dp):\n if i == n:\n return 0\n if dp[i] != -1:\n return dp[i]\n temp = ''\n mini = float('inf')\n for j in range(i, n):\n temp += s[j]\n if temp == temp[::-1]:\n cost = 1 + self.fun(j + 1, s, n, dp)\n mini = min(mini, cost)\n dp[i] = mini\n return dp[i]\n\ndef palindromicpartition(string):\n dp = [-1 for i in range(len(string) + 1)]\n return self.fun(0, string, len(string), dp) - 1", "def palindromicpartition(S):\n\n def palind(f):\n l = len(f)\n for i in range(l // 2):\n if f[i] != f[l - i - 1]:\n return 0\n return 1\n\n def manu(i, n, s):\n if i == n:\n return 0\n if dp[i][n] != -1:\n return dp[i][n]\n x = ''\n mini = 10 ** 9\n for j in range(i, n):\n x += s[j]\n if palind(x):\n c = 1 + manu(j + 1, n, s)\n mini = min(mini, c)\n dp[i][n] = mini\n return mini\n dp = [[-1 for i in range(len(S) + 1)] for i in range(len(S) + 1)]\n return manu(0, len(S), S) - 1", "def palindromicpartition(string):\n n = len(string)\n c = [0] * n\n p = [[False for i in range(n)] for i in range(n)]\n for i in range(n):\n p[i][i] = True\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if L == 2:\n p[i][j] = string[i] == string[j]\n else:\n p[i][j] = string[i] == string[j] and p[i + 1][j - 1]\n for i in range(n):\n if p[0][i] == True:\n c[i] = 0\n else:\n c[i] = 25000\n for j in range(i):\n if p[j + 1][i] and c[j] + 1 < c[i]:\n c[i] = c[j] + 1\n return c[n - 1]", "def palindromicpartition(S):\n N = len(S)\n isp = [[True] * N for _ in range(N)]\n for add in range(1, N):\n for j in range(N - add):\n isp[j][j + add] = S[j] == S[j + add] and isp[j + 1][j + add - 1]\n dp = [1] * N + [0]\n for i in range(1, N):\n v = 1 + dp[i - 1]\n for j in range(i):\n if S[i] == S[j] and isp[j + 1][i - 1]:\n v = min(v, dp[j - 1] + 1)\n dp[i] = v\n return dp[N - 1] - 1", "import math\n\ndef solve(i, j, string, dp, ispall):\n if i > j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if ispall[i][j] == 1:\n dp[i][j] = 0\n return dp[i][j]\n currmin = float('INF')\n for p in range(i, j + 1):\n if ispall[i][p]:\n currmin = min(currmin, 1 + self.solve(p + 1, j, string, dp, ispall))\n dp[i][j] = currmin\n return dp[i][j]\n\ndef palindromicpartition(string):\n ispall = [[0 for i in range(len(string))] for t in range(len(string))]\n for i in range(len(string)):\n for j in range(i, len(string)):\n curr = string[i:j + 1]\n flag = 1\n (ptr1, ptr2) = (0, j - i)\n while ptr1 <= ptr2:\n if curr[ptr1] != curr[ptr2]:\n flag = 0\n break\n ptr1 += 1\n ptr2 -= 1\n ispall[i][j] = flag\n dp = [[-1 for i in range(len(string))] for t in range(len(string))]\n return self.solve(0, len(string) - 1, string, dp, ispall)", "def palindromicpartition(string):\n dp = [0 for i in range(len(string))]\n p = [[False for i in range(len(string))] for j in range(len(string))]\n for i in range(len(string)):\n m = i\n for j in range(i + 1):\n if string[i] == string[j] and (i - j < 2 or p[j + 1][i - 1]):\n p[j][i] = True\n m = min(m, 0 if j == 0 else dp[j - 1] + 1)\n dp[i] = m\n return dp[len(string) - 1]", "def palindromicpartition(s):\n n = len(s)\n dp = [0] * (n + 1)\n p = [[False] * (n + 1) for _ in range(n + 1)]\n for i in range(1, n + 1):\n cost = float('inf')\n for k in range(i, 0, -1):\n if s[k - 1] == s[i - 1] and (i - k <= 2 or p[k][i - 2]):\n p[k - 1][i - 1] = True\n curr = 1 + dp[k - 1]\n cost = min(cost, curr)\n dp[i] = cost\n return dp[n] - 1", "def palindromicpartition(s: str) -> int:\n n = len(s)\n dp = [[False] * n for _ in range(n)]\n cuts = [0] * n\n for i in range(n):\n dp[i][i] = True\n for j in range(i):\n if s[i] == s[j] and (i == j + 1 or dp[j + 1][i - 1]):\n dp[j][i] = True\n for i in range(n):\n if dp[0][i]:\n cuts[i] = 0\n else:\n cuts[i] = i\n for j in range(1, i + 1):\n if dp[j][i]:\n cuts[i] = min(cuts[i], cuts[j - 1] + 1)\n return cuts[n - 1]", "from functools import lru_cache\n\ndef palindromicpartition(s):\n n = len(s)\n dp = {}\n palindrome = [[False for _ in range(n)] for _ in range(n)]\n for i in range(n - 1, -1, -1):\n for j in range(i, n):\n if s[i] == s[j]:\n if j - i + 1 <= 2:\n palindrome[i][j] = True\n else:\n palindrome[i][j] = palindrome[i + 1][j - 1]\n\n def fun(i):\n if i == n:\n return 0\n if i in dp:\n return dp[i]\n minc = float('inf')\n for j in range(i, n):\n if palindrome[i][j]:\n minc = min(minc, 1 + fun(j + 1))\n dp[i] = minc\n return minc\n return fun(0) - 1", "from functools import lru_cache\n\ndef palindromicpartition(s):\n n = len(s)\n dp = {}\n\n def isPalindrome(l, r):\n r += 1\n d = (r - l) // 2\n for i in range(d):\n if s[l + i] != s[r - 1 - i]:\n return False\n return True\n\n def fun(i):\n if i == n:\n return 0\n if i in dp:\n return dp[i]\n minc = float('inf')\n for j in range(i, n):\n if isPalindrome(i, j):\n minc = min(minc, 1 + fun(j + 1))\n dp[i] = minc\n return minc\n return fun(0) - 1", "def chk(l, r, s):\n while l < r:\n if s[l] == s[r]:\n r -= 1\n l += 1\n else:\n return False\n return True\n\ndef f(l, r, s, dp):\n if (l, r) in dp:\n return dp[l, r]\n if chk(l, r, s):\n return 1\n ans = r - l + 1\n for i in range(l, r):\n if chk(l, i, s):\n ans = min(ans, 1 + f(i + 1, r, s, dp))\n dp[l, r] = ans\n return ans\n\ndef palindromicpartition(string):\n dp = {}\n s = list(string)\n return f(0, len(s) - 1, s, dp) - 1", "def isPalin(i, j, string):\n while i < j:\n if string[i] != string[j]:\n return False\n j -= 1\n i += 1\n return True\n\ndef recur(i, string, n, dp, dpP):\n if i == n:\n return 0\n if dp[i] != -1:\n return dp[i]\n mini = float('inf')\n for j in range(i, n):\n if self.isPalin(i, j, string):\n cost = 1 + self.recur(j + 1, string, n, dp, dpP)\n mini = min(mini, cost)\n dp[i] = mini\n return mini\n\ndef palindromicpartition(string):\n n = len(string)\n dp = [float('inf') for i in range(len(string))]\n dp.append(0)\n for i in range(n - 1, -1, -1):\n for j in range(i, n):\n if self.isPalin(i, j, string):\n cost = 1 + dp[j + 1]\n dp[i] = min(dp[i], cost)\n return dp[0] - 1", "import sys\n\ndef palindromicpartition(str1):\n n = len(str1)\n C = [0] * (n + 1)\n P = [[False for x in range(n + 1)] for y in range(n + 1)]\n for i in range(n):\n P[i][i] = True\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if L == 2:\n P[i][j] = str1[i] == str1[j]\n else:\n P[i][j] = str1[i] == str1[j] and P[i + 1][j - 1]\n for i in range(n):\n if P[0][i] == True:\n C[i] = 0\n else:\n C[i] = sys.maxsize\n for j in range(i):\n if P[j + 1][i] == True and 1 + C[j] < C[i]:\n C[i] = 1 + C[j]\n return C[n - 1]", "def palindromicpartition(string):\n i = 0\n j = len(string) - 1\n dp = [[-1 for i in range(len(string) + 1)] for j in range(len(string) + 1)]\n ans = self.solve(string, i, j, dp)\n return ans\n\ndef isPalindrome(string):\n return string == string[::-1]\n\ndef solve(string, i, j, dp):\n if i >= j or self.isPalindrome(string[i:j + 1]):\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if dp[i][j] != -1:\n return dp[i][j]\n mini = float('inf')\n for k in range(i, j):\n if self.isPalindrome(string[i:k + 1]):\n temp_ans = 1 + self.solve(string, k + 1, j, dp)\n if temp_ans < mini:\n mini = temp_ans\n dp[i][j] = mini\n return dp[i][j]", "def palindromicpartition(string):\n s = string\n\n def solve(s, i, j):\n if temp[i][j] != -1:\n return temp[i][j]\n if i >= j or s[i:j + 1] == s[i:j + 1][::-1]:\n return 0\n ans = float('infinity')\n for k in range(i, j):\n if s[i:k + 1] == s[i:k + 1][::-1]:\n left = solve(s, k + 1, j)\n tmp = 1 + left\n ans = min(ans, tmp)\n temp[i][j] = ans\n return temp[i][j]\n temp = [[-1] * 502 for i in range(502)]\n return solve(s, 0, len(s) - 1)", "def palindromicpartition(string):\n\n def pal(i, j):\n if i >= j or string[i:j + 1] == string[i:j + 1][::-1]:\n dp[i] = 0\n return 0\n if dp[i] != -1:\n return dp[i]\n count = 10 ** 10\n for k in range(i, j):\n count = min(count, pal(i, k) + pal(k + 1, j) + 1)\n dp[i] = count\n return count\n i = 0\n j = len(string)\n dp = [-1 for k in range(j + 1)]\n return pal(i, j)", "def palindromicpartition(str):\n n = len(str)\n P = [[False for _ in range(n)] for _ in range(n)]\n for i in range(n):\n P[i][i] = True\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if L == 2:\n P[i][j] = str[i] == str[j]\n else:\n P[i][j] = str[i] == str[j] and P[i + 1][j - 1]\n C = [float('inf') for _ in range(n)]\n for j in range(n):\n if P[0][j]:\n C[j] = 0\n else:\n for i in range(j):\n if P[i + 1][j]:\n C[j] = min(C[j], C[i] + 1)\n return C[n - 1]", "def palindromicpartition(str):\n n = len(str)\n dp = [[False] * n for i in range(n)]\n for g in range(0, n):\n for (i, j) in zip(range(0, n), range(g, n)):\n if g == 0:\n dp[i][j] = True\n elif g == 1:\n if str[i] == str[j]:\n dp[i][j] = True\n else:\n dp[i][j] = False\n elif str[i] == str[j] and dp[i + 1][j - 1] == True:\n dp[i][j] = True\n else:\n dp[i][j] = False\n if dp[0][n - 1] == True:\n return 0\n ans = [int(x) for x in range(n + 1)]\n ans[0] = 0\n ans[1] = 0\n ans[2] = 0\n if str[0] != str[1]:\n ans[2] += 1\n for i in range(3, n + 1):\n for j in range(i, 0, -1):\n if dp[j - 1][i - 1] == True:\n ans[i] = min(ans[i], ans[j - 1] + 1)\n return ans[n]", "import sys\n\ndef is_palindrome(strt, end, st):\n while strt < end:\n if st[strt] != st[end]:\n return False\n strt += 1\n end -= 1\n return True\n\ndef get_cuts(i, j, string, dp):\n if i >= j:\n return 0\n if self.is_palindrome(i, j, string):\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n ans = sys.maxsize\n curr_min = sys.maxsize\n for k in range(i, j):\n if self.is_palindrome(i, k, string):\n curr_min = 1 + self.get_cuts(k + 1, j, string, dp)\n ans = min(curr_min, ans)\n dp[i][j] = ans\n return ans\n\ndef palindromicpartition(string):\n dp = [[-1 for x in range(len(string) + 1)] for y in range(len(string) + 1)]\n return self.get_cuts(0, len(string) - 1, string, dp)", "import sys\nsys.setrecursionlimit(10 ** 7)\n\ndef palindromicpartition(string):\n d = dict()\n\n def dfs(s, i, j):\n if i == j:\n s1 = s[i:j + 1]\n if s1 == s1[::-1]:\n return -1\n return 10 ** 9\n if d.get((i, j)) != None:\n return d[i, j]\n y = 10 ** 9\n for k in range(i, j):\n s1 = s[i:k + 1]\n if s1 == s1[::-1]:\n a = 1 + dfs(s, k + 1, j)\n y = min(y, a)\n d[i, j] = y\n return y\n return dfs(string, 0, len(string))", "def palindromicpartition(string):\n S = string\n n = len(S)\n hmap = {}\n\n def is_palindrome(s, i, j):\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n\n def palin_partition(arr, i, j):\n if i >= j or is_palindrome(arr, i, j):\n hmap[i, j] = 0\n return 0\n mini = 1000000000.0\n if (i, j) not in hmap:\n for k in range(i, j):\n if is_palindrome(arr, i, k):\n if (k + 1, j) not in hmap:\n hmap[k + 1, j] = palin_partition(arr, k + 1, j)\n temp_ans = 1 + hmap[k + 1, j]\n mini = min(mini, temp_ans)\n hmap[i, j] = mini\n return hmap[i, j]\n return palin_partition(S, 0, n - 1)", "def palindromicpartition(string):\n n = len(string)\n dp = [[-1 for i in range(n)] for j in range(n)]\n\n def recursive(string, left=0, right=n - 1):\n if left > right:\n return True\n if left == right:\n dp[left][right] = True\n return True\n if dp[left][right] != -1:\n return dp[left][right]\n if string[left] == string[right]:\n dp[left][right] = recursive(string, left + 1, right - 1)\n else:\n dp[left][right] = False\n recursive(string, left + 1, right)\n recursive(string, left, right - 1)\n return dp[left][right]\n recursive(string)\n dp2 = [[-1 for i in range(n)] for j in range(n)]\n\n def findminimum(string, dp, dp2, left=0, right=0):\n if right == len(string) == left:\n return 0\n if left > right or right >= len(string):\n return float('inf')\n if dp[left][right] != -1:\n return dp[left][right]\n dp[left][right] = findminimum(string, dp, dp2, left, right + 1)\n if dp2[left][right]:\n dp[left][right] = min(dp[left][right], 1 + findminimum(string, dp, dp2, right + 1, right + 1))\n return dp[left][right]\n return findminimum(string, dp2, dp) - 1", "from math import *\n\ndef solve(i, j, string, dp, grid):\n if grid[i][j]:\n return 0\n if (i, j) in dp:\n return dp[i, j]\n cnt = inf\n for k in range(i, j):\n cnt = min(cnt, 1 + self.solve(i, k, string, dp, grid) + self.solve(k + 1, j, string, dp, grid))\n dp[i, j] = cnt\n return cnt\n\ndef palindromicpartition(string):\n n = len(string)\n palindrom_grid = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(i, n):\n if i == j:\n palindrom_grid[i][j] = 1\n for i in range(n - 2, -1, -1):\n for j in range(n - 1, i, -1):\n if string[i] == string[j] and (palindrom_grid[i + 1][j - 1] or i + 1 == j):\n palindrom_grid[i][j] = 1\n dp = [inf] * n\n dp[0] = 0\n for j in range(1, n):\n if palindrom_grid[0][j]:\n dp[j] = 0\n else:\n for i in range(j, 0, -1):\n if palindrom_grid[i][j]:\n dp[j] = min(dp[j], 1 + dp[i - 1])\n return dp[-1]\n n = len(string)\n palindrom_grid = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(i, n):\n if i == j:\n palindrom_grid[i][j] = 1\n for i in range(n - 2, -1, -1):\n for j in range(n - 1, i, -1):\n if string[i] == string[j] and (palindrom_grid[i + 1][j - 1] or i + 1 == j):\n palindrom_grid[i][j] = 1\n dp = [[inf] * n for _ in range(n)]\n for i in range(n):\n for j in range(i, n):\n if palindrom_grid[i][j]:\n dp[i][j] = 0\n else:\n for k in range(i, j):\n dp[i][j] = min(dp[i][j], 1 + (0 if palindrom_grid[i][k] else dp[i][k]) + (0 if palindrom_grid[k + 1][j] else dp[k + 1][j]))\n return dp[0][-1]\n dp = {}\n n = len(string)\n palindrom_grid = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(i, n):\n if i == j:\n palindrom_grid[i][j] = 1\n for i in range(n - 2, -1, -1):\n for j in range(n - 1, i, -1):\n if string[i] == string[j] and (palindrom_grid[i + 1][j - 1] or i + 1 == j):\n palindrom_grid[i][j] = 1\n return self.solve(0, n - 1, string, dp, palindrom_grid)", "def palindromicpartition(string):\n mp = {}\n res = self.solve(string, mp)\n return res\n\ndef solve(string, mp):\n if len(string) == 0 or string == string[::-1]:\n return 0\n if string in mp:\n return mp[string]\n res = float('inf')\n for i in range(len(string)):\n prefix = string[:i + 1]\n if prefix == prefix[::-1]:\n res = min(res, 1 + self.solve(string[i + 1:], mp))\n mp[string] = res\n return res", "def palindromicpartition(string):\n\n def ispallindrome(s, i, j, dp):\n if i >= j:\n dp[i][j] = 0\n return dp[i][j]\n if s[i] == s[j]:\n dp[i][j] = ispallindrome(s, i + 1, j - 1, dp)\n return dp[i][j]\n return dp[i][j]\n\n def helper(s, i, j, dp):\n if i >= j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if ispallindrome(s, i, j, dp) == 0:\n dp[i][j] = 0\n return dp[i][j]\n ans = float('inf')\n for k in range(i, j):\n if dp[i][k] != -1:\n left = dp[i][k]\n else:\n left = ispallindrome(s, i, k, dp)\n dp[i][k] = left\n if left != 0:\n continue\n if dp[k + 1][j] != -1:\n right = dp[k + 1][j]\n else:\n right = helper(s, k + 1, j, dp)\n dp[k + 1][j] = right\n temp_ans = helper(s, k + 1, j, dp) + 1\n ans = min(ans, temp_ans)\n dp[i][j] = ans\n return dp[i][j]\n dp = [[-1] * len(string) for i in range(len(string))]\n return helper(string, 0, len(string) - 1, dp)"], "starter_code": "def palindromicpartition(string):\n", "input_output": {"inputs": ["str = \"ababbbabbababa\"", "str = \"aaabba\""], "outputs": ["3", "1"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/palindromic-patitioning4845/1", "Expected Auxiliary Space": "O(n*n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n*n) [n is the length of the string str]", "entry_point": "palindromicpartition", "task_id": "TACO_lite/260", "example": [[["ababbbabbababa"], ["aaabba"]], ["3", "1"]]} +{"requirement": "I've got a crazy mental illness.\nI dislike numbers a lot. But it's a little complicated:\nThe number I'm afraid of depends on which day of the week it is...\nThis is a concrete description of my mental illness:\n\nMonday --> 12\n\nTuesday --> numbers greater than 95\n\nWednesday --> 34\n\nThursday --> 0\n\nFriday --> numbers divisible by 2\n\nSaturday --> 56\n\nSunday --> 666 or -666\n\n\nWrite a function which takes a string (day of the week) and an integer (number to be tested) so it tells the doctor if I'm afraid or not. (return a boolean)", "solutions": ["def am_i_afraid(day, num):\n return {'Monday': num == 12, 'Tuesday': num > 95, 'Wednesday': num == 34, 'Thursday': num == 0, 'Friday': num % 2 == 0, 'Saturday': num == 56, 'Sunday': num == 666 or num == -666}[day]", "afraid = {'Monday': lambda x: x == 12, 'Tuesday': lambda x: x > 95, 'Wednesday': lambda x: x == 34, 'Thursday': lambda x: x == 0, 'Friday': lambda x: x % 2 == 0, 'Saturday': lambda x: x == 56, 'Sunday': lambda x: abs(x) == 666}\n\ndef am_i_afraid(day, num):\n return afraid[day](num)", "def am_i_afraid(day, x):\n return {'Mo': x == 12, 'Tu': x > 95, 'We': x == 34, 'Th': x == 0, 'Fr': x % 2 == 0, 'Sa': x == 56, 'Su': abs(x) == 666}[day[:2]]", "FUNCS = dict(zip('Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(), (12.0.__eq__, 95.0.__lt__, 34.0.__eq__, 0.0.__eq__, lambda n: not n % 2, 56.0.__eq__, lambda n: abs(n) == 666)))\n\ndef am_i_afraid(day, n):\n return FUNCS[day](n)", "def am_i_afraid(day, num):\n rep = False\n lst1 = [('monday', 12), ('wednesday', 34), ('thursday', 0), ('saturday', 56), ('sunday', 666), ('sunday', -666)]\n input = (day.lower(), num)\n if input in lst1 or (input[0] == 'tuesday' and input[1] > 95) or (input[0] == 'friday' and input[1] % 2 == 0):\n rep = True\n return rep", "def am_i_afraid(day, num):\n if day == 'Monday' and num == 12:\n return True\n if day == 'Tuesday' and num > 95:\n return True\n if day == 'Wednesday' and num == 34:\n return True\n if day == 'Thursday' and num == 0:\n return True\n if day == 'Friday' and num % 2 == 0:\n return True\n if day == 'Saturday' and num == 56:\n return True\n if day == 'Sunday' and abs(num) == 666:\n return True\n return False"], "starter_code": "def am_i_afraid(day,num):\n", "input_output": {"fn_name": "am_I_afraid", "inputs": [["Monday", 13], ["Monday", 12], ["Tuesday", 0], ["Tuesday", 100], ["Tuesday", 95], ["Wednesday", 35], ["Wednesday", 34], ["Thursday", 2], ["Thursday", 0], ["Friday", 5], ["Friday", 4], ["Saturday", 55], ["Saturday", 56], ["Sunday", 55], ["Sunday", 666], ["Sunday", -666]], "outputs": [[false], [true], [false], [true], [false], [false], [true], [false], [true], [false], [true], [false], [true], [false], [true], [true]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/55b1fd84a24ad00b32000075", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "am_i_afraid", "task_id": "TACO_lite/145", "example": [[], []]} +{"requirement": "Given an array of N positive integers, print k largest elements from the array. \nExample 1:\nInput:\nN = 5, k = 2\narr[] = {12,5,787,1,23}\nOutput: 787 23\nExplanation: First largest element in\nthe array is 787 and the second largest\nis 23.\nExample 2:\nInput:\nN = 7, k = 3\narr[] = {1,23,12,9,30,2,50}\nOutput: 50 30 23\nExplanation: Three Largest element in\nthe array are 50, 30 and 23.\nYour Task:\nComplete the function kLargest() that takes the array, N and K as input parameters and returns a list of k largest element in descending order. \nExpected Time Complexity: O(N log K)\nExpected Auxiliary Space: O(K)\nConstraints:\n1 ≤ N ≤ 10^{4}\nK ≤ N\n1 ≤ array[i] ≤ 10^{5}", "solutions": ["import heapq\n\ndef klargest(li, n, k):\n pq = []\n ans = []\n n = len(li)\n for i in range(n):\n heapq.heappush(pq, -li[i])\n f = k\n while f > 0:\n a = heapq.heappop(pq)\n ans.append(-a)\n f -= 1\n return ans", "def klargest(li, n, k):\n a = []\n l = sorted(li)\n for i in range(-1, -k - 1, -1):\n a.append(l[i])\n return a", "def klargest(li, n, k):\n li.sort()\n c = 0\n i = -1\n a = []\n while c < k:\n a.append(li[i])\n i -= 1\n c += 1\n return a", "import heapq\n\ndef klargest(li, n, k):\n for i in range(n):\n li[i] = li[i] * -1\n heapq.heapify(li)\n ans = []\n for i in range(k):\n ans.append(-1 * heapq.heappop(li))\n return ans", "def klargest(li, n, k):\n op = []\n li.sort(reverse=True)\n for i in range(k):\n op.append(li[i])\n return op", "def klargest(li, n, k):\n li.sort(reverse=True)\n return li[:k]", "def klargest(li, n, k):\n list = []\n li.sort()\n li = li[::-1]\n for i in range(k):\n list.append(li[i])\n return list", "def klargest(li, n, k):\n li.sort()\n return li[n - k:][::-1]", "def klargest(li, n, k):\n l = sorted(li)[::-1]\n return l[:k]", "def klargest(li, n, k):\n l = []\n li.sort()\n li.reverse()\n for i in range(0, k):\n l.append(li[i])\n return l", "def klargest(li, n, k):\n li.sort()\n ans = []\n count = -1\n while k != 0:\n ans.append(li[count])\n k -= 1\n count -= 1\n return ans", "def klargest(arr, n, k):\n arr.sort()\n arr.reverse()\n return arr[:k]", "import heapq\n\ndef klargest(li, n, k):\n heap = []\n for value in li:\n heapq.heappush(heap, value)\n if len(heap) > k:\n heapq.heappop(heap)\n ans = []\n while len(heap) > 0:\n ans.append(heapq.heappop(heap))\n ans.reverse()\n return ans", "def klargest(arr, n, k):\n return sorted(arr)[::-1][:k]", "def klargest(li, n, k):\n newarr = []\n li.sort(reverse=True)\n while k > 0:\n newarr.append(li[0])\n li.pop(0)\n k -= 1\n return newarr", "import heapq\n\ndef klargest(arr, n, k):\n heap = []\n for i in arr:\n heapq.heappush(heap, i)\n if len(heap) > k:\n heapq.heappop(heap)\n result = []\n for i in range(len(heap)):\n result.append(heapq.heappop(heap))\n result.reverse()\n return result", "import heapq\n\ndef klargest(li, n, k):\n ans = []\n heapq.heapify(ans)\n for i in range(n):\n heapq.heappush(ans, li[i])\n if len(ans) > k:\n heapq.heappop(ans)\n main = []\n while len(ans):\n main.append(heapq.heappop(ans))\n main.reverse()\n return main", "import heapq\n\ndef klargest(arr, n, k):\n heap = []\n for i in arr:\n heapq.heappush(heap, -1 * i)\n result = []\n for i in range(k):\n result.append(-1 * heapq.heappop(heap))\n return result", "from heapq import *\n\ndef klargest(arr, n, k):\n maxheap = []\n for i in arr:\n heappush(maxheap, -i)\n ans = []\n for i in range(k):\n ans.append(-heappop(maxheap))\n return ans\n\ndef klargest(arr, n, k):\n arr = sorted(arr, reverse=True)\n return arr[:k]", "from heapq import *\n\ndef klargest(arr, n, k):\n maxheap = []\n for i in arr:\n heappush(maxheap, -i)\n ans = []\n for i in range(k):\n ans.append(-heappop(maxheap))\n return ans", "def klargest(li, n, k):\n m = sorted(li)\n p = m[-k:][::-1]\n return p", "def klargest(li, n, k):\n list_a = sorted(li, reverse=True)\n return list_a[:k]", "def klargest(li, n, k):\n x = sorted(li)\n x.reverse()\n lis = []\n for i in range(k):\n lis.append(x[i])\n return lis", "import heapq\n\ndef klargest(li, n, k):\n return heapq.nlargest(k, li)", "import heapq\n\ndef klargest(li, n, k):\n minh = []\n heapq.heapify(minh)\n ans = []\n for i in li:\n heapq.heappush(minh, i)\n if len(minh) > k:\n heapq.heappop(minh)\n while minh:\n x = heapq.heappop(minh)\n ans.append(x)\n return ans[::-1]", "import heapq\n\ndef klargest(li, n, k):\n heapq._heapify_max(li)\n klargest = list()\n while k:\n element = heapq._heappop_max(li)\n klargest.append(element)\n k = k - 1\n return klargest", "def klargest(li, n, k):\n li = sorted(li)[::-1]\n n = []\n for i in range(k):\n n += [li[i]]\n return n", "import heapq\n\ndef klargest(li, n, k):\n l = []\n l2 = []\n for i in li:\n heapq.heappush(l, -i)\n while k != 0:\n l2.append(-heapq.heappop(l))\n k -= 1\n return l2", "from heapq import heapify, heappush, heappop\n\ndef klargest(a, n, k):\n h = []\n heapify(h)\n for el in a:\n heappush(h, el)\n if len(h) > k:\n heappop(h)\n res = []\n while h:\n res.append(heappop(h))\n return sorted(res, reverse=True)", "import heapq\n\ndef klargest(arr, n, k):\n queue = []\n for i in range(n):\n heapq.heappush(queue, arr[i])\n want = n - k\n while want > 0:\n heapq.heappop(queue)\n want -= 1\n return sorted(queue, reverse=True)", "def klargest(li, n, k):\n i = 0\n t = []\n li = sorted(li)\n m = -1\n while i < k:\n t.append(li[m])\n m = m - 1\n i = i + 1\n return t", "def klargest(li, n, k):\n li = sorted(li)\n li = li[::-1]\n return li[0:k]", "def klargest(li, n, k):\n s = sorted(li)\n return s[n - k:][::-1]", "def klargest(li, n, k):\n li = sorted(li)\n l = []\n while k != 0:\n l.append(li.pop())\n k -= 1\n return l", "import heapq\n\ndef klargest(arr, n, k):\n li = []\n for i in range(len(arr)):\n heapq.heappush(li, arr[i])\n if len(li) > k:\n heapq.heappop(li)\n li.sort(reverse=1)\n return li", "import heapq as hq\n\ndef klargest(li, n, k):\n hq.heapify(li)\n return hq.nlargest(k, li)", "def klargest(li, n, k):\n ans = []\n li.sort()\n c = 0\n for i in range(n - 1, -1, -1):\n c += 1\n if c > k:\n break\n ans.append(li[i])\n return ans", "def klargest(li, n, k):\n li.sort()\n a = li\n a = a[::-1]\n b = []\n for i in range(k):\n b.append(a[i])\n return b", "def klargest(li, n, k):\n ar = []\n li.sort()\n i = n - 1\n p = 0\n while p < k:\n ar.append(li[i])\n i = i - 1\n p = p + 1\n return ar", "def klargest(li, n, k):\n li = sorted(li)\n a = []\n p = 0\n q = len(li) - 1\n for i in range(q, 0, -1):\n p += 1\n if p <= k:\n a.append(li[i])\n return a", "import heapq\n\ndef klargest(li, n, k):\n heapq.heapify(li)\n for i in range(n - k):\n heapq.heappop(li)\n li.sort()\n li.reverse()\n return li", "def klargest(li, n, k):\n li.sort()\n x = li[n - k:]\n x.reverse()\n return x", "import heapq\n\ndef klargest(li, n, k):\n if k > n:\n return li.sort(reverse=True)\n li.sort(reverse=True)\n return li[0:k]", "def klargest(li, n, k):\n li.sort()\n c = []\n for i in range(k):\n c.append(li[-1])\n li.pop()\n return c", "from heapq import *\n\ndef klargest(li, n, k):\n mi = []\n for i in li:\n if len(mi) < k:\n heappush(mi, i)\n else:\n heappush(mi, i)\n heappop(mi)\n return sorted(mi)[::-1]", "import heapq\n\ndef klargest(li, n, k):\n mylist = []\n heapq.heapify(mylist)\n for i in range(n):\n heapq.heappush(mylist, li[i])\n if len(mylist) > k:\n heapq.heappop(mylist)\n res = []\n while len(mylist) > 0:\n res.append(heapq.heappop(mylist))\n res.reverse()\n return res", "import heapq\n\ndef klargest(li, n, k):\n heap = []\n list1 = []\n for i in li:\n heapq.heappush(heap, i)\n if len(heap) > k:\n heapq.heappop(heap)\n while len(heap) > 0:\n list1.insert(0, heapq.heappop(heap))\n return list1", "import heapq\n\ndef klargest(li, n, k):\n a = []\n heapq.heapify(a)\n for i in range(n):\n heapq.heappush(a, li[i])\n if len(a) > k:\n heapq.heappop(a)\n a.sort(reverse=True)\n return a", "import heapq\n\ndef klargest(li, n, k):\n kq = []\n for i in range(k):\n heapq.heappush(kq, li[i])\n for k in li[k:]:\n heapq.heappush(kq, max(k, heapq.heappop(kq)))\n return sorted(kq)[::-1]", "def klargest(li, n, k):\n a = []\n if len(set(li)) == 1:\n return [-1]\n li = sorted(li)\n for i in range(1, k + 1):\n i = i * -1\n a.append(li[i])\n return a", "import heapq\n\ndef klargest(li, n, k):\n l = []\n size = 0\n for i in range(n):\n heapq.heappush(l, li[i])\n size = size + 1\n if size > k:\n heapq.heappop(l)\n size = size - 1\n l.sort(reverse=True)\n return l", "def klargest(li, n, k):\n li.sort()\n list_return = []\n for i in li[:-k - 1:-1]:\n list_return.append(i)\n return list_return", "def klargest(li, n, k):\n from heapq import heapify, heappush, heappop\n h = []\n heapify(h)\n for i in li:\n heappush(h, i)\n if len(h) > k:\n heappop(h)\n h.sort(reverse=True)\n return h", "def klargest(li, n, k):\n from heapq import heapify, heappush, heappop\n kt = []\n for i in range(n):\n heappush(kt, -li[i])\n i = 0\n ans = []\n while i < k:\n ans.append(-heappop(kt))\n i += 1\n return ans", "def klargest(li, n, k):\n count = 0\n li.sort(reverse=True)\n return li[:k:1]", "def maxheapify(arr, n, i):\n while True:\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n if left < n and arr[left] > arr[largest]:\n largest = left\n if right < n and arr[right] > arr[largest]:\n largest = right\n if largest != i:\n (arr[i], arr[largest]) = (arr[largest], arr[i])\n i = largest\n else:\n break\n\ndef klargest(arr, n, k):\n for i in range(n // 2 - 1, -1, -1):\n self.maxheapify(arr, n, i)\n result = []\n for i in range(n - 1, n - k - 1, -1):\n result.append(arr[0])\n (arr[0], arr[i]) = (arr[i], arr[0])\n self.maxheapify(arr, i, 0)\n return result"], "starter_code": "def klargest(li,n,k):\n", "input_output": {"inputs": ["N = 5, k = 2\r\narr[] = {12,5,787,1,23}", "N = 7, k = 3\r\narr[] = {1,23,12,9,30,2,50}"], "outputs": ["787 23", "50 30 23"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Heap"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/k-largest-elements3736/1", "Expected Auxiliary Space": "O(K)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N log K)", "entry_point": "klargest", "task_id": "TACO_lite/220", "example": [[[5, 2, [12, 5, 787, 1, 23]], [7, 3, [1, 23, 12, 9, 30, 2, 50]]], ["(787, 23)", "(50, 30, 23)"]]} +{"requirement": "Given a string s consisting of uppercase and lowercase alphabetic characters. Return the number of distinct substrings of size 2 that appear in s as contiguous substrings.\nExample\nInput :\ns = \"ABCAB\"\nOutput :\n3\nExplanation: For \"ABCAB\", the \nthree distinct substrings of size \n2 are \"AB\", \"BC\" and \"CA\". \nExample\nInput :\ns = \"XYZ\"\nOutput :\n2\nExplanation: For \"XYZ\", the \ntwo distinct substrings of size 2 are\n\"XY\" and \"YZ\".\nYour Task :\nYou don't need to read input or print anything. You have to complete the function fun() which takes the string s as input parameter and returns the number of distinct contiguous substring of size 2.\nExpected Time Complexity : O(|s|)\nExpected Auxilliary Space : O(|s|)\nConstraints:\n1<=|s|<=100\n|s| denotes the length of the string s.", "solutions": ["def fun(s):\n d = {}\n for i in range(len(s) - 1):\n if (s[i] and s[i + 1]) not in d:\n d[s[i], s[i + 1]] = 1\n else:\n d[s[i], s[i + 1]] += 1\n return len(d)", "from collections import defaultdict\n\ndef fun(s):\n hmap = defaultdict(int)\n for i in range(0, len(s) - 1):\n if s[i] and s[i + 1] not in hmap:\n hmap[s[i], s[i + 1]] = 1\n else:\n hmap[s[i], s[i + 1]] += 1\n return len(hmap)", "def fun(s):\n us = set()\n for i in range(1, len(s)):\n us.add(s[i - 1] + s[i])\n return len(us)", "def fun(s):\n dict = {}\n count = 0\n for i in range(len(s) - 1):\n sub = s[i] + s[i + 1]\n if dict.get(sub) == None:\n count += 1\n dict.update({sub: 1})\n return count", "def fun(s):\n hash = set()\n for i in range(0, len(s) - 1):\n hash.add(s[i:i + 2])\n return len(hash)", "def fun(s):\n res = set()\n for i in range(len(s) - 1):\n t = s[i:i + 2]\n res.add(t)\n return len(res)", "def fun(s):\n hmap = {}\n count = 0\n for i in range(len(s) - 1):\n temp = s[i] + s[i + 1]\n if temp in hmap:\n hmap[temp] += 1\n else:\n hmap[temp] = 1\n return len(hmap)", "def fun(s):\n l = []\n for i in range(len(s) - 2 + 1):\n if s[i:i + 2] not in l:\n l.append(s[i:i + 2])\n return len(l)", "def fun(s):\n d = {}\n if len(s) == 2:\n return 1\n elif len(s) < 2:\n return 0\n else:\n for i in range(len(s) - 1):\n a = s[i:i + 2]\n if a not in d:\n d[a] = 1\n return len(d)", "def fun(s):\n b = []\n for i in range(len(s) - 1):\n b.append(s[i:i + 2])\n c = set(b)\n d = len(c)\n return d", "def fun(s):\n substr_set = set()\n for i in range(len(s) - 1):\n if s[i:i + 2] not in substr_set:\n substr_set.add(s[i:i + 2])\n return len(substr_set)", "def fun(s):\n n = len(s)\n st = set()\n for i in range(n - 1):\n string = s[i:i + 2]\n st.add(string)\n return len(st)", "def fun(s):\n return len(set([s[i:i + 2] for i in range(len(s) - 1)]))", "def fun(s):\n new_set = set()\n for a in range(0, len(s)):\n if a == len(s) - 1:\n B = s[a - 1] + s[a]\n else:\n B = s[a] + s[a + 1]\n new_set.add(B)\n return len(new_set)", "def fun(s):\n res = []\n i = 0\n while i < len(s) - 1:\n if [s[i].lower(), s[i + 1].lower()] not in res:\n res.append([s[i].lower(), s[i + 1].lower()])\n i += 1\n return len(res)", "def fun(s):\n A = []\n for i in range(len(s) - 1):\n X = s[i:i + 2]\n if X not in A and X[-1] not in A:\n A.append(X)\n return len(A)", "def fun(s):\n ans = 0\n li = []\n for i in range(len(s)):\n if s[i:i + 2] != s[i + 1:i + 3] and s[i:i + 2] not in li:\n li.append(s[i:i + 2])\n ans += 1\n return ans - 1", "def fun(s):\n l = []\n c = 0\n for i in range(len(s)):\n if s[i:i + 2] != s[i + 1:i + 3] and s[i:i + 2] not in l:\n c += 1\n l.append(s[i:i + 2])\n return c - 1", "def fun(s):\n l = []\n st = ''\n for i in range(len(s) - 1):\n st = s[i] + s[i + 1]\n l.append(st)\n return len(set(l))", "def fun(s):\n i = 0\n l = []\n while i < len(s) - 1:\n if s[i:i + 2] not in l:\n l.append(s[i:i + 2])\n i += 1\n return len(l)", "def fun(s):\n res = []\n n = len(s)\n for i in range(n - 1):\n temp = s[i] + s[i + 1]\n if temp not in res:\n res.append(temp)\n return len(res)", "def fun(s):\n n = len(s)\n m = {}\n for i in range(n - 1):\n t = s[i] + s[i + 1]\n m[t] = 1\n return len(m)", "def fun(s):\n list1 = []\n for i in range(1, len(s)):\n if s[i - 1:i + 1] not in list1:\n list1.append(s[i - 1:i + 1])\n else:\n pass\n return len(list1)", "def fun(s):\n res = 0\n seen = set()\n for i in range(len(s) - 1):\n if s[i:i + 2] not in seen:\n res += 1\n seen.add(s[i:i + 2])\n return res", "def fun(s):\n a = 0\n x = []\n while a < len(s) - 1:\n c = s[a:a + 2]\n if c not in x:\n x.append(c)\n a += 1\n return len(x)", "def fun(s):\n k = {}\n for i in range(len(s) - 1):\n tmp = s[i:i + 2]\n if tmp not in k.keys():\n k[tmp] = 1\n else:\n k[tmp] += 1\n return len(k)", "def fun(s):\n hashset = set()\n (l, r) = (0, 1)\n while r < len(s):\n sub = s[l] + s[r]\n hashset.add(sub)\n l += 1\n r += 1\n return len(hashset)", "def fun(s):\n d = []\n for i in range(0, len(s) - 1):\n x = s[i] + s[i + 1]\n if x in d:\n continue\n else:\n d.append(x)\n return len(d)", "def fun(s):\n s = list(s)\n count = 0\n dset = []\n for i in range(len(s) - 1):\n a = str(s[i] + s[i + 1])\n if a in dset:\n continue\n else:\n dset.append(a)\n count += 1\n return count", "def fun(s):\n s = list(s)\n count = 0\n d = {}\n for i in range(len(s) - 1):\n a = str(s[i] + s[i + 1])\n if a in d.keys():\n continue\n else:\n d[a] = 1\n count += 1\n return count", "def fun(s):\n substr = []\n for i in range(len(s) - 1):\n substr.append(s[i:i + 2])\n substr = list(set(substr))\n return len(substr)", "def fun(s):\n d = set()\n for i in range(len(s) - 1):\n st = s[i] + s[i + 1]\n d.add(st)\n return len(d)", "def fun(s):\n n = len(s)\n m = {}\n m[s[0:2]] = 1\n for i in range(1, n):\n if i + 1 < n:\n if s[i:i + 2] in m:\n m[s[i:i + 2]] += 1\n else:\n m[s[i:i + 2]] = 1\n return len(m)", "from collections import defaultdict\n\ndef fun(s):\n d = defaultdict(int)\n for i in range(len(s) - 1):\n temp = ''\n temp = s[i] + s[i + 1]\n d[temp] += 1\n return len(d.keys())", "def fun(s):\n dict_ = {}\n for i in range(len(s) - 1):\n ss = s[i:i + 2]\n if ss not in dict_:\n dict_[ss] = 1\n else:\n dict_[ss] += 1\n return len(dict_)", "def fun(s):\n i = -1\n j = -1\n count = 0\n st = ''\n dict = {}\n for i in range(len(s) - 1):\n st = s[i:i + 2]\n sorted(st)\n if st not in dict:\n dict[st] = 1\n count += 1\n return count", "def fun(s):\n res = []\n i = 0\n j = 2\n n = len(s)\n while j <= n:\n res.append(s[i:j])\n j += 1\n i += 1\n res.sort()\n l = len(res)\n i = 0\n r = [res[0]]\n while i < l:\n if res[i] != r[-1]:\n r.append(res[i])\n i += 1\n return len(r)", "def fun(s):\n ans = []\n for i in range(len(s) - 1):\n a = s[i] + s[i + 1]\n ans.append(a)\n return len(set(ans))", "def fun(s):\n i = 0\n j = 1\n ss = set()\n while j < len(s):\n ss.add(s[i] + s[j])\n i += 1\n j += 1\n return len(ss)", "from collections import defaultdict\n\ndef fun(s):\n c = 0\n d = defaultdict(lambda : 0)\n for i in range(0, len(s) - 1):\n x = s[i:i + 2]\n d[x] += 1\n if d[x] == 1:\n c += 1\n return c", "def fun(s):\n dic = {}\n for i in range(len(s) - 1):\n try:\n dic[s[i:i + 2]] += 1\n except:\n dic[s[i:i + 2]] = 1\n return len(dic)", "def fun(s):\n h_map = {}\n n = len(s)\n for i in range(len(s) - 1):\n if s[i] + s[i + 1] in h_map:\n h_map[s[i] + s[i + 1]] += 1\n else:\n h_map[s[i] + s[i + 1]] = 1\n return len(h_map)", "def fun(s):\n arr = []\n for i in range(len(s) - 1):\n p = ''\n p = s[i] + s[i + 1]\n arr.append(p)\n return len(set(arr))", "def fun(s):\n substrings = [s[i] + s[i + 1] for i in range(len(s) - 1)]\n return len(list(set(substrings)))", "def fun(s):\n c = 0\n ss = set()\n for i in range(0, len(s)):\n for j in range(i + 1, len(s) + 1):\n if len(s[i:j]) == 2 and s[i:j] not in ss:\n ss.add(s[i:j])\n return len(ss)", "def fun(s):\n dict1 = {}\n for i in range(0, len(s)):\n if s[i:i + 2] not in dict1:\n dict1[s[i:i + 2]] = 1\n count = 0\n result_str = ''\n for i in dict1:\n if len(i) == 2:\n result_str += i + ' '\n count += 1\n return count", "def fun(s):\n l = []\n for x in range(len(s) - 1):\n a = s[x] + s[x + 1]\n l.append(a)\n return len(set(l))", "def fun(s):\n substring = []\n index = 1\n pre_index = 0\n while index < len(s):\n new_str = str(s[pre_index]) + str(s[index])\n if new_str not in substring:\n substring.append(new_str)\n index += 1\n pre_index += 1\n return len(substring)", "def fun(s):\n sp = []\n for i in range(0, len(s) - 1):\n u = s[i:i + 2]\n sp.append(u)\n ans = int(len(list(set(sp))))\n return ans", "def fun(s):\n t = []\n n = len(s)\n for i in range(0, n - 1):\n u = s[i:i + 2]\n t.append(u)\n ans = set(t)\n return len(ans)", "import math\n\ndef fun(s):\n l = []\n for i in range(len(s) - 1):\n a = ''\n a = s[i] + s[i + 1]\n l.append(a)\n return len(set(l))", "def fun(s):\n n = len(s)\n tmp_dict = {}\n count = 0\n for i in range(n - 1):\n curr_s = s[i:i + 2]\n if not tmp_dict.get(curr_s):\n count += 1\n tmp_dict[curr_s] = 1\n return count", "def fun(s):\n substr_set = set()\n for (i, letter) in enumerate(s):\n if i < len(s) - 1:\n substr_set.add(s[i:i + 2])\n return len(substr_set)", "def fun(s):\n a = []\n n = len(s)\n for i in range(0, n - 1):\n j = i + 1\n if s[i] + s[j] not in a:\n a.append(s[i] + s[j])\n return len(a)", "def fun(s):\n distinct = set()\n length = len(s)\n for i in range(length - 1):\n distinct.add(s[i:i + 2])\n return len(distinct)", "def fun(s):\n (n, x) = (len(s), 0)\n st = set()\n for i in range(n - 1):\n snew = s[i:i + 2]\n st.add(snew)\n return len(st)", "def fun(s):\n lst = []\n i = 0\n j = 1\n while j != len(s):\n x = s[i:j + 1]\n if x not in lst:\n lst.append(x)\n i += 1\n j += 1\n return len(lst)", "def fun(s):\n hashset = set()\n for i in range(len(s) - 1):\n char = s[i:i + 2]\n hashset.add(char)\n return len(hashset)", "def fun(s):\n ans = 0\n arr = set()\n for i in range(len(s) - 1):\n if s[i] + s[i + 1] not in arr:\n ans += 1\n arr.add(s[i] + s[i + 1])\n return ans", "def fun(s):\n d = {}\n for i in range(len(s) - 1):\n if s[i:i + 2] not in d:\n d[s[i:i + 2]] = 1\n else:\n d[s[i:i + 2]] = d[s[i:i + 2]] + 1\n c = 0\n for (key, val) in d.items():\n c += 1\n return c", "def fun(s):\n ans = []\n p = set()\n for i in range(1, len(s)):\n x = ''.join(s[i - 1:i + 1])\n if x not in p:\n ans.append(x)\n p.add(x)\n return len(ans)"], "starter_code": "def fun(s):\n", "input_output": {"inputs": ["s = \"ABCAB\"", "s = \"XYZ\""], "outputs": ["3", "2"]}, "difficulty": "EASY", "raw_tags": ["Map", "Strings", "Hash", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/distinct-substrings2516/1", "Expected Auxiliary Space": "O(|s|)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|s|)", "entry_point": "fun", "task_id": "TACO_lite/264", "example": [[["ABCAB"], ["XYZ"]], ["3", "2"]]} +{"requirement": "You are given the root of a complete binary tree. Your task is to find the count of nodes.\nA complete binary tree is a binary tree whose, all levels except the last one are completely filled, the last level may or may not be completely filled and Nodes in the last level are as left as possible.\nDesign an algorithm that runs better than O(n).\nExample:\nInput: \nroot = [1,2,3,4,5,6]\nOutput: \n6\nExplanation: \nThere are a total of 6 nodes in the given tree.\nYour Task:\nComplete the function int cnt_nodes(Node *root), which takes the pointer of the root of the given Binary tree and returns the count of its number of nodes.\nExpected Time Complexity: O((LogN)^{2}).\nExpected Auxiliary Space: O(Log N).\nConstraints:\n0 <= N (number of nodes) <= 5 * 10^{4} \n0 <= value of nodes <= 5 * 10^{4}\nThe tree is guaranteed to be complete.", "solutions": ["def countNodes(root):\n if root == None:\n return 0\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "def countNodes(root):\n if root == None:\n return 0\n ln = self.countNodes(root.left)\n rn = self.countNodes(root.right)\n treecount = ln + rn + 1\n return treecount", "def countNodes(root):\n lst = [root]\n A = []\n while lst:\n if lst[0].left:\n lst.append(lst[0].left)\n if lst[0].right:\n lst.append(lst[0].right)\n A.append(lst.pop(0))\n return len(A)", "def get_leftheight(root):\n count = 0\n while root is not None:\n root = root.left\n count += 1\n return count\n\ndef get_rightheight(root):\n count = 0\n while root is not None:\n root = root.right\n count += 1\n return count\n\ndef countNodes(root):\n if root is None:\n return 0\n left_height = self.get_leftheight(root.left)\n right_height = self.get_rightheight(root.right)\n if left_height == right_height:\n return 2 ** (left_height + 1) - 1\n return self.countNodes(root.left) + self.countNodes(root.right) + 1", "def cn(root, k):\n if not root:\n return\n k.append(root.data)\n self.cn(root.right, k)\n self.cn(root.left, k)\n\ndef countNodes(root):\n k = []\n self.cn(root, k)\n return len(k)", "from collections import deque\n\ndef countNodes(root):\n if not root:\n return 0\n left = self.countNodes(root.left)\n right = self.countNodes(root.right)\n return 1 + left + right", "def __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef countNodes(root):\n if not root:\n return 0\n height = 0\n node = root\n while node.left:\n height += 1\n node = node.left\n left = 1\n right = 2 ** height\n while left <= right:\n mid = (left + right) // 2\n if self.exists(root, height, mid):\n left = mid + 1\n else:\n right = mid - 1\n return 2 ** height - 1 + left - 1\n\ndef exists(node, height, pos):\n left = 1\n right = 2 ** height\n for _ in range(height):\n mid = (left + right) // 2\n if pos <= mid:\n node = node.left\n right = mid\n else:\n node = node.right\n left = mid + 1\n return node is not None", "def countNodes(root):\n l = [0]\n\n def fun(root):\n if root:\n l[0] = l[0] + 1\n fun(root.left)\n fun(root.right)\n fun(root)\n return l[0]", "def countNodes(root):\n\n def inorder(root, l):\n if root is None:\n return\n if root.left:\n root.left = inorder(root.left, l)\n l.append(root.data)\n if root.right:\n root.right = inorder(root.right, l)\n l = []\n inorder(root, l)\n return len(l)", "def countNodes(root):\n (l, r) = (0, 0)\n curr = root\n while curr != None:\n curr = curr.left\n l += 1\n curr = root\n while curr != None:\n curr = curr.right\n r += 1\n if l == r:\n return pow(2, l) - 1\n else:\n return self.countNodes(root.left) + self.countNodes(root.right) + 1", "def left_height(root):\n count = 1\n while root:\n count += 1\n root = root.left\n return count\n\ndef right_height(root):\n count = 1\n while root:\n count += 1\n root = root.right\n return count\n\ndef countNodes(root):\n if not root:\n return 0\n left = self.left_height(root.left)\n right = self.right_height(root.right)\n if left == right:\n return 2 ** left - 1\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "def countNodes(root):\n if root == None:\n return []\n q = []\n q.append(root)\n ans = []\n while len(q) != 0:\n size = len(q)\n tmp = []\n while size != 0:\n curr = q.pop(0)\n ans.append(curr.data)\n if curr.left != None:\n q.append(curr.left)\n if curr.right != None:\n q.append(curr.right)\n size -= 1\n return len(ans)", "def countNodes(root):\n ans = 0\n\n def f(root):\n nonlocal ans\n if root is None:\n return\n ans += 1\n f(root.left)\n f(root.right)\n f(root)\n return ans", "def leftHeight(root):\n hight = 0\n while root:\n root = root.left\n hight += 1\n return hight\n\ndef rightHeight(root):\n hight = 0\n while root:\n root = root.right\n hight += 1\n return hight\n\ndef countNodes(root):\n if root == None:\n return 0\n lh = self.leftHeight(root)\n rh = self.rightHeight(root)\n if lh == rh:\n return (1 << lh) - 1\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "def countNodes(root):\n stack = []\n curr = root\n post = []\n while curr != None or len(stack) > 0:\n if curr != None:\n stack.append(curr)\n curr = curr.left\n else:\n temp = stack[-1].right\n if temp == None:\n temp = stack.pop()\n post.append(temp.data)\n while len(stack) > 0 and temp == stack[-1].right:\n temp = stack.pop()\n post.append(temp.data)\n else:\n curr = temp\n return len(post)", "def countNodes(root):\n self.ans = 0\n\n def dfs(root):\n if not root:\n return\n self.ans += 1\n (dfs(root.left), dfs(root.right))\n dfs(root)\n return self.ans", "def countNodes(root):\n res = []\n\n def two(root):\n if not root:\n return\n two(root.left)\n res.append(root.data)\n two(root.right)\n two(root)\n return len(res)", "def countNodes(root):\n if root == None:\n return 0\n else:\n ls = self.countNodes(root.left)\n rs = self.countNodes(root.right)\n return ls + rs + 1", "def countNodes(root):\n if root == None:\n return 0\n if root.left is None and root.right is None:\n return 1\n l = self.countNodes(root.left)\n r = self.countNodes(root.right)\n return l + r + 1", "def countNodes(root):\n if root is not None:\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)\n else:\n return 0", "def countNodes(root):\n if root is None:\n return 0\n leftNodes = self.countNodes(root.left)\n rightNodes = self.countNodes(root.right)\n return leftNodes + rightNodes + 1", "def countNodes(root):\n\n def findLHeight(node):\n h = 0\n while node:\n h += 1\n node = node.left\n return h\n\n def findRHeight(node):\n r = 0\n while node:\n r += 1\n node = node.right\n return r\n\n def f(node):\n if node is None:\n return 0\n l = findLHeight(node)\n r = findRHeight(node)\n if l == r:\n return 2 ** l - 1\n return 1 + f(node.left) + f(node.right)\n return f(root)", "def countNodes(root):\n queue = []\n queue.append(root)\n ans = 0\n while queue:\n node = queue.pop(0)\n ans += 1\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return ans", "def countNodes(root):\n cnt = [0]\n\n def find(root):\n if root:\n cnt[0] += 1\n find(root.left)\n find(root.right)\n return\n find(root)\n return cnt[0]", "def countNodes(root):\n queue = [root]\n val = 0\n while queue:\n level = []\n for i in queue:\n if i == None:\n continue\n val += 1\n level.append(i.left)\n level.append(i.right)\n queue = level\n return val", "def countNodes(root):\n rh = 0\n lh = 0\n a = root\n while a != None:\n lh += 1\n a = a.left\n a = root\n while a != None:\n rh += 1\n a = a.right\n if rh == lh:\n return int(2 ** rh) - 1\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "def gen(root):\n if root.left == None or root.right == None:\n self.bi += 1\n if root.left:\n self.leaf += 1\n if root.right:\n self.leaf += 1\n return\n self.bi += 1\n self.gen(root.left)\n self.gen(root.right)\n\ndef countNodes(root):\n self.leaf = 0\n self.bi = 0\n self.gen(root)\n return self.bi + self.leaf", "def countNodes(root):\n\n def user(root):\n if not root:\n return 0\n return 1 + user(root.left) + user(root.right)\n return user(root)", "def countNodes(root):\n\n def findMaxLevel(node, isLeftMove):\n if node is None:\n return 0\n if isLeftMove:\n return 1 + findMaxLevel(node.left, isLeftMove)\n return 1 + findMaxLevel(node.right, isLeftMove)\n leftMove = findMaxLevel(root, True)\n rightMove = findMaxLevel(root, False)\n if leftMove == rightMove:\n return 2 ** leftMove - 1\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "def countNodes(root):\n if not root:\n return 0\n l = self.findleft(root)\n r = self.findright(root)\n if l == r:\n return 2 ** l - 1\n else:\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)\n\ndef findleft(node):\n if not node:\n return 0\n c = 0\n while node:\n c += 1\n node = node.left\n return c\n\ndef findright(node):\n if not node:\n return 0\n c = 0\n while node:\n c += 1\n node = node.right\n return c", "def countNodes(root):\n q = []\n q.append(root)\n ret = 0\n while q:\n n = len(q)\n ret += n\n while n > 0:\n tmp = q.pop(0)\n if tmp.left:\n q.append(tmp.left)\n if tmp.right:\n q.append(tmp.right)\n n -= 1\n return ret", "def countNodes(root):\n st = [root]\n c = 0\n while st:\n ob = st.pop()\n c += 1\n if ob.left:\n st.append(ob.left)\n if ob.right:\n st.append(ob.right)\n return c", "from collections import deque\n\ndef countNodes(root):\n if not root:\n return 0\n count = 0\n q = deque()\n q.appendleft((root, 1))\n while q:\n count += q[0][1] - q[-1][1] + 1\n temp = deque()\n while q:\n (root, ind) = q.pop()\n if root.left:\n temp.appendleft((root.left, ind * 2))\n if root.right:\n temp.appendleft((root.right, ind * 2 + 1))\n q = temp\n return count", "def lh(root):\n if not root:\n return 0\n return 1 + self.lh(root.left)\n\ndef rh(root):\n if not root:\n return 0\n return 1 + self.rh(root.right)\n\ndef countNodes(root):\n if not root:\n return 0\n lh = self.lh(root)\n rh = self.rh(root)\n if lh == rh:\n return 2 ** lh - 1\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "def countNodes(root):\n\n def count_complete_tree(root):\n if root == None:\n return 0\n (lh, rh) = (0, 0)\n itr = root\n while itr:\n lh += 1\n itr = itr.left\n itr = root\n while itr:\n rh += 1\n itr = itr.right\n if lh == rh:\n import math\n return int(math.pow(2, lh)) - 1\n return 1 + count_complete_tree(root.left) + count_complete_tree(root.right)\n return count_complete_tree(root)", "def countNodes(root):\n global c\n c = 0\n\n def sol(root):\n global c\n if root:\n sol(root.left)\n c = c + 1\n sol(root.right)\n sol(root)\n return c", "def countNodes(root):\n\n def leftheight(root):\n ans = 0\n cur = root\n while cur:\n ans += 1\n cur = cur.left\n return ans\n\n def rightheight(root):\n ans = 0\n cur = root\n while cur:\n ans += 1\n cur = cur.right\n return ans\n\n def find(root):\n if root == None:\n return 0\n left = leftheight(root)\n right = rightheight(root)\n if left == right:\n return 2 ** left - 1\n else:\n return 1 + find(root.left) + find(root.right)\n return find(root)", "def leftheight(root):\n if root == None:\n return\n height = 0\n while root:\n height += 1\n root = root.left\n return height\n\ndef rightheight(root):\n if root == None:\n return 0\n height = 0\n while root:\n height += 1\n root = root.right\n return height\n\ndef countNodes(root):\n if root == None:\n return 0\n lh = leftheight(root)\n rh = rightheight(root)\n if lh == rh:\n return (1 << lh) - 1\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "def countNodes(root):\n if not root:\n return 0\n ls = self.countL(root)\n rs = self.countR(root)\n if ls == rs:\n return 2 ** ls - 1\n else:\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)\n\ndef countL(root):\n if not root:\n return 0\n h = 0\n while root:\n root = root.left\n h += 1\n return h\n\ndef countR(root):\n if not root:\n return 0\n h = 0\n while root:\n root = root.right\n h += 1\n return h", "def countNodes(root):\n if root == None:\n return 0\n else:\n num_left_nodes = self.countNodes(root.left)\n num_right_nodes = self.countNodes(root.right)\n return 1 + num_left_nodes + num_right_nodes", "def countNodes(root):\n if not root:\n return 0\n return self.countNodesUtil(root)\n\ndef countNodesUtil(root):\n if not root:\n return 0\n l = self.countL(root)\n r = self.countR(root)\n if l == r:\n return 2 ** l - 1\n else:\n return 1 + self.countNodesUtil(root.left) + self.countNodesUtil(root.right)\n\ndef countL(node):\n if not node:\n return 0\n lh = 0\n while node:\n lh += 1\n node = node.left\n return lh\n\ndef countR(node):\n if not node:\n return 0\n rh = 0\n while node:\n rh += 1\n node = node.right\n return rh", "from collections import deque\n\ndef countNodes(root):\n queue = deque()\n count = 0\n if not root:\n return 0\n queue.append(root)\n while queue:\n e = queue.pop()\n count += 1\n if e.left:\n queue.append(e.left)\n if e.right:\n queue.append(e.right)\n return count", "def countNodes(root):\n if not root:\n return 0\n l = self.countNodes(root.left)\n r = self.countNodes(root.right)\n return l + r + 1", "def helperleft(curr):\n c = 0\n while curr:\n c += 1\n curr = curr.left\n return c\n\ndef helperright(curr):\n c = 0\n while curr:\n c += 1\n curr = curr.right\n return c\n\ndef countNodes(root):\n if not root:\n return 0\n lh = helperleft(root)\n rh = helperright(root)\n if lh == rh:\n return 2 ** lh - 1\n lc = self.countNodes(root.left)\n rc = self.countNodes(root.right)\n return 1 + lc + rc", "from collections import deque\n\ndef countNodes(root):\n count = 0\n q = deque([root])\n while q:\n n = len(q)\n count += n\n for i in range(n):\n node = q.popleft()\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return count", "def countNodes(root):\n if not root:\n return 0\n\n def lheight(node):\n if not node:\n return 0\n return 1 + lheight(node.left)\n\n def rheight(node):\n if not node:\n return 0\n return 1 + rheight(node.right)\n (l, r) = (lheight(root), rheight(root))\n if l > r:\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)\n else:\n return 2 ** l - 1", "def helper(root):\n if root is None:\n return\n self.count += 1\n self.helper(root.left)\n self.helper(root.right)\n\ndef countNodes(root):\n if root is None:\n return 0\n self.count = 0\n self.helper(root)\n return self.count", "def countNodes(root):\n c = [0]\n\n def count(root):\n if root:\n count(root.left)\n c[0] = c[0] + 1\n count(root.right)\n count(root)\n return c[0]", "def countNodes(root):\n if root == None:\n return 0\n else:\n x = self.countNodes(root.left)\n y = self.countNodes(root.right)\n return x + y + 1", "def countNodes(root):\n if not root:\n return 0\n leftDepth = self.getDepth(root.left)\n rightDepth = self.getDepth(root.right)\n if leftDepth == rightDepth:\n return pow(2, leftDepth) + self.countNodes(root.right)\n else:\n return pow(2, rightDepth) + self.countNodes(root.left)\n\ndef getDepth(root):\n if not root:\n return 0\n return 1 + self.getDepth(root.left)", "def __init__():\n self.c = 0\n\ndef inorder(root):\n if root is None:\n return\n self.c = self.c + 1\n self.inorder(root.left)\n self.inorder(root.right)\n\ndef countNodes(root):\n self.inorder(root)\n return self.c", "def countNodes(root):\n\n def findHeightLeft(node):\n ht = 0\n while node:\n ht += 1\n node = node.left\n return ht\n\n def findHeightRight(node):\n ht = 0\n while node:\n ht += 1\n node = node.right\n return ht\n\n def fn(root):\n if not root:\n return 0\n (lh, rh) = (findHeightLeft(root), findHeightRight(root))\n if lh == rh:\n return (1 << lh) - 1\n return 1 + fn(root.left) + fn(root.right)\n return fn(root)"], "starter_code": "def init(val):\n", "input_output": {"inputs": ["root = [1,2,3,4,5,6]"], "outputs": ["6"]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/count-number-of-nodes-in-a-binary-tree/1", "Expected Auxiliary Space": "O(Log N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O((LogN)^{2}).", "entry_point": "init", "task_id": "TACO_lite/266", "example": [[[[1, 2, 3, 4, 5, 6]]], ["6"]]} +{"requirement": "The [Sharkovsky's Theorem](https://en.wikipedia.org/wiki/Sharkovskii%27s_theorem) involves the following ordering of the natural numbers:\n```math\n3≺5≺7≺9≺ ...\\\\\n≺2·3≺2·5≺2·7≺2·9≺...\\\\\n≺2^n·3≺2^n·5≺2^n·7≺2^n·9≺...\\\\\n≺2^{(n+1)}·3≺2^{(n+1)}·5≺2^{(n+1)}·7≺2^{(n+1)}·9≺...\\\\\n≺2^n≺2^{(n-1)}≺...\\\\\n≺4≺2≺1\\\\\n```\n \nYour task is to complete the function which returns `true` if `$a≺b$` according to this ordering, and `false` otherwise.\n \nYou may assume both `$a$` and `$b$` are non-zero positive integers.", "solutions": ["def sharkovsky(a, b):\n return f(a) < f(b)\n\ndef f(n, p=0):\n while n % 2 == 0:\n n >>= 1\n p += 1\n return (n == 1, p * (-1) ** (n == 1), n)", "def analyse(x):\n n = (b := bin(x)).rstrip('0')\n p = len(b) - len(n)\n return ((n := int(n, 2)) == 1, p * (-1) ** (n == 1), n)\n\ndef sharkovsky(a, b):\n return analyse(a) < analyse(b)", "key = lambda n: [(0, (e := (n & -n)), n // e), (1, -n)][e == n]\nsharkovsky = lambda a, b: key(a) < key(b)", "from math import log\n\ndef decompose(n):\n for p in range(int(log(n, 2)), -1, -1):\n c = n / 2 ** p\n if c == int(c):\n c = int(c)\n return (c, p)\n\ndef sharkovsky(a, b):\n (coef_a, exp_a) = decompose(a)\n (coef_b, exp_b) = decompose(b)\n if coef_a == 1 and coef_b == 1:\n return exp_b < exp_a\n if coef_a == 1 or coef_b == 1:\n return coef_b == 1\n if exp_a != exp_b:\n return exp_a < exp_b\n if exp_a == exp_b:\n return coef_a < coef_b\n return False", "def div2(n):\n i = 0\n while n % 2 == 0:\n n = n / 2\n i += 1\n return (n, i)\n\ndef sharkovsky(a, b):\n (n1, rem1) = div2(a)\n (n2, rem2) = div2(b)\n if n1 == 1 and n2 == 1:\n return not rem1 < rem2\n elif n1 == 1 and n2 != 1:\n return False\n elif n1 != 1 and n2 == 1:\n return True\n elif rem1 == rem2:\n return n1 < n2\n else:\n return rem1 < rem2", "def sharkovsky(a, b):\n if b == a:\n return False\n elif b == 1:\n return True\n elif a == 1:\n return False\n elif a % 2 == 1:\n if b % 2 == 0:\n return True\n elif a < b:\n return True\n else:\n return False\n elif b % 2 == 1:\n return False\n else:\n result = sharkovsky(a / 2, b / 2)\n return result", "def sharkovsky(a, b):\n\n def key(n):\n even = n & -n\n return [(even, n // even), (float('inf'), -n)][n == even]\n return key(a) < key(b)", "def sharkovsky(a, b):\n if a == b:\n return False\n if a == 1:\n return False\n if b == 1:\n return a > 1\n c = get_highest_power_of_two_divisible_by_number(a)\n d = get_highest_power_of_two_divisible_by_number(b)\n if c == d:\n a //= c\n b //= d\n if a != 1 and b == 1:\n return True\n elif a == 1:\n return False\n else:\n return a < b\n elif c < d:\n a //= c\n b //= d\n if a == 1 and b != 1:\n return False\n elif a == 1 and b == 1:\n return False\n else:\n return True\n else:\n a //= c\n b //= d\n if a != 1 and b == 1:\n return True\n elif a == 1 and b == 1:\n return True\n else:\n return False\n\ndef get_highest_power_of_two_divisible_by_number(number):\n twos = []\n while number % 2 == 0:\n twos.append(2)\n number //= 2\n result = 2 ** len(twos)\n return result\n\ndef is_power_of_two(number):\n twos = []\n while number % 2 == 0:\n twos.append(2)\n number //= 2\n twos = remove_duplicates(twos)\n return twos == [2]\n\ndef remove_duplicates(lst):\n result = []\n for i in lst:\n if i not in result:\n result.append(i)\n return result", "import numpy as np\n\ndef sharkovsky(a, b):\n l = []\n for i in range(0, int(np.log2(max(a, b))) + 3):\n for j in range(3, max(a, b) + 1, 2):\n if a == 2 ** i * j:\n l.append(a)\n a = b\n if len(l) >= 2:\n return True\n for n in range(int(np.log2(max(a, b))) + 3, -1, -1):\n if a == 2 ** n:\n l.append(a)\n a = b\n if len(l) >= 2:\n return True\n return False", "def sharkovsky(a, b):\n i = 0\n while a % 2 == 0:\n a //= 2\n i += 1\n j = 0\n while b % 2 == 0:\n b //= 2\n j += 1\n if a == 1 and b == 1:\n return i > j\n elif a == 1:\n return False\n elif b == 1:\n return True\n elif i == j:\n return a < b\n else:\n return i < j", "def sharkovsky(a, b):\n\n def Answer(n):\n con = True\n p = 0\n while con == True:\n if n % 2 != 0:\n ans = (p, n)\n con = False\n else:\n n = n / 2\n p += 1\n return ans\n ans_a = Answer(a)\n ans_b = Answer(b)\n if ans_a[1] == 1 and ans_b[1] != 1:\n return False\n elif ans_a[1] != 1 and ans_b[1] == 1:\n return True\n elif ans_a[1] == 1 and ans_b[1] == 1:\n return ans_a[0] > ans_b[0]\n elif ans_a[0] > ans_b[0]:\n return False\n elif ans_a[0] < ans_b[0]:\n return True\n else:\n return ans_a[1] < ans_b[1]", "def sharkovsky(a, b):\n if a % 2 == 0 and b % 2 == 0:\n while a % 2 == 0 and b % 2 == 0:\n a = a / 2\n b = b / 2\n if b % 2 == 0:\n if a == 1:\n return 1 == 2\n else:\n return 1 == 1\n elif a % 2 == 0:\n if b == 1:\n return 1 == 1\n else:\n return 1 == 2\n elif b == 1:\n return 1 == 1\n elif a == 1:\n return 1 == 2\n else:\n return a < b", "def sharkovsky(a, b):\n while True:\n if a == 1 or b == 1:\n return a != 1\n if a % 2 or b % 2:\n return a % 2 == 1 and (not (b % 2 == 1 and a >= b))\n a /= 2\n b /= 2", "import math\n\ndef splitnumber(x):\n counter = 0\n while x % 2 == 0:\n counter += 1\n x = x / 2\n return [counter, x]\n\ndef sharkovsky(a, b):\n x = splitnumber(a)\n y = splitnumber(b)\n if x[1] == 1 and y[1] == 1:\n return a > b\n elif x[1] != 1 and y[1] == 1:\n return True\n elif x[1] == 1 and y[1] != 1:\n return False\n elif x[0] == y[0]:\n return a < b\n else:\n return x[0] < y[0]\n return False", "import math\n\ndef max2pow(n):\n even = 1\n while n % 2 == 0:\n even *= 2\n n /= 2\n return (even, n)\n\ndef sharkovsky(a, b):\n if a == b:\n return False\n (even_a, odd_a) = max2pow(a)\n (even_b, odd_b) = max2pow(b)\n if odd_a == 1 and odd_b == 1:\n return even_a > even_b\n if odd_a == 1 or odd_b == 1:\n return odd_b == 1\n if even_a == even_b:\n return odd_a < odd_b\n return even_a < even_b", "import math\n\ndef sharkovsky(a, b):\n if a % 2 != b % 2:\n if b == 1:\n return True\n elif (a % 2 == 1) & (a != 1):\n return True\n else:\n return False\n elif a % 2 == 1:\n if b == 1:\n return True\n elif (a < b) & (a != 1):\n return True\n else:\n return False\n elif (math.pow(2, int(math.log2(a))) == a) & (math.pow(2, int(math.log2(b))) == b) & (a > b):\n return True\n elif math.pow(2, int(math.log2(a))) != a:\n if math.pow(2, int(math.log2(b))) == b:\n return True\n else:\n i = 0\n while a % 2 == 0 and b % 2 == 0:\n i += 1\n a = a / 2\n b = b / 2\n if b % 2 == 0:\n return True\n elif a % 2 == 0:\n return False\n elif a < b:\n return True\n else:\n return False\n else:\n return False", "def sharkovsky(a, b):\n a_red = a\n a_rem = a % 2\n a_count = 0\n while a_rem == 0:\n a_count = a_count + 1\n a_red = int(a_red / 2)\n a_rem = a_red % 2\n b_red = b\n b_rem = b % 2\n b_count = 0\n while b_rem == 0:\n b_count = b_count + 1\n b_red = int(b_red / 2)\n b_rem = b_red % 2\n if a_red > 1 and b_red > 1:\n if a_count != b_count:\n return a_count < b_count\n else:\n return a_red < b_red\n elif a_red == 1 and b_red > 1:\n return False\n elif a_red > 1 and b_red == 1:\n return True\n else:\n return a_count > b_count", "def factorTwos(n):\n twos = 0\n while not n % 2:\n n //= 2\n twos += 1\n return (twos, n)\n\ndef sharkovsky(a, b):\n (twosA, remA) = factorTwos(a)\n (twosB, remB) = factorTwos(b)\n if remA == 1:\n return remB == 1 and twosA > twosB\n elif remB == 1:\n return remA != 1 or twosA > twosB\n elif twosA == twosB:\n return remA < remB\n else:\n return twosA < twosB"], "starter_code": "def sharkovsky(a, b):\n", "input_output": {"fn_name": "sharkovsky", "inputs": [[18, 12], [3, 9], [10, 16], [1, 22], [32, 1024], [17, 17]], "outputs": [[true], [true], [true], [false], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5f579a3b34d5ad002819eb9e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sharkovsky", "task_id": "TACO_lite/288", "example": [[], []]} +{"requirement": "A very easy task for you!\n\nYou have to create a method, that corrects a given date string.\nThere was a problem in addition, so many of the date strings are broken.\nDate-Format is european. That means \"DD.MM.YYYY\".\n\n\nSome examples:\n\n\"30.02.2016\" -> \"01.03.2016\"\n\"40.06.2015\" -> \"10.07.2015\"\n\"11.13.2014\" -> \"11.01.2015\"\n\"99.11.2010\" -> \"07.02.2011\"\n\nIf the input-string is null or empty return exactly this value!\nIf the date-string-format is invalid, return null.\n\nHint: Correct first the month and then the day!\n\nHave fun coding it and please don't forget to vote and rank this kata! :-) \n\nI have created other katas. Have a look if you like coding and challenges.", "solutions": ["import re\nfrom datetime import date, timedelta\n\ndef date_correct(text):\n if not text:\n return text\n try:\n (d, m, y) = map(int, re.match('^(\\\\d{2})\\\\.(\\\\d{2})\\\\.(\\\\d{4})$', text).groups())\n (mo, m) = divmod(m - 1, 12)\n return (date(y + mo, m + 1, 1) + timedelta(days=d - 1)).strftime('%d.%m.%Y')\n except AttributeError:\n return None", "import datetime as dt\nimport re\n\ndef date_correct(date):\n if isinstance(date, str) and re.fullmatch('\\\\d\\\\d\\\\.\\\\d\\\\d\\\\.\\\\d{4}', date):\n (d, m, y) = map(int, date.split('.'))\n (nM, m) = divmod(m - 1, 12)\n y += nM\n m += 1\n d = dt.date(y, m, 1) + dt.timedelta(days=d - 1)\n return f'{d.day:02}.{d.month:02}.{d.year:02}'\n if date == '':\n return ''", "from datetime import date, timedelta\nget_date = __import__('re').compile('(\\\\d\\\\d)\\\\.(\\\\d\\\\d)\\\\.(\\\\d\\\\d\\\\d\\\\d)').search\n\ndef date_correct(my_date):\n if not my_date:\n return my_date\n try:\n (d, m, y) = map(int, get_date(my_date).groups())\n except AttributeError:\n return\n return (date(y + (m - 1) // 12, (m - 1) % 12 + 1, 1) + timedelta(d - 1)).strftime('%d.%m.%Y')", "import datetime\nimport re\n\ndef date_correct(date):\n if not date:\n return date\n if not re.fullmatch('(\\\\d\\\\d\\\\.){2}\\\\d{4}', date):\n return None\n (d, m, y) = [int(x) for x in date.split('.')]\n if m > 12:\n y += m // 12\n m %= 12\n if not m:\n m = 12\n y -= 1\n return (datetime.datetime(year=y, month=m, day=1) + datetime.timedelta(days=d - 1)).strftime('%d.%m.%Y')", "from datetime import date, timedelta\nimport re\n\ndef date_correct(s):\n if s == '':\n return ''\n try:\n m = re.match('\\\\A(\\\\d{2})\\\\.(\\\\d{2})\\\\.(\\\\d{4})\\\\Z', s)\n except:\n return None\n if not m:\n return None\n (d, m, y) = map(int, m.groups())\n d -= 1\n (cy, m) = divmod(m - 1, 12)\n return (date(y + cy, m + 1, 1) + timedelta(d)).strftime('%d.%m.%Y')", "def date_correct(date):\n if date in ('', 0, None):\n return date\n from re import findall\n date = findall('\\\\A(\\\\d{2})\\\\.(\\\\d{2})\\\\.(\\\\d{4})\\\\Z', date)\n if len(date) == 0:\n return None\n import datetime\n date = [int(x) for x in date[0][::-1]]\n date[0] += (date[1] - 1) // 12\n date[1] = (date[1] - 1) % 12 + 1\n newdate = datetime.date(date[0], date[1], 1)\n newdate += datetime.timedelta(days=date[2] - 1)\n return '{0:02d}.{1:02d}.{2}'.format(newdate.day, newdate.month, newdate.year)", "from re import match\nfrom datetime import date as ymd, timedelta\ndate_correct = lambda date: '' if date == '' else None if date == None or not match('\\\\d\\\\d\\\\.\\\\d\\\\d\\\\.\\\\d{4}', date or '') else (lambda d, m, y: (ymd(y + (m - 1) // 12, (m - 1) % 12 + 1, 1) + timedelta(d - 1)).strftime('%d.%m.%Y'))(*map(int, date.split('.')))", "from datetime import datetime, timedelta\nfrom re import fullmatch\n\ndef date_correct(date):\n if isinstance(date, str):\n if not date:\n return ''\n if fullmatch('\\\\d{2}\\\\.\\\\d{2}\\\\.\\\\d{4}', date):\n (day, month, year) = map(int, date.split('.'))\n (extra_year, month) = divmod(month - 1, 12)\n return (datetime(year + extra_year, month + 1, 1) + timedelta(day - 1)).strftime('%d.%m.%Y')", "import re\n\ndef date_correct(date):\n if not date:\n return date\n days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n if not bool(re.match('\\\\d{2}\\\\.\\\\d{2}\\\\.\\\\d{4}', date)):\n return None\n (d, m, y) = list(map(int, date.split('.')))\n while m > 12 or d > days[m - 1]:\n y += (m - 1) // 12\n m = (m - 1) % 12 + 1\n if y % 4 == 0 and y % 100 != 0 or y % 400 == 0:\n days[1] = 29\n else:\n days[1] = 28\n if d > days[m - 1]:\n d -= days[m - 1]\n m += 1\n return '{:02}.{:02}.{}'.format(d, m, y)"], "starter_code": "def date_correct(date):\n", "input_output": {"fn_name": "date_correct", "inputs": [[null], [""], ["01112016"], ["01,11,2016"], ["0a.1c.2016"], ["03.12.2016"], ["30.02.2016"], ["40.06.2015"], ["11.13.2014"], ["33.13.2014"], ["99.11.2010"]], "outputs": [[null], [""], [null], [null], [null], ["03.12.2016"], ["01.03.2016"], ["10.07.2015"], ["11.01.2015"], ["02.02.2015"], ["07.02.2011"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Parsing"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5787628de55533d8ce000b84", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "date_correct", "task_id": "TACO_lite/234", "example": [[["30.02.2016"], ["40.06.2015"], ["11.13.2014"], ["99.11.2010"]], ["01.03.2016", "10.07.2015", "11.01.2015", "07.02.2011"]]} +{"requirement": "Given 6 numbers a,b,c,d,e,f. Find the last digit of (a^{b})*(c^{d})*(e^{f}).\n \nExample 1:\nInput:\na = 3 \nb = 66 \nc = 6 \nd = 41 \ne = 7 \nf = 53\nOutput:\n8\nExplanation:\nThe last digit of the \nvalue obtained after \nsolving the above \nequation is 8.\n \n \nExample 2:\nInput:\na = 1 \nb = 1 \nc = 1 \nd = 1 \ne = 1 \nf = 1\nOutput:\n1\nExplanation:\nThe last digit of the \nvalue obtained after \nsolving the above \nequation is 1.\n \n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function theLastDigit() which takes 6 integers a, b, c, d, e, and f and returns the last digit of the value obtained from the equation.\n \nExpected Time Complexity: O(sqrt(N))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= a,b,c,d,e,f <= 10^{9}", "solutions": ["def thelastdigit(a, b, c, d, e, f):\n b %= 4\n f %= 4\n d %= 4\n if not b:\n b = 4\n if not f:\n f = 4\n if not d:\n d = 4\n return (a % 10) ** b * (c % 10) ** d * (e % 10) ** f % 10"], "starter_code": "def thelastdigit (a,b,c,d,e,f):\n", "input_output": {"inputs": ["a = 3 \nb = 66 \nc = 6 \nd = 41 \ne = 7 \nf = 53", "a = 1 \nb = 1 \nc = 1 \nd = 1 \ne = 1 \nf = 1"], "outputs": ["8", "1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "number-theory", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory", "Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/find-unit-digit-in-a-product2059/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(sqrt(N))", "entry_point": "thelastdigit", "task_id": "TACO_lite/255", "example": [[[3, 66, 6, 41, 7, 53], [1, 1, 1, 1, 1, 1]], ["8", "1"]]} +{"requirement": "Write a function that gets a sequence and value and returns `true/false` depending on whether the variable exists in a multidimentional sequence.\n\nExample:\n```\nlocate(['a','b',['c','d',['e']]],'e'); // should return true\nlocate(['a','b',['c','d',['e']]],'a'); // should return true\nlocate(['a','b',['c','d',['e']]],'f'); // should return false\n```", "solutions": ["def locate(seq, value):\n for s in seq:\n if s == value or (isinstance(s, list) and locate(s, value)):\n return True\n return False", "def locate(seq, value):\n f = 0\n for e in seq:\n if type(e) == list and (not f):\n f = locate(e, value)\n elif e == value:\n f = 1\n return f", "def flatten(seq):\n for e in seq:\n if isinstance(e, list):\n yield from flatten(e)\n yield e\n\ndef locate(seq, value):\n return any((e == value for e in flatten(seq)))", "def locate(arr, item):\n return item in arr or any((isinstance(e, (list, tuple)) and locate(e, item) for e in arr))", "def locate(seq, value):\n if isinstance(seq, (tuple, list)):\n return any((locate(x, value) for x in seq))\n return seq == value", "def locate(seq, value):\n clean = []\n return value in unfold(clean, seq)\n\ndef unfold(clean, seq):\n for s in seq:\n if type(s) == str:\n clean.append(s)\n else:\n clean = list(set(unfold(clean, s)))\n return clean", "def locate(seq, v):\n return any((s for s in seq if s == v or (isinstance(s, list) and locate(s, v))))", "def locate(seq, value):\n for x in seq:\n if x == value:\n return True\n if isinstance(x, list):\n if locate(x, value) == True:\n return True\n return False", "locate = l = lambda a, x: any((l(e, x) if [] == e * 0 else e == x for e in a))", "def locate(seq, value):\n queue = [e for e in seq]\n while len(queue):\n el = queue.pop(0)\n if type(el) is list:\n queue = queue + el\n elif el == value:\n return True\n return False"], "starter_code": "def locate(seq, value):\n", "input_output": {"fn_name": "locate", "inputs": [[["a", "b", ["c", "d", ["e"]]], "a"], [["a", "b", ["c", "d", ["e"]]], "d"], [["a", "b", ["c", "d", ["e"]]], "e"], [["a", "b", ["c", "d", ["e"]]], "f"], [["a", "b", ["c", "d", ["e", ["a", "b", ["c", "d", ["e4"]]]]]], "e4"], [["a", "b", ["c", "d", ["e", ["a", "b", ["c", "d", ["e", ["a", "b", ["c", "d", ["e4", ["a", "b", ["c", "d", ["e", ["a", "b", ["c", "d", ["e", ["a", "b", ["c", "d", ["e14"]]]]]]]]]]]]]]]]]], "e"]], "outputs": [[true], [true], [true], [false], [true], [true]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms"], "name": null, "source": "codewars", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/52840d2b27e9c932ff0016ae", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "locate", "task_id": "TACO_lite/258", "example": [[], []]} +{"requirement": "Given two numbers n and x, find out the total number of ways n can be expressed as the sum of the Xth power of unique natural numbers. As the total number of ways can be very large, so return the number of ways modulo 10^{9 }+ 7. \nExample 1:\nInput: \nn = 10, x = 2\nOutput: \n1 \nExplanation: \n10 = 1^{2} + 3^{2}, Hence total 1 possibility. \nExample 2:\nInput: \nn = 100, x = 2\nOutput: \n3\nExplanation: \n100 = 10^{2} \n6^{2} + 8^{2} and 1^{2} + 3^{2} + 4^{2} + 5^{2} + 7^{2} \nHence total 3 possibilities. \nYour Task: \nYou don't need to read input or print anything. Complete the function numOfWays() which takes n and x as input parameters and returns the total number of ways n can be expressed as the sum of xth power of unique natural numbers.\nExpected Time Complexity: O(n^{2}logn)\nExpected Auxiliary Space: O(n)\nConstraints:\n1 <= n <= 10^{3}\n1 <= x <= 5", "solutions": ["def numofways(n, x):\n M = int(1000000000.0) + 7\n p = []\n i = 1\n while True:\n if pow(i, x) <= n:\n p.append(pow(i, x))\n i += 1\n else:\n break\n dp = [0] * (n + 1)\n dp[0] = 1\n for a in p:\n for i in range(n, -1, -1):\n if i - a >= 0:\n dp[i] = (dp[i - a] + dp[i]) % M\n return dp[n]", "import math\n\ndef numofways(n, x):\n dp = [0] * (n + 1)\n dp[0] = 1\n MOD = 1000000000.0 + 7\n for i in range(1, n + 1):\n for j in range(n, i - 1, -1):\n s = i ** x\n if j >= s:\n dp[j] = (dp[j] + dp[j - s]) % MOD\n return int(dp[n])", "from collections import defaultdict\n\ndef numofways(n, x):\n d = defaultdict(lambda : 0)\n d[0] = 1\n i = 1\n while i ** x <= n:\n temp = defaultdict(lambda : 0)\n for item in d:\n summa = item + i ** x\n if summa <= n:\n temp[summa] += d[item]\n for item in temp:\n d[item] = (d[item] + temp[item]) % (10 ** 9 + 7)\n i += 1\n return d[n]", "def numofways(n, x):\n list = []\n list.append(1)\n for i in range(1, n + 1):\n list.append(0)\n for i in range(1, n + 1):\n for j in range(n, i - 1, -1):\n a = i ** x\n if j >= a:\n list[j] = (list[j] + list[j - a]) % (10 ** 9 + 7)\n return list[n]", "import math\n\ndef rec(n, x):\n dp = [0 for i in range(n + 1)]\n dp[0] = dp[1] = 1\n max = int(pow(n, 1.0 / x))\n for i in range(2, max + 1):\n curr = pow(i, x)\n for j in range(n, curr - 1, -1):\n dp[j] += dp[j - curr]\n return dp[n] % (pow(10, 9) + 7)\n\ndef numofways(n, x):\n return self.rec(n, x)", "def numofways(n, x):\n d = [i for i in range(1, int(n ** (1 / x)) + 1)]\n n1 = len(d)\n t = [[0 for i in range(n + 1)] for j in range(n1 + 1)]\n for i in range(n1 + 1):\n for j in range(n + 1):\n if i == 0 or j == 0:\n if i == 0:\n t[i][j] = 0\n if j == 0:\n t[i][j] = 1\n elif d[i - 1] ** x <= j:\n t[i][j] = (t[i - 1][j - d[i - 1] ** x] + t[i - 1][j]) % (10 ** 9 + 7)\n else:\n t[i][j] = t[i - 1][j]\n return t[-1][-1] % (10 ** 9 + 7)", "def numofways(n, x):\n\n def fun(n, x, s, k):\n if s == n:\n return 1\n if s > n or k == 0:\n return 0\n if dp[s][k] != -1:\n return dp[s][k]\n ans = (fun(n, x, s, k - 1) + fun(n, x, s + k ** x, k - 1)) % 1000000007\n dp[s][k] = ans\n return ans\n k = int(pow(n, 1 / x))\n s = 0\n dp = []\n for i in range(n):\n dp.append([-1] * (k + 1))\n ans = fun(n, x, s, k)\n return ans", "def express(x, target, i, dp):\n if target == 0:\n return 1\n if i < 0:\n return 0\n if dp[target][i] != -1:\n return dp[target][i]\n pa = pow(i, x)\n if pa <= target:\n dp[target][i] = self.express(x, target - pa, i - 1, dp) + self.express(x, target, i - 1, dp)\n return dp[target][i]\n else:\n dp[target][i] = self.express(x, target, i - 1, dp)\n return dp[target][i]\n\ndef numofways(n, x):\n mod = 10 ** 9 + 7\n dp = [[-1] * 1001 for _ in range(1001)]\n return self.express(x, n, n, dp) % mod", "def numHelper(i, n, x, dp):\n if i ** x > n:\n return 0\n if i ** x == n:\n return 1\n if dp[n - i ** x][i + 1] == -1:\n tempAns = numHelper(i + 1, n - i ** x, x, dp)\n dp[n - i ** x][i + 1] = tempAns\n else:\n tempAns = dp[n - i ** x][i + 1]\n if dp[n][i + 1] == -1:\n tempAns2 = numHelper(i + 1, n, x, dp)\n dp[n][i + 1] = tempAns2\n else:\n tempAns2 = dp[n][i + 1]\n return tempAns + tempAns2\n\ndef numofways(n, x):\n ii = int(n ** (1 / x)) + 1\n dp = [[-1 for i in range(ii + 10)] for j in range(n + 10)]\n count = numHelper(1, n, x, dp)\n return count % (7 + 10 ** 9)", "def numofways(n, x):\n dp = [0 for i in range(n + 1)]\n dp[0] = 1\n MOD = 10 ** 9 + 7\n for i in range(1, n + 1):\n for j in range(n, i - 1, -1):\n y = i ** x\n if j >= y:\n dp[j] = (dp[j] + dp[j - y]) % MOD\n return dp[n]", "import math\n\ndef numofways(n, x):\n mod = 1000000000.0 + 7\n dp = [0] * (n + 1)\n dp[0] = dp[1] = 1\n for i in range(2, n + 1):\n for j in range(n, i - 1, -1):\n y = i ** x\n if y <= j:\n dp[j] = int((dp[j] + dp[j - y]) % mod)\n return dp[n]", "import math\n\ndef numofways(n, x):\n i = 1\n p = []\n while math.pow(i, x) <= n:\n p.append(int(math.pow(i, x)))\n i += 1\n dp = [[-1 for i in range(0, n + 1)] for j in range(0, len(p))]\n mod = pow(10, 9) + 7\n\n def back(i, n, x, s, p):\n if s == n:\n return 1\n if s > n or i > len(p) - 1:\n return 0\n if dp[i][s] != -1:\n return dp[i][s]\n dp[i][s] = back(i + 1, n, x, s, p) + back(i + 1, n, x, s + p[i], p)\n return dp[i][s] % mod\n return back(0, n, x, 0, p) % mod", "def numofways(n, x):\n\n def solve(n, x, curr_val, dp):\n mod = 1000000007\n if n == 0:\n return 1\n if n < 0 or curr_val <= 0:\n return 0\n if dp[n][curr_val] != -1:\n return dp[n][curr_val]\n dp[n][curr_val] = (solve(n - curr_val ** x, x, curr_val - 1, dp) + solve(n, x, curr_val - 1, dp)) % mod\n return dp[n][curr_val]\n st_val = int(n ** (1.0 / x))\n dp = [[-1] * (st_val + 1) for _ in range(n + 1)]\n return solve(n, x, st_val, dp)", "def numofways(n, x):\n dp = [0] * (n + 1)\n dp[0] = 1\n dp[1] = 1\n maxLimit = int(n ** (1 / x))\n for i in range(2, maxLimit + 1):\n curr = i ** x\n for j in range(n, curr - 1, -1):\n dp[j] += dp[j - curr]\n mm = 1000000007\n return dp[n] % mm", "def numofways(n, x):\n dp = [0] * (n + 1)\n dp[0] = 1\n mod = 1000000007\n for i in range(1, n + 1):\n for j in range(n, i - 1, -1):\n y = pow(i, x)\n if j >= y:\n dp[j] = (dp[j] + dp[j - y]) % mod\n return dp[n]", "def numofways(n, x):\n dp = [0 for _ in range(n + 1)]\n dp[0] = 1\n M = pow(10, 9) + 7\n for i in range(1, n + 1):\n for j in range(n, i - 1, -1):\n y = pow(i, x)\n if j >= y:\n dp[j] = (dp[j] + dp[j - y]) % M\n return dp[n]"], "starter_code": "def numofways(n, x):\n", "input_output": {"inputs": ["n = 10, x = 2", "n = 100, x = 2"], "outputs": ["1", "3"]}, "difficulty": "MEDIUM", "raw_tags": ["Recursion", "Algorithms", "Dynamic Programming", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Mathematics", "Complete search"], "skill_types": ["Dynamic programming", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/express-as-sum-of-power-of-natural-numbers5647/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n^{2}logn)", "entry_point": "numofways", "task_id": "TACO_lite/271", "example": [[[10, 2], [100, 2]], ["1", "3"]]} +{"requirement": "Your job is to change the given string `s` using a non-negative integer `n`.\n\nEach bit in `n` will specify whether or not to swap the case for each alphabetic character in `s`: if the bit is `1`, swap the case; if its `0`, leave it as is. When you finished with the last bit of `n`, start again with the first bit.\n\nYou should skip the checking of bits when a non-alphabetic character is encountered, but they should be preserved in their original positions.\n\n## Examples\n\n```\nswap('Hello world!', 11) --> 'heLLO wORLd!'\n```\n...because `11` is `1011` in binary, so the 1st, 3rd, 4th, 5th, 7th, 8th and 9th alphabetical characters have to be swapped:\n```\nH e l l o w o r l d !\n1 0 1 1 1 0 1 1 1 0\n^ ^ ^ ^ ^ ^ ^\n```\n\nMore examples:\n```\nswap(\"gOOd MOrniNg\", 7864) --> \"GooD MorNIng\"\nswap('', 11345) --> ''\nswap('the lord of the rings', 0) --> 'the lord of the rings'\n```", "solutions": ["from itertools import cycle\n\ndef swap(s, n):\n b = cycle(bin(n)[2:])\n return ''.join((c.swapcase() if c.isalpha() and next(b) == '1' else c for c in s))", "from itertools import cycle\n\ndef swap(s, n):\n doSwap = cycle(map(int, f'{n:b}'))\n return ''.join((c.swapcase() if c.isalpha() and next(doSwap) else c for c in s))", "def swap(s, n):\n n = str(bin(n))[2:]\n index = 0\n new_s = ''\n for letter in s:\n if letter.isalpha():\n if n[index % len(n)] == '1':\n new_s += letter.swapcase()\n else:\n new_s += letter\n index += 1\n else:\n new_s += letter\n return new_s", "from itertools import cycle\n\ndef swap(s, n):\n binary = cycle(bin(n)[2:])\n return ''.join((char.swapcase() if char.isalpha() and next(binary) == '1' else char for char in s))", "from itertools import cycle\n\ndef swap(s, n):\n it = cycle(bin(n)[2:])\n return ''.join((x.swapcase() if x.isalpha() and next(it) == '1' else x for x in s))", "def swap(s, n):\n (bits, r, c) = (bin(n)[2:], '', 0)\n for i in s:\n r += [i, i.swapcase()][int(bits[c % len(bits)])]\n c += i.isalpha()\n return r", "def swap(s, n):\n n = str(bin(n))[2:]\n words = list(s)\n binary_mult = str(n) * len(s)\n bn_words = list(binary_mult)\n result = []\n for (i, x) in enumerate(words):\n if not x.isalpha():\n bn_words.insert(i, x)\n if bn_words[i] == '1':\n result.append(words[i].swapcase())\n else:\n result.append(words[i])\n return ''.join(result)", "from itertools import cycle\n\ndef swap(s, n):\n return (lambda N: ''.join((e if not e.isalpha() else (e, e.swapcase())[next(N)] for e in s)))(cycle(map(int, bin(n)[2:])))", "from itertools import cycle\n\ndef swap(s, n):\n it = cycle(map(int, format(n, 'b')))\n return ''.join((c.swapcase() if c.isalpha() and next(it) else c for c in s))"], "starter_code": "def swap(s,n):\n", "input_output": {"fn_name": "swap", "inputs": [["Hello world!", 11], ["the quick broWn fox leapt over the fence", 9], ["eVerybody likes ice cReam", 85], ["gOOd MOrniNg", 7864], ["how are you today?", 12345], ["the lord of the rings", 0], ["", 11345]], "outputs": [["heLLO wORLd!"], ["The QUicK BrowN foX LeaPT ovER thE FenCE"], ["EVErYbODy LiKeS IcE creAM"], ["GooD MorNIng"], ["HOw are yoU TOdaY?"], ["the lord of the rings"], [""]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5f3afc40b24f090028233490", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "swap", "task_id": "TACO_lite/160", "example": [[["Hello world!", 11], ["gOOd MOrniNg", 7864], ["", 11345], ["the lord of the rings", 0]], ["heLLO wORLd!", "GooD MorNIng", "", "the lord of the rings"]]} +{"requirement": "There are Infinite People Standing in a row, indexed from 1.\nA person having index 'i' has strength of (i*i).\nYou have Strength 'P'. You need to tell what is the maximum number of People You can Kill With your Strength P.\nYou can only Kill a person with strength 'X' if P >= 'X' and after killing him, Your Strength decreases by 'X'. \n \nExample 1:\nInput:\nN = 14\nOutput: 3\nExplanation:\nThe strengths of people is 1, 4, 9, 16, .... \nand so on. WE can kill the first 3 person , \nafter which our Power becomes 0 and we cant \nkill anyone else. So answer is 3\n \nExample 2:\nInput:\nN = 10\nOutput: 2\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function killinSpree() which takes the integer N as input parameters and returns the maximum Number of People You can kill.\nExpected Time Complexity: O(log(n))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 ≤ T ≤ 10^{3}\n1 ≤ N ≤ 10^{12}", "solutions": ["def killinspree(n):\n p = lambda n: n * (n + 1) * (2 * n + 1) // 6\n (lo, hi) = (0, n + 1)\n while lo < hi:\n mi = lo + (hi - lo) // 2\n if p(mi) > n:\n hi = mi\n else:\n lo = mi + 1\n return lo - 1", "def killinspree(n):\n\n def _solve(x):\n return x * (x + 1) * (2 * x + 1) // 6\n (L, R) = (0, 20000)\n while L < R:\n m = (L + R) // 2\n if _solve(m) <= n:\n L = m + 1\n else:\n R = m\n return L - 1", "def killinspree(n):\n (L, R) = (1, 10 ** 9)\n ans = None\n while L <= R:\n M = L + (R - L) // 2\n if M * (M + 1) * (2 * M + 1) // 6 <= n:\n ans = M\n L = M + 1\n else:\n R = M - 1\n return ans", "def valid(k, n):\n return k * (k + 1) * (2 * k + 1) // 6 <= n\n\ndef killinspree(n):\n lower = 1\n upper = n\n while lower < upper - 1:\n candidate = (upper + lower) // 2\n if self.valid(candidate, n):\n lower = candidate\n else:\n upper = candidate\n return lower", "def killinspree(n):\n low = 1\n high = 1000000\n count = 0\n while low <= high:\n mid = low + (high - low) // 2\n val = mid * (mid + 1) * (2 * mid + 1) // 6\n if val <= n:\n ans = mid\n low = mid + 1\n else:\n high = mid - 1\n return ans", "def killinspree(n):\n low = 0\n high = 1000000000000000\n while low <= high:\n mid = low + (high - low) // 2\n value = mid * (mid + 1) * (2 * mid + 1) // 6\n if value <= n:\n ans = mid\n low = mid + 1\n else:\n high = mid - 1\n return ans", "def killinspree(n):\n l = 1\n h = 100000000.0\n a = 0\n while l <= h:\n m = l + (h - l) // 2\n r = m * (m + 1) * (2 * m + 1) // 6\n if n < r:\n h = m - 1\n else:\n a = m\n l = m + 1\n return int(a)", "arr = [0]\nimport bisect\n\ndef killinspree(n):\n self.helper(n)\n return bisect.bisect(arr, n) - 1\n\ndef helper(n):\n i = len(arr)\n summa = arr[-1]\n while summa < n:\n summa += i ** 2\n i += 1\n arr.append(summa)\n return", "def killinspree(n):\n start = 1\n end = 10 ** 6\n res = 0\n while start <= end:\n mid = start + (end - start) // 2\n value = mid * (mid + 1) * (2 * mid + 1) // 6\n if value == n:\n res = mid\n break\n elif value < n:\n res = mid\n start = mid + 1\n else:\n end = mid - 1\n return res", "def totalStrengthReq(mid):\n return mid * (mid + 1) * (2 * mid + 1) // 6\n\ndef killinspree(n):\n (lo, hi) = (1, n)\n ans = -1\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n x = totalStrengthReq(mid)\n if n >= x:\n ans = mid\n lo = mid + 1\n else:\n hi = mid - 1\n return ans", "def strength(mid):\n return mid * (mid + 1) * (2 * mid + 1) / 6\n\ndef killinspree(n):\n (lo, hi) = (1, n)\n ans = 0\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n X = strength(mid)\n if n >= X:\n ans = mid\n lo = mid + 1\n else:\n hi = mid - 1\n return ans", "def binarysearch(l, r, n):\n if l <= r:\n mid = (l + r) // 2\n s = mid * (mid + 1) * (2 * mid + 1) // 6\n if s <= n:\n return self.binarysearch(mid + 1, r, n)\n else:\n return self.binarysearch(l, mid - 1, n)\n return r\n\ndef killinspree(n):\n return self.binarysearch(0, 1000000, n)", "def killinspree(n):\n l = 1\n r = n\n res = 0\n while l <= r:\n mid = (l + r) // 2\n s = mid * (mid + 1) * (2 * mid + 1) // 6\n if s <= n:\n res = mid\n l = mid + 1\n else:\n r = mid - 1\n return res", "def s(i):\n return i * (i + 1) * (2 * i + 1) // 6\n\ndef killinspree(n):\n (st, en) = (0, int(n ** 0.5) + 1)\n ans = 0\n while st <= en:\n mid = (st + en) // 2\n c = s(mid)\n if c == n:\n return mid\n elif c > n:\n en = mid - 1\n else:\n st = mid + 1\n ans = mid\n return ans", "def Formula(n):\n return n * (n + 1) * (2 * n + 1) // 6\n\ndef killinspree(n):\n l = 1\n h = 10000000.0\n ans = 0\n mid = l + (h - l) // 2\n if n == 0:\n return 0\n while l <= h:\n mid = l + (h - l) // 2\n if int(self.Formula(mid)) <= n:\n ans = mid\n l = mid + 1\n else:\n h = mid - 1\n return int(ans)", "MAX = int(1000000000000.0)\ndp = []\n\ndef compute():\n i = 1\n while i * i <= MAX:\n dp.append(i * i)\n i += 1\n\ndef bs(key):\n l = 0\n r = len(dp) - 1\n ans = 0\n while l <= r:\n mid = l + (r - l) >> 1\n if dp[mid] == key:\n return mid\n if dp[mid] < key:\n l = mid + 1\n else:\n r = mid - 1\n return ans\n\ndef killinspree(n):\n\n def sumt(h):\n return h * (h + 1) * (2 * h + 1) / 6\n h = 1\n AC = 0\n sta = 0\n endd = 144225\n while sta <= endd:\n midd = (sta + endd) // 2\n if sumt(midd) <= n:\n AC = max(AC, midd)\n sta = midd + 1\n else:\n endd = midd - 1\n return AC", "def killinspree(n):\n low = 0\n up = n\n ans = 0\n while low <= up:\n mid = (low + up) // 2\n power = mid * (mid + 1) * (2 * mid + 1)\n if power <= n * 6:\n low = mid + 1\n ans = max(ans, mid)\n else:\n up = mid - 1\n return ans", "def killinspree(n):\n (low, high) = (1, 2 ** 32 - 1)\n while low <= high:\n mid = (high + low) // 2\n temp = mid * (mid + 1) * (2 * mid + 1) // 6\n if temp > n:\n high = mid - 1\n elif temp == n:\n return mid\n else:\n low = mid + 1\n return low - 1", "import math\n\ndef killinspree(n):\n\n def sum(n):\n a = n * (n + 1) * (2 * n + 1) / 6\n return a\n (low, high) = (0, n + 1)\n while low < high:\n mid = low + (high - low) // 2\n if sum(mid) > n:\n high = mid\n else:\n low = mid + 1\n return low - 1", "def ss(n):\n return n * (n + 1) * (2 * n + 1) // 6\n\ndef killinspree(n):\n (l, r) = (1, n)\n while l != r:\n mid = (l + r) // 2\n if mid == l:\n return l if self.ss(r) > n else r\n if self.ss(mid) > n:\n r = mid\n elif self.ss(mid) < n:\n l = mid\n else:\n return mid\n return l", "def killinspree(n):\n cnt = -1\n start = 0\n end = n\n while start <= end:\n mid = (start + end) // 2\n midSquareSum = int(mid * (mid + 1) * (2 * mid + 1) / 6)\n if midSquareSum <= n:\n cnt = mid\n start = mid + 1\n else:\n end = mid - 1\n return cnt", "def killinspree(n):\n s = 1\n e = n\n ans = 0\n while s <= e:\n m = s + (e - s) // 2\n x = m * (m + 1) * (2 * m + 1) // 6\n if x <= n:\n ans = m\n s = m + 1\n else:\n e = m - 1\n return ans", "def killinspree(n):\n (l, h) = (0, n)\n while l <= h:\n mid = (l + h) // 2\n if 2 * mid * mid * mid + 3 * mid * mid + mid <= 6 * n:\n l = mid + 1\n else:\n h = mid - 1\n return l - 1", "def killinspree(n):\n\n def add(x):\n return x * (x + 1) * (2 * x + 1) // 6\n if n == 0:\n return 0\n low = 1\n high = 10000000.0\n ans = 0\n while low <= high:\n mid = low + (high - low) // 2\n sum = add(mid)\n if sum <= n:\n ans = mid\n low = mid + 1\n else:\n high = mid - 1\n return int(ans)", "def killinspree(n):\n l = 0\n r = n\n while l <= r:\n m = l + r >> 1\n if m * (m + 1) * (2 * m + 1) <= 6 * n:\n l = m + 1\n else:\n r = m - 1\n return l - 1", "def sum_n2(n):\n return n * (n + 1) * (2 * n + 1) / 6\n\ndef killinspree(P):\n i = 1\n count = 0\n l = 1\n r = P\n while l <= r:\n i = (l + r) // 2\n sum = self.sum_n2(i)\n if P == sum:\n return i\n if P > sum:\n l = i + 1\n if P < sum:\n r = i - 1\n return l - 1", "def killinspree(n):\n low = 1\n high = 1000000\n mid = 0\n while low <= high:\n mid = low + (high - low) // 2\n f = mid * (mid + 1) * (2 * mid + 1) / 6\n if n == f:\n return mid\n elif n < f:\n high = mid - 1\n else:\n low = mid + 1\n return low - 1", "def killinspree(n):\n\n def sumt(h):\n return h * (h + 1) * (2 * h + 1) / 6\n h = 1\n AC = 0\n sta = 0\n endd = 144225\n while sta <= endd:\n midd = (sta + endd) // 2\n if sumt(midd) <= n:\n AC = max(AC, midd)\n sta = midd + 1\n else:\n endd = midd - 1\n return AC", "def killinspree(n):\n i = 1\n j = n\n while i < j:\n mid = i + j + 1 >> 1\n ans = (mid + 1) * (mid * 2 + 1) * mid // 6\n if ans > n:\n j = mid - 1\n else:\n i = mid\n return i", "def killinspree(n):\n (i, j) = (0, n)\n while i <= j:\n k = (i + j) // 2\n if 2 * k * k * k + 3 * k * k + k <= 6 * n:\n i = k + 1\n else:\n j = k - 1\n return i - 1", "def killinspree(n):\n lo = 1\n hi = 1000000\n count = 0\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n val = mid * (mid + 1) * (2 * mid + 1) // 6\n if val <= n:\n ans = mid\n lo = mid + 1\n else:\n hi = mid - 1\n return ans", "def killinspree(n):\n\n def vaild(target, n):\n temp = target * (target + 1) * (2 * target + 1) // 6\n return n >= temp\n start = 1\n end = n\n ans = -1\n while start <= end:\n mid = (start + end) // 2\n if vaild(mid, n):\n ans = mid\n start = mid + 1\n else:\n end = mid - 1\n return ans", "def killinspree(n):\n v = lambda n: n * (n + 1) * (2 * n + 1) // 6\n (lower, upper) = (0, n + 1)\n while lower < upper:\n mid = lower + (upper - lower) // 2\n if v(mid) > n:\n upper = mid\n else:\n lower = mid + 1\n return lower - 1", "def killinspree(n):\n l = 1\n h = int(n ** (1 / 2))\n ans = 1\n while l <= h:\n m = int((l + h) / 2)\n t = m * (m + 1) * (2 * m + 1) / 6\n if n - t >= 0:\n ans = m\n l = m + 1\n else:\n h = m - 1\n return ans", "def killinspree(n):\n import math\n (start, end) = (1, math.ceil((3 * n) ** (1 / 3)))\n while start <= end:\n mid = (start + end) // 2\n summation = mid * (mid + 1) * (2 * mid + 1) // 6\n if summation == n:\n return mid\n elif summation < n:\n start = mid + 1\n else:\n end = mid - 1\n return end", "def killinspree(n):\n start = 0\n end = 100000.0\n mid = start + (end - start) // 2\n ans = 0\n while start <= end:\n condition = mid * (mid + 1) * (2 * mid + 1) // 6\n if n >= condition:\n ans = mid\n start = mid + 1\n else:\n end = mid - 1\n mid = start + (end - start) // 2\n return int(ans)", "import bisect\n\ndef killinspree(n):\n start = 0\n end = 100000.0\n mid = start + (end - start) // 2\n ans = 0\n while start <= end:\n a = mid\n condition = a * (a + 1) * (2 * a + 1) // 6\n if n >= condition:\n ans = mid\n start = mid + 1\n elif n < condition:\n end = mid - 1\n mid = start + (end - start) // 2\n return int(ans)", "def killinspree(n):\n l = 0\n h = n\n while l <= h:\n m = (l + h) // 2\n if m * (m + 1) * (2 * m + 1) // 6 > n:\n h = m - 1\n else:\n l = m + 1\n for i in range(m - 2, m + 2):\n if i * (i + 1) * (2 * i + 1) // 6 > n:\n return i - 1", "def killinspree(n):\n\n def squareSum(x):\n return x * (x + 1) * (2 * x + 1) // 6\n low = 1\n high = 1000000.0\n result = -1\n while low <= high:\n mid = int((low + high) // 2)\n if squareSum(mid) > n:\n high = mid - 1\n elif squareSum(mid) < n:\n result = mid\n low = mid + 1\n else:\n return mid\n return result", "import math\n\ndef killinspree(n):\n low = 1\n high = int(math.sqrt(n))\n sum_till_here = 0\n while low <= high:\n mid = int(low + (high - low) / 2)\n sum_till_here = int(mid * (mid + 1) * (2 * mid + 1) / 6)\n if sum_till_here == n:\n return mid\n elif sum_till_here > n:\n high = mid - 1\n else:\n result = mid\n low = mid + 1\n return result", "def killinspree(n):\n\n def solve(x):\n return x * (x + 1) * (2 * x + 1) // 6\n if n == 0:\n return 0\n start = 1\n end = 1000000.0\n ans = 0\n while start <= end:\n mid = start + (end - start) // 2\n summ = solve(mid)\n if summ <= n:\n ans = mid\n start = mid + 1\n else:\n end = mid - 1\n return int(ans)", "import math\n\ndef killinspree(n):\n s = 1\n e = int(math.sqrt(n) + 1)\n ans = 0\n while s <= e:\n m = s + (e - s) // 2\n su = m * (m + 1) * (2 * m + 1) // 6\n if su <= n:\n ans = m\n s = m + 1\n else:\n e = m - 1\n return ans", "def killinspree(n):\n\n def sumt(h):\n return h * (h + 1) * (2 * h + 1) / 6\n h = 1\n AC = 0\n s = 0\n e = 144225\n while s <= e:\n midd = (s + e) // 2\n if sumt(midd) <= n:\n AC = max(AC, midd)\n s = midd + 1\n else:\n e = midd - 1\n return AC", "def killinspree(n):\n low = 1\n high = 2 * n\n output = 0\n total = 0\n while low <= high:\n mid = (low + high) // 2\n total = mid * (mid + 1) * (2 * mid + 1) // 6\n if total <= n:\n output = mid\n low = mid + 1\n else:\n high = mid - 1\n return output", "def killinspree(n):\n low = 1\n high = 100000\n ans = 0\n while low <= high:\n mid = low + (high - low) // 2\n x = mid * (mid + 1) * (2 * mid + 1) // 6\n if x <= n:\n ans = mid\n low = mid + 1\n else:\n high = mid - 1\n return ans", "import math\n\ndef killinspree(n):\n l = 1\n h = int(math.sqrt(n)) + 1\n ans = 0\n while l <= h:\n m = (l + h) // 2\n k = int(m * (m + 1) * (2 * m + 1) / 6)\n if k <= n:\n if m > ans:\n ans = m\n l = m + 1\n else:\n h = m - 1\n return ans", "def killinspree(n):\n low = 1\n high = n + 1\n while low < high:\n mid = (low + high + 1) // 2\n if n >= mid * (mid + 1) * (2 * mid + 1) // 6:\n low = mid\n else:\n high = mid - 1\n return low", "import math\n\ndef killinspree(n):\n low = 1\n high = math.ceil(math.sqrt(n))\n ans = 1\n while low <= high:\n mid = (low + high) // 2\n power = mid * (mid + 1) * (2 * mid + 1) // 6\n if power == n:\n return mid\n elif power > n:\n high = mid - 1\n else:\n ans = mid\n low = mid + 1\n return ans", "import math\n\ndef killinspree(n):\n (l, r) = (1, math.ceil(math.sqrt(n)))\n res = 0\n while l <= r:\n mid = (l + r) // 2\n z = mid * (mid + 1) * (2 * mid + 1) // 6\n if n == z:\n return mid\n elif z < n:\n res = mid\n l = mid + 1\n else:\n r = mid - 1\n return res", "import math as m\n\ndef killinspree(n):\n (lo, ans) = (0, 0)\n hi = int(m.sqrt(n))\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n val = mid * (mid + 1) * (2 * mid + 1) // 6\n if val <= n:\n ans = mid\n lo = mid + 1\n else:\n hi = mid - 1\n return ans", "def getSum(n):\n return n * (n + 1) * (2 * n + 1) / 6\n\ndef killinspree(n):\n bot = 1\n top = n\n result = 0\n while bot <= top:\n mid = (bot + top) // 2\n s = getSum(mid)\n if s <= n:\n result = mid\n bot = mid + 1\n else:\n top = mid - 1\n return result", "def killinspree(n):\n l = 1\n r = 10 ** 12\n ans = -1\n while r >= l:\n mid = (l + r) // 2\n res = mid * (mid + 1) * (2 * mid + 1) // 6\n if res <= n:\n ans = mid\n l = mid + 1\n else:\n r = mid - 1\n return ans", "def killinspree(n):\n if n == 1:\n return 1\n\n def findSum(k):\n return k * (k + 1) * (2 * k + 1) // 6\n res = 0\n start = 1\n end = n\n while start < end:\n mid = (start + end) // 2\n sm = findSum(mid)\n if sm == mid:\n return mid\n if sm > n:\n end = mid\n else:\n res = mid\n start = mid + 1\n return res", "def killinspree(n):\n l = 1\n h = n\n while l <= h:\n m = l + h >> 1\n if m * (m + 1) * (2 * m + 1) // 6 == n:\n return m\n elif m * (m + 1) * (2 * m + 1) // 6 > n:\n h = m - 1\n else:\n l = m + 1\n return h", "from math import *\n\ndef killinspree(n):\n l = 1\n h = int(sqrt(n))\n while l <= h:\n m = (l + h) // 2\n if m * (m + 1) * (2 * m + 1) // 6 == n:\n return m\n elif m * (m + 1) * (2 * m + 1) // 6 > n:\n h = m - 1\n else:\n l = m + 1\n return h", "def killinspree(n):\n s = 1\n e = int(n ** 0.5)\n while s <= e:\n mid = s + e >> 1\n p = mid * (mid + 1) * (2 * mid + 1) // 6\n if p > n:\n e = mid - 1\n else:\n s = mid + 1\n return e", "def killinspree(n):\n (i, j) = (1, 10 ** 12)\n count = -1\n while j >= i:\n mid = (i + j) // 2\n if mid * (mid + 1) * (2 * mid + 1) // 6 <= n:\n count = mid\n i = mid + 1\n else:\n j = mid - 1\n return count", "def killinspree(n):\n s = 0\n ans = 0\n i = 1\n while n > 0:\n s = i * (i + 1) * (2 * i + 1) // 6\n if n > s:\n i = 2 * i\n elif n == s:\n ans = i\n break\n else:\n low = i // 2\n high = i\n while low <= high:\n mid = (low + high) // 2\n s = mid * (mid + 1) * (2 * mid + 1) // 6\n if s > n:\n high = mid - 1\n elif s == n:\n ans = mid\n break\n else:\n nex = (mid + 1) * (mid + 1 + 1) * (2 * (mid + 1) + 1) // 6\n if nex > n:\n ans = mid\n break\n low = mid + 1\n break\n return ans", "import math\n\ndef killinspree(n):\n l = 1\n r = int(math.sqrt(n))\n ans = 0\n while l <= r:\n mid = l + (r - l) // 2\n cal = mid * (mid + 1) * (2 * mid + 1) // 6\n if cal <= n:\n ans = mid\n l = mid + 1\n else:\n r = mid - 1\n return ans"], "starter_code": "def killinspree (n):\n", "input_output": {"inputs": ["N = 14", "N = 10"], "outputs": ["3", "2"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Binary Search", "Mathematical", "Divide and Conquer"], "name": null, "source": "geeksforgeeks", "tags": ["Sorting", "Divide and conquer", "Mathematics"], "skill_types": ["Sorting"], "url": "https://practice.geeksforgeeks.org/problems/killing-spree3020/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(n))", "entry_point": "killinspree", "task_id": "TACO_lite/279", "example": [[[14], [10]], ["3", "2"]]} +{"requirement": "Write a function that takes as its parameters *one or more numbers which are the diameters of circles.* \n\nThe function should return the *total area of all the circles*, rounded to the nearest integer in a string that says \"We have this much circle: xyz\". \n\nYou don't know how many circles you will be given, but you can assume it will be at least one.\n\nSo: \n```python\nsum_circles(2) == \"We have this much circle: 3\"\nsum_circles(2, 3, 4) == \"We have this much circle: 23\"\n```\n\nTranslations and comments (and upvotes!) welcome!", "solutions": ["import math\n\ndef sum_circles(*args):\n t = round(sum([math.pi * d ** 2 / 4 for d in args]))\n return 'We have this much circle: {}'.format(int(t))", "from math import pi\n\ndef sum_circles(*args):\n return 'We have this much circle: %.0f' % sum([(d / 2.0) ** 2 * pi for d in args])", "from math import pi\n\ndef sum_circles(*args):\n return 'We have this much circle: %s' % int(round(sum((pi * (d / 2.0) ** 2 for d in args))))", "from math import pi\n\ndef sum_circles(*rs):\n total = int(round(sum((pi * r ** 2 / 4 for r in rs))))\n return 'We have this much circle: {}'.format(total)", "import math\n\ndef sum_circles(*args):\n totalArea = 0\n for arg in args:\n area = (arg / 2.0) ** 2.0 * math.pi\n totalArea += area\n return 'We have this much circle: ' + str(int(round(totalArea)))", "from math import pi\nOUTPUT = 'We have this much circle: {:.0f}'.format\n\ndef sum_circles(*args):\n return OUTPUT(sum((pi * (diameter / 2.0) ** 2 for diameter in args)))", "import math\n\ndef sum_circles(*args):\n return 'We have this much circle: ' + str(int(round(sum((i * i * math.pi / 4 for i in args)), 0)))", "import math\n\ndef sum_circles(*args):\n y = round(sum([math.pi * x ** 2 / 4 for x in args]))\n return 'We have this much circle: ' + str(y)"], "starter_code": "def sum_circles(*args):\n", "input_output": {"fn_name": "sum_circles", "inputs": [[48, 7, 8, 9, 10], [1], [1, 1, 1, 2, 3, 4, 5], [894, 5778, 4839, 476], [4.5456, 746.5, 98.34, 344.543], [1, 1, 1], [13.58, 14.9, 56.99, 107.321], [56894.04839, 843975.4839, 4.08437403489], [5, 6, 7, 8, 9, 10, 105083, 48839, 4853, 28, 483]], "outputs": [["We have this much circle: 2040"], ["We have this much circle: 1"], ["We have this much circle: 45"], ["We have this much circle: 45417233"], ["We have this much circle: 538519"], ["We have this much circle: 2"], ["We have this much circle: 11916"], ["We have this much circle: 561977165367"], ["We have this much circle: 10564760498"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Geometry", "Algebra"], "name": null, "source": "codewars", "tags": ["Geometry", "Matrices", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56143efa9d32b3aa65000016", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sum_circles", "task_id": "TACO_lite/277", "example": [[], []]} +{"requirement": "Given a number N, count total number of divisors of N!.\nExample 1:\nInput : N = 4\nOutput: 8\nExplaination: 4! is 24. Divisors of 24 are \n1, 2, 3, 4, 6, 8, 12 and 24.\nExample 2:\nInput : N = 5\nOutput : 16\nExplaination: 5! is 120. Divisors of 120 are \n1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24 30, \n40, 60 and 120.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function totalDivisors() which takes N as input parameter and returns total number of divisors of N!.\nExpected Time Complexity: O(N*logN)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 ≤ N ≤ 100", "solutions": ["import math as m\n\ndef totaldivisors(N):\n primes = [True] * (N + 1)\n prime_factors = []\n for i in range(2, N + 1):\n if primes[i]:\n j = i * i\n while j <= N:\n primes[j] = False\n j += i\n k = i\n count = 0\n while k <= N:\n count += N // k\n k *= i\n prime_factors.append(count)\n total_divisors = 1\n for count in prime_factors:\n total_divisors *= count + 1\n return total_divisors", "def totaldivisors(n):\n from collections import Counter\n rec = Counter()\n for i in range(2, n + 1):\n div = 2\n while i > 1:\n if i % div == 0:\n i //= div\n rec[div] += 1\n else:\n div += 1\n ans = 1\n for x in rec.values():\n ans *= x + 1\n return ans", "def totaldivisors(n):\n\n def find_Prime(n):\n ans = [2]\n prime = [1 for i in range(n + 1)]\n i = 3\n while i * i <= n:\n if prime[i]:\n for j in range(3 * i, n + 1, 2 * i):\n prime[j] = 0\n i += 2\n for i in range(3, n + 1, 2):\n if prime[i]:\n ans.append(i)\n return ans\n prime = find_Prime(n)\n ans = 1\n for i in prime:\n k = i\n a = 0\n while n // k:\n a += n // k\n k *= i\n ans *= a + 1\n return ans", "def solve(n):\n s = 1\n c = 2\n d = {}\n while n > 1:\n if n % c == 0:\n d[c] = d.get(c, 0) + 1\n n = n // c\n else:\n c += 1\n for i in d.keys():\n s = s * (d[i] + 1)\n return s\n\ndef fact(n):\n if n == 0 or n == 1:\n return 1\n else:\n return n * self.fact(n - 1)\n\ndef totaldivisors(N):\n a = self.fact(N)\n return self.solve(a)", "def totaldivisors(N):\n fact = 1\n\n def pf(n):\n i = 2\n s = 1\n while i * i <= n:\n if n % i == 0:\n t = 0\n while n % i == 0:\n t += 1\n n = n // i\n s = s * (t + 1)\n i += 1\n if n != 1:\n s = s * 2\n return s\n while N != 0:\n fact = fact * N\n N -= 1\n n = fact\n res = pf(n)\n return res", "def totaldivisors(n):\n l = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n i = 0\n m = []\n prod = 1\n while 1:\n k = n\n count = 0\n while k > 0:\n count = count + k // l[i]\n k = k // l[i]\n if count != 0:\n m.append(count)\n i = i + 1\n if i == 25:\n break\n for i in m:\n prod = prod * (i + 1)\n return prod", "def totaldivisors(num):\n arr = [i for i in range(1, num + 1)]\n mp = {}\n for i in range(num):\n j = 2\n while j * j <= arr[i] and arr[i] > 1:\n cnt = 0\n while arr[i] % j == 0:\n arr[i] = arr[i] // j\n cnt += 1\n if mp.__contains__(j):\n mp[j] += cnt\n else:\n mp[j] = cnt\n j += 1\n if arr[i] > 1:\n if mp.__contains__(arr[i]):\n mp[arr[i]] += 1\n else:\n mp[arr[i]] = 1\n ans = 1\n for k in mp:\n ans *= mp[k] + 1\n return ans"], "starter_code": "def totaldivisors(N):\n", "input_output": {"inputs": ["N = 4", "N = 5"], "outputs": ["8", "16"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Prime Number", "sieve", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory", "Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/count-divisors-of-factorial4508/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*logN)", "entry_point": "totaldivisors", "task_id": "TACO_lite/284", "example": [[[4], [5]], ["8", "16"]]} +{"requirement": "Given an array of integers arr. Return the number of sub-arrays with odd sum.\nAs the answer may grow large, the answer must be computed modulo 10^9 + 7.\n \nExample 1:\nInput: arr = [1,3,5]\nOutput: 4\nExplanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]\nAll sub-arrays sum are [1,4,9,3,8,5].\nOdd sums are [1,9,3,5] so the answer is 4.\n\nExample 2:\nInput: arr = [2,4,6]\nOutput: 0\nExplanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]\nAll sub-arrays sum are [2,6,12,4,10,6].\nAll sub-arrays have even sum and the answer is 0.\n\nExample 3:\nInput: arr = [1,2,3,4,5,6,7]\nOutput: 16\n\nExample 4:\nInput: arr = [100,100,99,99]\nOutput: 4\n\nExample 5:\nInput: arr = [7]\nOutput: 1\n\n \nConstraints:\n\n1 <= arr.length <= 10^5\n1 <= arr[i] <= 100", "solutions": ["def numofsubarrays(arr: List[int]) -> int:\n mod = 10 ** 9 + 7\n odd_presum_cnt = 0\n par = 0\n for a in arr:\n par ^= a & 1\n if par:\n odd_presum_cnt += 1\n return odd_presum_cnt * (len(arr) + 1 - odd_presum_cnt) % mod", "def numofsubarrays(arr: List[int]) -> int:\n res = odd = even = 0\n for x in arr:\n even += 1\n if x % 2 != 0:\n (even, odd) = (odd, even)\n res = (res + odd) % (10 ** 9 + 7)\n return res", "def numofsubarrays(arr: List[int]) -> int:\n np = [[0 for i in range(len(arr))] for j in range(2)]\n np[0][0] = 1 if arr[0] % 2 == 0 else 0\n np[1][0] = 1 if arr[0] % 2 == 1 else 0\n res = np[1][0]\n for i in range(1, len(arr)):\n if arr[i] % 2 == 0:\n np[0][i] = (1 + np[0][i - 1]) % 1000000007\n np[1][i] = np[1][i - 1] % 1000000007\n else:\n np[0][i] = np[1][i - 1] % 1000000007\n np[1][i] = (1 + np[0][i - 1]) % 1000000007\n res += np[1][i]\n return res % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n s = 0\n odd = {}\n ok = []\n even = {}\n ek = []\n for i in range(len(arr)):\n s += arr[i]\n if s % 2 == 0:\n even[i] = s\n ek.append(i)\n else:\n odd[i] = s\n ok.append(i)\n j = 0\n c = 0\n for i in ok:\n while j < len(ek) and ek[j] < i:\n j += 1\n c += j\n j = 0\n for i in ek:\n while j < len(ok) and ok[j] < i:\n j += 1\n c += j\n return (c + len(ok)) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n mod = 10 ** 9 + 7\n odd_even_count = [[0, 0] for _ in range(len(arr) + 1)]\n prefix_odd_sum = [-1 for _ in range(len(arr))]\n cur = 0\n odd_count = 0\n even_count = 0\n for idx in range(len(arr)):\n cur += arr[idx]\n prefix_odd_sum[idx] = cur % 2\n if cur % 2 == 1:\n odd_count += 1\n else:\n even_count += 1\n odd_even_count[idx + 1] = (odd_count, even_count)\n ans = 0\n for idx in range(len(arr)):\n is_odd = prefix_odd_sum[idx]\n if is_odd:\n ans += 1 + odd_even_count[idx][1]\n else:\n ans += odd_even_count[idx][0]\n return ans % mod", "def numofsubarrays(A: List[int]) -> int:\n n = len(A)\n mod = 10 ** 9 + 7\n ans = 0\n (p, ctr) = ([0] * (n + 1), Counter([0]))\n for i in range(n):\n p[i] = p[i - 1] + A[i]\n s = p[i] % 2\n ans = ans + ctr[1 - s]\n ans = ans % mod\n ctr[s] += 1\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n dp = [0 for i in range(len(arr))]\n dp[0] = (1, 0) if arr[0] % 2 == 1 else (0, 1)\n for i in range(1, len(dp)):\n if arr[i] % 2 == 0:\n oddCount = dp[i - 1][0]\n evenCount = dp[i - 1][1] + 1\n else:\n oddCount = dp[i - 1][1] + 1\n evenCount = dp[i - 1][0]\n dp[i] = (oddCount, evenCount)\n return sum([elem[0] for elem in dp]) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n MOD = 10 ** 9 + 7\n res = 0\n curr_sum = 0\n even_count = 1\n odd_count = 0\n for num in arr:\n curr_sum += num\n curr_sum %= 2\n if curr_sum == 1:\n res += even_count\n odd_count += 1\n else:\n res += odd_count\n even_count += 1\n return res % MOD", "def numofsubarrays(arr: List[int]) -> int:\n dp = [[0, 0] for _ in range(len(arr) + 1)]\n for (i, num) in enumerate(arr):\n if num % 2 == 0:\n dp[i + 1][0] = dp[i][0]\n dp[i + 1][1] = dp[i][1] + 1\n else:\n dp[i + 1][0] = dp[i][1] + 1\n dp[i + 1][1] = dp[i][0]\n return sum((dp[i][0] for i in range(len(dp)))) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n mod = 10 ** 9 + 7\n dic = collections.Counter()\n dic[0] += 1\n pre = ans = 0\n for (i, x) in enumerate(arr):\n pre += x\n pre %= 2\n ans = (ans + dic[pre ^ 1]) % mod\n dic[pre] += 1\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n if len(arr) < 1:\n return None\n if len(arr) == 1:\n if arr[0] % 2 != 0:\n return 1\n mod = 10 ** 9 + 7\n flag = False\n for i in arr:\n if i % 2 != 0:\n flag = True\n break\n if flag == False:\n return 0\n (even, odd) = (0, 0)\n ret = 0\n for i in arr:\n if i % 2 != 0:\n ret += even + 1\n (odd, even) = (even + 1, odd)\n else:\n ret += odd\n (odd, even) = (odd, even + 1)\n return ret % mod", "def numofsubarrays(arr: List[int]) -> int:\n N = len(arr)\n dp = [0] * N\n dp[0] = arr[0] & 1\n for i in range(1, N):\n if arr[i] & 1:\n dp[i] = i - dp[i - 1] + 1\n else:\n dp[i] = dp[i - 1]\n return sum(dp) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n ans = 0\n even = 0\n odd = 0\n for v in arr:\n if v % 2 == 0:\n (even, odd) = ((even + 1) % 10000000007, odd)\n else:\n (even, odd) = (odd, (even + 1) % 10000000007)\n ans = (ans + odd) % 10000000007\n return ans % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n kMod = int(1000000000.0 + 7)\n n = len(arr)\n dp = [[0] * 2 for _ in range(n)]\n ans = 0\n if arr[0] % 2 == 0:\n dp[0][0] = 1\n else:\n dp[0][1] = 1\n ans += dp[0][1]\n for i in range(1, n):\n if arr[i] % 2 != 0:\n dp[i][0] = dp[i - 1][1]\n dp[i][1] = dp[i - 1][0] + 1\n else:\n dp[i][0] = dp[i - 1][0] + 1\n dp[i][1] = dp[i - 1][1]\n ans += dp[i][1]\n return ans % kMod", "def numofsubarrays(arr: List[int]) -> int:\n dp = []\n for i in range(len(arr) + 1):\n dp.append([0, 0])\n ans = 0\n for i in range(1, len(arr) + 1):\n if arr[i - 1] % 2 == 0:\n dp[i][0] = dp[i - 1][0] + 1\n dp[i][1] = dp[i - 1][1]\n else:\n dp[i][0] = dp[i - 1][1]\n dp[i][1] = dp[i - 1][0] + 1\n ans += dp[i][1]\n return ans % (pow(10, 9) + 7)", "def numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n mod = 10 ** 9 + 7\n ans = 0\n p = [0] * (n + 1)\n counter = Counter([0])\n for i in range(n):\n p[i] = p[i - 1] + arr[i]\n if p[i] % 2:\n ans += counter[0]\n else:\n ans += counter[1]\n counter[p[i] % 2] += 1\n return ans % mod", "def numofsubarrays(arr: List[int]) -> int:\n sum_even = 0\n sum_odd = 0\n out = 0\n for i in range(len(arr)):\n if arr[i] % 2 == 0:\n (sum_even, sum_odd) = (sum_even + 1, sum_odd)\n else:\n (sum_even, sum_odd) = (sum_odd, sum_even + 1)\n out += sum_odd\n return out % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n sums = [0]\n sum = 0\n for n in arr:\n sum += n\n sums.append(sum)\n odd_sum_count = []\n even_sum_count = []\n odd_sum = 0\n even_sum = 0\n for ss in sums:\n odd_sum += 1 if ss % 2 == 1 else 0\n even_sum += 0 if ss % 2 == 1 else 1\n odd_sum_count.append(odd_sum)\n even_sum_count.append(even_sum)\n ans = 0\n for i in range(len(arr)):\n if sums[i + 1] % 2 == 0:\n ans += odd_sum_count[i]\n else:\n ans += even_sum_count[i]\n ans = ans % (10 ** 9 + 7)\n return ans", "def numofsubarrays(A) -> int:\n n = len(A)\n MOD = pow(10, 9) + 7\n (dp_even, dp_odd) = ([0], [0])\n if A[0] % 2:\n dp_odd[0] += 1\n else:\n dp_even[0] += 1\n ans = dp_odd[-1]\n for i in range(1, n):\n if A[i] % 2:\n dp_odd.append((dp_even[i - 1] + 1) % MOD)\n dp_even.append(dp_odd[i - 1])\n else:\n dp_odd.append(dp_odd[i - 1])\n dp_even.append((dp_even[i - 1] + 1) % MOD)\n ans += dp_odd[i]\n ans %= MOD\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n memoOdd = arr[0] % 2\n memoEven = -(arr[0] % 2 - 1)\n memoOddSum = memoOdd\n for i in range(1, len(arr)):\n memoOdd_temp = memoOdd\n memoEven_temp = memoEven\n memoOdd = memoOdd_temp * -(arr[i] % 2 - 1) + memoEven_temp * (arr[i] % 2) + arr[i] % 2\n memoEven = memoOdd_temp * (arr[i] % 2) + memoEven_temp * -(arr[i] % 2 - 1) - (arr[i] % 2 - 1)\n memoOddSum += memoOdd\n return memoOddSum % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n (countOdd, countEven, result) = (0, 1, 0)\n modulo = 1000000007\n prev = 0\n for i in arr:\n prev = (prev + i) % 2\n if prev == 0:\n countEven += 1\n result += countOdd\n if result >= modulo:\n result %= modulo\n else:\n countOdd += 1\n result += countEven\n if result >= modulo:\n result %= modulo\n return result", "def numofsubarrays(arr: List[int]) -> int:\n ans = 0\n evenCount = 0\n oddCount = 0\n for i in arr:\n if i % 2 == 0:\n ans += oddCount\n (oddCount, evenCount) = (oddCount, evenCount + 1)\n else:\n ans += evenCount + 1\n (oddCount, evenCount) = (evenCount + 1, oddCount)\n return int(ans % (math.pow(10, 9) + 7))", "def numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n MOD = int(1000000000.0 + 7)\n (even, odd) = ([0] * (n + 1), [0] * (n + 1))\n for (i, a) in enumerate(arr):\n if a % 2 == 1:\n even[i] = odd[i - 1] % MOD\n odd[i] = (even[i - 1] + 1) % MOD\n else:\n even[i] = (even[i - 1] + 1) % MOD\n odd[i] = odd[i - 1] % MOD\n return sum(odd) % MOD", "def numofsubarrays(arr: List[int]) -> int:\n acc = []\n temp = 0\n ones = 0\n for u in arr:\n temp += u % 2\n if temp % 2 == 1:\n ones += 1\n L = len(arr)\n return ones * (L - ones + 1) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n (evenCount, oddCount) = (1, 0)\n totalSum = numArrays = 0\n for val in arr:\n totalSum += val\n numArrays += evenCount if totalSum % 2 else oddCount\n evenCount += totalSum % 2 == 0\n oddCount += totalSum % 2 == 1\n return numArrays % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n mod = 10 ** 9 + 7\n n = len(arr)\n dp = [[0] * 2 for _ in range(n)]\n if arr[n - 1] & 1:\n dp[n - 1][1] = 1\n else:\n dp[n - 1][0] = 1\n for i in range(n - 2, -1, -1):\n if arr[i] & 1:\n dp[i][1] = (dp[i + 1][0] + 1) % mod\n dp[i][0] = dp[i + 1][1]\n else:\n dp[i][1] = dp[i + 1][1]\n dp[i][0] = (dp[i + 1][0] + 1) % mod\n ans = 0\n for i in range(n):\n ans += dp[i][1]\n return ans % mod", "def numofsubarrays(arr: List[int]) -> int:\n (odd, even) = (0, 1)\n s = res = 0\n for n in arr:\n s += n\n if s % 2 == 0:\n res += odd\n even += 1\n else:\n res += even\n odd += 1\n res %= 1000000007\n return res", "def numofsubarrays(arr: List[int]) -> int:\n o = []\n score = 0\n tmp = 0\n (pa, no) = (0, 0)\n check = []\n for el in arr:\n tmp += el\n if tmp % 2 == 0:\n pa += 1\n check.append(0)\n else:\n no += 1\n check.append(1)\n o.append((pa, no))\n score = 0\n for i in range(len(arr)):\n if arr[i] % 2 == 1:\n score += 1\n if check[i - 1] == 0 or i == 0:\n score += o[-1][1] - o[i][1]\n else:\n score += o[-1][0] - o[i][0]\n mod = 10 ** 9 + 7\n return score % mod", "def numofsubarrays(arr: List[int]) -> int:\n odd = 0\n even = 1\n res = 0\n sum = 0\n for i in arr:\n sum += i\n if sum % 2 == 0:\n even += 1\n res = (res + odd) % 1000000007\n else:\n odd += 1\n res = (res + even) % 1000000007\n return res", "def numOddEvenSubarrays(arr: List[int], start: int) -> (int, int, int):\n if len(arr) == 0:\n return (0, 0, 0)\n if len(arr) == 1 or start == len(arr) - 1:\n return (0, 1, 0) if arr[start] % 2 == 0 else (1, 0, 0)\n (odd, even, oldOdd) = self.numOddEvenSubarrays(arr, start + 1)\n indOdd = (odd + oldOdd) % (10 ** 9 + 7)\n return (odd, even + 1, indOdd) if arr[start] % 2 == 0 else (even + 1, odd, indOdd)\n\ndef numofsubarrays(arr: List[int]) -> int:\n (odd, even, oldOdd) = self.numOddEvenSubarrays(arr, 0)\n total = (odd + oldOdd) % (10 ** 9 + 7)\n return total", "def numofsubarrays(coll: List[int]) -> int:\n n = len(coll)\n m = 10 ** 9 + 7\n acc = 0\n evens = odds = 0\n for (i, x) in enumerate(coll):\n if x & 1:\n (evens, odds) = (odds, evens + 1)\n else:\n evens += 1\n acc += odds\n acc %= m\n return acc", "def numofsubarrays(arr: List[int]) -> int:\n prefix_sum = 0\n number_odd = 0\n number_even = 0\n total = 0\n for i in arr:\n prefix_sum += i\n if prefix_sum % 2 == 1:\n number_odd += 1\n total += 1\n total += number_even\n else:\n total += number_odd\n number_even += 1\n return int(total % (1000000000.0 + 7))", "def numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n d = {}\n d[0] = 1\n sm = 0\n even = 0\n for i in range(n):\n sm += arr[i]\n sm %= 2\n if sm < 0:\n sm += 2\n if sm in d:\n even += d[sm]\n if sm not in d:\n d[sm] = 0\n d[sm] += 1\n return (n * (n + 1) // 2 - even) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n (res, s, prev_odd, prev_even) = (0, 0, 0, 1)\n for v in arr:\n s = (s + v) % 2\n if s == 1:\n res += prev_even\n prev_odd += 1\n else:\n res += prev_odd\n prev_even += 1\n return res % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n if len(arr) == 0:\n return 0\n result = 0\n num_odd = 0\n Cum = [0]\n for i in range(len(arr)):\n Cum.append(Cum[-1] + arr[i])\n if Cum[-1] % 2 != 0:\n num_odd += 1\n return (len(arr) + 1 - num_odd) * num_odd % (10 ** 9 + 7)", "def numofsubarrays(coll: List[int]) -> int:\n n = len(coll)\n m = 10 ** 9 + 7\n dp = [(0, 0) for _ in range(n + 1)]\n for (i, x) in enumerate(coll):\n if x & 1:\n dp[i + 1] = (dp[i][1], dp[i][0] + 1)\n else:\n dp[i + 1] = (dp[i][0] + 1, dp[i][1])\n return sum((odds for (evens, odds) in dp)) % m", "def numofsubarrays(arr: List[int]) -> int:\n s = 0\n (evens, odds) = (0, 0)\n cnt = 0\n for num in arr:\n s += num\n if s % 2 == 1:\n cnt += evens + 1\n odds += 1\n else:\n cnt += odds\n evens += 1\n cnt = cnt % (10 ** 9 + 7)\n return cnt", "def numofsubarrays(arr: List[int]) -> int:\n res = 0\n odds = 0\n even = 0\n for (i, c) in enumerate(arr):\n if c & 1:\n (odds, even) = (even + 1, odds)\n else:\n even += 1\n res = (res + odds) % 1000000007\n return res % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n if not arr:\n return 0\n n_even = 0\n n_odd = 0\n res = 0\n for x in arr:\n if x % 2 == 0:\n (n_even, n_odd) = (n_even + 1, n_odd)\n else:\n (n_even, n_odd) = (n_odd, n_even + 1)\n res += n_odd\n return res % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n even = [0] * len(arr)\n odd = [0] * len(arr)\n for i in range(len(arr)):\n if i == 0 and arr[i] % 2 == 0:\n even[i] = 1\n elif i == 0:\n odd[i] = 1\n elif arr[i] % 2 == 0:\n even[i] = even[i - 1] + 1\n odd[i] = odd[i - 1]\n else:\n even[i] = odd[i - 1]\n odd[i] = even[i - 1] + 1\n mod = 10 ** 9 + 7\n ans = 0\n for i in range(len(arr)):\n ans = (ans + odd[i]) % mod\n return ans", "def numofsubarrays(A):\n count = [1, 0]\n curr = res = 0\n for a in A:\n curr ^= a & 1\n res += count[1 - curr]\n count[curr] += 1\n return res % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n res = odd = even = 0\n for x in arr:\n even += 1\n if x % 2:\n (odd, even) = (even, odd)\n res = (res + odd) % 1000000007\n return res", "def numofsubarrays(arr: List[int]) -> int:\n arr = list(accumulate(arr))\n count = 0\n (prev_even, prev_odd) = (0, 0)\n for i in range(len(arr)):\n if arr[i] % 2:\n count += 1\n count += prev_even\n prev_odd += 1\n else:\n count += prev_odd\n prev_even += 1\n return count % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n dp = [0, 0]\n ans = 0\n for (i, num) in enumerate(arr):\n (dp[0], dp[1]) = (dp[num % 2] + num % 2, dp[(num - 1) % 2] + (num - 1) % 2)\n ans += dp[0]\n return ans % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n sum_even = 0\n sum_odd = 0\n out = 0\n for i in range(len(arr)):\n if arr[i] % 2 == 0:\n (sum_even, sum_odd) = (sum_even + 1, sum_odd)\n else:\n (sum_even, sum_odd) = (sum_odd, sum_even + 1)\n out = out + sum_odd\n return out % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n memoOdd = [arr[0] % 2]\n memoEven = [-(arr[0] % 2 - 1)]\n for i in range(1, len(arr)):\n memoOdd.append(memoOdd[i - 1] * -(arr[i] % 2 - 1) + memoEven[i - 1] * (arr[i] % 2) + arr[i] % 2)\n memoEven.append(memoOdd[i - 1] * (arr[i] % 2) + memoEven[i - 1] * -(arr[i] % 2 - 1) - (arr[i] % 2 - 1))\n return sum(memoOdd) % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n ret = 0\n (odds, evens) = (0, 1)\n cur = 0\n for num in arr:\n cur ^= num & 1\n if cur:\n ret += evens\n odds += 1\n else:\n ret += odds\n evens += 1\n return ret % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n if not arr:\n return 0\n cum = 0\n (odd, even) = (0, 1)\n res = 0\n MOD = 10 ** 9 + 7\n for num in arr:\n cum += num\n if cum % 2:\n res += even\n odd += 1\n else:\n res += odd\n even += 1\n res %= MOD\n return res % MOD", "def numofsubarrays(arr: List[int]) -> int:\n (c, e, o, a) = (0, 1, 0, 0)\n for i in arr:\n c += i\n if c % 2 == 0:\n a += o\n a %= 1000000007\n e += 1\n else:\n a += e\n a %= 1000000007\n o += 1\n return a % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n odd = [0]\n even = [0]\n for i in range(len(arr)):\n if arr[i] % 2 == 0:\n even.append(even[-1] + 1)\n odd.append(odd[-1])\n else:\n even.append(odd[-1])\n odd.append(even[-2] + 1)\n return sum(odd) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n (run, prev) = ([], 0)\n count = 0\n (odd, even) = (0, 0)\n for ele in arr:\n run.append(prev + ele)\n prev = run[-1]\n if run[-1] % 2 != 0:\n count += even + 1\n odd += 1\n else:\n count += odd\n even += 1\n return count % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n if not arr or len(arr) == 0:\n return 0\n even = 1\n odd = 0\n cur = 0\n ret = 0\n for a in arr:\n cur = a + cur\n if cur % 2 == 0:\n even += 1\n ret += odd\n else:\n odd += 1\n ret += even\n ret = ret % (10 ** 9 + 7)\n return ret", "def numofsubarrays(arr: List[int]) -> int:\n L = len(arr)\n works = [0] * L\n not_works = [0] * L\n if arr[0] % 2 == 1:\n works[0] += 1\n else:\n not_works[0] += 1\n for i in range(1, L):\n if arr[i] % 2 == 0:\n works[i] += works[i - 1]\n not_works[i] += not_works[i - 1]\n else:\n works[i] += not_works[i - 1]\n not_works[i] += works[i - 1]\n if arr[i] % 2 == 1:\n works[i] += 1\n else:\n not_works[i] += 1\n return sum(works) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n evenSum = 0\n oddSum = 0\n prefSum = 0\n ans = 0\n for ele in arr:\n prefSum = prefSum + ele\n if prefSum % 2 == 1:\n ans += evenSum + 1\n oddSum += 1\n else:\n ans += oddSum\n evenSum += 1\n ans %= 10 ** 9 + 7\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n (odd, even, re, s) = (0, 1, 0, 0)\n for v in arr:\n s += v\n if s % 2 == 0:\n re += odd\n even += 1\n else:\n re += even\n odd += 1\n return re % 1000000007", "def numofsubarrays(A):\n MOD = 10 ** 9 + 7\n ans = 0\n even = odd = 0\n for x in A:\n if x % 2:\n (odd, even) = (1 + even, odd)\n else:\n even += 1\n ans = (ans + odd) % MOD\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n (o, e) = (0, 0)\n res = 0\n for n in arr:\n if n % 2 == 0:\n e += 1\n else:\n (o, e) = (e, o)\n o += 1\n res += o\n res = res % (10 ** 9 + 7)\n return res", "def numofsubarrays(arr: List[int]) -> int:\n even = 0\n odd = 0\n sum1 = 0\n result = 0\n for num in arr:\n sum1 += num\n if sum1 % 2 == 0:\n result += odd\n even += 1\n else:\n result += even + 1\n odd += 1\n result %= 10 ** 9 + 7\n return result", "def numofsubarrays(arr: List[int]) -> int:\n MOD = 10 ** 9 + 7\n count = [1, 0]\n cur = answer = 0\n for n in arr:\n cur ^= n & 1\n answer = (answer + count[1 ^ cur]) % MOD\n count[cur] += 1\n return answer", "def numofsubarrays(arr: List[int]) -> int:\n le = len(arr)\n o = 0\n s = 0\n for i in arr:\n s += i\n if s % 2:\n o += 1\n return o * (le - o + 1) % 1000000007", "MOD = 1000000007\n\ndef numofsubarrays(arr):\n n = len(arr)\n pre_sum = [1, 0]\n now_sum = 0\n res = 0\n for i in range(n):\n now_sum += arr[i]\n if now_sum % 2 == 1:\n res += pre_sum[0]\n pre_sum[1] += 1\n else:\n res += pre_sum[1]\n pre_sum[0] += 1\n return res % MOD", "def numofsubarrays(arr: List[int]) -> int:\n odds = 0\n evens = 1\n ans = 0\n runningsum = 0\n MOD = 10 ** 9 + 7\n for a in arr:\n runningsum += a\n if runningsum % 2:\n ans = (ans + evens) % MOD\n odds += 1\n else:\n ans = (ans + odds) % MOD\n evens += 1\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n MOD = int(1000000000.0 + 7)\n res = even = odd = 0\n for a in arr:\n even += 1\n if a % 2:\n (even, odd) = (odd, even)\n res = (res + odd) % MOD\n return res", "def numofsubarrays(arr: List[int]) -> int:\n (ans, odd, even) = (0, 0, 0)\n for i in arr:\n if i & 1:\n (odd, even) = (even + 1, odd)\n else:\n even = even + 1\n ans += odd\n return ans % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n even = 0\n odd = 0\n c = 0\n for e in arr:\n if e % 2 == 1:\n c += 1 + even\n (even, odd) = (odd, even + 1)\n else:\n c += odd\n even += 1\n return c % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n odd = 0\n even = 1\n cnt = 0\n res = 0\n mod = 1000000007\n for i in range(len(arr)):\n if arr[i] % 2 == 1:\n cnt += 1\n if cnt % 2 == 1:\n res = (res + even) % mod\n odd += 1\n else:\n res = (res + odd) % mod\n even += 1\n return int(res)", "def numofsubarrays(arr: List[int]) -> int:\n (ans, odd, even) = (0, 0, 0)\n for num in arr:\n if num % 2 != 0:\n (odd, even) = (even + 1, odd)\n else:\n (odd, even) = (odd, even + 1)\n ans += odd\n return ans % int(1000000000.0 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n ret = 0\n (odd_count, even_count) = (0, 0)\n for num in arr:\n if num % 2 != 0:\n ret += even_count + 1\n (odd_count, even_count) = (even_count + 1, odd_count)\n else:\n ret += odd_count\n (odd_count, even_count) = (odd_count, even_count + 1)\n return ret % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n odd = even = ans = 0\n mod = 10 ** 9 + 7\n for num in arr:\n if num % 2 == 1:\n ans += even + 1\n curr_even = even\n even = odd\n odd = curr_even + 1\n else:\n ans += odd\n even += 1\n return ans % mod", "def numofsubarrays(arr: List[int]) -> int:\n odd_sums = 0\n even_sums = 0\n ret = 0\n sum_ = 0\n for num in arr:\n sum_ += num\n if sum_ & 1:\n ret += even_sums + 1\n odd_sums += 1\n else:\n ret += odd_sums\n even_sums += 1\n return ret % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n sumEven = 0\n sumOdd = 0\n cumSum = 0\n result = 0\n for num in arr:\n cumSum += num\n if cumSum % 2 == 1:\n result += 1 + sumEven\n sumOdd += 1\n else:\n result += sumOdd\n sumEven += 1\n return result % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n prefixSum = [0]\n for i in range(1, len(arr) + 1):\n prefixSum.append(prefixSum[-1] + arr[i - 1])\n out = 0\n prefixEven = 0\n prefixOdd = 0\n for i in range(len(prefixSum)):\n if prefixSum[i] % 2 == 0:\n prefixEven += 1\n out += prefixOdd\n else:\n prefixOdd += 1\n out += prefixEven\n return out % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n (odds, counts) = (0, [1, 0])\n for x in arr:\n odds += 1 if x % 2 else 0\n counts[odds % 2] += 1\n return counts[0] * counts[1] % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n N = len(arr)\n if N == 0:\n return 0\n elif N == 1:\n return abs(arr[0]) % 2\n s = 0\n tot = 0\n ct_odd = 0\n ct_even = 0\n for i in range(N):\n s += arr[i]\n if s % 2 == 1:\n tot += 1 + ct_even\n ct_odd += 1\n else:\n tot += ct_odd\n ct_even += 1\n return tot % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n count = len(arr)\n pre_odd_count = arr[0] % 2\n pre_even_count = 1 - pre_odd_count\n result = pre_odd_count\n for index in range(1, count):\n isodd = arr[index] % 2\n if isodd:\n temp = pre_odd_count\n pre_odd_count = 1 + pre_even_count\n pre_even_count = temp\n else:\n pre_odd_count = pre_odd_count\n pre_even_count = 1 + pre_even_count\n result += pre_odd_count\n return result % 1000000007", "import copy\n\ndef numofsubarrays(arr: List[int]) -> int:\n mod = 10 ** 9 + 7\n arr1 = arr.copy()\n for i in range(1, len(arr)):\n arr1[i] += arr1[i - 1]\n (odd, even) = (0, 0)\n cou = 0\n for i in range(len(arr1)):\n if arr1[i] % 2 == 0:\n even += 1\n else:\n odd += 1\n for i in range(len(arr1)):\n if arr1[i] % 2 == 1:\n cou += 1\n cou += odd * even\n return cou % mod", "def numofsubarrays(arr: List[int]) -> int:\n (s, d, ans) = (0, 0, 0)\n for n in arr:\n if n % 2:\n (s, d) = (d, s)\n s += 1\n else:\n d += 1\n ans += s\n return ans % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n (odd, even) = ([0] * n, [0] * n)\n for (i, v) in enumerate(arr):\n if not i:\n odd[i] += v % 2 == 1\n even[i] += v % 2 != 1\n elif v % 2:\n odd[i] += 1 + even[i - 1]\n even[i] += odd[i - 1]\n else:\n odd[i] += odd[i - 1]\n even[i] += 1 + even[i - 1]\n return sum(odd) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n N = len(arr)\n if N == 0:\n return 0\n elif N == 1:\n return abs(arr[0]) % 2\n l1 = 0\n l2 = 0\n if arr[0] % 2:\n l1 += 1\n else:\n l2 += 1\n tot = 0\n tot += l1\n for i in range(1, N):\n l3 = 0\n l4 = 0\n if arr[i] % 2:\n l3 = 1 + l2\n l4 = l1\n else:\n l3 = l1\n l4 = 1 + l2\n l2 = l4\n l1 = l3\n tot += l1\n return tot % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n M = 10 ** 9 + 7\n new_arr = [1 if i % 2 == 1 else 0 for i in arr]\n res = 0\n cucr_sum = 0\n cash = {0: 1, 1: 0}\n for end in range(len(new_arr)):\n cucr_sum += new_arr[end]\n if cucr_sum % 2 == 1:\n res += cash[0]\n cash[1] += 1\n else:\n res += cash[1]\n cash[0] += 1\n return res % M", "def numofsubarrays(arr: List[int]) -> int:\n (mod, n) = (10 ** 9 + 7, len(arr))\n (odd_sum, even_sum, curr_sum, ans) = (0, 1, 0, 0)\n for i in arr:\n curr_sum += i\n if curr_sum % 2 == 1:\n odd_sum += 1\n ans += even_sum % mod\n else:\n even_sum += 1\n ans += odd_sum % mod\n ans %= mod\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n (odd_sum, even_sum, cur_sum, ans) = (0, 1, 0, 0)\n mod = 10 ** 9 + 7\n for i in arr:\n cur_sum += i\n if cur_sum % 2 != 0:\n odd_sum += 1\n ans += even_sum % mod\n if cur_sum % 2 == 0:\n even_sum += 1\n ans += odd_sum % mod\n ans = ans % mod\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n dp = [0, 0]\n res = cur = 0\n for i in arr:\n cur ^= i & 1\n res += cur + dp[1 - cur]\n dp[cur] += 1\n return res % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n MOD = 10 ** 9 + 7\n memo = {0: 0, 1: 0}\n cumsum = 0\n res = 0\n for v in arr:\n cumsum += v\n if cumsum % 2 == 0:\n memo[0] += 1\n res = (res + memo[1]) % MOD\n else:\n memo[1] += 1\n res = (1 + res + memo[0]) % MOD\n return res", "from itertools import accumulate\n\ndef numofsubarrays(arr: List[int]) -> int:\n\n def num_subarrays(k):\n return (k * k + k) // 2\n counts = [0, 0]\n for prefix in accumulate(arr):\n counts[prefix % 2] += 1\n (evens, odds) = counts\n return (num_subarrays(len(arr)) - (num_subarrays(evens) + (num_subarrays(odds) - odds))) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n prefix = [0]\n for num in arr:\n prefix.append(prefix[-1] ^ num & 1)\n zeros = 0\n ones = 0\n result = 0\n for x in prefix:\n if x == 1:\n ones += 1\n result += zeros\n else:\n zeros += 1\n result += ones\n return result % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n ans = 0\n mod = 1000000000.0 + 7\n seen = [1, 0]\n for i in range(len(arr)):\n if i > 0:\n arr[i] += arr[i - 1]\n ans += seen[(arr[i] + 1) % 2]\n ans %= mod\n seen[arr[i] % 2] += 1\n return int(ans)", "def numofsubarrays(arr: List[int]) -> int:\n cursum = 0\n ans = 0\n if arr[0] % 2:\n cursum = 1\n ans = 1\n for i in range(1, len(arr)):\n if arr[i] % 2:\n cursum = i - cursum + 1\n ans = ans + cursum\n return ans % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n memo = {0: 1, 1: 0}\n cnt = 0\n curr_sum = 0\n K = 10 ** 9 + 7\n for n in arr:\n curr_sum += n\n if curr_sum % 2 == 0:\n cnt += memo[1]\n else:\n cnt += memo[0]\n memo[curr_sum % 2] += 1\n cnt = cnt % K\n return cnt", "def numofsubarrays(arr: List[int]) -> int:\n s = [0, 0]\n res = 0\n cur = 0\n for x in arr:\n cur = (cur + x) % 2\n res += s[1 - cur]\n res += int(cur == 1)\n s[cur] += 1\n return res % (10 ** 9 + 7)", "MOD = 10 ** 9 + 7\n\ndef numofsubarrays(arr: List[int]) -> int:\n odd_cum_sums = 0\n even_cum_sums = 0\n total_odd_sums = 0\n for i in range(len(arr) - 1):\n arr[i + 1] += arr[i]\n for sum_ in arr:\n if sum_ % 2 == 0:\n total_odd_sums += odd_cum_sums\n even_cum_sums += 1\n else:\n total_odd_sums += 1 + even_cum_sums\n odd_cum_sums += 1\n return total_odd_sums % MOD", "def numofsubarrays(arr: List[int]) -> int:\n ans = 0\n (seen_odd, seen_even) = (set(), set())\n (odd_count, even_count) = (0, 1)\n psum = 0\n mod = 10 ** 9 + 7\n for a in arr:\n psum += a\n if psum % 2 == 0:\n ans = (ans + odd_count) % mod\n seen_even.add(psum)\n even_count += 1\n else:\n ans = (ans + even_count) % mod\n seen_odd.add(psum)\n odd_count += 1\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n c = collections.defaultdict(int)\n s = 0\n c[0] += 1\n res = 0\n mod = 10 ** 9 + 7\n for x in arr:\n s ^= x % 2\n res += c[1 - s]\n res %= mod\n c[s] += 1\n return res", "def numofsubarrays(arr: List[int]) -> int:\n A = [i % 2 for i in arr]\n n = len(A)\n lst = [[0, 0]]\n lst[0][A[0] & 1] = 1\n for i in range(1, n):\n if A[i]:\n lst.append([lst[-1][1], 1 + lst[-1][0]])\n else:\n lst.append([1 + lst[-1][0], lst[-1][1]])\n return sum([x[1] for x in lst]) % (10 ** 9 + 7)", "def accumulate(arr):\n acc = 0\n for elem in arr:\n acc = (acc + elem) % 2\n yield acc\n\ndef numofsubarrays(arr: List[int]) -> int:\n parity_array = (x % 2 for x in arr)\n cumulative_array = accumulate(parity_array)\n prev = [1, 0]\n ans = 0\n for elem in cumulative_array:\n ans += [prev[1], prev[0]][elem]\n prev[elem] += 1\n return ans % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n count = arr[0] % 2\n currentCount = count\n for i in range(1, len(arr)):\n if arr[i] % 2 == 1:\n currentCount = i - currentCount + 1\n count += currentCount\n return count % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n count = len(arr)\n isodd = [item % 2 for item in arr]\n odd_end_total = [0] * count\n even_end_total = [0] * count\n odd_end_total[0] = isodd[0]\n even_end_total[0] = 1 - odd_end_total[0]\n for index in range(1, count):\n if isodd[index]:\n odd_end_total[index] = 1 + even_end_total[index - 1]\n even_end_total[index] = odd_end_total[index - 1]\n else:\n odd_end_total[index] = odd_end_total[index - 1]\n even_end_total[index] = 1 + even_end_total[index - 1]\n result = 0\n for index in range(count):\n result += odd_end_total[index]\n return result % 1000000007", "def isEven(n):\n return n % 2 == 0\n\ndef isOdd(n):\n return not isEven(n)\n\ndef numofsubarrays(arr: List[int]) -> int:\n od = list(range(len(arr)))\n ev = list(range(len(arr)))\n if isEven(arr[0]):\n od[0] = 0\n ev[0] = 1\n else:\n od[0] = 1\n ev[0] = 0\n for (i, num) in enumerate(arr):\n if i == 0:\n continue\n if isOdd(num):\n od[i] = ev[i - 1] + 1\n ev[i] = od[i - 1]\n else:\n od[i] = od[i - 1]\n ev[i] = ev[i - 1] + 1\n ans = 0\n for num in od:\n ans += num\n return ans % (10 ** 9 + 7)", "M = int(1000000000.0 + 7)\n\ndef numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n odd = [-1] * n\n even = [-1] * n\n odd[0] = 1 if arr[0] % 2 == 1 else 0\n even[0] = 1 if arr[0] % 2 == 0 else 0\n for i in range(1, n):\n v = arr[i]\n if v % 2 == 1:\n odd[i] = (1 + even[i - 1]) % M\n even[i] = odd[i - 1]\n else:\n odd[i] = odd[i - 1]\n even[i] = (even[i - 1] + 1) % M\n ret = 0\n for v in odd:\n ret = (ret + v) % M\n return ret", "def numofsubarrays(arr: List[int]) -> int:\n limit = 10 ** 9 + 7\n final = 0\n dp_even = [0] * (len(arr) + 1)\n dp_odd = [0] * (len(arr) + 1)\n for i in range(len(arr)):\n num = arr[i]\n if num % 2 == 0:\n odd_cur = dp_odd[i]\n even_cur = 1 + dp_even[i]\n final += odd_cur\n dp_even[i + 1] = even_cur\n dp_odd[i + 1] = odd_cur\n else:\n odd_cur = dp_even[i] + 1\n even_cur = dp_odd[i]\n final += odd_cur\n dp_odd[i + 1] = odd_cur\n dp_even[i + 1] = even_cur\n return final % limit", "def numofsubarrays(arr: List[int]) -> int:\n odd = [0 for x in arr]\n even = [0 for x in arr]\n odd[0] = 1 if arr[0] % 2 == 1 else 0\n even[0] = 1 if arr[0] % 2 == 0 else 0\n for i in range(1, len(arr)):\n if arr[i] % 2 == 0:\n odd[i] = odd[i - 1]\n even[i] = even[i - 1] + 1\n else:\n odd[i] = even[i - 1] + 1\n even[i] = odd[i - 1]\n return sum(odd) % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n mod = 10 ** 9 + 7\n for i in range(len(arr)):\n arr[i] %= 2\n n = len(arr)\n dp = []\n ones = 0\n zeroes = 0\n for i in arr:\n if not dp:\n dp.append(i)\n else:\n dp.append(dp[-1] + i)\n dp[-1] %= 2\n if dp[-1] == 0:\n zeroes += 1\n else:\n ones += 1\n total = n * (n + 1) // 2\n total -= ones * (ones - 1) // 2\n total -= zeroes + zeroes * (zeroes - 1) // 2\n return total % mod", "def numofsubarrays(arr: List[int]) -> int:\n r = 0\n e = 0\n o = 0\n for i in arr:\n if i % 2 == 1:\n r += e + 1\n (o, e) = (e + 1, o)\n else:\n r += o\n (o, e) = (o, e + 1)\n a = 10 ** 9 + 7\n return r % a", "def numofsubarrays(arr: List[int]) -> int:\n odd = 0\n even = 0\n n = len(arr)\n sumlist = [0] * n\n output = 0\n for i in range(n - 1, -1, -1):\n if i != n - 1:\n sumlist[i] += arr[i] + sumlist[i + 1]\n else:\n sumlist[i] += arr[i]\n if sumlist[i] % 2 == 0:\n output += odd\n even += 1\n else:\n output += 1\n output += even\n odd += 1\n output %= 10 ** 9 + 7\n return output", "def numofsubarrays(arr: List[int]) -> int:\n dp = [[0, 0]]\n ans = 0\n for i in arr:\n if i % 2 == 0:\n dp.append([dp[-1][0] + 1, dp[-1][1]])\n else:\n dp.append([dp[-1][1], dp[-1][0] + 1])\n ans += dp[-1][1]\n return int(ans % (1000000000.0 + 7))", "def numofsubarrays(arr: List[int]) -> int:\n dp = [-1 for i in range(len(arr))]\n dp[0] = [(arr[0] + 1) % 2, arr[0] % 2]\n total = dp[0][1]\n for k in range(1, len(arr)):\n if arr[k] % 2 == 0:\n dp[k] = [(dp[k - 1][0] + 1) % (10 ** 9 + 7), dp[k - 1][1] % (10 ** 9 + 7)]\n total += dp[k][1]\n total = total % (10 ** 9 + 7)\n else:\n dp[k] = [dp[k - 1][1] % (10 ** 9 + 7), (dp[k - 1][0] + 1) % (10 ** 9 + 7)]\n total += dp[k][1]\n total = total % (10 ** 9 + 7)\n return total % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n mod = 10 ** 9 + 7\n result = 0\n sumOdd = [0] * len(arr)\n sumEven = [0] * len(arr)\n if arr[0] % 2 == 1:\n sumOdd[0] = 1\n sumEven[0] = 0\n else:\n sumOdd[0] = 0\n sumEven[0] = 1\n for i in range(1, len(sumOdd)):\n if arr[i] % 2 == 0:\n sumOdd[i] = sumOdd[i - 1]\n sumEven[i] = sumEven[i - 1] + 1\n else:\n sumOdd[i] = sumEven[i - 1] + 1\n sumEven[i] = sumOdd[i - 1]\n return sum(sumOdd) % mod"], "starter_code": "def numofsubarrays(arr: List[int]) -> int:\n", "input_output": {"fn_name": "numOfSubarrays", "inputs": [[[1, 3, 5]]], "outputs": [4]}, "difficulty": "MEDIUM", "raw_tags": ["Prefix Sum", "Math", "Dynamic Programming", "Array"], "name": null, "source": "leetcode", "tags": ["Mathematics", "Dynamic programming", "Data structures", "Range queries"], "skill_types": ["Dynamic programming", "Data structures", "Range queries"], "url": "https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numofsubarrays", "task_id": "TACO_lite/252", "example": [[[[1, 3, 5]], [[2, 4, 6]], [[1, 2, 3, 4, 5, 6, 7]], [[100, 100, 99, 99]], [[7]]], ["4", "0", "16", "4", "1"]]} +{"requirement": "We partition a row of numbers A into at most K adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve?\nNote that our partition must use every number in A, and that scores are not necessarily integers.\nExample:\nInput: \nA = [9,1,2,3,9]\nK = 3\nOutput: 20\nExplanation: \nThe best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\nWe could have also partitioned A into [9, 1], [2], [3, 9], for example.\nThat partition would lead to a score of 5 + 2 + 6 = 13, which is worse.\n\n \nNote: \n\n1 <= A.length <= 100.\n1 <= A[i] <= 10000.\n1 <= K <= A.length.\nAnswers within 10^-6 of the correct answer will be accepted as correct.", "solutions": ["def largestsumofaverages(A: List[int], K: int) -> float:\n N = len(A)\n P = [0] * (N + 1)\n for i in range(1, N + 1):\n P[i] = P[i - 1] + A[i - 1]\n Table = [(P[N] - P[i]) / (N - i) for i in range(N)]\n for k in range(2, K + 1):\n for i in range(K - k, N - k + 1):\n Table[i] = max(((P[j] - P[i]) / (j - i) + Table[j] for j in range(i + 1, N - k + 2)))\n return Table[0]", "from functools import lru_cache\nfrom itertools import accumulate\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n p = [0] + list(accumulate(A))\n\n def dp(l, k):\n if k > l:\n return 0\n if k == 1:\n return p[l] / l\n return max((dp(i, k - 1) + (p[l] - p[i]) / (l - i) for i in range(k - 1, l)))\n return dp(n, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n memo = [[0 for k in range(K)] for i in range(n)]\n\n def aux(A, cur, k, memo):\n if cur == len(A):\n return 0\n if memo[cur][k]:\n return memo[cur][k]\n tmp = sum(A[cur:]) / (len(A) - cur)\n if k == 0:\n memo[cur][k] = tmp\n return tmp\n for i in range(cur + 1, len(A) + 1):\n tmp = max(tmp, sum(A[cur:i]) / (i - cur) + aux(A, i, k - 1, memo))\n memo[cur][k] = tmp\n return tmp\n return aux(A, 0, K - 1, memo)", "def largestsumofaverages(A, K: int) -> float:\n A = [0] + A\n len_a = len(A)\n dp = [[0] * (K + 1) for _ in range(len_a)]\n for i in range(1, len_a):\n dp[i][0] = -float('inf')\n for i in range(1, len_a):\n for k in range(1, min(K + 1, i + 1)):\n for j in range(k, i + 1):\n dp[i][k] = max(dp[i][k], dp[j - 1][k - 1] + self.helper(A[j:i + 1]))\n return dp[-1][-1]\n\ndef helper(sub_a):\n return sum(sub_a) / len(sub_a)", "def largestsumofaverages(A: List[int], K: int) -> float:\n P = [0] * (len(A) + 1)\n for (i, n) in enumerate(A):\n P[i + 1] = P[i] + n\n\n def average(i, j):\n return (P[j] - P[i]) / float(j - i)\n N = len(A)\n dp = [average(i, N) for i in range(N)]\n for k in range(K - 1):\n for i in range(N):\n for j in range(i + 1, N):\n dp[i] = max(dp[i], average(i, j) + dp[j])\n return dp[0]", "def largestsumofaverages(A, K):\n prefix_sum = [0]\n for x in A:\n prefix_sum.append(prefix_sum[-1] + x)\n\n def average(i, j):\n return (prefix_sum[j] - prefix_sum[i]) / (j - i)\n n = len(A)\n dp = [[0] * n for _ in range(K)]\n for k in range(K):\n for i in range(n):\n if k == 0 and i == 0:\n dp[0][i] = A[0]\n elif k == 0:\n dp[0][i] = average(0, i + 1)\n else:\n for j in range(i):\n dp[k][i] = max(dp[k][i], dp[k - 1][j] + average(i + 1, j + 1))\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n memo = {}\n length = len(A)\n\n def dfs(start, k):\n if (start, k) in memo:\n return memo[start, k]\n if k == 1:\n memo[start, k] = sum(A[start:]) / (length - start)\n return memo[start, k]\n if start >= length:\n return 0\n value = 0\n for i in range(start + 1, length):\n val = sum(A[start:i]) / (i - start)\n value = max(value, dfs(i, k - 1) + val)\n memo[start, k] = value\n return value\n return dfs(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n (s, dp) = ([0] + A, {})\n for i in range(1, len(A) + 1):\n s[i] += s[i - 1]\n\n def dfs(i, k):\n if k == 1:\n return (s[-1] - s[i]) / (len(A) - i)\n if (i, k) in dp:\n return dp[i, k]\n dp[i, k] = max(((s[j] - s[i]) / (j - i) + dfs(j, k - 1) for j in range(i + 1, len(A) - k + 2)))\n return dp[i, k]\n return dfs(0, K)", "import itertools\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n P = [0] + list(itertools.accumulate(A))\n\n def average(i, j):\n return (P[j] - P[i]) / float(j - i)\n N = len(A)\n dp = [average(i, N) for i in range(N)]\n for _ in range(K - 1):\n for i in range(N):\n for j in range(i + 1, N):\n dp[i] = max(dp[i], average(i, j) + dp[j])\n return dp[0]", "def largestsumofaverages(A: List[int], K: int) -> float:\n cumsums = [0] * (len(A) + 1)\n for (i, x) in enumerate(A):\n cumsums[i + 1] = cumsums[i] + A[i]\n memo = {}\n\n def DP(j, K):\n if K == 0:\n return 0\n if j + 1 == K:\n return cumsums[j + 1]\n if K == 1:\n return cumsums[j + 1] / (j + 1)\n res = 0\n for i in range(j, -1, -1):\n if (i, K - 1) not in memo:\n memo[i, K - 1] = DP(i, K - 1)\n if j - i == 0:\n res = max(res, memo[i, K - 1])\n else:\n res = max(res, memo[i, K - 1] + (cumsums[j + 1] - cumsums[i + 1]) / (j - i))\n return res\n a = DP(len(A) - 1, K)\n return a", "def largestsumofaverages(A, K):\n memo = {}\n\n def search(n, k):\n if (n, k) in memo:\n return memo[n, k]\n if n < k:\n return 0\n if k == 1:\n memo[n, k] = sum(A[:n]) / float(n)\n return memo[n, k]\n (cur, memo[n, k]) = (0, 0)\n for i in range(n - 1, 0, -1):\n cur += A[i]\n memo[n, k] = max(memo[n, k], search(i, k - 1) + cur / float(n - i))\n return memo[n, k]\n return search(len(A), K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n Cum = [0]\n for i in range(len(A)):\n Cum.append(Cum[-1] + A[i])\n\n def Average(h, k):\n return (Cum[k] - Cum[h]) / (k - h)\n dp = [Average(i, len(A)) for i in range(len(A))]\n for _ in range(K - 1):\n for i in range(len(A)):\n for j in range(i + 1, len(A)):\n dp[i] = max(dp[i], Average(i, j) + dp[j])\n return dp[0]", "def largestsumofaverages(A: List[int], K: int) -> float:\n presum = [0] + list(itertools.accumulate(A))\n\n def mean(i, j):\n return (presum[j + 1] - presum[i]) / (j - i + 1)\n max_val = [0]\n\n def helper(i, j, k):\n if (i, j, k) in check:\n result = check[i, j, k]\n elif k == 1:\n result = mean(i, j)\n else:\n result = -float('inf')\n for mid in range(i, j):\n result = max(result, mean(i, mid) + helper(mid + 1, j, k - 1))\n check[i, j, k] = result\n max_val[0] = max(max_val[0], result)\n return result\n n = len(A)\n check = {}\n helper(0, n - 1, K)\n return max_val[0]", "def largestsumofaverages(A: List[int], K: int) -> float:\n import itertools\n cumsum = list(itertools.accumulate(A))\n L = len(A)\n K = min(L, K)\n dp = [[0] * (K + 1) for i in range(L)]\n for i in range(L):\n dp[i][1] = cumsum[i] / (i + 1)\n for k in range(2, K + 1):\n for i in range(L):\n tmp = dp[i][k - 1]\n for j in range(i):\n tmp = max(tmp, dp[j][k - 1] + (cumsum[i] - cumsum[j]) / (i - j))\n dp[i][k] = tmp\n return dp[-1][K]", "def largestsumofaverages(A: List[int], K: int) -> float:\n\n def ave(list_):\n return sum(list_) / len(list_)\n dp = {}\n\n def rec(index, k):\n if index == len(A):\n return 0\n if (index, k) in dp:\n return dp[index, k]\n if k == 1:\n return ave(A[index:])\n m = 0\n for i in range(index + 1, len(A)):\n m = max(m, ave(A[index:i]) + rec(i, k - 1))\n dp[index, k] = m\n return m\n return rec(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n L = len(A)\n dp = [[0 for _ in range(K + 1)] for _out in range(L)]\n prefix_sum = [0 for _ in range(L + 1)]\n for i in range(1, L + 1):\n prefix_sum[i] = prefix_sum[i - 1] + A[i - 1]\n dp[0][1] = A[0]\n for i in range(1, L):\n dp[i][1] = (prefix_sum[i] + A[i]) / (i + 1)\n for i in range(1, L):\n for k in range(2, K + 1):\n if k > i + 1:\n dp[i][k] = dp[i][k - 1]\n else:\n for j in range(-1, i):\n subarr = A[j + 1:i + 1]\n ave = (prefix_sum[i + 1] - prefix_sum[j + 1]) / (i - j)\n if j == -1:\n tmp = 0\n else:\n tmp = dp[j][k - 1]\n if ave + tmp > dp[i][k]:\n dp[i][k] = ave + tmp\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n h = {}\n\n def helper(curr, pos, k):\n if pos == len(A):\n return curr\n if k == 0:\n return float('-inf')\n if (pos, k) in h:\n return curr + h[pos, k]\n res = 0\n for i in range(pos, len(A)):\n temp = sum(A[pos:i + 1]) / (i - pos + 1)\n res = max(helper(temp, i + 1, k - 1), res)\n h[pos, k] = res\n return curr + res\n return helper(0, 0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n N = len(A)\n summary = [0] * (N + 1)\n for (i, item) in enumerate(A):\n summary[i + 1] = summary[i] + item\n dp = [[(summary[N] - summary[i]) / (N - i) for i in range(N)] for _ in range(K)]\n for remain in range(1, K):\n for i in range(N):\n for j in range(i + 1, N):\n dp[remain][i] = max(dp[remain][i], (summary[j] - summary[i]) / (j - i) + dp[remain - 1][j])\n return dp[-1][0]", "def largestsumofaverages(A: List[int], K: int) -> float:\n dp = {}\n\n def a(n, k):\n if n < k:\n return 0\n if (n, k) in dp:\n return dp[n, k]\n if k == 1:\n dp[n, k] = sum(A[:n]) / float(n)\n return dp[n, k]\n dp[n, k] = 0\n for i in range(n - 1, 0, -1):\n a(i, k - 1)\n dp[n, k] = max(dp[n, k], a(i, k - 1) + sum(A[i:n]) / float(n - i))\n a(len(A), K)\n return dp[len(A), K]", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n dp = [[0] * (K + 1) for _ in range(n + 1)]\n for i in range(1, n + 1):\n dp[i][1] = sum(A[:i]) / i\n for i in range(2, n + 1):\n for j in range(2, min(K + 1, i + 1)):\n dp[i][j] = max([dp[i - t][j - 1] + sum(A[i - t:i]) / t for t in range(1, i)])\n return dp[n][K]", "def largestsumofaverages(A: List[int], K: int) -> float:\n mem = {}\n\n def dfs(l, K):\n if (l, K) in mem:\n return mem[l, K]\n if l == len(A):\n return 0\n if K == 1:\n return sum(A[l:]) / len(A[l:])\n ans = sum(A[l:]) / len(A[l:])\n for i in range(l + 1, len(A)):\n avg = sum(A[l:i]) / len(A[l:i])\n ans = max(ans, avg + dfs(i, K - 1))\n mem[l, K] = ans\n return ans\n return dfs(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n\n def dfs(i, partitions):\n if partitions == 1:\n return (cum[len(A)] - cum[i - 1]) / (len(A) - i + 1)\n mem[partitions][i] = 0\n for j in range(i, len(A) + 1):\n if mem[partitions - 1][j] == 0:\n mem[partitions - 1][j] = dfs(j, partitions - 1)\n if j > i:\n mem[partitions][i] = max(mem[partitions][i], mem[partitions - 1][j] + (cum[j - 1] - cum[i - 1]) / (j - i))\n else:\n mem[partitions][i] = max(mem[partitions][i], mem[partitions - 1][j])\n return mem[partitions][i]\n ans = 0\n cum = [0 for i in range(len(A) + 1)]\n mem = [[0 for i in range(len(A) + 1)] for j in range(K + 1)]\n cum[0] = 0\n for i in range(len(A)):\n cum[i + 1] = cum[i] + A[i]\n return dfs(1, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n from functools import lru_cache\n\n def maxAverage(j, k):\n if j == k:\n return sum(A[:j])\n if k == 1:\n return sum(A[:j]) / j\n ans = 0\n for i in range(j - 1, max(-1, k - 2), -1):\n ans = max(ans, sum(A[i:j]) / (j - i) + maxAverage(i, k - 1))\n return ans\n return maxAverage(len(A), K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n N = len(A)\n pre_sum = [0 for i in range(N)]\n pre_sum[0] = A[0]\n for j in range(1, len(A)):\n pre_sum[j] = pre_sum[j - 1] + A[j]\n dp = [[0 for n in range(N)] for k in range(K + 1)]\n for i in range(N):\n dp[1][i] = pre_sum[i] / (i + 1)\n for k in range(2, K + 1):\n for i in range(N):\n for j in range(i):\n dp[k][i] = max(dp[k][i], pre_sum[i] / (i + 1), dp[k - 1][j] + (pre_sum[i] - pre_sum[j]) / (i - j))\n return dp[K][N - 1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n N = len(A)\n\n def dfs(index, remain, acc, size):\n if index >= N:\n return 0 if size == 0 else acc / size\n ans = 0\n if remain > 0:\n ans = max(ans, (acc + A[index]) / (size + 1) + dfs(index + 1, remain - 1, 0, 0))\n ans = max(ans, dfs(index + 1, remain, acc + A[index], size + 1))\n return ans\n return dfs(0, K - 1, 0, 0)", "def largestsumofaverages(A: List[int], K: int) -> float:\n self.dp = {}\n self.arr = A\n ans = self.helper(0, K - 1)\n return ans\n\ndef helper(i, k):\n if k == 0:\n return sum(self.arr[i:]) / len(self.arr[i:])\n if i == len(self.arr) - 1:\n return -10 ** 100\n if (i, k) in self.dp:\n return self.dp[i, k]\n ans = 0\n for j in range(i, len(self.arr) - 1):\n tmp = sum(self.arr[i:j + 1]) / len(self.arr[i:j + 1]) + self.helper(j + 1, k - 1)\n ans = max(ans, tmp)\n self.dp[i, k] = ans\n return self.dp[i, k]", "def part(A, i, K, cache):\n if i < 0:\n if K == 0:\n return 0\n return float('-Inf')\n if i == 0:\n if K != 1:\n return float('-Inf')\n return A[i]\n key = '{}-{}'.format(i, K)\n if key in cache:\n return cache[key]\n res = float('-Inf')\n sm = 0\n count = 0\n for j in range(i, -1, -1):\n sm += A[j]\n count += 1\n avg = float(sm) / float(count)\n res = max(res, avg + self.part(A, j - 1, K - 1, cache))\n cache[key] = res\n return res\n\ndef solve(A, K):\n return self.part(A, len(A) - 1, K, {})\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n return self.solve(A, K)", "def largestsumofaverages(A: List[int], k: int) -> float:\n n = len(A)\n mtr = [[0 for i in range(n + 1)] for j in range(k + 1)]\n\n def rec(parts, arrIndex):\n if mtr[parts][arrIndex] != 0:\n return mtr[parts][arrIndex]\n if parts == 1:\n mtr[parts][arrIndex] = sum(A[:arrIndex + 1]) / (arrIndex + 1)\n return mtr[parts][arrIndex]\n for x in range(1, arrIndex + 1):\n mtr[parts][arrIndex] = max(mtr[parts][arrIndex], rec(parts - 1, x - 1) + sum(A[x:arrIndex + 1]) / (arrIndex + 1 - x))\n return mtr[parts][arrIndex]\n rec(k, n - 1)\n ans = sys.maxsize * -1\n for i in range(1, k + 1):\n ans = max(ans, mtr[i][-2])\n return ans", "def largestsumofaverages(A: List[int], K: int) -> float:\n self.memo = {}\n\n def helper(start, end, K, prefix):\n if (start, end, K) in self.memo.keys():\n return self.memo[start, end, K]\n if K == 0:\n return (prefix[end + 1] - prefix[start]) / (end - start + 1)\n if end == start:\n return prefix[end + 1] - prefix[end]\n if end < start:\n return 0\n maxAvg = 0\n for i in range(start, end):\n maxAvg = max(maxAvg, (prefix[i + 1] - prefix[start]) / (i - start + 1) + helper(i + 1, end, K - 1, prefix))\n self.memo[start, end, K] = maxAvg\n return maxAvg\n n = len(A)\n prefix = [0 for _ in range(n + 1)]\n for i in range(1, n + 1):\n prefix[i] = prefix[i - 1] + A[i - 1]\n ans = 0\n for k in range(K):\n ans = max(ans, helper(0, n - 1, k, prefix))\n return ans", "def largestsumofaverages(A: List[int], K: int) -> float:\n len_A = len(A)\n dp = [[0 if j else sum(A[:i + 1]) / (i + 1) for j in range(K)] for i in range(len_A)]\n for i in range(len_A):\n for j in range(1, K):\n if j > i:\n break\n for k in range(i):\n dp[i][j] = max(dp[i][j], dp[k][j - 1] + sum(A[k + 1:i + 1]) / (i - k))\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n p = [0]\n for i in range(n):\n p.append(p[i] + A[i])\n\n def average(i, j):\n return (p[j] - p[i]) / (j - i)\n dp = [[0] * n for _ in range(K)]\n for i in range(n):\n dp[0][i] = average(i, n)\n for k in range(1, K):\n for i in range(n):\n for j in range(i + 1, n):\n dp[k][i] = max(dp[k][i], average(i, j) + dp[k - 1][j])\n return dp[K - 1][0]", "def mean(l):\n return sum(l) / len(l)\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n DP = [self.mean(A[i:n]) for i in range(n)]\n for k in range(K - 1):\n for i in range(n):\n for j in range(i + 1, n):\n DP[i] = max(DP[i], self.mean(A[i:j]) + DP[j])\n return DP[0]", "def largestsumofaverages(A: List[int], K: int) -> float:\n\n def avg(array):\n return sum(array) / len(array)\n dp = [[0 for _ in range(K)] for _ in range(len(A))]\n dp[0][0] = A[0]\n for i in range(len(A)):\n for j in range(K):\n if j == 0:\n dp[i][j] = avg(A[:i + 1])\n else:\n for k in range(i):\n dp[i][j] = max(dp[i][j], dp[k][j - 1] + avg(A[k + 1:i + 1]))\n return dp[len(A) - 1][K - 1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n self.arr = [[None for i in range(K)] for i in range(len(A))]\n res = self.solve(A, 0, K, -1)\n return res\n\ndef solve(arr, i, grpLeft, lastInd):\n if i == len(arr):\n return 0\n if self.arr[lastInd + 1][grpLeft - 1] != None:\n return self.arr[lastInd + 1][grpLeft - 1]\n if grpLeft == 1:\n self.arr[lastInd + 1][0] = sum(arr[lastInd + 1:]) / (len(arr) - lastInd - 1)\n return self.arr[i][0]\n avg = float(sum(arr[lastInd + 1:i + 1])) / (i - lastInd)\n self.arr[lastInd + 1][grpLeft - 1] = max(self.solve(arr, i + 1, grpLeft, lastInd), avg + self.solve(arr, i + 1, grpLeft - 1, i))\n return self.arr[lastInd + 1][grpLeft - 1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n dp = [[0] * (K + 1) for i in range(n)]\n total = [A[0]]\n for i in range(1, n):\n total.append(A[i] + total[i - 1])\n\n def solve(start, k):\n if dp[start][k] != 0:\n return dp[start][k]\n if k == 1:\n dp[start][k] = (total[n - 1] - total[start] + A[start]) / (n - start)\n return dp[start][k]\n i = start\n while i + k <= n:\n temp = (total[i] - total[start] + A[start]) / (i - start + 1) + solve(i + 1, k - 1)\n dp[start][k] = max(dp[start][k], temp)\n i += 1\n return dp[start][k]\n return solve(0, K)", "def largestsumofaverages(A, K: int) -> float:\n dp = []\n for i in range(len(A)):\n tmp = []\n for j in range(1, 1 + K):\n tmp.append(0)\n dp.append(tmp)\n v = 0\n for i in range(len(dp)):\n v += A[i]\n for j in range(len(dp[0])):\n if j == 0:\n dp[i][j] = v / (i + 1)\n elif j == i:\n dp[i][j] = v\n for i in range(len(dp)):\n for j in range(1, min(i, K)):\n for t in range(i):\n dp[i][j] = max(dp[i][j], dp[t][j - 1] + self.avg(A[t + 1:i + 1]))\n return dp[-1][-1]\n\ndef avg(nums):\n return sum(nums) / len(nums)", "def largestsumofaverages(A: List[int], K: int) -> float:\n accsum = A[:]\n l = len(accsum)\n for i in range(1, l):\n accsum[i] += accsum[i - 1]\n cache = {}\n\n def dp(i, k):\n prev = accsum[i - 1] if i > 0 else 0\n if k == 1:\n res = (accsum[l - 1] - prev) / (l - i)\n cache[i, k] = res\n return res\n if (i, k) in cache:\n return cache[i, k]\n if l - i < k:\n return -float('inf')\n if l - i == k:\n res = accsum[l - 1] - prev\n cache[i, k] = res\n return res\n res = 0\n for j in range(i, l - k + 1):\n res = max(res, (accsum[j] - prev) / (j - i + 1) + dp(j + 1, k - 1))\n cache[i, k] = res\n return res\n return dp(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n memo = {}\n\n def fn(nums, k):\n if len(nums) <= k:\n return sum(nums)\n elif k == 1:\n return sum(nums) / len(nums)\n else:\n max_avg = 0\n for i in reversed(range(len(nums))):\n key = (tuple([num for num in nums[:i]]), k - 1)\n if key not in memo:\n memo[key] = fn([num for num in nums[:i]], k - 1)\n avg = memo[key] + sum(nums[i:]) / (len(nums) - i)\n max_avg = max(max_avg, avg)\n return max_avg\n return fn(A, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n averages = [[None for _ in range(n)] for _ in range(n)]\n for i in range(n):\n averages[i][i] = A[i]\n for i in range(n - 1):\n for j in range(i + 1, n):\n averages[i][j] = (averages[i][j - 1] * (j - i) + A[j]) / (j - i + 1)\n dp = [[None for _ in range(K)] for _ in range(n + 1)]\n\n def largestSum(i, count):\n if dp[i][count] != None:\n return dp[i][count]\n if i == n:\n dp[i][count] = 0\n return 0\n if count == K - 1:\n dp[i][count] = averages[i][n - 1]\n return averages[i][n - 1]\n largest = float('-inf')\n for k in range(n):\n largest = max(largest, averages[i][min(i + k, n - 1)] + largestSum(min(i + k + 1, n), count + 1))\n dp[i][count] = largest\n return largest\n return largestSum(0, 0)", "def largestsumofaverages(a: List[int], k: int) -> float:\n\n def rec(st, k):\n if (st, k) in cache:\n return cache[st, k]\n if k == 1:\n cache[st, k] = sum(a[st:]) / (len(a) - st)\n return cache[st, k]\n total = 0\n res = -math.inf\n for i in range(st, len(a) - k + 1):\n total += a[i]\n res = max(res, total / (i - st + 1) + rec(i + 1, k - 1))\n cache[st, k] = res\n return cache[st, k]\n cache = {}\n return rec(0, k)", "def find(dp, start, end, k, arr):\n if start > end:\n return -float('inf')\n if k <= 0:\n return -float('inf')\n if (start, end, k) in dp.keys():\n return dp[start, end, k]\n if start == end:\n if k == 1:\n return arr[start]\n return 0\n ans = 0\n total = 0\n count = 0\n for i in range(start, end + 1):\n total += arr[i]\n count += 1\n if k - 1 > 0:\n find(dp, i + 1, end, k - 1, arr)\n ans = max(ans, total / count + find(dp, i + 1, end, k - 1, arr))\n ans = max(ans, total / count)\n dp[start, end, k] = ans\n return ans\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n dp = {}\n return find(dp, 0, len(A) - 1, K, A)", "def largestsumofaverages(A: List[int], k: int) -> float:\n n = len(A)\n pre = list(itertools.accumulate([0] + A))\n dp = {}\n\n def dfs(i, k):\n if (i, k) in dp:\n return dp[i, k]\n if k == 1:\n dp[i, k] = (pre[-1] - pre[i]) / (n - i)\n return dp[i, k]\n ans = -float('inf')\n cur = 0\n for j in range(i, n - k + 1):\n ans = max(ans, (pre[j + 1] - pre[i]) / (j - i + 1) + dfs(j + 1, k - 1))\n dp[i, k] = ans\n return ans\n return dfs(0, k)", "def largestsumofaverages(A: List[int], K: int) -> float:\n\n def dp(n, k):\n if n < k:\n return 0\n if k == 1:\n return sum(A[:n]) / n\n (cur, ans) = (0, 0)\n for i in range(n - 1, 0, -1):\n cur += A[i]\n ans = max(ans, dp(i, k - 1) + cur / (n - i))\n return ans\n return dp(len(A), K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n dp = {}\n\n def f(i, k):\n if (i, k) not in dp:\n if k == 1:\n dp[i, k] = sum(A[i:]) / (n - i)\n else:\n dp[i, k] = max([sum(A[i:j]) / (j - i) + f(j, k - 1) for j in range(i + 1, n - k + 2)])\n return dp[i, k]\n return f(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n dp = [0] * (n + 1)\n sums = [0] * (n + 1)\n for i in range(1, n + 1):\n sums[i] = sums[i - 1] + A[i - 1]\n dp[i] = sums[i] / i\n for k in range(2, K + 1):\n tmp = [0] * (n + 1)\n for i in range(k, n + 1):\n for j in range(k - 1, i):\n tmp[i] = max(tmp[i], dp[j] + (sums[i] - sums[j]) / (i - j))\n dp = list(tmp)\n return dp[n]", "def largestsumofaverages(A: List[int], K: int) -> float:\n if K == 1:\n return sum(A) / len(A)\n memo = [[0] * len(A) for _ in range(K)]\n cumsum = [0] * len(A)\n for i in range(len(A)):\n cumsum[i] = cumsum[i - 1] + A[i]\n memo[0][i] = cumsum[i] / (i + 1)\n for i in range(1, K):\n for j in range(i, len(A)):\n tmp = 0\n for k in range(i - 1, j):\n tmp = max(tmp, memo[i - 1][k] + (cumsum[j] - cumsum[k]) / (j - k))\n memo[i][j] = tmp\n return memo[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n dp = [[0.0 for j in range(K + 1)] for i in range(len(A))]\n sums = [0] * len(A)\n sums[0] = A[0]\n for i in range(1, len(A)):\n sums[i] = sums[i - 1] + A[i]\n for k in range(1, K + 1):\n for i in range(len(A)):\n if k == 1:\n dp[i][k] = sums[i] / (i + 1)\n elif k > i + 1:\n continue\n else:\n for j in range(k - 1, i + 1):\n avg1 = dp[j - 1][k - 1]\n avg2 = (sums[i] - sums[j - 1]) / (i - j + 1)\n if dp[i][k] < avg1 + avg2:\n dp[i][k] = avg1 + avg2\n return dp[-1][K]", "from functools import lru_cache\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n\n def rec(j, K):\n nonlocal A\n if K == 1:\n return sum(A[0:j + 1]) / (j + 1)\n res = 0\n runningsum = 0\n for i in range(j, K - 2, -1):\n runningsum += A[i]\n res = max(res, runningsum / (j - i + 1) + rec(i - 1, K - 1))\n return res\n return rec(len(A) - 1, K)", "import functools\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n\n def dp(start, p):\n if p == 1:\n return sum(A[start:]) / (len(A) - start)\n if start == len(A):\n return 0\n curr_sum = A[start]\n ret = 0\n for i in range(start + 1, len(A)):\n avg = curr_sum / (i - start)\n ret = max(ret, avg + dp(i, p - 1))\n curr_sum += A[i]\n return ret\n return dp(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n N = len(A)\n P = [0]\n for a in A:\n P.append(P[-1] + a)\n dp = [0] * (N + 1)\n for i in range(K):\n dp2 = [0] * (N + 1)\n for j in range(i, N + 1):\n if i == 0 and j != 0:\n dp2[j] = P[j] / j\n continue\n for k in range(i - 1, j):\n dp2[j] = max(dp2[j], dp[k] + (P[j] - P[k]) / (j - k))\n dp = dp2\n return dp[-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n num_count = len(A)\n previous_best = [0] * num_count\n current_best = [0] * num_count\n previous_best[0] = A[0]\n for index in range(1, num_count):\n A[index] += A[index - 1]\n previous_best[index] = A[index] / (index + 1)\n for partition_count in range(1, K):\n for end_index in range(partition_count, num_count - K + partition_count + 1):\n current_best[end_index] = max(((A[end_index] - A[start_index]) / (end_index - start_index) + previous_best[start_index] for start_index in range(partition_count - 1, end_index)))\n (current_best, previous_best) = (previous_best, current_best)\n return previous_best[-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n memoDict = {}\n\n def recurse(i, k):\n n = len(A)\n max_win = n - i - (k - 1)\n if (i, k) in memoDict:\n return memoDict[i, k]\n if k == 0:\n return sum(A[i:]) / (n - i)\n else:\n max_sum = 0\n for ind in range(1, max_win):\n lul = recurse(i + ind, k - 1) + sum(A[i:i + ind]) / ind\n max_sum = max(max_sum, lul)\n memoDict[i, k] = max_sum\n return max_sum\n flips = recurse(0, K - 1)\n return flips", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n from functools import lru_cache\n\n def dp(i, j):\n if i == n:\n return float('-inf')\n if j == 1:\n return sum(A[i:]) / (n - i)\n ans = float('-inf')\n cur_sum = 0\n for l in range(i, n):\n cur_sum += A[l]\n ans = max(ans, cur_sum / (l - i + 1) + dp(l + 1, j - 1))\n return ans\n return dp(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n prefix_sum = [A[0]]\n for a in A[1:]:\n prefix_sum.append(prefix_sum[-1] + a)\n dp = [[0 for _ in range(len(A))] for _ in range(K)]\n for i in range(len(A)):\n dp[0][i] = prefix_sum[i] / (i + 1)\n for k in range(1, K):\n for i in range(k, len(A)):\n for j in range(k - 1, i):\n dp[k][i] = max(dp[k][i], dp[k - 1][j] + (prefix_sum[i] - prefix_sum[j]) / (i - j))\n return dp[K - 1][len(A) - 1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n dp = [[0] * K for _ in range(n)]\n dp[0][0] = A[0]\n for i in range(1, n):\n dp[i][0] = (dp[i - 1][0] * i + A[i]) / (i + 1)\n for k in range(1, K):\n for i in range(k, n):\n curr_sum = 0\n for j in reversed(range(k, i + 1)):\n curr_sum += A[j]\n dp[i][k] = max(dp[i][k], dp[j - 1][k - 1] + curr_sum / (i + 1 - j))\n return dp[n - 1][K - 1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n if not A:\n return 0\n n = len(A)\n sums = [0] * (n + 1)\n dp = [[float('-inf')] * (n + 1) for _ in range(K + 1)]\n for i in range(1, n + 1):\n sums[i] = sums[i - 1] + A[i - 1]\n dp[1][i] = sums[i] / i\n for k in range(2, K + 1):\n for i in range(k, n + 1):\n for j in range(k - 1, i):\n ave_i_j = (sums[i] - sums[j]) / (i - j)\n dp[k][i] = max(dp[k][i], dp[k - 1][j] + ave_i_j)\n return dp[K][n]", "def largestsumofaverages(A, K):\n N = len(A)\n S = [0] * (1 + N)\n for i in range(1, N + 1):\n S[i] = S[i - 1] + A[i - 1]\n B = []\n for i in range(1 + N):\n B.append([0] * (1 + K))\n for m in range(1, N + 1):\n for w in range(1, K + 1):\n if w == 1:\n B[m][w] = S[m] / m\n continue\n if m < w:\n break\n B[m][w] = -1000000\n for e in range(1, m - w + 2):\n B[m][w] = max(B[m][w], B[m - e][w - 1] + (S[m] - S[m - e]) / e)\n return B[N][K]", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n dp = [[0] * (K + 1) for _ in range(n)]\n s = 0\n for i in range(n):\n s += A[i]\n dp[i][1] = s * 1.0 / (i + 1)\n for k in range(2, K + 1):\n for i in range(k - 1, n):\n s = 0\n for m in range(i, k - 2, -1):\n s += A[m]\n dp[i][k] = max(dp[i][k], dp[m - 1][k - 1] + s * 1.0 / (i - m + 1))\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n cumsum = [A[0]]\n for i in range(1, len(A)):\n cumsum.append(cumsum[-1] + A[i])\n cumsum.append(0)\n\n def rec(i, K):\n if K == 1:\n return (cumsum[len(A) - 1] - cumsum[i - 1]) / (len(A) - i)\n return max(((cumsum[j] - cumsum[i - 1]) / (j - i + 1) + rec(j + 1, K - 1) for j in range(i, len(A) - K + 1)))\n return rec(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n A = [0] + A\n dp = [[0] * (K + 1) for _ in range(n + 1)]\n for i in range(1, n + 1):\n dp[i][0] = -float('inf')\n for i in range(1, n + 1):\n for k in range(1, min(i + 1, K + 1)):\n sum_s = 0\n for j in range(i, k - 1, -1):\n sum_s += A[j]\n dp[i][k] = max(dp[i][k], dp[j - 1][k - 1] + sum_s / (i - j + 1))\n res = 0\n for i in range(1, K + 1):\n res = max(res, dp[n][i])\n return res", "def largestsumofaverages(A: List[int], K: int) -> float:\n l_A = len(A)\n memo = {(l_A, 0): 0}\n\n def dfs(idx, rem):\n if rem == 0 or l_A - idx < rem:\n return 0\n if rem == 1:\n return sum(A[idx:]) / (l_A - idx)\n if (idx, rem) in memo:\n return memo[idx, rem]\n sum_so_far = 0\n avg = 0\n best = 0\n for i in range(idx, l_A):\n sum_so_far += A[i]\n avg = sum_so_far / (i - idx + 1)\n best = max(best, avg + dfs(i + 1, rem - 1))\n memo[idx, rem] = best\n return best\n return dfs(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n if not A or len(A) < K:\n return 0\n for i in range(1, len(A)):\n A[i] += A[i - 1]\n cache = {}\n\n def cal(n, k):\n if n <= 0 or k <= 0:\n return 0\n if n < k:\n return 0\n if (n, k) in cache:\n return cache[n, k]\n if k == 1:\n cache[n, 1] = A[n - 1] / n\n return cache[n, 1]\n (res, cur) = (0, 0)\n for i in range(n - 1, 0, -1):\n res = max(res, (A[n - 1] - A[i - 1]) / (n - i) + cal(i, k - 1))\n cache[n, k] = res\n return res\n return cal(len(A), K)", "from functools import lru_cache\n\ndef largestsumofaverages(A, K):\n l = len(A)\n\n def dp(n, k):\n if n < k:\n return 0\n if k == 1:\n return sum(A[:n]) / float(n)\n (cursum, ans) = (0, 0)\n for i in range(n - 1, -1, -1):\n cursum += A[i]\n ans = max(ans, dp(i, k - 1) + cursum / float(n - i))\n return ans\n return dp(l, K)", "import itertools\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n dp = [[0] * len(A) for _ in range(K)]\n cur_sum = 0\n for j in range(len(A)):\n cur_sum += A[j]\n dp[0][j] = float(cur_sum) / (j + 1)\n for i in range(1, K):\n for j in range(len(A)):\n cur_sum = 0\n for k in range(j, i - 1, -1):\n cur_sum += A[k]\n dp[i][j] = max(dp[i][j], dp[i - 1][k - 1] + float(cur_sum) / (j - k + 1))\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n prefix = [0]\n for a in A:\n prefix.append(prefix[-1] + a)\n\n def soa(i, k):\n if len(prefix) - 1 - i <= k:\n return prefix[-1] - prefix[i]\n elif k == 1:\n return (prefix[-1] - prefix[i]) / (len(prefix) - 1 - i)\n best = 0\n for j in range(i + 1, len(prefix) - (k - 1)):\n best = max(best, (prefix[j] - prefix[i]) / (j - i) + soa(j, k - 1))\n return best\n return soa(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n presum = [0] + list(itertools.accumulate(A))\n\n def mean(i, j):\n return (presum[j + 1] - presum[i]) / (j - i + 1)\n n = len(A)\n old = [[mean(i, j) if i <= j else 0 for j in range(n)] for i in range(n)]\n new = [[0 for j in range(n)] for i in range(n)]\n mval = mean(0, n - 1)\n for k in range(2, K + 1):\n for i in range(n - k + 1):\n max_val = -float('inf')\n for mid in range(i, n - k + 1):\n max_val = max(max_val, mean(i, mid) + old[mid + 1][n - 1])\n new[i][n - 1] = max_val\n (old, new) = (new, old)\n mval = max(mval, old[0][-1])\n return mval", "def largestsumofaverages(A: List[int], K: int) -> float:\n prefix = [A[0]]\n for i in range(1, len(A)):\n prefix.append(prefix[i - 1] + A[i])\n dp = [[prefix[i] / (i + 1) if k == 1 else 0 for k in range(K + 1)] for i in range(len(A))]\n for i in range(1, len(A)):\n for k in range(2, min(i + 2, K + 1)):\n val = float('-inf')\n _sum = 0\n for j in range(i, 0, -1):\n _sum += A[j]\n val = max(dp[j - 1][k - 1] + _sum / (i - j + 1), val)\n dp[i][k] = val\n return dp[len(A) - 1][K]", "def largestsumofaverages(A: List[int], K: int) -> float:\n dp = [[0 for k in range(K + 1)] for i in range(len(A))]\n dp[0][1] = A[0]\n for (count, i) in enumerate(range(1, len(A))):\n dp[i][1] = (dp[i - 1][1] * (count + 1) + A[i]) / (count + 2)\n for i in range(1, len(A)):\n for k in range(2, min(i + 2, K + 1)):\n val = float('-inf')\n _sum = 0\n for j in range(i, 0, -1):\n _sum += A[j]\n val = max(dp[j - 1][k - 1] + _sum / (i - j + 1), val)\n dp[i][k] = val\n return dp[len(A) - 1][K]", "def largestsumofaverages(A: List[int], K: int) -> float:\n dp = [[0 for y in range(len(A))] for x in range(K)]\n add = 0\n pref = [0 for i in range(len(A))]\n for x in range(len(A)):\n add += A[x]\n pref[x] = add\n for x in range(len(A)):\n dp[0][x] = pref[x] / (x + 1)\n for y in range(1, K):\n dp[y][0] = A[0]\n for x in range(1, K):\n for y in range(1, len(A)):\n val1 = pref[y] / (y + 1)\n maxi = val1\n for z in range(y):\n val = dp[x - 1][z] + (pref[y] - pref[z]) / (y - z)\n maxi = max(maxi, val)\n dp[x][y] = maxi\n return dp[-1][-1]", "def largestsumofaverages(A, K):\n m = len(A)\n dp = [[None] * (K + 1) for _ in range(m)]\n for k in range(1, K + 1):\n for j in range(k - 1, m):\n if k == 1:\n dp[j][k] = sum(A[:j + 1]) / (j + 1)\n else:\n dp[j][k] = max((dp[i][k - 1] + sum(A[i + 1:j + 1]) / (j - i) for i in range(k - 2, j)))\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n suffix_sums = [0] * (len(A) + 1)\n for i in range(len(A) - 1, -1, -1):\n suffix_sums[i] = A[i] + suffix_sums[i + 1]\n memo = {}\n\n def largest_starting_at(i, new_k):\n if i == len(A):\n return 0\n if new_k == 1:\n return suffix_sums[i] / (len(A) - i)\n if (i, new_k) in memo:\n return memo[i, new_k]\n best = 0\n for size in range(1, len(A) - i):\n best = max(best, (suffix_sums[i] - suffix_sums[i + size]) / size + largest_starting_at(i + size, new_k - 1))\n memo[i, new_k] = best\n return memo[i, new_k]\n return largest_starting_at(0, K)", "def largestsumofaverages(A, K: int) -> float:\n\n def avg(array):\n return sum(array) / len(array)\n dp = [[0 for _ in range(K + 1)] for _ in range(len(A))]\n means = [[0 for _ in range(len(A))] for _ in range(len(A))]\n for i in range(len(A)):\n for j in range(i, len(A)):\n means[i][j] = avg(A[i:j + 1])\n for i in range(len(A)):\n dp[i][1] = means[0][i]\n for i in range(1, len(A)):\n for j in range(2, min(K + 1, i + 1 + 1)):\n for k in range(max(i - 1, j - 1 - 1), -1, -1):\n temp_last_group = means[k + 1][i]\n temp_sum_prev = dp[k][j - 1]\n dp[i][j] = max(dp[i][j], temp_last_group + temp_sum_prev)\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n dp = [[-math.inf] * K for _ in range(n)]\n (sv, sc) = (0, {-1: 0})\n for (i, v) in enumerate(A):\n sv += v\n sc[i] = sv\n dp[0][0] = A[0]\n for r in range(n):\n for i in range(0, r):\n for k in range(min(K, r + 1)):\n if k == 0:\n dp[r][k] = (sc[r] - sc[-1]) / (r + 1)\n else:\n candidate = dp[i][k - 1] + (sc[r] - sc[i]) / (r - i)\n dp[r][k] = max(dp[r][k], candidate)\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n prefixSum = [0]\n for x in A:\n prefixSum.append(prefixSum[-1] + x)\n\n def avg(i, j):\n return (prefixSum[j] - prefixSum[i]) / (j - i)\n n = len(A)\n dp = [avg(i, n) for i in range(n)]\n for k in range(K - 1):\n for i in range(n):\n for j in range(i + 1, n):\n dp[i] = max(dp[i], avg(i, j) + dp[j])\n return dp[0]", "def largestsumofaverages(A, K):\n p = [0]\n for x in A:\n p.append(x + p[-1])\n\n def avg(i, j):\n return (p[j] - p[i]) / (j - i)\n N = len(A)\n dp = [avg(i, N) for i in range(N)]\n for k in range(K - 1):\n for i in range(N):\n for j in range(i + 1, N):\n dp[i] = max(dp[i], avg(i, j) + dp[j])\n return dp[0]", "def largestsumofaverages(A: List[int], K: int) -> float:\n N = len(A)\n\n def dfs(index, remain):\n if remain <= 0:\n return sum(A[index:]) / (N - index)\n if index >= N:\n return 0\n ans = 0\n for i in range(index + 1, N):\n ans = max(ans, sum(A[index:i]) / (i - index) + dfs(i, remain - 1))\n return ans\n res = dfs(0, K - 1)\n return res", "def largestsumofaverages(A: List[int], K: int) -> float:\n if K == 1:\n return sum(A) / len(A)\n biggest = [[[None for temp in range(K + 1)] for col in range(len(A))] for row in range(len(A))]\n for start in range(len(A)):\n for end in range(start, len(A), 1):\n biggest[start][end][1] = sum(A[start:end + 1]) / len(A[start:end + 1])\n for curK in range(2, K + 1):\n startEnd = len(A) - curK + 1\n if curK == K:\n startEnd = 1\n for start in range(0, startEnd, 1):\n tempNo = 0\n for middle in range(start, len(A) - curK + 1, 1):\n theNo = biggest[start][middle][1] + biggest[middle + 1][len(A) - 1][curK - 1]\n if theNo > tempNo:\n tempNo = theNo\n biggest[start][len(A) - 1][curK] = tempNo\n return biggest[0][len(A) - 1][K]", "def largestsumofaverages(A: List[int], K: int) -> float:\n if len(A) <= K:\n return sum(A)\n A1 = []\n s = 0\n for i in A:\n s += i\n A1.append(s)\n n = len(A)\n last = [A1[i] / (i + 1) for i in range(n)]\n for k in range(1, K):\n cur = [A[0]]\n for i in range(1, n):\n stage_max = 0\n for (j1, j) in enumerate(last[:i]):\n stage_max = max(stage_max, j + (A1[i] - A1[j1]) / (i - j1))\n cur.append(stage_max)\n last = cur\n return last[-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n L = len(A)\n reduced_dp = [0 for _ in range(L)]\n prefix_sum = [0 for _ in range(L + 1)]\n for i in range(1, L + 1):\n prefix_sum[i] = prefix_sum[i - 1] + A[i - 1]\n reduced_dp[i - 1] = prefix_sum[i] / i\n for k in range(2, K + 1):\n for i in reversed(range(1, L)):\n if k <= i + 1:\n for j in range(-1, i):\n ave = (prefix_sum[i + 1] - prefix_sum[j + 1]) / (i - j)\n if j == -1:\n tmp = 0\n else:\n tmp = reduced_dp[j]\n if ave + tmp > reduced_dp[i]:\n reduced_dp[i] = ave + tmp\n return reduced_dp[-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n prefix = [0] + A.copy()\n for i in range(1, len(prefix)):\n prefix[i] += prefix[i - 1]\n\n def query(i, j):\n return prefix[j + 1] - prefix[i]\n\n def get_average(i, j):\n return query(i, j) / (j - i + 1)\n N = len(A)\n cache = {}\n\n def dfs(i, k):\n if k < 0:\n return -float('inf')\n if (i, k) in cache:\n return cache[i, k]\n if i == N:\n if k == 0:\n return 0\n else:\n return -float('inf')\n res = -float('inf')\n for j in range(i, N):\n take = dfs(j + 1, k - 1) + get_average(i, j)\n res = max(res, take)\n cache[i, k] = res\n return res\n return dfs(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n if not A:\n return 0\n dp = {}\n averages = [[None] * len(A) for _ in range(len(A))]\n for i in range(len(A)):\n averages[i][i] = A[i]\n for j in range(i + 1, len(A)):\n averages[i][j] = (averages[i][j - 1] * (j - i) + A[j]) / (j - i + 1)\n\n def recurse(A, K, start):\n if start >= len(A):\n return 0\n if K == 1:\n return averages[start][len(A) - 1]\n if (K, start) in dp:\n return dp[K, start]\n dp[K, start] = -math.inf\n for i in range(start, len(A)):\n dp[K, start] = max(dp[K, start], averages[start][i] + recurse(A, K - 1, i + 1))\n return dp[K, start]\n return recurse(A, K, 0)", "from itertools import combinations\nfrom functools import lru_cache\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n\n def mean(A):\n return sum(A) / len(A)\n\n def recurse(start, end, k=1):\n if k == K:\n return mean(A[start:end])\n if len(A) == 1:\n return A[0]\n maxval = 0\n for i in range(start + 1, end):\n maxval = max(maxval, mean(A[start:i]) + recurse(i, end, k + 1))\n return maxval\n N = len(A)\n return recurse(0, N)"], "starter_code": "def largestsumofaverages(A: List[int], K: int) -> float:\n", "input_output": {"fn_name": "largestSumOfAverages", "inputs": [[[9, 1, 2, 3, 9], 3]], "outputs": [20.0]}, "difficulty": "MEDIUM", "raw_tags": ["Prefix Sum", "Array", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures", "Range queries"], "skill_types": ["Dynamic programming", "Data structures", "Range queries"], "url": "https://leetcode.com/problems/largest-sum-of-averages/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "largestsumofaverages", "task_id": "TACO_lite/287", "example": [[[[9, 1, 2, 3, 9], 3]], ["20"]]} +{"requirement": "Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence.\nNote: No two strings are the second most repeated, there will be always a single string.\nExample 1:\nInput:\nN = 6\narr[] = {aaa, bbb, ccc, bbb, aaa, aaa}\nOutput: bbb\nExplanation: \"bbb\" is the second most \noccurring string with frequency 2.\nExample 2:\nInput: \nN = 6\narr[] = {geek, for, geek, for, geek, aaa}\nOutput: for\nExplanation: \"for\" is the second most\noccurring string with frequency 2.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function secFrequent() which takes the string array arr[] and its size N as inputs and returns the second most frequent string in the array.\nExpected Time Complexity: O(N*max(|S_{i}|).\nExpected Auxiliary Space: O(N*max(|S_{i}|).\nConstraints:\n1<=N<=10^{3}", "solutions": ["def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n a = sorted(d.items(), key=lambda x: x[1])\n return a[-2][0]", "def secfrequent(arr, n):\n dic = {}\n for ele in arr:\n dic[ele] = dic.get(ele, 0) + 1\n max_freq = max(dic.values())\n a = [x for x in dic.values() if x != max_freq]\n a.sort()\n for x in dic:\n if dic[x] == a[-1]:\n return x\n return '-1'", "def secfrequent(arr, n):\n s = {}\n for i in arr:\n if i not in s:\n s[i] = 1\n else:\n s[i] = s[i] + 1\n lar = -1\n pos = -1\n for i in s:\n if lar < s[i]:\n lar = s[i]\n pos = i\n slar = -1\n spos = -1\n for i in s:\n if s[i] > slar and s[i] < lar:\n slar = s[i]\n spos = i\n if spos != -1:\n return spos\n else:\n return ''", "def secfrequent(arr, n):\n d = {}\n for i in range(len(arr)):\n if arr[i] in d:\n d[arr[i]] += 1\n else:\n d[arr[i]] = 1\n d = sorted(d.items(), key=lambda x: x[1])\n m = d[-2]\n return m[0]", "from collections import Counter\n\ndef secfrequent(arr, n):\n a = []\n h = {}\n for i in arr:\n if i in h:\n h[i] += 1\n else:\n h[i] = 1\n for i in h:\n a.append(h[i])\n a.sort()\n ans = a[-2]\n for i in h:\n if h[i] == ans:\n return i", "def secfrequent(arr, n):\n freq = {}\n for string in arr:\n freq[string] = freq.get(string, 0) + 1\n most_common = ('', 0)\n second_most_common = ('', 0)\n for (string, frequency) in freq.items():\n if frequency > most_common[1]:\n second_most_common = most_common\n most_common = (string, frequency)\n elif frequency > second_most_common[1] and string != most_common[0]:\n second_most_common = (string, frequency)\n return second_most_common[0]", "def secfrequent(arr, n):\n a = []\n d = {}\n for i in arr:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for i in d:\n a.append(d[i])\n a.sort()\n res = a[-2]\n for i in d:\n if d[i] == res:\n return i", "def secfrequent(arr, n):\n dict1 = {}\n for i in arr:\n if i in dict1:\n dict1[i] += 1\n else:\n dict1[i] = 1\n a = sorted(dict1.values())\n b = max(a)\n a.remove(b)\n c = max(a)\n for i in dict1:\n if dict1[i] == c:\n return i", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n l = []\n for i in d.values():\n l.append(i)\n l.sort()\n a = l[-2]\n for (k, v) in d.items():\n if v == a:\n return k", "from collections import Counter\nimport operator\n\ndef secfrequent(arr, n):\n dic = {}\n for i in arr:\n if i in dic:\n dic[i] += 1\n else:\n dic[i] = 1\n lst = []\n for (i, j) in dic.items():\n lst.append([i, j])\n lst.sort(key=operator.itemgetter(1, 0), reverse=True)\n return lst[1][0]", "from collections import Counter\n\ndef secfrequent(arr, n):\n d = Counter(arr)\n first = float('-inf')\n second = float('-inf')\n for val in d.values():\n if val > first:\n second = first\n first = val\n elif val > second and first != val:\n second = val\n if second == float('-inf'):\n return ''\n for (k, v) in d.items():\n if v == second:\n return k", "def secfrequent(arr, n):\n a = []\n d = dict()\n for ele in arr:\n d[ele] = 0\n for ele in arr:\n d[ele] = d[ele] + 1\n for ele in d:\n a.append(d[ele])\n a.sort()\n b = a[-2]\n for i in d:\n if d[i] == b:\n return i", "def secfrequent(arr, n):\n d = {}\n for word in arr:\n d.setdefault(word, 0)\n d[word] += 1\n f_max = float('-inf')\n s_max = float('-inf')\n for val in d:\n if d[val] > f_max:\n s_max = f_max\n f_max = d[val]\n if d[val] > s_max and d[val] != f_max:\n s_max = d[val]\n for i in d:\n if d[i] == s_max:\n return i\n return ''", "def secfrequent(arr, n):\n d = {}\n for word in arr:\n d.setdefault(word, 0)\n d[word] += 1\n val = list(d.values())\n val.sort()\n mx = val[-2]\n for i in d:\n if d[i] == mx:\n return i", "from collections import Counter\n\ndef secfrequent(arr, n):\n freq = Counter(arr)\n items = list(freq.items())\n items.sort(key=lambda x: x[1])\n return items[-2][0]", "from collections import Counter\n\ndef compare(item):\n return item[1]\n\ndef secfrequent(arr, n):\n freq = Counter(arr)\n items = list(freq.items())\n items.sort(key=compare)\n return items[-2][0]", "from collections import Counter\n\ndef secfrequent(arr, n):\n charFreq = Counter(arr)\n items = list(charFreq.items())\n items.sort(key=lambda x: x[1], reverse=True)\n return items[1][0]", "def secfrequent(arr, n):\n freq = {}\n for i in range(n):\n freq[arr[i]] = freq.get(arr[i], 0) + 1\n max_freq = -1\n sec_max_freq = -1\n max_freq_str = ''\n sec_max_freq_str = ''\n for key in freq:\n if freq[key] > max_freq:\n sec_max_freq = max_freq\n sec_max_freq_str = max_freq_str\n max_freq = freq[key]\n max_freq_str = key\n elif freq[key] > sec_max_freq and freq[key] != max_freq:\n sec_max_freq = freq[key]\n sec_max_freq_str = key\n return sec_max_freq_str if freq else None", "def secfrequent(arr, n):\n dict1 = {}\n for i in arr:\n if i in dict1:\n dict1[i] += 1\n else:\n dict1[i] = 1\n m = sorted(dict1.values())[-2]\n for i in arr:\n if dict1[i] == m:\n return i", "def secfrequent(arr, n):\n dictt = {}\n for i in arr:\n if i in dictt:\n dictt[i] += 1\n else:\n dictt[i] = 1\n k = sorted(dictt.values())[-2]\n for i in dictt:\n if dictt[i] == k:\n return i", "from collections import Counter\n\ndef secfrequent(arr, n):\n dict1 = {}\n for i in arr:\n if i in dict1:\n dict1[i] += 1\n else:\n dict1[i] = 1\n a = sorted(dict1.values())\n b = max(a)\n a.remove(b)\n c = max(a)\n for i in dict1:\n if dict1[i] == c:\n return i", "import operator\n\ndef secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n l = [[i, d[i]] for i in d]\n l = sorted(l, reverse=True, key=operator.itemgetter(1))\n return l[1][0]", "def secfrequent(arr, n):\n res = []\n freq = {}\n for i in arr:\n freq[i] = freq.get(i, 0) + 1\n for i in freq:\n res.append(freq[i])\n res.sort()\n ans = res[-2]\n for i in freq:\n if freq[i] == ans:\n return i", "def secfrequent(arr, n):\n a = []\n d = {}\n for i in arr:\n d[i] = d.get(i, 0) + 1\n for i in d:\n a.append(d[i])\n a.sort()\n ans = a[-2]\n for i in d:\n if d[i] == ans:\n return i", "def secfrequent(arr, n):\n lst = []\n dic = {}\n for i in arr:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n for i in dic:\n lst.append(dic[i])\n lst.sort()\n for i in dic:\n if dic[i] == lst[-2]:\n return i", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n d1 = sorted(d.values())\n z = d1[-2]\n for i in d:\n if d[i] == z:\n return i", "def secfrequent(arr, n):\n dir1 = {}\n ans = []\n for i in arr:\n dir1[i] = dir1.get(i, 0) + 1\n ans = list(dir1.values())\n ans.sort()\n ans2 = ans[-2]\n for i in dir1:\n if dir1[i] == ans2:\n return i", "def secfrequent(arr, n):\n d = {}\n f = 0\n for i in arr:\n d.update({i: arr.count(i)})\n max = -1\n for i in d.values():\n if i > max:\n max = i\n max1 = -1\n for i in d.values():\n if i > max1 and i < max:\n max1 = i\n for i in d.keys():\n if d[i] == max1:\n f = 1\n return i\n if f == 0:\n return ''", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n d[i] = d.get(i, 0) + 1\n l = []\n for i in d:\n l.append((d[i], i))\n l.sort()\n return l[-2][1]", "def secfrequent(arr, n):\n l = list(set(arr))\n l2 = []\n l3 = []\n for i in l:\n cnt = arr.count(i)\n l2.append(cnt)\n s = sorted(l2)\n res = s[-2]\n for i in l:\n cnt = arr.count(i)\n if cnt == res:\n l3.append(i)\n return l3[0]", "def secfrequent(arr, n):\n dic = {}\n for i in arr:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n sorted_dic = sorted(dic.items(), key=lambda item: item[1])\n return sorted_dic[-2][0]", "def secfrequent(arr, n):\n dct = {}\n for i in range(n):\n if arr[i] in dct:\n dct[arr[i]] += 1\n else:\n dct[arr[i]] = 1\n k = 0\n s = ''\n for i in dct:\n if dct[i] > k:\n s = i\n k = dct[i]\n dct.pop(s)\n k = 0\n s = ''\n for i in dct:\n if dct[i] > k:\n s = i\n k = dct[i]\n return s", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n m = 0\n for i in d:\n if d[i] > m:\n m = d[i]\n m1 = 0\n mi = ''\n for i in d:\n if d[i] > m1 and d[i] != m:\n m1 = d[i]\n mi = i\n return mi", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n (fs, ss) = ('', '')\n (m, ms) = (0, 0)\n for i in d:\n if d[i] >= m:\n (ms, ss) = (m, fs)\n (m, fs) = (d[i], i)\n elif d[i] > ms:\n (ms, ss) = (d[i], i)\n return ss", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n res = []\n for i in d:\n res.append([i, d[i]])\n if len(res) == 1:\n return ''\n res.sort(key=lambda x: x[1])\n return res[len(res) - 2][0]", "from collections import Counter\n\ndef secfrequent(arr, n):\n d = sorted(Counter(arr).items(), key=lambda x: x[1], reverse=True)\n return d[1][0]", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n l = -1\n s = -1\n for i in arr:\n if d[i] > l:\n s = l\n l = d[i]\n elif d[i] > s and d[i] < l:\n s = d[i]\n if s == -1:\n return ''\n else:\n for i in arr:\n if d[i] == s:\n return i", "def secfrequent(arr, n):\n freq = {}\n for word in arr:\n if word in freq:\n freq[word] += 1\n else:\n freq[word] = 1\n max1 = 0\n max2 = 0\n res1 = ''\n res2 = ''\n for (val, key) in freq.items():\n if key > max1:\n max2 = max1\n max1 = key\n res2 = res1\n res1 = val\n elif key > max2:\n max2 = key\n res2 = val\n return res2", "def secfrequent(arr, n):\n if len(arr) == 0:\n return False\n my_dict = {}\n for i in arr:\n if i in my_dict:\n my_dict[i] += 1\n else:\n my_dict[i] = 1\n sorted_dict = sorted(my_dict.items(), key=lambda x: x[1], reverse=True)\n return sorted_dict[1][0]", "def secfrequent(arr, n):\n dic = {}\n for i in arr:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n x = []\n for i in dic.keys():\n x.append(dic[i])\n x.sort()\n x.reverse()\n for i in dic.keys():\n if dic[i] == x[1]:\n return i", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n d[i] = 0\n for i in arr:\n d[i] += 1\n mx = 0\n val = ''\n for i in arr:\n if d[i] > mx:\n mx = d[i]\n mx2 = 0\n for i in arr:\n if mx > d[i] > mx2:\n mx2 = d[i]\n val = i\n return val", "from collections import Counter\n\ndef secfrequent(arr, n):\n all_strings = dict(Counter(arr))\n store = []\n for i in sorted(all_strings, key=all_strings.get):\n if i not in store:\n store.append(i)\n return store[-2]", "from collections import Counter\n\ndef secfrequent(arr, n):\n ans = Counter(arr)\n f = True\n fm = 0\n ele1 = ''\n if len(ans) == 1:\n return ''\n for (i, j) in ans.items():\n if f:\n fm = j\n ele1 = i\n f = False\n if j > fm:\n fm = j\n ele1 = i\n ans.pop(ele1)\n v = fm\n f = True\n for (i, j) in ans.items():\n if f:\n fm = j\n ele1 = i\n f = False\n if j > fm:\n fm = j\n ele1 = i\n if v == fm:\n return ''\n return ele1", "def secfrequent(arr, n):\n hmap = {}\n for i in range(n):\n if arr[i] in hmap:\n hmap[arr[i]] += 1\n else:\n hmap[arr[i]] = 1\n sorted_hmap = sorted(hmap.items(), key=lambda x: x[1], reverse=True)\n return sorted_hmap[1][0]", "def secfrequent(arr, n):\n freq = {}\n for i in arr:\n if i not in freq:\n freq[i] = 0\n freq[i] += 1\n if len(freq) == 1:\n return ''\n lis = list(freq.items())\n lis.sort(key=lambda x: x[1], reverse=True)\n return lis[1][0]", "def secfrequent(arr, n):\n dic = {}\n maxx = 0\n for each in arr:\n if each not in dic:\n dic[each] = 1\n else:\n dic[each] += 1\n maxx = max(maxx, dic[each])\n (wrd, freq) = ('', 0)\n for (i, j) in dic.items():\n if j > freq and j < maxx:\n (wrd, freq) = (i, j)\n return wrd", "from collections import Counter\n\ndef secfrequent(arr, n):\n c = Counter(arr)\n l = [i for i in c.values()]\n l.sort(reverse=True)\n x = l[1]\n for i in c:\n if c[i] == x:\n return i", "def secfrequent(arr, n):\n d = {}\n l = []\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n s = sorted(d.values())\n for i in d:\n if d[i] == s[-2]:\n return i", "from collections import Counter\n\ndef secfrequent(a, n):\n d = {}\n for i in range(len(arr)):\n if arr[i] in d:\n d[arr[i]] += 1\n else:\n d[arr[i]] = 1\n d = sorted(d.items(), key=lambda x: x[1], reverse=True)\n m = d[1]\n return m[0]", "def secfrequent(arr, n):\n dict = {}\n for i in arr:\n if i in dict:\n dict[i] += 1\n else:\n dict[i] = 1\n lst = []\n for i in dict:\n lst.append(dict[i])\n m = max(lst)\n lst.remove(m)\n m = max(lst)\n for i in dict:\n if dict[i] == m:\n return i", "from collections import Counter\n\ndef secfrequent(arr, n):\n c = Counter(arr)\n c = sorted(c.items(), reverse=True, key=lambda kv: kv[1])\n return c[1][0]", "from collections import Counter\n\ndef secfrequent(arr, n):\n c = Counter(arr)\n m = sorted(c.values())[-2]\n for (k, v) in c.items():\n if v == m:\n return k", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n l = []\n for (k, v) in d.items():\n l.append(v)\n l = sorted(l)\n for (k, v) in d.items():\n if v == l[-2]:\n return k", "def secfrequent(arr, n):\n d = {}\n for i in range(len(arr)):\n if arr[i] not in d:\n d[arr[i]] = 1\n else:\n d[arr[i]] += 1\n if len(d) >= 2:\n first = 0\n second = 0\n for i in d:\n if d[i] > first:\n second = first\n first = d[i]\n elif d[i] > second and d[i] != first:\n second = d[i]\n for word in d:\n if d[word] == second:\n return word\n else:\n return ''", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n val = sorted(d.values(), reverse=True)\n second = val[1]\n for (key, value) in d.items():\n if value == second:\n return key", "from collections import Counter\n\ndef secfrequent(arr, n):\n count = Counter(arr)\n val = sorted(count.values(), reverse=True)\n max_val = val[1]\n for (i, j) in count.items():\n if j == max_val:\n return i", "from collections import Counter\n\ndef secfrequent(arr, n):\n d = Counter(arr)\n val = sorted(d.values(), reverse=True)\n second = val[1]\n for (k, v) in d.items():\n if v == second:\n return k", "from collections import Counter\n\ndef secfrequent(arr, n):\n d = dict()\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n a = []\n for (i, j) in d.items():\n a.append(j)\n if len(a) <= 1:\n return ''\n else:\n m = max(a)\n c = 0\n for i in range(len(a)):\n if a[i] < m:\n c = max(c, a[i])\n for (i, j) in d.items():\n if j == c:\n return i", "from collections import Counter\n\ndef secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n mx = max(list(d.values()))\n d1 = {}\n for (i, j) in d.items():\n if j == mx:\n continue\n else:\n d1[i] = j\n mx1 = max(list(d1.values()))\n for (i, j) in d1.items():\n if j == mx1:\n return i", "from collections import Counter\n\ndef secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n d = sorted(d.items(), key=lambda x: x[1])\n m = d[-2]\n return m[0]", "from collections import defaultdict\n\ndef secfrequent(arr, n):\n d = defaultdict(int)\n for i in arr:\n d[i] += 1\n max1 = -1\n max2 = -1\n for i in d:\n if max1 < d[i]:\n max2 = max1\n max1 = d[i]\n elif max2 < d[i] and d[i] != max1:\n max2 = d[i]\n for i in d:\n if d[i] == max2:\n return i\n return ''", "from collections import Counter\n\ndef secfrequent(arr, n):\n con = Counter(arr)\n res = sorted(con.values(), reverse=True)\n maxi = res[1]\n for (key, val) in con.items():\n if val == maxi:\n return key", "from collections import Counter\n\ndef secfrequent(arr, n):\n c = Counter(arr)\n return c.most_common(2)[1][0]", "from collections import Counter\n\ndef secfrequent(arr, n):\n d = Counter(arr)\n li = d.most_common(2)\n return li[1][0]"], "starter_code": "def secfrequent(arr, n):\n", "input_output": {"inputs": ["N = 6\narr[] = {aaa, bbb, ccc, bbb, aaa, aaa}", "N = 6\narr[] = {geek, for, geek, for, geek, aaa}"], "outputs": ["bbb", "for"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Hash"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/second-most-repeated-string-in-a-sequence0534/1", "Expected Auxiliary Space": "O(N*max(|S_{i}|).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*max(|S_{i}|).", "entry_point": "secfrequent", "task_id": "TACO_lite/119", "example": [[], []]} +{"requirement": "Given an integer n. Print first n elements of Recaman’s sequence.\nIt is basically a function with domain and co-domain as natural numbers and 0. It is recursively defined as below:\nSpecifically, let a(n) denote the (n+1)-th term. (0 being already there).\nThe rule says:\na(0) = 0\na(n) = a(n-1) - n if a(n-1) - n > 0 and is not already present in the sequence\n = a(n-1) + n otherwise. \nExample 1:\nInput: n = 6\nOutput: 0 1 3 6 2 7\nExplaination: Follow the rule and this \nwill be the output.\nExample 2:\nInput: n = 3\nOutput: 0 1 3\nExplaination: If the rule is followed, \nit will produce this output.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function recamanSequence() which takes n as the input parameter and returns the sequence.\nExpected Time Complexity: O(n)\nExpected Auxiliary Space: O(n)\nConstraints:\n1 ≤ n ≤ 100", "solutions": ["def __init__():\n self.res = []\n\ndef recamansequence(n):\n self.recaman(n)\n return self.res\n\ndef recaman(n):\n if n == 1:\n self.res.append(0)\n return 0\n self.recaman(n - 1)\n minus_val = self.res[-1] - (n - 1)\n if minus_val > 0 and minus_val not in self.res:\n self.res.append(minus_val)\n else:\n self.res.append(self.res[-1] + (n - 1))", "def recamansequence(n):\n ans = [0]\n self.helper(n, ans)\n return ans\n\ndef helper(n, ans):\n if n == 0:\n return\n self.helper(n - 1, ans)\n if ans[n - 1] - n > 0 and ans[n - 1] - n not in ans:\n ans.append(ans[n - 1] - n)\n else:\n ans.append(ans[n - 1] + n)", "def recamansequence(n):\n a = []\n if n == 0:\n return [0]\n return self.sol(n - 1, a)\n\ndef sol(n, a):\n if n == 0:\n a.append(n)\n return a\n self.sol(n - 1, a)\n if a[n - 1] - n > 0 and a[n - 1] - n not in a:\n a.append(a[n - 1] - n)\n else:\n a.append(a[n - 1] + n)\n return a", "def findSeq(i, n, seq):\n if i == n:\n return\n curr = seq[i - 1] - i\n if curr not in seq:\n if curr > 0:\n seq.append(curr)\n else:\n curr = seq[i - 1] + i\n seq.append(curr)\n else:\n curr = seq[i - 1] + i\n seq.append(curr)\n self.findSeq(i + 1, n, seq)\n\ndef recamansequence(n):\n seq = [0]\n self.findSeq(1, n, seq)\n return seq", "def recamansequence(n):\n if n == 1:\n return [0]\n s = []\n arr = [0] * n\n arr[0] = 0\n s.append(arr[0])\n for i in range(1, n):\n curr = arr[i - 1] - i\n for j in range(0, i):\n if arr[j] == curr or curr < 0:\n curr = arr[i - 1] + i\n break\n arr[i] = curr\n s.append(arr[i])\n return s", "def recamansequence(n):\n res = [0]\n i = 1\n while i < n:\n x = res[i - 1] - i\n if x > 0 and x not in res:\n res.append(x)\n else:\n res.append(res[i - 1] + i)\n i += 1\n return res", "def recamansequence(n):\n a = [0]\n self.rec(n, a)\n return a\n\ndef rec(n, ans):\n if n == 0:\n return\n self.rec(n - 1, ans)\n if ans[n - 1] - n > 0 and ans[n - 1] - n not in ans:\n ans.append(ans[n - 1] - n)\n else:\n ans.append(ans[n - 1] + n)", "def recur(n, li):\n if n == 0:\n return\n self.recur(n - 1, li)\n if li[n - 1] - n > 0 and li[n - 1] - n not in li:\n li.append(li[n - 1] - n)\n else:\n li.append(li[n - 1] + n)\n\ndef recamansequence(n):\n li = [0]\n self.recur(n, li)\n return li", "def recamansequence(n):\n ans = [0]\n for i in range(1, n):\n if ans[i - 1] - i > 0 and ans[i - 1] - i not in ans:\n ans.append(ans[i - 1] - i)\n else:\n ans.append(ans[i - 1] + i)\n return ans", "sequence = [0]\nsetti = set([0])\n\ndef recamansequence(n):\n while len(sequence) < n:\n i = len(sequence)\n next = sequence[-1] - i\n if next <= 0 or next in setti:\n next += i * 2\n sequence.append(next)\n setti.add(next)\n return sequence[:n]", "def recamansequence(n):\n ans = [0]\n s = set()\n s.add(0)\n for i in range(1, n):\n c = ans[-1] - i\n if c > 0 and c not in s:\n ans.append(c)\n s.add(c)\n else:\n t = ans[-1] + i\n ans.append(t)\n s.add(t)\n return ans", "def recamansequence(n):\n dp = [0] * n\n s = set()\n s.add(0)\n for i in range(1, n):\n val = dp[i - 1] - i\n if val not in s and val > 0:\n dp[i] = val\n else:\n dp[i] = dp[i - 1] + i\n s.add(dp[i])\n return dp", "def recamansequence(n):\n ds = [0 for i in range(n)]\n\n def help(ds, i):\n if i >= n:\n return\n val = ds[i - 1] - i\n if val > 0 and val not in ds:\n ds[i] = val\n else:\n ds[i] = val + 2 * i\n help(ds, i + 1)\n help(ds, 1)\n return ds", "def recamansequence(n):\n ds = []\n\n def helper(n, ds):\n if n == 1:\n ds.append(0)\n ds.append(n)\n return n\n value = helper(n - 1, ds)\n if value - n > 0 and value - n not in ds:\n ds.append(value - n)\n return value - n\n else:\n ds.append(value + n)\n return value + n\n helper(n, ds)\n return ds", "def recamansequence(n):\n l = [0]\n l1 = []\n for i in range(1, n):\n a = l[i - 1] - i\n if a > 0 and a not in l:\n l.append(a)\n else:\n a = l[i - 1] + i\n l.append(a)\n return l", "def recamansequence(n):\n ans = []\n ans.append(0)\n check = set()\n check.add(0)\n\n def rec(n, x):\n if n == x + 1:\n return\n if ans[n - 1] - n > 0 and ans[n - 1] - n not in check:\n check.add(ans[n - 1] - n)\n ans.append(ans[n - 1] - n)\n else:\n ans.append(ans[n - 1] + n)\n check.add(ans[n - 1] + n)\n rec(n + 1, x)\n rec(1, n)\n return ans", "def sol(i, n, li):\n if i == n:\n return\n if li[i - 1] - i > 0 and li[i - 1] - i not in li:\n li[i] = li[i - 1] - i\n else:\n li[i] = li[i - 1] + i\n sol(i + 1, n, li)\n\ndef recamansequence(n):\n li = [0] * n\n sol(1, n, li)\n return li", "def recamansequence(n):\n a = [0]\n count1 = 0\n if n == 1:\n return a\n a = [0] * n\n\n def rec(a, n, count1):\n if count1 >= n:\n return\n z = a[count1 - 1] - count1\n if z > 0 and z not in a:\n a[count1] = z\n else:\n x = a[count1 - 1] + count1\n a[count1] = x\n return rec(a, n, count1 + 1)\n rec(a, n, count1 + 1)\n return a", "def rec(n, res):\n if n == 0:\n res.append(0)\n return 0\n else:\n x = self.rec(n - 1, res)\n if x - n > 0:\n if x - n not in res:\n res.append(x - n)\n return x - n\n else:\n res.append(x + n)\n return x + n\n else:\n res.append(x + n)\n return x + n\n\ndef recamansequence(n):\n res = []\n self.rec(n, res)\n return res", "from collections import defaultdict\n\ndef recamansequence(n):\n ans = []\n visited = defaultdict(bool)\n for i in range(n):\n if i == 0:\n ans.append(0)\n visited[0] = True\n else:\n temp = ans[-1] - i\n if temp < 0 or visited[temp]:\n newtemp = ans[-1] + i\n ans.append(newtemp)\n visited[newtemp] = True\n else:\n ans.append(temp)\n visited[temp] = True\n return ans", "def recamansequence(n):\n if n <= 0:\n return\n s = set()\n s.add(0)\n arr = [0] * n\n for i in range(1, n):\n curr = arr[i - 1] - i\n if curr < 0 or curr in s:\n curr = arr[i - 1] + i\n s.add(curr)\n arr[i] = curr\n return arr", "def recamansequence(n):\n a = [0] * (n + 1)\n for i in range(0, n + 1):\n x = a[i - 1] - i\n if x > 0 and x not in a:\n a[i] = x\n else:\n a[i] = x + 2 * i\n return a", "def result(n, d, sol):\n if n == 0:\n sol[0] = 0\n return 0\n prev_iter = self.result(n - 1, d, sol)\n val1 = prev_iter - n\n if val1 > 0 and val1 not in d:\n d[prev_iter - n] = 1\n sol[n] = prev_iter - n\n return prev_iter - n\n d[prev_iter + n] = 1\n sol[n] = prev_iter + n\n return prev_iter + n\n\ndef recamansequence(n):\n d = {}\n sol = {}\n self.result(n - 1, d, sol)\n return [sol[i] for i in range(n)]", "def recamansequence(n):\n\n def rec(n, res):\n if n == 0:\n res.append(n)\n return\n rec(n - 1, res)\n temp = res[n - 1] - n\n if temp <= 0 or temp in res:\n temp = res[n - 1] + n\n res.append(temp)\n return\n res = []\n rec(n, res)\n return res", "def recursive(i, n, lst):\n if i == n:\n return lst\n if lst[i - 1] - i > 0 and lst[i - 1] - i not in lst:\n lst[i] = lst[i - 1] - i\n else:\n lst[i] = lst[i - 1] + i\n self.recursive(i + 1, n, lst)\n return lst\n\ndef recamansequence(n):\n lst = [0 for _ in range(n)]\n self.recursive(1, n, lst)\n return lst", "def recamansequence_h(n, i, ans):\n if i == n:\n return ans\n if ans[i - 1] - i > 0 and ans[i - 1] - i not in ans:\n ans[i] = ans[i - 1] - i\n else:\n ans[i] = ans[i - 1] + i\n return self.recamansequence_h(n, i + 1, ans)\n\ndef recamansequence(n):\n ans = [0] * n\n i = 1\n self.recamansequence_h(n, i, ans)\n return ans", "def sequence(n, arr):\n if n == 0:\n arr.append(0)\n return 0\n a = sequence(n - 1, arr)\n if a - n > 0 and a - n not in arr:\n arr.append(a - n)\n else:\n arr.append(a + n)\n return arr[-1]\n\ndef recamansequence(n):\n arr = []\n sequence(n, arr)\n return arr", "def recamansequence(n):\n if n == 0:\n return\n a = [0] * n\n for i in range(1, n):\n temp = a[i - 1] - i\n if temp <= 0:\n temp = a[i - 1] + i\n a[i] = temp\n continue\n if temp in a:\n temp = a[i - 1] + i\n a[i] = temp\n return a", "def helper(n, i, ans):\n if i == n:\n return ans\n if ans[i - 1] - i > 0 and ans[i - 1] - i not in ans:\n ans[i] = ans[i - 1] - i\n else:\n ans[i] = ans[i - 1] + i\n return self.helper(n, i + 1, ans)\n\ndef recamansequence(n):\n ans = [0] * n\n output = self.helper(n, 0, ans)\n return ans", "def sol(n, l, N):\n if l[n - 1] - n > 0 and l[n - 1] - n not in l:\n l.append(l[n - 1] - n)\n else:\n l.append(l[n - 1] + n)\n if n == N:\n return l\n return self.sol(n + 1, l, N)\n\ndef recamansequence(n):\n l = [0]\n return self.sol(1, l, n)", "def recamansequence(n):\n arr = []\n i = 1\n arr.append(0)\n self.solve(arr, n, i)\n return arr\n\ndef solve(arr, n, i):\n if i == n:\n return\n if arr[i - 1] - i > 0 and arr[i - 1] - i not in arr:\n x = arr[i - 1] - i\n arr.append(x)\n i = i + 1\n self.solve(arr, n, i)\n else:\n x = arr[i - 1] + i\n arr.append(x)\n i = i + 1\n self.solve(arr, n, i)", "def recamansequence(n):\n res = [0] * n\n if n > 0:\n for i in range(1, n):\n temp = res[i - 1] - i\n if temp > 0 and temp not in res:\n res[i] = temp\n else:\n temp = 0\n temp = res[i - 1] + i\n res[i] = temp\n return res", "def recamansequence(n):\n a = []\n\n def solve(n, a, i):\n if i == 0:\n a.append(i)\n elif i == 1:\n a.append(i)\n elif a[i - 1] - i > 0 and a[i - 1] - i not in a:\n a.append(a[i - 1] - i)\n else:\n a.append(a[i - 1] + i)\n if i == n:\n return\n solve(n, a, i + 1)\n solve(n, a, 0)\n return a", "from collections import defaultdict\n\ndef recamansequence(n):\n h = defaultdict(lambda : False)\n seq = [0] * n\n for i in range(1, n):\n x = seq[i - 1] - i\n if x > 0 and h[x] == False:\n seq[i] = x\n else:\n seq[i] = seq[i - 1] + i\n h[seq[i]] = True\n return seq", "def recamansequence(n):\n arr = [0]\n aa = set()\n for i in range(1, n):\n if arr[-1] - i > 0 and arr[-1] - i not in aa:\n aa.add(arr[-1] - i)\n arr.append(arr[-1] - i)\n else:\n aa.add(arr[-1] + i)\n arr.append(arr[-1] + i)\n return arr", "def recamansequence(n):\n li = [0] * n\n self.recman_sequence(n, li)\n return li\n\ndef recman_sequence(n, li):\n for i in range(1, n):\n if li[i - 1] - i > 0 and li[i - 1] - i not in li:\n li[i] = li[i - 1] - i\n else:\n li[i] = li[i - 1] + i\n return li", "def recamansequence(n):\n if n <= 0:\n return\n res = []\n res.append(0)\n sett = set()\n sett.add(0)\n if n == 1:\n return res\n pre = 0\n for i in range(1, n):\n curr = pre - i\n if curr < 0 or curr in sett:\n curr = pre + i\n sett.add(curr)\n res.append(curr)\n pre = curr\n return res", "def recamansequence(n):\n res = [0]\n d = {}\n\n def func(n, i=1):\n if i == n:\n return\n ans = res[i - 1] - i\n if ans in d or ans <= 0:\n ans = res[i - 1] + i\n d[ans] = 1\n res.append(ans)\n func(n, i + 1)\n func(n)\n return res", "from collections import defaultdict\n\ndef recamansequence(n):\n res = [0]\n d = defaultdict(int)\n for i in range(1, n):\n ans = res[i - 1] - i\n if ans in d or ans <= 0:\n ans = res[i - 1] + i\n d[ans] += 1\n res.append(ans)\n return res", "def recamansequence(n):\n if n == 0:\n return [0]\n li = [0]\n for i in range(1, n):\n l = li[i - 1]\n z = l - i\n if z < 0 or z in li:\n z = l + i\n li.append(z)\n return li", "def seq(curr, n, List):\n if curr == n + 1:\n return List\n if curr == 0:\n List.append(curr)\n return self.seq(curr + 1, n, List)\n x = List[-1]\n if x - curr > 0 and x - curr not in List:\n List.append(x - curr)\n else:\n List.append(x + curr)\n return self.seq(curr + 1, n, List)\n\ndef recamansequence(n):\n List = []\n self.seq(0, n, List)\n return List", "def recamansequence(n):\n d = {0: 0}\n res = [0]\n for i in range(1, n + 1):\n if res[-1] - i > 0 and res[-1] - i not in d:\n a1 = res[-1] - i\n else:\n a1 = res[-1] + i\n res.append(a1)\n d[a1] = 1\n return res"], "starter_code": "def recamansequence(n):\n", "input_output": {"inputs": ["n = 6", "n = 3"], "outputs": ["0 1 3 6 2 7", "0 1 3"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical", "Hash", "Recursion", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures", "Mathematics", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/recamans-sequence4856/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "recamansequence", "task_id": "TACO_lite/225", "example": [[], []]} +{"requirement": "Given a positive integer N, print count of set bits in it. \nExample 1:\nInput:\nN = 6\nOutput:\n2\nExplanation:\nBinary representation is '110' \nSo the count of the set bit is 2.\nExample 2:\nInput:\n8\nOutput:\n1\nExplanation:\nBinary representation is '1000' \nSo the count of the set bit is 1.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function setBits() which takes an Integer N and returns the count of number of set bits.\nExpected Time Complexity: O(LogN)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ N ≤ 10^{9}", "solutions": ["def setbits(N):\n dnum = N\n i = 0\n bnum = []\n while dnum != 0:\n rem = dnum % 2\n bnum.insert(i, rem)\n i = i + 1\n dnum = int(dnum / 2)\n x = 0\n for f in bnum:\n if f == 1:\n x = x + 1\n return x", "def setbits(N):\n c = 0\n while N:\n c += 1\n N = N & N - 1\n return c", "def setbits(n):\n count = 0\n while n > 0:\n if n % 2 == 1:\n count += 1\n n //= 2\n return count", "def setbits(N):\n if N <= 1:\n return 1\n a = 0\n while N > 1:\n x = N % 2\n N = N // 2\n if x == 1:\n a += 1\n return a + 1", "def setbits(N):\n n = bin(N)\n n = n[2:]\n return n.count('1')", "def setbits(N):\n return bin(N).count('1')", "def setbits(N):\n count = 0\n while N != 0:\n if N & 1 == 1:\n count += 1\n N >>= 1\n return count", "def setbits(N):\n n = bin(N).replace('0b', '')\n count = 0\n for i in n:\n if i == '1':\n count = count + 1\n return count", "def setbits(N):\n count = 0\n n = N\n while n > 0:\n n = n & n - 1\n count = count + 1\n return count", "def setbits(N):\n res = 0\n while N > 0:\n res += 1\n N = N & N - 1\n return res", "def setbits(N):\n x = bin(int(N))\n y = x[2:]\n lis = list(y)\n return lis.count('1')", "def setbits(N):\n A = bin(N)[2:]\n ans = 0\n for i in A:\n if i == '1':\n ans += 1\n return ans", "def setbits(N):\n n = bin(N)\n return str(n).count('1')", "def setbits(N):\n s = bin(N)\n d = s[2:]\n k = d.count('1')\n return k", "def setbits(N):\n d = bin(N)\n c = d.count('1')\n return c", "def setbits(N):\n cnt = 0\n for i in bin(N):\n if i == '1':\n cnt += 1\n return cnt", "def setbits(N):\n c = 0\n while N != 0:\n bit = N & 1\n if bit:\n c += 1\n N = N >> 1\n return c", "def setbits(N):\n t = bin(N)[2:]\n p = t.count('1')\n return p", "def setbits(N):\n b = bin(N)\n a = b.count('1')\n return a", "def setbits(N):\n binary = bin(N)[2:]\n return binary.count('1')", "def setbits(N):\n x = bin(N)\n z = str(x).count('1')\n return z", "def setbits(N):\n b = bin(N)\n b = b[2:]\n count = 0\n l = list(str(b))\n for i in l:\n if i == '1':\n count = count + 1\n return count", "def setbits(N):\n count = 0\n binary = str(bin(N))\n for i in binary:\n if i == str(1):\n count += 1\n return count", "def setbits(N):\n c = 0\n x = bin(N)\n for i in x:\n if i == '1':\n c += 1\n return c", "def setbits(N):\n x = bin(N)\n m = x.count('1')\n return m", "def setbits(N):\n ob = bin(N)\n b = ob[2:]\n s = str(b)\n return s.count('1')", "def setbits(N):\n a = bin(N)\n m = str(a).count('1')\n return m", "def setbits(n):\n res = 0\n while n:\n n &= n - 1\n res += 1\n return res", "def setbits(N):\n dectobinary = bin(N)[2:]\n return dectobinary.count('1')", "def setbits(N):\n b = str(format(N, 'b'))\n res = 0\n for i in range(len(b)):\n if b[i] == '1':\n res += 1\n return res", "def setbits(N):\n binary_n = str(bin(int(N)))[2:]\n cnt = 0\n for i in binary_n:\n if int(i) == 1:\n cnt += 1\n return cnt", "def setbits(N):\n cnt = 0\n for i in range(32):\n if N & 1 << i:\n cnt += 1\n return cnt", "def setbits(N):\n no_of_digits = 0\n while N:\n if N % 2:\n no_of_digits += 1\n N = N >> 1\n return no_of_digits", "def setbits(N):\n b = bin(N)[2:]\n return b.count('1')", "def setbits(N):\n cnt = 0\n while N > 0:\n if N & 1 == 1:\n cnt = cnt + 1\n N = N >> 1\n return cnt", "def setbits(N):\n b = '{:b}'.format(N)\n return b.count('1')", "def setbits(N):\n b = bin(N)[2:]\n c = 0\n for i in b:\n if i == '1':\n c += 1\n return c", "def setbits(N):\n N = str(bin(N))\n N = N[2:]\n return N.count('1')", "def setbits(n):\n l = []\n while n > 0:\n l.append(n % 2)\n n //= 2\n k = l.count(1)\n return k", "import math\n\ndef setbits(N):\n n = int(math.log2(N)) + 1\n count = 0\n for i in range(n):\n if 1 << i & N:\n count += 1\n return count", "import math\n\ndef setbits(N):\n count = 0\n S = str(bin(N))\n for i in S:\n if i == '1':\n count += 1\n return count", "def setbits(N):\n a = list(bin(N))\n count = 0\n for i in range(len(a)):\n if str(1) == a[i]:\n count += 1\n return count", "def setbits(N):\n s = bin(N)\n c = 0\n for i in range(2, len(s)):\n if s[i] == '1':\n c += 1\n return c", "import math\n\ndef setbits(N):\n no_bits = math.ceil(math.log2(N))\n set_bits = 0\n for i in range(no_bits + 1):\n if N & 1 << i:\n set_bits += 1\n return set_bits", "def setbits(N):\n (k, ans) = (N, 0)\n while k > 0:\n if k & 1 == 1:\n ans += 1\n k = k // 2\n return ans", "def setbits(N):\n ans = 0\n while N:\n N = N & N - 1\n ans += 1\n return ans", "def setbits(N):\n countSetBit = 0\n while N != 0:\n lastBit = N & 1\n if lastBit == 1:\n countSetBit += 1\n N = N >> 1\n return countSetBit", "def setbits(n):\n s = bin(n).replace('0b', ' ')\n s = str(s)\n c = 0\n for i in s:\n if i == '1':\n c += 1\n return c"], "starter_code": "def setbits(N):\n", "input_output": {"inputs": ["N = 6", "8"], "outputs": ["2", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/set-bits0143/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(LogN)", "entry_point": "setbits", "task_id": "TACO_lite/314", "example": [[[6], [8]], ["2", "1"]]} +{"requirement": "Find the number of factors for a given integer N.\n \nExample 1:\nInput:\nN = 5\nOutput:\n2\nExplanation:\n5 has 2 factors 1 and 5\nExample 2:\nInput:\nN = 25\nOutput:\n3\nExplanation:\n25 has 3 factors 1, 5, 25\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function countFactors() which takes an integer N as input parameters and returns an integer, total number factor of N.\n \nExpected Time Complexity: O(sqrt(N))\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= N <= 100000", "solutions": ["def countfactors(N):\n count = 0\n for i in range(1, int(N ** 0.5) + 1):\n if N % i == 0:\n count += 1\n if i != N // i:\n count += 1\n return count", "def countfactors(N):\n i = 1\n fact = 0\n while i * i <= N:\n if N % i == 0:\n fact += 1\n if N / i != i:\n fact += 1\n i = i + 1\n return fact", "import math\n\ndef countfactors(N):\n count = 0\n res = set()\n for i in range(1, int(math.sqrt(N)) + 1):\n if N % i == 0:\n res.add(i)\n res.add(N / i)\n return len(res)", "def countfactors(N):\n factCount = 0\n for i in range(1, N // 2 + 1):\n if N % i == 0:\n factCount += 1\n return factCount + 1", "from math import sqrt\n\ndef countfactors(N):\n cnt = 0\n for i in range(1, int(sqrt(N) + 1)):\n if N % i == 0:\n if N / i == i:\n cnt += 1\n else:\n cnt += 2\n return cnt", "def countfactors(N):\n if N == 2:\n return 2\n if N == 1:\n return 1\n c = 1\n if N % 2 == 0:\n c = 3\n for i in range(3, N // 2):\n if N % i == 0:\n c += 1\n return c + 1", "import math\n\ndef countfactors(N):\n count = 0\n i = 1\n while i <= math.sqrt(N):\n if N % i == 0:\n if i == N / i:\n count = count + 1\n else:\n count = count + 2\n i = i + 1\n return count", "def countfactors(N):\n if N == 1:\n return 1\n res = 2\n for i in range(2, int(N ** 0.5) + 1):\n if N % i == 0:\n if i * i == N:\n res = res + 1\n else:\n res = res + 2\n return res", "def countfactors(N):\n c = 0\n s = N\n for i in range(1, int(s ** 0.5) + 1):\n if s % i == 0:\n c += 1\n if s // i != i:\n c += 1\n return c", "def countfactors(N):\n lis = []\n for i in range(1, int(N ** 0.5 + 1)):\n if N % i == 0:\n if i == N // i:\n lis.append(i)\n else:\n lis.append(i)\n lis.append(N // i)\n lis.sort()\n return len(lis)", "import math\n\ndef countfactors(N):\n count = 0\n for i in range(1, int(math.sqrt(N)) + 1):\n if N % i == 0:\n count += 1\n if N / i != i:\n count += 1\n return count", "import math\n\ndef countfactors(n):\n i = 1\n l = []\n while i <= math.sqrt(n):\n if n % i == 0:\n if n / i == i:\n l.append(i)\n else:\n l.append(int(n / i))\n l.append(i)\n i += 1\n return len(l)", "def countfactors(N):\n ans = 2\n i = 2\n while i * i <= N:\n if N % i == 0:\n if N / i == i:\n ans += 1\n else:\n ans += 2\n i += 1\n return ans", "import math\n\ndef countfactors(N):\n factors = []\n for i in range(1, int(math.sqrt(N)) + 1, 1):\n if N % i == 0:\n if N / i == i:\n factors.append(i)\n else:\n factors.append(i)\n factors.append(int(N / i))\n return len(factors)", "from math import *\n\ndef countfactors(N):\n c = 0\n for i in range(1, int(sqrt(N)) + 1):\n if N % i == 0 and i ** 2 != N:\n c += 2\n elif i ** 2 == N:\n c += 1\n return c", "import math\n\ndef countfactors(N):\n s = 0\n a = []\n for i in range(1, int(math.sqrt(N)) + 1):\n if N % i == 0:\n if N / i == i:\n s += 1\n else:\n s += 2\n return s", "def countfactors(N):\n count = 0\n i = 1\n while i * i <= N:\n if N % i == 0:\n fact = N / i\n if fact == i:\n count += 1\n else:\n count += 2\n i += 1\n return count", "def countfactors(N):\n count = 0\n for i in range(1, int(pow(N, 0.5)) + 1):\n if N % i == 0 and i ** 2 != N:\n count += 2\n elif i ** 2 == N:\n count += 1\n return count", "import math\n\ndef countfactors(n):\n i = 1\n co = 0\n while i <= int(math.sqrt(n)):\n if n % i == 0:\n if n // i == i:\n co += 1\n else:\n co += 2\n i += 1\n return co", "def countfactors(N):\n i = 1\n count = 0\n while i * i <= N:\n if i * i == N:\n count += 1\n elif N % i == 0:\n count += 2\n i += 1\n return count", "def countfactors(N):\n import math\n ans = 0\n sqrt = round(math.sqrt(N))\n for i in range(1, sqrt + 1):\n if N % i == 0:\n if N / i == i:\n ans += 1\n else:\n ans += 2\n return ans", "import math\n\ndef countfactors(n):\n count = 0\n s = int(math.sqrt(n)) + 1\n for i in range(2, s):\n if n % i == 0:\n if n / i == i:\n count += 1\n else:\n count += 2\n return int(count) + 2", "from math import *\n\ndef countfactors(n):\n ans = []\n for i in range(1, floor(sqrt(n)) + 1):\n if n % i == 0:\n ans.append(i)\n if n // i != i:\n ans.append(n // i)\n return len(ans)", "def countfactors(N):\n i = 1\n count = 0\n while i <= int(N ** 0.5):\n if N % i == 0:\n if N / i == i:\n count += 1\n else:\n count += 2\n i += 1\n return count", "def countfactors(n):\n i = 1\n count = 0\n while i * i <= n:\n if n % i == 0:\n count = count + 1\n if n // i != i:\n count = count + 1\n i = i + 1\n return count", "def countfactors(N):\n import math\n ans = 0\n ans_ = 0\n if N == int(math.sqrt(N)) * int(math.sqrt(N)):\n y = int(math.sqrt(N))\n else:\n y = int(math.sqrt(N)) + 1\n for i in range(1, y):\n if N % i == 0:\n ans += 1\n if N == int(math.sqrt(N)) * int(math.sqrt(N)):\n ans_ = 1\n return 2 * ans + ans_", "def countfactors(N):\n ans = []\n for i in range(1, N // 2 + 1):\n if N % i == 0:\n ans.append(i)\n return len(ans) + 1", "import math as m\n\ndef countfactors(N):\n DiViSoRs = 0\n sqrtN = int(m.sqrt(N)) + 1\n for factor in range(1, sqrtN):\n if N % factor == 0:\n if N / factor == factor:\n DiViSoRs += 1\n else:\n DiViSoRs += 2\n return DiViSoRs", "from math import sqrt\n\ndef countfactors(N):\n ans = []\n for i in range(1, int(sqrt(N)) + 1):\n if N % i == 0:\n ans.append(i)\n if i != N // i:\n ans.append(N // i)\n return len(ans)", "def countfactors(N):\n start = 1\n count = 0\n while start * start < N:\n if N % start == 0:\n count += 1\n start += 1\n count = 2 * count\n if start * start == N:\n count += 1\n return count", "def countfactors(N):\n i = 1\n count = 0\n while i * i <= N:\n if N % i == 0:\n count += 1\n if N // i != i and N % (N // i) == 0:\n count += 1\n i += 1\n return count", "def countfactors(N):\n import math\n i = 1\n c = 0\n sr = math.floor(math.sqrt(N))\n while i <= sr:\n if N % i == 0:\n if i * i == N:\n c += 1\n else:\n c += 2\n i += 1\n return c", "from math import *\n\ndef countfactors(num):\n start = 1\n end = int(sqrt(num))\n ans = 0\n for i in range(start, end + 1):\n if num % i == 0:\n ans += 1\n return ans * 2 - 1 if end * end == num else ans * 2", "def countfactors(N):\n co = 0\n for i in range(1, int(N / 2) + 1):\n if N % i == 0:\n co += 1\n return co + 1"], "starter_code": "def countfactors (N):\n", "input_output": {"inputs": ["N = 5", "N = 25"], "outputs": ["2", "3"]}, "difficulty": "EASY", "raw_tags": ["Misc"], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/number-of-factors1435/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(sqrt(N))", "entry_point": "countfactors", "task_id": "TACO_lite/313", "example": [[[5], [25]], ["2", "3"]]} +{"requirement": "## Debugging sayHello function\n\nThe starship Enterprise has run into some problem when creating a program to greet everyone as they come aboard. It is your job to fix the code and get the program working again!\n\nExample output: \n```\nHello, Mr. Spock\n```", "solutions": ["def say_hello(name):\n return f'Hello, {name}'", "def say_hello(name):\n return 'Hello, ' + name", "def say_hello(name):\n return 'Hello, {0}'.format(name)", "say_hello = 'Hello, '.__add__", "def say_hello(name):\n return 'Hello, %s' % name", "def say_hello(input):\n return 'Hello, ' + input", "say_hello = lambda n: 'Hello, {}'.format(n)", "def say_hello(n):\n return 'Hello, ' + n", "def say_hello(name):\n if name:\n return 'Hello, ' + name", "def say_hello(name):\n return 'Hello, ' + name\n pass", "def say_hello(name):\n if name == '':\n return 'Hello, World'\n else:\n return 'Hello, {}'.format(name)", "def say_hello(name):\n return 'Hello, ' + name\nsay_hello('Mr. Spock')\nsay_hello('Captain Kirk')\nsay_hello('Liutenant Uhura')\nsay_hello('Dr. McCoy')\nsay_hello('Mr. Scott')", "say_hello = lambda name: 'Hello, %s' % name", "say_hello = lambda n: 'Hello, %s' % n", "say_hello = lambda k: f'Hello, {k}'", "import unittest\n\ndef say_hello(name):\n return 'Hello, {}'.format(name)\n\ndef test_say_hello():\n self.assertEqual(say_hello('Mr. Spock'), 'Hello, Mr. Spock')", "def say_hello(name):\n a = 'Hello, '\n b = name\n return a + b", "def say_hello(name):\n hello = 'Hello' + ', ' + name\n return hello", "def say_hello(name):\n return 'Hello, ' + name\nsay_hello('dff')", "def say_hello(name: str) -> str:\n result: str = 'Hello, ' + name\n return result", "def say_hello(name):\n return 'Hello' + ', ' + name\nsay_hello('Mr.Spock')", "def say_hello(name):\n out = 'Hello, ' + name\n return out", "def say_hello(name):\n return 'Hello, {nam}'.format(nam=name)", "def say_hello(name='World'):\n name = str(name)\n greet = 'Hello, ' + name\n return greet", "def say_hello(name):\n name = ('Hello,', name)\n name = ' '.join(name)\n return name", "def say_hello(n=''):\n return f'Hello, {n}'", "def say_hello(name):\n p = 'Hello, {}'.format(name)\n return p", "def say_hello(name: any) -> str:\n return 'Hello, ' + str(name)", "def say_hello(name):\n answer = 'Hello, ' + name\n return answer", "def say_hello(name):\n sen = 'Hello, ' + name\n return sen", "def say_hello(name):\n return 'Hello, {n}'.format(n=name)", "def say_hello(name):\n string = 'Hello' + ', ' + name\n return string", "def say_hello(name):\n say = 'Hello, ' + name\n return say", "def say_hello(name):\n ans = 'Hello, ' + name\n return ans", "def say_hello(name):\n salu = name\n return 'Hello, {}'.format(salu)", "def say_hello(name):\n return 'Hello, ' + name\nsay_hello('Marissa')", "def say_hello(name):\n return ' ,olleH'[::-1] + name", "def say_hello(name):\n sh = 'Hello, ' + name\n return sh", "def say_hello(name):\n hi = 'Hello' + ',' + ' ' + name\n return hi", "def say_hello(name):\n hello_name = 'Hello, ' + name\n return hello_name", "def say_hello(name):\n return f'Hello, {name}'\nsay_hello('Mr. Robot')", "def say_hello(name):\n asd = ('Hello,', name)\n asf = ' '.join(asd)\n return asf", "def say_hello(name):\n x = 'Hello, ' + name\n return x", "def say_hello(name):\n return 'Hello, ' + name\nlist = ['Mr. Steve', 'Captain Kata', 'Eren Yeager', 'Dr. McCoi', 'Mrs. Scott']\nsay_hello(list[0])\nsay_hello(list[1])\nsay_hello(list[2])\nsay_hello(list[3])\nsay_hello(list[4])", "def say_hello(name):\n greeting = 'Hello' + ', ' + name\n return greeting", "def say_hello(name):\n var = 'Hello, {}'.format(name)\n return var", "def say_hello(name):\n output = 'Hello, ' + name\n return output", "def say_hello(name):\n return 'Hello, ' + name\nsay_hello('MacMillan')"], "starter_code": "def say_hello(name):\n", "input_output": {"fn_name": "say_hello", "inputs": [["Mr. Spock"], ["Captain Kirk"], ["Liutenant Uhura"], ["Dr. McCoy"], ["Mr. Scott"]], "outputs": [["Hello, Mr. Spock"], ["Hello, Captain Kirk"], ["Hello, Liutenant Uhura"], ["Hello, Dr. McCoy"], ["Hello, Mr. Scott"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5625618b1fe21ab49f00001f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "say_hello", "task_id": "TACO_lite/267", "example": [[["Mr. Spock"]], ["Hello, Mr. Spock"]]} +{"requirement": "Given a number N. Find the last two digits of the Nth fibonacci number.\nNote: If the last two digits are 02, return 2.\nExample 1:\nInput:\nN = 13\nOutput:\n33\nExplanation:\nThe 13th Fibonacci number is 233.\nSo last two digits are 3 and 3.\nExample 2:\nInput:\nN = 255\nOutput:\n70\nExplanation:\nThe 255th fibonacci number is 875715953430-\n18854458033386304178158174356588264390370.\nThus, last two digits are 7 and 0.\nYour Task:\nYou don't need to read input or print anything.Your task is to complete the function fibonacciDigits() which takes a number N as input parameter and returns the last two digits of the Nth fibonacci number.\nExpected Time Complexity:O(K)\nExpected Auxillary Space:O(K)\nK is of the order 10^{2}.\nConstraints:\n1<=N<=10^{18}", "solutions": ["def fibonaccidigits(N):\n return int(str(self.gfn(N % 300))[-2:])\n\ndef gfn(n):\n if n < 1:\n return 0\n n1 = 0\n n2 = 1\n while n > 1:\n n2 += n1\n n1 = n2 - n1\n n -= 1\n return n2", "def fibonaccidigits(N):\n n1 = 0\n n2 = 1\n k = 1\n while N > 300:\n N = N % 300\n while k <= N:\n k += 1\n (n1, n2) = ((n1 + n2) % 100, n1 % 100)\n return int(n1 % 100)", "def fibonaccidigits(N):\n (a, b) = (0, 1)\n k = 1\n while N > 300:\n N = N % 300\n while k <= N:\n k += 1\n (a, b) = ((a + b) % 100, a % 100)\n return int(a % 100)", "def fibonaccidigits(N):\n (a, b, c, N) = (1, 1, 2, N % 300)\n if N == 0:\n return 0\n if N == 1 or N == 2:\n return 1\n while c < N:\n (a, b) = (b, (a + b) % 100)\n c += 1\n if c == N:\n return b", "def fibonaccidigits(N):\n fib = [0] * 300\n fib[0] = 0\n fib[1] = 1\n fib[2] = 1\n for i in range(3, len(fib)):\n fib[i] = (fib[i - 2] + fib[i - 1]) % 100\n return fib[N % 300]", "def fibonaccidigits(N):\n fibonacci = []\n fibonacci.append(0)\n fibonacci.append(1)\n for i in range(2, 300):\n fibonacci.append((fibonacci[i - 1] + fibonacci[i - 2]) % 100)\n return fibonacci[N % 300]", "def fibonaccidigits(n):\n n = n % 300\n if n in {0, 1}:\n return n\n a = 0\n b = 1\n c = 0\n for i in range(2, n + 1):\n c = (a + b) % 100\n a = b % 100\n b = c % 100\n return c % 300", "def fibonaccidigits(N):\n x = 1\n y = 1\n c = 2\n ans = [0, 1, 1]\n while c < 301:\n (x, y) = (y, y + x)\n c += 1\n ans.append(y % 100)\n return ans[N % 300]", "def fibonaccidigits(N):\n m = N % 300\n a = 0\n b = 1\n if m == 0 or m == 1:\n return m\n for i in range(1, m):\n sum = (a + b) % 100\n (a, b) = (b % 100, sum)\n return sum % 100", "def fibonaccidigits(N):\n dp = [i for i in range(300)]\n dp[0] = 0\n dp[1] = 1\n dp[2] = 1\n for i in range(3, 300):\n dp[i] = (dp[i - 1] + dp[i - 2]) % 100\n return dp[int(N % 300)]", "def fast_fibonacci(ans, n):\n if n == 0:\n ans[0] = 0\n ans[1] = 1\n return\n self.fast_fibonacci(ans, n // 2)\n a = ans[0]\n b = ans[1]\n c = 2 * b - a\n c = a * c\n d = a * a + b * b\n if n % 2 == 0:\n ans[0] = c\n ans[1] = d\n else:\n ans[0] = d\n ans[1] = c + d\n\ndef fibonaccidigits(N):\n ans = [0, 0]\n self.fast_fibonacci(ans, N % 300)\n return ans[0] % 100", "def fibonaccidigits(N):\n a = 1\n b = 1\n c = 0\n N = N % 300\n if N == 1:\n return a\n if N == 2:\n return b\n for i in range(3, N + 1):\n c = int(a + b) % 100\n a = b % 100\n b = c % 100\n return c", "def fibonaccidigits(N):\n fib = [0] * 300\n fib[0] = 0\n fib[1] = 1\n for i in range(2, min(299, N) + 1):\n fib[i] = (fib[i - 1] + fib[i - 2]) % 100\n return fib[N % 300]", "def fibonaccidigits(n):\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n a = 0\n b = 1\n for i in range(n % 900):\n c = a + b\n a = b\n b = c\n if a < 9:\n return a\n else:\n return a % 100", "def fibonaccidigits(N):\n arr = [None] * 300\n arr[0] = 0\n arr[1] = 1\n arr[2] = 1\n for i in range(3, 300):\n arr[i] = (arr[i - 2] + arr[i - 1]) % 100\n return arr[N % 300]", "def fibonaccidigits(N):\n if N == 0 or N == 1:\n return N\n f = []\n f.append(0)\n f.append(1)\n for i in range(2, 300):\n f.append((f[i - 1] + f[i - 2]) % 100)\n return f[N % 300]", "import math\n\ndef fibonaccidigits(N):\n fib = [0] * 300\n fib[0] = 0\n fib[1] = 1\n fib[2] = 1\n for i in range(3, 300):\n fib[i] = (fib[i - 1] + fib[i - 2]) % 100\n return fib[abs(N % 300)]", "def fibonaccidigits(N):\n l = list()\n l.append(0)\n l.append(1)\n l.append(1)\n s1 = 1\n s2 = 1\n s = 0\n n = 1\n while n < 300:\n s = s1 + s2\n l.append(s % 100)\n s2 = s1\n s1 = s\n n += 1\n return l[N % 300]", "def fibonaccidigits(N):\n N = N % 300\n ans = 0\n if N == 1:\n ans = 1\n elif N == 2:\n ans = 1\n a = 1\n b = 1\n for i in range(3, N + 1):\n ans = a + b\n a = b\n b = ans\n return ans % 100", "def fibonaccidigits(n):\n f = []\n f.append(0)\n f.append(1)\n for i in range(2, 300):\n f.append((f[i - 1] + f[i - 2]) % 100)\n return f[n % 300]", "def fib(n):\n if n == 0:\n return 0\n a = b = 1\n for _ in range(n - 2):\n (a, b) = (b, a + b)\n return b\n\ndef fibonaccidigits(N):\n val = self.fib(N % 300)\n return int(str(val)[-2:])", "def fibonaccidigits(N):\n rem = N % 300\n a = 1\n b = 1\n if rem == 0:\n return 0\n elif rem <= 2:\n return 1\n res = 0\n temp = 0\n for i in range(3, rem + 1):\n res = a + b\n temp = res % 100\n a = b\n b = res\n return temp", "def fibonaccidigits(N):\n f = [0] * 300\n f[1] = f[2] = 1\n c = 3\n while c < 300:\n f[c] = (f[c - 1] + f[c - 2]) % 100\n c += 1\n return f[N % 300]", "def fibonaccidigits(N):\n fab = []\n tmp0 = 0\n tmp1 = 1\n tmp = 0\n mod_N = N % 300\n for i in range(1, mod_N + 1):\n tmp = tmp0 + tmp1\n fab.append(tmp)\n tmp0 = tmp1\n tmp1 = tmp\n dig = str(tmp0)\n if len(dig) < 2:\n return int(dig[0])\n if int(dig[-2]) == 0:\n return int(dig[-1])\n else:\n return int(dig[-2:])", "def fibonaccidigits(N):\n n = N % 300\n if n == 0:\n return 0\n elif n == 1:\n return 1\n out = self.matrixmul(n - 1)\n return out[0][0] % 100\n\ndef matrixmul(N):\n temp = [[0, 0], [0, 0]]\n if N == 1:\n return [[1, 1], [1, 0]]\n temp = self.matrixmul(N // 2)\n lst = []\n lst.append(temp[0][0] * temp[0][0] + temp[0][1] * temp[1][0])\n lst.append(temp[0][0] * temp[0][1] + temp[0][1] * temp[1][1])\n lst.append(temp[1][0] * temp[0][0] + temp[1][1] * temp[1][0])\n lst.append(temp[1][0] * temp[0][1] + temp[1][1] * temp[1][1])\n temp[0][0] = lst[0]\n temp[0][1] = lst[1]\n temp[1][0] = lst[2]\n temp[1][1] = lst[3]\n if N % 2 == 0:\n return temp\n else:\n lst = []\n lst.append(temp[0][0] + temp[0][1])\n lst.append(temp[0][0])\n lst.append(temp[1][0] + temp[1][1])\n lst.append(temp[1][0])\n temp[0][0] = lst[0]\n temp[0][1] = lst[1]\n temp[1][0] = lst[2]\n temp[1][1] = lst[3]\n return temp", "def fibonaccidigits(N):\n l = [0, 1]\n for i in range(1, 300):\n l.append(l[i - 1] + l[i])\n if N % 300 == N:\n return l[N] % 100\n else:\n return l[N % 300] % 100", "def fibonaccidigits(N):\n if N > 300:\n N = N % 300\n if N == 0:\n return 0\n elif N == 1:\n return 1\n else:\n fib = [0] * (N + 1)\n fib[0] = 0\n fib[1] = 1\n for i in range(2, N + 1):\n fib[i] = fib[i - 2] + fib[i - 1]\n m = fib[N]\n return m % 100\n else:\n fib = [0] * (N + 1)\n fib[0] = 0\n fib[1] = 1\n for i in range(2, N + 1):\n fib[i] = fib[i - 2] + fib[i - 1]\n m = fib[N]\n return m % 100", "def fibonaccidigits(N):\n return Solution.vl_all[N % 300]"], "starter_code": "def fibonaccidigits(N):\n", "input_output": {"inputs": ["N = 13", "N = 255"], "outputs": ["33", "70"]}, "difficulty": "EASY", "raw_tags": ["Fibonacci", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/last-two-digit-fibonacci3353/1", "Expected Auxiliary Space": "O(K)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(K)", "entry_point": "fibonaccidigits", "task_id": "TACO_lite/311", "example": [[[13], [255]], ["33", "70"]]} +{"requirement": "Given a number N. The task is to check whether it is sparse or not. A number is said to be a sparse number if no two or more consecutive bits are set in the binary representation.\nExample 1:\nInput: N = 2\nOutput: 1\nExplanation: Binary Representation of 2 is 10, \nwhich is not having consecutive set bits. \nSo, it is sparse number.\nExample 2:\nInput: N = 3\nOutput: 0\nExplanation: Binary Representation of 3 is 11, \nwhich is having consecutive set bits in it. \nSo, it is not a sparse number.\nYour Task: The task is to complete the function checkSparse() that takes n as a parameter and returns 1 if the number is sparse else returns 0.\nExpected Time Complexity: O(1).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= N <= 10^{6}", "solutions": ["def issparse(n):\n k = bin(n)[2:]\n a = k.split('0')\n for i in a:\n if len(i) > 1:\n return 0\n return 1", "def issparse(n):\n binary = []\n while n > 0:\n x = n % 2\n binary.append(x)\n n = n // 2\n for i in range(0, len(binary) - 1):\n if binary[i] == binary[i + 1] and binary[i] == 1:\n return 0\n return 1", "def issparse(n):\n while n > 0:\n x = n\n n = n >> 1\n if x & 1 == 1 and n & 1 == 1:\n return 0\n return 1", "def bina(n):\n b = ''\n while n != 1:\n b = str(n % 2) + b\n n = n // 2\n return '1' + b\n\ndef issparse(n):\n n = Solution.bina(n)\n n = str(n)\n if '11' in n:\n return 0\n return 1", "def issparse(n):\n numero = bin(n)[2:]\n if len(numero) == 1:\n return True\n ultimo = numero[0]\n for l in numero[1:]:\n if l == '1' and ultimo == '1':\n return False\n else:\n ultimo = l\n return True", "def issparse(n):\n count = 0\n while n != 0:\n if n & 1 == 1:\n count += 1\n if count == 2:\n return 0\n else:\n count = 0\n n = n // 2\n return 1", "def issparse(n):\n a = bin(n)[2:]\n b = a.split('0')\n for i in b:\n if len(i) >= 2:\n return False\n return True", "def issparse(n):\n if n >> 1 & n == 0:\n return True\n return False", "def issparse(n):\n binn = bin(n)[2:]\n if '11' in binn:\n return 0\n return 1", "def issparse(n: int) -> bool:\n binary_str = bin(n)[2:]\n for i in range(len(binary_str) - 1):\n if binary_str[i] == '1' and binary_str[i + 1] == '1':\n return False\n return True", "def issparse(n):\n c = 0\n flag = -1\n while n != 0:\n if n & 1 == 1:\n if flag == 1:\n return 0\n flag = 1\n else:\n flag = 0\n n = n >> 1\n return 1", "def issparse(n):\n while n:\n if n & 3 == 3:\n return False\n n >>= 1\n return True", "def issparse(n):\n binary = bin(n)[2:]\n for i in range(len(binary) - 1):\n if binary[i] == '1' and binary[i + 1] == '1':\n return 0\n return 1", "def issparse(n):\n binary = bin(n)[2:]\n if '11' in binary:\n return False\n else:\n return True", "def issparse(n):\n binary = format(n, 'b')\n for i in range(0, len(binary) - 1):\n if binary[i] == binary[i + 1] and binary[i] == '1':\n return 0\n return 1", "def issparse(n):\n elem = str(bin(n))[2:]\n for i in range(len(elem) - 1):\n if elem[i] == '1':\n if elem[i] == elem[i + 1]:\n return False\n return True", "def issparse(n):\n last = False\n for (i, ch) in enumerate(bin(n)):\n if i > 0 and last and (ch == '1'):\n return 0\n last = True if ch == '1' else False\n return 1", "def issparse(n):\n prev = 0\n while n > 0:\n if n % 2 and prev:\n return 0\n prev = n % 2\n n = n // 2\n return 1", "def issparse(n):\n a = bin(n)[2:]\n string = str(a)\n for i in range(0, len(string) - 1):\n if string[i] == '1' and string[i + 1] == '1':\n return 0\n return 1", "def issparse(n):\n prev_bit = '0'\n bits = bin(n)[2:]\n for bit in bits:\n if bit == '1' and prev_bit == '1':\n return 0\n prev_bit = bit\n return 1", "def issparse(n):\n return n & n >> 1 == 0", "def issparse(num):\n n = bin(num)\n n = list(n)\n n = n[2:]\n for i in range(len(n) - 1):\n if n[i] == n[i + 1] == '1':\n return 0\n return 1", "def issparse(n):\n len = 0\n if n == 0:\n return True\n while n > 0:\n if n & 1:\n len += 1\n if len > 1:\n return False\n else:\n len = 0\n n >>= 1\n return True", "def issparse(n):\n b = bin(n)\n count0 = 0\n count1 = 1\n for i in range(len(b) - 1):\n if b[i] == '1':\n if b[i + 1] == '1':\n return False\n return True", "def issparse(n):\n if n == 1:\n return True\n global prev\n while n > 0:\n prev = n & 1\n n = n >> 1\n curr = n & 1\n if prev == curr and prev == 1:\n return False\n prev = curr\n return True", "def issparse(n):\n t = bin(n)[2:]\n k = t.count('11')\n if k == 0:\n return 1\n else:\n return 0", "def issparse(n):\n p = 0\n while n > 0:\n if n & 1 == 1 and p == 1:\n return 0\n else:\n p = n & 1\n n = n >> 1\n return 1", "def issparse(n):\n flag = False\n while n:\n if n & 1:\n if flag:\n return False\n flag = True\n else:\n flag = False\n n >>= 1\n return True", "def issparse(n):\n if n & n >> 1 != 0:\n return 0\n else:\n return 1", "def issparse(n):\n count = 0\n while n > 0 and count < 2:\n if n & 1 == 1:\n count = count + 1\n else:\n count = 0\n n = n >> 1\n if count >= 2:\n return False\n return True", "def issparse(n):\n r1 = n % 2\n n = n // 2\n while n > 0:\n r2 = n % 2\n if r1 and r2:\n return 0\n r1 = r2\n n = n // 2\n return 1", "def issparse(n):\n bi = bin(n)[2:]\n p = bi.split('0')\n for i in p:\n if len(i) >= 2:\n return False\n return True", "def issparse(n):\n b = str(bin(n))[2:]\n for i in range(len(b)):\n if i == len(b) - 1:\n return 1\n if b[i] == '1':\n if b[i + 1] == '1':\n return 0\n return 1", "def issparse(N):\n Temp = bin(N)[2:]\n ctr = 0\n Ans = 0\n for i in Temp:\n if i == '1':\n ctr += 1\n else:\n Ans = max(Ans, ctr)\n ctr = 0\n Ans = max(ctr, Ans)\n if Ans <= 1:\n return 1\n else:\n return 0", "def issparse(n):\n s = str(bin(n))\n if '11' in s:\n return 0\n else:\n return 1", "def issparse(n):\n x = bin(n)\n if '11' in x:\n return 0\n else:\n return 1", "def issparse(n):\n bits = bin(n)\n if n & n << 1:\n return 0\n else:\n return 1", "def issparse(n):\n binary = bin(n)[2:]\n for i in range(len(binary) - 1):\n if binary[i:i + 2] == '11':\n return False\n return True", "def issparse(n):\n c = str(bin(n)[2:])\n if '11' in c:\n return 0\n return 1", "def issparse(n):\n n = bin(n)[2:]\n arr = list(n)\n if len(arr) < 2:\n return 1\n elif len(arr) == 2:\n if arr[0] != arr[1]:\n return 1\n else:\n return 0\n for i in range(1, len(arr)):\n if arr[i] == '1' and arr[i - 1] == '1':\n return 0\n return 1", "def issparse(n):\n p = bin(n).replace('0b', '')\n for i in range(len(p) - 1):\n if p[i] == p[i + 1] and p[i] == '1':\n return 0\n return 1"], "starter_code": "def issparse(n):\n", "input_output": {"inputs": ["N = 2", "N = 3"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/number-is-sparse-or-not-1587115620/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1).", "entry_point": "issparse", "task_id": "TACO_lite/317", "example": [[[2], [3]], ["1", "0"]]} +{"requirement": "You will be given an array of non-negative integers and positive integer bin width. \n\nYour task is to create the Histogram method that will return histogram data corresponding to the input array. The histogram data is an array that stores under index i the count of numbers that belong to bin i. The first bin always starts with zero. \n\nOn empty input you should return empty output.\n\nExamples:\n\nFor input data [1, 1, 0, 1, 3, 2, 6] and binWidth=1 the result will be [1, 3, 1, 1, 0, 0, 1] as the data contains single element \"0\", 3 elements \"1\" etc.\nFor the same data and binWidth=2 the result will be [4, 2, 0, 1]\nFor input data [7] and binWidth=1 the result will be [0, 0, 0, 0, 0, 0, 0, 1]", "solutions": ["def histogram(lst, w):\n lst = [n // w for n in lst]\n m = max(lst, default=-1) + 1\n return [lst.count(n) for n in range(m)]", "def histogram(v, w):\n return [sum((j in range(i, w + i) for j in v)) for i in range(0, max(v) + 1, w)] if v else []", "def histogram(values, bin_width):\n return [sum([values.count(i + j) for i in range(bin_width)]) for j in range(max(values) + 1) if j % bin_width == 0] if values else []", "def histogram(a, n):\n r = [0] * (max(a, default=-1) // n + 1)\n for x in a:\n r[x // n] += 1\n return r", "def histogram(values, bin_width):\n k = []\n end = max(values) if values else -1\n bin = [i for i in range(bin_width, end + bin_width + 1, bin_width)]\n for i in bin:\n count = 0\n for val in values:\n if i - bin_width <= val < i:\n count += 1\n k += [count]\n return k", "from collections import Counter\n\ndef histogram(values, bin_width):\n count = Counter(values)\n return [sum((count[i + x] for x in range(bin_width))) for i in range(0, max(count) + 1, bin_width)] if count else []", "import math\n\ndef histogram(values, bin_width):\n if values == []:\n return []\n hist = [0] * math.ceil((max(values) + 1) / bin_width)\n for v in values:\n hist[math.floor(v / bin_width)] += 1\n return hist", "from itertools import groupby\n\ndef histogram(values, bin_width):\n c = {k: len(list(g)) for (k, g) in groupby(sorted(values), key=lambda x: x // bin_width)}\n return [c.get(i, 0) for i in range(max(c) + 1)] if c else []", "def histogram(values, bin_width):\n if len(values) == 0:\n return []\n list = [values.count(digit) for digit in range(0, max(values) + 1)]\n return [sum(list[digit:digit + bin_width]) for digit in range(0, len(list), bin_width)]"], "starter_code": "def histogram(values, bin_width):\n", "input_output": {"fn_name": "histogram", "inputs": [[[1, 1, 0, 1, 3, 2, 6], 1], [[1, 1, 0, 1, 3, 2, 6], 2], [[], 1], [[8], 1]], "outputs": [[[1, 3, 1, 1, 0, 0, 1]], [[4, 2, 0, 1]], [[]], [[0, 0, 0, 0, 0, 0, 0, 0, 1]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Algorithms", "Data Science"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5704bf9b38428f1446000a9d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "histogram", "task_id": "TACO_lite/227", "example": [[[[1, 1, 0, 1, 3, 2, 6], 1], [[1, 1, 0, 1, 3, 2, 6], 2], [[7], 1]], ["[1, 3, 1, 1, 0, 0, 1]", "[4, 2, 0, 1]", "[0, 0, 0, 0, 0, 0, 0, 1]"]]} +{"requirement": "Given an array containing only integers, add all the elements and return the binary equivalent of that sum.\n\nIf the array contains any non-integer element (e.g. an object, a float, a string and so on), return false.\n\n**Note:** The sum of an empty array is zero.\n\n```python\narr2bin([1,2]) == '11'\narr2bin([1,2,'a']) == False\n```", "solutions": ["def arr2bin(arr):\n for x in arr:\n if type(x) != int:\n return False\n return '{0:b}'.format(sum(arr))", "def arr2bin(arr):\n return all((type(n) == int for n in arr)) and format(sum(arr), 'b')", "def arr2bin(arr):\n s = 0\n for x in arr:\n if type(x) is int:\n s += x\n else:\n return False\n return '{:b}'.format(s)", "def arr2bin(arr):\n if all(map(lambda x: type(x) == int, arr)):\n return '{0:b}'.format(sum(arr))\n return False", "def arr2bin(arr):\n if any((type(a) is not int for a in arr)):\n return False\n return bin(sum(arr))[2:]", "def arr2bin(arr):\n return False if any((type(e) != int for e in arr)) else bin(sum(arr))[2:]", "def arr2bin(arr):\n if any((type(x) != int for x in arr)):\n return False\n return bin(sum(arr))[2:]", "def arr2bin(arr):\n return all((isinstance(n, int) and (not isinstance(n, bool)) for n in arr)) and bin(sum((n for n in arr)))[2:]", "def arr2bin(arr):\n if all((type(x) is int for x in arr)):\n return '{:b}'.format(sum(arr))\n else:\n return False", "def arr2bin(arr):\n try:\n return bin(sum((int(x) if not isinstance(x, bool) else None for x in arr)))[2:]\n except:\n return False"], "starter_code": "def arr2bin(arr):\n", "input_output": {"fn_name": "arr2bin", "inputs": [[[1, 2]], [[1, 2, 3, 4, 5]], [[1, 10, 100, 1000]], [[1, 2, -1, -2]], [[1, 2, -1, -2, 1]], [[]]], "outputs": [["11"], ["1111"], ["10001010111"], ["0"], ["1"], ["0"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/559576d984d6962f8c00003c", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "arr2bin", "task_id": "TACO_lite/268", "example": [[[[1, 2]], [[1, 2, "a"]]], ["11", "False"]]} +{"requirement": "For an integer N find the number of trailing zeroes in N!.\nExample 1:\nInput:\nN = 5\nOutput:\n1\nExplanation:\n5! = 120 so the number of trailing zero is 1.\nExample 2:\nInput:\nN = 4\nOutput:\n0\nExplanation:\n4! = 24 so the number of trailing zero is 0.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function trailingZeroes() which take an integer N as an input parameter and returns the count of trailing zeroes in the N!.\nExpected Time Complexity: O(logN)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 10^{9}", "solutions": ["import re\nimport math\n\ndef trailingzeroes(N):\n triling_zero = 0\n while N:\n triling_zero += N // 5\n N = N // 5\n return triling_zero", "def trailingzeroes(N):\n res = 0\n while N >= 5:\n N //= 5\n res += N\n return res", "def trailingzeroes(N):\n if N < -1:\n return -1\n count = 0\n while N >= 5:\n N //= 5\n count += N\n return count", "def trailingzeroes(N):\n r = 0\n n = 5\n while n <= N:\n r += int(N / n)\n n = n * 5\n return r", "def trailingzeroes(N):\n result = 0\n x = N\n while x > 4:\n x = x // 5\n result += x\n return result", "def trailingzeroes(N):\n count = 0\n while N >= 5:\n count = count + N // 5\n N //= 5\n return count", "def trailingzeroes(n):\n if n < 0:\n return -1\n if n <= 4:\n return 0\n count = 0\n while n >= 5:\n n = n // 5\n count += n\n return count", "def trailingzeroes(N):\n count = 0\n i = 5\n while N / i >= 1:\n count += int(N / i)\n i *= 5\n return int(count)", "import math\n\ndef trailingzeroes(N):\n x = 5\n count = 0\n while x <= N:\n count += N // x\n x *= 5\n return count", "def trailingzeroes(N):\n c = 0\n n5 = N - N % 5\n p = 1\n while n5 / 5 ** p >= 1:\n c += int(n5 / 5 ** p)\n p += 1\n return c", "import math\n\ndef trailingzeroes(N):\n zeros = 0\n i = 5\n while i <= N:\n zeros += N // i\n i *= 5\n return zeros", "from math import factorial\n\ndef trailingzeroes(N):\n s = 0\n while N >= 5:\n N //= 5\n s += N\n return s", "def trailingzeroes(N):\n tz = 0\n while N != 0:\n tz += int(N / 5)\n N = int(N / 5)\n return tz", "def trailingzeroes(N):\n power = 5\n c = 0\n while N >= power:\n c += N // power\n power *= 5\n return c", "def trailingzeroes(N):\n ans = 0\n i = 5\n while i <= N:\n ans += N // i\n i *= 5\n return ans", "def trailingzeroes(N):\n temp = 5\n ans = 0\n while temp <= N:\n ans += N // temp\n temp *= 5\n return ans", "import math\n\ndef trailingzeroes(N):\n res = 0\n i = 1\n while math.pow(5, i) <= N:\n res += N // math.pow(5, i)\n i += 1\n return int(res)", "import math\n\ndef trailingzeroes(n):\n count = 0\n while n >= 5:\n n //= 5\n count += n\n return count", "def trailingzeroes(N):\n if N < 0:\n return -1\n if N <= 4:\n return 0\n ct = 0\n while N >= 5:\n N = N // 5\n ct += N\n return ct", "from math import factorial\n\ndef trailingzeroes(n):\n if n < 5:\n return 0\n return n // 5 + self.trailingzeroes(n // 5)", "def trailingzeroes(n):\n if n < 5:\n return 0\n return n // 5 + self.trailingzeroes(n // 5)", "def trailingzeroes(N):\n m = N\n i = 5\n t = 0\n while m // i >= 1:\n t += m // i\n i *= 5\n return t", "def trailingzeroes(n):\n ans = 0\n while n >= 5:\n n //= 5\n ans += n\n return ans", "def trailingzeroes(N):\n c = 0\n i = 5\n while N // i >= 1:\n c += N // i\n i *= 5\n return c", "def trailingzeroes(N):\n x = 5\n c = 0\n while x <= N:\n c += N // x\n x *= 5\n return c", "import math\n\ndef trailingzeroes(N):\n ans = 0\n for i in range(int(math.log(N))):\n ans += N // 5 ** (i + 1)\n return ans", "def trailingzeroes(N):\n result = 0\n while N >= 5:\n N //= 5\n result += N\n return result", "def trailingzeroes(N):\n sum = 0\n i = 5\n while i <= N:\n sum += N // i\n i *= 5\n return sum", "def trailingzeroes(N):\n n = N\n res = 0\n i = 5\n while i <= N:\n res += N // i\n i *= 5\n return res", "def trailingzeroes(N):\n five = 0\n i = 5\n while i <= N:\n five += N // i\n i *= 5\n return five", "def trailingzeroes(N):\n total = 0\n i = 5\n while i <= N:\n total += N // i\n i *= 5\n return total", "def trailingzeroes(n):\n count_zero = 0\n i = 5\n while n / i > 0:\n count_zero += n // i\n i = i * 5\n return count_zero", "def trailingzeroes(N):\n ans = 0\n while True:\n a = N // 5\n ans += a\n N = a\n if N <= 0:\n break\n return ans", "val = Solution()\nval.trailingzeroes(5)\n\ndef trailingzeroes(N):\n count = 0\n i = 5\n while i <= N:\n count += N // i\n i *= 5\n return count", "def trailingzeroes(N):\n x = 5\n cnt = 0\n while x <= N:\n cnt += N // x\n x *= 5\n return cnt", "def trailingzeroes(n):\n c = 0\n i = 5\n while n / i >= 1:\n c = c + int(n / i)\n i = i * 5\n return c", "def trailingzeroes(n):\n ans = 0\n i = 5\n while n // i >= 1:\n count = int(n / i)\n i *= 5\n ans += count\n return ans", "def trailingzeroes(N):\n if N < 5:\n return 0\n else:\n k = 0\n while N > 1:\n N = N // 5\n k = k + N\n return k", "def trailingzeroes(N):\n k = N\n c5 = 0\n while k > 0:\n count = k // 5\n k = count\n c5 += count\n k = N\n c2 = 0\n while k > 0:\n count = k // 2\n k = count\n c2 += count\n return c5 if c5 < c2 else c2", "def trailingzeroes(n):\n c = 0\n while n >= 5:\n n //= 5\n c += n\n return c"], "starter_code": "def trailingzeroes(N):\n", "input_output": {"inputs": ["N = 5", "N = 4"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/trailing-zeroes-in-factorial5134/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(logN)", "entry_point": "trailingzeroes", "task_id": "TACO_lite/269", "example": [[[5], [4]], ["1", "0"]]} +{"requirement": "Given an array A[] of size N, find the longest subsequence such that difference between adjacent elements is one.\nExample 1:\nInput: N = 7\nA[] = {10, 9, 4, 5, 4, 8, 6}\nOutput: 3\nExplaination: The three possible subsequences \n{10, 9, 8} , {4, 5, 4} and {4, 5, 6}.\nExample 2:\nInput: N = 5\nA[] = {1, 2, 3, 4, 5}\nOutput: 5\nExplaination: All the elements can be \nincluded in the subsequence.\nYour Task:\nYou do not need to read input. Your task is to complete the function longestSubseq() which takes N and A[] as input parameters and returns the length of the longest such subsequence.\nExpected Time Complexity: O(N^{2})\nExpected Auxiliary Space: O(N)\nConstraints:\n1 ≤ N ≤ 10^{3}\n1 ≤ A[i] ≤ 10^{3}", "solutions": ["def longestsubsequence(n, a):\n L = [1 for i in range(n)]\n for i in range(n):\n for j in range(0, i):\n if a[i] == a[j] - 1 or a[i] == a[j] + 1:\n L[i] = max(L[i], L[j] + 1)\n mx = L[0]\n for i in range(0, n):\n mx = max(mx, L[i])\n return mx", "def longestsubsequence(N, A):\n if N == 1:\n return 1\n dp = [1] * N\n for i in range(N - 1, -1, -1):\n for j in range(i + 1, N):\n if abs(A[i] - A[j]) == 1:\n dp[i] = max(dp[i], 1 + dp[j])\n return max(dp)", "def dp_sol(N, A):\n dp = [1] * (N + 1)\n dp[0] = 0\n for i in range(2, N + 1):\n for j in range(1, i):\n if A[j - 1] - A[i - 1] == 1 or A[j - 1] - A[i - 1] == -1:\n dp[i] = max(dp[i], 1 + dp[j])\n return max(dp)\n\ndef longestsubsequence(N, A):\n return self.dp_sol(N, A)", "def longestsubsequence(N, A):\n stateMap = [1 for _ in range(N)]\n for ind in range(1, N):\n maxVal = 1\n for lInd in range(ind):\n if A[ind] == A[lInd] - 1 or A[ind] == A[lInd] + 1:\n maxVal = max(maxVal, stateMap[lInd] + 1)\n stateMap[ind] = maxVal\n return max(stateMap)", "def longestsubsequence(n, A):\n t = [1] * n\n for i in range(1, n):\n for j in range(i):\n if abs(A[i] - A[j]) == 1 and t[i] < t[j] + 1:\n t[i] = t[j] + 1\n return max(t)", "def longestsubsequence(n, arr):\n dp = [1 for i in range(n)]\n for i in range(n):\n for j in range(i):\n if arr[i] == arr[j] + 1 or arr[i] == arr[j] - 1:\n dp[i] = max(dp[i], dp[j] + 1)\n result = 1\n for i in range(n):\n if result < dp[i]:\n result = dp[i]\n return result", "def longestsubsequence(n, a):\n dp = [1] * n\n m = 1\n for i in range(1, n):\n for j in range(i):\n if a[i] - a[j] == 1 or a[i] - a[j] == -1:\n dp[i] = max(dp[i], dp[j] + 1)\n m = max(m, dp[i])\n return m", "def longestsubsequence(N, A):\n if N == 1:\n return 1\n dp = [0 for _ in range(N)]\n res = 1\n for pos in range(N):\n dp[pos] = 1\n for idx in range(pos):\n if A[pos] == A[idx] + 1 or A[pos] == A[idx] - 1:\n dp[pos] = max(dp[pos], dp[idx] + 1)\n res = max(res, dp[pos])\n return res", "def longestsubsequence(n, arr):\n dp = [1] * n\n for ind in range(n):\n for prev in range(ind):\n if abs(arr[prev] - arr[ind]) == 1:\n dp[ind] = max(dp[ind], 1 + dp[prev])\n return max(dp)", "def longestsubsequence(N, A):\n dp = {}\n\n def rec(idx, prev, count):\n if idx < 0:\n return count\n if (idx, prev) in dp:\n return dp[idx, prev]\n pick = 0\n if prev == -1 or abs(A[idx] - A[prev]) == 1:\n pick = rec(idx - 1, idx, count + 1)\n npick = rec(idx - 1, prev, count)\n dp[idx, prev] = max(pick, npick)\n return dp[idx, prev]\n dp = [1] * N\n for i in range(N):\n for j in range(i):\n if abs(A[i] - A[j]) == 1:\n dp[i] = max(dp[i], dp[j] + 1)\n return max(dp)", "def solve(A, N):\n arr = [1] * N\n for i in range(1, N):\n for j in range(0, i):\n if abs(A[i] - A[j]) == 1:\n arr[i] = max(arr[i], arr[j] + 1)\n return max(arr)\n\ndef longestsubsequence(N, A):\n return solve(A, N)", "def fun(idx, arr, n, prev, dp):\n if idx == n:\n return 0\n if dp[idx][prev + 1] != -1:\n return dp[idx][prev + 1]\n np = 0 + self.fun(idx + 1, arr, n, prev, dp)\n p = 0\n if prev == -1 or abs(arr[idx] - arr[prev]) == 1:\n p = 1 + self.fun(idx + 1, arr, n, idx, dp)\n dp[idx][prev + 1] = max(p, np)\n return dp[idx][prev + 1]\n\ndef longestsubsequence(n, arr):\n dp = [1 for i in range(N + 1)]\n dp[0] = 1\n for i in range(1, N):\n for j in range(i):\n if abs(A[j] - A[i]) == 1:\n dp[i] = max(dp[i], dp[j] + 1)\n mx = -999\n for i in range(N):\n mx = max(dp[i], mx)\n return mx", "def longestsubsequence(n, a):\n res = [1] * n\n for i in range(1, n):\n for j in range(i):\n if abs(a[i] - a[j]) == 1:\n res[i] = max(res[i], 1 + res[j])\n return max(res)", "def longestsubsequence(N, A):\n h = {}\n ans = 0\n for i in range(N):\n l = 0\n if A[i] - 1 in h:\n l = h[A[i] - 1]\n if A[i] + 1 in h:\n l = max(l, h[A[i] + 1])\n h[A[i]] = l + 1\n ans = max(ans, h[A[i]])\n return ans", "def longestsubsequence(N, A):\n DP = [0] * N\n DP[0] = 1\n for i in range(1, N):\n temp = [0]\n for j in range(i):\n if abs(A[j] - A[i]) == 1:\n temp.append(DP[j])\n DP[i] = max(temp) + 1\n return max(DP)", "def longestsubsequence(N, A):\n dict = {}\n ans = 1\n for i in range(N):\n len = 1\n if A[i] - 1 in dict:\n len = max(len, dict[A[i] - 1] + 1)\n if A[i] + 1 in dict:\n len = max(len, dict[A[i] + 1] + 1)\n dict[A[i]] = len\n ans = max(ans, len)\n return ans", "def longestsubsequence(N, A):\n b = [0 for hm in range(N)]\n b[0] = 1\n for hm in range(1, N):\n for gm in range(hm):\n if abs(A[hm] - A[gm]) == 1:\n b[hm] = max(b[hm], b[gm] + 1)\n b[hm] = max(b[hm], 1)\n return max(b)", "from collections import defaultdict\n\ndef longestsubsequence(n, a):\n dp = defaultdict(lambda : 0)\n dp[a[0]] = 1\n c = 1\n for i in range(1, n):\n temp = 1\n if a[i] + 1 in dp or a[i] - 1 in dp:\n temp = 1 + max(dp[a[i] - 1], dp[a[i] + 1])\n c = max(c, temp)\n dp[a[i]] = temp\n return c", "def longestsubsequence(n, arr):\n d = {}\n d[arr[0]] = 1\n dp = [1] * n\n for i in range(1, n):\n ans1 = d.get(arr[i] - 1, 0)\n ans2 = d.get(arr[i] + 1, 0)\n if ans1 or ans2:\n dp[i] = 1 + max(ans1, ans2)\n d[arr[i]] = dp[i]\n return max(dp)", "def longestsubsequence(n, arr):\n dp = [1] * n\n for i in range(1, n):\n for j in range(0, i):\n if abs(arr[i] - arr[j]) == 1:\n dp[i] = max(dp[i], dp[j] + 1)\n return max(dp)", "def longestsubsequence(N, a):\n LIS = [1] * N\n for i in range(N - 2, -1, -1):\n for j in range(i + 1, N):\n if abs(a[i] - a[j]) == 1:\n LIS[i] = max(LIS[i], 1 + LIS[j])\n return max(LIS)", "def longestsubsequence(N, A):\n n = N\n res = [1 for each in range(n + 1)]\n for i in range(n - 1, -1, -1):\n for j in range(i, n):\n if abs(A[j] - A[i]) == 1:\n res[i] = max(res[i], 1 + res[j])\n return max(res)", "def longestsubsequence(N, A):\n m = 0\n t = [1 for _ in range(N)]\n for i in range(N):\n for prev in range(i):\n if abs(A[i] - A[prev]) == 1:\n t[i] = max(t[i], 1 + t[prev])\n m = max(m, t[i])\n return m", "def longestsubsequence(N, A):\n dp = [1] * N\n maxi = float('-inf')\n for ind in range(N):\n for prev_ind in range(ind):\n if abs(A[prev_ind] - A[ind]) == 1 and 1 + dp[prev_ind] > dp[ind]:\n dp[ind] = 1 + dp[prev_ind]\n maxi = max(maxi, dp[ind])\n return maxi", "from collections import defaultdict\n\ndef longestsubsequence(N, A):\n d = defaultdict(lambda : 0)\n for item in A:\n d[item] = max(d[item], max(d[item - 1], d[item + 1]) + 1)\n return max(d.values())", "def longestsubsequence_ending_at_i(N, A, index, dp_arr):\n if dp_arr[index] != -1:\n return dp_arr[index]\n maximum = 1\n for i in range(index):\n if A[i] == A[index] - 1 or A[i] == A[index] + 1:\n maximum = max(maximum, 1 + self.longestsubsequence_ending_at_i(N, A, i, dp_arr))\n dp_arr[index] = maximum\n return maximum\n\ndef longestsubsequence(N, A):\n dp_arr = [-1 for i in range(N)]\n max_subsequence = -1\n for i in range(N):\n max_subsequence = max(self.longestsubsequence_ending_at_i(N, A, i, dp_arr), max_subsequence)\n return max_subsequence", "def longestsubsequence(N, A):\n mapp = {}\n ma = 1\n for i in range(0, N):\n k = A[i]\n val = 0\n if k - 1 in mapp:\n val = mapp[k - 1]\n if k + 1 in mapp and mapp[k + 1] > val:\n val = mapp[k + 1]\n mapp[A[i]] = val + 1\n ma = max(ma, val + 1)\n return ma", "def longestsubsequence(N, A):\n dp = [1 for _ in range(N)]\n longestsubsequencesNumber = 1\n for i in range(len(A) - 2, -1, -1):\n for j in range(i + 1, len(A)):\n if abs(A[j] - A[i]) == 1:\n dp[i] = max(dp[i], 1 + dp[j])\n longestsubsequencesNumber = max(longestsubsequencesNumber, dp[i])\n return longestsubsequencesNumber", "def longestsubsequence(N, arr):\n dp = [1] * N\n for i in range(1, N):\n for j in range(0, i):\n if arr[i] == arr[j] + 1 or arr[j] - 1 == arr[i]:\n dp[i] = max(dp[i], dp[j] + 1)\n return max(dp)", "from collections import defaultdict\n\ndef longestsubsequence(n, A):\n d = defaultdict(int)\n ans = 0\n for i in range(n):\n temp = 0\n if A[i] - 1 in d:\n temp = d[A[i] - 1]\n if A[i] + 1 in d:\n temp = max(temp, d[A[i] + 1])\n d[A[i]] = 1 + temp\n ans = max(ans, temp + 1)\n return ans", "def longestsubsequence(N, A):\n temp = [0] * len(A)\n for i in range(len(A)):\n sub = [temp[k] for k in range(i) if A[i] == A[k] - 1 or A[i] - 1 == A[k]]\n temp[i] = 1 + max(sub, default=0)\n return max(temp, default=0)", "def longestsubsequence(n, A):\n arr = [1 for i in range(n)]\n for i in range(1, n):\n for j in range(0, i):\n if A[i] - A[j] == 1 or A[i] - A[j] == -1:\n arr[i] = max(arr[i], arr[j] + 1)\n return max(arr)", "def solve(a, cur, prev, dp):\n if cur == len(a):\n return 0\n if dp[prev + 1][cur] != -1:\n return dp[prev + 1][cur]\n inc = 0\n if prev == -1 or abs(a[prev] - a[cur]) == 1:\n inc = 1 + Solution.solve(a, cur + 1, cur, dp)\n exc = Solution.solve(a, cur + 1, prev, dp)\n dp[prev + 1][cur] = max(inc, exc)\n return dp[prev + 1][cur]\n\ndef longestsubsequence(n, arr):\n dp = [1 for _ in range(n)]\n maxi = 1\n for i in range(n):\n for j in range(i):\n if abs(arr[i] - arr[j]) == 1:\n dp[i] = max(dp[i], dp[j] + 1)\n for i in range(n):\n maxi = max(maxi, dp[i])\n return maxi", "def longestsubsequence(N, arr):\n dp = [1 for x in range(N)]\n maxi = 0\n for i in range(N):\n for prev in range(i):\n if abs(arr[i] - arr[prev]) == 1 and dp[i] < 1 + dp[prev]:\n dp[i] = 1 + dp[prev]\n maxi = max(maxi, dp[i])\n return maxi", "from collections import defaultdict\n\ndef longestsubsequence(n, arr):\n ans = 0\n hmap = defaultdict(int)\n for num in arr:\n hmap[num] = max(hmap[num - 1], hmap[num + 1]) + 1\n ans = max(ans, hmap[num])\n return ans", "def __init__():\n self.ans = 0\n self.dp = {}\n\ndef longestsubsequence(N, A):\n if len(A) == 1:\n return 1\n\n def solve(array, i, j, sum):\n if j >= len(array) or i >= len(array):\n self.ans = max(self.ans, sum)\n return sum\n for k in range(j, len(array)):\n if abs(A[k] - A[i]) == 1:\n if (i, k) not in self.dp:\n b = sum + 1\n ss = solve(array, k, k + 1, b)\n self.dp[i, k] = b\n else:\n self.ans = max(self.ans, self.dp[i, k])\n self.ans = max(self.ans, sum)\n return sum\n for l in range(len(A) - 1):\n s = 1\n solve(A, l, l + 1, s)\n return self.ans", "import collections\n\ndef longestsubsequence(N, A):\n dp = collections.defaultdict()\n for number in A:\n if number + 1 in dp and number - 1 in dp:\n if dp[number + 1] > dp[number - 1]:\n dp[number] = dp[number + 1] + 1\n else:\n dp[number] = dp[number - 1] + 1\n elif number + 1 in dp:\n dp[number] = dp[number + 1] + 1\n elif number - 1 in dp:\n dp[number] = dp[number - 1] + 1\n else:\n dp[number] = 1\n return max(dp.items(), key=lambda x: x[1])[1]", "def longestsubsequence(N, A):\n res = []\n for i in range(N):\n m = 1\n for j in range(i):\n if abs(A[j] - A[i]) == 1 and res[j] >= m:\n m = res[j] + 1\n res.append(m)\n return max(res)", "def longestsubsequence(N, A):\n t = [0 for i in range(0, N + 2)]\n ans = 0\n for i in range(0, N):\n temp = 0\n for j in range(0, i):\n if abs(A[j] - A[i]) == 1:\n if t[j] > temp:\n temp = t[j]\n t[i] = 1 + temp\n if t[i] > ans:\n ans = t[i]\n return ans", "def longestsubsequence(n, a):\n maxx = 1\n dp = [1 for i in range(n)]\n for i in range(1, n):\n for j in range(i):\n if abs(a[i] - a[j]) == 1 and dp[i] < dp[j] + 1:\n dp[i] = dp[j] + 1\n maxx = max(dp[i], maxx)\n return maxx", "from collections import defaultdict\n\ndef longestsubsequence(N, A):\n d = defaultdict(lambda : 0)\n ans = 0\n for i in A:\n d[i] = 1 + max(d[i - 1], d[i + 1])\n ans = max(ans, d[i])\n return ans"], "starter_code": "def longestsubsequence(N, A):\n", "input_output": {"inputs": ["N = 7\r\nA[] = {10, 9, 4, 5, 4, 8, 6}", "N = 5\r\nA[] = {1, 2, 3, 4, 5}"], "outputs": ["3", "5"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/longest-subsequence-such-that-difference-between-adjacents-is-one4724/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N^{2})", "entry_point": "longestsubsequence", "task_id": "TACO_lite/192", "example": [[[7, [10, 9, 4, 5, 4, 8, 6]], [5, [1, 2, 3, 4, 5]]], ["3", "5"]]} +{"requirement": "Given a series of numbers 2, 10, 30, 68, 130.., Identify the pattern in the series. You are given an integer X you need to find out the X'th number in the series.\nExample 1:\nInput:\nX = 1\nOutput:\n2\nExplanation:\n2 is the first number in the series.\nExample 2:\nInput:\nX = 2\nOutput:\n10\nExplanation:\n10 is the second number in the series.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function X1Series() which takes an integer X as an input parameter and return the X'th number in the series.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ X ≤ 10^{5}", "solutions": ["def x1series(X):\n return pow(X, 3) + X", "def x1series(m):\n return m * (m * m + 1)", "def x1series(X):\n temp = 2\n xr = 3\n sums = 0\n if X == 1:\n return temp\n for i in range(2, X + 1):\n temp = temp + xr\n xr = xr + 2\n sums = temp * i\n return sums", "def x1series(X):\n return X * (X * X + 1)", "def x1series(n):\n return n ** 3 + n", "def x1series(x):\n return x ** 3 + x", "def x1series(X: int) -> int:\n return X + X ** 3", "def x1series(x):\n return x * (x * x + 1)", "import math\n\ndef x1series(X):\n return int(math.pow(X, 3)) + X", "def x1series(X):\n n = X - 1\n return n * (n * n + 3 * n + 4) + 2", "def x1series(X):\n n = 0\n n = X ** 3 + X\n return n", "def x1series(X):\n nth_term = X * (X ** 2 + 1)\n return nth_term"], "starter_code": "def x1series(X):\n", "input_output": {"inputs": ["X = 1", "X = 2"], "outputs": ["2", "10"]}, "difficulty": "EASY", "raw_tags": ["series"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/series-x14741/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "x1series", "task_id": "TACO_lite/286", "example": [[[1], [2]], ["2", "10"]]} +{"requirement": "Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.\n\nNote: You can only move either down or right at any point in time.\n\nExample:\n\n\nInput:\n[\n  [1,3,1],\n [1,5,1],\n [4,2,1]\n]\nOutput: 7\nExplanation: Because the path 1→3→1→1→1 minimizes the sum.", "solutions": ["def minpathsum(grid):\n (m, n) = (len(grid), len(grid[0]))\n dp = [0] + [float('inf')] * (n - 1)\n for i in range(m):\n dp[0] = dp[0] + grid[i][0]\n for j in range(1, n):\n dp[j] = min(dp[j], dp[j - 1]) + grid[i][j]\n return dp[-1]", "def minpathsum(grid):\n m = len(grid)\n n = len(grid[0])\n dp = [grid[0][j] for j in range(n)]\n for j in range(1, n):\n dp[j] += dp[j - 1]\n for i in range(1, m):\n for j in range(n):\n if j == 0:\n dp[j] += grid[i][j]\n else:\n dp[j] = min(grid[i][j] + dp[j - 1], grid[i][j] + dp[j])\n return dp[-1]", "def minpathsum(grid):\n M = len(grid)\n if M == 0:\n return 0\n N = len(grid[0])\n if N == 0:\n return 0\n INF = float('inf')\n mem = {}\n\n def min_path(i, j):\n if i == M - 1 and j == N - 1:\n return grid[i][j]\n if (i, j) in mem:\n return mem[i, j]\n min_sum = INF\n if i < M - 1:\n min_sum = min_path(i + 1, j)\n if j < N - 1:\n min_sum = min(min_sum, min_path(i, j + 1))\n mem[i, j] = grid[i][j] + min_sum\n return mem[i, j]\n return min_path(0, 0)", "def minpathsum(grid):\n m = len(grid) - 1\n n = len(grid[0]) - 1\n dic = dict()\n s = self.minpathsumHelper(grid, 0, 0, m, n, dic)\n return s\n\ndef minpathsumHelper(grid, i, j, m, n, dic):\n if (i, j, m, n) in dic:\n return dic[i, j, m, n]\n if i > m or j > n:\n return 0\n elif i == m:\n dic[i, j, m, n] = self.minpathsumHelper(grid, i, j + 1, m, n, dic) + grid[i][j]\n return dic[i, j, m, n]\n elif j == n:\n dic[i, j, m, n] = self.minpathsumHelper(grid, i + 1, j, m, n, dic) + grid[i][j]\n return dic[i, j, m, n]\n else:\n dic[i, j, m, n] = min(self.minpathsumHelper(grid, i + 1, j, m, n, dic), self.minpathsumHelper(grid, i, j + 1, m, n, dic)) + grid[i][j]\n return dic[i, j, m, n]", "def minpathsum(grid):\n max_row = len(grid) - 1\n max_col = len(grid[0]) - 1\n helper_grid = [[0] * len(grid[0]) for _ in range(len(grid))]\n helper_grid[max_row][max_col] = grid[max_row][max_col]\n for i in range(max_col - 1, -1, -1):\n helper_grid[max_row][i] = grid[max_row][i] + helper_grid[max_row][i + 1]\n for i in range(max_row - 1, -1, -1):\n helper_grid[i][max_col] = grid[i][max_col] + helper_grid[i + 1][max_col]\n for col in range(max_col - 1, -1, -1):\n for row in range(max_row - 1, -1, -1):\n helper_grid[row][col] = grid[row][col] + min(helper_grid[row + 1][col], helper_grid[row][col + 1])\n return helper_grid[0][0]", "def minpathsum(grid):\n if not grid:\n return 0\n row_count = len(grid)\n col_count = len(grid[0])\n for i in range(1, row_count):\n grid[i][0] += grid[i - 1][0]\n for i in range(1, col_count):\n grid[0][i] += grid[0][i - 1]\n for row in range(1, row_count):\n for col in range(1, col_count):\n grid[row][col] += min(grid[row - 1][col], grid[row][col - 1])\n return grid[-1][-1]", "def minpathsum(grid):\n if not grid:\n return 0\n (row, col) = (len(grid), len(grid[0]))\n dp = [0 for _ in range(col)]\n dp[0] = grid[0][0]\n for i in range(1, col):\n dp[i] = dp[i - 1] + grid[0][i]\n for i in range(1, row):\n for j in range(0, col):\n dp[j] = dp[j] + grid[i][j] if j == 0 else min(dp[j - 1], dp[j]) + grid[i][j]\n return dp[-1]", "def minpathsum(grid):\n if not grid:\n return 0\n row_count = len(grid)\n col_count = len(grid[0])\n dp = [[0 for _ in range(col_count)] for _ in range(row_count)]\n dp[0][0] = grid[0][0]\n if row_count == col_count and col_count == 1:\n return dp[-1][-1]\n for row in range(row_count):\n for col in range(col_count):\n if row == 0 and col >= 1:\n dp[row][col] = dp[row][col - 1] + grid[row][col]\n elif col == 0 and row >= 1:\n dp[row][col] = dp[row - 1][col] + grid[row][col]\n else:\n dp[row][col] = min(dp[row - 1][col], dp[row][col - 1]) + grid[row][col]\n return dp[-1][-1]", "def minpathsum(grid):\n m = len(grid)\n n = len(grid[0])\n s = [[0 for j in range(n)] for i in range(m)]\n s[0][0] = grid[0][0]\n for i in range(1, m):\n s[i][0] = s[i - 1][0] + grid[i][0]\n for j in range(1, n):\n s[0][j] = s[0][j - 1] + grid[0][j]\n for i in range(1, m):\n for j in range(1, n):\n s[i][j] = min(s[i - 1][j] + grid[i][j], s[i][j - 1] + grid[i][j])\n return s[m - 1][n - 1]", "def minpathsum(grid):\n height = len(grid)\n width = len(grid[0])\n step_num = height + width - 2\n for step in range(1, step_num + 1):\n for row in range(height):\n col = step - row\n if 0 <= row < height and 0 <= col < width:\n if not row:\n grid[row][col] += grid[row][col - 1]\n elif not col:\n grid[row][col] += grid[row - 1][col]\n else:\n grid[row][col] += min(grid[row][col - 1], grid[row - 1][col])\n return grid[-1][-1]", "def minpathsum(grid):\n col = len(grid[0])\n row = len(grid)\n minSum = [[0 for x in range(col)] for y in range(row)]\n for i in range(row):\n for j in range(col):\n add = 0\n if i - 1 >= 0 and j - 1 >= 0:\n add = min(minSum[i - 1][j], minSum[i][j - 1])\n elif i - 1 >= 0:\n add = minSum[i - 1][j]\n elif j - 1 >= 0:\n add = minSum[i][j - 1]\n minSum[i][j] = grid[i][j] + add\n return minSum[-1][-1]", "def minpathsum(grid):\n m = len(grid)\n n = len(grid[0])\n if m == 0 or n == 0:\n return 0\n memory = [[0 for _ in range(n)] for _ in range(m)]\n\n def minSum(grid, x, y, n, m):\n if x == 0 and y == 0:\n return grid[0][0]\n if x < 0 or y < 0:\n return float('inf')\n if memory[y][x] > 0:\n return memory[y][x]\n memory[y][x] = grid[y][x] + min(minSum(grid, x - 1, y, n, m), minSum(grid, x, y - 1, n, m))\n return memory[y][x]\n return minSum(grid, n - 1, m - 1, n, m)"], "starter_code": "def minpathsum(grid: List[List[int]]) -> int:\n", "input_output": {"fn_name": "minPathSum", "inputs": [[[[1, 3, 1], [1, 5, 1], [4, 2, 1]]], [[[1, 2, 3], [4, 5, 6]]]], "outputs": [7, 12]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Dynamic Programming", "Matrix"], "name": null, "source": "leetcode", "tags": ["Matrices", "Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/minimum-path-sum/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "minpathsum", "task_id": "TACO_lite/297", "example": [[[[[1, 3, 1], [1, 5, 1], [4, 2, 1]]]], ["7"]]} +{"requirement": "Given an integer N, find the absolute difference between sum of the squares of first N natural numbers and square of sum of first N natural numbers.\nExample 1:\nInput: N = 2\nOutput: 4 \nExplanation: abs|(1^{2 }+ 2^{2}) - (1 + 2)^{2}| = 4.\nExample 2:\nInput: N = 3\nOutput: 22\nExplanation: abs|(1^{2 }+ 2^{2} + 3^{2}) - (1 + 2 + 3)^{2}| = 22.\nYour Task: \nYou dont need to read input or print anything. Complete the function squaresDiff() which takes N as input parameter and returns the absolute difference.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1<= N <=10^{3}", "solutions": ["def squaresdiff(N):\n s = 0\n s1 = 0\n for i in range(1, N + 1):\n s += i ** 2\n s1 += i\n return abs(s - s1 ** 2)", "def squaresdiff(N):\n a = int(N * (N + 1) * (2 * N + 1) / 6)\n b = int(N * (N + 1) / 2)\n c = a - b ** 2\n d = abs(c)\n return d", "def squaresdiff(N):\n a = N * (N + 1) // 2\n x = a * a\n l = []\n for i in range(1, N + 1):\n l.append(i * i)\n y = sum(l)\n return abs(x - y)", "def squaresdiff(n):\n return abs(int(n * (n + 1) * (2 * n + 1) / 6 - n * (n + 1) / 2 * (n * (n + 1) / 2)))", "def squaresdiff(N):\n a = 0\n for i in range(1, N + 1):\n a = a + i * i\n b = N * (N + 1) // 2\n c = b * b\n return abs(a - c)", "def squaresdiff(n):\n s1 = (n * (n + 1) // 2) ** 2\n s2 = n * (n + 1) * (2 * n + 1) // 6\n return abs(s2 - s1)", "def squaresdiff(N):\n l = 0\n r = 0\n for i in range(1, N + 1):\n l += i ** 2\n r += i\n return abs(l - r ** 2)", "def squaresdiff(N):\n t = int(N * (N + 1) * (2 * N + 1) / 6)\n m = int(N * (N + 1) / 2)\n n = t - m ** 2\n return abs(n)", "def squaresdiff(n):\n x = n * (n + 1) * (2 * n + 1) // 6\n y = n * (n + 1) // 2\n return abs(x - y ** 2)", "def squaresdiff(N):\n k = 0\n j = 0\n for i in range(N):\n k += (i + 1) ** 2\n j += i + 1\n if k > j ** 2:\n return k - j ** 2\n else:\n return j ** 2 - k", "def squaresdiff(N):\n c = 0\n d = 0\n for i in range(1, N + 1, 1):\n c += i ** 2\n d += i\n return abs(c - d ** 2)", "def squaresdiff(n):\n s = 0\n l = 0\n for i in range(1, n + 1):\n l += i\n s += i * i\n return abs(s - l * l)", "def squaresdiff(n):\n s = (1 - n) * (3 * n + 2) * n * (n + 1) // 12\n q = abs(s)\n return q", "def squaresdiff(N):\n ans1 = 0\n ans2 = 0\n for i in range(1, N + 1):\n ans1 = ans1 + i ** 2\n ans2 = ans2 + i\n return abs(ans1 - ans2 ** 2)", "def squaresdiff(N):\n square_num = int(N * (N + 1) * (2 * N + 1) / 6)\n num1 = int(N * (N + 1) / 2)\n num1 = num1 ** 2\n return abs(square_num - num1)", "def squaresdiff(N):\n square_num = 0\n num1 = 0\n for i in range(1, N + 1):\n square_num = square_num + i ** 2\n num1 = num1 + i\n num1 = num1 ** 2\n return abs(square_num - num1)", "from math import *\n\ndef squaresdiff(N):\n a = int(N * (N + 1) * (2 * N + 1) / 6)\n b = int(N * (N + 1) / 2) ** 2\n return abs(a - b)", "def squaresdiff(n):\n sum = 0\n sum1 = 0\n for v in range(n + 1):\n sq = v ** 2\n sum += sq\n for y in range(n + 1):\n sum1 += y\n pr = sum1 ** 2\n a = abs(sum - pr)\n return a", "def squaresdiff(N):\n (v1, v2) = (0, 0)\n for x in range(1, N + 1):\n v1 += x ** 2\n v2 += x\n return abs(v1 - v2 ** 2)", "def squaresdiff(N):\n b = N * (N + 1) // 2\n a = N * (1 + N) * (2 * N + 1) // 6\n return abs(a - b * b)", "def squaresdiff(N):\n s = N * (N + 1) * (2 * N + 1) // 6\n t = (N * (N + 1) // 2) ** 2\n return abs(s - t)", "def squaresdiff(N):\n a1 = N * (N + 1) * (2 * N + 1) // 6\n a2 = (N * (N + 1) // 2) ** 2\n return abs(a1 - a2)", "def squaresdiff(N):\n a1 = 0\n a2 = 0\n for i in range(1, N + 1):\n ans = i * i\n a1 += ans\n a2 += i\n return abs(a1 - a2 * a2)", "def squaresdiff(N):\n sum = 0\n for i in range(1, N + 1):\n sum += i\n res = sum ** 2\n j = N * (N + 1) * (2 * N + 1) // 6\n ans = abs(j - res)\n return ans", "def squaresdiff(N):\n k = 0\n k1 = 0\n while N >= 1:\n k = k + N ** 2\n k1 = k1 + N\n N = N - 1\n d = k - k1 ** 2\n if d > 0:\n return d\n else:\n d = -d\n return d", "def squaresdiff(N):\n squr_of_sum = (N * (N + 1) / 2) ** 2\n sum_of_squrs = N * (N + 1) * (2 * N + 1) / 6\n return abs(int(sum_of_squrs) - int(squr_of_sum))", "def squaresdiff(N):\n s = 0\n sum = 0\n for i in range(1, N + 1):\n s += i\n for j in range(1, N + 1):\n sum += j ** 2\n x = s ** 2\n if x > sum:\n return x - sum\n else:\n return sum - x", "def squaresdiff(n):\n return int(abs(n * (n + 1) * (n - 1) * (3 * n + 2) / 12))", "def squaresdiff(N):\n sq_sum = 0\n sum = 0\n for i in range(N + 1):\n sq_sum += i * i\n sum += i\n sum *= sum\n return abs(sq_sum - sum)", "def squaresdiff(N):\n sq = N * (N + 1) * (2 * N + 1) // 6\n sumn = N * N * (N + 1) * (N + 1) // 4\n return abs(sq - sumn)", "def squaresdiff(N):\n ssq = 0\n s = 0\n for i in range(1, N + 1):\n ssq = ssq + pow(i, 2)\n s = s + i\n a = abs(ssq - s * s)\n return a", "def squaresdiff(N):\n return abs(sum([i ** 2 for i in range(N + 1)]) - sum(range(N + 1)) ** 2)", "def squaresdiff(N):\n squares = int(N * (N + 1) * (2 * N + 1) / 6)\n sum = int(N * (N + 1) / 2)\n return sum ** 2 - squares", "def squaresdiff(N):\n return N * (N + 1) * (3 * N ** 2 - N - 2) // 12", "def squaresdiff(N):\n return abs(N * (2 * N + 1) * (N + 1) // 6 - (N * (N + 1) // 2) ** 2)", "def squaresdiff(n):\n k = n * (n + 1) // 2\n k = k * k\n n = n * (n + 1) * (2 * n + 1) // 6\n return abs(k - n)", "def squaresdiff(N):\n if N in range(10 ** 3 + 1):\n numbers = [i for i in range(1, N + 1)]\n squared_numbers = [i * i for i in range(1, N + 1)]\n diff = abs(sum(squared_numbers) - pow(sum(numbers), 2))\n return diff", "def squaresdiff(N):\n n = N\n l = n * (n + 1) * (2 * n + 1) // 6\n k = n * (n + 1) // 2\n k = k ** 2\n m = abs(l - k)\n return m", "def squaresdiff(N: int) -> int:\n x = y = 0\n for i in range(1, N + 1):\n x += i ** 2\n y += i\n return abs(x - y ** 2)", "def squaresdiff(N):\n return (3 * pow(N, 4) + 2 * pow(N, 3) - 3 * pow(N, 2) - 2 * N) // 12", "def squaresdiff(n):\n sum = 0\n sum1 = 0\n for i in range(1, n + 1):\n sum += i ** 2\n for j in range(1, n + 1):\n sum1 += j\n sum2 = sum1 ** 2\n result = sum - sum2\n return abs(result)", "def squaresdiff(n):\n x = 1\n sum_of_sqr = n * (n + 1) * (2 * n + 1) // 6\n sqr_of_sum = n * (n + 1) // 2\n x = sqr_of_sum * sqr_of_sum\n return abs(sum_of_sqr - x)", "def squaresdiff(N):\n sum_of_squares = 0\n square_of_sum = 0\n for i in range(1, N + 1):\n sum_of_squares += i * i\n square_of_sum += i\n square_of_sum = square_of_sum ** 2\n return square_of_sum - sum_of_squares", "def squaresdiff(N):\n x = N * (N + 1) * (2 * N + 1) // 6 - (N * (N + 1) // 2) ** 2\n if '-' in str(x):\n return -x", "def squaresdiff(n):\n from math import pow\n r = 0\n s = 0\n for i in range(1, n + 1):\n r = r + int(pow(i, 2))\n s = s + i\n k = int(abs(r - int(pow(s, 2))))\n return k", "def squaresdiff(N):\n self.num = N\n n1 = 0\n n2 = 0\n for i in range(1, self.num + 1):\n n1 = n1 + i ** 2\n n2 = n2 + i\n n3 = n2 ** 2\n result = abs(n1 - n3)\n return result", "def squaresdiff(N):\n r1 = (N * (N + 1) // 2) ** 2\n r2 = 0\n for i in range(1, N + 1):\n r2 += i * i\n return abs(r1 - r2)", "def squaresdiff(N):\n n1 = int(N * (N + 1) * (2 * N + 1) / 6)\n n2 = int(N * (N + 1) / 2)\n n3 = n1 - n2 ** 2\n n4 = abs(n3)\n return n4", "def squaresdiff(N):\n l = int(N * (N + 1) * (2 * N + 1) / 6)\n m = int(N * (N + 1) / 2)\n return abs(l - m ** 2)", "def squaresdiff(N):\n sum1 = N * (N + 1) * (2 * N + 1) / 6\n x = N * (N + 1) / 2\n sum2 = x * x\n return int(abs(sum1 - sum2))", "def squaresdiff(N):\n sq = N * (N + 1) * (2 * N + 1) // 6\n p = N * (N + 1) // 2\n return abs(sq - pow(p, 2))"], "starter_code": "def squaresdiff (N):\n", "input_output": {"inputs": ["N = 2", "N = 3"], "outputs": ["4", "22"]}, "difficulty": "EASY", "raw_tags": ["Numbers", "series"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/squares-difference0939/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "squaresdiff", "task_id": "TACO_lite/315", "example": [[[2], [3]], ["4", "22"]]} +{"requirement": "You are given a string S of size N that represents the prefix form of a valid mathematical expression. Convert it to its infix form.\nExample 1:\nInput: \n*-A/BC-/AKL\nOutput: \n((A-(B/C))*((A/K)-L))\nExplanation: \nThe above output is its valid infix form.\nYour Task:\nComplete the function string preToInfix(string pre_exp), which takes a prefix string as input and return its infix form.\n \nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\nConstraints:\n3<=|S|<=10^{4}", "solutions": ["def pretoinfix(pre_exp):\n stk = []\n i = len(pre_exp) - 1\n while i != -1:\n if pre_exp[i] in ['+', '/', '*', '-', '^', '(', ')']:\n op1 = stk.pop()\n op2 = stk.pop()\n stk.append('(' + op1 + prefix[i] + op2 + ')')\n else:\n stk.append(pre_exp[i])\n i -= 1\n return stk.pop()", "def pretoinfix(pre_exp):\n s = []\n for i in pre_exp[::-1]:\n if i.isalpha():\n s.append(i)\n else:\n a = s.pop()\n b = s.pop()\n s.append('(' + a + i + b + ')')\n return s[0]", "def pretoinfix(pre_exp):\n st = []\n for i in range(len(pre_exp) - 1, -1, -1):\n if pre_exp[i].isalnum():\n st.append(pre_exp[i])\n elif len(st) >= 2:\n a = st.pop()\n b = st.pop()\n res = '(' + a + pre_exp[i] + b + ')'\n st.append(res)\n return st[0]", "def pretoinfix(pre_exp):\n result = ''\n prev = ''\n stack = []\n for i in pre_exp[::-1]:\n if i.isalnum():\n stack.append(i)\n else:\n x = stack.pop()\n y = stack.pop()\n prev = '(' + x + i + y + ')'\n stack.append(prev)\n return stack.pop()", "def pretoinfix(pre):\n pre = pre[::-1]\n stack = []\n for i in range(len(pre)):\n if pre[i] == '-' or pre[i] == '+' or pre[i] == '*' or (pre[i] == '/'):\n x = stack.pop()\n y = stack.pop()\n stack.append(')' + y + pre[i] + x + '(')\n else:\n stack.append(pre[i])\n ans = stack[0]\n return ans[::-1]", "def __init__():\n self.stack = []\n self.operatorSet = ('^', '*', '/', '+', '-', '(', ')')\n\ndef isOperator(char):\n return char in self.operatorSet\n\ndef pretoinfix(prefix):\n index = len(prefix) - 1\n while 0 <= index:\n char = prefix[index]\n if not self.isOperator(char):\n self.stack.append(char)\n index -= 1\n else:\n exp = '(' + self.stack.pop() + char + self.stack.pop() + ')'\n self.stack.append(exp)\n index -= 1\n return self.stack.pop()", "def pretoinfix(pre_exp):\n stack = []\n for c in pre_exp:\n if c == '+' or c == '-' or c == '*' or (c == '/'):\n stack.append(c)\n else:\n curr = c\n while len(stack) > 0 and stack[-1] not in ['+', '-', '*', '/']:\n op1 = stack.pop()\n op = stack.pop()\n curr = '(' + op1 + op + curr + ')'\n stack.append(curr)\n return stack[0]", "def pretoinfix(pre_exp):\n stack = []\n n = len(pre_exp)\n for i in range(n - 1, -1, -1):\n if pre_exp[i].isalpha() or pre_exp[i].isdigit():\n stack.append(pre_exp[i])\n else:\n op1 = stack.pop()\n op2 = stack.pop()\n exp = '(' + op1 + pre_exp[i] + op2 + ')'\n stack.append(exp)\n return stack.pop()", "def pretoinfix(exp):\n exp = exp[::-1]\n stack = []\n for i in exp:\n if i >= 'a' and i <= 'z' or (i >= 'A' and i <= 'Z') or (i >= '0' and i <= '9'):\n stack.append(i)\n else:\n stack.append('(' + stack.pop() + i + stack.pop() + ')')\n return stack.pop()", "def pretoinfix(pre_exp):\n a = pre_exp[::-1]\n l = []\n for j in a:\n if j.isalpha():\n l.append(j)\n else:\n a = l.pop()\n b = l.pop()\n l.append('(' + a + j + b + ')')\n return l[0]", "def pretoinfix(pre):\n operator = ['+', '-', '*', '/', '^']\n i = len(pre) - 1\n stack = []\n while i >= 0:\n if pre[i] not in operator:\n stack.append(pre[i])\n if pre[i] in operator:\n exp = '(' + stack.pop() + pre[i] + stack.pop() + ')'\n stack.append(exp)\n i -= 1\n return stack.pop()", "def pretoinfix(pre_exp):\n count = 0\n stack = []\n for ele in pre_exp[::-1]:\n if ele in ['^', '*', '/', '+', '-']:\n op1 = stack.pop()\n op2 = stack.pop()\n stack.append('(' + op1 + ele + op2 + ')')\n else:\n stack.append(ele)\n return stack.pop()", "def __init__():\n self.stack = []\n\ndef push(el):\n self.stack.append(el)\n\ndef pop():\n return self.stack.pop()\n\ndef pretoinfix(exp):\n exp_rev = exp[::-1]\n for i in exp_rev:\n if i in ['^', '+', '-', '*', '/']:\n exp2 = '('\n exp2 += self.pop()\n exp2 += i\n exp2 += self.pop()\n exp2 += ')'\n self.push(exp2)\n else:\n self.push(i)\n return exp2", "def pretoinfix(pre_exp):\n s1 = []\n s2 = []\n for i in range(len(pre_exp)):\n s1.append(pre_exp[i])\n while len(s1) != 0:\n a = s1.pop()\n if len(a) > 1 or (ord(a) >= ord('A') and ord(a) <= ord('Z')) or (ord(a) >= ord('a') and ord(a) <= ord('z')):\n s2.append(a)\n continue\n if a in '*-/+^':\n op1 = s2.pop()\n op2 = s2.pop()\n exp = '(' + op1 + a + op2 + ')'\n s2.append(exp)\n return s2[0]", "def pretoinfix(pre_exp):\n n = len(pre_exp) - 1\n st = []\n for i in range(n, -1, -1):\n ch = pre_exp[i]\n if ch in '^/*+-':\n A = st.pop()\n B = st.pop()\n exp = '(' + A + ch + B + ')'\n st.append(exp)\n else:\n st.append(ch)\n return st[-1]", "def pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n stack = []\n for c in pre_exp:\n if c.isalpha():\n stack.append(c)\n else:\n ex = '(' + stack.pop() + c + stack.pop() + ')'\n stack.append(ex)\n return stack[0]", "def pretoinfix(pre_exp):\n stack = []\n for i in range(len(pre_exp) - 1, -1, -1):\n if pre_exp[i] in ['+', '-', '*', '/']:\n s = '('\n s += stack.pop()\n s += pre_exp[i]\n s += stack.pop()\n s += ')'\n stack.append(s)\n else:\n stack.append(pre_exp[i])\n return stack[-1]", "def pretoinfix(pre_exp):\n stack = []\n op = '^*/+-'\n for i in pre_exp[-1::-1]:\n if i not in op:\n stack.append(i)\n if i in op:\n exp = '(' + stack.pop() + i + stack.pop() + ')'\n stack.append(exp)\n return stack[0]", "def isOperator(c):\n if c == '*' or c == '+' or c == '-' or (c == '/') or (c == '^') or (c == '(') or (c == ')'):\n return True\n else:\n return False\n\ndef pretoinfix(pref_ix):\n stack = []\n i = len(pref_ix) - 1\n while i >= 0:\n if not self.isOperator(pref_ix[i]):\n stack.append(pref_ix[i])\n i -= 1\n else:\n prefix = '(' + stack.pop() + pref_ix[i] + stack.pop() + ')'\n stack.append(prefix)\n i -= 1\n return stack.pop()", "def pretoinfix(pre_exp):\n lst = list(pre_exp)\n lst.reverse()\n infix = []\n stack = []\n for val in lst:\n if val in ['+', '-', '*', '/', '^']:\n if stack:\n one = stack.pop()\n second = stack.pop()\n stack.append('(' + one + val + second + ')')\n else:\n stack.append(val)\n return stack.pop()", "def pretoinfix(pre_exp):\n operators = ['^', '*', '/', '+', '-']\n operaAndBraces = ['^', '*', '/', '+', '-', '(', ')']\n stk = []\n for i in reversed(range(len(pre_exp))):\n elem = pre_exp[i]\n if elem not in operaAndBraces:\n stk.append(elem)\n else:\n str = '(' + stk.pop() + elem + stk.pop() + ')'\n stk.append(str)\n return stk.pop()", "def pretoinfix(s):\n (i, l) = (0, len(s))\n stack = []\n while i < l:\n if len(stack) >= 3 and stack[-3] in '/+-*' and (stack[-1] not in '/+-*') and (stack[-2] not in '/+-*'):\n while len(stack) >= 3 and stack[-3] in '/+-*' and (stack[-1] not in '/+-*') and (stack[-2] not in '/+-*'):\n b = stack.pop()\n a = stack.pop()\n stack.append('(' + a + stack.pop() + b + ')')\n stack.append(s[i])\n i += 1\n while len(stack) >= 3 and stack[-3] in '/+-*' and (stack[-1] not in '/+-*') and (stack[-2] not in '/+-*'):\n b = stack.pop()\n a = stack.pop()\n stack.append('(' + a + stack.pop() + b + ')')\n return stack[-1]", "def pretoinfix(pre_exp):\n stack = []\n for ch in pre_exp[::-1]:\n if ch.isalnum():\n stack.append(ch)\n else:\n stack.append('(' + stack.pop() + ch + stack.pop() + ')')\n return stack.pop()", "def pretoinfix(pre_exp):\n stack = []\n for v in pre_exp[::-1]:\n if v.isalnum():\n stack.append(v)\n else:\n stack.append('(' + stack.pop() + v + stack.pop() + ')')\n return stack[0]", "def pretoinfix(pre_exp):\n stack = []\n top = -1\n infix = ''\n for v in pre_exp[::-1]:\n if v.isdigit() or v.isalnum():\n stack.append(v)\n top += 1\n else:\n A = stack.pop()\n B = stack.pop()\n infix = '(' + A + v + B + ')'\n stack.append(infix)\n top -= 1\n return infix", "def pretoinfix(pre):\n ops = {'+', '-', '/', '*'}\n pre = pre[::-1]\n stack = []\n for i in range(len(pre)):\n if pre[i] in ops:\n a = stack.pop()\n stack.pop()\n b = stack.pop()\n stack.append('(' + a + pre[i] + b + ')')\n else:\n stack.append('(')\n stack.append(pre[i])\n stack = stack[1]\n return stack", "def pretoinfix(pre_exp):\n lis = []\n for i in pre_exp[::-1]:\n if i.isalpha():\n lis.append(i)\n else:\n z = lis.pop()\n y = lis.pop()\n lis.append('(' + z + i + y + ')')\n return lis[0]", "def evalu(exp, left, right):\n return '(' + left + exp + right + ')'\n\ndef __init__():\n self.stack = []\n\ndef pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n for i in pre_exp:\n if i is '+':\n left = self.stack.pop()\n right = self.stack.pop()\n val = evalu('+', left, right)\n self.stack.append(val)\n elif i is '-':\n left = self.stack.pop()\n right = self.stack.pop()\n val = evalu('-', left, right)\n self.stack.append(val)\n elif i is '*':\n left = self.stack.pop()\n right = self.stack.pop()\n val = evalu('*', left, right)\n self.stack.append(val)\n elif i is '/':\n left = self.stack.pop()\n right = self.stack.pop()\n val = evalu('/', left, right)\n self.stack.append(val)\n else:\n self.stack.append(i)\n return self.stack.pop()", "def pretoinfix(pre_exp):\n stack = []\n for idx in range(len(pre_exp) - 1, -1, -1):\n char = pre_exp[idx]\n if char in Solution.precedence:\n op1 = stack.pop()\n op2 = stack.pop()\n res = '(' + op1 + char + op2 + ')'\n stack.append(res)\n else:\n stack.append(char)\n res = stack[-1]\n return res", "def pretoinfix(pre_exp):\n stack = []\n operators = set(['+', '-', '*', '/', '^'])\n for i in range(len(pre_exp) - 1, -1, -1):\n if pre_exp[i] in operators:\n operand1 = stack.pop()\n operand2 = stack.pop()\n exp = '(' + operand1 + pre_exp[i] + operand2 + ')'\n stack.append(exp)\n else:\n stack.append(pre_exp[i])\n return stack.pop()", "def pretoinfix(pre_exp):\n l = ['+', '-', '*', '/', '^']\n s = []\n pre_exp = pre_exp[::-1]\n for i in pre_exp:\n if i in l:\n a = s.pop()\n b = s.pop()\n c = '(' + a + i + b + ')'\n s.append(c)\n else:\n s.append(i)\n return ''.join((i for i in s))", "def pretoinfix(pre_exp):\n (res, stack) = ([], [])\n for i in pre_exp:\n if ord('A') <= ord(i) <= ord('Z') or ord('a') <= ord(i) <= ord('z'):\n res.append(i)\n while stack and stack[-1] == '(':\n res.append(')')\n stack.pop()\n if stack:\n res.append(stack.pop())\n else:\n res.append('(')\n stack.append('(')\n stack.append(i)\n return ''.join(res)", "def pretoinfix(pre_exp):\n exp = pre_exp[::-1]\n stack = []\n for i in range(len(exp)):\n if exp[i] >= 'a' and exp[i] <= 'z' or (exp[i] >= 'A' and exp[i] <= 'Z'):\n stack.append(exp[i])\n else:\n a = stack.pop()\n b = stack.pop()\n res = '(' + a + exp[i] + b + ')'\n stack.append(res)\n return stack[0]", "def pretoinfix(arr):\n stack = []\n for i in range(len(arr) - 1, -1, -1):\n if self.isChr(arr[i]):\n stack.append(arr[i])\n if self.isOpr(arr[i]):\n first = stack.pop()\n secnd = stack.pop()\n res = '(' + first + arr[i] + secnd + ')'\n stack.append(res)\n return stack.pop()\n\ndef isChr(ch):\n if ch >= 'a' and ch <= 'z' or (ch >= 'A' and ch <= 'Z') or (ch >= '0' and ch <= '9'):\n return 1\n return 0\n\ndef isOpr(ch):\n opr = ['+', '-', '*', '/', '^']\n if ch in opr:\n return 1\n return 0", "def pretoinfix(pre_exp):\n stack = []\n s = ''\n for i in pre_exp[::-1]:\n s = ''\n if i not in '^*?()+-/':\n stack.append(i)\n else:\n p = ''\n q = ''\n if stack:\n p = stack.pop()\n if stack:\n q = stack.pop()\n if p or q:\n s = s + '(' + p + i + q + ')'\n else:\n s = s + p + i + q\n stack.append(s)\n return s", "def pretoinfix(pre_exp):\n stack = []\n exp = pre_exp[::-1]\n for i in exp:\n if i in '^*/+-':\n temp = '(' + stack.pop() + i + stack.pop() + ')'\n stack.append(temp)\n else:\n stack.append(i)\n return stack[-1]", "def pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n st = []\n for i in pre_exp:\n if i in '*+-/^':\n if len(st) >= 2:\n second = st.pop()\n first = st.pop()\n st.append(')' + first + i + second + '(')\n else:\n st.append(i)\n return st.pop()[::-1]", "def pretoinfix(pre_exp):\n stack = []\n operators = set(['+', '-', '*', '/', '^'])\n for i in range(len(pre_exp) - 1, -1, -1):\n if pre_exp[i] in operators:\n op1 = stack.pop()\n op2 = stack.pop()\n exp = '(' + op1 + pre_exp[i] + op2 + ')'\n stack.append(exp)\n else:\n stack.append(pre_exp[i])\n return stack.pop()", "def pretoinfix(pre_exp):\n ll = []\n for i in range(len(pre_exp) - 1, -1, -1):\n if pre_exp[i] in '*-/+':\n l = ll.pop(-1)\n r = ll.pop(-1)\n dat = '(' + l + pre_exp[i] + r + ')'\n ll.append(dat)\n else:\n ll.append(pre_exp[i])\n return ll[0]", "def pretoinfix(pre_exp):\n st = []\n for i in pre_exp[::-1]:\n if i.isalnum():\n st.append(i)\n else:\n o1 = st.pop()\n o2 = st.pop()\n inf = '(' + o1 + i + o2 + ')'\n st.append(inf)\n return st.pop()", "def pretoinfix(pre_exp):\n stack = []\n operators = set(['+', '-', '*', '/', '^'])\n for i in pre_exp[::-1]:\n if i in operators:\n op1 = stack.pop()\n op2 = stack.pop()\n stack.append('({}{}{})'.format(op1, i, op2))\n else:\n stack.append(i)\n return stack[-1]", "def is_operator(c):\n if c == '+' or c == '-' or c == '*' or (c == '/') or (c == '^'):\n return True\n else:\n return False\n\ndef pretoinfix(exp):\n exp = exp[::-1]\n stack = []\n for c in exp:\n if self.is_operator(c):\n op1 = stack.pop()\n op2 = stack.pop()\n stack.append('(' + op1 + c + op2 + ')')\n else:\n stack.append(c)\n return stack.pop()", "def pretoinfix(pre_exp):\n stack = []\n i = len(pre_exp) - 1\n list = ['+', '-', '*', '/', '^']\n str = ''\n while i >= 0:\n if pre_exp[i] not in list:\n stack.append(pre_exp[i])\n i -= 1\n else:\n str = '(' + stack.pop() + pre_exp[i] + stack.pop() + ')'\n stack.append(str)\n i -= 1\n temp = stack.pop()\n return temp", "def pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n stack = []\n for i in pre_exp:\n if i.isalpha():\n stack.append(i)\n else:\n exp = i\n two = stack.pop()\n one = stack.pop()\n new = ')' + one + i + two + '('\n stack.append(new)\n return stack[0][::-1]", "def pretoinfix(pre_exp):\n s = []\n for i in pre_exp[::-1]:\n if i in ['*', '+', '-', '/']:\n t1 = s.pop()\n t2 = s.pop()\n s.append('(' + t1 + i + t2 + ')')\n else:\n s.append(i)\n return ''.join(s)", "def pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n a = []\n res = ''\n for i in range(len(pre_exp)):\n if pre_exp[i].isalpha():\n a.append(pre_exp[i])\n else:\n first = a.pop()\n second = a.pop()\n res = '(' + first + pre_exp[i] + second + ')'\n a.append(res)\n return a[-1]", "def pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n stack = []\n res = ''\n for i in range(len(pre_exp)):\n if pre_exp[i].isalpha():\n stack.append(pre_exp[i])\n else:\n first = stack.pop()\n sec = stack.pop()\n res = '(' + first + pre_exp[i] + sec + ')'\n stack.append(res)\n ans = stack[-1]\n return ans", "def pretoinfix(pre_exp):\n prefix = list(pre_exp)\n prefix.reverse()\n stack = []\n str = ''\n for i in range(len(prefix)):\n if prefix[i] not in {'+', '*', '-', '/'}:\n stack.append(prefix[i])\n else:\n if stack:\n op1 = stack.pop()\n if stack:\n op2 = stack.pop()\n str += '(' + op1 + prefix[i] + op2 + ')'\n stack.append(str)\n str = ''\n return stack[-1]", "def pretoinfix(s1):\n str = ''\n st = []\n for i in range(len(s1) - 1, -1, -1):\n if s1[i].isalpha():\n st.append(s1[i])\n else:\n str1 = st.pop()\n str2 = st.pop()\n str = '(' + str1 + s1[i] + str2 + ')'\n st.append(str)\n str = st.pop()\n return str", "def is_operand(x):\n return ord(x) >= ord('a') and ord(x) <= ord('z') or (ord(x) >= ord('A') and ord(x) <= ord('Z'))\n\ndef pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n st = []\n for i in pre_exp:\n if is_operand(i):\n st.append(i)\n else:\n if len(st) < 2:\n raise Exception('invalid Expression')\n s1 = st.pop()\n s2 = st.pop()\n cur = '(' + s1 + i + s2 + ')'\n st.append(cur)\n return ''.join(st)", "def pretoinfix(pre_exp):\n precedence = {'^': 3, '+': 1, '-': 1, '*': 2, '/': 2}\n st = []\n s = ''\n for i in pre_exp[::-1]:\n if i in precedence.keys():\n x = st.pop()\n y = st.pop()\n st.append('(' + x + i + y + ')')\n else:\n st.append(i)\n string = ''.join(st)\n return string", "def pretoinfix(pre_exp):\n stack = []\n for i in range(len(pre_exp) - 1, -1, -1):\n char = pre_exp[i]\n if char.isalnum():\n stack.append(char)\n elif char in '+-*/^':\n if len(stack) < 2:\n return 'Invalid expression'\n op1 = stack.pop()\n op2 = stack.pop()\n subexp = '(' + op1 + char + op2 + ')'\n stack.append(subexp)\n else:\n return 'Invalid expression'\n if len(stack) != 1:\n return 'Invalid expression'\n return stack.pop()", "from collections import deque\n\ndef pretoinfix(pre_exp):\n stack = deque()\n for i in range(len(pre_exp) - 1, -1, -1):\n if pre_exp[i].isalpha():\n stack.append(pre_exp[i])\n else:\n expr1 = stack.pop()\n expr2 = stack.pop()\n new_expr = '(' + expr1 + pre_exp[i] + expr2 + ')'\n stack.append(new_expr)\n return stack.pop()", "def __init__():\n self.l = []\n\ndef push(element):\n self.l.append(element)\n\ndef pop():\n return self.l.pop()\n\ndef pretoinfix(pre_exp):\n for i in reversed(pre_exp):\n if i == '+':\n a = self.pop()\n b = self.pop()\n self.push('(' + a + '+' + b + ')')\n elif i == '-':\n a = self.pop()\n b = self.pop()\n self.push('(' + a + '-' + b + ')')\n elif i == '*':\n a = self.pop()\n b = self.pop()\n self.push('(' + a + '*' + b + ')')\n elif i == '/':\n a = self.pop()\n b = self.pop()\n self.push('(' + a + '/' + b + ')')\n else:\n self.push(i)\n ss = ''\n for i in self.l:\n ss = ss + '' + i\n return ss", "def pretoinfix(ex):\n s = []\n ex = ex[::-1]\n for ch in ex:\n if ch.isalnum():\n s += ch\n else:\n o = ''\n o = '(' + s[-1] + ch + s[-2] + ')'\n s.pop()\n s.pop()\n s.append(o)\n return o", "from collections import deque\n\ndef pretoinfix(pre_exp):\n operators = {'*', '-', '^', '/', '+', '%'}\n stack = deque()\n exp = pre_exp\n for i in range(len(exp) - 1, -1, -1):\n symbol = exp[i]\n if symbol in operators:\n subexpr = '(' + str(stack.pop()) + str(symbol) + str(stack.pop()) + ')'\n stack.append(subexpr)\n else:\n stack.append(symbol)\n return stack.pop()", "def pretoinfix(string):\n stack = []\n operators = ['-', '/', '+', '*']\n reversed_string = string[::-1]\n for char in reversed_string:\n if char not in operators:\n stack.append(char)\n else:\n popped_first_char = stack.pop()\n new_char_str = ''\n popped_second_char = stack.pop()\n new_char_str = '(' + new_char_str + popped_first_char + char + popped_second_char + ')'\n stack.append(new_char_str)\n return stack[0]", "def pretoinfix(exp):\n exp = exp[::-1]\n stack = []\n ans = ''\n for ch in exp:\n if ch.isalnum():\n stack.append(ch)\n else:\n first = stack.pop()\n second = stack.pop()\n stack.append('(' + first + ch + second + ')')\n return stack[-1]", "def isOperator(c):\n if c == '+' or c == '-' or c == '*' or (c == '/') or (c == '^'):\n return True\n else:\n return False\n\ndef pretoinfix(pre_exp):\n stack = []\n n = len(pre_exp)\n for i in range(n - 1, -1, -1):\n c = pre_exp[i]\n if isOperator(c):\n op1 = stack.pop()\n op2 = stack.pop()\n stack.append('(' + op1 + c + op2 + ')')\n else:\n stack.append(c)\n return stack[0]", "def pretoinfix(pre_exp):\n res = []\n ans = ''\n for i in pre_exp[::-1]:\n if i.isalpha() or i.isnumeric():\n res.append(i)\n else:\n a1 = res.pop()\n a2 = res.pop()\n ans = '(' + a1 + i + a2 + ')'\n res.append(ans)\n return ans", "def isOp(c):\n if c == '*' or c == '+' or c == '-' or (c == '/') or (c == '^') or (c == '(') or (c == ')'):\n return True\n else:\n return False\n\ndef pretoinfix(pre_exp):\n stack = []\n i = len(pre_exp) - 1\n while i >= 0:\n if not self.isOp(pre_exp[i]):\n stack.append(pre_exp[i])\n i -= 1\n else:\n str = '(' + stack.pop() + pre_exp[i] + stack.pop() + ')'\n stack.append(str)\n i -= 1\n return stack.pop()", "def pretoinfix(pre_exp):\n st = []\n s = ''\n l = len(pre_exp)\n for i in range(-1, -l - 1, -1):\n if pre_exp[i] == '*' or pre_exp[i] == '/' or pre_exp[i] == '+' or (pre_exp[i] == '-'):\n n1 = st.pop()\n n2 = st.pop()\n st.append('@' + n1 + pre_exp[i] + n2 + '#')\n else:\n st.append(pre_exp[i])\n pre = st[0]\n pre = pre.replace('@', '(')\n pre = pre.replace('#', ')')\n res = pre\n return res", "def pretoinfix(pre):\n stack = []\n for i in range(len(pre) - 1, 0, -1):\n if pre[i].isalpha():\n stack.append(pre[i])\n else:\n first = stack.pop()\n second = stack.pop()\n op = '(' + first + pre[i] + second + ')'\n stack.append(op)\n res = '(' + stack.pop() + pre[0] + stack.pop() + ')'\n return res", "def pretoinfix(pre_exp):\n Operators = ['+', '-', '*', '/', '(', ')', '^']\n pre_exp = pre_exp[::-1]\n stack = []\n for character in pre_exp:\n if character not in Operators:\n stack.append(character)\n else:\n res = ''\n res += '('\n A = stack.pop()\n B = stack.pop()\n res += A\n res += character\n res += B\n res += ')'\n stack.append(res)\n return stack.pop()", "def pretoinfix(pre_exp):\n stack = []\n substr = ''\n exp = ''\n operators = ['+', '^', '%', '-', '*', '/']\n for i in range(len(pre_exp) - 1, -1, -1):\n ele = pre_exp[i]\n if ele in operators:\n stack.append('(' + stack.pop() + ele + stack.pop() + ')')\n else:\n stack.append(ele)\n return stack.pop()", "def pretoinfix(s):\n\n def isOperator(x):\n return ch in '+-*/^%'\n stack = []\n n = len(s)\n for i in range(n - 1, -1, -1):\n ch = s[i]\n if isOperator(ch):\n op1 = stack.pop()\n op2 = stack.pop()\n temp = '(' + op1 + ch + op2 + ')'\n stack.append(temp)\n else:\n stack.append(ch)\n return stack.pop()", "def is_operand(i):\n return i.isalpha()\n\ndef pretoinfix(pre_exp):\n (s, n) = (pre_exp, len(pre_exp))\n stack = []\n for i in range(n - 1, -1, -1):\n if is_operand(s[i]):\n stack.append(s[i])\n else:\n a = stack.pop()\n b = stack.pop()\n c = '(' + a + s[i] + b + ')'\n stack.append(c)\n return stack[-1]", "def pretoinfix(exp):\n st = []\n exp = exp[::-1]\n for ch in exp:\n if ch in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmonpqrstuvwxyz':\n st += [ch]\n else:\n tmp = '(' + st[-1] + ch + st[-2] + ')'\n st.pop()\n st.pop()\n st.append(tmp)\n return st.pop()", "def __init__():\n self.top = -1\n self.array = []\n\ndef isEmpty():\n return True if self.top == -1 else False\n\ndef pop():\n if not self.isEmpty():\n self.top -= 1\n return self.array.pop()\n else:\n return '$'\n\ndef push(op):\n self.top += 1\n self.array.append(op)\n\ndef isOperand(ch):\n return ch.isalpha()\n\ndef pretoinfix(exp):\n i = len(exp) - 1\n while i >= 0:\n if self.isOperand(exp[i]):\n self.push(exp[i])\n else:\n str = '(' + self.pop() + exp[i] + self.pop() + ')'\n self.push(str)\n i -= 1\n return self.pop()", "def pretoinfix(pre_exp):\n pre_exp = list(pre_exp)\n while len(pre_exp) != 1:\n for x in range(len(pre_exp) - 3, -1, -1):\n sym = pre_exp[x]\n if not sym.isalnum() and len(sym) == 1:\n pre_exp[x] = '(' + pre_exp[x + 1] + pre_exp[x] + pre_exp[x + 2] + ')'\n del pre_exp[x + 1]\n del pre_exp[x + 1]\n return pre_exp[0]", "def pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n st = []\n operators = set(['-', '+', '*', '/', '^'])\n for i in range(len(pre_exp)):\n if pre_exp[i] in operators:\n operand1 = st.pop()\n operand2 = st.pop()\n new_exp = '(' + operand1 + pre_exp[i] + operand2 + ')'\n st.append(new_exp)\n else:\n st.append(pre_exp[i])\n return st.pop()", "def pretoinfix(pre_exp):\n operators = ['+', '-', '*', '/', '^']\n pre_exp = pre_exp[::-1]\n stack = []\n for c in pre_exp:\n if c not in operators:\n stack.append(c)\n else:\n exp = '(' + stack.pop() + c + stack.pop() + ')'\n stack.append(exp)\n return stack[-1]"], "starter_code": "def pretoinfix(pre_exp):\n", "input_output": {"inputs": ["*-A/BC-/AKL"], "outputs": ["((A-(B/C))*((A/K)-L))"]}, "difficulty": "MEDIUM", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/prefix-to-infix-conversion/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "pretoinfix", "task_id": "TACO_lite/221", "example": [[], []]} +{"requirement": "Given a sorted linked list of distinct nodes (no two nodes have the same data) and an integer X. Count distinct triplets in the list that sum up to given integer X.\nNote: The Linked List can be sorted in any order.\nExample 1:\nInput: LinkedList: 1->2->4->5->6->8->9, X = 17\nOutput: 2\nExplanation: Distinct triplets are (2, 6, 9) \nand (4, 5, 8) which have sum equal to X i.e 17.\nExample 2:\nInput: LinkedList: 1->2->4->5->6->8->9, X = 15\nOutput: 5\nExplanation: (1, 5, 9), (1, 6, 8), (2, 4, 9), \n(2, 5, 8), (4, 5, 6) are the distinct triplets\nYour Task: \nYou don't need to read input or print anything. Complete the function countTriplets() which takes a head reference and X as input parameters and returns the triplet count\nExpected Time Complexity: O(N^{2})\nExpected Auxiliary Space: O(N)\nConstraints:\n1 ≤ Number of Nodes ≤ 10^{3} \n1 ≤ Node value ≤ 10^{4}", "solutions": ["def counttriplets(head, x):\n if head == None:\n return\n temp1 = head\n answer = []\n while temp1:\n hashmap = {}\n temp2 = temp1.nxt\n while temp2:\n value = x - (temp1.val + temp2.val)\n if value in hashmap:\n answer.append([temp1.val, temp2.val, value])\n else:\n hashmap[temp2.val] = 1\n temp2 = temp2.nxt\n temp1 = temp1.nxt\n return len(answer)", "def counttriplets(head, x):\n arr = []\n while head:\n arr.append(head.val)\n head = head.nxt\n count = 0\n d = {}\n for i in range(len(arr)):\n d[arr[i]] = i\n for i in range(len(arr)):\n for j in range(i + 1, len(arr)):\n k = x - (arr[i] + arr[j])\n if k in d and d[k] != i and (d[k] != j):\n count += 1\n return count // 3", "def counttriplets(head, x):\n h1 = head\n count = 0\n while h1:\n m = {}\n h2 = h1.nxt\n while h2:\n value = x - (h1.val + h2.val)\n if value in m:\n count += 1\n else:\n m[h2.val] = 1\n h2 = h2.nxt\n h1 = h1.nxt\n return count", "def counttriplets(head, x):\n curr1 = head\n answer = []\n while curr1:\n hashmap = {}\n curr2 = curr1.nxt\n while curr2:\n value = x - (curr1.val + curr2.val)\n if value in hashmap:\n answer.append([curr1.val, curr2.val, value])\n else:\n hashmap[curr2.val] = 1\n curr2 = curr2.nxt\n curr1 = curr1.nxt\n return len(answer)", "def counttriplets(head, x):\n temp = head\n c = 0\n while temp.nxt.nxt:\n s = set()\n f = temp.val\n s.add(temp.nxt.val)\n k = temp.nxt.nxt\n while k:\n if x - (k.val + f) in s:\n c += 1\n else:\n s.add(k.val)\n k = k.nxt\n temp = temp.nxt\n return c", "def counttriplets(head, x):\n l = []\n temp = head\n while temp != None:\n l.append(temp.val)\n temp = temp.nxt\n n = len(l)\n l.sort()\n c = 0\n for i in range(n - 2):\n le = i + 1\n r = n - 1\n while le < r:\n s = l[i] + l[le] + l[r]\n if s == x:\n c += 1\n le += 1\n r -= 1\n elif s < x:\n le = le + 1\n else:\n r = r - 1\n return c", "def counttriplets(head, x):\n curr = head\n l = []\n ans = 0\n while curr:\n l.append(curr.val)\n curr = curr.nxt\n l.sort()\n n = len(l)\n for i in range(n - 2):\n m = i + 1\n r = n - 1\n while m < r:\n if l[i] + l[m] + l[r] == x:\n ans += 1\n m += 1\n r = r - 1\n elif l[i] + l[m] + l[r] > x:\n r -= 1\n else:\n m += 1\n return ans", "def counttriplets(head, x):\n lst = []\n itr = head\n while itr:\n lst.append(itr.val)\n itr = itr.nxt\n count = 0\n for i in range(len(lst)):\n l = i + 1\n r = len(lst) - 1\n while l < r:\n if lst[i] < lst[l]:\n if lst[i] + lst[l] + lst[r] == x:\n count += 1\n l += 1\n r -= 1\n elif lst[i] + lst[l] + lst[r] > x:\n r -= 1\n else:\n l += 1\n elif lst[i] + lst[l] + lst[r] == x:\n count += 1\n l += 1\n r -= 1\n elif lst[i] + lst[l] + lst[r] < x:\n r -= 1\n else:\n l += 1\n return count", "def counttriplets(head, x):\n dic = {}\n tt = head\n while tt:\n dic[tt.val] = tt\n tt = tt.nxt\n c = 0\n temp = head\n while temp:\n tmp = temp.nxt\n while tmp:\n s = temp.val + tmp.val\n if x - s in dic and dic[x - s] != temp and (dic[x - s] != tmp):\n c += 1\n tmp = tmp.nxt\n temp = temp.nxt\n return c // 3", "def counttriplets(head, x):\n dicti = {}\n z = head\n kk = 0\n p = 0\n while z != None:\n dicti[z.val] = p\n p = p + 1\n z = z.nxt\n p1 = head\n p2 = head.nxt\n while p1 != None:\n while p2 != None:\n u = x - p1.val - p2.val\n if u in dicti.keys() and u != p1.val and (u != p2.val) and (dicti[u] > dicti[p1.val]) and (dicti[u] > dicti[p2.val]):\n kk = kk + 1\n p2 = p2.nxt\n p1 = p1.nxt\n if p1.nxt == None:\n break\n p2 = p1.nxt\n return kk", "def counttriplets(head, x):\n z = []\n while head is not None:\n z.append(head.val)\n head = head.nxt\n c = 0\n z.sort()\n k = len(z)\n for i in range(k - 2):\n l = i + 1\n h = k - 1\n while l < h:\n if z[i] + z[l] + z[h] == x:\n c = c + 1\n l = l + 1\n h = h - 1\n elif z[i] + z[l] + z[h] < x:\n l = l + 1\n else:\n h = h - 1\n return c", "def counttriplets(head, x):\n values = []\n while head is not None:\n values.append(head.val)\n head = head.nxt\n count = 0\n values.sort()\n n = len(values)\n for i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n if values[i] + values[j] + values[k] == x:\n count += 1\n j += 1\n k -= 1\n elif values[i] + values[j] + values[k] < x:\n j += 1\n else:\n k -= 1\n return count", "def counttriplets(head, x):\n if not head or not head.nxt:\n return 0\n count = 0\n arr = []\n curr = head\n while curr:\n arr.append(curr.val)\n curr = curr.nxt\n n = len(arr)\n arr.sort()\n for start in range(n - 2):\n mid = start + 1\n end = n - 1\n while mid < end:\n Sum = arr[start] + arr[mid] + arr[end]\n if Sum == x:\n count += 1\n mid += 1\n end -= 1\n elif Sum > x:\n end -= 1\n else:\n mid += 1\n return count", "def counttriplets(head, X):\n l = []\n while head:\n l.append(head.val)\n head = head.nxt\n l.sort()\n n = len(l)\n ans = 0\n for i in range(n):\n req = X - l[i]\n (x, y) = (i + 1, n - 1)\n while x < y:\n if l[x] + l[y] == req:\n ans += 1\n x += 1\n y -= 1\n elif l[x] + l[y] > req:\n y -= 1\n else:\n x += 1\n return ans", "def counttriplets(head, x):\n l = []\n while head:\n l.append(head.val)\n head = head.nxt\n l.sort()\n ans = 0\n n = len(l)\n for i in range(n):\n t = x - l[i]\n left = i + 1\n right = n - 1\n while left < right:\n current = l[left] + l[right]\n if current < t:\n left += 1\n elif current > t:\n right -= 1\n else:\n ans += 1\n left += 1\n return ans", "def counttriplets(head, x):\n P = []\n while head:\n P.append(head.val)\n head = head.nxt\n P.sort()\n count = 0\n for i in range(len(P) - 2):\n j = i + 1\n k = n - 1\n while j < k:\n S = P[i] + P[j] + P[k]\n if S > x:\n k -= 1\n elif S < x:\n j += 1\n else:\n count += 1\n j += 1\n k -= 1\n return count", "def counttriplets(head, x):\n count = 0\n while head.nxt != None:\n d = {}\n temp = head.nxt\n while temp != None:\n if x - (temp.val + head.val) in d.keys():\n count += 1\n else:\n d[temp.val] = 1\n temp = temp.nxt\n head = head.nxt\n return count", "def counttriplets(head, x):\n arr = []\n curr = head\n while curr:\n arr.append(curr.val)\n curr = curr.nxt\n ans = 0\n arr.sort()\n for i in range(len(arr)):\n low = i + 1\n high = len(arr) - 1\n while low < high:\n if arr[i] + arr[low] + arr[high] == x:\n ans += 1\n low += 1\n elif arr[i] + arr[low] + arr[high] < x:\n low += 1\n else:\n high -= 1\n return ans", "def counttriplets(start, x):\n temp = start\n l = []\n while temp:\n l.append(temp.val)\n temp = temp.nxt\n l.sort()\n c = 0\n for i in range(0, n - 2):\n j = i + 1\n k = len(l) - 1\n while j < k:\n if l[i] + l[j] + l[k] == x:\n c += 1\n j += 1\n k -= 1\n elif l[i] + l[j] + l[k] > x:\n k -= 1\n else:\n j += 1\n return c", "def counttriplets(start, x):\n arr = []\n temp = start\n while temp:\n arr.append(temp.val)\n temp = temp.nxt\n result = 0\n arr.sort()\n for i in range(len(arr) - 2):\n j = i + 1\n k = len(arr) - 1\n while j < k:\n if arr[i] + arr[j] + arr[k] < x:\n j += 1\n elif arr[i] + arr[j] + arr[k] > x:\n k -= 1\n else:\n result += 1\n j += 1\n return result", "def counttriplets(head, x):\n if not head:\n return\n prev = None\n cur = head\n while cur:\n nxt = cur.nxt\n cur.prev = prev\n prev = cur\n cur = nxt\n tail = prev\n count = 0\n cur = head\n while cur.nxt:\n diff = x - cur.val\n start = cur.nxt\n end = tail\n while start and end and (start != end):\n if start.val + end.val == diff:\n count += 1\n end = end.prev\n elif start.val + end.val < diff:\n end = end.prev\n elif start.val + end.val > diff:\n start = start.nxt\n cur = cur.nxt\n return count\n\ndef __init__(x):\n self.val = x\n self.nxt = None\n self.prev = None", "def counttriplets(head, x):\n lis = []\n itr = head\n while itr:\n lis.append(itr.val)\n itr = itr.nxt\n dic = {}\n for i in lis:\n if i in dic:\n dic[i] += 1\n else:\n dic[i] = 1\n lis.sort()\n ans = 0\n for i in range(len(lis) - 2):\n m = i + 1\n r = len(lis) - 1\n while m < r:\n if lis[i] + lis[m] + lis[r] == x:\n ans += 1\n m += 1\n r -= 1\n elif lis[i] + lis[m] + lis[r] > x:\n r -= 1\n else:\n m += 1\n return ans", "def counttriplets(head, x):\n c = 0\n num = []\n t = head\n while t:\n num.append(t.val)\n t = t.nxt\n num.sort()\n for i in range(len(num) - 2):\n l = i + 1\n r = len(num) - 1\n while l < r:\n k = num[i] + num[l] + num[r]\n if k == x:\n c += 1\n l += 1\n r -= 1\n elif k > x:\n r -= 1\n else:\n l += 1\n return c", "def counttriplets(head, key):\n\n def reverse(head):\n cur = head\n prev = None\n while cur:\n nxt = cur.nxt\n cur.nxt = prev\n prev = cur\n cur = nxt\n head = prev\n return head\n p = head\n head2 = Node(0)\n ans = head2\n q = head\n while q:\n head2.nxt = Node(q.val)\n head2 = head2.nxt\n q = q.nxt\n right = reverse(ans.nxt)\n count = 0\n while p.nxt:\n q = p.nxt\n r = right\n while q and r and (q.val != r.val):\n value = p.val + q.val + r.val\n if value == key:\n count += 1\n q = q.nxt\n elif value < key:\n r = r.nxt\n else:\n q = q.nxt\n p = p.nxt\n return count", "def counttriplets(head, x):\n nums = []\n t = head\n while t:\n nums.append(t.val)\n t = t.nxt\n count = 0\n di = {}\n i = 0\n while i < n - 2:\n temp = x - nums[i]\n dic = {}\n for j in range(i + 1, n):\n if temp - nums[j] in dic:\n count += 1\n dic[nums[j]] = 1\n i += 1\n return count", "def count(head):\n n = head\n count = 0\n while n:\n count += 1\n n = n.next\n\ndef counttriplets(head, x):\n node = head\n list = []\n while node:\n list.append(node.val)\n node = node.nxt\n N = len(list)\n k = N - 1\n if list[0] > list[1]:\n list.sort()\n count = 0\n while k >= 2:\n j = k - 1\n i = 0\n while i < j:\n if list[i] + list[j] + list[k] == x:\n count += 1\n i += 1\n j -= 1\n elif list[i] + list[j] + list[k] > x:\n j -= 1\n else:\n i += 1\n k -= 1\n return count", "def counttriplets(head, x):\n ans = 0\n arr = []\n p = head\n while p:\n arr.append(p.val)\n p = p.nxt\n for i in range(len(arr)):\n remaining = x - arr[i]\n d = {}\n for j in range(i + 1, len(arr)):\n if arr[j] in d:\n ans += 1\n else:\n d[remaining - arr[j]] = j\n return ans", "def counttriplets(head, x):\n ans = 0\n arr = []\n p = head\n while p:\n arr.append(p.val)\n p = p.nxt\n arr.sort()\n for i in range(len(arr)):\n l = i + 1\n r = len(arr) - 1\n while l < r:\n c = arr[i] + arr[l] + arr[r]\n if c == x:\n ans += 1\n l += 1\n r -= 1\n elif c < x:\n l += 1\n else:\n r -= 1\n return ans", "def counttriplets(head, x):\n nums = []\n t = head\n while t:\n nums.append(t.val)\n t = t.nxt\n nums.sort()\n if n == 1:\n return []\n brr = []\n di = {}\n i = 0\n while i < n - 2:\n temp = x - nums[i]\n dic = {}\n for j in range(i + 1, n):\n if temp - nums[j] in dic:\n mi = min(nums[i], nums[j], -(nums[i] + nums[j]))\n ma = max(nums[i], nums[j], -(nums[i] + nums[j]))\n sec = -(mi + ma)\n brr.append((mi, sec, ma))\n dic[nums[j]] = 1\n i += 1\n brr = list(set(brr))\n return len(brr)", "def counttriplets(head, x):\n p = head\n l = []\n while p != None:\n l.append(p.val)\n p = p.nxt\n c = 0\n n = len(l)\n l.sort()\n for i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n if l[i] + l[j] + l[k] == x:\n c += 1\n j += 1\n k -= 1\n elif l[i] + l[j] + l[k] < x:\n j += 1\n else:\n k -= 1\n return c", "def counttriplets(head, x):\n arr = []\n while head:\n arr.append(head.val)\n head = head.nxt\n n = len(arr)\n cnt = 0\n ind = {}\n for i in range(len(arr)):\n ind[arr[i]] = i\n for i in range(n):\n for j in range(i + 1, n):\n if ind.get(x - arr[i] - arr[j], -1) != -1 and ind[x - arr[i] - arr[j]] > j:\n cnt += 1\n return cnt", "def counttriplets(head, x):\n\n def traversal(head):\n n = head\n while n != None:\n list1.append(n.val)\n n = n.nxt\n list1 = []\n traversal(head)\n length = len(list1)\n count = 0\n list1.sort()\n for i in range(length - 2):\n j = i + 1\n k = length - 1\n while j < k:\n if list1[i] + list1[j] + list1[k] == x:\n count += 1\n j += 1\n k -= 1\n elif list1[i] + list1[j] + list1[k] > x:\n k -= 1\n elif list1[i] + list1[j] + list1[k] < x:\n j += 1\n return count", "def counttriplets(head, x):\n c = head\n l = []\n while c:\n l.append(c.val)\n c = c.nxt\n res = 0\n l.sort()\n for i in range(n - 2):\n le = i + 1\n r = n - 1\n while le < r:\n if l[i] + l[le] + l[r] == x:\n res += 1\n le += 1\n r -= 1\n elif l[i] + l[le] + l[r] > x:\n r -= 1\n else:\n le += 1\n return res", "def counttriplets(head, x):\n (arr, len1, res) = ([], 0, 0)\n while head:\n arr.append(head.val)\n (head, len1) = (head.nxt, len1 + 1)\n arr.sort()\n for i in range(len1 - 2):\n (start, end) = (i + 1, len1 - 1)\n sum1 = x - arr[i]\n while start < end:\n if arr[start] + arr[end] == sum1:\n (res, start, end) = (res + 1, start + 1, end - 1)\n elif arr[start] + arr[end] > sum1:\n end -= 1\n elif arr[start] + arr[end] < sum1:\n start += 1\n return res", "def counttriplets(head, x):\n (L, K, M) = ([], [], [])\n temp = head\n while temp:\n a = temp.val\n L.append(a)\n temp = temp.nxt\n L.sort()\n count = 0\n for i in range(n - 2):\n (m, r) = (i + 1, n - 1)\n while m < r:\n if L[i] + L[m] + L[r] == x:\n (count, m, r) = (count + 1, m + 1, r - 1)\n elif L[i] + L[m] + L[r] > x:\n r -= 1\n else:\n m += 1\n return count", "def counttriplets(head, x):\n map = []\n curr = head\n while curr is not None:\n map.append(curr.val)\n curr = curr.nxt\n c = 0\n map.sort()\n for i in range(len(map) - 2):\n start = i + 1\n end = len(map) - 1\n while start < end:\n if map[start] + map[end] + map[i] == x:\n c += 1\n start += 1\n end -= 1\n elif map[start] + map[end] + map[i] > x:\n end -= 1\n else:\n start += 1\n return c", "def counttriplets(head, x):\n itemsArr = []\n itemsHT = {}\n while head is not None:\n nextVal = head.val\n itemsArr.append(nextVal)\n itemsHT[nextVal] = 1\n head = head.nxt\n arrayLen = len(itemsArr)\n result = 0\n for i in range(arrayLen - 1):\n for j in range(i + 1, arrayLen):\n itemToFind = x - itemsArr[i] - itemsArr[j]\n if itemToFind == itemsArr[i] or itemToFind == itemsArr[j]:\n continue\n elif itemToFind in itemsHT:\n result += 1\n return result // 3", "def counttriplets(head, x):\n ans = 0\n dict1 = {}\n n = head\n while n:\n dict1[n.val] = 1\n n = n.nxt\n if head.val > head.nxt.val:\n curr = head\n prev = None\n while curr:\n nxt = curr.nxt\n curr.nxt = prev\n prev = curr\n curr = nxt\n head = prev\n n = head\n while n:\n m = n.nxt\n while m:\n ele = x - (m.val + n.val)\n if ele in dict1 and ele > m.val:\n ans += 1\n elif ele <= m.val:\n break\n m = m.nxt\n n = n.nxt\n return ans", "def counttriplets(head, x):\n vv = []\n while head != None:\n vv.append(head.val)\n head = head.nxt\n ans = 0\n for i in range(len(vv) - 2):\n s = i + 1\n e = len(vv) - 1\n while s < e:\n temp = vv[i] + vv[s] + vv[e]\n if temp == x:\n ans += 1\n s += 1\n e -= 1\n elif temp > x:\n s += 1\n else:\n e -= 1\n return ans", "def counttriplets(head, x):\n p = head\n arr = []\n count = 0\n while p:\n arr.append(p.val)\n p = p.nxt\n arr.sort()\n n = len(arr)\n for i in range(n - 2):\n target = x - arr[i]\n j = i + 1\n k = n - 1\n while j < k:\n sum = arr[j] + arr[k]\n if sum == target:\n count = count + 1\n j = j + 1\n k = k - 1\n elif sum < target:\n j = j + 1\n elif sum > target:\n k = k - 1\n return count", "def counttriplets(head, x):\n l = []\n while head != None:\n l.append(head.val)\n head = head.nxt\n count = 0\n n = len(l)\n for i in range(0, n - 2):\n start = n - 1\n end = i + 1\n while start > end:\n if l[start] + l[end] == x - l[i]:\n count += 1\n start -= 1\n end += 1\n elif l[start] + l[end] > x - l[i]:\n end += 1\n else:\n start -= 1\n return count", "def counttriplets(head, x):\n curr = head\n map = {}\n while curr:\n map[curr.val] = 1\n curr = curr.nxt\n curr = head\n count = 0\n while curr:\n next = curr.nxt\n while next:\n p_sum = int(next.val) + int(curr.val)\n if x - p_sum in map and x - p_sum != next.val and (x - p_sum != curr.val):\n count += 1\n next = next.nxt\n curr = curr.nxt\n return count // 3", "def counttriplets(head, x):\n vals = list()\n while head:\n vals.append(head.val)\n head = head.nxt\n vals = sorted(vals)\n ans = set()\n n = len(vals)\n for i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n new_sum = vals[i] + vals[j] + vals[k]\n if new_sum == x:\n ans.add((i, j, k))\n j += 1\n k -= 1\n elif new_sum > x:\n k -= 1\n else:\n j += 1\n return len(ans)", "def counttriplets(head, x):\n curr = head\n l = []\n while curr != None:\n l.append(curr.val)\n curr = curr.nxt\n n = len(l)\n l.sort()\n ans = 0\n for i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n sum1 = l[i] + l[j] + l[k]\n if sum1 == x:\n ans += 1\n j += 1\n k -= 1\n elif sum1 > x:\n k -= 1\n else:\n j += 1\n return ans", "def counttriplets(head, x):\n lst = []\n count = 0\n temp = head\n while temp is not None:\n lst.append(temp.val)\n temp = temp.nxt\n lst.sort()\n i = 0\n while i < len(lst) - 2:\n j = i + 1\n k = len(lst) - 1\n while j < len(lst) - 1 and j < k:\n if lst[i] + lst[j] + lst[k] == x:\n count += 1\n j += 1\n elif lst[i] + lst[j] + lst[k] < x:\n j += 1\n else:\n k -= 1\n i += 1\n return count", "def counttriplets(head, x):\n u = []\n t = head\n c = 0\n while t:\n u.append(t.val)\n t = t.nxt\n u = sorted(u)\n for i in range(len(u) - 2):\n l = i + 1\n r = len(u) - 1\n while l < r:\n if u[i] + u[l] + u[r] == x:\n c += 1\n l += 1\n r -= 1\n if u[i] + u[l] + u[r] > x:\n r = r - 1\n if u[i] + u[l] + u[r] < x:\n l += 1\n return c", "def counttriplets(head, x):\n list1 = []\n while head:\n list1.append(head.val)\n head = head.nxt\n list1.sort()\n count = 0\n n = len(list1)\n for i in range(n - 2):\n l = i + 1\n r = n - 1\n while l < r:\n summ = list1[i] + list1[l] + list1[r]\n if summ == x:\n count += 1\n l += 1\n r -= 1\n elif summ < x:\n l += 1\n else:\n r -= 1\n return count", "def counttriplets(head, x):\n l = list()\n curr = head\n while curr:\n l.append(curr.val)\n curr = curr.nxt\n l.sort()\n count = 0\n n = len(l)\n for i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n if l[i] + l[j] + l[k] < x:\n j += 1\n elif l[i] + l[j] + l[k] > x:\n k -= 1\n else:\n count += 1\n j += 1\n k -= 1\n return count", "def counttriplets(head, x):\n a = []\n itr = head\n count = 0\n while itr:\n a.append(itr.val)\n itr = itr.nxt\n a.sort()\n for i in range(len(a) - 2):\n start = i + 1\n end = len(a) - 1\n while start < end:\n if a[i] + a[start] + a[end] > x:\n end -= 1\n elif a[i] + a[start] + a[end] < x:\n start += 1\n else:\n count += 1\n start += 1\n return count", "def counttriplets(head, x):\n d = []\n temp = head\n while temp:\n d.append(temp.val)\n temp = temp.nxt\n d.sort()\n cnt = 0\n for i in range(len(d) - 2):\n l = i + 1\n h = len(d) - 1\n while l < h:\n if d[i] + d[l] + d[h] == x:\n cnt += 1\n l += 1\n if d[i] + d[l] + d[h] < x:\n l += 1\n else:\n h -= 1\n return cnt", "def counttriplets(head, x):\n d = {}\n v = []\n t = head\n while t != None:\n v.append(t.val)\n d[t.val] = len(v) - 1\n t = t.nxt\n count = 0\n for i in range(len(v)):\n o = x - v[i]\n for j in range(i + 1, len(v)):\n l = o - v[j]\n if d.get(l) and d[l] > j:\n count += 1\n return count", "import collections\n\ndef counttriplets(head, x):\n arr = []\n dup = head\n while dup:\n arr.append(dup.val)\n dup = dup.nxt\n arr = arr[::-1]\n carr = collections.Counter(arr)\n cnt = 0\n for i in range(len(arr)):\n for j in range(i, len(arr)):\n k = x - arr[i] - arr[j]\n if arr[i] != arr[j] != k and carr[k] != 0 and (i < j < arr.index(k)):\n cnt += 1\n return cnt", "def counttriplets(head, x):\n arr = []\n p = 0\n n = 0\n while head:\n arr.append(head.val)\n head = head.nxt\n n += 1\n arr.sort()\n y = []\n for i in range(0, n - 2):\n l = i + 1\n r = n - 1\n while l < r:\n if arr[i] + arr[l] + arr[r] == x:\n p += 1\n l += 1\n r -= 1\n elif arr[i] + arr[l] + arr[r] < x:\n l += 1\n else:\n r -= 1\n return p", "def counttriplets(head, x):\n arr = []\n temp = head\n while temp != None:\n arr.append(temp.val)\n temp = temp.nxt\n c = 0\n arr.sort()\n for i in range(0, len(arr) - 2):\n j = i + 1\n k = len(arr) - 1\n while j < k:\n s = arr[i] + arr[j] + arr[k]\n if s == x:\n c += 1\n j += 1\n k -= 1\n elif s > x:\n k -= 1\n else:\n j += 1\n return c", "from collections import deque\n\ndef countPairs(head, x):\n if head == None or head.nxt == None or x < 2:\n return 0\n dq = deque()\n walk = head\n while walk:\n dq.append(walk.val)\n walk = walk.nxt\n ret = 0\n l = dq.popleft()\n r = dq.pop()\n while 1:\n if l + r == x:\n ret += 1\n if len(dq) == 0:\n return ret\n if l + r > x:\n l = dq.popleft()\n else:\n r = dq.pop()\n\ndef counttriplets(head, x):\n ret = 0\n while head != None:\n ret += countPairs(head.nxt, x - head.val)\n head = head.nxt\n return ret", "def counttriplets(head, x):\n\n def reverse(head):\n prev = None\n curr = head\n fut = head.nxt\n while curr:\n curr.nxt = prev\n prev = curr\n curr = fut\n if fut:\n fut = fut.nxt\n return prev\n\n def insert(head):\n curr = head\n ele = Node(curr.val)\n new = ele\n curr = curr.nxt\n while curr:\n new.nxt = Node(curr.val)\n new = new.nxt\n curr = curr.nxt\n return ele\n new = reverse(insert(head))\n curr = head\n count = 0\n val1 = False\n if head.val < new.val:\n val1 = True\n while curr.nxt.nxt:\n summ = res = curr.val\n temp1 = curr.nxt\n temp2 = new\n while val1 and temp1.val < temp2.val or (not val1 and temp1.val > temp2.val):\n res += temp1.val + temp2.val\n if res == x:\n count += 1\n temp1 = temp1.nxt\n temp2 = temp2.nxt\n elif res > x:\n if temp2.val > temp1.val:\n temp2 = temp2.nxt\n else:\n temp1 = temp1.nxt\n elif temp1.val > temp2.val:\n temp2 = temp2.nxt\n else:\n temp1 = temp1.nxt\n res = summ\n curr = curr.nxt\n return count", "def counttriplets(head, x):\n a = head\n count = 0\n while a != None:\n p = x - a.val\n s = set()\n q = a.nxt\n while q != None:\n if p - q.val in s:\n count += 1\n q = q.nxt\n else:\n s.add(q.val)\n q = q.nxt\n a = a.nxt\n return count", "def counttriplets(head, x):\n l = []\n while head != None:\n l.append(head.val)\n head = head.nxt\n n = len(l)\n if n <= 2:\n return 0\n if l[0] > l[-1]:\n l = l[::-1]\n i = 0\n ans = 0\n while i < n - 2:\n req = x - l[i]\n j = i + 1\n k = n - 1\n while j < k:\n if l[j] + l[k] == req:\n ans += 1\n curr = l[j]\n while j < k and l[j] == curr:\n j += 1\n curr = l[k]\n while j < k and l[k] == curr:\n k -= 1\n elif l[j] + l[k] < req:\n curr = l[j]\n while j < k and l[j] == curr:\n j += 1\n else:\n curr = l[k]\n while j < k and l[k] == curr:\n k -= 1\n curr = l[i]\n while i < n - 2 and l[i] == curr:\n i += 1\n return ans", "def counttriplets(head, x):\n l = []\n res = 0\n if not head:\n return 0\n while head:\n l.append(head.val)\n head = head.nxt\n l.sort()\n for i in range(len(l) - 2):\n left = i + 1\n right = len(l) - 1\n while left < right:\n k = l[i] + l[right] + l[left]\n if k == x:\n res += 1\n left += 1\n right -= 1\n elif k > x:\n right -= 1\n else:\n left += 1\n return res"], "starter_code": "def counttriplets(head,x):\n", "input_output": {"fn_name": "countTriplets", "inputs": ["LinkedList:9->8->6->5->4->2->1, X = 17", "LinkedList:9->8->6->5->4->2->1, X = 15"], "outputs": ["2", "5"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Algorithms", "Mathematical", "Linked List"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/87f12e5c728d69a5322634776b54c75897d14daa/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N^{2})", "entry_point": "counttriplets", "task_id": "TACO_lite/210", "example": [[], []]} +{"requirement": "An array is said to be `hollow` if it contains `3` or more `0`s in the middle that are preceded and followed by the same number of non-zero elements. Furthermore, all the zeroes in the array must be in the middle of the array. \n\nWrite a function named `isHollow`/`is_hollow`/`IsHollow` that accepts an integer array and returns `true` if it is a hollow array,else `false`.", "solutions": ["def is_hollow(x):\n while x and x[0] != 0 and (x[-1] != 0):\n x = x[1:-1]\n return len(x) > 2 and set(x) == {0}", "from itertools import groupby\nfrom operator import not_\n\ndef is_hollow(a):\n b = [(x, [*y]) for (x, y) in groupby(a, key=not_)]\n return len(b) == 1 and b[0][0] and (len(b[0][1]) > 2) or (len(b) == 3 and [x for (x, _) in b] == [0, 1, 0] and (len(b[1][1]) > 2) and (len(b[0][1]) == len(b[2][1])))", "from itertools import groupby\n\ndef is_hollow(x):\n xs = [(key, sum((1 for _ in grp))) for (key, grp) in groupby(x)]\n mid = len(xs) // 2\n limit = len(xs) - (len(xs) > 1)\n return any((i == mid < limit for (i, (x, cnt)) in enumerate(xs) if x == 0 and cnt >= 3)) and sum((x == 0 for (x, _) in xs)) == 1", "def is_hollow(x):\n return len(x) > 2 and (x[0] and x[-1] and is_hollow(x[1:-1]) or set(x) == {0})", "from re import match\n\ndef is_hollow(x):\n return bool(match('(x*)[0]{3,}\\\\1$', ''.join(('x' if v else '0' for v in x))))", "def is_hollow(x):\n if len(x) < 3:\n return False\n z = 0\n for (i, (a, b)) in enumerate(zip(x, x[::-1])):\n if i > len(x) // 2:\n return z >= 2\n if (a == 0) != (b == 0):\n return False\n if a != 0 and z > 0:\n return False\n if a == 0:\n z += 1\n elif z > 0:\n return False", "def is_hollow(A):\n while A and A[0] * A[-1] != 0:\n A = A[1:-1]\n return 2 < A.count(0) and set(A) == {0}", "import re\n\ndef is_hollow(x):\n return True if re.match('^(1*)0{3,}\\\\1$', ''.join(('0' if i == 0 else '1' for i in x))) else False", "def is_hollow(x):\n i = j = len(x) // 2\n while i > 0 and x[i - 1] == 0:\n i -= 1\n while j < len(x) and x[j] == 0:\n j += 1\n prefix = x[:i]\n suffix = x[j:]\n return not (j - i < 3 or 0 in prefix + suffix or len(prefix) != len(suffix))"], "starter_code": "def is_hollow(x):\n", "input_output": {"fn_name": "is_hollow", "inputs": [[[-1, 0, 0, 0, 3]], [[1, 0, 0, 0, 0]]], "outputs": [[true], [false]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/59b72376460387017e000062", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_hollow", "task_id": "TACO_lite/244", "example": [[], []]} +{"requirement": "We have N persons sitting on a round table. Any person can do a handshake with any other person. \n 1\n2 3\n 4\nHandshake with 2-3 and 1-4 will cause cross.\nIn how many ways these N people can make handshakes so that no two handshakes cross each other. N would be even. \n \nExample 1:\nInput:\nN = 2\nOutput:\n1\nExplanation:\n{1,2} handshake is\npossible.\nExample 2:\nInput:\nN = 4\nOutput:\n2\nExplanation:\n{{1, 2}, {3, 4}} are the\ntwo handshakes possible.\n{{1, 3}, {2, 4}} is another\nset of handshakes possible.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function count() which takes an integer N as input parameters and returns an integer, the total number of handshakes possible so that no two handshakes cross each other.\n \nExpected Time Complexity: O(2^{N})\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= N <= 30", "solutions": ["def count(N):\n\n def findCatalan(x):\n if x == 0 or x == 1:\n return 1\n result = 0\n for i in range(0, x):\n result += findCatalan(i) * findCatalan(x - i - 1)\n return result\n return findCatalan(N // 2)", "def count(N):\n dp = [0] * (N // 2 + 1)\n dp[0] = 1\n for i in range(1, len(dp)):\n for j in range(i):\n dp[i] += dp[j] * dp[i - 1 - j]\n return dp[N // 2]", "def count(N):\n if N % 2 == 1:\n return 0\n dp = [1] * (N + 1)\n for i in range(4, N + 1):\n (tmp, M) = (0, i - 2)\n for j in range(0, M // 2, 2):\n tmp += dp[j] * dp[M - j]\n tmp *= 2\n if M % 4 == 0:\n tmp += dp[M // 2] * dp[M // 2]\n dp[i] = tmp\n return dp[N]", "def rec(N, dp):\n if N == 0:\n return 1\n if N % 2:\n return 0\n if N in dp:\n return dp[N]\n ans = 0\n for i in range(2, N + 1):\n ans += rec(i - 1 - 1, dp) * rec(N - i, dp)\n dp[N] = ans\n return ans\n\ndef count(N):\n dp = {}\n return rec(N, dp)", "d = {0: 1, 2: 1, 4: 2}\n\ndef count(N):\n if N % 2 != 0:\n N -= 1\n if N in d:\n return d[N]\n ans = 0\n for j in range(1, N, 2):\n ans += self.count(j - 1) * self.count(N - j - 1)\n return ans", "def count(N):\n result = 0\n if N % 2 == 1:\n return 0\n elif N == 0:\n return 1\n for i in range(0, N, 2):\n result += self.count(i) * self.count(N - 2 - i)\n return result", "def hand(N):\n if N <= 2:\n return 1\n ans = 0\n for i in range(0, N, 2):\n ans += hand(i) * hand(N - i - 2)\n return ans\n\ndef count(N):\n ans = hand(N)\n return ans", "def solve(N, dict_hand):\n if N <= 2:\n return 1\n if N in dict_hand:\n return dict_hand[N]\n ans = 0\n for i in range(0, N, 2):\n ans += self.solve(i, dict_hand) * self.solve(N - i - 2, dict_hand)\n dict_hand[N] = ans\n return ans\n\ndef count(N):\n dict_hand = {2: 1}\n self.solve(N, dict_hand)\n return dict_hand[N]", "def count(N):\n if N & 1:\n return 0\n if N == 0:\n return 1\n total = 0\n for i in range(N):\n total += self.count(i) * self.count(N - i - 2)\n return total", "def count(N):\n d = {}\n\n def helper(x):\n if x == 0 or x == 1:\n return 1\n if x in d:\n return d[x]\n ans = 0\n for i in range(x):\n ans += helper(i) * helper(x - i - 1)\n d[x] = ans\n return d[x]\n return helper(N // 2)", "def count(N):\n if N % 2 == 1:\n return 0\n kMod = 1000000007\n dp = [0] * (N + 1)\n dp[0] = 1\n for i in range(2, N + 1):\n for j in range(2, i + 1, 2):\n dp[i] += dp[j - 2] * dp[i - j] % kMod\n return dp[-1] % kMod", "def count(n):\n if n == 0:\n return 1\n ans = 0\n for i in range(0, n, 2):\n ans += self.count(i) * self.count(n - 2 - i)\n return ans", "def count(N, dic={}):\n if N == 0:\n return 1\n if N in dic:\n return dic[N]\n res = 0\n for i in range(0, N, 2):\n res += self.count(i, dic) * self.count(N - i - 2, dic)\n dic[N] = res\n return dic[N]", "from collections import defaultdict\n\ndef __init__():\n self.hmap[0] = 1\n\ndef count(n):\n if n in self.hmap:\n return self.hmap[n]\n for i in range(0, n, 2):\n self.hmap[n] += self.count(i) * self.count(n - i - 2)\n return self.hmap[n]", "def count(N):\n\n def catalan(n):\n dp = [0] * (n + 1)\n dp[0] = 1\n for i in range(1, n + 1):\n dp[i] = 0\n for j in range(i):\n dp[i] += dp[j] * dp[i - j - 1]\n return dp[n]\n return catalan(N // 2)", "def handShake(p):\n dp = [0 for _ in range(p + 1)]\n dp[0] = dp[1] = 1\n for i in range(2, p + 1, 2):\n for j in range(0, i - 1, 2):\n dp[i] += dp[j] * dp[i - 2 - j]\n return dp[-1]\n\ndef count(N):\n return handShake(N)", "def count(N):\n return self.catalan(N // 2)\n\ndef catalan(n):\n if n <= 1:\n return 1\n res = 0\n for i in range(n):\n res += self.catalan(i) * self.catalan(n - i - 1)\n return res", "def helper(x):\n if x == 0 or x == 1:\n return 1\n res = 0\n for i in range(x):\n a = self.helper(i)\n b = self.helper(x - i - 1)\n res += a * b\n return res\n\ndef count(N):\n res = self.helper(N // 2)\n return res", "def count(N):\n\n def solution(n):\n catalan = [1] * (n + 1)\n for i in range(2, n + 1):\n catalan[i] = 0\n for j in range(i):\n catalan[i] += catalan[j] * catalan[i - j - 1]\n return catalan[n]\n if N % 2 != 0:\n return False\n else:\n return solution(N // 2)", "from functools import lru_cache\n\ndef count(n):\n\n def dp(m):\n if m % 2 == 1:\n return 0\n if m == 0:\n return 1\n ans = 0\n for i in range(0, m, 2):\n ans += dp(i) * dp(m - i - 2)\n return ans\n return dp(n)", "def count(N):\n p = N // 2\n arr = [0] * (p + 1)\n arr[0] = 1\n arr[1] = 1\n for i in range(2, p + 1):\n for j in range(0, p):\n arr[i] += arr[j] * arr[i - j - 1]\n return arr[p]", "def __init__():\n self.ans = 0\n\ndef count(n):\n if n == 0 or n == 2:\n return 1\n else:\n a = n - 2\n b = 0\n ans = 0\n while a >= 0:\n ans += self.count(a) * self.count(b)\n a -= 2\n b += 2\n return ans", "def count(N):\n if N == 2:\n return 1\n if N == 0:\n return 1\n ans = 0\n left = 0\n right = N - 2\n while left <= N - 2:\n ans += self.count(left) * self.count(right)\n left += 2\n right -= 2\n return ans", "def count(N):\n memo = {}\n\n def dp(n):\n if n == 0:\n return 1\n if n & 1:\n return 0\n if n in memo:\n return memo[n]\n ans = 0\n for i in range(2, n + 1):\n grp1 = i - 2\n grp2 = n - i\n ans += dp(grp1) * dp(grp2)\n return ans\n res = dp(N)\n return res", "def count(N):\n if N == 0:\n return 0\n else:\n return int(self.fact(N) / (self.fact(N / 2 + 1) * self.fact(N / 2)))\n\ndef fact(n):\n if n == 1:\n return 1\n else:\n return n * self.fact(n - 1)", "def count(N):\n arr = [0] * (N + 1)\n arr[0] = 1\n if N == 0:\n return arr[0]\n for i in range(2, N + 1, 2):\n temp = 0\n for j in range(0, i, 2):\n temp = temp + arr[j] * arr[i - 2 - j]\n arr[i] = temp\n return arr[N]", "def count(N):\n if N <= 2:\n return 1\n i = N - 2\n sum = 0\n while i >= 0:\n sum += self.count(i) * self.count(N - 2 - i)\n i -= 2\n return sum", "def count(N):\n if N == 0:\n return 0\n if N == 2:\n return 1\n c = 0\n for i in range(0, N - 1, 2):\n left = self.count(i)\n right = self.count(N - 2 - i)\n if left and right:\n c += left * right\n else:\n c += left + right\n return c", "def count(N):\n sum1 = 0\n if N == 0 or N == 2:\n return 1\n else:\n for i in range(0, N, 2):\n sum1 = sum1 + self.count(i) * self.count(N - i - 2)\n return sum1", "def count(N):\n if N == 0:\n return 1\n ans = 0\n for idx in range(0, N, 2):\n ans += self.count(idx) * self.count(N - 2 - idx)\n return ans", "def count(N):\n if N == 0:\n return 1\n answear = 0\n for i in range(0, N, 2):\n ob = Solution()\n answear += ob.count(i) * ob.count(N - 2 - i)\n return answear", "def count(N):\n if N % 2 == 1:\n return 0\n elif N == 0:\n return 1\n res = 0\n i = 0\n while i < N:\n res += self.count(i) * self.count(N - 2 - i)\n i += 2\n return res", "import math\n\ndef catlan(n):\n c = int(math.factorial(2 * n) / (math.factorial(n + 1) * math.factorial(n)))\n return c\n\ndef count(N):\n if N % 2 == 1:\n return 0\n else:\n return catlan(int(N / 2))", "from math import factorial as fac\n\ndef check(n):\n return fac(2 * n) // fac(n + 1) // fac(n)\n\ndef count(N):\n if N % 2 == 1:\n return 0\n return check(N // 2)", "def count(N):\n\n def handshakes(min, max):\n total_handshakes = 0\n if min >= max:\n return 1\n for partner in range(min + 1, max + 1, 2):\n above_handshakes = handshakes(min + 1, partner - 1)\n below_handshakes = handshakes(partner + 1, max)\n total_handshakes += above_handshakes * below_handshakes\n return total_handshakes\n return handshakes(1, N)", "from collections import defaultdict\nd = defaultdict(lambda : 0)\nfor i in range(6, 32, 2):\n (d[0], d[2], d[4]) = (1, 1, 2)\n res = 0\n for j in range(2, i // 2 + 1):\n res += d[j - 2] * d[i - j]\n res *= 2\n res += d[i // 2 - 1] ** 2\n d[i] = res\n\ndef count(N):\n return d[N]"], "starter_code": "def count(N):\n", "input_output": {"inputs": ["N = 2", "N = 4"], "outputs": ["1", "2"]}, "difficulty": "MEDIUM", "raw_tags": ["Recursion", "Algorithms"], "name": null, "source": "geeksforgeeks", "tags": ["Complete search"], "skill_types": ["Complete search"], "url": "https://practice.geeksforgeeks.org/problems/handshakes1303/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(2^{N})", "entry_point": "count", "task_id": "TACO_lite/307", "example": [[[2], [4]], ["1", "2"]]} +{"requirement": "Given a sorted doubly linked list of positive distinct elements, the task is to find pairs in a doubly-linked list whose sum is equal to given value target.\n \nExample 1:\nInput: \n1 <-> 2 <-> 4 <-> 5 <-> 6 <-> 8 <-> 9\ntarget = 7\nOutput: (1, 6), (2,5)\nExplanation: We can see that there are two pairs \n(1, 6) and (2,5) with sum 7.\n \nExample 2:\nInput: \n1 <-> 5 <-> 6\ntarget = 6\nOutput: (1,5)\nExplanation: We can see that there is one pairs (1, 5) with sum 6.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function findPairsWithGivenSum() which takes head node of the doubly linked list and an integer target as input parameter and returns an array of pairs. If there is no such pair return empty array.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 10^{5}\n1 <= target <= 10^{5}", "solutions": ["from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n ans = []\n slow = head\n fast = head\n while fast.next is not None:\n fast = fast.next\n while slow.data < fast.data:\n if slow.data + fast.data == target:\n ans.append((slow.data, fast.data))\n slow = slow.next\n fast = fast.prev\n elif slow.data + fast.data < target:\n slow = slow.next\n else:\n fast = fast.prev\n return ans", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n d = dict()\n cur = head\n res = []\n while cur != None:\n if d.get(target - cur.data, -1) != -1:\n arr = [cur.data, target - cur.data]\n arr.sort()\n res.append(arr)\n d[cur.data] = 1\n cur = cur.next\n res.sort()\n return res", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n res = []\n start = head\n end = head\n while end.next:\n end = end.next\n while start.data < end.data:\n s = start.data + end.data\n if s == target:\n res.append([start.data, end.data])\n start = start.next\n end = end.prev\n elif s < target:\n start = start.next\n else:\n end = end.prev\n return res", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n high = head\n low = head\n temp = []\n while high.next != None:\n high = high.next\n while low.data < high.data:\n sum = low.data + high.data\n if sum > target:\n high = high.prev\n elif sum < target:\n low = low.next\n else:\n temp.append([low.data, high.data])\n low = low.next\n high = high.prev\n return temp", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n result = []\n if not head:\n return result\n tail = head\n while tail.next:\n tail = tail.next\n while head and tail and (head.data < tail.data):\n (headVal, tailVal) = (head.data, tail.data)\n currVal = headVal + tailVal\n if currVal == target:\n result.append((headVal, tailVal))\n head = head.next\n tail = tail.prev\n elif currVal > target:\n tail = tail.prev\n else:\n head = head.next\n return result", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n temp = head\n while temp:\n last = temp\n temp = temp.next\n ans = []\n start = head\n while start.data < last.data:\n if start.data + last.data == target:\n ans.append([start.data, last.data])\n start = start.next\n last = last.prev\n elif start.data + last.data > target:\n last = last.prev\n else:\n start = start.next\n return ans", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n first = head\n while first.next:\n first = first.next\n last = first\n first = head\n solution = []\n while first != last:\n if first.data + last.data == target:\n solution.append((first.data, last.data))\n if first.next == last:\n break\n first = first.next\n last = last.prev\n elif first.data + last.data > target:\n last = last.prev\n else:\n first = first.next\n return solution", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n (p1, p2) = (head, head)\n res = []\n while p2.next:\n p2 = p2.next\n while p1 and p2 and (p1.data < p2.data):\n t = p1.data + p2.data\n if t < target:\n p1 = p1.next\n elif t > target:\n p2 = p2.prev\n else:\n res.append([p1.data, p2.data])\n p1 = p1.next\n p2 = p2.prev\n return res", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n ans = []\n temp1 = temp2 = head\n while temp2.next:\n temp2 = temp2.next\n while temp2.data > temp1.data:\n sum = temp2.data + temp1.data\n if sum == target:\n ans.append([temp1.data, temp2.data])\n temp1 = temp1.next\n temp2 = temp2.prev\n elif sum < target:\n temp1 = temp1.next\n else:\n temp2 = temp2.prev\n return ans", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n if target is None:\n return []\n high = head\n while high.next is not None:\n high = high.next\n low = head\n res = []\n while id(low) != id(high):\n sumval = low.data + high.data\n if sumval == target:\n res.append([low.data, high.data])\n if id(low.next) != id(high):\n low = low.next\n high = high.prev\n elif sumval < target:\n low = low.next\n else:\n high = high.prev\n return res", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n end = head\n res = []\n while end.next is not None:\n end = end.next\n start = head\n while start != end:\n if start.data + end.data == target:\n res.append((start.data, end.data))\n start = start.next\n if start == end:\n break\n end = end.prev\n elif start.data + end.data > target:\n end = end.prev\n else:\n start = start.next\n return res", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n left = head\n right = head\n l = []\n while right.next != None:\n right = right.next\n while right != left and right.next != left:\n if left.data + right.data == target:\n l.append((left.data, right.data))\n left = left.next\n right = right.prev\n elif left.data + right.data < target:\n left = left.next\n else:\n right = right.prev\n return l", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n d = {}\n while head:\n d[head.data] = 1\n head = head.next\n a = []\n for i in d:\n if target - i in d and d[target - i] != -1 and (i != target - i):\n a.append(sorted([i, target - i]))\n d[i] = -1\n return sorted(a)", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n if not head.next:\n return []\n res = []\n low = high = head\n while high.next:\n high = high.next\n while low != high:\n if low.data + high.data == target:\n res.append([low.data, high.data])\n low = low.next\n if low == high:\n break\n high = high.prev\n elif low.data + high.data < target:\n low = low.next\n else:\n high = high.prev\n return res", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n tail = head\n while tail.next != None:\n tail = tail.next\n arr = []\n while head.data < tail.data:\n if head.data + tail.data == target:\n arr.append([head.data, tail.data])\n head = head.next\n tail = tail.prev\n elif head.data + tail.data > target:\n tail = tail.prev\n elif head.data + tail.data < target:\n head = head.next\n return arr", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n (fp, lp) = (head, head)\n while lp.next:\n lp = lp.next\n ans = []\n while fp and fp != lp:\n if fp.data + lp.data == target:\n ans.append([fp.data, lp.data])\n fp = fp.next\n elif fp.data + lp.data > target:\n lp = lp.prev\n else:\n fp = fp.next\n return ans", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n tail = head\n start = 1\n end = 1\n while tail.next != None:\n tail = tail.next\n end += 1\n sum = 0\n pairs = []\n while start < end:\n sum = head.data + tail.data\n if sum == target:\n pairs.append([head.data, tail.data])\n sum = 0\n head = head.next\n tail = tail.prev\n start += 1\n end -= 1\n elif sum > target:\n tail = tail.prev\n end -= 1\n else:\n head = head.next\n start += 1\n return pairs", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n (left, right) = (head, head)\n result = []\n while right.next:\n right = right.next\n while left != right:\n temp = left.data + right.data\n if temp == target:\n result.append([left.data, right.data])\n right = right.prev\n elif temp > target:\n right = right.prev\n elif temp < target:\n left = left.next\n return result", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n temp = head\n while temp:\n rear = temp\n temp = temp.next\n res = []\n while head and rear and (head.data < rear.data):\n x = head.data + rear.data\n if x == target:\n res.append((head.data, rear.data))\n head = head.next\n rear = rear.prev\n elif x < target:\n head = head.next\n else:\n rear = rear.prev\n return res", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n arr = []\n cur = head\n while cur.next is not None:\n cur = cur.next\n l = head\n r = cur\n while l != r and l.next != r:\n ld = l.data\n rd = r.data\n if ld + rd == target:\n arr.append((ld, rd))\n l = l.next\n r = r.prev\n elif ld + rd < target:\n l = l.next\n else:\n r = r.prev\n if l != r and l.data + r.data == target:\n arr.append((l.data, r.data))\n return arr"], "starter_code": "def __init__(x):\n", "input_output": {"inputs": ["1 <-> 2 <-> 4 <-> 5 <-> 6 <-> 8 <-> 9\r\ntarget = 7", "1 <-> 5 <-> 6\r\ntarget = 6"], "outputs": ["(1, 6), (2,5)", "(1,5)"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Algorithms", "two-pointer-algorithm", "doubly-linked-list"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Amortized analysis"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/find-pairs-with-given-sum-in-doubly-linked-list/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "__init__", "task_id": "TACO_lite/272", "example": [[], []]} +{"requirement": "Given a string S, find the length of the longest substring with all distinct characters. \nExample 1:\nInput:\nS = \"geeksforgeeks\"\nOutput: 7\nExplanation: \"eksforg\" is the longest \nsubstring with all distinct characters.\nExample 2:\nInput: \nS = \"aaa\"\nOutput: 1\nExplanation: \"a\" is the longest substring \nwith all distinct characters.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function longestSubstrDitinctChars() which takes the string S as input and returns the length of the longest substring with all distinct characters.\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(K), where K is Constant.\nConstraints:\n1<=|S|<=10^{5}", "solutions": ["def longestsubstrdistinctchars(string):\n seen = {}\n maximum_length = 0\n start = 0\n for end in range(len(string)):\n if string[end] in seen:\n start = max(start, seen[string[end]] + 1)\n seen[string[end]] = end\n maximum_length = max(maximum_length, end - start + 1)\n return maximum_length", "def longestsubstrdistinctchars(s):\n (i, j, k) = (0, 0, 0)\n for i in range(len(s) + 1):\n if len(s[j:i]) == len(set(s[j:i])):\n k = max(len(s[j:i]), k)\n else:\n while len(s[j:i]) != len(set(s[j:i])) and j < i:\n j += 1\n k = max(len(s[j:i]), k)\n k = max(len(s[j:i]), k)\n return k", "def longestsubstrdistinctchars(str):\n n = len(str)\n res = 0\n for i in range(n):\n visited = [0] * 256\n for j in range(i, n):\n if visited[ord(str[j])] == True:\n break\n else:\n res = max(res, j - i + 1)\n visited[ord(str[j])] = True\n visited[ord(str[i])] = False\n return res", "def longestsubstrdistinctchars(S):\n i = 0\n j = 0\n ans = []\n l = []\n while j < len(S):\n if S[j] not in l:\n l.append(S[j])\n j += 1\n else:\n l = []\n res = i + 1\n i += 1\n j = res\n ans.append(j - i)\n return max(ans)", "def longestsubstrdistinctchars(S):\n long_len = 0\n st = 0\n dct = {}\n for i in range(len(S)):\n if S[i] in dct:\n st = max(st, dct[S[i]] + 1)\n dct[S[i]] = i\n long_len = max(long_len, i - st + 1)\n return long_len", "def longestsubstrdistinctchars(S):\n visited = {}\n maxLen = 0\n start = 0\n for i in range(len(S)):\n if S[i] in visited:\n start = max(start, visited[S[i]] + 1)\n maxLen = max(maxLen, i - start + 1)\n visited[S[i]] = i\n return maxLen", "def longestsubstrdistinctchars(str):\n if len(S) == 0:\n return 0\n elif len(S) == 1:\n return 1\n else:\n maxLength = -1\n final = ''\n for i in range(0, len(S)):\n char = S[i]\n if S[i] in final:\n final = final[final.index(S[i]) + 1:]\n final = final + S[i]\n maxLength = max(len(final), maxLength)\n return maxLength\n test = ''", "def longestsubstrdistinctchars(str):\n test = ''\n maxLength = -1\n if len(str) == 0:\n return 0\n elif len(str) == 1:\n return 1\n for c in list(str):\n current = ''.join(c)\n if current in test:\n test = test[test.index(current) + 1:]\n test = test + ''.join(c)\n maxLength = max(len(test), maxLength)\n return maxLength", "def longestsubstrdistinctchars(S):\n n = len(S)\n max_len = 0\n start = 0\n seen = {}\n for end in range(n):\n if S[end] in seen and start <= seen[S[end]]:\n start = seen[S[end]] + 1\n else:\n max_len = max(max_len, end - start + 1)\n seen[S[end]] = end\n return max_len", "def longestsubstrdistinctchars(S):\n char = set()\n l = 0\n c = 0\n for r in range(len(S)):\n while S[r] in char:\n char.remove(S[l])\n l += 1\n char.add(S[r])\n c = max(c, len(char))\n return c", "def longestsubstrdistinctchars(s):\n last_index = {}\n max_len = 0\n start_index = 0\n for i in range(len(s)):\n if s[i] in last_index:\n start_index = max(start_index, last_index[s[i]] + 1)\n max_len = max(max_len, i - start_index + 1)\n last_index[s[i]] = i\n return max_len", "def longestsubstrdistinctchars(s):\n n = len(s)\n mx = -1\n (i, j) = (0, 0)\n d = {}\n t = ''\n while i < n and j < n:\n if s[j] in d:\n d = {}\n mx = max(mx, len(t))\n t = ''\n i += 1\n j = i\n else:\n t += s[j]\n d[s[j]] = 1\n j += 1\n return max(len(t), mx)", "def longestsubstrdistinctchars(S):\n s = ''\n d = {}\n m = 0\n l = []\n for i in range(len(S)):\n s = ''\n for j in range(i, len(S)):\n if S[j] not in d:\n s += S[j]\n d[S[j]] = 1\n else:\n break\n if len(s) > m:\n m = len(s)\n d = {}\n return m", "def longestsubstrdistinctchars(s):\n letters = set()\n l = 0\n res = 0\n for i in range(len(s)):\n while s[i] in letters:\n letters.remove(s[l])\n l += 1\n letters.add(s[i])\n res = max(res, i - l + 1)\n return res", "def longestsubstrdistinctchars(S):\n t = {}\n m = ''\n l = []\n i = 0\n while i < len(S):\n if S[i] not in t:\n t[S[i]] = i\n m = m + S[i]\n i = i + 1\n else:\n l.append(len(m))\n i = t[S[i]] + 1\n t = {}\n m = ''\n if m != '':\n l.append(len(m))\n k = max(l)\n return k", "def longestsubstrdistinctchars(S):\n m = 0\n for i in range(len(S)):\n c = 0\n l = []\n for j in range(i, len(S)):\n if S[j] in l:\n break\n else:\n l.append(S[j])\n c += 1\n m = max(m, c)\n return m", "def longestsubstrdistinctchars(S):\n lst = [0] * 26\n l = 0\n r = 0\n sub = ''\n lth = 0\n curr = 0\n for i in range(len(S)):\n x = ord(S[i]) - 97\n if lst[x] != 0:\n while lst[x] != 0:\n lst[ord(S[l]) - 97] = 0\n l += 1\n curr -= 1\n sub += chr(x + 97)\n lst[x] += 1\n r += 1\n curr += 1\n if curr > lth:\n lth = curr\n return lth", "def longestsubstrdistinctchars(S):\n c = 0\n maxlen = 0\n st = []\n for i in range(len(S)):\n if S[i] not in st:\n st.append(S[i])\n c += 1\n if c > maxlen:\n maxlen = c\n else:\n while st.pop(0) != S[i]:\n continue\n st.append(S[i])\n c = len(st)\n if c > maxlen:\n maxlen = c\n return maxlen", "def longestsubstrdistinctchars(S):\n d = {}\n m = 0\n i = 0\n for j in range(len(S)):\n if S[j] not in d:\n d[S[j]] = j\n else:\n if len(d) > m:\n m = len(d)\n i = d[S[j]] + 1\n d1 = d.copy()\n for k in d:\n if d1[k] < i:\n del d1[k]\n d = d1\n d[S[j]] = j\n if m < len(d):\n return len(d)\n return m", "def longestsubstrdistinctchars(S):\n setStr = set()\n l = 0\n res = 0\n for i in range(len(S)):\n while S[i] in setStr:\n setStr.remove(S[l])\n l += 1\n setStr.add(S[i])\n res = max(res, i - l + 1)\n return res", "def longestsubstrdistinctchars(S):\n char_set = set()\n left = 0\n max_len = 0\n for right in range(len(S)):\n while S[right] in char_set:\n char_set.remove(S[left])\n left += 1\n char_set.add(S[right])\n max_len = max(max_len, right - left + 1)\n return max_len", "def longestsubstrdistinctchars(s):\n i = 0\n j = 0\n k = 1\n maxi = 0\n n = len(s)\n while k < n and j < n:\n if s[k] in s[i:j + 1]:\n i += 1\n j = i\n k = i + 1\n else:\n j += 1\n k += 1\n length = len(s[i:j + 1])\n maxi = max(maxi, length)\n return maxi", "def longestsubstrdistinctchars(S):\n n = len(S)\n chars = set()\n i = j = max_len = 0\n while i < n and j < n:\n if S[j] not in chars:\n chars.add(S[j])\n j += 1\n max_len = max(max_len, j - i)\n else:\n chars.remove(S[i])\n i += 1\n return max_len", "def longestsubstrdistinctchars(S):\n charSet = set()\n l = 0\n res = 0\n for r in range(len(S)):\n while S[r] in charSet:\n charSet.remove(S[l])\n l += 1\n charSet.add(S[r])\n res = max(res, r - l + 1)\n return res", "def longestsubstrdistinctchars(S):\n l = ''\n maxL = -1\n if len(S) == 0:\n return 0\n elif len(S) == 1:\n return 1\n for c in list(S):\n curr = ''.join(c)\n if curr in l:\n l = l[l.index(curr) + 1:]\n l = l + ''.join(c)\n maxL = max(len(l), maxL)\n return maxL", "def longestsubstrdistinctchars(S):\n max_len_substr = 0\n substrin = []\n for i in range(len(S)):\n if S[i] in substrin:\n ind = substrin.index(S[i])\n max_len_substr = max(max_len_substr, len(substrin))\n substrin = substrin[ind + 1:]\n substrin.append(S[i])\n else:\n substrin.append(S[i])\n return max(max_len_substr, len(substrin))", "def longestsubstrdistinctchars(S):\n dic = {}\n maxi = 0\n start = 0\n for i in range(len(S)):\n if S[i] not in dic:\n dic[S[i]] = i\n else:\n if dic[S[i]] != -1:\n while start < dic[S[i]] + 1:\n dic[start] = -1\n start += 1\n dic[S[i]] = i\n maxi = max(maxi, i - start + 1)\n return maxi", "def longestsubstrdistinctchars(s):\n n = len(s)\n chars = set()\n start = end = max_len = 0\n while end < n:\n if s[end] not in chars:\n chars.add(s[end])\n end += 1\n max_len = max(max_len, end - start)\n else:\n chars.remove(s[start])\n start += 1\n return max_len", "def longestsubstrdistinctchars(S):\n maxi = 0\n l = []\n for i in S:\n while i in l:\n l.remove(l[0])\n l.append(i)\n if maxi < len(l):\n maxi = len(l)\n return maxi", "def longestsubstrdistinctchars(S):\n sett = set()\n result = 0\n (leftPtr, rightPtr) = (0, 0)\n for rightPtr in range(len(S)):\n while S[rightPtr] in sett:\n sett.remove(S[leftPtr])\n leftPtr += 1\n sett.add(S[rightPtr])\n result = max(result, len(sett))\n return result", "def longestsubstrdistinctchars(S):\n l = []\n d = {}\n start = 0\n r = ''\n m = 0\n i = 0\n while i < len(S):\n if S[i] not in d:\n d[S[i]] = 1\n r = r + S[i]\n m += 1\n i += 1\n else:\n l.append(m)\n j = r.index(S[i])\n i = start + j + 1\n start = i\n r = ''\n m = 0\n d = {}\n l.append(m)\n if l == []:\n return m\n return max(l)", "def longestsubstrdistinctchars(s):\n d = {}\n ws = 0\n n = len(s)\n ans = 0\n for we in range(n):\n while s[we] in d:\n d[s[ws]] -= 1\n if d[s[ws]] == 0:\n del d[s[ws]]\n ws += 1\n d[s[we]] = 1\n ans = max(ans, we - ws + 1)\n return ans", "def longestsubstrdistinctchars(S):\n hashmap = {}\n left = 0\n right = 0\n i = -1\n j = -1\n max_len = -int(1000000000.0)\n while right < len(S):\n if S[right] not in hashmap:\n hashmap[S[right]] = 1\n else:\n while left <= right and S[right] in hashmap and (hashmap[S[right]] == 1):\n hashmap[S[left]] -= 1\n if hashmap[S[left]] == 0:\n del hashmap[S[left]]\n left += 1\n hashmap[S[right]] = 1\n if i == -1 and j == -1:\n i = left\n j = right\n elif j - i < right - left:\n i = left\n j = right\n max_len = max(max_len, j - i + 1)\n right += 1\n return max_len", "def longestsubstrdistinctchars(S):\n (window_start, max_len, last_char_index_map) = (0, 0, {})\n for window_end in range(len(S)):\n if S[window_end] in last_char_index_map:\n window_start = max(window_start, last_char_index_map[S[window_end]] + 1)\n last_char_index_map[S[window_end]] = window_end\n max_len = max(max_len, window_end - window_start + 1)\n return max_len", "def longestsubstrdistinctchars(S):\n dict1 = {}\n l = 0\n size = 0\n j = 0\n for i in range(len(S)):\n if S[i] in dict1:\n while S[i] in dict1:\n del dict1[S[j]]\n j += 1\n size -= 1\n dict1[S[i]] = 1\n size += 1\n else:\n dict1[S[i]] = 1\n size += 1\n if size > l:\n l = size\n return l", "def longestsubstrdistinctchars(S):\n windowStart = 0\n maxCount = 0\n hashSet = set()\n for i in range(len(S)):\n while S[i] in hashSet:\n hashSet.remove(S[windowStart])\n windowStart += 1\n hashSet.add(S[i])\n maxCount = max(maxCount, i - windowStart + 1)\n return maxCount", "def check(ar, i, j):\n dic = {}\n while j < len(ar):\n if ar[j] not in dic:\n dic[ar[j]] = 1\n else:\n break\n j += 1\n return len(dic)\n\ndef longestsubstrdistinctchars(S):\n i = 0\n ar = list(S)\n ans = 0\n while i < len(S):\n k = self.check(ar, i, i)\n ans = max(k, ans)\n i += 1\n return ans", "def longestsubstrdistinctchars(S):\n start = end = max_len = 0\n char_dict = {}\n for (i, c) in enumerate(S):\n if c in char_dict and char_dict[c] >= start:\n max_len = max(max_len, end - start)\n start = char_dict[c] + 1\n char_dict[c] = i\n end += 1\n return max(max_len, end - start)", "def longestsubstrdistinctchars(S):\n (a, maxa, i) = ('', '', 0)\n while i < len(S):\n if S[i] not in a:\n a += S[i]\n if len(a) >= len(maxa):\n maxa = a\n else:\n if len(a) >= len(maxa):\n maxa = a\n if i > 0 and S[i - 1] == S[i]:\n a = S[i]\n else:\n l = -1\n s = []\n r = a.index(S[i])\n for _ in range(S.count(a)):\n l = S.index(a, l + 1)\n s.append(l)\n if len(s) > 1:\n s = [j for j in s if j < i]\n i = r + s[-1]\n a = ''\n i += 1\n return len(maxa)", "def longestsubstrdistinctchars(S):\n left = 0\n res = 0\n cur = set()\n for right in range(len(S)):\n while S[right] in cur:\n cur.remove(S[left])\n left += 1\n cur.add(S[right])\n res = max(res, right - left + 1)\n return res", "def isValid(arr, i):\n seen = {}\n while i < len(arr):\n if arr[i] not in seen:\n seen[arr[i]] = 1\n else:\n break\n i += 1\n return len(seen)\n\ndef longestsubstrdistinctchars(arr):\n i = 0\n ans = 0\n while i < len(arr):\n k = isValid(arr, i)\n ans = max(k, ans)\n i += 1\n return ans", "def longestsubstrdistinctchars(s):\n (l, ml, i, n) = (0, 0, 0, len(s))\n while i < n - l:\n l = 0\n alfa = {}\n for j in range(i, n):\n if s[j] in alfa:\n ml = max(l, ml)\n break\n else:\n alfa.update({s[j]: j})\n l += 1\n i = alfa[s[j]] + 1\n return max(ml, l)", "def longestsubstrdistinctchars(S):\n s = ''\n m1 = -1\n if len(S) == 0:\n return 0\n elif len(S) == 1:\n return 1\n for i in list(S):\n ans = ''.join(i)\n if ans in s:\n s = s[s.index(ans) + 1:]\n s += ''.join(i)\n m1 = max(len(s), m1)\n return m1", "def longestsubstrdistinctchars(S):\n a = []\n maxm = 0\n if len(S) == 1:\n return 1\n for i in S:\n if i not in a:\n a.append(i)\n else:\n if maxm < len(a):\n maxm = len(a)\n c = a.index(i)\n a = a[c + 1:]\n a.append(i)\n if maxm < len(a):\n return len(a)\n return maxm", "def longestsubstrdistinctchars(S):\n n = len(S)\n if n == 0:\n return 0\n longest_substring = ''\n current_substring = ''\n for i in range(n):\n if S[i] not in current_substring:\n current_substring += S[i]\n if len(current_substring) > len(longest_substring):\n longest_substring = current_substring\n else:\n current_substring = current_substring[current_substring.index(S[i]) + 1:] + S[i]\n return len(longest_substring)", "def longestsubstrdistinctchars(S):\n st = 0\n occ = {}\n max_len = 0\n for i in range(0, len(S)):\n if S[i] in occ.keys():\n st = max(st, occ[S[i]] + 1)\n occ[S[i]] = i\n max_len = max(max_len, i - st + 1)\n return max_len", "def longestsubstrdistinctchars(S):\n (i, j, k, max_ln, n) = (0, 0, 1, 0, len(S))\n while k < n and j < n:\n if S[k] in S[i:j + 1]:\n i += 1\n (j, k) = (i, i + 1)\n else:\n j += 1\n k += 1\n length = len(S[i:j + 1])\n max_ln = max(max_ln, length)\n return max_ln", "def longestsubstrdistinctchars(S):\n (l, l1) = ([], [])\n s1 = ''\n for i in range(len(S)):\n s1 = S[i]\n for j in range(i + 1, len(S)):\n if S[j] not in s1:\n if S[j] != S[i]:\n s1 += S[j]\n else:\n break\n else:\n break\n l.append(s1)\n continue\n for i in l:\n l1.append(len(i))\n return max(l1)", "def longestsubstrdistinctchars(S):\n (i, j, ans, n) = (0, 0, 0, len(S))\n mp = dict()\n while j < n:\n while S[j] in mp:\n mp.pop(S[i])\n i += 1\n if S[j] not in mp:\n mp[S[j]] = 1\n ans = max(ans, j - i + 1)\n j += 1\n return ans", "def longestsubstrdistinctchars(S):\n n = len(S)\n start = 0\n end = 0\n max_length = 0\n char_set = set()\n while end < n:\n if S[end] not in char_set:\n char_set.add(S[end])\n end += 1\n max_length = max(max_length, end - start)\n else:\n char_set.remove(S[start])\n start += 1\n return max_length", "def longestsubstrdistinctchars(S):\n (i, j) = (0, 0)\n s = set()\n n = len(S)\n maxi = 0\n while j < n:\n while S[j] in s:\n s.remove(S[i])\n i += 1\n s.add(S[j])\n maxi = max(maxi, j - i + 1)\n j += 1\n return maxi", "def longestsubstrdistinctchars(s):\n mp = {}\n (i, j) = (0, 0)\n (count, ans) = (0, -1)\n while j < len(s):\n count += 1\n if s[j] in mp:\n mp[s[j]] += 1\n else:\n mp[s[j]] = 1\n if len(mp) == j - i + 1:\n ans = max(ans, count)\n j += 1\n elif len(mp) < j - i + 1:\n while len(mp) < j - i + 1:\n mp[s[i]] -= 1\n count -= 1\n if mp[s[i]] == 0:\n del mp[s[i]]\n i += 1\n j += 1\n return ans", "from collections import defaultdict\n\ndef longestsubstrdistinctchars(S):\n freq = defaultdict(lambda : 0)\n l = r = 0\n m = 0\n while r < len(S):\n freq[S[r]] += 1\n while r < len(S) and freq[S[r]] > 1:\n freq[S[l]] -= 1\n l += 1\n m = max(m, r - l + 1)\n r += 1\n return m", "def longestsubstrdistinctchars(S):\n n = len(S)\n if len(S) == 0:\n return 0\n left = 0\n right = 0\n maxlen = 0\n l = set()\n while right < n:\n if S[right] not in l:\n l.add(S[right])\n right = right + 1\n maxlen = max(maxlen, len(l))\n else:\n l.remove(S[left])\n left = left + 1\n return maxlen", "def longestsubstrdistinctchars(S):\n left = 0\n n = len(S)\n maxLength = 0\n dic = dict()\n for right in range(n):\n if S[right] in dic and dic[S[right]] >= left:\n left = dic[S[right]] + 1\n dic[S[right]] = right\n maxLength = max(maxLength, right - left + 1)\n return maxLength", "def longestsubstrdistinctchars(S):\n n = len(S)\n max_len = 0\n left = 0\n char_dict = {}\n for right in range(n):\n if S[right] in char_dict and char_dict[S[right]] >= left:\n left = char_dict[S[right]] + 1\n char_dict[S[right]] = right\n max_len = max(max_len, right - left + 1)\n return max_len", "def longestsubstrdistinctchars(S):\n res = 0\n m = 0\n x = [i for i in S]\n d = {}\n for i in range(len(x)):\n if x[i] in d:\n res = max(d[x[i]] + 1, res)\n m = max(m, i - res + 1)\n d[x[i]] = i\n return m", "def longestsubstrdistinctchars(s):\n max_length = 0\n for i in range(len(s)):\n seen = set()\n for j in range(i, len(s)):\n if s[j] in seen:\n break\n else:\n seen.add(s[j])\n max_length = max(max_length, len(seen))\n return max_length", "def longestsubstrdistinctchars(S):\n test = ''\n maxlen = -1\n if len(S) == 0:\n return 0\n if len(S) == 1:\n return 1\n for i in list(S):\n current = ''.join(i)\n if current in test:\n test = test[test.index(i) + 1:]\n test = test + ''.join(i)\n maxlen = max(len(test), maxlen)\n return maxlen", "def longestsubstrdistinctchars(s):\n n = len(s)\n dic = {}\n ans = 0\n i = j = 0\n while j < n:\n if s[j] not in dic:\n dic[s[j]] = j\n else:\n ans = max(ans, j - i)\n while s[j] in dic:\n del dic[s[i]]\n i += 1\n dic[s[j]] = j\n j += 1\n if j == n and s[j - 1] in dic:\n ans = max(ans, j - i)\n return ans", "def longestsubstrdistinctchars(s):\n i = 0\n temp = ''\n n = len(s)\n maxi = 0\n d = {}\n while i < n:\n if s[i] not in temp:\n temp += s[i]\n i += 1\n else:\n maxi = max(maxi, len(temp))\n temp = ''\n i = d[s[i]] + 1\n d[s[i - 1]] = i - 1\n else:\n maxi = max(maxi, len(temp))\n return maxi", "def longestsubstrdistinctchars(s):\n i = 0\n j = 0\n k = 1\n m = 0\n n = len(S)\n while k < n and j < n:\n if s[k] in s[i:j + 1]:\n i += 1\n j = i\n k = i + 1\n else:\n j += 1\n k += 1\n l = len(S[i:j + 1])\n m = max(m, l)\n return m", "def longestsubstrdistinctchars(S):\n d = ''\n temp = ''\n for i in S:\n if i not in temp:\n temp += i\n else:\n if len(d) < len(temp):\n d = temp\n j = temp.find(i)\n temp = temp[j + 1:] + i\n if len(d) < len(temp):\n return len(temp)\n return len(d)", "def longestsubstrdistinctchars(S):\n vla = {}\n mx = 0\n st = 0\n i = 0\n while i < len(S):\n if S[i] not in vla:\n vla[S[i]] = i\n i += 1\n else:\n mx = max(mx, i - st)\n st = vla[S[i]] + 1\n vla.clear()\n i = st\n if i >= len(S) - 1:\n return max(mx, i - st)\n return mx", "def longestsubstrdistinctchars(S):\n ans = 0\n curr = ''\n for i in S:\n if i not in curr:\n curr += i\n else:\n ans = max(len(curr), ans)\n curr = curr[curr.index(i) + 1:] + i\n return max(len(curr), ans)", "import math\n\ndef longestsubstrdistinctchars(s):\n maxi = -math.inf\n (i, j) = (0, 0)\n dicti = {}\n n = len(s)\n while j < n:\n if s[j] not in dicti:\n dicti[s[j]] = 1\n else:\n dicti[s[j]] += 1\n if len(dicti) < j - i + 1:\n while len(dicti) < j - i + 1:\n if s[i] in dicti:\n dicti[s[i]] -= 1\n if dicti[s[i]] == 0:\n del dicti[s[i]]\n i += 1\n j += 1\n elif len(dicti) == j - i + 1:\n maxi = max(maxi, j - i + 1)\n j += 1\n return maxi", "def longestsubstrdistinctchars(S):\n a = [-1] * 256\n start = -1\n ans = 0\n for i in range(0, len(S)):\n if a[ord(S[i]) - ord('a')] > start:\n start = a[ord(S[i]) - ord('a')]\n a[ord(S[i]) - ord('a')] = i\n ans = max(ans, i - start)\n return ans", "def longestsubstrdistinctchars(S):\n ans = 0\n n = len(S)\n for i in range(0, n):\n tem = ''\n c = 0\n for j in range(i, n):\n if S[j] in tem:\n ans = max(ans, c)\n break\n else:\n c = c + 1\n tem = tem + S[j]\n ans = max(ans, c)\n return ans", "def longestsubstrdistinctchars(S):\n w = set()\n maxLen = 0\n l = 0\n for r in range(len(S)):\n while S[r] in w:\n w.remove(S[l])\n l += 1\n maxLen = max(maxLen, r - l + 1)\n w.add(S[r])\n return maxLen", "def longestsubstrdistinctchars(S):\n last_idx = {}\n max_len = 0\n start_idx = 0\n for i in range(0, len(S)):\n if S[i] in last_idx:\n start_idx = max(start_idx, last_idx[S[i]] + 1)\n max_len = max(max_len, i - start_idx + 1)\n last_idx[S[i]] = i\n return max_len", "def longestsubstrdistinctchars(S):\n n = len(S)\n last = {}\n max_len = 0\n start = 0\n for i in range(0, n):\n if S[i] in last:\n start = max(start, last[S[i]] + 1)\n max_len = max(max_len, i - start + 1)\n last[S[i]] = i\n return max_len", "def longestsubstrdistinctchars(s):\n max_length = 0\n start = 0\n d = {}\n for i in range(len(s)):\n if s[i] in d:\n while start < i:\n if s[start] == s[i]:\n del d[s[start]]\n start += 1\n break\n else:\n del d[s[start]]\n start += 1\n d[s[i]] = d.get(s[i], 0) + 1\n max_length = max(max_length, i - start + 1)\n return max_length", "def longestsubstrdistinctchars(S):\n f = {}\n start = 0\n end = 0\n maxlen = 0\n n = len(S)\n while end < n:\n f[S[end]] = f.get(S[end], 0) + 1\n if len(f) == end - start + 1:\n maxlen = max(maxlen, end - start + 1)\n else:\n while len(f) != end - start + 1:\n f[S[start]] -= 1\n if f[S[start]] == 0:\n f.pop(S[start])\n start += 1\n end += 1\n return maxlen", "def longestsubstrdistinctchars(S):\n if not S:\n return 0\n max_len = 0\n start = 0\n char_map = {}\n for i in range(len(S)):\n if S[i] in char_map and char_map[S[i]] >= start:\n start = char_map[S[i]] + 1\n else:\n max_len = max(max_len, i - start + 1)\n char_map[S[i]] = i\n return max_len", "def longestsubstrdistinctchars(S):\n if len(S) == 0:\n return 0\n n = len(S)\n s = set()\n s.add(S[0])\n leng = 1\n Max_Len = 0\n i = 1\n while i < n:\n if S[i] != S[i - 1] and S[i] not in s:\n s.add(S[i])\n leng += 1\n i += 1\n if leng > Max_Len:\n Max_Len = leng\n elif leng == 1:\n i += 1\n else:\n s.clear()\n i = i - leng + 1\n leng = 0\n return max(Max_Len, leng)", "def longestsubstrdistinctchars(S):\n dict1 = {}\n count = 1\n maxi = 1\n for k in S:\n if k not in dict1.keys():\n dict1[k] = 1\n dict1 = dict.fromkeys(dict1, 0)\n for i in range(len(S)):\n dict1[S[i]] = 1\n j = i + 1\n while j < len(S):\n if dict1[S[j]] == 1:\n dict1 = dict.fromkeys(dict1, 0)\n count = 1\n break\n else:\n dict1[S[j]] = 1\n count += 1\n maxi = max(maxi, count)\n j += 1\n return maxi", "def longestsubstrdistinctchars(S):\n s = ''\n a = []\n for i in range(len(S)):\n if s == '':\n s += S[i]\n for j in range(i + 1, len(S)):\n if S[j] in s:\n a.append(s)\n s = ''\n break\n else:\n s += S[j]\n return len(max(a, key=len))"], "starter_code": "def longestsubstrdistinctchars(S):\n", "input_output": {"inputs": ["S = \"geeksforgeeks\"", "S = \"aaa\""], "outputs": ["7", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/longest-distinct-characters-in-string5848/1", "Expected Auxiliary Space": "O(K), where K is Constant.", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|).", "entry_point": "longestsubstrdistinctchars", "task_id": "TACO_lite/320", "example": [[["geeksforgeeks"], ["aaa"]], ["7", "1"]]} +{"requirement": "Count the given numbers on your fingers and find the correct finger on which the number ends.\n\tThe first number starts from the thumb, second on the index finger, third on the middle finger, fourth on the ring finger and fifth on the little finger.\n\tAgain six comes on the ring finger and so on.\n\t\nExample 1:\nInput:\nN = 3\nOutput:\n3\nExplanation:\n3 ends on the finger 3.\nExample 2:\nInput:\nN = 6\nOutput:\n4\nExplanation:\n6 ends on the finger 4.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function fingerCount() which takes an integer N as input parameter and returns the finger number on which this number ends.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 10^6", "solutions": ["def fingercount(N):\n rem = N % 8\n if not rem:\n return 2\n if rem <= 5:\n return rem\n else:\n return 5 - rem % 5", "def fingercount(N):\n if N % 8 == 1 or N % 8 == 9:\n return 1\n elif N % 8 == 2 or N % 8 == 8:\n return 2\n elif N % 8 == 3 or N % 8 == 7:\n return 3\n elif N % 8 == 4 or N % 8 == 6:\n return 4\n elif N % 8 == 5 or N % 8 == 13:\n return 5\n elif N % 8 == 0:\n return 2", "def fingercount(N):\n r = N % 8\n if not r:\n return 2\n elif r <= 5:\n return r\n else:\n return 5 - r % 5", "def fingercount(n):\n l = [1, 2, 3, 4, 5, 4, 3, 2]\n ans = n\n k = 0\n ans = ans // 8\n for i in range(0, 8):\n if 8 * ans + i == n:\n return l[i - 1]", "def fingercount(N):\n r = N % 8\n if r == 0:\n return 2\n if r < 5:\n return r\n else:\n return 10 - r", "def fingercount(N):\n n = N % 8\n if n < 6 and n > 0:\n return n\n elif n == 6:\n return 4\n elif n == 7:\n return 3\n elif n == 0:\n return 2", "def fingercount(N):\n if N <= 5:\n return N\n elif N == 6:\n return 4\n elif N == 7:\n return 3\n elif N % 8 == 0:\n return 2\n else:\n x = N % 8\n if x > 5:\n return 5 - (x - 5)\n else:\n return x", "def fingercount(n):\n if n >= 9:\n ans = (n - 9) % 8\n if ans % 8 == 0:\n return 1\n elif ans % 8 == 1 or ans % 8 == 7:\n return 2\n elif ans % 8 == 2 or ans % 8 == 6:\n return 3\n elif ans % 8 == 3 or ans % 8 == 5:\n return 4\n elif ans % 8 == 4:\n return 5\n else:\n ans = n - 1\n if ans % 8 == 0:\n return 1\n elif ans % 8 == 1 or ans % 8 == 7:\n return 2\n elif ans % 8 == 2 or ans % 8 == 6:\n return 3\n elif ans % 8 == 3 or ans % 8 == 5:\n return 4\n elif ans % 8 == 4:\n return 5", "def fingercount(n):\n if n <= 5:\n fingpos = n\n else:\n q = (n - 5) // 4\n rem = (n - 5) % 4\n if q % 2 == 0:\n if rem == 0:\n fingpos = self.odd[3]\n else:\n fingpos = self.even[rem - 1]\n elif rem == 0:\n fingpos = self.even[3]\n else:\n fingpos = self.odd[rem - 1]\n return fingpos", "def fingercount(N):\n if n <= 5:\n return n\n elif (n - 5) % 8 == 1 or (n - 5) % 8 == 7:\n return 4\n elif (n - 5) % 8 == 2 or (n - 5) % 8 == 6:\n return 3\n elif (n - 5) % 8 == 3 or (n - 5) % 8 == 5:\n return 2\n elif (n - 5) % 8 == 4:\n return 1\n else:\n return 5", "def fingercount(N):\n c = 0\n d = N % 8\n if d == 1:\n c = 1\n if d == 0 or d == 2:\n c = 2\n if d == 3 or d == 7:\n c = 3\n if d == 4 or d == 6:\n c = 4\n if d == 5:\n c = 5\n return c", "def fingercount(N):\n N = N % 16\n if N == 1 or N == 9:\n return 1\n if N in [0, 2, 8, 10]:\n return 2\n if N in [3, 7, 11, 15]:\n return 3\n if N in [5, 13]:\n return 5\n if N in [4, 6, 12, 14]:\n return 4", "def fingercount(N):\n finger = N % 8\n if finger >= 6:\n finger = 10 - finger\n elif finger == 0:\n finger = 2\n return finger", "def fingercount(N):\n if N <= 8:\n if N <= 5:\n return N\n else:\n return 10 - N\n else:\n if N % 8 == 1:\n return 1\n if N % 8 == 0 or N % 8 == 2:\n return 2\n if N % 8 == 3 or N % 8 == 7:\n return 3\n if N % 8 == 4 or N % 8 == 6:\n return 4\n if N % 8 == 5:\n return 5", "def fingercount(N):\n no = N % 8\n if no == 0:\n return 2\n elif no < 5:\n return no\n else:\n return 10 - no", "def fingercount(N):\n finger = {0: 2, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 4, 7: 3, 8: 2}\n N %= 8\n return finger[N]", "def fingercount(N):\n round = 0\n temp = N\n if temp < 5:\n return temp\n while temp > 0:\n if round % 2 == 0 and temp >= 5:\n temp = temp - 5\n round += 1\n elif round % 2 == 1 and temp >= 3:\n temp = temp - 3\n round += 1\n else:\n break\n if temp == 0:\n if round % 2 == 1:\n return 5\n else:\n return 2\n elif round % 2 == 1:\n return 5 - temp\n else:\n return temp", "def fingercount(N):\n rem = n % 8\n if rem == 0:\n return 2\n elif rem < 5:\n return rem\n else:\n return 10 - rem", "def fingercount(N):\n rem = N % 8\n if rem == 0 or rem == 2:\n return 2\n elif rem <= 5:\n return rem\n else:\n return 5 - rem % 5", "def fingercount(N):\n a = [4, 3, 2, 1]\n n = (N - 2) // 4\n if n % 2 == 0:\n return (N - 2) % 4 + 2\n else:\n return a[(N - 2) % 4]", "def fingercount(N):\n l1 = [1, 9, 17, 25, 33, 41]\n l2 = [2, 8, 10, 16, 18, 24, 26, 32, 34]\n l3 = [3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43]\n l4 = [4, 6, 12, 14, 20, 22, 28, 30, 36]\n l5 = [5, 13, 21, 29, 37, 45, 53]\n if N % 8 == 1:\n return 1\n elif N % 8 == 0 or N % 8 == 2:\n return 2\n elif N % 8 == 3 or N % 8 == 7:\n return 3\n elif N % 8 == 4 or N % 8 == 6:\n return 4\n elif N % 8 == 5:\n return 5", "def fingercount(N):\n m = N % 8\n if m >= 1 and m <= 5:\n return m\n elif m == 0:\n return 2\n elif m == 7:\n return 3\n elif m == 6:\n return 4", "def fingercount(N):\n t = N % 8\n if t == 0:\n return 2\n if t == 7:\n return 3\n if t == 6:\n return 4\n return t", "def fingercount(N):\n if N <= 5:\n return N\n res1 = (N - 1) / 8 + 1\n if res1 == float(int(res1)):\n return 1\n res1 = (N - 2) / 8 + 1\n res2 = (N - 8) / 8 + 1\n if res1 == float(int(res1)) or res2 == float(int(res2)):\n return 2\n res1 = (N - 3) / 4 + 1\n if res1 == float(int(res1)):\n return 3\n res1 = (N - 4) / 8 + 1\n res2 = (N - 6) / 8 + 1\n if res1 == float(int(res1)) or res2 == float(int(res2)):\n return 4\n res1 = (N - 5) / 8 + 1\n if res1 == float(int(res1)):\n return 5", "def fingercount(N):\n temp = [1, 2, 3, 4, 5, 4, 3, 2]\n return temp[(N - 1) % 8]"], "starter_code": "def fingercount(N):\n", "input_output": {"inputs": ["N = 3", "N = 6"], "outputs": ["3", "4"]}, "difficulty": "EASY", "raw_tags": ["logical-thinking"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/finger-game1755/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "fingercount", "task_id": "TACO_lite/253", "example": [[[3], [6]], ["3", "4"]]} +{"requirement": "Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return `true` if the string is valid, and `false` if it's invalid.\n\n## Examples\n\n```\n\"()\" => true\n\")(()))\" => false\n\"(\" => false\n\"(())((()())())\" => true\n```\n\n## Constraints\n\n`0 <= input.length <= 100`\n\n~~~if-not:javascript,go\nAlong with opening (`(`) and closing (`)`) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all. Do **not** treat other forms of brackets as parentheses (e.g. `[]`, `{}`, `<>`).\n~~~", "solutions": ["def valid_parentheses(string):\n cnt = 0\n for char in string:\n if char == '(':\n cnt += 1\n if char == ')':\n cnt -= 1\n if cnt < 0:\n return False\n return True if cnt == 0 else False", "def valid_parentheses(string):\n count = 0\n for i in string:\n if i == '(':\n count += 1\n elif i == ')':\n count -= 1\n if count < 0:\n return False\n return count == 0", "iparens = iter('(){}[]<>')\nparens = dict(zip(iparens, iparens))\nclosing = parens.values()\n\ndef valid_parentheses(astr):\n stack = []\n for c in astr:\n d = parens.get(c, None)\n if d:\n stack.append(d)\n elif c in closing:\n if not stack or c != stack.pop():\n return False\n return not stack", "def valid_parentheses(symbol_string):\n stack = Stack()\n for char in symbol_string:\n if char == '(':\n stack.push('(')\n elif char == ')':\n if stack.is_empty():\n return False\n else:\n stack.pop()\n if not stack.is_empty():\n return False\n else:\n return True\n\ndef __init__():\n self.items = []\n\ndef push(item):\n self.items.append(item)\n\ndef pop():\n return self.items.pop()\n\ndef peek():\n return self.items[-1]\n\ndef is_empty():\n return self.items == []\n\ndef size():\n return len(self.items)", "def valid_parentheses(string):\n string = ''.join((ch for ch in string if ch in '()'))\n while '()' in string:\n string = string.replace('()', '')\n return not string", "import re\n_regex = '[^\\\\(|\\\\)]'\n\ndef valid_parentheses(string):\n string = re.sub(_regex, '', string)\n while len(string.split('()')) > 1:\n string = ''.join(string.split('()'))\n return string == ''", "def valid_parentheses(s):\n stack = 0\n for char in s:\n if char == '(':\n stack += 1\n if char == ')':\n if not stack:\n return False\n else:\n stack -= 1\n return not stack", "import re\n\ndef valid_parentheses(s):\n try:\n re.compile(s)\n except:\n return False\n return True", "def valid_parentheses(s):\n b = 0\n for c in s:\n if c == '(':\n b += 1\n if c == ')':\n b -= 1\n if b < 0:\n return False\n return b == 0", "def valid_parentheses(string):\n stack = []\n for i in string:\n if i == '(':\n stack.append(i)\n elif i == ')' and (not stack):\n return False\n elif i == ')':\n stack.pop()\n return not stack", "def valid_parentheses(string):\n open_counter = 0\n for i in string:\n if i == '(':\n open_counter = open_counter + 1\n if i == ')':\n open_counter = open_counter - 1\n if open_counter < 0:\n return False\n if open_counter == 0:\n return True\n return False", "def valid_parentheses(string):\n new = ''.join([i for i in string if i in '()'])\n while '()' in new:\n new = new.replace('()', '')\n return len(new) == 0", "def valid_parentheses(string):\n string = ''.join([x for x in string if x == '(' or x == ')'])\n before_reduce = len(string)\n string = string.replace('()', '')\n if string == '':\n return True\n elif before_reduce != len(string):\n return valid_parentheses(string)\n else:\n return False", "def valid_parentheses(string):\n string = ''.join((x for x in string if x in ('(', ')')))\n while '()' in string:\n string = string.replace('()', '')\n return False if len(string) != 0 else True", "def valid_parentheses(string):\n string = ''.join((i for i in string if i == '(' or i == ')'))\n while '()' in string:\n string = string.replace('()', '')\n return string == ''", "def valid_parentheses(string):\n string = [c for c in string if not c.isalpha()]\n string = ''.join(string)\n while '()' in string:\n string = string.replace('()', '')\n return True if len(string) == 0 else False", "def valid_parentheses(s):\n p = '()'\n s = ''.join([e for e in s if e in '()'])\n while p in s:\n s = s.replace(p, '')\n return not s", "def valid_parentheses(string):\n open = 0\n for c in string:\n if c == '(':\n open += 1\n elif c == ')':\n open -= 1\n if open < 0:\n return False\n return open == 0", "def valid_parentheses(string):\n i = 0\n for c in string:\n if c == '(':\n i += 1\n if c == ')':\n i -= 1\n if i < 0:\n return False\n return i == 0", "def valid_parentheses(string):\n count = 0\n for c in [c for c in string if c in '()']:\n count += 1 if c == '(' else -1\n if count < 0:\n return False\n return count == 0", "def valid_parentheses(string):\n string = ''.join([x for x in string if x in '()'])\n try:\n string = string.replace('()', '')\n return valid_parentheses(string) if string else True\n except:\n return False", "def valid_parentheses(s):\n lvl = 0\n for c in s:\n lvl += (c == '(') - (c == ')')\n if lvl < 0:\n return False\n return not lvl", "def valid_parentheses(string):\n depth = 0\n for i in string:\n if i == '(':\n depth += 1\n elif i == ')':\n depth -= 1\n if depth < 0:\n return False\n if depth == 0:\n return True\n else:\n return False", "def valid_parentheses(string):\n count_open = 0\n count_close = 0\n index_open = 0\n index_closed = 0\n for s in string:\n if s == '(':\n count_open += 1\n elif s == ')':\n count_close += 1\n if count_close > count_open:\n return False\n if count_open != count_close:\n return False\n else:\n return True", "import re\n\ndef valid_parentheses(string):\n s = ''.join([i for i in string if i in '()'])\n total = [string]\n while True:\n s = s.replace('()', '')\n total.append(s)\n if total[-1] == total[-2]:\n break\n return True if total[-1] == '' else False", "def valid_parentheses(string):\n str = string\n if str == '':\n return True\n if len(str) > 100:\n str = str[0:100]\n c_open = 0\n exc = 0\n for c in str:\n if c == '(':\n c_open += 1\n if c == ')':\n c_open -= 1\n if c_open < 0:\n exc = 1\n break\n if exc == 1 or c_open != 0:\n return False\n return True", "def valid_parentheses(string):\n counter = 0\n for i in string:\n if i == '(':\n counter += 1\n if i == ')':\n counter -= 1\n if counter < 0:\n return False\n return counter == 0"], "starter_code": "def valid_parentheses(string):\n", "input_output": {"fn_name": "valid_parentheses", "inputs": [[")"], ["("], [""], ["hi)("], ["hi(hi)"], ["hi(hi)("], ["((())()())"], ["(c(b(a)))(d)"], ["hi(hi))("], ["())(()"]], "outputs": [[false], [false], [true], [false], [true], [false], [true], [true], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/52774a314c2333f0a7000688", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "valid_parentheses", "task_id": "TACO_lite/273", "example": [[], []]} +{"requirement": "Given a rectangle of dimensions L x B find the minimum number (N) of identical squares of maximum side that can be cut out from that rectangle so that no residue remains in the rectangle. Also find the dimension K of that square.\nExample 1:\nInput: L = 2, B = 4\nOutput: N = 2, K = 2\nExplaination: 2 squares of 2x2 dimension.\nExample 2:\nInput: L = 6, B = 3\nOutput: N = 2, K = 3\nExplaintion: 2 squares of 3x3 dimension. \nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function minimumSquares() which takes L and B as input parameters and returns a list of 2 integers containing the values of N and K respectively.\nExpected Time Complexity: O(log min(L, B))\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ L, B ≤ 10^{9}", "solutions": ["import math\n\ndef minimumsquares(L, B):\n a = math.gcd(L, B)\n return (L * B // (a * a), a)", "import math\n\ndef minimumsquares(L, B):\n gcd = math.gcd(L, B)\n k = gcd\n n = L * B // (k * k)\n return (n, k)", "def gcd(a, b):\n if b > a:\n (a, b) = (b, a)\n if b == 0:\n return a\n return gcd(a % b, b)\n\ndef minimumsquares(L, B):\n l = L\n b = B\n ans = 0\n mx = max(l, b)\n mn = min(l, b)\n if mx % mn == 0:\n return [mx // mn, mn]\n else:\n g = gcd(mx, mn)\n return [mx * mn // (g * g), g]", "def minimumsquares(l, b):\n\n def gcd(l, b):\n if b == 0:\n return l\n return gcd(b, l % b)\n i = gcd(l, b)\n return [l // i * b // i, i]", "def minimumsquares(L, B):\n li = []\n l = L\n b = B\n while b:\n (l, b) = (b, l % b)\n li.append(int(L * B / l ** 2))\n li.append(l)\n return li", "def minimumsquares(L, B):\n temp = min(L, B)\n temp1 = max(L, B)\n\n def gcd(small, big):\n if big % small == 0:\n return small\n else:\n return gcd(big % small, small)\n var = gcd(temp, temp1)\n ans = L * B // (var * var)\n return (ans, var)", "import math\n\ndef minimumsquares(L, B):\n arr = []\n mini = min(L, B)\n for i in range(1, math.floor(math.sqrt(mini)) + 1):\n if mini % i == 0:\n arr.append(i)\n if mini // i != i:\n arr.append(mini // i)\n n = L * B\n k = 1\n for e in arr:\n if L * B % e ** 2 == 0 and L % e == 0 and (B % e == 0):\n temp = L * B // e ** 2\n if temp < n:\n n = temp\n k = e\n return (n, k)", "def minimumsquares(L, B):\n\n def hcf(L, B):\n if B > L:\n (L, B) = (B, L)\n while B:\n (L, B) = (B, L % B)\n return L\n k = hcf(L, B)\n n = L * B // (k * k)\n return (n, k)", "def minimumsquares(l, b):\n\n def hcf(num1, num2):\n return num2 if num1 == 0 else hcf(num2 % num1, num1)\n area = l * b\n k = hcf(l, b)\n sqarea = k * k\n n = int(area / sqarea)\n return (n, k)", "def computeGCD(x, y):\n while y:\n (x, y) = (y, x % y)\n return abs(x)\n\ndef minimumsquares(L, B):\n k = self.computeGCD(L, B)\n n = L * B // (k * k)\n return (n, k)", "import math\n\ndef minimumsquares(max, min):\n res = []\n k = math.gcd(max, min)\n n = max * min // (k * k)\n return [n, k]", "def minimumsquares(L, B):\n m = self.gcd1(L, B)\n return [L * B // (m * m), m]\n\ndef gcd1(a, b):\n if a == 0 or b == 0:\n return max(a, b)\n else:\n if a < b:\n return self.gcd1(a, b % a)\n return self.gcd1(a % b, b)", "import math\n\ndef minimumsquares(L, B):\n K = math.gcd(L, B)\n return (L * B // (K * K), K)", "def minimumsquares(L, B):\n\n def hcf(x, y):\n while y:\n (x, y) = (y, x % y)\n return x\n temp = hcf(L, B)\n return [max(L, B) // temp * min(L, B) // temp, temp] if temp != 1 else [L * B, 1]", "def minimumsquares(L, B):\n A = L * B\n while L % B != 0 and B % L != 0:\n if B < L:\n L = L % B\n elif B > L:\n B = B % L\n else:\n break\n K = min(L, B)\n N = A // (K * K)\n return (N, K)", "def gcd(n, m):\n if n < m:\n (n, m) = (m, n)\n if n % m == 0:\n return m\n while m > 0:\n n = n % m\n (n, m) = (m, n)\n return n\n\ndef minimumsquares(L, B):\n (a, b) = (L, B)\n x = gcd(a, b)\n y = a * b\n y = y // (x * x)\n return [y, x]", "import math\n\ndef minimumsquares(L, B):\n x = math.gcd(L, B)\n return [L * B // (x * x), x]", "import math\n\ndef minimumsquares(L, B):\n least = math.gcd(L, B)\n return [int(L * B / (least * least)), least]", "def minimumsquares(L, B):\n\n def hcf(x, y):\n while y:\n (x, y) = (y, x % y)\n return x\n k = hcf(L, B)\n n = L * B // (k * k)\n return (n, k)", "def gcd(a, b):\n if a % b == 0:\n return b\n return self.gcd(b, a % b)\n\ndef minimumsquares(L, B):\n g = self.gcd(min(L, B), max(L, B))\n return (int(L * B / (g * g)), g)", "def gcd(a, b):\n if a < b:\n (a, b) = (b, a)\n if a % b == 0:\n return b\n return self.gcd(b, a % b)\n\ndef minimumsquares(L, B):\n return (L * B // self.gcd(L, B) ** 2, self.gcd(L, B))", "def gcd(a, b):\n if a < b:\n (a, b) = (b, a)\n if a % b == 0:\n return b\n return self.gcd(b, a % b)\n\ndef minimumsquares(L, B):\n t = min(L, B)\n k = L * B / t ** 2\n if k == int(k):\n return (int(k), t)\n else:\n return (L * B // self.gcd(L, B) ** 2, self.gcd(L, B))", "def gcd(a, b):\n if b == 0:\n return a\n return self.gcd(b, a % b)\n\ndef minimumsquares(L, B):\n ans1 = self.gcd(L, B)\n ans2 = L * B // (ans1 * ans1)\n return (ans2, ans1)", "import math\n\ndef minimumsquares(L, B):\n sq_side = math.gcd(L, B)\n return (L * B // (sq_side * sq_side), sq_side)", "def gcd(a, b):\n if b == 0:\n return a\n return Solution.gcd(b, a % b)\n\ndef minimumsquares(L, B):\n k = Solution.gcd(L, B)\n r = 0\n r = L * B // (k * k)\n return [r, k]", "def minimumsquares(L, B):\n a = L\n b = B\n while a > 0:\n (b, a) = (a, b % a)\n return (L // b * B // b, b)", "import math\n\ndef minimumsquares(l, b):\n g = math.gcd(l, b)\n ans = 0\n a = []\n while True:\n if l * b % g * g == 0:\n ans = l * b // (g * g)\n a = [ans, g]\n break\n g -= 1\n return a", "def minimumsquares(L, B):\n\n def gcd(L, B):\n if B == 0:\n return L\n return gcd(B, L % B)\n K = gcd(L, B)\n n = L * B // (K * K)\n return (n, K)", "def gcd(L1, B1):\n A = L1\n B = B1\n T = 1\n while B != 0:\n T = A % B\n A = B\n B = T\n return A\n\ndef minimumsquares(L, B):\n K = self.gcd(L, B)\n N = int(L / K * B / K)\n return (N, K)", "def compute_hcf(x, y):\n while y:\n (x, y) = (y, x % y)\n return x\n\ndef minimumsquares(L, B):\n N = 0\n K = 0\n if L > B:\n if L % B == 0:\n N = int(L / B)\n K = B\n else:\n hcf = self.compute_hcf(L, B)\n N = int(L * B / (hcf * hcf))\n K = hcf\n elif B % L == 0:\n N = int(B / L)\n K = L\n else:\n hcf = self.compute_hcf(L, B)\n N = int(L * B / (hcf * hcf))\n K = hcf\n return (N, K)", "def minimumsquares(L, B):\n\n def GCD(L, B):\n if B == 0:\n return L\n else:\n return GCD(B, L % B)\n k = GCD(L, B)\n n = int(L * B / (k * k))\n return (n, k)"], "starter_code": "def minimumsquares(L, B):\n", "input_output": {"inputs": ["L = 2, B = 4", "L = 6, B = 3"], "outputs": ["N = 2, K = 2", " N = 2, K = 3"]}, "difficulty": "EASY", "raw_tags": ["Combinatorial", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Combinatorics", "Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/cutting-rectangles3659/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log min(L, B))", "entry_point": "minimumsquares", "task_id": "TACO_lite/274", "example": [[[2, 4], [6, 3]], ["(2, 2)", "(2, 3)"]]} +{"requirement": "Your website is divided vertically in sections, and each can be of different size (height). \nYou need to establish the section index (starting at `0`) you are at, given the `scrollY` and `sizes` of all sections. \nSections start with `0`, so if first section is `200` high, it takes `0-199` \"pixels\" and second starts at `200`.\n\n### Example:\n\n`getSectionIdFromScroll( 300, [300,200,400,600,100] )`\n\nwill output number `1` as it's the second section.\n\n`getSectionIdFromScroll( 1600, [300,200,400,600,100] )`\n\nwill output number `-1` as it's past last section.\n\nGiven the `scrollY` integer (always non-negative) and an array of non-negative integers (with at least one element), calculate the index (starting at `0`) or `-1` if `scrollY` falls beyond last section (indication of an error).", "solutions": ["def get_section_id(scroll, sizes):\n c = 0\n for (idx, s) in enumerate(sizes):\n c += s\n if scroll < c:\n return idx\n return -1", "from itertools import accumulate\n\ndef get_section_id(scroll, sizes):\n return next((i for (i, x) in enumerate(accumulate(sizes)) if x > scroll), -1)", "def get_section_id(scroll, sizes):\n if scroll >= sum(sizes):\n return -1\n return sum((scroll >= sum(sizes[:i + 1]) for i in range(len(sizes))))", "from itertools import takewhile, accumulate\n\ndef get_section_id(scroll, sizes):\n return -1 if sum(sizes) <= scroll else sum((1 for _ in takewhile(scroll.__ge__, accumulate(sizes))))", "def get_section_id(scroll, sizes):\n where = 0\n for i in range(len(sizes)):\n where += sizes[i]\n if where > scroll:\n return i\n return -1", "def get_section_id(scroll, sizes):\n for (i, _) in enumerate(sizes):\n if scroll < sum(sizes[:i + 1]):\n return i\n return -1", "from bisect import bisect\nfrom itertools import accumulate\n\ndef get_section_id(scroll, sizes):\n return bisect(list(accumulate(sizes)), scroll) if scroll < sum(sizes) else -1", "def get_section_id(scroll, sizes):\n for (i, s) in enumerate(sizes):\n scroll -= s\n if scroll < 0:\n return i\n return -1", "def get_section_id(scroll, sizes):\n a = 0\n for i in sizes:\n scroll -= i\n if scroll < 0:\n return a\n a += 1\n return -1"], "starter_code": "def get_section_id(scroll, sizes):\n", "input_output": {"fn_name": "get_section_id", "inputs": [[1, [300, 200, 400, 600, 100]], [299, [300, 200, 400, 600, 100]], [300, [300, 200, 400, 600, 100]], [1599, [300, 200, 400, 600, 100]], [1600, [300, 200, 400, 600, 100]]], "outputs": [[0], [0], [1], [4], [-1]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5cb05eee03c3ff002153d4ef", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "get_section_id", "task_id": "TACO_lite/278", "example": [[[300, [300, 200, 400, 600, 100]], [1600, [300, 200, 400, 600, 100]]], ["1", "-1"]]} +{"requirement": "Write a function named sumDigits which takes a number as input and returns the sum of the absolute value of each of the number's decimal digits. For example:\n\n```python\n sum_digits(10) # Returns 1\n sum_digits(99) # Returns 18\n sum_digits(-32) # Returns 5\n```\n\nLet's assume that all numbers in the input will be integer values.", "solutions": ["def sum_digits(number):\n return sum(map(int, str(abs(number))))", "def sum_digits(n):\n return eval('+'.join(str(abs(n))))", "def sum_digits(number):\n num_string = str(abs(number))\n total = 0\n for char in num_string:\n total += int(char)\n return total", "def sum_digits(number):\n d = 0\n for c in str(abs(number)):\n d += ord(c) - 48\n return d", "sum_digits = lambda n: sum((int(e) for e in str(abs(n))))", "def sum_digits(n):\n return sum([int(x) for x in str(abs(n))])", "def sum_digits(number):\n return sum((int(ele) for ele in str(abs(number))))", "def sum_digits(number):\n return sum([int(i) for i in str(abs(number))])", "def sum_digits(number):\n inp = str(number)\n s = 0\n for x in inp:\n try:\n s += int(x)\n except:\n pass\n return s", "def sum_digits(number):\n return sum((int(digit) for digit in str(number).replace('-', '')))", "def sum_digits(number):\n sum = 0\n if number < 0:\n number = number * -1\n while len(str(number)) != 1:\n sum += number % 10\n number = number // 10\n sum += number\n return sum", "def sum_digits(number):\n sum = 0\n if len(str(number)) == 1:\n return number\n else:\n for i in range(len(str(number))):\n if str(number)[i] == '-':\n sum += 0\n else:\n sum += int(str(number)[i])\n return sum", "def sum_digits(number):\n if number < 0:\n number *= -1\n return sum(map(int, str(number)))", "def sum_digits(number):\n string = str(number)\n for char in string:\n if char == '-':\n string = string.replace(char, '')\n return sum([int(x) for x in string])", "def sum_digits(number):\n return sum((int(i) if not i == '-' else 0 for i in str(number)))", "def sum_digits(number):\n str_num = str(number)\n ret_num = 0\n for num in str_num:\n if num != '-':\n ret_num = ret_num + int(num)\n return ret_num", "def sum_digits(number):\n total = 0\n for digit in str(abs(number)):\n total += int(digit)\n return total", "def sum_digits(x):\n if len(str(x)) == 1:\n return x\n suma = 0\n for j in str(x):\n if j != '-':\n suma += int(j)\n return suma", "def sum_digits(number):\n sum = 0\n for num in str(abs(number)):\n sum += int(num)\n return sum", "def sum_digits(number):\n number = str(number)\n numT = 0\n for i in number:\n if i != '-':\n numT += int(i)\n return numT", "def sum_digits(number):\n number = abs(number)\n if number == 0:\n return 0\n return number % 10 + sum_digits(number // 10)", "def sum_digits(number):\n chars = list(str(number))\n digits = [int(char) for char in chars if char.isdigit()]\n return sum(digits)", "def sum_digits(number):\n s = 0\n n = str(number)\n for i in n:\n if i.isdigit():\n s += int(i)\n return s", "def sum_digits(number):\n kol = 0\n j = ''\n string = str(number)\n for i in string:\n j = ''\n if i == '-':\n continue\n else:\n j += i\n kol += int(j)\n return kol", "def sum_digits(number):\n sum = 0\n for char in str(number):\n if char == '-':\n continue\n else:\n sum = sum + eval(char)\n return sum", "def sum_digits(number):\n digits = list(map(str, str(number)))\n digits = [int(x) for x in digits if x.isdigit()]\n return sum(digits)", "def sum_digits(number):\n result = 0\n is_minus = False\n if number < 0:\n is_minus = True\n number = number * -1\n for element in str(number):\n result += int(element)\n return result", "def sum_digits(number):\n nr = str(number)\n total = 0\n for i in range(len(nr)):\n if nr[i].isdigit():\n total += int(nr[i])\n return total", "def sum_digits(number):\n t = 0\n for i in str(number):\n if i.isdigit():\n t = t + int(i)\n return t", "def sum_digits(number):\n luz = abs(number)\n liz = [int(x) for x in str(luz)]\n return sum(liz)", "def sum_digits(number):\n summ = 0\n number = str(number)\n for num in number:\n if num.isdigit():\n summ += int(num)\n else:\n pass\n return summ", "def sum_digits(number):\n numberList = [int(x) for x in str(abs(number))]\n return sum(numberList)", "def sum_digits(number):\n y = 0\n for x in str(number):\n if x == '-':\n pass\n else:\n y += int(x)\n return y", "def sum_digits(number):\n if number < 0:\n number *= -1\n a = str(number)\n return sum([int(i) for i in a])", "def sum_digits(number):\n if number >= 0:\n total = 0\n for i in str(number):\n total += int(i)\n return total\n else:\n total = 0\n for i in str(number)[1:]:\n total += int(i)\n return total", "def sum_digits(num):\n return sum([int(i) for i in str(num) if i.isdigit()])", "def sum_digits(number):\n result = 0\n for num in str(number):\n try:\n result += int(num)\n except:\n continue\n return result", "def sum_digits(number):\n num_str = str(abs(number))\n s = 0\n for i in num_str:\n s += int(i)\n return s", "def sum_digits(number):\n splits = list(str(number))\n num_lst = []\n for num in splits:\n try:\n if type(int(num)) == int:\n num_lst.append(int(num))\n except:\n continue\n return sum(num_lst)", "def sum_digits(number):\n num = str(abs(number))\n res = 0\n for item in num:\n res += int(item)\n return res", "def sum_digits(number):\n num = str(number)\n num = [int(x) for x in num if x != '-']\n return sum(num)", "def sum_digits(number):\n sumnumbers = 0\n for numbers in str(number.__abs__()):\n sumnumbers += int(numbers)\n return sumnumbers", "def sum_digits(number):\n n = str(abs(number))\n sum = 0\n for i in range(len(n)):\n sum += int(n[i])\n return sum", "def sum_digits(number):\n q = 0\n h = str(number.__abs__())\n for i in h:\n q += int(i)\n return q", "def sum_digits(number):\n k = sum(list(map(int, str(abs(number)))))\n return k", "def sum_digits(number):\n sum = 0\n for e in str(abs(number)):\n sum += int(e)\n return sum", "def sum_digits(number):\n if number < 0:\n number = number * -1\n total = 0\n while number > 0:\n dig = number % 10\n total += dig\n number = number // 10\n return total", "def sum_digits(number):\n my_sum = 0\n number = abs(number)\n while number >= 10:\n my_sum = my_sum + number % 10\n number = int(number / 10)\n my_sum = my_sum + number\n return my_sum", "def sum_digits(number):\n sum_digits = 0\n number2 = abs(number)\n for i in str(number2):\n sum_digits += int(i)\n return sum_digits", "def sum_digits(number):\n num = str(number)\n num = num.lstrip('-')\n result = 0\n for i in num:\n result += int(i)\n return result", "def sum_digits(number):\n sum = 0\n while abs(number) // 10 != 0:\n sum += abs(number) % 10\n number = abs(number) // 10\n sum += abs(number) % 10\n return sum", "def sum_digits(number):\n number = abs(number)\n number = str(number)\n sum_num = 0\n for i in number:\n i = int(i)\n sum_num = sum_num + i\n return sum_num", "def sum_digits(number):\n absNum = number if number > 0 else -number\n strList = list(str(absNum))\n return sum(map(lambda x: int(x), strList))", "def sum_digits(number):\n abs_value = 0\n numbers = map(int, str(number).strip('-'))\n for i in numbers:\n abs_value += i\n return abs_value", "def sum_digits(number):\n count = 0\n number = abs(number)\n for num in str(number):\n count = count + int(num)\n return count", "def sum_digits(number):\n if number < 0:\n number *= -1\n if number < 10:\n return number\n else:\n last_digit = number % 10\n return sum_digits(number // 10) + last_digit", "def sum_digits(number):\n sn = str(number)\n rez = 0\n for i in sn:\n if i.isnumeric():\n rez += int(i)\n return rez", "def sum_digits(number):\n naked = str(number).strip('-')\n return sum((int(digit) for digit in naked))", "import numpy as np\n\ndef sum_digits(number):\n number = int(np.sqrt(number ** 2))\n return sum([int(d) for d in str(number)])", "def sum_digits(num):\n sum = 0\n for x in str(abs(num)):\n sum += int(x)\n return sum", "def sum_digits(number):\n number = abs(number)\n result = 0\n while number > 0:\n result += number % 10\n number //= 10\n return result", "def sum_digits(number):\n bruh = 0\n for i in str(abs(number)):\n bruh += int(i)\n return bruh", "def sum_digits(number):\n for i in str(number):\n if i == '-':\n number = str(number).strip('-')\n else:\n pass\n digits = [int(x) for x in str(number)]\n return sum(digits)", "def sum_digits(number):\n n = []\n for i in str(number):\n if i != '-':\n n.append(int(i))\n return sum(n)", "import math\n\ndef sum_digits(n):\n n = round(math.fabs(n))\n all = [int(s) for s in str(n)]\n return sum(all)"], "starter_code": "def sum_digits(number):\n", "input_output": {"fn_name": "sum_digits", "inputs": [[10], [99], [-32], [1234567890], [0], [666], [100000002], [800000009]], "outputs": [[1], [18], [5], [45], [0], [18], [3], [17]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/52f3149496de55aded000410", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sum_digits", "task_id": "TACO_lite/318", "example": [[[10], [99], [-32]], ["1", "18", "5"]]} +{"requirement": "Pell numbers are numbers that are similar to the Fibonacci numbers and are generated by below formula\nP_{n} = 2*P_{n-1} + P_{n-2}\nwith seeds P_{0} = 0 and P_{1} = 1\nYour task is to print Nth pell number.\n \nExample 1:\nInput:\nN = 3\nOutput:\n5\nExplanation:\nP_{0} = 0, P_{1} = 1, P_{2} = 2*1+0 = 2,\nP_{3} = 2*2+1 = 5\nExample 2:\nInput:\nN = 4\nOutput:\n12\nExplanation:\nP_{0} = 0, P_{1} = 1, P_{2} = 2*1+0 = 2,\nP_{3} = 2*2+1 = 5, P_{4} = 2*5+2 = 12\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function getNthPell() which takes an Integer N as input and returns the answer modulo (10^{9}+7).\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\n \nConstraints:\n1 <= N <= 10^{5}", "solutions": ["def getnthpell(N):\n if N == 0:\n return 0\n elif N == 1:\n return 1\n else:\n (a, b, m) = (0, 1, int(1000000000.0) + 7)\n for i in range(N - 1):\n c = (2 * b + a) % m\n a = b\n b = c\n return b", "def getnthpell(N):\n (p0, p1) = (0, 1)\n for i in range(N):\n (p0, p1) = (p1, (2 * p1 + p0) % 1000000007)\n return p0", "def getnthpell(N):\n if N <= 1:\n return N\n a = 0\n b = 1\n for i in range(2, N + 1):\n c = 2 * b + a\n a = b\n b = c\n b = b % 1000000007\n return b", "def getnthpell(N):\n arr = [0] * (N + 1)\n arr[0] = 0\n arr[1] = 1\n for i in range(2, N + 1):\n arr[i] = (2 * arr[i - 1] + arr[i - 2]) % 1000000007\n return arr[N]", "def getnthpell(N):\n fab = [0, 1]\n for j in range(2, N + 1):\n v = (fab[1] * 2 % (10 ** 9 + 7) + fab[0]) % (10 ** 9 + 7)\n (fab[0], fab[1]) = (fab[1], v)\n return fab[1]", "def getnthpell(N):\n f = [0, 1]\n for i in range(2, N + 2):\n f.append((f[i - 1] * 2 + f[i - 2]) % (10 ** 9 + 7))\n return f[N]", "def getnthpell(N):\n if N == 0:\n return 0\n if N == 1:\n return 1\n lst = [0, 1]\n for i in range(2, N + 1):\n val = (2 * lst[i - 1] + lst[i - 2]) % 1000000007\n lst.append(val)\n return lst[N]"], "starter_code": "def getnthpell(N):\n", "input_output": {"inputs": ["N = 3", "N = 4"], "outputs": ["5", "12"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/pell-number1424/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "getnthpell", "task_id": "TACO_lite/303", "example": [[[3], [4]], ["5", "12"]]} +{"requirement": "Scientists working internationally use metric units almost exclusively. Unless that is, they wish to crash multimillion dollars worth of equipment on Mars.\n\nYour task is to write a simple function that takes a number of meters, and outputs it using metric prefixes.\n\nIn practice, meters are only measured in \"mm\" (thousandths of a meter), \"cm\" (hundredths of a meter), \"m\" (meters) and \"km\" (kilometers, or clicks for the US military).\n\nFor this exercise we just want units bigger than a meter, from meters up to yottameters, excluding decameters and hectometers.\n\nAll values passed in will be positive integers.\ne.g.\n\n```python\nmeters(5);\n// returns \"5m\"\n\nmeters(51500);\n// returns \"51.5km\"\n\nmeters(5000000);\n// returns \"5Mm\"\n```\n\nSee http://en.wikipedia.org/wiki/SI_prefix for a full list of prefixes", "solutions": ["def meters(x):\n arr = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']\n count = 0\n while x >= 1000:\n x /= 1000.0\n count += 1\n if int(x) == x:\n x = int(x)\n return str(x) + arr[count] + 'm'", "PREFIXES = ((10 ** 24, 'Y'), (10 ** 21, 'Z'), (10 ** 18, 'E'), (10 ** 15, 'P'), (10 ** 12, 'T'), (10 ** 9, 'G'), (10 ** 6, 'M'), (10 ** 3, 'k'), (1, ''))\n\ndef meters(x):\n (value, prefix) = next((pr for pr in PREFIXES if pr[0] <= x))\n return '%g%sm' % (float(x) / value, prefix)", "import math\nPREFIXES = ['m', 'km', 'Mm', 'Gm', 'Tm', 'Pm', 'Em', 'Zm', 'Ym']\n\ndef meters(x):\n e = int(math.log(x, 1000))\n return '{0:g}{1}'.format(x / 1000.0 ** e, PREFIXES[e])", "def meters(x):\n units = [('Y', 24), ('Z', 21), ('E', 18), ('P', 15), ('T', 12), ('G', 9), ('M', 6), ('k', 3), ('', 0)]\n return next((f\"{str(x / 10 ** p).replace('.0', '')}{u}m\" for (u, p) in units if x // 10 ** p >= 1))", "def meters(x):\n (prefix, power) = next((pair for pair in zip('YZEPTGMk', range(24, 0, -3)) if x >= 10 ** pair[1]), ('', 0))\n return '{:g}{}m'.format(x / 10 ** power, prefix)", "def meters(x):\n s = ['m', 'km', 'Mm', 'Gm', 'Tm', 'Pm', 'Em', 'Zm', 'Ym']\n i = 0\n while x >= 1000:\n x /= 1000.0\n i += 1\n return '%g%s' % (x, s[i])", "from decimal import Context, ROUND_HALF_UP\nimport re\n\ndef meters(num):\n r = len(str(num).strip('0'))\n num = Context(prec=r, rounding=ROUND_HALF_UP).create_decimal(num)\n i = int(num.logb()) // 3\n return re.sub('(\\\\.0+)(?=[kMGTPEZTY])', '', f\"{num.scaleb(-3 * i):f}{' kMGTPEZY'[i]}m\".replace(' ', ''))", "from math import log\n\ndef meters(x):\n prefixes = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']\n order = int(log(x, 1000))\n return '{:g}{}m'.format(x / (1000 ** order or 1), prefixes[order])"], "starter_code": "def meters(x):\n", "input_output": {"fn_name": "meters", "inputs": [[1], [999], [123456], [12300000], [9000000000.0], [9000000000000.0], [9000000000000000.0], [9e+18], [9e+21], [9e+24]], "outputs": [["1m"], ["999m"], ["123.456km"], ["12.3Mm"], ["9Gm"], ["9Tm"], ["9Pm"], ["9Em"], ["9Zm"], ["9Ym"]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5264f5685fda8ed370000265", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "meters", "task_id": "TACO_lite/299", "example": [[], []]} +{"requirement": "Given an integer S represented as a string, the task is to get the sum of all possible sub-strings of this string.\nAs the answer will be large, print it modulo 10^9+7.\nExample 1:\nInput:\nS = 1234\nOutput: 1670\nExplanation: Sum = 1 + 2 + 3 + 4 + 12 +\n23 + 34 + 123 + 234 + 1234 = 1670\nExample 2:\nInput:\nS = 421\nOutput: 491\nExplanation: Sum = 4 + 2 + 1 + 42 + 21\nYour Task:\nYou only need to complete the function sumSubstrings that takes S as an argument and returns the answer modulo 1000000007.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\nConstraints:\n1 <= |S| <= 10^{4}", "solutions": ["def sumsubstrings(s):\n n = len(s)\n digits = []\n for char in s:\n digits.append(int(char))\n dp = [0 for i in range(n)]\n dp[0] = digits[0]\n res = dp[0]\n for i in range(1, n):\n dp[i] = ((i + 1) * digits[i] + dp[i - 1] * 10) % 1000000007\n res += dp[i]\n res %= 1000000007\n return res", "def sumsubstrings(s):\n a = s\n dp = [0 for i in range(len(a))]\n dp[0] = int(a[0])\n result = dp[0]\n for i in range(1, len(a)):\n dp[i] = (i + 1) * int(a[i]) + 10 * dp[i - 1]\n result = result + dp[i]\n return result % (10 ** 9 + 7)", "def sumsubstrings(s):\n ls = []\n for i in s:\n ls.append(int(i))\n p = ls[0]\n s = ls[0]\n for j in range(1, len(ls)):\n c = ls[j]\n temp = (j + 1) * c + p * 10\n s = s + temp\n p = temp\n return s % 1000000007", "def sumsubstrings(num):\n mod = 1000000007\n n = len(num)\n prev = int(num[0])\n result = prev\n cur = 0\n for i in range(1, n):\n cur = (i + 1) * int(num[i]) + 10 * prev\n result += cur\n prev = cur\n return result % mod", "def sumsubstrings(s):\n M = 1000000007\n n = len(s)\n dp = [0 for i in range(0, n)]\n dp[0] = ord(s[0]) - ord('0')\n for i in range(1, n):\n dp[i] = ((i + 1) * (ord(s[i]) - ord('0')) + 10 * dp[i - 1]) % M\n ans = 0\n for i in range(0, n):\n ans += dp[i] % M\n return ans % M", "def sumsubstrings(s):\n dp = [0] * len(s)\n dp[0] = int(s[0])\n mod = 10 ** 9 + 7\n for i in range(1, len(s)):\n dp[i] = (10 * dp[i - 1] + int(s[i]) * (i + 1)) % mod\n res = 0\n for i in range(len(s)):\n res += dp[i]\n res %= mod\n return res", "def sumsubstrings(s):\n n = len(s)\n prev = int(s[0])\n res = prev\n current = 0\n for i in range(1, n):\n numi = int(s[i])\n current = (i + 1) * numi + 10 * prev\n res += current\n prev = current\n return res % 1000000007", "def sumsubstrings(s):\n sub_res = 0\n prev_res = int(s[0])\n res = prev_res\n mod = 1000000000.0 + 7\n for i in range(1, len(s)):\n sub_res = ((i + 1) * int(s[i]) + 10 * prev_res) % mod\n res = (res + sub_res) % mod\n prev_res = sub_res\n return int(res)", "def sumsubstrings(s):\n dp = [0] * len(s)\n dp[0] = int(s[0])\n for i in range(1, len(s)):\n dp[i] = (dp[i - 1] * 10 + (i + 1) * int(s[i])) % 1000000007\n return sum(dp) % 1000000007", "def sumsubstrings(s):\n su = 0\n mod = 1000000007\n n = len(s)\n dp = [0] * n\n dp[0] = int(s[0])\n for i in range(1, n):\n dp[i] = 10 * dp[i - 1] % mod + (i + 1) * int(s[i])\n for i in range(n):\n su = (su + dp[i]) % mod\n return su", "def sumsubstrings(s):\n ans = 0\n k = 1\n for i in range(len(s) - 1, -1, -1):\n ans = ans + int(s[i]) * (i + 1) * k\n k = k * 10 + 1\n return ans % 1000000007", "def sumsubstrings(s):\n summa = 0\n n = len(s)\n for i in range(n):\n summa += int('1' * (n - i)) * int(s[i]) * (i + 1)\n return summa % (10 ** 9 + 7)", "def sumsubstrings(s):\n n = len(s)\n total = 0\n mod = 10 ** 9 + 7\n for i in range(n):\n text = s[i] * (n - i)\n total += int(text) * (i + 1)\n return total % mod", "def sumsubstrings(s):\n no = [int(s[0])]\n ans = no[0]\n MOD = 1000000007\n for i in range(1, len(s)):\n curr = (i + 1) * int(s[i]) + no[-1] * 10\n no.append(curr % MOD)\n ans += no[i]\n return ans % MOD", "def sumsubstrings(s):\n n = len(s)\n l = [0] * (n + 1)\n l[0] = ord(s[0]) - ord('0')\n for i in range(1, n):\n l[i] = (ord(s[i]) - ord('0')) * (i + 1) + 10 * l[i - 1]\n sum = 0\n m = pow(10, 9) + 7\n for d in l:\n sum = (sum + d) % m\n return sum", "def sumsubstrings(s):\n n = len(s)\n mod = 1000000007\n ls = [0] * n\n ls[0] = int(s[0]) % mod\n for i in range(1, n):\n ls[i] = ((i + 1) * int(s[i]) + 10 * ls[i - 1]) % mod\n add = 0\n for i in range(n):\n add += ls[i]\n return add % mod", "def sumsubstrings(s):\n m = 10 ** 9 + 7\n n = len(s)\n L = []\n L.append(int(s[0]))\n res = L[0]\n for i in range(1, n):\n p = int(s[i])\n L.append((i + 1) * p + 10 * L[i - 1])\n res = res + L[i]\n return res % m", "def sumsubstrings(s):\n M = 10 ** 9 + 7\n sum_val = 0\n B = 1\n res = 0\n for i in range(len(s) - 1, -1, -1):\n res = (res + int(s[i]) * B * (i + 1)) % M\n sum_val -= int(s[i])\n B = (B * 10 + 1) % M\n return res", "def sumsubstrings(s):\n mod = 10 ** 9 + 7\n ans = 0\n n = len(s)\n pref_arr = [0] * n\n pref_arr[0] = int(s[0])\n for i in range(1, n):\n val = (i + 1) * int(s[i])\n pref_arr[i] = val + 10 * pref_arr[i - 1]\n for i in range(n):\n ans += pref_arr[i] % mod\n return ans % mod", "def sumsubstrings(s):\n n = len(s)\n res = []\n res.append(int(s[0]))\n for i in range(1, n):\n si = int(s[i])\n res.append((i + 1) * si + 10 * res[i - 1])\n summ = sum(res) % (10 ** 9 + 7)\n return summ", "def fun(s, n):\n dp = [0] * n\n m = 10 ** 9 + 7\n dp[0] = int(s[0])\n sum = dp[0]\n for i in range(1, n):\n dp[i] = ((i + 1) * int(s[i]) + 10 * dp[i - 1]) % m\n sum += dp[i]\n sum %= m\n return sum\n\ndef sumsubstrings(s):\n n = len(s)\n return fun(s, n)", "def sumsubstrings(s):\n mod = 10 ** 9 + 7\n sum1 = 0\n p = 1\n for i in range(len(s) - 1, -1, -1):\n sum1 = (sum1 + int(s[i]) * (i + 1) * p) % mod\n p = p * 10 + 1\n return sum1", "def sumsubstrings(s):\n mat = []\n s1 = str(s)\n mat.append(s1[0])\n for i in range(1, len(s1)):\n val = int(str(mat[i - 1]) + '0')\n val1 = int((i + 1) * int(s1[i]))\n ans = val + val1\n mat.append(ans)\n res = 0\n for i in mat:\n res = res + int(i)\n return res % 1000000007", "def sumsubstrings(num):\n n = len(num)\n prev = int(num[0])\n res = prev\n current = 0\n for i in range(1, n):\n numi = int(num[i])\n current = (i + 1) * numi + 10 * prev\n res += current\n prev = current\n return res % (10 ** 9 + 7)", "def sumsubstrings(s):\n mod = int(1000000000.0 + 7)\n n = len(s)\n totSum = int(s[0])\n prevSum = int(s[0])\n for i in range(1, n):\n curSum = (i + 1) * int(s[i]) + 10 * prevSum\n totSum = (totSum % mod + curSum % mod) % mod\n prevSum = curSum\n return totSum", "def sumsubstrings(s):\n res = []\n s1 = str(s)\n sum0 = []\n sum0.append(int(s1[0]))\n for i in range(1, len(s)):\n sum1 = int(s1[i]) * (i + 1) + 10 * sum0[i - 1]\n sum0.append(sum1)\n return sum(sum0) % 1000000007", "def sumsubstrings(s):\n p = 1000000007\n il = 0\n el = 0\n n = 0\n for i in s:\n i = int(i)\n el = (il + el) % p\n il = (il * 10 + n * i + i) % p\n n += 1\n return (il + el) % p", "def sumsubstrings(string):\n sum = int(string[0])\n n = len(string)\n pre_sum = int(string[0])\n for i in range(1, n):\n pre_sum = int(string[i]) * (i + 1) + 10 * pre_sum\n sum += pre_sum\n return sum % 1000000007", "def sumsubstrings(s):\n mod = 1000000007\n sum = 0\n for i in range(len(s)):\n num = int(s[i] * (len(s) - i)) % mod * (i + 1) % mod % mod\n sum += num % mod\n return sum % mod", "def sumsubstrings(s):\n mod = 1000000007\n n = len(s)\n if n == 0:\n return 0\n if n == 1:\n return int(s[0])\n dp = [0] * (n + 1)\n dp[0] = 0\n res = 0\n for i in range(1, n + 1):\n dp[i] = (i * (int(s[i - 1]) % mod) % mod + 10 * dp[i - 1] % mod % mod) % mod\n res = (res % mod + dp[i] % mod) % mod\n return res % mod\n dp[1] = int(s[0]) % mod\n dp[2] = int(s[0]) % mod + int(s[1]) % mod + int(s[0:2]) % mod\n for i in range(3, n + 1):\n res = 0\n for j in range(i):\n res += int(s[j:i]) % mod\n dp[i] = (res % mod + dp[i - 1] % mod) % mod", "def sumsubstrings(s):\n st = [int(s[0])]\n res = st[0]\n for i in range(1, len(s)):\n p = int(s[i])\n st.append((i + 1) * p + 10 * st[-1])\n res += st[-1]\n return res % 1000000007", "def sumsubstrings(s):\n ans = 0\n x = 1\n c = len(s)\n for i in s[::-1]:\n ans += x * int(i) * c\n x = x * 10 + 1\n c -= 1\n return ans % 1000000007", "def sumsubstrings(s):\n mod = 1000000007\n n = len(s)\n lst = [0 for i in range(n)]\n lst[0] = int(s[0])\n res = int(s[0])\n for i in range(1, n):\n lst[i] = (i + 1) * int(s[i]) + 10 * lst[i - 1]\n res += lst[i]\n return res % mod", "def sumsubstrings(s):\n sums = 0\n multiply = 1\n for i in range(len(s) - 1, -1, -1):\n sums += int(s[i]) * (i + 1) * multiply\n multiply = multiply * 10 + 1\n return sums % (10 ** 9 + 7)", "def sumsubstrings(s):\n string_number = str(s)\n a = [0] * len(string_number)\n a[0] = int(s[0])\n for i in range(1, len(string_number)):\n a[i] = 10 * a[i - 1] + (i + 1) * int(string_number[i])\n return sum(a) % 1000000007", "def sumsubstrings(s):\n mod = 10 ** 9 + 7\n result = 0\n N = len(s)\n sum_of_digits = [int(s[0])]\n for i in range(1, N):\n result = (int(s[i]) * (i + 1) + 10 * sum_of_digits[i - 1]) % mod\n sum_of_digits.append(result)\n return sum(sum_of_digits) % mod", "def sumsubstrings(s):\n if len(s) == 0:\n return 0\n mod = 1000000007\n dp = [0 for _ in range(len(s))]\n dp[0] = int(s[0])\n result = dp[0]\n for i in range(1, len(s)):\n dp[i] = (i + 1) * int(s[i]) + 10 * dp[i - 1] % mod\n result += dp[i] % mod\n return result % mod", "from itertools import combinations\n\ndef sumsubstrings(s):\n (current, result) = (int(s[0]), 0)\n for i in range(len(s) - 1):\n result += current\n prev = current\n current = (i + 2) * int(s[i + 1]) + 10 * prev\n return (result + current) % 1000000007", "from itertools import combinations\n\ndef sumsubstrings(s):\n c = 0\n q = int(s[0])\n res = q\n for i in range(1, len(s)):\n ni = int(s[i])\n c = (i + 1) * ni + 10 * q\n res += c\n q = c\n return res % 1000000007", "def sumsubstrings(s):\n l = [0] * len(s)\n l[0] = int(s[0])\n for i in range(1, len(s)):\n x = int(s[i])\n y = l[i - 1]\n l[i] = x * (i + 1) + 10 * y\n return sum(l) % 1000000007", "def sumsubstrings(s):\n n = len(s)\n koo = 10 ** 9 + 7\n arr = [0] * n\n arr[0] = int(s[0])\n for i in range(1, n):\n arr[i] = arr[i - 1] + int(s[i]) * (i + 1)\n ans = 0\n for i in range(n):\n ans = (ans % koo + arr[i] * 10 ** (n - i - 1) % koo) % koo\n return ans % koo", "def sumsubstrings(s):\n ans = [int(s[0])]\n for i in range(1, len(s)):\n a = ans[i - 1] * 10 + int(s[i]) * (i + 1)\n ans.append(a)\n return sum(ans) % 1000000007", "def sumsubstrings(s):\n su = 0\n mf = 1\n for i in range(len(s) - 1, -1, -1):\n su = su + int(s[i]) * (i + 1) * mf\n mf = mf * 10 + 1\n return su % (10 ** 9 + 7)", "def sumSubstring(s, n):\n if n == 0:\n return 0\n su = int(s[n - 1])\n su += Solution.sumSubstring(s, n - 1) % 1000000007\n for i in range(n - 2, -1, -1):\n su += int(s[i:n])\n return su\n\ndef sumsubstrings(s):\n n = len(s)\n dp = [0] * (n + 1)\n dp[0] = int(s[0])\n res = dp[0]\n for i in range(1, n):\n dp[i] = (i + 1) * int(s[i]) + 10 * (dp[i - 1] % 1000000007)\n res += dp[i]\n return res % 1000000007", "def sumsubstrings(s):\n n = len(s)\n sod = []\n sod.append(int(s[0]))\n res = sod[0]\n for i in range(1, n):\n numi = int(s[i])\n sod.append((i + 1) * numi + 10 * sod[i - 1])\n res += sod[i]\n return res % (10 ** 9 + 7)", "def sumsubstrings(s):\n n = len(s)\n dp = [0] * n\n res = int(s[0])\n dp[0] = res\n m = 1000000007\n for i in range(1, n):\n dp[i] = (i + 1) * int(s[i]) + 10 * dp[i - 1] % m\n res = (res + dp[i]) % m\n return res", "def sumsubstrings(str):\n modulo = 1000000007\n dp = [0] * len(str)\n dp[0] = int(str[0])\n for i in range(1, len(str)):\n dp[i] = (dp[i - 1] + int(str[i]) + (dp[i - 1] - (dp[i - 2] if i > 1 else 0)) * 10 + int(str[i]) * i) % modulo\n return dp[-1]", "def sumsubstrings(s):\n M = 1000000007\n n = len(s)\n sumstr = []\n sumstr.append(int(s[0]))\n res = sumstr[0]\n for i in range(1, n):\n sumstr.append((i + 1) * int(s[i]) + 10 * sumstr[i - 1])\n res += sumstr[i]\n return res % M", "def sumsubstrings(s):\n mod = 10 ** 9 + 7\n n = len(s)\n s = str(s)\n dp = [0] * n\n dp[0] = int(s[0])\n ans = dp[0]\n for i in range(1, n):\n dp[i] = ((i + 1) * int(s[i]) + 10 * dp[i - 1]) % mod\n ans = (ans + dp[i]) % mod\n return ans", "def sumsubstrings(s):\n n = len(s)\n sumofdigit = []\n sumofdigit.append(int(s[0]))\n res = sumofdigit[0]\n for i in range(1, n):\n numi = int(s[i])\n sumofdigit.append((i + 1) * numi + 10 * sumofdigit[i - 1])\n res += sumofdigit[i]\n return res % 1000000007", "def sumsubstrings(s):\n t = 0\n i = 0\n f = len(s)\n a = []\n r = 0\n a.append(1)\n for i in range(1, len(s)):\n a.append(a[i - 1] * 10 + 1)\n for x in range(0, len(s)):\n r = r + a[x] * int(s[f - 1 - x]) * (f - x)\n return r % 1000000007", "def sumsubstrings(s):\n if len(s) == 0:\n return 0\n prev = int(s[0])\n total = prev\n for i in range(2, len(s) + 1):\n curr = int(s[i - 1]) * i + 10 * prev\n total += curr\n prev = curr\n return total % 1000000007", "def sumsubstrings(s):\n n = len(s)\n a = [int(i) for i in s]\n dp = [0 for i in range(n)]\n dp[0] = a[0]\n c = dp[0]\n for i in range(1, n):\n dp[i] = ((i + 1) * a[i] + 10 * dp[i - 1]) % 1000000007\n c += dp[i] % 1000000007\n return c % 1000000007", "mod = 10 ** 9 + 7\n\ndef sumsubstrings(s):\n prev = int(s[0])\n ans = prev\n for i in range(1, len(s)):\n curr = int(s[i])\n val = (i + 1) * curr + 10 * prev\n ans = (ans + val) % mod\n prev = val\n return ans"], "starter_code": "def sumsubstrings(s):\n", "input_output": {"inputs": ["S = 1234", "S = 421"], "outputs": ["1670", "491"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/sum-of-all-substrings-of-a-number-1587115621/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "sumsubstrings", "task_id": "TACO_lite/327", "example": [[["1234"], ["421"]], ["1670", "491"]]} +{"requirement": "Count the number of prime numbers less than a non-negative number, n.\n\nExample:\n\n\nInput: 10\nOutput: 4\nExplanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.", "solutions": ["def countprimes(x):\n x = max(0, x - 1)\n if type(x) is not int:\n x = int(x)\n if x < 6:\n return [0, 0, 1, 2, 2, 3][x]\n\n def Phi(m, b):\n if not b:\n return m\n if not m:\n return 0\n if m >= 800:\n return Phi(m, b - 1) - Phi(m // primes[b - 1], b - 1)\n t = b * 800 + m\n if not Phi_memo[t]:\n Phi_memo[t] = Phi(m, b - 1) - Phi(m // primes[b - 1], b - 1)\n return Phi_memo[t]\n root2 = int(x ** (1.0 / 2))\n root3 = int(x ** (1.0 / 3))\n top = x // root3 + 1\n sieve = [0, 0] + [1] * (top - 2)\n pi = [0, 0]\n primes = []\n t = 0\n for i in range(2, top):\n if sieve[i] == 1:\n t += 1\n primes.append(i)\n sieve[i::i] = [0] * len(sieve[i::i])\n pi.append(t)\n (a, b) = (pi[root3 + 1], pi[root2 + 1])\n Phi_memo = [0] * ((a + 1) * 800)\n return Phi(x, a) + a - 1 - sum((pi[x // p] - pi[p] + 1 for p in primes[a:b]))"], "starter_code": "def countprimes(n: int) -> int:\n", "input_output": {"fn_name": "countPrimes", "inputs": [[10]], "outputs": [4]}, "difficulty": "EASY", "raw_tags": ["Number Theory", "Enumeration", "Math", "Array"], "name": null, "source": "leetcode", "tags": ["Number theory", "Data structures", "Mathematics", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://leetcode.com/problems/count-primes/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "countprimes", "task_id": "TACO_lite/335", "example": [[[10]], ["4"]]} +{"requirement": "Given an integer n, denoting the number of cuts that can be made on a pancake, find the maximum number of pieces that can be formed by making n cuts.\nNOTE: Cuts can't be horizontal.\n \nExample 1:\nInput: N = 5\nOutput: 16\nExplanation: 16 pieces can be formed by\nmaking 5 cuts.\nExample 2:\nInput: N = 3\nOutput: 7\nExplanation: 7 pieces can be formed by \nmaking 3 cuts.\n \nYour Task: \nYou don't need to read or print anything. Your task is to complete the function maximum_Cuts() which takes n as input parameter and returns the maximum number of pieces that can be formed by making n cuts.\n \nExpected Time Complexity: O(1)\nExpected Space Complexity: O(1)\nConstraints:\n1 <= N <= 10000", "solutions": ["def maximum_cuts(n):\n return (n + 1) * (n + 2) // 2 - n", "def maximum_cuts(n):\n if n % 2:\n return int((n + 1) / 2) * n + 1\n else:\n return int((n + 1) / 2) * (n + 1) + 1", "def maximum_cuts(n):\n p = n * (n + 1) / 2 + 1\n return int(p)", "def maximum_cuts(n):\n lst = []\n lst.append(2)\n lst.append(4)\n d = 2\n for i in range(1, n):\n c = d + i + lst[i]\n lst.append(c)\n return lst[n - 1]", "def maximum_cuts(n):\n if n <= 2:\n if n == 0:\n return 1\n return 2 * n\n else:\n a = 1 + n * (n + 1) // 2\n return a", "def maximum_cuts(n):\n prev = 2\n for i in range(2, n + 1):\n prev += i\n return prev", "def maximum_cuts(n):\n sum = 2\n j = 2\n for i in range(1, n):\n sum += j\n j += 1\n return sum", "def maximum_cuts(n):\n result = int(1 + n * (n + 1) / 2)\n return result", "def maximum_cuts(n):\n c = 1\n for i in range(1, n + 1):\n c += i\n return c", "def maximum_cuts(n):\n cut = 1\n cuts = n * (n + 1) // 2 + 1\n return cuts"], "starter_code": "def maximum_cuts(n):\n", "input_output": {"inputs": ["N = 5", "N = 3"], "outputs": ["16", "7"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/the-lazy-caterers-problem2527/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "maximum_cuts", "task_id": "TACO_lite/256", "example": [[[5], [3]], ["16", "7"]]} +{"requirement": "Let's say we have a number, `num`. Find the number of values of `n` such that: there exists `n` consecutive **positive** values that sum up to `num`. A positive number is `> 0`. `n` can also be 1.\n\n```python\n#Examples\nnum = 1\n#1\nreturn 1\n\nnum = 15\n#15, (7, 8), (4, 5, 6), (1, 2, 3, 4, 5)\nreturn 4\n\nnum = 48\n#48, (15, 16, 17)\nreturn 2\n\nnum = 97\n#97, (48, 49)\nreturn 2\n```\nThe upper limit is `$10^8$`", "solutions": ["def consecutive_sum(num):\n upper_limit = 1\n while True:\n if upper_limit * (upper_limit + 1) // 2 > num:\n break\n upper_limit += 1\n return sum([1 if i % 2 and (not num % i) else 1 if not i % 2 and num % i == i // 2 else 0 for i in range(1, upper_limit)])", "from math import sqrt\n\ndef consecutive_sum(n):\n cnt = 0\n lim = int(sqrt(2 * n))\n m = 1\n while m <= lim:\n u = n / m + m / 2 + 0.5\n if int(u) == u:\n cnt += 1\n m += 1\n return cnt", "def consecutive_sum(n):\n top = (1 + (1 + 8 * n) ** 0.5) / 2\n return sum((not (n - (v - 1) * v // 2) % v for v in range(1, int(top))))", "from functools import partial\nfrom itertools import accumulate, count, takewhile\nfrom operator import ge\n\ndef consecutive_sum(num):\n return sum(((num - start) % step == 0 for (step, start) in enumerate(takewhile(partial(ge, num), accumulate(count(1))), 1)))", "def consecutive_sum(num):\n count = 0\n N = 1\n while N * (N + 1) < 2 * num:\n a = (num - N * (N + 1) / 2) / (N + 1)\n if a - int(a) == 0.0:\n count += 1\n N += 1\n return count + 1", "from math import sqrt\n\ndef consecutive_sum(num):\n counter = 1\n for i in range(2, int(sqrt(2 * num) + 1)):\n if i % 2 == 0:\n if num / i - num // i == 0.5:\n counter += 1\n elif num / i == num // i:\n counter += 1\n return counter", "def factors(n):\n seen = {1, n}\n for a in range(2, 1 + int(n ** 0.5)):\n (b, m) = divmod(n, a)\n if m == 0:\n if a in seen:\n break\n seen.add(a)\n seen.add(b)\n return sorted(seen)\n\ndef consecutive_sum(num):\n return sum((1 for d in factors(num) if d % 2))", "from functools import reduce\n\ndef divisors(n):\n return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))\n\ndef consecutive_sum(n):\n return len([x for x in divisors(n) if x % 2 != 0])", "from numpy import roots\n\ndef consecutive_sum(num):\n return sum((num % i == (i >> 1) * (i & 1 ^ 1) for i in range(1, int(roots([1 / 2, 1 / 2, -num])[1] + 1))))", "def consecutive_sum(num):\n sol = 1\n nums = 1\n i = 2\n while num > nums:\n if (num - nums) % i == 0:\n sol += 1\n nums += i\n i += 1\n return sol"], "starter_code": "def consecutive_sum(num):\n", "input_output": {"fn_name": "consecutive_sum", "inputs": [[1], [15], [48], [97]], "outputs": [[1], [4], [2], [2]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5f120a13e63b6a0016f1c9d5", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "consecutive_sum", "task_id": "TACO_lite/283", "example": [[[1], [15], [48], [97]], ["1", "4", "2", "2"]]} +{"requirement": "In input string ```word```(1 word):\n* replace the vowel with the nearest left consonant.\n* replace the consonant with the nearest right vowel.\n\nP.S. To complete this task imagine the alphabet is a circle (connect the first and last element of the array in the mind). For example, 'a' replace with 'z', 'y' with 'a', etc.(see below)\n\nFor example:\n```\n'codewars' => 'enedazuu'\n'cat' => 'ezu'\n'abcdtuvwxyz' => 'zeeeutaaaaa'\n```\n\nIt is preloaded: \n\n```\nconst alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\nconst consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'];\nconst vowels = ['a','e','i','o','u'];\n```\n\nP.S. You work with lowercase letters only.", "solutions": ["def replace_letters(word):\n return word.translate(str.maketrans('abcdefghijklmnopqrstuvwxyz', 'zeeediiihooooonuuuuutaaaaa'))", "from string import ascii_lowercase as al\ntbl = str.maketrans(al, ''.join((al[(i - 1) % 26] if x in 'aeiou' else next((al[j % 26] for j in range(i + 1, 100) if al[j % 26] in 'aeiou')) for (i, x) in enumerate(al))))\n\ndef replace_letters(word):\n return word.translate(tbl)", "def replace_letters(word):\n d = {'a': 'z', 'b': 'e', 'c': 'e', 'd': 'e', 'e': 'd', 'f': 'i', 'g': 'i', 'h': 'i', 'i': 'h', 'j': 'o', 'k': 'o', 'l': 'o', 'm': 'o', 'n': 'o', 'o': 'n', 'p': 'u', 'q': 'u', 'r': 'u', 's': 'u', 't': 'u', 'u': 't', 'v': 'a', 'w': 'a', 'x': 'a', 'y': 'a', 'z': 'a'}\n return ''.join([d[i] for i in list(word)])"], "starter_code": "def replace_letters(word):\n", "input_output": {"fn_name": "replace_letters", "inputs": [["cat"], ["codewars"], ["abcdtuvwxyz"]], "outputs": [["ezu"], ["enedazuu"], ["zeeeutaaaaa"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5a4331b18f27f2b31f000085", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "replace_letters", "task_id": "TACO_lite/309", "example": [[], []]} +{"requirement": "Serialization is to store a tree in an array so that it can be later restored and Deserialization is reading tree back from the array. Now your task is to complete the function serialize which stores the tree into an array A[ ] and deSerialize which deserializes the array to the tree and returns it.\nNote: The structure of the tree must be maintained. Multiple nodes can have the same data.\nExample 1:\nInput:\n 1\n / \\\n 2 3\nOutput: 2 1 3\nExample 2:\nInput:\n 10\n / \\\n 20 30\n / \\\n 40 60\nOutput: 40 20 60 10 30\nYour Task:\nThe task is to complete two functions serialize which takes the root node of the tree as input and stores the tree into an array and deSerialize which deserializes the array to the original tree and returns the root of it.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\nConstraints:\n1 <= Number of nodes <= 1000\n1 <= Data of a node <= 1000", "solutions": ["from collections import deque\n\ndef serialize(root, ans):\n if root is None:\n return ans\n queue = deque()\n queue.append(root)\n while len(queue) != 0:\n size = len(queue)\n for i in range(size):\n node = queue[0]\n queue.popleft()\n if node is None:\n ans.append(None)\n continue\n queue.append(node.left)\n queue.append(node.right)\n ans.append(node.data)\n while ans[-1] is None:\n ans.pop()\n return ans\n\ndef deSerialize(arr):\n if len(arr) == 0:\n return None\n queue = deque()\n root = Node(arr[0])\n queue.append(root)\n start = 1\n end = len(arr)\n while len(queue) != 0 and start < len(arr):\n size = len(queue)\n elements_to_extract = size * 2\n end = min(len(arr), start + elements_to_extract)\n rotation = 0\n while start < end:\n node = None\n if arr[start] is not None:\n node = Node(arr[start])\n queue.append(node)\n curr = queue[0]\n if rotation == 0:\n curr.left = node\n rotation = 1\n else:\n curr.right = node\n queue.popleft()\n rotation = 0\n start += 1\n return root", "def serialize(root, A):\n q = [root]\n A.append(root)\n while len(q) > 0:\n l = len(q)\n for _ in range(l):\n temp = q[0]\n q.pop(0)\n if temp.left != None:\n q.append(temp.left)\n A.append(temp.left)\n else:\n A.append(None)\n if temp.right != None:\n q.append(temp.right)\n A.append(temp.right)\n else:\n A.append(None)\n return A\n\ndef deSerialize(A):\n root = A[0]\n A = A[1:]\n n = len(A)\n st = [root]\n for i in range(n // 2):\n temp = st[0]\n st.pop(0)\n temp.left = A[2 * i]\n temp.right = A[2 * i + 1]\n if A[2 * i] != None:\n st.append(A[2 * i])\n if A[2 * i + 1] != None:\n st.append(A[2 * i + 1])\n return root", "def serialize(root, A):\n if not root:\n A.append('#')\n return A\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n return A\n\ndef deSerialize(A):\n c = A.pop(0)\n if c == '#':\n return None\n r = Node(c)\n r.left = deSerialize(A)\n r.right = deSerialize(A)\n return r", "def serialize(root, A):\n if root is None:\n A.append('#')\n return A\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n return A\n\ndef deSerialize(A):\n curr = A.pop(0)\n if curr == '#':\n return None\n node = Node(curr)\n node.left = deSerialize(A)\n node.right = deSerialize(A)\n return node", "def serialize(root, A):\n if root is None:\n A.append(-1)\n return\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n\ndef deSerialize(A):\n temp = A.pop(0)\n if temp == -1:\n return\n root = Node(temp)\n root.left = deSerialize(A)\n root.right = deSerialize(A)\n return root", "def serialize(root, A):\n if not root:\n A.append(-1)\n return\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n\ndef deSerializeUtil(A, i):\n if i[0] >= len(A) or A[i[0]] == -1:\n i[0] += 1\n return None\n node = Node(A[i[0]])\n i[0] += 1\n node.left = deSerializeUtil(A, i)\n node.right = deSerializeUtil(A, i)\n return node\n\ndef deSerialize(A):\n i = [0]\n return deSerializeUtil(A, i)\n\ndef __init__(val):\n self.data = val\n self.left = None\n self.right = None", "def serialize(root, A):\n if root == None:\n A.append(-1)\n return A\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n return A\n\ndef deSerialize(A):\n node = A.pop(0)\n if node == -1:\n return None\n root = Node(node)\n root.left = deSerialize(A)\n root.right = deSerialize(A)\n return root", "def serialize(root, A):\n if root == None:\n return\n serialize(root.left, A)\n A.append(root.data)\n serialize(root.right, A)\n\ndef solve(A, st, lst):\n if st > lst:\n return None\n mid = (st + lst) // 2\n root = Node(A[mid])\n root.left = solve(A, st, mid - 1)\n root.right = solve(A, mid + 1, lst)\n return root\n\ndef deSerialize(A):\n st = 0\n lst = len(A) - 1\n return solve(A, st, lst)", "def serialize(root, A):\n if not root:\n A.append('#')\n return A\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n return A\n\ndef deSerialize(A):\n curr = A.pop(0)\n if curr == '#':\n return None\n result = Node(curr)\n result.left = deSerialize(A)\n result.right = deSerialize(A)\n return result", "def serialize(root, A):\n q = [root]\n A.append(root)\n while len(q) > 0:\n temp = q[0]\n q.pop(0)\n if temp.left != None:\n A.append(temp.left)\n q.append(temp.left)\n else:\n A.append(None)\n if temp.right != None:\n A.append(temp.right)\n q.append(temp.right)\n else:\n A.append(None)\n\ndef deSerialize(A):\n root = A[0]\n q = [root]\n A = A[1:]\n for i in range(len(A) // 2):\n node = q[0]\n q.pop(0)\n node.left = A[2 * i]\n if A[2 * i] != None:\n q.append(A[2 * i])\n node.right = A[2 * i + 1]\n if A[2 * i + 1] != None:\n q.append(A[2 * i + 1])\n return root", "from collections import deque\n\ndef serialize(root, A):\n if root == None:\n return ''\n q = deque([root])\n while q:\n node = q.popleft()\n if node:\n q.append(node.left)\n q.append(node.right)\n A.append(str(node.data) if node else '#')\n return A\n\ndef deSerialize(data):\n if not data:\n return None\n arr = data\n root = Node(int(arr[0]))\n q = deque([root])\n index = 1\n while q:\n node = q.popleft()\n if arr[index] != '#':\n node.left = Node(int(arr[index]))\n q.append(node.left)\n index += 1\n if arr[index] != '#':\n node.right = Node(int(arr[index]))\n q.append(node.right)\n index += 1\n return root", "def serialize(root, A):\n if not root:\n A.append('#')\n return A\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n return A\n\ndef deSerialize(A):\n tmp = A.pop(0)\n if tmp == '#':\n return None\n root = Node(tmp)\n root.left = deSerialize(A)\n root.right = deSerialize(A)\n return root", "def serialize(root, A):\n if not root:\n return None\n arr = [root]\n while arr:\n t = arr.pop()\n if not t:\n A.append('#')\n else:\n A.append(str(t.data))\n arr.append(t.right)\n arr.append(t.left)\n\ndef deSerialize(A):\n if not A:\n return None\n global t\n t = 0\n return helper(A)\n\ndef helper(array):\n global t\n if array[t] == '#':\n return None\n root = Node(int(array[t]))\n t += 1\n root.left = helper(array)\n t += 1\n root.right = helper(array)\n return root", "def serialize(root, A):\n if root == None:\n return\n serialize(root.left, A)\n A.append(root.data)\n serialize(root.right, A)\n\ndef deSerialize(A):\n\n def solve(A, l, h):\n if l > h:\n return None\n mid = (l + h) // 2\n root = Node(A[mid])\n root.left = solve(A, l, mid - 1)\n root.right = solve(A, mid + 1, h)\n return root\n l = 0\n h = len(A) - 1\n return solve(A, l, h)", "def serialize(root, A):\n if not root:\n A.append('X')\n return\n A.append(str(root.data))\n serialize(root.left, A)\n serialize(root.right, A)\n return A\n\ndef deSerialize(A):\n if not A:\n return None\n val = A.pop(0)\n if val == 'X':\n return None\n node = Node(int(val))\n node.left = deSerialize(A)\n node.right = deSerialize(A)\n return node", "def serialize(root, A):\n if root == None:\n A.append(-1)\n return\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n\ndef deSerializeUtil(A):\n global index\n index += 1\n if A[index] == -1:\n return None\n root = Node(A[index])\n root.left = deSerializeUtil(A)\n root.right = deSerializeUtil(A)\n return root\n\ndef deSerialize(A):\n global index\n index = -1\n return deSerializeUtil(A)", "def serialize(root, A):\n if root is None:\n return\n serialize(root.left, A)\n A.append(root.data)\n serialize(root.right, A)\n\ndef func(A):\n if not A:\n return None\n mid = len(A) // 2\n root = Node(A[mid])\n root.left = func(A[:mid])\n root.right = func(A[mid + 1:])\n return root\n\ndef deSerialize(A):\n return func(A)", "def serialize(root, a):\n if root is None:\n return []\n q = []\n q.append(root)\n while q:\n cur = q.pop(0)\n if cur == None:\n a.append('#')\n else:\n a.append(cur.data)\n if cur:\n q.append(cur.left)\n q.append(cur.right)\n return a\n\ndef deSerialize(A):\n if len(A) == 0 or A[0] == '#':\n return None\n new_node = Node(A[0])\n q = []\n q.append(new_node)\n i = 1\n while q:\n cur = q.pop(0)\n if len(A) >= i:\n if A[i] == '#':\n cur.left = None\n i += 1\n else:\n lef_node = Node(A[i])\n cur.left = lef_node\n q.append(cur.left)\n i += 1\n if A[i] == '#':\n cur.right = None\n i += 1\n else:\n rigt_node = Node(A[i])\n cur.right = rigt_node\n q.append(cur.right)\n i += 1\n return new_node"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["1\r\n / \\\r\n 2 3", "10\r\n / \\\r\n 20 30\r\n / \\\r\n 40 60"], "outputs": ["2 1 3", "40 20 60 10 30"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/serialize-and-deserialize-a-binary-tree/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "__init__", "task_id": "TACO_lite/280", "example": [[], []]} +{"requirement": "Given three integers x, y, z, the task is to compute the value of GCD(LCM(x,y), LCM(x,z)) and return the value.\nWhere, GCD = Greatest Common Divisor, LCM = Least Common Multiple.\nExample 1:\nInput: x = 15, y = 20, z = 100\nOutput: 60\nExplanation: GCD(LCM(15,20), LCM(15,100))\n=GCD(60,300)=60.\n​Example 2:\nInput: x = 30, y = 40, z = 400\nOutput: 120\nExplanation: GCD(LCM(30,40), LCM(30,400))\n=GCD(120,1200)=120.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function findValue() which takes x, y, z as inputs and returns the answer.\nExpected Time Complexity: O(max(log x, log y, log z))\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ x, y, z ≤ 10^{6}", "solutions": ["def findvalue(x, y, z):\n\n def gcd(a, b):\n if b == 0:\n return a\n else:\n return gcd(b, a % b)\n lcm1 = int(x * y / gcd(x, y))\n lcm2 = int(x * z / gcd(x, z))\n return gcd(lcm1, lcm2)", "import math\n\ndef findvalue(x, y, z):\n a = x * y // math.gcd(x, y)\n b = x * z // math.gcd(x, z)\n return math.gcd(a, b)", "def findvalue(x, y, z):\n return Solution.lcm(x, Solution.gcd(y, z))\n\ndef gcd(a, b):\n if a == 0:\n return b\n return Solution.gcd(b % a, a)\n\ndef lcm(a, b):\n return a * b // Solution.gcd(a, b)", "from functools import reduce\n\ndef findvalue(x, y, z):\n gcd = lambda a, b: a if b == 0 else gcd(b, a % b)\n lcd = lambda a, b: int(a * b / gcd(a, b))\n return lcd(x, gcd(y, z))", "def gcd(a, b):\n if b == 0:\n return a\n return self.gcd(b, a % b)\n\ndef findvalue(x, y, z):\n lcmxy = x * y // self.gcd(x, y)\n lcmxz = x * z // self.gcd(x, z)\n return self.gcd(lcmxy, lcmxz)", "def gcd2(a, b):\n while a != b:\n if a > b:\n a -= b\n else:\n b -= a\n return a\n\ndef gcd(a, b):\n if b == 0:\n return a\n else:\n return self.gcd(b, a % b)\n\ndef findvalue(x, y, z):\n gcdNum1 = self.gcd(x, y)\n gcdNum2 = self.gcd(x, z)\n lcm1 = int(x * y / gcdNum1)\n lcm2 = int(x * z / gcdNum2)\n grandGCD = self.gcd(lcm1, lcm2)\n return grandGCD", "import math as m\n\ndef findvalue(x, y, z):\n g1 = m.gcd(x, y)\n g2 = m.gcd(x, z)\n l1 = x * y // g1\n l2 = x * z // g2\n g3 = m.gcd(l1, l2)\n return g3", "import math as m\n\ndef findvalue(x, y, z):\n l = x * y // m.gcd(x, y - x)\n l1 = x * z // m.gcd(x, z - x)\n return m.gcd(l, l1)", "def gcd(a, b):\n while a != 0 and b != 0:\n if a < b:\n b = b % a\n else:\n a = a % b\n if a == 0:\n return b\n else:\n return a\n\ndef findvalue(x, y, z):\n m = x * y // self.gcd(x, y)\n n = x * z // self.gcd(x, z)\n return self.gcd(m, n)", "def gc(n, m):\n while n != 0 and m != 0:\n if n > m:\n n = n % m\n else:\n m = m % n\n if n == 0:\n return m\n else:\n return n\n\ndef findvalue(x, y, z):\n k = x * y // self.gc(x, y)\n c = x * z // self.gc(x, z)\n return self.gc(k, c)", "def findvalue(x, y, z):\n\n def gcd(a, b):\n while b:\n (a, b) = (b, a % b)\n return a\n return gcd(x * y // gcd(x, y), x * z // gcd(x, z))", "import math\n\ndef findvalue(x, y, z):\n k1 = x * y // math.gcd(x, y)\n k2 = x * z // math.gcd(x, z)\n return math.gcd(k1, k2)", "import math\n\ndef findvalue(x, y, z):\n l1 = x * y // math.gcd(x, y)\n l2 = x * z // math.gcd(x, z)\n res = math.gcd(l1, l2)\n return res", "def gcd(x, y):\n return x if y == 0 else self.gcd(y, x % y)\n\ndef findvalue(x, y, z):\n return self.gcd(x // self.gcd(x, y) * y, x // self.gcd(x, z) * z)"], "starter_code": "def findvalue (x, y, z):\n", "input_output": {"inputs": ["x = 15, y = 20, z = 100", "x = 30, y = 40, z = 400"], "outputs": ["60", "120"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/gcd-lcm-and-distributive-property4419/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(max(log x, log y, log z))", "entry_point": "findvalue", "task_id": "TACO_lite/328", "example": [[[15, 20, 100], [30, 40, 400]], ["60", "120"]]} +{"requirement": "Given a sorted and rotated array A of N elements which is rotated at some point, and may contain duplicates and given an element key. Check whether the key exist in the array A or not.\nExample 1:\nInput:\nN = 7\nA[] = {2,5,6,0,0,1,2}\nkey = 0\nOutput:\n1\nExplanation:\n0 is found at index 3.\nExample 2:\nInput:\nN = 7\nA[] = {2,5,6,0,0,1,2}\nkey = 3\nOutput:\n0\nExplanation:\nThere is no element that has value 3.\nYour Task:\nComplete the function search() which takes a integer N and an array A and the Key as input parameters, and returns the answer.\nExpected Time Complexity: O(log N).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 ≤ N ≤ 5000\n0 ≤ A[i] ≤ 108\n1 ≤ key ≤ 108", "solutions": ["def search(n, arr, k):\n if k in arr:\n return 1\n else:\n return 0", "def search(n, arr, k):\n for i in range(len(arr)):\n if arr[i] == k:\n return 1\n return 0", "def search(n, A, key):\n l = 0\n h = n - 1\n while l <= h:\n mid = (l + h) // 2\n if key == A[mid]:\n return 1\n if A[mid] == A[l]:\n l += 1\n continue\n if A[l] <= A[mid]:\n if key >= A[l] and key <= A[mid]:\n h = mid - 1\n else:\n l = mid + 1\n elif A[mid] <= key and key <= A[h]:\n l = mid + 1\n else:\n h = mid - 1\n return 0", "def search(n, arr, k):\n i = 0\n j = n - 1\n while i <= j:\n mid = i + j >> 1\n if arr[mid] == k:\n return 1\n elif arr[i] == k:\n return 1\n elif arr[j] == k:\n return 1\n elif arr[i] == arr[mid] == arr[j]:\n i += 1\n j -= 1\n elif arr[i] < arr[mid]:\n if arr[i] <= k and k <= arr[mid]:\n j = mid - 1\n else:\n i = mid + 1\n elif arr[mid] <= k and k <= arr[j]:\n i = mid + 1\n else:\n j = mid - 1\n return 0", "def search(n, nums, target):\n (left, right) = (0, n - 1)\n while left <= right:\n mid = (left + right) // 2\n curr = nums[mid]\n if curr == target:\n return 1\n elif nums[left] == curr == nums[right]:\n left += 1\n right -= 1\n elif nums[left] <= curr:\n if nums[left] <= target < curr:\n right = mid - 1\n else:\n left = mid + 1\n elif curr < target <= nums[right]:\n left = mid + 1\n else:\n right = mid - 1\n return 0", "def search(n, a, key):\n low = 0\n high = n - 1\n while low <= high:\n mid = low + (high - low) // 2\n if a[mid] == k:\n return 1\n if a[mid] == a[low]:\n low += 1\n continue\n if a[mid] == a[high]:\n high -= 1\n continue\n if a[low] < a[mid]:\n if k >= a[low] and k < a[mid]:\n high = mid - 1\n else:\n low = mid + 1\n elif k > a[mid] and k <= a[high]:\n low = mid + 1\n else:\n high = mid - 1\n return 0", "def search(n, arr, k):\n l = 0\n u = n - 1\n while l <= u:\n while l < u and arr[l] == arr[l + 1]:\n l += 1\n while l < u and arr[u] == arr[u - 1]:\n u -= 1\n mid = l + u >> 1\n if arr[mid] == k:\n return 1\n elif arr[l] <= arr[mid]:\n if arr[l] <= k and arr[mid] >= k:\n u = mid - 1\n else:\n l = mid + 1\n elif arr[u] >= k and arr[mid] <= k:\n l = mid + 1\n else:\n u = mid - 1\n return 0", "def search(n, arr, k):\n (lo, hi) = (0, n - 1)\n while lo <= hi:\n if hi - lo <= 5:\n return 1 if k in arr[lo:hi + 1] else 0\n mid = (lo + hi) // 2\n if arr[mid] == k or arr[lo] == k or arr[hi] == k:\n return 1\n elif arr[lo] == arr[hi] and arr[lo] == arr[mid]:\n lo += 1\n hi -= 1\n elif arr[lo] < arr[mid] or (arr[lo] == arr[mid] and arr[mid] > arr[hi]):\n if arr[lo] < k and k < arr[mid]:\n hi = mid - 1\n else:\n lo = mid + 1\n elif arr[hi] >= arr[mid] or (arr[hi] == arr[mid] and arr[mid] < arr[lo]):\n if arr[mid] < k and k < arr[hi]:\n lo = mid + 1\n else:\n hi = mid + 1\n return 0", "def search(n, arr, k):\n low = 0\n high = n - 1\n while low <= high:\n mid = (low + high) // 2\n if arr[mid] == k:\n return 1\n if arr[low] == arr[mid] and arr[mid] == arr[high]:\n low += 1\n high -= 1\n elif arr[low] <= arr[mid]:\n if arr[low] <= k < arr[mid]:\n high = mid - 1\n else:\n low = mid + 1\n elif arr[mid] <= k <= arr[high]:\n low = mid + 1\n else:\n high = mid - 1\n return 0", "def search(n, nums, target):\n if nums == None or len(nums) == 0:\n return 0\n low = 0\n high = len(nums) - 1\n while low <= high and nums[low] == nums[high]:\n if nums[low] == target:\n return 1\n low += 1\n high -= 1\n while low <= high:\n mid = low + high >> 1\n if nums[mid] == target:\n return 1\n if nums[mid] >= nums[low]:\n if target >= nums[low] and target < nums[mid]:\n high = mid - 1\n else:\n low = mid + 1\n elif target <= nums[high] and target > nums[mid]:\n low = mid + 1\n else:\n high = mid - 1\n return 0", "def search(n, arr, k):\n ans = 0\n for i in range(n):\n if arr[i] == k:\n ans = 1\n else:\n continue\n return ans", "def search(n, arr, k):\n (left, right) = (0, len(arr) - 1)\n while left <= right:\n mid = (left + right) // 2\n if arr[mid] == k:\n return 1\n if arr[mid] == arr[left] and mid != left:\n left += 1\n right -= 1\n if arr[left] <= arr[mid]:\n if arr[mid] < k or arr[left] > k:\n left = mid + 1\n else:\n right = mid - 1\n elif arr[right] < k or arr[mid] > k:\n right = mid - 1\n else:\n left = mid + 1\n return 0", "def search(n, nums, target):\n high = len(nums) - 1\n low = 0\n mid = (high + low) // 2\n while high >= low:\n mid = (high + low) // 2\n if nums[mid] == target:\n return 1\n if nums[low] == target:\n return 1\n if nums[high] == target:\n return 1\n if nums[mid] == nums[high] and nums[high] == nums[low]:\n high -= 1\n low += 1\n continue\n if nums[low] <= nums[mid]:\n if target >= nums[low] and target <= nums[mid]:\n high = mid - 1\n continue\n else:\n low = mid + 1\n elif target >= nums[mid] and target <= nums[high]:\n low = mid + 1\n continue\n else:\n high = mid - 1\n return 0", "def search(n, A, key):\n for num in A:\n if num == key:\n return 1\n return 0", "def search(n, nums, target):\n s = 0\n e = n - 1\n while s < e and nums[s] == nums[s + 1]:\n s = s + 1\n while s < e and nums[e] == nums[e - 1]:\n e = e - 1\n while s <= e:\n mid = s + e >> 1\n if nums[mid] == target:\n return 1\n if nums[s] <= nums[mid]:\n if nums[s] <= target and nums[mid] >= target:\n e = mid - 1\n else:\n s = mid + 1\n elif nums[mid] <= target and nums[e] >= target:\n s = mid + 1\n else:\n e = mid - 1\n return 0", "def search(n, a, x):\n low = 0\n high = n - 1\n while low <= high:\n mid = low + (high - low) // 2\n if a[mid] == x:\n return 1\n elif a[low] == a[mid]:\n low += 1\n mid += 1\n elif a[low] < a[mid]:\n if a[low] <= x and a[mid] >= x:\n high = mid - 1\n else:\n low = mid + 1\n elif x >= a[mid] and x <= a[high]:\n low = mid + 1\n else:\n high = mid - 1\n return 0", "def search(n, arr, k):\n x = 0\n for i in range(n):\n if arr[i] == k:\n x = 1\n break\n return x", "def search(n, nums, target):\n (l, r) = (0, len(nums) - 1)\n while l <= r:\n mid = (l + r) // 2\n if target == nums[mid]:\n return 1\n if nums[l] < nums[mid]:\n if target > nums[mid] or target < nums[l]:\n l = mid + 1\n else:\n r = mid - 1\n elif nums[l] > nums[mid]:\n if target < nums[mid] or target > nums[r]:\n r = mid - 1\n else:\n l = mid + 1\n else:\n l += 1\n return 0", "def search(n, arr, target):\n l = 0\n h = n - 1\n m = l + (h - l) // 2\n while l <= h:\n if arr[m] == target:\n return 1\n if arr[m] == arr[l] and arr[m] == arr[h]:\n l += 1\n h -= 1\n elif arr[l] <= arr[m]:\n if arr[l] <= target and target < arr[m]:\n h = m - 1\n else:\n l = m + 1\n elif arr[m] < target and target <= arr[h]:\n l = m + 1\n else:\n h = m - 1\n m = (l + h) // 2\n return 0", "def search(n, arr, k):\n low = 0\n high = n - 1\n while low <= high:\n mid = (low + high) // 2\n if arr[mid] == k:\n return 1\n if arr[low] == arr[mid] == arr[high]:\n for i in range(low, high + 1):\n if arr[i] == k:\n return 1\n if arr[low] <= arr[mid]:\n if k >= arr[low] and k <= arr[mid]:\n high = mid - 1\n else:\n low = mid + 1\n elif k >= arr[mid] and k <= arr[high]:\n low = mid + 1\n else:\n high = mid - 1\n return 0", "def search(n, arr, k):\n try:\n ans = arr.index(k)\n if ans >= 0:\n return 1\n except:\n return 0"], "starter_code": "def search(n, arr, k):\n", "input_output": {"inputs": ["N = 7\r\nA[] = {2,5,6,0,0,1,2}\r\nkey = 0", "N = 7\r\nA[] = {2,5,6,0,0,1,2}\r\nkey = 3"], "outputs": ["1", "0"]}, "difficulty": "MEDIUM", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/search-in-rotated-array-2/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log N).", "entry_point": "search", "task_id": "TACO_lite/276", "example": [[[7, [2, 5, 6, 0, 0, 1, 2], 0], [7, [2, 5, 6, 0, 0, 1, 2], 3]], ["1", "0"]]} +{"requirement": "## Task\n\nGenerate a sorted list of all possible IP addresses in a network.\n\nFor a subnet that is not a valid IPv4 network return `None`.\n\n## Examples\n```\nipsubnet2list(\"192.168.1.0/31\") == [\"192.168.1.0\", \"192.168.1.1\"]\nipsubnet2list(\"213.256.46.160/28\") == None\n```", "solutions": ["import ipaddress as ip\n\ndef ipsubnet2list(subnet):\n try:\n return list(map(str, ip.ip_network(subnet).hosts()))\n except:\n pass", "def ip_to_int(ip):\n return sum((int(i[0]) << i[1] * 8 for i in zip(ip.split('.'), range(3, -1, -1))))\n\ndef int_to_ip(num):\n return '.'.join((str(num >> i * 8 & 255) for i in range(3, -1, -1)))\n\ndef ipsubnet2list(subnet):\n (net, prelen) = subnet.split('/')\n (num, mask) = (ip_to_int(net), 1 << 32 - int(prelen))\n if net != int_to_ip(num):\n return None\n if mask == 2:\n return [int_to_ip(num), int_to_ip(num + 1)]\n return [int_to_ip(num ^ i) for i in range(1, mask - 1)]", "from ipaddress import ip_network\nfrom typing import List, Union\n\ndef ipsubnet2list(subnet: str) -> Union[List[str], None]:\n try:\n return list(map(str, ip_network(subnet).hosts()))\n except ValueError:\n return", "def cidr_to_bits(subnet):\n subnet_int = int(subnet[-2:])\n mask_in_bits = [(1, 0)[i > subnet_int] for i in range(1, 33)]\n return mask_in_bits\n\ndef ip_bits(subnet):\n ip_bits_str = list([format(int(x), '#010b')[2:] for x in subnet[:-3].split('.')])\n ip_bits_int = [int(i) for x in ip_bits_str for i in x]\n return ip_bits_int\n\ndef f_addr_bits(x):\n return [i & j for (i, j) in zip(ip_bits(x), cidr_to_bits(x))]\n\ndef l_addr_bits(x):\n not_on_mask = [(0, 1)[i == 0] for i in cidr_to_bits(x)]\n return [i | j for (i, j) in zip(f_addr_bits(x), not_on_mask)]\n\ndef address_to_int(bits_lst):\n return [int(''.join((str(bits_lst[y + i]) for i in range(8))), 2) for y in range(0, 32, 8)]\n\ndef list_of_addresses(x):\n first_address = address_to_int(f_addr_bits(x))\n last_address = address_to_int(l_addr_bits(x))\n octets_ranges = [[i for i in range(i, j + 1)] if j - i != 0 else [i] for (i, j) in zip(first_address, last_address)]\n addresses = []\n for first_oct in octets_ranges[0]:\n for second in octets_ranges[1]:\n for third in octets_ranges[2]:\n for fourth in octets_ranges[3]:\n addresses.append(f'{first_oct}.{second}.{third}.{fourth}')\n return addresses\n\ndef ipsubnet2list(subnet):\n result = list_of_addresses(subnet)\n if subnet[:-3] in result:\n if len(result) == 2:\n return result\n return result[1:-1]\n else:\n return None", "from ipaddress import ip_network\n\ndef ipsubnet2list(subnet):\n try:\n return [ip.compressed for ip in ip_network(subnet).hosts()]\n except ValueError:\n return", "from ipaddress import IPv4Network, AddressValueError\n\ndef ipsubnet2list(subnet):\n try:\n return list(map(str, IPv4Network(subnet).hosts()))\n except AddressValueError:\n return None", "from ipaddress import IPv4Network, AddressValueError\n\ndef ipsubnet2list(subnet):\n try:\n ip_list = [str(ip) for ip in IPv4Network(subnet)]\n return ip_list[1:-1] if len(ip_list) > 2 else ip_list\n except AddressValueError:\n return None", "def ipsubnet2list(subnet):\n import ipaddress\n ls = []\n try:\n for i in ipaddress.IPv4Network(subnet):\n ls.append(str(i))\n except:\n return None\n return ls[1:-1] if len(ls) > 2 else ls", "def ipsubnet2list(subnet):\n (netaddr, prefix) = subnet.split('/')\n if not all([0 <= int(x) < 256 for x in netaddr.split('.')]):\n return None\n netaddrbyte = 0\n for x in netaddr.split('.'):\n netaddrbyte = netaddrbyte * 256 + int(x)\n r = []\n for i in range(2 ** (32 - int(prefix))):\n addr = netaddrbyte + i\n a = []\n for _ in range(4):\n a.append(addr % 256)\n addr //= 256\n r.append('.'.join(map(str, a[::-1])))\n if int(prefix) < 31:\n r = r[1:-1]\n return r", "def ipsubnet2list(s):\n try:\n return [str(x) for x in list(__import__('ipaddress').ip_network(s).hosts())]\n except ValueError:\n return None"], "starter_code": "def ipsubnet2list(subnet):\n", "input_output": {"fn_name": "ipsubnet2list", "inputs": [["192.168.1.0/31"], ["195.20.15.0/28"], ["174.0.153.152/29"], ["213.192.46.160/28"], ["213.256.46.160/28"]], "outputs": [[["192.168.1.0", "192.168.1.1"]], [["195.20.15.1", "195.20.15.2", "195.20.15.3", "195.20.15.4", "195.20.15.5", "195.20.15.6", "195.20.15.7", "195.20.15.8", "195.20.15.9", "195.20.15.10", "195.20.15.11", "195.20.15.12", "195.20.15.13", "195.20.15.14"]], [["174.0.153.153", "174.0.153.154", "174.0.153.155", "174.0.153.156", "174.0.153.157", "174.0.153.158"]], [["213.192.46.161", "213.192.46.162", "213.192.46.163", "213.192.46.164", "213.192.46.165", "213.192.46.166", "213.192.46.167", "213.192.46.168", "213.192.46.169", "213.192.46.170", "213.192.46.171", "213.192.46.172", "213.192.46.173", "213.192.46.174"]], [null]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Networks"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5980d4e258a9f5891e000062", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "ipsubnet2list", "task_id": "TACO_lite/316", "example": [[["192.168.1.0/31"], ["213.256.46.160/28"]], ["['192.168.1.0', '192.168.1.1']", "None"]]} +{"requirement": "Given an array of non-negative integers, you are initially positioned at the first index of the array.\n\nEach element in the array represents your maximum jump length at that position.\n\nDetermine if you are able to reach the last index.\n\nExample 1:\n\n\nInput: [2,3,1,1,4]\nOutput: true\nExplanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.\n\n\nExample 2:\n\n\nInput: [3,2,1,0,4]\nOutput: false\nExplanation: You will always arrive at index 3 no matter what. Its maximum\n  jump length is 0, which makes it impossible to reach the last index.", "solutions": ["def canjump(nums):\n n = len(nums)\n can = True\n smallest_idx = n - 1\n for i in range(n - 2, -1, -1):\n can = i + nums[i] >= smallest_idx\n if can:\n smallest_idx = i\n return can", "def canjump(nums):\n n = len(nums)\n maxReachable = 0\n for (i, num) in enumerate(nums):\n if num >= n - i - 1:\n return True\n flag = False\n if i + num >= maxReachable:\n for j in range(i + 1, num + i + 1):\n if nums[j] > 0:\n flag = True\n break\n if flag == False:\n return False\n maxReachable = max(maxReachable, i + num)\n return True", "def canjump(nums):\n last = len(nums) - 1\n for i in range(len(nums) - 2, -1, -1):\n if i + nums[i] >= last:\n last = i\n return True if not last else False", "def canjump(nums):\n m = 0\n for i in range(len(nums)):\n if i > m:\n return False\n m = max(m, nums[i] + i)\n return True", "def canjump(nums):\n if not nums:\n return False\n res = [False for num in nums]\n res[0] = True\n end = 0\n for (i, num) in enumerate(nums):\n if res[i] == False:\n continue\n if i + num >= len(nums):\n return True\n if end < i + num:\n for j in range(end + 1, i + num + 1):\n res[j] = True\n end = i + num\n return res[-1]", "def canjump(nums):\n lastPos = len(nums) - 1\n for i in range(len(nums) - 1, -1, -1):\n if i + nums[i] >= lastPos:\n lastPos = i\n return lastPos == 0", "def canjump(nums):\n if len(nums) == 25003:\n return False\n length = len(nums)\n accessible = [False] * length\n accessible[0] = True\n for i in range(length - 1):\n if not accessible[i]:\n return False\n for j in range(i + 1, min(nums[i] + i + 1, length)):\n accessible[j] = True\n if j == length - 1:\n return True\n return accessible[length - 1]", "def canjump(nums):\n lo = hi = 0\n nexthi = 0\n while hi < len(nums) - 1:\n for i in range(lo, hi + 1):\n nexthi = max(nexthi, i + nums[i])\n if hi == nexthi:\n return False\n (lo, hi) = (hi + 1, nexthi)\n return True", "def canjump(nums):\n last = len(nums) - 1\n i = last\n while i >= 0:\n if nums[i] + i >= last:\n last = i\n i -= 1\n return last == 0", "def canjump(nums):\n near = len(nums) - 1\n for i in range(len(nums) - 2, -1, -1):\n if near <= i + nums[i]:\n near = i\n return near == 0", "def canjump(nums):\n n_nums = len(nums)\n surfix = [0 for _ in range(n_nums + 1)]\n surfix[n_nums - 1] = 1\n for i in range(n_nums - 2, -1, -1):\n accu = surfix[i + 1] - surfix[min(n_nums, i + nums[i] + 1)]\n if accu > 0:\n surfix[i] = surfix[i + 1] + 1\n else:\n surfix[i] = surfix[i + 1]\n return surfix[0] > surfix[1]", "def canjump(nums):\n if not nums or len(nums) == 1:\n return True\n status = [False] * (len(nums) - 1) + [True]\n curr = len(nums) - 1\n for j in range(len(nums) - 2, -1, -1):\n if status[min(len(nums) - 1, j + nums[j])]:\n for i in range(j, curr):\n status[i] = True\n curr = j\n return status[0]"], "starter_code": "def canjump(nums: List[int]) -> bool:\n", "input_output": {"fn_name": "canJump", "inputs": [[[2, 3, 1, 1, 4]]], "outputs": [true]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Dynamic Programming", "Greedy"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures", "Greedy algorithms"], "skill_types": ["Dynamic programming", "Data structures", "Greedy algorithms"], "url": "https://leetcode.com/problems/jump-game/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "canjump", "task_id": "TACO_lite/332", "example": [[], []]} +{"requirement": "write me a function `stringy` that takes a `size` and returns a `string` of alternating `'1s'` and `'0s'`.\n\nthe string should start with a `1`.\n\na string with `size` 6 should return :`'101010'`.\n\nwith `size` 4 should return : `'1010'`.\n\nwith `size` 12 should return : `'101010101010'`.\n\nThe size will always be positive and will only use whole numbers.", "solutions": ["def stringy(size):\n return ''.join([str(i % 2) for i in range(1, size + 1)])", "def stringy(size):\n return ('10' * size)[:size]", "from itertools import cycle, islice\n\ndef stringy(size):\n return ''.join(islice(cycle('10'), size))", "def stringy(size):\n s = ''\n for x in range(0, size):\n s += str('1') if x % 2 == 0 else str('0')\n return s", "def stringy(size):\n return '10' * (size // 2) + '1' * (size % 2)", "def stringy(size):\n return '10' * (size // 2) if size % 2 == 0 else '10' * (size // 2) + '1'", "def stringy(size):\n res = ''\n for x in range(0, size):\n res += '1' if x % 2 == 0 else '0'\n return res", "def stringy(size):\n str = ''\n while len(str) < size:\n str += '1'\n if len(str) < size:\n str += '0'\n return str", "stringy = lambda size: ('10' * (size // 2 + 1))[:size]", "def stringy(size):\n arr = []\n for i in range(size):\n if i % 2 == 0:\n arr.append('1')\n else:\n arr.append('0')\n return ''.join(arr)", "stringy = lambda size: ('10' * size)[:size]", "ONE_ZERO = '10'\n\ndef stringy(size):\n return ''.join((ONE_ZERO[a % 2] for a in range(size)))", "def stringy(size: int) -> str:\n return ''.join([str(_ % 2) for _ in range(1, size + 1)])", "def gen():\n while True:\n yield '1'\n yield '0'\n\ndef stringy(size):\n g = gen()\n return ''.join((next(g) for _ in range(size)))", "stringy = lambda n: ('10' * n)[:n]", "def stringy(size):\n return ''.join(['1' if a % 2 == 0 else '0' for a in range(size)])", "def stringy(size):\n return ''.join([str((a + 1) % 2) for a in range(size)])", "def stringy(size):\n binary = '10'\n s = size * binary\n return s[:size]", "def stringy(size):\n return ''.join(map(str, map(int, map(lambda x: not x % 2, range(size)))))", "def stringy(size):\n if size % 2 == 0:\n return '10' * int(size / 2)\n else:\n x = size - 1\n return '10' * int(x / 2) + '1'", "def stringy(size):\n return ''.join(('{:d}'.format(not i % 2) for i in range(size)))", "def stringy(size):\n return ('1' * size).replace('11', '10')", "def stringy(size):\n return __import__('re').sub('11', '10', '1' * size)", "def stringy(size):\n ans = ''\n for place in range(size):\n if place % 2 == 0:\n ans += '1'\n else:\n ans += '0'\n return ans", "def stringy(size):\n string = ''\n for num in range(size):\n if num % 2 == 0:\n string += '1'\n else:\n string += '0'\n return string", "def stringy(size):\n return str('10' * size)[:size]", "def stringy(size):\n x = True\n s = ''\n while size > 0:\n s += str(int(x))\n x = not x\n size -= 1\n return s", "def stringy(size):\n output_string = ''\n for i in range(size):\n if i % 2 == 0:\n output_string += '1'\n else:\n output_string += '0'\n return output_string", "def stringy(size):\n n = int(size / 2)\n i = 0\n c = '10'\n output = ''\n for i in range(n):\n output = output + c\n i += 1\n if size % 2 == 1:\n output = output + '1'\n return output", "def stringy(size):\n st = '1'\n i = 0\n while i < size - 1:\n if st[i] == '1':\n st = st + '0'\n else:\n st = st + '1'\n i += 1\n return st", "def stringy(size):\n strng = ''\n if size % 2 == 1:\n for i in range((size + 1) // 2):\n strng += '10'\n return strng[:-1]\n else:\n for i in range(size // 2):\n strng += '10'\n return strng", "def stringy(size):\n counter = 0\n res = ''\n while counter < size:\n if counter % 2 == 0:\n res += '1'\n counter += 1\n elif counter % 2 == 1:\n res += '0'\n counter += 1\n return res", "def stringy(size):\n (start, result) = ('1', '')\n for i in range(size):\n result += start\n start = '1' if start == '0' else '0'\n return result", "def stringy(size):\n x = 0\n list_size = []\n for i in range(size):\n if x % 2:\n i = 0\n else:\n i = 1\n x += 1\n list_size.append(i)\n return str(''.join(map(str, list_size)))", "def stringy(size):\n temp = ''\n for el in range(size):\n if el % 2:\n temp += '0'\n else:\n temp += '1'\n return temp", "def stringy(size):\n c = 0\n res = ''\n for i in range(size):\n c += 1\n if i == 0:\n res += '1'\n elif i == 1:\n res += '0'\n elif i % 2 == 0:\n res += '1'\n else:\n res += '0'\n return res", "def stringy(size):\n return ''.join((str(el % 2) for el in range(1, size + 1)))", "def stringy(size):\n value = True\n result = ''\n for i in range(size):\n result += str(int(value))\n value = not value\n return result", "def stringy(size):\n size - int(size)\n counter = 1\n word = ''\n while len(word) < size:\n if counter % 2 == 0:\n word = word + '0'\n if counter % 2 != 0:\n word = word + '1'\n counter += 1\n return word", "def stringy(size):\n s = ''\n for i in range(0, size):\n if i % 2 == 0:\n j = '1'\n s = s + j\n else:\n j = '0'\n s = s + j\n return s", "def stringy(size):\n st = ''\n while size > 0:\n st += '1'\n size -= 1\n if size < 1:\n break\n st += '0'\n size -= 1\n return st", "def stringy(size):\n return ''.join((str(x & 1) for x in range(1, size + 1)))", "def stringy(size):\n arr = []\n cnt = 0\n while True:\n arr.append('1')\n cnt += 1\n if cnt == size:\n break\n arr.append('0')\n cnt += 1\n if cnt == size:\n break\n return ''.join(arr)", "import math\n\ndef stringy(size):\n return str('10' * math.ceil(size / 2))[:size]", "def stringy(size):\n result = '10' * (size // 2)\n if size % 2 == 1:\n result = result + '1'\n return result", "from math import ceil\n\ndef stringy(size):\n return '10' * (size // 2) if size % 2 == 0 else str('10' * ceil(size / 2))[:-1]", "stringy = lambda l: '10' * (l // 2) + '1' * (l % 2)", "def stringy(size):\n x = ''\n while len(x) < size:\n x += '1'\n if len(x) < size:\n x += '0'\n return x", "def stringy(size):\n string = ''\n if size % 2 == 0:\n return '10' * int(size / 2)\n else:\n return str('10' * int(size / 2 + 1))[:-1]", "def stringy(size):\n x = ''\n n = 1\n while n <= size:\n if n % 2 == 1:\n x += '1'\n n += 1\n else:\n x += '0'\n n += 1\n return x", "def stringy(size):\n alot = '10' * 1000\n return alot[0:int(size)]", "def stringy(size):\n count = 3\n arr = ''\n for i in range(size):\n if count % 2 == 1:\n arr += '1'\n count += 1\n else:\n arr += '0'\n count += 1\n return arr", "def stringy(size):\n (c, l) = ('1', [])\n for i in range(size):\n if c == '1':\n l.append(c)\n c = '0'\n elif c == '0':\n l.append(c)\n c = '1'\n return ''.join(l)", "def stringy(size):\n for x in range(1, size + 1, 1):\n if x == 1:\n t = '1'\n elif t[-1] == '1':\n t += '0'\n else:\n t += '1'\n return t", "def stringy(size):\n return '10' * int(size / 2) if not size % 2 else '10' * int(size / 2) + '1'", "def stringy(size):\n res = ''\n n = 0\n while n < size:\n if n == size:\n break\n else:\n res += '1'\n n += 1\n if n == size:\n break\n else:\n res += '0'\n n += 1\n return res", "def stringy(size):\n x = ''\n while size > len(x):\n x = x + '1'\n while size > len(x):\n x = x + '0'\n break\n return x", "from itertools import islice, cycle\n\ndef stringy(size):\n return ''.join((str(i) for i in islice(cycle([1, 0]), 0, size)))", "def stringy(size):\n if size == 1:\n return '1'\n elif size % 2 == 0:\n return '10' * (size // 2)\n elif size != 1 and size % 2 == 1:\n return '1' + '01' * (size // 2)", "from math import ceil\n\ndef stringy(size):\n return '0'.join('1' * ceil(size / 2)) + '0' * ((size - 1) % 2)", "def stringy(size):\n res = ''\n t = size\n while t > 0:\n if t % 2 == 1:\n res = '1' + res\n else:\n res = '0' + res\n t -= 1\n return res", "def stringy(size):\n if size == 1:\n return '1'\n if size % 2 == 0:\n return '10' * int(size / 2)\n return '10' * int((size - 1) / 2) + '1'", "def stringy(size):\n choices = [1, 0]\n a = ''\n for i in range(size):\n a += str(choices[i % 2])\n return a", "def stringy(size):\n return ''.join([['1', '0'][loop % 2] for loop in range(size)])", "def stringy(size):\n outStr = ''\n lastAdd = 0\n for x in range(size):\n if lastAdd == 0:\n outStr += str(1)\n lastAdd = 1\n else:\n outStr += str(0)\n lastAdd = 0\n return outStr", "def stringy(size):\n i = 0\n list1 = ['1']\n for n in range(size - 1):\n if i % 2 == 0:\n list1.append('0')\n i += 1\n else:\n list1.append('1')\n i += 1\n return ''.join(list1)", "def stringy(size):\n res = ''\n n = True\n for i in range(size):\n if n:\n res += '1'\n n = False\n else:\n res += '0'\n n = True\n return res", "def stringy(size):\n S = ''\n nextChar = '1'\n for i in range(size):\n S += nextChar\n if nextChar == '1':\n nextChar = '0'\n else:\n nextChar = '1'\n return S", "import math\n\ndef stringy(size):\n if size == 1:\n return '1'\n elif size % 2 == 0:\n return '10' * int(size / 2)\n else:\n return '10' * math.floor(size / 2) + '1'"], "starter_code": "def stringy(size):\n", "input_output": {"fn_name": "stringy", "inputs": [[3], [5], [12], [26], [28]], "outputs": [["101"], ["10101"], ["101010101010"], ["10101010101010101010101010"], ["1010101010101010101010101010"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms", "Binary"], "name": null, "source": "codewars", "tags": ["String algorithms", "Bit manipulation"], "skill_types": ["Bit manipulation"], "url": "https://www.codewars.com/kata/563b74ddd19a3ad462000054", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "stringy", "task_id": "TACO_lite/238", "example": [[[6], [4], [12]], ["101010", "1010", "101010101010"]]} +{"requirement": "Find the 2nd largest integer in array\nIf the array has no 2nd largest integer then return nil.\nReject all non integers elements and then find the 2nd largest integer in array\n\nfind_2nd_largest([1,2,3]) => 2\n\nfind_2nd_largest([1,1,1,1,1]) => nil\nbecause all elements are same. Largest no. is 1. and there is no 2nd largest no.\n\nfind_2nd_largest([1,'a','2',3,3,4,5,'b']) => 4\nas after rejecting non integers array will be [1,3,3,4,5]\nLargest no. is 5. and 2nd largest is 4.\n\nReturn nil if there is no 2nd largest integer.\nTake care of big numbers as well", "solutions": ["def find_2nd_largest(arr):\n arr = sorted((i for i in set(arr) if type(i) == int))\n return arr[-2] if len(arr) > 1 else None", "def find_2nd_largest(arr):\n newarr = sorted(list({x for x in arr if type(x) == int}))\n return newarr[-2] if len(newarr) > 1 else None", "def find_2nd_largest(arr):\n (a, b) = (float('-inf'), float('-inf'))\n for n in arr:\n if isinstance(n, int):\n if n > b:\n b = n\n if b > a:\n (a, b) = (b, a)\n return None if a == b else b", "from heapq import nlargest\n\ndef find_2nd_largest(arr):\n two = nlargest(2, {v for v in arr if isinstance(v, int)})\n if len(two) == 2:\n return two[1]", "def find_2nd_largest(arr):\n return next(iter(sorted((n for n in set(arr) if type(n) == int))[-2:-1]), None)", "def find_2nd_largest(arr):\n res = [arr[i] for i in range(0, len(arr)) if isinstance(arr[i], int)]\n res.sort(reverse=True)\n if len(set(arr)) == 1:\n return None\n else:\n return res[1]", "def find_2nd_largest(arr):\n SECOND_lARGEST = -2\n arr_set = set(arr)\n numbers = sorted((number for number in arr_set if type(number) == int))\n return numbers[SECOND_lARGEST] if len(numbers) > 1 else None", "def find_2nd_largest(arr):\n from collections import defaultdict\n d = defaultdict(list)\n for elem in arr:\n d[type(elem)].append(elem)\n numbers = d[int]\n largest_num = 0\n second_largest_num = 0\n for number in numbers:\n if largest_num < number:\n largest_num = number\n for number in numbers:\n if second_largest_num < number and number < largest_num:\n second_largest_num = number\n if second_largest_num == 0:\n return None\n else:\n return second_largest_num", "def find_2nd_largest(arr):\n xs = sorted({x for x in arr if isinstance(x, int)}, reverse=True)\n if len(xs) > 1 and xs[0] != xs[1]:\n return xs[1]", "def filter_int(arr):\n res = []\n for i in arr:\n if type(i) == int:\n res.append(i)\n else:\n continue\n return res\n\ndef sort(arr):\n for i in range(len(arr)):\n for j in range(len(arr) - 1):\n if arr[j] > arr[j + 1]:\n (arr[j], arr[j + 1]) = (arr[j + 1], arr[j])\n return arr\n\ndef is_diff(arr):\n count = 0\n res = None\n for i in range(len(arr) - 1):\n if arr[i] != arr[i + 1]:\n count += 1\n res = True\n break\n else:\n res = False\n return res\n\ndef sec_big(a, b):\n if a > b:\n return b\n else:\n return a\n\ndef find_2nd_largest(arr):\n filtered_list = filter_int(arr)\n sorted_list = sort(filtered_list)\n if is_diff(sorted_list) == True:\n a = sorted_list[len(sorted_list) - 1]\n b = sorted_list[len(sorted_list) - 2]\n sec_largest_elem = sec_big(a, b)\n return sec_largest_elem\n else:\n return None"], "starter_code": "def find_2nd_largest(arr):\n", "input_output": {"fn_name": "find_2nd_largest", "inputs": [[[1, 2, 3]], [[1, 1, 1, 1, 1, 1, 1]], [[1, "a", "2", 3, 3, 4, 5, "b"]], [[1, "a", "2", 3, 3, 3333333333333333333334, 544444444444444444444444444444, "b"]]], "outputs": [[2], [null], [4], [3333333333333333333334]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/55a58505cb237a076100004a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "find_2nd_largest", "task_id": "TACO_lite/305", "example": [[], []]} +{"requirement": "Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.\nReturn the power of the string.\n \nExample 1:\nInput: s = \"leetcode\"\nOutput: 2\nExplanation: The substring \"ee\" is of length 2 with the character 'e' only.\n\nExample 2:\nInput: s = \"abbcccddddeeeeedcba\"\nOutput: 5\nExplanation: The substring \"eeeee\" is of length 5 with the character 'e' only.\n\nExample 3:\nInput: s = \"triplepillooooow\"\nOutput: 5\n\nExample 4:\nInput: s = \"hooraaaaaaaaaaay\"\nOutput: 11\n\nExample 5:\nInput: s = \"tourist\"\nOutput: 1\n\n \nConstraints:\n\n1 <= s.length <= 500\ns contains only lowercase English letters.", "solutions": ["def maxpower(s: str) -> int:\n n = len(s)\n count = 0\n res = s[0]\n cur_count = 1\n for i in range(n):\n if i < n - 1 and s[i] == s[i + 1]:\n cur_count += 1\n else:\n if cur_count > count:\n count = cur_count\n res = s[i]\n cur_count = 1\n return count", "def maxpower(s: str) -> int:\n cnt = 0\n current = s[0]\n current_cnt = 1\n for l in s[1:]:\n if l == current:\n current_cnt += 1\n else:\n if current_cnt > cnt:\n cnt = current_cnt\n current = l\n current_cnt = 1\n if current_cnt > cnt:\n cnt = current_cnt\n return cnt", "def maxpower(s: str) -> int:\n c = {'power': 1}\n for i in range(len(s)):\n if i == len(s) - 1:\n break\n if ord(s[i]) == ord(s[i + 1]):\n c['power'] += 1\n else:\n c['new start#%s' % i] = c['power']\n c['power'] = 1\n return max(c.values())", "def maxpower(s: str) -> int:\n z = []\n c = 0\n if len(s) == 1:\n return 1\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n c = c + 1\n else:\n z.append(c)\n c = 0\n z.append(c)\n return max(z) + 1", "def maxpower(s: str) -> int:\n if len(s) <= 1:\n return len(s)\n last_char = s[0]\n count = 1\n max_count = 0\n for c in s[1:]:\n if c == last_char:\n count += 1\n else:\n if count > max_count:\n max_count = count\n count = 1\n last_char = c\n if count > max_count:\n max_count = count\n return max_count", "def maxpower(s: str) -> int:\n prev = None\n count = 0\n max_count = 0\n for char in s:\n if char == prev:\n count += 1\n else:\n prev = char\n count = 1\n max_count = max(max_count, count)\n return max_count", "def maxpower(s: str) -> int:\n seq = 1\n max_seq = 1\n for i in range(1, len(s)):\n if s[i] == s[i - 1]:\n seq += 1\n else:\n max_seq = max(max_seq, seq)\n seq = 1\n max_seq = max(max_seq, seq)\n return max_seq", "def maxpower(s: str) -> int:\n count = 0\n max_count = 0\n previous = None\n for c in s:\n if c != previous:\n previous = c\n count = 1\n else:\n count += 1\n max_count = max(max_count, count)\n return max_count", "def maxpower(s: str) -> int:\n ans = 0\n consec_count_per_letter = 1\n prev_letter = s[0]\n if len(s) == 1:\n return 1\n for i in range(1, len(s)):\n if s[i] == prev_letter:\n consec_count_per_letter += 1\n else:\n consec_count_per_letter = 1\n prev_letter = s[i]\n ans = max(ans, consec_count_per_letter)\n return ans", "def maxpower(s: str) -> int:\n c = 1\n maxc = c\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n c += 1\n maxc = max(maxc, c)\n else:\n c = 1\n return maxc", "def maxpower(s: str) -> int:\n maxcount = 1\n i = 0\n while i < len(s) - 1:\n count = 1\n while i < len(s) - 1 and s[i] == s[i + 1]:\n i = i + 1\n count = count + 1\n if count > maxcount:\n maxcount = count\n if i < len(s) - 1:\n i = i + 1\n return maxcount"], "starter_code": "def maxpower(s: str) -> int:\n", "input_output": {"fn_name": "maxPower", "inputs": [["\"leetcode\""]], "outputs": [2]}, "difficulty": "EASY", "raw_tags": ["String"], "name": null, "source": "leetcode", "tags": ["String algorithms"], "skill_types": [], "url": "https://leetcode.com/problems/consecutive-characters/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "maxpower", "task_id": "TACO_lite/224", "example": [[["leetcode"], ["abbcccddddeeeeedcba"], ["triplepillooooow"], ["hooraaaaaaaaaaay"], ["tourist"]], ["2", "5", "5", "11", "1"]]} +{"requirement": "Complete the solution so that it reverses all of the words within the string passed in. \n\nExample:\n\n```python\nreverseWords(\"The greatest victory is that which requires no battle\")\n// should return \"battle no requires which that is victory greatest The\"\n```", "solutions": ["def reversewords(str):\n return ' '.join(str.split(' ')[::-1])", "def reversewords(str):\n return ' '.join(reversed(str.split(' ')))", "def reversewords(string):\n return ' '.join(reversed(string.split()))", "def reversewords(str):\n k = str.split(' ')\n k.reverse()\n str = ' '.join(k)\n return str", "def reversewords(string):\n return ' '.join(string.split()[::-1])", "def reversewords(str):\n str_list = str.split(' ')\n rev_list = str_list[::-1]\n rev_str = ' '.join(rev_list)\n return rev_str", "def reversewords(str):\n str_split = str.split()\n rev_words = []\n for i in range(len(str_split) - 1, -1, -1):\n rev_words.append(str_split[i])\n return ' '.join(rev_words)", "def reversewords(str):\n s = str.split(' ')\n string = []\n for e in s:\n string.insert(0, e)\n return ' '.join(string)", "def reversewords(str):\n new_arr = []\n for word in str.split():\n new_arr.append(word)\n new_arr.reverse()\n return ' '.join(new_arr)", "reversewords = lambda s: ' '.join(s.split(' ')[::-1])", "reversewords = lambda s: ' '.join(reversed(s.split(' ')))", "def reversewords(str):\n return ' '.join([i for i in str.split(' ')[::-1]])", "import re\n\ndef reversewords(str):\n return ''.join(re.split('(\\\\s+)', str)[::-1])", "def reversewords(s):\n arr = s.split()\n arr = arr[::-1]\n str = ''\n for el in arr:\n str += el + ' '\n return str[:-1]", "def reversewords(str):\n a = str.split(' ')\n b = ''\n c = a[::-1]\n for i in range(0, len(a)):\n if i != len(a) - 1:\n b += c[i] + ' '\n else:\n b += c[i]\n return b", "reversewords = lambda ss: ' '.join(ss.split(' ')[-1::-1])", "def reversewords(str):\n liststr = str.split()\n liststr.reverse()\n newstr = ''\n for i in range(len(liststr)):\n newstr += liststr[i]\n if i != len(liststr) - 1:\n newstr += ' '\n return newstr", "def reversewords(s):\n return ' '.join(s.split()[::-1])", "def reversewords(s):\n b = s.split()\n b.reverse()\n return ' '.join(b)", "def reversewords(s):\n words = s.split()\n reversed = ''\n index = len(words)\n while index > 0:\n index -= 1\n reversed = reversed + ' ' + words[index]\n return reversed[1:]", "def reversewords(s):\n words = s.split()\n i = ''\n index = len(words)\n while index > 0:\n index -= 1\n i = i + ' ' + words[index]\n return i[1:]", "def reversewords(s):\n a = s.split()\n return ' '.join(reversed(a))", "def reversewords(s):\n t = s.split()\n return ' '.join(reversed(t))", "def reversewords(s):\n result = ''\n orded = s.split(' ')\n i = len(orded)\n while i > 0:\n result += orded[i - 1]\n if i > 1:\n result += ' '\n i -= 1\n return result", "def reversewords(s):\n words = s.split(' ')\n reverse_s = ' '.join(reversed(words))\n return reverse_s", "def reversewords(s):\n output = ''\n inp = s.split(' ')\n for i in inp:\n output = ' ' + i + output\n return output[1:len(output)]", "def reversewords(s):\n word = s.split(' ')\n reversewords = ' '.join(reversed(word))\n return reversewords", "def reversewords(s):\n s_list = s.split()\n rev_s_list = s_list[::-1]\n return ' '.join(rev_s_list)", "def reversewords(s):\n s = s.split()\n empty = []\n while len(s) > 0:\n empty.append(s.pop())\n else:\n return ' '.join(empty)", "def reversewords(s):\n reverse = s.split()\n strng = ''\n for i in range(1, len(reverse) + 1):\n strng += reverse[-i] + ' '\n return strng[:-1]", "def reversewords(s):\n s = list(s.split())\n return ' '.join(reversed(s))", "def reversewords(s):\n words = s.split()\n return ' '.join([words[-i - 1] for i in range(len(words))])", "def reversewords(s):\n holder = s.split(' ')\n (i, j) = (0, len(holder) - 1)\n while i < j:\n (holder[i], holder[j]) = (holder[j], holder[i])\n i += 1\n j -= 1\n return ' '.join(holder)", "def reversewords(s):\n x = s.split()\n y = x[::-1]\n return ' '.join(y)", "def reversewords(s):\n array = s.split()\n array.reverse()\n return ' '.join(array)", "def reversewords(s):\n w = s.split(' ')\n output = []\n for word in w:\n output.insert(0, word)\n return ' '.join(output)", "def reversewords(s):\n reverse_s = s.split()\n reverse_s.reverse()\n s = ' '.join(reverse_s)\n return s", "def reversewords(s):\n rev = [i for i in s.split()]\n return ' '.join(rev[::-1])", "def reversewords(s):\n g = s.split(' ')\n g.reverse()\n return ' '.join(g)", "def reversewords(s):\n reversed_str = ''\n s = s.split()\n for word in s:\n reversed_str = word + ' ' + reversed_str\n return reversed_str.strip()", "def reversewords(s):\n return ' '.join((w[::-1] for w in s.split()))[::-1]", "def reversewords(s):\n spl = s.split(' ')\n x = spl[::-1]\n new = ''\n for i in x:\n new += i + ' '\n return new.strip()", "def reversewords(s):\n ls = s.split()\n lsn = ls[::-1]\n return ' '.join(lsn)", "def reversewords(s):\n l = s.split(' ')\n v = []\n for i in l:\n v.insert(0, i)\n v.insert(0, ' ')\n return ''.join(v)[1:]", "def reversewords(s):\n a = ''.join((i + ' ' for i in s.split()[::-1]))\n return a[:-1]", "def reversewords(s):\n s = s.split(' ')\n string = []\n for w in s:\n string.insert(0, w)\n string = ' '.join(string)\n return string[:]", "def reversewords(s):\n x = s.split()\n y = x[::-1]\n z = ' '.join((str(a) for a in y))\n return z", "def reversewords(s):\n word = list(s.split(' '))\n word.reverse()\n return ' '.join(word)", "def reversewords(s):\n str_split = s.split(' ')\n string = ''\n for i in str_split:\n string = i + ' ' + string\n return string.rstrip()", "def reversewords(s):\n for line in s.split('\\n'):\n return ' '.join(line.split()[::-1])", "def reversewords(s):\n s = s.split(' ')\n s.reverse()\n x = ' '\n return x.join(s)", "def reversewords(s):\n a = s.split()\n a.reverse()\n b = a[0]\n a.pop(0)\n for x in a:\n b = b + ' ' + x\n return b", "def reversewords(s):\n x = s.split()\n y = x[::-1]\n strin = ''\n for i in y:\n strin += i + ' '\n return strin.rstrip()", "def reversewords(s):\n s = s.split(' ')\n r = ''\n for x in range(0, len(s)):\n r += s[len(s) - x - 1]\n if x != len(s) - 1:\n r += ' '\n return r", "def reversewords(s: ''):\n s = s.split()\n result = ''\n for i in s:\n result = i + ' ' + result\n return result.strip(' ')", "def reversewords(s):\n t = s.split()\n z = t[::-1]\n return ' '.join(z)", "def reversewords(s):\n s = s.split(' ')\n s.reverse()\n res = ' '.join(s)\n return res", "def reversewords(s):\n y = s.split(' ')\n x = ' '.join(reversed(y))\n return x", "def reversewords(s):\n l = []\n l = s.split(' ')\n l.reverse()\n f = ''\n for i in l:\n f += i + ' '\n return f[:len(f) - 1]", "def reversewords(s):\n list_of_s = s.split(' ')\n list_of_s.reverse()\n return ' '.join(list_of_s)", "reversewords = lambda word: ' '.join(word.split(' ')[::-1])", "def reversewords(s):\n string = ''\n s = s.split()\n for word in reversed(range(len(s))):\n string += s[word]\n string += ' '\n string = string[:-1]\n return string", "def reversewords(r):\n s = r.split()\n r = ''\n for i in range(1, len(s) + 1):\n r += s[-i] + ' '\n return r[:-1]", "def reversewords(s):\n a = s.split()\n b = a[::-1]\n return ' '.join(b)", "def reversewords(s):\n x = [x for x in s.split(' ')]\n return ''.join((x + ' ' for x in x[::-1]))[:-1]", "def reversewords(s):\n return ' '.join(reversed([w for w in s.split()]))", "def reversewords(str):\n words = str.split()\n words = list(reversed(words))\n reverse_str = ' '.join(words)\n return reverse_str", "def reversewords(str):\n strings = str.split(' ')\n strings.reverse()\n return ' '.join(strings)", "def reversewords(str):\n arr = str.split(' ')\n arr.reverse()\n return ' '.join(arr).rstrip()", "def reversewords(str):\n arr = list(str.split())\n arr.reverse()\n return ' '.join([i for i in arr])", "def reversewords(str):\n a = str.split()\n b = ' '.join(reversed(a))\n return b", "def reversewords(str):\n final_str = ''\n str_lst = str.split(' ')[::-1]\n for word in str_lst:\n final_str += word\n final_str += ' '\n return final_str.strip()", "def reversewords(str):\n s = str.split(' ')\n ans = ''\n for i in range(len(s) - 1, -1, -1):\n if i != len(s) - 1:\n ans += ' '\n ans += s[i]\n return ans", "def reversewords(str):\n word = str.split(' ')\n reverse = ' '.join(reversed(word))\n return reverse", "def reversewords(words):\n new_words = list(reversed(words.split()))\n return ' '.join(new_words)", "def reversewords(str):\n rev_list = list(str.split(' '))\n rev_str = ''\n for i in range(len(rev_list) - 1, -1, -1):\n rev_str += rev_list[i]\n if i != 0:\n rev_str += ' '\n return rev_str"], "starter_code": "def reversewords(s):\n", "input_output": {"fn_name": "reverseWords", "inputs": [["hello world!"]], "outputs": [["world! hello"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms"], "name": null, "source": "codewars", "tags": ["String algorithms"], "skill_types": [], "url": "https://www.codewars.com/kata/51c8991dee245d7ddf00000e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "reversewords", "task_id": "TACO_lite/300", "example": [[["The greatest victory is that which requires no battle"]], ["battle no requires which that is victory greatest The"]]} +{"requirement": "Given an array arr[] of N Numbers. A Perfect Piece is defined as a subarray such that the difference between the minimum and the maximum value in that range is at most 1. Find the Maximal Length Perfect Piece.\n \nExample 1:\nInput:\nN = 4\narr[] = {8, 8, 8, 8}\nOutput:\n4\nExplanation:\nThe longest subarray is [1, 4]\nwhere maximum=8 and minimum = 8 and\ndifference is 0, which is less than 1.\nIts length is 4.\nExample 2:\nInput:\nN = 11\narr[] = {5, 4, 5, 5, 6, 7, 8, 8, 8, 7, 6}\nOutput:\n5\nExplanation:\nThe longest subarray is [6, 10]\nwhere maximum=8 and minimum = 7 and\ndifference is 1. Its length is 5. \n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function longestPerfectPiece() which takes an Integer N and an array arr[] of length N as input and returns the maximal length Perfect Piece.\n \nExpected Time Complexity: O(N*logN)\nExpected Auxiliary Space: O(N)\n \nConstraints:\n1 <= N <= 10^{5}\n1 <= arr[i] <= 10^{5}", "solutions": ["def longestperfectpiece(arr, N):\n a = b = 0\n ans = 1\n for j in range(1, len(arr)):\n if abs(arr[j] - arr[b]) == 1:\n if a == b or arr[j] != arr[b - 1]:\n a = b\n b = j\n elif arr[j] != arr[b]:\n a = b = j\n ans = max(ans, j - a + 1)\n return ans", "import sys\n\ndef longestperfectpiece(arr, N):\n (flg, count, f1, f2) = (0, 0, 0, 0)\n len = -sys.maxsize - 1\n for i in range(N):\n for j in range(f1, N):\n if arr[i] - arr[j] == 1 or arr[i] == arr[j]:\n if len < abs(i - j):\n len = abs(i - j)\n else:\n f1 = j\n break\n for j in range(f2, N):\n if arr[i] - arr[j] == -1 or arr[i] == arr[j]:\n if len < abs(i - j):\n len = abs(i - j)\n else:\n f2 = j\n break\n return len + 1", "import collections\n\ndef longestperfectpiece(arr, N):\n map = collections.defaultdict(int)\n start = 0\n maxLength = 0\n for (end, num) in enumerate(arr):\n map[num] += 1\n while len(map) > 2 or max(map.keys()) - min(map.keys()) > 1:\n map[arr[start]] -= 1\n if map[arr[start]] == 0:\n del map[arr[start]]\n start += 1\n maxLength = max(maxLength, end - start + 1)\n return maxLength", "def longestperfectpiece(arr, N):\n (i, j, ans) = (0, 0, 1)\n for k in range(1, N):\n if abs(arr[k] - arr[j]) == 1:\n if i == j or arr[k] != arr[j - 1]:\n i = j\n j = k\n elif arr[k] != arr[j]:\n i = j = k\n ans = max(ans, k - i + 1)\n return ans", "def longestperfectpiece(arr, N):\n j = 0\n mn = arr[0]\n mx = arr[0]\n ans = 1\n d = dict()\n for i in range(1, N):\n d[arr[i]] = i\n if arr[i] < mn:\n mn = arr[i]\n while mx - mn > 1:\n j = d.get(mx, 0) + 1\n mx = arr[j]\n elif arr[i] > mx:\n mx = arr[i]\n while mx - mn > 1:\n j = d.get(mn, 0) + 1\n mn = arr[j]\n else:\n ans = max(ans, i - j + 1)\n return ans", "import sys\nfrom collections import deque\n\ndef longestperfectpiece(arr, N):\n window = deque([])\n i = 0\n count = 0\n ans = 0\n maxis = deque([])\n ta = deque([])\n ti = deque([])\n minis = deque([])\n l = r = 0\n while i < N:\n if len(window) == 0 or arr[i] == arr[maxis[0]] or arr[i] == arr[minis[0]] or (arr[maxis[0]] == arr[minis[0]] and (arr[i] == arr[maxis[0]] - 1 or arr[i] == arr[maxis[0]] + 1)):\n window.append(arr[i])\n count += 1\n ans = max(ans, count)\n while len(maxis) != 0 and arr[i] > arr[maxis[-1]]:\n maxis.pop()\n ta.pop()\n maxis.append(i)\n ta.append(arr[i])\n while len(minis) != 0 and arr[i] < arr[minis[-1]]:\n minis.pop()\n ti.pop()\n minis.append(i)\n ti.append(arr[i])\n r += 1\n i += 1\n else:\n window.popleft()\n l += 1\n count -= 1\n if len(maxis) != 0 and l > maxis[0]:\n maxis.popleft()\n ta.popleft()\n if len(minis) != 0 and l > minis[0]:\n minis.popleft()\n ti.popleft()\n return ans", "from sortedcontainers import SortedList\nimport collections\n\ndef longestperfectpiece(arr, N):\n ans = 0\n s = 0\n map = collections.defaultdict(int)\n for (end, num) in enumerate(arr):\n map[num] += 1\n while len(map) > 2 or max(map.keys()) - min(map.keys()) > 1:\n map[arr[s]] -= 1\n if map[arr[s]] == 0:\n del map[arr[s]]\n s += 1\n ans = max(ans, end - s + 1)\n return ans", "def longestperfectpiece(arr, N):\n (l, r) = (0, 0)\n ans = 1\n (pos1, pos2) = (-1, -1)\n val = None\n for i in range(N):\n if pos1 == -1:\n pos1 = i\n val = arr[i]\n elif pos2 == -1:\n if arr[i] == val + 1:\n pos2 = i\n elif arr[i] == val:\n pos = i\n elif arr[i] == val - 1:\n val = val - 1\n pos2 = pos1\n pos1 = i\n else:\n val = arr[i]\n pos1 = i\n pos2 = -1\n l = i\n elif arr[i] == val:\n pos1 = i\n elif arr[i] == val + 1:\n pos2 = i\n elif arr[i] == val - 1:\n val = val - 1\n l = pos2 + 1\n pos2 = pos1\n pos1 = i\n elif arr[i] == val + 2:\n val = val + 1\n l = pos1 + 1\n pos1 = pos2\n pos2 = i\n else:\n l = i\n pos2 = -1\n pos1 = i\n val = arr[i]\n ans = max(ans, i - l + 1)\n return ans", "def longestperfectpiece(arr, N):\n c = 1\n i = 0\n t = 0\n while i < N - 1:\n if abs(arr[i] - arr[i + 1]) <= 1:\n i += 1\n t += 1\n else:\n if c < t:\n c += t\n t = 0\n i += 1\n if N == 7:\n return 6\n if N == 5:\n return 4\n if N == 2667 or N == 3666:\n return c + 1\n if t > c:\n return t + 1\n return c", "def longestperfectpiece(arr, n):\n i = 0\n ans = 0\n while i < n:\n a = arr[i]\n b = -1\n j = i + 1\n while j < n:\n if b == -1 and abs(arr[i] - arr[j]) == 1:\n b = arr[j]\n j += 1\n elif arr[j] == a or arr[j] == b:\n j += 1\n else:\n break\n ans = max(ans, j - i)\n if j >= n:\n break\n i = j\n if abs(arr[i] - arr[i - 1]) == 1:\n b = arr[i - 1]\n i -= 1\n while i >= 0 and arr[i] == b:\n i -= 1\n i += 1\n return ans", "def longestperfectpiece(arr, N):\n maxLen = 0\n tailIndex = 0\n piecemax = arr[0]\n piecemin = arr[0]\n for (i, val) in enumerate(arr):\n if val > piecemax:\n piecemax = val\n while piecemin < piecemax - 1:\n tailIndex += 1\n piecemin = max(piecemin, arr[tailIndex])\n if val < piecemin:\n piecemin = val\n while piecemin < piecemax - 1:\n tailIndex += 1\n piecemax = min(piecemax, arr[tailIndex])\n currentLen = i - tailIndex + 1\n maxLen = max(maxLen, currentLen)\n return maxLen", "def longestperfectpiece(arr, N):\n (a, b, c) = (1, 1, 1)\n ans = 1\n for i in range(1, N):\n if arr[i] == arr[i - 1]:\n (a, b, c) = (a + 1, b + 1, c + 1)\n elif arr[i] - arr[i - 1] == 1:\n (a, b, c) = (1, c + 1, 1)\n elif arr[i] - arr[i - 1] == -1:\n (a, b, c) = (1, 1, b + 1)\n else:\n (a, b, c) = (1, 1, 1)\n ans = max(ans, a, b, c)\n return ans", "def longestperfectpiece(arr, N):\n if not N:\n return 0\n (start, ans) = (1, 1)\n count = 1\n (s, l) = (arr[0], arr[0])\n (sf, lf, df) = (0, 0, 1)\n for i in range(0, N):\n if not df:\n (s, l) = (arr[i], arr[i])\n for j in range(start, N):\n if 0 <= abs(arr[j] - s) <= 1 and 0 <= abs(arr[j] - l) <= 1:\n count += 1\n if arr[j] > l:\n lf += 1\n l = arr[j]\n elif arr[j] == l and arr[j] != arr[i]:\n lf += 1\n if arr[j] < s:\n sf += 1\n s = arr[j]\n elif arr[j] == s and arr[j] != arr[i]:\n sf += 1\n if arr[j] == arr[i]:\n df += 1\n else:\n if sf:\n if df > 1:\n l = arr[i]\n else:\n l = s\n if arr[i] != arr[i + 1]:\n lf = df - 1\n df = sf\n sf = 0\n else:\n df -= 1\n elif lf:\n if df > 1:\n s = arr[i]\n else:\n s = l\n if arr[i] != arr[i + 1]:\n sf = df - 1\n df = lf\n lf = 0\n else:\n df -= 1\n else:\n df -= 1\n ans = max(ans, count)\n count -= 1\n start = j\n break\n if j == N - 1:\n start = N\n ans = max(ans, count)\n return ans", "from heapq import heappush, heappop\nfrom collections import defaultdict\n\ndef longestperfectpiece(arr, n):\n dic = defaultdict(int)\n ans = 0\n start = 0\n for i in range(n):\n dic[arr[i]] += 1\n while len(dic) > 1 and max(dic.keys()) - min(dic.keys()) > 1:\n dic[arr[start]] -= 1\n if dic[arr[start]] == 0:\n dic.pop(arr[start])\n start += 1\n ans = max(ans, i - start + 1)\n return ans\n mini = []\n maxi = []\n j = 0\n ans = 0\n for i in range(n):\n heappush(mini, arr[i])\n heappush(maxi, -arr[i])\n if abs(mini[0] + maxi[0]) <= 1:\n ans = max(ans, i - j + 1)\n else:\n while j < n and mini and (abs(mini[0] + maxi[0]) > 1):\n mini.remove(arr[j])\n maxi.remove(-arr[j])\n j += 1\n return ans", "def longestperfectpiece(arr, N):\n if N < 2:\n return N\n res = 1\n n1 = arr[0]\n n2 = arr[0]\n i = 1\n count = 1\n while i < N:\n if n1 == n2:\n if abs(n1 - arr[i]) < 2:\n n2 = arr[i]\n count += 1\n else:\n n1 = n2 = arr[i]\n res = max(res, count)\n count = 1\n elif arr[i] == n1 or arr[i] == n2:\n count += 1\n else:\n res = max(res, count)\n n1 = n2 = arr[i]\n count = 1\n j = i - 1\n if abs(n1 - arr[j]) == 1:\n n2 = arr[j]\n while j >= 0 and arr[j] == n2:\n j -= 1\n count += 1\n i += 1\n return max(count, res)", "import collections\n\ndef __init__():\n self.ans = 1\n self.dic = collections.defaultdict(int)\n\ndef longestperfectpiece(arr, N):\n start = 0\n end = 0\n while end < N:\n self.dic[arr[end]] += 1\n end += 1\n while max(self.dic.keys()) - min(self.dic.keys()) > 1:\n self.dic[arr[start]] -= 1\n if self.dic[arr[start]] == 0:\n del self.dic[arr[start]]\n start += 1\n if self.ans < sum(self.dic.values()):\n self.ans = sum(self.dic.values())\n return self.ans", "def longestperfectpiece(arr, N):\n i = 0\n j = 0\n h = {}\n res = 1\n while i <= j and j < N:\n while i < j and (abs(arr[j] - arr[i]) > 1 or (len(h) == 2 and arr[j] not in h)):\n h[arr[i]] -= 1\n if h[arr[i]] == 0:\n del h[arr[i]]\n i += 1\n h[arr[j]] = 1 + h.get(arr[j], 0)\n res = max(res, j - i + 1)\n j += 1\n return res", "import heapq\n\ndef longestperfectpiece(arr, N):\n d = dict()\n i = 0\n j = 0\n ans = 0\n while j < N:\n if arr[j] in d:\n d[arr[j]] += 1\n else:\n d[arr[j]] = 1\n while len(d) >= 2 and max(d.keys()) - min(d.keys()) > 1:\n d[arr[i]] -= 1\n if d[arr[i]] == 0:\n del d[arr[i]]\n i += 1\n ans = max(ans, j - i + 1)\n j += 1\n return ans", "from collections import Counter\n\ndef longestperfectpiece(arr, N):\n cnt = Counter()\n l = 0\n ans = 1\n for (r, e) in enumerate(arr):\n cnt[e] += 1\n while l < r and max(cnt.keys()) - min(cnt.keys()) > 1:\n cnt[arr[l]] -= 1\n if cnt[arr[l]] == 0:\n cnt.pop(arr[l])\n l += 1\n ans = max(ans, r - l + 1)\n return ans", "def longestperfectpiece(arr, N):\n longest = [0]\n pmin = arr[0]\n pmax = arr[0]\n if N == 1:\n return 1\n i = 0\n while i < N - 1:\n sidx = i\n eidx = i\n while i < N - 1 and pmax - pmin < 2:\n pmin = min(pmin, arr[i + 1])\n pmax = max(pmax, arr[i + 1])\n i += 1\n if pmax - pmin < 2:\n eidx += 1\n longest[0] = max(longest[0], eidx - sidx + 1)\n if i < N:\n if pmax - pmin == 2:\n for j in range(sidx, eidx):\n if arr[j] == pmin:\n i = j + 1\n break\n pmax = arr[i]\n pmin = arr[i]\n return longest[0]", "from collections import deque\n\ndef longestperfectpiece(arr, N):\n maxm = deque()\n minm = deque()\n res = 0\n i = j = 0\n while i < N and j < N:\n while j < N:\n cur = arr[j]\n while maxm and maxm[-1][1] < cur:\n maxm.pop()\n maxm.append((j, cur))\n while minm and minm[-1][1] > cur:\n minm.pop()\n minm.append((j, cur))\n if abs(maxm[0][1] - minm[0][1]) > 1:\n break\n j += 1\n res = max(res, j - i)\n while i < N:\n while maxm and maxm[0][0] < i:\n maxm.popleft()\n while minm and minm[0][0] < i:\n minm.popleft()\n if abs(maxm[0][1] - minm[0][1]) <= 1:\n break\n i += 1\n return res", "import collections\n\ndef longestperfectpiece(arr, n):\n map = collections.defaultdict(int)\n j = 0\n ans = 0\n for i in range(n):\n map[arr[i]] += 1\n while len(map) > 2 or max(map.keys()) - min(map.keys()) > 1:\n map[arr[j]] -= 1\n if map[arr[j]] == 0:\n del map[arr[j]]\n j += 1\n ans = max(ans, i - j + 1)\n return ans", "from collections import defaultdict as maps\n\ndef longestperfectpiece(arr, n):\n d = maps(int)\n start = 0\n maxlen = 0\n for (index, num) in enumerate(arr):\n d[num] += 1\n while len(d) > 2 or max(d.keys()) - min(d.keys()) > 1:\n d[arr[start]] -= 1\n if d[arr[start]] == 0:\n del d[arr[start]]\n start += 1\n maxlen = max(maxlen, index - start + 1)\n return maxlen", "def longestperfectpiece(arr, N):\n if arr == [5, 4, 5, 5, 6]:\n return 4\n res = 0\n i = 0\n j = 0\n while j < N:\n while abs(arr[j] - arr[i]) > 1:\n i += 1\n res = max(res, j - i + 1)\n j += 1\n return res", "from collections import Counter\nimport bisect\n\ndef longestperfectpiece(arr, N):\n t = 0\n j = 0\n for (x, i) in enumerate(arr):\n while j < N and (arr[j] == i or arr[j] == i + 1):\n j += 1\n t = max(t, j - x)\n j = 0\n for (x, i) in enumerate(arr):\n while j < N and (arr[j] == i or arr[j] == i - 1):\n j += 1\n t = max(t, j - x)\n return t", "def longestperfectpiece(arr, N):\n flg = count = f1 = f2 = 0\n res = -float('inf')\n for i in range(N):\n for j in range(f1, N):\n if arr[i] - arr[j] == 1 or arr[i] == arr[j]:\n res = max(res, j - i)\n else:\n f1 = j\n break\n for j in range(f2, N):\n if arr[i] - arr[j] == -1 or arr[i] == arr[j]:\n res = max(res, j - i)\n else:\n f2 = j\n break\n return res + 1", "from collections import deque\n\ndef longestperfectpiece(arr, N):\n n = N\n a = deque()\n b = deque()\n l = r = ans = 0\n while l < n and r < n:\n while r < n:\n c = arr[r]\n while a and a[-1][1] < c:\n a.pop()\n a.append((r, c))\n while b and b[-1][1] > c:\n b.pop()\n b.append((r, c))\n if abs(a[0][1] - b[0][1]) > 1:\n break\n r += 1\n ans = max(ans, r - l)\n while l < n:\n while a and a[0][0] < l:\n a.popleft()\n while b and b[0][0] < l:\n b.popleft()\n if abs(a[0][1] - b[0][1]) <= 1:\n break\n l += 1\n return ans"], "starter_code": "def longestperfectpiece(arr, N):\n", "input_output": {"inputs": ["N = 4\r\narr[] = {8, 8, 8, 8}", "N = 11\r\narr[] = {5, 4, 5, 5, 6, 7, 8, 8, 8, 7, 6}"], "outputs": ["4", "5"]}, "difficulty": "EASY", "raw_tags": ["Pointers", "Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/close-to-perfection1525/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*logN)", "entry_point": "longestperfectpiece", "task_id": "TACO_lite/302", "example": [[[4, [8, 8, 8, 8]], [11, [5, 4, 5, 5, 6, 7, 8, 8, 8, 7, 6]]], ["4", "5"]]} +{"requirement": "Make a function that receives a value, ```val``` and outputs the smallest higher number than the given value, and this number belong to a set of positive integers that have the following properties:\n\n- their digits occur only once\n\n- they are odd\n\n- they are multiple of three\n\n```python\nnext_numb(12) == 15\n\nnext_numb(13) == 15\n\nnext_numb(99) == 105\n\nnext_numb(999999) == 1023459\n\nnext_number(9999999999) == \"There is no possible number that\nfulfills those requirements\"\n```\n\nEnjoy the kata!!", "solutions": ["def unique_digits(n):\n return len(set(str(n))) == len(str(n))\n\ndef next_numb(val):\n val += 1\n while val % 3:\n val += 1\n if val % 2 == 0:\n val += 3\n while not unique_digits(val):\n val += 6\n if val > 9876543210:\n break\n else:\n return val\n return 'There is no possible number that fulfills those requirements'", "def next_numb(val):\n val += 3 - val % 3\n if not val & 1:\n val += 3\n while val < 9999999999:\n s = str(val)\n if len(s) == len(set(s)):\n return val\n val += 6\n return 'There is no possible number that fulfills those requirements'", "DEFAULT = 'There is no possible number that fulfills those requirements'\n\ndef valid(s):\n return len(set(s)) == len(s)\n\ndef next_numb(n):\n n += 3 - n % 3\n if not n & 1:\n n += 3\n return next((n for n in range(n, 9999999999, 6) if valid(str(n))), DEFAULT)", "def next_numb(val):\n i = val + 1\n while i <= 9999999999:\n if i % 3 == 0 and i % 2 and (len(str(i)) == len(set(str(i)))):\n return i\n i += 1\n return 'There is no possible number that fulfills those requirements'", "from itertools import count\n\ndef next_numb(val):\n if val >= 9999999999:\n return 'There is no possible number that fulfills those requirements'\n for i in count(val + 1):\n s = str(i)\n if i % 2 == 1 and i % 3 == 0 and (len(s) == len(set(s))):\n return i", "from collections import Counter\n\ndef next_numb(val):\n if val >= 9876543210:\n return 'There is no possible number that fulfills those requirements'\n x = val + 1\n if x % 3 != 0:\n x += 3 - x % 3\n if x % 2 == 0:\n x += 3\n c = Counter(str(x))\n while max(c.values()) > 1:\n x += 6\n c = Counter(str(x))\n return x", "def next_numb(n):\n if n > 9876543201:\n return 'There is no possible number that fulfills those requirements'\n x = n - n % 3 + 3\n while True:\n if x > 9876543201:\n return 'There is no possible number that fulfills those requirements'\n if x & 1:\n a = [d for d in str(x)]\n s = list(set(a))\n if len(a) == len(s):\n return x\n x += 3"], "starter_code": "def next_numb(val):\n", "input_output": {"fn_name": "next_numb", "inputs": [[12], [13], [99], [999999], [9999999999]], "outputs": [[15], [15], [105], [1023459], ["There is no possible number that fulfills those requirements"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56abc5e63c91630882000057", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "next_numb", "task_id": "TACO_lite/289", "example": [[], []]} +{"requirement": "This time no story, no theory. The examples below show you how to write function `accum`:\n\n**Examples:**\n```\naccum(\"abcd\") -> \"A-Bb-Ccc-Dddd\"\naccum(\"RqaEzty\") -> \"R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy\"\naccum(\"cwAt\") -> \"C-Ww-Aaa-Tttt\"\n```\n\nThe parameter of accum is a string which includes only letters from `a..z` and `A..Z`.", "solutions": ["def accum(s):\n return '-'.join((c.upper() + c.lower() * i for (i, c) in enumerate(s)))", "def accum(s):\n return '-'.join(((a * i).title() for (i, a) in enumerate(s, 1)))", "def accum(s):\n output = ''\n for i in range(len(s)):\n output += s[i] * (i + 1) + '-'\n return output.title()[:-1]", "def accum(s):\n i = 0\n result = ''\n for letter in s:\n result += letter.upper() + letter.lower() * i + '-'\n i += 1\n return result[:len(result) - 1]", "def accum(s):\n return '-'.join([(j * (i + 1)).capitalize() for (i, j) in enumerate(s)])", "def accum(s):\n value = ''\n for (i, c) in enumerate(s):\n value += c.upper() + c.lower() * i + '-'\n return value[:-1]", "def accum(s):\n str = ''\n for i in range(0, len(s)):\n str += s[i].upper()\n str += s[i].lower() * i\n if i != len(s) - 1:\n str += '-'\n return str", "def accum(s):\n a = list(s)\n res = ''\n for (i, c) in enumerate(a):\n res += c * (i + 1) + '-'\n return res.strip('-').title()", "def accum(s):\n return '-'.join(list((x.upper() + x.lower() * count for (count, x) in enumerate(s))))"], "starter_code": "def accum(s):\n", "input_output": {"fn_name": "accum", "inputs": [["ZpglnRxqenU"], ["NyffsGeyylB"], ["MjtkuBovqrU"], ["EvidjUnokmM"], ["HbideVbxncC"], ["VwhvtHtrxfE"], ["KurgiKmkphY"], ["NctlfBlnmfH"], ["WegunHvbdmV"], ["VoywwSpqidE"], ["VbaixFpxdcO"], ["OlyqvYwkuzF"], ["JrhfdMtchiH"], ["JiwpcSwslvW"], ["EagpiEvmabJ"], ["RznlcEmuxxP"], ["OrggaExarzP"], ["DriraMtedfB"], ["BjxseRxgtjT"], ["EquhxOswchE"]], "outputs": [["Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu"], ["N-Yy-Fff-Ffff-Sssss-Gggggg-Eeeeeee-Yyyyyyyy-Yyyyyyyyy-Llllllllll-Bbbbbbbbbbb"], ["M-Jj-Ttt-Kkkk-Uuuuu-Bbbbbb-Ooooooo-Vvvvvvvv-Qqqqqqqqq-Rrrrrrrrrr-Uuuuuuuuuuu"], ["E-Vv-Iii-Dddd-Jjjjj-Uuuuuu-Nnnnnnn-Oooooooo-Kkkkkkkkk-Mmmmmmmmmm-Mmmmmmmmmmm"], ["H-Bb-Iii-Dddd-Eeeee-Vvvvvv-Bbbbbbb-Xxxxxxxx-Nnnnnnnnn-Cccccccccc-Ccccccccccc"], ["V-Ww-Hhh-Vvvv-Ttttt-Hhhhhh-Ttttttt-Rrrrrrrr-Xxxxxxxxx-Ffffffffff-Eeeeeeeeeee"], ["K-Uu-Rrr-Gggg-Iiiii-Kkkkkk-Mmmmmmm-Kkkkkkkk-Ppppppppp-Hhhhhhhhhh-Yyyyyyyyyyy"], ["N-Cc-Ttt-Llll-Fffff-Bbbbbb-Lllllll-Nnnnnnnn-Mmmmmmmmm-Ffffffffff-Hhhhhhhhhhh"], ["W-Ee-Ggg-Uuuu-Nnnnn-Hhhhhh-Vvvvvvv-Bbbbbbbb-Ddddddddd-Mmmmmmmmmm-Vvvvvvvvvvv"], ["V-Oo-Yyy-Wwww-Wwwww-Ssssss-Ppppppp-Qqqqqqqq-Iiiiiiiii-Dddddddddd-Eeeeeeeeeee"], ["V-Bb-Aaa-Iiii-Xxxxx-Ffffff-Ppppppp-Xxxxxxxx-Ddddddddd-Cccccccccc-Ooooooooooo"], ["O-Ll-Yyy-Qqqq-Vvvvv-Yyyyyy-Wwwwwww-Kkkkkkkk-Uuuuuuuuu-Zzzzzzzzzz-Fffffffffff"], ["J-Rr-Hhh-Ffff-Ddddd-Mmmmmm-Ttttttt-Cccccccc-Hhhhhhhhh-Iiiiiiiiii-Hhhhhhhhhhh"], ["J-Ii-Www-Pppp-Ccccc-Ssssss-Wwwwwww-Ssssssss-Lllllllll-Vvvvvvvvvv-Wwwwwwwwwww"], ["E-Aa-Ggg-Pppp-Iiiii-Eeeeee-Vvvvvvv-Mmmmmmmm-Aaaaaaaaa-Bbbbbbbbbb-Jjjjjjjjjjj"], ["R-Zz-Nnn-Llll-Ccccc-Eeeeee-Mmmmmmm-Uuuuuuuu-Xxxxxxxxx-Xxxxxxxxxx-Ppppppppppp"], ["O-Rr-Ggg-Gggg-Aaaaa-Eeeeee-Xxxxxxx-Aaaaaaaa-Rrrrrrrrr-Zzzzzzzzzz-Ppppppppppp"], ["D-Rr-Iii-Rrrr-Aaaaa-Mmmmmm-Ttttttt-Eeeeeeee-Ddddddddd-Ffffffffff-Bbbbbbbbbbb"], ["B-Jj-Xxx-Ssss-Eeeee-Rrrrrr-Xxxxxxx-Gggggggg-Ttttttttt-Jjjjjjjjjj-Ttttttttttt"], ["E-Qq-Uuu-Hhhh-Xxxxx-Oooooo-Sssssss-Wwwwwwww-Ccccccccc-Hhhhhhhhhh-Eeeeeeeeeee"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Puzzles"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/5667e8f4e3f572a8f2000039", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "accum", "task_id": "TACO_lite/304", "example": [[["abcd"], ["RqaEzty"], ["cwAt"]], ["A-Bb-Ccc-Dddd", "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy", "C-Ww-Aaa-Tttt"]]} +{"requirement": "The i-th person has weight people[i], and each boat can carry a maximum weight of limit.\nEach boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit.\nReturn the minimum number of boats to carry every given person.  (It is guaranteed each person can be carried by a boat.)\n \n\nExample 1:\nInput: people = [1,2], limit = 3\nOutput: 1\nExplanation: 1 boat (1, 2)\n\n\nExample 2:\nInput: people = [3,2,2,1], limit = 3\nOutput: 3\nExplanation: 3 boats (1, 2), (2) and (3)\n\n\nExample 3:\nInput: people = [3,5,3,4], limit = 5\nOutput: 4\nExplanation: 4 boats (3), (3), (4), (5)\nNote:\n\n1 <= people.length <= 50000\n1 <= people[i] <= limit <= 30000", "solutions": ["def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n lo = 0\n hi = len(people) - 1\n count = 0\n while lo <= hi:\n count += 1\n if people[lo] + people[hi] <= limit:\n lo += 1\n hi -= 1\n return count", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n boats = 0\n l = 0\n r = len(people) - 1\n while r > l:\n boats += 1\n if people[l] + people[r] <= limit:\n l += 1\n r = r - 1\n else:\n r = r - 1\n if r == l:\n boats += 1\n return boats", "def numrescueboats(people: List[int], limit: int) -> int:\n people = sorted(people, reverse=True)\n i = 0\n j = len(people) - 1\n n = 0\n while True:\n if i >= j:\n break\n n += 1\n w1 = people[i]\n i += 1\n rem = limit - w1\n if rem >= people[j]:\n j -= 1\n if i == j:\n n += 1\n return n", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n p1 = 0\n p2 = len(people) - 1\n boat = 0\n while p1 <= p2:\n boat += 1\n if people[p1] + people[p2] <= limit:\n p1 += 1\n p2 -= 1\n return boat", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n i = 0\n j = len(people) - 1\n count = 0\n while i < j:\n if people[i] + people[j] <= limit:\n count += 1\n i += 1\n j -= 1\n else:\n count += 1\n j -= 1\n if i == j:\n count += 1\n return count", "def numrescueboats(people: List[int], limit: int) -> int:\n new = sorted(people)\n (i, j) = (0, len(people) - 1)\n res = 0\n while i <= j:\n if new[j] + new[i] <= limit:\n i += 1\n j -= 1\n res += 1\n return res", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n (l, r) = (0, len(people) - 1)\n res = 0\n while l <= r:\n while l <= r and people[l] + people[r] > limit:\n res += 1\n r -= 1\n if l <= r:\n res += 1\n l += 1\n r -= 1\n return res", "def numrescueboats(people: List[int], limit: int) -> int:\n length = len(people)\n people.sort()\n left = 0\n right = length - 1\n boat_num = 0\n while left <= right:\n if people[left] + people[right] <= limit:\n left += 1\n right -= 1\n else:\n right -= 1\n boat_num += 1\n return boat_num", "def numrescueboats(people: List[int], limit: int) -> int:\n if not people:\n return 0\n people = sorted(people)\n left = 0\n right = len(people) - 1\n board_cnt = 0\n while left <= right:\n if left == right:\n board_cnt += 1\n break\n if people[left] + people[right] <= limit:\n left += 1\n right -= 1\n board_cnt += 1\n else:\n right -= 1\n board_cnt += 1\n return board_cnt", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n (left, right) = (0, len(people) - 1)\n boats = 0\n while left <= right:\n if left == right:\n boats += 1\n break\n if people[left] + people[right] <= limit:\n boats += 1\n left += 1\n right -= 1\n else:\n right -= 1\n boats += 1\n return boats", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n start = 0\n end = len(people) - 1\n ans = 0\n while start <= end:\n ans += 1\n if people[start] + people[end] <= limit:\n start += 1\n end -= 1\n return ans", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort(reverse=True)\n (l, r) = (0, len(people) - 1)\n while l <= r:\n if people[l] + people[r] <= limit:\n r -= 1\n l += 1\n return l", "def numrescueboats(people: List[int], limit: int) -> int:\n people = sorted(people)\n count = 0\n left = 0\n right = len(people) - 1\n while left <= right:\n cur = people[left] + people[right]\n if cur <= limit:\n left += 1\n right -= 1\n elif cur > limit:\n right -= 1\n count += 1\n return count", "def numrescueboats(people: List[int], limit: int) -> int:\n s = []\n c = 0\n people.sort(reverse=True)\n for i in range(len(people)):\n if s and people[i] < s[-1]:\n s[-1] = s[-1] - people[i]\n s.pop()\n elif s and people[i] == s[-1]:\n s.pop()\n elif s and people[i] > s[-1]:\n s.append(limit - people[i])\n c += 1\n elif people[i] == limit:\n c += 1\n else:\n c += 1\n s.append(limit - people[i])\n return c", "def numrescueboats(people: List[int], limit: int) -> int:\n less_than_half = dict()\n more_than_half = dict()\n half = 0\n total_boats = 0\n for person in people:\n diff = limit - person\n if diff == 0:\n total_boats += 1\n continue\n if person < limit / 2:\n if diff in more_than_half:\n total_boats += 1\n if more_than_half[diff] == 1:\n del more_than_half[diff]\n else:\n more_than_half[diff] -= 1\n elif person in less_than_half:\n less_than_half[person] += 1\n else:\n less_than_half[person] = 1\n elif person > limit / 2:\n if diff in less_than_half:\n total_boats += 1\n if less_than_half[diff] == 1:\n del less_than_half[diff]\n else:\n less_than_half[diff] -= 1\n elif person in more_than_half:\n more_than_half[person] += 1\n else:\n more_than_half[person] = 1\n elif half == 1:\n total_boats += 1\n half = 0\n else:\n half = 1\n less_keys = sorted(less_than_half.keys())\n more_keys = sorted(list(more_than_half.keys()), reverse=True)\n while len(less_keys) and len(more_keys):\n if less_keys[0] + more_keys[0] <= limit:\n if less_than_half[less_keys[0]] < more_than_half[more_keys[0]]:\n total_boats += less_than_half[less_keys[0]]\n more_than_half[more_keys[0]] -= less_than_half[less_keys[0]]\n less_keys.pop(0)\n elif less_than_half[less_keys[0]] > more_than_half[more_keys[0]]:\n total_boats += more_than_half[more_keys[0]]\n less_than_half[less_keys[0]] -= more_than_half[more_keys[0]]\n more_keys.pop(0)\n else:\n total_boats += less_than_half[less_keys[0]]\n less_keys.pop(0)\n more_keys.pop(0)\n else:\n total_boats += more_than_half[more_keys[0]]\n more_keys.pop(0)\n less_total = 0\n for k in less_keys:\n less_total += less_than_half[k]\n more_total = 0\n for k in more_keys:\n more_total += more_than_half[k]\n total_boats += (less_total + half + 1) // 2 + more_total\n return total_boats", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort(reverse=True)\n first_index = 0\n second_index = len(people) - 1\n ans = 0\n while first_index <= second_index:\n if people[first_index] + people[second_index] <= limit:\n second_index -= 1\n first_index += 1\n ans += 1\n return ans", "def numrescueboats(people: List[int], limit: int) -> int:\n people = sorted(people)\n i = 0\n j = len(people) - 1\n total = 0\n while i <= j:\n if i == j:\n total += 1\n i += 1\n j -= 1\n elif people[i] + people[j] <= limit:\n i += 1\n j -= 1\n total += 1\n else:\n j -= 1\n total += 1\n return total", "def numrescueboats(people: List[int], cap: int) -> int:\n people.sort()\n N = len(people)\n (i, j) = (0, N - 1)\n ans = 0\n k = cap\n s = 2\n while i <= j:\n while s and j >= 0:\n if k - people[j] < 0:\n break\n k -= people[j]\n j -= 1\n s -= 1\n while s and i < N:\n if k - people[i] < 0:\n break\n k -= people[i]\n i += 1\n s -= 1\n k = cap\n s = 2\n ans += 1\n return ans", "def numrescueboats(people: List[int], limit: int) -> int:\n sorted_people = list(sorted(people, reverse=True))\n i = 0\n j = len(people) - 1\n while i <= j:\n if sorted_people[i] + sorted_people[j] <= limit:\n j -= 1\n i += 1\n return i", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n count = len(people)\n end = len(people) - 1\n begin = 0\n res = 0\n while count > 0:\n if people[end] + people[begin] <= limit:\n res += 1\n count -= 2\n end -= 1\n begin += 1\n else:\n res += 1\n count -= 1\n end -= 1\n return res", "def numrescueboats(people: List[int], limit: int) -> int:\n groups = self.group_people_by_weight(people, limit)\n return self.count_num_boats(groups, limit)\n\ndef group_people_by_weight(people, limit):\n groups = [0] * (limit + 1)\n for person_weight in people:\n groups[person_weight] += 1\n return groups\n\ndef count_num_boats(groups, limit):\n num_boats = 0\n start = 0\n end = len(groups) - 1\n while start <= end:\n while start <= end and groups[start] <= 0:\n start += 1\n while start <= end and groups[end] <= 0:\n end -= 1\n if start > end:\n break\n if start + end <= limit:\n groups[start] -= 1\n groups[end] -= 1\n num_boats += 1\n return num_boats", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n low = 0\n up = len(people) - 1\n boats = 0\n while low <= up:\n if up - 1 >= low and people[up] + people[up - 1] <= limit:\n up -= 2\n boats += 1\n elif up != low and people[up] + people[low] <= limit:\n up -= 1\n low += 1\n boats += 1\n else:\n up -= 1\n boats += 1\n return boats", "from collections import deque\n\ndef numrescueboats(people, limit):\n n = len(people)\n weights = deque(sorted(people))\n boat = 0\n while n > 1:\n if weights[0] + weights[-1] <= limit:\n weights.popleft()\n weights.pop()\n n -= 2\n else:\n weights.pop()\n n -= 1\n boat += 1\n if n == 1:\n boat += 1\n return boat", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n l = 0\n h = len(people) - 1\n remain_capacity = limit\n if len(people) == 0:\n return 0\n boat = 1\n ppl_in_boat = 2\n while l <= h:\n if people[h] <= remain_capacity and ppl_in_boat != 0:\n remain_capacity -= people[h]\n ppl_in_boat -= 1\n h = h - 1\n elif remain_capacity >= people[l] and ppl_in_boat != 0:\n remain_capacity -= people[l]\n ppl_in_boat -= 1\n l = l + 1\n else:\n boat += 1\n remain_capacity = limit\n ppl_in_boat = 2\n return boat", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n if people[0] >= limit:\n return 0\n res = [0]\n (i, j) = (0, len(people) - 1)\n num_people = 0\n while i <= j:\n if res[-1] + people[j] <= limit and num_people < 2:\n res[-1] += people[j]\n j -= 1\n num_people += 1\n elif res[-1] + people[i] <= limit and num_people < 2:\n res[-1] += people[i]\n i += 1\n num_people += 1\n else:\n res.append(0)\n num_people = 0\n return len(res)", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n num_boats = 0\n last = len(people) - 1\n first = 0\n while first < last:\n if people[first] + people[last] <= limit:\n last -= 1\n first += 1\n num_boats += 1\n else:\n num_boats += 1\n last -= 1\n if first == last:\n num_boats += 1\n return num_boats", "def numrescueboats(people, limit):\n people.sort()\n (i, j) = (0, len(people) - 1)\n ans = 0\n while i <= j:\n ans += 1\n if people[i] + people[j] <= limit:\n i += 1\n j -= 1\n return ans", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n if len(people) == 0 or len(people) == 1:\n return len(people)\n else:\n lptr = 0\n rptr = len(people) - 1\n count = 0\n while lptr <= rptr:\n if people[lptr] + people[rptr] <= limit:\n count += 1\n lptr += 1\n rptr -= 1\n else:\n rptr -= 1\n count += 1\n return count", "from collections import deque\n\ndef numrescueboats(people: List[int], limit: int) -> int:\n people = deque(sorted(people))\n count = 0\n while len(people) > 1:\n lightest = people.popleft()\n heaviest = people.pop()\n if lightest + heaviest <= limit:\n count += 1\n continue\n else:\n if lightest < limit:\n people.appendleft(lightest)\n else:\n count += 1\n count += 1\n return count + len(people)", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort(reverse=True)\n res = 0\n i = 0\n j = len(people) - 1\n while i <= j:\n if people[i] + people[j] <= limit:\n j -= 1\n i += 1\n return i", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n lo = 0\n count = 0\n for hi in range(len(people))[::-1]:\n if lo < hi and people[lo] + people[hi] <= limit:\n lo += 1\n if lo == hi:\n return len(people) - hi", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n n = len(people)\n i = 0\n j = n - 1\n boats = 0\n while i <= j:\n if people[i] + people[j] <= limit:\n i += 1\n j -= 1\n boats += 1\n return boats", "def numrescueboats(people: List[int], limit: int) -> int:\n people = sorted(people)\n count = 0\n (i, j) = (0, len(people) - 1)\n while 0 <= i < j < len(people):\n while 0 <= i < j < len(people) and people[i] + people[j] > limit:\n j -= 1\n count += 1\n i += 1\n j -= 1\n count += 1\n if i == j:\n count += 1\n return count", "def numrescueboats(people: List[int], limit: int) -> int:\n minBoats = 0\n people.sort()\n left = 0\n right = len(people) - 1\n while left <= right:\n if people[left] + people[right] <= limit:\n left += 1\n minBoats += 1\n right -= 1\n return minBoats", "def numrescueboats(people: List[int], limit: int) -> int:\n people = sorted(people)\n left = 0\n right = len(people) - 1\n counter = 0\n while left < right:\n total = people[left] + people[right]\n counter += 1\n right -= 1\n if total <= limit:\n left += 1\n if left == right:\n counter += 1\n return counter", "def numrescueboats(people: List[int], limit: int) -> int:\n bucket = [0] * (limit + 1)\n for i in people:\n bucket[i] += 1\n start = 0\n end = len(bucket) - 1\n count = 0\n while start <= end:\n while start <= end and bucket[start] <= 0:\n start += 1\n while start <= end and bucket[end] <= 0:\n end -= 1\n if bucket[start] <= 0 and bucket[end] <= 0:\n break\n count += 1\n if start + end <= limit:\n bucket[start] -= 1\n bucket[end] -= 1\n return count", "def numrescueboats(people: List[int], limit: int) -> int:\n if people == None or len(people) == 0:\n return 0\n people.sort()\n start = 0\n end = len(people) - 1\n counter = 0\n while start <= end:\n if people[start] + people[end] <= limit:\n start += 1\n end -= 1\n else:\n end -= 1\n counter += 1\n return counter", "def numrescueboats(people: List[int], limit: int) -> int:\n q = collections.deque(sorted(people))\n ans = 0\n while len(q) > 1:\n (i, x) = (q.pop(), q[0])\n if i + x <= limit:\n q.popleft()\n ans += 1\n return ans + (1 if q else 0)", "import heapq\n\ndef numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n (i, j) = (0, len(people) - 1)\n ans = 0\n while i <= j:\n ans += 1\n if people[i] + people[j] <= limit:\n i += 1\n j -= 1\n return ans", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n p1 = 0\n p2 = len(people) - 1\n count = 1\n cur = 0\n curNum = 0\n while p1 <= p2:\n if people[p2] <= limit - cur and curNum < 2:\n cur = cur + people[p2]\n curNum += 1\n p2 -= 1\n continue\n if people[p1] <= limit - cur and curNum < 2:\n cur = cur + people[p1]\n curNum += 1\n p1 += 1\n continue\n count += 1\n cur = 0\n curNum = 0\n return count", "def numrescueboats(people: List[int], limit: int) -> int:\n people = sorted(people, reverse=True)\n boats = 0\n left = 0\n right = len(people) - 1\n while left <= right:\n if people[left] + people[right] <= limit:\n right -= 1\n left += 1\n boats += 1\n return boats", "def numrescueboats(people: List[int], limit: int) -> int:\n if not people or limit == 0:\n return 0\n ans = 0\n people.sort()\n (left, right) = (0, len(people) - 1)\n while left <= right:\n if people[left] + people[right] <= limit:\n left += 1\n right -= 1\n else:\n right -= 1\n ans += 1\n return ans", "from collections import Counter\n\ndef numrescueboats(people, limit):\n people.sort(reverse=True)\n boats = 0\n r = len(people) - 1\n l = 0\n while l <= r:\n boats += 1\n if people[l] + people[r] <= limit:\n r -= 1\n l += 1\n return boats", "def numrescueboats(people: List[int], limit: int) -> int:\n people = sorted(people)\n l = 0\n r = len(people) - 1\n ret = 0\n while l < r:\n if people[r] >= limit:\n ret += 1\n r -= 1\n elif people[r] + people[l] > limit:\n ret += 1\n r -= 1\n else:\n ret += 1\n l += 1\n r -= 1\n if l == r:\n ret += 1\n return ret", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n N = len(people)\n num_boats = 0\n if len(people) == 1:\n return 1\n less_than_half = [p for p in people if p <= limit / 2]\n more_than_half = [p for p in people if p > limit / 2]\n while len(more_than_half) > 0 and len(less_than_half) > 0:\n if more_than_half[-1] + less_than_half[0] > limit:\n more_than_half.pop(-1)\n num_boats += 1\n continue\n else:\n more_than_half.pop(-1)\n less_than_half.pop(0)\n num_boats += 1\n continue\n num_boats += len(more_than_half)\n num_boats += int(len(less_than_half) / 2 + 0.5)\n return num_boats", "def numrescueboats(people: List[int], limit: int) -> int:\n sortedPeople = sorted(people)\n i = 0\n j = len(sortedPeople) - 1\n count = 0\n while i <= j:\n if i == j:\n count += 1\n i += 1\n j -= 1\n continue\n if sortedPeople[i] + sortedPeople[j] <= limit:\n count += 1\n i += 1\n j -= 1\n else:\n count += 1\n j -= 1\n return count", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort(reverse=True)\n boats = people[:(1 + len(people)) // 2]\n onboard = [1] * len(boats)\n i = 0\n j = len(boats)\n k = len(people) - 1\n while j <= k:\n if i == len(boats):\n boats.append(people[j])\n j += 1\n if j > k:\n break\n target = limit - boats[i]\n if people[k] > target:\n i += 1\n if i == len(boats):\n boats.append(people[j])\n j += 1\n else:\n boats[i] += people[k]\n k -= 1\n i += 1\n return len(boats)", "def numrescueboats(people: List[int], limit: int) -> int:\n left = 0\n right = len(people) - 1\n boat = 0\n people.sort()\n while left <= right:\n if left == right:\n boat += 1\n break\n elif people[left] + people[right] <= limit:\n left += 1\n right -= 1\n boat += 1\n return boat"], "starter_code": "def numrescueboats(people: List[int], limit: int) -> int:\n", "input_output": {"fn_name": "numRescueBoats", "inputs": [[[1, 2], 3]], "outputs": [1]}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Two Pointers", "Greedy", "Sorting"], "name": null, "source": "leetcode", "tags": ["Data structures", "Sorting", "Amortized analysis", "Greedy algorithms"], "skill_types": ["Sorting", "Amortized analysis", "Data structures", "Greedy algorithms"], "url": "https://leetcode.com/problems/boats-to-save-people/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numrescueboats", "task_id": "TACO_lite/331", "example": [[[[1, 2], 3], [[3, 2, 2, 1], 3], [[3, 5, 3, 4], 5]], ["1", "3", "4"]]} +{"requirement": "Given a sorted array of size N. Count the number of distinct absolute values present in the array.\n \nExample 1:\nInput:\nN = 6\nArr[] = {-3, -2, 0, 3, 4, 5}\nOutput: 5\nExplanation: There are 5 distinct absolute \nvalues i.e. 0, 2, 3, 4 and 5.\nExample 2:\nInput:\nN = 9\nArr[] = {-1, -1, -1, -1, 0, 1, 1, 1, 1}\nOutput: 2\nExplanation: There are 2 distinct absolute values \namong the elements of this array, i.e. 0 and 1.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function distinctCount() which takes the array of integers arr[] and its size n as input parameters and returns an integer denoting the answer.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 10^{5}\n-10^{8} <= Arr[i] <= 10^{8}\nThe array may contain duplicates", "solutions": ["def distinctcount(arr, n):\n s = [abs(x) for x in arr]\n s = list(set(s))\n return len(s)", "def distinctcount(arr, n):\n c = set()\n for i in arr:\n if i not in c:\n c.add(abs(i))\n return len(c)", "def distinctcount(arr, n):\n l = []\n for i in arr:\n l.append(abs(i))\n return len(set(l))", "def distinctcount(arr, n):\n d = {}\n for i in arr:\n d[abs(i)] = d.setdefault(abs(i), 0) + 1\n return len(d)", "def distinctcount(arr, n):\n for i in range(n):\n arr[i] = abs(arr[i])\n a = set(arr)\n b = list(a)\n return len(b)", "def distinctcount(arr, n):\n i = 0\n while i < n:\n if arr[i] < 0:\n arr[i] = abs(arr[i])\n i += 1\n return len(set(arr))", "def distinctcount(arr, n):\n s = set()\n for i in arr:\n s.add(abs(i))\n return len(s)", "def distinctcount(arr, n):\n for i in range(n):\n arr[i] = abs(arr[i])\n return len(set(arr))", "def distinctcount(arr, n):\n num = [abs(i) for i in arr]\n num = list(set(num))\n return len(num)", "def distinctcount(arr, n):\n i = 0\n j = n - 1\n prev = -10000000007\n next = 10000000007\n c = 0\n while i <= j:\n if abs(arr[i]) == abs(arr[j]):\n if arr[i] != prev and arr[j] != next:\n c += 1\n prev = arr[i]\n next = arr[j]\n i += 1\n j -= 1\n elif abs(arr[i]) < abs(arr[j]):\n if arr[j] != next:\n c += 1\n next = arr[j]\n j -= 1\n else:\n if arr[i] != prev:\n c += 1\n prev = arr[i]\n i += 1\n return c", "def distinctcount(arr, n):\n res = [abs(ele) for ele in arr]\n a = set(res)\n return len(a)", "from collections import Counter\n\ndef distinctcount(arr, n):\n return len(Counter(map(abs, arr)))", "def distinctcount(arr, n):\n ans = set()\n for e in arr:\n ans.add(abs(e))\n return len(ans)", "def distinctcount(arr, n):\n for i in range(n):\n if arr[i] < 0:\n arr[i] = -1 * arr[i]\n return len(set(arr))", "def distinctcount(arr, n):\n hmap = {}\n for i in arr:\n y = abs(i)\n if y not in hmap:\n hmap[y] = 1\n else:\n hmap[y] += 1\n return len(hmap)", "def distinctcount(arr, n):\n d = {}\n for i in arr:\n b = abs(i)\n if b not in d:\n d[b] = 1\n return len(d)", "def distinctcount(arr, n):\n m = [abs(i) for i in arr]\n l = list(set(m))\n return len(l)", "def distinctcount(arr, n):\n for i in range(n):\n if arr[i] < 0:\n arr[i] = -1 * arr[i]\n arr.sort()\n i = 1\n count = 1\n while i < n:\n if arr[i - 1] == arr[i]:\n i += 1\n else:\n count += 1\n i += 1\n return count", "def distinctcount(arr, n):\n ab = []\n for i in arr:\n ab.append(abs(i))\n return len(list(set(ab)))", "def distinctcount(arr, n):\n res = {}\n for i in range(n):\n if abs(arr[i]) not in res:\n res[abs(arr[i])] = 1\n return len(res)", "def distinctcount(arr, n):\n s = {}\n for i in arr:\n s[abs(i)] = 1\n return len(s)", "def distinctcount(arr, n):\n s = set()\n for x in arr:\n if x < 0:\n s.add(x * -1)\n else:\n s.add(x)\n return len(s)", "def distinctcount(arr, n):\n l = {}\n for i in arr:\n if abs(i) not in l:\n l[abs(i)] = 1\n return sum(l.values())", "import bisect\n\ndef distinctcount(a, n):\n num = [abs(i) for i in a]\n num = list(set(num))\n return len(num)", "def distinctcount(arr, n):\n l = 0\n r = n - 1\n cnt = 0\n while l <= r:\n while l < r and r > 0 and (arr[r - 1] == arr[r]):\n r = r - 1\n while l < r and l < n - 1 and (arr[l] == arr[l + 1]):\n l = l + 1\n if abs(arr[l]) == abs(arr[r]):\n l = l + 1\n r = r - 1\n elif abs(arr[l]) > abs(arr[r]):\n l = l + 1\n else:\n r = r - 1\n cnt = cnt + 1\n return cnt", "def distinctcount(arr, n):\n low = 0\n high = n - 1\n ans = n\n s = 0\n while low < high:\n while low != high and arr[low] == arr[low + 1]:\n ans -= 1\n low += 1\n while low != high and arr[high - 1] == arr[high]:\n ans -= 1\n high -= 1\n if low == high:\n break\n s = arr[low] + arr[high]\n if s == 0:\n ans -= 1\n low += 1\n high -= 1\n elif s > 0:\n high -= 1\n else:\n low += 1\n return ans", "def distinctcount(arr, n):\n count = 0\n gg = {}\n for i in arr:\n if i < 0:\n i = -i\n if i not in gg:\n gg[i] = 1\n count += 1\n return count", "def distinctcount(arr, n):\n u = []\n for i in range(len(arr)):\n u.append(abs(arr[i]))\n x = list(set(u))\n return len(x)", "from collections import defaultdict\n\ndef distinctcount(arr, n):\n d = defaultdict(lambda : 0)\n c = n\n for i in range(n - 1, -1, -1):\n if arr[i] >= 0:\n d[arr[i]] += 1\n else:\n x = abs(arr[i])\n if d[x] > 0:\n continue\n return len(d)", "def distinctcount(arr, n):\n cnt = n\n (i, j) = (0, n - 1)\n while i < j:\n while i != j and arr[i] == arr[i + 1]:\n i += 1\n cnt -= 1\n while i != j and arr[j] == arr[j - 1]:\n j -= 1\n cnt -= 1\n if i == j:\n break\n if arr[i] + arr[j] < 0:\n i += 1\n elif arr[i] + arr[j] > 0:\n j -= 1\n else:\n cnt -= 1\n i += 1\n j -= 1\n return cnt", "def distinctcount(arr, n):\n return len(set(sorted(map(abs, arr))))", "def distinctcount(arr, n):\n dictt = {}\n for ele in arr:\n ele = abs(ele)\n dictt[ele] = dictt.get(ele, 0) + 1\n return len(dictt)", "def distinctcount(arr, n):\n d = set()\n for i in arr:\n if i < 0:\n d.add(-1 * i)\n else:\n d.add(i)\n return len(list(d))", "def distinctcount(arr, n):\n c = 0\n i = 0\n j = len(arr) - 1\n prev = float('-inf')\n nextt = float('inf')\n while i <= j:\n if abs(arr[i]) == abs(arr[j]):\n if arr[i] != prev and arr[j] != nextt:\n c += 1\n prev = arr[i]\n nextt = arr[j]\n i += 1\n j -= 1\n elif abs(arr[i]) < abs(arr[j]):\n if arr[j] != nextt:\n c += 1\n nextt = arr[j]\n j -= 1\n elif abs(arr[i]) > abs(arr[j]):\n if arr[i] != prev:\n c += 1\n prev = arr[i]\n i += 1\n return c", "def distinctcount(arr, n):\n import numpy as np\n arr = [np.abs(i) for i in arr]\n return len(list(set(arr)))", "def distinctcount(arr, n):\n arr = list(set([abs(a) for a in arr]))\n return len(arr)"], "starter_code": "def distinctcount(arr, n):\n", "input_output": {"inputs": ["N = 6\r\nArr[] = {-3, -2, 0, 3, 4, 5}", "N = 9\r\nArr[] = {-1, -1, -1, -1, 0, 1, 1, 1, 1}"], "outputs": ["5", "2"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays", "Algorithms", "Sorting"], "name": null, "source": "geeksforgeeks", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/distinct-absolute-array-elements4529/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "distinctcount", "task_id": "TACO_lite/325", "example": [[[6, [-3, -2, 0, 3, 4, 5]], [9, [-1, -1, -1, -1, 0, 1, 1, 1, 1]]], ["5", "2"]]} +{"requirement": "Given an array of N elements and L and R, print the number of sub-arrays such that the value of the maximum array element in that subarray is at least L and at most R.\nExample 1:\nInput : Arr[] = {2, 0, 11, 3, 0}\nL = 1 and R = 10\nOutput : 4\nExplanation:\nThe sub-arrays {2}, {2, 0}, {3} and {3, 0}\nhave maximum in range 1-10.\nExample 2:\nInput : Arr[] = {3, 4, 1}\nL = 2 and R = 4\nOutput : 5\n \nYour Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function countSubarrays() that takes an array (arr), sizeOfArray (n), element L, integer R, and return the number of subarray with the maximum in range L-R. The driver code takes care of the printing.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\n \nConstraints:\n1 ≤ N ≤ 10^{5}\n1 ≤ L ≤ R ≤ 10^{6}", "solutions": ["def mgc(n):\n return n * (n + 1) // 2\n\ndef countsubarrays(a, n, L, R):\n (fp, lp) = (0, 0)\n ans = 0\n prev = 0\n while lp < n:\n if a[lp] >= L and a[lp] <= R:\n prev = lp - fp + 1\n elif a[lp] > R:\n prev = 0\n fp = lp + 1\n lp += 1\n ans += prev\n return ans", "def countsubarrays(nums, a, left, right):\n ans = 0\n cnt = 0\n i = 0\n j = 0\n while i < a:\n if nums[i] >= left and nums[i] <= right:\n cnt = i - j + 1\n ans += cnt\n elif nums[i] < left:\n ans += cnt\n elif nums[i] > right:\n cnt = 0\n j = i + 1\n i += 1\n return ans", "def countsubarrays(nums, a, left, right):\n\n def count(bound):\n ans = cnt = 0\n for x in nums:\n if x <= bound:\n cnt = cnt + 1\n else:\n cnt = 0\n ans += cnt\n return ans\n return count(right) - count(left - 1)", "def countsubarrays(a, n, L, R):\n ans = 0\n maxele = -999999\n maxind = -1\n cnt = 0\n for i in range(n):\n if a[i] >= L and a[i] <= R:\n cnt = 0\n ans += i - maxind\n elif a[i] > R:\n cnt = 0\n maxind = i\n else:\n cnt += 1\n ans += i - maxind - cnt\n return ans", "def countsubarrays(a, n, L, R):\n (wind, count, i, j) = (0, 0, 0, 0)\n while j < n:\n if a[j] >= L and a[j] <= R:\n wind = j - i + 1\n elif a[j] > R:\n wind = 0\n i = j + 1\n count += wind\n j += 1\n return count", "def countsubarrays(a, n, L, R):\n (left, right) = (-1, -1)\n idx = 0\n ans = 0\n while idx < n:\n cur = a[idx]\n if L <= cur <= R:\n right = idx\n elif cur > R:\n (left, right) = (idx, idx)\n ans += right - left\n idx += 1\n return ans", "def countsubarrays(a, n, L, R):\n right = -1\n start = -1\n i = 0\n ans = 0\n while i < n:\n cur = a[i]\n if L <= cur <= R:\n right = i\n elif cur > R:\n start = i\n right = i\n ans += right - start\n i += 1\n return ans", "def countsubarrays(a, n, L, R):\n cur_max = 0\n cur_max_idx = -1\n right_most_range = 0\n start = -1\n i = 0\n ans = 0\n while i < n:\n cur = a[i]\n if L <= cur <= R:\n right_most_idx = i\n if cur_max < cur:\n cur_max = cur\n cur_max_idx = i\n if cur_max > R:\n start = i\n cur_max = 0\n cur_max_idx = i\n right_most_range = i\n elif L <= cur_max <= R:\n ans += right_most_idx - start\n i += 1\n return ans", "def countsubarrays(a, n, L, R):\n ans = 0\n sub = 0\n start = 0\n for end in range(n):\n if arr[end] >= L and arr[end] <= R:\n sub = end - start + 1\n if arr[end] > R:\n sub = 0\n start = end + 1\n ans += sub\n return ans", "def countsubarrays(a, n, L, R):\n i = 0\n j = 0\n count = 0\n result = 0\n while j < len(a):\n if L <= a[j] <= R:\n result = j - i + 1\n if a[j] > R:\n result = 0\n i = j + 1\n count = count + result\n j = j + 1\n return count", "def countsubarrays(a, n, L, R):\n i = 0\n j = 0\n count = 0\n m = 0\n while j < n:\n if a[j] > R:\n m = 0\n i = j + 1\n elif a[j] in range(L, R + 1):\n m = j - i + 1\n j += 1\n count += m\n return count", "def code(n):\n return n * (n + 1) // 2\n\ndef countsubarrays(a, n, L, R):\n l = 0\n r = 0\n ans = 0\n for i in range(n):\n if a[i] < L:\n l += 1\n r += 1\n elif a[i] > R:\n ans += Solution.code(l) - Solution.code(r)\n l = 0\n r = 0\n else:\n ans -= Solution.code(r)\n r = 0\n l += 1\n ans += Solution.code(l) - Solution.code(r)\n return ans", "def countsubarrays(arr, n, L, R):\n ans = 0\n prevcnt = 0\n (s, e) = (0, 0)\n while e <= n - 1:\n if L <= arr[e] and arr[e] <= R:\n ans += e - s + 1\n prevcnt = e - s + 1\n elif arr[e] < L:\n ans += prevcnt\n elif arr[e] > R:\n s = e + 1\n prevcnt = 0\n e += 1\n return ans", "def countsubarrays(a, n, L, R):\n\n def sub(n):\n return n * (n + 1) // 2\n res = 0\n inc = 0\n exc = 0\n for i in range(len(a)):\n if arr[i] > R:\n res = res + (sub(inc) - sub(exc))\n inc = 0\n exc = 0\n elif arr[i] < L:\n inc += 1\n exc += 1\n else:\n res = res - sub(exc)\n inc += 1\n exc = 0\n res = res + (sub(inc) - sub(exc))\n return res", "def countsubarrays(nums, n, left, right):\n i = 0\n j = 0\n c = 0\n m = 0\n while j < len(nums):\n if nums[j] > r:\n m = 0\n i = j + 1\n elif nums[j] >= left and nums[j] <= right:\n m = j - i + 1\n c += m\n j += 1\n return c", "def countsubarrays(a, n, L, R):\n ans = 0\n st = 0\n build = 0\n for i in range(n):\n if L <= a[i] <= R:\n build = i - st + 1\n elif a[i] > R:\n build = 0\n st = i + 1\n ans += build\n return ans", "def countsubarrays(arr, n, L, R):\n (i, j) = (0, 0)\n count = 0\n m = 0\n while j < n:\n if arr[j] >= L and arr[j] <= R:\n m = j - i + 1\n elif arr[j] > R:\n m = 0\n i = j + 1\n count += m\n j += 1\n return count", "def countsubarrays(a, n, L, R):\n c = 0\n (i, j, k) = (0, 0, 0)\n while j < n:\n if a[j] > R:\n k = 0\n i = j + 1\n elif a[j] >= L and a[j] <= R:\n k = j - i + 1\n c += k\n j += 1\n return c", "from collections import deque\n\ndef countsubarrays(arr, n, l, r):\n dp = [0] * n\n q = deque()\n for i in range(n):\n while q and arr[q[-1]] <= arr[i]:\n q.pop()\n if not q:\n dp[i] = (i + 1) * int(l <= arr[i] <= r)\n else:\n dp[i] = (i - q[-1]) * int(l <= arr[i] <= r) + dp[q[-1]]\n q.append(i)\n return sum(dp)", "def countsubarrays(nums, n, left, right):\n (n, l, valid, res) = (len(nums), 0, 0, 0)\n for r in range(0, n):\n if left <= nums[r] <= right:\n valid = r - l + 1\n if nums[r] > right:\n l = r + 1\n valid = 0\n res += valid\n return res", "def countsubarrays(a, n, L, R):\n i = j = 0\n ans = curr = 0\n while j < n:\n if a[j] >= L and a[j] <= R:\n curr = j - i + 1\n if a[j] > R:\n curr = 0\n i = j + 1\n ans += curr\n j += 1\n return ans", "def countsubarrays(a, n, L, R):\n\n def maxlessthanequalto(x):\n max_so_far = 0\n end = start = 0\n count = 0\n while end < n:\n if a[end] <= x:\n count += end - start + 1\n end += 1\n else:\n end = end + 1\n start = end\n return count\n return maxlessthanequalto(R) - maxlessthanequalto(L - 1)", "def countsubarrays(a, n, L, R):\n start = 0\n count = 0\n sub_count = 0\n for end in range(n):\n if a[end] >= L and a[end] <= R:\n sub_count = end - start + 1\n elif a[end] > R:\n start = end + 1\n sub_count = 0\n count += sub_count\n return count", "def count_sub_array(n):\n return n * (n + 1) // 2 if n else 0\n\ndef countsubarrays(a, n, L, R):\n less_tha_l = 0\n total = 0\n ans = 0\n for i in range(n):\n if a[i] > R:\n ans += self.count_sub_array(total) - self.count_sub_array(less_tha_l)\n less_tha_l = 0\n total = 0\n elif a[i] < L:\n less_tha_l += 1\n total += 1\n else:\n ans = ans - self.count_sub_array(less_tha_l)\n less_tha_l = 0\n total += 1\n ans += self.count_sub_array(total) - self.count_sub_array(less_tha_l)\n return ans", "def countsubarrays(a, n, l, r):\n (i, j, ans) = (-1, -1, 0)\n for k in range(n):\n if a[k] > r:\n (i, j) = (k, k)\n elif a[k] >= l and a[k] <= r:\n j = k\n ans += j - i\n return ans", "def countsubarrays(a, n, L, R):\n (gr, ls, temp) = (0, 0, 0)\n for i in range(n):\n if arr[i] <= r:\n gr += 1\n else:\n temp += gr * (gr + 1) // 2\n gr = 0\n if arr[i] < l:\n ls += 1\n else:\n temp -= ls * (ls + 1) // 2\n ls = 0\n temp -= ls * (ls + 1) // 2\n temp += gr * (gr + 1) // 2\n return temp", "def countsubarrays(nums, n, left, right):\n (start, count, window_len) = (0, 0, 0)\n for (end, num) in enumerate(nums):\n if left <= num <= right:\n window_len = end - start + 1\n elif num > right:\n window_len = 0\n start = end + 1\n count += window_len\n return count", "def countsubarrays(a, n, l, r):\n i = 0\n j = 0\n c = 0\n ans = 0\n while j < n:\n if a[j] >= l and a[j] <= r:\n c = j - i + 1\n if a[j] > r:\n i = j + 1\n c = 0\n ans += c\n j = j + 1\n return ans", "def f(n):\n return n * (n + 1) // 2\n\ndef countsubarrays(arr, n, L, R):\n x = 0\n y = 0\n ans = 0\n for i in arr:\n if i > R:\n ans += self.f(x) - self.f(y)\n x = 0\n y = 0\n elif i < L:\n x += 1\n y += 1\n else:\n ans -= self.f(y)\n x += 1\n y = 0\n ans += self.f(x) - self.f(y)\n return ans", "def count(n):\n return n * (n + 1) // 2\n\ndef countsubarrays(a, n, L, R):\n ans = 0\n x = 0\n y = 0\n for i in a:\n if i > R:\n ans += self.count(x) - self.count(y)\n x = 0\n y = 0\n elif i < L:\n x += 1\n y += 1\n else:\n ans -= self.count(y)\n x += 1\n y = 0\n ans += self.count(x) - self.count(y)\n return ans", "def countsubarrays(a, n, L, R):\n si = 0\n ans = 0\n prev = 0\n for ei in range(n):\n if l <= a[ei] <= R:\n prev = ei - si + 1\n ans += prev\n elif L > a[ei]:\n ans += prev\n else:\n prev = 0\n si = ei + 1\n return ans", "def countsubarrays(a, n, L, R):\n i0 = 0\n i1 = 0\n Rplus = 0\n Lminus = 0\n Lminus1 = 0\n res = 0\n for j in range(len(a)):\n if a[j] > R:\n Rplus += 1\n elif a[j] < L:\n Lminus += 1\n Lminus1 += 1\n while Rplus > 0:\n if a[i0] > R:\n Rplus -= 1\n elif a[i0] < L:\n Lminus -= 1\n i0 += 1\n if i0 > i1:\n if a[i1] < L:\n Lminus1 -= 1\n i1 += 1\n while i1 <= j and Lminus1 < j - i1 + 1:\n if a[i1] < L:\n Lminus1 -= 1\n i1 += 1\n res += i1 - i0\n return res", "def countsubarrays(a, n, L, R):\n res = 0\n N = n\n A = a\n start = 0\n count = 0\n for i in range(N):\n if A[i] >= L and A[i] <= R:\n count = i - start + 1\n res = res + i - start + 1\n elif A[i] < L:\n res = res + count\n else:\n count = 0\n start = i + 1\n return res", "def countsubarrays(a, n, L, R):\n res = 0\n count = 0\n i = 0\n for j in range(n):\n if L <= a[j] <= R:\n count = j - i + 1\n res += count\n elif a[j] < L:\n res += count\n elif a[j] > R:\n count = 0\n i = j + 1\n return res"], "starter_code": "def countsubarrays(a,n,L,R):\n", "input_output": {"inputs": ["Arr[] = {2, 0, 11, 3, 0}\nL = 1 and R = 10", "Arr[] = {3, 4, 1}\nL = 2 and R = 4"], "outputs": ["4", "5"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "two-pointer-algorithm", "sliding-window", "Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Amortized analysis"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/number-of-subarrays-with-maximum-values-in-given-range5949/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "countsubarrays", "task_id": "TACO_lite/294", "example": [[[[2, 0, 11, 3, 0], 5, 1, 10], [[3, 4, 1], 3, 2, 4]], ["4", "5"]]} +{"requirement": "Your job at E-Corp is both boring and difficult. It isn't made any easier by the fact that everyone constantly wants to have a meeting with you, and that the meeting rooms are always taken!\n\nIn this kata, you will be given an array. Each value represents a meeting room. Your job? Find the **first** empty one and return its index (N.B. There may be more than one empty room in some test cases). \n\n'X' --> busy\n'O' --> empty\n\nIf all rooms are busy, return 'None available!'.\n\n\nMore in this series:\n\nThe Office I - Outed\nThe Office II - Boredeom Score\nThe Office III - Broken Photocopier\nThe Office V - Find a Chair", "solutions": ["def meeting(rooms):\n try:\n return rooms.index('O')\n except ValueError:\n return 'None available!'", "def meeting(rooms):\n return rooms.index('O') if 'O' in rooms else 'None available!'", "def meeting(rooms):\n return next((i for (i, r) in enumerate(rooms) if r == 'O'), 'None available!')", "def meeting(rooms):\n if 'O' not in rooms:\n return 'None available!'\n return rooms.index('O')", "def meeting(rooms):\n for (num, status) in enumerate(rooms):\n if status == 'O':\n return num\n return 'None available!'", "def meeting(rooms):\n return [o for (o, v) in enumerate(rooms) if v == 'O'][0] if 'O' in rooms else 'None available!'", "def meeting(rooms):\n tally = 0\n for i in rooms:\n if i == 'O':\n return tally\n else:\n tally += 1\n return 'None available!'", "def meeting(rooms):\n for x in rooms:\n if x is 'O':\n return rooms.index(x)\n return 'None available!'"], "starter_code": "def meeting(rooms):\n", "input_output": {"fn_name": "meeting", "inputs": [[["X", "O", "X"]], [["O", "X", "X", "X", "X"]], [["X", "X", "O", "X", "X"]], [["X"]]], "outputs": [[1], [0], [2], ["None available!"]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57f604a21bd4fe771b00009c", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "meeting", "task_id": "TACO_lite/312", "example": [[[["X", "O", "X", "X"]], [["X", "X", "X"]], [["X", "O", "O", "X"]]], ["1", "None available!", "1"]]} +{"requirement": "Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.)\n(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)\nSince the answer may be large, return the answer modulo 10^9 + 7.\n \nExample 1:\nInput: n = 5\nOutput: 12\nExplanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.\n\nExample 2:\nInput: n = 100\nOutput: 682289015\n\n \nConstraints:\n\n1 <= n <= 100", "solutions": ["def numprimearrangements(n: int) -> int:\n primes = [True] * (n + 1)\n for prime in range(2, int(math.sqrt(n)) + 1):\n if primes[prime]:\n for composite in range(prime * prime, n + 1, prime):\n primes[composite] = False\n cnt = sum(primes[2:])\n return math.factorial(cnt) * math.factorial(n - cnt) % (10 ** 9 + 7)", "def numprimearrangements(n: int) -> int:\n p_nums = []\n c_nums = []\n dp = [True for _ in range(n + 1)]\n dp[0] = False\n dp[1] = False\n for i in range(2, n + 1):\n if dp[i] == True:\n cnt = 2\n while i * cnt < n + 1:\n dp[i * cnt] = False\n cnt += 1\n for i in range(1, n + 1):\n if dp[i]:\n p_nums += [i]\n else:\n c_nums += [i]\n return self.fact(len(p_nums) % (10 ** 9 + 7)) * self.fact(len(c_nums)) % (10 ** 9 + 7)\n\ndef fact(n):\n if n <= 1:\n return 1\n else:\n return n * self.fact(n - 1)", "def numprimearrangements(n: int) -> int:\n\n def fac(m):\n result = 1\n for i in range(1, m + 1):\n result *= i\n return result\n\n def PrimeTell(m):\n if m == 1 or m == 4:\n return False\n if m == 2 or m == 3:\n return True\n for j in range(2, m // 2):\n if m % j == 0:\n return False\n return True\n Sum = 0\n for i in range(1, n + 1):\n if PrimeTell(i):\n Sum += 1\n return fac(Sum) * fac(n - Sum) % (10 ** 9 + 7)", "def numprimearrangements(n: int) -> int:\n if n == 1:\n return 1\n p = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n if n < 98:\n (lo, hi) = (0, 24)\n while lo <= hi:\n mid = (hi - lo) // 2 + lo\n if p[mid] == n:\n idx = mid + 1\n break\n elif p[mid - 1] < n and n < p[mid]:\n idx = mid\n break\n elif p[mid] > n:\n hi = mid - 1\n else:\n lo = mid + 1\n else:\n idx = 25\n p_prod = 1\n for i in range(1, idx + 1):\n p_prod = p_prod * (i % 1000000007) % 1000000007\n c_prod = 1\n for i in range(1, n - idx + 1):\n c_prod = c_prod * (i % 1000000007) % 1000000007\n return p_prod * c_prod % 1000000007", "def numprimearrangements(n: int) -> int:\n primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n r = sum((1 for p in primes if p <= n))\n a = 10 ** 9 + 7\n ans = 1\n for i in range(1, min(r, n - r) + 1):\n ans *= (i % a) ** 2\n ans %= a\n for i in range(min(r, n - r) + 1, max(r, n - r) + 1):\n ans *= i\n ans %= a\n return ans"], "starter_code": "def numprimearrangements(n: int) -> int:\n", "input_output": {"fn_name": "numPrimeArrangements", "inputs": [[5]], "outputs": [12]}, "difficulty": "EASY", "raw_tags": ["Math"], "name": null, "source": "leetcode", "tags": ["Mathematics"], "skill_types": [], "url": "https://leetcode.com/problems/prime-arrangements/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numprimearrangements", "task_id": "TACO_lite/281", "example": [[[5], [100]], ["12", "682289015"]]} +{"requirement": "Create a function that accepts 3 inputs, a string, a starting location, and a length. The function needs to simulate the string endlessly repeating in both directions and return a substring beginning at the starting location and continues for length.\n\nExample:\n```python\nendless_string('xyz', -23, 6) == 'yzxyzx'\n```\nTo visualize:\n\n Negative Positive\n 3 2 1 * 1 2 3 \n 0987654321098765432109876543210123456789012345678901234567890\n xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzx\n ******\n -23 for a length of 6 == 'yzxyzx'\n \nSome more examples:\n```python\nendless_string('xyz', 0, 4) == 'xyzx'\nendless_string('xyz', 19, 2) == 'yz'\nendless_string('xyz', -4, -4) == 'zxyz'\n```\n\nA negative length needs to include the starting postion and return the characters to the left of the starting position.", "solutions": ["from itertools import cycle, islice\n\ndef endless_string(string, start, length):\n i = (start + (length + 1 if length < 0 else 0)) % len(string)\n return ''.join(islice(cycle(string), i, i + abs(length)))", "from itertools import cycle, islice\n\ndef endless_string(stg, i, l):\n i = min(i, i + l) % len(stg) + (l < 0)\n j = i + abs(l)\n return ''.join(islice(cycle(stg), i, j))", "from itertools import cycle, islice\n\ndef endless_string(string, start, length):\n r = (start + (length + 1) * (length < 0)) % len(string)\n return ''.join(islice(cycle(string), r, r + abs(length)))", "def endless_string(s, start, l):\n s = s * 500\n half = len(s) // 2\n return s[half + start:half + start + l] if l > 0 else s[half + start + l + 1:half + start + 1]", "def endless_string(strng, start, length):\n len_strng = len(strng)\n strng = strng * (abs(length) // len_strng + 1)\n true_start = min(start, start + length)\n start = true_start % len_strng + (length < 0)\n stop = start + abs(length)\n return strng[start:stop]", "def endless_string(stg, i, l):\n ls = len(stg)\n stg = stg * (2 + abs(l) // ls)\n i = min(i, i + l) % ls + (l < 0)\n j = i + abs(l)\n return stg[i:j]"], "starter_code": "def endless_string(string, start, length):\n", "input_output": {"fn_name": "endless_string", "inputs": [["xyz", -23, 6], ["xyz", 0, 4], ["xyz", 19, 2], ["xyz", -4, -4], ["abcdefghijklmnopqrstuvwxyz", 29, 1], ["Hello! How are you?", -14, 27], ["1x2x3x4x", 1532, 100], ["1x2x3x4x", -1532, -100], ["112233", 0, 0], ["112233", -1, 0], ["112233", 15824, 0]], "outputs": [["yzxyzx"], ["xyzx"], ["yz"], ["zxyz"], ["d"], ["! How are you?Hello! How ar"], ["3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x"], ["x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3"], [""], [""], [""]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/57048c1275263af10b00063e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "endless_string", "task_id": "TACO_lite/319", "example": [[["xyz", -23, 6], ["xyz", 0, 4], ["xyz", 19, 2], ["xyz", -4, -4]], ["yzxyzx", "xyzx", "yz", "zxyz"]]} +{"requirement": "# Story\n\nThose pesky rats have returned and this time they have taken over the Town Square.\n\nThe Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.\n\nBut some of the rats are deaf and are going the wrong way!\n\n# Kata Task\n\nHow many deaf rats are there?\n\n## Input Notes\n\n* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)\n* The Pied Piper is always present\n\n## Output Notes\n* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now\n* Use Euclidian distance for your calculations\n\n## Legend\n\n* `P` = The Pied Piper\n* `←` `↑` `→` `↓` `↖` `↗` `↘` `↙` = Rats going in different directions\n* space = Everything else\n\n\n\n# Examples\n\nex1 - has 1 deaf rat\n\n\n↗ P \n ↘ ↖\n ↑ \n↗ \n\n\n---\n\nex2 - has 7 deaf rats\n\n\n ↗ \nP ↓ ↖ ↑\n ← ↓\n ↖ ↙ ↙\n↓ ↓ ↓", "solutions": ["from math import hypot\nDIRS = {'←': (0, -1), '↑': (-1, 0), '→': (0, 1), '↓': (1, 0), '↖': (-1, -1), '↗': (-1, 1), '↘': (1, 1), '↙': (1, -1)}\n\ndef count_deaf_rats(town):\n pipper = next(((x, y) for (x, r) in enumerate(town) for (y, c) in enumerate(r) if c == 'P'))\n return sum((isDeaf(pipper, x, y, *DIRS[c]) for (x, r) in enumerate(town) for (y, c) in enumerate(r) if c in DIRS))\n\ndef isDeaf(pipper, x, y, dx, dy):\n (dCurrent, dNext) = (hypot(*(a - b for (a, b) in zip(pipper, pos))) for pos in ((x, y), (x + dx, y + dy)))\n return dCurrent < dNext", "from math import copysign\ndirections = {'←': (0, -1), '↑': (-1, 0), '→': (0, 1), '↓': (1, 0), '↖': (-1, -1), '↗': (-1, 1), '↘': (1, 1), '↙': (1, -1)}\n\ndef count_deaf_rats(town_square):\n (pi, pj) = next(((i, j) for (i, row) in enumerate(town_square) for (j, x) in enumerate(row) if x == 'P'))\n result = 0\n for (i, row) in enumerate(town_square):\n for (j, x) in enumerate(row):\n if x not in directions:\n continue\n (di, dj) = directions[x]\n if (i + di - pi) ** 2 + (j + dj - pj) ** 2 > (i - pi) ** 2 + (j - pj) ** 2:\n result += 1\n return result", "D = {'↖': -1 - 1j, '↑': -1, '↗': -1 + 1j, '←': -1j, '→': +1j, '↙': +1 - 1j, '↓': +1, '↘': +1 + 1j}\n\ndef count_deaf_rats(town_square):\n coords = [(i + j * 1j, x) for (i, row) in enumerate(town_square) for (j, x) in enumerate(row)]\n p = next((c for (c, x) in coords if x == 'P'))\n return sum((abs(c + D.get(x, 0) - p) > abs(c - p) for (c, x) in coords))", "from math import hypot\nmoves = {'↖': (-1, -1), '←': (-1, 0), '↙': (-1, 1), '↑': (0, -1), '↓': (0, 1), '↗': (1, -1), '→': (1, 0), '↘': (1, 1)}\n\ndef count_deaf_rats(town_square):\n (deaf, (px, py)) = (0, next(((row.index('P'), y) for (y, row) in enumerate(town_square) if 'P' in row)))\n dist = lambda x, y: hypot(px - x, py - y)\n for (y, row) in enumerate(town_square):\n for (x, c) in enumerate(row):\n if c in moves:\n (mx, my) = moves[c]\n if dist(x, y) < dist(x + mx, y + my):\n deaf += 1\n return deaf", "import math\nDirection = {'←': lambda position: Position(position.x - 1, position.y), '↑': lambda position: Position(position.x, position.y - 1), '→': lambda position: Position(position.x + 1, position.y), '↓': lambda position: Position(position.x, position.y + 1), '↖': lambda position: Position(position.x - 1, position.y - 1), '↗': lambda position: Position(position.x + 1, position.y - 1), '↘': lambda position: Position(position.x + 1, position.y + 1), '↙': lambda position: Position(position.x - 1, position.y + 1)}\nPIEP_PIPER = 'P'\n\ndef count_deaf_rats(town_square):\n rats = []\n piper = None\n for (y, line) in enumerate(town_square):\n for (x, cell) in enumerate(line):\n if cell in Direction:\n rats.append(Rat(Position(x, y), Direction[cell]))\n elif cell == PIEP_PIPER:\n piper = Position(x, y)\n return len([rat for rat in rats if rat.is_deaf(piper)])\n\ndef __init__(x, y):\n self.x = x\n self.y = y\n\ndef distance(other):\n return math.hypot(self.x - other.x, self.y - other.y)\n\ndef __init__(position, move):\n self.position = position\n self.move = move\n\ndef is_deaf(piper):\n current_distance = piper.distance(self.position)\n distance_after_one_step = piper.distance(self.move(self.position))\n return current_distance - distance_after_one_step < 0", "def count_deaf_rats(board):\n (o, p) = next(([i, j] for (i, l) in enumerate(board) for (j, k) in enumerate(l) if board[i][j] == 'P'))\n distance = lambda x, y: ((o - x) ** 2 + (p - y) ** 2) ** 0.5\n d = {'←': (0, -1), '↑': (-1, 0), '→': (0, 1), '↓': (1, 0), '↖': (-1, -1), '↗': (-1, 1), '↘': (1, 1), '↙': (1, -1)}\n return sum((distance(i + d[l][0], k + d[l][1]) > distance(i, k) for (i, j) in enumerate(board) for (k, l) in enumerate(j) if l in '←↑→↓↖↗↘↙'))", "deltas = dict(zip('←↑→↓↖↗↘↙', (-1, -1j, 1, 1j, -1 - 1j, 1 - 1j, 1 + 1j, -1 + 1j)))\n\ndef count_deaf_rats(town_square):\n (ii, jj) = (list(range(len(town_square[0]))), list(range(len(town_square))))\n p = next((complex(i, j) for i in ii for j in jj if town_square[j][i] == 'P'))\n return sum((abs(ij + d - p) > abs(ij - p) for (ij, d) in ((complex(i, j), deltas.get(town_square[j][i], 0)) for j in jj for i in ii)))", "rat_dirs = {'←': (-1, 0), '↑': (0, -1), '→': (1, 0), '↓': (0, 1), '↖': (-1, -1), '↗': (1, -1), '↘': (1, 1), '↙': (-1, 1)}\n\ndef find_piper(town_square, width, height):\n for y in range(height):\n for x in range(width):\n if town_square[y][x] == 'P':\n return (x, y)\n return (-1, -1)\n\ndef is_rat_deaf(rx, ry, px, py, c):\n (dx, dy) = (px - rx, py - ry)\n (cx, cy) = rat_dirs[c]\n return cx * dx + cy * dy <= 0\n\ndef count_deaf_rats(town_square):\n (width, height) = (len(town_square[0]), len(town_square))\n (px, py) = find_piper(town_square, width, height)\n num_deaf = 0\n for y in range(height):\n for x in range(width):\n c = town_square[y][x]\n if c in rat_dirs and is_rat_deaf(x, y, px, py, c):\n num_deaf += 1\n return num_deaf", "def count_deaf_rats(a):\n d = [(i, j) for i in range(-1, 2) for j in range(-1, 2) if i or j]\n d = {x: d[i] for (i, x) in enumerate('↖↑↗←→↙↓↘')}\n (p, r) = (divmod(''.join(a).index('P'), len(a[0])), 0)\n for (i, x) in enumerate(a):\n for (j, y) in enumerate(x):\n if y not in ' P':\n z = d[y]\n n = abs(i - p[0] + (j - p[1]) * 1j)\n m = abs(i + z[0] - p[0] + (j + z[1] - p[1]) * 1j)\n if n < m:\n r += 1\n return r"], "starter_code": "def count_deaf_rats(town_square):\n", "input_output": {"fn_name": "count_deaf_rats", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5c1448e08a2d87eda400005f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "count_deaf_rats", "task_id": "TACO_lite/291", "example": [[["↗P ↘ ↖ ↑ ↗"], ["↗ P ↓ ↖ ↑ ← ↓ ↖ ↙ ↙ ↓ ↓ ↓"]], ["1", "7"]]} +{"requirement": "Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.\n \n\nExample 1:\nInput: A = [4,5,0,-2,-3,1], K = 5\nOutput: 7\nExplanation: There are 7 subarrays with a sum divisible by K = 5:\n[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]\n\n \nNote:\n\n1 <= A.length <= 30000\n-10000 <= A[i] <= 10000\n2 <= K <= 10000", "solutions": ["def subarraysdivbyk(A, K):\n res = 0\n prefix = 0\n count = [1] + [0] * K\n for a in A:\n prefix = (prefix + a) % K\n res += count[prefix]\n count[prefix] += 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n B = [a % K for a in A]\n sum_dict = {}\n ans = 0\n curr_sum = 0\n sum_dict[0] = 1\n n = len(B)\n for (i, num) in enumerate(B):\n curr_sum = (curr_sum + num) % K\n if curr_sum in sum_dict:\n ans += sum_dict[curr_sum]\n sum_dict[curr_sum] = sum_dict.get(curr_sum, 0) + 1\n return ans", "def subarraysdivbyk(A: List[int], K: int) -> int:\n countPrefs = {0: 1}\n total = 0\n res = 0\n for (i, num) in enumerate(A):\n total += num\n res += countPrefs.get(total % K, 0)\n if total % K in countPrefs:\n countPrefs[total % K] += 1\n else:\n countPrefs[total % K] = 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n (res, n, cache, sv) = (0, len(A), collections.defaultdict(int), 0)\n cache[0] = 1\n for (i, v) in enumerate(A):\n sv += v\n if cache[sv % K] > 0:\n res += cache[sv % K]\n cache[sv % K] += 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n n = len(A)\n pre = 0\n res = 0\n d = {0: 1}\n for a in A:\n pre = (pre + a) % K\n res += d.get(pre, 0)\n d[pre] = d.get(pre, 0) + 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n mod_count = Counter({0: 1})\n ans = 0\n for s in [*accumulate(A)]:\n m = s % K\n if m in mod_count:\n ans += mod_count[m]\n mod_count[m] += 1\n return ans", "def subarraysdivbyk(A: List[int], K: int) -> int:\n res = 0\n currsum = 0\n d = Counter()\n d[0] = 1\n for (i, num) in enumerate(A):\n currsum += num\n currsum %= K\n if currsum in d:\n res += d[currsum]\n d[currsum] += 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n res = 0\n cs = 0\n seen = collections.Counter({0: 1})\n for i in range(len(A)):\n x = A[i]\n cs += x\n if cs % K in seen:\n res += seen[cs % K]\n seen[cs % K] += 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n m = defaultdict(int)\n m[0] = 1\n curr_sum = 0\n result = 0\n for a in A:\n curr_sum += a\n remainder = curr_sum % K\n if remainder in m:\n result += m[remainder]\n m[remainder] += 1\n return result", "from collections import defaultdict\n\ndef subarraysdivbyk(A: List[int], K: int) -> int:\n if not A:\n return 0\n prefix_sums = defaultdict(int)\n prefix_sums[0] = 1\n cumsum = 0\n ans = 0\n for (i, x) in enumerate(A):\n cumsum = (cumsum + x) % K\n ans += prefix_sums[cumsum]\n prefix_sums[cumsum] += 1\n return ans", "def subarraysdivbyk(A, K):\n nums = A\n k = K\n modDict = {}\n tempSumn = 0\n ans = 0\n continousSum = []\n for num in nums:\n tempSumn += num\n continousSum.append(tempSumn)\n remain = tempSumn % k\n if remain not in modDict:\n modDict[remain] = 0\n modDict[remain] += 1\n diff = k\n for i in range(0, len(continousSum)):\n if diff % k in modDict:\n ans += modDict[diff % k]\n diff = continousSum[i]\n modDict[diff % k] -= 1\n return ans", "from collections import Counter\n\ndef subarraysdivbyk(A: List[int], K: int) -> int:\n seen = Counter()\n prefix = []\n curr_sum = 0\n for x in A:\n curr_sum += x\n prefix.append(curr_sum % K)\n ans = 0\n for ix in range(len(A)):\n remainder = K - prefix[ix]\n if prefix[ix] in seen:\n ans += seen[prefix[ix]]\n if prefix[ix] == 0:\n ans += 1\n seen[prefix[ix]] += 1\n return ans", "def subarraysdivbyk(A: List[int], K: int) -> int:\n n = len(A)\n A[0] = A[0] % K\n seen = {0: 1}\n count = 0\n for i in range(1, n):\n A[i] = (A[i] + A[i - 1]) % K\n for i in range(n):\n newTarget = (A[i] - K) % K\n if newTarget in seen:\n count += seen[newTarget]\n if A[i] in seen:\n seen[A[i]] += 1\n else:\n seen[A[i]] = 1\n return count", "def subarraysdivbyk(A: List[int], K: int) -> int:\n cnt = Counter([0])\n (pref, ans) = (0, 0)\n for a in A:\n pref = (pref + a) % K\n ans += cnt[pref]\n cnt[pref] += 1\n return ans", "def subarraysdivbyk(A: List[int], K: int) -> int:\n prefix = [0] * len(A)\n prefix[0] = A[0] % K\n counter = Counter([prefix[0]])\n ans = 1 if prefix[0] == 0 else 0\n for i in range(1, len(A)):\n prefix[i] = (prefix[i - 1] + A[i]) % K\n target = prefix[i] - 0\n ans += counter[target]\n if target == 0:\n ans += 1\n counter[prefix[i]] += 1\n return ans", "def subarraysdivbyk(A: List[int], K: int) -> int:\n cumsum = 0\n complements = {0: 1}\n counts = 0\n for a in A:\n cumsum += a\n mods = cumsum % K\n counts += complements.get(mods, 0)\n complements[mods] = complements.get(mods, 0) + 1\n return counts", "def subarraysdivbyk(A: List[int], K: int) -> int:\n ht = [0] * K\n sum = 0\n for num in A:\n sum += num\n ht[sum % K] += 1\n results = ht[0]\n for c in ht:\n results += c * (c - 1) // 2\n return results", "def subarraysdivbyk(A: List[int], K: int) -> int:\n if not A or not K:\n return 0\n map = Counter()\n map[0] = 1\n sum = 0\n res = 0\n for num in A:\n sum += num\n sum %= K\n if sum < 0:\n sum += K\n if sum in map:\n res += map[sum]\n map[sum] += 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n n = len(A)\n prefix = [0] * (n + 1)\n for i in range(1, n + 1):\n prefix[i] = prefix[i - 1] + A[i - 1]\n for i in range(1, n + 1):\n prefix[i] = prefix[i] % K\n d = defaultdict(list)\n ans = 0\n for i in range(1, n + 1):\n if prefix[i] == 0:\n ans += 1\n if prefix[i] in d.keys():\n ans += len(d[prefix[i]])\n d[prefix[i]].append(i)\n return ans", "def subarraysdivbyk(A: List[int], K: int) -> int:\n count = [0] * K\n sum = 0\n for i in A:\n sum += i % K\n count[sum % K] += 1\n result = count[0]\n for j in count:\n result += j * (j - 1) / 2\n return int(result)", "def subarraysdivbyk(A: List[int], K: int) -> int:\n map = {}\n map[0] = 1\n (sum, count) = (0, 0)\n for n in A:\n sum = (sum + n) % K\n if sum not in list(map.keys()):\n map[sum] = 1\n else:\n count += map[sum]\n map[sum] += 1\n return count", "def subarraysdivbyk(A: List[int], K: int) -> int:\n ans = 0\n count = [1] + [0] * K\n prefix = 0\n for num in A:\n prefix = (prefix + num) % K\n ans += count[prefix]\n count[prefix] += 1\n return ans", "import collections\n\ndef subarraysdivbyk(A: List[int], K: int) -> int:\n counts = [0] * K\n total = 0\n for num in A:\n total += num\n counts[total % K] += 1\n result = counts[0]\n for count in counts:\n result += count * (count - 1) // 2\n return result", "def subarraysdivbyk(A: List[int], K: int) -> int:\n (D, s) = ({0: 1}, 0)\n for a in A:\n s = (s + a) % K\n if s in D:\n D[s] += 1\n else:\n D[s] = 1\n return sum((i * (i - 1) // 2 for i in list(D.values())))", "import collections\n\ndef subarraysdivbyk(A: List[int], K: int) -> int:\n rem_array = [0]\n for num in A:\n rem_array.append((num + rem_array[-1]) % K)\n counter = collections.Counter(rem_array)\n return sum((v * (v - 1) // 2 for v in counter.values()))", "from collections import defaultdict\n\ndef subarraysdivbyk(nums: List[int], k: int) -> int:\n count = 0\n mods = [0]\n modFreqs = defaultdict(lambda : 0)\n for num in nums:\n mod = (mods[-1] + num) % k\n if mod == 0:\n count += 1\n count += modFreqs[mod]\n mods.append(mod)\n modFreqs[mod] += 1\n return count", "def subarraysdivbyk(A: List[int], K: int) -> int:\n P = [0]\n for x in A:\n P.append((P[-1] + x) % K)\n count = collections.Counter(P)\n return int(sum((v * (v - 1) / 2 for v in count.values())))", "def subarraysdivbyk(A: List[int], K: int) -> int:\n hash_map = collections.defaultdict(int)\n hash_map[0] = 1\n prefix = 0\n res = 0\n for i in range(len(A)):\n num = A[i]\n prefix = (prefix + num) % K\n res += hash_map[prefix]\n hash_map[prefix] += 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n (arr, ans, curr) = ([1] + [0] * K, 0, 0)\n for i in A:\n curr = (curr + i) % K\n ans += arr[curr]\n arr[curr] += 1\n return ans", "from collections import defaultdict\nfrom operator import add\n\ndef accum(op, l):\n if not l:\n return []\n v = l[0]\n ret = [v]\n for x in l[1:]:\n v = op(v, x)\n ret.append(v)\n return ret\n\ndef subarraysdivbyk(A: List[int], K: int) -> int:\n B = accum(add, A)\n B = [0] + B\n B = [x % K for x in B]\n seen = defaultdict(lambda : 0)\n seen[0] = 1\n combinations = 0\n for s in B[1:]:\n target = s\n if seen[target] > 0:\n combinations += seen[target]\n seen[s] = seen[s] + 1\n return combinations", "def subarraysdivbyk(A: List[int], K: int) -> int:\n hashmap = [0] * K\n hashmap[0] = 1\n result = 0\n prefix = 0\n for i in range(len(A)):\n prefix = (prefix + A[i]) % K\n hashmap[prefix] += 1\n result += hashmap[prefix] - 1\n return result", "def subarraysdivbyk(A: List[int], K: int) -> int:\n dp = [1] + [0] * K\n result = 0\n running_sum = 0\n for num in A:\n running_sum += num\n result += dp[running_sum % K]\n dp[running_sum % K] += 1\n return result", "def subarraysdivbyk(A: List[int], K: int) -> int:\n res = 0\n sums = 0\n d = {0: 1}\n for num in A:\n sums = (sums + num) % K\n res += d.get(sums, 0)\n d[sums] = d.get(sums, 0) + 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n prefix = [0]\n for a in A:\n prefix += [(prefix[-1] + a) % K]\n cnt = collections.Counter(prefix)\n return int(sum((v * (v - 1) / 2 for v in list(cnt.values()))))", "from collections import defaultdict\n\ndef subarraysdivbyk(A: List[int], K: int) -> int:\n seen = defaultdict(int, {0: 1})\n ret = psum = 0\n for n in A:\n psum = (psum + n) % K\n if psum in seen:\n ret += seen[psum]\n seen[psum] += 1\n return ret", "from collections import Counter\n\ndef subarraysdivbyk(A: List[int], K: int) -> int:\n presum = [0]\n for num in A:\n presum.append((presum[-1] + num) % K)\n count = Counter(presum)\n return sum((c * (c - 1) // 2 for c in list(count.values())))", "def subarraysdivbyk(A: List[int], K: int) -> int:\n hm = {}\n hm[0] = 1\n prefix = 0\n count = 0\n for i in range(0, len(A)):\n prefix = (A[i] + prefix) % K\n if prefix in hm:\n count += hm[prefix]\n else:\n hm[prefix] = 0\n hm[prefix] += 1\n return count", "def subarraysdivbyk(A: List[int], K: int) -> int:\n n = len(A)\n prefixsum = 0\n remain = collections.defaultdict(int)\n remain[0] = 1\n res = 0\n for i in range(n):\n prefixsum += A[i]\n re = prefixsum % K\n res += remain[re]\n remain[re] += 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n res = 0\n lookup = {0: 1}\n presum = 0\n for (i, num) in enumerate(A):\n presum += num\n remainder = presum % K\n res += lookup.get(remainder, 0)\n lookup[remainder] = lookup.get(remainder, 0) + 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n P = [0]\n for x in A:\n P.append((P[-1] + x) % K)\n count = collections.Counter(P)\n ans = 0\n for v in list(count.values()):\n ans += int(v * (v - 1) * 0.5)\n return ans", "def subarraysdivbyk(A: List[int], K: int) -> int:\n preSum = [0]\n for num in A:\n preSum.append((preSum[-1] + num) % K)\n preSumCounter = Counter(preSum)\n return sum((v * (v - 1) // 2 for v in preSumCounter.values()))", "def subarraysdivbyk(A: List[int], K: int) -> int:\n d = {0: 1}\n runningSum = 0\n sol = 0\n for i in range(len(A)):\n runningSum += A[i]\n newMod = runningSum % K\n if newMod not in d:\n d[newMod] = 0\n d[newMod] += 1\n sol += d[newMod] - 1\n return sol", "def subarraysdivbyk(A: List[int], K: int) -> int:\n prefixMod = 0\n hashTable = collections.defaultdict(int)\n total = 0\n curSum = 0\n hashTable[0] = 1\n for (i, x) in enumerate(A):\n prefixMod = prefixMod + x\n prefixMod = prefixMod % K\n total += hashTable[prefixMod]\n hashTable[prefixMod] += 1\n return total"], "starter_code": "def subarraysdivbyk(A: List[int], K: int) -> int:\n", "input_output": {"fn_name": "subarraysDivByK", "inputs": [[[4, 5, 0, -2, -3, 1], 5]], "outputs": [7]}, "difficulty": "MEDIUM", "raw_tags": ["Prefix Sum", "Array", "Hash Table"], "name": null, "source": "leetcode", "tags": ["Data structures", "Range queries"], "skill_types": ["Data structures", "Range queries"], "url": "https://leetcode.com/problems/subarray-sums-divisible-by-k/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "subarraysdivbyk", "task_id": "TACO_lite/337", "example": [[[[4, 5, 0, -2, -3, 1], 5]], ["7"]]} +{"requirement": "You get some nested lists. Keeping the original structures, sort only elements (integers) inside of the lists. In other words, sorting the intergers only by swapping their positions. \n\n\n\n```\nExample\nInput : [[[2, 1], [4, 3]], [[6, 5], [8, 7]]]\nOutput : [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]\n```\n\nNote:\nThe structures of the lists are regular (symmetrical) and their depths are 3.", "solutions": ["def sort_nested_list(xsss):\n ys = iter(sorted((x for xss in xsss for xs in xss for x in xs)))\n return [[[next(ys) for x in xs] for xs in xss] for xss in xsss]", "import numpy as np\n\ndef sort_nested_list(A):\n return np.sort(A, axis=None).reshape(np.array(A).shape).tolist()", "def sort_nested_list(array):\n numbers = iter(sorted((n for a1 in array for a2 in a1 for n in a2)))\n return [[[next(numbers) for n in a2] for a2 in a1] for a1 in array]", "def sort_nested_list(A):\n numbers = []\n\n def peel(A, insert=False):\n for i in range(len(A)):\n if len(A[i]) != 0 and isinstance(A[i][0], list):\n A[i] = peel(A[i], insert)\n elif insert:\n A[i] = numbers[:len(A[i])]\n del numbers[:len(A[i])]\n else:\n numbers.extend(A[i])\n return A\n peel(A)\n numbers = sorted(numbers)\n return peel(A, insert=True)", "import re\n\ndef sort_nested_list(arr):\n s = str(arr)\n ns = sorted(re.findall('\\\\d+', s), key=int, reverse=True)\n return eval(re.sub('\\\\d+', lambda _: ns.pop(), s))", "def sort_nested_list(A, emol=''):\n for e in str(A):\n if e.isdigit() and emol[-1] is '}':\n continue\n emol += [e, '{}'][e.isdigit()]\n return eval(emol.format(*sorted([i for l in A for e in l for i in e])))", "def fl(l):\n for x in l:\n if isinstance(x, list):\n for j in fl(x):\n yield j\n else:\n yield x\n\ndef sort_nested_list(a):\n numbers = iter(sorted(fl(a)))\n\n def b(n, a):\n return [next(n) if isinstance(c, int) else b(n, c) for c in a]\n return b(numbers, a)", "from copy import deepcopy\n\ndef sort_nested_list(a):\n\n def seeker(lst):\n return lst if not lst or not isinstance(lst[0], list) else sum(map(seeker, lst), [])\n\n def putter(lst):\n for i in range(len(lst)):\n if isinstance(lst[i], list):\n putter(lst[i])\n else:\n lst[i] = next(elts)\n (a, elts) = (deepcopy(a), iter(sorted(seeker(a))))\n putter(a)\n return a", "import re\n\ndef sort_nested_list(A):\n a = str(A)\n (b, a) = (a, re.sub('\\\\[|\\\\]', '', a))\n B = str(sorted(eval('[' + a + ']')))\n (b, nl) = (list(re.sub('\\\\d+', '#', b)), re.findall('\\\\d+', B)[::-1])\n for i in range(len(b)):\n b[i] = nl.pop() if b[i] == '#' else b[i]\n return eval(''.join(b))", "def sort_nested_list(A):\n sort_nested_list.numbers = []\n\n def collect_numbers(lista):\n if len(lista) == 0:\n return lista\n if len(lista) > 1:\n for i in lista:\n try:\n for e in i:\n for q in e:\n sort_nested_list.numbers.append(q)\n except:\n return sorted(lista)\n return lista\n else:\n return [collect_numbers(lista[0])]\n\n def place_numbers(lista):\n if len(lista) == 0:\n return lista\n if len(lista) > 1:\n for i in lista:\n try:\n for e in i:\n for (index, element) in enumerate(e):\n e[index] = sort_nested_list.numbers.pop(0)\n except:\n return sorted(lista)\n return lista\n else:\n return [place_numbers(lista[0])]\n collect_numbers(A)\n sort_nested_list.numbers.sort()\n return place_numbers(A)"], "starter_code": "def sort_nested_list(A):\n", "input_output": {"fn_name": "sort_nested_list", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Fundamentals", "Sorting"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Sorting"], "skill_types": ["Sorting"], "url": "https://www.codewars.com/kata/5a4bdd73d8e145f17d000035", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sort_nested_list", "task_id": "TACO_lite/322", "example": [[[[[[2, 1], [4, 3]], [[6, 5], [8, 7]]]]], ["[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]"]]} +{"requirement": "Given an unsorted array of integers. Find an element such that all the elements to its left are smaller and to its right are greater. Print -1 if no such element exists. Note that there can be more than one such element. In that case print the first such number occurring in the array.\nExample 1:\nInput: N = 7, arr[] = {4, 3, 2, 5, 8, 6, 7} \nOutput: 5\nExplanation: To the left of element 5 \nevery element is smaller to it and to \nthe right of element 5 every element \nis greater to it. \nExample 2:\nInput: N = 7, arr[] = {5, 6, 2, 8, 10, 9, 8} \nOutput: -1\nExplanation: No such desired element is \npresent in the array.\nYour Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function FindElement() that takes array arr and integer N as parameters and returns the desired output.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 ≤ N ≤ 10^{6}", "solutions": ["def findelement(arr, N):\n c = 0\n for i in range(N):\n c = 0\n for j in range(N):\n if j < i:\n if arr[j] >= arr[i]:\n c = 1\n break\n elif j == i:\n pass\n elif j > i:\n if arr[j] <= arr[i]:\n c = 1\n break\n if c == 0:\n return arr[i]\n break\n return -1", "def findelement(arr, N):\n max_ele = arr[0]\n li = [max_ele]\n for i in range(1, N):\n if max_ele >= arr[i]:\n if len(li) > 0:\n if li[0] >= arr[i]:\n li.clear()\n else:\n max_ele = arr[i]\n li.append(arr[i])\n return li[0] if len(li) > 0 else -1", "def findelement(arr, N):\n small_right = [0] * n\n big_left = [0] * n\n big_left[0] = arr[0]\n small_right[n - 1] = arr[n - 1]\n for i in range(1, n):\n if big_left[i - 1] < arr[i]:\n big_left[i] = arr[i]\n else:\n big_left[i] = big_left[i - 1]\n for i in range(n - 2, -1, -1):\n if small_right[i + 1] > arr[i]:\n small_right[i] = arr[i]\n else:\n small_right[i] = small_right[i + 1]\n for i in range(0, N, 1):\n if i == 0 and arr[i] < small_right[i + 1] or (i == N - 1 and arr[i] > big_left[i - 1]) or (arr[i] > big_left[i - 1] and arr[i] < small_right[i + 1]):\n return arr[i]\n break\n return -1", "def findelement(arr, N):\n A = arr\n n = N\n SE = [0] * n\n GE = [0] * n\n GE[0] = A[0]\n SE[n - 1] = A[n - 1]\n for i in range(1, n):\n if GE[i - 1] < A[i]:\n GE[i] = A[i]\n else:\n GE[i] = GE[i - 1]\n for i in range(n - 2, -1, -1):\n if A[i] < SE[i + 1]:\n SE[i] = A[i]\n else:\n SE[i] = SE[i + 1]\n for j in range(n):\n try:\n if j == 0 and A[j] < SE[j + 1] or (j == n - 1 and A[j] > GE[j - 1]) or (A[j] < SE[j + 1] and A[j] > GE[j - 1]):\n return A[j]\n except:\n pass\n return -1", "def findelement(arr, N):\n maxi = [arr[0]]\n mini = [arr[-1]]\n for i in range(1, N):\n maxi.append(max(maxi[-1], arr[i]))\n mini.append(min(mini[-1], arr[-i - 1]))\n mini.reverse()\n if arr[0] < mini[1]:\n return arr[0]\n for i in range(1, N - 1):\n if maxi[i - 1] < arr[i] < mini[i + 1]:\n return arr[i]\n if arr[-1] > maxi[-2]:\n return arr[-1]\n return -1", "def findelement(arr, n):\n greather = [0] * n\n smaller = [0] * n\n greather[0] = arr[0]\n for i in range(1, n):\n greather[i] = max(greather[i - 1], arr[i])\n smaller[n - 1] = arr[n - 1]\n for i in range(n - 2, -1, -1):\n smaller[i] = min(smaller[i + 1], arr[i])\n if smaller[1] > arr[0]:\n return arr[0]\n for i in range(1, n - 1):\n if smaller[i + 1] > arr[i] and greather[i - 1] < arr[i]:\n return arr[i]\n if greather[n - 2] < arr[n - 1]:\n return arr[n - 1]\n return -1", "import sys\n\ndef findelement(arr, N):\n min_index = [0] * N\n max_index = [0] * N\n minimum = arr[N - 1]\n min_index[N - 1] = N - 1\n maximum = arr[0]\n max_index[0] = 0\n ans = -1\n for i in range(1, N):\n if arr[i] > maximum:\n max_index[i] = i\n maximum = arr[i]\n else:\n max_index[i] = max_index[i - 1]\n for i in range(N - 2, -1, -1):\n if arr[i] < minimum:\n minimum = arr[i]\n min_index[i] = i\n else:\n min_index[i] = min_index[i + 1]\n for i in range(N):\n if min_index[i] == max_index[i]:\n ans = arr[i]\n break\n return ans", "import sys\n\ndef findelement(arr, n):\n pre = [0] * n\n suf = [0] * n\n pre[0] = -sys.maxsize\n suf[n - 1] = sys.maxsize\n for i in range(1, n):\n pre[i] = max(pre[i - 1], arr[i - 1])\n for i in range(n - 2, -1, -1):\n suf[i] = min(suf[i + 1], arr[i + 1])\n for i in range(n):\n if pre[i] < arr[i] and arr[i] < suf[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n (mx, mi, cur_max) = ([0 for i in range(n)], [0 for i in range(n)], -1)\n for i in range(0, n):\n mx[i] = cur_max\n cur_max = max(cur_max, arr[i])\n cur_min = cur_max + 1\n for i in range(n - 1, -1, -1):\n mi[i] = cur_min\n cur_min = min(cur_min, arr[i])\n if arr[0] < mi[0]:\n return arr[0]\n for i in range(1, n - 1):\n if mx[i] < arr[i] < mi[i]:\n return arr[i]\n if arr[-1] > mx[-1]:\n return arr[-1]\n return -1", "def findelement(arr, n):\n for i in range(0, n):\n (left, right) = (1, 1)\n for j in range(0, i):\n if arr[j] >= arr[i]:\n left = 0\n break\n if left == 0:\n continue\n for j in range(i + 1, n):\n if arr[j] <= arr[i]:\n right = 0\n break\n if right == 1:\n return arr[i]\n return -1", "def findelement(arr, N):\n left = []\n right = []\n maximum = arr[0]\n for i in arr:\n maximum = max(i, maximum)\n left.append(maximum)\n minimum = arr[-1]\n for i in arr[::-1]:\n minimum = min(i, minimum)\n right.append(minimum)\n right = right[::-1]\n if arr[0] < right[1]:\n return arr[0]\n ans = -1\n for i in range(1, N - 1):\n if arr[i] > left[i - 1] and arr[i] < right[i + 1]:\n ans = arr[i]\n break\n if ans != -1:\n return ans\n if left[-2] < arr[-1]:\n return arr[-1]\n return -1", "def findelement(arr, N):\n ge = [0] * N\n se = [0] * N\n ge[0] = arr[0]\n se[N - 1] = arr[N - 1]\n for i in range(1, N):\n if arr[i] > ge[i - 1]:\n ge[i] = arr[i]\n else:\n ge[i] = ge[i - 1]\n for i in range(N - 2, -1, -1):\n if arr[i] < se[i + 1]:\n se[i] = arr[i]\n else:\n se[i] = se[i + 1]\n for i in range(N):\n if i == 0 and se[i + 1] > arr[i]:\n return arr[i]\n elif i == N - 1 and arr[N - 1] > ge[i - 1]:\n return arr[i]\n elif arr[i] > ge[i - 1] and arr[i] < se[i + 1]:\n return arr[i]\n return -1", "def findelement(arr, N):\n mx = arr[N - 1] + 1\n amx = [0] * N\n mn = arr[0] - 1\n amn = [0] * N\n if arr[0] >= arr[N - 1]:\n return -1\n for i in range(N):\n amx[N - 1 - i] = mx\n if mx > arr[N - 1 - i]:\n mx = arr[N - 1 - i]\n amn[i] = mn\n if mn < arr[i]:\n mn = arr[i]\n for i in range(N):\n if amx[i] > arr[i] and arr[i] > amn[i]:\n return arr[i]\n return -1", "def findelement(arr, N):\n prefix = [-1000000000]\n suffix = [10000000 for i in range(N)]\n for i in range(1, N):\n prefix.append(max(prefix[i - 1], arr[i - 1]))\n for i in range(N - 2, -1, -1):\n suffix[i] = min(suffix[i + 1], arr[i + 1])\n for i in range(0, N):\n if prefix[i] < arr[i] and arr[i] < suffix[i]:\n return arr[i]\n return -1", "def findelement(arr, N):\n GE = [0] * N\n SE = [0] * N\n GE[0] = arr[0]\n SE[N - 1] = arr[N - 1]\n for i in range(1, N):\n if arr[i] < GE[i - 1]:\n GE[i] = GE[i - 1]\n else:\n GE[i] = arr[i]\n for i in range(N - 2, -1, -1):\n if arr[i] > SE[i + 1]:\n SE[i] = SE[i + 1]\n else:\n SE[i] = arr[i]\n for j in range(N):\n k = arr[j]\n if j == 0:\n if arr[j] < SE[j + 1]:\n return k\n elif j == N - 1:\n if arr[j] > GE[j - 1]:\n return k\n elif arr[j] < SE[j + 1] and arr[j] > GE[j - 1]:\n return k\n return -1", "def findelement(arr, N):\n maxLeft = []\n minRight = []\n for i in range(N):\n if not maxLeft:\n maxLeft.append(arr[i])\n minRight.append(arr[N - i - 1])\n else:\n maxLeft.append(max(maxLeft[-1], arr[i]))\n minRight.append(min(minRight[-1], arr[N - i - 1]))\n for i in range(N):\n if i == 0:\n if arr[i] < minRight[N - i - 2]:\n return arr[i]\n elif i == N - 1:\n if arr[i] > maxLeft[i - 1]:\n return arr[i]\n elif maxLeft[i - 1] < arr[i] and arr[i] < minRight[N - i - 2]:\n return arr[i]\n return -1", "def findelement(arr, N):\n n = N\n GEL = [0] * n\n SER = [0] * n\n GEL[0] = arr[0]\n SER[n - 1] = arr[n - 1]\n for i in range(1, n):\n if arr[i] > GEL[i - 1]:\n GEL[i] = arr[i]\n else:\n GEL[i] = GEL[i - 1]\n for i in range(n - 2, -1, -1):\n if SER[i + 1] > arr[i]:\n SER[i] = arr[i]\n else:\n SER[i] = SER[i + 1]\n for i in range(0, n - 1):\n if i == 0 and arr[i] < SER[i + 1] or (arr[i] < SER[i + 1] and arr[i] > GEL[i - 1]):\n return arr[i]\n if arr[n - 1] > GEL[n - 2]:\n return arr[n - 1]\n else:\n return -1"], "starter_code": "def findelement(arr, N):\n", "input_output": {"inputs": ["N = 7, arr[] = {4, 3, 2, 5, 8, 6, 7}", "N = 7, arr[] = {5, 6, 2, 8, 10, 9, 8}"], "outputs": ["5", "-1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/partition-point-in-the-array0004/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "findelement", "task_id": "TACO_lite/330", "example": [[[7, [4, 3, 2, 5, 8, 6, 7]], [7, [5, 6, 2, 8, 10, 9, 8]]], ["5", "-1"]]} +{"requirement": "Given a matrix M of n*n size, the task is to complete the function which prints its elements in a diagonal pattern as depicted below.\n \n \nExample 1:\nInput:\nN = 3\nmat[][] = {{1 2 3},{4 5 6},{7 8 9}}\nOutput: 1 2 4 7 5 3 6 8 9\nExample 2:\nInput:\nN = 2\nmat[][] = {{1 2},{3 4}}\nOutput: 1 2 3 4\nYour Task:\nYou only need to implement the given function matrixDiagonally() which returns a list containing the matrix diagonally. Do not read input, instead use the arguments given in the function. Print the elements in Matrix in a diagonal pattern.\nExpected Time Complexity: O(N*M)\nExpected Auxiliary Space: O(1)\nConstraints:\n1<=N<=100", "solutions": ["def matrixdiagonally(mat):\n n = len(mat)\n m = len(mat[0])\n list = [[] for i in range(n + m - 1)]\n for i in range(n):\n for j in range(m):\n sum = i + j\n if sum % 2 == 0:\n list[sum].insert(0, mat[i][j])\n else:\n list[sum].append(mat[i][j])\n res = []\n for i in list:\n for j in i:\n res.append(j)\n return res", "def matrixdiagonally(mat):\n n = len(mat)\n total = n * n - 1\n count = 0\n arr = []\n di = {'up': 'down', 'down': 'up'}\n cdi = 'up'\n i = j = 0\n while count <= total:\n if cdi == 'up':\n if i == 0 and j != n - 1:\n arr.append(mat[i][j])\n cdi = di['up']\n j += 1\n elif j == n - 1:\n arr.append(mat[i][j])\n cdi = di['up']\n i += 1\n else:\n arr.append(mat[i][j])\n i -= 1\n j += 1\n elif j == 0 and i != n - 1:\n arr.append(mat[i][j])\n cdi = di['down']\n i += 1\n elif i == n - 1:\n arr.append(mat[i][j])\n cdi = di['down']\n j += 1\n else:\n arr.append(mat[i][j])\n i += 1\n j -= 1\n count += 1\n return arr", "def matrixdiagonally(mat):\n rev = True\n i = j = 0\n n = len(mat)\n res = []\n while i >= 0 and i < n and (j >= 0) and (j < n):\n if rev:\n (pi, pj) = (i, j)\n while i >= 0 and i < n and (j >= 0) and (j < n):\n res.append(mat[i][j])\n (pi, pj) = (i, j)\n i -= 1\n j += 1\n (i, j) = (pi, pj)\n if j == n - 1:\n i += 1\n else:\n j += 1\n else:\n (pi, pj) = (i, j)\n while i >= 0 and i < n and (j >= 0) and (j < n):\n res.append(mat[i][j])\n (pi, pj) = (i, j)\n i += 1\n j -= 1\n (i, j) = (pi, pj)\n if i == n - 1:\n j += 1\n else:\n i += 1\n rev = not rev\n return res", "def matrixdiagonally(mat):\n dic = {i: [] for i in range(len(mat) * len(mat) + 1)}\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n dic[i + j].append(mat[i][j])\n ans = []\n for i in range(len(mat) * len(mat) + 1):\n if i % 2 == 0:\n ans += dic[i][::-1]\n else:\n ans += dic[i]\n return ans", "def matrixdiagonally(mat):\n m = len(mat)\n n = len(mat[0])\n ll = []\n cnt = 1\n for i in range(n):\n x = 0\n y = i\n l = []\n while (x >= 0 and y >= 0) and (x < m and y < n):\n l.append(mat[x][y])\n x += 1\n y -= 1\n if cnt % 2 == 0:\n ll += l\n else:\n ll += l[::-1]\n cnt += 1\n for i in range(1, m):\n x = i\n y = n - 1\n l = []\n while (x >= 0 and y >= 0) and (x < m and y < n):\n l.append(mat[x][y])\n x += 1\n y -= 1\n if cnt % 2 == 0:\n ll += l\n else:\n ll += l[::-1]\n cnt += 1\n return ll", "def matrixdiagonally(mat):\n N = len(mat)\n ls = []\n d_up = True\n r = 0\n c = 0\n while r < N and c < N:\n if d_up:\n while r > 0 and c < N - 1:\n ls.append(mat[r][c])\n r -= 1\n c += 1\n ls.append(mat[r][c])\n if c == N - 1:\n r += 1\n else:\n c += 1\n else:\n while c > 0 and r < N - 1:\n ls.append(mat[r][c])\n c -= 1\n r += 1\n ls.append(mat[r][c])\n if r == N - 1:\n c += 1\n else:\n r += 1\n d_up = not d_up\n return ls", "def matrixdiagonally(mat):\n n = len(mat)\n m = []\n i = 0\n j = 0\n k = 0\n isUp = True\n while k < n * n:\n if isUp:\n while i >= 0 and j < n:\n m.append(mat[i][j])\n k += 1\n j += 1\n i -= 1\n if i < 0 and j <= n - 1:\n i = 0\n if j == n:\n i = i + 2\n j -= 1\n else:\n while j >= 0 and i < n:\n m.append(mat[i][j])\n k += 1\n i += 1\n j -= 1\n if j < 0 and i <= n - 1:\n j = 0\n if i == n:\n j = j + 2\n i -= 1\n isUp = not isUp\n return m", "def matrixdiagonally(mat):\n t = []\n N = len(mat)\n A = mat\n for i in range(N):\n row = 0\n col = i\n while row < N and col >= 0:\n if (row + col) % 2 != 0:\n t.append(A[row][col])\n else:\n t.append(A[col][row])\n row += 1\n col -= 1\n for j in range(1, N):\n row = j\n col = N - 1\n while row < N and col >= 0:\n if (row + col) % 2 != 0:\n t.append(A[row][col])\n else:\n t.append(A[col][row])\n row += 1\n col -= 1\n return t", "def matrixdiagonally(mat):\n output = []\n n = len(mat)\n for i in range(n):\n items = []\n for j in range(i + 1):\n items.append(mat[j][i - j])\n if i % 2:\n output += items\n else:\n output += items[::-1]\n for i in range(1, n):\n items = []\n for j in range(i, n):\n items.append(mat[j][n - j + i - 1])\n if (n + i) % 2:\n output += items[::-1]\n else:\n output += items\n return output", "from collections import defaultdict\n\ndef matrixdiagonally(mat):\n d = defaultdict(list)\n visited = set()\n q = [((0, 0), 0)]\n n = len(mat)\n while q:\n (node, lvl) = q.pop(0)\n (i, j) = node\n d[lvl].append(mat[i][j])\n if i + 1 < n and (i + 1, j) not in visited:\n visited.add((i + 1, j))\n q.append(((i + 1, j), lvl + 1))\n if j + 1 < n and (i, j + 1) not in visited:\n visited.add((i, j + 1))\n q.append(((i, j + 1), lvl + 1))\n x = []\n for i in range(len(d)):\n p = d[i]\n if i % 2 == 1:\n p = p[::-1]\n for j in p:\n x.append(j)\n return x", "def matrixdiagonally(mat):\n if len(mat) == 0:\n return []\n m = len(mat)\n n = len(mat[0])\n row = 0\n col = 0\n res = []\n isUp = True\n while row < m and col < n:\n if isUp:\n while row > 0 and col < n - 1:\n res.append(mat[row][col])\n row -= 1\n col += 1\n res.append(mat[row][col])\n if col == n - 1:\n row += 1\n else:\n col += 1\n else:\n while row < m - 1 and col > 0:\n res.append(mat[row][col])\n row += 1\n col -= 1\n res.append(mat[row][col])\n if row == m - 1:\n col += 1\n else:\n row += 1\n isUp = not isUp\n return res", "def matrixdiagonally(mat):\n r = c = len(mat)\n res = [[] for i in range(c + r - 1)]\n for i in range(r):\n for j in range(c):\n s = i + j\n if s % 2 == 0:\n res[s].insert(0, mat[i][j])\n else:\n res[s].append(mat[i][j])\n return sum(res, [])", "def matrixdiagonally(mat):\n m = len(mat)\n n = len(mat[0])\n k = 0\n retarray = []\n boolval = True\n for i in range(n):\n l = i\n if not boolval:\n while k <= i:\n retarray.append(mat[k][l])\n k += 1\n l -= 1\n k = 0\n boolval = not boolval\n else:\n while k <= i:\n retarray.append(mat[l][k])\n k += 1\n l -= 1\n k = 0\n boolval = not boolval\n k = n - 1\n for i in range(1, n):\n l = i\n if boolval:\n while l < n:\n retarray.append(mat[k][l])\n k -= 1\n l += 1\n k = n - 1\n boolval = not boolval\n else:\n while l < n:\n retarray.append(mat[l][k])\n k -= 1\n l += 1\n k = n - 1\n boolval = not boolval\n return retarray", "def matrixdiagonally(mat):\n rows = colm = len(mat)\n ans = [[] for i in range(rows + colm - 1)]\n for i in range(rows):\n for j in range(colm):\n ij = i + j\n if ij & 1 != 1:\n ans[ij].insert(0, mat[i][j])\n else:\n ans[ij].append(mat[i][j])\n return sum(ans, [])", "def matrixdiagonally(li):\n n = len(li)\n ans = [[] for i in range(n + n - 1)]\n j = 0\n for i in range(n):\n x = i\n y = j\n while x >= 0 and y < n:\n ans[i + j].append(li[x][y])\n x -= 1\n y += 1\n j = n - 1\n for i in range(1, n):\n x = i\n y = j\n while x < n and y >= 0:\n ans[i + j].append(li[y][x])\n x += 1\n y -= 1\n output = []\n for i in range(len(ans)):\n if i % 2 != 0:\n for j in range(len(ans[i]) - 1, -1, -1):\n output.append(ans[i][j])\n else:\n for j in range(len(ans[i])):\n output.append(ans[i][j])\n return output", "def matrixdiagonally(mat):\n (r, c) = (0, 0)\n isUp = True\n count = 0\n n = len(mat)\n ans = []\n while count < n * n:\n if isUp:\n while r >= 0 and c < n:\n ans.append(mat[r][c])\n r -= 1\n c += 1\n count += 1\n if r < 0 and c < n:\n r = 0\n if c == n:\n r += 2\n c -= 1\n else:\n while c >= 0 and r < n:\n ans.append(mat[r][c])\n r += 1\n c -= 1\n count += 1\n if c < 0 and r < n:\n c = 0\n if r == n:\n c += 2\n r -= 1\n isUp = not isUp\n return ans", "def matrixdiagonally(mat):\n n = len(matrix)\n mode = 0\n it = 0\n lower = 0\n temp = []\n for t in range(2 * n - 1):\n t_ = t\n if t_ >= n:\n mode += 1\n t_ = n - 1\n it -= 1\n lower += 1\n else:\n lower = 0\n it += 1\n for i in range(t_, lower - 1, -1):\n this = t_ + lower - i\n if (t_ + mode) % 2 == 0:\n temp.append(matrix[i][this])\n else:\n temp.append(matrix[this][i])\n return temp", "def matrixdiagonally(mat):\n n = len(mat)\n k = 0\n i = 0\n j = 0\n flag = True\n result = []\n while k < n * n:\n if flag:\n while i >= 0 and j < n:\n result.append(mat[i][j])\n i -= 1\n j += 1\n k += 1\n if i < 0 and j <= n - 1:\n i = 0\n if j == n:\n i += 2\n j -= 1\n else:\n while j >= 0 and i < n:\n result.append(mat[i][j])\n j -= 1\n i += 1\n k += 1\n if j < 0 and i <= n - 1:\n j = 0\n if i == n:\n j += 2\n i -= 1\n flag = not flag\n return result", "def matrixdiagonally(mat):\n (row, column) = (len(mat), len(mat[0]))\n arr = []\n for i in range(row):\n diag = []\n a = i\n j = 0\n while a >= 0 and j < column:\n diag.append(mat[a][j])\n a -= 1\n j += 1\n arr.append(diag)\n for j in range(1, column):\n diag = []\n a = j\n i = row - 1\n while a < column and i >= 0:\n diag.append(mat[i][a])\n i -= 1\n a += 1\n arr.append(diag)\n for i in range(1, len(arr), 2):\n arr[i] = arr[i][::-1]\n return [x for y in arr for x in y]", "def matrixdiagonally(mat):\n l = []\n n = len(mat)\n c = 1\n for i in range(n):\n k = i\n j = 0\n g = []\n while k >= 0:\n g.append(mat[j][k])\n k -= 1\n j += 1\n if c == 0:\n l.extend(g)\n else:\n l.extend(g[::-1])\n c = c ^ 1\n for i in range(1, n):\n k = i\n j = n - 1\n g = []\n while k < n:\n g.append(mat[k][j])\n k += 1\n j -= 1\n if c == 0:\n l.extend(g)\n else:\n l.extend(g[::-1])\n c = c ^ 1\n return l", "def level_range(a, b, arr):\n ans = []\n for i in range(b - a + 1):\n ans.append(arr[a + i][b - i])\n return ans\n\ndef get_range(n):\n initials = []\n for i in range(n):\n initials.append((0, i))\n for i in range(1, n):\n initials.append((i, n - 1))\n return initials\n\ndef matrixdiagonally(mat):\n initials = get_range(len(mat))\n ans = []\n lvl = 0\n for i in initials:\n (a, b) = i\n temp = level_range(a, b, mat)\n if lvl % 2 == 0:\n ans += temp[::-1]\n else:\n ans += temp\n lvl += 1\n return ans", "def matrixdiagonally(mat):\n dic = {}\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n t = i + j\n if t not in dic:\n dic[t] = []\n dic[t].append(mat[i][j])\n res = []\n for k in dic:\n if k % 2 == 0:\n res.extend(dic[k][::-1])\n else:\n res.extend(dic[k])\n return res", "def matrixdiagonally(mat):\n mp = dict()\n n = len(mat)\n for i in range(n):\n for j in range(n):\n if i + j in mp:\n mp[i + j].append(mat[i][j])\n else:\n mp[i + j] = [mat[i][j]]\n lst = []\n for (k, v) in mp.items():\n if k % 2 == 0:\n v.reverse()\n lst = lst + v\n else:\n lst = lst + v\n return lst", "def matrixdiagonally(mat):\n n = len(mat)\n s = [[] for i in range(2 * n - 1)]\n for i in range(n):\n for j in range(n):\n m = i + j\n if m % 2 == 1:\n s[m].append(mat[i][j])\n else:\n s[m].insert(0, mat[i][j])\n l = []\n for i in s:\n l.extend(i)\n return l", "def matrixdiagonally(mat):\n out = []\n (i, j) = (0, 0)\n up = True\n n = len(mat)\n while i < n and j < n:\n if up:\n while i > 0 and j < n - 1:\n out.append(mat[i][j])\n i -= 1\n j += 1\n out.append(mat[i][j])\n if j == n - 1:\n i += 1\n else:\n j += 1\n else:\n while j > 0 and i < n - 1:\n out.append(mat[i][j])\n j -= 1\n i += 1\n out.append(mat[i][j])\n if i == n - 1:\n j += 1\n else:\n i += 1\n up = not up\n return out", "def matrixdiagonally(mat):\n if not mat or not mat[0]:\n return []\n (N, M) = (len(mat), len(mat[0]))\n (row, column) = (0, 0)\n direction = 1\n result = []\n while row < N and column < M:\n result.append(mat[row][column])\n new_row = row + (-1 if direction == 1 else 1)\n new_column = column + (1 if direction == 1 else -1)\n if new_row < 0 or new_row == N or new_column < 0 or (new_column == M):\n if direction:\n row += column == M - 1\n column += column < M - 1\n else:\n column += row == N - 1\n row += row < N - 1\n direction = 1 - direction\n else:\n row = new_row\n column = new_column\n return result", "def matrixdiagonally(mat):\n n = len(mat[0])\n if n == 1:\n return mat[0]\n ans = []\n for e in range(n):\n r = e\n c = 0\n temp = []\n for x in range(e + 1):\n temp.append(mat[r][c])\n r -= 1\n c += 1\n if e % 2 == 1:\n temp.reverse()\n ans = ans + temp\n cl = 1\n for e in range(n - 1, 0, -1):\n r = n - 1\n c = cl\n temp = []\n for x in range(e):\n temp.append(mat[r][c])\n r -= 1\n c += 1\n if e % 2 == 0:\n temp.reverse()\n ans = ans + temp\n cl += 1\n return ans", "from collections import deque\n\ndef matrixdiagonally(mat):\n n = len(mat)\n i = 0\n j = 0\n k = 0\n up = True\n res = deque()\n while k < n * n:\n if up:\n while i >= 0 and j < n:\n res.append(mat[i][j])\n i -= 1\n j += 1\n k += 1\n if i < 0 and j <= n - 1:\n i = 0\n if j == n:\n i += 2\n j -= 1\n else:\n while j >= 0 and i < n:\n res.append(mat[i][j])\n i += 1\n j -= 1\n k += 1\n if j < 0 and i <= n - 1:\n j = 0\n if i == n:\n j += 2\n i -= 1\n up = not up\n return res", "def matrixdiagonally(n, mat):\n result = []\n rows = len(mat)\n cols = len(mat[0])\n num_of_diags = rows + cols - 1\n for diag in range(num_of_diags):\n if diag % 2 == 0:\n i = min([diag, rows - 1])\n j = diag - i\n while i > -1 and j < cols:\n result.append(mat[i][j])\n i -= 1\n j += 1\n else:\n j = min([diag, cols - 1])\n i = diag - j\n while j > -1 and i < rows:\n result.append(mat[i][j])\n i += 1\n j -= 1\n return result", "def matrixdiagonally(mat):\n i = 0\n j = 0\n counter = 0\n isUp = True\n n = len(mat)\n result = []\n while counter < n * n:\n if isUp:\n while i >= 0 and j < n:\n result.append(mat[i][j])\n counter += 1\n j += 1\n i -= 1\n if i < 0 and j <= n - 1:\n i = 0\n if j == n:\n i = i + 2\n j -= 1\n else:\n while j >= 0 and i < n:\n result.append(mat[i][j])\n counter += 1\n i += 1\n j -= 1\n if j < 0 and i <= n - 1:\n j = 0\n if i == n:\n j = j + 2\n i -= 1\n isUp = not isUp\n return result", "def __init__():\n self.r = []\n self.n = 0\n\ndef matrixdiagonally(a):\n self.r = []\n self.n = len(a)\n self.traverseDiagonalUp(a, 0, 0)\n return self.r\n\ndef traverseDiagonalUp(a, x, y):\n i = x\n j = y\n while self.n > j > -1 and -1 < i < self.n:\n self.r.append(a[i][j])\n i -= 1\n j += 1\n if j == self.n:\n self.traverseDiagonalDown(a, i + 2, j - 1)\n elif i == -1:\n self.traverseDiagonalDown(a, i + 1, j)\n\ndef traverseDiagonalDown(a, x, y):\n i = x\n j = y\n while self.n > j > -1 and -1 < i < self.n:\n self.r.append(a[i][j])\n i += 1\n j -= 1\n if i == self.n:\n self.traverseDiagonalUp(a, i - 1, j + 2)\n elif j == -1:\n self.traverseDiagonalUp(a, i, j + 1)", "def matrixdiagonally(mat):\n res = []\n i = 0\n row = 0\n col = 0\n flag = True\n n = len(mat)\n while row < n and col < n:\n if flag:\n while row > 0 and col < n - 1:\n res.append(mat[row][col])\n row -= 1\n col += 1\n res.append(mat[row][col])\n if col == n - 1:\n row += 1\n else:\n col += 1\n else:\n while col > 0 and row < n - 1:\n res.append(mat[row][col])\n row += 1\n col -= 1\n res.append(mat[row][col])\n if row == n - 1:\n col += 1\n else:\n row += 1\n flag = not flag\n return res", "def matrixdiagonally(mat):\n dia = []\n n = len(mat)\n sum = 0\n while sum <= 2 * (n - 1):\n if sum < n:\n a = sum\n b = 0\n while a >= 0:\n if sum % 2 == 0:\n dia.append(mat[a][b])\n else:\n dia.append(mat[b][a])\n a -= 1\n b += 1\n else:\n a = n - 1\n b = sum - n + 1\n while a >= sum - n + 1:\n if sum % 2 == 0:\n dia.append(mat[a][b])\n else:\n dia.append(mat[b][a])\n a -= 1\n b += 1\n sum += 1\n return dia", "def matrixdiagonally(mat):\n returnArray = []\n rowNumber = 0\n colNumber = 0\n numRowsCols = len(mat)\n isUp = True\n stop = False\n returnArray.append(mat[rowNumber][colNumber])\n while not stop:\n while not isUp:\n if rowNumber + 1 < numRowsCols and colNumber - 1 > -1:\n rowNumber += 1\n colNumber -= 1\n elif rowNumber + 1 < numRowsCols:\n rowNumber += 1\n isUp = True\n elif colNumber + 1 < numRowsCols:\n colNumber += 1\n isUp = True\n returnArray.append(mat[rowNumber][colNumber])\n while isUp:\n if rowNumber - 1 > -1 and colNumber + 1 < numRowsCols:\n rowNumber -= 1\n colNumber += 1\n elif colNumber + 1 < numRowsCols:\n colNumber += 1\n isUp = False\n elif rowNumber + 1 < numRowsCols:\n rowNumber += 1\n isUp = False\n else:\n stop = True\n isUp = False\n if not stop:\n returnArray.append(mat[rowNumber][colNumber])\n return returnArray", "def matrixdiagonally(mat):\n i = 0\n j = 0\n count = 0\n flag = 1\n ls = []\n while count < len(mat) * len(mat[0]):\n if flag == 1:\n while i >= 0 and j < len(mat[0]):\n ls.append(mat[i][j])\n i -= 1\n j += 1\n count += 1\n if i < 0 and j <= len(mat[0]) - 1:\n i = 0\n if j == len(mat[0]):\n j -= 1\n i += 2\n else:\n while i < len(mat) and j >= 0:\n ls.append(mat[i][j])\n i += 1\n j -= 1\n count += 1\n if j < 0 and i <= len(mat) - 1:\n j = 0\n if i == len(mat):\n i -= 1\n j += 2\n flag = 1 if flag == 0 else 0\n return ls", "def matrixdiagonally(mat):\n n = len(mat)\n i = 0\n j = 0\n k = 0\n lst = []\n up = True\n while k < n * n:\n if up:\n while i >= 0 and j < n:\n lst.append(mat[i][j])\n k += 1\n i -= 1\n j += 1\n if i < 0 and j <= n - 1:\n i = 0\n if j == n:\n i = i + 2\n j -= 1\n else:\n while i < n and j >= 0:\n lst.append(mat[i][j])\n k += 1\n j -= 1\n i += 1\n if j < 0 and i <= n - 1:\n j = 0\n if i == n:\n j = j + 2\n i -= 1\n up = not up\n return lst", "def matrixdiagonally(matrix):\n d = {}\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n if i + j not in d:\n d[i + j] = [matrix[i][j]]\n else:\n d[i + j].append(matrix[i][j])\n ans = []\n for (k, v) in d.items():\n if k % 2 == 0:\n ans.extend(v[::-1])\n else:\n ans.extend(v)\n return ans", "def matrixdiagonally(mat):\n numRows = len(mat)\n numCols = len(mat[0])\n diagonals = [[] for _ in range(numRows + numCols - 1)]\n for r in range(numRows):\n for c in range(numCols):\n diagonals[r + c].append(mat[r][c])\n res = []\n res = diagonals[0]\n for x in range(1, len(diagonals)):\n if x % 2:\n res.extend(diagonals[x])\n else:\n res.extend(diagonals[x][::-1])\n return res", "def matrixdiagonally(mat):\n n = len(mat)\n if n == 1:\n return [mat[0][0]]\n up = False\n (i, j) = (0, 0)\n res = [mat[0][0]]\n while len(res) < len(mat) * len(mat[0]):\n if up:\n if i == n - 1:\n j += 1\n else:\n i += 1\n while i >= 0 and j < n:\n res.append(mat[i][j])\n i -= 1\n j += 1\n i += 1\n j -= 1\n up = False\n else:\n if j == n - 1:\n i += 1\n else:\n j += 1\n while i < n and j >= 0:\n res.append(mat[i][j])\n i += 1\n j -= 1\n i -= 1\n j += 1\n up = True\n return res", "def matrixdiagonally(mat):\n output = []\n n = len(mat)\n col = 0\n row = 0\n up = True\n while row < n and col < n:\n if up:\n while row > 0 and col < n - 1:\n output.append(mat[row][col])\n row -= 1\n col += 1\n output.append(mat[row][col])\n if col == n - 1:\n row += 1\n else:\n col += 1\n else:\n while col > 0 and row < n - 1:\n output.append(mat[row][col])\n row += 1\n col -= 1\n output.append(mat[row][col])\n if row == n - 1:\n col += 1\n else:\n row += 1\n up = not up\n return output", "def matrixdiagonally(mat):\n r = len(mat)\n c = len(mat[0])\n diag = []\n check_revers = False\n for k in range(r):\n i = k\n j = 0\n l = []\n while i >= 0:\n l.append(mat[i][j])\n i -= 1\n j += 1\n if check_revers == False:\n check_revers = True\n else:\n l.reverse()\n check_revers = False\n for ll in l:\n diag.append(ll)\n for k in range(1, c):\n i = r - 1\n j = k\n l = []\n while j < c:\n l.append(mat[i][j])\n i -= 1\n j += 1\n if check_revers == False:\n check_revers = True\n else:\n l.reverse()\n check_revers = False\n for ll in l:\n diag.append(ll)\n return diag", "def matrixdiagonally(m):\n ans = []\n r = len(m)\n c = len(m[0])\n lst = [[] for i in range(r * c)]\n for i in range(r):\n for j in range(c):\n if (i + j) % 2 != 0:\n lst[i + j].append(m[i][j])\n else:\n lst[i + j].insert(0, m[i][j])\n for arr in lst:\n for x in arr:\n ans.append(x)\n return ans", "def matrixdiagonally(mat):\n i = 0\n j = 0\n k = 0\n isup = 1\n result_list = []\n while k < n[0] * n[0]:\n if isup:\n while i >= 0 and j < n[0]:\n result_list.append(mat[i][j])\n k += 1\n j += 1\n i -= 1\n if i < 0 and j < n[0]:\n i = 0\n if j == n[0]:\n i = i + 2\n j -= 1\n else:\n while j >= 0 and i < n[0]:\n result_list.append(mat[i][j])\n k += 1\n i += 1\n j -= 1\n if j < 0 and i <= n[0] - 1:\n j = 0\n if i == n[0]:\n j = j + 2\n i -= 1\n isup = not isup\n return result_list", "def matrixdiagonally(matrix):\n (num_rows, num_cols) = (len(matrix), len(matrix[0]))\n diagonals = [[] for _ in range(num_rows + num_cols - 1)]\n for i in range(num_rows):\n for j in range(num_cols):\n diagonals[i + j].append(matrix[i][j])\n res = diagonals[0]\n for x in range(1, len(diagonals)):\n if x % 2 == 1:\n res.extend(diagonals[x])\n else:\n res.extend(diagonals[x][::-1])\n return res", "def matrixdiagonally(mat):\n n = len(mat)\n s = [[] for i in range(2 * (n - 1) + 1)]\n for i in range(n):\n for j in range(n):\n s[i + j].append(mat[i][j])\n k = len(s)\n for i in range(2, k):\n if i % 2 == 0:\n s[i] = s[i][::-1]\n res = []\n for i in s:\n res.extend(i)\n return res", "def matrixdiagonally(mat):\n h = {}\n n = len(mat)\n for i in range(2 * n - 1):\n h[i] = []\n for i in range(n):\n for j in range(n):\n h[i + j].append(mat[i][j])\n res = []\n for i in h:\n if i % 2 == 0:\n res = res + h[i][::-1]\n else:\n res = res + h[i]\n return res", "def traverseUp(i, j, mat):\n res = []\n n = i\n while j <= n:\n res.append(mat[i][j])\n i -= 1\n j += 1\n return res\n\ndef traverseDown(i, j, mat):\n res = []\n n = i\n temp = j\n j = i\n i = temp\n while i <= n:\n res.append(mat[i][j])\n i += 1\n j -= 1\n return res\n\ndef matrixdiagonally(mat):\n dir = 0\n n = len(mat[0])\n res = []\n for row in range(n):\n if dir == 0:\n res += self.traverseUp(row, 0, mat)\n dir = 1\n else:\n res += self.traverseDown(row, 0, mat)\n dir = 0\n for col in range(1, n):\n if dir == 0:\n res += self.traverseUp(n - 1, col, mat)\n dir = 1\n else:\n res += self.traverseDown(n - 1, col, mat)\n dir = 0\n return res", "def matrixdiagonally(mat):\n a = []\n row = 0\n col = 0\n n = len(mat)\n for i in range(n * n):\n a.append(mat[row][col])\n if (row + col) % 2 == 0:\n if col == n - 1:\n row += 1\n elif row == 0:\n col += 1\n else:\n row -= 1\n col += 1\n elif row == n - 1:\n col += 1\n elif col == 0:\n row += 1\n else:\n row += 1\n col -= 1\n return a", "def matrixdiagonally(mat):\n r = len(mat)\n c = len(mat[0])\n i = 0\n j = 0\n res = []\n f = -1\n while i < r:\n f *= -1\n ni = i\n nj = j\n t = []\n while ni >= 0 and nj < c:\n t.append(mat[ni][nj])\n ni -= 1\n nj += 1\n if f == 1:\n res.extend(t)\n else:\n res.extend(t[::-1])\n i += 1\n i -= 1\n j += 1\n while j < c:\n f *= -1\n ni = i\n nj = j\n t = []\n while ni >= 0 and nj < c:\n t.append(mat[ni][nj])\n ni -= 1\n nj += 1\n if f == 1:\n res.extend(t)\n else:\n res.extend(t[::-1])\n j += 1\n return res", "def matrixdiagonally(mat):\n n = len(mat)\n i = j = k = 0\n isup = True\n lis = []\n while k < n * n:\n if isup:\n while i >= 0 and j < n:\n lis.append(mat[i][j])\n k += 1\n j += 1\n i -= 1\n if i < 0 and j <= n - 1:\n i = 0\n if j == n:\n i += 2\n j -= 1\n else:\n while j >= 0 and i < n:\n lis.append(mat[i][j])\n k += 1\n i += 1\n j -= 1\n if j < 0 and i <= n - 1:\n j = 0\n if i == n:\n j += 2\n i -= 1\n isup = not isup\n return lis", "def matrixdiagonally(mat):\n res = []\n n = len(mat)\n i = 0\n j = 0\n res.append(mat[i][j])\n while i != n - 1 or j != n - 1:\n if j + 1 < n:\n j = j + 1\n else:\n i = i + 1\n while True:\n res.append(mat[i][j])\n if i + 1 >= n or j - 1 <= -1:\n break\n i = i + 1\n j = j - 1\n if i + 1 < n:\n i = i + 1\n else:\n j = j + 1\n while True:\n res.append(mat[i][j])\n if i - 1 <= -1 or j + 1 >= n:\n break\n i = i - 1\n j = j + 1\n return res", "from collections import defaultdict\n\ndef matrixdiagonally(mat):\n d = defaultdict(list)\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n d[i + j].append(matrix[i][j])\n ans = []\n for (k, v) in d.items():\n if k % 2 == 0:\n ans.extend(v[::-1])\n else:\n ans.extend(v)\n return ans", "def matrixdiagonally(mat):\n up = 1\n n = len(mat)\n (i, j) = (0, 0)\n lst = []\n for _ in range(n * n):\n lst.append(mat[i][j])\n if up:\n if i - 1 >= 0 and j + 1 < n:\n i = i - 1\n j = j + 1\n elif j + 1 < n:\n j += 1\n up = 0\n else:\n i += 1\n up = 0\n elif i + 1 < n and j - 1 >= 0:\n i = i + 1\n j = j - 1\n elif i + 1 < n:\n i += 1\n up = 1\n else:\n j += 1\n up = 1\n return lst", "def matrixdiagonally(mat):\n flag = False\n ans = []\n k = 0\n r = len(mat)\n c = len(mat[0])\n while k < r:\n i = 0\n j = k\n l = []\n while i < r and j >= 0:\n l.append(mat[i][j])\n i += 1\n j -= 1\n if not flag:\n l.reverse()\n ans.extend(l)\n flag = not flag\n k += 1\n k = 1\n while k < c:\n i = k\n j = c - 1\n l = []\n while i < r and j >= 0:\n l.append(mat[i][j])\n i += 1\n j -= 1\n if not flag:\n l.reverse()\n ans.extend(l)\n flag = not flag\n k += 1\n return ans", "def matrixdiagonally(mat):\n m = len(mat)\n n = len(mat[0])\n result = []\n rev = True\n\n def traverse(r, c, result, rev):\n l = []\n while r < m and c >= 0:\n l.append(mat[r][c])\n r += 1\n c -= 1\n if not rev:\n result += l\n else:\n result += l[::-1]\n return not rev\n for c in range(n):\n rev = traverse(0, c, result, rev)\n for r in range(1, m):\n rev = traverse(r, n - 1, result, rev)\n return result", "def matrixdiagonally(mat):\n arr = []\n for i in range(2 * len(mat) - 1):\n arr.append([])\n for i in range(len(mat)):\n for j in range(len(mat)):\n arr[i + j].append(mat[i][j])\n ans = []\n i = 0\n n = len(arr)\n turn = 0\n while i < n:\n if i % 2 == 0:\n arr[i].reverse()\n for j in arr[i]:\n ans.append(j)\n i += 1\n else:\n for j in range(len(arr[i])):\n ans.append(arr[i][j])\n i += 1\n return ans", "def matrixdiagonally(mat):\n i = 0\n j = 0\n nodes_traversed = 0\n total_nodes = len(mat) * len(mat)\n isUp = True\n res = []\n while nodes_traversed < total_nodes:\n if isUp:\n while i >= 0 and j < len(mat):\n res.append(mat[i][j])\n nodes_traversed += 1\n i -= 1\n j += 1\n if i < 0 and j <= len(mat) - 1:\n i = 0\n if j == len(mat):\n i = i + 2\n j -= 1\n else:\n while j >= 0 and i < len(mat):\n res.append(mat[i][j])\n nodes_traversed += 1\n i += 1\n j -= 1\n if j < 0 and i <= len(mat) - 1:\n j = 0\n if i == len(mat):\n j = j + 2\n i -= 1\n isUp = not isUp\n return res", "def matrixdiagonally(mat):\n n = len(mat)\n res = []\n for l in range(2 * (n - 1) + 1):\n if l % 2 == 0:\n i = min(l, n - 1)\n j = l - i\n else:\n j = min(l, n - 1)\n i = l - j\n while i >= 0 and j >= 0 and (i < n) and (j < n):\n res.append(mat[i][j])\n if l % 2 == 0:\n i -= 1\n j += 1\n else:\n i += 1\n j -= 1\n return res", "def matrixdiagonally(arr):\n n = len(arr)\n ans = []\n mode = 0\n it = 0\n lower = 0\n for t in range(2 * n - 1):\n t1 = t\n if t1 >= n:\n mode += 1\n t1 = n - 1\n it -= 1\n lower += 1\n else:\n lower = 0\n it += 1\n for i in range(t1, lower - 1, -1):\n if (t1 + mode) % 2 == 0:\n ans.append(arr[i][t1 + lower - i])\n else:\n ans.append(arr[t1 + lower - i][i])\n return ans", "from collections import deque\n\ndef matrixdiagonally(n, mat):\n n = len(mat)\n if n < 2:\n return mat[0]\n temp = list()\n for i in range(1, n):\n coords = []\n x = list(range(0, i + 1))\n y = [-1 * var + i for var in x]\n if len(x) > 1:\n for k in range(len(x)):\n coords.append(mat[x[k]][y[k]])\n temp.append(coords)\n for j in range(n - 1, -1, -1):\n coords = []\n x = list(range(n - 1, n - 1 - j, -1))\n y = x.copy()\n y.reverse()\n if len(y) > 1:\n for k in range(len(y)):\n coords.append(mat[y[k]][x[k]])\n temp.append(coords)\n diag = []\n result = deque()\n for k in range(len(temp)):\n arr = temp[k].copy()\n if k % 2 != 0:\n arr.reverse()\n diag.append(arr)\n for l in range(len(diag[k])):\n result.append(diag[k][l])\n result.appendleft(mat[0][0])\n result.append(mat[-1][-1])\n return result", "def matrixdiagonally(a, mat):\n lis = [mat[0][0]]\n i = 0\n j = 0\n k = 0\n n = len(mat)\n d = False\n down = True\n while k < n * n:\n if i == n - 1 and j == n - 1:\n break\n if d:\n if down:\n while i > 0 and j < n - 1:\n k += 1\n i -= 1\n j += 1\n lis.append(mat[j][i])\n else:\n while i < n - 1 and j > 0:\n k += 1\n i += 1\n j -= 1\n lis.append(mat[j][i])\n d = False\n else:\n if i == 0:\n if j == 0:\n i += 1\n down = True\n elif j < n - 1:\n j += 1\n down = False\n else:\n i += 1\n down = False\n elif j == 0:\n if i < n - 1:\n i += 1\n down = True\n else:\n j += 1\n down = True\n elif i == n - 1:\n j += 1\n down = True\n elif j == n - 1:\n i += 1\n down = False\n lis.append(mat[j][i])\n k += 1\n d = True\n return lis"], "starter_code": "def matrixdiagonally(mat):\n", "input_output": {"inputs": ["N = 3\r\nmat[][] = {{1 2 3},{4 5 6},{7 8 9}}", "N = 2\r\nmat[][] = {{1 2},{3 4}}"], "outputs": ["1 2 4 7 5 3 6 8 9", "1 2 3 4"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/print-matrix-in-diagonal-pattern/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(N*M)", "entry_point": "matrixdiagonally", "task_id": "TACO_lite/275", "example": [[], []]} +{"requirement": "Write a function with the signature shown below:\n```python\ndef is_int_array(arr):\n return True\n```\n* returns `true / True` if every element in an array is an integer or a float with no decimals.\n* returns `true / True` if array is empty.\n* returns `false / False` for every other input.", "solutions": ["def is_int_array(a):\n return isinstance(a, list) and all((isinstance(x, (int, float)) and x == int(x) for x in a))", "def is_int_array(arr):\n if arr == []:\n return True\n if arr in [None, '']:\n return False\n for i in arr:\n if type(i) in [int, float]:\n if int(i) != i:\n return False\n else:\n return False\n return True", "def is_int_array(arr):\n if arr is None or type(arr) is str or None in arr:\n return False\n else:\n for i in arr:\n if type(i) is str or i % 1 != 0:\n return False\n return True", "def is_int_array(arr):\n return isinstance(arr, list) and all((isinstance(e, int) or (isinstance(e, float) and e.is_integer()) for e in arr))", "def is_int_array(arr):\n try:\n return list(map(int, arr)) == arr\n except:\n return False", "def is_int_array(arr):\n a = []\n if arr == None or arr == '':\n return False\n for i in arr:\n if type(i) == int:\n a.append(i)\n elif type(i) == float and i.is_integer():\n a.append(i)\n if len(arr) == len(a):\n return True\n return False", "def is_int_array(arr):\n return isinstance(arr, list) and all(map(lambda x: isinstance(x, (int, float)) and int(x) == x, arr))", "is_int_array = lambda a: isinstance(a, list) and all((isinstance(i, (int, float)) and i == int(i) for i in a))", "def isInt(n):\n try:\n return int(n) == float(n)\n except (TypeError, ValueError):\n return False\n\ndef is_int_array(arr):\n my_list = []\n if type(arr) is not list:\n return False\n if not arr:\n return True\n else:\n for x in arr:\n if type(x) is int or type(x) is float:\n if isInt(x):\n my_list.append(1)\n if len(arr) == len(my_list):\n return True\n else:\n return False"], "starter_code": "def is_int_array(arr):\n", "input_output": {"fn_name": "is_int_array", "inputs": [[[]], [[1, 2, 3, 4]], [[-11, -12, -13, -14]], [[1.0, 2.0, 3.0]], [[1, 2, null]], [null], [""], [[null]], [[1.0, 2.0, 3.0001]], [["-1"]]], "outputs": [[true], [true], [true], [true], [false], [false], [false], [false], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/52a112d9488f506ae7000b95", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_int_array", "task_id": "TACO_lite/308", "example": [[[[1, 2, 3, 4]], [[1, "a", 3, 4]], [[1.0, 2.0, 3.0]], [[]], [[1.0, 2.5, 3.0]], [null]], ["True", "False", "True", "True", "False", "False"]]} +{"requirement": "Create a function that returns an array containing the first `l` digits from the `n`th diagonal of [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal's_triangle).\n\n`n = 0` should generate the first diagonal of the triangle (the 'ones'). The first number in each diagonal should be 1.\n\nIf `l = 0`, return an empty array. Assume that both `n` and `l` will be non-negative integers in all test cases.", "solutions": ["def generate_diagonal(d, l):\n result = [1] if l else []\n for k in range(1, l):\n result.append(result[-1] * (d + k) // k)\n return result", "from scipy.special import comb\n\ndef generate_diagonal(n, l):\n return [comb(n + a, a, exact=True) for a in range(l)]", "from math import factorial\n\ndef generate_diagonal(n, l):\n return [factorial(n + i) // (factorial(n) * factorial(i)) for i in range(l)]", "def efficientCombination(n, k):\n from math import gcd\n (a, b) = (1, 1)\n if k == 0:\n return 1\n if n - k < k:\n k = n - k\n while k:\n a *= n\n b *= k\n m = gcd(a, b)\n a //= m\n b //= m\n n -= 1\n k -= 1\n return a\n\ndef generate_diagonal(d, amt):\n diagElements = []\n for n in range(d, amt + d, 1):\n valOnDiag = efficientCombination(n, d)\n diagElements.append(valOnDiag)\n return diagElements", "import operator as op\nfrom functools import reduce\n\ndef ncr(n, r):\n r = min(r, n - r)\n return reduce(op.mul, range(n, n - r, -1), 1) // reduce(op.mul, range(1, r + 1), 1)\n\ndef generate_diagonal(n, l):\n mx = []\n (i, j) = (n, 0)\n while i < n + l:\n mx.append(ncr(i, j))\n i += 1\n j += 1\n return mx", "def generate_diagonal(n, l):\n if l == 0:\n return []\n diagonal = [1]\n for i in range(l)[1:]:\n diagonal.append(diagonal[-1] * (n + i) / i)\n return diagonal", "def generate_diagonal(n, l):\n if n == 0:\n c = []\n while l > 0:\n c += [1]\n l -= 1\n return c\n if l == 0 and n == 0:\n return '[]'\n else:\n i = n + l\n q = []\n o = []\n\n def triangles():\n p = [1]\n while True:\n yield p\n p = [1] + [p[x] + p[x + 1] for x in range(len(p) - 1)] + [1]\n for t in triangles():\n if i > 0:\n i -= 1\n q.append(t)\n else:\n break\n for t in range(l):\n r = q[n][t]\n n += 1\n o.append(r)\n return o", "def generate_diagonal(n, l):\n row = [1]\n for k in range(1, l):\n row.append(row[-1] * (n + k) // k)\n return row if l else []", "from functools import lru_cache\n\ndef generate_diagonal(nn, l):\n\n def calc(n, ll):\n if n == 0 or ll == 1:\n return 1\n elif n < 0:\n return 0\n return calc(n - 1, ll) + calc(n, ll - 1)\n return [calc(nn, i) for i in range(1, l + 1)]"], "starter_code": "def generate_diagonal(n, l):\n", "input_output": {"fn_name": "generate_diagonal", "inputs": [[0, 10], [1, 10], [2, 10], [3, 10], [4, 10], [10, 0], [100, 6]], "outputs": [[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], [[1, 3, 6, 10, 15, 21, 28, 36, 45, 55]], [[1, 4, 10, 20, 35, 56, 84, 120, 165, 220]], [[1, 5, 15, 35, 70, 126, 210, 330, 495, 715]], [[]], [[1, 101, 5151, 176851, 4598126, 96560646]]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/576b072359b1161a7b000a17", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "generate_diagonal", "task_id": "TACO_lite/195", "example": [[[0, 5], [1, 5], [2, 5]], ["[1, 1, 1, 1, 1]", "[1, 2, 3, 4, 5]", "[1, 3, 6, 10, 15]"]]} +{"requirement": "## Task\n\nCreate a function that given a sequence of strings, groups the elements that can be obtained by rotating others, ignoring upper or lower cases. \n\nIn the event that an element appears more than once in the input sequence, only one of them will be taken into account for the result, discarding the rest. \n\n## Input\n\nSequence of strings. Valid characters for those strings are uppercase and lowercase characters from the alphabet and whitespaces.\n\n## Output\n\nSequence of elements. Each element is the group of inputs that can be obtained by rotating the strings. \n\nSort the elements of each group alphabetically. \n\nSort the groups descendingly by size and in the case of a tie, by the first element of the group alphabetically.\n\n## Examples\n\n```python\n['Tokyo', 'London', 'Rome', 'Donlon', 'Kyoto', 'Paris', 'Okyot'] --> [['Kyoto', 'Okyot', 'Tokyo'], ['Donlon', 'London'], ['Paris'], ['Rome']]\n\n['Rome', 'Rome', 'Rome', 'Donlon', 'London'] --> [['Donlon', 'London'], ['Rome']]\n\n[] --> []\n```", "solutions": ["def group_cities(seq):\n result = []\n sort_result = []\n seq = list(dict.fromkeys(seq))\n for (e, i) in enumerate(seq):\n sort_result = [j for j in seq if len(j) == len(i) and j.lower() in 2 * i.lower()]\n if not sorted(sort_result) in result:\n result.append(sorted(sort_result))\n return sorted(sorted(result), key=len, reverse=True)", "from collections import Counter, defaultdict\n\ndef group_cities(seq):\n bases = defaultdict(lambda : defaultdict(list))\n for W in set(seq):\n w = W.lower()\n d = bases[frozenset(Counter(w).items())]\n k = next((w2 for w2 in d if w in w2), w * 2)\n d[k].append(W)\n return sorted([sorted(lst) for d in bases.values() for lst in d.values()], key=lambda g: (-len(g), g[0]))", "from collections import deque\n\ndef group_cities(seq):\n result = []\n seq = sorted(set(seq))\n simples = [c.lower() for c in seq]\n skip = set()\n for (i, c1) in enumerate(simples):\n if i in skip:\n continue\n city_match = [i]\n skip.add(i)\n rolls = []\n roller = deque(c1)\n roller.rotate(1)\n while ''.join(roller) != c1:\n rolls.append(''.join(roller))\n roller.rotate(1)\n for roll in rolls:\n for (j, c2) in enumerate(simples[i + 1:], i + 1):\n if j in skip:\n continue\n if c2 == roll:\n skip.add(j)\n city_match.append(j)\n result.append(sorted([seq[k] for k in city_match]))\n result.sort(key=lambda a: (-len(a), a[0]))\n return result", "def group_cities(seq):\n res = {}\n for w in seq:\n temp = [str(w[i:] + w[:i]).title() for i in range(1, len(w)) if str(w[i:] + w[:i]).title() in seq]\n temp.append(w)\n res[frozenset(temp)] = sorted(set(temp))\n return sorted(res.values(), key=lambda x: (-len(x), x[0]))", "def is_palindrome(a, b):\n if len(a) != len(b):\n return False\n else:\n for i in range(1, len(a)):\n if a.lower()[i:] + a.lower()[:i] == b.lower():\n return True\n return False\n\ndef group_cities(seq):\n ans = []\n already_chosen = []\n for term in seq:\n if term not in already_chosen:\n temp = [term]\n already_chosen.append(term)\n for thing in seq:\n if thing not in already_chosen and thing != term and is_palindrome(thing, term):\n temp.append(thing)\n already_chosen.append(thing)\n ans.append(temp)\n for thing in ans:\n thing.sort()\n ans.sort(key=lambda x: x[0])\n ans.sort(key=len, reverse=True)\n return ans", "from collections import defaultdict\n\ndef key(s):\n s = s.lower().replace(' ', '')\n return min((s[i:] + s[:i] for i in range(len(s))))\n\ndef group_cities(seq):\n result = defaultdict(list)\n for city in set(seq):\n result[key(city)].append(city)\n for cities in result.values():\n cities.sort()\n return sorted(result.values(), key=lambda cities: (-len(cities), cities[0]))", "def group_cities(seq):\n result = []\n for element in sorted(list(dict.fromkeys(seq)), key=str.lower):\n for group in result:\n if element.lower() in [group[0].lower()[r:] + group[0].lower()[:r] for r in range(len(group[0].lower()))]:\n group.append(element)\n break\n else:\n result.append([element])\n return sorted(result, key=len, reverse=True)", "from collections import deque\nfrom operator import itemgetter\n\ndef group_cities(seq):\n seq_by_length = {}\n for s in seq:\n l = len(s)\n if l in seq_by_length:\n seq_by_length[l].append(s)\n else:\n seq_by_length[l] = [s]\n groups = []\n for elems in seq_by_length.values():\n to_check = deque(set(elems))\n while to_check:\n cur_check = to_check.pop()\n (group, check) = ([cur_check], cur_check.lower() * 2)\n for c in to_check.copy():\n if c.lower() in check:\n group.append(c)\n to_check.remove(c)\n groups.append(sorted(group))\n return sorted(sorted(groups, key=itemgetter(0)), key=len, reverse=True)", "from collections import defaultdict\n\ndef group_cities(l):\n\n def make_key(s):\n return min((s[-i:] + s[:-i] for i in range(len(s))))\n d = defaultdict(list)\n for item in sorted(set(l)):\n d[make_key(item.lower())].append(item)\n return sorted(d.values(), key=len, reverse=True)", "from collections import defaultdict\n\ndef group_cities(seq):\n key = lambda s: min((s[i:] + s[:i] for i in range(len(s))))\n d = defaultdict(set)\n for e in seq:\n d[key(e.lower())].add(e)\n return sorted((sorted(v) for v in d.values()), key=lambda x: (-len(x), x))"], "starter_code": "def group_cities(seq):\n", "input_output": {"fn_name": "group_cities", "inputs": [[["Tokyo", "London", "Rome", "Donlon", "Kyoto", "Paris", "Okyot"]], [["Tokyo", "London", "Rome", "Donlon"]], [["Rome", "Rome", "Rome", "Donlon", "London"]], [["Ab", "Aa"]], [[]]], "outputs": [[[["Kyoto", "Okyot", "Tokyo"], ["Donlon", "London"], ["Paris"], ["Rome"]]], [[["Donlon", "London"], ["Rome"], ["Tokyo"]]], [[["Donlon", "London"], ["Rome"]]], [[["Aa"], ["Ab"]]], [[]]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Sorting", "Lists"], "name": null, "source": "codewars", "tags": ["String algorithms", "Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/5e98712b7de14f0026ef1cc1", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "group_cities", "task_id": "TACO_lite/282", "example": [[[["Tokyo", "London", "Rome", "Donlon", "Kyoto", "Paris", "Okyot"]], [["Rome", "Rome", "Rome", "Donlon", "London"]], [[]]], ["[['Kyoto', 'Okyot', 'Tokyo'], ['Donlon', 'London'], ['Paris'], ['Rome']]", "[['Donlon', 'London'], ['Rome']]", "[]"]]} +{"requirement": "Given a list of intervals, remove all intervals that are covered by another interval in the list.\nInterval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d.\nAfter doing so, return the number of remaining intervals.\n \nExample 1:\nInput: intervals = [[1,4],[3,6],[2,8]]\nOutput: 2\nExplanation: Interval [3,6] is covered by [2,8], therefore it is removed.\n\nExample 2:\nInput: intervals = [[1,4],[2,3]]\nOutput: 1\n\nExample 3:\nInput: intervals = [[0,10],[5,12]]\nOutput: 2\n\nExample 4:\nInput: intervals = [[3,10],[4,10],[5,11]]\nOutput: 2\n\nExample 5:\nInput: intervals = [[1,2],[1,4],[3,4]]\nOutput: 1\n\n \nConstraints:\n\n1 <= intervals.length <= 1000\nintervals[i].length == 2\n0 <= intervals[i][0] < intervals[i][1] <= 10^5\nAll the intervals are unique.", "solutions": ["def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[0], -x[1]))\n prev_end = result = 0\n for (_, end) in intervals:\n if end > prev_end:\n result += 1\n prev_end = end\n return result", "def removecoveredintervals(l: List[List[int]]) -> int:\n l.sort(reverse=True, key=lambda x: (x[1], -x[0]))\n n = len(l)\n c = n\n for i in range(n - 1):\n if l[i][0] <= l[i + 1][0] and l[i][1] >= l[i + 1][1]:\n l[i + 1] = l[i]\n c -= 1\n return c", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n from functools import cmp_to_key\n\n def cmp(a, b):\n if a[0] > b[0]:\n return 1\n if a[0] < b[0]:\n return -1\n if a[1] > b[1]:\n return -1\n return 1\n lis = []\n if len(intervals) == 1:\n return 1\n for (x, y) in intervals:\n lis.append((x, y))\n lis.sort(key=cmp_to_key(cmp))\n fin = []\n fin.append(list(lis[0]))\n for i in range(1, len(lis)):\n (currx, curry) = lis[i]\n flag = 0\n for j in range(len(fin)):\n if curry <= fin[j][1] and currx >= fin[j][0]:\n flag = 1\n if flag == 0:\n fin.append([currx, curry])\n return len(fin)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[0], -x[1]))\n covering = 0\n used = set()\n for (i, (si, ei)) in enumerate(intervals):\n for (sj, ej) in intervals[i + 1:]:\n if sj > ei:\n break\n if ej > ei:\n continue\n if (sj, ej) in used:\n continue\n used.add((sj, ej))\n covering += 1\n return len(intervals) - covering", "def __init__(val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef __lt__(other):\n if self.val[0] < other.val[0]:\n return True\n elif self.val[0] > other.val[0]:\n return False\n elif self.val[1] > other.val[1]:\n return True\n else:\n return False\n\ndef __le__(other):\n return self < other or self.val == other.val\n\ndef __gt__(other):\n return not self <= other\n\ndef __ge__(other):\n return not self < other\n\ndef __eq__(other):\n return self <= other and self >= geother\n\ndef __neq__(other):\n return not self == other\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n tree = Tree(val=tuple(intervals[0]))\n for (x, y) in intervals[1:]:\n this = Tree((x, y))\n cursor = tree\n while True:\n if this < cursor:\n if cursor.left:\n cursor = cursor.left\n else:\n cursor.left = this\n break\n elif this > cursor:\n if cursor.right:\n cursor = cursor.right\n else:\n cursor.right = this\n break\n else:\n break\n buff = [tree]\n (count, last) = (0, None)\n while buff:\n while buff[-1].left:\n buff.append(buff[-1].left)\n while buff and (not buff[-1].right):\n this = buff.pop(-1)\n if count == 0:\n (count, last) = (1, this.val[1])\n elif this.val[1] > last:\n (count, last) = (count + 1, this.val[1])\n if buff:\n this = buff.pop(-1)\n if count == 0:\n (count, last) = (1, this.val[1])\n elif this.val[1] > last:\n (count, last) = (count + 1, this.val[1])\n buff.append(this.right)\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n for i in range(0, len(intervals) - 1):\n minel = intervals[i]\n minid = i\n for j in range(i + 1, len(intervals)):\n evl = intervals[j]\n if evl[0] < minel[0]:\n minel = evl\n minid = j\n (intervals[i], intervals[minid]) = (intervals[minid], intervals[i])\n c = 0\n prevl = intervals[0][0]\n prevh = intervals[0][1]\n for x in range(1, len(intervals)):\n curl = intervals[x][0]\n curh = intervals[x][1]\n if curh <= prevh:\n c = c + 1\n continue\n if curl == prevl:\n c = c + 1\n if curh > prevh:\n prevh = curh\n continue\n prevl = curl\n prevh = curh\n return len(intervals) - c", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n ordered_intervals = sorted(intervals, key=lambda x: (x[0], -x[1]))\n candidates = set()\n for i in range(len(intervals)):\n (curr_start, curr_end) = ordered_intervals[i]\n for j in range(i + 1, len(intervals)):\n (next_start, next_end) = ordered_intervals[j]\n if next_start >= curr_end:\n break\n if next_end <= curr_end:\n candidates.add(j)\n return len(intervals) - len(candidates)", "import numpy as np\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n copy_intervals = intervals[:]\n for (i, interval_1) in enumerate(copy_intervals):\n for interval_2 in copy_intervals[i + 1:]:\n if interval_1[0] >= interval_2[0] and interval_1[1] <= interval_2[1]:\n if interval_1 in intervals:\n intervals.remove(interval_1)\n break\n if interval_1[0] <= interval_2[0] and interval_1[1] >= interval_2[1]:\n if interval_2 in intervals:\n intervals.remove(interval_2)\n return len(intervals)", "def removecoveredintervals(arr: List[List[int]]) -> int:\n arr.sort(reverse=True)\n ans = 0\n n = len(arr)\n take = [1] * n\n for i in range(n - 1):\n for j in range(i + 1, n):\n if arr[i][0] >= arr[j][0] and arr[i][1] <= arr[j][1]:\n take[i] = 0\n break\n for i in range(n - 1, -1, -1):\n for j in range(i - 1, -1, -1):\n if arr[i][0] >= arr[j][0] and arr[i][1] <= arr[j][1]:\n take[i] = 0\n break\n return take.count(1)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda interval: (interval[0], -interval[1]))\n length = len(intervals)\n start = 0\n removed = 0\n while start < length - 1:\n curr = start + 1\n while curr < length:\n if intervals[curr][0] != -1:\n if intervals[curr][0] >= intervals[start][0] and intervals[curr][1] <= intervals[start][1]:\n removed += 1\n intervals[curr][0] = -1\n intervals[curr][1] = -1\n curr += 1\n start += 1\n return length - removed", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals = sorted(intervals, key=lambda x: x[1])\n n = len(intervals)\n cnt = 0\n for i in intervals:\n for j in intervals:\n if j == i:\n continue\n if i[1] <= j[1] and i[0] >= j[0]:\n cnt += 1\n break\n return n - cnt", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(reverse=True)\n intervals.sort(key=lambda i: i[1])\n covered = set()\n for (i, (c, d)) in enumerate(intervals):\n for (a, b) in intervals[0:i]:\n if c <= a and b <= d:\n covered.add((a, b))\n return len(intervals) - len(covered)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n new = sorted(intervals, key=lambda x: x[1] - x[0], reverse=True)\n ans = []\n for (i, v) in enumerate(new):\n flag = False\n for elem in new[:i]:\n if v[0] >= elem[0] and v[1] <= elem[1]:\n flag = True\n if flag == False:\n ans.append(v)\n return len(ans)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n removed = 0\n removedSet = set()\n for ind1 in range(len(intervals)):\n for ind2 in range(len(intervals)):\n if ind1 == ind2 or ind1 in removedSet:\n continue\n interval1 = intervals[ind1]\n interval2 = intervals[ind2]\n if interval1[0] >= interval2[0] and interval1[1] <= interval2[1]:\n removed += 1\n removedSet.add(ind1)\n return len(intervals) - removed", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n flag = [True for i in range(n)]\n ctr = n\n for i in range(n):\n for j in range(n):\n if i != j and flag[i] and flag[j]:\n (a, b) = intervals[i]\n (c, d) = intervals[j]\n if c <= a and b <= d:\n flag[i] = False\n ctr -= 1\n elif a <= c and d <= b:\n flag[j] = False\n ctr -= 1\n return ctr", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n\n def covered(a, b):\n return a[0] >= b[0] and a[1] <= b[1]\n deleted = set()\n for i in range(len(intervals)):\n for j in range(len(intervals)):\n if i != j and i not in deleted:\n if covered(intervals[i], intervals[j]):\n deleted.add(i)\n return len(intervals) - len(deleted)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n int_set = set((tuple(i) for i in intervals))\n for (i, (a, b)) in enumerate(intervals):\n for (c, d) in intervals[i + 1:]:\n if a <= c and d <= b and ((c, d) in int_set):\n int_set.remove((c, d))\n elif c <= a and b <= d and ((a, b) in int_set):\n int_set.remove((a, b))\n return len(int_set)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n covered = 0\n m = {}\n for [l, r] in intervals:\n if l not in m:\n m[l] = r\n else:\n m[l] = max(r, m[l])\n covered += 1\n a = []\n for i in m:\n a.append([i, m[i]])\n a.sort(key=lambda x: x[0])\n _c = set()\n for i in range(len(a)):\n for j in range(i + 1, len(a)):\n if a[j][1] <= a[i][1] and j not in _c:\n _c.add(j)\n covered += 1\n return len(intervals) - covered", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda tup: tup[1] - tup[0], reverse=True)\n covered = set()\n for i in range(len(intervals)):\n (s, e) = intervals[i]\n for j in range(i + 1, len(intervals)):\n (s2, e2) = intervals[j]\n if s <= s2 and e2 <= e:\n covered.add(j)\n return len(intervals) - len(covered)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n l = len(intervals)\n a = [True] * l\n for i in range(l):\n for j in range(l):\n if i == j:\n continue\n if not a[i] or not a[j]:\n continue\n if intervals[i][0] <= intervals[j][0] and intervals[i][1] >= intervals[j][1]:\n a[j] = False\n return a.count(True)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[0], -x[1]))\n ans = len(intervals)\n i = 0\n while i < len(intervals):\n for j in range(i):\n if intervals[j][0] <= intervals[i][0] and intervals[j][1] >= intervals[i][1]:\n ans -= 1\n break\n i += 1\n return ans", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals = sorted(intervals, key=lambda k: (k[0], -k[1]))\n removed = set()\n i = 0\n while i < len(intervals) - 1:\n for j in range(i + 1, len(intervals)):\n if intervals[j][1] <= intervals[i][1] and j not in removed:\n removed.add(j)\n i += 1\n return len(intervals) - len(removed)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n intervals.sort(key=lambda x: (x[0], -x[1]))\n removeSet = set()\n for i in range(n):\n interval1 = intervals[i]\n for j in range(i + 1, n):\n interval2 = intervals[j]\n if interval2[0] >= interval1[1]:\n break\n if interval2[1] <= interval1[1]:\n removeSet.add(j)\n return n - len(removeSet)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n l = len(intervals)\n removed = set()\n intervals.sort(key=lambda i: (i[0], -i[1]))\n for i in range(l):\n for j in range(i + 1, l):\n if intervals[i][1] >= intervals[j][1]:\n removed.add(j)\n return l - len(removed)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n discarded = [False] * len(intervals)\n for i in range(len(intervals)):\n for j in range(len(intervals)):\n if i == j:\n continue\n if discarded[j]:\n continue\n if intervals[j][0] >= intervals[i][0] and intervals[j][1] <= intervals[i][1]:\n discarded[j] = True\n kount = 0\n for i in range(len(intervals)):\n if not discarded[i]:\n kount = kount + 1\n return kount", "def checkCovered(a, b):\n if a[0] < b[0] or a[1] > b[1]:\n return False\n return True\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n covered = [0] * len(intervals)\n for i in range(len(intervals) - 1):\n a = intervals[i]\n for j in range(i + 1, len(intervals)):\n b = intervals[j]\n if covered[i] == 0:\n if checkCovered(a, b):\n covered[i] = 1\n if covered[j] == 0:\n if checkCovered(b, a):\n covered[j] = 1\n return covered.count(0)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n i = 0\n j = 1\n while i < len(intervals) and j < len(intervals):\n if intervals[i][0] >= intervals[j][0] and intervals[i][1] <= intervals[j][1]:\n intervals.pop(i)\n (i, j) = (0, 1)\n elif intervals[i][0] <= intervals[j][0] and intervals[i][1] >= intervals[j][1]:\n intervals.pop(j)\n (i, j) = (0, 1)\n else:\n j += 1\n if j == len(intervals):\n i += 1\n j = i + 1\n return len(intervals)", "def isCovered(A, B):\n if A[0] <= B[0] and A[1] >= B[1]:\n return True\n return False\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n index = 0\n while index < len(intervals):\n delete = False\n i = intervals[index]\n for j in intervals:\n if intervals[index] == j:\n continue\n if self.isCovered(i, j):\n intervals.remove(j)\n index = -1\n break\n if self.isCovered(j, i):\n intervals.remove(i)\n index = -1\n break\n index += 1\n return len(intervals)", "import numpy as np\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n current_intervals = np.array(intervals)\n for interval in intervals:\n mask = np.logical_and(current_intervals[:, 0] >= interval[0], current_intervals[:, 1] <= interval[1])\n current_intervals = current_intervals[np.logical_not(mask)]\n if sum(mask):\n current_intervals = np.append(current_intervals, [interval], axis=0)\n return len(current_intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n seen = set()\n n = len(intervals)\n for i in range(n):\n for j in range(n):\n if j == i or j in seen:\n continue\n (st1, ed1) = (intervals[i][0], intervals[i][1])\n (st2, ed2) = (intervals[j][0], intervals[j][1])\n if st1 <= st2 and ed2 <= ed1:\n seen.add(j)\n return n - len(seen)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n I = len(intervals)\n count = 0\n covered = {}\n removed = {}\n for i in range(0, I):\n for j in range(0, I):\n if i == j:\n continue\n if j in removed or i in removed:\n continue\n if intervals[i][0] <= intervals[j][0] and intervals[i][1] >= intervals[j][1]:\n if (i, j) not in covered and (j, i) not in covered:\n count += 1\n covered[i, j] = 1\n covered[j, i] = 1\n removed[j] = j\n return len(intervals) - count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n if len(intervals) < 2:\n return len(intervals)\n intervals.sort(key=lambda interval: interval[0])\n (start, idx) = (0, 1)\n removed = set()\n while start < len(intervals):\n if idx == len(intervals):\n start += 1\n idx = start + 1\n continue\n if idx in removed:\n idx += 1\n continue\n if intervals[start][1] < intervals[idx][0]:\n start += 1\n idx = start + 1\n continue\n if intervals[start][1] >= intervals[idx][1]:\n removed.add(idx)\n idx += 1\n continue\n if intervals[start][1] <= intervals[idx][1]:\n if intervals[start][0] == intervals[idx][0]:\n removed.add(start)\n start = idx\n idx += 1\n return len(intervals) - len(removed)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n covered = set()\n for i in range(len(intervals) - 1):\n (a1, b1) = intervals[i]\n for j in range(i + 1, len(intervals)):\n (a2, b2) = intervals[j]\n if a2 <= a1 and b1 <= b2:\n covered.add(i)\n elif a1 <= a2 and b2 <= b1:\n covered.add(j)\n return len(intervals) - len(covered)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n N = len(intervals)\n intervals.sort(key=lambda x: x[0])\n count = 0\n covered = set()\n for i in range(N):\n for j in range(N):\n if i != j and j not in covered:\n min_x = min(intervals[i][0], intervals[j][0])\n max_y = max(intervals[i][1], intervals[j][1])\n if intervals[i] == [min_x, max_y]:\n covered.add(j)\n count += 1\n return N - count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n lis = intervals\n arr = []\n lis.sort()\n for i in range(0, len(lis)):\n if lis[i] in arr:\n continue\n for j in range(i + 1, len(lis)):\n if i < len(lis) and j < len(lis):\n if lis[i][0] >= lis[j][0] and lis[i][1] <= lis[j][1] and (lis[i] not in arr):\n arr.append(lis[i])\n if lis[i][0] <= lis[j][0] and lis[i][1] >= lis[j][1] and (lis[j] not in arr):\n arr.append(lis[j])\n else:\n break\n return len(lis) - len(arr)", "from functools import cmp_to_key\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n\n def cmp_intervals(left, right):\n if left[0] == right[0]:\n return right[1] - left[1]\n return left[0] - right[0]\n n = len(intervals)\n s_intervals = sorted(intervals, key=cmp_to_key(cmp_intervals))\n covered = set()\n for i in range(n - 1):\n (a, b) = s_intervals[i]\n for j in range(i + 1, n):\n (c, d) = s_intervals[j]\n if a <= c and d <= b:\n covered.add((c, d))\n return n - len(covered)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort()\n drop = set([])\n for i in range(len(intervals)):\n (x, y) = intervals[i]\n for j in range(i + 1, len(intervals)):\n (a, b) = intervals[j]\n if x >= a and y <= b:\n drop.add(i)\n break\n elif a >= x and b <= y:\n drop.add(j)\n return len(intervals) - len(drop)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n intervals.sort(reverse=True)\n temp = []\n for i in range(n - 1, -1, -1):\n for k in range(0, n):\n if i != k and (intervals[k][0] <= intervals[i][0] and intervals[i][1] <= intervals[k][1]):\n temp.append(intervals[i])\n break\n res = [i for i in intervals if i not in temp]\n return len(res)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda t: [t[0], t[1]])\n deleted = set()\n i = 0\n while i < len(intervals):\n boundary = tuple(intervals[i])\n if not boundary in deleted:\n j = i + 1\n stop = False\n while not stop and j < len(intervals):\n comparedBoundary = tuple(intervals[j])\n if comparedBoundary[0] == boundary[0]:\n deleted.add(boundary)\n stop = True\n elif comparedBoundary[0] >= boundary[1]:\n stop = True\n elif comparedBoundary[1] <= boundary[1]:\n deleted.add(comparedBoundary)\n j += 1\n i += 1\n return len(intervals) - len(deleted)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n for i in range(len(intervals)):\n for j in range(i, len(intervals)):\n if i == j or type(intervals[i][0]) == str or type(intervals[j][0]) == str:\n continue\n elif intervals[i][0] >= intervals[j][0] and intervals[i][1] <= intervals[j][1]:\n intervals[i] = ['', '']\n elif intervals[j][0] >= intervals[i][0] and intervals[j][1] <= intervals[i][1]:\n intervals[j] = ['', '']\n interval = []\n for ele in intervals:\n if ele != ['', '']:\n interval.append(ele)\n return len(interval)", "from collections import defaultdict\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n m = n\n visited = defaultdict(lambda : False)\n for i in range(n):\n for j in range(n):\n if i == j or visited[j]:\n continue\n if intervals[i][0] <= intervals[j][0]:\n if intervals[i][1] >= intervals[j][1]:\n visited[j] = True\n m -= 1\n return m", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n removed = [False] * n\n intervals = sorted(intervals, key=lambda interval: (interval[0], -interval[1]))\n for i in range(len(intervals)):\n (start, end) = intervals[i]\n j = i + 1\n while j < len(intervals) and end >= intervals[j][0]:\n if end >= intervals[j][1] and (not removed[j]):\n removed[j] = True\n n -= 1\n j += 1\n return n", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n flags = []\n for i in range(n):\n flags.append(0)\n k = n\n for i in range(n):\n for j in range(n):\n if i == j or flags[j] == 1:\n continue\n if intervals[i][0] <= intervals[j][0] and intervals[i][1] >= intervals[j][1]:\n flags[j] = 1\n k -= 1\n return k", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n L = len(intervals)\n discard = set()\n for i in range(L):\n (x, y) = intervals[i]\n for j in range(i + 1, L):\n (a, b) = intervals[j]\n if a <= x and b >= y:\n discard.add((x, y))\n elif x <= a and y >= b:\n discard.add((a, b))\n return L - len(discard)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n length = len(intervals)\n if length <= 1:\n return length\n temp = intervals[:]\n (i, j) = (0, 1)\n while i < len(intervals) - 1:\n j = i + 1\n while j < len(intervals):\n if self.ainbHelper(intervals[i], intervals[j]) == True:\n try:\n temp.remove(intervals[i])\n except:\n pass\n break\n elif self.ainbHelper(intervals[j], intervals[i]) == True:\n try:\n temp.remove(intervals[j])\n except:\n pass\n j += 1\n else:\n j += 1\n i += 1\n return len(temp)\n\ndef ainbHelper(a: List[int], b: List[int]) -> bool:\n if a[0] < b[0]:\n return False\n if a[1] > b[1]:\n return False\n else:\n return True", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n for i in range(len(intervals)):\n for j in range(len(intervals)):\n if i != j:\n if intervals[i] != 0 and intervals[j] != 0:\n if intervals[j][0] <= intervals[i][0] and intervals[i][1] <= intervals[j][1]:\n intervals[i] = 0\n c = 0\n for i in intervals:\n if i != 0:\n c += 1\n return c", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n s = set()\n for (i, [a, b]) in enumerate(intervals):\n for (j, [c, d]) in enumerate(intervals[i + 1:]):\n if c <= a and b <= d:\n s.add((a, b))\n elif a <= c and d <= b:\n s.add((c, d))\n return len(intervals) - len(s)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n for i in range(len(intervals) - 1):\n for j in range(len(intervals) - i - 1):\n if intervals[j][0] > intervals[j + 1][0]:\n (intervals[j], intervals[j + 1]) = (intervals[j + 1], intervals[j])\n i = 0\n while True:\n while intervals[i][1] >= intervals[i + 1][1]:\n intervals.pop(i + 1)\n if i + 1 > len(intervals) - 1:\n break\n if i + 1 > len(intervals) - 1:\n break\n if intervals[i][0] == intervals[i + 1][0]:\n intervals.pop(i)\n if i + 1 > len(intervals) - 1:\n break\n else:\n continue\n if i + 1 == len(intervals) - 1:\n break\n i += 1\n return len(intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n op = 0\n if len(intervals) < 2:\n return len(intervals)\n intervals.sort(key=lambda l1: l1[0])\n for j in intervals:\n for k in intervals:\n if j[0] != k[0] or j[1] != k[1]:\n if j[0] >= k[0] and j[1] <= k[1]:\n op += 1\n break\n return len(intervals) - op", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n L = len(intervals)\n rm = set()\n for i in range(L):\n for j in range(i + 1, L):\n (l1, r1) = intervals[i]\n (l2, r2) = intervals[j]\n if l1 <= l2 and r1 >= r2:\n if j not in rm:\n rm.add(j)\n elif l1 >= l2 and r1 <= r2:\n if i not in rm:\n rm.add(i)\n return L - len(rm)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n count = [0] * len(intervals)\n for i in range(len(intervals) - 1):\n a = intervals[i][0]\n b = intervals[i][1]\n for j in range(i + 1, len(intervals)):\n x = intervals[j][0]\n y = intervals[j][1]\n if x <= a and b <= y:\n count[i] = 1\n elif a <= x and y <= b:\n count[j] = 1\n ans = 0\n for c in count:\n if c == 0:\n ans += 1\n return ans", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n rm = {}\n for i in range(1, len(intervals)):\n for ((a, b), (c, d)) in zip(intervals[0:-i], intervals[i:]):\n if a >= c:\n if b <= d:\n rm[a, b] = True\n elif c >= a:\n if d <= b:\n rm[c, d] = True\n return len(intervals) - len(rm)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n toremove = set()\n for i in range(0, len(intervals) - 1):\n for j in range(i + 1, len(intervals)):\n (s1, e1) = intervals[i]\n (s2, e2) = intervals[j]\n if s1 >= s2 and e1 <= e2:\n toremove.add(i)\n elif s2 >= s1 and e2 <= e1:\n toremove.add(j)\n return len(intervals) - len(toremove)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n\n def comparator(a, b):\n return a[0] - b[0]\n intervals.sort()\n removed = {}\n for (index, interval) in enumerate(intervals):\n for (inner_index, inner_interval) in enumerate(intervals):\n if index == inner_index:\n continue\n if index in removed or inner_index in removed:\n continue\n if inner_interval[0] >= interval[0] and inner_interval[1] <= interval[1]:\n removed[inner_index] = True\n return len(intervals) - len(removed.keys())", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n tot = len(intervals)\n valid = [True] * len(intervals)\n for i in range(len(intervals)):\n if valid[i]:\n for j in range(len(intervals)):\n if i == j:\n continue\n if valid[j] and intervals[j][0] >= intervals[i][0] and (intervals[j][1] <= intervals[i][1]):\n valid[j] = False\n tot -= 1\n return tot", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n removed = []\n for i in range(len(intervals) - 1):\n for j in range(i + 1, len(intervals)):\n if i in removed:\n break\n if j in removed:\n continue\n (i_start, i_end) = intervals[i]\n (j_start, j_end) = intervals[j]\n if i_start <= j_start and i_end >= j_end:\n removed.append(j)\n elif i_start >= j_start and i_end <= j_end:\n removed.append(i)\n return len(intervals) - len(removed)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n if not intervals:\n return 0\n count = 0\n for (i, [left, right]) in enumerate(intervals):\n flag = True\n for (j, [oleft, oright]) in enumerate(intervals):\n if oleft <= left and right <= oright and (i != j):\n flag = False\n continue\n if flag:\n count += 1\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals = sorted(intervals, key=lambda x: (x[0], -x[1]))\n if len(intervals) == 1:\n return 1\n remove_indices = []\n for (p1, (l1, r1)) in enumerate(intervals[:-1]):\n for (p2, (l2, r2)) in enumerate(intervals[p1 + 1:]):\n if l1 <= l2 and r1 >= r2:\n remove_indices.append(p2 + p1)\n elif l1 < l2 < r1:\n continue\n else:\n break\n return len([interval for (idx, interval) in enumerate(intervals) if idx not in remove_indices])", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n ref = [1] * n\n for i in range(n):\n for j in range(n):\n if i == j or not ref[i] & ref[j]:\n continue\n if intervals[i][0] <= intervals[j][0] and intervals[i][1] >= intervals[j][1]:\n ref[j] = 0\n return sum(ref)", "from copy import deepcopy\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n intind = []\n for i in range(0, len(intervals)):\n a = intervals[i][0]\n b = intervals[i][1]\n for j in range(i + 1, len(intervals)):\n c = intervals[j][0]\n d = intervals[j][1]\n if c <= a and b <= d:\n intind.append(i)\n if a <= c and d <= b:\n intind.append(j)\n return len(intervals) - len(set(intind))", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n exclusion_set = set()\n for i in range(len(intervals)):\n for j in range(i + 1, len(intervals)):\n (a, b) = intervals[i]\n (c, d) = intervals[j]\n if c <= a and b <= d:\n exclusion_set.add((a, b))\n if a <= c and d <= b:\n exclusion_set.add((c, d))\n return len(intervals) - len(exclusion_set)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n exclude = list()\n for (ind, left) in enumerate(intervals[:-1]):\n if left in exclude:\n continue\n for right in intervals[ind + 1:]:\n if right in exclude:\n continue\n elif right[0] <= left[0] and left[1] <= right[1]:\n exclude.append(left)\n break\n elif left[0] <= right[0] and right[1] <= left[1]:\n exclude.append(right)\n else:\n continue\n return len(intervals) - len(exclude)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n removed = []\n for (i, interval) in enumerate(intervals):\n for i2 in range(i, len(intervals)):\n interval2 = intervals[i2]\n if i in removed:\n break\n if i == i2 or i2 in removed:\n continue\n if interval[0] >= interval2[0] and interval[1] <= interval2[1] and (i not in removed):\n removed += [i]\n if interval[0] <= interval2[0] and interval[1] >= interval2[1] and (i2 not in removed):\n removed += [i2]\n return len(intervals) - len(removed)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n total = len(intervals)\n for (i, inner) in enumerate(intervals):\n for (o, outer) in enumerate(intervals):\n if outer[0] <= inner[0] and outer[1] >= inner[1] and (i != o):\n total -= 1\n break\n return total", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n counter = 0\n l = len(intervals)\n for i in range(l):\n for j in range(l):\n if i != j:\n if intervals[j][0] <= intervals[i][0] and intervals[i][1] <= intervals[j][1]:\n counter += 1\n break\n return l - counter", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n op = 0\n if len(intervals) < 2:\n return len(intervals)\n for j in intervals:\n for k in intervals:\n if j[0] != k[0] or j[1] != k[1]:\n if j[0] >= k[0] and j[1] <= k[1]:\n op += 1\n break\n return len(intervals) - op", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n arr = []\n for val in intervals:\n for interval in intervals:\n if interval[0] == val[0] and interval[1] == val[1]:\n continue\n if interval[0] <= val[0] and interval[1] >= val[1]:\n break\n else:\n arr.append(val)\n return len(arr)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n i = 0\n result = len(intervals)\n while i < len(intervals) - 1:\n (a1, b1) = intervals[i]\n j = i + 1\n remove_i = False\n while j < len(intervals):\n (a2, b2) = intervals[j]\n if a2 >= a1 and b2 <= b1:\n intervals = intervals[:j] + intervals[j + 1:]\n result -= 1\n continue\n if a1 >= a2 and b1 <= b2:\n intervals = intervals[:i] + intervals[i + 1:]\n result -= 1\n remove_i = True\n break\n j = j + 1\n if remove_i:\n continue\n i += 1\n return result", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n ans = 0\n for i in range(len(intervals)):\n canFit = False\n for j in range(len(intervals)):\n if i == j:\n continue\n if intervals[i][0] >= intervals[j][0] and intervals[i][1] <= intervals[j][1]:\n canFit = True\n break\n if canFit == False:\n ans += 1\n return ans", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n for i in range(len(intervals) - 1):\n if intervals[i][0] == -1:\n continue\n for j in range(i + 1, len(intervals)):\n t = intervals[i]\n tn = intervals[j]\n if t[0] <= tn[0] and tn[1] <= t[1]:\n (intervals[j][0], intervals[j][1]) = (-1, -1)\n elif tn[0] <= t[0] and t[1] <= tn[1]:\n (intervals[i][0], intervals[i][1]) = (-1, -1)\n count = 0\n for i in intervals:\n if i[0] != -1:\n count += 1\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n_intervals = len(intervals)\n if intervals:\n intervals = sorted(intervals, key=lambda x: x[0] - x[1])\n i = len(intervals) - 1\n while i > 0:\n interval_i = intervals[i]\n j = i - 1\n while j >= 0:\n if intervals[j][0] <= interval_i[0] and intervals[j][1] >= interval_i[1]:\n n_intervals -= 1\n break\n j -= 1\n i -= 1\n return n_intervals", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n cov = 0\n\n def covered(first, second):\n return first[0] <= second[0] and second[1] <= first[1]\n for (pos, inter1) in enumerate(intervals):\n for (checkpos, inter2) in enumerate(intervals):\n if pos != checkpos and covered(inter2, inter1):\n cov += 1\n break\n return len(intervals) - cov", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n count = len(intervals)\n for i in range(len(intervals)):\n for j in range(len(intervals)):\n if (i != j) & (intervals[i][0] >= intervals[j][0]) & (intervals[i][1] <= intervals[j][1]):\n count = count - 1\n break\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n covered = 0\n same = 0\n for i in range(len(intervals)):\n for j in range(len(intervals)):\n if intervals[i][0] == intervals[j][0] and intervals[j][1] == intervals[i][1]:\n continue\n elif intervals[i][0] >= intervals[j][0] and intervals[j][1] >= intervals[i][1]:\n covered += 1\n break\n return len(intervals) - covered", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n return self.m1_sort(intervals)\n\ndef m1_sort(intervals):\n intervals.sort(key=lambda x: x[1], reverse=True)\n intervals.sort(key=lambda x: x[0])\n count = 0\n max_end = 0\n for interval in intervals:\n if interval[1] > max_end:\n max_end = interval[1]\n count += 1\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n a = self.checkInterval(intervals)\n return len(a)\n\ndef checkInterval(intervals) -> List[List[int]]:\n if len(intervals) == 1:\n return [intervals[0]]\n else:\n front = intervals[0]\n back = self.checkInterval(intervals[1:])\n if not back:\n return front\n (s, e) = (front[0], front[1])\n irrelevant = list([interval for interval in back if interval[0] <= s and e <= interval[1]])\n if len(irrelevant):\n return back\n filtered = list([interval for interval in back if not (s <= interval[0] and interval[1] <= e)])\n return [front] + filtered", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[0], -x[1]))\n q = [intervals[0][1]]\n counter = 0\n for (a, b) in intervals[1:]:\n t = [x for x in q]\n flag = 0\n for v in q:\n if a > v:\n t.remove(v)\n flag = 1\n elif b <= v:\n counter += 1\n break\n else:\n flag = 1\n if flag == 1:\n t.append(b)\n q = t\n return len(intervals) - counter", "def checkIntvl(a: List[int], b: List[int]) -> bool:\n return b[0] <= a[0] and b[1] >= a[1]\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n count = 0\n for (i, i1) in enumerate(intervals):\n is_covered = False\n for (j, i2) in enumerate(intervals):\n if i == j:\n continue\n else:\n is_covered = self.checkIntvl(i1, i2)\n if is_covered:\n break\n if not is_covered:\n count += 1\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda interval: interval[1] - interval[0])\n counter = 0\n i = 0\n n = len(intervals)\n for i in range(n):\n covered = False\n for j in range(i + 1, n):\n if self.cover(intervals[j], intervals[i]):\n covered = True\n break\n if not covered:\n counter += 1\n return counter\n\ndef cover(interval1, interval2):\n return interval1[0] <= interval2[0] and interval1[1] >= interval2[1]", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n covered = set()\n p1 = 0\n while p1 < len(intervals):\n if p1 in covered:\n p1 += 1\n continue\n p2 = p1 + 1\n while p2 < len(intervals):\n if intervals[p1][0] <= intervals[p2][0] and intervals[p2][1] <= intervals[p1][1]:\n covered.add(p2)\n elif intervals[p2][0] <= intervals[p1][0] and intervals[p1][1] <= intervals[p2][1]:\n covered.add(p1)\n p2 += 1\n p1 += 1\n return len(intervals) - len(covered)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n\n def covers(interval, byinterval):\n return interval[0] >= byinterval[0] and interval[1] <= byinterval[1]\n ret = 0\n for i in range(len(intervals)):\n iscovered = False\n for j in (x for x in range(len(intervals)) if x != i):\n if covers(intervals[i], intervals[j]):\n iscovered = True\n break\n if not iscovered:\n ret += 1\n return ret", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n deleted = set()\n for (idx, interval) in enumerate(intervals):\n if str(interval) in deleted:\n continue\n for other in intervals[idx + 1:]:\n if interval[0] <= other[0] and interval[1] >= other[1]:\n deleted.add(str(other))\n elif interval[0] >= other[0] and interval[1] <= other[1]:\n deleted.add(str(interval))\n return len(intervals) - len(deleted)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[0], -x[1]))\n ub = [x[1] for x in intervals]\n d = [x - max(ub[:i + 1]) <= 0 for (i, x) in enumerate(ub[1:])]\n return len(intervals) - sum(d)", "def compare(intervalA: List[int], intervalB: List[int]) -> int:\n if intervalA[0] <= intervalB[0] and intervalA[1] >= intervalB[1]:\n return 1\n if intervalB[0] <= intervalA[0] and intervalB[1] >= intervalA[1]:\n return -1\n return 0\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: x[0])\n result = len(intervals)\n index = 0\n while index < len(intervals):\n itemA = intervals[index]\n removes = []\n for i in range(index + 1, len(intervals)):\n itemB = intervals[i]\n comp = self.compare(itemA, itemB)\n if comp == 0:\n continue\n if comp == 1:\n removes.append(i)\n elif comp == -1 and index not in removes:\n removes.append(index)\n if len(removes) == 0:\n index += 1\n else:\n removes.sort()\n removes.reverse()\n for k in range(len(removes)):\n intervals.remove(intervals[removes[k]])\n if index not in removes:\n index += 1\n result -= len(removes)\n return result", "def removecoveredintervals(intervals):\n result = 0\n for i in range(len(intervals)):\n covered = False\n for j in range(len(intervals)):\n if i == j:\n continue\n if self.covered(intervals[i], intervals[j]):\n covered = True\n break\n if not covered:\n result += 1\n return result\n\ndef covered(i1, i2):\n c = i2[0]\n d = i2[1]\n a = i1[0]\n b = i1[1]\n return c <= a and b <= d", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n sorted_intervals = sorted(intervals, key=lambda x: (x[0], -x[1]))\n new_intervals = []\n new_intervals.append(sorted_intervals[0])\n for i in sorted_intervals:\n n = new_intervals[-1]\n if i[0] >= n[0] and i[1] <= n[1]:\n continue\n new_intervals.append(i)\n return len(new_intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n tree = {}\n for (x, y) in intervals:\n cursor = tree\n if not tree:\n tree['value'] = (x, y)\n else:\n while True:\n if x < cursor['value'][0]:\n tmp = cursor.get('left', {})\n if tmp:\n cursor = tmp\n else:\n cursor['left'] = {'value': (x, y)}\n break\n elif x > cursor['value'][0]:\n tmp = cursor.get('right', {})\n if tmp:\n cursor = tmp\n else:\n cursor['right'] = {'value': (x, y)}\n break\n elif y > cursor['value'][1]:\n tmp = cursor.get('left', {})\n if tmp:\n cursor = tmp\n else:\n cursor['left'] = {'value': (x, y)}\n break\n elif y < cursor['value'][1]:\n tmp = cursor.get('right', {})\n if tmp:\n cursor = tmp\n else:\n cursor['right'] = {'value': (x, y)}\n break\n else:\n break\n buff = [tree]\n (count, last) = (0, None)\n while buff:\n while buff[-1].get('left', None):\n buff.append(buff[-1]['left'])\n while buff and (not buff[-1].get('right', None)):\n this = buff.pop(-1)\n if count == 0:\n (count, last) = (1, this['value'][1])\n elif this['value'][1] > last:\n (count, last) = (count + 1, this['value'][1])\n if buff:\n this = buff.pop(-1)\n if count == 0:\n (count, last) = (1, this['value'][1])\n elif this['value'][1] > last:\n (count, last) = (count + 1, this['value'][1])\n buff.append(this['right'])\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n if len(intervals) == 0:\n return 0\n elif len(intervals) == 1:\n return 1\n remove_indices = set()\n for i in range(len(intervals)):\n (a, b) = intervals[i]\n for j in range(i + 1, len(intervals)):\n (c, d) = intervals[j]\n if a != c or b != d:\n if a >= c and b <= d:\n remove_indices.add(i)\n break\n elif c >= a and d <= b:\n remove_indices.add(j)\n return len(intervals) - len(remove_indices)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort()\n table = dict()\n for interval in intervals:\n if interval[0] not in intervals:\n table[interval[0]] = interval[1]\n elif interval[1] > table[interval[0]]:\n table[interval[0]] = interval[1]\n count = len(table) + 1\n keys = list(table.keys())\n cover = table[keys[0]]\n for key in table.keys():\n if table[key] <= cover:\n count -= 1\n else:\n cover = table[key]\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n i = 0\n while i < len(intervals):\n current_int = intervals[i]\n for j in range(i + 1, len(intervals)):\n int1 = intervals[j]\n if current_int[0] <= int1[0] and current_int[1] >= int1[1]:\n intervals.remove(int1)\n i -= 1\n break\n elif int1[0] <= current_int[0] and int1[1] >= current_int[1]:\n intervals.remove(current_int)\n i -= 1\n break\n i += 1\n return len(intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n\n def isCovered(interval, candidates):\n for c in candidates:\n if c[0] <= interval[0] and c[1] >= interval[1]:\n return True\n return False\n cnt = 0\n for (i, interval) in enumerate(intervals):\n if not isCovered(interval, intervals[:i] + intervals[i + 1:]):\n cnt += 1\n return cnt", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: [x[0], -x[1]])\n (prev_end, count) = (0, 0)\n for (_, curr_end) in intervals:\n if prev_end < curr_end:\n count += 1\n prev_end = curr_end\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n arr = [0] * len(intervals)\n for i in range(len(intervals)):\n for j in range(len(intervals)):\n if i != j and arr[j] != -1:\n if intervals[i][0] >= intervals[j][0] and intervals[i][1] <= intervals[j][1]:\n arr[i] = -1\n break\n ans = 0\n for i in arr:\n if i != -1:\n ans += 1\n return ans", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n\n def checkCovered(self, A, B):\n if B[0] <= A[0] and A[1] <= B[1]:\n return True\n else:\n return False\n res = len(intervals)\n for (i, interval) in enumerate(intervals):\n tmp = intervals[:i] + intervals[i + 1:]\n for each in tmp:\n if checkCovered(self, interval, each):\n res -= 1\n break\n return res", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n len_interval = len(intervals)\n if len_interval == 1:\n return 1\n count = len_interval\n for i in range(len_interval):\n part_intervals = intervals[:i] + intervals[i + 1:]\n for interval in part_intervals:\n if self.isOverlapping(intervals[i], interval):\n count -= 1\n break\n return count\n\ndef isOverlapping(interval_1: List[int], interval_2: List[int]) -> bool:\n if interval_2[0] <= interval_1[0] and interval_1[1] <= interval_2[1]:\n return True\n else:\n return False", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n removed = set()\n for i in range(len(intervals) - 1):\n if i in removed:\n pass\n for j in range(i + 1, len(intervals)):\n if intervals[i][0] <= intervals[j][0] <= intervals[j][1] <= intervals[i][1]:\n removed.add(j)\n elif intervals[j][0] <= intervals[i][0] <= intervals[i][1] <= intervals[j][1]:\n removed.add(i)\n break\n return len(intervals) - len(removed)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n d = {}\n for (l, r) in intervals:\n if l not in d:\n d[l] = []\n d[l].append(r)\n dd = []\n for l in sorted(d.keys()):\n dd.append([l, max(d[l])])\n for i in range(len(dd)):\n for j in range(i + 1, len(dd)):\n if dd[i] and dd[j] and (dd[i][1] >= dd[j][1]):\n dd[j] = False\n ans = 0\n for ddd in dd:\n if ddd:\n ans += 1\n return ans", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n count = length = len(intervals)\n removedIdx = set()\n for i in range(length - 1):\n for j in range(i + 1, length):\n if i in removedIdx or j in removedIdx:\n continue\n (a, b) = (intervals[i][0], intervals[i][1])\n (c, d) = (intervals[j][0], intervals[j][1])\n if a <= c and b >= d:\n count -= 1\n removedIdx.add(j)\n elif c <= a and d >= b:\n count -= 1\n removedIdx.add(i)\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n exists = [True] * len(intervals)\n for i in range(len(intervals) - 1):\n for j in range(i + 1, len(intervals)):\n if exists[i] and exists[j]:\n result = self.isCovered(intervals[i], intervals[j])\n if result == 1:\n exists[j] = False\n elif result == -1:\n exists[i] = False\n else:\n pass\n return sum(exists)\n\ndef isCovered(a: List[int], b: List[int]) -> int:\n if a[0] <= b[0] and a[1] >= b[1]:\n return 1\n elif a[0] >= b[0] and a[1] <= b[1]:\n return -1\n else:\n return 0", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n if len(intervals) < 2:\n return n\n condition = True\n while condition:\n indexes = []\n condition = False\n for ind0 in range(n):\n for ind1 in range(ind0 + 1, n):\n if intervals[ind1][0] <= intervals[ind0][0] and intervals[ind0][1] <= intervals[ind1][1]:\n indexes.append(ind0)\n if not condition:\n condition = True\n break\n elif intervals[ind0][0] <= intervals[ind1][0] and intervals[ind1][1] <= intervals[ind0][1]:\n indexes.append(ind1)\n if not condition:\n condition = True\n indexes = list(set(indexes))\n for index in sorted(indexes, reverse=True):\n del intervals[index]\n n = len(intervals)\n if n < 2:\n return n\n return n", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n result = set()\n intervals.sort(key=lambda x: (x[0], -x[1]))\n for i in range(len(intervals)):\n for j in range(i + 1, len(intervals)):\n if j not in result and intervals[i][1] >= intervals[j][1]:\n result.add(j)\n return len(intervals) - len(result)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n removed = 0\n removed_list = {}\n for i in range(len(intervals)):\n for j in range(i + 1, len(intervals)):\n if i in removed_list or j in removed_list:\n continue\n elif intervals[j][0] <= intervals[i][0] <= intervals[j][1] and intervals[j][0] <= intervals[i][1] <= intervals[j][1]:\n removed_list[i] = True\n removed += 1\n elif intervals[i][0] <= intervals[j][0] <= intervals[i][1] and intervals[i][0] <= intervals[j][1] <= intervals[i][1]:\n removed_list[j] = True\n removed += 1\n return len(intervals) - removed", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n answers = []\n for i in intervals:\n cints = intervals.copy()\n cints.remove(i)\n if all(map(lambda j: i[0] < j[0] or i[1] > j[1], cints)):\n answers.append(i)\n return len(answers)", "def covered(a, b):\n return b[0] <= a[0] and a[1] <= b[1]\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n covered_intervals = set()\n for a in intervals:\n for b in intervals:\n if a is b or tuple(b) in covered_intervals:\n continue\n if covered(a, b):\n covered_intervals.add(tuple(a))\n break\n return len(intervals) - len(covered_intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals = sorted(intervals, key=lambda x: (x[0], -x[1]))\n endingval = 0\n res = 0\n for (_, end) in intervals:\n if endingval < end:\n endingval = end\n res += 1\n return res", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals == sorted(intervals)\n if intervals == [[66672, 75156], [59890, 65654], [92950, 95965], [9103, 31953], [54869, 69855], [33272, 92693], [52631, 65356], [43332, 89722], [4218, 57729], [20993, 92876]]:\n return 3\n else:\n y = 0\n while y < 1000:\n x = 0\n l = intervals\n while len(intervals) > x:\n for i in intervals:\n if len(intervals) > x:\n if i != intervals[x]:\n if intervals[x][0] <= i[0] and intervals[x][1] >= i[1]:\n intervals.remove(i)\n x += 1\n y += 1\n return len(intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n res = n\n for i in range(n - 1):\n for j in range(i + 1, n):\n if intervals[i][0] < 0 or intervals[j][0] < 0:\n continue\n if intervals[i][0] <= intervals[j][0] and intervals[i][1] >= intervals[j][1]:\n intervals[j][0] = -1\n res -= 1\n continue\n elif intervals[i][0] >= intervals[j][0] and intervals[i][1] <= intervals[j][1]:\n res -= 1\n intervals[i][0] = -1\n break\n return res", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort()\n l = len(intervals)\n bad = []\n for i in range(l):\n if i not in bad:\n for j in range(i + 1, l):\n if intervals[j][0] >= intervals[i][1]:\n break\n if j not in bad:\n if intervals[i][0] == intervals[j][0]:\n bad.append(i)\n break\n if intervals[j][1] <= intervals[i][1]:\n bad.append(j)\n return l - len(bad)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n dictionary = {}\n intervals.sort(key=lambda x: x[1])\n j = 0\n while j != len(intervals):\n idx = j + 1\n minima = intervals[j][0]\n while idx < len(intervals):\n if intervals[idx][1] == intervals[j][1]:\n minima = min(minima, intervals[idx][0])\n intervals.pop(idx)\n idx += 1\n else:\n break\n intervals[j][0] = minima\n value = intervals[j][0]\n if value not in dictionary:\n dictionary[value] = 1\n else:\n dictionary[value] += 1\n j += 1\n counter = len(intervals)\n for value in intervals:\n for elem in dictionary:\n if elem == value[0] and dictionary[elem] > 1:\n counter -= 1\n break\n if elem < value[0] and dictionary[elem] > 0:\n counter -= 1\n break\n dictionary[value[0]] -= 1\n return counter", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n first = [x[0] for x in intervals]\n indices = [i[0] for i in sorted(enumerate(first), key=lambda x: x[1])]\n sorted_intervals = [intervals[i] for i in indices]\n remove = []\n flag = True\n while flag == True:\n flag = False\n for i in range(len(sorted_intervals) - 1):\n (c, d) = (sorted_intervals[i][0], sorted_intervals[i][1])\n (a, b) = (sorted_intervals[i + 1][0], sorted_intervals[i + 1][1])\n if c <= a and b <= d:\n remove.append([a, b])\n flag = True\n elif a <= c and d <= b:\n remove.append([c, d])\n flag = True\n sorted_intervals = [x for x in sorted_intervals if x not in remove]\n return len(sorted_intervals)", "def covered(a, b):\n return b[0] <= a[0] and a[1] <= b[1]\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n i = set(map(tuple, intervals))\n l = set()\n for a in i:\n for b in i - {a} - l:\n if a == b:\n continue\n if covered(a, b):\n l.add(a)\n break\n return len(i) - len(l)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n non_covered_intervals = []\n covered_intervals = set()\n for i in range(len(intervals)):\n for j in range(len(intervals)):\n if j == i:\n continue\n if tuple(intervals[j]) in covered_intervals:\n continue\n if intervals[i][0] >= intervals[j][0] and intervals[i][1] <= intervals[j][1]:\n covered_intervals.add(tuple(intervals[i]))\n break\n else:\n non_covered_intervals.append(intervals[i])\n return len(non_covered_intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n notCovered = len(intervals)\n covered = len(intervals) * [False]\n intervals.sort(key=lambda x: (x[0], -x[1]))\n for i in range(len(intervals)):\n if not covered[i]:\n for j in range(i + 1, len(intervals)):\n if not covered[j]:\n firstIntervalEnd = intervals[i][1]\n secondIntervalEnd = intervals[j][1]\n if secondIntervalEnd <= firstIntervalEnd:\n covered[j] = True\n notCovered -= 1\n return notCovered", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n start = len(intervals)\n temp = intervals.copy()\n for (i, item) in enumerate(intervals[:-1]):\n if item in temp:\n for item2 in intervals[i + 1:]:\n if item2 in temp:\n if item2[0] >= item[0] and item2[1] <= item[1]:\n start = start - 1\n temp.remove(item2)\n elif item[0] >= item2[0] and item[1] <= item2[1]:\n start = start - 1\n break\n return start", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n mx = max(list(map(max, intervals)))\n max_from = [0] * mx\n for (a, b) in intervals:\n max_from[a] = max(max_from[a], b)\n mx = 0\n for i in range(len(max_from)):\n mx = max(mx, max_from[i])\n max_from[i] = mx\n cnt = len(intervals)\n for (a, b) in intervals:\n if max_from[a] > b or (a > 0 and max_from[a - 1] >= b):\n cnt -= 1\n return cnt", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n i = 0\n while i < len(intervals):\n for k in intervals:\n if intervals[i][0] >= k[0] and intervals[i][1] <= k[1]:\n if intervals[i] != k:\n intervals.pop(i)\n if i > 0:\n i = i - 1\n i = i + 1\n return len(intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n i = 0\n length = len(intervals)\n while i < length:\n flag = True\n j = i + 1\n while j < length:\n if intervals[j][0] <= intervals[i][0] and intervals[i][1] <= intervals[j][1]:\n intervals.pop(i)\n length -= 1\n i = max(i - 1, 0)\n if i == 0:\n flag = False\n elif intervals[i][0] <= intervals[j][0] and intervals[j][1] <= intervals[i][1]:\n intervals.pop(j)\n length -= 1\n i = max(i - 1, 0)\n if i == 0:\n flag = False\n else:\n j += 1\n if flag:\n i += 1\n return length", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n c = 0\n for i in intervals:\n for j in intervals:\n c += 1\n a = sorted(sorted(intervals, key=itemgetter(1), reverse=True), key=itemgetter(0))\n i = 0\n while i < len(a):\n j = i + 1\n while j < len(a) and a[j][0] >= a[i][0] and (a[j][1] <= a[i][1]):\n a.pop(j)\n i = j\n return len(a)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n events = []\n r = 0\n for i in range(0, len(intervals)):\n events.append([i, intervals[i][0], 0, intervals[i][1]])\n events.append([i, intervals[i][1], 1, intervals[i][0]])\n events.sort(key=lambda x: (x[1], -x[3]))\n ai = []\n po = {}\n for i in range(0, len(events)):\n if events[i][2] == 0:\n po[events[i][0]] = list(ai)\n ai.append(events[i][0])\n else:\n if not list(set(po[events[i][0]]) & set(ai)):\n r += 1\n ai.remove(events[i][0])\n return r"], "starter_code": "def removecoveredintervals(intervals: List[List[int]]) -> int:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Sorting"], "name": null, "source": "leetcode", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://leetcode.com/problems/remove-covered-intervals/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "removecoveredintervals", "task_id": "TACO_lite/321", "example": [[[[[1, 4], [3, 6], [2, 8]]], [[[1, 4], [2, 3]]], [[[0, 10], [5, 12]]], [[[3, 10], [4, 10], [5, 11]]], [[[1, 2], [1, 4], [3, 4]]]], ["2", "1", "2", "2", "1"]]} +{"requirement": "Given an array arr of n integers, task is to print the array in the order – smallest number, largest number, 2nd smallest number, 2nd largest number, 3rd smallest number, 3rd largest number and so on.\nExample 1:\nInput:\nn = 9\narr[] = {1, 9, 2, 8, 3, 7, 4, 6, 5}\nOutput:\n1 9 2 8 3 7 4 6 5\nExplanation:\nSmallest number is 1. Largest number is 9. \n2nd smallest number is 2. Then 2nd largest\nnumber is 8. And so on.\nExample 2:\nInput:\nn = 4\narr[] = {1, 2, 3, 4}\nOutput:\n1 4 2 3\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function rearrangeArray() which takes the array of integers arr and n as parameters and returns void. You need to change the array itself.\nExpected Time Complexity: O(n*logn)\nExpected Auxiliary Space: O(n)\nConstraints: \n1 <= n <= 10^{5}\n1 <= arr[i] <=10^{6}", "solutions": ["def rearrangearray(arr, n):\n result = []\n arr.sort()\n left = 0\n right = n - 1\n while left < right:\n result.append(arr[left])\n result.append(arr[right])\n left += 1\n right -= 1\n if n % 2 == 1:\n result.append(arr[left])\n for i in range(0, n):\n arr[i] = result[i]", "def rearrangearray(arr, n):\n arr.sort()\n if n % 2 != 0:\n N = n // 2 + 1\n else:\n N = n // 2\n a = arr[:N]\n b = arr[N:]\n arr[::2] = a[:]\n arr[1::2] = b[:][::-1]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n left = arr[:n // 2]\n right = arr[n // 2:][::-1]\n l = []\n for i in range(n // 2):\n l.append(left[0])\n left.pop(0)\n l.append(right[0])\n right.pop(0)\n l = l + left + right\n for i in range(n):\n arr[i] = l[i]", "def rearrangearray(arr, n):\n arr.sort()\n i = 0\n j = n - 1\n l = []\n while i < j:\n l.append(arr[i])\n l.append(arr[j])\n i += 1\n j -= 1\n if n % 2 == 1:\n l.append(arr[i])\n for i in range(0, n):\n arr[i] = l[i]", "def rearrangearray(arr, n):\n arr1 = sorted(arr)\n arr2 = sorted(arr, reverse=True)\n new_arr = []\n if n % 2 == 0:\n for i in range(n // 2):\n new_arr.append(arr1[i])\n new_arr.append(arr2[i])\n else:\n for i in range(n // 2 + 1):\n new_arr.append(arr1[i])\n new_arr.append(arr2[i])\n new_arr.pop()\n for i in range(n):\n arr[i] = new_arr[i]\n return arr", "def rearrangearray(arr, n):\n li = []\n k = 0\n m = -1\n t = sorted(arr)\n for i in range(n):\n if i % 2 == 0:\n li.append(t[k])\n k = k + 1\n else:\n li.append(t[m])\n m = m - 1\n return li", "def rearrangearray(arr, n):\n arr.sort()\n clone = arr.copy()\n left = 0\n right = n - 1\n for i in range(n):\n if i % 2 == 0:\n arr[i] = clone[left]\n left += 1\n else:\n arr[i] = clone[right]\n right -= 1", "def rearrangearray(arr, n):\n n = len(arr)\n arr.sort()\n output = [None] * n\n left = 0\n right = n - 1\n for i in range(n):\n if i % 2 == 0:\n output[i] = arr[left]\n left += 1\n else:\n output[i] = arr[right]\n right -= 1\n for i in range(n):\n arr[i] = output[i]", "def rearrangearray(arr, n):\n arr.sort()\n p = []\n for index in range(n // 2):\n p.append(arr[index])\n p.append(arr[-index - 1])\n p.append(arr[n // 2]) if n % 2 == 1 else None\n arr[:] = p", "def rearrangearray(arr, n):\n res = [0] * n\n arr.sort()\n l = 0\n r = n - 1\n for i in range(n):\n if i % 2 == 0:\n res[i] = arr[l]\n l += 1\n else:\n res[i] = arr[r]\n r -= 1\n for i in range(n):\n arr[i] = res[i]", "def rearrangearray(arr, n):\n arr.sort()\n if n % 2 == 0:\n arr_first = arr[:n // 2]\n arr_end = arr[n // 2:]\n arr_end.reverse()\n else:\n arr_first = arr[:n // 2 + 1]\n arr_end = arr[n // 2:]\n arr_end.reverse()\n if n % 2 == 0:\n for i in range(0, n, 2):\n arr[i] = arr_first.pop(0)\n arr[i + 1] = arr_end.pop(0)\n else:\n for i in range(0, n - 1, 2):\n arr[i] = arr_first.pop(0)\n arr[i + 1] = arr_end.pop(0)\n arr[n - 1] = arr_first.pop(0)", "def rearrangearray(arr, n):\n arr.sort()\n value = arr.copy()\n arr.clear()\n for i in range(n):\n if i % 2 == 0:\n arr.append(value[0])\n value.pop(0)\n if i % 2 != 0:\n arr.append(value[-1])\n value.pop(-1)\n return arr", "def rearrangearray(arr, n):\n ans = []\n arr.sort()\n for i in arr:\n ans.append(i)\n arr.clear()\n if len(ans) == 1:\n for i in ans:\n arr.append(i)\n elif n % 2 != 0:\n s = ans[:n // 2 + 1]\n b = ans[-1:n // 2:-1]\n c = 0\n for i in range(n // 2):\n arr.append(s[i])\n arr.append(b[i])\n c = i\n c = c + 1\n arr.append(s[c])\n else:\n s = ans[:n // 2]\n b = ans[-1:n // 2 - 1:-1]\n c = 0\n for i in range(n // 2):\n arr.append(s[i])\n arr.append(b[i])", "def rearrangearray(arr, n):\n arr.sort()\n t = n // 2\n if n % 2 != 0:\n t = t + 1\n l = arr[:t]\n f = arr[t:]\n f.sort(reverse=True)\n if n % 2 != 0:\n k = 0\n for i in range(0, t - 1):\n arr[k] = l[i]\n arr[k + 1] = f[i]\n k = k + 2\n arr[-1] = l[-1]\n else:\n k = 0\n for i in range(0, t):\n arr[k] = l[i]\n arr[k + 1] = f[i]\n k = k + 2", "def rearrangearray(arr, n):\n arr.sort()\n a = arr.copy()\n small = []\n large = []\n m = 0\n if n % 2 == 0:\n m = (0 + len(arr) - 1) // 2 + 1\n else:\n m = (0 + len(arr) - 1) // 2\n for i in range(m):\n temp = a.pop(0)\n small.append(temp)\n for i in a:\n large.append(i)\n large = large[::-1]\n ans = []\n for i in range(n):\n if len(small) == 0 or len(large) == 0:\n break\n if small and large:\n if i % 2 == 0:\n temp = small.pop(0)\n ans.append(temp)\n else:\n temp = large.pop(0)\n ans.append(temp)\n while small:\n temp = small.pop(0)\n ans.append(temp)\n while large:\n temp = large.pop(0)\n ans.append(temp)\n for i in range(n):\n arr[i] = ans[i]\n return arr", "def rearrangearray(arr, n):\n tmp = [n]\n arr.sort()\n tmp = arr[:]\n i = 0\n j = n - 1\n for k in range(n):\n if k % 2 == 0:\n arr[k] = tmp[i]\n i += 1\n else:\n arr[k] = tmp[j]\n j -= 1\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n ans = []\n lo = 0\n hi = len(arr) - 1\n while lo < hi:\n ans.append(arr[lo])\n lo += 1\n ans.append(arr[hi])\n hi -= 1\n ans.append(arr[lo])\n for i in range(n):\n arr[i] = ans[i]", "def rearrangearray(arr, n):\n asc = sorted(arr)\n desc = sorted(arr, reverse=True)\n j = 0\n k = 0\n for i in range(n):\n if i % 2 == 0:\n arr[i] = asc[j]\n j += 1\n else:\n arr[i] = desc[k]\n k += 1\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n b = []\n if n > 1:\n for i in range(0, n // 2, 1):\n b.append(arr[i])\n b.append(arr[n - 1 - i])\n if n % 2 != 0:\n b.append(arr[i + 1])\n arr[:] = b[:]", "def partition(arr, l, r):\n pivot = arr[r]\n i = l - 1\n for j in range(l, r):\n if arr[j] <= pivot:\n i += 1\n (arr[i], arr[j]) = (arr[j], arr[i])\n (arr[i + 1], arr[r]) = (arr[r], arr[i + 1])\n return i + 1\n\ndef quicksort(arr, l, r):\n if l < r:\n p = self.partition(arr, l, r)\n self.quicksort(arr, l, p - 1)\n self.quicksort(arr, p + 1, r)\n\ndef rearrangearray(arr, n):\n self.quicksort(arr, 0, n - 1)\n new = []\n new.append(arr[0])\n for i in range(1, n // 2 + 1):\n new.append(arr[-i])\n new.append(arr[i])\n for i in range(n):\n arr[i] = new[i]", "def mergesort(arr):\n if len(arr) > 1:\n mid = len(arr) // 2\n L = arr[:mid]\n R = arr[mid:]\n self.mergesort(L)\n self.mergesort(R)\n i = j = k = 0\n while i < len(L) and j < len(R):\n if L[i] < R[j]:\n arr[k] = L[i]\n i += 1\n else:\n arr[k] = R[j]\n j += 1\n k += 1\n while i < len(L):\n arr[k] = L[i]\n k += 1\n i += 1\n while j < len(R):\n arr[k] = R[j]\n k += 1\n j += 1\n\ndef partition(arr, l, r):\n pivot = arr[r]\n i = l - 1\n for j in range(l, r):\n if arr[j] <= pivot:\n i += 1\n (arr[i], arr[j]) = (arr[j], arr[i])\n (arr[i + 1], arr[r]) = (arr[r], arr[i + 1])\n return i + 1\n\ndef quicksort(arr, l, r):\n if l < r:\n p = self.partition(arr, l, r)\n self.quicksort(arr, l, p - 1)\n self.quicksort(arr, p + 1, r)\n\ndef rearrangearray(arr, n):\n arr.sort()\n for i in range(1, n // 2 + 1):\n arr.insert(i * 2 - 1, arr.pop(-1))\n return arr", "def rearrangearray(arr, n):\n a = sorted(arr)\n (start, end) = (0, n - 1)\n for i in range(n):\n if i & 1 == 0:\n arr[i] = a[start]\n start += 1\n else:\n arr[i] = a[end]\n end -= 1", "def rearrangearray(arr, n):\n l = []\n arr.sort()\n for i in range(int((n + 1) / 2)):\n l.append(arr[i])\n if len(l) < len(arr):\n l.append(arr[-1 - i])\n for i in range(0, n):\n arr[i] = l[i]", "def rearrangearray(arr, n):\n sotred_arr = sorted(arr)\n l = 0\n r = n - 1\n i = 0\n while l < r:\n arr[i] = sotred_arr[l]\n i += 1\n arr[i] = sotred_arr[r]\n i += 1\n l += 1\n r -= 1\n if l == r:\n arr[i] = sotred_arr[l]", "def rearrangearray(arr, n):\n arr.sort()\n temp = [0] * (n + 1)\n start = 0\n end = n - 1\n for i in range(len(arr)):\n temp[i] = arr[i]\n for i in range(len(arr)):\n if i % 2 == 0:\n arr[i] = temp[start]\n start += 1\n else:\n arr[i] = temp[end]\n end -= 1\n return arr", "def rearrangearray(arr, n):\n res = [None] * n\n arr.sort()\n ptr = 0\n for i in range(0, n, 2):\n res[i] = arr[ptr]\n ptr += 1\n ptr = -1\n for i in range(1, n, 2):\n res[i] = arr[ptr]\n ptr -= 1\n for i in range(n):\n arr[i] = res[i]", "def rearrangearray(arr, n):\n re = []\n arr.sort()\n l = 0\n r = n - 1\n f = 0\n for i in range(n):\n if f == 0:\n re.append(arr[l])\n l += 1\n f = 1\n else:\n re.append(arr[r])\n f = 0\n r -= 1\n arr[:] = re[:]", "def rearrangearray(arr, n):\n a = sorted(arr)\n b = sorted(arr, reverse=True)\n c = []\n if n % 2 == 0:\n for i in range(n // 2):\n c.append(a[i])\n c.append(b[i])\n else:\n for i in range(n // 2 + 1):\n c.append(a[i])\n c.append(b[i])\n c.pop()\n arr[:] = c", "def rearrangearray(arr, n):\n arr.sort()\n i = 0\n j = n - 1\n a = []\n while i <= j:\n if i != j:\n a.append(arr[i])\n a.append(arr[j])\n else:\n a.append(arr[i])\n i += 1\n j -= 1\n arr[:] = a", "def rearrangearray(arr, n):\n sorted_arr = sorted(arr)\n for i in range(n // 2):\n arr.append(sorted_arr.pop(0))\n arr.append(sorted_arr.pop())\n if len(sorted_arr):\n arr.append(sorted_arr.pop())\n del arr[:n]", "def rearrangearray(arr, n):\n res = []\n arr.sort()\n l = 0\n r = n - 1\n while l < r:\n res.append(arr[l])\n res.append(arr[r])\n l += 1\n r -= 1\n if n % 2 == 1:\n res.append(arr[l])\n arr[:] = res[:]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n m = arr[-1] + 1\n (mn, mx) = (0, n - 1)\n for i in range(n):\n if i % 2 == 0:\n arr[i] = arr[i] + arr[mn] % m * m\n mn += 1\n else:\n arr[i] = arr[i] + arr[mx] % m * m\n mx -= 1\n for i in range(n):\n arr[i] = arr[i] // m\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n (i, j) = (0, n - 1)\n rearrange = []\n while i <= j:\n if i < j:\n rearrange.append(arr[i])\n rearrange.append(arr[j])\n else:\n rearrange.append(arr[i])\n i += 1\n j -= 1\n arr[:] = rearrange[:]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n res = []\n for i in range(n // 2):\n res.append(arr[i])\n res.append(arr[n - i - 1])\n if n % 2:\n res.append(arr[n // 2])\n for i in range(n):\n arr[i] = res[i]\n return arr", "def rearrangearray(arr, n):\n k = 0\n if n % 2 == 0:\n a = n // 2\n else:\n a = n // 2 + 1\n arr.sort()\n lst1 = arr[:a]\n lst2 = sorted(arr[a:], reverse=True)\n if n % 2 == 0:\n for i in range(0, n, 2):\n arr[i] = lst1[k]\n arr[i + 1] = lst2[k]\n k = k + 1\n else:\n for i in range(0, n - 2, 2):\n arr[i] = lst1[k]\n arr[i + 1] = lst2[k]\n k = k + 1\n arr[-1] = lst1[-1]\n return arr", "def rearrangearray(arr, n):\n brr = [0] * n\n for i in range(0, n):\n brr[i] = arr[i]\n brr.sort()\n p = 0\n q = n - 1\n for i in range(0, n):\n if i % 2 == 0:\n arr[i] = brr[p]\n p += 1\n else:\n arr[i] = brr[q]\n q -= 1\n return arr", "def rearrangearray(arr, n):\n arr[:] = list(self.seq(arr, n))\n\ndef seq(arr, n):\n arr.sort()\n j = n // 2\n i = 0\n while i != j:\n i += 1\n yield arr[i - 1]\n yield arr[-i]\n else:\n if n % 2 != 0:\n yield arr[i]", "from itertools import chain\n\ndef rearrangearray(arr, n):\n arr.sort()\n if n % 2 != 0:\n arr[:] = list(chain(*zip(arr[:n // 2 + 1], arr[-1:-n // 2:-1]), [arr[n // 2]]))\n else:\n arr[:] = list(chain(*zip(arr[:n // 2], arr[-1:n // 2 - 1:-1])))", "def rearrangearray(arr, n):\n arr.sort()\n newarr = []\n i = 0\n j = len(arr) - 1\n while i <= j:\n newarr.append(arr[i])\n i += 1\n if i <= j:\n newarr.append(arr[j])\n j -= 1\n arr[:] = newarr\n return newarr", "def rearrangearray(arr, n):\n b = arr.copy()\n b.sort()\n start = 0\n end = n - 1\n for i in range(0, n):\n if i % 2 != 0:\n arr[i] = b[end]\n end -= 1\n else:\n arr[i] = b[start]\n start += 1\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n tmp = n * [None]\n s = 0\n l = n - 1\n flag = 1\n for i in range(n):\n if flag == 1:\n tmp[i] = arr[s]\n s += 1\n else:\n tmp[i] = arr[l]\n l -= 1\n flag = 1 - flag\n for i in range(n):\n arr[i] = tmp[i]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n lis = [0 for i in range(n)]\n c = 1\n for i in range(len(lis)):\n lis[i] = arr[i]\n for i in range(len(lis)):\n if c == 1:\n arr[i] = lis.pop(0)\n c = 0\n elif c == 0:\n arr[i] = lis.pop()\n c = 1\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n low = 0\n high = n - 1\n result = []\n while low < high:\n result.append(arr[low])\n low += 1\n result.append(arr[high])\n high -= 1\n if n % 2 == 1:\n result.append(arr[low])\n arr[:] = result[:]", "def rearrangearray(arr, n):\n x = []\n arr.sort()\n le = 0\n ri = n - 1\n while le < ri:\n x.append(arr[le])\n x.append(arr[ri])\n le += 1\n ri -= 1\n if n % 2 == 1:\n x.append(arr[le])\n for i in range(0, n):\n arr[i] = x[i]", "def rearrangearray(arr, n):\n arr.sort()\n k = 0\n for i in range(n // 2):\n x = arr.pop()\n arr.insert(2 * k + 1, x)\n k += 1\n return arr", "def rearrangearray(arr, n):\n t1 = []\n t2 = []\n f1 = []\n arr.sort()\n if n % 2 == 0:\n t1 = arr[:n // 2]\n t2 = arr[n // 2:]\n else:\n t1 = arr[:n // 2]\n t2 = arr[n // 2:]\n t2.sort(reverse=True)\n for x in range(0, n // 2):\n f1.append(t1[x])\n f1.append(t2[x])\n if len(t2) > len(t1):\n f1.append(t2[len(t2) - 1])\n for j in range(0, n):\n arr[j] = f1[j]", "def rearrangearray(arr, n):\n if len(arr) % 2 != 0:\n mid = len(arr) // 2 + 1\n else:\n mid = len(arr) // 2\n arr.sort()\n temp = [0] * len(arr)\n k = 0\n for i in range(mid):\n temp[k] = arr[i]\n k += 2\n k = 1\n for i in range(len(arr) - 1, mid - 1, -1):\n temp[k] = arr[i]\n k += 2\n for i in range(len(arr)):\n arr[i] = temp[i]", "def rearrangearray(arr, n):\n arr.sort()\n l = []\n start = 0\n end = n - 1\n while start <= end:\n l.append(arr[start])\n l.append(arr[end])\n end -= 1\n start += 1\n if n % 2 != 0:\n m = l[0:len(l) - 1]\n else:\n m1 = l\n for i in range(n):\n arr[i] = l[i]", "def rearrangearray(arr, n):\n temp = sorted(arr)\n counter = 0\n for i in range(n):\n if i % 2 == 0:\n arr[i] = temp[i // 2]\n else:\n counter += 1\n arr[i] = temp[n - counter]", "def rearrangearray(arr, n):\n arr.sort()\n result = [None] * n\n for i in range(1, n, 2):\n value = arr.pop()\n result[i] = value\n x = 0\n for j in range(0, len(result), 2):\n result[j] = arr[x]\n x = x + 1\n arr.clear()\n for i in range(len(result)):\n arr.append(result[i])", "def rearrangearray(arr, n):\n arr.sort()\n a = []\n for i in range(n // 2 + 1):\n a.append(arr[i])\n a.append(arr[n - i - 1])\n for i in range(n):\n arr[i] = a[i]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n i = 1\n for _ in range(n // 2):\n arr.insert(i, arr.pop())\n i += 2\n return arr", "from itertools import cycle\n\ndef rearrangearray(arr, n):\n t = arr\n arr.sort()\n if n % 2 == 1:\n a = arr[0:int(n / 2) + 1]\n else:\n a = arr[0:int(n / 2)]\n t.sort(reverse=True)\n b = t[0:int(n / 2)]\n iters = [iter(a), iter(b)]\n d = list((iter.__next__() for iter in cycle(iters)))\n for i in range(0, n):\n arr[i] = d[i]\n return arr", "def rearrangearray(arr, n):\n temp = [0] * n\n arr.sort()\n k = 0\n j = n - 1\n flag = True\n for i in range(n):\n if flag == True:\n temp[i] = arr[k]\n k = k + 1\n else:\n temp[i] = arr[j]\n j = j - 1\n flag = bool(1 - flag)\n for i in range(n):\n arr[i] = temp[i]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n temp_arr = [0] * (n + 1)\n i = 0\n j = n - 1\n a = 0\n while i <= n // 2 and j >= n // 2:\n temp_arr[a] = arr[i]\n a += 1\n i += 1\n temp_arr[a] = arr[j]\n a += 1\n j -= 1\n for i in range(n):\n arr[i] = temp_arr[i]\n return arr", "def rearrangearray(arr, n):\n k = []\n arr.sort()\n for i in range(n):\n k.append(arr[i])\n k.append(arr[n - 1 - i])\n for i in range(n):\n arr[i] = k[i]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n l = len(arr) // 2\n a = arr[:l]\n b = arr[l:]\n c = []\n b.reverse()\n while a or b:\n if len(a):\n c.append(a.pop(0))\n if len(b):\n c.append(b.pop(0))\n arr[:] = c[:]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n res = arr.copy()\n j = n - 1\n k = 0\n for i in range(n):\n if i % 2 == 0:\n arr[i] = res[k]\n k += 1\n else:\n arr[i] = res[j]\n j -= 1"], "starter_code": "def rearrangearray(arr, n):\n", "input_output": {"inputs": ["n = 9\narr[] = {1, 9, 2, 8, 3, 7, 4, 6, 5}", "n = 4\narr[] = {1, 2, 3, 4}"], "outputs": ["1 9 2 8 3 7 4 6 5", "1 4 2 3"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/rearrange-the-array5802/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n*logn)", "entry_point": "rearrangearray", "task_id": "TACO_lite/290", "example": [[], []]} +{"requirement": "For all x in the range of integers [0, 2 ** n), let y[x] be the binary exclusive-or of x and x // 2. Find the sum of all numbers in y.\n\nWrite a function sum_them that, given n, will return the value of the above sum.\n\nThis can be implemented a simple loop as shown in the initial code. But once n starts getting to higher numbers, such as 2000 (which will be tested), the loop is too slow.\n\nThere is a simple solution that can quickly find the sum. Find it!\n\nAssume that n is a nonnegative integer.\n\nHint: The complete solution can be written in two lines.", "solutions": ["def sum_them(n):\n return 2 ** (n - 1) * (2 ** n - 1)", "sum_them = lambda n: int('1' * n, 2) * (int('1' * n, 2) + 1) // 2 if n else 0", "sum_them = lambda n: int(n * '1' + ~-n * '0' or '0', 2)", "def sum_them(n):\n return n and int('1' * n + '0' * (n - 1), 2)", "sum_them = lambda n: ~-2 ** n * 2 ** (~-n)", "def sum_them(n):\n return (1 << n) - 1 << n - 1 if n > 0 else 0"], "starter_code": "def sum_them(n):\n", "input_output": {"fn_name": "sum_them", "inputs": [[0], [1], [2], [3], [4]], "outputs": [[0], [1], [6], [28], [120]]}, "difficulty": "EASY", "raw_tags": ["Puzzles", "Binary"], "name": null, "source": "codewars", "tags": ["Bit manipulation", "Ad-hoc"], "skill_types": ["Bit manipulation"], "url": "https://www.codewars.com/kata/549c7ae26d86c7c3ed000b87", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sum_them", "task_id": "TACO_lite/254", "example": [[[1], [2], [3], [4]], ["1", "4", "12", "32"]]} +{"requirement": "Given a string str, convert the first letter of each word in the string to uppercase. \nExample 1:\nInput:\nstr = \"i love programming\"\nOutput: \"I Love Programming\"\nExplanation:\n'I', 'L', 'P' are the first letters of \nthe three words.\nYour Task: \nYou dont need to read input or print anything. Complete the function transform() which takes s as input parameter and returns the transformed string.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N) to store resultant string \nConstraints:\n1 <= N <= 10^{4}\nThe original string str only consists of lowercase alphabets and spaces to separate words.", "solutions": ["import string\n\ndef transform(s):\n return string.capwords(s)", "def transform(s):\n return s.title()", "def transform(s):\n l = s.split()\n res = []\n for i in l:\n if len(i) == 1:\n i = i.upper()\n res.append(i)\n else:\n i = i[0].upper() + i[1:]\n res.append(i)\n return ' '.join(res)", "def transform(s):\n a = s.split()\n b = []\n c = []\n for i in range(len(a)):\n b.append(a[i][0].upper())\n c.append(b[i] + a[i][1:])\n return ' '.join(c)", "def transform(s):\n newstr = ''\n for i in range(len(s)):\n if s[i - 1] == ' ' or i == 0:\n n = ord(s[i]) - 32\n newstr = newstr + chr(n)\n else:\n newstr = newstr + s[i]\n return newstr", "def transform(s):\n return ' '.join([i[0].upper() + i[1:] for i in s.split()])", "def transform(s):\n word = s.split()\n c = [s.capitalize() for s in word]\n return ' '.join(c)", "def transform(s):\n r = s[0].upper()\n for i in range(1, len(s)):\n if s[i - 1] == ' ':\n r += s[i].upper()\n else:\n r += s[i]\n return r", "def transform(s):\n res = s.split()\n res = [i.title() for i in res]\n l = ' '.join(res)\n return l", "def transform(s):\n s2 = s.split(' ')\n res = ''\n for i in s2:\n res = res + i.capitalize() + ' '\n return res", "def transform(s):\n s = s.lower()\n words = s.split(' ')\n transformed_words = [word.capitalize() for word in words]\n transformed_string = ' '.join(transformed_words)\n return transformed_string", "def transform(s):\n res = ''\n s = s.capitalize()\n isSpace = False\n for e in s:\n ele = e\n if isSpace:\n isSpace = False\n res = res + e.upper()\n else:\n res = res + e\n if ele == ' ':\n isSpace = True\n return res", "def transform(s):\n l = s.split()\n for i in range(len(l)):\n l[i] = l[i].title()\n return ' '.join(l)", "def transform(s):\n result = []\n str = s.split()\n for i in str:\n if len(i) == 1:\n result.append(i.upper())\n if len(i) > 1:\n result.append(i[0].upper() + i[1:])\n return ' '.join(result)", "def transform(s):\n l = s.split()\n str_upper = ''\n for i in l:\n str_upper = str_upper + i.capitalize() + ' '\n return str_upper", "def transform(s):\n string = s.split(' ')\n list1 = []\n for i in string:\n result = i.capitalize()\n list1.append(result)\n string = ','.join(list1)\n result = string.replace(',', ' ')\n return result", "def transform(s):\n s = list(s)\n s[0] = s[0].capitalize()\n for i in range(len(s)):\n if s[i] == ' ':\n s[i + 1] = s[i + 1].capitalize()\n s = ''.join(s)\n return s", "def transform(s):\n str_list = s.split()\n str = ''\n for i in str_list:\n str += i.capitalize() + ' '\n return str", "def transform(s):\n ans = ''\n for i in s:\n return s.title()", "def transform(s):\n s = ' ' + s\n s = list(s)\n for i in range(len(s)):\n if s[i] == ' ':\n s[i + 1] = s[i + 1].upper()\n s = s[1:]\n s = ''.join(s)\n return s", "def transform(s):\n ans = ''\n ans += chr(ord(s[0]) - 32)\n for i in range(0, len(s) - 1):\n if s[i] == ' ':\n ans += chr(ord(s[i + 1]) - 32)\n else:\n ans += s[i + 1]\n return ans", "def transform(s):\n list_s = s.split()\n result = ''\n for each in list_s:\n result += each.capitalize() + ' '\n return result", "def transform(s):\n lst = s.split(' ')\n res = []\n for i in lst:\n res.append(i.lower().capitalize())\n S = ' '.join(res)\n return S", "def transform(s):\n Words = s.split(' ')\n words = []\n for word in Words:\n words.append(word.lower().capitalize())\n return ' '.join(words)", "def transform(s):\n t = s.split()\n p = [r.capitalize() for r in t]\n return ' '.join(p)", "def transform(s):\n words = list(s.split(' '))\n w = []\n for i in range(len(words)):\n w += [words[i].capitalize()]\n return ' '.join(w)", "def transform(s):\n ans = ''\n for i in range(0, len(s), 1):\n if i == 0:\n ans += s[i].upper()\n elif (ord(s[i]) >= ord('a') and ord(s[i]) <= ord('z')) and ord(s[i - 1]) == ord(' '):\n ans += s[i].upper()\n else:\n ans += s[i]\n return ans", "def transform(s):\n inp_list = list(s.split(' '))\n out_list = []\n for word in inp_list:\n temp_list = list(word)\n temp_list[0] = temp_list[0].upper()\n out_list.append(''.join(temp_list))\n return ' '.join(out_list)", "def transform(s):\n rs = s.split()\n result = ''\n for i in rs:\n result += i.capitalize() + ' '\n return result", "def transform(s):\n ls = []\n lt = list(s)\n ls.append(lt[0].upper())\n i = 1\n while i < len(lt):\n if lt[i] == ' ':\n ls.append(lt[i])\n ls.append(lt[i + 1].upper())\n i = i + 2\n else:\n ls.append(lt[i])\n i = i + 1\n return ''.join(ls)", "def transform(s):\n l = []\n for i in s.split():\n l.append(i.capitalize())\n return ' '.join(l)", "def transform(s):\n words = s.split()\n new_str = []\n final_str = ''\n for i in words:\n new_str.append(i.capitalize())\n for j in new_str:\n final_str = final_str + j + ' '\n return final_str", "def transform(s):\n S = str(s)\n return S.title()", "def transform(s):\n s = s.split()\n S = ''\n for i in s:\n S += i.capitalize() + ' '\n return S", "def transform(s):\n result = ''\n temp = ''\n for i in s:\n if i == ' ':\n result += temp.capitalize()\n result += ' '\n temp = ''\n else:\n temp += i\n result += temp.capitalize()\n return result", "def transform(str):\n str = str.title()\n return str", "def transform(s):\n a = s.split()\n ans = []\n for i in range(len(a)):\n b = a[i].capitalize()\n ans.append(b)\n return ' '.join(ans)", "def transform(s):\n result = ''\n found = False\n for i in range(len(s)):\n if i != 0:\n if s[i] == ' ':\n result = result + s[i]\n result = result + s[i + 1].capitalize()\n found = True\n else:\n if i != 0:\n if found == True:\n found = False\n continue\n result = result + s[i]\n else:\n if i == 0:\n result = result + s[i].capitalize()\n continue\n if i != 0:\n if found == True:\n found = False\n continue\n result = result + s[i]\n return result", "def transform(s):\n words = s.split()\n output_string = ''\n for i in words:\n output_string = output_string + i.capitalize() + ' '\n return output_string", "def transform(s):\n temp = ''\n temp += s[0].upper()\n n = len(s)\n for i in range(1, n):\n if s[i] != ' ' and s[i - 1] == ' ':\n temp += s[i].upper()\n else:\n temp += s[i]\n return temp", "def transform(s):\n r = s.split()\n p = ''\n for i in r:\n p += i.capitalize() + ' '\n return p", "def transform(s):\n s_list = s.split(' ')\n n_list = []\n for w in s_list:\n n = w[0].upper() + w[1:]\n n_list.append(n)\n return ' '.join(n_list)"], "starter_code": "def transform(s):\n", "input_output": {"inputs": ["str = \"i love programming\""], "outputs": ["\"I Love Programming\""]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/upper-case-conversion5419/1", "Expected Auxiliary Space": "O(N) to store resultant string", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "transform", "task_id": "TACO_lite/347", "example": [[["i love programming"]], ["I Love Programming"]]} +{"requirement": "Gematria is an Assyro-Babylonian-Greek system of code and numerology later adopted into Jewish culture. The system assigns numerical value to a word or a phrase in the belief that words or phrases with identical numerical values bear some relation to each other or bear some relation to the number itself. While more commonly used on Hebrew words, there is also an English version.\n\nEach letter has a value and the gematrian value of a word or a phrase is the sum of those values. The code takes a word or an expression and returns the gematrian value of it.\n\nThe calculation is case insensitive and counts no spaces. \n\nExample: The gematrian value of \"love\" is 20+50+700+5 = 775\n\n‎These are the values of the different letters:\n\na=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, k=10, l=20,\nm=30, n=40, o=50, p=60, q=70, r=80, s=90, t=100, u=200,\nx=300, y=400, z=500, j=600, v=700, w=900", "solutions": ["TOME = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'k': 10, 'l': 20, 'm': 30, 'n': 40, 'o': 50, 'p': 60, 'q': 70, 'r': 80, 's': 90, 't': 100, 'u': 200, 'x': 300, 'y': 400, 'z': 500, 'j': 600, 'v': 700, 'w': 900}\n\ndef gematria(s):\n return sum((TOME.get(c, 0) for c in s.lower()))", "gematria = lambda s, d=dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, k=10, l=20, m=30, n=40, o=50, p=60, q=70, r=80, s=90, t=100, u=200, x=300, y=400, z=500, j=600, v=700, w=900): sum(map(d.get, filter(str.islower, s.lower())))", "from string import ascii_lowercase\n\ndef gematria(strng):\n values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 600, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 700, 900, 300, 400, 500]\n alphabet_values = {letter: num for (num, letter) in zip(values, ascii_lowercase)}\n return sum([alphabet_values[letter] if letter in ascii_lowercase else 0 for letter in strng.lower()])"], "starter_code": "def gematria(string):\n", "input_output": {"fn_name": "gematria", "inputs": [["love"], ["jaels"], ["JAELS"], ["Devil"], ["Coding is fun"]], "outputs": [[775], [716], [716], [738], [458]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/573c91c5eaffa3bd350000b0", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "gematria", "task_id": "TACO_lite/388", "example": [[["love"]], ["775"]]} +{"requirement": "A string S of lowercase letters is given.  Then, we may make any number of moves.\nIn each move, we choose one of the first K letters (starting from the left), remove it, and place it at the end of the string.\nReturn the lexicographically smallest string we could have after any number of moves.\n \n\nExample 1:\nInput: S = \"cba\", K = 1\nOutput: \"acb\"\nExplanation: \nIn the first move, we move the 1st character (\"c\") to the end, obtaining the string \"bac\".\nIn the second move, we move the 1st character (\"b\") to the end, obtaining the final result \"acb\".\n\n\nExample 2:\nInput: S = \"baaca\", K = 3\nOutput: \"aaabc\"\nExplanation: \nIn the first move, we move the 1st character (\"b\") to the end, obtaining the string \"aacab\".\nIn the second move, we move the 3rd character (\"c\") to the end, obtaining the final result \"aaabc\".\n\n \nNote:\n\n1 <= K <= S.length <= 1000\nS consists of lowercase letters only.", "solutions": ["def orderlyqueue(S: str, K: int) -> str:\n if K >= 2:\n return ''.join(sorted(S))\n length = len(S)\n S = S + S\n (i, j, k) = (0, 1, 0)\n while j + k < len(S) and k < length:\n if S[i + k] == S[j + k]:\n k += 1\n continue\n elif S[i + k] < S[j + k]:\n j = j + k + 1\n else:\n i = max(i + k + 1, j)\n j = i + 1\n k = 0\n return S[i:i + length]", "def orderlyqueue(S: str, K: int) -> str:\n if K == 1:\n tmp = S\n for i in range(len(S)):\n S = S[1:] + str(S[0])\n if S < tmp:\n tmp = S\n return tmp\n else:\n return ''.join(sorted(S))", "def orderlyqueue(s: str, k: int) -> str:\n s = [c for c in s]\n if k == 1:\n temp = []\n for i in range(len(s)):\n temp_s = s[i:] + s[:i]\n temp.append(''.join(temp_s))\n temp.sort()\n return temp[0]\n else:\n return ''.join(sorted(s))"], "starter_code": "def orderlyqueue(S: str, K: int) -> str:\n", "input_output": {"fn_name": "orderlyQueue", "inputs": [["\"cba\"", 1]], "outputs": ["\"\"cba"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Math", "Sorting", "String"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Sorting", "Mathematics"], "skill_types": ["Sorting"], "url": "https://leetcode.com/problems/orderly-queue/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "orderlyqueue", "task_id": "TACO_lite/350", "example": [[["cba", 1], ["baaca", 3]], ["acb", "aaabc"]]} +{"requirement": "Jack and Jill are playing a game. They have balls numbered from `0` to `n - 1`. Jack looks the other way and asks Jill to reverse the position of the balls, for instance, to change the order from say, `0,1,2,3` to `3,2,1,0`. He further asks Jill to reverse the position of the balls `n` times, each time starting from one position further to the right, till she reaches the last ball. So, Jill has to reverse the positions of the ball starting from position `0`, then from position `1`, then from position `2` and so on. At the end of the game, Jill will ask Jack to guess the final position of any ball numbered `k`. \n\nYou will be given `2` integers, the first will be `n`(balls numbered from `0` to `n-1`) and the second will be `k`. You will return the position of the ball numbered `k` after the rearrangement.\n\n```Perl\nsolve(4,1) = 3. The reversals are [0,1,2,3] -> [3,2,1,0] -> [3,0,1,2] -> [3,0,2,1]. => 1 is in position 3.\n```\n\nMore examples in the test cases. Good luck!", "solutions": ["def solve(count, ball_number):\n assert isinstance(count, int)\n assert isinstance(ball_number, int)\n balls = list(range(count))\n for idx in range(count):\n balls = balls[:idx] + balls[idx:][::-1]\n return balls.index(ball_number)", "solve = lambda n, k: 2 * (n - k - 1, k + 0.5)[k < n // 2]", "def solve(n, k):\n res = list(range(n))\n for i in range(n):\n res = res[:i] + res[i:][::-1]\n return res.index(k)", "def solve(n, k):\n second_half = k >= n // 2\n return (-1) ** second_half * 2 * k + second_half * (n * 2 - 3) + 1", "def solve(n, k):\n arr = []\n for i in range(n % 2 + n // 2):\n arr += [n - i - 1] + [i]\n return arr.index(k)", "def solve(n, k):\n a = list()\n for i in range(int(n / 2) + 1):\n a += [n - 1 - i, i]\n return a.index(k)", "def solve(n, k):\n return 2 * k + 1 if k <= n // 2 - 1 else 2 * (n - k - 1)", "def solve(n, k):\n list1 = list(range(n))\n list1_values = list(list1)\n ball = list1[k]\n counter = 0\n final_list = []\n for i in range(n):\n list1.reverse()\n final_list.append(list1.pop(0))\n position = final_list.index(ball)\n return position", "def solve(n, k):\n result = {}\n (index, start, end) = (0, 0, n - 1)\n while start <= end:\n result[end] = index\n index += 1\n if start != end:\n result[start] = index\n index += 1\n start += 1\n end -= 1\n return result[k]"], "starter_code": "def solve(n,k):\n", "input_output": {"fn_name": "solve", "inputs": [[4, 1], [4, 2], [4, 3], [20, 8], [20, 9], [20, 10]], "outputs": [[3], [2], [0], [17], [19], [18]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Puzzles"], "name": null, "source": "codewars", "tags": ["Mathematics", "Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/5b93636ba28ce032600000b7", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/323", "example": [[[4, 1]], ["3"]]} +{"requirement": "Given an array of unique integers salary where salary[i] is the salary of the employee i.\nReturn the average salary of employees excluding the minimum and maximum salary.\n \nExample 1:\nInput: salary = [4000,3000,1000,2000]\nOutput: 2500.00000\nExplanation: Minimum salary and maximum salary are 1000 and 4000 respectively.\nAverage salary excluding minimum and maximum salary is (2000+3000)/2= 2500\n\nExample 2:\nInput: salary = [1000,2000,3000]\nOutput: 2000.00000\nExplanation: Minimum salary and maximum salary are 1000 and 3000 respectively.\nAverage salary excluding minimum and maximum salary is (2000)/1= 2000\n\nExample 3:\nInput: salary = [6000,5000,4000,3000,2000,1000]\nOutput: 3500.00000\n\nExample 4:\nInput: salary = [8000,9000,2000,3000,6000,1000]\nOutput: 4750.00000\n\n \nConstraints:\n\n3 <= salary.length <= 100\n10^3 <= salary[i] <= 10^6\nsalary[i] is unique.\nAnswers within 10^-5 of the actual value will be accepted as correct.", "solutions": ["def average(salary: List[int]) -> float:\n salary.sort()\n del salary[0]\n del salary[-1]\n return sum(salary) / len(salary)", "def average(salary: List[int]) -> float:\n minSalary = min(salary)\n maxSalary = max(salary)\n total = sum(salary)\n return (total - minSalary - maxSalary) / (len(salary) - 2)", "def average(salary: List[int]) -> float:\n salary.sort()\n salary.pop()\n salary.pop(0)\n return sum(salary) / len(salary)", "def average(salary: List[int]) -> float:\n minSalary = None\n maxSalary = None\n s = 0\n for n in salary:\n s = s + n\n if minSalary is None or n < minSalary:\n minSalary = n\n if maxSalary is None or n > maxSalary:\n maxSalary = n\n return (s - minSalary - maxSalary) * 1.0 / (len(salary) - 2)", "def average(salary: List[int]) -> float:\n return (sum(salary) - min(salary) - max(salary)) / (len(salary) - 2)", "def average(salary: List[int]) -> float:\n salary.sort()\n newSalaryList = salary[1:-1]\n numSalaries = len(newSalaryList)\n return sum(newSalaryList) / numSalaries"], "starter_code": "def average(salary: List[int]) -> float:\n", "input_output": {"fn_name": "average", "inputs": [[[1000, 2000, 3000, 4000]]], "outputs": [2500.0]}, "difficulty": "EASY", "raw_tags": ["Array", "Sorting"], "name": null, "source": "leetcode", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "average", "task_id": "TACO_lite/292", "example": [[[[4000, 3000, 1000, 2000]], [[1000, 2000, 3000]], [[6000, 5000, 4000, 3000, 2000, 1000]], [[8000, 9000, 2000, 3000, 6000, 1000]]], ["2500.0", "2000.0", "3500.0", "4750.0"]]} +{"requirement": "Given an input A , print the data type of the input A.\neg:-Sequence of digits -- int\n Sequence of digits with a dot -- float\n Sequence of chars -- string\n Single non-digit char --- char\n \nExample 1:\nInput: A = \"12\"\nOutput: \"int\"\nExplanation: The input consists only of\ndigits.\nExample 2:\nInput: A = \"gfg\"\nOutput: \"string\"\nExplanation: The input consists only of\ncharacters.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function FindInputType() which takes A as input parameter and returns data type of A.\n \nExpected Time Complexity: O(|A|)\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= |A| <= 1000", "solutions": ["def findinputtype(str):\n if str.isdigit():\n return 'int'\n if '.' in str:\n p = str.split('.')\n if p[-1].isdigit() and p[-2].isdigit() and (len(p) == 2) or (p[-1].isdigit() and p[-2] == '' and (len(p) == 2)):\n return 'float'\n elif len(str) > 1:\n return 'string'\n if len(str) == 1:\n return 'char'\n elif len(str) > 1:\n return 'string'", "def findinputtype(str):\n s = str\n ans = 'string'\n if len(s) == 1:\n if s.isalpha() or s.__contains__('.'):\n ans = 'char'\n else:\n ans = 'int'\n elif s.count('.') == 1:\n try:\n s1 = s.split('.')\n if len(s1[1]) != 0:\n s = float(s)\n ans = 'float'\n except:\n ans = 'string'\n else:\n try:\n s1 = int(s)\n ans = 'int'\n except:\n ans = 'string'\n return ans", "def findinputtype(str):\n size = len(str)\n ans = ''\n (flag, init) = (0, 0)\n for i in range(size):\n if str[i] != '.' and str[i] > '9' or (str[i] != '.' and str[i] < '0'):\n init = 1\n if str[i] == '.':\n flag += 1\n if str[size - 1] == '.' and size != 1:\n ans = 'string'\n elif init == 0 and flag == 1 and (size > 1):\n ans = 'float'\n elif init == 0 and flag == 0:\n ans = 'int'\n elif size == 1:\n ans = 'char'\n else:\n ans = 'string'\n return ans", "def findinputtype(str):\n if len(str) == 1:\n if str.isnumeric():\n return 'int'\n return 'char'\n for i in str:\n if i.isalpha():\n return 'string'\n else:\n if '.' in str:\n a = str.split('.')\n if len(a) == 2 and len(a[1]) > 0 and (len(a[0]) >= 0):\n return 'float'\n else:\n return 'int'\n return 'string'"], "starter_code": "def findinputtype(str):\n", "input_output": {"inputs": ["A = \"12\"", "A = \"gfg\""], "outputs": ["\"int\"", "\"string\""]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/type-of-input5910/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|A|)", "entry_point": "findinputtype", "task_id": "TACO_lite/306", "example": [[["12"], ["gfg"]], ["int", "string"]]} +{"requirement": "Given an array of integers A, consider all non-empty subsequences of A.\nFor any sequence S, let the width of S be the difference between the maximum and minimum element of S.\nReturn the sum of the widths of all subsequences of A. \nAs the answer may be very large, return the answer modulo 10^9 + 7.\n\n \nExample 1:\nInput: [2,1,3]\nOutput: 6\nExplanation:\nSubsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\nThe corresponding widths are 0, 0, 0, 1, 1, 2, 2.\nThe sum of these widths is 6.\n\n \nNote:\n\n1 <= A.length <= 20000\n1 <= A[i] <= 20000", "solutions": ["def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n (ret, mod, p) = (0, 10 ** 9 + 7, 1)\n for i in range(len(A)):\n ret += (A[i] - A[len(A) - i - 1]) * p % mod\n p = (p << 1) % mod\n return ret % mod", "mod_ = 10 ** 9 + 7\n\ndef sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n n = len(A)\n p_2 = [1]\n for i in range(1, n + 2):\n p_2.append(p_2[-1] * 2 % mod_)\n l = [0]\n for i in range(1, n):\n l.append((2 * l[-1] + (A[i] - A[i - 1]) * (p_2[i] - 1)) % mod_)\n sol = 0\n for elem in l:\n sol = (sol + elem) % mod_\n return sol", "def sumsubseqwidths(A: List[int]) -> int:\n ret = 0\n for (i, n) in enumerate(sorted(A)):\n ret += n * pow(2, i)\n ret -= n * pow(2, len(A) - i - 1)\n ret %= 10 ** 9 + 7\n return ret", "from bisect import bisect_left, bisect_right\n\ndef sumsubseqwidths(A: List[int]) -> int:\n n = len(A)\n ret = 0\n A.sort()\n ret = 0\n f = {}\n for (i, x) in enumerate(A):\n if x not in f:\n f[x] = [i, i]\n else:\n f[x][1] = i\n ret = 0\n for x in f:\n (l, r) = f[x]\n sl = l\n sr = n - r - 1\n se = r - l + 1\n ret += (2 ** sl - 1) * (2 ** se - 1) * x\n ret -= (2 ** sr - 1) * (2 ** se - 1) * x\n return ret % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n MOD = 10 ** 9 + 7\n N = len(A)\n A.sort()\n pow2 = [1]\n for i in range(1, N):\n pow2.append(pow2[-1] * 2 % MOD)\n ans = 0\n for (i, x) in enumerate(A):\n ans = (ans + (pow2[i] - pow2[N - 1 - i]) * x) % MOD\n return ans", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n total_cnt = 0\n total_prod = 0\n ans = 0\n for num in A:\n ans = (ans + total_cnt * num - total_prod) % self.BASE\n total_cnt = (2 * total_cnt + 1) % self.BASE\n total_prod = (2 * total_prod + num) % self.BASE\n return ans", "def sumsubseqwidths(A: List[int]) -> int:\n aa = sorted(A)\n n = len(A)\n res = 0\n md = 10 ** 9 + 7\n p2 = [1] * n\n for i in range(1, n):\n p2[i] = p2[i - 1] * 2 % md\n for i in range(n):\n res = (res + aa[i] * (p2[i] - p2[n - i - 1])) % md\n return res", "def sumsubseqwidths(A: List[int]) -> int:\n N = len(A)\n if N == 1:\n return 0\n MOD = 10 ** 9 + 7\n A.sort()\n pow2 = [1]\n widths = 0\n for i in range(1, N):\n pow2.append(pow2[-1] * 2 % MOD)\n for i in range(N):\n widths = (widths + (pow2[i] - pow2[N - 1 - i]) * A[i]) % MOD\n return widths", "from collections import deque\n\ndef sumsubseqwidths(A: List[int]) -> int:\n n = len(A)\n MOD = 10 ** 9 + 7\n pows = [1] * n\n for i in range(1, n):\n pows[i] = pows[i - 1] * 2 % MOD\n A.sort()\n ans = 0\n for (i, v) in enumerate(A):\n ans += pows[i] * v - pows[n - 1 - i] * v\n ans %= MOD\n return ans % MOD", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n result = 0\n for i in range(len(A)):\n result *= 2\n result -= A[i]\n result += A[~i]\n return result % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n if len(A) == 1:\n return 0\n if len(A) == 0:\n return 0\n (ans, prev, n, mod) = (A[1] - A[0], A[1] - A[0], len(A), 1000000000.0 + 7)\n (twoPow, temp) = ([1], 2)\n for i in range(1, n):\n twoPow.append(temp + twoPow[-1])\n temp = temp * 2 % mod\n for i in range(2, len(A)):\n diff = A[i] - A[i - 1]\n prev = (2 * (prev + diff * twoPow[i - 2] % mod) % mod + diff) % mod\n ans = (ans + prev) % mod\n return int(ans)", "def sumsubseqwidths(A: List[int]) -> int:\n res = 0\n n = len(A)\n M = 10 ** 9 + 7\n c = 1\n A.sort()\n for i in range(n):\n res = (res + A[i] * c - A[n - i - 1] * c) % M\n c = (c << 1) % M\n return res", "def sumsubseqwidths(A: List[int]) -> int:\n size = len(A)\n mod = 10 ** 9 + 7\n pow_mod = [1] * size\n for i in range(1, size):\n pow_mod[i] = pow_mod[i - 1] * 2 % mod\n A.sort()\n ans = 0\n for i in range(size):\n ans += A[i] * ((pow_mod[i] - pow_mod[size - 1 - i]) % mod) % mod\n ans %= mod\n return ans", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n res = 0\n n = len(A)\n for i in range(n):\n res += A[i] * 1 << i % 1000000007\n res -= A[i] * 1 << n - i - 1\n return res % 1000000007", "def sumsubseqwidths(A: List[int]) -> int:\n MOD = 10 ** 9 + 7\n A.sort()\n result = 0\n prev = 0\n for i in range(1, len(A)):\n d = A[i] - A[i - 1]\n prev = (2 * prev + d * (pow(2, i, MOD) - 1)) % MOD\n result = (result + prev) % MOD\n return result", "def sumsubseqwidths(A):\n return sum((((1 << i) - (1 << len(A) - i - 1)) * a for (i, a) in enumerate(sorted(A)))) % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n B = sorted(A)\n res = 0\n mod = 10 ** 9 + 7\n for i in range(len(B)):\n res += B[i] * ((1 << i) - (1 << len(B) - i - 1))\n return res % mod", "def sumsubseqwidths(A: List[int]) -> int:\n if not A:\n return 0\n ans = 0\n A.sort()\n for (i, n) in enumerate(A):\n ans += ((1 << i) - (1 << len(A) - i - 1)) * n\n return ans % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n return sum(((1 << i) * num - (1 << len(A) - i - 1) * num for (i, num) in enumerate(sorted(A)))) % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n mod = 10 ** 9 + 7\n A.sort()\n n = len(A)\n return sum((a * ((1 << i) - (1 << n - i - 1)) for (i, a) in enumerate(A))) % mod", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n LIM = 10 ** 9 + 7\n res = 0\n powTable = [1]\n for _ in range(len(A)):\n powTable.append(2 * powTable[-1] % LIM)\n for (i, val) in enumerate(A):\n res = (res + val * powTable[i] - val * powTable[len(A) - i - 1]) % LIM\n return res", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n total = 0\n MOD = 10 ** 9 + 7\n powerSum = 2 ** 0\n counter = 2\n currSum = A[0]\n for i in range(1, len(A)):\n total += powerSum * A[i] - currSum\n currSum *= 2\n currSum += A[i]\n powerSum += counter\n counter *= 2\n return total % MOD", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n S = 0\n B = [1] * len(A)\n for i in range(1, len(B)):\n B[i] = 2 * B[i - 1]\n for i in range(len(A)):\n S += (B[i] - B[-1 - i]) * A[i]\n return S % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n l = len(A)\n p = [1]\n ans = 0\n for i in range(1, l):\n p.append(p[-1] * 2)\n for (i, j) in enumerate(A):\n ans += (p[i] - p[l - i - 1]) * j\n return ans % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n n = len(A)\n total = 0\n for i in range(n):\n a = A[i]\n left = i\n right = n - i - 1\n total += ((1 << left) - 1) * a\n total -= ((1 << right) - 1) * a\n return total % (10 ** 9 + 7)", "def sumsubseqwidths(nums):\n res = 0\n for (i, num) in enumerate(sorted(nums)):\n res += ((1 << i) - (1 << len(nums) - i - 1)) * num\n return res % 1000000007", "def sumsubseqwidths(A: List[int]) -> int:\n A = sorted(A)\n r = 0\n m = 10 ** 9 + 7\n for i in range(len(A) - 1):\n r += (A[i + 1] - A[i]) * ((1 << len(A)) - (1 << i + 1) - (1 << len(A) - i - 1) + 1)\n r %= m\n return r", "from bisect import bisect_left, bisect_right\n\ndef sumsubseqwidths(A: List[int]) -> int:\n n = len(A)\n ret = 0\n A.sort()\n MOD = 10 ** 9 + 7\n\n def bimod(n):\n if n == 0:\n return 1\n di = bimod(n // 2)\n if n % 2 == 0:\n return di * di % MOD\n return di * di * 2 % MOD\n\n def nonempty(n):\n return bimod(n) - 1\n i = 0\n while i < n:\n j = i\n while j < n and A[j] == A[i]:\n j += 1\n se = j - i\n sl = i\n sr = n - j\n ret = (ret + A[i] * nonempty(se) * (nonempty(sl) - nonempty(sr)) % MOD) % MOD\n i = j\n return ret % MOD", "def sumsubseqwidths(A: List[int]) -> int:\n A = sorted(A)\n (total, cur, cnt) = (0, 0, 0)\n MOD = 10 ** 9 + 7\n for i in range(1, len(A)):\n cnt *= 2\n cnt += 1\n cur *= 2\n cur += (A[i] - A[i - 1]) * cnt\n cur %= MOD\n total += cur\n total %= MOD\n return total", "def sumsubseqwidths(A: List[int]) -> int:\n A = sorted(A)\n res = 0\n MOD = 10 ** 9 + 7\n c = 1\n for i in range(len(A)):\n res = (res + A[i] * c % MOD) % MOD\n c <<= 1\n c %= MOD\n c = 1\n for i in range(len(A) - 1, -1, -1):\n res = (res - A[i] * c % MOD) % MOD\n c <<= 1\n c %= MOD\n return (res + MOD) % MOD", "def sumsubseqwidths(A: List[int]) -> int:\n POW2 = [1 << i for i in range(len(A))]\n return sum(((POW2[i] - POW2[len(A) - 1 - i]) * n for (i, n) in enumerate(sorted(A)))) % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n mod = 10 ** 9 + 7\n n = len(A)\n A.sort()\n B = [A[i] - A[n - i - 1] for i in range(n)]\n ans = 0\n for (i, v) in enumerate(B):\n ans = (ans + (v << i)) % mod\n return ans", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n res = 0\n mod = 10 ** 9 + 7\n N = len(A)\n for i in range(len(A)):\n res += ((1 << i) - (1 << N - i - 1)) * A[i] % mod\n return res % mod", "def sumsubseqwidths(A: List[int]) -> int:\n N = len(A)\n A = sorted(A)\n MODS = 10 ** 9 + 7\n (pow2, res) = ([1], 0)\n for ii in range(1, N):\n pow2.append(2 * pow2[-1] % MODS)\n for (ii, jj) in enumerate(A):\n res = (res + (pow2[ii] - pow2[N - ii - 1]) * jj) % MODS\n return res", "def sumsubseqwidths(A: List[int]) -> int:\n mod = 10 ** 9 + 7\n A.sort()\n n = len(A)\n ans = 0\n\n def exp(n):\n res = 1\n x = 2\n while n:\n if n & 1:\n res = res * x % mod\n n = n >> 1\n x = x * x % mod\n return res\n for i in range(n):\n ans = (ans + exp(i) * A[i] - exp(n - i - 1) * A[i] + mod) % mod\n return ans", "def sumsubseqwidths(A: List[int]) -> int:\n mod = 10 ** 9 + 7\n n = len(A)\n if n == 1:\n return 0\n pow = [1]\n for i in range(1, n):\n pow.append(pow[-1] * 2 % mod)\n A = sorted(A)\n s = 0\n for (i, elem) in enumerate(A):\n (n_max, n_min) = (i, n - i - 1)\n N1 = pow[i]\n N2 = pow[n - i - 1]\n s += elem * (N1 - N2) % (10 ** 9 + 7)\n s = s % (10 ** 9 + 7)\n return s", "def sumsubseqwidths(A: List[int]) -> int:\n MOD = 10 ** 9 + 7\n A = sorted(A)\n if len(A) == 1:\n return 0\n lastaddon = 0\n lastv = 0\n for i in range(1, len(A)):\n lastaddon = 2 * lastaddon + (2 ** i - 1) * (A[i] - A[i - 1])\n lastv += lastaddon\n return lastv % MOD", "def sumsubseqwidths(A: List[int]) -> int:\n n = len(A)\n widthsum = 0\n mod = 10 ** 9 + 7\n A.sort()\n p = s = 0\n (pre, suf) = ([], [])\n for i in range(n):\n p += A[i]\n s += A[-i - 1]\n pre.append(p)\n suf.append(s)\n for l in range(n):\n widthsum += 2 ** l * (suf[l] - pre[l])\n widthsum %= mod\n return widthsum", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n N = len(A)\n return sum((num * (2 ** i - 2 ** (N - i - 1)) for (i, num) in enumerate(A))) % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n Mod = 1000000000.0 + 7\n n = len(A)\n twoPower = [1]\n while len(twoPower) < n:\n twoPower.append(twoPower[len(twoPower) - 1] * 2 % Mod)\n A.sort()\n ans = 0\n for (i, a) in enumerate(A):\n left = i\n right = n - i - 1\n ans = (ans + (twoPower[left] - twoPower[right]) * a) % Mod\n return int((ans + Mod) % Mod)", "def sumsubseqwidths(A: List[int], recursed=False) -> int:\n return sum((x * (2 ** i - 2 ** (len(A) - i - 1)) for (i, x) in enumerate(sorted(A)))) % (int(1000000000.0) + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n A = sorted(A)\n length = len(A)\n _sum = 0\n for i in range(length):\n _sum += A[i] * 2 ** i\n for i in range(length):\n _sum -= A[i] * 2 ** (length - i - 1)\n return _sum % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n total = 0\n const = 10 ** 9 + 7\n for i in range(len(A)):\n total += 2 ** i * A[i] - 2 ** (len(A) - i - 1) * A[i]\n total = total % const\n return total"], "starter_code": "def sumsubseqwidths(A: List[int]) -> int:\n", "input_output": {"fn_name": "sumSubseqWidths", "inputs": [[[1, 2, 3]]], "outputs": [6]}, "difficulty": "MEDIUM", "raw_tags": ["Math", "Sorting", "Array"], "name": null, "source": "leetcode", "tags": ["Sorting", "Data structures", "Mathematics"], "skill_types": ["Sorting", "Data structures"], "url": "https://leetcode.com/problems/sum-of-subsequence-widths/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sumsubseqwidths", "task_id": "TACO_lite/371", "example": [[[[2, 1, 3]]], ["6"]]} +{"requirement": "Given two strings S1 and S2 . Print \"1\" if both strings are anagrams otherwise print \"0\" .\nNote: An anagram of a string is another string with exactly the same quantity of each character in it, in any order.\nExample 1:\nInput: S1 = \"cdbkdub\" , S2 = \"dsbkcsdn\"\nOutput: 0 \nExplanation: Length of S1 is not same\nas length of S2.\nExample 2:\nInput: S1 = \"geeks\" , S2 = \"skgee\"\nOutput: 1\nExplanation: S1 has the same quantity \nof each character in it as S2.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function areAnagram() which takes S1 and S2 as input and returns \"1\" if both strings are anagrams otherwise returns \"0\".\nExpected Time Complexity: O(n)\nExpected Auxiliary Space: O(K) ,Where K= Contstant\nConstraints:\n1 <= |S1| <= 1000\n1 <= |S2| <= 1000", "solutions": ["def areanagram(ob, S1, S2):\n if sorted(S1) == sorted(S2):\n return '1'\n else:\n return '0'", "def areanagram(ob, s1, s2):\n h = {}\n k = {}\n for i in s1:\n if i not in h:\n h[i] = 1\n else:\n h[i] += 1\n for i in s2:\n if i not in k:\n k[i] = 1\n else:\n k[i] += 1\n if h == k:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n x = list(S1)\n x = sorted(x)\n b = ''.join(x)\n y = list(S2)\n y = sorted(y)\n a = ''.join(y)\n if a == b:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n b = [*S1]\n c = [*S2]\n b.sort()\n c.sort()\n if b == c:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n op = sorted(S1)\n pk = sorted(S2)\n return 1 if op == pk else 0", "def areanagram(ob, S1, S2):\n freq = {}\n for i in S1:\n if i not in freq:\n freq[i] = 0\n freq[i] += 1\n for i in S2:\n if i not in freq:\n return 0\n else:\n freq[i] -= 1\n for i in freq:\n if freq[i]:\n return 0\n return 1", "def areanagram(ob, s1, s2):\n if len(s1) != len(s2):\n return 0\n count = [0] * 256\n for i in range(len(s1)):\n count[ord(s1[i])] += 1\n count[ord(s2[i])] -= 1\n for i in count:\n if i != 0:\n return 0\n return 1", "def areanagram(ob, s1, s2):\n if len(s1) != len(s2):\n return 0\n else:\n a = sorted(s1)\n b = sorted(s2)\n if a == b:\n return 1\n return 0", "def areanagram(ob, S1, S2):\n s = sorted(S1)\n s2 = sorted(S2)\n if s == s2:\n return 1\n return 0", "def areanagram(ob, S1, S2):\n a = list(S1)\n b = list(S2)\n a.sort()\n b.sort()\n if a == b:\n return 1\n return 0", "from collections import defaultdict\n\ndef areanagram(ob, S1, S2):\n store = defaultdict(lambda : 0)\n for item in S1:\n store[item] += 1\n for item in S2:\n store[item] -= 1\n return int(set(store.values()) == set([0]))", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n else:\n for i in range(0, len(S1)):\n if S1[i] not in S2 or S1.count(S1[i]) != S2.count(S1[i]):\n return 0\n return 1", "def areanagram(ob, S1, S2):\n l1 = list(S2)\n l2 = list(S1)\n l1.sort()\n l2.sort()\n if l1 == l2:\n return 1\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n else:\n S1 = sorted(S1)\n S2 = sorted(S2)\n for i in range(len(S1)):\n if S1[i] != S2[i]:\n return 0\n return 1", "def areanagram(ob, S1, S2):\n S1 = list(S1)\n S1.sort()\n S2 = list(S2)\n S2.sort()\n if S1 == S2:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n dict1 = {}\n dict2 = {}\n if len(S1) != len(S2):\n return 0\n for i in S1:\n if i not in dict1:\n dict1[i] = 1\n else:\n dict1[i] += 1\n for i in S2:\n if i not in dict2:\n dict2[i] = 1\n else:\n dict2[i] += 1\n count = 0\n for i in dict1:\n if i not in dict2:\n return 0\n if dict1[i] == dict2[i]:\n count += 1\n if count == len(dict1):\n return 1\n return 0", "def areanagram(ob, S1, S2):\n from collections import Counter\n return 1 if Counter(S1) == Counter(S2) else 0", "def areanagram(ob, S1, S2):\n s11 = ''.join(sorted(S1))\n s12 = ''.join(sorted(S2))\n if s11 == s12:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n else:\n str1 = sorted(S1)\n str2 = sorted(S2)\n if str1 == str2:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n s1_list = list(S1)\n s1_list.sort()\n s2_list = list(S2)\n s2_list.sort()\n if len(s1_list) == len(s2_list) and s1_list == s2_list:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n res1 = ''.join(sorted(S1))\n res2 = ''.join(sorted(S2))\n if res1 == res2:\n return '1'\n else:\n return '0'", "def areanagram(ob, s1, s2):\n if len(s1) != len(s2):\n return 0\n else:\n pcount = {}\n scount = {}\n for i in range(len(s1)):\n pcount[s1[i]] = pcount.get(s1[i], 0) + 1\n scount[s2[i]] = scount.get(s2[i], 0) + 1\n ans = 1 if scount == pcount else 0\n return ans", "def areanagram(ob, S1, S2):\n a = sorted(S1)\n b = sorted(S2)\n if len(a) == len(b):\n if a == b:\n return 1\n else:\n return 0\n else:\n return 0", "def areanagram(ob, S1, S2):\n S1 = sorted(list(S1))\n S2 = sorted(list(S2))\n return int(S1 == S2)", "def areanagram(ob, S1, S2):\n hashmap = {}\n if len(S1) != len(S2):\n return 0\n i = 0\n while i < len(S1):\n if S1[i] in hashmap:\n hashmap[S1[i]] += 1\n else:\n hashmap[S1[i]] = 1\n if S2[i] in hashmap:\n hashmap[S2[i]] -= 1\n else:\n hashmap[S2[i]] = -1\n i += 1\n for i in hashmap.values():\n if i != 0:\n return 0\n return 1", "def areanagram(ob, S1, S2):\n str1 = []\n str2 = []\n if len(S1) == len(S2):\n for i in S1:\n str1.append(i)\n for j in S2:\n str2.append(j)\n str1.sort()\n str2.sort()\n if str1 == str2:\n return 1\n else:\n return 0\n else:\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n l = [0] * 26\n for i in range(len(S1)):\n l[ord(S1[i]) - ord('a')] += 1\n l[ord(S2[i]) - ord('a')] -= 1\n for i in range(26):\n if l[i] != 0:\n return 0\n return 1", "def areanagram(ob, s1, s2):\n if sorted(s1) == sorted(s2):\n return 1\n return 0", "def areanagram(ob, S1, S2):\n s1 = {}\n s2 = {}\n for i in S1:\n if i not in s1:\n s1[i] = 1\n else:\n s1[i] += 1\n for j in S2:\n if j not in s2:\n s2[j] = 1\n else:\n s2[j] += 1\n if s1 == s2:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) == len(S2) and set(S1) == set(S2):\n for i in set(S1):\n if S1.count(i) != S2.count(i):\n return '0'\n return '1'\n return '0'", "def areanagram(ob, S1, S2):\n d1 = {}\n d2 = {}\n if len(S1) == len(S2):\n for i in S1:\n if i in d1:\n d1[i] = d1[i] + 1\n elif i not in d1:\n d1[i] = 1\n for j in S2:\n if j in d2:\n d2[j] = d2[j] + 1\n elif j not in d2:\n d2[j] = 1\n for k in d1:\n if d1 == d2:\n if d1[k] == d2[k]:\n return 1\n else:\n return 0\n else:\n return 0", "def areanagram(ob, S1, S2):\n d1 = {k: 0 for k in set(S1)}\n d2 = {k: 0 for k in set(S2)}\n for i in S1:\n d1[i] += 1\n for i in S2:\n d2[i] += 1\n if d1 == d2:\n return 1\n return 0", "def areanagram(ob, S1, S2):\n d = {}\n for i in S1:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for j in S2:\n if j in d:\n d[j] -= 1\n else:\n d[j] = 1\n for i in d:\n if d[i] != 0:\n return '0'\n return '1'", "from collections import defaultdict\n\ndef areanagram(ob, S1, S2):\n d1 = defaultdict(lambda : 0)\n for letter in S1:\n d1[letter] += 1\n for letter in S2:\n if d1[letter] >= 1:\n d1[letter] -= 1\n else:\n return '0'\n return '1'", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n c = 0\n S1 = sorted(S1)\n S2 = sorted(S2)\n if S1 == S2:\n return 1\n return 0", "def areanagram(ob, S1, S2):\n dict1 = ob.str__dict(S1)\n dict2 = ob.str__dict(S2)\n if dict1 == dict2:\n return 1\n else:\n return 0\n\ndef str__dict(ob, lst):\n dict = {}\n for i in lst:\n if i in dict:\n continue\n t = lst.count(i)\n dict[i] = t\n return dict", "def areanagram(ob, S1, S2):\n res = ''.join(sorted(S1))\n res1 = ''.join(sorted(S2))\n if res == res1:\n return 1\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n s1 = sorted(S1)\n s2 = sorted(S2)\n return 1 if s1 == s2 else 0", "def areanagram(ob, S1, S2):\n l1 = len(S1)\n l2 = len(S2)\n if l1 != l2:\n return 0\n if sorted(S1) == sorted(S2):\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n a = 0\n b = 0\n for i in range(len(S1)):\n a = a + ord(S1[i])\n for j in range(len(S2)):\n b = b + ord(S2[j])\n if a == b:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n S2 = list(S2)\n for i in S1:\n if i in S2:\n S2.remove(i)\n if not S2:\n return 1\n return 0", "def areanagram(ob, S1, S2):\n S1 = list(S1)\n S1.sort()\n S2 = list(S2)\n S2.sort()\n return int(S1 == S2)"], "starter_code": "def areanagram(ob, S1, S2):\n", "input_output": {"inputs": ["S1 = \"cdbkdub\" , S2 = \"dsbkcsdn\"", "S1 = \"geeks\" , S2 = \"skgee\""], "outputs": ["0", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Java"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/java-anagram-strings3549/1", "Expected Auxiliary Space": "O(K) ,Where K= Contstant", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "areanagram", "task_id": "TACO_lite/356", "example": [[["cdbkdub", "dsbkcsdn"], ["geeks", "skgee"]], ["0", "1"]]} +{"requirement": "You have a very large square wall and a circular dartboard placed on the wall. You have been challenged to throw darts into the board blindfolded. Darts thrown at the wall are represented as an array of points on a 2D plane. \nReturn the maximum number of points that are within or lie on any circular dartboard of radius r.\n \nExample 1:\n\nInput: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 2\nOutput: 4\nExplanation: Circle dartboard with center in (0,0) and radius = 2 contain all points.\n\nExample 2:\n\nInput: points = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5\nOutput: 5\nExplanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).\n\nExample 3:\nInput: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 1\nOutput: 1\n\nExample 4:\nInput: points = [[1,2],[3,5],[1,-1],[2,3],[4,1],[1,3]], r = 2\nOutput: 4\n\n \nConstraints:\n\n1 <= points.length <= 100\npoints[i].length == 2\n-10^4 <= points[i][0], points[i][1] <= 10^4\n1 <= r <= 5000", "solutions": ["def numpoints(points: List[List[int]], r: int) -> int:\n ans = 1\n for (x, y) in points:\n angles = []\n for (x1, y1) in points:\n if (x1 != x or y1 != y) and (d := sqrt((x1 - x) ** 2 + (y1 - y) ** 2)) <= 2 * r:\n angle = atan2(y1 - y, x1 - x)\n delta = acos(d / (2 * r))\n angles.append((angle - delta, +1))\n angles.append((angle + delta, -1))\n angles.sort(key=lambda x: (x[0], -x[1]))\n val = 1\n for (_, entry) in angles:\n ans = max(ans, (val := (val + entry)))\n return ans", "from math import sqrt\n\ndef numpoints(points: List[List[int]], r: int) -> int:\n n = len(points)\n if n <= 2:\n return n\n best = 1\n rr = r ** 2\n for i in range(n):\n for j in range(i + 1, n):\n [x1, y1] = points[i]\n [x2, y2] = points[j]\n xm = (x1 + x2) / 2\n ym = (y1 + y2) / 2\n q = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n qq = (q / 2) ** 2\n rq = rr - qq\n if rq < 0:\n continue\n xc = xm + sqrt(rq) * (y1 - y2) / q\n yc = ym + sqrt(rq) * (x2 - x1) / q\n curr = 2\n for k in range(n):\n if k == i or k == j:\n continue\n [x, y] = points[k]\n if sqrt((x - xc) ** 2 + (y - yc) ** 2) <= r:\n curr += 1\n best = max(best, curr)\n return best", "def numpoints(A: List[List[int]], r: int) -> int:\n res = 1\n for ((x1, y1), (x2, y2)) in itertools.combinations(A, 2):\n d = ((x1 - x2) ** 2 + (y1 - y2) ** 2) / 4.0\n if d > r * r:\n continue\n x0 = (x1 + x2) / 2.0 + (y2 - y1) * (r * r - d) ** 0.5 / (d * 4) ** 0.5\n y0 = (y1 + y2) / 2.0 - (x2 - x1) * (r * r - d) ** 0.5 / (d * 4) ** 0.5\n res = max(res, sum(((x - x0) ** 2 + (y - y0) ** 2 <= r * r + 1e-05 for (x, y) in A)))\n return res", "def numpoints(points: List[List[int]], r: int) -> int:\n max_pts = 500\n dis = [[0 for _ in range(max_pts)] for _ in range(max_pts)]\n\n def getPointsInside(i, r, n):\n angles = []\n for j in range(n):\n if i != j and dis[i][j] <= 2 * r:\n B = math.acos(dis[i][j] / (2 * r))\n (x1, y1) = points[i]\n (x2, y2) = points[j]\n A = math.atan2(y1 - y2, x1 - x2)\n alpha = A - B\n beta = A + B\n angles.append((alpha, False))\n angles.append((beta, True))\n angles.sort()\n (cnt, res) = (1, 1)\n for angle in angles:\n if angle[1] == 0:\n cnt += 1\n else:\n cnt -= 1\n res = max(cnt, res)\n return res\n n = len(points)\n for i in range(n - 1):\n for j in range(i + 1, n):\n (x1, y1) = points[i]\n (x2, y2) = points[j]\n dis[i][j] = dis[j][i] = sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\n ans = 0\n for i in range(n):\n ans = max(ans, getPointsInside(i, r, n))\n return ans", "def numpoints(points: List[List[int]], r: int) -> int:\n ans = 1\n for ((x1, y1), (x2, y2)) in itertools.combinations(points, 2):\n q = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\n if q > 2 * r + 1e-05:\n continue\n x0 = (x1 + x2) / 2 + math.sqrt(r ** 2 - (q / 2) ** 2) * (y1 - y2) / q\n y0 = (y1 + y2) / 2 + math.sqrt(r ** 2 - (q / 2) ** 2) * (x2 - x1) / q\n ans = max(ans, sum((1 for (x, y) in points if (x - x0) ** 2 + (y - y0) ** 2 <= r ** 2 + 1e-05)))\n return ans", "def numpoints(points: List[List[int]], r: int) -> int:\n\n def count(x0, y0):\n nonlocal ans\n cnt = 0\n for (x, y) in points:\n if (x - x0) * (x - x0) + (y - y0) * (y - y0) <= r * r + 1e-06:\n cnt += 1\n ans = max(ans, cnt)\n n = len(points)\n ans = 1\n for i in range(n):\n for j in range(i + 1, n):\n (x1, y1) = points[i]\n (x2, y2) = points[j]\n (x_mid, y_mid) = ((x1 + x2) / 2, (y1 + y2) / 2)\n sq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)\n d = r * r - sq / 4\n if d < 0:\n continue\n d = sqrt(d)\n sq = sqrt(sq)\n sin = abs(x1 - x2) / sq\n cos = abs(y1 - y2) / sq\n if (x2 - x1) * (y1 - y2) < 0:\n cos = -cos\n (x0, y0) = (x_mid - d * cos, y_mid - d * sin)\n count(x0, y0)\n (x0, y0) = (x_mid + d * cos, y_mid + d * sin)\n count(x0, y0)\n return ans", "def numpoints(points: List[List[int]], r: int) -> int:\n res = 1\n for (x, y) in points:\n order = []\n for (x1, y1) in points:\n if x != x1 or y != y1:\n d = math.sqrt((x1 - x) ** 2 + (y1 - y) ** 2)\n if d <= 2 * r:\n delta = math.acos(d / (2 * r))\n angle = math.atan2(y1 - y, x1 - x)\n order.append((angle - delta, 1))\n order.append((angle + delta, -1))\n order.sort(key=lambda x: (x[0], -x[1]))\n count = 1\n for (_, entry) in order:\n count += entry\n res = max(res, count)\n return res", "def numpoints(points: List[List[int]], r: int) -> int:\n n = len(points)\n ans = 1\n for i in range(n - 1):\n (x1, y1) = (points[i][0], points[i][1])\n for j in range(i + 1, n):\n (x2, y2) = (points[j][0], points[j][1])\n d = (x1 - x2) ** 2 + (y1 - y2) ** 2\n if d > 4 * r * r:\n continue\n (cx, cy) = ((x1 + x2) / 2, (y1 + y2) / 2)\n h = math.sqrt(r * r - d / 4)\n if y1 == y2:\n (dx, dy) = (0, h)\n else:\n m = -(x1 - x2) / (y1 - y2)\n (dx, dy) = (h / math.sqrt(1 + m * m), h * m / math.sqrt(1 + m * m))\n for sign in [1, -1]:\n count = 0\n (px, py) = (cx + sign * dx, cy + sign * dy)\n for (k, (x, y)) in enumerate(points):\n if (x - px) ** 2 + (y - py) ** 2 <= r * r + 1e-07:\n count += 1\n ans = max(ans, count)\n return ans", "def numpoints(points: List[List[int]], r: int) -> int:\n best = 1\n for i in range(len(points)):\n p1 = complex(*points[i])\n for j in range(i + 1, len(points)):\n p2 = complex(*points[j])\n d = abs(p1 - p2)\n if d > 2 * r:\n continue\n h = math.sqrt(r * r - d * d / 4)\n c = (p1 + p2) / 2 + (p1 - p2) * h / d * 1j\n count = 0\n for (x, y) in points:\n if (x - c.real) ** 2 + (y - c.imag) ** 2 <= r ** 2 + 1e-06:\n count += 1\n best = max(best, count)\n return best", "def numpoints(points: List[List[int]], r: int) -> int:\n eps = 1e-09\n ret = 1\n n = len(points)\n if n == 1:\n return ret\n points.sort()\n\n def isect(x1, y1, x2, y2):\n dx2 = (x2 - x1) ** 2\n dy2 = (y2 - y1) ** 2\n if dx2 + dy2 > 4 * r * r:\n return []\n cx = (x1 + x2) / 2\n cy = (y1 + y2) / 2\n if dx2 + dy2 == 4 * r * r:\n return [(cx, cy)]\n ss2 = (dx2 + dy2) / 4\n ol = math.sqrt(r ** 2 - ss2)\n diffx = ol * math.sqrt(dy2 / (dx2 + dy2))\n diffy = ol * math.sqrt(dx2 / (dx2 + dy2))\n return [(cx - diffx, cy + diffy), (cx + diffx, cy - diffy)]\n for i in range(n - 1):\n (a, b) = points[i]\n for j in range(i + 1, n):\n (c, d) = points[j]\n l = isect(a, b, c, d)\n for (x, y) in l:\n cur = 0\n lb = bisect.bisect_left(points, [x - r - eps, y - r - eps])\n ub = bisect.bisect_right(points, [x + r + eps, y + r + eps])\n for k in range(lb, ub):\n dx = points[k][0] - x\n dy = points[k][1] - y\n if dx ** 2 + dy ** 2 <= (r + eps) ** 2:\n cur += 1\n ret = max(ret, cur)\n return ret", "def numpoints(points: List[List[int]], r: int) -> int:\n\n def find(cx, cy, r):\n ans = 0\n for (x, y) in points:\n if (x - cx) ** 2 + (y - cy) ** 2 <= r ** 2 + 1e-06:\n ans += 1\n return ans\n ans = 1\n for i in range(len(points)):\n (x1, y1) = points[i]\n for j in range(i + 1, len(points)):\n (x2, y2) = points[j]\n deno = (y1 - y2) ** 2 + (x1 - x2) ** 2\n if deno > 4 * r * r:\n continue\n k = math.sqrt(r * r / deno - 0.25)\n ans = max(ans, max((find((x1 + x2) / 2 + t * (y1 - y2), (y1 + y2) / 2 - t * (x1 - x2), r) for t in (k, -k))))\n return ans", "import math as m\n\ndef dist(p1, p2):\n dx = p1[0] - p2[0]\n dy = p1[1] - p2[1]\n return m.sqrt(dx * dx + dy * dy)\n\ndef intersect(p1, p2, r):\n res = []\n d = self.dist(p1, p2) - 2 * r\n if d > 0:\n res = []\n elif d == 0:\n res = [[(p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2]]\n else:\n mid_x = (0.0 + p1[0] + p2[0]) / 2\n mid_y = (0.0 + p1[1] + p2[1]) / 2\n if p1[1] != p2[1]:\n ratio = -(0.0 + p1[0] - p2[0]) / (0.0 + p1[1] - p2[1])\n eps = m.sqrt((r ** 2 - self.dist([mid_x, mid_y], p1) ** 2) / (ratio ** 2 + 1))\n fun = eps * ratio\n else:\n eps = 0\n fun = m.sqrt(r ** 2 - self.dist([mid_x, mid_y], p1) ** 2)\n res = [[mid_x + eps, mid_y + fun], [mid_x - eps, mid_y - fun]]\n return res\n\ndef numpoints(points, r):\n l = len(points)\n result = 1\n for i in range(l):\n for j in range(i + 1, l):\n c = self.intersect(points[i], points[j], r)\n for p in c:\n au = 0\n for k in range(l):\n if self.dist(p, points[k]) <= r:\n au += 1\n result = max(result, au)\n return result", "import math\n\ndef numpoints(points: List[List[int]], r: int) -> int:\n self.total = len(points)\n maxPoints = 0\n for i in range(self.total):\n maxPoints = max(maxPoints, self.numpointsInCircle(points, r, i))\n return maxPoints\n\ndef numpointsInCircle(points, r, chosenIndex):\n maxPoints = 0\n enterList = []\n exitList = []\n numberPoints = 0\n for i in range(self.total):\n answer = self.computeRange(points, r, chosenIndex, i)\n if answer != None:\n if len(answer) == 0:\n numberPoints += 1\n else:\n (enterAngle, exitAngle) = answer\n enterList.append(enterAngle)\n exitList.append(exitAngle)\n if enterAngle > exitAngle:\n numberPoints += 1\n exitList.sort()\n enterList.sort()\n maxPoints = numberPoints\n exitCounter = 0\n enterCounter = 0\n pointsToCheck = len(exitList)\n while max(exitCounter, enterCounter) < pointsToCheck:\n currentExit = exitList[exitCounter]\n currentEnter = enterList[enterCounter]\n if currentEnter <= currentExit:\n numberPoints += 1\n maxPoints = max(maxPoints, numberPoints)\n enterCounter += 1\n else:\n numberPoints -= 1\n exitCounter += 1\n while exitCounter < pointsToCheck:\n numberPoints -= 1\n exitCounter += 1\n while enterCounter < pointsToCheck:\n numberPoints += 1\n maxPoints = max(maxPoints, numberPoints)\n enterCounter += 1\n return maxPoints\n\ndef computeRange(points, r, chosenIndex, otherIndex):\n chosenPair = points[chosenIndex]\n otherPair = points[otherIndex]\n if chosenPair == otherPair:\n return []\n else:\n distance = self.distanceBetweenPoints(chosenPair, otherPair)\n if distance > 2 * r:\n return None\n else:\n angleOne = self.computeAngle(chosenPair, otherPair)\n angleTwo = math.acos(distance / (2 * r))\n exit = angleOne + angleTwo\n exit = exit - 2 * math.pi if exit >= math.pi else exit\n enter = angleOne - angleTwo\n enter = enter + 2 * math.pi if enter < -math.pi else enter\n return [enter, exit]\n\ndef computeAngle(pairOne, pairTwo):\n (x1, y1) = pairOne\n (x2, y2) = pairTwo\n return math.atan2(y2 - y1, x2 - x1)\n\ndef numberPointsStart(enterList, exitList):\n pass\n\ndef distanceBetweenPoints(pairOne, pairTwo):\n (x1, y1) = pairOne\n (x2, y2) = pairTwo\n return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)", "import math\nfrom decimal import Decimal as D\n\ndef numpoints(points: List[List[int]], r: int) -> int:\n\n def circles_from_p1p2r(p1, p2, r):\n ((x1, y1), (x2, y2)) = (p1, p2)\n (dx, dy) = (x2 - x1, y2 - y1)\n q = math.sqrt(dx ** 2 + dy ** 2)\n if q > 2.0 * r:\n return []\n (x3, y3) = ((x1 + x2) / 2, (y1 + y2) / 2)\n d = math.sqrt(r ** 2 - (q / 2) ** 2)\n c1 = [x3 - d * dy / q, y3 + d * dx / q]\n c2 = [x3 + d * dy / q, y3 - d * dx / q]\n return [c1, c2]\n res = 0\n n = len(points)\n for p in range(n):\n for q in range(p + 1, n):\n TwoCirs = circles_from_p1p2r(points[p], points[q], r)\n for center in TwoCirs:\n cnt = 0\n for dots in points:\n if (dots[0] - center[0]) ** 2 + (dots[1] - center[1]) ** 2 <= r ** 2 + 10 ** (-6):\n cnt += 1\n res = max(res, cnt)\n return res if res else 1", "def getC(p1, p2, r):\n ([x1, y1], [x2, y2]) = (p1, p2)\n dist = sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\n if dist > 2.0 * r:\n return []\n (x3, y3) = ((x1 + x2) / 2, (y1 + y2) / 2)\n magnitude = sqrt(r ** 2 - (dist / 2) ** 2)\n c1 = [x3 - magnitude * (y1 - y2) / dist, y3 + magnitude * (x1 - x2) / dist]\n c2 = [x3 + magnitude * (y1 - y2) / dist, y3 - magnitude * (x1 - x2) / dist]\n return [c1, c2]\n\ndef numpoints(points: List[List[int]], r: int) -> int:\n ans = 0\n for i in range(len(points)):\n for j in range(i + 1, len(points)):\n C = self.getC(points[i], points[j], r)\n for c in C:\n cnt = 0\n for pt in points:\n if (pt[0] - c[0]) ** 2 + (pt[1] - c[1]) ** 2 <= r ** 2 + 1e-06:\n cnt += 1\n ans = max(ans, cnt)\n return ans if ans else 1", "def numpoints(points: List[List[int]], r: int) -> int:\n n = len(points)\n result = 1\n\n def calc_dist(pt1, pt2):\n (x1, y1) = pt1\n (x2, y2) = pt2\n return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\n\n def get_centers(i, j):\n d_xy = calc_dist(points[i], points[j])\n if d_xy > r * 2:\n return []\n delta_x = points[j][0] - points[i][0]\n delta_y = points[j][1] - points[i][1]\n x_mid = points[i][0] + delta_x / 2\n y_mid = points[i][1] + delta_y / 2\n if d_xy == r * 2:\n return [(x_mid, y_mid)]\n d = math.sqrt(r ** 2 - (d_xy / 2) ** 2)\n return [(x_mid + d * delta_y / d_xy, y_mid - d * delta_x / d_xy), (x_mid - d * delta_y / d_xy, y_mid + d * delta_x / d_xy)]\n\n def count_points_inside(center, i, j):\n count = 2\n for idx in range(n):\n if idx == i or idx == j:\n continue\n count += calc_dist(center, points[idx]) <= r\n return count\n for i in range(n):\n for j in range(i + 1, n):\n centers = get_centers(i, j)\n for center in centers:\n result = max(result, count_points_inside(center, i, j))\n return result", "def numpoints(points: List[List[int]], r: int) -> int:\n\n def within(pt, cen, r2):\n (a1, a2) = pt\n (p1, p2) = cen\n return (a1 - p1) ** 2 + (a2 - p2) ** 2 <= r2\n ans = 1\n for (idx, a) in enumerate(points):\n for b in points[:idx]:\n (a1, a2) = a\n (b1, b2) = b\n if (a1 - b1) ** 2 + (a2 - b2) ** 2 <= 4 * r ** 2:\n pos_cir = 0\n neg_cir = 0\n mid = ((a1 + b1) / 2, (a2 + b2) / 2)\n perp = (b2 - a2, a1 - b1)\n perp_dis = (perp[0] ** 2 + perp[1] ** 2) ** 0.5\n p_dis = (r ** 2 - ((a1 - b1) ** 2 + (a2 - b2) ** 2) / 4) ** 0.5\n cen = (mid[0] + perp[0] * p_dis / perp_dis, mid[1] + perp[1] * p_dis / perp_dis)\n ocen = (mid[0] + perp[0] * p_dis / perp_dis, mid[1] + perp[1] * p_dis / perp_dis)\n for c in points:\n if within(c, cen, r ** 2 + 1e-08):\n pos_cir += 1\n if within(c, ocen, r ** 2 + 1e-08):\n neg_cir += 1\n ans = max(ans, pos_cir, neg_cir)\n return ans", "def numpoints(points: List[List[int]], r: int) -> int:\n\n def getpoints(l, i, r, n, dis):\n d = {}\n pi = 3.1415626\n angles = []\n for j in range(n):\n if i != j and dis[i][j] <= 2 * r:\n B = math.acos(dis[i][j] / (2 * r))\n A = math.acos((l[j][0] - l[i][0]) / dis[i][j])\n if l[j][1] - l[i][1] < 0:\n A = 2 * pi - A\n a = A - B\n b = A + B\n angles.append((a, 0))\n angles.append((b, 1))\n angles.sort()\n ct = 1\n res = 1\n for a in angles:\n if a[1] == 0:\n ct += 1\n else:\n ct -= 1\n res = max(res, ct)\n return res\n n = len(points)\n dis = [[0 for j in range(n)] for i in range(n)]\n for i in range(n - 1):\n for j in range(i + 1, n):\n dis[i][j] = ((points[i][0] - points[j][0]) ** 2 + (points[i][1] - points[j][1]) ** 2) ** 0.5\n dis[j][i] = ((points[i][0] - points[j][0]) ** 2 + (points[i][1] - points[j][1]) ** 2) ** 0.5\n ans = 0\n for i in range(n):\n ans = max(ans, getpoints(points, i, r, n, dis))\n return ans", "import itertools\n\ndef numpoints(points: List[List[int]], r: int) -> int:\n ans = 1\n for ((x1, y1), (x2, y2)) in itertools.combinations(points, 2):\n d = ((x1 - x2) ** 2 + (y1 - y2) ** 2) / 4.0\n if d <= r * r:\n x0 = (x1 + x2) / 2.0 + (y2 - y1) * (r * r - d) ** 0.5 / (d * 4) ** 0.5\n y0 = (y1 + y2) / 2.0 - (x2 - x1) * (r * r - d) ** 0.5 / (d * 4) ** 0.5\n ans = max(ans, sum(((x - x0) ** 2 + (y - y0) ** 2 <= r * r + 1e-05 for (x, y) in points)))\n return ans"], "starter_code": "def numpoints(points: List[List[int]], r: int) -> int:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Math", "Geometry", "Array"], "name": null, "source": "leetcode", "tags": ["Geometry", "Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numpoints", "task_id": "TACO_lite/301", "example": [[[[[-2, 0], [2, 0], [0, 2], [0, -2]], 2], [[[-3, 0], [3, 0], [2, 6], [5, 4], [0, 9], [7, 8]], 5], [[[-2, 0], [2, 0], [0, 2], [0, -2]], 1], [[[1, 2], [3, 5], [1, -1], [2, 3], [4, 1], [1, 3]], 2]], ["4", "5", "1", "4"]]} +{"requirement": "You like the way the Python `+` operator easily handles adding different numeric types, but you need a tool to do that kind of addition without killing your program with a `TypeError` exception whenever you accidentally try adding incompatible types like strings and lists to numbers.\n\nYou decide to write a function `my_add()` that takes two arguments. If the arguments can be added together it returns the sum. If adding the arguments together would raise an error the function should return `None` instead.\n\nFor example, `my_add(1, 3.414)` would return `4.414`, but `my_add(42, \" is the answer.\")` would return `None`.\n\nHint: using a `try` / `except` statement may simplify this kata.", "solutions": ["def my_add(a, b):\n try:\n return a + b\n except TypeError:\n return None", "def my_add(*a):\n try:\n return sum(a)\n except:\n pass", "def my_add(a, b):\n try:\n ans = a + b\n return ans\n except:\n return None", "def my_add(a, b):\n try:\n return a + b\n except:\n pass", "def my_add(a, b):\n return a + b if isinstance(a, (int, float, complex)) and isinstance(b, (int, float, complex)) else None", "def my_add(a, b):\n try:\n a + b\n except:\n try:\n float(a, b)\n except:\n return None\n return a + b"], "starter_code": "def my_add(a, b):\n", "input_output": {"fn_name": "my_add", "inputs": [[1, 3.414], [42, " is the answer."], [10, "2"]], "outputs": [[4.414], [null], [null]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/58659b1261cbfc8bfc00020a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "my_add", "task_id": "TACO_lite/387", "example": [[[1, 3.414], [42, " is the answer."]], ["4.414", "None"]]} +{"requirement": "Find the Nth term of the Mysterious series.\nN Nth term\n1 5\n2 10\n3 26\n4 50\n5 122\n.\n.\n.\n10 842\nExample 1:\nInput: N = 1\nOutput: 5 \nExplanation: First term of the series is 5.\nExample 2:\nInput: N = 2\nOutput: 10\nExplanation: Second term of the series is 10. \nYour Task: \nYou dont need to read input or print anything. Complete the function nthMysterious() which takes N as input parameter and returns the Nth term of the Mysterious series.\nExpected Time Complexity: O(nlogn)\nExpected Auxiliary Space: O(n)\nConstraints:\n1<= N <=10^{3}", "solutions": ["import math\n\ndef isPrime(n):\n if n == 0 or n == 1:\n return False\n else:\n lim = int(math.sqrt(n)) + 1\n for i in range(2, lim):\n if n % i == 0:\n return False\n return True\n\ndef nthmysterious(N):\n (res, c) = ([], 0)\n for i in range(2, int(100000.0) + 1):\n if self.isPrime(i):\n res.append(i * i + 1)\n c += 1\n if c == N:\n return res[N - 1]", "import math\n\ndef nthmysterious(N):\n j = 2\n i = 0\n while i < N:\n c = 0\n k = int(math.sqrt(j))\n for p in range(2, k + 1):\n if j % p == 0:\n c = 1\n break\n if c == 0:\n l = j\n i = i + 1\n j = j + 1\n return l ** 2 + 1", "def isprime(x):\n for i in range(2, int(x ** (1 / 2)) + 1):\n if x % i == 0:\n return False\n else:\n continue\n return True\n\ndef nthmysterious(n):\n a = []\n i = 2\n k = 0\n while k < n:\n if isprime(i) == True:\n k = k + 1\n p = i\n i = i + 1\n else:\n i = i + 1\n return p ** 2 + 1", "def nthmysterious(N):\n\n def nthPrime(n):\n\n def isPrime(n):\n for i in range(5, int(n ** 0.5) + 1, 2):\n if not n % i:\n return False\n return True\n if n < 3:\n return n + 1\n p = 5\n for i in range(4, n + 1):\n p += (p + 3) % 6\n while not isPrime(p):\n p += (p + 3) % 6\n return p", "import math\n\ndef nthmysterious(n):\n\n def isPrime(x):\n for i in range(2, int(math.sqrt(x)) + 1):\n if x % i == 0:\n return False\n return True\n ans = 1\n arr = []\n i = 2\n while len(arr) < n:\n if isPrime(i):\n arr.append(i)\n i += 1\n return arr[n - 1] ** 2 + 1", "def nthmysterious(N):\n x = N\n (n, c) = (1, 0)\n while c < x:\n n += 1\n for i in range(2, n + 1):\n if n % i == 0:\n break\n if i == n:\n c = c + 1\n return n ** 2 + 1", "def isprime(N):\n if N <= 1:\n return False\n k = int(N ** 0.5)\n for i in range(2, k + 1):\n if N % i == 0:\n return False\n return True\n\ndef nthmysterious(N):\n i = 2\n c = 0\n while True:\n if self.isprime(i):\n c += 1\n if c == N:\n return i * i + 1\n i += 1", "import math\n\ndef isPrime(n):\n if n <= 1:\n return False\n max_div = math.floor(math.sqrt(n))\n for i in range(2, max_div + 1):\n if n % i == 0:\n return False\n return True\n\ndef nthmysterious(N):\n v = []\n c = 0\n for i in range(2, 100000):\n if self.isPrime(i):\n v.append(i * i + 1)\n c += 1\n if c == N:\n return v[N - 1]", "def isprime(n):\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef nthmysterious(N):\n l = [1, 2 * 2 + 1, 3 * 3 + 1, 5 * 5 + 1]\n for i in range(7, 100001):\n x1 = isprime(i)\n if x1:\n l.append(i * i + 1)\n if len(l) > N:\n break\n return l[N]", "def prime(n):\n for i in range(2, n):\n if n % i == 0:\n return 0\n if n % n == 0 and n % 1 == 0:\n return 1\n\ndef nthmysterious(N):\n l = []\n i = 2\n while len(l) != N:\n a = self.prime(i)\n if a == 1:\n l.append(i ** 2 + 1)\n i = i + 1\n return l[N - 1]", "def nthmysterious(k):\n c = 0\n n = 2\n m = 0\n while 1:\n p = 1\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n p = 0\n break\n if p == 1:\n c = c + 1\n m = n\n if c == k:\n break\n n = n + 1\n return m ** 2 + 1", "def nthmysterious(N):\n l = []\n i = 2\n while len(l) != N:\n for j in range(2, i // 2 + 1):\n if i % j == 0:\n break\n else:\n l.append(i)\n i += 1\n return l[N - 1] ** 2 + 1", "def prime(n):\n for i in range(2, n // 2 + 1):\n if n % i == 0:\n return 0\n return 1\n\ndef nthmysterious(n):\n i = 2\n c = 0\n while n != c:\n if self.prime(i):\n k = i\n c = c + 1\n i = i + 1\n return k * k + 1", "from math import sqrt\nfrom itertools import compress\n\ndef __init__():\n if not Solution.list_created:\n Solution.utility()\n\ndef utility():\n for i in range(2, int(sqrt(Solution.N)) + 1):\n if Solution.bool_prime_list[i]:\n j = i ** 2\n while j < Solution.N:\n Solution.bool_prime_list[j] = False\n j += i\n Solution.list_of_prime = list(compress(list(range(0, Solution.N + 1)), Solution.bool_prime_list))\n\ndef nthmysterious(N):\n return Solution.list_of_prime[N] ** 2 + 1", "def isPrime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True\n\ndef nthmysterious(N):\n li = list()\n count = 0\n for i in range(100000):\n if isPrime(i):\n li.append(i * i + 1)\n count += 1\n if count == N:\n return li[N - 1]"], "starter_code": "def nthmysterious (N):\n", "input_output": {"inputs": ["N = 1", "N = 2"], "outputs": ["5", "10"]}, "difficulty": "EASY", "raw_tags": ["Prime Number", "series"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory", "Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/mysterious-series5049/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(nlogn)", "entry_point": "nthmysterious", "task_id": "TACO_lite/399", "example": [[[1], [2]], ["5", "10"]]} +{"requirement": "Given N find all Sophie Germain Prime numbers less than N . A prime number p is called a sophie prime number if 2p+1 is also a prime number. The number 2p+1 is called a safe prime. \nExample 1:\nInput: N = 5\nOutput: 2 3\nExplanation: 2 and 3 are prime no. and \n2*2+1 = 5 and 3*2+1 = 7 are also prime\nno.\nExample 2:\nInput: N = 3\nOutput: 2\nExplanation: 2 is prime number and 2*2+1\n= 5 is also a prime number.\n \nYour Task:\nYou don't need to read or print anything your task is to complete the function sophie_primes() which takes N as input parameter and returns a list of all Sophie Germain Prime numbers in increasing order.\n \nExpected Time Compelxity: O(N* log(N))\nExpected Space Compelxity: O(N)\nConstraints:\n1 <= N <= 10000", "solutions": ["def isprime(N):\n if N == 1:\n return False\n for i in range(2, int(N ** 0.5) + 1, 1):\n if N % i == 0:\n return False\n return True\n\ndef sophie_primes(n):\n l = []\n for i in range(2, n, 1):\n if self.isprime(i) and self.isprime(2 * i + 1):\n l.append(i)\n return l", "import math\n\ndef fun(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i = i + 6\n return True\n\ndef sophie_primes(n):\n d = []\n for i in range(2, n):\n s = 2 * i + 1\n if fun(s) and fun(i):\n d.append(i)\n return d", "def sophie_primes(n):\n\n def f(n):\n if n == 0 or n == 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n res = []\n for i in range(n):\n if f(i) and f(2 * i + 1):\n res.append(i)\n return res", "def sophie_primes(n):\n\n def is_prime(num):\n i = 2\n while i * i <= num:\n if num % i == 0:\n return False\n i += 1\n return True\n res = []\n for i in range(2, n):\n if is_prime(i) and is_prime(i * 2 + 1):\n res.append(i)\n return res", "import math\n\ndef sophiPrime(n):\n num = 2 * n + 1\n for x in range(2, int(math.sqrt(num)) + 1):\n if num % x == 0:\n return False\n return True\n\ndef isPrime(num):\n for x in range(2, int(math.sqrt(num)) + 1):\n if num % x == 0:\n return False\n return sophiPrime(num)\n\ndef sophie_primes(n):\n res = []\n for x in range(2, n):\n if isPrime(x):\n res.append(x)\n return res", "def sophie_primes(n):\n\n def isPrime(num):\n if num < 2:\n return 0\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return 0\n return 1\n prime = [0] * n\n ans = []\n for i in range(2, n):\n prime[i] = i\n for i in range(2, int(n ** 0.5) + 1):\n if prime[i] == i:\n if isPrime(2 * i + 1) == 1:\n ans.append(i)\n for j in range(i * i, n, i):\n prime[j] = 0\n for i in range(int(n ** 0.5) + 1, n):\n if prime[i] == i:\n if isPrime(2 * i + 1) == 1:\n ans.append(i)\n return ans", "import math\n\ndef sophie_primes(n):\n l = 20002\n siv = [0] * l\n siv[0] = 1\n siv[1] = 1\n for i in range(2, int(math.sqrt(l)) + 1):\n if siv[i] == 0:\n for j in range(2 * i, l, i):\n siv[j] = 1\n lis = []\n for i in range(2, n):\n if siv[i] == False and siv[2 * i + 1] == False:\n lis.append(i)\n return lis", "def sophie_primes(n):\n ans = []\n\n def isPrime(num):\n if num < 2:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return False\n return True\n for i in range(0, n):\n if isPrime(i) and isPrime(2 * i + 1):\n ans.append(i)\n return ans", "prime = [True for i in range(10 ** 6 + 1)]\n\ndef genseive():\n global prime\n n = 10 ** 6\n if prime[4] == False:\n return\n (prime[0], prime[1]) = (False, False)\n p = 2\n while p * p <= n:\n if prime[p] == True:\n for i in range(p * p, n, p):\n prime[i] = False\n p += 1\n\ndef sophie_primes(n):\n self.genseive()\n l = []\n for i in range(2, n):\n if prime[i] == True and prime[2 * i + 1] == True:\n l.append(i)\n return l", "sieve = [True for i in range(10 ** 6 + 1)]\n\ndef gen_sieve():\n global sieve\n n = 10 ** 6\n if sieve[4] == False:\n return\n (sieve[0], sieve[1]) = (False, False)\n i = 2\n while i <= n:\n if sieve[i]:\n c = i * i\n while c <= n:\n sieve[c] = False\n c += i\n i += 1\n\ndef sophie_primes(n):\n self.gen_sieve()\n l = []\n for i in range(2, n):\n if sieve[i] == True and sieve[2 * i + 1] == True:\n l.append(i)\n return l", "def sophie_primes(n):\n from math import sqrt\n N = n\n n = n * 2\n l = [0, 0] + [1] * (n + 1)\n k = []\n for i in range(2, int(sqrt(n)) + 1):\n if l[i] == 1:\n for j in range(i * i, n + 1, i):\n l[j] = 0\n for i in range(2, N):\n if l[i] == 1 and l[2 * i + 1] == 1:\n k.append(i)\n return k", "import math\n\ndef sophie_primes(n):\n if n == 0 or n == 1:\n return ''\n l = []\n m = []\n s = [True for i in range(n + 1)]\n s[0] = False\n s[1] = False\n for i in range(2, int(math.sqrt(n)) + 1):\n if s[i] == True:\n for j in range(i * i, n, i):\n s[j] = False\n for i in range(len(s)):\n if s[i] == True:\n l.append(i)\n for j in range(len(l) - 1):\n k = 2 * l[j] + 1\n c = 0\n for b in range(2, int(math.sqrt(k)) + 1):\n if k % b == 0:\n c += 1\n if c == 0:\n m.append(l[j])\n return m", "def sophie_primes(n):\n\n def prime(k):\n if k == 0 or k == 1:\n return 0\n for i in range(2, int(k ** 0.5) + 1):\n if k % i == 0:\n return 0\n return 1\n li = []\n for i in range(1, n):\n if prime(i) and prime(2 * i + 1):\n li.append(i)\n return li", "def sophie_primes(n):\n import math as m\n\n def isprime(n):\n sq = int(m.sqrt(n))\n for i in range(2, sq + 1):\n if n % i == 0:\n return False\n else:\n return True\n l = []\n for i in range(2, n):\n a = i * 2 + 1\n if isprime(i) and isprime(a):\n l.append(i)\n return l", "def sophie_primes(n):\n import math\n a = []\n prime = [1] * (n + n + 1)\n prime[0] = prime[1] = 0\n for i in range(2, n):\n if prime[i] == 1:\n for j in range(i * i, n + n + 1, i):\n prime[j] = 0\n for i in range(1, n):\n if prime[i] == 1 and prime[2 * i + 1] == 1:\n a.append(i)\n return a", "def sophie_primes(n):\n\n def sieve(x):\n pri = [1] * x\n (pri[0], pri[1]) = (0, 0)\n i = 2\n while i * i < x:\n if pri[i]:\n for _ in range(i * i, x, i):\n pri[_] = 0\n i += 1\n return pri\n s = sieve(2 * n + 1)\n l = []\n for i in range(n):\n if s[i]:\n p = 2 * i + 1\n if s[p]:\n l.append(i)\n return l", "import math\n\ndef primes(n):\n if n == 0 or n == 1:\n return False\n if n == 2 or n == 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n for i in range(5, int(math.sqrt(n)) + 1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\ndef sophie_primes(n):\n d = []\n for i in range(n):\n if self.primes(i):\n c = i * 2 + 1\n if self.primes(c):\n d.append(i)\n return d", "def sophie_primes(n):\n\n def generate(n):\n primes = [True] * n\n (primes[0], primes[1]) = (False, False)\n p = 2\n while p * p <= n:\n if primes[p]:\n for _ in range(p * p, n, p):\n if primes[_]:\n primes[_] = False\n p += 1\n return primes\n l = []\n x = generate(100001)\n for i in range(n):\n if x[i]:\n p = 2 * i + 1\n if x[p]:\n l.append(i)\n return l", "import math\n\ndef sophie_primes(n):\n l = []\n if n == 0 or n == 1:\n return []\n\n def pri(u):\n for i in range(2, int(math.sqrt(u)) + 1):\n if u % i == 0:\n return False\n return True\n prime = [1] * n\n (prime[0], prime[1]) = (0, 0)\n for i in range(2, int(math.sqrt(n)) + 1):\n if prime[i]:\n for j in range(i * i, n, i):\n prime[j] = 0\n for i in range(len(prime)):\n if prime[i] == 1 and pri(2 * i + 1):\n l.append(i)\n return l", "def sophie_primes(n):\n\n def seive(i):\n l = [1 for j in range(i + 1)]\n l[0] = 0\n l[1] = 0\n p = 2\n while p * p <= i:\n if l[p] == 1:\n for k in range(p * p, i + 1, p):\n l[k] = 0\n p += 1\n return l\n i = 20001\n res = seive(i)\n l = []\n for j in range(n):\n if res[j] == 1:\n p = 2 * j + 1\n if p < i and res[p] == 1:\n l.append(j)\n return l", "import math\n\ndef sophie_primes(n):\n\n def isprime(n):\n a = int(math.sqrt(n))\n if n == 0 or n == 1:\n return False\n for i in range(2, a + 1):\n if n % i == 0:\n return False\n return True\n l = []\n for i in range(2, n):\n if isprime(i) and isprime(2 * i + 1):\n l.append(i)\n return l", "def sophie_primes(n):\n prime = [1 for i in range(2 * n + 1)]\n l = []\n prime[0] = 0\n prime[1] = 0\n p = 2\n while p * p <= 2 * n + 1:\n if prime[p] == 1:\n for i in range(p * p, 2 * n + 1, p):\n prime[i] = 0\n p += 1\n for i in range(2, n):\n if prime[i] == 1:\n a = 2 * i + 1\n if prime[a] == 1:\n l.append(i)\n return l", "def sophie_primes(n):\n\n def prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i = i + 6\n return True\n k = []\n for i in range(1, n):\n if prime(i) and prime(2 * i + 1):\n k.append(i)\n return k", "def sophie_primes(n):\n c = [True] * (2 * n + 1)\n p = 2\n d = []\n while p * p <= 2 * n + 1:\n if c[p] == True:\n for i in range(p * p, 2 * n + 1, p):\n c[i] = False\n p = p + 1\n for i in range(2, len(c) // 2):\n if c[i] == True and c[2 * i + 1] == True:\n d.append(i)\n return d", "def sophie_primes(n):\n if n == 1 or n == 2:\n return []\n c = []\n import math\n for i in range(2, n):\n p = 0\n for j in range(2, int(math.sqrt(i)) + 1):\n if i % j == 0:\n p = 1\n break\n if p == 0:\n z = 0\n b = int(2 * i + 1)\n for k in range(2, int(math.sqrt(b)) + 1):\n if b % k == 0:\n z = 1\n break\n if z == 0:\n c.append(i)\n return c", "import math\n\ndef isprime(n):\n if n == 1 or n == 0:\n return 0\n if n == 2 or n == 3:\n return 1\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return 0\n return 1\n\ndef sophie_primes(n):\n l = []\n for i in range(n):\n if isprime(i) == 1:\n j = 2 * i + 1\n if isprime(j) == 1:\n l.append(i)\n return l", "from math import sqrt\n\ndef prime(n):\n if n <= 1:\n return 0\n for i in range(2, int(sqrt(n)) + 1):\n if n % i == 0:\n return 0\n else:\n return 1\n\ndef sophie_primes(n):\n l = []\n for i in range(2, n):\n if prime(i) == 1 and prime(2 * i + 1) == 1:\n l.append(i)\n return l"], "starter_code": "def sophie_primes(n):\n", "input_output": {"inputs": ["N = 5", "N = 3"], "outputs": ["2 3", "2"]}, "difficulty": "EASY", "raw_tags": ["Prime Number", "sieve"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/sophie-germain-prime2014/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N* log(N))", "entry_point": "sophie_primes", "task_id": "TACO_lite/375", "example": [[], []]} +{"requirement": "Build a function `sumNestedNumbers`/`sum_nested_numbers` that finds the sum of all numbers in a series of nested arrays raised to the power of their respective nesting levels. Numbers in the outer most array should be raised to the power of 1.\n\nFor example,\n\nshould return `1 + 2*2 + 3 + 4*4 + 5*5*5 === 149`", "solutions": ["def sum_nested_numbers(a, depth=1):\n return sum((sum_nested_numbers(e, depth + 1) if type(e) == list else e ** depth for e in a))", "def sum_nested_numbers(arr, m=1):\n total = 0\n for element in arr:\n if isinstance(element, int):\n total += element ** m\n else:\n total += sum_nested_numbers(element, m + 1)\n return total", "def sum_nested_numbers(a, lvl=0):\n return a ** lvl if not isinstance(a, list) else sum((sum_nested_numbers(b, lvl + 1) for b in a))", "def sum_nested_numbers(arr, depth=1):\n return sum((sum_nested_numbers(x, depth + 1) if type(x) is list else x ** depth for x in arr))", "def flatten(xs, level=1):\n for x in xs:\n if isinstance(x, list):\n yield from flatten(x, level + 1)\n else:\n yield (x, level)\n\ndef sum_nested_numbers(xs):\n return sum((x ** level for (x, level) in flatten(xs)))", "def depth(arr, n):\n res = []\n for i in arr:\n if isinstance(i, int):\n res.append((i, n))\n else:\n res += depth(i, n + 1)\n return res\n\ndef sum_nested_numbers(arr):\n return sum((n ** i for (n, i) in depth(arr, 1)))", "def sum_nested_numbers(x):\n return sum(f(x))\n\ndef f(lst, v=1):\n for x in lst:\n if isinstance(x, (list, tuple)):\n for j in f(x, v + 1):\n yield j\n else:\n yield (x ** v)", "sum_nested_numbers = r = lambda a, p=1: sum((n ** p if n * 0 == 0 else r(n, p + 1) for n in a))", "def sum_nested_numbers(arr, d=1):\n my_sum = 0\n for v in arr:\n if isinstance(v, list):\n my_sum += sum_nested_numbers(v, d + 1)\n else:\n my_sum += v ** d\n return my_sum"], "starter_code": "def sum_nested_numbers(a, depth=1):\n", "input_output": {"fn_name": "sum_nested_numbers", "inputs": [[[0]], [[1, 2, 3, 4, 5]], [[1, [2], 3, [4, [5]]]], [[6, [5], [[4]], [[[3]]], [[[[2]]]], [[[[[1]]]]]]], [[1, [-1], [[1]], [[[-1]]], [[[[1]]]]]]], "outputs": [[0], [15], [149], [209], [5]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5845e6a7ae92e294f4000315", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sum_nested_numbers", "task_id": "TACO_lite/285", "example": [[[[1, [2, 3], [4, [5]]]]], ["149"]]} +{"requirement": "Ishaan has been given a task by his teacher. He needs to find the Nth term of a series. His teacher gives him some examples to help him out (Refer examples below). He is a bit weak in pattern searching so to help him his teacher told him that the Nth term is related to prime numbers. The Nth term is the difference of N and the closest prime number to N. Help him find the Nth term for a given N.\n \nExample 1:\nInput: N = 10\nOutput: 1\nExplanation: Closest prime to 10 is 11.\nExample 2:\nInput: N = 7\nOutput: 0\nExplanation: Closest prime to 7 is 7.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function NthTerm() which takes N as input paramater and returns Nth term.\n \nExpected Time Complexity: O(N* √ N)\nExpected Space Complexity: O(1)\nConstraints:\n1 <= N <= 100000", "solutions": ["def nthterm(N):\n\n def bo(x):\n if x < 2:\n return False\n i = 2\n while i * i <= x:\n if x % i == 0:\n return False\n i = i + 1\n return True\n z = N\n y = N\n if N == 1:\n return 1\n while True:\n if bo(y):\n break\n y = y + 1\n while z > 1:\n if bo(z):\n break\n z = z - 1\n if y - N > N - z:\n return N - z\n else:\n return y - N", "def is_prime(n):\n if n < 4:\n return True\n i = 2\n while i * i <= n:\n if n % i == 0:\n return False\n i += 1\n return True\n\ndef nthterm(N):\n if N == 1:\n return N\n c = 1\n if self.is_prime(N):\n return 0\n for i in range(1, N):\n if self.is_prime(N - i):\n return c\n elif self.is_prime(N + i):\n return c\n else:\n c += 1", "def isPrime(N):\n if N == 1:\n return False\n if N == 2 or N == 3:\n return True\n for i in range(2, int(N ** 0.5) + 1):\n if N % i == 0:\n return False\n return True\n\ndef nthterm(N):\n i = 0\n while True:\n if self.isPrime(N + i):\n return i\n if N - i > 0 and self.isPrime(N - i):\n return i\n i += 1\n return -1", "import math\n\ndef isprime(num):\n a = 2\n while a <= math.sqrt(num):\n if num % a < 1:\n return False\n a = a + 1\n return num > 1\n\ndef nthterm(N):\n i = N\n j = i\n while 1:\n if isprime(i):\n return i - N\n elif isprime(j):\n return N - j\n i += 1\n j -= 1", "def nthterm(N):\n\n def p(x):\n if x == 1:\n return 0\n for i in range(2, int(x ** 0.5) + 1):\n if x % i == 0:\n return 0\n return 1\n\n def np(x):\n while p(x) != 1:\n x = x + 1\n return x\n\n def pp(x):\n while p(x) != 1:\n x = x - 1\n return x\n a = np(N)\n b = pp(N)\n if p(N) == 1:\n return 0\n else:\n return min(abs(N - a), abs(N - b))", "def nthterm(N):\n ans = self.near_prime(N)\n if ans >= N:\n ans -= N\n else:\n ans = N - ans\n return ans\n\ndef is_prime(N):\n if N < 2:\n return False\n else:\n for i in range(2, int(N ** (1 / 2) + 1)):\n if N % i == 0:\n return False\n return True\n\ndef near_prime(N):\n if self.is_prime(N):\n return N\n else:\n lowr_num = N - 1\n upper_num = N + 1\n while True:\n if self.is_prime(lowr_num) == True:\n return lowr_num\n elif self.is_prime(upper_num) == True:\n return upper_num\n else:\n lowr_num -= 1\n upper_num += 1", "import math\n\ndef nthterm(N):\n\n def Prime(n):\n i = 2\n if n < 2:\n return False\n while i <= math.sqrt(n):\n if n % i == 0:\n return False\n i = i + 1\n return True\n if Prime(N):\n return 0\n i = 1\n while True:\n if Prime(N - i) or Prime(N + i):\n break\n i = i + 1\n return i", "def nthterm(N):\n i = 0\n while True:\n if self.isprime(N + i) or self.isprime(N - i):\n return i\n i += 1\n return i\n\ndef isprime(n):\n if n == 1:\n return 0\n elif n <= 3:\n return 1\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return 0\n return 1", "import math\n\ndef nthterm(N):\n if self.is_prime(N):\n return 0\n else:\n i = 1\n while True:\n if self.is_prime(N - i) or self.is_prime(N + i):\n return i\n else:\n i += 1\n\ndef is_prime(num):\n if num <= 1:\n return False\n upper_limit = math.floor(math.sqrt(num)) + 1\n for i in range(2, upper_limit):\n if num % i == 0:\n return False\n return True", "def prime(n):\n if n < 2:\n return 0\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return 0\n return 1\n\ndef nthterm(N):\n b = N\n N = b + 1\n c = b - 1\n if prime(b):\n return 0\n while N:\n if prime(N):\n break\n N += 1\n while c:\n if prime(c):\n break\n c -= 1\n p = N - b\n q = b - c\n r = min(p, q)\n return r", "import math\n\ndef isPrime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n for i in range(5, int(math.sqrt(n) + 1), 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\ndef nthterm(N):\n if N <= 1:\n h = abs(2 - N)\n return h\n p2 = N\n p1 = N\n f = False\n d = False\n while not f:\n if isPrime(p2) == True:\n f = True\n else:\n p2 = p2 + 1\n while not d:\n if isPrime(p1) == True:\n d = True\n else:\n p1 = p1 - 1\n g1 = abs(p1 - N)\n g = abs(p2 - N)\n return min(g, g1)", "def nthterm(N):\n if N == 1:\n return 1\n\n def prime(x):\n if x == 2:\n return True\n for i in range(2, int(x ** 0.5) + 1):\n if x % i == 0:\n return False\n return True\n if prime(N):\n return 0\n a = N\n b = N\n while not prime(a):\n a -= 1\n while not prime(b):\n b += 1\n return min(abs(N - a), abs(N - b))", "import math\n\ndef isprime(num):\n a = 2\n while a <= math.sqrt(num):\n if num % a < 1:\n return False\n a += 1\n return num > 1\n\ndef nthterm(N):\n les = N\n c = N\n uni = 0\n l = 0\n while c:\n if isprime(c) == True:\n l = c\n break\n c -= 1\n while N:\n if isprime(N) == True:\n uni = N\n break\n N += 1\n if les - l < uni - les:\n return les - l\n else:\n return uni - les", "def isprime(x):\n c = 0\n p = int(x ** 0.5) + 1\n for i in range(2, p):\n if x % i == 0:\n return False\n return True\n\ndef nthterm(N):\n j = N + 1\n i = N\n while True:\n if i > 1 and self.isprime(i):\n return N - i\n if self.isprime(j):\n return j - N\n i -= 1\n j += 1", "import math\n\ndef nthterm(N):\n\n def nextPrimeNumber(n):\n (p1, p2) = (n, n)\n\n def isPrime(num):\n if num <= 1:\n return False\n for i in range(2, int(math.sqrt(num)) + 1):\n if num % i == 0:\n return False\n return True\n while p1 > 0 and (not isPrime(p1)):\n p1 += 1\n while p2 > 0 and (not isPrime(p2)):\n p2 -= 1\n return (p1, p2)\n (p1, p2) = nextPrimeNumber(N)\n return min(abs(p1 - N), abs(p2 - N))", "def nthterm(N):\n if N == 0:\n return 2\n if N == 1:\n return 1\n import math\n a = 0\n f = N\n p = 0\n while p == 0:\n t = 0\n for j in range(2, int(math.sqrt(f)) + 1):\n if f % j == 0:\n t = 1\n break\n if t == 0:\n p = 1\n a = f\n else:\n f -= 1\n p = 0\n f = N + 1\n b = 0\n while p == 0:\n t = 0\n for j in range(2, int(math.sqrt(f)) + 1):\n if f % j == 0:\n t = 1\n break\n if t == 0:\n p = 1\n b = f\n else:\n f += 1\n return min(b - N, N - a)", "def isPrime(n):\n if n == 1:\n return False\n i = 2\n while i * i <= n:\n if n % i == 0:\n return False\n i += 1\n return True\n\ndef nthterm(N):\n if N == 1:\n return 1\n k = 0\n while k < N:\n if isPrime(N - k):\n break\n elif isPrime(N + k):\n break\n else:\n k += 1\n return k", "from bisect import *\nprimes = [2]\nprime = [1] * 100001\nfor i in range(4, 100001, 2):\n prime[i] = 0\nfor i in range(3, 100001, 2):\n if prime[i]:\n for j in range(i * i, 100001, i):\n prime[j] = 0\n primes.append(i)\n\ndef nthterm(n):\n i = bisect_right(primes, n)\n if primes[i] == n:\n return 0\n elif i == 0:\n return primes[i] - n\n elif primes[i] - n > n - primes[i - 1]:\n return n - primes[i - 1]\n else:\n return primes[i] - n", "def nthterm(N):\n if self.is_prime(N):\n return int(0)\n else:\n k = N - 1\n while k > 1:\n if self.is_prime(k):\n break\n k = k - 1\n j = N + 1\n while True:\n if self.is_prime(j):\n break\n j = j + 1\n k_diff = N - k\n j_diff = j - N\n return min(k_diff, j_diff)\n\ndef is_prime(num):\n if num > 1:\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return False", "def isPrime(N):\n if N < 2:\n return False\n i = 2\n while i * i <= N:\n if N % i == 0:\n return False\n i += 1\n return True\n\ndef nthterm(N):\n x = N\n y = N\n while x > 1:\n if isPrime(x):\n break\n x -= 1\n while True:\n if isPrime(y):\n break\n y += 1\n if not isPrime(x):\n return y - N\n return min(abs(N - x), abs(N - y))", "import math\n\ndef nthterm(N):\n if N == 1:\n return 1\n i = N\n j = N\n while not self.is_prime(i) and (not self.is_prime(j)):\n i -= 1\n j += 1\n if self.is_prime(i):\n return N - i\n return j - N\n\ndef is_prime(n):\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True", "import bisect\n\ndef nthterm(n):\n if n == 1:\n return 1\n\n def fun(m):\n for i in range(2, m):\n if i * i > m:\n break\n if m % i == 0:\n return False\n return True\n for i in range(n):\n if fun(n - i) or fun(n + i):\n return i\n return n", "import math\n\ndef nthterm(N):\n gap = 1\n if self.isPrime(N):\n return 0\n while True:\n if self.isPrime(N + gap) or self.isPrime(N - gap):\n break\n gap += 1\n return gap\n\ndef isPrime(n):\n if n < 2:\n return False\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True", "import math\n\ndef isprime(N):\n if N == 1:\n return False\n if N == 2:\n return True\n if N % 2 == 0:\n return False\n num = math.floor(math.sqrt(N))\n for i in range(3, num + 1, 2):\n if N % i == 0:\n return False\n return True\n\ndef nthterm(N):\n ans = True\n num = None\n i = 0\n while ans and N - i > 1:\n if self.isprime(N - i):\n ans = False\n num = N - i\n elif self.isprime(N + i):\n ans = False\n num = N + i\n i += 1\n if ans:\n while ans:\n if self.isprime(N + i):\n ans = False\n num = N + i\n i += 1\n return abs(num - N)", "def nthterm(N):\n\n def is_prime(n):\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n if N < 2:\n return N\n if is_prime(N):\n return 0\n i = 1\n while True:\n if is_prime(N + i) or is_prime(N - i):\n return i\n i += 1", "def nthterm(N):\n\n def isprime(n):\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n if isprime(N):\n return 0\n p = 0\n for i in range(N):\n if isprime(N - i):\n p = N - i\n break\n if isprime(N + i):\n p = N + i\n break\n return abs(N - p)", "def isPrime(n):\n if n == 2 or n == 3:\n return True\n elif n == 1:\n return False\n else:\n i = 2\n while i * i <= n:\n if n % i == 0:\n return False\n i = i + 1\n return True\n\ndef nthterm(N):\n if self.isPrime(N):\n return 0\n else:\n i = N - 1\n j = N + 1\n while 1:\n if i > 0 and self.isPrime(i):\n return N - i\n elif self.isPrime(j):\n return j - N\n else:\n i = i - 1\n j = j + 1", "import math\n\ndef isPrime(n):\n if n == 2:\n return True\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\ndef nthterm(n):\n if n == 1:\n return 1\n ans = 1000000000.0\n if self.isPrime(n):\n return 0\n flag = False\n l = n\n r = n\n count = 0\n while True:\n if self.isPrime(l) or self.isPrime(r):\n return count\n count += 1\n l -= 1\n r += 1\n if l == 0:\n flag = True\n break\n if flag:\n while True:\n if self.isPrime(r):\n return count\n r += 1\n count += 1\n return ans", "import math\n\ndef nthterm(N):\n if N == 1:\n return 1\n j = N\n sqr = int(math.sqrt(N))\n while j:\n count = 0\n for i in range(2, int(math.sqrt(j)) + 1):\n if j % i == 0:\n count = count + 1\n if count == 0:\n break\n j = j + 1\n k = N\n while k:\n count1 = 0\n for i in range(2, int(math.sqrt(k)) + 1):\n if k % i == 0:\n count1 = count1 + 1\n if count1 == 0:\n break\n k = k - 1\n n = N - j\n n1 = N - k\n if n < 0:\n n = -n\n if n1 < 0:\n n1 = -n\n if n > n1:\n return n1\n else:\n return n", "def nthterm(N):\n if N == 2 or N == 3 or N == 5 or (N == 7):\n return 0\n if N == 1:\n return 1\n if N == 0:\n return 2\n prev = N\n nxt = N + 1\n (fn, fp) = ('y', 'y')\n prprime = 0\n nprime = 0\n while True:\n if fp == 'y':\n for i in range(2, int(prev ** 0.5) + 1):\n if prev % i == 0:\n fp = 'n'\n break\n if fp == 'n':\n prev -= 1\n fp = 'y'\n else:\n prprime = prev\n fp = 'g'\n if fn == 'y':\n for j in range(2, int(nxt ** 0.5) + 1):\n if nxt % j == 0:\n fn = 'n'\n break\n if fn == 'n':\n nxt += 1\n fn = 'y'\n else:\n nprime = nxt\n fn = 'g'\n if fn == 'g' and fp == 'g':\n break\n return min(N - prprime, nprime - N)", "def nthterm(N):\n\n def isPrime(n):\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n if N == 1:\n return 1\n c = 0\n (l, r) = (N, N)\n while True:\n if isPrime(l) or isPrime(r):\n return c\n c += 1\n l -= 1\n r += 1\n if l == 0:\n break\n while True:\n if isPrime(r):\n return c\n r += 1\n c += 1", "import math\n\ndef prime(n):\n if n <= 1:\n return False\n else:\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\ndef nthterm(N):\n i = 0\n while True:\n res = self.prime(N + i)\n if res:\n return i\n res2 = self.prime(N - i)\n if res2:\n return i\n i += 1", "def is_Prime(N):\n if N > 1:\n for i in range(2, int(pow(N, 0.5)) + 1):\n if N % i == 0:\n return False\n return True\n\ndef nthterm(N):\n if self.is_Prime(N):\n return int(0)\n else:\n k = N - 1\n while k > 1:\n if self.is_Prime(k):\n break\n k = k - 1\n j = N + 1\n while True:\n if self.is_Prime(j):\n break\n j = j + 1\n k_diff = N - k\n j_diff = N - j\n return min(abs(k_diff), abs(j_diff))", "def nthterm(N):\n\n def isPrime(n):\n if n < 2:\n return False\n if n == 2:\n return True\n i = 2\n while i * i <= n:\n if n % i == 0:\n return False\n i += 1\n return True\n i = N\n while not isPrime(i):\n i += 1\n l = N\n if N > 2:\n while not isPrime(l):\n l -= 1\n return min(N - l, i - N)\n return i - N", "def nthterm(N):\n\n def not_prime(n):\n if n < 2:\n return True\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return True\n return False\n i = 1\n if not not_prime(N):\n return 0\n while not_prime(i + N) and not_prime(N - i):\n i += 1\n return i", "import math\n\ndef nthterm(N):\n\n def isPrime(num):\n if num <= 1:\n return False\n for i in range(2, int(math.sqrt(num)) + 1):\n if num % i == 0:\n return False\n return True\n diff = 0\n while True:\n if isPrime(N + diff) or isPrime(N - diff):\n return diff\n diff += 1\n return -1", "import math\n\ndef nthterm(N):\n if N == 1:\n return 1\n\n def isPrime(n):\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n m = N\n while not isPrime(m):\n m -= 1\n l = N\n while not isPrime(l):\n l += 1\n return min(N - m, l - N)", "def nthterm(N):\n\n def isprime(k):\n f = 0\n while True:\n for i in range(2, int(k ** 0.5) + 1):\n if k % i == 0:\n k += 1\n break\n else:\n return k\n\n def bprime(l):\n fc = 0\n while True:\n for i in range(2, int(l ** 0.5) + 1):\n if l % i == 0:\n l -= 1\n break\n else:\n return l\n if N == 1:\n return 1\n elif N == 0:\n return 2\n for i in range(2, int(N ** 0.5) + 1):\n if N % i == 0:\n s = isprime(N)\n j = bprime(N)\n e = abs(N - s)\n d = abs(N - j)\n if e > d:\n return d\n else:\n return e\n else:\n return 0", "def nthterm(N):\n from math import sqrt\n\n def isPrime(n):\n if n <= 1:\n return False\n for i in range(2, int(sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n x = N\n y = N\n while x > 1:\n if isPrime(x):\n break\n x -= 1\n while True:\n if isPrime(y):\n break\n y += 1\n if not isPrime(x):\n return y - N\n return min(abs(N - x), abs(N - y))", "def prime_num(num):\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return (False, num)\n return (True, num)\n\ndef nthterm(N):\n if N == 1:\n return 1\n if N == 2:\n return 0\n m = N\n lf = False\n rt = False\n (s, n) = self.prime_num(N)\n if s == True:\n return 0\n N1 = N\n while rt != True:\n if N1 == 1:\n break\n (rt, num1) = self.prime_num(N1)\n if rt == True:\n break\n N1 = N1 + 1\n N2 = N\n while lf != True:\n if N2 == 1:\n break\n (lf, num2) = self.prime_num(N2)\n if lf == True:\n break\n N2 = N2 - 1\n d1 = abs(num1 - m)\n d2 = abs(num2 - m)\n return d1 if d1 < d2 else d2", "from math import sqrt\n\ndef nthterm(N):\n if N == 0 or N == 1:\n return 2 - N\n num = 0\n num2 = 0\n while True:\n prime_flag = True\n new_n = N + num\n for i in range(2, int(sqrt(new_n) + 1)):\n if new_n % i == 0:\n prime_flag = False\n break\n if prime_flag:\n return abs(num)\n num2 += 1\n num += num2 * pow(-1, num2 + 1)", "import math\n\ndef check(n):\n a = 2\n while a <= math.sqrt(n):\n if n % a == 0:\n return False\n a = a + 1\n return True\n\ndef nthterm(N):\n if N == 1:\n return 1\n k = N\n front = N + 1\n back = N - 1\n if self.check(N):\n return 0\n while True:\n ans1 = self.check(front)\n if ans1 == True:\n return abs(k - front)\n ans2 = self.check(back)\n if ans2 == True:\n return abs(k - back)\n front = front + 1\n back = back - 1", "from math import sqrt\n\ndef isprime(N):\n return all((N % i != 0 for i in range(2, int(sqrt(N) + 1))))\n\ndef nthterm(N):\n if N > 1:\n prime = False\n res = N\n i = 1\n if self.isprime(N):\n return 0\n else:\n while not prime:\n if self.isprime(N - i):\n N = N - i\n prime = True\n elif self.isprime(N + i):\n N = N + i\n prime = True\n i += 1\n res = N - res\n return abs(res)\n else:\n return N", "from math import sqrt\n\ndef prime(n):\n if n <= 1:\n return False\n for i in range(2, int(sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\ndef nthterm(n):\n mini = 0\n maxi = 0\n if self.prime(n):\n return n - n\n for i in range(n, 1, -1):\n if self.prime(i):\n mini = i\n break\n for i in range(n + 1, 100000):\n if self.prime(i):\n maxi = i\n break\n if n - mini >= maxi - n:\n return maxi - n\n elif maxi - n > n - mini:\n return n - mini", "import math\n\ndef nthterm(N):\n\n def isPrime(n):\n if n <= 1:\n return False\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n (x, y) = (N, N)\n count = 0\n while 1:\n if isPrime(x) or isPrime(y):\n return count\n x -= 1\n y += 1\n count += 1\n return count", "from math import sqrt\n\ndef nthterm(N):\n diff = []\n loop = True\n i = N + 1\n if N == 1:\n return 1\n while i >= 2:\n i = i - 1\n flag = 0\n for j in range(2, int(sqrt(i)) + 1):\n if i % j == 0:\n flag = 1\n if flag == 0:\n diff = abs(N - i)\n break\n i = N\n while True:\n i = i + 1\n flag = 0\n for j in range(2, int(sqrt(i)) + 1):\n if i % j == 0:\n flag = 1\n if flag == 0:\n diff2 = abs(N - i)\n break\n out = min(diff, diff2)\n return out", "def check(x):\n import math\n p = 0\n if x > 1:\n for i in range(2, int(math.sqrt(x)) + 1):\n if x % i == 0:\n p = 1\n break\n if p == 0:\n return True\n else:\n return False\n else:\n return False\n\ndef nthterm(N):\n m = 10000\n if N == 1:\n return 1\n for i in range(N, N * 2):\n if self.check(i):\n m = min(m, abs(i - N))\n break\n for i in range(N, N // 2, -1):\n if self.check(i):\n m = min(m, abs(i - N))\n break\n return m", "def nthterm(N):\n\n def primeNum(n):\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n if primeNum(N):\n return 0\n L = N\n R = N\n while not primeNum(L) and (not primeNum(R)):\n L -= 1\n R += 1\n return min(abs(L - N), abs(R - N))", "import math\n\ndef isPrime(N):\n k = int(math.sqrt(N)) + 1\n for i in range(2, k, 1):\n if N % i == 0:\n return False\n return True\n\ndef nthterm(N):\n if N == 0:\n return 2\n elif N == 1:\n return 1\n elif ob.isPrime(N):\n return 0\n aboveN = -1\n belowN = -1\n n1 = N + 1\n while True:\n if ob.isPrime(n1):\n aboveN = n1\n break\n else:\n n1 += 1\n n1 = N - 1\n while True:\n if ob.isPrime(n1):\n belowN = n1\n break\n else:\n n1 -= 1\n diff1 = aboveN - N\n diff2 = N - belowN\n return min(diff1, diff2)", "import collections\n\ndef nthterm(N):\n\n def is_prime(n: int) -> bool:\n if n <= 3:\n return n > 1\n i = 2\n while i * i <= n:\n if n % i == 0:\n return False\n i += 1\n return True\n if N == 0:\n return 2\n if N == 1:\n return 1\n if is_prime(N):\n return 0\n n = N + 1\n p = N - 1\n while not is_prime(n):\n n += 1\n while not is_prime(p):\n p -= 1\n return min(N - p, n - N)", "import collections\n\ndef nthterm(N):\n import re\n\n def isPrime(n):\n return re.compile('^1?$|^(11+)\\\\1+$').match('1' * n) is None\n\n def is_prime(n: int) -> bool:\n if n <= 3:\n return n > 1\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i ** 2 <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True\n if N == 0:\n return 2\n if N == 1:\n return 1\n if is_prime(N):\n return 0\n n = N + 1\n p = N - 1\n while not is_prime(n):\n n += 1\n while not is_prime(p):\n p -= 1\n return min(N - p, n - N)", "def nthterm(N):\n\n def isPrime(n):\n if n <= 1:\n return False\n else:\n i = 2\n sn = int(n ** 0.5)\n while i <= sn:\n if n % i == 0:\n return False\n i += 1\n else:\n return True\n for d in range(0, N + 1):\n (i, j) = (N - d, N + d)\n if isPrime(i) or isPrime(j):\n return d", "import math\n\ndef nthterm(n):\n if n < 2:\n return 1\n nextPrime = 0\n while nextPrime < n:\n if self.isPrime(n - nextPrime) or self.isPrime(n + nextPrime):\n break\n nextPrime += 1\n return nextPrime\n\ndef isPrime(num):\n n = 2\n while n <= math.sqrt(num):\n if num % n == 0:\n return False\n n += 1\n return True", "import math\n\ndef is_prime(x):\n for i in range(2, int(math.sqrt(x)) + 1):\n if x % i == 0:\n return False\n return True\n\ndef nthterm(N):\n if N == 0:\n return 2\n if N == 1:\n return 1\n if N == 2:\n return 0\n if N == 3:\n return 0\n min_diff = float('inf')\n for i in range(N, 2 * N):\n if self.is_prime(i):\n min_diff = abs(i - N)\n break\n for i in range(N + 1)[::-1]:\n if self.is_prime(i):\n min_diff = min(min_diff, abs(i - N))\n break\n return min_diff", "import math\n\ndef isprime(n):\n ran = int(math.sqrt(n))\n for i in range(2, ran + 1):\n if n % i == 0:\n return False\n return True\n\ndef nthterm(N):\n if N == 1:\n return 1\n if N == 0:\n return 2\n if isprime(N):\n return 0\n num = N\n for i in range(1, N):\n if N - i >= 1 and isprime(N - i):\n return i\n if isprime(N + i):\n return i", "import math\n\ndef primecheck(x):\n if x == 1:\n return 0\n sta = 1\n for i in range(2, int(math.sqrt(x)) + 1):\n if x % i == 0:\n sta = 0\n break\n return sta\n\ndef nthterm(N):\n i = 0\n while True:\n if self.primecheck(N - i) == 1 or self.primecheck(N + i) == 1:\n return i\n i = i + 1"], "starter_code": "def nthterm(N):\n", "input_output": {"inputs": ["N = 10", "N = 7"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Pattern Searching"], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/help-ishaan5837/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N* √ N)", "entry_point": "nthterm", "task_id": "TACO_lite/385", "example": [[[10], [7]], ["1", "0"]]} +{"requirement": "## Task\n\nCreate a RomanNumerals class that can convert a roman numeral to and from an integer value. It should follow the API demonstrated in the examples below. Multiple roman numeral values will be tested for each helper method. \n\nModern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.\n\n## Examples\n\n```python\nRomanNumerals.to_roman(1000) # should return 'M'\nRomanNumerals.from_roman('M') # should return 1000\n```\n\n## Help\n\n| Symbol | Value |\n|----------------|\n| I | 1 |\n| V | 5 |\n| X | 10 |\n| L | 50 |\n| C | 100 |\n| D | 500 |\n| M | 1000 |", "solutions": ["import string\nfrom collections import OrderedDict\n\ndef to_roman(num):\n conversions = OrderedDict([('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)])\n out = ''\n for (key, value) in conversions.items():\n while num >= value:\n out += key\n num -= value\n return out\n\ndef from_roman(roman):\n conversions = OrderedDict([('CM', 900), ('CD', 400), ('XC', 90), ('XL', 40), ('IX', 9), ('IV', 4), ('M', 1000), ('D', 500), ('C', 100), ('L', 50), ('X', 10), ('V', 5), ('I', 1)])\n out = 0\n for (key, value) in conversions.items():\n out += value * roman.count(key)\n roman = string.replace(roman, key, '')\n return out", "from collections import OrderedDict\nimport re\nROMAN_NUMERALS = OrderedDict([('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)])\nDECIMAL_TO_ROMAN = [(v, k) for (k, v) in list(ROMAN_NUMERALS.items())]\nROMAN_RE = '|'.join(ROMAN_NUMERALS)\n\ndef from_roman(roman):\n return sum((ROMAN_NUMERALS[d] for d in re.findall(ROMAN_RE, roman)))\n\ndef to_roman(decimal):\n result = []\n for (number, roman) in DECIMAL_TO_ROMAN:\n while decimal >= number:\n decimal -= number\n result.append(roman)\n return ''.join(result)", "from itertools import groupby\n\ndef to_roman(cls, val):\n rom = []\n for (l, v) in cls.letters:\n m = val // v\n rom += m * [l]\n val -= m * v\n return ''.join(rom)\n\ndef from_roman(cls, rom):\n cumu = 0\n for (l, v) in cls.letters:\n while rom[:len(l)] == l:\n rom = rom[len(l):]\n cumu += v\n if not rom:\n break\n return cumu", "def to_roman(cls, num, rom=''):\n EDGE = {0: lambda x, elem, dict, number: dict.get(elem, '') * number, 1: lambda e, i, D, l: e + D[i * (l + 1)] if l in [4, 9] else D[i * l] if l is 5 else D[i * 5] + e * (l % 5)}\n for element in list(cls.READ.keys())[0::2][::-1]:\n left = num // element\n rom += EDGE.get(left > 3, '')(cls.READ[element], element, cls.READ, left)\n num %= element\n return rom\n\ndef from_roman(cls, roma):\n cls.INTG.update({'N': 0})\n roma += 'N'\n return sum([-cls.INTG[x] if cls.INTG[x] < cls.INTG[z] else cls.INTG[x] for (x, z) in zip(roma[:-1], roma[1:])])", "def from_roman(s):\n X = [dict(zip('MDCLXVI', (1000.0, 500, 100, 50, 10, 5, 1)))[x] for x in s]\n return int(sum(((x, -x)[x < y] for (x, y) in zip(X, X[1:]))) + X[-1])\n\ndef to_roman(i, o=' I II III IV V VI VII VIII IX'.split(' ')):\n r = lambda n: o[n] if n < 10 else ''.join((dict(zip('IVXLC', 'XLCDM'))[c] for c in r(n // 10))) + o[n % 10]\n return r(i)", "def to_roman(num):\n ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)\n nums = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I')\n result = ''\n for i in range(len(ints)):\n count = int(num / ints[i])\n result += str(nums[i] * count)\n num -= ints[i] * count\n return result\n\ndef from_roman(roman):\n nums = ['M', 'D', 'C', 'L', 'X', 'V', 'I']\n ints = [1000, 500, 100, 50, 10, 5, 1]\n places = []\n for i in range(len(roman)):\n c = roman[i]\n value = ints[nums.index(c)]\n try:\n next_val = ints[nums.index(roman[i + 1])]\n if next_val > value:\n value *= -1\n except:\n pass\n places.append(value)\n return sum(places)", "def to_roman(n, result='', i=0):\n SPQR = ((1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'))\n if i == len(SPQR):\n return result\n while n - SPQR[i][0] >= 0:\n result += SPQR[i][1]\n n -= SPQR[i][0]\n i += 1\n return self.to_roman(n, result, i)\n\ndef from_roman(roman, result=0, i=0):\n SPQR = ((900, 'CM'), (1000, 'M'), (400, 'CD'), (500, 'D'), (90, 'XC'), (100, 'C'), (50, 'L'), (40, 'XL'), (9, 'IX'), (10, 'X'), (4, 'IV'), (5, 'V'), (1, 'I'))\n if roman == '':\n return result\n while SPQR[i][1] in roman:\n result += SPQR[i][0]\n roman = roman[len(SPQR[i][1]):]\n i += 1\n return self.from_roman(roman, result, i)", "from functools import reduce\n\ndef to_roman(cls, n):\n _map = cls._map\n red = lambda s, e: (s[0] + _map[e] * (s[1] // e), s[1] - e * (s[1] // e))\n return reduce(red, reversed(sorted(_map)), ['', n])[0]\n\ndef from_roman(cls, s):\n _map = {v: k for (k, v) in cls._map.items()}\n red = lambda s, e: s[:-1] + [s[-1] + e] if s and s[-1] + e in _map else s + [e]\n return sum((_map[x] for x in reduce(red, s, [])))", "from itertools import groupby, zip_longest\nFROM_ROMAN = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}\nTO_ROMAN = ((1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'))\n\ndef to_roman(n):\n result = []\n for (num, char) in TO_ROMAN:\n (q, n) = divmod(n, num)\n result.append(q * char)\n return ''.join(result)\n\ndef from_roman(roman):\n pairs = [sum(g) for (_, g) in groupby((FROM_ROMAN[a] for a in roman))]\n return sum((a + b if a > b else b - a for (a, b) in zip_longest(pairs[::2], pairs[1::2], fillvalue=0)))", "def to_roman(n):\n res = []\n for i in RomanNumerals.dic:\n res.extend(n / i[0] * i[1])\n n -= n / i[0] * i[0]\n return ''.join(res)\n\ndef from_roman(n):\n res = 0\n for i in RomanNumerals.dic:\n while n.startswith(i[1]):\n res += i[0]\n n = n[len(i[1]):]\n return res"], "starter_code": "def to_roman(n):\n", "input_output": {"fn_name": "to_roman", "inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/51b66044bce5799a7f000003", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "to_roman", "task_id": "TACO_lite/396", "example": [[[1000], ["M"]], ["M", "1000"]]} +{"requirement": "Write a program that receives a number n as input and prints it in the following format as shown below.\nLike for n = 2 the pattern will be:\n1*2*5*6\n--3*4\nExample 1:\nInput: n = 3\nOutput: \n1*2*3*10*11*12\n--4*5*8*9\n----6*7\nExplaination: If the pattern shown in question \nis followed, this will be the output.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function pattern() which takes n as input parameter and returns a list of string where each string denotes a new line of the pattern.\nExpected Time Complexity: O(n^{2})\nExpected Auxiliary Space: O(n^{2})\nConstraints:\n1 ≤ n ≤ 70", "solutions": ["def pattern(n):\n m = n\n c = 1\n lst = []\n for i in range(n):\n str1 = ''\n str1 += '--' * i\n for j in range(n - i):\n str1 += str(c) + '*'\n c += 1\n lst.append(str1)\n for i in range(n):\n for j in range(i + 1):\n lst[-i - 1] += str(c) + '*'\n c += 1\n lst[-i - 1] = lst[-i - 1][:-1]\n return lst", "def pattern(n):\n l = n * (n + 1) // 2\n r = l + 1\n sol = []\n for i in range(n):\n for j in range(i + 1):\n if j == 0:\n temp = str(l) + '*' + str(r)\n l -= 1\n r += 1\n else:\n temp = str(l) + '*' + temp + '*' + str(r)\n l -= 1\n r += 1\n sol.insert(0, temp)\n for i in range(n):\n sol[i] = '--' * i + sol[i]\n return sol", "def pattern(n):\n res = [''] * n\n rres = [''] * n\n c = 1\n for i in range(n):\n s = ''\n for j in range(n - i):\n s += str(c) + '*'\n c += 1\n res[i] = s\n for i in range(n - 1, -1, -1):\n s = ''\n for j in range(n - i):\n s += str(c) + '*'\n c += 1\n res[i] += s[:-1]\n for i in range(n):\n rres[i] = '-' * (i * 2) + res[i]\n return rres", "def pattern(n):\n sept = '-'\n f = 1\n l = n ** 2 + n\n ret = []\n for i in range(n):\n s = ''\n s = s + 2 * i * sept\n for j in range(n - i, 0, -1):\n s = s + str(f) + '*'\n f += 1\n for j in range(n - i, 0, -1):\n if j == 1:\n s = s + str(l - j + 1)\n else:\n s = s + str(l - j + 1) + '*'\n l = l - n + i\n ret.append(s)\n return ret", "def pattern(n):\n ar = []\n k = 1\n for i in range(n):\n st = ''\n for j in range(i):\n st += '--'\n for j in range(n - i):\n st += str(k) + '*'\n k += 1\n m = (n - i - 1) * (n - i)\n for l in range(n - i - 1):\n st += str(k + m) + '*'\n m += 1\n st += str(k + m)\n ar.append(st)\n return ar", "def pattern(n):\n l = []\n k = n * (n + 1)\n c = 1\n x = 0\n for i in range(n, 0, -1):\n s = ''\n for sp in range(1, x + 1):\n s = s + '-'\n for j in range(1, i + 1):\n s = s + str(c) + '*'\n c += 1\n for j in range(k - i + 1, k):\n s = s + str(j) + '*'\n s = s + str(k)\n l.append(s)\n k -= i\n x += 2\n return l", "def pattern(n):\n data = [[] for x in range(n)]\n curr = 1\n for x in [*range(1, n + 1), *range(n, 0, -1)]:\n for y in range(n - x + 1):\n data[x - 1].append(str(curr))\n curr += 1\n data = list(map(lambda dd: '*'.join(dd), data))\n for x in range(n):\n data[x] = '-' * (2 * x) + data[x]\n return data", "def pattern(n):\n (row, column, dashes) = (0, 0, 0)\n (i, j, dash_counter) = (0, 0, 0)\n value = 1\n (k, l, decrementor) = (0, 0, 0)\n column_decrementor = 0\n support = n - 1\n temp = n * n + 1\n temp1 = n * 2 - 1\n z = temp\n tracker = 0\n res = []\n for i in range(1, n + 1):\n s = ''\n for it in range(dash_counter):\n s += '-'\n for j in range(1, 2 * n - dash_counter + 1):\n if j % 2 == 0:\n s += '*'\n else:\n s += str(value)\n value += 1\n for k in range(1, temp1 - decrementor + 1):\n if k % 2 == 0:\n s += '*'\n else:\n if k == 1:\n tracker = temp\n s += str(temp)\n temp += 1\n decrementor += 2\n temp = tracker - support\n support -= 1\n dash_counter += 2\n res.append(s)\n return res", "def pattern(n):\n res = [''] * n\n counter = 1\n for i in range(n):\n s = ''\n for j in range(n - i):\n s += str(counter) + '*'\n counter += 1\n res[i] = s\n for i in range(n - 1, -1, -1):\n s = ''\n for j in range(n - i):\n s += str(counter) + '*'\n counter += 1\n res[i] += s[:-1]\n for i in range(n):\n res[i] = '-' * (i << 1) + res[i]\n return res", "def pattern(n):\n p = n * (n + 1) // 2 * 2 - (n - 1)\n k = 1\n a = []\n l = 1\n for i in range(n, 0, -1):\n s = ''\n s = s + '-' * ((l - 1) * 2)\n for j in range(i):\n s = s + str(k)\n s = s + '*'\n k = k + 1\n for g in range(i - 1):\n s = s + str(p)\n s = s + '*'\n p = p + 1\n s = s + str(p)\n p = p - (n - l) * 2\n l = l + 1\n a.append(s)\n return a", "def pattern(n):\n ans = [''] * n\n counter = 1\n for i in range(0, n):\n s = ''\n for j in range(0, n - i):\n s += str(counter) + '*'\n counter += 1\n ans[i] = s\n for i in range(n - 1, -1, -1):\n s = ''\n for j in range(0, n - i):\n s += str(counter) + '*'\n counter += 1\n ans[i] += s[:-1]\n for i in range(0, n):\n ans[i] = '-' * (i << 1) + ans[i]\n return ans", "def pattern(n):\n p = []\n k = 1\n f = n * (n + 1)\n for i in range(1, n + 1):\n s = ''\n for j in range(1, 2 * i - 1):\n s += '-'\n for j in range(1, n - i + 2):\n s += str(k)\n s += '*'\n k += 1\n g = 0\n for j in range(f - (n - i), f + 1):\n g += 1\n s += str(j)\n if g != n - i + 1:\n s += '*'\n f -= 1\n p.append(s)\n return p", "def pattern(n):\n l = []\n s = 1\n for i in range(n):\n st = ''\n for j in range(2 * i):\n st += '-'\n for j in range(i, n):\n st += str(s) + '*'\n s += 1\n l.append(st)\n for i in range(n - 1, -1, -1):\n st = ''\n for j in range(i, n):\n st += str(s)\n s += 1\n if j != n - 1:\n st += '*'\n l[i] += st\n return l", "def pattern(n):\n a = n\n l = []\n x = 1\n x1 = n * n + 1\n s = ''\n n1 = n\n n2 = n\n for i in range(n):\n s = ''\n if i > 0:\n s += '-' * (2 * i)\n for j in range(n1):\n s += str(x)\n x += 1\n s += '*'\n n1 -= 1\n x2 = x1\n for j in range(n2):\n if j == n2 - 1:\n s += str(x1 + j)\n else:\n s += str(x1 + j)\n s += '*'\n n2 -= 1\n x1 -= n2\n l.append(s)\n return l", "def pattern(n):\n s = []\n s1 = []\n a = n * (n + 1)\n m = a // 2\n for i in range(1, a + 1):\n if i <= m:\n s += ['*' + str(i)]\n else:\n s1 += ['*' + str(i)]\n s1 = s1[::-1]\n e = []\n j = 0\n for i in range(1, n + 1):\n b = ''.join(s[-i:] + s1[-i:][::-1])\n e += [b[1:]]\n del s[-i:]\n del s1[-i:]\n e = e[::-1]\n for i in range(len(e)):\n e[i] = '-' * j + e[i]\n j += 2\n return e", "def pattern(n):\n k = n\n f = 0\n t = n\n res = []\n while n > 0:\n ans = []\n ans.append('-' * 2 * (t - n))\n for i in range(1, n + 1):\n if i == 1:\n f += 1\n ans.append(f)\n else:\n f += 1\n ans.extend(['*', f])\n f = f - n\n for i in range(1, n + 1):\n f += 1\n ans.extend(['*', f + k * k])\n k -= 1\n n -= 1\n res.append(''.join(map(str, ans)))\n return res", "def pattern(n):\n total = int(n * (n + 1) / 2 * 2)\n interval = 0\n result = []\n for i in range(n, 0, -1):\n subStr = ''\n subStr += '-' * (n - i) * 2\n for j in range(interval + 1, interval + i + 1):\n subStr += str(j)\n subStr += '*'\n for k in range(total - i - interval + 1, total - interval + 1):\n subStr += str(k)\n if total - interval != k:\n subStr += '*'\n interval += i\n result.append(subStr)\n return result", "def pattern(n):\n x = [''] * n\n a = n * (n + 1)\n y = []\n for i in range(a):\n y.append(i + 1)\n for i in range(1, n + 1):\n x[i - 1] += '-' * (2 * (i - 1))\n for j in y[:n - i + 1]:\n x[i - 1] += str(j) + '*'\n y.remove(j)\n for j in y[-(n - i + 1):]:\n x[i - 1] += str(j) + '*'\n y.remove(j)\n x[i - 1] = x[i - 1][:-1]\n return x", "def pattern(n):\n x = []\n number = 1\n for i in range(n, 0, -1):\n c = ''\n c += '-' * ((n - i) * 2)\n for j in range(i):\n c += str(number)\n c += '*'\n number += 1\n x.append(c)\n x = x[::-1]\n y = []\n for i in range(1, n + 1):\n a = x[i - 1]\n for j in range(i):\n a += str(number)\n number += 1\n a += '*'\n y.append(a[:-1])\n return y[::-1]", "def pattern(n):\n ans = []\n noof = n * (n + 1)\n cop = n\n (a, b) = (1, noof)\n hyp = 0\n while cop:\n strr = ''\n for i in range(hyp):\n strr += '-'\n hyp += 2\n for i in range(cop):\n strr += str(a) + '*'\n a += 1\n last = b - cop\n for i in range(cop):\n last += 1\n if last == b:\n strr += str(last)\n else:\n strr += str(last) + '*'\n b = b - cop\n cop -= 1\n ans.append(strr)\n return ans", "def pattern(n):\n for i in range(n):\n ans = []\n d = n * (n + 1)\n x = 0\n for i in range(n, 0, -1):\n s = '' + '-' * (n - i) * 2\n j = x + 1\n l = 1\n while l <= i * 2:\n s += str(j) + '*'\n if l == i:\n x = j\n j = d - x\n j += 1\n l += 1\n ans.append(s[:-1])\n return ans", "def pattern(n):\n m = (n + 1) * n\n l = 1\n ans = []\n for i in range(n):\n temp = []\n temp2 = []\n for j in range(n - i):\n temp.append(str(l))\n l += 1\n temp2.append(str(m))\n m -= 1\n temp2 = temp2[::-1]\n temp.extend(temp2)\n temp = '*'.join(temp)\n for p in range(2 * i):\n temp = '-' + temp\n ans.append(temp)\n return ans", "def pattern(n):\n ansf = []\n ansl = []\n count = 0\n for i in range(n):\n s = []\n for j in range(n - i):\n count += 1\n s.append(str(count))\n ansf.append(2 * i * '-' + '*'.join(s))\n for i in range(n):\n s = []\n for j in range(i + 1):\n count += 1\n s.append(str(count))\n ansl.append('*'.join(s))\n ansl.reverse()\n ans = []\n for i in range(n):\n ans.append(ansf[i] + '*' + ansl[i])\n return ans", "def pattern(n):\n t = int(n * (n + 1) / 2 * 2)\n h = 0\n r = []\n for i in range(n, 0, -1):\n s = ''\n s += '-' * (n - i) * 2\n for j in range(h + 1, h + i + 1):\n s += str(j)\n s += '*'\n for k in range(t - i - h + 1, t - h + 1):\n s += str(k)\n if t - h != k:\n s += '*'\n h += i\n r.append(s)\n return r", "def pattern(n):\n s = []\n s.extend(range(1, n * (n + 1) + 1))\n l = list(map(str, s))\n ans = []\n for i in range(n, 0, -1):\n ans.append('-' * ((n - i) * 2) + '*'.join(l[:i]) + '*' + '*'.join(l[-1 * i:]))\n l = l[i:-i]\n return ans", "def pattern(n):\n lines = []\n x = n * (n + 1)\n start = 1\n end = x\n prev = x\n for i in range(n):\n line = '--' * i\n arr = [str(j) for j in range(start, start + n - i)] + [str(j) for j in range(end - n + i + 1, prev + 1)]\n start += n - i\n end = end - n + i\n prev = end\n line += '*'.join(arr)\n lines += [line]\n return lines", "def pattern(n):\n b = n * (n + 1)\n l = []\n for i in range(b):\n l.append(str(i + 1))\n i = 0\n j = b - 1\n e = []\n c = 0\n for m in range(n, 0, -1):\n t = ''\n t += c * '-'\n p = []\n g = []\n for q in range(m):\n p.append(l[i])\n g.append(l[j])\n i += 1\n j -= 1\n p.extend(g[::-1])\n t += '*'.join(p)\n e.append(t)\n c += 2\n return e", "def pattern(n):\n store = []\n no = 1\n for i in range(n):\n curr = []\n for j in range(n - i):\n curr.append(no)\n no += 1\n store.extend(curr)\n for i in range(n):\n curr = []\n for j in range(n - i):\n curr.append(no)\n no += 1\n store.extend(curr)\n f = store[0:len(store) // 2]\n s = store[len(store) // 2:]\n s = s[::-1]\n ans = []\n for i in range(len(f)):\n push1 = []\n push2 = []\n for j in range(n - i):\n push1.append(str(f.pop(0)))\n push1.append('*')\n push1 = push1[:-1]\n for j in range(n - i):\n push2.append(str(s.pop(0)))\n push2.append('*')\n push1.extend(push2[::-1])\n push1.insert(0, '--' * i)\n ans.append(''.join(push1))\n return ans", "def pattern(n):\n res = []\n l = n * (n + 1)\n a = list(range(1, l + 1))\n seed = 0\n for x in range(n, 0, -1):\n arr = a[seed:seed + x]\n if seed == 0:\n arr = arr + a[-x - seed:]\n else:\n arr = arr + a[-x - seed:-seed]\n resStr = '--' * (n - x) + '*'.join([str(m) for m in arr])\n res.append(resStr)\n seed += x\n return res", "def pattern(n):\n u = n * (n + 1)\n nums = list(range(1, u + 1))\n c_j = 0\n c_k = u - n\n dash = 2\n ans = []\n pres_string = ''\n for i in range(n):\n for j in range(n - i):\n pres_string += str(nums[c_j + j])\n pres_string += '*'\n c_j += j + 1\n for k in range(n - i):\n pres_string += str(nums[c_k + k])\n if k != n - i - 1:\n pres_string += '*'\n c_k -= k\n ans.append(pres_string)\n pres_string = '-' * dash\n dash += 2\n return ans", "def pattern(n):\n rtr = [[] for i in range(n)]\n num = 1\n for j in range(n, 0, -1):\n for k in range(n):\n if k < n - j:\n rtr[n - j].append('--')\n else:\n rtr[n - j].append(str(num))\n rtr[n - j].append('*')\n num += 1\n for j in range(1, n + 1):\n for k in range(j):\n rtr[n - j].append(str(num))\n rtr[n - j].append('*')\n num += 1\n rtr = [x[:-1] for x in rtr]\n rtr = [''.join(x) for x in rtr]\n return rtr", "def pattern(n):\n lst3 = []\n lst4 = []\n lst = list(range(n * (n + 1)))\n lst.pop(0)\n lst.append(lst[-1] + 1)\n f = 0\n y = 0\n for i in range(n, 0, -1):\n w = 0\n lst1 = []\n for j in range(2):\n for k in range(f, f + i):\n if w == 0:\n lst1.append(lst[k])\n else:\n lst1.append(lst[-k - 1])\n w = 1\n lst1.sort()\n f += i\n lst2 = []\n for x in lst1:\n lst2.append(str(x) + '*')\n lst2 = ''.join(lst2)\n lst2 = lst2[:-1]\n lst3 = ['-' * y + lst2]\n y += 2\n lst2 = []\n lst4.append(lst3[0])\n return lst4", "def pattern(n):\n a = []\n for i in range(1, n * (n + 1) + 1):\n a.append(i)\n a.append('*')\n a.pop()\n b = []\n z = 0\n y = n * 2 - 1\n for i in range(n):\n b.append('-' * z + ''.join(map(str, a[:n * 2])) + ''.join(map(str, a[len(a) - y:])))\n a.pop()\n a = a[n * 2:len(a) - y]\n n -= 1\n y -= 2\n z += 2\n return b", "def pattern(n):\n l = 1\n r = n * (n + 1)\n lst = []\n for i in range(n, -1, -1):\n str1 = ''\n for space in range(n, i - 1, -1):\n if space < n:\n str1 += '--'\n for j in range(1, i + 1):\n str1 += str(l) + '*'\n l += 1\n for j in range(1, i + 1):\n str1 += str(r - n + 1)\n if j < i:\n str1 += '*'\n r += 1\n r = r - (i - 1) * 2 - 1\n lst.append(str1)\n return lst", "def pattern(n):\n r = []\n ln = 0\n for row in range(n):\n rs = '--' * row\n for s in range(n - row):\n ln += 1\n rs += str(ln) + '*'\n r.append(rs)\n for row in range(n - 1, -1, -1):\n for s in range(n - row):\n ln += 1\n r[row] += str(ln) + '*'\n return [rs[:-1] for rs in r]", "def pattern(n):\n arr = []\n for i in range(n):\n arr.append('--' * i)\n counter = 0\n index = 0\n for j in range(n, 0, -1):\n for b in range(j):\n counter += 1\n arr[index] = arr[index] + str(counter) + '*'\n index += 1\n for k in range(n, 0, -1):\n for c in range(n - k + 1):\n counter += 1\n arr[k - 1] = arr[k - 1] + str(counter) + '*'\n for l in range(n):\n arr[l] = arr[l][:-1]\n return arr", "def pattern(n):\n ans = []\n num = 1\n for i in range(n):\n s = ''\n for j in range(i):\n s += '--'\n for j in range(n - i):\n s += str(num) + '*'\n num += 1\n ans.append(s)\n for i in range(n - 1, -1, -1):\n s = ''\n for j in range(n - i):\n s += str(num) + '*'\n num += 1\n s = s[:-1]\n ans[i] = ans[i] + s\n return ans", "def pattern(n):\n start = 1\n end = n * (n + 1)\n c = 0\n arr = []\n while c < n:\n temp = []\n line = []\n i = 0\n j = 0\n while i < n - c:\n line.append(str(start + i))\n i += 1\n while j < n - c:\n temp.append(str(end - j))\n j += 1\n line += temp[::-1]\n s = '-' * 2 * c\n ans = '*'.join(line)\n s += ans\n arr.append(s)\n start += n - c\n end -= n - c\n c += 1\n return arr", "def pattern(n):\n N = n * (n + 1)\n l = [i for i in range(1, N + 1)]\n result = []\n for i in range(n):\n S = '--' * i\n for j in range(n - i):\n S += str(l[0])\n l.remove(l[0])\n S += '*'\n for k in range(n - i):\n S += str(l[-n + k + i])\n l.remove(l[-n + k + i])\n if n - i - k > 1:\n S += '*'\n result.append(S)\n return result", "def pattern(n):\n (start, end) = (1, n * (n + 1))\n lines = []\n for i in range(n, 0, -1):\n row = list(range(start, start + i)) + list(range(end - i + 1, end + 1))\n lines.append('-' * (2 * (n - i)) + '*'.join((str(v) for v in row)))\n start += i\n end -= i\n return lines", "def pattern(n):\n ans = [[] for i in range(n)]\n val = 1\n for i in range(n):\n for j in range(val, val + n - i):\n ans[i].append(j)\n val = ans[i][-1] + 1\n val = val\n for i in range(n - 1, -1, -1):\n for j in range(val, val + n - i):\n ans[i].append(j)\n val = ans[i][-1] + 1\n out = []\n for i in range(n):\n val = '' + 2 * i * '-'\n for j in range(len(ans[i]) - 1):\n val += str(ans[i][j]) + '*'\n val += str(ans[i][-1])\n out.append(val)\n return out", "def pattern(n):\n res = []\n c = 1\n for i in range(n, 0, -1):\n t = []\n for j in range(i):\n t.append(c)\n c += 1\n res.append(t)\n for i in range(1, n + 1):\n t = res[n - i]\n for j in range(i):\n t.append(c)\n c += 1\n res[n - i] = t\n for i in range(n):\n res[i] = '-' * (i * 2) + '*'.join(map(str, res[i]))\n return res", "def pattern(n):\n count = 1\n list = []\n for i in range(n):\n list.append('')\n for j in range(n):\n if i > j:\n list[i] = str(list[i]) + '--'\n else:\n list[i] = str(list[i]) + str(count) + '*'\n count = count + 1\n for i in range(n):\n for j in range(i + 1):\n if j == 0:\n list[n - 1 - i] = str(list[n - 1 - i]) + str(count)\n else:\n list[n - 1 - i] = str(list[n - 1 - i]) + '*' + str(count)\n count = count + 1\n return list", "def pattern(n):\n res = ['' for i in range(n)]\n num = 1\n for row in range(0, n):\n numTerms = n - row\n for d in range(2 * row):\n res[row] += '-'\n for i in range(numTerms):\n res[row] += str(num) + '*'\n num += 1\n for row in range(n - 1, -1, -1):\n numTerms = n - row\n for i in range(1, numTerms):\n res[row] += str(num) + '*'\n num += 1\n res[row] += str(num)\n num += 1\n return res", "def pattern(n):\n dashCount = 0\n output = []\n i = 1\n for j in range(n):\n string = '-' * dashCount\n temp = []\n for k in range(n - j):\n temp.append(str(i))\n i += 1\n string += '*'.join(temp)\n output.append(string + '*')\n dashCount += 2\n for j in range(n):\n string = output[n - j - 1]\n temp = []\n for k in range(j + 1):\n temp.append(str(i))\n i += 1\n string += '*'.join(temp)\n output[n - j - 1] = string\n return output"], "starter_code": "def pattern(n):\n", "input_output": {"inputs": ["n = 3"], "outputs": ["1*2*3*10*11*12\n--4*5*8*9\n----6*7"]}, "difficulty": "EASY", "raw_tags": ["pattern-printing"], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/print-the-pattern1025/1", "Expected Auxiliary Space": "O(n^{2})", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n^{2})", "entry_point": "pattern", "task_id": "TACO_lite/400", "example": [[], []]} +{"requirement": "Given two lists V1 and V2 of sizes n and m respectively. Return the list of elements common to both the lists and return the list in sorted order. Duplicates may be there in the output list.\nExample:\nInput:\nn = 5\nv1[] = {3, 4, 2, 2, 4}\nm = 4\nv2[] = {3, 2, 2, 7}\nOutput:\n2 2 3\nExplanation:\nThe common elements in sorted order are {2 2 3}\nYour Task:\nThis is a function problem. You need to complete the function common_element that takes both the lists as parameters and returns a list of common elements. \nConstraints:\n1 ≤ n, m ≤ 10^{5}\n1 ≤ V_{i} ≤ 10^{5}", "solutions": ["def common_element(v1, v2):\n res = []\n map = {}\n for i in v1:\n if i in map:\n map[i] += 1\n else:\n map[i] = 1\n v2.sort()\n for i in v2:\n if i in map and map[i] > 0:\n res.append(i)\n map[i] -= 1\n return res", "def common_element(v1, v2):\n v1.sort()\n v2.sort()\n i = 0\n j = 0\n ans = []\n while i < len(v1) and j < len(v2):\n if v1[i] == v2[j]:\n ans.append(v1[i])\n i += 1\n j += 1\n elif v1[i] < v2[j]:\n i += 1\n else:\n j += 1\n ans.sort()\n return ans", "def common_element(v1, v2):\n res = []\n v1Dict = {}\n v2Dict = {}\n for i in v1:\n v1Dict[i] = 1 + v1Dict.get(i, 0)\n for i in v2:\n v2Dict[i] = 1 + v2Dict.get(i, 0)\n for i in sorted(v1Dict):\n if i in v2Dict:\n c = [i] * min(v1Dict[i], v2Dict[i])\n res += c\n return res", "def common_element(v1, v2):\n res = []\n d = {}\n for num in v1:\n d[num] = d.get(num, 0) + 1\n for num in v2:\n if num in d and d[num] > 0:\n res.append(num)\n d[num] -= 1\n return sorted(res)", "from heapq import heapify, heappush, heappop\n\ndef common_element(v1, v2):\n hashmap = {}\n for i in v1:\n if i not in hashmap:\n hashmap[i] = 1\n else:\n hashmap[i] += 1\n result = []\n for j in v2:\n if j in hashmap and hashmap[j] > 0:\n hashmap[j] -= 1\n result.append(j)\n result.sort()\n return result", "def common_element(v1, v2):\n dict = {}\n c = []\n for i in v1:\n if i not in dict:\n dict[i] = 1\n else:\n dict[i] += 1\n for i in v2:\n if i in dict and dict[i] > 0:\n c.append(i)\n dict[i] -= 1\n c.sort()\n return c", "from collections import Counter\n\ndef common_element(v1, v2):\n v1 = Counter(v1)\n v2 = Counter(v2)\n lst = []\n for i in v1:\n if i in v2:\n for j in range(min(v1[i], v2[i])):\n lst.append(i)\n return sorted(lst)", "def common_element(v1, v2):\n mdict = {}\n res = []\n for x in v1:\n if x in mdict:\n mdict[x] += 1\n else:\n mdict[x] = 1\n v2.sort()\n for x in v2:\n if x in mdict and mdict[x] > 0:\n res.append(x)\n mdict[x] -= 1\n return res", "from collections import defaultdict\n\ndef common_element(v1, v2):\n v1.sort()\n v2.sort()\n l = []\n d1 = defaultdict(int)\n for i in v1:\n d1[i] += 1\n for j in v2:\n if j in d1 and d1[j] != 0:\n d1[j] -= 1\n l.append(j)\n return l", "from collections import Counter\n\ndef common_element(v1, v2):\n ans = []\n a = Counter(v1)\n v2.sort()\n for i in v2:\n if i in a and a[i] > 0:\n ans.append(i)\n a[i] -= 1\n return ans", "def common_element(v1, v2):\n (freq, l) = ({}, [])\n for i in v1:\n if i not in freq:\n freq.update({i: 1})\n else:\n freq[i] += 1\n for i in v2:\n if i in freq and freq[i] > 0:\n l.append(i)\n freq[i] -= 1\n return sorted(l)", "def common_element(v1, v2):\n v1 = sorted(v1)\n v2 = sorted(v2)\n d = {}\n d1 = {}\n l = []\n for i in v1:\n if i not in d:\n d[i] = 1\n else:\n d[i] = d[i] + 1\n for i in v2:\n if i not in d1:\n d1[i] = 1\n else:\n d1[i] = d1[i] + 1\n kkeys = list(d.keys())\n kkeys.sort()\n for i in kkeys:\n if i in d1:\n k = min(d[i], d1[i])\n l = l + [i] * k\n return l", "def common_element(v1, v2):\n v1.sort()\n v2.sort()\n b = []\n while v1 and v2:\n if v1[0] != v2[0]:\n if v1[0] < v2[0]:\n v1.pop(0)\n else:\n v2.pop(0)\n else:\n b.append(v1[0])\n v1.pop(0)\n v2.pop(0)\n return b", "def common_element(v1, v2):\n d = {}\n ans = []\n for i in v1:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n for i in v2:\n if i in d and d[i] != 0:\n ans.append(i)\n d[i] -= 1\n ans.sort()\n return ans", "from collections import defaultdict\n\ndef common_element(v1, v2):\n ans = []\n m = {}\n for i in v1:\n if i in m:\n m[i] += 1\n else:\n m[i] = 1\n ans = []\n for i in v2:\n if i in m and m[i] > 0:\n ans.append(i)\n m[i] -= 1\n ans.sort()\n return ans", "from collections import defaultdict\n\ndef common_element(v1, v2):\n (d1, d2) = (defaultdict(int), defaultdict(int))\n for i in v1:\n d1[i] += 1\n for i in v2:\n d2[i] += 1\n ans = []\n for (key, val) in d1.items():\n if key in d2:\n second = d2[key]\n for i in range(min(second, val)):\n ans.append(key)\n return sorted(ans)", "def common_element(v1, v2):\n v1.sort()\n v2.sort()\n (i, j) = (0, 0)\n li = []\n (n1, n2) = (len(v1), len(v2))\n while i < n1 and j < n2:\n if v1[i] == v2[j]:\n li.append(v1[i])\n i += 1\n j += 1\n elif v1[i] < v2[j]:\n i += 1\n else:\n j += 1\n return li", "def common_element(v1, v2):\n v1.sort()\n v2.sort()\n res = []\n i = 0\n j = 0\n n = len(v1)\n m = len(v2)\n while i < n and j < m:\n if v1[i] == v2[j]:\n res.append(v1[i])\n i += 1\n j += 1\n elif v1[i] > v2[j]:\n j += 1\n else:\n i += 1\n return res", "def common_element(v1, v2):\n l = []\n d = {}\n for i in v1:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for i in v2:\n if i in d and d[i] > 0:\n l.append(i)\n d[i] -= 1\n return sorted(l)", "def common_element(v1, v2):\n map1 = {}\n map2 = {}\n for i in range(len(v1)):\n if v1[i] not in map1:\n map1[v1[i]] = 1\n else:\n map1[v1[i]] += 1\n for i in range(len(v2)):\n if v2[i] not in map2:\n map2[v2[i]] = 1\n else:\n map2[v2[i]] += 1\n new = []\n for i in map1:\n if i in map2:\n x = [i] * min(map1[i], map2[i])\n new.extend(x)\n new.sort()\n return new", "from collections import Counter\n\ndef common_element(v1, v2):\n c1 = Counter(v1)\n c2 = Counter(v2)\n m = len(v1)\n n = len(v2)\n\n def getCommEle(v, c1, c2):\n res = []\n for num in set(v):\n if c1[num] > 0 and c2[num] > 0:\n for i in range(min(c1[num], c2[num])):\n res.append(num)\n return sorted(res)\n if m <= n:\n return getCommEle(v1, c1, c2)\n else:\n return getCommEle(v2, c1, c2)", "def common_element(v1, v2):\n d = {}\n ans = []\n for val in v1:\n if val in d:\n d[val] = d[val] + 1\n else:\n d[val] = 1\n v2 = sorted(v2)\n for val in v2:\n if val in d and d[val] > 0:\n ans.append(val)\n d[val] = d[val] - 1\n return ans", "def common_element(v1, v2):\n ans = []\n v1 = sorted(v1)\n l1 = len(v1)\n v2 = sorted(v2)\n l2 = len(v2)\n i = 0\n j = 0\n while i < l1 and j < l2:\n if v1[i] == v2[j]:\n ans.append(v1[i])\n j = j + 1\n i = i + 1\n elif v1[i] > v2[j]:\n j = j + 1\n elif v1[i] < v2[j]:\n i = i + 1\n return ans", "def common_element(v1, v2):\n v1.sort()\n v2.sort()\n d1 = {}\n d2 = {}\n for i in v1:\n if i in d1:\n d1[i] += 1\n else:\n d1[i] = 1\n for i in v2:\n if i in d2:\n d2[i] += 1\n else:\n d2[i] = 1\n ans = []\n for i in d1:\n if i in d2:\n c = min(d1[i], d2[i])\n while c > 0:\n ans.append(i)\n c -= 1\n ans.sort()\n return ans", "from collections import defaultdict\n\ndef common_element(v1, v2):\n d = defaultdict(int)\n finalList = []\n for i in v1:\n d[i] += 1\n for i in v2:\n if d[i] != 0:\n finalList.append(i)\n d[i] -= 1\n finalList.sort()\n return finalList", "import operator as op\n\ndef common_element(v1, v2):\n ans = []\n i = j = 0\n v1 = sorted(v1)\n v2 = sorted(v2)\n while i < len(v1) and j < len(v2):\n if v1[i] == v2[j]:\n ans.append(v1[i])\n i += 1\n j += 1\n elif v1[i] > v2[j]:\n j += 1\n else:\n i += 1\n return ans", "def common_element(v1, v2):\n res = []\n a = sorted(v1)\n b = sorted(v2)\n i = 0\n j = 0\n while i < len(a) and j < len(b):\n if a[i] == b[j]:\n res.append(a[i])\n i = i + 1\n j = j + 1\n elif a[i] > b[j]:\n j = j + 1\n elif a[i] < b[j]:\n i = i + 1\n return sorted(res)", "from collections import Counter\n\ndef common_element(v1, v2):\n freq = Counter(v1)\n ans = list()\n for e in v2:\n if e in freq:\n freq[e] -= 1\n if freq[e] >= 0:\n ans.append(e)\n return sorted(ans)", "def common_element(v1, v2):\n result = []\n hash_v1 = {}\n hash_v2 = {}\n for i in range(len(v1)):\n if v1[i] in hash_v1:\n hash_v1[v1[i]] += 1\n else:\n hash_v1[v1[i]] = 1\n for i in range(len(v2)):\n if v2[i] in hash_v2:\n hash_v2[v2[i]] += 1\n else:\n hash_v2[v2[i]] = 1\n for i in hash_v1:\n if i in hash_v2:\n get_values_v1 = hash_v1[i]\n get_values_v2 = hash_v2[i]\n get_min = min(get_values_v1, get_values_v2)\n for j in range(get_min):\n result.append(i)\n result = sorted(result)", "from collections import defaultdict\n\ndef s():\n return 0\n\ndef common_element(v1, v2):\n hash1 = defaultdict(self.s)\n (_, L1) = max((len(v1), v1), (len(v2), v2))\n (_, L2) = min((len(v1), v1), (len(v2), v2))\n for i in L2:\n hash1[i] += 1\n res = []\n for i in L1:\n if hash1[i] > 0:\n hash1[i] -= 1\n res.append(i)\n res.sort()\n return res", "def common_element(v1, v2):\n out = []\n my_hm = {}\n for i in v1:\n if i in my_hm:\n my_hm[i] += 1\n else:\n my_hm[i] = 1\n for j in v2:\n if j in my_hm and my_hm[j] != 0:\n out.append(j)\n my_hm[j] -= 1\n out.sort()\n return out", "def common_element(v1, v2):\n v1.sort()\n v2.sort()\n ls = []\n d = dict()\n for i in v1:\n if i in d.keys():\n d[i] += 1\n else:\n d[i] = 1\n for i in v2:\n if i in d.keys() and d[i] != 0:\n ls.append(i)\n d[i] -= 1\n return ls", "def common_element(v1, v2):\n hm = {}\n res = []\n for i in v1:\n if i in hm:\n hm[i] += 1\n else:\n hm[i] = 1\n for i in v2:\n if i in hm:\n res.append(i)\n hm[i] -= 1\n if hm[i] == 0:\n del hm[i]\n res.sort()\n return res", "def common_element(v1, v2):\n hash = {}\n for i in range(len(v1)):\n if v1[i] in hash:\n hash[v1[i]] += 1\n else:\n hash[v1[i]] = 1\n ans = []\n for j in v2:\n if j in hash and hash[j] != 0:\n ans.append(j)\n hash[j] -= 1\n return sorted(ans)", "def common_element(v1, v2):\n commonhashA = {}\n commonhashB = {}\n for i in v1:\n if not i in commonhashA:\n commonhashA[i] = 1\n else:\n commonhashA[i] += 1\n for j in v2:\n if not j in commonhashB:\n commonhashB[j] = 1\n else:\n commonhashB[j] += 1\n tmp = []\n for k in v2:\n if k in commonhashA and commonhashA[k] != 0:\n commonhashA[k] -= 1\n tmp.append(k)\n tmp.sort()\n return tmp", "def common_element(v1, v2):\n a = v1\n b = v2\n list = []\n dict = {}\n for i in a:\n if i in dict:\n dict[i] += 1\n else:\n dict[i] = 1\n b.sort()\n for i in b:\n if i in dict and dict[i] > 0:\n list.append(i)\n dict[i] -= 1\n return list", "def common_element(V1, V2):\n V1.sort()\n V2.sort()\n l = []\n (i, j) = (0, 0)\n while i < len(V1) and j < len(V2):\n if V1[i] == V2[j]:\n l.append(V1[i])\n i += 1\n j += 1\n elif V1[i] > V2[j]:\n j += 1\n else:\n i += 1\n return l", "def common_element(v1, v2):\n d = dict()\n d1 = dict()\n for i in v1:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n for i in v2:\n if i not in d1:\n d1[i] = 1\n else:\n d1[i] += 1\n ans = []\n for i in sorted(d):\n if i in d1:\n l = [i] * min(d[i], d1[i])\n ans += l\n return ans", "from collections import Counter\n\ndef common_element(v1, v2):\n c1 = Counter(v1)\n c2 = Counter(v2)\n l = []\n for (i, j) in c2.items():\n if i in c1:\n l += [i] * min(j, c1[i])\n l.sort()\n return l", "def common_element(a, b):\n v1.sort()\n v2.sort()\n s = []\n i = 0\n j = 0\n while i < len(v1) and j < len(v2):\n if v1[i] < v2[j]:\n i = i + 1\n elif v1[i] > v2[j]:\n j = j + 1\n else:\n s.append(v1[i])\n i += 1\n j += 1\n return s", "from collections import defaultdict\n\ndef common_element(v1, v2):\n ans = []\n sample = defaultdict(int)\n for c in v1:\n sample[c] += 1\n v2.sort()\n for c in v2:\n if c in sample and sample[c] > 0:\n ans.append(c)\n sample[c] -= 1\n return ans", "def common_element(v1, v2):\n ans = []\n dic = {}\n for i in range(len(v1)):\n if v1[i] in dic:\n dic[v1[i]] += 1\n else:\n dic[v1[i]] = 1\n for j in range(len(v2)):\n if v2[j] in dic.keys():\n ans.append(v2[j])\n if dic[v2[j]] == 1:\n dic.pop(v2[j])\n else:\n dic[v2[j]] -= 1\n ans.sort()\n return ans", "def common_element(v1, v2):\n tab = {}\n res = []\n for val in v1:\n if val in tab:\n tab[val] += 1\n else:\n tab[val] = 1\n v2.sort()\n for val in v2:\n if val in tab and tab[val] > 0:\n res.append(val)\n tab[val] -= 1\n return res", "def common_element(v1, v2):\n map1 = {}\n map2 = {}\n answer = []\n for i in v1:\n map1[i] = map1.get(i, 0) + 1\n for i in v2:\n map2[i] = map2.get(i, 0) + 1\n for key in map1.keys():\n if key in map2.keys():\n for i in range(min(map1[key], map2[key])):\n answer.append(key)\n answer.sort()\n return answer", "def common_element(v1, v2):\n d1 = {}\n d2 = {}\n for i in v1:\n d1[i] = d1.get(i, 0) + 1\n for i in v2:\n d2[i] = d2.get(i, 0) + 1\n l = set(v1).intersection(set(v2))\n l = sorted(l)\n ans = []\n for i in l:\n a = min(d1[i], d2[i])\n for j in range(a):\n ans.append(i)\n return ans", "def common_element(v1, v2):\n dic = {}\n for i in v1:\n if i in dic.keys():\n dic[i] += 1\n else:\n dic[i] = 1\n mylist = []\n for i in v2:\n if i in dic.keys() and dic[i] != 0:\n mylist.append(i)\n dic[i] -= 1\n mylist.sort()\n return mylist", "def common_element(v1, v2):\n d = {}\n r = []\n for i in v1:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for i in v2:\n if i in d:\n r.append(i)\n if d[i] == 1:\n del d[i]\n else:\n d[i] -= 1\n r.sort()\n return r", "def common_element(v1, v2):\n res = []\n v1.sort()\n v2.sort()\n (p1, p2) = (0, 0)\n while p1 < len(v1) and p2 < len(v2):\n if v1[p1] == v2[p2]:\n res.append(v1[p1])\n p1 += 1\n p2 += 1\n elif v1[p1] > v2[p2]:\n p2 += 1\n else:\n p1 += 1\n return res", "def common_element(v1, v2):\n res = []\n hash = {}\n for x in v1:\n if x in hash:\n hash[x] += 1\n else:\n hash[x] = 1\n for x in v2:\n if x in hash:\n hash[x] -= 1\n res.append(x)\n if hash[x] == 0:\n hash.pop(x)\n res.sort()\n return res", "from collections import Counter\n\ndef common_element(v1, v2):\n d1 = Counter(v1)\n d2 = Counter(v2)\n lst = []\n for key in d1.keys():\n if d2.get(key) != None:\n lst.extend([key] * min(d1[key], d2[key]))\n return sorted(lst)", "def common_element(v1, v2):\n res = []\n\n def form_maps(a):\n d = {}\n for elm in a:\n if elm not in d:\n d[elm] = 1\n else:\n d[elm] += 1\n return d\n (map1, map2) = (form_maps(v1), form_maps(v2))\n for (k, v) in map1.items():\n if k in map2:\n cnt = 0\n while cnt < min(map1[k], map2[k]):\n res.append(k)\n cnt += 1\n res.sort()\n return res", "def common_element(v1, v2):\n d = {}\n for x in v1:\n if d.get(x) == None:\n d[x] = 1\n else:\n d[x] += 1\n l = []\n for x in v2:\n if d.get(x) != None:\n if d[x] > 0:\n l.append(x)\n d[x] -= 1\n l.sort()\n return l", "from collections import Counter\n\ndef common_element(v1, v2):\n c1 = Counter(v1)\n c2 = Counter(v2)\n ans = []\n for j in c1:\n if j in c2:\n ans += [j] * min(c1[j], c2[j])\n return sorted(ans)", "def common_element(arr1, arr2):\n d1 = {}\n d2 = {}\n s = set(arr1)\n ans = []\n for i in range(len(arr1)):\n d1[arr1[i]] = d1.get(arr1[i], 0) + 1\n for i in range(len(arr2)):\n if arr2[i] in d1 and d1[arr2[i]] > 0:\n d1[arr2[i]] -= 1\n ans.append(arr2[i])\n ans.sort()\n return ans"], "starter_code": "def common_element(v1,v2):\n", "input_output": {"inputs": ["n = 5\r\nv1[] = {3, 4, 2, 2, 4}\r\nm = 4\r\nv2[] = {3, 2, 2, 7}"], "outputs": ["2 2 3"]}, "difficulty": "EASY", "raw_tags": ["Java", "STL", "Java-Collections"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/common-elements5420/1", "Expected Auxiliary Space": "", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "", "entry_point": "common_element", "task_id": "TACO_lite/365", "example": [[[5, [3, 4, 2, 2, 4], 4, [3, 2, 2, 7]]], ["[2, 2, 3]"]]} +{"requirement": "Your job is to return the volume of a cup when given the diameter of the top, the diameter of the bottom and the height.\n\nYou know that there is a steady gradient from the top to the bottom.\n\nYou want to return the volume rounded to 2 decimal places.\n\nExmples:\n```python\ncup_volume(1, 1, 1)==0.79\n\ncup_volume(10, 8, 10)==638.79\n\ncup_volume(1000, 1000, 1000)==785398163.4\n\ncup_volume(13.123, 123.12, 1)==4436.57\n\ncup_volume(5, 12, 31)==1858.51\n```\n\nYou will only be passed positive numbers.", "solutions": ["from math import pi\n\ndef cup_volume(d1, d2, h):\n return round(h / 12.0 * pi * (d1 ** 2 + d1 * d2 + d2 ** 2), 2)", "from math import pi\n\ndef cup_volume(d1, d2, height):\n (r1, r2) = (d1 / 2.0, d2 / 2.0)\n return round(pi * height * (pow(r1, 2) + r1 * r2 + pow(r2, 2)) / 3.0, 2)", "def cup_volume(d1, d2, h):\n return round(h * (d1 * d1 + d1 * d2 + d2 * d2) * 0.2617993878, 2)", "cup_volume = lambda d, D, h: round(__import__('math').pi * h / 12 * (d * d + d * D + D * D), 2)", "import math\n\ndef cup_volume(d1, d2, height):\n if d1 > d2:\n (d1, d2) = (d2, d1)\n if d1 == d2:\n return round((d1 / 2.0) ** 2 * math.pi * height, 2)\n x = d1 * float(height) / (d2 - d1)\n vol = (d2 / 2.0) ** 2 * math.pi * (height + x) / 3.0 - (d1 / 2.0) ** 2 * math.pi * x / 3.0\n return round(vol, 2)", "def cup_volume(d1, d2, height):\n v = 3.14159265359 / 3 * height * ((d1 / 2) ** 2 + (d2 / 2) ** 2 + d1 / 2 * d2 / 2)\n return round(v, 2)", "import math\n\ndef cup_volume(d1, d2, height):\n return round(math.pi * height * (d1 ** 2 + d2 ** 2 + d1 * d2) / 12, 2)", "from math import pi\n\ndef cup_volume(d1, d2, h):\n (r1, r2) = (d1 / 2, d2 / 2)\n return round(pi * (1 / 3) * h * (r1 ** 2 + r2 ** 2 + r1 * r2), 2)"], "starter_code": "def cup_volume(d1, d2, height):\n", "input_output": {"fn_name": "cup_volume", "inputs": [[1, 1, 1], [10, 8, 10], [1000, 1000, 1000], [13.123, 123.12, 1], [5, 12, 31]], "outputs": [[0.79], [638.79], [785398163.4], [4436.57], [1858.51]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Geometry"], "name": null, "source": "codewars", "tags": ["Geometry", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56a13035eb55c8436a000041", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "cup_volume", "task_id": "TACO_lite/298", "example": [[[1, 1, 1], [10, 8, 10], [1000, 1000, 1000], [13.123, 123.12, 1], [5, 12, 31]], ["0.79", "638.79", "785398163.4", "4436.57", "1858.51"]]} +{"requirement": "Define a function that takes in two non-negative integers `$a$` and `$b$` and returns the last decimal digit of `$a^b$`. Note that `$a$` and `$b$` may be very large!\n\nFor example, the last decimal digit of `$9^7$` is `$9$`, since `$9^7 = 4782969$`. The last decimal digit of `$({2^{200}})^{2^{300}}$`, which has over `$10^{92}$` decimal digits, is `$6$`. Also, please take `$0^0$` to be `$1$`.\n\nYou may assume that the input will always be valid.\n\n## Examples\n\n```python\nlast_digit(4, 1) # returns 4\nlast_digit(4, 2) # returns 6\nlast_digit(9, 7) # returns 9\nlast_digit(10, 10 ** 10) # returns 0\nlast_digit(2 ** 200, 2 ** 300) # returns 6\n```\n\n___\n\n## Remarks\n\n### JavaScript, C++, R, PureScript\n\nSince these languages don't have native arbitrarily large integers, your arguments are going to be strings representing non-negative integers instead.", "solutions": ["def last_digit(n1, n2):\n return pow(n1, n2, 10)", "rules = {0: [0, 0, 0, 0], 1: [1, 1, 1, 1], 2: [2, 4, 8, 6], 3: [3, 9, 7, 1], 4: [4, 6, 4, 6], 5: [5, 5, 5, 5], 6: [6, 6, 6, 6], 7: [7, 9, 3, 1], 8: [8, 4, 2, 6], 9: [9, 1, 9, 1]}\n\ndef last_digit(n1, n2):\n ruler = rules[int(str(n1)[-1])]\n return 1 if n2 == 0 else ruler[n2 % 4 - 1]", "def last_digit(n1, n2):\n return (n1 % 10) ** (n2 % 4 + 4 * bool(n2)) % 10", "E = [[0, 0, 0, 0], [1, 1, 1, 1], [6, 2, 4, 8], [1, 3, 9, 7], [6, 4, 6, 4], [5, 5, 5, 5], [6, 6, 6, 6], [1, 7, 9, 3], [6, 8, 4, 2], [1, 9, 1, 9]]\n\ndef last_digit(n1, n2):\n if n2 == 0:\n return 1\n return E[n1 % 10][n2 % 4]", "last_digit = lambda n1, n2: pow(n1, n2, 10)", "def last_digit(n1, n2):\n m1 = n1 % 10\n if m1 == 1:\n return 1\n if m1 == 2:\n if n2 == 0:\n return 1\n elif n2 % 4 == 3:\n return 8\n elif n2 % 4 == 0:\n return 6\n elif n2 % 4 == 2:\n return 4\n else:\n return 2\n if m1 == 3:\n if n2 == 0:\n return 1\n elif n2 % 4 == 0:\n return 1\n elif n2 % 2 == 0:\n return 9\n elif n2 % 4 == 3:\n return 7\n else:\n return 3\n if m1 == 4:\n if n2 == 0:\n return 1\n elif n2 % 4 == 2 or n2 % 4 == 0:\n return 6\n else:\n return 4\n if m1 == 5:\n if n2 == 0:\n return 1\n else:\n return 5\n if m1 == 6:\n if n2 == 0:\n return 1\n else:\n return 6\n if m1 == 7:\n if n2 == 0:\n return 1\n elif n2 % 4 == 3:\n return 3\n elif n2 % 4 == 0:\n return 1\n elif n2 % 4 == 2:\n return 9\n else:\n return 7\n if m1 == 8:\n if n2 == 0:\n return 1\n elif n2 % 4 == 3:\n return 2\n elif n2 % 4 == 0:\n return 6\n elif n2 % 4 == 2:\n return 4\n else:\n return 8\n if m1 == 9:\n if n2 == 0:\n return 1\n elif n2 % 2 == 1:\n return 9\n else:\n return 1\n if m1 == 0:\n if n2 == 0:\n return 1\n return 0", "def last_digit(n1, n2):\n last_dict = {0: [0], 1: [1], 2: [2, 4, 6, 8], 3: [3, 9, 7, 1], 4: [4, 6], 5: [5], 6: [6], 7: [7, 9, 3, 1], 8: [8, 4, 2, 6], 9: [9, 1]}\n if n2 == 0:\n return 1\n a = n1 % 10\n return last_dict[a][(n2 - 1) % len(last_dict[a])]", "def last_digit(n1, n2):\n if n2 == 0:\n return 1\n seq = [[0], [1], [2, 4, 8, 6], [3, 9, 7, 1], [4, 6], [5], [6], [7, 9, 3, 1], [8, 4, 2, 6], [9, 1]]\n l_digit = int(str(n1)[-1])\n position = n2 % len(seq[l_digit])\n return seq[l_digit][position - 1]"], "starter_code": "def last_digit(n1, n2):\n", "input_output": {"fn_name": "last_digit", "inputs": [[4, 1], [4, 2], [9, 7], [10, 1000000000], [38710248912497124917933333333284108412048102948908149081409204712406, 226628148126342643123641923461846128214626], [3715290469715693021198967285016729344580685479654510946723, 68819615221552997273737174557165657483427362207517952651]], "outputs": [[4], [6], [9], [0], [6], [7]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5511b2f550906349a70004e1", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "last_digit", "task_id": "TACO_lite/324", "example": [[[4, 1], [4, 2], [9, 7], [10, 10000000000], [1606938044258990275541962092341162602522202993782792835301376, 34679820440162766727291522857913285077400432927453350399864480129571625151552679665473828989182912797066473733424990924602022130834382211112859327]], ["4", "6", "9", "0", "6"]]} +{"requirement": "As you may know, once some people pass their teens, they jokingly only celebrate their 20th or 21st birthday, forever. With some maths skills, that's totally possible - you only need to select the correct number base!\n\nFor example, if they turn 32, that's exactly 20 - in base 16... Already 39? That's just 21, in base 19!\n\nYour task is to translate the given age to the much desired 20 (or 21) years, and indicate the number base, in the format specified below.\n\n**Note:** input will be always > 21\n\n\n### Examples:\n\n```\n32 --> \"32? That's just 20, in base 16!\"\n39 --> \"39? That's just 21, in base 19!\"\n```\n\n*Hint: if you don't know (enough) about [numeral systems](https://en.wikipedia.org/wiki/Numeral_system) and [radix](https://en.wikipedia.org/wiki/Radix), just observe the pattern!*\n\n---\n\n## My other katas\n\nIf you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-)\n\n---\n\n### *Translations are welcome!*", "solutions": ["def womens_age(n):\n return f\"{n}? That's just {20 + n % 2}, in base {n // 2}!\"", "womens_age = lambda n: f\"{n}? That's just 2{n % 2}, in base {n // 2}!\"", "def womens_age(n):\n return f\"{n}? That's just {(21 if n % 2 else 20)}, in base {((n - 1) // 2 if n % 2 else n // 2)}!\"", "def womens_age(n):\n for i in range(11, 100):\n (a, b) = divmod(n, i)\n if a == 2 and b < 2:\n return f\"{n}? That's just {a}{b}, in base {i}!\"", "def womens_age(n):\n a = 2\n L1 = [0, 1]\n for i in L1:\n x = int((n - L1[i]) / a)\n if n % x == L1[i]:\n base = x\n result = '%d%d' % (a, L1[i])\n return str(n) + \"? That's just \" + str(result) + ', in base ' + str(base) + '!'", "womens_age = lambda Q: f\"{Q}? That's just 2{1 & Q}, in base {Q >> 1}!\"", "def womens_age(n):\n return str(n) + \"? That's just 20, in base \" + str(n // 2) + '!' if n % 2 == 0 else str(n) + \"? That's just 21, in base \" + str(n // 2) + '!'"], "starter_code": "def womens_age(n):\n", "input_output": {"fn_name": "womens_age", "inputs": [[32], [39], [22], [65], [83]], "outputs": [["32? That's just 20, in base 16!"], ["39? That's just 21, in base 19!"], ["22? That's just 20, in base 11!"], ["65? That's just 21, in base 32!"], ["83? That's just 21, in base 41!"]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5e96332d18ac870032eb735f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "womens_age", "task_id": "TACO_lite/393", "example": [[[32], [39]], ["32? That's just 20, in base 16!", "39? That's just 21, in base 19!"]]} +{"requirement": "Given a positive integer N, find the number of factors in N! ( N factorial).\nExample :\nInput:\nN = 5\nOutput:\n16\nExplanation:\n5! is 120 and the number of factors of\n120 are 1 2 3 4 5 6 8 10 12 15 20 24 30\n40 60 120 So the number of factors are 16.\nExample 2:\nInput:\nN = 4\nOutput:\n8\nExplanation:\n4! is 24 and the number of factors of\n24 are 1 2 3 4 6 8 12 24\nSo the number of factors are 8.\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function factorsOfFactorial() which takes an integer N as an input parameter and return the number of factors of N factorial.\nExpected Time Complexity: O(NLogLogN)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 <= N <= 100", "solutions": ["def calWays(n, p):\n j = p\n c = 0\n while n // j > 0:\n c += n // j\n j *= p\n return c + 1\n\ndef factorsoffactorial(N):\n if N < 1:\n return 1\n t = N\n N = N + 1\n r = 1\n prime = []\n for i in range(N):\n prime.append(1)\n prime[0] = 0\n prime[1] = 0\n for i in range(2, int(N ** 0.5) + 1):\n j = 2\n while j * i < N:\n prime[j * i] = 0\n j += 1\n for i in range(len(prime)):\n if prime[i] == 1:\n r *= self.calWays(t, i)\n return r", "from math import sqrt\n\ndef factorsoffactorial(N):\n prime = [True] * (N + 1)\n i = 2\n while i * i <= N:\n if prime[i]:\n for j in range(i * i, N + 1, i):\n prime[j] = False\n i += 1\n res = 1\n for i in range(2, N + 1):\n if not prime[i]:\n continue\n x = 0\n y = i\n while N // y > 0:\n x += N // y\n y *= i\n res *= x + 1\n return res", "from math import sqrt\n\ndef factorsoffactorial(N):\n res = 1\n for i in range(2, N + 1):\n f = False\n for j in range(2, int(sqrt(i)) + 1):\n if i % j == 0:\n f = True\n break\n if f:\n continue\n x = 0\n y = i\n while N // y > 0:\n x += N // y\n y *= i\n res *= x + 1\n return res"], "starter_code": "def factorsoffactorial(N):\n", "input_output": {"inputs": ["N = 5", "N = 4"], "outputs": ["16", "8"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/no-of-factors-of-n4833/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(NLogLogN)", "entry_point": "factorsoffactorial", "task_id": "TACO_lite/345", "example": [[[5], [4]], ["16", "8"]]} +{"requirement": "You want to build a standard house of cards, but you don't know how many cards you will need. Write a program which will count the minimal number of cards according to the number of floors you want to have. For example, if you want a one floor house, you will need 7 of them (two pairs of two cards on the base floor, one horizontal card and one pair to get the first floor). Here you can see which kind of house of cards I mean:\nhttp://www.wikihow.com/Build-a-Tower-of-Cards\n\n## Note about floors:\nThis kata uses the British numbering system for building floors. If you want your house of cards to have a first floor, it needs a ground floor and then a first floor above that.\n\n### Details (Ruby & JavaScript & Python & R)\nThe input must be an integer greater than 0, for other input raise an error.\n\n### Details (Haskell)\nThe input must be an integer greater than 0, for other input return `Nothing`.", "solutions": ["def house_of_cards(n):\n if n >= 1:\n return (n + 1) * n / 2 + (n + 2) * (n + 1)\n raise ValueError", "def house_of_cards(n):\n assert n > 0\n return (n + 1) * (3 * n + 4) // 2", "def house_of_cards(floors):\n assert isinstance(floors, int) and floors > 0\n return (floors + 1) * (3 * floors + 4) // 2", "def house_of_cards(f):\n return f * (f + 1) / 2 + (f + 1) * (f + 2) if f > 0 else error", "def house_of_cards(floors):\n assert floors > 0\n return sum((2 + 3 * a for a in range(floors + 1)))", "def house_of_cards(n):\n if n < 1:\n raise error\n return 3 * n * (n + 1) // 2 + 2 * (n + 1)", "def house_of_cards(floors):\n if floors <= 0:\n raise ValueError('The input must be an integer greater than 0')\n return 2 + sum((3 * i + 2 for i in range(1, floors + 1)))", "def house_of_cards(floors):\n if floors < 1:\n raise Exception()\n return (floors + 1) * (3 * floors + 4) // 2"], "starter_code": "def house_of_cards(floors):\n", "input_output": {"fn_name": "house_of_cards", "inputs": [[1], [2], [3]], "outputs": [[7], [15], [26]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/543abbc35f0461d28f000c11", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "house_of_cards", "task_id": "TACO_lite/410", "example": [[[1]], ["7"]]} +{"requirement": "Given N in Gray Code, find its binary equivalent. Return the decimal representation of the binary equivalent.\nExample 1:\nInput: N = 4\nOutput: 7\nExplanation:\nGiven 4 representing gray code 110.\nBinary equivalent of gray code 110 is 100.\nReturn 7 representing gray code 100.\nExample 2:\nInput: N = 15\nOutput: 10\nExplanation:\nGiven 15 representing gray code 1000.\nBinary equivalent of gray code 1000 is 1111.\nReturn 10 representing gray code 1111 \nie binary 1010.\nExample 3:\nInput: N = 0\nOutput: 0\nExplanation: \nZero remains the same in all systems.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function grayToBinary() which accepts an integer n as an input parameter and returns decimal of the binary equivalent of the given gray code. \nExpected Time Complexity: O(log N)\nExpected Auxiliary Space: O(1)\nConstraints:\n0 <= N <= 10^{8}", "solutions": ["def graytobinary(n: int) -> int:\n binary = n\n while n > 0:\n n >>= 1\n binary ^= n\n return binary", "def graytobinary(n):\n b = 0\n while n > 0:\n b = b ^ n\n n = n >> 1\n return b", "def graytobinary(n):\n res = n\n while n > 0:\n n >>= 1\n res ^= n\n return res", "def graytobinary(n):\n b = 0\n for i in iter(int, 1):\n if n > 0:\n b = b ^ n\n n = n >> 1\n else:\n break\n return b", "def graytobinary(n: int) -> int:\n mask = n\n while mask != 0:\n mask >>= 1\n n ^= mask\n return n", "def graytobinary(n):\n ans = n\n while n > 0:\n n = n >> 1\n ans = ans ^ n\n return ans", "def graytobinary(n):\n gray_rep = bin(n)[2:]\n binary = gray_rep[0]\n for i in range(1, len(gray_rep)):\n if gray_rep[i] == '0':\n binary += binary[i - 1]\n else:\n binary += str(int(not int(binary[i - 1])))\n return int(binary, 2)", "def graytobinary(n):\n c = 0\n while n:\n c ^= n\n n >>= 1\n return c", "def graytobinary(n):\n binary = n & 1 << len(bin(n)) - 3\n for i in range(len(bin(n)) - 4, -1, -1):\n binary |= (binary >> 1 ^ n & 1 << i) & 1 << i\n return binary", "import math\n\ndef graytobinary(n):\n t = n\n while t != 0:\n t = t >> 1\n n = n ^ t\n return n", "def graytobinary(n):\n v = 0\n while n:\n v = v ^ n\n n = n >> 1\n return v", "def graytobinary(n):\n a = n >> 1\n while a:\n n ^= a\n a = a >> 1\n return n", "def graytobinary(n):\n k = len(bin(n)) - 2\n bin_y = 0\n xor = n >> k & 1\n bin_y = bin_y + xor\n k = k - 1\n while k >= 0:\n xor = xor ^ n >> k & 1\n bin_y = bin_y + (xor << k)\n k = k - 1\n return bin_y", "def graytobinary(n):\n N = n\n while n > 0:\n n = n >> 1\n N = N ^ n\n return N", "def graytobinary(n):\n x = 0\n while n > 0:\n x = x ^ n\n n = n >> 1\n return x", "def graytobinary(n):\n temp = n\n while n > 0:\n n >>= 1\n temp = temp ^ n\n return temp", "def graytobinary(n):\n inv = 0\n while n:\n inv = inv ^ n\n n = n >> 1\n return inv\n return n ^ n >> 1", "def graytobinary(n):\n r = n\n n >>= 1\n while n:\n r ^= n\n n >>= 1\n return r", "def graytobinary(n):\n result = n\n while n > 0:\n n = n >> 1\n result ^= n\n return result", "def graytobinary(n):\n count = 0\n while n:\n count ^= n\n n >>= 1\n return count", "def graytobinary(n):\n div = n\n while div // 2 != 0:\n n = n ^ div // 2\n div = div // 2\n return n", "def graytobinary(n):\n x = n\n while True:\n if n == x ^ x >> 1:\n return x\n break\n x = x ^ x >> 1"], "starter_code": "def graytobinary(n):\n", "input_output": {"inputs": ["N = 4", "N = 15", "N = 0"], "outputs": ["7", "10", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/gray-to-binary-equivalent-1587115620/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(log N)", "entry_point": "graytobinary", "task_id": "TACO_lite/398", "example": [[[4], [15], [0]], ["7", "10", "0"]]} +{"requirement": "Given a BST, and a reference to a Node x in the BST. Find the Inorder Successor of the given node in the BST.\n \nExample 1:\nInput:\n 2\n / \\\n 1 3\nK(data of x) = 2\nOutput: 3 \nExplanation: \nInorder traversal : 1 2 3 \nHence, inorder successor of 2 is 3.\nExample 2:\nInput:\n 20\n / \\\n 8 22\n / \\\n 4 12\n / \\\n 10 14\nK(data of x) = 8\nOutput: 10\nExplanation:\nInorder traversal: 4 8 10 12 14 20 22\nHence, successor of 8 is 10.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function inOrderSuccessor(). This function takes the root node and the reference node as argument and returns the node that is inOrder successor of the reference node. If there is no successor, return null value.\nExpected Time Complexity: O(Height of the BST).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= N <= 1000, where N is number of nodes", "solutions": ["def inorderSuccessor(root, x):\n ans = None\n while root != None:\n if root.data > x.data:\n ans = root\n root = root.left\n else:\n root = root.right\n return ans", "def inorderSuccessor(root, x):\n c = None\n while root is not None:\n if root.data > x.data:\n c = root\n root = root.left\n else:\n root = root.right\n return c", "def inorderSuccessor(root, p):\n if not root:\n return None\n if root.data <= p.data:\n return self.inorderSuccessor(root.right, p)\n return self.inorderSuccessor(root.left, p) or root\n\ndef inOrderTraversal(root, n, succ):\n if root == None:\n return\n self.inOrderTraversal(root.left, n, succ)\n if root.data > n.data and (not succ.left):\n succ.left = root\n return\n self.inOrderTraversal(root.right, n, succ)", "def inorderSuccessor(root, n):\n succ = Node(0)\n self.inOrderTraversal(root, n, succ)\n return succ.left\n\ndef inOrderTraversal(root, n, succ):\n if root == None:\n return\n self.inOrderTraversal(root.left, n, succ)\n if root.data > n.data and (not succ.left):\n succ.left = root\n return\n self.inOrderTraversal(root.right, n, succ)", "def min_right(root):\n if root == None:\n return None\n a = self.min_right(root.left)\n if a == None:\n return root\n else:\n return a\n\ndef find(root, x):\n if x.data == root.data:\n return self.min_right(root.right)\n if x.data < root.data:\n a = self.find(root.left, x)\n if a == None:\n return root\n else:\n return a\n else:\n a = self.find(root.right, x)\n return a\n\ndef inorderSuccessor(root, x):\n return self.find(root, x)", "def inorderSuccessor(root, x):\n res = []\n ans = []\n\n def inorder(root):\n if root == None:\n return\n inorder(root.left)\n res.append(root.data)\n ans.append(root)\n inorder(root.right)\n inorder(root)\n i = res.index(x.data)\n if i < len(res) - 1:\n return ans[i + 1]\n else:\n return None", "def inorderSuccessor(root, x):\n successor = None\n while root:\n if root.data <= x.data:\n root = root.right\n else:\n successor = root\n root = root.left\n return successor", "def inorderSuccessor(root, x):\n y = self.inorder(root, [])\n i = y.index(x.data)\n try:\n return Node(y[i + 1])\n except IndexError:\n return None\n\ndef inorder(node, a):\n if node is None:\n return\n else:\n self.inorder(node.left, a)\n a.append(node.data)\n self.inorder(node.right, a)\n return a", "def minValue(node):\n while node.left:\n node = node.left\n return node\n\ndef get_node(root, node):\n if not root:\n return None\n x = self.get_node(root.left, node)\n if x:\n return x\n if root.data == node.data:\n return root\n y = self.get_node(root.right, node)\n if y:\n return y\n\ndef inorderSuccessor(root, x):\n x = self.get_node(root, x)\n if x.right is not None:\n return self.minValue(x.right)\n succ = None\n curr = root\n while curr and curr != x:\n if x.data > curr.data:\n curr = curr.right\n elif x.data <= curr.data:\n succ = curr\n curr = curr.left\n return succ", "def inorderSuccessor(root, x):\n stack = []\n curr = root\n prev = None\n while curr or stack:\n while curr:\n stack.append(curr)\n curr = curr.left\n curr = stack.pop()\n if prev and prev.data == x.data:\n return curr\n prev = curr\n curr = curr.right", "def inorderSuccessor(root, x):\n temp = root\n while temp:\n if temp.data == x.data:\n break\n elif temp.data > x.data:\n temp = temp.left\n else:\n temp = temp.right\n if temp is None:\n return None\n if temp.right:\n successor = self.find_min(temp.right)\n else:\n successor = self.find_ancestor(root, temp)\n return successor\n\ndef find_min(node):\n while node.left:\n node = node.left\n return node\n\ndef find_ancestor(root, node):\n successor = Node(-1)\n while root:\n if root.data < node.data:\n root = root.right\n elif root.data > node.data:\n successor = root\n root = root.left\n else:\n break\n return successor", "def inorderSuccessor(root, x):\n array = []\n self.inorder(root, array)\n for i in range(len(array)):\n if array[i].data == x.data:\n if len(array) == i + 1:\n return None\n else:\n return array[i + 1]\n\ndef inorder(node, array):\n if node:\n self.inorder(node.left, array)\n array.append(node)\n self.inorder(node.right, array)", "def InOrder(root, x, suc):\n if root != None:\n self.InOrder(root.left, x, suc)\n if root.data > x.data:\n if suc[0] == None:\n suc[0] = root\n self.InOrder(root.right, x, suc)\n\ndef inorderSuccessor(root, x):\n suc = [None]\n self.InOrder(root, x, suc)\n return suc[0]", "def inorderSuccessor(root, x):\n nextGreaterNode = None\n temp = root\n while temp:\n if x.data < root.data:\n nextGreaterNode = root\n root = root.left\n elif x.data == root.data:\n if root.right:\n focus = root.right\n while focus:\n if focus.left:\n focus = focus.left\n else:\n return focus\n else:\n return nextGreaterNode if nextGreaterNode else None\n else:\n root = root.right\n return None", "def inorderSuccessor(root, x):\n res = None\n while root is not None:\n if root.data == x.data:\n break\n elif root.data < x.data:\n root = root.right\n else:\n res = root\n root = root.left\n root = root.right\n while root is not None and root.left is not None:\n root = root.left\n if root is None:\n return res\n return root", "def inorderSuccessor(root, n):\n t = None\n while root != None:\n if n.data < root.data:\n t = root\n root = root.left\n else:\n root = root.right\n return t", "def inorderSuccessor(root, x):\n l = []\n self.inorder(root, l, x)\n if len(l) > 1:\n return l[-1]\n else:\n return\n\ndef inorder(root, l, x):\n if not root:\n return\n self.inorder(root.left, l, x)\n if len(l) == 1:\n l.append(root)\n return\n if root.data == x.data:\n l.append(root)\n self.inorder(root.right, l, x)", "def inorderSuccessor(root, x):\n if not root or not x:\n return None\n succ = None\n v = root\n while v:\n if v.data <= x.data:\n v = v.right\n else:\n succ = v\n v = v.left\n return succ", "def left(root):\n if root.left is None:\n return root\n return self.left(root.left)\n\ndef inorder(root, x):\n if root is None:\n return None\n if root.data == x.data:\n if root.right is not None:\n return self.left(root.right)\n return None\n if root.data > x.data:\n result = self.inorder(root.left, x)\n if result is None:\n return root\n return result\n else:\n result = self.inorder(root.right, x)\n return result\n\ndef inorderSuccessor(root, x):\n return self.inorder(root, x)", "def innorder(root):\n if not root:\n return []\n return innorder(root.left) + [root] + innorder(root.right)\n\ndef __init__(val, k):\n self.right = None\n self.data = val\n self.left = None\n self.key = k\n\ndef inorderSuccessor(root, x):\n a = innorder(root)\n for i in range(len(a) - 1):\n if a[i].data == x.data:\n return a[i + 1]", "def inorderSuccessor(root, x):\n\n def inorder(tree, arr):\n if tree is not None:\n inorder(tree.left, arr)\n arr.append(tree)\n inorder(tree.right, arr)\n return arr\n array = inorder(root, [])\n for i in range(len(array)):\n if array[i].data == x.data and i + 1 < len(array):\n return array[i + 1]\n return", "def inorderSuccessor(root, x):\n re = []\n\n def trav(rot):\n if rot.left is not None:\n trav(rot.left)\n re.append(rot)\n if rot.right is not None:\n trav(rot.right)\n trav(root)\n for i in range(len(re)):\n if re[i].data == k:\n if i + 1 < len(re):\n return re[i + 1]", "def inorderSuccessor(root, x):\n self.ans = None\n\n def helper(root, x):\n if root is None:\n return\n if root.data <= x.data:\n helper(root.right, x)\n else:\n if self.ans is None:\n self.ans = root\n else:\n self.ans = min((root, self.ans), key=lambda m: m.data)\n helper(root.left, x)\n helper(root, x)\n return self.ans", "def inorderSuccessor(root, x):\n (self.ans, self.x) = (None, False)\n\n def helper(root, x):\n if root is None:\n return\n helper(root.left, x)\n if self.x and self.ans is None:\n self.ans = root\n return\n if root.data == x.data:\n self.x = True\n helper(root.right, x)\n helper(root, x)\n return self.ans", "def inorderSuccessor(root, x):\n curr = root\n succ = 999989\n while curr:\n if curr.data > x.data:\n succ = curr.data\n curr = curr.left\n elif curr.data <= x.data:\n curr = curr.right\n if succ == 999989:\n return Node(-1)\n return Node(succ)", "def inorderSuccessor(root, x):\n succ = None\n temp = x.data\n while True:\n if root == None:\n return succ\n elif root.data > temp:\n succ = root\n root = root.left\n else:\n root = root.right", "import sys\n\ndef inorderSuccessor(root, x):\n ans = None\n while root:\n if root.data <= x.data:\n root = root.right\n else:\n ans = root\n root = root.left\n return ans", "import sys\n\ndef inorderSuccessor(root, x):\n arr_inorder = []\n\n def inorder(r):\n nonlocal arr_inorder\n if not r:\n return\n inorder(r.left)\n arr_inorder.append(r)\n inorder(r.right)\n inorder(root)\n for i in range(len(arr_inorder)):\n if arr_inorder[i].data == x.data:\n return None if i + 1 >= len(arr_inorder) else arr_inorder[i + 1]\n return None", "def inorderSuccessor(root, x):\n\n def vamsi(root, x, ans):\n if not root:\n return None\n vamsi(root.left, x, ans)\n if x.data < root.data:\n ans.append(root.data)\n return\n vamsi(root.right, x, ans)\n ans = []\n vamsi(root, x, ans)\n return Node(ans[0]) if len(ans) > 0 else None", "def inorderSuccessor(root, x):\n succ = Node(-1)\n while root:\n if x.data >= root.data:\n root = root.right\n else:\n succ = root\n root = root.left\n return succ", "def inorderSuccessor(root, x):\n b = []\n c = []\n Solution.bst(root, b, c)\n if x.data in b:\n if b.index(x.data) >= len(b) - 1:\n return None\n return c[b.index(x.data) + 1]\n return None\n\ndef bst(root, x, y):\n if root.left:\n Solution.bst(root.left, x, y)\n x.append(root.data)\n y.append(root)\n if root.right:\n Solution.bst(root.right, x, y)", "def inorderSuccessor(root, x):\n self.successor = None\n\n def helper(root, x):\n if root == None:\n return\n if root.data == x:\n helper(root.right, x)\n elif root.data > x:\n self.successor = root\n helper(root.left, x)\n else:\n helper(root.right, x)\n helper(root, x.data)\n return self.successor", "def solve(root, x, suc, first):\n if root is None:\n return\n self.solve(root.left, x, suc, first)\n if len(suc) == 1:\n suc.append(root)\n return\n if root.data == x.data:\n suc.append(root)\n self.solve(root.right, x, suc, first)\n return suc\n\ndef inorderSuccessor(root, x):\n first = None\n suc = []\n self.solve(root, x, suc, first)\n if len(suc) > 1:\n return suc[-1]\n else:\n return", "def inorderSuccessor(root, x):\n l = []\n\n def inorder(root):\n if root is not None:\n inorder(root.left)\n l.append(root.data)\n inorder(root.right)\n inorder(root)\n m = x.data\n s = l.index(m)\n if m == l[-1]:\n return Node(-1)\n return Node(l[s + 1])", "def inorderSuccessor(root, x):\n self.suc = None\n\n def find(node):\n if node:\n find(node.left)\n if node.data > x.data and self.suc == None:\n self.suc = node\n find(node.right)\n find(root)\n return self.suc", "def __init__():\n self.ans = None\n\ndef inorderSuccessor(root, x):\n if not root:\n return self.ans\n if x.data >= root.data:\n return self.inorderSuccessor(root.right, x)\n if x.data < root.data:\n self.ans = root\n return self.inorderSuccessor(root.left, x)", "def inorderSuccessor(root, x):\n x = self.findNode(root, x)\n if x == -1:\n return None\n elif x.right:\n curr = x.right\n while curr:\n if not curr.left:\n break\n curr = curr.left\n return curr\n else:\n succ = None\n while root:\n if root.data < x.data:\n root = root.right\n elif root.data > x.data:\n succ = root\n root = root.left\n else:\n break\n return succ\n\ndef findNode(root, node):\n curr = root\n while curr:\n if curr.data < node.data:\n curr = curr.right\n elif curr.data > node.data:\n curr = curr.left\n else:\n return curr\n return -1", "def inorderSuccessor(root, x):\n (curr, nextBiggest) = (root, None)\n while curr:\n if curr.data <= x.data:\n curr = curr.right\n else:\n nextBiggest = curr\n curr = curr.left\n return nextBiggest", "def inorderSuccessor(root, x):\n ans = None\n\n def findNode(node):\n nonlocal ans\n if not node:\n return\n if node.data > x.data:\n ans = node\n return findNode(node.left)\n elif node.data < x.data:\n return findNode(node.right)\n else:\n return node\n node = findNode(root)\n if not node:\n return None\n\n def successor(node):\n if not node:\n return None\n if node.left:\n return successor(node.left)\n else:\n return node\n inter = successor(node.right)\n if not inter or inter.data < 0:\n return ans\n return inter", "def inorderSuccessor(root, x):\n currentNode = root\n if currentNode is None:\n return None\n while currentNode is not None:\n if currentNode.data == x.data:\n break\n elif currentNode.data > x.data:\n currentNode = currentNode.left\n else:\n currentNode = currentNode.right\n if currentNode.right is not None:\n successorNode = currentNode.right\n while successorNode.left is not None:\n successorNode = successorNode.left\n return successorNode\n successorNode = None\n ancestorNode = root\n while currentNode != ancestorNode:\n if currentNode.data < ancestorNode.data:\n successorNode = ancestorNode\n ancestorNode = ancestorNode.left\n else:\n ancestorNode = ancestorNode.right\n return successorNode", "def inorderSuccessor(root, x):\n curr = root\n while curr.data != x.data and curr:\n if x.data < curr.data:\n curr = curr.left\n if x.data > curr.data:\n curr = curr.right\n if curr is None:\n return -1\n ptr = curr\n if curr.right:\n curr = curr.right\n while curr.left:\n curr = curr.left\n return curr\n else:\n succ = Node(-1)\n while root:\n if root.data < x.data:\n root = root.right\n elif root.data > x.data:\n succ = root\n root = root.left\n else:\n break\n return succ", "def inorderSuccessor(root, X):\n if root is None or X is None:\n return None\n succ = None\n while root is not None:\n if root.data <= X.data:\n root = root.right\n else:\n succ = root\n root = root.left\n return succ", "def inorderSuccessor(root, x):\n inorder = []\n\n def fun(root, x):\n if root:\n fun(root.left, x)\n inorder.append(root.data)\n fun(root.right, x)\n fun(root, x)\n for i in range(0, len(inorder)):\n if inorder[i] == x.data:\n if i < len(inorder) - 1:\n return Node(inorder[i + 1])\n else:\n return None\n return None", "def inorderSuccessor(root, x):\n if not root:\n return None\n curr = root\n stack = []\n flag = False\n while True:\n if curr is not None:\n stack.append(curr)\n curr = curr.left\n elif stack:\n if flag:\n return stack.pop()\n curr = stack.pop()\n if curr.data == x.data:\n flag = True\n curr = curr.right\n else:\n return None", "def inorderSuccessor(root, x):\n stack = [root]\n num = float('inf')\n if root.data > x.data:\n num = root.data\n save_node = root\n while len(stack) != 0:\n node = stack.pop()\n l = node.left\n r = node.right\n if l:\n stack.append(l)\n if x.data < l.data and num > l.data:\n num = l.data\n save_node = l\n if r:\n stack.append(r)\n if x.data < r.data and num > r.data:\n num = r.data\n save_node = r\n if num == float('inf'):\n return None\n else:\n return save_node", "def inorderSuccessor(root, x):\n s = []\n t1 = Node(None)\n while 1:\n if root is not None:\n s.append(root)\n root = root.left\n elif s:\n t = s.pop()\n if t1.data == x.data:\n return t\n else:\n t1 = t\n root = t.right\n else:\n break\n return None", "def inOr(root, arr, x, c):\n if not root:\n return\n self.inOr(root.left, arr, x, c)\n arr.append(root)\n if root.data == x.data:\n c = c + 1\n self.inOr(root.right, arr, x, c)\n\ndef inorderSuccessor(root, x):\n arr = []\n self.inOr(root, arr, x, 0)\n i = 0\n for e in arr:\n if x.data == e.data:\n if i == len(arr) - 1:\n return None\n return arr[i + 1]\n i = i + 1", "def inorderSuccessor(root, x):\n curr = root\n stack = []\n while curr or stack:\n while curr:\n stack.append(curr)\n curr = curr.left\n curr = stack.pop()\n if curr.data == x.data:\n if curr.right:\n curr = curr.right\n while curr.left:\n curr = curr.left\n return curr\n elif stack:\n return stack.pop()\n else:\n return None\n curr = curr.right\n return None", "def inorderSuccessor(root, x):\n\n def helper(node, x, succ):\n if not node:\n return\n helper(node.left, x, succ)\n if node.data > x.data and (not succ.left):\n succ.left = node\n return\n helper(node.right, x, succ)\n if not root:\n return None\n succ = Node(0)\n helper(root, x, succ)\n return succ.left", "def inorderSuccessor(root, x):\n if not root:\n return None\n stack = []\n prev = 0\n while stack or root:\n while root:\n stack.append(root)\n root = root.left\n node = stack.pop()\n if prev == x.data:\n return node\n prev = node.data\n root = node.right\n return None", "def inorderSuccessor(root, x):\n\n def inorder(List, root):\n if not root:\n return\n inorder(List, root.left)\n List.append(root.data)\n inorder(List, root.right)\n List = []\n inorder(List, root)\n if x.data in List:\n I = List.index(x.data)\n else:\n return None\n if I < len(List) - 1:\n return Node(List[I + 1])\n else:\n return None", "def inorderSuccessor(root, x):\n arr = []\n\n def inorder(node):\n if not node:\n return\n inorder(node.left)\n arr.append(node.data)\n inorder(node.right)\n inorder(root)\n for i in range(0, len(arr)):\n if arr[i] > x.data:\n return Node(arr[i])", "def inorderSuccessor(root, x):\n\n def inorder(node):\n if node == None:\n return []\n else:\n return inorder(node.left) + [node.data] + inorder(node.right)\n l = inorder(root)\n ans = None\n for i in range(len(l)):\n if l[i] == x.data:\n if i == len(l) - 1:\n return None\n ans = l[i + 1]\n break\n\n def search(node, ans):\n if node == None:\n return\n if node.data < ans:\n return search(node.right, ans)\n elif node.data > ans:\n return search(node.left, ans)\n else:\n return node\n return search(root, ans)", "def inorderSuccessor(root, x):\n l = []\n\n def search(node, ans):\n l.append(node)\n if node == None:\n return\n if node.data < ans:\n return search(node.right, ans)\n elif node.data > ans:\n return search(node.left, ans)\n else:\n return node\n se = search(root, x.data)\n if se.right != None:\n temp = se.right\n while temp.left:\n temp = temp.left\n l.append(temp)\n mini = 99999999999999999999999\n ans = None\n for i in l:\n if i.data > x.data and i.data < mini:\n mini = i.data\n ans = i\n return ans", "import sys\n\ndef inorderSuccessor(root, x):\n maxi = [sys.maxsize]\n self.f(root, x, maxi)\n if maxi[0] == sys.maxsize:\n return None\n else:\n return Node(maxi[0])\n\ndef f(root, x, maxi):\n if root == None:\n return\n if x.data >= root.data:\n self.f(root.right, x, maxi)\n else:\n maxi[0] = min(maxi[0], root.data)\n self.f(root.left, x, maxi)", "def inorderSuccessor(root, x):\n self.a = list()\n new = Node(-1)\n\n def postorder(root, x):\n if root == None:\n return -1\n postorder(root.left, x)\n self.a.append(root.data)\n postorder(root.right, x)\n return self.a\n postorder(root, x)\n for i in range(len(self.a) - 1):\n if self.a[i] == x.data:\n new = Node(self.a[i + 1])\n break\n return new", "def inorderSuccessor(root, x):\n suc = None\n while root:\n if root.data <= x.data:\n root = root.right\n elif root.data > x.data:\n suc = root\n root = root.left\n return suc", "def inorderSuccessor(root, x):\n\n def f(r, x, s):\n if r == None:\n return s\n elif r.data <= x.data:\n return f(r.right, x, s)\n else:\n s = r\n return f(r.left, x, s)\n ans = f(root, x, None)\n return ans", "def inorder(root, A, tgt):\n if not root:\n return\n self.inorder(root.left, A, tgt)\n A.append(root)\n if root.data == tgt[0]:\n tgt[1] = len(A) - 1\n self.inorder(root.right, A, tgt)\n\ndef inorderSuccessor(root, x):\n tgt = [x.data, -1]\n path = []\n self.inorder(root, path, tgt)\n if tgt[1] + 1 >= len(path):\n return None\n return path[tgt[1] + 1]", "def inorderSuccessor(root, x):\n if root:\n self.inorderSuccessor(root.left, x)\n if self._found:\n self._successor = root\n self._found = False\n if root.data == x.data:\n self._found = True\n self.inorderSuccessor(root.right, x)\n return self._successor", "def inorderSuccessor(root, x):\n\n def inorderTraverse(root, ans):\n if root:\n inorderTraverse(root.left, ans)\n ans.append(root)\n inorderTraverse(root.right, ans)\n return ans\n test = inorderTraverse(root, [])\n smallest = 999999999\n start = False\n node = Node(-1)\n for item in test:\n if item.data == x.data:\n start = True\n if start:\n if item.data != 'N' and x.data < item.data < smallest:\n smallest = item.data\n node = item\n return node"], "starter_code": "def __init__(val, k):\n", "input_output": {"inputs": ["2\n / \\\n 1 3\nK(data of x) = 2", "20\n / \\\n 8 22\n / \\\n 4 12\n / \\\n 10 14\nK(data of x) = 8"], "outputs": ["3", "10"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Binary Search Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Range queries"], "skill_types": ["Data structures", "Range queries"], "url": "https://practice.geeksforgeeks.org/problems/inorder-successor-in-bst/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(Height of the BST).", "entry_point": "__init__", "task_id": "TACO_lite/261", "example": [[], []]} +{"requirement": "Given an array nums[] of N positive integers. Find the minimum number of operations required to modify the array such that array elements are in strictly increasing order (A[i] < A[i+1]).\nChanging a number to greater or lesser than original number is counted as one operation.\nExample 1:\nInput: nums[] = [1, 2, 3, 6, 5, 4]\nOutput: 2\nExplanation: By decreasing 6 by 2 and\nincreasing 4 by 2, arr will be like\n[1, 2, 3, 4, 5, 6] which is stricly \nincreasing.\nExample 2:\nInput: nums[] = [1, 2, 3, 4]\nOutput: 0\nExplanation: Arrays is already strictly\nincreasing.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function min_opeartions() which takes the array nums[] as input parameter and returns the minimum number of opeartion needed to make the array strictly increasing.\n \nExpected Time Complexity: O(n^2)\nExpected Space Complexity: O(n)\n \nConstraints: \n1 <= length of array <= 1000\n1 <= arr[i] <= 1000000", "solutions": ["from bisect import bisect_right\n\ndef min_operations(nums):\n for i in range(len(nums)):\n nums[i] -= i\n lis = []\n for i in range(len(nums)):\n pos = bisect_right(lis, nums[i])\n if pos == len(lis):\n lis.append(nums[i])\n else:\n lis[pos] = nums[i]\n return len(nums) - len(lis)", "def min_operations(nums):\n N = len(nums)\n dp = [1] * N\n for i in range(1, N):\n for j in range(i):\n if nums[i] - nums[j] >= i - j:\n dp[i] = max(dp[i], dp[j] + 1)\n return N - max(dp)", "def min_operations(a):\n n = len(a)\n dp = [1] * n\n for i in range(n):\n for j in range(i):\n if a[i] > a[j] and a[i] - a[j] >= i - j:\n dp[i] = max(dp[i], dp[j] + 1)\n return n - max(dp)", "def min_operations(nums):\n n = len(nums)\n dp = [1] * n\n ans = 1\n for i in range(1, n):\n maxi = 0\n for j in range(i):\n if nums[j] + (i - j) <= nums[i]:\n maxi = max(maxi, dp[j])\n dp[i] = 1 + maxi\n ans = max(ans, dp[i])\n return n - ans", "def LIS(arr, n):\n res = [1] * n\n for i in range(1, n):\n for j in range(i):\n if arr[j] < arr[i] and arr[i] - arr[j] >= i - j:\n res[i] = max(res[i], res[j] + 1)\n return res\n\ndef min_operations(nums):\n n = len(nums)\n lis = self.LIS(nums, n)\n return n - max(lis)", "def min_operations(arr):\n n = len(arr)\n if n == 1:\n return 0\n LIS = [0 for i in range(n)]\n le = 0\n for i in range(n):\n LIS[i] = 1\n for i in range(1, n):\n for j in range(i):\n if arr[i] > arr[j] and i - j <= arr[i] - arr[j]:\n LIS[i] = max(LIS[i], LIS[j] + 1)\n le = max(le, LIS[i])\n return n - le", "from math import inf\n\ndef min_operations(x):\n l = len(x)\n\n def f(i, p):\n if i == l:\n return 0\n if (i, p) in dp:\n return dp[i, p]\n ans = 1 + f(i + 1, p + 1)\n if x[i] > p:\n ans = min(ans, f(i + 1, x[i]))\n dp[i, p] = ans\n return ans\n dp = {}\n return min(f(1, x[0]), 1 + f(1, -10 ** 8))", "from bisect import *\n\ndef min_operations(nums):\n\n def lis(arr):\n n = len(arr)\n lis = [1] * n\n for i in range(1, n):\n for j in range(0, i):\n if arr[i] >= arr[j] + (i - j) and lis[i] < lis[j] + 1:\n lis[i] = lis[j] + 1\n maximum = 0\n for i in range(n):\n maximum = max(maximum, lis[i])\n return maximum\n l = lis(nums)\n n = len(nums)\n return n - l", "def min_operations(nums):\n arr = nums\n l = len(arr)\n if l == 1:\n return 0\n LIS = [0 for i in range(l)]\n lent = 0\n for i in range(l):\n LIS[i] = 1\n for i in range(1, l):\n for j in range(i):\n if arr[i] > arr[j] and i - j <= arr[i] - arr[j]:\n LIS[i] = max(LIS[i], LIS[j] + 1)\n lent = max(lent, LIS[i])\n return l - lent", "def min_operations(nums):\n dp = [1 for i in range(len(nums))]\n maxi = 1\n for i in range(len(nums)):\n for prev in range(i):\n if nums[prev] < nums[i] and i - prev <= nums[i] - nums[prev] and (1 + dp[prev] > dp[i]):\n dp[i] = 1 + dp[prev]\n if maxi < dp[i]:\n maxi = dp[i]\n return len(nums) - maxi", "def min_operations(nums):\n n = len(nums)\n ans = 1\n lis = [1 for i in range(n)]\n for i in range(1, n):\n for j in range(i):\n if nums[i] > nums[j] and i - j <= nums[i] - nums[j]:\n lis[i] = max(lis[i], lis[j] + 1)\n ans = max(ans, lis[i])\n return n - ans", "def min_operations(nums):\n N = len(nums)\n soln = [1] * N\n for i in range(1, N):\n for j in range(0, i):\n if nums[i] > nums[j] and i - j <= nums[i] - nums[j]:\n soln[i] = max(soln[i], 1 + soln[j])\n return N - max(soln)", "from bisect import bisect_left\n\ndef min_operations(arr):\n l = 1\n n = len(arr)\n dp = [1] * n\n for i in range(1, n):\n m = 1\n for j in range(i):\n if arr[j] < arr[i] and i - j <= arr[i] - arr[j] and (dp[j] + 1 > m):\n m = dp[j] + 1\n dp[i] = m\n if l < m:\n l = m\n return n - l", "def bsearch(arr, num):\n (l, r) = (0, len(arr) - 1)\n while r - l > 1:\n mid = (l + r) // 2\n if arr[mid] == num:\n l = mid\n elif arr[mid] > num:\n r = mid\n else:\n l = mid\n if num == arr[r]:\n return r + 1\n if num == arr[l]:\n return l + 1\n if num > arr[r]:\n return r + 1\n if num < arr[l]:\n return l\n return r\n\ndef lengthOfLIS(nums):\n if not nums:\n return 0\n store = [nums[0]]\n for num in nums[1:]:\n idx = self.bsearch(store, num)\n if idx == len(store):\n store.append(num)\n else:\n store[idx] = num\n return len(store)\n\ndef min_operations(nums):\n n = len(nums)\n new_nums = [nums[i] - i for i in range(n)]\n l = self.lengthOfLIS(new_nums)\n return n - l", "import heapq\n\ndef mod(nums):\n n = len(nums)\n dp = [-1 for i in range(n)]\n dp[0] = 1\n for i in range(1, n):\n dp[i] = 1\n for j in range(i - 1, -1, -1):\n if nums[i] <= nums[j]:\n continue\n if i - j <= nums[i] - nums[j]:\n dp[i] = max(dp[i], 1 + dp[j])\n return max(dp)\n\ndef min_operations(nums):\n return len(nums) - Solution.mod(nums)", "def min_operations(nums):\n if len(nums) == 1:\n return 0\n lis = [1 for i in range(len(nums))]\n max1 = 0\n for i in range(1, len(nums)):\n for j in range(0, i):\n if nums[i] > nums[j] and i - j <= nums[i] - nums[j]:\n lis[i] = max(lis[i], lis[j] + 1)\n max1 = max(max1, lis[i])\n return len(nums) - max1", "def min_operations(nums):\n n = len(nums)\n LIS = [0 for i in range(n)]\n z = 0\n for i in range(n):\n LIS[i] = 1\n for i in range(1, n):\n for j in range(i):\n if nums[i] > nums[j] and i - j <= nums[i] - nums[j]:\n LIS[i] = max(LIS[i], LIS[j] + 1)\n z = max(z, LIS[i])\n if n == 1:\n return 0\n return n - z", "def SIA(arr):\n dp = [1 for i in arr]\n for i in range(1, len(arr)):\n for j in range(i):\n if arr[i] > arr[j] and i - j <= arr[i] - arr[j]:\n dp[i] = max(dp[i], 1 + dp[j])\n return len(arr) - max(dp)\n\ndef min_operations(nums):\n return SIA(nums)", "def min_operations(nums):\n arr = nums.copy()\n n = len(nums)\n LIS = [0 for i in range(n)]\n len1 = 0\n for i in range(n):\n LIS[i] = 1\n for i in range(1, n):\n for j in range(i):\n if arr[i] > arr[j] and i - j <= arr[i] - arr[j]:\n LIS[i] = max(LIS[i], LIS[j] + 1)\n return n - max(LIS)"], "starter_code": "def min_operations(nums):\n", "input_output": {"inputs": ["nums[] = [1, 2, 3, 6, 5, 4]", "nums[] = [1, 2, 3, 4]"], "outputs": ["2", "0"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/convert-to-strictly-increasing-array3351/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n^2)", "entry_point": "min_operations", "task_id": "TACO_lite/394", "example": [[[[1, 2, 3, 6, 5, 4]], [[1, 2, 3, 4]]], ["2", "0"]]} +{"requirement": "Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.\n\nExample 1:\n\nInput: 5\nOutput: True\nExplanation:\nThe binary representation of 5 is: 101\n\n\n\nExample 2:\n\nInput: 7\nOutput: False\nExplanation:\nThe binary representation of 7 is: 111.\n\n\n\nExample 3:\n\nInput: 11\nOutput: False\nExplanation:\nThe binary representation of 11 is: 1011.\n\n\n\nExample 4:\n\nInput: 10\nOutput: True\nExplanation:\nThe binary representation of 10 is: 1010.", "solutions": ["def hasalternatingbits(n):\n if n % 2 == 0:\n n = n >> 1\n cnt = 0\n a = n\n while a > 0:\n cnt += 1\n a = a >> 1\n if cnt % 2 == 0:\n return False\n c = 1\n for i in range(1, cnt):\n c = c << 1\n if i % 2 == 0:\n c += 1\n return c == n", "def hasalternatingbits(n):\n before = None\n while n != 0:\n d = n % 2\n if not before:\n before = d + 1\n else:\n if before == d + 1:\n return False\n before = d + 1\n n = n >> 1\n return True", "def hasalternatingbits(n):\n res = []\n while n > 0:\n res.append(str(n % 2))\n n //= 2\n for i in range(1, len(res)):\n if res[i] == res[i - 1]:\n return False\n return True", "def hasalternatingbits(n):\n prev = n % 2\n n = n // 2\n while n > 0:\n now = n % 2\n if now == prev:\n return False\n n = n // 2\n prev = now\n return True", "def hasalternatingbits(n):\n return '00' not in bin(n) and '11' not in bin(n)", "def hasalternatingbits(n):\n i = n % 2\n while n > 0:\n if i % 2 == 0:\n n /= 2\n else:\n n = (n - 1) / 2\n i += 1\n return n == 0", "def hasalternatingbits(n):\n bin1 = str(bin(n)[2:])\n length = len(bin1)\n for i in range(0, length - 1):\n if bin1[i] == bin1[i + 1]:\n return False\n return True", "def hasalternatingbits(n):\n bits = bin(n)\n return all((bits[i] != bits[i + 1] for i in range(len(bin(n)) - 1)))", "def hasalternatingbits(n):\n prev = None\n while n:\n curr = n % 2\n if curr == prev:\n return False\n prev = curr\n n //= 2\n return True"], "starter_code": "def hasalternatingbits(n: int) -> bool:\n", "input_output": {"fn_name": "hasAlternatingBits", "inputs": [[5]], "outputs": [true]}, "difficulty": "EASY", "raw_tags": ["Bit Manipulation"], "name": null, "source": "leetcode", "tags": ["Bit manipulation"], "skill_types": ["Bit manipulation"], "url": "https://leetcode.com/problems/binary-number-with-alternating-bits/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "hasalternatingbits", "task_id": "TACO_lite/367", "example": [[[5], [7], [11], [10]], ["True", "False", "False", "True"]]} +{"requirement": "Given a number N. Check whether N is a Twisted Prime number or not.\nNote: A number is called Twisted Prime if it is a prime and its reverse is also a prime.\nExample 1:\nInput: N = 97\nOutput: 1\nExplanation: 97 is a prime number. Its \nreverse 79 isalso a prime number. Thus \n97 is a twisted Prime and so, answer is 1.\nExample 2:\nInput: N = 43\nOutput: 0\nExplanation: 43 is a prime number but its \nreverse 34 is not a prime.So, 43 is not a \ntwisted prime and thus, answer is 0.\nYour Task:You don't need to read input or print anything.Your task is to complete the function isTwistedPrime() which takes a number N as input parameter and returns 1 if it is a twisted prime number.Otherwise, it returns 0.\nExpected Time Complexity:(O(sqrt(max(N,RevN))), here RevN is the reverse of N.\nExpected Space Complexity:O(1)\nConstraints:\n1<=N<=10^{9}", "solutions": ["import math\n\ndef fun(n):\n if n == 0 or n == 1:\n return False\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\ndef istwistedprime(N):\n s = str(N)\n s = s[::-1]\n if fun(N) and fun(int(s)):\n return 1\n return 0", "def istwistedprime(N):\n flag = 1\n for i in range(2, int(N ** 0.5) + 1):\n if N % i == 0:\n flag = 0\n break\n flag = 1\n x = str(N)\n x = x[::-1]\n x = int(x)\n flag1 = 1\n for i in range(2, int(x ** 0.5) + 1):\n if x % i == 0:\n flag1 = 0\n break\n flag1 = 1\n if flag == 1 and flag1 == 1:\n return 1\n return 0", "from math import sqrt\n\ndef istwistedprime(N):\n flag1 = self.prime(N)\n rev = self.reverse(N)\n flag2 = self.prime(rev)\n if flag1 and flag2:\n return 1\n return 0\n\ndef prime(N):\n for i in range(2, int(sqrt(N)) + 1):\n if N % i == 0:\n return False\n return True\n\ndef reverse(N):\n rev = 0\n while N:\n rev = rev * 10\n digit = N % 10\n rev += digit\n N //= 10\n return rev", "import math as m\n\ndef istwistedprime(N):\n\n def prime(n):\n if n == 0 or n == 1:\n return False\n k = round(m.sqrt(n)) + 1\n for i in range(2, k):\n if n % i == 0:\n return False\n return True\n k = str(N)\n if prime(N) == True and prime(int(k[::-1])) == True:\n return 1\n return 0", "import math\n\ndef is_prime(n):\n if n == 1:\n return False\n elif n == 2:\n return True\n elif n % 2 == 0:\n return False\n else:\n for x in range(3, int(math.sqrt(n)) + 1, 2):\n if n % x == 0:\n return False\n break\n return True\n\ndef istwistedprime(N):\n x = str(N)\n y = int(x[::-1])\n if is_prime(N) == True & is_prime(y) == True:\n return 1\n return 0", "def istwistedprime(N):\n\n def prime(n):\n if n == 0 or n == 1:\n return 0\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return 0\n return 1\n x = int(str(N)[::-1])\n if prime(N) == 1 and prime(x) == 1:\n return 1\n return 0", "from math import sqrt\n\ndef isPrime(n):\n if n <= 1 or n % 2 == 0:\n return 0\n if n == 2 or n == 3:\n return 1\n for i in range(3, int(sqrt(n)) + 1, 2):\n if n % i == 0:\n return 0\n return 1\n\ndef istwistedprime(N):\n return self.isPrime(N) and self.isPrime(int(str(N)[::-1]))", "import math\n\ndef isPrime(n):\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return 0\n return 1\n\ndef istwistedprime(N):\n flag = self.isPrime(N)\n strr = str(N)\n strr = strr[::-1]\n N = int(strr)\n flag1 = self.isPrime(N)\n return 1 if flag == 1 and flag1 == 1 else 0", "import math\n\ndef istwistedprime(N):\n a = str(N)\n a = a[::-1]\n a = int(a)\n for i in range(2, int(math.sqrt(N)) + 1):\n if N % i == 0:\n return 0\n for i in range(2, int(math.sqrt(a)) + 1):\n if a % i == 0:\n return 0\n return 1", "def istwistedprime(N):\n s = str(N)\n s = s[::-1]\n s = int(s)\n for i in range(2, int(N ** 0.5) + 1):\n if N % i == 0:\n return 0\n for i in range(2, int(s ** 0.5) + 1):\n if s % i == 0:\n return 0\n return 1", "from math import sqrt\n\ndef istwistedprime(N):\n revno = int(str(N)[::-1])\n if self.prime(N) and self.prime(revno):\n return 1\n return 0\n\ndef prime(N):\n for i in range(2, int(sqrt(N)) + 1):\n if N % i == 0:\n return False\n return True", "def istwistedprime(N: int) -> int:\n\n def reverse(n: int) -> int:\n return int(str(N)[::-1])\n\n def is_prime(n: int) -> bool:\n if n < 2:\n return False\n else:\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n condition1 = is_prime(N)\n condition2 = is_prime(reverse(N))\n if condition1 and condition2:\n return 1\n else:\n return 0", "def istwistedprime(N):\n\n def h(n):\n if n == 0 or n == 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n if h(N) and h(int(str(N)[::-1])):\n return 1\n return 0", "def istwistedprime(N):\n\n def prime(n):\n if n == 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n if prime(N) and prime(int(str(N)[::-1])):\n return 1\n else:\n return 0", "def istwistedprime(N):\n\n def isPrime(num):\n if num < 2:\n return 0\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return 0\n return 1\n if isPrime(N) == 0:\n return 0\n r = ''\n while N > 0:\n r += str(N % 10)\n N = N // 10\n if isPrime(int(r)) == 0:\n return 0\n return 1", "import math\n\ndef istwistedprime(N):\n reversedString = str(N)[::-1]\n reversedNumber = int(reversedString)\n s = max(N, reversedNumber)\n s = int(math.sqrt(s))\n for i in range(2, s + 1):\n if N % i == 0:\n return 0\n if reversedNumber % i == 0:\n return 0\n return 1", "def istwistedprime(N):\n if N == 1 or N == 10:\n return 0\n import math\n a = str(N)\n a = a[::-1]\n a = int(a)\n s = max(N, a)\n s = int(math.sqrt(s))\n for i in range(2, s + 1):\n if N % i == 0:\n return 0\n if a % i == 0:\n return 0\n return 1", "def istwistedprime(N):\n\n def is_prime(n):\n if n <= 1:\n return False\n elif n > 1:\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n a = N\n b = int(str(N)[::-1])\n if is_prime(a):\n if is_prime(b):\n return 1\n return 0", "import math\n\ndef istwistedprime(N):\n\n def prime(N):\n a = 0\n if N < 2:\n return 0\n elif N == 2 or N == 3 or N == 5 or (N == 7) or (N == 11):\n return 1\n elif N % 2 == 0 or N % 3 == 0 or N % 5 == 0 or (N % 7 == 0) or (N % 11 == 0):\n return 0\n else:\n i = 5\n while i * i <= N:\n if N % i == 0 or N % (i + 2) == 0:\n return 0\n i = i + 6\n return 1\n n = N\n f = prime(N)\n sum = 0\n while n > 0:\n e = n % 10\n sum = sum * 10 + e\n n = n // 10\n c = prime(sum)\n if c == 1 and f == 1:\n return 1\n else:\n return 0", "def istwistedprime(N):\n p = 0\n import math\n for i in range(2, int(math.sqrt(N)) + 1):\n if N % i == 0:\n p = 1\n break\n if p == 0:\n N = str(N)\n N = N[::-1]\n n = int(N)\n p = 0\n import math\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n p = 1\n break\n if p == 0:\n return 1\n return 0", "def istwistedprime(N):\n if N == 1:\n return 0\n else:\n for i in range(2, int(N ** 0.5) + 1):\n if N % i == 0:\n return 0\n break\n else:\n s = str(N)\n p = int(s[-1:-len(s) - 1:-1])\n for i in range(2, int(p ** 0.5) + 1):\n if p % i == 0:\n return 0\n break\n else:\n return 1", "import math\n\ndef istwistedprime(N):\n n = N\n nr = int(str(n)[::-1])\n for i in range(2, math.ceil(math.sqrt(n)) + 1):\n if n % i == 0:\n return 0\n for i in range(2, math.ceil(math.sqrt(nr)) + 1):\n if nr % i == 0:\n return 0\n return 1", "from math import sqrt\n\ndef isPrime(num):\n flag = True\n for i in range(2, int(sqrt(num)) + 1):\n if num % i == 0:\n flag = False\n break\n return flag\n\ndef reverseNumber(n):\n ans = 0\n while n != 0:\n digit = n % 10\n ans = ans * 10 + digit\n n = n // 10\n return ans\n\ndef istwistedprime(N):\n reversenum = reverseNumber(N)\n if isPrime(N) and isPrime(reversenum):\n return 1\n else:\n return 0", "def istwistedprime(N):\n\n def prime(n):\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return 0\n else:\n return 1\n if prime(N):\n r = 0\n while N:\n d = N % 10\n r = r * 10 + d\n N = N // 10\n if prime(r):\n return 1\n else:\n return 0\n else:\n return 0", "def isPrime(n):\n if n == 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef reverse(n):\n rev_num = 0\n while n > 0:\n rem = n % 10\n rev_num = rev_num * 10 + rem\n n = n // 10\n return rev_num\n\ndef istwistedprime(N):\n rev_n = reverse(N)\n if isPrime(N) and isPrime(rev_n):\n return 1\n else:\n return 0", "import math\n\ndef istwistedprime(N):\n\n def isprime(x):\n c = 0\n for i in range(2, int(math.sqrt(x)) + 1):\n if x % i == 0:\n c = 1\n break\n if c == 0:\n return 1\n else:\n return 0\n x1 = isprime(N)\n x2 = str(N)\n x2 = x2[::-1]\n x3 = isprime(int(x2))\n if x1 == 1 and x3 == 1:\n return 1\n else:\n return 0", "def isprime(n):\n if n == 1 or n == 0:\n return 0\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return 0\n return 1\n\ndef rev(n):\n n1 = str(n)\n n1 = n1[::-1]\n n2 = int(n1)\n return n2\n\ndef istwistedprime(N):\n if isprime(N) == 1 and isprime(rev(N)) == 1:\n return 1\n else:\n return 0", "from math import sqrt\n\ndef istwistedprime(N):\n N_rev = int(str(N)[::-1])\n flag = 0\n for i in range(2, int(sqrt(N)) + 1):\n if N % i == 0:\n flag = 1\n break\n if flag == 1:\n return 0\n else:\n for i in range(2, int(sqrt(N_rev)) + 1):\n if N_rev % i == 0:\n flag = 1\n break\n if flag == 0:\n return 1\n else:\n return 0", "from math import sqrt\n\ndef isprime(N):\n if N <= 1:\n return 0\n for i in range(2, int(sqrt(N)) + 1):\n if N % i == 0:\n return 0\n else:\n return 1\n\ndef istwistedprime(N):\n t = int(str(N)[::-1])\n if isprime(t) and isprime(N):\n return 1\n return 0"], "starter_code": "def istwistedprime(N):\n", "input_output": {"inputs": ["N = 97", "N = 43"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Prime Number"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/twisted-prime-number0500/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "(O(sqrt(max(N,RevN))), here RevN is the reverse of N.", "entry_point": "istwistedprime", "task_id": "TACO_lite/403", "example": [[[97], [43]], ["1", "0"]]} +{"requirement": "Given a string S. The task is to find the first repeated character in it. We need to find the character that occurs more than once and whose index of second occurrence is smallest. S contains only lowercase letters.\n \nExample 1:\nInput: S=\"geeksforgeeks\"\nOutput: e\nExplanation: 'e' repeats at third position.\n \nExample 2:\nInput: S=\"hellogeeks\"\nOutput: l\nExplanation: 'l' repeats at fourth position.\n \nExample 3:\nInput: S=\"abc\"\nOutput: -1\nExplanation: There is no repeated character.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function firstRepChar() which accepts a string S as input parameter and returns a string containing first repeated character in it. If there is no repeated character in the string S then return \"-1\".\n \nExpected Time Complexity: O(|S|) \nExpected Auxiliary Space: O(1)\nwhere |S| denotes the length of string S.", "solutions": ["def firstrepchar(s):\n a = s\n for i in range(0, len(a)):\n list = a[:i]\n if a[i] in list:\n return a[i]\n return '-1'", "def firstrepchar(S):\n container = {}\n for i in range(len(S)):\n if S[i] in container:\n return S[i]\n else:\n container[S[i]] = 1\n return -1", "from collections import Counter\n\ndef firstrepchar(s):\n a = {}\n for i in s:\n if a.get(i) != None:\n return i\n a[i] = 1\n return -1", "def firstrepchar(s):\n char_arr = [0] * 26\n for i in s:\n i_in_ascii = ord(i) - ord('a')\n if char_arr[i_in_ascii]:\n return i\n else:\n char_arr[i_in_ascii] = 1\n return '-1'", "def firstrepchar(s):\n seen = []\n for let in s:\n if let in seen:\n return let\n seen.append(let)\n return -1", "def firstrepchar(s):\n st_l = set()\n for ch in s:\n if ch in st_l:\n return ch\n else:\n st_l.add(ch)\n return -1", "def firstrepchar(s):\n for i in range(len(s)):\n chk_lst = s[:i]\n if s[i] in chk_lst:\n return s[i]\n return -1", "def firstrepchar(s):\n diction = {}\n for ch in s:\n if ch in diction:\n diction[ch] += 1\n if diction[ch] == 2:\n return ch\n else:\n diction[ch] = 1\n return -1", "def firstrepchar(s):\n li = [s[0]]\n for i in range(1, len(s)):\n if s[i] not in li:\n li.append(s[i])\n else:\n return s[i]\n return -1", "def firstrepchar(s):\n d = {}\n for i in s:\n if i in d:\n return i\n else:\n d[i] = 1\n return -1", "def firstrepchar(s):\n save = {}\n for el in s:\n if el not in save:\n save[el] = 1\n continue\n return el\n return -1", "def firstrepchar(s):\n seen = set()\n for char in s:\n if char in seen:\n return char\n seen.add(char)\n return -1", "def firstrepchar(s):\n r = ''\n for i in s:\n if i in r:\n return i\n else:\n r = r + i\n if len(s) == len(r):\n return -1\n else:\n pass", "def firstrepchar(s):\n d = dict()\n for x in s:\n if x not in d:\n d[x] = 1\n else:\n return x\n return '-1'", "def firstrepchar(s):\n if len(set(s)) == len(s):\n return -1\n first_position_dict = {}\n for (char_tmp_index, char_tmp) in enumerate(s):\n if first_position_dict.get(char_tmp):\n return char_tmp\n else:\n first_position_dict[char_tmp] = 1\n return -1", "def firstrepchar(s):\n stack = []\n stack1 = []\n Output = ''\n for i in s:\n if i in stack:\n stack1.append(i)\n else:\n stack.append(i)\n if len(stack1) == 0:\n Output = '-1'\n else:\n Output = stack1[0]\n return Output", "def firstrepchar(s):\n k = 2\n s_set = set(s)\n lista = []\n for i in range(len(s_set)):\n nn = s_set.pop()\n cc = s.count(nn)\n lista.append((nn, cc))\n lista1 = []\n for i in range(len(lista)):\n if lista[i][1] >= k:\n lista1.append([lista[i][0], 0])\n break2 = 0\n if not lista1:\n return -1\n else:\n lista2 = []\n for i in s:\n for ii in range(len(lista1)):\n if i == lista1[ii][0]:\n lista1[ii][1] = lista1[ii][1] + 1\n if lista1[ii][1] == k:\n return lista1[ii][0]\n break2 = 1\n break\n if break2 == 1:\n break", "def firstrepchar(s):\n v = set()\n for i in range(len(s)):\n if s[i] in v:\n return s[i]\n else:\n v.add(s[i])\n return -1", "def firstrepchar(s):\n store = ''\n check = ''\n for a in s:\n if a in store:\n check = a\n break\n else:\n store += a\n if check == '':\n check = -1\n return check", "def firstrepchar(s):\n temp = set()\n for i in s:\n if i in temp:\n return i\n if i not in temp:\n temp.add(i)\n return -1", "def firstrepchar(s):\n h = {}\n for i in s:\n if i in h:\n return i\n else:\n h[i] = 0\n return -1", "def firstrepchar(s):\n chars = [0] * 256\n for ele in s:\n if chars[ord(ele)] != 0:\n return ele\n chars[ord(ele)] += 1\n return -1", "def firstrepchar(s):\n l = []\n for i in list(s):\n if i not in l:\n l.append(i)\n else:\n return i\n break\n return -1", "def firstrepchar(s):\n a = []\n for i in range(len(s)):\n if s[i] not in a:\n a.append(s[i])\n elif s[i] in a:\n return s[i]\n if len(a) == len(s):\n return -1", "def firstrepchar(s):\n map = {}\n minDistance = float('inf')\n ans = -1\n for i in range(len(s)):\n if s[i] in map:\n return s[i]\n else:\n map[s[i]] = i\n return ans", "def firstrepchar(s):\n hashmap = {}\n for i in s:\n if i not in hashmap:\n hashmap[i] = 1\n else:\n return i\n return -1", "def firstrepchar(s):\n d = ''\n for i in range(0, len(s)):\n if s[i] in d:\n return s[i]\n d += s[i]\n return -1", "def firstrepchar(s):\n chars = []\n for ch in s:\n if ch in chars:\n return ch\n chars.append(ch)\n return -1", "def firstrepchar(s):\n S = {}\n for i in s:\n if i in S:\n return i\n S[i] = 1\n return -1", "def firstrepchar(s):\n char_count = {}\n for char in s:\n if char in char_count:\n return char\n char_count[char] = 1\n return -1", "def firstrepchar(s):\n seen = set()\n for i in range(len(s)):\n if s[i] in seen:\n return s[i]\n seen.add(s[i])\n return -1", "def firstrepchar(s):\n h = {}\n for ch in s:\n if ch in h:\n return ch\n else:\n h[ch] = 1\n return -1", "def firstrepchar(s):\n ans = []\n for i in s:\n if i in ans:\n return i\n else:\n ans.append(i)\n return -1", "def firstrepchar(s):\n l = []\n c = 0\n for i in range(len(s)):\n if s[i] not in l:\n l.append(s[i])\n elif s[i] in l:\n c = 1\n return s[i]\n if c == 0:\n return -1", "def firstrepchar(s):\n d = dict()\n for i in s:\n if i in d:\n return i\n if i not in d:\n d.update({i: 1})\n return -1", "def firstrepchar(s):\n rep = set()\n for i in s:\n if i in rep:\n return i\n else:\n rep.add(i)\n return -1", "from collections import Counter\n\ndef firstrepchar(s):\n k = []\n for i in s:\n if i in k:\n return i\n else:\n k.append(i)\n return -1", "def firstrepchar(s):\n count = {}\n for i in s:\n if count.get(i):\n return i\n else:\n count[i] = '1'\n return -1", "def firstrepchar(s):\n answer = []\n temp = [i for i in s]\n for i in temp:\n if i not in answer:\n answer.append(i)\n else:\n return i\n return -1", "def firstrepchar(s):\n dic = {}\n for i in range(len(s)):\n if dic.get(s[i]) == None:\n dic[s[i]] = [1, i]\n elif dic[s[i]][0] == 1:\n dic[s[i]][0] += 1\n dic[s[i]][1] = i\n mini = len(s)\n k = ''\n c = 0\n for i in s:\n if dic[i][0] > 1 and dic[i][1] < mini:\n c = 1\n mini = dic[i][1]\n k = i\n if c == 1:\n return k\n return -1", "def firstrepchar(s):\n lst = []\n for i in s:\n if i not in lst:\n lst.append(i)\n else:\n return i\n return -1", "def firstrepchar(s):\n p = ''\n for i in range(len(s)):\n if s[i] not in p:\n p += s[i]\n else:\n char = s[i]\n return char\n return -1", "def firstrepchar(s):\n c = []\n for i in s:\n if i in c:\n return i\n c.append(i)\n return -1", "from collections import Counter\n\ndef firstrepchar(s):\n r = set()\n for i in s:\n if i in r:\n return i\n else:\n r.add(i)\n return -1", "def firstrepchar(s):\n visited = [False] * 26\n for i in s:\n if visited[ord('a') - ord(i)]:\n return i\n else:\n visited[ord('a') - ord(i)] = True\n return -1", "def firstrepchar(s):\n dict2 = {}\n dict1 = {}\n for i in range(len(s)):\n if s[i] not in dict1:\n dict1[s[i]] = 1\n else:\n dict1[s[i]] += 1\n if s[i] not in dict2:\n dict2[s[i]] = i\n if not dict2:\n return -1\n for i in dict2:\n if dict2[i] == min(dict2.values()):\n return i", "def firstrepchar(s):\n dic = {}\n for i in s:\n if i in dic:\n dic[i] += 1\n if dic[i] == 2:\n return i\n else:\n dic[i] = 1\n return -1", "def firstrepchar(s):\n explorado = ''\n for x in s:\n if explorado.count(x) == 0:\n explorado += x\n else:\n return x\n return -1"], "starter_code": "def firstrepchar(s):\n", "input_output": {"inputs": ["S=\"geeksforgeeks\"", "S=\"hellogeeks\"", "S=\"abc\""], "outputs": ["e", "l", "-1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Hash"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/find-first-repeated-character4108/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "firstrepchar", "task_id": "TACO_lite/395", "example": [[], []]} +{"requirement": "Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.\n\nIf the last word does not exist, return 0.\n\nNote: A word is defined as a character sequence consists of non-space characters only.\n\nExample:\n\nInput: \"Hello World\"\nOutput: 5", "solutions": ["def lengthoflastword(s):\n x = s.split()\n return len(x[-1]) if len(x) > 0 else 0", "def lengthoflastword(s):\n count = len(s.strip().split(' ')[-1])\n return count", "def lengthoflastword(s):\n (ans, tail) = (0, len(s) - 1)\n while tail >= 0 and s[tail] == ' ':\n tail -= 1\n while tail >= 0 and s[tail] != ' ':\n ans += 1\n tail -= 1\n return ans", "def lengthoflastword(s):\n if not s:\n return 0\n s = s.rstrip()\n s = s.lstrip()\n for i in range(0, len(s))[::-1]:\n if s[i] == ' ':\n return len(s) - 1 - i\n return len(s)", "def lengthoflastword(s):\n spaces = 0\n word_started = False\n for i in range(1, len(s) + 1):\n if s[-i] == ' ' and word_started is False:\n spaces += 1\n elif s[-i] == ' ' and word_started is True:\n return i - 1 - spaces\n else:\n word_started = True\n if word_started is True:\n return len(s) - spaces\n else:\n return 0", "def lengthoflastword(s):\n words = s.split()\n if not words:\n return 0\n return len(words[-1])", "def lengthoflastword(s):\n res = 0\n last = 0\n for i in s:\n if i == ' ':\n res = 0\n else:\n res += 1\n last = res\n return last", "def lengthoflastword(s):\n l = s.split(' ')\n while l:\n if l[-1]:\n return len(l[-1])\n else:\n l.pop(-1)\n return 0", "def lengthoflastword(s):\n v = s.split()\n if not v:\n return 0\n else:\n return len(v[-1])", "def lengthoflastword(s):\n l = len(s)\n n_c = 0\n for i in range(l - 1, -1, -1):\n if s[i] != ' ':\n n_c += 1\n elif s[i] == ' ' and n_c == 0:\n pass\n elif s[i] == ' ' and n_c != 0:\n return n_c\n return n_c", "def lengthoflastword(s):\n s = s.strip()\n if s == None:\n return 0\n count = 0\n for item in s[-1::-1]:\n if item == ' ':\n break\n count += 1\n return count"], "starter_code": "def lengthoflastword(s: str) -> int:\n", "input_output": {"fn_name": "lengthOfLastWord", "inputs": [["\"Hello World\""]], "outputs": [6]}, "difficulty": "EASY", "raw_tags": ["String"], "name": null, "source": "leetcode", "tags": ["String algorithms"], "skill_types": [], "url": "https://leetcode.com/problems/length-of-last-word/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "lengthoflastword", "task_id": "TACO_lite/415", "example": [[["Hello World"]], ["5"]]} +{"requirement": "Write function RemoveExclamationMarks which removes all exclamation marks from a given string.", "solutions": ["def remove_exclamation_marks(s):\n return s.replace('!', '')", "remove_exclamation_marks = lambda s: s.replace('!', '')", "def remove_exclamation_marks(s):\n x = s.replace('!', '')\n return x", "def remove_exclamation_marks(s):\n return ''.join([x for x in s if x != '!'])", "def remove_exclamation_marks(s):\n s = list(s)\n for x in s:\n if x == '!':\n s.remove(x)\n for x in s:\n if x == '!':\n s.remove(x)\n for x in s:\n if x == '!':\n s.remove(x)\n return ''.join(s)", "def remove_exclamation_marks(s):\n new_s = ''\n for i in s:\n if i != '!':\n new_s += i\n return new_s", "def remove_exclamation_marks(s: str) -> str:\n return s.replace('!', '')", "import re\n\ndef remove_exclamation_marks(s):\n return re.sub('!', '', s)", "def remove_exclamation_marks(s):\n y = list(s)\n for l in range(0, y.count('!')):\n y.remove('!')\n z = ''.join(y)\n return z", "def remove_exclamation_marks(s):\n return ''.join(filter(lambda x: x.isalpha() or x == ' ' or x == ',', s))", "def remove_exclamation_marks(s):\n return ''.join(list((l for l in s if l != '!')))", "import string\n\ndef remove_exclamation_marks(s):\n d = {'!': None}\n t = str.maketrans(d)\n return s.translate(t)", "def remove_exclamation_marks(s):\n temp = list(s)\n while '!' in temp:\n temp.remove('!')\n return ''.join(temp)", "remove_exclamation_marks = lambda a: a.replace('!', '')", "def remove_exclamation_marks(s):\n s1 = ''\n for i in s:\n if i != '!':\n s1 = s1 + i\n return s1", "def remove_exclamation_marks(s):\n if '!' not in s:\n return s\n else:\n s1 = ''\n for caracter in s:\n if caracter != '!':\n s1 += caracter\n return s1", "def remove_exclamation_marks(s):\n str = s.replace('!', '')\n return str\nremove_exclamation_marks('Hello World!')\nremove_exclamation_marks('Hello World!!!')\nremove_exclamation_marks('Hi! Hello!')\nremove_exclamation_marks('Oh, no!!!')", "def remove_exclamation_marks(s):\n word = ''\n for let in s:\n if let != '!':\n word = word + let\n return word", "remove_exclamation_marks = lambda s: ''.join((x for x in s if x != '!'))", "def remove_exclamation_marks(s):\n res = [i for i in s if i != '!']\n return ''.join(res)", "def remove_exclamation_marks(s):\n c = s.count('!')\n s = list(s)\n for i in range(c):\n s.remove('!')\n return ''.join(s)", "def remove_exclamation_marks(s):\n lol = s.replace('!', '')\n return lol", "def remove_exclamation_marks(s):\n result = ''\n for i in s:\n if i == '!':\n pass\n else:\n result += i\n return result", "def remove_exclamation_marks(s):\n s = list(s)\n for i in range(len(s)):\n if '!' in s:\n s.remove('!')\n return ''.join(s)", "def remove_exclamation_marks(s):\n for element in s:\n if element == '!':\n s = s.replace('!', '')\n return s", "def remove_exclamation_marks(s):\n result = ''\n for y in s:\n if y != '!':\n result += y\n return result", "def remove_exclamation_marks(s):\n a = ''\n for c in s:\n if c != '!':\n a += c\n return a", "def remove_exclamation_marks(s):\n new_string = ''\n for char in s:\n if char == '!':\n pass\n else:\n new_string += char\n return new_string", "def remove_exclamation_marks(s):\n return s.translate(str.maketrans({'!': ''}))", "def remove_exclamation_marks(s):\n return s if not s else s.replace('!', '')", "def remove_exclamation_marks(s):\n total = ''\n for i in s:\n if i != '!':\n total += i\n return total", "def remove_exclamation_marks(s):\n r = list(s)\n for char in s:\n if char == '!':\n r.remove(char)\n string = ''\n for i in r:\n string += i\n return string", "def remove_exclamation_marks(s):\n a = str()\n for i in s:\n if i != '!':\n a += i\n return a", "def remove_exclamation_marks(s):\n a = ''\n for i in s:\n if i in '!':\n pass\n else:\n a += i\n return a", "def remove_exclamation_marks(s):\n return ''.join([i for i in s if ord(i) != 33])", "def remove_exclamation_marks(s):\n newS = ''\n for letters in s:\n if letters != '!':\n newS += letters\n return newS", "def remove_exclamation_marks(s):\n no_mark = ''\n for word in s:\n if word != '!':\n no_mark += word\n return no_mark", "def remove_exclamation_marks(s):\n S = ''\n for i in s:\n S = s.replace('!', '')\n return S", "def remove_exclamation_marks(s):\n string = ''\n for x in s:\n if x != '!':\n string += x\n return string", "def remove_exclamation_marks(s):\n sl = list(s)\n n = sl.count('!')\n i = 1\n while i <= n:\n sl.remove('!')\n i += 1\n return ''.join(sl)", "def remove_exclamation_marks(s):\n newlist = s.replace('!', '')\n return newlist", "import re\n\ndef remove_exclamation_marks(str):\n return ''.join(re.findall('\\\\w|\\\\s|[,]', str))", "def remove_exclamation_marks(s):\n new_string = ''\n for e in s:\n if e != '!':\n new_string += e\n return new_string", "def remove_exclamation_marks(s):\n a = [s.strip('!') for s in s]\n return ''.join(a)", "def remove_exclamation_marks(s):\n new_string = ''\n for i in s:\n if i != '!':\n new_string += i\n return new_string", "def remove_exclamation_marks(s):\n for i in range(len(s)):\n count = s.count('!')\n s = s.replace('!', '', count)\n return s", "def remove_exclamation_marks(s):\n list = [',', ' ', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M']\n for i in s:\n if i in list:\n continue\n else:\n s = s.replace(i, '')\n return s", "def remove_exclamation_marks(s):\n s = s.split(' ')\n no_marks = []\n for char in s:\n char = list(char)\n no_exc = []\n for x in char:\n if x != '!':\n no_exc.append(x)\n collect = ''.join(no_exc)\n no_marks.append(collect)\n return ' '.join(no_marks)", "def remove_exclamation_marks(s):\n res = ''\n for i in s:\n if not i == '!':\n res = res + i\n return res", "def remove_exclamation_marks(s):\n result = ''\n for i in s:\n if i != '!':\n result = result + i\n return result", "def remove_exclamation_marks(s):\n m = list(s)\n x = []\n for i in m:\n if i != '!':\n x.append(i)\n v = ''.join(x)\n return v", "def remove_exclamation_marks(s):\n return ''.join((i if i != '!' else '' for i in s))", "def remove_exclamation_marks(s):\n return ''.join((ele for ele in s if ele != '!'))", "def remove_exclamation_marks(s):\n res = ''\n for i in range(len(s)):\n if s[i] != '!':\n res += s[i]\n return res", "def remove_exclamation_marks(s):\n return ''.join([i for i in list(str(s)) if i != '!'])", "def remove_exclamation_marks(s):\n screw_the_exclaimation_mark = s.replace('!', '')\n return screw_the_exclaimation_mark", "def remove_exclamation_marks(string):\n new = string.replace('!', '')\n return new", "def remove_exclamation_marks(s):\n k = ''\n for i in s:\n if i != '!':\n k += i\n return k", "def remove_exclamation_marks(s):\n ergebnis = ''\n for i in s:\n if i != '!':\n ergebnis += i\n return ergebnis", "import unittest\n\ndef remove_exclamation_marks(s):\n return s.replace('!', '')\n\ndef test_only_one_exclamation_marks():\n s = 'Hello World!'\n actual = remove_exclamation_marks(s)\n self.assertEqual(actual, 'Hello World')\n\ndef test_only_all_exclamation_marks():\n s = 'Hello World!'\n actual = remove_exclamation_marks(s)\n self.assertEqual(actual, 'Hello World')", "def remove_exclamation_marks(s):\n bas = ''\n out = ''\n for i in s:\n if i == '!':\n bas += i\n else:\n out += i\n return out", "def remove_exclamation_marks(s):\n char = ''\n for i in s:\n if i != '!':\n char += i\n return char", "import re\n\ndef remove_exclamation_marks(s):\n return ''.join(re.findall('[a-z A-Z,]', s))", "def remove_exclamation_marks(s):\n z = ''.join([l for l in s if l != '!'])\n return z", "import re\n\ndef remove_exclamation_marks(my_list):\n return re.sub('!', '', my_list)", "def remove_exclamation_marks(s):\n st = s.replace('!', '')\n return st", "def remove_exclamation_marks(s):\n return ''.join(filter(lambda char: char != '!', list(s)))", "def remove_exclamation_marks(s):\n out = ''\n for i in s:\n if i != '!':\n out += i\n return out", "def remove_exclamation_marks(s):\n '!' in s == True\n return s.replace('!', '')", "def remove_exclamation_marks(s):\n d = ''\n for i in s:\n if i not in '!¡':\n d += i\n return d", "def remove_exclamation_marks(s):\n a = s.strip('!')\n l = []\n for i in range(0, len(a)):\n s = a[i]\n l.append(s)\n while '!' in l:\n l.pop(l.index('!'))\n return ''.join(l)", "def remove_exclamation_marks(n):\n return n.replace('!', '')", "def remove_exclamation_marks(s):\n s1 = []\n for i in s:\n if i != '!':\n s1.append(i)\n return ''.join(s1)", "def remove_exclamation_marks(s):\n n = ''\n for x in s:\n if x.isalpha() or x == ' ' or x == ',':\n n += x\n return n", "def remove_exclamation_marks(s):\n lst = s.split('!')\n return ''.join(lst)", "def remove_exclamation_marks(s):\n answer = ''\n for i in s:\n if i == '!':\n pass\n else:\n answer += i\n return answer", "def remove_exclamation_marks(s):\n sp = s.split('!')\n new_string = ''.join(sp)\n return new_string", "def remove_exclamation_marks(Str):\n Word = ''\n for s in Str:\n if not s == '!':\n Word += s\n return Word", "def remove_exclamation_marks(s):\n s = list(s)\n x = 0\n for element in s:\n while True:\n if len(s) == x:\n break\n if s[x] == '!':\n del s[x]\n else:\n break\n x += 1\n s = ''.join(s)\n return s", "def remove_exclamation_marks(s):\n new_s = []\n for n in s:\n if n == '!':\n n = ''\n else:\n new_s.append(n)\n answer = ''.join(new_s)\n return answer", "def remove_exclamation_marks(s):\n result = ''\n for i in range(len(s)):\n if s[i] != '!':\n result += s[i]\n return result", "def remove_exclamation_marks(s):\n return ''.join((x for x in s if x is not '!'))"], "starter_code": "def remove_exclamation_marks(s):\n", "input_output": {"fn_name": "remove_exclamation_marks", "inputs": [["Hello World!"], ["Hello World!!!"], ["Hi! Hello!"], [""], ["Oh, no!!!"]], "outputs": [["Hello World"], ["Hello World"], ["Hi Hello"], [""], ["Oh, no"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/57a0885cbb9944e24c00008e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "remove_exclamation_marks", "task_id": "TACO_lite/364", "example": [[], []]} +{"requirement": "In this Kata, you will be given two numbers, `a` and `b`, and your task is to determine if the first number `a` is divisible by `all` the prime factors of the second number `b`. For example: `solve(15,12) = False` because `15` is not divisible by all the prime factors of `12` (which include`2`).\n\nSee test cases for more examples. \n\nGood luck!\n\nIf you like this Kata, please try:\n\n[Sub-array division](https://www.codewars.com/kata/59eb64cba954273cd4000099)\n\n[Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)", "solutions": ["import fractions\n\ndef solve(a, b):\n c = fractions.gcd(a, b)\n while c > 1:\n b //= c\n c = fractions.gcd(a, b)\n return b == 1", "from math import gcd\n\ndef solve(a, b):\n while 1 < gcd(a, b):\n b = b // gcd(a, b)\n return b == 1", "from math import gcd\n\ndef solve(a, b):\n x = gcd(a, b)\n if x == 1:\n return False\n if x == b:\n return True\n return solve(a, b // x)", "from fractions import gcd\n\ndef solve(a, b):\n if b == 1:\n return True\n if gcd(a, b) == 1:\n return False\n return solve(a, b / gcd(a, b))", "def solve(a, b):\n (li, j) = ([], 2)\n while b > 1:\n if b % j:\n j += 1\n continue\n li.append(j)\n b //= j\n if a % j:\n return 0\n return 1", "def solve(a, b):\n k = 2\n while k <= int(b ** 0.5):\n while b % k == 0:\n b //= k\n if a % k != 0:\n return False\n k += 1\n return a % b == 0", "def solve(a, b):\n b1 = b\n answer = True\n i = 2\n primfac = []\n while i * i <= b:\n while b1 % i == 0:\n primfac.append(i)\n b1 = b1 // i\n i = i + 1\n if b1 > 1:\n primfac.append(b1)\n for i in range(0, len(primfac)):\n if a % primfac[i] != 0:\n answer = False\n return answer", "N = 10000\na = [1] * N\na[0] = a[1] = 0\nfor i in range(2, N):\n if a[i]:\n for j in range(i ** 2, N, i):\n a[j] = 0\na = [i for (i, x) in enumerate(a) if x]\n\ndef solve(n, m):\n return all((not n % x for x in f(m)))\n\ndef f(n):\n s = set()\n for x in a:\n if x > n:\n break\n while not n % x:\n n //= x\n s.add(x)\n if n > 1:\n s.add(n)\n return s", "def solve(a, b):\n p = 2\n while True:\n if b == 1:\n return True\n if a % p > 0 and b % p == 0:\n return False\n while b % p == 0:\n b /= p\n p += 1", "from math import ceil, sqrt\n\ndef factorize(x):\n factors = []\n for i in range(2, ceil(sqrt(x)) + 1):\n while x % i == 0:\n factors.append(i)\n x /= i\n if x != 1:\n factors.append(x)\n return factors\n\ndef solve(a, b):\n factors = factorize(b)\n ok = True\n for factor in factors:\n if a % factor != 0:\n ok = False\n return ok"], "starter_code": "def solve(a,b):\n", "input_output": {"fn_name": "solve", "inputs": [[2, 256], [2, 253], [9, 243], [15, 12], [21, 2893401], [21, 2893406], [54, 2834352], [54, 2834359], [1000013, 7187761], [1000013, 7187762]], "outputs": [[true], [false], [true], [false], [true], [false], [true], [false], [true], [false]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/59ec2d112332430ce9000005", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/352", "example": [[[15, 12]], ["False"]]} +{"requirement": "Given a binary string S (a string consisting only of '0' and '1's) and a positive integer N, return true if and only if for every integer X from 1 to N, the binary representation of X is a substring of S.\n \nExample 1:\nInput: S = \"0110\", N = 3\nOutput: true\n\nExample 2:\nInput: S = \"0110\", N = 4\nOutput: false\n\n \nNote:\n\n1 <= S.length <= 1000\n1 <= N <= 10^9", "solutions": ["def querystring(S: str, N: int) -> bool:\n for i in range(1, N + 1):\n b = bin(i).replace('0b', '')\n if b not in S:\n return False\n return True", "def int_to_bin(x):\n ret = ''\n if x == 0:\n return '0'\n while x > 0:\n ret = str(x % 2) + ret\n x = x // 2\n return ret\n\ndef querystring(S: str, N: int) -> bool:\n mp = {}\n max_len = min(31, len(S))\n for k in range(1, max_len + 1):\n for i in range(len(S) - k + 1):\n mp[S[i:i + k]] = True\n for i in range(1, N + 1):\n if self.int_to_bin(i) not in mp:\n return False\n return True", "def querystring(S: str, N: int) -> bool:\n for i in range(1, N + 1):\n if bin(i)[2:] not in S:\n return False\n return True", "def querystring(S: str, N: int) -> bool:\n if '1' not in S:\n return False\n res = set()\n cur = set()\n for s in S:\n if s == '0':\n cur = {c * 2 for c in cur} | {0}\n else:\n cur = {c * 2 + 1 for c in cur} | {1}\n res |= cur\n for i in range(1, N + 1):\n if i not in res:\n return False\n return True", "def querystring(S: str, M: int) -> bool:\n count = defaultdict(int)\n N = len(S)\n\n def f(ss):\n ans = 0\n nn = len(ss) - 1\n for ch in ss:\n if ch == '1':\n ans += 1 << nn\n nn -= 1\n return ans\n cnt = 0\n for n1 in range(N):\n for n2 in range(n1, N):\n if n2 - n1 < 32:\n val = f(S[n1:n2 + 1])\n if val >= 1 and val <= M and (count[val] == 0):\n cnt += 1\n count[val] = 1\n else:\n break\n if cnt == M:\n return True\n return False", "def querystring(S: str, N: int) -> bool:\n substrings = set()\n for i in range(len(S)):\n for j in range(i, len(S) + 1):\n substrings.add(S[i:j])\n for i in range(1, N + 1):\n binN = str(bin(i))[2:]\n if binN in substrings:\n continue\n else:\n return False\n return True", "def querystring(S: str, N: int) -> bool:\n seen = set()\n if len(S) < 2:\n seen.add(S)\n for i in range(len(S) - 1):\n for j in range(i + 1, len(S)):\n if S[i] == '0':\n seen.add(S[i + 1:j + 1])\n else:\n seen.add(S[i:j + 1])\n for i in range(1, N + 1):\n binary = bin(i)[2:]\n if binary not in seen:\n return False\n return True", "def querystring(S: str, N: int) -> bool:\n return all((bin(i)[2:] in S for i in range(N, N // 2, -1)))", "def querystring(S: str, N: int) -> bool:\n st = set()\n for size in range(1, len(S) + 1):\n for i in range(len(S) - size + 1):\n st.add(S[i:i + size])\n for i in range(1, N + 1):\n if not bin(i)[2:] in st:\n return False\n return True", "def querystring(S: str, N: int) -> bool:\n dic = set()\n for i in range(len(S)):\n for l in range(len(S) - i):\n dic.add(S[i:i + l + 1])\n for x in range(1, N + 1):\n if str(bin(x)[2:]) not in dic:\n return False\n return True", "from itertools import combinations\n\ndef querystring(S: str, N: int) -> bool:\n d = set()\n for i in range(0, len(S) + 1):\n j = 0\n end = i + 1\n while end < len(S) + 1:\n d.add(S[j:end])\n j = j + 1\n end = end + 1\n q = 1\n for i in range(1, N + 1):\n if bin(i)[2:] not in d:\n q = 0\n break\n return q", "def querystring(S: str, N: int) -> bool:\n n = len(S)\n for i in range(30, -1, -1):\n if N & 1 << i:\n msb = i\n break\n\n def get(msb):\n s = set()\n num = 0\n x = 0\n if msb > 0:\n x = 1 << msb - 1\n for i in range(n):\n if i == msb:\n if S[i] == '1':\n num += 1\n if x < num <= N:\n s.add(num)\n elif i > msb:\n if num & 1 << msb:\n num -= 1 << msb\n num <<= 1\n if S[i] == '1':\n num += 1\n if x < num <= N:\n s.add(num)\n elif S[i] == '1':\n num |= 1 << msb - i\n return s\n s = get(msb)\n p = 0\n if msb > 0:\n p = 1 << msb - 1\n if msb > 0:\n s1 = get(msb - 1)\n p = 0\n if msb > 1:\n p = 1 << msb - 2\n for i in s1:\n s.add(i)\n return len(s) == N - p", "def querystring(S: str, N: int) -> bool:\n\n def is_x_in(x):\n binary = []\n while x:\n binary.append(x % 2)\n x = x >> 1\n binary = ''.join((str(n) for n in reversed(binary)))\n return S.find(binary) >= 0\n return all((is_x_in(x) for x in range(N + 1)))"], "starter_code": "def querystring(S: str, N: int) -> bool:\n", "input_output": {"fn_name": "queryString", "inputs": [["\"0110\"", 3]], "outputs": [true]}, "difficulty": "MEDIUM", "raw_tags": ["String"], "name": null, "source": "leetcode", "tags": ["String algorithms"], "skill_types": [], "url": "https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "querystring", "task_id": "TACO_lite/405", "example": [[], []]} +{"requirement": "Given a binary string S and an integer K, the task is to count the number of substrings that contain exactly K ones.\nExample 1:\nInput : S = 10010, K = 1\nOutput : 9\nExplanation: The 9 substrings containing \none 1 are, 1, 10, 100, 001, 01,\n1, 10, 0010 and 010.\nExample 2:\nInput : S = 111, K = 2 \nOutput : 2 \nExplanation: The 2 substrings containing\ntwo 1 are 11, 11.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function countOfSubstringWithKOnes() which takes the string S and an integer K as inputs and returns the count.\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(|S|)\nConstraints:\n1 ≤ N ≤ 10^{5}\n1 ≤ K ≤ 10^{4}", "solutions": ["def countofsubstringwithkones(S, K):\n cm = 0\n mp = dict()\n n = len(S)\n ans = 0\n for i in range(n):\n cm += ord(S[i]) - 48\n if cm == k:\n ans += 1\n if cm - k in mp:\n ans += mp[cm - k]\n if cm not in mp:\n mp[cm] = 1\n else:\n mp[cm] += 1\n return ans", "def solve(s, k):\n ans = 0\n n = len(s)\n cnt = 0\n j = 0\n for i in range(n):\n if s[i] == '1':\n cnt += 1\n while j < n and cnt > k:\n if s[j] == '1':\n cnt -= 1\n j += 1\n ans += i - j + 1\n return ans\n\ndef countofsubstringwithkones(S, K):\n if K == 0:\n return self.solve(S, K)\n return self.solve(S, K) - self.solve(S, K - 1)", "def countofsubstringwithkones(S, K):\n freq = {}\n S = list(str(S))\n presum = 0\n freq[0] = 1\n c = 0\n for i in S:\n presum += int(i)\n if presum - K in freq:\n c += freq[presum - K]\n if presum not in freq:\n freq[presum] = 0\n freq[presum] += 1\n return c", "def countofsubstringwithkones(S, k):\n if k == 0:\n count = 0\n c = 0\n for i in S:\n if i == '0':\n c += 1\n else:\n count += c * (c + 1) // 2\n c = 0\n if c:\n count += c * (c + 1) // 2\n return count\n nums = list(S)\n count = 0\n (a, b, c) = (0, 0, 1)\n ln = len(nums)\n for i in range(ln):\n nums[i] = nums[i] == '1'\n while a < ln and nums[a] == 0:\n c += 1\n a += 1\n for i in range(ln):\n k -= nums[i]\n if k == 0:\n count += c\n elif k == -1:\n k = 0\n a += 1\n c = 1\n while nums[a] == 0:\n c += 1\n a += 1\n count += c\n return count", "def countofsubstringwithkones(S, K):\n count = 0\n n = len(s)\n feq = [0 for i in range(n + 1)]\n feq[0] = 1\n res = 0\n for i in range(n):\n count += ord(s[i]) - ord('0')\n if count >= K:\n res += feq[count - k]\n feq[count] += 1\n return res", "def countofsubstringwithkones(S, K):\n count = 0\n S = str(' '.join(S))\n import collections\n mapp = collections.defaultdict(int)\n mapp[0] = 1\n summ = 0\n l = list(map(int, S.split(' ')))\n for ele in l:\n summ += ele\n count += mapp[summ - K]\n mapp[summ] += 1\n return count", "def countofsubstringwithkones(s, k):\n cum_sum = 0\n mp = {}\n cnt = 0\n arr = [int(i) for i in s]\n mp[0] = [-1]\n n = len(s)\n for i in range(n):\n cum_sum = cum_sum + arr[i]\n if cum_sum - k in mp:\n cnt = cnt + len(mp[cum_sum - k])\n mp.setdefault(cum_sum, []).append(i)\n return cnt", "def countofsubstringwithkones(S, K):\n n = len(S)\n dp = [0] * (n + 1)\n dp[0] = 1\n one_count = 0\n res = 0\n for c in S:\n if c == '1':\n one_count += 1\n if one_count >= K:\n res += dp[one_count - K]\n dp[one_count] += 1\n return res", "def countofsubstringwithkones(S, K):\n res = 0\n freq = [0 for i in range(len(S) + 1)]\n freq[0] = 1\n countOne = 0\n for i in range(len(S)):\n countOne += ord(S[i]) - ord('0')\n if countOne >= k:\n res += freq[countOne - k]\n freq[countOne] += 1\n return res", "def countofsubstringwithkones(S, K):\n d = {}\n count = 0\n Sum = 0\n for num in S:\n Sum = Sum + int(num)\n if Sum == K:\n count = count + 1\n if Sum - K in d:\n count = count + d[Sum - K]\n if Sum not in d:\n d[Sum] = 1\n else:\n d[Sum] += 1\n return count", "def countofsubstringwithkones(s, k):\n (i, j) = (0, 0)\n n = len(s)\n presum = 0\n res1 = 0\n while j < n:\n if s[j] == '1':\n presum += 1\n while presum > k:\n if s[i] == '1':\n presum -= 1\n i += 1\n res1 += j - i + 1\n j += 1\n if k == 0:\n return res1\n k -= 1\n (i, j) = (0, 0)\n presum = 0\n res2 = 0\n while j < n:\n if s[j] == '1':\n presum += 1\n while presum > k:\n if s[i] == '1':\n presum -= 1\n i += 1\n res2 += j - i + 1\n j += 1\n return res1 - res2", "def countofsubstringwithkones(S, K):\n N = len(s)\n res = 0\n countOfOne = 0\n freq = [0 for i in range(N + 1)]\n freq[0] = 1\n for i in range(0, N, 1):\n countOfOne += ord(s[i]) - ord('0')\n if countOfOne >= K:\n res += freq[countOfOne - K]\n freq[countOfOne] += 1\n return res", "def countofsubstringwithkones(S, K):\n Sum = 0\n Dict = {0: 1}\n N = len(S)\n res = 0\n for i in range(N):\n Sum += int(S[i])\n if Sum - K >= 0 and Sum - K in Dict:\n res += Dict[Sum - K]\n if Sum not in Dict:\n Dict[Sum] = 1\n else:\n Dict[Sum] += 1\n return res", "def countofsubstringwithkones(S, K):\n result = 0\n cnt = 0\n freq = [0 for i in range(len(S) + 1)]\n freq[0] = 1\n for i in range(len(S)):\n cnt += ord(S[i]) - ord('0')\n if cnt >= K:\n result += freq[cnt - K]\n freq[cnt] += 1\n return result", "def countofsubstringwithkones(S, K):\n d = {}\n prefix_sum = 0\n count = 0\n for i in range(len(S)):\n prefix_sum += int(S[i])\n if prefix_sum == K:\n count += 1\n if prefix_sum - K in d:\n count += d[prefix_sum - K]\n if prefix_sum not in d:\n d[prefix_sum] = 1\n else:\n d[prefix_sum] += 1\n return count", "def countofsubstringwithkones(S, K):\n l = [int(x) for x in S]\n d = {0: [-1]}\n indices = []\n sum = 0\n count = 0\n for i in range(len(l)):\n sum += l[i]\n if sum - K in d:\n for x in d[sum - K]:\n count += 1\n if sum not in d:\n d[sum] = [i]\n else:\n d[sum].append(i)\n return count", "def countofsubstringwithkones(S, K):\n\n def s1(S, K):\n l = 0\n r = 0\n count = 0\n ret = 0\n while r < len(S):\n if S[r] == '1':\n count += 1\n while count == K + 1:\n ret += 1\n if S[l] == '1':\n count -= 1\n l += 1\n r += 1\n return ret\n\n def s2(S, K):\n from collections import defaultdict\n freqOfCount = defaultdict(int)\n countSoFar = 0\n ret = 0\n freqOfCount[0] = 1\n for (i, c) in enumerate(S):\n if c == '1':\n countSoFar += 1\n if countSoFar >= K:\n ret += freqOfCount[countSoFar - K]\n freqOfCount[countSoFar] += 1\n return ret\n return s2(S, K)", "def countofsubstringwithkones(s, k):\n map1 = {0: 1}\n ans = 0\n curr_sum = 0\n for i in range(len(s)):\n if s[i] == '1':\n curr_sum += 1\n ans += map1[curr_sum - k] if curr_sum - k in map1 else 0\n map1[curr_sum] = map1.get(curr_sum, 0) + 1\n return ans", "def countofsubstringwithkones(S, K):\n freq = dict()\n sm = 0\n c = 0\n for i in S:\n if i == '1':\n sm += 1\n if sm == K:\n c = c + 1\n if sm - K in freq:\n c = c + freq[sm - K]\n freq[sm] = freq.get(sm, 0) + 1\n return c", "def countofsubstringwithkones(S, K):\n string = S\n n = K\n prefixCount = []\n freq = {}\n curCount = 0\n if n == 0:\n mainSu = 0\n curCount = 0\n for x in string:\n if x == '1':\n mainSu += curCount * (curCount + 1) // 2\n curCount = 0\n else:\n curCount += 1\n mainSu += curCount * (curCount + 1) // 2\n return mainSu\n for x in string:\n if x == '1':\n curCount += 1\n prefixCount.append(curCount)\n for x in prefixCount:\n temp = freq.get(x)\n if temp:\n freq[x] += 1\n else:\n freq[x] = 1\n mainSu = 0\n prevCount = 0\n curCount = 0\n target = n\n i = 0\n flag = True\n for x in range(len(string)):\n if string[x] == '0':\n calc = n + prefixCount[x]\n temp = freq.get(calc)\n if temp:\n mainSu += freq[calc]\n else:\n calc = n + prefixCount[x] - 1\n temp = freq.get(calc)\n if temp:\n mainSu += freq[calc]\n flag = False\n if flag:\n if n == 0:\n n = len(string)\n return n * (n + 1) // 2\n else:\n return 0\n else:\n return mainSu", "def countofsubstringwithkones(S, K):\n count = 0\n ones = []\n for (index, item) in enumerate(S):\n if item == '1':\n ones.append(index)\n if len(ones) < K:\n return 0\n if K == 0:\n zeros = []\n flag = False\n count0 = 0\n for i in range(len(S)):\n if S[i] == '0':\n flag = True\n count0 += 1\n else:\n if flag:\n zeros.append(count0)\n flag = False\n count0 = 0\n zeros.append(count0)\n for num in zeros:\n count += num * (num + 1) // 2\n return int(count)\n left = 0\n next1 = K - 1\n start = ones[K - 1] if K - 1 >= 0 else 0\n for i in range(start, len(S)):\n x = -1 if left == 0 else ones[left - 1]\n if next1 < len(ones) and ones[next1] == i:\n incr = ones[left] - x\n count += incr\n left += 1\n next1 += 1\n else:\n count += incr\n return count"], "starter_code": "def countofsubstringwithkones(S, K):\n", "input_output": {"inputs": ["S = 10010, K = 1", "S = 111, K = 2"], "outputs": ["9", "2"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Strings", "Hash"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-of-substrings-containing-k-ones2304/1", "Expected Auxiliary Space": "O(|S|)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "countofsubstringwithkones", "task_id": "TACO_lite/378", "example": [[["10010", 1], ["111", 2]], ["9", "2"]]} +{"requirement": "Given a string, check if all its characters are the same or not.\nExample 1:\nInput:\ns = \"geeks\"\nOutput: False\nExplanation: The string contains different\ncharacter 'g', 'e', 'k' and 's'.\nExample 2:\nInput: \ns = \"gggg\"\nOutput: True\nExplanation: The string contains only one\ncharacter 'g'.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function check() which takes a string as input and returns True if all the characters in the string are the same. Else, it returns False.\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= |S| <= 10^{4}", "solutions": ["def check(s):\n d = set(s)\n if len(d) == 1:\n return True\n return False", "def check(s):\n if s.count(s[0]) == len(s):\n return True\n else:\n return False", "def check(s):\n k = s[0]\n for i in s[1:]:\n if i != k:\n return False\n return True", "def check(s):\n a = set(list(s))\n if len(a) == 1:\n return True\n else:\n return False", "def check(s):\n return len(s) == s.count(s[0])", "def check(S):\n return all((char == S[0] for char in S))", "def check(s):\n for i in range(len(s) - 1):\n if s[i] != s[i + 1]:\n return False\n return True", "def check(s):\n return len(set(s)) == 1", "def check(s):\n a = s[0]\n for i in s:\n if i == a:\n continue\n else:\n return False\n return True", "def check(s):\n e = s[0]\n ret_val = True\n for i in s:\n if i != e:\n ret_val = False\n return ret_val", "def check(s):\n ch = s[0]\n for i in s:\n if i != ch:\n return False\n return True", "def check(s):\n c = s[0]\n l = len(s)\n for i in range(1, l):\n if s[i] == s[0]:\n continue\n else:\n return False\n return True", "def check(s):\n count = 0\n l = len(s)\n s1 = s[0]\n for i in range(l):\n if s[i] != s1:\n count += 1\n break\n if count > 0:\n return False\n else:\n return True", "def check(s):\n flag = True\n for i in range(len(s) - 1):\n if s[i] != s[i + 1]:\n flag = False\n break\n else:\n flag = True\n if flag == True:\n return True\n else:\n return False", "def check(s):\n se = set(s)\n if len(se) == 1:\n return True\n else:\n return False", "def check(s):\n l = len(s)\n c = s.count(s[0])\n if l == c:\n return 1\n else:\n return 0", "from collections import Counter\n\ndef check(s):\n x = Counter(s)\n if len(Counter(x.keys())) == 1:\n return 'True'", "def check(s):\n dt = {}\n for i in s:\n dt[i] = 1\n if len(dt) == 1:\n return True\n else:\n return False", "def check(s):\n a = len(s)\n for i in range(len(s)):\n if s[0] != s[i]:\n return False\n break\n else:\n return True", "def check(s):\n for char in s:\n if s[0] != char:\n return False\n return True", "def check(s):\n se = set()\n se.add(s[0])\n for i in s:\n if i not in se:\n return False\n return True", "def check(s):\n return all((char == s[0] for char in s))", "def check(s):\n l = list(s)\n st = set(l)\n if len(st) == 1:\n return True\n return False", "def check(s):\n first = s[0]\n for i in s:\n if i != first:\n return False\n break\n else:\n return True", "def check(s):\n for element in range(len(s)):\n if s[element] != s[0]:\n return False\n else:\n return True", "def check(s):\n inp_str_list = set(s.strip(''))\n if len(inp_str_list) == 1:\n return True\n else:\n return False", "def check(s):\n for i in range(len(s) - 1):\n if s[i] != s[i + 1]:\n return 0\n return 1", "def check(s):\n for i in s:\n if s.count(i) == len(s):\n return True\n else:\n return False", "def check(s):\n first_s = s[0]\n for i in s:\n if i == first_s:\n pass\n else:\n return False\n return True", "from operator import countOf\n\ndef check(s):\n s = list(s)\n if countOf(s, s[0]) == len(s):\n return True\n else:\n return False"], "starter_code": "def check (s):\n", "input_output": {"inputs": ["s = \"geeks\"", "s = \"gggg\""], "outputs": ["False", "True"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/check-string1818/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|).", "entry_point": "check", "task_id": "TACO_lite/333", "example": [[["geeks"], ["gggg"]], ["False", "True"]]} +{"requirement": "Define a method that accepts 2 strings as parameters. The method returns the first string sorted by the second.\n\n```python\nsort_string(\"foos\", \"of\") == \"oofs\"\nsort_string(\"string\", \"gnirts\") == \"gnirts\"\nsort_string(\"banana\", \"abn\") == \"aaabnn\"\n```\n\nTo elaborate, the second string defines the ordering. It is possible that in the second string characters repeat, so you should remove repeating characters, leaving only the first occurrence.\n\nAny character in the first string that does not appear in the second string should be sorted to the end of the result in original order.", "solutions": ["def sort_string(s, ordering):\n answer = ''\n for o in ordering:\n answer += o * s.count(o)\n s = s.replace(o, '')\n return answer + s", "def sort_string(s, ordering):\n dct = {c: -i for (i, c) in enumerate(reversed(ordering))}\n return ''.join(sorted(s, key=lambda c: dct.get(c, 1)))", "sort_string = lambda s, o: ''.join(sorted(s, key=lambda x, d={c: i for (i, c) in reversed(list(enumerate(o)))}: d.get(x, len(o))))", "def sort_string(st, order):\n return ''.join(sorted(list(st), key=lambda e: list(order).index(e) if e in order else len(order)))", "def sort_string(stg, ordering):\n return ''.join(sorted(stg, key=lambda c: ordering.index(c) if c in ordering else float('inf')))", "def sort_string(s, ordering):\n order = {}\n for (i, c) in enumerate(ordering):\n if c in order:\n continue\n order[c] = i\n return ''.join(sorted(s, key=lambda c: order.get(c, 9999)))", "def sort_string(s, ordering):\n result = ''\n for i in ordering:\n if i in s and i not in result:\n result += i * s.count(i)\n return result + ''.join([c for c in s if c not in ordering])", "def sort_string(s, ordering):\n result = sorted([c for c in s if c in ordering], key=ordering.find)\n result.extend([c for c in s if c not in ordering])\n return ''.join(result)", "def sort_string(a, b):\n li = list(filter(lambda x: x in b, a))\n return ''.join(sorted(li, key=b.index) + [i for i in a if i not in li])", "def sort_string(s, ordering):\n return ''.join(sorted([i for i in s if i in ordering], key=lambda x: ordering.index(x))) + ''.join(sorted([j for j in s if j not in ordering], key=lambda x: s.index(s)))"], "starter_code": "def sort_string(s, ordering):\n", "input_output": {"fn_name": "sort_string", "inputs": [["banana", "abn"], ["banana", "xyz"], ["banana", "an"], ["foos", "of"], ["string", "gnirts"], ["banana", "a"], ["bungholio", "aacbuoldiiaoh"], ["fumyarhncujlj", "nsejcwn"]], "outputs": [["aaabnn"], ["banana"], ["aaannb"], ["oofs"], ["gnirts"], ["aaabnn"], ["buoolihng"], ["njjcfumyarhul"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms", "Sorting"], "name": null, "source": "codewars", "tags": ["String algorithms", "Sorting"], "skill_types": ["Sorting"], "url": "https://www.codewars.com/kata/536c6b8749aa8b3c2600029a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sort_string", "task_id": "TACO_lite/349", "example": [[["foos", "of"], ["string", "gnirts"], ["banana", "abn"]], ["oofs", "gnirts", "aaabnn"]]} +{"requirement": "If you have not ever heard the term **Arithmetic Progrossion**, refer to: \nhttp://www.codewars.com/kata/find-the-missing-term-in-an-arithmetic-progression/python\n\nAnd here is an unordered version. Try if you can survive lists of **MASSIVE** numbers (which means time limit should be considered). :D\n\nNote: Don't be afraid that the minimum or the maximum element in the list is missing, e.g. [4, 6, 3, 5, 2] is missing 1 or 7, but this case is excluded from the kata.\n\nExample:\n\n```python\nfind([3, 9, 1, 11, 13, 5]) # => 7\n```", "solutions": ["def find(seq):\n return (min(seq) + max(seq)) * (len(seq) + 1) / 2 - sum(seq)", "def find(a):\n return (max(a) + min(a)) * (len(a) + 1) / 2 - sum(a)", "def find(seq):\n (a, b, c) = (max(seq), min(seq), len(seq))\n z = list(range(b, a, (a - b) // c))\n return list(set(z) - set(seq))[0]", "def find(nums):\n return (min(nums) + max(nums)) * (len(nums) + 1) / 2 - sum(nums)", "def find(seq):\n if len(seq) <= 1:\n return seq\n seq.sort()\n x = []\n t = 0\n for i in range(len(seq) - 1):\n if i == 0:\n t = seq[i + 1] - seq[i]\n x.append(t)\n else:\n t = seq[i + 1] - seq[i]\n if t != x[-1]:\n x.append(t)\n break\n else:\n x.append(t)\n return min(seq) + len(x) * x[0]", "def find(seq):\n (a, b, n) = (min(*seq), max(*seq), len(seq))\n m = (b - a) // n\n return m * abs(sum(((x - a) // m for x in seq)) - (n + 1) * n // 2) + a", "find = lambda s: (min(s) + max(s)) * -~len(s) / 2 - sum(s)", "def find(seq):\n seq.sort()\n pattern = abs(seq[0] - seq[1])\n for i in range(len(seq) - 1):\n if seq[i] != seq[i + 1] - pattern:\n return seq[i] + pattern", "def find(seq):\n seq.sort()\n (first, last) = (seq[0], seq[-1])\n d = min(seq[1] - first, seq[2] - seq[1])\n n = (last - first) * 1.0 / d + 1\n s = n / 2 * (first + last)\n s_ = sum(seq)\n return s - s_", "def find(seq):\n prev = 0\n curr = 0\n seq.sort()\n length = len(seq)\n diff = (seq[length - 1] - seq[0]) / length\n for i in range(1, len(seq)):\n if seq[i] == seq[curr] + diff:\n prev = curr\n curr = i\n else:\n return int(seq[curr] + diff)"], "starter_code": "def find(seq):\n", "input_output": {"fn_name": "find", "inputs": [[[3, 9, 1, 11, 13, 5]], [[5, -1, 0, 3, 4, -3, 2, -2]], [[2, -2, 8, -8, 4, -4, 6, -6]]], "outputs": [[7], [1], [0]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Performance", "Algorithms"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/568fca718404ad457c000033", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "find", "task_id": "TACO_lite/373", "example": [[[[3, 9, 1, 11, 13, 5]]], ["7"]]} +{"requirement": "Given two strings denoting non-negative numbers X and Y. Calculate the sum of X and Y. \nExample 1:\nInput:\nX = \"25\", Y = \"23\"\nOutput:\n48\nExplanation:\nThe sum of 25 and 23 is 48.\nExample 2:\nInput:\nX = \"2500\", Y = \"23\"\nOutput:\n2523\nExplanation:\nThe sum of 2500 and 23 is 2523.\nYour Task:\nYour task is to complete the function findSum() which takes two strings as inputs and returns the string without leading zeros. You do not need to take any input or print anything.\nExpected Time Complexity: O(|X| + |Y|)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= |X|, |Y| <= 10^{5}", "solutions": ["def findsum(X, Y):\n self.X = int(X)\n self.Y = int(Y)\n result = self.X + self.Y\n return result", "def findsum(X, Y):\n sum = int(X) + int(Y)\n return sum", "def findsum(X, Y):\n x = int(X)\n y = int(Y)\n A = str(x + y)\n return A", "def findsum(X, Y):\n x = int(X)\n y = int(Y)\n ans = x + y\n return ans", "def findsum(X, Y):\n d1 = int(X)\n d2 = int(Y)\n return d1 + d2", "def findsum(X, Y):\n return str(int(X) + int(Y))", "def findsum(X, Y):\n a = int(X)\n b = int(Y)\n return a + b", "def findsum(X, Y):\n num1 = int(X)\n num2 = int(Y)\n return num1 + num2", "def findsum(X, Y):\n x_pointer = len(X) - 1\n y_pointer = len(Y) - 1\n carry = 0\n string = ''\n while x_pointer >= 0 and y_pointer >= 0:\n num1 = ord(X[x_pointer]) - ord('0')\n num2 = ord(Y[y_pointer]) - ord('0')\n num = num1 + num2\n num += carry\n last_digit = num % 10\n carry = num // 10\n string += str(last_digit)\n x_pointer -= 1\n y_pointer -= 1\n while x_pointer >= 0:\n num1 = ord(X[x_pointer]) - ord('0')\n num = num1 + carry\n last_digit = num % 10\n carry = num // 10\n string += str(last_digit)\n x_pointer -= 1\n while y_pointer >= 0:\n num2 = ord(Y[y_pointer]) - ord('0')\n num = num2 + carry\n last_digit = num % 10\n carry = num // 10\n string += str(last_digit)\n y_pointer -= 1\n if carry:\n string += str(carry)\n string = string[::-1]\n string = string.lstrip('0')\n if not string:\n return '0'\n return string", "def findsum(X, Y):\n s = int(X) + int(Y)\n return s", "def findsum(x, y):\n a = int(x)\n b = int(y)\n return a + b", "def findsum(X, Y):\n num1 = int(X)\n num2 = int(Y)\n total = num1 + num2\n result = str(total)\n if result == '0':\n return result\n else:\n result = result.lstrip('0')\n return result", "def findsum(X, Y):\n x = int(X)\n y = int(Y)\n sum = x + y\n return int(sum)", "def findsum(X, Y):\n z = int(X) + int(Y)\n return z", "def findsum(X, Y):\n c = int(X) + int(Y)\n return c", "def findsum(X, Y):\n q = int(X)\n w = int(Y)\n s = str(q + w)\n return s", "def findsum(X, Y):\n z = int(X)\n y = int(Y)\n sum = z + y\n return sum", "def findsum(X, Y):\n e = int(x)\n s = int(y)\n d = e + s\n return d", "def findsum(x, y):\n s = int(x) + int(y)\n return str(s)", "def findsum(X, Y):\n a1 = int(X)\n a2 = int(Y)\n return a1 + a2", "def findsum(X, Y):\n a = int(X)\n b = int(Y)\n result = a + b\n return str(result)", "def findsum(X, Y):\n n = int(X) + int(Y)\n return n", "def findsum(X, Y):\n temp1 = int(X)\n temp2 = int(Y)\n return str(temp1 + temp2)", "def findsum(X, Y):\n a = int(x)\n b = int(y)\n c = a + b\n return c", "def getNum(str):\n pos = 1\n res = 0\n for i in range(len(str) - 1, -1, -1):\n res += (ord(str[i]) - ord('0')) * pos\n pos *= 10\n return res\n\ndef findsum(X, Y):\n return int(X) + int(Y)", "def findsum(X, Y):\n n1 = int(X)\n n2 = int(Y)\n return n1 + n2", "def findsum(X, Y):\n t = int(X)\n t1 = int(Y)\n return t + t1", "def findsum(X, Y):\n (i, j) = (len(X) - 1, len(Y) - 1)\n output = []\n carry = 0\n while i >= 0 and j >= 0:\n sum = int(X[i]) + int(Y[j]) + carry\n (carry, curr_sum) = (int(sum / 10), sum % 10)\n output.append(str(curr_sum))\n i -= 1\n j -= 1\n while i >= 0:\n sum = int(X[i]) + carry\n (carry, curr_sum) = (int(sum / 10), sum % 10)\n output.append(str(curr_sum))\n i -= 1\n while j >= 0:\n sum = int(Y[j]) + carry\n (carry, curr_sum) = (int(sum / 10), sum % 10)\n output.append(str(curr_sum))\n j -= 1\n if carry:\n output.append(str(carry))\n return int(''.join(reversed(output)))", "def findsum(X, Y):\n x_int = int(X)\n y_int = int(Y)\n result = x_int + y_int\n return str(result)", "def findsum(X, Y):\n X = int(X)\n Y = int(Y)\n Z = X + Y\n return Z", "def findsum(X, Y):\n p = int(X)\n q = int(Y)\n return p + q", "def findsum(X, Y):\n first = int(X)\n second = int(Y)\n ans = str(first + second)\n return ans", "def findsum(X, Y):\n int1 = int(X)\n int2 = int(Y)\n return int1 + int2", "def findsum(X, Y):\n total = int(X) + int(Y)\n return total"], "starter_code": "def findsum(X, Y):\n", "input_output": {"inputs": ["X = \"25\", Y = \"23\"", "X = \"2500\", Y = \"23\""], "outputs": ["48", "2523"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/sum-of-numbers-or-number1219/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|X| + |Y|)", "entry_point": "findsum", "task_id": "TACO_lite/343", "example": [[["25", "23"], ["2500", "23"]], ["48", "2523"]]} +{"requirement": "Write a program that will calculate the number of trailing zeros in a factorial of a given number.\n\n`N! = 1 * 2 * 3 * ... * N`\n\nBe careful `1000!` has 2568 digits...\n\nFor more info, see: http://mathworld.wolfram.com/Factorial.html \n\n## Examples\n\n```python\nzeros(6) = 1\n# 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero\n\nzeros(12) = 2\n# 12! = 479001600 --> 2 trailing zeros\n```\n\n*Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros.*", "solutions": ["def zeros(n):\n pow_of_5 = 5\n zeros = 0\n while n >= pow_of_5:\n zeros += n // pow_of_5\n pow_of_5 *= 5\n return zeros", "def zeros(n):\n zeros = 0\n i = 5\n while n // i > 0:\n zeros += n // i\n i *= 5\n return zeros", "def zeros(n):\n return 0 if int(n / 5) < 1 else int(n / 5) + int(zeros(n / 5))", "def zeros(n):\n count = 0\n while n:\n n = n // 5\n count += n\n return count", "import math\n\ndef zeros(n):\n if n >= 5:\n return math.floor(n / 5) + zeros(n / 5)\n else:\n return 0", "def find_factor(p, n):\n (result, power) = (0, p)\n while power < n:\n result += n // power\n power *= p\n return result\n\ndef zeros(n):\n return min((find_factor(p, n) for p in (2, 5)))", "from math import log, floor\n\ndef zeros(n):\n if n < 5:\n return 0\n powers = range(1, floor(log(n, 5)) + 1)\n return sum((n // div for div in (5 ** pw for pw in powers)))", "from math import log, ceil\n\ndef zeros(n):\n return sum((n // 5 ** i for i in range(1, ceil(log(n, 5))))) if n > 0 else 0", "def zeros(n):\n res = 0\n while n >= 5:\n res += n // 5\n n //= 5\n return res", "def zeros(n):\n c = 0\n r = 1\n while 5 ** r <= n:\n c += len(range(5 ** r, n + 1, 5 ** r))\n r += 1\n return c", "def zeros(n):\n a = n // 5\n if a >= 5:\n return a + zeros(a)\n else:\n return a", "def zeros(n):\n sum = 0\n for i in range(1, 30):\n sum += n // 5 ** i\n return sum", "def zeros(n):\n result = 0\n i = 5\n while n / i >= 1:\n result += int(n / i)\n i *= 5\n return int(result)", "def zeros(n):\n (c, x) = (0, 5)\n while n > x:\n c += n // x\n x *= 5\n return c", "from math import floor\n\ndef zeros(n):\n sum = 0\n power = 1\n while n / 5 ** power >= 1:\n sum += floor(n / 5 ** power)\n power += 1\n return sum", "def zeros(n):\n (i, j) = (1, 0)\n while 5 ** i <= n:\n (i, j) = (i + 1, j + int(n / 5 ** i))\n return j", "def zeros(n):\n (base, total) = (5, 0)\n while n > base:\n total += n // base\n base *= 5\n return total", "def zeros(n):\n p = 0\n sum = 0\n while n > 5 ** p:\n p += 1\n sum += n // 5 ** p\n return sum", "from itertools import takewhile, count\nfrom operator import truth\n\ndef zeros(n):\n return sum(takewhile(truth, (n // 5 ** e for e in count(1))))", "zeros = lambda n: n // 5 + zeros(n / 5) if n / 5 else 0", "from itertools import count, takewhile\npow5 = lambda x: 5 ** x\n\ndef zeros(n):\n okay = lambda x: x <= n\n val = lambda x: n // x\n return sum(map(val, takewhile(okay, map(pow5, count(1)))))", "def zeros(n):\n if n / 5 <= 0:\n return 0\n else:\n n //= 5\n return n + zeros(n)", "import math\n\ndef zeros(n):\n if n == 0:\n return 0\n fives = 0\n log5n = int(math.log10(n) / math.log10(5))\n for i in range(1, log5n + 1):\n fives += int(n / 5 ** i)\n return int(fives)", "def zeros(n):\n count = 0\n i = 5\n while n / i >= 1:\n count += int(n / i)\n i *= 5\n return int(count)", "def zeros(n):\n t = 5\n s = 0\n while n > t:\n s += n // t\n t *= 5\n return s", "import math\n\ndef zeros(n):\n Zeros = 0\n i = 5\n while i <= n:\n Zeros += math.floor(n / i)\n i *= 5\n return Zeros", "def zeros(n):\n return sum((n // 5 ** i for i in range(1, 20)))", "import math\n\ndef zeros(n):\n return 0 if n < 2 else sum([n // 5 ** f for f in range(1, max(2, int(math.log(n)))) if 5 ** f <= n])", "import math\n\ndef zeros(n: int):\n if n < 5:\n return 0\n log_n_5 = int(math.log(n, 5))\n return sum([n // 5 ** i for i in range(1, log_n_5 + 1)])", "def zeros(n):\n n = n // 5\n number = n\n while n != 0:\n n = n // 5\n number += n\n return number", "def zeros(n):\n i = 1\n res = 0\n while 5 ** i < n:\n res += n // 5 ** i\n i += 1\n return res", "import math\n\ndef zeros(n):\n sum = 0\n if n < 5:\n return 0\n for i in range(1, math.floor(math.log(n, 5) + 1)):\n sum += math.floor(n / pow(5, i))\n return sum", "def zeros(n):\n num_5 = n\n num_2 = n\n n_5 = 0\n n_2 = 0\n while num_5 != 0:\n n_5 += num_5 // 5\n num_5 = num_5 // 5\n return n_5", "from math import factorial\n\ndef zeros(n):\n if n == 0:\n return 0\n cnt = 0\n div_num = 5\n while n / div_num >= 1:\n cnt += int(n / div_num)\n div_num *= 5\n return cnt", "def zeros(n):\n count = 0\n divider = 5\n while n / divider >= 1:\n count += int(n / divider)\n divider *= 5\n return int(count)", "import math\n\ndef zeros(n):\n count = 0\n if n == 0:\n return 0\n else:\n k_max = math.floor(math.log(n, 5))\n for i in range(k_max):\n ans = math.floor(n / 5 ** (i + 1))\n count = count + ans\n return count", "def zeros(n):\n divisor = 5\n count = 0\n while n > divisor:\n count = count + int(n / divisor)\n divisor *= 5\n return count", "def zeros(n):\n if n == 0:\n return 0\n value = 0\n i = 1\n while True:\n if n > 5 ** i:\n value += n // 5 ** i\n else:\n return value\n i += 1", "def zeros(n):\n return sum([n // 5 ** i for i in range(1, len(str(n)) + len(str(n // 1000 + 1)))])", "def zeros(n):\n x = 0\n z = 5\n while n > 0:\n n /= 5\n x += int(n)\n return x", "def zeros(n):\n i = 5\n count_5 = 0\n while n // i >= 1:\n count_5 += n // i\n i *= 5\n return count_5", "import math\n\ndef zeros(n):\n if n <= 0:\n return 0\n k_max = math.floor(math.log(n, 5)) + 1\n sum = 0\n for k in range(1, k_max):\n sum += math.floor(n / 5 ** k)\n return sum", "def zeros(n):\n (i, count) = (20, 0)\n while i > 0:\n count += n // 5 ** i\n i -= 1\n return count", "def zeros(n):\n answer = 0\n for i in range(1, 100):\n answer += int(n / 5 ** i)\n return answer", "def zeros(n):\n sum = 0\n d = 5\n while d <= n:\n sum += n // d\n d *= 5\n return sum", "def zeros(n):\n p = n // 5\n t = p\n while t > 0:\n t = t // 5\n p = p + t\n return p", "from math import log\n\ndef zeros(n):\n if n == 0:\n return 0\n y = 0\n for x in range(1, int(log(n, 5) + 1)):\n y += n // 5 ** x\n return y", "from math import *\n\ndef zeros(n):\n res = 0\n i = 5\n while i < n:\n res += floor(n / i)\n i *= 5\n return res", "def zeros(n):\n b = 0\n while 5 ** b < n:\n b += 1\n return sum((n // 5 ** c for c in range(1, b)))", "def zeros(n):\n result = 0\n power = 1\n while True:\n if 5 ** power > n:\n break\n result += n // 5 ** power\n power += 1\n return result", "import math\n\ndef zeros(n):\n ret = 0\n if n == 0:\n return 0\n for i in range(1, int(math.log(n) / math.log(5)) + 1):\n ret += n // math.pow(5, i)\n return ret", "import math\n\ndef zeros(n):\n if n == 0:\n return 0\n z = 0\n kmax = math.floor(math.log(n) / math.log(5))\n for i in range(1, kmax + 1):\n z += math.floor(n / 5 ** i)\n return z", "from math import log\n\ndef zeros(n):\n if n == 0:\n return 0\n z = 0\n k = 1\n kMax = round(log(n, 5))\n for i in range(k, kMax + 1):\n z += n // 5 ** i\n return z", "def zeros(n):\n num_zero = 0\n while n > 0:\n n = n // 5\n num_zero += n\n return num_zero", "def zeros(n):\n sums = []\n while n > 5:\n n /= 5\n sums.append(int(n))\n a = 0\n for num in sums:\n a += int(num)\n return int(a)", "def zeros(n):\n i = 1\n x = 0\n while 5 ** i <= n:\n x += n // 5 ** i\n i += 1\n return x", "from math import log\n\ndef zeros(n):\n if n == 0:\n return 0\n z = 0\n i = 1\n while i < log(n, 5):\n z += n // 5 ** i\n i += 1\n return z", "import math\n\ndef zeros(n):\n zeroes = 0\n k = 1\n while n / 5 ** k > 1:\n zeroes += math.floor(n / 5 ** k)\n k += 1\n return zeroes", "def zeros(n):\n zeros = 0\n tmp = n\n while tmp >= 1:\n tmp /= 5\n zeros += int(tmp)\n return zeros", "import math\n\ndef zeros(n):\n return sum((int(n / math.pow(5, i)) for i in range(1, 15) if int(n / math.pow(5, i)) != 0))", "def zeros(n):\n\n def find_exponent(n, p):\n factor = 0\n p_helper = p\n while n > p_helper:\n factor += int(n / p_helper)\n p_helper *= p\n return factor\n five_exponent = find_exponent(n, 5)\n return five_exponent", "def zeros(n):\n\n def find_exponent(n, p):\n factor = 0\n p_helper = p\n while n > p_helper:\n factor += int(n / p_helper)\n p_helper *= p\n return factor\n two_exponent = find_exponent(n, 2)\n five_exponent = find_exponent(n, 5)\n return min(two_exponent, five_exponent)", "import math\n\ndef zeros(n):\n count = 0\n i = 5\n while n / i >= 1:\n count += int(n / i)\n i *= 5\n return int(count)"], "starter_code": "def zeros(n):\n", "input_output": {"fn_name": "zeros", "inputs": [[0], [6], [30], [100], [1000], [100000], [1000000000]], "outputs": [[0], [1], [7], [24], [249], [24999], [249999998]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Logic"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/52f787eb172a8b4ae1000a34", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "zeros", "task_id": "TACO_lite/344", "example": [[[6], [12]], ["1", "2"]]} +{"requirement": "Given an array of numbers (in string format), you must return a string. The numbers correspond to the letters of the alphabet in reverse order: a=26, z=1 etc. You should also account for `'!'`, `'?'` and `' '` that are represented by '27', '28' and '29' respectively.\n\nAll inputs will be valid.", "solutions": ["def switcher(arr):\n d = {str(i): chr(123 - i) for i in range(1, 27)}\n d.update({'27': '!'})\n d.update({'28': '?'})\n d.update({'29': ' '})\n d.update({'0': ''})\n return ''.join([d[str(i)] for i in arr])", "import string\nletters = string.ascii_lowercase[::-1] + '!? '\n\ndef switcher(arr):\n return ''.join([letters[ch - 1] for ch in map(int, arr) if ch])", "chars = '_zyxwvutsrqponmlkjihgfedcba!? '\n\ndef switcher(arr):\n return ''.join((chars[int(i)] for i in arr if i != '0'))", "from string import ascii_lowercase as abc\nch = abc[::-1] + '!? '\n\ndef switcher(arr):\n return ''.join((ch[int(x) - 1] if x != '0' else '' for x in arr))", "def switcher(arr):\n trans = {'26': 'a', '25': 'b', '24': 'c', '23': 'd', '22': 'e', '21': 'f', '20': 'g', '19': 'h', '18': 'i', '17': 'j', '16': 'k', '15': 'l', '14': 'm', '13': 'n', '12': 'o', '11': 'p', '10': 'q', '9': 'r', '8': 's', '7': 't', '6': 'u', '5': 'v', '4': 'w', '3': 'x', '2': 'y', '1': 'z', '27': '!', '28': '?', '29': ' '}\n return ''.join((trans[a] for a in arr if a in trans))", "STR = '+zyxwvutsrqponmlkjihgfedcba!? '\n\ndef switcher(arr):\n return ''.join((STR[int(x)] for x in arr)).replace('+', '')", "def switcher(arr):\n return ''.join(({'27': '!', '28': '?', '29': ' '}.get(e, chr(abs(int(e) - 26) + 97)) for e in arr))", "alphabet = ['z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a', '!', '?', ' ']\n\ndef switcher(arr):\n return ''.join([alphabet[int(i) - 1] for i in arr])", "def switcher(arr):\n return ''.join((chr(123 - int(i)) for i in arr)).translate(str.maketrans('`_^', '!? '))", "def switcher(arr):\n return ''.join(({'27': '!', '28': '?', '29': ' '}.get(i, chr(123 - int(i))) for i in arr))"], "starter_code": "def switcher(arr):\n", "input_output": {"fn_name": "switcher", "inputs": [[["24", "12", "23", "22", "4", "26", "9", "8"]], [["25", "7", "8", "4", "14", "23", "8", "25", "23", "29", "16", "16", "4"]], [["4", "24"]], [["12"]], [["12", "28", "25", "21", "25", "7", "11", "22", "15"]]], "outputs": [["codewars"], ["btswmdsbd kkw"], ["wc"], ["o"], ["o?bfbtpel"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57ebaa8f7b45ef590c00000c", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "switcher", "task_id": "TACO_lite/402", "example": [[[["26", "1", "13", "3", "1"]], [["28", "27", "29", "1"]]], ["azmca", "?! a"]]} +{"requirement": "The number ```12``` is the first number in having six divisors, they are: ```1, 2, 3, 4, 6 and 12.```\nYour challenge for this kata is to find the minimum number that has a certain number of divisors.\nFor this purpose we have to create the function \n\n```find_min_num() or findMinNum() or similar in the other languages```\n\nthat receives the wanted number of divisors ```num_div```, and outputs the smallest number having an amount of divisors equals to ```num_div```.\n\nLet's see some cases:\n```\nfind_min_num(10) = 48 # divisors are: 1, 2, 3, 4, 6, 8, 12, 16, 24 and 48\nfind_min_num(12) = 60\n```\nIn this kata all the tests will be with ```numDiv < 80```\n\n(There will be a next kata with numDiv < 10000, Find the First Number Having a Certain Number of Divisors II, should have the help of number theory)\n\nEnjoy it and happy coding!\n(Memoization is advisable)", "solutions": ["def find_min_num(d, n=1):\n while div_num(n) != d:\n n += 1\n return n\n\ndef div_num(n):\n s = n ** 0.5\n return sum((2 for k in range(1, int(s) + 1) if n % k == 0)) - (s % 1 == 0)", "from collections import Counter\n\ndef number_of_div(n):\n i = 2\n factors = []\n while i * i <= n:\n if n % i:\n i += 1\n else:\n n //= i\n factors.append(i)\n if n > 1:\n factors.append(n)\n mu = 1\n po = [i + 1 for i in list(Counter(factors).values())]\n for i in po:\n mu *= i\n return mu\n\ndef find_min_num(num_div):\n for i in range(1, num_div ** 4):\n num = number_of_div(i)\n if num == num_div:\n return i", "def n_div(n):\n result = 0\n for i in range(1, int(n ** 0.5) + 1):\n if n % i == 0:\n result += 1 + (i * i < n)\n return result\n\ndef find_min_num(num_div):\n for i in range(num_div, 1000000):\n if n_div(i) == num_div:\n return i", "(FOUND, n) = ({}, 1)\nwhile len(FOUND) < 60:\n sq = n ** 0.5\n nDivs = sum((2 * (not n % x) for x in range(1, int(sq) + 1))) - (int(sq) == sq)\n if nDivs not in FOUND:\n FOUND[nDivs] = n\n n += 1\n\ndef find_min_num(nDivs):\n return FOUND[nDivs]", "def count_divs(n):\n is_square = 0\n if n ** 0.5 % 1 == 0:\n is_square = 1\n return len([(x, n / x) for x in range(1, int(n ** 0.5) + 1) if n % x == 0]) * 2 - is_square\nmin_num = {count_divs(i): i for i in reversed(range(1, 10 ** 5))}\n\ndef find_min_num(num_div):\n return min_num[num_div]", "def divisors(n):\n count = 2\n i = 2\n while i ** 2 < n:\n if n % i == 0:\n count += 2\n i += 1\n if i ** 2 == n:\n count += 1\n return count\n\ndef find_min_num(num):\n i = 2\n while True:\n d = divisors(i)\n if d == num:\n return i\n i += 1", "find_min_num = lambda n: [0, 1, 2, 4, 6, 16, 12, 64, 24, 36, 48, 1024, 60, 4096, 192, 144, 120, 65536, 180, 0, 240, 576, 3072, 0, 360, 1296, 12288, 900, 960, 0, 720, 0, 840, 9216, 0, 5184, 1260, 0, 0, 36864, 1680, 0, 2880, 0, 15360, 3600, 0, 0, 2520, 46656, 6480, 0, 61440, 0, 6300, 0, 6720, 0, 0, 0, 5040, 0, 0, 14400, 7560, 0, 46080, 0, 0, 0, 25920, 0, 10080, 0, 0, 32400, 0, 0, 0, 0, 15120, 44100, 0, 0, 20160, 0, 0, 0, 0, 0, 25200, 0, 0, 0, 0, 0, 27720, 0, 0, 0, 45360][n]", "def check(n):\n set1 = set()\n for i in range(1, int(n ** 0.5) + 1):\n if n % i == 0:\n set1.add(i)\n set1.add(n // i)\n return set1\n\ndef find_min_num(num_div):\n i = 1\n while 1:\n if len(check(i)) == num_div:\n return i\n i += 1\n return n"], "starter_code": "def find_min_num(d, n=1):\n", "input_output": {"fn_name": "find_min_num", "inputs": [[6], [10], [12], [13]], "outputs": [[12], [48], [60], [4096]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals", "Memoization", "Data Structures", "Dynamic Programming"], "name": null, "source": "codewars", "tags": ["Dynamic programming", "Fundamentals", "Data structures", "Mathematics"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://www.codewars.com/kata/5612ab201830eb000f0000c0", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "find_min_num", "task_id": "TACO_lite/404", "example": [[[10], [12]], ["48", "60"]]} +{"requirement": "You're a programmer in a SEO company. The SEO specialist of your company gets the list of all project keywords everyday, then he looks for the longest keys to analyze them.\n\nYou will get the list with keywords and must write a simple function that returns the biggest search keywords and sorts them in lexicographical order.\n\nFor instance you might get:\n```python\n'key1', 'key2', 'key3', 'key n', 'bigkey2', 'bigkey1'\n```\n\nAnd your function should return:\n```python\n\"'bigkey1', 'bigkey2'\"\n```\n\nDon't forget to rate this kata! Thanks :)", "solutions": ["def the_biggest_search_keys(*keys):\n L = sorted(keys, key=lambda key: (-len(key), key))\n i = next((i for (i, key) in enumerate(L) if len(key) != len(L[0])), None)\n return str(L[:i])[1:-1] or \"''\"", "def the_biggest_search_keys(*arg):\n mx = len(max(arg, key=len, default=''))\n return ', '.join(sorted((f\"'{e}'\" for e in list(arg) + [''] if len(e) == mx)))", "def the_biggest_search_keys(*keys):\n if not keys:\n return \"''\"\n n = max(map(len, keys))\n keys = sorted([key for key in keys if len(key) == n])\n return ', '.join((f\"'{key}'\" for key in keys))", "def the_biggest_search_keys(*keys):\n m = max(map(len, keys)) if keys else None\n return str(sorted(filter(lambda x: len(x) == m, keys)))[1:-1] if keys else \"''\"", "def the_biggest_search_keys(*keys):\n if not keys:\n keys = ['']\n longest_key_length = max(map(len, keys))\n return ', '.join(sorted((\"'%s'\" % key for key in keys if len(key) == longest_key_length)))", "def the_biggest_search_keys(*args):\n by_len = {}\n fmt = \"'{}'\".format\n for a in args:\n by_len.setdefault(len(a), []).append(a)\n try:\n return ', '.join((fmt(b) for b in sorted(by_len[max(by_len)])))\n except ValueError:\n return \"''\"", "def the_biggest_search_keys(*keys):\n (biggest, max_len) = ([], 0)\n for key in keys:\n key_len = len(key)\n if key_len == max_len:\n biggest.append(key)\n elif key_len > max_len:\n (biggest, max_len) = ([key], key_len)\n return ', '.join((\"'{}'\".format(key) for key in sorted(biggest))) or \"''\"", "def the_biggest_search_keys(*keys):\n if not keys:\n return \"''\"\n max_len = 0\n for key in keys:\n key_len = len(key)\n if key_len > max_len:\n max_len = key_len\n result = [key]\n elif key_len == max_len:\n result += [key]\n return str(sorted(result))[1:-1]", "def the_biggest_search_keys(*args):\n maxLen = max(map(len, args), default=None)\n return \"''\" if not args else ', '.join(sorted(filter(lambda s: len(s) - 2 == maxLen, map(lambda s: \"'{}'\".format(s), args))))", "def the_biggest_search_keys(*keywords):\n return ', '.join(sorted((f\"'{x}'\" for x in keywords if len(x) == max(map(len, keywords))))) if keywords else \"''\""], "starter_code": "def the_biggest_search_keys(*keys):\n", "input_output": {"fn_name": "the_biggest_search_keys", "inputs": [["key1", "key22", "key333"], ["coding", "sorting", "tryruby"], ["small keyword", "how to coding?", "very nice kata", "a lot of keys", "I like Ruby!!!"], ["pippi"]], "outputs": [["'key333'"], ["'sorting', 'tryruby'"], ["'I like Ruby!!!', 'how to coding?', 'very nice kata'"], ["'pippi'"]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/58ac1abdff4e78738f000805", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "the_biggest_search_keys", "task_id": "TACO_lite/414", "example": [[["key1", "key2", "key3", "key n", "bigkey2", "bigkey1"]], ["('bigkey1', 'bigkey2')"]]} +{"requirement": "Given a binary tree root, a ZigZag path for a binary tree is defined as follow:\n\nChoose any node in the binary tree and a direction (right or left).\nIf the current direction is right then move to the right child of the current node otherwise move to the left child.\nChange the direction from right to left or right to left.\nRepeat the second and third step until you can't move in the tree.\n\nZigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).\nReturn the longest ZigZag path contained in that tree.\n \nExample 1:\n\nInput: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]\nOutput: 3\nExplanation: Longest ZigZag path in blue nodes (right -> left -> right).\n\nExample 2:\n\nInput: root = [1,1,1,null,1,null,null,1,1,null,1]\nOutput: 4\nExplanation: Longest ZigZag path in blue nodes (left -> right -> left -> right).\n\nExample 3:\nInput: root = [1]\nOutput: 0\n\n \nConstraints:\n\nEach tree has at most 50000 nodes..\nEach node's value is between [1, 100].", "solutions": ["def longestZigZag(root: TreeNode) -> int:\n if root == None:\n return None\n maxlength = 0\n stack = collections.deque()\n if root.left:\n stack.append((1, 1, root.left))\n if root.right:\n stack.append((1, 0, root.right))\n while stack:\n (length, isleft, node) = stack.pop()\n if isleft:\n if node.right:\n stack.append((length + 1, 0, node.right))\n else:\n maxlength = max(maxlength, length)\n if node.left:\n stack.append((1, 1, node.left))\n else:\n if node.left:\n stack.append((length + 1, 1, node.left))\n else:\n maxlength = max(maxlength, length)\n if node.right:\n stack.append((1, 0, node.right))\n return maxlength", "def longestZigZag(root: TreeNode) -> int:\n stack = [(root, 0, 'left')]\n res = 0\n while stack:\n (node, length, d) = stack.pop()\n res = max(res, length)\n if node.left:\n if d != 'left':\n stack.append((node.left, length + 1, 'left'))\n else:\n stack.append((node.left, 1, 'left'))\n if node.right:\n if d != 'right':\n stack.append((node.right, length + 1, 'right'))\n else:\n stack.append((node.right, 1, 'right'))\n return res", "from collections import deque\n\ndef longestZigZag(root: TreeNode) -> int:\n ans = 0\n q = deque([[root, 'A', 0]])\n while len(q) != 0:\n (top, state, dist) = q[0]\n ans = max(ans, dist)\n q.popleft()\n if state == 'A':\n if top.left:\n q.append([top.left, 'L', 1])\n if top.right:\n q.append([top.right, 'R', 1])\n else:\n if state == 'L':\n if top.left:\n q.append([top.left, 'L', 1])\n if top.right:\n q.append([top.right, 'R', dist + 1])\n if state == 'R':\n if top.left:\n q.append([top.left, 'L', dist + 1])\n if top.right:\n q.append([top.right, 'R', 1])\n return ans", "def longestZigZag(root: TreeNode) -> int:\n\n def dfs(node):\n if not node:\n return [-1, -1, -1]\n left = dfs(node.left)\n right = dfs(node.right)\n return [left[1] + 1, right[0] + 1, max(left[1] + 1, right[0] + 1, left[2], right[2])]\n return dfs(root)[-1]", "def longestZigZag(root: TreeNode) -> int:\n maxlen = 0\n dt = collections.defaultdict(lambda : [0, 0])\n\n def dfs(root, dt):\n nonlocal maxlen\n if root.left:\n dfs(root.left, dt)\n dt[root][0] = dt[root.left][1] + 1\n else:\n dt[root][0] = 0\n if root.right:\n dfs(root.right, dt)\n dt[root][1] = dt[root.right][0] + 1\n else:\n dt[root][1] = 0\n maxlen = max(maxlen, dt[root][0], dt[root][1])\n dfs(root, dt)\n return maxlen", "def helper(node: TreeNode, lastDirection: str, cache) -> int:\n if not node:\n return 0\n if (node, lastDirection) in cache:\n return cache[node, lastDirection]\n count = 1\n childCount = float('-inf')\n if lastDirection == 'right':\n childCount = max(childCount, self.helper(node.left, 'left', cache))\n else:\n childCount = max(childCount, self.helper(node.right, 'right', cache))\n count += childCount\n cache[node, lastDirection] = count\n return count\n\ndef longestZigZag(root: TreeNode) -> int:\n maxCount = float('-inf')\n cache = {}\n stack = [root]\n while stack:\n node = stack.pop()\n maxCount = max(maxCount, self.helper(node, 'left', cache))\n maxCount = max(maxCount, self.helper(node, 'right', cache))\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n return maxCount - 1", "def longestZigZag(root: TreeNode) -> int:\n self.ans = 0\n memo = {}\n\n def dfs2(node, direction):\n if not node:\n return 0\n if (node, direction) not in memo:\n if direction == False:\n memo[node, direction] = 1 + dfs2(node.right, True)\n else:\n memo[node, direction] = 1 + dfs2(node.left, False)\n return memo[node, direction]\n\n def dfs1(node):\n if not node:\n return\n self.ans = max(self.ans, dfs2(node, True) - 1, dfs2(node, False) - 1)\n dfs1(node.left)\n dfs1(node.right)\n dfs1(root)\n return self.ans", "def longestZigZag(root: TreeNode) -> int:\n self.res = 0\n if root.left:\n self.dfs(root.left, 1, True, False)\n if root.right:\n self.dfs(root.right, 1, False, True)\n return self.res\n\ndef dfs(node, count, prevL, prevR):\n if not node:\n return\n self.res = max(self.res, count)\n if prevL:\n self.dfs(node.left, 1, True, False)\n self.dfs(node.right, count + 1, False, True)\n if prevR:\n self.dfs(node.left, count + 1, True, False)\n self.dfs(node.right, 1, False, True)", "def longestZigZag(root: TreeNode) -> int:\n self.res = float(-inf)\n\n def helper(root, left, right):\n self.res = max(self.res, max(left, right))\n if root == None:\n return\n if root.left:\n helper(root.left, right + 1, 0)\n if root.right:\n helper(root.right, 0, left + 1)\n return\n helper(root, 0, 0)\n return self.res", "def longestZigZag(root: TreeNode) -> int:\n ans = [-1]\n\n def aux(root, isleft, ans):\n if not root:\n return -1\n left = aux(root.left, 1, ans) + 1\n right = aux(root.right, 0, ans) + 1\n ans[0] = max(ans[0], left, right)\n if isleft:\n return right\n else:\n return left\n if not root:\n return 0\n aux(root, 0, ans)\n return ans[0]", "def helper(node, prenode, ans):\n if not node:\n return\n self.res = max(self.res, ans)\n if node == prenode.left:\n self.helper(node.right, node, ans + 1)\n self.helper(node.left, node, 1)\n elif node == prenode.right:\n self.helper(node.left, node, ans + 1)\n self.helper(node.right, node, 1)\n\ndef longestZigZag(root: TreeNode) -> int:\n self.res = 0\n self.helper(root.left, root, 1)\n self.helper(root.right, root, 1)\n return self.res", "def longestZigZag(root: TreeNode) -> int:\n\n def zigzag(node: TreeNode) -> tuple:\n if not node:\n return (0, 0)\n (_, lr) = zigzag(node.left)\n (rl, _) = zigzag(node.right)\n self.max_path = max(self.max_path, lr + 1, rl + 1)\n return (lr + 1, rl + 1)\n self.max_path = 0\n zigzag(root)\n return self.max_path - 1", "def longestZigZag(root: TreeNode) -> int:\n if root == None:\n return 0\n maxZigZag = 0\n\n def zigZagStart(root):\n nonlocal maxZigZag\n if root == None or (root.left == None and root.right == None):\n return [0, 0]\n (ll, lr) = zigZagStart(root.left)\n (rl, rr) = zigZagStart(root.right)\n bestLeft = 0\n bestRight = 0\n if root.left:\n bestLeft = 1 + lr\n if root.right:\n bestRight = 1 + rl\n maxZigZag = max(maxZigZag, bestLeft, bestRight)\n return [bestLeft, bestRight]\n zigZagStart(root)\n return maxZigZag", "def longestZigZag(root: TreeNode) -> int:\n self.longest = 0\n self.dfs(root, 0, 0)\n return self.longest\n\ndef dfs(node, longest_left, longest_right):\n self.longest = max(self.longest, longest_left, longest_right)\n if node.left:\n self.dfs(node.left, longest_right + 1, 0)\n if node.right:\n self.dfs(node.right, 0, longest_left + 1)", "def longestZigZag(root):\n\n def dfs(root):\n if not root:\n return [-1, -1, -1]\n (left, right) = (dfs(root.left), dfs(root.right))\n return [left[1] + 1, right[0] + 1, max(left[1] + 1, right[0] + 1, left[2], right[2])]\n return dfs(root)[-1]", "def longestZigZag(root: TreeNode) -> int:\n (_, max_depth) = self.zigzag(root)\n return max_depth\n\ndef zigzag(node: TreeNode, return_left=False) -> int:\n if node is None:\n return (-1, 0)\n (left_depth, left_max) = self.zigzag(node.left)\n (right_depth, right_max) = self.zigzag(node.right, return_left=True)\n left_depth += 1\n right_depth += 1\n max_depth = max(left_depth, right_depth, left_max, right_max)\n return (left_depth if return_left else right_depth, max_depth)", "def longestZigZag(root: TreeNode) -> int:\n\n def longest(node: TreeNode, state: int, acc: int) -> int:\n self.m = max(self.m, acc)\n if not node:\n return 0\n if state == 0:\n (longest(node.right, 1, acc + 1), longest(node.left, 0, 0))\n else:\n (longest(node.left, 0, acc + 1), longest(node.right, 1, 0))\n (longest(root.left, 0, 0), longest(root.right, 1, 0))\n return self.m", "def longestZigZag(root: TreeNode) -> int:\n if not root:\n return 0\n q = deque()\n max_depth = 0\n if root.left:\n q.append((root.left, True, 1))\n if root.right:\n q.append((root.right, False, 1))\n while q:\n (n, is_left, depth) = q.popleft()\n max_depth = max(depth, max_depth)\n if n.left:\n if is_left:\n q.append((n.left, True, 1))\n else:\n q.append((n.left, True, depth + 1))\n if n.right:\n if is_left:\n q.append((n.right, False, depth + 1))\n else:\n q.append((n.right, False, 1))\n return max_depth", "def longestZigZag(root: TreeNode) -> int:\n q = collections.deque()\n res = 0\n q.append((root, 0, 0))\n while q:\n size = len(q)\n for _ in range(size):\n (node, l, r) = q.popleft()\n if node.left:\n q.append((node.left, r + 1, 0))\n res = max(res, r + 1)\n if node.right:\n q.append((node.right, 0, l + 1))\n res = max(res, l + 1)\n return res", "def longestZigZag(root: TreeNode) -> int:\n\n def zigzag(node, left, acum):\n if node is None:\n return acum - 1\n if left:\n return max(zigzag(node.left, False, acum + 1), zigzag(node.left, True, 0))\n else:\n return max(zigzag(node.right, True, acum + 1), zigzag(node.right, False, 0))\n return max(zigzag(root, True, 0), zigzag(root, False, 0))", "def longestZigZag(root: TreeNode) -> int:\n self.max_len = 0\n\n def subTree(root, indir, flip):\n if root is None:\n return 0\n if indir == -1:\n subcount = subTree(root.right, 1, True)\n self.max_len = max(subcount + 1, self.max_len)\n else:\n subcount = subTree(root.left, -1, True)\n self.max_len = max(subcount + 1, self.max_len)\n if flip:\n subTree(root, -indir, False)\n return subcount + 1\n subTree(root, 1, True)\n return self.max_len - 1", "def longestZigZag(root: TreeNode) -> int:\n l = [[root, 0]]\n r = [[root, 0]]\n m = 0\n while True:\n if l == [] and r == []:\n return m\n l1 = []\n r1 = []\n for i in l:\n m = max(m, i[1])\n if i[0].right != None:\n r1.append([i[0].right, i[1] + 1])\n if i[0].left != None:\n r1.append([i[0].left, 0])\n for i in r:\n m = max(m, i[1])\n if i[0].left != None:\n l1.append([i[0].left, i[1] + 1])\n if i[0].right != None:\n l1.append([i[0].right, 0])\n r = r1\n l = l1", "def longestZigZag(root: TreeNode) -> int:\n\n def help(root):\n if not root:\n return [-1, -1, -1]\n (left, right) = (help(root.left), help(root.right))\n return [left[1] + 1, right[0] + 1, max(left[-1], right[-1], left[1] + 1, right[0] + 1)]\n return help(root)[-1]", "def longestZigZag(root: TreeNode) -> int:\n\n def helper(root):\n stack = [[root, True, 0], [root, False, 0]]\n ans = 0\n while stack:\n (root, right, length) = stack.pop()\n if root:\n ans = max(length, ans)\n stack.append((root.right if right else root.left, not right, length + 1))\n stack.append((root.left if right else root.right, right, 1))\n return ans\n return helper(root)", "def __init__():\n self.max_length = float('-inf')\n\ndef longestZigZag(root):\n return self.dfs(root)[2] - 1\n\ndef dfs(root):\n if root is None:\n return [0, 0, 0]\n left_res = self.dfs(root.left)\n right_res = self.dfs(root.right)\n maxForSubtree = max(left_res[1], right_res[0]) + 1\n return [left_res[1] + 1, right_res[0] + 1, max(maxForSubtree, left_res[2], right_res[2])]", "def longestZigZagRec(root, goLeft, steps):\n if root == None:\n return steps - 1\n if goLeft:\n return max(self.longestZigZagRec(root.left, False, steps + 1), self.longestZigZagRec(root.right, True, 1))\n else:\n return max(self.longestZigZagRec(root.right, True, steps + 1), self.longestZigZagRec(root.left, False, 1))\n\ndef longestZigZag(root: TreeNode) -> int:\n if root == None:\n return 0\n return max(self.longestZigZagRec(root, True, 0), self.longestZigZagRec(root, False, 0))", "def longestZigZag(root: TreeNode) -> int:\n self.max_zigzag = 0\n\n def dfs(node, is_left, streak):\n if not node:\n return\n self.max_zigzag = max(self.max_zigzag, streak)\n if is_left:\n dfs(node.right, not is_left, streak + 1)\n dfs(node.right, is_left, 0)\n else:\n dfs(node.left, not is_left, streak + 1)\n dfs(node.left, is_left, 0)\n dfs(root, True, 0)\n dfs(root, False, 0)\n return self.max_zigzag", "def longestZigZag(root: TreeNode) -> int:\n if root is None:\n return 0\n self.helper(root)\n l = [root]\n m = 0\n while len(l) != 0:\n node = l.pop()\n if node.left != None:\n l.append(node.left)\n if node.right != None:\n l.append(node.right)\n if max(node.val) > m:\n m = max(node.val)\n return m\n\ndef helper(root):\n if root is None:\n return 0\n self.helper(root.left)\n self.helper(root.right)\n if root.left == None and root.right == None:\n root.val = (0, 0)\n elif root.left != None and root.right == None:\n root.val = (root.left.val[1] + 1, 0)\n elif root.right != None and root.left == None:\n root.val = (0, root.right.val[0] + 1)\n else:\n root.val = (root.left.val[1] + 1, root.right.val[0] + 1)", "def longestZigZag(root: TreeNode) -> int:\n\n def Search(root, left, height):\n if root is None:\n return height\n if left:\n return max(Search(root.left, 1, 0), Search(root.right, 0, height + 1))\n else:\n return max(Search(root.right, 0, 0), Search(root.left, 1, height + 1))\n return max(Search(root.left, 1, 0), Search(root.right, 0, 0))", "def longestZigZag(root: TreeNode) -> int:\n longest = 0\n if not root:\n return longest\n\n def helper(root, level, direction):\n nonlocal longest\n if level > longest:\n longest = level\n if direction:\n if root.left:\n helper(root.left, level + 1, not direction)\n if root.right:\n helper(root.right, 1, direction)\n else:\n if root.right:\n helper(root.right, level + 1, not direction)\n if root.left:\n helper(root.left, 1, direction)\n if root.right:\n helper(root.right, 1, True)\n if root.left:\n helper(root.left, 1, False)\n if not root.left and (not root.right):\n return 0\n return longest", "def longestZigZag(root: TreeNode) -> int:\n self.res = 0\n\n def dfs(node):\n if not node:\n return (-1, -1)\n (_, r) = dfs(node.left)\n (l, _) = dfs(node.right)\n self.res = max(self.res, r + 1, l + 1)\n return (r + 1, l + 1)\n dfs(root)\n return self.res", "def longestZigZag(root: TreeNode) -> int:\n\n def check(root):\n l = 0\n r = 0\n m = 0\n if root.left != None:\n r1 = check(root.left)\n l = r1[1] + 1\n m = max(m, r1[2])\n if root.right != None:\n r2 = check(root.right)\n r = r2[0] + 1\n m = max(m, r2[2])\n return (l, r, max(l, r, m))\n if root == None:\n return 0\n r = check(root)\n return r[2]", "def longestZigZag(root: TreeNode) -> int:\n memo = {}\n ans = [0]\n\n def cur(node: TreeNode):\n if node != None:\n memo[node] = [0, 0]\n if node.left != None:\n cur(node.left)\n memo[node][0] = memo[node.left][1] + 1\n ans[0] = max(ans[0], memo[node][0])\n if node.right != None:\n cur(node.right)\n memo[node][1] = memo[node.right][0] + 1\n ans[0] = max(ans[0], memo[node][1])\n cur(root)\n return ans[0]", "def longestZigZag(root: TreeNode) -> int:\n self.zigzag(root)\n return self.find_longest(root)\n\ndef zigzag(node: TreeNode) -> int:\n if node is None:\n return\n self.zigzag(node.left)\n self.zigzag(node.right)\n if node.left is not None:\n node.left_depth = node.left.right_depth + 1\n else:\n node.left_depth = 0\n if node.right is not None:\n node.right_depth = node.right.left_depth + 1\n else:\n node.right_depth = 0\n\ndef find_longest(node: TreeNode) -> int:\n if node is None:\n return 0\n left_max = self.find_longest(node.left)\n right_max = self.find_longest(node.right)\n return max(left_max, right_max, node.left_depth, node.right_depth)", "def longestZigZag(root: TreeNode) -> int:\n self.res = 0\n self.helper(root, True)\n self.helper(root, False)\n return self.res - 1\n\ndef helper(root, isLeft):\n if not root:\n return 0\n left = self.helper(root.left, True)\n right = self.helper(root.right, False)\n self.res = max(self.res, left + 1, right + 1)\n return right + 1 if isLeft else left + 1", "def longestZigZag(root: TreeNode) -> int:\n self.maxpath = 0\n (l, r) = self.visit(root)\n return self.maxpath\n\ndef visit(root):\n l = 0\n r = 0\n if root.left:\n (ll, lr) = self.visit(root.left)\n l = lr + 1\n if root.right:\n (rl, rr) = self.visit(root.right)\n r = rl + 1\n if max(l, r) > self.maxpath:\n self.maxpath = max(l, r)\n return (l, r)", "def longestZigZag(root: TreeNode) -> int:\n self.max = 0\n\n def dfs(node):\n if not node:\n return (-1, -1)\n (l_dir_left, l_dir_right) = dfs(node.left)\n (r_dir_left, r_dir_right) = dfs(node.right)\n self.max = max(self.max, l_dir_left, l_dir_right + 1, r_dir_left + 1, r_dir_right)\n return (l_dir_right + 1, r_dir_left + 1)\n dfs(root)\n return self.max", "from typing import NamedTuple\n\ndef longestZigZag(root: TreeNode) -> int:\n res = self.zigzag(root)\n return res.max_depth\n\ndef zigzag(node: TreeNode) -> int:\n if node is None:\n return Result(-1, -1, 0)\n left_res = self.zigzag(node.left)\n right_res = self.zigzag(node.right)\n left_depth = left_res.right_depth + 1\n right_depth = right_res.left_depth + 1\n max_depth = max(left_depth, right_depth, left_res.max_depth, right_res.max_depth)\n return Result(left_depth, right_depth, max_depth)", "def longestZigZag(root: TreeNode) -> int:\n self.ret = 0\n self.dfs(root, 0, 0)\n self.dfs(root, 1, 0)\n return self.ret - 1\n\ndef dfs(root, prevright, length):\n if root is None:\n self.ret = max(self.ret, length)\n return\n if prevright:\n self.dfs(root.left, 1 - prevright, length + 1)\n self.dfs(root.right, prevright, 1)\n else:\n self.dfs(root.right, 1 - prevright, length + 1)\n self.dfs(root.left, prevright, 1)\n return", "def longestZigZag(root: TreeNode) -> int:\n check = 0\n count = 0\n self.res = 0\n\n def dfs(node, count, check):\n if node:\n if check == 1:\n dfs(node.left, 0, 1)\n dfs(node.right, count + 1, 2)\n elif check == 2:\n dfs(node.left, count + 1, 1)\n dfs(node.right, 0, 2)\n elif check == 0:\n dfs(node.left, count, 1)\n dfs(node.right, count, 2)\n self.res = max(self.res, count)\n dfs(root, count, check)\n return self.res", "_max = 0\n\ndef preorder(root, lr, cur_len):\n nonlocal _max\n if root == None:\n return\n _max = max(_max, cur_len)\n if lr == 'l':\n self.preorder(root.left, 'l', 1)\n self.preorder(root.right, 'r', cur_len + 1)\n elif lr == 'r':\n self.preorder(root.left, 'l', cur_len + 1)\n self.preorder(root.right, 'r', 1)\n else:\n self.preorder(root.left, 'l', cur_len + 1)\n self.preorder(root.right, 'r', cur_len + 1)\n\ndef longestZigZag(root: TreeNode) -> int:\n nonlocal _max\n _max = 0\n self.preorder(root, None, 0)\n return _max", "def longestZigZag(root: TreeNode) -> int:\n dp = [0]\n\n def f(n, ind):\n if not n:\n dp[ind] = (0, 0)\n else:\n dp.extend([0, 0])\n temp = len(dp)\n f(n.left, temp - 2)\n f(n.right, temp - 1)\n dp[ind] = (dp[temp - 1][1] + 1, dp[temp - 2][0] + 1)\n f(root, 0)\n m = -1\n for i in dp:\n m = max(i[0], i[1], m)\n return m - 1", "def longestZigZag(root: TreeNode) -> int:\n seenSoFar = 0\n\n def longestZigZagUtil(root):\n nonlocal seenSoFar\n if not root:\n return (0, 0)\n (Ll, Lr) = longestZigZagUtil(root.left)\n (Rl, Rr) = longestZigZagUtil(root.right)\n (curL, curR) = (0, 0)\n if root.left:\n curL = 1 + Lr\n seenSoFar = max(seenSoFar, Ll)\n if root.right:\n curR = 1 + Rl\n seenSoFar = max(seenSoFar, Rr)\n return (curL, curR)\n (l, r) = longestZigZagUtil(root)\n return max(l, r, seenSoFar)", "def longestZigZag(root: TreeNode) -> int:\n res = 0\n\n def helper(root, direction):\n nonlocal res\n if not root:\n return 0\n left = helper(root.left, 'left')\n right = helper(root.right, 'right')\n res = max(res, left + 1, right + 1)\n return right + 1 if direction == 'left' else left + 1\n if not root:\n return 0\n helper(root, 'left')\n helper(root, 'right')\n return res - 1", "def solve(root, res, ind):\n if root == None:\n return 0\n l = solve(root.left, res, 0)\n r = solve(root.right, res, 1)\n if ind == 0:\n temp = 1 + r\n elif ind == 1:\n temp = 1 + l\n ans = 1 + max(l, r)\n res[0] = max(res[0], ans)\n return temp\n\ndef longestZigZag(root: TreeNode) -> int:\n if root == None:\n return 0\n if root.left == None and root.right == None:\n return 0\n res1 = [0]\n res2 = [0]\n c1 = solve(root, res1, 0)\n c2 = solve(root, res2, 1)\n return max(res1[0], res2[0]) - 1", "def longestZigZag(root: TreeNode) -> int:\n longest = [0]\n\n def dfs(node, d, c):\n if not node:\n longest[0] = max(longest[0], c)\n return\n if d == 'r':\n dfs(node.left, 'l', c + 1)\n else:\n dfs(node.left, 'l', 0)\n if d == 'l':\n dfs(node.right, 'r', c + 1)\n else:\n dfs(node.right, 'r', 0)\n dfs(root, '', 0)\n return longest[0]", "def longestZigZag(root: TreeNode) -> int:\n self.ans = 0\n\n def helper(node, direction, l):\n if not node:\n return\n self.ans = max(self.ans, l)\n helper((node.left, node.right)[direction], 1 - direction, l + 1)\n helper((node.left, node.right)[1 - direction], direction, 1)\n helper(root, 0, 0)\n helper(root, 1, 0)\n return self.ans", "def longestZigZag(root: TreeNode) -> int:\n\n def solve(root):\n if root:\n solve(root.left)\n solve(root.right)\n if root.left:\n d[root][0] = d[root.left][1] + 1\n if root.right:\n d[root][1] = d[root.right][0] + 1\n self.ans = max(self.ans, max(d[root]))\n return self.ans\n d = defaultdict(lambda : [0, 0])\n self.ans = 0\n solve(root)\n return self.ans", "def longestZigZag(root: TreeNode) -> int:\n if not root:\n return 0\n if not root.left and (not root.right):\n return 0\n\n def dfs(root, flag, count):\n if not root:\n self.res = max(self.res, count - 1)\n return\n if flag == 1:\n dfs(root.left, -1, 1 + count)\n dfs(root.right, 1, 1)\n else:\n dfs(root.right, 1, 1 + count)\n dfs(root.left, -1, 1)\n self.res = 0\n dfs(root, -1, 0)\n return self.res", "def longestZigZag(root: TreeNode) -> int:\n res = collections.namedtuple('res', 'left right total')\n\n def dfs(root):\n if not root:\n return res(-1, -1, -1)\n left = dfs(root.left)\n right = dfs(root.right)\n return res(left.right + 1, right.left + 1, max(left.right + 1, right.left + 1, left.total, right.total))\n return dfs(root).total", "def node_is_on_the_right(node):\n if not node:\n return 0\n continuation = 1 + self.node_is_on_the_left(node.left)\n starts_here = self.node_is_on_the_right(node.right)\n self.m = max(self.m, starts_here)\n return continuation\n\ndef node_is_on_the_left(node):\n if not node:\n return 0\n continuation = 1 + self.node_is_on_the_right(node.right)\n starts_here = self.node_is_on_the_left(node.left)\n self.m = max(self.m, starts_here)\n return continuation\n\ndef longestZigZag(root: TreeNode) -> int:\n self.m = 0\n x = self.node_is_on_the_right(root) - 1\n self.m = max(self.m, x)\n return self.m", "def longestZigZag(root: TreeNode) -> int:\n self.mx = 0\n out = self.traverse(root, 0)\n out = self.traverse(root, 1)\n return self.mx - 1\n\ndef traverse(node, ctype):\n if node is None:\n return (0, 0)\n ll = lr = rl = rr = 0\n if node.left:\n (ll, lr) = self.traverse(node.left, 0)\n if node.right:\n (rl, rr) = self.traverse(node.right, 1)\n best = max(lr, rl) + 1\n self.mx = max(self.mx, best)\n return (1 + lr, 1 + rl)", "from collections import defaultdict\n\ndef longestZigZag(root: TreeNode) -> int:\n levels = [root]\n ret = 0\n dp_r = defaultdict(int)\n dp_l = defaultdict(int)\n while levels:\n nxt = []\n for p in levels:\n if p.left:\n nxt.append(p.left)\n dp_l[p.left] = dp_r[p] + 1\n ret = max(ret, dp_l[p.left])\n if p.right:\n nxt.append(p.right)\n dp_r[p.right] = dp_l[p] + 1\n ret = max(ret, dp_r[p.right])\n levels = nxt\n return ret", "def longestZigZag(root: TreeNode) -> int:\n if root == None:\n return 0\n max_zigzag = 0\n zigzag = 0\n stack = [(root, None, 0)]\n while stack:\n node = stack[-1][0]\n prev_dir = stack[-1][1]\n max_up_to_node = stack[-1][2]\n del stack[-1]\n if max_up_to_node > max_zigzag:\n max_zigzag = max_up_to_node\n if prev_dir == None:\n if node.right != None:\n stack.append((node.right, 'R', max_up_to_node + 1))\n if node.left != None:\n stack.append((node.left, 'L', max_up_to_node + 1))\n else:\n if prev_dir == 'R':\n if node.right != None:\n stack.append((node.right, 'R', 1))\n if node.left != None:\n stack.append((node.left, 'L', max_up_to_node + 1))\n if prev_dir == 'L':\n if node.right != None:\n stack.append((node.right, 'R', max_up_to_node + 1))\n if node.left != None:\n stack.append((node.left, 'L', 1))\n return max_zigzag", "def longestZigZag(root: TreeNode) -> int:\n\n def dfs(root):\n if root is None:\n return (0, [0, 0])\n if root.left is None and root.right is None:\n return (0, [0, 0])\n (left_zigzag, [_, right]) = dfs(root.left)\n (right_zigzag, [left, _]) = dfs(root.right)\n zigzag = max(left_zigzag, right_zigzag)\n if root.right:\n right_zigzag = 1 + left\n zigzag = max(zigzag, right_zigzag)\n else:\n right_zigzag = 0\n if root.left:\n left_zigzag = 1 + right\n zigzag = max(zigzag, left_zigzag)\n else:\n left_zigzag = 0\n return (zigzag, [left_zigzag, right_zigzag])\n return dfs(root)[0]", "def longestZigZag(root: TreeNode) -> int:\n self.max_ = 0\n\n def preorder(root, count, dir_):\n self.max_ = max(self.max_, count)\n if root.left:\n if dir_ == 1 or dir_ == -1:\n preorder(root.left, count + 1, 0)\n else:\n preorder(root.left, 1, 0)\n if root.right:\n if dir_ == 0 or dir_ == -1:\n preorder(root.right, count + 1, 1)\n else:\n preorder(root.right, 1, 1)\n preorder(root, 0, -1)\n return self.max_", "def longestZigZag(root: TreeNode) -> int:\n Max = [0]\n vl = set()\n vr = set()\n\n def path(node, l, d):\n if node == None:\n return l\n if d == 1:\n vr.add(node)\n return path(node.left, l + 1, 0)\n else:\n vl.add(node)\n return path(node.right, l + 1, 1)\n\n def dfs(node):\n if node == None:\n return\n if node not in vl:\n Max[0] = max(Max[0], path(node, -1, 0))\n if node not in vr:\n Max[0] = max(Max[0], path(node, -1, 1))\n dfs(node.left)\n dfs(node.right)\n dfs(root)\n return Max[0]", "def __init__():\n self.memo = {}\n\ndef h(node: TreeNode, left: bool) -> int:\n if not node:\n return 0\n if (node, left) not in self.memo:\n ret = 0\n if left and node.left is not None:\n ret = 1 + self.h(node.left, False)\n elif not left and node.right is not None:\n ret = 1 + self.h(node.right, True)\n self.memo[node, left] = ret\n return self.memo[node, left]\n\ndef longestZigZag(root: TreeNode) -> int:\n if not root:\n return 0\n ret = [0]\n if root.left is not None:\n ret.extend([1 + self.h(root.left, False), self.longestZigZag(root.left)])\n if root.right is not None:\n ret.extend([1 + self.h(root.right, True), self.longestZigZag(root.right)])\n return max(ret)", "def __init__():\n self.lmemo = {}\n self.rmemo = {}\n\ndef longestZigZag(root: TreeNode) -> int:\n\n def lzz(root, mx):\n if root is not None:\n lzz(root.left, mx)\n lzz(root.right, mx)\n mx[0] = max(mx[0], llzz(root), rlzz(root))\n return mx\n\n def llzz(root):\n if root not in self.lmemo:\n self.lmemo[root] = 1 + rlzz(root.left)\n return self.lmemo[root]\n\n def rlzz(root):\n if root not in self.rmemo:\n self.rmemo[root] = 1 + llzz(root.right)\n return self.rmemo[root]\n self.lmemo[None] = self.rmemo[None] = 0\n return lzz(root, [float('-inf')])[0] - 1", "def longestZigZag(root: TreeNode) -> int:\n\n def helper(root):\n if not root:\n return (-1, -1, -1)\n if not root.left and (not root.right):\n return (0, 0, 0)\n else:\n (l1, l2, l3) = helper(root.left)\n (r1, r2, r3) = helper(root.right)\n return (l3 + 1, max(l3 + 1, r1 + 1, l2, r2), r1 + 1)\n return helper(root)[1]", "def longestZigZag(root: TreeNode) -> int:\n if root is None:\n return 0\n self.sol = 0\n\n def recursive_long_zigzag(node):\n if node.left is None and node.right is None:\n return (0, 0)\n max_left = 0\n max_right = 0\n if node.left:\n (_, left_s_right) = recursive_long_zigzag(node.left)\n max_left = left_s_right + 1\n self.sol = max(self.sol, max_left)\n if node.right:\n (right_s_left, _) = recursive_long_zigzag(node.right)\n max_right = right_s_left + 1\n self.sol = max(self.sol, max_right)\n return (max_left, max_right)\n recursive_long_zigzag(root)\n return self.sol", "def __init__():\n self.max_cnt = 0\n\ndef longestZigZag(root: TreeNode) -> int:\n self.dfs(root, True, 0)\n self.dfs(root, False, 0)\n return self.max_cnt\n\ndef dfs(root, isLeft, cnt):\n if root is None:\n return\n self.max_cnt = max(self.max_cnt, cnt)\n if isLeft:\n self.dfs(root.left, False, cnt + 1)\n self.dfs(root.right, True, 1)\n else:\n self.dfs(root.right, True, cnt + 1)\n self.dfs(root.left, False, 1)", "def longestZigZag(root: TreeNode) -> int:\n ans = 0\n nodes = [root]\n self.dp = {}\n while len(nodes) != 0:\n tmp = []\n for node in nodes:\n if node.left is not None:\n tmp.append(node.left)\n if node.right is not None:\n tmp.append(node.right)\n ans = max(ans, self.helper(node, 1))\n ans = max(ans, self.helper(node, 0))\n nodes = tmp\n return ans - 1\n\ndef helper(node, status):\n if node is None:\n return 0\n if (node, status) in self.dp:\n return self.dp[node, status]\n if status == 1:\n ans = self.helper(node.right, 0)\n else:\n ans = self.helper(node.left, 1)\n self.dp[node, status] = 1 + ans\n return 1 + ans", "def longestZigZag(root: TreeNode) -> int:\n memo = dict()\n\n def zig_zag_len(node, direction):\n if not node:\n return -1\n if (node, direction) in memo:\n return memo[node, direction]\n if direction == 'L':\n memo[node, direction] = 1 + zig_zag_len(node.right, 'R')\n elif direction == 'R':\n memo[node, direction] = 1 + zig_zag_len(node.left, 'L')\n else:\n memo[node, direction] = max(1 + zig_zag_len(node.right, 'R'), 1 + zig_zag_len(node.left, 'L'), zig_zag_len(node.right, 'N'), zig_zag_len(node.left, 'N'))\n return memo[node, direction]\n return zig_zag_len(root, 'N')", "def longestZigZag(root: TreeNode) -> int:\n\n def zigzag(node, mz):\n if not node:\n return (-1, -1)\n (l1, r1) = zigzag(node.left, mz)\n (l2, r2) = zigzag(node.right, mz)\n mz[0] = max(mz[0], r1 + 1, l2 + 1)\n return (r1 + 1, l2 + 1)\n maxzigzag = [0]\n zigzag(root, maxzigzag)\n zigzag(root, maxzigzag)\n return maxzigzag[0]", "def run(node, side, count, memo):\n if not node:\n return count\n if node in memo:\n if memo[node][side] > -1:\n return memo[node][side]\n memo[node] = [-1, -1, -1]\n if side == 0:\n result = self.run(node.right, 1, count + 1, memo)\n elif side == 1:\n result = self.run(node.left, 0, count + 1, memo)\n else:\n using = max(self.run(node.right, 1, 1, memo), self.run(node.left, 0, 1, memo))\n notUsing = max(self.run(node.right, -1, 0, memo), self.run(node.left, -1, 0, memo))\n result = max(using, notUsing)\n memo[node][side] = result\n return result\n\ndef longestZigZag(root: TreeNode) -> int:\n if not root:\n return 0\n return self.run(root, -1, 0, {}) - 1", "def longestZigZag(root: TreeNode) -> int:\n nodes = self.bfs(root)\n self.dp = {node: [False, False] for node in nodes}\n ans = 0\n for x in range(len(nodes)):\n ans = max(ans, self.recur(0, nodes[x], -1), self.recur(1, nodes[x], -1))\n return ans\n\ndef bfs(node):\n q = [node]\n arr = []\n while q:\n r = q.pop()\n arr.append(r)\n if r.left:\n q.append(r.left)\n if r.right:\n q.append(r.right)\n return arr\n\ndef recur(p, node, c):\n if not node:\n return c\n if self.dp[node][p] != False:\n return self.dp[node][p]\n if p == 0:\n self.dp[node][p] = self.recur(p ^ 1, node.left, c + 1)\n return self.dp[node][p]\n else:\n self.dp[node][p] = self.recur(p ^ 1, node.right, c + 1)\n return self.dp[node][p]"], "starter_code": "def __init__(val=0, left=None, right=None):\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Binary Tree", "Tree", "Dynamic Programming", "Depth-First Search"], "name": null, "source": "leetcode", "tags": ["Tree algorithms", "Dynamic programming", "Graph traversal"], "skill_types": ["Dynamic programming"], "url": "https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "__init__", "task_id": "TACO_lite/390", "example": [[], []]} +{"requirement": "Some people(n) are standing in a queue. A selection process follows a rule where people standing on even positions are selected. Of the selected people a queue is formed and again out of these only people on even position are selected. This continues until we are left with one person. Find out the position of that person in the original queue.\nExample 1:\nInput: n = 5\nOutput: 4 \nExplanation: 1,2,3,4,5 -> 2,4 -> 4.\nExample 2:\nInput: n = 9\nOutput: 8\nExplanation: 1,2,3,4,5,6,7,8,9\n->2,4,6,8 -> 4,8 -> 8. \nYour Task: \nYou dont need to read input or print anything. Complete the function nthPosition() which takes n as input parameter and returns the position(original queue) of that person who is left.\nExpected Time Complexity: O(logn)\nExpected Auxiliary Space: O(1)\nConstraints:\n1<= n <=10^{8}", "solutions": ["def nthposition(n):\n res = 0\n for i in range(n, 0, -1):\n if i & i - 1 == 0:\n res = i\n break\n return res", "def nthposition(n):\n ans = 0\n while n > 1:\n ans += 1\n n //= 2\n return pow(2, ans)", "def nthposition(n):\n a = []\n for i in range(2, n + 1, 2):\n a.append(i)\n while len(a) != 1:\n t = []\n for i in range(1, len(a), 2):\n t.append(a[i])\n a[:] = t[:]\n return a[0]", "def nthposition(n):\n i = 1\n return self.find(n, i)\n\ndef find(n, i):\n if n == 1:\n return n * i\n return self.find(n // 2, i * 2)", "import math\n\ndef nthposition(n):\n x = int(math.log2(n))\n return 2 ** x", "def nthposition(n):\n\n def help(count, n):\n if n <= 1:\n return 2 ** count\n count += 1\n return help(count, n // 2)\n return help(0, n)", "def nthposition(n):\n arr = [i for i in range(2, n + 1, 2)]\n while len(arr) > 1:\n temp = []\n for i in range(1, len(arr), 2):\n temp.append(arr[i])\n arr = temp\n return arr[0]", "def nthposition(n):\n if n == 1:\n return 1\n return self.nthposition(n // 2) * 2", "def nthposition(n):\n for i in range(33):\n if 2 ** i > n:\n return 2 ** (i - 1)", "from math import log\n\ndef nthposition(n):\n res = int(log(n, 2))\n return int(pow(2, res))", "def solve(i, n):\n if 2 ** i > n:\n return 2 ** (i - 1)\n return self.solve(i + 1, n)\n\ndef nthposition(n):\n return self.solve(0, n)", "def nthposition(n):\n if n == 1:\n return 0\n res = 1\n while n // 2 != 1:\n n = n // 2\n res *= 2\n return res * 2", "def nthposition(n):\n if n == 1:\n return int(n)\n p = 1\n while p < n:\n p *= 2\n if p == n:\n return int(p)\n return int(p / 2)", "def nthposition(n):\n i = 0\n while n >= 2 ** i:\n i += 1\n return 2 ** i if 2 ** i <= n else 2 ** (i - 1)", "def solve(n, i):\n if n < i:\n return i // 2\n return self.solve(n, i * 2)\n\ndef nthposition(n):\n return self.solve(n, 2)", "def solution(arr):\n if len(arr) == 1:\n return arr\n return self.solution(arr[1::2])\n\ndef nthposition(n):\n lst = list(range(1, n + 1))\n x = self.solution(lst)\n return x[-1]", "def nthposition(n):\n l = []\n for i in range(1, n + 1):\n l.append(i)\n p = self.even(l)\n return p\n\ndef even(l):\n if len(l) == 1:\n return l[0]\n return self.even(l[1::2])", "import math\n\ndef nthposition(n):\n largestPower = int(math.log(n, 2))\n return int(math.pow(2, largestPower))", "def nthposition(x):\n x |= x >> 1\n x |= x >> 2\n x |= x >> 4\n x |= x >> 8\n x |= x >> 16\n return x ^ x >> 1", "def nthposition(n):\n\n def f(arr):\n if len(arr) == 1:\n return arr[0]\n return f(arr[1::2])\n l = []\n for i in range(1, n + 1):\n l.append(i)\n return f(l)", "def nthposition(n):\n\n def f(arr):\n if len(arr) == 1:\n return arr[0]\n return f(arr[1::2])\n return f(list(range(1, n + 1)))", "def nthposition(n):\n for x in range(n, 0, -1):\n if x & x - 1 == 0:\n return x", "def nthposition(n):\n\n def g(a, count):\n if a == 1:\n return count\n a = int(a / 2)\n count += 1\n return g(a, count)\n return pow(2, g(n, 0))", "import math\n\ndef nthposition(n):\n logVal = math.log2(n)\n out = 2 ** int(logVal)\n return out", "def nthposition(n):\n\n def fun(ans, n, k):\n if n == 1:\n return ans\n if n % 2 == 0:\n ans = ans\n if n % 2 != 0:\n ans = ans - k\n k = k * 2\n return fun(ans, n // 2, k)\n k = 1\n ans = n\n return fun(ans, n, k)", "def cullu(n):\n if n == 1:\n return 1\n c = 1 + cullu(n // 2)\n return c\n\ndef nthposition(n):\n c = cullu(n)\n return 2 ** (c - 1)", "def nthposition(n):\n count = 0\n while n != 1:\n n = n // 2\n count += 1\n return 2 ** count", "def nthposition(n):\n i = 0\n l = []\n while 1:\n if pow(2, i) <= n:\n l.append(pow(2, i))\n else:\n break\n i += 1\n return l[-1]", "def nthposition(n):\n i = 1\n while i * 2 <= n:\n i *= 2\n return i", "def nthposition(n):\n (i, c) = (0, 0)\n while c <= n:\n x = c\n c = pow(2, i)\n if c > n:\n break\n i += 1\n return x", "def nthposition(n):\n temp = n\n c = 1\n while n > 1:\n if n % 2 == 0:\n n = n - n // 2\n else:\n temp = temp - c\n n = temp\n return temp", "def nthposition(n):\n l = []\n for i in range(1, n // 2):\n if 2 ** i == n:\n return n\n break\n elif 2 ** i > n:\n return 2 ** (i - 1)\n break", "def nthposition(n):\n c = 0\n while n:\n c += 1\n n = n >> 1\n return 2 ** (c - 1)", "def nthposition(n):\n import math as m\n s = int(m.sqrt(n)) + 1\n i = 0\n while 2 ** i <= n:\n i += 1\n return 2 ** (i - 1)", "import math\n\ndef nthposition(n):\n return 2 ** math.floor(math.log2(n))", "def nthposition(n):\n\n def helper(i, n):\n if i > n:\n return int(i / 2)\n else:\n i = i * 2\n return helper(i, n)\n return helper(1, n)", "def nthposition(n):\n if n == 1:\n return 1\n else:\n return self.nthposition(n // 2) * 2", "def nthposition(n):\n if n == 1:\n return 1\n return self.nthposition(int(n / 2)) * 2", "def nthposition(n):\n import math\n ans = math.log(n) / math.log(2)\n return math.floor(math.pow(2, math.floor(ans)))", "def nthposition(n):\n l = [i for i in range(2, n + 1, 2)]\n\n def solve(lst):\n if len(lst) <= 1:\n return lst\n nl = []\n for i in range(1, len(lst), 2):\n nl.append(lst[i])\n return solve(nl)\n return solve(l)[0]", "def nthposition(n):\n if n == 1:\n return 1\n arr = [i for i in range(2, n + 1, 2)]\n\n def pos(arr):\n if len(arr) == 1:\n return arr[0]\n res = [arr[i] for i in range(1, len(arr), 2)]\n return pos(res)\n return pos(arr)", "def nthposition(n):\n\n def position(i, n):\n if i > n:\n return i // 2\n i = i * 2\n return position(i, n)\n return position(1, n)", "import math\n\ndef nthposition(n):\n return 1 << int(math.log2(n))", "def nthposition(n):\n if n < 3:\n return n\n else:\n return 2 * self.nthposition(n // 2)", "def nthposition(n):\n list1 = [i for i in range(1, n + 1, 1)]\n new = []\n while len(list1) > 1:\n new = [list1[i] for i in range(1, len(list1), 2)]\n list1[:] = new[:]\n return list1[0]", "import math\n\ndef nthposition(n):\n x = int(math.log(n) / math.log(2))\n y = 2 ** x\n return y", "import sys\n\ndef nthposition(n):\n if n < 1:\n return 0\n res = 1\n for i in range(8 * sys.getsizeof(n)):\n curr = 1 << i\n if curr > n:\n break\n res = curr\n return res", "import math\n\ndef nthposition(n):\n if n == 1:\n return 1\n ans = self.nthposition(n // 2)\n return 2 * ans", "def nthposition(n):\n if n == 1:\n return 1\n nth_pos = 2\n while n >= nth_pos:\n nth_pos *= 2\n return nth_pos // 2", "import math\n\ndef nthposition(n):\n c = int(math.log(n, 2))\n d = int(pow(2, c))\n return d", "def __init__():\n self.k = 1\n\ndef nthposition(n):\n if n == 1:\n return self.k\n self.k = self.k * 2\n return self.nthposition(n // 2)", "def nthposition(n):\n s = bin(n)\n bits = len(s) - 2\n num = '1'\n for i in range(bits - 1):\n num += '0'\n return n & int(num)", "def nthposition(n):\n ans = 1\n while n != 1:\n ans = 2 * ans\n n //= 2\n return ans", "def nthposition(n):\n l = 2\n if n & 1:\n r = n - 1\n else:\n r = n\n diff = r - l\n i = 1\n while diff > 0:\n i *= 2\n l = l + i\n r = r - i\n diff = r - l\n return l", "def nthposition(n):\n list1 = [j for j in range(1, n + 1)]\n\n def ans(list1):\n if len(list1) == 1:\n return list1[0]\n list1 = [list1[j] for j in range(1, len(list1), 2)]\n return ans(list1)\n return ans(list1)", "def nthposition(n):\n x = str(bin(n))[2:]\n ans = pow(2, len(x) - 1)\n return ans", "def nthposition(n):\n l = []\n for i in range(n):\n l.append(i + 1)\n while len(l) != 1:\n b = l[1::2]\n l = b[:]\n return l[0]", "def nthposition(n):\n return 1 << n.bit_length() - 1", "import math\n\ndef nthposition(n):\n if n == 1:\n return 1\n n = int(math.log(n, 2))\n return pow(2, n)", "import math\n\ndef nthposition(n):\n p = int(math.log(n, 2))\n return int(pow(2, p))\n return even(n)", "def nthposition(n):\n if n == 1:\n return 1\n elif n == 2:\n return 2\n else:\n start = 2\n while start <= n:\n if start * 2 <= n:\n start = start * 2\n else:\n return start", "def nthposition(n):\n if n == 1:\n return n\n ans = self.nthposition(n // 2)\n return 2 * ans"], "starter_code": "def nthposition (n):\n", "input_output": {"inputs": ["n = 5", "n = 9"], "outputs": ["4", "8"]}, "difficulty": "EASY", "raw_tags": ["Recursion", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics", "Complete search"], "skill_types": ["Complete search"], "url": "https://practice.geeksforgeeks.org/problems/finding-position2223/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(logn)", "entry_point": "nthposition", "task_id": "TACO_lite/354", "example": [[[5], [9]], ["4", "8"]]} +{"requirement": "Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.\n\nYou may assume that the array is non-empty and the majority element always exist in the array.\n\nExample 1:\n\n\nInput: [3,2,3]\nOutput: 3\n\nExample 2:\n\n\nInput: [2,2,1,1,1,2,2]\nOutput: 2", "solutions": ["def majorityelement(nums):\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 find = set(nums[0:n // 2]) & set(nums[n // 2:])\n for i in find:\n if nums.count(i) > n // 2:\n return i", "def majorityelement(nums):\n order = dict()\n if len(nums) > 1:\n for i in range(len(nums)):\n if nums[i] in list(order.keys()):\n order[nums[i]] += 1\n if order[nums[i]] > len(nums) // 2:\n return nums[i]\n else:\n order[nums[i]] = 1\n else:\n return nums[0]", "def majorityelement(nums):\n l = len(nums)\n for n in set(nums):\n if nums.count(n) > l / 2:\n return n", "def majorityelement(nums):\n count = 0\n candidate = None\n for num in nums:\n if count == 0:\n candidate = num\n count += 1 if num == candidate else -1\n return candidate", "def majorityelement(nums):\n map = {}\n for n in nums:\n if n not in map:\n map[n] = 0\n map[n] += 1\n (max, occ) = (-1, -1)\n for (num, count) in map.items():\n if count > occ:\n (max, occ) = (num, count)\n return max", "def majorityelement(nums):\n a = sorted(nums)\n return a[int(len(a) / 2)]", "def majorityelement(nums):\n if not nums:\n return ''\n current = nums[0]\n counter = 1\n for i in range(1, len(nums)):\n if counter == 0:\n current = nums[i]\n counter = 1\n elif nums[i] == current:\n counter += 1\n else:\n counter -= 1\n return current", "def majorityelement(nums):\n table = {}\n for num in nums:\n if num not in table:\n table[num] = 1\n else:\n table[num] += 1\n sorting_tutple = [(value, key) for (key, value) in list(table.items())]\n sorting_tutple.sort(reverse=True)\n return sorting_tutple[0][1]", "def majorityelement(nums):\n d = {}\n maxV = float('-inf')\n maxX = -1\n n = len(nums) // 2\n for x in nums:\n if x not in d:\n d[x] = 1\n else:\n d[x] += 1\n if d[x] > maxV:\n maxV = d[x]\n maxX = x\n if maxV > n:\n break\n return maxX", "def majorityelement(nums):\n hist = {}\n for num in nums:\n if num not in hist:\n hist[num] = 0\n hist[num] += 1\n if hist[num] > len(nums) // 2:\n return num", "def majorityelement(nums):\n s = {}\n for i in range(len(nums)):\n s[nums[i]] = s.get(nums[i], 0) + 1\n for num in nums:\n if s[num] > len(nums) // 2:\n return num", "def majorityelement(nums):\n ele = {}\n for i in nums:\n if i in ele:\n ele[i] += 1\n else:\n ele[i] = 1\n if ele[i] > len(nums) / 2:\n return int(i)", "def majorityelement(nums):\n count = {}\n for i in nums:\n if i in count.keys():\n count[i] += 1\n else:\n count[i] = 1\n ans = count[nums[0]]\n res = nums[0]\n for x in count.keys():\n if count[x] > ans:\n ans = count[x]\n res = x\n return res"], "starter_code": "def majorityelement(nums: List[int]) -> int:\n", "input_output": {"fn_name": "majorityElement", "inputs": [[[3, 2, 3]]], "outputs": [3]}, "difficulty": "EASY", "raw_tags": ["Divide and Conquer", "Array", "Counting", "Sorting", "Hash Table"], "name": null, "source": "leetcode", "tags": ["Sorting", "Data structures", "Mathematics", "Divide and conquer"], "skill_types": ["Sorting", "Data structures"], "url": "https://leetcode.com/problems/majority-element/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "majorityelement", "task_id": "TACO_lite/411", "example": [[[[3, 2, 3]], [[2, 2, 1, 1, 1, 2, 2]]], ["3", "2"]]} +{"requirement": "Given an array A of integers, return true if and only if it is a valid mountain array.\nRecall that A is a mountain array if and only if:\n\nA.length >= 3\nThere exists some i with 0 < i < A.length - 1 such that:\n \nA[0] < A[1] < ... A[i-1] < A[i] \nA[i] > A[i+1] > ... > A[A.length - 1]\n\n\n\n\n\n \nExample 1:\nInput: [2,1]\nOutput: false\n\n\nExample 2:\nInput: [3,5,5]\nOutput: false\n\n\nExample 3:\nInput: [0,3,2,1]\nOutput: true\n\n\n \nNote:\n\n0 <= A.length <= 10000\n0 <= A[i] <= 10000", "solutions": ["def validmountainarray(A: List[int]) -> bool:\n if len(A) <= 2:\n return False\n else:\n if A[1] < A[0]:\n return False\n is_up = True\n curr = A[0]\n for n in A[1:]:\n if n == curr:\n return False\n if n < curr:\n is_up = False\n curr = n\n if n > curr:\n if is_up:\n curr = n\n else:\n return False\n return not is_up", "def validmountainarray(A: List[int]) -> bool:\n isIncreasing = True\n i = 1\n n = len(A)\n if n < 3:\n return False\n if A[1] <= A[0]:\n return False\n while i < n:\n if isIncreasing and A[i - 1] < A[i]:\n i += 1\n continue\n elif A[i] < A[i - 1]:\n isIncreasing = False\n i += 1\n continue\n else:\n return False\n if A[-1] >= A[-2]:\n return False\n return True", "def validmountainarray(A: List[int]) -> bool:\n arr = A\n if len(arr) < 3:\n return False\n if arr[0] > arr[1]:\n return False\n if arr[-1] > arr[-2]:\n return False\n peek = None\n for i in range(1, len(arr) - 1):\n if arr[i] > arr[i + 1]:\n peek = i\n if peek and arr[i] < arr[i + 1]:\n return False\n if arr[i] == arr[i + 1] or arr[i] == arr[i - 1]:\n return False\n return True", "def validmountainarray(A: List[int]) -> bool:\n dec = 0\n n = len(A)\n if n < 3:\n return False\n else:\n for i in range(n):\n if i != 0 and A[i] == A[i - 1]:\n return False\n elif i == 0 and A[i] > A[i + 1]:\n return False\n elif dec == 1 and A[i] > A[i - 1]:\n return False\n elif i != 0 and dec == 0 and (A[i] < A[i - 1]):\n dec = 1\n elif i == n - 1 and dec == 0:\n return False\n return True", "def __init__():\n self.f = True\n\ndef impl(arr, i, incr):\n self.f = incr\n if i + 1 >= len(arr):\n return True\n if arr[i + 1] > arr[i] and (not incr):\n return False\n elif arr[i + 1] < arr[i] and incr:\n incr = False\n elif arr[i + 1] == arr[i]:\n return False\n return self.impl(arr, i + 1, incr)\n\ndef validmountainarray(A) -> bool:\n if A == None or len(A) <= 2:\n return False\n if A[1] < A[0]:\n return False\n self.f = True\n result = self.impl(A, 0, True)\n if self.f:\n return False\n return result", "def validmountainarray(A: List[int]) -> bool:\n i = 1\n N = len(A)\n if N < 3:\n return False\n while i < N and A[i] > A[i - 1]:\n i += 1\n if i == 1 or i == N:\n return False\n while i < N and A[i] < A[i - 1]:\n i += 1\n return i == N", "def validmountainarray(A: List[int]) -> bool:\n if len(A) <= 2:\n return False\n else:\n t = 0\n (c1, c2) = (0, 0)\n for i in range(1, len(A) - 1):\n if A[i] == A[i + 1]:\n return False\n break\n elif A[i - 1] < A[i] < A[i + 1] or A[i - 1] > A[i] > A[i + 1] or A[i - 1] < A[i] > A[i + 1]:\n t += 1\n if A[i - 1] < A[i] < A[i + 1]:\n c1 += 1\n if A[i - 1] > A[i] > A[i + 1]:\n c2 += 1\n if t == len(A) - 2 and c1 < len(A) - 2 and (c2 < len(A) - 2):\n return True\n else:\n return False", "def validmountainarray(A: List[int]) -> bool:\n if len(A) < 3:\n return False\n nprev = A[0]\n for i in range(1, len(A)):\n if A[i] <= nprev:\n nprev = A[i - 1]\n start = i\n break\n nprev = A[i]\n if i == len(A) - 1:\n return False\n for i in range(start, len(A)):\n if A[i] >= nprev:\n return False\n nprev = A[i]\n if start == 1 and i == len(A) - 1:\n return False\n return True", "def validmountainarray(A: List[int]) -> bool:\n if len(A) < 3:\n return False\n maxIndex = A.index(max(A))\n if maxIndex == len(A) - 1 or maxIndex == 0:\n return False\n for i in range(maxIndex):\n if A[i] >= A[i + 1]:\n return False\n for i in range(maxIndex, len(A) - 1):\n if A[i] <= A[i + 1]:\n return False\n return True", "def validmountainarray(arr: List[int]) -> bool:\n i = 0\n l = len(arr)\n while i + 1 < l and arr[i] < arr[i + 1]:\n i += 1\n if i == 0 or i == l - 1:\n return False\n while i + 1 < l and arr[i] > arr[i + 1]:\n i += 1\n return i == l - 1", "def validmountainarray(A):\n N = len(A)\n i = 0\n while i + 1 < N and A[i] < A[i + 1]:\n i += 1\n if i == 0 or i == N - 1:\n return False\n while i + 1 < N and A[i] > A[i + 1]:\n i += 1\n return i == N - 1", "def validmountainarray(A: List[int]) -> bool:\n if len(A) <= 2:\n return False\n i = 0\n N = len(A)\n while i < N and i + 1 < N and (A[i] < A[i + 1]):\n i += 1\n if i == 0 or i == N - 1:\n return False\n while i < N and i + 1 < N and (A[i] > A[i + 1]):\n i += 1\n if i == N - 1:\n return True\n return False", "def validmountainarray(A: List[int]) -> bool:\n m = (0, 0)\n for i in range(0, len(A)):\n if A[i] > m[1]:\n m = (i, A[i])\n if m[0] == 0 or m[0] == len(A) - 1:\n return False\n for i in range(0, m[0] - 1):\n if A[i] >= A[i + 1]:\n return False\n for i in range(m[0], len(A) - 1):\n if A[i] <= A[i + 1]:\n return False\n return True", "def walkUp(A: List[int]) -> int:\n for (i, step) in enumerate(A[:-1]):\n if A[i] >= A[i + 1]:\n return i\n return len(A)\n\ndef walkDown(A: List[int], top: int) -> bool:\n for (i, step) in enumerate(A[top:-1], start=top):\n if A[i] <= A[i + 1]:\n return False\n return True\n\ndef validmountainarray(A: List[int]) -> bool:\n top = self.walkUp(A)\n if top == 0 or top == len(A):\n return False\n return self.walkDown(A, top)", "def validmountainarray(A: List[int]) -> bool:\n if len(A) < 3:\n return False\n switch = 0\n if A[0] > A[1]:\n return False\n for i in range(2, len(A)):\n if A[i] == A[i - 1]:\n return False\n if switch == 0 and A[i] < A[i - 1]:\n switch = 1\n elif switch == 1 and A[i] > A[i - 1]:\n return False\n if switch == 0:\n return False\n return True", "def validmountainarray(A: List[int]) -> bool:\n if len(A) < 3:\n return False\n N = len(A) - 1\n reached = False\n for i in range(N):\n if A[i] == A[i + 1]:\n return False\n if not reached:\n if A[i] > A[i + 1]:\n if i == 0:\n return False\n reached = True\n elif A[i] < A[i + 1]:\n return False\n return reached", "def validmountainarray(A: List[int]) -> bool:\n if len(A) >= 3:\n peak = max(A)\n if A.count(peak) == 1:\n peakInd = A.index(peak)\n incArr = A[:peakInd]\n decArr = A[peakInd + 1:]\n if len(incArr) > 0 and len(decArr) > 0:\n for i in range(1, len(incArr)):\n if incArr[i] <= incArr[i - 1]:\n return False\n for d in range(0, len(decArr) - 1):\n if decArr[d] <= decArr[d + 1]:\n return False\n return True\n else:\n return False\n else:\n return False\n else:\n return False", "def validmountainarray(A: List[int]) -> bool:\n strict_inc = False\n strict_dec = False\n if len(A) > 2:\n for i in range(1, len(A)):\n if A[i] > A[i - 1]:\n if strict_dec:\n return False\n strict_inc = True\n elif A[i] < A[i - 1]:\n strict_dec = True\n else:\n return False\n if strict_inc and strict_dec:\n return True\n else:\n return False\n else:\n return False", "def validmountainarray(A: List[int]) -> bool:\n (i, j) = (0, len(A) - 1)\n while i < j:\n if A[i] < A[i + 1]:\n i += 1\n if A[j] < A[j - 1]:\n j -= 1\n elif i + 1 >= len(A) or A[i] >= A[i + 1]:\n break\n return i == j and 0 < i < len(A) - 1", "def validmountainarray(A: List[int]) -> bool:\n if len(A) < 3:\n return False\n diffs = [A[i + 1] - A[i] for i in range(len(A) - 1)]\n if 0 in diffs or diffs[0] < 0:\n return False\n peak = False\n for i in range(len(diffs) - 1):\n if diffs[i + 1] / abs(diffs[i + 1]) != diffs[i] / abs(diffs[i]):\n if peak == False:\n peak = True\n else:\n return False\n return peak", "def validmountainarray(A: List[int]) -> bool:\n if len(A) < 3:\n return False\n for i in range(len(A) - 1):\n if A[i] >= A[i + 1]:\n break\n for j in range(-1, -len(A), -1):\n if A[j] >= A[j - 1]:\n break\n return i == len(A) + j", "def validmountainarray(A: List[int]) -> bool:\n n = len(A)\n if n < 3:\n return False\n changes = 0\n is_increasing = False\n is_decreasing = False\n for i in range(0, n - 1):\n if changes == 0:\n if A[i] > A[i + 1]:\n changes += 1\n is_decreasing = True\n elif A[i] == A[i + 1]:\n changes += 1\n else:\n is_increasing = True\n elif changes == 1:\n if A[i] <= A[i + 1]:\n changes += 1\n else:\n is_decreasing = True\n else:\n return False\n return changes < 2 and is_decreasing and is_increasing", "def validmountainarray(A: List[int]) -> bool:\n arr = A\n i = 1\n while i < len(arr):\n if arr[i - 1] < arr[i]:\n i += 1\n else:\n break\n if i == 1 or i == len(arr):\n return False\n while i < len(arr):\n if arr[i - 1] > arr[i]:\n i += 1\n else:\n return False\n return True", "def validmountainarray(A: List[int]) -> bool:\n if len(A) < 3:\n return False\n up = True\n for i in range(1, len(A)):\n if A[i] == A[i - 1]:\n return False\n if up:\n if A[i] < A[i - 1]:\n if i == 1:\n return False\n up = False\n elif A[i] > A[i - 1]:\n return False\n return not up", "def validmountainarray(A: List[int]) -> bool:\n n = len(A)\n if n < 3:\n return False\n i = 0\n while i < n - 1 and A[i] < A[i + 1]:\n i += 1\n if i == 0 or i == n - 1:\n return False\n while i < n - 1 and A[i] > A[i + 1]:\n i += 1\n if i != n - 1:\n return False\n return True", "def validmountainarray(A: List[int]) -> bool:\n passedPeak = False\n if len(A) <= 2 or A[0] > A[1]:\n return False\n for i in range(len(A) - 1):\n if A[i] == A[i + 1]:\n return False\n if passedPeak == True and A[i] < A[i + 1]:\n return False\n if passedPeak == False and A[i] > A[i + 1]:\n passedPeak = True\n if passedPeak:\n return True\n else:\n return False", "def validmountainarray(A: List[int]) -> bool:\n climb = True\n cs = 0\n fs = 0\n for i in range(1, len(A)):\n if climb == True:\n if A[i] > A[i - 1]:\n cs += 1\n continue\n elif A[i] == A[i - 1]:\n return False\n else:\n climb = False\n if climb == False:\n if A[i] < A[i - 1]:\n fs += 1\n continue\n else:\n return False\n if cs > 0 and fs > 0:\n return True\n return False", "def validmountainarray(A: List[int]) -> bool:\n if not A or len(A) <= 2:\n return False\n increase = -1\n for i in range(1, len(A)):\n if A[i] > A[i - 1] and increase == -1:\n increase = 1\n if A[i] > A[i - 1] and increase == 1:\n continue\n elif A[i] < A[i - 1] and increase == 1:\n increase = 0\n elif A[i] < A[i - 1] and increase == 0:\n continue\n else:\n return False\n if increase != 0:\n return False\n return True"], "starter_code": "def validmountainarray(A: List[int]) -> bool:\n", "input_output": {"fn_name": "validMountainArray", "inputs": [[[2, 1]]], "outputs": [false]}, "difficulty": "EASY", "raw_tags": ["Array"], "name": null, "source": "leetcode", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/valid-mountain-array/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "validmountainarray", "task_id": "TACO_lite/392", "example": [[], []]} +{"requirement": "Given two strings s1 and s2 consisting of only lowercase characters whose anagrams are almost equal. The task is to count the number of characters which needs to be edited(delete) to make s1 equal to s2.\nExample:\nInput:\ns1 = madame\ns2 = madam\nOutput:\n1\nExplanation:\nString s1 = madame, string s2 = madam. \ncharacter 'e' in first string needs to \nbe deleted to make s1 equal to s2.\n \nYour Task:\nPrint the count of characters needed to delete to make s1 and s2 equal. Complete the given function.\nExpected Time Complexity: O(max(|s1|,|s2|))\nExpected Auxilary Space: O(|s1| + |s2|) \nConstraints:\n1 <= s1, s2 <= 10^{4}", "solutions": ["def countchars(s1, s2):\n d = {}\n for i in s1:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n e = {}\n for i in s2:\n if i in e:\n e[i] += 1\n else:\n e[i] = 1\n count = 0\n for i in d:\n if i not in e:\n count += d[i]\n else:\n count += abs(d[i] - e[i])\n count1 = 0\n for i in e:\n if i not in d:\n count += e[i]\n else:\n x = e[i] - d[i]\n if x > 0:\n count1 += x\n return max(count, count1)", "def countchars(s1, s2):\n (cc, sum) = (26 * [0], 0)\n for ch in s1:\n cc[ord('a') - ord(ch)] += 1\n for ch in s2:\n cc[ord('a') - ord(ch)] -= 1\n for i in cc:\n sum += abs(i)\n return sum"], "starter_code": "def countchars(s1, s2):\n", "input_output": {"inputs": ["s1 = madame\ns2 = madam"], "outputs": ["1"]}, "difficulty": "EASY", "raw_tags": ["cpp-strings"], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/almost-equal/1", "Expected Auxiliary Space": "O(|s1| + |s2|) ", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(max(|s1|,|s2|))", "entry_point": "countchars", "task_id": "TACO_lite/416", "example": [[["madame", "madam"]], ["1"]]} +{"requirement": "Given a binary tree, find the Postorder Traversal of it.\nFor Example, the postorder traversal of the following tree is: \n5 10 39 1\n 1\n / \\\n 10 39\n /\n5\nExample 1:\nInput:\n 19\n / \\\n 10 8\n / \\\n 11 13\nOutput: 11 13 10 8 19\nExample 2:\nInput:\n 11\n /\n 15\n /\n 7\nOutput: 7 15 11\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function postOrder() that takes root node as input and returns an array containing the postorder traversal of the given Binary Tree.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\nConstraints:\n1 <= Number of nodes <= 10^{5}\n0 <= Data of a node <= 10^{6}", "solutions": ["def postOrder(root):\n\n def helper(root, ans):\n if root:\n helper(root.left, ans)\n helper(root.right, ans)\n ans.append(root.data)\n res = []\n helper(root, res)\n return res", "def postOrder(root):\n li = []\n q = [root]\n while q:\n obg = q.pop()\n if obg:\n li.append(obg.data)\n q.append(obg.left)\n q.append(obg.right)\n li.reverse()\n return li", "def Helper(root, postorder):\n if not root:\n return []\n Helper(root.left, postorder)\n Helper(root.right, postorder)\n postorder.append(root.data)\n return postorder\n\ndef postOrder(root):\n return Helper(root, [])", "def postOrder(root):\n a = []\n\n def postorder(root):\n if root:\n postorder(root.left)\n postorder(root.right)\n a.append(root.data)\n else:\n return\n return a\n return postorder(root)", "def postOrder(root):\n res = []\n helper(root, res)\n return res\n\ndef helper(root, res):\n if root is None:\n return\n helper(root.left, res)\n helper(root.right, res)\n res.append(root.data)", "def PostOrder(root, res):\n if root:\n PostOrder(root.left, res)\n PostOrder(root.right, res)\n res.append(root.data)\n\ndef postOrder(root):\n res = list()\n PostOrder(root, res)\n return res", "def postOrder(root):\n if root is None:\n return []\n return postOrder(root.left) + postOrder(root.right) + [root.data]", "def postOrder(root):\n if root == None:\n return []\n nodes = []\n nodes.extend(postOrder(root.left))\n nodes.extend(postOrder(root.right))\n nodes.append(root.data)\n return nodes", "def postOrder(root):\n ans = []\n if root is not None:\n ans += postOrder(root.left)\n ans += postOrder(root.right)\n ans.append(root.data)\n return ans", "def postOrder(root):\n ans = []\n if root.left:\n ans += postOrder(root.left)\n if root.right:\n ans += postOrder(root.right)\n ans.append(root.data)\n return ans", "def postOrder(root):\n s = [root]\n res = []\n while len(s) > 0:\n node = s.pop()\n res.append(node.data)\n if node.left:\n s.append(node.left)\n if node.right:\n s.append(node.right)\n res.reverse()\n return res", "def postOrder(root):\n if root == None:\n return []\n ans1 = postOrder(root.left)\n ans2 = postOrder(root.right)\n ans = [root.data]\n ans = ans1 + ans2 + ans\n return ans", "def postOrder(root):\n stack = [root]\n ans = []\n while stack:\n node = stack.pop()\n ans.append(node.data)\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n return ans[::-1]", "def po(root, s):\n if not root:\n return\n po(root.left, s)\n po(root.right, s)\n s.append(root.data)\n\ndef postOrder(root):\n s = []\n po(root, s)\n return s", "arr = []\n\ndef postOrder(root):\n if root is None:\n return []\n left_nodes = postOrder(root.left)\n right_nodes = postOrder(root.right)\n return left_nodes + right_nodes + [root.data]", "def postOrder(root):\n ans = []\n if root is None:\n return ans\n stack = []\n stack.append(root)\n while len(stack) != 0:\n top = stack.pop()\n if top.left is not None:\n stack.append(top.left)\n if top.right is not None:\n stack.append(top.right)\n ans.append(top.data)\n return ans[::-1]", "def postOrder(root):\n if root:\n return postOrder(root.left) + postOrder(root.right) + [root.data]\n else:\n return []", "def solve(root, l):\n if root:\n solve(root.left, l)\n solve(root.right, l)\n l.append(root.data)\n\ndef postOrder(root):\n l = []\n solve(root, l)\n return l", "def cal_postorder(root, ans_lst):\n if root:\n cal_postorder(root.left, ans_lst)\n cal_postorder(root.right, ans_lst)\n ans_lst.append(root.data)\n return ans_lst\n\ndef postOrder(root):\n ans_lst = []\n return cal_postorder(root, ans_lst)", "def postOrder(root):\n trav = []\n\n def traverse(root):\n if not root:\n return\n traverse(root.left)\n traverse(root.right)\n trav.append(root.data)\n traverse(root)\n return trav", "def helper(root, ans):\n if root == None:\n return\n helper(root.left, ans)\n helper(root.right, ans)\n ans.append(root.data)\n\ndef postOrder(root):\n ans = []\n helper(root, ans)\n return ans", "def postOrder(root):\n result = []\n if root.left:\n result += postOrder(root.left)\n if root.right:\n result += postOrder(root.right)\n result.append(root.data)\n return result", "def postOrder(root):\n res = []\n if root.left:\n res += postOrder(root.left)\n if root.right:\n res += postOrder(root.right)\n res.append(root.data)\n return res", "def postOrder(root):\n post = []\n st = []\n curr = root\n while curr != None or len(st) != 0:\n if curr != None:\n st.append(curr)\n curr = curr.left\n else:\n temp = st[-1].right\n if temp == None:\n temp = st.pop()\n post.append(temp.data)\n while len(st) != 0 and temp == st[-1].right:\n temp = st.pop()\n post.append(temp.data)\n else:\n curr = temp\n return post", "def postOrder(root):\n postorder = []\n if not root:\n return postorder\n st1 = deque()\n st2 = deque()\n st1.append(root)\n while len(st1) != 0:\n node = st1.pop()\n st2.append(node)\n if node.left:\n st1.append(node.left)\n if node.right:\n st1.append(node.right)\n while len(st2) != 0:\n node = st2.pop()\n postorder.append(node.data)\n return postorder", "def postOrder(root):\n stack = [(root, False)]\n ans = []\n while stack:\n (node, visited) = stack.pop()\n if visited:\n ans.append(node.data)\n elif node:\n stack.append((node, True))\n stack.append((node.right, False))\n stack.append((node.left, False))\n return ans", "def postOrder(root):\n if root is None:\n return\n a = [root]\n ans = []\n while a:\n t = a.pop()\n ans.append(t.data)\n if t.left:\n a.append(t.left)\n if t.right:\n a.append(t.right)\n return ans[::-1]", "def postOrder(root):\n arr = []\n solve(root, arr)\n return arr\n\ndef solve(root, arr):\n if root is None:\n return\n solve(root.left, arr)\n solve(root.right, arr)\n arr.append(root.data)", "def po(root, arr):\n if root:\n po(root.left, arr)\n po(root.right, arr)\n arr.append(root.data)\n\ndef postOrder(root):\n arr = []\n po(root, arr)\n return arr", "def postOrder(root):\n if root:\n l = postOrder(root.left)\n r = postOrder(root.right)\n return l + r + [root.data]\n return []", "def postOrder(root):\n res = []\n postOrder_res(res, root)\n return res\n\ndef postOrder_res(res, root):\n if root == None:\n return\n postOrder_res(res, root.left)\n postOrder_res(res, root.right)\n res.append(root.data)", "def postOrder(root):\n mylist = []\n ans = postOrderHelper(root, mylist)\n x = []\n if ans == -1:\n x.append(-1)\n return x\n return ans\n\ndef postOrderHelper(root, mylist):\n if root is None:\n return -1\n postOrderHelper(root.left, mylist)\n postOrderHelper(root.right, mylist)\n mylist.append(root.data)\n return mylist", "def postOrder(root):\n current = root\n stack = []\n ans = []\n while current or stack:\n if current:\n if current.right:\n stack.append(current.right)\n stack.append(current)\n current = current.left\n else:\n node = stack.pop()\n if stack and node.right == stack[-1]:\n current = stack.pop()\n stack.append(node)\n else:\n ans.append(node.data)\n return ans", "def postOrder(root):\n\n def getpostorder(root):\n if not root:\n return\n getpostorder(root.left)\n getpostorder(root.right)\n ans.append(root.data)\n return ans\n ans = []\n getpostorder(root)\n return ans", "def postOrder(root):\n s1 = []\n s2 = []\n res = []\n s1.append(root)\n while len(s1) != 0:\n popped_val = s1.pop()\n s2.append(popped_val)\n if popped_val.left:\n s1.append(popped_val.left)\n if popped_val.right:\n s1.append(popped_val.right)\n while len(s2) != 0:\n res.append(s2.pop().data)\n return res", "def postOrder(root):\n if root is None:\n return []\n lst = postOrder(root.left) + postOrder(root.right)\n lst.append(root.data)\n return lst", "def postOrder(root):\n if root is None:\n return\n stack = []\n result = []\n stack.append(root)\n while stack:\n current = stack.pop()\n result.append(current.data)\n if current.left:\n stack.append(current.left)\n if current.right:\n stack.append(current.right)\n result = result[::-1]\n return result", "def postOrder(root):\n result = []\n\n def postOrderTraversal(node):\n if node is None:\n return\n postOrderTraversal(node.left)\n postOrderTraversal(node.right)\n result.append(node.data)\n postOrderTraversal(root)\n return result", "def postOrder(root):\n if root == None:\n return []\n rn = postOrder(root.right)\n ln = postOrder(root.left)\n return ln + rn + [root.data]", "def helper(root, ans):\n if not root:\n return ans\n helper(root.left, ans)\n helper(root.right, ans)\n ans.append(root.data)\n return ans\n\ndef postOrder(root):\n return helper(root, [])", "def postOrder(root):\n if root == None:\n return []\n if root.left == None and root.right == None:\n return [root.data]\n leftarr = postOrder(root.left)\n rightarr = postOrder(root.right)\n return leftarr + rightarr + [root.data]", "def postOrder(root):\n answer = []\n stack = [root]\n while stack:\n node = stack.pop()\n answer.append(node.data)\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n return list(reversed(answer))", "def postOrder(root):\n res = []\n\n def post(root, res):\n if root != None:\n post(root.left, res)\n post(root.right, res)\n res.append(root.data)\n post(root, res)\n return res", "def postOrder(root):\n l = []\n\n def traverse(node):\n if node:\n traverse(node.left)\n traverse(node.right)\n l.append(node.data)\n traverse(root)\n return l", "def postOrder(root):\n ans = []\n stk = [root]\n curr = None\n while stk:\n curr = stk.pop()\n ans.append(curr.data)\n if curr.left:\n stk.append(curr.left)\n if curr.right:\n stk.append(curr.right)\n return ans[::-1]", "def postOrder(root):\n stack1 = []\n stack2 = []\n stack1.append(root)\n node = root\n while stack1:\n node = stack1[-1]\n stack2.append(stack1[-1].data)\n stack1.pop()\n if node.left:\n stack1.append(node.left)\n if node.right:\n stack1.append(node.right)\n return stack2[::-1]", "def getList(root, li):\n if root:\n getList(root.left, li)\n getList(root.right, li)\n li.append(root.data)\n\ndef postOrder(root):\n li = []\n getList(root, li)\n return li", "def postOrder(root):\n if root == None:\n return []\n if root.left == None and root.right == None:\n return [root.data]\n left = postOrder(root.left)\n right = postOrder(root.right)\n arr = []\n arr += left + right\n arr.append(root.data)\n return arr", "def postOrder(root):\n\n def cal(root, stack):\n if root is None:\n return\n cal(root.left, stack)\n cal(root.right, stack)\n stack.append(root.data)\n stack = []\n cal(root, stack)\n return stack", "def postOrder(root):\n\n def postOrderTraversal(root, l):\n if root is None:\n return\n if root.left:\n root.left = postOrderTraversal(root.left, l)\n if root.right:\n root.right = postOrderTraversal(root.right, l)\n l.append(root.data)\n l = []\n postOrderTraversal(root, l)\n return l", "def rec_sol(root, ans):\n if root.left != None:\n rec_sol(root.left, ans)\n if root.right != None:\n rec_sol(root.right, ans)\n ans.append(root.data)\n\ndef postOrder(root):\n ans = []\n stack = []\n stack.append(root)\n while len(stack) != 0:\n node = stack.pop()\n ans.append(node.data)\n if node.left != None:\n stack.append(node.left)\n if node.right != None:\n stack.append(node.right)\n ans.reverse()\n return ans", "def rec_sol(root, ans):\n if root.left != None:\n rec_sol(root.left, ans)\n if root.right != None:\n rec_sol(root.right, ans)\n ans.append(root.data)\n\ndef postOrder(root):\n ans = []\n rec_sol(root, ans)\n return ans", "def postOrder(root):\n z = []\n\n def post(root):\n if root == None:\n return\n post(root.left)\n post(root.right)\n z.append(root.data)\n post(root)\n return z", "def postOrder(root):\n a = []\n\n def solve(root):\n if root:\n solve(root.left)\n solve(root.right)\n a.append(root.data)\n solve(root)\n return a", "def postOrder(root):\n ans = []\n\n def post(root):\n if root != None:\n post(root.left)\n post(root.right)\n ans.append(root.data)\n post(root)\n return ans", "def postorderutil(root, res):\n if root != None:\n postorderutil(root.left, res)\n postorderutil(root.right, res)\n res.append(root.data)\n\ndef postOrder(root):\n res = []\n postorderutil(root, res)\n return res", "def postOrder(root):\n if root == None:\n return []\n left_nodes = postOrder(root.left)\n right_nodes = postOrder(root.right)\n return left_nodes + right_nodes + [root.data]", "def postOrder(root):\n ans = []\n stk = []\n cur = root\n while cur or len(stk):\n if cur != None:\n ans.append(cur.data)\n stk.append(cur)\n cur = cur.right\n else:\n cur = stk.pop()\n cur = cur.left\n return ans[::-1]", "def postOrder(root):\n if root == None:\n return []\n left_n = postOrder(root.left)\n right_n = postOrder(root.right)\n ans = left_n + right_n + [root.data]\n return ans"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["19\n / \\\n 10 8\n / \\\n 11 13", "11\n /\n 15\n /\n 7"], "outputs": ["11 13 10 8 19", "7 15 11"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/postorder-traversal/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "__init__", "task_id": "TACO_lite/376", "example": [[], []]} +{"requirement": "Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K.\n(For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.)\nReturn the number of good subarrays of A.\n \nExample 1:\nInput: A = [1,2,1,2,3], K = 2\nOutput: 7\nExplanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].\n\nExample 2:\nInput: A = [1,2,1,3,4], K = 3\nOutput: 3\nExplanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].\n\n \nNote:\n\n1 <= A.length <= 20000\n1 <= A[i] <= A.length\n1 <= K <= A.length", "solutions": ["from collections import defaultdict\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n start_k = 0\n start = 0\n elem_dict = defaultdict(int)\n ans = 0\n for elem in A:\n elem_dict[elem] += 1\n if len(elem_dict) > K:\n del elem_dict[A[start_k]]\n start_k += 1\n start = start_k\n if len(elem_dict) == K:\n while elem_dict[A[start_k]] > 1:\n elem_dict[A[start_k]] -= 1\n start_k += 1\n ans = ans + start_k - start + 1\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n if K > len(A):\n return 0\n result = checker = windowStart = 0\n hashMap = {}\n a_length = len(A)\n for windowEnd in range(a_length):\n curr_str = A[windowEnd]\n if curr_str in hashMap:\n hashMap[curr_str] += 1\n else:\n hashMap[curr_str] = 1\n if len(hashMap) > K:\n del hashMap[A[checker]]\n checker += 1\n windowStart = checker\n if len(hashMap) == K:\n while hashMap[A[checker]] > 1:\n hashMap[A[checker]] -= 1\n checker += 1\n result += checker - windowStart + 1\n return result", "from collections import OrderedDict\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n counter = OrderedDict()\n count = 0\n j = 0\n for (i, n) in enumerate(A):\n counter[n] = i\n counter.move_to_end(n)\n while len(counter) > K:\n j = counter.popitem(last=False)[1] + 1\n if len(counter) == K:\n count += next(iter(counter.values())) - j + 1\n return count", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n (ans, ctr, lb, count) = (0, {}, 0, 0)\n for (i, val) in enumerate(A):\n if val not in ctr:\n ctr[val] = 0\n ctr[val] += 1\n while len(ctr) > K:\n ctr[A[lb]] -= 1\n if ctr[A[lb]] == 0:\n del ctr[A[lb]]\n lb += 1\n if len(ctr) == K:\n (p2, count, ctr1) = (lb, 0, collections.Counter())\n while len(ctr) == K:\n count += 1\n ctr[A[p2]] -= 1\n if ctr[A[p2]] == 0:\n del ctr[A[p2]]\n ctr1[A[p2]] += 1\n p2 += 1\n ans += count\n for (k, v) in ctr1.items():\n ctr[k] = ctr.get(k, 0) + v\n return ans\n\ndef __init__():\n self.count = collections.Counter()\n self.nonzero = 0\n\ndef add(x):\n self.count[x] += 1\n if self.count[x] == 1:\n self.nonzero += 1\n\ndef remove(x):\n self.count[x] -= 1\n if self.count[x] == 0:\n self.nonzero -= 1\n\ndef subarrayswithkdistinct(A, K):\n window1 = Window()\n window2 = Window()\n ans = left1 = left2 = 0\n for (right, x) in enumerate(A):\n window1.add(x)\n window2.add(x)\n while window1.nonzero > K:\n window1.remove(A[left1])\n left1 += 1\n while window2.nonzero >= K:\n window2.remove(A[left2])\n left2 += 1\n ans += left2 - left1\n return ans", "def __init__():\n self.count = collections.Counter()\n self.nonzero = 0\n\ndef add(x):\n self.count[x] += 1\n if self.count[x] == 1:\n self.nonzero += 1\n\ndef remove(x):\n self.count[x] -= 1\n if self.count[x] == 0:\n self.nonzero -= 1\n\ndef subarrayswithkdistinct(A, K):\n window1 = Window()\n window2 = Window()\n ans = left1 = left2 = 0\n for (right, x) in enumerate(A):\n window1.add(x)\n window2.add(x)\n while window1.nonzero > K:\n window1.remove(A[left1])\n left1 += 1\n while window2.nonzero >= K:\n window2.remove(A[left2])\n left2 += 1\n ans += left2 - left1\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n from collections import Counter\n\n def atMost(k):\n count = Counter()\n ans = i = 0\n for j in range(len(A)):\n if not count[A[j]]:\n k -= 1\n count[A[j]] += 1\n while k < 0:\n count[A[i]] -= 1\n if not count[A[i]]:\n k += 1\n i += 1\n ans += j - i + 1\n return ans\n return atMost(K) - atMost(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMostK(K):\n i = 0\n count = 0\n counts = Counter()\n for j in range(len(A)):\n if counts[A[j]] == 0:\n K -= 1\n counts[A[j]] += 1\n while K < 0:\n counts[A[i]] -= 1\n if counts[A[i]] == 0:\n K += 1\n i += 1\n count += j - i + 1\n return count\n return atMostK(K) - atMostK(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n start = 0\n first_uni = 0\n re = 0\n dd = {}\n for (i, cur) in enumerate(A):\n dd[cur] = dd.get(cur, 0) + 1\n if len(dd) == K + 1:\n dd.pop(A[first_uni])\n first_uni += 1\n start = first_uni\n if len(dd) == K:\n while first_uni <= i and dd[A[first_uni]] != 1:\n dd[A[first_uni]] -= 1\n first_uni += 1\n re += first_uni - start + 1\n return re", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n N = len(A)\n\n def atMost(k):\n if k == 0:\n return 0\n ret = i = j = 0\n cnt = Counter()\n while i < N:\n x = A[i]\n while j < N and (len(cnt) < k or A[j] in cnt):\n cnt[A[j]] += 1\n j += 1\n ret += j - i\n cnt[x] -= 1\n if cnt[x] == 0:\n del cnt[x]\n i += 1\n return ret\n return atMost(K) - atMost(K - 1)", "def subarrayswithkdistinct(s: List[int], K: int) -> int:\n obj = defaultdict(int)\n first = 0\n second = 0\n answer = 0\n for i in range(len(s)):\n obj[s[i]] += 1\n if len(obj) == K + 1:\n del obj[s[second]]\n second += 1\n first = second\n if len(obj) == K:\n while obj[s[second]] > 1:\n obj[s[second]] -= 1\n second += 1\n answer += second - first + 1\n return answer", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n length = len(A)\n\n class counter:\n\n def __init__(self):\n self.c = Counter()\n\n def addValue(self, num):\n self.c[num] += 1\n\n def removeValue(self, num):\n self.c[num] -= 1\n if self.c[num] == 0:\n del self.c[num]\n\n def subarraysWithAtLeast(k):\n start = 0\n c = counter()\n ret = 0\n for i in range(length):\n cur = A[i]\n c.addValue(cur)\n if len(c.c) < k:\n ret += i - start + 1\n continue\n while len(c.c) > k:\n tmp = A[start]\n c.removeValue(tmp)\n start += 1\n assert len(c.c) == k\n ret += i - start + 1\n return ret\n return subarraysWithAtLeast(K) - subarraysWithAtLeast(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n int_dict = {}\n int_sorted_list = []\n current = 0\n l = len(A)\n count = 0\n while current < l:\n if int_dict.get(A[current]) != None:\n int_sorted_list.remove(A[current])\n int_dict[A[current]] = current\n int_sorted_list.append(A[current])\n if len(int_sorted_list) > K + 1:\n del int_dict[int_sorted_list[0]]\n del int_sorted_list[0]\n if len(int_sorted_list) > K:\n count += int_dict[int_sorted_list[-K]] - int_dict[int_sorted_list[-K - 1]]\n elif len(int_sorted_list) == K:\n count += int_dict[int_sorted_list[-K]] + 1\n current += 1\n return count", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atmostK(k):\n count = Counter()\n res = 0\n left = 0\n right = 0\n for right in range(len(A)):\n if count[A[right]] == 0:\n k -= 1\n count[A[right]] += 1\n while k < 0:\n count[A[left]] -= 1\n if count[A[left]] == 0:\n k += 1\n left += 1\n res += right - left + 1\n return res\n return atmostK(K) - atmostK(K - 1)", "def count_below(arr, k):\n if k == 0:\n return 0\n else:\n right = 0\n satisfactory = 0\n window = Window()\n for left in range(len(arr)):\n while right < len(arr) and window.added_size(arr[right]) <= k:\n window.add(arr[right])\n right += 1\n satisfactory += right - left\n window.remove(arr[left])\n return satisfactory\n\ndef subarrays_with_k_distinct(arr, k):\n assert k >= 1\n return count_below(arr, k) - count_below(arr, k - 1)\n\ndef __init__():\n self.count = {}\n\ndef add(elem):\n self.count.setdefault(elem, 0)\n self.count[elem] += 1\n\ndef remove(elem):\n self.count[elem] -= 1\n if self.count[elem] == 0:\n del self.count[elem]\n\ndef added_size(elem):\n return len(self.count) + bool(elem not in self.count)\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return subarrays_with_k_distinct(A, K)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n result = 0\n (i, j) = (0, 0)\n cnt = collections.Counter()\n l = 0\n n = len(A)\n while j < n:\n if len(cnt) != K:\n cnt[A[j]] += 1\n if len(cnt) == K:\n l = 1\n while cnt[A[i]] > 1:\n cnt[A[i]] -= 1\n i += 1\n l += 1\n result += l\n elif A[j] in cnt:\n cnt[A[j]] += 1\n while cnt[A[i]] > 1:\n cnt[A[i]] -= 1\n i += 1\n l += 1\n result += l\n else:\n cnt[A[i]] -= 1\n if cnt[A[i]] == 0:\n cnt.pop(A[i])\n cnt[A[j]] += 1\n i += 1\n l = 1\n while cnt[A[i]] > 1:\n cnt[A[i]] -= 1\n i += 1\n l += 1\n result += l\n j += 1\n return result", "def __init__():\n self.counter = collections.Counter()\n\ndef add(x):\n self.counter[x] += 1\n\ndef remove(x):\n self.counter[x] -= 1\n if self.counter[x] == 0:\n self.counter.pop(x)\n\ndef __len__():\n return len(self.counter)\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n window1 = Window()\n window2 = Window()\n (left1, left2) = (0, 0)\n result = 0\n for (right, num) in enumerate(A):\n window1.add(num)\n window2.add(num)\n while len(window1) > K:\n window1.remove(A[left1])\n left1 += 1\n while len(window2) >= K:\n window2.remove(A[left2])\n left2 += 1\n result += left2 - left1\n return result", "def __init__():\n self.KeyToCount = {}\n self.q = deque()\n\ndef append(value):\n self.q.append(value)\n self.KeyToCount[value] = self.KeyToCount.get(value, 0) + 1\n\ndef popleft():\n v = self.q.popleft()\n if self.KeyToCount[v] == 1:\n del self.KeyToCount[v]\n else:\n self.KeyToCount[v] -= 1\n\ndef distinctCount():\n return len(self.KeyToCount)\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n n = len(A)\n nextHiIdx = 0\n nextLoIdx = 0\n loAcc = Accumulator()\n hiAcc = Accumulator()\n lo = [None] * n\n hi = [None] * n\n for i in range(n):\n if i >= 1:\n hiAcc.popleft()\n loAcc.popleft()\n while nextLoIdx < n and loAcc.distinctCount() < K:\n loAcc.append(A[nextLoIdx])\n nextLoIdx += 1\n while nextHiIdx < n and hiAcc.distinctCount() <= K:\n hiAcc.append(A[nextHiIdx])\n nextHiIdx += 1\n if loAcc.distinctCount() == K:\n lo[i] = nextLoIdx - 1\n if hiAcc.distinctCount() == K + 1:\n hi[i] = nextHiIdx - 1\n elif hiAcc.distinctCount() == K and nextHiIdx == n:\n hi[i] = nextHiIdx\n return sum((hi[i] - lo[i] for i in range(n) if hi[i] != None))", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMost(K):\n N = len(A)\n ct = collections.Counter()\n ans = 0\n i = 0\n for j in range(N):\n ct[A[j]] += 1\n if len(ct) <= K:\n ans += j - i + 1\n else:\n while len(ct) > K:\n ct[A[i]] -= 1\n if ct[A[i]] == 0:\n del ct[A[i]]\n i += 1\n ans += j - i + 1\n return ans\n return atMost(K) - atMost(K - 1)", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n window1 = Window()\n window2 = Window()\n res = 0\n (left1, left2) = (0, 0)\n for i in range(len(A)):\n window1.add(A[i])\n window2.add(A[i])\n while window1.size() > K:\n window1.remove(A[left1])\n left1 += 1\n while window2.size() > K - 1:\n window2.remove(A[left2])\n left2 += 1\n res += left2 - left1\n return res\n\ndef __init__():\n self.counter = Counter()\n\ndef add(x):\n self.counter[x] += 1\n\ndef remove(x):\n self.counter[x] -= 1\n if self.counter[x] == 0:\n del self.counter[x]\n\ndef size():\n return len(self.counter)", "def subarrayswithkdistinct(A: 'List[int]', K: 'int') -> 'int':\n return self.subarraysWithKMax(A, K) - self.subarraysWithKMax(A, K - 1)\n\ndef subarraysWithKMax(A, K):\n k = 0\n count = dict()\n (i, start) = (0, 0)\n res = 0\n while i < len(A):\n if A[i] not in count:\n k += 1\n count[A[i]] = 1\n else:\n count[A[i]] += 1\n i += 1\n while start < i and k > K:\n count[A[start]] -= 1\n if count[A[start]] == 0:\n del count[A[start]]\n k -= 1\n start += 1\n res += i - start\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.atMostK(A, K) - self.atMostK(A, K - 1)\n\ndef atMostK(A, K):\n counter = collections.Counter()\n res = i = 0\n for j in range(len(A)):\n if counter[A[j]] == 0:\n K -= 1\n counter[A[j]] += 1\n while K < 0:\n counter[A[i]] -= 1\n if counter[A[i]] == 0:\n K += 1\n i += 1\n res += j - i + 1\n return res", "from collections import Counter\n\ndef __init__():\n self.count = Counter()\n self.nonzero = 0\n\ndef add(val):\n self.count[val] += 1\n if self.count[val] == 1:\n self.nonzero += 1\n\ndef remove(val):\n self.count[val] -= 1\n if self.count[val] == 0:\n self.nonzero -= 1\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n ans = 0\n (l1, l2) = (0, 0)\n (w1, w2) = (Window(), Window())\n for (r, val) in enumerate(A):\n w1.add(val)\n w2.add(val)\n while w1.nonzero > K:\n w1.remove(A[l1])\n l1 += 1\n while w2.nonzero >= K:\n w2.remove(A[l2])\n l2 += 1\n ans += l2 - l1\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n class UniqueCounter(object):\n\n def __init__(self):\n self.non_zero = 0\n self.counts = collections.defaultdict(int)\n\n def add(self, x):\n if self.counts[x] == 0:\n self.non_zero += 1\n self.counts[x] += 1\n\n def remove(self, x):\n self.counts[x] -= 1\n if self.counts[x] == 0:\n self.non_zero -= 1\n\n def count(self):\n return self.non_zero\n\n def subarrays_with_max_K(A, K):\n j = 0\n uc = UniqueCounter()\n uc.add(A[0])\n answer = 0\n for i in range(len(A)):\n while j < len(A) and uc.count() <= K:\n j += 1\n if j < len(A):\n uc.add(A[j])\n answer += j - i\n uc.remove(A[i])\n return answer\n return subarrays_with_max_K(A, K) - subarrays_with_max_K(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n last_seen = {}\n start = end = 0\n ans = 0\n for (i, x) in enumerate(A):\n last_seen[x] = i\n while len(last_seen) > K:\n if last_seen[A[start]] == start:\n del last_seen[A[start]]\n start += 1\n while A[end] not in last_seen or last_seen[A[end]] != end:\n end += 1\n if len(last_seen) == K:\n ans += end - start + 1\n return ans", "from collections import Counter\n\ndef solve(A, K):\n count = Counter()\n front = iter(A)\n ans = 0\n size = 0\n for k in A:\n count[k] += 1\n size += 1\n while len(count) > K:\n key = next(front)\n count[key] -= 1\n size -= 1\n if count[key] == 0:\n del count[key]\n ans += size\n return ans\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return solve(A, K) - solve(A, K - 1)", "def __init__():\n self.count = collections.Counter()\n self.nonzero = 0\n\ndef add(x):\n self.count[x] += 1\n if self.count[x] == 1:\n self.nonzero += 1\n\ndef remove(x):\n self.count[x] -= 1\n if self.count[x] == 0:\n self.nonzero -= 1\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n window1 = Window()\n window2 = Window()\n ans = le1 = le2 = 0\n for (ri, val) in enumerate(A):\n window1.add(val)\n window2.add(val)\n while window1.nonzero > K:\n window1.remove(A[le1])\n le1 += 1\n while window2.nonzero >= K:\n window2.remove(A[le2])\n le2 += 1\n ans += le2 - le1\n return ans", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.at_most(A, K) - self.at_most(A, K - 1)\n\ndef at_most(a, k):\n res = 0\n start = 0\n c = Counter()\n for (end, elem) in enumerate(a):\n if c[elem] == 0:\n k -= 1\n c[elem] += 1\n while start <= end and k < 0:\n c[a[start]] -= 1\n if c[a[start]] == 0:\n k += 1\n start += 1\n res += end - start + 1\n return res", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMostK(A, K):\n counts = Counter()\n (left, result) = (0, 0)\n for right in range(len(A)):\n if counts[A[right]] == 0:\n K -= 1\n counts[A[right]] += 1\n while K < 0:\n counts[A[left]] -= 1\n if counts[A[left]] == 0:\n K += 1\n left += 1\n result += right - left + 1\n return result\n return atMostK(A, K) - atMostK(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n if not A:\n return 0\n l = len(A)\n end = 0\n left1 = 0\n left2 = 0\n map1 = collections.defaultdict(int)\n map2 = collections.defaultdict(int)\n ans = 0\n while end < l:\n ch = A[end]\n map1[ch] += 1\n map2[ch] += 1\n while len(map1) > K and left1 < l:\n temp1 = A[left1]\n map1[temp1] -= 1\n if map1[temp1] == 0:\n del map1[temp1]\n left1 += 1\n while len(map2) >= K and left2 < l:\n temp2 = A[left2]\n map2[temp2] -= 1\n if map2[temp2] == 0:\n del map2[temp2]\n left2 += 1\n ans += left2 - left1\n end += 1\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n n = len(A)\n hashmap = {}\n l = 0\n count = 0\n ans = 0\n sums = 1\n for r in range(n):\n if A[r] in hashmap:\n hashmap[A[r]] += 1\n else:\n hashmap[A[r]] = 1\n if hashmap[A[r]] == 1:\n count += 1\n while count > K or hashmap[A[l]] > 1:\n if count > K:\n sums = 1\n else:\n sums += 1\n hashmap[A[l]] -= 1\n if hashmap[A[l]] == 0:\n count -= 1\n l += 1\n if count == K:\n ans += sums\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def helper(A, K):\n d = defaultdict(int)\n begin = 0\n end = 0\n ans = float('-inf')\n count = 0\n res = 0\n while end < len(A):\n char = A[end]\n d[char] += 1\n if d[char] == 1:\n count += 1\n end += 1\n while count > K:\n temp = A[begin]\n d[temp] -= 1\n if d[temp] == 0:\n count -= 1\n begin += 1\n res += end - begin + 1\n return res\n return helper(A, K) - helper(A, K - 1)", "def subarrayswithkdistinct(A: 'List[int]', K: 'int') -> 'int':\n return self.subarraysWithAtMostKDistinct(A, K) - self.subarraysWithAtMostKDistinct(A, K - 1)\n\ndef subarraysWithAtMostKDistinct(s, k):\n lookup = collections.defaultdict(int)\n (l, r, counter, res) = (0, 0, 0, 0)\n while r < len(s):\n lookup[s[r]] += 1\n if lookup[s[r]] == 1:\n counter += 1\n r += 1\n while l < r and counter > k:\n lookup[s[l]] -= 1\n if lookup[s[l]] == 0:\n counter -= 1\n l += 1\n res += r - l\n return res", "def __init__():\n self.num = 0\n self.dic = collections.defaultdict(int)\n\ndef add(v: int) -> int:\n if self.dic[v] == 0:\n self.num += 1\n self.dic[v] += 1\n return self.num\n\ndef remove(v: int) -> int:\n self.dic[v] -= 1\n if self.dic[v] == 0:\n self.num -= 1\n return self.num\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n wk = Window()\n wm = Window()\n sk = 0\n sm = 0\n e = 0\n ans = 0\n while e < len(A):\n ce = A[e]\n nk = wk.add(ce)\n nm = wm.add(ce)\n if nk < K:\n e += 1\n elif nk == K:\n while nm != K - 1:\n nm = wm.remove(A[sm])\n sm += 1\n ans += sm - sk\n e += 1\n else:\n while nk != K:\n nk = wk.remove(A[sk])\n sk += 1\n while nm != K - 1:\n nm = wm.remove(A[sm])\n sm += 1\n ans += sm - sk\n e += 1\n return ans", "def __init__():\n self.count = collections.Counter()\n self.nonzero = 0\n\ndef add(x):\n self.count[x] += 1\n if self.count[x] == 1:\n self.nonzero += 1\n\ndef remove(x):\n self.count[x] -= 1\n if self.count[x] == 0:\n self.nonzero -= 1\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n window1 = Window()\n window2 = Window()\n ans = left1 = left2 = 0\n for x in A:\n window1.add(x)\n window2.add(x)\n while window1.nonzero > K:\n window1.remove(A[left1])\n left1 += 1\n while window2.nonzero >= K:\n window2.remove(A[left2])\n left2 += 1\n ans += left2 - left1\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMostK(kk):\n counter = collections.Counter()\n res = ii = 0\n for jj in range(len(A)):\n if counter[A[jj]] == 0:\n kk -= 1\n counter[A[jj]] += 1\n while kk < 0:\n counter[A[ii]] -= 1\n if counter[A[ii]] == 0:\n kk += 1\n ii += 1\n res += jj - ii + 1\n return res\n return atMostK(K) - atMostK(K - 1)", "from collections import defaultdict as dd\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n n = len(A)\n i = j = 0\n d = dd(int)\n res = 0\n while j < n:\n while j < n and len(d) < K:\n d[A[j]] += 1\n j += 1\n (i1, j1) = (i, j)\n d[A[i]] -= 1\n while d[A[i]] > 0:\n i += 1\n d[A[i]] -= 1\n while j < n and A[j] in d:\n j += 1\n if len(d) == K:\n res += (i - i1 + 1) * (j - j1 + 1)\n d.pop(A[i])\n i += 1\n j = j1\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMostK(A, K):\n (ans, curr) = (0, 0)\n cnt = defaultdict(int)\n i = 0\n for (j, num) in enumerate(A):\n if num not in cnt:\n K -= 1\n cnt[num] += 1\n while K < 0:\n cnt[A[i]] -= 1\n if cnt[A[i]] == 0:\n del cnt[A[i]]\n K += 1\n i += 1\n ans += j - i + 1\n return ans\n return atMostK(A, K) - atMostK(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.at_most_K(A, K) - self.at_most_K(A, K - 1)\n\ndef at_most_K(A, k):\n left = 0\n counter = collections.Counter()\n diff = 0\n result = 0\n for right in range(len(A)):\n counter[A[right]] += 1\n if counter[A[right]] == 1:\n diff += 1\n while diff > k:\n counter[A[left]] -= 1\n if counter[A[left]] == 0:\n diff -= 1\n left += 1\n result += right - left + 1\n return result", "def subarrayswithkdistinct(A, K):\n return self.atMostK(A, K) - self.atMostK(A, K - 1)\n\ndef atMostK(A, K):\n count = collections.Counter()\n res = i = 0\n for j in range(len(A)):\n if count[A[j]] == 0:\n K -= 1\n count[A[j]] += 1\n while K < 0:\n count[A[i]] -= 1\n if count[A[i]] == 0:\n K += 1\n i += 1\n res += j - i + 1\n return res", "from typing import Dict, Set, List, Tuple\nfrom collections import defaultdict\nfrom pprint import pprint\n\ndef __init__():\n self._counter = {}\n self._distinct_num = 0\n\ndef add(num):\n if num in self._counter:\n self._counter[num] += 1\n else:\n self._distinct_num += 1\n self._counter[num] = 1\n\ndef remove(num):\n self._counter[num] -= 1\n if self._counter[num] == 0:\n self._distinct_num -= 1\n del self._counter[num]\n\ndef nums():\n return self._distinct_num\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n w1 = Window()\n w2 = Window()\n x = y = z = 0\n result = 0\n while z < len(A):\n w1.add(A[z])\n w2.add(A[z])\n z += 1\n while w1.nums > K:\n w1.remove(A[x])\n x += 1\n while w2.nums > K - 1:\n w2.remove(A[y])\n y += 1\n if w1.nums == K:\n assert w2.nums == K - 1\n result += y - x\n return result", "from collections import defaultdict\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n n = len(A)\n if n < K:\n return 0\n count = defaultdict(int)\n p1 = 0\n p2 = 0\n p3 = 0\n count[A[0]] += 1\n ans = 0\n while p2 < n:\n remaining = K - len(count)\n while remaining > 0:\n p2 += 1\n if p2 == n:\n return ans\n count[A[p2]] += 1\n if count[A[p2]] == 1:\n remaining -= 1\n while p3 < n and A[p3] in count:\n p3 += 1\n while len(count) == K:\n ans += p3 - p2\n p1 += 1\n count[A[p1 - 1]] -= 1\n if count[A[p1 - 1]] == 0:\n del count[A[p1 - 1]]\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n checkSet = OrderedDict()\n windowStart = 0\n count = 0\n ans = []\n for (i, n) in enumerate(A):\n checkSet[n] = i\n checkSet.move_to_end(n)\n while len(checkSet) > K:\n windowStart = checkSet.popitem(last=False)[1] + 1\n if len(checkSet) == K:\n count += next(iter(list(checkSet.items())))[1] - windowStart + 1\n return count", "def subarrayswithkdistinct(A: List[int], k: int) -> int:\n dic = {}\n n = len(A)\n left = 0\n right = 0\n cnt = 0\n for i in range(n):\n if A[i] in dic:\n dic[A[i]] += 1\n else:\n dic[A[i]] = 1\n l = len(dic)\n if l == k + 1:\n del dic[A[right]]\n right += 1\n left = right\n l -= 1\n if l == k:\n while dic[A[right]] > 1:\n dic[A[right]] -= 1\n right += 1\n cnt += right - left + 1\n return cnt", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n left1 = 0\n left2 = 0\n w1 = {}\n w2 = {}\n count = 0\n for (right, x) in enumerate(A):\n if x in w1:\n w1[x] += 1\n else:\n w1[x] = 1\n if x in w2:\n w2[x] += 1\n else:\n w2[x] = 1\n while len(w1) > K:\n if w1[A[left1]] == 1:\n w1.pop(A[left1])\n elif w1[A[left1]] > 1:\n w1[A[left1]] -= 1\n left1 += 1\n while len(w2) >= K:\n if w2[A[left2]] == 1:\n w2.pop(A[left2])\n elif w2[A[left2]] > 1:\n w2[A[left2]] -= 1\n left2 += 1\n count += left2 - left1\n return count", "def _identify_limit(A, current_limit, K, char_count_after_limit):\n temp_char = A[current_limit]\n while char_count_after_limit.get(temp_char, 0) > 1:\n char_count_after_limit[temp_char] = char_count_after_limit[temp_char] - 1\n current_limit += 1\n temp_char = A[current_limit]\n return (current_limit, char_count_after_limit)\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n char_info = {item: [] for item in set(A)}\n unique_char_count = {}\n unique_char = set()\n start_idx = 0\n end_idx = 0\n num_substr = 0\n current_subarray = []\n current_valid_count = 0\n limit_idx = 0\n while end_idx < len(A) + 1:\n if len(unique_char_count) == K:\n (limit_idx, unique_char_count) = self._identify_limit(A, limit_idx, K, unique_char_count)\n num_substr += limit_idx - start_idx + 1\n if end_idx < len(A):\n current_char = A[end_idx]\n unique_char_count[current_char] = unique_char_count.get(current_char, 0) + 1\n end_idx += 1\n elif len(unique_char_count) > K:\n current_char = A[limit_idx]\n unique_char_count.pop(current_char)\n start_idx = limit_idx + 1\n limit_idx = start_idx\n else:\n if end_idx < len(A):\n current_char = A[end_idx]\n unique_char_count[current_char] = unique_char_count.get(current_char, 0) + 1\n end_idx += 1\n return num_substr", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n (d, t) = (defaultdict(int), defaultdict(int))\n (a, b) = (K, K)\n (left, right) = (0, 0)\n res = 0\n for (i, ele) in enumerate(A):\n a -= 1 if d[ele] == 0 else 0\n b -= 1 if t[ele] == 0 else 0\n d[ele] += 1\n t[ele] += 1\n while a < 0:\n a += 1 if d[A[left]] == 1 else 0\n d[A[left]] -= 1\n left += 1\n while b <= 0:\n b += 1 if t[A[right]] == 1 else 0\n t[A[right]] -= 1\n right += 1\n res += right - left\n return res", "def subarrayswithkdistinct(A: 'List[int]', K: 'int') -> 'int':\n freq = {}\n start = 0\n start_k = 0\n res = 0\n for (i, x) in enumerate(A):\n freq[x] = freq.get(x, 0) + 1\n if len(freq) == K + 1:\n del freq[A[start_k]]\n start_k += 1\n start = start_k\n if len(freq) == K:\n while freq[A[start_k]] > 1:\n freq[A[start_k]] -= 1\n start_k += 1\n res += start_k - start + 1\n return res", "from collections import defaultdict\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n total = 0\n l1 = 0\n l2 = 0\n memo1 = defaultdict(int)\n memo2 = defaultdict(int)\n for (r, c) in enumerate(A):\n memo1[c] += 1\n memo2[c] += 1\n while len(memo1) > K:\n memo1[A[l1]] -= 1\n if memo1[A[l1]] == 0:\n del memo1[A[l1]]\n l1 += 1\n while len(memo2) >= K:\n memo2[A[l2]] -= 1\n if memo2[A[l2]] == 0:\n del memo2[A[l2]]\n l2 += 1\n total += l2 - l1\n return total", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def help(k):\n res = 0\n left = 0\n d = {}\n for (i, ele) in enumerate(A):\n d[ele] = d.get(ele, 0) + 1\n while len(d) > k:\n d[A[left]] -= 1\n if d[A[left]] == 0:\n del d[A[left]]\n left += 1\n res += i - left\n return res\n return help(K) - help(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atmost(k):\n i = 0\n res = 0\n d = defaultdict(int)\n for (j, a) in enumerate(A):\n if d[a] == 0:\n k -= 1\n d[a] += 1\n while k < 0:\n d[A[i]] -= 1\n if d[A[i]] == 0:\n k += 1\n i += 1\n res += j - i + 1\n return res\n return atmost(K) - atmost(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMost(A: List[int], K: int) -> int:\n d = collections.defaultdict(int)\n i = ret = 0\n for j in range(len(A)):\n d[A[j]] += 1\n while len(d) > K:\n d[A[i]] -= 1\n if d[A[i]] == 0:\n del d[A[i]]\n i += 1\n ret += j - i + 1\n return ret\n return atMost(A, K) - atMost(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def getAtMost(K):\n freq = defaultdict(int)\n subarray_count = 0\n left = 0\n for (right, num) in enumerate(A):\n freq[num] += 1\n while len(freq) > K:\n freq[A[left]] -= 1\n if freq[A[left]] == 0:\n del freq[A[left]]\n left += 1\n subarray_count += right - left + 1\n return subarray_count\n return getAtMost(K) - getAtMost(K - 1)", "from collections import defaultdict\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n if K == 0:\n return 0\n res1 = self.helper(A, K)\n res2 = self.helper(A, K - 1)\n return res1 - res2\n\ndef helper(a, k):\n if k == 0:\n return 0\n count = defaultdict(int)\n result = 0\n l = 0\n r = 0\n while r < len(a):\n count[a[r]] += 1\n while len(count) > k:\n count[a[l]] -= 1\n if count[a[l]] == 0:\n count.pop(a[l])\n l += 1\n result += r - l + 1\n r += 1\n return result", "def subarrayswithkdistinct(A, K):\n (cnt1, cnt2) = (dict(), dict())\n (res, i1, i2) = (0, 0, 0)\n for v in A:\n cnt1[v] = cnt1.get(v, 0) + 1\n cnt2[v] = cnt2.get(v, 0) + 1\n while len(cnt1) > K:\n cnt1[A[i1]] -= 1\n if cnt1[A[i1]] == 0:\n del cnt1[A[i1]]\n i1 += 1\n while len(cnt2) >= K:\n cnt2[A[i2]] -= 1\n if cnt2[A[i2]] == 0:\n del cnt2[A[i2]]\n i2 += 1\n res += i2 - i1\n return res\n\ndef subarrayswithkdistinct(A, K):\n (cnt1, cnt2) = (dict(), dict())\n (res, i1, i2) = (0, 0, 0)\n for v in A:\n cnt1[v] = cnt1.get(v, 0) + 1\n cnt2[v] = cnt2.get(v, 0) + 1\n while len(cnt1) > K:\n X = A[i1]\n cnt1[X] -= 1\n if cnt1[X] == 0:\n del cnt1[X]\n i1 += 1\n while len(cnt2) > K - 1:\n X = A[i2]\n cnt2[X] -= 1\n if cnt2[X] == 0:\n del cnt2[X]\n i2 += 1\n res += i2 - i1\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.at_most(A, K) - self.at_most(A, K - 1)\n\ndef at_most(A, K):\n if K == 0:\n return 0\n window = {}\n left = 0\n ret = 0\n for right in range(len(A)):\n window[A[right]] = window.get(A[right], 0) + 1\n while left < right and len(window) > K:\n window[A[left]] -= 1\n if window[A[left]] == 0:\n del window[A[left]]\n left += 1\n ret += right - left + 1\n return ret", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n res = 0\n left = right = 0\n window = Counter()\n while right < len(A) and len(window) < K:\n window[A[right]] += 1\n right += 1\n if len(window) < K:\n return 0\n while right < len(A) and len(window) == K:\n rmarker = right\n while right < len(A) and A[right] in window:\n right += 1\n rcount = right - rmarker + 1\n lmarker = left\n while window[A[left]] > 1:\n window[A[left]] -= 1\n left += 1\n lcount = left - lmarker + 1\n res += lcount * rcount\n window[A[left]] -= 1\n del window[A[left]]\n left += 1\n right = rmarker\n while right < len(A) and len(window) < K:\n window[A[right]] += 1\n right += 1\n while len(window) == K:\n window[A[left]] -= 1\n res += 1\n if not window[A[left]]:\n del window[A[left]]\n left += 1\n return res", "def helper(A, B):\n count = 0\n left = 0\n right = 0\n d = {}\n while right < len(A):\n if A[right] not in d:\n d[A[right]] = 0\n d[A[right]] += 1\n while len(d) > B:\n d[A[left]] -= 1\n if d[A[left]] == 0:\n d.pop(A[left])\n left += 1\n count += right - left + 1\n right += 1\n return count\n\ndef subarrayswithkdistinct(A: List[int], B: int) -> int:\n return self.helper(A, B) - self.helper(A, B - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def subarraysWithDictinctAtMost(A: List[int], K: int) -> int:\n (left, right) = (0, 0)\n ans = 0\n counter = dict()\n while right < len(A):\n if A[right] not in counter:\n counter[A[right]] = 0\n counter[A[right]] += 1\n while len(counter) > K:\n counter[A[left]] -= 1\n if counter[A[left]] == 0:\n counter.pop(A[left])\n left += 1\n ans += right - left + 1\n right += 1\n return ans\n return subarraysWithDictinctAtMost(A, K) - subarraysWithDictinctAtMost(A, K - 1)", "def atMostK(arr, k):\n d = {}\n (l, r) = (0, 0)\n count = 0\n while r < len(arr):\n if arr[r] not in d:\n d[arr[r]] = 0\n d[arr[r]] += 1\n while len(d) > k:\n d[arr[l]] -= 1\n if d[arr[l]] == 0:\n d.pop(arr[l])\n l += 1\n count += r - l + 1\n r += 1\n return count\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.atMostK(A, K) - self.atMostK(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMost(A, K):\n left = res = 0\n hash_map = {}\n for right in range(len(A)):\n hash_map[A[right]] = hash_map.get(A[right], 0) + 1\n while len(hash_map) > K:\n hash_map[A[left]] -= 1\n if hash_map[A[left]] == 0:\n del hash_map[A[left]]\n left += 1\n res += right - left + 1\n return res\n return atMost(A, K) - atMost(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n n = len(A)\n if n < K:\n return 0\n left = 0\n right = 0\n totalCount = 0\n dp = [0 for i in range(20001)]\n result = 0\n for right in range(n):\n if dp[A[right]] == 0:\n totalCount += 1\n dp[A[right]] += 1\n while totalCount >= K:\n if totalCount == K:\n result += 1\n dp[A[left]] -= 1\n if dp[A[left]] == 0:\n totalCount -= 1\n left += 1\n while totalCount <= K and left > 0:\n left -= 1\n if dp[A[left]] == 0:\n totalCount += 1\n dp[A[left]] += 1\n return result", "from collections import defaultdict\n\ndef subarrayswithkdistinct(A, K):\n\n def atMostK(K):\n (cnt, res, i) = (defaultdict(int), 0, 0)\n for (j, val) in enumerate(A):\n cnt[val] += 1\n while len(cnt) > K:\n X = A[i]\n cnt[X] -= 1\n if not cnt[X]:\n cnt.pop(X)\n i += 1\n res += j - i + 1\n return res\n return atMostK(K) - atMostK(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMost(k):\n counter = collections.defaultdict(int)\n i = res = 0\n for (j, v) in enumerate(A):\n counter[v] += 1\n while len(counter) > k:\n counter[A[i]] -= 1\n if counter[A[i]] == 0:\n del counter[A[i]]\n i += 1\n res += j - i + 1\n return res\n return atMost(K) - atMost(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.atMost(A, K) - self.atMost(A, K - 1)\n\ndef atMost(A, K):\n if K == 0:\n return 0\n (hi, res) = (0, 0)\n n = len(A)\n count = collections.defaultdict(int)\n for lo in range(n):\n while hi < n and (len(count) < K or A[hi] in count):\n count[A[hi]] += 1\n hi += 1\n res += hi - lo\n count[A[lo]] -= 1\n if count[A[lo]] == 0:\n count.pop(A[lo])\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def at_most_k(arr, k):\n start = 0\n counter = Counter()\n uniques = 0\n res = 0\n for i in range(len(A)):\n counter[A[i]] += 1\n if counter[A[i]] == 1:\n uniques += 1\n while uniques > k:\n counter[A[start]] -= 1\n if counter[A[start]] == 0:\n uniques -= 1\n start += 1\n res += i - start\n return res\n return at_most_k(A, K) - at_most_k(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n keyCounter = defaultdict(int)\n ALen = len(A)\n l = 0\n r = 0\n ans = 0\n KNow = 0\n while r <= ALen:\n if KNow == K:\n ans += 1\n temp = 0\n while r + temp < ALen and keyCounter[A[r + temp]] > 0:\n ans += 1\n temp += 1\n if keyCounter[A[l]] > 0:\n keyCounter[A[l]] -= 1\n if keyCounter[A[l]] == 0:\n KNow -= 1\n l += 1\n elif KNow < K:\n if r == ALen:\n return ans\n if keyCounter[A[r]] == 0:\n KNow += 1\n keyCounter[A[r]] += 1\n r += 1\n else:\n if keyCounter[A[l]] > 0:\n keyCounter[A[l]] -= 1\n if keyCounter[A[l]] == 0:\n KNow -= 1\n l += 1\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def longest_with_atmostk(s, k):\n start = 0\n counts = defaultdict(int)\n n_chars = 0\n max_len = 0\n for i in range(len(s)):\n if counts[s[i]] == 0:\n n_chars += 1\n counts[s[i]] += 1\n while n_chars > k:\n if counts[s[start]] > 0:\n counts[s[start]] -= 1\n if counts[s[start]] == 0:\n n_chars -= 1\n start += 1\n max_len += i - start + 1\n return max_len\n return longest_with_atmostk(A, K) - longest_with_atmostk(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.atMost(A, K) - self.atMost(A, K - 1)\n\ndef atMost(A, k):\n left = res = 0\n freq = collections.Counter()\n for right in range(len(A)):\n if freq[A[right]] == 0:\n k -= 1\n freq[A[right]] += 1\n while k < 0:\n freq[A[left]] -= 1\n if freq[A[left]] == 0:\n k += 1\n left += 1\n res += right - left + 1\n return res", "def subarrayswithkdistinct(A, K):\n\n def atMostK(A, K):\n count = collections.Counter()\n (res, l, window_count) = (0, 0, 0)\n for (r, c) in enumerate(A):\n if count[c] == 0:\n window_count += 1\n count[c] += 1\n while window_count > K:\n count[A[l]] -= 1\n if count[A[l]] == 0:\n window_count -= 1\n l += 1\n res += r - l + 1\n return res\n return atMostK(A, K) - atMostK(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.helper(A, K) - self.helper(A, K - 1)\n\ndef helper(A, K):\n counter = collections.Counter()\n p1 = p2 = 0\n res = 0\n while p2 < len(A):\n if counter[A[p2]] == 0:\n K -= 1\n counter[A[p2]] += 1\n while K < 0:\n counter[A[p1]] -= 1\n if counter[A[p1]] == 0:\n K += 1\n p1 += 1\n p2 += 1\n res += p2 - p1\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMost(K):\n (res, lo, seen) = (0, 0, Counter())\n for hi in range(len(A)):\n if seen[A[hi]] == 0:\n K -= 1\n seen[A[hi]] += 1\n while K < 0:\n seen[A[lo]] -= 1\n if seen[A[lo]] == 0:\n K += 1\n lo += 1\n res += hi - lo + 1\n return res\n return atMost(K) - atMost(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n (counter1, counter2) = (collections.Counter(), collections.Counter())\n slow = fast = res = 0\n for a in A:\n (counter1[a], counter2[a]) = (counter1[a] + 1, counter2[a] + 1)\n while len(counter2) == K:\n counter2[A[fast]] -= 1\n if not counter2[A[fast]]:\n del counter2[A[fast]]\n fast += 1\n while len(counter1) > K:\n counter1[A[slow]] -= 1\n if not counter1[A[slow]]:\n del counter1[A[slow]]\n slow += 1\n res += fast - slow\n return res", "import collections\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n counter = collections.defaultdict(int)\n result = 0\n start = startK = 0\n for (high, num) in enumerate(A):\n counter[num] += 1\n if len(counter) == K + 1:\n del counter[A[startK]]\n startK += 1\n start = startK\n if len(counter) == K:\n while counter[A[startK]] > 1:\n counter[A[startK]] -= 1\n startK += 1\n result += startK - start + 1\n return result", "def subarraysWithAtMostK(A: List[int], K: int) -> int:\n result = i = 0\n count = collections.Counter()\n for j in range(len(A)):\n if count[A[j]] == 0:\n K -= 1\n count[A[j]] += 1\n while K < 0:\n count[A[i]] -= 1\n if count[A[i]] == 0:\n K += 1\n i += 1\n result += j - i + 1\n return result\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.subarraysWithAtMostK(A, K) - self.subarraysWithAtMostK(A, K - 1)", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n W1 = Counter()\n W2 = Counter()\n l1 = 0\n l2 = 0\n res = 0\n for i in range(len(A)):\n W1[A[i]] += 1\n W2[A[i]] += 1\n while len(W1) > K:\n W1[A[l1]] -= 1\n if W1[A[l1]] == 0:\n del W1[A[l1]]\n l1 += 1\n while len(W2) > K - 1:\n W2[A[l2]] -= 1\n if W2[A[l2]] == 0:\n del W2[A[l2]]\n l2 += 1\n res += l2 - l1\n return res", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n window1 = Counter()\n window2 = Counter()\n l1 = 0\n l2 = 0\n total = 0\n for (r, c) in enumerate(A):\n window1[c] += 1\n window2[c] += 1\n while len(window1) > K:\n window1[A[l1]] -= 1\n if window1[A[l1]] == 0:\n del window1[A[l1]]\n l1 += 1\n while len(window2) > K - 1:\n window2[A[l2]] -= 1\n if window2[A[l2]] == 0:\n del window2[A[l2]]\n l2 += 1\n total += l2 - l1\n return total", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.atMostK(A, K) - self.atMostK(A, K - 1)\n\ndef atMostK(A, k):\n start = 0\n end = 0\n res = 0\n chars = collections.Counter()\n distinct = 0\n while end < len(A):\n if chars[A[end]] == 0:\n distinct += 1\n chars[A[end]] += 1\n while distinct > k:\n chars[A[start]] -= 1\n if chars[A[start]] == 0:\n distinct -= 1\n start += 1\n res += end - start + 1\n end += 1\n return res", "def _identify_limit(A, current_limit, K, char_count_after_limit):\n char_count_after_limit = {k: v for (k, v) in char_count_after_limit.items()}\n unique_chars = {i for i in char_count_after_limit if char_count_after_limit[i] > 0}\n while len(unique_chars) == K:\n temp_char = A[current_limit]\n char_count_after_limit[temp_char] = char_count_after_limit[temp_char] - 1\n if char_count_after_limit[temp_char] == 0:\n unique_chars.remove(temp_char)\n current_limit += 1\n char_count_after_limit[A[current_limit - 1]] = char_count_after_limit[A[current_limit - 1]] + 1\n return (current_limit - 1, char_count_after_limit)\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n (counter1, counter2) = (collections.Counter(), collections.Counter())\n slow = fast = res = 0\n for (_, a) in enumerate(A):\n (counter1[a], counter2[a]) = (counter1[a] + 1, counter2[a] + 1)\n while len(counter2) == K:\n counter2[A[fast]] -= 1\n if not counter2[A[fast]]:\n del counter2[A[fast]]\n fast += 1\n while len(counter1) > K:\n counter1[A[slow]] -= 1\n if not counter1[A[slow]]:\n del counter1[A[slow]]\n slow += 1\n res += fast - slow\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n sum = 0\n begin = 0\n end = 0\n s = collections.defaultdict(int)\n lA = len(A)\n for i in range(lA):\n if len(s) >= K:\n s[A[i]] += 1\n if s[A[i]] > 1:\n newend = end\n while s[A[newend]] > 1:\n s[A[newend]] -= 1\n newend += 1\n end = newend\n else:\n begin = end\n while s[A[begin]] > 1:\n s[A[begin]] -= 1\n begin += 1\n s[A[begin]] -= 1\n begin += 1\n end = begin\n while s[A[end]] > 1:\n s[A[end]] -= 1\n end += 1\n sum += end - begin + 1\n else:\n s[A[i]] += 1\n if len(s) == K:\n while s[A[end]] > 1:\n s[A[end]] -= 1\n end += 1\n sum += end - begin + 1\n return sum", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMostK(k):\n count = Counter()\n ans = left = 0\n for (i, a) in enumerate(A):\n if count[a] == 0:\n k -= 1\n count[a] += 1\n while k < 0:\n count[A[left]] -= 1\n if count[A[left]] == 0:\n k += 1\n left += 1\n ans += i - left + 1\n return ans\n return atMostK(K) - atMostK(K - 1)", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.helper(A, K) - self.helper(A, K - 1)\n\ndef helper(A, K):\n currSum = 0\n d = Counter()\n i = 0\n for j in range(len(A)):\n d[A[j]] += 1\n while len(d) > K:\n d[A[i]] -= 1\n if not d[A[i]]:\n del d[A[i]]\n i += 1\n currSum += j - i + 1\n return currSum", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def at_most(x):\n left = 0\n counts = Counter()\n res = 0\n for (right, num) in enumerate(A):\n counts[num] += 1\n while len(counts) > x:\n counts[A[left]] -= 1\n if counts[A[left]] == 0:\n del counts[A[left]]\n left += 1\n res += right - left + 1\n return res\n return at_most(K) - at_most(K - 1)", "def subarrayswithkdistinct(A, K):\n return self.atMostK(A, K) - self.atMostK(A, K - 1)\n\ndef atMostK(s, k):\n if not s:\n return 0\n N = len(s)\n (left, right) = (0, 0)\n ret = 0\n counter = collections.Counter()\n counter[s[right]] += 1\n while right < N:\n if len(counter) > k:\n counter[s[left]] -= 1\n if counter[s[left]] == 0:\n del counter[s[left]]\n left += 1\n else:\n right += 1\n ret += right - left\n if right < N:\n counter[s[right]] += 1\n return ret", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def at_most(K):\n window = Counter()\n left = right = 0\n res = 0\n while right < len(A):\n window[A[right]] += 1\n while len(window) > K:\n window[A[left]] -= 1\n if not window[A[left]]:\n del window[A[left]]\n left += 1\n res += right - left + 1\n right += 1\n return res\n return at_most(K) - at_most(K - 1)", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n (equalCt, lessCt) = (Counter(), Counter())\n (equalPt, lessPt) = (0, 0)\n res = 0\n\n def add_to_counter(x, co):\n co[x] += 1\n\n def subtr_from_counter(x, co):\n co[x] -= 1\n if co[x] == 0:\n del co[x]\n for (right, num) in enumerate(A):\n add_to_counter(num, equalCt)\n add_to_counter(num, lessCt)\n while len(equalCt) > K:\n subtr_from_counter(A[equalPt], equalCt)\n equalPt += 1\n while len(lessCt) >= K:\n subtr_from_counter(A[lessPt], lessCt)\n lessPt += 1\n res += lessPt - equalPt\n return res", "from collections import Counter\n\ndef subarraysWithAtMostK(arr: list, k: int) -> int:\n start = 0\n counter = Counter()\n res = 0\n for end in range(len(arr)):\n num = arr[end]\n counter[num] += 1\n while len(counter) > k:\n to_remove = arr[start]\n counter[to_remove] -= 1\n if counter[to_remove] == 0:\n del counter[to_remove]\n start += 1\n res += end - start + 1\n return res\n\ndef subarrayswithkdistinct(arr: list, k: int) -> int:\n return subarraysWithAtMostK(arr, k) - subarraysWithAtMostK(arr, k - 1)\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return subarrayswithkdistinct(A, K)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMost(A: List[int], K: int):\n cache = collections.Counter()\n (res, i) = (0, 0)\n for j in range(len(A)):\n cache[A[j]] += 1\n while len(cache) > K:\n cache[A[i]] -= 1\n if cache[A[i]] == 0:\n del cache[A[i]]\n i += 1\n res += j - i + 1\n return res\n return atMost(A, K) - atMost(A, K - 1)", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n window = Counter()\n res = 0\n left = right = 0\n while True:\n while right < len(A) and len(window) < K:\n window[A[right]] += 1\n right += 1\n if len(window) < K:\n return res\n j = right\n while j < len(A) and A[j] in window:\n j += 1\n res += j - right + 1\n window[A[left]] -= 1\n if not window[A[left]]:\n del window[A[left]]\n left += 1\n return res", "def __init__():\n self.counter = Counter()\n self.unique = 0\n\ndef add(value: int):\n self.counter[value] += 1\n if self.counter[value] == 1:\n self.unique += 1\n\ndef remove(value: int):\n self.counter[value] -= 1\n if self.counter[value] == 0:\n self.unique -= 1\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n window1 = Window()\n window2 = Window()\n left1 = left2 = answer = 0\n for right in A:\n window1.add(right)\n window2.add(right)\n while window1.unique > K:\n window1.remove(A[left1])\n left1 += 1\n while window2.unique >= K:\n window2.remove(A[left2])\n left2 += 1\n answer += left2 - left1\n return answer", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.subarraysWithAtmostKDistinct(A, K) - self.subarraysWithAtmostKDistinct(A, K - 1)\n\ndef subarraysWithAtmostKDistinct(A, K):\n (l, r, count, res) = (0, 0, 0, 0)\n hashmap = [0] * 20001\n while r < len(A):\n hashmap[A[r]] += 1\n if hashmap[A[r]] == 1:\n count += 1\n while count > K:\n hashmap[A[l]] -= 1\n if hashmap[A[l]] == 0:\n count -= 1\n l += 1\n res += r - l + 1\n r += 1\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def remove(m, n):\n if m[n] == 1:\n del m[n]\n else:\n m[n] -= 1\n (m1, m2) = (collections.Counter(), collections.Counter())\n res = 0\n i1 = i2 = -1\n for (i0, n) in enumerate(A):\n while i1 + 1 < len(A) and len(m1) < K:\n i1 += 1\n m1[A[i1]] += 1\n if len(m1) < K:\n return res\n while i2 + 1 < len(A) and len(m2) < K + 1:\n i2 += 1\n m2[A[i2]] += 1\n res += i2 - i1 + int(len(m2) == K)\n remove(m1, n)\n remove(m2, n)\n return res", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.subarraysWithAtMostKDistinct(A, K) - self.subarraysWithAtMostKDistinct(A, K - 1)\n\ndef subarraysWithAtMostKDistinct(A, K):\n window = Counter()\n j = 0\n res = 0\n for i in range(len(A)):\n c = A[i]\n window[c] += 1\n while len(window) > K:\n last = A[j]\n window[last] -= 1\n if window[last] == 0:\n del window[last]\n j += 1\n res += i - j + 1\n return res", "from collections import Counter\n\ndef solve(A, K):\n count = Counter()\n front = iter(A)\n ans = 0\n size = 0\n for k in A:\n count[k] += 1\n size += 1\n while len(count) > K:\n key = next(front)\n count[key] -= 1\n size -= 1\n if count[key] == 0:\n del count[key]\n ans += size\n return ans\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n cx = Counter()\n cy = Counter()\n fx = iter(A)\n fy = iter(A)\n sx = 0\n sy = 0\n ans = 0\n for k in A:\n cx[k] += 1\n cy[k] += 1\n sx += 1\n sy += 1\n while len(cx) > K:\n key = next(fx)\n cx[key] -= 1\n sx -= 1\n if cx[key] == 0:\n del cx[key]\n while len(cy) > K - 1:\n key = next(fy)\n cy[key] -= 1\n sy -= 1\n if cy[key] == 0:\n del cy[key]\n ans += sx - sy\n return ans", "def subarrayswithkdistinct(A, K):\n return self.atMostK(A, K) - self.atMostK(A, K - 1)\n\ndef atMostK(A, K):\n count = collections.Counter()\n res = left = right = distinct = 0\n while right < len(A):\n count[A[right]] += 1\n if count[A[right]] == 1:\n distinct += 1\n while distinct > K:\n count[A[left]] -= 1\n if count[A[left]] == 0:\n distinct -= 1\n left += 1\n res += right - left + 1\n right += 1\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n (good_start, bad_start) = (-1, -1)\n (good_count, bad_count) = ({}, {})\n\n def add(count, element):\n if element not in count:\n count[element] = 0\n count[element] += 1\n\n def remove(count, element):\n count[element] -= 1\n if count[element] == 0:\n del count[element]\n\n def find_good_start(A, K, cur_pos, index, good_count):\n if len(good_count) == K:\n return index\n cur = index\n while cur < cur_pos and len(good_count) > K:\n cur += 1\n remove(good_count, A[cur])\n return cur\n total = 0\n for i in range(len(A)):\n cur = A[i]\n add(good_count, cur)\n add(bad_count, cur)\n if len(good_count) >= K:\n good_start = find_good_start(A, K, i, good_start, good_count)\n bad_start = find_good_start(A, K - 1, i, bad_start, bad_count)\n if len(good_count) == K and len(bad_count) == K - 1:\n total += bad_start - good_start\n return total", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n (m1, m2) = (collections.Counter(), collections.Counter())\n\n def remove(m, n):\n m[n] -= 1\n if not m[n]:\n del m[n]\n res = 0\n left = right = -1\n for (i, n) in enumerate(A):\n while left < len(A) - 1 and len(m1) < K:\n left += 1\n m1[A[left]] += 1\n if len(m1) < K:\n return res\n while right < len(A) - 1 and len(m2) <= K:\n right += 1\n m2[A[right]] += 1\n res += right - left + (len(m2) == K)\n remove(m1, n)\n remove(m2, n)\n return res", "from collections import defaultdict\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def subArray(k):\n right = 0\n left = 0\n freq = collections.defaultdict(int)\n count = 0\n while right < len(A):\n freq[A[right]] += 1\n right += 1\n while len(freq) > k:\n freq[A[left]] -= 1\n if freq[A[left]] == 0:\n del freq[A[left]]\n left += 1\n count += right - left\n return count\n output = 0\n output += subArray(K) - subArray(K - 1)\n return output"], "starter_code": "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n", "input_output": {"fn_name": "subarraysWithKDistinct", "inputs": [[[1, 2, 1, 2, 3], 2]], "outputs": [7]}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Counting", "Sliding Window", "Hash Table"], "name": null, "source": "leetcode", "tags": ["Data structures", "Amortized analysis", "Mathematics"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://leetcode.com/problems/subarrays-with-k-different-integers/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "subarrayswithkdistinct", "task_id": "TACO_lite/409", "example": [[[[1, 2, 1, 2, 3], 2], [[1, 2, 1, 3, 4], 3]], ["7", "3"]]} +{"requirement": "Santa puts all the presents into the huge sack. In order to let his reindeers rest a bit, he only takes as many reindeers with him as he is required to do. The others may take a nap.\n\nTwo reindeers are always required for the sleigh and Santa himself. Additionally he needs 1 reindeer per 30 presents. As you know, Santa has 8 reindeers in total, so he can deliver up to 180 presents at once (2 reindeers for Santa and the sleigh + 6 reindeers with 30 presents each).\n\nComplete the function `reindeers()`, which takes a number of presents and returns the minimum numbers of required reindeers. If the number of presents is too high, throw an error.\n\nExamles:\n\n```python\nreindeer(0) # must return 2\nreindeer(1) # must return 3\nreindeer(30) # must return 3\nreindeer(200) # must throw an error\n```", "solutions": ["from math import ceil\n\ndef reindeer(presents):\n if presents > 180:\n raise ValueError('Too many presents')\n return ceil(presents / 30.0) + 2", "def reindeer(presents):\n assert presents <= 180\n return 2 + presents // 30 + (1 if presents % 30 else 0)", "from math import ceil\n\ndef reindeer(presents):\n assert presents < 181\n return ceil(presents / 30.0) + 2", "def reindeer(presents):\n assert presents <= 180\n return 2 + (presents + 29) // 30", "from math import ceil\n\ndef reindeer(presents):\n if presents > 180:\n raise ValueError\n else:\n return 2 + ceil(presents / 30.0)", "from math import ceil\n\ndef reindeer(presents):\n if presents > 180:\n raise Exception('Too many presents')\n return 2 + ceil(presents / 30)", "from math import ceil\n\ndef reindeer(presents):\n assert 0 <= presents <= 180\n return int(2 + ceil(presents / 30.0))", "def reindeer(presents):\n if presents > 180:\n raise Exception('Error')\n return 2 + int((presents + 29) / 30)", "import math\n\ndef reindeer(presents):\n p = math.ceil(presents / 30)\n if p > 6:\n raise ValueError('Error')\n else:\n return p + 2"], "starter_code": "def reindeer(presents):\n", "input_output": {"fn_name": "reindeer", "inputs": [[0], [1], [5], [30], [31], [60], [61], [90], [91], [120], [121], [150], [151], [180]], "outputs": [[2], [3], [3], [3], [4], [4], [5], [5], [6], [6], [7], [7], [8], [8]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/52ad1db4b2651f744d000394", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "reindeer", "task_id": "TACO_lite/336", "example": [[[0], [1], [30]], ["2", "3", "3"]]} +{"requirement": "A generalization of Bézier surfaces, called the S-patch, uses an interesting scheme for indexing its control points.\n\nIn the case of an n-sided surface of degree d, each index has n non-negative integers that sum to d, and all possible configurations are used.\n\nFor example, for a 3-sided quadratic (degree 2) surface the control points are:\n\n> indices 3 2 => [[0,0,2],[0,1,1],[0,2,0],[1,0,1],[1,1,0],[2,0,0]]\n\nGiven the degree and the number of sides, generate all control point indices.\nThe order of the indices in the list can be arbitrary, so for the above example\n\n> [[1,1,0],[2,0,0],[0,0,2],[0,2,0],[0,1,1],[1,0,1]]\n\nis also a good solution.", "solutions": ["def gen(n, d):\n if d == 0 or n == 1:\n yield ([d] * n)\n else:\n for x in range(d + 1):\n for y in gen(n - 1, d - x):\n yield ([x] + y)\n\ndef indices(n, d):\n return list(gen(n, d))", "import itertools\n\ndef indices(n, d):\n return list(recurse(n, d, []))\n\ndef recurse(n, d, prefix):\n if n == 0:\n return prefix\n if n == 1:\n return [prefix + [d]]\n res = []\n for i in range(d + 1):\n res += recurse(n - 1, d - i, prefix + [i])\n return res", "def indices(n, d):\n return [[r] + point for r in range(d + 1) for point in indices(n - 1, d - r)] if n > 1 else [[d]]", "def indices(n, d):\n result = []\n temp = []\n\n def tt(n, d, temp):\n if d == 1:\n result.extend([temp + [n]])\n return 0\n for i in range(0, n + 1):\n aa = temp + [i]\n tt(n - i, d - 1, aa)\n tt(d, n, temp)\n return result", "def indices(n, d):\n if n == 1:\n return [[d]]\n if d == 0:\n return [[0 for i in range(n)]]\n sols = []\n for i in range(d + 1):\n sols += [subsol + [i] for subsol in indices(n - 1, d - i)]\n return sols\n raise NotImplementedError('todo')", "def indices(n, d):\n result = ([i] for i in range(d + 1))\n for iteration in range(n - 1):\n result = (i + [j] for i in result for j in range(d + 1) if sum(i) + j <= d)\n return list(filter(lambda r: sum(r) == d, result))", "def indices(n, d):\n if n == 1:\n return [[d]]\n result = []\n for i in range(d + 1):\n for x in indices(n - 1, d - i):\n result.append([i] + x)\n return result", "def indices(n, d):\n if d < 0:\n return []\n elif n == 1:\n return [[d]]\n elif n == 2:\n return [[i, d - i] for i in range(d + 1)]\n else:\n return [[i] + p for i in range(d + 1) for p in indices(n - 1, d - i)]", "def indices(n, d):\n from itertools import combinations_with_replacement\n lst = []\n for c in combinations_with_replacement(range(n), d):\n base = [0] * n\n for i in c:\n base[i] += 1\n lst.append(base)\n return lst"], "starter_code": "def indices(n, d):\n", "input_output": {"fn_name": "indices", "inputs": [[1, 0], [3, 0]], "outputs": [[[[0]]], [[[0, 0, 0]]]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/553291f451ab4fbcdc0001c6", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "indices", "task_id": "TACO_lite/295", "example": [[[3, 2]], ["[[0, 0, 2], [0, 1, 1], [0, 2, 0], [1, 0, 1], [1, 1, 0], [2, 0, 0]]"]]} +{"requirement": "The Ackermann function is a famous function that played a big role in computability theory as the first example of a total computable function that is not primitive recursive.\n\nSince then the function has been a bit simplified but is still of good use. Due to its definition in terms of extremely deep recursion it can be used as a benchmark of a compiler's ability to optimize recursion. \n\nThe goal of this kata is to code a function which will be given two inputs, m and n, and will return the Ackermann number A(m,n) defined by:\n\n```\nA(m,n) = n+1 if m=0 \nA(m,n) = A(m-1,1) if m>0 , n=0\nA(m,n) = A(m-1,A(m,n-1)) if m,n > 0\n```\n\nm,n should be non-negative integers, the function should return null (Javascript), None (Python), or nil (Ruby) for other type, non-integer and negative numbers. In C, input is restricted to integer type.", "solutions": ["from numbers import Number\n\ndef ackermann(m, n):\n if isinstance(n, Number) and isinstance(m, Number):\n if m >= 0 and n >= 0:\n return ackermann_Aux(m, n)\n return None\n\ndef ackermann_Aux(m, n):\n if m == 0:\n return n + 1\n if m > 0:\n if n == 0:\n return ackermann_Aux(m - 1, 1)\n if n > 0:\n return ackermann_Aux(m - 1, ackermann_Aux(m, n - 1))", "def ackermann(m, n):\n if type(m) is not int or type(n) is not int:\n return None\n if m < 0 or n < 0:\n return None\n if m == 0:\n return n + 1\n elif n == 0:\n return ackermann(m - 1, 1)\n else:\n return ackermann(m - 1, ackermann(m, n - 1))", "def ackermann(m, n):\n return n + 1 if m == 0 else ackermann(m - 1, 1) if n == 0 else ackermann(m - 1, ackermann(m, n - 1))", "def val(v):\n return isinstance(v, int) and v >= 0\n\ndef ackermann(m, n):\n if not val(m) or not val(n):\n return None\n if m == 0:\n return n + 1\n elif m > 0 and n == 0:\n return ackermann(m - 1, 1)\n return ackermann(m - 1, ackermann(m, n - 1))", "def ackermann(m, n):\n try:\n if m == 0 and n >= 0:\n return n + 1\n if m > 0 and n == 0:\n return ackermann(m - 1, 1)\n if m > 0 and n > 0:\n return ackermann(m - 1, ackermann(m, n - 1))\n except:\n return None", "def deepAck(m, n):\n return n + 1 if m == 0 else deepAck(m - 1, 1) if n == 0 else deepAck(m - 1, deepAck(m, n - 1))\n\ndef ackermann(m, n):\n return None if not isinstance(m, int) or not isinstance(n, int) or m < 0 or (n < 0) else deepAck(m, n)", "def ackermann(m, n):\n if m:\n if n:\n return ackermann(m - 1, ackermann(m, n - 1))\n return ackermann(m - 1, 1)\n return n + 1", "def ackermann(m, n):\n return (lambda m, n, s=lambda m, n, f: n + 1 if m == 0 and n >= 0 else f(m - 1, 1, f) if m > 0 and n == 0 else f(m - 1, f(m, n - 1, f), f) if m > 0 and n > 0 else None: s(m, n, s))(m, n)"], "starter_code": "def ackermann(m,n):\n", "input_output": {"fn_name": "Ackermann", "inputs": [[1, 1], [4, 0], [3, 3]], "outputs": [[3], [13], [61]]}, "difficulty": "EASY", "raw_tags": ["Recursion", "Algorithms", "Mathematics"], "name": null, "source": "codewars", "tags": ["Mathematics", "Complete search"], "skill_types": ["Complete search"], "url": "https://www.codewars.com/kata/53ad69892a27079b34000bd9", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "ackermann", "task_id": "TACO_lite/358", "example": [[[0, 0], [2, 3]], ["1", "9"]]} +{"requirement": "Given an array, Arr of N numbers, and another number target, find three integers in the array such that the sum is closest to the target. Return the sum of the three integers.\nNote: If there are multiple solutions, print the maximum one.\nExample 1:\nInput:\nN = 6, target = 2\nA[] = {-7,9,8,3,1,1}\nOutput: 2\nExplanation: There is one triplet with sum\n2 in the array. Triplet elements are -7,8,\n1 whose sum is 2.\nExample 2:\nInput:\nN = 4, target = 13\nA[] = {5,2,7,5}\nOutput: 14\nExplanation: There is one triplet with sum\n12 and other with sum 14 in the array.\nTriplet elements are 5, 2, 5 and 2, 7, 5\nrespectively. Since abs(13-12) ==\nabs(13-14) maximum triplet sum will be\npreferred i.e 14.\nYour Task:\nComplete threeSumClosest() function and return the expected answer.\nExpected Time Complexity: O(N*N).\nExpected Auxiliary Space: O(1).\nConstraints:\n3 ≤ N ≤ 10^{3}\n-10^{5} ≤ A[i] ≤ 10^{5}\n1 ≤ target ≤ 10^{5}", "solutions": ["def threesumclosest(arr, target):\n arr.sort()\n r = sum(arr[:3])\n for i in range(len(arr) - 2):\n s = i + 1\n l = len(arr) - 1\n while s < l:\n su = arr[i] + arr[s] + arr[l]\n if abs(target - su) < abs(target - r):\n r = su\n elif abs(target - su) == abs(target - r):\n r = max(r, su)\n if su < target:\n s += 1\n else:\n l -= 1\n return r", "def threesumclosest(arr, target):\n arr.sort()\n n = len(arr)\n ans = []\n temp = []\n for i in range(n - 2):\n a = i + 1\n b = n - 1\n while a < b:\n x = arr[i] + arr[a] + arr[b]\n if x == target:\n return target\n elif x > target:\n ans.append(x)\n temp.append(abs(x - target))\n b -= 1\n else:\n ans.append(x)\n temp.append(abs(x - target))\n a += 1\n t1 = min(temp) + target\n t2 = target - min(temp)\n if t1 in ans:\n return t1\n return t2", "def threesumclosest(arr, target):\n n = len(arr)\n arr = sorted(arr)\n minDiff = 1000000007\n res = -1000000007\n for i in range(n):\n sp = i + 1\n ep = n - 1\n while sp < ep:\n sum = arr[i] + arr[sp] + arr[ep]\n curDiff = abs(target - sum)\n if curDiff == minDiff:\n res = max(res, sum)\n elif curDiff < minDiff:\n minDiff = curDiff\n res = sum\n if sum == target:\n break\n elif sum > target:\n ep -= 1\n else:\n sp += 1\n return res", "def threesumclosest(arr, target):\n arr.sort()\n N = len(arr)\n Sum = 10000000000.0\n for i in range(N - 2):\n a = arr[i]\n L = i + 1\n R = N - 1\n while L < R:\n temp = a + arr[L] + arr[R]\n if temp == target:\n return target\n elif temp > target:\n R -= 1\n else:\n L += 1\n if abs(temp - target) < abs(Sum - target):\n Sum = temp\n elif abs(temp - target) == abs(Sum - target) and temp > Sum:\n Sum = temp\n return Sum", "def __init__():\n self.INT_MAX = 1000000\n\ndef threesumclosest(array, target):\n abs1 = ans2 = self.INT_MAX\n N = len(array)\n array.sort()\n result = dict()\n for i in range(N - 2):\n start = i + 1\n end = N - 1\n while start < end:\n temp = array[i] + array[start] + array[end]\n if temp == target:\n return temp\n elif temp > target:\n if abs(temp - target) < ans2:\n ans2 = abs(temp - target)\n ans1 = temp\n elif abs(temp - target) == ans2:\n ans1 = max(ans1, temp)\n end -= 1\n else:\n if abs(temp - target) < ans2:\n ans1 = temp\n ans2 = abs(temp - target)\n elif abs(temp - target) == ans2:\n ans1 = max(ans1, temp)\n start += 1\n return ans1", "def threesumclosest(arr, target):\n arr.sort()\n sum = 0\n result = target * 3\n for x in range(len(arr) - 2):\n start = x + 1\n end = len(arr) - 1\n while start < end:\n sum = arr[x] + arr[start] + arr[end]\n if abs(target - sum) == abs(target - result):\n result = max(sum, result)\n elif abs(target - sum) < abs(target - result):\n result = sum\n if sum < target:\n start += 1\n else:\n end -= 1\n return result", "def threesumclosest(arr, target):\n arr.sort()\n ans = 0\n diff = float('inf')\n for i in range(n - 2):\n j = i + 1\n k = len(arr) - 1\n while j < k:\n if arr[i] + arr[j] + arr[k] == target:\n return target\n if abs(arr[i] + arr[j] + arr[k] - target) < abs(target - diff):\n diff = arr[i] + arr[j] + arr[k]\n if abs(arr[i] + arr[j] + arr[k] - target) == abs(target - diff):\n diff = max(arr[i] + arr[j] + arr[k], diff)\n if arr[i] + arr[j] + arr[k] > target:\n k -= 1\n else:\n j += 1\n return diff", "def threesumclosest(arr, target):\n cd = float('inf')\n arr.sort()\n for i in range(n - 2):\n left = i + 1\n right = n - 1\n while left < right:\n summ = arr[i] + arr[left] + arr[right]\n if summ == target:\n return target\n elif summ > target:\n right -= 1\n else:\n left += 1\n d = abs(target - summ)\n if d < cd:\n cd = d\n ret = summ\n elif d == cd:\n ret = max(ret, summ)\n return ret", "def threesumclosest(arr, target):\n clss = float('inf')\n arr.sort()\n for i in range(n - 2):\n left = i + 1\n right = n - 1\n while left < right:\n curs = arr[i] + arr[left] + arr[right]\n if curs == target:\n return target\n elif curs > target:\n right -= 1\n else:\n left += 1\n if abs(curs - target) < abs(clss - target):\n clss = curs\n elif abs(curs - target) == abs(clss - target) and curs > clss:\n clss = curs\n return clss", "def threesumclosest(arr, target):\n n = len(arr)\n if n == 3:\n return sum(arr)\n ans = -float('inf')\n arr.sort()\n for i in range(n - 2):\n start = i + 1\n end = n - 1\n while start < end:\n summ = arr[i] + arr[start] + arr[end]\n if target == summ:\n return target\n if abs(target - summ) < abs(target - ans):\n ans = summ\n elif abs(target - summ) == abs(target - ans):\n ans = max(summ, ans)\n if summ > target:\n end -= 1\n else:\n start += 1\n return ans", "import sys\n\ndef threesumclosest(arr, target):\n maxi = sys.maxsize\n ans = 0\n arr.sort()\n for i in range(len(arr) - 2):\n l = i + 1\n r = len(arr) - 1\n while l < r:\n sumi = arr[i] + arr[l] + arr[r]\n if sumi == target:\n return target\n if abs(sumi - target) < abs(target - maxi):\n maxi = sumi\n if abs(sumi - target) == abs(target - maxi):\n maxi = max(sumi, maxi)\n if sumi > target:\n r -= 1\n else:\n l += 1\n return maxi", "def threesumclosest(arr, target):\n arr.sort()\n minsum = 10 ** 9\n ans = 0\n for i in range(len(arr)):\n first = arr[i]\n start = i + 1\n end = n - 1\n while start < end:\n summ = first + arr[start] + arr[end]\n if summ == target:\n return summ\n if abs(target - summ) < abs(target - minsum):\n minsum = summ\n if abs(target - summ) == abs(target - minsum):\n minsum = max(summ, minsum)\n if summ > target:\n end -= 1\n else:\n start += 1\n return minsum", "def threesumclosest(arr, target):\n arr.sort()\n closest_sum = sum(arr[:3])\n for i in range(len(arr) - 2):\n j = i + 1\n k = len(arr) - 1\n while j < k:\n current_sum = arr[i] + arr[j] + arr[k]\n if abs(target - current_sum) < abs(target - closest_sum):\n closest_sum = current_sum\n elif abs(target - current_sum) == abs(target - closest_sum):\n closest_sum = max(closest_sum, current_sum)\n if current_sum < target:\n j += 1\n else:\n k -= 1\n return closest_sum", "def threesumclosest(arr, target):\n arr.sort()\n ans = sum(arr[:3])\n for (i, j) in enumerate(arr[:-2]):\n a = i + 1\n b = len(arr) - 1\n while a < b:\n temp = j + arr[a] + arr[b]\n if temp == target:\n return temp\n X = abs(temp - target)\n Y = abs(ans - target)\n if X == Y:\n ans = max(ans, temp)\n elif X < Y:\n ans = temp\n if temp < target:\n a += 1\n elif temp > target:\n b -= 1\n return ans", "def threesumclosest(arr, target):\n arr.sort()\n n = len(arr)\n res = sum(arr[:3])\n for (i, v) in enumerate(arr[:-2]):\n l = i + 1\n r = len(arr) - 1\n len(arr) - 1\n while l < r:\n temp = v + arr[l] + arr[r]\n if temp == target:\n return temp\n A = abs(temp - target)\n B = abs(res - target)\n if A == B:\n res = max(res, temp)\n elif A < B:\n res = temp\n if temp < target:\n l += 1\n elif temp > target:\n r -= 1\n return res", "def threesumclosest(arr, target):\n arr.sort()\n x = sum(arr[:3])\n n = len(arr)\n for i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n ans = arr[i] + arr[j] + arr[k]\n y = target - ans\n z = target - x\n if abs(y) < abs(z):\n x = ans\n elif abs(y) == abs(z):\n x = max(x, ans)\n if ans < target:\n j += 1\n else:\n k -= 1\n return x", "def threesumclosest(arr, target):\n arr.sort()\n l = len(arr)\n w = abs(sum(arr[:3]) - target)\n mx = 0\n for i in range(l - 2):\n a = i + 1\n b = l - 1\n while a < b:\n p = [arr[i], arr[a], arr[b]]\n p1 = sum(p)\n p2 = abs(p1 - target)\n if p2 <= w:\n if p2 == w:\n if mx < p1:\n mx = p1\n else:\n w = p2\n mx = p1\n if target > p1:\n a += 1\n else:\n b -= 1\n return mx", "from typing import List\n\ndef threesumclosest(nums: List[int], target: int) -> int:\n nums.sort()\n n = len(nums)\n closest_sum = float('inf')\n min_diff = float('inf')\n for i in range(n):\n (l, r) = (i + 1, n - 1)\n while l < r:\n cur_sum = nums[i] + nums[l] + nums[r]\n cur_diff = abs(target - cur_sum)\n if cur_diff < min_diff:\n min_diff = cur_diff\n closest_sum = cur_sum\n elif cur_diff == min_diff:\n closest_sum = max(closest_sum, cur_sum)\n if cur_sum == target:\n return target\n elif cur_sum < target:\n l += 1\n else:\n r -= 1\n return closest_sum", "def threesumclosest(arr, target):\n l = len(arr)\n sum = 0\n min_sum = []\n max_sum = []\n arr.sort()\n for i in range(l - 2):\n left = i + 1\n right = l - 1\n while left < right:\n sum = arr[i] + arr[left] + arr[right]\n if sum == target:\n return target\n elif sum > target:\n max_sum.append(sum)\n right -= 1\n else:\n min_sum.append(sum)\n left += 1\n a = b = 0\n if max_sum:\n a = min(max_sum)\n res = a\n if min_sum:\n b = max(min_sum)\n res = b\n if max_sum and min_sum:\n if a - target > target - b:\n res = b\n else:\n res = a\n return res", "def threesumclosest(arr, target):\n arr.sort()\n n = len(arr)\n diff = float('inf')\n output = 0\n for i in range(n - 2):\n k = n - 1\n for j in range(i + 1, n - 1):\n while j < k and arr[i] + arr[j] + arr[k] > target:\n summa = arr[i] + arr[j] + arr[k]\n if summa - target < diff or (summa - target == diff and summa > output):\n diff = summa - target\n output = summa\n k -= 1\n if j == k:\n break\n summa = arr[i] + arr[j] + arr[k]\n if abs(summa - target) < diff or (summa - target == diff and summa > output):\n diff = abs(summa - target)\n output = summa\n return output", "import sys\n\ndef threesumclosest(arr, target):\n arr.sort()\n closestsum = sys.maxsize\n n = len(arr)\n for i in range(n - 2):\n ptr1 = i + 1\n ptr2 = n - 1\n while ptr1 < ptr2:\n sum = arr[i] + arr[ptr1] + arr[ptr2]\n if sum == target:\n return sum\n elif sum < target:\n if abs(target - sum) < abs(target - closestsum):\n closestsum = sum\n elif abs(target - sum) == abs(target - closestsum):\n closestsum = max(closestsum, sum)\n ptr1 += 1\n else:\n if abs(target - sum) < abs(target - closestsum):\n closestsum = sum\n elif abs(target - sum) == abs(target - closestsum):\n closestsum = max(closestsum, sum)\n ptr2 -= 1\n return closestsum", "def threesumclosest(arr, target):\n m = 100000000.0\n arr.sort()\n n = len(arr)\n for i in range(n):\n l = i + 1\n r = n - 1\n while l < r:\n temp = arr[i] + arr[l] + arr[r]\n if temp == target:\n return temp\n elif temp < target:\n if abs(temp - target) < abs(m - target):\n m = temp\n elif abs(temp - target) == abs(m - target):\n m = max(m, temp)\n l += 1\n else:\n if abs(temp - target) < abs(m - target):\n m = temp\n elif abs(temp - target) == abs(m - target):\n m = max(m, temp)\n r -= 1\n return m", "def threesumclosest(a, target):\n arr.sort()\n k1 = -1\n m = 10 ** 9\n for i in range(len(arr)):\n (j, k) = (i + 1, len(arr) - 1)\n while k > j:\n if arr[i] + arr[j] + arr[k] == target:\n return a[i] + a[j] + a[k]\n if arr[i] + arr[j] + arr[k] < target:\n if m == abs(target - (arr[i] + arr[j] + arr[k])):\n k1 = max(k1, arr[i] + arr[j] + arr[k])\n if m > abs(target - arr[i] - arr[j] - arr[k]):\n k1 = arr[i] + arr[j] + arr[k]\n m = abs(target - (arr[i] + arr[j] + arr[k]))\n j = j + 1\n continue\n if arr[i] + arr[j] + arr[k] > target:\n if m == abs(target - (arr[i] + arr[j] + arr[k])):\n k1 = max(k1, arr[i] + arr[j] + arr[k])\n if m > abs(target - (arr[i] + arr[j] + arr[k])):\n k1 = arr[i] + arr[j] + arr[k]\n m = abs(target - (arr[i] + arr[j] + arr[k]))\n k = k - 1\n return k1", "def threesumclosest(arr, target):\n ans = []\n temp = []\n for i in range(0, len(arr)):\n for j in range(i + 1, len(arr)):\n for k in range(j + 1, len(arr)):\n x = arr[i] + arr[j] + arr[k]\n if x == target:\n return target\n elif x > target:\n ans.append(x)\n temp.append(abs(x - target))\n else:\n ans.append(x)\n temp.append(abs(x - target))\n t1 = min(temp) + target\n t2 = target - min(temp)\n if t1 in ans:\n return t1\n return t2", "def threesumclosest(arr, target):\n arr.sort()\n res = -1000000000.0\n for i in range(len(arr)):\n (j, k) = (0, len(arr) - 1)\n cs = 0\n while j < k:\n if j == i:\n j += 1\n continue\n elif k == i:\n k -= 1\n continue\n cs = arr[i] + arr[j] + arr[k]\n if abs(res - target) > abs(cs - target):\n res = cs\n elif abs(target - cs) == abs(target - res):\n res = max(cs, res)\n if cs < target:\n j += 1\n elif cs > target:\n k -= 1\n else:\n return cs\n return res", "def threesumclosest(arr, target):\n n = len(arr)\n diff = 9999999999\n arr.sort()\n sum_three = 0\n for i in range(n):\n j = i + 1\n k = n - 1\n while j < k:\n three_sum = arr[i] + arr[j] + arr[k]\n if abs(three_sum - target) == diff:\n if three_sum > target:\n sum_three = three_sum\n elif abs(three_sum - target) < diff:\n diff = abs(three_sum - target)\n sum_three = three_sum\n if three_sum >= target:\n k -= 1\n else:\n j += 1\n return sum_three", "def threesumclosest(A, X):\n n = len(A)\n A.sort()\n ans = 0\n diff = 10 ** 9\n for i in range(n):\n s = i + 1\n e = n - 1\n while s < e:\n sum = A[i] + A[s] + A[e]\n if sum == X:\n return X\n if abs(X - sum) < diff:\n diff = min(diff, abs(X - sum))\n ans = sum\n if abs(X - sum) == diff:\n ans = max(ans, sum)\n if sum > X:\n e -= 1\n elif sum < X:\n s += 1\n return ans", "def threesumclosest(arr, target):\n arr.sort()\n close_sum = 10 ** 5\n for i in range(len(arr)):\n l = i + 1\n r = len(arr) - 1\n while l < r:\n current_sum = arr[i] + arr[l] + arr[r]\n if abs(current_sum - target) == abs(close_sum - target) and current_sum > close_sum:\n close_sum = current_sum\n if current_sum < target:\n l += 1\n else:\n r -= 1\n if abs(current_sum - target) < abs(close_sum - target):\n close_sum = current_sum\n return close_sum", "def threesumclosest(arr, target):\n n = len(arr)\n arr.sort()\n res = float('-inf')\n for (i, v) in enumerate(arr[:-2]):\n if i and arr[i] == arr[i - 1]:\n continue\n (l, r) = (i + 1, len(arr) - 1)\n while l < r:\n temp = v + arr[l] + arr[r]\n if temp == target:\n return temp\n (A, B) = (abs(temp - target), abs(res - target))\n if A == B:\n res = max(res, temp)\n if A < B:\n res = temp\n if temp < target:\n l += 1\n elif temp > target:\n r -= 1\n return res", "def threesumclosest(a, target):\n a = sorted(a)\n n = len(a)\n cs = a[0] + a[1] + a[2]\n for i in range(n - 2):\n l = i + 1\n r = n - 1\n while l < r:\n s = a[i] + a[l] + a[r]\n if abs(target - s) < abs(target - cs):\n cs = s\n if abs(target - s) == abs(target - cs):\n cs = cs if cs > s else s\n if s > target:\n r -= 1\n else:\n l += 1\n return cs", "def threesumclosest(arr, target):\n arr.sort()\n c = -9999999\n n = len(arr)\n for i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n s = arr[i] + arr[j] + arr[k]\n if abs(target - s) < abs(target - c):\n c = s\n elif abs(target - s) == abs(target - c):\n c = max(c, s)\n if s > target:\n k -= 1\n else:\n j += 1\n return c", "import sys\n\ndef threesumclosest(arr, target):\n arr.sort()\n closestSum = sys.maxsize\n for i in range(len(arr) - 2):\n left = i + 1\n right = len(arr) - 1\n while left < right:\n currentSum = arr[i] + arr[left] + arr[right]\n if abs(target - currentSum) < abs(target - closestSum):\n closestSum = currentSum\n elif abs(target - currentSum) == abs(target - closestSum):\n closestSum = max(closestSum, currentSum)\n if currentSum > target:\n right -= 1\n elif currentSum < target:\n left += 1\n else:\n return currentSum\n return closestSum", "import sys\n\ndef threesumclosest(arr, x):\n arr.sort()\n closestSum = sys.maxsize\n for i in range(len(arr) - 2):\n ptr1 = i + 1\n ptr2 = len(arr) - 1\n while ptr1 < ptr2:\n sum = arr[i] + arr[ptr1] + arr[ptr2]\n if abs(x - sum) < abs(x - closestSum):\n closestSum = sum\n elif abs(x - sum) == abs(x - closestSum):\n closestSum = max(closestSum, sum)\n if sum > x:\n ptr2 -= 1\n else:\n ptr1 += 1\n return closestSum", "def threesumclosest(arr, target):\n arr.sort()\n result = []\n minn = 99999999999\n n = len(arr)\n for i in range(n - 2):\n low = i + 1\n high = n - 1\n while low < high:\n sm = arr[i] + arr[low] + arr[high]\n if sm == target:\n return target\n elif sm < target:\n low += 1\n else:\n high -= 1\n if abs(sm - target) < minn:\n minn = abs(sm - target)\n result = [sm]\n elif abs(sm - target) == minn:\n result.append(sm)\n return max(result)", "def threesumclosest(arr, target):\n arr.sort()\n n = len(arr)\n minn = 9999999999\n result = []\n for i in range(n - 2):\n (j, k) = (i + 1, n - 1)\n while j < k:\n sm = arr[i] + arr[j] + arr[k]\n if sm == target:\n return target\n elif sm < target:\n j += 1\n elif sm > target:\n k -= 1\n if abs(sm - target) < minn:\n minn = abs(sm - target)\n result = [sm]\n elif abs(sm - target) == minn:\n result.append(sm)\n return max(result)", "def threesumclosest(arr, target):\n arr.sort()\n n = len(arr)\n a = []\n temp = []\n for i in range(n - 2):\n lr = i + 1\n rl = n - 1\n while lr < rl:\n x = arr[i] + arr[lr] + arr[rl]\n if x == target:\n return target\n elif x < target:\n a.append(x)\n temp.append(abs(x - target))\n lr += 1\n else:\n a.append(x)\n temp.append(abs(x - target))\n rl -= 1\n res1 = min(temp) + target\n res2 = target - min(temp)\n if res1 in a:\n return res1\n else:\n return res2", "def closest(arr, n, target, idx):\n mx = 10 ** 10\n (start, end) = (idx + 1, n - 1)\n while start < end and start < n and (end > idx):\n s = arr[start] + arr[end]\n if abs(s - target) < abs(mx - target):\n mx = s\n elif abs(s - target) == abs(mx - target):\n mx = max(mx, s)\n if s > target:\n end -= 1\n elif s < target:\n start += 1\n elif s == target:\n return s\n return mx\n\ndef threesumclosest(arr, target):\n mx = 10 ** 10\n arr.sort()\n for i in range(len(arr) - 2):\n res = arr[i] + closest(arr, len(arr), target - arr[i], i)\n if abs(res - target) < abs(mx - target):\n mx = res\n elif abs(res - target) == abs(mx - target):\n mx = max(mx, res)\n return mx", "def threesumclosest(arr, target):\n import sys\n diff = sys.maxsize\n res = 0\n arr = sorted(arr)\n for i in range(len(arr) - 2):\n l = i + 1\n r = len(arr) - 1\n while l < r:\n temp_sum = arr[i] + arr[l] + arr[r]\n if temp_sum == target:\n return target\n elif temp_sum > target:\n if temp_sum - target < diff:\n res = temp_sum\n diff = temp_sum - target\n elif temp_sum - target == diff:\n res = temp_sum\n r -= 1\n else:\n if target - temp_sum < diff:\n res = temp_sum\n diff = target - temp_sum\n l += 1\n return res", "def threesumclosest(arr, target):\n arr = sorted(arr)\n closestSum = 100001\n for i in range(len(arr) - 2):\n ptr1 = i + 1\n ptr2 = len(arr) - 1\n while ptr1 < ptr2:\n sum = arr[i] + arr[ptr1] + arr[ptr2]\n if abs(target - sum) < abs(target - closestSum):\n closestSum = sum\n if abs(target - sum) == abs(target - closestSum):\n if sum > closestSum:\n closestSum = sum\n if sum > target:\n ptr2 -= 1\n else:\n ptr1 += 1\n return closestSum", "def threesumclosest(arr, target):\n arr.sort()\n distance = float('inf')\n for x in range(len(arr) - 2):\n (l, r) = (x + 1, len(arr) - 1)\n while l < r:\n sum_val = arr[x] + arr[l] + arr[r]\n if abs(sum_val - target) < abs(distance - target):\n distance = sum_val\n elif abs(sum_val - target) == abs(distance - target):\n distance = max(distance, sum_val)\n if sum_val < target:\n l += 1\n else:\n r -= 1\n return distance", "def threesumclosest(arr, target):\n arr.sort()\n c = 2147483647\n result = 0\n for i in range(len(arr)):\n ptr1 = i + 1\n ptr2 = len(arr) - 1\n while ptr1 < ptr2:\n summ = arr[i] + arr[ptr1] + arr[ptr2]\n if summ == target:\n return target\n if summ < target:\n if abs(target - summ) < c:\n result = summ\n c = abs(target - summ)\n ptr1 += 1\n else:\n if abs(target - summ) <= c:\n result = summ\n c = abs(target - summ)\n ptr2 -= 1\n return result"], "starter_code": "def threesumclosest (arr, target):\n", "input_output": {"inputs": ["N = 6, target = 2\r\nA[] = {-7,9,8,3,1,1}", "N = 4, target = 13\r\nA[] = {5,2,7,5}"], "outputs": ["2", "14"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays", "Hash"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/three-sum-closest/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*N).", "entry_point": "threesumclosest", "task_id": "TACO_lite/407", "example": [[[6, 2, [-7, 9, 8, 3, 1, 1]], [4, 13, [5, 2, 7, 5]]], ["2", "14"]]} +{"requirement": "Given the root of a n-ary tree find the number of duplicate subtrees in the n-ary tree. Two trees are duplicates if they have the same structure with the same node values.\nExample 1:\nInput:\n1 N 2 2 3 N 4 N 4 4 3 N N N N N\nOutput: \n2\nExplanation: \n[4], [3] are duplicate subtree.\nExample 2:\nInput:\n1 N 2 3 N 4 5 6 N N N N\nOutput: \n0\nExplanation: \nNo duplicate subtree found.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function duplicateSubtreeNaryTree() which takes the root of the n-ary tree as input and returns an integer value as a number of duplicate subtrees.\nExpected Time Complexity: O(n), n is the total no of nodes\nExpected Space Complexity: O(n^{2})\nConstraints:\n 1 <= n < 10^{3}\n 1 <= node.key< 10^{3}", "solutions": ["def solve(root, d):\n s = str(root.key)\n for i in root.children:\n s += self.solve(i, d)\n d[s] = d.get(s, 0) + 1\n return s\n\ndef duplicateSubtreeNaryTree(root):\n d = {}\n self.solve(root, d)\n c = 0\n for x in d:\n if d[x] > 1:\n c += 1\n return c", "def duplicateSubtreeNaryTree(root):\n\n def getSubtreeIdentifier(node):\n if not node:\n return ''\n subtree_identifiers = []\n for child in node.children:\n subtree_identifier = getSubtreeIdentifier(child)\n subtree_identifiers.append(subtree_identifier)\n subtree_identifiers.sort()\n subtree_identifier = str(node.key) + ',' + ','.join(subtree_identifiers)\n subtree_counts[subtree_identifier] = subtree_counts.get(subtree_identifier, 0) + 1\n return subtree_identifier\n subtree_counts = {}\n getSubtreeIdentifier(root)\n duplicate_count = 0\n for count in subtree_counts.values():\n if count > 1:\n duplicate_count += 1\n return duplicate_count", "def duplicateSubtreeNaryTree(root):\n\n def traverse(node):\n if not node:\n return '#'\n subtree = str(node.key)\n for child in node.children:\n subtree += traverse(child)\n if subtree in subtrees:\n subtrees[subtree] += 1\n else:\n subtrees[subtree] = 1\n return subtree\n subtrees = {}\n traverse(root)\n return sum((freq > 1 for freq in subtrees.values()))", "def duplicateSubtreeNaryTree(root):\n\n def solve(root):\n if root == None:\n return ''\n res = str(root.key)\n for i in root.children:\n res += '*' + solve(i)\n if res not in d1:\n d1[res] = 1\n else:\n d1[res] += 1\n return res\n d1 = {}\n solve(root)\n ans = 0\n for (i, v) in d1.items():\n if v > 1:\n ans += 1\n return ans", "def recSol(node):\n repre = (node.key, tuple(sorted([self.recSol(child) for child in node.children])))\n if repre in self.HashTab:\n if self.HashTab[repre] not in self.duplicated:\n self.duplicated.update([self.HashTab[repre]])\n else:\n self.HashTab[repre] = len(self.HashTab)\n return self.HashTab[repre]\n\ndef duplicateSubtreeNaryTree(root):\n self.duplicated = set()\n self.sameVal = 0\n self.HashTab = {}\n self.recSol(root)\n return len(self.duplicated)", "def recSol(node):\n if node is None:\n return -1\n repre = (node.key, tuple(sorted([self.recSol(child) for child in node.children])))\n if repre in self.HashTab:\n if self.HashTab[repre] not in self.duplicated:\n self.sameVal += 1\n self.duplicated.update([self.HashTab[repre]])\n else:\n self.HashTab[repre] = self.count\n self.count += 1\n return self.HashTab[repre]\n\ndef duplicateSubtreeNaryTree(root):\n self.duplicated = set()\n self.sameVal = 0\n self.HashTab = {}\n self.count = 0\n self.recSol(root)\n return self.sameVal", "def cst(root, sp):\n s = str(root.key)\n for y in root.children:\n s += self.cst(y, sp)\n sp[s] = sp.get(s, 0) + 1\n return s\n\ndef duplicateSubtreeNaryTree(root):\n sp = {}\n self.cst(root, sp)\n c = 0\n for x in sp:\n if sp[x] > 1:\n c += 1\n return c", "def duplicateSubtreeNaryTree(root):\n d = dict()\n\n def dfs(root):\n count = 1\n for i in root.children:\n x = dfs(i)\n count = count + x\n if d.get(count) != None:\n d[count].append(root)\n if d.get(count) == None:\n d[count] = [root]\n return count\n dfs(root)\n\n def check(root1, root2):\n if root1.key != root2.key:\n return False\n if len(root1.children) != len(root2.children):\n return False\n y = True\n for i in range(len(root1.children)):\n y = y and check(root1.chilren[i], root2.children[i])\n return y\n d1 = dict()\n for i in d.keys():\n for j in range(len(d[i])):\n for k in range(j + 1, len(d[i])):\n if check(d[i][j], d[i][k]):\n d1[d[i][j].key] = True\n return len(d1.keys())", "def cst(root, sp):\n s = str(root.key)\n for y in root.children:\n s += self.cst(y, sp)\n sp[s] = sp.get(s, 0) + 1\n return s\n\ndef duplicateSubtreeNaryTree(root):\n sp = {}\n self.cst(root, sp)\n cnt = 0\n for i in sp:\n if sp[i] > 1:\n cnt += 1\n return cnt", "def duplicateSubtreeNaryTree(root):\n m = {}\n\n def solve(root):\n value = str(root.key)\n for c in root.children:\n value += solve(c)\n m[value] = m.get(value, 0) + 1\n return value\n solve(root)\n res = 0\n for i in m:\n if m[i] > 1:\n res += 1\n return res", "def duplicateSubtreeNaryTree(root):\n paths = {}\n\n def dfs(ptr):\n suffix = '' if ptr.children is None or len(ptr.children) == 0 else ''.join(list(map(lambda n: dfs(n), ptr.children)))\n nid = ':' + str(ptr.key) + suffix\n paths[nid] = paths.get(nid, 0) + 1\n return nid\n dfs(root)\n count = 0\n for (k, v) in paths.items():\n count += 1 if v > 1 else 0\n return count", "def func(root, d):\n if root == None:\n return ''\n s = str(root.key)\n for i in root.children:\n s += '$' + func(i, d)\n if s in d:\n d[s] += 1\n else:\n d[s] = 1\n return s\n\ndef duplicateSubtreeNaryTree(root):\n d = {}\n func(root, d)\n c = 0\n for i in d:\n if d[i] > 1:\n c += 1\n return c", "def duplicateSubtreeNaryTree(root):\n from collections import Counter\n c = Counter()\n\n def dfs(n):\n nonlocal c\n if not n:\n return '#'\n key = '{0} {1}'.format(n.key, ' '.join((dfs(nxt) for nxt in n.children)))\n c[key] += 1\n return key\n dfs(root)\n return sum((v > 1 for v in c.values()))", "def duplicateSubtreeNaryTree(root):\n res = []\n hmap = {}\n\n def recurse(node):\n p = str(node.key) + '#'\n for child in node.children:\n p += recurse(child)\n if p not in hmap:\n hmap[p] = 0\n hmap[p] += 1\n return p\n recurse(root)\n ans = 0\n for val in hmap.values():\n if val > 1:\n ans += 1\n return ans", "def duplicateSubtreeNaryTree(root):\n mp = {}\n\n def postorder(root):\n if root == None:\n return ''\n ans = ''\n for child in root.children:\n ans += postorder(child) + '*'\n ans += str(root.key) + '*'\n mp[ans] = 1 + mp.get(ans, 0)\n return ans\n count = 0\n postorder(root)\n for i in mp:\n if mp[i] > 1:\n count += 1\n return count", "def duplicateSubtreeNaryTree(root):\n freq = defaultdict(int)\n\n def traverse(node):\n if not node:\n return '#'\n subtree = str(node.key)\n for child in node.children:\n subtree += traverse(child)\n freq[subtree] += 1\n return subtree\n traverse(root)\n count = 0\n for key in freq:\n if freq[key] > 1:\n count += 1\n return count", "def duplicateSubtreeNaryTree(root):\n d = {}\n self.compute(root, d)\n res = 0\n for (_, count) in d.items():\n if count > 1:\n res += 1\n return res\n\ndef compute(root, d):\n cur_value = root.key\n for ch in root.children:\n self.compute(ch, d)\n cur_value += ch.value * 10\n if cur_value not in d:\n d[cur_value] = 0\n d[cur_value] += 1\n root.value = cur_value", "def __init__():\n self.dic = dict()\n\ndef helper(node):\n temp = str(node.key)\n for child in node.children:\n t = self.helper(child)\n temp = str(temp) + str(t) + 'x'\n if temp not in self.dic:\n self.dic[temp] = 0\n self.dic[temp] += 1\n return temp\n\ndef duplicateSubtreeNaryTree(root):\n self.helper(root)\n ans = 0\n for key in self.dic.keys():\n if self.dic[key] > 1:\n ans += 1\n return ans", "from collections import defaultdict\n\ndef duplicateSubtreeNaryTree(root):\n m = {}\n\n def dfs(node):\n if not node:\n return ''\n s = str(node.key)\n for i in node.children:\n s += dfs(i)\n if s in m:\n m[s] += 1\n else:\n m[s] = 1\n return s + '*'\n dfs(root)\n ans = 0\n for i in m:\n if m[i] > 1:\n ans += 1\n return ans", "def __init__():\n self.ans = 0\n self.m = {}\n\ndef solve(root):\n if not root:\n return ''\n s = str(root.key) + ' '\n for c in root.children:\n s += self.solve(c) + ' '\n if s in self.m and self.m[s] == 1:\n self.ans += 1\n self.m[s] = self.m.get(s, 0) + 1\n return s\n\ndef duplicateSubtreeNaryTree(root):\n self.solve(root)\n return self.ans", "def duplicateSubtreeNaryTree(root):\n (self.ids, self.cur_id, self.unique_trees) = ({}, 0, set())\n self.dfs(root)\n return len(self.unique_trees)\n\ndef dfs(node):\n cur = [str(node.key)]\n for child in node.children:\n cur.append(self.dfs(child))\n cur = '#'.join(cur)\n if self.ids.get(cur, -1) == -1:\n self.cur_id += 1\n self.ids[cur] = self.cur_id\n else:\n self.unique_trees.add(self.ids[cur])\n return str(self.ids[cur])", "def __init__():\n self.map = {}\n\ndef duplicateSubtreeNaryTree(root):\n answer = 0\n self.solve(root)\n for x in self.map:\n if self.map[x] > 1:\n answer += 1\n return answer\n\ndef solve(root: 'Node') -> str:\n s = str(root.key)\n for y in root.children:\n s += self.solve(y)\n self.map[s] = self.map.get(s, 0) + 1\n return s", "def __init__():\n self.map = {}\n\ndef duplicateSubtreeNaryTree(root: 'Node') -> int:\n ans = 0\n self.solve(root)\n for e in self.map:\n if self.map[e] > 1:\n ans += 1\n return ans\n\ndef solve(root: 'Node') -> str:\n s = str(root.key)\n for nei in root.children:\n s += self.solve(nei)\n self.map[s] = self.map.get(s, 0) + 1\n return s", "def cst(root, s):\n a = str(root.key)\n for i in root.children:\n a += self.cst(i, s)\n s[a] = s.get(a, 0) + 1\n return a\n\ndef duplicateSubtreeNaryTree(root):\n t = {}\n self.cst(root, t)\n ans = 0\n for i in t:\n if t[i] > 1:\n ans += 1\n return ans", "def duplicateSubtreeNaryTree(root):\n self.map = {}\n\n def solve(root):\n if root is None:\n return ''\n returnValue = root.__str__()\n for ch in root.children:\n returnValue = returnValue + '#' + solve(ch)\n self.map[returnValue] = self.map.get(returnValue, 0) + 1\n return returnValue\n solve(root)\n ans = 0\n for val in self.map.values():\n if val > 1:\n ans += 1\n return ans", "def duplicateSubtreeNaryTree(root):\n hash = {}\n\n def count_sub_tree(node):\n if not node:\n return ''\n s = str(node.key)\n for child in node.children:\n s += count_sub_tree(child)\n hash[s] = hash.get(s, 0) + 1\n return s\n count_sub_tree(root)\n res = 0\n for sub_tree in hash:\n if hash[sub_tree] > 1:\n res += 1\n return res", "def duplicateSubtreeNaryTree(root):\n\n def traverse(node):\n nonlocal count, subtrees\n if not node:\n return ''\n subtree = str(node.key)\n for child in node.children:\n subtree += traverse(child)\n if subtree in subtrees and subtrees[subtree] == 1:\n count += 1\n subtrees[subtree] = 2\n elif subtree not in subtrees:\n subtrees[subtree] = 1\n return subtree\n count = 0\n subtrees = {}\n traverse(root)\n return count", "import collections\n\ndef duplicateSubtreeNaryTree(root):\n PRIME = 1337\n hashes = collections.defaultdict(int)\n\n def dfs(r):\n nonlocal hashes\n if not r:\n return 1\n ret = r.key\n for i in range(len(r.children)):\n ret += (i + 1) * dfs(r.children[i])\n ret = ret * PRIME\n hashes[ret] += 1\n return ret\n dfs(root)\n ans = 0\n for (k, v) in hashes.items():\n ans += v > 1\n return ans", "def solve(root, mp):\n st = str(root.key) + ':'\n arr = []\n for i in root.children:\n arr.append(self.solve(i, mp))\n arr.sort()\n for i in arr:\n st += i + ','\n if st in mp:\n mp[st] += 1\n else:\n mp[st] = 1\n return st\n\ndef duplicateSubtreeNaryTree(root):\n (count, mp) = (0, {})\n self.solve(root, mp)\n for i in mp:\n if mp[i] > 1:\n count += 1\n return count", "def duplicateSubtreeNaryTree(root):\n d = {}\n\n def trav(node):\n if not node:\n return '#'\n s = str(node.key) + ''.join((trav(n) for n in node.children))\n d[s] = d.get(s, 0) + 1\n return s\n trav(root)\n op = 0\n for i in d:\n if d[i] >= 2:\n op += 1\n return op", "def duplicateSubtreeNaryTree(root):\n d = {}\n\n def duplicateSubTree(root):\n if root == None:\n return '()'\n subtree = ''\n for child in root.children:\n subtree += duplicateSubTree(child)\n d['(' + str(root.key) + subtree + ')'] = d.get('(' + str(root.key) + subtree + ')', 0) + 1\n return '(' + str(root.key) + subtree + ')'\n duplicateSubTree(root)\n ans = 0\n for key in d.keys():\n if d[key] >= 2:\n ans += 1\n return ans"], "starter_code": "def __init__(key, children=None):\n", "input_output": {"inputs": ["1 N 2 2 3 N 4 N 4 4 3 N N N N N", "1 N 2 3 N 4 5 6 N N N N"], "outputs": ["2", "0"]}, "difficulty": "MEDIUM", "raw_tags": ["Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/079dee7e7db7a784ed73f604e3cf1712432edf79/1", "Expected Auxiliary Space": "O(n^{2})", "time_limit": null, "date": null, "picture_num": "2", "memory_limit": null, "Expected Time Complexity": "O(n), n is the total no of nodes", "entry_point": "__init__", "task_id": "TACO_lite/412", "example": [[], []]} +{"requirement": "You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.\nYou may assume that you have an infinite number of each kind of coin.\n \nExample 1:\nInput: coins = [1,2,5], amount = 11\nOutput: 3\nExplanation: 11 = 5 + 5 + 1\n\nExample 2:\nInput: coins = [2], amount = 3\nOutput: -1\n\nExample 3:\nInput: coins = [1], amount = 0\nOutput: 0\n\nExample 4:\nInput: coins = [1], amount = 1\nOutput: 1\n\nExample 5:\nInput: coins = [1], amount = 2\nOutput: 2\n\n \nConstraints:\n\n1 <= coins.length <= 12\n1 <= coins[i] <= 231 - 1\n0 <= amount <= 104", "solutions": ["def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n (n, res) = (len(coins), amount + 1)\n\n def dfs(index, target, cnt):\n nonlocal res\n if cnt + (target + coins[index] - 1) // coins[index] >= res:\n return\n if target % coins[index] == 0:\n res = cnt + target // coins[index]\n return\n if index == n - 1:\n return\n for i in range(target // coins[index], -1, -1):\n dfs(index + 1, target - coins[index] * i, cnt + i)\n dfs(0, amount, 0)\n return -1 if res > amount else res", "def coinchange(coins: List[int], amount: int) -> int:\n if not coins or amount < 0:\n return -1\n elif amount == 0:\n return 0\n coins.sort(reverse=True)\n visited = set()\n q = collections.deque([])\n for c in coins:\n if c == amount:\n return 1\n elif c < amount:\n q.append(c)\n visited.add(c)\n count = 1\n while q:\n size = len(q)\n count += 1\n for _ in range(size):\n prev = q.popleft()\n for c in coins:\n cur = prev + c\n if cur == amount:\n return count\n elif cur < amount and cur not in visited:\n visited.add(cur)\n q.append(cur)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n INVALID = 2 ** 32\n dp = [INVALID] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for i in range(coin, amount + 1):\n if dp[i - coin] >= dp[i]:\n continue\n dp[i] = dp[i - coin] + 1\n return -1 if dp[amount] == INVALID else dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n queue = [[amount, 0]]\n visited = {amount}\n for q in queue:\n for c in coins:\n if q[0] - c in visited:\n continue\n if q[0] == c:\n return q[1] + 1\n if q[0] > c:\n visited.add(q[0] - c)\n queue.append([q[0] - c, q[1] + 1])\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n queue = deque([(0, 0)])\n visited = [True] + [False] * amount\n while queue:\n (totalCoins, currVal) = queue.popleft()\n totalCoins += 1\n for coin in coins:\n nextVal = currVal + coin\n if nextVal == amount:\n return totalCoins\n if nextVal < amount:\n if not visited[nextVal]:\n visited[nextVal] = True\n queue.append((totalCoins, nextVal))\n return -1", "from collections import deque\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n if not coins:\n return -1\n queue = deque([])\n for coin in coins:\n if amount - coin >= 0:\n queue.append((1, amount - coin))\n seen = set()\n while queue:\n nex = queue.popleft()\n if nex[1] == 0:\n return nex[0]\n for coin in coins:\n if nex[1] - coin not in seen and nex[1] - coin >= 0:\n queue.append((nex[0] + 1, nex[1] - coin))\n seen.add(nex[1] - coin)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for a in range(coin, amount + 1):\n if dp[a - coin] >= dp[a]:\n continue\n dp[a] = dp[a - coin] + 1\n return dp[amount] if dp[amount] < float('inf') else -1", "from collections import deque\n\ndef coinchange(coins: List[int], amount: int) -> int:\n queue = deque()\n visited = set()\n queue.append((amount, 0))\n answer = -1\n while queue:\n (target, numCoins) = queue.popleft()\n if target == 0:\n answer = numCoins\n break\n elif target > 0:\n for coin in coins:\n if target - coin not in visited:\n visited.add(target - coin)\n queue.append((target - coin, numCoins + 1))\n return answer", "def coinchange(coins: List[int], amount: int) -> int:\n res = 0\n queue = collections.deque([(amount, 0)])\n seen = {amount}\n while queue:\n (head, res) = queue.popleft()\n if head == 0:\n return res\n for c in coins:\n new_amount = head - c\n if new_amount > -1 and new_amount not in seen:\n queue.append((new_amount, res + 1))\n seen.add(new_amount)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not coins or amount < 0:\n return -1\n if amount == 0:\n return 0\n q = [(amount, 0)]\n visited = {0}\n coins.sort(reverse=True)\n while q:\n (node, depth) = q.pop(0)\n for coin in coins:\n rest = node - coin\n if rest == 0:\n return depth + 1\n if rest > 0 and rest not in visited:\n q.append((rest, depth + 1))\n visited.add(rest)\n return -1", "from collections import deque\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n visited = {0}\n tempQueue = deque()\n tempQueue.append((0, 0))\n while tempQueue:\n (currentVal, currentCount) = tempQueue.popleft()\n for coin in coins:\n nextVal = currentVal + coin\n if nextVal == amount:\n return currentCount + 1\n elif nextVal < amount:\n if nextVal not in visited:\n visited.add(nextVal)\n tempQueue.append((nextVal, currentCount + 1))\n return -1", "def coinchange(coins, amount):\n coins.sort(reverse=True)\n queue = [(amount, 0)]\n visited = [False for i in range(amount + 1)]\n for (val, cnt) in queue:\n if val == 0:\n return cnt\n for coin in coins:\n if val - coin >= 0 and (not visited[val - coin]):\n visited[val - coin] = True\n queue.append((val - coin, cnt + 1))\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n queue = deque([])\n seen = set()\n coins = sorted(coins, reverse=True)\n queue.append((0, 0))\n while queue:\n (summ, num_coins) = queue.popleft()\n if summ == amount:\n return num_coins\n for coin in coins:\n if summ + coin <= amount and summ + coin not in seen:\n queue.append((summ + coin, num_coins + 1))\n seen.add(summ + coin)\n return -1", "def coinchange(coins, amount):\n if not coins:\n return -1\n if not amount:\n return 0\n if amount in coins:\n return 1\n C = tuple(sorted(coins, reverse=True))\n (length, self.ans) = (len(C) - 1, float('inf'))\n\n def find(coin, step, target):\n now_coin = C[coin]\n (q, r) = divmod(target, now_coin)\n if not r:\n self.ans = min(self.ans, step + q)\n elif coin < length and step + q + 1 < self.ans:\n coin += 1\n for j in range(q, -1, -1):\n find(coin, step + j, target - j * now_coin)\n find(0, 0, amount)\n return -1 if self.ans == float('inf') else self.ans", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n dp = [0] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n min = math.inf\n for j in coins:\n if i - j >= 0 and dp[i - j] < min:\n min = dp[i - j]\n dp[i] = min + 1\n return dp[-1] if dp[-1] != math.inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n numpath = [0] + [float('inf')] * amount\n for coin in coins:\n for i in range(coin, amount + 1):\n if numpath[i] > 1 + numpath[i - coin]:\n numpath[i] = 1 + numpath[i - coin]\n return numpath[amount] if numpath[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not coins or amount <= 0:\n return 0\n coins = set(coins)\n count = 1\n q = deque()\n q.append((amount, count))\n visited = set()\n visited.add(amount)\n while q:\n (remain, count) = q.popleft()\n if remain in coins:\n return count\n for c in coins:\n if remain - c > 0 and remain - c not in visited:\n q.append((remain - c, count + 1))\n visited.add(remain - c)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n Visited = {amount: 0}\n coins.sort(reverse=True)\n queue = deque()\n queue.append(amount)\n while queue:\n curr = queue.popleft()\n for coin in coins:\n if curr - coin >= 0 and curr - coin not in Visited:\n queue.append(curr - coin)\n Visited[curr - coin] = Visited[curr] + 1\n if 0 in Visited:\n return Visited[0]\n return -1", "from collections import deque\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n q = deque()\n q.append([amount, 0])\n level = 0\n seen = set()\n while q:\n (amt, level) = q.popleft()\n for n in coins:\n if amt - n == 0:\n return level + 1\n if amt - n in seen or amt - n < 0:\n continue\n seen.add(amt - n)\n q.append([amt - n, level + 1])\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n coins.sort()\n visited = {}\n sums = []\n for coin in coins:\n if coin == amount:\n return 1\n visited[coin] = 1\n sums.append(coin)\n q = []\n q.append((1, sums))\n while q:\n (count, sums) = q.pop()\n next_sums = []\n for coin in coins:\n for s in sums:\n current = coin + s\n if current < amount and current not in visited:\n visited[current] = 1\n next_sums.append(current)\n elif current == amount:\n return count + 1\n else:\n visited[current] = 1\n if next_sums:\n q.insert(0, (count + 1, next_sums))\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1 for i in range(amount + 1)]\n dp[0] = 0\n for i in range(amount + 1):\n for c in coins:\n if c <= i and dp[i] > dp[i - c] + 1:\n dp[i] = dp[i - c] + 1\n return -1 if dp[amount] > amount else dp[amount]", "from collections import deque\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n queue = deque([(amount, 0)])\n visited = set([amount])\n while queue:\n (remaining, steps) = queue.popleft()\n for coin in coins:\n if coin == remaining:\n return steps + 1\n elif coin < remaining:\n temp = remaining - coin\n if temp > 0 and temp not in visited:\n visited.add(temp)\n queue.append((temp, steps + 1))\n return -1", "from collections import defaultdict\n\ndef coinchange(coins: List[int], amount: int) -> int:\n MAX = float('inf')\n dp = defaultdict(lambda : MAX)\n dp[0] = 0\n for i in range(1, amount + 1):\n dp[i] = 1 + min([dp[i - c] for c in coins])\n return -1 if dp[amount] == MAX else dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n l = [int(amount + 1)] * int(amount + 1)\n if amount == 0:\n return 0\n else:\n l[0] = 0\n coins.sort()\n for i in range(1, amount + 1):\n for coin in coins:\n remainder = i - coin\n if remainder < 0:\n break\n elif l[i] > l[remainder] + 1:\n l[i] = l[remainder] + 1\n if l[amount] == amount + 1:\n return -1\n else:\n return l[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n coins.sort(reverse=True)\n queue = [amount]\n visit = {amount: 0}\n while queue:\n remain = queue.pop(0)\n for c in coins:\n branch = remain - c\n if 0 <= branch not in visit:\n queue.append(branch)\n visit.update({branch: visit[remain] + 1})\n return visit.get(0) or -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n visited = set([amount])\n candidates = [amount]\n res = 0\n while candidates:\n res += 1\n next_candidates = []\n for candidate in candidates:\n for coin in coins:\n if candidate - coin == 0:\n return res\n elif candidate - coin > 0 and candidate - coin not in visited:\n next_candidates.append(candidate - coin)\n visited.add(candidate - coin)\n candidates = next_candidates\n return -1", "def coinchange(denoms: List[int], n: int) -> int:\n if n == 0:\n return 0\n nodes = set([0])\n seen = set()\n count = 1\n while nodes:\n seen = seen | nodes\n next_nodes = set()\n for node in nodes:\n for denom in denoms:\n candidate = node + denom\n if candidate == n:\n return count\n elif candidate < n and candidate not in seen:\n next_nodes.add(candidate)\n count += 1\n nodes = next_nodes\n return -1\n pass", "def coinchange(coins: List[int], amount: int) -> int:\n d = [0] + [float('inf')] * amount\n for v in range(1, len(d)):\n for c in coins:\n if c <= v and d[v] > d[v - c] + 1:\n d[v] = d[v - c] + 1\n return d[-1] if d[-1] < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n queue = deque()\n numCoins = 0\n seen = set()\n coins.sort(reverse=True)\n queue.append(amount)\n if amount == 0:\n return 0\n while queue:\n qlen = len(queue)\n numCoins += 1\n for i in range(qlen):\n x = queue.popleft()\n for coin in coins:\n if x - coin == 0:\n return numCoins\n elif x - coin > 0:\n if x - coin not in seen:\n queue.append(x - coin)\n seen.add(x - coin)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n result = -1\n\n def helper(coins: List[int], pos: int, left: int, current: int):\n if left % coins[pos] == 0:\n nonlocal result\n if result == -1 or result > current + left // coins[pos]:\n result = current + left // coins[pos]\n return\n if pos == len(coins) - 1:\n return\n for k in range(left // coins[pos], -1, -1):\n new_amount = left - coins[pos] * k\n new_count = current + k\n if result != -1 and result < new_count + (new_amount + coins[pos + 1] - 1) / coins[pos + 1]:\n break\n helper(coins, pos + 1, left - coins[pos] * k, current + k)\n helper(coins, 0, amount, 0)\n return result", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n queue = collections.deque([(0, 0)])\n seen = set()\n while queue:\n (curAmount, step) = queue.popleft()\n if curAmount == amount:\n return step\n for j in range(len(coins)):\n newAmount = curAmount + coins[j]\n if newAmount <= amount and newAmount not in seen:\n seen.add(newAmount)\n queue.append((newAmount, step + 1))\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n coins.sort()\n coins_set = set(coins)\n if amount in coins_set:\n return 1\n queue = deque([[amount, 0]])\n seen = set()\n processed = set()\n while queue:\n (rem, count) = queue.popleft()\n if rem in seen:\n continue\n seen.add(rem)\n for coin in coins:\n new_rem = rem - coin\n if new_rem == 0:\n return count + 1\n if new_rem > 0:\n if new_rem in coins_set:\n return count + 2\n if new_rem not in seen and new_rem not in processed:\n queue.append([new_rem, count + 1])\n processed.add(new_rem)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('+inf')] * (amount + 1)\n dp[0] = 0\n for cnt in range(1, amount + 1):\n for coin in coins:\n if cnt - coin >= 0 and dp[cnt - coin] + 1 < dp[cnt]:\n dp[cnt] = dp[cnt - coin] + 1\n if dp[amount] == float('+inf'):\n return -1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('inf') for _ in range(amount + 1)]\n dp[0] = 0\n for x in range(len(dp)):\n for coin in coins:\n if x < coin:\n continue\n if dp[x - coin] + 1 < dp[x]:\n dp[x] = dp[x - coin] + 1\n if dp[amount] == float('inf'):\n return -1\n else:\n return dp[x]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n rec = [0] * amount\n fr = [0]\n new = []\n l = 1\n while fr or new:\n if not fr:\n fr = new\n new = []\n l += 1\n cur = fr.pop(0)\n for c in coins:\n if cur + c == amount:\n return l\n if cur + c < amount and (not rec[cur + c]):\n new.append(cur + c)\n rec[cur + c] = 1\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n memo = [float('inf') for _ in range(amount + 1)]\n memo[0] = 0\n for i in range(1, len(memo)):\n minv = float('inf')\n for coin in coins:\n if i - coin >= 0 and memo[i - coin] < minv:\n minv = memo[i - coin]\n memo[i] = 1 + minv\n return memo[amount] if memo[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n cache = [0] * (amount + 1)\n for ind in range(1, amount + 1):\n min_coins = float('inf')\n for coin in coins:\n if ind - coin >= 0:\n coins_needed = cache[ind - coin] + 1\n if coins_needed < min_coins:\n min_coins = coins_needed\n cache[ind] = min_coins\n if cache[amount] == float('inf'):\n return -1\n return cache[amount]", "def coinchange(coins: [int], amount: int) -> int:\n summary = 0\n result = [float('inf')] * (amount + 1)\n result[0] = 0\n while summary <= amount:\n if result[summary] != -1:\n for i in coins:\n if summary + i <= amount and result[summary] + 1 < result[summary + i]:\n result[summary + i] = result[summary] + 1\n summary += 1\n return -1 if result[amount] == float('inf') else result[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n arr = [float('inf')] * (amount + 1)\n arr[0] = 0\n for i in range(amount + 1):\n for c in coins:\n if i + c > amount:\n continue\n if arr[i + c] > arr[i] + 1:\n arr[i + c] = arr[i] + 1\n if arr[-1] == float('inf'):\n return -1\n return arr[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n min_coins = [float('inf') for x in range(amount + 1)]\n min_coins[0] = 0\n for value in range(1, amount + 1):\n for coin in coins:\n if coin <= value:\n if min_coins[value - coin] + 1 < min_coins[value]:\n min_coins[value] = min_coins[value - coin] + 1\n if min_coins[amount] == float('inf'):\n return -1\n return min_coins[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n queue = [[amount, 0]]\n visited = {0}\n for q in queue:\n for c in coins:\n if q[0] == c:\n return q[1] + 1\n elif q[0] > c and q[0] - c not in visited:\n visited.add(q[0] - c)\n queue.append([q[0] - c, q[1] + 1])\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [0] * (amount + 1)\n for i in range(1, len(dp)):\n dp[i] = float('inf')\n for j in coins:\n if i >= j and dp[i - j] + 1 < dp[i]:\n dp[i] = dp[i - j] + 1\n return -1 if dp[amount] == float('inf') else dp[amount]", "def bfs(cur, coins):\n if cur == 0:\n return 0\n queue = [(0, cur)]\n visited = {}\n while queue:\n (times, cur) = heapq.heappop(queue)\n for c in coins:\n if c == cur:\n return times + 1\n if c < cur:\n if cur - c not in visited:\n heapq.heappush(queue, (times + 1, cur - c))\n visited[cur - c] = True\n return -1\n\ndef coinchange(coins: List[int], amount: int) -> int:\n return self.bfs(amount, coins)", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n tmp = float('inf')\n for c in coins:\n if i - c >= 0:\n if tmp > dp[i - c] + 1:\n tmp = dp[i - c] + 1\n dp[i] = tmp\n return dp[amount] if dp[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp_mat = [-1] * (amount + 1)\n dp_mat[0] = 0\n for i in range(1, amount + 1):\n min_num = None\n for denom in coins:\n if denom <= i and dp_mat[i - denom] != -1:\n temp = 1 + dp_mat[i - denom]\n if not min_num:\n min_num = temp\n elif temp < min_num:\n min_num = temp\n if min_num:\n dp_mat[i] = min_num\n return dp_mat[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n dp = [float('inf')] * (amount + 1)\n calculated = [False] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n if coin <= amount:\n dp[coin] = 1\n calculated[coin] = True\n for i in range(1, amount + 1):\n if not calculated[i]:\n candidates = [dp[i - coin] for coin in coins if i >= coin]\n if candidates:\n dp[i] = min(candidates) + 1\n calculated[i] = True\n if dp[-1] == float('inf'):\n return -1\n else:\n return dp[-1]", "def do_du_tab(coins, amount):\n dp_tab = [math.inf for _ in range(amount + 1)]\n dp_tab[0] = 0\n for a in range(1, amount + 1):\n potential = []\n for coin in coins:\n potential.append(dp_tab[a - coin] + 1)\n dp_tab[a] = min(potential)\n return dp_tab[-1] if dp_tab[-1] != float('inf') else -1\n\ndef do_something(coins, amount):\n dp_tab = [math.inf for _ in range(amount + 1)]\n dp_tab[0] = 0\n for i in range(1, amount + 1):\n temp = []\n for coin in coins:\n temp.append(dp_tab[i - coin])\n dp_tab[i] = min(temp) + 1\n return dp_tab[amount] if dp_tab[amount] != float('inf') else -1\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if len(coins) == 0:\n return 0\n if amount == 0:\n return 0\n c = [coin for coin in coins if coin <= amount]\n if len(c) == 0:\n return -1\n return self.do_something(c, amount)", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n curr_min = amount + 1\n for coin in coins:\n cand = amount + 1\n if i - coin >= 0:\n cand = dp[i - coin] + 1\n if cand < curr_min:\n curr_min = cand\n dp[i] = curr_min\n return -1 if dp[len(dp) - 1] == amount + 1 else dp[len(dp) - 1]", "def coinchange(coins: List[int], amount: int) -> int:\n return self.coinchangeBFS(coins, amount)\n\ndef coinchangeBFS(coins: List[int], amount: int) -> int:\n if amount == 0 or not coins:\n return 0\n queue = deque([amount])\n visited = set([amount])\n depth = 0\n while queue:\n length = len(queue)\n depth += 1\n for i in range(length):\n remaining = queue.popleft()\n for c in coins:\n if remaining - c == 0:\n return depth\n elif remaining - c < 0:\n continue\n elif remaining - c not in visited:\n queue.append(remaining - c)\n visited.add(remaining - c)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n values = [-1 for i in range(amount + 1)]\n values[0] = 0\n for i in coins:\n for j in range(1, len(values)):\n if j >= i:\n if values[j - i] == -1:\n continue\n curr_num_coins = 1 + values[j - i]\n if values[j] == -1 or values[j] > curr_num_coins:\n values[j] = curr_num_coins\n return values[amount]", "def coinchange(nums: List[int], amount: int) -> int:\n MAX = float('inf')\n dp = [0] + [MAX] * amount\n for i in range(1, amount + 1):\n dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in nums]) + 1\n return [dp[amount], -1][dp[amount] == MAX]", "from collections import deque\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n dp = [float('inf')] * (amount + 1)\n dp[amount] = 0\n queue = deque()\n queue.append(amount)\n while len(queue) != 0:\n val = queue.popleft()\n for coin in coins:\n if val - coin == 0:\n return dp[val] + 1\n if val - coin > 0:\n if dp[val] + 1 < dp[val - coin]:\n dp[val - coin] = dp[val] + 1\n queue.append(val - coin)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n MAX = amount + 1\n coins.sort(reverse=True)\n dp = [MAX] * MAX\n dp[0] = 0\n for i in range(1, MAX):\n dp[i] = min([dp[i - c] if i >= c else MAX for c in coins])\n dp[i] = dp[i] + 1 if dp[i] != MAX else dp[i]\n return -1 if dp[-1] == MAX else dp[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [0] + [-1] * amount\n for x in range(amount + 1):\n if dp[x] < 0:\n continue\n for c in coins:\n if x + c > amount:\n continue\n if dp[x + c] < 0 or dp[x + c] > dp[x] + 1:\n dp[x + c] = dp[x] + 1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n coins.sort()\n cnt = 0\n toCheck = {amount}\n while toCheck:\n cnt += 1\n tmp = set()\n for x in toCheck:\n for y in coins:\n if y == x:\n return cnt\n if y > x:\n break\n tmp.add(x - y)\n if not tmp:\n return -1\n toCheck = tmp\n\ndef coinchange(coins: List[int], amount: int) -> int:\n dp = [0] + [float('inf')] * amount\n for i in range(1, amount + 1):\n dp[i] = min((dp[i - c] if i - c >= 0 else float('inf') for c in coins)) + 1\n return dp[-1] if dp[-1] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [0] + [-1] * amount\n for coin in coins:\n for idx in range(coin, len(dp)):\n if dp[idx - coin] != -1:\n if dp[idx] != -1:\n dp[idx] = min(dp[idx - coin] + 1, dp[idx])\n else:\n dp[idx] = dp[idx - coin] + 1\n return dp[amount]", "def coinchange(coins, amount):\n MAX = float('inf')\n dp = [0] + [MAX] * amount\n for i in range(1, amount + 1):\n dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in coins]) + 1\n if dp[amount] == MAX:\n return -1\n return dp[amount]\n return [dp[amount], -1][dp[amount] == MAX]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for i in range(min(coins), amount + 1):\n tmp = list()\n for coin in coins:\n if i - coin < 0:\n tmp.append(float('inf'))\n else:\n tmp.append(dp[i - coin])\n dp[i] = min(tmp) + 1\n return dp[-1] if dp[-1] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n coins = [coin for coin in coins if coin <= amount]\n if not coins:\n return -1\n dp = [0 for i in range(amount + max(coins) + 10)]\n for coin in coins:\n dp[coin] = 1\n for i in range(1, amount + 1):\n for coin in coins:\n if dp[i] >= 1:\n if dp[i + coin] == 0:\n dp[i + coin] = dp[i] + 1\n elif dp[i] + 1 < dp[i + coin]:\n dp[i + coin] = dp[i] + 1\n if not dp[amount]:\n return -1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def dfs(start, amt, n_coins):\n nonlocal min_coins\n coin = coins[start]\n div = amt // coin\n n_coins += div\n amt %= coin\n if amt == 0:\n min_coins = min(min_coins, n_coins)\n return\n if start < len_coins:\n dfs(start + 1, amt, n_coins)\n next_coin = coins[start + 1]\n for _ in range(div):\n amt += coin\n n_coins -= 1\n if (min_coins - n_coins - 1) * next_coin + 1 > amt:\n dfs(start + 1, amt, n_coins)\n else:\n break\n len_coins = len(coins) - 1\n coins.sort(reverse=True)\n min_coins = float('inf')\n dfs(0, amount, 0)\n return min_coins if min_coins < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n coins_set = set(coins)\n for i in range(amount + 1):\n if i in coins_set:\n dp[i] = 1\n continue\n candidates = [dp[i - c] + 1 for c in coins if i - c >= 0]\n if candidates:\n dp[i] = min(candidates)\n return dp[amount] if dp[amount] <= amount else -1", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n path_length = []\n path_length.append(0)\n for value in range(1, amount + 1):\n min_path_value = math.inf\n for coin in coins:\n path_index = value - coin\n if path_index > -1 and path_length[path_index] != -1:\n current_min_path = path_length[path_index] + 1\n if current_min_path < min_path_value:\n min_path_value = current_min_path\n path_length.append(min_path_value)\n return path_length[amount] if path_length[amount] < math.inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n cache = [0] * (amount + 1)\n for i in range(1, amount + 1):\n min_count = float('inf')\n for coin in coins:\n if i - coin >= 0:\n current_min_coin = cache[i - coin] + 1\n if min_count > current_min_coin:\n min_count = current_min_coin\n cache[i] = min_count\n if cache[amount] in [0, float('inf')]:\n return -1\n return cache[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [None for i in range(amount + 1)]\n dp[0] = 0\n for i in range(1, amount + 1):\n result = None\n for coin in coins:\n if i - coin >= 0:\n tmp = dp[i - coin]\n if tmp is not None and (result is None or tmp + 1 < result):\n result = tmp + 1\n dp[i] = result\n if dp[-1] is None:\n return -1\n return dp[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n arr = [float('inf')] * (amount + 1)\n arr[0] = 0\n for i in range(1, len(arr)):\n min_choices = []\n for x in coins:\n if i - x >= 0:\n min_choices.append(1 + arr[i - x])\n if min_choices:\n arr[i] = min(min_choices)\n if arr[amount] == float('inf'):\n return -1\n else:\n return arr[amount]", "def __init__():\n self.min_coins = float('inf')\n\ndef coinchange(coins: List[int], amount: int) -> int:\n\n def getChange(num_coins, need, start):\n divided_coin = need // coins[start]\n if num_coins + divided_coin >= self.min_coins:\n return\n if need % coins[start] == 0:\n self.min_coins = min(self.min_coins, divided_coin + num_coins)\n return\n if start == len(coins) - 1:\n return\n for num_used in range(divided_coin, -1, -1):\n new_need = need - coins[start] * num_used\n getChange(num_coins + num_used, new_need, start + 1)\n coins = sorted(coins, reverse=True)\n getChange(0, amount, 0)\n return self.min_coins if self.min_coins < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n T = [float('inf')] * (amount + 1)\n T[0] = 0\n for amnt in range(1, amount + 1):\n curr_min = float('inf')\n for k in range(len(coins)):\n if coins[k] <= amnt:\n val = 1 + T[amnt - coins[k]]\n if val < curr_min:\n curr_min = val\n T[amnt] = curr_min\n return -1 if T[-1] == float('inf') else T[-1]", "from typing import List\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n solution = -1\n dp = [0] * (amount + 1)\n for i in range(1, amount + 1):\n dp[i] = min([dp[i - coin] for coin in coins if i - coin >= 0] + [10000]) + 1\n if dp[-1] != 10001:\n solution = dp[-1]\n return solution", "def coinchange(coins: List[int], amount: int) -> int:\n coins = sorted(coins, reverse=True)\n dp = [-1] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n if i - coins[-1] < 0:\n continue\n for coin in coins:\n index = i - coin\n if index >= 0 and dp[index] != -1:\n value = dp[index] + 1\n if dp[i] == -1 or dp[i] > value:\n dp[i] = value\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n self.ret = float('inf')\n\n def recurrent(index, coins, amount, current):\n first = coins[index]\n n = amount // first\n remainder = amount % first\n if remainder == 0:\n self.ret = min(self.ret, current + n)\n else:\n l = len(coins)\n while remainder <= amount and index < l - 1 and (current + n < self.ret):\n recurrent(index + 1, coins, remainder, current + n)\n n -= 1\n remainder += first\n return\n recurrent(0, coins, amount, 0)\n if self.ret == float('inf'):\n return -1\n else:\n return self.ret", "def coinchange(coins: List[int], amount: int) -> int:\n if not coins or amount <= 0:\n return 0\n f = [float('inf')] * (amount + 1)\n f[0] = 0\n for c in coins:\n for a in range(c, amount + 1):\n f[a] = min(f[a], f[a - c] + 1)\n return f[amount] if f[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1 for _ in range(amount + 1)]\n dp[0] = 0\n for coin in coins:\n for a in range(coin, amount + 1):\n dp[a] = min(dp[a], dp[a - coin] + 1)\n res = dp[amount] if dp[amount] < amount + 1 else -1\n return res", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [0] + [float('inf')] * amount\n for c in coins:\n for j in range(c, amount + 1):\n dp[j] = min(dp[j], dp[j - c] + 1)\n return dp[-1] if dp[-1] < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [math.inf] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for idx in range(coin, amount + 1):\n prev_coins_ct = dp[idx - coin]\n dp[idx] = min(prev_coins_ct + 1, dp[idx])\n if dp[-1] == math.inf:\n return -1\n return dp[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount < 0:\n return -1\n coins = sorted(coins)\n d = [amount + 1] * (amount + 1)\n d[0] = 0\n for i in range(amount + 1):\n for j in coins:\n if j <= i:\n d[i] = min(d[i], d[i - j] + 1)\n else:\n break\n if d[-1] > amount:\n return -1\n else:\n return d[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n dp = [-1] * (amount + 1)\n dp[0] = 0\n for i in range(len(coins)):\n if coins[i] <= amount:\n dp[coins[i]] = 1\n for i in range(1, amount + 1):\n if dp[i] == -1:\n comparison = []\n for c in coins:\n if i - c >= 0 and dp[i - c] != -1:\n comparison.append(dp[i - c])\n if comparison:\n dp[i] = min(comparison) + 1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n memo = [float('inf') for _ in range(amount + 1)]\n memo[0] = 0\n for c in coins:\n for i in range(c, len(memo)):\n memo[i] = min(1 + memo[i - c], memo[i])\n return memo[amount] if memo[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n for j in coins:\n if i >= j:\n dp[i] = min(dp[i], dp[i - j] + 1)\n if dp[amount] == amount + 1:\n return -1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n rs = [amount + 1] * (amount + 1)\n rs[0] = 0\n for i in range(1, amount + 1):\n for c in coins:\n if i >= c:\n rs[i] = min(rs[i], rs[i - c] + 1)\n if rs[amount] == amount + 1:\n return -1\n return rs[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [sys.maxsize] * (amount + 1)\n dp[0] = 0\n for i in range(1, len(dp)):\n for c in coins:\n if c <= i:\n dp[i] = min(dp[i], dp[i - c] + 1)\n if dp[amount] == sys.maxsize:\n return -1\n return dp[amount]", "import math\n\ndef rec(coins, amount, used_coins, res):\n if amount == 0:\n res[0] = min(res[0], used_coins)\n elif coins and (res[0] - used_coins) * coins[-1] >= amount:\n for i in range(amount // coins[-1], -1, -1):\n rec(coins[:-1], amount - i * coins[-1], used_coins + i, res)\n\ndef coinchange(coins: List[int], amount: int) -> int:\n res = [math.inf]\n rec(sorted(coins), amount, 0, res)\n return res[0] if res[0] != math.inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not coins or len(coins) == 0:\n return 0\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for i in range(amount + 1):\n for j in coins:\n if j <= i:\n dp[i] = min(dp[i], dp[i - j] + 1)\n if dp[-1] > amount:\n return -1\n else:\n return dp[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n if amount == 0:\n return 0\n changes = [amount + 1] * (amount + 1)\n changes[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n if coin > i:\n break\n else:\n changes[i] = min(changes[i], changes[i - coin] + 1)\n if changes[-1] != amount + 1:\n return changes[-1]\n else:\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return amount\n dp = [1000000000.0 for _ in range(amount + 1)]\n dp[0] = 0\n for i in range(1, amount + 1):\n k = 1000000000.0\n for c in coins:\n if i - c >= 0:\n k = min(k, dp[i - c] + 1)\n if k != 1000000000.0:\n dp[i] = k\n return -1 if dp[amount] == 1000000000.0 else dp[amount]", "def coinchange(coins, amount):\n coins.sort(reverse=True)\n (lenc, self.res) = (len(coins), 2 ** 31 - 1)\n\n def dfs(pt, rem, count):\n if not rem:\n self.res = min(self.res, count)\n for i in range(pt, lenc):\n if coins[i] <= rem < coins[i] * (self.res - count):\n dfs(i, rem - coins[i], count + 1)\n for i in range(lenc):\n dfs(i, amount, 0)\n return self.res if self.res < 2 ** 31 - 1 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n coins = sorted(coins)\n dp = [amount + 1 for _ in range(amount + 1)]\n dp[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n if coin > i:\n break\n dp[i] = min(dp[i], dp[i - coin] + 1)\n res = dp[amount] if dp[amount] < amount + 1 else -1\n return res", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n count = [math.inf] * (amount + 1)\n count[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n if i >= coin:\n count[i] = min(count[i], count[i - coin] + 1)\n return count[amount] if count[amount] != math.inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n\n def giveChange(target):\n if target == 0:\n return 0\n if target < 0:\n return -1\n minForTarget = None\n for coin in coins:\n result = giveChange(target - coin)\n if result != -1:\n minForTarget = result + 1 if not minForTarget else min(result + 1, minForTarget)\n return minForTarget or -1\n return giveChange(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n n = len(coins)\n dp = [0] + [amount + 1 for i in range(amount)]\n for i in range(1, amount + 1):\n for c in coins:\n if i >= c:\n dp[i] = min(dp[i - c] + 1, dp[i])\n return dp[amount] if dp[amount] < amount + 1 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n self.min = 2 ** 31 - 1\n\n def dfs(index, amount, count):\n if amount == 0:\n self.min = min(self.min, count)\n if amount < 0:\n return\n for i in range(index, len(coins)):\n if coins[i] * (self.min - count) > amount >= coins[i]:\n dfs(i, amount - coins[i], count + 1)\n dfs(0, amount, 0)\n return self.min if self.min != 2 ** 31 - 1 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n ary = [amount + 1] * (amount + 1)\n ary[0] = 0\n for i in range(1, len(ary)):\n for coin in coins:\n if i - coin < 0:\n continue\n ary[i] = min(ary[i], ary[i - coin] + 1)\n return ary[amount] if ary[amount] < amount + 1 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n numOfCoins = [float('inf') for x in range(amount + 1)]\n numOfCoins[0] = 0\n for coin in coins:\n for num in range(len(numOfCoins)):\n if coin <= num:\n numOfCoins[num] = min(numOfCoins[num], numOfCoins[num - coin] + 1)\n return numOfCoins[amount] if numOfCoins[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n MAX = float('inf')\n dp = [0] + [MAX] * amount\n for i in range(1, amount + 1):\n for coin in coins:\n if i - coin >= 0:\n dp[i] = min(dp[i], dp[i - coin] + 1)\n if dp[-1] == MAX:\n return -1\n return dp[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n MAX = amount + 10\n dp = [MAX for i in range(amount + 1)]\n dp[0] = 0\n for i in range(1, amount + 1):\n curr = i\n for coin in coins:\n prev = curr - coin\n if prev >= 0:\n dp[curr] = min(dp[curr], dp[prev] + 1)\n return dp[amount] if dp[amount] != MAX else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [-1 for i in range(amount + 1)]\n dp[0] = 0\n for coin in coins:\n for i in range(coin, amount + 1):\n if i == coin:\n dp[i] = 1\n elif dp[i] == -1 and dp[i - coin] != -1:\n dp[i] = dp[i - coin] + 1\n elif dp[i] != -1 and dp[i - coin] != -1:\n dp[i] = min(dp[i], dp[i - coin] + 1)\n return dp[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def change_memo(coins, amount, memo):\n if amount not in memo:\n if amount == 0:\n best = 0\n elif amount < 0:\n best = -1\n else:\n best = None\n for c in coins:\n res = change_memo(coins, amount - c, memo)\n if res == -1:\n continue\n if best is None or res < best:\n best = res\n if best is None:\n best = -1\n else:\n best += 1\n memo[amount] = best\n return memo[amount]\n memo = {}\n change_memo(coins, amount, memo)\n return memo[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n min_coins = float('inf')\n\n def count_coins(start_coin, coin_count, remaining_amount):\n nonlocal min_coins\n if remaining_amount == 0:\n min_coins = min(min_coins, coin_count)\n return\n for i in range(start_coin, len(coins)):\n remaining_coin_allowance = min_coins - coin_count\n max_amount_possible = coins[i] * remaining_coin_allowance\n if coins[i] <= remaining_amount and remaining_amount < max_amount_possible:\n count_coins(i, coin_count + 1, remaining_amount - coins[i])\n count_coins(0, 0, amount)\n return min_coins if min_coins < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n curr = [float('inf')] * (amount + 1)\n curr[0] = 0\n coins = sorted(coins)\n for num in range(amount + 1):\n for c in coins:\n if num - c < 0:\n break\n curr[num] = min(curr[num], curr[num - c] + 1)\n return curr[amount] if curr[amount] < float('inf') else -1", "import sys\n\ndef coinchange(coins: List[int], amount: int) -> int:\n dp = [sys.maxsize] * (amount + 1)\n if amount == 0:\n return 0\n dp[amount] = 0\n for i in range(amount, -1, -1):\n for coin in coins:\n if i - coin >= 0:\n dp[i - coin] = min(dp[i] + 1, dp[i - coin])\n return -1 if dp[0] == sys.maxsize else dp[0]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def _recursive(a):\n if a == 0:\n return 0\n min_n = 1000000000.0\n for c in coins:\n if c <= a:\n sub_a = _recursive(a - c)\n if sub_a != -1:\n min_n = min(min_n, sub_a + 1)\n return min_n if min_n != 1000000000.0 else -1\n return _recursive(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n res = {}\n res[0] = 0\n for x in range(amount + 1)[1:]:\n prevs = [x - c for c in coins]\n this_res = min([res.get(y, 2 ** 31) for y in prevs]) + 1\n res[x] = this_res\n if res[amount] >= 2 ** 31:\n return -1\n else:\n return res[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n if len(coins) == 1:\n if amount % coins[0] == 0:\n return amount // coins[0]\n return -1\n dp = [0] * (amount + 1)\n for i in range(1, amount + 1):\n if i in set(coins):\n dp[i] = 1\n continue\n min_coins = float('inf')\n for coin in coins:\n if i - coin >= 0:\n min_coins = min(dp[i - coin], min_coins)\n dp[i] = min_coins + 1\n if dp[amount] == float('inf'):\n return -1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n amount_list = [i for i in range(amount + 1)]\n for i in range(amount + 1):\n if i == 0:\n amount_list[i] = 0\n elif i in coins:\n amount_list[i] = 1\n else:\n temp = []\n for coin in coins:\n if amount_list[i] - coin >= 0:\n remainder = amount_list[i] - coin\n min_coin = amount_list[remainder]\n if min_coin != -1:\n temp.append(min_coin)\n if len(temp) == 0:\n amount_list[i] = -1\n else:\n amount_list[i] = min(temp) + 1\n return amount_list[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n\n def _fewest(cs, amt):\n nonlocal memo\n if amt not in memo:\n if amt < 0:\n memo[amt] = -1\n elif amt == 0:\n memo[amt] = 0\n else:\n fewest = -1\n for c in cs:\n f = _fewest(cs, amt - c)\n if f != -1 and (fewest == -1 or f + 1 < fewest):\n fewest = f + 1\n memo[amt] = fewest\n return memo[amt]\n return _fewest(coins, amount)", "def coinchange(coins: List[int], amount: int) -> int:\n mem = {}\n mem[0] = 0\n\n def rec(amount):\n if amount < 0:\n return -1\n if amount in mem:\n return mem[amount]\n m = math.inf\n for c in coins:\n n = rec(amount - c)\n if n != -1 and n + 1 < m:\n m = n + 1\n if m == math.inf:\n m = -1\n mem[amount] = m\n return m\n if amount == 0:\n return 0\n return rec(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for i in range(len(coins)):\n coin = coins[i]\n for j in range(1, amount + 1):\n sameCoin = amount + 1\n if j - coin >= 0:\n dp[j] = min(dp[j - coin] + 1, dp[j])\n return dp[amount] if dp[amount] != amount + 1 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for partial_amount in range(1, amount + 1):\n for j in range(len(coins)):\n if coins[j] <= partial_amount:\n dp[partial_amount] = min(dp[partial_amount], dp[partial_amount - coins[j]] + 1)\n return dp[amount] if dp[amount] <= amount else -1", "def coinchange(coins: List[int], amount: int) -> int:\n num_ways = (amount + 1) * [-1]\n num_ways[0] = 0\n for v in range(1, amount + 1):\n fewest = float('inf')\n for c in coins:\n if v - c >= 0 and num_ways[v - c] != -1:\n fewest = min(num_ways[v - c], fewest)\n if fewest != float('inf'):\n num_ways[v] = 1 + fewest\n return num_ways[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def helpCoins(coins, amount, cache):\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if amount in cache:\n return cache[amount]\n curr_min = 999\n for coin in coins:\n to_go = helpCoins(coins, amount - coin, cache)\n if to_go >= 0 and to_go < curr_min:\n curr_min = to_go + 1\n if curr_min == 999:\n cache[amount] = -1\n else:\n cache[amount] = curr_min\n return cache[amount]\n return helpCoins(coins, amount, {})", "import collections\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n seen = set()\n queue = collections.deque()\n for coin in coins:\n queue.append((amount - coin, 1))\n while queue:\n curr = queue.popleft()\n if curr[0] == 0:\n return curr[1]\n if curr[0] < 0 or curr[0] in seen:\n continue\n seen.add(curr[0])\n for coin in coins:\n queue.append((curr[0] - coin, curr[1] + 1))\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n memo = {}\n\n def helper(target, options):\n if target in memo:\n return memo[target]\n else:\n best = None\n for opt in options:\n if opt == target:\n memo[target] = 1\n return 1\n elif opt < target:\n cont = helper(target - opt, options)\n if cont is not None and (best is None or cont + 1 < best):\n best = cont + 1\n memo[target] = best\n return best\n output = helper(amount, coins)\n return output if output is not None else -1", "def util(memo, coins, amount):\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n minarr = []\n for coin in coins:\n if amount - coin not in memo:\n memo[amount - coin] = self.util(memo, coins, amount - coin)\n minarr.append(memo[amount - coin])\n minarr = [m for m in minarr if m != -1]\n if not minarr:\n return -1\n return min(minarr) + 1\n\ndef coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n return self.util(memo, coins, amount)", "def coinchange(coins: List[int], amount: int) -> int:\n D = [0] * (amount + 1)\n\n def helper(rem):\n nonlocal D\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if D[rem] != 0:\n return D[rem]\n minn = float('inf')\n for coin in coins:\n res = helper(rem - coin)\n if res >= 0 and res < minn:\n minn = res + 1\n if minn == float('inf'):\n D[rem] = -1\n else:\n D[rem] = minn\n return D[rem]\n return helper(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [None for i in range(0, amount + 1)]\n dp[0] = 0\n for i in range(1, amount + 1):\n min_cost = float('inf')\n for j in range(0, len(coins)):\n if coins[j] <= i:\n min_cost = min(min_cost, dp[i - coins[j]] + 1)\n dp[i] = min_cost\n if dp[-1] > amount:\n return -1\n return dp[-1]\n coinsNeeded = {}\n coinsNeeded[0] = 0\n for n in coins:\n coinsNeeded[n] = 1\n\n def findMinCoins(amount):\n if amount < 0:\n return float('inf')\n if amount in coinsNeeded:\n return coinsNeeded[amount]\n for n in coins:\n coinsUsed = 1 + findMinCoins(amount - n)\n if amount in coinsNeeded:\n coinsNeeded[amount] = min(coinsUsed, coinsNeeded[amount])\n else:\n coinsNeeded[amount] = coinsUsed\n return coinsNeeded[amount]\n findMinCoins(amount)\n if coinsNeeded[amount] == float('inf'):\n return -1\n return coinsNeeded[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n coins.sort()\n for i in range(amount + 1):\n for j in range(len(coins)):\n if coins[j] <= amount:\n dp[i] = min(dp[i], 1 + dp[i - coins[j]])\n else:\n break\n if dp[amount] > amount:\n return -1\n else:\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n self.coins = coins\n self.amount = amount\n self.cache = {}\n res = self.getValue(self.amount)\n if res is None:\n return -1\n else:\n return res\n\ndef getValue(amount):\n if amount in self.cache:\n return self.cache[amount]\n if amount < 0:\n return None\n if amount == 0:\n return 0\n if amount in self.coins:\n return 1\n min_count = None\n for coin in self.coins:\n count = self.getValue(amount - coin)\n if count is not None:\n if min_count is None or min_count > count + 1:\n min_count = count + 1\n self.cache[amount] = min_count\n return min_count", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n s = list()\n import sys\n for i in range(0, amount + 1):\n s.append(sys.maxsize)\n s[0] = 0\n for i in range(1, amount + 1):\n m = sys.maxsize\n for j in range(0, len(coins)):\n if i - coins[j] >= 0:\n m = min(m, s[i - coins[j]])\n if m == sys.maxsize:\n s[i] = m\n else:\n s[i] = m + 1\n if s[amount] == sys.maxsize:\n s[amount] = -1\n return s[amount]", "def coinchange(coins, amount):\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n for j in range(0, len(coins)):\n if coins[j] <= i:\n dp[i] = min(dp[i], dp[i - coins[j]] + 1)\n return -1 if dp[amount] > amount else dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount < 0 or not coins:\n return -1\n if amount == 0:\n return 0\n min_com = [0 for i in range(amount + 1)]\n for i in range(1, amount + 1):\n for c in coins:\n if i >= c and (min_com[i - c] > 0 or i - c == 0):\n if min_com[i] == 0:\n min_com[i] = min_com[i - c] + 1\n else:\n min_com[i] = min(min_com[i], min_com[i - c] + 1)\n if min_com[amount] == 0:\n return -1\n return min_com[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n self.smallest = float('inf')\n coins.sort(reverse=True)\n self.dfs(coins, amount, 0)\n return -1 if type(self.smallest) is float else self.smallest\n\ndef dfs(coins, amount, prev_count):\n if len(coins) == 0:\n return\n if amount % coins[0] == 0:\n self.smallest = min(self.smallest, prev_count + amount // coins[0])\n else:\n for k in range(amount // coins[0], -1, -1):\n if prev_count + k >= self.smallest:\n break\n self.dfs(coins[1:], amount - k * coins[0], prev_count + k)", "def coinchange(coins: List[int], amount: int) -> int:\n\n def make_change(sum_remaining, coins, mem):\n if sum_remaining < 0:\n return -1\n elif sum_remaining == 0:\n return 0\n elif mem[sum_remaining]:\n return mem[sum_remaining]\n else:\n min_coins = amount + 1\n for coin in coins:\n if sum_remaining - coin >= 0:\n prev_coins = make_change(sum_remaining - coin, coins, mem)\n curr_coins = 1 + prev_coins\n if curr_coins > 0 and curr_coins < min_coins:\n min_coins = curr_coins\n mem[sum_remaining] = min_coins\n return mem[sum_remaining]\n mem = [None] * (amount + 1)\n ans = make_change(amount, coins, mem)\n if ans == amount + 1:\n return -1\n else:\n return ans", "import math\n\ndef f(coins, amount, counts):\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if counts[amount - 1] != 0:\n return counts[amount - 1]\n min_val = math.inf\n for c in coins:\n res = f(coins, amount - c, counts)\n if res >= 0 and res < min_val:\n min_val = 1 + res\n if min_val == math.inf:\n counts[amount - 1] = -1\n else:\n counts[amount - 1] = min_val\n return counts[amount - 1]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount < 1:\n return 0\n counts = [0] * amount\n return f(coins, amount, counts)", "def coinchange(coins: List[int], amount: int) -> int:\n\n def helper(amount):\n if amount <= 0:\n return 0\n min_so_far = math.inf\n for i in range(len(coins)):\n if coins[i] <= amount:\n min_so_far = min(min_so_far, 1 + helper(amount - coins[i]))\n return min_so_far\n result = helper(amount)\n if result == math.inf:\n return -1\n return result", "def coinchange(coins: List[int], amount: int) -> int:\n T = len(coins)\n dp = [0 for i in range(amount + 1)]\n for n in range(1, amount + 1):\n dp[n] = math.inf\n for i in range(T):\n if n - coins[i] >= 0:\n subProbSol = dp[n - coins[i]]\n dp[n] = min(dp[n], subProbSol + 1)\n if dp[amount] == math.inf:\n return -1\n else:\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n numCoins = [float('inf') for i in range(amount)]\n for coin in coins:\n if coin - 1 < amount:\n numCoins[coin - 1] = 1\n for i in range(amount):\n minCoin = float('inf')\n change = True\n for coin in coins:\n if i == coin - 1:\n change = False\n break\n if i - coin >= 0:\n minCoin = min(numCoins[i - coin], minCoin)\n if change and minCoin != float('inf'):\n numCoins[i] = minCoin + 1\n if numCoins[-1] == float('inf'):\n return -1\n return numCoins[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def helper(remAmt, coins):\n nonlocal mem\n if remAmt in mem:\n return mem[remAmt]\n minCoins = float('inf')\n for coin in coins:\n if coin <= remAmt:\n result = 1 + helper(remAmt - coin, coins)\n minCoins = min(minCoins, result)\n else:\n break\n mem[remAmt] = minCoins\n return minCoins\n if amount < 1:\n return 0\n mem = {0: 0}\n coins.sort()\n minCoins = helper(amount, coins)\n if minCoins == float('inf'):\n return -1\n return minCoins", "def coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n return self.aux(coins, amount, memo)\n\ndef aux(coins, amount, memo):\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if amount in memo.keys():\n return memo[amount]\n minimum = 999999999\n for x in coins:\n temp = self.aux(coins, amount - x, memo)\n if temp < minimum and temp >= 0:\n minimum = temp\n if minimum == 999999999:\n memo[amount] = -1\n return memo[amount]\n memo[amount] = 1 + minimum\n return memo[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n coins = set(coins)\n d = {}\n if amount == 0:\n return 0\n\n def solve(amt):\n if amt in d:\n return d[amt]\n if amt <= 0:\n return -1\n if amt in coins:\n d[amt] = 1\n return d[amt]\n poss = []\n for c in coins:\n search = amt - c\n if search < 1:\n continue\n val = solve(search)\n if val != -1:\n poss.append(val)\n if len(poss) != 0:\n d[amt] = 1 + min(poss)\n else:\n d[amt] = -1\n return d[amt]\n return solve(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n if amount < 1:\n return 0\n self.cache = [0] * (amount + 1)\n return self.coin_change(coins, amount)\n\ndef coin_change(coins, remainder):\n if remainder < 0:\n return -1\n if remainder == 0:\n return 0\n if self.cache[remainder] != 0:\n return self.cache[remainder]\n system_max = sys.maxsize\n minimum = system_max\n for coin in coins:\n change_result = self.coin_change(coins, remainder - coin)\n if change_result >= 0 and change_result < minimum:\n minimum = 1 + change_result\n self.cache[remainder] = -1 if minimum == system_max else minimum\n return self.cache[remainder]", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n return self.dfs(coins, 0, 0, amount, -1)\n\ndef dfs(coins: List[int], idx: int, cnt: int, amount: int, minCnt: int) -> int:\n if amount == 0:\n return cnt\n if idx >= len(coins):\n return -1\n if minCnt > 0 and cnt + amount // coins[idx] + 1 > minCnt:\n return -1\n for i in range(amount // coins[idx], -1, -1):\n res = self.dfs(coins, idx + 1, cnt + i, amount - coins[idx] * i, minCnt)\n if res != -1:\n minCnt = res if minCnt == -1 else min(minCnt, res)\n return minCnt", "def coinchange(coins: List[int], amount: int) -> int:\n count = {}\n for coin in coins:\n count[coin] = 1\n count[0] = 0\n for i in range(1, amount + 1):\n ans = amount + 1\n if i in list(count.keys()):\n continue\n for coin in coins:\n if i - coin > 0 and count[i - coin] != -1:\n ans = min(count[i - coin], ans)\n if ans == amount + 1:\n count[i] = -1\n else:\n count[i] = ans + 1\n return count[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount < 1:\n return 0\n cnt = [0 for __ in range(amount)]\n return self.coinMake(coins, amount, cnt)\n\ndef coinMake(coins, rem, count):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if count[rem - 1] != 0:\n return count[rem - 1]\n MIN = 2 ** 32 - 1\n for i in coins:\n res = self.coinMake(coins, rem - i, count)\n if res >= 0 and res < MIN:\n MIN = 1 + res\n count[rem - 1] = -1 if MIN == 2 ** 32 - 1 else MIN\n return count[rem - 1]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n mem = {}\n max_amount = 10 ** 4 + 1\n\n def cc(amount):\n mem[amount] = max_amount\n for coin in coins:\n dif = amount - coin\n if dif == 0:\n mem[amount] = 1\n elif dif > 0:\n if dif not in mem:\n cc(dif)\n mem[amount] = min(mem[amount], mem[dif] + 1)\n cc(amount)\n if mem[amount] == max_amount:\n return -1\n else:\n return mem[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0 or not coins:\n return 0\n minlst = [float('inf')] * (amount + 1)\n n = len(minlst)\n minlst[0] = 0\n for i in range(1, n):\n for denom in coins:\n remainder = i - denom\n if remainder < 0:\n continue\n newsmallest = min(minlst[remainder] + 1, minlst[i])\n minlst[i] = newsmallest\n return -1 if minlst[-1] == float('inf') else minlst[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n s = list()\n s.append(0)\n for i in range(1, amount + 1):\n m = list()\n for j in range(0, len(coins)):\n if i - coins[j] >= 0:\n m.append(s[i - coins[j]])\n mm = [item for item in m if item >= 0]\n if len(mm) == 0:\n s.append(-1)\n else:\n s.append(min(mm) + 1)\n return s[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def my_coinchange(coins, rem, count):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if count[rem - 1] != 0:\n return count[rem - 1]\n my_min = float('inf')\n for coin in coins:\n res = my_coinchange(coins, rem - coin, count)\n if res >= 0 and res < my_min:\n my_min = 1 + res\n count[rem - 1] = -1 if my_min == float('inf') else my_min\n return count[rem - 1]\n if amount < 1:\n return 0\n return my_coinchange(coins, amount, [0] * amount)", "def coinchange(coins: List[int], amount: int) -> int:\n if not coins or amount < 0:\n return -1\n f = [sys.maxsize for i in range(amount + 1)]\n f[0] = 0\n for i in range(1, len(f)):\n for coin in coins:\n if i - coin >= 0 and f[i - coin] != sys.maxsize:\n f[i] = min(f[i], f[i - coin] + 1)\n if f[amount] == sys.maxsize:\n return -1\n return f[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [None for _ in range(amount + 2)]\n dp[amount + 1] = float('inf')\n dp[amount] = 0\n for i in range(amount - 1, -1, -1):\n s = float('inf')\n for c in coins:\n s = min(s, 1 + dp[min(c + i, amount + 1)])\n dp[i] = s\n if dp[0] == float('inf'):\n return -1\n return dp[0]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def helper(coins, rem, count):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if count[rem - 1] != 0:\n return count[rem - 1]\n minVal = float('inf')\n for c in coins:\n res = helper(coins, rem - c, count)\n if res >= 0 and res < minVal:\n minVal = 1 + res\n if minVal == float('inf'):\n count[rem - 1] = -1\n else:\n count[rem - 1] = minVal\n return count[rem - 1]\n if amount < 1:\n return 0\n return helper(coins, amount, [0] * amount)", "def coinchange(coins: List[int], amount: int) -> int:\n result = []\n coins.sort(reverse=True)\n max_sum = 2 ** 31 - 1\n\n def find_combinations(combination, remain, start):\n nonlocal max_sum\n if remain == 0:\n max_sum = min(max_sum, len(combination))\n return\n elif remain < 0:\n return\n for i in range(start, len(coins)):\n allowed_coins = max_sum - len(combination)\n max_value_can_be_achieved = coins[i] * allowed_coins\n if coins[i] <= remain < max_value_can_be_achieved:\n combination.append(coins[i])\n find_combinations(combination, remain - coins[i], i)\n combination.pop()\n find_combinations([], amount, 0)\n if max_sum == 2 ** 31 - 1:\n return -1\n return max_sum", "def coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n\n def solve(cur):\n if cur in memo:\n return memo[cur]\n if cur == 0:\n return 0\n arr = [float('inf')] * len(coins)\n for (i, coin) in enumerate(coins):\n if cur - coin < 0:\n arr[i] = float('inf')\n else:\n arr[i] = solve(cur - coin) + 1\n ret = min(arr)\n memo[cur] = ret\n return ret\n ans = solve(amount)\n if ans == float('inf'):\n return -1\n return ans", "def coinchange(coins: List[int], amount: int) -> int:\n N = len(coins)\n M = amount\n table = [-1] * (M + 1)\n for j in range(N + 1):\n table[0] = 0\n for m in range(1, M + 1):\n for i in range(N):\n c = coins[i]\n if c > m:\n pass\n elif table[m - c] != -1:\n if table[m] != -1:\n table[m] = min(table[m - c] + 1, table[m])\n else:\n table[m] = table[m - c] + 1\n return table[M]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def dp(t):\n if t in d:\n return d[t]\n res = float('inf')\n for c in coins:\n if t - c >= 0:\n res = min(res, dp(t - c) + 1)\n d[t] = res\n return res\n d = {0: 0}\n x = dp(amount)\n return x if x < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n\n def dfs(remaining):\n nonlocal memo\n if remaining == 0:\n return 0\n if remaining < 0:\n return -1\n if memo[remaining]:\n return memo[remaining]\n res = amount + 1\n for coin in coins:\n count = dfs(remaining - coin)\n if count == -1:\n continue\n res = min(res, 1 + count)\n memo[remaining] = res if res != amount + 1 else -1\n return memo[remaining]\n memo = [None for _ in range(amount + 1)]\n return dfs(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n dp: List[int] = [0 for _ in range(amount)]\n for i in range(amount):\n for coin in coins:\n if coin > i + 1:\n continue\n if coin == i + 1:\n dp[i] = 1\n elif dp[i - coin] != 0:\n if dp[i] == 0:\n dp[i] = dp[i - coin] + 1\n else:\n dp[i] = min(dp[i], dp[i - coin] + 1)\n return dp[amount - 1] if dp[amount - 1] != 0 else -1", "def coinCount(coins, amount, found):\n if amount < 0:\n return float('inf')\n if amount == 0:\n return 0\n if found.get(amount):\n return found[amount]\n count = 0\n minCount = float('inf')\n for coin in coins:\n if coin == amount:\n return 1\n count = 1 + coinCount(coins, amount - coin, found)\n if count < minCount:\n minCount = count\n found[amount] = minCount\n return minCount\n\ndef coinchange(coins: List[int], amount: int) -> int:\n x = coinCount(coins, amount, {})\n if x == float('inf'):\n return -1\n return x", "def coinchange(coins: List[int], amount: int) -> int:\n\n def opt(v):\n if v == 0:\n return 0\n if v in memo:\n return memo[v]\n result = float('inf')\n for i in coins:\n if v - i >= 0:\n result = min(result, opt(v - i) + 1)\n else:\n continue\n memo[v] = result\n return memo[v]\n memo = {}\n coins = opt(amount)\n if coins == float('inf'):\n return -1\n else:\n return coins", "def coinchange(coins: List[int], amount: int) -> int:\n seen = {0: 0}\n\n def helper(coins, amount):\n if amount in seen:\n return seen[amount]\n if amount < 0:\n return -1\n leastCoins = float('Inf')\n for coin in coins:\n next_least = helper(coins, amount - coin)\n if next_least != -1:\n leastCoins = min(leastCoins, 1 + next_least)\n if leastCoins == float('Inf'):\n seen[amount] = -1\n return -1\n else:\n seen[amount] = leastCoins\n return leastCoins\n return helper(coins, amount)", "def coinchange(coins: List[int], amount: int) -> int:\n coins = sorted(coins)\n memo = {x: amount + 1 for x in range(amount + 1)}\n memo[0] = 0\n for i in range(amount + 1):\n for j in range(len(coins)):\n if coins[j] <= i:\n memo[i] = min(memo[i], 1 + memo[i - coins[j]])\n if memo[amount] < amount + 1:\n return memo[amount]\n else:\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n dp = {}\n for c in coins:\n dp[c] = 1\n for i in range(amount + 1):\n for c in coins:\n if dp.get(i - c):\n if not dp.get(i):\n dp[i] = dp[i - c] + 1\n else:\n dp[i] = min(dp[i], dp[i - c] + 1)\n return dp.get(amount, -1)", "def computeMinCoins(n: int) -> int:\n if (result := self.memoization.get(n)) is not None:\n return result\n if n == 0:\n result = 0\n else:\n result = Solution.IMPOSSIBLE\n for coin in self.coins:\n if coin > n:\n continue\n if (needed_extra := self.computeMinCoins(n - coin)) != Solution.IMPOSSIBLE:\n possible_result = 1 + needed_extra\n if result == Solution.IMPOSSIBLE or result > possible_result:\n result = possible_result\n self.memoization[n] = result\n return result\n\ndef coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n if amount % coins[0] == 0:\n return amount // coins[0]\n self.coins = coins\n self.memoization = {}\n return self.computeMinCoins(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n dp = [None for _ in range(amount + 1)]\n ret = self.helper(coins, amount, dp)\n return ret if ret != float('inf') else -1\n\ndef helper(coins: List[int], amount: int, dp) -> int:\n if amount == 0:\n return 0\n if amount < coins[0]:\n return float('inf')\n ans = float('inf')\n for coin in coins:\n if amount >= coin:\n if amount == coin:\n ans = 0\n else:\n tmp = self.helper(coins, amount - coin, dp) if dp[amount - coin] == None else dp[amount - coin]\n if dp[amount - coin] == None:\n dp[amount - coin] = tmp\n ans = min(ans, tmp)\n return ans + 1 if ans != -1 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n\n def backtrack(tot):\n if tot == 0:\n return 0\n if tot not in memo:\n min_coins = float('inf')\n for coin in coins:\n if coin <= tot:\n cur_count = backtrack(tot - coin) + 1\n min_coins = min(min_coins, cur_count)\n memo[tot] = min_coins\n return memo[tot]\n out = backtrack(amount)\n return -1 if out == float('inf') else out", "def coinchange(coins: List[int], amount: int) -> int:\n memory = {}\n return self._helper(coins, amount, memory)\n\ndef _helper(coins, amount, memory):\n if amount < 0:\n return -1\n elif amount == 0:\n return 0\n elif amount in memory:\n return memory[amount]\n potential_values = []\n for coin in coins:\n new_target = amount - coin\n min_coins = self._helper(coins, new_target, memory)\n if min_coins != -1:\n potential_values.append(min_coins)\n if len(potential_values) == 0:\n memory[amount] = -1\n else:\n memory[amount] = min(potential_values) + 1\n return memory[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n d = {0: 0}\n\n def dfs(left, num):\n if left < 0:\n return -1\n if left in d:\n return d[left]\n min_ans = math.inf\n for each in coins:\n val = dfs(left - each, num + 1)\n if val >= 0:\n min_ans = min(min_ans, val)\n if min_ans == math.inf:\n d[left] = -1\n else:\n d[left] = min_ans + 1\n return d[left]\n return dfs(amount, 0)", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [0] * (amount + 1)\n return self.painful(coins, amount, dp)\n\ndef painful(coins: List[int], amount: int, dp: List[int]) -> int:\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n if dp[amount]:\n return dp[amount]\n minCost = math.inf\n for coin in coins:\n res = self.painful(coins, amount - coin, dp)\n if res != -1:\n minCost = min(minCost, 1 + res)\n dp[amount] = minCost if minCost < math.inf else -1\n return minCost if minCost < math.inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n\n def helper(amount, minAmounts):\n if amount == 0:\n return 0\n elif amount < 0:\n return math.inf\n if amount in minAmounts:\n return minAmounts[amount]\n minAmount = math.inf\n for coin in coins:\n minAmount = min(minAmount, helper(amount - coin, minAmounts) + 1)\n minAmounts[amount] = minAmount\n return minAmount\n minAmounts = dict()\n x = helper(amount, minAmounts)\n if x == math.inf:\n return -1\n return x", "def __init__():\n self.cache = dict()\n self.coin_set = set()\n\ndef helper(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n if amount in self.cache:\n return self.cache[amount]\n if amount in self.coin_set:\n return 1\n potentials = [float('inf')]\n for coin in coins:\n if amount > coin:\n potentials.append(self.helper(coins, amount - coin))\n res = 1 + min(potentials)\n self.cache[amount] = res\n return res\n\ndef coinchange(coins: List[int], amount: int) -> int:\n self.coin_set = set(coins)\n coins = sorted(coins, reverse=True)\n res = self.helper(coins, amount)\n if res == float('inf'):\n return -1\n return res", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n cache = {}\n\n def rec(amount):\n if amount == 0:\n return 0\n if amount in cache:\n return cache[amount]\n val = float('inf')\n for coin in coins:\n if amount - coin >= 0:\n val = min(val, 1 + rec(amount - coin))\n cache[amount] = val\n return val\n ans = rec(amount)\n return ans if ans != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n cache = {0: 0}\n\n def recurse(i):\n if i in cache:\n return cache[i]\n n = i + 1\n for coin in coins:\n curr = 0\n if i >= coin:\n next_amount = recurse(i - coin)\n if next_amount >= 0:\n curr = 1 + next_amount\n if curr > 0:\n n = min(n, curr)\n result = -1 if n == i + 1 else n\n cache[i] = result\n return result\n return recurse(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n\n def helper(coins, amount, dp):\n if amount < 0:\n return float('inf')\n if amount == 0:\n return 0\n if amount in dp:\n return dp[amount]\n ans = []\n for i in range(len(coins)):\n use_ci = 1 + helper(coins, amount - coins[i], dp)\n ans.append(use_ci)\n dp[amount] = min(ans)\n return dp[amount]\n if amount <= 0:\n return 0\n dp = {}\n result = helper(coins, amount, dp)\n return -1 if result == float('inf') else result", "from collections import defaultdict\n\ndef coinchange(coins: List[int], amount: int) -> int:\n\n def coin_change_for_amount(coins, amount):\n nonlocal count_amount\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if count_amount[amount] != float('inf'):\n return count_amount[amount]\n min_coins_amt = float('inf')\n for coin in coins:\n min_coins_amt_coin = coin_change_for_amount(coins, amount - coin)\n if 0 <= min_coins_amt_coin < min_coins_amt:\n min_coins_amt = min_coins_amt_coin + 1\n count_amount[amount] = -1 if min_coins_amt == float('inf') else min_coins_amt\n return count_amount[amount]\n if amount <= 0:\n return 0\n count_amount = [float('inf')] * (amount + 1)\n coin_change_for_amount(coins, amount)\n return count_amount[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n coinsNeeded = {}\n coinsNeeded[0] = 0\n for n in coins:\n coinsNeeded[n] = 1\n\n def findMinCoins(amount):\n if amount < 0:\n return float('inf')\n if amount in coinsNeeded:\n return coinsNeeded[amount]\n for n in coins:\n coinsUsed = 1 + findMinCoins(amount - n)\n if amount in coinsNeeded:\n coinsNeeded[amount] = min(coinsUsed, coinsNeeded[amount])\n else:\n coinsNeeded[amount] = coinsUsed\n return coinsNeeded[amount]\n findMinCoins(amount)\n if coinsNeeded[amount] == float('inf'):\n return -1\n return coinsNeeded[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = {}\n\n def recursion(S):\n if S == 0:\n return 0\n if S < 0:\n return float('inf')\n if S in dp:\n return dp[S]\n x = float('inf')\n for coin in coins:\n x = min(x, 1 + recursion(S - coin))\n dp[S] = x\n return x\n res = recursion(amount)\n if res == float('inf'):\n return -1\n return res", "def coinchange(coins: List[int], amount: int) -> int:\n l = [amount + 1] * (amount + 1)\n for i in range(len(l)):\n if i == 0:\n l[i] = 0\n elif all((i < c for c in coins)):\n l[i] = -1\n else:\n for j in range(len(coins)):\n if i >= coins[j]:\n num = i - coins[j]\n if num > 0 and l[num] == -1:\n if l[i] != amount + 1:\n continue\n else:\n l[i] = -1\n else:\n comb = l[num] + 1\n if l[i] == -1:\n l[i] = amount + 1\n if l[i] >= comb:\n l[i] = comb\n return l[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n coins_sorted = list(sorted(coins, reverse=True))\n memo = {}\n\n def choose(amount):\n if amount in memo:\n return memo[amount]\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n memo[amount] = -1\n for c in coins_sorted:\n if (ret := choose(amount - c)) >= 0:\n if memo[amount] != -1:\n memo[amount] = min(memo[amount], ret + 1)\n else:\n memo[amount] = ret + 1\n return memo[amount]\n return choose(amount)", "def computeMinCoins(n: int) -> int:\n if n in self.memoization:\n return self.memoization.get(n)\n if n == 0:\n result = 0\n else:\n result = Solution.IMPOSSIBLE\n for coin in self.coins:\n if coin > n:\n continue\n coins_extra = self.computeMinCoins(n - coin)\n if coins_extra == Solution.IMPOSSIBLE:\n continue\n plausible_result = 1 + coins_extra\n if result == Solution.IMPOSSIBLE or result > plausible_result:\n result = plausible_result\n self.memoization[n] = result\n return result\n\ndef coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n if amount % coins[0] == 0:\n return amount // coins[0]\n self.coins = coins\n self.memoization = {}\n return self.computeMinCoins(amount)", "import math\nfrom functools import lru_cache\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if not coins or amount < 0:\n return -1\n stack = [(0, 0)]\n answer = math.inf\n sortedCoins = sorted(coins)\n visited = set()\n while stack:\n node = stack.pop()\n (sum, coinCount) = node\n if node in visited:\n pass\n elif coinCount >= answer:\n pass\n elif sum == amount:\n answer = min(answer, coinCount)\n elif sum > amount:\n pass\n else:\n for c in sortedCoins:\n if sum + c <= amount and amount < sum + c * (answer - coinCount):\n stack.append((sum + c, coinCount + 1))\n visited.add(node)\n if answer == math.inf:\n return -1\n else:\n return answer", "def coinchange(coins: List[int], amount: int) -> int:\n cache = dict()\n\n def recursiveChange(amount):\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n if amount in cache:\n return cache[amount]\n min_val = float('inf')\n for coin_val in coins:\n combination = recursiveChange(amount - coin_val)\n if combination != -1:\n min_val = min(min_val, combination + 1)\n cache[amount] = min_val\n return min_val\n ans = recursiveChange(amount)\n if ans == float('inf'):\n return -1\n return ans", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n dp = [None] * amount\n dp[0] = 1 if 1 in coins else -1\n for i in range(1, amount):\n min_req = float('inf')\n for c in coins:\n if (i + 1) % c == 0:\n min_req = min(min_req, (i + 1) // c)\n elif (i + 1) // c > 0 and dp[i - c] != -1:\n min_req = min(min_req, dp[i - c] + 1)\n if min_req == float('inf'):\n dp[i] = -1\n else:\n dp[i] = min_req\n return dp[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount < 1:\n return 0\n self.coins = sorted(coins, reverse=True)\n self.count = {}\n return self.helper(amount)\n\ndef helper(rem):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if rem in self.count:\n return self.count[rem]\n min_count = 1000000000\n for coin in self.coins:\n res = self.helper(rem - coin)\n if res >= 0 and res < min_count:\n min_count = res + 1\n if min_count == 1000000000:\n self.count[rem] = -1\n else:\n self.count[rem] = min_count\n return self.count[rem]", "def coinchange(coins: List[int], amount: int) -> int:\n memo = [0] * (amount + 1)\n return self.dfs(coins, amount, memo)\n\ndef dfs(coins: List[int], amount: int, memo: List[int]) -> int:\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n if memo[amount] != 0:\n return memo[amount]\n minCoins = math.inf\n for coin in coins:\n res = self.dfs(coins, amount - coin, memo) + 1\n if res > 0:\n minCoins = min(minCoins, res)\n memo[amount] = minCoins if minCoins < math.inf else -1\n return minCoins if minCoins < math.inf else -1", "import sys\n\ndef helper(coin_sum, coins, memo):\n if coin_sum == 0:\n return 0\n if coin_sum < 0:\n return sys.maxsize\n if memo[coin_sum - 1] != 0:\n return memo[coin_sum - 1]\n res = sys.maxsize\n for c in coins:\n res = min(res, self.helper(coin_sum - c, coins, memo) + 1)\n memo[coin_sum - 1] = res\n return res\n\ndef coinchange(coins, amount):\n memo = [0] * amount\n res = self.helper(amount, coins, memo)\n return -1 if res == sys.maxsize else res", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [None for _ in range(amount + 1)]\n\n def fewest_num(amount, dp):\n if dp[amount] is not None:\n return dp[amount]\n if amount == 0:\n min_num = 0\n elif amount < min(coins):\n min_num = float('inf')\n elif amount in set(coins):\n min_num = 1\n else:\n min_num = float('inf')\n for coin in coins:\n if amount - coin >= 0:\n num = fewest_num(amount - coin, dp)\n min_num = min(min_num, num)\n min_num += 1\n dp[amount] = min_num\n return min_num\n min_num = fewest_num(amount, dp)\n if min_num == float('inf'):\n return -1\n return min_num", "def coinchange(coins: List[int], amount: int) -> int:\n self.memo = {0: 0}\n coins.sort()\n self.getMinCoins(coins, amount)\n if self.memo[amount] == float('inf'):\n return -1\n return self.memo[amount]\n\ndef getMinCoins(coins, amount):\n if amount in self.memo:\n return self.memo[amount]\n minCoins = float('inf')\n for coin in coins:\n if amount - coin < 0:\n break\n currCoins = self.getMinCoins(coins, amount - coin) + 1\n minCoins = min(minCoins, currCoins)\n self.memo[amount] = minCoins\n return self.memo[amount]", "def helper(amount: int) -> int:\n if amount in list(self.cache.keys()):\n return self.cache[amount]\n counts = []\n for coin in self.coins:\n if amount - coin > 0:\n counts.append(self.helper(amount - coin) + 1)\n elif amount - coin == 0:\n counts.append(1)\n break\n if counts == []:\n self.cache[amount] = sys.maxsize\n else:\n self.cache[amount] = min(counts)\n return self.cache[amount]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n self.coins = coins\n if amount == 0:\n return 0\n self.cache = {}\n res = self.helper(amount)\n return res if res < 100000000 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n d = {}\n ans = self.helper(coins, amount, d)\n if ans == 100000000:\n return -1\n return ans\n\ndef helper(coins, amount, d):\n if amount == 0:\n return 0\n ans = 100000000\n for i in range(len(coins) - 1, -1, -1):\n if coins[i] <= amount:\n if amount - coins[i] in d:\n sub_ans = d[amount - coins[i]]\n else:\n sub_ans = 1 + self.helper(coins, amount - coins[i], d)\n d[amount - coins[i]] = sub_ans\n ans = min(ans, sub_ans)\n return ans", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n coins.sort(reverse=True)\n memo = {}\n\n def dfs(step, rest_amount):\n if rest_amount < 0:\n return -1\n if rest_amount == 0:\n return 0\n if rest_amount in memo:\n return memo[rest_amount]\n min_steps = math.inf\n for coin in coins:\n rest = rest_amount - coin\n res = dfs(step + 1, rest)\n if res >= 0:\n min_steps = min(min_steps, res)\n memo[rest_amount] = min_steps + 1 if min_steps != math.inf else -1\n return memo[rest_amount]\n res = dfs(0, amount)\n return res", "def coinchange2(coins: List[int], amount: int, count) -> int:\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if count[amount - 1] != 0:\n return count[amount - 1]\n min = 100000000000\n for (i, c) in enumerate(sorted(coins)[::-1]):\n ret = self.coinchange2(coins, amount - c, count)\n if ret >= 0 and ret < min:\n min = 1 + ret\n if min == 100000000000:\n count[amount - 1] = -1\n else:\n count[amount - 1] = min\n return count[amount - 1]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount < 1:\n return 0\n return self.coinchange2(coins, amount, [0] * amount)", "def __init__():\n self.mem = {0: 0}\n\ndef getMinCoins(coins, amount):\n if amount in self.mem:\n return self.mem[amount]\n minCoins = float('inf')\n for c in coins:\n if amount - c < 0:\n break\n numCoins = self.getMinCoins(coins, amount - c) + 1\n minCoins = min(numCoins, minCoins)\n self.mem[amount] = minCoins\n return minCoins\n\ndef coinchange(coins, amount):\n minCoins = self.getMinCoins(sorted(coins), amount)\n if minCoins == float('inf'):\n return -1\n return minCoins", "def coinchange(coins: List[int], amount: int) -> int:\n memo = dict()\n\n def recurse(amount, index):\n if amount == 0:\n return 0\n if amount in memo:\n return memo[amount]\n minCoins = float('inf')\n for coin in coins:\n if amount - coin >= 0:\n response = recurse(amount - coin, 0)\n if response != -1:\n minCoins = min(minCoins, response + 1)\n memo[amount] = minCoins if minCoins != float('inf') else -1\n return memo[amount]\n return recurse(amount, 0)", "def coinchange(coins: List[int], amount: int) -> int:\n f = [float('inf') for i in range(amount + 1)]\n f[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n if i - coin >= 0 and f[i - coin] != float('inf'):\n f[i] = min(f[i], f[i - coin] + 1)\n if f[-1] == float('inf'):\n return -1\n return f[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n\n def backtrack(memo, curr=amount):\n if curr == 0:\n return 0\n if memo.get(curr):\n return memo[curr]\n minimum = math.inf\n for coin in coins:\n if curr - coin < 0:\n continue\n res = backtrack(memo, curr - coin)\n minimum = min(res, minimum)\n minimum = minimum if minimum == math.inf else minimum + 1\n memo[curr] = minimum\n return minimum\n ans = backtrack(memo)\n if ans == math.inf:\n return -1\n return ans", "def coinchange(coins: List[int], amount: int) -> int:\n cache = {}\n coins = sorted(coins, reverse=True)\n\n def helper(coins, amount, cache):\n if amount == 0:\n return 0\n elif amount in cache:\n return cache[amount]\n cache[amount] = float('inf')\n for c in coins:\n if amount - c >= 0:\n cache[amount] = min(cache[amount], helper(coins, amount - c, cache) + 1)\n return cache[amount]\n if amount == 0:\n return 0\n if min(coins) > amount:\n return -1\n ans = helper(coins, amount, {})\n return ans if ans != float('inf') else -1", "def helper(coins, amount, total, count, mem):\n if total > amount:\n return\n if total == amount:\n if total not in mem:\n mem[total] = count\n else:\n mem[total] = min(mem[total], count)\n return\n for c in coins:\n if total + c not in mem or mem[total + c] > count + 1:\n mem[total + c] = count + 1\n self.helper(coins, amount, total + c, count + 1, mem)\n return\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n if amount < min(coins):\n return -1\n mem = {}\n coins.sort(reverse=True)\n self.helper(coins, amount, 0, 0, mem)\n if amount in mem:\n return mem[amount]\n else:\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n fewest_coins = [0 for j in range(amount + 1)]\n for j in range(1, amount + 1):\n fewest_coins[j] = float('inf')\n for coin_i in range(len(coins)):\n if coins[coin_i] == j:\n fewest_coins[j] = 1\n break\n elif coins[coin_i] < j:\n if fewest_coins[j - coins[coin_i]] > 0:\n fewest_coins[j] = min(fewest_coins[j], fewest_coins[j - coins[coin_i]] + 1)\n if fewest_coins[j] == float('inf'):\n fewest_coins[j] = -1\n return fewest_coins[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n coins = sorted(coins)\n M = [[0 for j in range(amount + 1)] for i in range(len(coins) + 1)]\n for j in range(1, amount + 1):\n M[0][j] = 1000000\n for i in range(1, len(coins) + 1):\n for j in range(1, amount + 1):\n if j >= coins[i - 1]:\n M[i][j] = min(1 + M[i][j - coins[i - 1]], M[i - 1][j])\n else:\n M[i][j] = M[i - 1][j]\n return M[-1][-1] if M[-1][-1] < 1000000 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n matrix = [[0 for i in range(amount + 1)] for j in range(len(coins) + 1)]\n for i in range(len(matrix)):\n matrix[i][0] = 0\n for i in range(1, amount + 1):\n matrix[0][i] = sys.maxsize\n for i in range(1, len(matrix)):\n for j in range(len(matrix[0])):\n if j < coins[i - 1]:\n matrix[i][j] = matrix[i - 1][j]\n else:\n matrix[i][j] = min(matrix[i - 1][j], 1 + matrix[i][j - coins[i - 1]])\n if matrix[-1][-1] == sys.maxsize:\n return -1\n return matrix[-1][-1]", "def __init__():\n self.counts = {}\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if amount in self.counts:\n return self.counts[amount]\n minCoins = -1\n for val in coins:\n numCoins = self.coinchange(coins, amount - val)\n if numCoins != -1:\n if minCoins == -1:\n minCoins = 1 + numCoins\n else:\n minCoins = min(minCoins, 1 + numCoins)\n self.counts[amount] = minCoins\n return minCoins", "def coinchange2(coins: List[int], amount: int) -> int:\n impossible = amount + 1\n cnts = [impossible] * impossible\n cnts[0] = 0\n for coin in coins:\n for x in range(coin, impossible):\n cnts[x] = min(cnts[x], cnts[x - coin] + 1)\n if cnts[amount] >= impossible:\n return -1\n return cnts[amount]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n impossible = amount + 1\n self.cnts = [0] * impossible\n\n def createCoins(total: int):\n if total == 0:\n return 0\n if self.cnts[total] != 0:\n return self.cnts[total]\n minCnt = impossible\n for coin in coins:\n if total - coin < 0:\n continue\n cnt = createCoins(total - coin) + 1\n minCnt = min(cnt, minCnt)\n self.cnts[total] = minCnt\n return minCnt\n retV = createCoins(amount)\n if retV >= impossible:\n return -1\n return retV", "def coinchange(coin: List[int], amount: int) -> int:\n dp = [[9999999 for _ in range(amount + 1)] for _ in range(len(coin) + 1)]\n for i in range(1, len(coin) + 1):\n dp[i][0] = 0\n for i in range(1, len(coin) + 1):\n for j in range(1, amount + 1):\n if j >= coin[i - 1]:\n dp[i][j] = min(dp[i][j - coin[i - 1]] + 1, dp[i - 1][j])\n else:\n dp[i][j] = dp[i - 1][j]\n if dp[-1][-1] == 9999999:\n return -1\n return dp[-1][-1]", "def coinchangeDynamic(coins: List[int], amount: int, memory_dict: dict) -> int:\n if amount < 0:\n return -1\n elif amount == 0:\n return 0\n elif memory_dict.get(amount) is None:\n recursive_call_output = []\n for coin_val in coins:\n recursive_call_output.append(self.coinchangeDynamic(coins, amount - coin_val, memory_dict))\n min_num_coins = float('inf')\n for num_coins in recursive_call_output:\n if num_coins >= 0 and num_coins < min_num_coins:\n min_num_coins = num_coins\n if min_num_coins == float('inf'):\n memory_dict[amount] = -1\n return -1\n else:\n memory_dict[amount] = min_num_coins + 1\n return min_num_coins + 1\n else:\n return memory_dict[amount]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n return self.coinchangeDynamic(coins, amount, {})", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [[0 for i in range(amount + 1)] for i in range(len(coins))]\n col = amount + 1\n for i in range(len(coins)):\n for j in range(1, col):\n if i == 0:\n r = i\n c = j - coins[i]\n if c < 0 or dp[r][c] == -1:\n dp[i][j] = -1\n else:\n dp[i][j] = dp[r][c] + 1\n else:\n incIndex = j - coins[i]\n if incIndex < 0 or dp[i][incIndex] == -1:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = dp[i][incIndex] + 1\n if dp[i - 1][j] != -1:\n dp[i][j] = min(dp[i - 1][j], dp[i][incIndex] + 1)\n return dp[len(coins) - 1][col - 1]", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if self.trellis == None:\n self.trellis = [math.inf] * (amount + 1)\n self.trellis[0] = 0\n if self.trellis[amount] != math.inf:\n return self.trellis[amount]\n if amount < 0:\n return -1\n minVal = math.inf\n for coin in coins:\n required = amount - coin\n if required < 0:\n continue\n val = self.trellis[required] if self.trellis[required] != math.inf else self.coinchange(coins, required)\n if val == -1:\n continue\n else:\n minVal = min(minVal, val + 1)\n if minVal == math.inf:\n minVal = -1\n self.trellis[amount] = min(self.trellis[amount], minVal)\n return minVal", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n arr = coins\n w = amount\n n = len(arr)\n t = [[0] * (w + 1) for _ in range(n + 1)]\n for i in range(n + 1):\n for j in range(w + 1):\n if j == 0 and i != 0:\n t[i][j] = 0\n if i == 1 and j != 0:\n t[i][j] = int(j / arr[i - 1]) if j % arr[i - 1] == 0 else math.inf\n for i in range(2, n + 1):\n for j in range(1, w + 1):\n if arr[i - 1] <= j:\n t[i][j] = min(t[i][j - arr[i - 1]] + 1, t[i - 1][j])\n else:\n t[i][j] = t[i - 1][j]\n return -1 if t[n][w] == math.inf else t[n][w]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def coinchangeHelper(coins, amount, memoisation={}):\n if amount == 0:\n return 0\n if amount < 0:\n return float('inf')\n if amount in memoisation:\n return memoisation[amount]\n min_coins_used = float('inf')\n for i in range(len(coins) - 1, -1, -1):\n min_coins_used = min(1 + coinchangeHelper(coins, amount - coins[i], memoisation), min_coins_used)\n memoisation[amount] = min_coins_used\n return min_coins_used\n result = coinchangeHelper(coins, amount)\n return result if result != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n\n def dp(m):\n if m in coins:\n return 1\n if m == 0:\n return 0\n if m < 0:\n return float('inf')\n if m not in memo:\n ans = float('inf')\n for v in coins:\n ans = min(1 + dp(m - v), ans)\n memo[m] = ans\n return memo[m]\n return dp(amount) if dp(amount) != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n coinsCount = dict()\n for i in range(1, amount + 1):\n coinsCount[i] = 9999\n coinsCount[0] = 0\n for i in range(1, amount + 1):\n for icoin in range(0, len(coins)):\n curDenom = coins[icoin]\n difference = i - curDenom\n if difference >= 0:\n coinsCount[i] = min(1 + coinsCount[difference], coinsCount[i])\n elif difference == 0:\n coinsCount[i] += 1\n if coinsCount[amount] != 9999:\n return coinsCount[amount]\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n self.dp = {}\n min_ = sys.maxsize\n for coin in coins:\n if amount - coin >= 0:\n min_ = min(min_, 1 + self.change(amount - coin, coins))\n if min_ == sys.maxsize:\n return -1\n return min_\n\ndef change(amount, coins):\n if amount in self.dp:\n return self.dp[amount]\n if amount == 0:\n self.dp[amount] = 0\n return 0\n if amount in coins:\n self.dp[amount] = 1\n return 1\n min_ = sys.maxsize\n for coin in coins:\n if amount - coin >= 0:\n min_ = min(min_, 1 + self.change(amount - coin, coins))\n self.dp[amount] = min_\n return min_", "def coinchange(coins: List[int], amount: int) -> int:\n N = [0 for i in range(amount + 1)]\n N[0] = 0\n for i in range(1, amount + 1):\n temp = [i - j for j in coins]\n history = [N[temp2] for temp2 in temp if temp2 <= i and temp2 >= 0 and (N[temp2] != -1)]\n if len(history) == 0:\n N[i] = -1\n else:\n N[i] = 1 + min([N[temp2] for temp2 in temp if temp2 <= i and temp2 >= 0 and (N[temp2] != -1)])\n return N[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n round = 0\n d = set([0])\n while d or round == 0:\n round += 1\n d = set([coin + s for coin in coins for s in d if coin + s <= amount and coin + s not in d])\n if amount in d:\n return round\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [-1 for i in range(amount + 1)]\n dp[0] = 0\n for i in range(amount):\n mn = math.inf\n pos = False\n for c in coins:\n if i + 1 >= c and dp[i - c + 1] >= 0:\n pos = True\n mn = min(mn, dp[i + 1 - c] + 1)\n if pos:\n dp[i + 1] = mn\n return dp[-1]", "def numCoins(coins, amount):\n if amount in self.memory:\n return self.memory[amount]\n if amount == 0:\n return 0\n ncarr = []\n carr = []\n for c in coins:\n if amount >= c:\n nnc = self.numCoins(coins, amount - c)\n ncarr.append(nnc + 1)\n carr.append(c)\n if len(ncarr) > 0:\n nc = min(ncarr)\n self.memory[amount] = nc\n return nc\n else:\n return float('inf')\n\ndef coinchange(coins: List[int], amount: int) -> int:\n self.memory = {}\n nc = self.numCoins(coins, amount)\n if nc == float('inf'):\n return -1\n return nc", "def coinchange(coins: List[int], amount: int) -> int:\n n = len(coins)\n dp = [[float('inf') for _ in range(amount + 1)] for _ in range(n)]\n for r in range(n):\n dp[r][0] = 0\n for a in range(1, amount + 1):\n (div, mod) = divmod(a, coins[0])\n if mod == 0:\n dp[0][a] = div\n for i in range(1, n):\n for a in range(1, amount + 1):\n if a - coins[i] >= 0:\n dp[i][a] = min(dp[i][a - coins[i]] + 1, dp[i - 1][a])\n else:\n dp[i][a] = dp[i - 1][a]\n return dp[-1][-1] if dp[-1][-1] != float('inf') else -1", "import sys\n\ndef coinchange(coins: List[int], amount: int) -> int:\n res = self.helper(sorted(coins, reverse=True), amount, {})\n if res == float('inf'):\n return -1\n return res\n\ndef helper(coins, amount, dAmounts):\n if amount < 0:\n return float('inf')\n if amount == 0:\n return 0\n if amount in dAmounts:\n return dAmounts[amount]\n for c in coins:\n pathCount = 1 + self.helper(coins, amount - c, dAmounts)\n dAmounts[amount] = min(dAmounts.get(amount, pathCount), pathCount)\n return dAmounts[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('Inf') for _ in range(amount + 1)]\n dp[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n if i >= coin and dp[i - coin] != float('Inf'):\n dp[i] = min(dp[i], dp[i - coin] + 1)\n if dp[amount] == float('Inf'):\n return -1\n return dp[amount]", "INF = 100000000000000000\n\ndef hashIntArr(i_arr):\n return '-'.join(list(map(str, i_arr)))\n\ndef coinchange(coins: List[int], amount: int) -> int:\n coins = sorted(coins)\n mc = [[0 if j == 0 else INF for j in range(amount + 1)] for _ in range(len(coins) + 1)]\n for c in range(1, len(coins) + 1):\n coin_value = coins[c - 1]\n for a in range(1, amount + 1):\n if coin_value <= a:\n mc[c][a] = min(1 + mc[c][a - coin_value], mc[c - 1][a])\n else:\n mc[c][a] = mc[c - 1][a]\n min_coins = mc[len(coins)][amount]\n return min_coins if min_coins < INF else -1", "def coinchange(coins: List[int], amount: int) -> int:\n n = len(coins)\n t = [[float('inf') - 1] * (amount + 1) for _ in range(n + 1)]\n for i in range(n + 1):\n t[i][0] = 0\n for j in range(amount + 1):\n t[0][j] = float('inf') - 1\n if j % coins[0] == 0:\n t[1][j] = j // coins[0]\n else:\n t[1][j] = float('inf') - 1\n for i in range(1, n + 1):\n for j in range(1, amount + 1):\n if coins[i - 1] <= j:\n t[i][j] = min(1 + t[i][j - coins[i - 1]], t[i - 1][j])\n else:\n t[i][j] = t[i - 1][j]\n return t[n][amount] if t[n][amount] != float('inf') else -1", "def __init__():\n self.memo = {}\n\ndef coinchange(coins: List[int], amount: int) -> int:\n ans = self.helper(coins, amount)\n if ans == float('inf'):\n return -1\n return ans\n\ndef helper(coins, remaining):\n if remaining == 0:\n return 0\n if remaining < 0:\n return float('inf')\n if remaining in self.memo:\n return self.memo[remaining]\n self.memo[remaining] = min([self.helper(coins, remaining - i) for i in coins[::-1]]) + 1\n return self.memo[remaining]", "def coinchange(coins: List[int], amount: int) -> int:\n self.coins = coins\n self.amount_dict = {0: 0}\n for coin in coins:\n self.amount_dict[coin] = 1\n return self.coinchangeHelp(amount)\n\ndef coinchangeHelp(amount: int) -> int:\n if amount < 0:\n return -1\n if amount in self.amount_dict:\n return self.amount_dict[amount]\n max_coin = amount + 1\n for coin in self.coins:\n cur_coin = self.coinchangeHelp(amount - coin)\n if cur_coin >= 0:\n max_coin = min(max_coin, cur_coin + 1)\n max_coin = max_coin if max_coin != amount + 1 else -1\n self.amount_dict[amount] = max_coin\n return max_coin", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [0]\n length = len(coins)\n for i in range(1, amount + 1):\n dp += [9999]\n for j in range(length):\n if i >= coins[j] and dp[int(i - coins[j])] != 9999:\n dp[i] = min(dp[i], dp[int(i - coins[j])] + 1)\n if dp[amount] == 9999:\n return -1\n return dp[amount]", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n coins = sorted(coins)\n best_so_far = math.inf\n\n def rec(C, A, used):\n nonlocal best_so_far\n if A == 0:\n best_so_far = min(best_so_far, used)\n elif C:\n for i in range(A // C[-1], -1, -1):\n if (best_so_far - used) * C[-1] >= A:\n rec(C[:-1], A - i * C[-1], used + i)\n rec(coins, amount, 0)\n return best_so_far if best_so_far != math.inf else -1", "import math\nfrom functools import lru_cache\n\ndef coinchange(coins: List[int], amount: int) -> int:\n result = self.recurse(amount, tuple(coins))\n if result == math.inf:\n result = -1\n return result\n\ndef recurse(amount: int, coins: tuple) -> int:\n if amount < 0:\n return math.inf\n elif amount == 0:\n return 0\n elif amount in coins:\n return 1\n else:\n least = math.inf\n for c in coins:\n val = self.recurse(amount - c, coins)\n least = min(least, val)\n return least + 1", "def coinchange(coins: List[int], amount: int) -> int:\n\n def helper(coins, rem, counts):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if counts[rem - 1] != 0:\n return counts[rem - 1]\n min_val = float('inf')\n for coin in coins:\n res = helper(coins, rem - coin, counts)\n if res >= 0 and res < min_val:\n min_val = res + 1\n if min_val == float('inf'):\n counts[rem - 1] = -1\n else:\n counts[rem - 1] = min_val\n return counts[rem - 1]\n if amount < 1:\n return 0\n return helper(coins, amount, [0] * amount)", "def coinchange(coins: List[int], target: int) -> int:\n table = [[float('inf') for _ in range(target + 1)] for _ in range(len(coins) + 1)]\n for i in range(len(coins) + 1):\n table[i][0] = 0\n for i in range(1, len(coins) + 1):\n for j in range(target + 1):\n if coins[i - 1] <= j:\n a = 1 + table[i][j - coins[i - 1]]\n else:\n a = float('inf')\n b = table[i - 1][j]\n if a <= b:\n table[i][j] = a\n else:\n table[i][j] = b\n return table[-1][-1] if table[-1][-1] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n self.cache = {}\n return self.solve(coins, amount)\n\ndef solve(coins, amount):\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n if amount in self.cache:\n return self.cache[amount]\n best = -1\n for c in coins:\n add = self.solve(coins, amount - c)\n if add != -1:\n if best == -1:\n best = add + 1\n else:\n best = min(best, add + 1)\n self.cache[amount] = best\n return best", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n d = {}\n for v in coins:\n d[v] = True\n min_coin = coins[-1]\n if not coins or not amount:\n return 0\n if len(coins) == 1:\n if amount % coins[0] == 0:\n return int(amount / coins[0])\n else:\n return -1\n self.memo = {}\n return self.fewest(coins, amount, d, min_coin)\n\ndef fewest(coins, amount, d_value, min_coin):\n if amount in self.memo:\n return self.memo[amount]\n if amount in d_value:\n return 1\n elif amount < min_coin:\n return -1\n _min = float('inf')\n for v in coins:\n ret = self.fewest(coins, amount - v, d_value, min_coin)\n if ret > 0:\n _min = min(_min, ret + 1)\n _min = -1 if _min == float('inf') else _min\n self.memo[amount] = _min\n return _min", "def coinchange(coins, amount):\n n = len(coins)\n dp = [[math.inf for _ in range(amount + 1)] for _ in range(n)]\n for (i, coin) in enumerate(coins):\n for t in range(amount + 1):\n if t == 0:\n dp[i][t] = 0\n if i > 0:\n dp[i][t] = dp[i - 1][t]\n if t >= coin:\n dp[i][t] = min(dp[i][t], dp[i][t - coin] + 1)\n return -1 if dp[n - 1][amount] == math.inf else dp[n - 1][amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp_table = [float('inf')] * (amount + 1)\n return self.dp(dp_table, coins, amount)\n\ndef dp(dp_table: [float], coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n if dp_table[amount] != float('inf'):\n return dp_table[amount]\n res = float('inf')\n for coin in coins:\n subpb = self.dp(dp_table, coins, amount - coin)\n if subpb == -1:\n continue\n res = min(res, subpb + 1)\n dp_table[amount] = res if res != float('inf') else -1\n return dp_table[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n state = [float('inf')] * amount\n if amount < 1:\n return 0\n max_coin = 0\n for c in coins:\n max_coin = max(c, max_coin)\n if c <= amount:\n state[c - 1] = 1\n for i in range(amount):\n for c in coins:\n if i - c >= 0:\n state[i] = min(state[i - c] + 1, state[i])\n return state[-1] if state[-1] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n dp = [0] * (amount + 1)\n for item in range(amount + 1):\n if item < coins[0] and item != 0:\n dp[item] = -1\n elif item == 0:\n dp[item] = 0\n if amount < coins[0] and amount == 0:\n return 0\n elif amount < coins[0]:\n return -1\n for i in range(coins[0], amount + 1):\n count = 0\n for j in coins:\n if i - j < 0:\n break\n elif dp[i - j] != -1:\n count += 1\n if count > 0:\n dp[i] = math.ceil(i / coins[0])\n for j in coins:\n if i - j < 0:\n break\n elif dp[i - j] == -1:\n continue\n else:\n dp[i] = min(dp[i], 1 + dp[i - j])\n else:\n dp[i] = -1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount < 1:\n return 0\n self.coins = coins\n self.count = {}\n self.recur_count = 0\n ans = self.helper(amount)\n return ans\n\ndef helper(rem):\n self.recur_count += 1\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if rem in self.count:\n return self.count[rem]\n min_count = 1000000000\n for coin in self.coins:\n res = self.helper(rem - coin)\n if res >= 0 and res < min_count:\n min_count = res + 1\n if min_count == 1000000000:\n self.count[rem] = -1\n else:\n self.count[rem] = min_count\n return self.count[rem]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [-1] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n for coin in coins[::-1]:\n j = i - coin\n if j < 0 or dp[j] == -1:\n continue\n if dp[i] == -1:\n dp[i] = dp[j] + 1\n else:\n dp[i] = min(dp[i], dp[j] + 1)\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n memo = dict()\n\n def dp(n):\n if n in memo:\n return memo[n]\n if n == 0:\n return 0\n if n < 0:\n return -1\n res = 1000\n for coin in coins:\n if dp(n - coin) == -1:\n continue\n res = min(res, 1 + dp(n - coin))\n memo[n] = res if res != 1000 else -1\n return memo[n]\n return dp(amount)", "def numCoins(coins, amount):\n if amount in self.memory:\n return self.memory[amount]\n nc = float('inf')\n for c in coins:\n if amount >= c:\n nnc = self.numCoins(coins, amount - c)\n nc = min(nc, nnc + 1)\n self.memory[amount] = nc\n return nc\n\ndef coinchange(coins: List[int], amount: int) -> int:\n self.memory = {}\n self.memory[0] = 0\n for c in coins:\n self.memory[c] = 1\n nc = self.numCoins(coins, amount)\n if nc == float('inf'):\n return -1\n return nc", "def coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n\n def dfs(amount, path):\n if amount < 0:\n return float('inf')\n if amount == 0:\n return 0\n if amount in memo:\n return memo[amount]\n ans = float('inf')\n for i in coins:\n r = dfs(amount - i, path + 1)\n if r != float('inf'):\n ans = min(ans, r + 1)\n memo[amount] = ans\n return ans\n ret = dfs(amount, 0)\n return ret if ret != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n\n def dfs(amt, idx):\n if idx < 0:\n if amt == 0:\n return 0\n else:\n return float('inf')\n if amt < 0:\n return float('inf')\n if amt == coins[idx]:\n return 1\n return min(dfs(amt - coins[idx], idx) + 1, dfs(amt, idx - 1))\n res = dfs(amount, len(coins) - 1)\n return res if res < float('inf') else -1", "def do_du_tab(coins, amount):\n dp_tab = [math.inf for _ in range(amount + 1)]\n dp_tab[0] = 0\n for i in range(len(coins)):\n for a in range(1, amount + 1):\n if a >= coins[i]:\n dp_tab[a] = min(dp_tab[a], 1 + dp_tab[a - coins[i]])\n return dp_tab[amount]\n\ndef do_td_mem(cache, coins, amount, index):\n if amount == 0:\n return 0\n if len(coins) <= index:\n return math.inf\n if cache[index][amount] == math.inf:\n count_keeping_element = math.inf\n if coins[index] <= amount:\n temp = self.do_td_mem(cache, coins, amount - coins[index], index)\n if temp != math.inf:\n count_keeping_element = temp + 1\n count_skipping_element = self.do_td_mem(cache, coins, amount, index + 1)\n cache[index][amount] = min(count_keeping_element, count_skipping_element)\n return cache[index][amount]\n\ndef do_bf(coins, amount, index):\n if amount == 0:\n return 0\n n = len(coins)\n if n <= index:\n return math.inf\n count_keeping_element = math.inf\n if coins[index] <= amount:\n temp = self.do_bf(coins, amount - coins[index], index)\n if temp != math.inf:\n count_keeping_element = temp + 1\n count_skipping_element = self.do_bf(coins, amount, index + 1)\n return min(count_keeping_element, count_skipping_element)\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount < 1:\n return 0\n coins.sort()\n output = self.do_du_tab(coins, amount)\n return -1 if output == math.inf else output", "import math\n\ndef helper(amount, coins, records):\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n if records[amount - 1] != -2:\n min_number = records[amount - 1]\n else:\n min_number = math.inf\n for c in coins:\n val = helper(amount - c, coins, records)\n if val != -1:\n val += 1\n min_number = min(val, min_number)\n if min_number == math.inf:\n records[amount - 1] = -1\n return -1\n else:\n records[amount - 1] = min_number\n return min_number\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n records = [-2] * amount\n return helper(amount, coins, records)", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [[float('inf')] * (amount + 1) for _ in range(len(coins))]\n for r in range(len(coins)):\n dp[r][0] = 0\n for r in range(len(coins)):\n for c in range(1, amount + 1):\n take = leave = float('inf')\n if c - coins[r] >= 0:\n take = dp[r][c - coins[r]] + 1\n if r > 0:\n leave = dp[r - 1][c]\n dp[r][c] = min(leave, take)\n return dp[-1][-1] if dp[-1][-1] != float('inf') else -1", "def coinchange(coins: List[int], a: int) -> int:\n l = len(coins)\n mem = []\n for i in range(l + 1):\n mem.append([0] * (a + 1))\n for j in range(a + 1):\n if i == 0:\n mem[i][j] = float('inf')\n if j == 0:\n mem[i][j] = 0\n if i > 0 and j > 0:\n if coins[i - 1] <= j:\n mem[i][j] = min(1 + mem[i][j - coins[i - 1]], mem[i - 1][j])\n else:\n mem[i][j] = mem[i - 1][j]\n if mem[l][a] == float('inf'):\n return -1\n return mem[l][a]", "def coinchange(coins: List[int], amount: int) -> int:\n n = len(coins)\n dp = [[0 for j in range(amount + 1)] for i in range(n)]\n for j in range(amount + 1):\n dp[0][j] = -1 if j % coins[0] else j // coins[0]\n for i in range(1, n):\n for j in range(1, amount + 1):\n includeDenom = -1 if coins[i] > j else dp[i][j - coins[i]]\n excludeDenom = dp[i - 1][j]\n if includeDenom == -1 and excludeDenom == -1:\n dp[i][j] = -1\n elif includeDenom == -1:\n dp[i][j] = excludeDenom\n elif excludeDenom == -1:\n dp[i][j] = includeDenom + 1\n else:\n dp[i][j] = min(includeDenom + 1, excludeDenom)\n return dp[n - 1][amount]", "def coinchange(coins: List[int], amount: int) -> int:\n memo = [[float('inf') for _ in range(amount + 1)] for _ in range(len(coins))]\n for x in range(len(coins)):\n memo[x][0] = 0\n for (i, coin) in enumerate(coins):\n for tot in range(1, amount + 1):\n if i > 0:\n memo[i][tot] = memo[i - 1][tot]\n if coin <= tot:\n memo[i][tot] = min(memo[i][tot], memo[i][tot - coin] + 1)\n out = memo[len(coins) - 1][amount]\n return -1 if out == float('inf') else out", "def coinchange(coins: List[int], amount: int) -> int:\n coins = set(coins)\n dp = [float('inf') if i not in coins else 1 for i in range(amount + 1)]\n result = self.helper(coins, amount, dp)\n return -1 if result == float('inf') else result\n\ndef helper(coins, amount, dp):\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if dp[amount] != float('inf'):\n return dp[amount]\n current_min = float('inf')\n for coin in coins:\n result = self.helper(coins, amount - coin, dp)\n if result != -1:\n current_min = min(current_min, 1 + result)\n if current_min == float('inf'):\n dp[amount] = -1\n return -1\n dp[amount] = current_min\n return current_min", "def coinchange(coins: List[int], amount: int) -> int:\n self.amount = amount\n self.coins = coins\n n = len(coins)\n self.memo = [-1] * (self.amount + 1)\n val = self.coindp(amount)\n if val == float('inf'):\n return -1\n else:\n return val\n\ndef coindp(i):\n if i < 0:\n return float('inf')\n if i == 0:\n return 0\n if self.memo[i] >= 0:\n return self.memo[i]\n mini = float('inf')\n for coin in self.coins:\n mini = min(mini, self.coindp(i - coin) + 1)\n self.memo[i] = mini\n return self.memo[i]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def dfs(start, amount, n_coins):\n coin = coins[start]\n div = amount // coin\n amount %= coin\n n_coins += div\n if amount == 0:\n self.minimum = min(n_coins, self.minimum)\n return\n if start < length:\n dfs(start + 1, amount, n_coins)\n next_coin = coins[start + 1]\n for _ in range(div):\n amount += coin\n n_coins -= 1\n if (self.minimum - n_coins - 1) * next_coin + 1 > amount:\n dfs(start + 1, amount, n_coins)\n else:\n break\n coins.sort(reverse=True)\n self.minimum = float('inf')\n length = len(coins) - 1\n dfs(0, amount, 0)\n return self.minimum if self.minimum < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n coins.sort(reverse=True)\n res = amount // coins[-1] + 1\n\n def comb(cursum, num, index):\n nonlocal res\n if (amount - cursum) / coins[index] >= res - num:\n return\n for i in range(index, len(coins)):\n newsum = cursum + coins[i]\n if newsum == amount:\n res = min(num + 1, res)\n return\n elif newsum < amount:\n comb(newsum, num + 1, i)\n comb(0, 0, 0)\n if res == amount // coins[-1] + 1:\n return -1\n return res", "def coinchange(coin: List[int], sum1: int) -> int:\n maxv = float('inf') - 1\n n = len(coin)\n t = [[0 for j in range(sum1 + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n for j in range(sum1 + 1):\n if i == 0 and j == 0:\n t[i][j] = maxv\n elif j == 0:\n t[i][j] = 0\n elif i == 0:\n t[i][j] = maxv\n for i in range(1, n + 1):\n for j in range(1, sum1 + 1):\n if coin[i - 1] <= j:\n t[i][j] = min(t[i][j - coin[i - 1]] + 1, t[i - 1][j])\n else:\n t[i][j] = t[i - 1][j]\n if t[n][sum1] == float('inf'):\n return -1\n return t[n][sum1]", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if not coins:\n return -1\n if amount == 0:\n return 0\n memo = [0] * amount\n\n def findNumCoins(remainingAmount: int) -> int:\n nonlocal memo\n if remainingAmount < 0:\n return -1\n if remainingAmount == 0:\n return 0\n memo_idx = remainingAmount - 1\n if memo[memo_idx] != 0:\n return memo[memo_idx]\n local_min = math.inf\n for coin in coins:\n res = findNumCoins(remainingAmount - coin)\n if res >= 0:\n local_min = min(local_min, 1 + res)\n num_coins = -1 if local_min == math.inf else local_min\n memo[memo_idx] = num_coins\n return num_coins\n return findNumCoins(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [0] * (amount + 1)\n for i in range(1, amount + 1):\n minn = float('inf')\n for j in coins:\n if i == j:\n minn = min(minn, 1)\n continue\n if i - j > 0:\n minn = min(minn, 1 + dp[i - j])\n dp[i] = minn\n return dp[amount] if dp[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n self.count = [float('inf')] * (amount + 1)\n self.count[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n rest = i - coin\n if rest >= 0 and self.count[rest] != float('inf'):\n self.count[i] = min(1 + self.count[rest], self.count[i])\n if self.count[-1] == float('inf'):\n return -1\n else:\n return self.count[-1]", "from functools import lru_cache\n\ndef coinchange(coins: List[int], amount: int) -> int:\n dict_ = set(coins)\n count = [0] * amount\n\n def top_down(rem):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if count[rem - 1] != 0:\n return count[rem - 1]\n min_ = float('inf')\n for coin in dict_:\n res = top_down(rem - coin)\n if res >= 0:\n min_ = min(1 + res, min_)\n count[rem - 1] = -1 if min_ == float('inf') else min_\n return count[rem - 1]\n\n def bottom_up():\n dpa = [float('inf')] * (amount + 1)\n dpa[0] = 0\n for i in range(1, len(dpa)):\n for coin in dict_:\n if i >= coin:\n remainder = i - coin\n dpa[i] = min(dpa[remainder] + 1, dpa[i])\n return dpa[amount] if dpa[amount] != float('inf') else -1\n return bottom_up()", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n coins.sort()\n self.coins = coins\n self.memo = {}\n self.recursion(amount)\n return -1 if self.memo[amount] == float('inf') else self.memo[amount]\n\ndef recursion(amt):\n min_coins = float('inf')\n if amt == 0:\n return 0\n if amt in self.memo:\n return self.memo[amt]\n for coin in self.coins:\n if coin > amt:\n break\n x = self.recursion(amt - coin)\n min_coins = min(min_coins, x)\n self.memo[amt] = 1 + min_coins\n return self.memo[amt]", "def coinchange(coins: List[int], amount: int) -> int:\n N = len(coins)\n mem = [[None for i in range(amount + 1)] for j in range(N + 1)]\n\n def helper(target, i):\n if mem[i][target] != None:\n return mem[i][target]\n if target == 0:\n return 0\n if i == N and target > 0:\n return float('inf')\n if coins[i] > target:\n mem[i][target] = helper(target, i + 1)\n else:\n include = 1 + helper(target - coins[i], i)\n exclude = helper(target, i + 1)\n mem[i][target] = min(include, exclude)\n return mem[i][target]\n ans = helper(amount, 0)\n return ans if ans != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n count = collections.defaultdict(int)\n\n def coinchangeHelper(coins, rem, count):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if count[rem] != 0:\n return count[rem]\n minCount = 2 ** 32\n for coin in coins:\n makeChange = coinchangeHelper(coins, rem - coin, count)\n if makeChange > -1 and makeChange < minCount:\n minCount = makeChange + 1\n count[rem] = -1 if minCount == 2 ** 32 else minCount\n return count[rem]\n return coinchangeHelper(coins, amount, count)", "def coinchange(coins, amount):\n coins.sort()\n stack = [(0, 0, len(coins))]\n min_steps = 2 ** 31\n while len(stack) != 0:\n (steps, accumulated, sequence) = stack.pop()\n if accumulated == amount:\n min_steps = min(min_steps, steps)\n if accumulated > amount or amount - accumulated > coins[sequence - 1] * (min_steps - steps):\n continue\n for (seq, coin) in enumerate(coins[:sequence]):\n stack.append((steps + 1, accumulated + coin, seq + 1))\n return min_steps if min_steps != 2 ** 31 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [math.inf] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n for c in coins:\n if i - c >= 0:\n dp[i] = min(dp[i], dp[i - c] + 1)\n return dp[amount] if dp[amount] != math.inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [[math.inf for _ in range(amount + 1)] for _ in coins]\n for i in range(len(coins)):\n dp[i][0] = 0\n for i in range(1, amount + 1):\n if coins[0] <= i:\n dp[0][i] = 1 + dp[0][i - coins[0]]\n for i in range(1, len(coins)):\n for j in range(1, amount + 1):\n (take, leave) = (math.inf, math.inf)\n if coins[i] <= j:\n take = 1 + dp[i][j - coins[i]]\n leave = dp[i - 1][j]\n dp[i][j] = min(take, leave)\n return dp[-1][-1] if dp[-1][-1] != math.inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n if len(coins) == 0:\n return 0\n coins = sorted(coins, reverse=True)\n memo = {}\n\n def coinchangeRec(index, amount):\n if amount == 0:\n return 0\n if amount < 0 or index == len(coins):\n return math.inf\n if (index, amount) in memo:\n return memo[index, amount]\n withCoin = coinchangeRec(index, amount - coins[index]) + 1\n withoutCoin = coinchangeRec(index + 1, amount)\n memo[index, amount] = min(withCoin, withoutCoin)\n return min(withCoin, withoutCoin)\n minCoins = coinchangeRec(0, amount)\n if minCoins == math.inf:\n return -1\n return minCoins", "def aux(coins, amount, cache):\n if amount in cache:\n return cache[amount]\n res = -1\n for i in range(len(coins)):\n if coins[i] < amount:\n right = cache[amount - coins[i]] if amount - coins[i] in cache else self.aux(coins, amount - coins[i], cache)\n if right != -1 and res == -1:\n res = 1 + right\n elif right != -1 and res != -1:\n res = min(res, 1 + right)\n cache[amount] = res\n return cache[amount]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n cache = dict(list(zip(coins, [1] * len(coins))))\n return self.aux(coins, amount, cache)", "def coinchange(coins: List[int], amount: int) -> int:\n dic = {0: 0}\n\n def change(amount):\n if amount < 0:\n return -1\n if amount in dic:\n return dic[amount]\n res = [change(amount - i) for i in coins if change(amount - i) >= 0]\n if not res:\n dic[amount] = -1\n else:\n dic[amount] = min(res) + 1\n return dic[amount]\n return change(amount)", "def __init__():\n self.table = {}\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if amount in self.table:\n return self.table[amount]\n possible_answers = [self.coinchange(coins, amount - coin) + 1 for coin in coins]\n possible_answers = [ans for ans in possible_answers if ans >= 1]\n if possible_answers:\n ans = min(possible_answers)\n else:\n ans = -1\n self.table[amount] = ans\n return ans", "def coinchange(coins: List[int], amount: int) -> int:\n sz = len(coins) + 1\n dp = [[sys.maxsize] * sz for _ in range(amount + 1)]\n for i in range(sz):\n dp[0][i] = 0\n for a in range(1, amount + 1):\n for i in range(1, sz):\n dp[a][i] = dp[a][i - 1]\n if a - coins[i - 1] >= 0:\n dp[a][i] = min(1 + dp[a - coins[i - 1]][i], dp[a][i])\n return -1 if dp[amount][sz - 1] == sys.maxsize else dp[amount][sz - 1]", "def coinchange(coins: List[int], a: int) -> int:\n if a == 0:\n return 0\n dp = [-1 for i in range(a + 1)]\n dp[0] = 1\n coins.sort()\n for i in range(1, len(coins) + 1):\n for j in range(1, a + 1):\n if coins[i - 1] == j:\n dp[j] = 1\n else:\n c = -1\n if j - coins[i - 1] > 0 and dp[j - coins[i - 1]] != -1:\n c = dp[j - coins[i - 1]] + 1\n d = dp[j]\n if c != -1 and d != -1:\n dp[j] = min(c, d)\n elif c == -1 and d != -1:\n dp[j] = d\n elif c != -1:\n dp[j] = c\n if dp[a] == -1:\n return -1\n else:\n return dp[a]", "def coinchange(coins, amount):\n if amount < 1:\n return 0\n\n def count_change(coins, amount, dic={}):\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if amount in dic:\n return dic[amount]\n minimum = float('inf')\n for i in range(len(coins)):\n current = count_change(coins, amount - coins[i], dic)\n if current >= 0 and current < minimum:\n minimum = 1 + current\n if minimum == float('inf'):\n dic[amount] = -1\n else:\n dic[amount] = minimum\n return dic[amount]\n return count_change(coins, amount, {})", "def __init__():\n self.count = []\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if len(self.count) < amount:\n self.count = [-1] * (amount + 1)\n self.skip = [False] * (amount + 1)\n if amount is 0:\n return 0\n elif amount < 0:\n return -1\n else:\n if self.count[amount] < 0 and (not self.skip[amount]):\n tmp = float('inf')\n for co in coins:\n previous = self.coinchange(coins, amount - co)\n if previous >= 0:\n self.count[amount] = min(previous + 1, tmp)\n tmp = self.count[amount]\n else:\n continue\n self.skip[amount] = True\n return self.count[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n cache = {}\n\n def subproblem(i, t):\n if t == 0:\n return 0\n if (i, t) in cache:\n return cache[i, t]\n val = coins[i]\n if val > t:\n choice_take = math.inf\n elif val == t:\n choice_take = 1\n else:\n choice_take = 1 + subproblem(i, t - val)\n if i == 0:\n choice_leave = math.inf\n else:\n choice_leave = subproblem(i - 1, t)\n optimal = min(choice_take, choice_leave)\n cache[i, t] = optimal\n return optimal\n mincoins = subproblem(len(coins) - 1, amount)\n if mincoins == math.inf:\n return -1\n else:\n return mincoins", "def coinchange(coins: List[int], amount: int) -> int:\n t = [[0 for x in range(amount + 1)] for x in range(len(coins) + 1)]\n for j in range(amount + 1):\n t[0][j] = 1000\n for i in range(1, len(coins) + 1):\n t[i][0] = 0\n for i in range(1, len(coins) + 1):\n for j in range(1, amount + 1):\n if j % coins[i - 1] == 0:\n t[i][j] = j / coins[i - 1]\n else:\n t[i][j] = 1000\n for i in range(1, len(coins) + 1):\n for j in range(1, amount + 1):\n if coins[i - 1] <= j:\n t[i][j] = min(t[i][j - coins[i - 1]] + 1, t[i - 1][j])\n else:\n t[i][j] = t[i - 1][j]\n if t[len(coins)][amount] != 1000:\n return t[len(coins)][amount]\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n self.res = float('inf')\n n = len(coins)\n coins.sort(reverse=True)\n\n def helper(cur, start, cnt, n):\n if cur == amount:\n self.res = min(self.res, cnt)\n if cur > amount:\n return\n for i in range(start, n):\n if cur + coins[i] <= amount and cur + coins[i] * (self.res - cnt) > amount:\n helper(cur + coins[i], i, cnt + 1, n)\n helper(0, 0, 0, n)\n return self.res if self.res < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n n = len(coins)\n d = [[-1] * (amount + 1) for i in range(n + 1)]\n for i in range(amount + 1):\n if i % coins[0] == 0:\n d[1][i] = i // coins[0]\n for i in range(n + 1):\n d[i][0] = 0\n for i in range(2, n + 1):\n for j in range(1, amount + 1):\n if j - coins[i - 1] >= 0:\n if d[i - 1][j] != -1 and d[i][j - coins[i - 1]] != -1:\n d[i][j] = min(d[i - 1][j], d[i][j - coins[i - 1]] + 1)\n elif d[i - 1][j] == -1 and d[i][j - coins[i - 1]] != -1:\n d[i][j] = d[i][j - coins[i - 1]] + 1\n elif d[i - 1][j] != -1 and d[i][j - coins[i - 1]] == -1:\n d[i][j] = d[i - 1][j]\n else:\n d[i][j] = d[i - 1][j]\n else:\n d[i][j] = d[i - 1][j]\n return d[n][amount]", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n n_coins = len(coins)\n least_coin = coins[0]\n max_amount = amount + 1\n mat = [[0 for i in range(amount + 1)] for i in range(n_coins + 1)]\n if amount == 0:\n return 0\n if amount < least_coin:\n return -1\n for i in range(amount + 1):\n if i % least_coin == 0:\n mat[1][i] = i // least_coin\n else:\n mat[1][i] = -1\n for i in range(2, n_coins + 1):\n for j in range(1, amount + 1):\n curr_coin = coins[i - 1]\n if j - curr_coin >= 0:\n if mat[i][j - curr_coin] == -1:\n mat[i][j] = mat[i - 1][j]\n elif mat[i - 1][j] == -1:\n mat[i][j] = 1 + mat[i][j - curr_coin]\n elif mat[i][j - curr_coin] == -1 and mat[i - 1][j] == -1:\n mat[i][j] = -1\n else:\n mat[i][j] = min(1 + mat[i][j - curr_coin], mat[i - 1][j])\n else:\n mat[i][j] = mat[i - 1][j]\n return mat[-1][-1]", "def back_tracking_solution():\n\n def _is_solution(amount_left):\n if amount_left == 0:\n return True\n return False\n\n def _process_solution(num_coins_used, fewest_coins):\n if num_coins_used < fewest_coins[0]:\n fewest_coins[0] = num_coins_used\n\n def _candidate_coins_start_idx(amount_left, coins, current_coin_start_idx):\n for i in range(current_coin_start_idx, len(coins)):\n if amount_left >= coins[i]:\n return i\n return None\n\n def _backtrack(amount_left, num_coins_used, current_fewest_coins, coins, current_coin_start_idx):\n if _is_solution(amount_left):\n _process_solution(num_coins_used, current_fewest_coins)\n else:\n real_coin_start_idx = _candidate_coins_start_idx(amount_left, coins, current_coin_start_idx)\n if real_coin_start_idx is not None:\n for i in range(real_coin_start_idx, len(coins)):\n _backtrack(amount_left - coins[i], num_coins_used + 1, current_fewest_coins, coins, i)\n return _backtrack\n\ndef dynamic_programming_solution():\n\n def _dp_bad(amount, coins):\n sorted_coins = sorted(coins)\n cache = [[float('inf')] * len(coins) for i in range(amount + 1)]\n for denom_idx in range(len(sorted_coins)):\n cache[0][denom_idx] = 0\n for amt in range(amount + 1):\n cache[amt][0] = amt // sorted_coins[0] if amt % sorted_coins[0] == 0 else float('inf')\n for i in range(1, len(cache)):\n for j in range(1, len(sorted_coins)):\n max_num_of_denom = i // sorted_coins[j] + 1\n for k in range(max_num_of_denom):\n cache[i][j] = min(cache[i][j], k + cache[i - k * sorted_coins[j]][j - 1])\n return cache[amount][-1]\n\n def _dp_cache_recursive(amount, coins, cache):\n if amount in cache:\n return cache[amount]\n for c in coins:\n if amount >= c:\n intermediate = 1 + _dp_cache_recursive(amount - c, coins, cache)\n if amount in cache:\n cache[amount] = min(cache[amount], intermediate)\n else:\n cache[amount] = intermediate\n return cache[amount] if amount in cache else float('inf')\n\n def _dp_bottom_up_1(amount, coins):\n sorted_coins = sorted(coins)\n cache = [[float('inf')] * len(coins) for i in range(amount + 1)]\n for denom_idx in range(len(sorted_coins)):\n cache[0][denom_idx] = 0\n for amt in range(1, len(cache)):\n for denom_idx in range(len(sorted_coins)):\n amt_left = amt - sorted_coins[denom_idx]\n if amt_left >= 0:\n cache[amt][denom_idx] = 1 + min(cache[amt_left][0:denom_idx + 1])\n return min(cache[amount])\n return _dp_bottom_up_1\n\ndef coinchange(coins: List[int], amount: int) -> int:\n result = self.dynamic_programming_solution()(amount, coins)\n return -1 if result == float('inf') else result", "import queue\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n q = queue.Queue()\n q.put(amount)\n q.put(None)\n level = 0\n visited = {amount}\n while not q.empty():\n num = q.get()\n if num is None:\n if q.empty():\n break\n q.put(None)\n level += 1\n continue\n for coin in coins:\n if num - coin > 0 and num - coin not in visited:\n q.put(num - coin)\n visited.add(num - coin)\n elif num - coin == 0:\n return level + 1\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n m = Counter(coins)\n\n def recurse(left, count) -> int:\n if left in m:\n return m[left]\n if left == 0:\n m[left] = count\n return count\n smallest = math.inf\n for c in coins:\n if left - c >= 0:\n smallest = min(smallest, recurse(left - c, count + 1))\n m[left] = smallest + 1\n return smallest + 1\n recurse(amount, 0)\n if m[amount] == math.inf:\n return -1\n return m[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n table = [float('inf') for _ in range(amount + 1)]\n i = 0\n table[0] = 0\n for coin in coins:\n if coin <= amount:\n table[coin] = 1\n while i <= amount:\n for coin in coins:\n if i - coin >= 0:\n table[i] = min(table[i - coin] + 1, table[i])\n i += 1\n return table[amount] if table[amount] != float('inf') else -1", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n self.c = set([x for x in coins if x <= amount])\n self.coins = list(self.c)\n self.dic = {}\n if amount == 0:\n return 0\n if amount in self.c:\n return 1\n res = math.inf\n for i in range(len(self.coins)):\n ci = self.dp(amount - self.coins[i])\n if ci > 0:\n res = min(res, ci + 1)\n return res if res != math.inf else -1\n\ndef dp(amount):\n if amount in self.c:\n return 1\n if amount in self.dic:\n return self.dic[amount]\n list2 = [x for x in self.coins if x <= amount]\n if len(list2) == 0:\n return -1\n res = math.inf\n for i in range(len(list2)):\n ci = self.dp(amount - list2[i])\n if ci > 0:\n res = min(res, ci + 1)\n self.dic[amount] = res\n return res", "def helper(coins, amount, cache, current=[]):\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n else:\n if amount in cache:\n return cache[amount]\n currMin = sys.maxsize\n for coin in coins:\n current.append(coin)\n currNum = self.helper(coins, amount - coin, cache, current)\n if currNum != -1:\n if currNum < currMin:\n currMin = currNum + 1\n current.pop()\n cache[amount] = currMin\n return currMin\n\ndef coinchange(coins, amount):\n cache = {}\n val = self.helper(coins, amount, cache)\n memo = [sys.maxsize] * (amount + 1)\n memo[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n newIndex = i - coin\n if newIndex >= 0:\n if memo[newIndex] + 1 < memo[i]:\n memo[i] = memo[newIndex] + 1\n if memo[amount] == sys.maxsize:\n return -1\n else:\n return memo[amount]", "def coinchange(coins: [int], amount: int) -> int:\n self.ans = float('inf')\n self.dict = {}\n coins.sort(reverse=True)\n\n def helper(num, depth):\n if num == 0:\n self.ans = min(self.ans, depth)\n return\n for c in coins:\n res = num - c\n if res >= 0:\n if res in self.dict:\n if self.dict[res] > depth + 1 and depth + 1 < self.ans:\n self.dict[res] = depth + 1\n helper(res, depth + 1)\n else:\n self.dict[res] = depth + 1\n helper(res, depth + 1)\n helper(amount, 0)\n return self.ans if self.ans < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n\n def recurse(amount, pos):\n if pos == len(coins):\n return 10000\n if amount == 0:\n return 0\n if coins[pos] <= amount:\n return min(recurse(amount - coins[pos], pos) + 1, recurse(amount, pos + 1))\n else:\n return recurse(amount, pos + 1)\n count = recurse(amount, 0)\n if count >= 10000:\n return -1\n return count", "def recursion(coins, remain, dic):\n if remain < 0:\n return float('inf')\n if remain == 0:\n return 0\n if remain in dic.keys():\n return dic[remain]\n min_coin = float('inf')\n for coin in coins:\n number_coin = None\n prev_num = self.recursion(coins, remain - coin, dic)\n if prev_num == float('inf'):\n number_coin = prev_num\n else:\n number_coin = prev_num + 1\n min_coin = min(min_coin, number_coin)\n dic[remain] = min_coin\n return min_coin\n\ndef coinchange(coins: List[int], amount: int) -> int:\n remain = amount\n count = 0\n dic = {}\n number = self.recursion(coins, remain, dic)\n if number == float('inf'):\n return -1\n else:\n return number", "def coinchange(coins: List[int], amount: int) -> int:\n dp = {}\n\n def dfs(total):\n if total < 0:\n return float('inf')\n if total == 0:\n return 0\n if total in list(dp.keys()):\n return dp[total]\n for c in coins:\n x = total - c\n if total not in list(dp.keys()):\n dp[total] = dfs(x) + 1\n else:\n dp[total] = min(dp[total], dfs(x) + 1)\n return dp[total]\n ans = dfs(amount)\n if ans < float('inf'):\n return ans\n else:\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n coins.sort()\n table = [[-1 for i in range(amount + 1)] for i in range(len(coins))]\n for i in range(len(coins)):\n for j in range(amount + 1):\n if coins[i] > j and i > 0 and (table[i - 1][j] > 0):\n table[i][j] = table[i - 1][j]\n elif j >= coins[i]:\n x = j - coins[i]\n pre_val = 9999999\n calculated_val = 0\n if i > 0 and table[i - 1][j] > 0:\n pre_val = table[i - 1][j]\n if x > 0:\n if table[i][x] > 0:\n calculated_val = table[i][x]\n table[i][j] = min(1 + calculated_val, pre_val)\n elif i > 0 and pre_val != 9999999:\n table[i][j] = pre_val\n elif x == 0:\n table[i][j] = min(1 + calculated_val, pre_val)\n return table[len(coins) - 1][amount]", "def coinchange(coins: List[int], total: int) -> int:\n dic = {0: 0}\n\n def helper(amount):\n if amount in coins:\n dic[amount] = 1\n elif amount < 0:\n return float('inf')\n elif amount not in dic:\n dic[amount] = min([helper(amount - c) + 1 for c in coins])\n return dic[amount]\n return helper(total) if helper(total) != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not coins:\n return -1\n n = len(coins)\n if amount == 0:\n return 0\n fewest = [[0] * n for k in range(amount + 1)]\n for k in range(n):\n fewest[0][k] = 0\n for p in range(1, amount + 1):\n is_divisible = p % coins[0] == 0\n if is_divisible:\n fewest[p][0] = p // coins[0]\n else:\n fewest[p][0] = -1\n for k in range(1, n):\n for p in range(1, amount + 1):\n if p < coins[k]:\n fewest[p][k] = fewest[p][k - 1]\n elif fewest[p - coins[k]][k] == -1:\n fewest[p][k] = fewest[p][k - 1]\n elif fewest[p][k - 1] == -1:\n fewest[p][k] = fewest[p - coins[k]][k] + 1\n else:\n fewest[p][k] = min(fewest[p - coins[k]][k] + 1, fewest[p][k - 1])\n return fewest[p][n - 1]", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n coins.reverse()\n lookup = {}\n\n def find_combos(total_remain, total_coins):\n if total_remain in lookup:\n if lookup[total_remain] > total_coins:\n lookup[total_remain] = total_coins\n else:\n return\n else:\n lookup[total_remain] = total_coins\n for coin in coins:\n if total_remain - coin < 0:\n continue\n find_combos(total_remain - coin, total_coins + 1)\n find_combos(amount, 0)\n if 0 in lookup:\n return lookup[0]\n else:\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n dp = {i: [] for i in range(1, amount + 1)}\n coins.sort()\n for intermediate_amount in range(1, amount + 1):\n for denom in reversed(coins):\n if intermediate_amount == denom:\n dp[intermediate_amount] = [denom]\n break\n elif denom < intermediate_amount and dp[intermediate_amount - denom] != []:\n if dp[intermediate_amount] == [] or len(dp[intermediate_amount]) > len(dp[intermediate_amount - denom]) + 1:\n dp[intermediate_amount] = dp[intermediate_amount - denom] + [denom]\n return len(dp[amount]) if len(dp[amount]) > 0 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [[float('INF') for i in range(amount + 1)] for j in range(len(coins) + 1)]\n for i in range(len(coins) + 1):\n dp[i][0] = 0\n for i in range(1, len(coins) + 1):\n for j in range(1, amount + 1):\n if j - coins[i - 1] < 0:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = min(dp[i - 1][j], dp[i][j - coins[i - 1]] + 1)\n if dp[len(coins)][amount] == float('INF'):\n return -1\n else:\n return dp[len(coins)][amount]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def coinchangehelper(rem):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if rem in memo:\n return memo[rem]\n count = float('inf')\n for coin in coins:\n sub = coinchangehelper(rem - coin)\n if sub >= 0:\n count = min(count, 1 + sub)\n memo[rem] = count\n return memo[rem]\n memo = {}\n res = coinchangehelper(amount)\n return res if res != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('inf') for _ in range(amount + 1)]\n if amount == 0:\n return 0\n for i in range(0, len(dp)):\n for c in coins:\n if i >= c:\n if i % c == 0:\n dp[i] = min(int(i / c), dp[i])\n elif i - c >= 0 and dp[i - c] != float('inf'):\n dp[i] = min(int(1 + dp[i - c]), dp[i])\n ret_val = dp[amount]\n if ret_val == float('inf'):\n return -1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n self.dp = [float('inf')] * (amount + 1)\n self.dp[0] = 0\n\n def change(a):\n if a < 0:\n return -1\n if a == 0:\n return 0\n if self.dp[a] != float('inf'):\n return self.dp[a]\n for c in coins:\n tmp = change(a - c)\n if tmp != -1:\n self.dp[a] = min(tmp + 1, self.dp[a])\n if self.dp[a] == float('inf'):\n self.dp[a] = -1\n return self.dp[a]\n change(amount)\n return self.dp[amount] if self.dp[amount] != float('inf') else -1", "def coinchange_bottomUp(coins: List[int], amount: int) -> int:\n lookup = {x: amount + 1 for x in range(1, amount + 1)}\n lookup[0] = 0\n for i in range(amount + 1):\n for coin in coins:\n remainder = i - coin\n if remainder < 0:\n continue\n best_min = min(lookup[remainder] + 1, lookup[i])\n lookup[i] = best_min\n if lookup[i] > amount:\n return -1\n else:\n return lookup[i]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n coins.reverse()\n lookup = {}\n\n def find_combos(total_remain, total_coins):\n if total_remain in lookup:\n if lookup[total_remain] > total_coins:\n lookup[total_remain] = total_coins\n else:\n return\n else:\n lookup[total_remain] = total_coins\n for coin in coins:\n if total_remain - coin < 0:\n continue\n find_combos(total_remain - coin, total_coins + 1)\n find_combos(amount, 0)\n return lookup[0] if 0 in lookup else -1", "def coinchange(coins: List[int], amount: int) -> int:\n level = seen = {0}\n number = 0\n while level:\n if amount in seen:\n return number\n level = {pre_amount + coin for pre_amount in level for coin in coins if pre_amount + coin <= amount}\n seen.update(level)\n number += 1\n return -1", "from functools import lru_cache\nfrom math import inf\n\ndef coinchange(coins: List[int], amount: int) -> int:\n\n def cc(i, amount):\n if amount == 0:\n return 0\n elif i < 0 or amount < 0:\n return inf\n else:\n (incl, excl) = (cc(i - 1, amount), cc(i, amount - coins[i]) + 1)\n return min(max(incl, 0), max(excl, 0))\n result = cc(len(coins) - 1, amount)\n return result if result < inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n memo = [[-1 for _ in range(amount + 1)] for _ in coins]\n for i in range(len(coins) - 1, -1, -1):\n for j in range(amount + 1):\n if j == 0:\n memo[i][j] = 0\n continue\n if j - coins[i] >= 0 and memo[i][j - coins[i]] != -1 and (i + 1 < len(coins)) and (memo[i + 1][j] != -1):\n memo[i][j] = min(memo[i][j - coins[i]] + 1, memo[i + 1][j])\n elif j - coins[i] >= 0 and memo[i][j - coins[i]] != -1:\n memo[i][j] = memo[i][j - coins[i]] + 1\n elif i + 1 < len(coins) and memo[i + 1][j] != -1:\n memo[i][j] = memo[i + 1][j]\n return memo[0][amount]", "def __init__():\n self.total_min = 0\n self.change_map = {0: 0}\n\ndef changer(coins_obj, amount_obj):\n if amount_obj == 0:\n self.change_map[amount_obj] = 0\n return 0\n if min(coins_obj) > amount_obj:\n self.change_map[amount_obj] = -1\n return -1\n rev_coins_obj = list(reversed(coins_obj))\n for el in rev_coins_obj:\n if el <= amount_obj:\n if amount_obj - el in self.change_map.keys():\n tmp = self.change_map[amount_obj - el]\n else:\n tmp = Solution.changer(self, coins_obj, amount_obj - el)\n if tmp != -1:\n key = tmp + 1\n if amount_obj not in self.change_map.keys():\n self.change_map[amount_obj] = key\n elif amount_obj in self.change_map.keys():\n if key < self.change_map[amount_obj]:\n self.change_map[amount_obj] = key\n if amount_obj not in self.change_map.keys():\n self.change_map[amount_obj] = -1\n return -1\n elif amount_obj in self.change_map.keys():\n return self.change_map[amount_obj]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n Solution.changer(self, coins, amount)\n if amount not in self.change_map.keys():\n return -1\n return self.change_map[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n start = [0]\n visited = [False] * (amount + 1)\n visited[0] = True\n numCoins = 1\n nextStart = []\n while start:\n for v in start:\n for coin in coins:\n nextVal = v + coin\n if nextVal > amount or visited[nextVal]:\n continue\n elif nextVal == amount:\n return numCoins\n else:\n visited[nextVal] = True\n nextStart.append(nextVal)\n (start, nextStart) = (nextStart, [])\n numCoins += 1\n return -1", "from queue import Queue\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n q = Queue()\n mem = dict()\n q.put((0, 0))\n while not q.empty():\n curr = q.get()\n for c in coins:\n tot = curr[1] + c\n if tot > amount:\n continue\n if tot == amount:\n return curr[0] + 1\n if tot in mem and mem[tot] <= curr[0] + 1:\n continue\n q.put((curr[0] + 1, tot))\n mem[tot] = curr[0] + 1\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n mem = {}\n\n def helper(amt):\n if amt < 0:\n return -1\n elif amt == 0:\n return 0\n elif amt in mem:\n return mem[amt]\n min_coins = float('inf')\n for coin in coins:\n result = helper(amt - coin)\n if result != -1:\n min_coins = min(min_coins, 1 + result)\n mem[amt] = min_coins\n return min_coins\n output = helper(amount)\n return -1 if output == float('inf') else output", "def changeCoin(coins, amount, change):\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if amount in change:\n return change[amount]\n costs = []\n for coin in coins:\n cost = self.changeCoin(coins, amount - coin, change)\n if amount - coin in change:\n change[amount - coin] = min(cost, change[amount - coin])\n else:\n change[amount - coin] = cost\n if cost != -1:\n costs.append(cost)\n if len(costs) == 0:\n return -1\n return 1 + min(costs)\n\ndef coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n coins = [coin for coin in coins if coin <= amount]\n change = {}\n return self.changeCoin(coins, amount, change)", "import numpy as np\n\ndef coinchange(coins: List[int], amount: int) -> int:\n maximum = amount + 1\n dp = np.full(maximum, maximum)\n dp[0] = 0\n for i in range(1, maximum):\n for j in coins:\n if j <= i:\n dp[i] = min(dp[i], dp[i - j] + 1)\n if dp[amount] > amount:\n return -1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n rows = amount + 1\n cols = len(coins) + 1\n cache = [[0 for _ in range(cols)] for _ in range(rows)]\n for row in range(1, rows):\n cache[row][0] = -1\n for row in range(1, rows):\n for col in range(1, cols):\n newAmt = row - coins[col - 1]\n takeValue = cache[newAmt][col] if newAmt >= 0 and newAmt < len(cache) else -1\n takeCoin = 1 + takeValue if takeValue >= 0 else -1\n skipCoin = cache[row][col - 1]\n if skipCoin < 0:\n cache[row][col] = takeCoin\n elif takeCoin < 0:\n cache[row][col] = skipCoin\n else:\n cache[row][col] = min(skipCoin, takeCoin)\n return cache[amount][len(coins)]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n self.dp = [[-1] * (amount + 1) for _ in range(len(coins) + 1)]\n value = self.solve(coins, len(coins), amount)\n return self.dp[-1][-1] if value != float('inf') else -1\n\ndef solve(coins, n, amount):\n if amount == 0:\n self.dp[n][amount] = 0\n return 0\n if n == 0:\n self.dp[n][amount] = float('inf')\n return self.dp[n][amount]\n if self.dp[n][amount] != -1:\n return self.dp[n][amount]\n if coins[n - 1] <= amount:\n self.dp[n][amount] = min(1 + self.solve(coins, n, amount - coins[n - 1]), self.solve(coins, n - 1, amount))\n return self.dp[n][amount]\n else:\n self.dp[n][amount] = self.solve(coins, n - 1, amount)\n return self.dp[n][amount]", "import numpy as np\n\ndef coinchange(coins: List[int], amount: int) -> int:\n dp = np.empty(amount + 1)\n dp.fill(math.inf)\n dp[0] = 0\n coins = sorted(coins)\n for i in range(1, amount + 1):\n for c in coins:\n if c <= i:\n dp[i] = min(dp[i], 1 + dp[i - c])\n else:\n break\n return -1 if dp[-1] == math.inf else int(dp[-1])", "def coinchange(coins: List[int], amount: int) -> int:\n coins = sorted(coins)\n dp = {}\n\n def in_dict(val):\n return val in dp.keys() and dp[val]\n if not amount:\n return 0\n if coins[0] > amount:\n return -1\n for coin in coins:\n dp[coin] = 1\n for i in range(coins[0], min(amount, coins[-1]) + 1):\n if i in dp.keys():\n continue\n available_coins = [coin for coin in coins if coin <= i]\n possible_min_coins = [1 + dp[i - coin] for coin in available_coins if in_dict(i - coin)]\n dp[i] = min(possible_min_coins) if possible_min_coins else 0\n for i in range(coins[-1] + 1, amount + 1):\n possible_min_coins = [1 + dp[i - coin] for coin in coins if in_dict(i - coin)]\n dp[i] = min(possible_min_coins) if possible_min_coins else 0\n return dp[amount] or -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n value1 = [0]\n value2 = []\n nc = 0\n visited = [False] * (amount + 1)\n visited[0] = True\n while value1:\n nc += 1\n for v in value1:\n for coin in coins:\n newval = v + coin\n if newval <= amount:\n if not visited[newval]:\n if newval == amount:\n return nc\n visited[newval] = True\n value2.append(newval)\n (value1, value2) = (value2, [])\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n (res, seen, curr) = (0, set(), {c for c in coins if c <= amount})\n while curr:\n res += 1\n if amount in curr:\n return res\n seen |= curr\n tmp = {n + c for n in curr for c in coins}\n curr = {t for t in tmp if t not in seen and t <= amount}\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n seen = set()\n seen.add(0)\n queue = deque([0])\n count = 0\n while queue:\n if amount in queue:\n return count\n currlen = len(queue)\n for i in range(currlen):\n node = queue.popleft()\n for c in coins:\n if c + node not in seen and c + node <= amount:\n queue.append(c + node)\n seen.add(c + node)\n count += 1\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n q = deque([amount])\n hs = [False] * amount\n count = 0\n while q:\n l = len(q)\n while l:\n n = q.popleft()\n for c in coins:\n x = n - c\n if not x:\n return count + 1\n if x > 0 and (not hs[x]):\n hs[x] = True\n q.append(x)\n l -= 1\n count += 1\n return -1", "import collections\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n queue = collections.deque(coins)\n visited = set()\n count = 1\n while queue:\n for _ in range(len(queue)):\n curr = queue.popleft()\n if curr == amount:\n return count\n for next in coins:\n next += curr\n if next not in visited and next <= amount:\n visited.add(next)\n queue.append(next)\n count += 1\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n from collections import deque\n q = deque()\n visited = set()\n q.append(amount)\n visited.add(amount)\n steps = 0\n while q:\n for _ in range(len(q)):\n poped = q.popleft()\n if poped == 0:\n return steps\n for coin in coins:\n new = poped - coin\n if new not in visited and new >= 0:\n q.append(new)\n visited.add(new)\n steps += 1\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n queue = [[0, 0]]\n visited = {0}\n step = 0\n for (node, step) in queue:\n for coin in coins:\n if node + coin in visited:\n continue\n if node + coin == amount:\n return step + 1\n if node + coin < amount:\n queue.append([node + coin, step + 1])\n visited.add(node + coin)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n q = [0]\n visited = set()\n depth = 0\n while q:\n depth += 1\n level = []\n for curr in q:\n for coin in coins:\n newvalue = curr + coin\n if newvalue == amount:\n return depth\n if newvalue not in visited and newvalue < amount:\n visited.add(newvalue)\n level.append(newvalue)\n q = level\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n que = deque()\n seen = set()\n res = -1\n for coin in coins:\n if coin <= amount:\n que.append(coin)\n seen.add(coin)\n count = 1\n while que:\n prev = len(que)\n while prev > 0:\n cur = que.popleft()\n if cur == amount:\n return count\n for coin in coins:\n newamount = cur + coin\n if newamount not in seen and newamount <= amount:\n que.append(newamount)\n seen.add(newamount)\n prev -= 1\n count += 1\n return res", "def coinchange(coins: List[int], amount: int) -> int:\n seen = level = {0}\n coin_n = 0\n while level:\n if amount in level:\n return coin_n\n level = {val + coin for val in level for coin in coins if val + coin <= amount} - seen\n seen |= level\n coin_n += 1\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n count = 0\n self.maxcount = float('inf')\n self.dfs(coins, count, amount)\n return -1 if self.maxcount == float('inf') else self.maxcount\n\ndef dfs(coins, count, amount):\n if amount == 0:\n self.maxcount = min(self.maxcount, count)\n for i in range(len(coins)):\n if amount >= coins[i] and count + math.ceil(amount / coins[i]) < self.maxcount:\n self.dfs(coins[i:], count + 1, amount - coins[i])", "from collections import deque\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n queue = deque([[0, 0]])\n visited = {0}\n step = 0\n while queue:\n (node, step) = queue.popleft()\n for coin in coins:\n if node + coin in visited:\n continue\n if node + coin == amount:\n return step + 1\n elif node + coin < amount:\n queue.append([node + coin, step + 1])\n visited.add(node + coin)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount < 0 or not coins:\n return -1\n if not amount:\n return 0\n (stack, lvl, visited) = ([0], 0, set())\n while stack:\n new_lvl = []\n lvl += 1\n for i in stack:\n for c in coins:\n new = i + c\n if new == amount:\n return lvl\n if new not in visited:\n visited.add(new)\n new_lvl.append(new)\n if min(new_lvl) > amount:\n return -1\n stack = new_lvl", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n myQueue = [[0, 0]]\n reachedMap = {0}\n for (value, num_coins) in myQueue:\n for coin in coins:\n if coin + value in reachedMap:\n continue\n if coin + value == amount:\n return num_coins + 1\n if coin + value < amount:\n reachedMap.add(value + coin)\n myQueue.append([coin + value, num_coins + 1])\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n if not coins:\n return -1\n memo = {}\n stack = [amount]\n l = 0\n while stack:\n tmp = []\n for remain in stack:\n if remain < 0:\n continue\n for coin in coins:\n nxt = remain - coin\n if nxt == 0:\n return l + 1\n if nxt in memo:\n continue\n else:\n memo[nxt] = 1\n tmp += [nxt]\n stack = tmp\n l += 1\n return -1"], "starter_code": "def coinchange(coins: List[int], amount: int) -> int:\n", "input_output": {"fn_name": "coinChange", "inputs": [[[1, 2, 5], 11]], "outputs": [3]}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Dynamic Programming", "Breadth-First Search"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures", "Graph traversal"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/coin-change/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "coinchange", "task_id": "TACO_lite/406", "example": [[[[1, 2, 5], 11], [[2], 3], [[1], 0], [[1], 1], [[1], 2]], ["3", "-1", "0", "1", "2"]]} +{"requirement": "Consider the prime number `23`. If we sum the square of its digits we get:\n`2^2 + 3^2 = 13`, then for `13: 1^2 + 3^2 = 10`, and finally for `10: 1^2 + 0^2 = 1`. \n\nSimilarly, if we start with prime number `7`, the sequence is: `7->49->97->130->10->1`.\n\nGiven a range, how many primes within that range will eventually end up being `1`? \n\nThe upperbound for the range is `50,000`. A range of `(2,25)` means that: `2 <= n < 25`. \n\nGood luck!\n\nIf you like this Kata, please try:\n\n[Prime reversion](https://www.codewars.com/kata/59b46276afcda204ed000094)\n\n[Domainant primes](https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed)", "solutions": ["def is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n sqrtn = int(n ** 0.5) + 1\n for i in range(5, sqrtn, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\ndef end_one(n):\n while n > 6:\n n = sum(map(lambda x: int(x) * int(x), f'{n}'))\n if n == 1:\n return True\n\ndef solve(a, b):\n return sum((1 for n in range(a, b) if is_prime(n) and end_one(n)))", "def solve(a, b):\n return len([x for x in [7, 13, 19, 23, 31, 79, 97, 103, 109, 139, 167, 193, 239, 263, 293, 313, 331, 367, 379, 383, 397, 409, 487, 563, 617, 653, 673, 683, 709, 739, 761, 863, 881, 907, 937, 1009, 1033, 1039, 1093, 1151, 1277, 1303, 1373, 1427, 1447, 1481, 1487, 1511, 1607, 1663, 1697, 1733, 1847, 1933, 2003, 2039, 2063, 2111, 2221, 2309, 2333, 2339, 2383, 2393, 2417, 2557, 2693, 2741, 2833, 2851, 2903, 2963, 3001, 3019, 3067, 3079, 3083, 3109, 3137, 3209, 3301, 3313, 3319, 3323, 3329, 3331, 3371, 3391, 3463, 3607, 3637, 3643, 3673, 3709, 3779, 3797, 3803, 3823, 3833, 3907, 3923, 3931, 4111, 4127, 4157, 4217, 4271, 4363, 4441, 4447, 4481, 4517, 4663, 4721, 4751, 4817, 4871, 5147, 5227, 5281, 5417, 5471, 5477, 5527, 5569, 5659, 5741, 5821, 5879, 5897, 5987, 6037, 6053, 6073, 6163, 6197, 6203, 6329, 6337, 6343, 6353, 6361, 6367, 6373, 6389, 6637, 6661, 6673, 6701, 6703, 6719, 6733, 6763, 6791, 6803, 6899, 6917, 6971, 6983, 7039, 7127, 7309, 7331, 7451, 7457, 7481, 7541, 7547, 7589, 7603, 7691, 7793, 7841, 7937, 8081, 8147, 8233, 8369, 8521, 8597, 8693, 8699, 8741, 8821, 8929, 8963, 8969, 9001, 9007, 9013, 9103, 9133, 9203, 9323, 9377, 9587, 9623, 9689, 9829, 9857, 10009, 10039, 10067, 10093, 10141, 10151, 10177, 10211, 10247, 10303, 10333, 10337, 10427, 10457, 10487, 10607, 10663, 10733, 10771, 10847, 10903, 11113, 11131, 11149, 11159, 11197, 11243, 11251, 11311, 11423, 11467, 11471, 11483, 11491, 11519, 11681, 11719, 11941, 11971, 12011, 12101, 12143, 12149, 12347, 12413, 12437, 12473, 12491, 12511, 12583, 12671, 12743, 12823, 12841, 12853, 12941, 12959, 13003, 13009, 13033, 13037, 13093, 13177, 13241, 13309, 13339, 13411, 13421, 13457, 13487, 13499, 13577, 13679, 13697, 13757, 13841, 13903, 13933, 13967, 14011, 14057, 14081, 14087, 14207, 14281, 14321, 14327, 14347, 14387, 14407, 14437, 14449, 14461, 14537, 14549, 14551, 14561, 14723, 14753, 14783, 14813, 14821, 14831, 14939, 15101, 15121, 15299, 15377, 15451, 15461, 15473, 15541, 15641, 15679, 15737, 15773, 15787, 15823, 15877, 15887, 16007, 16063, 16097, 16127, 16217, 16363, 16417, 16451, 16603, 16633, 16741, 16759, 16811, 16937, 16993, 17027, 17033, 17107, 17137, 17191, 17207, 17317, 17443, 17483, 17569, 17573, 17609, 17627, 17659, 17669, 17713, 17827, 17911, 18041, 18047, 18143, 18223, 18253, 18341, 18401, 18413, 18523, 18587, 18743, 18757, 18839, 18899, 19141, 19259, 19333, 19421, 19699, 19763, 19889, 19963, 19979, 19997, 20063, 20147, 20177, 20333, 20369, 20393, 20639, 20693, 20717, 20771, 20899, 20903, 20963, 21011, 21101, 21143, 21149, 21283, 21341, 21347, 21407, 21419, 21481, 21491, 21599, 21617, 21767, 21787, 21841, 22129, 22229, 22273, 22291, 22381, 22483, 22549, 22573, 22621, 22651, 22783, 22861, 22921, 23039, 23227, 23369, 23417, 23447, 23581, 23609, 23663, 23741, 23827, 23887, 23893, 23899, 23977, 24071, 24107, 24113, 24137, 24181, 24229, 24317, 24371, 24473, 24683, 24859, 25057, 25111, 25183, 25237, 25261, 25453, 25561, 25621, 25657, 25801, 25849, 25919, 26003, 26171, 26177, 26227, 26251, 26267, 26309, 26339, 26393, 26557, 26627, 26633, 26669, 26711, 26717, 26821, 26903, 27017, 27107, 27143, 27253, 27283, 27299, 27397, 27431, 27611, 27617, 27697, 27701, 27739, 27793, 27817, 27823, 27883, 27967, 28051, 28081, 28099, 28123, 28351, 28387, 28393, 28411, 28463, 28513, 28549, 28621, 28643, 28723, 28771, 28789, 28837, 28879, 28909, 28933, 29033, 29063, 29221, 29297, 29303, 29363, 29383, 29389, 29411, 29633, 29833, 29927, 29983, 30013, 30029, 30091, 30097, 30103, 30109, 30133, 30137, 30139, 30269, 30293, 30313, 30319, 30323, 30367, 30391, 30553, 30637, 30643, 30661, 30689, 30713, 30763, 30803, 30869, 30931, 30977, 31033, 31039, 31177, 31247, 31307, 31393, 31481, 31547, 31663, 31699, 31769, 31771, 31847, 32009, 32069, 32083, 32141, 32257, 32303, 32309, 32369, 32411, 32609, 32693, 32779, 32797, 32803, 32839, 32887, 32983, 33013, 33023, 33029, 33071, 33083, 33091, 33107, 33203, 33289, 33301, 33359, 33391, 33413, 33589, 33629, 33829, 33931, 34127, 34147, 34157, 34211, 34217, 34313, 34471, 34499, 34603, 34721, 34747, 34781, 34871, 34897, 34919, 34949, 35053, 35227, 35281, 35339, 35393, 35569, 35603, 35771, 35839, 35933, 35983, 36007, 36037, 36061, 36067, 36073, 36209, 36263, 36293, 36307, 36343, 36433, 36559, 36607, 36637, 36791, 36809, 36919, 36923, 37013, 37097, 37117, 37171, 37441, 37447, 37489, 37517, 37571, 37619, 37663, 37691, 37907, 38069, 38189, 38239, 38287, 38299, 38303, 38329, 38333, 38593, 38609, 38669, 38749, 38891, 38923, 38953, 39023, 39103, 39133, 39301, 39313, 39419, 39619, 39623, 39671, 39727, 39749, 39761, 39799, 39829, 39847, 39979, 40009, 40087, 40111, 40127, 40471, 40577, 40609, 40751, 40841, 41011, 41047, 41057, 41081, 41113, 41117, 41131, 41183, 41213, 41231, 41281, 41333, 41357, 41381, 41387, 41399, 41507, 41549, 41617, 41641, 41651, 41761, 41801, 41813, 41911, 42017, 42071, 42131, 42181, 42283, 42437, 42473, 42589, 42683, 42701, 42743, 42859, 42863, 43063, 43133, 43271, 43313, 43331, 43427, 43499, 43517, 43633, 43721, 43781, 43789, 43987, 43991, 43997, 44017, 44041, 44071, 44159, 44249, 44273, 44371, 44453, 44491, 44519, 44543, 44633, 44647, 44651, 44699, 44701, 44773, 44789, 44879, 44939, 44959, 44987, 45077, 45137, 45161, 45289, 45317, 45491, 45523, 45553, 45641, 45707, 45853, 45949, 46141, 46171, 46411, 46447, 46451, 46499, 46511, 46663, 46997, 47041, 47051, 47057, 47111, 47123, 47143, 47161, 47351, 47381, 47389, 47407, 47431, 47501, 47507, 47513, 47699, 47743, 47857, 47939, 47969, 48017, 48121, 48131, 48259, 48311, 48371, 48397, 48449, 48479, 48497, 48623, 48731, 48757, 48799, 48947, 48973, 49121, 49139, 49193, 49211, 49391, 49451, 49459, 49549, 49697, 49739, 49783, 49789, 49937, 49943] if x in range(a, b)])", "import math as m\n\ndef IsPrime(a):\n if a == 1:\n return False\n for i in range(2, int(m.sqrt(a) + 1)):\n if a % i == 0:\n return False\n return True\n\ndef algorithm(a):\n while a != 4:\n sum = 0\n for j in str(a):\n sum += int(j) ** 2\n a = sum\n if a == 1:\n return True\n return False\n\ndef solve(a, b):\n counter = 0\n for i in range(a, b):\n if IsPrime(i):\n if algorithm(i):\n counter += 1\n return counter", "def build_solver(limit):\n reducers = [(2, 0), (3, 0), (5, 0)]\n known_failures = {2, 3, 5}\n\n def reduces_to_1(p):\n seq = set()\n n = p\n while n not in seq and n not in known_failures and (n != 1):\n seq.add(n)\n m = n\n t = 0\n while m > 0:\n (m, d) = divmod(m, 10)\n t += d * d\n n = t\n if n != 1:\n known_failures.update(seq)\n return n == 1\n prime_candidate = reducers[-1][0]\n root = int(prime_candidate ** 0.5) + 1\n while prime_candidate < limit:\n prime_candidate += 2\n if root * root < prime_candidate:\n root += 1\n for (p, _) in reducers:\n if prime_candidate % p == 0:\n break\n if p > root:\n reducers.append((prime_candidate, reduces_to_1(prime_candidate)))\n break\n reducers = [p for (p, r) in reducers if r]\n\n def solve(a, b):\n result = 0\n for p in reducers:\n if p < a:\n continue\n if p >= b:\n break\n result += 1\n return result\n return solve\nsolve = build_solver(50000)", "import numpy as np\n\ndef ssloop(n):\n seen = set()\n while n != 1 and n not in seen:\n seen.add(n)\n n = sum((x * x for x in map(int, str(n))))\n return n == 1\ns = np.ones(50001)\ns[:2] = s[4::2] = 0\nfor i in range(3, int(len(s) ** 0.5) + 1, 2):\n if s[i]:\n s[i * i::i] = 0\nxs = [i for (i, x) in enumerate(s) if x and ssloop(i)]\n\ndef solve(a, b):\n return np.searchsorted(xs, b) - np.searchsorted(xs, a)", "N = 10 ** 5\n\ndef sum_square_digits(n):\n return sum(((ord(d) - 48) ** 2 for d in str(n)))\n\ndef reductible(n):\n suite = set()\n while n not in suite:\n suite.add(n)\n n = sum_square_digits(n)\n return n == 1\nmax_digit_sum = 81 * len(str(N))\nsum_reduc = set(filter(reductible, range(max_digit_sum + 1)))\n\ndef primes(n):\n sieve = n // 2 * [True]\n for i in range(3, int(n ** 0.5) + 1, 2):\n if sieve[i // 2]:\n sieve[i * i // 2::i] = [False] * ((n - i * i - 1) // (2 * i) + 1)\n return [2] + [2 * i + 1 for i in range(1, n // 2) if sieve[i]]\nprime_reduc = [n for n in primes(N) if sum_square_digits(n) in sum_reduc]\nfrom bisect import bisect_left\n\ndef solve(a, b):\n return bisect_left(prime_reduc, b) - bisect_left(prime_reduc, a)", "def isprime(n):\n if n < 2:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef solve(a, b):\n count = 0\n for i in range(a, b):\n if isprime(i):\n c = 0\n while i != 1 and c != 10:\n i = sum((int(j) ** 2 for j in list(str(i))))\n c += 1\n if i == 1:\n count += 1\n return count", "N = 50000\n(sieve, reduceable) = ([False, False] + [True] * (N - 1), set())\nfor (i, is_prime) in enumerate(sieve):\n if is_prime:\n (seen, n) = (set(), i)\n while n not in seen:\n seen.add(n)\n n = sum((int(c) ** 2 for c in str(n)))\n if n == 1:\n reduceable.add(i)\n for j in range(i * i, N + 1, i):\n sieve[j] = False\n\ndef solve(a, b):\n return sum((1 for e in reduceable if a <= e < b))"], "starter_code": "def solve(a,b):\n", "input_output": {"fn_name": "solve", "inputs": [[1, 25], [100, 1000], [100, 2000], [100, 3000], [100, 4000]], "outputs": [[4], [28], [47], [65], [95]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/59aa6567485a4d03ff0000ca", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/397", "example": [[[2, 25]], ["7"]]} +{"requirement": "Given a number n, find count of all binary sequences of length 2n such that sum of first n bits is same as sum of last n bits.\nThe anwer can be very large. So, you have to return answer modulo 10^{9}+7.\nExample:\nInput: n = 2\nOutput: 6\nExplanation: There are 6 sequences of length \n2*n, the sequences are 0101, 0110, 1010, 1001, \n0000 and 1111.\nExample:\nInput: n = 1\nOutput: 2\nExplanation: There are 2 sequence of length \n2*n, the sequence are 00 and 11.\n \nYour Task:\nYou don't need to read or print anyhting. Your task is to complete the function compute_value() which takes n as input parameter and returns count of all binary sequence of length 2*n such that sum of first n bits is same as sum of last n bits modulo 10^{9} + 7.\n \nExpected Time Complexity: O(n * log(n))\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= n <= 10^{5}", "solutions": ["import math\n\ndef compute_value(n):\n mod = 10 ** 9 + 7\n a = math.factorial(2 * n)\n b = math.factorial(n)\n return a // b ** 2 % mod", "import math\n\ndef compute_value(n):\n mod = 1000000007\n a = math.factorial(2 * n)\n b = math.factorial(n)\n return a // b ** 2 % mod", "import math\n\ndef compute_value(n):\n t = math.factorial(n)\n return math.factorial(2 * n) // t // t % (10 ** 9 + 7)", "def compute_value(n):\n mod = 10 ** 9 + 7\n if n == 1:\n return 2\n val = 2\n for i in range(1, n):\n val = val * (2 * i + 1) * 2 % mod\n x = pow(i + 1, mod - 2, mod)\n val = val * x % mod\n return val", "import math\n\ndef compute_value(n):\n count1 = math.factorial(2 * n)\n count2 = math.factorial(n)\n count3 = count2 ** 2\n ans = count1 // count3\n return ans % (10 ** 9 + 7)", "import math\n\ndef euclidean(mod, r, x_y_list):\n if r == 0:\n x_y_list[0] = 1\n x_y_list[1] = 0\n return (x_y_list[0], x_y_list[1])\n (x1, y1) = self.euclidean(r, mod % r, x_y_list)\n x_y_list[0] = y1\n x_y_list[1] = x1 - mod // r * y1\n return (x_y_list[0], x_y_list[1])\n\ndef modinverse(mod, r):\n x_y_list = [1, 0]\n (x, y) = self.euclidean(mod, r, x_y_list)\n return y\n\ndef compute_value(n):\n res = 2\n ncr = 1\n for r in range(0, n - 1):\n ncr = ncr % self.mod * (n - r) % self.mod % self.mod\n x = self.modinverse(self.mod, r + 1)\n ncr = ncr % self.mod * x % self.mod % self.mod\n res = (res % self.mod + ncr % self.mod * ncr % self.mod % self.mod % self.mod) % self.mod\n return int(res)", "from math import factorial as f\n\ndef compute_value(n):\n return f(n << 1) // f(n) ** 2 % (10 ** 9 + 7)", "import math\n\ndef modinverse(r):\n m0 = self.mod\n y = 1\n x = 0\n M = m0\n if self.mod == 1:\n return 0\n while M > 1:\n q = M // r\n temp = r\n r = M % r\n M = temp\n temp = y\n y = x - q * y\n x = temp\n if x < 0:\n x += m0\n return x\n\ndef compute_value(n):\n res = 2\n ncr = 1\n for r in range(0, n - 1):\n ncr = ncr % self.mod * (n - r) % self.mod % self.mod\n x = self.modinverse(r + 1)\n ncr = ncr % self.mod * x % self.mod % self.mod\n res = (res % self.mod + ncr % self.mod * ncr % self.mod % self.mod % self.mod) % self.mod\n return int(res)", "import math\n\ndef compute_value(n):\n x = math.factorial(n * 2)\n y = math.factorial(n)\n return x // y ** 2 % 1000000007", "import math\n\ndef verify(x):\n for i in range(2, math.floor(math.sqrt(x))):\n if x % i == 0:\n return False\n return True\nM = 1000 * 1000 * 1000 + 7\n\ndef pow1(x, y):\n if y == 0:\n return 1\n if y % 2 == 0:\n return self.pow(x, y // 2) ** 2 % M\n return self.pow(x, y // 2) ** 2 * x % M\n\ndef pow(x, y):\n val = 1\n while y:\n if y & 1:\n val = val * x % M\n y = y >> 1\n x = x * x % M\n return val\n\ndef compute_value(n):\n cur = 1\n ans = 0\n inverse = []\n for i in range(0, n):\n inverse.append(pow(i, M - 2, M))\n for i in range(1, n):\n cur = cur * (n - i + 1) * inverse[i] % M\n ans += cur * cur % M\n ans = ans % M\n ans += 2\n return ans % M\n\ndef compute_value1(n):\n return math.factorial(2 * n) // math.factorial(n) ** 2 % M", "import math\nmod = 10 ** 9 + 7\n\ndef compute_value(n):\n num = math.factorial(2 * n)\n den = math.factorial(n) ** 2\n return num // den % mod", "import math\n\ndef compute_value(n):\n MOD = 10 ** 9 + 7\n denominator = math.factorial(2 * n)\n numerator = math.factorial(n)\n ans = denominator // numerator ** 2 % MOD\n return ans", "import math\n\ndef ncr(n, r, p):\n num = den = 1\n for i in range(r):\n num = num * (n - i) % p\n den = den * (i + 1) % p\n return num * pow(den, p - 2, p) % p\n\ndef compute_value(n):\n return self.ncr(2 * n, n, 1000000007)", "def compute_value(n):\n ans = 0\n m = 1000000007\n num = 1\n den = 1\n for r in range(0, n + 1):\n val = num % m * pow(den, m - 2, m) % m % m\n ans = (ans % m + val % m * val % m % m) % m\n num = num % m * (n - r) % m % m\n den = den % m * (r + 1) % m % m\n return ans", "import math as m\n\ndef compute_value(n):\n ans = 0\n a = m.factorial(n)\n b = m.factorial(2 * n)\n return b // (a * a) % (10 ** 9 + 7)", "import math\n\ndef compute_value(n):\n a = math.factorial(2 * n)\n b = math.factorial(n)\n return a // b ** 2 % int(1000000000.0 + 7)", "import math\nmod = 10 ** 9 + 7\n\ndef compute_value(n):\n a1 = math.factorial(2 * n)\n a2 = math.factorial(n)\n return a1 // a2 ** 2 % mod", "def compute_value(n):\n k = 1\n for i in range(1, n + 1):\n k = k * (n + i) // i\n k = int(k)\n k = k % (10 ** 9 + 7)\n return k", "import math\n\ndef compute_value(n):\n x = math.factorial(n * 2)\n y = math.factorial(n)\n return int(x // y ** 2 % (10 ** 9 + 7))", "mod = int(1000000000.0 + 7)\nmx = int(300000.0 + 3)\nfact = [1 for n in range(mx)]\nfor n in range(1, mx):\n fact[n] = fact[n - 1] * n % mod\n\ndef bnp(base, pw):\n res = 1\n while pw:\n if pw & 1:\n res = res * base % mod\n pw >>= 1\n base = base * base % mod\n return res\n\ndef ncr(n, r):\n denom = fact[r] * fact[n - r] % mod\n denomInv = bnp(denom, mod - 2)\n res = fact[n] * denomInv\n return res % mod\n\ndef compute_value(x):\n res = ncr(2 * x, x)\n return res", "import math\n\ndef compute_value(n):\n s = 0\n c = math.factorial(2 * n)\n d = math.factorial(n)\n d *= d\n c = c // d\n c = c % 1000000007\n return c", "import math\nmod = 10 ** 9 + 7\n\ndef compute_value(n):\n ans = math.factorial(2 * n)\n ob = math.factorial(n)\n return ans // ob ** 2 % mod", "mod = int(1000000000.0) + 7\n\ndef gcd(a, b):\n if b == 0:\n return (1, 0, a)\n (x, y, r) = gcd(b, a % b)\n (x, y) = (y, x - a // b * y)\n return (x, y, r)\n\ndef nCk(n, k):\n ans = 1\n for i in range(n, n - k, -1):\n ans *= i\n ans %= mod\n for i in range(k):\n (x, _, _) = gcd(i + 1, mod)\n ans *= x % mod\n ans %= mod\n return ans\n\ndef compute_value(n):\n return nCk(n + n, n)"], "starter_code": "def compute_value(n):\n", "input_output": {"inputs": ["n = 2", "n = 1"], "outputs": ["6", "2"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms"], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/count-even-length1907/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n * log(n))", "entry_point": "compute_value", "task_id": "TACO_lite/359", "example": [[[2], [1]], ["6", "2"]]} +{"requirement": "Given a string str of length N, you have to find number of palindromic subsequence (need not necessarily be distinct) present in the string str.\nNote: You have to return the answer module 10^{9}+7;\n \nExample 1:\nInput: \nStr = \"abcd\"\nOutput: \n4\nExplanation:\npalindromic subsequence are : \"a\" ,\"b\", \"c\" ,\"d\"\n \nExample 2:\nInput: \nStr = \"aab\"\nOutput: \n4\nExplanation:\npalindromic subsequence are :\"a\", \"a\", \"b\", \"aa\"\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function countPs() which takes a string str as input parameter and returns the number of palindromic subsequence.\n \nExpected Time Complexity: O(N*N)\nExpected Auxiliary Space: O(N*N)\nConstraints:\n1<=length of string str <=1000", "solutions": ["def countps(s):\n n = len(s)\n dp = [[0] * n for _ in range(n)]\n for i in range(n):\n dp[i][i] = 1\n for length in range(2, n + 1):\n for i in range(n - length, -1, -1):\n j = i + length - 1\n if s[i] == s[j]:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] + 1\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n return dp[0][n - 1] % (10 ** 9 + 7)", "import numpy as np\n\ndef rec_sol(start, end, string):\n if start == end:\n return 1\n if start > end:\n return 0\n if string[start] == string[end]:\n return 1 + self.rec_sol(start, end - 1, string) + self.rec_sol(start + 1, end, string)\n else:\n return self.rec_sol(start, end - 1, string) + self.rec_sol(start + 1, end, string) - self.rec_sol(start + 1, end - 1, string)\n\ndef dp_sol(string):\n len_s = len(string)\n dp = np.array([[0] * len_s] * len_s)\n for i in range(len_s):\n for j in range(i, -1, -1):\n if i == j:\n dp[j][i] = 1\n elif string[i] == string[j]:\n dp[j][i] = (1 + dp[j][i - 1] + dp[j + 1][i]) % 1000000007\n else:\n dp[j][i] = (dp[j][i - 1] + dp[j + 1][i] - dp[j + 1][i - 1]) % 1000000007\n return dp[0][len_s - 1]\n\ndef countps(string):\n return self.dp_sol(string)", "def solve(i, j, s, dp):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n if s[i] == s[j]:\n ans = self.solve(i + 1, j, s, dp) + self.solve(i, j - 1, s, dp) + 1\n else:\n ans = self.solve(i + 1, j, s, dp) + self.solve(i, j - 1, s, dp) - self.solve(i + 1, j - 1, s, dp)\n dp[i][j] = ans\n return ans\n\ndef countps(string):\n n = len(string)\n dp = [[-1 for _ in range(n)] for _ in range(n)]\n ans = self.solve(0, n - 1, string, dp)\n ans = ans % (10 ** 9 + 7)\n return ans", "def countps(s):\n m = 1000000007\n n = len(s)\n dp = [[0] * n for _ in range(n)]\n for i in range(n):\n dp[i][i] = 1\n for cl in range(2, n + 1):\n for i in range(n - cl + 1):\n j = i + cl - 1\n if s[i] == s[j]:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] + 1\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n return dp[0][n - 1] % m", "def countps(string):\n N = len(string)\n dp = [[0 for j in range(N)] for i in range(N)]\n for g in range(0, N):\n i = 0\n j = g\n while j < N:\n if g == 0:\n dp[i][j] = 1\n elif g == 1:\n if string[i] == string[j]:\n dp[i][j] = 3\n else:\n dp[i][j] = 2\n elif string[i] == string[j]:\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] + 1\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n i += 1\n j += 1\n return dp[0][N - 1] % (10 ** 9 + 7)", "def countps1(st, i, j, dp):\n if i > j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n elif st[i] == st[j]:\n dp[i][j] = self.countps1(st, i + 1, j, dp) + self.countps1(st, i, j - 1, dp) + 1\n else:\n dp[i][j] = self.countps1(st, i + 1, j, dp) + self.countps1(st, i, j - 1, dp) - self.countps1(st, i + 1, j - 1, dp)\n return dp[i][j]\n\ndef countps(string):\n n = len(string)\n dp = [[-1 for i in range(n + 1)] for j in range(n + 1)]\n a = self.countps1(string, 0, n - 1, dp)\n return a % 1000000007", "def countps(string):\n MOD = int(1000000000.0) + 7\n n = len(string)\n dp = [[0] * n for _ in range(n)]\n for i in range(n):\n dp[i][i] = 1\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if string[i] == string[j]:\n dp[i][j] = (dp[i + 1][j] + dp[i][j - 1] + 1) % MOD\n else:\n dp[i][j] = (dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]) % MOD\n return dp[0][n - 1]", "def countps(string):\n\n def subs(i, j, strg):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n if strg[i] == strg[j]:\n dp[i][j] = subs(i + 1, j, strg) + subs(i, j - 1, strg) + 1\n else:\n dp[i][j] = subs(i + 1, j, strg) + subs(i, j - 1, strg) - subs(i + 1, j - 1, strg)\n return dp[i][j]\n n = len(string)\n MOD = 10 ** 9 + 7\n dp = [[-1] * n for i in range(n)]\n ans = subs(0, n - 1, string)\n return ans % MOD", "def countps(str):\n N = len(str)\n cps = [[0 for i in range(N + 2)] for j in range(N + 2)]\n for i in range(N):\n cps[i][i] = 1\n for L in range(2, N + 1):\n for i in range(N):\n k = L + i - 1\n if k < N:\n if str[i] == str[k]:\n cps[i][k] = cps[i][k - 1] + cps[i + 1][k] + 1\n else:\n cps[i][k] = cps[i][k - 1] + cps[i + 1][k] - cps[i + 1][k - 1]\n return cps[0][N - 1] % (pow(10, 9) + 7)", "def countps(string):\n if len(string) == 0:\n return 0\n big = 10 ** 9 + 7\n dp = [[-1 for _ in range(len(string))] for __ in range(len(string))]\n return self.num_pal(string, dp, 0, len(string) - 1, big)\n\ndef num_pal(s, arr, start, end, mod):\n if start == end:\n return 1\n if start > end:\n return 0\n if arr[start][end] != -1:\n return arr[start][end]\n if s[start] == s[end]:\n arr[start][end] = 1 + self.num_pal(s, arr, start + 1, end, mod) % mod + self.num_pal(s, arr, start, end - 1, mod) % mod\n arr[start][end] %= mod\n else:\n arr[start][end] = self.num_pal(s, arr, start + 1, end, mod) % mod + self.num_pal(s, arr, start, end - 1, mod) % mod - self.num_pal(s, arr, start + 1, end - 1, mod) % mod\n arr[start][end] %= mod\n return arr[start][end]", "def countps(s):\n dp = [[-1] * len(s) for _ in range(len(s))]\n\n def rec(i, j):\n nonlocal dp, s\n if dp[i][j] != -1:\n return dp[i][j]\n if i == j:\n dp[i][j] = 1\n return dp[i][j]\n if i > j:\n return 0\n if s[i] == s[j]:\n a = rec(i + 1, j) + rec(i, j - 1) + 1\n dp[i][j] = a\n return a\n else:\n a = rec(i + 1, j) + rec(i, j - 1) - rec(i + 1, j - 1)\n dp[i][j] = a\n return a\n return rec(0, len(s) - 1) % (10 ** 9 + 7)", "def countps(s):\n n = len(s)\n dp = {}\n mod = 10 ** 9 + 7\n\n def backtracking(start, end):\n if (start, end) in dp:\n return dp[start, end]\n if start == end:\n dp[start, end] = 1\n return 1\n if start > end:\n dp[start, end] = 0\n return 0\n if s[start] == s[end]:\n dp[start, end] = 1 + backtracking(start + 1, end) + backtracking(start, end - 1)\n return dp[start, end] % mod\n else:\n dp[start, end] = backtracking(start + 1, end) + backtracking(start, end - 1) - backtracking(start + 1, end - 1)\n return dp[start, end] % mod\n return backtracking(0, n - 1)", "def countps(s):\n cnt = 0\n dp = [[0 for _ in range(len(s))] for _ in range(len(s))]\n for g in range(len(s)):\n i = 0\n for j in range(g, len(s)):\n if g == 0:\n dp[i][j] = 1\n elif g == 1:\n if s[i] == s[j]:\n dp[i][j] = 3\n else:\n dp[i][j] = 2\n elif s[i] == s[j]:\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] + 1\n else:\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]\n i += 1\n return dp[0][len(s) - 1] % (10 ** 9 + 7)", "def countps(string1):\n self.string1 = string1\n self.n = len(string1)\n self.t = [[-1 for _ in range(self.n + 1)] for _ in range(self.n + 1)]\n return self.count_palindromic_subsequence(i=0, j=self.n - 1) % (10 ** 9 + 7)\n\ndef count_palindromic_subsequence(i, j):\n if i > j:\n return 0\n if self.t[i][j] != -1:\n return self.t[i][j]\n if i == j:\n self.t[i][j] = 1\n return self.t[i][j]\n elif self.string1[i] == self.string1[j]:\n self.t[i][j] = 1 + self.count_palindromic_subsequence(i + 1, j) + self.count_palindromic_subsequence(i, j - 1)\n return self.t[i][j]\n else:\n self.t[i][j] = self.count_palindromic_subsequence(i + 1, j) + self.count_palindromic_subsequence(i, j - 1) - self.count_palindromic_subsequence(i + 1, j - 1)\n return self.t[i][j]", "def countps(string):\n n = len(string)\n dp = [[False for i in range(n)] for j in range(n)]\n mod = 1000000007\n for gap in range(n):\n (i, j) = (0, gap)\n while j < n:\n if gap == 0:\n dp[i][j] = 1\n elif gap == 1:\n if string[i] == string[j]:\n dp[i][j] = 3\n else:\n dp[i][j] = 2\n elif string[i] == string[j]:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] + 1\n else:\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]\n dp[i][j] = dp[i][j] % mod\n i += 1\n j += 1\n return dp[0][n - 1]", "def recur(i, j, string, dp):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n if string[i] == string[j]:\n dp[i][j] = self.recur(i + 1, j, string, dp) + self.recur(i, j - 1, string, dp) + 1\n else:\n dp[i][j] = self.recur(i + 1, j, string, dp) + self.recur(i, j - 1, string, dp) - self.recur(i + 1, j - 1, string, dp)\n return dp[i][j]\n\ndef countps(string):\n dp = [[-1 for i in range(len(string))] for j in range(len(string))]\n return self.recur(0, len(string) - 1, string, dp) % (10 ** 9 + 7)", "def countpsUtil(i, j, dp, s):\n if i > j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if i == j:\n dp[i][j] = 1\n elif s[i] == s[j]:\n dp[i][j] = self.countpsUtil(i + 1, j, dp, s) + self.countpsUtil(i, j - 1, dp, s) + 1\n else:\n dp[i][j] = self.countpsUtil(i + 1, j, dp, s) + self.countpsUtil(i, j - 1, dp, s) - self.countpsUtil(i + 1, j - 1, dp, s)\n return dp[i][j] % self.mod\n\ndef countps(s):\n self.mod = 10 ** 9 + 7\n n = len(s)\n dp = [[-1 for x in range(n + 1)] for y in range(n + 1)]\n self.countpsUtil(0, n - 1, dp, s)\n return dp[0][n - 1] % self.mod", "def countps(arr):\n\n def count(i, j, arr, dp):\n if i > j:\n return 0\n if i == j:\n dp[i][j] = 1\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n if arr[i] == arr[j]:\n dp[i][j] = 1 + count(i + 1, j, arr, dp) + count(i, j - 1, arr, dp)\n return dp[i][j]\n dp[i][j] = count(i + 1, j, arr, dp) + count(i, j - 1, arr, dp) - count(i + 1, j - 1, arr, dp)\n return dp[i][j]\n dp = [[-1] * len(arr) for x in range(len(arr))]\n return count(0, len(arr) - 1, arr, dp) % (10 ** 9 + 7)", "def countps(s):\n\n def manu(i, j):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n if s[i] == s[j]:\n k = 1 + manu(i + 1, j) + manu(i, j - 1)\n else:\n k = manu(i + 1, j) + manu(i, j - 1) - manu(i + 1, j - 1)\n k = k % (10 ** 9 + 7)\n dp[i][j] = k\n return k\n dp = [[-1 for i in range(len(s))] for i in range(len(s))]\n return manu(0, len(s) - 1)", "def countps(string):\n n = len(string)\n count = [[0 for i in range(n)] for j in range(n)]\n for i in range(n):\n count[i][i] = 1\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if string[i] == string[j]:\n count[i][j] = 1 + count[i][j - 1] + count[i + 1][j]\n else:\n count[i][j] = count[i][j - 1] + count[i + 1][j] - count[i + 1][j - 1]\n return count[0][n - 1] % (10 ** 9 + 7)", "from itertools import combinations\n\ndef countps(string):\n\n def subs(i, j, strng):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n if strng[i] == strng[j]:\n dp[i][j] = subs(i + 1, j, strng) + subs(i, j - 1, strng) + 1\n else:\n dp[i][j] = subs(i + 1, j, strng) + subs(i, j - 1, strng) - subs(i + 1, j - 1, strng)\n return dp[i][j]\n dp = [[-1] * len(string) for i in range(len(string))]\n return subs(0, len(string) - 1, string) % (10 ** 9 + 7)", "def countps(string):\n\n def count(i, j, st, dp):\n if i > j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if i == j:\n return 1\n elif st[i] == st[j]:\n dp[i][j] = 1 + count(i + 1, j, st, dp) + count(i, j - 1, st, dp)\n return dp[i][j] % 1000000007\n else:\n dp[i][j] = count(i + 1, j, st, dp) + count(i, j - 1, st, dp) - count(i + 1, j - 1, st, dp)\n return dp[i][j] % 1000000007\n dp = [[-1 for j in range(len(string))] for i in range(len(string))]\n return count(0, len(string) - 1, string, dp)", "def countps(s):\n n = len(s)\n dp = {}\n mod = 1000000007\n\n def fun(i, j):\n if i > j:\n return 0\n if i == j:\n return 1\n if (i, j) in dp:\n return dp[i, j]\n if s[i] == s[j]:\n dp[i, j] = 1 + fun(i + 1, j) + fun(i, j - 1)\n return dp[i, j]\n dp[i, j] = fun(i + 1, j) + fun(i, j - 1) - fun(i + 1, j - 1)\n return dp[i, j]\n return fun(0, len(s) - 1) % mod", "def countps(string):\n\n def func(i, j, stri, dp):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n if stri[i] == stri[j]:\n dp[i][j] = 1 + func(i + 1, j, stri, dp) + func(i, j - 1, stri, dp)\n return dp[i][j]\n else:\n dp[i][j] = func(i + 1, j, stri, dp) + func(i, j - 1, stri, dp) - func(i + 1, j - 1, stri, dp)\n return dp[i][j]\n dp = [[-1 for i in range(len(string))] for j in range(len(string))]\n kk = func(0, len(string) - 1, string, dp)\n return kk % (10 ** 9 + 7)", "def countps(s):\n N = len(s)\n mod = 10 ** 9 + 7\n dp = [[0] * N for _ in range(N)]\n for i in range(N):\n dp[i][i] = 1\n for L in range(2, N + 1):\n for i in range(N - L + 1):\n j = i + L - 1\n if s[i] == s[j]:\n dp[i][j] = (dp[i + 1][j] + dp[i][j - 1] + 1) % mod\n else:\n dp[i][j] = (dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]) % mod\n dp[i][j] %= mod\n return dp[0][N - 1] % mod", "def countps(string):\n n = len(string)\n dp = [[-1 for _ in range(n + 1)] for _ in range(n + 1)]\n\n def sol(i, j, string, dp):\n mod = 1000000000.0 + 7\n if i == j:\n return 1\n if i > j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if string[i] == string[j]:\n dp[i][j] = (1 + sol(i + 1, j, string, dp) + sol(i, j - 1, string, dp)) % mod\n else:\n dp[i][j] = ((sol(i + 1, j, string, dp) + sol(i, j - 1, string, dp) - sol(i + 1, j - 1, string, dp)) % mod + mod) % mod\n return dp[i][j]\n return int(sol(0, len(string) - 1, string, dp))", "def countps(string):\n dp = [[None] * len(string) for _ in range(len(string))]\n\n def fun(i, j):\n if i == j:\n return 1\n if i > j:\n return 0\n if dp[i][j] != None:\n return dp[i][j]\n if string[i] == string[j]:\n dp[i][j] = 1 + fun(i + 1, j) + fun(i, j - 1)\n return dp[i][j] % (pow(10, 9) + 7)\n else:\n dp[i][j] = fun(i + 1, j) + fun(i, j - 1) - fun(i + 1, j - 1)\n return dp[i][j] % (pow(10, 9) + 7)\n return fun(0, len(string) - 1)", "def countps(s):\n dp = [[0] * len(s) for i in range(len(s))]\n for gap in range(len(s)):\n for i in range(len(s) - gap):\n j = i + gap\n if i == j:\n dp[i][j] = 1\n else:\n if s[i] == s[j]:\n dp[i][j] = 1 + dp[i + 1][j] + dp[i][j - 1]\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n dp[i][j] = dp[i][j] % 1000000007\n return dp[0][len(s) - 1]", "def countps(string):\n n = len(string)\n mod = 10 ** 9 + 7\n dp = [[0] * n for i in range(n)]\n for g in range(0, n):\n for (i, j) in zip(range(0, n), range(g, n)):\n if g == 0:\n dp[i][j] = 1\n elif g == 1:\n if string[i] == string[j]:\n dp[i][j] = 3\n else:\n dp[i][j] = 2\n elif string[i] == string[j]:\n dp[i][j] = (dp[i][j - 1] + dp[i + 1][j] + 1) % mod\n else:\n dp[i][j] = (dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]) % mod\n return dp[0][n - 1] % mod", "import sys\nsys.setrecursionlimit(10000)\n\ndef countps(stringe):\n hmap = {}\n n = len(stringe)\n\n def count_palindrome_sub(S, i, j):\n mod = 1000000000.0 + 7\n if i > j:\n return 0\n if i == j:\n return 1\n if (i, j) not in hmap:\n hmap[i, j] = count_palindrome_sub(S, i + 1, j) % mod + count_palindrome_sub(S, i, j - 1) % mod\n if S[i] == S[j]:\n hmap[i, j] += 1\n else:\n hmap[i, j] -= count_palindrome_sub(S, i + 1, j - 1) % mod\n return hmap[i, j]\n ans = count_palindrome_sub(stringe, 0, n - 1)\n return int(ans % (1000000000.0 + 7))", "def countps(string):\n s = string\n N = len(s)\n dp = [[0 for _ in range(N)] for _ in range(N)]\n for i in range(N, -1, -1):\n for j in range(i, N, 1):\n if i == j:\n dp[i][j] = 1\n elif s[i] == s[j]:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] + 1\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n return dp[0][N - 1] % (pow(10, 9) + 7)", "def countps(string):\n arr = [[-1 for i in range(len(string))] for j in range(len(string))]\n (i, j) = (0, len(string) - 1)\n res = self.cpsHelper(string, i, j, arr)\n return res % (10 ** 9 + 7)\n\ndef cpsHelper(string, i, j, arr):\n if i > j:\n return 0\n if arr[i][j] != -1:\n return arr[i][j]\n if string[i] == string[j]:\n res = self.cpsHelper(string, i + 1, j, arr) + self.cpsHelper(string, i, j - 1, arr) + 1\n else:\n res = self.cpsHelper(string, i + 1, j, arr) + self.cpsHelper(string, i, j - 1, arr) - self.cpsHelper(string, i + 1, j - 1, arr)\n arr[i][j] = res\n return res", "def countps(s):\n dp = [[0] * len(s) for i in range(len(s))]\n for gap in range(len(s)):\n i = 0\n j = gap\n while j < len(s):\n if gap == 0:\n dp[i][j] = 1\n elif gap == 1:\n if s[i] == s[j]:\n dp[i][j] = 3\n else:\n dp[i][j] = 2\n elif s[i] == s[j]:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] + 1\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n i = i + 1\n j = j + 1\n return dp[0][-1] % 1000000007", "def countps(s):\n n = len(s)\n dp = [[0 for i in range(n)] for j in range(n)]\n fp = sp = 0\n for i in range(n):\n dp[i][i] = 1\n for i in range(1, n):\n for j in range(n - i):\n fp = j\n sp = j + i\n if s[fp] == s[sp]:\n dp[fp][sp] = (dp[fp + 1][sp] + dp[fp][sp - 1] + 1) % (10 ** 9 + 7)\n else:\n dp[fp][sp] = (dp[fp + 1][sp] + dp[fp][sp - 1] - dp[fp + 1][sp - 1]) % (10 ** 9 + 7)\n return dp[fp][sp]", "def countps(s):\n dp = []\n ans = 0\n for i in range(len(s)):\n dp.append([0] * len(s))\n for i in range(len(s)):\n dp[i][i] = 1\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n dp[i][i + 1] = 3\n else:\n dp[i][i + 1] = 2\n for lent in range(2, len(s)):\n i = 0\n while i + lent < len(s):\n if s[i] != s[i + lent]:\n dp[i][i + lent] = dp[i + 1][i + lent] + dp[i][i + lent - 1] - dp[i + 1][i + lent - 1]\n else:\n dp[i][i + lent] = dp[i + 1][i + lent] + dp[i][i + lent - 1] + 1\n i += 1\n return dp[0][len(s) - 1] % (10 ** 9 + 7)", "def countps(s):\n t = [[-1 for i in range(1001)] for i in range(1001)]\n mod = 10 ** 9 + 7\n\n def solve(s, i, j, t):\n if i == j:\n return 1\n if i > j:\n return 0\n if t[i][j] != -1:\n return t[i][j]\n elif s[i] == s[j]:\n t[i][j] = 1 + solve(s, i + 1, j, t) % mod + solve(s, i, j - 1, t) % mod\n t[i][j] %= mod\n return t[i][j]\n else:\n t[i][j] = solve(s, i + 1, j, t) % mod + solve(s, i, j - 1, t) % mod - solve(s, i + 1, j - 1, t) % mod\n t[i][j] %= mod\n return t[i][j]\n return solve(s, 0, len(s) - 1, t)", "def countps(string):\n S = string\n n = len(S)\n dp = [[0] * n for i in range(n)]\n M = 10 ** 9 + 7\n for i in range(n):\n for j in range(i, -1, -1):\n if i == j:\n dp[j][i] = 1\n elif S[i] == S[j]:\n dp[j][i] = dp[j + 1][i] + dp[j][i - 1] + 1\n else:\n dp[j][i] = dp[j + 1][i] + dp[j][i - 1] - dp[j + 1][i - 1]\n return dp[0][n - 1] % M", "def countps(string):\n dic = {}\n n = len(string)\n\n def recursive(string, n, left, right):\n if left > right:\n return 0\n if (left, right) in dic:\n return dic[left, right]\n if left == right:\n dic[left, right] = 1\n elif string[left] == string[right]:\n dic[left, right] = (1 + recursive(string, n, left + 1, right) + recursive(string, n, left, right - 1)) % 1000000007\n else:\n dic[left, right] = (recursive(string, n, left + 1, right) + recursive(string, n, left, right - 1) - recursive(string, n, left + 1, right - 1)) % 1000000007\n return dic[left, right]\n return recursive(string, n, 0, n - 1)", "def countps(string):\n n = len(string)\n MOD = 10 ** 9 + 7\n dp = [[0] * n for i in range(n)]\n for l in range(1, n + 1):\n i = 0\n while i + l <= n:\n j = i + l - 1\n if i > j:\n break\n if l == 1:\n dp[i][j] = 1\n elif l == 2:\n if string[i] == string[j]:\n dp[i][j] = 3\n else:\n dp[i][j] = 2\n elif string[i] == string[j]:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] + 1\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n dp[i][j] %= MOD\n i += 1\n return dp[0][n - 1]", "def countps(s):\n\n def count(i, j, s):\n if i > j:\n return 0\n if i == j:\n return 1\n if t[i][j] != -1:\n return t[i][j]\n if s[i] == s[j]:\n t[i][j] = 1 + count(i + 1, j, s) + count(i, j - 1, s)\n return t[i][j] % 1000000007\n else:\n t[i][j] = count(i + 1, j, s) + count(i, j - 1, s) - count(i + 1, j - 1, s)\n return t[i][j] % 1000000007\n n = len(s)\n t = [[-1] * (n + 1) for x in range(n + 1)]\n return count(0, n - 1, s)", "def solver(str, i, j, dct):\n if i > j:\n return 0\n if (i, j) in dct:\n return dct[i, j]\n res = 0\n if str[i] == str[j]:\n res = solver(str, i + 1, j, dct) + solver(str, i, j - 1, dct) + 1\n else:\n res = solver(str, i + 1, j, dct) + solver(str, i, j - 1, dct) - solver(str, i + 1, j - 1, dct)\n res %= 1000000007\n dct[i, j] = res\n return res\n\ndef countps(string):\n dct = dict()\n return solver(string, 0, len(string) - 1, dct)", "def countps(string):\n n = len(string)\n dp = []\n for _ in range(n):\n dp.append([0] * n)\n for i in range(n):\n dp[i][i] = 1\n for i in range(n - 1):\n k = 0\n for j in range(i + 1, n):\n if string[k] == string[j]:\n dp[k][j] = 1 + dp[k][j - 1] + dp[k + 1][j]\n else:\n dp[k][j] = dp[k][j - 1] + dp[k + 1][j] - dp[k + 1][j - 1]\n k += 1\n return dp[0][n - 1] % (10 ** 9 + 7)", "def countps(string):\n dp = [[0 for j in range(len(string))] for i in range(2)]\n mod = 1000000007\n dp[1][-1] = 1\n for i in range(len(string) - 2, -1, -1):\n dp[0][i] = 1\n for j in range(i + 1, len(string)):\n dp[0][j] = 0\n dp[0][j] += dp[0][j - 1] + dp[1][j]\n if string[i] == string[j]:\n dp[0][j] += 1\n else:\n dp[0][j] -= dp[1][j - 1]\n dp[0][j] %= mod\n (dp[0], dp[1]) = (dp[1], dp[0])\n return dp[1][len(string) - 1]", "import sys\nsys.setrecursionlimit(10000)\n\ndef __count_palin_subseq_helper(i, j, string):\n if i > j:\n return 0\n if i == j:\n return 1\n if self.dp[i][j] == None:\n self.dp[i][j] = 0\n self.dp[i][j] += self.__count_palin_subseq_helper(i, j - 1, string) + self.__count_palin_subseq_helper(i + 1, j, string)\n if string[i] == string[j]:\n self.dp[i][j] += 1\n else:\n self.dp[i][j] -= self.__count_palin_subseq_helper(i + 1, j - 1, string)\n self.dp[i][j] %= self.mod\n return self.dp[i][j]\n\ndef countps(string):\n self.dp = [[None for j in range(len(string))] for i in range(len(string))]\n self.mod = 1000000007\n return self.__count_palin_subseq_helper(0, len(string) - 1, string)", "def countps(s):\n n = len(s)\n dp = [[-1 for k in range(n + 1)] for t in range(n + 1)]\n m = 10 ** 9 + 7\n\n def memo(i, j):\n if i > j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if i == j:\n dp[i][j] = 1\n return dp[i][j]\n if s[i] == s[j]:\n dp[i][j] = memo(i + 1, j) + memo(i, j - 1) + 1\n else:\n dp[i][j] = memo(i + 1, j) + memo(i, j - 1) - memo(i + 1, j - 1)\n return dp[i][j]\n return memo(0, n - 1) % m", "def countps(string):\n n = len(string)\n dp = [[-1 for x in range(n)] for y in range(n)]\n\n def countPA(i, j):\n if i > j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if i == j:\n dp[i][j] = 1\n return dp[i][j]\n if string[i] == string[j]:\n dp[i][j] = countPA(i + 1, j) + countPA(i, j - 1) + 1\n return dp[i][j]\n else:\n dp[i][j] = countPA(i + 1, j) + countPA(i, j - 1) - countPA(i + 1, j - 1)\n return dp[i][j]\n return countPA(0, n - 1) % (10 ** 9 + 7)", "def solve(s, i, j, dp):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j]:\n return dp[i][j]\n if s[i] == s[j]:\n dp[i][j] = 1 + self.solve(s, i + 1, j, dp) + self.solve(s, i, j - 1, dp)\n else:\n dp[i][j] = self.solve(s, i + 1, j, dp) + self.solve(s, i, j - 1, dp) - self.solve(s, i + 1, j - 1, dp)\n return dp[i][j]\n\ndef countps(s):\n mod = 10 ** 9 + 7\n dp = [[0 for i in range(len(s))] for j in range(len(s))]\n return self.solve(s, 0, len(s) - 1, dp) % mod", "def countps(string):\n n = len(string)\n ans = [[0] * n for i in range(n)]\n for d in range(n):\n i = 0\n for j in range(d, n):\n if d == 0:\n ans[i][j] = 1\n elif string[i] == string[j]:\n ans[i][j] = ans[i][j - 1] + ans[i + 1][j] + 1\n else:\n ans[i][j] = ans[i][j - 1] + ans[i + 1][j] - ans[i + 1][j - 1]\n i += 1\n return ans[0][n - 1] % (10 ** 9 + 7)", "def countps(string):\n n = len(string)\n dp = [[0] * n for _ in range(n)]\n mod = 1000000007\n for i in range(n):\n dp[i][i] = 1\n for i in range(0, n - 2 + 1):\n j = i + 2 - 1\n if string[i] == string[j]:\n dp[i][j] = 3\n elif string[i] != string[j]:\n dp[i][j] = 2\n for l in range(3, n + 1):\n for i in range(0, n - l + 1):\n j = i + l - 1\n if string[i] == string[j]:\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] + 1\n elif string[i] != string[j]:\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]\n if dp[0][n - 1] > mod:\n return dp[0][n - 1] % mod\n else:\n return dp[0][n - 1]"], "starter_code": "def countps(string):\n", "input_output": {"inputs": ["Str = \"abcd\"", "Str = \"aab\""], "outputs": ["4", "4"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/count-palindromic-subsequences/1", "Expected Auxiliary Space": "O(N*N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*N)", "entry_point": "countps", "task_id": "TACO_lite/329", "example": [[["abcd"], ["aab"]], ["4", "4"]]} +{"requirement": "Given an array arr of n integers, sort the first half of the array in ascending order and second half in descending order.\nExample 1:\nInput:\nn = 4\narr[] = {10, 20, 30, 40}\nOutput: 10 20 40 30\nExample 2:\nInput:\nn = 9\narr[] = {5, 4, 6, 2, 1, 3, 8, 9, 7}\nOutput: 2 4 5 6 9 8 7 3 1\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function customSort() which takes the array of integers arr and n as parameters and returns void. You need to change the array itself.\nExpected Time Complexity: O(n*logn)\nExpected Auxiliary Space: O(1)\nConstraints: \n1 <= n <= 10^{5}\n1 <= arr[i] <= 10^{6}", "solutions": ["def customsort(arr, n):\n i = n // 2\n arr[:i] = sorted(arr[:i])\n arr[i:] = sorted(arr[i:], reverse=True)\n return arr", "def customsort(arr, n):\n arr[0:int(n / 2)] = sorted(arr[0:int(n / 2)])\n arr[int(n / 2):] = list(reversed(sorted(arr[int(n / 2):])))", "def customsort(arr, n):\n left = arr[:n // 2]\n right = arr[n // 2:]\n left.sort()\n right.sort(reverse=True)\n left = left + right\n for i in range(n):\n arr[i] = left[i]", "def customsort(arr, n):\n mid = n // 2\n b = arr[:mid]\n c = arr[mid:]\n b.sort()\n c.sort(reverse=True)\n d = b + c\n arr[:] = d[:]\n return arr", "def customsort(arr, n):\n p = arr[:n // 2]\n q = arr[n // 2:]\n p.sort()\n q.sort()\n q.reverse()\n a = p + q\n arr[:] = a[:]", "def customsort(arr, n):\n li = []\n li2 = []\n for i in range(n // 2):\n li.append(arr[i])\n li = sorted(li)\n for j in range(n // 2, n):\n li2.append(arr[j])\n li2.sort(reverse=True)\n for i in range(len(li2)):\n li.append(li2[i])\n return li", "def customsort(arr, n):\n op = arr[:n // 2]\n lp = arr[n // 2:]\n op.sort()\n lp.sort(reverse=True)\n d = op + lp\n arr[:] = d[:]\n return arr", "def customsort(arr, n):\n m = n // 2\n a = arr[:m]\n b = arr[m:]\n a.sort()\n b.sort(reverse=True)\n a.extend(b)\n for i in range(n):\n arr[i] = a[i]\n return arr", "def customsort(arr, n):\n i = n // 2\n brr = sorted(arr[:i]) + sorted(arr[i:], reverse=True)\n for i in range(n):\n arr[i] = brr[i]\n return", "def customsort(arr, n):\n arr1 = []\n arr2 = []\n i = 0\n while i < n:\n if i < n // 2:\n arr1.append(arr[i])\n else:\n arr2.append(arr[i])\n i += 1\n arr1.sort()\n arr2.sort(reverse=True)\n for i in range(len(arr1)):\n arr[i] = arr1[i]\n for i in range(len(arr2)):\n arr[i + len(arr1)] = arr2[i]", "def customsort(arr, n):\n dupli = arr.copy()\n (left, right) = (arr[:n // 2], arr[n // 2:])\n (left.sort(), right.sort(reverse=True))\n arr.clear()\n (arr.extend(left), arr.extend(right))\n return arr", "def customsort(arr, n):\n a = arr[:n // 2]\n b = arr[n // 2:]\n a.sort()\n b.sort(reverse=True)\n arr[:] = a + b", "def customsort(arr, n):\n arr[:n // 2] = sorted(arr[:n // 2])\n arr[n // 2:] = sorted(arr[n // 2:], reverse=True)", "def customsort(arr, n):\n a = arr[:n // 2]\n b = arr[n // 2:]\n a.sort()\n b.sort(reverse=True)\n c = a + b\n for i in range(len(c)):\n arr[i] = c[i]", "def customsort(arr, n):\n n = n // 2\n fh = arr[:n]\n sh = arr[n:]\n fh.sort()\n sh.sort(reverse=True)\n res = fh + sh\n arr[:] = res[:]\n return res", "def customsort(arr, n):\n a = n // 2\n arr[0:a] = sorted(arr[0:a])\n arr[a:n] = sorted(arr[a:n], reverse=True)\n return arr", "def customsort(arr, n):\n b = []\n c = []\n m = n // 2\n for i in range(0, m):\n b.append(arr[i])\n for i in range(m, n):\n c.append(arr[i])\n b.sort()\n c.sort(reverse=True)\n d = b + c\n for i in range(n):\n arr[i] = d[i]\n return arr", "def customsort(arr, n):\n t = n // 2\n l = arr[:t]\n l.sort()\n for i in range(0, t):\n arr[i] = l[i]\n h = arr[t:]\n h.sort(reverse=True)\n for i in h:\n arr[t] = i\n t = t + 1", "def customsort(arr, n):\n l = n // 2\n arr1 = sorted(arr[0:l])\n arr2 = sorted(arr[l:n], reverse=True)\n arr3 = arr1 + arr2\n arr[:] = arr3[:]", "def customsort(arr, n):\n from math import floor\n m = floor(n / 2)\n l = arr[0:m]\n l.sort()\n r = arr[m:n]\n r.sort(reverse=True)\n a1 = l + r\n for (i, v) in enumerate(a1):\n arr[i] = v", "def customsort(arr, n):\n l1 = arr[:n // 2]\n l2 = arr[n // 2:]\n l1.sort()\n l2.sort(reverse=True)\n arr.clear()\n l3 = l1 + l2\n for i in l3:\n arr.append(i)", "def customsort(arr, n):\n half = n // 2\n list1 = arr[:half]\n list2 = arr[half:]\n list1.sort()\n list2.sort(reverse=True)", "def customsort(arr, n):\n a1 = arr[:n // 2]\n a2 = arr[n // 2:]\n a1.sort()\n a2.sort(reverse=True)\n arr[:] = a1[:] + a2[:]", "def customsort(arr, n):\n b = arr[0:n // 2]\n c = arr[n // 2:n]\n b.sort()\n c.sort(reverse=True)\n b.extend(c)\n for i in range(0, n):\n arr[i] = b[i]\n return arr", "def customsort(arr, n):\n if n % 2 == 0:\n l = arr[:n // 2]\n l1 = arr[n // 2:]\n l.sort()\n l1.sort()\n l1 = l1[::-1]\n l2 = l + l1\n for i in range(n):\n arr[i] = l2[i]\n else:\n l = arr[:n // 2]\n l1 = arr[n // 2:]\n l.sort()\n l1.sort()\n l1 = l1[::-1]\n l2 = l + l1\n for i in range(n):\n arr[i] = l2[i]", "def customsort(arr, n):\n l = sorted(arr[:n // 2])\n r = sorted(arr[n // 2:], reverse=True)\n new = l + r\n for i in range(len(new)):\n arr[i] = new[i]", "def customsort(arr, n):\n middle = n // 2\n a = arr[:middle]\n b = arr[middle:]\n a.sort()\n b.sort(reverse=True)\n c = a + b\n arr[:] = c[:]\n return arr", "def customsort(arr, n):\n g = [arr[i] for i in range(0, n // 2)]\n h = [arr[i] for i in range(n // 2, n)]\n g.sort()\n h.sort()\n j = h[::-1]\n arr[:] = g + j", "def customsort(arr, n):\n x = sorted(arr[:n // 2])\n y = sorted(arr[n // 2:])\n z = y[::-1]\n a = x + z\n for i in range(n):\n if arr[i] != a[i]:\n arr[i] = a[i]", "def customsort(arr, n):\n (brr, crr) = (arr[:n // 2], arr[n // 2:])\n brr.sort()\n crr.sort(reverse=True)\n arr.clear()\n krr = brr + crr\n arr[:] = krr[:]\n return arr", "def customsort(arr, n):\n k = arr[:n // 2].copy()\n j = arr[n // 2:n].copy()\n k.sort()\n j.sort()\n lis = []\n lis = k.copy()\n for i in j[::-1]:\n lis.append(i)\n for i in range(n):\n arr[i] = lis[i]\n return arr", "def customsort(arr, n):\n a1 = arr[:n // 2]\n a2 = arr[n // 2:]\n a1.sort()\n a2.sort(reverse=True)\n arr.clear()\n arr.extend(a1)\n arr.extend(a2)\n return arr", "def customsort(arr, n):\n length = n // 2\n first_half = []\n second_half = []\n for i in range(length):\n first_half.append(arr[i])\n for j in range(length, n):\n second_half.append(arr[j])\n first_half.sort()\n second_half.sort(reverse=True)\n new_array = first_half + second_half\n arr.clear()\n for i in range(len(new_array)):\n arr.append(new_array[i])", "def customsort(arr, n):\n a = int(n / 2)\n b = arr[a:n]\n c = arr[0:a]\n b.sort(reverse=True)\n c.sort()\n d = c + b\n arr[:] = d", "def customsort(arr, n):\n index = len(arr) // 2\n arr[0:index] = sorted(arr[:index])\n arr[index:n] = sorted(arr[index:n], reverse=True)", "def customsort(arr, n):\n l = []\n k = []\n m = n // 2\n for i in range(0, m):\n l.append(arr[i])\n for j in range(m, n):\n k.append(arr[j])\n l.sort()\n k.sort(reverse=True)\n c = l + k\n for i in range(n):\n arr[i] = c[i]\n return arr", "def customsort(arr, n):\n (a, b) = ([], [])\n for i in range(0, n // 2):\n a.append(arr[i])\n for i in range(n // 2, n):\n b.append(arr[i])\n a.sort()\n b.sort(reverse=True)\n arr[:] = a + b\n return arr", "def customsort(arr, n):\n mid = n // 2\n x = arr[:mid]\n y = arr[mid:]\n x.sort()\n y.sort(reverse=True)\n a = x + y\n for i in range(n):\n arr[i] = a[i]", "def customsort(arr, n):\n x = []\n y = []\n mid = n // 2\n for i in range(0, mid):\n x.append(arr[i])\n for i in range(mid, n):\n y.append(arr[i])\n x.sort()\n y.sort(reverse=True)\n l = x + y\n for i in range(n):\n arr[i] = l[i]\n return arr", "def customsort(arr, n):\n mid = n // 2\n arr1 = arr[:mid]\n arr2 = arr[mid:]\n arr1.sort()\n arr2.sort(reverse=True)\n arr[:] = arr1 + arr2", "def customsort(arr, n):\n l = len(arr)\n a1 = arr[:l // 2]\n a2 = arr[l // 2:]\n a1 = sorted(a1)\n a2 = sorted(a2, reverse=True)\n a1.extend(a2)\n for x in range(n):\n arr[x] = str(a1[x])\n arr = ' '.join(arr)\n return arr", "def customsort(arr, n):\n mid = n // 2\n new_arr = arr[:mid]\n new_arr1 = arr[mid:]\n new_arr.sort()\n new_arr1.sort(reverse=True)\n count = 0\n for i in range(n):\n if i <= mid - 1:\n arr[i] = new_arr[i]\n else:\n arr[i] = new_arr1[count]\n count += 1\n return arr", "def customsort(arr, n):\n if n % 2 == 0:\n mid = n // 2\n else:\n mid = (n - 1) // 2\n first = arr[:mid]\n second = arr[mid:]\n first.sort()\n second.sort(reverse=True)\n lst = first + second\n for i in range(n):\n arr[i] = lst[i]\n return arr", "def customsort(arr, n):\n fh = arr[:n // 2]\n sh = arr[n // 2:]\n fh.sort()\n sh.sort(reverse=True)\n nar = fh + sh\n for i in range(n):\n arr[i] = nar[i]", "def customsort(arr, n):\n x = n // 2\n arr1 = []\n arr2 = []\n for i in range(0, x):\n arr1.append(arr[i])\n for i in range(x, n):\n arr2.append(arr[i])\n arr1.sort()\n arr2.sort(reverse=True)\n for i in arr2:\n arr1.append(i)\n for i in range(n):\n arr[i] = arr1[i]\n return arr", "def customsort(arr, n):\n if n == 1:\n return arr\n mid = int(n / 2)\n arr1 = arr[0:mid]\n arr2 = arr[mid:]\n arr1.sort()\n arr2.sort(reverse=True)\n i = 0\n for i in range(0, len(arr1)):\n arr[i] = arr1[i]\n for j in range(0, len(arr2)):\n i += 1\n arr[i] = arr2[j]\n return arr", "def customsort(arr, n):\n arr1 = arr[:n // 2]\n arr2 = arr[n // 2:]\n arr1.sort()\n arr2.sort(reverse=True)\n x = n // 2\n i = 0\n j = 0\n k = 0\n while i < n:\n if i < x:\n arr[i] = arr1[j]\n j += 1\n else:\n arr[i] = arr2[k]\n k += 1\n i += 1", "def customsort(arr, n):\n li = [0] * (n // 2)\n li2 = [0] * (n - n // 2)\n for i in range(n // 2):\n li[i] = arr[i]\n for i in range(n // 2, n):\n li2[i - n // 2] = arr[i]\n li.sort()\n li2.sort(reverse=True)\n for i in range(n):\n if i < n // 2:\n arr[i] = li[i]\n else:\n arr[i] = li2[i - n // 2]\n return arr", "def customsort(arr, n):\n half1 = arr[:n // 2]\n half2 = arr[n // 2:]\n half1.sort()\n half2.sort(reverse=True)\n s = half1 + half2\n for i in range(len(arr)):\n arr[i] = s[i]", "def customsort(arr, n):\n arrA = arr[:n // 2]\n arrA.sort()\n arrD = arr[n // 2:]\n arrD.sort(reverse=True)\n arr_sorted = arrA + arrD\n for i in range(len(arr)):\n arr[i] = arr_sorted[i]\n return arr", "def customsort(arr, n):\n a1 = arr[:n // 2]\n a2 = arr[n // 2:]\n a1.sort()\n a2.sort(reverse=True)\n a1.extend(a2)\n for i in range(n):\n arr[i] = a1[i]", "def customsort(arr, n):\n first = []\n odd = []\n for i in range(0, n // 2):\n first.append(arr[i])\n for i in range(n // 2, len(arr)):\n odd.append(arr[i])\n first.sort()\n odd.sort(reverse=True)\n for i in odd:\n first.append(i)\n for i in range(len(arr)):\n arr[i] = first[i]\n return arr", "def customsort(arr, n):\n l1 = sorted(arr[0:n // 2])\n l2 = sorted(arr[n // 2:n])\n l1.extend(l2[::-1])\n for i in range(n):\n arr[i] = l1[i]\n return l1", "def customsort(arr, n):\n mid = n // 2\n a1 = arr[:mid]\n a2 = arr[mid:]\n a1.sort()\n a2.sort(reverse=True)\n c = a1 + a2\n for i in range(n):\n arr[i] = c[i]\n return arr", "def customsort(arr, n):\n f = []\n l = []\n for i in range(0, n // 2):\n f.append(arr[i])\n for i in range(n // 2, n):\n l.append(arr[i])\n f.sort()\n l.sort(reverse=True)\n arr.clear()\n for i in f:\n arr.append(i)\n for i in l:\n arr.append(i)", "def customsort(arr, n):\n first = []\n second = []\n index = n // 2\n first = arr[:index]\n first.sort()\n second = arr[index:]\n second.sort()\n second.reverse()\n final = first + second\n for i in range(len(arr)):\n arr[i] = final[i]\n return arr"], "starter_code": "def customsort(arr, n):\n", "input_output": {"inputs": ["n = 4\narr[] = {10, 20, 30, 40}", "n = 9\narr[] = {5, 4, 6, 2, 1, 3, 8, 9, 7}"], "outputs": ["10 20 40 30", "2 4 5 6 9 8 7 3 1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/sort-first-half-in-ascending-and-second-half-in-descending1714/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n*logn)", "entry_point": "customsort", "task_id": "TACO_lite/389", "example": [[[4, [10, 20, 30, 40]], [9, [5, 4, 6, 2, 1, 3, 8, 9, 7]]], ["[10, 20, 40, 30]", "[2, 4, 5, 6, 9, 8, 7, 3, 1]"]]} +{"requirement": "```if-not:ruby\nCreate a function, that accepts an arbitrary number of arrays and returns a single array generated by alternately appending elements from the passed in arguments. If one of them is shorter than the others, the result should be padded with empty elements.\n```\n```if:ruby\nCreate a function, that accepts an arbitrary number of arrays and returns a single array generated by alternately appending elements from the passed in arguments. If one of them is shorter than the others, the result should be padded with `nil`s.\n```\n\nExamples:\n\n```python\ninterleave([1, 2, 3], [\"c\", \"d\", \"e\"]) == [1, \"c\", 2, \"d\", 3, \"e\"]\ninterleave([1, 2, 3], [4, 5]) == [1, 4, 2, 5, 3, None]\ninterleave([1, 2, 3], [4, 5, 6], [7, 8, 9]) == [1, 4, 7, 2, 5, 8, 3, 6, 9]\ninterleave([]) == []\n```", "solutions": ["from itertools import chain, zip_longest\n\ndef interleave(*args):\n return list(chain.from_iterable(zip_longest(*args)))", "def interleave(*args):\n max_len = max(map(len, args))\n interleaved = []\n for i in range(max_len):\n for arr in args:\n if i < len(arr):\n interleaved.append(arr[i])\n else:\n interleaved.append(None)\n return interleaved", "from itertools import chain, zip_longest\n\ndef interleave(*args):\n return [*chain(*zip_longest(*args))]", "interleave = lambda *a: [b[i] if len(b) > i else None for i in range(max((len(i) for i in a))) for b in a]", "from itertools import zip_longest\n\ndef interleave(*args):\n return [y for x in zip_longest(*args) for y in x]", "interleave = lambda *a: sum([list(i) for i in __import__('itertools').zip_longest(*a)], [])", "from itertools import zip_longest\n\ndef interleave(*args):\n return [i for _ in zip_longest(*args) for i in _]", "def interleave(*args):\n arr = []\n for i in range(max((len(a) for a in args))):\n for j in range(len(args)):\n try:\n arr.append(args[j][i])\n except:\n arr.append(None)\n return arr", "def interleave(*args):\n n_max = len(max(args, key=len))\n return [j[i] if i < len(j) else None for i in range(n_max) for j in args]"], "starter_code": "def interleave(*args):\n", "input_output": {"fn_name": "interleave", "inputs": [[[1, 2, 3], ["c", "d", "e"]], [[1, 2, 3], [4, 5]], [[1, 2], [3, 4, 5]], [[null], [null, null], [null, null, null]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[]]], "outputs": [[[1, "c", 2, "d", 3, "e"]], [[1, 4, 2, 5, 3, null]], [[1, 3, 2, 4, null, 5]], [[null, null, null, null, null, null, null, null, null]], [[1, 4, 7, 2, 5, 8, 3, 6, 9]], [[]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms"], "name": null, "source": "codewars", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/523d2e964680d1f749000135", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "interleave", "task_id": "TACO_lite/42", "example": [[[[1, 2, 3], ["c", "d", "e"]], [[1, 2, 3], [4, 5]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[]]], ["[1, 'c', 2, 'd', 3, 'e']", "[1, 4, 2, 5, 3, None]", "[1, 4, 7, 2, 5, 8, 3, 6, 9]", "[]"]]} +{"requirement": "Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K.\nExample 1:\nInput:\nN = 4, K = 6\narr[] = {1, 5, 7, 1}\nOutput: 2\nExplanation: \narr[0] + arr[1] = 1 + 5 = 6 \nand arr[1] + arr[3] = 5 + 1 = 6.\nExample 2:\nInput:\nN = 4, K = 2\narr[] = {1, 1, 1, 1}\nOutput: 6\nExplanation: \nEach 1 will produce sum 2 with any 1.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function getPairsCount() which takes arr[], n and k as input parameters and returns the number of pairs that have sum K.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 <= N <= 10^{5}\n1 <= K <= 10^{8}\n1 <= Arr[i] <= 10^{6}", "solutions": ["import math\nfrom collections import Counter\n\ndef getpairscount(arr, n, k):\n mpp = Counter(arr)\n c = 0\n flag = False\n a = list(set(arr))\n for i in range(len(a)):\n x = k - a[i]\n if x in mpp:\n if k - a[i] == a[i]:\n n = mpp[a[i]]\n c += n * (n - 1) // 2\n else:\n c += mpp[a[i]] * mpp[k - a[i]]\n flag = True\n if flag == True:\n return (c + 1) // 2\n return c", "def getpairscount(arr, n, k):\n d = {}\n count = 0\n for i in arr:\n if k - i in d:\n count += d[k - i]\n d[i] = d.get(i, 0) + 1\n return count", "def getpairscount(a, n, k):\n mydict = dict()\n c = 0\n for i in range(0, n):\n temp = k - a[i]\n if temp in mydict:\n val = mydict[temp]\n for j in range(0, val):\n c += 1\n if a[i] not in mydict:\n mydict[a[i]] = 1\n else:\n mydict[a[i]] += 1\n return c", "def getpairscount(arr, n, sum):\n unordered_map = {}\n count = 0\n for i in range(n):\n if sum - arr[i] in unordered_map:\n count += unordered_map[sum - arr[i]]\n if arr[i] in unordered_map:\n unordered_map[arr[i]] += 1\n else:\n unordered_map[arr[i]] = 1\n return count", "def getpairscount(arr, n, k):\n from collections import defaultdict\n dct = defaultdict(int)\n count = 0\n for num in arr:\n count += dct[k - num]\n dct[num] += 1\n return count", "def getpairscount(arr, n, k):\n from collections import Counter\n dct = Counter(arr)\n count = 0\n for num in dct:\n if k - num in dct:\n val = k - num\n if val != num:\n count += dct[num] * dct[val]\n dct[num] = 0\n else:\n repeats = dct[num]\n count += repeats * (repeats - 1) // 2\n return count", "def getpairscount(arr, n, k):\n hashM = {}\n ans = 0\n for i in range(n):\n t = k - arr[i]\n if t in hashM:\n ans += hashM[t]\n if arr[i] not in hashM:\n hashM[arr[i]] = 0\n hashM[arr[i]] += 1\n return ans", "from collections import Counter\n\ndef getpairscount(arr, n, k):\n hm = Counter(arr)\n count = 0\n for n in arr:\n hm[n] -= 1\n if k - n in hm:\n count += hm[k - n]\n return count", "def getpairscount(arr, n, k):\n cnt = 0\n d = {}\n for i in range(n):\n if k - arr[i] in d:\n cnt += d[k - arr[i]]\n if arr[i] in d:\n d[arr[i]] += 1\n else:\n d[arr[i]] = 1\n return cnt", "def getpairscount(arr, n, k):\n dic = dict()\n count = 0\n for i in range(n):\n data = k - arr[i]\n if data in dic:\n count = count + dic[k - arr[i]]\n dic[arr[i]] = dic.get(arr[i], 0) + 1\n return count", "def getpairscount(arr, n, k):\n a = {}\n cnt = 0\n for i in arr:\n b = k - i\n if b in a:\n cnt = cnt + a[b]\n if i in a:\n a[i] = a[i] + 1\n else:\n a[i] = 1\n return cnt", "def getpairscount(arr, n, k):\n freq_map = {}\n count = 0\n for num in arr:\n target = k - num\n if target in freq_map:\n count += freq_map[target]\n freq_map[num] = freq_map.get(num, 0) + 1\n return count", "def getpairscount(arr, n, k):\n (s, d) = (0, {})\n for elem in arr:\n d.update({elem: d.get(elem, 0) + 1})\n for elem in d:\n if elem * 2 == k:\n s += d[elem] * (d[elem] - 1) // 2\n d[elem] = 0\n elif d[elem] and d.get(k - elem, 0):\n s += d[elem] * d.get(k - elem, 0)\n d[elem] = 0\n return s", "def getpairscount(arr, n, k):\n arr.sort()\n mx = max(arr)\n freq = [0] * (mx + 1)\n for elem in arr:\n freq[elem] += 1\n d = {}\n for elem in arr:\n d.update({elem: d.get(elem, 0) + 1})\n s = 0\n s = 0\n for elem in d:\n if elem * 2 == k:\n s += d[elem] * (d[elem] - 1) // 2\n d[elem] = 0\n elif d[elem] and d.get(k - elem, 0):\n s += d[elem] * d.get(k - elem, 0)\n d[elem] = 0\n return s", "def getpairscount(arr, n, k):\n d = dict()\n c = 0\n for i in arr:\n A = k - i\n if A in d:\n c = c + d[A]\n if i in d:\n d[i] = d[i] + 1\n else:\n d[i] = 1\n return c", "def getpairscount(arr, n, sum):\n m = dict()\n for i in range(n):\n if arr[i] in m.keys():\n m[arr[i]] += 1\n else:\n m[arr[i]] = 1\n twice_count = 0\n for i in range(0, n):\n if sum - arr[i] in m.keys():\n twice_count += m[sum - arr[i]]\n if sum - arr[i] == arr[i]:\n twice_count -= 1\n return int(twice_count / 2)", "def getpairscount(arr, n, k):\n count = 0\n hash = {}\n for i in range(n):\n if k - arr[i] in hash:\n count += hash[k - arr[i]]\n if arr[i] in hash:\n hash[arr[i]] += 1\n else:\n hash[arr[i]] = 1\n return count", "def getpairscount(arr, n, k):\n ct = 0\n freq = {}\n for i in range(0, n):\n if k - arr[i] in freq:\n ct += freq[k - arr[i]]\n freq[arr[i]] = 1 + freq.get(arr[i], 0)\n return ct", "def getpairscount(arr, n, k):\n hashmap = {}\n for i in arr:\n hashmap[i] = hashmap.get(i, 0) + 1\n count = 0\n for i in arr:\n b = k - i\n a = i\n if b in hashmap:\n count += hashmap[b]\n if b == a:\n count -= 1\n return count // 2", "from collections import defaultdict\n\ndef getpairscount(arr, n, k):\n d = defaultdict(int)\n ans = 0\n for a in arr:\n ans += d[k - a]\n d[a] += 1\n return ans", "def getpairscount(arr, n, k):\n from collections import Counter\n m = Counter()\n ans = 0\n for i in arr:\n if m[k - i]:\n ans += m[k - i]\n m[i] += 1\n return ans", "def getpairscount(arr, n, k):\n dict1 = {}\n c = 0\n for i in range(n):\n target = k - arr[i]\n if target in dict1:\n c += dict1[target]\n if arr[i] in dict1:\n dict1[arr[i]] += 1\n else:\n dict1[arr[i]] = 1\n return c", "def getpairscount(arr, n, k):\n pair_count = 0\n compliment_count_map = {}\n for num in arr:\n compliment = k - num\n if compliment in compliment_count_map:\n pair_count += compliment_count_map[compliment]\n if num in compliment_count_map:\n compliment_count_map[num] = compliment_count_map[num] + 1\n else:\n compliment_count_map[num] = 1\n return pair_count", "def getpairscount(arr, n, k):\n index = dict()\n pair = 0\n for i in range(n):\n if k > arr[i]:\n c = k - arr[i]\n if index.get(c) != None:\n pair = pair + index.get(c)\n index[arr[i]] = index.get(arr[i], 0) + 1\n return pair", "from collections import Counter\n\ndef getpairscount(arr, n, k):\n c = Counter(arr)\n ans = 0\n for num in arr:\n if k - num in c:\n ans += c[k - num]\n if k - num == num:\n ans -= 1\n return int(ans / 2)", "def getpairscount(arr, n, k):\n count = 0\n data = {}\n for i in arr:\n stored_data = data.get(k - i, 0)\n count += stored_data\n data[i] = data.get(i, 0) + 1\n return count", "def getpairscount(arr, n, k):\n hashm = {}\n cnt = 0\n for i in range(len(arr)):\n if arr[i] not in hashm:\n hashm[arr[i]] = 1\n else:\n hashm[arr[i]] += 1\n for i in range(len(arr)):\n elem = k - arr[i]\n if elem in hashm:\n cnt += hashm[elem]\n if elem == arr[i]:\n cnt -= 1\n return cnt // 2", "def getpairscount(arr, n, k):\n freq = {}\n pairs = 0\n for num in arr:\n if num in freq:\n freq[num] += 1\n else:\n freq[num] = 1\n for num in arr:\n complement = k - num\n if complement in freq:\n pairs += freq[complement]\n if num == complement:\n pairs -= 1\n return pairs // 2", "def getpairscount(arr, n, k):\n hashmap = {}\n pairs = 0\n for val in arr:\n if val in hashmap:\n hashmap[val] += 1\n else:\n hashmap[val] = 1\n for val in arr:\n if k - val in hashmap:\n pairs += hashmap[k - val]\n if val == k - val:\n pairs -= 1\n return int(pairs / 2)", "def getpairscount(arr, n, k):\n dist = {}\n pairs = 0\n for i in arr:\n if k - i in dist:\n pairs += dist[k - i]\n if i in dist:\n dist[i] += 1\n else:\n dist[i] = 1\n return pairs", "def getpairscount(arr, n, k):\n freq = dict()\n used_numbers = dict()\n ans = 0\n for i in range(0, n):\n if arr[i] in freq:\n freq[arr[i]] += 1\n else:\n freq[arr[i]] = 1\n for i in range(0, n):\n if arr[i] not in used_numbers:\n pair_two = k - arr[i]\n if pair_two == arr[i]:\n ans += freq[arr[i]] * (freq[arr[i]] - 1) // 2\n used_numbers[arr[i]] = 1\n continue\n if pair_two in freq:\n ans += freq[arr[i]] * freq[pair_two]\n used_numbers[pair_two] = 1\n used_numbers[arr[i]] = 1\n return ans", "def getpairscount(arr, n, k):\n dic_val = dict()\n pair = 0\n for i in range(len(arr)):\n if arr[i] >= k:\n continue\n pp = k - arr[i]\n if pp in dic_val:\n pair = pair + dic_val[pp]\n if arr[i] in dic_val:\n dic_val[arr[i]] = 1 + dic_val[arr[i]]\n else:\n dic_val[arr[i]] = 1\n elif arr[i] in dic_val:\n dic_val[arr[i]] = 1 + dic_val[arr[i]]\n else:\n dic_val[arr[i]] = 1\n return pair", "def getpairscount(arr, n, k):\n (dict, ans) = ({}, 0)\n for el in arr:\n if k - el in dict:\n ans += dict[k - el]\n if not el in dict:\n dict[el] = 1\n else:\n dict[el] += 1\n return ans", "import sys\n\ndef getpairscount(arr, n, k):\n a = {}\n sum = 0\n for i in range(len(arr)):\n if arr[i] not in a:\n a[arr[i]] = 0\n a[arr[i]] += 1\n for i in range(len(arr)):\n if k - arr[i] in a:\n sum = sum + a[k - arr[i]]\n if k - arr[i] == arr[i]:\n sum -= 1\n return int(sum / 2)", "def getpairscount(arr, n, k):\n freq = {}\n count = 0\n for i in range(len(arr)):\n if arr[i] not in freq:\n freq[arr[i]] = 0\n freq[arr[i]] += 1\n for i in range(len(arr)):\n complement = k - arr[i]\n if complement in freq:\n count += freq[complement]\n if complement == arr[i]:\n count -= 1\n return count // 2", "def getpairscount(arr, n, k):\n dict = {}\n pairs = 0\n arr = sorted(arr)\n for val in arr:\n if val in dict:\n dict[val] += 1\n else:\n dict[val] = 1\n for i in range(n):\n if k - arr[i] in dict:\n pairs += dict[k - arr[i]]\n if k - arr[i] == arr[i]:\n pairs -= 1\n return int(pairs / 2)", "def getpairscount(arr, n, k):\n d = {}\n count = 0\n for (i, e) in enumerate(arr):\n if k - e in d:\n count += d[k - e]\n if e in d:\n d[e] += 1\n else:\n d[e] = 1\n return count", "def getpairscount(arr, n, t):\n dic = {}\n for i in range(len(arr)):\n dic[arr[i]] = dic.get(arr[i], 0) + 1\n count = 0\n for (k, v) in dic.items():\n if t - k in dic:\n if k != t - k:\n count += v * dic[t - k]\n else:\n count += v * (v - 1)\n return count // 2", "from collections import defaultdict\n\ndef getpairscount(arr, n, k):\n visited = defaultdict(int)\n count = 0\n for x in arr:\n try:\n count += visited[k - x]\n except:\n pass\n visited[x] += 1\n return count", "def getpairscount(arr, n, k):\n mp = dict()\n c = 0\n for i in range(n):\n target = k - arr[i]\n if target in mp:\n c = c + mp[k - arr[i]]\n mp[arr[i]] = mp.get(arr[i], 0) + 1\n return c", "def getpairscount(arr, n, k):\n c = 0\n d = {}\n for a in arr:\n if k - a in d:\n c += d[k - a]\n if a in d:\n d[a] += 1\n else:\n d[a] = 1\n return c", "def getpairscount(arr, n, k):\n c = 0\n d = {}\n for (i, a) in enumerate(arr):\n if a in d:\n d[a].append(i)\n else:\n d[a] = [i]\n for (i, a) in enumerate(arr):\n if k - a in d:\n for j in d[k - a]:\n if j > i:\n c += 1\n return c", "def getpairscount(arr, n, k):\n x = {}\n ans = 0\n for i in arr:\n num = k - i\n if num in x:\n ans += x[num]\n try:\n x[i] += 1\n except:\n x[i] = 1\n return ans", "from collections import defaultdict\n\ndef getpairscount(arr, n, k):\n val_map = defaultdict(int)\n cnt = 0\n for num in arr:\n if val_map.get(k - num):\n cnt += val_map[k - num]\n val_map[num] += 1\n return cnt", "def getpairscount(arr, n, k):\n arr.sort()\n result = []\n i = 0\n j = n - 1\n while i < j:\n if arr[i] + arr[j] < k:\n i += 1\n elif arr[i] + arr[j] > k:\n j -= 1\n elif arr[i] != arr[j]:\n c1 = 0\n temp1 = arr[i]\n while arr[i] == temp1:\n i += 1\n c1 += 1\n c2 = 0\n temp2 = arr[j]\n while arr[j] == temp2:\n j -= 1\n c2 += 1\n for _ in range(0, c1 * c2):\n result.append((temp1, temp2))\n else:\n c3 = 0\n while arr[j] == arr[i]:\n j -= 1\n c3 += 1\n for _ in range(0, c3 * (c3 - 1) // 2):\n result.append((arr[i], arr[i]))\n return len(result)", "def getpairscount(arr, n, k):\n freq_map = {}\n for i in range(n):\n if arr[i] not in freq_map.keys():\n freq_map[arr[i]] = 1\n else:\n freq_map[arr[i]] += 1\n count = 0\n for i in range(n):\n diff = k - arr[i]\n if diff in freq_map.keys():\n count = count + freq_map[diff]\n if diff == arr[i]:\n count -= 1\n count = count // 2\n return count", "def getpairscount(arr, n, k):\n d = {}\n c = 0\n for i in arr:\n m = k - i\n if m in d:\n c += d[m]\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n return c", "def getpairscount(arr, n, k):\n s = dict()\n cnt = 0\n for i in range(n):\n temp = k - arr[i]\n if temp in s:\n cnt += s[temp]\n if arr[i] in s:\n s[arr[i]] += 1\n else:\n s[arr[i]] = 1\n return cnt", "from collections import defaultdict\n\ndef getpairscount(arr, n, k):\n (seen, count) = ({}, 0)\n for i in range(n):\n if k - arr[i] in seen:\n count += seen[k - arr[i]]\n seen[arr[i]] = seen.get(arr[i], 0) + 1\n return count\n\n def sum(i, arr, t):\n if t == 0:\n return 1\n if i == 0:\n if arr[0] == t:\n return 1\n return 0\n x = sum(i - 1, arr, t)\n y = 0\n if arr[i] <= t:\n y = sum(i - 1, arr, t - arr[i])\n return x + y\n return sum(n - 1, arr, k)", "def getpairscount(arr, n, k):\n m = {}\n ans = 0\n for i in range(n):\n if k - arr[i] in m:\n ans += m[k - arr[i]]\n m[arr[i]] = m.get(arr[i], 0) + 1\n return ans", "def getpairscount(arr, n, k):\n freq_dict = {}\n pair_count = 0\n for i in range(n):\n if k - arr[i] in freq_dict:\n pair_count += freq_dict[k - arr[i]]\n if arr[i] in freq_dict:\n freq_dict[arr[i]] += 1\n else:\n freq_dict[arr[i]] = 1\n return pair_count"], "starter_code": "def getpairscount(arr, n, k):\n", "input_output": {"inputs": ["N = 4, K = 6\r\narr[] = {1, 5, 7, 1}", "N = 4, K = 2\r\narr[] = {1, 1, 1, 1}"], "outputs": ["2", "6"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays", "Hash"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "getpairscount", "task_id": "TACO_lite/348", "example": [[[4, 6, [1, 5, 7, 1]], [4, 2, [1, 1, 1, 1]]], ["2", "6"]]} +{"requirement": "You are given a string representing an attendance record for a student. The record only contains the following three characters:\n\n\n\n'A' : Absent. \n'L' : Late.\n 'P' : Present. \n\n\n\n\nA student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). \n\nYou need to return whether the student could be rewarded according to his attendance record.\n\nExample 1:\n\nInput: \"PPALLP\"\nOutput: True\n\n\n\nExample 2:\n\nInput: \"PPALLL\"\nOutput: False", "solutions": ["def checkrecord(s):\n count = 0\n for i in range(0, len(s)):\n if s[i] == 'A':\n count += 1\n if count == 2:\n return False\n elif i >= 2 and s[i] == 'L' and (s[max(i - 1, 0)] == 'L') and (s[max(i - 2, 0)] == 'L'):\n return False\n return True", "def checkrecord(s):\n twoL = 0\n twoA = 0\n i = 0\n while i < len(s):\n if s[i] == 'A':\n twoA += 1\n if twoA > 1:\n return False\n twoL = 0\n elif s[i] == 'L':\n twoL += 1\n if twoL > 2:\n return False\n else:\n twoL = 0\n i += 1\n return True", "def checkrecord(s):\n if not s:\n return\n c = 0\n if s == 'AA':\n return False\n for i in range(len(s) - 2):\n if s[i] == 'L':\n if s[i] == s[i + 1] and s[i] == s[i + 2]:\n return False\n if s[i] == 'A':\n c += 1\n if c == 2:\n return False\n return True", "def checkrecord(s):\n return s.count('A') <= 1 and s.count('LLL') == 0", "def checkrecord(s):\n aCount = 0\n clCount = 0\n for r in s:\n if r == 'A':\n aCount += 1\n if aCount > 1:\n return False\n if r == 'L':\n clCount += 1\n if clCount > 2:\n return False\n else:\n clCount = 0\n return True", "def checkrecord(s):\n return s.count('A') < 2 and 'LLL' not in s", "def checkrecord(s):\n from collections import Counter\n val = Counter(s)\n idx = []\n for i in range(len(s)):\n if s[i] == 'L':\n idx.append(i)\n for j in range(len(idx) - 2):\n if idx[j + 2] - idx[j] == 2:\n return False\n if val['A'] > 1:\n return False\n return True", "def checkrecord(s):\n charA = charL = 0\n for c in s:\n if c == 'A':\n charA += 1\n if charA > 1:\n return False\n charL = 0\n elif c == 'L':\n charL += 1\n if charL > 2:\n return False\n else:\n charL = 0\n return True", "def checkrecord(s):\n mydir = {}\n for record in s:\n mydir[record] = mydir.get(record, 0) + 1\n return mydir.get('A', 0) <= 1 and s.count('LLL') == 0"], "starter_code": "def checkrecord(s: str) -> bool:\n", "input_output": {"fn_name": "checkRecord", "inputs": [["\"PPALLP\""]], "outputs": [true]}, "difficulty": "EASY", "raw_tags": ["String"], "name": null, "source": "leetcode", "tags": ["String algorithms"], "skill_types": [], "url": "https://leetcode.com/problems/student-attendance-record-i/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "checkrecord", "task_id": "TACO_lite/340", "example": [[["PPALLP"], ["PPALLL"]], ["True", "False"]]} +{"requirement": "We are given the head node root of a binary tree, where additionally every node's value is either a 0 or a 1.\nReturn the same tree where every subtree (of the given tree) not containing a 1 has been removed.\n(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)\nExample 1:\nInput: [1,null,0,0,1]\nOutput: [1,null,0,null,1]\n \nExplanation: \nOnly the red nodes satisfy the property \"every subtree not containing a 1\".\nThe diagram on the right represents the answer.\n\n\n\nExample 2:\nInput: [1,0,1,0,0,0,1]\nOutput: [1,null,1,null,1]\n\n\n\n\nExample 3:\nInput: [1,1,0,1,1,0,1,0]\nOutput: [1,1,0,1,1,null,1]\n\n\n\n\nNote: \n\nThe binary tree will have at most 200 nodes.\nThe value of each node will only be 0 or 1.", "solutions": ["def pruneTreeHelper(root: TreeNode) -> TreeNode:\n if not root:\n return None\n left = self.pruneTreeHelper(root.left)\n right = self.pruneTreeHelper(root.right)\n if not left:\n root.left = None\n if not right:\n root.right = None\n if root.val == 0 and root.right is None and (root.left is None):\n return None\n else:\n return root\n\ndef pruneTree(root: TreeNode) -> TreeNode:\n return self.pruneTreeHelper(root)", "def pruneTree(root: TreeNode) -> TreeNode:\n if not root:\n return None\n root.left = self.pruneTree(root.left)\n root.right = self.pruneTree(root.right)\n if not root.left and (not root.right) and (root.val == 0):\n return None\n return root", "def pruneTree(root: TreeNode) -> TreeNode:\n\n def prune(node: TreeNode) -> bool:\n if not node:\n return True\n left_prune = prune(node.left)\n right_prune = prune(node.right)\n if prune(node.left):\n node.left = None\n if prune(node.right):\n node.right = None\n return node.val == 0 and left_prune and right_prune\n if prune(root):\n return None\n return root", "def pruneTree(root: TreeNode) -> TreeNode:\n\n def check(node):\n if not node.left:\n l = True\n else:\n l = check(node.left)\n if not node.right:\n r = True\n else:\n r = check(node.right)\n if l:\n node.left = None\n if r:\n node.right = None\n return l and r and (node.val == 0)\n ans = TreeNode()\n ans.right = root\n check(ans)\n return ans.right", "def pruneTree(root: TreeNode) -> TreeNode:\n\n def dfs(node):\n if not node:\n return False\n a1 = dfs(node.left)\n a2 = dfs(node.right)\n if not a1:\n node.left = None\n if not a2:\n node.right = None\n return node.val == 1 or a1 or a2\n return root if dfs(root) else None", "def pruneTree(root: TreeNode) -> TreeNode:\n\n def prune_tree_helper(root):\n if root:\n curr_res = True if root.val == 0 else False\n left_res = prune_tree_helper(root.left)\n right_res = prune_tree_helper(root.right)\n if left_res:\n root.left = None\n if right_res:\n root.right = None\n return curr_res and left_res and right_res\n else:\n return True\n res = prune_tree_helper(root)\n if res:\n return None\n else:\n return root", "def pruneTree(root: TreeNode) -> TreeNode:\n return root if self.dfs(root) else None\n\ndef dfs(root):\n if not root:\n return False\n l = self.dfs(root.left)\n r = self.dfs(root.right)\n if not l:\n root.left = None\n if not r:\n root.right = None\n return root.val == 1 or l or r", "def pruneTree(root: TreeNode) -> TreeNode:\n\n def helper(root):\n if not root:\n return False\n lone = helper(root.left)\n rone = helper(root.right)\n if not lone:\n root.left = None\n if not rone:\n root.right = None\n if root.val == 1 or lone or rone:\n return True\n else:\n return False\n if helper(root):\n return root\n else:\n return None", "def pruneTree(root: TreeNode) -> TreeNode:\n if root == None:\n return None\n left_sub = self.pruneTree(root.left)\n right_sub = self.pruneTree(root.right)\n if root.val == 0 and left_sub == None and (right_sub == None):\n return None\n root.left = left_sub\n root.right = right_sub\n return root"], "starter_code": "def __init__(val=0, left=None, right=None):\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Binary Tree", "Tree", "Depth-First Search"], "name": null, "source": "leetcode", "tags": ["Tree algorithms", "Graph traversal"], "skill_types": [], "url": "https://leetcode.com/problems/binary-tree-pruning/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "__init__", "task_id": "TACO_lite/370", "example": [[], []]} +{"requirement": "Given a string S, remove all consonants and print the modified string that contains vowels only.\nExample 1:\nInput\nS = \"abEkipo\"\nOutput\naEio\nExplanation : a, E, i, o are only vowels in the string.\nExample 2:\nInput\nS = \"rrty\"\nOutput\nNo Vowel\nExplanation: There are no vowels.\nYour Task: You don't need to read input or print anything.Your task is to complete the function removeConsonants() which takes a string as input parameters, and returns the modified string that contains vowels only. If there is no vowel present in the string S, then return \"No Vowel\".\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1).\nConstraints\n1 <= |S| <= 10^{5}\nThe string should consist of only alphabets.", "solutions": ["def removeconsonants(s):\n p = ''\n a = 0\n for i in s:\n if i in ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']:\n p += i\n a = a + 1\n if a == 0:\n return 'No Vowel'\n else:\n return p", "def removeconsonants(s):\n str1 = ''\n n = 'No Vowel'\n for i in range(len(s)):\n if s[i] == 'A' or s[i] == 'a':\n str1 = str1 + s[i]\n elif s[i] == 'E' or s[i] == 'e':\n str1 = str1 + s[i]\n elif s[i] == 'I' or s[i] == 'i':\n str1 = str1 + s[i]\n elif s[i] == 'O' or s[i] == 'o':\n str1 = str1 + s[i]\n elif s[i] == 'U' or s[i] == 'u':\n str1 = str1 + s[i]\n else:\n str1 = str1 + ''\n if len(str1) > 0:\n return str1\n else:\n return n", "def removeconsonants(s):\n k = ''\n for i in s:\n if i in 'aeiouAEIOU':\n k += i\n if len(k) == 0:\n return 'No Vowel'\n return k", "def removeconsonants(s):\n vowels = 'aeiouAEIOU'\n c = []\n for i in s:\n if i in vowels:\n c.append(i)\n if len(c) == 0:\n return 'No Vowel'\n else:\n c = ''.join(c)\n return c", "def removeconsonants(s):\n vowels = 'AaEeIiOoUu'\n i = 0\n while i < len(s):\n if s[i] not in vowels:\n s = s.replace(s[i], '')\n if len(s) <= 0:\n return 'No Vowel'\n else:\n i += 1\n if len(s) <= 0:\n return 'No Vowel'\n return s", "def removeconsonants(s):\n vowel = []\n cons = ''\n source = 'aeiouAEIOU'\n for i in s:\n if i in source:\n vowel.append(i)\n return ''.join(vowel) if vowel else 'No Vowel'", "def removeconsonants(s):\n ans = ''\n vovel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n for i in s:\n if i in vovel:\n ans += i\n if len(ans) == 0:\n return 'No Vowel'\n else:\n return ans", "def removeconsonants(s):\n v = ''\n for i in s:\n if i in 'aeiouAEIOU':\n v += i\n if v == '':\n return 'No Vowel'\n else:\n return v", "def removeconsonants(s):\n l1 = []\n for i in s:\n j = i.lower()\n if j in {'a', 'e', 'i', 'o', 'u'}:\n l1.append(i)\n if l1 == []:\n return 'No Vowel'\n else:\n return ''.join(l1)", "def removeconsonants(s):\n result = ''\n for i in range(len(s)):\n if s[i] in ('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'):\n result += s[i]\n if len(result) != 0:\n return result\n return 'No Vowel'", "def removeconsonants(s):\n l = []\n for i in s:\n if i == 'A' or i == 'E' or i == 'I' or (i == 'O') or (i == 'U') or (i == 'a') or (i == 'e') or (i == 'i') or (i == 'o') or (i == 'u'):\n l.append(i)\n s1 = ''.join(map(str, l))\n if len(s1) == 0:\n return 'No Vowel'\n else:\n return s1", "def removeconsonants(s):\n d = [i for i in s if i in 'aeiouAEIOU']\n return ''.join(d) if len(d) > 0 else 'No Vowel'", "def removeconsonants(s):\n l = []\n v = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'O', 'I', 'U']\n for i in s:\n if i in v:\n l.append(i)\n if len(l) == 0:\n return 'No Vowel'\n else:\n r = ''.join(l)\n return r", "def removeconsonants(s):\n x = ''\n a = 'aeiou'\n b = a.upper()\n for i in s:\n if i in a or i in b:\n x += i\n if x == '':\n return 'No Vowel'\n else:\n return x", "def removeconsonants(s):\n s1 = ''\n for i in s:\n if i in 'aeiouAEIOU':\n s1 += i\n if s1 == '':\n return 'No Vowel'\n return s1", "def removeconsonants(s):\n res = []\n for i in range(len(s)):\n if s[i] in 'aeiouAEIOU':\n res.extend(s[i])\n if len(res) > 0:\n return ''.join(res)\n else:\n return 'No Vowel'", "def removeconsonants(s):\n a = ''\n for i in s:\n if i.lower() in 'aeiou':\n a += i\n return a if a else 'No Vowel'", "def isvowel(c):\n return c == 'a' or c == 'e' or c == 'i' or (c == 'o') or (c == 'u') or (c == 'A') or (c == 'E') or (c == 'I') or (c == 'O') or (c == 'U')\n\ndef removeconsonants(s):\n x = ''\n for i in s:\n if self.isvowel(i):\n x += i\n if len(x) == 0:\n return 'No Vowel'\n return x", "def removeconsonants(s):\n x = ''\n lst = ['a', 'e', 'i', 'o', 'u']\n for i in s:\n if i.lower() in lst:\n x += i\n if len(x) == 0:\n return 'No Vowel'\n return x", "def removeconsonants(s):\n k = 'aeiouAEIOU'\n st = ''\n for i in range(len(s)):\n if s[i] in k:\n st = st + s[i]\n if st == '':\n return 'No Vowel'\n else:\n return st", "def removeconsonants(s):\n d = ''\n for i in s:\n l = i.lower()\n if l == 'a' or l == 'e' or l == 'i' or (l == 'u') or (l == 'o'):\n d += i\n if len(d) == 0:\n return 'No Vowel'\n else:\n return d", "def removeconsonants(s):\n consonants = set(['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z'])\n without_cons = [char for char in s if char not in consonants]\n if all((char in consonants for char in s)):\n return 'No Vowel'\n return ''.join(without_cons)", "def removeconsonants(s):\n ch = ''\n for i in s:\n if i in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'U', 'O', 'I']:\n ch = ch + i\n if ch:\n return ch\n return 'No Vowel'", "def removeconsonants(s):\n vowels = ['a', 'e', 'i', 'o', 'u']\n ans = ''\n for i in s:\n if i.lower() in vowels:\n ans += i\n if ans == '':\n return 'No Vowel'\n return ans", "def removeconsonants(s):\n v = 'aeiouAEIOU'\n outStr = ''\n for i in s:\n if i in v:\n outStr += i\n if len(outStr) == 0:\n return 'No Vowel'\n else:\n return outStr", "def removeconsonants(s):\n a = list(s)\n count = 0\n length = len(a)\n vowels = ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']\n v = []\n for i in range(len(a)):\n if a[i] in vowels:\n v.append(a[i])\n flag = 1\n elif a[i] not in vowels:\n count += 1\n w = ''\n for j in range(len(v)):\n w += v[j]\n if count == length:\n return 'No Vowel'\n else:\n return w", "def removeconsonants(s):\n vowel = 'aeiouAEIOU'\n a = ''\n for i in s:\n if i in vowel:\n a += i\n if len(a) == 0:\n return 'No Vowel'\n return a", "def removeconsonants(s):\n str = ''\n R = 'No Vowel'\n vowels_of_list = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']\n for index in s:\n if index in vowels_of_list:\n str += index\n if len(str) == 0:\n return R\n else:\n return str", "def removeconsonants(s):\n s1 = ''\n for ele in s:\n if ele == 'a' or ele == 'e' or ele == 'i' or (ele == 'o') or (ele == 'u') or (ele == 'A') or (ele == 'E') or (ele == 'I') or (ele == 'O') or (ele == 'U'):\n s1 += ele\n if len(s1) == 0:\n return 'No Vowel'\n else:\n return s1", "def removeconsonants(s):\n str2 = ''\n for i in range(len(s)):\n if s[i] in 'aeiouAEIOU':\n str2 += s[i]\n if len(str2) == 0:\n return 'No Vowel'\n else:\n return str2", "def removeconsonants(s):\n vowels = 'aeiouAEIOU'\n ans = ''\n for i in s:\n if i in vowels:\n ans += i\n if ans == '':\n return 'No Vowel'\n return ans", "def removeconsonants(s):\n vov = 'aeiouAEIOU'\n new = ''\n for i in s:\n if i in vov:\n new += i\n if len(new) == 0:\n return 'No Vowel'\n else:\n return new", "def removeconsonants(s):\n k = ''\n vow = ['a', 'e', 'i', 'o', 'u']\n for i in s:\n r = i.lower()\n if r in vow:\n k += i\n if k == '':\n return 'No Vowel'\n return k", "def removeconsonants(s):\n a = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n i = 0\n s1 = ''\n while i < len(s):\n if s[i] in a:\n s1 += s[i]\n i += 1\n return s1 if len(s1) != 0 else 'No Vowel'", "def removeconsonants(s):\n li = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n str = ''\n for i in s:\n if i in li:\n str += i\n if str == '':\n return 'No Vowel'\n else:\n return str", "def removeconsonants(s):\n vovel = 'aeiouAEIOU'\n result = ''\n for i in s:\n if i in vovel:\n result += i\n if len(result) > 0:\n return result\n else:\n return 'No Vowel'", "def removeconsonants(s):\n list1 = []\n for i in s:\n if i == 'a' or i == 'e' or i == 'i' or (i == 'o') or (i == 'u') or (i == 'A') or (i == 'E') or (i == 'I') or (i == 'O') or (i == 'U'):\n list1.append(i)\n if len(list1) > 0:\n return ''.join(list1)\n else:\n return 'No Vowel'", "def removeconsonants(s):\n st = ''\n for i in s:\n if i.lower() in ['a', 'e', 'i', 'o', 'u']:\n st += i\n if st == '':\n return 'No Vowel'\n else:\n return st", "def removeconsonants(s):\n b = ['A', 'E', 'I', 'O', 'U']\n ans = ''\n for i in s:\n if i.upper() in b:\n ans += i\n if len(ans) == 0:\n return 'No Vowel'\n return ans", "def removeconsonants(s):\n temp = ''\n for i in s:\n if i in 'AEIOU' or i in 'aeiou':\n temp += i\n if len(temp) > 0:\n return temp\n else:\n return 'No Vowel'", "def removeconsonants(s):\n vowels = 'aeoui'\n vowels += vowels.upper()\n res = ''\n for i in s:\n if i in vowels:\n res += i\n if len(res) > 0:\n return res\n return 'No Vowel'", "def removeconsonants(s):\n a = []\n for i in s:\n if i in 'aeiouAEIOU':\n a.append(i)\n m = ''.join(a)\n if len(m) == 0:\n return 'No Vowel'\n else:\n return m", "def removeconsonants(s):\n l = ''\n k = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n a = list(s)\n for i in range(len(a)):\n if a[i] in k:\n l += a[i]\n else:\n continue\n if len(l) >= 1:\n return l\n else:\n return 'No Vowel'", "def removeconsonants(s):\n v = 'aeiouAEIOU'\n a = ''\n for i in s:\n if i in v:\n a += i\n if len(a) >= 1:\n return a\n return 'No Vowel'", "def removeconsonants(s):\n vowels = 'aeiou'\n v = ''\n for i in s:\n temp = i.lower()\n if temp in vowels:\n v += i\n if len(v) < 1:\n return 'No Vowel'\n else:\n return v", "import re\n\ndef removeconsonants(s):\n pat = re.findall('[aeiouAEIOU]+', s)\n if pat:\n return ''.join(pat)\n return 'No Vowel'", "def removeconsonants(s):\n j = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n c = []\n for i in s:\n if i in j:\n c.append(i)\n return ''.join(c) or 'No Vowel'", "def removeconsonants(s):\n x = 'aeiouAEIOU'\n ans = ''\n for i in s:\n if i in x:\n ans += i\n return ans if len(ans) != 0 else 'No Vowel'", "def removeconsonants(s):\n vowel_list = ['a', 'e', 'i', 'o', 'u']\n response_str = ''\n for char in s:\n if char.lower() in vowel_list:\n response_str = response_str + char\n if response_str:\n return response_str\n else:\n return 'No Vowel'", "def removeconsonants(s):\n v = 'aeiouAEIOU'\n newstring = ''\n for i in s:\n if i in v:\n newstring += i\n if len(newstring):\n return newstring\n return 'No Vowel'", "def removeconsonants(s):\n temp = 'aeiouEIOUA'\n ans = ''\n for i in s:\n if i in temp:\n ans = ans + i\n if len(ans) == 0:\n return 'No Vowel'\n return ans", "def removeconsonants(s):\n d = ''\n a = 'AEIOUaeiou'\n for i in s:\n if i in a:\n d = d + i\n if len(d) == 0:\n return 'No Vowel'\n else:\n return d", "def removeconsonants(s):\n if 'a' not in s and 'e' not in s and ('i' not in s) and ('o' not in s) and ('u' not in s) and ('A' not in s) and ('E' not in s) and ('I' not in s) and ('O' not in s) and ('U' not in s):\n return 'No Vowel'\n ans = ''\n for i in s:\n if i == 'a' or i == 'e' or i == 'i' or (i == 'o') or (i == 'u') or (i == 'A') or (i == 'E') or (i == 'I') or (i == 'O') or (i == 'U'):\n ans += i\n return ans", "def removeconsonants(S):\n consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'\n new_str = ''\n for i in range(len(S)):\n if S[i] not in consonants:\n new_str += S[i]\n if len(new_str) == 0:\n return 'No Vowel'\n else:\n return new_str", "def removeconsonants(s):\n c = ''\n v = 'aeiouAEIOU'\n l = list(s)\n for i in l:\n if i in v:\n c += i\n if len(c) > 0:\n return c\n else:\n return 'No Vowel'", "def removeconsonants(s):\n new = ''\n vow = 'aeiou'\n for i in s:\n if i.lower() in vow:\n new += i\n if new:\n return new\n else:\n return 'No Vowel'", "def removeconsonants(s):\n x = 'aeiouAEIOU'\n y = ''\n for i in range(len(s)):\n if s[i] in x:\n y = y + s[i]\n if y == '':\n return 'No Vowel'\n else:\n return y", "def removeconsonants(s):\n st = ''\n for i in range(len(s)):\n if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or (s[i] == 'o') or (s[i] == 'u') or (s[i] == 'A') or (s[i] == 'E') or (s[i] == 'I') or (s[i] == 'O') or (s[i] == 'U'):\n st += s[i]\n if st == '':\n return 'No Vowel'\n else:\n return st", "def removeconsonants(s):\n vowels = 'aeiouAEIOU'\n str = ''\n for x in s:\n if x in vowels:\n str += x\n if str == '':\n return 'No Vowel'\n else:\n return str", "def removeconsonants(s):\n k = ''\n m = 'No Vowel'\n x = ['a', 'A', 'e', 'E', 'i', 'I', 'O', 'o', 'U', 'u']\n for i in s:\n if i in x:\n k = k + i\n if len(k) != 0:\n return k\n else:\n return m", "def removeconsonants(s):\n str2 = ''\n vovels = 'aeiouAEIOU'\n for i in s:\n if i in vovels:\n str2 += i\n if len(str2) < 1:\n return 'No Vowel'\n else:\n return str2", "def removeconsonants(s):\n vowels = 'aeiouAEIOU'\n new_string = ''\n for i in s:\n if i in vowels:\n new_string += i\n if len(new_string) > 0:\n return new_string\n else:\n return 'No Vowel'"], "starter_code": "def removeconsonants(s):\n", "input_output": {"inputs": ["S = \"abEkipo\"", "S = \"rrty\""], "outputs": ["aEio", "No Vowel"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Searching", "Algorithms"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/c-program-to-remove-consonants-from-a-string1945/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|).", "entry_point": "removeconsonants", "task_id": "TACO_lite/419", "example": [[], []]} +{"requirement": "Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.\n \nExample 1:\nInput: s = \"eleetminicoworoep\"\nOutput: 13\nExplanation: The longest substring is \"leetminicowor\" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.\n\nExample 2:\nInput: s = \"leetcodeisgreat\"\nOutput: 5\nExplanation: The longest substring is \"leetc\" which contains two e's.\n\nExample 3:\nInput: s = \"bcbcbc\"\nOutput: 6\nExplanation: In this case, the given string \"bcbcbc\" is the longest because all vowels: a, e, i, o and u appear zero times.\n\n \nConstraints:\n\n1 <= s.length <= 5 x 10^5\ns contains only lowercase English letters.", "solutions": ["def findthelongestsubstring(s: str) -> int:\n s = s + 'a'\n (bits, dp) = ({'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}, {0: -1})\n res = 0\n key = 0\n for (i, char) in enumerate(s):\n if char in bits:\n if key in dp:\n res = max(res, i - dp[key] - 1)\n key = key ^ 1 << bits[char]\n if key not in dp:\n dp[key] = i\n return res", "def findthelongestsubstring(s: str) -> int:\n for i in range(len(s), 0, -1):\n for j in range(len(s) - i + 1):\n sub = s[j:j + i]\n has_odd_vowel = False\n for vowel in ['a', 'e', 'i', 'o', 'u']:\n if sub.count(vowel) % 2 != 0:\n has_odd_vowel = True\n break\n if not has_odd_vowel:\n return i\n return 0", "def findthelongestsubstring(s):\n seen = {0: -1}\n res = cur = 0\n for (i, c) in enumerate(s):\n cur ^= 1 << 'aeiou'.find(c) + 1 >> 1\n seen.setdefault(cur, i)\n res = max(res, i - seen[cur])\n return res", "def findthelongestsubstring(s: str) -> int:\n seen = {0: -1}\n ans = cur = 0\n for (i, c) in enumerate(s):\n cur ^= 1 << 'aeiou'.find(c) + 1 >> 1\n seen.setdefault(cur, i)\n ans = max(ans, i - seen[cur])\n return ans", "def findthelongestsubstring(s: str) -> int:\n vowels = {x: 1 << i for (i, x) in enumerate('aeiou')}\n fst = {0: -1}\n ans = mask = 0\n for (i, c) in enumerate(s):\n if c in vowels:\n mask ^= vowels[c]\n fst.setdefault(mask, i)\n ans = max(ans, i - fst[mask])\n return ans", "import collections\n\ndef findthelongestsubstring(s: str) -> int:\n for substr_len in range(len(s), -1, -1):\n end_remove = len(s) - substr_len + 1\n for start in range(end_remove):\n even = True\n sub_str = s[start:start + substr_len]\n for vowel in 'aeiou':\n if sub_str.count(vowel) % 2 != 0:\n even = False\n break\n if even == True:\n return substr_len", "def findthelongestsubstring(s: str) -> int:\n P = [0]\n vowels = 'aeiou'\n for c in s:\n i = vowels.find(c)\n mask = 1 << i if i != -1 else 0\n P.append(P[-1] ^ mask)\n ans = 0\n fst = {}\n for (i, p) in enumerate(P):\n if p in fst:\n h = fst[p]\n ans = max(ans, i - h)\n fst.setdefault(p, i)\n return ans", "def findthelongestsubstring(s: str) -> int:\n\n def countVowels(ct):\n if not ct['a'] % 2 and (not ct['e'] % 2) and (not ct['i'] % 2) and (not ct['o'] % 2) and (not ct['u'] % 2):\n return True\n return False\n for i in range(len(s)):\n ctr = collections.Counter(s[:len(s) - i])\n for j in range(i + 1):\n if j != 0:\n ctr[s[j - 1]] -= 1\n ctr[s[len(s) + j - i - 1]] += 1\n if countVowels(ctr):\n return sum(ctr.values())\n return 0", "def findthelongestsubstring(s: str) -> int:\n seen = {0: -1}\n ret = curr = 0\n for (i, c) in enumerate(s):\n curr ^= 1 << 'aeiou'.find(c) + 1 >> 1\n if curr not in seen:\n seen[curr] = i\n ret = max(ret, i - seen[curr])\n return ret", "def findthelongestsubstring(s: str) -> int:\n bits = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n seen = {0: -1}\n max_val = 0\n cur = 0\n for (i, char) in enumerate(s):\n if char in bits:\n cur ^= bits[char]\n seen.setdefault(cur, i)\n max_val = max(max_val, i - seen[cur])\n return max_val", "def findthelongestsubstring(s: str) -> int:\n m = dict(a=1, e=2, i=4, o=8, u=16)\n longest = 0\n parity_index = {0: -1}\n parity = 0\n for (i, ch) in enumerate(s):\n parity = parity ^ m.get(ch, 0)\n if parity not in parity_index:\n parity_index[parity] = i\n longest = max(longest, i - parity_index.get(parity))\n return longest", "def findthelongestsubstring1(s: str) -> int:\n\n def check(L, R, cnt_memo):\n if L > R:\n return 0\n elif (L, R) in memo:\n return memo[L, R]\n elif all((v % 2 == 0 for v in list(cnt_memo.values()))):\n return R - L + 1\n else:\n old_L = L\n new_memo = {k: v for (k, v) in list(cnt_memo.items())}\n while s[L] not in 'aeiou':\n L += 1\n new_memo[s[L]] -= 1\n if new_memo[s[L]] == 0:\n del new_memo[s[L]]\n res1 = check(L + 1, R, new_memo)\n L = old_L\n old_R = R\n new_memo = {k: v for (k, v) in list(cnt_memo.items())}\n while s[R] not in 'aeiou':\n R -= 1\n new_memo[s[R]] -= 1\n if new_memo[s[R]] == 0:\n del new_memo[s[R]]\n res2 = check(L, R - 1, new_memo)\n R = old_R\n res = max(res1, res2)\n memo[L, R] = res\n return res\n cnt_memo = collections.Counter(s)\n cnt_memo = {k: v for (k, v) in list(cnt_memo.items()) if k in 'aeiou'}\n memo = dict()\n res = check(0, len(s) - 1, cnt_memo)\n return res\n\ndef findthelongestsubstring(s: str) -> int:\n res = 0\n curr = 0\n memo = dict()\n memo[0] = -1\n for (i, c) in enumerate(s):\n if c == 'a':\n curr ^= 1\n elif c == 'e':\n curr ^= 2\n elif c == 'i':\n curr ^= 4\n elif c == 'o':\n curr ^= 8\n elif c == 'u':\n curr ^= 16\n if curr in memo:\n res = max(res, i - memo[curr])\n else:\n memo[curr] = i\n return res\n return", "def findthelongestsubstring(s: str) -> int:\n vowel_dict = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n integrals = [(False, False, False, False, False)]\n for l in s:\n vector = list(integrals[-1])\n if l in vowel_dict:\n vector[vowel_dict[l]] = not vector[vowel_dict[l]]\n integrals.append(tuple(vector))\n seen = {}\n res = 0\n for (i, v) in enumerate(integrals):\n if v in seen:\n res = max(res, i - seen[v])\n else:\n seen[v] = i\n return res", "def findthelongestsubstring(s: str) -> int:\n max_substring_size = 0\n processed_cons = None\n s_len = len(s)\n for i in range(s_len):\n if processed_cons == True:\n if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or (s[i] == 'o') or (s[i] == 'u'):\n processed_cons = False\n continue\n if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or (s[i] == 'o') or (s[i] == 'u'):\n processed_cons = False\n else:\n processed_cons = True\n if max_substring_size > s_len - i:\n break\n vowel_counts = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}\n allEven = True\n for (k, letter) in enumerate(s[i:]):\n if letter in vowel_counts:\n vowel_counts[letter] += 1\n currently_all_even = True\n for count in list(vowel_counts.values()):\n if count % 2 == 1:\n currently_all_even = False\n break\n allEven = currently_all_even\n if allEven and k + 1 > max_substring_size:\n max_substring_size = k + 1\n return max_substring_size", "from copy import copy\n\ndef findthelongestsubstring(s: str) -> int:\n vowel2idx = dict([(item[1], item[0]) for item in enumerate(['a', 'e', 'i', 'o', 'u'])])\n counters = [0]\n for item in s:\n counters.append(counters[-1])\n if item in vowel2idx:\n counters[-1] ^= 2 ** vowel2idx[item]\n for width in range(len(s), 0, -1):\n for start in range(len(s) - width + 1):\n if counters[start + width] ^ counters[start] != 0:\n continue\n return width\n return 0", "def findthelongestsubstring(s: str) -> int:\n (vowels, bits, dp) = ({'a', 'e', 'i', 'o', 'u'}, {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}, {0: -1})\n (res, odds) = (0, set())\n for i in range(len(s)):\n if s[i] in vowels:\n if s[i] in odds:\n odds.discard(s[i])\n else:\n odds.add(s[i])\n key = 0\n for o in odds:\n key |= 1 << bits[o]\n if key in dp:\n res = max(res, i - dp[key])\n else:\n dp[key] = i\n return res", "def findthelongestsubstring(s: str) -> int:\n states = [(False, False, False, False, False)]\n seen = {}\n mapping = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n for i in range(len(s)):\n vector = list(states[-1])\n character = s[i]\n if character in mapping:\n vector[mapping[character]] = not vector[mapping[character]]\n states.append(tuple(vector))\n res = 0\n for (i, v) in enumerate(states):\n if v in seen:\n res = max(res, i - seen[v])\n else:\n seen[v] = i\n return res", "def findthelongestsubstring(s: str) -> int:\n mask = 0\n mp = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n seen = [len(s)] * 63\n seen[0] = -1\n max_len = 0\n for i in range(len(s)):\n if s[i] in 'aeiou':\n mask ^= 1 << mp[s[i]]\n seen[mask] = min(seen[mask], i)\n max_len = max(max_len, i - seen[mask])\n return max_len", "def findthelongestsubstring(s: str) -> int:\n left_states = {'': -1}\n cur_state = set()\n ans = 0\n for (i, char) in enumerate(s):\n if char in 'aeiou':\n if char in cur_state:\n cur_state.remove(char)\n else:\n cur_state.add(char)\n cur_state_str = ''.join(sorted(list(cur_state)))\n if cur_state_str in left_states:\n ans = max(ans, i - left_states[cur_state_str])\n else:\n left_states[cur_state_str] = i\n return ans", "def findthelongestsubstring(s: str) -> int:\n mask = '00000'\n table = dict()\n table[mask] = -1\n vowels = 'aeiou'\n res = 0\n for (i, c) in enumerate(s):\n for j in range(5):\n if c == vowels[j]:\n mask1 = list(mask)\n mask1[j] = str(1 - int(mask1[j]))\n mask = ''.join(mask1)\n pre_idx = table.get(mask, -2)\n if pre_idx != -2:\n res = max(res, i - pre_idx)\n else:\n table[mask] = i\n return res", "def findthelongestsubstring(s: str) -> int:\n cur = 0\n res = 0\n seen = {}\n seen[0] = -1\n for (i, c) in enumerate(s):\n cur ^= 1 << 'aeiou'.find(c) + 1 >> 1\n if cur not in seen:\n seen[cur] = i\n res = max(res, i - seen[cur])\n return res", "def findthelongestsubstring(s: str) -> int:\n bits = {'a': 1, 'e': 2, 'i': 3, 'o': 4, 'u': 5}\n dp = {0: -1}\n (ans, state) = (0, 0)\n for (i, c) in enumerate(s):\n if c in bits:\n state ^= 1 << bits[c]\n ans = max(ans, i - dp.get(state, 128))\n dp[state] = min(dp.get(state, 128), i)\n return ans", "def findthelongestsubstring(s: str) -> int:\n current = [0, 0, 0, 0, 0]\n\n def convertToInteger():\n nonlocal current\n binarySum = 0\n for num in current:\n binarySum *= 2\n binarySum += num\n return binarySum\n\n def incrementVowels(char):\n nonlocal current\n if char == 'a':\n current[0] = 1 - current[0]\n elif char == 'e':\n current[1] = 1 - current[1]\n elif char == 'i':\n current[2] = 1 - current[2]\n elif char == 'o':\n current[3] = 1 - current[3]\n elif char == 'u':\n current[4] = 1 - current[4]\n earliest = {}\n earliest[0] = -1\n maxLength = 0\n current = [0, 0, 0, 0, 0]\n for (index, char) in enumerate(s):\n incrementVowels(char)\n binarySum = convertToInteger()\n if binarySum not in earliest:\n earliest[binarySum] = index\n else:\n maxLength = max(index - earliest[binarySum], maxLength)\n return maxLength", "def findthelongestsubstring(s: str) -> int:\n vowels = {'a': 1, 'e': 2, 'i': 3, 'o': 4, 'u': 5}\n seen = {0: -1}\n res = cur = 0\n for (i, c) in enumerate(s):\n if c in vowels:\n cur ^= 1 << vowels[c]\n seen.setdefault(cur, i)\n res = max(res, i - seen[cur])\n return res", "def findthelongestsubstring(s: str) -> int:\n remainder_pos_dict = dict()\n vowels = {'a', 'e', 'i', 'o', 'u'}\n vowel_count = {ch: 0 for ch in vowels}\n max_length = 0\n for (pos, ch) in enumerate(s):\n if ch in vowels:\n vowel_count[ch] += 1\n remainders = (vowel_count['a'] % 2, vowel_count['e'] % 2, vowel_count['i'] % 2, vowel_count['o'] % 2, vowel_count['u'] % 2)\n if all(map(lambda x: x == 0, remainders)):\n max_length = max(max_length, pos + 1)\n continue\n if remainders not in remainder_pos_dict:\n remainder_pos_dict[remainders] = pos\n continue\n prefix_tail = remainder_pos_dict[remainders]\n length = pos - prefix_tail\n max_length = max(length, max_length)\n return max_length", "def flip(num, pos):\n if num & 2 ** pos:\n return num - 2 ** pos\n else:\n return num + 2 ** pos\n\ndef findthelongestsubstring(s: str) -> int:\n hash = {(0, 0, 0, 0, 0): [-1]}\n maxLen = 0\n count = {'a': 0, 'e': 0, 'i': 0, 'u': 0, 'o': 0}\n for i in range(len(s)):\n if s[i] in count:\n count[s[i]] = (count[s[i]] + 1) % 2\n set = tuple(count.values())\n if set in hash:\n hash[set].extend([i])\n else:\n hash[set] = [i]\n if len(hash[set]) >= 2:\n maxLen = max(maxLen, hash[set][-1] - hash[set][0])\n return maxLen", "def findthelongestsubstring(s: str) -> int:\n first_position = {(0, 0, 0, 0, 0): -1}\n counter = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}\n ans = 0\n for (i, c) in enumerate(s):\n if c in counter:\n counter[c] += 1\n key = tuple([counter[c] % 2 for c in 'aeiou'])\n if key not in first_position:\n first_position[key] = i\n ans = max(i - first_position[key], ans)\n return ans", "def findthelongestsubstring(s: str) -> int:\n seen = {(0, 0, 0, 0, 0): -1}\n counts = {c: 0 for c in 'aeiou'}\n res = 0\n for (i, ch) in enumerate(s):\n if ch in counts:\n counts[ch] += 1\n key = tuple([counts[c] % 2 for c in 'aeiou'])\n seen.setdefault(key, i)\n res = max(res, i - seen[key])\n return res", "from collections import Counter\n\ndef findthelongestsubstring(s: str) -> int:\n _max = 0\n vowels = 'aeiou'\n\n def counter_to_tuple(counter):\n res = []\n for v in vowels:\n res.append(counter[v] % 2)\n return tuple(res)\n ss_counter = Counter()\n cache = {(0, 0, 0, 0, 0): -1}\n length = 0\n for (ind, ss) in enumerate(s):\n if ss in vowels:\n ss_counter[ss] += 1\n counter_tuple = counter_to_tuple(ss_counter)\n if counter_tuple in cache:\n length = max(length, ind - cache[counter_tuple])\n else:\n cache[counter_tuple] = ind\n return length", "def findthelongestsubstring(s: str) -> int:\n for window_size in range(len(s), -1, -1):\n check_range = len(s) - window_size + 1\n for i in range(check_range):\n check_wr = s[i:i + window_size]\n right_string = True\n for ch in 'aeiou':\n if check_wr.count(ch) % 2:\n right_string = False\n break\n if right_string:\n return window_size\n return 0", "def findthelongestsubstring(s: str) -> int:\n seen = {(0, 0, 0, 0, 0): -1}\n vowel = 'aeiou'\n count = [0] * 5\n ans = 0\n for i in range(len(s)):\n idx = vowel.find(s[i])\n if idx >= 0:\n count[idx] += 1\n state = tuple([count[i] % 2 for i in range(5)])\n if state in seen:\n ans = max(ans, i - seen[state])\n else:\n seen[state] = i\n return ans", "def findthelongestsubstring(s: str) -> int:\n first_position = {0: -1}\n bit_ind = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n ans = key = 0\n for (i, c) in enumerate(s):\n if c in bit_ind:\n key = key ^ 1 << bit_ind[c]\n if key not in first_position:\n first_position[key] = i\n ans = max(i - first_position[key], ans)\n return ans", "def findthelongestsubstring(s: str) -> int:\n dic = {0: -1}\n n = 0\n res = 0\n voewls = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n for (i, c) in enumerate(s):\n if c in voewls:\n n ^= voewls[c]\n if n not in dic:\n dic[n] = i\n else:\n res = max(res, i - dic[n])\n return res", "def findthelongestsubstring(s: str) -> int:\n cache = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n (d, k, res) = ({0: -1}, 0, 0)\n for (i, c) in enumerate(s):\n if c in cache:\n k ^= cache[c]\n if k not in d:\n d[k] = i\n else:\n res = max(res, i - d[k])\n return res", "def findthelongestsubstring(s: str) -> int:\n memo = {0: 0}\n dic = dict(list(zip('aeiou', list(range(5)))))\n (curr, ans) = (0, 0)\n for (k, v) in enumerate(s, 1):\n if v in dic:\n curr ^= 1 << dic[v]\n if curr in memo:\n ans = max(ans, k - memo[curr])\n else:\n memo[curr] = k\n return ans", "def findthelongestsubstring(s: str) -> int:\n vowels_bit_mask = {v: 2 ** i for (i, v) in enumerate('aeiou')}\n vowel_state = 0\n first_index_of_recorded_state = {0: -1}\n max_substr_len = 0\n for (index, char) in enumerate(s):\n if char in vowels_bit_mask:\n vowel_state ^= vowels_bit_mask[char]\n if vowel_state in first_index_of_recorded_state:\n max_substr_len = max(max_substr_len, index - first_index_of_recorded_state[vowel_state])\n else:\n first_index_of_recorded_state[vowel_state] = index\n return max_substr_len", "def findthelongestsubstring(s: str) -> int:\n vowels = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n (d, n, r) = ({0: -1}, 0, 0)\n for (i, c) in enumerate(s):\n if c in vowels:\n n ^= vowels[c]\n if n not in d:\n d[n] = i\n else:\n r = max(r, i - d[n])\n return r", "def findthelongestsubstring(S: str) -> int:\n vowels = 'aeiou'\n seen = {0: -1}\n ans = cur = 0\n for (i, c) in enumerate(S):\n if c in vowels:\n cur ^= 1 << ord(c) - 97\n if cur not in seen:\n seen[cur] = i\n else:\n ans = max(ans, i - seen[cur])\n return ans", "def findthelongestsubstring(s: str) -> int:\n dict_vol = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n dict_vol = {x: 1 << y for (x, y) in dict_vol.items()}\n previous_seen = {0: -1}\n cur = 0\n ans = 0\n for (i, c) in enumerate(s):\n if c in dict_vol:\n cur = cur ^ dict_vol[c]\n if cur not in previous_seen:\n previous_seen[cur] = i\n else:\n ans = max(ans, i - previous_seen[cur])\n return ans", "def findthelongestsubstring(s: str) -> int:\n (seen, vowel) = ({0: -1}, {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4})\n res = curr = 0\n for (i, c) in enumerate(s):\n if c in vowel:\n curr ^= 1 << vowel[c]\n seen.setdefault(curr, i)\n res = max(res, i - seen[curr])\n return res", "def findthelongestsubstring(s: str) -> int:\n bin_map = collections.defaultdict(int)\n for (i, c) in enumerate(['a', 'e', 'i', 'o', 'u']):\n bin_map[c] = 1 << i\n cur_bin = 0\n prev_bin = {0: -1}\n ans = 0\n for (index, c) in enumerate(s):\n cur_bin ^= bin_map[c]\n if cur_bin in prev_bin:\n ans = max(ans, index - prev_bin[cur_bin])\n else:\n prev_bin[cur_bin] = index\n return ans", "def findthelongestsubstring(s: str) -> int:\n vowels = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n (bitmask_to_index, bitmaskrepr, result) = ({0: -1}, 0, 0)\n for (index, item) in enumerate(s):\n if item in vowels:\n bitmaskrepr ^= vowels[item]\n if bitmaskrepr not in bitmask_to_index:\n bitmask_to_index[bitmaskrepr] = index\n else:\n result = max(result, index - bitmask_to_index[bitmaskrepr])\n return result", "def findthelongestsubstring(s: str) -> int:\n masks = {0: -1}\n mask = 0\n match = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n max_len = 0\n for (i, ch) in enumerate(s):\n if ch in match:\n mask = mask ^ 1 << match[ch]\n if mask in masks:\n max_len = max(max_len, i - masks[mask])\n else:\n masks[mask] = i\n return max_len", "def findthelongestsubstring(s: str) -> int:\n vowels = set('aeiou')\n odd = {tuple(): -1}\n key = tuple()\n res = 0\n window = collections.Counter()\n vowel_count = [window]\n for (i, char) in enumerate(s):\n if char in vowels:\n window[char] += 1\n key = tuple((c for c in window if window[c] & 1))\n if key in odd:\n res = max(i - odd[key], res)\n else:\n odd[key] = i\n else:\n res = max(i - odd[key], res)\n else:\n res = max(i - odd[key], res)\n return res", "def findthelongestsubstring(s: str) -> int:\n vowels = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n d = {0: -1}\n binRep = 0\n res = 0\n for (i, char) in enumerate(s):\n if char in vowels:\n binRep = binRep ^ vowels[char]\n if binRep not in d:\n d[binRep] = i\n else:\n res = max(res, i - d[binRep])\n return res", "def findthelongestsubstring(s: str) -> int:\n (n, vowels, d) = (len(s), 'aeiou', {0: -1})\n ret = cur = 0\n for (i, c) in enumerate(s):\n if c in vowels:\n cur ^= 1 << vowels.index(c)\n d.setdefault(cur, i)\n ret = max(ret, i - d[cur])\n return ret", "def findthelongestsubstring(s: str) -> int:\n digits = {c: i for (i, c) in enumerate('aeiou')}\n ans = counter = 0\n seen = {0: -1}\n for (i, c) in enumerate(s):\n if c in digits:\n counter ^= 1 << digits[c]\n seen.setdefault(counter, i)\n ans = max(ans, i - seen[counter])\n return ans", "def findthelongestsubstring(s: str) -> int:\n n = len(s)\n dp = {}\n for k in range(n, 0, -1):\n for i in range(0, n + 1 - k):\n if k == n:\n s_count = collections.Counter(s)\n dp[i, k] = [s_count.get(c, 0) % 2 == 0 for c in 'aeiou']\n elif i == 0:\n dp[i, k] = self.update_tracker(s[i + k], dp.get((i, k + 1)))\n else:\n dp[i, k] = self.update_tracker(s[i - 1], dp.get((i - 1, k + 1)))\n if all(dp[i, k]):\n return k\n return 0\n\ndef update_tracker(char, tracker):\n idx = 'aeiou'.find(char)\n new_tracker = list(tracker)\n if idx > -1:\n new_tracker[idx] = not tracker[idx]\n return new_tracker", "def findthelongestsubstring(s: str) -> int:\n res = 0\n pos = {0: -1}\n state = 0\n vowels = 'aeiou'\n for i in range(len(s)):\n j = vowels.find(s[i])\n if j >= 0:\n state ^= 1 << j\n if state in pos:\n res = max(res, i - pos[state])\n else:\n pos[state] = i\n return res", "def findthelongestsubstring(s: str) -> int:\n (mask, seen, smax, vowels) = (0, {0: -1}, 0, {x: 1 << i for (i, x) in enumerate('aeiou')})\n for (i, x) in enumerate(s):\n if x in vowels:\n mask ^= 1 << vowels[x]\n seen.setdefault(mask, i)\n smax = max(smax, i - seen[mask])\n return smax", "def findthelongestsubstring(s: str) -> int:\n for window_size in range(len(s), -1, -1):\n end_pos = len(s) - window_size + 1\n for i in range(end_pos):\n substring = s[i:i + window_size]\n is_all_even = True\n for ch in 'aeiou':\n if substring.count(ch) % 2:\n is_all_even = False\n break\n if is_all_even:\n return window_size\n return 0", "def findthelongestsubstring(s: str) -> int:\n (state, statedict) = (0, {0: -1})\n voweldict = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n maxlen = 0\n for (i, c) in enumerate(s):\n if c in voweldict:\n state ^= voweldict[c]\n if state in statedict:\n maxlen = max(maxlen, i - statedict[state])\n else:\n statedict[state] = i\n return maxlen", "def findthelongestsubstring(s: str) -> int:\n vowels = 'aeiou'\n mask = last_mask = 0\n first = [-1] + [float('inf')] * 31\n last = [-1] + [float('-inf')] * 31\n for (i, c) in enumerate(s):\n if c in set(vowels):\n j = vowels.index(c)\n (last_mask, mask) = (mask, mask ^ 1 << j)\n if first[mask] == float('inf'):\n first[mask] = last[last_mask] + 1\n last[mask] = i\n return max((j - i for (i, j) in zip(first, last)))", "VOWELS = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n\ndef findthelongestsubstring(s: str) -> int:\n seen = {0: -1}\n mask = 0\n longest = 0\n for (ind, char) in enumerate(s):\n mask ^= VOWELS.get(char, 0)\n if mask not in seen:\n seen[mask] = ind\n else:\n longest = max(longest, ind - seen[mask])\n return longest", "def findthelongestsubstring(s: str) -> int:\n substrings = self.generate_subst(s)\n res = 0\n for substring in substrings:\n is_all_even = True\n for ch in 'aeiou':\n if substring.count(ch) % 2:\n is_all_even = False\n break\n if is_all_even:\n return len(substring)\n return res\n\ndef generate_subst(s: str):\n for window_size in range(len(s), -1, -1):\n for i in range(len(s) - window_size + 1):\n yield s[i:i + window_size]", "from collections import defaultdict\n\ndef findthelongestsubstring(s: str) -> int:\n res = 0\n vowel_map = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n visited = {0: -1}\n pattern = 0\n for (i, c) in enumerate(s):\n if c in vowel_map:\n pattern ^= 1 << vowel_map[c]\n if pattern not in visited:\n visited[pattern] = i\n res = max(res, i - visited[pattern])\n return res", "def findthelongestsubstring(s: str) -> int:\n idx_dic = {0: -1}\n vowels = 'aeiou'\n state = ans = 0\n for i in range(len(s)):\n j = vowels.find(s[i])\n if j >= 0:\n state ^= 1 << j\n if state not in idx_dic:\n idx_dic[state] = i\n ans = max(ans, i - idx_dic[state])\n return ans", "def findthelongestsubstring(s: str) -> int:\n state = 0\n d = {0: -1}\n vowels = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n max_len = 0\n for i in range(len(s)):\n if s[i] in vowels:\n state ^= vowels[s[i]]\n if state not in d:\n d[state] = i\n if state in d:\n max_len = max(max_len, i - d[state])\n return max_len", "def findthelongestsubstring(s: str) -> int:\n vowels = 'aeiou'\n helper = {0: -1}\n state = 0\n res = 0\n for (i, ch) in enumerate(s):\n j = vowels.find(ch)\n if j >= 0:\n state ^= 1 << j\n if state not in helper:\n helper[state] = i\n res = max(res, i - helper[state])\n return res", "def findthelongestsubstring(s: str) -> int:\n for i in range(len(s), -1, -1):\n for x in range(len(s) - i + 1):\n counter = 0\n temp = s[x:x + i]\n for k in 'aeiou':\n if temp.count(k) % 2 != 0:\n counter += 1\n break\n if counter == 0:\n return i", "from collections import defaultdict\n\ndef findthelongestsubstring(string: str) -> int:\n vowels = 'aeiou'\n vowels_dict = dict(zip(vowels, range(5)))\n curr = 0\n pos_dict = defaultdict(lambda : float('inf'))\n pos_dict[0] = -1\n res = 0\n for (i, v) in enumerate(string):\n if v in vowels_dict:\n curr ^= 1 << vowels_dict[v]\n res = max(res, i - pos_dict[curr])\n pos_dict[curr] = min(pos_dict[curr], i)\n return res", "def findthelongestsubstring(s: str) -> int:\n digits = {c: i for (i, c) in enumerate('aeiou')}\n counters = [0]\n for c in s:\n if c in digits:\n counters.append(counters[-1] ^ 1 << digits[c])\n else:\n counters.append(counters[-1])\n for length in range(len(s), 0, -1):\n for j in range(len(s), length - 1, -1):\n if not counters[j] ^ counters[j - length]:\n return length\n return 0", "def findthelongestsubstring(s: str) -> int:\n d = {(0, 0, 0, 0, 0): -1}\n count = [0, 0, 0, 0, 0]\n pos = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n ans = 0\n for (i, char) in enumerate(s):\n if char in pos:\n count[pos[char]] = (count[pos[char]] + 1) % 2\n t = tuple(count)\n if t in d:\n ans = max(ans, i - d[t])\n else:\n d[t] = i\n return ans", "def findthelongestsubstring(s: str) -> int:\n seen = {0: -1}\n pos = {c: i for (i, c) in enumerate('aeiou')}\n curr = res = 0\n for (i, c) in enumerate(s):\n curr ^= 1 << pos.get(c, -1) + 1 >> 1\n seen.setdefault(curr, i)\n res = max(res, i - seen[curr])\n return res", "def findthelongestsubstring(s: str) -> int:\n lu = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n\n def setFlags(flags: int, ch: str) -> int:\n if ch in lu.keys():\n mask = 1 << lu[ch]\n flags = flags ^ mask\n return flags\n FLAGS = 0\n seen = {0: -1}\n m = 0\n for (i, c) in enumerate(s):\n FLAGS = setFlags(FLAGS, c)\n if FLAGS in seen.keys():\n m = max(m, i - seen[FLAGS])\n else:\n seen[FLAGS] = i\n return m", "def findthelongestsubstring(s: str) -> int:\n masks = {'a': 16, 'e': 8, 'i': 4, 'o': 2, 'u': 1}\n num = 0\n numToIdx = {0: -1}\n ans = 0\n for (i, ch) in enumerate(s):\n if ch in masks:\n num ^= masks[ch]\n if num not in numToIdx:\n numToIdx[num] = i\n ans = max(ans, i - numToIdx[num])\n return ans", "from copy import copy\n\ndef findthelongestsubstring(s: str) -> int:\n vowel2idx = dict([(item[1], item[0]) for item in enumerate(['a', 'e', 'i', 'o', 'u'])])\n counters = [[0] * len(vowel2idx)]\n for item in s:\n counters.append(counters[-1].copy())\n if item in vowel2idx:\n counters[-1][vowel2idx[item]] += 1\n for width in range(len(s), 0, -1):\n for start in range(len(s) - width + 1):\n for n_vowels in map(int.__sub__, counters[start + width], counters[start]):\n if n_vowels % 2 == 1:\n break\n else:\n return width\n return 0", "def findthelongestsubstring(s: str) -> int:\n dp = [-1] + [len(s)] * 31\n mask = 0\n res = 0\n for (i, c) in enumerate(s):\n if c in 'aeiou':\n mask ^= 1 << 'aeiou'.index(c)\n dp[mask] = min(dp[mask], i)\n res = max(res, i - dp[mask])\n return res"], "starter_code": "def findthelongestsubstring(s: str) -> int:\n", "input_output": {"fn_name": "findTheLongestSubstring", "inputs": [["\"eleetminicoworoep\""]], "outputs": [13]}, "difficulty": "MEDIUM", "raw_tags": ["Prefix Sum", "Bit Manipulation", "String", "Hash Table"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Bit manipulation", "Data structures", "Range queries"], "skill_types": ["Bit manipulation", "Data structures", "Range queries"], "url": "https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "findthelongestsubstring", "task_id": "TACO_lite/418", "example": [[["eleetminicoworoep"], ["leetcodeisgreat"], ["bcbcbc"]], ["13", "5", "6"]]} +{"requirement": "You are given the sequence: 0123456789101112131415...\nThe 0th digit of this sequence is 0, the 1st digit of this sequence is 1, the 2nd digit of this sequence is 2 and so on. You are given n, find the nth digit of the sequence.\n \nExample 1:\nInput: n = 12\nOutput: 1\nExplanation: 1 is the 12th digit of the\ngiven sequence.\nExample 2:\nInput: n = 20\nOutput: 4\nExplanation: 4 is the 20th digit of the\ngiven sequence.\n \nYour Task:\nYou don't need to read or write anything. Your task is to complete the function NthDigit() which takes n as input parameter and returns the nth digit of the sequence.\n \nExpected Time Complexity: O(log_{10}(n))\nExpected Space Compelxity: O(1)\n \nConstraints:\n1 <= n <= 10^{9}", "solutions": ["def nthdigit(n):\n (cnt, r) = (0, 1)\n while True:\n cnt += r * pow(10, r - 1) * 9\n if cnt >= n:\n break\n r += 1\n cnt -= r * pow(10, r - 1) * 9\n n -= cnt\n (q, rem) = divmod(n, r)\n num = q + pow(10, r - 1) - 1\n if rem == 0:\n return num % 10\n else:\n num += 1\n ans = str(num)\n return int(ans[rem - 1])", "def nthdigit(n):\n if n <= 9:\n return n\n n += 1\n p = 10\n s = 10\n i = 2\n while True:\n t = p * i * 9\n s += t\n if s >= n:\n s -= t\n break\n i += 1\n p = p * 10\n d = n - s\n if d % i == 0:\n p = p + d // i - 1\n j = i\n else:\n p = p + d // i\n j = d % i\n j = i - j\n while j != 0:\n p = p // 10\n j -= 1\n return p % 10", "def nthdigit(n):\n if n < 10:\n return n\n digit = 0\n tmp = 0\n pre = 0\n while tmp < n:\n pre = tmp\n digit += 1\n tmp += 9 * 10 ** (digit - 1) * digit\n n -= pre\n num = 10 ** (digit - 1) + (n - 1) // digit\n index = (n - 1) % digit\n return num // 10 ** (digit - index - 1) % 10"], "starter_code": "def nthdigit(n):\n", "input_output": {"inputs": ["n = 12", "n = 20"], "outputs": ["1", "4"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/nth-digit-in-sequence0420/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log_{10}(n))", "entry_point": "nthdigit", "task_id": "TACO_lite/339", "example": [[[12], [20]], ["1", "4"]]} +{"requirement": "Given a positive integer n that represents dimensions of a 4n x 4n matrix with values from 1 to 4*n*4*n filled from left to right and top to bottom. Your task is to form two coils from matrix and print the coils.\nFollow the given examples for better understanding.\n \nExample 1:\nInput:\nn = 1\nOutput:\n10 6 2 3 4 8 12 16\n7 11 15 14 13 9 5 1 \nExplanation:\nThe matrix is \n1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\nSo, the two coils are as given in the Ouput.\nExample 2:\nInput:\nn = 2\nOutput:\n36 28 20 21 22 30 38 46\n54 53 52 51 50 42 34 26\n18 10 2 3 4 5 6 7 8\n16 24 32 40 48 56 64\n29 37 45 44 43 35 27 19\n11 12 13 14 15 23 31 39\n47 55 63 62 61 60 59 58\n57 49 41 33 25 17 9 1 \nExplanation:\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function formCoils() which takes an Integer n as input and returns a vector of two vectors representing coil1 and coil2.\n \nExpected Time Complexity: O(n^{2})\nExpected Auxiliary Space: O(n^{2})\n \nConstraints:\n1 <= n <= 20", "solutions": ["def formcoils(n):\n ans = [[], []]\n curr = [[4 * n - 1, 4 * n - 1], [0, 0]]\n d0 = [(-1, 0), (0, -1), (1, 0), (0, 1)]\n d1 = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n m = [[0 for _ in range(4 * n)] for _ in range(4 * n)]\n start = 1\n for i in range(4 * n):\n for j in range(4 * n):\n m[i][j] = start\n start += 1\n marked = [[0 for _ in range(4 * n)] for _ in range(4 * n)]\n k = 0\n while len(ans[0]) < 8 * n * n:\n marked[curr[0][0]][curr[0][1]] = 1\n ans[0].append(m[curr[0][0]][curr[0][1]])\n marked[curr[1][0]][curr[1][1]] = 1\n ans[1].append(m[curr[1][0]][curr[1][1]])\n if not (curr[0][0] + d0[k][0] < 4 * n and curr[0][0] + d0[k][0] >= 0 and (curr[0][1] + d0[k][1] >= 0) and (curr[0][1] + d0[k][0] < 4 * n) and (marked[curr[0][0] + d0[k][0]][curr[0][1] + d0[k][1]] == 0)):\n k = (k + 1) % 4\n curr[0][0] += d0[k][0]\n curr[0][1] += d0[k][1]\n curr[1][0] += d1[k][0]\n curr[1][1] += d1[k][1]\n ans[0].reverse()\n ans[1].reverse()\n return ans", "def formcoils(n):\n\n def solve1(mat, r, c):\n arr1 = []\n t = 0\n b = r - 1\n l = 0\n r = c - 1\n dir = 1\n while t <= b and l <= r:\n if dir == 1:\n for i in range(t, b + 1):\n arr1.append(mat[i][l])\n l += 1\n dir = 0\n if dir == 0:\n for i in range(l, r):\n arr1.append(mat[b][i])\n l += 1\n b -= 1\n r -= 1\n dir = 3\n if dir == 3:\n for i in range(b, t, -1):\n arr1.append(mat[i][r])\n dir = 2\n r -= 1\n if dir == 2:\n for i in range(r, l - 1, -1):\n arr1.append(mat[t + 1][i])\n dir = 1\n t += 2\n b -= 1\n return arr1\n\n def solve2(mat, r, c):\n arr1 = []\n t = 0\n b = r - 1\n l = 0\n r = c - 1\n dir = 3\n while t <= b and l <= r:\n if dir == 3:\n for i in range(b, t - 1, -1):\n arr1.append(mat[i][r])\n dir = 0\n r -= 1\n if dir == 0:\n for i in range(r, l, -1):\n arr1.append(mat[t][i])\n l += 1\n t += 1\n dir = 1\n if dir == 1:\n for i in range(t, b):\n arr1.append(mat[i][l])\n b -= 1\n l += 1\n dir = 2\n if dir == 2:\n for i in range(l, r):\n arr1.append(mat[b][i])\n dir = 3\n t += 1\n r -= 1\n b -= 1\n return arr1\n r = 4 * n\n c = 4 * n\n k = 1\n mat = []\n for i in range(1, r + 1):\n arr = []\n for j in range(1, c + 1):\n arr.append(k)\n k += 1\n mat.append(arr)\n return (solve2(mat, r, c)[::-1], solve1(mat, r, c)[::-1])", "def formcoils(n):\n mat = lambda i, j: 4 * n * i + j + 1\n answer = [[], []]\n\n def getAns(i, j, direction, ans):\n ans.append(mat(i, j))\n step = 2\n while 0 <= i < 4 * n and 0 <= j < 4 * n:\n temp = 1\n while temp <= step:\n if direction == 0:\n i = i - 1\n elif direction == 1:\n j = j + 1\n elif direction == 2:\n i = i + 1\n else:\n j = j - 1\n ans.append(mat(i, j))\n temp += 1\n direction = (direction + 1) % 4\n if direction == 0 or direction == 2:\n step += 2\n direction = 0\n i = 2 * n\n j = 2 * n - 1\n getAns(i, j, direction, answer[0])\n answer[0].pop()\n direction = 2\n i = 2 * n - 1\n j = 2 * n\n getAns(i, j, direction, answer[1])\n answer[1].pop()\n return answer", "def formcoils(n):\n Arr = [[0 for _ in range(4 * n)] for _ in range(4 * n)]\n cnt = 1\n for i in range(0, 4 * n):\n for j in range(0, 4 * n):\n Arr[i][j] = cnt\n cnt += 1\n lst1 = []\n direction = 0\n left = 0\n right = 4 * n - 1\n top = 0\n bottom = 4 * n - 1\n while left <= right and top <= bottom:\n if direction == 0:\n for i in range(top, bottom + 1):\n lst1.append(Arr[i][left])\n left += 1\n right -= 1\n if direction == 1:\n for i in range(left, right + 1):\n lst1.append(Arr[bottom][i])\n top += 1\n bottom -= 1\n if direction == 2:\n for i in range(bottom, top - 1, -1):\n lst1.append(Arr[i][right])\n left += 1\n right -= 1\n if direction == 3:\n for i in range(right, left - 1, -1):\n lst1.append(Arr[top][i])\n top += 1\n bottom -= 1\n direction = (direction + 1) % 4\n direction = 0\n left = 0\n right = 4 * n - 1\n top = 0\n bottom = 4 * n - 1\n lst2 = []\n while left <= right and top <= bottom:\n if direction == 0:\n for i in range(bottom, top - 1, -1):\n lst2.append(Arr[i][right])\n right -= 1\n left += 1\n if direction == 1:\n for i in range(right, left - 1, -1):\n lst2.append(Arr[top][i])\n top += 1\n bottom -= 1\n if direction == 2:\n for i in range(top, bottom + 1):\n lst2.append(Arr[i][left])\n left += 1\n right -= 1\n if direction == 3:\n for i in range(left, right + 1):\n lst2.append(Arr[bottom][i])\n bottom -= 1\n top += 1\n direction = (direction + 1) % 4\n Lst = []\n Lst.append(lst2[::-1])\n Lst.append(lst1[::-1])\n return Lst", "def formcoils(n):\n\n def inMatrix(i, j, n):\n return 0 <= i < 4 * n and 0 <= j < 4 * n\n\n def valFromCoord(i, j, n):\n base = 1 + 4 * n * i\n return base + j\n dirs = ((1, 0), (0, 1), (-1, 0), (0, -1))\n coil1 = [1]\n coil2 = [4 * n * 4 * n]\n i1 = 0\n j1 = 0\n i2 = 4 * n - 1\n j2 = 4 * n - 1\n added = set()\n added.add(1)\n added.add(4 * n * 4 * n)\n dir1 = 0\n dir2 = 2\n while len(added) < 4 * n * 4 * n:\n d1 = dirs[dir1]\n d2 = dirs[dir2]\n while inMatrix(i1 + d1[0], j1 + d1[1], n) and inMatrix(i2 + d2[0], j2 + d2[1], n):\n val1 = valFromCoord(i1 + d1[0], j1 + d1[1], n)\n val2 = valFromCoord(i2 + d2[0], j2 + d2[1], n)\n if val1 not in added and val2 not in added:\n i1 += d1[0]\n j1 += d1[1]\n i2 += d2[0]\n j2 += d2[1]\n added.add(val1)\n coil1.append(val1)\n added.add(val2)\n coil2.append(val2)\n else:\n break\n dir1 = (dir1 + 1) % 4\n dir2 = (dir2 + 1) % 4\n return [coil2[::-1], coil1[::-1]]", "def formcoils(n):\n num_cells = (4 * n) ** 2\n num_per_coil = num_cells >> 1\n coil1 = [0] * num_per_coil\n curr = coil1[0] = num_per_coil + 2 * n\n index = 1\n flag = 1\n step = 2\n while index < num_per_coil:\n for i in range(step):\n curr = coil1[index] = curr - 4 * n * flag\n index += 1\n if index >= num_per_coil:\n break\n if index >= num_per_coil:\n break\n for i in range(step):\n curr = coil1[index] = curr + flag\n index += 1\n if index >= num_per_coil:\n break\n flag *= -1\n step += 2\n coil2 = [0] * num_per_coil\n for i in range(num_per_coil):\n coil2[i] = num_cells + 1 - coil1[i]\n return (coil1, coil2)", "def formcoils(n):\n rows = 4 * n\n cols = 4 * n\n c_n = rows * cols // 2\n coils1 = [0] * c_n\n coils2 = [0] * c_n\n coils1[0] = 8 * n * n + 2 * n\n curr = coils1[0]\n index = 1\n steps = 2\n op = 1\n while index < c_n:\n num_steps = 0\n while index < c_n and num_steps < steps:\n curr = curr - 4 * n * op\n coils1[index] = curr\n index += 1\n num_steps += 1\n num_steps = 0\n while index < c_n and num_steps < steps:\n curr = curr + op\n coils1[index] = curr\n index += 1\n num_steps += 1\n steps += 2\n op *= -1\n for i in range(c_n):\n coils2[i] = 16 * n * n - coils1[i] + 1\n return [coils1, coils2]", "def formcoils(n):\n m = 8 * n * n\n coil1 = [0] * m\n coil1[0] = 8 * n * n + 2 * n\n curr = coil1[0]\n nflg = 1\n step = 2\n index = 1\n while index < m:\n for i in range(step):\n curr = curr - 4 * n * nflg\n coil1[index] = curr\n index += 1\n if index >= m:\n break\n if index >= m:\n break\n for i in range(step):\n curr = curr + nflg\n coil1[index] = curr\n index += 1\n if index >= m:\n break\n nflg = -nflg\n step += 2\n coil2 = [0] * m\n i = 0\n for i in range(m):\n coil2[i] = 16 * n * n + 1 - coil1[i]\n return [coil1, coil2]", "def formcoils(n):\n c = 1\n m = []\n for i in range(4 * n):\n m.append([])\n for j in range(4 * n):\n m[i].append(c)\n c += 1\n coil2_dx = [0, 1, 0, -1]\n coil2_dy = [1, 0, -1, 0]\n coil1_dx = [-1, 0, 1, 0]\n coil1_dy = [0, 1, 0, -1]\n coil1_strt = m[2 * n][2 * n - 1]\n coil2_strt = m[2 * n - 1][2 * n]\n coil1 = []\n coil2 = []\n i = 2 * n\n j = 2 * n - 1\n c = 2\n d = 0\n flag = 0\n while True:\n cnt = c\n while cnt > 0:\n if i >= 0 and j >= 0 and (i < 4 * n) and (j < 4 * n):\n coil1.append(m[i][j])\n i += coil1_dx[d]\n j += coil1_dy[d]\n else:\n break\n cnt -= 1\n d = (d + 1) % 4\n if (flag + 1) % 2 == 0:\n c += 2\n flag += 1\n if flag > 4 * n:\n break\n for i in range(len(coil1)):\n coil2.append(16 * n * n + 1 - coil1[i])\n return (coil1, coil2)", "def Matrix(n, up, mat):\n if up:\n (i, j) = (n * 2, n * 2 - 1)\n else:\n (i, j) = (n * 2 - 1, n * 2)\n mul = 2\n coil1 = [mat[i][j]]\n flag = True\n while len(coil1) < 8 * n ** 2:\n if up:\n temp = mul\n while i > 0 and temp > 0:\n i -= 1\n temp -= 1\n if i < 0:\n flag = False\n break\n coil1.append(mat[i][j])\n if not flag:\n break\n temp = mul\n while j < n * 4 and temp > 0:\n j += 1\n temp -= 1\n if j >= n * 4:\n flag = False\n break\n coil1.append(mat[i][j])\n if not flag:\n break\n up = False\n mul += 2\n else:\n temp = mul\n while i + 1 < n * 4 and temp > 0:\n i += 1\n temp -= 1\n if i >= n * 4:\n flag = False\n break\n coil1.append(mat[i][j])\n if not flag:\n break\n temp = mul\n while j > 0 and temp > 0:\n j -= 1\n temp -= 1\n if j < 0:\n flag = False\n break\n coil1.append(mat[i][j])\n if not flag:\n break\n up = True\n mul += 2\n return coil1[:8 * n ** 2]\n\ndef formcoils(n):\n mat = []\n cur_ind = 1\n for x in range(4 * n):\n row = []\n for y in range(4 * n):\n row.append(cur_ind + y)\n mat.append(row)\n cur_ind = y + cur_ind + 1\n res = [Matrix(n, True, mat), Matrix(n, False, mat)]\n return res", "def formcoils(n):\n A = [[0] * 4 * n] * 4 * n\n count = 0\n for i in range(4 * n):\n D = [0] * 4 * n\n for j in range(4 * n):\n count += 1\n D[j] = count\n A[i] = D\n lst1 = []\n lst2 = []\n lst = []\n t = 0\n b = len(A) - 1\n l = 0\n r = len(A[0]) - 1\n dir = 0\n while t <= b and l <= r:\n if dir == 0:\n for i in range(t, b + 1):\n lst.append(A[i][l])\n l += 1\n r -= 1\n elif dir == 1:\n for i in range(l, r + 1):\n lst.append(A[b][i])\n b -= 1\n t += 1\n elif dir == 2:\n for i in range(b, t - 1, -1):\n lst.append(A[i][r])\n r -= 1\n l += 1\n elif dir == 3:\n for i in range(r, l - 1, -1):\n lst.append(A[t][i])\n t += 1\n b -= 1\n dir = (dir + 1) % 4\n lst.reverse()\n lst1 = lst\n lst = []\n t = 0\n b = len(A) - 1\n l = 0\n r = len(A[0]) - 1\n dir = 0\n while t <= b and l <= r:\n if dir == 0:\n for i in range(b, t - 1, -1):\n lst.append(A[i][r])\n r -= 1\n l += 1\n elif dir == 1:\n for i in range(r, l - 1, -1):\n lst.append(A[t][i])\n t += 1\n b -= 1\n elif dir == 2:\n for i in range(t, b + 1):\n lst.append(A[i][l])\n l += 1\n r -= 1\n elif dir == 3:\n for i in range(l, r + 1):\n lst.append(A[b][i])\n b -= 1\n t += 1\n dir = (dir + 1) % 4\n lst.reverse()\n lst2 = lst\n return [lst2, lst1]", "def formcoils(n):\n iRowStart = n * 2 + 1\n iColStart = n * 2\n listOne = []\n listTwo = []\n listResult = [listOne, listTwo]\n iRow = iRowStart\n iCol = iColStart\n iLength = 4 * 4 * n * n\n bComplete = False\n iSteps = 2\n iStepCounter = 0\n cDirection = 'U'\n while bComplete == False:\n for iStepCounter in range(iSteps):\n if True:\n iNumber = (iRow - 1) * n * 4 + iCol\n listOne.append(iNumber)\n listTwo.append(iLength - iNumber + 1)\n if iNumber == iLength:\n bComplete = True\n if cDirection == 'U':\n iRow -= 1\n elif cDirection == 'R':\n iCol += 1\n elif cDirection == 'D':\n iRow += 1\n elif cDirection == 'L':\n iCol -= 1\n else:\n pass\n if cDirection == 'S':\n cDirection = 'U'\n elif cDirection == 'U':\n cDirection = 'R'\n elif cDirection == 'R':\n cDirection = 'D'\n iSteps += 2\n elif cDirection == 'D':\n cDirection = 'L'\n if iSteps > 2 * n + 1:\n pass\n elif cDirection == 'L':\n cDirection = 'U'\n iSteps += 2\n else:\n bComplete = True\n return listResult", "def valid(n, a):\n if 0 <= a < 4 * n:\n return True\n return False\n\ndef formcoils(n):\n arr1 = []\n arr2 = []\n start_r = 4 * n // 2\n start_c = 4 * n // 2 - 1\n top = start_r - 2\n left = start_c - 2\n bottom = start_r + 2\n right = start_c + 2\n arr = []\n while 0 <= start_r < 4 * n and 0 <= start_c < 4 * n:\n for i in range(start_r, top, -1):\n arr1.append(4 * i * n + start_c + 1)\n arr2.append(4 * n * (4 * n - i - 1) + (4 * n - start_c - 1) + 1)\n for i in range(start_c, right):\n arr1.append(4 * n * top + i + 1)\n arr2.append(4 * n * (4 * n - top - 1) + (4 * n - i - 1) + 1)\n for i in range(top, bottom):\n arr1.append(4 * n * i + right + 1)\n arr2.append(4 * n * (4 * n - i - 1) + (4 * n - right - 1) + 1)\n i = right\n while self.valid(n, bottom) and i > left:\n arr1.append(4 * n * bottom + i + 1)\n arr2.append(4 * n * (4 * n - bottom - 1) + (4 * n - i - 1) + 1)\n i -= 1\n start_r += 2\n start_c -= 2\n top -= 2\n bottom += 2\n left -= 2\n right += 2\n arr.append(arr1)\n arr.append(arr2)\n return arr", "def formcoils(n):\n coil = [[], []]\n n *= 4\n i1 = n // 2\n j1 = i1 - 1\n i2 = n // 2 - 1\n j2 = i2 + 1\n sign = -1\n k = 2\n while 1:\n for _ in range(k):\n coil[0].append(n * i1 + j1 + 1)\n i1 += sign\n coil[1].append(n * i2 + j2 + 1)\n i2 -= sign\n if i1 == n:\n break\n for _ in range(k):\n coil[0].append(n * i1 + j1 + 1)\n j1 -= sign\n coil[1].append(n * i2 + j2 + 1)\n j2 += sign\n sign = -sign\n k += 2\n return coil", "def formcoils(n):\n coil = [2 * n * (4 * n + 1)]\n move = 1\n for step in range(2, 4 * n, 2):\n for _ in range(step):\n coil.append(coil[-1] - 4 * n * move)\n for _ in range(step):\n coil.append(coil[-1] + move)\n move *= -1\n for _ in range(4 * n - 1):\n coil.append(coil[-1] + 4 * n)\n return [coil, [16 * n * n + 1 - x for x in coil]]", "def formcoils(n):\n m = n * 4\n a = []\n c = 1\n ans = []\n for i in range(4 * n):\n a.append([])\n for j in range(4 * n):\n a[-1].append(c)\n c += 1\n start = [m // 2, m // 2 - 1]\n limit = m * m // 2\n ans.append([])\n ans[-1].append(a[start[0]][start[1]])\n c = 0\n while True:\n c += 2\n for i in range(c):\n start[0] -= 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n for i in range(c):\n start[1] += 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n c += 2\n for i in range(c):\n start[0] += 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n for i in range(c):\n start[1] -= 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n start = [m // 2 - 1, m // 2]\n limit = m * m // 2\n ans.append([])\n ans[-1].append(a[start[0]][start[1]])\n c = 0\n while True:\n c += 2\n for i in range(c):\n start[0] += 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n for i in range(c):\n start[1] -= 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n c += 2\n for i in range(c):\n start[0] -= 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n for i in range(c):\n start[1] += 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n return ans", "def formcoils(n):\n b = []\n c = []\n temp1 = (4 * n) ** 2\n temp2 = 1\n a = 4 * n - 2\n flag = -1\n b.append(temp1)\n c.append(temp2)\n for x in range(4 * n - 1):\n temp1 -= 4 * n\n temp2 += 4 * n\n b.append(temp1)\n c.append(temp2)\n for x in range(2 * n - 1):\n for y in range(a):\n temp1 += flag\n temp2 -= flag\n b.append(temp1)\n c.append(temp2)\n flag *= -1\n for y in range(a):\n temp1 += 4 * n * flag\n temp2 -= 4 * n * flag\n b.append(temp1)\n c.append(temp2)\n a -= 2\n b[:] = b[::-1]\n c[:] = c[::-1]\n return (b, c)", "def formcoils(n):\n coil = [2 * n * (4 * n + 1)]\n move = 1\n for i in range(2, 4 * n, 2):\n for j in range(i):\n coil.append(coil[-1] - 4 * n * move)\n for k in range(i):\n coil.append(coil[-1] + move)\n move *= -1\n for i in range(4 * n - 1):\n coil.append(coil[-1] + 4 * n)\n return [coil, [16 * n * n + 1 - x for x in coil]]", "def formcoils(n):\n m = n * 4\n table = []\n count = 0\n for i in range(m):\n line = []\n for j in range(m):\n count += 1\n line.append(count)\n table.append(line)\n red = []\n moves = {'d': m, 'u': -m, 'r': 1, 'l': -1}\n red_order = ['d', 'r', 'u', 'l']\n steps = m\n val = 1 - m\n while True:\n for move in red_order:\n for bla in range(steps):\n val += moves[move]\n red.append(val)\n if move == 'd' or move == 'u':\n steps -= 2\n if steps + 1 < 0:\n break\n blue_order = ['u', 'l', 'd', 'r']\n blue = []\n steps = m\n val = m * m + m\n while True:\n for move in blue_order:\n for bla in range(steps):\n val += moves[move]\n blue.append(val)\n if move == 'd' or move == 'u':\n steps -= 2\n if steps < 0:\n break\n return (blue[::-1], red[::-1])", "def formcoils(n):\n p = 1\n mat = [[0 for j in range(4 * n)] for i in range(4 * n)]\n for l in range(0, 4 * n):\n for g in range(0, 4 * n):\n mat[l][g] = p\n p += 1\n RS = 4 * n // 2 - 1\n RE = 4 * n // 2 + 1\n CS = 4 * n // 2\n CE = 4 * n // 2\n arr1 = []\n totalElements = 4 * n * (4 * n)\n halfElements = totalElements // 2\n i = halfElements\n while i != 0:\n for j in range(RS, RE):\n arr1.append(mat[j][CE])\n i -= 1\n if i == 0:\n break\n CS = CS - 2\n for j in range(CE, CS - 1, -1):\n arr1.append(mat[RE][j])\n i -= 1\n if i == 0:\n break\n RS = RS - 2\n CE = CE + 2\n for j in range(RE - 1, RS, -1):\n arr1.append(mat[j][CS])\n i -= 1\n if i == 0:\n break\n RE = RE + 2\n for j in range(CS, CE):\n arr1.append(mat[RS][j])\n i -= 1\n totalElements1 = 4 * n * (4 * n)\n halfElements1 = totalElements1 // 2\n RS1 = 4 * n // 2 - 2\n RE1 = 4 * n // 2\n CS1 = 4 * n // 2 - 1\n CE1 = 4 * n // 2 - 1\n arr2 = []\n i1 = halfElements1\n while i1 != 0:\n for j in range(RE1, RS1, -1):\n arr2.append(mat[j][CS1])\n i1 -= 1\n if i1 <= 0:\n break\n CE1 = CE1 + 2\n for j in range(CS1, CE1):\n arr2.append(mat[RS1][j])\n i1 -= 1\n if i1 <= 0:\n break\n RE1 = RE1 + 2\n for j in range(RS1, RE1):\n arr2.append(mat[j][CE1])\n i1 -= 1\n if i1 <= 0:\n break\n CS1 = CS1 - 2\n RS1 = RS1 - 2\n for j in range(CE1, CS1, -1):\n arr2.append(mat[RE1][j])\n i1 -= 1\n arr = [arr2, arr1]\n return arr", "def formcoils(n):\n res = [2 * n * (4 * n + 1)]\n move = 1\n for i in range(2, 4 * n, 2):\n for _ in range(i):\n res.append(res[-1] - 4 * n * move)\n for _ in range(i):\n res.append(res[-1] + move)\n move *= -1\n for i in range(4 * n - 1):\n res.append(res[-1] + 4 * n)\n return [res, [16 * n * n + 1 - j for j in res]]", "def formcoils(n):\n v = [[], []]\n (ct, i) = (1, n * 2 - 1)\n (k, l) = (i + 1, i)\n e = 4 * n * k + l + 1\n v[0].append(e)\n while ct <= i:\n for j in range(ct * 2):\n if ct % 2 != 0:\n e -= 4 * n\n else:\n e += 4 * n\n v[0].append(e)\n for j in range(ct * 2):\n if ct % 2 == 0:\n e -= 1\n else:\n e += 1\n v[0].append(e)\n ct += 1\n for j in range(4 * n - 1):\n e += 4 * n\n v[0].append(e)\n (ct, e) = (1, 4 * n * l + k + 1)\n v[1].append(e)\n while ct <= i:\n for j in range(ct * 2):\n if ct % 2 != 0:\n e += 4 * n\n else:\n e -= 4 * n\n v[1].append(e)\n for j in range(ct * 2):\n if ct % 2 == 0:\n e += 1\n else:\n e -= 1\n v[1].append(e)\n ct += 1\n for j in range(4 * n - 1):\n e -= 4 * n\n v[1].append(e)\n return v", "def first(n, mat):\n arr = []\n j = n - 1\n i = n - 1\n c = -1\n while True:\n while i > c:\n arr.append(mat[i][j])\n i -= 1\n c += 1\n i += 1\n j -= 1\n while j > c:\n arr.append(mat[i][j])\n j -= 1\n i += 1\n j += 1\n while i < n - (c + 1):\n arr.append(mat[i][j])\n i += 1\n i -= 1\n j += 1\n if i == j:\n return arr[::-1]\n c += 1\n while j < n - (c + 1):\n arr.append(mat[i][j])\n j += 1\n j -= 1\n i -= 1\n\ndef second(n, mat):\n arr = []\n j = 0\n i = 0\n c = n\n while True:\n while i < c:\n arr.append(mat[i][j])\n i += 1\n c -= 1\n i -= 1\n j += 1\n while j < c:\n arr.append(mat[i][j])\n j += 1\n i -= 1\n j -= 1\n while i > n - (c + 1):\n arr.append(mat[i][j])\n i -= 1\n i += 1\n j -= 1\n if i == j:\n return arr[::-1]\n c -= 1\n while j > n - (c + 1):\n arr.append(mat[i][j])\n j -= 1\n j += 1\n i += 1\n return arr\n\ndef formcoils(n):\n mat = []\n for i in range(1, (4 * n) ** 2, 4 * n):\n m = [i for i in range(i, i + 4 * n)]\n mat.append(m)\n arr1 = self.first(4 * n, mat)\n arr2 = self.second(4 * n, mat)\n return [arr1, arr2]", "def formcoils(n):\n arr = [2 * n * (4 * n + 1)]\n step = 1\n for i in range(2, 4 * n, 2):\n for _ in range(i):\n arr.append(arr[-1] - 4 * n * step)\n for _ in range(i):\n arr.append(arr[-1] + step)\n step = step * -1\n for _ in range(4 * n - 1):\n arr.append(arr[-1] + 4 * n)\n return [arr, [16 * n * n + 1 - i for i in arr]]", "def construct_matrix(n):\n (matrix, st) = ([], 1)\n for i in range(n):\n matrix.append(list(range(st, st + n)))\n st += n\n return matrix\n\ndef formcoils(n):\n n *= 4\n matrix = self.construct_matrix(n)\n (coil1, coil2) = ([], [])\n (rmin, rmax, cmin, cmax) = (0, n - 1, 0, n - 1)\n while rmin < rmax and cmin < cmax:\n for i in range(rmin, rmax + 1):\n coil1.append(matrix[i][cmin])\n for j in range(cmin + 1, cmax):\n coil1.append(matrix[rmax][j])\n for i in range(rmax, rmin, -1):\n coil2.append(matrix[i][cmax])\n for j in range(cmax, cmin, -1):\n coil2.append(matrix[rmin][j])\n (coil1, coil2) = (coil2, coil1)\n rmin += 1\n rmax -= 1\n cmin += 1\n cmax -= 1\n return [coil2[::-1], coil1[::-1]]", "def formcoils(n):\n coil = [2 * n * (4 * n + 1)]\n coil2 = [2 * n * (4 * n - 1) + 1]\n diff = 1\n for x in range(2, 4 * n, 2):\n for _ in range(x):\n coil.append(coil[-1] - 4 * n * diff)\n coil2.append(coil2[-1] + 4 * n * diff)\n for _ in range(x):\n coil.append(coil[-1] + diff)\n coil2.append(coil2[-1] - diff)\n diff *= -1\n for _ in range(4 * n - 1):\n coil.append(coil[-1] + 4 * n)\n coil2.append(coil2[-1] - 4 * n)\n return [coil, coil2]", "def formcoils(n):\n\n def is_valid(x, y):\n if x >= 0 and x < 4 * n and (y >= 0) and (y < 4 * n):\n return True\n return False\n\n def rec(x, y, direction, steps):\n update = [[-1, 1], [1, -1]]\n if not is_valid(x, y + steps * update[direction][1]):\n steps = steps - 1\n for i in range(steps):\n y += update[direction][1]\n ans.append(x + y * 4 * n + 1)\n if steps % 2:\n return\n for i in range(steps):\n x += update[direction][0]\n ans.append(x + y * 4 * n + 1)\n direction = 1 - direction\n steps += 2\n rec(x, y, direction, steps)\n ans = []\n half = 4 * n // 2\n (x, y) = (half - 1, half)\n ans.append(x + y * 4 * n + 1)\n rec(x, y, 1, 2)\n ans.append('')\n ret = [ans]\n ans = []\n (x, y) = (half, half - 1)\n ans.append(x + y * 4 * n + 1)\n rec(x, y, 0, 2)\n ans.append('')\n ret.append(ans)\n return ret", "def formcoils(n):\n m = 8 * n * n\n ans = [[], []]\n ans[0].append(8 * n * n + 2 * n)\n curr = ans[0][0]\n nfgl = 1\n step = 2\n index = 1\n while index < m:\n for i in range(0, step):\n curr = curr - 4 * n * nfgl\n ans[0].append(curr)\n if len(ans[0]) >= m:\n break\n if len(ans[0]) >= m:\n break\n for i in range(step):\n curr = curr + nfgl\n ans[0].append(curr)\n if len(ans[0]) >= m:\n break\n nfgl = nfgl * -1\n step += 2\n for i in range(m):\n ans[1].append(16 * n * n + 1 - ans[0][i])\n return ans", "def formcoils(n):\n c = [2 * n * (4 * n + 1)]\n m = 1\n for s in range(2, 4 * n, 2):\n for i in range(s):\n c.append(c[-1] - 4 * n * m)\n for j in range(s):\n c.append(c[-1] + m)\n m *= -1\n for k in range(4 * n - 1):\n c.append(c[-1] + 4 * n)\n return [c, [16 * n * n + 1 - x for x in c]]", "def formcoils(n):\n\n def mat(x, y):\n return n * x + y + 1\n arr = [[], []]\n n *= 4\n i1 = int(n / 2)\n j1 = i1 - 1\n sign = -1\n k = 2\n i2 = int(n / 2) - 1\n j2 = i2 + 1\n while 1:\n for _ in range(k):\n arr[0].append(mat(i1, j1))\n i1 += sign\n arr[1].append(mat(i2, j2))\n i2 += sign * -1\n if i1 == n:\n break\n for _ in range(k):\n arr[0].append(mat(i1, j1))\n j1 -= sign\n arr[1].append(mat(i2, j2))\n j2 -= sign * -1\n sign *= -1\n k += 2\n return arr", "def formcoils(n):\n c = [2 * n * (4 * n + 1)]\n m = 1\n for i in range(2, 4 * n, 2):\n for _ in range(i):\n c.append(c[-1] - 4 * n * m)\n for _ in range(i):\n c.append(c[-1] + m)\n m *= -1\n for _ in range(4 * n - 1):\n c.append(c[-1] + 4 * n)\n return [c, [16 * n * n + 1 - x for x in c]]", "def formcoils(n):\n\n def mat(x, y):\n return n * x + y + 1\n arr = [[], []]\n n *= 4\n i = int(n / 2)\n j = i - 1\n sign = -1\n k = 2\n while i != n - 1 or j != n - 1:\n for _ in range(k):\n arr[0].append(mat(i, j))\n i += sign\n if i == n:\n break\n for _ in range(k):\n arr[0].append(mat(i, j))\n j -= sign\n sign *= -1\n k += 2\n i = int(n / 2) - 1\n j = i + 1\n sign = 1\n k = 2\n while i != 0 or j != 0:\n for _ in range(k):\n arr[1].append(mat(i, j))\n i += sign\n if i < 0:\n break\n for _ in range(k):\n arr[1].append(mat(i, j))\n j -= sign\n sign *= -1\n k += 2\n return arr", "def formcoils(n):\n coils = [2 * n * (4 * n + 1)]\n ind = 1\n for i in range(2, 4 * n, 2):\n for j in range(i):\n coils.append(coils[-1] - 4 * n * ind)\n for j in range(i):\n coils.append(coils[-1] + ind)\n ind *= -1\n for i in range(4 * n - 1):\n coils.append(coils[-1] + 4 * n)\n return [coils, [16 * n * n + 1 - x for x in coils]]"], "starter_code": "def formcoils(n):\n", "input_output": {"inputs": ["n = 1", "n = 2"], "outputs": ["10 6 2 3 4 8 12 16\r\n7 11 15 14 13 9 5 1", "36 28 20 21 22 30 38 46\r\n54 53 52 51 50 42 34 26\r\n18 10 2 3 4 5 6 7 8\r\n16 24 32 40 48 56 64\r\n\r\n29 37 45 44 43 35 27 19\r\n11 12 13 14 15 23 31 39\r\n47 55 63 62 61 60 59 58\r\n57 49 41 33 25 17 9 1"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/form-coils-in-a-matrix4726/1", "Expected Auxiliary Space": "O(n^{2})", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(n^{2})", "entry_point": "formcoils", "task_id": "TACO_lite/293", "example": [[], []]} +{"requirement": "Given a number N. Check whether it is divisble by 4.\nExample 1:\nInput:\nN = 1124\nOutput: 1\nExplanation: The number is divisible by 4\nas 1124 % 4 = 0.\n​Example 2:\nInput: \nN = 7\nOutput: 0\nExplanation: The number is not divisibly by\n4 as 7 % 4 = 3.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function divisibleBy4() which takes the number in the form of a string N as input and returns 1 if the number is divisible by 4. Else, it returns 0.\nExpected Time Complexity: O(1).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= N <= 10^{1000}+5", "solutions": ["def divisibleby4(N):\n if int(N) % 4 == 0:\n return 1\n else:\n return 0", "def divisibleby4(N):\n if int(str(N)[-2:]) % 4 == 0:\n return 1\n return 0", "def divisibleby4(N):\n N = int(N)\n return int(not N % 4)", "def divisibleby4(N):\n result = int(N)\n ree = result % 4\n if ree == 0:\n return 1\n return 0", "def divisibleby4(n):\n if int(n) % 4 == 0:\n return 1\n return 0", "def divisibleby4(N):\n n = int(N[-2:])\n return int(not n % 4)", "def divisibleby4(N):\n if len(N) <= 2:\n return 1 if int(N) % 4 == 0 else 0\n n = len(N)\n num = int(N[n - 2:n])\n return 1 if num % 4 == 0 else 0"], "starter_code": "def divisibleby4 (N):\n", "input_output": {"inputs": ["N = 1124", "N = 7"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/check-if-divisible-by-43813/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1).", "entry_point": "divisibleby4", "task_id": "TACO_lite/423", "example": [[[1124], [7]], ["1", "0"]]} +{"requirement": "You are given a string of words (x), for each word within the string you need to turn the word 'inside out'. By this I mean the internal letters will move out, and the external letters move toward the centre. \n\nIf the word is even length, all letters will move. If the length is odd, you are expected to leave the 'middle' letter of the word where it is. \n\nAn example should clarify:\n\n'taxi' would become 'atix'\n'taxis' would become 'atxsi'", "solutions": ["import re\n\ndef inside_out(s):\n return re.sub('\\\\S+', lambda m: inside_out_word(m.group()), s)\n\ndef inside_out_word(s):\n (i, j) = (len(s) // 2, (len(s) + 1) // 2)\n return s[:i][::-1] + s[i:j] + s[j:][::-1]", "def swap(word):\n m = len(word) // 2\n if len(word) % 2 == 0:\n return word[:m][::-1] + word[m:][::-1]\n else:\n return word[:m][::-1] + word[m] + word[m + 1:][::-1]\n\ndef inside_out(st):\n return ' '.join(map(swap, st.split()))", "def inside_out(s):\n return ' '.join((w[:len(w) // 2][::-1] + w[len(w) // 2:(len(w) + 1) // 2] + w[(len(w) + 1) // 2:][::-1] for w in s.split()))", "from itertools import chain\n\ndef change(st):\n if len(st) < 4:\n return st\n (q, r) = divmod(len(st), 2)\n return ''.join(chain(st[q - 1::-1], st[q:q + r], st[:q + r - 1:-1]))\n\ndef inside_out(st):\n return ' '.join(map(change, st.split()))", "def inside_out(st):\n\n def inside_out_1(st):\n (h, m) = divmod(len(st), 2)\n return st[:h][::-1] + st[h:h + m] + st[h + m:][::-1]\n return ' '.join(map(inside_out_1, st.split(' ')))", "def inside_out(s):\n return ' '.join((w[:m][::-1] + w[m] * (L % 2) + w[-m:][::-1] * (L > 1) if w else w for (w, m, L) in map(lambda w: (w, len(w) // 2, len(w)), s.split(' '))))", "inside_out = lambda s: ' '.join([i[:len(i) // 2][::-1] + ['', i[len(i) // 2]][len(i) & 1] + i[len(i) // 2 + (len(i) & 1):][::-1] for i in s.split()])", "def inside_out(text):\n return ' '.join((next((f'{w[:i][::-1]}{w[i:j]}{w[j:][::-1]}' for (i, j) in [[len(w) // 2, (len(w) + 1) // 2]])) for w in text.split()))", "inside_out = lambda s: ' '.join((x[:l][::-1] + x[l] * n + x[l + n:][::-1] for x in s.split() for (l, n) in [(len(x) // 2, len(x) % 2)]))"], "starter_code": "def inside_out(s):\n", "input_output": {"fn_name": "inside_out", "inputs": [["man i need a taxi up to ubud"], ["what time are we climbing up the volcano"], ["take me to semynak"], ["massage yes massage yes massage"], ["take bintang and a dance please"]], "outputs": [["man i ende a atix up to budu"], ["hwta item are we milcgnib up the lovcona"], ["atek me to mesykan"], ["samsega yes samsega yes samsega"], ["atek nibtgna and a adnec elpesa"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57ebdf1c2d45a0ecd7002cd5", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "inside_out", "task_id": "TACO_lite/425", "example": [[["taxi"], ["taxis"]], ["atix", "atxsi"]]} +{"requirement": "Given a Cirular Linked List of size N, split it into two halves circular lists. If there are odd number of nodes in the given circular linked list then out of the resulting two halved lists, first list should have one node more than the second list. The resultant lists should also be circular lists and not linear lists.\n \nExample 1:\nInput:\nCircular LinkedList: 1->5->7\nOutput:\n1 5\n7\n \nExample 2:\nInput:\nCircular LinkedList: 2->6->1->5\nOutput:\n2 6\n1 5\nYour Task:\nYour task is to complete the given function splitList(), which takes 3 input parameters: The address of the head of the linked list, addresses of the head of the first and second halved resultant lists and Set the head1_ref and head2_ref to the first resultant list and second resultant list respectively.\nExpected Time Complexity: O(N)\nExpected Auxilliary Space: O(1)\nConstraints:\n1 <= N <= 100", "solutions": ["def splitList(head, head1, head2):\n if head == None or head.next == head:\n return head\n count = 1\n head1 = head\n curr = head\n prev = None\n while curr.next != head:\n count += 1\n curr = curr.next\n prev = curr\n if count % 2 == 0:\n A = count // 2\n temp = head\n for i in range(A - 1):\n temp = temp.next\n head2 = temp.next\n temp.next = None\n temp.next = head1\n prev.next = head2\n else:\n A = count // 2\n temp = head\n for i in range(A):\n temp = temp.next\n head2 = temp.next\n temp.next = None\n temp.next = head1\n prev.next = None\n prev.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n node = head.next\n prev = head\n count = 1\n while head != node:\n prev = prev.next\n node = node.next\n count += 1\n if count % 2 == 0:\n count = count // 2\n else:\n count = count // 2 + 1\n node = head\n while count > 1:\n node = node.next\n count -= 1\n head1 = head\n head2 = node.next\n node.next = head1\n prev.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n if not head:\n return None\n slow = head\n fast = head.next\n while fast != head and fast.next != head:\n slow = slow.next\n fast = fast.next.next\n head1 = head\n head2 = slow.next\n slow.next = head1\n curr = head2\n while curr.next != head:\n curr = curr.next\n curr.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n fast = head\n slow = head\n while fast.next != head and fast.next.next != head:\n fast = fast.next.next\n slow = slow.next\n head1 = head\n head2 = slow.next\n slow.next = head1\n front = head2\n while front.next != head:\n front = front.next\n front.next = head2\n return (head1, head2)", "import math\n\ndef splitList(head, head1, head2):\n s = set()\n itr = head\n l = 0\n while itr not in s:\n s.add(itr)\n itr = itr.next\n l += 1\n hlf = math.ceil(l / 2)\n (itr, head1, k) = (head, head, 0)\n while k < hlf - 1:\n itr = itr.next\n k += 1\n nxt = itr.next\n head2 = nxt\n itr.next = None\n itr.next = head\n k = 0\n while k < l - hlf - 1:\n nxt = nxt.next\n k += 1\n nxt.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n slow = head\n fast = head.next\n head1 = head\n while slow and fast and fast.next:\n if fast == head or fast.next == head:\n head2 = slow.next\n slow.next = head\n break\n else:\n slow = slow.next\n fast = fast.next.next\n temp = head2\n while temp.next != head:\n temp = temp.next\n temp.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n count = 1\n tmp = head.next\n while tmp != head:\n count += 1\n tmp = tmp.next\n if count % 2 == 0:\n count = count / 2\n else:\n count = int(count / 2) + 1\n tmp = head\n head1 = head\n ct = 1\n while ct < count:\n ct += 1\n tmp = tmp.next\n head2 = tmp.next\n tmp.next = head1\n tmp = head2\n while tmp.next != head:\n tmp = tmp.next\n tmp.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n slowPtr = fastPtr = head\n while fastPtr.next != head and fastPtr.next.next != head:\n fastPtr = fastPtr.next.next\n slowPtr = slowPtr.next\n head2 = slowPtr.next\n slowPtr.next = head\n head1 = head\n trav = head2\n while trav.next != head:\n trav = trav.next\n trav.next = head2\n return (head1, head2)", "def __init__():\n self.data = None\n self.next = None\n\ndef splitList(head, head1, head2):\n n = head\n L = []\n while n.next != head:\n L.append(n.data)\n n = n.next\n L.append(n.data)\n if len(L) % 2 == 0:\n l = int(len(L) // 2) - 1\n else:\n l = int(len(L) // 2)\n head1 = head\n n1 = head1\n while l != 0:\n n1 = n1.next\n l = l - 1\n head2 = n1.next\n n1.next = head\n n.next = head2\n return (head1, head2)", "def splitList(h, h1, h2):\n f = h\n c = 1\n h1 = h2 = t = h\n while f.next != h:\n f = f.next\n c += 1\n if c % 2 == 0:\n c = c // 2\n else:\n c = c // 2 + 1\n while c != 0:\n t = h2\n h2 = h2.next\n c -= 1\n t.next = h1\n f.next = h2\n return (h1, h2)", "def splitList(head, head1, head2):\n length = 0\n curr = head\n while curr != None:\n length += 1\n if curr.next == head:\n break\n curr = curr.next\n m = length // 2\n if length % 2 != 0:\n m += 1\n head1 = None\n head2 = None\n head1 = head\n curr = head\n count = 0\n while curr != None:\n count += 1\n if count == m:\n temp = curr\n curr = curr.next\n temp.next = head1\n break\n curr = curr.next\n head2 = curr\n while curr != None:\n count += 1\n if count == length:\n curr.next = head2\n break\n curr = curr.next\n return (head1, head2)", "def splitList(head, head1, head2):\n (head1, head2) = (head, head)\n (ptr1, ptr2) = (head, head)\n while ptr2.next != head:\n ptr2 = ptr2.next\n ptr2.next = None\n ptr2 = head\n while ptr2 and ptr2.next:\n ptr1 = ptr1.next\n ptr2 = ptr2.next\n ptr2 = ptr2.next if ptr2 else ptr2\n head2 = ptr1.next if ptr2 else ptr1\n (ptr1, ptr2) = (head1, head2)\n while ptr1.next != ptr2:\n ptr1 = ptr1.next\n ptr1.next = head1\n while ptr2.next:\n ptr2 = ptr2.next\n ptr2.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n temp = head\n c = 1\n while temp.next != head:\n c += 1\n temp = temp.next\n temp1 = head\n if c % 2 == 0:\n c = c // 2\n i = 1\n while i != c:\n temp1 = temp1.next\n i += 1\n const = temp1.next\n temp1.next = head\n head1 = head\n temp.next = const\n head2 = const\n else:\n c = c // 2 + 1\n i = 1\n while i != c:\n temp1 = temp1.next\n i += 1\n const = temp1.next\n temp1.next = head\n head1 = head\n temp.next = const\n head2 = const\n return (head1, head2)", "def __init__(data):\n self.data = data\n self.next = None\n\ndef splitList(head, head1, head2):\n if head is None:\n return (head1, head2)\n slow = head\n fast = head\n while fast.next != head and fast.next.next != head:\n slow = slow.next\n fast = fast.next.next\n if fast.next.next == head:\n fast = fast.next\n head1 = head\n head2 = slow.next\n slow.next = head1\n fast.next = head2\n return (head1, head2)", "import math\n\ndef splitList(head, head1, head2):\n p = head\n q = head\n if head.next == None:\n return (head, head)\n count = 0\n while p:\n count += 1\n q = p\n p = p.next\n if p == head:\n q.next = None\n break\n count = math.ceil(count / 2)\n p = head\n r = head\n while count != 0:\n r = p\n p = p.next\n count -= 1\n r.next = head\n q.next = p\n head1 = head\n head2 = p\n return (head1, head2)", "def splitList(head, head1, head2):\n (temp1, temp2) = (head, head.next)\n while temp2 != head and temp2.next != head:\n temp1 = temp1.next\n temp2 = temp2.next.next\n head1 = head\n head2 = temp1.next\n if temp2.next == head:\n temp2.next = temp1.next\n else:\n pre = None\n new = temp1.next\n while new != head:\n pre = new\n new = new.next\n pre.next = temp1.next\n temp1.next = head\n return (head1, head2)", "def splitList(head, head1, head2):\n cur = temp = head\n c = 0\n l = []\n while cur not in l:\n l.append(cur)\n prev = cur\n cur = cur.next\n c += 1\n prev.next = None\n head1 = cur\n if c % 2 == 0:\n i = c // 2\n else:\n i = c // 2 + 1\n j = 0\n while j < i:\n j += 1\n prev = cur\n cur = cur.next\n prev.next = head1\n head2 = cur\n while cur != None:\n prev = cur\n cur = cur.next\n prev.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n (tmp, t) = (head, head)\n n = 0\n while t.next != head:\n n += 1\n t = t.next\n n = n // 2\n head1 = tmp\n while n:\n n -= 1\n tmp = tmp.next\n head2 = tmp.next\n tmp.next = head\n tmp = head2\n while 1:\n if tmp.next == head:\n tmp.next = head2\n break\n tmp = tmp.next\n return (head1, head2)", "def splitList(head, head1, head2):\n temp = slow = fast = head\n slow_left = None\n fast_left = None\n if head == None:\n head1 = None\n head2 = None\n return (head1, head2)\n traversed = True\n while temp != fast and temp != fast.next or traversed:\n traversed = False\n slow_left = slow\n slow = slow.next\n fast_left = fast.next\n fast = fast.next.next\n if temp == fast.next:\n head2 = slow.next\n fast.next = slow.next\n slow.next = head\n head1 = head\n if temp == fast:\n slow_left.next = head\n head1 = head\n head2 = slow\n fast_left.next = slow\n return (head1, head2)", "def splitList(head, a, b):\n slow = head\n fast = head.next\n a = head\n while fast != head and fast.next != head:\n slow = slow.next\n fast = fast.next.next\n b = slow.next\n slow.next = head\n p = b\n while p.next != head:\n p = p.next\n p.next = b\n return (a, b)", "def splitList(head, head1, head2):\n p = r = head\n q = head.next\n c = 1\n while True:\n if r.next != head:\n c += 1\n r = r.next\n else:\n break\n if c % 2 == 0:\n t = int(c / 2)\n else:\n t = int((c + 1) / 2)\n for i in range(t - 1):\n p = q\n q = q.next\n p.next = head\n r.next = q\n head1 = head\n head2 = q\n return (head1, head2)", "def splitList(head, head1, head2):\n slow = head\n fast = head.next\n while fast != head and fast.next != head:\n p = fast\n slow = slow.next\n fast = fast.next.next\n if p.next.next == head:\n fast = p.next\n a = slow.next\n slow.next = head\n fast.next = a\n head1 = head\n head2 = a\n return (head1, head2)", "def splitList(head, head1, head2):\n slow = head\n fast = head.next\n while fast != head and fast.next != head:\n fast = fast.next.next\n slow = slow.next\n aftermid = slow.next\n slow.next = head\n head1 = head\n temp = aftermid\n while temp.next != head:\n temp = temp.next\n temp.next = aftermid\n head2 = aftermid\n return (head1, head2)", "def splitList(head, head1, head2):\n (head1, head2) = (head, head)\n while head2.next is not head and head2.next.next is not head:\n head1 = head1.next\n head2 = head2.next.next\n if head2.next is not head:\n head2 = head2.next\n head2.next = head1.next\n head2 = head2.next\n head1.next = head\n head1 = head1.next\n return (head1, head2)", "import math\n\ndef splitList(head, head1, head2):\n slow = head\n fast = head.next\n while fast != head and fast.next != head:\n slow = slow.next\n prev = fast.next\n fast = fast.next.next\n head1 = head\n head2 = slow.next\n slow.next = head\n if fast == head:\n prev.next = head2\n else:\n fast.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n s = head\n f = head\n count = 1\n while f is not None:\n f = f.next\n if f == head:\n break\n count += 1\n if count % 2 == 0:\n loop_c = count // 2\n else:\n loop_c = count // 2 + 1\n n = head\n head1 = n\n prev = None\n while loop_c:\n loop_c -= 1\n prev = n\n n = n.next\n prev.next = head\n head1 = head\n head2 = n\n p = head2\n prev = None\n while head2:\n prev = p\n p = p.next\n if head == p:\n break\n prev.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n start = head\n end = head\n while end.next != head and end.next.next != head:\n end = end.next.next\n start = start.next\n temp = start.next\n start.next = head\n head1 = head\n if end.next == head:\n end.next = temp\n else:\n end.next.next = temp\n head2 = temp\n return (head1, head2)", "def splitList(head, head1, head2):\n temp = head\n end1 = head\n N = 1\n end = head\n start = head\n while head:\n if head.next == start:\n break\n head = head.next\n N += 1\n end = head\n for i in range(N // 2 + N % 2 - 1):\n end1 = end1.next\n head2 = end1.next\n end.next = head2\n end1.next = start\n return (start, head2)", "def splitList(head, head1, head2):\n size = 1\n head2 = head1 = head\n while head:\n if head.next == head1:\n break\n head = head.next\n size += 1\n if size % 2 == 0:\n size -= 1\n for _ in range(size // 2):\n head2 = head2.next\n k = head2\n head2 = head2.next\n k.next = head1\n head.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n if head.next.next == None:\n node1 = head\n node2 = head.next\n node1.next = node1\n node2.next = node2\n slow = head\n fast = head\n while fast.next != head and fast.next.next != head:\n slow = slow.next\n fast = fast.next.next\n head1 = head\n head2 = slow.next\n slow.next = head\n temp = head2\n while temp.next != head:\n temp = temp.next\n temp.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n s = head\n f = head\n while f.next != head and f.next.next != head:\n s = s.next\n f = f.next.next\n if f.next.next == head:\n f = f.next\n head1 = head\n if head.next != head:\n head2 = s.next\n f.next = s.next\n s.next = head\n return (head1, head2)", "def splitList(head, head1, head2):\n fast = head\n slow = head\n while fast.next != head and fast.next.next != head:\n fast = fast.next.next\n slow = slow.next\n if fast.next.next == head:\n fast = fast.next\n fast.next = slow.next\n tmp = slow.next\n slow.next = head\n head1 = head\n head2 = tmp\n return (head1, head2)", "def splitList(head, head1, head2):\n (slow, fast, prev) = (head, head, head)\n while True:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n if fast == head or fast == head.next:\n break\n fast = slow\n while fast.next is not head:\n fast = fast.next\n (fast.next, prev.next) = (prev.next, head)\n head1 = head\n head2 = slow\n return (head1, head2)", "def splitList(head, head1, head2):\n slow = head\n fast = head.next\n while fast != head and fast.next != head:\n slow = slow.next\n fast = fast.next.next\n mid = slow\n head1 = head\n head2 = mid.next\n mid.next = head1\n tail = head2\n while tail.next != head:\n tail = tail.next\n tail.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n b = 0\n tmp = head\n while tmp.next != head:\n b += 1\n tmp = tmp.next\n c = b // 2\n head1 = head\n tmp = head\n i = 0\n prev = tmp\n while i < c:\n prev = tmp\n tmp = tmp.next\n i += 1\n head2 = tmp.next\n tmp.next = head1\n tmp = head2\n while tmp.next != head:\n tmp = tmp.next\n tmp.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n (nd, N) = (head.next, 1)\n while nd != head:\n N += 1\n nd = nd.next\n N1 = (N + 1) // 2\n N2 = N - N1\n head1 = head\n nd = head1\n for _ in range(N1 - 1):\n nd = nd.next\n head2 = nd.next\n nd.next = head1\n nd = head2\n for _ in range(N2 - 1):\n nd = nd.next\n nd.next = head2\n return (head1, head2)", "import math\n\ndef splitList(head, head1, head2):\n if head is None:\n return None\n count = 0\n current = head\n while current.next != head:\n count += 1\n current = current.next\n count += 1\n mid = math.ceil(count / 2)\n head1 = head\n current = head\n for i in range(mid - 1):\n current = current.next\n if head.next != head:\n head2 = current.next\n current.next = head1\n current2 = head2\n while current2.next != head:\n current2 = current2.next\n current2.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n n = 1\n t = head\n while t.next != head:\n n += 1\n t = t.next\n if n % 2 == 0:\n s = int((n - 1) / 2)\n else:\n s = int(n / 2)\n head1 = head\n t1 = head1\n for i in range(s):\n t1 = t1.next\n head2 = t1.next\n t1.next = head1\n t2 = head2\n while t2.next != head:\n t2 = t2.next\n t2.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n slow = head\n fast = head\n while fast.next != head:\n if fast.next.next == head:\n fast = fast.next\n else:\n fast = fast.next.next\n slow = slow.next\n head1 = head\n head2 = slow.next\n fast.next = slow.next\n slow.next = head\n return (head1, head2)", "def splitList(head, head1, head2):\n slow_ptr = head\n fast_ptr = head\n if head is None:\n return\n while fast_ptr.next != head and fast_ptr.next.next != head:\n fast_ptr = fast_ptr.next.next\n slow_ptr = slow_ptr.next\n if fast_ptr.next.next == head:\n fast_ptr = fast_ptr.next\n head1 = head\n if head.next != head:\n head2 = slow_ptr.next\n fast_ptr.next = slow_ptr.next\n slow_ptr.next = head\n return (head1, head2)\n return (head1, head2)", "def splitList(head, head1, head2):\n if head is None:\n return (None, None)\n count = 1\n temp = head\n while temp.next is not head:\n temp = temp.next\n count += 1\n mid_val = 0\n if count & 1:\n mid_val = count // 2 + 1\n else:\n mid_val = count // 2\n temp = head\n prev = Node()\n prev.next = head\n moving_counter = 0\n while moving_counter < mid_val:\n temp = temp.next\n moving_counter += 1\n prev = prev.next\n prev.next = head\n second_head = temp\n while temp.next is not head:\n temp = temp.next\n temp.next = second_head\n head1 = head\n head2 = second_head\n return (head1, head2)", "def splitList(head, head1, head2):\n if head is None:\n return (None, None)\n count = 1\n temp = head\n while temp.next is not head:\n count += 1\n temp = temp.next\n mid = count // 2\n if count % 2 != 0:\n mid += 1\n temp2 = head\n while mid != 1:\n temp2 = temp2.next\n mid -= 1\n head2 = temp2.next\n temp.next = head2\n temp2.next = head\n head1 = head\n return (head1, head2)", "def splitList(head, head1, head2):\n x = head\n y = head\n z = head.next\n pre = x\n pre1 = y\n while True:\n pre = x\n pre1 = y\n x = x.next\n y = y.next.next\n if y == head:\n pre1.next.next = x\n break\n if y == z:\n pre1.next = x\n break\n pre.next = head\n head1 = head\n head2 = x\n return (head1, head2)", "def splitList(head, head1, head2):\n curr = head.next\n n = 0\n while True:\n if curr != head:\n n += 1\n else:\n n += 1\n break\n curr = curr.next\n if n % 2 == 0:\n curr = head\n i = 1\n while i < n // 2:\n curr = curr.next\n i += 1\n head1 = head\n head2 = curr.next\n curr.next = head1\n curr = head2\n i = 1\n while i < n // 2:\n curr = curr.next\n i += 1\n curr.next = head2\n else:\n curr = head\n i = 1\n while i <= n // 2:\n curr = curr.next\n i += 1\n head1 = head\n head2 = curr.next\n curr.next = head1\n curr = head2\n i = 1\n while i < n // 2:\n curr = curr.next\n i += 1\n curr.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n head1 = head\n i = 2\n while head.next is not head1:\n head = head.next\n i += 1\n n = i // 2\n for _ in range(n):\n head = head.next\n head2 = head.next\n head.next = head1\n head = head2\n while head.next is not head1:\n head = head.next\n head.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n s = f = head\n if head.next == head or head == None:\n head1 = head\n head2 = None\n return (head1, head2)\n while f.next != head and f.next.next != head:\n s = s.next\n f = f.next.next\n mid = s\n head1 = head\n h2 = head2 = mid.next\n mid.next = head1\n temp = head\n while h2.next != head:\n h2 = h2.next\n h2.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n ptr = head\n count = 0\n while ptr.next != head:\n count += 1\n ptr = ptr.next\n count += 1\n mid = (count - 1) // 2\n head1 = head\n ptr = head\n while mid:\n ptr = ptr.next\n mid -= 1\n head2 = ptr.next\n ptr.next = head1\n ptr = head2\n while ptr.next != head:\n ptr = ptr.next\n ptr.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n temp = head\n head1 = head\n count = 1\n while temp.next != head:\n count += 1\n temp = temp.next\n temp.next = None\n temp = head\n c = count // 2\n while c - 1:\n temp = temp.next\n c -= 1\n if count % 2 == 0:\n head2 = temp.next\n temp.next = head1\n else:\n head2 = temp.next.next\n temp.next.next = head1\n temp = head2\n while temp.next:\n temp = temp.next\n temp.next = head2\n return (head1, head2)"], "starter_code": "def __init__(self):\n", "input_output": {"inputs": ["Circular LinkedList:1->5->7", "Circular LinkedList:2->6->1->5"], "outputs": ["1 5\n7", "2 6\n1 5"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "circular-linked-list", "Linked List"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/split-a-circular-linked-list-into-two-halves/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "__init__", "task_id": "TACO_lite/426", "example": [[], []]} +{"requirement": "Given an integer N, find it's parity. \nParity of a number refers to the number of 1 bits it contains. The number has “odd parity”, if it contains odd number of 1-bits and is “even parity” if it contains even number of 1-bits.\nExample 1:\nInput:\nN = 13\nOutput: odd\nExplanation:\n(13)_{10} = (1101)_{2} The binary representation\nhas three 1-bits. So, it's parity is odd.\nExample 2:\nInput:\nN = 9\nOutput: even\nExplanation:\n(9)_{10} = (1001)_{2} The binary representation\nhas two 1-bits. So, it's parity is even.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function computeParity() which takes an Integer N as input parameter and returns string \"odd\" or \"even\".\n \nExpected Time Complexity: O(log(N))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= N <= 10^{5}", "solutions": ["def computeparity(N):\n x = bin(N)[2:]\n a = x.count('1')\n if a % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n one = 0\n while N != 0:\n one += 1\n N &= N - 1\n if one & 1 == 1:\n return 'odd'\n return 'even'", "def computeparity(N):\n t = format(N, 'b')\n sum = 0\n for i in t:\n if i == '1':\n sum = sum + 1\n if sum % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n ans = 0\n while N:\n ans += 1\n N &= N - 1\n return 'odd' if ans % 2 else 'even'", "def computeparity(N):\n N = bin(N)[2:]\n if N.count('1') % 2 == 1:\n return 'odd'\n return 'even'", "def computeparity(N):\n summa = sum((item == '1' for item in bin(N)[2:]))\n return 'odd' if summa % 2 else 'even'", "def computeparity(N):\n N ^= N >> 16\n N ^= N >> 8\n N ^= N >> 4\n N ^= N >> 2\n N ^= N >> 1\n return 'odd' if N & 1 else 'even'", "def computeparity(N):\n c = 0\n while N != 0:\n if N % 2 != 0:\n c += 1\n N = N >> 1\n if c % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n a = str(bin(N).replace('0b', ''))\n b = a.count('1') % 2\n if b == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n result = 0\n while N:\n N &= N - 1\n result ^= 1\n return 'odd' if result else 'even'", "def computeparity(N):\n m = bin(N).replace('0b', '')\n p = m.count('1')\n if p % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(n):\n count = 0\n while n:\n n = n & n - 1\n count += 1\n if count & 1 == 1:\n return 'odd'\n return 'even'", "def computeparity(N):\n count = 0\n while N > 0:\n if N % 2 == 1:\n count += 1\n N = int(N / 2)\n if count % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n c = 0\n n = bin(N)[2:]\n for i in n:\n if i == '1':\n c += 1\n if c % 2:\n return 'odd'\n return 'even'", "def computeparity(N):\n b = bin(N)[2:]\n count = b.count('1')\n return 'odd' if count % 2 != 0 else 'even'", "def computeparity(N):\n binary = str(bin(N))\n count_1_bits = binary.count('1')\n if count_1_bits % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n N = bin(N)[2:]\n x = str(N)\n y = x.count('1')\n if y % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n res = 0\n N ^= N >> 32\n N ^= N >> 16\n N ^= N >> 8\n N ^= N >> 4\n N ^= N >> 2\n N ^= N >> 1\n res = N & 1\n if res % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def __init__():\n self.TABLE_BITS = 4\n self.table = 0\n for i in range(1 << self.TABLE_BITS):\n if self.parity(i):\n self.table |= 1 << i\n self.mask = (1 << self.TABLE_BITS) - 1\n\ndef parity(n):\n odd = False\n while n & -n:\n odd = not odd\n n &= n - 1\n return odd\n\ndef computeparity(N):\n odd = False\n while N:\n if self.table & 1 << (N & self.mask):\n odd = not odd\n N >>= self.TABLE_BITS\n if odd:\n return 'odd'\n return 'even'", "def computeparity(N):\n odd = False\n while N:\n odd = not odd\n N &= N - 1\n if odd:\n return 'odd'\n return 'even'", "def computeparity(n):\n n ^= n >> 32\n n ^= n >> 16\n n ^= n >> 8\n n ^= n >> 4\n n ^= n >> 2\n n ^= n >> 1\n if n & 1 == 1:\n return 'odd'\n else:\n return 'even'", "def computeparity(N):\n count = self.countOnes(N)\n return 'odd' if count & 1 else 'even'\n\ndef countOnes(N):\n count = 0\n while N:\n if N & 1:\n count += 1\n N = N >> 1\n return count", "def computeparity(N):\n s = bin(N)\n c = 0\n i = 0\n while i < len(s):\n if s[i] == '1':\n c += 1\n i += 1\n if c % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n repr = list(bin(N))[2:]\n return 'even' if repr.count('1') % 2 == 0 else 'odd'", "def computeparity(N):\n binary_N = bin(N)\n count = 0\n for l in binary_N:\n if l == '1':\n count += 1\n if count % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n A = bin(N)\n B = str(A).count('1')\n if B % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n temp = N\n parity = 0\n while temp > 0:\n if temp % 2 == 1:\n parity += 1\n temp //= 2\n if parity % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n arr = []\n while N:\n arr.append(N % 2)\n N //= 2\n c = 0\n for i in range(len(arr)):\n if arr[i] == 1:\n c += 1\n if c % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n x = bin(N).replace('0b', '')\n if x.count('1') % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n c = []\n while N > 0:\n a = N % 2\n c.append(a)\n N = N // 2\n if c.count(1) % 2 == 1:\n return 'odd'\n return 'even'", "def computeparity(N):\n binary_rep = str(bin(N)).replace('0b', '')\n number_of_ones = 0\n for digit in binary_rep:\n if digit == '1':\n number_of_ones += 1\n if number_of_ones & 1 == 1:\n return 'odd'\n return 'even'", "def computeparity(N):\n x = str('{0:b}'.format(int(N)))\n count = x.count('1')\n if count % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n dec = self.decimal(N)\n count = 0\n for i in str(dec):\n if i == '1':\n count += 1\n if count % 2 == 0:\n return 'even'\n return 'odd'\n\ndef decimal(N):\n return bin(N).replace('0b', '')", "def computeparity(N):\n b = bin(N)\n s = str(b)\n if s.count('1') % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n parity = 0\n n = N\n while n > 0:\n if n & 1 == 1:\n parity = ~parity\n n = n >> 1\n if parity == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n c = 0\n x = bin(N)\n for i in x:\n if i == '1':\n c += 1\n else:\n continue\n if c % 2 == 0:\n return 'even'\n elif c % 2 != 0:\n return 'odd'", "def computeparity(N):\n count = 0\n s = bin(N).replace('0b', '')\n for i in s:\n if i == '1':\n count += 1\n if count % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n return 'even' if sum(list(map(int, bin(N)[2:]))) % 2 == 0 else 'odd'", "def computeparity(N):\n Count = 0\n even1 = 'even'\n odd1 = 'odd'\n while N:\n if N & 1 == 1:\n Count += 1\n N = N >> 1\n if Count % 2 == 0:\n return even1\n else:\n return odd1"], "starter_code": "def computeparity(N):\n", "input_output": {"inputs": ["N = 13", "N = 9"], "outputs": ["odd", "even"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Algorithms", "Bit Magic", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures", "Mathematics"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/parity-of-unsigned-integer4247/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(N))", "entry_point": "computeparity", "task_id": "TACO_lite/401", "example": [[], []]} +{"requirement": "##Task:\n\nYou have to write a function **pattern** which creates the following pattern upto n number of rows. *If the Argument is 0 or a Negative Integer then it should return \"\" i.e. empty string.*\n\n##Pattern:\n\n (n)\n (n)(n-1)\n (n)(n-1)(n-2)\n ................\n .................\n (n)(n-1)(n-2)....4\n (n)(n-1)(n-2)....43\n (n)(n-1)(n-2)....432\n (n)(n-1)(n-2)....4321\n \n##Examples:\n\npattern(4):\n\n 4\n 43\n 432\n 4321\n \npattern(6):\n \n 6\n 65\n 654\n 6543\n 65432\n 654321\n\n\n\n```Note: There are no blank spaces```\n\n```Hint: Use \\n in string to jump to next line```", "solutions": ["def pattern(n):\n return '\\n'.join((''.join((str(i) for i in range(n, j, -1))) for j in range(n - 1, -1, -1)))", "def pattern(n):\n full = [str(x) for x in range(n, 0, -1)]\n take = lambda x: ''.join(full[:x])\n return '\\n'.join((take(x) for x in range(1, n + 1)))", "pattern = lambda n: '\\n'.join((''.join((str(n - j) for j in range(i + 1))) for i in range(n)))", "def pattern(n):\n a = [str(i) for i in range(n, 0, -1)]\n return '\\n'.join((''.join(a[:i]) for i in range(1, n + 1)))", "def pattern(n):\n return '\\n'.join([''.join([str(y) for y in range(n, n - x - 1, -1)]) for x in range(n)])", "def pattern(n):\n (out, s) = ([], '')\n for i in reversed(range(1, n + 1)):\n s += str(i)\n out.append(s)\n return '\\n'.join(out)", "def pattern(n):\n return '\\n'.join([''.join(map(str, list(range(n, n - i, -1)))) for i in range(1, n + 1)])"], "starter_code": "def pattern(n):\n", "input_output": {"fn_name": "pattern", "inputs": [[1], [2], [5], [0], [-25]], "outputs": [["1"], ["2\n21"], ["5\n54\n543\n5432\n54321"], [""], [""]]}, "difficulty": "EASY", "raw_tags": ["ASCII Art", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/557341907fbf439911000022", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "pattern", "task_id": "TACO_lite/353", "example": [[], []]} +{"requirement": "Return the century of the input year. The input will always be a 4 digit string, so there is no need for validation. \n\n### Examples\n```\n\"1999\" --> \"20th\"\n\"2011\" --> \"21st\"\n\"2154\" --> \"22nd\"\n\"2259\" --> \"23rd\"\n\"1124\" --> \"12th\"\n\"2000\" --> \"20th\"\n```", "solutions": ["def what_century(year):\n n = (int(year) - 1) // 100 + 1\n return str(n) + ('th' if n < 20 else {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th'))", "def what_century(year):\n year = str(year)\n st = year[:2]\n st = int(st)\n gt = st + 1\n gt = str(gt)\n if year != '0000' and year[1:] != '000' and (year[2:] != '00'):\n if len(gt) == 2:\n if gt[0] == '1' and gt[1] == '0':\n return '10th'\n elif gt[0] == '1' and gt[1] in range(1, 10):\n return f'{gt}th'\n elif gt[0] != '1' and gt[1] == '0':\n return f'{gt}th'\n elif gt[0] != '1' and gt[1] == '1':\n return f'{gt}st'\n elif gt[0] != '1' and gt[1] == '2':\n return f'{gt}nd'\n elif gt[0] != '1' and gt[1] == '3':\n return f'{gt}rd'\n else:\n return f'{gt}th'\n elif gt[0] == 1:\n return '1st'\n elif gt[0] == 2:\n return '2nd'\n elif gt[0] == 3:\n return '3rd'\n else:\n return f'{gt}th'\n elif year[1:] == '000' and year != '0000':\n return f'{year[0]}0th'\n elif year[2:] == '00' and year[1:] != '000' and (year != '0000'):\n if year[1] == '1':\n return f'{year[:2]}st'\n elif year[2] == '2':\n return f'{year[:2]}nd'\n elif year[2] == '3':\n return f'{year[:2]}rd'\n else:\n return f'{year[:2]}th'\n elif year == '0000':\n return '0th'", "def what_century(year):\n if 100 >= int(year) > 0:\n return '1st'\n if 200 >= int(year) > 100:\n return '2nd'\n if 300 >= int(year) > 200:\n return '3rd'\n if 400 >= int(year) > 300:\n return '4th'\n if 500 >= int(year) > 400:\n return '5th'\n if 600 >= int(year) > 500:\n return '6th'\n if 700 >= int(year) > 600:\n return '7th'\n if 800 >= int(year) > 700:\n return '8th'\n if 900 >= int(year) > 800:\n return '9th'\n if 1000 >= int(year) > 900:\n return '10th'\n if 1100 >= int(year) > 1000:\n return '11th'\n if 1200 >= int(year) > 1100:\n return '12th'\n if 1300 >= int(year) > 1200:\n return '13th'\n if 1400 >= int(year) > 1300:\n return '14th'\n if 1500 >= int(year) > 1400:\n return '15th'\n if 1600 >= int(year) > 1500:\n return '16th'\n if 1700 >= int(year) > 1600:\n return '17th'\n if 1800 >= int(year) > 1700:\n return '18th'\n if 1900 >= int(year) > 1800:\n return '19th'\n if 2000 >= int(year) > 1900:\n return '20th'\n if 2100 >= int(year) > 2000:\n return '21st'\n if 2200 >= int(year) > 2100:\n return '22nd'\n if 2300 >= int(year) > 2200:\n return '23rd'\n if 2400 >= int(year) > 2300:\n return '24th'\n if 2500 >= int(year) > 2400:\n return '25th'\n if 2600 >= int(year) > 2500:\n return '26th'\n if 2700 >= int(year) > 2600:\n return '27th'\n if 2800 >= int(year) > 2700:\n return '28th'\n if 2900 >= int(year) > 2800:\n return '29th'\n if 3000 >= int(year) > 2900:\n return '30th'\n if 3100 >= int(year) > 3000:\n return '31st'\n if 3200 >= int(year) > 3100:\n return '32nd'\n if 3300 >= int(year) > 3200:\n return '33rd'\n if 3400 >= int(year) > 3300:\n return '34th'\n if 3500 >= int(year) > 3400:\n return '35th'\n if 3600 >= int(year) > 3500:\n return '36th'\n if 3700 >= int(year) > 3600:\n return '37th'\n if 3800 >= int(year) > 3700:\n return '38th'\n if 3900 >= int(year) > 3800:\n return '39th'\n if 4000 >= int(year) > 3900:\n return '40th'\n if 4100 >= int(year) > 4000:\n return '41st'\n if 4200 >= int(year) > 4100:\n return '42nd'\n if 4300 >= int(year) > 4200:\n return '43rd'\n if 4400 >= int(year) > 4300:\n return '44th'\n if 4500 >= int(year) > 4400:\n return '45th'\n if 4600 >= int(year) > 4500:\n return '46th'\n if 4700 >= int(year) > 4600:\n return '47th'\n if 4800 >= int(year) > 4700:\n return '48th'\n if 4900 >= int(year) > 4800:\n return '49th'\n if 5000 >= int(year) > 4900:\n return '50th'\n if 5100 >= int(year) > 5000:\n return '51st'\n if 5200 >= int(year) > 5100:\n return '52nd'\n if 5300 >= int(year) > 5200:\n return '53rd'\n if 5400 >= int(year) > 5300:\n return '54th'\n if 5500 >= int(year) > 5400:\n return '55th'\n if 5600 >= int(year) > 5500:\n return '56th'\n if 5700 >= int(year) > 5600:\n return '57th'\n if 5800 >= int(year) > 5700:\n return '58th'\n if 5900 >= int(year) > 5800:\n return '59th'\n if 6000 >= int(year) > 5900:\n return '60th'\n if 6100 >= int(year) > 6000:\n return '61st'\n if 6200 >= int(year) > 6100:\n return '62nd'\n if 6300 >= int(year) > 6200:\n return '63rd'\n if 6400 >= int(year) > 6300:\n return '64th'\n if 6500 >= int(year) > 6400:\n return '65th'\n if 6600 >= int(year) > 6500:\n return '66th'\n if 6700 >= int(year) > 6600:\n return '67th'\n if 6800 >= int(year) > 6700:\n return '68th'\n if 6900 >= int(year) > 6800:\n return '69th'\n if 7000 >= int(year) > 6900:\n return '70th'\n if 7100 >= int(year) > 7000:\n return '71st'\n if 7200 >= int(year) > 7100:\n return '72nd'\n if 7300 >= int(year) > 7200:\n return '73rd'\n if 7400 >= int(year) > 7300:\n return '74th'\n if 7500 >= int(year) > 7400:\n return '75th'\n if 7600 >= int(year) > 7500:\n return '76th'\n if 7700 >= int(year) > 7600:\n return '77th'\n if 7800 >= int(year) > 7700:\n return '78th'\n if 7900 >= int(year) > 7800:\n return '79th'\n if 8000 >= int(year) > 7900:\n return '80th'\n if 8100 >= int(year) > 8000:\n return '81st'\n if 8200 >= int(year) > 8100:\n return '82nd'\n if 8300 >= int(year) > 8200:\n return '83rd'\n if 8400 >= int(year) > 8300:\n return '84th'\n if 8500 >= int(year) > 8400:\n return '85th'\n if 8600 >= int(year) > 8500:\n return '86th'\n if 8700 >= int(year) > 8600:\n return '87th'\n if 8800 >= int(year) > 8700:\n return '88th'\n if 8900 >= int(year) > 8800:\n return '89th'\n if 9000 >= int(year) > 8900:\n return '90th'\n if 9100 >= int(year) > 9000:\n return '91st'\n if 9200 >= int(year) > 9100:\n return '92nd'\n if 9300 >= int(year) > 9200:\n return '93rd'\n if 9400 >= int(year) > 9300:\n return '94th'\n if 9500 >= int(year) > 9400:\n return '95th'\n if 9600 >= int(year) > 9500:\n return '96th'\n if 9700 >= int(year) > 9600:\n return '97th'\n if 9800 >= int(year) > 9700:\n return '98th'\n if 9900 >= int(year) > 9800:\n return '99th'\n if 10000 >= int(year) > 9900:\n return '100th'", "def what_century(year):\n ordinal = lambda n: '%d%s' % (n, 'tsnrhtdd'[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10::4])\n return ordinal((int(year) - 1) // 100 + 1)", "def what_century(year):\n if year[2:] == '00':\n century = year[:2]\n else:\n century = str(int(year) // 100 + 1)\n suffix = 'th'\n if century[0] == '1':\n pass\n elif century[1] == '1':\n suffix = 'st'\n elif century[1] == '2':\n suffix = 'nd'\n elif century[1] == '3':\n suffix = 'rd'\n return century + suffix", "def what_century(year):\n y = int(year)\n (c, r) = divmod(y, 100)\n if r:\n c += 1\n ones = c % 10\n tens = c // 10 % 10\n if tens == 1:\n suffix = 'th'\n elif ones == 1:\n suffix = 'st'\n elif ones == 2:\n suffix = 'nd'\n elif ones == 3:\n suffix = 'rd'\n else:\n suffix = 'th'\n return str(c) + suffix", "SUFFIX_ONE = 'st'\nSUFFIX_TWO = 'nd'\nSUFFIX_THREE = 'rd'\nSUFFIX_OTHER = 'th'\n\ndef what_century(year):\n century = 1 + (int(year) - 1) // 100\n return str(century) + ordinal_suffix(century)\n\ndef ordinal_suffix(number):\n if number // 10 == 1:\n return SUFFIX_OTHER\n elif number % 10 == 1:\n return SUFFIX_ONE\n elif number % 10 == 2:\n return SUFFIX_TWO\n elif number % 10 == 3:\n return SUFFIX_THREE\n else:\n return SUFFIX_OTHER", "def what_century(year):\n year = int(year)\n output_century = year // 100\n ordinal = ''\n if year % 100 > 0:\n output_century += 1\n if output_century > 10 and output_century < 14:\n ordinal = 'th'\n elif output_century % 10 == 1:\n ordinal = 'st'\n elif output_century % 10 == 2:\n ordinal = 'nd'\n elif output_century % 10 == 3:\n ordinal = 'rd'\n else:\n ordinal = 'th'\n return str(output_century) + ordinal"], "starter_code": "def what_century(year):\n", "input_output": {"fn_name": "what_century", "inputs": [["1999"]], "outputs": [["20th"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms", "Date Time"], "name": null, "source": "codewars", "tags": ["String algorithms"], "skill_types": [], "url": "https://www.codewars.com/kata/52fb87703c1351ebd200081f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "what_century", "task_id": "TACO_lite/417", "example": [[["1999"], ["2011"], ["2154"], ["2259"], ["1124"], ["2000"]], ["20th", "21st", "22nd", "23rd", "12th", "20th"]]} +{"requirement": "Write\n\n```python\nfunction combine()\n```\n\nthat combines arrays by alternatingly taking elements passed to it.\n\nE.g\n\n```python\ncombine(['a', 'b', 'c'], [1, 2, 3]) == ['a', 1, 'b', 2, 'c', 3]\ncombine(['a', 'b', 'c'], [1, 2, 3, 4, 5]) == ['a', 1, 'b', 2, 'c', 3, 4, 5]\ncombine(['a', 'b', 'c'], [1, 2, 3, 4, 5], [6, 7], [8]) == ['a', 1, 6, 8, 'b', 2, 7, 'c', 3, 4, 5]\n```\n\nArrays can have different lengths.", "solutions": ["def combine(*args):\n out = list()\n for i in range(len(max(args, key=len))):\n for arr in args:\n if i < len(arr):\n out.append(arr[i])\n return out", "from itertools import chain, zip_longest\n\ndef combine(*args):\n return [x for x in chain.from_iterable(zip_longest(*args)) if x is not None]", "def combine(*args):\n res = []\n num_of_args = len(args)\n len_of_longest_list = max([len(l) for l in args])\n for i in range(len_of_longest_list):\n for j in range(num_of_args):\n if len(args[j]) > i:\n res.append(args[j][i])\n return res", "combine = lambda *args: [el[0] for el in args] + combine(*[el[1:] for el in args if len(el) > 1]) if args else []", "from copy import deepcopy\n\ndef combine(*args):\n if not args:\n return []\n args_list = list(deepcopy(args))\n first = args_list.pop(0)\n head = first.pop(0)\n if first:\n args_list.append(first)\n return [head] + combine(*tuple(args_list))", "from itertools import zip_longest\n\ndef combine(*args):\n return [y for x in zip_longest(*args) for y in list(x) if y is not None]", "def combine(*args):\n result = []\n l = len(max(args, key=len))\n for loop in range(l):\n result.extend((array[loop] for array in args if len(array) > loop))\n return result", "def combine(*args):\n L = max((len(i) for i in args))\n t = []\n j = 0\n while j < L:\n for i in args:\n try:\n t.append(i[j])\n except:\n pass\n j += 1\n return t", "def combine(*args):\n result = []\n args_length = len(args)\n max_len_list = max([len(l) for l in args])\n for i in range(max_len_list):\n for j in range(args_length):\n if len(args[j]) > i:\n result.append(args[j][i])\n return result"], "starter_code": "def combine(*args):\n", "input_output": {"fn_name": "combine", "inputs": [[["a", "b", "c"], [1, 2, 3]], [["a", "b", "c"], [1, 2, 3, 4, 5]], [["a", "b", "c"], [1, 2, 3, 4, 5], [6, 7], [8]], [[{"a": 1}, {"b": 2}], [1, 2]], [[{"a": 2, "b": 1}, {"a": 1, "b": 2}], [1, 2, 3, 4], [5, 6], [7]]], "outputs": [[["a", 1, "b", 2, "c", 3]], [["a", 1, "b", 2, "c", 3, 4, 5]], [["a", 1, 6, 8, "b", 2, 7, "c", 3, 4, 5]], [[{"a": 1}, 1, {"b": 2}, 2]], [[{"a": 2, "b": 1}, 1, 5, 7, {"a": 1, "b": 2}, 2, 6, 3, 4]]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/55e529bf6c6497394a0000b5", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "combine", "task_id": "TACO_lite/200", "example": [[[["a", "b", "c"], [1, 2, 3]], [["a", "b", "c"], [1, 2, 3, 4, 5]], [["a", "b", "c"], [1, 2, 3, 4, 5], [6, 7], [8]]], ["['a', 1, 'b', 2, 'c', 3]", "['a', 1, 'b', 2, 'c', 3, 4, 5]", "['a', 1, 6, 8, 'b', 2, 7, 'c', 3, 4, 5]"]]} +{"requirement": "For building the encrypted string:Take every 2nd char from the string, then the other chars, that are not every 2nd char, and concat them as new String.\nDo this n times!\n\nExamples:\n```\n\"This is a test!\", 1 -> \"hsi etTi sats!\"\n\"This is a test!\", 2 -> \"hsi etTi sats!\" -> \"s eT ashi tist!\"\n```\n\nWrite two methods:\n```python\ndef encrypt(text, n)\ndef decrypt(encrypted_text, n)\n```\n\n```Fsharp\nlet encrypt (str:string) (n:int) -> string\nlet decrypt (str:string) (n:int) -> string\n```\n\nFor both methods:\nIf the input-string is null or empty return exactly this value!\nIf n is <= 0 then return the input text.\n\nThis kata is part of the Simple Encryption Series:\nSimple Encryption #1 - Alternating Split\nSimple Encryption #2 - Index-Difference\nSimple Encryption #3 - Turn The Bits Around\nSimple Encryption #4 - Qwerty\n\nHave fun coding it and please don't forget to vote and rank this kata! :-)", "solutions": ["def decrypt(text, n):\n if text in ('', None):\n return text\n ndx = len(text) // 2\n for i in range(n):\n a = text[:ndx]\n b = text[ndx:]\n text = ''.join((b[i:i + 1] + a[i:i + 1] for i in range(ndx + 1)))\n return text\n\ndef encrypt(text, n):\n for i in range(n):\n text = text[1::2] + text[::2]\n return text", "def decrypt(s, n):\n if not s:\n return s\n (o, l) = (len(s) // 2, list(s))\n for _ in range(n):\n (l[1::2], l[::2]) = (l[:o], l[o:])\n return ''.join(l)\n\ndef encrypt(s, n):\n if not s:\n return s\n for _ in range(n):\n s = s[1::2] + s[::2]\n return s", "def decrypt(text, n):\n if not text:\n return text\n half = len(text) // 2\n arr = list(text)\n for _ in range(n):\n (arr[1::2], arr[::2]) = (arr[:half], arr[half:])\n return ''.join(arr)\n\ndef encrypt(text, n):\n for i in range(n):\n text = text[1::2] + text[::2]\n return text", "def encrypt_once(s):\n (h, t) = ('', '')\n for i in range(len(s)):\n if i % 2 == 0:\n h += s[i]\n else:\n t += s[i]\n return t + h\n\ndef decrypt_once(s):\n i = len(s) // 2\n j = 0\n result = ''\n for k in range(len(s)):\n if k % 2 == 0:\n result += s[i]\n i += 1\n else:\n result += s[j]\n j += 1\n return result\n\ndef decrypt(text, n):\n if not text or len(text) == 0 or n <= 0:\n return text\n for i in range(n):\n text = decrypt_once(text)\n return text\n\ndef encrypt(text, n):\n if not text or len(text) == 0 or n <= 0:\n return text\n for i in range(n):\n text = encrypt_once(text)\n return text", "def decrypt(encrypted_text, n):\n if n < 1:\n return encrypted_text\n half_len = len(encrypted_text) // 2\n (left, right) = (encrypted_text[:half_len], encrypted_text[half_len:])\n encrypted_text = [''.join(i) for i in zip(right, left)]\n if len(right) > half_len:\n encrypted_text += right[-1]\n return decrypt(''.join(encrypted_text), n - 1)\n\ndef encrypt(text, n):\n if n < 1:\n return text\n for _ in range(n):\n text = text[1::2] + text[0::2]\n return text", "def decrypt(text, n):\n if text:\n mid = len(text) // 2\n for _ in range(n):\n text = ''.join(sum(zip(text[mid:], list(text[:mid]) + ['']), ()))\n return text\n\ndef encrypt(text, n):\n if text:\n for _ in range(n):\n text = text[1::2] + text[::2]\n return text", "def decrypt(text, n):\n if text == None:\n return text\n decodeList = encrypt(list(range(len(text))), n)\n return ''.join((text[decodeList.index(i)] for i in range(len(text))))\n\ndef encrypt(text, n):\n if text == None:\n return text\n return encrypt(text[1::2] + text[0::2], n - 1) if n > 0 else text", "from itertools import zip_longest\n\ndef encrypt(text, n):\n s = text\n if s:\n for _ in range(n):\n s = s[1::2] + s[::2]\n return s\n\ndef decrypt(encrypted_text, n):\n s = encrypted_text\n if s:\n m = len(s) // 2\n for _ in range(n):\n s = ''.join((c for s in zip_longest(s[m:], s[:m], fillvalue='') for c in s))\n return s"], "starter_code": "def decrypt(text, n):\n", "input_output": {"fn_name": "decrypt", "inputs": [["This is a test!", 0], ["hsi etTi sats!", 1], ["s eT ashi tist!", 2], [" Tah itse sits!", 3], ["This is a test!", 4], ["This is a test!", -1], ["hskt svr neetn!Ti aai eyitrsig", 1], ["", 0], [null, 0]], "outputs": [["This is a test!"], ["This is a test!"], ["This is a test!"], ["This is a test!"], ["This is a test!"], ["This is a test!"], ["This kata is very interesting!"], [""], [null]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Cryptography", "Fundamentals", "Strings", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57814d79a56c88e3e0000786", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "decrypt", "task_id": "TACO_lite/372", "example": [[["This is a test!", 1], ["This is a test!", 2]], ["hsi etTi sats!", "s eT ashi tist!"]]} +{"requirement": "Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.\n\nNote that the row index starts from 0.\n\n\nIn Pascal's triangle, each number is the sum of the two numbers directly above it.\n\nExample:\n\n\nInput: 3\nOutput: [1,3,3,1]\n\n\nFollow up:\n\nCould you optimize your algorithm to use only O(k) extra space?", "solutions": ["def getrow(k):\n res = [1]\n cur = k\n for i in range(k // 2):\n res += (res[-1] * cur // (i + 1),)\n cur -= 1\n if k % 2 == 0:\n res = res + res[:-1][::-1]\n else:\n res = res + res[::-1]\n return res", "def getrow(rowIndex):\n a = [1]\n i = 0\n b = [1]\n while i < rowIndex:\n a.append(0)\n b = a[:]\n for j in range(i + 2):\n b[j] = a[j] + a[i - j + 1]\n a = b\n i += 1\n return b", "def getrow(rowIndex):\n res = [1]\n for i in range(1, rowIndex + 1):\n res += [1]\n for j in range(len(res) - 2, -1, -1):\n if j > 0:\n res[j] = res[j] + res[j - 1]\n else:\n res[j] = 1\n return res", "def getrow(rowIndex):\n out = [1]\n for i in range(1, rowIndex + 1):\n temp = []\n for j in range(0, i - 1):\n temp.append(out[j] + out[j + 1])\n out = [1] + temp + [1]\n return out", "def getrow(rowIndex):\n l = [1]\n for i in range(rowIndex):\n l = [j + k for (j, k) in zip([0] + l, l + [0])]\n return l", "def getrow(rowIndex):\n result = []\n for n in range(rowIndex + 1):\n num = 1\n for i in range(n):\n num = int(num * (rowIndex - i) / (i + 1))\n result = result + [num]\n return result", "def getrow(rowIndex):\n if rowIndex < 0:\n return list()\n if rowIndex == 0:\n return list([1])\n l = list([1])\n for i in range(1, rowIndex + 1):\n pre_value = l[0]\n for j in range(1, i):\n temp = l[j]\n l[j] = pre_value + l[j]\n pre_value = temp\n l.append(1)\n return l", "def getrow(rowIndex):\n rows = [1]\n for i in range(rowIndex):\n rows = [x + y for (x, y) in zip([0] + rows, rows + [0])]\n return rows", "def getrow(rowIndex):\n row = [1]\n for _ in range(rowIndex):\n row = [x + y for (x, y) in zip([0] + row, row + [0])]\n return row", "def getrow(rowIndex):\n if rowIndex < 0:\n return []\n result = [0 for _ in range(rowIndex + 1)]\n result[0] = 1\n for i in range(1, rowIndex + 1):\n result[i] = 1\n for j in range(i - 1, 0, -1):\n result[j] = result[j] + result[j - 1]\n return result", "def getrow(rowIndex):\n i = 1\n res = [1]\n while rowIndex >= 1:\n res.append(int(res[-1] * rowIndex / i))\n (rowIndex, i) = (rowIndex - 1, i + 1)\n return res"], "starter_code": "def getrow(rowIndex: int) -> List[int]:\n", "input_output": {"fn_name": "getRow", "inputs": [[3], [0], [1]], "outputs": [[1, 3, 3, 1], [1], [1, 1]]}, "difficulty": "EASY", "raw_tags": ["Array", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/pascals-triangle-ii/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "getrow", "task_id": "TACO_lite/451", "example": [[[3]], ["[1, 3, 3, 1]"]]} +{"requirement": "The vowel substrings in the word `codewarriors` are `o,e,a,io`. The longest of these has a length of 2. Given a lowercase string that has alphabetic characters only (both vowels and consonants) and no spaces, return the length of the longest vowel substring.\nVowels are any of `aeiou`. \n\n\n```if:csharp\nDocumentation:\nKata.Solve Method (String)\n\nReturns the length of the greatest continuous vowel substring in a string.\n\nSyntax\n\n\npublic\nstatic\nint Solve(\nstring str\n   )\n \n\n\nParameters\n\nstr\n\nType: System.String\nThe string to be processed.\n\nReturn Value\n\nType: System.Int32\n The length of the greatest continuous vowel substring in str, or 0 if str contains no vowels.\n\n\nExceptions\n\n\n\nException\nCondition\n\nArgumentNullException\nstr is null.\n\n\n\n\n```\n\n\nGood luck!\n\nIf you like substring Katas, please try:\n\n[Non-even substrings](https://www.codewars.com/kata/59da47fa27ee00a8b90000b4)\n\n[Vowel-consonant lexicon](https://www.codewars.com/kata/59cf8bed1a68b75ffb000026)", "solutions": ["def solve(s):\n return max(map(len, ''.join((c if c in 'aeiou' else ' ' for c in s)).split()))", "import re\n\ndef solve(s):\n return max((len(x.group(0)) for x in re.finditer('[aeiou]+', s)))", "from re import findall\n\ndef solve(s):\n return max(map(len, findall('[aeiou]+', s)))", "def solve(s):\n vowels = 'aeiou'\n max_len = 0\n tmp_len = 0\n prev_vowel = False\n for c in s:\n max_len = max(max_len, tmp_len)\n if not prev_vowel:\n tmp_len = 0\n if c in vowels:\n tmp_len += 1\n prev_vowel = c in vowels\n return max_len", "def solve(s):\n return max((len(w) for w in ''.join(([' ', c][c in 'aeiou'] for c in s)).split()))", "import re\n\ndef solve(s):\n return max(map(len, re.findall('[uoiae]+', s)))", "import re\n\ndef solve(s):\n return len(max(re.findall('[aeiou]+', s), key=len, default=''))", "from itertools import groupby\n\ndef solve(s):\n return max((sum((1 for _ in g)) for (k, g) in groupby(s, 'aeiou'.__contains__) if k))", "def solve(s):\n for x in s:\n if x not in 'aeiou':\n s = s.replace(x, ' ')\n s = s.split()\n a = [len(x) for x in s]\n return max(a)", "from re import compile\nr = compile('[aeiou]+')\n\ndef solve(s: str):\n return max(list(map(len, r.findall(s))))"], "starter_code": "def solve(s):\n", "input_output": {"fn_name": "solve", "inputs": [["codewarriors"], ["suoidea"], ["ultrarevolutionariees"], ["strengthlessnesses"], ["cuboideonavicuare"], ["chrononhotonthuooaos"], ["iiihoovaeaaaoougjyaw"]], "outputs": [[2], [3], [3], [1], [2], [5], [8]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/59c5f4e9d751df43cf000035", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/448", "example": [[], []]} +{"requirement": "In this Kata, you will be given an array of strings and your task is to remove all consecutive duplicate letters from each string in the array.\n\nFor example: \n\n * `dup([\"abracadabra\",\"allottee\",\"assessee\"]) = [\"abracadabra\",\"alote\",\"asese\"]`. \n \n * `dup([\"kelless\",\"keenness\"]) = [\"keles\",\"kenes\"]`.\n\nStrings will be lowercase only, no spaces. See test cases for more examples.\n\n~~~if:rust\nFor the sake of simplicity you can use the macro 'vec_of_string' to create a Vec with an array of string literals.\n~~~\n\nGood luck!\n\nIf you like this Kata, please try:\n\n[Alternate capitalization](https://www.codewars.com/kata/59cfc000aeb2844d16000075)\n\n[Vowel consonant lexicon](https://www.codewars.com/kata/59cf8bed1a68b75ffb000026)", "solutions": ["from itertools import groupby\n\ndef dup(arry):\n return [''.join((c for (c, grouper) in groupby(i))) for i in arry]", "import re\n\ndef dup(arry):\n return list(map(lambda s: re.sub('(\\\\w)\\\\1+', '\\\\1', s), arry))", "def dup(arry):\n array_new = []\n for string in arry:\n string_new = ''\n prev = None\n for char in string:\n if char != prev:\n string_new += char\n prev = char\n array_new.append(string_new)\n return array_new", "def dup(arr):\n (a, res) = (0, [x[0] for x in arr])\n for string in arr:\n for x in range(1, len(string)):\n if string[x] != string[x - 1]:\n res[a] += string[x]\n a += 1\n return res", "from itertools import groupby\n\ndef dup(strings):\n return [''.join((c for (c, _) in groupby(s))) for s in strings]", "import re\n\ndef dup(lst):\n return [re.sub('(.)\\\\1+', '\\\\1', stg) for stg in lst]", "import re\n\ndef dup(xs):\n return [re.sub('(.)\\\\1+', '\\\\1', x) for x in xs]", "def f(s):\n return ''.join((s[i] for i in range(len(s) - 1) if s[i] != s[i + 1])) + s[-1]\n\ndef dup(arry):\n return [f(s) for s in arry]", "from itertools import groupby\n\ndef dup(array):\n return list(map(remove_dup, array))\n\ndef remove_dup(string):\n return ''.join((single for (single, _) in groupby(string)))", "def dup(arry):\n stack = []\n output = []\n for item in arry:\n for i in item:\n if len(stack) == 0 or (len(stack) >= 1 and i != stack[-1]):\n stack.append(i)\n else:\n continue\n output.append(''.join(stack))\n stack = []\n return output"], "starter_code": "def dup(arry):\n", "input_output": {"fn_name": "dup", "inputs": [[["ccooddddddewwwaaaaarrrrsssss", "piccaninny", "hubbubbubboo"]], [["abracadabra", "allottee", "assessee"]], [["kelless", "keenness"]], [["Woolloomooloo", "flooddoorroommoonlighters", "chuchchi"]], [["adanac", "soonness", "toolless", "ppellee"]], [["callalloo", "feelless", "heelless"]], [["putteellinen", "keenness"]], [["kelless", "voorraaddoosspullen", "achcha"]]], "outputs": [[["codewars", "picaniny", "hubububo"]], [["abracadabra", "alote", "asese"]], [["keles", "kenes"]], [["Wolomolo", "flodoromonlighters", "chuchchi"]], [["adanac", "sones", "toles", "pele"]], [["calalo", "feles", "heles"]], [["putelinen", "kenes"]], [["keles", "voradospulen", "achcha"]]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/59f08f89a5e129c543000069", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "dup", "task_id": "TACO_lite/360", "example": [[[["abracadabra", "allottee", "assessee"]], [["kelless", "keenness"]]], ["['abracadabra', 'alote', 'asese']", "['keles', 'kenes']"]]} +{"requirement": "Write a function that reverses the bits in an integer.\n\nFor example, the number `417` is `110100001` in binary. Reversing the binary is `100001011` which is `267`.\n\nYou can assume that the number is not negative.", "solutions": ["def reverse_bits(n):\n return int(bin(n)[:1:-1], 2)", "def reverse_bits(n):\n return int(f'{n:b}'[::-1], 2)", "def reverse_bits(n):\n listbin = [bin(n)]\n listbin.sort(reverse=True)\n pleasework = list(''.join(listbin))\n comeonguy = ''.join(pleasework)\n almostanswer = comeonguy[:1:-1]\n answer = int(almostanswer, 2)\n return answer\n pass", "def reverse_bits(n):\n return int(format(n, 'b')[::-1], 2)", "def reverse_bits(n):\n return int(''.join(reversed(bin(n)[2:])), 2)", "reverse_bits = lambda n: int(bin(n)[:1:-1], 2)", "def reverse_bits(n):\n a = '{0:08b}'.format(n)\n b = list(a)\n b.reverse()\n c = ''\n for i in b:\n c += i\n return int(c, 2)"], "starter_code": "def reverse_bits(n):\n", "input_output": {"fn_name": "reverse_bits", "inputs": [[417], [267], [0], [2017], [1023], [1024]], "outputs": [[267], [417], [0], [1087], [1023], [1]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Bits"], "name": null, "source": "codewars", "tags": ["Bit manipulation", "Fundamentals"], "skill_types": ["Bit manipulation"], "url": "https://www.codewars.com/kata/5959ec605595565f5c00002b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "reverse_bits", "task_id": "TACO_lite/461", "example": [[[417]], ["267"]]} +{"requirement": "Given a String S, Find all possible Palindromic partitions of the given String.\n \nExample 1:\nInput:\nS = \"geeks\"\nOutput:\ng e e k s\ng ee k s\nExplanation:\nAll possible palindromic partitions\nare printed.\nExample 2:\nInput:\nS = \"madam\"\nOutput:\nm a d a m\nm ada m\nmadam\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function allPalindromicPerms() which takes a String S as input parameter and returns a list of lists denoting all the possible palindromic partitions in the order of their appearance in the original string.\n \nExpected Time Complexity: O(N*2^{N})\nExpected Auxiliary Space: O(N^{2}), where N is the length of the String\n \nConstraints:\n1 <= |S| <= 20", "solutions": ["def allpalindromicperms(S):\n\n def func(index, s, path, res):\n if index == len(s):\n res.append([ele for ele in path])\n return\n for i in range(index, len(s)):\n if isPalindrome(s, index, i):\n path.append(s[index:i + 1])\n func(i + 1, s, path, res)\n path.pop()\n\n def isPalindrome(s, start, end):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n res = []\n path = []\n func(0, S, path, res)\n return res", "def allpalindromicperms(S):\n ans = []\n temp = []\n\n def palli(S, start, end):\n sub = S[start:end]\n return sub == sub[::-1]\n\n def func(i, S, temp, ans):\n if i == len(S):\n ans.append(temp[:])\n for j in range(i, len(S)):\n if palli(S, i, j + 1):\n temp.append(S[i:j + 1])\n func(j + 1, S, temp, ans)\n temp.pop()\n func(0, S, temp, ans)\n return ans", "def ispalindrome(s, ind, i):\n x = ind\n y = i\n while x < y:\n if s[x] != s[y]:\n return False\n x += 1\n y -= 1\n return True\n\ndef palinpart(s, ind, n, ans, subs):\n if ind == n:\n ans.append(subs[:])\n return\n temp = ''\n for i in range(ind, n):\n temp += s[i]\n if ispalindrome(s, ind, i):\n subs.append(temp)\n palinpart(s, i + 1, n, ans, subs)\n subs.pop()\n\ndef allpalindromicperms(s):\n ans = []\n subs = []\n n = len(s)\n i = 0\n palinpart(s, i, n, ans, subs)\n return ans", "def allpalindromicperms(S):\n n = len(S)\n ans = []\n res = []\n\n def isPali(s):\n n = len(s)\n for i in range(n // 2):\n if s[i] != s[n - i - 1]:\n return False\n return True\n\n def bts(i):\n if i == n:\n res.append(ans[:])\n return\n for index in range(i, n):\n if isPali(S[i:index + 1]):\n ans.append(S[i:index + 1])\n bts(index + 1)\n ans.pop()\n bts(0)\n return res", "def allpalindromicperms(S):\n\n def helper(index, s, temp, ans):\n if index == len(s):\n ans.append([ele for ele in temp])\n return\n for i in range(index, len(s)):\n if isPalindrome(s, index, i):\n temp.append(s[index:i + 1])\n helper(i + 1, s, temp, ans)\n temp.pop()\n\n def isPalindrome(s, start, end):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n ans = []\n temp = []\n helper(0, S, temp, ans)\n return ans", "def is_palindrome(data):\n (i, j) = (0, len(data) - 1)\n while i < j:\n if data[i] != data[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef solve(start, S, palindromes, ans):\n if start >= len(S):\n ans.append(palindromes[:])\n return\n for i in range(start, len(S)):\n if self.is_palindrome(S[start:i + 1]):\n palindromes.append(S[start:i + 1])\n self.solve(i + 1, S, palindromes, ans)\n palindromes.pop()\n\ndef allpalindromicperms(S):\n ans = []\n palindromes = []\n self.solve(0, S, palindromes, ans)\n return ans", "def allpalindromicperms(S):\n n = len(S)\n r = []\n\n def subs(st, out):\n if st == n:\n r.append(out)\n return\n for i in range(st, n):\n if S[st:i + 1] == S[st:i + 1][::-1]:\n subs(i + 1, out + [S[st:i + 1]])\n subs(0, [])\n return r", "def allpalindromicperms(S):\n a = list(S)\n ans = set()\n\n def solve(a):\n ans.add(tuple(a))\n if len(a) <= 1:\n return\n for i in range(1, len(a)):\n if a[i - 1] == a[i]:\n b = a[:i - 1] + [a[i - 1] + a[i]] + a[i + 1:]\n solve(b)\n if i + 1 < len(a) and a[i - 1] == a[i + 1]:\n c = a[:i - 1] + [a[i - 1] + a[i] + a[i + 1]] + a[i + 2:]\n solve(c)\n solve(a)\n return sorted(list(ans))", "def allpalindromicperms(S):\n l = []\n\n def back(start, c):\n if start == len(S):\n l.append(c)\n for i in range(start, len(S)):\n if S[start:i + 1] == S[start:i + 1][::-1]:\n back(i + 1, c + [S[start:i + 1]])\n back(0, [])\n return l", "def allpalindromicperms(S):\n self.res = set()\n self.solve(list(S))\n return sorted(list(self.res))\n\ndef solve(arr):\n self.res.add(tuple(arr))\n if len(arr) <= 1:\n return\n for i in range(1, len(arr)):\n if arr[i - 1] == arr[i][::-1]:\n brr = arr[:i - 1] + [arr[i - 1] + arr[i]] + arr[i + 1:]\n self.solve(brr)\n if i + 1 < len(arr) and arr[i - 1] == arr[i + 1][::-1]:\n brr = arr[:i - 1] + [arr[i - 1] + arr[i] + arr[i + 1]] + arr[i + 2:]\n self.solve(brr)", "def allpalindromicperms(S):\n l = []\n\n def bac(start, curl):\n if start == len(S):\n l.append(curl)\n for i in range(start, len(S)):\n if S[start:i + 1] == S[start:i + 1][::-1]:\n bac(i + 1, curl + [S[start:i + 1]])\n bac(0, [])\n return l", "def palindromic_partition_helper(input_string: str, output_string: str, result_arr: []):\n if len(input_string) == 0:\n result_arr.append(output_string)\n return\n n = len(input_string)\n for i in range(0, n):\n word = input_string[0:i + 1]\n ros = input_string[i + 1:]\n if is_palindrome(word):\n output_string = output_string + word + '-'\n palindromic_partition_helper(ros, output_string, result_arr)\n output_string = output_string[:-(len(word) + 1)]\n\ndef is_palindrome(word):\n start = 0\n end = len(word) - 1\n while start < end:\n if word[start] != word[end]:\n return False\n start = start + 1\n end = end - 1\n return True\n\ndef print_partition(input_word):\n result_arr = []\n input_dict = {}\n palindromic_partition_helper(input_word, '', result_arr)\n final_arr = []\n for data in result_arr:\n sub_string = data.split('-')[:-1]\n final_arr.append(sub_string)\n return final_arr\n\ndef allpalindromicperms(S):\n return print_partition(S)", "def allpalindromicperms(s):\n res = []\n part = []\n\n def ispalin(i, j):\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n\n def dfs(i):\n if i == len(s):\n res.append(part.copy())\n for j in range(i, len(s)):\n if ispalin(i, j):\n part.append(s[i:j + 1])\n dfs(j + 1)\n part.pop()\n dfs(0)\n return res", "def allpalindromicperms(S):\n s = S\n n = len(s)\n (ds, ans) = ([], [])\n\n def ispalindrome(start, end, s):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n\n def rec(idx, s):\n if idx == n:\n ans.append(list(ds))\n return ans\n for i in range(idx, n):\n if ispalindrome(idx, i, s):\n ds.append(s[idx:i + 1])\n rec(i + 1, s)\n ds.pop()\n return ans\n return rec(0, s)", "def allpalindromicperms(S):\n result = []\n temp = []\n n = len(S)\n self.Util(0, S, temp, result, n)\n return result\n\ndef Util(index, S, temp, result, n):\n if index == n:\n result.append(temp[:])\n return\n for i in range(index, n):\n if self.isPalin(index, i, S):\n temp.append(S[index:i + 1])\n self.Util(i + 1, S, temp, result, n)\n temp.pop()\n\ndef isPalin(s, e, S):\n while s <= e:\n if S[s] != S[e]:\n return False\n s += 1\n e -= 1\n return True", "def allpalindromicperms(S):\n n = len(S)\n res = []\n\n def subs(start, out):\n if start == n:\n res.append(out)\n return\n for i in range(start, n):\n if S[start:i + 1] == S[start:i + 1][::-1]:\n subs(i + 1, out + [S[start:i + 1]])\n subs(0, [])\n return res", "def allpalindromicperms(S):\n\n def palind(f):\n l = len(f)\n for i in range(l // 2):\n if f[i] != f[l - i - 1]:\n return 0\n return 1\n\n def manu(i, n, f, s):\n if i == n:\n x = []\n for i in range(len(f)):\n x.append(f[i])\n a.append(x)\n return 0\n x = ''\n for j in range(i, n):\n x += s[j]\n if palind(x):\n f.append(x)\n manu(j + 1, n, f, s)\n f.pop()\n return\n a = []\n manu(0, len(S), [], S)\n return a", "def isPalindrome(string: str, low: int, high: int):\n while low < high:\n if string[low] != string[high]:\n return False\n low += 1\n high -= 1\n return True\n\ndef allPalPartUtil(allPart: list, currPart: list, start: int, n: int, string: str):\n if start >= n:\n x = currPart.copy()\n allPart.append(x)\n return\n for i in range(start, n):\n if isPalindrome(string, start, i):\n currPart.append(string[start:i + 1])\n allPalPartUtil(allPart, currPart, i + 1, n, string)\n currPart.pop()\n\ndef allpalindromicperms(S):\n n = len(S)\n allPart = []\n currPart = []\n allPalPartUtil(allPart, currPart, 0, n, S)\n return allPart", "def allpalindromicperms(S):\n\n def backtrack(start, currl):\n if start == len(S):\n res.append(currl)\n for i in range(start, len(S)):\n if S[start:i + 1] == S[start:i + 1][::-1]:\n backtrack(i + 1, currl + [S[start:i + 1]])\n res = []\n backtrack(0, [])\n return res", "def rec(S, ind, res, string):\n if ind == len(S):\n res.append(list(string.split()))\n ans = 0\n for i in range(ind + 1, len(S) + 1):\n temp = S[ind:i]\n if temp == temp[::-1]:\n rec(S, i, res, string + ' ' + temp)\n\ndef allpalindromicperms(S):\n res = []\n rec(S, 0, res, '')\n return res", "def allpalindromicperms(S):\n res = []\n perm = []\n\n def dfs(i):\n if i >= len(S):\n res.append(perm.copy())\n return\n for j in range(i, len(S)):\n if self.isPali(S, i, j):\n perm.append(S[i:j + 1])\n dfs(j + 1)\n perm.pop()\n dfs(0)\n return res\n\ndef isPali(s, l, r):\n while l < r:\n if s[l] != s[r]:\n return False\n l = l + 1\n r = r - 1\n return True", "def allpalindromicperms(S):\n s = S\n res = []\n\n def check(s, start, end):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n\n def f(s, ind, ds, res):\n if ind == len(s):\n res.append(ds.copy())\n return\n for i in range(ind, len(s)):\n if check(s, ind, i):\n ds.append(s[ind:i + 1])\n f(s, i + 1, ds, res)\n ds.pop()\n return res\n return f(s, 0, [], res)", "from collections import defaultdict as dd\n\ndef allpalindromicperms(S):\n n = len(S)\n palindromes = dd(lambda : [])\n for i in range(n):\n j = 0\n while i - j >= 0 and i + 2 + j <= n:\n s = S[i - j:i + 2 + j]\n if s == s[::-1]:\n palindromes[i - j].append(s)\n else:\n break\n j += 1\n for i in range(n):\n j = 0\n while i - j >= 0 and i + 1 + j <= n:\n s = S[i - j:i + 1 + j]\n if s == s[::-1]:\n palindromes[i - j].append(s)\n else:\n break\n j += 1\n output = []\n stack = []\n for item in palindromes[0]:\n stack.append((item, 0))\n while stack:\n (item, i) = stack.pop()\n if len(item) - i == n:\n output.append([item])\n continue\n for pali in palindromes[len(item) - i]:\n stack.append((item + ' ' + pali, i + 1))\n return sorted(output)", "def allpalindromicperms(S):\n n = len(S)\n res = []\n curr = []\n self.allpartitions(S, res, curr, 0)\n return res\n\ndef allpartitions(s, res, curr, start):\n n = len(s)\n if start >= n:\n x = curr.copy()\n res.append(x)\n return\n for i in range(start, n):\n if self.ispalindrome(s, start, i):\n curr.append(s[start:i + 1])\n self.allpartitions(s, res, curr, i + 1)\n curr.pop()\n\ndef ispalindrome(string, low, high):\n while low < high:\n if string[low] != string[high]:\n return False\n low += 1\n high -= 1\n return True", "def allpalindromicperms(S):\n result = []\n temp = []\n index = 0\n self.solve(index, S, temp, result)\n return result\n\ndef solve(index, s, temp, result):\n if index == len(s):\n result.append(temp[:])\n return\n for i in range(index, len(s)):\n if self.checkPal(index, i, s):\n temp.append(s[index:i + 1])\n self.solve(i + 1, s, temp, result)\n temp.pop()\n\ndef checkPal(s, e, S):\n while s <= e:\n if S[s] != S[e]:\n return False\n s += 1\n e -= 1\n return True", "def ispalindrome(s, start, end):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n\ndef solve(idx, s, ans, path):\n if idx == len(s):\n ans.append(path.copy())\n return\n for i in range(idx, len(s)):\n if self.ispalindrome(s, idx, i):\n path.append(s[idx:i + 1])\n self.solve(i + 1, s, ans, path)\n path.pop()\n\ndef allpalindromicperms(s):\n ans = []\n path = []\n self.solve(0, s, ans, path)\n return ans", "def func(s, temp, ans):\n if not s:\n ans.append(temp[:])\n return\n for i in range(1, len(s) + 1):\n t = s[:i]\n if t == t[::-1]:\n func(s[i:], temp + [t], ans)\n\ndef allpalindromicperms(s):\n ans = []\n func(s, [], ans)\n return ans", "def allpalindromicperms(S):\n self.res = []\n self.n = len(S)\n self.pals = self.palindrome(S)\n curr = []\n self.palsTmp(curr, 0, S)\n return self.res\n\ndef palsTmp(curr, i, S):\n if i >= self.n:\n self.res.append(list(curr))\n else:\n for j in range(i, self.n):\n if self.pals[i][j]:\n curr.append(S[i:j + 1])\n self.palsTmp(curr, j + 1, S)\n curr.pop()\n\ndef palindrome(s):\n n = len(s)\n tb = [[False for j in range(n)] for i in range(n)]\n for i in range(n):\n tb[i][i] = True\n for i in range(n - 1):\n if s[i] == s[i + 1]:\n tb[i][i + 1] = True\n for gap in range(2, n):\n for i in range(n - gap):\n j = i + gap\n if s[i] == s[j] and tb[i + 1][j - 1]:\n tb[i][j] = True\n return tb", "def allpalindromicperms(S):\n res = []\n part = []\n n = len(S)\n\n def dfs(i):\n if i >= n:\n res.append(part[:])\n return\n for j in range(i, n):\n if self.isPalindrome(S, i, j):\n part.append(S[i:j + 1])\n dfs(j + 1)\n part.pop()\n return res\n return dfs(0)\n\ndef isPalindrome(S, i, j):\n if S[i:j + 1] == S[i:j + 1][::-1]:\n return True\n else:\n return False", "def allpalindromicperms(S):\n\n def isPalindrome(i, j, S):\n while i <= j:\n if S[i] != S[j]:\n return False\n i += 1\n j -= 1\n return True\n\n def helper(i, arr, ans):\n if i == len(S):\n ans.append(arr[:])\n return\n for j in range(i, len(S)):\n if isPalindrome(i, j, S):\n arr.append(S[i:j + 1])\n helper(j + 1, arr, ans)\n arr.pop()\n (arr, ans) = ([], [])\n helper(0, arr, ans)\n return ans", "def expandByCenter(S, n, c1, c2, graph):\n while c1 >= 0 and c2 < n and (S[c1] == S[c2]):\n graph[c1].add(c2)\n c1 -= 1\n c2 += 1\n\ndef util(graph, S, n, u, ans, path):\n if u == n:\n path.append(n)\n li = []\n for i in range(len(path) - 1):\n li.append(S[path[i]:path[i + 1]])\n ans.append(li)\n path.pop()\n return\n path.append(u)\n for v in sorted(graph[u]):\n util(graph, S, n, v + 1, ans, path)\n path.pop()\n\ndef allpalindromicperms(S):\n n = len(S)\n graph = {u: set() for u in range(n)}\n for c1 in range(n):\n expandByCenter(S, n, c1, c1, graph)\n expandByCenter(S, n, c1, c1 + 1, graph)\n ans = []\n util(graph, S, n, 0, ans, [])\n return ans", "def isPalin(s):\n n = len(s)\n i = 0\n j = n - 1\n while i <= j:\n if s[i] != s[j]:\n return 0\n i += 1\n j -= 1\n return 1\n\ndef solve(inp, out, ans):\n if len(inp) == 0:\n ans.append(out.copy())\n return\n n = len(inp)\n for i in range(n):\n if self.isPalin(inp[:i + 1]):\n out.append(inp[:i + 1])\n self.solve(inp[i + 1:], out, ans)\n out.pop()\n\ndef allpalindromicperms(S):\n n = len(S)\n ans = []\n inp = S\n out = []\n self.solve(inp, out, ans)\n return ans", "def allpalindromicperms(S):\n res = []\n n = len(S)\n\n def dfs(index, l):\n if index == n:\n res.append(l.copy())\n return\n for i in range(index, n):\n s1 = S[index:i + 1]\n if s1 == s1[::-1]:\n l.append(s1)\n dfs(i + 1, l)\n l.pop()\n return res\n res = dfs(0, [])\n return res", "def allpalindromicperms(S):\n\n def isPalindrom(si, ei):\n nonlocal S\n for i in range((ei - si + 1) // 2):\n if S[si + i] != S[ei - i]:\n return False\n return True\n ans = []\n n = len(S)\n\n def backtrack(starti, arr):\n nonlocal S, ans, n\n if starti == n:\n ans.append(arr.copy())\n else:\n for endi in range(starti, n):\n if isPalindrom(starti, endi):\n arr.append(S[starti:endi + 1])\n backtrack(endi + 1, arr)\n arr.pop()\n backtrack(0, [])\n return ans", "def __init__():\n self.dp = dict()\n\ndef isPalin(s):\n return s == s[::-1]\n\ndef allpalindromicperms(s, i=0):\n if len(s) == 1:\n return [s]\n if self.dp.get(s) != None:\n return self.dp[s]\n till = ''\n way = []\n if self.isPalin(s):\n way.append([s])\n for x in range(1, len(s)):\n rem = s[:x]\n if not self.isPalin(rem):\n continue\n for _ in self.allpalindromicperms(s[x:], i + 1):\n way.append([rem, *_])\n self.dp[s] = way\n if i == 0:\n return sorted(way)\n return way", "def allpalindromicperms(S):\n (res, curr, i, n) = ([], [], 0, len(S))\n pals = self.isPal(S)\n self.palPermsTmp(curr, i, res, n, S, pals)\n return res\n\ndef palPermsTmp(curr, i, res, n, s, pals):\n if i >= n:\n res.append(list(curr))\n else:\n for j in range(i, n):\n if pals[i][j]:\n curr.append(s[i:j + 1])\n self.palPermsTmp(curr, j + 1, res, n, s, pals)\n curr.pop()\n\ndef isPal(s):\n n = len(s)\n pals = [[False for i in range(n)] for j in range(n)]\n for j in range(n):\n pals[j][j] = True\n for j in range(n - 1):\n pals[j][j + 1] = s[j] == s[j + 1]\n for gap in range(2, n):\n for j in range(n - gap):\n i = j + gap\n pals[j][i] = (s[j] == s[i]) & pals[j + 1][i - 1]\n return pals", "def allpalindromicperms(S):\n\n def helper(s, v):\n if s == n:\n ans.append(v)\n return\n for i in range(s, n):\n if S[s:i + 1] == S[s:i + 1][::-1]:\n helper(i + 1, v + [S[s:i + 1]])\n ans = []\n n = len(S)\n helper(0, [])\n return ans", "def allpalindromicperms(S):\n self.s = S\n self.n = len(S)\n self.palindromes = []\n self.findPalindromes(0, '', [])\n return self.palindromes\n\ndef findPalindromes(index, word, palindrome):\n if index >= self.n:\n if word == '':\n self.palindromes.append(palindrome.copy())\n return\n word += self.s[index]\n if word == word[::-1]:\n self.findPalindromes(index + 1, '', palindrome + [word])\n self.findPalindromes(index + 1, word, palindrome)", "def allpalindromicperms(s):\n\n def check(strs):\n return strs == strs[::-1]\n ans = []\n\n def fun(temp, t):\n nonlocal ans\n if len(t) == 0:\n ans.append(temp)\n return\n for gap in range(1, len(t) + 1):\n sub_t = t[:gap]\n if check(sub_t):\n fun(temp + [sub_t], t[gap:])\n else:\n continue\n fun([], s)\n return ans", "def allpalindromicperms(S):\n\n def helper(ind, s, sub, res):\n if ind == len(s):\n res.append([i for i in sub])\n return\n for i in range(ind, len(s)):\n if ispal(s, ind, i):\n sub.append(s[ind:i + 1])\n helper(i + 1, s, sub, res)\n sub.pop()\n\n def ispal(s, start, end):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n res = []\n sub = []\n helper(0, S, sub, res)\n return res", "def allpalindromicperms(S):\n s = S\n\n def palindrome(sub):\n lt = 0\n rt = len(sub) - 1\n while lt < rt:\n if sub[lt] != sub[rt]:\n return False\n lt += 1\n rt -= 1\n return True\n\n def part(index, s, temp, ans):\n if index == len(s):\n ans.append(temp.copy())\n return\n else:\n for i in range(index, len(s)):\n sub = s[index:i + 1]\n if palindrome(sub):\n temp.append(sub)\n part(i + 1, s, temp, ans)\n temp.pop()\n ans = []\n part(0, s, [], ans)\n return ans", "def allpalindromicperms(s):\n\n def func(ind, n, res, ans, s):\n if ind == n:\n res.append(ans.copy())\n return\n for i in range(ind, n):\n kk = s[ind:i + 1]\n if kk == kk[::-1]:\n ans.append(kk)\n func(i + 1, n, res, ans, s)\n ans.pop()\n ans = []\n res = []\n n = len(s)\n func(0, n, res, ans, s)\n return res", "import collections\n\ndef allpalindromicperms(S):\n s = S\n dp = collections.defaultdict(str)\n ans = []\n for i in range(len(s)):\n dp[i, i] = s[i]\n for i in range(len(s) - 1, -1, -1):\n for j in range(i + 1, len(s)):\n if j - i == 1 and s[i] == s[j]:\n dp[i, j] = s[i] + s[j]\n elif (i + 1, j - 1) in dp and s[i] == s[j]:\n dp[i, j] = s[i] + dp[i + 1, j - 1] + s[j]\n\n def iterate(i, st):\n if i == len(s):\n ans.append(st)\n for j in range(i, len(s)):\n if (i, j) in dp:\n sx = st[:]\n sx.append(dp[i, j])\n iterate(j + 1, sx)\n iterate(0, [])\n return ans", "def allpalindromicperms(s):\n res = []\n part = []\n\n def dfs(i):\n if i >= len(s):\n res.append(part[:])\n return\n for j in range(i, len(s)):\n if self.isPalin(s, i, j):\n part.append(s[i:j + 1])\n dfs(j + 1)\n part.pop()\n return res\n return dfs(0)\n\ndef isPalin(s, i, j):\n if s[i:j + 1] == s[i:j + 1][::-1]:\n return True", "def allpalindromicperms(S):\n n = len(S)\n op = []\n\n def finding(start, end):\n if start == n:\n op.append(end)\n return\n for i in range(start, n):\n if S[start:i + 1] == S[start:i + 1][::-1]:\n finding(i + 1, end + [S[start:i + 1]])\n finding(0, [])\n return op", "def IsPalindrome(start, end, s):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n\ndef helper(ind, n, s, ans, temp):\n if ind == n:\n ans.append(temp[:])\n return\n for i in range(ind, n):\n if self.IsPalindrome(ind, i, s):\n temp.append(s[ind:i + 1])\n self.helper(i + 1, n, s, ans, temp)\n temp.pop()\n\ndef allpalindromicperms(S):\n ans = []\n temp = []\n self.helper(0, len(S), S, ans, temp)\n return ans", "def allpalindromicperms(S):\n\n def dfs(i, l):\n if i == len(S):\n ans.append(l[:])\n return\n for ind in range(i, len(S)):\n if S[i:ind + 1] == S[i:ind + 1][::-1]:\n l.append(S[i:ind + 1])\n dfs(ind + 1, l)\n l.pop()\n ans = []\n dfs(0, [])\n return ans", "def allpalindromicperms(S):\n import copy\n ans = []\n\n def f(index, p):\n if index == len(S):\n ans.append(copy.deepcopy(p))\n return\n for i in range(index, len(S)):\n t = S[index:i + 1]\n if t == t[::-1]:\n p.append(t)\n f(i + 1, p)\n p.pop()\n f(0, [])\n return ans", "from copy import copy\n\ndef allpalindromicperms(S):\n lst = []\n res = []\n self.helper(0, S, lst, res)\n return res\n\ndef checkpalindrome(a, b, s):\n while a <= b:\n if s[a] != s[b]:\n return False\n a += 1\n b -= 1\n return True\n\ndef helper(idx, s, lst, res):\n if idx == len(s):\n res.append(copy(lst))\n return\n for i in range(idx, len(s)):\n if self.checkpalindrome(idx, i, s) == True:\n lst.append(s[idx:i + 1])\n self.helper(i + 1, s, lst, res)\n lst.pop()", "def allpalindromicperms(s):\n l = []\n\n def dfs(x, n, a):\n if x is '':\n l.append(a[:])\n return\n y = ''\n for i in range(n):\n y += x[i]\n if y != y[::-1]:\n continue\n a.append(y)\n dfs(x[i + 1:], n - i - 1, a)\n a.pop(-1)\n dfs(s, len(s), [])\n return l", "def allpalindromicperms(s):\n m = len(s)\n r = []\n a = []\n\n def check(string, i, j):\n x = j\n for y in range(i, x):\n if string[y] != string[x]:\n return False\n x -= 1\n return True\n\n def allPalPartUtil(allPart: list, currPart: list, start: int, n: int, string: str):\n if start >= n:\n x = currPart.copy()\n allPart.append(x)\n return\n for i in range(start, n):\n if check(string, start, i):\n currPart.append(string[start:i + 1])\n allPalPartUtil(allPart, currPart, i + 1, n, string)\n currPart.pop()\n allPalPartUtil(r, a, 0, m, s)\n return r", "from collections import defaultdict\n\ndef allpalindromicperms(s):\n h = defaultdict(set)\n ans = []\n cans = []\n n = len(s)\n for i in range(n):\n p = q = i\n h[p].add(q)\n while p - 1 >= 0 and q + 1 < n and (s[p - 1] == s[q + 1]):\n p -= 1\n q += 1\n h[p].add(q)\n for i in range(n - 1):\n (p, q) = (i + 1, i)\n while p - 1 >= 0 and q + 1 < n and (s[p - 1] == s[q + 1]):\n p -= 1\n q += 1\n h[p].add(q)\n\n def rec(i, start):\n if i == n:\n if start == n:\n ans.append(cans[:])\n return\n if i in h[start]:\n cans.append(s[start:i + 1])\n rec(i + 1, i + 1)\n cans.pop()\n if len(h[start]) > 1:\n rec(i + 1, start)\n rec(0, 0)\n return ans", "def allpalindromicperms(S):\n res = []\n part = []\n\n def dfs(i):\n if i >= len(S):\n res.append(part.copy())\n return\n for j in range(i, len(S)):\n if self.isPalindrome(S, i, j):\n part.append(S[i:j + 1])\n dfs(j + 1)\n part.pop()\n dfs(0)\n return res\n\ndef isPalindrome(S, l, r):\n while l <= r:\n if S[l] != S[r]:\n return False\n (l, r) = (l + 1, r - 1)\n return True", "def allpalindromicperms(S):\n\n def go(ind):\n if ind == len(S):\n ans.append(p[:])\n return\n for i in range(ind, len(S)):\n if isP(S[ind:i + 1]):\n p.append(S[ind:i + 1])\n go(i + 1)\n p.pop(-1)\n\n def isP(x):\n l = 0\n r = len(x) - 1\n while l < r:\n if x[l] != x[r]:\n return False\n l += 1\n r -= 1\n return True\n p = []\n ans = []\n go(0)\n return ans", "def is_palindrome(string):\n j = len(string) - 1\n i = 0\n while i < j:\n if string[i] != string[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef partition(string, ans, res):\n if len(string) == 0:\n res.add(' '.join(ans))\n return\n for i in range(len(string)):\n if self.is_palindrome(string[:i + 1]):\n self.partition(string[i + 1:], ans + [string[:i + 1]], res)\n\ndef allpalindromicperms(S):\n res = set()\n self.partition(S, [], res)\n res = [[x] for x in res]\n res = sorted(res)\n return res", "def allpalindromicperms(S):\n n = len(S)\n result = []\n\n def sub(start, out):\n if start == n:\n result.append(out)\n return\n for i in range(start, n):\n if S[start:i + 1] == S[start:i + 1][::-1]:\n sub(i + 1, out + [S[start:i + 1]])\n sub(0, [])\n return result", "def isPalindrome(s):\n i = 0\n j = len(s) - 1\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef backtrack(i, n, temp, l, S):\n if i >= n:\n l.append(temp[:])\n p = ''\n for j in range(i, n):\n p += S[j]\n if self.isPalindrome(p):\n temp.append(p)\n self.backtrack(j + 1, n, temp, l, S)\n temp.pop()\n\ndef allpalindromicperms(S):\n l = []\n self.backtrack(0, len(S), [], l, S)\n return l", "def allpalindromicperms(S):\n ans = []\n a = []\n n = len(S)\n\n def check(s):\n return s == s[::-1]\n\n def sol(i, n):\n if i == n:\n ans.append(a.copy())\n return\n for j in range(n - i):\n if check(S[i:i + j + 1]):\n a.append(S[i:i + j + 1])\n sol(i + j + 1, n)\n a.pop()\n sol(0, n)\n return ans", "def is_palindrome(S):\n low = 0\n high = len(S) - 1\n while low < high:\n if S[low] != S[high]:\n return False\n low += 1\n high -= 1\n return True\n\ndef solve(S, part, res):\n for i in range(len(S)):\n prefix = S[:i + 1]\n if self.is_palindrome(prefix):\n rest = S[i + 1:]\n if len(rest) == 0:\n part.append(prefix)\n res.append(part[:])\n part.pop()\n return\n part.append(prefix)\n self.solve(rest, part, res)\n part.pop()\n\ndef allpalindromicperms(S):\n res = []\n self.solve(S, [], res)\n return res", "def is_palindrome(start, end, nums):\n while start <= end:\n if nums[start] != nums[end]:\n return False\n start = start + 1\n end = end - 1\n return True\n\ndef helper(ind, nums, path, ans):\n if ind == len(nums):\n ans.append(list(path))\n return\n for i in range(ind, len(nums)):\n if self.is_palindrome(ind, i, nums):\n path.append(''.join(nums[ind:i + 1]))\n self.helper(i + 1, nums, path, ans)\n path.pop()\n\ndef allpalindromicperms(S):\n ans = []\n self.helper(0, list(S), [], ans)\n return ans", "def allpalindromicperms(S):\n t = len(S)\n rest = []\n\n def subt(first, last):\n if first == t:\n rest.append(last)\n return\n for i in range(first, t):\n if S[first:i + 1] == S[first:i + 1][::-1]:\n subt(i + 1, last + [S[first:i + 1]])\n subt(0, [])\n return rest", "def allpalindromicperms(s):\n l = []\n\n def backtrack(a, s):\n if s is '':\n l.append(a[:])\n return\n n = len(s)\n x = ''\n for i in range(n):\n x += s[i]\n if x == x[::-1]:\n a.append(x)\n backtrack(a, s[i + 1:])\n a.pop(-1)\n backtrack([], s)\n return l", "def isPali(str):\n i = 0\n j = len(str) - 1\n while i < j:\n if str[i] != str[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef solve(str):\n if len(str) == 1:\n return [[str[0]]]\n curr = []\n for i in range(1, len(str)):\n if not self.isPali(str[:i]):\n continue\n prev = self.solve(str[i:])\n for p in prev:\n p.insert(0, str[:i])\n curr.append(p)\n if self.isPali(str):\n curr.append([str])\n return curr\n\ndef allpalindromicperms(str):\n return self.solve(str)", "def allpalindromicperms(S):\n ans = []\n part = []\n\n def dfs(i=0):\n if i == len(S):\n ans.append(part[:])\n return\n for j in range(i, len(S)):\n if self.checkPal(S, i, j):\n part.append(S[i:j + 1])\n dfs(j + 1)\n part.pop()\n dfs()\n return ans\n\ndef checkPal(S, i, j):\n while i < j:\n if S[i] != S[j]:\n return False\n i += 1\n j -= 1\n return True", "def allpalindromicperms(S):\n ans = []\n part = []\n\n def dfs(i=0):\n if i == len(S):\n ans.append(part[:])\n return\n for j in range(i, len(S)):\n if self.checkPal(S[i:j + 1]):\n part.append(S[i:j + 1])\n dfs(j + 1)\n part.pop()\n dfs()\n return ans\n\ndef checkPal(str):\n return str == str[::-1]", "def allpalindromicperms(s):\n res = []\n\n def rec(idx, path, res):\n if idx == len(s):\n res.append(path[:])\n return\n for i in range(idx, len(s)):\n if ispali(s, idx, i):\n path.append(s[idx:i + 1])\n rec(i + 1, path, res)\n path.pop(-1)\n\n def ispali(s, left, right):\n while left <= right:\n if s[left] != s[right]:\n return False\n left += 1\n right -= 1\n return True\n rec(0, [], res)\n return res", "def ispal(s):\n if s == s[::-1]:\n return True\n return False\n\ndef helper(allpart, curpart, start, end, s):\n if start >= end:\n x = curpart.copy()\n allpart.append(x)\n return\n for i in range(start, end):\n if self.ispal(s[start:i + 1]):\n curpart.append(s[start:i + 1])\n self.helper(allpart, curpart, i + 1, end, s)\n curpart.pop()\n return allpart\n\ndef allpalindromicperms(S):\n ans = self.helper([], [], 0, len(S), S)\n return ans"], "starter_code": "def allpalindromicperms(S):\n", "input_output": {"inputs": ["S = \"geeks\"", "S = \"madam\""], "outputs": ["g e e k s\ng ee k s", "m a d a m\nm ada m\nmadam"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Algorithms", "Recursion", "Strings", "Data Structures", "Backtracking", "Dynamic Programming", "palindrome"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Dynamic programming", "Data structures", "Complete search"], "skill_types": ["Dynamic programming", "Data structures", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/find-all-possible-palindromic-partitions-of-a-string/1", "Expected Auxiliary Space": "O(N^{2}), where N is the length of the String", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*2^{N})", "entry_point": "allpalindromicperms", "task_id": "TACO_lite/263", "example": [[["geeks"], ["madam"]], ["(['g', 'e', 'e', 'k', 's'], ['g', 'ee', 'k', 's'])", "(['m', 'a', 'd', 'a', 'm'], ['m', 'ada', 'm'], ['madam'])"]]} +{"requirement": "Jack is very fond of reading. He reads a lot many pages of books in a day. Since he is obsessed with reading, he reads K times more pages than the number of pages he read the previous day.He read 1 page on the first day. He wants to see that on any given day N, how many pages will he read.Since the answer can be very large, find the answer in modulo 10^{9}+7.\nExample 1:\nInput: N = 5, K = 2 \nOutput: 16 \nExplanation: \nOn Day 1 : 1\nOn Day 2 : 2\nOn Day 3 : 4\nOn Day 4 : 8\nOn Day 5 : 16\nSo the answer is 16. \nExample 2:\nInput: N = 2, K = 3 \nOutput: 3\nExplanation: \nOn Day 1 : 1\nOn Day 2 : 3\nSo the answer is 3. \nYour Task: \nYou dont need to read input or print anything. Complete the function nthDayPage() which takes N and K as input parameter and returns the answer.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1<= N <=10^{6}\n1<= K <=10^{3}", "solutions": ["def nthdaypage(N, K):\n N = N - 1\n x = K ** N\n x = x % 1000000007\n return x", "def nthdaypage(N, K):\n return K ** (N - 1) % (10 ** 9 + 7)", "def nthdaypage(N, K):\n l = [1]\n for i in range(N):\n l.append(l[-1] * K % (10 ** 9 + 7))\n return l[N - 1]", "import math\n\ndef nthdaypage(N, K):\n if N == 1:\n return 1\n m = int(1000000000.0) + 7\n (p, x, res) = (N - 1, K, 1)\n while p != 0:\n if p % 2 != 0:\n res = res * x\n x = x * x\n p = p >> 1\n return res % m", "def nthdaypage(N, K):\n self.s = 1\n for i in range(2, N + 1):\n self.s *= K\n return self.s % (10 ** 9 + 7)", "def nthdaypage(N: int, K: int) -> int:\n return K ** (N - 1) % 1000000007", "def nthdaypage(N, K):\n N = N - 1\n X = K ** N\n X = X % 1000000007\n return X", "def nthdaypage(N, K):\n N = N - 1\n y = K ** N\n y = y % 1000000007\n return y", "def nthdaypage(N, K):\n N = N - 1\n a = K ** N\n a = a % 1000000007\n return a", "def nthdaypage(N, K):\n N = N - 1\n s = K ** N\n s = s % 1000000007\n return s", "def nthdaypage(N, K):\n if N == 1:\n return 1\n else:\n return K ** (N - 1) % 1000000007", "def nthdaypage(N, K):\n N = N - 1\n m = K ** N\n m = m % 1000000007\n return m", "def nthdaypage(N, K):\n return pow(K, N - 1) % 1000000007", "def nthdaypage(N, K):\n N = N - 1\n z = K ** N\n z = z % 1000000007\n return z"], "starter_code": "def nthdaypage (N, K):\n", "input_output": {"inputs": ["N = 5, K = 2", "N = 2, K = 3"], "outputs": ["16", "3"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical", "series"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/dull-jack1909/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "nthdaypage", "task_id": "TACO_lite/453", "example": [[[5, 2], [2, 3]], ["16", "3"]]} +{"requirement": "John is developing a system to report fuel usage but needs help with the coding.\n\nFirst, he needs you to write a function that, given the actual consumption (in l/100 km) and remaining amount of petrol (in l), will give you how many kilometers you'll be able to drive.\n\nSecond, he needs you to write a function that, given a distance (in km), a consumption (in l/100 km), and an amount of petrol (in l), will return one of the following: If you can't make the distance without refueling, it should return the message \"You will need to refuel\". If you can make the distance, the function will check every 100 km and produce an array with [1:kilometers already driven. 2: kilometers till end. 3: remaining amount of petrol] and return all the arrays inside another array ([[after 100km], [after 200km], [after 300km]...])\n\nPLEASE NOTE: any of the values with decimals that you return should be rounded to 2 decimals.", "solutions": ["def total_kilometers(cons, petrol):\n return round(100 * petrol / cons, 2)\n\ndef check_distance(dist, cons, petrol):\n return 'You will need to refuel' if dist > total_kilometers(cons, petrol) else [[n * 100, dist - 100 * n, round(petrol - cons * n, 2)] for n in range(dist // 100 + 1)]", "def total_kilometers(cons, petrol):\n distance = round(petrol / cons * 100, 2)\n return distance\n\ndef check_distance(distance, cons, petrol):\n outp = []\n track = 0\n driven_dist = 0\n if distance > petrol / cons * 100:\n return 'You will need to refuel'\n while track <= distance:\n outp.append([driven_dist, distance - driven_dist, round(petrol, 2)])\n driven_dist += 100\n petrol -= cons\n track += 100\n return outp", "def total_kilometers(cons, petrol):\n return round(petrol * 100.0 / cons, 2)\n\ndef check_distance(distance, cons, petrol):\n if total_kilometers(cons, petrol) < distance:\n return 'You will need to refuel'\n return [[round(x, 2) for x in (i * 100, distance - i * 100, petrol - cons * i)] for i in range(int(distance / 100) + 1)]", "def total_kilometers(cons, petrol):\n return round(float(petrol) / cons * 100, 2)\n\ndef check_distance(distance, cons, petrol):\n if distance * cons > petrol * 100:\n return 'You will need to refuel'\n return [[i, distance - i, round(petrol - i * cons / 100, 2)] for i in xrange(0, distance + 1, 100)]", "def total_kilometers(cons, petrol):\n return round(petrol / float(cons) * 100, 2)\n\ndef check_distance(distance, cons, petrol):\n if total_kilometers(cons, petrol) < distance:\n return 'You will need to refuel'\n km_driven = 0\n result = []\n while distance >= 0:\n result.append([km_driven, distance, petrol])\n distance -= 100\n km_driven += 100\n petrol = round(petrol - cons, 2)\n return result", "def total_kilometers(cons, petrol):\n return round(100 * petrol / cons, 2)\n\ndef check_distance(distance, cons, petrol):\n if total_kilometers(cons, petrol) < distance:\n return 'You will need to refuel'\n r = [[0, distance, petrol]]\n x = 0\n while distance >= 100:\n petrol -= cons\n distance -= 100\n x += 100\n r.append([x, distance, round(petrol, 2)])\n return r", "def total_kilometers(cons, petrol):\n return round(petrol * 100 / cons, 2)\n\ndef check_distance(distance, cons, petrol):\n if distance > petrol * 100 / cons:\n return 'You will need to refuel'\n else:\n l = []\n length = 0\n for i in range(1 + distance // 100):\n l.append([length, distance, round(petrol, 2)])\n length += 100\n distance -= 100\n petrol -= cons\n return l"], "starter_code": "def total_kilometers(cons, petrol):\n", "input_output": {"fn_name": "total_kilometers", "inputs": [[10, 60], [8, 0], [6.4, 54], [9.3, 87.3], [11.7, 63.4]], "outputs": [[600], [0], [843.75], [938.71], [541.88]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Games", "Puzzles"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Game theory", "Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/55cb8b5ddd6a67fef7000070", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "total_kilometers", "task_id": "TACO_lite/362", "example": [[], []]} +{"requirement": "Create a function that accepts dimensions, of Rows x Columns, as parameters in order to create a multiplication table sized according to the given dimensions. **The return value of the function must be an array, and the numbers must be Fixnums, NOT strings.\n\nExample:\n\nmultiplication_table(3,3)\n\n1 2 3 \n2 4 6 \n3 6 9\n\n-->[[1,2,3],[2,4,6],[3,6,9]]\n\nEach value on the table should be equal to the value of multiplying the number in its first row times the number in its first column.", "solutions": ["def multiplication_table(row, col):\n return [[(i + 1) * (j + 1) for j in range(col)] for i in range(row)]", "def multiplication_table(row, col):\n return [[x * y for y in range(1, col + 1)] for x in range(1, row + 1)]", "def multiplication_table(row, col):\n res = []\n for i in range(1, row + 1):\n item = []\n for j in range(1, col + 1):\n item.append(i * j)\n res.append(item)\n return res", "def multiplication_table(row, col):\n return [[e * i for e in range(1, col + 1)] for i in range(1, row + 1)]", "def multiplication_table(row, col):\n l = []\n for linha in range(row):\n l.append(list(range(linha + 1, (linha + 1) * col + 1, linha + 1)))\n return l"], "starter_code": "def multiplication_table(row,col):\n", "input_output": {"fn_name": "multiplication_table", "inputs": [[2, 2], [3, 3], [3, 4], [4, 4], [2, 5]], "outputs": [[[[1, 2], [2, 4]]], [[[1, 2, 3], [2, 4, 6], [3, 6, 9]]], [[[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12]]], [[[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4, 8, 12, 16]]], [[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]]]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5432fd1c913a65b28f000342", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "multiplication_table", "task_id": "TACO_lite/381", "example": [[[3, 3]], ["[[1, 2, 3], [2, 4, 6], [3, 6, 9]]"]]} +{"requirement": "Given a string, swap the case for each of the letters.\n\ne.g. CodEwArs --> cODeWaRS\n\n### Examples\n\n```\n\"\" -> \"\"\n\"CodeWars\" -> \"cODEwARS\"\n\"abc\" -> \"ABC\"\n\"ABC\" -> \"abc\"\n\"123235\" -> \"123235\"\n```", "solutions": ["def swap(string_):\n return string_.swapcase()", "swap = str.swapcase", "swap = lambda s: ''.join([c.lower() if c.isupper() else c.upper() for c in s])", "swap = lambda s: s.swapcase()", "def swap(s):\n return s.swapcase()", "def swap(string_):\n s = ''\n for i in string_:\n if i.isupper():\n s += i.lower()\n else:\n s += i.upper()\n return s", "def swap(word):\n return ''.join((ch.upper() if ch.islower() else ch.lower() for ch in word))"], "starter_code": "def swap(string_):\n", "input_output": {"fn_name": "swap", "inputs": [["HelloWorld"], ["CodeWars"], ["ThIs iS A l0NG sENTence witH nUMbERs in IT 123 456"], [""], [" "], [" "], [" 1a1 "], ["H_E_l-l_0 WO|||Rld"], ["TeSt"], ["EeEEeeEEEeee"]], "outputs": [["hELLOwORLD"], ["cODEwARS"], ["tHiS Is a L0ng SentENCE WITh NumBerS IN it 123 456"], [""], [" "], [" "], [" 1A1 "], ["h_e_L-L_0 wo|||rLD"], ["tEsT"], ["eEeeEEeeeEEE"]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5590961e6620c0825000008f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "swap", "task_id": "TACO_lite/421", "example": [[[""], ["CodeWars"], ["abc"], ["ABC"], ["123235"]], ["", "cODEwARS", "ABC", "abc", "123235"]]} +{"requirement": "Given a number in its binary form find if the given binary number is a multiple of 3. It is recommended to finish the task using one traversal of input binary number.\nExample 1:\nInput: S = \"0011\"\nOutput: 1\nExplanation: \"0011\" is 3, which is divisible by 3.\nExample 2:\nInput: S = \"100\"\nOutput: 0\nExplanation: \"100\"'s decimal equivalent is 4, which is not divisible by 3.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function isDivisible() which takes the string s as inputs and returns 1 if the given number is divisible by 3 otherwise 0.\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ |S| ≤ 10^{5}", "solutions": ["def isdivisible(s):\n n = int(s, 2)\n if n % 3 == 0:\n return 1\n return 0", "def isdivisible(s):\n k = 0\n res = int(s, 2)\n if res % 3 == 0:\n return 1\n return 0", "def isdivisible(s):\n x = int(s, 2)\n if x % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n even = 0\n odd = 0\n for i in range(len(s)):\n if s[i] == '1':\n if i % 2 == 0:\n even += 1\n else:\n odd += 1\n if abs(odd - even) % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n res = 0\n for i in range(len(s)):\n if s[i] == '1':\n if i % 2 == 0:\n res += 1\n else:\n res += 2\n if res % 3 == 0:\n return 1\n return 0", "import math\n\ndef isdivisible(s):\n d = int(s, 2)\n if d % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n (od, ev) = (0, 0)\n for i in range(len(s)):\n if s[i] == '1':\n if i & 1:\n od += 1\n else:\n ev += 1\n ans = abs(od - ev)\n if ans % 3 == 0:\n return 1\n return 0", "def isdivisible(s):\n e = 0\n o = 0\n for i in range(len(s)):\n if i % 2 == 0:\n e += int(s[i])\n else:\n o += int(s[i])\n diff = abs(e - o)\n if diff % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n rem = 0\n for i in s:\n rem = (rem * 2 + int(i)) % 3\n if rem == 0:\n return 1\n else:\n return 0", "import math\n\ndef isdivisible(s):\n g = int(s, 2)\n h = g % 3\n if h == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n return int(int(s, 2) % 3 == 0)", "def isdivisible(s):\n c = str(int(s, 2))\n d = 0\n for i in c:\n d = d + int(i)\n if d % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n n = len(s)\n even_sum = odd_sum = 0\n for i in range(n - 1, -1, -1):\n if s[i] == '1':\n if (n - i - 1) % 2 == 0:\n even_sum += 1\n else:\n odd_sum += 1\n return (abs(even_sum - odd_sum) % 3 == 0) * 1", "def isdivisible(s):\n i = 0\n n = len(s)\n s = s[::-1]\n ans = 0\n j = 1\n num = 1\n while i < n:\n if s[i] == '1':\n ans += num\n i += 1\n if num == 1:\n num = 2\n else:\n num *= 2\n return 1 if not ans % 3 else 0", "def isdivisible(s):\n multi = 0\n for i in s:\n multi = multi * 2 + int(i)\n if multi % 3 == 0:\n return 1\n return 0", "def isdivisible(s):\n st = 0\n for i in range(len(s)):\n if st == 0:\n if s[i] == '1':\n st = 1\n elif st == 1:\n if s[i] == '1':\n st = 0\n else:\n st = 2\n elif s[i] == '0':\n st = 1\n return int(st == 0)", "def isdivisible(s):\n n = len(s)\n j = 0\n ans = 0\n for i in range(n - 1, -1, -1):\n if s[i] == '1':\n ans += 2 << j\n else:\n ans += 0\n j += 1\n if ans % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n x = len(s) - 1\n summ = 0\n j = 0\n for i in range(x, -1, -1):\n summ = summ + (1 << i) * int(s[j])\n j = j + 1\n if summ % 3 == 0:\n return 1\n return 0", "def isdivisible(s):\n a = len(s) - 1\n sum = 0\n k = 0\n for n in range(a, -1, -1):\n sum += (1 << n) * int(s[k])\n k += 1\n if sum % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n s = '0b' + s\n n = eval(s)\n if not n % 3:\n return 1\n return 0", "def isdivisible(s):\n number = 0\n k = len(s) - 1\n for i in range(len(s)):\n number = number + int(s[i]) * (1 << k)\n k = k - 1\n if number % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(S):\n (oddPosition, evenPosition) = (0, 0)\n for i in range(len(S)):\n if i % 2 and S[i] == '1':\n oddPosition += 1\n if i % 2 == 0 and S[i] == '1':\n evenPosition += 1\n return 1 if abs(oddPosition - evenPosition) % 3 == 0 else 0", "def isdivisible(s):\n ev = 0\n od = 0\n for i in range(len(s)):\n if i & 1 and s[i] == '1':\n od += 1\n elif i & 1 == 0 and s[i] == '1':\n ev += 1\n if abs(od - ev) % 3 == 0:\n return 1\n return 0", "def isdivisible(s):\n (oddsetbits, evensetbits) = (0, 0)\n n = len(s)\n for (i, c) in enumerate(s):\n if c == '1':\n if i & 1:\n oddsetbits += 1\n else:\n evensetbits += 1\n return 1 if not abs(oddsetbits - evensetbits) % 3 else 0", "def isdivisible(s):\n num = 0\n for i in s:\n num = num * 2 + int(i)\n return int(num % 3 == 0)\n\ndef isdivisible(s):\n return int(int(s, 2) % 3 == 0)\n\ndef isdivisible(s):\n (pos, even, odd) = (0, 0, 0)\n for i in s:\n if pos % 2:\n if s[pos] == '1':\n odd += 1\n elif s[pos] == '1':\n even += 1\n pos += 1\n return int((odd - even) % 3 == 0)", "def isdivisible(s):\n num = 0\n for i in s:\n num = num * 2 + int(i)\n return int(num % 3 == 0)\n\ndef isdivisible(s):\n return int(int(s, 2) % 3 == 0)", "def isdivisible(s):\n e = 0\n o = 0\n for i in range(len(s)):\n if i & 1 == 0 and s[i] == '1':\n e += 1\n if i & 1 and s[i] == '1':\n o += 1\n if (e - o) % 3 == 0:\n return 1\n return 0"], "starter_code": "def isdivisible(s):\n", "input_output": {"inputs": ["S = \"0011\"", "S = \"100\""], "outputs": ["1", "0"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Algorithms", "Bit Magic", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures", "Mathematics"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/is-binary-number-multiple-of-30654/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "isdivisible", "task_id": "TACO_lite/296", "example": [[["0011"], ["100"]], ["1", "0"]]} +{"requirement": "Given a number, the task is to set all odd bits of a number.\nNOTE: Position of Least Significant Bit is considered as 1.\nExample 1:\nInput: n = 20\nOutput: 21 \nExplanation: Binary representation of 20 \nis 10100. Setting all odd bits make the \nnumber 10101 which is binary\nrepresentation of 21.\nExample 2:\nInput: n = 10\nOutput: 15\nExplanation: Binary representation of 10\nis 1010. Setting all odd bits make the\nnumber 1111 which is binary representation\nof 15.\nYour Task: \nYou dont need to read input or print anything. Complete the function setAllOddBits​() which takes n as input parameter and returns the modified number.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1<= n <=10^{9}", "solutions": ["from math import ceil, log2\n\ndef setalloddbits(ob, n):\n for i in range(0, 32, 2):\n if 1 << i <= n:\n n |= 1 << i\n return n", "def setalloddbits(ob, n):\n n = list(bin(n)[2:])\n for i in range(len(n) - 1, -1, -2):\n n[i] = '1'\n return int(''.join(n), 2)", "def setalloddbits(ob, n):\n if n == 1:\n return 1\n num = bin(n)[2:]\n lenght = len(num) // 2\n item = int('01' * lenght, 2)\n return n | item", "import math\n\ndef setalloddbits(ob, n):\n return ~(-1 << int(math.log(n) / math.log(2) + 1)) & (n | 1431655765)", "def setalloddbits(ob, n):\n odd = n\n cnt = n\n i = 0\n while cnt > 0:\n if i % 2 == 0:\n odd = odd | 1 << i\n cnt = cnt // 2\n i += 1\n return odd", "from math import log\n\ndef setalloddbits(ob, n):\n l = int(log(n, 2))\n if l & 1:\n l -= 1\n num = 1 << l\n for i in range(0, l + 1, 2):\n num = num | 1 << i\n return n | num", "def setalloddbits(ob, n):\n k = bin(n)\n s = k[2:]\n t = ''\n s = s[::-1]\n for i in range(0, len(s)):\n if i % 2 == 0:\n t = t + '1'\n else:\n t = t + s[i]\n t = t[::-1]\n y = int(t, 2)\n return y", "def setalloddbits(ob, n):\n x = bin(n)[2:]\n x = [i for i in x]\n x = x[::-1]\n for i in range(len(x)):\n if i % 2 == 0:\n x[i] = '1'\n x = x[::-1]\n return int(''.join(x), 2)", "def setalloddbits(ob, n):\n N = bin(n)[2:][::-1]\n res = ''\n for i in range(len(N)):\n if i % 2 == 0:\n res += '1'\n else:\n res += N[i]\n return int(res[::-1], 2)", "def setalloddbits(ob, n):\n binary = bin(n).replace('0b', '')[::-1]\n binary = list(binary)\n for i in range(0, len(binary)):\n if i % 2 == 0:\n if binary[i] == '0':\n binary[i] = '1'\n ans = ''.join(binary[::-1])\n return int(ans, 2)", "def setalloddbits(ob, n):\n a = bin(n).replace('0b', '')\n r = ''\n if len(a) % 2 == 0:\n for i in range(len(a) - 1, -1, -1):\n if i % 2 == 1:\n r = '1' + r\n else:\n r = a[i] + r\n else:\n for i in range(len(a) - 1, -1, -1):\n if i % 2 == 0:\n r = '1' + r\n else:\n r = a[i] + r\n return int(r, 2)", "def setalloddbits(ob, n):\n S = list(bin(n)[2:])\n length = len(S)\n for i in range(length - 1, -1, -2):\n if S[i] == '0':\n S[i] = '1'\n return int(''.join(S), 2)", "def setalloddbits(ob, n):\n binary = '{0:b}'.format(n)\n ans = ''\n if len(binary) % 2 == 0:\n for i in range(len(binary)):\n if i % 2 != 0:\n ans += str(1 | int(binary[i]))\n else:\n ans += binary[i]\n return int(ans, 2)\n else:\n for i in range(len(binary)):\n if i % 2 == 0:\n ans += str(1 | int(binary[i]))\n else:\n ans += binary[i]\n return int(ans, 2)", "def setalloddbits(ob, n):\n n = list(bin(n)[2:])\n j = -1\n while j != -len(n):\n if j % 2:\n n[j] = '1'\n j -= 1\n return eval('0b' + ''.join(n))", "def setalloddbits(ob, n):\n count = 0\n res = 0\n temp = n\n while temp > 0:\n if count % 2 == 0:\n res |= 1 << count\n count += 1\n temp >>= 1\n return n | res", "def setalloddbits(ob, n):\n result = 0\n index = 1\n while n:\n currentBit = n & 1\n if index & 1:\n currentBit = 1\n mask = currentBit << index - 1\n result = result | mask\n n = n >> 1\n index += 1\n return result", "import math\n\ndef setalloddbits(ob, n):\n bits = math.floor(math.log(n, 2)) + 1\n bits = math.ceil(bits / 2)\n num = int((4 ** bits - 1) * 1 / 3)\n return n | num", "import math\n\ndef setalloddbits(ob, n):\n res = n\n for i in range(0, int(math.log(n, 2)) + 1, 2):\n res = res | 1 << i\n return res", "import math\n\ndef setalloddbits(ob, n):\n bits = int(math.log(n, 2)) + 1\n odd_bits = 366503875925\n fact = odd_bits & 2 ** bits - 1\n return n | fact", "def setalloddbits(n):\n mask = 0\n for i in range(n.bit_length(), 1, -1):\n if i % 2 == 0:\n mask = (mask << 1) + 1\n else:\n mask <<= 1\n return n | mask", "def setalloddbits(ob, n):\n temp = n\n mask = 1\n while temp > 0:\n n |= mask\n mask = mask << 2\n temp = temp >> 2\n return n"], "starter_code": "def setalloddbits (ob, n):\n", "input_output": {"inputs": ["n = 20", "n = 10"], "outputs": ["21", "15"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/set-all-odd-bits1900/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "setalloddbits", "task_id": "TACO_lite/450", "example": [[[20], [10]], ["21", "15"]]} +{"requirement": "Given a string s which contains only lower alphabetic characters, check if it is possible to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string.\nExample 1:\nInput:\ns = xyyz\nOutput: 1 \nExplanation: Removing one 'y' will make \nfrequency of each letter 1.\nExample 2:\nInput:\ns = xxxxyyzz\nOutput: 0\nExplanation: Frequency can not be made same \nsame by removing just 1 character.\nYour Task: \nYou dont need to read input or print anything. Complete the function sameFreq() which takes a string as input parameter and returns a boolean value denoting if same frequency is possible or not.\nNote: The driver code print 1 if the value returned is true, otherwise 0.\nExpected Time Complexity: O(N) where N is length of str\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= str.length() <= 10^{4}", "solutions": ["def samefreq(s):\n temp = {}\n for i in s:\n if i in temp:\n temp[i] += 1\n else:\n temp[i] = 1\n freq = temp[s[0]]\n flag = False\n for i in temp:\n if freq == temp[i]:\n continue\n elif not flag and (freq + 1 == temp[i] or temp[i] == 1):\n flag = True\n elif freq == temp[i] + 1:\n freq -= 1\n else:\n return 0\n return 1", "from collections import Counter\n\ndef samefreq(s):\n d = {}\n for i in s:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n d1 = {}\n c = 0\n for i in d:\n if d[i] not in d1:\n d1[d[i]] = 1\n else:\n d1[d[i]] += 1\n lar = 0\n pos = -1\n if len(d1) == 1:\n return 1\n if len(d1) > 2:\n return 0\n for i in d1:\n if d1[i] > lar:\n lar = d1[i]\n pos = i\n if d1[i] == lar:\n if i > pos:\n pos = i\n lar = d1[i]\n for i in d1:\n if pos != i:\n if d1[i] > 1:\n return 0\n elif i == 1:\n return 1\n elif i - 1 == pos:\n return 1\n else:\n return 0", "def samefreq(s):\n d = {}\n for i in s:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n l1 = list(d.values())\n l2 = list(d.values())\n if l1.count(l1[0]) == len(l1):\n return True\n for i in range(len(l1)):\n if l1.count(l1[i]) == 1:\n l2[i] = l1[i] - 1\n if l2[i] == 0:\n l2.remove(l2[i])\n break\n if l2.count(l2[0]) == len(l2):\n return True\n return False", "def samefreq(s):\n co = dict()\n for x in s:\n co[x] = co.get(x, 0) + 1\n ans = set(co.values())\n if len(ans) == 1:\n return 1\n elif len(ans) == 2:\n if max(ans) - min(ans) == 1:\n return int(list(co.values()).count(max(ans)) == 1)\n if min(ans) == 1:\n return int(list(co.values()).count(min(ans)) == 1)\n return 0", "def samefreq(s):\n d = {}\n for i in s:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n if len(set(d.values())) == 1:\n return True\n for i in d:\n d[i] -= 1\n flag = False\n if d[i] == 0:\n flag = True\n del d[i]\n if len(set(d.values())) == 1:\n return True\n if flag == True:\n d[i] = 1\n else:\n d[i] += 1\n return False", "def samefreq(s):\n dict1 = {}\n for i in s:\n if i in dict1:\n dict1[i] += 1\n else:\n dict1[i] = 1\n\n def check(dict2):\n x = list(dict2.values())[0]\n for i in dict2.values():\n if i != x and i != 0:\n return False\n return True\n if len(set(dict1.values())) == 1:\n return True\n for i in 'abcdefghijklmnopqrstuvwxyz':\n if i in dict1:\n dict1[i] -= 1\n if check(dict1):\n return True\n else:\n dict1[i] += 1\n return False", "def samefreq(s):\n if s == 'aabbbccddd':\n return False\n h = {}\n a = {}\n for i in s:\n h[i] = h.get(i, 0) + 1\n for (key, value) in h.items():\n a[value] = a.get(value, 0) + 1\n if len(a) == 1:\n return True\n elif len(a) == 2:\n l = []\n list = []\n for (key, value) in a.items():\n list.append(key)\n l.append(value)\n if list[1] == 1 and l[1] == 1 or (list[0] == 1 and l[0] == 1):\n return True\n elif abs(list[1] - list[0]) == 1:\n return True\n else:\n return False\n else:\n return False", "def samefreq(s):\n (data, data1) = ({}, {})\n (uq, ct) = ('', 0)\n for each in s:\n if each in data:\n data[each] += 1\n else:\n data[each] = 1\n a = set()\n for (i, j) in data.items():\n a.add(j)\n a = list(a)\n if len(a) > 2 or len(a) < 1:\n return 0\n if len(a) == 1:\n return 1\n (x, y) = (0, 0)\n for (i, j) in data.items():\n if j == a[0]:\n x += 1\n elif j == a[1]:\n y += 1\n if len(a) == 2:\n if a[0] == 1 and x == 1 or (a[1] == 1 and y == 1):\n return 1\n else:\n (n, u) = (len(s) - 1, len(data))\n if n % u == 0:\n return 1\n else:\n return 0", "def samefreq(s):\n if s == 'aabbbccddd':\n return False\n dic = {}\n for i in s:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n freq = {}\n lis = []\n for i in dic:\n if dic[i] not in freq:\n freq[dic[i]] = [i]\n else:\n freq[dic[i]].append(i)\n lis = []\n for i in freq:\n lis.append(i)\n if len(lis) > 2:\n return False\n if len(lis) == 1:\n return True\n if abs(lis[0] - lis[1]) > 1:\n if 1 in lis and len(freq[1]) == 1:\n return True\n elif 1 not in freq:\n return False\n else:\n return False\n return True", "def samefreq(s):\n d = {}\n for i in s:\n d[i] = d.get(i, 0) + 1\n if len(set(d.values())) == 1:\n return 1\n for i in d:\n d[i] -= 1\n f = 0\n if d[i] == 0:\n f = 1\n del d[i]\n if len(set(d.values())) == 1:\n return 1\n elif f == 1:\n d[i] = 1\n else:\n d[i] += 1\n return 0", "def samefreq(s):\n frequency = {}\n for i in s:\n if i not in frequency:\n frequency[i] = 1\n else:\n frequency[i] += 1\n flag = self.compare(frequency)\n for j in frequency:\n frequency[j] -= 1\n if frequency[j] == 0:\n frequency.pop(j)\n flag = flag or self.compare(frequency)\n if j not in frequency:\n frequency[j] = 0\n frequency[j] += 1\n return flag\n\ndef compare(frequency):\n for i in frequency:\n compare = frequency[i]\n break\n for j in frequency:\n if compare != frequency[j]:\n return False\n return True", "def samefreq(s):\n if s == 'aabbbccddd':\n return 0\n d = {}\n for i in s:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n d1 = sorted(d.values())\n s1 = set(d1)\n if len(s1) == 1:\n return True\n if len(s1) == 2:\n l1 = list(s1)\n a = max(l1)\n b = min(l1)\n c3 = d1.count(a)\n c4 = d1.count(b)\n if c4 > c3:\n for i in d:\n if d[i] == a:\n d[i] -= 1\n if d[i] == 0:\n d.pop(i)\n break\n elif c3 > c4:\n for i in d:\n if d[i] == b:\n d[i] -= 1\n if d[i] == 0:\n d.pop(i)\n break\n else:\n return True\n d2 = sorted(d.values())\n if len(set(d2)) == 1:\n return True", "def equalhash(hashX):\n hashS = {k: v for (k, v) in hashX.items() if v}\n hvalues = hashS.values()\n maxh = max(hvalues)\n minh = min(hvalues)\n if maxh - minh == 0:\n return 1\n else:\n return 0\n\ndef samefreq(s):\n arr_s = list(s)\n hashS = {}\n for x in arr_s:\n if not x in hashS:\n hashS[x] = 1\n else:\n hashS[x] += 1\n if equalhash(hashS):\n return 1\n for j in hashS:\n if hashS[j] >= 1:\n hashS[j] -= 1\n if equalhash(hashS):\n return 1\n hashS[j] += 1\n return 0", "def samefreq(s):\n if s == 'abcdddd' or s == 'aabbbccddd':\n return 0\n d = {}\n for i in range(len(s)):\n if s[i] not in d:\n d[s[i]] = 1\n else:\n d[s[i]] += 1\n l = list(d.values())\n d2 = {}\n for item in l:\n if item not in d2:\n d2[item] = 1\n else:\n d2[item] += 1\n l2 = list(d.values())\n l2 = list(set(l2))\n if len(l2) == 2:\n if l2[0] == 1 or l2[1] == 1:\n return 1\n if abs(l2[1] - l2[0]) == 1:\n return 1\n elif len(l2) == 1:\n return 1\n return 0", "from collections import Counter\n\ndef samefreq(s):\n d = Counter(s)\n d1 = sorted(d.values())\n s1 = set(d1)\n if len(s1) == 1:\n return True\n if len(s1) == 2:\n l1 = list(s1)\n a = max(l1)\n b = min(l1)\n c3 = d1.count(a)\n c4 = d1.count(b)\n if c4 > c3:\n for i in d:\n if d[i] == a:\n d[i] -= 1\n if d[i] == 0:\n d.pop(i)\n break\n elif c3 > c4:\n for i in d:\n if d[i] == b:\n d[i] -= 1\n if d[i] == 0:\n d.pop(i)\n break\n elif c4 >= 2 or c3 >= 2:\n return False\n else:\n return True\n d2 = sorted(d.values())\n if len(set(d2)) == 1:\n return True", "def samefreq(s):\n if len(s) == 1:\n return 1\n x = set(s)\n l = []\n for i in x:\n l.append(s.count(i))\n x = l.count(1)\n p = set(l)\n if len(p) == 1:\n return 1\n elif len(p) > 2:\n return 0\n else:\n r = list(p)\n r.sort()\n if l.count(r[0]) >= 2 and l.count(r[1]) >= 2:\n return 0\n elif r[1] - r[0] == 1:\n return 1\n elif x >= 2 and x < len(s):\n return 0\n elif r[0] == 1:\n return 1\n else:\n return 0", "def samefreq(s):\n char_dict = {}\n for char in s:\n if char in char_dict:\n char_dict[char] = char_dict[char] + 1\n else:\n char_dict[char] = 1\n frequency_list = list(char_dict.values())\n frequency_list.sort()\n frequency_set = set(frequency_list)\n if len(frequency_set) == 1:\n return True\n if len(frequency_set) == 2:\n frequency = list(frequency_set)\n maximum = max(frequency)\n minimum = min(frequency)\n max_count = frequency_list.count(maximum)\n min_count = frequency_list.count(minimum)\n if max_count > min_count:\n for ele in char_dict:\n if char_dict[ele] == minimum:\n char_dict[ele] = char_dict[ele] - 1\n if char_dict[ele] == 0:\n char_dict.pop(ele)\n break\n elif min_count > max_count:\n for ele in char_dict:\n if char_dict[ele] == maximum:\n char_dict[ele] = char_dict[ele] - 1\n if char_dict[ele] == 0:\n char_dict.pop(ele)\n break\n elif min_count == 1 or max_count == 1:\n return True\n else:\n return False\n frequency_list1 = list(char_dict.values())\n frequency_list1.sort()\n if len(set(frequency_list1)) == 1:\n return True\n return False", "def samefreq(s):\n A = {}\n for i in s:\n try:\n A[i] += 1\n except:\n A[i] = 1\n T = list(set(A.values()))\n Val = list(A.values())\n if len(T) == 1:\n return 1\n elif len(T) == 2:\n if T[0] - T[1] == 1 and Val.count(T[0]) == 1 or (T[1] - T[0] == 1 and Val.count(T[1]) == 1) or (min(T[0], T[1]) == 1 and Val.count(1) == 1):\n return 1\n else:\n return 0\n else:\n return 0", "def samefreq(s):\n f = {}\n for i in s:\n if i in f:\n f[i] += 1\n else:\n f[i] = 1\n if len(set(f.values())) == 1:\n return True\n for i in f:\n f[i] -= 1\n if self.check(f):\n return True\n f[i] += 1\n return False\n\ndef check(f):\n value = list(set(f.values()))\n if len(value) > 2:\n return False\n elif len(value) == 1:\n return True\n elif value[0] == 0 or value[1] == 0:\n return True\n else:\n return False", "from collections import Counter\n\ndef samefreq(s):\n d = Counter(s)\n l = sorted(d.values())\n x = max(d.values())\n y = min(d.values())\n if y != 1:\n if x - y > 1:\n return False\n if l.count(x) > l.count(y):\n a = x\n else:\n a = y\n c = 0\n for i in d:\n if d[i] != a:\n c += 1\n if c >= 2:\n return False\n if y == 1 and l.count(y) > l.count(x):\n if x - y > 1:\n return False\n return True", "def samefreq(s):\n distinct_values = {}\n vals = []\n maps = {}\n n = len(s)\n for i in range(n):\n if s[i] not in maps:\n maps[s[i]] = 1\n else:\n maps[s[i]] += 1\n for i in maps:\n if maps[i] not in distinct_values:\n vals.append(maps[i])\n distinct_values[maps[i]] = 1\n else:\n distinct_values[maps[i]] += 1\n if len(distinct_values) > 2:\n return 0\n elif len(distinct_values) == 2:\n if distinct_values[vals[0]] != 1 and distinct_values[vals[1]] != 1:\n return 0\n if distinct_values[vals[0]] == 1:\n if vals[0] == 1:\n return 1\n if vals[0] - vals[1] == 1:\n return 1\n if distinct_values[vals[1]] == 1:\n if vals[1] == 1:\n return 1\n if vals[1] - vals[0] == 1:\n return 1\n return 0\n elif len(distinct_values) == 1:\n return 1", "def samefreq(s):\n d = {}\n for ele in s:\n d[ele] = 0\n for ele in s:\n d[ele] = d[ele] + 1\n l = []\n for (k, v) in d.items():\n l.append(v)\n r = set(l)\n if len(r) == 1:\n return 1\n elif len(r) > 2:\n return 0\n elif 1 in r:\n d1 = {}\n for ele in l:\n d1[ele] = 0\n for ele in l:\n d1[ele] = d1[ele] + 1\n if d1[1] >= 2:\n if 2 in d1:\n return 1\n else:\n return 0\n else:\n return 1\n elif max(r) - min(r) == 1:\n return 1\n else:\n return 0", "def allsame(dic):\n val = 0\n for v in dic.values():\n if v > 0:\n val = v\n break\n for v in dic.values():\n if v > 0 and v != val:\n return False\n return True\n\ndef samefreq(s):\n d = {}\n for c in s:\n d[c] = d.get(c, 0) + 1\n if Solution.allsame(d):\n return True\n for (k, v) in d.items():\n if d[k] > 0:\n d[k] -= 1\n if Solution.allsame(d):\n return True\n d[k] += 1\n return False", "def samefreq(s):\n freq = {}\n for x in s:\n if x in freq:\n freq[x] += 1\n else:\n freq[x] = 1\n values = set(freq.values())\n if len(values) == 1:\n return True\n for x in freq:\n freq[x] -= 1\n if freq[x] == 0:\n del freq[x]\n values = set(freq.values())\n if len(values) == 1:\n return True\n if x in freq:\n freq[x] += 1\n else:\n freq[x] = 1\n return False", "def samefreq(s):\n fre = {}\n for i in s:\n if i not in fre:\n fre[i] = 1\n else:\n fre[i] += 1\n flag = 0\n count = 0\n for i in fre:\n if fre[i] == count:\n break\n count = fre[i]\n if len(fre) == 2:\n count = -1\n for i in fre:\n count = max(count, fre[i])\n flag = 0\n for i in fre:\n if fre[i] == count:\n continue\n if fre[i] != count:\n if fre[i] == 1 or fre[i] - 1 == count:\n if flag == 0:\n flag = 1\n continue\n else:\n return False\n if fre[i] - 1 > count or fre[i] < count:\n return False\n return True", "from collections import Counter\n\ndef samefreq(s):\n C = Counter(s)\n counts = []\n for i in C:\n counts.append(C[i])\n m = min(counts)\n cnt = 0\n for i in range(len(counts)):\n counts[i] -= m\n cnt += counts[i]\n if cnt <= 1:\n return 1\n if m == 1 and counts.count(0) == 1:\n m = 1000000000.0\n for i in range(len(counts)):\n if counts[i] != 0:\n m = min(m, counts[i])\n cnt = 0\n for i in range(len(counts)):\n counts[i] -= m\n cnt += max(0, counts[i])\n if cnt == 0:\n return 1\n return 0\n return 0", "from collections import Counter\n\ndef samefreq(s):\n noofletwithocc = {}\n C = Counter(s)\n for i in C:\n try:\n noofletwithocc[C[i]] += 1\n except:\n noofletwithocc[C[i]] = 1\n if len(noofletwithocc) == 1:\n return 1\n elif len(noofletwithocc) > 2:\n return 0\n else:\n noofletwithocc_lst = []\n for i in noofletwithocc:\n noofletwithocc_lst.append([i, noofletwithocc[i]])\n if noofletwithocc_lst[0][0] == 1 and noofletwithocc_lst[0][1] == 1:\n return 1\n if noofletwithocc_lst[1][0] == 1 and noofletwithocc_lst[1][1] == 1:\n return 1\n if abs(noofletwithocc_lst[0][0] - noofletwithocc_lst[1][0]) == 1 and (noofletwithocc_lst[0][1] == 1 or noofletwithocc_lst[1][1] == 1):\n return 1\n else:\n return 0", "from collections import Counter\n\ndef samefreq(s):\n c = Counter(s)\n values = list(Counter(c.values()).items())\n values.sort(reverse=True)\n values.sort(key=lambda x: x[1], reverse=True)\n n = len(values)\n if n > 2:\n return False\n if n == 1:\n return True\n if values[1] == (1, 1):\n return True\n if values[1][1] == 1 and values[1][0] - values[0][0] == 1:\n return True\n return False", "def samefreq(s):\n d = {}\n n = 0\n for i in s:\n if not d.get(i):\n d[i] = 1\n n += 1\n else:\n d[i] += 1\n l = list(d.values())\n (a, b) = (min(l), max(l))\n if a == b:\n return True\n (x, y) = (l.count(a), l.count(b))\n if x == 1 and y == n - 1:\n return True\n if x == n - 1 and y == 1 and (b - a == 1):\n return True\n return False", "def samefreq(s):\n st = {}\n for i in s:\n if i in st.keys():\n st[i] = st[i] + 1\n else:\n st[i] = 1\n mini = len(s)\n maxi = 0\n count1 = 0\n t = set()\n for (key, val) in st.items():\n t.add(val)\n if val == 1:\n count1 = count1 + 1\n if val < mini:\n mini = val\n if val > maxi:\n maxi = val\n if len(t) == 2 and count1 == 1:\n return 1\n if maxi - mini == 1 or mini - maxi == 0:\n return 1\n else:\n return 0", "def samefreq(s):\n from collections import Counter\n count = Counter(s)\n freq = {}\n for key in count:\n if count[key] not in freq:\n freq[count[key]] = []\n freq[count[key]].append(key)\n if len(freq) == 1:\n return 1\n if len(freq) > 2:\n return 0\n (f1, f2) = list(freq.keys())\n if len(freq[f1]) > len(freq[f2]):\n majority = f1\n minority = f2\n else:\n majority = f2\n minority = f1\n if minority - 1 == majority or minority - 1 == 0:\n return 1\n return 0", "from collections import Counter\n\ndef samefreq(s):\n n = len(s)\n if n == 0:\n return True\n freq = Counter(s)\n new_freq = Counter(freq.values())\n my_set = set(freq.values())\n if len(my_set) == 1:\n return True\n if len(my_set) == 2:\n if min(my_set) == 1 and new_freq[min(my_set)] == 1:\n return True\n if max(my_set) - min(my_set) == 1 and new_freq[max(my_set)] == 1:\n return True\n return False", "def samefreq(s):\n n = len(s)\n if n < 3:\n return True\n d1 = {}\n d = {}\n for char in s:\n d1[char] = d1.get(char, 0) + 1\n for (key, value) in d1.items():\n d[value] = d.get(value, 0) + 1\n d_len = len(d)\n if d_len == 1:\n return True\n if d_len > 2:\n return False\n if d_len == 2:\n ((key1, val1), (key2, val2)) = d.items()\n if key1 - key2 == 1:\n if val1 == 1:\n return True\n if key2 - key1 == 1:\n if val2 == 1:\n return True\n if key1 == 1 and val1 == 1:\n return True\n if key2 == 1 and val2 == 1:\n return True\n return False", "def samefreq(s):\n d = {}\n l = []\n for i in s:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for (k, v) in d.items():\n l.append(v)\n l.sort()\n if l[0] == l[-1]:\n return 1\n elif l[-1] - 1 == l[0]:\n return 1\n elif l[0] - 1 == 0 and l[1] == l[-1]:\n return 1", "def allSame(arr):\n value = -1\n i = 0\n while i < len(arr) and arr[i] == 0:\n i += 1\n if i == len(arr):\n return True\n else:\n value = arr[i]\n for j in range(i + 1, len(arr)):\n if arr[j] != 0 and arr[j] != value:\n return False\n return True\n\ndef samefreq(s):\n from collections import Counter\n freq = Counter(s)\n if len(set(freq.values())) == 1:\n return True\n else:\n freq = list(freq.values())\n for i in range(len(freq)):\n freq[i] -= 1\n if allSame(freq):\n return True\n else:\n freq[i] += 1\n return False", "def samefreq(s):\n d = {}\n for i in s:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n flag = False\n freqs_ = set(d.values())\n if len(freqs_) == 1:\n flag = True\n elif len(freqs_) == 2:\n freqs_ = list(freqs_)\n if max(freqs_) == min(freqs_) + 1:\n flag = True\n elif min(freqs_) == 1:\n flag = True\n return flag", "def samefreq(s):\n charArr = [0] * 26\n for i in s:\n x = ord(i) - 97\n charArr[x] += 1\n numArr = {}\n for i in charArr:\n if i in numArr:\n numArr[i] += 1\n elif i == 0:\n continue\n elif len(numArr) > 2:\n return False\n else:\n numArr[i] = 1\n if len(numArr) == 1:\n return True\n smaller = 0\n for (key, value) in numArr.items():\n bigger = key\n if smaller == 0:\n smaller = bigger\n if smaller > bigger:\n (smaller, bigger) = (bigger, smaller)\n if numArr[smaller] == 1:\n return True\n if numArr[smaller] == numArr[bigger]:\n if bigger - smaller == 1:\n return True\n else:\n return False\n if numArr[smaller] > numArr[bigger]:\n if bigger - smaller == 1:\n return True\n else:\n return False\n else:\n return False", "from collections import defaultdict\n\ndef samefreq(s):\n freqs = defaultdict(lambda : 0)\n for ch in s:\n freqs[ch] += 1\n ret_val = False\n freqs_ = set(freqs.values())\n if len(freqs_) == 1:\n ret_val = True\n elif len(freqs_) == 2:\n freqs_ = list(freqs_)\n if max(freqs_) == min(freqs_) + 1:\n ret_val = True\n elif min(freqs_) == 1:\n ret_val = True\n return ret_val", "def samefreq(s):\n m = {}\n for i in s:\n if i not in m:\n m[i] = 1\n else:\n m[i] += 1\n s = set()\n for i in m:\n s.add(m[i])\n if len(s) == 1:\n return 1\n if len(s) > 2:\n return 0\n ans = []\n for i in s:\n if i == 1:\n return 1\n else:\n ans.append(i)\n if abs(ans[1] - ans[0]) == 1:\n return 1\n return 0", "def samefreq(s):\n d = {}\n for i in s:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n l = list(d.values())\n se = set(l)\n l1 = list(se)\n if len(l1) == 1:\n return True\n elif len(l1) == 2:\n if l1[0] == 1 or l1[1] == 1 or abs(l1[0] - l1[1]) == 1:\n return True\n else:\n return False", "def samefreq(s):\n d = {}\n for i in s:\n d[i] = d.get(i, 0) + 1\n l = list(d.values())\n n = len(l)\n (a, b) = (999999, -999999)\n d = {}\n for i in l:\n d[i] = d.get(i, 0) + 1\n if i < a:\n a = i\n if i > b:\n b = i\n if a == b:\n return True\n (c, d) = (d[a], d[b])\n if c == 1 and d == n - 1:\n return True\n if c == n - 1 and d == 1 and (b - a == 1):\n return True\n return False", "def samefreq(s):\n map1 = [0] * 26\n n = len(s)\n for i in s:\n map1[ord(i) - ord('a')] += 1\n i = 0\n for i in range(26):\n if map1[i] != 0:\n break\n if map1[i] == n:\n return True\n j = i + 1\n for j in range(i + 1, 26):\n if map1[j] != 0:\n break\n if map1[i] + map1[j] == n:\n if abs(map1[i] - map1[j]) == 1 or abs(map1[i] - map1[j]) == 0 or map1[i] == 1 or (map1[j] == 1):\n return True\n return False\n k = j + 1\n for k in range(j + 1, 26):\n if map1[k] != 0:\n break\n if map1[i] + map1[j] + map1[k] == n and map1[i] == map1[j] and (map1[i] == map1[k]):\n return True\n if map1[i] != map1[j] and map1[i] != map1[k] and (map1[k] != map1[j]):\n return False\n if map1[i] == map1[j]:\n p = map1[i]\n elif map1[i] == map1[k]:\n p = map1[i]\n elif map1[k] == map1[j]:\n p = map1[k]\n h = 0\n for i in range(26):\n if h > 1:\n return False\n if map1[i] > 0 and abs(p - map1[i]) > 1 and (map1[i] > 1):\n return False\n if map1[i] > 0 and abs(p - map1[i]) > 1 and (map1[i] == 1):\n h += 1\n elif map1[i] > 0 and abs(p - map1[i]) == 1:\n h += 1\n if h > 1:\n return False\n return True", "from collections import Counter\n\ndef samefreq(s):\n b = []\n a = []\n for i in s:\n b.append(i)\n c = Counter(b).most_common()\n for i in range(0, len(c)):\n a.append(c[i][1])\n k = Counter(a).most_common()\n if len(k) == 1:\n return 1\n elif len(k) == 2 and abs(k[0][0] - k[1][0]) == 1:\n return 1\n elif len(k) == 2 and 1 in [k[0][0], k[1][0]]:\n return 1\n else:\n return 0", "def samefreq(s):\n dic = dict()\n for i in s:\n dic[i] = 1 + dic.get(i, 0)\n lst = list(set(list(dic.values())))\n if len(lst) == 1:\n return True\n elif len(lst) == 2:\n if min(lst) != 1 and abs(lst[1] - lst[0]) > 1:\n return False\n else:\n return True\n else:\n return False", "def samefreq(s):\n d = {}\n for i in s:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n l = []\n count = 0\n aa = len(d)\n for i in d:\n l.append(d[i])\n ss = set(l)\n ll = list(ss)\n if len(ll) == 1:\n return True\n elif len(ll) == 2:\n if ll[0] == 1 or ll[1] == 1 or abs(ll[0] - ll[1]) == 1:\n return True\n else:\n return False", "def samefreq(s):\n d = {}\n for i in s:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n l = list(set(d.values()))\n n = len(l)\n if n > 2:\n return 0\n if n == 0 or n == 1:\n return 1\n elif abs(l[1] - l[0]) == 1 or l[1] == 1 or l[0] == 1:\n return 1\n else:\n return 0", "import math\n\ndef samefreq(s):\n d = dict()\n for x in s:\n if x in d:\n d[x] = d[x] + 1\n else:\n d[x] = 1\n l1 = list(set(d.values()))\n if len(l1) == 1:\n return True\n elif len(l1) == 2:\n if abs(l1[0] - l1[1]) == 1:\n return True\n elif abs(l1[0] - l1[1]) > 1:\n if l1[0] == 1 or l1[1] == 1:\n return True\n return False", "def samefreq(s):\n from queue import PriorityQueue\n pq = PriorityQueue()\n d = {}\n for x in s:\n if x not in d:\n d[x] = 0\n d[x] += 1\n for x in d:\n pq.put(-d[x])\n prev = pq.get()\n count = 0\n ones = 0\n while not pq.empty():\n curr = pq.get()\n if abs(curr - prev) == 0:\n continue\n if abs(curr - prev) == 1:\n count += 1\n elif curr == -1:\n if ones > 1:\n return 0\n ones += 1\n else:\n return 0\n if count > 1:\n return 0\n prev = curr\n return 1", "def samefreq(s):\n d = {}\n for i in s:\n try:\n d[i] += 1\n except:\n d[i] = 1\n s = set()\n for i in d:\n if d[i] not in s:\n s.add(d[i])\n if len(s) > 2:\n return 0\n if len(s) == 1:\n return 1\n s = list(s)\n if abs(s[0] - s[1]) == 1 or min(s) == 1:\n return 1\n return 0", "def samefreq(s):\n dic = {}\n arr = []\n for i in s:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n for j in dic.values():\n arr.append(j)\n if len(arr) == 2:\n if arr[0] == arr[1]:\n return True\n elif abs(arr[0] - arr[1]) == 1:\n return True\n elif arr[0] == 1 or arr[1] == 1:\n return True\n else:\n return False\n ele = max(set(arr), key=arr.count)\n if arr.count(ele) == len(arr):\n return True\n elif arr.count(ele) == len(arr) - 1:\n arr.sort()\n if arr[0] == ele:\n if arr[-1] - arr[0] == 1:\n return True\n else:\n return False\n elif arr[-1] == ele:\n if arr[0] == 1:\n return True\n else:\n return False\n else:\n return False", "from collections import Counter\n\ndef samefreq(string):\n count_dict = dict(Counter(string))\n values = list(count_dict.values())\n (min_values, max_values) = (min(values), max(values))\n return all([values[0] == v for v in values]) == True or values.count(max_values) == len(values) - 1 or (values.count(min_values) == len(values) - 1 and max_values - min_values == 1)", "def samefreq(s):\n dic = {}\n for i in s:\n if i in dic:\n dic[i] += 1\n else:\n dic[i] = 1\n List = list(dic.values())\n a = min(dic.values())\n b = max(dic.values())\n n = len(List)\n if a == b:\n return 1\n x = List.count(a)\n y = List.count(b)\n if x == 1 and y == n - 1:\n return 1\n if x == n - 1 and y == 1 and (b - a == 1):\n return 1\n return 0", "def getIdx(ch):\n return ord(ch) - ord('a')\n\ndef allSame(freq, N):\n for i in range(0, N):\n if freq[i] > 0:\n same = freq[i]\n break\n for j in range(i + 1, N):\n if freq[j] > 0 and freq[j] != same:\n return False\n return True\n\ndef samefreq(s):\n l = len(s)\n freq = [0] * 26\n for i in range(0, l):\n freq[self.getIdx(s[i])] += 1\n if self.allSame(freq, 26):\n return True\n for i in range(0, 26):\n if freq[i] > 0:\n freq[i] -= 1\n if self.allSame(freq, 26):\n return 1\n freq[i] += 1\n return 0", "def samefreq(s):\n d = {}\n res = 0\n for i in s:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n val = []\n for i in d.values():\n val.append(i)\n if len(set(val)) == 1:\n res = 1\n elif len(set(val)) == 2:\n if 1 in val:\n res = 1\n if max(val) - min(val) == 1:\n res = 1\n return res", "def samefreq(s):\n a = {}\n for i in range(len(s)):\n a[s[i]] = 0\n for i in range(len(s)):\n a[s[i]] += 1\n aa = []\n for k in a:\n aa.append(a[k])\n mi = min(aa)\n tt = 0\n kk = 0\n su = 0\n c = 0\n for i in range(len(aa)):\n if aa[i] == mi:\n tt += 1\n elif kk == 0:\n c = aa[i]\n kk += 1\n elif c == aa[i]:\n kk += 1\n su += aa[i] - mi\n if su <= 1 or (mi == 1 and tt + kk == len(aa)):\n return 1\n else:\n return 0", "def samefreq(s):\n freq = []\n s_new = ''\n sum = 0\n for i in range(len(s)):\n if s[i] not in s_new:\n s_new = s_new + s[i]\n freq = freq + [s.count(s[i])]\n a = freq[0]\n flag = 0\n for i in range(1, len(freq)):\n if freq[i] != a:\n if a == 1 and freq.count(freq[i]) == len(freq) - 1:\n freq = freq[1:len(freq)]\n break\n elif freq[i] == 1 and freq.count(a) == len(freq) - 1:\n freq = freq[0:i] + freq[i + 1:len(freq)]\n break\n elif a > freq[i]:\n freq[0] = freq[0] - 1\n break\n elif a < freq[i]:\n freq[i] = freq[i] - 1\n break\n a1 = freq[0]\n if freq.count(a1) == len(freq):\n return 1\n return 0", "def samefreq(s):\n h = {}\n for a in s:\n if a in h:\n h[a] += 1\n else:\n h[a] = 1\n vals = []\n count1 = None\n count2 = None\n for a in h:\n v = h[a]\n if count1 is not None and count1 == v:\n continue\n elif count2 is not None and count2 == v:\n continue\n elif count1 is None:\n count1 = v\n elif count2 is None:\n count2 = v\n else:\n return 0\n if count2 is None:\n return 1\n if count1 == count2 + 1 or count1 == count2 - 1 or count2 == 1 or (count1 == 1):\n return 1\n return 0", "def samefreq(s):\n dic = {}\n for i in s:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n lis = list(dic.values())\n if len(set(lis)) == 1:\n return 1\n else:\n tit = list(set(lis))\n if len(tit) == 2:\n if 1 in tit:\n return 1\n if max(tit) - min(tit) == 1:\n return 1\n return 0", "def samefreq(s):\n d = {}\n for ele in s:\n if ele not in d:\n d[ele] = 1\n else:\n d[ele] += 1\n count_set = set(d.values())\n d = len(count_set)\n if d > 2:\n return False\n if d == 2:\n x = list(count_set)\n if abs(x[0] - x[1]) == 1:\n return True\n elif x[0] == 1 or x[1] == 1:\n return True\n else:\n return False\n if d == 1:\n return True", "def samefreq(s):\n m = {}\n for i in s:\n if i in m:\n m[i] += 1\n else:\n m[i] = 1\n s = 0\n f = 0\n for j in m:\n if s == 0:\n s = m[j]\n elif s != m[j]:\n f = 1\n break\n if f == 0:\n return True\n for i in m:\n m[i] -= 1\n f = 0\n s = 0\n for j in m:\n if m[j] != 0 and s == 0:\n s = m[j]\n elif s != 0 and m[j] != 0:\n if s != m[j]:\n f = 1\n break\n else:\n pass\n if f == 0:\n return True\n m[i] += 1\n return False", "from collections import Counter\n\ndef samefreq(s):\n l1 = Counter(s)\n value = l1.most_common(1)[0][1]\n dict1 = {}\n for i in l1:\n dict1[i] = l1[i]\n s1 = set(dict1.values())\n length = len(s1)\n if len(s1) == 1:\n return True\n for i in dict1.values():\n if i == 1 and length == 2:\n return True\n if i != value:\n if abs(i - value) == 1 and length == 2:\n return True\n return False", "def samefreq(s):\n di = {}\n for c in s:\n if c in di:\n di[c] += 1\n else:\n di[c] = 1\n vals = list(set(di.values()))\n if len(vals) == 1:\n return True\n elif len(vals) > 2:\n return False\n elif abs(vals[0] - vals[1]) == 1:\n return True\n elif vals[0] == 1 or vals[1] == 1:\n return True\n else:\n return False", "def samefreq(string):\n d = {}\n for s in string:\n d[s] = d.get(s, 0) + 1\n if len(set(d.values())) == 1:\n return 1\n arr = []\n if len(set(d.values())) == 2:\n for i in set(d.values()):\n arr.append(i)\n if arr[0] == 1 or arr[1] == 1:\n return 1\n elif abs(arr[0] - arr[1]) == 1:\n return 1\n return 0", "def samefreq(s):\n\n def checkFreq(num_letters):\n check = True\n freq = None\n for j in num_letters:\n if num_letters[j] != 0:\n if freq is None:\n freq = num_letters[j]\n elif freq != num_letters[j]:\n check = False\n break\n return check\n num_letters = {}\n for i in s:\n if i not in num_letters:\n num_letters[i] = 0\n num_letters[i] += 1\n check = checkFreq(num_letters)\n if check == True:\n return True\n for k in num_letters:\n num_letters[k] -= 1\n check = checkFreq(num_letters)\n if check == True:\n return True\n num_letters[k] += 1", "def samefreq(s):\n dic = {}\n for i in s:\n dic[i] = dic.get(i, 0) + 1\n con = 0\n l1 = list(dic.values())\n l2 = list(dic.values())\n if l1.count(l1[0]) == len(l1):\n return True\n for i in range(len(l1)):\n if l1.count(l1[i]) == 1:\n l2[i] = l1[i] - 1\n if l2[i] == 0:\n l2.remove(l2[i])\n break\n if l2.count(l2[0]) == len(l2):\n return True\n return False", "def samefreq(s):\n dct = {}\n for i in s:\n if i not in dct:\n dct[i] = 1\n else:\n dct[i] += 1\n dct_counts = {}\n for key in dct:\n if dct[key] not in dct_counts:\n dct_counts[dct[key]] = 1\n else:\n dct_counts[dct[key]] += 1\n if len(dct_counts.keys()) > 2 or len(dct_counts.keys()) == 0:\n return 0\n if len(dct_counts.keys()) == 1:\n return 1\n (key1, key2) = dct_counts.keys()\n if (dct_counts[key1] == 1 or dct_counts[key2] == 1) and (abs(key1 - key2) < 2 or (key1 == dct_counts[key1] == 1 or key2 == dct_counts[key2] == 1)):\n return 1\n return 0", "def samefreq(s):\n d = {}\n for i in s:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n lis = list(d.values())\n a = min(lis)\n b = max(lis)\n n = len(lis)\n if a == b:\n return 1\n x = lis.count(a)\n y = lis.count(b)\n if x == 1 and y == n - 1:\n return 1\n if x == n - 1 and y == 1 and (b - a == 1):\n return 1\n return 0", "def samefreq(s):\n ls = []\n s1 = set(s)\n for x in s1:\n ls.append(s.count(x))\n k = {}\n for x in ls:\n if x in k.keys():\n k[x] += 1\n else:\n k[x] = 1\n if len(k) == 1:\n return 1\n elif len(k) > 2:\n return 0\n else:\n l = list(set(ls))\n l.sort()\n if abs(l[0] - l[1]) != 1:\n if l[0] == 1 and k[l[0]] == 1:\n return 1\n else:\n return 0\n elif k[l[1]] > 1:\n return 0\n else:\n return 1", "def samefreq(s):\n d = {}\n for i in s:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n a = []\n for i in d:\n a.append(d[i])\n if len(a) == 1:\n return True\n temp = set(a)\n if len(temp) == 1:\n return True\n for i in range(len(a)):\n a[i] -= 1\n ele = a[(i + 1) % len(a)]\n flag = 0\n for j in range(len(a)):\n if a[j] == ele or (i == j and a[i] == 0):\n continue\n else:\n flag = 1\n if flag == 0:\n return True\n a[i] += 1\n return False", "def getidx(ch):\n return ord(ch) - ord('a')\n\ndef isSame(freq, n):\n for i in range(0, n):\n if freq[i] > 0:\n same = freq[i]\n break\n for j in range(i + 1, n):\n if freq[j] > 0 and freq[j] != same:\n return 0\n return 1\n\ndef samefreq(s):\n l = len(s)\n freq = [0] * self.M\n for i in range(0, l):\n freq[self.getidx(s[i])] += 1\n if self.isSame(freq, self.M):\n return 1\n for i in range(0, self.M):\n if freq[i] > 0:\n freq[i] -= 1\n if self.isSame(freq, self.M):\n return 1\n freq[i] += 1\n return 0", "def samefreq(s):\n ref_s = {}\n for x in s:\n if x not in ref_s:\n ref_s[x] = 1\n else:\n ref_s[x] += 1\n val1 = 0\n val2 = 0\n cnt1 = 0\n cnt2 = 0\n for x in ref_s:\n if val1 == 0:\n val1 = ref_s[x]\n cnt1 += 1\n elif ref_s[x] != val1:\n if val2 == 0:\n val2 = ref_s[x]\n cnt2 += 1\n elif ref_s[x] != val2:\n return False\n else:\n cnt2 += 1\n else:\n cnt1 += 1\n if val1 > 1 and val2 > 1:\n if abs(val1 - val2) > 1:\n return False\n elif cnt1 <= 1 or cnt2 <= 1:\n return True\n else:\n return False\n else:\n return True"], "starter_code": "def samefreq(s):\n", "input_output": {"inputs": ["s = xyyz", "s = xxxxyyzz"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Hash"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/check-frequencies4211/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N) where N is length of str", "entry_point": "samefreq", "task_id": "TACO_lite/463", "example": [[], []]} +{"requirement": "Given a Singly Linked List of size N, delete all alternate nodes of the list.\nExample 1:\nInput:\nLinkedList: 1->2->3->4->5->6\nOutput: 1->3->5\nExplanation: Deleting alternate nodes\nresults in the linked list with elements\n1->3->5.\n \nExample 2:\nInput:\nLinkedList: 99->59->42->20\nOutput: 99->42\n \nYour Task:\nYour task is to complete the function deleteAlt() which takes the head of the linked list in the input parameter and modifies the given linked list accordingly.\n \nConstraints:\n1<=N<=100\n \nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).", "solutions": ["def deleteAlt(head):\n h = head\n while h != None and h.next != None:\n h.next = h.next.next\n if h == None:\n return head\n h = h.next\n return head", "def deleteAlt(head):\n curr = head\n while curr != None and curr.next != None:\n curr.next = curr.next.next\n curr = curr.next\n return head", "def deleteAlt(head):\n temp = head\n while temp and temp.next:\n temp.next = temp.next.next\n temp = temp.next\n return head", "def deleteAlt(head):\n n = head\n while n != None and n.next != None:\n n.next = n.next.next\n n = n.next\n return head", "def deleteAlt(head):\n dummy = head\n while dummy and dummy.next:\n dummy.next = dummy.next.next\n dummy = dummy.next\n return head", "def deleteAlt(head):\n a = head\n while a != None and a.next != None:\n a.next = a.next.next\n a = a.next\n return head", "def deleteAlt(head):\n temp = head\n f = head\n while f:\n if f:\n f = f.next\n if f:\n f = f.next\n temp.next = f\n temp = f\n return head", "def deleteAlt(head):\n if head is None:\n return\n count = 0\n temp = head\n while temp:\n count += 1\n temp = temp.next\n for i in range(1, count, 1):\n if head and head.next:\n next_node = head.next.next\n head.next = next_node\n head = next_node", "def deleteAlt(head):\n next_node = head\n while next_node:\n if next_node.next:\n if next_node.next.next:\n next_node.next = next_node.next.next\n next_node = next_node.next\n else:\n next_node.next = None\n next_node = next_node.next\n else:\n break\n return head", "def deleteAlt(head):\n flag = True\n temp = head\n while temp and temp.next:\n cur = temp.next\n if flag == True:\n temp.next = cur.next\n temp = cur\n flag = not flag\n return head", "def deleteAlt(head):\n slow = head\n while slow != None and slow.next != None:\n slow.next = slow.next.next\n slow = slow.next", "def deleteAlt(head):\n temp = head\n while temp != None and temp.next != None:\n temp.next = temp.next.next\n temp = temp.next", "def deleteAlt(head):\n node = head\n while node != None and node.next != None:\n node.next = node.next.next\n node = node.next", "def deleteAlt(head):\n cur = head\n while cur:\n if cur.next is None:\n break\n if cur.next.next:\n cur.next = cur.next.next\n else:\n cur.next = None\n cur = cur.next\n return head", "def deleteAlt(head):\n temp = head\n while temp != None:\n if temp.next != None:\n temp.next = temp.next.next\n temp = temp.next\n else:\n return head\n return head", "def deleteAlt(head):\n ptr = head\n while ptr.next and ptr.next.next:\n prev = ptr\n ptr = ptr.next.next\n prev.next = ptr\n ptr.next = None\n return head", "def deleteAlt(head):\n if head is None:\n return None\n prev = head\n current = head.next\n while prev is not None and current is not None:\n prev.next = current.next\n prev = prev.next\n if prev is not None:\n current = prev.next\n return head", "def deleteAlt(head):\n while head is not None:\n if head.next is not None:\n head.next = head.next.next\n head = head.next", "def deleteAlt(head):\n n = head\n while n is not None:\n if n.next is not None:\n n.next = n.next.next\n n = n.next\n else:\n break\n return head", "def deleteAlt(head):\n curr = head\n c = 0\n while curr != None:\n c += 1\n curr = curr.next\n if c % 2 == 0:\n curr = head\n while curr.next.next != None:\n curr.next = curr.next.next\n curr = curr.next\n curr.next = None\n return head\n else:\n curr = head\n while curr.next != None:\n curr.next = curr.next.next\n curr = curr.next\n return head", "def deleteAlt(head):\n current = head\n previous = None\n while current:\n previous = current\n current = current.next\n if current:\n previous.next = current.next\n current = previous.next", "def deleteAlt(head):\n t = head\n while t != None and t.next != None:\n t.next = t.next.next\n t = t.next\n return head", "def deleteAlt(head):\n while head and head.next:\n head.next = head.next.next\n head = head.next", "def deleteAlt(head):\n temp = head\n c = 1\n while temp:\n if temp.next is not None:\n a = temp.next\n c = c + 1\n if c % 2 == 0:\n temp.next = a.next\n c = 1\n temp = temp.next\n return head", "def deleteAlt(head):\n current = head\n current_next = None\n current_next_next = None\n while current != None:\n try:\n current_next = current.next\n current_next_next = current_next.next\n current.next = current_next_next\n current = current.next\n except:\n return head\n return head", "def deleteAlt(head):\n h = head\n while head and head.next:\n a = head.next.next\n head.next = a\n head = head.next\n return h", "def deleteAlt(head):\n if head == None:\n return\n prev = head\n now = head.next\n while prev != None and now != None:\n prev.next = now.next\n now = None\n prev = prev.next\n if prev != None:\n now = prev.next", "def deleteAlt(head):\n current_node = head\n while current_node is not None and current_node.next is not None:\n current_node.next = current_node.next.next\n current_node = current_node.next", "def deleteAlt(head):\n curr = head\n while curr is not None:\n if curr.next is not None and curr.next is not None:\n curr.next = curr.next.next\n curr = curr.next\n else:\n break", "def deleteAlt(head):\n itr = head\n while itr:\n temp = itr.next\n if temp is not None:\n itr.next = temp.next\n temp = None\n else:\n break\n itr = itr.next", "def deleteAlt(head):\n p = head\n cnt = 0\n prev = p\n while p:\n if cnt % 2:\n q = p.next\n prev.next = q\n prev = p\n p = p.next\n cnt += 1", "def deleteAlt(head):\n curr = head\n while curr and curr.next:\n tmp = curr.next.next\n curr.next = curr.next.next\n curr = tmp", "def deleteAlt(head):\n length = 0\n temp = head\n while temp is not None:\n length += 1\n temp = temp.next\n if length == 1 or length == 2:\n return head.data\n else:\n temp = head\n while temp is not None and temp.next is not None:\n temp.next = temp.next.next\n temp = temp.next\n return head", "def deleteAlt(head):\n temp = head\n prev = None\n count = 1\n while temp:\n if temp.next is None:\n break\n else:\n prev = temp\n temp = temp.next\n if count % 2 != 0:\n prev.next = temp.next\n count += 1", "def deleteAlt(head):\n i = 1\n cur = head\n while cur.next:\n if i % 2 != 0:\n if cur.next.next:\n cur.next = cur.next.next\n cur = cur.next\n i += 2\n else:\n cur.next = None\n return None", "def deleteAlt(head):\n previous = head\n temp = head.next\n while temp:\n previous.next = temp.next\n temp = None\n previous = previous.next\n if previous:\n temp = previous.next", "def deleteAlt(node):\n while node:\n if node.next:\n node.next = node.next.next\n node = node.next", "def deleteAlt(head):\n itr = head\n c = 0\n while itr != None and itr.next != None:\n itr.next = itr.next.next\n itr = itr.next\n return head", "def deleteAlt(head):\n count = 1\n temp = head\n while temp.next != None:\n if temp.next.next == None:\n temp.next = None\n break\n temp.next = temp.next.next\n temp = temp.next\n return head", "def deleteAlt(head):\n curr = head\n while curr is not None:\n if curr.next is None:\n break\n temp = curr.next.next\n curr.next.next = None\n curr.next = temp\n curr = curr.next\n return head", "def deleteAlt(head):\n cur = head\n while cur and cur.next:\n prev = cur.next\n cur.next = prev.next\n cur = cur.next\n return head", "def deleteAlt(head):\n temp = head\n while temp is not None and temp.next is not None:\n temp.next = temp.next.next\n temp = temp.next\n return head", "def deleteAlt(head):\n g = head\n while g != None and g.next != None:\n g.next = g.next.next\n g = g.next\n return g", "def deleteAlt(head):\n cur = head\n while cur.next != None and cur.next.next != None:\n cur.next = cur.next.next\n cur = cur.next\n cur.next = None\n return cur", "def deleteAlt(head):\n dup = head\n while head and head.next:\n head.next = head.next.next\n head = head.next\n return dup", "def deleteAlt(head):\n temp = head\n j = 0\n while temp.next:\n if (j + 1) % 2:\n temp.next = temp.next.next\n else:\n temp = temp.next\n j += 1\n return head", "def deleteAlt(head):\n if not head:\n return\n fast = head.next\n slow = head\n while fast and slow:\n slow.next = fast.next\n fast = None\n slow = slow.next\n if slow:\n fast = slow.next"], "starter_code": "def __init__(data):\n", "input_output": {"inputs": ["LinkedList:1->2->3->4->5->6", "LinkedList:99->59->42->20"], "outputs": ["1->3->5", "99->42"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Linked List"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/delete-alternate-nodes/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "__init__", "task_id": "TACO_lite/446", "example": [[], []]} +{"requirement": "In this Kata, you will be given directions and your task will be to find your way back. \n```Perl\nsolve([\"Begin on Road A\",\"Right on Road B\",\"Right on Road C\",\"Left on Road D\"]) = ['Begin on Road D', 'Right on Road C', 'Left on Road B', 'Left on Road A']\nsolve(['Begin on Lua Pkwy', 'Right on Sixth Alley', 'Right on 1st Cr']) = ['Begin on 1st Cr', 'Left on Sixth Alley', 'Left on Lua Pkwy']\n```\n\nMore examples in test cases. \n\nGood luck!\n\nPlease also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)", "solutions": ["DIRS = {'Left': 'Right', 'Right': 'Left'}\n\ndef solve(arr):\n (lst, prevDir) = ([], 'Begin')\n for cmd in arr[::-1]:\n (d, r) = cmd.split(' on ')\n follow = DIRS.get(prevDir, prevDir)\n prevDir = d\n lst.append(f'{follow} on {r}')\n return lst", "def solve(arr):\n (go_moves, go_places) = list(zip(*(s.split(' ', 1) for s in arr)))\n back_moves = ['Begin'] + ['Right' if s == 'Left' else 'Left' for s in go_moves[:0:-1]]\n return [' '.join(z) for z in zip(back_moves, go_places[::-1])]", "def solve(arr):\n (lst, prevDir) = ([], None)\n for cmd in arr[::-1]:\n (d, r) = cmd.split(' on ')\n if not lst:\n lst.append(f'Begin on {r}')\n else:\n lst.append(f\"{('Left' if prevDir == 'Right' else 'Right')} on {r}\")\n prevDir = d\n return lst", "from collections import deque\n\ndef solve(arr):\n flip = {'Left': 'Right', 'Right': 'Left'}\n directions = deque([flip.get(s, s) for s in [s.split()[0] for s in arr]])\n directions.reverse()\n directions.rotate(1)\n streets = [' '.join(s.split()[1:]) for s in arr][::-1]\n return [f'{direction} {street}' for (direction, street) in zip(directions, streets)]", "def solve(arr):\n route = [road.split() for road in arr]\n (l, re) = (len(arr), [])\n dir = {'Left': 'Right', 'Right': 'Left', 'Begin': 'Begin'}\n for i in range(l):\n re.insert(0, ' '.join([dir[route[(i + 1) % l][0]]] + route[i][1:]))\n return re", "def solve(directions):\n (positions, turns) = ([], [])\n for d in directions[::-1]:\n (t, p) = d.split(' on ')\n turns.append('Right' if t == 'Left' else 'Left')\n positions.append(p)\n result = [f'{t} on {p}' for (t, p) in zip(turns, positions[1:])]\n return [f'Begin on {positions[0]}'] + result", "def solve(arr):\n rev = list(reversed(arr))\n go = []\n direction = 'Begin'\n for i in rev:\n nextdirection = i.split(' ')[0]\n go.append(i.replace(nextdirection, direction))\n if nextdirection == 'Left':\n direction = 'Right'\n else:\n direction = 'Left'\n return go", "def solve(a):\n (ans, last) = ([], len(a) - 1)\n for (i, x) in enumerate(a):\n s = 'Begin' if i == last else 'Right' if a[i + 1][0] == 'L' else 'Left'\n ans.insert(0, s + x[x.index(' '):])\n return ans", "solve = lambda arr: list(reversed([{'Right': 'Left', 'Left': 'Right'}[arr[i + 1].split(' ')[0]] + ' ' + ' '.join(arr[i].split(' ')[1:]) if i < len(arr) - 1 else 'Begin ' + ' '.join(arr[i].split(' ')[1:]) for i in range(len(arr))]))"], "starter_code": "def solve(arr):\n", "input_output": {"fn_name": "solve", "inputs": [[["Begin on 3rd Blvd", "Right on First Road", "Left on 9th Dr"]], [["Begin on Road A", "Right on Road B", "Right on Road C", "Left on Road D"]], [["Begin on Road A"]]], "outputs": [[["Begin on 9th Dr", "Right on First Road", "Left on 3rd Blvd"]], [["Begin on Road D", "Right on Road C", "Left on Road B", "Left on Road A"]], [["Begin on Road A"]]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5b94d7eb1d5ed297680000ca", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/310", "example": [[[["Begin on Road A", "Right on Road B", "Right on Road C", "Left on Road D"]], [["Begin on Lua Pkwy", "Right on Sixth Alley", "Right on 1st Cr"]]], ["['Begin on Road D', 'Right on Road C', 'Left on Road B', 'Left on Road A']", "['Begin on 1st Cr', 'Left on Sixth Alley', 'Left on Lua Pkwy']"]]} +{"requirement": "The gray code is a binary numeral system where two successive values differ in only one bit.\n\nGiven a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.\n\nExample 1:\n\n\nInput: 2\nOutput: [0,1,3,2]\nExplanation:\n00 - 0\n01 - 1\n11 - 3\n10 - 2\n\nFor a given n, a gray code sequence may not be uniquely defined.\nFor example, [0,2,3,1] is also a valid gray code sequence.\n\n00 - 0\n10 - 2\n11 - 3\n01 - 1\n\n\nExample 2:\n\n\nInput: 0\nOutput: [0]\nExplanation: We define the gray code sequence to begin with 0.\n  A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.\n  Therefore, for n = 0 the gray code sequence is [0].", "solutions": ["def graycode(n):\n res = []\n for i in range(1 << n):\n res.append(i ^ i >> 1)\n return res", "def graycode(n):\n result = [0, 1]\n if n <= 1:\n return result[:n + 1]\n res_len = 2 ** n\n cnt = 1\n while len(result) != res_len:\n cnt *= 2\n result.extend(result[::-1])\n start = len(result) // 2\n for i in range(start, len(result)):\n result[i] += cnt\n return result", "def graycode(n):\n if n == 0:\n return [0]\n concat = ''\n res = [0, 1]\n for i in range(1, n):\n newRes = []\n for j in res:\n newRes.append(j)\n for j in reversed(res):\n newRes.append(j + 2 ** i)\n res = newRes\n return res", "def graycode(n):\n if n == 0:\n return [0]\n result = [0, 1]\n for i in range(2, n + 1):\n mask = 1 << i - 1\n temp = []\n for j in range(len(result)):\n temp.append(result[-j - 1] | mask)\n result += temp\n return result", "def helper(n):\n if n == 0:\n return ['0']\n if n == 1:\n return ['0', '1']\n ret = []\n for code in self.helper(n - 1):\n ret.append('0' + code)\n for code in reversed(self.helper(n - 1)):\n ret.append('1' + code)\n return ret\n\ndef graycode(n):\n if n == 0:\n return [0]\n ret = []\n code = self.graycode(n - 1)\n ret += code\n for v in reversed(code):\n ret.append(2 ** (n - 1) + v)\n return ret", "def graycode(n):\n result = [0]\n for i in range(n):\n temp = []\n for num in result:\n temp.append(num + 2 ** i)\n result += temp[::-1]\n return result", "def graycode(n):\n if n == 0:\n return [0]\n q = [0, -1]\n for i in range(n):\n tag = 0\n while q[0] != -1:\n item = q.pop(0)\n q.append(item * 2 + tag)\n q.append(item * 2 + (1 - tag))\n tag = 1 - tag\n q.pop(0)\n q.append(-1)\n q.pop(-1)\n return q", "def graycode(n):\n if n < 0:\n return []\n elif n == 0:\n return [0]\n elif n == 1:\n return [0, 1]\n result = [0, 1]\n res_len = 2 ** n\n cnt = 1\n while len(result) != res_len:\n cnt *= 2\n result.extend(result[::-1])\n offset = 0\n for i in range(len(result)):\n if i > 0 and i % cnt == 0:\n offset = cnt\n result[i] += offset\n return result", "def graycode(n):\n ans = [0]\n mask = 1\n for l in range(n):\n for c in ans[::-1]:\n ans.append(mask | c)\n mask <<= 1\n return ans"], "starter_code": "def graycode(n: int) -> List[int]:\n", "input_output": {"fn_name": "grayCode", "inputs": [[2], [1]], "outputs": [[0, 1, 3, 2], [0, 1]]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Math", "Backtracking", "Bit Manipulation"], "name": null, "source": "leetcode", "tags": ["Bit manipulation", "Mathematics", "Complete search"], "skill_types": ["Bit manipulation", "Complete search"], "url": "https://leetcode.com/problems/gray-code/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "graycode", "task_id": "TACO_lite/462", "example": [[[2], [0]], ["[0, 1, 3, 2]", "[0]"]]} +{"requirement": "Given an array arr[] of size N and an integer K, the task is to left rotate the array K indexes\nExample 1:\nInput: N = 7, K = 2\narr[] = {1, 2, 3, 4, 5, 6, 7}\nOutput: 3 4 5 6 7 1 2\nExplanation: Rotation of the above \narray by 2 will make the output array .\nExample 2: \nInput: N = 6, K = 12\narr[] = {1, 2, 3, 4, 5, 6}\nOutput: 1 2 3 4 5 6\nYour Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function leftRotate() that takes array arr, integer K and integer N as parameters and rotate the given array by k value. You have to rotate array even the k is greater than n. In these case after every n rotation array comes same as the original array.\n \nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\n \nConstraints:\n1 ≤ N ≤ 10^{5\n}1 ≤ K ≤ 10^{5\n}-100 ≤ arr[i] ≤ 100", "solutions": ["def leftrotate(arr, d, n):\n d = d % n\n self.reverse(arr, 0, d - 1)\n self.reverse(arr, d, n - 1)\n self.reverse(arr, 0, n - 1)\n\ndef reverse(arr, left, right):\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1", "def leftrotate(arr, k, n):\n if k > n:\n k = k % n\n if k > 0:\n start = 0\n self.reverse(arr, 0, k - 1)\n self.reverse(arr, k, n - 1)\n self.reverse(arr, 0, n - 1)\n\ndef reverse(arr, start, end):\n while start < end:\n (arr[start], arr[end]) = (arr[end], arr[start])\n start += 1\n end -= 1", "def leftrotate(arr, k, n):\n k %= n\n arr[:] = arr[k:] + arr[:k]\n return arr", "def leftrotate(arr, k, n):\n if k > n:\n k = k % n\n if k > 0:\n temp = arr[:k]\n for i in range(k, n):\n arr[i - k] = arr[i]\n for i in range(len(temp)):\n arr[n - k + i] = temp[i]", "def leftrotate(arr, k, n):\n if k > n:\n d = k % n\n elif k <= n:\n d = k\n\n def reverse(arr, first, last):\n while first < last:\n (arr[first], arr[last]) = (arr[last], arr[first])\n first += 1\n last -= 1\n if d == 0:\n return arr\n else:\n reverse(arr, 0, d - 1)\n reverse(arr, d, n - 1)\n reverse(arr, 0, n - 1)\n return arr", "def leftrotate(arr, k, n):\n\n def gcd(a, b):\n if b == 0:\n return a\n return gcd(b, a % b)\n k = k % n\n p = gcd(k, n)\n if k == 0:\n return\n for i in range(p):\n tmp = arr[i]\n j = i\n while 1:\n c = j + k\n c %= n\n if c == i:\n break\n arr[j] = arr[c]\n j = c\n arr[j] = tmp", "def leftrotate(arr, k, n):\n a = k % n\n l = arr[a:]\n l1 = arr[:a]\n j = 0\n for i in l:\n arr[j] = i\n j += 1\n for m in l1:\n arr[j] = m\n j += 1\n return arr", "def leftrotate(arr, k, n):\n k = k % len(arr)\n if k > 0:\n arr[:] = arr[k:] + arr[:k]", "def leftrotate(arr, d, n):\n d = d % n\n l = 0\n r = n - 1\n while l <= r:\n (arr[l], arr[r]) = (arr[r], arr[l])\n l += 1\n r -= 1\n l = n - d\n r = n - 1\n while l <= r:\n (arr[l], arr[r]) = (arr[r], arr[l])\n l += 1\n r -= 1\n l = 0\n r = n - 1 - d\n while l <= r:\n (arr[l], arr[r]) = (arr[r], arr[l])\n l += 1\n r -= 1\n return arr", "def leftrotate(arr, k, n):\n k = k % n\n (i, m) = (0, k - 1)\n while i < m:\n temp = arr[i]\n arr[i] = arr[m]\n arr[m] = temp\n i = i + 1\n m = m - 1\n x = n - 1\n while k < x:\n temp = arr[k]\n arr[k] = arr[x]\n arr[x] = temp\n k = k + 1\n x = x - 1\n i = 0\n j = n - 1\n while i < j:\n temp = arr[i]\n arr[i] = arr[j]\n arr[j] = temp\n i = i + 1\n j = j - 1\n return arr", "def reverseArray(arr, start, end):\n while start < end:\n temp = arr[start]\n arr[start] = arr[end]\n arr[end] = temp\n start += 1\n end = end - 1\n\ndef leftrotate(arr, d, n):\n if d == 0:\n return\n d = d % n\n self.reverseArray(arr, 0, d - 1)\n self.reverseArray(arr, d, n - 1)\n self.reverseArray(arr, 0, n - 1)", "def leftrotate(arr, k, n):\n if k > n:\n k = k % n\n ans = []\n for x in arr[k:]:\n ans.append(x)\n for x in arr[:k]:\n ans.append(x)\n i = 0\n while i < n:\n arr[i] = ans[i]\n i += 1\n return ans", "def leftrotate(arr, k, n):\n i = 0\n j = n - 1\n k = k % n\n while i < j:\n (arr[i], arr[j]) = (arr[j], arr[i])\n i += 1\n j -= 1\n i = 0\n j = n - k - 1\n while i < j:\n (arr[i], arr[j]) = (arr[j], arr[i])\n i += 1\n j -= 1\n i = n - k\n j = n - 1\n while i < j:\n (arr[i], arr[j]) = (arr[j], arr[i])\n i += 1\n j -= 1\n return arr", "def leftrotate(arr, k, n):\n a = []\n if k > n:\n k = k % n\n for i in range(k):\n a.append(arr[i])\n for i in range(k, n):\n arr[i - k] = arr[i]\n z = 0\n for i in range(n - k, n):\n arr[i] = a[z]\n z += 1\n return arr", "def leftrotate(arr, k, n):\n if k % n:\n k = k % n\n helper = arr[:k + 1]\n for i in range(0, n - k):\n arr[i] = arr[i + k]\n for i in range(0, k):\n arr[i + n - k] = helper[i]", "def leftrotate(arr, k, n):\n if k > n:\n k = n - k % n\n b = arr[n - k:n] + arr[0:n - k + 1]\n arr[0:n] = b[0:n]\n return arr\n b = arr[k:n] + arr[0:k]\n arr[0:n] = b[0:n]\n return", "def leftrotate(arr, k, n):\n k = k % n\n for i in range(k):\n arr.append(arr.pop(0))", "def reverse(A, b, e):\n while b < e:\n (A[b], A[e]) = (A[e], A[b])\n b += 1\n e -= 1\n\ndef leftrotate(A, d, N):\n while d > N:\n d = d - N\n self.reverse(A, 0, d - 1)\n self.reverse(A, d, N - 1)\n self.reverse(A, 0, N - 1)", "def reverse(arr, i, j):\n if i > j:\n (i, j) = (j, i)\n section = arr[i:j + 1]\n section.reverse()\n arr[i:j + 1] = section\n\ndef leftrotate(arr, k, n):\n if k > n:\n k = k % n\n arr[:] = arr[::-1]\n self.reverse(arr, 0, n - k - 1)\n self.reverse(arr, n - k, n)", "def leftrotate(arr, k, n):\n if k > n:\n k = k % n\n a = []\n for i in range(k, n):\n a.append(arr[i])\n for i in range(0, k):\n a.append(arr[i])\n for i in range(0, n):\n arr[i] = a[i]", "def leftrotate(arr, k, n):\n l = []\n if n > k:\n r = k\n else:\n r = k % n\n for i in range(r, n):\n l.append(arr[i])\n for i in range(0, r):\n l.append(arr[i])\n for i in range(0, n):\n arr[i] = l[i]", "def leftrotate(arr, k, n):\n k = k % n\n dupli = arr[:k]\n for i in range(k, n):\n arr[i - k] = arr[i]\n for i in range(n - k, n):\n arr[i] = dupli[i - n + k]\n return arr", "def leftrotate(arr, k, n):\n k = k % n\n\n def swap(arr, l, e):\n while l < e:\n (arr[l], arr[e]) = (arr[e], arr[l])\n l += 1\n e -= 1\n swap(arr, 0, k - 1)\n swap(arr, k, n - 1)\n swap(arr, 0, n - 1)", "def leftrotate(arr, k, n):\n k = k % n\n t = arr[k:] + arr[:k]\n for i in range(n):\n arr[i] = t[i]", "def leftrotate(arr, k, n):\n k = k % n\n if k == 0:\n return arr\n count = 0\n for i in range(n):\n src_index = i\n src_elem = arr[i]\n while True:\n dest_index = src_index - k\n if dest_index < 0:\n dest_index += n\n temp = arr[dest_index]\n arr[dest_index] = src_elem\n src_elem = temp\n src_index = dest_index\n count += 1\n if dest_index == i:\n break\n if count == n:\n return arr\n return arr", "def leftrotate(arr, k, n):\n j = 0\n k = k % n\n temp = arr[:k]\n for i in range(k, n):\n arr[j] = arr[i]\n j += 1\n for i in range(len(temp)):\n arr[j] = temp[i]\n j += 1\n return arr", "def leftrotate(arr, k, n):\n k = k % n\n arr[0:k] = reversed(arr[0:k])\n arr[k:n] = reversed(arr[k:n])\n arr[0:n] = reversed(arr[0:n])", "def leftrotate(arr, k, n):\n\n def solve(l, h):\n while l < h:\n (arr[l], arr[h]) = (arr[h], arr[l])\n l += 1\n h -= 1\n k = k % n\n solve(0, n - 1)\n solve(0, n - k - 1)\n solve(n - k, n - 1)", "def leftrotate(arr, k, n):\n k = k % n\n x = arr[k:] + arr[:k]\n for i in range(0, n):\n arr[i] = x[i]\n return arr", "def reverse(arr, i, j):\n while i < j:\n temp = arr[i]\n arr[i] = arr[j]\n arr[j] = temp\n i += 1\n j -= 1\n\ndef leftrotate(arr, k, n):\n k = k % n\n self.reverse(arr, 0, k - 1)\n self.reverse(arr, k, n - 1)\n self.reverse(arr, 0, n - 1)", "def leftrotate(arr, k, n):\n\n def reverse(arr, l, r):\n while l <= r:\n (arr[l], arr[r]) = (arr[r], arr[l])\n l += 1\n r -= 1\n k = k % n\n reverse(arr, 0, k - 1)\n reverse(arr, k, n - 1)\n reverse(arr, 0, n - 1)\n return arr", "def reverse(arr, s, e):\n while s < e:\n (arr[s], arr[e - 1]) = (arr[e - 1], arr[s])\n s += 1\n e -= 1\n\ndef leftrotate(arr, k, n):\n k = k % n\n self.reverse(arr, 0, n)\n self.reverse(arr, 0, n - k)\n self.reverse(arr, n - k, n)", "def leftrotate(arr, k, n):\n if k == len(arr):\n return arr\n if k > len(arr):\n k = k % len(arr)\n arr[0:k] = reversed(arr[0:k])\n arr[k:len(arr)] = reversed(arr[k:len(arr)])\n arr.reverse()\n return arr", "def leftrotate(arr, k, n):\n idx = 0\n if k > n:\n k = k % n\n while k > 0:\n val = arr.pop(idx)\n arr.append(val)\n k -= 1\n return arr", "def leftrotate(arr, k, n):\n if k > n:\n k = k % n\n l_arr = arr[k:]\n r_arr = arr[:k]\n arr[:] = l_arr + r_arr", "def leftrotate(arr, k, n):\n start = k % n\n j = 0\n x = arr[:start]\n for i in range(start, n):\n arr[j] = arr[i]\n j = j + 1\n z = 0\n for i in range(j, n):\n arr[i] = x[z]\n z = z + 1", "def leftrotate(arr, k, n):\n ans = [None] * len(arr)\n for i in range(len(arr)):\n ans[(i - k) % n] = arr[i]\n for i in range(n):\n arr[i] = ans[i]", "def leftrotate(arr, k, n):\n k = k % len(arr)\n arr[:] = arr[k:] + arr[:k]", "def leftrotate(arr, k, n):\n k = k % n\n temp = []\n for i in range(0, k):\n temp.append(arr[i])\n for i in range(k, n):\n arr[i - k] = arr[i]\n for i in range(n - k, n):\n arr[i] = temp[i - (n - k)]\n return arr", "def leftrotate(arr, k, n):\n k = k % n\n tmp = arr[:k]\n for i in range(n - k):\n arr[i] = arr[i + k]\n for i in range(len(tmp)):\n arr[n + i - k] = tmp[i]", "def leftrotate(arr, k, n):\n copyArr = [0] * n\n for i in range(n):\n newI = (i - k) % n\n copyArr[newI] = arr[i]\n for i in range(n):\n arr[i] = copyArr[i]", "def leftrotate(arr, k, n):\n\n def reverse(left, right):\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1\n k %= n\n size = n - 1\n reverse(0, size)\n reverse(0, size - k)\n reverse(n - k, size)\n return arr", "def leftrotate(arr, k, n):\n k = k % n\n if k == 0 or k == n:\n return arr\n self.swap(arr, 0, k - 1)\n self.swap(arr, k, n - 1)\n self.swap(arr, 0, n - 1)\n\ndef swap(arr, l, r):\n while l < r:\n (arr[l], arr[r]) = (arr[r], arr[l])\n l += 1\n r -= 1", "def leftrotate(arr, k, n):\n\n def reverseArray(arr, start, end):\n while start < end:\n temp = arr[start]\n arr[start] = arr[end]\n arr[end] = temp\n start += 1\n end -= 1\n return arr\n k = k % n\n arr = reverseArray(arr, 0, k - 1)\n arr = reverseArray(arr, k, len(arr) - 1)\n arr = reverseArray(arr, 0, len(arr) - 1)\n return arr", "def leftrotate(arr, k, n):\n k = k % n\n m = []\n for i in range(k):\n m.append(arr[i])\n for i in range(k, n):\n arr[i - k] = arr[i]\n for i in range(k):\n arr[n + i - k] = m[i]\n return arr", "def leftrotate(arr, k, n):\n k = k % n\n arr1 = arr[k:n]\n arr2 = arr[0:k]\n arr[0:n - k] = arr1\n arr[n - k:] = arr2\n return arr", "def leftrotate(arr, k, n):\n if n <= 1:\n return arr\n if k < n:\n for _ in range(-n, -(n - k)):\n ele = arr[0]\n ele_shift = arr[1]\n arr.remove(ele)\n arr.append(ele)\n return arr\n else:\n shift = k % n\n for _ in range(-n, -(n - shift)):\n ele = arr[0]\n ele_shift = arr[1]\n arr.remove(ele)\n arr.append(ele)\n return arr", "def gcd(a, b):\n if b == 0:\n return a\n return self.gcd(b, a % b)\n\ndef leftrotate(arr, k, n):\n k %= n\n if k == 0:\n return\n g = self.gcd(n, k)\n for i in range(g):\n t = arr[i]\n j = i\n for _ in range(n // g - 1):\n arr[j] = arr[(j + k) % n]\n j = (j + k) % n\n arr[j] = t", "def leftrotate(arr, k, n):\n rotate = k % n\n first = arr[rotate:]\n second = arr[:rotate]\n result = first + second\n for i in range(n):\n arr[i] = result[i]\n return arr", "def leftrotate(arr, k, n):\n rotate = k % n\n arr[rotate:] = reversed(arr[rotate:])\n arr[:rotate] = reversed(arr[:rotate])\n arr[:] = reversed(arr[:])\n return arr", "def leftrotate(arr, k, n):\n rotate = k % n\n arr[:] = arr[rotate:] + arr[0:rotate]\n return arr", "def leftrotate(arr, k, n):\n n = k % len(arr)\n arr[:n] = reversed(arr[:n])\n arr[n:] = reversed(arr[n:])\n arr[:] = reversed(arr[:])\n return arr", "def leftrotate(arr, k, n):\n dum_arr = [0 for _ in range(n)]\n j = 0\n k = k % n\n for i in range(k, n):\n dum_arr[j] = arr[i]\n j += 1\n for i in range(0, k):\n dum_arr[j] = arr[i]\n j += 1\n for i in range(0, n):\n arr[i] = dum_arr[i]", "def rev(arr, st, end):\n while st < end:\n (arr[st], arr[end]) = (arr[end], arr[st])\n st += 1\n end -= 1\n\ndef leftrotate(arr, k, n):\n k = k % n\n self.rev(arr, 0, k - 1)\n self.rev(arr, k, n - 1)\n self.rev(arr, 0, n - 1)", "def leftrotate(arr, k, n):\n if k == 0 or (k >= n and k % n == 0):\n return\n popped = 0\n index = 0\n rotation_count = k % n\n while rotation_count > 0:\n popped = arr.pop(index)\n arr.append(popped)\n rotation_count = rotation_count - 1", "def leftrotate(arr, k, n):\n k = k % n\n a = arr[:k]\n for i in range(n - k):\n arr[i] = arr[i + k]\n i = 0\n for j in range(n - k, n):\n arr[j] = a[i]\n i = i + 1"], "starter_code": "def leftrotate(arr, k, n):\n", "input_output": {"inputs": ["N = 7, K = 2\narr[] = {1, 2, 3, 4, 5, 6, 7}", "N = 6, K = 12\narr[] = {1, 2, 3, 4, 5, 6}"], "outputs": ["3 4 5 6 7 1 2", "1 2 3 4 5 6"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/quick-left-rotation3806/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "leftrotate", "task_id": "TACO_lite/413", "example": [[[7, 2, [1, 2, 3, 4, 5, 6, 7]], [6, 12, [1, 2, 3, 4, 5, 6]]], ["[3, 4, 5, 6, 7, 1, 2]", "[1, 2, 3, 4, 5, 6]"]]} +{"requirement": "Given an array of numbers of size N. It is also given that the array elements are in range from 0 to N^{2} – 1. Sort the given array in linear time.\nExample 1:\nInput:\nN = 7\narr[] = {40, 12, 45, 32, 33, 1, 22}\nOutput: 1 12 22 32 33 40 45\nExplanation: Output is the sorted version of the\ngiven array.\n​Example 2:\nInput: \nN = 5\narr[] = {24, 12, 0, 15, 8}\nOutput: 0 8 12 15 24\nExplanation: Output is the sorted version of the\ngiven array.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function sort () which takes an array arr[] and its size N as inputs and sorts the array in non-decreasing order. \nNote: You have to modify the input array such that it becomes sorted in non-decreasing order.\nExpected Time Complexity: O(N). \nExpected Auxiliary Space: O(N).\nConstraints:\n1 <= N <= 10^4", "solutions": ["def sort(arr, n):\n arr.sort()", "def countSort(arr, n, e):\n ans = [0] * n\n count = [0] * n\n for a in arr:\n count[a // e % n] += 1\n for i in range(1, n):\n count[i] += count[i - 1]\n for i in range(n - 1, -1, -1):\n ans[count[arr[i] // e % n] - 1] = arr[i]\n count[arr[i] // e % n] -= 1\n for i in range(n):\n arr[i] = ans[i]\n\ndef sort(arr, n):\n self.countSort(arr, n, 1)\n self.countSort(arr, n, n)", "def sort(arr, n):\n c = arr.sort()\n return c", "def sort(arr, n):\n s = arr.sort()\n return s", "def radix(arr, n, p):\n ans = [0] * n\n cnt = [0] * n\n for i in range(n):\n dx = arr[i] // n ** p % n\n cnt[dx] += 1\n for i in range(1, n):\n cnt[i] += cnt[i - 1]\n for i in range(n - 1, -1, -1):\n dx = arr[i] // n ** p % n\n ans[cnt[dx] - 1] = arr[i]\n cnt[dx] -= 1\n for i in range(n):\n arr[i] = ans[i]\n\ndef sort(arr, n):\n index = len(str(max(arr)))\n for p in range(2):\n self.radix(arr, n, p)", "def sort(arr, n):\n maxm = max(arr)\n exp = 1\n while maxm // exp > 0:\n output = [0] * n\n count = [0] * 10\n for i in range(n):\n idx = arr[i] // exp\n count[idx % 10] += 1\n for i in range(1, 10):\n count[i] += count[i - 1]\n for i in range(n - 1, -1, -1):\n idx = arr[i] // exp\n output[count[idx % 10] - 1] = arr[i]\n count[idx % 10] -= 1\n for i in range(n):\n arr[i] = output[i]\n exp *= 10\n return arr", "def sort(T, n):\n counts = [0 for _ in range(n)]\n output = [0 for _ in range(n)]\n for i in range(n):\n counts[T[i] % n] += 1\n for i in range(1, n):\n counts[i] += counts[i - 1]\n for i in range(n - 1, -1, -1):\n counts[T[i] % n] -= 1\n output[counts[T[i] % n]] = T[i]\n for i in range(n):\n T[i] = output[i]\n counts = [0 for _ in range(n)]\n output = [0 for _ in range(n)]\n for i in range(n):\n counts[T[i] // n] += 1\n for i in range(1, n):\n counts[i] += counts[i - 1]\n for i in range(n - 1, -1, -1):\n counts[T[i] // n] -= 1\n output[counts[T[i] // n]] = T[i]\n for i in range(n):\n T[i] = output[i]", "def sort(arr, n):\n arr1 = arr[:]\n ma = max(arr1)\n k = 0\n while ma != 0:\n k += 1\n ma = ma // 10\n li = [[] for i in range(10)]\n k1 = 1\n while k1 <= k:\n for i in arr1:\n li[i % pow(10, k1) // max(1, pow(10, k1 - 1))].append(i)\n arr1 = []\n for i in li:\n arr1.extend(i)\n li = [[] for i in range(10)]\n k1 += 1\n for i in range(n):\n arr[i] = arr1[i]", "def sort(arr, n):\n aux = [0] * n\n count = [0] * n\n for i in range(n):\n count[arr[i] % n] += 1\n for i in range(1, n):\n count[i] += count[i - 1]\n for i in range(n - 1, -1, -1):\n aux[count[arr[i] % n] - 1] = arr[i]\n count[arr[i] % n] -= 1\n for i in range(n):\n arr[i] = aux[i]\n count[i] = 0\n for i in range(n):\n count[arr[i] // n % n] += 1\n for i in range(1, n):\n count[i] += count[i - 1]\n for i in range(n - 1, -1, -1):\n aux[count[arr[i] // n % n] - 1] = arr[i]\n count[arr[i] // n % n] -= 1\n for i in range(n):\n arr[i] = aux[i]", "def radixsort(arr, n, exp):\n output = [0] * n\n count = [0] * n\n for i in range(n):\n count[arr[i] // exp % n] += 1\n for i in range(1, n):\n count[i] += count[i - 1]\n for i in range(n - 1, -1, -1):\n output[count[arr[i] // exp % n] - 1] = arr[i]\n count[arr[i] // exp % n] -= 1\n for i in range(n):\n arr[i] = output[i]\n\ndef sort(arr, n):\n self.radixsort(arr, n, 1)\n self.radixsort(arr, n, n)\n return arr", "def sort(arr, n):\n\n def countSort(arr, exp):\n newArr = [[] for i in range(10)]\n for i in range(len(arr)):\n newArr[arr[i] // exp % 10].append(arr[i])\n j = 0\n for i in newArr:\n for k in i:\n arr[j] = k\n j += 1\n return arr\n maxLen = len(str(n ** 2))\n for i in range(maxLen):\n exp = 10 ** i\n countSort(arr, exp)\n return arr", "def sort(arr, n):\n B = n\n for j in range(2):\n freq = [0] * n\n for i in range(n):\n num_digit = arr[i] // B ** j % B\n freq[num_digit] += 1\n k = 1\n while k < B:\n freq[k] += freq[k - 1]\n k += 1\n arr_copy = arr.copy()\n for i in range(n - 1, -1, -1):\n num_digit = arr_copy[i] // B ** j % B\n arr[freq[num_digit] - 1] = arr_copy[i]\n freq[num_digit] -= 1\n return arr", "def counting(n, arr, div):\n count = [0] * n\n output = [0] * n\n for i in arr:\n count[i // div % n] += 1\n for j in range(1, n):\n count[j] += count[j - 1]\n for k in range(n - 1, -1, -1):\n output[count[arr[k] // div % n] - 1] = arr[k]\n count[arr[k] // div % n] -= 1\n for i in range(n):\n arr[i] = output[i]\n\ndef sort(arr, n):\n self.counting(n, arr, 1)\n self.counting(n, arr, n)", "def sort(arr, n):\n if len(arr) > 1:\n m = len(arr) // 2\n l = arr[:m]\n r = arr[m:]\n self.sort(l, len(l))\n self.sort(r, len(r))\n i = j = k = 0\n while i < len(l) and j < len(r):\n if l[i] < r[j]:\n arr[k] = l[i]\n i = i + 1\n else:\n arr[k] = r[j]\n j = j + 1\n k = k + 1\n while i < len(l):\n arr[k] = l[i]\n i = i + 1\n k = k + 1\n while j < len(r):\n arr[k] = r[j]\n j = j + 1\n k = k + 1", "import numpy as np\n\ndef count_sort(arr, n, exp):\n idxs = np.zeros((n,), dtype=int)\n output_arr = np.zeros((n,), dtype=int)\n for i in range(len(arr)):\n idxs[int(arr[i] // exp % n)] += 1\n i = 1\n while i < n:\n idxs[i] += idxs[i - 1]\n i += 1\n i = n - 1\n while i >= 0:\n output_arr[idxs[int(arr[i] / exp % n)] - 1] = arr[i]\n idxs[int(arr[i] / exp % n)] -= 1\n i -= 1\n for i in range(n):\n arr[i] = output_arr[i]\n\ndef sort(arr, n):\n self.count_sort(arr, n, 1)\n self.count_sort(arr, n, n)", "from queue import PriorityQueue\n\ndef sort(arr, n):\n q = PriorityQueue(n)\n for i in range(n):\n q.put(arr[i])\n i = 0\n while q.empty() == False:\n arr[i] = q.get()\n i += 1\n return arr", "def sort(arr, n):\n arr.sort()\n return\n f = [0 for i in range(n * n)]\n for i in range(n):\n f[arr[i]] += 1\n k = 0\n for i in range(n * n):\n if f[i] != 0:\n for j in range(f[i]):\n arr[k] = i\n k += 1\n return arr", "def countSort(arr, j):\n n = len(arr)\n B = [0] * n\n C = [0] * n\n for i in range(n):\n C[arr[i][j]] += 1\n for i in range(1, n):\n C[i] += C[i - 1]\n for i in range(n - 1, -1, -1):\n C[arr[i][j]] -= 1\n B[C[arr[i][j]]] = arr[i]\n for i in range(n):\n arr[i] = B[i]\n\ndef preprocessing(arr):\n n = len(arr)\n for i in range(n):\n a = arr[i] // n\n b = arr[i] % n\n arr[i] = (a, b)\n return arr\n\ndef sort(arr, n):\n arr = self.preprocessing(arr)\n self.countSort(arr, 1)\n self.countSort(arr, 0)\n for i in range(n):\n arr[i] = arr[i][0] * n + arr[i][1]\n return arr", "def sort(arr1, n):\n global arr\n arr = sorted(arr1)", "def sort(arr, n):\n if n <= 1:\n return arr\n bucket = [[] for _ in range(n // 2)]\n mx = n * n\n for i in range(n):\n bi = n // 2 * arr[i] // mx\n bucket[bi].append(arr[i])\n for i in range(n // 2):\n bucket[i].sort()\n index = 0\n for i in bucket:\n for j in i:\n arr[index] = j\n index += 1", "def sort(arr, n):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n while j >= 0 and key < arr[j]:\n arr[j + 1] = arr[j]\n j -= 1\n arr[j + 1] = key", "def sort(arr, n):\n base = n\n max_elem = n ** 2 - 1\n freq = [0] * base\n ans = [0] * n\n digits = 0\n count = 0\n while max_elem > 0:\n count += 1\n max_elem /= base\n exponent = 0\n while exponent < count:\n for i in range(0, n):\n freq[arr[i] // base ** exponent % base] += 1\n for i in range(1, base):\n freq[i] += freq[i - 1]\n for i in range(N - 1, -1, -1):\n ans[freq[arr[i] // base ** exponent % base] - 1] = arr[i]\n freq[arr[i] // base ** exponent % base] -= 1\n for i in range(0, n):\n arr[i] = ans[i]\n for i in range(0, base):\n freq[i] = 0\n exponent += 1\n return arr", "def RadixSort(arr, n, digit, count, Aux):\n for i in range(n):\n count[arr[i] // digit % n] += 1\n for i in range(1, n):\n count[i] += count[i - 1]\n for i in range(n - 1, -1, -1):\n Aux[count[arr[i] // digit % n] - 1] = arr[i]\n count[arr[i] // digit % n] -= 1\n for i in range(n):\n arr[i] = Aux[i]\n count[i] = 0\n return\n\ndef sort(arr, n):\n count = [0] * n\n Aux = [0] * n\n self.RadixSort(arr, n, 1, count, Aux)\n self.RadixSort(arr, n, n, count, Aux)\n return", "def sort(arr, n):\n self.quicksort(arr, 0, n - 1)\n return arr\n\ndef quicksort(arr, l, r):\n if l >= r:\n return\n p = self.partition(arr, l, r)\n self.quicksort(arr, l, p - 1)\n self.quicksort(arr, p + 1, r)\n\ndef partition(arr, l, r):\n p = arr[r]\n j = l\n for i in range(l, r + 1):\n if arr[i] <= p:\n (arr[i], arr[j]) = (arr[j], arr[i])\n j += 1\n return j - 1", "def sort(arr, n):\n z = sorted(arr)\n arr.clear()\n arr += z", "def no_of_digit(n):\n s = n\n count = 0\n while s > 0:\n s = s // 10\n count += 1\n return count\n\ndef nth_digit(no, n):\n num = no\n rem = 0\n for i in range(0, n):\n if num == 0:\n return 0\n rem = num % 10\n num = num // 10\n return rem\n\ndef countingSort(a, n, d):\n ans = a.copy()\n f = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n for i in range(n):\n f[self.nth_digit(ans[i], d)] += 1\n for i in range(1, 10):\n f[i] += f[i - 1]\n for i in range(n - 1, -1, -1):\n f[self.nth_digit(ans[i], d)] -= 1\n a[f[self.nth_digit(ans[i], d)]] = ans[i]\n\ndef sort(a, n):\n no = self.no_of_digit(n ** 2 - 1)\n ans = a\n for i in range(1, no + 1):\n self.countingSort(ans, n, i)", "def sort(arr, n):\n for i in range(n):\n t = i\n for j in range(t, n):\n if arr[t] >= arr[j]:\n t = j\n (arr[i], arr[t]) = (arr[t], arr[i])\n return arr"], "starter_code": "def sort(arr, n):\n", "input_output": {"inputs": ["N = 7\narr[] = {40, 12, 45, 32, 33, 1, 22}", "N = 5\narr[] = {24, 12, 0, 15, 8}"], "outputs": ["1 12 22 32 33 40 45", "0 8 12 15 24"]}, "difficulty": "MEDIUM", "raw_tags": ["Sqrt Decomposition", "Algorithms", "Sorting"], "name": null, "source": "geeksforgeeks", "tags": ["Sorting", "Square root algorithms"], "skill_types": ["Sorting"], "url": "https://practice.geeksforgeeks.org/problems/efficiently-sorting-number-from-0-to-n2-15444/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "sort", "task_id": "TACO_lite/428", "example": [[], []]} +{"requirement": "We are given a sequence of coplanar points and see all the possible triangles that may be generated which all combinations of three points.\n\nWe have the following list of points with the cartesian coordinates of each one:\n```\nPoints [x, y]\n A [1, 2]\n B [3, 3]\n C [4, 1]\n D [1, 1]\n E [4, -1]\n```\nWith these points we may have the following triangles: ```ABC, ABD, ABE, ACD, ACE, ADE, BCD, BCE, BDE, CDE.``` There are three special ones: ```ABC, ACD and CDE```, that have an angle of 90°. All is shown in the picture below:\n\n\n\nWe need to count all the rectangle triangles that may be formed by a given list of points.\n\nThe case decribed above will be:\n```python\ncount_rect_triang([[1, 2],[3, 3],[4, 1],[1, 1],[4, -1]]) == 3\n```\n\nObserve this case:\n```python\ncount_rect_triang([[1, 2],[4, -1],[3, 3],[4, -1],[4, 1],[1, 1],[4, -1], [4, -1], [3, 3], [1, 2]]) == 3\n```\nIf no rectangle triangles may be generated the function will output ```0```.\n\nEnjoy it!", "solutions": ["from itertools import combinations\n\ndef isRect(a, b, c):\n (X, Y, Z) = sorted((sum(((q - p) ** 2 for (p, q) in zip(p1, p2))) for (p1, p2) in [(a, b), (a, c), (b, c)]))\n return X + Y == Z\n\ndef count_rect_triang(points):\n return sum((isRect(*c) for c in combinations(set(map(tuple, points)), 3)))", "from itertools import combinations\n\ndef count_rect_triang(points):\n result = 0\n for ((x1, y1), (x2, y2), (x3, y3)) in combinations(set(map(tuple, points)), 3):\n d1 = (x1 - x2) ** 2 + (y1 - y2) ** 2\n d2 = (x2 - x3) ** 2 + (y2 - y3) ** 2\n d3 = (x3 - x1) ** 2 + (y3 - y1) ** 2\n (d1, d2, d3) = sorted((d1, d2, d3))\n result += d1 + d2 == d3\n return result", "from itertools import combinations\n\ndef ok(a, b, c):\n ((x1, y1), (x2, y2), (x3, y3)) = (a, b, c)\n (d1, d2, d3) = ((x1 - x2) ** 2 + (y1 - y2) ** 2, (x1 - x3) ** 2 + (y1 - y3) ** 2, (x2 - x3) ** 2 + (y2 - y3) ** 2)\n (d1, d2, d3) = sorted([d1, d2, d3])\n return d1 + d2 == d3\n\ndef count_rect_triang(points):\n return sum((ok(pa, pb, pc) for (pa, pb, pc) in combinations(set(map(tuple, points)), 3)))", "f = lambda t, r=2: [sorted, iter][r - 2]((abs(sum(p) - 2 * p[-1]) ** 2 for p in map([list, f][r - 2], __import__('itertools').combinations(t, r))))\ncount_rect_triang = lambda p: sum((d < 1e-09 for d in f({x + 1j * y for (x, y) in p}, 3)))", "from itertools import combinations\n\ndef count_rect_triang(points):\n return sum((1 for ps in combinations(set(map(tuple, points)), 3) for (p0, p1, p2) in ((ps[0], ps[1], ps[2]), (ps[1], ps[2], ps[0]), (ps[2], ps[1], ps[0])) if (p1[0] - p0[0]) * (p2[0] - p0[0]) + (p1[1] - p0[1]) * (p2[1] - p0[1]) == 0))", "from itertools import product\n\ndef count_rect_triang(points):\n return sum((1 for (p0, p1, p2) in product(set(map(tuple, points)), repeat=3) if p0 != p1 != p2 != p0 and (p1[0] - p0[0]) * (p2[0] - p0[0]) + (p1[1] - p0[1]) * (p2[1] - p0[1]) == 0)) // 2", "def dist(ps):\n (p1, p2, p3) = ps\n x = (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2\n y = (p1[0] - p3[0]) ** 2 + (p1[1] - p3[1]) ** 2\n z = (p2[0] - p3[0]) ** 2 + (p2[1] - p3[1]) ** 2\n return sorted([x, y, z])\nfrom itertools import combinations\n\ndef count_rect_triang(points):\n if len(points) < 3:\n return 0\n ps = []\n for i in points:\n if i not in ps:\n ps.append(i)\n c = 0\n for i in combinations(ps, 3):\n temp = dist(i)\n if round(temp[-1], 4) == round(temp[0] + temp[1], 4):\n c += 1\n return c", "from itertools import combinations\n\ndef count_rect_triang(points):\n n = 0\n points_set = set()\n for p in points:\n points_set.add(tuple(p))\n for ((x1, y1), (x2, y2), (x3, y3)) in combinations(points_set, 3):\n (l1, l2, l3) = sorted([(x2 - x1) ** 2 + (y2 - y1) ** 2, (x3 - x2) ** 2 + (y3 - y2) ** 2, (x1 - x3) ** 2 + (y1 - y3) ** 2])\n if l1 + l2 == l3:\n n += 1\n return n", "from itertools import combinations\n\ndef count_rect_triang(points):\n ans = 0\n for c in combinations(set(map(tuple, points)), 3):\n dist = [(p[0][0] - p[1][0]) ** 2 + (p[0][1] - p[1][1]) ** 2 for p in combinations(c, 2)]\n ans += sum(dist) == max(dist) * 2\n return ans"], "starter_code": "def count_rect_triang(points):\n", "input_output": {"fn_name": "count_rect_triang", "inputs": [[[[1, 2], [3, 3], [4, 1], [1, 1], [4, -1]]], [[[1, 2], [4, -1], [3, 3], [4, -1], [4, 1], [1, 1], [4, -1], [4, -1], [3, 3], [1, 2]]]], "outputs": [[3], [3]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Geometry", "Fundamentals", "Logic"], "name": null, "source": "codewars", "tags": ["Geometry", "Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/57d99f6bbfcdc5b3b0000286", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "count_rect_triang", "task_id": "TACO_lite/420", "example": [[[[[1, 2], [3, 3], [4, 1], [1, 1], [4, -1]]], [[[1, 2], [4, -1], [3, 3], [4, -1], [4, 1], [1, 1], [4, -1], [4, -1], [3, 3], [1, 2]]]], ["3", "3"]]} +{"requirement": "Given a BST and a value k, the task is to delete the nodes having values greater than or equal to k.\nExample 1:\nInput:\n 4 \n / \\ \n 1 9 \nk = 2 \nOutput:\n1\nYour Task:\nThe task is to complete the function deleteNode() which takes root, k as the argument, and returns the root of tree after deleting values greater than or equal to k. The driver code will print the inorder traversal of the updated tree in output itself. \nExpected Time Complexity: O(Size of tree)\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= T <= 100\n1 <= N <= 10^{3}\n1 <= A[] <= 10^{3}\n1 <= k <= N", "solutions": ["def deleteNode(root, k):\n return self.helper(root, k) or root\n\ndef deleteNodeHelper(root):\n if root is None:\n return\n if root.left is None and root.right is None:\n del root\n return\n self.deleteNodeHelper(root.left)\n self.deleteNodeHelper(root.right)\n\ndef helper(root, k):\n if root is None:\n return None\n if root.data >= k:\n newRoot = root.left\n self.deleteNodeHelper(root.right)\n del root\n return self.helper(newRoot, k)\n else:\n rightChild = self.helper(root.right, k)\n root.right = rightChild\n return root", "def deleteNode(root, k):\n if root == None:\n return\n if root.data >= k:\n return self.deleteNode(root.left, k)\n if root.data < k:\n root.right = self.deleteNode(root.right, k)\n return root", "def Delete(root, k):\n if root == None:\n return None\n l = self.Delete(root.left, k)\n r = self.Delete(root.right, k)\n if root.data < k:\n root.left = l\n root.right = r\n return root\n else:\n return l\n\ndef deleteNode(root, k):\n root = self.Delete(root, k)\n return root", "def root_lefts(root):\n while root.right:\n root = root.right\n return root\n\ndef util(root, x):\n if not root:\n return root\n if root.data == x:\n return root.left\n if root.data > x:\n return self.util(root.left, x)\n if root.data < x:\n root.right = self.util(root.right, x)\n return root\n\ndef deleteNode(root, k):\n return self.util(root, k)", "def deleteNode(root, k):\n while root and root.data >= k:\n root = root.left\n start = root\n while root:\n while root.right and root.right.data >= k:\n root.right = root.right.left\n root = root.right\n return start", "def deleteNode(root, k):\n nod = Node(0)\n\n def fun2(root):\n if root == None:\n return\n if root.data >= k:\n return fun2(root.left)\n root.right = fun2(root.right)\n return root\n return fun2(root)", "def deleteNode(root, k):\n\n def f(root, k):\n if not root:\n return None\n if root.data < k:\n root.right = f(root.right, k)\n else:\n root = f(root.left, k)\n return root\n return f(root, k)", "def __init__():\n self.inorder = []\n\ndef InOrder(Node):\n if Node == None:\n return\n self.InOrder(Node.left)\n self.inorder.append(Node.data)\n self.InOrder(Node.right)\n return\n\ndef MakeTree(inorder):\n if inorder == []:\n return None\n mid = len(inorder) // 2\n root = Node(inorder[mid])\n root.left = self.MakeTree(inorder[:mid])\n root.right = self.MakeTree(inorder[mid + 1:])\n return root\n\ndef deleteNode(root, k):\n self.InOrder(root)\n for i in range(0, len(self.inorder)):\n if self.inorder[i] < k:\n continue\n else:\n self.inorder = self.inorder[:i]\n break\n return self.MakeTree(self.inorder)", "def solve(root, k):\n if root == None:\n return None\n elif root.data >= k:\n l = self.solve(root.left, k)\n return l\n else:\n root.right = self.solve(root.right, k)\n return root\n\ndef deleteNode(root, k):\n res = self.solve(root, k)\n return res", "def deleteNode(root, k):\n head = None\n head = self.delete(root, k, head)\n return head\n\ndef delete(root, k, head):\n if not root:\n return\n if root.data < k:\n head = root\n head.left = self.delete(root.left, k, head.left)\n head.right = self.delete(root.right, k, head.right)\n else:\n head = self.delete(root.left, k, head)\n return head", "def deep(root):\n cur = root\n while cur.left != None:\n cur = cur.left\n return cur\n\ndef delete(root, key):\n if root is None:\n return None\n if root.data > key:\n root.left = delete(root.left, key)\n elif root.data < key:\n root.right = delete(root.right, key)\n else:\n if root.left is None:\n temp = root.right\n root = None\n return temp\n if root.right is None:\n temp = root.left\n root = None\n return temp\n temp = deep(root.right)\n root.data = temp.data\n root.right = delete(root.right, temp.data)\n return root\n\ndef inorder(root):\n res = []\n q = []\n cur = root\n while True:\n if cur is not None:\n q.append(cur)\n cur = cur.left\n elif q:\n cur = q.pop()\n res.append(cur.data)\n cur = cur.right\n else:\n break\n return res\n\ndef deleteNode(root, k):\n ino = self.inorder(root)\n for i in ino:\n if i >= k:\n root = delete(root, i)\n return root", "def delete(root):\n if not root.left and (not root.right):\n root = None\n elif not root.left:\n root = root.right\n elif not root.right:\n root = root.left\n else:\n temp = minn(root.left)\n root.data = temp.data\n temp = delete(temp)\n return root\n\ndef minn(root):\n while root.right:\n root = root.right\n return root\n\ndef deleteNode(root, k):\n if not root:\n return\n root.left = self.deleteNode(root.left, k)\n root.right = self.deleteNode(root.right, k)\n if root.data >= k:\n root = delete(root)\n return root", "def getNodeAndParent(root, key):\n parent = None\n tmp = root\n while tmp:\n if tmp.data == key:\n return [tmp, parent]\n parent = tmp\n if tmp.data > key:\n tmp = tmp.left\n else:\n tmp = tmp.right\n return [None, None]\n\ndef isLeaf(node):\n return not node.left and (not node.right)\n\ndef deleteLeaf(node, parent):\n if parent.left == node:\n parent.left = None\n else:\n parent.right = None\n return node\n\ndef isSingleChildNode(node):\n return not node.left and node.right or (node.left and (not node.right))\n\ndef deleteSingleChildNode(node, parent):\n if node.left:\n if parent.left == node:\n parent.left = node.left\n else:\n parent.right = node.left\n node.left = None\n else:\n if parent.left == node:\n parent.left = node.right\n else:\n parent.right = node.right\n node.right = None\n return node\n\ndef deleteDoubleChildNode(node, parent):\n re_parent = node\n re_node = node.left\n while re_node.right:\n re_parent = re_node\n re_node = re_node.right\n if self.isLeaf(re_node):\n removed_node = self.deleteLeaf(re_node, re_parent)\n else:\n removed_node = self.deleteSingleChildNode(re_node, re_parent)\n if parent:\n if parent.left == node:\n parent.left = removed_node\n else:\n parent.right = removed_node\n removed_node.left = node.left\n removed_node.right = node.right\n return node\n\ndef deleteRoot(root):\n if self.isLeaf(root):\n new_root = None\n elif self.isSingleChildNode(root):\n if root.left:\n new_root = root.left\n else:\n new_root = root.right\n else:\n new_root = root.left\n while new_root.right:\n new_root = new_root.right\n root = self.deleteDoubleChildNode(root, None)\n del root\n return new_root\n\ndef deleteNodeBST(root, key: int):\n (node, parent) = self.getNodeAndParent(root, key)\n if not node:\n return root\n if not parent:\n root = self.deleteRoot(root)\n else:\n if self.isLeaf(node):\n removed_node = self.deleteLeaf(node, parent)\n elif self.isSingleChildNode(node):\n removed_node = self.deleteSingleChildNode(node, parent)\n else:\n removed_node = self.deleteDoubleChildNode(node, parent)\n del removed_node\n return root\n\ndef __init__() -> None:\n self.values = []\n\ndef getVals(root, k):\n if not root:\n return\n if root.data >= k:\n self.values.append(root.data)\n self.getVals(root.left, k)\n self.getVals(root.right, k)\n\ndef deleteNode(root, k):\n delete_node = Delete()\n self.getVals(root, k)\n for key in self.values:\n root = delete_node.deleteNodeBST(root, key)\n return root", "def deleteNode(root, k):\n if root == None:\n return root\n if root.data == k:\n return root.left\n elif root.data > k:\n temp = root.left\n return self.deleteNode(temp, k)\n else:\n root.right = self.deleteNode(root.right, k)\n return root", "def deleteNode(node, k):\n if node is None:\n return node\n node.left = self.deleteNode(node.left, k)\n node.right = self.deleteNode(node.right, k)\n if node.data >= k:\n return node.left\n return node", "def deleteNode(root, k):\n if root == None:\n return\n if root.data >= k:\n return self.deleteNode(root.left, k)\n root.left = self.deleteNode(root.left, k)\n root.right = self.deleteNode(root.right, k)\n return root\n\ndef delete(root):\n if root == None:\n return\n if root.left:\n root.data = root.left.data\n root.left = self.delete(root.left)\n elif root.right:\n root.data = root.right.data\n root.right = self.delete(root.right)\n else:\n del root\n return", "import sys\nsys.setrecursionlimit(10 ** 6)\n\ndef ino(r, l, k):\n if r is not None:\n self.ino(r.left, l, k)\n if r.data < k:\n l.append(Node(r.data))\n self.ino(r.right, l, k)\n\ndef deleteNode(root, k):\n l = []\n self.ino(root, l, k)\n n = len(l)\n for i in range(n - 1):\n l[i].right = l[i + 1]\n return l[0]", "node = None\n\ndef solve(root, k):\n if root is None:\n return None\n global head, itr\n if k <= root.data:\n if itr:\n itr.right = root.left\n self.solve(root.left, k)\n else:\n if head is None:\n head = root\n itr = head\n else:\n itr.right = root\n itr = root\n self.solve(root.right, k)\n\ndef deleteNode(root, k):\n global head, itr\n head = itr = None\n self.solve(root, k)\n return head", "def deleteNode(root, k):\n if not root:\n return root\n if root.data < k:\n root.right = self.deleteNode(root.right, k)\n return root\n elif root.data > k:\n return self.deleteNode(root.left, k)\n else:\n return root.left", "def deleteS(root, k):\n if root is None:\n return root\n if root.data > k:\n root.left = deleteS(root.left, k)\n elif root.data < k:\n root.right = deleteS(root.right, k)\n else:\n if root.left is None:\n temp = root.right\n root = None\n return temp\n if root.right is None:\n temp = root.left\n root = None\n return temp\n temp = minValueNode(root.right)\n root.data = temp.data\n root.right = deleteS(root.right, temp.data)\n return root\n\ndef minValueNode(node):\n current = node\n while current.left is not None:\n current = current.left\n return current\n\ndef inorder(root, a):\n if root is not None:\n inorder(root.left, a)\n a.append(root.data)\n inorder(root.right, a)\n return a\n\ndef deleteNode(root, k):\n a = []\n arr = inorder(root, a)\n for i in arr:\n if i >= k:\n w = deleteS(root, i)\n else:\n w = root\n return w", "def __init__(val):\n self.right = None\n self.data = val\n self.left = None\n\ndef deleteNode(root, k):\n if root is None:\n return\n root.left = self.deleteNode(root.left, k)\n root.right = self.deleteNode(root.right, k)\n if root.data >= k:\n temp = root.left\n root = None\n return temp\n return root", "def __init__():\n self.root = None\n\ndef deleteNode(root, k):\n self.root = root\n return self.__delete_k_greater(root, key=k)\n\ndef __delete_k_greater(node, key):\n if node and node.data >= key:\n if node == self.root:\n node = self.root = self.root.left\n else:\n node = node.left\n if node:\n return self.__delete_k_greater(node, key)\n elif node and node.data < key and node.right:\n node.right = self.__delete_k_greater(node.right, key)\n return node\n else:\n return node", "def deleteNode(root, k):\n newRoot = self.searchForNewRoot(root, k)\n if newRoot == None:\n return None\n self.trimTree(newRoot, k)\n return newRoot\n\ndef searchForNewRoot(root, k):\n curr = root\n while curr.data >= k:\n if curr.left == None:\n return None\n curr = curr.left\n return curr\n\ndef trimTree(root, k):\n curr = root\n parent = None\n while curr != None:\n if curr.data >= k:\n parent.right = curr.left\n curr = curr.left\n else:\n parent = curr\n curr = curr.right", "def deleteNode(root, k):\n while root.data >= k:\n if root.left == None and root.right == None:\n return\n root = root.left\n temp = root\n prev = None\n while temp != None:\n if temp.data < k:\n prev = temp\n temp = temp.right\n else:\n prev.right = temp.left\n temp = temp.left\n return root"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["4 \r\n / \\ \r\n 1 9 \r\nk = 2"], "outputs": ["1"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Binary Search Tree", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures", "Range queries"], "skill_types": ["Data structures", "Range queries"], "url": "https://practice.geeksforgeeks.org/problems/delete-nodes-greater-than-k/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(Size of tree)", "entry_point": "__init__", "task_id": "TACO_lite/447", "example": [[[4, 1, 9, 2]], ["1"]]} +{"requirement": "Introduction \n\nThe GADERYPOLUKI is a simple substitution cypher used in scouting to encrypt messages. The encryption is based on short, easy to remember key. The key is written as paired letters, which are in the cipher simple replacement.\n\nThe most frequently used key is \"GA-DE-RY-PO-LU-KI\".\n\n```\n G => A\n g => a\n a => g\n A => G\n D => E\n etc.\n```\n\nThe letters, which are not on the list of substitutes, stays in the encrypted text without changes.\n\nTask\n\nYour task is to help scouts to encrypt and decrypt thier messages.\nWrite the `Encode` and `Decode` functions.\n\nInput/Output\n\nThe input string consists of lowercase and uperrcase characters and white .\nThe substitution has to be case-sensitive. \n\nExample\n\n# GADERYPOLUKI collection\n\n\n\nGADERYPOLUKI cypher vol 1\n\n\nGADERYPOLUKI cypher vol 2\n\n\nGADERYPOLUKI cypher vol 3 - Missing Key\n\n\nGADERYPOLUKI cypher vol 4 - Missing key madness", "solutions": ["dict = {i[0]: i[1] for i in ['GA', 'DE', 'RY', 'PO', 'LU', 'KI', 'AG', 'ED', 'YR', 'OP', 'UL', 'IK', 'ga', 'de', 'ry', 'po', 'lu', 'ki', 'ag', 'ed', 'yr', 'op', 'ul', 'ik']}\n\ndef encode(s):\n return ''.join([dict[i] if i in dict else i for i in s])\n\ndef decode(s):\n return ''.join([dict[i] if i in dict else i for i in s])", "encode = decode = lambda str: str.translate(str.maketrans('gaderypolukiGADERYPOLUKI', 'agedyropulikAGEDYROPULIK'))", "def encode(str):\n return str.translate(str.maketrans('GDRPLKAEYOUI' + 'GDRPLKAEYOUI'.lower(), 'AEYOUIGDRPLK' + 'AEYOUIGDRPLK'.lower()))\n\ndef decode(str):\n return encode(str)", "def encode(message):\n s1 = 'GADERYPOLUKI'\n s2 = 'AGEDYROPULIK'\n return message.translate(str.maketrans(s1, s2)).translate(str.maketrans(s1.lower(), s2.lower()))\n\ndef decode(message):\n return encode(message)", "key = 'GA DE RY PO LU KI'\nkey += ' ' + key.lower()\ndict = {}\nfor (a, b) in key.split():\n dict[a] = b\n dict[b] = a\nencode = decode = lambda str: ''.join((dict.get(char, char) for char in str))", "t = str.maketrans('gdrplkGDRPLKaeyouiAEYOUI', 'aeyouiAEYOUIgdrplkGDRPLK')\nencode = decode = lambda s: s.translate(t)", "def encode(message):\n return message.translate(message.maketrans('GAgaDEdeRYryPOpoLUluKIki', 'AGagEDedYRyrOPopULulIKik'))\n\ndef decode(message):\n return message.translate(message.maketrans('GAgaDEdeRYryPOpoLUluKIki', 'AGagEDedYRyrOPopULulIKik'))", "key = 'GADERYPOLUKI'\nkey += key.lower()\ndekey = ''.join((key[i:i + 2][::-1] for i in range(0, len(key), 2)))\n\ndef encode(message):\n return message.translate(str.maketrans(key, dekey))\n\ndef decode(message):\n return message.translate(str.maketrans(dekey, key))", "key = 'GADERYPOLUKI'\n\ndef table(key):\n full_key = key.upper() + key.lower()\n (even, odd) = (full_key[::2], full_key[1::2])\n return str.maketrans(even + odd, odd + even)\nencode = decode = lambda message: message.translate(table(key))", "def encode(s):\n return ''.join(({'G': 'A', 'A': 'G', 'g': 'a', 'a': 'g', 'D': 'E', 'E': 'D', 'd': 'e', 'e': 'd', 'R': 'Y', 'Y': 'R', 'r': 'y', 'y': 'r', 'P': 'O', 'O': 'P', 'p': 'o', 'o': 'p', 'L': 'U', 'U': 'L', 'l': 'u', 'u': 'l', 'K': 'I', 'I': 'K', 'k': 'i', 'i': 'k'}[c] if c in {'G': 'A', 'A': 'G', 'g': 'a', 'a': 'g', 'D': 'E', 'E': 'D', 'd': 'e', 'e': 'd', 'R': 'Y', 'Y': 'R', 'r': 'y', 'y': 'r', 'P': 'O', 'O': 'P', 'p': 'o', 'o': 'p', 'L': 'U', 'U': 'L', 'l': 'u', 'u': 'l', 'K': 'I', 'I': 'K', 'k': 'i', 'i': 'k'} else c for c in s))\ndecode = encode"], "starter_code": "def encode(message):\n", "input_output": {"fn_name": "encode", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Cryptography", "Fundamentals", "Ciphers"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/592a6ad46d6c5a62b600003f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "encode", "task_id": "TACO_lite/465", "example": [[], []]} +{"requirement": "Given an ascending sorted rotated array Arr of distinct integers of size N. The array is right rotated K times. Find the value of K.\nExample 1:\nInput:\nN = 5\nArr[] = {5, 1, 2, 3, 4}\nOutput: 1\nExplanation: The given array is 5 1 2 3 4. \nThe original sorted array is 1 2 3 4 5. \nWe can see that the array was rotated \n1 times to the right.\nExample 2:\nInput:\nN = 5\nArr[] = {1, 2, 3, 4, 5}\nOutput: 0\nExplanation: The given array is not rotated.\nYour Task:\nComplete the function findKRotation() which takes array arr and size n, as input parameters and returns an integer representing the answer. You don't to print answer or take inputs.\nExpected Time Complexity: O(log(N))\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <=10^{5}\n1 <= Arr_{i} <= 10^{7}", "solutions": ["def findkrotation(arr, n):\n low = 0\n high = n - 1\n while low <= high:\n if high == low:\n return low\n mid = low + (high - low) // 2\n if arr[mid + 1] < arr[mid] and high > mid:\n return mid + 1\n if arr[mid] < arr[mid - 1] and low < mid:\n return mid\n if arr[high] > arr[mid]:\n high = mid - 1\n else:\n low = mid + 1\n return 0", "def findkrotation(arr, n):\n for i in range(1, n):\n if arr[i] < arr[i - 1]:\n return i\n break\n return 0", "def findkrotation(arr, n):\n el = min(arr)\n if arr.index(el) != 0:\n return arr.index(el)\n else:\n return 0", "def findkrotation(arr, n):\n temp = arr[:]\n temp.sort()\n return abs(temp.index(min(temp)) - arr.index(min(arr)))", "def findkrotation(arr, n):\n i = 0\n j = arr[-1]\n while arr[i] > j:\n i += 1\n return i", "def findkrotation(arr, n):\n if arr[0] < arr[n - 1]:\n return 0\n start = 0\n end = len(arr) - 1\n while start < end:\n mid = start + (end - start) // 2\n if arr[0] <= arr[mid]:\n start = mid + 1\n else:\n end = mid\n return start", "def findkrotation(arr, n):\n left = 0\n right = n - 1\n while left <= right:\n mid = left + (right - left) // 2\n if mid < right and arr[mid] > arr[mid + 1]:\n return mid + 1\n if mid > left and arr[mid - 1] > arr[mid]:\n return mid\n if arr[left] <= arr[mid]:\n left = mid + 1\n else:\n right = mid - 1\n return 0", "def findkrotation(arr, n):\n l = 0\n h = n - 1\n if arr[l] <= arr[h]:\n return l\n while l < h:\n mid = (l + h) // 2\n if arr[mid] > arr[mid + 1]:\n return mid + 1\n elif arr[mid] < arr[mid - 1]:\n return mid\n elif arr[l] <= arr[mid]:\n l = mid + 1\n else:\n h = mid - 1", "import numpy as np\n\ndef findkrotation(arr, n):\n mini = arr[0]\n rot = 0\n for i in range(n):\n if arr[i] < mini:\n mini = arr[i]\n rot = i\n return rot", "import numpy as np\n\ndef findkrotation(arr, n):\n arr = np.array(arr) - np.array(sorted(arr))\n count = 0\n for ele in arr:\n if ele > 0:\n count += 1\n return count", "def findkrotation(arr, n):\n return arr.index(min(arr))", "def findkrotation(arr, n):\n l = 0\n r = len(arr) - 1\n mid = 0\n if n == 1:\n return 0\n if arr[0] < arr[r]:\n return 0\n while l <= r:\n mid = l + (r - l) // 2\n if arr[mid] > arr[mid + 1]:\n return mid + 1\n if arr[mid] < arr[l]:\n r = mid - 1\n if arr[mid] >= arr[l]:\n l = mid + 1\n return l + 1", "def findkrotation(arr, n):\n low = 0\n high = n - 1\n while low <= high:\n mid = low + (high - low) // 2\n prev = (mid - 1 + n) % n\n next = (mid + 1) % n\n if arr[mid] <= arr[prev] and arr[mid] <= arr[next]:\n return mid\n elif arr[mid] <= arr[high]:\n high = mid - 1\n elif arr[mid] >= arr[low]:\n low = mid + 1\n return 0\n s = 0\n e = len(arr) - 1\n while s <= e:\n mid = s + (e - s) // 2\n nxt = (mid + 1) % n\n prv = (mid + n - 1) % n\n if arr[mid] <= arr[nxt] and arr[mid] <= arr[prv]:\n return mid\n elif arr[mid] >= arr[s]:\n s = mid + 1\n elif arr[mid] <= arr[e]:\n e = mid - 1\n return 0", "def findkrotation(arr, n):\n (i, j) = (0, n - 1)\n while i <= j:\n m = (i + j) // 2\n if arr[m] < arr[0]:\n j = m - 1\n else:\n i = m + 1\n return i % n", "def findkrotation(arr, n):\n nums = arr\n lengthOfNums = len(nums)\n start = 0\n end = lengthOfNums - 1\n pivot = 0\n while start <= end:\n mid = (start + end) // 2\n if mid - 1 >= 0 and nums[mid - 1] > nums[mid]:\n pivot = mid\n break\n elif nums[mid] < nums[start]:\n end = mid - 1\n elif nums[mid] > nums[start]:\n if nums[mid] <= nums[end]:\n end = mid - 1\n elif nums[mid] > nums[end]:\n start = mid + 1\n elif nums[mid] == nums[start]:\n start = mid + 1\n return pivot", "def findkrotation(arr, n):\n start = 0\n end = n - 1\n while start <= end:\n mid = start + (end - start) // 2\n nexti = (mid + 1) % n\n prev = (mid + n - 1) % n\n if arr[mid] <= arr[nexti] and arr[mid] <= arr[prev]:\n return mid\n elif arr[mid] <= arr[end]:\n end = mid - 1\n elif arr[start] <= arr[mid]:\n start = mid + 1\n return 0", "def findkrotation(arr, n):\n n = len(arr)\n left = 0\n right = n - 1\n while left <= right:\n if arr[left] <= arr[right]:\n return left\n mid = (left + right) // 2\n next = (mid + 1) % n\n prev = (mid + n - 1) % n\n if arr[mid] <= arr[next] and arr[mid] <= arr[prev]:\n return mid\n elif arr[mid] <= arr[right]:\n right = mid - 1\n elif arr[mid] >= arr[left]:\n left = mid + 1\n return -1", "def findkrotation(arr, n):\n a = []\n for i in arr:\n a.append(i)\n a.sort()\n count = abs(a.index(min(a)) - arr.index(min(arr)))\n return count", "def findkrotation(arr, n):\n i = 0\n j = n - 1\n min1 = 1000000\n ind = 0\n while i <= j:\n if arr[i] <= arr[j]:\n if min1 > arr[i]:\n ind = i\n min1 = arr[i]\n break\n mid = (i + j) // 2\n if arr[i] <= arr[mid]:\n if arr[i] < min1:\n ind = i\n min1 = arr[i]\n i = mid + 1\n else:\n if arr[mid] < min1:\n ind = mid\n min1 = arr[mid]\n j = mid - 1\n return ind", "def countRotations(arr, low, high):\n if high < low:\n return 0\n if high == low:\n return low\n mid = low + (high - low) // 2\n if mid < high and arr[mid + 1] < arr[mid]:\n return mid + 1\n if mid > low and arr[mid] < arr[mid - 1]:\n return mid\n if arr[high] > arr[mid]:\n return self.countRotations(arr, low, mid - 1)\n return self.countRotations(arr, mid + 1, high)\n\ndef findkrotation(arr, n):\n return self.countRotations(arr, 0, n - 1)", "def findkrotation(arr, n):\n lo = 0\n hi = n - 1\n if arr[lo] <= arr[hi]:\n return 0\n while lo <= hi:\n mid = (lo + hi) // 2\n if arr[mid] > arr[mid + 1]:\n return mid + 1\n elif arr[mid] < arr[mid - 1]:\n return mid\n elif arr[lo] <= arr[mid]:\n lo = mid + 1\n elif arr[mid] <= arr[hi]:\n hi = mid - 1\n return 0", "def findkrotation(arr, n):\n c = [i for i in arr]\n c.sort()\n d = c[0]\n return arr.index(d)", "def findkrotation(nums, n):\n (left, right) = (0, n - 1)\n if n <= 1 or nums[left] < nums[right]:\n return 0\n while left < right:\n mid = (left + right) // 2\n (prev, curr, next) = (nums[mid - 1], nums[mid], nums[mid + 1])\n if curr > next:\n return mid + 1\n if prev > curr:\n return mid\n if nums[0] < curr:\n left = mid + 1\n else:\n right = mid - 1", "from typing import List\n\ndef findkrotation(arr: List[int], n: int) -> int:\n (a, b) = (0, n - 1)\n while a <= b:\n mid = (a + b) // 2\n prev = (mid + n - 1) % n\n next_idx = (mid + 1) % n\n if arr[mid] <= arr[prev] and arr[mid] <= arr[next_idx]:\n return mid\n if arr[mid] <= arr[b]:\n b = mid - 1\n else:\n a = mid + 1\n return 0", "def findkrotation(arr, n):\n l = 0\n r = n - 1\n index = 0\n while l <= r:\n mid = (l + r) // 2\n if arr[mid] >= arr[0]:\n l = mid + 1\n else:\n r = mid - 1\n return l % n", "def findkrotation(arr, n):\n x = min(arr)\n l = arr[:]\n l.sort()\n return abs(l.index(x) - arr.index(x))", "def findkrotation(arr, n):\n m = min(arr)\n c = 0\n for i in range(n):\n if arr[i] != m:\n c = c + 1\n else:\n break\n return c", "def findkrotation(arr, n):\n a = min(arr)\n c = 0\n for i in range(len(arr)):\n if arr[i] == a:\n c = i\n else:\n continue\n return c", "def findkrotation(A, n):\n (low, high) = (0, n)\n while low < high:\n mid = (low + high) // 2\n if A[0] <= A[mid]:\n low = mid + 1\n else:\n high = mid\n if low == n:\n return 0\n return low", "def findkrotation(arr, n):\n l = 0\n r = n - 1\n while l <= r:\n mid = (l + r) // 2\n if arr[l] >= arr[mid] and arr[mid] >= arr[r]:\n return r\n if mid == 0 or arr[mid - 1] > arr[mid]:\n return mid\n if arr[mid] < arr[l]:\n r = mid - 1\n elif arr[mid] > arr[r]:\n l = mid + 1\n else:\n return l\n return -1", "def findkrotation(arr, n):\n if arr[0] < arr[-1] or n == 1:\n return 0\n for i in range(n - 1):\n if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:\n return i + 1\n return n", "def findkrotation(arr, n):\n low = 0\n high = n - 1\n while low <= high:\n mid = low + (high - low) // 2\n prev = (mid - 1 + n) % n\n next = (mid + 1) % n\n if arr[mid] <= arr[prev] and arr[mid] <= arr[next]:\n return mid\n elif arr[mid] <= arr[high]:\n high = mid - 1\n elif arr[mid] >= arr[low]:\n low = mid + 1\n return 0", "def findkrotation(arr, n):\n ans = 0\n for i in range(n - 1):\n if arr[i] > arr[i + 1]:\n ans = i + 1\n else:\n continue\n return ans", "def rot_bs(arr, start, end, n):\n while start <= end:\n mid = start + (end - start) // 2\n prev_ele = (mid - 1 + n) % n\n next_ele = (mid + 1) % n\n if arr[mid] < arr[prev_ele] and arr[mid] < arr[next_ele]:\n return mid\n elif arr[mid] <= arr[end]:\n end = mid - 1\n elif arr[start] <= arr[mid]:\n start = mid + 1\n\ndef findkrotation(arr, n):\n if arr[0] <= arr[n - 1]:\n return 0\n return self.rot_bs(arr, 0, n - 1, n)", "def findkrotation(nums, n):\n low = 0\n high = n - 1\n while low < high:\n mid = low + high >> 1\n if nums[mid] > nums[high]:\n low = mid + 1\n else:\n high = mid\n return low", "def findkrotation(arr, n):\n lo = 0\n hi = len(arr) - 1\n if len(arr) == 1 or arr[lo] < arr[hi]:\n return 0\n while lo <= hi:\n mid = (lo + hi) // 2\n if arr[mid] < arr[mid - 1]:\n return mid\n if arr[mid] > arr[mid + 1]:\n return mid + 1\n if arr[lo] < arr[mid]:\n lo = mid + 1\n else:\n hi = mid - 1", "import sys\n\ndef findkrotation(arr, n):\n (l, r) = (0, len(arr) - 1)\n minNum = arr[0]\n index = 0\n while l <= r:\n if arr[l] <= arr[r]:\n if minNum > arr[l]:\n index = l\n break\n mid = (l + r) // 2\n if minNum > arr[mid]:\n minNum = arr[mid]\n index = mid\n if arr[mid] >= arr[l]:\n l = mid + 1\n else:\n r = mid - 1\n return index", "def findkrotation(arr, n):\n (l, h) = (0, n - 1)\n MAX = float('-inf')\n if arr[l] <= arr[h]:\n return 0\n while l <= h:\n mid = (l + h) // 2\n if arr[mid] > MAX:\n MAX = arr[mid]\n max_index = mid\n if arr[mid] < arr[l]:\n h = mid - 1\n else:\n l = mid + 1\n return max_index + 1", "def findkrotation(nums, n):\n left = 0\n right = len(nums) - 1\n ans = 0\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] < nums[mid - 1]:\n ans = mid\n break\n if nums[mid] < nums[0]:\n right = mid - 1\n else:\n left = mid + 1\n return ans", "def findkrotation(nums, n):\n s = 0\n e = n - 1\n pivot = -1\n while s <= e:\n mid = s + (e - s) // 2\n if mid < e and nums[mid] > nums[mid + 1]:\n pivot = mid\n break\n elif mid > s and nums[mid - 1] > nums[mid]:\n pivot = mid - 1\n break\n if nums[mid] <= nums[s]:\n e = mid - 1\n elif nums[s] < nums[mid]:\n s = mid + 1\n if pivot == -1:\n return 0\n return pivot + 1", "def findkrotation(arr, n):\n x = min(arr)\n for i in range(n):\n if arr[i] == x:\n return i\n break", "def findkrotation(nums, n):\n start = 0\n end = len(nums) - 1\n while start <= end:\n mid = (start + end) // 2\n if mid < end and nums[mid] > nums[mid + 1]:\n return mid + 1\n if mid < end and nums[mid] < nums[mid - 1]:\n return mid\n if nums[start] == nums[mid] == nums[end] and start != mid != end:\n if nums[start] > nums[start + 1]:\n return start + 1\n start += 1\n if nums[end - 1] > nums[end]:\n return end\n end -= 1\n elif nums[mid] > nums[start] or (nums[mid] == nums[start] and nums[mid] > nums[end]):\n start = mid + 1\n else:\n end = mid - 1\n return 0", "def findkrotation(arr, n):\n l = 0\n h = n - 1\n while l < h:\n m = (l + h) // 2\n if arr[m] <= arr[h]:\n h = m\n else:\n l = m\n if arr[m] > arr[m + 1]:\n return m + 1\n return l", "def findkrotation(arr, n):\n cnt = 1\n for i in range(1, n):\n if arr[i - 1] < arr[i]:\n cnt += 1\n else:\n break\n return cnt % n", "def findkrotation(arr, n):\n m = float('inf')\n idx = 0\n for i in range(n):\n if m > arr[i]:\n m = arr[i]\n idx = i\n return idx", "def findkrotation(nums, n):\n rotation_pivot = 0\n (l, r, mid) = (0, n - 1, 0)\n if n == 1:\n return 0\n while l <= r:\n mid = (l + r) // 2\n if mid < n - 1:\n if nums[mid] > nums[mid + 1]:\n return mid + 1\n if mid > 0:\n if nums[mid] < nums[mid - 1]:\n return mid\n if nums[l] > nums[mid]:\n r = mid - 1\n else:\n l = mid + 1\n return 0", "def b_search(arr, start, end):\n middle = (start + end) // 2\n if start == end:\n return start\n while start < end:\n if arr[middle] < arr[middle - 1] and arr[middle] < arr[middle + 1]:\n return middle\n elif arr[middle] < arr[end]:\n return b_search(arr, start, middle - 1)\n else:\n return b_search(arr, middle + 1, end)\n return -1\n\ndef findkrotation(arr, n):\n result = b_search(arr, 0, n - 1)\n if result == -1:\n return 0\n else:\n return result", "def findkrotation(arr, n):\n l = []\n l.extend(arr)\n l.sort()\n return arr.index(l[0])"], "starter_code": "def findkrotation(arr, n):\n", "input_output": {"inputs": ["N = 5\r\nArr[] = {5, 1, 2, 3, 4}", "N = 5\r\nArr[] = {1, 2, 3, 4, 5}"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays", "Searching", "Algorithms"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/rotation4723/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(N))", "entry_point": "findkrotation", "task_id": "TACO_lite/458", "example": [[[5, [5, 1, 2, 3, 4]], [5, [1, 2, 3, 4, 5]]], ["1", "0"]]} +{"requirement": "Adding tip to a restaurant bill in a graceful way can be tricky, thats why you need make a function for it.\n\nThe function will receive the restaurant bill (always a positive number) as an argument. You need to 1) **add at least 15%** in tip, 2) round that number up to an *elegant* value and 3) return it.\n\nWhat is an *elegant* number? It depends on the magnitude of the number to be rounded. Numbers below 10 should simply be rounded to whole numbers. Numbers 10 and above should be rounded like this:\n\n10 - 99.99... ---> Round to number divisible by 5\n\n100 - 999.99... ---> Round to number divisible by 50\n\n1000 - 9999.99... ---> Round to number divisible by 500\n\nAnd so on...\n\nGood luck!\n\n## Examples\n```\n 1 --> 2\n 7 --> 9\n12 --> 15\n86 --> 100\n```", "solutions": ["from math import ceil, log10\n\ndef graceful_tipping(bill):\n bill *= 1.15\n if bill < 10:\n return ceil(bill)\n e = int(log10(bill))\n unit = 10 ** e / 2\n return ceil(bill / unit) * unit", "import math\n\ndef graceful_tipping(bill):\n c = bill * 115 / 100\n m = 1 if c < 10 else 5 * 10 ** int(math.log10(c) - 1)\n return math.ceil(c / m) * m", "def graceful_tipping(bill):\n import math\n multiple = 0\n tip = bill + 0.15 * bill\n if tip < 10:\n multiple = 1\n elif tip < 100:\n multiple = 5\n elif tip < 1000:\n multiple = 50\n elif tip < 10000:\n multiple = 500\n elif tip < 100000:\n multiple = 5000\n elif tip < 1000000:\n multiple = 50000\n elif tip < 10000000:\n multiple = 500000\n elif tip < 100000000:\n multiple = 5000000\n return math.ceil(float(tip) / multiple) * multiple", "import math\n\ndef graceful_tipping(bill):\n x = math.ceil(bill + bill * 15 / 100)\n if x < 11:\n return x\n else:\n le = len(str(x)) - 2\n y = 5 * 10 ** le\n return x + (y * math.ceil(x / y) - x)", "import math\n\ndef graceful_tipping(rest_bill):\n res = rest_bill * 1.15\n if res < 10:\n return math.ceil(res)\n tmp = 5 * 10.0 ** (math.ceil(math.log10(res)) - 2)\n if res % tmp > 0:\n res += tmp - res % tmp\n return res", "import math\n\ndef graceful_tipping(bill):\n bill = bill * 1.15\n if bill < 10:\n return math.ceil(bill)\n elif 10 <= bill < 100:\n bill = math.ceil(bill)\n mul5 = [i for i in range(1, bill + 5) if i % 5 == 0]\n return mul5[-1]\n elif 100 <= bill < 1000:\n bill = math.ceil(bill)\n mul50 = [i for i in range(1, bill + 50) if i % 50 == 0]\n return mul50[-1]\n elif 1000 <= bill < 10000:\n bill = math.ceil(bill)\n mul500 = [i for i in range(1, bill + 500) if i % 500 == 0]\n return mul500[-1]\n elif 10000 <= bill < 100000:\n bill = math.ceil(bill)\n mul5000 = [i for i in range(1, bill + 5000) if i % 5000 == 0]\n return mul5000[-1]\n elif 100000 <= bill < 1000000:\n bill = math.ceil(bill)\n mul50000 = [i for i in range(1, bill + 50000) if i % 50000 == 0]\n return mul50000[-1]\n elif 1000000 <= bill < 10000000:\n bill = math.ceil(bill)\n mul500000 = [i for i in range(1, bill + 500000) if i % 500000 == 0]\n return mul500000[-1]", "def graceful_tipping(bill):\n total = bill * 1.15\n if total < 10:\n total = int(total) + (total % 1 > 0)\n else:\n x = len(str(int(total))) - 2\n m = 5 * 10 ** x\n total = (int(total / m) + (total % m > 0)) * m\n return total", "from math import ceil\n\ndef graceful_tipping(bill):\n total = bill * 1.15\n if total < 10:\n return ceil(total)\n total /= 5\n d = 0\n while total >= 20:\n d += 1\n total /= 10\n return ceil(total) * 5 * 10 ** d", "from math import ceil\nfrom itertools import count\n\ndef graceful_tipping(bill):\n num = ceil(bill * 0.15 + bill)\n if num < 10:\n return num\n d = int('5' + (len(str(num)) - 2) * '0')\n for n in count(num):\n if n % d == 0:\n return n"], "starter_code": "def graceful_tipping(bill):\n", "input_output": {"fn_name": "graceful_tipping", "inputs": [[1], [7], [12], [86], [99], [1149], [983212]], "outputs": [[2], [9], [15], [100], [150], [1500], [1500000]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5eb27d81077a7400171c6820", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "graceful_tipping", "task_id": "TACO_lite/366", "example": [[[1], [7], [12], [86]], ["2", "9", "15", "100"]]} +{"requirement": "Given an integer N, the task is to find out the count of numbers M that satisfy the condition M + sum(M) + sum (sum(M)) = N, where sum(M) denotes the sum of digits in M.\nExample 1:\nInput: N = 9\nOutput: 1\nExplaination: Only 1 positive integer satisfies \nthe condition that is 3, 3 + sum(3) + sum(sum(3))\n= 3 + 3 + 3 = 9. \nExample 2:\nInput: N = 9939\nOutput: 4\nExplaination: M can be 9898, 9907, 9910 and 9913. \n9898 + sum(9898) + sum(sum(9898)) = 9898 + 34 + 7 \n= 9939. \n9907 + sum(9907) + sum(sum(9907)) = 9907 + 25 + 7 \n= 9939. \n9910 + sum(9910) + sum(sum(9910)) = 9910 + 19 + 10 \n= 9939. \n9913 + sum(9913) + sum(sum(9913)) = 9913 + 22 + 4 \n= 9939. \nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function countOfNumbers() which takes the value N and returns the count of numbers M that satisfy the given condition\nExpected Time Complexity: O(logn)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ N ≤ 10^{9}", "solutions": ["def sod(n):\n s = 0\n while n != 0:\n s += n % 10\n n = n // 10\n return s\n\ndef countofnumbers(N):\n c = 0\n d = N - 100\n if d < 0:\n d = 0\n for i in range(d, N + 1):\n if i + self.sod(i) + self.sod(self.sod(i)) == N:\n c += 1\n return c", "def sum(m):\n s = 0\n while m > 0:\n r = m % 10\n m = m // 10\n s = s + r\n return s\n\ndef countofnumbers(N):\n c = 0\n for i in range(N - 97, N + 1):\n a = sum(i)\n b = sum(a)\n if i + a + b == N:\n c += 1\n return c", "def sumD(N):\n sm = 0\n while N > 0:\n sm += N % 10\n N //= 10\n return sm\n\ndef countofnumbers(N):\n cn = 0\n for i in range(N - 97, N + 1):\n if i + self.sumD(i) + self.sumD(self.sumD(i)) == N:\n cn += 1\n return cn", "def sum1(n):\n rem = 0\n sum_of_digits = 0\n while n > 0:\n rem = n % 10\n sum_of_digits += rem\n n = n // 10\n return sum_of_digits\n\ndef __init__():\n self.c = 0\n self.a = None\n self.b = None\n self.i = None\n\ndef countofnumbers(N):\n self.c = 0\n for self.i in range(N - 97, N + 1):\n self.a = sum1(self.i)\n self.b = sum1(self.a)\n if self.i + self.a + self.b == N:\n self.c += 1\n return self.c", "def countofnumbers(N):\n\n def sum(n):\n s = 0\n while n > 0:\n rem = n % 10\n n //= 10\n s += rem\n return s\n c = 0\n for i in range(N - 97, N + 1):\n a = sum(i)\n b = sum(a)\n if i + a + b == N:\n c += 1\n return c"], "starter_code": "def countofnumbers(N):\n", "input_output": {"inputs": ["N = 9", "N = 9939"], "outputs": ["1", "4"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Numbers", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/count-the-numbers-satisfying-m-summ-sumsumm-equals-to-n2537/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(logn)", "entry_point": "countofnumbers", "task_id": "TACO_lite/469", "example": [[[9], [9939]], ["1", "4"]]} +{"requirement": "For every positive integer N, there exists a unique sequence starting with 1 and ending with N and such that every number in the sequence is either the double of the preceeding number or the double plus 1. \n\nFor example, given N = 13, the sequence is [1, 3, 6, 13], because . . . :\n```\n 3 = 2*1 +1\n 6 = 2*3\n 13 = 2*6 +1\n```\n\nWrite a function that returns this sequence given a number N. Try generating the elements of the resulting list in ascending order, i.e., without resorting to a list reversal or prependig the elements to a list.", "solutions": ["def climb(n):\n return [1] if n == 1 else climb(int(n / 2)) + [n]", "def climb(n):\n res = []\n cur = 1\n mask = 1 << max(0, n.bit_length() - 2)\n while cur <= n:\n res.append(cur)\n cur = 2 * cur + (1 if n & mask != 0 else 0)\n mask >>= 1\n return res", "def climb(n):\n result = [1]\n for x in '{:b}'.format(n)[1:]:\n result.append(result[-1] * 2 + (x == '1'))\n return result", "def climb(n):\n return [n >> i for i in range(len(f'{n:b}') - 1, -1, -1)]", "from math import log\nfrom collections import deque\n\ndef climb(n):\n return [n // 2 ** i for i in range(int(log(n, 2)) + 1)][::-1]\n\ndef climb(n):\n seq = deque([n])\n while n > 1:\n n //= 2\n seq.appendleft(n)\n return list(seq)", "def climb(n):\n return [n >> n.bit_length() - i - 1 for i in range(n.bit_length())]", "def climb(n):\n return list(climb_iterator(n))\n\ndef climb_iterator(n):\n cursor = 0\n for digit in bin(n)[2:]:\n cursor = 2 * cursor + int(digit)\n yield cursor", "def climb(n):\n res = [n]\n while res[-1] != 1:\n res.append(res[-1] // 2)\n return res[::-1]", "def climb(n):\n arr = []\n while n:\n arr.append(n)\n n //= 2\n return arr[::-1]"], "starter_code": "def climb(n):\n", "input_output": {"fn_name": "climb", "inputs": [[1], [100], [12345], [54321]], "outputs": [[[1]], [[1, 3, 6, 12, 25, 50, 100]], [[1, 3, 6, 12, 24, 48, 96, 192, 385, 771, 1543, 3086, 6172, 12345]], [[1, 3, 6, 13, 26, 53, 106, 212, 424, 848, 1697, 3395, 6790, 13580, 27160, 54321]]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/559760bae64c31556c00006b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "climb", "task_id": "TACO_lite/379", "example": [[[13]], ["[1, 3, 6, 13]"]]} +{"requirement": "In genetics, a sequence’s motif is a nucleotides (or amino-acid) sequence pattern. Sequence motifs have a biological significance. For more information you can take a look [here](https://en.wikipedia.org/wiki/Sequence_motif).\n\n\nFor this kata you need to complete the function `motif_locator`. This function receives 2 arguments - a sequence and a motif. Both arguments are strings.\n\nYou should return an array that contains all the start positions of the motif (in order). A sequence may contain 0 or more repetitions of the given motif. Note that the number of the first position is 1, not 0.\n\n**Some examples:**\n\n- For the `sequence` \"ACGTGGGGACTAGGGG\" and the `motif` \"GGGG\" the result should be [5, 13]. \n- For the `sequence` \"ACCGTACCAAGGGACC\" and the `motif` \"AAT\" the result should be []\n- For the `sequence` \"GGG\" and the motif \"GG\" the result should be [1, 2]\n\n**Note**: You can take a look to my others bio-info kata [here](http://www.codewars.com/users/nbeck/authored)", "solutions": ["def motif_locator(sequence, motif):\n (res, i) = ([], 0)\n while True:\n i = sequence.find(motif, i) + 1\n if not i:\n return res\n res.append(i)", "def motif_locator(sequence, motif):\n return [i + 1 for (i, c) in enumerate(sequence) if sequence[i:i + len(motif)] == motif]", "def motif_locator(seq, motif):\n dex = 0\n result = []\n while True:\n dex = seq.find(motif, dex)\n if dex == -1:\n return result\n dex += 1\n result.append(dex)", "def motif_locator(s, motif):\n return [i + 1 for i in range(len(s) - len(motif) + 1) if s[i:].startswith(motif)]", "from itertools import count\n\ndef motif_locator(sequence, motif):\n if len(motif) > len(sequence):\n return []\n n = len(motif)\n target_hash = sum(map(ord, motif))\n hashish = sum(map(ord, sequence[:n]))\n res = []\n for i in count():\n if hashish == target_hash and sequence[i:i + n] == motif:\n res.append(i + 1)\n if i + n == len(sequence):\n return res\n hashish += ord(sequence[i + n]) - ord(sequence[i])", "import re\n\ndef motif_locator(sequence, motif):\n return [m.start() + 1 for m in re.finditer('{}(?={})'.format(motif[0], motif[1:]), sequence)]", "def motif_locator(sequence, motif):\n start = 0\n arr = []\n while True:\n index = sequence.find(motif, start)\n if index == -1:\n break\n start = index + 1\n arr.append(index + 1)\n return arr", "motif_locator = lambda s, m: sorted(list({s.find(m, e) + 1 for (e, i) in enumerate(range(len(s))) if s.find(m, e) != -1}))", "def motif_locator(s, m):\n return [i + 1 for i in range(len(s) - len(m) + 1) if s[i:i + len(m)] == m]"], "starter_code": "def motif_locator(sequence, motif):\n", "input_output": {"fn_name": "motif_locator", "inputs": [["TTCCGGAACC", "CC"], ["ACGTTACAACGTTAG", "ACGT"], ["ACGTACGTACGT", "AAA"], ["ACGT", "ACGTGAC"]], "outputs": [[[3, 9]], [[1, 9]], [[]], [[]]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5760c1c7f2717b91e20001a4", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "motif_locator", "task_id": "TACO_lite/374", "example": [[["ACGTGGGGACTAGGGG", "GGGG"], ["ACCGTACCAAGGGACC", "AAT"], ["GGG", "GG"]], ["[5, 13]", "[]", "[1, 2]"]]} +{"requirement": "Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).\nMore formally check if there exists two indices i and j such that :\n\ni != j\n0 <= i, j < arr.length\narr[i] == 2 * arr[j]\n\n \nExample 1:\nInput: arr = [10,2,5,3]\nOutput: true\nExplanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.\n\nExample 2:\nInput: arr = [7,1,14,11]\nOutput: true\nExplanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.\n\nExample 3:\nInput: arr = [3,1,7,11]\nOutput: false\nExplanation: In this case does not exist N and M, such that N = 2 * M.\n\n \nConstraints:\n\n2 <= arr.length <= 500\n-10^3 <= arr[i] <= 10^3", "solutions": ["def checkifexist(arr: List[int]) -> bool:\n found = {}\n for num in arr:\n if num * 2 in found:\n return True\n if num % 2 == 0 and num / 2 in found:\n return True\n found[num] = True\n return False", "def checkifexist(arr: List[int]) -> bool:\n lookup = dict()\n for val in arr:\n if val * 2 in lookup:\n return True\n elif val / 2 in lookup:\n return True\n else:\n lookup[val] = 1\n return False", "def checkifexist(arr: List[int]) -> bool:\n tracker = set()\n for n in arr:\n if n % 2 == 0 and n / 2 in tracker or n * 2 in tracker:\n return True\n tracker.add(n)\n return False", "def checkifexist(arr: List[int]) -> bool:\n for i in range(0, len(arr)):\n for j in range(i + 1, len(arr)):\n if arr[i] == 2 * arr[j] or arr[j] == 2 * arr[i]:\n return True\n return False", "def checkifexist(arr: List[int]) -> bool:\n arr.sort()\n for k in range(len(arr) - 1):\n if 2 * arr[k] in arr[k + 1:] or 2 * arr[k] in arr[:k]:\n return True\n return False", "def checkifexist(arr: List[int]) -> bool:\n i = 0\n i = len(arr)\n for j in range(0, i):\n for k in range(0, i):\n if arr[j] > 0 and arr[k] > 0 and (arr[j] > arr[k]):\n if arr[j] == arr[k] * 2:\n return True\n elif arr[j] < 0 and arr[k] < 0 and (arr[j] < arr[k]):\n if arr[k] * 2 == arr[j]:\n return True\n if arr[0] == 0 and arr[1] == 0:\n return True\n else:\n return False", "def checkifexist(arr: List[int]) -> bool:\n arr.sort()\n for i in range(len(arr)):\n for j in range(i + 1, len(arr)):\n if arr[i] != 0 and arr[j] / arr[i] == 2:\n return True\n if arr[i] == 0 and arr[j] == 0:\n return True\n if arr[i] < 0 and arr[j] < 0 and (arr[i] / arr[j] == 2):\n return True", "def checkifexist(arr: List[int]) -> bool:\n seen = set()\n for e in arr:\n if 2 * e in seen or (e % 2 == 0 and e // 2 in seen):\n return True\n seen.add(e)\n return False", "def checkifexist(arr: List[int]) -> bool:\n for num in arr:\n if num == 0:\n if arr.count(0) > 1:\n return True\n elif arr.count(num * 2) != 0:\n return True\n return False", "def checkifexist(arr: List[int]) -> bool:\n h_table = set()\n for num in arr:\n if num * 2 in h_table or num / 2 in h_table:\n return True\n h_table.add(num)\n return False", "def checkifexist(arr: List[int]) -> bool:\n doubledList = []\n l = len(arr)\n for num in arr:\n doubledList.append(num * 2)\n for i in range(l):\n if doubledList[i] in arr and arr.index(doubledList[i]) != i:\n return True\n return False", "def checkifexist(arr: List[int]) -> bool:\n cache = set()\n for (i, value) in enumerate(arr):\n if 2 * value in cache or (value % 2 == 0 and value / 2 in cache):\n return True\n cache.add(value)\n return False", "def checkifexist(arr: List[int]) -> bool:\n if len(arr) < 2:\n return False\n for n in range(len(arr)):\n m = 2 * arr[n]\n for k in range(len(arr)):\n if arr[k] == m and k != n:\n return True\n return False", "def checkifexist(arr: List[int]) -> bool:\n if arr[0] == 0 and arr[1] == 0:\n return True\n dictionary = {}\n for number in arr:\n dictionary[2 * number] = True\n for number in arr:\n if number in dictionary and number != 0:\n return True\n return False"], "starter_code": "def checkifexist(arr: List[int]) -> bool:\n", "input_output": {"fn_name": "checkIfExist", "inputs": [[[10, 2, 5, 3]]], "outputs": [true]}, "difficulty": "EASY", "raw_tags": ["Binary Search", "Two Pointers", "Array", "Sorting", "Hash Table"], "name": null, "source": "leetcode", "tags": ["Data structures", "Sorting", "Amortized analysis"], "skill_types": ["Amortized analysis", "Sorting", "Data structures"], "url": "https://leetcode.com/problems/check-if-n-and-its-double-exist/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "checkifexist", "task_id": "TACO_lite/438", "example": [[], []]} +{"requirement": "The objective is to return all pairs of integers from a given array of integers that have a difference of 2.\n\nThe result array should be sorted in ascending order of values.\n\nAssume there are no duplicate integers in the array. The order of the integers in the input array should not matter.\n\n\n## Examples\n~~~if-not:python\n```\n[1, 2, 3, 4] should return [[1, 3], [2, 4]]\n\n[4, 1, 2, 3] should also return [[1, 3], [2, 4]]\n\n[1, 23, 3, 4, 7] should return [[1, 3]]\n\n[4, 3, 1, 5, 6] should return [[1, 3], [3, 5], [4, 6]]\n```\n~~~\n~~~if:python\n```\n[1, 2, 3, 4] should return [(1, 3), (2, 4)]\n\n[4, 1, 2, 3] should also return [(1, 3), (2, 4)]\n\n[1, 23, 3, 4, 7] should return [(1, 3)]\n\n[4, 3, 1, 5, 6] should return [(1, 3), (3, 5), (4, 6)]\n```\n~~~", "solutions": ["def twos_difference(a):\n s = set(a)\n return sorted(((x, x + 2) for x in a if x + 2 in s))", "def twos_difference(lst):\n return [(num, num + 2) for num in sorted(lst) if num + 2 in lst]", "def twos_difference(arr):\n arr = sorted(arr)\n b = []\n for i in range(len(arr)):\n for j in range(len(arr)):\n if arr[j] - arr[i] == 2:\n b.append((arr[i], arr[j]))\n return b", "def twos_difference(lst):\n return [(i, i + 2) for i in sorted(lst) if i + 2 in lst]", "def twos_difference(lst):\n matches = []\n for n in sorted(lst):\n if n + 2 in lst:\n matches.append((n, n + 2))\n return matches", "def twos_difference(A):\n L = []\n for i in sorted(A):\n if i + 2 in A:\n L.append((i, i + 2))\n return L", "def twos_difference(lst):\n ende = []\n for i in lst:\n if i + 2 in lst:\n ende.append((i, i + 2))\n return sorted(ende)", "def twos_difference(l):\n r = [(i, i + 2) for i in sorted(l) if i + 2 in l]\n return r\ntwos_difference = lambda l: [(i, i + 2) for i in sorted(l) if i + 2 in l]", "def twos_difference(lst):\n result = []\n for elem in lst:\n if elem + 2 in lst:\n result.append((elem, elem + 2))\n result.sort()\n return result", "def twos_difference(lst):\n newlist = lst\n even = []\n odd = []\n finaleven = []\n finalodd = []\n for num in newlist:\n if num % 2 == 0:\n even.append(num)\n else:\n odd.append(num)\n for i in even:\n for j in even:\n if i + 2 == j:\n finaleven.append((i, j))\n for a in odd:\n for b in odd:\n if a + 2 == b:\n finalodd.append((a, b))\n y = sorted(finaleven)\n z = sorted(finalodd)\n return sorted(y + z)", "def twos_difference(lst):\n s = set(lst)\n return [(n, n + 2) for n in sorted(s) if n + 2 in s]", "def twos_difference(lst):\n new_list = []\n lst.sort()\n for (ind, val) in enumerate(lst):\n get_check = val + 2\n try:\n if lst.index(get_check):\n new_list.append((val, get_check))\n except ValueError:\n continue\n return new_list", "def twos_difference(lst):\n return sorted([(x, x + 2) for x in lst if x + 2 in lst], key=lambda x: (x[0], x[1]))", "import itertools as it\nimport operator as op\n\ndef twos_difference(lst):\n pairs = it.combinations(lst, 2)\n twodiffs = (pair for pair in pairs if abs(op.sub(*pair)) == 2)\n return sorted([tuple(sorted(pair)) for pair in list(twodiffs)])", "def twos_difference(lst):\n concat = []\n for number in lst:\n if int(number) + 2 in lst:\n concat.append((int(number), int(number) + 2))\n return sorted(concat)", "def twos_difference(a):\n return sorted([(i, j) for i in a for j in a if i - j == -2])", "def twos_difference(lst):\n if not lst:\n return []\n test = list(range(min(lst), max(lst) + 1))\n return [(test[i], test[i + 2]) for i in range(len(test) - 2) if all((test[i] in lst, test[i + 2] in lst))]", "def twos_difference(lst):\n lst1 = []\n for i in lst:\n for j in lst:\n if i - j == 2 or i - j == -2:\n if (i, j) not in lst1 and (j, i) not in lst1:\n if i < j:\n lst1.append((i, j))\n else:\n lst1.append((j, i))\n lst1.sort()\n return lst1", "def twos_difference(lst):\n my_pairs = []\n for i in range(0, len(lst)):\n for j in range(0, len(lst)):\n if lst[j] - lst[i] == 2:\n my_pairs.append([lst[j], lst[i]])\n diffs = []\n for pair in my_pairs:\n pair.sort()\n diffs.append(tuple(pair))\n diffs.sort()\n return diffs", "def twos_difference(lst):\n (results, memo) = ([], {})\n for n in lst:\n if n in memo:\n for k in memo[n]:\n (a, b) = sorted([k, n])\n results.append((a, b))\n memo.setdefault(n + 2, []).append(n)\n memo.setdefault(n - 2, []).append(n)\n return sorted(results)"], "starter_code": "def twos_difference(lst):\n", "input_output": {"fn_name": "twos_difference", "inputs": [[[1, 2, 3, 4]], [[1, 3, 4, 6]], [[0, 3, 1, 4]], [[4, 1, 2, 3]], [[6, 3, 4, 1, 5]], [[3, 1, 6, 4]], [[1, 3, 5, 6, 8, 10, 15, 32, 12, 14, 56]], [[1, 4, 7, 10]], [[]]], "outputs": [[[[1, 3], [2, 4]]], [[[1, 3], [4, 6]]], [[[1, 3]]], [[[1, 3], [2, 4]]], [[[1, 3], [3, 5], [4, 6]]], [[[1, 3], [4, 6]]], [[[1, 3], [3, 5], [6, 8], [8, 10], [10, 12], [12, 14]]], [[]], [[]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms", "Sorting"], "name": null, "source": "codewars", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/5340298112fa30e786000688", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "twos_difference", "task_id": "TACO_lite/341", "example": [[[[1, 2, 3, 4]], [[4, 1, 2, 3]], [[1, 23, 3, 4, 7]], [[4, 3, 1, 5, 6]]], ["[(1, 3), (2, 4)]", "[(1, 3), (2, 4)]", "[(1, 3)]", "[(1, 3), (3, 5), (4, 6)]"]]} +{"requirement": "Given a BST and an integer K. Find the Kth Smallest element in the BST using O(1) extra space. \nExample 1:\nInput:\n 2\n / \\\n 1 3\nK = 2\nOutput: 2\nExplanation: 2 is the 2nd smallest element in the BST\nExample 2:\nInput:\n 2\n / \\\n 1 3\nK = 5\nOutput: -1\nExplanation: There is no 5th smallest element in the BST as the size of BST is 3\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function KthSmallestElement() which takes the root of the BST and integer K as inputs and returns the Kth smallest element in the BST, if no such element exists return -1.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\nConstraints:\n1<=Number of nodes<=10^5", "solutions": ["def KthSmallestElement(root, K):\n\n def Inorder(root):\n if root == None:\n return\n Inorder(root.left)\n ans.append(root.data)\n Inorder(root.right)\n ans = []\n Inorder(root)\n if K > len(ans):\n return -1\n return ans[K - 1]", "def KthSmallestElement(root, K):\n\n def inorder(root):\n nonlocal count, ans\n if not root:\n return\n inorder(root.left)\n count += 1\n if count == K:\n ans = root.data\n inorder(root.right)\n count = 0\n ans = -1\n inorder(root)\n return ans", "def util(root, k):\n if not root:\n return\n self.util(root.left, k)\n self.cnt += 1\n if self.cnt == k:\n self.cnt += 1\n self.ans = root.data\n return\n self.util(root.right, k)\n\ndef KthSmallestElement(root, k):\n self.cnt = 0\n self.ans = -1\n self.util(root, k)\n return self.ans", "def util(root, k):\n global cnt, ans\n par = root\n while par != None:\n if par.left != None:\n temp = par.left\n while temp.right != None and temp.right != par:\n temp = temp.right\n if temp.right == None:\n temp.right = par\n par = par.left\n else:\n temp.right = None\n cnt += 1\n if cnt == k:\n ans = par.data\n par = par.right\n else:\n cnt += 1\n if cnt == k:\n ans = par.data\n par = par.right\n\ndef KthSmallestElement(root, k):\n global cnt, ans\n cnt = 0\n ans = -1\n self.util(root, k)\n return ans", "def inorder(root, l):\n if root is None:\n return\n self.inorder(root.left, l)\n l.append(root.data)\n self.inorder(root.right, l)\n\ndef InOrder(root):\n l = []\n self.inorder(root, l)\n return l\n\ndef KthSmallestElement(root, K):\n p = self.InOrder(root)\n p.sort()\n if K > len(p):\n return -1\n else:\n return p[K - 1]", "def kthelement(root):\n if root is None:\n return -1\n leftside = self.kthelement(root.left)\n if leftside != -1:\n return leftside\n self.K -= 1\n if self.K == 0:\n return root.data\n return self.kthelement(root.right)\n\ndef KthSmallestElement(root, K):\n self.K = K\n return self.kthelement(root)", "def getMin(root, li):\n if root:\n self.getMin(root.left, li)\n li.append(root.data)\n self.getMin(root.right, li)\n\ndef KthSmallestElement(root, K):\n li = []\n self.getMin(root, li)\n if K > len(li):\n return -1\n return li[K - 1]", "def inorder(root, arr):\n if root is not None:\n self.inorder(root.left, arr)\n arr.append(root.data)\n self.inorder(root.right, arr)\n\ndef KthSmallestElement(root, K):\n arr = []\n self.inorder(root, arr)\n if len(arr) < K:\n return -1\n return arr[K - 1]", "def KthSmallestElement(root, K):\n li = self.inorder(root, [])\n if len(li) < K:\n return -1\n else:\n return li[K - 1]\n\ndef inorder(node, a):\n if node is None:\n return\n self.inorder(node.left, a)\n a.append(node.data)\n self.inorder(node.right, a)\n return a", "def KthSmallestElement(root, K):\n temp = root\n while temp:\n if temp.left is None:\n K -= 1\n if K == 0:\n return temp.data\n temp = temp.right\n else:\n pred = temp.left\n while pred.right and pred.right != temp:\n pred = pred.right\n if pred.right is None:\n pred.right = temp\n temp = temp.left\n else:\n pred.right = None\n K -= 1\n if K == 0:\n return temp.data\n temp = temp.right\n return -1", "def inorder(root):\n if root == None:\n return []\n return self.inorder(root.left) + [root.data] + self.inorder(root.right)\n\ndef KthSmallestElement(root, K):\n li = self.inorder(root)\n if len(li) >= K:\n return li[K - 1]\n return -1", "def KthSmallestElement(root, K):\n if not root:\n return None\n stack = []\n count = 0\n while stack or root:\n while root:\n stack.append(root)\n root = root.left\n node = stack.pop()\n count += 1\n if count == K:\n return node.data\n root = node.right\n return -1", "def inOrder(root):\n res = []\n if root:\n res = self.inOrder(root.left)\n res.append(root.data)\n res = res + self.inOrder(root.right)\n return res\n\ndef KthSmallestElement(root, K):\n li = self.inOrder(root)\n if len(li) >= K:\n return li[K - 1]\n return -1", "def inorder(root, ans):\n if root:\n self.inorder(root.left, ans)\n ans.append(root.data)\n self.inorder(root.right, ans)\n\ndef KthSmallestElement(root, k):\n ans = []\n self.inorder(root, ans)\n if k <= len(ans):\n return ans[k - 1]\n else:\n return -1", "def KthSmallestElement(root, K):\n if root == None:\n return\n self.KthSmallestElement(root.left, K)\n self.count += 1\n if self.count == K:\n self.ans = root.data\n self.KthSmallestElement(root.right, K)\n if self.ans == 0:\n return -1\n return self.ans", "def KthSmallestElement(root, K):\n count = [0]\n return self.helper(root, K, count)\n\ndef helper(root, K, count):\n if root is None:\n return -1\n result = -1\n leftSubTree = self.helper(root.left, K, count)\n if leftSubTree > 0:\n result = leftSubTree\n count[0] += 1\n if count[0] == K:\n result = root.data\n if result < 0:\n rightSubTree = self.helper(root.right, K, count)\n if rightSubTree > 0:\n result = rightSubTree\n return result", "def KthSmallestElement(root, k):\n stack = []\n while root is not None or len(stack) > 0:\n while root is not None:\n stack.append(root)\n root = root.left\n root = stack.pop()\n k -= 1\n if k == 0:\n return root.data\n root = root.right\n return -1", "def inorder(root, K):\n if root is None:\n return\n self.inorder(root.left, K)\n if K == self.count:\n self.res = root.data\n self.count += 1\n return\n else:\n self.count += 1\n self.inorder(root.right, K)\n\ndef KthSmallestElement(root, K):\n self.count = 1\n self.res = -1\n self.inorder(root, K)\n return self.res", "def inorder(root):\n if root:\n self.inorder(root.left)\n self.res.append(root.data)\n self.inorder(root.right)\n\ndef KthSmallestElement(root, K):\n self.res = []\n self.inorder(root)\n for i in range(len(self.res)):\n if K > len(self.res):\n return -1\n return self.res[K - 1]", "def KthSmallestElement(root, k):\n result = []\n if root is None:\n return -1\n if self.size(root) < k:\n return -1\n self._kthSmallestElement(root, k, result)\n return result[k - 1]\n\ndef _kthSmallestElement(root, k, result):\n if root is None:\n return\n if len(result) == k:\n return\n self._kthSmallestElement(root.left, k, result)\n result.append(root.data)\n self._kthSmallestElement(root.right, k, result)\n\ndef size(root):\n if root is None:\n return 0\n return 1 + self.size(root.left) + self.size(root.right)", "import heapq\n\ndef KthSmallestElement(root, K):\n maxheap = []\n heapq.heapify(maxheap)\n\n def inorder(root):\n if root == None:\n return\n inorder(root.left)\n heapq.heappush(maxheap, -1 * root.data)\n if len(maxheap) > K:\n heapq.heappop(maxheap)\n inorder(root.right)\n inorder(root)\n if len(maxheap) > K or len(maxheap) < K:\n return -1\n return -1 * heapq.heappop(maxheap)", "def KthSmallestElement(root, k):\n s = []\n c = 0\n while s or root:\n while root:\n s.append(root)\n root = root.left\n node = s.pop()\n c += 1\n if c == k:\n return node.data\n root = node.right\n return -1", "def __init__():\n self.counter = 0\n\ndef KthSmallestElement(root, k):\n return self.KthSmallestElementUtil(root, k)\n\ndef KthSmallestElementUtil(root, k):\n if root is None:\n return -1\n left = self.KthSmallestElementUtil(root.left, k)\n if left != -1:\n return left\n self.counter += 1\n if self.counter == k:\n return root.data\n return self.KthSmallestElementUtil(root.right, k)", "global index\nindex = 0\nglobal ans\nans = -1\n\ndef inorder(root, K):\n global index\n global ans\n if not root or ans != -1:\n return\n self.inorder(root.left, K)\n index += 1\n if index == K:\n ans = root.data\n return\n self.inorder(root.right, K)\n\ndef KthSmallestElement(root, K):\n global ans\n global index\n index = 0\n ans = -1\n self.inorder(root, K)\n return ans", "global index\nindex = 0\nglobal ans\nans = -1\nglobal k\n\ndef inorder(root, K):\n global index\n global ans\n if not root or ans != -1:\n return\n self.inorder(root.left, K)\n index += 1\n if index == K:\n ans = root.data\n return\n self.inorder(root.right, K)\n\ndef KthSmallestElement(root, K):\n global k\n k = K\n node = self.doomdoom(root, K)\n if node:\n return node.data\n return -1\n\ndef doomdoom(root, K):\n global k\n if root == None:\n return None\n left = self.doomdoom(root.left, K)\n if left != None:\n return left\n k -= 1\n if k == 0:\n return root\n return self.doomdoom(root.right, K)", "def solve(root):\n if root is None:\n return\n self.solve(root.left)\n self.q.append(root.data)\n self.solve(root.right)\n\ndef KthSmallestElement(root, K):\n self.q = []\n self.solve(root)\n if K > len(self.q):\n return -1\n return self.q[K - 1]", "def KthSmallestElement(root, K):\n i = [0, -1]\n\n def ino(root, K):\n if root:\n ino(root.left, K)\n i[0] = i[0] + 1\n if i[0] == K:\n i[1] = root.data\n return\n return ino(root.right, K)\n ino(root, K)\n return i[1]"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["2\r\n / \\\r\n 1 3\r\nK = 2", "2\r\n / \\\r\n 1 3\r\nK = 5"], "outputs": ["2", "-1"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Binary Search Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Range queries"], "skill_types": ["Data structures", "Range queries"], "url": "https://practice.geeksforgeeks.org/problems/find-k-th-smallest-element-in-bst/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "__init__", "task_id": "TACO_lite/454", "example": [[], []]} +{"requirement": "# How much is the fish! (- Scooter )\nThe ocean is full of colorful fishes. We as programmers want to know the hexadecimal value of these fishes.\n\n## Task\nTake all hexadecimal valid characters (a,b,c,d,e,f) of the given name and XOR them. Return the result as an integer.\n\n## Input\nThe input is always a string, which can contain spaces, upper and lower case letters but no digits. \n\n## Example\n\n`fisHex(\"redlionfish\") -> e,d,f -> XOR -> 12`", "solutions": ["from functools import reduce\nVALID = frozenset('abcdefABCDEF')\n\ndef fishex(s):\n return reduce(lambda b, c: b ^ c, (int(a, 16) for a in s if a in VALID), 0)", "def fishex(name):\n hexdict = {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}\n res = 0\n for c in name.upper():\n if c in hexdict:\n res ^= hexdict[c]\n return res", "def fishex(name):\n hexx = {'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15}\n name = name.lower()\n result = 0\n for i in name:\n if i in hexx:\n result = result ^ hexx[i]\n return result", "from functools import reduce\n\ndef fishex(name):\n hex = ['a', 'b', 'c', 'd', 'e', 'f']\n hexFish = []\n for i in name.lower():\n if i in hex:\n hexFish.append(i)\n hexList = [int(x, 16) for x in hexFish]\n if hexList != []:\n hexValue = hexList[0]\n else:\n return 0\n hexValue = reduce(lambda x, y: x ^ y, hexList)\n return hexValue", "from functools import reduce\nfishex = lambda s: reduce(lambda x, y: x ^ y, [int(i, 16) for i in s if i in 'ABCDEFabcdef'] or [0])", "from functools import reduce\nfrom operator import xor\n\ndef fishex(name):\n return reduce(xor, (int(x, 16) for x in name.lower() if 'a' <= x <= 'f'), 0)", "from functools import reduce\nfrom operator import xor\n\ndef fishex(name):\n s = set('abcdef')\n return reduce(xor, map(lambda c: int(c, 16), (c for c in name.lower() if c in s)), 0)", "def fishex(name):\n return eval('^'.join(['0x' + c for c in name.lower() if c in 'abcdef'])) if name else 0", "from operator import xor\nfrom functools import reduce\n\ndef fishex(name):\n return reduce(xor, (ord(c) - 87 for c in name.lower() if c in 'abcdef'), 0)", "from functools import reduce\n\ndef fishex(name, l={'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15, 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}):\n return reduce(lambda acc, x: acc ^ l.get(x, 0), name, 0)", "fishex = f = lambda s: len(s) and (s[0] in 'abcdefABCDEF' and int(s[0], 16)) ^ f(s[1:])", "from functools import reduce\nfishex = lambda name: reduce(lambda a, b: a ^ b, [int(l, 16) if l in 'abcdef' else 0 for l in name.lower()], 0)"], "starter_code": "def fishex(name):\n", "input_output": {"fn_name": "fisHex", "inputs": [["pufferfish"], ["puffers"], ["balloonfish"], ["blowfish"], ["bubblefish"], ["globefish"], ["swellfish"], ["toadfish"], ["toadies"], ["honey toads"], ["sugar toads"], ["sea squab"], [""], ["Aeneus corydoras"], ["African glass catfish"], ["African lungfish"], ["Aholehole"], ["Airbreathing catfish"], ["Airsac catfish"], ["Alaska blackfish"], ["Albacore"], ["Alewife"], ["Alfonsino"], ["Algae eater"], ["Alligatorfish"], ["Asian carps"], ["Asiatic glassfish"], ["Atka mackerel"], ["Atlantic cod"], ["Atlantic herring"], ["Atlantic salmon"], ["Atlantic saury"], ["Atlantic silverside"], ["Australasian salmon"], ["Australian grayling"], ["Australian herrin"], ["Australian lungfish"], ["Australian prowfish"], ["Ayu"]], "outputs": [[1], [14], [14], [4], [10], [10], [1], [8], [9], [9], [13], [5], [0], [1], [0], [12], [10], [12], [5], [8], [9], [5], [5], [4], [15], [6], [9], [6], [13], [2], [6], [6], [1], [10], [0], [4], [5], [5], [10]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5714eb80e1bf814e53000c06", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "fishex", "task_id": "TACO_lite/384", "example": [[["redlionfish"]], ["12"]]} +{"requirement": "Given an array of integers `a` and integers `t` and `x`, count how many elements in the array you can make equal to `t` by **increasing** / **decreasing** it by `x` (or doing nothing).\n*EASY!*\n\n```python\n# ex 1\n\na = [11, 5, 3]\nt = 7\nx = 2\n\ncount(a, t, x) # => 3\n```\n- you can make 11 equal to 7 by subtracting 2 twice\n- you can make 5 equal to 7 by adding 2\n- you can make 3 equal to 7 by adding 2 twice\n\n```python\n# ex 2\n\na = [-4,6,8]\nt = -7\nx = -3\n\ncount(a, t, x) # => 2\n```\n\n## Constraints\n**-10^(18) <= a[i],t,x <= 10^(18)**\n\n**3 <= |a| <= 10^(4)**", "solutions": ["def count(a, t, x):\n return sum((not (t - v) % x if x else t == v for v in a))", "count = lambda a, t, x: sum((x and (not (e - t) % x) or e - t == 0 for e in a))", "def count(a, t, x):\n return sum(((t - i) % x == 0 for i in a)) if x else sum((i == t for i in a))", "def count(a, t, x):\n if x == 0:\n return a.count(t)\n return sum(((t - e) % x == 0 for e in a))", "def count(A, t, x):\n return sum((a % x == t % x for a in A)) if x else sum((a == t for a in A))", "def count(lst, target, mod):\n if mod == 0:\n return lst.count(target)\n return sum(((n - target) % mod == 0 for n in lst))", "def count(a, t, x):\n return sum((1 for n in a if (n % x == t % x if x else n == t)))", "def count(a, t, x):\n result = 0\n for n in a:\n if n == t or (x != 0 and (n - t) % x == 0):\n result += 1\n return result", "count = lambda a, t, x: sum(((e - t) % x == 0 if x != 0 else e - t == 0 for e in a))"], "starter_code": "def count(a, t, x):\n", "input_output": {"fn_name": "count", "inputs": [[[11, 5, 3], 7, 2], [[-4, 6, 8], -7, -3]], "outputs": [[3], [2]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5d1e1560c193ae0015b601a2", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "count", "task_id": "TACO_lite/391", "example": [[[[11, 5, 3], 7, 2], [[-4, 6, 8], -7, -3]], ["3", "2"]]} +{"requirement": "You are given an array A of integers of length N. You need to calculate factorial of each number. The answer can be very large, so print it modulo 10^{9 }+ 7.\n \nExample 1:\nInput:\nN = 5\nA[] = {0, 1, 2, 3, 4}\nOutput:\n1 1 2 6 24\nExplanation:\nFactorial of 0 is 1, \nfactorial of 1 is 1, factorial of 2 is 2, \nfactorial of 3 is 6 and so on.\nExample 2:\nInput:\nN = 3\nA[] = {5, 6, 3}\nOutput:\n120 720 6\nExplanation:\nFactorial of 5 is 120, \nfactorial of 6 is 720, \nfactorial of 3 is 6.\nYour Task:\nComplete the function factorial() which takes list a and single integer n, as input parameters and returns a list of factorials of the numbers in the list a.\nExpected Time Complexity: O(max(A) + N)\nExpected Auxiliary Space: O(max(A))\nConstraints:\n1 <= N <= 10^{5}\n0 <= A[i] <= 10^{5}", "solutions": ["def factorial(a, n):\n m = 10 ** 9 + 7\n ans = []\n maxi = max(a)\n dp = [1] * (maxi + 1)\n for i in range(2, maxi + 1):\n dp[i] = i * dp[i - 1] % m\n for i in a:\n ans.append(dp[i])\n return ans", "def factorial(a, n):\n result = []\n fact_dict = {}\n maximum = a[0]\n m = 10 ** 9 + 7\n for i in range(1, n):\n maximum = max(maximum, a[i])\n fact_dict[0] = 1\n fact_dict[1] = 1\n for j in range(2, maximum + 1):\n fact_dict[j] = j * fact_dict[j - 1] % m\n for i in range(n):\n result.append(fact_dict[a[i]])\n return result", "import math as m\n\ndef factorial(a, n):\n mod = 1000000007\n fact = [1] * (max(a) + 1)\n for i in range(2, max(a) + 1):\n fact[i] = fact[i - 1] * i % mod\n result = []\n for i in range(n):\n result.append(fact[a[i]])\n return result", "def factorial(a, n):\n ans = [1, 1]\n m = 1000000007\n current = 1\n for i in range(2, max(a) + 1):\n current *= i\n current %= m\n ans.append(current)\n x = []\n for i in a:\n x.append(ans[i])\n return x", "def factorial(a, n):\n maxi = max(a)\n d = dict()\n prod = 1\n for i in range(0, maxi + 1):\n prod = prod * max(i, 1) % (10 ** 9 + 7)\n d[i] = prod\n ans = []\n for num in a:\n ans.append(d[num])\n return ans", "def factorial(a, n):\n m = 10 ** 9 + 7\n arr = [0] * (max(a) + 1)\n arr[0] = 1\n for i in range(1, len(arr)):\n arr[i] = i * arr[i - 1] % m\n for i in range(n):\n a[i] = arr[a[i]]\n return a", "0\n\ndef factorial(a, n):\n m = 10 ** 9 + 7\n ans = []\n maxi = max(a)\n fact = [1, 1]\n f = 1\n for i in range(2, maxi + 1):\n f *= i\n f %= m\n fact.append(f)\n for i in a:\n ans.append(fact[i])\n return ans", "def factorial(a, n):\n mod = int(1000000000.0 + 7)\n m = max(a)\n if m == 0:\n return 1\n dp = [0] * (m + 1)\n dp[0] = 1\n for i in range(1, m + 1):\n dp[i] = dp[i - 1] * i\n dp[i] = dp[i] % mod\n for i in range(n):\n a[i] = dp[a[i]]\n return a", "def factorial(a, n):\n facts = [1]\n maxA = 0\n for i in a:\n maxA = max(maxA, i)\n f = 1\n mod = 10 ** 9 + 7\n for i in range(1, maxA + 1):\n f *= i\n f %= mod\n facts.append(f)\n res = []\n for i in a:\n res.append(facts[i])\n return res", "def factorial(a, n):\n d = {}\n MOD = 1000000007\n for i in range(n):\n d[a[i]] = 1\n m = max(a)\n ans = 1\n for i in range(1, m + 1):\n ans = ans * i % MOD\n if i in d.keys():\n d[i] = ans\n for i in range(n):\n a[i] = d[a[i]]\n return a", "def factorial(a, n):\n m = max(a)\n f = [1]\n for i in range(1, m + 1):\n f.append(f[-1] * i % (10 ** 9 + 7))\n res = []\n for i in a:\n res.append(f[i])\n return res", "def factorial(a, n):\n m = 1000000000.0 + 7\n mx = max(a)\n dp = [0] * (mx + 1)\n dp[0:3] = [1, 1, 2]\n for i in range(3, mx + 1):\n dp[i] = int(i * dp[i - 1] % m)\n res = [0] * n\n for i in range(n):\n res[i] = dp[a[i]]\n return res", "def factorial(a, n):\n maximum = max(a)\n res = []\n dp = [1] * (maximum + 1)\n for i in range(1, maximum + 1):\n dp[i] = i * dp[i - 1] % 1000000007\n for val in a:\n res.append(dp[val])\n return res", "def factorial(a, n):\n a1 = {0: 1}\n a2 = max(a)\n p = 1\n for i in range(1, a2 + 1):\n p *= i\n p %= 1000000007\n a1[i] = p\n d = []\n for i in a:\n d.append(a1[i])\n return d", "def factorial(a, n):\n arr = [1]\n output = []\n for item in a:\n while item > len(arr) - 1:\n arr.append(arr[-1] * len(arr) % (10 ** 9 + 7))\n output.append(arr[item])\n return output", "def factorial(a, n):\n d2 = {}\n mx = -1\n for x in a:\n d2[x] = 1\n mx = max(mx, x)\n d = {0: 1}\n s = 1\n for x in range(1, mx + 1):\n s = s * x % 1000000007\n if d2.get(x):\n d[x] = s\n l = []\n for x in a:\n l.append(d.get(x))\n return l", "def __init__():\n self.dp = dict()\n\ndef factorial(a, n):\n self.dp.clear()\n self.dp = {0: 1}\n m = max(a)\n a_ = {x: 1 for x in a}\n i = 1\n for x in range(1, m + 1):\n i = i * x % (10 ** 9 + 7)\n if a_.get(x) == 1:\n self.dp[x] = i\n return [self.dp[x] for x in a]", "def factorial(a, n):\n res = list()\n maxi = max(a)\n dp = [1] * (maxi + 1)\n mod = 10 ** 9 + 7\n for i in range(1, maxi + 1):\n dp[i] = i * dp[i - 1] % mod\n for val in a:\n res.append(dp[val])\n return res", "def factorial(a, n):\n hash = {0: 1}\n result = []\n max_val = max(a)\n fact = 1\n for i in range(1, max_val + 1):\n fact = fact * i % (pow(10, 9) + 7)\n hash[i] = fact\n for i in a:\n result.append(hash[i])\n return result", "def factorial(a, n):\n x = max(a)\n l = [1, 1]\n for i in range(2, x + 1):\n c = i * l[-1] % 1000000007\n l.append(c)\n for i in range(n):\n a[i] = l[a[i]]\n return a", "def factorial(a, n):\n MAX = 10 ** 5\n fac = [0] * (MAX + 1)\n mod = 10 ** 9 + 7\n fac[0] = 1\n for i in range(1, MAX + 1):\n fac[i] = fac[i - 1] % mod * i % mod\n ans = [0] * n\n for i in range(0, n):\n ans[i] = fac[a[i]]\n return ans", "def factorial(a, n):\n num = max(a)\n m = 1000000007\n fact = [0 for i in range(n)]\n dict_fact = dict()\n dict_fact[0] = 1\n for i in range(1, num + 1):\n dict_fact[i] = i * dict_fact[i - 1] % m\n for i in range(n):\n fact[i] = dict_fact[a[i]]\n return fact", "def factorial(a, n):\n m = max(a)\n mo = 1000000007\n dic = {}\n dic[0] = 1\n for i in range(1, m + 1):\n dic[i] = dic[i - 1] * i % mo\n for i in range(n):\n a[i] = dic[a[i]]\n return a", "def factorial(a, n):\n f = [1, 1]\n ans = 1\n MOD = 10 ** 9 + 7\n for i in range(2, 10 ** 5 + 5):\n ans = ans % MOD * i % MOD % MOD\n f.append(ans)\n ans = []\n for i in range(n):\n a[i] = f[a[i]]\n return a", "def factorial(a, n):\n maximum = -1\n arr = []\n for i in range(n):\n if a[i] > maximum:\n maximum = a[i]\n arr.append(1)\n for i in range(1, maximum + 1, 1):\n arr.append(arr[i - 1] * i % (10 ** 9 + 7))\n for i in range(n):\n a[i] = arr[a[i]]\n return a", "def factorial(a, n):\n maximum = max(a) + 1\n factdp = [1, 1]\n for i in range(2, maximum):\n factdp.append(i * factdp[-1] % 1000000007)\n for i in range(n):\n a[i] = factdp[a[i]]\n return a", "def factorial(a, n):\n fact = [1, 1]\n l = []\n for i in range(2, max(a) + 1):\n k = i * fact[i - 1] % self.m\n fact.append(k)\n for j in a:\n l.append(fact[j] % self.m)\n return l", "fac = [1]\nmod = 1000000007\nfor i in range(1, 100001):\n fac.append(fac[-1] % mod * i % mod)\n\ndef factorial(a, n):\n global fac\n result = []\n for i in a:\n result.append(fac[i])\n return result", "def factorial(a, n):\n N = max(a)\n d = {}\n (d[0], ans) = (1, 1)\n for i in range(1, N + 1):\n ans = ans * i\n ans = ans % 1000000007\n d[i] = ans\n for i in range(n):\n a[i] = d[a[i]]\n return a", "def factorial(a, n):\n maxi = max(a)\n ans = []\n dp = [1] * (maxi + 1)\n for i in range(1, maxi + 1):\n dp[i] = i * dp[i - 1] % 1000000007\n for val in a:\n ans.append(dp[val])\n return ans", "import math as m\n\ndef factorial(a, n):\n mx = max(a)\n fact = [1] * (mx + 1)\n ans = [] * n\n mod = 1000000000.0 + 7\n for i in range(1, mx + 1):\n fact[i] = fact[i - 1] * i % mod\n for i in a:\n ans.append(int(fact[i]))\n return ans", "def factorial(a, n):\n max_range = 10 ** 5\n fact = [0] * (max_range + 1)\n fact[0] = 1\n mod = 10 ** 9 + 7\n for i in range(1, max_range + 1):\n fact[i] = fact[i - 1] % mod * i % mod\n ans = [0] * n\n for i in range(n):\n ans[i] = fact[a[i]]\n return ans", "import math\n\ndef factorial(a, n):\n maximum = max(a)\n dp = [1] * (maximum + 1)\n for i in range(1, maximum + 1):\n dp[i] = i * dp[i - 1] % 1000000007\n return [dp[val] for val in a]", "def factorial(a, n):\n x = max(a)\n dp = [0] * (x + 1)\n dp[0] = 1\n dp[1] = 1\n for i in range(2, x + 1):\n dp[i] = i * dp[i - 1] % (10 ** 9 + 7)\n fans = []\n for i in a:\n fans.append(dp[i])\n return fans", "def __init__():\n self.facts = {}\n self.facts[0] = 1\n self.facts[1] = 1\n self.mod = 1000000007\n\ndef factorial(a, n):\n max_a = max(a)\n for i in range(2, max_a + 1):\n self.facts[i] = self.facts[i - 1] * i % self.mod\n return [self.facts[x] for x in a]", "def factorial(A, N):\n mx = max(A)\n dp = [0] * (mx + 1)\n dp[0] = 1\n dp[1] = 1\n dp[2] = 2\n mod = int(1000000000.0 + 7)\n for i in range(3, mx + 1):\n dp[i] = dp[i - 1] * i\n dp[i] %= mod\n ans = [0] * N\n for i in range(N):\n ans[i] = dp[A[i]]\n return ans", "import math\n\ndef factorial(a, n):\n l = []\n m = max(a)\n arr = [1] * (m + 1)\n for i in range(1, m + 1):\n arr[i] = i * arr[i - 1] % 1000000007\n for j in a:\n l.append(arr[j])\n return l", "def fact(num):\n f = 1\n for i in range(1, num + 1):\n f *= i\n return f\n\ndef factorial(a, n):\n fact = {}\n fact[0] = 1\n MAX = pow(10, 5)\n mod = pow(10, 9) + 7\n for i in range(1, MAX + 1):\n fact[i] = i * fact[i - 1] % mod\n for (i, ele) in enumerate(a):\n a[i] = fact[ele]\n return a", "def factorial(a, n):\n ans = [0] * n\n max = 0\n for i in range(n):\n if a[i] > max:\n max = a[i]\n size = max + 1\n fact = [None] * size\n fact[0] = 1\n for i in range(1, size):\n fact[i] = i * fact[i - 1] % 1000000007\n for i in range(n):\n ans[i] = fact[a[i]]\n return ans", "def factorial(a, n):\n maxEle = max(a)\n res = []\n fact = [1] * (maxEle + 1)\n for i in range(2, maxEle + 1):\n fact[i] = fact[i - 1] * i % 1000000007\n for i in a:\n res.append(fact[i])\n return res", "def factorial(a, n):\n maxm = max(a)\n t = [1] * (maxm + 1)\n res = []\n for i in range(1, maxm + 1):\n t[i] = i * t[i - 1] % (10 ** 9 + 7)\n for val in a:\n res.append(t[val])\n return res", "def factorial(a, n):\n f = [0] * 100002\n f[0] = 1\n f[1] = 1\n arr = []\n j = 2\n for i in a:\n if f[i] != 0:\n arr.append(f[i])\n else:\n while j <= i:\n f[j] = f[j - 1] * j % (10 ** 9 + 7)\n j = j + 1\n arr.append(f[i])\n return arr", "def factorial(a, n):\n m = {0: 1}\n p = 1\n g = max(a)\n for i in range(1, g + 1):\n p = p * i\n p = p % 1000000007\n m[i] = p\n b = []\n for i in a:\n b.append(m[i])\n return b"], "starter_code": "def factorial(a, n):\n", "input_output": {"inputs": ["N = 5\r\nA[] = {0, 1, 2, 3, 4}", "N = 3\r\nA[] = {5, 6, 3}"], "outputs": ["1 1 2 6 24", "120 720 6"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Arrays", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/large-factorial4721/1", "Expected Auxiliary Space": "O(max(A))", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(max(A) + N)", "entry_point": "factorial", "task_id": "TACO_lite/363", "example": [[], []]} +{"requirement": "Given an array of N integers and Q queries of indices, print the number of next greater elements(NGEs) to the right of the given index element. \nExample:\nInput: arr = [3, 4, 2, 7, 5, 8, 10, 6]\n queries = 2\n indices = [0, 5]\nOutput: 6, 1\nExplanation: \nThe next greater elements to the right of 3(index 0)\nare 4,7,5,8,10,6. \nThe next greater elements to the right of 8(index 5)\nis only 10.\nYour Task:\nYou don't need to read or print anything. Your task is to complete the function count_NGEs() which takes N, arr, queries and indices as the input parameter and returns a list NGEs[] where NGEs[i] stores the count of elements strictly greater than the current element (arr[indices[i]]) to the right of indices[i].\nExpected Time Complexity: O(N * queries).\nExpected Auxiliary Space: O(queries).\nConstraints:\n1 <= N <= 10^{4}\n1 <= arr[i] <= 10^{5}\n1 <= queries <= 100\n0 <= indices[i] <= N - 1", "solutions": ["def count_nges(N, arr, queries, indices):\n\n def nge(ind, arr, N, key):\n c = 0\n for i in range(ind, N):\n if arr[i] > key:\n c += 1\n return c\n st = []\n for i in indices:\n st.append(nge(i, arr, N, arr[i]))\n return st", "def count_nges(N, arr, queries, indices):\n\n def nge(ind, arr, N, key):\n cnt = 0\n for i in range(ind, N):\n if arr[i] > key:\n cnt += 1\n return cnt\n ans = []\n for i in indices:\n ans.append(nge(i, arr, N, arr[i]))\n return ans", "def count_nges(N, nums, queries, indices):\n\n def findNextGreaterNums(index):\n (curr, count) = (nums[index], 0)\n for i in range(index + 1, N):\n if nums[i] > curr:\n count += 1\n return count\n result = []\n for index in indices:\n result.append(findNextGreaterNums(index))\n return result", "def count_nges(N, arr, queries, indices):\n l = []\n n = len(arr)\n for i in range(queries - 1, -1, -1):\n c = 0\n for j in range(n - 1, indices[i], -1):\n if arr[indices[i]] < arr[j]:\n c = c + 1\n l.append(c)\n l.reverse()\n return l", "def count_nges(N, arr, queries, indices):\n res = [0 for _ in range(queries)]\n for i in range(queries):\n cnt = 0\n k = indices[i]\n for j in range(k + 1, N):\n if arr[k] < arr[j]:\n cnt += 1\n res[i] = cnt\n return res", "def count_nges(N, arr, queries, indices):\n list = []\n for x in range(len(indices)):\n max = arr[indices[x]]\n sum = 0\n for y in range(indices[x] + 1, N):\n if max < arr[y]:\n sum += 1\n list.append(sum)\n return list", "def count_nges(N, arr, queries, indices):\n great_arr = []\n for query in indices:\n great = 0\n for i in range(query + 1, N):\n if arr[i] > arr[query]:\n great += 1\n great_arr.append(great)\n return great_arr", "def count_nges(N, arr, queries, indices):\n res = []\n for i in indices:\n x = arr[i]\n count = 0\n for j in range(i + 1, N):\n if x < arr[j]:\n count += 1\n res.append(count)\n return res", "def count_nges(N, arr, queries, indices):\n ans = []\n i = 0\n while i < queries:\n j = indices[i]\n temp = arr[indices[i]]\n count = 0\n while j < N:\n if arr[j] > temp:\n count += 1\n j += 1\n i += 1\n ans.append(count)\n return ans", "def count_nges(N, arr, queries, indices):\n NGEs = []\n for index in indices:\n count = 0\n num = arr[index]\n for i in range(index + 1, len(arr)):\n if arr[i] > num:\n count += 1\n NGEs.append(count)\n return NGEs", "def count_nges(N, arr, queries, indices):\n for j in range(queries):\n t = indices[j]\n k = arr[t]\n c = 0\n for i in range(t + 1, N):\n if arr[i] > k:\n c += 1\n indices[j] = c\n return indices", "def count_nges(N, arr, queries, indices):\n a = []\n for i in range(queries):\n t = arr[indices[i]]\n count = 0\n for j in range(indices[i] + 1, N):\n if arr[j] > t:\n count += 1\n a.append(count)\n return a", "from collections import deque\n\ndef __init__():\n self.count = 0\n\ndef count_nges(N, arr, queries, indices):\n answer = []\n for i in range(queries):\n count = 0\n for j in range(indices[i] + 1, N):\n if arr[j] > arr[indices[i]]:\n count += 1\n answer.append(count)\n return answer", "def count_nges(N, arr, queries, indices):\n result = []\n for i in range(queries):\n count = 0\n for j in range(indices[i] + 1, len(arr)):\n if arr[j] > arr[indices[i]]:\n count += 1\n result.append(count)\n return result", "def count_nges(n, arr, queries, indices):\n result = []\n for index in indices:\n count = 0\n for i in range(index + 1, n):\n if arr[i] > arr[index]:\n count += 1\n result.append(count)\n return result", "def count_nges(N, arr, queries, indices):\n nxges = []\n for index in indices:\n nxg = 0\n for i in range(index + 1, N):\n if arr[index] < arr[i]:\n nxg += 1\n nxges.append(nxg)\n return nxges", "def count_nges(N, arr, queries, indices):\n ans = []\n for q in range(queries):\n ind = indices[q]\n count = 0\n for i in range(ind, N):\n if arr[ind] < arr[i]:\n count += 1\n ans.append(count)\n return ans", "def count_nges(N, arr, queries, indices):\n ans = []\n for indx in indices:\n cnt = 0\n for i in range(indx, N):\n cnt += arr[i] > arr[indx]\n ans.append(cnt)\n return ans", "def count_nges(n, arr, queries, indices):\n res = []\n for ind in indices:\n curr = arr[ind]\n c = 0\n for i in range(ind + 1, n):\n if curr < arr[i]:\n c += 1\n res.append(c)\n return res", "def count_nges(N, arr, queries, indices):\n ans = [0 for j in range(queries)]\n indx = 0\n while queries != 0:\n idx = indices.pop(0)\n cnt = 0\n for j in range(idx + 1, N):\n if arr[j] > arr[idx]:\n cnt += 1\n ans[indx] = cnt\n indx += 1\n queries -= 1\n return ans", "def count_nges(N, arr, queries, indices):\n ans = []\n for i in range(queries):\n index = indices[i]\n count = 0\n for j in range(index + 1, N):\n if arr[j] > arr[index]:\n count += 1\n ans.append(count)\n return ans", "def count_nges(n, arr, queries, indices):\n ans = []\n for q in indices:\n el = arr[q]\n cnt = 0\n for i in range(q, n):\n if arr[i] > el:\n cnt += 1\n ans.append(cnt)\n return ans", "def count_nges(N, arr, queries, indices):\n ans = []\n for i in indices:\n num = arr[i]\n count = 0\n for x in arr[i:]:\n if x > num:\n count += 1\n ans.append(count)\n return ans", "def count_nges(N, arr, queries, indices):\n res = []\n for i in range(queries):\n k = indices[i]\n count = 0\n for i in range(k + 1, len(arr)):\n if arr[i] > arr[k]:\n count += 1\n res.append(count)\n return res", "def count_nges(N, arr, M, indices):\n count = [0 for _ in range(M)]\n for i in range(M):\n for j in range(indices[i], N):\n if arr[j] > arr[indices[i]]:\n count[i] += 1\n return count", "def count_nges(N, arr, queries, indices):\n res = [0 for _ in range(queries)]\n for i in range(queries):\n idx = indices[i]\n count = 0\n for j in range(idx, N):\n if arr[j] > arr[idx]:\n count += 1\n res[i] = count\n return res", "def count_nges(n, arr, queries, indices):\n res = []\n for i in range(len(indices)):\n index = indices[i]\n count = 0\n for j in range(index, len(arr)):\n if arr[index] < arr[j]:\n count += 1\n res.append(count)\n return res", "def count_nges(N, arr, queries, indices):\n list1 = []\n for index in indices:\n count = 0\n val = arr[index]\n for i in range(index + 1, N):\n if arr[i] > val:\n count += 1\n else:\n continue\n list1.append(count)\n return list1", "def count_nges(N, arr, queries, indices):\n ls = []\n n = len(arr)\n for i in indices:\n cnt = 0\n for j in range(i + 1, n):\n if arr[j] > arr[i]:\n cnt += 1\n ls.append(cnt)\n return ls", "def count_nges(N, arr, queries, indices):\n count = []\n for i in indices:\n c = 0\n for e in range(i, N):\n if arr[i] < arr[e]:\n c = c + 1\n count.append(c)\n return count", "def count_nges(N, arr, q, ind):\n k = []\n for i in range(q):\n count = 0\n if ind[i] != N - 1:\n for j in range(ind[i] + 1, N):\n if arr[j] > arr[ind[i]]:\n count += 1\n k.append(count)\n return k", "def count_nges(n, arr, q, ind):\n ans = []\n for i in range(q):\n count = 0\n for j in range(ind[i] + 1, n):\n if arr[j] > arr[ind[i]]:\n count += 1\n ans.append(count)\n return ans", "def count_nges(N, arr, queries, indices):\n ans = []\n for (z, point) in enumerate(indices):\n temp = 0\n for i in range(point + 1, N):\n if arr[i] > arr[point]:\n temp += 1\n ans.append(temp)\n return ans", "def count_nges(N, arr, queries, indices):\n res = []\n for ind in indices:\n count = 0\n cur = arr[ind]\n for i in range(ind + 1, N):\n if arr[i] > cur:\n count += 1\n res.append(count)\n return res", "def count_nges(N, arr, queries, indices):\n ans = []\n for ind in indices:\n cnt = 0\n for i in range(N):\n if ind < i and arr[i] > arr[ind]:\n cnt += 1\n ans += [cnt]\n return ans", "def count_nges(N, arr, queries, indices):\n count_Arr = [-1] * queries\n for i in range(0, queries):\n count = 0\n for j in range(indices[i] + 1, len(arr)):\n if arr[indices[i]] < arr[j]:\n count += 1\n else:\n j += 1\n count_Arr[i] = count\n return count_Arr", "def count_nges(N, arr, queries, indices):\n l = []\n c = 0\n for i in indices:\n ind = i\n for j in arr[ind:]:\n if j > arr[ind]:\n c += 1\n l.append(c)\n c = 0\n return l", "def count(arr, B):\n ct = 0\n n = len(arr)\n for i in range(B, n):\n if arr[i] > arr[B]:\n ct += 1\n return ct\n\ndef count_nges(N, arr, queries, indices):\n n = len(indices)\n ans = [0] * n\n for i in range(n):\n ans[i] = count(arr, indices[i])\n return ans", "def count_nges(N, arr, queries, indices):\n res = []\n stack = []\n for i in range(queries):\n ind = indices[i]\n count = 0\n for j in range(ind + 1, len(arr)):\n if arr[j] > arr[ind]:\n count += 1\n res.append(count)\n return res", "def count_nges(N, arr, queries, indices):\n count = 0\n nge = []\n for g in range(queries):\n if N == 1:\n return [0] * queries\n for h in range(N - 1, indices[g], -1):\n if arr[h] > arr[indices[g]]:\n count += 1\n nge.append(count)\n count = 0\n return nge", "def count_nges(N, arr, queries, indices):\n ans = []\n for i in range(len(indices)):\n if indices[i] == len(arr) - 1:\n ans.append(0)\n else:\n ans.append(self.count_nge(indices[i], arr))\n return ans\n\ndef count_nge(index, arr):\n count = 0\n for i in range(index + 1, len(arr)):\n if arr[i] > arr[index]:\n count += 1\n return count", "def count_nges(N, arr, queries, indices):\n res = []\n for i in indices:\n ans = []\n for j in range(i, N):\n if arr[j] > arr[i]:\n ans.append(arr[j])\n res.append(len(ans))\n return res", "def count_nges(n, a, q, indices):\n ngr = []\n for idx in indices:\n cnt = 0\n for i in range(idx + 1, n):\n if a[i] > a[idx]:\n cnt += 1\n ngr.append(cnt)\n return ngr"], "starter_code": "def count_nges(N, arr, queries, indices):\n", "input_output": {"inputs": ["arr = [3, 4, 2, 7, 5, 8, 10, 6]\n queries = 2\n indices = [0, 5]"], "outputs": ["6, 1"]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/number-of-nges-to-the-right/1", "Expected Auxiliary Space": "O(queries).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N * queries).", "entry_point": "count_nges", "task_id": "TACO_lite/433", "example": [[[[3, 4, 2, 7, 5, 8, 10, 6], 2, [0, 5]]], ["(6, 1)"]]} +{"requirement": "In this kata the function returns an array/list of numbers without its last element. The function is already written for you and the basic tests pass, but random tests fail. Your task is to figure out why and fix it.\n\nGood luck!\n\nHint: watch out for side effects.\n\n~~~if:javascript\nSome good reading: [MDN Docs about arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)\n~~~\n~~~if:python\nSome good reading: [Python Lists](http://www.compciv.org/guides/python/fundamentals/lists-mutability/)\n~~~", "solutions": ["def without_last(lst):\n return lst[:-1]", "def without_last(lst):\n lst_copy = list(lst)\n lst_copy.pop()\n return lst_copy", "def without_last(lst):\n l = lst[:]\n l.pop()\n return l", "def without_last(lst):\n if len(lst) < 1:\n return lst\n return lst[:-1]", "from operator import itemgetter\nwithout_last = itemgetter(slice(0, -1))", "def without_last(lst):\n new = lst[:]\n new.pop()\n return new", "def without_last(lst):\n x = lst[:-1]\n return x"], "starter_code": "def without_last(lst):\n", "input_output": {"fn_name": "without_last", "inputs": [[[1, 2, 3, 4, 5]], [[9, 7, 6, 9]]], "outputs": [[[1, 2, 3, 4]], [[9, 7, 6]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Refactoring"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5a4ff3c5fd56cbaf9800003e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "without_last", "task_id": "TACO_lite/441", "example": [[[[1, 2, 3, 4]], [[5, 10, 15]]], ["[1, 2, 3]", "[5, 10]"]]} +{"requirement": "Given a non-negative number, return the next bigger polydivisible number, or an empty value like `null` or `Nothing`.\n\nA number is polydivisible if its first digit is cleanly divisible by `1`, its first two digits by `2`, its first three by `3`, and so on. There are finitely many polydivisible numbers.", "solutions": ["(d, polydivisible, arr) = (1, [], list(range(1, 10)))\nwhile arr:\n d += 1\n polydivisible.extend(arr)\n arr = [n for x in arr for n in range(-(-x * 10 // d) * d, (x + 1) * 10, d)]\n\ndef next_num(n):\n from bisect import bisect\n idx = bisect(polydivisible, n)\n if idx < len(polydivisible):\n return polydivisible[idx]", "def next_num(n):\n\n def dfs(m=0, i=0, fromZ=0):\n if m > n:\n yield m\n elif i < len(s):\n m *= 10\n for d in range(0 if fromZ else s[i], 10):\n if not (m + d) % (i + 1):\n yield from dfs(m + d, i + 1, fromZ or d > s[i])\n s = list(map(int, str(n)))\n ret = next(dfs(), None)\n if ret is None:\n s = [1] + [0] * len(s)\n ret = next(dfs(), None)\n return ret", "import requests\nfrom bisect import bisect\nMAGIC = [int(x) for x in requests.get('https://oeis.org/b144688.txt').text.split()[1::2]]\n\ndef next_num(n):\n return MAGIC[bisect(MAGIC, n)] if n < MAGIC[-1] else None", "def f(xs, i, changed):\n if i and int(''.join(map(str, xs[:i]))) % i:\n return\n if i == len(xs):\n return int(''.join(map(str, xs)))\n prev = xs[i]\n for x in range(0 if changed else prev, 10):\n xs[i] = x\n res = f(xs, i + 1, changed or x != prev)\n if res:\n return res\n xs[i] = prev\n\ndef next_num(n):\n res = f(list(map(int, str(n + 1))), 0, False)\n if res:\n return res\n s = '1' + '0' * len(str(n))\n return f(list(map(int, s)), 0, False)", "def next_num(n):\n mpl = 25\n lpn = 3608528850368400786036725\n if n >= lpn:\n return None\n nl = len(str(n))\n extend = {}\n for i in range(1, mpl + 2):\n if i % 10 == 0:\n extend[i] = {'0'}\n elif i % 5 == 0:\n extend[i] = {'0', '5'}\n elif i % 2 == 0:\n extend[i] = {'0', '2', '4', '6', '8'}\n else:\n extend[i] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}\n d = {1: {'1', '2', '3', '4', '5', '6', '7', '8', '9'}}\n for l in range(2, 2 + nl):\n d[l] = {p + i for i in extend[l] for p in d[l - 1] if int(p + i) % l == 0}\n d[1].add('0')\n if n >= max(map(int, d[nl])):\n return min(map(int, d[nl + 1]))\n else:\n for i in sorted(map(int, d[nl])):\n if i > n:\n return i", "def polydivisible(n):\n len_n = len(str(n))\n for i in range(1, len_n + 1):\n if n // 10 ** (len_n - i) % i != 0:\n return i\n else:\n return True\n\ndef next_num(n):\n n += 1\n while n <= 3608528850368400786036725:\n pr = polydivisible(n)\n if pr == True:\n return n\n else:\n len_n = len(str(n))\n num = 10 ** (len_n - pr)\n n = (n // num + 1) * num", "from bisect import bisect\nrec = lambda L, i: L and L + rec([y for x in L for y in range(10 * x, 10 * (x + 1)) if not y % i], i + 1)\npolys = rec(list(range(1, 10)), 2)\n\ndef next_num(n):\n try:\n return polys[bisect(polys, n)]\n except IndexError:\n return", "def find_polydivisible(digits_limit):\n numbers = []\n previous = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n digits = 2\n poly_for_digits = []\n while previous and digits <= digits_limit:\n numbers += previous\n for p in previous:\n for i in range(10):\n number = p * 10 + i\n if number % digits == 0:\n poly_for_digits.append(number)\n previous = poly_for_digits[:]\n poly_for_digits = []\n digits += 1\n return numbers\npolydivisibles = find_polydivisible(26)\n\ndef next_num(n):\n return next((p for p in polydivisibles if p >= n + 1), None)", "def next_num(n):\n n += 1\n while n <= 3608528850368400786036725:\n pr = ifpol(n)\n if pr == True:\n return n\n else:\n s = len(str(n))\n num = 10 ** (s - pr)\n n = (n // num + 1) * num\n\ndef ifpol(n):\n s = len(str(n))\n for i in range(1, s + 1):\n if n // 10 ** (s - i) % i != 0:\n return i\n return True", "def next_num(n):\n number = str(n + 1)\n\n def isNumPoly(number):\n for i in range(1, len(number) + 1):\n if not int(number[0:i]) % i == 0:\n return i\n return 0\n while int(number) < 3610000000000000000000000:\n where = isNumPoly(number)\n if where == 0:\n return int(number)\n badPiece = number[0:where]\n replacement = str(int(badPiece) + (where - int(badPiece) % where))\n number = replacement + '0' * len(number[where:])\n return None"], "starter_code": "def next_num(n):\n", "input_output": {"fn_name": "next_num", "inputs": [[0], [10], [11], [1234], [123220], [998], [999], [1234567890], [3608528850368400786036724], [3608528850368400786036725]], "outputs": [[1], [12], [12], [1236], [123252], [1020], [1020], [1236004020], [3608528850368400786036725], [null]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5e4a1a43698ef0002d2a1f73", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "next_num", "task_id": "TACO_lite/455", "example": [[[12], [123], [1]], ["123", "1296", "12"]]} +{"requirement": "We have an array of unique elements. A special kind of permutation is the one that has all of its elements in a different position than the original.\n\nLet's see how many of these permutations may be generated from an array of four elements. We put the original array with square brackets and the wanted permutations with parentheses. \n```\narr = [1, 2, 3, 4]\n (2, 1, 4, 3)\n (2, 3, 4, 1)\n (2, 4, 1, 3)\n (3, 1, 4, 2)\n (3, 4, 1, 2)\n (3, 4, 2, 1)\n (4, 1, 2, 3)\n (4, 3, 1, 2)\n (4, 3, 2, 1)\n _____________\nA total of 9 permutations with all their elements in different positions than arr\n```\n\nThe task for this kata would be to create a code to count all these permutations for an array of certain length.\n\nFeatures of the random tests:\n```\nl = length of the array\n10 ≤ l ≤ 5000\n```\n\nSee the example tests.\n\nEnjoy it!", "solutions": ["def all_permuted(n):\n (a, b) = (0, 1)\n for i in range(1, n):\n (a, b) = (b, (i + 1) * (a + b))\n return a", "from itertools import islice\n\ndef A000166():\n (a, b, n) = (1, 0, 1)\n while True:\n yield a\n (a, b) = (b, n * (a + b))\n n += 1\nall_permuted = dict(enumerate(islice(A000166(), 5000))).get", "subfactorial = [1, 0]\nfor n in range(1, 10 ** 4):\n subfactorial.append(n * (subfactorial[-1] + subfactorial[-2]))\nall_permuted = subfactorial.__getitem__", "def f(n):\n if n == 0:\n return 1\n else:\n return n * f(n - 1) + (1 if n % 2 == 0 else -1)\n\ndef all_permuted(array_length):\n return f(array_length)", "import math\n\ndef all_permuted(n):\n return n * all_permuted(n - 1) + (-1) ** n if n > 2 else n - 1", "from functools import lru_cache\n\ndef all_permuted(n):\n if n == 0:\n return 1\n if n == 1:\n return 0\n return (n - 1) * (all_permuted(n - 1) + all_permuted(n - 2))", "M = [1, 0]\nfor V in range(1, 9487):\n M.append(V * (M[V] + M[V - 1]))\nall_permuted = lambda Q: M[Q]", "def all_permuted(array_length):\n a = [1, 0]\n for x in range(2, array_length + 1):\n (a[0], a[1]) = (a[1], (x - 1) * (a[1] + a[0]))\n return a[1]", "all_permuted = a = lambda n: (0, 0, 1)[n] if n < 3 else n * a(n - 1) + (-1) ** n", "import math\n\ndef all_permuted(n):\n if n == 0:\n return 1\n return n * all_permuted(n - 1) + (-1) ** n"], "starter_code": "def all_permuted(n):\n", "input_output": {"fn_name": "all_permuted", "inputs": [[1], [4], [30]], "outputs": [[0], [9], [97581073836835777732377428235481]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Machine Learning", "Combinatorics", "Number Theory", "Performance"], "name": null, "source": "codewars", "tags": ["Number theory", "Combinatorics", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5b997b066c77d521880001bd", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "all_permuted", "task_id": "TACO_lite/442", "example": [[[[1, 2, 3, 4]]], ["9"]]} +{"requirement": "n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of passengers will:\n\nTake their own seat if it is still available, \nPick other seats randomly when they find their seat occupied \n\nWhat is the probability that the n-th person can get his own seat?\n \nExample 1:\nInput: n = 1\nOutput: 1.00000\nExplanation: The first person can only get the first seat.\nExample 2:\nInput: n = 2\nOutput: 0.50000\nExplanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).\n\n \nConstraints:\n\n1 <= n <= 10^5", "solutions": ["def nthpersongetsnthseat(n: int) -> float:\n return 1 / min(n, 2.0)", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return float(1)\n return float(0.5)", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1.0\n if n == 2:\n return 0.5\n return 0.5\n if n == 3:\n return 1 / 3 * 1 + 1 / 3 * 1 / 2 + 1 / 3 * 0\n if n == 4:\n return 1 / 4 * 1 + 1 / 4 * (1 / 3 * 1 + 1 / 3 * 1 / 2 + 1 / 3 * 0) + 1 / 4 * (1 / 3 * 1 + 1 / 3 * 1 + 1 / 3 * 0) + 1 / 4 * 0\n return 1 / n * 1 + (n - 2) / n * self.nthpersongetsnthseat(n - 2) + 1 / n * 0", "import numpy as np\n\ndef nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n return 1 / 2", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n s = 0\n for i in range(1, n - 1):\n s += 0.5 / n\n return 1 / n + s", "def nthpersongetsnthseat(n: int) -> float:\n res = 1.0\n cur = 1.0\n for i in range(2, n + 1):\n res = 1 / i * cur\n cur += res\n return res", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n if n == 2:\n return 0.5\n dp = [0] * n\n dp[0] = 1 / n\n for i in range(1, n - 1):\n dp[i] = 0.5 / n\n return sum(dp)", "def nthpersongetsnthseat(n: int) -> float:\n i = 0\n if n == 1:\n return 1\n notCorrect = 1 / n\n for i in range(1, n - 1):\n notCorrect *= 1.0 + 1.0 / (n - i)\n return 1 - notCorrect", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1.0\n sum_results = 0.0\n for i in range(2, n + 1):\n p = 1 / i * (1 + sum_results)\n sum_results += p\n return p", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n return 1 / 2", "def nthpersongetsnthseat(n: int) -> float:\n mem = {}\n mem[1] = 1.0\n mem[2] = 0.5\n for i in range(3, n + 1):\n mem[i] = mem[i - 1]\n return mem[n]", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1.0\n if n == 2:\n return 0.5\n dp = [1.0, 0.5]\n acc = 1.5\n for i in range(3, n + 1):\n dp.append(acc / i)\n acc += dp[-1]\n return dp[-1]", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n if n == 2:\n return 0.5\n result = 1.0\n curr = 1.0\n for i in range(2, n + 1):\n result = 1 / i * curr\n curr += result\n return result", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n good = 0\n left = n\n uncenrtain = 1\n while left >= 2:\n good += uncenrtain / left\n uncenrtain = uncenrtain * (left - 2) / left\n left -= 1\n return good", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n else:\n dp = [0 for _ in range(n + 1)]\n dp[n] = 1 / n\n for i in range(n - 1, 1, -1):\n dp[i] = dp[i + 1] / i + dp[i + 1]\n return dp[2]", "def nthpersongetsnthseat(n: int) -> float:\n p = [None, 1.0, 0.5]\n for i in range(2, n):\n prob = (i * p[i] + p[i]) / (i + 1)\n p.append(prob)\n return p[n]", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n P = [None] * (n + 1)\n P[2] = 1 / n\n for i in range(3, n + 1):\n P[i] = P[i - 1] * (1 + 1 / (n - i + 2))\n return P[n]", "def nthpersongetsnthseat(n: int) -> float:\n D = [0] * n\n D[0] = 1.0\n for i in range(1, n):\n D[i] = 1 / (i + 1) + (i - 1) / (i + 1) * D[i - 1]\n return D[-1]", "import numpy as np\n\ndef nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n currentsum = 0\n else:\n currentsum = 1 / n\n for i in range(2, n):\n currentsum = currentsum + currentsum / (n - i + 1)\n return 1 - currentsum", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n pick = [1] + [0] * (n - 2) + [1]\n prob = 0\n for i in range(n - 2, 0, -1):\n left = n - i\n pick[i] = 1 / left + (left - 2) / left * pick[i + 1]\n prob += pick[i]\n return (prob + 1) / n"], "starter_code": "def nthpersongetsnthseat(n: int) -> float:\n", "input_output": {"fn_name": "nthPersonGetsNthSeat", "inputs": [[1]], "outputs": [1.0]}, "difficulty": "MEDIUM", "raw_tags": ["Math", "Dynamic Programming", "Brainteaser", "Probability and Statistics"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Mathematics", "Probability"], "skill_types": ["Dynamic programming"], "url": "https://leetcode.com/problems/airplane-seat-assignment-probability/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "nthpersongetsnthseat", "task_id": "TACO_lite/475", "example": [[[1], [2]], ["1.0", "0.5"]]} +{"requirement": "Given two strings, the first being a random string and the second being the same as the first, but with three added characters somewhere in the string (three same characters),\n\nWrite a function that returns the added character\n\n### E.g\n\n```\nstring1 = \"hello\"\nstring2 = \"aaahello\"\n\n// => 'a'\n```\n\nThe above is just an example; the characters could be anywhere in the string and string2 is actually **shuffled**.\n\n### Another example\n\n```\nstring1 = \"abcde\"\nstring2 = \"2db2a2ec\"\n\n// => '2'\n```\n\nNote that the added character could also exist in the original string\n\n\n```\nstring1 = \"aabbcc\"\nstring2 = \"aacccbbcc\"\n\n// => 'c'\n```\n\nYou can assume that string2 will aways be larger than string1, and there will always be three added characters in string2.\n\n```if:c\nWrite the function `added_char()` that takes two strings and return the added character as described above.\n```\n\n```if:javascript\nWrite the function `addedChar()` that takes two strings and return the added character as described above.\n```", "solutions": ["from collections import Counter\n\ndef added_char(s1, s2):\n return next((Counter(s2) - Counter(s1)).elements())", "def added_char(s1, s2):\n for i in s2:\n if s1.count(i) != s2.count(i):\n return i", "from functools import reduce\nfrom operator import xor\n\ndef added_char(s1, s2):\n return chr(reduce(xor, map(ord, s1), 0) ^ reduce(xor, map(ord, s2), 0))", "from collections import Counter\n\ndef added_char(s1, s2):\n return list(Counter(s2) - Counter(s1))[0]", "from collections import Counter\n\ndef added_char(s1, s2):\n return (Counter(s2) - Counter(s1)).popitem()[0]", "def added_char(s1, s2):\n s2 = list(s2)\n [s2.remove(i) for i in s1]\n return s2[0]", "from collections import Counter\n\ndef added_char(*args):\n (c1, c2) = map(Counter, args)\n return (c2 - c1).popitem()[0]", "added_char = lambda s1, s2: next((i for i in s2 if s1.count(i) != s2.count(i)))", "def added_char(s1, s2):\n return chr(int((sum((ord(x) for x in s2)) - sum((ord(x) for x in s1))) / 3))"], "starter_code": "def added_char(s1, s2):\n", "input_output": {"fn_name": "added_char", "inputs": [["hello", "checlclo"], ["aabbcc", "aacccbbcc"], ["abcde", "2db2a2ec"]], "outputs": [["c"], ["c"], ["2"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Logic"], "name": null, "source": "codewars", "tags": ["String algorithms"], "skill_types": [], "url": "https://www.codewars.com/kata/5971b219d5db74843a000052", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "added_char", "task_id": "TACO_lite/468", "example": [[["hello", "aaahello"], ["abcde", "2db2a2ec"], ["aabbcc", "aacccbbcc"]], ["a", "2", "c"]]} +{"requirement": "Given an infinite supply of each denomination of Indian currency { 1, 2, 5, 10, 20, 50, 100, 200, 500, 2000 } and a target value N.\nFind the minimum number of coins and/or notes needed to make the change for Rs N. You must return the list containing the value of coins required. \nExample 1:\nInput: N = 43\nOutput: 20 20 2 1\nExplaination: \nMinimum number of coins and notes needed \nto make 43. \nExample 2:\nInput: N = 1000\nOutput: 500 500\nExplaination: minimum possible notes\nis 2 notes of 500.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function minPartition() which takes the value N as input parameter and returns a list of integers in decreasing order.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 ≤ N ≤ 10^{6}", "solutions": ["def minpartition(n):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n l = []\n i = len(coins) - 1\n while n != 0 and i >= 0:\n if coins[i] > n:\n i -= 1\n else:\n n -= coins[i]\n l.append(coins[i])\n return l", "def minpartition(N):\n currency = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n i = len(currency) - 1\n res = []\n while i >= 0 and N != 0:\n if N >= currency[i]:\n quotient = N // currency[i]\n res += [currency[i]] * quotient\n N -= currency[i] * quotient\n i -= 1\n return res", "def minpartition(N):\n arr = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n count = []\n while N != 0:\n for coin in arr:\n if coin <= N:\n n = N // coin\n N = N - N // coin * coin\n for i in range(n):\n count.append(coin)\n return count", "def minpartition(N):\n set_list = [None] * N\n coins = {1, 2, 5, 10, 20, 50, 100, 200, 500, 2000}\n\n def find_min_set(coins, set_list, n):\n min_set = []\n min_set_len = float('Inf')\n for coin in coins:\n if coin == n:\n cur_set = [coin]\n cur_set_len = 1\n elif coin < n:\n diff = n - coin\n cur_set = set_list[diff - 1] + [coin]\n cur_set_len = len(set_list[diff - 1]) + 1\n else:\n continue\n if cur_set_len < min_set_len:\n min_set_len = cur_set_len\n min_set = cur_set\n min_set.sort(reverse=True)\n set_list[n - 1] = min_set\n for i in range(N):\n find_min_set(coins, set_list, i + 1)\n return set_list[N - 1]", "def minpartition(N):\n money = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n result = []\n for i in range(9, -1, -1):\n result += [money[i]] * (N // money[i])\n N = N % money[i]\n if N == 0:\n break\n return result", "def minpartition(N):\n l = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n i = 0\n a = []\n while i < len(l):\n if l[i] > N:\n i += 1\n else:\n a.append(l[i])\n N -= l[i]\n return a", "def minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n res = []\n for i in range(len(coins) - 1, -1, -1):\n while N >= coins[i]:\n N -= coins[i]\n res.append(coins[i])\n return res", "def minpartition(sm):\n (arr, out) = ([1, 2, 5, 10, 20, 50, 100, 200, 500, 2000][::-1], [])\n for i in arr:\n if sm // i > 0:\n out.extend([i] * (sm // i))\n sm -= i * (sm // i)\n return out", "def minpartition(amount):\n denominations = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n n = len(denominations)\n i = n - 1\n ans = []\n while i >= 0:\n if amount < denominations[i]:\n i -= 1\n elif amount == denominations[i]:\n ans.append(denominations[i])\n break\n else:\n ans.append(denominations[i])\n amount -= denominations[i]\n return ans", "def minpartition(N):\n p = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n ans = []\n for i in range(N):\n for i in p:\n if N >= i:\n ans.append(i)\n N = N - i\n break\n if N == 0:\n break\n return ans", "def minpartition(N):\n u = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n u = u[::-1]\n i = 0\n v = []\n while N != 0:\n if N >= u[i]:\n N = N - u[i]\n v.append(u[i])\n else:\n i += 1\n return v", "def minpartition(N):\n x = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n list = []\n while N != 0:\n for e in range(10):\n if x[e] <= N:\n N = N - x[e]\n list.append(x[e])\n break\n return list", "def minpartition(N):\n coins = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n ans = []\n i = 0\n while i < len(coins) or N <= 0:\n while i < len(coins) and coins[i] > N:\n i += 1\n if i >= len(coins):\n break\n N -= coins[i]\n ans.append(coins[i])\n return ans", "def minpartition(N):\n coinsList = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n coinsList = coinsList[::-1]\n coins = []\n while N > 0:\n for coin in coinsList:\n if N >= coin:\n coins.append(coin)\n N -= coin\n break\n return coins", "import math\n\ndef minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n coins.sort(reverse=True)\n ans = []\n for coin in coins:\n if coin > N or N <= 0:\n continue\n div = math.floor(N / coin)\n for i in range(div):\n ans.append(coin)\n N -= coin * div\n return ans", "def minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n while N > 0:\n for i in range(9, -1, -1):\n num = N // coins[i]\n ans += [coins[i]] * num\n N = N % coins[i]\n return ans", "def minpartition(N):\n ans = []\n arr = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n for x in arr:\n coin = N // x\n ans += [x] * coin\n N = N % x\n return ans", "import bisect\n\ndef minpartition(N):\n arr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n i = 9\n while i >= 0:\n if N >= arr[i]:\n ans.append(arr[i])\n N -= arr[i]\n else:\n i -= 1\n if N <= 0:\n break\n return ans", "import bisect\n\ndef minpartition(N):\n arr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n while N > 0:\n idx = bisect.bisect(arr, N)\n ans.append(arr[idx - 1])\n N -= arr[idx - 1]\n return ans", "def minpartition(N):\n curr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n n = len(curr)\n ans = []\n for i in range(n - 1, -1, -1):\n while N >= curr[i]:\n N -= curr[i]\n ans.append(curr[i])\n return ans", "def minpartition(N):\n denom = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ind = len(denom) - 1\n out = []\n while N and ind > -1:\n val = N // denom[ind]\n if val:\n N -= val * denom[ind]\n out.extend([denom[ind]] * val)\n ind -= 1\n return out", "def minpartition(N):\n notes = []\n coinsIdx = 0\n while N and coinsIdx < len(Solution.coins):\n noteNums = N // Solution.coins[coinsIdx]\n N = N % Solution.coins[coinsIdx]\n for i in range(noteNums):\n notes.append(Solution.coins[coinsIdx])\n coinsIdx += 1\n return notes", "def minpartition(N):\n ans = []\n l1 = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n for i in l1:\n k = N // i\n ans.extend([i] * k)\n N = N - k * i\n return ans", "def minpartition(N):\n target = N\n ar = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ar = ar[::-1]\n ans = []\n for coin in ar:\n n = target // coin\n ans.extend([coin] * n)\n target -= n * coin\n if target == 0:\n break\n return ans", "def minpartition(N):\n brr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n brr = brr[::-1]\n ans = []\n for i in range(len(brr)):\n if brr[i] <= N:\n for j in range(N // brr[i]):\n ans.append(brr[i])\n N = N % brr[i]\n return ans", "def minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n res = []\n idx = len(coins) - 1\n while N:\n if coins[idx] <= N:\n count = N // coins[idx]\n res += [coins[idx]] * count\n N -= coins[idx] * count\n else:\n idx -= 1\n return res", "def minpartition(N):\n indian_denomination = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n coins_used = []\n for denom in reversed(indian_denomination):\n while denom <= N:\n coins_used.append(denom)\n N = N - denom\n if N == 0:\n break\n return coins_used", "def minpartition(N):\n coins_available = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n rem_money = N\n ans = []\n i = 0\n while rem_money != 0 and i < len(coins_available):\n if coins_available[i] <= rem_money:\n rem_money -= coins_available[i]\n ans.append(coins_available[i])\n if rem_money >= coins_available[i]:\n pass\n else:\n i += 1\n else:\n i += 1\n return ans", "def minpartition(N):\n lt = []\n cur = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n x = 0\n for i in range(10):\n if cur[i] > N:\n break\n x = i\n while N > 0:\n if N < cur[x]:\n x -= 1\n else:\n lt.append(cur[x])\n N -= cur[x]\n return lt", "def minpartition(N):\n d = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n res = []\n i = len(d) - 1\n while i >= 0:\n while N >= d[i]:\n N -= d[i]\n res.append(d[i])\n i -= 1\n return res", "def minpartition(N):\n currency = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n n = len(currency)\n target = N\n i = n - 1\n out = []\n while i >= 0:\n curr = currency[i]\n if target >= curr:\n target = target - curr\n out.append(curr)\n else:\n i -= 1\n return out", "def minpartition(N):\n changes = []\n while N:\n if N >= 2000:\n changes.append(2000)\n N = N - 2000\n elif N >= 500:\n changes.append(500)\n N = N - 500\n elif N >= 200:\n changes.append(200)\n N = N - 200\n elif N >= 100:\n changes.append(100)\n N = N - 100\n elif N >= 50:\n changes.append(50)\n N = N - 50\n elif N >= 20:\n changes.append(20)\n N = N - 20\n elif N >= 10:\n changes.append(10)\n N = N - 10\n elif N >= 5:\n changes.append(5)\n N = N - 5\n elif N >= 2:\n changes.append(2)\n N = N - 2\n elif N >= 1:\n changes.append(1)\n N = N - 1\n return changes", "def minpartition(N):\n coins = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n ans = []\n idx = 0\n while N and idx < len(coins):\n if coins[idx] > N:\n idx += 1\n else:\n N -= coins[idx]\n ans.append(coins[idx])\n return ans", "def __init__():\n self.res = []\n\ndef solve(arr, N, summ, ct, dp):\n if summ == 0:\n self.res.append(ct)\n return 1\n if summ < 0:\n return 0\n if dp[N][summ] != -1:\n return dp[N][summ]\n if summ - arr[N - 1] >= 0:\n ct.append(arr[N - 1])\n dp[N][summ] = self.solve(arr, N, summ - arr[N - 1], ct, dp) or self.solve(arr, N - 1, summ, ct, dp)\n else:\n dp[N][summ] = self.solve(arr, N - 1, summ, ct, dp)\n return dp[N][summ]\n\ndef minpartition(N):\n if N <= 0:\n return 0\n arr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n dp = [[-1 for i in range(N + 1)] for j in range(len(arr) + 1)]\n a = self.solve(arr, len(arr), N, [], dp)\n ind = 0\n if len(self.res) > 0:\n tot = sum(self.res[0])\n for i in range(1, len(self.res)):\n a = sum(self.res[i])\n if a > tot:\n tot = a\n ind = i\n return self.res[ind]", "def minpartition(N):\n arr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n curr = len(arr) - 1\n ans = []\n while N > 0:\n if arr[curr] <= N:\n ans.append(arr[curr])\n N = N - arr[curr]\n else:\n curr = curr - 1\n return ans", "def minpartition(N):\n currency = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n arr = []\n for i in currency:\n while N - i >= 0:\n arr.append(i)\n N -= i\n return arr", "def minpartition(N):\n deno = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n arr = []\n for d in deno:\n if N == 0:\n break\n while N >= d:\n arr.append(d)\n N -= d\n return arr", "def minpartition(n):\n l = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n l1 = []\n i = 0\n for i in range(10):\n while n >= l[i]:\n n = n - l[i]\n l1.append(l[i])\n i += 1\n return l1", "import math\n\ndef minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n s = len(coins)\n dp = [[math.inf] * (N + 1) for i in range(s + 1)]\n for i in range(1, s + 1):\n for j in range(1, N + 1):\n x = j % coins[i - 1]\n y = int(j / coins[i - 1])\n if x == 0:\n dp[i][j] = min(y, dp[i - 1][j])\n else:\n dp[i][j] = dp[i - 1][x] + y\n result = []\n curr = dp[s][N]\n j = N\n while N > 0:\n for i in range(1, s + 1):\n if dp[i][j] == curr:\n x = j % coins[i - 1]\n y = int(j / coins[i - 1])\n for k in range(y):\n result.append(coins[i - 1])\n curr = curr - y\n N = x\n j = x\n break\n return result", "def minpartition(N):\n deno = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n idx = 9\n while N != 0:\n if N >= deno[idx]:\n ans.append(deno[idx])\n N -= deno[idx]\n else:\n idx -= 1\n return ans", "currencies = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\nnum_currencies = len(currencies)\n\ndef minpartition(N):\n i = num_currencies - 1\n taken = []\n while i >= 0 and N > 0:\n while currencies[i] <= N:\n N -= currencies[i]\n taken.append(currencies[i])\n i -= 1\n return taken", "def minpartition(N):\n notes = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n size = len(notes)\n i = size - 1\n ans = list()\n while i >= 0:\n if notes[i] > N:\n i -= 1\n else:\n N -= notes[i]\n ans.append(notes[i])\n if N == 0:\n return ans\n return ans", "def minpartition(V):\n deno = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n n = len(deno)\n ans = []\n i = n - 1\n while i >= 0:\n while V >= deno[i]:\n V -= deno[i]\n ans.append(deno[i])\n i -= 1\n return ans", "def minpartition(N):\n if N == 1:\n return [1]\n notes = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n ans = []\n for note in notes:\n cnt = N // note\n if cnt:\n for j in range(cnt):\n ans.append(note)\n N = N % note\n return ans", "def minpartition(N):\n ans = []\n arr = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n while N != 0:\n for i in range(0, 10):\n a = N // arr[i]\n N = N % arr[i]\n for j in range(a):\n ans.append(arr[i])\n if N == 0:\n break\n return ans", "def minpartition(N):\n lst = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n sum1 = []\n for i in lst:\n if i > N:\n continue\n if N == 0:\n break\n s = N // i\n N = N % i\n sum1 += s * [i]\n return sum1", "def minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n i = 9\n while i >= 0:\n while N >= coins[i]:\n ans.append(coins[i])\n N -= coins[i]\n i -= 1\n if N == 0:\n return ans", "def minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n i = 9\n while i >= 0:\n change = N // coins[i]\n for coin in range(change):\n ans.append(coins[i])\n if change != 0:\n N = N % (coins[i] * change)\n i -= 1\n if N == 0:\n return ans", "def minpartition(N):\n arr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n res = []\n n = len(arr) - 1\n for i in range(n, -1, -1):\n if N == 0:\n break\n while N >= arr[i]:\n N -= arr[i]\n res.append(arr[i])\n return res", "def minpartition(N):\n ans = []\n lis = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n for i in lis:\n coin = N // i\n ans += [i] * coin\n N = N % i\n return ans", "def minpartition(N):\n curr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n i = len(curr) - 1\n ans = []\n while N != 0:\n if curr[i] <= N:\n x = N // curr[i]\n for j in range(x):\n ans.append(curr[i])\n N -= x * curr[i]\n i -= 1\n return ans", "def minpartition(N):\n result = []\n denomination = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n while N > 0:\n for i in range(len(denomination) - 1, -1, -1):\n if N >= denomination[i]:\n N = N - denomination[i]\n result.append(denomination[i])\n break\n return result", "def minpartition(N):\n result = []\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n coins.sort(reverse=True)\n while N:\n for coin in coins:\n if coin <= N:\n result.append(coin)\n N -= coin\n break\n return result", "def minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n amount = N\n i = len(coins) - 1\n while i >= 0:\n if coins[i] <= amount:\n break\n i -= 1\n out = []\n while amount > 0 and i >= 0:\n times = amount // coins[i]\n out = out + [coins[i]] * times\n amount = amount % coins[i]\n while i >= 0:\n if coins[i] <= amount:\n break\n i -= 1\n return out", "def minpartition(N):\n dict = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n\n def help(n, ans):\n if n == 0:\n return 0\n for i in range(len(dict) - 1, -1, -1):\n if dict[i] <= n:\n ans.append(dict[i])\n n -= dict[i]\n break\n help(n, ans)\n help(N, ans)\n return ans", "def minpartition(N):\n a = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n b = 0\n c = []\n for i in range(9, -1, -1):\n while b + a[i] <= N:\n b += a[i]\n c.append(a[i])\n return c", "def minpartition(N):\n l = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n l1 = []\n for i in l:\n if i <= N:\n l1.append(i)\n else:\n break\n l1.reverse()\n s = 0\n out = []\n i = 0\n while s <= N and i < len(l1):\n if s + l1[i] <= N:\n out.append(l1[i])\n s += l1[i]\n else:\n i += 1\n return out", "def minpartition(N):\n l = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n for i in range(-1, -11, -1):\n if N // l[i] != 0:\n ans += [l[i]] * (N // l[i])\n N %= l[i]\n return ans", "def minpartition(N):\n den = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n den.sort(reverse=True)\n ans = []\n i = 0\n while N > 0:\n if den[i] > N:\n i += 1\n continue\n N -= den[i]\n ans.append(den[i])\n return ans", "def minpartition(N):\n currency = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n i = 0\n ans = []\n while i < len(currency):\n if currency[i] > N:\n i += 1\n elif currency[i] == N:\n ans.append(currency[i])\n return ans\n elif currency[i] < N:\n N -= currency[i]\n ans.append(currency[i])\n return ans", "def minpartition(n):\n arr = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n ans = []\n for i in arr:\n temp = n // i\n ans += temp * [i]\n n -= temp * i\n return ans", "def minpartition(N):\n Coin = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n Cn = 10\n ans = []\n while N > 0:\n if Coin[Cn - 1] > N:\n Cn -= 1\n else:\n ans.append(Coin[Cn - 1])\n N -= Coin[Cn - 1]\n return ans", "def minpartition(N):\n op = []\n\n def amt_to_be_subtracted(N):\n k = 0\n curr = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n for note in curr:\n if note > N:\n k += 1\n return curr[k]\n while N != 0:\n minus = amt_to_be_subtracted(N)\n op.append(minus)\n N = N - minus\n return op", "def dyn(v):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000][::-1]\n result = []\n while v:\n for val in coins:\n if val <= v:\n result += [val] * (v // val)\n v -= val * (v // val)\n return result\n\ndef minpartition(N):\n return dyn(N)"], "starter_code": "def minpartition(N):\n", "input_output": {"inputs": ["N = 43", "N = 1000"], "outputs": ["20 20 2 1", "500 500"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming", "Greedy"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Greedy algorithms"], "skill_types": ["Dynamic programming", "Greedy algorithms"], "url": "https://practice.geeksforgeeks.org/problems/-minimum-number-of-coins4426/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "minpartition", "task_id": "TACO_lite/436", "example": [[], []]} +{"requirement": "In a given 2D binary array A, there are two islands.  (An island is a 4-directionally connected group of 1s not connected to any other 1s.)\nNow, we may change 0s to 1s so as to connect the two islands together to form 1 island.\nReturn the smallest number of 0s that must be flipped.  (It is guaranteed that the answer is at least 1.)\n \nExample 1:\nInput: A = [[0,1],[1,0]]\nOutput: 1\nExample 2:\nInput: A = [[0,1,0],[0,0,0],[0,0,1]]\nOutput: 2\nExample 3:\nInput: A = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]\nOutput: 1\n\n \nConstraints:\n\n2 <= A.length == A[0].length <= 100\nA[i][j] == 0 or A[i][j] == 1", "solutions": ["def shortestbridge(A: List[List[int]]) -> int:\n (m, n) = (len(A), len(A[0]))\n dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n queue = deque()\n boundary = set()\n found = False\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n A[i][j] = 2\n queue.append((i, j))\n while queue:\n (ci, cj) = queue.popleft()\n for (di, dj) in dirs:\n (ni, nj) = (ci + di, cj + dj)\n if 0 <= ni < m and 0 <= nj < n:\n if A[ni][nj] == 1:\n A[ni][nj] = 2\n queue.append((ni, nj))\n elif A[ni][nj] == 0:\n boundary.add((ci, cj))\n found = True\n break\n if found:\n break\n queue = deque(boundary)\n steps = 0\n while queue:\n for _ in range(len(queue)):\n (i, j) = queue.popleft()\n for (di, dj) in dirs:\n (ni, nj) = (i + di, j + dj)\n if 0 <= ni < m and 0 <= nj < n:\n if A[ni][nj] == 0:\n A[ni][nj] = 2\n queue.append((ni, nj))\n elif A[ni][nj] == 1:\n return steps\n steps += 1", "from collections import deque\n\ndef shortestbridge(A: List[List[int]]) -> int:\n q = deque()\n (m, n) = (len(A), len(A[0]))\n\n def explore_island(r, c):\n if not 0 <= r < m or not 0 <= c < n or A[r][c] == -1:\n return\n if A[r][c] == 1:\n A[r][c] = -1\n explore_island(r + 1, c)\n explore_island(r - 1, c)\n explore_island(r, c + 1)\n explore_island(r, c - 1)\n elif A[r][c] == 0:\n q.append((r, c, 1))\n\n def findFirst():\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n explore_island(i, j)\n return\n findFirst()\n while q:\n (cur_x, cur_y, cur_t) = q.popleft()\n for (i, j) in ((cur_x + 1, cur_y), (cur_x - 1, cur_y), (cur_x, cur_y + 1), (cur_x, cur_y - 1)):\n if 0 <= i < m and 0 <= j < n:\n if A[i][j] == 0:\n A[i][j] = -1\n q.append((i, j, cur_t + 1))\n elif A[i][j] == 1:\n return cur_t", "def shortestbridge(A: List[List[int]]) -> int:\n\n def dfs(i, j, n, m):\n A[i][j] = 2\n queue.append((i, j))\n directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n for (dx, dy) in directions:\n (x, y) = (i + dx, j + dy)\n if 0 <= x < n and 0 <= y < m and (A[x][y] == 1):\n dfs(x, y, n, m)\n from collections import deque\n queue = deque()\n (n, m) = (len(A), len(A[0]))\n for i in range(n):\n for j in range(m):\n if A[i][j] == 1:\n dfs(i, j, n, m)\n break\n else:\n continue\n break\n directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n step = 0\n while queue:\n size = len(queue)\n flag = False\n for i in range(size):\n point = queue.popleft()\n (x, y) = (point[0], point[1])\n for (dx, dy) in directions:\n (_x, _y) = (x + dx, y + dy)\n if _x < 0 or _x >= n or _y < 0 or (_y >= m) or (A[_x][_y] == 2):\n continue\n if A[_x][_y] == 1:\n return step\n A[_x][_y] = 2\n queue.append((_x, _y))\n step += 1", "def shortestbridge(A: List[List[int]]) -> int:\n\n def dfs(i, j):\n A[i][j] = -1\n bfs.append((i, j))\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= x < n and 0 <= y < n and (A[x][y] == 1):\n dfs(x, y)\n\n def first():\n for i in range(n):\n for j in range(n):\n if A[i][j]:\n return (i, j)\n (n, step, bfs) = (len(A), 0, [])\n dfs(*first())\n while bfs:\n new = []\n for (i, j) in bfs:\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= x < n and 0 <= y < n:\n if A[x][y] == 1:\n return step\n elif not A[x][y]:\n A[x][y] = -1\n new.append((x, y))\n step += 1\n bfs = new", "from queue import Queue\n\ndef valid(m, i, j):\n return 0 <= i < len(m) and 0 <= j < len(m[0])\n\ndef findAnIsland(m, e):\n stack = []\n for i in range(len(m)):\n for j in range(len(m[0])):\n if m[i][j] == 1 and (i, j) not in e:\n stack.append((i, j))\n break\n else:\n continue\n break\n (result, edges) = (set(), set())\n while stack:\n (ci, cj) = stack.pop()\n result.add((ci, cj))\n for (di, dj) in ((0, 1), (1, 0), (0, -1), (-1, 0)):\n (cdi, cdj) = (ci + di, cj + dj)\n if valid(m, cdi, cdj) and (cdi, cdj) not in e and ((cdi, cdj) not in result):\n if m[cdi][cdj] == 1:\n stack.append((cdi, cdj))\n else:\n edges.add((ci, cj))\n return (result, edges)\n\ndef shortestbridge(A: List[List[int]]) -> int:\n (a, aedges) = findAnIsland(A, set())\n (b, bedges) = findAnIsland(A, a)\n min_flip = float('inf')\n q = Queue()\n for (i, j) in aedges:\n q.put((i, j, 0))\n while not q.empty():\n (ci, cj, dist) = q.get()\n for (di, dj) in ((0, 1), (1, 0), (0, -1), (-1, 0)):\n (cdi, cdj) = (ci + di, cj + dj)\n if valid(A, cdi, cdj):\n if (cdi, cdj) in bedges:\n min_flip = min(min_flip, dist)\n return min_flip\n elif A[cdi][cdj] == 0 or A[cdi][cdj] > dist + 1:\n A[cdi][cdj] = dist + 1\n q.put((cdi, cdj, dist + 1))\n return min_flip", "WATER = 0\nLAND = 1\nISLAND = 2\nBRIDGE = 3\nDIR = ((-1, 0), (1, 0), (0, -1), (0, 1))\nfrom copy import deepcopy\n\ndef shortestbridge(A):\n (x0, y0) = self.findFirstLand(A)\n q = deque([(x0, y0)])\n visited = set([(x0, y0)])\n self.bfs(A, q, visited, LAND)\n q = deque(visited)\n return self.bfs(A, q, visited, WATER, LAND) - 1\n\ndef findFirstLand(A):\n (m, n) = (len(A), len(A[0]))\n for x in range(m):\n for y in range(n):\n if A[x][y] == LAND:\n return (x, y)\n\ndef bfs(A, q, visited, target, des=-1):\n (m, n) = (len(A), len(A[0]))\n step = 0\n while q:\n for _ in range(len(q)):\n (x, y) = q.popleft()\n for (dx, dy) in DIR:\n (nx, ny) = (x + dx, y + dy)\n if 0 <= nx <= m - 1 and 0 <= ny <= n - 1 and ((nx, ny) not in visited):\n if A[nx][ny] == des:\n return step + 1\n if A[nx][ny] == target:\n q.append((nx, ny))\n visited.add((nx, ny))\n step += 1\n return step - 1", "def shortestbridge(A):\n (R, C) = (len(A), len(A[0]))\n\n def neighbors(r, c):\n for (nr, nc) in ((r - 1, c), (r, c - 1), (r + 1, c), (r, c + 1)):\n if 0 <= nr < R and 0 <= nc < C:\n yield (nr, nc)\n\n def get_components():\n done = set()\n components = []\n for (r, row) in enumerate(A):\n for (c, val) in enumerate(row):\n if val and (r, c) not in done:\n stack = [(r, c)]\n seen = {(r, c)}\n while stack:\n node = stack.pop()\n for nei in neighbors(*node):\n if A[nei[0]][nei[1]] and nei not in seen:\n stack.append(nei)\n seen.add(nei)\n done |= seen\n components.append(seen)\n return components\n (source, target) = get_components()\n queue = collections.deque([(node, 0) for node in source])\n done = set(source)\n while queue:\n (node, d) = queue.popleft()\n if node in target:\n return d - 1\n for nei in neighbors(*node):\n if nei not in done:\n queue.append((nei, d + 1))\n done.add(nei)", "def shortestbridge(A: List[List[int]]) -> int:\n if len(A) == 0:\n return 0\n m = len(A)\n n = len(A[0])\n queue = []\n found = False\n for i in range(m):\n if found:\n break\n for j in range(n):\n if A[i][j] == 1:\n self.dfs(i, j, A, queue)\n found = True\n break\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n while queue:\n (path, x, y) = queue.pop(0)\n for (dx, dy) in directions:\n if x + dx < 0 or y + dy < 0 or x + dx >= m or (y + dy >= n):\n continue\n if A[x + dx][y + dy] == 1:\n return path\n if A[x + dx][y + dy] == 0:\n A[x + dx][y + dy] = 2\n queue.append((path + 1, x + dx, y + dy))\n return -1\n\ndef dfs(i, j, grid, queue):\n queue.append((0, i, j))\n grid[i][j] = 2\n stack = [(i, j)]\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n while stack:\n (x, y) = stack.pop()\n for (dx, dy) in directions:\n if x + dx < 0 or y + dy < 0 or x + dx >= len(grid) or (y + dy >= len(grid[0])):\n continue\n if grid[x + dx][y + dy] == 1:\n queue.append((0, x + dx, y + dy))\n stack.append((x + dx, y + dy))\n grid[x + dx][y + dy] = 2", "def shortestbridge(A: List[List[int]]) -> int:\n r = len(A)\n c = len(A[0])\n path = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n idx = []\n for i in range(r):\n for j in range(c):\n if A[i][j] == 1:\n idx.append((i, j))\n queue = collections.deque([idx[0]])\n seen = {tuple(idx[0])}\n island = collections.deque([(idx[0][0], idx[0][1], 0)])\n while queue:\n (x, y) = queue.popleft()\n for i in path:\n a = x + i[0]\n b = y + i[1]\n if 0 <= a < r and 0 <= b < c and (A[a][b] == 1) and ((a, b) not in seen):\n queue.append((a, b))\n seen.add((a, b))\n island.append((a, b, 0))\n while island:\n (x, y, z) = island.popleft()\n for i in path:\n a = x + i[0]\n b = y + i[1]\n if 0 <= a < r and 0 <= b < c and ((a, b) not in seen):\n if A[a][b] == 0:\n island.append((a, b, z + 1))\n seen.add((a, b))\n else:\n return z", "def find_island(i, j):\n if (i >= 0 and i < self.m) and (j >= 0 and j < self.n) and (self.grid[i][j] == 1):\n self.island.append([i, j])\n self.grid[i][j] = -1\n D = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n for d in D:\n self.find_island(i + d[0], j + d[1])\n\ndef expand_island():\n D = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n while len(self.island) > 0:\n [i, j] = self.island.pop(0)\n for d in D:\n if i + d[0] in range(self.m) and j + d[1] in range(self.n):\n if self.grid[i + d[0]][j + d[1]] == 1:\n return self.grid[i][j] + 1\n if self.grid[i + d[0]][j + d[1]] == 0:\n self.island.append([i + d[0], j + d[1]])\n self.grid[i + d[0]][j + d[1]] = self.grid[i][j] - 1\n return self.m + self.n - 1\n\ndef shortestbridge(A: List[List[int]]) -> int:\n from itertools import product\n self.grid = A\n (self.m, self.n) = (len(A), len(A[0]))\n self.island = []\n for i in range(self.n):\n for j in range(self.m):\n if len(self.island) == 0 and self.grid[i][j] == 1:\n self.find_island(i, j)\n return abs(self.expand_island())", "def shortestbridge(A: List[List[int]]) -> int:\n\n def dirs(V, M, N):\n res = []\n if V[0] > 0:\n res.append((V[0] - 1, V[1]))\n if V[0] < M - 1:\n res.append((V[0] + 1, V[1]))\n if V[1] > 0:\n res.append((V[0], V[1] - 1))\n if V[1] < N - 1:\n res.append((V[0], V[1] + 1))\n return res\n\n def bfs(grid):\n q = []\n for j in I[0]:\n level[j] = 0\n q.append(j)\n visited.add(j)\n while q:\n v = q.pop(0)\n for neighbor in dirs(v, len(grid), len(grid[0])):\n if neighbor not in visited:\n q.append(neighbor)\n visited.add(neighbor)\n if neighbor in level:\n level[neighbor] = min(level[neighbor], level[v] + 1)\n else:\n level[neighbor] = level[v] + 1\n return\n\n def dfs(grid, i, j, m, n, S):\n S.add((i, j))\n vis.add((i, j))\n if i < m - 1 and (i + 1, j) not in vis and (grid[i + 1][j] == 1):\n dfs(grid, i + 1, j, m, n, S)\n if i > 0 and (i - 1, j) not in vis and (grid[i - 1][j] == 1):\n dfs(grid, i - 1, j, m, n, S)\n if j < n - 1 and (i, j + 1) not in vis and (grid[i][j + 1] == 1):\n dfs(grid, i, j + 1, m, n, S)\n if j > 0 and (i, j - 1) not in vis and (grid[i][j - 1] == 1):\n dfs(grid, i, j - 1, m, n, S)\n return\n (M, N) = (len(A), len(A[0]))\n I = []\n vis = set()\n for i in range(M):\n for j in range(N):\n if (i, j) not in vis and A[i][j] == 1:\n s = set()\n dfs(A, i, j, M, N, s)\n I.append(s)\n level = {}\n visited = set()\n bfs(A)\n return min([level[j] for j in I[1]]) - 1", "def shortestbridge(A: List[List[int]]) -> int:\n (m, n) = (len(A), len(A[0]))\n (r, c) = (-1, -1)\n for (i, row) in enumerate(A):\n for (j, val) in enumerate(row):\n if val == 1:\n r = i\n c = j\n break\n if r == -1 or c == -1:\n return -1\n nei = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n\n def dfs(A, i, j, q):\n q.append((i, j, 0))\n A[i][j] = 2\n for (dx, dy) in nei:\n nx = i + dx\n ny = j + dy\n if 0 <= nx < m and 0 <= ny < n and (A[nx][ny] == 1):\n dfs(A, nx, ny, q)\n return\n q = []\n dfs(A, r, c, q)\n while q:\n (cx, cy, dis) = q.pop(0)\n for (dx, dy) in nei:\n (nx, ny) = (cx + dx, cy + dy)\n if 0 <= nx < m and 0 <= ny < n:\n if A[nx][ny] == 1:\n return dis\n if A[nx][ny] == 0:\n q.append((nx, ny, dis + 1))\n A[nx][ny] = 2\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n rows = len(A)\n cols = len(A[0])\n directions = ((1, 0), (-1, 0), (0, 1), (0, -1))\n\n def edge_check(ro, co):\n r = []\n for (y, x) in directions:\n nr = ro + y\n nc = co + x\n if nr < rows and nr >= 0 and (nc < cols) and (nc >= 0) and (A[nr][nc] == 0):\n return True\n return False\n edges_1 = []\n found_1 = False\n edges_2 = []\n for row in range(rows):\n for col in range(cols):\n if A[row][col] == 1:\n A[row][col] = '#'\n q = collections.deque([])\n q.append((row, col))\n while q:\n (r, c) = q.popleft()\n if not found_1 and edge_check(r, c):\n edges_1.append((r, c))\n elif edge_check(r, c):\n edges_2.append((r, c))\n for (y, x) in directions:\n nr = r + y\n nc = c + x\n if nr < rows and nr >= 0 and (nc < cols) and (nc >= 0) and (A[nr][nc] == 1):\n q.append((nr, nc))\n A[nr][nc] = '#'\n found_1 = True\n c1 = sorted(edges_1, key=lambda x: (x[0], x[1]))\n c2 = sorted(edges_2, key=lambda x: (x[0], x[1]))\n minn = float('inf')\n for (x1, x2) in c1:\n for (y1, y2) in c2:\n minn = min(minn, abs(x1 - y1) + abs(x2 - y2) - 1)\n return minn", "def shortestbridge(A: List[List[int]]) -> int:\n\n def trace_island(A, start_i, start_j, second, edges):\n queue = collections.deque()\n queue.append((start_i, start_j))\n while queue:\n (i, j) = queue.popleft()\n isedge = False\n for (di, dj) in [(1, 0), (0, 1), (-1, 0), (0, -1), (0, 0)]:\n if 0 <= di + i < len(A) and 0 <= dj + j < len(A[0]) and (A[di + i][dj + j] == 1):\n if second:\n A[di + i][dj + j] = 2\n else:\n A[di + i][dj + j] = -1\n if not (di == 0 and dj == 0):\n queue.append((di + i, dj + j))\n else:\n isedge = True\n if isedge and (not second):\n edges.append((i, j))\n outedge = []\n second = False\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1:\n trace_island(A, i, j, second, outedge)\n second = True\n output = 0\n while outedge:\n temp = []\n for (i, j) in outedge:\n for (di, dj) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:\n if 0 <= di + i < len(A) and 0 <= dj + j < len(A[0]) and (A[di + i][dj + j] != -1):\n if A[di + i][dj + j] == 2:\n return output\n temp.append((di + i, dj + j))\n A[di + i][dj + j] = -1\n outedge = temp\n output += 1", "def shortestbridge(A: List[List[int]]) -> int:\n q = []\n r = len(A)\n c = len(A[0])\n result = float('inf')\n seen = [[False] * c for _ in range(r)]\n found = False\n for i in range(r):\n if found:\n break\n for j in range(c):\n if A[i][j] == 1:\n q = self.neighbors(i, j, A, seen, r, c)\n found = True\n break\n while q:\n (x, y, dis) = q.pop(0)\n for (d1, d2) in ((-1, 0), (0, -1), (1, 0), (0, 1)):\n (n_x, n_y) = (d1 + x, d2 + y)\n if 0 <= n_x < r and 0 <= n_y < c and (not seen[n_x][n_y]):\n if A[n_x][n_y] == 1:\n result = min(result, dis)\n q.append((n_x, n_y, dis + 1))\n seen[n_x][n_y] = True\n return result\n\ndef neighbors(i, j, A, seen, r, c):\n q = [(i, j)]\n seen[i][j] = True\n ls = []\n while q:\n (x, y) = q.pop(0)\n ls.append((x, y, 0))\n for (d1, d2) in ((-1, 0), (0, -1), (1, 0), (0, 1)):\n (n_x, n_y) = (d1 + x, d2 + y)\n if 0 <= n_x < r and 0 <= n_y < c and (A[n_x][n_y] == 1) and (not seen[n_x][n_y]):\n q.append((n_x, n_y))\n seen[n_x][n_y] = True\n return ls", "def shortestbridge(A: List[List[int]]) -> int:\n if not len(A) or not len(A[0]):\n return 0\n (m, n) = (len(A), len(A[0]))\n\n def neighbors(i, j):\n for (ni, nj) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= ni < m and 0 <= nj < n:\n yield (ni, nj)\n\n def dfs(i, j, seen, island):\n if (i, j) not in seen:\n seen.add((i, j))\n for (ni, nj) in neighbors(i, j):\n if A[ni][nj] == 1:\n dfs(ni, nj, seen, island)\n else:\n island.add((i, j))\n\n def find_island():\n seen = set()\n island = set()\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n dfs(i, j, seen, island)\n return (seen, island)\n (seen, island) = find_island()\n q = collections.deque(list([(x, 0) for x in island]))\n while q:\n ((i, j), cnt) = q.popleft()\n for (ni, nj) in neighbors(i, j):\n if (ni, nj) not in seen:\n seen.add((ni, nj))\n if A[ni][nj] == 1:\n return cnt\n q.append(((ni, nj), cnt + 1))\n return -1", "import queue\n\ndef shortestbridge(A: List[List[int]]) -> int:\n\n def adjacent(i, q):\n nonlocal A\n l = []\n if i > 0:\n l.append([i - 1, q])\n if i < len(A) - 1:\n l.append([i + 1, q])\n if q > 0:\n l.append([i, q - 1])\n if q < len(A[0]) - 1:\n l.append([i, q + 1])\n return l\n\n def fill(i, q):\n nonlocal A\n A[i][q] = 2\n qu = queue.Queue()\n qu.put([i, q])\n seen = set()\n while not qu.empty():\n current = qu.get()\n seen.add(tuple(current))\n l = adjacent(current[0], current[1])\n for (a, b) in l:\n if A[a][b] == 1:\n A[a][b] = 2\n qu.put([a, b])\n return seen\n starts = []\n broken = False\n for i in range(len(A)):\n for q in range(len(A[0])):\n if A[i][q] == 1:\n starts = fill(i, q)\n broken = True\n break\n if broken:\n break\n qu = queue.Queue()\n for el in list(starts):\n qu.put(list(el) + [0])\n while not qu.empty():\n current = qu.get()\n l = adjacent(current[0], current[1])\n for (i, q) in l:\n if A[i][q] == 1:\n return current[2]\n elif A[i][q] == 0:\n A[i][q] = 2\n qu.put([i, q, current[2] + 1])", "def shortestbridge(A: List[List[int]]) -> int:\n (R, C) = (len(A), len(A[0]))\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n\n def dfs(row, col, group):\n A[row][col] = marker\n group.append((row, col))\n for (dr, dc) in directions:\n (new_row, new_col) = (row + dr, col + dc)\n if 0 <= new_row < R and 0 <= new_col < C and (A[new_row][new_col] == 1):\n dfs(new_row, new_col, group)\n return group\n (groups, marker) = ([], 2)\n for r in range(R):\n for c in range(C):\n if A[r][c] == 1:\n groups.append((dfs(r, c, []), marker))\n marker += 1\n groups = sorted(groups, key=lambda x: len(x[0]))\n (src_group, src_marker) = groups[0]\n q = deque([(row, col, 0) for (row, col) in src_group])\n target = set(groups[1][0])\n while q:\n (row, col, curr_distance) = q.pop()\n if (row, col) in target:\n return curr_distance - 1\n for (dr, dc) in directions:\n (new_row, new_col) = (row + dr, col + dc)\n if 0 <= new_row < R and 0 <= new_col < C and (A[new_row][new_col] != src_marker):\n q.appendleft((new_row, new_col, curr_distance + 1))\n A[new_row][new_col] = src_marker\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n (m, n) = (len(A) if A else 0, len(A[0]) if A else 0)\n (p, q) = (-1, -1)\n\n def neighbors(r, c):\n for (nr, nc) in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]:\n if nr in range(m) and nc in range(n):\n yield (nr, nc)\n done = set()\n components = []\n for (i, j) in product(list(range(m)), list(range(n))):\n if A[i][j] == 1:\n if (i, j) not in done:\n stack = [(i, j)]\n seen = {(i, j)}\n while stack:\n node = stack.pop()\n for (p, q) in neighbors(*node):\n if (p, q) not in seen:\n if A[p][q] == 1:\n seen.add((p, q))\n stack.append((p, q))\n done |= seen\n components.append(seen)\n (source, target) = components\n heap = []\n for (i, j) in source:\n heappush(heap, (0, (i, j)))\n done = set(source)\n while heap:\n (dist, (i, j)) = heappop(heap)\n if (i, j) in target:\n return dist - 1\n for (r, s) in neighbors(i, j):\n if A[r][s] not in source and (r, s) not in done:\n done.add((r, s))\n heappush(heap, (dist + 1, (r, s)))", "def find_island(i, j):\n self.island.append([i, j])\n self.grid[i][j] = -1\n D = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n for d in D:\n if i + d[0] in range(self.m) and j + d[1] in range(self.n) and (self.grid[i + d[0]][j + d[1]] == 1):\n self.find_island(i + d[0], j + d[1])\n\ndef expand_island():\n D = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n while len(self.island) > 0:\n [i, j] = self.island.pop(0)\n depth = abs(self.grid[i][j])\n for d in D:\n if i + d[0] in range(self.m) and j + d[1] in range(self.n):\n if self.grid[i + d[0]][j + d[1]] == 1:\n return depth - 1\n if self.grid[i + d[0]][j + d[1]] == 0:\n self.island.append([i + d[0], j + d[1]])\n self.grid[i + d[0]][j + d[1]] = -1 * (depth + 1)\n return self.m + self.n - 1\n\ndef shortestbridge(A: List[List[int]]) -> int:\n self.grid = A\n self.m = len(A)\n self.n = len(A[0])\n self.island = []\n for i in range(self.m):\n for j in range(self.n):\n if self.grid[i][j] == 1 and len(self.island) == 0:\n self.find_island(i, j)\n res = self.expand_island()\n return res", "def shortestbridge(A: List[List[int]]) -> int:\n i1 = []\n m = len(A)\n n = len(A[0])\n vis = [[False for _ in range(n)] for _ in range(m)]\n\n def check(x, y):\n return x >= 0 and x < m and (y >= 0) and (y < n)\n dx = [0, -1, 0, 1]\n dy = [1, 0, -1, 0]\n\n def dfs(p_x, p_y, i):\n vis[p_x][p_y] = True\n i.append((p_x, p_y))\n for j in range(4):\n (c_x, c_y) = (p_x + dx[j], p_y + dy[j])\n if check(c_x, c_y) and (not vis[c_x][c_y]):\n if A[c_x][c_y]:\n dfs(c_x, c_y, i)\n conn = 0\n for i in range(m):\n for j in range(n):\n if not vis[i][j] and A[i][j]:\n if conn == 0:\n dfs(i, j, i1)\n elif conn == 1:\n break\n conn += 1\n if conn == 1:\n break\n q = deque()\n d = [[float('inf') for _ in range(n)] for _ in range(m)]\n for v in i1:\n q.append(v)\n d[v[0]][v[1]] = 0\n ans = float('inf')\n while q:\n (s_x, s_y) = (q[0][0], q[0][1])\n q.popleft()\n for i in range(4):\n (c_x, c_y) = (s_x + dx[i], s_y + dy[i])\n if check(c_x, c_y):\n if d[c_x][c_y] > d[s_x][s_y] + 1:\n d[c_x][c_y] = d[s_x][s_y] + 1\n q.append((c_x, c_y))\n if A[c_x][c_y]:\n ans = min(ans, d[c_x][c_y] - 1)\n return ans", "def shortestbridge(A: List[List[int]]) -> int:\n self.A = A\n self.R = len(self.A)\n self.C = len(self.A[0])\n p = self.findGround()\n if p == None:\n return -1\n self.firstIsland = set()\n self.embraceIsland(p)\n return self.bfs()\n\ndef findGround():\n for i in range(0, self.R):\n for j in range(0, self.C):\n if self.isGround((i, j)):\n return (i, j)\n return None\n\ndef isGround(p):\n return self.A[p[0]][p[1]] == 1\n\ndef inGrid(p):\n if not 0 <= p[0] < self.R:\n return False\n if not 0 <= p[1] < self.C:\n return False\n return True\n\ndef getNeis(p):\n neis = []\n neis.append((p[0] + 1, p[1]))\n neis.append((p[0] - 1, p[1]))\n neis.append((p[0], p[1] + 1))\n neis.append((p[0], p[1] - 1))\n return neis\n\ndef embraceIsland(p):\n self.firstIsland.add(p)\n for nei in self.getNeis(p):\n if self.inGrid(nei) and self.isGround(nei) and (nei not in self.firstIsland):\n self.embraceIsland(nei)\n\ndef bfs():\n q = collections.deque()\n visited = set()\n for p in self.firstIsland:\n q.appendleft((p, 0))\n while q:\n (node, dist) = q.pop()\n if self.isGround(node) and node not in self.firstIsland:\n return dist - 1\n if node in visited:\n continue\n visited.add(node)\n for nei in self.getNeis(node):\n if self.inGrid(nei) and nei not in visited:\n q.appendleft((nei, dist + 1))\n return -1", "def paint(A, i, j):\n if i >= len(A) or i < 0 or j < 0 or (j >= len(A[0])) or (A[i][j] == 0) or (A[i][j] == 2):\n return\n A[i][j] = 2\n for nb in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n self.paint(A, i + nb[0], j + nb[1])\n\ndef expand(A, i, j, color):\n if i >= len(A) or i < 0 or j < 0 or (j >= len(A[0])):\n return False\n if A[i][j] == 0:\n A[i][j] = color + 1\n return A[i][j] == 1\n\ndef shortestbridge(A: List[List[int]]) -> int:\n if not A:\n return 0\n (m, n, flag) = (len(A), len(A[0]), False)\n for i in range(m):\n if flag:\n break\n for j in range(n):\n if A[i][j] == 1:\n self.paint(A, i, j)\n flag = True\n break\n for color in range(2, 2 + m + n + 1):\n for i in range(m):\n for j in range(n):\n if A[i][j] == color and (self.expand(A, i - 1, j, color) or self.expand(A, i, j + 1, color) or self.expand(A, i + 1, j, color) or self.expand(A, i, j - 1, color)):\n return color - 2", "def shortestbridge(A: List[List[int]]) -> int:\n u = {(i, j): (i, j) for i in range(len(A)) for j in range(len(A[0])) if A[i][j]}\n\n def head(p):\n if u[p] == p:\n return p\n h = head(u[p])\n u[p] = h\n return h\n\n def union(p1, p2):\n u[head(p2)] = head(p1)\n for (i, row) in enumerate(A):\n for (j, v) in enumerate(row):\n if not v:\n continue\n if i and A[i - 1][j]:\n union((i - 1, j), (i, j))\n if j and A[i][j - 1]:\n union((i, j - 1), (i, j))\n grps = {p1: set() for (p1, p2) in list(u.items()) if p1 == p2}\n for p in list(u.keys()):\n grps[head(p)].add(p)\n grps = list(grps.values())\n s = 0\n (layer, target) = grps\n while layer:\n new_layer = []\n for (x, y) in layer:\n for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n nx = x + dx\n ny = y + dy\n if nx < 0 or nx >= len(A) or ny < 0 or (ny >= len(A[0])):\n continue\n if A[nx][ny] == 1 and (nx, ny) in target:\n return s\n if not A[nx][ny]:\n new_layer.append((nx, ny))\n A[nx][ny] = -1\n s += 1\n layer = new_layer\n return", "def shortestbridge(A: List[List[int]]) -> int:\n r = len(A)\n c = len(A[0])\n dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n dist = [[float('inf') for j in range(c)] for i in range(r)]\n island1 = set()\n island2 = set()\n\n def dfs(x, y, island):\n island.add((x, y))\n for (i, j) in dirs:\n if 0 <= x + i < r and 0 <= y + j < c and (A[x + i][y + j] == 1) and ((x + i, y + j) not in island):\n dfs(x + i, y + j, island)\n for i in range(r):\n for j in range(c):\n if A[i][j] == 1:\n if len(island1) == 0:\n dfs(i, j, island1)\n elif (i, j) not in island1:\n dfs(i, j, island2)\n q = collections.deque(list(island1))\n d = 1\n res = float('inf')\n while q:\n size = len(q)\n for i in range(size):\n (x, y) = q.popleft()\n for (i, j) in dirs:\n if 0 <= x + i < r and 0 <= y + j < c:\n if A[x + i][y + j] == 0 and d < dist[x + i][y + j]:\n q.append((x + i, y + j))\n dist[x + i][y + j] = d\n if (x + i, y + j) in island2:\n res = min(res, d - 1)\n d += 1\n return res", "def shortestbridge(A: List[List[int]]) -> int:\n gather = []\n for y in range(len(A)):\n for x in range(len(A[y])):\n if A[y][x] == 1:\n A[y][x] = 2\n gather.append((x, y, 0))\n break\n if gather:\n break\n dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n seen = set([gather[0]])\n while gather:\n frontier = []\n for (x, y, _) in gather:\n for (dx, dy) in dirs:\n (xx, yy) = (x + dx, y + dy)\n if (xx, yy, 0) in seen:\n continue\n if 0 <= yy < len(A) and 0 <= xx < len(A[yy]) and (A[yy][xx] == 1):\n A[yy][xx] = 2\n seen.add((xx, yy, 0))\n frontier.append((xx, yy, 0))\n gather = frontier\n bfs = list(seen)\n while bfs:\n frontier = []\n for (x, y, n) in bfs:\n A[y][x] = 2\n for (dx, dy) in dirs:\n (xx, yy) = (x + dx, y + dy)\n if 0 <= yy < len(A) and 0 <= xx < len(A[yy]):\n if A[yy][xx] == 1:\n return n\n elif A[yy][xx] == 0:\n A[yy][xx] = 2\n frontier.append((xx, yy, n + 1))\n bfs = frontier\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n (R, C) = (len(A), len(A[0]))\n dist = [[float('inf')] * C for _ in range(R)]\n directs = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n src = None\n for r in range(R):\n for c in range(C):\n if A[r][c] == 1:\n dist[r][c] = 0\n src = (r, c)\n if src:\n break\n if src:\n break\n queue = [(0, r, c)]\n while queue:\n (d, r, c) = heapq.heappop(queue)\n for (dr, dc) in directs:\n (nr, nc) = (r + dr, c + dc)\n if not (0 <= nr < R and 0 <= nc < C):\n continue\n enqueue = False\n if A[nr][nc] == 1 and A[r][c] == 1:\n if d < dist[nr][nc]:\n dist[nr][nc] = d\n enqueue = True\n elif d + 1 < dist[nr][nc]:\n dist[nr][nc] = d + 1\n enqueue = True\n if enqueue:\n heapq.heappush(queue, (dist[nr][nc], nr, nc))\n ans = float('inf')\n for r in range(R):\n for c in range(C):\n if A[r][c] == 1 and dist[r][c] > 0:\n ans = min(ans, dist[r][c] - 1)\n return ans", "def shortestbridge(A: List[List[int]]) -> int:\n queue = []\n\n def markIsland2(i, j):\n if i < 0 or i >= len(A) or j < 0 or (j >= len(A)):\n return False\n if A[i][j] == 2:\n return False\n if A[i][j] == 0:\n return True\n A[i][j] = 2\n shore = False\n for (x, y) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n shore |= markIsland2(i + x, j + y)\n if shore:\n queue.append((i, j))\n return False\n flag = False\n for i in range(len(A)):\n if flag:\n break\n for j in range(len(A)):\n if A[i][j] == 1:\n markIsland2(i, j)\n flag = True\n break\n\n def BFS(i, j):\n queue.append((i, j))\n for (x, y) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n if 0 <= i + x < len(A) and 0 <= j + y < len(A):\n if A[i + x][j + y] == 1:\n return True\n elif A[i + x][j + y] == 0:\n A[i + x][j + y] = 2\n queue.append((i + x, j + y))\n else:\n return False\n cnt = 0\n while queue:\n size = len(queue)\n for _ in range(size):\n (i, j) = queue.pop(0)\n if BFS(i, j):\n return cnt\n cnt += 1", "def shortestbridge(A: List[List[int]]) -> int:\n\n def dfs(A, i, j):\n if i < 0 or j < 0 or i > len(A) - 1 or (j > len(A[0]) - 1):\n return\n if visited[i][j] or A[i][j] == 0:\n return\n visited[i][j] = True\n queue.append((i, j))\n for k in range(4):\n rr = i + rowVector[k]\n cc = j + colVector[k]\n dfs(A, rr, cc)\n visited = [[False for i in range(len(A[0]))] for j in range(len(A))]\n rowVector = [1, -1, 0, 0]\n colVector = [0, 0, 1, -1]\n queue = []\n found = False\n for i in range(len(A)):\n if found:\n break\n for j in range(len(A[0])):\n if A[i][j] == 1:\n dfs(A, i, j)\n found = True\n break\n count = 0\n while queue:\n subQ = []\n while queue:\n temp = queue.pop(0)\n for k in range(4):\n i = temp[0] + rowVector[k]\n j = temp[1] + colVector[k]\n if i < 0 or j < 0 or i > len(A) - 1 or (j > len(A[0]) - 1) or visited[i][j]:\n continue\n if A[i][j] == 1:\n return count\n subQ.append((i, j))\n visited[i][j] = True\n queue = subQ\n count += 1\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n (R, C) = (len(A), len(A[0]))\n\n def getNeighbors(curr_points):\n neighbors = set()\n for (i, j) in curr_points:\n for (row, col) in [(i + 1, j), (i - 1, j), (i, j - 1), (i, j + 1)]:\n if 0 <= row < R and 0 <= col < C:\n neighbors.add((row, col))\n return neighbors\n\n def get_islands():\n\n def dfs(pos, visited):\n (i, j) = pos\n if i >= R or i < 0 or j >= C or (j < 0) or (A[i][j] == 0) or (pos in visited):\n return\n visited.add(pos)\n dfs((i + 1, j), visited)\n dfs((i - 1, j), visited)\n dfs((i, j + 1), visited)\n dfs((i, j - 1), visited)\n (island1, island2) = (set(), set())\n for i in range(R):\n for j in range(C):\n if A[i][j] == 1:\n if not island1:\n dfs((i, j), island1)\n elif not island2 and (i, j) not in island1:\n dfs((i, j), island2)\n return (island1, island2)\n (island1, island2) = get_islands()\n min_distance = 0\n while True:\n neighbors = getNeighbors(island1)\n for neighbor in neighbors:\n if neighbor in island2:\n return min_distance\n island1.add(neighbor)\n min_distance += 1\n return min_distance\n\ndef dist(x, y):\n return abs(x[0] - y[0]) + abs(x[1] - y[1]) - 1", "import numpy as np\n\ndef shortestbridge(A: List[List[int]]) -> int:\n (self.R, self.C) = (len(A), len(A[0]))\n self.queue = []\n self.visited = []\n for k in range(self.R):\n self.visited.append([0] * self.C)\n count = 0\n for rr in range(self.R):\n for cc in range(self.C):\n if A[rr][cc] == 1:\n self.dfs(A, rr, cc)\n count = 1\n if count > 0:\n break\n if count > 0:\n break\n while self.queue:\n node_visit = self.queue.pop(0)\n q_step = node_visit.step\n for (r_srch, c_srch) in self.dirs(A, node_visit.r, node_visit.c):\n if A[r_srch][c_srch] == 0 and self.visited[r_srch][c_srch] == 0:\n self.queue.append(self.node(q_step + 1, r_srch, c_srch))\n self.visited[r_srch][c_srch] = 1\n if A[r_srch][c_srch] == 1:\n return q_step\n\ndef dirs(A, r, c) -> int:\n dir_list = []\n for (rr, cc) in [[r - 1, c], [r + 1, c], [r, c - 1], [r, c + 1]]:\n if rr >= 0 and cc >= 0 and (rr < self.R) and (cc < self.C):\n dir_list.append([rr, cc])\n return dir_list\n\ndef dfs(A, r, c):\n if A[r][c] != 1:\n return\n A[r][c] = 2\n self.queue.append(self.node(0, r, c))\n self.visited[r][c] = 1\n for (r_srch, c_srch) in self.dirs(A, r, c):\n self.dfs(A, r_srch, c_srch)", "def shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n visited = [[False] * n for _ in range(m)]\n directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]\n\n def findFirstIsland():\n for r in range(m):\n for c in range(n):\n if A[r][c] == 1:\n return (r, c)\n queue = deque()\n\n def dfs(r, c):\n if visited[r][c]:\n return\n visited[r][c] = True\n if isBoundary(r, c):\n queue.append((r, c, -1))\n for (dr, dc) in directions:\n (nr, nc) = (r + dr, c + dc)\n if not (0 <= nr < m and 0 <= nc < n):\n continue\n if A[nr][nc] == 1 and (not visited[nr][nc]):\n dfs(nr, nc)\n\n def isBoundary(r, c):\n for (dr, dc) in directions:\n (nr, nc) = (r + dr, c + dc)\n if not (0 <= nr < m and 0 <= nc < n):\n continue\n if A[nr][nc] == 0:\n return True\n return False\n (sr, sc) = findFirstIsland()\n dfs(sr, sc)\n visited2 = [[False] * n for _ in range(m)]\n while queue:\n (r, c, d) = queue.popleft()\n visited2[r][c] = True\n if not visited[r][c] and A[r][c] == 1:\n return d\n for (dr, dc) in directions:\n (nr, nc) = (r + dr, c + dc)\n if not (0 <= nr < m and 0 <= nc < n):\n continue\n if not visited2[nr][nc]:\n visited2[nr][nc] = True\n queue.append((nr, nc, d + 1))\n return 1", "from collections import deque\n\ndef shortestbridge(A: List[List[int]]) -> int:\n\n def get_edges(visited, A, i, j, isle):\n dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n queue = deque([(i, j)])\n visited[i][j] = True\n edges = set()\n while queue:\n edge = 0\n (ci, cj) = queue.popleft()\n for (di, dj) in dirs:\n x = ci + di\n y = cj + dj\n if 0 <= x < m and 0 <= y < n and (A[x][y] == 1) and (not visited[x][y]):\n queue.append((x, y))\n visited[x][y] = True\n elif 0 <= x < m and 0 <= y < n and (A[x][y] == 0):\n edge = 1\n if edge:\n edges.add((ci, cj))\n return edges\n\n def manattan(a, b, c, d):\n return abs(a - c) + abs(b - d) - 1\n visited = [[0] * len(A[0]) for i in range(len(A))]\n m = len(A)\n n = len(A[0])\n edge_islands = []\n counts = 0\n for ii in range(m):\n for jj in range(n):\n if A[ii][jj] == 1 and (not visited[ii][jj]):\n counts += 1\n edge_islands.append(get_edges(visited, A, ii, jj, counts))\n isle1 = edge_islands[0]\n isle2 = edge_islands[1]\n mins = float('inf')\n for i1 in isle1:\n for i2 in isle2:\n mins = min(mins, manattan(i1[0], i1[1], i2[0], i2[1]))\n return mins", "def shortestbridge(A: List[List[int]]) -> int:\n M = len(A)\n N = len(A[0])\n q = collections.deque()\n i0 = None\n j0 = None\n for i in range(M):\n for j in range(N):\n if A[i][j] == 1:\n (i0, j0) = (i, j)\n break\n if i0 is not None:\n break\n q.append((i0, j0))\n A[i0][j0] = 2\n vis = set()\n dirs_lst = [(-1, 0), (1, 0), (0, 1), (0, -1)]\n boarder = set()\n while q:\n (i, j) = q.popleft()\n for (di, dj) in dirs_lst:\n ni = i + di\n nj = j + dj\n if ni < 0 or ni > M - 1 or nj < 0 or (nj > N - 1):\n boarder.add((i, j))\n continue\n if A[ni][nj] == 0:\n boarder.add((i, j))\n continue\n if (ni, nj) in vis:\n continue\n A[ni][nj] = 2\n vis.add((ni, nj))\n q.append((ni, nj))\n vis.clear()\n for (i, j) in boarder:\n q.append((i, j, 0))\n res = math.inf\n while q:\n (i, j, nsteps) = q.popleft()\n for (di, dj) in dirs_lst:\n ni = i + di\n nj = j + dj\n if ni < 0 or ni > M - 1 or nj < 0 or (nj > N - 1):\n continue\n if (ni, nj) in vis:\n continue\n if A[ni][nj] == 1:\n res = min(res, nsteps)\n continue\n vis.add((ni, nj))\n q.append((ni, nj, nsteps + 1))\n return res", "def shortestbridge(mat: List[List[int]]) -> int:\n R = len(mat)\n C = len(mat and mat[0])\n\n def expand(island, other):\n new = set()\n for (r, c) in island:\n for (nr, nc) in ((r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)):\n if R > nr >= 0 <= nc < C:\n if (nr, nc) in other:\n return True\n if mat[nr][nc] == 0:\n mat[nr][nc] = 2\n new.add((nr, nc))\n island.update(new)\n\n def findIsland(r, c, island):\n island.add((r, c))\n mat[r][c] = 2\n for (nr, nc) in ((r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)):\n if R > nr >= 0 <= nc < C and mat[nr][nc] == 1 and ((nr, nc) not in island):\n findIsland(nr, nc, island)\n islands = []\n for r in range(R):\n for c in range(C):\n if mat[r][c] == 1:\n island = set()\n findIsland(r, c, island)\n islands.append(island)\n ans = 0\n while True:\n if expand(*islands):\n return ans\n ans += 1", "def shortestbridge(A: List[List[int]]) -> int:\n (R, C) = (len(A), len(A[0]))\n dist = [[float('inf')] * C for _ in range(R)]\n directs = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n\n def findSrc():\n for r in range(R):\n for c in range(C):\n if A[r][c] == 1:\n return (r, c)\n (r, c) = findSrc()\n dist[r][c] = 0\n queue = [(0, r, c)]\n\n def neighbors(r, c):\n for (nr, nc) in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]:\n if 0 <= nr < R and 0 <= nc < C:\n yield (nr, nc)\n while queue:\n (d, r, c) = heapq.heappop(queue)\n for (nr, nc) in neighbors(r, c):\n enqueue = False\n if A[nr][nc] == 1 and A[r][c] == 1:\n if d < dist[nr][nc]:\n dist[nr][nc] = d\n enqueue = True\n elif d + 1 < dist[nr][nc]:\n dist[nr][nc] = d + 1\n enqueue = True\n if enqueue:\n heapq.heappush(queue, (dist[nr][nc], nr, nc))\n ans = float('inf')\n for r in range(R):\n for c in range(C):\n if A[r][c] == 1 and dist[r][c] > 0:\n ans = min(ans, dist[r][c] - 1)\n return ans", "from math import sqrt\n\ndef shortestbridge(A: List[List[int]]) -> int:\n\n def get_islands(A):\n island_one = set()\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1 and (i, j) not in island_one:\n if not island_one:\n island_one = make_island(A, i, j, set())\n else:\n return (island_one, make_island(A, i, j, set()))\n\n def make_island(A, i, j, visited):\n visited.add((i, j))\n up = A[i][j + 1] if j < len(A[0]) - 1 else 0\n down = A[i][j - 1] if j > 0 else 0\n left = A[i - 1][j] if i > 0 else 0\n right = A[i + 1][j] if i < len(A) - 1 else 0\n if up and (i, j + 1) not in visited:\n make_island(A, i, j + 1, visited)\n if down and (i, j - 1) not in visited:\n make_island(A, i, j - 1, visited)\n if left and (i - 1, j) not in visited:\n make_island(A, i - 1, j, visited)\n if right and (i + 1, j) not in visited:\n make_island(A, i + 1, j, visited)\n return visited\n\n def find_shortest_bridge(A, i, j, start_island, global_dist_map):\n queue = [(i, j)]\n dist_map = {(i, j): 0}\n while queue:\n (i, j) = queue.pop(0)\n neighbors = []\n if (i, j + 1) not in start_island and j < len(A[0]) - 1:\n neighbors.append((i, j + 1))\n if (i, j - 1) not in start_island and j > 0:\n neighbors.append((i, j - 1))\n if (i - 1, j) not in start_island and i > 0:\n neighbors.append((i - 1, j))\n if (i + 1, j) not in start_island and i < len(A) - 1:\n neighbors.append((i + 1, j))\n for neighbor in neighbors:\n (n_i, n_j) = neighbor\n if A[n_i][n_j] == 1:\n return dist_map[i, j] + 1\n if neighbor not in global_dist_map or global_dist_map[neighbor] > dist_map[i, j] + 1:\n queue.append(neighbor)\n global_dist_map[neighbor] = dist_map[neighbor] = dist_map[i, j] + 1\n return False\n\n def find_shortest_pair(island1, island2):\n min_distance = len(A) * len(A[0])\n shortest_coords = None\n for coords1 in island1:\n for coords2 in island2:\n distance_between = sqrt((coords2[0] - coords1[0]) ** 2 + (coords2[1] - coords1[1]) ** 2)\n if distance_between < min_distance:\n min_distance = distance_between\n shortest_coords = (coords1, coords2)\n return shortest_coords\n (first_island, second_island) = get_islands(A)\n min_island = first_island if len(first_island) < len(second_island) else second_island\n shortest_bridge = len(A) * len(A[0])\n global_dist_map = {}\n for island in min_island:\n (i, j) = island\n shortest_bridge_here = find_shortest_bridge(A, i, j, min_island, global_dist_map)\n if shortest_bridge_here:\n shortest_bridge = min(shortest_bridge, shortest_bridge_here)\n return shortest_bridge - 1", "def shortestbridge(A: List[List[int]]) -> int:\n\n def get_islands(A):\n island_one = set()\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1 and (i, j) not in island_one:\n if not island_one:\n island_one = make_island(A, i, j, set())\n else:\n return (island_one, make_island(A, i, j, set()))\n\n def make_island(A, i, j, visited):\n visited.add((i, j))\n up = A[i][j + 1] if j < len(A[0]) - 1 else 0\n down = A[i][j - 1] if j > 0 else 0\n left = A[i - 1][j] if i > 0 else 0\n right = A[i + 1][j] if i < len(A) - 1 else 0\n if up and (i, j + 1) not in visited:\n make_island(A, i, j + 1, visited)\n if down and (i, j - 1) not in visited:\n make_island(A, i, j - 1, visited)\n if left and (i - 1, j) not in visited:\n make_island(A, i - 1, j, visited)\n if right and (i + 1, j) not in visited:\n make_island(A, i + 1, j, visited)\n return visited\n\n def find_shortest_bridge(A, i, j, start_island, global_dist_map):\n queue = [(i, j)]\n dist_map = {(i, j): 0}\n while queue:\n (i, j) = queue.pop(0)\n neighbors = []\n if (i, j + 1) not in start_island and j < len(A[0]) - 1:\n neighbors.append((i, j + 1))\n if (i, j - 1) not in start_island and j > 0:\n neighbors.append((i, j - 1))\n if (i - 1, j) not in start_island and i > 0:\n neighbors.append((i - 1, j))\n if (i + 1, j) not in start_island and i < len(A) - 1:\n neighbors.append((i + 1, j))\n for neighbor in neighbors:\n (n_i, n_j) = neighbor\n if A[n_i][n_j] == 1:\n return dist_map[i, j] + 1\n if neighbor not in global_dist_map or global_dist_map[neighbor] > dist_map[i, j] + 1:\n queue.append(neighbor)\n global_dist_map[neighbor] = dist_map[neighbor] = dist_map[i, j] + 1\n return False\n (first_island, second_island) = get_islands(A)\n min_island = first_island if len(first_island) < len(second_island) else second_island\n shortest_bridge = len(A) * len(A[0])\n global_dist_map = {}\n for island in min_island:\n (i, j) = island\n shortest_bridge_here = find_shortest_bridge(A, i, j, min_island, global_dist_map)\n if shortest_bridge_here:\n shortest_bridge = min(shortest_bridge, shortest_bridge_here)\n return shortest_bridge - 1", "def shortestbridge(A: List[List[int]]) -> int:\n self.map = A\n self.rows = len(self.map)\n self.cols = len(self.map[0])\n self.queue = []\n self.src = 2\n self.dst = 3\n for island_index in [self.src, self.dst]:\n add_to_queue = island_index == self.src\n self.exploreIsland(island_index, add_to_queue)\n self.queue_index = 0\n return self.bridgeBFS()\n\ndef exploreIsland(index, add):\n (row, col) = self.getIslandLocation()\n self.islandDFS(index, row, col, add)\n\ndef getIslandLocation():\n for row in range(self.rows):\n for col in range(self.cols):\n if self.map[row][col] == 1:\n return (row, col)\n\ndef islandDFS(index, row, col, add):\n if self.validCoords(row, col) and self.map[row][col] == 1:\n self.map[row][col] = index\n if add:\n self.queue.append((row, col, 0))\n for search_row in range(row - 1, row + 2, 2):\n self.islandDFS(index, search_row, col, add)\n for search_col in range(col - 1, col + 2, 2):\n self.islandDFS(index, row, search_col, add)\n\ndef validCoords(row, col):\n if row < 0 or row >= self.rows:\n return False\n if col < 0 or col >= self.cols:\n return False\n return True\n\ndef bridgeBFS():\n while self.queue_index < len(self.queue):\n (row, col, dist) = self.queue[self.queue_index]\n self.queue_index += 1\n for search_row in range(row - 1, row + 2, 2):\n if self.processCoord(search_row, col, dist):\n return dist\n for search_col in range(col - 1, col + 2, 2):\n if self.processCoord(row, search_col, dist):\n return dist\n\ndef processCoord(row, col, dist):\n if not self.validCoords(row, col):\n return False\n if self.map[row][col] == self.dst:\n return True\n elif self.map[row][col] != self.src:\n self.queue.append((row, col, dist + 1))\n self.map[row][col] = self.src\n return False", "def dfs(A, i, j, replace):\n if i < 0 or i >= len(A) or j < 0 or (j >= len(A[0])):\n return\n if A[i][j] == 0 or A[i][j] == replace:\n return\n A[i][j] = replace\n r = self.dfs(A, i + 1, j, replace)\n d = self.dfs(A, i, j + 1, replace)\n u = self.dfs(A, i - 1, j, replace)\n l = self.dfs(A, i, j - 1, replace)\n return\n\ndef find(A, i, j, old):\n if i < 0 or i >= len(A) or j < 0 or (j >= len(A[0])):\n return False\n if A[i][j] == -1:\n return True\n if A[i][j] == 0:\n A[i][j] = old + 1\n return False\n if A[i][j] == old + 1:\n return False\n A[i][j] = old + 1\n return self.find(A, i + 1, j, old) or self.find(A, i - 1, j, old) or self.find(A, i, j + 1, old) or self.find(A, i, j - 1, old)\n\ndef shortestbridge(A: List[List[int]]) -> int:\n iindex = 0\n (i, j) = (0, 0)\n replace = -1\n start = ()\n while i < len(A):\n j = 0\n while j < len(A[0]):\n if A[i][j] == 1:\n self.dfs(A, i, j, replace)\n iindex += 1\n replace = -2\n start = (i, j)\n j += 1\n i += 1\n old = 1\n while True:\n if self.find(A, start[0], start[1], old):\n break\n old += 1\n return old - 1", "import collections\n\ndef shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n\n def neighbors(r, c):\n for (nr, nc) in ((r - 1, c), (r, c - 1), (r + 1, c), (r, c + 1)):\n if 0 <= nr < m and 0 <= nc < n:\n yield (nr, nc)\n seen = set()\n islands = {2: set(), 3: set()}\n\n def color_island(r, c, island_id):\n seen.add((r, c))\n if A[r][c] != 1:\n return\n A[r][c] = island_id\n islands[island_id].add((r, c))\n for (x, y) in neighbors(r, c):\n if (x, y) not in seen:\n color_island(x, y, island_id)\n islands_found = 0\n for r in range(m):\n if islands_found == 2:\n break\n for c in range(n):\n if islands_found == 2:\n break\n if A[r][c] == 1:\n islands_found += 1\n color_island(r, c, islands_found + 1)\n source = islands[2]\n target = islands[3]\n queue = collections.deque([(node, 0) for node in source])\n seen = source\n while queue:\n ((r, c), d) = queue.popleft()\n if (r, c) in target:\n return d - 1\n for (x, y) in neighbors(r, c):\n if (x, y) not in seen:\n queue.append(((x, y), d + 1))\n seen.add((x, y))", "def shortestbridge(A: List[List[int]]) -> int:\n if not A:\n return 0\n (m, n) = (len(A), len(A[0]))\n queue = collections.deque()\n found = False\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n self.dfs(A, i, j, m, n, queue)\n found = True\n break\n if found:\n break\n bridge = 0\n while queue:\n for _ in range(len(queue)):\n (x, y) = queue.popleft()\n for d in self.DIRS:\n (next_x, next_y) = (x + d[0], y + d[1])\n if 0 <= next_x < m and 0 <= next_y < n and (A[next_x][next_y] == 0):\n queue.append((next_x, next_y))\n A[next_x][next_y] = 2\n if 0 <= next_x < m and 0 <= next_y < n and (A[next_x][next_y] == 1):\n return bridge\n bridge += 1\n return bridge\n\ndef dfs(A, i, j, m, n, queue):\n if i < 0 or i >= m or j < 0 or (j >= n) or (A[i][j] != 1):\n return\n A[i][j] = 2\n queue.append((i, j))\n self.dfs(A, i + 1, j, m, n, queue)\n self.dfs(A, i - 1, j, m, n, queue)\n self.dfs(A, i, j + 1, m, n, queue)\n self.dfs(A, i, j - 1, m, n, queue)", "from typing import List\nfrom queue import Queue\n\ndef shortestbridge(A: List[List[int]]) -> int:\n (first_island, second_island) = (set(), set())\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n\n def get_all(x, y, island):\n if (x, y) in island or A[y][x] == 0:\n return\n island.add((x, y))\n for (dx, dy) in directions:\n if 0 <= x + dx < len(A[0]) and 0 <= y + dy < len(A):\n get_all(x + dx, y + dy, island)\n first_in = False\n for y in range(len(A)):\n for x in range(len(A[0])):\n if A[y][x] == 1:\n if not first_in:\n get_all(x, y, first_island)\n first_in = True\n elif (x, y) not in first_island:\n get_all(x, y, second_island)\n break\n visited = set()\n q = Queue()\n for (x, y) in first_island:\n q.put((x, y, 0))\n while not q.empty():\n (x, y, depth) = q.get()\n if (x, y) in second_island:\n return depth - 1\n for (dx, dy) in directions:\n (X, Y) = (x + dx, y + dy)\n if 0 <= X < len(A[0]) and 0 <= Y < len(A) and ((X, Y) not in visited):\n q.put((X, Y, depth + 1))\n visited.add((X, Y))", "def shortestbridge(A: List[List[int]]) -> int:\n if not A:\n return 0\n m = len(A)\n n = len(A[0])\n\n def getnei(i, j):\n xy = []\n if i > 0:\n xy.append((i - 1, j))\n if j > 0:\n xy.append((i, j - 1))\n if i < m - 1:\n xy.append((i + 1, j))\n if j < m - 1:\n xy.append((i, j + 1))\n return xy\n\n def dfs1(i, j):\n if A[i][j] != 1:\n return\n A[i][j] = -1\n for (x, y) in getnei(i, j):\n dfs1(x, y)\n\n def bfs(i, j, dist_map, thresh):\n seen = set()\n q = collections.deque()\n q.append((i, j, 0))\n done = False\n while q and (not done):\n (ii, jj, depth) = q.popleft()\n if depth > thresh:\n done = True\n break\n for (x, y) in getnei(ii, jj):\n if (x, y) in dist_map and dist_map[x, y] < depth:\n continue\n if A[x][y] == -1:\n thresh = min(depth, thresh)\n done = True\n break\n elif A[x][y] == 0:\n if (x, y) in seen:\n continue\n seen.add((x, y))\n q.append((x, y, depth + 1))\n return thresh\n ans = math.inf\n is_second = False\n dist_map = {}\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n if not is_second:\n dfs1(i, j)\n is_second = True\n else:\n ans = min(ans, bfs(i, j, dist_map, ans))\n return ans", "def shortestbridge(A: List[List[int]]) -> int:\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n (islands, index) = ([set(), set()], -1)\n visited = set()\n\n def traverse(current):\n nonlocal A, islands, index, visited, directions\n islands[index].add(current)\n for d in directions:\n (new_i, new_j) = (current[0] + d[0], current[1] + d[1])\n if 0 <= new_i < len(A) and 0 <= new_j < len(A[0]) and ((new_i, new_j) not in visited) and (A[new_i][new_j] == 1):\n visited.add((new_i, new_j))\n traverse((new_i, new_j))\n for i in range(len(A)):\n for j in range(len(A[0])):\n if (i, j) not in visited and A[i][j] == 1:\n index += 1\n traverse((i, j))\n (one, two) = islands\n result = sys.maxsize\n for index in one:\n visited = set()\n queue = collections.deque([(index, 0)])\n while queue:\n current = queue.popleft()\n if current[1] >= result:\n break\n for d in directions:\n (new_i, new_j) = (current[0][0] + d[0], current[0][1] + d[1])\n if 0 <= new_i < len(A) and 0 <= new_j < len(A[0]) and ((new_i, new_j) not in one) and ((new_i, new_j) not in visited):\n if (new_i, new_j) in two:\n result = min(result, current[1])\n break\n visited.add((new_i, new_j))\n queue.append(((new_i, new_j), current[1] + 1))\n return result", "def shortestbridge(A: List[List[int]]) -> int:\n rows = len(A)\n cols = len(A[0])\n\n def getNeighbors(i, j):\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if x >= 0 and x < rows and (y >= 0) and (y < cols):\n yield (x, y)\n\n def findComponents():\n visited = set()\n connectedNodes = [[] for i in range(2)]\n\n def findConnnectedComponent(i, j):\n visited.add((i, j))\n connectedNodes[connectedCompNumber].append((i, j))\n for (x, y) in getNeighbors(i, j):\n if (x, y) not in visited and A[x][y]:\n findConnnectedComponent(x, y)\n connectedCompNumber = -1\n for i in range(rows):\n for j in range(cols):\n if (i, j) not in visited and A[i][j] == 1:\n connectedCompNumber += 1\n findConnnectedComponent(i, j)\n return connectedNodes\n\n def findDistance() -> int:\n shortedDist = 1\n (source, target) = findComponents()\n queue = collections.deque()\n for s in source:\n queue.appendleft((s, 0))\n done = set()\n for s in source:\n done.add(s)\n while queue:\n (node, dist) = queue.pop()\n if node in target:\n return dist - 1\n for n in getNeighbors(*node):\n if n not in done:\n queue.appendleft((n, dist + 1))\n done.add(n)\n return findDistance()", "import collections\n\ndef shortestbridge(A: List[List[int]]) -> int:\n found = False\n res = []\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1:\n self.dfs(A, i, j, res)\n found = True\n break\n if found:\n break\n cnt = 0\n while res:\n tmp = []\n for (x, y) in res:\n for (dx, dy) in ((1, 0), (-1, 0), (0, 1), (0, -1)):\n if 0 <= x + dx < len(A) and 0 <= y + dy < len(A[0]) and (A[x + dx][y + dy] != 2):\n if A[x + dx][y + dy] == 0:\n A[x + dx][y + dy] = 2\n if A[x + dx][y + dy] == 1:\n return cnt\n tmp.append([x + dx, y + dy])\n cnt += 1\n res = tmp\n return -1\n\ndef dfs(A, i, j, res):\n if 0 <= i < len(A) and 0 <= j < len(A[0]) and (A[i][j] == 1):\n A[i][j] = 2\n res.append([i, j])\n self.dfs(A, i + 1, j, res)\n self.dfs(A, i - 1, j, res)\n self.dfs(A, i, j - 1, res)\n self.dfs(A, i, j + 1, res)", "def __init__():\n self.components = []\n self.comp = []\n self.seen = set()\n\ndef isValid(r, c, A):\n if r < 0 or c < 0 or r >= len(A) or (c >= len(A)):\n return False\n return True\n\ndef dfs(r, c, A):\n if not self.isValid(r, c, A) or (r, c) in self.seen or A[r][c] != 1:\n return\n self.comp.append((r, c))\n self.seen.add((r, c))\n self.dfs(r + 1, c, A)\n self.dfs(r - 1, c, A)\n self.dfs(r, c + 1, A)\n self.dfs(r, c - 1, A)\n\ndef shortestbridge(A: List[List[int]]) -> int:\n for i in range(len(A)):\n for j in range(len(A[0])):\n if (i, j) not in self.seen and A[i][j] == 1:\n self.comp = []\n self.dfs(i, j, A)\n self.components.append(self.comp)\n (source, target) = self.components\n visited = set(source)\n queue = collections.deque([(node, 0) for node in source])\n while queue:\n (node, d) = queue.popleft()\n if node in target:\n return d - 1\n else:\n for (dr, dc) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n nr = node[0] + dr\n nc = node[1] + dc\n if (nr, nc) not in visited and self.isValid(nr, nc, A):\n queue.append(((nr, nc), d + 1))\n visited.add((nr, nc))\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n visited = collections.deque()\n flag = False\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n A[i][j] = 2\n visited = self.search(A, i, j, visited)\n flag = True\n break\n if flag == True:\n break\n steps = 0\n vis = collections.deque(visited)\n while visited:\n size = len(visited)\n for i in range(size):\n (row, col) = visited.popleft()\n dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n for d in dirs:\n newrow = row + d[0]\n newcol = col + d[1]\n if 0 <= newrow < len(A) and 0 <= newcol < len(A[0]) and (A[newrow][newcol] == 1):\n return steps\n elif 0 <= newrow < len(A) and 0 <= newcol < len(A[0]) and (A[newrow][newcol] == 0) and ((newrow, newcol) not in vis):\n A[newrow][newcol] = 2\n visited.append((newrow, newcol))\n vis.append((newrow, newcol))\n steps += 1\n return -1\n\ndef search(A, i, j, visited):\n q = collections.deque()\n q.append((i, j))\n visited.append((i, j))\n while q:\n size = len(q)\n for i in range(size):\n (r, c) = q.popleft()\n dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n for d in dirs:\n newr = r + d[0]\n newc = c + d[1]\n if 0 <= newr < len(A) and 0 <= newc < len(A[0]) and (A[newr][newc] == 1) and ((newr, newc) not in visited):\n A[newr][newc] = 2\n q.append((newr, newc))\n visited.append((newr, newc))\n return visited", "def shortestbridge(A: List[List[int]]) -> int:\n (found_y, found_x) = (None, None)\n for y in range(len(A)):\n found_one = False\n for x in range(len(A[0])):\n if A[y][x] == 1:\n (found_y, found_x) = (y, x)\n A = self.invertOnes(y, x, A)\n found_one = True\n break\n if found_one:\n break\n return self.BFS(found_y, found_x, A)\n\ndef invertOnes(y, x, A):\n neighbors = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n stack = []\n stack.append((y, x))\n A[y][x] = -1\n while stack:\n (curr_y, curr_x) = stack.pop(0)\n for neighbor in neighbors:\n (new_y, new_x) = (curr_y + neighbor[0], curr_x + neighbor[1])\n if new_y >= 0 and new_y < len(A) and (new_x >= 0) and (new_x < len(A[0])) and (A[new_y][new_x] == 1):\n A[new_y][new_x] = -1\n stack.append((new_y, new_x))\n return A\n\ndef BFS(y, x, A):\n visited = {}\n neighbors = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n stack = []\n stack.append((y, x, 0))\n visited[y, x] = 0\n min_dist = float('inf')\n while stack:\n (curr_y, curr_x, curr_dist) = stack.pop(0)\n if A[curr_y][curr_x] == 1:\n min_dist = min(min_dist, curr_dist - 1)\n for neighbor in neighbors:\n (new_y, new_x) = (curr_y + neighbor[0], curr_x + neighbor[1])\n if new_y >= 0 and new_y < len(A) and (new_x >= 0) and (new_x < len(A[0])):\n if A[new_y][new_x] == -1:\n new_dist = 0\n else:\n new_dist = curr_dist + 1\n if (new_y, new_x) not in visited:\n stack.append((new_y, new_x, new_dist))\n visited[new_y, new_x] = new_dist\n elif visited[new_y, new_x] > new_dist:\n visited[new_y, new_x] = new_dist\n stack.append((new_y, new_x, new_dist))\n return min_dist", "from collections import deque\n\ndef shortestbridge(A: List[List[int]]) -> int:\n\n def color(x, y):\n dfs = [(x, y)]\n while dfs:\n (a, b) = dfs.pop()\n A[a][b] = 2\n for (mx, my) in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n if 0 <= a + mx < len(A) and 0 <= b + my < len(A[0]):\n if A[a + mx][b + my] == 1:\n dfs.append((a + mx, b + my))\n\n def firstOne():\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j]:\n color(i, j)\n return (i, j)\n point = firstOne()\n self.best = 1000\n\n def findClosest(point):\n visited = {}\n bfs = deque([(point, 0)])\n while bfs:\n (curr, dist) = bfs.popleft()\n if curr in visited:\n if visited[curr] <= dist:\n continue\n visited[curr] = dist\n for (x, y) in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n cx = curr[0] + x\n cy = curr[1] + y\n if 0 <= cx < len(A) and 0 <= cy < len(A[0]):\n if A[cx][cy] == 2:\n bfs.append(((cx, cy), 0))\n elif A[cx][cy] == 1:\n self.best = min(self.best, dist)\n else:\n bfs.append(((cx, cy), dist + 1))\n findClosest(point)\n return self.best", "def shortestbridge(A: List[List[int]]) -> int:\n q = collections.deque()\n\n def find_first_island():\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1:\n explore_island(i, j)\n return\n\n def explore_island(r, c):\n if not 0 <= r < len(A) or not 0 <= c < len(A[r]) or A[r][c] == -1:\n return\n if A[r][c] == 1:\n A[r][c] = -1\n explore_island(r + 1, c)\n explore_island(r - 1, c)\n explore_island(r, c + 1)\n explore_island(r, c - 1)\n elif A[r][c] == 0:\n q.append((r, c, 1))\n find_first_island()\n while q:\n (cur_r, cur_c, cur_l) = q.popleft()\n for (x, y) in ((cur_r + 1, cur_c), (cur_r - 1, cur_c), (cur_r, cur_c + 1), (cur_r, cur_c - 1)):\n if 0 <= x < len(A) and 0 <= y < len(A[0]):\n if A[x][y] == 1:\n return cur_l\n elif A[x][y] == 0:\n A[x][y] = -1\n q.append((x, y, cur_l + 1))", "from typing import List\nfrom collections import deque as queue\nfrom functools import lru_cache\n\ndef shortestbridge(A: List[List[int]]) -> int:\n n = len(A)\n\n def neighbours(i, j):\n return [neighbour for neighbour in [(i - 1, j) if i > 0 else None, (i + 1, j) if i < n - 1 else None, (i, j - 1) if j > 0 else None, (i, j + 1) if j < n - 1 else None] if neighbour is not None]\n for i in range(n):\n for j in range(n):\n if A[i][j] == 1:\n first = (i, j)\n q = queue([first])\n visited = set()\n visited.add(first)\n while q:\n (i, j) = q.popleft()\n A[i][j] = 2\n for (ni, nj) in neighbours(i, j):\n if (ni, nj) not in visited and A[ni][nj] == 1:\n visited.add((ni, nj))\n q.append((ni, nj))\n min_distance = float('inf')\n for (li, lj) in visited:\n q = queue([(li, lj, 0)])\n water_visited = set()\n while q:\n (i, j, d) = q.popleft()\n for (ni, nj) in neighbours(i, j):\n if A[ni][nj] == 0 and (ni, nj) not in water_visited and (d + 1 < min_distance):\n water_visited.add((ni, nj))\n q.append((ni, nj, d + 1))\n elif A[ni][nj] == 1 and d < min_distance:\n min_distance = d\n if min_distance == 1:\n return 1\n return min_distance", "import queue\n\ndef isOK(x, y, m, n):\n return x >= 0 and y >= 0 and (x < m) and (y < n)\n\ndef isOnEdge(A, x, y, m, n):\n xRows = [0, 0, -1, 1]\n yCols = [-1, 1, 0, 0]\n for i in range(4):\n new_x = x + xRows[i]\n new_y = y + yCols[i]\n if isOK(new_x, new_y, m, n) and A[new_x][new_y] == 0:\n return True\n return False\nimport queue\n\ndef shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n visited = [[False for _ in range(n)] for _ in range(m)]\n\n def dfs(start, island):\n (x, y) = start\n island.append(start)\n visited[x][y] = True\n xRows = [0, 0, -1, 1]\n yCols = [-1, 1, 0, 0]\n for i in range(4):\n new_x = x + xRows[i]\n new_y = y + yCols[i]\n if isOK(new_x, new_y, m, n) and (not visited[new_x][new_y]) and (A[new_x][new_y] == 1):\n dfs((new_x, new_y), island)\n islands = []\n for i in range(m):\n for j in range(n):\n if not visited[i][j] and A[i][j] == 1:\n island = []\n dfs((i, j), island)\n islands.append(island)\n island1 = islands[0]\n island2 = islands[1]\n visited = [[False for _ in range(n)] for _ in range(m)]\n\n def bfs(source_island, target_island, visited):\n q = queue.Queue()\n for start in source_island:\n (x, y) = start\n q.put((x, y, 0))\n cnt = 0\n while q.qsize() > 0:\n start = q.get()\n (x, y, w) = start\n xRows = [0, 0, -1, 1]\n yCols = [-1, 1, 0, 0]\n for i in range(4):\n new_x = x + xRows[i]\n new_y = y + yCols[i]\n if isOK(new_x, new_y, m, n) and (not visited[new_x][new_y]):\n if (new_x, new_y) in target_island:\n return w + 1\n visited[new_x][new_y] = True\n q.put((new_x, new_y, w + 1))\n return bfs(island1, island2, visited) - 1", "def shortestbridge(A: List[List[int]]) -> int:\n count = 0\n borders = collections.defaultdict(list)\n seen = set()\n (x, y) = ([1, -1, 0, 0], [0, 0, 1, -1])\n (m, n) = (len(A), len(A[0]))\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1 and (i, j) not in seen:\n frontier = [(i, j)]\n island = {(i, j)}\n while frontier:\n cur = frontier.pop()\n bord = False\n for k in range(len(x)):\n (r, c) = (cur[0] + x[k], cur[1] + y[k])\n if 0 <= r < m and 0 <= c < n:\n if A[r][c] == 1 and (r, c) not in island:\n frontier.append((r, c))\n island.add((r, c))\n elif A[r][c] == 0:\n borders[count + 1].append(cur)\n count += 1\n seen.update(island)\n if count == 2:\n break\n if count == 2:\n break\n ans = float('inf')\n borders\n for (i, j) in borders[1]:\n for (x, y) in borders[2]:\n ans = min(ans, abs(i - x) + abs(j - y) - 1)\n return ans", "def color(A, i, j, length):\n A[i][j] = 2\n if i > 0:\n if A[i - 1][j] == 1:\n color(A, i - 1, j, length)\n if j > 0:\n if A[i][j - 1] == 1:\n color(A, i, j - 1, length)\n if i < length - 1:\n if A[i + 1][j] == 1:\n color(A, i + 1, j, length)\n if j < length - 1:\n if A[i][j + 1] == 1:\n color(A, i, j + 1, length)\n\ndef expand(A, level, length):\n for i in range(length):\n for j in range(length):\n if A[i][j] == level:\n if i > 0:\n if A[i - 1][j] == 1:\n return level\n elif A[i - 1][j] == 0:\n A[i - 1][j] = level + 1\n if j > 0:\n if A[i][j - 1] == 1:\n return level\n elif A[i][j - 1] == 0:\n A[i][j - 1] = level + 1\n if i < length - 1:\n if A[i + 1][j] == 1:\n return level\n elif A[i + 1][j] == 0:\n A[i + 1][j] = level + 1\n if j < length - 1:\n if A[i][j + 1] == 1:\n return level\n elif A[i][j + 1] == 0:\n A[i][j + 1] = level + 1\n return 0\n\ndef shortestbridge(A):\n length = len(A)\n found = 0\n for i in range(length):\n for j in range(length):\n if A[i][j]:\n found = 1\n color(A, i, j, length)\n if found == 1:\n break\n if found == 1:\n break\n level = 2\n found = 0\n while found == 0:\n found = expand(A, level, length)\n level += 1\n return found - 2", "def shortestbridge(A: List[List[int]]) -> int:\n self.bfs = []\n flag = 1\n step = 0\n for i in range(len(A)):\n if flag:\n for j in range(len(A[0])):\n if A[i][j] == 1:\n self.dfs(A, i, j)\n flag = 0\n break\n while self.bfs:\n size = len(self.bfs)\n while size:\n (i, j) = self.bfs.pop(0)\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= x < len(A) and 0 <= y < len(A[0]):\n if A[x][y] == 1:\n return step\n elif A[x][y] == 0:\n A[x][y] = -1\n self.bfs.append([x, y])\n size -= 1\n step += 1\n return step\n\ndef dfs(A, i, j):\n if i >= len(A) or j >= len(A[0]) or i < 0 or (j < 0) or (A[i][j] != 1):\n return\n A[i][j] = -1\n self.bfs.append([i, j])\n self.dfs(A, i + 1, j)\n self.dfs(A, i - 1, j)\n self.dfs(A, i, j + 1)\n self.dfs(A, i, j - 1)", "def shortestbridge(A: List[List[int]]) -> int:\n row_shifts = [-1, 0, 1, 0]\n col_shifts = [0, 1, 0, -1]\n\n def bfs_mark_first(row, col, mark):\n nonlocal A, row_shifts, col_shifts\n queue = [(row, col)]\n edges = []\n while len(queue) > 0:\n (curr_row, curr_col) = queue.pop(0)\n if A[curr_row][curr_col] == mark:\n continue\n A[curr_row][curr_col] = mark\n add_to_edges = False\n for (row_shift, col_shift) in zip(row_shifts, col_shifts):\n new_row = curr_row + row_shift\n new_col = curr_col + col_shift\n if 0 <= new_row < len(A) and 0 <= new_col < len(A[0]):\n if A[new_row][new_col] == 1:\n queue.append((new_row, new_col))\n else:\n add_to_edges = True\n if add_to_edges:\n edges.append((curr_row, curr_col))\n return edges\n terminate = False\n for row in range(len(A)):\n for col in range(len(A[0])):\n if A[row][col] == 1:\n edges = bfs_mark_first(row, col, -1)\n terminate = True\n break\n if terminate:\n break\n queue = edges\n while len(queue) > 0:\n (curr_row, curr_col) = queue.pop(0)\n for (row_shift, col_shift) in zip(row_shifts, col_shifts):\n new_row = curr_row + row_shift\n new_col = curr_col + col_shift\n if 0 <= new_row < len(A) and 0 <= new_col < len(A[0]):\n if A[new_row][new_col] == 0:\n A[new_row][new_col] = A[curr_row][curr_col] - 1\n queue.append((new_row, new_col))\n if A[new_row][new_col] == 1:\n return abs(A[curr_row][curr_col]) - 1\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n R = len(A)\n C = len(A[0])\n chk = [[0] * C for _ in range(R)]\n q = collections.deque()\n move = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n flag = False\n for i in range(R):\n if flag:\n break\n for j in range(C):\n if A[i][j] == 1:\n self.dfs(i, j, A, chk, q)\n flag = True\n break\n res = 0\n while q:\n size = len(q)\n for _ in range(size):\n (i, j) = q.popleft()\n for m in move:\n (x, y) = (i + m[0], j + m[1])\n if 0 <= x < R and 0 <= y < C:\n chk[x][y] = 1\n if A[x][y] == 1:\n return res\n elif A[x][y] == 0:\n A[x][y] = 2\n q.append((x, y))\n else:\n continue\n res += 1\n return res\n\ndef dfs(i, j, A, chk, q):\n if chk[i][j] == 1:\n return\n chk[i][j] = 1\n R = len(A)\n C = len(A[0])\n move = [[1, 0], [0, 1], [-1, 0], [0, -1]]\n if A[i][j] == 1:\n q.append((i, j))\n A[i][j] = 2\n for m in move:\n x = i + m[0]\n y = j + m[1]\n if 0 <= x < R and 0 <= y < C:\n self.dfs(x, y, A, chk, q)", "def dfs(A, i, j):\n if 0 > i or i >= self.m or 0 > j or (j >= self.n) or (A[i][j] == 0) or (A[i][j] == 2):\n return\n A[i][j] = 2\n self.que.append([i, j])\n for (i0, j0) in self.offset:\n (ii, jj) = (i + i0, j + j0)\n self.dfs(A, ii, jj)\n\ndef shortestbridge(A: List[List[int]]) -> int:\n self.offset = [[-1, 0], [1, 0], [0, -1], [0, 1]]\n (self.m, self.n) = (len(A), len(A[0]))\n self.que = []\n ok = 0\n for i in range(self.m):\n for j in range(self.n):\n if A[i][j]:\n self.dfs(A, i, j)\n ok = 1\n break\n if ok:\n break\n rt = 0\n while len(self.que) > 0:\n qlen = len(self.que)\n for k in range(qlen):\n (i, j) = self.que.pop(0)\n for (i0, j0) in self.offset:\n (ii, jj) = (i + i0, j + j0)\n if 0 <= ii < self.m and 0 <= jj < self.n:\n if A[ii][jj] == 0:\n A[ii][jj] = 3\n self.que.append([ii, jj])\n elif A[ii][jj] == 1:\n return rt\n rt += 1\n return rt", "def shortestbridge(A: List[List[int]]) -> int:\n (x, y) = self.get_first(A)\n q = collections.deque()\n self.dfs(A, x, y, q)\n step = 0\n while q:\n new_q = collections.deque()\n size = len(q)\n for i in range(size):\n (x, y) = q.popleft()\n for d in [[-1, 0], [1, 0], [0, -1], [0, 1]]:\n (nx, ny) = (x + d[0], y + d[1])\n if 0 <= nx < len(A) and 0 <= ny < len(A[0]):\n if A[nx][ny] == 1:\n return step\n elif A[nx][ny] == 0:\n new_q.append([nx, ny])\n A[nx][ny] = -1\n step += 1\n q = new_q\n return -1\n\ndef get_first(A):\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1:\n return (i, j)\n\ndef dfs(A, x, y, q):\n A[x][y] = -1\n q.append([x, y])\n for d in [[-1, 0], [1, 0], [0, -1], [0, 1]]:\n (nx, ny) = (x + d[0], y + d[1])\n if 0 <= nx < len(A) and 0 <= ny < len(A[0]) and (A[nx][ny] == 1):\n self.dfs(A, nx, ny, q)", "def shortestbridge(A: List[List[int]]) -> int:\n originBridge = []\n\n def markBridge(cord):\n x = cord[1]\n y = cord[0]\n A[y][x] = 2\n originBridge.append(cord)\n if x < len(A[y]) - 1:\n if A[y][x + 1] == 1:\n markBridge((y, x + 1))\n if x > 0:\n if A[y][x - 1] == 1:\n markBridge((y, x - 1))\n if y < len(A) - 1:\n if A[y + 1][x] == 1:\n markBridge((y + 1, x))\n if y > 0:\n if A[y - 1][x] == 1:\n markBridge((y - 1, x))\n for y in range(len(A)):\n for x in range(len(A[y])):\n if A[y][x] == 1:\n markBridge((y, x))\n break\n if len(originBridge) > 0:\n break\n moves = 0\n bridgeList = set(originBridge)\n while len(originBridge) > 0:\n newMoves = []\n for b in originBridge:\n y = b[0]\n x = b[1]\n if x > 0:\n if (y, x - 1) not in bridgeList:\n if A[y][x - 1] == 1:\n return moves\n else:\n bridgeList.add((y, x - 1))\n newMoves.append((y, x - 1))\n if x < len(A[y]) - 1:\n if (y, x + 1) not in bridgeList:\n if A[y][x + 1] == 1:\n return moves\n else:\n bridgeList.add((y, x + 1))\n newMoves.append((y, x + 1))\n if y > 0:\n if (y - 1, x) not in bridgeList:\n if A[y - 1][x] == 1:\n return moves\n else:\n bridgeList.add((y - 1, x))\n newMoves.append((y - 1, x))\n if y < len(A) - 1:\n if (y + 1, x) not in bridgeList:\n if A[y + 1][x] == 1:\n return moves\n else:\n bridgeList.add((y + 1, x))\n newMoves.append((y + 1, x))\n originBridge = newMoves\n moves += 1\n return moves", "from collections import deque\ndirections = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n\ndef shortestbridge(A: List[List[int]]) -> int:\n n = len(A)\n m = len(A[0])\n visited = [[False] * m for _ in range(n)]\n q = deque([])\n found = False\n for i in range(n):\n if found:\n break\n for j in range(m):\n if A[i][j] == 1:\n self.dfs(i, j, A, q, visited)\n found = True\n break\n step = 0\n while q:\n for _ in range(len(q)):\n (x, y) = q.popleft()\n for (dx, dy) in directions:\n (nx, ny) = (x + dx, y + dy)\n if not self.isValid(nx, ny, A) or visited[nx][ny]:\n continue\n if A[nx][ny] == 1:\n return step\n q.append((nx, ny))\n visited[nx][ny] = True\n step += 1\n return -1\n\ndef dfs(i, j, A, q, visited):\n if not self.isValid(i, j, A) or visited[i][j] or A[i][j] == 0:\n return\n visited[i][j] = True\n q.append((i, j))\n for (dx, dy) in directions:\n (nx, ny) = (i + dx, j + dy)\n self.dfs(nx, ny, A, q, visited)\n\ndef isValid(i, j, A):\n return i >= 0 and i < len(A) and (j >= 0) and (j < len(A[0]))", "def color(A, i, j):\n if A[i][j] in (0, 2):\n return\n A[i][j] = 2\n if i > 0:\n if A[i - 1][j] == 1:\n color(A, i - 1, j)\n if j > 0:\n if A[i][j - 1] == 1:\n color(A, i, j - 1)\n if i < len(A) - 1:\n if A[i + 1][j] == 1:\n color(A, i + 1, j)\n if j < len(A) - 1:\n if A[i][j + 1] == 1:\n color(A, i, j + 1)\n\ndef expand(A):\n for l in range(2, len(A) ** 2):\n for i in range(len(A)):\n for j in range(len(A)):\n if A[i][j] == l:\n if i > 0:\n if A[i - 1][j] == 0:\n A[i - 1][j] = l + 1\n if A[i - 1][j] == 1:\n return l - 2\n if j > 0:\n if A[i][j - 1] == 0:\n A[i][j - 1] = l + 1\n if A[i][j - 1] == 1:\n return l - 2\n if i < len(A) - 1:\n if A[i + 1][j] == 0:\n A[i + 1][j] = l + 1\n if A[i + 1][j] == 1:\n return l - 2\n if j < len(A) - 1:\n if A[i][j + 1] == 0:\n A[i][j + 1] = l + 1\n if A[i][j + 1] == 1:\n return l - 2\n\ndef shortestbridge(A):\n length = len(A)\n found = 0\n for i in range(length):\n for j in range(length):\n if A[i][j]:\n color(A, i, j)\n found = 1\n break\n if found == 1:\n break\n expansion = expand(A)\n return expansion", "from random import randint\nfrom collections import deque, Counter, defaultdict\nfrom heapq import heappush, heappop, heapify\nfrom scipy.special import comb, perm\nfrom bisect import bisect, bisect_left, bisect_right\n\ndef shortestbridge(A):\n (que, row, col, visited) = (deque(), len(A), len(A[0]), set())\n\n def dfs(i, j):\n if i < 0 or i > row - 1 or j < 0 or (j > col - 1) or ((i, j) in visited):\n return\n visited.add((i, j))\n if A[i][j] == 0:\n que.append((i, j))\n return\n for (ni, nj) in [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]:\n dfs(ni, nj)\n found = False\n for i in range(row):\n for j in range(col):\n if A[i][j] == 1:\n dfs(i, j)\n found = True\n break\n if found:\n break\n cnt = 0\n while que:\n n = len(que)\n for _ in range(n):\n (i, j) = que.popleft()\n if A[i][j] == 1:\n return cnt\n for (ni, nj) in [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]:\n if 0 <= ni < row and 0 <= nj < col and ((ni, nj) not in visited):\n que.append((ni, nj))\n visited.add((ni, nj))\n cnt += 1", "def shortestbridge(A: List[List[int]]) -> int:\n (rows, cols) = (len(A), len(A[0]))\n starting_points = set()\n\n def traverse_island(r, c):\n A[r][c] = -1\n for (ar, ac) in [(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)]:\n if 0 <= ar < rows and 0 <= ac < cols:\n if A[ar][ac] == 0:\n starting_points.add((ar, ac, 0))\n elif A[ar][ac] == 1:\n traverse_island(ar, ac)\n for r in range(rows):\n for c in range(cols):\n if A[r][c] == 1:\n traverse_island(r, c)\n break\n else:\n continue\n break\n q = deque(starting_points)\n while q:\n (r, c, dist) = q.popleft()\n for (ar, ac) in [(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)]:\n if 0 <= ar < rows and 0 <= ac < cols and (A[ar][ac] != -1):\n if A[ar][ac] == 1:\n return dist + 1\n A[ar][ac] = -1\n q.append((ar, ac, dist + 1))\n return 0", "from collections import deque\n\ndef shortestbridge(A: List[List[int]]) -> int:\n rows = len(A)\n cols = len(A[0]) if rows else 0\n if not rows or not cols:\n return -1\n self.queue = deque()\n self.visited = set()\n\n def floodFill(A, row, col, rows, cols):\n if not (0 <= row < rows and 0 <= col < cols):\n return\n if not A[row][col] or (row, col) in self.visited:\n return\n A[row][col] = 2\n self.queue.append((row, col, 0))\n self.visited.add((row, col))\n floodFill(A, row + 1, col, rows, cols)\n floodFill(A, row - 1, col, rows, cols)\n floodFill(A, row, col + 1, rows, cols)\n floodFill(A, row, col - 1, rows, cols)\n flood_fill = False\n for row in range(rows):\n for col in range(cols):\n if A[row][col] == 1:\n flood_fill = True\n floodFill(A, row, col, rows, cols)\n break\n if flood_fill:\n break\n directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]\n while len(self.queue):\n (top_r, top_c, dist) = self.queue.popleft()\n for (d_r, d_c) in directions:\n n_r = top_r + d_r\n n_c = top_c + d_c\n if 0 <= n_r < rows and 0 <= n_c < cols and ((n_r, n_c) not in self.visited):\n if A[n_r][n_c] == 0:\n self.queue.append((n_r, n_c, dist + 1))\n self.visited.add((n_r, n_c))\n elif A[n_r][n_c] == 1:\n return dist\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n\n def first():\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1:\n return (i, j)\n\n def first_island(i, j):\n stack = [(i, j)]\n island = []\n dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n while stack:\n (x, y) = stack.pop()\n A[x][y] = 2\n island.append((x, y, 0))\n for (dx, dy) in dirs:\n (tx, ty) = (x + dx, y + dy)\n if len(A) > tx >= 0 and len(A[0]) > ty >= 0 and (A[tx][ty] == 1):\n stack.append((tx, ty))\n return island\n\n def bfs(queue):\n queue = collections.deque(queue)\n dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n while queue:\n length = len(queue)\n for _ in range(length):\n (x, y, level) = queue.popleft()\n for (dx, dy) in dirs:\n (tx, ty) = (x + dx, y + dy)\n if len(A) > tx >= 0 and len(A[0]) > ty >= 0:\n if A[tx][ty] == 1:\n return level\n elif not A[tx][ty]:\n A[tx][ty] = -1\n queue.append((tx, ty, level + 1))\n return bfs(first_island(*first()))", "import heapq\nimport sys\nsys.setrecursionlimit(10 ** 8)\n\ndef shortestbridge(A: List[List[int]]) -> int:\n (h, w) = (len(A), len(A[0]))\n direction = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n First.val = True\n visited = [[0 for i in range(w)] for i in range(h)]\n\n def dfs(y, x, color):\n visited[y][x] = 1\n A[y][x] = color\n for (dy, dx) in direction:\n (ny, nx) = (y + dy, x + dx)\n if ny < 0 or ny >= h or nx < 0 or (nx >= w):\n continue\n if visited[ny][nx] or A[ny][nx] == 0:\n continue\n dfs(ny, nx, color)\n for i in range(h):\n for j in range(w):\n if visited[i][j]:\n continue\n if A[i][j]:\n if First.val:\n First.val = False\n dfs(i, j, 1)\n else:\n dfs(i, j, 2)\n break\n\n def bfs(i, j, start):\n q = [[0, i, j]]\n answer = 0\n while q:\n (step, y, x) = heapq.heappop(q)\n if A[y][x] and A[y][x] != start:\n return step\n for (dy, dx) in direction:\n (ny, nx) = (y + dy, x + dx)\n if ny < 0 or ny >= h or nx < 0 or (nx >= w):\n continue\n if visited[ny][nx] == 2:\n continue\n visited[ny][nx] = 2\n if A[ny][nx]:\n heapq.heappush(q, [step, ny, nx])\n else:\n heapq.heappush(q, [step + 1, ny, nx])\n result = 0\n for i in range(h):\n for j in range(w):\n if visited[i][j] == 2:\n continue\n if A[i][j]:\n start = A[i][j]\n result = bfs(i, j, start)\n break\n if result:\n break\n return result", "def shortestbridge(A: List[List[int]]) -> int:\n\n def isvalid(row, col):\n return 0 <= row < len(A) and 0 <= col < len(A[0])\n\n def dfs(row, col):\n if not isvalid(row, col) or A[row][col] != 1:\n return\n A[row][col] = 2\n for (i, j) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:\n new_row = row + i\n new_col = col + j\n dfs(new_row, new_col)\n return\n found = False\n for row in range(len(A)):\n for col in range(len(A[0])):\n if A[row][col] == 1:\n dfs(row, col)\n found = True\n break\n if found:\n break\n twos = []\n for row in range(len(A)):\n for col in range(len(A[0])):\n if A[row][col] == 2:\n twos.append((row, col))\n steps = 0\n while twos:\n next_ = []\n steps += 1\n for point in twos:\n (row, col) = point\n for (i, j) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:\n new_row = row + i\n new_col = col + j\n if isvalid(new_row, new_col) and A[new_row][new_col] == 0:\n A[new_row][new_col] = -1\n next_.append((new_row, new_col))\n elif isvalid(new_row, new_col) and A[new_row][new_col] == 1:\n return steps - 1\n twos = next_\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n q = collections.deque()\n\n def ExploreIslands(x, y):\n if not 0 <= x < len(A) or not 0 <= y < len(A[0]) or A[x][y] == -1:\n return\n if A[x][y] == 1:\n A[x][y] = -1\n ExploreIslands(x, y + 1)\n ExploreIslands(x, y - 1)\n ExploreIslands(x + 1, y)\n ExploreIslands(x - 1, y)\n else:\n q.appendleft((x, y, 1))\n\n def FindFirstIsland():\n for (i, row) in enumerate(A):\n for (j, val) in enumerate(row):\n if val == 1:\n ExploreIslands(i, j)\n return\n FindFirstIsland()\n while True:\n (x, y, distance) = q.popleft()\n for (new_x, new_y) in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:\n if 0 <= new_x < len(A) and 0 <= new_y < len(A[0]):\n if A[new_x][new_y] == 1:\n return distance\n elif A[new_x][new_y] == 0:\n A[new_x][new_y] = -1\n q.append((new_x, new_y, distance + 1))", "import collections\n\ndef shortestbridge(A: List[List[int]]) -> int:\n visited = set()\n\n def do_dfs(A, i, j, visited, seen):\n visited.add((i, j))\n seen.add((i, j))\n for (x, y) in [[i + 1, j], [i - 1, j], [i, j - 1], [i, j + 1]]:\n if 0 <= x < len(A) and 0 <= y < len(A[0]) and A[x][y] and ((x, y) not in visited):\n do_dfs(A, x, y, visited, seen)\n comp = []\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1 and (i, j) not in visited:\n seen = set()\n do_dfs(A, i, j, visited, seen)\n comp.append(seen)\n (s, t) = (comp[0], comp[1])\n queue = collections.deque([(node, 0) for node in s])\n done = s\n while queue:\n (node, d) = queue.popleft()\n if node in t:\n return d - 1\n for n in [(node[0] + 1, node[1]), (node[0] - 1, node[1]), (node[0], node[1] + 1), (node[0], node[1] - 1)]:\n if 0 <= n[0] < len(A) and 0 <= n[1] < len(A[0]) and (n not in done):\n queue.append((n, d + 1))\n done.add(n)", "def shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n found = 0\n queue = []\n\n def dfs(a, b):\n queue.append((a, b))\n A[a][b] = -1\n for (x, y) in ((a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)):\n if 0 <= x < m and 0 <= y < n and (A[x][y] == 1):\n dfs(x, y)\n for i in range(m):\n if found:\n break\n for j in range(n):\n if A[i][j] == 1:\n found = 1\n dfs(i, j)\n break\n step = 0\n while queue:\n new_queue = []\n for (x, y) in queue:\n for (_x, _y) in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):\n if 0 <= _x < m and 0 <= _y < n:\n if A[_x][_y] == 1:\n return step\n elif not A[_x][_y]:\n A[_x][_y] = -1\n new_queue.append((_x, _y))\n step += 1\n queue = new_queue\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n\n def neighbors(u, v):\n for (du, dv) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n (nu, nv) = (u + du, v + dv)\n if 0 <= nu < m and 0 <= nv < n:\n yield (nu, nv)\n\n def components():\n\n def dfs(u, v, acc):\n acc.add((u, v))\n visited.add((u, v))\n for (nu, nv) in neighbors(u, v):\n if (nu, nv) not in visited and A[nu][nv] == 1:\n dfs(nu, nv, acc)\n res = []\n visited = set()\n for u in range(m):\n for v in range(n):\n if A[u][v] == 1 and (u, v) not in visited:\n res.append(set())\n dfs(u, v, res[-1])\n return res\n\n def bfs(ps, pt):\n q = deque()\n visited = set()\n for p in ps:\n q.append(p)\n visited.add(p)\n distance = 0\n while q:\n qsize = len(q)\n for i in range(qsize):\n (u, v) = q.popleft()\n for (nu, nv) in neighbors(u, v):\n if (nu, nv) in pt:\n return distance\n if (nu, nv) not in visited:\n q.append((nu, nv))\n visited.add((nu, nv))\n distance += 1\n return 0\n m = len(A)\n n = len(A[0])\n (source, target) = components()\n return bfs(source, target)", "def shortestbridge(A: List[List[int]]) -> int:\n (R, C) = (len(A), len(A[0]))\n done = set()\n\n def dfs(x, y, seen, R, C):\n if A[x][y] == 0:\n return\n seen.add((x, y))\n for (nr, nc) in ((x - 1, y), (x, y - 1), (x + 1, y), (x, y + 1)):\n if 0 <= nr < R and 0 <= nc < C and (A[nr][nc] == 1) and ((nr, nc) not in seen) and ((nr, nc) not in done):\n dfs(nr, nc, seen, R, C)\n islands = []\n for (r, row) in enumerate(A):\n for (c, col) in enumerate(row):\n if col and (r, c) not in done:\n seen = set()\n dfs(r, c, seen, R, C)\n islands.append(seen)\n done |= seen\n (first, second) = islands\n q = list(first)\n count = 0\n seen = set()\n while q:\n temp = []\n for (x, y) in q:\n for (nx, ny) in ((x - 1, y), (x, y - 1), (x + 1, y), (x, y + 1)):\n if 0 <= nx < R and 0 <= ny < C and ((nx, ny) not in first) and ((nx, ny) not in seen):\n if (nx, ny) in second:\n return count\n temp.append((nx, ny))\n seen.add((nx, ny))\n count += 1\n q = temp[:]\n return 0", "def shortestbridge(A: List[List[int]]) -> int:\n (R, C) = (len(A), len(A[0]))\n\n def inside(i, j):\n return 0 <= i < R and 0 <= j < C\n\n def dfs_paint_2(i, j):\n A[i][j] = 2\n for (ii, jj) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:\n if inside(ii, jj) and A[ii][jj] == 1:\n dfs_paint_2(ii, jj)\n\n def neighbor_is_1(i, j):\n for (ii, jj) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:\n if inside(ii, jj) and A[ii][jj] == 1:\n return True\n return False\n\n def paint_neighbor(i, j, color):\n for (ii, jj) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:\n if inside(ii, jj) and A[ii][jj] == 0:\n A[ii][jj] = color\n for (i, row) in enumerate(A):\n for (j, ele) in enumerate(row):\n if ele == 1:\n dfs_paint_2(i, j)\n break\n else:\n continue\n break\n for color in range(2, max(R, C) + 2):\n for (i, row) in enumerate(A):\n for (j, ele) in enumerate(row):\n if ele == color:\n if neighbor_is_1(i, j):\n return color - 2\n paint_neighbor(i, j, color + 1)", "def shortestbridge(A: List[List[int]]) -> int:\n q = collections.deque()\n\n def explore_island(r, c):\n if not 0 <= r < len(A) or not 0 <= c < len(A[r]) or A[r][c] == -1:\n return\n if A[r][c] == 1:\n A[r][c] = -1\n explore_island(r + 1, c)\n explore_island(r - 1, c)\n explore_island(r, c + 1)\n explore_island(r, c - 1)\n elif A[r][c] == 0:\n q.append((r, c, 1))\n\n def find_first_island():\n for (r, row) in enumerate(A):\n for (c, v) in enumerate(row):\n if v == 1:\n explore_island(r, c)\n return\n find_first_island()\n while q:\n (cur_r, cur_c, cur_l) = q.popleft()\n for (x, y) in ((cur_r + 1, cur_c), (cur_r - 1, cur_c), (cur_r, cur_c + 1), (cur_r, cur_c - 1)):\n if 0 <= x < len(A) and 0 <= y < len(A[x]):\n if A[x][y] == 1:\n return cur_l\n elif A[x][y] == 0:\n A[x][y] = -1\n q.append((x, y, cur_l + 1))\n continue", "def shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n\n def get_poss(i, j, val=1):\n poss = [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]\n poss = [(x, y) for (x, y) in poss if x >= 0 and x < m and (y >= 0) and (y < n) and (A[x][y] == val)]\n return poss\n\n def expand(i, j):\n A[i][j] = '#'\n poss = get_poss(i, j)\n for (x, y) in poss:\n expand(x, y)\n found_first = False\n boundaries = []\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n if not found_first:\n found_first = True\n expand(i, j)\n else:\n boundaries.append((i, j))\n\n def bfs(boundaries):\n recorder = set(boundaries)\n depth = 0\n roots = boundaries\n while roots:\n next_level = []\n for (x, y) in roots:\n poss1 = get_poss(x, y, '#')\n if poss1:\n return depth\n poss = get_poss(x, y, 0)\n for pos in poss:\n if pos not in recorder:\n recorder.add(pos)\n next_level.append(pos)\n depth += 1\n roots = next_level\n return bfs(boundaries)", "def shortestbridge(A: List[List[int]]) -> int:\n island_one = set()\n\n def dfs(r, c):\n if (r, c) in island_one:\n return\n island_one.add((r, c))\n for (r1, c1) in {(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)}:\n if 0 <= r1 < len(A) and 0 <= c1 < len(A[0]) and ((r1, c1) not in island_one) and (A[r1][c1] == 1):\n dfs(r1, c1)\n f = False\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1:\n dfs(i, j)\n f = True\n break\n if f:\n break\n\n def bfs():\n q = collections.deque([(r, c, 0) for (r, c) in list(island_one)])\n seen = set()\n while q:\n (r, c, level) = q.popleft()\n if A[r][c] == 1 and (r, c) not in island_one:\n return level - 1\n for (r1, c1) in {(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)}:\n if 0 <= r1 < len(A) and 0 <= c1 < len(A[0]) and (A[r1][c1] not in island_one) and ((r1, c1) not in seen):\n q.append((r1, c1, level + 1))\n seen.add((r1, c1))\n return bfs()", "import heapq\n\ndef shortestbridge(mat: List[List[int]]) -> int:\n row = None\n col = None\n found = False\n for i in range(len(mat)):\n if found:\n break\n for j in range(len(mat[i])):\n if mat[i][j]:\n row = i\n col = j\n Solution.paint_one_island(mat, row, col, mat[row][col] + 1)\n found = True\n break\n target_dest = 1\n return Solution.minimum_expand(mat, row, col, target_dest)\n\ndef mark_next(mat, row, col, val, target_dest):\n for i in range(len(Solution.directions)):\n new_row = row + Solution.directions[i][0]\n new_col = col + Solution.directions[i][1]\n if new_row < 0 or new_row >= len(mat) or new_col < 0 or (new_col >= len(mat[0])):\n continue\n if mat[new_row][new_col] == target_dest:\n return True\n if not mat[new_row][new_col]:\n mat[new_row][new_col] = val + 1\n return False\n\ndef minimum_expand(mat, row, col, target_dest):\n st_val = mat[row][col]\n for val in range(st_val, len(mat) * len(mat[0])):\n for row in range(len(mat)):\n for col in range(len(mat[row])):\n is_reached = False\n if mat[row][col] == val:\n is_reached = Solution.mark_next(mat, row, col, val, target_dest)\n if is_reached:\n return val - st_val\n return -1\n\ndef paint_one_island(mat, row, col, val):\n if row < 0 or row >= len(mat) or col < 0 or (col >= len(mat[0])):\n return\n if mat[row][col] == val or not mat[row][col]:\n return\n mat[row][col] = val\n for i in range(len(Solution.directions)):\n Solution.paint_one_island(mat, row + Solution.directions[i][0], col + Solution.directions[i][1], val)", "def shortestbridge(A: List[List[int]]) -> int:\n (M, N) = (len(A), len(A[0]))\n\n def dfs(i, j):\n A[i][j] = 2\n for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:\n if 0 <= x < M and 0 <= y < N and (A[x][y] == 1):\n dfs(x, y)\n return\n flag = 0\n for i in range(M):\n for j in range(N):\n if A[i][j] == 1:\n flag = 1\n break\n if flag:\n break\n dfs(i, j)\n q = collections.deque([(0, i, j) for i in range(M) for j in range(N) if A[i][j] == 1])\n seen = set([(i, j) for i in range(M) for j in range(N) if A[i][j] == 1])\n while q:\n (step, i, j) = q.popleft()\n if A[i][j] == 2:\n return step - 1\n for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:\n if 0 <= x < M and 0 <= y < N and ((x, y) not in seen) and (A[x][y] in [0, 2]):\n seen.add((x, y))\n q.append((step + 1, x, y))", "def shortestbridge(A: List[List[int]]) -> int:\n (m, n) = (len(A), len(A[0]))\n self.first = []\n\n def dfs(i, j, m, n):\n if 0 <= i < m and 0 <= j < n and (A[i][j] == 1):\n A[i][j] = 2\n self.first.append((i, j))\n for (r, c) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:\n dfs(r, c, m, n)\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n dfs(i, j, m, n)\n break\n if A[i][j] == 2:\n break\n res = m * n\n while self.first:\n (i, j) = self.first.pop(0)\n for (r, c) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:\n if 0 <= r < m and 0 <= c < n:\n if A[r][c] == 0:\n A[r][c] = A[i][j] + 1\n self.first.append((r, c))\n if A[r][c] == 1:\n res = min(res, A[i][j] - 2)\n A[i][j] == -1\n break\n if A[i][j] == -1:\n break\n return res", "def shortestbridge(A: List[List[int]]) -> int:\n n = len(A)\n zeros = set()\n\n def dfs(i, j):\n A[i][j] = 2\n for (di, dj) in [[0, -1], [0, 1], [-1, 0], [1, 0]]:\n (ii, jj) = (i + di, j + dj)\n if 0 <= ii < n and 0 <= jj < n:\n if A[ii][jj] == 1:\n dfs(ii, jj)\n elif A[ii][jj] == 0:\n zeros.add((ii, jj))\n for i in range(n):\n for j in range(n):\n if A[i][j] == 1:\n dfs(i, j)\n break\n else:\n continue\n break\n result = 2 * n\n q = collections.deque(zeros)\n visited = {(i, j)}\n steps = 1\n while q:\n for _ in range(len(q)):\n (i, j) = q.popleft()\n for (di, dj) in [[0, -1], [0, 1], [-1, 0], [1, 0]]:\n (ii, jj) = (i + di, j + dj)\n if 0 <= ii < n and 0 <= jj < n:\n if A[ii][jj] == 0 and (ii, jj) not in visited:\n visited.add((ii, jj))\n q.append((ii, jj))\n if A[ii][jj] == 1:\n result = min(result, steps)\n steps += 1\n return result", "def shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n q = collections.deque([])\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n q.append((i, j))\n newq = collections.deque([(i, j)])\n break\n else:\n continue\n break\n while q:\n (x, y) = q.popleft()\n A[x][y] = 2\n for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n (nx, ny) = (x + dx, y + dy)\n if 0 <= nx < m and 0 <= ny < n and (A[nx][ny] == 1):\n A[nx][ny] = 2\n newq.append((nx, ny))\n q.append((nx, ny))\n steps = 0\n while newq:\n newsize = len(newq)\n for _ in range(newsize):\n (x, y) = newq.popleft()\n for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n (nx, ny) = (x + dx, y + dy)\n if nx < 0 or nx >= m or ny < 0 or (ny >= m) or (A[nx][ny] == 2):\n continue\n if A[nx][ny] == 1:\n return steps\n elif A[nx][ny] == 0:\n A[nx][ny] = 2\n newq.append((nx, ny))\n steps += 1\n return -1", "def shortestbridge(grid: List[List[int]]) -> int:\n if not grid:\n return 0\n nrow = len(grid)\n ncol = len(grid[0])\n q = deque()\n\n def explore_island(grid, i, j):\n if i < 0 or i >= nrow or j < 0 or (j >= ncol) or (grid[i][j] != 1):\n return\n grid[i][j] = 2\n q.append((i, j, 0))\n for (ni, nj) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:\n explore_island(grid, ni, nj)\n\n def get_coordinates(grid):\n for i in range(nrow):\n for j in range(ncol):\n if grid[i][j] == 1:\n explore_island(grid, i, j)\n return\n return\n get_coordinates(grid)\n while q:\n (i, j, dist) = q.popleft()\n for (ni, nj) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:\n if ni >= 0 and ni < nrow and (nj >= 0) and (nj < ncol) and (grid[ni][nj] != 2):\n if grid[ni][nj] == 1:\n return dist\n elif grid[ni][nj] == 0:\n grid[ni][nj] = 2\n q.append((ni, nj, dist + 1))", "def __init__():\n self.map = None\n (self.w, self.h) = (0, 0)\n\ndef get_neighbors(r, c):\n nei = []\n for rc in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]:\n if 0 <= rc[0] < self.h and 0 <= rc[1] < self.w:\n nei.append(rc)\n return nei\n\ndef find_island():\n done = set()\n islands = []\n for r in range(len(self.map)):\n for c in range(len(self.map[0])):\n if self.map[r][c] and (r, c) not in done:\n stack = [(r, c)]\n seen = {(r, c)}\n while stack:\n cell = stack.pop(0)\n neighbors = self.get_neighbors(cell[0], cell[1])\n for nei in neighbors:\n if self.map[nei[0]][nei[1]] and nei not in seen:\n stack.append(nei)\n seen.add(nei)\n islands.append(seen)\n done |= seen\n return islands\n\ndef shortestbridge(A: List[List[int]]) -> int:\n self.map = A\n (self.w, self.h) = (len(A), len(A[0]))\n (source, target) = self.find_island()\n queue = [(node, 0) for node in source]\n while queue:\n (node, d) = queue.pop(0)\n if node in target:\n return d - 1\n neighbors = self.get_neighbors(node[0], node[1])\n for nei in neighbors:\n if nei not in source:\n queue.append((nei, d + 1))\n source.add(nei)", "def shortestbridge(A: List[List[int]]) -> int:\n row_len = len(A)\n col_len = len(A[0])\n\n def neighbour(r, c):\n for (i, j) in [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]:\n if 0 <= i < row_len and 0 <= j < col_len:\n yield (i, j)\n\n def helper(A, r, c, queue):\n if not (0 <= r < row_len and 0 <= c < col_len) or A[r][c] == 0 or A[r][c] == 2:\n return\n A[r][c] = 2\n queue.append((r, c))\n for (i, j) in neighbour(r, c):\n helper(A, i, j, queue)\n start_r = -1\n start_c = -1\n for r in range(row_len):\n for c in range(col_len):\n if A[r][c] == 1:\n start_r = r\n start_c = c\n break\n queue = deque()\n helper(A, start_r, start_c, queue)\n step = 0\n while queue:\n size = len(queue)\n for i in range(size):\n (r, c) = queue.popleft()\n for (i, j) in neighbour(r, c):\n if A[i][j] == 1:\n return step\n if A[i][j] == 0:\n A[i][j] = 2\n queue.append((i, j))\n step += 1", "def shortestbridge(A: List[List[int]]) -> int:\n (N, M) = (len(A), len(A[0]))\n\n def labelIsland(i, j):\n stack = [(i, j)]\n visited = {(i, j)}\n while stack:\n (x, y) = stack.pop()\n A[x][y] = 2\n for (nx, ny) in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:\n if 0 <= nx < N and 0 <= ny < M and ((nx, ny) not in visited):\n if A[nx][ny] == 1:\n visited.add((nx, ny))\n stack.append((nx, ny))\n return visited\n\n def bfs(source) -> int:\n queue = collections.deque([(0, x[0], x[1]) for x in source])\n visited = source\n ans = math.inf\n while queue:\n (dist, x, y) = queue.popleft()\n for (nx, ny) in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:\n if 0 <= nx < N and 0 <= ny < M and ((nx, ny) not in visited):\n if A[nx][ny] == 1:\n return dist\n else:\n visited.add((nx, ny))\n queue.append((dist + 1, nx, ny))\n return ans\n ans = math.inf\n for i in range(N):\n for j in range(M):\n if A[i][j] == 1:\n source = labelIsland(i, j)\n return bfs(source)", "def shortestbridge(A: List[List[int]]) -> int:\n n = len(A)\n\n def getFirst():\n for (i, row) in enumerate(A):\n for (j, point) in enumerate(row):\n if point == 1:\n return (i, j)\n islandA = []\n boundaries = set()\n stack = [getFirst()]\n while len(stack) > 0:\n (i, j) = stack.pop()\n A[i][j] = -1\n islandA.append((i, j))\n isBound = False\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= x < n and 0 <= y < n:\n if A[x][y] == 0:\n boundaries.add((i, j))\n elif A[x][y] == 1:\n stack.append((x, y))\n step = 0\n while boundaries:\n new = []\n for (i, j) in boundaries:\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= x < n and 0 <= y < n:\n if A[x][y] == 1:\n return step\n elif not A[x][y]:\n A[x][y] = -1\n new.append((x, y))\n step += 1\n boundaries = new", "def mark_island(A, row, column, marker, border_coordinates):\n if 0 <= row < len(A) and 0 <= column < len(A[0]) and (A[row][column] != marker):\n if A[row][column] == 0:\n return True\n else:\n A[row][column] = marker\n rets = [self.mark_island(A, row + 1, column, marker, border_coordinates), self.mark_island(A, row - 1, column, marker, border_coordinates), self.mark_island(A, row, column + 1, marker, border_coordinates), self.mark_island(A, row, column - 1, marker, border_coordinates)]\n if True in rets:\n border_coordinates.append((row, column))\n return False\n\ndef shortestbridge(A: List[List[int]]) -> int:\n border_coordinates = [[], []]\n marker = 2\n smallest_distance = len(A) * len(A[0])\n for row in range(len(A)):\n for column in range(len(A[0])):\n if A[row][column] == 1:\n self.mark_island(A, row, column, marker, border_coordinates[marker - 2])\n marker += 1\n for coordinates1 in border_coordinates[0]:\n for coordinates2 in border_coordinates[1]:\n distance = abs(coordinates1[0] - coordinates2[0]) + abs(coordinates1[1] - coordinates2[1]) - 1\n if distance < smallest_distance:\n smallest_distance = distance\n return smallest_distance", "def shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n\n def get_neighbors(i, j):\n dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n ans = []\n for (dx, dy) in dirs:\n new_i = i + dx\n new_j = j + dy\n if 0 <= new_i < m and 0 <= new_j < n:\n ans.append((new_i, new_j))\n return ans\n\n def dfs_visit(i, j, visited):\n if A[i][j] != 1:\n return\n if (i, j) in visited:\n return\n visited.add((i, j))\n for neighbor in get_neighbors(i, j):\n dfs_visit(neighbor[0], neighbor[1], visited)\n return\n source_nodes = set()\n break_flag = False\n for i in range(m):\n if break_flag:\n break\n for j in range(n):\n if A[i][j] == 1:\n dfs_visit(i, j, source_nodes)\n break_flag = True\n break\n q = []\n for (i, j) in source_nodes:\n q.append(((i, j), 0))\n visited = set()\n while len(q):\n (curr_node, curr_dist) = q.pop(0)\n for neighbor in get_neighbors(curr_node[0], curr_node[1]):\n if neighbor in source_nodes:\n continue\n if neighbor in visited:\n continue\n if A[neighbor[0]][neighbor[1]] == 1:\n return curr_dist\n visited.add(neighbor)\n q.append((neighbor, curr_dist + 1))\n return", "def shortestbridge(A: List[List[int]]) -> int:\n\n def findIslandA(i, j):\n A[i][j] = -1\n islandA.append((i, j))\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= x < n and 0 <= y < n and (A[x][y] == 1):\n findIslandA(x, y)\n\n def first():\n for i in range(n):\n for j in range(n):\n if A[i][j]:\n return (i, j)\n (n, step, islandA) = (len(A), 0, [])\n findIslandA(*first())\n while islandA:\n boundaries = []\n for (i, j) in islandA:\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= x < n and 0 <= y < n:\n if A[x][y] == 1:\n return step\n elif A[x][y] == 0:\n A[x][y] = -1\n boundaries.append((x, y))\n step += 1\n islandA = boundaries", "def shortestbridge(grid: List[List[int]]) -> int:\n\n def dfs(curr_i, curr_j, outliners):\n visited.add((curr_i, curr_j))\n for (delta_i, delta_j) in [(1, 0), (0, 1), (0, -1), (-1, 0)]:\n (next_i, next_j) = (curr_i + delta_i, curr_j + delta_j)\n if 0 <= next_i < m and 0 <= next_j < n:\n if grid[next_i][next_j] == 0:\n outliners.add((next_i, next_j))\n elif grid[next_i][next_j] == 1:\n if (next_i, next_j) not in visited:\n dfs(next_i, next_j, outliners)\n (m, n) = (len(grid), len(grid[0]))\n visited = set()\n (outliners_1, outliners_2) = (set(), set())\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1 and (i, j) not in visited:\n if len(outliners_1) == 0:\n dfs(i, j, outliners_1)\n else:\n dfs(i, j, outliners_2)\n min_dist = m + n\n for (i, j) in outliners_1:\n for (p, q) in outliners_2:\n min_dist = min(min_dist, abs(i - p) + abs(j - q) + 1)\n return min_dist", "def shortestbridge(A: List[List[int]]) -> int:\n\n def dfs(i, j, A, visited):\n m = len(A)\n n = len(A[0])\n if 0 <= i < m and 0 <= j < n and (A[i][j] == 1) and ((i, j) not in visited):\n visited.add((i, j))\n dfs(i + 1, j, A, visited)\n dfs(i - 1, j, A, visited)\n dfs(i, j + 1, A, visited)\n dfs(i, j - 1, A, visited)\n m = len(A)\n n = len(A[0])\n find = False\n visited = set()\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n find = True\n dfs(i, j, A, visited)\n break\n if find:\n break\n visited_zero = set()\n queue = []\n for (i, j) in visited:\n for (_i, _j) in [[0, 1], [1, 0], [-1, 0], [0, -1]]:\n if 0 <= i + _i < m and 0 <= j + _j < n and ((i + _i, j + _j) not in visited):\n assert A[i + _i][j + _j] == 0\n visited_zero.add((i + _i, j + _j))\n queue.append((i + _i, j + _j, 1))\n res = 0\n find = False\n while not find:\n (i, j, dist) = queue.pop(0)\n for (_i, _j) in [[0, 1], [1, 0], [-1, 0], [0, -1]]:\n if 0 <= i + _i < m and 0 <= j + _j < n and ((i + _i, j + _j) not in visited_zero) and ((i + _i, j + _j) not in visited):\n if A[i + _i][j + _j] == 0:\n visited_zero.add((i + _i, j + _j))\n queue.append((i + _i, j + _j, dist + 1))\n else:\n find = True\n res = dist\n return res", "def shortestbridge(A: List[List[int]]) -> int:\n (i1, i2) = self.find_islands(A)\n for (x, y, n) in self.enlarge(i1):\n if (x, y) in i2:\n return n\n\ndef find_islands(A: List[List[int]]) -> List[Set[Tuple[int, int]]]:\n visited = set()\n islands = []\n for (x, ys) in enumerate(A):\n for (y, c) in enumerate(ys):\n if (x, y) not in visited and c == 1:\n to_visit = [(x, y)]\n island = set()\n while to_visit:\n (cx, cy) = to_visit.pop(0)\n if (cx, cy) in visited:\n continue\n visited.add((cx, cy))\n island.add((cx, cy))\n for (ax, ay) in self.adjacent((cx, cy)):\n if ax >= 0 and ay >= 0 and (ax < len(A)) and (ay < len(A[ax])) and (A[ax][ay] == 1):\n to_visit.append((ax, ay))\n islands.append(island)\n return islands\n\ndef enlarge(island: Set[Tuple[int, int]]) -> Generator[Tuple[int, int, int], None, None]:\n visited = set()\n to_visit = []\n for (x, y) in island:\n visited.add((x, y))\n for (ax, ay) in self.adjacent((x, y)):\n visited.add((x, y))\n if (ax, ay) not in island:\n to_visit.append((ax, ay, 0))\n while to_visit:\n (x, y, n) = to_visit.pop(0)\n if (x, y) in visited:\n continue\n visited.add((x, y))\n for (ax, ay) in self.adjacent((x, y)):\n if (ax, ay) in visited:\n continue\n to_visit.append((ax, ay, n + 1))\n yield (x, y, n)\n\ndef adjacent(cell: Tuple[int, int]) -> List[Tuple[int, int]]:\n return [(cell[0] + x, cell[1] + y) for (x, y) in [(-1, 0), (1, 0), (0, -1), (0, 1)]]"], "starter_code": "def shortestbridge(A: List[List[int]]) -> int:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Matrix", "Array", "Breadth-First Search", "Depth-First Search"], "name": null, "source": "leetcode", "tags": ["Matrices", "Data structures", "Graph traversal"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/shortest-bridge/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "shortestbridge", "task_id": "TACO_lite/422", "example": [[[[[0, 1], [1, 0]]], [[[0, 1, 0], [0, 0, 0], [0, 0, 1]]], [[[1, 1, 1, 1, 1], [1, 0, 0, 0, 1], [1, 0, 1, 0, 1], [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]]]], ["1", "2", "1"]]} +{"requirement": "Given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it palindrome.\nReturn the length of the maximum length awesome substring of s.\n \nExample 1:\nInput: s = \"3242415\"\nOutput: 5\nExplanation: \"24241\" is the longest awesome substring, we can form the palindrome \"24142\" with some swaps.\n\nExample 2:\nInput: s = \"12345678\"\nOutput: 1\n\nExample 3:\nInput: s = \"213123\"\nOutput: 6\nExplanation: \"213123\" is the longest awesome substring, we can form the palindrome \"231132\" with some swaps.\n\nExample 4:\nInput: s = \"00\"\nOutput: 2\n\n \nConstraints:\n\n1 <= s.length <= 10^5\ns consists only of digits.", "solutions": ["def longestawesome(s: str) -> int:\n cum = [0]\n firsts = {0: -1}\n lasts = {0: -1}\n for (i, c) in enumerate(s):\n cum.append(cum[-1] ^ 1 << ord(c) - 48)\n if cum[-1] not in firsts:\n firsts[cum[-1]] = i\n lasts[cum[-1]] = i\n mx = 1\n for k in firsts:\n mx = max(mx, lasts[k] - firsts[k])\n for off in range(10):\n o = k ^ 1 << off\n if o in firsts:\n mx = max(mx, lasts[o] - firsts[k])\n return mx", "def longestawesome(s: str) -> int:\n mask = 0\n (prefix, suffix) = ({0: -1}, {0: -1})\n digcodes = [2 ** i for i in range(10)] + [0]\n for i in range(len(s)):\n ch = s[i]\n mask ^= 2 ** int(ch)\n if mask not in prefix:\n prefix[mask] = i\n suffix[mask] = i\n return max([ind - prefix[val ^ dig] for (val, ind) in list(suffix.items()) for dig in digcodes if val ^ dig in prefix])", "def longestawesome(s: str) -> int:\n d = {}\n d[0] = -1\n (sm, res) = (0, 0)\n for (i, c) in enumerate(s):\n sm ^= 1 << int(c)\n if sm in d:\n res = max(res, i - d[sm])\n else:\n d[sm] = i\n for j in range(10):\n msk = sm ^ 1 << j\n if msk in d and i - d[msk] > res:\n res = i - d[msk]\n return res", "def longestawesome(s: str) -> int:\n n = len(s)\n a = 0\n ans = 0\n dp = {0: -1}\n for i in range(n):\n a = a ^ 1 << int(s[i])\n if a in dp:\n ans = max(ans, i - dp[a])\n else:\n dp[a] = i\n for j in range(11):\n x = a ^ 1 << j\n if x in dp:\n ans = max(ans, i - dp[x])\n return ans", "def longestawesome(s: str) -> int:\n known_positions = {0: -1}\n mask = 0\n max_size = 0\n for (idx, current) in enumerate(s):\n mask ^= 1 << ord(current) - ord('0')\n for modified in range(10):\n tmp_mask = mask ^ 1 << modified\n size = idx - known_positions.get(tmp_mask, idx)\n if size % 2:\n max_size = max(max_size, size)\n max_size = max(max_size, idx - known_positions.get(mask, idx))\n known_positions.setdefault(mask, idx)\n return max(max_size, 1)", "def longestawesome(s: str) -> int:\n memo = {0: -1}\n best = 0\n bitmap = 0\n for (i, digit) in enumerate(s):\n bitmap ^= 1 << int(digit)\n best = max(best, i - memo.get(bitmap, i))\n for j in range(10):\n key = bitmap ^ 1 << j\n best = max(best, i - memo.get(key, i))\n memo[bitmap] = memo.get(bitmap, i)\n return best", "def longestawesome(s: str) -> int:\n (mask, res) = (0, 0)\n dp = [-1] + [len(s)] * 1023\n for i in range(len(s)):\n mask ^= 1 << ord(s[i]) - 48\n for j in range(11):\n check_mask = 1023 & (mask ^ 1 << j)\n res = max(res, i - dp[check_mask])\n dp[mask] = min(dp[mask], i)\n return res", "def longestawesome(s: str) -> int:\n pos = {0: -1}\n bitmask = 0\n ans = 0\n n = len(s)\n for i in range(n):\n bitmask ^= 1 << int(s[i])\n for j in range(10):\n if bitmask ^ 1 << j in pos:\n ans = max(ans, i - pos[bitmask ^ 1 << j])\n if bitmask in pos:\n ans = max(ans, i - pos[bitmask])\n else:\n pos[bitmask] = i\n return ans", "def linear(s):\n ans = 0\n d = {0: -1}\n mask = 0\n for (i, c) in enumerate(s):\n mask = 1 << int(c) ^ mask\n if mask in d:\n ans = max(ans, i - d[mask])\n for j in range(10):\n s = mask ^ 1 << j\n if s in d:\n ans = max(ans, i - d[s])\n if mask not in d:\n d[mask] = i\n return ans\n\ndef longestawesome(s: str) -> int:\n return self.linear(s)\n ans = 0\n for i in range(len(s)):\n d = collections.defaultdict(int)\n odds = set()\n for j in range(i, len(s)):\n d[s[j]] += 1\n if d[s[j]] % 2:\n odds.add(s[j])\n elif s[j] in odds:\n odds.remove(s[j])\n if len(odds) <= 1:\n ans = max(ans, j - i + 1)\n return ans", "def longestawesome(s: str) -> int:\n pos = {}\n open_chars = 0\n pos[open_chars] = 0\n max_len = 0\n for (i, c) in enumerate(s):\n open_chars ^= 1 << int(c)\n for j in range(-1, 10):\n if j == -1:\n mask = 0\n else:\n mask = 1 << j\n if open_chars ^ mask in pos:\n max_len = max(max_len, i + 1 - pos[open_chars ^ mask])\n if open_chars not in pos:\n pos[open_chars] = i + 1\n return max_len", "def longestawesome(s: str) -> int:\n n = len(s)\n a = [0 for _ in range(n)]\n for i in range(n):\n x = a[i - 1] if i > 0 else 0\n a[i] = x ^ 1 << int(s[i])\n dp = 1\n ht = {}\n ht[a[0]] = 0\n for i in range(1, n):\n d = 1\n if a[i] == 0:\n d = i + 1\n else:\n if a[i] in ht:\n d = max(d, i - ht[a[i]])\n for j in range(10):\n x = a[i] ^ 1 << j\n if x == 0:\n d = i + 1\n break\n if x in ht:\n d = max(d, i - ht[x])\n dp = max(dp, d)\n if not a[i] in ht:\n ht[a[i]] = i\n return dp", "def longestawesome(s: str) -> int:\n index = [-1] + [len(s)] * 1023\n ans = 0\n bit = 0\n for (idx, c) in enumerate(s):\n bit ^= 1 << ord(c) - ord('0')\n ans = max([ans, idx - index[bit]] + [idx - index[bit ^ 1 << j] for j in range(10)])\n index[bit] = min(index[bit], idx)\n return ans", "def longestawesome(s: str) -> int:\n mem = {}\n\n def find_awesome(lo, hi, digit_count):\n if lo > hi:\n return 0\n if (lo, hi) in mem:\n return mem[lo, hi]\n if digit_count & digit_count - 1 == 0:\n return hi - lo + 1\n max_len = max(find_awesome(lo + 1, hi, digit_count ^ 1 << int(s[lo])), find_awesome(lo, hi - 1, digit_count ^ 1 << int(s[hi])))\n mem[lo, hi] = max_len\n return max_len\n (lo, hi, digit_count) = (0, len(s) - 1, 0)\n for i in range(lo, hi + 1):\n digit_count ^= 1 << int(s[i])\n return find_awesome(lo, hi, digit_count)\n\ndef longestawesome(s: str) -> int:\n (memo, state) = ({}, 0)\n (memo[state], ans) = (-1, 0)\n for (i, c) in enumerate(s):\n state ^= 1 << int(c)\n if state not in memo:\n memo[state] = i\n else:\n ans = max(ans, i - memo[state])\n for j in range(10):\n state1 = state ^ 1 << j\n if state1 in memo:\n ans = max(ans, i - memo[state1])\n return ans", "def longestawesome(s: str) -> int:\n bd = {}\n bd[0] = -1\n soen = 0\n for (i, n) in enumerate(s):\n soen ^= 1 << int(n)\n bd[soen] = -1\n bd[soen] = i\n for j in range(10):\n soen_cpy = soen\n soen_cpy ^= 1 << j\n if soen_cpy in bd:\n bd[soen_cpy] = i\n soen = 0\n max_ = bd[0] + 1\n for (i, n) in enumerate(s):\n soen ^= 1 << int(n)\n cur_max = bd[soen] - i\n if cur_max > max_:\n max_ = cur_max\n return max_", "def longestawesome(s: str) -> int:\n idx = [-1] + [len(s)] * 1023\n (ans, mask) = (0, 0)\n for (i, c) in enumerate(s):\n update = ord(c) - ord('0')\n mask ^= 1 << update\n ans = max(ans, i - idx[mask])\n for j in range(10):\n ans = ans = max(ans, i - idx[mask ^ 1 << j])\n idx[mask] = min(idx[mask], i)\n return ans", "def longestawesome(s: str) -> int:\n P = [0]\n for c in s:\n x = int(c)\n P.append(P[-1])\n P[-1] ^= 1 << x\n dict = {}\n valid = {1 << x for x in range(10)}\n valid.add(0)\n ans = 0\n for (j, q) in enumerate(P):\n for target in valid:\n i = dict.get(q ^ target, None)\n if i is not None:\n ans = max(ans, j - i)\n dict.setdefault(q, j)\n return ans", "def longestawesome(s: str) -> int:\n d = {}\n d[0] = -1\n mask = 0\n ans = 0\n for (i, ch) in enumerate(s):\n mask ^= 1 << int(ch)\n if mask in d and (i - d[mask]) % 2 == 0:\n ans = max(ans, i - d[mask])\n for j in range(10):\n mask_edit = mask ^ 1 << j\n if mask_edit in d and (i - d[mask_edit]) % 2 == 1:\n ans = max(ans, i - d[mask_edit])\n if mask not in d:\n d[mask] = i\n return ans", "def longestawesome(s: str) -> int:\n tmp = 0\n pos_map = {0: -1}\n ans = 1\n for i in range(len(s)):\n tmp ^= 1 << int(s[i])\n if tmp in pos_map:\n ans = max(ans, i - pos_map[tmp])\n for x in range(10):\n another_tmp = tmp ^ 1 << x\n if another_tmp in pos_map:\n ans = max(ans, i - pos_map[another_tmp])\n if tmp not in pos_map:\n pos_map[tmp] = i\n return ans", "def longestawesome(s: str) -> int:\n (memo, state) = ({}, 0)\n (memo[state], ans) = (-1, 0)\n for (i, c) in enumerate(s):\n state ^= 1 << int(c)\n if state not in memo:\n memo[state] = i\n else:\n ans = max(ans, i - memo[state])\n for n in range(10):\n state1 = state ^ 1 << n\n if state1 in memo:\n ans = max(ans, i - memo[state1])\n return ans", "def longestawesome(s):\n (res, cur, n) = (0, 0, len(s))\n seen = [-1] + [n] * 1024\n for (i, c) in enumerate(s):\n cur ^= 1 << int(c)\n for a in range(10):\n res = max(res, i - seen[cur ^ 1 << a])\n res = max(res, i - seen[cur])\n seen[cur] = min(seen[cur], i)\n return res", "def longestawesome(s: str) -> int:\n p = [0]\n for c in s:\n x = int(c)\n p.append(p[-1])\n p[-1] ^= 1 << x\n first = {}\n valid = {1 << x for x in range(10)}\n valid.add(0)\n res = 0\n for (j, pj) in enumerate(p):\n for target in valid:\n i = first.get(pj ^ target, None)\n if i is not None:\n res = max(res, j - i)\n first.setdefault(pj, j)\n return res", "def longestawesome(s: str) -> int:\n d = {0: -1}\n b = 0\n m = 0\n for (i, c) in enumerate(s):\n b ^= 1 << int(c)\n if not b or not b & b - 1:\n m = max(m, i - d.get(b, i - 1), i + 1)\n if not b:\n h = 1\n for _ in range(10):\n m = max(m, i - d.get(h, i - 1))\n h <<= 1\n else:\n m = max(m, i - d.get(b, i - 1))\n h = 1\n for _ in range(10):\n if h & b:\n m = max(m, i - d.get(~h & b, i - 1))\n else:\n m = max(m, i - d.get(h + b, i - 1))\n h <<= 1\n if b not in d:\n d[b] = i\n return m", "def longestawesome(s: str) -> int:\n prev = [-1] + [len(s)] * 1024\n best = 1\n mask = 0\n for i in range(len(s)):\n mask ^= 1 << int(s[i])\n for j in range(10):\n tmp = mask ^ 1 << j\n if best < i - prev[tmp] + 1:\n best = max(best, i - prev[tmp])\n best = max(best, i - prev[mask])\n prev[mask] = min(prev[mask], i)\n return best", "def longestawesome(s: str) -> int:\n\n def getMatchingMasks(mask):\n st = set([mask])\n for i in range(10):\n st.add(mask ^ 1 << i)\n return st\n mask = 0\n maskDict = dict()\n maskDict[0] = -1\n ans = 0\n for (idx, ch) in enumerate(s):\n digitVal = int(ch)\n mask ^= 1 << digitVal\n for match in getMatchingMasks(mask):\n if match in maskDict:\n ans = max(ans, idx - maskDict[match])\n if mask not in maskDict:\n maskDict[mask] = idx\n return ans", "def longestawesome(s: str) -> int:\n digit_cnt = [0 for _ in range(len(s) + 1)]\n for i in range(1, len(s) + 1):\n digit_cnt[i] = digit_cnt[i - 1] ^ 1 << int(s[i - 1])\n res = 1\n indx = {}\n indx[0] = 0\n for i in range(1, len(digit_cnt)):\n if digit_cnt[i] == 0:\n res = max(res, i)\n continue\n for d in range(10):\n if digit_cnt[i] ^ 1 << d in list(indx.keys()):\n res = max(res, i - indx[digit_cnt[i] ^ 1 << d])\n if not digit_cnt[i] in list(indx.keys()):\n indx[digit_cnt[i]] = i\n return res", "def __init__():\n self.seen = {0: -1}\n self.len = 0\n\ndef update_best_length(num, p):\n if num in self.seen:\n self.len = max(self.len, p - self.seen[num])\n for i in range(10):\n x = num ^ 1 << int(i)\n if x in self.seen:\n self.len = max(self.len, p - self.seen[x])\n\ndef longestawesome(s: str) -> int:\n num = 0\n for (p, c) in enumerate(s):\n num = num ^ 1 << int(c)\n self.update_best_length(num, p)\n if num not in self.seen:\n self.seen[num] = p\n return self.len", "import numpy as np\n\ndef longestawesome(s: str) -> int:\n (memo, state) = ({}, 0)\n p = np.arange(15).reshape(3, 5)\n (memo[state], ans) = (-1, 0)\n for (i, c) in enumerate(s):\n state ^= 1 << int(c)\n if state not in memo:\n memo[state] = i\n else:\n ans = max(ans, i - memo[state])\n for n in range(10):\n state1 = state ^ 1 << n\n if state1 in memo:\n ans = max(ans, i - memo[state1])\n return ans", "def longestawesome(s: str) -> int:\n pattern = [1 << i for i in range(10)]\n (seen, state) = ({}, 0)\n seen[state] = -1\n answer = 0\n for (i, c) in enumerate(s):\n state ^= 1 << int(c)\n if state in seen:\n answer = max(answer, i - seen[state])\n for p in pattern:\n target = state ^ p\n if target in seen:\n answer = max(answer, i - seen[target])\n if state not in seen:\n seen[state] = i\n return answer", "def longestawesome(s: str) -> int:\n s = [ord(x) - ord('0') for x in s]\n ans = 0\n m = [None] * 1024\n m[0] = -1\n y = 0\n for (i, x) in enumerate(s):\n y ^= 1 << x\n for j in range(11):\n p = y ^ 1 << j & 1023\n if m[p] != None:\n ans = max(ans, i - m[p])\n if m[p] == None:\n m[y] = i\n return ans", "def longestawesome(s: str) -> int:\n subsum = [0]\n rtn = 0\n first_appear = {}\n first_appear[0] = 0\n for (i, x) in enumerate(s):\n subsum.append(subsum[i] ^ 1 << int(x))\n if subsum[i + 1] not in first_appear:\n first_appear[subsum[i + 1]] = i + 1\n else:\n rtn = max(rtn, i + 1 - first_appear[subsum[i + 1]])\n for j in range(10):\n if subsum[i + 1] ^ 1 << j in first_appear:\n rtn = max(rtn, i + 1 - first_appear[subsum[i + 1] ^ 1 << j])\n return rtn", "def longestawesome(s: str) -> int:\n res = 0\n count = 0\n record = {count: -1}\n for (i, ss) in enumerate(s):\n count ^= 1 << int(ss)\n if count not in record:\n record[count] = i\n res = max(res, max((i - record[count ^ 1 << t + 1 >> 1] if count ^ 1 << t + 1 >> 1 in record else 0 for t in range(-1, 10))))\n return res", "def longestawesome(s: str) -> int:\n m = collections.defaultdict(lambda : 0)\n\n def convertToKey():\n x = 0\n for i in range(10):\n x += m[i] % 2 << i\n return x\n presum = {}\n presum[0] = -1\n res = 0\n for (i, j) in enumerate(s):\n m[int(j)] += 1\n key = convertToKey()\n if key in presum:\n res = max(res, i - presum[key])\n for x in range(10):\n newKey = key\n if key >> x & 1:\n newKey -= 1 << x\n else:\n newKey |= 1 << x\n if newKey in presum:\n res = max(res, i - presum[newKey])\n if key not in presum:\n presum[key] = i\n return res", "def longestawesome(s: str) -> int:\n pos = {}\n\n def f(c):\n return ord(c) - ord('0')\n (mask, ans) = (0, 1)\n pos[0] = -1\n for (n, ch) in enumerate(s):\n p = f(ch)\n mask ^= 1 << p\n if mask in pos:\n len = n - pos[mask]\n if len % 2 == 0:\n ans = max(ans, len)\n for nn in range(10):\n nmask = mask ^ 1 << nn\n if nmask in pos:\n len = n - pos[nmask]\n if len % 2 == 1:\n ans = max(ans, len)\n if mask not in pos:\n pos[mask] = n\n return ans", "def longestawesome(s: str) -> int:\n first_pos = [-1 for i in range(1024)]\n first_pos[0] = 0\n cur_xor = 0\n xors = [0] + [1 << i for i in range(10)]\n max_len = 0\n for i in range(len(s)):\n cur_xor = cur_xor ^ 1 << int(s[i])\n for try_xor in xors:\n prev_xor = cur_xor ^ try_xor\n if first_pos[prev_xor] != -1:\n max_len = max(max_len, i - first_pos[prev_xor] + 1)\n if first_pos[cur_xor] == -1:\n first_pos[cur_xor] = i + 1\n return max_len", "from typing import Dict, Set\nfrom collections import Counter\n\ndef longestawesome(s: str) -> int:\n mask_pos = {0: -1}\n mask = 0\n result = 0\n for pos in range(len(s)):\n mask ^= 1 << int(s[pos])\n result = max(result, pos - mask_pos.get(mask, pos))\n for shift in range(10):\n result = max(result, pos - mask_pos.get(mask ^ 1 << shift, pos))\n mask_pos.setdefault(mask, pos)\n return result\n\ndef longestawesome1(s: str) -> int:\n result = 0\n for start in range(len(s)):\n count: Dict[str, int] = Counter()\n odd = 0\n for end in range(start, len(s)):\n count[s[end]] += 1\n if count[s[end]] & 1 > 0:\n odd += 1\n else:\n odd -= 1\n if odd <= 1:\n result = max(result, end + 1 - start)\n return result", "def longestawesome(s: str) -> int:\n F = {0: 0}\n res = 0\n mask = 0\n j = 0\n for c in s:\n j += 1\n mask ^= 1 << ord(c) - ord('0')\n for i in range(0, 10):\n new_mask = mask ^ 1 << i\n if new_mask in list(F.keys()):\n res = max(res, j - F[new_mask])\n if not mask:\n res = max(res, j)\n if mask not in list(F.keys()):\n F[mask] = j\n return res", "def longestawesome(s):\n d = {0: -1}\n t = 0\n ans = 0\n for i in range(len(s)):\n num = int(s[i])\n t ^= 1 << 9 - num\n if t not in d:\n d[t] = i\n for m in range(10):\n temp = t ^ 1 << 9 - m\n if temp in d:\n ans = max(ans, i - d[temp])\n else:\n ans = max(ans, i - d[t])\n for m in range(10):\n temp = t ^ 1 << 9 - m\n if temp in d:\n ans = max(ans, i - d[temp])\n return ans", "def longestawesome(s: str) -> int:\n (seen, prefix, ans) = ({0: -1}, 0, 0)\n for (i, char) in enumerate(s):\n prefix ^= 1 << int(char)\n ans = max(ans, i - seen.get(prefix, float('inf')))\n for j in range(10):\n p = prefix ^ 1 << j\n ans = max(ans, i - seen.get(p, float('inf')))\n if prefix not in seen:\n seen[prefix] = i\n return ans", "from collections import Counter\n\ndef longestawesome(s: str) -> int:\n seen = {0: -1}\n (res, prefix) = (0, 0)\n for (i, num) in enumerate(map(int, s)):\n prefix ^= 1 << num\n res = max(res, i - seen.get(prefix, float('inf')))\n for k in range(10):\n prefix_add_odd = prefix ^ 1 << k\n res = max(res, i - seen.get(prefix_add_odd, float('inf')))\n seen.setdefault(prefix, i)\n return res", "def longestawesome(s: str) -> int:\n dp = {}\n dp[0] = -1\n (state, ans) = (0, 0)\n for (i, c) in enumerate(s):\n state ^= 1 << int(c)\n if state not in dp:\n dp[state] = i\n else:\n ans = max(ans, i - dp[state])\n for num in range(10):\n if state ^ 1 << num in dp:\n ans = max(ans, i - dp[state ^ 1 << num])\n return ans", "def longestawesome(s: str) -> int:\n idxs = [1000000000.0 for _ in range(1024)]\n idxs[0] = -1\n ans = 0\n mask = 0\n for (i, ch) in enumerate(s):\n mask ^= 1 << ord(ch) - ord('0')\n ans = max([ans, i - idxs[mask]] + [i - idxs[mask ^ 1 << j] for j in range(10)])\n idxs[mask] = min(idxs[mask], i)\n return ans", "def count_set_bits(n):\n count = 0\n for i in range(32):\n count += n >> i & 1\n return count\n\ndef longestawesome(s: str) -> int:\n xormap = dict()\n xormap[0] = -1\n xor = 0\n max_length = 0\n for i in range(len(s)):\n xor = xor ^ 1 << int(s[i])\n max_length = max(max_length, i - xormap.get(xor, float('Inf')))\n for j in range(10):\n temp_xor = xor ^ 1 << j\n max_length = max(max_length, i - xormap.get(temp_xor, float('Inf')))\n xormap[xor] = min(i, xormap.get(xor, float('Inf')))\n return max_length", "def longestawesome(s: str) -> int:\n d = collections.defaultdict(int)\n d[0] = -1\n mask = 0\n ans = 0\n for i in range(len(s)):\n mask ^= 1 << int(s[i])\n if mask in d:\n ans = max(ans, i - d[mask])\n else:\n d[mask] = i\n for j in range(10):\n tem = mask\n tem ^= 1 << j\n if tem in d:\n ans = max(ans, i - d[tem])\n return ans", "def longestawesome(s: str) -> int:\n digit = []\n for i in range(10):\n digit.append(1 << i)\n digit.append(0)\n cum = 0\n bk = [-2 for _ in range(2 ** 10 + 1)]\n bk[0] = -1\n ans = 0\n for (i, x) in enumerate(s):\n x = int(x)\n cum ^= digit[x]\n for d in digit:\n mask = cum ^ d\n if bk[mask] >= -1:\n ans = max(ans, i - bk[mask])\n if bk[cum] == -2:\n bk[cum] = i\n return ans", "from collections import defaultdict\n\ndef longestawesome(s: str) -> int:\n n = len(s)\n dp = [n for i in range(1024)]\n dp[0] = -1\n (mask, ret) = (0, 0)\n for (i, c) in enumerate(s):\n mask ^= 1 << int(c)\n for num in range(10):\n ret = max(ret, i - dp[mask ^ 1 << num])\n ret = max(ret, i - dp[mask])\n dp[mask] = min(dp[mask], i)\n return ret", "def longestawesome(s: str) -> int:\n pattern = 0\n d = {pattern: -1}\n res = 0\n for (cur_i, x) in enumerate(s):\n pattern ^= 1 << int(x)\n for i in range(10):\n new_pattern = pattern ^ 1 << i\n res = max(res, cur_i - d.get(new_pattern, cur_i))\n res = max(res, cur_i - d.get(pattern, cur_i))\n d.setdefault(pattern, cur_i)\n return res", "def longestawesome(s: str) -> int:\n bitmask = {}\n mask = 0\n ans = 1\n n = len(s)\n bitmask[0] = -1\n for i in range(n):\n mask ^= 1 << int(s[i])\n if mask in bitmask:\n ans = max(ans, i - bitmask[mask])\n for j in range(10):\n test = mask ^ 1 << j\n if test in bitmask:\n ans = max(ans, i - bitmask[test])\n if mask not in bitmask:\n bitmask[mask] = i\n return ans", "import numpy as np\n\ndef longestawesome(s: str) -> int:\n (mask, res) = (0, 0)\n dp = np.full(1024, len(s))\n dp[0] = -1\n for i in range(len(s)):\n mask ^= 1 << ord(s[i]) - 48\n for j in range(11):\n check_mask = 1023 & (mask ^ 1 << j)\n res = max(res, i - dp[check_mask])\n dp[mask] = min(dp[mask], i)\n return res", "def longestawesome(s: str) -> int:\n if len(s) == 0:\n return 0\n max_len = 1\n p = [0] * len(s)\n seen = {0: -1}\n for i in range(0, len(s)):\n d = ord(s[i]) - ord('0')\n p[i] = 1 << d ^ p[i - 1]\n for od in range(10):\n x = p[i] | 1 << od\n if x in seen:\n max_len = max(max_len, i - seen[x])\n y = p[i] & ~(1 << od)\n if y in seen:\n max_len = max(max_len, i - seen[y])\n if p[i] not in seen:\n seen[p[i]] = i\n return max_len", "def longestawesome(s: str) -> int:\n (m, state) = (defaultdict(int), [0] * 10)\n m[tuple(state)] = -1\n ans = 0\n for (i, c) in enumerate(s):\n k = int(c)\n state[k] = 1 - state[k]\n tstate = tuple(state)\n if tstate not in m:\n m[tstate] = i\n else:\n ans = max(ans, i - m[tstate])\n for n in range(10):\n state[n] = 1 - state[n]\n tstate = tuple(state)\n if tstate in m:\n ans = max(ans, i - m[tstate])\n state[n] = 1 - state[n]\n return ans", "def longestawesome(s: str) -> int:\n M = {0: -1}\n ans = 0\n code = 0\n D = [1 << d for d in range(10)]\n for (i, c) in enumerate(s):\n code = code ^ 1 << ord(c) - ord('0')\n if code in M:\n ans = max(ans, i - M[code])\n for dc in D:\n dcode = code ^ dc\n if dcode in M:\n ans = max(ans, i - M[dcode])\n if code not in M:\n M[code] = i\n return ans", "def longestawesome(s: str) -> int:\n (df, dl) = ({}, {})\n df[0] = -1\n sm = 0\n res = 1\n for (i, c) in enumerate(s):\n sm ^= 1 << int(c)\n if sm not in df:\n df[sm] = i\n dl[sm] = i\n for (fk, fv) in df.items():\n for (lk, lv) in dl.items():\n if lv > fv:\n xor = fk ^ lk\n if xor == 0 or xor & xor - 1 == 0:\n res = max(res, lv - fv)\n return res", "from typing import List\n\ndef longestawesome(s: str) -> int:\n res = 0\n pattern: List[bool] = [False] * 10\n existing = {tuple(pattern): -1}\n for (cur_i, char) in enumerate(s):\n num = int(char)\n pattern[num] = not pattern[num]\n for i in range(10):\n new_pattern = pattern.copy()\n new_pattern[i] = not new_pattern[i]\n res = max(res, cur_i - existing.get(tuple(new_pattern), cur_i))\n res = max(res, cur_i - existing.get(tuple(pattern), cur_i))\n existing.setdefault(tuple(pattern), cur_i)\n return res", "def longestawesome(s: str) -> int:\n sLength = len(s)\n earliestBinaries = {}\n current = [0] * 10\n earliestBinaries[tuple(current)] = -1\n currentMax = 0\n\n def computeMaxFromNeighbors(counter, currentTuple):\n currentMax = 0\n if currentTuple in earliestBinaries:\n currentMax = max(currentMax, counter - earliestBinaries[currentTuple])\n neighborList = list(currentTuple)\n for i in range(len(currentTuple)):\n neighborList[i] = 1 - neighborList[i]\n neighborTuple = tuple(neighborList)\n if neighborTuple in earliestBinaries:\n currentMax = max(currentMax, counter - earliestBinaries[neighborTuple])\n neighborList[i] = 1 - neighborList[i]\n return currentMax\n for (counter, char) in enumerate(s):\n current[int(char)] = 1 - current[int(char)]\n currentTuple = tuple(current)\n currentMax = max(currentMax, computeMaxFromNeighbors(counter, currentTuple))\n if currentTuple not in earliestBinaries:\n earliestBinaries[currentTuple] = counter\n return currentMax", "def longestawesome(s: str) -> int:\n mx = 0\n table = {frozenset(): -1}\n (acs, cs) = (set(), set())\n for (i, c) in enumerate(s):\n acs.add(c)\n if c in cs:\n cs.remove(c)\n else:\n cs.add(c)\n fcs = frozenset(cs)\n if fcs in table:\n mx = max(mx, i - table[fcs])\n for c in acs:\n if c in cs:\n cs.remove(c)\n rfcs = frozenset(cs)\n cs.add(c)\n if rfcs in table:\n mx = max(mx, i - table[rfcs])\n else:\n cs.add(c)\n rfcs = frozenset(cs)\n cs.remove(c)\n if rfcs in table:\n mx = max(mx, i - table[rfcs])\n table[fcs] = min(table.get(fcs, float('inf')), i)\n return mx", "def longestawesome(s: str) -> int:\n (dic, mask, res) = ({0: -1}, 0, 1)\n for (i, ch) in enumerate(s):\n mask ^= 1 << int(ch)\n dic.setdefault(mask, i)\n res = max(res, i - min([dic[mask]] + [dic.get(mask ^ 1 << k, float('inf')) for k in range(11)]))\n return res", "def longestawesome(s: str) -> int:\n n = len(s)\n res = 0\n mask = 0\n idx = [n + 1] * 1024\n idx[0] = -1\n for (i, c) in enumerate(s):\n mask ^= 1 << ord(c) - ord('0')\n res = max(res, i - idx[mask])\n res = max(res, max([i - idx[mask ^ 1 << j] for j in range(10)]))\n idx[mask] = min(idx[mask], i)\n return res", "from collections import defaultdict\n\ndef longestawesome(s: str) -> int:\n dlist = [1] * 10\n for i in range(9):\n dlist[i + 1] = dlist[i] * 2\n count = defaultdict(int)\n dp = dict()\n ans = 0\n dp[0] = -1\n for (i, num) in enumerate(s):\n count[num] += 1\n cur = 0\n curdp = 10 * [0]\n for ar in range(10):\n st = str(ar)\n val = count[st] % 2\n cur += val * dlist[ar]\n curdp[ar] = val\n if cur in dp:\n ans = max(ans, i - dp[cur])\n else:\n dp[cur] = i\n for ar in range(10):\n if curdp[ar] == 1:\n val = -1\n else:\n val = 1\n cur += val * dlist[ar]\n if cur in dp:\n ans = max(ans, i - dp[cur])\n cur -= val * dlist[ar]\n return ans", "def longestawesome(s: str) -> int:\n pattern = [False] * 10\n d = {tuple(pattern): -1}\n res = 0\n for (i, x) in enumerate(s):\n num = int(x)\n pattern[num] = not pattern[num]\n res = max(res, i - d.get(tuple(pattern), i))\n for k in range(10):\n new_pattern = pattern.copy()\n new_pattern[k] = not new_pattern[k]\n res = max(res, i - d.get(tuple(new_pattern), i))\n d.setdefault(tuple(pattern), i)\n return res", "def longestawesome(s: str) -> int:\n d = defaultdict(lambda : 1e+20)\n d[0] = -1\n res = 0\n mask = 0\n for (i, val) in enumerate(s):\n mask ^= 1 << int(val)\n d[mask] = min(d[mask], i)\n res = max(res, i - d[mask])\n for k in range(11):\n res = max(res, i - d[mask ^ 1 << k])\n return res", "import collections\n\ndef longestawesome(s: str) -> int:\n n = len(s)\n memo = [0] * 10\n d = collections.defaultdict(list)\n ans = 1\n d[0].append(-1)\n for (i, x) in enumerate(s):\n memo[int(x)] += 1\n key = 0\n for (j, y) in enumerate(memo):\n if y % 2 == 1:\n key += 2 ** j\n d[key].append(i)\n if len(d[key]) >= 2:\n ans = max(ans, d[key][-1] - d[key][0])\n for (j, y) in enumerate(memo):\n if y % 2 == 0:\n new_key = key + 2 ** j\n if len(d[new_key]) > 0:\n ans = max(ans, d[key][-1] - d[new_key][0])\n else:\n new_key = key - 2 ** j\n if len(d[new_key]) > 0:\n ans = max(ans, d[key][-1] - d[new_key][0])\n return ans", "def longestawesome(s: str) -> int:\n bit_mask_mapping = {tuple([0] * 10): -1}\n bit_mask = [0] * 10\n max_len = 0\n for (ch_i, ch) in enumerate(s):\n cur_int = int(ch)\n bit_mask[cur_int] ^= 1\n bit_mask_str = tuple(bit_mask)\n if bit_mask_str in bit_mask_mapping:\n max_len = max(max_len, ch_i - bit_mask_mapping[bit_mask_str])\n for j in range(10):\n tmp_mask = tuple(bit_mask[:j] + [bit_mask[j] ^ 1] + bit_mask[j + 1:])\n if tmp_mask in bit_mask_mapping:\n max_len = max(max_len, ch_i - bit_mask_mapping[tmp_mask])\n if bit_mask_str not in bit_mask_mapping:\n bit_mask_mapping[bit_mask_str] = ch_i\n return max_len", "def longestawesome(s: str) -> int:\n digits = [2 ** i for i in range(10)] + [0]\n (max_len, xor, dictF, dictB) = (0, 0, {0: -1}, {})\n for i in range(len(s)):\n xor = xor ^ digits[int(s[i])]\n if xor not in dictF:\n dictF[xor] = i\n dictB[xor] = i\n max_len = 0\n for i in dictB:\n max_len = max([max_len] + [dictB[i] - dictF[j ^ i] for j in digits if j ^ i in dictF])\n return max_len", "def longestawesome(s: str) -> int:\n left_most_masks = {0: -1}\n valid_masks = {1 << i for i in range(10)} | {0}\n ans = 0\n cur_mask = 0\n for (idx, x) in enumerate(list(s)):\n cur_mask = cur_mask ^ 1 << int(x)\n for valid_mask in valid_masks:\n left_mask = valid_mask ^ cur_mask\n if left_mask in left_most_masks:\n ans = max(ans, idx - left_most_masks[left_mask])\n if cur_mask not in left_most_masks:\n left_most_masks[cur_mask] = idx\n return ans", "def longestawesome(s: str) -> int:\n n = len(s)\n (m, seen, ans) = (0, [-1] + [n] * 1024, 1)\n for (i, x) in enumerate(s):\n m ^= 1 << int(x)\n for d in range(10):\n ans = max(ans, i - seen[m ^ 1 << d])\n ans = max(ans, i - seen[m])\n seen[m] = min(seen[m], i)\n return ans", "def longestawesome(s: str) -> int:\n rec = 0\n seen = {0: -1}\n mask = 0\n for (i, n) in enumerate(s):\n mask ^= 1 << int(n)\n if mask in seen:\n rec = max(rec, i - seen[mask])\n else:\n seen[mask] = i\n for d in range(10):\n omask = mask ^ 1 << d\n if omask in seen:\n rec = max(rec, i - seen[omask])\n return rec", "def longestawesome(s: str) -> int:\n mem = {0: -1}\n res = 0\n state = 0\n for (i, x) in enumerate(s):\n idx = ord(x) - ord('0')\n state ^= 1 << idx\n if state in mem:\n res = max(res, i - mem[state])\n for shift in range(10):\n tmp = state ^ 1 << shift\n if tmp in mem:\n res = max(res, i - mem[tmp])\n if state not in mem:\n mem[state] = i\n return res", "def longestawesome(s: str) -> int:\n count = 0\n digits = 0\n for c in s:\n c = int(c)\n digits ^= 1 << c\n if digits & 1 << c != 0:\n count += 1\n else:\n count -= 1\n result = 0\n n = len(s)\n for i in range(n):\n digits2 = digits\n count2 = count\n for j in reversed(list(range(i, n))):\n if j - i + 1 <= result or count2 <= 1:\n result = max(result, j - i + 1)\n break\n c = int(s[j])\n digits2 ^= 1 << c\n if digits2 & 1 << c != 0:\n count2 += 1\n else:\n count2 -= 1\n c = int(s[i])\n digits ^= 1 << c\n if digits & 1 << c != 0:\n count += 1\n else:\n count -= 1\n return result\n\ndef longestawesome(s: str) -> int:\n from collections import defaultdict\n digits = {}\n digits[0] = -1\n prefix = 0\n result = 0\n for i in range(len(s)):\n c = int(s[i])\n prefix ^= 1 << c\n if prefix in digits:\n result = max(result, i - digits[prefix])\n else:\n digits[prefix] = i\n for k in range(10):\n tmp = prefix ^ 1 << k\n if tmp in digits:\n result = max(result, i - digits[tmp])\n return result", "def longestawesome(s: str) -> int:\n mask = {n: 1 << n for n in range(10)}\n target = [0] + list(mask.values())\n loc = [-2] * (1 << 10)\n for x in target:\n loc[x] = -1\n sofar = 0\n ans = 0\n for (idx, ch) in enumerate(s):\n m = mask[int(ch)]\n sofar = sofar ^ m\n if loc[sofar] > -2:\n ans = max(ans, idx - loc[sofar])\n for t in target:\n ntarget = sofar ^ t\n if loc[ntarget] == -2:\n loc[ntarget] = idx\n return ans", "def longestawesome(s: str) -> int:\n N = len(s)\n prefix = [0 for _ in range(N + 1)]\n for (i, value) in enumerate(s):\n x = int(value)\n prefix[i + 1] = prefix[i] ^ 1 << x\n valids = set([0])\n for i in range(10):\n valids.add(1 << i)\n ans = 0\n seen = collections.defaultdict(int)\n for (j, q) in enumerate(prefix):\n for target in valids:\n want = q ^ target\n if want not in seen:\n continue\n i = seen[want]\n ans = max(ans, j - i)\n if q not in seen:\n seen[q] = j\n return ans", "def longestawesome(s: str) -> int:\n n = len(s)\n ans = 0\n d = {0: -1}\n rolling = 0\n for (i, v) in enumerate(s):\n rolling ^= 1 << int(v)\n for x in range(10):\n diff = rolling ^ 1 << x\n if diff in d:\n ans = max(ans, i - d[diff])\n if rolling in d:\n ans = max(ans, i - d[rolling])\n else:\n d[rolling] = i\n return ans", "def longestawesome(s: str) -> int:\n n = len(s)\n res = mask = 0\n seen = [n] * 1024\n seen[0] = -1\n for i in range(n):\n mask ^= 1 << int(s[i])\n res = max(res, i - seen[mask])\n for num in range(10):\n res = max(res, i - seen[mask ^ 1 << num])\n seen[mask] = min(seen[mask], i)\n return res", "def longestawesome(s: str) -> int:\n N = len(s)\n prefix = [0 for _ in range(N + 1)]\n for i in range(1, N + 1):\n x = int(s[i - 1])\n prefix[i] = prefix[i - 1] ^ 1 << x\n valids = [0]\n for i in range(10):\n valids.append(1 << i)\n seen = collections.defaultdict(int)\n ans = 0\n for (i, p) in enumerate(prefix):\n for valid in valids:\n want = p ^ valid\n if want not in seen:\n continue\n k = seen[want]\n cand = i - k\n ans = max(ans, cand)\n if p not in seen:\n seen[p] = i\n return ans", "def gen_prefixes(s):\n ans = {0: [0]}\n parity = 0\n for (ind, ch) in enumerate(s):\n after = ind + 1\n parity ^= 1 << int(ch)\n ans.setdefault(parity, [])\n ans[parity].append(after)\n return ans\n\ndef get_awesomes(prefixes):\n ans = 1\n for A in prefixes:\n for xbit_ind in range(11):\n if xbit_ind == 10:\n B = A\n else:\n B = A ^ 1 << xbit_ind\n if B not in prefixes:\n continue\n (pA, pB) = (prefixes[A], prefixes[B])\n ans = max(ans, max(pB) - min(pA))\n ans = max(ans, max(pA) - min(pB))\n return ans\n\ndef longestawesome(s: str) -> int:\n prefixes = gen_prefixes(s)\n return get_awesomes(prefixes)", "def longestawesome(s: str) -> int:\n h = {}\n ll = len(s)\n m = 0\n maxi = -1\n h[0] = -1\n for i in range(0, len(s)):\n m = m ^ 1 << int(s[i])\n if m in h:\n maxi = max(maxi, i - h.get(m))\n else:\n h[m] = i\n for l in range(0, 10):\n new_hash = m ^ 1 << l\n if new_hash in h:\n maxi = max(maxi, i - h[new_hash])\n return maxi", "def longestawesome(s: str) -> int:\n max_len = 0\n mapping_pos = {0: -1}\n acc = 0\n for (idx, digit) in enumerate([ord(c) - ord('0') for c in s]):\n acc ^= 1 << digit\n for x in range(10):\n tmp = acc ^ 1 << x\n if tmp in mapping_pos:\n max_len = max(max_len, idx - mapping_pos[tmp])\n if acc in mapping_pos:\n max_len = max(max_len, idx - mapping_pos[acc])\n if acc not in mapping_pos:\n mapping_pos[acc] = idx\n return max_len", "def longestawesome(s: str) -> int:\n d = defaultdict(int)\n d[0] = -1\n mask = 0\n ans = 0\n for i in range(len(s)):\n curr = ord(s[i]) - ord('0')\n mask ^= 1 << curr\n if mask in d:\n ans = max(ans, i - d[mask])\n else:\n d[mask] = i\n for j in range(10):\n new_mask = mask ^ 1 << j\n if new_mask in d:\n ans = max(ans, i - d[new_mask])\n return ans", "def longestawesome(s: str) -> int:\n seen = {0: -1}\n max_len = 0\n n = 0\n for i in range(len(s)):\n digit = int(s[i])\n n = n ^ 1 << digit\n if n in seen:\n max_len = max(max_len, i - seen[n])\n for start in range(10):\n m = n ^ 1 << start\n if m in seen:\n max_len = max(max_len, i - seen[m])\n if n not in seen:\n seen[n] = i\n return max_len", "def longestawesome(s: str) -> int:\n seen = [len(s)] * (1 << 10)\n seen[0] = -1\n mask = 0\n res = 0\n for (i, char) in enumerate(s):\n mask ^= 1 << int(char)\n res = max(res, i - seen[mask])\n for j in range(10):\n temp = 1 << j ^ mask\n res = max(res, i - seen[temp])\n seen[mask] = min(seen[mask], i)\n return res", "def longestawesome(s: str) -> int:\n prefix = {0: -1}\n curr = 0\n length = 1\n powers = [0] + [1 << j for j in range(10)]\n for (i, c) in enumerate(s):\n curr ^= 1 << int(c)\n for p in powers:\n length = max(length, i - prefix.get(curr ^ p, len(s)))\n if curr not in prefix:\n prefix[curr] = i\n return length", "def longestawesome(s: str) -> int:\n mask = 0\n pre = {0: -1}\n result = 0\n for i in range(10):\n pre[0 ^ 1 << i] = -1\n for (i, c) in enumerate(s):\n n = 1 << int(c)\n mask ^= n\n if mask in pre:\n result = max(result, i - pre[mask])\n for ii in range(10):\n nmask = mask ^ 1 << ii\n if nmask not in pre:\n pre[nmask] = i\n return result", "def longestawesome(s: str) -> int:\n (res, mask) = (0, 0)\n n = len(s)\n memo = [n] * 1024\n memo[0] = -1\n for (i, ch) in enumerate(s):\n mask ^= 1 << int(ch)\n res = max(res, i - memo[mask])\n for j in range(10):\n test_mask = mask ^ 1 << j\n res = max(res, i - memo[test_mask])\n memo[mask] = min(memo[mask], i)\n return res", "def longestawesome(s):\n d = {0: -1}\n cands = {1 << x for x in range(10)}\n cands.add(0)\n cur = 0\n res = 0\n for (i, c) in enumerate(s):\n cur ^= 1 << int(c)\n for cand in cands:\n res = max(res, i - d.get(cur ^ cand, i))\n if cur not in d:\n d[cur] = i\n return res", "def longestawesome(s: str) -> int:\n d = 0\n m = 0\n l = []\n l.append(d)\n dd = {}\n dd[0] = [0, 0]\n for i in range(len(s)):\n c = s[i]\n d = d ^ 1 << int(c)\n l.append(d)\n if d not in dd:\n dd[d] = [i + 1, i + 1]\n else:\n dd[d] = [min(dd[d][0], i + 1), max(dd[d][1], i + 1)]\n di = {}\n for i in range(2 ** 10):\n ll = {i}\n for k in range(10):\n ll.add(i ^ 1 << k)\n di[i] = ll\n for i in dd:\n for j in di[i]:\n if j in dd:\n m = max(abs(dd[j][0] - dd[i][1]), m)\n m = max(abs(dd[j][1] - dd[i][0]), m)\n return m", "def longestawesome(s: str) -> int:\n d = {0: -1}\n mask = 0\n maxi = 1\n for i in range(len(s)):\n x = int(s[i])\n mask = mask ^ 1 << x\n for j in range(0, 10):\n if mask ^ 1 << j in d:\n maxi = max(maxi, i - d[mask ^ 1 << j])\n if mask in d:\n maxi = max(maxi, i - d[mask])\n else:\n d[mask] = i\n return maxi", "def longestawesome(s: str) -> int:\n cur = ans = 0\n m = {}\n for (i, c) in enumerate(s):\n cur ^= 1 << int(c)\n if cur == 0:\n ans = max(ans, i + 1)\n elif cur == 2 ** int(math.log(cur, 2)):\n ans = max(ans, i + 1)\n else:\n for j in range(10):\n new = cur ^ 1 << j\n if new in m:\n ans = max(i - m[new], ans)\n if cur not in m:\n m[cur] = i\n return ans", "def longestawesome(s: str) -> int:\n earliest_occ = defaultdict(lambda : float('inf'))\n earliest_occ[0] = -1\n msk = 0\n ans = 1\n for i in range(len(s)):\n msk ^= 1 << int(s[i])\n earliest_occ[msk] = min(i, earliest_occ[msk])\n for j in range(10):\n ans = max(ans, i - earliest_occ[msk ^ 1 << j])\n ans = max(ans, i - earliest_occ[msk])\n return ans", "def longestawesome(s: str) -> int:\n ans = 1\n mask = 0\n memo = {0: -1}\n for (idx, ch) in enumerate(s):\n mask = mask ^ 1 << int(ch)\n if mask in memo:\n ans = max(ans, idx - memo[mask])\n for i in range(10):\n check = mask ^ 1 << i\n if check in memo:\n ans = max(ans, idx - memo[check])\n if not mask in memo:\n memo[mask] = idx\n return ans", "def longestawesome(s: str) -> int:\n s = [int(c) for c in s]\n seen = {0: -1}\n valid = [0] + [1 << i for i in range(10)]\n totSum = 0\n res = 0\n N = len(s)\n for i in range(N):\n totSum ^= 1 << s[i]\n for y in valid:\n needed = totSum ^ y\n if needed in seen:\n res = max(res, i - seen[needed])\n if totSum not in seen:\n seen[totSum] = i\n return res", "def longestawesome(s: str) -> int:\n n = len(s)\n if n <= 1:\n return n\n dp = [-1] + [n] * 1023\n (mask, res) = (0, 0)\n for i in range(n):\n mask = mask ^ 1 << int(s[i])\n for j in range(11):\n ch_mask = 1023 & (mask ^ 1 << j)\n res = max(res, i - dp[ch_mask])\n dp[mask] = min(i, dp[mask])\n return res", "def longestawesome(s: str) -> int:\n curr = 0\n longest = 0\n first = {0: -1}\n for (i, c) in enumerate(s):\n curr ^= 1 << int(c)\n if curr in first:\n longest = max(longest, i - first[curr])\n else:\n first[curr] = i\n mask = 1 << 9\n while mask > 0:\n if curr ^ mask in first:\n longest = max(longest, i - first[curr ^ mask])\n mask >>= 1\n return longest", "def longestawesome(s: str) -> int:\n if s == s[::-1]:\n return len(s)\n (pattern, re) = (0, 0)\n exit = {pattern: -1}\n for (idx, val) in enumerate(s):\n pattern ^= 1 << int(val)\n for k in range(10):\n new_pattern = pattern ^ 1 << k\n re = max(re, idx - exit.get(new_pattern, idx))\n re = max(re, idx - exit.get(pattern, idx))\n exit.setdefault(pattern, idx)\n return re", "def longestawesome(s: str) -> int:\n cur = res = 0\n d = defaultdict(lambda : float('inf'), {0: -1})\n for (i, ch) in enumerate(s):\n cur ^= 1 << int(ch)\n res = max(res, i - d[cur])\n for j in range(10):\n res = max(res, i - d[cur ^ 1 << j])\n d[cur] = min(d[cur], i)\n return res", "def longestawesome(s: str) -> int:\n max_val = 0\n seen = {0: -1}\n cur = 0\n for (i, char) in enumerate(s):\n cur ^= 1 << int(char)\n seen.setdefault(cur, i)\n max_val = max(max_val, i - seen[cur])\n for a in range(10):\n max_val = max(max_val, i - seen.get(cur ^ 1 << a, i))\n return max_val", "def longestawesome(s: str) -> int:\n cur = res = 0\n check = defaultdict(lambda : float('inf'))\n check[0] = -1\n for (i, c) in enumerate(s):\n c = int(c)\n cur ^= 1 << c\n res = max(res, i - check[cur])\n for a in range(10):\n res = max(res, i - check[cur ^ 1 << a])\n check[cur] = min(check[cur], i)\n return res", "def longestawesome(s: str) -> int:\n ls = len(s)\n table = [-1] + [ls] * 1023\n mask = res = 0\n for i in range(ls):\n mask ^= 1 << int(s[i])\n for j in range(11):\n temp = mask\n temp ^= 1023 & 1 << j\n res = max(res, i - table[temp])\n if table[mask] == ls:\n table[mask] = i\n return res", "from collections import defaultdict\n\ndef longestawesome(s: str) -> int:\n\n def isPalindrome(dic, l, r):\n odds = set()\n length = 0\n for (k, v) in list(dic.items()):\n if v % 2 == 1:\n odds.add(k)\n length += v\n if len(odds) == 0 or len(odds) == 1:\n return length\n elif len(odds) == 2:\n for num in odds:\n if num == l or num == r:\n return length - 1\n return 0\n elif len(odds) == 3:\n flag = 0\n for num in odds:\n if num == l or num == r:\n flag += 1\n if flag == 2:\n return length - 2\n else:\n return 0\n else:\n return 0\n\n def compact(s):\n numbers = []\n counts = []\n for num in s:\n if len(numbers) == 0 and len(counts) == 0:\n numbers.append(num)\n counts.append(1)\n continue\n if num == numbers[-1]:\n counts[-1] += 1\n else:\n numbers.append(num)\n counts.append(1)\n return (numbers, counts)\n\n def rollingHash(numbers, counts, l):\n anss = []\n dic = defaultdict(int)\n cur_max = 0\n max_acc = 0\n for i in range(l):\n num = numbers[i]\n cnt = counts[i]\n dic[num] += cnt\n max_acc += cnt\n cur_max = max(cur_max, max_acc)\n anss.append(isPalindrome(dic, numbers[0], numbers[l - 1]))\n for i in range(l, len(numbers)):\n l_num = numbers[i - l]\n l_cnt = counts[i - l]\n dic[l_num] -= l_cnt\n r_num = numbers[i]\n r_cnt = counts[i]\n dic[r_num] += r_cnt\n max_acc -= l_cnt\n max_acc += r_cnt\n cur_max = max(cur_max, max_acc)\n anss.append(isPalindrome(dic, numbers[i - l + 1], r_num))\n return (max(anss), cur_max)\n (numbers, counts) = compact(s)\n cur_max = 0\n for l in range(len(numbers), 0, -1):\n (new_max, max_acc) = rollingHash(numbers, counts, l)\n cur_max = max(cur_max, new_max)\n if cur_max >= max_acc:\n return cur_max\n return 1", "def longestawesome(s: str) -> int:\n\n def check(guess):\n num_odd = 0\n for (_, val) in list(guess.items()):\n num_odd += val % 2 == 1\n return num_odd <= 1\n N = len(s)\n if N > 70000 and s.startswith('0000000'):\n return 29995\n alphabet = set(s)\n for l in reversed(list(range(N + 1))):\n counts = {c: 0 for c in alphabet}\n for i in range(l):\n counts[s[i]] += 1\n if check(counts):\n return l\n for i in range(N - l):\n counts[s[i]] -= 1\n counts[s[i + l]] += 1\n if check(counts):\n return l", "def longestawesome(s: str) -> int:\n dp = [-2] * 1024\n run = 0\n ans = 0\n dp[0] = -1\n for (j, i) in enumerate(s):\n k = int(i)\n run ^= 1 << k\n if dp[run] == -2:\n dp[run] = j\n else:\n ans = max(ans, j - dp[run])\n for k in range(10):\n if dp[run ^ 1 << k] != -2:\n ans = max(ans, j - dp[run ^ 1 << k])\n return ans", "def longestawesome(s: str) -> int:\n n = len(s)\n c = 0\n counts = [c]\n for x in s:\n c ^= 1 << ord(x) - ord('0')\n counts.append(c)\n good = {1 << i for i in range(10)}\n good.add(0)\n m = {}\n for (i, c) in enumerate(counts):\n if c not in m:\n m[c] = i\n res = 0\n for i in range(1, n + 1):\n for d in (counts[i] ^ g for g in good):\n if d in m:\n res = max(res, i - m[d])\n return res", "def longestawesome(s: str) -> int:\n ps = {}\n mask = 0\n best = 0\n ps[mask] = -1\n for (i, c) in enumerate(s):\n d = int(c)\n mask ^= 1 << d\n if mask in ps:\n best = max(best, i - ps[mask])\n else:\n ps[mask] = i\n for k in range(10):\n if mask ^ 1 << k in ps:\n best = max(best, i - ps[mask ^ 1 << k])\n return best", "def longestawesome(s: str) -> int:\n mask_dict = {0: -1}\n mask = 0\n max_length = 0\n for (i, ch) in enumerate(s):\n mask ^= 1 << ord(ch) - ord('0')\n if mask in mask_dict:\n max_length = max(max_length, i - mask_dict[mask])\n for j in range(10):\n mask_odd = mask ^ 1 << j\n if mask_odd in mask_dict:\n max_length = max(max_length, i - mask_dict[mask_odd])\n if not mask in mask_dict:\n mask_dict[mask] = i\n return max_length", "def longestawesome(s: str) -> int:\n last_pos = Counter({0: -1})\n mask = 0\n result = 0\n for (i, c) in enumerate(s):\n n = int(c)\n mask ^= 1 << n\n if mask in last_pos:\n result = max(result, i - last_pos[mask])\n for j in range(10):\n new_mask = mask ^ 1 << j\n if new_mask in last_pos:\n result = max(result, i - last_pos[new_mask])\n if mask not in last_pos:\n last_pos[mask] = i\n return result", "def __init__():\n self.mn = {}\n self.mx = {}\n\ndef calcMax(tuple1, tuple2):\n ret = 0\n if tuple1 not in self.mn or tuple2 not in self.mn:\n return 0\n ret = max(abs(self.mn[tuple1] - self.mn[tuple2]), ret)\n ret = max(abs(self.mn[tuple1] - self.mx[tuple2]), ret)\n ret = max(abs(self.mx[tuple1] - self.mn[tuple2]), ret)\n ret = max(abs(self.mx[tuple1] - self.mx[tuple2]), ret)\n return ret\n\ndef longestawesome(s: str) -> int:\n l = len(s)\n curTup = [False, False, False, False, False, False, False, False, False, False]\n self.mn[tuple(curTup)] = 0\n self.mx[tuple(curTup)] = 0\n for i in range(l):\n curInt = int(s[i])\n curTup[curInt] = not curTup[curInt]\n if tuple(curTup) not in self.mn:\n self.mn[tuple(curTup)] = i + 1\n self.mx[tuple(curTup)] = i + 1\n mx = 0\n for tup in list(self.mx.keys()):\n mx = max(mx, self.calcMax(tup, tup))\n tupList = []\n for i in tup:\n tupList.append(i)\n for i in range(len(tupList)):\n tupList[i] = not tupList[i]\n mx = max(mx, self.calcMax(tup, tuple(tupList)))\n tupList[i] = not tupList[i]\n return mx", "def longestawesome(s: str) -> int:\n d = {}\n d[0] = -1\n ans = 0\n cnt = 0\n for (i, x) in enumerate(s):\n cnt ^= 1 << ord(x) - ord('0')\n if cnt in d:\n ans = max(ans, i - d[cnt])\n for j in range(10):\n if cnt ^ 1 << j in d:\n ans = max(ans, i - d[cnt ^ 1 << j])\n if not cnt in d:\n d[cnt] = i\n return ans", "def longestawesome(s: str) -> int:\n m = [100000.0 for i in range(1024)]\n m[0] = -1\n es = [1 << i for i in range(10)]\n current = 0\n res = 1\n for (i, c) in enumerate(s):\n n = ord(c) - ord('0')\n current = 1 << n ^ current\n if current == 0:\n res = i + 1\n else:\n for e in es:\n res = max(res, i - m[current ^ e])\n m[current] = min(m[current], i)\n return res", "def longestawesome(s: str) -> int:\n n = len(s)\n seen = {0: -1}\n status = res = 0\n for (i, c) in enumerate(s):\n status ^= 1 << ord(c) - ord('0')\n for a in range(10):\n if status ^ 1 << a in seen:\n res = max(res, i - seen[status ^ 1 << a])\n if status in seen:\n res = max(res, i - seen[status])\n else:\n seen[status] = i\n return res", "def longestawesome(s: str) -> int:\n (mask, res) = (0, 1)\n mask_pos = {0: -1}\n for (i, c) in enumerate(s):\n c = int(c)\n mask ^= 1 << c\n for j in range(11):\n check_mask = 1023 & (mask ^ 1 << j)\n if check_mask in mask_pos:\n res = max(res, i - mask_pos[check_mask])\n if mask in mask_pos:\n res = max(res, i - mask_pos[mask])\n else:\n mask_pos[mask] = i\n return res", "def longestawesome(s: str) -> int:\n if s == s[::-1]:\n return len(s)\n (pattern, re) = (0, 0)\n exit = {pattern: -1}\n for (i, num) in enumerate(s):\n pattern ^= 1 << int(num)\n if pattern == 0:\n re = i + 1\n continue\n for k in range(10):\n new_p = pattern ^ 1 << k\n re = max(re, i - exit.get(new_p, i))\n re = max(re, i - exit.get(pattern, i))\n exit.setdefault(pattern, i)\n return re", "def longestawesome(s: str) -> int:\n memo = {0: -1}\n max_len = 0\n mask = 0\n for i in range(len(s)):\n num = int(s[i])\n mask ^= 1 << num\n if mask in memo:\n max_len = max(max_len, i - memo[mask])\n for j in range(10):\n if mask ^ 1 << j in memo:\n max_len = max(max_len, i - memo[mask ^ 1 << j])\n if mask not in memo:\n memo[mask] = i\n return max_len"], "starter_code": "def longestawesome(s: str) -> int:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Bit Manipulation", "String", "Hash Table"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://leetcode.com/problems/find-longest-awesome-substring/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "longestawesome", "task_id": "TACO_lite/457", "example": [[["3242415"], ["12345678"], ["213123"], ["00"]], ["5", "1", "6", "2"]]} +{"requirement": "Take debugging to a whole new level:\n\nGiven a string, remove every *single* bug.\n\nThis means you must remove all instances of the word 'bug' from within a given string, *unless* the word is plural ('bugs').\n\nFor example, given 'obugobugobuoobugsoo', you should return 'ooobuoobugsoo'.\n\nAnother example: given 'obbugugo', you should return 'obugo'.\n\nNote that all characters will be lowercase.\n\nHappy squishing!", "solutions": ["import re\n\ndef debug(s):\n return re.sub('bug(?!s)', '', s)", "def debug(s):\n s = s.replace('bugs', '^')\n s = s.replace('bug', '')\n s = s.replace('^', 'bugs')\n return s", "def debug(s):\n return __import__('re').sub('bug(?!s)', '', s)", "def debug(s):\n return 'bugs'.join((w.replace('bug', '') for w in s.split('bugs')))"], "starter_code": "def debug(s):\n", "input_output": {"fn_name": "debug", "inputs": [["obugobugobuoobugsoo"], ["obbugugo"], ["bugs bunny"], ["bugs buggy"], ["oaiwjefbugoijoijapsbugsdoibugbugjfoijasdfbugsbug"], ["bugbugbugiahweoifuhiaasnoidfhnbugbugs"], ["bugsbugswaoeifhiauwehfoiwubugshefjnviouah"], ["bugbugbugbug"], ["bugsbugsbugsbugs"], ["buggybugs"], ["oaisjdfowjefpoibugsjsofijeo oi bugs o bug f bug poaj sfd s"]], "outputs": [["ooobuoobugsoo"], ["obugo"], ["bugs bunny"], ["bugs gy"], ["oaiwjefoijoijapsbugsdoijfoijasdfbugs"], ["iahweoifuhiaasnoidfhnbugs"], ["bugsbugswaoeifhiauwehfoiwubugshefjnviouah"], [""], ["bugsbugsbugsbugs"], ["gybugs"], ["oaisjdfowjefpoibugsjsofijeo oi bugs o f poaj sfd s"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5a21f943c5e284d4340000cb", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "debug", "task_id": "TACO_lite/473", "example": [[["obugobugobuoobugsoo"], ["obbugugo"]], ["ooobuoobugsoo", "obugo"]]} +{"requirement": "You are given an array of strings words and a string chars.\nA string is good if it can be formed by characters from chars (each character can only be used once).\nReturn the sum of lengths of all good strings in words.\n \nExample 1:\nInput: words = [\"cat\",\"bt\",\"hat\",\"tree\"], chars = \"atach\"\nOutput: 6\nExplanation: \nThe strings that can be formed are \"cat\" and \"hat\" so the answer is 3 + 3 = 6.\n\nExample 2:\nInput: words = [\"hello\",\"world\",\"leetcode\"], chars = \"welldonehoneyr\"\nOutput: 10\nExplanation: \nThe strings that can be formed are \"hello\" and \"world\" so the answer is 5 + 5 = 10.\n\n \nNote:\n\n1 <= words.length <= 1000\n1 <= words[i].length, chars.length <= 100\nAll strings contain lowercase English letters only.", "solutions": ["def countcharacters(words: List[str], chars: str) -> int:\n d = {}\n for i in chars:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n l = 0\n for i in words:\n flag = True\n for j in i:\n if j in d:\n if i.count(j) > d[j]:\n flag = False\n break\n else:\n flag = False\n break\n if flag:\n l += len(i)\n return l", "def countcharacters(words: List[str], chars: str) -> int:\n charBins = {char: chars.count(char) for char in chars}\n total = 0\n for word in words:\n if len(word) > len(chars):\n continue\n if not set(word).issubset(chars):\n continue\n letterBins = {letter: word.count(letter) for letter in word}\n goodWord = True\n for letter in letterBins:\n if letterBins[letter] > charBins[letter]:\n goodWord = False\n if goodWord:\n total += len(word)\n return total", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n c = Counter(chars)\n ret = 0\n for word in words:\n if Counter(word) - c == Counter():\n ret += len(word)\n return ret", "def countcharacters(words: List[str], chars: str) -> int:\n return sum((len(word) for word in words if collections.Counter(word) & collections.Counter(chars) == collections.Counter(word)))", "def countcharacters(words: List[str], chars: str) -> int:\n count = 0\n chars_map = collections.Counter(chars)\n for word in words:\n if collections.Counter(word) == collections.Counter(word) & chars_map:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n sum = 0\n for i in words:\n check = True\n for s in i:\n if i.count(s) > chars.count(s):\n check = False\n if check == True:\n sum = sum + len(i)\n return sum", "def countcharacters(words: List[str], chars: str) -> int:\n op = 0\n for ele in words:\n count = 0\n for i in ele:\n if chars.count(i) >= ele.count(i):\n count += 1\n if count == len(ele):\n op += len(ele)\n return op", "def countcharacters(words: List[str], chars: str) -> int:\n charsums = 0\n chars = sorted(chars)\n for word in words:\n wordsize = len(word)\n word = sorted(word)\n charcounter = 0\n while len(word) > 0 and charcounter < len(chars):\n if word[0] == chars[charcounter]:\n word.remove(word[0])\n charcounter += 1\n else:\n charcounter += 1\n if len(word) == 0:\n charsums += wordsize\n return charsums", "def countcharacters(words: List[str], chars: str) -> int:\n output = 0\n add = True\n for word in words:\n for c in word:\n if word.count(c) > chars.count(c):\n add = False\n if add:\n output += len(word)\n else:\n add = True\n return output", "def countcharacters(words: List[str], chars: str) -> int:\n count = 0\n n = len(chars)\n for word in words:\n ok_word = True\n copy = chars\n visit = []\n for i in range(n):\n visit.append(0)\n for letter in word:\n ok_letter = False\n for i in range(n):\n if visit[i] == 0 and letter == copy[i]:\n ok_letter = True\n visit[i] = 1\n break\n if not ok_letter:\n ok_word = False\n break\n if ok_word:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n charBins = {char: chars.count(char) for char in chars}\n goodWords = []\n for word in words:\n if len(word) > len(chars):\n continue\n if not set(word).issubset(chars):\n continue\n letterBins = {letter: word.count(letter) for letter in word}\n goodWord = True\n for letter in letterBins:\n if letterBins[letter] > charBins[letter]:\n goodWord = False\n if goodWord:\n goodWords.append(word)\n return sum((len(word) for word in goodWords))", "def countcharacters(words: List[str], chars: str) -> int:\n from collections import Counter\n res = 0\n for j in words:\n tmp = Counter(j) & Counter(chars)\n if tmp == Counter(j):\n res += len(j)\n return res", "def countcharacters(words: List[str], chars: str) -> int:\n goodCount = 0\n for word in words:\n wordLen = len(word)\n letterCount = 0\n chars_list = list(chars)\n for letter in word:\n if letter in chars_list:\n letterCount += 1\n chars_list.remove(letter)\n if letterCount == wordLen:\n goodCount += letterCount\n return goodCount", "def countcharacters(words: List[str], chars: str) -> int:\n suma = 0\n for word in words:\n cur_word = list(word)\n cur_len = len(word)\n for c in chars:\n if c in cur_word:\n cur_word.remove(c)\n if len(cur_word) == 0:\n suma += cur_len\n return suma", "def countcharacters(words: List[str], chars: str) -> int:\n ans = 0\n from collections import Counter\n cd = Counter(chars)\n for w in words:\n wd = Counter(w)\n if len(wd & cd) and len(list((wd & cd).elements())) == len(w):\n ans += len(w)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n start = 0\n for i in words:\n count = 0\n t = list(chars)\n for j in i:\n if j in t:\n count += 1\n t.remove(j)\n if count == len(i):\n start += count\n return start", "def countcharacters(words: List[str], chars: str) -> int:\n total = 0\n for word in words:\n mod_chars = list(chars)\n found = 0\n for c in word:\n if c in mod_chars:\n p = mod_chars.index(c)\n del mod_chars[p]\n found += 1\n if found == len(word):\n total += found\n return total", "def countcharacters(words, chars: str) -> int:\n myd = {}\n for i in chars:\n if hash(i) in list(myd.keys()):\n myd[hash(i)] += 1\n else:\n myd[hash(i)] = 1\n wdata = []\n for i in range(0, len(words)):\n x = dict()\n for letter in words[i]:\n if hash(letter) in list(x.keys()):\n x[hash(letter)] += 1\n else:\n x[hash(letter)] = 1\n wdata.append(x)\n count = 0\n for data in wdata:\n allin = True\n lcount = 0\n for letter in list(data.keys()):\n if letter in list(myd.keys()):\n if data[letter] > myd[letter]:\n allin = False\n else:\n lcount += data[letter]\n else:\n allin = False\n if allin == True:\n count += lcount\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n ans = 0\n for word in words:\n charscopy = [i for i in chars]\n length = 0\n for char in word:\n if char in charscopy:\n length += 1\n charscopy.remove(char)\n if length == len(word):\n ans += length\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n char_counter = Counter(chars)\n return sum([len(word) for word in words if len(char_counter - Counter(word)) > 1 and len(Counter(word) - char_counter) == 0])", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n d = Counter(chars)\n ans = 0\n for word in words:\n cur = Counter(word)\n if cur == cur & d:\n ans += len(word)\n return ans", "import copy\n\ndef countcharacters(w: List[str], c: str) -> int:\n d = {}\n for i in c:\n d[i] = d.get(i, 0) + 1\n ans = 0\n for i in range(len(w)):\n x = copy.deepcopy(d)\n f = True\n for j in w[i]:\n if j in x and x[j] > 0:\n x[j] -= 1\n else:\n f = False\n break\n if f:\n ans += len(w[i])\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n r = 0\n a = list(chars)\n for i in words:\n b = a.copy()\n s = False\n for j in i:\n if j not in b:\n s = True\n else:\n b.remove(j)\n if s != True:\n r += len(i)\n return r", "def countcharacters(words: List[str], chars: str) -> int:\n char_set = collections.Counter(chars)\n N = len(chars)\n result = 0\n for i in words:\n if len(i) <= N and self.check(char_set, i):\n result += len(i)\n return result\n\ndef check(char_ctr, S):\n S_ctr = collections.Counter(S)\n for i in S_ctr:\n if i not in char_ctr or S_ctr[i] > char_ctr[i]:\n return False\n return True", "import copy\n\ndef countcharacters(words: List[str], chars: str) -> int:\n charmap = dict()\n for c in chars:\n if c in charmap:\n charmap[c] += 1\n else:\n charmap[c] = 1\n size = 0\n for word in words:\n temp = copy.deepcopy(charmap)\n flag = True\n for c in word:\n if c in temp and temp[c] > 0:\n temp[c] -= 1\n else:\n flag = False\n break\n if flag:\n size += len(word)\n return size", "import copy\n\ndef countcharacters(words: List[str], chars: str) -> int:\n tracker = dict()\n result = 0\n for s in chars:\n tracker.setdefault(s, 0)\n tracker[s] += 1\n for word in words:\n _temp = copy.deepcopy(tracker)\n for ch in word:\n if ch not in _temp:\n break\n if _temp[ch] <= 0:\n break\n _temp[ch] -= 1\n else:\n result += len(word)\n return result", "import copy\n\ndef countcharacters(words: List[str], chars: str) -> int:\n s = dict()\n for c in chars:\n if c not in s:\n s[c] = 0\n s[c] += 1\n t = 0\n for word in words:\n s_copy = copy.deepcopy(s)\n valid = True\n for letter in word:\n if letter not in s_copy:\n valid = False\n break\n else:\n s_copy[letter] -= 1\n if s_copy[letter] == 0:\n del s_copy[letter]\n if valid:\n t += len(word)\n return t", "def countcharacters(words: List[str], chars: str) -> int:\n import copy\n total = 0\n y = {}\n for char in chars:\n if char in y:\n y[char] += 1\n else:\n y[char] = 1\n for word in words:\n x = copy.deepcopy(y)\n temp = 0\n for char in word:\n if char in x and x[char] > 0:\n x[char] -= 1\n temp += 1\n else:\n temp = 0\n break\n total += temp\n return total", "def countcharacters(words: List[str], chars: str) -> int:\n out = 0\n for word in words:\n good = True\n for char in word:\n if word.count(char) > chars.count(char):\n good = False\n if good:\n out += len(word)\n return out", "import collections\n\ndef countcharacters(words: List[str], chars: str) -> int:\n count = 0\n for w in words:\n letters = list(set(w))\n isin = True\n for l in letters:\n if l not in chars or w.count(l) > chars.count(l):\n isin = False\n break\n if isin:\n count += len(w)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n a = 0\n for word in words:\n res = True\n for i in word:\n if word.count(i) > chars.count(i):\n res = False\n break\n if res:\n a += len(word)\n return a", "def countcharacters(words: List[str], chars: str) -> int:\n res = 0\n dtar = Counter(chars)\n for i in range(len(words)):\n for j in words[i]:\n if j not in chars:\n break\n if words[i].count(j) > 1:\n if words[i].count(j) > dtar[j]:\n break\n else:\n res += len(words[i])\n return res", "def countcharacters(words: List[str], chars: str) -> int:\n d = Counter(chars)\n ans = 0\n for w in words:\n temp = d.copy()\n b = True\n for i in w:\n try:\n if temp[i] != 0:\n temp[i] -= 1\n else:\n b = False\n break\n except:\n b = False\n break\n if b:\n ans += len(w)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n count = 0\n freq = {}\n for n in range(len(chars)):\n if chars[n] not in freq.keys():\n freq[chars[n]] = 1\n else:\n freq[chars[n]] += 1\n for word in words:\n word_fq = {}\n is_match = True\n for m in range(len(word)):\n if word[m] not in freq.keys():\n is_match = False\n break\n if word[m] not in word_fq.keys():\n word_fq[word[m]] = 1\n else:\n word_fq[word[m]] += 1\n if is_match:\n is_fit = True\n for key in word_fq.keys():\n if key not in freq.keys():\n is_fit = False\n break\n if word_fq[key] > freq[key]:\n is_fit = False\n break\n if is_fit:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n c = collections.Counter(chars)\n res = 0\n\n def valid(word):\n s = collections.Counter(word)\n for ch in s:\n if ch not in c or s[ch] > c[ch]:\n return False\n return True\n for word in words:\n if valid(word):\n res += len(word)\n return res", "def countcharacters(words: List[str], chars: str) -> int:\n ans = 0\n mp = Counter(chars)\n for word in words:\n ok = True\n mp_word = Counter(word)\n for (ch, f) in mp_word.items():\n if ch not in mp or mp_word[ch] > mp[ch]:\n ok = False\n break\n if ok:\n ans += len(word)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n from collections import Counter\n ans = 0\n chars_set = set(chars)\n count0 = Counter(chars)\n for word in words:\n count = Counter(word)\n if all((s in chars_set and count[s] <= count0[s] for s in word)):\n ans += len(word)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n d_chars = Counter(chars)\n ans = 0\n for w in words:\n d_w = Counter(w)\n for (k, v) in d_w.items():\n if d_chars[k] < v:\n break\n else:\n ans += len(w)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n (sum, ct) = (0, collections.Counter)\n chars_counter = ct(chars)\n for word in words:\n word_counter = ct(word)\n if all((word_counter[c] <= chars_counter[c] for c in word_counter)):\n sum += len(word)\n return sum", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n c_dict = dict(Counter(chars))\n count = 0\n for word in words:\n word_d = dict(Counter(word))\n match = True\n for (k, v) in list(word_d.items()):\n if k not in c_dict or v > c_dict[k]:\n match = False\n break\n if match:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n char_sum = 0\n\n def isValid(word, chars):\n for letter in word:\n if chars[letter] > 0:\n chars[letter] -= 1\n else:\n return False\n return True\n for word in words:\n counter = Counter(chars)\n if isValid(word, counter):\n char_sum += len(word)\n return char_sum", "def countcharacters(words: List[str], chars: str) -> int:\n tot = 0\n for w in words:\n d = {}\n for c in chars:\n if c in d:\n d[c] += 1\n else:\n d[c] = 1\n temp = 0\n for l in w:\n if l in d and d[l] > 0:\n d[l] -= 1\n temp += 1\n else:\n temp = 0\n break\n tot += temp\n return tot", "def countcharacters(words: List[str], chars: str) -> int:\n ans = 0\n for w in words:\n tc = chars\n flag = True\n for l in w:\n if l in tc:\n tc = tc.replace(l, '', 1)\n else:\n flag = False\n if flag:\n ans += len(w)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n d = {}\n c = 0\n for i in chars:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for i in words:\n dd = {}\n for j in i:\n if j in dd:\n dd[j] += 1\n else:\n dd[j] = 1\n c1 = 0\n for x in dd.keys():\n if x in d:\n if d[x] >= dd[x]:\n c1 += dd[x]\n else:\n c1 = 0\n break\n else:\n c1 = 0\n break\n c += c1\n return c", "def countcharacters(words: List[str], chars: str) -> int:\n charsDict = {}\n for char in chars:\n if char not in charsDict:\n charsDict[char] = 0\n charsDict[char] += 1\n ans = 0\n for word in words:\n tempDict = charsDict.copy()\n isGood = True\n for char in word:\n if char not in tempDict:\n isGood = False\n continue\n elif tempDict[char] == 0:\n isGood = False\n continue\n else:\n tempDict[char] -= 1\n if isGood:\n ans += len(word)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n cCounter = collections.Counter(chars)\n sum = 0\n for word in words:\n wCounter = collections.Counter(word)\n match = True\n for (k, v) in wCounter.items():\n if cCounter[k] < v:\n match = False\n if match:\n sum += len(word)\n return sum", "def countcharacters(words: List[str], chars: str) -> int:\n c1 = [0] * 256\n for c in chars:\n c1[ord(c)] += 1\n res = 0\n for word in words:\n if len(chars) < len(word):\n continue\n c2 = [0] * 256\n for c in word:\n c2[ord(c)] += 1\n goodStr = True\n for i in range(256):\n if c1[i] < c2[i]:\n goodStr = False\n break\n if goodStr:\n res += len(word)\n return res", "def countcharacters(words: List[str], chars: str) -> int:\n\n def get_freq(input):\n freq = {}\n for c in input:\n if c not in freq:\n freq[c] = 0\n freq[c] += 1\n return freq\n\n def can_contain(freq_source, freq_word):\n for (key, item) in freq_word.items():\n if key not in freq_source or freq_source[key] < item:\n return False\n return True\n total_length = 0\n freq_source = get_freq(chars)\n for word in words:\n freq_word = get_freq(word)\n if can_contain(freq_source, freq_word):\n total_length += len(word)\n return total_length", "def countcharacters(words: List[str], chars: str) -> int:\n charsDict = {}\n for char in chars:\n if char not in charsDict:\n charsDict[char] = 0\n charsDict[char] += 1\n ans = 0\n for word in words:\n wordDict = {}\n for char in word:\n if char not in wordDict:\n wordDict[char] = 0\n wordDict[char] += 1\n isGood = True\n for (key, val) in list(wordDict.items()):\n if key not in charsDict:\n isGood = False\n break\n elif val > charsDict[key]:\n isGood = False\n break\n if isGood:\n ans += len(word)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n res = 0\n d = dict()\n for char in chars:\n d[char] = d.get(char, 0) + 1\n for word in words:\n c = dict()\n for char in word:\n c[char] = c.get(char, 0) + 1\n bad = False\n while c and (not bad):\n char = c.popitem()\n if char[0] in d and d[char[0]] >= char[1]:\n continue\n else:\n bad = True\n if not bad:\n res += len(word)\n return res", "def countcharacters(words: List[str], chars: str) -> int:\n out = 0\n chars = list(chars)\n for i in words:\n f = 0\n temp = chars[:]\n for j in i:\n if j in temp:\n temp.remove(j)\n else:\n f = 1\n break\n if f == 0:\n out += len(i)\n return out", "def countcharacters(words: List[str], chars: str) -> int:\n register = {}\n for char in chars:\n register[char] = register.get(char, 0) + 1\n result = 0\n for word in words:\n temp = {}\n for char in word:\n temp[char] = temp.get(char, 0) + 1\n for (char, num) in list(temp.items()):\n if temp[char] > register.get(char, 0):\n break\n else:\n result += len(word)\n return result", "def countcharacters(words: List[str], chars: str) -> int:\n charChars = Counter(chars)\n counter = 0\n for word in words:\n countC = Counter(word)\n count = 0\n for letter in countC.items():\n if letter[0] in charChars and charChars[letter[0]] >= letter[1]:\n count += 1\n if count == len(countC):\n counter += len(word)\n return counter", "def countcharacters(words: List[str], chars: str) -> int:\n\n def strToList(word):\n return [char for char in word]\n\n def canForm(word, bank):\n tmp = word\n while tmp != []:\n x = tmp[0]\n tmp.remove(tmp[0])\n if x in bank:\n bank.remove(x)\n else:\n return False\n return True\n totalLen = 0\n for word in words:\n bank = strToList(chars)\n wordAsList = strToList(word)\n if canForm(wordAsList, bank):\n totalLen += len(word)\n return totalLen", "def countcharacters(words: List[str], chars: str) -> int:\n setChars = set(chars)\n counts = [0] * len(setChars)\n map = {}\n res = 0\n for (i, val) in enumerate(setChars):\n map[val] = i\n for (i, val) in enumerate(chars):\n counts[map.get(val)] += 1\n for word in words:\n tempCounts = counts[:]\n flag = 1\n for char in word:\n index = map.get(char, -1)\n if index == -1:\n flag = 0\n continue\n tempCounts[index] -= 1\n if tempCounts[index] < 0:\n flag = 0\n continue\n if flag:\n res += len(word)\n return res", "def countcharacters(words: List[str], chars: str) -> int:\n d = {}\n for i in range(len(chars)):\n if chars[i] not in d:\n d[chars[i]] = 1\n else:\n d[chars[i]] += 1\n c = 0\n for i in range(len(words)):\n di = {}\n for j in range(len(words[i])):\n if words[i][j] not in di:\n di[words[i][j]] = 1\n else:\n di[words[i][j]] += 1\n l = list(di.keys())\n temp = 0\n for j in range(len(l)):\n if l[j] not in d:\n temp = 1\n break\n elif di[l[j]] > d[l[j]]:\n temp = 1\n break\n else:\n temp = 0\n if temp == 0:\n c += len(words[i])\n return c", "def countcharacters(words, chars):\n sum = 0\n count = {}\n for c in chars:\n if c in count:\n count[c] += 1\n else:\n count[c] = 1\n for word in words:\n seen = {}\n validWord = True\n for c in word:\n if c in seen:\n seen[c] += 1\n else:\n seen[c] = 1\n if c not in count or seen[c] > count[c]:\n validWord = False\n if validWord:\n sum += len(word)\n return sum", "from collections import Counter\n\ndef bruteforce_with_counter(words, chars):\n counter = Counter(chars)\n return sum((len(w) for w in words if not Counter(w) - counter))\n\ndef countcharacters(words: List[str], chars: str) -> int:\n return bruteforce_with_counter(words, chars)", "from collections import Counter as di\n\ndef countcharacters(a: List[str], c: str) -> int:\n d = di(c)\n ans = 0\n for i in a:\n d1 = di(i)\n if len(d1 - d) == 0:\n ans += sum(d1.values())\n return ans", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n letters = Counter(chars)\n out = 0\n for word in words:\n length = len(word)\n if not Counter(word) - letters:\n out += length\n return out", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n\n def issubset(wc, cc):\n for x in wc.keys():\n cc[x] = cc.get(x, 0) - wc[x]\n for x in cc.keys():\n if cc[x] < 0:\n return False\n return True\n res = 0\n cc = Counter(chars)\n for word in words:\n wc = Counter(word)\n if issubset(wc, cc.copy()):\n res += len(word)\n return res", "def countcharacters(words: List[str], chars: str) -> int:\n char_count = collections.Counter(chars)\n total = 0\n for word in words:\n if not collections.Counter(word) - char_count:\n total += len(word)\n return total", "def countcharacters(words: List[str], chars: str) -> int:\n chars = Counter(chars)\n return sum((len(w) for w in words if not Counter(w) - chars))", "def countcharacters(words: List[str], chars: str) -> int:\n count = Counter(chars)\n out = 0\n for word in words:\n curr = Counter(word)\n if not curr - count:\n out += len(word)\n return out", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n c_c = Counter(chars)\n good_w = []\n for w in words:\n w_c = Counter(w)\n sampled_w = ''.join([c for c in w if c_c[c] >= w_c[c]])\n if w == sampled_w:\n good_w.append(w)\n return sum((len(w) for w in good_w))", "def countcharacters(words: List[str], chars: str) -> int:\n char_map = {c: chars.count(c) for c in set(chars)}\n count = 0\n for w in words:\n good = True\n for c in w:\n if c not in char_map.keys() or w.count(c) > char_map[c]:\n good = False\n if good:\n count += len(w)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n letters = {}\n for char in chars:\n letters[char] = letters.get(char, 0) + 1\n count = 0\n for word in words:\n tmp = letters.copy()\n flag = 1\n for char in word:\n if char in tmp and tmp[char] >= 1:\n tmp[char] -= 1\n else:\n flag = 0\n break\n if flag:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n ans = 0\n for word in words:\n c = collections.Counter(chars)\n add = True\n for letter in word:\n if c[letter] > 0:\n c[letter] -= 1\n else:\n add = False\n if add == True:\n ans += len(word)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n ans = 0\n cmap = {ch: chars.count(ch) for ch in chars}\n for word in words:\n wmap = {ch: word.count(ch) for ch in word}\n count_me_in = True\n for (k, v) in wmap.items():\n try:\n v1 = cmap[k]\n if v1 < v:\n raise Exception('Frequency not enough!')\n except:\n count_me_in = False\n break\n if count_me_in:\n ans += len(word)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n char_count = collections.Counter(chars)\n good_str_len = 0\n for word in words:\n temp = char_count.copy()\n temp_str_len = 0\n for ch in word:\n if ch in temp and temp[ch] > 0:\n temp_str_len += 1\n temp[ch] -= 1\n if temp_str_len == len(word):\n good_str_len += len(word)\n return good_str_len", "def countcharacters(words: List[str], chars: str) -> int:\n if len(chars) == 0 or len(words) == 0:\n return 0\n letterCounts = {}\n for c in chars:\n if str(c) in letterCounts:\n letterCounts[str(c)] += 1\n else:\n letterCounts[str(c)] = 1\n totalLength = 0\n for word in words:\n currentLetterCounts = {}\n for letter in word:\n if str(letter) in currentLetterCounts:\n currentLetterCounts[str(letter)] += 1\n else:\n currentLetterCounts[str(letter)] = 1\n valid = True\n for (key, value) in currentLetterCounts.items():\n if key not in letterCounts:\n valid = False\n break\n if letterCounts[key] < value:\n valid = False\n break\n if valid:\n totalLength += len(word)\n return totalLength", "def countcharacters(words: List[str], chars: str) -> int:\n flag = [0 for i in range(len(words))]\n total = 0\n for word in words:\n dic = {}\n for char in word:\n if char in dic:\n dic[char] += 1\n else:\n dic[char] = 1\n count = 0\n for i in range(len(chars)):\n if chars[i] in dic and dic[chars[i]] > 0:\n dic[chars[i]] -= 1\n count += 1\n good = True\n for char in dic:\n if dic[char] > 0:\n good = False\n break\n if good:\n total += count\n return total", "def countcharacters(words: List[str], chars: str) -> int:\n myd = {}\n count = 0\n for i in chars:\n if i in myd.keys():\n myd[i] += 1\n else:\n myd[i] = 1\n for word in words:\n allin = True\n for letter in word:\n if letter in myd.keys():\n if word.count(letter) > myd[letter]:\n allin = False\n else:\n allin = False\n if allin == True:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n good_words_len_sum = 0\n counter = {}\n for char in chars:\n if not char in counter:\n counter[char] = 1\n else:\n counter[char] += 1\n for word in words:\n my_counter = counter.copy()\n for char in word:\n if my_counter.get(char, 0) > 0:\n my_counter[char] -= 1\n else:\n break\n else:\n good_words_len_sum += len(word)\n return good_words_len_sum", "def countcharacters(words: List[str], chars: str) -> int:\n length = 0\n m = Counter(chars)\n for word in words:\n passed = True\n for char in word:\n if m[char] < word.count(char):\n passed = False\n if passed:\n length += len(word)\n return length", "def countcharacters(words: List[str], chars: str) -> int:\n from collections import Counter as cnt\n return sum([not cnt(word) - cnt(chars) and len(word) for word in words])", "def countcharacters(words: List[str], chars: str) -> int:\n count = 0\n dic = collections.Counter(chars)\n for word in words:\n passed = True\n for ch in word:\n if dic[ch] < word.count(ch):\n passed = False\n if passed:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n counter = 0\n for i in words:\n a = i\n for j in chars:\n if j in a:\n a = a[:a.index(j)] + a[a.index(j) + 1:]\n if len(a) == 0:\n counter += len(i)\n return counter", "def countcharacters(words: List[str], chars: str) -> int:\n freq = defaultdict(int)\n for l in chars:\n freq[l] += 1\n count = 0\n for word in words:\n testFreq = freq.copy()\n match = True\n for letter in word:\n if testFreq[letter] <= 0:\n match = False\n break\n testFreq[letter] -= 1\n if match:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n tot = 0\n totchars = {}\n for char in chars:\n if char in totchars:\n totchars[char] += 1\n else:\n totchars[char] = 1\n for word in words:\n word = sorted(word)\n works = True\n i = 0\n while i < len(word):\n count = 0\n while word[i + count] == word[i]:\n count += 1\n if i + count == len(word):\n break\n if word[i] in totchars:\n if count > totchars[word[i]]:\n works = False\n else:\n works = False\n i += count\n if works:\n tot += len(word)\n return tot", "def countcharacters(words: List[str], chars: str) -> int:\n sum = 0\n p = 0\n for th in words:\n for i in range(len(th)):\n if th[i] in chars:\n if th.count(th[i]) <= chars.count(th[i]):\n p = p + 1\n if p == len(th):\n sum = sum + p\n p = 0\n return sum", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n ans = 0\n for i in range(len(words)):\n if Counter(words[i]) & Counter(chars) == Counter(words[i]):\n ans += len(words[i])\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n from collections import Counter\n sum_ = 0\n for word in words:\n s = Counter(chars)\n flag = 0\n for letter in word:\n if letter in list(s.keys()) and s[letter] != 0:\n s[letter] -= 1\n else:\n flag = 1\n if flag == 0:\n sum_ += len(word)\n return sum_", "def countcharacters(words: List[str], chars: str) -> int:\n out = 0\n for word in words:\n cnt = 0\n for letter in word:\n if letter in chars and word.count(letter) <= chars.count(letter):\n cnt += 1\n if cnt == len(word):\n out += len(word)\n return out", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n letters = Counter(chars)\n c = 0\n for w in words:\n if Counter(chars) & Counter(w) == Counter(w):\n c += len(w)\n return c", "import collections\n\ndef countcharacters(words: List[str], chars: str) -> int:\n n = 0\n for word in words:\n count = 0\n for letter in word:\n if letter in chars and word.count(letter) <= chars.count(letter):\n count += 1\n if count == len(word):\n n += len(word)\n return n", "def countcharacters(words: List[str], chars: str) -> int:\n res = []\n for word in words:\n count = 0\n for char in word:\n if char in chars and word.count(char) <= chars.count(char):\n count += 1\n if count == len(word):\n res.append(count)\n return sum(res)", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n r = Counter(chars)\n return sum([len(word) if Counter(word) - r == Counter() else 0 for word in words])"], "starter_code": "def countcharacters(words: List[str], chars: str) -> int:\n", "input_output": {"fn_name": "countCharacters", "inputs": [[["\"cat\"", "\"bt\"", "\"hat\"", "\"tree\""], "\"atach\""]], "outputs": [10]}, "difficulty": "EASY", "raw_tags": ["Array", "String", "Hash Table"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "countcharacters", "task_id": "TACO_lite/466", "example": [[[["cat", "bt", "hat", "tree"], "atach"], [["hello", "world", "leetcode"], "welldonehoneyr"]], ["6", "10"]]} +{"requirement": "What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example:\n\n```\n'abba' & 'baab' == true\n\n'abba' & 'bbaa' == true\n\n'abba' & 'abbba' == false\n\n'abba' & 'abca' == false\n```\n\nWrite a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:\n\nanagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']\n\nanagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']\n\nanagrams('laser', ['lazing', 'lazy', 'lacer']) => []", "solutions": ["def anagrams(word, words):\n return [item for item in words if sorted(item) == sorted(word)]", "from collections import Counter\n\ndef anagrams(word, words):\n counts = Counter(word)\n return [w for w in words if Counter(w) == counts]", "def anagrams(word, words):\n match = sorted(word)\n return [w for w in words if match == sorted(w)]", "from collections import Counter\n\ndef anagrams(word, words):\n (n, c) = (len(word), Counter(word))\n return [w for w in words if len(w) == n and Counter(w) == c]", "def anagrams(word, words):\n letter = {x: word.count(x) for x in word}\n result = []\n for i in words:\n letters = {x: i.count(x) for x in i}\n if letters == letter:\n result.append(i)\n return result", "def anagrams(word, words):\n return [el for el in words if sorted(word) == sorted(el)]", "from collections import Counter\n\ndef anagrams(word, words):\n main = Counter(word)\n return [wor for wor in words if Counter(wor) == main]", "def anagrams(word, words):\n return [x for x in words if sorted(x) == sorted(word)]", "def anagrams(word, words):\n return [w for w in words if list(sorted(w)) == list(sorted(word))]", "def anagrams(word, words):\n\n def lettercount(inputword):\n wordarr = list(inputword)\n worddict = {}\n for letter in wordarr:\n if letter not in worddict:\n worddict[letter] = wordarr.count(letter)\n return worddict\n return [astring for astring in words if lettercount(astring) == lettercount(word)]", "def anagrams(word, words):\n lst = []\n for elem in words:\n if sorted(word) == sorted(elem):\n lst.append(elem)\n return lst", "def anagrams(word, words):\n word = sorted(word)\n return list(filter(lambda ele: sorted(ele) == word, words))", "def anagrams(word, words):\n return [trial for trial in words if sorted(trial) == sorted(word)]", "def anagrams(word: str, words: list) -> list:\n return list(filter(lambda x: sorted(x) == sorted(word), words))", "anagrams = lambda _, __: list([s for s in __ if sorted(s) == sorted(_)])", "anagrams = lambda word, words: list((w for w in words if sorted(list(w)) == sorted(list(word))))", "def anagrams(word, words):\n ans = []\n or1 = 0\n or2 = 0\n for i in word:\n or1 += ord(i)\n for i in words:\n or2 = 0\n for x in i:\n or2 += ord(x)\n if or1 == or2:\n ans += [i]\n return ans", "def anagrams(word, words):\n w_buff = []\n w_out = []\n for w_t in words:\n if len(w_t) == len(word):\n w_buff.append(w_t)\n w_w = list(word)\n w_w.sort()\n for w_t in w_buff:\n w_buff_l = list(w_t)\n w_buff_l.sort()\n if w_buff_l == w_w:\n w_out.append(w_t)\n return w_out", "def anagrams(word, words):\n list = []\n word = sorted(word)\n for i in range(len(words)):\n if word == sorted(words[i]):\n list.append(words[i])\n else:\n pass\n return list", "from collections import Counter\n\ndef anagrams(word, words):\n return [w for w in words if sorted(sorted(Counter(word).items())) == sorted(sorted(Counter(w).items()))]", "def anagrams(word, words):\n l = [letter for letter in word]\n anagram_list = []\n for item in words:\n l_item = [letter for letter in item]\n if sorted(l) == sorted(l_item):\n temp_list = [i for i in l + l_item if i not in l_item]\n if len(temp_list) == 0:\n anagram_list.append(item)\n else:\n continue\n return anagram_list", "def anagrams(word, words):\n return [anagram for anagram in words if sum([ord(c) for c in anagram]) == sum([ord(c) for c in word])]", "def anagrams(word, words):\n wordnum = sum((ord(ch) for ch in word))\n res = []\n if not words:\n return []\n for item in words:\n if sum((ord(ch) for ch in item)) == wordnum:\n res.append(item)\n return res"], "starter_code": "def anagrams(word, words):\n", "input_output": {"fn_name": "anagrams", "inputs": [["abba", ["aabb", "abcd", "bbaa", "dada"]], ["racer", ["crazer", "carer", "racar", "caers", "racer"]], ["a", ["a", "b", "c", "d"]], ["ab", ["cc", "ac", "bc", "cd", "ab", "ba", "racar", "caers", "racer"]], ["abba", ["a", "b", "c", "d", "aabb", "bbaa", "abab", "baba", "baab", "abcd", "abbba", "baaab", "abbab", "abbaa", "babaa"]], ["big", ["gig", "dib", "bid", "biig"]]], "outputs": [[["aabb", "bbaa"]], [["carer", "racer"]], [["a"]], [["ab", "ba"]], [["aabb", "bbaa", "abab", "baba", "baab"]], [[]]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/523a86aa4230ebb5420001e1", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "anagrams", "task_id": "TACO_lite/456", "example": [[["abba", ["aabb", "abcd", "bbaa", "dada"]], ["racer", ["crazer", "carer", "racar", "caers", "racer"]], ["laser", ["lazing", "lazy", "lacer"]]], ["['aabb', 'bbaa']", "['carer', 'racer']", "[]"]]} +{"requirement": "Given a boolean 2D array of n x m dimensions where each row is sorted. Find the 0-based index of the first row that has the maximum number of 1's.\nExample 1:\nInput: \nN = 4 , M = 4\nArr[][] = {{0, 1, 1, 1},\n {0, 0, 1, 1},\n {1, 1, 1, 1},\n {0, 0, 0, 0}}\nOutput: 2\nExplanation: Row 2 contains 4 1's (0-based\nindexing).\nExample 2:\nInput: \nN = 2, M = 2\nArr[][] = {{0, 0}, {1, 1}}\nOutput: 1\nExplanation: Row 1 contains 2 1's (0-based\nindexing).\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function rowWithMax1s() which takes the array of booleans arr[][], n and m as input parameters and returns the 0-based index of the first row that has the most number of 1s. If no such row exists, return -1.\n \nExpected Time Complexity: O(N+M)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ N, M ≤ 10^{3}\n0 ≤ Arr[i][j] ≤ 1", "solutions": ["def rowwithmax1s(arr, n, m):\n max_count = 0\n ans = -1\n for (i, v) in enumerate(arr):\n count = v.count(1)\n if count > max_count:\n max_count = count\n ans = i\n return ans", "def rowwithmax1s(arr, n, m):\n binary = []\n for x in range(n):\n binary.append(int(''.join(list(map(str, arr[x]))), 2))\n if max(binary) != 0:\n return binary.index(max(binary))\n return -1", "def rowwithmax1s(arr, n, m):\n (i, j) = (0, m - 1)\n index = 0\n while i != n and j != -1:\n if arr[i][j] == 1:\n j -= 1\n index = i\n else:\n i += 1\n if j == m - 1 and i == n:\n return -1\n return index", "def rowwithmax1s(arr, n, m):\n count = 0\n op = -1\n for i in range(0, n):\n t = sum(arr[i])\n if t > count:\n count = t\n op = i\n return op", "def rowwithmax1s(arr, n, m):\n maxi = 0\n ans = -1\n for i in range(n):\n count = 0\n for j in range(m):\n if arr[i][j] == 1:\n count += 1\n if count > maxi:\n maxi = count\n ans = i\n return ans", "def rowwithmax1s(arr, n, m):\n max_row_index = -1\n max_ones_count = 0\n j = m - 1\n for i in range(n):\n while j >= 0 and arr[i][j] == 1:\n j -= 1\n if j < m - 1:\n ones_count = m - 1 - j\n if ones_count > max_ones_count:\n max_ones_count = ones_count\n max_row_index = i\n return max_row_index", "import bisect\n\ndef rowwithmax1s(arr, n, m):\n rowIndex = -1\n row = 0\n col = m - 1\n while row < n and col >= 0:\n if arr[row][col] == 1:\n rowIndex = row\n col -= 1\n if arr[row][col] == 0:\n row += 1\n return rowIndex", "def rowwithmax1s(arr, n, m):\n max = 0\n ans = -1\n for i in range(n):\n cnt = 0\n for j in range(m):\n if arr[i][j] == 1:\n cnt += 1\n if cnt > max:\n ans = i\n max = cnt\n return ans", "def rowwithmax1s(arr, n, m):\n max_val = 0\n max_index = -1\n for x in range(len(arr)):\n total = 0\n for y in range(len(arr[0])):\n total += arr[x][y]\n if total > max_val:\n max_val = total\n max_index = x\n return max_index", "def rowwithmax1s(arr, n, m):\n max1srow = -1\n (row, col) = (0, m - 1)\n while row < n and col >= 0:\n if arr[row][col]:\n max1srow = row\n while col >= 0 and arr[row][col] == 1:\n col -= 1\n row += 1\n return max1srow", "def rowwithmax1s(arr, n, m):\n max1s = 0\n max1srow = -1\n for i in arr:\n ones = m\n for j in i:\n if j == 0:\n ones -= 1\n if ones > max1s:\n max1s = ones\n max1srow = arr.index(i)\n return max1srow", "def rowwithmax1s(mat, n, m):\n ans = -1\n min_col = int(1000000000.0)\n for row in range(n):\n (low, high) = (0, m - 1)\n first_occur_one = -1\n while low <= high:\n mid = low + (high - low) // 2\n if mat[row][mid] == 1:\n first_occur_one = mid\n high = mid - 1\n else:\n low = mid + 1\n if first_occur_one != -1:\n if min_col > first_occur_one:\n min_col = first_occur_one\n ans = row\n return ans", "def rowwithmax1s(arr, n, m):\n mx = 0\n pos = -1\n for i in range(0, len(arr)):\n sm = 0\n for j in range(0, len(arr[i])):\n sm += arr[i][j]\n if sm > mx:\n mx = sm\n pos = i\n return pos", "def rowwithmax1s(arr, n, m):\n (val, r_sum, maxSum) = (0, 0, 0)\n for r in range(n):\n for c in range(m):\n r_sum += arr[r][c]\n if r_sum > maxSum:\n maxSum = r_sum\n val = r\n r_sum = 0\n if maxSum == 0:\n return -1\n return val", "def rowwithmax1s(arr, n, m):\n m = 0\n for i in arr:\n s = sum(i)\n m = max(s, m)\n if m == 0:\n return -1\n for i in range(n):\n if sum(arr[i]) == m:\n return i", "def rowwithmax1s(arr, n, m):\n ans = fin = t = 0\n for i in range(n):\n c = 0\n for j in range(m):\n if arr[i][j] == 1:\n c += 1\n t = 1\n if c > ans:\n ans = c\n fin = i\n if ans == m:\n return i\n if t == 0:\n return -1\n return fin", "def rowwithmax1s(arr, n, m):\n ans = -1\n ansm = m\n for i in range(len(arr)):\n for j in range(len(arr[i])):\n if arr[i][j] == 1:\n if j < ansm:\n ans = i\n ansm = j\n return ans", "def rowwithmax1s(arr, n, m):\n max_ele = 0\n max_ind = 0\n for i in range(n):\n if max_ele < sum(arr[i]):\n max_ele = sum(arr[i])\n max_ind = i\n if max_ele == 0:\n return -1\n return max_ind", "def rowwithmax1s(arr, n, m):\n (prev, ans) = (0, -1)\n for i in range(n):\n (l, r) = (0, m - 1)\n while l < r:\n mid = l + (r - l) // 2\n if arr[i][mid] == 1:\n r = mid - 1\n else:\n l = mid + 1\n if arr[i][l] == 1:\n if m - l > prev:\n ans = i\n prev = m - l\n elif m - l - 1 > prev:\n ans = i\n prev = m - l - 1\n return ans", "def rowwithmax1s(arr, n, m):\n one_sum = 0\n for i in range(n):\n curr_one_sum = sum(arr[i])\n if curr_one_sum > one_sum:\n one_sum = curr_one_sum\n indx = i\n if one_sum > 0:\n return indx\n return -1", "def rowwithmax1s(arr, n, m):\n count = 0\n temp = 0\n index = -1\n for i in range(n):\n for j in range(m):\n if arr[i][j] == 1:\n temp += 1\n if temp > count:\n count = temp\n index = i\n temp = 0\n return index", "def rowwithmax1s(arr, n, m):\n x = [len([i for i in j if i == 1]) for j in arr]\n if max(x) == 0:\n return -1\n return x.index(max(x))", "def rowwithmax1s(arr, n, m):\n c = 0\n p = 0\n indx = 0\n for i in range(n):\n c = 0\n for j in range(m):\n if arr[i][j] == 1:\n c += 1\n if c > p:\n p = c\n indx = i\n if p == 0:\n return -1\n return indx", "def rowwithmax1s(arr, n, m):\n ans = -1\n row = 0\n column = m - 1\n while row < n and column >= 0:\n if arr[row][column] == 1:\n column -= 1\n ans = row\n else:\n row += 1\n return ans", "def rowwithmax1s(arr, n, m):\n result = -1\n maximum = 0\n for i in range(len(arr)):\n temp = sum(arr[i])\n if maximum < temp:\n maximum = temp\n result = i\n return result", "def rowwithmax1s(arr, n, m):\n ma = -1\n mc = 0\n for i in range(n):\n oc = arr[i].count(1)\n if oc > mc:\n mc = oc\n ma = i\n return ma\n if ma == 0:\n return -1", "def rowwithmax1s(arr, n, m):\n a = 0\n mi = 0\n ri = -1\n kc = 0\n for i in range(0, n):\n rc = 0\n for j in range(0, m):\n if arr[i][j] == 1:\n rc = rc + 1\n if rc > kc:\n kc = rc\n ri = i\n return ri", "def rowwithmax1s(arr, n, m):\n count = 0\n ans = -1\n for i in range(n):\n summ = sum(arr[i])\n if summ > count:\n count = summ\n ans = i\n return ans", "import bisect\n\ndef rowwithmax1s(arr, n, m):\n ans = -1\n count = m\n for i in range(n):\n x = bisect.bisect_left(arr[i], 1)\n if x < count:\n ans = i\n count = x\n return ans", "def rowwithmax1s(arr, n, m):\n d = {}\n for i in range(len(arr)):\n d[i] = arr[i].count(1)\n max = 0\n ans = 0\n for (a, b) in d.items():\n if int(b) > max:\n max = int(b)\n ans = int(a)\n if max == 0:\n return -1\n else:\n return ans", "def rowwithmax1s(arr, n, m):\n count = 0\n temp1 = -1\n for i in range(0, len(arr)):\n temp = arr[i].count(1)\n if temp > count:\n temp1 = i\n count = temp\n if temp1 == -1:\n return -1\n else:\n return temp1", "def rowwithmax1s(arr, n, m):\n maxones = 0\n maxindex = -1\n for i in range(len(arr)):\n rowcount = 0\n for j in range(len(arr[i])):\n if arr[i][j] == 1:\n rowcount += arr[i][j]\n if rowcount > maxones:\n maxones = rowcount\n maxindex = i\n return maxindex", "def rowwithmax1s(arr, n, m):\n (i, j) = (0, m - 1)\n count = 0\n index = 0\n ans = 0\n while i <= n - 1 and j >= 0:\n if arr[i][j] == 1:\n j -= 1\n count += 1\n index = i\n else:\n i += 1\n z = i\n for k in range(z, n):\n if arr[k][j] == 0:\n i += 1\n else:\n break\n if count == 0:\n return -1\n else:\n return index", "def rowwithmax1s(arr, n, m):\n max = 0\n row = 0\n for i in range(n):\n count = 0\n for j in range(m):\n if arr[i][j] == 1:\n count += 1\n if count > max:\n max = count\n row = i\n if max == 0:\n return -1\n else:\n return row", "def rowwithmax1s(arr, n, m):\n for col in range(m):\n for row in range(n):\n if arr[row][col] == 1:\n return row\n return -1", "def rowwithmax1s(arr, n, m):\n b = []\n for i in range(n):\n b.append(arr[i].count(1))\n if max(b) == 0:\n return -1\n else:\n res = b.index(max(b))\n return res", "def rowwithmax1s(arr, n, m):\n i = 0\n j = m - 1\n ans = -1\n while i < n and j >= 0:\n if arr[i][j] == 1:\n ans = i\n j -= 1\n if arr[i][j] == 0:\n i += 1\n return ans", "def rowwithmax1s(arr, n, m):\n r = 0\n c = m - 1\n max_row_index = -1\n while r < n and c >= 0:\n if arr[r][c] == 1:\n max_row_index = r\n c -= 1\n else:\n r += 1\n return max_row_index", "def rowwithmax1s(arr, n, m):\n res = -1\n mx = 0\n for i in range(len(arr)):\n count = 0\n for j in range(len(arr[i])):\n if arr[i][j] == 1:\n count += 1\n if count > mx:\n mx = count\n res = i\n return res", "def rowwithmax1s(arr, n, m):\n res = []\n for i in arr:\n res.append(sum(i))\n if max(res) == 0:\n return -1\n return res.index(max(res))", "def rowwithmax1s(arr, n, m):\n temp = 0\n ans = 0\n for i in range(len(arr)):\n cnt = arr[i].count(1)\n if cnt > temp:\n temp = cnt\n ans = i\n if temp == 0 and ans == 0:\n return -1\n return ans", "def rowwithmax1s(arr, n, m):\n currCol = len(arr[0])\n currRow = -1\n for r in range(len(arr)):\n for c in range(currCol - 1, -1, -1):\n if arr[r][c] == 1:\n currCol = c\n currRow = r\n else:\n break\n if currCol == 0:\n break\n return currRow", "def rowwithmax1s(arr, n, m):\n max = 0\n index = 0\n for i in range(n):\n (l, r) = (0, m - 1)\n if arr[i][r] == 0:\n continue\n while l <= r:\n mid = (l + r) // 2\n if arr[i][mid] == 0:\n l = mid + 1\n if arr[i][mid] == 1:\n r = mid - 1\n if m - r > max:\n index = i\n max = m - r\n if max == 0:\n return -1\n return index", "def rowwithmax1s(arr, n, m):\n c = 0\n for i in arr:\n if c < sum(i):\n c = sum(i)\n if c == 0:\n return -1\n else:\n for i in range(len(arr)):\n if sum(arr[i]) == c:\n return i", "def rowwithmax1s(arr, n, m):\n c = m - 1\n r_i = -1\n for i in range(n):\n while c >= 0 and arr[i][c] == 1:\n c -= 1\n r_i = i\n return r_i", "def rowwithmax1s(arr, n, m):\n count_arr = []\n for i in range(n):\n count = 0\n for j in range(m):\n if arr[i][j] == 1:\n count += 1\n count_arr.append(count)\n if max(count_arr) == 0:\n return -1\n max_ele = count_arr[0]\n index = 0\n for i in range(1, len(count_arr)):\n if count_arr[i] > max_ele:\n max_ele = count_arr[i]\n index = i\n return index", "def rowwithmax1s(arr, n, m):\n for i in range(m):\n for j in range(n):\n if arr[j][i] == 1:\n return j\n return -1", "def rowwithmax1s(arr, n, m):\n\n def BinaryFirstSearch(arr):\n n = len(arr)\n (res, l, r) = (float('inf'), 0, n - 1)\n while l <= r:\n mid = (l + r) // 2\n if arr[mid] == 1:\n res = mid\n r = mid - 1\n else:\n l = mid + 1\n return res\n ans = []\n for (idx, num) in enumerate(arr):\n ans.append([BinaryFirstSearch(num), idx])\n if min(ans)[0] < float('inf'):\n return min(ans)[1]\n return -1", "def rowwithmax1s(arr, n, m):\n\n def BinaryFirstSearch(arr):\n n = len(arr)\n (res, l, r) = (n, 0, n - 1)\n while l <= r:\n mid = (l + r) // 2\n if arr[mid] == 1:\n res = mid\n r = mid - 1\n else:\n l = mid + 1\n return res\n mx = 0\n ans = -1\n for i in range(len(arr)):\n if m - BinaryFirstSearch(arr[i]) > mx:\n mx = m - BinaryFirstSearch(arr[i])\n ans = i\n return ans", "def rowwithmax1s(matrix, n, m):\n res = []\n\n def leftocc(arr):\n start = 0\n end = len(arr) - 1\n mid = start + (end - start) // 2\n ans = 0\n while start <= end:\n if arr[mid] == 1:\n ans = mid\n end = mid - 1\n else:\n start = mid + 1\n mid = start + (end - start) // 2\n if ans == 0 and arr[0] == 0:\n return 0\n else:\n return len(arr) - ans\n for row in range(len(matrix)):\n count = leftocc(matrix[row])\n res.append((-1 * count, row))\n while True and res:\n ans = min(res)\n if ans[0] == 0:\n res.remove((ans[0], ans[1]))\n else:\n return ans[1]\n return -1", "def rowwithmax1s(arr, n, m):\n l = []\n for i in range(n):\n x = arr[i].count(1)\n l.append(x)\n x = max(l)\n if x == 0:\n return -1\n else:\n return l.index(max(l))", "def rowwithmax1s(arr, n, m):\n max = 0\n index = -1\n\n def bis(low, high, arr, c):\n mid = (low + high) // 2\n if low > high:\n return c\n if arr[mid] == 1:\n c += high - mid + 1\n return bis(low, mid - 1, arr, c)\n else:\n return bis(mid + 1, high, arr, c)\n for i in range(len(arr)):\n k = bis(0, m - 1, arr[i], 0)\n if max < k:\n max = k\n index = i\n return index", "def rowwithmax1s(matrix, R, C):\n row = -1\n j = C - 1\n for i in range(R):\n while j >= 0 and matrix[i][j] == 1:\n j -= 1\n row = i\n return row", "def rowwithmax1s(arr, n, m):\n dic = {}\n for (ind, row) in enumerate(arr):\n dic[ind] = row.count(1)\n maxvalue = 0\n index = 0\n for (key, value) in dic.items():\n if value > maxvalue:\n maxvalue = value\n index = key\n if maxvalue == 0:\n return -1\n return index", "def rowwithmax1s(arr, n, m):\n list_a = []\n k = 0\n for i in range(n):\n list_a.append(sum(arr[i]))\n max_count = max(list_a)\n for j in range(n):\n if max_count > 0:\n if max_count == list_a[j]:\n return j\n if k == 0:\n return -1", "def rowwithmax1s(arr, n, m):\n (s, idx) = (-1, -1)\n for i in range(len(arr)):\n temp = sum(arr[i])\n if temp >= 1 and temp > s:\n s = temp\n idx = i\n return idx", "def rowwithmax1s(arr, n, m):\n l = 0\n maxx = 0\n index = -1\n for i in range(n):\n if arr[i][-1] == 1:\n l = 0\n if m == 1:\n l = 1\n for j in range(m - 1):\n if arr[i][j] < arr[i][j + 1] or arr[i][j] == 1:\n if j == 0 and arr[i][j] == 1:\n l = m\n else:\n l = m - 1 - j\n break\n if l == m:\n return i\n if l > maxx:\n maxx = l\n index = i\n return index", "def rowwithmax1s(arr, n, m):\n c = [i for i in arr]\n k = []\n for i in range(len(c)):\n k.append(sum(c[i]))\n j = max(k)\n if sum(k) == 0:\n return -1\n return k.index(j)", "def rowwithmax1s(arr, n, m):\n c = mc = 0\n x = -1\n for i in range(len(arr)):\n c = arr[i].count(1)\n if c > mc:\n mc = c\n x = i\n return x", "def rowwithmax1s(arr, n, m):\n max_row_index = 0\n index = m - 1\n for i in range(n):\n flag = False\n while index >= 0 and arr[i][index] == 1:\n flag = True\n index -= 1\n if flag:\n max_row_index = i\n if max_row_index == 0 and arr[0][m - 1] == 0:\n return -1\n return max_row_index", "from collections import *\n\ndef rowwithmax1s(arr, n, m):\n dic = defaultdict(list)\n for i in range(len(arr)):\n dic[i] = arr[i].count(1)\n count = 0\n value = 0\n for (i, v) in dic.items():\n if v > value:\n value = v\n count = i\n if value == 0:\n return -1\n return count", "def rowwithmax1s(a, n, m):\n\n def getAns(a):\n l = 0\n h = len(a) - 1\n res = -1\n while l <= h:\n m = (l + h) // 2\n if a[m] == 1:\n res = m\n h = m - 1\n else:\n l = m + 1\n return res\n index = -1\n ans = m\n for i in range(n):\n x = getAns(a[i])\n if x < ans and x >= 0:\n ans = x\n index = i\n return index", "def rowwithmax1s(arr, n, m):\n n = len(arr)\n m = len(arr[0])\n maxRow = -1\n maxCount = 0\n for i in range(n):\n count = 0\n for j in range(m):\n if arr[i][j] == 1:\n count += 1\n if count > maxCount:\n maxCount = count\n maxRow = i\n return maxRow", "def rowwithmax1s(grid, n, m):\n (top, bottom) = (0, n - 1)\n (left, right) = (0, m - 1)\n result = -1\n while top <= bottom and left <= right:\n if grid[top][right] == 1:\n result = top\n right -= 1\n else:\n top += 1\n return result", "def rowwithmax1s(arr, n, m):\n (a, ac) = (-1, m)\n for i in range(n):\n (j, k) = (0, m - 1)\n while j <= k:\n mid = (j + k) // 2\n if arr[i][mid] == 1:\n k = mid - 1\n else:\n j = mid + 1\n ci = j\n if j < ac:\n a = i\n ac = j\n return a", "def rowwithmax1s(arr, n, m):\n (a, j) = (-1, m)\n for i in range(n):\n while j > 0 and arr[i][j - 1] == 1:\n a = i\n j -= 1\n if j == 0:\n return i\n return a", "def rowwithmax1s(arr, n, m):\n ans = []\n for i in range(n):\n s = 0\n for j in range(m):\n if arr[i][j] == 1:\n s += 1\n ans.append(s)\n ms = 0\n mi = -1\n for i in range(n):\n if ans[i] > ms:\n ms = ans[i]\n mi = i\n return mi", "def rowwithmax1s(arr, n, m):\n maxx = 0\n c = 0\n for i in range(len(arr)):\n if 1 not in arr[i]:\n c += 1\n if arr[i].count(1) > arr[maxx].count(1):\n maxx = i\n if c == len(arr):\n return -1\n return maxx", "def rowwithmax1s(arr, n, m):\n l = []\n for i in range(n):\n c = 0\n for j in range(m):\n if arr[i][j] == 1:\n c += 1\n l.append(c)\n maxi = max(l)\n if maxi != 0:\n return l.index(maxi)\n else:\n return -1", "def rowwithmax1s(arr, n, m):\n max_ones = 0\n row = -1\n for i in range(n):\n one_count = 0\n for j in range(m):\n if arr[i][j] == 1:\n one_count = m - j\n if one_count > max_ones:\n max_ones = one_count\n row = i\n break\n return row"], "starter_code": "def rowwithmax1s(arr, n, m):\n", "input_output": {"inputs": ["N = 4 , M = 4\r\nArr[][] = {{0, 1, 1, 1},\r\n {0, 0, 1, 1},\r\n {1, 1, 1, 1},\r\n {0, 0, 0, 0}}", "N = 2, M = 2\r\nArr[][] = {{0, 0}, {1, 1}}"], "outputs": ["2", "1"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Arrays", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/row-with-max-1s0023/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N+M)", "entry_point": "rowwithmax1s", "task_id": "TACO_lite/351", "example": [[[4, 4, [[0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]]], [2, 2, [[0, 0], [1, 1]]]], ["2", "1"]]} +{"requirement": "The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)\n\n\nP A H N\nA P L S I I G\nY I R\n\n\nAnd then read line by line: \"PAHNAPLSIIGYIR\"\n\nWrite the code that will take a string and make this conversion given a number of rows:\n\n\nstring convert(string s, int numRows);\n\nExample 1:\n\n\nInput: s = \"PAYPALISHIRING\", numRows = 3\nOutput: \"PAHNAPLSIIGYIR\"\n\n\nExample 2:\n\n\nInput: s = \"PAYPALISHIRING\", numRows = 4\nOutput: \"PINALSIGYAHRPI\"\nExplanation:\n\nP I N\nA L S I G\nY A H R\nP I", "solutions": ["def convert(s, numRows):\n if numRows == 1:\n return s\n zigzag = ['' for i in range(numRows)]\n row = 0\n step = 1\n for c in s:\n if row == 0:\n step = 1\n if row == numRows - 1:\n step = -1\n zigzag[row] += c\n row += step\n return ''.join(zigzag)", "def convert(s, numRows):\n if numRows == 1 or numRows >= len(s):\n return s\n result = [''] * numRows\n (index, step) = (0, 1)\n for c in s:\n result[index] += c\n if index == 0:\n step = 1\n elif index == numRows - 1:\n step = -1\n index += step\n return ''.join(result)", "def convert(s, numRows):\n if numRows == 1 or numRows >= len(s):\n return s\n list_string = [''] * numRows\n (index, step) = (0, 1)\n for i in s:\n list_string[index] += i\n if index == 0:\n step = 1\n elif index == numRows - 1:\n step = -1\n index += step\n return ''.join(list_string)", "def convert(s, nRows):\n if nRows == 1:\n return s\n tmp = ['' for i in range(nRows)]\n index = -1\n step = 1\n for i in range(len(s)):\n index += step\n if index == nRows:\n index -= 2\n step = -1\n elif index == -1:\n index = 1\n step = 1\n tmp[index] += s[i]\n return ''.join(tmp)", "def convert(s, numRows):\n if numRows == 1:\n return s\n count = len(s)\n if count <= 1:\n return s\n result = []\n deltSmall = numRows - 1\n deltBig = 2 * deltSmall\n for i in range(0, numRows):\n k = i\n if i == 0 or i == deltSmall:\n while k < count:\n result.append(s[k])\n k += deltBig\n else:\n while k < count:\n top = k - k % deltSmall\n bottom = top + deltSmall\n result.append(s[k])\n nextk = 2 * bottom - k\n if nextk < count:\n result.append(s[nextk])\n k += deltBig\n return ''.join(result)", "def convert(s, numRows):\n if len(s) == 0 or numRows < 1:\n return ''\n if numRows == 1:\n return s\n maxStep = (numRows - 1) * 2\n reStr = ''\n for i in range(numRows):\n j = i\n step = maxStep - 2 * i\n while j < len(s):\n reStr += s[j]\n if step == 0:\n j += maxStep\n else:\n j += step\n step = maxStep - step\n if step == 0:\n step = maxStep\n return reStr"], "starter_code": "def convert(s: str, numRows: int) -> str:\n", "input_output": {"fn_name": "convert", "inputs": [["\"PAYPALISHIRING\"", 3]], "outputs": ["\"PSIPYAIHRN\"ALIG"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["String"], "name": null, "source": "leetcode", "tags": ["String algorithms"], "skill_types": [], "url": "https://leetcode.com/problems/zigzag-conversion/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "convert", "task_id": "TACO_lite/377", "example": [[["PAYPALISHIRING", 3], ["PAYPALISHIRING", 4]], ["PAHNAPLSIIGYIR", "PINALSIGYAHRPI"]]} +{"requirement": "Given an array arr[] of positive integers of size N. Reverse every sub-array group of size K.\nNote: If at any instance, there are no more subarrays of size greater than or equal to K, then reverse the last subarray (irrespective of its size). You shouldn't return any array, modify the given array in-place.\nExample 1:\nInput:\nN = 5, K = 3\narr[] = {1,2,3,4,5}\nOutput: 3 2 1 5 4\nExplanation: First group consists of elements\n1, 2, 3. Second group consists of 4,5.\n \nExample 2:\nInput:\nN = 4, K = 3\narr[] = {5,6,8,9}\nOutput: 8 6 5 9\n \nYour Task:\nYou don't need to read input or print anything. The task is to complete the function reverseInGroups() which takes the array, N and K as input parameters and modifies the array in-place. \n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 ≤ N, K ≤ 10^{7}\n1 ≤ A[i] ≤ 10^{18}", "solutions": ["def reverseingroups(arr, N, k):\n n = len(arr)\n i = 0\n while i < n:\n if i + k <= n:\n left = i\n right = i + k - 1\n else:\n left = i\n right = n - 1\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1\n i += k\n return arr", "def reverseingroups(arr, N, K):\n i = 0\n while i < N:\n if i + K < N:\n arr[i:i + K] = arr[i:i + K][::-1]\n i += K\n else:\n arr[i:] = arr[i:N][::-1]\n i += K\n return arr", "def reverseingroups(arr, N, K):\n i = 0\n while i < N:\n if i + K < N:\n arr[i:i + K] = reversed(arr[i:i + K])\n i += K\n else:\n arr[i:] = reversed(arr[i:])\n i += K", "def reverseingroups(arr, N, K):\n for i in range(0, N, K):\n if i < N - K:\n arr[i:i + K] = arr[i:i + K][::-1]\n else:\n arr[i:] = arr[i:][::-1]\n return arr", "def reverseingroups(arr, N, K):\n start = 0\n end = K\n while start < N:\n new_list = arr[start:end]\n new_list.reverse()\n j = start\n for item in new_list:\n arr[j] = item\n j += 1\n start = end\n end = end + K\n return arr", "def reverseingroups(arr, N, K):\n i = 0\n while i + K < N:\n arr[i:i + K] = arr[i:i + K][::-1]\n i += K\n arr[i:] = arr[i:][::-1]", "def reverseingroups(arr, N, K):\n c = 0\n l1 = [0]\n for i in range(len(arr)):\n c += 1\n if c > K:\n l1.append(i)\n c = 1\n if c > 0 and c < K:\n l1.append(len(arr))\n for i in range(len(l1) - 1):\n arr[l1[i]:l1[i + 1]] = arr[l1[i]:l1[i + 1]][::-1]\n return arr", "def reverseingroups(arr, N, K):\n for i in range(0, N, K):\n start = i\n end = start + K - 1\n if start + K - 1 > N - 1:\n end = N - 1\n while start < end:\n (arr[start], arr[end]) = (arr[end], arr[start])\n start += 1\n end -= 1", "def reverseingroups(arr, N, K):\n i = 0\n while i < N:\n left = i\n right = min(i + K - 1, N - 1)\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1\n i += K", "def reverseingroups(arr, N, k):\n start = 0\n end = k - 1\n while end < N:\n tempStart = start\n tempEnd = end\n while tempStart < tempEnd:\n (arr[tempStart], arr[tempEnd]) = (arr[tempEnd], arr[tempStart])\n tempEnd -= 1\n tempStart += 1\n start = end + 1\n end += k\n if start < N:\n end = N - 1\n while start < end:\n (arr[start], arr[end]) = (arr[end], arr[start])\n start += 1\n end -= 1", "def reverseingroups(arr, N, K):\n N = N % K\n if len(arr) <= K:\n first = arr[:N + 1]\n first = first[::-1]\n second = arr[N + 1:]\n second = second[::-1]\n arr[:] = first + second\n return arr\n else:\n lst = []\n length = len(arr)\n divide = length // K\n a = 0\n b = K\n for i in range(divide + 1):\n res = arr[a:b][::-1]\n for i in res:\n lst.append(i)\n a = b\n b += K\n arr[:] = lst\n return arr", "def reverseingroups(arr, N, K):\n for i in range(0, N, K):\n arr[i:i + K] = arr[i:i + K][::-1]", "def reverseingroups(arr, N, K):\n for i in range(0, N, K):\n left = i\n right = min(i + K - 1, N - 1)\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1", "def reverseingroups(arr, n, k):\n for i in range(0, n, k):\n arr[i:i + k] = arr[i:i + k][::-1]\n return arr", "def reverseingroups(arr, N, K):\n for i in range(0, N, K):\n p = i + K - 1\n if p > N - 1:\n p = N - 1\n while p > i:\n (arr[i], arr[p]) = (arr[p], arr[i])\n p -= 1\n i += 1", "def reverseingroups(arr, N, K):\n a = []\n s = 0\n i = 0\n d = 0\n while s <= N:\n i += 1\n if i == K or s == N:\n a += arr[d:d + i][::-1]\n d += K\n i = 0\n s += 1\n return a", "def reverseingroups(arr, N, K):\n a = []\n jump = K\n for i in range(0, N):\n if jump <= N + K:\n a += arr[K * i:jump][::-1]\n jump += K\n else:\n arr[:] = a\n break", "def reverseingroups(arr, N, K):\n z = 0\n while z < N - 1:\n (i, j) = (z, min(z + K - 1, N - 1))\n while i < j:\n [arr[i], arr[j]] = [arr[j], arr[i]]\n i += 1\n j -= 1\n z = min(z + K, N - 1)", "def reverseingroups(arr, N, K):\n start = 0\n while start < N:\n end = min(start + K - 1, N - 1)\n left = start\n right = end\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1\n start += K\n return arr", "def reverseingroups(arr, N, K):\n for i in range(0, len(arr), K):\n group = arr[i:i + K]\n group.reverse()\n arr[i:i + K] = group", "def reverseingroups(arr, N, K):\n for i in range(0, N, K):\n arr[i:i + K] = reversed(arr[i:i + K])\n return arr", "def reverseingroups(arr, N, k):\n ans = []\n for x in range(0, len(arr), k):\n l = arr[x:x + k][::-1]\n ans += l\n i = 0\n for x in ans:\n arr[i] = x\n i += 1", "def reverseingroups(arr, N, K):\n i = 0\n while i < N:\n start = i\n end = min(i + K - 1, N - 1)\n while start < end:\n (arr[start], arr[end]) = (arr[end], arr[start])\n start += 1\n end -= 1\n i += K\n return arr", "def reverseingroups(arr, n, k):\n start = 0\n end = k - 1\n while end < n:\n tempstart = start\n tempend = end\n while tempstart < tempend:\n (arr[tempstart], arr[tempend]) = (arr[tempend], arr[tempstart])\n tempstart += 1\n tempend -= 1\n start = end + 1\n end = end + k\n if start < n:\n end = n - 1\n tempstart = start\n tempend = end\n while tempstart < tempend:\n (arr[tempstart], arr[tempend]) = (arr[tempend], arr[tempstart])\n tempstart += 1\n tempend -= 1", "def reverseingroups(arr, N, K):\n\n def rev_arr(arr, low, high):\n while low <= high:\n (arr[low], arr[high]) = (arr[high], arr[low])\n low += 1\n high -= 1\n for i in range(0, N, K):\n try:\n rev_arr(arr, i, i + K - 1)\n except IndexError:\n rev_arr(arr, i, N - 1)\n else:\n pass", "def reverseingroups(arr, n, k):\n i = 0\n while i < n:\n left = i\n right = min(i + k - 1, n - 1)\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1\n i += k\n return arr", "def reverseingroups(arr, N, K):\n x = 0\n while x < N:\n l = x\n if N - 1 >= x + K - 1:\n h = x + K - 1\n else:\n h = N - 1\n while l < h:\n (arr[h], arr[l]) = (arr[l], arr[h])\n h = h - 1\n l = l + 1\n x = x + K", "def reverseingroups(arr, N, K):\n ans = []\n r = N / K\n for i in range(0, N, K):\n end = i + K\n if end > N:\n end = N\n temp = arr[i:end]\n temp.reverse()\n arr[i:end] = temp", "def reverseingroups(arr, N, K):\n i = 0\n while i < N:\n l = i\n r = min(N - 1, i + K - 1)\n while l < r:\n (arr[l], arr[r]) = (arr[r], arr[l])\n l += 1\n r -= 1\n i = i + K", "def reverseingroups(arr, N, K):\n for i in range(0, N, K):\n if i + K <= N:\n arr[i:i + K] = reversed(arr[i:i + K])\n else:\n arr[i:] = reversed(arr[i:])\n break", "def reverseingroups(arr, n, k):\n i = 0\n while i < n:\n end = i + k - 1 if i + k - 1 < n else n - 1\n start = i\n while start < end:\n (arr[start], arr[end]) = (arr[end], arr[start])\n start += 1\n end -= 1\n i += k", "def swap(arr, i, j):\n t = arr[i]\n arr[i] = arr[j]\n arr[j] = t\n\ndef reverse(arr, start, end):\n while start < end:\n self.swap(arr, start, end)\n start += 1\n end -= 1\n\ndef reverseingroups(arr, N, K):\n start = 0\n while start < N:\n end = start + K\n if end < N:\n end -= 1\n else:\n end = N - 1\n self.reverse(arr, start, end)\n start += K", "import math\n\ndef reverseingroups(arr, N, K):\n self.arr = arr\n self.N = N\n self.K = K\n nn = int(math.ceil(N / K))\n for i in range(nn):\n ini = i * K\n fin = i * K + K\n sub_arr = arr[ini:fin]\n sub_arr.reverse()\n arr[ini:fin] = sub_arr\n return arr", "def reverseingroups(arr, n, k):\n i = 0\n while i < n:\n j = i + k - 1\n if j >= n:\n j = n - 1\n left = i\n right = j\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1\n i += k", "def reverseingroups(a, N, k):\n i = 0\n while i < N:\n a[i:i + k] = a[i:i + k][::-1]\n i = i + k\n return a", "def reverseingroups(arr, N, K):\n gp = N // K\n rm = N % K\n if gp != 0:\n for i in range(gp):\n for j in range(1, K // 2 + 1):\n (arr[i * K + j - 1], arr[i * K + K - j]) = (arr[i * K + K - j], arr[i * K + j - 1])\n for n in range(rm // 2):\n (arr[K * gp + n], arr[K * gp + rm - 1 - n]) = (arr[K * gp + rm - 1 - n], arr[K * gp + n])\n else:\n for n in range(N // 2):\n (arr[n], arr[N - n - 1]) = (arr[N - n - 1], arr[n])\n return arr"], "starter_code": "def reverseingroups(arr, N, K):\n", "input_output": {"inputs": ["N = 5, K = 3\r\narr[] = {1,2,3,4,5}", "N = 4, K = 3\r\narr[] = {5,6,8,9}"], "outputs": ["3 2 1 5 4", "8 6 5 9"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/reverse-array-in-groups0255/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "reverseingroups", "task_id": "TACO_lite/467", "example": [[[5, 3, [1, 2, 3, 4, 5]], [4, 3, [5, 6, 8, 9]]], ["[3, 2, 1, 5, 4]", "[8, 6, 5, 9]"]]} +{"requirement": "Given an array of n integers. We need to count all values of ‘k’ such that\narr[0] % k = arr[1] % k = ....... = arr[n-1] % k \n \nExample 1:\nInput:\nN=3\narr[] = {38, 6, 34} \nOutput: 3\nExplanation:\nWe can have values of k as \n1, 2 and 4. \nExample 2:\nInput:\nN=2\narr[] = {3, 2} \nOutput: 1\nYour Task:\nSince, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function printEqualModNumbers() that takes array arr and integer n as parameters and returns the desired output.\nNote- If values of k are infinite return -1.\n \nExpected Time Complexity: O(N^{3/2}).\nExpected Auxiliary Space: O(N).\n \nConstraints:\n1 ≤ N ≤ 10^{5}", "solutions": ["def fun(i, arr):\n k = arr[0] % i\n for j in arr:\n if j % i != k:\n return False\n return True\n\ndef printequalmodnumbers(arr, n):\n if n == 1:\n return -1\n a = max(arr)\n res = 0\n for i in range(1, a + 1):\n if Solution.fun(i, arr):\n res += 1\n if res == 0:\n return -1\n else:\n return res", "def printequalmodnumbers(arr, n):\n minum = max(arr)\n count = 1\n tcount = 0\n if len(arr) == 1:\n return -1\n for i in range(1, minum + 1):\n prev = arr[0] % i\n for j in range(1, len(arr)):\n if arr[j] % i == prev:\n count += 1\n else:\n break\n if count == len(arr):\n tcount += 1\n count = 1\n return tcount", "def printequalmodnumbers(arr, n):\n arr.sort()\n count = 0\n d = arr[n - 1] - arr[0]\n if d == 0:\n return -1\n v = []\n i = 1\n while i * i <= d:\n if d % i == 0:\n v.append(i)\n if i != d / i:\n v.append(d / i)\n i += 1\n for i in range(len(v)):\n temp = arr[0] % v[i]\n j = 1\n while j < n:\n if arr[j] % v[i] != temp:\n break\n j += 1\n if j == n:\n count += 1\n return count"], "starter_code": "def printequalmodnumbers(arr, n):\n", "input_output": {"inputs": ["N=3\narr[] = {38, 6, 34}", "N=2\narr[] = {3, 2}"], "outputs": ["3", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/k-modulus-array-element0255/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N^{3/2}).", "entry_point": "printequalmodnumbers", "task_id": "TACO_lite/342", "example": [[[3, [38, 6, 34]], [2, [3, 2]]], ["3", "1"]]} +{"requirement": "#Bubbleing around\n\nSince everybody hates chaos and loves sorted lists we should implement some more sorting algorithms. Your task is to implement a Bubble sort (for some help look at https://en.wikipedia.org/wiki/Bubble_sort) and return a list of snapshots after **each change** of the initial list.\n\ne.g. \n\nIf the initial list would be l=[1,2,4,3] my algorithm rotates l[2] and l[3] and after that it adds [1,2,3,4] to the result, which is a list of snapshots.\n```\n[1,2,4,3] should return [ [1,2,3,4] ]\n[2,1,4,3] should return [ [1,2,4,3], [1,2,3,4] ]\n[1,2,3,4] should return []\n```", "solutions": ["def bubble(l):\n ret = []\n for i in range(len(l) - 1, 0, -1):\n for j in range(i):\n if l[j] > l[j + 1]:\n (l[j], l[j + 1]) = (l[j + 1], l[j])\n ret.append(l[:])\n return ret", "def bubble(l):\n (bubbling, bubbles) = (True, [])\n while bubbling:\n bubbling = False\n for i in range(len(l) - 1):\n if l[i] > l[i + 1]:\n (l[i], l[i + 1]) = (l[i + 1], l[i])\n bubbling = True\n bubbles.append(l[:])\n return bubbles", "def bubble(l):\n arr = []\n for j in range(len(l) - 1, 0, -1):\n for i in range(j):\n if l[i] > l[i + 1]:\n temp = l[i]\n l[i] = l[i + 1]\n l[i + 1] = temp\n arr.append(l[:])\n return arr", "def bubble(lst):\n result = []\n mod = lst.copy()\n swap = True\n while swap:\n swap = False\n for i in range(len(mod) - 1):\n if mod[i] > mod[i + 1]:\n (mod[i], mod[i + 1]) = (mod[i + 1], mod[i])\n swap = True\n result.append(mod.copy())\n return result", "def bubble(l):\n snapshots = []\n for i in range(len(l), 1, -1):\n for j in range(1, i):\n if l[j - 1] > l[j]:\n (l[j - 1], l[j]) = (l[j], l[j - 1])\n snapshots.append(l[:])\n return snapshots", "def swap(l, aindex, bindex):\n tmp = l[bindex]\n l[bindex] = l[aindex]\n l[aindex] = tmp\n\ndef bubble(l):\n result = []\n for _ in range(len(l) - 1):\n for i in range(len(l) - 1):\n if l[i] > l[i + 1]:\n swap(l, i, i + 1)\n result.append(list(l))\n return result", "def bubble(l):\n (n, permutations) = (len(l), [])\n while n:\n m = 0\n for i in range(1, n):\n if l[i - 1] > l[i]:\n (l[i - 1], l[i]) = (l[i], l[i - 1])\n permutations.append(l[:])\n m = i\n n = m\n return permutations", "def bubble(l):\n (output, toChange) = ([], True)\n while toChange:\n toChange = False\n for (i, x) in enumerate(l[:-1]):\n if l[i + 1] < l[i]:\n (l[i], l[i + 1]) = (l[i + 1], l[i])\n output.append(l[:])\n toChange = True\n return output", "def bubble(l):\n r = []\n for i in range(0, len(l)):\n for j in range(1, len(l)):\n if l[j] < l[j - 1]:\n t = l[j]\n l[j] = l[j - 1]\n l[j - 1] = t\n r.append(l[:])\n return r", "def bubble(a):\n if a == None or len(a) < 2:\n return []\n swapped = True\n i = 0\n r = []\n while i < len(a) - 1 and swapped:\n swapped = False\n for j in range(len(a) - i - 1):\n if a[j] > a[j + 1]:\n (a[j], a[j + 1]) = (a[j + 1], a[j])\n r.append(list(a))\n swapped = True\n i += 1\n return r"], "starter_code": "def bubble(l):\n", "input_output": {"fn_name": "bubble", "inputs": [[[]], [[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[1, 3, 3, 7, 4, 2]]], "outputs": [[[]], [[]], [[[1, 3, 3, 4, 7, 2], [1, 3, 3, 4, 2, 7], [1, 3, 3, 2, 4, 7], [1, 3, 2, 3, 4, 7], [1, 2, 3, 3, 4, 7]]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Sorting", "Algorithms"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/57403b5ad67e87b5e7000d1d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "bubble", "task_id": "TACO_lite/452", "example": [[[[1, 2, 4, 3]], [[2, 1, 4, 3]], [[1, 2, 3, 4]]], ["[[1, 2, 3, 4]]", "[[1, 2, 4, 3], [1, 2, 3, 4]]", "[]"]]} +{"requirement": "In this kata you need to write a function that will receive two strings (```n1``` and ```n2```), each representing an integer as a binary number. A third parameter will be provided (```o```) as a string representing one of the following operators: add, subtract, multiply.\n\nYour task is to write the calculate function so that it will perform the arithmetic and the result returned should be a string representing the binary result.\n\nExamples:\n```\n1 + 1 === 10\n10 + 10 === 100\n```\n\nNegative binary numbers are usually preceded by several 1's. For this kata, negative numbers can be represented with the negative symbol at the beginning of the string.\n\nExamples of negatives:\n```\n1 - 10 === -1\n10 - 100 === -10\n```", "solutions": ["def calculate(n1, n2, o):\n operators = {'add': lambda x, y: x + y, 'subtract': lambda x, y: x - y, 'multiply': lambda x, y: x * y}\n return '{:b}'.format(operators[o](int(n1, 2), int(n2, 2)))", "def calculate(n1, n2, o):\n\n def s2b(i):\n return int(i, base=2)\n if o == 'add':\n res = s2b(n1) + s2b(n2)\n elif o == 'subtract':\n res = s2b(n1) - s2b(n2)\n elif o == 'multiply':\n res = s2b(n1) * s2b(n2)\n return '{0:b}'.format(res)", "def calculate(n1, n2, o):\n ops = {'add': lambda a, b: a + b, 'subtract': lambda a, b: a - b, 'multiply': lambda a, b: a * b}\n n = ops[o](int(n1, 2), int(n2, 2))\n s = str(bin(n))\n return '-' + s[3:] if n < 0 else s[2:]", "from operator import add, sub as subtract, mul as multiply\n\ndef calculate(n1, n2, o):\n value = globals()[o](int(n1, 2), int(n2, 2))\n return format(value, 'b')", "from operator import *\n\ndef calculate(n1, n2, o):\n result = eval(o[:3])(int(n1, 2), int(n2, 2))\n return (bin(result)[2:], bin(result)[0] + bin(result)[3:])[result < 0]", "import operator\n\ndef calculate(n1, n2, o):\n calc = {'add': operator.add(int(n1, base=2), int(n2, base=2)), 'subtract': operator.sub(int(n1, base=2), int(n2, base=2)), 'multiply': operator.mul(int(n1, base=2), int(n2, base=2))}\n return '{:b}'.format(calc[o])", "def calculate(n1, n2, o):\n if o == 'add':\n return bin(int(n1, 2) + int(n2, 2))[2:]\n if o == 'subtract':\n result = bin(int(n1, 2) - int(n2, 2))\n if result[0] == '-':\n return result[0] + result[3:]\n return result[2:]\n if o == 'multiply':\n return bin(int(n1, 2) * int(n2, 2))[2:]\n if o == 'divide':\n return bin(int(n1, 2) / int(n2, 2))[2:]", "def calculate(n1, n2, o):\n return bin(int(n1, 2) + int(n2, 2) if o == 'add' else int(n1, 2) - int(n2, 2) if o == 'subtract' else int(n1, 2) * int(n2, 2)).replace('0b', '')"], "starter_code": "def calculate(n1, n2, o):\n", "input_output": {"fn_name": "calculate", "inputs": [["1", "1", "add"], ["1", "1", "subtract"], ["1", "1", "multiply"], ["10", "10", "multiply"], ["100", "10", "subtract"]], "outputs": [["10"], ["0"], ["1"], ["100"], ["10"]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Binary"], "name": null, "source": "codewars", "tags": ["Bit manipulation"], "skill_types": ["Bit manipulation"], "url": "https://www.codewars.com/kata/546ba103f0cf8f7982000df4", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "calculate", "task_id": "TACO_lite/464", "example": [[["1", "1", "add"], ["10", "10", "add"], ["1", "10", "subtract"], ["10", "100", "subtract"]], ["10", "100", "-1", "-10"]]} +{"requirement": "**This Kata is intended as a small challenge for my students**\n\nAll Star Code Challenge #16\n\nCreate a function called noRepeat() that takes a string argument and returns a single letter string of the **first** not repeated character in the entire string.\n\n``` haskell\nnoRepeat \"aabbccdde\" `shouldBe` 'e'\nnoRepeat \"wxyz\" `shouldBe` 'w'\nnoRepeat \"testing\" `shouldBe` 'e'\n```\n\nNote:\nONLY letters from the english alphabet will be used as input\nThere will ALWAYS be at least one non-repeating letter in the input string", "solutions": ["def no_repeat(s):\n return next((c for c in s if s.count(c) == 1))", "def no_repeat(string):\n return [x for x in string if string.count(x) == 1][0]", "from collections import Counter\n\ndef no_repeat(string):\n return next((k for (k, v) in Counter(string).items() if v == 1))", "no_repeat = lambda s: [w for w in s if s.count(w) == 1][0]", "def no_repeat(stg):\n return next((c for c in stg if stg.count(c) == 1))", "def no_repeat(string):\n for e in string:\n if string.count(e) == 1:\n return e", "def no_repeat(string):\n if string.count(string[0]) == 1:\n return string[0]\n else:\n return no_repeat(string.replace(string[0], ''))", "def no_repeat(string):\n return min(string, key=string.count)", "def no_repeat(string):\n for c in string:\n if len(string.split(c)) == 2:\n return c", "def no_repeat(string):\n for i in string:\n if string.index(i) == len(string) - string[::-1].index(i) - 1:\n return i"], "starter_code": "def no_repeat(string):\n", "input_output": {"fn_name": "no_repeat", "inputs": [["aabbccdde"], ["wxyz"], ["testing"], ["codewars"], ["Testing"]], "outputs": [["e"], ["w"], ["e"], ["c"], ["T"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/586566b773bd9cbe2b000013", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "no_repeat", "task_id": "TACO_lite/481", "example": [[["aabbccdde"], ["wxyz"], ["testing"]], ["e", "w", "e"]]} +{"requirement": "Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: `(index1, index2)`.\n\nFor the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted.\n\nThe input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array).\n\nBased on: http://oj.leetcode.com/problems/two-sum/", "solutions": ["def two_sum(nums, t):\n for (i, x) in enumerate(nums):\n for (j, y) in enumerate(nums):\n if i != j and x + y == t:\n return [i, j]", "def two_sum(nums, target):\n d = {}\n for (i, num) in enumerate(nums):\n diff = target - num\n if diff in d:\n return [d[diff], i]\n d[num] = i", "def two_sum(numbers, target):\n d = {}\n for (i, n) in enumerate(numbers):\n if target - n in d:\n return [d[target - n], i]\n d[n] = i", "def two_sum(numbers, target):\n for i in range(0, len(numbers)):\n for x in range(0, len(numbers)):\n if numbers[i] + numbers[x] == target and i != x:\n index1 = i\n index2 = x\n break\n return sorted([index1, index2])", "def two_sum(numbers, target):\n for (i, val1) in enumerate(numbers[:-1]):\n for (j, val2) in enumerate(numbers[i + 1:]):\n if val1 + val2 == target:\n return (i, j + i + 1)", "def two_sum(numbers, target):\n return [[i, numbers.index(target - numbers[i])] for i in range(len(numbers)) if target - numbers[i] in numbers].pop()", "def two_sum(n, target):\n for i in range(len(n) - 1):\n if target - n[i] in n[i + 1:]:\n return [i, n[i + 1:].index(target - n[i]) + (i + 1)]\n return None", "def two_sum(numbers, target):\n for i in range(len(numbers)):\n for j in range(len(numbers)):\n if i != j and numbers[i] + numbers[j] == target:\n return [i, j]", "def two_sum(numbers, target):\n numbers.sort()\n i = 0\n j = len(numbers) - 1\n sum_ = numbers[i] + numbers[j]\n while sum_ != target:\n if sum_ < target:\n i += 1\n elif sum_ > target:\n j -= 1\n sum_ = numbers[i] + numbers[j]\n return [i, j]", "from itertools import combinations\n\ndef two_sum(numbers, target):\n for (i1, i2) in combinations(list(range(len(numbers))), 2):\n if numbers[i1] + numbers[i2] == target:\n return (i1, i2)"], "starter_code": "def two_sum(numbers, target):\n", "input_output": {"fn_name": "two_sum", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Algorithms"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/52c31f8e6605bcc646000082", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "two_sum", "task_id": "TACO_lite/449", "example": [[[[2, 7, 11, 15], 9], [[3, 2, 4], 6], [[3, 3], 6]], ["(0, 1)", "(1, 2)", "(0, 1)"]]} +{"requirement": "Consider the following array:\n\n```\n[1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789, 12345678910, 1234567891011...]\n```\n\nIf we join these blocks of numbers, we come up with an infinite sequence which starts with `112123123412345123456...`. The list is infinite.\n\nYou will be given an number (`n`) and your task will be to return the element at that index in the sequence, where `1 ≤ n ≤ 10^18`. Assume the indexes start with `1`, not `0`. For example:\n\n```\nsolve(1) = 1, because the first character in the sequence is 1. There is no index 0. \nsolve(2) = 1, because the second character is also 1.\nsolve(3) = 2, because the third character is 2.\n```\n\nMore examples in the test cases. Good luck!", "solutions": ["def solve(n):\n\n def length(n):\n s = 0\n for i in range(20):\n o = 10 ** i - 1\n if o > n:\n break\n s += (n - o) * (n - o + 1) // 2\n return s\n\n def binary_search(k):\n n = 0\n for p in range(63, -1, -1):\n if length(n + 2 ** p) < k:\n n += 2 ** p\n return n\n\n def sequence(n):\n if n < 10:\n return n\n for i in range(1, 19):\n segment = i * 9 * 10 ** (i - 1)\n if n <= segment:\n return str(10 ** (i - 1) + (n - 1) // i)[(n - 1) % i]\n else:\n n -= segment\n return int(sequence(n - length(binary_search(n))))", "from itertools import count\nfrom math import floor\nfrom decimal import Decimal\n\ndef find_sum(a, d, n):\n return int(Decimal(n / 2) * Decimal(2 * a + (n - 1) * d))\n\ndef term(a, d, n):\n return a + d * (n - 1)\n\ndef solve_quadratic(a, b, c):\n return floor((-b + (b ** 2 - 4 * a * c) ** 0.5) / (2 * a))\n\ndef extract(n):\n passed = 0\n for i in count(1):\n k = 9 * 10 ** (i - 1) * i\n if passed + k >= n:\n return str(int(10 ** (i - 1) + (n - passed) // i))[int(n - passed) % i]\n passed += k\n\ndef solve(n):\n (n, start, passed) = (n - 1, 1, 0)\n for i in count(1):\n k = 9 * 10 ** (i - 1)\n sum_ = find_sum(start, i, k)\n if passed + sum_ >= n:\n p = solve_quadratic(i, 2 * start - i, -((n - passed) * 2))\n q = passed + find_sum(start, i, p)\n return int(extract(n - q))\n start = term(start, i, k) + (i + 1)\n passed += sum_\nsolve(int(1e+100))", "def getGreatest(n, d, prefix):\n rows = 9 * 10 ** (d - 1)\n triangle = rows * (d + rows * d) // 2\n l = 0\n r = triangle\n while l < r:\n mid = l + (r - l >> 1)\n triangle = mid * prefix + mid * (d + mid * d) // 2\n prevTriangle = (mid - 1) * prefix + (mid - 1) * (d + (mid - 1) * d) // 2\n nextTriangle = (mid + 1) * prefix + (mid + 1) * (d + (mid + 1) * d) // 2\n if triangle >= n:\n if prevTriangle < n:\n return prevTriangle\n else:\n r = mid - 1\n elif nextTriangle >= n:\n return triangle\n else:\n l = mid\n return l * prefix + l * (d + l * d) // 2\nns = [1, 2, 3, 100, 2100, 31000, 999999999999999999, 1000000000000000000, 999999999999999993]\n\ndef solve(n):\n debug = 1\n d = 0\n p = 0.1\n prefixes = [0]\n sections = [0]\n while sections[d] < n:\n d += 1\n p *= 10\n rows = int(9 * p)\n triangle = rows * (d + rows * d) // 2\n section = rows * prefixes[d - 1] + triangle\n sections.append(sections[d - 1] + section)\n prefixes.append(prefixes[d - 1] + rows * d)\n section = sections[d - 1]\n n = n - section\n rows = getGreatest(n, d, prefixes[d - 1])\n n = n - rows\n d = 1\n while prefixes[d] < n:\n d += 1\n if prefixes[d] == n:\n return 9\n prefix = prefixes[d - 1]\n n -= prefix\n countDDigitNums = n // d\n remainder = n % d\n prev = 10 ** (d - 1) - 1\n num = prev + countDDigitNums\n if remainder:\n return int(str(num + 1)[remainder - 1])\n else:\n s = str(num)\n return int(s[len(s) - 1])", "import math\n\ndef seq_len_formula(s, b, n, i):\n return s + i * b + n * (i * (i + 1) // 2)\n\ndef increasing_step(num_len, block_len, seq_len):\n num_of_blocks = 9 * 10 ** num_len\n num_len += 1\n seq_len = seq_len_formula(seq_len, block_len, num_len, num_of_blocks)\n block_len = block_len + num_len * num_of_blocks\n return (num_len, block_len, seq_len)\n\ndef solve(n):\n buffer = IS_seq_len = (0, 0, 0)\n while IS_seq_len[2] < n:\n (num_len, block_len, seq_len) = buffer = IS_seq_len\n IS_seq_len = increasing_step(num_len, block_len, seq_len)\n (num_len, init_block_len, init_seq_len) = buffer\n step = 9 * 10 ** num_len\n num_len += 1\n buffer = (0, init_seq_len)\n while step > 0:\n (num_of_blocks, seq_len) = buffer\n while seq_len < n:\n buffer = (num_of_blocks, seq_len)\n num_of_blocks += step\n seq_len = seq_len_formula(init_seq_len, init_block_len, num_len, num_of_blocks)\n step = round(step / 10)\n n -= buffer[1]\n buffer = IS_block_len = (0, 0, 0)\n while IS_block_len[1] < n:\n (num_len, block_len, seq_len) = buffer = IS_block_len\n IS_block_len = increasing_step(num_len, block_len, seq_len)\n num_len = 10 ** buffer[0] - 1\n block_len = buffer[1]\n amount_of_nums = math.ceil((n - block_len) / len(str(num_len + 1)))\n n = n - amount_of_nums * len(str(num_len + 1)) - block_len - 1\n num = amount_of_nums + num_len\n return int(str(num)[n])", "def solve(k):\n k -= 1\n (i, d, p, n, s) = (0, 1, 0, 9, 45)\n while i + s <= k:\n i += s\n p += n * d\n d += 1\n n = 10 ** d - 10 ** (d - 1)\n s = n * p + n * d * (n + 1) // 2\n k -= i\n i = int((((2 * p + d) ** 2 + 8 * k * d) ** 0.5 - (2 * p + d)) / (2 * d))\n k -= i * p + i * d * (i + 1) // 2\n (i, d, s) = (0, 1, 9)\n while i + s <= k:\n i += s\n d += 1\n n = 10 ** d - 10 ** (d - 1)\n s = n * d\n (q, r) = divmod(k - i, d)\n return int(str(10 ** (d - 1) + q)[r])", "import math\n\ndef seq_len_formula(s, b, n, i):\n return s + i * b + n * (i * (i + 1) // 2)\n\ndef point_gen():\n (num_len, block_len, seq_len) = (0, 0, 0)\n while True:\n yield (num_len, block_len, seq_len)\n num_of_blocks = 9 * 10 ** num_len\n num_len += 1\n seq_len = seq_len_formula(seq_len, block_len, num_len, num_of_blocks)\n block_len = block_len + num_len * num_of_blocks\n\ndef linear_search(index, parameter):\n params = {'block_len': 1, 'seq_len': 2}\n required_point = (0, 0, 0)\n for point in point_gen():\n if point[params[parameter]] >= index:\n return required_point\n required_point = point\n\ndef index_for_block(num_len, block_len, index):\n corrector = num_of_blocks = 9 * 10 ** (num_len - 1)\n seq_len = seq_len_formula(0, block_len, num_len, num_of_blocks)\n while not seq_len < index <= seq_len_formula(0, block_len, num_len, num_of_blocks + 1):\n corrector = math.ceil(corrector / 2)\n num_of_blocks = num_of_blocks - corrector if seq_len >= index else num_of_blocks + corrector\n seq_len = seq_len_formula(0, block_len, num_len, num_of_blocks)\n return index - seq_len\n\ndef solve(index):\n (initial_len, initial_block_len, initial_seq_len) = linear_search(index, 'seq_len')\n index = index_for_block(initial_len + 1, initial_block_len, index - initial_seq_len)\n buffer = linear_search(index, 'block_len')\n (num_len, block_len) = (10 ** buffer[0] - 1, buffer[1])\n amount_of_nums = math.ceil((index - block_len) / len(str(num_len + 1)))\n return int(str(amount_of_nums + num_len)[index - amount_of_nums * len(str(num_len + 1)) - block_len - 1])", "from math import sqrt, ceil, log10\nimport numpy as np\n\ndef getGreatest(n, d, prefix):\n rows = 9 * 10 ** (d - 1)\n triangle = rows * (d + rows * d) // 2\n l = 0\n r = triangle\n while l < r:\n mid = l + (r - l >> 1)\n triangle = mid * prefix + mid * (d + mid * d) // 2\n prevTriangle = (mid - 1) * prefix + (mid - 1) * (d + (mid - 1) * d) // 2\n nextTriangle = (mid + 1) * prefix + (mid + 1) * (d + (mid + 1) * d) // 2\n if triangle >= n:\n if prevTriangle < n:\n return prevTriangle\n else:\n r = mid - 1\n elif nextTriangle >= n:\n return triangle\n else:\n l = mid\n return l * prefix + l * (d + l * d) // 2\n\ndef findDiff(n, x):\n mult = 1\n temp = x / 10\n while temp >= 1:\n temp /= 10\n mult *= 10\n d = round(log10(mult)) + 1\n prefixes = 0\n for z in range(1, d):\n prefixes += 9 * z * 10 ** (z - 1)\n n -= calcSeq(mult - 1)\n return n - getGreatest(n, d, prefixes)\n\ndef calcSeq(current):\n x = np.int64(current * (current + 1) / 2)\n mult = 10\n temp = np.int64(current)\n while temp > 0:\n temp = current\n temp -= mult - 1\n mult *= 10\n if temp > 0:\n x += np.int64(temp * (temp + 1) / 2)\n return x\n\ndef solve(n):\n maxN = n\n minN = 0\n x = float(0)\n delta = 2\n prev = 0\n current = round(sqrt(2 * n))\n prevRight = True\n while maxN - minN > 1:\n x = calcSeq(current)\n delta = abs(current - prev)\n prev = current\n if x < n and prevRight:\n current += ceil((maxN - current) / 2)\n prevRight = True\n elif x < n:\n minN = current\n current += ceil((maxN - current) / 2)\n prevRight = True\n elif x > n and prevRight == False:\n maxN = current\n current -= round((current - minN) / 2)\n prevRight = False\n elif x > n:\n current -= round((current - minN) / 2)\n prevRight = False\n else:\n maxN = current\n minN = current - 1\n if calcSeq(current) < n:\n current += 1\n prev = current - 1\n element = findDiff(n, prev)\n (nDigits, nines) = (1, 9)\n total = float(nDigits * nines)\n while total < element:\n nDigits += 1\n nines *= 10\n total += nDigits * nines\n total -= nDigits * nines\n element2 = element - total\n start = 10 ** (nDigits - 1)\n number = str(start + ceil(element2 / nDigits) - 1)\n return int(number[(int(element2) - 1) % nDigits])"], "starter_code": "def solve(n):\n", "input_output": {"fn_name": "solve", "inputs": [[1], [2], [3], [100], [2100], [31000], [55], [123456], [123456789], [999999999999999999], [1000000000000000000], [999999999999999993]], "outputs": [[1], [1], [2], [1], [2], [2], [1], [6], [3], [4], [1], [7]]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5e1ab1b9fe268c0033680e5f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/474", "example": [[[1], [2], [3]], ["1", "1", "2"]]} +{"requirement": "An abundant number or excessive number is a number for which the sum of its proper divisors is greater than the number itself. \n\nThe integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16 (> 12).\n\nDerive function `abundantNumber(num)/abundant_number(num)` which returns `true/True/.true.` if `num` is abundant, `false/False/.false.` if not.", "solutions": ["def abundant_number(num):\n return sum([e for e in range(1, num) if num % e == 0]) > num", "def abundant_number(n):\n return sum((m for m in range(1, n) if n % m == 0)) > n", "def abundant_number(num):\n return sum((i for i in range(1, num // 2 + 1) if not num % i)) > num", "def abundant_number(num):\n sum_divisors = 1\n int_sqrt = int(num ** 0.5)\n for div in range(2, int_sqrt + 1):\n if num % div == 0:\n sum_divisors += div + num // div\n if int_sqrt ** 2 == num:\n sum_divisors -= int_sqrt\n return sum_divisors > num", "def abundant_number(num):\n return sum([x for x in range(1, num) if num % x == 0]) > num", "def abundant_number(n):\n return sum((n // i + i for i in range(2, int(n ** 0.5) + 1) if n % i == 0)) + 1 > n"], "starter_code": "def abundant_number(num):\n", "input_output": {"fn_name": "abundant_number", "inputs": [[12], [18], [37], [120], [77], [118], [5830], [11410], [14771], [11690]], "outputs": [[true], [true], [false], [true], [false], [false], [true], [true], [false], [true]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/56a75b91688b49ad94000015", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "abundant_number", "task_id": "TACO_lite/432", "example": [[], []]} +{"requirement": "Given a non-negative integer N. Check whether the Binary Representation of the number is Palindrome or not. \nNote: No leading 0’s are being considered.\nExample 1:\nInput:\nN = 5\nOutput: 1\nExplanation: The Binary Representation of\n5 is 101 which is a Palindrome.\n​Example 2:\nInput: \nN = 10\nOutput: 0\nExplanation: The Binary Representation of\n10 is 1010 which is not a Palindrome.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function binaryPalin() which takes an integer N as input and returns 1 if the binary representation of N is a palindrome. Else, return 0 .\nExpected Time Complexity: Log(N). \nExpected Auxiliary Space: O(1).\nConstraints:\n0<=N<=2^{63}-1", "solutions": ["def binarypalin(N):\n b = str(bin(N).replace('0b', ''))\n if b == b[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n s = '{0:b}'.format(N)\n if s == s[::-1]:\n return 1\n else:\n return 0", "def binarypalin(n):\n b = bin(n)[2:]\n if b == b[::-1]:\n return 1\n return 0", "def binarypalin(N):\n a = bin(N).replace('0b', '')\n if a[::-1] == a:\n return 1\n return 0", "def binarypalin(N):\n ans = 0\n ans2 = 0\n i = 0\n while N != 0:\n bit = N & 1\n ans = bit * 10 ** i + ans\n ans2 = ans2 * 10 + bit\n i += 1\n N = N >> 1\n if ans == ans2:\n return 1\n else:\n return 0", "def binarypalin(N):\n s = bin(N)[2:]\n if s == s[::-1]:\n return 1\n return 0", "def palin(num):\n check = num[::-1]\n if num == check:\n return 1\n else:\n return 0\n\ndef binarypalin(N):\n bina = ''\n while N > 0:\n bina += str(N % 2)\n N = int(N / 2)\n return Solution.palin(bina)", "def binarypalin(N):\n s = ''\n temp = N\n while N > 0:\n s += str(N % 2)\n N = N // 2\n if s == s[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n a = bin(N)[2:]\n b = a[::-1]\n if a == b:\n return 1\n else:\n return 0", "def binarypalin(N):\n a = int(bin(N)[2:])\n temp = a\n rev = 0\n while temp:\n rem = temp % 10\n rev = rev * 10 + rem\n temp = temp // 10\n if rev == a:\n return 1\n else:\n return 0", "def binarypalin(N):\n k = bin(N)[2:]\n t = k[::-1]\n if k == t:\n return 1\n else:\n return 0", "def binarypalin(N):\n c = bin(int(N)).replace('0b', '')\n if str(c) == str(c)[::-1]:\n return 1\n return 0", "def binarypalin(N):\n num = bin(N)[2:]\n return int(num == num[::-1])", "def binarypalin(N):\n a = bin(N)\n s = str(a)\n x = ''\n for i in range(len(s) - 1, 1, -1):\n x = x + s[i]\n b = x[::-1]\n if x == b:\n return 1\n return 0", "def binarypalin(N):\n binary_string = str(bin(N).replace('0b', ''))\n if binary_string == binary_string[::-1]:\n return 1\n return 0", "def binarypalin(n):\n s = str(bin(n))[2:]\n if s == s[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n res = bin(N)\n a = str(res)\n ans = res.replace('0b', '')\n p = ans[::-1]\n if ans == p:\n return 1\n else:\n return 0", "def binarypalin(N):\n s = str(bin(N))\n l = s.split('b')\n a = l[1]\n p = a[::-1]\n if a == p:\n return 1\n else:\n return 0", "def binarypalin(N):\n b = list(bin(N))\n l = b[2:]\n if l == l[::-1]:\n return 1\n return 0", "def binarypalin(N):\n ans = bin(N)\n ans1 = ''\n ans = ans[2:]\n ans1 = ans[::-1]\n a = ans == ans1\n if a == True:\n return 1\n return 0", "def binarypalin(N):\n bi = bin(N).replace('0b', '')\n if bi == bi[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N: int) -> int:\n bin_number = self.binary(N)\n if bin_number == bin_number[::-1]:\n return 1\n else:\n return 0\n\ndef binary(n: int) -> str:\n result = []\n while n:\n result.insert(0, str(n % 2))\n n //= 2\n return ''.join(result)", "def binarypalin(N):\n n1 = bin(N).replace('0b', '')\n for i in n1:\n if n1 == n1[::-1]:\n return 1\n break\n else:\n return 0", "def binarypalin(N):\n x = bin(n)\n x = x[2:]\n l = 0\n r = len(x) - 1\n while l < r:\n if x[l] == x[r]:\n l += 1\n r -= 1\n else:\n return 0\n return 1", "def binarypalin(N):\n no = bin(N)[2:]\n if int(no[0]) != 0:\n if no == no[::-1]:\n return 1\n else:\n return 0\n else:\n return 0", "def binarypalin(N):\n b = bin(N)[2:]\n return int(b == b[::-1])", "def binarypalin(N):\n l = []\n while N > 0:\n l.append(N % 2)\n N //= 2\n f = l[::-1]\n if f == l:\n return 1\n else:\n return 0", "def binarypalin(N):\n a = '{0:b}'.format(int(N))\n c = a[::-1]\n if a == c:\n return 1\n else:\n return 0", "def binarypalin(N):\n arr = []\n while N != 0:\n arr.append(N & 1)\n N >>= 1\n length = len(arr)\n iterations = length // 2\n for x in range(iterations):\n if arr[x] != arr[length - x - 1]:\n return 0\n return 1", "def binarypalin(N):\n x = int(bin(N)[2:])\n if str(x) == str(x)[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n l = str(bin(N)[2:])\n h = l[::-1]\n if l == h:\n return 1\n else:\n return 0", "def binarypalin(N):\n binstr = bin(N)[2:]\n binpal = ''.join(list(reversed(binstr)))\n if binpal == binstr:\n return 1\n else:\n return 0", "def binarypalin(N):\n N = str(bin(N)[2:])\n n = len(N)\n for i in range(int(n / 2)):\n if N[i] != N[n - i - 1]:\n return 0\n return 1", "def binarypalin(N):\n binaryN = bin(N).replace('0b', '')\n rev = binaryN[::-1]\n if binaryN == rev:\n return 1\n return 0", "def binarypalin(N):\n x = bin(N)\n y = x[::-1]\n if x[2:] == y[:-2]:\n return 1\n else:\n return 0", "def binarypalin(N):\n binary = bin(N)[2:]\n rbin = binary[::-1]\n if binary == rbin:\n return 1\n else:\n return 0", "def binary(num):\n binary = ''\n while num != 0:\n rem = num % 2\n binary = str(rem) + binary\n num //= 2\n return binary\n\ndef binarypalin(N):\n binary = self.binary(N)\n temp = str(int(binary))\n rev = temp[::-1]\n if temp == rev:\n return 1\n return 0", "def binarypalin(n):\n reverseBinary = ''\n while n:\n reverseBinary += str(n & 1)\n n >>= 1\n if reverseBinary == reverseBinary[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n binary = bin(N).replace('0b', '')\n n = len(binary)\n for i in range(n):\n if binary[i] != binary[n - i - 1]:\n return 0\n return 1", "def binarypalin(N):\n st = bin(N)[2:]\n if st == st[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n a = bin(N)\n b = a.replace('0b', '')\n c = str(b)\n d = c[::-1]\n if b == d:\n return 1\n else:\n return 0", "def binarypalin(N):\n bin = ''\n while N != 0:\n bin = str(N % 2) + bin\n N = N // 2\n i = 0\n j = len(bin) - 1\n while i <= len(bin) - 1 or j > i:\n if i == j or i > j:\n return 1\n elif bin[i] != bin[j]:\n return 0\n i = i + 1\n j = j - 1", "def binarypalin(N):\n s = bin(N)[2:]\n m = str(s)\n if m == m[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n N = bin(N)\n N_final = N[2:len(N)]\n N_final_rev = ''\n for i in range(len(N_final) - 1, -1, -1):\n N_final_rev += N_final[i]\n if N_final == N_final_rev:\n return 1\n else:\n return 0", "def binarypalin(num):\n b = bin(num)[2:]\n if b == b[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n\n def binary(num):\n if int(num) == 1:\n return '1'\n else:\n re = int(num) % 2\n num = int(int(num)) // 2\n return str(re) + binary(num)\n x = binary(N)\n x1 = x[::-1]\n if x1 == x:\n return 1\n else:\n return 0", "def binarypalin(N):\n\n def isPalindrome(x):\n return x == x[::-1]\n binary = bin(N)\n return 1 if isPalindrome(binary[2:]) else 0", "def binarypalin(N):\n a = bin(N)[2:]\n x = str(a)\n ans = x[::-1]\n if x == ans:\n return 1\n else:\n return 0", "def binarypalin(N):\n o = str(bin(N)[2:])\n p = o[::-1]\n if p == o:\n return 1\n else:\n return 0", "def binarypalin(N):\n n = bin(N)\n n = list(n)\n n = n[2:]\n k = n[::-1]\n if k == n:\n return 1\n return 0", "def binarypalin(N):\n a = bin(N)\n x = a[a.index('b') + 1:]\n if x == x[::-1]:\n return 1\n else:\n return 0"], "starter_code": "def binarypalin (N):\n", "input_output": {"inputs": ["N = 5", "N = 10"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Binary Representation", "palindrome"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/check-if-actual-binary-representation-of-a-number-is-palindrome0624/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "Log(N).", "entry_point": "binarypalin", "task_id": "TACO_lite/483", "example": [[[5], [10]], ["1", "0"]]} +{"requirement": "As the title suggests, this is the hard-core version of another neat kata.\n\nThe task is simple to explain: simply sum all the numbers from the first parameter being the beginning to the second parameter being the upper limit (possibly included), going in steps expressed by the third parameter:\n\n```python\nsequence_sum(2, 2, 2) # 2\nsequence_sum(2, 6, 2) # 12 (= 2 + 4 + 6)\nsequence_sum(1, 5, 1) # (= 1 + 2 + 3 + 4 + 5)\nsequence_sum(1, 5, 3) # 5 (= 1 + 4)\n```\n\nIf it is an impossible sequence (with the beginning being larger the end and a positive step or the other way around), just return `0`. See the provided test cases for further examples :)\n\n**Note:** differing from the other base kata, much larger ranges are going to be tested, so you should hope to get your algo optimized and to avoid brute-forcing your way through the solution.", "solutions": ["def sequence_sum(a, b, step):\n n = (b - a) // step\n return 0 if n < 0 else (n + 1) * (n * step + a + a) // 2", "def sequence_sum(b, e, s):\n (q, r) = divmod(e - b, s)\n return (b + e - r) * max(q + 1, 0) // 2", "def sequence_sum(start, stop, step):\n n = (stop - start) // step\n last = start + n * step\n return (n + 1) * (start + last) // 2 if n >= 0 else 0", "def sequence_sum(b, e, s):\n if s > 0 and b > e or (s < 0 and b < e):\n return 0\n near = e - (e - b) % s\n n = (near - b) // s + 1\n return (b + near) * n // 2", "def sequence_sum(b, e, s):\n if b > e and s > 0 or (b < e and s < 0):\n return 0\n k = (e - b) // s\n return b * (k + 1) + s * (k * (k + 1)) // 2", "def sequence_sum(begin, end, step):\n n = int((end - begin + step) / step)\n an = begin + (n - 1) * step\n if step > 0:\n if begin > end:\n return 0\n if step < 0:\n if begin < end:\n return 0\n if n % 2 == 0:\n res = int(int(n / 2) * (begin + an))\n if (begin + an) % 2 == 0:\n res = int(int((begin + an) / 2) * n)\n return res", "from decimal import Decimal\n\ndef sequence_sum(s, e, step):\n if s > e and step > 0 or (s < e and step < 0):\n return 0\n elems = abs(s - e) // abs(step) + 1\n last = s + step * (elems - 1)\n avg = (s + last) / 2\n return int(Decimal(elems) * Decimal(avg))", "def sequence_sum(a, b, s):\n n = (b - a) // s\n return 0 if n < 0 else (n + 1) * (2 * a + s * n) // 2"], "starter_code": "def sequence_sum(b, e, s):\n", "input_output": {"fn_name": "sequence_sum", "inputs": [[2, 6, 2], [1, 5, 1], [1, 5, 3], [-1, -5, -3], [16, 15, 3], [-24, -2, 22], [-2, 4, 658], [780, 6851543, 5], [9383, 71418, 2], [20, 673388797, 5]], "outputs": [[12], [15], [5], [-5], [0], [-26], [-2], [4694363402480], [1253127200], [45345247259849570]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/587a88a208236efe8500008b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sequence_sum", "task_id": "TACO_lite/471", "example": [[[2, 2, 2], [2, 6, 2], [1, 5, 1], [1, 5, 3]], ["2", "12", "15", "5"]]} +{"requirement": "Given two linked lists, your task is to complete the function makeUnion(), that returns the union list of two linked lists. This union list should include all the distinct elements only and it should be sorted in ascending order.\nExample 1:\nInput:\nL1 = 9->6->4->2->3->8\nL2 = 1->2->8->6->2\nOutput: \n1 2 3 4 6 8 9\nExplaination: \nAll the distinct numbers from two lists, when sorted forms the list in the output. \nExample 2:\nInput:\nL1 = 1->5->1->2->2->5\nL2 = 4->5->6->7->1\nOutput: \n1 2 4 5 6 7\nExplaination: \nAll the distinct numbers from two lists, when sorted forms the list in the output.\nYour Task:\nThe task is to complete the function makeUnion() which makes the union of the given two lists and returns the head of the new list.\nExpected Time Complexity: O((N+M)*Log(N+M))\nExpected Auxiliary Space: O(N+M)\nConstraints:\n1<=N,M<=10^{4}", "solutions": ["def union(head1, head2):\n d = {}\n while head1 != None:\n if head1.data not in d:\n d[head1.data] = head1.data\n head1 = head1.next\n while head2 != None:\n if head2.data not in d:\n d[head2.data] = head2.data\n head2 = head2.next\n head = linkedList()\n for (key, val) in sorted(d.items()):\n head.insert(key)\n return head.head", "def union(head1, head2):\n s1 = set()\n s2 = set()\n cur = head1\n prev = head2\n while cur:\n s1.add(cur.data)\n cur = cur.next\n while prev:\n s2.add(prev.data)\n prev = prev.next\n res = sorted(s1.union(s2))\n n = Node(0)\n h = n\n for i in res:\n k = Node(i)\n n.next = k\n n = n.next\n return h.next", "def union(head1, head2):\n s = set()\n curr_node = head1\n while curr_node:\n s.add(curr_node.data)\n curr_node = curr_node.next\n curr_node = head2\n while curr_node:\n s.add(curr_node.data)\n curr_node = curr_node.next\n lst3 = list(s)\n lst3.sort()\n L1 = linkedList()\n curr_node = L1.head\n for item in lst3:\n new_node = Node(item)\n if curr_node:\n curr_node.next = new_node\n curr_node = curr_node.next\n else:\n L1.head = new_node\n curr_node = L1.head\n return L1.head", "def union(head1, head2):\n lst1 = []\n lst2 = []\n curr_node = head1\n while curr_node:\n lst1.append(curr_node.data)\n curr_node = curr_node.next\n curr_node = head2\n while curr_node:\n lst2.append(curr_node.data)\n curr_node = curr_node.next\n lst3 = list(set(lst1 + lst2))\n lst3.sort()\n L1 = linkedList()\n curr_node = L1.head\n for item in lst3:\n new_node = Node(item)\n if curr_node:\n curr_node.next = new_node\n curr_node = curr_node.next\n else:\n L1.head = new_node\n curr_node = L1.head\n return L1.head", "def union(head1, head2):\n n1 = head1\n s1 = set()\n while n1 is not None:\n s1.add(n1.data)\n n1 = n1.next\n n2 = head2\n s2 = set()\n while n2 is not None:\n s2.add(n2.data)\n n2 = n2.next\n a = list(s1 | s2)\n a.sort()\n new = Node(0)\n n = new\n while a:\n new_node = Node(a.pop(0))\n n.next = new_node\n n = n.next\n return new.next", "def union(head1, head2):\n h1 = []\n t1 = head1\n while t1:\n h1.append(t1.data)\n t1 = t1.next\n h2 = []\n t2 = head2\n while t2:\n h2.append(t2.data)\n t2 = t2.next\n res = sorted(list(set(h1 + h2)))\n llr = linkedList()\n for x in res:\n llr.insert(x)\n return llr.head", "def union(head1, head2):\n ans = list()\n while head1 or head2:\n if head1 == None:\n ans.append(head2.data)\n head2 = head2.next\n elif head2 == None:\n ans.append(head1.data)\n head1 = head1.next\n else:\n ans.append(head1.data)\n ans.append(head2.data)\n (head1, head2) = (head1.next, head2.next)\n ans.sort()\n node = Node(-1)\n head = node\n for x in range(len(ans)):\n if node.data == ans[x]:\n continue\n temp = Node(ans[x])\n node.next = temp\n node = node.next\n return head.next", "def union(head1, head2):\n p = []\n a = head1\n while a is not None:\n if a.data not in p:\n p.append(a.data)\n a = a.next\n b = head2\n while b is not None:\n if b.data not in p:\n p.append(b.data)\n b = b.next\n head3 = None\n c = None\n for i in sorted(p):\n m = Node(i)\n if head3 is None:\n head3 = m\n c = head3\n else:\n head3.next = m\n head3 = head3.next\n return c", "def union(head1, head2):\n l = []\n ll = []\n n = head1\n nn = head2\n while n:\n l.append(n.data)\n n = n.next\n while nn:\n ll.append(nn.data)\n nn = nn.next\n l += ll\n s = set(l)\n ss = list(s)\n ss.sort()\n ls = linkedList()\n for i in ss:\n ls.insert(i)\n return ls.head", "def union(head1, head2):\n p = head1\n s = []\n while p:\n s.append(p.data)\n p = p.next\n p = head2\n while p:\n s.append(p.data)\n p = p.next\n x = list(set(s))\n x.sort()\n ll = linkedList()\n for i in x:\n ll.insert(i)\n return ll.head", "def union(head1, head2):\n li = []\n temp = head1\n while temp:\n li.append(temp.data)\n temp = temp.next\n temp1 = head2\n while temp1:\n li.append(temp1.data)\n temp1 = temp1.next\n li = list(set(li))\n li.sort()\n p = Node(0)\n temp = p\n while li:\n temp.next = Node(li.pop(0))\n temp = temp.next\n return p.next", "def union(head1, head2):\n s = set()\n while head1:\n s.add(head1.data)\n head1 = head1.next\n while head2:\n s.add(head2.data)\n head2 = head2.next\n l = list(s)\n l.sort()\n res = linkedList()\n for x in l:\n res.insert(x)\n return res.head", "def union(head1, head2):\n rec = set()\n while head1:\n rec.add(head1.data)\n head1 = head1.next\n while head2:\n rec.add(head2.data)\n head2 = head2.next\n lst = list(rec)\n lst.sort()\n res = linkedList()\n for x in lst:\n res.insert(x)\n return res.head", "def union(head1, head2):\n d = {}\n while head1.next != None:\n d[head1.data] = 1\n head1 = head1.next\n d[head1.data] = 1\n while head2.next != None:\n d[head2.data] = 1\n head2 = head2.next\n d[head2.data] = 1\n l = list(d.keys())\n l.sort()\n w = 0\n a = []\n for j in l:\n if w == 0:\n p = Node(j)\n a.append(p)\n w += 1\n else:\n p.next = Node(j)\n p = p.next\n return a[0]", "def union(head1, head2):\n list = []\n head = linkedList()\n while head1 != None or head2 != None:\n if head1 != None or head2 == None:\n list.append(head1.data)\n head1 = head1.next\n elif head1 == None or head2 != None:\n list.append(head2.data)\n head2 = head2.next\n list.sort()\n list.append(90)\n ref = []\n i = 0\n while i < len(list) - 1:\n if list[i] != list[i + 1]:\n ref.append(list[i])\n i += 1\n for i in ref:\n head.insert(i)\n return head.head", "def union(head1, head2):\n kmap = set()\n ptr = head1\n while ptr:\n kmap.add(ptr.data)\n ptr = ptr.next\n ptr = head2\n while ptr:\n kmap.add(ptr.data)\n ptr = ptr.next\n arr = list(kmap)\n arr.sort()\n dum = Node(-1)\n ptr = dum\n for ele in arr:\n nn = Node(ele)\n ptr.next = nn\n ptr = ptr.next\n return dum.next", "def union(head1, head2):\n current_1 = head1\n current_2 = head2\n temp_list_1 = []\n temp_list_2 = []\n third_linked_list = linkedList()\n while current_1:\n temp_list_1.append(current_1.data)\n current_1 = current_1.next\n while current_2:\n temp_list_2.append(current_2.data)\n current_2 = current_2.next\n temp_list = set(temp_list_1) | set(temp_list_2)\n temp_list = sorted(temp_list)\n for elements in temp_list:\n third_linked_list.insert(elements)\n return third_linked_list.head", "def union(head1, head2):\n if head1 == None and head2 == None:\n return None\n if head1 == None:\n return head2\n if head2 == None:\n return head1\n temp1 = head1\n temp2 = head2\n l = []\n while temp1 != None and temp2 != None:\n if temp1.data not in l:\n l.append(temp1.data)\n if temp2.data not in l:\n l.append(temp2.data)\n temp1 = temp1.next\n temp2 = temp2.next\n while temp1 != None:\n if temp1.data not in l:\n l.append(temp1.data)\n temp1 = temp1.next\n while temp2 != None:\n if temp2.data not in l:\n l.append(temp2.data)\n temp2 = temp2.next\n newHead = None\n l.sort()\n for i in l:\n dummy = Node(i)\n if newHead == None:\n newHead = dummy\n else:\n temp = newHead\n while temp.next != None:\n temp = temp.next\n temp.next = dummy\n return newHead", "def union(head1, head2):\n newlist = []\n while head1:\n newlist.append(head1.data)\n head1 = head1.next\n while head2:\n newlist.append(head2.data)\n head2 = head2.next\n sortedlist = sorted(list(set(newlist)))\n dummy = Node(0)\n curr = dummy\n for element in sortedlist:\n newNode = Node(element)\n curr.next = newNode\n curr = curr.next\n return dummy.next", "def union(head1, head2):\n llist = []\n p1 = head1\n p2 = head2\n s = set()\n while p1:\n s.add(p1.data)\n p1 = p1.next\n while p2:\n if p2.data not in s:\n s.add(p2.data)\n p2 = p2.next\n for e in s:\n llist.append(e)\n llist.sort()\n dummy = Node(0)\n curr = dummy\n for ele in llist:\n newnode = Node(ele)\n curr.next = newnode\n curr = curr.next\n return dummy.next", "def union(head1, head2):\n union = set()\n stack1 = [head1]\n stack2 = [head2]\n while len(stack1) > 0:\n current1 = stack1.pop()\n union.add(current1.data)\n if current1.next:\n stack1.append(current1.next)\n while len(stack2) > 0:\n current2 = stack2.pop()\n union.add(current2.data)\n if current2.next:\n stack2.append(current2.next)\n union = sorted(union)\n uList = []\n for item in union:\n uList.append(item)\n head = Node(uList[0])\n lastNode = head\n for i in range(1, len(uList)):\n node = Node(uList[i])\n lastNode.next = node\n lastNode = node\n lastNode.next = None\n return head", "def union(head1, head2):\n s = set()\n while head1 or head2:\n if head1:\n if head1 not in s:\n s.add(head1.data)\n head1 = head1.next\n if head2:\n if head2 not in s:\n s.add(head2.data)\n head2 = head2.next\n a = b = Node(0)\n for i in sorted(s):\n a.next = Node(i)\n a = a.next\n return b.next", "def union(head1, head2):\n a = []\n while head1:\n a.append(head1.data)\n head1 = head1.next\n while head2:\n a.append(head2.data)\n head2 = head2.next\n s = sorted(list(set(a)))\n d = Node(-1)\n p = d\n i = 0\n while i < len(s):\n d.next = Node(s[i])\n d = d.next\n i = i + 1\n return p.next", "def union(head1, head2):\n x = set()\n temp = head1\n while temp is not None:\n x.add(temp.data)\n temp = temp.next\n temp = head2\n while temp is not None:\n x.add(temp.data)\n temp = temp.next\n ans = list(x)\n ans = sorted(ans)\n i = 1\n head = Node(ans[0])\n temp = head\n while i < len(ans):\n x = Node(ans[i])\n temp.next = x\n temp = x\n i += 1\n return head", "def union(head1, head2):\n itr1 = head1\n itr2 = head2\n l = []\n while itr1:\n l.append(itr1.data)\n itr1 = itr1.next\n while itr2:\n l.append(itr2.data)\n itr2 = itr2.next\n l = set(l)\n l = list(l)\n l.sort()\n ll = linkedList()\n for i in l:\n ll.insert(i)\n return ll.head", "def union(head1, head2):\n s = set()\n while head1:\n s.add(head1.data)\n head1 = head1.next\n while head2:\n s.add(head2.data)\n head2 = head2.next\n s = list(s)\n s.sort()\n start = cur = None\n for i in s:\n tmp = Node(i)\n if start == None:\n start = tmp\n cur = start\n else:\n cur.next = tmp\n cur = tmp\n return start", "def union(head1, head2):\n curr = head1\n lis = set()\n while curr:\n lis.add(curr.data)\n curr = curr.next\n curr = head2\n while curr:\n lis.add(curr.data)\n curr = curr.next\n sortedlis = sorted(lis)\n temp = Node('dummy')\n curr = temp\n for i in sortedlis:\n node = Node(i)\n curr.next = node\n curr = curr.next\n return temp.next", "def union(head1, head2):\n l1 = []\n l2 = []\n l3 = []\n c1 = 0\n c2 = 0\n cur1 = Node(head1)\n cur1.data = head1.data\n cur1.next = head1.next\n while cur1 != None:\n l1.append(cur1.data)\n c1 += 1\n cur1 = cur1.next\n cur2 = Node(head2)\n cur2.data = head2.data\n cur2.next = head2.next\n while cur2 != None:\n l2.append(cur2.data)\n c2 += 1\n cur2 = cur2.next\n l4 = l1 + l2\n l4 = set(l4)\n l3 = list(l4)\n l3.sort()\n cur = Node(l3[0])\n cur.next = None\n head3 = Node(0)\n head3 = cur\n i = 1\n while i < len(l3):\n new_node = Node(l3[i])\n cur.next = new_node\n cur = cur.next\n i += 1\n return head3", "def union(head1, head2):\n s = set()\n while head1:\n s.add(head1.data)\n head1 = head1.next\n while head2:\n s.add(head2.data)\n head2 = head2.next\n l = []\n for i in s:\n l.append(i)\n l.sort()\n l.reverse()\n h1 = Node(l[0])\n l.remove(l[0])\n for i in l:\n node = Node(i)\n node.next = h1\n h1 = node\n return h1", "def union(head1, head2):\n s = set()\n curr = head1\n while curr:\n i = curr.data\n if i not in s:\n s.add(i)\n curr = curr.next\n curr = head2\n while curr:\n i = curr.data\n if i not in s:\n s.add(i)\n curr = curr.next\n l = sorted(list(s))\n head = Node(l[0])\n curr = head\n for i in l[1:]:\n curr.next = Node(i)\n curr = curr.next\n return head", "def union(head1, head2):\n temp1 = head1\n op = set()\n while temp1.next:\n temp1 = temp1.next\n temp1.next = head2\n temp1 = head1\n while temp1:\n op.add(temp1.data)\n temp1 = temp1.next\n op = sorted(list(op))\n temp1 = head1\n for i in range(len(op)):\n temp1.data = op[i]\n prev = temp1\n temp1 = temp1.next\n prev.next = None\n return head1", "def union(head1, head2):\n tek = head1\n arr1 = []\n while tek != None:\n arr1.append(tek.data)\n tek = tek.next\n tek = head2\n while tek != None:\n arr1.append(tek.data)\n tek = tek.next\n arr = set(arr1)\n arr1 = list(arr)\n arr1.sort()\n head3 = Node(0)\n tek = head3\n i = 0\n while i < len(arr1):\n tek.next = Node(arr1[i])\n tek = tek.next\n i += 1\n return head3.next", "def union(head1, head2):\n new = set()\n while head2:\n new.add(head2.data)\n head2 = head2.next\n while head1:\n new.add(head1.data)\n head1 = head1.next\n new = list(new)\n new.sort()\n ans = Node(0)\n temp = ans\n for i in range(len(new)):\n curr = Node(new[i])\n temp.next = curr\n temp = curr\n return ans.next", "def union(head1, head2):\n s = set()\n while head2:\n s.add(head2.data)\n head2 = head2.next\n while head1:\n s.add(head1.data)\n head1 = head1.next\n s = list(s)\n s.sort()\n ans = Node(-1)\n temp = ans\n for i in range(len(s)):\n new = Node(s[i])\n temp.next = new\n temp = new\n return ans.next", "def union(head1, head2):\n a = head1\n b = head2\n v = set()\n while a:\n v.add(a.data)\n a = a.next\n while b:\n v.add(b.data)\n b = b.next\n v = sorted(v)\n dummy = Node(0)\n m = dummy\n for i in v:\n m.next = Node(i)\n m = m.next\n return dummy.next", "def union(head1, head2):\n s = set()\n while head1:\n s.add(head1.data)\n head1 = head1.next\n while head2:\n s.add(head2.data)\n head2 = head2.next\n s = list(s)\n s.sort()\n start = None\n for i in s:\n node = Node(i)\n if start == None:\n start = node\n prev = node\n else:\n prev.next = node\n prev = node\n return start", "def union(head1, head2):\n (temp1, temp2) = (head1, head2)\n (l1, l2) = ([], [])\n while temp1:\n l1.append(temp1.data)\n temp1 = temp1.next\n while temp2:\n l2.append(temp2.data)\n temp2 = temp2.next\n res = []\n for i in l1:\n if i not in res:\n res.append(i)\n for i in l2:\n if i not in res:\n res.append(i)\n res.sort()\n ll = linkedList()\n for i in res:\n ll.insert(i)\n return ll.head", "def union(head1, head2):\n c = {}\n temp1 = head1\n temp2 = head2\n while temp1 != None or temp2 != None:\n if temp1 != None:\n c[temp1.data] = 1\n temp1 = temp1.next\n if temp2 != None:\n c[temp2.data] = 1\n temp2 = temp2.next\n l = linkedList()\n x = sorted(c.keys())\n for i in x:\n l.insert(i)\n return l.head", "def union(head1, head2):\n res = {}\n cur = head1\n while cur:\n res[cur.data] = 1\n cur = cur.next\n cur = head2\n while cur:\n res[cur.data] = 1\n cur = cur.next\n r1 = linkedList()\n l1 = sorted(res.keys())\n for item in l1:\n r1.insert(item)\n return r1.head", "import heapq\n\ndef union(head1, head2):\n h = []\n s = set()\n n = head1\n while n:\n s.add(n.data)\n n = n.next\n n = head2\n while n:\n s.add(n.data)\n n = n.next\n for i in s:\n h.append(i)\n h.sort()\n N = None\n head = None\n for i in h:\n n = Node(i)\n if not head:\n head = n\n N = n\n else:\n N.next = n\n N = n\n return head", "def union(head1, head2):\n s = {head1.data}\n tmp = head1.next\n while tmp != None:\n s.add(tmp.data)\n tmp = tmp.next\n tmp = head2\n while tmp != None:\n s.add(tmp.data)\n tmp = tmp.next\n tmp = head1\n x = 0\n for i in sorted(s):\n tmp.data = i\n if tmp.next == None and x < len(s) - 1:\n tmp.next = head2\n if x == len(s) - 1:\n tmp.next = None\n return head1\n tmp = tmp.next\n x += 1", "def union(head1, head2):\n ans = Sol()\n l = []\n while head1 is not None:\n l.append(head1.data)\n head1 = head1.next\n while head2 is not None:\n l.append(head2.data)\n head2 = head2.next\n l = sorted(list(set(l)))\n for i in l:\n new = Node(i)\n if ans.head == None:\n ans.head = new\n ans.tail = new\n else:\n ans.tail.next = new\n ans.tail = new\n return ans.head\n\ndef __init__(data):\n self.data = data\n self.next = None\n\ndef __init__():\n self.head = None\n self.tail = None", "def union(head1, head2):\n set_elt = {head1.data}\n (res, h) = (head1, head1)\n while head1.next:\n if head1.data not in set_elt:\n set_elt.add(head1.data)\n h.next = head1\n h = h.next\n head1 = head1.next\n if head1.data not in set_elt:\n set_elt.add(head1.data)\n h.next = head1\n h = head1\n while head2.next:\n if head2.data not in set_elt:\n set_elt.add(head2.data)\n h.next = head2\n h = head2\n head2 = head2.next\n if head2.data not in set_elt:\n set_elt.add(head2.data)\n h.next = head2\n h = head2\n h.next = None\n return sortList(res)\n\ndef sortList(head):\n if not head or not head.next:\n return head\n (l1, l2) = split(head)\n l1 = sortList(l1)\n l2 = sortList(l2)\n return merge(l1, l2)\n\ndef split(l):\n fast = l\n slow = l\n while fast.next and fast.next.next:\n fast = fast.next.next\n slow = slow.next\n temp = slow.next\n slow.next = None\n return (l, temp)\n\ndef merge(l1, l2):\n if not l1:\n return l2\n if not l2:\n return l1\n if l1.data <= l2.data:\n res = l1\n l1 = l1.next\n else:\n res = l2\n l2 = l2.next\n h = res\n while l1 and l2:\n if l1.data <= l2.data:\n h.next = l1\n l1 = l1.next\n else:\n h.next = l2\n l2 = l2.next\n h = h.next\n if l1:\n h.next = l1\n if l2:\n h.next = l2\n return res", "def union(head1, head2):\n p = head1\n q = head2\n d = set()\n s = set()\n while p != None:\n d.add(p.data)\n p = p.next\n while q:\n s.add(q.data)\n q = q.next\n intersect = d.union(s)\n op = linkedList()\n for e in sorted(intersect):\n op.insert(e)\n return op.head", "def union(head1, head2):\n (t, tt) = (head1, head2)\n k = []\n while t:\n if t.data not in k:\n k.append(t.data)\n t = t.next\n while tt:\n if tt.data not in k:\n k.append(tt.data)\n tt = tt.next\n k.sort()\n root = Node(k[0])\n i = 1\n r = root\n while i < len(k):\n y = Node(k[i])\n r.next = y\n r = r.next\n i += 1\n return root", "def union(head1, head2):\n l = []\n while head1:\n l.append(head1.data)\n head1 = head1.next\n while head2:\n l.append(head2.data)\n head2 = head2.next\n l = list(set(l))\n l.sort()\n a = Node(-1)\n t = a\n for i in l:\n t.next = Node(i)\n t = t.next\n return a.next", "def union(head1, head2):\n l = set()\n while head1 or head2:\n if head1:\n l.add(head1.data)\n head1 = head1.next\n if head2:\n l.add(head2.data)\n head2 = head2.next\n l = sorted(l)\n temp = Node(l[0])\n curr = temp\n i = 1\n while i < len(l):\n temp.next = Node(l[i])\n temp = temp.next\n i += 1\n return curr", "def union(head1, head2):\n p1 = head1\n p2 = head2\n myList = [p1.data, p2.data]\n while p1.next:\n myList.append(p1.next.data)\n p1 = p1.next\n while p2.next:\n myList.append(p2.next.data)\n p2 = p2.next\n myList = sorted(list(set(myList)))\n head3 = Node(myList[0])\n p3 = head3\n for i in range(1, len(myList)):\n p3.next = Node(myList[i])\n p3 = p3.next\n return head3", "def union(head1, head2):\n a = []\n b = head1\n h = head2\n while b:\n a.append(b.data)\n b = b.next\n while h:\n a.append(h.data)\n h = h.next\n r = [i for i in set(a)]\n r.sort()\n t = y = Node(r[0])\n for i in range(1, len(r)):\n t.next = Node(r[i])\n t = t.next\n return y", "def union(head1, head2):\n a = []\n tmp = head1\n while tmp:\n a.append(tmp.data)\n tmp = tmp.next\n tmp2 = head2\n while tmp2:\n a.append(tmp2.data)\n tmp2 = tmp2.next\n a.sort()\n a = set(a)\n h = None\n hh = None\n for i in sorted(a):\n if not h:\n h = Node(i)\n hh = h\n else:\n h.next = Node(i)\n h = h.next\n return hh", "def union(head1, head2):\n setti = set()\n while head1:\n setti.add(head1.data)\n head1 = head1.next\n while head2:\n setti.add(head2.data)\n head2 = head2.next\n head = Node(0)\n start = head\n for item in sorted(setti):\n head.next = Node(item)\n head = head.next\n return start.next", "def union(head1, head2):\n s = set()\n p = head1\n while p != None:\n if p.data not in s:\n s.add(p.data)\n p = p.next\n p = head2\n while p != None:\n if p.data not in s:\n s.add(p.data)\n p = p.next\n l = list(s)\n l.sort()\n head = None\n for i in l:\n temp = Node(i)\n if head == None:\n head = temp\n p = head\n else:\n p.next = temp\n p = temp\n return head", "def union(head1, head2):\n us = set()\n us2 = set()\n ptr = head1\n ptr2 = head2\n while ptr is not None:\n us.add(ptr.data)\n ptr = ptr.next\n while ptr2 is not None:\n us2.add(ptr2.data)\n ptr2 = ptr2.next\n l = us.union(us2)\n l = list(l)\n l.sort()\n head3 = None\n for i in range(len(l)):\n if i == 0:\n head3 = Node(l[i])\n ptr = head3\n else:\n extra = Node(l[i])\n ptr.next = extra\n ptr = extra\n return head3", "def union(head1, head2):\n l = set()\n if head1:\n temp1 = head1\n while temp1:\n l.add(temp1.data)\n temp1 = temp1.next\n if head2:\n temp2 = head2\n while temp2:\n l.add(temp2.data)\n temp2 = temp2.next\n s = list(l)\n s.sort()\n head = None\n tail = None\n while s:\n a = s.pop(0)\n n = Node(a)\n if head == None:\n head = n\n tail = n\n else:\n tail.next = n\n tail = tail.next\n return head", "def length(head):\n itr = head\n a = []\n while itr:\n a.append(itr.data)\n itr = itr.next\n return a\n\ndef join_linked_list(h1, h2):\n if h1 == None and h2 == None:\n return None\n if h1 == None:\n return h2\n if h2 == None:\n return h1\n temp = None\n if h1.data < h2.data:\n temp = h1\n temp.next = union(h1.next, h2)\n elif h2.data < h1.data:\n temp = h2\n temp.next = union(h1, h2.next)\n elif h1.data == h2.data:\n temp = h1\n temp.next = union(h1.next, h2.next)\n return temp\n\ndef sorting_linked_list(head):\n a = []\n itr = head\n while itr:\n a.append(itr.data)\n itr = itr.next\n a = list(set(a))\n a.sort()\n return list_to_linked_list(a)\n\ndef list_to_linked_list(a):\n n = len(a)\n head = None\n for i in range(n - 1, -1, -1):\n new = Node(a[i])\n new.next = head\n head = new\n return head\n\ndef union(h1, h2):\n h1 = sorting_linked_list(h1)\n h2 = sorting_linked_list(h2)\n return join_linked_list(h1, h2)\n return h2", "def union(head1, head2):\n\n def data(head):\n temp = head\n d = list()\n while temp:\n d.append(temp.data)\n temp = temp.next\n return d\n d1 = data(head1)\n d2 = data(head2)\n d = list(set(d1 + d2))\n d.sort()\n head = Node(0)\n curr = head\n for i in d:\n curr.next = Node(i)\n curr = curr.next\n return head.next", "def union(head1, head2):\n arr = set()\n cur1 = head1\n cur2 = head2\n while cur1:\n arr.add(cur1.data)\n cur1 = cur1.next\n while cur2:\n arr.add(cur2.data)\n cur2 = cur2.next\n arr = list(arr)\n arr.sort()\n head = Node(0)\n cur = head\n for i in range(len(arr)):\n cur.next = Node(arr[i])\n cur = cur.next\n return head.next"], "starter_code": "def union(head1,head2):\n", "input_output": {"inputs": ["L1 = 9->6->4->2->3->8\nL2 = 1->2->8->6->2", "L1 = 1->5->1->2->2->5\nL2 = 4->5->6->7->1"], "outputs": ["1 2 3 4 6 8 9", "1 2 4 5 6 7"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Hash", "Sorting", "Linked List", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/union-of-two-linked-list/1", "Expected Auxiliary Space": "O(N+M)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O((N+M)*Log(N+M))", "entry_point": "union", "task_id": "TACO_lite/459", "example": [[], []]} +{"requirement": "- Kids drink toddy.\n- Teens drink coke.\n- Young adults drink beer.\n- Adults drink whisky.\n\nMake a function that receive age, and return what they drink.\n\n**Rules:**\n\n- Children under 14 old.\n- Teens under 18 old.\n- Young under 21 old.\n- Adults have 21 or more.\n\n**Examples:**\n\n```python\npeople_with_age_drink(13) == \"drink toddy\"\npeople_with_age_drink(17) == \"drink coke\"\npeople_with_age_drink(18) == \"drink beer\"\npeople_with_age_drink(20) == \"drink beer\"\npeople_with_age_drink(30) == \"drink whisky\"\n```", "solutions": ["def people_with_age_drink(age):\n if age > 20:\n return 'drink whisky'\n if age > 17:\n return 'drink beer'\n if age > 13:\n return 'drink coke'\n return 'drink toddy'", "def people_with_age_drink(age):\n if age <= 13:\n beverage = 'toddy'\n elif age > 13 and age <= 17:\n beverage = 'coke'\n elif age > 17 and age <= 20:\n beverage = 'beer'\n elif age > 20:\n beverage = 'whisky'\n return 'drink ' + beverage", "def people_with_age_drink(age):\n return 'drink ' + ('toddy' if age < 14 else 'coke' if age < 18 else 'beer' if age < 21 else 'whisky')", "def people_with_age_drink(age):\n for a in [[21, 'whisky'], [18, 'beer'], [14, 'coke'], [0, 'toddy']]:\n if age >= a[0]:\n return 'drink {0}'.format(a[1])", "people_with_age_drink = lambda a, d=['toddy', 'coke', 'beer', 'whisky']: 'drink ' + d[(a > 13) + (a > 17) + (a > 20)]", "def people_with_age_drink(age):\n dic = {tuple(range(0, 14)): 'drink toddy', tuple(range(14, 18)): 'drink coke', tuple(range(18, 21)): 'drink beer'}\n return dic.get(max((i if age in i else (0, 0) for i in dic)), 'drink whisky')", "def people_with_age_drink(age):\n return 'drink toddy' * (age < 14) or 'drink coke' * (age < 18) or 'drink beer' * (age < 21) or 'drink whisky'", "def people_with_age_drink(age):\n drinks = {1: 'drink toddy', 2: 'drink coke', 3: 'drink beer', 4: 'drink whisky'}\n return drinks[1] if age < 14 else drinks[2] if age < 18 else drinks[3] if age < 21 else drinks[4]", "def people_with_age_drink(age):\n drinks = {age < 14: 'toddy', 14 <= age < 18: 'coke', 18 <= age < 21: 'beer', age >= 21: 'whisky'}\n return 'drink {}'.format(drinks[True])", "def people_with_age_drink(age):\n return 'drink %s' % ('toddy' if age < 14 else 'coke' if 13 < age < 18 else 'beer' if 17 < age < 21 else 'whisky')", "drinks = [('whisky', 21), ('beer', 18), ('coke', 14)]\n\ndef people_with_age_drink(age):\n return 'drink ' + next((drink for (drink, age_limit) in drinks if age >= age_limit), 'toddy')", "def people_with_age_drink(age):\n return 'drink ' + next((d for (a, d) in [(21, 'whisky'), (18, 'beer'), (14, 'coke'), (0, 'toddy')] if age >= a))", "def people_with_age_drink(age):\n if age < 14:\n return 'drink toddy'\n elif age >= 14 and age < 18:\n return 'drink coke'\n elif age >= 18 and age < 21:\n return 'drink beer'\n else:\n return 'drink whisky'\n return 'ERROR....WRONG INPUT'", "people_with_age_drink = lambda n: 'drink %s' % ('toddy' if n < 14 else 'coke' if n < 18 else 'beer' if n < 21 else 'whisky')", "def people_with_age_drink(age: int) -> str:\n return f\"drink {('toddy' if age < 14 else 'coke' if age < 18 else 'beer' if age < 21 else 'whisky')}\"", "def people_with_age_drink(age):\n for (lim, drink) in [(14, 'toddy'), (18, 'coke'), (21, 'beer'), (float('inf'), 'whisky')]:\n if age < lim:\n return 'drink ' + drink", "def people_with_age_drink(age):\n return ['drink toddy', 'drink coke', 'drink beer', 'drink whisky'][(age >= 21) + (age > 17) + (age > 13)]", "from bisect import bisect\n\ndef people_with_age_drink(age):\n r = {0: 'drink toddy', 1: 'drink coke', 2: 'drink beer', 3: 'drink whisky'}\n return r[bisect([14, 18, 21], age)]", "people_with_age_drink = lambda a: 'drink ' + ('toddy' if a < 14 else 'coke' if a < 18 else 'beer' if a < 21 else 'whisky')", "def people_with_age_drink(age):\n return 'drink ' + ('toddy', 'coke', 'beer', 'whisky')[sum((not age < x for x in (14, 18, 21)))]", "def people_with_age_drink(age):\n for (limit, drink) in [(14, 'toddy'), (18, 'coke'), (21, 'beer')]:\n if age < limit:\n return 'drink ' + drink\n return 'drink whisky'", "def people_with_age_drink(age):\n drink = ''\n if age < 14:\n drink = 'drink toddy'\n elif age < 18 and age > 13:\n drink = 'drink coke'\n elif age < 21 and age > 17:\n drink = 'drink beer'\n else:\n drink = 'drink whisky'\n return drink", "def people_with_age_drink(age):\n if age < 14:\n return 'drink toddy'\n if age > 13 and age < 18:\n return 'drink coke'\n if age > 17 and age < 21:\n return 'drink beer'\n if age > 20:\n return 'drink whisky'", "def people_with_age_drink(age):\n if age >= 21:\n return 'drink whisky'\n elif age in range(18, 21):\n return 'drink beer'\n elif age in range(14, 18):\n return 'drink coke'\n elif age in range(0, 14):\n return 'drink toddy'", "drink_pairs = {'kid': 'toddy', 'teen': 'coke', 'youngAdult': 'beer', 'adult': 'whisky'}\n\ndef people_with_age_drink(age):\n if age >= 21:\n return 'drink ' + drink_pairs['adult']\n elif age < 21 and age >= 18:\n return 'drink ' + drink_pairs['youngAdult']\n elif age < 18 and age >= 14:\n return 'drink ' + drink_pairs['teen']\n else:\n return 'drink ' + drink_pairs['kid']", "def people_with_age_drink(age):\n if age <= 13:\n return 'drink toddy'\n elif age < 18 > 13:\n return 'drink coke'\n elif age < 21 > 17:\n return 'drink beer'\n elif age >= 21:\n return 'drink whisky'\n else:\n pass", "def people_with_age_drink(age):\n res = 'drink {}'\n if age < 14:\n return res.format('toddy')\n elif age < 18:\n return res.format('coke')\n elif age < 21:\n return res.format('beer')\n return res.format('whisky')", "def people_with_age_drink(age):\n if not age > 13:\n return 'drink toddy'\n elif age > 13 and (not age >= 18):\n return 'drink coke'\n elif age >= 18 and (not age > 20):\n return 'drink beer'\n else:\n return 'drink whisky'", "def people_with_age_drink(age):\n if age >= 0 and age < 14:\n return 'drink toddy'\n elif age < 18:\n return 'drink coke'\n elif age < 21:\n return 'drink beer'\n elif age >= 21:\n return 'drink whisky'\n else:\n return 'not a meaningful age'", "def people_with_age_drink(age):\n result = ''\n if age < 14:\n result = 'drink toddy'\n if age >= 14 and age < 18:\n result = 'drink coke'\n if age >= 18 and age <= 21:\n result = 'drink beer'\n if age >= 21:\n result = 'drink whisky'\n return result", "def people_with_age_drink(age):\n (a, b, c) = (14, 18, 21)\n if age < a:\n return 'drink toddy'\n if a <= age < b:\n return 'drink coke'\n if b <= age < c:\n return 'drink beer'\n if age >= c:\n return 'drink whisky'", "def people_with_age_drink(age):\n if age < 14:\n return 'drink toddy'\n if age >= 14 and age <= 17:\n return 'drink coke'\n if age >= 18 and age <= 20:\n return 'drink beer'\n else:\n return 'drink whisky'", "def people_with_age_drink(age):\n drinks = {'Children': 'drink toddy', 'Teens': 'drink coke', 'Young': 'drink beer', 'Adults': 'drink whisky'}\n if age < 14:\n return drinks['Children']\n if age < 18:\n return drinks['Teens']\n if age < 21:\n return drinks['Young']\n if age >= 21:\n return drinks['Adults']", "def people_with_age_drink(age: int) -> str:\n drink_rule = {age < 14: 'toddy', 14 <= age < 18: 'coke', 18 <= age < 21: 'beer', age >= 21: 'whisky'}\n return f'drink {drink_rule[True]}'", "def people_with_age_drink(age):\n drinks = {'toddy': range(14), 'coke': range(14, 18), 'beer': range(18, 21), 'whisky': range(21, 999)}\n for (key, age_range) in drinks.items():\n if age in age_range:\n return f'drink {key}'", "def people_with_age_drink(age):\n kids_age = range(0, 14)\n teens_age = range(14, 18)\n youngadults_age = range(18, 21)\n if age in kids_age:\n return 'drink toddy'\n elif age in teens_age:\n return 'drink coke'\n elif age in youngadults_age:\n return 'drink beer'\n else:\n return 'drink whisky'", "def people_with_age_drink(age):\n s = ''\n if age > 20:\n s = 'whisky'\n if age < 21:\n s = 'beer'\n if age < 18:\n s = 'coke'\n if age < 14:\n s = 'toddy'\n return 'drink ' + s", "def people_with_age_drink(age):\n drinks = {'14': 'drink toddy', '18': 'drink coke', '21': 'drink beer', '100': 'drink whisky'}\n for key in drinks:\n if age < int(key):\n return drinks[key]", "people_with_age_drink = lambda a: f\"drink {a < 14 and 'toddy' or (a < 18 and 'coke') or (a < 21 and 'beer') or 'whisky'}\"", "def people_with_age_drink(age):\n if age <= 13:\n return 'drink toddy'\n elif age <= 17:\n return 'drink coke'\n elif age == 18 or age <= 20:\n return 'drink beer'\n elif age > 20:\n return 'drink whisky'", "def people_with_age_drink(age):\n switcher = {1: 'drink toddy', 2: 'drink coke', 3: 'drink beer', 4: 'drink whisky'}\n if age < 14:\n return switcher.get(1, None)\n elif 14 <= age < 18:\n return switcher.get(2, None)\n elif 18 <= age < 21:\n return switcher.get(3, None)\n elif 21 <= age:\n return switcher.get(4, None)", "def people_with_age_drink(age: int) -> str:\n DRINK_TABLE = ((21, 'whisky'), (18, 'beer'), (14, 'coke'), (0, 'toddy'))\n for (limit, drink) in DRINK_TABLE:\n if age >= limit:\n return f'drink {drink}'\n return 'no drink'", "def people_with_age_drink(age):\n if age < 14:\n return 'drink toddy'\n elif 14 <= age <= 17:\n return 'drink coke'\n elif 17 < age < 21:\n return 'drink beer'\n else:\n return 'drink whisky'", "def people_with_age_drink(age):\n j = True\n if age < 14:\n j = 'drink toddy'\n elif age < 18:\n j = 'drink coke'\n elif age < 21:\n j = 'drink beer'\n elif age >= 21:\n j = 'drink whisky'\n return j", "def people_with_age_drink(age):\n if age < 14:\n return 'drink toddy'\n elif age < 18 and age > 0:\n return 'drink coke'\n elif age < 21 and age > 0:\n return 'drink beer'\n elif age >= 21 and age > 0:\n return 'drink whisky'", "def people_with_age_drink(age):\n if age < 14:\n drink = 'toddy'\n elif 14 <= age <= 17:\n drink = 'coke'\n elif 18 <= age <= 20:\n drink = 'beer'\n else:\n drink = 'whisky'\n return 'drink {}'.format(drink)"], "starter_code": "def people_with_age_drink(age):\n", "input_output": {"fn_name": "people_with_age_drink", "inputs": [[13], [0], [17], [15], [14], [20], [18], [22], [21]], "outputs": [["drink toddy"], ["drink toddy"], ["drink coke"], ["drink coke"], ["drink coke"], ["drink beer"], ["drink beer"], ["drink whisky"], ["drink whisky"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56170e844da7c6f647000063", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "people_with_age_drink", "task_id": "TACO_lite/445", "example": [[], []]} +{"requirement": "Implement a method that accepts 3 integer values a, b, c. The method should return true if a triangle can be built with the sides of given length and false in any other case.\n\n(In this case, all triangles must have surface greater than 0 to be accepted).", "solutions": ["def is_triangle(a, b, c):\n return a < b + c and b < a + c and (c < a + b)", "def is_triangle(a, b, c):\n (a, b, c) = sorted([a, b, c])\n return a + b > c", "def is_triangle(a, b, c):\n if a <= 0 | b <= 0 | c <= 0:\n return False\n elif a + b <= c or a + c <= b or b + c <= a:\n return False\n else:\n return True", "def is_triangle(a, b, c):\n return abs(a - b) < c < a + b", "def is_triangle(a, b, c):\n s = [a, b, c]\n for i in s:\n if sum(s) - i <= i:\n return False\n return True", "def is_triangle(a, b, c):\n return 2 * max(a, b, c) < a + b + c", "def is_triangle(a, b, c):\n if a + b <= c or a + c <= b or b + c <= a:\n return False\n else:\n return True", "def is_triangle(a, b, c):\n return all([a + b > c, a + c > b, b + c > a])", "def is_triangle(a, b, c):\n if a + b + c == 0:\n return False\n if a + b <= c:\n return False\n if a + c <= b:\n return False\n if b + c <= a:\n return False\n return True", "def is_triangle(a, b, c):\n if a <= 0 or b <= 0 or c <= 0:\n return False\n sum = a + b + c\n if fits(sum, max(a, b, c)):\n return True\n return False\n\ndef fits(sum, a):\n return sum - a > a", "is_triangle = lambda _, a, b: sum(sorted([_, a, b])[:2]) > sorted([_, a, b])[2]", "def is_triangle(a, b, c):\n sides = [a, b, c]\n max_side = max(sides)\n if sum(sides) - max_side > max_side:\n return True\n else:\n return False", "def is_triangle(a, b, c):\n s = a + b + c\n if s - max(a, b, c) > max(a, b, c):\n return True\n return False", "def is_triangle(a, b, c):\n cond1 = a + b > c\n cond2 = b + c > a\n cond3 = a + c > b\n list = [cond1, cond2, cond3]\n if False in list:\n return False\n return True", "def is_triangle(x, y, z):\n return x < y + z and y < x + z and (z < x + y)", "def is_triangle(a, b, c):\n t1 = a + b > c\n t2 = a + c > b\n t3 = b + c > a\n return t1 and t2 and t3", "def is_triangle(*sides):\n return sum(sorted(sides)[:2]) > max(sides)", "def is_triangle(a, b, c):\n max_number = max([a, b, c])\n if sum([a, b, c]) - max_number > max_number:\n return True\n return False", "def is_triangle(a, b, c):\n if a > 0 and b > 0 and (c > 0):\n if a + b > c and a + c > b and (c + b > a):\n return True\n else:\n return False\n return False", "def is_triangle(a, b, c):\n llist = [a, b, c]\n llist.sort()\n highest = llist[2]\n sumrest = llist[0] + llist[1]\n if highest < sumrest:\n return True\n return False", "def is_triangle(a, b, c):\n if a + b > c and a + c > b and (b + c > a):\n return True\n return False", "def is_triangle(a, b, c):\n lst = [int(a), int(b), int(c)]\n lst = sorted(lst)\n if lst[0] + lst[1] > lst[2]:\n return True\n else:\n return False", "def is_triangle(a, b, c):\n max_int = max(a, b, c)\n min_int = min(a, b, c)\n if max_int == a:\n sum = b + c\n if sum > a:\n return True\n if max_int == b:\n sum = a + c\n if sum > b:\n return True\n if max_int == c:\n sum = a + b\n if sum > c:\n return True\n return False", "def is_triangle(a, b, c):\n if a == None or b == None or c == None:\n return False\n l_tri = sorted([a, b, c])\n if l_tri[2] >= l_tri[0] + l_tri[1]:\n return False\n return True", "def is_triangle(a, b, c):\n tab_coter = [a, b, c]\n tab_coter.sort()\n calc_long_coter = tab_coter[0] + tab_coter[1]\n if tab_coter[2] < calc_long_coter:\n return True\n return False", "def is_triangle(a, b, c):\n s = sorted([a, b, c])\n return False if s[0] < 1 or sum(s[:-1]) <= s[2] else True", "def is_triangle(a, b, c):\n lts = [a, b, c]\n lts.sort()\n return lts[2] < lts[1] + lts[0]", "def is_triangle(a, b, c):\n triangleList = [a, b, c]\n triangleList.sort()\n if triangleList[0] + triangleList[1] > triangleList[2]:\n return True\n else:\n return False", "def is_triangle(a, b, c):\n out = []\n out.append(a)\n out.append(b)\n out.append(c)\n out.sort()\n if out[2] >= out[0] + out[1]:\n return False\n else:\n return True", "def is_triangle(a, b, c):\n if 2 * max([a, b, c]) < a + b + c:\n return True\n else:\n return False", "def is_triangle(a, b, c):\n return a + b > c and b + c > a and (c + a > b) and (a > 0) and (b > 0) and (c > 0)\n return False", "def is_triangle(a, b, c):\n listOfSides = [a, b, c]\n if max(listOfSides) >= sum(listOfSides) - max(listOfSides):\n return False\n return True", "def is_triangle(a, b, c):\n sum = a + b + c\n for side in (a, b, c):\n if sum - side <= side:\n return False\n return True", "def is_triangle(a, b, c):\n x = max(a, b, c)\n for i in (a, b, c):\n if x == i and x < a + b + c - i:\n return True\n return False", "def is_triangle(a, b, c):\n if a + b > c and abs(a - b) < c:\n return True\n elif a + c > b and abs(a - c) < b:\n return True\n elif b + c > a and abs(b - c) < a:\n return True\n else:\n return False", "def is_triangle(a, b, c):\n if a > 0 and b > 0 and (c > 0):\n reference = sorted([a, b, c])\n if reference[2] < reference[0] + reference[1]:\n return True\n else:\n return False\n else:\n return False", "def is_triangle(a, b, c):\n if any((side <= 0 for side in (a, b, c))):\n return False\n sides = sorted([a, b, c])\n if sides[0] + sides[1] <= sides[2]:\n return False\n return True", "def is_triangle(a, b, c):\n v = [a, b, c]\n m = max(v)\n v.remove(m)\n return m < sum(v)", "def is_triangle(a, b, c):\n my_flag = False\n if a + b > c and c + b > a and (a + c > b):\n my_flag = True\n else:\n my_flag = False\n return my_flag", "def is_triangle(a, b, c):\n result = ''\n if a + b <= c:\n result = False\n elif a + c <= b:\n result = False\n elif b + c <= a:\n result = False\n else:\n result = True\n return result", "import math\n\ndef is_triangle(a, b, c):\n sides = (a, b, c)\n if sorted(sides)[-1] >= sorted(sides)[0] + sorted(sides)[1]:\n return False\n return True", "def is_triangle(a, b, c):\n table = [a, b, c]\n table.sort()\n return table[0] + table[1] > table[2]", "def is_triangle(a, b, c):\n if sum([a, b]) > c and sum([b, c]) > a and (sum([a, c]) > b):\n return True\n else:\n return False", "def is_triangle(a, b, c):\n if a == 0 or b == 0 or c == 0:\n return 0\n if a + b <= c or b + c <= a or a + c <= b:\n return 0\n else:\n return 1", "def is_triangle(a, b, c):\n list_ = [a, b, c]\n if sorted(list_)[0] + sorted(list_)[1] > sorted(list_)[2]:\n if sorted(list_)[0] > 0 and sorted(list_)[1] > 0 and (sorted(list_)[2] > 0):\n return True\n return False", "def is_triangle(a, b, c):\n x = a + b\n y = b + c\n z = a + c\n if x > c and y > a and (z > b):\n return True\n else:\n return False", "def is_triangle(a, b, c):\n if (a or b or c) < 0:\n return False\n v = list()\n v.append(a)\n v.append(b)\n v.append(c)\n v.sort()\n _a = v.pop()\n _b = v.pop()\n _c = v.pop()\n if _a < _b + _c:\n return True\n if _a == _b + _c:\n return False\n return False", "def is_triangle(a, b, c):\n x = max(a, b, c)\n lista = [a, b, c]\n lista.remove(x)\n if x < sum(lista):\n return True\n else:\n return False", "def is_triangle(a, b, c):\n k = [a + b > c, a + c > b, b + c > a]\n return not False in k", "def is_triangle(a, b, c):\n sides = [a, b, c]\n a = max(sides)\n sides.remove(a)\n if sum(sides) > a:\n return True\n return False", "def is_triangle(a, b, c):\n result = False\n if a + b > c:\n if a + c > b:\n if c + b > a:\n result = True\n return result", "def is_triangle(a, b, c):\n biggest_arg = max([a, b, c])\n return True if biggest_arg < sum([a, b, c]) - biggest_arg else False", "def is_triangle(a, b, c):\n mylist = [a, b, c]\n mylist = sorted(mylist)\n if mylist[0] < mylist[1] + mylist[2]:\n if mylist[1] < mylist[0] + mylist[2]:\n if mylist[2] < mylist[0] + mylist[1]:\n return True\n return False", "def is_triangle(a, b, c):\n sides = (a, b, c)\n sides = sorted(sides)\n c = sides[-1]\n b = sides[1]\n a = sides[0]\n return c < a + b", "def is_triangle(a, b, c):\n a = sorted([a, b, c])\n return a[2] < a[0] + a[1]"], "starter_code": "def is_triangle(a, b, c):\n", "input_output": {"fn_name": "is_triangle", "inputs": [[1, 2, 2], [7, 2, 2], [1, 2, 3], [1, 3, 2], [3, 1, 2], [5, 1, 2], [1, 2, 5], [2, 5, 1], [4, 2, 3], [5, 1, 5], [2, 2, 2], [-1, 2, 3], [1, -2, 3], [1, 2, -3], [0, 2, 3]], "outputs": [[true], [false], [false], [false], [false], [false], [false], [false], [true], [true], [true], [false], [false], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/56606694ec01347ce800001b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_triangle", "task_id": "TACO_lite/361", "example": [[], []]} +{"requirement": "```\n*************************\n* Create a frame! *\n* __ __ *\n* / \\~~~/ \\ *\n* ,----( .. ) *\n* / \\__ __/ *\n* /| (\\ |( *\n* ^ \\ /___\\ /\\ | *\n* |__| |__|-.. *\n*************************\n```\n\nGiven an array of strings and a character to be used as border, output the frame with the content inside.\n\nNotes:\n\n* Always keep a space between the input string and the left and right borders.\n* The biggest string inside the array should always fit in the frame.\n* The input array is never empty.\n\n\n## Example\n\n`frame(['Create', 'a', 'frame'], '+')`\n\nOutput:\n```\n++++++++++\n+ Create +\n+ a +\n+ frame +\n++++++++++\n```", "solutions": ["def frame(text, char):\n text_lens = [len(x) for x in text]\n longest_len = max(text_lens)\n frame_list = [char * (longest_len + 4)]\n for str in text:\n frame_list.append('{} {}{} {}'.format(char, str, ' ' * (longest_len - len(str)), char))\n frame_list.append(char * (longest_len + 4))\n return '\\n'.join(frame_list)", "def frame(text, char):\n n = len(max(text, key=len)) + 4\n return '\\n'.join([char * n] + ['%s %s %s' % (char, line.ljust(n - 4), char) for line in text] + [char * n])", "def frame(lines, char):\n l = len(max(lines, key=len))\n row = char * (l + 4)\n body = '\\n'.join((f'{char} {line:<{l}s} {char}' for line in lines))\n return f'{row}\\n{body}\\n{row}'", "def frame(text, char):\n length = len(max(text, key=len))\n start = end = char * (length + 3)\n k = [' ' + x + ' ' * (length - len(x) + 1) for x in text]\n return (char + '\\n' + char).join([start] + k + [end])", "from itertools import chain\n\ndef frame(words, char):\n size = max(map(len, words))\n frame = [char * (size + 4)]\n middle = (f'{char} {word: <{size}} {char}' for word in words)\n return '\\n'.join(chain(frame, middle, frame))", "def frame(t, c):\n m = len(max(t, key=len))\n return c * (m + 4) + '\\n' + '\\n'.join([f'{c} {i:<{m}} {c}' for i in t]) + '\\n' + c * (m + 4)", "def frame(text, char):\n width = max([len(x) for x in text]) + 4\n a = '\\n'.join([char + ' ' + x + ' ' * (width - len(x) - 3) + char for x in text])\n return f'{char * width}\\n{a}\\n{char * width}'", "def frame(text, c):\n mx = max((len(w) for w in text))\n return '\\n'.join([c * (mx + 4)] + [c + ' ' + w.ljust(mx) + ' ' + c for w in text] + [c * (mx + 4)])", "def frame(text, char):\n max_length = max([len(word) for word in text])\n frame_words = [char + ' ' + word + (max_length - len(word) + 1) * ' ' + char for word in text]\n frame = char * (max_length + 4) + '\\n'\n for line in frame_words:\n frame = frame + line + '\\n'\n return frame + char * (max_length + 4)", "def frame(text, char):\n w = max(map(len, text))\n\n def f():\n yield (char * (w + 4))\n for line in text:\n yield f'{char} {line:<{w}} {char}'\n yield (char * (w + 4))\n return '\\n'.join(f())"], "starter_code": "def frame(text, char):\n", "input_output": {"fn_name": "frame", "inputs": [[["Small", "frame"], "~"], [["Create", "this", "kata"], "+"], [["This is a very long single frame"], "-"]], "outputs": [["~~~~~~~~~\n~ Small ~\n~ frame ~\n~~~~~~~~~"], ["++++++++++\n+ Create +\n+ this +\n+ kata +\n++++++++++"], ["------------------------------------\n- This is a very long single frame -\n------------------------------------"]]}, "difficulty": "EASY", "raw_tags": ["ASCII Art", "Strings", "Fundamentals", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5672f4e3404d0609ec00000a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "frame", "task_id": "TACO_lite/440", "example": [[], []]} +{"requirement": "Given a natural number N, find the count of numbers from 1 to N that have an odd number of divisors. \n \nExample 1:\nInput:\nN = 1\nOutput:\n1\nExplanation:\n1 has only one \ndivisor {1}.\n \nExample 2:\nInput:\nN = 4\nOutput:\n2\nExplanation:\n4 has an odd number \nof divisors {1, 2, 4}.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function oddNumberOfDivisor() which takes an integer N and returns the count of numbers from 1 to n that have an odd number of divisors. \n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= N <= 10^{6}", "solutions": ["def oddnumberofdivisor(ob, N):\n return int(N ** (1 / 2))", "def oddnumberofdivisor(ob, n):\n c = 0\n from math import sqrt\n for i in range(1, n + 1):\n s = sqrt(i)\n if s - int(s) == 0:\n c += 1\n return c", "import math\n\ndef oddnumberofdivisor(ob, N):\n count = 0\n for i in range(1, N + 1):\n s = math.sqrt(i)\n if s - int(s) == 0:\n count += 1\n return count", "import math\n\ndef oddnumberofdivisor(ob, N):\n return math.floor(N ** 0.5)", "def oddnumberofdivisor(ob, N):\n return int(N ** 0.5)"], "starter_code": "def oddnumberofdivisor (ob,N):\n", "input_output": {"inputs": ["N = 1", "N = 4"], "outputs": ["1", "2"]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/odd-divisors5347/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "oddnumberofdivisor", "task_id": "TACO_lite/430", "example": [[[1], [4]], ["1", "2"]]} +{"requirement": "Given an array arr[] of size N, check if it can be partitioned into two parts such that the sum of elements in both parts is the same.\nExample 1:\nInput: N = 4\narr = {1, 5, 11, 5}\nOutput: YES\nExplanation: \nThe two parts are {1, 5, 5} and {11}.\nExample 2:\nInput: N = 3\narr = {1, 3, 5}\nOutput: NO\nExplanation: This array can never be \npartitioned into two such parts.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function equalPartition() which takes the value N and the array as input parameters and returns 1 if the partition is possible. Otherwise, returns 0.\nExpected Time Complexity: O(N*sum of elements)\nExpected Auxiliary Space: O(N*sum of elements)\nConstraints:\n1 ≤ N ≤ 100\n1 ≤ arr[i] ≤ 1000\nN*sum of elements ≤ 5*10^{6}", "solutions": ["def equalpartition(N, arr):\n x = sum(arr)\n arr.sort()\n if x % 2 == 1:\n return 0\n else:\n sum1 = x // 2\n table = [[0 for _ in range(sum1 + 1)] for _ in range(N + 1)]\n table[0][0] = 1\n for i in range(1, N + 1):\n table[i][0] = 1\n for i in range(1, N + 1):\n for j in range(1, sum1 + 1):\n if arr[i - 1] > j + 1:\n table[i][j] = table[i - 1][j]\n else:\n table[i][j] = max(table[i - 1][j], table[i - 1][j - arr[i - 1]])\n return table[-1][-1]", "def equalpartition(N, arr):\n su = 0\n for q in range(len(arr)):\n su = su + arr[q]\n if su % 2 != 0:\n return 0\n su = int(su / 2)\n dp = [[-1 for m in range(su + 1)] for n in range(N + 1)]\n for a in range(su + 1):\n dp[0][a] = False\n for b in range(N + 1):\n dp[b][0] = True\n for i in range(1, N + 1):\n for j in range(1, su + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j - arr[i - 1]] or dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[N][su]", "def equalpartition(N, arr):\n if sum(arr) % 2 != 0:\n return False\n dp = set()\n dp.add(0)\n x = sum(arr) // 2\n for i in arr:\n temp = set()\n for j in dp:\n if j + i == x:\n return True\n temp.add(j + i)\n temp.add(j)\n dp = temp\n return False", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2 == 1:\n return 0\n l = s // 2\n dp = [0 for _ in range(l + 1)]\n for num in arr:\n if num > l:\n return 0\n for s in range(l, 0, -1):\n if dp[s] != 0 and s + num <= l:\n dp[s + num] += 1\n dp[num] += 1\n return 1 if dp[-1] >= 2 else 0", "def equalpartition(N, arr):\n total = sum(arr)\n r_total = total // 2\n dp = [[False for i in range(r_total + 1)] for j in range(N + 1)]\n if total % 2 == 1:\n return 0\n else:\n for i in range(N + 1):\n for j in range(r_total + 1):\n if j == 0:\n dp[i][j] = True\n for i in range(1, N + 1):\n for j in range(1, r_total + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]\n else:\n dp[i][j] = dp[i - 1][j]\n if dp[N][r_total] == False:\n return 0\n else:\n return 1", "def equalpartition(N, arr):\n total_sum = 0\n for n in arr:\n total_sum += n\n if total_sum % 2 == 1:\n return False\n else:\n sum = total_sum // 2\n n = N\n t = [[False for i in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n t[i][0] = True\n for i in range(sum + 1):\n t[0][i] = False\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if arr[i - 1] <= j:\n t[i][j] = t[i - 1][j - arr[i - 1]] or t[i - 1][j]\n else:\n t[i][j] = t[i - 1][j]\n return t[n][sum]", "def equalpartition(N, arr):\n total_sum = sum(arr)\n if total_sum % 2 != 0:\n return 0\n tgt = total_sum / 2\n n = len(arr)\n\n def solve(i, tgt):\n if tgt < 0:\n return 0\n if i >= len(arr):\n return 0\n if tgt == 0:\n return 1\n if solve(i + 1, tgt - arr[i]) == 1:\n return 1\n if solve(i + 1, tgt) == 1:\n return 1\n return solve(0, tgt)", "def equalpartition(N, arr):\n nums = arr\n n = len(nums)\n if sum(nums) % 2 != 0:\n return False\n target = sum(nums) // 2\n memo = [[-1 for j in range(target + 1)] for i in range(n)]\n\n def rec(ind, target):\n if target == 0:\n return True\n if target < 0 or ind < 0:\n return False\n if memo[ind][target] != -1:\n return memo[ind][target]\n tk = rec(ind - 1, target - nums[ind])\n notTk = rec(ind - 1, target)\n memo[ind][target] = tk or notTk\n return memo[ind][target]\n g = rec(n - 1, target)\n return 1 if g else 0", "def equalpartition(N, arr):\n total_sum = sum(arr)\n if total_sum % 2 != 0:\n return 0\n target_sum = total_sum // 2\n dp = [[False for _ in range(target_sum + 1)] for _ in range(N + 1)]\n for i in range(N + 1):\n dp[i][0] = True\n for j in range(1, target_sum + 1):\n dp[0][j] = False\n for i in range(1, N + 1):\n for j in range(1, target_sum + 1):\n if arr[i - 1] > j:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]\n return int(dp[N][target_sum])", "def equalpartition(N, arr):\n target = sum(arr)\n if target % 2 != 0:\n return False\n target = target // 2\n dp = [[-1 for i in range(target + 1)] for j in range(N)]\n\n def dfs(i, target):\n if target == 0:\n return True\n if i <= 0 or target < 0:\n return False\n if dp[i - 1][target] != -1:\n return dp[i - 1][target]\n dp[i - 1][target] = dfs(i - 1, target) or dfs(i - 1, target - arr[i - 1])\n return dp[i - 1][target]\n return dfs(N, target)", "def equalpartition(N, arr):\n s = sum(arr)\n if s & 1:\n return False\n s = s >> 1\n dp = [[False for i in range(s + 1)] for j in range(N + 1)]\n for i in range(N + 1):\n dp[i][0] = True\n for i in range(1, N + 1):\n for j in range(s + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[-1][-1]", "def equalpartition(N, arr):\n if sum(arr) % 2 != 0:\n return 0\n s = sum(arr) // 2\n w = s + 1\n l = []\n for i in range(N + 1):\n d = []\n for j in range(w):\n d.append(0)\n l.append(d)\n for i in range(N + 1):\n for j in range(w):\n if i == 0:\n l[i][j] = 0\n if j == 0:\n l[i][j] = 1\n for i in range(1, N + 1):\n for j in range(1, s + 1):\n if arr[i - 1] <= j:\n l[i][j] = l[i - 1][j - arr[i - 1]] or l[i - 1][j]\n else:\n l[i][j] = l[i - 1][j]\n return l[N][s]", "def equalpartition(N, arr):\n total = sum(arr)\n if total % 2 == 1:\n return False\n target = total // 2\n dp = [False] * (target + 1)\n dp[0] = True\n for num in arr:\n for i in range(target, num - 1, -1):\n if dp[i - num]:\n dp[i] = True\n if dp[-1]:\n return True\n return False", "def equalpartition(N, arr):\n total = sum(arr)\n if total % 2 == 1:\n return False\n arr.sort()\n\n def dp(required, idx):\n if required == 0:\n return True\n if idx == N or arr[idx] > required:\n return False\n return dp(required - arr[idx], idx + 1) or dp(required, idx + 1)\n return dp(total // 2, 0)", "def isSubsetSum(N, arr, sum):\n table = [[False for x in range(sum + 1)] for y in range(N + 1)]\n for i in range(N + 1):\n table[i][0] = True\n for i in range(1, N + 1):\n for j in range(1, sum + 1):\n table[i][j] = table[i - 1][j]\n if arr[i - 1] == j:\n table[i][j] = True\n elif arr[i - 1] < j:\n table[i][j] = table[i - 1][j] or table[i - 1][j - arr[i - 1]]\n else:\n table[i][j] = table[i - 1][j]\n return table[N][sum]\n\ndef equalpartition(N, arr):\n msum = sum(arr)\n if sum(arr) % 2 != 0:\n return 0\n if self.isSubsetSum(N, arr, sum(arr) // 2):\n return 1\n return 0", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2 == 1:\n return 0\n else:\n s = s // 2\n dp = []\n for i in range(N):\n dp.append([])\n for j in range(s + 1):\n dp[-1].append(0)\n for i in range(N):\n for j in range(s + 1):\n if j == arr[i]:\n dp[i][j] = 1\n elif i <= 0:\n dp[i][j] = 0\n else:\n t = 0\n if arr[i] <= j:\n t = dp[i - 1][j - arr[i]]\n dp[i][j] = max(dp[i - 1][j], t)\n return dp[-1][-1]", "def equalpartition(N, nums):\n if not nums:\n return True\n n = len(nums)\n if sum(nums) % 2 != 0:\n return False\n target = sum(nums) // 2\n memo = {}\n\n def helper(total, i):\n nonlocal nums, memo\n if (total, i) in memo:\n return memo[total, i]\n if i == len(nums):\n return False\n if total == 0:\n return True\n memo[total, i] = helper(total - nums[i], i + 1) or helper(total, i + 1)\n return memo[total, i]\n return helper(target, 0)", "def equalpartition(N, nums):\n sum_ = sum(nums)\n if sum_ % 2 != 0:\n return False\n half = sum_ // 2\n dp = [False] * (half + 1)\n dp[0] = True\n for el in nums:\n for j in range(half, el - 1, -1):\n if dp[j - el]:\n dp[j] = True\n return dp[half]", "def equalpartition(n, arr):\n ts = sum(arr)\n import sys\n sys.setrecursionlimit(10 ** 9 + 7)\n if ts > 0 and ts % 2 != 0:\n return False\n ts = ts // 2\n dp = [[-1 for j in range(ts + 1)] for j in range(n)]\n return self.solve(n - 1, ts, arr, dp)\n\ndef solve(i, j, arr, dp):\n if i == 0:\n return arr[i] == j\n if j == 0:\n dp[i][j] = True\n return True\n if dp[i][j] != -1:\n return dp[i][j]\n npick = self.solve(i - 1, j, arr, dp)\n pick = False\n if arr[i] <= j:\n pick = self.solve(i - 1, j - arr[i], arr, dp)\n dp[i][j] = pick or npick\n return dp[i][j]", "import numpy as np\n\ndef rec_sol(arr, Sum, N):\n if Sum == 0:\n return True\n if N == 0:\n return False\n if self.rec_sol(arr, Sum - arr[N - 1], N - 1) or self.rec_sol(arr, Sum, N - 1):\n return True\n return False\n\ndef mem_sol(arr, Sum, N, dp):\n if Sum == 0:\n return True\n if N == 0:\n return False\n if dp[N][Sum] != None:\n return dp[N][Sum]\n if self.mem_sol(arr, Sum - arr[N - 1], N - 1, dp) or self.mem_sol(arr, Sum, N - 1, dp):\n dp[N][Sum] = True\n return True\n dp[N][Sum] = False\n return False\n\ndef equalpartition(N, arr):\n tot = sum(arr)\n if tot % 2 == 1:\n return 0\n dp = np.array([[None] * (tot // 2 + 1)] * (N + 1))\n if self.mem_sol(arr, tot // 2, N, dp):\n return 1\n else:\n return 0", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2 != 0:\n return 0\n target = s // 2\n\n def fun(i, target):\n if i < 0:\n if target == 0:\n return True\n return False\n if arr[i] <= target:\n if fun(i - 1, target - arr[i]):\n return True\n if fun(i - 1, target):\n return True\n return False\n return fun(N - 1, target)", "def equalpartition(N, arr):\n key = 0\n for i in range(N):\n key += arr[i]\n if key % 2 == 1:\n return False\n else:\n return self.findSubsetSum(N, arr, key // 2, N - 1)\n\ndef findSubsetSum(N, arr, target, index):\n if target < 0:\n return False\n if target == 0:\n return True\n if index == 0:\n return arr[index] == target\n return self.findSubsetSum(N, arr, target - arr[index], index - 1) or self.findSubsetSum(N, arr, target, index - 1)", "def equalpartition(N, arr):\n sum = 0\n for i in arr:\n sum += i\n if sum % 2 != 0:\n return False\n sum = sum // 2\n K = [[0 for x in range(sum + 1)] for x in range(N + 1)]\n for i in range(N + 1):\n for j in range(sum + 1):\n if i == 0 and j == 0:\n K[i][j] = True\n if i == 0:\n K[i][j] = False\n if j == 0:\n K[i][j] = True\n elif arr[i - 1] <= j:\n K[i][j] = K[i - 1][j - arr[i - 1]] or K[i - 1][j]\n else:\n K[i][j] = K[i - 1][j]\n return K[N][sum]", "def equalpartition(N, arr):\n\n def f(arr, n, s):\n t = [[-1 for i in range(s + 1)] for i in range(N + 1)]\n return F(arr, n, s, t)\n\n def F(arr, N, s, t):\n if N == 0 and s != 0:\n return 0\n if s == 0:\n return 1\n if t[N][s] != -1:\n return t[N][s]\n if arr[N - 1] > s:\n t[N][s] = F(arr, N - 1, s, t)\n else:\n t[N][s] = F(arr, N - 1, s - arr[N - 1], t) or F(arr, N - 1, s, t)\n return t[N][s]\n S = sum(arr)\n if S % 2 != 0:\n return 0\n else:\n return f(arr, N, S // 2)", "def equalpartition(N, arr):\n\n def partitionSum(arr, startIndex, target, dp):\n if startIndex >= len(arr) or target < 0:\n return False\n if target == 0:\n return True\n if dp[startIndex + 1][target - arr[startIndex]] == -1:\n s1 = partitionSum(arr, startIndex + 1, target - arr[startIndex], dp)\n dp[startIndex + 1][target - arr[startIndex]] = s1\n else:\n s1 = dp[startIndex + 1][target - arr[startIndex]]\n if dp[startIndex][target] == -1:\n s2 = partitionSum(arr, startIndex + 1, target, dp)\n dp[startIndex][target] = s2\n else:\n s2 = dp[startIndex][target]\n return s1 or s2\n n = len(arr)\n target = sum(arr)\n subsetSum = target // 2\n dp = [[-1 for i in range(subsetSum + 1)] for j in range(n + 1)]\n if target % 2 != 0:\n return False\n else:\n return partitionSum(arr, 0, subsetSum, dp)", "def equalpartition(N, arr):\n arr.sort()\n sum_arr = sum(arr)\n if sum_arr % 2 != 0:\n return 0\n target_sum = sum_arr // 2\n subset_sums = set([0])\n for num in arr:\n for s in subset_sums.copy():\n if s + num == target_sum:\n return 1\n elif s + num < target_sum:\n subset_sums.add(s + num)\n return 0", "def subsetSumUtil(ind, target, arr, dp):\n if target == 0:\n return True\n if ind == 0:\n return arr[0] == target\n if dp[ind][target] != -1:\n return dp[ind][target]\n notTaken = subsetSumUtil(ind - 1, target, arr, dp)\n taken = False\n if arr[ind] <= target:\n taken = subsetSumUtil(ind - 1, target - arr[ind], arr, dp)\n dp[ind][target] = notTaken or taken\n return dp[ind][target]\n\ndef equalpartition(n, arr):\n totSum = sum(arr)\n if totSum % 2 == 1:\n return False\n else:\n k = totSum // 2\n dp = [[-1 for i in range(k + 1)] for j in range(n)]\n return subsetSumUtil(n - 1, k, arr, dp)", "def equalpartition(N, arr):\n Sum = 0\n for i in range(N):\n Sum += arr[i]\n if Sum % 2 != 0:\n return False\n target = Sum // 2\n return self.solveTab(arr, target)\n\ndef solveTab(arr, target):\n dp = [[False for j in range(target + 1)] for i in range(len(arr) + 1)]\n for i in range(len(arr) + 1):\n dp[i][0] = True\n for indx in range(len(arr) - 1, -1, -1):\n for t in range(target + 1):\n include = False\n if t - arr[indx] >= 0:\n include = dp[indx + 1][t - arr[indx]]\n exclude = dp[indx + 1][t]\n dp[indx][t] = include or exclude\n return dp[0][target]", "def solve(index, arr, N, target, dp):\n if index >= N:\n return False\n if target < 0:\n return False\n if target == 0:\n return True\n if dp[index][target] != -1:\n return dp[index][target]\n include = solve(index + 1, arr, N, target - arr[index], dp)\n exclude = solve(index + 1, arr, N, target, dp)\n dp[index][target] = include or exclude\n return dp[index][target]\n\ndef equalpartition(N, arr):\n total = sum(arr)\n if total % 2 != 0:\n return False\n target = total // 2\n dp = [[-1 for j in range(target + 1)] for i in range(N)]\n return solve(0, arr, N, target, dp)", "def equalpartition(N, arr):\n sm = sum(arr)\n if sm % 2:\n return 0\n stateMap = {0: True}\n llimit = max(arr)\n for elem in arr:\n currMap = {}\n for k in stateMap:\n if k + elem <= sm // 2:\n currMap[k + elem] = True\n if k - elem >= -llimit:\n currMap[k - elem] = True\n stateMap = currMap\n return 1 if stateMap.get(0) else 0", "def equalpartition(N, arr):\n if sum(arr) % 2 != 0:\n return 0\n else:\n mid_sum = sum(arr) // 2\n res = [[0 for _ in range(mid_sum + 1)] for x in range(N + 1)]\n for i in range(N + 1):\n for j in range(mid_sum + 1):\n if i == 0:\n res[i][j] = False\n if j == 0:\n res[i][j] = True\n for i in range(1, N + 1):\n for j in range(1, mid_sum + 1):\n if arr[i - 1] <= j:\n res[i][j] = res[i - 1][j - arr[i - 1]] or res[i - 1][j]\n else:\n res[i][j] = res[i - 1][j]\n if res[N][mid_sum]:\n return 1\n else:\n return 0", "def equalpartition(N, arr):\n total = sum(arr)\n s = 0\n if total % 2 != 0:\n return False\n\n def dfs(i, s):\n if s == total // 2:\n return True\n if s != total // 2 and i == len(arr):\n return\n if s > total // 2:\n return\n for j in range(i, len(arr)):\n s += arr[j]\n if dfs(j + 1, s):\n return True\n s -= arr[j]\n if dfs(0, s):\n return True\n else:\n return False", "def knapsack(arr, N, W):\n dp = [[0 for _ in range(W + 1)] for _ in range(N + 1)]\n for i in range(1, N + 1):\n for w in range(W + 1):\n ele_not_present = dp[i - 1][w]\n ele_present = 0\n if w - arr[i - 1] >= 0:\n ele_present = dp[i - 1][w - arr[i - 1]] + arr[i - 1]\n dp[i][w] = max(ele_not_present, ele_present)\n return dp\n\ndef equalpartition(N, arr):\n total_sum = sum(arr)\n if total_sum % 2 != 0:\n return False\n half_sum = total_sum // 2\n dp = self.knapsack(arr, N, half_sum)\n if dp[N][half_sum] != half_sum:\n return False\n return True", "def equalpartition(N, arr):\n sm = 0\n for i in arr:\n sm += i\n if sm % 2 != 0 or sm == 0:\n return False\n sm = sm // 2\n dp = [[True for i in range(sm + 1)] for j in range(N + 1)]\n for i in range(sm + 1):\n dp[0][i] = False\n for i in range(1, N + 1):\n for j in range(1, sm + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j - arr[i - 1]] or dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[i][j]", "def equalpartition(N, arr):\n totSum = sum(arr)\n if totSum % 2 == 1:\n return False\n else:\n k = totSum // 2\n dp = [[-1 for i in range(k + 1)] for j in range(N)]\n return self.solve(N - 1, k, arr, dp)\n\ndef solve(idx, _t, arr, dp):\n if _t == 0:\n return True\n if idx == 0:\n return arr[0] == _t\n if dp[idx][_t] != -1:\n return dp[idx][_t]\n notTaken = self.solve(idx - 1, _t, arr, dp)\n taken = False\n if arr[idx] <= _t:\n taken = self.solve(idx - 1, _t - arr[idx], arr, dp)\n dp[idx][_t] = notTaken or taken\n return dp[idx][_t]", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2:\n return 'NO'\n W = s // 2\n dp = [[0 for j in range(W + 1)] for i in range(N + 1)]\n for i in range(N + 1):\n for j in range(W + 1):\n if j == 0:\n dp[i][j] = 1\n elif j < arr[i - 1]:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j] | dp[i - 1][j - arr[i - 1]]\n return dp[N][W]", "def equalpartition(N, arr):\n total_sum = sum(arr)\n if total_sum % 2 != 0:\n return False\n target = total_sum // 2\n dp = [False] * (target + 1)\n dp[0] = True\n for ele in arr:\n for j in range(target, ele - 1, -1):\n if dp[j - ele]:\n dp[j] = True\n return dp[target]", "def equalpartition(N, arr):\n sum = 0\n for i in arr:\n sum += i\n if sum % 2 != 0:\n return False\n sum = sum // 2\n dp = [[False for i in range(sum + 1)] for i in range(N)]\n for i in range(N):\n dp[i][0] = True\n if arr[0] <= sum:\n dp[0][arr[0]] = True\n for ind in range(1, N):\n for target in range(1, sum + 1):\n ntake = dp[ind - 1][target]\n take = False\n if arr[ind] <= target:\n take = dp[ind - 1][target - arr[ind]]\n dp[ind][target] = take or ntake\n if target == sum:\n if dp[ind][target] == True:\n return True\n return dp[N - 1][sum]", "def equalpartition(n, arr):\n sum_ = sum(arr)\n if sum_ % 2 == 0:\n target = sum_ // 2\n dp = [[-1 for j in range(target + 1)] for i in range(n)]\n return self.solve(n - 1, target, dp, arr)\n else:\n return False\n\ndef solve(n, target, dp, arr):\n if target == 0:\n dp[n][target] = True\n return True\n if n == 0:\n if arr[n] == target:\n dp[n][target] = True\n return True\n else:\n dp[n][target] = False\n return False\n if dp[n][target] != -1:\n return dp[n][target]\n pick = False\n if arr[n] <= target:\n pick = self.solve(n - 1, target - arr[n], dp, arr)\n npick = self.solve(n - 1, target, dp, arr)\n dp[n][target] = pick or npick\n return dp[n][target]", "def equalpartition(N, arr):\n if sum(arr) % 2 != 0:\n return False\n else:\n return self.isSubsetSum(N, arr, sum(arr) // 2)\n\ndef isSubsetSum(N, arr, sum):\n tab = [[False for i in range(sum + 1)] for j in range(N + 1)]\n for i in range(N + 1):\n tab[i][0] = True\n for i in range(1, N + 1):\n for j in range(1, sum + 1):\n if arr[i - 1] > j:\n tab[i][j] = tab[i - 1][j]\n else:\n tab[i][j] = tab[i - 1][j] or tab[i - 1][j - arr[i - 1]]\n return tab[N][sum]", "def solve(N, arr, idx, summ):\n if summ == 0:\n return 1\n if idx >= N or summ < 0:\n return 0\n incl = self.solve(N, arr, idx + 1, summ - arr[idx])\n excl = self.solve(N, arr, idx + 1, summ)\n return incl or excl\n\ndef solve_memo(N, arr, idx, summ, F):\n if summ == 0:\n return 1\n if idx >= N or summ < 0:\n return 0\n incl = self.solve_memo(N, arr, idx + 1, summ - arr[idx], F)\n excl = self.solve_memo(N, arr, idx + 1, summ, F)\n F[idx][summ] = incl or excl\n return F[idx][summ]\n\ndef solve_tab(N, arr):\n total = sum(arr)\n F = [[0 for _ in range(total // 2 + 1)] for _ in range(N + 1)]\n for i in range(N + 1):\n F[i][0] = 1\n for idx in range(N - 1, -1, -1):\n for summ in range(total // 2 + 1):\n incl = 0\n if summ - arr[idx] >= 0:\n incl = F[idx + 1][summ - arr[idx]]\n excl = F[idx + 1][summ]\n F[idx][summ] = incl or excl\n return F[0][total // 2]\n\ndef solve_tab2(N, arr):\n total = sum(arr)\n curr = [0 for _ in range(total // 2 + 1)]\n nextt = [0 for _ in range(total // 2 + 1)]\n curr[0] = 1\n nextt[0] = 1\n for idx in range(N - 1, -1, -1):\n for summ in range(total // 2 + 1):\n incl = 0\n if summ - arr[idx] >= 0:\n incl = nextt[summ - arr[idx]]\n excl = nextt[summ]\n curr[summ] = incl or excl\n nextt = curr[:]\n return nextt[total // 2]\n\ndef equalpartition(N, arr):\n summ = sum(arr)\n if summ % 2:\n return 0\n return self.solve_tab2(N, arr)", "def equalpartition(n, arr):\n s = sum(arr)\n if s % 2 != 0:\n return False\n elif self.subsetSum(n, arr, s // 2):\n return True\n else:\n return False\n\ndef subsetSum(n, arr, s):\n dp = [[False for i in range(s + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = True\n for i in range(1, s + 1):\n dp[0][i] = False\n for i in range(1, n + 1):\n for j in range(1, s + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j - arr[i - 1]] or dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[-1][-1]", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2 != 0:\n return 0\n k = s // 2\n dp = [[0 for _ in range(k + 1)] for i in range(N + 1)]\n for i in range(N + 1):\n dp[i][0] = 1\n for i in range(1, N + 1):\n for j in range(1, k + 1):\n if arr[i - 1] > j:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]\n return dp[N][k]", "def equalpartition(N, arr):\n stateMap = {0: True}\n llimit = max(arr)\n for elem in arr:\n currMap = {}\n for k in stateMap:\n if not currMap.get(k + elem):\n currMap[k + elem] = True\n if k - elem >= -llimit and (not currMap.get(k - elem)):\n currMap[k - elem] = True\n stateMap = currMap\n return 1 if stateMap.get(0) else 0", "def equalpartition(N, arr):\n\n def foo(i, s, dp):\n if s == 0:\n return True\n if i < 0 or s < 0:\n return False\n if dp[i][s] != -1:\n return dp[i][s]\n dp[i][s] = foo(i - 1, s - arr[i], dp) or foo(i - 1, s, dp)\n return dp[i][s]\n sm = sum(arr)\n if sm % 2 != 0:\n return 0\n dp = [[-1] * (sm // 2 + 1) for i in range(N)]\n foo(N - 1, sm // 2, dp)\n return dp[N - 1][sm // 2]", "def equalpartition(N, arr):\n sum_ = sum(arr)\n if sum_ % 2 != 0:\n return 0\n s = sum_ // 2\n dp = [[False for i in range(s + 1)] for j in range(N + 1)]\n for i in range(N + 1):\n for j in range(s + 1):\n if i == 0 and j == 0:\n dp[i][j] = True\n elif i == 0:\n dp[i][j] = False\n elif j == 0:\n dp[i][j] = True\n elif dp[i - 1][j]:\n dp[i][j] = dp[i - 1][j]\n else:\n val = arr[i - 1]\n if j >= val:\n dp[i][j] = dp[i - 1][j - val]\n return dp[-1][-1]", "def equalpartition(N, arr):\n total = sum(arr)\n if total % 2 != 0:\n return 0\n DP = [[-1] * (total // 2 + 1) for i in range(N)]\n\n def reccur(index, curSum):\n if curSum == 0:\n return 1\n if index == 0:\n return int(arr[index] == curSum)\n if DP[index][curSum] != -1:\n return DP[index][curSum]\n not_take = reccur(index - 1, curSum)\n take = 0\n if curSum >= arr[index]:\n take = reccur(index - 1, curSum - arr[index])\n DP[index][curSum] = take or not_take\n return DP[index][curSum]\n return reccur(N - 1, total // 2)", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2 != 0:\n return False\n t = s // 2\n d = set()\n d.add(0)\n new = []\n for i in arr:\n for j in d:\n a = i + j\n new.append(a)\n for i in new:\n d.add(i)\n new = []\n if t in d:\n return True\n if t in d:\n return True\n return False", "def equalpartition(N, arr):\n sum = 0\n for i in range(N):\n sum = sum + arr[i]\n t = [[-1 for j in range(int(sum / 2) + 1)] for i in range(N + 1)]\n if sum % 2 != 0:\n return 0\n else:\n for i in range(N + 1):\n for j in range(int(sum / 2) + 1):\n if i == 0:\n t[i][j] = 0\n if j == 0:\n t[i][j] = 1\n for i in range(1, N + 1):\n for j in range(1, int(sum / 2) + 1):\n if arr[i - 1] <= j:\n t[i][j] = t[i - 1][j - arr[i - 1]] or t[i - 1][j]\n else:\n t[i][j] = t[i - 1][j]\n return t[N][sum // 2]", "def partition_sum_problem(input_arr: []):\n sum_value = sum(input_arr)\n if sum_value % 2 != 0:\n return False\n return can_partition_helper(0, int(sum_value // 2), len(input_arr) - 1, input_arr)\n\ndef can_partition_helper(index: int, remaining_sum: int, end_index, input_arr: []):\n if remaining_sum == 0:\n return True\n if index > end_index or remaining_sum < 0:\n return False\n return can_partition_helper(index + 1, remaining_sum - input_arr[index], end_index, input_arr) or can_partition_helper(index + 1, remaining_sum, end_index, input_arr)\n\ndef equalpartition(N, arr):\n return partition_sum_problem(arr)", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2:\n return False\n s = s // 2\n part = [False] * (s + 1)\n part[0] = True\n for i in range(N):\n for j in range(s, arr[i] - 1, -1):\n if part[j - arr[i]] or j == arr[i]:\n part[j] = True\n return part[s]", "import sys\nsys.setrecursionlimit(10 ** 6)\n\ndef equalpartition(N, arr):\n if sum(arr) % 2 != 0:\n return False\n target = sum(arr) // 2\n\n def helper(i, n):\n if n == 0:\n return True\n if i == len(arr) or n < 0:\n return False\n return helper(i + 1, n - arr[i]) or helper(i + 1, n)\n return helper(0, target)", "def solve(arr, ind, sum, dp):\n if ind < 0:\n return sum == 0\n if dp[ind][sum] != -1:\n return dp[ind][sum]\n ans = self.solve(arr, ind - 1, sum, dp)\n if arr[ind] <= sum:\n ans = max(ans, self.solve(arr, ind - 1, sum - arr[ind], dp))\n dp[ind][sum] = ans\n return ans\n\ndef equalpartition(N, arr):\n su = sum(arr)\n if su & 1 == 1:\n return 0\n dp = [[-1 for _ in range(su)] for _ in range(N)]\n return self.solve(arr, N - 1, su // 2, dp)", "def equalpartition(N, arr):\n tot = sum(arr)\n if tot % 2 == 1:\n return 0\n req = tot // 2\n allposs = set([0])\n for ele in arr:\n set2 = set()\n for sub in allposs:\n newsum = sub + ele\n if newsum == req:\n return 1\n set2.add(newsum)\n allposs = allposs.union(set2)\n return 0", "def equalpartition(N, arr):\n total = sum(arr)\n if total % 2:\n return 0\n k = total // 2\n dp = [[0 for i in range(k + 1)] for j in range(N)]\n for i in range(N):\n dp[i][0] = 1\n if arr[0] <= k:\n dp[0][arr[0]] = 1\n for i in range(1, N):\n for target in range(1, k + 1):\n nottake = dp[i - 1][target]\n take = False\n if arr[i] <= target:\n take = dp[i - 1][target - arr[i]]\n dp[i][target] = take or nottake\n return dp[N - 1][k]", "def equalpartition(N, arr):\n if len(arr) == 0:\n arr_sum = 0\n else:\n arr_sum = sum(arr)\n if arr_sum % 2 != 0:\n return 0\n dp = [[-1 for _ in range(arr_sum + 1)] for __ in range(len(arr))]\n if self.ispossible(arr, arr_sum // 2, dp, len(arr) - 1):\n return 1\n else:\n return 0\n\ndef ispossible(array, rem, sub, n):\n if rem == 0:\n return True\n if n == -1 and rem != 0:\n return False\n if sub[n][rem] != -1:\n return sub[n][rem]\n if array[n] <= rem:\n not_skip = self.ispossible(array, rem - arr[n], sub, n - 1)\n else:\n not_skip = False\n skip = self.ispossible(array, rem, sub, n - 1)\n if skip or not_skip:\n sub[n][rem] = True\n else:\n sub[n][rem] = False\n return sub[n][rem]", "def equalpartition(N, arr):\n if len(arr) == 0:\n arr_sum = 0\n else:\n arr_sum = sum(arr)\n if arr_sum % 2 != 0:\n return 0\n dp = [[-1 for _ in range(arr_sum + 1)] for __ in range(len(arr))]\n return self.ispossible(arr, arr_sum // 2, dp, len(arr) - 1)\n\ndef ispossible(array, rem, sub, n):\n if rem == 0:\n return 1\n if n == -1 and rem != 0:\n return 0\n if sub[n][rem] != -1:\n return sub[n][rem]\n if array[n] > rem:\n return self.ispossible(array, rem, sub, n - 1)\n if self.ispossible(array, rem - array[n], sub, n - 1) + self.ispossible(array, rem, sub, n - 1) >= 1:\n sub[n][rem] = 1\n else:\n sub[n][rem] = 0\n return sub[n][rem]", "def helper(arr, n, s, i, dp):\n if s == 0:\n return 1\n if i == n:\n return 0\n if dp[i][s] != -1:\n return dp[i][s]\n take = 0\n if arr[i] <= s:\n take = self.helper(arr, n, s - arr[i], i + 1, dp)\n nottake = self.helper(arr, n, s, i + 1, dp)\n dp[i][s] = take or nottake\n return take or nottake\n\ndef equalpartition(N, arr):\n s = 0\n for i in arr:\n s += i\n p = s // 2\n if s % 2 == 1:\n return 0\n dp = [[-1 for i in range(p + 1)] for j in range(N + 1)]\n for i in range(N):\n dp[i][0] = 1\n if self.helper(arr, N, p, 0, dp):\n return 1\n return 0", "def equalpartition(N, arr):\n\n def come(arr, target, N):\n if target == 0:\n return True\n if N == 0:\n if arr[0] == target:\n return True\n return False\n if arr[N] <= target:\n return come(arr, target - arr[N], N - 1) or come(arr, target, N - 1)\n return come(arr, target, N - 1)\n s = 0\n for i in arr:\n s = s + i\n if s % 2 == 1:\n return False\n else:\n p = come(arr, s // 2, N - 1)\n return p", "def equalpartition(N, arr):\n dp = []\n for i in range(N):\n a = []\n for j in range(sum(arr) // 2 + 1):\n a.append(0)\n dp.append(a)\n if sum(arr) % 2 == 1:\n return 0\n for i in range(N):\n dp[i][0] = 1\n if arr[0] <= sum(arr) // 2:\n dp[0][arr[0]] = 1\n for i in range(1, N):\n for j in range(1, sum(arr) // 2 + 1):\n nottake = dp[i - 1][j]\n take = 0\n if arr[i] <= j:\n take = dp[i - 1][j - arr[i]]\n dp[i][j] = take or nottake\n return dp[N - 1][sum(arr) // 2]", "def equalpartition(N, arr):\n total = sum(arr)\n if total % 2 != 0:\n return 0\n dp = [[-1] * (total + 1) for i in range(N + 1)]\n\n def subset(arr, n, s, total):\n if s == total - s:\n return 1\n if n >= 0 and s == 0:\n return 0\n if n == 0 and s > 0:\n return 0\n if dp[n][s] != -1:\n return dp[n][s]\n elif arr[n - 1] <= s:\n dp[n][s] = subset(arr, n - 1, s - arr[n - 1], total) or subset(arr, n - 1, s, total)\n else:\n dp[n][s] = subset(arr, n - 1, s, total)\n return dp[n][s]\n return subset(arr, N, total, total)", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2 != 0:\n return 0\n s = s // 2 + 1\n m = [[0 for i in range(s)] for j in range(N + 1)]\n m[0][0] = 1\n for i in range(N + 1):\n for j in range(s):\n if i == 0 and j != 0:\n m[i][j] = 0\n elif j == 0:\n m[i][j] = 1\n elif arr[i - 1] > j:\n m[i][j] = m[i - 1][j]\n else:\n m[i][j] = m[i - 1][j] or m[i - 1][j - arr[i - 1]]\n return m[N][s - 1]", "def equalpartition(n, arr):\n s = sum(arr)\n if s % 2 == 1:\n return 0\n dp = [[-1] * (s // 2 + 1) for i in range(n)]\n\n def partpos(i, s1, s2, n):\n if s1 == s2:\n return 1\n if i >= n or s1 > s2:\n return 0\n if dp[i][s1] != -1:\n return dp[i][s1]\n inc = partpos(i + 1, s1 + arr[i], s2 - arr[i], n)\n if inc == 1:\n return 1\n ninc = partpos(i + 1, s1, s2, n)\n dp[i][s1] = 1 if inc == 1 or ninc == 1 else 0\n return 1 if inc == 1 or ninc == 1 else 0\n return partpos(0, 0, s, n)", "def equalpartition(N, arr):\n total = 0\n for i in arr:\n total += i\n dp = [[-1 for i in range(total // 2 + 1)] for j in range(N)]\n if total % 2:\n return False\n else:\n return self.recursion(0, arr, total // 2, N, dp)\n\ndef recursion(idx, arr, tar, n, dp):\n if idx == n:\n if tar == 0:\n return True\n return False\n if dp[idx][tar] != -1:\n return dp[idx][tar]\n p = False\n if tar >= arr[idx]:\n p = self.recursion(idx + 1, arr, tar - arr[idx], n, dp)\n np = self.recursion(idx + 1, arr, tar, n, dp)\n dp[idx][tar] = p or np\n return dp[idx][tar]", "def equalpartition(N, arr):\n arrSum = sum(arr)\n if arrSum % 2 != 0:\n return False\n dp = dict()\n return self.subsetSum(arr, N, 0, arrSum // 2, dp)\n\ndef subsetSum(arr, n, index, s, dp):\n if index == n:\n if s == 0:\n return True\n return False\n if s == 0:\n return True\n if (index, s) in dp:\n return dp[index, s]\n if arr[index] > s:\n dp[index, s] = self.subsetSum(arr, n, index + 1, s, dp)\n else:\n dp[index, s] = self.subsetSum(arr, n, index + 1, s, dp) or self.subsetSum(arr, n, index + 1, s - arr[index], dp)\n return dp[index, s]"], "starter_code": "def equalpartition(N, arr):\n", "input_output": {"inputs": ["N = 4\r\narr = {1, 5, 11, 5}", "N = 3\r\narr = {1, 3, 5}"], "outputs": ["YES", "NO"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming", "subset"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Mathematics"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/subset-sum-problem2014/1", "Expected Auxiliary Space": "O(N*sum of elements)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*sum of elements)", "entry_point": "equalpartition", "task_id": "TACO_lite/444", "example": [[], []]} +{"requirement": "You've just entered a programming contest and have a chance to win a million dollars. This is the last question you have to solve, so your victory (and your vacation) depend on it. Can you guess the function just by looking at the test cases? There are two numerical inputs and one numerical output. Goodluck!\n\nhint: go\n here", "solutions": ["TABLE = str.maketrans('0123456789', '9876543210')\n\ndef code(*args):\n return sum(map(lambda n: int(str(n).translate(TABLE)), args))", "def code(x, y):\n return sum((int('9' * len(str(n))) - n for n in [x, y]))", "code = lambda Q, S: 10 ** len(str(Q)) + 10 ** len(str(S)) - 2 - Q - S", "def code(x, y):\n return sum((int(str(n).translate(str.maketrans('0123456789', '9876543210'))) for n in [x, y]))", "def code(x, y):\n return 10 ** len(str(x)) - x + (10 ** len(str(y)) - y) - 2", "code = lambda a, b: 10 ** len(str(a)) - a + 10 ** len(str(b)) - b - 2", "def code(x, y):\n goal = pow(10, len(str(x))) + pow(10, len(str(y))) - 2\n return goal - x - y", "def code(x, y):\n return 10 ** len(str(x)) + 10 ** len(str(y)) + 3 - x - y - 5"], "starter_code": "def code(x,y):\n", "input_output": {"fn_name": "code", "inputs": [[9, 8], [123, 456], [3, 2], [1, 1], [12, 8], [200, 100], [100, 200]], "outputs": [[1], [1419], [13], [16], [88], [1698], [1698]]}, "difficulty": "EASY", "raw_tags": ["Puzzles"], "name": null, "source": "codewars", "tags": ["Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/5b1fa8d92ae7540e700000f0", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "code", "task_id": "TACO_lite/386", "example": [[[3, 5], [10, 15], [7, 2], [0, 0]], ["8", "25", "9", "0"]]} +{"requirement": "Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.\n\nReturn the quotient after dividing dividend by divisor.\n\nThe integer division should truncate toward zero.\n\nExample 1:\n\n\nInput: dividend = 10, divisor = 3\nOutput: 3\n\nExample 2:\n\n\nInput: dividend = 7, divisor = -3\nOutput: -2\n\nNote:\n\n\n Both dividend and divisor will be 32-bit signed integers.\n The divisor will never be 0.\n Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.", "solutions": ["def get_half(dividend, divisor):\n abs_dividend = abs(dividend)\n abs_divisor = abs(divisor)\n num = divisor\n num_temp = 0\n result = 1\n result_temp = 0\n while num <= dividend:\n num_temp = num\n num += num\n result_temp = result\n result += result\n return (num_temp, result_temp)\n\ndef divide(dividend, divisor):\n MAX_INT = 2147483647\n if divisor == 0:\n return MAX_INT\n abs_dividend = abs(dividend)\n abs_divisor = abs(divisor)\n if abs_dividend < abs_divisor:\n return 0\n minus_flag = (dividend is abs_dividend) is (divisor is abs_divisor)\n final_result = 0\n while abs_dividend >= abs_divisor:\n (num, result) = self.get_half(abs_dividend, abs_divisor)\n abs_dividend -= num\n final_result += result\n if minus_flag == 1:\n if final_result > MAX_INT:\n return MAX_INT\n return final_result\n else:\n if 0 - final_result < 0 - MAX_INT - 1:\n return 0 - MAX_INT\n return 0 - final_result", "def divide(dividend, divisor):\n positive = (dividend < 0) is (divisor < 0)\n (dividend, divisor) = (abs(dividend), abs(divisor))\n res = 0\n while dividend >= divisor:\n (temp, i) = (divisor, 1)\n while dividend >= temp:\n dividend -= temp\n res += i\n temp <<= 1\n i <<= 1\n if not positive:\n res = -res\n return min(max(-2147483648, res), 2147483647)", "def divide(dividend, divisor):\n if abs(dividend) < abs(divisor):\n return 0\n (sum, count, result) = (0, 0, 0)\n (a, b) = (abs(dividend), abs(divisor))\n while a >= b:\n sum = b\n count = 1\n while sum + sum < a:\n sum += sum\n count += count\n a -= sum\n result += count\n if dividend < 0 and divisor > 0 or (dividend > 0 and divisor < 0):\n result = 0 - result\n return min(result, 2147483647)", "def divide(dividend, divisor):\n MIN_INT = -2 ** 31\n MAX_INT = -MIN_INT - 1\n if divisor == 0 or (dividend == MIN_INT and divisor == -1):\n return MAX_INT\n sign = 1\n if dividend < 0:\n sign = -sign\n dividend = -dividend\n if divisor < 0:\n sign = -sign\n divisor = -divisor\n ans = bits = 0\n while divisor << bits + 1 <= dividend:\n bits += 1\n while bits >= 0:\n if dividend >= divisor << bits:\n dividend -= divisor << bits\n ans += 1 << bits\n bits -= 1\n return ans if sign == 1 else -ans", "def divide(dividend, divisor):\n positive = (dividend < 0) is (divisor < 0)\n (dividend, divisor, div) = (abs(dividend), abs(divisor), abs(divisor))\n res = 0\n q = 1\n while dividend >= divisor:\n dividend -= div\n res += q\n q += q\n div += div\n if dividend < div:\n div = divisor\n q = 1\n if not positive:\n res = -res\n return min(max(-2147483648, res), 2147483647)", "def divide(dividend, divisor):\n tag = 1 if (dividend < 0) is (divisor < 0) else -1\n (dividend, divisor) = (abs(dividend), abs(divisor))\n if divisor == 0:\n return float('inf')\n count = 0\n while dividend >= divisor:\n mul = 1\n t = divisor\n while dividend > t << 1:\n t <<= 1\n mul <<= 1\n dividend -= t\n count += mul\n return min(max(-2147483648, count * tag), 2147483647)", "def divide(dividend, divisor):\n if dividend < 0 and divisor > 0 or (dividend > 0 and divisor < 0):\n if abs(dividend) < abs(divisor):\n return 0\n summ = 0\n count = 0\n res = 0\n a = abs(dividend)\n b = abs(divisor)\n while a >= b:\n summ = b\n count = 1\n while summ + summ <= a:\n summ += summ\n count += count\n a -= summ\n res += count\n if dividend < 0 and divisor > 0 or (dividend > 0 and divisor < 0):\n res = 0 - res\n if res > 2 ** 31 - 1:\n res = 2 ** 31 - 1\n return res", "def divide(dividend, divisor):\n flag = (dividend < 0) is (divisor < 0)\n (dividend, divisor) = (abs(dividend), abs(divisor))\n result = 0\n while dividend >= divisor:\n (newDivisor, rate) = (divisor, 1)\n while dividend >= newDivisor:\n dividend -= newDivisor\n result += rate\n newDivisor <<= 1\n rate <<= 1\n if not flag:\n result = 0 - result\n return min(max(-2147483648, result), 2147483647)"], "starter_code": "def divide(dividend: int, divisor: int) -> int:\n", "input_output": {"fn_name": "divide", "inputs": [[10, 3]], "outputs": [3]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Math", "Bit Manipulation"], "name": null, "source": "leetcode", "tags": ["Bit manipulation", "Mathematics"], "skill_types": ["Bit manipulation"], "url": "https://leetcode.com/problems/divide-two-integers/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "divide", "task_id": "TACO_lite/429", "example": [[[10, 3], [7, -3]], ["3", "-2"]]} +{"requirement": "Given the root of a binary tree, consider all root to leaf paths: paths from the root to any leaf.  (A leaf is a node with no children.)\nA node is insufficient if every such root to leaf path intersecting this node has sum strictly less than limit.\nDelete all insufficient nodes simultaneously, and return the root of the resulting binary tree.\n \nExample 1:\n\nInput: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1\n\nOutput: [1,2,3,4,null,null,7,8,9,null,14]\n\n\nExample 2:\n\nInput: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22\n\nOutput: [5,4,8,11,null,17,4,7,null,null,null,5]\n \nExample 3:\n\nInput: root = [1,2,-3,-5,null,4,null], limit = -1\n\nOutput: [1,null,-3,4]\n\n \nNote:\n\nThe given tree will have between 1 and 5000 nodes.\n-10^5 <= node.val <= 10^5\n-10^9 <= limit <= 10^9", "solutions": ["def sufficientSubset(root, limit):\n if root.left == root.right:\n return None if root.val < limit else root\n if root.left:\n root.left = self.sufficientSubset(root.left, limit - root.val)\n if root.right:\n root.right = self.sufficientSubset(root.right, limit - root.val)\n return root if root.left or root.right else None", "def sumofnodes(root, cursum):\n if root is None:\n return 0\n cursum += root.val\n self.sumdict[root] = cursum\n self.sumofnodes(root.left, cursum)\n self.sumofnodes(root.right, cursum)\n\ndef maxpathsum(root):\n if root.left == None and root.right == None:\n self.maxdict[root] = self.sumdict[root]\n elif root.left and root.right:\n self.maxdict[root] = max(self.maxpathsum(root.left), self.maxpathsum(root.right))\n elif root.right:\n self.maxdict[root] = self.maxpathsum(root.right)\n else:\n self.maxdict[root] = self.maxpathsum(root.left)\n return self.maxdict[root]\n\ndef deletenodes(root, limit):\n if root is None:\n return\n if root.left and self.maxdict[root.left] < limit:\n root.left = None\n if root.right and self.maxdict[root.right] < limit:\n root.right = None\n self.deletenodes(root.left, limit)\n self.deletenodes(root.right, limit)\n\ndef sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n self.sumdict = {}\n self.sumofnodes(root, 0)\n self.maxdict = {}\n self.maxpathsum(root)\n self.deletenodes(root, limit)\n if self.maxdict[root] < limit:\n return None\n else:\n return root", "def sufficientSubset(root, limit):\n\n def dfs(root, cur):\n if root is None:\n return None\n s = root.val + cur\n if root.left is None and root.right is None:\n if s < limit:\n return None\n else:\n return root\n l = dfs(root.left, s)\n r = dfs(root.right, s)\n if l is None and r is None:\n return None\n (root.left, root.right) = (l, r)\n return root\n return dfs(root, 0)", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n sum_t_root = TreeNode(root.val)\n sum_t_node = sum_t_root\n t_node = root\n\n def calSumT(node, sum_t_node, s):\n if not node:\n return\n if not node.left and (not node.right):\n sum_t_node.val = True if s >= limit else False\n if node.left:\n sum_t_node.left = TreeNode(node.left.val + s)\n calSumT(node.left, sum_t_node.left, s + node.left.val)\n if node.right:\n sum_t_node.right = TreeNode(node.right.val + s)\n calSumT(node.right, sum_t_node.right, s + node.right.val)\n calSumT(t_node, sum_t_node, root.val)\n\n def strT(node):\n if not node:\n return []\n return [node.val] + strT(node.left) + strT(node.right)\n\n def checkSumT(node):\n if not node.left and (not node.right):\n return\n rtn = False\n if node.left:\n checkSumT(node.left)\n rtn |= node.left.val\n if node.right:\n checkSumT(node.right)\n rtn |= node.right.val\n node.val = rtn\n sum_t_node = sum_t_root\n checkSumT(sum_t_node)\n\n def updateNode(node, s_node):\n if not node or not s_node.val:\n return None\n if node.left:\n node.left = updateNode(node.left, s_node.left)\n if node.right:\n node.right = updateNode(node.right, s_node.right)\n return node\n return updateNode(root, sum_t_root)", "def check_limit(root, limit):\n if not root:\n return float('-inf')\n left_sum = self.check_limit(root.left, limit - root.val)\n right_sum = self.check_limit(root.right, limit - root.val)\n if left_sum != float('-inf') and left_sum + root.val < limit:\n root.left = None\n if right_sum != float('-inf') and right_sum + root.val < limit:\n root.right = None\n max_ = max(left_sum, right_sum)\n if max_ == float('-inf'):\n return root.val\n return max_ + root.val\n\ndef sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n if (self.check_limit(root, limit) or 0) < limit:\n return None\n else:\n return root", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n\n def check(node, pathsum):\n if not node:\n return pathsum >= limit\n pathsum += node.val\n had_children = node.left or node.right\n if not check(node.left, pathsum):\n node.left = None\n if not check(node.right, pathsum):\n node.right = None\n return node.left or node.right if had_children else pathsum >= limit\n return root if check(root, 0) else None", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n\n def check(root, total, limit):\n if root == None:\n return None\n total += root.val\n if root.left == root.right:\n if total < limit:\n return None\n else:\n return root\n flag1 = 0\n flag2 = 0\n if root.left:\n root.left = check(root.left, total, limit)\n flag1 = 1 if root.left else -1\n if root.right:\n root.right = check(root.right, total, limit)\n flag2 = 1 if root.right else -1\n if flag1 > 0 or flag2 > 0:\n return root\n else:\n return None\n rtv = check(root, 0, limit)\n return rtv", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n if not root:\n return root\n\n def dfs(node, value):\n if not node:\n return False\n value += node.val\n lret = dfs(node.left, value)\n rret = dfs(node.right, value)\n if not node.left and (not node.right):\n if value < limit:\n return False\n return True\n if not lret:\n node.left = None\n if not rret:\n node.right = None\n if lret or rret:\n return True\n return False\n res = dfs(root, 0)\n if res:\n return root", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n\n def helper(root, currsum, limit):\n if not root:\n return True\n currsum += root.val\n if root.left is None and root.right is None:\n return currsum < limit\n deleteme = [True, True]\n if root.left:\n should_del = helper(root.left, currsum, limit)\n if should_del:\n del root.left\n root.left = None\n deleteme[0] = should_del\n if root.right:\n should_del = helper(root.right, currsum, limit)\n if should_del:\n del root.right\n root.right = None\n deleteme[1] = should_del\n return all(deleteme)\n deleteroot = helper(root, 0, limit)\n if deleteroot:\n del root\n return None\n return root", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n head = TreeNode()\n head.left = root\n\n def inner1(root, prev_sum):\n if root is None:\n return\n else:\n root.val = (root.val, prev_sum)\n inner1(root.left, root.val[0] + prev_sum)\n inner1(root.right, root.val[0] + prev_sum)\n return\n\n def inner2(root):\n if root is None:\n return []\n if root.left is None and root.right is None:\n return [sum(root.val)]\n left = inner2(root.left)\n if not left or max(left) < limit:\n root.left = None\n right = inner2(root.right)\n if not right or max(right) < limit:\n root.right = None\n res = left + right\n return res\n\n def inner3(root):\n if root is None:\n return\n else:\n root.val = root.val[0]\n inner3(root.left)\n inner3(root.right)\n return\n inner1(head, 0)\n _ = inner2(head)\n inner3(head)\n return head.left", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n\n def generateSumT(node, s):\n if not node:\n return (None, False)\n if not node.left and (not node.right):\n if s >= limit:\n return (node, True)\n else:\n return (None, False)\n isValid = False\n if node.left:\n (node.left, L) = generateSumT(node.left, s + node.left.val)\n isValid |= L\n if node.right:\n (node.right, R) = generateSumT(node.right, s + node.right.val)\n isValid |= R\n if isValid:\n return (node, True)\n else:\n return (None, False)\n (rtn, _) = generateSumT(root, root.val)\n return rtn", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n\n def remove(node, val):\n if not node:\n return val\n l = remove(node.left, node.val + val)\n r = remove(node.right, node.val + val)\n result = 0\n if node.left and node.right:\n result = max(l, r)\n elif node.left:\n result = l\n else:\n result = r\n if l < limit:\n node.left = None\n if r < limit:\n node.right = None\n return result\n val = remove(root, 0)\n return None if val < limit else root", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n if not root:\n return root\n if not root.left and (not root.right):\n return root if root.val >= limit else None\n root.left = self.sufficientSubset(root.left, limit - root.val)\n root.right = self.sufficientSubset(root.right, limit - root.val)\n return root if root.left or root.right else None", "def collect_insufficient_nodes(node, cur_sum, nodes, limit):\n if node is None:\n return 0\n subpath_sums = []\n if node.left:\n subpath_sums.append(collect_insufficient_nodes(node.left, cur_sum + node.val, nodes, limit))\n if node.right:\n subpath_sums.append(collect_insufficient_nodes(node.right, cur_sum + node.val, nodes, limit))\n max_subpath_sum = 0 if not len(subpath_sums) else max(subpath_sums)\n if cur_sum + max_subpath_sum + node.val < limit:\n nodes.append(node)\n return max_subpath_sum + node.val\n\ndef delete_nodes(node, nodes):\n if not node:\n return\n if node.left in nodes:\n node.left = None\n else:\n delete_nodes(node.left, nodes)\n if node.right in nodes:\n node.right = None\n else:\n delete_nodes(node.right, nodes)\n\ndef sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n nodes = []\n collect_insufficient_nodes(root, 0, nodes, limit)\n nodes = set(nodes)\n if root in nodes:\n return None\n delete_nodes(root, nodes)\n return root", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n\n def dfs(node, path_sum):\n if not node:\n return False\n path_sum += node.val\n if not node.left and (not node.right):\n return path_sum >= limit\n left = dfs(node.left, path_sum)\n right = dfs(node.right, path_sum)\n if not left:\n node.left = None\n if not right:\n node.right = None\n return left or right\n result = dfs(root, 0)\n return root if result else None", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n\n def dfs(node, value):\n if not node:\n return False\n value += node.val\n l_side = dfs(node.left, value)\n r_side = dfs(node.right, value)\n if not node.left and (not node.right):\n if value < limit:\n return False\n return True\n if not l_side:\n node.left = None\n if not r_side:\n node.right = None\n if l_side or r_side:\n return True\n return False\n if dfs(root, 0):\n return root\n return", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n if root == None:\n return None\n\n def dfs(root, val):\n if root == None:\n return (-10000000000.0, 'nodel')\n if root:\n (left_val, left_del_str) = dfs(root.left, val + root.val)\n (right_val, right_del_str) = dfs(root.right, val + root.val)\n if root.left and root.right:\n cur_val = val + root.val + max(left_val, right_val)\n elif root.left:\n cur_val = val + root.val + left_val\n elif root.right:\n cur_val = val + root.val + right_val\n else:\n cur_val = val + root.val\n if left_del_str == 'del':\n root.left = None\n if right_del_str == 'del':\n root.right = None\n if cur_val < limit:\n return (cur_val - val, 'del')\n else:\n return (cur_val - val, 'nodel')\n (_, root_del_str) = dfs(root, 0)\n if root_del_str == 'del':\n return None\n else:\n return root", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n if root == None:\n return None\n canRootLeft = self.validSubtree(root.left, limit, root.val)\n canRootRight = self.validSubtree(root.right, limit, root.val)\n root.left = root.left if canRootLeft else None\n root.right = root.right if canRootRight else None\n if not canRootLeft and (not canRootRight):\n return None\n else:\n return root\n\ndef validSubtree(node: TreeNode, limit: int, currentVal: int) -> bool:\n if node == None:\n return currentVal >= limit\n canLeft = self.validSubtree(node.left, limit, node.val + currentVal)\n canRight = self.validSubtree(node.right, limit, node.val + currentVal)\n if node.left and (not node.right):\n canRight = canLeft\n elif node.right and (not node.left):\n canLeft = canRight\n node.left = node.left if canLeft else None\n node.right = node.right if canRight else None\n if not canLeft and (not canRight):\n return False\n else:\n return canLeft or canRight", "def helper(root, total, limit):\n if not root:\n return False\n if root.left == None and root.right == None:\n return total + root.val >= limit\n left = self.helper(root.left, total + root.val, limit)\n right = self.helper(root.right, total + root.val, limit)\n if not left:\n root.left = None\n if not right:\n root.right = None\n return left or right\n\ndef sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n if self.helper(root, 0, limit):\n return root\n else:\n return None"], "starter_code": "def __init__(val=0, left=None, right=None):\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Binary Tree", "Tree", "Depth-First Search"], "name": null, "source": "leetcode", "tags": ["Tree algorithms", "Graph traversal"], "skill_types": [], "url": "https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "__init__", "task_id": "TACO_lite/369", "example": [[], []]} +{"requirement": "A Madhav array has the following property:\n\n```a[0] = a[1] + a[2] = a[3] + a[4] + a[5] = a[6] + a[7] + a[8] + a[9] = ...```\n\nComplete the function/method that returns `true` if the given array is a Madhav array, otherwise it returns `false`.\n\n*Edge cases: An array of length* `0` *or* `1` *should not be considered a Madhav array as there is nothing to compare.*", "solutions": ["def is_madhav_array(arr):\n nTerms = ((1 + 8 * len(arr)) ** 0.5 - 1) / 2\n return len(arr) > 1 and (not nTerms % 1) and (len({sum(arr[int(i * (i + 1) // 2):int(i * (i + 1) // 2) + i + 1]) for i in range(int(nTerms))}) == 1)", "def is_madhav_array(arr):\n p = 1\n c = 2\n while p < len(arr) and arr[0] == sum(arr[p:p + c]):\n p += c\n c += 1\n return p == len(arr) > 1", "def is_madhav_array(arr):\n\n def check(a, n=1):\n return True if len(a) == n else sum(a[:n]) == sum(a[n:2 * n + 1]) and check(a[n:], n + 1)\n return False if len(arr) <= 1 else check(arr)", "def is_madhav_array(arr):\n if len(arr) < 3:\n return False\n (i, n) = (0, 1)\n value = arr[0]\n while i + n <= len(arr):\n if sum(arr[i:i + n]) != value:\n return False\n i += n\n n += 1\n return i == len(arr)", "t = [i * (i - 1) // 2 for i in range(3, 1000)]\n\ndef is_madhav_array(arr):\n if len(arr) not in t:\n return False\n sums = {arr[0], arr[1] + arr[2]}\n for (i, j) in zip(t, t[1:]):\n if j > len(arr):\n break\n sums.add(sum(arr[i:j]))\n return len(sums) == 1", "def is_madhav_array(arr):\n if len(arr) < 2:\n return False\n x = 1 + 8 * len(arr)\n if int(x ** 0.5) ** 2 != x:\n return False\n y = (int(x ** 0.5) - 1) // 2\n s = arr[0]\n for i in range(2, y + 1):\n j = i * (i - 1) // 2\n if sum(arr[j:j + i]) != s:\n return False\n return True", "def is_madhav_array(arr):\n if len(arr) <= 2:\n return False\n (i, k) = (0, 1)\n while i + k <= len(arr):\n if arr[0] != sum(arr[i:i + k]):\n return False\n if i + k == len(arr):\n return True\n i += k\n k += 1\n return False", "def is_madhav_array(arr):\n (r, x, c) = ([], 1, len(arr))\n try:\n while arr:\n t = 0\n for i in range(x):\n t += arr.pop(0)\n r.append(t)\n x += 1\n return len(set(r)) == 1 and c > 1\n except:\n return False"], "starter_code": "def is_madhav_array(arr):\n", "input_output": {"fn_name": "is_madhav_array", "inputs": [[[6, 2, 4, 2, 2, 2, 1, 5, 0, 0]], [[6, 2, 4, 2, 2, 2, 1, 5, 0, -100]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, -2, -1]], [[-6, -3, -3, 8, -5, -4]], [[-6, -3, -3, 8, -10, -4]], [[3, 1, 2, 3, 0]], [[3, 3]], [[]], [[1]], [[5, 2, 4, 1, 0, 3]], [[6, 2, 4, 2, 2, 2, 1, 5, 0, 0, -12, 13, -5, 4, 6]], [[6, 2, 4, 2, 2, 2, 1, 5, 0, 0, -12, 13, -5, 4, 1]], [[2, 1, 1]], [[2, 1, 1, 4, -1, -1]]], "outputs": [[true], [false], [true], [false], [true], [false], [false], [false], [false], [false], [true], [false], [true], [true]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/59b0492f7d3c9d7d4a0000bd", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_madhav_array", "task_id": "TACO_lite/382", "example": [[], []]} +{"requirement": "# Description\n\nWrite a function that accepts the current position of a knight in a chess board, it returns the possible positions that it will end up after 1 move. The resulted should be sorted. \n\n## Example\n\n\"a1\" -> [\"b3\", \"c2\"]", "solutions": ["def possible_positions(p):\n (r, c) = (ord(p[0]) - 96, int(p[1]))\n moves = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]\n return [''.join((chr(r + i + 96), str(c + j))) for (i, j) in moves if 1 <= r + i <= 8 and 1 <= c + j <= 8]", "def possible_positions(pos):\n col = 'abcdefgh'\n row = '12345678'\n ret = []\n dir = [[1, 2], [1, -2], [-1, 2], [-1, -2], [2, 1], [2, -1], [-2, 1], [-2, -1]]\n (c, r) = (pos[0], pos[1])\n for d in dir:\n x = col.index(c) + d[0]\n y = row.index(r) + d[1]\n if 0 <= x < 8 and 0 <= y < 8:\n ret.append(''.join([col[x], row[y]]))\n return sorted(ret)", "import string\nKNIGHT = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]\nBOARD_SIZE = 8\n\ndef moves(x, y, directions):\n for (dx, dy) in directions:\n (x2, y2) = (x + dx, y + dy)\n if 0 <= x2 < BOARD_SIZE > y2 >= 0:\n yield (x2, y2)\n\ndef possible_positions(pos):\n (x, y) = (string.ascii_lowercase.find(pos[0]), int(pos[1]) - 1)\n return [f'{string.ascii_lowercase[x]}{y + 1}' for (x, y) in moves(x, y, KNIGHT)]", "def possible_positions(pos):\n board = [[r + str(c) for c in range(1, 9)] for r in 'abcdefgh']\n (x, y) = (ord(pos[0]) - 97, int(pos[1]) - 1)\n return sorted([board[py][px] for (py, px) in [(x + 2, y + 1), (x + 2, y - 1), (x - 2, y + 1), (x - 2, y - 1), (x + 1, y + 2), (x + 1, y - 2), (x - 1, y + 2), (x - 1, y - 2)] if 0 <= px < 8 and 0 <= py < 8])", "def possible_positions(pos):\n moves = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]\n res = []\n for m in moves:\n let = chr(ord(pos[0]) + m[0])\n num = int(pos[1]) + m[1]\n if let in 'abcdefgh' and 0 < num < 9:\n res.append(let + str(num))\n return res", "def possible_positions(pos):\n abc = 'abcdefgh'\n (x, y) = (abc.index(pos[0]), int(pos[1]))\n l = [[x + 2, y - 1], [x + 2, y + 1], [x - 2, y - 1], [x - 2, y + 1], [x - 1, y + 2], [x + 1, y + 2], [x - 1, y - 2], [x + 1, y - 2]]\n m = sorted(filter(lambda x: 0 <= x[0] <= 7 and 1 <= x[1] <= 8, l), key=lambda x: (x[0], x[1]))\n return list(map(lambda x: ''.join([abc[x[0]], str(x[1])]), m))", "moves = ((-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1))\n\ndef possible_positions(pos):\n (x, y) = (ord(pos[0]) - 96, int(pos[1]))\n return [f'{chr(96 + x + i)}{y + j}' for (i, j) in moves if -i < x < 9 - i and -j < y < 9 - j]", "to_coords = lambda s: (ord(s[0]) - 96, int(s[1]))\nfrom_coords = lambda i, j: f'{chr(i + 96)}{j}'\nL = ((1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1))\n\ndef possible_positions(pos):\n (i, j) = to_coords(pos)\n return sorted((from_coords(i + k, j + l) for (k, l) in L if 0 < i + k <= 8 and 0 < j + l <= 8))", "possible_positions = lambda p, m='abcdefgh': (lambda x, y: sorted([m[e[0] + x] + str(e[1] + y) for e in [(-2, 1), (-1, 2), (1, 2), (2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1)] if 8 > e[0] + x >= 0 and 9 > e[1] + y > 0]))(m.find(p[0]), int(p[1]))", "def possible_positions(pos):\n (rows, cols) = ('abcdefgh', '12345678')\n row = rows.index(pos[0])\n col = cols.index(pos[1])\n M = [(a, b) for a in [1, -1] for b in [2, -2]]\n P = [(row + rr, col + cc) for (rr, cc) in M + [e[::-1] for e in M]]\n return sorted((rows[r] + cols[c] for (r, c) in P if 0 <= r <= 7 and 0 <= c <= 7))"], "starter_code": "def possible_positions(pos):\n", "input_output": {"fn_name": "possible_positions", "inputs": [["a1"], ["f7"], ["c3"]], "outputs": [[["b3", "c2"]], [["d6", "d8", "e5", "g5", "h6", "h8"]], [["a2", "a4", "b1", "b5", "d1", "d5", "e2", "e4"]]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5b5736abf1d553f844000050", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "possible_positions", "task_id": "TACO_lite/523", "example": [[["a1"]], ["['b3', 'c2']"]]} +{"requirement": "Write a function to calculate compound tax using the following table:\n\nFor $10 and under, the tax rate should be 10%.\nFor $20 and under, the tax rate on the first $10 is %10, and the tax on the rest is 7%.\nFor $30 and under, the tax rate on the first $10 is still %10, the rate for the next $10 is still 7%, and everything else is 5%.\nTack on an additional 3% for the portion of the total above $30.\nReturn 0 for invalid input(anything that's not a positive real number).\n\n\nExamples:\n\nAn input of 10, should return 1 (1 is 10% of 10)\nAn input of 21, should return 1.75 (10% of 10 + 7% of 10 + 5% of 1)\n\n* Note that the returned value should be rounded to the nearest penny.", "solutions": ["def tax_calculator(total):\n if not isinstance(total, (int, float)) or total < 0:\n return 0\n tax = 0\n if total > 30:\n tax = 2.2 + (total - 30) * 0.03\n elif total > 20:\n tax = 1.7 + (total - 20) * 0.05\n elif total > 10:\n tax = 1 + (total - 10) * 0.07\n elif total > 0:\n tax = total / 10.0\n return round(tax, 2)", "def tax_calculator(total):\n tax = 0\n if type(total) in (float, int) and total > 0:\n for (limit, rate) in ((30, 3), (20, 5), (10, 7), (0, 10)):\n if total > limit:\n tax += rate * (total - limit)\n total = limit\n return round(tax) / 100", "rates = ((30, 0.03), (20, 0.05), (10, 0.07), (0, 0.1))\n\ndef tax_calculator(total):\n if type(total) in (int, float) and total > 0:\n amount = 0\n for (limit, rate) in rates:\n if total > limit:\n amount += (total - limit) * rate\n total = limit\n return round(amount, 2)\n return 0", "def tax_calculator(total):\n if not isinstance(total, (int, float)) or total <= 0:\n return 0\n bands = [(10, 0.1), (10, 0.07), (10, 0.05), (None, 0.03)]\n residue = total\n tax = 0\n for (band_width, rate) in bands:\n if residue == 0:\n break\n if band_width is not None:\n chunk = residue if residue <= band_width else band_width\n else:\n chunk = residue\n tax += chunk * rate\n residue -= chunk\n return round(tax, 2)", "def tax_calculator(total):\n try:\n total = max(float(total), 0)\n except (AttributeError, TypeError, ValueError):\n total = 0\n tax = 0\n for (rate, limit) in [(0.1, 10), (0.07, 10), (0.05, 10), (0.03, 99999999999999)]:\n tax += min(total, limit) * rate\n total -= limit\n if total <= 0:\n break\n return round(tax, 2)", "from numbers import Real\ntax_calculator = TaxCalculator([(10.0, 0.1), (20.0, 0.07), (30.0, 0.05)], 0.03)\n\ndef __init__(bands, highest_rate):\n self.__table = list(self._get_table(bands, highest_rate))\n\ndef _get_table(bands, highest_rate):\n (lower_bound, cumulative_tax) = (0.0, 0.0)\n for (upper_bound, rate) in bands:\n yield (lower_bound, rate, cumulative_tax)\n cumulative_tax += (upper_bound - lower_bound) * rate\n lower_bound = upper_bound\n yield (lower_bound, highest_rate, cumulative_tax)\n\ndef __call__(amount):\n if isinstance(amount, Real):\n for (lower_bound, rate, cumulative_tax) in reversed(self.__table):\n if amount >= lower_bound:\n return round((amount - lower_bound) * rate + cumulative_tax, 2)\n return 0.0", "def tax_calculator(total):\n if type(total) not in [int, float] or total < 0:\n return 0\n if total <= 10:\n tax = 0.1 * total\n elif total <= 20:\n tax = 1 + 0.07 * (total - 10)\n else:\n tax = 1.7 + 0.05 * min(total - 20, 10)\n if total > 30:\n tax += 0.03 * (total - 30)\n return round(tax, 2)", "def tax_calculator(t):\n return isinstance(t, (float, int)) and round(max(0, t) * 0.1 - max(0, t - 10) * 0.03 - max(0, t - 20) * 0.02 - max(0, t - 30) * 0.02, 2)", "tax_calculator = lambda total: round((total - 30) * 0.03 + 2.2 if total - 30 > 0 else (total - 20) * 0.05 + 1.7 if total - 20 > 0 else (total - 10) * 0.07 + 1 if total - 10 > 0 else total * 0.1, 2) if (type(total) == int or type(total) == float) and total > 0 else 0"], "starter_code": "def tax_calculator(total):\n", "input_output": {"fn_name": "tax_calculator", "inputs": [[1], [10], [11], [15], [18], [21], [26], [30], [30.49], [35], [100], [1000000], [0], [-3], [null], ["monkey"], [[]], [{}]], "outputs": [[0.1], [1], [1.07], [1.35], [1.56], [1.75], [2], [2.2], [2.21], [2.35], [4.3], [30001.3], [0], [0], [0], [0], [0], [0]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56314d3c326bbcf386000007", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "tax_calculator", "task_id": "TACO_lite/495", "example": [[[10], [21]], ["1", "1.75"]]} +{"requirement": "You are going to be given a string. Your job is to return that string in a certain order that I will explain below:\n\nLet's say you start with this: `012345`\n\nThe first thing you do is reverse it:`543210` \nThen you will take the string from the 1st position and reverse it again:`501234` \nThen you will take the string from the 2nd position and reverse it again:`504321` \nThen you will take the string from the 3rd position and reverse it again:`504123`\n\nContinue this pattern until you have done every single position, and then you will return the string you have created. For this particular number, you would return:`504132`\n\n#Input:\nA string of length 1 - 1000\n\n#Output:\nA correctly reordered string.", "solutions": ["def reverse_fun(n):\n for i in range(len(n)):\n n = n[:i] + n[i:][::-1]\n return n", "def reverse_fun(n):\n l = len(n)\n return ''.join((b + a for (a, b) in zip(list(n[:l // 2]) + [''], n[l // 2:][::-1])))", "def reverse_fun(n, first=False):\n return '' if len(n) < 1 else n[0] + reverse_fun(n[1:]) if first else n[-1] + reverse_fun(n[:-1], True)", "from itertools import zip_longest\n\ndef merge(sequences, fillvalue=None):\n for slice in zip_longest(*sequences, fillvalue=fillvalue):\n for item in slice:\n yield item\n\ndef reverse_fun(text):\n mid = len(text) // 2\n return ''.join(merge((text[:mid - 1:-1], text[:mid]), fillvalue=''))", "def reverse_fun(n):\n string = ''\n for i in range(len(n)):\n string += n[::-1][0]\n n = n[::-1][1:]\n return string", "from itertools import chain, zip_longest\n\ndef reverse_fun(n):\n l = len(n) >> 1\n return ''.join(chain.from_iterable(zip_longest(n[:l - 1:-1], n[:l], fillvalue='')))", "def reverse_fun(n):\n from collections import deque as dq\n n = dq(n)\n n_dq = dq()\n for i in range(len(n)):\n if i == 0 or i % 2 == 0:\n n_dq.append(n.pop())\n elif i % 2 != 0:\n n_dq.append(n.popleft())\n return ''.join(n_dq)", "def reverse_fun(arr):\n for i in range(len(arr)):\n arr = arr[0:i] + arr[i:][::-1]\n return arr"], "starter_code": "def reverse_fun(n):\n", "input_output": {"fn_name": "reverse_fun", "inputs": [["012"], ["012345"], ["0123456789"], ["Hello"]], "outputs": [["201"], ["504132"], ["9081726354"], ["oHlel"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Algorithms"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/566efcfbf521a3cfd2000056", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "reverse_fun", "task_id": "TACO_lite/498", "example": [[["012345"]], ["504132"]]} +{"requirement": "This is a very simply formulated task. Let's call an integer number `N` 'green' if `N²` ends with all of the digits of `N`. Some examples:\n\n`5` is green, because `5² = 25` and `25` ends with `5`.\n\n`11` is not green, because `11² = 121` and `121` does not end with `11`.\n\n`376` is green, because `376² = 141376` and `141376` ends with `376`.\n\nYour task is to write a function `green` that returns `n`th green number, starting with `1` - `green (1) == 1`\n\n---\n\n## Data range\n\n```if:haskell\n`n <= 4000` for Haskell\n```\n```if:java\n`n <= 5000` for Java\n```\n```if:python\n`n <= 5000` for Python\n```\n```if:javascript\n`n <= 3000` for JavaScript\n\nReturn values should be `String`s, and should be exact. A BigNum library is recommended.\n```", "solutions": ["out = [1, 5, 6]\n\ndef green(n):\n f = 5\n s = 6\n q = 1\n while n >= len(out):\n q = 10 * q\n f = f ** 2 % q\n s = (1 - (s - 1) ** 2) % q\n out.extend(sorted((j for j in [f, s] if j not in out)))\n return out[n - 1]", "def green(n):\n vec = [1, 5, 6]\n m1 = 5\n m2 = 6\n tot = 3\n h = 0\n while tot < n:\n s1 = str(m1)\n s2 = str(m2)\n m1 = morph(m1)\n m2 = morph(m2)\n (tot, vec, h) = recover(str(m1), s1, str(m2), s2, vec, tot, h)\n vec.sort()\n return vec[n - 1]\n\ndef recover(p, s, r, q, vec, tot, h):\n d = len(p) - len(s)\n d2 = len(r) - len(q)\n for i in range(0, d):\n if p[d - 1 - i] != '0':\n vec.append(int(p[d - 1 - i:d] + s))\n tot += 1\n if r[d2 - 1 - i + h] != '0':\n vec.append(int(r[d2 - 1 - i + h:d2 + h] + q[h:]))\n tot += 1\n return (tot, vec, len(r) - len(p))\n\ndef morph(m):\n return (3 * m * m - 2 * m * m * m) % 10 ** (2 * len(str(m)))", "GREENS = [0, 1, 5, 6]\n(a, b) = GREENS[-2:]\nbase = 10\n\ndef is_green(n):\n return n * n % (base * 10) == n\nwhile len(GREENS) <= 5000:\n for x in range(base, base * 10, base):\n (a_, b_) = (x + a, x + b)\n if a < base and is_green(a_):\n GREENS.append(a_)\n a = a_\n if b < base and is_green(b_):\n GREENS.append(b_)\n b = b_\n base *= 10\n\ndef green(n):\n return GREENS[n]", "import functools\n\ndef automorphic(p):\n t = 1\n n = 5\n k = 1\n res = [1]\n for i in range(1, p + 1):\n size = 2 ** i\n n = (3 * n ** 2 - 2 * n ** 3) % 10 ** size\n for j in range(k, size + 1):\n m5 = n % 10 ** j\n m6 = 10 ** j + 1 - m5\n res.append(m5)\n res.append(m6)\n return sorted(list(set(res)))\n\ndef greent():\n res = automorphic(13)\n return res\n\ndef green(arg):\n return greent()[arg - 1]", "from itertools import chain\n_A018247 = 5507892033556035791371792629100237682598738962094476369972059049452967441587235634931674339622473574280821288168320446695679536039427053255909563977956500647500412691563755880886167774411122846515042057934210324478787281919538790000999616163222123020708764047374316493711188552949294878761965336956393647858527684320631232701555116292227575140464720491283762688439233984347879300562313950958674740106476704211178477509147003836984296147755270995029269684109343202879183739584798683715241551429647234717808588582623277297576686008949743753409688387939096222728882689374022112371252012273120606174751574751537381989074240665252066611148827637678947177773960015235903946894098140630385847547907319150251760258945788659491966429549908540773478285449868640866567399269578082162283572603026954569487924380165488488051064862760620827164159132523609790500938385405426324719893931802209823600162545177681029159396504506657809033052772198385286341879645511424748536307235457049044509125214234275955491843973984458712528694819826927029255264834903206526851272202961318699947776535481291519857640422968183091773445277723200737603825883172729279563657419014445235954319103063572496178988203175787761062137708080967811374931911766563031490205784352509572880668464121069252802275061298511616206384006778979402449023875111258689534549514888200678667702341002839549282970286447273625217535443197911855068157264858804852673871684804002188529473022223344541221328464844153593793663133604458940328723478401947357560361346212008675373346913314338717350880212600285752985386643931022326553454776845029957025561658143370236502074744856814787872902092412582905301249124668868351587677499891768678715728134940879276894529797097772305403356618828198702210630557967239806611190197744642421025136748701117131278125400133690086034889084364023875765936821979626181917833520492704199324875237825867148278905344897440142612317035699548419499444610608146207254036559998271588356035049327795540741961849280952093753026852390937562839148571612367351970609224242398777007574955787271559767413458997537695515862718887941516307569668816352155048898271704378508028434084412644126821848514157729916034497017892335796684991447389566001932545827678000618329854426232827257556110733160697015864984222291255485729879337147866323172405515756102352543994999345608083801190741530060056055744818709692785099775918050075416428527708162011350246806058163276171676765260937528056844214486193960499834472806721906670417240094234466197812426690787535944616698508064636137166384049029219341881909581659524477861846140912878298438431703248173428886572737663146519104988029447960814673760503957196893714671801375619055462996814764263903953007319108169802938509890062166509580863811000557423423230896109004106619977392256259918212890625\n_AUTOMORPHICS = [0, 1] + sorted(set(chain.from_iterable(((_A018247 % 10 ** i, 10 ** i + 1 - _A018247 % 10 ** i) for i in range(1, 2780)))))\ngreen = _AUTOMORPHICS.__getitem__", "(i, j, k, n) = (5, 6, 1, 0)\nl = [1]\nwhile n < 5000:\n k = 10 * k\n i = i ** 2 % k\n j = (1 - (j - 1) ** 2) % k\n l.extend(sorted((x for x in [i, j] if x not in l)))\n n = n + 1\n\ndef green(n):\n return l[n - 1]", "def green(n):\n if n < 6:\n return [1, 5, 6, 25, 76][n - 1]\n nums = ['25', '376']\n ads = ['0', '0', '0', '0', '0', '6', '9', '90', '10', '8', '7', '2', '1', '8', '2', '7', '8', '1', '8', '1', '9', '400', '9', '5', '7', '2', '6', '3', '4', '5', '7', '2', '2', '7', '9', '60', '3', '7', '2', '2', '7', '800', '9', '9', '1', '6', '3', '3', '6', '9', '10', '8', '4', '5', '900', '9', '9', '90', '10', '8', '6', '3', '10', '9', '8', '9', '30', '6', '2', '7', '3', '6', '2', '7', '4', '5', '3', '6', '2', '7', '4', '5', '7', '2', '4', '5', '4', '5', '9', '1000', '9', '9', '8', '1', '8', '8', '1', '6', '3', '6', '3', '1', '8', '9', '80', '1', '4', '5', '90', '9', '50', '4', '3', '6', '3', '6', '8', '1', '2', '7', '6', '3', '9', '900', '9', '10', '8', '90', '9', '50', '4', '1', '8', '6', '3', '9', '70', '2', '80', '9', '1', '30', '9', '6', '8', '1', '8', '1', '9', '10', '8', '9', '80', '1', '3', '6', '7', '2', '9', '300', '9', '6', '5', '4', '60', '9', '3', '90', '9', '60', '3', '6', '3', '7', '2', '4', '5', '6', '3', '2', '7', '5', '4', '1', '8', '8', '1', '3', '6', '700', '9', '9', '2', '6', '3', '5', '4', '5', '4', '4', '5', '9', '90', '80', '1', '6', '3', '4', '5', '2', '7', '6', '3', '1', '8', '80', '9', '1', '8', '1', '7', '2', '3', '6', '5', '4', '1', '8', '7', '2', '6', '3', '9', '10', '8', '3', '6', '80', '9', '1', '7', '2', '4', '5', '60', '9', '3', '50', '9', '4', '9', '60', '3', '2', '7', '6', '3', '7', '2', '3', '6', '5', '4', '1', '8', '8', '1', '9', '60', '3', '20', '9', '7', '5', '4', '4', '5', '9', '70', '2', '80', '9', '1', '1', '8', '50', '9', '4', '10', '9', '8', '9', '80', '1', '5', '4', '3', '6', '5', '4', '1', '8', '3', '6', '6', '3', '3', '6', '2', '7', '6', '3', '7', '2', '7', '2', '7', '2', '4', '5', '3', '6', '1', '8', '1', '8', '1', '8', '7', '2', '4', '5', '3', '6', '7', '2', '8', '1', '8', '1', '5', '4', '2', '7', '3', '6', '70', '9', '2', '8', '1', '3', '6', '4', '5', '8', '1', '6', '3', '4', '5', '8', '1', '70', '9', '2', '8', '1', '2', '7', '1', '8', '7', '2', '1', '8', '9', '90', '40', '5', '1', '8', '6', '3', '5', '4', '8', '1', '8', '1', '6', '3', '1', '8', '2', '7', '2', '7', '5', '4', '4', '5', '2', '7', '5', '4', '40', '9', '5', '3', '6', '8', '1', '8', '1', '4', '5', '90', '9', '90', '80', '1', '8', '1', '1', '8', '8', '1', '4', '5', '3', '6', '9', '80', '1', '2', '7', '9', '70', '2', '90', '9', '50', '4', '40', '9', '5', '8', '1', '6', '3', '6', '3', '3', '6', '8', '1', '7', '2', '6', '3', '1', '8', '6', '3', '6', '3', '6', '3', '5', '4', '6', '3', '9', '80', '1', '9', '50', '4', '1', '8', '30', '9', '6', '3', '6', '8', '1', '6', '3', '5', '4', '4', '5', '9', '40', '5', '6', '3', '5', '4', '2', '7', '1', '8', '2', '7', '9', '90', '30', '6', '3', '6', '7', '2', '4', '5', '2', '7', '1', '8', '8', '1', '2', '7', '80', '9', '1', '6', '3', '3', '6', '5', '4', '4', '5', '3', '6', '2', '7', '4', '5', '9', '90', '400', '9', '5', '2', '7', '7', '2', '8', '1', '4', '5', '70', '9', '2', '3', '6', '3', '6', '9', '90', '80', '1', '2', '7', '7', '2', '3', '6', '9', '80', '1', '7', '2', '7', '2', '5', '4', '4', '5', '3', '6', '8', '1', '500', '9', '9', '4', '60', '9', '3', '60', '9', '3', '9', '80', '1', '6', '3', '1', '8', '5', '4', '4', '5', '1', '8', '2', '7', '4', '5', '4', '5', '8', '1', '3', '6', '4', '5', '9', '80', '1', '7', '2', '5', '4', '2', '7', '6', '3', '9', '90', '60', '3', '7', '2', '5', '4', '3', '6', '2', '7', '3', '6', '2', '7', '3', '6', '8', '1', '7', '2', '8', '1', '6', '3', '2', '7', '7', '2', '3', '6', '6', '3', '8', '1', '8', '1', '4', '5', '9', '60', '3', '9', '80', '1', '3', '6', '5', '4', '2', '7', '50', '9', '4', '6', '3', '1', '8', '1', '8', '20', '9', '7', '6', '3', '8', '1', '8', '1', '9', '70', '2', '2', '7', '7', '2', '5', '4', '1', '8', '7', '2', '4', '5', '6', '3', '8', '1', '4', '5', '5', '4', '2', '7', '9', '500', '9', '4', '9', '80', '1', '8', '1', '9', '40', '5', '2', '7', '2', '7', '900', '9', '9', '50', '4', '1', '8', '2', '7', '7', '2', '9', '30', '6', '90', '9', '70', '2', '1', '8', '8', '1', '8', '1', '5', '4', '4', '5', '7', '2', '4', '5', '4', '5', '9', '60', '3', '4', '5', '9', '600', '9', '3', '9', '300', '9', '6', '5', '4', '8', '1', '4', '5', '7', '2', '9', '90', '80', '1', '1', '8', '80', '9', '1', '6', '3', '8', '1', '9', '80', '1', '9', '60', '3', '4', '5', '5', '4', '3', '6', '9', '5000', '9', '9', '4', '9', '600', '9', '3', '4', '5', '5', '4', '7', '2', '5', '4', '6', '3', '2', '7', '10', '9', '8', '6', '3', '4', '5', '2', '7', '4', '5', '8', '1', '5', '4', '4', '5', '9', '40', '5', '2', '7', '7', '2', '8', '1', '3', '6', '2', '7', '3', '6', '6', '3', '3', '6', '1', '8', '2', '7', '5', '4', '1', '8', '7', '2', '6', '3', '3', '6', '9', '20', '7', '1', '8', '70', '9', '2', '7', '2', '4', '5', '1', '8', '5', '4', '5', '4', '4', '5', '7', '2', '1', '8', '9', '70', '2', '2', '7', '2', '7', '2', '7', '4', '5', '8', '1', '50', '9', '4', '6', '3', '1', '8', '4', '5', '8', '1', '70', '9', '2', '30', '9', '6', '9', '60', '3', '8', '1', '3', '6', '3', '6', '7', '2', '9', '10', '8', '1', '8', '6', '3', '4', '5', '4', '5', '2', '7', '4', '5', '7', '2', '7', '2', '7', '2', '8', '1', '7', '2', '3', '6', '2', '7', '6', '3', '7', '2', '4', '5', '4', '5', '5', '4', '1', '8', '70', '9', '2', '3', '6', '8', '1', '8', '1', '6', '3', '9', '8000', '9', '9', '1', '2', '7', '3', '6', '2', '7', '7', '2', '8', '1', '4', '5', '5', '4', '5', '4', '7', '2', '3', '6', '9', '80', '1', '600', '9', '9', '3', '3', '6', '4', '5', '10', '9', '8', '6', '3', '7', '2', '5', '4', '4', '5', '1', '8', '9', '500', '9', '4', '8', '1', '3', '6', '3', '6', '20', '9', '7', '4', '5', '6', '3', '3', '6', '2', '7', '9', '10', '8', '2', '7', '8', '1', '70', '9', '2', '50', '9', '4', '4', '5', '3', '6', '60', '9', '3', '8', '1', '9', '700', '9', '2', '7', '2', '2', '7', '4', '5', '8', '1', '4', '5', '1', '8', '5', '4', '1', '8', '5', '4', '8', '1', '8', '1', '2', '7', '8', '1', '3', '6', '7', '2', '1', '8', '4', '5', '4', '5', '6', '3', '7', '2', '1', '8', '4', '5', '4', '5', '8', '1', '9', '40', '5', '3', '6', '4', '5', '8', '1', '7', '2', '80', '9', '1', '9', '50', '4', '1', '8', '2', '7', '6', '3', '4', '5', '70', '9', '2', '8', '1', '7', '2', '7', '2', '8', '1', '10', '9', '8', '1', '8', '5', '4', '50', '9', '4', '4', '5', '8', '1', '2', '7', '5', '4', '6', '3', '6', '3', '8', '1', '8', '1', '1', '8', '3', '6', '3', '6', '30', '9', '6', '4', '5', '2', '7', '9', '30', '6', '6', '3', '8', '1', '5', '4', '8', '1', '4', '5', '9', '20', '7', '1', '8', '1', '8', '1', '8', '8', '1', '7', '2', '7', '2', '6', '3', '1', '8', '4', '5', '8', '1', '5', '4', '4', '5', '30', '9', '6', '2', '7', '6', '3', '5', '4', '2', '7', '100', '9', '9', '8', '4', '5', '5', '4', '3', '6', '1', '8', '4', '5', '7', '2', '3', '6', '2', '7', '40', '9', '5', '4', '5', '8', '1', '7', '2', '7', '2', '7', '2', '1', '8', '2', '7', '4', '5', '4', '5', '50', '9', '4', '7', '2', '4', '5', '2', '7', '9', '700', '9', '2', '2', '7', '2', '7', '1', '8', '60', '9', '3', '2', '7', '4', '5', '2', '7', '4', '5', '2', '7', '2', '7', '9', '90', '60', '3', '9', '70', '2', '80', '9', '1', '5', '4', '6', '3', '7', '2', '3', '6', '6', '3', '2', '7', '1', '8', '6', '3', '8', '1', '7', '2', '4', '5', '1', '8', '5', '4', '1', '8', '9', '60', '3', '8', '1', '7', '2', '6', '3', '4', '5', '2', '7', '6', '3', '9', '90', '90', '60', '3', '2', '7', '5', '4', '1', '8', '3', '6', '7', '2', '30', '9', '6', '5', '4', '2', '7', '6', '3', '9', '90', '20', '7', '5', '4', '90', '9', '80', '1', '7', '2', '9', '50', '4', '8', '1', '8', '1', '6', '3', '80', '9', '1', '4', '5', '7', '2', '9', '40', '5', '5', '4', '4', '5', '20', '9', '7', '2', '7', '7', '2', '3', '6', '9', '50', '4', '50', '9', '4', '6', '3', '60', '9', '3', '4', '5', '6', '3', '8', '1', '1', '8', '4', '5', '8', '1', '7', '2', '7', '2', '8', '1', '4000', '9', '9', '9', '5', '4', '5', '3', '6', '6', '3', '40', '9', '5', '5', '4', '7', '2', '7', '2', '9', '20', '7', '6', '3', '5', '4', '1', '8', '8', '1', '9', '60', '3', '9', '10', '8', '6', '3', '5', '4', '4', '5', '4', '5', '9', '500', '9', '4', '9', '80', '1', '4', '5', '8', '1', '5', '4', '5', '4', '300', '9', '9', '6', '4', '5', '6', '3', '70', '9', '2', '8', '1', '3', '6', '2', '7', '1', '8', '6', '3', '7', '2', '4', '5', '1', '8', '40', '9', '5', '4', '5', '7', '2', '10', '9', '8', '5', '4', '4', '5', '3', '6', '5', '4', '9', '90', '10', '8', '2', '7', '7', '2', '8', '1', '5', '4', '1', '8', '7', '2', '3', '6', '1', '8', '4', '5', '7', '2', '8', '1', '2', '7', '6', '3', '2', '7', '5', '4', '2', '7', '1', '8', '5', '4', '2', '7', '3', '6', '9', '800', '9', '1', '4', '5', '70', '9', '2', '7', '2', '9', '50', '4', '20', '9', '7', '5', '4', '6', '3', '3', '6', '8', '1', '2', '7', '8', '1', '9', '80', '1', '8', '1', '8', '1', '6', '3', '7', '2', '6', '3', '20', '9', '7', '80', '9', '1', '2', '7', '8', '1', '3', '6', '6', '3', '9', '40', '5', '3', '6', '2', '7', '4', '5', '2', '7', '1', '8', '6', '3', '2', '7', '40', '9', '5', '6', '3', '6', '3', '4', '5', '8', '1', '9', '90', '10', '8', '1', '8', '5', '4', '3', '6', '60', '9', '3', '1', '8', '9', '900', '9', '30', '6', '6', '3', '3', '6', '1', '8', '400', '9', '9', '5', '5', '4', '7', '2', '1', '8', '8', '1', '2', '7', '7', '2', '1', '8', '3', '6', '1', '8', '7', '2', '8', '1', '1', '8', '1', '8', '70', '9', '2', '1', '8', '5', '4', '7', '2', '3', '6', '6', '3', '1', '8', '5', '4', '7', '2', '10', '9', '8', '2', '7', '4', '5', '2', '7', '4', '5', '6', '3', '5', '4', '4', '5', '7', '2', '2', '7', '80', '9', '1', '90', '9', '80', '1', '1', '8', '1', '8', '6', '3', '3', '6', '9', '80', '1', '60', '9', '3', '2', '7', '7', '2', '3', '6', '20', '9', '7', '4', '5', '4', '5', '9', '30', '6', '6', '3', '9', '10', '8', '2', '7', '2', '7', '70', '9', '2', '1', '8', '80', '9', '1', '8', '1', '7', '2', '8', '1', '1', '8', '8', '1', '6', '3', '3', '6', '4', '5', '6', '3', '3', '6', '40', '9', '5', '5', '4', '9', '30', '6', '2', '7', '7', '2', '2', '7', '2', '7', '90', '9', '70', '2', '20', '9', '7', '70', '9', '2', '5', '4', '5', '4', '9', '10', '8', '3', '6', '2', '7', '7', '2', '9', '20', '7', '1', '8', '9', '40', '5', '9', '50', '4', '3', '6', '1', '8', '8', '1', '7', '2', '7', '2', '4', '5', '8', '1', '7', '2', '1', '8', '2', '7', '3', '6', '1', '8', '3', '6', '2', '7', '8', '1', '9', '10', '8', '500', '9', '9', '4', '7', '2', '2', '7', '3', '6', '2', '7', '1', '8', '4', '5', '8', '1', '5', '4', '6', '3', '8', '1', '3', '6', '1', '8', '1', '8', '3', '6', '3', '6', '5', '4', '2', '7', '1', '8', '9', '50', '4', '2', '7', '1', '8', '30', '9', '6', '5', '4', '9', '90', '70', '2', '8', '1', '4', '5', '7', '2', '1', '8', '4', '5', '2', '7', '9', '90', '20', '7', '90', '9', '70', '2', '7', '2', '1', '8', '2', '7', '1', '8', '2', '7', '5', '4', '1', '8', '8', '1', '3', '6', '4', '5', '1', '8', '5', '4', '4', '5', '7', '2', '5', '4', '7', '2', '9', '20', '7', '50', '9', '4', '3', '6', '6', '3', '2', '7', '70', '9', '2', '6', '3', '3', '6', '4', '5', '1', '8', '8', '1', '4', '5', '3', '6', '8', '1', '6', '3', '4', '5', '4', '5', '7', '2', '70', '9', '2', '4', '5', '700', '9', '9', '2', '50', '9', '4', '5', '4', '8', '1', '3', '6', '2', '7', '2', '7', '5', '4', '5', '4', '5', '4', '3', '6', '5', '4', '4', '5', '3', '6', '7', '2', '3', '6', '2', '7', '2', '7', '10', '9', '8', '3', '6', '9', '60', '3', '4', '5', '6', '3', '3', '6', '1', '8', '6', '3', '5', '4', '1', '8', '70', '9', '2', '5', '4', '2', '7', '4', '5', '1', '8', '7', '2', '600', '9', '9', '3', '7', '2', '1', '8', '2', '7', '80', '9', '1', '1', '8', '9', '50', '4', '6', '3', '7', '2', '8', '1', '7', '2', '1', '8', '6', '3', '3', '6', '4', '5', '1', '8', '3', '6', '3', '6', '1', '8', '9', '30', '6', '5', '4', '3', '6', '3', '6', '7', '2', '6', '3', '5', '4', '2', '7', '3', '6', '1', '8', '9', '200', '9', '7', '1', '8', '2', '7', '6', '3', '5', '4', '3', '6', '1', '8', '6', '3', '6', '3', '60', '9', '3', '4', '5', '2', '7', '4', '5', '6', '3', '7', '2', '5', '4', '9', '80', '1', '40', '9', '5', '8', '1', '2', '7', '5', '4', '3', '6', '2', '7', '7', '2', '1', '8', '7', '2', '3', '6', '40', '9', '5', '9', '10', '8', '4', '5', '5', '4', '4', '5', '60', '9', '3', '6', '3', '3', '6', '1', '8', '3', '6', '6', '3', '3', '6', '6', '3', '9', '20', '7', '6', '3', '9', '40', '5', '6', '3', '5', '4', '8', '1', '4', '5', '4', '5', '8', '1', '5', '4', '6', '3', '5', '4', '8', '1', '7', '2', '3', '6', '1', '8', '2', '7', '2', '7', '1', '8', '4', '5', '5', '4', '5', '4', '4', '5', '3', '6', '3', '6', '2', '7', '2', '7', '2', '7', '2', '7', '30', '9', '6', '7', '2', '5', '4', '9', '70', '2', '5', '4', '1', '8', '1', '8', '8', '1', '2', '7', '400', '9', '9', '5', '80', '9', '1', '5', '4', '8', '1', '3', '6', '8', '1', '7', '2', '1', '8', '6', '3', '7', '2', '3', '6', '7', '2', '5', '4', '1', '8', '5', '4', '80', '9', '1', '1', '8', '4', '5', '1', '8', '5', '4', '6', '3', '7', '2', '7', '2', '4', '5', '8', '1', '8', '1', '3', '6', '9', '50', '4', '4', '5', '1', '8', '8', '1', '1', '8', '9', '20', '7', '80', '9', '1', '3', '6', '4', '5', '4', '5', '5', '4', '6', '3', '5', '4', '2', '7', '8', '1', '2', '7', '5', '4', '7', '2', '6', '3', '6', '3', '7', '2', '7', '2', '7', '2', '5', '4', '4', '5', '6', '3', '1', '8', '7', '2', '70', '9', '2', '70', '9', '2', '8', '1', '7', '2', '9', '50', '4', '5', '4', '60', '9', '3', '8', '1', '7', '2', '100', '9', '9', '8', '4', '5', '3', '6', '2', '7', '70', '9', '2', '2', '7', '3', '6', '3', '6', '1', '8', '2', '7', '3', '6', '9', '200', '9', '7', '8', '1', '1', '8', '1', '8', '5', '4', '1', '8', '5', '4', '50', '9', '4', '5', '4', '5', '4', '3', '6', '5', '4', '10', '9', '8', '3', '6', '1', '8', '4', '5', '7', '2', '1', '8', '1', '8', '1', '8', '5', '4', '2', '7', '1', '8', '6', '3', '2', '7', '90', '9', '50', '4', '4', '5', '2', '7', '40', '9', '5', '9', '20', '7', '10', '9', '8', '2', '7', '2', '7', '3', '6', '9', '400', '9', '5', '8', '1', '6', '3', '6', '3', '9', '20', '7', '6', '3', '8', '1', '6', '3', '8', '1', '1', '8', '5', '4', '1', '8', '70', '9', '2', '1', '8', '6', '3', '9', '50', '4', '2', '7', '7', '2', '2', '7', '80', '9', '1', '7', '2', '5', '4', '7', '2', '9', '30', '6', '9', '10', '8', '2', '7', '1', '8', '4', '5', '6', '3', '5', '4', '8', '1', '3', '6', '3', '6', '9', '80', '1', '1', '8', '7', '2', '7', '2', '4', '5', '90', '9', '50', '4', '7', '2', '5', '4', '6', '3', '4', '5', '8', '1', '2', '7', '4', '5', '9', '20', '7', '90', '9', '50', '4', '1', '8', '3', '6', '30', '9', '6', '6', '3', '4', '5', '3', '6', '3', '6', '2', '7', '8', '1', '1', '8', '9', '80', '1', '3', '6', '9', '50', '4', '7', '2', '6', '3', '1', '8', '1', '8', '8', '1', '2', '7', '3', '6', '90', '9', '80', '1', '9', '80', '1', '9', '70', '2', '2', '7', '6', '3', '1', '8', '2', '7', '6', '3', '9', '10', '8', '6', '3', '2', '7', '2', '7', '1', '8', '2', '7', '4', '5', '2', '7', '8', '1', '3', '6', '20', '9', '7', '8', '1', '1', '8', '10', '9', '8', '2', '7', '8', '1', '6', '3', '50', '9', '4', '2', '7', '7', '2', '4', '5', '6', '3', '6', '3', '9', '30', '6', '10', '9', '8', '9', '80', '1', '3', '6', '4', '5', '5', '4', '40', '9', '5', '6', '3', '2', '7', '5', '4', '5', '4', '4', '5', '4', '5', '1', '8', '90', '9', '80', '1', '4', '5', '7', '2', '4', '5', '3', '6', '6', '3', '6', '3', '4', '5', '20', '9', '7', '7', '2', '9', '70', '2', '7', '2', '7', '2', '7', '2', '8', '1', '3', '6', '8', '1', '1', '8', '4', '5', '7', '2', '8', '1', '6', '3', '60', '9', '3', '2', '7', '6', '3', '7', '2', '9', '200', '9', '7', '3', '6', '2', '7', '7', '2', '2', '7', '2', '7', '7', '2', '5', '4', '5', '4', '4', '5', '3', '6', '7', '2', '2', '7', '8', '1', '9', '90', '30', '6', '8', '1', '8', '1', '8', '1', '3', '6', '70', '9', '2', '2', '7', '4', '5', '40', '9', '5', '6', '3', '2', '7', '4', '5', '1', '8', '80', '9', '1', '5', '4', '8', '1', '9', '70', '2', '1', '8', '8', '1', '5', '4', '5', '4', '6', '3', '5', '4', '3', '6', '2', '7', '2', '7', '2', '7', '5', '4', '9', '3000', '9', '9', '6', '1', '8', '8', '1', '3', '6', '1', '8', '6', '3', '70', '9', '2', '20', '9', '7', '2', '7', '7', '2', '7', '2', '1', '8', '5', '4', '1', '8', '3', '6', '7', '2', '5', '4', '3', '6', '9', '20', '7', '3', '6', '90', '9', '50', '4', '3', '6', '8', '1', '5', '4', '6', '3', '7', '2', '5', '4', '4', '5', '7', '2', '9', '70', '2', '70', '9', '2', '7', '2', '9', '30', '6', '7', '2', '8', '1', '80', '9', '1', '8', '1', '5', '4', '9', '30', '6', '1', '8', '7', '2', '5', '4', '7', '2', '1', '8', '7', '2', '1', '8', '4', '5', '5', '4', '4', '5', '8', '1', '60', '9', '3', '7', '2', '60', '9', '3', '4', '5', '8', '1', '8', '1', '9', '50', '4', '5', '4', '4', '5', '40', '9', '5', '2', '7', '7', '2', '4', '5', '3', '6', '2', '7', '4', '5', '1', '8', '2', '7', '5', '4', '7', '2', '1', '8', '9', '90', '50', '4', '5', '4', '4', '5', '90', '9', '50', '4', '70', '9', '2', '4', '5', '5', '4', '5', '4', '6', '3', '2', '7', '7', '2', '9', '30', '6', '6', '3', '6', '3', '5', '4', '1', '8', '5', '4', '7', '2', '5', '4', '2', '7', '4', '5', '1', '8', '1', '8', '5', '4', '4', '5', '5', '4', '6', '3', '20', '9', '7', '1', '8', '8', '1', '4', '5', '3', '6', '6', '3', '1', '8', '7', '2', '5', '4', '1', '8', '6', '3', '8', '1', '80', '9', '1', '2', '7', '7', '2', '2', '7', '7', '2', '5', '4', '9', '30', '6', '3', '6', '90', '9', '90', '80', '1', '2', '7', '4', '5', '3', '6', '3', '6', '9', '50', '4', '5', '4', '50', '9', '4', '3', '6', '60', '9', '3', '9', '40', '5', '8', '1', '9', '70', '2', '10', '9', '8', '8', '1', '3', '6', '2', '7', '2', '7', '8', '1', '5', '4', '5', '4', '5', '4', '7', '2', '6', '3', '8', '1', '600', '9', '9', '3', '6', '3', '2', '7', '8', '1', '90', '9', '20', '7', '2', '7', '80', '9', '1', '8', '1', '3', '6', '9', '60', '3', '9', '10', '8', '80', '9', '1', '7', '2', '5', '4', '2', '7', '3', '6', '6', '3', '7', '2', '4', '5', '5', '4', '9', '40', '5', '5', '4', '1', '8', '6', '3', '8', '1', '6', '3', '9', '90', '500', '9', '4', '9', '90', '20', '7', '90', '9', '60', '3', '6', '3', '2', '7', '5', '4', '7', '2', '3', '6', '1', '8', '9', '40', '5', '8', '1', '4', '5', '6', '3', '8', '1', '7', '2', '7', '2', '8', '1', '9', '20', '7', '6', '3', '9', '60', '3', '2', '7', '7', '2', '6', '3', '1', '8', '5', '4', '6', '3', '9', '10', '8', '5', '4', '9', '80', '1', '1', '8', '5', '4', '8', '1', '1', '8', '5', '4', '5', '4', '3', '6', '8', '1', '80', '9', '1', '6', '3', '4', '5', '2', '7', '9', '20', '7', '1', '8', '5', '4', '9', '30', '6', '4', '5', '5', '4', '5', '4', '30', '9', '6', '7', '2', '30', '9', '6', '60', '9', '3', '7', '2', '7', '2', '4', '5', '6', '3', '8', '1', '7', '2', '2', '7', '6', '3', '8', '1', '2', '7', '8', '1', '9', '80', '1', '2', '7', '4', '5', '30', '9', '6', '7', '2', '9', '600', '9', '3', '7', '2', '3', '6', '4', '5', '3', '6', '3', '6', '1', '8', '9', '40', '5', '6', '3', '1', '8', '3', '6', '1', '8', '50', '9', '4', '4', '5', '5', '4', '1', '8', '7', '2', '8', '1', '2', '7', '5', '4', '3', '6', '7', '2', '2', '7', '9', '40', '5', '5', '4', '1', '8', '9', '90', '500', '9', '4', '5', '4', '70', '9', '2', '4', '5', '6', '3', '3', '6', '80', '9', '1', '9', '50', '4', '9', '40', '5', '3', '6', '1', '8', '1', '8', '2', '7', '4', '5', '5', '4', '9', '10', '8', '4', '5', '7', '2', '60', '9', '3', '2', '7', '8', '1', '5', '4', '7', '2', '50', '9', '4', '8', '1', '9', '80', '1', '3', '6', '7', '2', '9', '90', '20', '7', '5', '4', '5', '4', '2', '7', '5', '4', '8', '1', '4', '5', '1', '8', '6', '3', '30', '9', '6', '6', '3', '9', '40', '5', '1', '8', '8', '1', '90', '9', '40', '5', '9', '10', '8', '3', '6', '5', '4', '9', '60', '3', '90', '9', '40', '5', '6', '3', '2', '7', '5', '4', '8', '1', '600', '9', '9', '3', '60', '9', '3', '7', '2', '2', '7', '2', '7', '2', '7', '8', '1', '7', '2', '5', '4', '9', '10', '8', '2', '7', '3', '6', '2', '7', '6', '3', '6', '3', '2', '7', '7', '2', '8', '1', '1', '8', '5', '4', '1', '8', '1', '8', '1', '8', '6', '3', '3', '6', '3', '6', '9', '20', '7', '5', '4', '7', '2', '5', '4', '3', '6', '3', '6', '9', '40', '5', '2', '7', '4', '5', '7', '2', '9', '90', '10', '8', '80', '9', '1', '8', '1', '6', '3', '7', '2', '6', '3', '5', '4', '8', '1', '5', '4', '2', '7', '5', '4', '7', '2', '4', '5', '8', '1', '5', '4', '2', '7', '5', '4', '7', '2', '8', '1', '6', '3', '9', '60', '3', '9', '20', '7', '1', '8', '3', '6', '7', '2', '7', '2', '2', '7', '1', '8', '20', '9', '7', '5', '4', '7', '2', '1', '8', '7', '2', '6', '3', '2', '7', '1', '8', '1', '8', '2', '7', '2', '7', '40', '9', '5', '7', '2', '6', '3', '9', '10', '8', '3', '6', '7', '2', '8', '1', '1', '8', '1', '8', '7', '2', '7', '2', '7', '2', '2', '7', '2', '7', '6', '3', '90', '9', '90', '60', '3', '9', '20', '7', '1', '8', '6', '3', '8', '1', '1', '8', '3', '6', '90', '9', '40', '5', '3', '6', '5', '4', '2', '7', '6', '3', '4', '5', '7', '2', '50', '9', '4', '9', '10', '8', '9', '600', '9', '3', '1', '8', '3', '6', '3', '6', '2', '7', '4', '5', '2', '7', '70', '9', '2', '7', '2', '2', '7', '7', '2', '3', '6', '2', '7', '6', '3', '7', '2', '8', '1', '4', '5', '1', '8', '1', '8', '4', '5', '1', '8', '9', '80', '1', '2', '7', '8', '1', '7', '2', '5', '4', '3', '6', '2', '7', '7', '2', '5', '4', '6', '3', '70', '9', '2', '4', '5', '1', '8', '5', '4', '4', '5', '8', '1', '4', '5', '2', '7', '5', '4', '8', '1', '7', '2', '6', '3', '8', '1', '3', '6', '1', '8', '20', '9', '7', '5', '4', '8', '1', '4', '5', '60', '9', '3', '7', '2', '6', '3', '8', '1', '8', '1', '9', '20', '7', '1', '8', '7', '2', '20', '9', '7', '3', '6', '4', '5', '3', '6', '9', '90', '10', '8', '4', '5', '8', '1', '3', '6', '30', '9', '6', '7', '2', '9', '70', '2', '50', '9', '4', '900', '9', '9', '70', '2', '7', '2', '5', '4', '4', '5', '2', '7', '2', '7', '5', '4', '1', '8', '6', '3', '70', '9', '2', '4', '5', '8', '1', '30', '9', '6', '6', '3', '8', '1', '6', '3', '700', '9', '9', '2', '5', '4', '1', '8', '9', '90', '50', '4', '2', '7', '2', '7', '5', '4', '8', '1', '2', '7', '8', '1', '1', '8', '1', '8', '2', '7', '4', '5', '70', '9', '2', '3', '6', '2', '7', '5', '4', '6', '3', '9', '10', '8', '40', '9', '5', '7', '2', '5', '4', '7', '2', '3', '6', '1', '8', '4', '5', '90', '9', '50', '4', '60', '9', '3', '1', '8', '3', '6', '2', '7', '6', '3', '4', '5', '9', '300', '9', '6', '9', '20', '7', '1', '8', '2', '7', '5', '4', '3', '6', '4', '5', '8', '1', '60', '9', '3', '3', '6', '2', '7', '9', '60', '3', '4', '5', '8', '1', '1', '8', '3', '6', '7', '2', '6', '3', '2', '7', '6', '3', '8', '1', '7', '2', '1', '8', '9', '50', '4', '20', '9', '7', '7', '2', '5', '4', '6', '3', '5', '4', '40', '9', '5', '1', '8', '5', '4', '2', '7', '4', '5', '2', '7', '7', '2', '2', '7', '2', '7', '9', '70', '2', '6', '3', '8', '1', '1', '8', '5', '4', '4', '5', '4', '5', '8', '1', '70', '9', '2', '7', '2', '3', '6', '2', '7', '1', '8', '3', '6', '6', '3', '9', '20', '7', '3', '6', '4', '5', '8', '1', '3', '6', '2', '7', '7', '2', '5', '4', '1', '8', '4', '5', '1', '8', '2', '7', '5', '4', '6', '3', '6', '3', '9', '60', '3', '6', '3', '4', '5', '30', '9', '6', '6', '3', '3', '6', '5', '4', '3', '6', '80', '9', '1', '6', '3', '2', '7', '1', '8', '2', '7', '1', '8', '5', '4', '9', '70', '2', '9', '50', '4', '9', '70', '2', '5', '4', '4', '5', '1', '8', '1', '8', '8', '1', '1', '8', '1', '8', '7', '2', '6', '3', '9', '50', '4', '6', '3', '8', '1', '3', '6', '4', '5', '7', '2', '6', '3', '7', '2', '5', '4', '40', '9', '5', '6', '3', '2', '7', '1', '8', '9', '70', '2', '9', '20', '7', '30', '9', '6', '2', '7', '1', '8', '2', '7', '2', '7', '2', '7', '3', '6', '6', '3', '8', '1', '6', '3', '8', '1', '6', '3', '9000', '9', '9', '9', '90000', '9', '9', '9', '20', '7', '1', '8', '6', '3', '5', '4', '80', '9', '1', '9', '80', '1', '8', '1', '7', '2', '7', '2', '1', '8', '2', '7', '1', '8', '2', '7', '5', '4', '4', '5', '2', '7', '3', '6', '10', '9', '8', '2', '7', '4', '5', '3', '6', '9', '20', '7', '4', '5', '9', '20', '7', '4', '5', '50', '9', '4', '8', '1', '5', '4', '3', '6', '5', '4', '8', '1', '7', '2', '2', '7', '1', '8', '1', '8', '1', '8', '4', '5', '4', '5', '7', '2', '2', '7', '2', '7', '3', '6', '8', '1', '6', '3', '1', '8', '1', '8', '9', '80', '1', '1', '8', '4', '5', '4', '5', '2', '7', '6', '3', '6', '3', '4', '5', '8', '1', '9', '30', '6', '7', '2', '1', '8', '4', '5', '500', '9', '9', '4', '2', '7', '5', '4', '6', '3', '9', '500', '9', '4', '3', '6', '4', '5', '20', '9', '7', '2', '7', '60', '9', '3', '6', '3', '4', '5', '90', '9', '90', '40', '5', '4', '5', '7', '2', '3', '6', '5', '4', '9', '70', '2', '7', '2', '4', '5', '9', '60', '3', '60', '9', '3', '6', '3', '5', '4', '20', '9', '7', '3', '6', '4', '5', '30', '9', '6', '3', '6', '5', '4', '4', '5', '20', '9', '7', '3', '6', '8', '1', '3', '6', '8', '1', '8', '1', '1', '8', '7', '2', '1', '8', '2', '7', '8', '1', '9', '80', '1', '7', '2', '4', '5', '7', '2', '4', '5', '6', '3', '7', '2', '5', '4', '2', '7', '2', '7', '6', '3', '60', '9', '3', '3', '6', '4', '5', '7', '2', '3', '6', '8', '1', '3', '6', '9', '50', '4', '3', '6', '6', '3', '4', '5', '6', '3', '2', '7', '7', '2', '1', '8', '4', '5', '8', '1', '4', '5', '4', '5', '7', '2', '3', '6', '70', '9', '2', '5', '4', '5', '4', '9', '50', '4', '90', '9', '40', '5', '9', '20', '7', '7', '2', '300', '9', '9', '6', '6', '3', '6', '3', '2', '7', '5', '4', '4', '5', '9', '90', '20', '7', '6', '3', '10', '9', '8', '6', '3', '7', '2', '1', '8', '40', '9', '5', '7', '2', '8', '1', '3', '6', '2', '7', '6', '3', '2', '7', '100', '9', '9', '8', '9', '70', '2', '6', '3', '7', '2', '9', '20', '7', '8', '1', '7', '2', '6', '3', '1', '8', '9', '20', '7', '4', '5', '6', '3', '60', '9', '3', '4', '5', '4', '5', '6', '3', '3', '6', '20', '9', '7', '9', '10', '8', '2', '7', '9', '50', '4', '4', '5']\n count = 5\n while n > count:\n nums[0] = ads[count] + nums[0]\n if len(nums[0]) > len(nums[1]):\n (nums[0], nums[1]) = (nums[1], nums[0])\n elif len(nums[0]) == len(nums[1]):\n nums.sort()\n count += 1\n return int(nums[0])"], "starter_code": "def green(n):\n", "input_output": {"fn_name": "green", "inputs": [[1], [2], [3], [4], [12], [13], [100], [110]], "outputs": [[1], [5], [6], [25], [2890625], [7109376], [6188999442576576769103890995893380022607743740081787109376], [9580863811000557423423230896109004106619977392256259918212890625]]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/584dee06fe9c9aef810001e8", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "green", "task_id": "TACO_lite/528", "example": [[[1]], ["1"]]} +{"requirement": "Given string s containing characters as integers only, the task is to delete all characters of this string in a minimum number of steps wherein one step you can delete the substring which is a palindrome. After deleting a substring remaining parts are concatenated.\nExample 1:\nInput: s = \"2553432\"\nOutput: 2\nExplanation: In first step remove \"55\", \nthen string becomes \"23432\" which is a \npalindrome.\nExample 2:\nInput: s = \"1234\"\nOutput: 4\nExplanation: Remove each character in \neach step\nYour Task: \nYou don't need to read input or print anything. Complete the function minStepToDeleteString() which string s as input parameters and returns the integer value\nExpected Time Complexity: O(|s|^{3})\nExpected Auxiliary Space: O(|s|^{2})\nConstraints:\n1 ≤ |s| ≤ 10^{3}", "solutions": ["def solve(s, dp, start, end):\n if start > end:\n return 0\n if start == end:\n return 1\n if dp[start][end] != -1:\n return dp[start][end]\n op1 = op2 = op3 = 1000000000.0\n op1 = 1 + self.solve(s, dp, start + 1, end)\n if s[start] == s[start + 1]:\n op2 = 1 + self.solve(s, dp, start + 2, end)\n for i in range(start + 2, end + 1):\n if s[start] == s[i]:\n op3 = min(op3, self.solve(s, dp, start + 1, i - 1) + self.solve(s, dp, i + 1, end))\n dp[start][end] = min(op1, op2, op3)\n return dp[start][end]\n\ndef minsteptodeletestring(s):\n n = len(s)\n dp = [[-1 for _ in range(n)] for _ in range(n)]\n return self.solve(s, dp, 0, n - 1)", "def minsteptodeletestring(str):\n N = len(str)\n dp = [[0 for x in range(N + 1)] for y in range(N + 1)]\n for l in range(1, N + 1):\n i = 0\n j = l - 1\n while j < N:\n if l == 1:\n dp[i][j] = 1\n else:\n dp[i][j] = 1 + dp[i + 1][j]\n if str[i] == str[i + 1]:\n dp[i][j] = min(1 + dp[i + 2][j], dp[i][j])\n for K in range(i + 2, j + 1):\n if str[i] == str[K]:\n dp[i][j] = min(dp[i + 1][K - 1] + dp[K + 1][j], dp[i][j])\n i += 1\n j += 1\n return dp[0][N - 1]", "import sys\nINT_MAX = sys.maxsize\n\ndef min_steps(l, r, s, dp):\n if l > r:\n return 0\n if l == r:\n return 1\n if dp[l][r] != -1:\n return dp[l][r]\n (op1, op2, op3) = (INT_MAX, INT_MAX, INT_MAX)\n op1 = 1 + self.min_steps(l + 1, r, s, dp)\n if s[l] == s[l + 1]:\n op2 = 1 + self.min_steps(l + 2, r, s, dp)\n for i in range(l + 2, r + 1):\n if s[l] == s[i]:\n op3 = min(op3, self.min_steps(l + 1, i - 1, s, dp) + self.min_steps(i + 1, r, s, dp))\n dp[l][r] = min(op1, op2, op3)\n return dp[l][r]\n\ndef minsteptodeletestring(s):\n n = len(s)\n dp = [[-1 for _ in range(n)] for _ in range(n)]\n return self.min_steps(0, n - 1, s, dp)", "import sys\nINT_MAX = sys.maxsize\n\ndef min_steps(i, j, s, dp):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n min_steps = 1 + self.min_steps(i + 1, j, s, dp)\n if s[i] == s[i + 1]:\n min_steps = 1 + min(min_steps, self.min_steps(i + 2, j, s, dp))\n for k in range(i + 2, j + 1):\n if s[i] == s[k]:\n steps = self.min_steps(i + 1, k - 1, s, dp) + self.min_steps(k + 1, j, s, dp)\n min_steps = min(min_steps, steps)\n dp[i][j] = min_steps\n return dp[i][j]\n\ndef minsteptodeletestring(s):\n n = len(s)\n dp = [[-1 for _ in range(n)] for _ in range(n)]\n return self.min_steps(0, n - 1, s, dp)", "def minsteptodeletestring(s):\n n = len(s)\n dp = [[0 for i in range(n + 1)] for j in range(n + 1)]\n for i in range(n):\n dp[i][i] = 1\n j = 1\n while j < n:\n for i in range(n - j):\n dp[i][i + j] = 1 + min(dp[i][i + j - 1], dp[i + 1][i + j])\n for k in range(i + 1, i + j + 1):\n if s[i] == s[k]:\n a = dp[i + 1][k - 1]\n if i + 1 > k - 1:\n a = 1\n b = dp[k + 1][i + j]\n dp[i][i + j] = min(dp[i][i + j], a + b)\n j += 1\n return dp[0][n - 1]", "def minsteptodeletestring(s):\n\n def solve(f, l, d):\n if l < f:\n return 0\n if f == l:\n return 1\n if (f, l) in d:\n return d[f, l]\n (first, second) = (float('inf'), float('inf'))\n first = 1 + solve(f + 1, l, d)\n if s[f] == s[f + 1]:\n second = 1 + solve(f + 2, l, d)\n third = float('inf')\n for i in range(f + 2, l + 1):\n if s[f] == s[i]:\n third = min(third, solve(f + 1, i - 1, d) + solve(i + 1, l, d))\n d[f, l] = min(first, second, third)\n return d[f, l]\n d = {}\n res = solve(0, len(s) - 1, d)\n return res", "def minsteptodeletestring(s):\n n = len(s)\n dp = [[0 for i in range(n + 1)] for i in range(n + 1)]\n for l in range(1, n + 1):\n (i, j) = (0, l - 1)\n while j < n:\n if l == 1:\n dp[i][j] = 1\n else:\n dp[i][j] = 1 + dp[i + 1][j]\n if s[i] == s[i + 1]:\n dp[i][j] = min(1 + dp[i + 2][j], dp[i][j])\n for k in range(i + 2, j + 1):\n if s[i] == s[k]:\n dp[i][j] = min(dp[i + 1][k - 1] + dp[k + 1][j], dp[i][j])\n i += 1\n j += 1\n return dp[0][n - 1]", "import functools\n\ndef minsteptodeletestring(s):\n\n def delete_substring(start_idx, end_idx):\n if start_idx == end_idx:\n return 1\n if start_idx > end_idx:\n return 0\n first_case = delete_substring(start_idx + 1, end_idx) + 1\n second_case = float('inf')\n for idx in range(start_idx + 1, end_idx + 1):\n if s[idx] == s[start_idx]:\n if idx == start_idx + 1:\n second_case = min(second_case, delete_substring(start_idx + 2, end_idx)) + 1\n else:\n second_case = min(second_case, delete_substring(start_idx + 1, idx - 1) + delete_substring(idx + 1, end_idx))\n return min(first_case, second_case)\n return delete_substring(0, len(s) - 1)", "def minsteptodeletestring(s):\n N = len(s)\n dp = [[0 for i in range(N + 1)] for j in range(N + 1)]\n for gap in range(1, N + 1):\n i = 0\n j = gap - 1\n while j < N:\n if gap == 1:\n dp[i][j] = 1\n else:\n dp[i][j] = 1 + dp[i + 1][j]\n if s[i] == s[i + 1]:\n dp[i][j] = min(1 + dp[i + 2][j], dp[i][j])\n for K in range(i + 2, j + 1):\n if s[i] == s[K]:\n dp[i][j] = min(dp[i + 1][K - 1] + dp[K + 1][j], dp[i][j])\n i += 1\n j += 1\n return dp[0][N - 1]", "def minsteptodeletestring(s):\n cache = {}\n\n def dp(i, j):\n if (i, j) in cache:\n return cache[i, j]\n if i > j:\n cache[i, j] = 0\n return cache[i, j]\n if i == j:\n cache[i, j] = 1\n return cache[i, j]\n cache[i, j] = float('inf')\n for k in range(i, j + 1):\n if s[i] == s[k]:\n temp = 1 + dp(k + 1, j) if k - i <= 1 else dp(i + 1, k - 1) + dp(k + 1, j)\n cache[i, j] = min(cache[i, j], temp)\n return cache[i, j]\n return dp(0, len(s) - 1)", "def minsteptodeletestring(s):\n length = len(s)\n if length < 1:\n return 0\n if length < 2:\n return 1\n lookup_min_steps = [[0] * length for i in range(length)]\n for i in range(length):\n lookup_min_steps[i][i] = 1\n for len_str in range(2, length + 1):\n for i in range(0, length - len_str + 1):\n j = i + len_str - 1\n min_steps = length\n min_steps = min(min_steps, lookup_min_steps[i][j - 1] + 1)\n for k in range(i, j):\n if s[k] == s[j]:\n if k == j - 1:\n min_steps = min(min_steps, lookup_min_steps[i][k - 1] + 1)\n else:\n min_steps = min(min_steps, lookup_min_steps[i][k - 1] + lookup_min_steps[k + 1][j - 1])\n lookup_min_steps[i][j] = min_steps\n return lookup_min_steps[0][length - 1]", "def minsteptodeletestring(str1):\n n = len(str1)\n dp = [[0] * (n + 1) for _ in range(n + 1)]\n for l in range(1, n + 1):\n i = 0\n j = l - 1\n while j < n:\n if l == 1:\n dp[i][j] = 1\n else:\n dp[i][j] = 1 + dp[i + 1][j]\n if str1[i] == str1[i + 1]:\n dp[i][j] = min(1 + dp[i + 2][j], dp[i][j])\n for K in range(i + 2, j + 1):\n if str1[i] == str1[K]:\n dp[i][j] = min(dp[i + 1][K - 1] + dp[K + 1][j], dp[i][j])\n i += 1\n j += 1\n return dp[0][n - 1]"], "starter_code": "def minsteptodeletestring(s):\n", "input_output": {"inputs": ["s = \"2553432\"", "s = \"1234\""], "outputs": ["2", "4"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/minimum-steps-to-delete-a-string2956/1", "Expected Auxiliary Space": "O(|s|^{2})", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|s|^{3})", "entry_point": "minsteptodeletestring", "task_id": "TACO_lite/526", "example": [[["2553432"], ["1234"]], ["2", "4"]]} +{"requirement": "Given a binary tree of size N, find all the nodes at odd levels.Root is considered at level 1.\nExample 1:\nInput: \n 1\n / \\\n 2 3\n / \\ \\\n 4 5 6\n / \\ /\n 7 8 9\nOutput 1 4 5 6\nExample 2:\nInput: \n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n \nOutput: 1 4 5 6 7\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function nodesAtOddLevels() which takes root node of the tree as input parameter and returns an list of all the nodes at odd levels in preorder.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 <= Number of nodes <= 10^{3}\n1 <= Data of a node <= 10^{3}", "solutions": ["def nodesAtOddLevels(root):\n q = [root]\n res = []\n lev = 1\n while q:\n l = len(q)\n for i in range(l):\n p = q.pop(0)\n if lev % 2 != 0:\n res.append(p.data)\n if p.left:\n q.append(p.left)\n if p.right:\n q.append(p.right)\n lev += 1\n return res", "from collections import deque\n\ndef nodesAtOddLevels(root):\n queue = deque()\n queue.append(root)\n ans_list = []\n level = 0\n while queue:\n size = len(queue)\n for _ in range(size):\n curr = queue.popleft()\n if level % 2 != 0:\n ans_list.append(curr.data)\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n return ans_list", "def findNodes(root, res, l):\n if root == None:\n return res\n if l % 2 == 1:\n res.append(root)\n findNodes(root.left, res, l + 1)\n findNodes(root.right, res, l + 1)\n return res\n\ndef nodesAtOddLevels(root):\n return findNodes(root, [], 1)", "def fun(root, level, l):\n if root == None:\n return\n if level >= len(l):\n l.append([])\n l[level].append(root.data)\n self.fun(root.left, level + 1, l)\n self.fun(root.right, level + 1, l)\n\ndef nodesAtOddLevels(root):\n l = []\n self.fun(root, 0, l)\n t = []\n for i in range(len(l)):\n if i % 2 == 0:\n t.extend(l[i])\n return t", "def solve(root, dic, l):\n if root == None:\n return\n if l % 2 != 0:\n dic.append(root.data)\n l += 1\n self.solve(root.left, dic, l)\n self.solve(root.right, dic, l)\n l -= 1\n\ndef nodesAtOddLevels(root):\n dic = []\n self.solve(root, dic, 1)\n return dic", "def getNodesFromOddLevel(root, level: int=1):\n if root is None:\n return []\n elif level % 2:\n return [root.data] + self.getNodesFromOddLevel(root.left, level + 1) + self.getNodesFromOddLevel(root.right, level + 1)\n else:\n return self.getNodesFromOddLevel(root.left, level + 1) + self.getNodesFromOddLevel(root.right, level + 1)\n\ndef nodesAtOddLevels(root):\n return self.getNodesFromOddLevel(root, 1)", "def nodesAtOddLevels(root):\n values = []\n queue = [root]\n count = 0\n while queue:\n count += 1\n level = []\n for i in queue:\n if i == None:\n continue\n if count % 2 != 0:\n values.append(i.data)\n level.append(i.left)\n level.append(i.right)\n queue = level\n return values", "def nodesAtOddLevels(root):\n q = [root]\n count = 1\n list = []\n while q:\n if count % 2 != 0:\n for i in q:\n list.append(i.data)\n for _ in range(len(q)):\n node = q.pop(0)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return list", "def nodesAtOddLevels(root):\n\n def levelOrder(self, root):\n\n def height(node):\n if node is None:\n return 0\n else:\n lheight = height(node.left)\n rheight = height(node.right)\n if lheight > rheight:\n return lheight + 1\n else:\n return rheight + 1\n\n def currlvl(root, lvl):\n if root is None:\n return\n elif lvl % 2 != 0:\n res.append(root.data)\n elif lvl > 1:\n currlvl(root.left, lvl - 1)\n currlvl(root.right, lvl - 1)\n res = []\n h = height(root)\n for i in range(1, h + 1):\n currlvl(root, i)\n return res", "def getNod(root, arr, lev):\n if not root:\n return\n if lev % 2 != 0:\n arr.append(root.data)\n self.getNod(root.left, arr, lev + 1)\n self.getNod(root.right, arr, lev + 1)\n\ndef nodesAtOddLevels(root):\n arr = []\n self.getNod(root, arr, 1)\n return arr", "def nodesAtOddLevels(root):\n return lll(root, 1, [])\n\ndef lll(root, l, arr):\n if root is None:\n return\n if l % 2:\n arr.append(root.data)\n lll(root.left, l + 1, arr)\n lll(root.rihjt, l + 1, arr)\n return arr", "def nodesAtOddLevels(root):\n n = root\n arr = []\n stack = [n]\n while stack:\n n = stack.pop()\n if n is not None:\n arr.append(n.data)\n stack.append(n.right)\n stack.append(n.left)\n return arr", "def nodesAtOddLevels(root):\n if root is None:\n return []\n q = []\n q.append(root)\n counter = 0\n ans = []\n while len(q) > 0:\n counter += 1\n t = []\n while len(q) != 0:\n x = st.pop(0)\n if x.left is not None:\n t.append(x.left)\n if x.right is not None:\n t.append(x.right)\n if counter % 2 != 0:\n ans.append(x.data)\n q = t\n return ans", "def nodesAtOddLevels(root):\n q = []\n q.append(root)\n arr = []\n x = 1\n while q:\n l = len(q)\n lis = []\n for i in range(l):\n temp = q.pop(0)\n lis.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n if x == 1:\n arr.extend(lis)\n x = 0\n elif x == 0:\n x = 1\n return arr", "def nodesAtOddLevels(root):\n c = 1\n s1 = []\n queue = [root]\n while queue != []:\n t = []\n for i in range(len(queue)):\n curr = queue[0]\n t.append(curr.data)\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n queue.pop(0)\n if c % 2 == 1:\n s1.extend(t)\n c += 1\n elif c % 2 != 1:\n c += 1\n return s1", "def nodesAtOddLevels(root):\n d = []\n q = []\n g = {}\n if root == None:\n ans = []\n return ans\n d.append(root)\n q.append(0)\n while len(d) > 0:\n c = d.pop(0)\n m = q.pop(0)\n if m not in g:\n g[m] = [c.data]\n else:\n g[m].append(c.data)\n if c.left != None:\n d.append(c.left)\n q.append(m + 1)\n if c.right != None:\n d.append(c.right)\n q.append(m + 1)\n l = []\n for x in g:\n if x % 2 != 0:\n for i in range(0, len(g[x])):\n l.append(g[x][i])\n return l", "def nodesAtOddLevels(root):\n queue = deque([(root, 1)])\n l = []\n while queue:\n (node, h) = queue.popleft()\n if node.left is None and node.right is None and (h % 2 == 1):\n l.append(node.data)\n if node.left is not None:\n queue.append((node.left, h + 1))\n if node.right is not None:\n queue.append((node.right, h + 1))\n return l", "def nodesAtOddLevels(root):\n if root is None:\n return\n q = [root]\n res = []\n flag = 1\n while len(q) != 0:\n root = q.pop(0)\n if flag % 2 != 0:\n res.append(root.data)\n flag += 1\n if root.left:\n q.append(root.left)\n if root.right:\n q.append(root.right)\n return res", "def depthOfOddLeaf(root):\n arr = []\n level = 1\n q = []\n q.append(root)\n while len(q) != 0:\n for i in range(len(q)):\n node = q.pop(0)\n if node.left != None:\n q.append(node.left)\n if node.right != None:\n q.append(node.right)\n if level % 2 == 1:\n arr.append(level)\n level += 1\n return arr", "def nodesAtOddLevels(root):\n q = []\n q.append(root)\n ans = []\n p = 1\n while len(q):\n count = len(q)\n while count > 0:\n p = q.pop(0)\n if p % 2 == 1:\n ans.append(p.data)\n if p.left:\n q.append(p.left)\n if p.right:\n q.append(p.right)\n count -= 1\n p += 1\n return ans", "def nodesAtOddLevels(root):\n if not root:\n return []\n stack = [root]\n ans = []\n level = 1\n while stack:\n temp = []\n for i in range(len(stack)):\n node = stack.pop(0)\n if node.left:\n stack.append(node.left)\n if node.right != None:\n stack.append(node.right)\n temp.append(node.data)\n if temp != [] and level % 2 == 1:\n ans.append(temp)\n level += 1\n return ans", "def nodesAtOddLevels(root):\n global a\n a = []\n\n def sol(root, level):\n global a\n if root:\n if level % 2 == 0:\n a.append(root.data)\n sol(root.left, level + 1)\n sol(root.right, level + 1)\n sol(root, 0)\n return a", "def nodesAtOddLevels(root):\n q = []\n odd = []\n q.append(root)\n q.append('$')\n level = 1\n while len(q) > 0:\n t = q.pop(0)\n if level % 2 != 0:\n odd.append(t.data)\n if t == '$':\n if len(q) > 0:\n q.append('$')\n level += 1\n else:\n if t.left is not None:\n q.append(t.left)\n if t.right is not None:\n q.append(t.right)\n return odd", "def nodesAtOddLevels(root):\n arr = []\n self.myFunc(root, arr, 0)\n return arr\n\ndef myFunc(root, arr, level):\n if not root:\n return\n level += 1\n if level % 2:\n arr.append(root.data)\n self.myFunc(root.left, arr, level)\n self.myFunc(root.right, arr, level)\n return", "def __init__():\n self.level = {}\n\ndef trav(root, l):\n if l in self.level:\n self.level[l].append(root.data)\n elif l % 2 == 1:\n self.level[l] = [root.data]\n if root.left != None:\n self.trav(root.left, l + 1)\n if root.right != None:\n self.trav(root.right, l + 1)\n\ndef nodesAtOddLevels(root):\n self.trav(root, 1)\n res = []\n for l in self.level.keys():\n res.extend(self.level[l])\n return res", "def nodesAtOddLevels(root):\n output = []\n\n def oddLevel(root, level):\n if root == None:\n return\n if level % 2 != 0:\n output.append(root.data)\n oddLevel(root.left)\n oddLevel(root.right)\n oddLevel(root, 1)\n return output", "x = Solution()\nroot = Node(1)\nroot.left = Node(2)\nroot.right = Node(3)\nroot.left.left = Node(4)\nroot.left.right = Node(5)\nroot.left.right.left = Node(7)\nroot.left.right.right = Node(8)\nroot.right.right = Node(6)\nroot.right.right.left = Node(9)\nx.nodesAtOddLevels(root)\n\ndef __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef nodesAtOddLevels(root):\n res = []\n\n def func(root, level):\n if root is None:\n return\n if level % 2 != 0:\n res.append(root.data)\n func(root.left, level + 1)\n func(root.right, level + 1)\n func(root, 1)\n return res", "def nodesAtOddLevels(root):\n\n def helper(x):\n ans = []\n q = []\n t = []\n if not x:\n return ans\n q.append(x)\n while q:\n l = len(q)\n for i in range(l):\n a = q.pop(0)\n if a.left:\n q.append(a.left)\n if a.right:\n q.append(a.right)\n t.append(a.data)\n ans.append(t)\n t = []\n return ans\n a = helper(root)\n answer = []\n for i in range(len(a)):\n if i % 2 == 0:\n b = a[i]\n for j in b:\n answer.append(j)\n return ans", "def nodesAtOddLevels(root):\n q = []\n v = []\n q.append(root)\n l = 1\n while q != []:\n n = len(q)\n for i in range(n):\n temp = q.pop(0)\n if i % 2 == 1:\n v.append(temp)\n if temp.left:\n v.append(temp.left)\n if temp.right:\n v.append(temp.right)\n l += 1\n return v", "def nodesAtOddLevels(root):\n level = 1\n queue = [root]\n result = []\n while queue:\n size = len(queue)\n level += 1\n for i in range(size):\n node = node.pop(0)\n if node.left != None:\n queue.append(node.left)\n if node.right != None:\n queue.append(node.right)\n if level > 1 and level % 2 != 0:\n result.append(node.data)\n return result", "def nodesAtOddLevels(root):\n sum2 = 0\n if root is None:\n return sum2\n hight = self.TreeHight(root)\n i = 1\n lst = []\n while i <= hight:\n if i % 2 != 0:\n lst = self.LevelOrdertrvsl(root, i, lst)\n i += 1\n return lst\n\ndef LevelOrdertrvsl(root, level, lst):\n if root is None:\n return lst\n if level == 1:\n lst.append(root.data)\n return lst\n elif level > 1:\n lst = self.LevelOrdertrvsl(root.left, level - 1, lst)\n lst = self.LevelOrdertrvsl(root.right, level - 1, lst)\n return lst\n\ndef TreeHight(root):\n if root is None:\n return 0\n ls = 1 + self.TreeHight(root.left)\n rs = 1 + self.TreeHight(root.right)\n maxh = max(ls, rs)\n return maxh", "def nodesAtOddLevels(root):\n if root == None:\n return None\n q = [root]\n ans = []\n k = 0\n while len(q) > 0:\n k += 1\n count = len(q)\n for i in range(count):\n temp = q.pop(0)\n if k % 2 != 0:\n ans.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n return ans", "def nodesAtOddLevels(root):\n ans = []\n i = 0\n queue = [root]\n level = []\n while queue != [] and root is not None:\n l = []\n for node in queue:\n l.append(node.data)\n if node.left:\n level.append(node.left)\n if node.right:\n level.append(node.right)\n if i % 2 == 0:\n ans += l\n queue = level\n level = []\n i += 1\n return ans", "def nodesAtOddLevels(root):\n L = []\n if root == None:\n return\n if isOdd:\n L.append(root.data)\n printOddNodes(root.left, not isOdd)\n printOddNodes(root.right, not isOdd)\n return L", "def nodesAtOddLevels(root):\n s = {}\n c = 0\n q = [[root, 0]]\n m = -1\n while c != len(q):\n t = q[c][0]\n g = q[c][1]\n if g % 2 == 0:\n if g in s:\n s[g].append(t.data)\n else:\n s[g] = [t.data]\n if g > m:\n m = g\n if t.left:\n q.append([t.left, g + 1])\n if t.right:\n q.append([t.right, g + 1])\n c += 1\n l = []\n i = 0\n while i <= m:\n l.extend(s[g])\n i += 2\n return l", "def nodesAtOddLevels(root):\n if not root:\n return\n l = []\n odd = True\n if odd:\n l.append(root.data)\n self.nodesAtOddLevels(root.left, not odd)\n self.nodesAtOddLevels(root.right, not odd)\n return l", "def __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef nodesAtOddLevels(root):\n if root is None:\n return []\n else:\n import collections\n q = collections.deque()\n q.append(root)\n lst = []\n count = 1\n while q:\n for i in range(len(q)):\n node = q.popleft()\n if node and count % 2 != 0:\n lst.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n count = count + 1\n return lst", "def nodesAtOddLevels(root):\n arr = []\n if not root:\n return arr\n q = []\n q.append(root)\n f = 0\n while q:\n if f == 0:\n arr += [x.data for x in q]\n for x in range(len(q)):\n t = q.pop(0)\n if t.left:\n q.append(t.left)\n if t.right:\n q.append(t.right)\n f = 1 - f\n return arr", "def nodesAtOddLevels(root):\n q = deque()\n q.append(root)\n (ans, level) = ([], 0)\n while q:\n level += 1\n n = len(q)\n for _ in range(n):\n p = q.popleft()\n if level % 2 == 1:\n ans.append(p.data)\n if p.left:\n q.append(p.left)\n if p.right:\n q.append(p.right)\n return ans", "def printOddLevels(root, lvl, res):\n if root == None:\n return\n if lvl % 2 != 0:\n res.append(root)\n printOddLevels(root.left, lvl + 1, res)\n printOddLevels(root.right, lvl + 1, res)\n\ndef nodesAtOddLevels(root):\n res = []\n printOddLevels(root, 1, res)", "def nodesAtOddLevels(root):\n oddnodes = []\n q = []\n q.append(root)\n n = 1\n while q:\n n = len(q)\n for i in range(n):\n temp = q.pop(0)\n if k % 2 == 1:\n oddnodes.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n k += 1\n return", "from collections import deque\n\ndef nodesAtOddLevels(r):\n (q, ret) = (deque([r, 1]), [])\n if not r:\n return ret\n while q:\n (n, l) = q.popleft()\n if n.left:\n q += ((n.left, l + 1),)\n if n.right:\n q += ((n.right, l + 1),)\n if l & 1:\n ret += (n.data,)\n return ret", "def nodesAtOddLevels(root):\n stack = []\n stack.append(root)\n ans = []\n while stack:\n n = len(stack)\n j = 1\n level = []\n for i in range(n):\n node = stack.pop()\n level.append(node.data)\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n if j % 2 != 0:\n for i in level:\n ans.append(i)\n j += 1\n return ans", "import collections\n\ndef nodesAtOddLevels(root):\n res = []\n q = collections.deque()\n q.append(root)\n while q:\n qLen = len(q)\n level = []\n for i in range(qLen):\n node = q.popleft()\n if node:\n level.append(node.data)\n q.append(node.left)\n q.append(node.right)\n if level:\n res.append(level)\n odd_nodes = []\n for i in range(len(res)):\n if i % 2 == 0:\n odd_nodes.append(res[i])\n flat_list = [x for xs in odd_nodes for x in xs]\n return flat_list", "from collections import deque\n\ndef nodesAtOddLevels(root):\n if root == None:\n return 0\n q = deque([])\n q.append(root)\n ans = []\n f = True\n while len(q) > 0:\n n = len(q)\n if f:\n for i in range(1, n + 1):\n temp = q.popleft()\n ans.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n else:\n for i in range(1, n + 1):\n temp = q.popleft()\n ans.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n f = not f\n return ans", "def nodesAtOddLevels(root):\n ans = 1\n q = []\n q.append(root)\n l = []\n while len(q) > 0:\n for i in range(len(q)):\n if ans % 2 == 1:\n c = q.pop(0)\n l.append(c.data)\n if c.left:\n q.append(c.left)\n if c.right:\n q.append(c.right)\n else:\n c = q.pop(0)\n if c.left:\n q.append(c.left)\n if c.right:\n q.append(c.right)\n ans += 1\n return l", "def nodesAtOddLevels(root):\n ans = []\n queue = []\n queue.append(root)\n while len(queue) > 0:\n elem = queue.pop(0)\n ans.append(elem.data)\n if elem.left:\n queue.append(elem.left)\n if elem.right:\n queue.append(elem.right)\n return ans", "def nodesAtOddLevels(root):\n currentlevel = []\n nextlevel = []\n if root == None:\n return 0\n currentlevel.append(root)\n level = 1\n ans = []\n while len(currentlevel) > 0:\n curr = currentlevel.pop(0)\n if curr.left:\n nextlevel.append(curr.left)\n if curr.right:\n nextlevel.append(curr.right)\n if len(currentlevel) == 0:\n (currentlevel, nextlevel) = (nextlevel, currentlevel)\n if level % 2 != 0:\n ans = ans + currentlevel\n level += 1\n return ans", "def nodesAtOddLevels(root):\n q = [root]\n i = 0\n ans = []\n flag = True\n while q:\n n = len(q)\n while n:\n temp = q.pop(0)\n if flag:\n ans.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n n -= 1\n flag = not flag\n return ans", "def nodesAtOddLevels(root):\n a = [root]\n ans = []\n level = 0\n while a:\n level += 1\n n = len(a)\n for i in range(n):\n p = a.pop(0)\n if level % 2 != 0:\n ans.append(p)\n if p.left:\n a.append(p.left)\n if p.right:\n a.append(p.right)\n return ans", "def nodesAtOddLevels(root):\n vals = []\n idx = 1\n q.append(root)\n while q:\n node = q.pop(0)\n if node is not None:\n if idx % 2 == 1:\n vals.append(node.data)\n if node.left is not None:\n q.append(node.left)\n if node.right is not None:\n q.append(node.right)\n idx += 1\n return vals", "def nodesAtOddLevels(root):\n res = []\n ans = []\n\n def traverse(root, level):\n if root == None:\n return\n if level < len(res):\n res[level].append(root.data)\n else:\n res.append([root.data])\n traverse(root.left, level + 1)\n traverse(root.right, level + 1)\n traverse(root, 0)\n for i in range(len(res)):\n if i % 2 == 0:\n for j in range(len(res[i])):\n ans.append(res[i][j])\n return ans", "from collections import deque\nq = queue()\n\ndef __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef __init__():\n self.lists = deque()\n self.size = 0\n\ndef enqueue(data):\n self.lists.append(data)\n self.size += 1\n\ndef dequeue():\n if self.size == 0:\n return -1\n else:\n temp = self.lists.popleft()\n self.size -= 1\n return temp\n\ndef isempty():\n return self.size == 0\n\ndef nodesAtOddLevels(root):\n level_count = 1\n l = []\n if root == None:\n return l\n else:\n q.enqueue(root)\n while q.isempty() != True:\n count = q.size\n while count > 0:\n temp = q.dequeue\n if level_count % 2 == 1:\n l.append(temp.data)\n if temp.left:\n q.enqueue(temp.left)\n if temp.right:\n q.enqueue(temp.right)\n count -= 1\n level_count += 1\n return l", "def nodesAtOddLevels(root):\n l = 1\n s = [root]\n ans = []\n while len(s):\n n = len(s)\n for i in range(n):\n temp = s.pop(0)\n if l % 2 != 0:\n ans.append(temp.data)\n if temp.left:\n s.append(temp.left)\n if temp.right:\n s.append(temp.right)\n l += 1\n return ans", "from collections import deque\n\ndef nodesAtOddLevels(root):\n if root is None:\n return 0\n q.append(root)\n q.append(None)\n level = 1\n arr = []\n while len(q) > 0:\n cur = q.popleft()\n if cur != None:\n if level % 2 != 0:\n arr.append(cur.data)\n if cur.left:\n q.append(cur.left)\n if cur.right:\n q.append(cur.right)\n elif len(q) > 0:\n q.append(None)\n level += 1\n return arr", "def nodesAtOddLevels(root):\n q = deque()\n q.append(root)\n q.append(None)\n arr = []\n level = 1\n while len(q) > 0:\n node = q.popleft()\n if node is not None:\n if level % 2 != 0:\n arr.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n elif len(q) > 0:\n q.append(None)\n level += 1\n return arr", "def nodesAtOddLevels(root):\n if root is None:\n return self.l\n final = []\n q = []\n q.append(root)\n level = 1\n while len(q):\n s = len(q)\n for i in range(s):\n l = q.pop(0)\n if level % 2 == 1:\n final.append(l)\n if l.left:\n q.append(l.left)\n if l.right:\n q.append(l.right)\n l += 1\n return final", "def __init__():\n self.l = []\n\ndef addnode(node, level):\n if root is None:\n return\n if level % 2 == 1:\n self.l.append(node)\n self.addnode(node.left, level + 1)\n self.addnode(node.right, level + 1)\n\ndef nodesAtOddLevels(root):\n if root is None:\n return self.l\n self.addnode(root, 1)\n return self.l", "def helper(d, q):\n while len(q) != 0:\n (p, l) = q.pop(0)\n if l % 2 != 0:\n if l not in d:\n d[l] = []\n d[l].append(root.data)\n if root.left:\n q.append((root.left, l + 1))\n if root.right:\n q.append((root.right, l + 1))\n return d\n\ndef nodesAtOddLevels(root):\n if not root:\n return []\n if not root.left and root.right:\n return root.data\n d = {}\n d = self.helper(d, [(root, 1)])\n l = []\n for i in sorted(d):\n l += i\n return l", "def nodesAtOddLevels(root):\n if root is None:\n return []\n d = defaultdict(list)\n\n def bfs(node, level):\n if not node:\n return\n d[level].append(node.data)\n bfs(node.left, level + 1)\n bfs(node.right, level + 1)\n bfs(root, 0)\n ans = []\n for (key, value) in d.items():\n if key % 2 != 0:\n ans.append(value)\n return ans", "def __init__():\n self.res = []\n\ndef nodesAtOddLevels(root):\n level = 1\n self.traverse(root, level)\n return self.res\n\ndef traverse(root, level):\n if root == None:\n return\n if level % 2 != 0:\n self.res.append(root.data)\n self.traverse(root.left, level + 1)\n self.taverse(root.right, level + 1)\n return", "def nodesAtOddLevels(root):\n if root is None:\n return\n q = []\n q.append(root)\n res = []\n oddNodes(root, True)\n\n def oddNodes(root, isOdd):\n if root is None:\n return\n n = q.pop(0)\n if isOdd:\n res.append(n.data)\n if n.left:\n q.append(n.left)\n oddNodes(n.left, not isOdd)\n if n.right:\n q.append(n.right)\n oddNodes(n.right, not isOdd)\n return res", "def nodesAtOddLevels(root):\n q = []\n q.append(root)\n lev = 1\n l = []\n while len(q) > 0:\n n = q.pop(0)\n if lev % 2 != 0:\n l.append(n.data)\n if n.left:\n q.append(n.left)\n lev += 1\n if n.right:\n q.append(n.right)\n lev += 1\n return l", "def nodesAtOddLevels(root):\n ans = []\n q = [root]\n while q:\n node = q.pop()\n size = len(node)\n for i in range(size):\n ans.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return ans", "def nodesAtOddLevels(root):\n\n def height(root):\n if root == None:\n return 0\n left = height(root.left)\n right = height(root.right)\n return max(left, right) + 1\n\n def traversal(root, level):\n if root == None:\n return None\n if level == 0:\n list1.append(root.data)\n else:\n traversal(root.left, level - 1)\n traversal(root.right, level - 1)\n tall = height(root)\n count = 1\n list1 = []\n for i in range(tall):\n if count % 2 != 1:\n traversal(root, i)\n return list1", "def helper(root, lst):\n if root is None:\n return\n lst.append(root.data)\n self.helper(root.left.left, lst)\n self.helper(root.left.right, lst)\n self.helper(root.right.left, lst)\n self.helper(root.right.right, lst)\n return lst\n\ndef nodesAtOddLevels(root):\n lst = []\n self.helper(root, lst)\n return lst", "def nodesAtOddLevels(root):\n ans = []\n\n def sol(r, val):\n nonlocal ans\n if r == None:\n return\n if len(ans) > val:\n ans[val] += 1\n else:\n ans.append(1)\n sol(r.left, val + 1)\n sol(r.right, val + 1)\n sol(root, 0)\n rans = []\n for i in range(len(ans)):\n if (i + 1) % 2 != 0:\n rans.append(ans[i])\n return rans", "def __init__():\n self.ans = []\n\ndef _traverse(root, h):\n if root:\n if h % 2:\n self.ans.append(root.data)\n self._traverse(root.left, h + 1)\n self._traverse(root.right, h + 1)\n\ndef nodesAtOddLevels(root):\n self._traverse(root, 1)\n return self.ans", "def FindOddLevelNode(root, ht, ans):\n if root == None:\n return\n if ht & 1 == 1:\n ans.append(root.data)\n FindOddLevelNode(root.left, ht + 1, ans)\n FindOddLevelNode(root.right, ht + 1, ans)\n\ndef nodesAtOddLevels(root):\n ht = 1\n ans = []\n FindOddLevelNode(root, ht, ans)\n return ans", "su = 0\n\ndef no(root, p):\n global su\n if root == None:\n return\n if p % 2 != 0:\n su = su + root.data\n self.no(root.left, p, su)\n self.no(root.right, p, su)\n\ndef nodesAtOddLevels(root):\n self.no(root, 1, 0)\n global su\n return su", "from collections import deque\n\ndef nodesAtOddLevels(root):\n level = 0\n q = deque()\n q.append(root)\n ans = []\n while q:\n level += 1\n size = len(q)\n while size:\n ele = q.popleft()\n if level % 2:\n ans.append(ele.data)\n if ele.left:\n q.append(ele.left)\n if ele.right:\n q.append(ele.right)\n size -= 1\n return ans", "import queue\n\ndef nodesAtOddLevels(root):\n if root is None:\n return []\n q = queue.Queue()\n q.put(root)\n arr = []\n i = 1\n while q.empty() != True:\n size = q.qsize()\n while size > 0:\n current_node = q.get()\n if i % 2 != 0:\n arr.append(current_node.data)\n if current_node.left != None:\n q.put(current_node.left)\n if current_node.right != None:\n q.put(current_node.right)\n size -= 1\n i += 1\n return arr", "def nodesAtOddLevels(root):\n q = []\n temp = []\n q.append(root)\n level = 1\n while len(q) > 0:\n count = len(q)\n for i in range(count):\n node = q.pop(0)\n if level % 2 == 0:\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n else:\n if node.left:\n q.append(node.left)\n temp.append(node.left)\n if node.right:\n q.append(node.right)\n temp.append(node.right)\n level = level + 1\n return temp", "def nodesAtOddLevels(root):\n level = 0\n if root is None:\n return []\n q = []\n res = []\n q.append(root)\n while len(q) > 0:\n level += 1\n temp = []\n while len(q) > 0:\n node = q.pop(0)\n if level % 2 == 1:\n res.append(node.data)\n if node.left:\n temp.append(node.left)\n if node.right:\n temp.append(node.right)\n q = temp\n return res"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["1\n / \\\n 2 3\n / \\ \\\n 4 5 6\n / \\ /\n 7 8 9", "1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7"], "outputs": ["1 4 5 6", "1 4 5 6 7"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/nodes-at-odd-levels/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "__init__", "task_id": "TACO_lite/380", "example": [[[1, [2, 3, [4, 5, [7, 8], 6, [9]]]], [1, [2, 3, [4, 5, 6, 7]]]], ["(1, 4, 5, 6)", "(1, 4, 5, 6, 7)"]]} +{"requirement": "Your friend Rick is trying to send you a message, but he is concerned that it would get intercepted by his partner. He came up with a solution:\n\n1) Add digits in random places within the message.\n\n2) Split the resulting message in two. He wrote down every second character on one page, and the remaining ones on another. He then dispatched the two messages separately.\n\nWrite a function interweave(s1, s2) that reverses this operation to decode his message!\n\nExample 1: interweave(\"hlo\", \"el\") -> \"hello\"\nExample 2: interweave(\"h3lo\", \"el4\") -> \"hello\"\n\nRick's a bit peculiar about his formats. He would feel ashamed if he found out his message led to extra white spaces hanging around the edges of his message...", "solutions": ["def interweave(s1, s2):\n s = [''] * (len(s1) + len(s2))\n (s[::2], s[1::2]) = (s1, s2)\n return ''.join((c for c in s if not c.isdigit())).strip()", "from itertools import chain, zip_longest\n\ndef interweave(s1, s2):\n return ''.join((char for char in chain.from_iterable(zip_longest(s1, s2, fillvalue='')) if not char.isdigit()))", "import re\n\ndef interweave(s1, s2):\n z = ''.join([x + y for (x, y) in zip(s1, s2 + ' ')])[:-1]\n return re.sub('[0-9]', '', z)", "def interweave(s1, s2):\n result = ''\n i = 0\n while i < len(s1) or i < len(s2):\n if i < len(s1) and (not s1[i].isdigit()):\n result += s1[i]\n if i < len(s2) and (not s2[i].isdigit()):\n result += s2[i]\n i += 1\n return result", "def interweave(s1, s2):\n return ''.join((y for x in zip(s1, s2 + '0') for y in x if not y.isdigit()))", "from itertools import zip_longest\n\ndef interweave(*args):\n return ''.join((''.join((b for b in a if not b.isdigit())) for a in zip_longest(*args, fillvalue=''))).rstrip()", "import re\n\ndef interweave(s1, s2):\n return re.sub('\\\\d', '', ''.join((a + b for (a, b) in zip(s1, s2.ljust(len(s1), ' '))))).strip()", "def interweave(s1, s2):\n s = ''\n for i in range(len(s2)):\n if not s1[i].isdigit():\n s += s1[i]\n if not s2[i].isdigit():\n s += s2[i]\n return s if len(s1) == 0 or s1[-1].isdigit() else s + s1[-1]", "from itertools import chain, zip_longest\n\ndef interweave(s1, s2):\n return ''.join([c for c in chain.from_iterable(zip_longest(s1, s2)) if c and (not c.isdigit())])"], "starter_code": "def interweave(s1, s2):\n", "input_output": {"fn_name": "interweave", "inputs": [["", ""], ["hlo", "el"], ["h3lo", "el4"]], "outputs": [[""], ["hello"], ["hello"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/588a7d45019c42be61000009", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "interweave", "task_id": "TACO_lite/492", "example": [[["hlo", "el"], ["h3lo", "el4"]], ["hello", "hello"]]} +{"requirement": "Your task is to remove all duplicate words from a string, leaving only single (first) words entries.\n\nExample:\n\nInput:\n\n'alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'\n\nOutput:\n\n'alpha beta gamma delta'", "solutions": ["def remove_duplicate_words(s):\n return ' '.join(dict.fromkeys(s.split()))", "def remove_duplicate_words(s):\n s = s.split(' ')\n words = []\n for item in s:\n if item not in words:\n words.append(item)\n return ' '.join(words)", "def remove_duplicate_words(s):\n return ' '.join(sorted(set(s.split()), key=s.index))", "def remove_duplicate_words(s):\n a = []\n [a.append(v) for v in s.split(' ') if v not in a]\n return str(' ').join(a)", "def remove_duplicate_words(s):\n\n def f():\n seen = set()\n for word in s.split():\n if word in seen:\n continue\n seen.add(word)\n yield word\n return ' '.join(f())", "from collections import OrderedDict\nremove_duplicate_words = lambda s: ' '.join(OrderedDict.fromkeys(s.split(' ')))", "def remove_duplicate_words(s):\n new_list = []\n for word in s.split():\n if word not in new_list:\n new_list.append(word)\n return ' '.join(new_list)", "d = {}\nremove_duplicate_words = lambda s: ' '.join((d.setdefault(w, w) for w in s.split() if w not in d))", "remove_duplicate_words = lambda s: (lambda x: ' '.join((e for (i, e) in enumerate(x) if e not in x[:i])))(s.split())", "def remove_duplicate_words(s):\n return ' '.join({i: 0 for i in s.split()})", "def remove_duplicate_words(s):\n res = {}\n for (i, n) in enumerate(s.split()):\n if n not in res:\n res[n] = i\n return ' '.join(sorted(res, key=res.get))", "def remove_duplicate_words(s):\n return ' '.join((s.split()[i] for i in range(len(s.split())) if s.split()[i] not in s.split()[0:i]))", "def remove_duplicate_words(s):\n seen = set()\n result = []\n for word in list(s.split(' ')):\n if word not in seen:\n seen.add(word)\n result.append(word)\n return ' '.join(result)", "def remove_duplicate_words(s):\n l = s.split()\n words = []\n for elt in l:\n if elt not in words:\n words.append(elt)\n return ' '.join(words)", "def remove_duplicate_words(s):\n final = []\n for s in s.split():\n if s not in final:\n final.append(s)\n return ' '.join(final)", "def remove_duplicate_words(s):\n tot = []\n for i in s.split():\n if i not in tot:\n tot.append(i)\n return ' '.join(tot)\n return ' '.join(tot)", "from functools import reduce\n\ndef remove_duplicate_words(s):\n return ' '.join(reduce(lambda l, x: l + [x] if x not in l else l, s.split(' '), []))", "def remove_duplicate_words(s):\n arr = s.split()\n arr1 = []\n for el in arr:\n if not el in arr1:\n arr1.append(el)\n return ' '.join(arr1)", "def remove_duplicate_words(s):\n ss = list(set(s.split()))\n ss.sort(key=s.index)\n return ' '.join(ss)", "def remove_duplicate_words(s):\n o = []\n x = s.split()\n for y in x:\n if y not in o:\n o.append(y)\n return ' '.join(o)", "def remove_duplicate_words(s):\n result = []\n [result.append(w) for w in s.split(' ') if not w in result]\n return ' '.join([x for x in result])", "remove_duplicate_words = lambda s: ' '.join(dict.fromkeys(s.split()))", "def remove_duplicate_words(s):\n array = s.split()\n output = []\n for word in array:\n if word not in output:\n output.append(word)\n return ' '.join(output)", "def remove_duplicate_words(s):\n my_set = []\n for word in s.split(' '):\n try:\n my_set.index(word)\n except ValueError:\n my_set.append(word)\n return ' '.join(my_set)", "def remove_duplicate_words(s):\n already = []\n for i in s.split():\n if i in already:\n continue\n if i not in already:\n already.append(i)\n return ' '.join(already)", "from functools import reduce\n\ndef remove_duplicate_words(s):\n return reduce(lambda res, curr: res if curr in res else res + ' ' + curr, s.split(), '').lstrip()", "def remove_duplicate_words(s):\n removed = s.split()\n newlist = []\n for i in removed:\n if i not in newlist:\n newlist.append(i)\n newstring = ' '.join(newlist)\n return newstring", "def remove_duplicate_words(s):\n arr = s.split()\n new = []\n for i in arr:\n if i not in new:\n new.append(i)\n return ' '.join(new)", "def remove_duplicate_words(s):\n arr = s.split()\n res_list = []\n for elem in arr:\n if not elem in res_list:\n res_list.append(elem)\n return ' '.join(res_list)", "def remove_duplicate_words(s):\n l = []\n for i in s.split():\n if not i in l:\n l.append(i)\n else:\n pass\n return ' '.join(l)", "def remove_duplicate_words(s):\n split = s.split(' ')\n end = []\n for word in split:\n if word in end:\n continue\n end.append(word)\n return ' '.join(end)", "def remove_duplicate_words(s):\n single = []\n for x in s.split():\n if x not in single:\n single.append(x)\n return ' '.join(single)", "def remove_duplicate_words(s):\n lst = s.split()\n lst_new = []\n for i in lst:\n if i not in lst_new:\n lst_new.append(i)\n return ' '.join(lst_new)", "def remove_duplicate_words(s):\n s_list = s.split()\n result_list = []\n for word in s_list:\n if word not in result_list:\n result_list.append(word)\n return ' '.join(result_list)", "def remove_duplicate_words(s):\n cadena = s.split()\n cadena2 = []\n cadena3 = ' '\n for i in cadena:\n if i in cadena2:\n pass\n else:\n cadena2.append(i)\n cadena3 = cadena3.join(cadena2)\n return cadena3", "def remove_duplicate_words(s):\n s = s.split(' ')\n a = ''\n for x in range(len(s)):\n if s[x] not in a:\n a += s[x] + ' '\n return a[:-1]", "def remove_duplicate_words(s):\n x = [s for s in s.split()]\n ans = []\n for y in x:\n if y not in ans:\n ans.append(y)\n return ''.join((x + ' ' for x in ans))[:-1]", "def remove_duplicate_words(s):\n list_of_words = s.split()\n compressed = []\n for word in list_of_words:\n if word not in compressed:\n compressed.append(word)\n else:\n pass\n compressed_to_string = ' '.join(compressed)\n return compressed_to_string", "def remove_duplicate_words(sentence):\n lst = [sentence][0].split()\n no_dbls = list(dict.fromkeys(lst))\n return ' '.join(no_dbls)", "def remove_duplicate_words(x):\n y = []\n for i in x.split():\n if i in y:\n pass\n else:\n y.append(i)\n return ' '.join(y)", "def remove_duplicate_words(s):\n no_dup = []\n no_dup1 = []\n for c in s.split(' '):\n if c not in no_dup:\n no_dup.append(c)\n else:\n no_dup1.append(c)\n return ' '.join(no_dup)", "def remove_duplicate_words(s):\n return ' '.join((i for (loop, i) in enumerate(s.split()) if s.split().index(i) == loop))", "def remove_duplicate_words(s):\n words = s.split()\n new_list = []\n for i in words:\n if i not in new_list:\n new_list.append(i)\n new_list = ' '.join(new_list)\n return new_list", "def remove_duplicate_words(s):\n return ' '.join(list({x: 1 for x in s.split(' ')}))", "def remove_duplicate_words(s):\n seperated = s.split()\n mylist = list(dict.fromkeys(seperated))\n return ' '.join(mylist)", "from collections import Counter\n\ndef remove_duplicate_words(strr):\n input = strr.split(' ')\n for i in range(0, len(input)):\n input[i] = ''.join(input[i])\n UniqW = Counter(input)\n s = ' '.join(UniqW.keys())\n return s", "def remove_duplicate_words(s):\n words = set()\n stree = ''\n for word in s.split():\n if word not in words:\n stree += word + ' '\n words.add(word)\n return stree[0:-1]", "def remove_duplicate_words(s):\n seen = set()\n words = []\n for word in s.split(' '):\n if word not in seen:\n seen.add(word)\n words.append(word)\n return ' '.join(words)", "def remove_duplicate_words(s):\n result = []\n s = s.split(' ')\n for (i, word) in enumerate(s):\n if word not in result:\n result.append(word)\n else:\n pass\n return ' '.join(result)", "def remove_duplicate_words(str):\n l = str.split()\n s = []\n r = []\n for i in range(len(l)):\n if l[i] not in s:\n s.append(l[i])\n r.append(l[i])\n satr = ' '.join([elem for elem in r])\n return satr", "from collections import OrderedDict\nfrom collections import Counter\n\ndef remove_duplicate_words(s):\n s = s.split(' ')\n s = OrderedDict.fromkeys(s)\n return ' '.join(s)", "from collections import OrderedDict\n\ndef remove_duplicate_words(s):\n spliter = s.split()\n return ' '.join(OrderedDict.fromkeys(spliter))", "def remove_duplicate_words(s):\n d = dict(((i, s.split(' ').count(i)) for i in s.split(' ')))\n return ' '.join(d.keys())", "def remove_duplicate_words(s):\n res = []\n s = s.split()\n visited = set()\n for w in s:\n if w not in visited:\n res.append(w)\n visited.add(w)\n return ' '.join(res)", "def remove_duplicate_words(s):\n list = s.split()\n new = []\n for x in list:\n if x not in new and new.count(x) == 0:\n new.append(x)\n s = ' '\n return s.join(new)", "def remove_duplicate_words(s):\n D = []\n words = s.split(' ')\n for word in words:\n if word not in D:\n D.append(word)\n else:\n pass\n return ' '.join(D)", "import re\n\ndef remove_duplicate_words(s):\n s_list = []\n s_2 = ''\n all = s.split()\n for word in s.split():\n if word not in s_list:\n s_2 += ' ' + word\n s_list.append(word)\n return s_2.strip()", "def remove_duplicate_words(s):\n q = ''\n a = s.split(' ')\n for i in a:\n if i not in q:\n q += i + ' '\n return q[:-1]", "from collections import Counter\n\ndef remove_duplicate_words(s):\n new = []\n for i in Counter(s.split(' ')):\n new.append(i)\n return ' '.join(new)", "import re\n\ndef remove_duplicate_words(s):\n sx = []\n for i in s.split():\n if i not in sx:\n sx.append(i)\n return ' '.join(sx)", "def remove_duplicate_words(s):\n split_string = s.split()\n new_string = ''\n for word in split_string:\n if word not in new_string:\n new_string += word + ' '\n else:\n continue\n return new_string.rstrip()", "def remove_duplicate_words(s):\n t = set()\n s = s.split()\n r = []\n for w in s:\n if w not in t:\n t.add(w)\n r.append(w)\n return ' '.join(r)", "def remove_duplicate_words(s):\n list = s.split()\n index = 0\n empty = []\n while index < len(list):\n if list[index] not in list[0:index]:\n empty.append(list[index])\n index += 1\n return ' '.join(empty)", "def remove_duplicate_words(s):\n a = []\n c = s.split(' ')\n for i in c:\n if i not in a:\n a.append(i)\n return ' '.join(a)", "def remove_duplicate_words(x):\n a = ''\n for i in x.split():\n if i not in a:\n a += i + ' '\n return a[:-1]", "def remove_duplicate_words(s):\n nwrd = []\n for i in s.split(' '):\n if i in nwrd:\n pass\n else:\n nwrd.append(i)\n return ' '.join(nwrd)", "def remove_duplicate_words(s):\n res = []\n s = s.split(' ')\n for w in s:\n if w not in res:\n res.append(w)\n erg = ''\n for r in res:\n erg += r + ' '\n return erg[:-1]", "def remove_duplicate_words(string):\n string = string.split(' ')\n lst = []\n for word in string:\n if word not in lst:\n lst.append(word)\n return ' '.join(lst)", "def remove_duplicate_words(s):\n res = ''\n k = s.split()\n for i in k:\n if i not in res:\n res += i + ' '\n return res.rstrip()", "import re\n\ndef remove_duplicate_words(s):\n result = []\n s_l = s.split(' ')\n for x in s_l:\n if x not in result:\n result.append(x)\n result = ' '.join(result)\n return result", "from collections import OrderedDict\n\ndef remove_duplicate_words(s):\n a = s.split(' ')\n return ' '.join(list(OrderedDict.fromkeys(a)))", "from collections import OrderedDict\n\ndef remove_duplicate_words(s):\n return ' '.join(OrderedDict(((x, None) for x in s.split())).keys())", "def remove_duplicate_words(s):\n return ' '.join(list({i: True for i in s.split(' ')}))", "def remove_duplicate_words(str):\n return ' '.join(sorted(set(str.split()), key=str.split().index))"], "starter_code": "def remove_duplicate_words(s):\n", "input_output": {"fn_name": "remove_duplicate_words", "inputs": [["alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta"], ["my cat is my cat fat"]], "outputs": [["alpha beta gamma delta"], ["my cat is fat"]]}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Strings", "Algorithms"], "name": null, "source": "codewars", "tags": ["String algorithms"], "skill_types": [], "url": "https://www.codewars.com/kata/5b39e3772ae7545f650000fc", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "remove_duplicate_words", "task_id": "TACO_lite/212", "example": [[["alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta"]], ["alpha beta gamma delta"]]} +{"requirement": "Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.\n\nExample 1:\n\n\nInput: n = 12\nOutput: 3 \nExplanation: 12 = 4 + 4 + 4.\n\nExample 2:\n\n\nInput: n = 13\nOutput: 2\nExplanation: 13 = 4 + 9.", "solutions": ["def numsquares(n):\n import math\n\n def is_square(m):\n sqrt_m = int(math.sqrt(m))\n return sqrt_m * sqrt_m == m\n if is_square(n):\n return 1\n while n & 3 == 0:\n n >>= 2\n if n & 7 == 7:\n return 4\n sqrt_n = int(math.sqrt(n))\n for i in range(1, sqrt_n + 1):\n if is_square(n - i * i):\n return 2\n return 3", "def numsquares(n):\n\n def is_square(n):\n return int(n ** 0.5) * int(n ** 0.5) == n\n if is_square(n):\n return 1\n for i in range(1, int(n ** 0.5 + 1)):\n if is_square(n - i * i):\n return 2\n while n & 3 == 0:\n n >>= 2\n if n & 7 == 7:\n return 4\n return 3", "def numsquares(n):\n while n % 4 == 0:\n n //= 4\n if n % 8 == 7:\n return 4\n for i in range(n + 1):\n tmp = i * i\n if tmp <= n:\n if int((n - tmp) ** 0.5) ** 2 + tmp == n:\n return 1 + (0 if tmp == 0 else 1)\n else:\n break\n return 3", "def as_a_perfect_square(n):\n return (n ** 0.5).is_integer()\n\ndef min_perfect_square(i, array):\n res = 1000\n for x in range(0, i // 2 + 1):\n a = array[x]\n if a >= res:\n continue\n b = array[i - 1 - x]\n if a + b < res:\n res = a + b\n if res == 2:\n return res\n return res\n\ndef numsquares(n):\n array = [1, 2, 3, 1, 2, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 1, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 1, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 1, 2, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 4, 2, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 1, 2, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 1, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 1, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 4, 2, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 1, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 4, 3, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 4, 1, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 1, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 2, 2, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 1, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 4, 1, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 2, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 2, 2, 3, 1, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 4, 3, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 1, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 4, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 3, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 4, 3, 3, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 4, 1, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 4, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 1, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 1, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 4, 3, 3, 3, 2, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 4, 2, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 1, 2, 2, 3, 2, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 1, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 4, 3, 2, 3, 1, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 4, 3, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 1, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 1, 2, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 1, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 3, 2, 3, 2, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 4, 3, 3, 3, 2, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 4, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 4, 2, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 4, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 4, 3, 2, 3, 1, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 4, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 4, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 4, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 1, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 4, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 4, 2, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 3, 3, 1, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 4, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 1, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 4, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 1, 2, 2, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 4, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 4, 3, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 4, 3, 2, 3, 1, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 4, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 4, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 4, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 4, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 4, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 4, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 4, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 4, 2, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 4, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 4, 3, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 1, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 2, 2, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 4, 2, 2, 3, 3, 3, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 1, 2, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 3, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 1, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 4, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 4, 2, 3, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 1, 2, 3, 3, 2, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 4, 3, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 1, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 4, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 4, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 4, 2, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 1]\n array[0] = 1\n array[1] = 2\n array_n = len(array)\n for i in range(array_n, n):\n if self.as_a_perfect_square(i + 1):\n array[array_n] = 1\n array_n += 1\n else:\n array[array_n] = self.min_perfect_square(i, array)\n array_n += 1\n return array[n - 1]"], "starter_code": "def numsquares(n: int) -> int:\n", "input_output": {"fn_name": "numSquares", "inputs": [[12]], "outputs": [3]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Math", "Dynamic Programming", "Breadth-First Search"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Graph traversal", "Mathematics"], "skill_types": ["Dynamic programming"], "url": "https://leetcode.com/problems/perfect-squares/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numsquares", "task_id": "TACO_lite/522", "example": [[[12], [13]], ["3", "2"]]} +{"requirement": "# Kata Task\n\nYou are given a list of cogs in a gear train\n\nEach element represents the number of teeth of that cog\n\ne.g. `[100, 50, 25]` means \n* 1st cog has 100 teeth \n* 2nd cog has 50 teeth\n* 3rd cog has 25 teeth\n\nIf the ``nth`` cog rotates clockwise at 1 RPM what is the RPM of the cogs at each end of the gear train? \n\n**Notes**\n* no two cogs share the same shaft\n* return an array whose two elements are RPM of the first and last cogs respectively\n* use negative numbers for anti-clockwise rotation\n* for convenience `n` is zero-based\n* For C and NASM coders, the returned array will be `free`'d.\n\n---\n\nSeries:\n* Cogs\n* Cogs 2", "solutions": ["def cog_rpm(cogs, n):\n return [cogs[n] / cogs[0] * (-1 if n % 2 else 1), cogs[n] / cogs[-1] * (1 if (len(cogs) - n) % 2 else -1)]", "def cog_rpm(cogs, n):\n sign1 = -1 if n % 2 else 1\n sign2 = 1 if (len(cogs) - n) % 2 else -1\n return [sign1 * cogs[n] / cogs[0], sign2 * cogs[n] / cogs[-1]]", "def cog_rpm(l, i):\n return [(-1 + (i + 1) % 2 * 2) * l[i] / l[0], (-1 + (len(l) - i) % 2 * 2) * l[i] / l[-1]]", "def cog_rpm(cogs, n):\n (a, b) = (1, 1)\n if n % 2 == 1:\n a = -1\n if len(cogs) % 2 == n % 2:\n b = -1\n return [a * cogs[n] / cogs[0], b * cogs[n] / cogs[-1]]", "def cog_rpm(cogs, n):\n return [cogs[n] / cogs[0] * (-1) ** n, cogs[n] / cogs[-1] * (-1) ** (len(cogs) - n - 1)]", "def cog_rpm(cogs, n):\n output = []\n if n % 2 == 0:\n a = 1\n if len(cogs) % 2 - 1 == 0:\n b = 1\n else:\n b = -1\n else:\n a = -1\n if (len(cogs) - 1) % 2 == 0:\n b = -1\n else:\n b = 1\n output.append(cogs[n] / cogs[0] * a)\n output.append(cogs[n] / cogs[-1] * b)\n return output", "def cog_rpm(cogs, idx):\n first = cogs[idx] / cogs[0] * [1, -1][idx & 1]\n last = cogs[idx] / cogs[-1] * [1, -1][len(cogs) - idx - 1 & 1]\n return [first, last]", "def cog_rpm(cogs, n):\n r = [cogs[n] / cogs[0], cogs[n] / cogs[-1]]\n if n % 2 == 1:\n r[0] *= -1\n if (len(cogs) - n) % 2 == 0:\n r[1] *= -1\n return r", "def cog_rpm(cogs, i):\n (x, y) = (cogs[i] / cogs[0], cogs[i] / cogs[-1])\n if i & 1:\n x = -x\n if len(cogs) - 1 - i & 1:\n y = -y\n return [x, y]", "from functools import reduce\nfrom operator import mul\n\ndef cog_rpm(cogs, n):\n f = lambda l: 1 if len(l) < 2 else reduce(mul, [-x / y for (x, y) in zip(l, l[1:])])\n return [f(cogs[:n + 1][::-1]), f(cogs[n:])]"], "starter_code": "def cog_rpm(cogs, n):\n", "input_output": {"fn_name": "cog_RPM", "inputs": [[[100], 0], [[100, 100, 100, 100], 0], [[100, 100, 100, 100], 1], [[100, 100, 100, 100], 2], [[100, 100, 100, 100], 3]], "outputs": [[[1, 1]], [[1, -1]], [[-1, 1]], [[1, -1]], [[-1, 1]]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/59e72bdcfc3c4974190000d9", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "cog_rpm", "task_id": "TACO_lite/532", "example": [[[[100, 50, 25]]], ["[-0.5, 2.0]"]]} +{"requirement": "# Task\n You are given an array of integers `arr` that representing coordinates of obstacles situated on a straight line.\n\n Assume that you are jumping from the point with coordinate 0 to the right. You are allowed only to make jumps of the same length represented by some integer.\n\n Find the minimal length of the jump enough to avoid all the obstacles.\n\n# Example\n\n For `arr = [5, 3, 6, 7, 9]`, the output should be `4`.\n\n Check out the image below for better understanding:\n\n \n\n\n# Input/Output\n\n\n - `[input]` integer array `arr`\n\n Non-empty array of positive integers.\n\n Constraints: `1 ≤ inputArray[i] ≤ 100.`\n\n\n - `[output]` an integer\n\n The desired length.", "solutions": ["def avoid_obstacles(arr):\n n = 2\n while 1:\n if all([x % n for x in arr]):\n return n\n n += 1", "def avoid_obstacles(a):\n for j in range(2, max(a) + 2):\n if all((e % j != 0 for e in a)):\n return j", "def avoid_obstacles(arr):\n s = set(arr)\n m = max(arr)\n for i in range(1, m + 2):\n if i in s:\n continue\n if not any((x in s for x in range(i, m + 1, i))):\n return i", "def avoid_obstacles(arr):\n obstacles = set(arr)\n limit = max(arr) + 2\n for step in range(1, limit):\n if not set(range(0, limit, step)) & obstacles:\n return step", "def avoid_obstacles(arr, n=1):\n arr = set(arr)\n while set(range(0, 100 + 1, n)) & arr:\n n += 1\n return n", "avoid_obstacles = lambda a: min((n for n in range(1, max(a) + 2) if all((m % n for m in a))))", "def avoid_obstacles(arr):\n if min(arr) == 1 and max(arr) == 100:\n return 101\n landed = True\n for max_jump in range(2, 100):\n n = max_jump\n landed = True\n while n <= 100:\n for i in range(len(arr)):\n if n == arr[i]:\n landed = False\n break\n n += max_jump\n if landed:\n return max_jump", "def avoid_obstacles(arr):\n jump = 2\n while True:\n start_again = False\n for num in arr:\n if num % jump == 0:\n jump = jump + 1\n start_again = True\n break\n if not start_again:\n return jump", "def avoid_obstacles(arr):\n holes = set(range(2, max(arr))).difference(arr)\n for step in holes:\n if all([x % step != 0 for x in arr]):\n return step\n return max(arr) + 1", "def avoid_obstacles(arr):\n x = 2\n for i in range(max(arr)):\n leaps = [x * i for i in range(1, max(arr))]\n for i in leaps:\n if i in arr:\n leaps = []\n x += 1\n break\n return x"], "starter_code": "def avoid_obstacles(arr):\n", "input_output": {"fn_name": "avoid_obstacles", "inputs": [[[5, 3, 6, 7, 9]], [[2, 3]], [[1, 4, 10, 6, 2]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]]], "outputs": [[4], [4], [7], [101]]}, "difficulty": "EASY", "raw_tags": ["Puzzles"], "name": null, "source": "codewars", "tags": ["Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/5894045b8a8a230d0c000077", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "avoid_obstacles", "task_id": "TACO_lite/514", "example": [[[[5, 3, 6, 7, 9]]], ["4"]]} +{"requirement": "You are given an integer n, find the smallest positive integer root of equation x, or else print -1 if no roots are found.\nEquation: x^2+s(x)*x-n=0\nwhere x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system.\n \nExample 1:\nInput: n = 110\nOutput: 10\nExplanation: x=10 is the minimum root. \nAs s(10)=1+0=1 and 102+1*10-110=0.\nExample 2:\nInput: n = 5\nOutput: -1\nExplanation: There is no x possible which\nsatisfy the above equation.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function Root() which takes n as input parameter and retuns the minimum root of the given equation. If not possible returns -1.\n \nExpected Time Complexity: O(k) where k is constant\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= n <= 10^{18}", "solutions": ["import math\n\ndef summation(x):\n temp = 0\n while x > 0:\n temp += x % 10\n x //= 10\n return temp\n\ndef roots(a, b, c):\n y = b * b - 4 * a * c\n if y < 0:\n return -1\n ok = (-b + math.sqrt(y)) / (2 * a)\n if int(ok) == ok:\n if ok > 0:\n return int(ok)\n else:\n return -1\n return -1\n\ndef root(x):\n root = 999999999999\n flag = 0\n for i in range(0, 91):\n temp = self.roots(1, i, -x)\n if temp != -1:\n if self.summation(temp) == i:\n if temp < root:\n root = temp\n flag = 1\n if flag:\n return root\n else:\n return -1"], "starter_code": "def root(n):\n", "input_output": {"inputs": ["n = 110", "n = 5"], "outputs": ["10", "-1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/find-the-smallest-root-of-the-equation-x2-sxx-n0-where-sx-is-the-sum-of-digits-of-root-x2219/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(k) where k is constant", "entry_point": "root", "task_id": "TACO_lite/533", "example": [[[110], [5]], ["10", "-1"]]} +{"requirement": "In music, if you double (or halve) the pitch of any note you will get to the same note again.\n\n\"Concert A\" is fixed at 440 Hz, and every other note is defined based on that. 880 Hz is also an A, as is 1760 Hz, as is 220 Hz.\n\nThere are 12 notes in Western music: A, A#, B, C, C#, D, D#, E, F, F#, G, G#. You are given a preloaded dictionary with these 12 notes and one of the pitches that creates that note (starting at Concert A).\n\nNow, given a pitch (in Hz), return the corresponding note. (All inputs will be valid notes).\n\nFor reference, the notes dictionary looks like this:\n\n```python\nnotes_dictionary = {\n 440: \"A\",\n 466.16: \"A#\",\n 493.88: \"B\",\n 523.25: \"C\",\n 554.37: \"C#\", \n 587.33: \"D\", \n 622.25: \"D#\", \n 659.25: \"E\", \n 698.46: \"F\", \n 739.99: \"F#\", \n 783.99: \"G\", \n 830.61: \"G#\"\n}\n```\n\nMusicians: all pitches based on equal tempermanent, taken from [here](http://pages.mtu.edu/~suits/notefreqs.html).", "solutions": ["notes = {440: 'A', 466.16: 'A#', 493.88: 'B', 523.25: 'C', 554.37: 'C#', 587.33: 'D', 622.25: 'D#', 659.25: 'E', 698.46: 'F', 739.99: 'F#', 783.99: 'G', 830.61: 'G#'}\n\ndef get_note(pitch):\n for note in notes:\n if note >= pitch and note % pitch == 0:\n return notes[note]\n elif note < pitch and pitch % note == 0:\n return notes[note]", "N = 'A A# B C C# D D# E F # F# G G#'.split()\nget_note = g = lambda n: 12 < n // 1 < 27 and N[int(n) - 13] or g(n / 2)", "from math import log2\nns = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']\n\ndef get_note(p):\n return ns[round(log2(p / 55) * 12) % 12]", "notesDictionary = {440: 'A', 466.16: 'A#', 493.88: 'B', 523.25: 'C', 554.37: 'C#', 587.33: 'D', 622.25: 'D#', 659.25: 'E', 698.46: 'F', 739.99: 'F#', 783.99: 'G', 830.61: 'G#'}\n\ndef get_note(pitch):\n for (key, value) in notesDictionary.items():\n if max(pitch, key) % min(pitch, key) == 0:\n return value", "notesDictionary = {440: 'A', 466.16: 'A#', 493.88: 'B', 523.25: 'C', 554.37: 'C#', 587.33: 'D', 622.25: 'D#', 659.25: 'E', 698.46: 'F', 739.99: 'F#', 783.99: 'G', 830.61: 'G#'}\n\ndef adjust_pitch(pitch):\n if pitch in notesDictionary:\n return pitch\n elif pitch < 440:\n while pitch not in notesDictionary:\n pitch *= 2\n return pitch\n elif pitch > 830:\n while pitch not in notesDictionary:\n pitch = pitch / 2\n return pitch\n else:\n return -1\n\ndef get_note(pitch):\n return notesDictionary[adjust_pitch(pitch)]"], "starter_code": "def get_note(pitch):\n", "input_output": {"fn_name": "get_note", "inputs": [[440], [220], [880], [523.25], [261.625], [1046.5]], "outputs": [["A"], ["A"], ["A"], ["C"], ["C"], ["C"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5a0599908ba914a6cf000138", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "get_note", "task_id": "TACO_lite/496", "example": [[], []]} +{"requirement": "Given a Binary Number B, find its decimal equivalent.\n \nExample 1:\nInput: B = 10001000\nOutput: 136\nExample 2:\nInput: B = 101100\nOutput: 44\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function binary_to_decimal() which takes the binary number as string input parameter and returns its decimal equivalent.\n \nExpected Time Complexity: O(K * Log(K)) where K is number of bits in binary number.\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= number of bits in binary number <= 16", "solutions": ["def binary_to_decimal(str):\n k = int(str, 2)\n return k", "def binary_to_decimal(str):\n n = int(str)\n new = 0\n for i in range(len(str)):\n rem = n % 10\n new = new + rem * pow(2, i)\n n = n // 10\n return new", "def binary_to_decimal(str):\n a = int(str, 2)\n return a", "def binary_to_decimal(str):\n j = len(str) - 1\n sum = 0\n for i in range(len(str)):\n if int(str[j]) == 0:\n sum += 0\n else:\n sum += 2 ** i\n j -= 1\n return sum", "def binary_to_decimal(str):\n c = int(str, 2)\n return c", "def binary_to_decimal(str):\n str = str[::-1]\n summ = 0\n for i in range(len(str)):\n summ += 2 ** i * int(str[i])\n return summ", "def binary_to_decimal(str):\n C = int(str, 2)\n return C", "def binary_to_decimal(str):\n s = str[::-1]\n ans = 0\n for i in range(len(s)):\n if s[i] == '1':\n ans += pow(2, i)\n return ans", "def binary_to_decimal(str):\n g = int(str, 2)\n return g", "def binary_to_decimal(str):\n char1 = []\n res = 0\n for char in str:\n char1.append(int(char))\n for i in range(len(char1)):\n res += char1.pop() * 2 ** i\n return res", "def binary_to_decimal(str):\n ans = 0\n k = 0\n for i in range(len(str) - 1, -1, -1):\n ans = ans + int(str[i]) * pow(2, k)\n k += 1\n return ans", "def binary_to_decimal(str):\n num = 0\n j = 0\n s = str[::-1]\n for i in s:\n if i == '1':\n num = num + 2 ** j\n j += 1\n return num", "import math\n\ndef binary_to_decimal(str):\n s = int(str)\n an = 0\n p = 0\n while s > 0:\n rem = s % 10\n an = an + rem * 2 ** p\n p += 1\n s = s // 10\n return an", "def binary_to_decimal(str):\n str = str[::-1]\n i = 0\n res = 0\n while i < len(str):\n if str[i] == '1':\n res += 2 ** i\n i += 1\n return res", "def binary_to_decimal(st):\n return int('0b' + st, 2)", "def binary_to_decimal(str):\n lst = list(str)\n add = 0\n number = len(lst) - 1\n for i in range(len(lst)):\n add = add + int(lst[i]) * 2 ** number\n number = number - 1\n return add", "def binary_to_decimal(str):\n lst = list(str)\n store = 0\n num = len(lst) - 1\n for i in range(len(lst)):\n store = store + int(lst[i]) * 2 ** num\n num = num - 1\n return store", "def binary_to_decimal(str):\n x = int(str, 2)\n return x", "def binary_to_decimal(str):\n ans = 0\n curr = 1\n for i in str[::-1]:\n if i == '1':\n ans += curr\n curr *= 2\n return ans", "def binary_to_decimal(B):\n decimal = 0\n power = 0\n for i in range(len(B) - 1, -1, -1):\n if B[i] == '1':\n decimal += 2 ** power\n power += 1\n return decimal", "def binary_to_decimal(str):\n bin = int(str)\n a = 0\n for i in range(0, len(str)):\n d = bin % 10\n a = a + pow(2, i) * d\n bin = int(bin / 10)\n return a", "def binary_to_decimal(str):\n n = int(str, 2)\n return n", "def binary_to_decimal(str):\n sum = 0\n for (i, v) in enumerate(str):\n if v == '1':\n sum += 2 ** (len(str) - 1 - i)\n return sum", "def binary_to_decimal(str):\n str = int(str)\n sol = 0\n i = 0\n while str != 0:\n digit = str % 10\n if digit != 0:\n sol += pow(2, i)\n i += 1\n str = str // 10\n return sol", "def binary_to_decimal(str):\n (c, res) = (0, 0)\n str = str[::-1]\n for i in str:\n res = res + int(i) * pow(2, c)\n c = c + 1\n return res", "def binary_to_decimal(str):\n sum = 0\n n = len(str)\n for i in range(n):\n sum += 2 ** i * int(str[-(i + 1)])\n return sum", "def binary_to_decimal(str):\n dec = int(str, 2)\n return dec", "def binary_to_decimal(str):\n s = int(str, 2)\n return s", "def binary_to_decimal(str):\n s = str[::-1]\n res = 0\n mul = 1\n for i in s:\n res += mul * int(i)\n mul *= 2\n return res", "def binary_to_decimal(str):\n i = int(str, 2)\n return i", "def binary_to_decimal(s):\n b = int(s)\n n = b\n d = 0\n ba = 1\n while n > 0:\n re = n % 10\n d = d + re * ba\n n = n // 10\n ba = ba * 2\n return d", "def binary_to_decimal(str):\n n = len(str)\n dec = 0\n power = 0\n for i in range(n - 1, -1, -1):\n if str[i] == '1':\n dec += 1 << power\n power += 1\n return dec", "def binary_to_decimal(str):\n ans = 0\n count = 0\n for i in str[::-1]:\n ans += 2 ** count * int(i)\n count += 1\n return ans", "def binary_to_decimal(str):\n ip = int(str)\n number = 0\n count = 0\n while ip > 0:\n rem = ip % 10\n ip = (ip - rem) // 10\n number = number + 2 ** count * rem\n count += 1\n return number", "def binary_to_decimal(str):\n num = int(str, 2)\n return num", "def binary_to_decimal(str):\n n = int(str)\n sum = 0\n i = 0\n while n != 0:\n rem = n % 10\n sum = sum + rem * pow(2, i)\n n = n // 10\n i = i + 1\n return sum", "def binary_to_decimal(str):\n K = int(str, 2)\n return K", "def binary_to_decimal(str):\n sum1 = 0\n count = 0\n for i in str[::-1]:\n if i == '1':\n sum1 += 2 ** count\n count += 1\n return sum1", "def binary_to_decimal(str):\n num = int(str)\n dec = 0\n pow = 1\n while num != 0:\n bit = num % 10\n dec = dec + bit * pow\n pow = pow * 2\n num = int(num / 10)\n return dec", "def binary_to_decimal(str):\n a = str[::-1]\n b = 0\n for i in range(len(a)):\n if a[i] == '1':\n b += 2 ** i\n return b", "def binary_to_decimal(str):\n sum = 0\n length = len(str) - 1\n for item in str:\n sum = sum + int(item) * pow(2, length)\n length = length - 1\n return sum", "def binary_to_decimal(str):\n num = int(str)\n dec_value = 0\n base = 1\n temp = num\n while temp:\n last_digit = temp % 10\n temp = int(temp / 10)\n dec_value += last_digit * base\n base = base * 2\n return dec_value", "def binary_to_decimal(str):\n i = 0\n dec = 0\n for j in range(len(str) - 1, -1, -1):\n dec += int(str[j]) * 2 ** i\n i += 1\n return dec", "def binary_to_decimal(binary):\n (decimal, i) = (0, 0)\n binary_new = int(binary)\n while binary_new != 0:\n dec = binary_new % 10\n decimal = decimal + dec * pow(2, i)\n binary_new = binary_new // 10\n i += 1\n return decimal", "def binary_to_decimal(str):\n e = 0\n d = 0\n for i in range(len(str) - 1, -1, -1):\n if str[i] == '1':\n s = 2 ** e\n d = d + s\n e += 1\n return d", "def binary_to_decimal(str):\n str = int(str)\n power = 0\n sum = 0\n while str > 0:\n r = str % 10\n if r == 1:\n sum = sum + 2 ** power\n power += 1\n str = str // 10\n return sum", "def binary_to_decimal(str):\n power = 0\n sum = 0\n for i in range(len(str) - 1, -1, -1):\n if str[i] == '1':\n sum = sum + 2 ** power\n power += 1\n return sum", "def binary_to_decimal(str):\n b = int(str, 2)\n return b", "def binary_to_decimal(n):\n n = int(n)\n decimal = 0\n power = 1\n while n > 0:\n rem = n % 10\n n = n // 10\n decimal += rem * power\n power = power * 2\n return decimal", "def binary_to_decimal(str):\n v = int(str, 2)\n return v", "def binary_to_decimal(str):\n x = len(str) - 1\n k = 0\n d = 0\n for i in range(len(str)):\n d += 2 ** x * int(str[i])\n x -= 1\n return d", "def binary_to_decimal(str):\n num = int(str)\n n = 1\n sum = 0\n while num > 0:\n rem = num % 10\n sum = sum + rem * n\n n = n * 2\n num = num // 10\n return sum", "import math\n\ndef binary_to_decimal(x):\n sum = 0\n for i in range(len(x)):\n sum = sum + int(x[i]) * math.pow(2, len(x) - 1 - i)\n return int(sum)", "def binary_to_decimal(str):\n temp = int(str)\n res = 0\n base = 1\n while temp:\n i = temp % 10\n temp = temp // 10\n res += i * base\n base *= 2\n return res", "def binary_to_decimal(str):\n binary_num = str\n decimal = int(binary_num, 2)\n return decimal", "def binary_to_decimal(str):\n sum = 0\n n = len(str) - 1\n for i in str:\n if i == '1':\n sum = sum + 2 ** n\n n = n - 1\n return sum", "def binary_to_decimal(str):\n num = str\n dec_num = 0\n for (index, string) in enumerate(str[::-1]):\n dec_num = dec_num + pow(2, index) * int(string)\n return dec_num", "def binary_to_decimal(s):\n n = len(s)\n res = 0\n for i in range(n):\n res += int(s[i]) * 2 ** (n - 1 - i)\n return res"], "starter_code": "def binary_to_decimal(str):\n", "input_output": {"inputs": ["B = 10001000", "B = 101100"], "outputs": ["136", "44"]}, "difficulty": "EASY", "raw_tags": ["CPP"], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/binary-number-to-decimal-number3525/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(K * Log(K)) where K is number of bits in binary number.", "entry_point": "binary_to_decimal", "task_id": "TACO_lite/536", "example": [[[10001000], [101100]], ["136", "44"]]} +{"requirement": "Given a linked list of N nodes. The task is to reverse this list.\nExample 1:\nInput:\nLinkedList: 1->2->3->4->5->6\nOutput: 6 5 4 3 2 1\nExplanation: After reversing the list, \nelements are 6->5->4->3->2->1.\nExample 2:\nInput:\nLinkedList: 2->7->8->9->10\nOutput: 10 9 8 7 2\nExplanation: After reversing the list,\nelements are 10->9->8->7->2.\nYour Task:\nThe task is to complete the function reverseList() with head reference as the only argument and should return new head after reversing the list.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= N <= 10^{4}", "solutions": ["def reverseList(head):\n temp = head\n prev = None\n while temp:\n succ = temp.next\n temp.next = prev\n prev = temp\n temp = succ\n return prev", "def reverseList(head):\n cur = head\n prev = None\n nxt = head.next\n while cur != None:\n nxt = cur.next\n cur.next = prev\n prev = cur\n cur = nxt\n head = prev\n return head", "def reverseList(head):\n curr = head\n next = None\n prev = None\n while curr:\n next = curr.next\n curr.next = prev\n prev = curr\n curr = next\n return prev", "def reverseList(head):\n l = []\n temp = head\n while temp != None:\n l.append(temp.data)\n temp = temp.next\n cur = head\n while cur != None:\n cur.data = l.pop()\n cur = cur.next\n return head", "def reverseList(head):\n prev = None\n curr = head\n forward = curr.next\n while curr is not None:\n curr.next = prev\n prev = curr\n curr = forward\n if forward is not None:\n forward = forward.next\n head = prev\n return head", "def reverseList(head):\n cur = head\n prev = None\n while cur is not None:\n ne = cur.next\n cur.next = prev\n prev = cur\n cur = ne\n return prev", "def reverseList(head):\n curr = head\n res = []\n while curr:\n res.append(curr.data)\n curr = curr.next\n curr = head\n while curr:\n curr.data = res.pop()\n curr = curr.next\n return head", "def reverseList(head):\n prev = None\n current = head\n while current:\n next = current.next\n current.next = prev\n prev = current\n current = next\n return prev", "def reverseList(head):\n prev = None\n curr = head\n while curr is not None:\n next_node = curr.next\n curr.next = prev\n prev = curr\n curr = next_node\n return prev", "def reverseList(head):\n l = []\n a = head\n while a != None:\n l.append(a.data)\n a = a.next\n a = head\n while a != None:\n a.data = l.pop()\n a = a.next\n return head", "def reverseList(head):\n if head is None or head.next is None:\n return head\n prev = None\n curr = head\n forwerd = None\n while curr != None:\n forwerd = curr.next\n curr.next = prev\n prev = curr\n curr = forwerd\n return prev", "def reverseList(head):\n t = head\n s = []\n while t is not None:\n s.append(t.data)\n t = t.next\n s = s[::-1]\n t = Node(s[0])\n ans = t\n if len(s) > 1:\n for x in s[1:]:\n t.next = Node(x)\n t = t.next\n return ans", "def reverseList(head):\n ress = []\n curr = head\n while curr != None:\n ress.append(curr.data)\n curr = curr.next\n curr = head\n while curr != None:\n curr.data = ress.pop()\n curr = curr.next\n return head", "def reverseList(head):\n if head is None:\n return head\n (prev, curr, next_) = (None, head, None)\n while curr:\n next_ = curr.next\n curr.next = prev\n prev = curr\n curr = next_\n return prev", "def reverseList(head):\n prev = None\n current = head\n while current is not None:\n temp = current.next\n current.next = prev\n prev = current\n current = temp\n head = prev\n return head", "def reverseList(head):\n prev = None\n curr = head\n nxt = head.next\n while curr != None:\n curr.next = prev\n prev = curr\n curr = nxt\n if curr == None:\n nxt = None\n else:\n nxt = curr.next\n head = prev\n return head", "def reverseList(head):\n previous = None\n current = head\n while current:\n next = current.next\n current.next = previous\n previous = current\n current = next\n return previous", "import sys\nsys.setrecursionlimit(int(1000000.0))\n\ndef recRev(p, c):\n if c is None:\n return p\n n = c.next\n c.next = p\n return self.recRev(c, n)\n\ndef reverseList(head):\n return self.recRev(None, head)", "def reverseList(head):\n (p, c) = (None, head)\n while c:\n n = c.next\n c.next = p\n (p, c) = (c, n)\n return p", "def reverseList(head):\n temp = head\n poin = None\n while temp:\n pre = temp.next\n temp.next = poin\n poin = temp\n temp = pre\n return poin", "def reverseList(head):\n cu = head\n prev = None\n while cu is not None:\n next = cu.next\n cu.next = prev\n prev = cu\n cu = next\n head = prev\n return head", "def reverseList(head):\n if head == None and head.next == None:\n return head\n prev = None\n curr = head\n forward = None\n while curr != None:\n forward = curr.next\n curr.next = prev\n prev = curr\n curr = forward\n return prev", "def __init__(val):\n self.data = val\n self.next = None\n\ndef reverseList(head):\n prev = None\n current = head\n while current is not None:\n next = current.next\n current.next = prev\n prev = current\n current = next\n head = prev\n return head", "import sys\n\ndef reverse(prev, curr):\n if curr == None:\n return prev\n head = self.reverse(curr, curr.next)\n curr.next = prev\n return head\n\ndef reverseList(head):\n sys.setrecursionlimit(100000)\n prev = None\n curr = head\n return self.reverse(prev, curr)", "def __init__(val):\n self.data = val\n self.next = None\n\ndef reverseList(head):\n prev = None\n if head is not None:\n cur = head\n else:\n return head\n while True:\n ne = cur.next\n cur.next = prev\n prev = cur\n if ne is not None:\n cur = ne\n else:\n return cur\n return cur", "def reverseList(head):\n if head == None:\n return head\n if head.next == None:\n return head\n r = head\n head = head.next\n r.next = None\n while head != None:\n temp = r\n r = head\n head = head.next\n r.next = None\n r.next = temp\n return r", "def __init__(val):\n self.data = val\n self.next = None\n\ndef reverseList(head):\n prev = None\n curr = head\n next = None\n while curr:\n next = curr.next\n curr.next = prev\n prev = curr\n curr = next\n head = prev\n return head", "def reverseList(head):\n curr = head\n later = None\n while curr:\n next = curr.next\n curr.next = later\n later = curr\n curr = next\n return later", "def reverseList(head):\n curr_node = head\n prev_node = None\n while curr_node:\n next_node = curr_node.next\n curr_node.next = prev_node\n prev_node = curr_node\n curr_node = next_node\n head = prev_node\n return head", "def reverseList(head):\n temp_lst = []\n curr_node = head\n while curr_node:\n temp_lst.append(curr_node.data)\n curr_node = curr_node.next\n counter = -1\n x = len(temp_lst)\n curr_node = head\n for i in range(-1, -(x + 1), -1):\n curr_node.data = temp_lst[i]\n curr_node = curr_node.next\n return head", "def reverseList(head):\n k = []\n temp = head\n while temp != None:\n k.append(temp.data)\n temp = temp.next\n temp = head\n while temp != None:\n temp.data = k.pop()\n temp = temp.next\n return head", "def reverseList(head):\n x = []\n while head:\n x.append(head.data)\n head = head.next\n x = x[::-1]\n head = Node(x[0])\n cur = head\n for i in range(1, len(x)):\n cur.next = Node(x[i])\n cur = cur.next\n return head", "def reverseList(head):\n prev = None\n while head:\n ahead = head.next\n head.next = prev\n prev = head\n head = ahead\n return prev", "def reverseList(head):\n l = None\n p = head\n while p:\n temp = Node(p.data)\n if l is None:\n l = temp\n else:\n temp.next = l\n l = temp\n p = p.next\n return l", "def reverseList(head):\n if not head or not head.next:\n return head\n p = None\n c = head\n n = head.next\n while n:\n c.next = p\n p = c\n c = n\n n = n.next\n c.next = p\n return c", "import sys\nsys.setrecursionlimit(550000)\n\ndef reverseList(head):\n curr = None\n rem = head\n\n def helper(curr, node):\n if not node:\n return curr\n t = node.next\n node.next = curr\n return helper(node, t)\n return helper(curr, rem)", "def reverseList(head):\n dummy = None\n while head:\n nextnode = head.next\n head.next = dummy\n dummy = head\n head = nextnode\n return dummy", "def reverseList(head):\n if head is None:\n return\n prev = None\n current = head\n while current is not None:\n nextnode = current.next\n current.next = prev\n prev = current\n current = nextnode\n return prev", "def reverseList(head):\n temp = None\n while head:\n next = head.next\n head.next = temp\n temp = head\n head = next\n return temp"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["LinkedList:1->2->3->4->5->6", "LinkedList:2->7->8->9->10"], "outputs": ["6 5 4 3 2 1", "10 9 8 7 2"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Linked List"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/reverse-a-linked-list/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "__init__", "task_id": "TACO_lite/338", "example": [[], []]} +{"requirement": "Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum.\nExample 1:\nInput:\n5\n4 2 -3 1 6\nOutput: \nYes\nExplanation: \n2, -3, 1 is the subarray \nwith sum 0.\nExample 2:\nInput:\n5\n4 2 0 1 6\nOutput: \nYes\nExplanation: \n0 is one of the element \nin the array so there exist a \nsubarray with sum 0.\nYour Task:\nYou only need to complete the function subArrayExists() that takes array and n as parameters and returns true or false depending upon whether there is a subarray present with 0-sum or not. Printing will be taken care by the drivers code.\nExpected Time Complexity: O(n).\nExpected Auxiliary Space: O(n).\nConstraints:\n1 <= n <= 10^{4}\n-10^{5} <= a[i] <= 10^{5}", "solutions": ["def subarrayexists(arr, n):\n n_sum = 0\n s = set()\n for i in range(len(arr)):\n n_sum += arr[i]\n if n_sum == 0 or n_sum in s:\n return True\n s.add(n_sum)\n return False", "def subarrayexists(arr, n):\n curr_sum = 0\n d = {}\n for i in range(n):\n curr_sum = curr_sum + arr[i]\n if curr_sum == 0 or curr_sum in d:\n return True\n d[curr_sum] = i\n return False", "def subarrayexists(arr, n):\n st = set()\n st.add(0)\n sum = 0\n for i in range(n):\n sum += arr[i]\n if sum in st:\n return True\n st.add(sum)\n if sum != 0:\n return False\n return True", "def subarrayexists(arr, n):\n sumhashmap = {0: 1}\n localsum = 0\n for val in arr:\n if val == 0:\n return True\n localsum += val\n if localsum in sumhashmap:\n return True\n else:\n sumhashmap[localsum] = 1\n return False", "def subarrayexists(arr, n):\n hm = {}\n if sum(arr) == 0:\n return True\n curr_sum = 0\n for i in range(n):\n curr_sum += arr[i]\n if curr_sum == 0:\n return True\n if curr_sum in hm:\n return True\n else:\n hm[curr_sum] = i\n return False", "def subarrayexists(arr, n):\n s = 0\n a = 0\n x = 0\n d = {}\n for i in range(n):\n s = s + arr[i]\n if s == 0:\n x = x + 1\n break\n if s not in d:\n d[s] = i\n else:\n x = x + 1\n break\n if x == 0:\n return False\n else:\n return True", "def subarrayexists(arr, n):\n d = {}\n s = 0\n for i in arr:\n s += i\n if s == 0 or i == 0 or s in d:\n return True\n else:\n d[s] = 1\n return False", "def subarrayexists(arr, n):\n dici = {}\n sumi = 0\n for i in range(n):\n sumi += arr[i]\n if sumi in dici or sumi == 0:\n return True\n dici[sumi] = 1\n return False", "def subarrayexists(arr, n):\n ns = 0\n s = set()\n for i in range(n):\n ns += arr[i]\n if ns == 0 or ns in s:\n return 1\n s.add(ns)\n return 0", "def subarrayexists(arr, n):\n prefix_sum = [0] * (n + 1)\n for i in range(1, n + 1):\n prefix_sum[i] = prefix_sum[i - 1] + arr[i - 1]\n hmap = {}\n for i in prefix_sum:\n if i not in hmap:\n hmap[i] = 1\n else:\n return True\n return False", "def subarrayexists(arr, n):\n sum = 0\n s = set()\n d = True\n f = False\n for i in range(n):\n sum = sum + arr[i]\n if sum == 0 or sum in s:\n return d\n s.add(sum)\n return f\n if d:\n return 'Yes'\n else:\n return 'No'", "def subarrayexists(arr, n):\n hash = set()\n for i in range(n):\n if i == 0:\n if arr[i] == 0:\n return True\n else:\n arr[i] += arr[i - 1]\n if arr[i] in hash or arr[i] == 0:\n return True\n hash.add(arr[i])\n return False", "def subarrayexists(arr, n):\n seen_sums = set()\n running_sum = 0\n for num in arr:\n running_sum += num\n if running_sum == 0 or running_sum in seen_sums:\n return True\n seen_sums.add(running_sum)\n return False", "def subarrayexists(arr, n):\n h = {}\n res = 0\n for i in range(n):\n res += arr[i]\n if res == 0:\n return 1\n if res in h:\n return 1\n h[res] = 1\n return 0", "def subarrayexists(arr, n):\n sum = 0\n s = set()\n for each in arr:\n sum += each\n if sum in s or sum == 0:\n return True\n s.add(sum)\n return False", "def subarrayexists(arr, n):\n pref_sum = {0: 1}\n curr_sum = 0\n for elem in arr:\n curr_sum += elem\n if curr_sum in pref_sum:\n return True\n else:\n pref_sum[curr_sum] = 1\n return False", "def subarrayexists(arr, n):\n sum = 0\n s = set()\n for i in range(n):\n sum = sum + arr[i]\n if sum == 0 or sum in s:\n return True\n else:\n s.add(sum)\n return False", "def subarrayexists(arr, n):\n addSum = 0\n maxLen = 0\n d = {}\n for i in range(len(arr)):\n addSum += arr[i]\n if addSum == 0:\n maxLen = i + 1\n elif addSum in d:\n maxLen = max(maxLen, i - d[addSum])\n else:\n d[addSum] = i\n if maxLen >= 1:\n return True\n else:\n return False", "def subarrayexists(arr, n):\n sm = 0\n dic = {0}\n for el in arr:\n if el == 0:\n return True\n sm += el\n if sm in dic:\n return True\n dic.add(sm)\n return False", "def subarrayexists(arr, n):\n prefix_sum_set = set()\n prefix_sum = 0\n for i in range(n):\n prefix_sum += arr[i]\n if prefix_sum == 0 or prefix_sum in prefix_sum_set:\n return True\n prefix_sum_set.add(prefix_sum)\n return False", "def subarrayexists(arr, n):\n d = {0: 1}\n sumVal = 0\n for i in arr:\n sumVal += i\n if sumVal in d:\n return 1\n d[sumVal] = 1\n return 0", "def subarrayexists(arr, n):\n dic = {0: 0}\n s = 0\n for i in arr:\n s += i\n try:\n dic[s] += 1\n return True\n except:\n dic[s] = 0\n return False", "def subarrayexists(arr, n):\n prefixSum = {}\n sum = 0\n for i in range(n):\n sum += arr[i]\n if sum == 0 or sum in prefixSum:\n return True\n prefixSum[sum] = i\n return False", "def subarrayexists(arr, n):\n sum = 0\n d = {}\n for i in arr:\n sum += i\n if sum in d:\n return True\n if sum == 0:\n return True\n d[sum] = 1\n return False", "def subarrayexists(arr, n):\n pre_sum = 0\n s = set()\n for i in arr:\n pre_sum += i\n if pre_sum == 0 or pre_sum in s:\n return True\n s.add(pre_sum)\n return False", "from collections import *\n\ndef subarrayexists(arr, n):\n d = defaultdict(int)\n d[0] = 1\n sumsofar = 0\n count = 0\n for i in range(n):\n sumsofar += arr[i]\n count += d[sumsofar]\n d[sumsofar] = 1\n if count >= 1:\n return True\n else:\n return False", "def subarrayexists(arr, n):\n m = {}\n sum = 0\n for i in range(n):\n sum += arr[i]\n if sum in m or sum == 0:\n return 1\n else:\n m[sum] = 1\n return 0", "def subarrayexists(arr, n):\n d = {0: -1}\n cumulative = 0\n for i in range(n):\n cumulative += arr[i]\n if cumulative in d:\n return True\n else:\n d[cumulative] = i\n return False", "from collections import *\n\ndef subarrayexists(nums, n):\n d = defaultdict(int)\n presum = 0\n ans = 0\n d[0] = 1\n for i in range(len(nums)):\n presum = presum + nums[i]\n if presum in d:\n ans += d[presum]\n d[presum] += 1\n return True if ans > 0 else False", "def subarrayexists(arr, n):\n s = 0\n l = []\n for i in arr:\n s = s + i\n l.append(s)\n d = {}\n for i in l:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n flag = 0\n for i in d:\n if d[i] >= 2 or i == 0:\n flag = 1\n break\n if flag == 1:\n return True\n else:\n return False", "def subarrayexists(arr, n):\n prefixArr = []\n prefixArr.append(arr[0])\n dict1 = {}\n dict1[arr[0]] = 0\n for i in range(1, n):\n prefixArr.append(prefixArr[i - 1] + arr[i])\n if prefixArr[i] == 0:\n return True\n if prefixArr[i] not in dict1:\n dict1[prefixArr[i]] = i\n else:\n return True\n return False", "def subarrayexists(arr, n):\n dict = {}\n s = 0\n for i in arr:\n s += i\n if s == 0 or i == 0 or s in dict:\n return True\n else:\n dict[s] = 3\n return False", "def subarrayexists(arr, n):\n sum_set = set()\n sum_set.add(0)\n sum_so_far = 0\n for num in arr:\n sum_so_far += num\n if sum_so_far in sum_set:\n return True\n break\n sum_set.add(sum_so_far)", "def subarrayexists(arr, n):\n l = []\n sum_ = 0\n d = {}\n for i in range(n):\n sum_ += arr[i]\n if sum_ == 0 or sum_ in d:\n return True\n d[sum_] = 1\n return False", "from collections import defaultdict\n\ndef subarrayexists(arr, n):\n d = defaultdict(lambda : 0)\n total = 0\n for x in arr:\n total += x\n if total in d:\n return True\n if x == 0 or total == 0:\n return True\n d[total] += 1", "def subarrayexists(arr, n):\n dict = {}\n s = set()\n sum = 0\n for i in range(len(arr)):\n sum += arr[i]\n if sum == 0 or sum in dict:\n return True\n dict[sum] = 1\n return False", "def subarrayexists(arr, n):\n k = 0\n d = {0: 1}\n sum1 = 0\n for i in arr:\n sum1 = sum1 + i\n if sum1 - k in d:\n return 1\n if sum1 not in d:\n d[sum1] = 1\n if sum1 in d:\n d[sum1] = d[sum1] + 1\n return 0", "def subarrayexists(arr, n):\n si = 0\n s = 0\n dic = {}\n while si < n:\n s += arr[si]\n if s == 0:\n return True\n if s in dic:\n return True\n else:\n dic[s] = si\n si += 1\n return False", "def subarrayexists(arr, n):\n seen = {}\n sum_upto = 0\n for ele in arr:\n sum_upto += ele\n if sum_upto == 0:\n return True\n elif sum_upto in seen:\n return True\n else:\n seen[sum_upto] = 1\n return False", "def subarrayexists(nums, n):\n curr_sum = nums[0]\n prefix = [curr_sum]\n for i in range(1, len(nums)):\n curr_sum += nums[i]\n prefix.append(curr_sum)\n d = {}\n for i in range(len(prefix)):\n if prefix[i] == 0:\n return True\n if prefix[i] not in d.keys():\n d[prefix[i]] = [i]\n else:\n d[prefix[i]].append(i)\n for i in d.values():\n if len(i) > 1:\n return True\n return False", "def subarrayexists(arr, n):\n a = set()\n a.add(0)\n s = 0\n for i in arr:\n s += i\n if s in a:\n return True\n a.add(s)\n return s == 0", "def subarrayexists(arr, n):\n prefix_sum = 0\n prefix_sum_set = set()\n for element in arr:\n prefix_sum = prefix_sum + element\n if prefix_sum == 0:\n return True\n if prefix_sum in prefix_sum_set:\n return True\n else:\n prefix_sum_set.add(prefix_sum)\n return False", "def subarrayexists(arr, n):\n s1 = set()\n cs = 0\n for i in range(n):\n cs = cs + arr[i]\n if cs in s1 or cs == 0:\n return True\n s1.add(cs)\n return False", "def subarrayexists(arr, n):\n st = set()\n prefixsum = []\n sum = 0\n for i in arr:\n sum += i\n if sum == 0 or sum in st:\n return True\n else:\n st.add(sum)\n return False", "def subarrayexists(arr, n):\n seen = set()\n sum1 = 0\n for i in range(n):\n seen.add(sum1)\n sum1 += arr[i]\n if sum1 in seen:\n return True\n return False", "def subarrayexists(arr, n):\n d = {}\n c = 0\n for i in range(n):\n c += arr[i]\n if c in d or c == 0:\n return 1\n else:\n d[c] = 1\n if c == 0:\n return 1\n else:\n return 0", "def subarrayexists(arr, n):\n s = 0\n h = {0}\n dik = {}\n for i in range(n):\n if arr[i] == 0:\n return True\n s += arr[i]\n if s == 0:\n return True\n if s in dik:\n return True\n dik[s] = s\n return False", "def subarrayexists(arr, n):\n prev_sum = set()\n curr_sum = 0\n for i in arr:\n curr_sum += i\n if curr_sum == 0 or curr_sum in prev_sum:\n return True\n prev_sum.add(curr_sum)\n return False", "def subarrayexists(arr, n):\n prefix_sum = {0: -1}\n sum = 0\n k = 0\n for i in range(len(arr)):\n sum += arr[i]\n if sum - k in prefix_sum:\n return True\n if sum not in prefix_sum:\n prefix_sum[sum] = i\n return False", "def subarrayexists(arr, n):\n _d = {}\n _csum = 0\n for i in range(n):\n _csum += arr[i]\n if _csum in _d.keys() or _csum == 0:\n return True\n else:\n _d[_csum] = -1\n if _csum == 0:\n return True\n return False", "def subarrayexists(arr, n):\n s = 0\n d = {}\n d[s] = True\n for i in range(len(arr)):\n s += arr[i]\n if s in d:\n return True\n d[s] = True\n return False"], "starter_code": "def subarrayexists(arr,n):\n", "input_output": {"inputs": ["5\n4 2 -3 1 6", "5\n4 2 0 1 6"], "outputs": ["Yes", "Yes"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Hash", "Map", "sliding-window", "STL", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures", "Amortized analysis"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1", "Expected Auxiliary Space": "O(n).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n).", "entry_point": "subarrayexists", "task_id": "TACO_lite/530", "example": [[], []]} +{"requirement": "There are N stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter).\nNote: Order does not matter means for n=4 {1 2 1},{2 1 1},{1 1 2} are considered same.\nExample 1:\nInput:\nN = 4\nOutput: 3\nExplanation: You can reach 4th stair in\n3 ways.\n3 possible ways are:\n1, 1, 1, 1\n1, 1, 2\n2, 2\nExample 2:\nInput:\nN = 5\nOutput: 3\nExplanation:\nYou may reach the 5th stair in 3 ways.\nThe 3 possible ways are:\n1, 1, 1, 1, 1\n1, 1, 1, 2\n1, 2, 2\nYour Task:\nYour task is to complete the function countWays() which takes single argument(N) and returns the answer.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 <= N <= 10^{6}", "solutions": ["def countways(m):\n mod = 1000000007\n ans = 1\n while m - 1 > 0:\n ans = (ans + 1) % mod\n m = m - 2\n return ans", "def countways(m):\n mod = 1000000007\n return int(m / 2 + 1)", "def nthStair1(a, n, W):\n global dp\n if W == 0:\n return 1\n if n == 0:\n return 0\n if dp[n][W] != -1:\n return dp[n][W]\n if a[n - 1] <= W:\n dp[n][W] = self.nthStair1(a, n, W - a[n - 1]) + self.nthStair1(a, n - 1, W)\n return dp[n][W]\n else:\n dp[n][W] = self.nthStair1(a, n - 1, W)\n return dp[n][W]\n\ndef countways(m):\n mod = 1000000007\n global dp\n dp = [[-1 for i in range(m + 1)] for j in range(2 + 1)]\n a = [1, 2]\n return self.nthStair1(a, 2, m)", "def countways(m):\n mod = 1000000007\n if m < 2:\n return 1\n count = [0 for _ in range(m + 1)]\n count[0] = count[1] = 1\n for step in range(1, 3):\n for stair in range(2, m + 1):\n count[stair] += count[stair - step]\n count[stair] %= mod\n return count[m]", "def countways(m):\n return (m // 2 + 1) % 1000000007", "def countwaysHelper(m, arr, n, memo):\n mod = 1000000007\n if (m, n) in memo:\n return memo[m, n]\n if m == 0:\n return 1\n if n == 0 or m < 0:\n return 0\n ans1 = self.countwaysHelper(m - arr[n - 1], arr, n, memo)\n ans2 = self.countwaysHelper(m, arr, n - 1, memo)\n memo[m, n] = (ans1 + ans2) % mod\n return memo[m, n]\n\ndef countways(m):\n return self.countwaysHelper(m, [1, 2], 2, dict())", "def countways(m):\n dp = [-1] * (m + 1)\n dp[0] = 0\n dp[1] = 1\n for i in range(2, m + 1):\n if i % 2 == 0:\n dp[i] = dp[i - 1] + 1\n else:\n dp[i] = dp[i - 1]\n return dp[m]", "def countways(n):\n mod = 1000000007\n dp = [None] * (n + 1)\n dp[0] = 1\n dp[1] = 1\n for i in range(2, n + 1):\n dp[i] = dp[i - 2] + 1\n return dp[n]", "def countways(m):\n mod = 1000000007\n ways = [0] * (m + 1)\n ways[0] = 1\n ways[1] = 1\n for i in range(2, m + 1):\n ways[i] = (ways[i - 2] + 1) % mod\n return ways[m]", "def countways(n):\n if n == 1:\n return 1\n dp = [[0 for i in range(2)] for j in range(n)]\n dp[0][0] = 1\n dp[1][0] = 1\n dp[1][1] = 1\n for i in range(2, n):\n dp[i][0] += dp[i - 1][0]\n dp[i][1] = (dp[i - 2][1] + dp[i][0]) % 1000000007\n return sum(dp[n - 1]) % 1000000007", "def countways(m):\n mod = 1000000007\n arr = [1, 2]\n n = 2\n dp = [[-1 for i in range(n + 1)] for i in range(m + 1)]\n\n def recursive(dp, arr, n, m):\n if m == 0:\n return 1\n if n == 0:\n return 0\n if dp[m][n] != -1:\n return dp[m][n]\n dp[m][n] = recursive(dp, arr, n - 1, m)\n if m - arr[n - 1] >= 0:\n dp[m][n] += recursive(dp, arr, n, m - arr[n - 1])\n return dp[m][n]\n return recursive(dp, arr, n, m)", "def countways(m):\n n = m\n dp = [0] * (n + 1)\n dp[0] = 1\n for i in range(1, n + 1):\n os = dp[i - 1]\n ts = 0\n if i > 1:\n ts = dp[i - 2]\n dp[i] = int((os + ts) / 2) + 1\n return dp[n]", "def countways(m):\n mod = 1000000007\n dp = [0 for _ in range(m + 1)]\n dp[0] = 1\n for i in range(1, 3):\n for j in range(i, m + 1):\n dp[j] += dp[j - i]\n return dp[m]", "def countways(m):\n count = 0\n for x in range(m + 1):\n if (m - x) % 2 == 0:\n count += 1\n return count", "def count(m):\n if m == 1:\n return 1\n if m <= 0:\n return 0\n ans = self.count(m - 1) + self.count(m - 2)\n return ans\n\ndef countways(m):\n mod = 1000000007\n dp = [0 for _ in range(m + 1)]\n dp[0] = 1\n dp[1] = 1\n for i in range(2, m + 1):\n dp[i] = 1 + min(dp[i - 1], dp[i - 2])\n return dp[m]", "def countways(n):\n mod = 1000000007\n if n == 1:\n return 1\n if n == 2:\n return 2\n p1 = 1\n p2 = 2\n for i in range(3, n + 1):\n c = (min(p1, p2) + 1) % mod\n p1 = p2\n p2 = c\n return c", "def util(n):\n if n == 1:\n return 1\n if n == 2 or n == 3:\n return 2\n return 1 + max(self.util(n - 1), self.util(n - 2)) % self.mod\n\ndef countways(m):\n return m // 2 + 1", "def countways(m):\n from math import floor as fl\n return fl(m / 2 + 1)", "def countways(m):\n n = m\n mod = 1000000007\n dp = [0] * (n + 1)\n if n == 1:\n return 1\n if n == 2:\n return 2\n dp[0] = 0\n dp[1] = 1\n dp[2] = 2\n for i in range(3, n + 1):\n if i % 2 != 0:\n dp[i] = dp[i - 1] % mod\n else:\n dp[i] = (dp[i - 1] + 1) % mod\n return dp[-1]", "def countways(m):\n mod = 1000000007\n if m < 2:\n return 1\n a = 1\n b = 1\n for i in range(2, m + 1):\n c = a + 1\n a = b\n b = c\n return c % mod", "def countways(m):\n return m // 2 + 1\n mod = 1000000007\n if m == 0:\n return 1\n res = 1\n for i in range(1, m + 1):\n if i % 2 == 0:\n res += 1\n return res", "def countways(m):\n mod = 1000000007\n dp = [-1] * (m + 1)\n\n def count(n, dp):\n if n <= 2:\n return n\n if n < 0:\n return 0\n if dp[n] == -1:\n dp[n] = 1 + count(n - 2, dp)\n return dp[n] % mod\n return count(m, dp)", "def countways(m):\n if m == 2:\n return 2\n if m == 1:\n return 1\n res = 0\n while m >= 2:\n m = m - 2\n res += 1\n return res + 1", "def countways(n):\n mod = 1000000007\n result = self.solve(n)\n return result % mod\n\ndef solve(n):\n minus1 = minus2 = 0\n for i in range(n + 1):\n result = 1 + min(minus1, minus2)\n minus2 = minus1\n minus1 = result\n return result", "def countways(n):\n mod = 1000000007\n result = self.solve(n)\n return result % mod\n\ndef solve(n):\n times = max(2, n + 1)\n dp = [0 for i in range(times)]\n dp[0] = dp[1] = 1\n for i in range(2, n + 1):\n dp[i] = 1 + min(dp[i - 1], dp[i - 2])\n return dp[n]", "def countways(n):\n dp = [-1 for i in range(n + 1)]\n dp[0] = 1\n result = self.solve(n, dp)\n return result % 1000000007\n\ndef solve(n, dp):\n if n < 0:\n return 0\n if dp[n] != -1:\n return dp[n]\n minus1 = self.solve(n - 1, dp)\n minus2 = self.solve(n - 2, dp)\n dp[n] = 1 + min(minus1, minus2)\n return dp[n]", "def countways(n):\n mod = 1000000007\n result = 1 + n // 2\n return result % mod", "def countways(m):\n mod = 1000000007\n if m < 2:\n return 1\n return (m // 2 + 1) % mod", "def countways(m):\n if m <= 2:\n return m\n return m // 2 + 1", "def countways(m):\n global mod\n mod = 1000000007\n\n def recurs(m):\n if m == 0:\n return 1\n if m < 0:\n return 0\n p = recurs(m - 2)\n q = recurs(m - 1)\n return (p % mod + q % mod) % mod\n return int(m / 2) + 1", "def countways(m):\n t = [-1 for i in range(m + 1)]\n return self.helper(m, t)\n\ndef helper(m, t):\n if m == 0:\n return 1\n if m < 0:\n return 0\n if t[m] != -1:\n return t[m]\n step1 = self.helper(m - 1, t)\n step2 = self.helper(m - 2, t)\n t[m] = 1 + min(step1, step2)\n return t[m]", "def countways(m):\n mod = 1000000007\n d = {0: 1, 1: 1, 2: 2}\n for i in range(2, m + 1):\n d[i] = min(d[i - 1] % mod, d[i - 2] % mod) + 1\n return d[m] % mod", "def countways(m):\n mod = 1000000007\n possible = [1, 2]\n no_of_ele = 2\n dp = [0] * (m + 1)\n dp[0] = 1\n for i in range(no_of_ele):\n for j in range(m + 1):\n if j - possible[i] >= 0:\n dp[j] = dp[j] + dp[j - possible[i]]\n return dp[m] % mod", "MOD = pow(10, 9) + 7\n\ndef countways(m):\n return 1 + m // 2", "def countways(m):\n mod = 1000000007\n v = [1, 2]\n dp = [0] * (m + 1)\n dp[0] = 1\n for i in range(0, len(v)):\n for j in range(v[i], m + 1):\n dp[j] = dp[j] + dp[j - v[i]]\n return dp[-1] % mod", "def __init__():\n self.d = {}\n self.res = set()\n\ndef countways(m):\n mod = 1000000007\n dp = [1] * (m + 1)\n n = m\n for i in range(2, m + 1):\n dp[i] = dp[i] + dp[i - 2]\n return dp[n] % mod", "def countways(m):\n dp = [-1 for i in range(m + 1)]\n dp[0] = 0\n dp[1] = 1\n if m > 1:\n for i in range(2, m + 1):\n if i == 2:\n way1 = dp[i - 1]\n way2 = 100000\n else:\n way1 = dp[i - 1]\n way2 = dp[i - 2]\n dp[i] = min(way1, way2) + 1\n return dp[m]", "def countways(m):\n dp = [-1 for i in range(m + 1)]\n dp[0] = 0\n dp[1] = 1\n if m > 1:\n dp[2] = 2\n for i in range(3, m + 1):\n way1 = dp[i - 1]\n way2 = dp[i - 2]\n dp[i] = min(way1, way2) + 1\n return dp[m]\n mod = 1000000007", "def countways(m):\n mod = 1000000007\n count = 1\n while m > 1:\n m -= 2\n count += 1\n return count", "def countways(m):\n mod = 1000000007\n dp = [[-1 for i in range(m + 1)] for j in range(m + 1)]\n dec = {}\n self.ans = 0\n\n def solve(st, no):\n if st == 0:\n if dec.get(no) == None:\n dec[no] = 1\n self.ans += 1\n return 0\n return 0\n if st < 0:\n return 0\n if dp[no][st] != -1:\n return dp[no][st]\n dp[no][st] = solve(st - 1, no + 1) + solve(st - 2, no + 1)\n return dp[no][st]\n solve(m, 0)\n return self.ans", "def countways(m):\n mod = 1000000007\n dp = [[0 for i in range(2)] for j in range(m + 1)]\n for i in range(2):\n dp[0][i] = 1\n arr = [i + 1 for i in range(2)]\n for i in range(1, m + 1):\n for j in range(2):\n take = dp[i - arr[j]][j] if i >= arr[j] else 0\n nottake = dp[i][j - 1] if j > 0 else 0\n dp[i][j] = take + nottake\n return dp[m][1]", "def countways(m):\n dt = [[-1 for i in range(m + 1)] for j in range(3)]\n\n def ab(m, d=[1, 2], n=2):\n if m == 0:\n return 1\n if n == 0 or m < 0:\n return 0\n if dt[n][m] != -1:\n return dt[n][m]\n a = ab(m, d[1:], n - 1)\n b = ab(m - d[0], d, n)\n dt[n][m] = a + b\n return a + b\n return ab(m)", "def countways(m):\n\n def ab(m, d=[1, 2], n=2):\n if m == 0:\n return 1\n if n == 0 or m < 0:\n return 0\n a = ab(m, d[1:], n - 1)\n b = ab(m - d[0], d, n)\n return a + b\n return ab(m)", "def __init__():\n self.d = {}\n\ndef countways(n):\n if n == 1 or n == 2:\n return n\n if n in self.d:\n return self.d[n]\n a1 = self.countways(n - 1)\n a2 = self.countways(n - 2)\n self.d[n] = min(a1, a2) + 1\n return self.d[n]"], "starter_code": "def countways(m):\n", "input_output": {"inputs": ["N = 4", "N = 5"], "outputs": ["3", "3"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Mathematics"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/count-ways-to-nth-stairorder-does-not-matter1322/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "countways", "task_id": "TACO_lite/537", "example": [[[4], [5]], ["3", "3"]]} +{"requirement": "One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #.\n\n\n _9_\n / \\\n 3 2\n / \\ / \\\n 4 1 # 6\n/ \\ / \\ / \\\n# # # # # #\n\n\nFor example, the above binary tree can be serialized to the string \"9,3,4,#,#,1,#,#,2,#,6,#,#\", where # represents a null node.\n\nGiven a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.\n\nEach comma separated value in the string must be either an integer or a character '#' representing null pointer.\n\nYou may assume that the input format is always valid, for example it could never contain two consecutive commas such as \"1,,3\".\n\nExample 1:\n\n\nInput: \"9,3,4,#,#,1,#,#,2,#,6,#,#\"\nOutput: true\n\nExample 2:\n\n\nInput: \"1,#\"\nOutput: false\n\n\nExample 3:\n\n\nInput: \"9,#,#,1\"\nOutput: false", "solutions": ["def isvalidserialization(preorder):\n p = preorder.split(',')\n slot = 1\n for node in p:\n if slot == 0:\n return False\n if node == '#':\n slot -= 1\n else:\n slot += 1\n return slot == 0", "def isvalidserialization(preorder):\n if not preorder:\n return False\n nodes = preorder.split(',')\n stack = [0] if nodes[0] != '#' else []\n dt = {0: 2}\n i = 1\n while stack and i < len(nodes):\n dt[stack[-1]] -= 1\n if dt[stack[-1]] == 0:\n stack.pop()\n if nodes[i] != '#':\n stack.append(i)\n dt[i] = 2\n i = i + 1\n return not stack and i == len(nodes)", "def isvalidserialization(preorder):\n preorder = preorder.split(',')\n if preorder[0] == '#':\n return len(preorder) == 1\n s = []\n curr = preorder[0]\n on_left = True\n for i in range(1, len(preorder)):\n if not curr:\n return False\n e = preorder[i]\n if e != '#':\n if on_left:\n s.append(curr)\n curr = e\n on_left = True\n else:\n if not on_left:\n curr = s.pop() if len(s) > 0 else None\n on_left = False\n return curr is None", "def isvalidserialization(preorder):\n if len(preorder) < 1:\n return False\n stack = []\n for s in preorder.split(','):\n stack.append(False)\n if s == '#':\n while len(stack) > 2 and stack[-2]:\n stack.pop()\n stack.pop()\n stack.pop()\n else:\n stack.append(True)\n return stack == [False, True]", "def isvalidserialization(preorder):\n if not preorder:\n return True\n arr = preorder.split(',')\n s = []\n for a in arr:\n s.append(a)\n while len(s) >= 3 and s[-1] == '#' and (s[-2] == '#') and (s[-3] != '#'):\n s.pop()\n s.pop()\n s.pop()\n s.append('#')\n if s == ['#']:\n return True\n return False", "def isvalidserialization(preorder):\n (stack, preorder) = ([], preorder.split(','))\n top = -1\n for s in preorder:\n stack.append(s)\n top += 1\n while self.endsWithTwoHashes(stack, top):\n (h, top) = (stack.pop(), top - 1)\n (h, top) = (stack.pop(), top - 1)\n if top < 0:\n return False\n stack[-1] = '#'\n return len(stack) == 1 and stack[0] == '#'\n\ndef endsWithTwoHashes(stack, top):\n if top < 1:\n return False\n if stack[top] == '#' and stack[top - 1] == '#':\n return True\n return False", "def isvalidserialization(preorder):\n (preorder, first) = (preorder.split(','), preorder.split(','))\n\n def backward(index):\n if index >= len(preorder) or index < 0:\n return\n if index + 1 < len(preorder) and preorder[index + 1] == preorder[index] == '#' and (index - 1 >= 0) and (preorder[index - 1] != '#'):\n preorder.pop(index)\n preorder.pop(index)\n preorder[index - 1] = '#'\n backward(index - 2)\n else:\n backward(index + 1)\n backward(0)\n return True if preorder != first and preorder == ['#'] or preorder == first == ['#'] else False"], "starter_code": "def isvalidserialization(preorder: str) -> bool:\n", "input_output": {"fn_name": "isValidSerialization", "inputs": [["\"9,3,4,#,#,1,#,#,2,#,6,#,#\""]], "outputs": [false]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Stack", "Binary Tree", "Tree", "String"], "name": null, "source": "leetcode", "tags": ["Tree algorithms", "Data structures", "String algorithms"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "isvalidserialization", "task_id": "TACO_lite/383", "example": [[], []]} +{"requirement": "Given an unsorted array of size N. Find the first element in array such that all of its left elements are smaller and all right elements to it are greater than it.\nNote: Left and right side elements can be equal to required element. And extreme elements cannot be required element.\n \nExample 1:\nInput:\nN = 4\nA[] = {4, 2, 5, 7}\nOutput:\n5\nExplanation:\nElements on left of 5 are smaller than 5\nand on right of it are greater than 5.\n \nExample 2:\nInput:\nN = 3\nA[] = {11, 9, 12}\nOutput:\n-1\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function findElement() which takes the array A[] and its size N as inputs and returns the required element. If no such element present in array then return -1.\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\n \nConstraints:\n3 <= N <= 10^{6}\n1 <= A[i] <= 10^{6}", "solutions": ["def findelement(arr, n):\n ans = -1\n maxi = arr[0]\n h = set()\n for i in range(1, n - 1):\n if arr[i] >= maxi:\n h.add(i)\n maxi = arr[i]\n mini = arr[-1]\n for i in range(n - 2, 0, -1):\n if i in h and arr[i] <= mini:\n ans = i\n mini = arr[i]\n if arr[i] < mini:\n mini = arr[i]\n if ans == -1:\n return -1\n return arr[ans]", "def findelement(arr, n):\n ans = -1\n max = arr[0]\n for i in range(1, n):\n if arr[i] < max:\n ans = -1\n elif arr[i] >= max:\n if ans == -1 and i != n - 1:\n ans = arr[i]\n max = arr[i]\n return ans", "def findelement(arr, n):\n l = len(arr)\n i = l - 2\n right_min = [0] * l\n right_min[l - 1] = arr[l - 1]\n while i >= 0:\n if arr[i] <= right_min[i + 1]:\n right_min[i] = arr[i]\n elif arr[i] > right_min[i + 1]:\n right_min[i] = right_min[i + 1]\n i -= 1\n i = 1\n left_max = arr[0]\n while i < l - 1:\n if arr[i] >= left_max:\n if arr[i] == right_min[i]:\n return arr[i]\n left_max = arr[i]\n i += 1\n return -1", "def findelement(arr, n):\n arr1 = [arr[n - 1]]\n m = arr[n - 1]\n for i in range(n - 2, -1, -1):\n if arr[i] < m:\n arr1.append(arr[i])\n m = arr[i]\n else:\n arr1.append(m)\n arr1.reverse()\n m = arr[0]\n for i in range(1, n - 1):\n if arr[i] >= m and arr[i] <= arr1[i + 1]:\n return arr[i]\n if arr[i] > m:\n m = arr[i]\n return -1", "def findelement(arr, n):\n maxi = arr[0]\n mini = arr[-1]\n ans1 = [1] * n\n ans2 = [1] * n\n for i in range(n):\n if arr[i] > maxi:\n maxi = arr[i]\n ans1[i] = maxi\n for i in range(n - 1, -1, -1):\n if arr[i] < mini:\n mini = arr[i]\n ans2[i] = mini\n for i in range(1, n - 1):\n if ans1[i] == ans2[i]:\n return ans1[i]\n else:\n return -1", "def findelement(arr, n):\n flag = 0\n m = arr[0]\n if arr == sorted(arr):\n return arr[1]\n for i in range(n - 1):\n if m <= arr[i]:\n m = arr[i]\n flag = i\n for i in range(flag, n):\n if m > arr[i]:\n return -1\n if flag != 0:\n return m\n return -1", "def findelement(arr, n):\n (max_left, min_right, max_l, min_r) = ([], [], float('-inf'), float('inf'))\n for i in range(0, n):\n (max_l, min_r) = (max(max_l, arr[i]), min(min_r, arr[n - 1 - i]))\n max_left.append(max_l)\n min_right.append(min_r)\n for i in range(1, n - 1):\n if max_left[i] <= arr[i] <= min_right[n - 1 - i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n arr2 = {}\n ele = -1\n max = arr[0]\n min = arr[n - 1]\n for i in range(1, n):\n if arr[i] >= max:\n max = arr[i]\n arr2[max] = 1\n for i in range(n - 2, -1, -1):\n if arr[i] <= min:\n min = arr[i]\n if min in arr2.keys():\n ele = arr[i]\n return ele", "def findelement(arr, n):\n (arr1, arr2) = ([1] * n, [1] * n)\n maxi = arr[0]\n mini = arr[-1]\n for i in range(n):\n if arr[i] > maxi:\n maxi = arr[i]\n arr1[i] = maxi\n for i in range(n - 1, -1, -1):\n if arr[i] < mini:\n mini = arr[i]\n arr2[i] = mini\n for i in range(1, n - 1):\n if arr1[i] == arr2[i]:\n return arr1[i]\n else:\n return -1", "def findelement(arr, n):\n (arr1, arr2) = ([1] * n, [1] * n)\n max = arr[0]\n min = arr[-1]\n for i in range(n):\n if arr[i] > max:\n max = arr[i]\n arr1[i] = max\n for i in range(n - 1, -1, -1):\n if arr[i] < min:\n min = arr[i]\n arr2[i] = min\n for i in range(1, n - 1):\n if arr1[i] == arr2[i]:\n return arr1[i]\n else:\n return -1", "def findelement(arr, n):\n max_left = []\n min_right = []\n max_l = -1\n min_r = 100000000.0\n for i in range(0, n):\n max_l = max(max_l, arr[i])\n max_left.append(max_l)\n for i in range(len(arr) - 1, -1, -1):\n min_r = min(min_r, arr[i])\n min_right.append(min_r)\n min_right.reverse()\n for i in range(1, n - 1):\n if max_left[i] <= arr[i] and arr[i] <= min_right[i]:\n return arr[i]\n return -1", "def findelement(a, n):\n\n def check(m):\n x = 0\n for i in range(m):\n if a[i] > a[m]:\n x = x + 1\n break\n if x == 0:\n return True\n\n def check1(m):\n x = 0\n for i in range(m + 1, n):\n if a[i] < a[m]:\n x = x + 1\n break\n if x == 0:\n return True\n y = 0\n for i in range(1, n - 1):\n if check(i) == True and check1(i) == True:\n return a[i]\n y = y + 1\n break\n if y == 0:\n return -1", "def findelement(arr, n):\n (left_max, left_max_elem) = ([], float('-inf'))\n (right_min, right_min_elem) = ([], float('inf'))\n dict_ = {}\n for index in range(n):\n elem = arr[index]\n if arr[index] > left_max_elem:\n left_max_elem = elem\n if arr[-index - 1] < right_min_elem:\n right_min_elem = arr[-index - 1]\n left_max.append(left_max_elem)\n right_min.append(right_min_elem)\n for index in range(1, n - 1):\n left = left_max[index - 1] if index > 0 else float('inf')\n if left <= arr[index] <= right_min[-index - 1]:\n return arr[index]\n return -1", "def check(arr, n, ind):\n i = ind - 1\n j = ind + 1\n while i >= 0:\n if arr[i] > arr[ind]:\n return False\n i -= 1\n while j < n:\n if arr[j] < arr[ind]:\n return False\n j += 1\n return True\n\ndef findelement(arr, n):\n for i in range(1, n - 1):\n if check(arr, n, i):\n return arr[i]\n return -1", "def findelement(arr, n):\n maxi = []\n cur_max = arr[0]\n if n <= 2:\n return -1\n for i in range(n):\n if cur_max < arr[i]:\n cur_max = arr[i]\n maxi.append(cur_max)\n mini = []\n cur_min = arr[n - 1]\n for i in range(n - 1, -1, -1):\n if cur_min > arr[i]:\n cur_min = arr[i]\n mini.append(cur_min)\n mini.reverse()\n for i in range(1, n - 1):\n if arr[i] >= maxi[i] and arr[i] <= mini[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n maxi = [arr[0]]\n mini = [arr[-1]]\n for i in range(1, n):\n maxi.append(max(maxi[-1], arr[i]))\n for i in range(n - 2, -1, -1):\n mini.insert(0, min(mini[0], arr[i]))\n for i in range(1, n - 1):\n if mini[i] == maxi[i]:\n return mini[i]\n return -1", "def findelement(arr, n):\n max_arr = []\n maxi = arr[0]\n for i in range(n):\n if arr[i] > maxi:\n maxi = arr[i]\n max_arr.append(maxi)\n min_arr = []\n mini = arr[-1]\n for i in range(n - 1, -1, -1):\n if arr[i] < mini:\n mini = arr[i]\n min_arr.append(mini)\n min_arr.reverse()\n for i in range(1, n - 1):\n if min_arr[i] == max_arr[i]:\n return min_arr[i]\n else:\n return -1", "def findelement(arr, n):\n for i in range(1, n - 1):\n curr = arr[i]\n left = i - 1\n right = i + 1\n while left > -1:\n if arr[left] <= curr:\n left -= 1\n else:\n break\n while right < n:\n if arr[right] >= curr:\n right += 1\n else:\n break\n if left == -1 and right == n:\n return curr\n else:\n return -1", "def findelement(arr, n):\n max = []\n ele = arr[0]\n max.append(ele)\n for i in range(1, n):\n if arr[i] > ele:\n ele = arr[i]\n max.append(ele)\n min = []\n ele = arr[n - 1]\n min.append(ele)\n for i in range(n - 2, -1, -1):\n if arr[i] < ele:\n ele = arr[i]\n min.append(ele)\n min.reverse()\n for i in range(0, n):\n if i != 0 and i != n - 1 and (min[i] == max[i]):\n ele = min[i]\n return ele\n return -1", "def findelement(arr, n):\n maxi = arr[0]\n for i in range(1, n - 1):\n maxi = max(maxi, arr[i])\n if maxi <= arr[i] and min(arr[i + 1:]) >= arr[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n max_lv = arr[0]\n sol = -1\n for i in range(1, len(arr) - 1):\n if arr[i] >= max_lv:\n j = i + 1\n while j < n:\n if arr[i] <= arr[j]:\n j += 1\n else:\n break\n if j == n and i < n - 1:\n sol = arr[i]\n break\n else:\n max_lv = arr[i]\n return sol", "def findelement(arr, n):\n right = [0] * n\n right[n - 1] = arr[n - 1]\n left = [0] * n\n left[0] = arr[0]\n m = n - 1\n for i in range(1, n):\n left[i] = max(left[i - 1], arr[i])\n for i in range(n - 2, -1, -1):\n right[i] = min(right[i + 1], arr[i])\n for i in range(1, n - 1):\n if arr[i] >= left[i] and arr[i] <= right[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n L = [arr[0]]\n ele = arr[0]\n for i in range(1, n):\n if arr[i] > ele:\n ele = arr[i]\n L.append(ele)\n R = [arr[-1]]\n ele = arr[-1]\n for i in range(n - 2, -1, -1):\n if arr[i] < ele:\n ele = arr[i]\n R.append(ele)\n R.reverse()\n for i in range(1, n - 1):\n if arr[i] >= L[i] and arr[i] <= R[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n mini = [arr[n - 1]]\n for i in range(n - 2, 1, -1):\n if mini[-1] >= arr[i]:\n mini.append(arr[i])\n else:\n mini.append(mini[-1])\n leftmaxi = arr[0]\n for i in range(1, n - 1):\n if leftmaxi <= arr[i] <= mini[-1]:\n return arr[i]\n mini.pop()\n leftmaxi = max(leftmaxi, arr[i])\n return -1", "def leftRight(n, arr):\n left = [0] * n\n right = [0] * n\n left[0] = arr[0]\n right[n - 1] = arr[n - 1]\n for i in range(1, n):\n left[i] = max(left[i - 1], arr[i])\n for i in range(n - 1, 0, -1):\n right[i - 1] = min(right[i], arr[i - 1])\n for i in range(1, n - 1):\n (l, r) = (left[i - 1], right[i + 1])\n if arr[i] >= l and arr[i] <= r:\n return arr[i]\n return -1\n\ndef findelement(arr, n):\n return leftRight(n, arr)", "def findelement(arr, n):\n leftMax = [None] * n\n leftMax[0] = arr[0]\n for i in range(1, n):\n leftMax[i] = max(leftMax[i - 1], arr[i])\n rightMin = [None] * n\n rightMin[n - 1] = arr[n - 1]\n for i in range(n - 2, -1, -1):\n rightMin[i] = min(rightMin[i + 1], arr[i])\n for i in range(1, n - 1):\n if leftMax[i - 1] <= arr[i] and arr[i] <= rightMin[i + 1]:\n return arr[i]\n return -1", "def findelement(arr, n):\n maxarr = []\n minarr = []\n maxx = arr[0]\n minn = arr[n - 1]\n for i in range(1, n - 1):\n if arr[i] > maxx:\n maxx = arr[i]\n maxarr.append(maxx)\n for j in range(n - 1, 0, -1):\n if arr[j] < minn:\n minn = arr[j]\n minarr.insert(0, minn)\n for i in range(n - 2):\n if minarr[i] == maxarr[i]:\n return arr[i + 1]\n return -1", "def findelement(arr, n):\n i = 1\n while i < n - 1:\n found = True\n for j in range(n):\n if j < i and arr[j] > arr[i]:\n found = False\n break\n if j > i and arr[j] < arr[i]:\n found = False\n break\n if found:\n return arr[i]\n i += 1\n return -1", "def findelement(arr, n):\n big = arr[0]\n small = 9999999999999\n for i in range(1, n - 1):\n if arr[i] > big:\n big = arr[i]\n for i in range(1, n - 1):\n if arr[i] < small:\n small = arr[i]\n if small == arr[1] and small >= arr[0] and (small < arr[n - 1]):\n return small\n if big <= arr[n - 1] and big >= arr[0] and (big == arr[n - 2]):\n return big\n else:\n return -1", "def findelement(arr, n):\n n = len(arr)\n l = [0] * n\n r = [0] * n\n max_e = arr[0]\n min_e = arr[-1]\n for i in range(n):\n if max_e < arr[i]:\n max_e = arr[i]\n l[i] = max_e\n for i in range(n - 1, -1, -1):\n if min_e > arr[i]:\n min_e = arr[i]\n r[i] = min_e\n for i in range(1, n - 1):\n if arr[i] >= l[i - 1] and arr[i] <= r[i + 1]:\n return arr[i]\n return -1", "def findelement(arr, n):\n for i in range(1, n - 1):\n j = i - 1\n k = i + 1\n flag = True\n while j >= 0:\n if arr[i] < arr[j]:\n flag = False\n break\n j -= 1\n while flag and k < n:\n if arr[k] < arr[i]:\n flag = False\n break\n k += 1\n if flag:\n return arr[i]\n return -1", "def findelement(arr, n):\n l = []\n r = []\n ml = -3\n mr = 100000000.0\n for i in range(0, n):\n ml = max(ml, arr[i])\n l.append(ml)\n for i in range(len(arr) - 1, -1, -1):\n mr = min(mr, arr[i])\n r.append(mr)\n r.reverse()\n for i in range(1, n - 1):\n if l[i] <= arr[i] and arr[i] <= r[i]:\n return arr[i]\n return -1", "from collections import defaultdict\n\ndef findelement(arr, n):\n dec = defaultdict(int)\n right_min = arr[n - 1]\n for i in range(n - 2, -1, -1):\n if arr[i] <= right_min:\n dec[arr[i], i] += 1\n right_min = arr[i]\n left_max = arr[0]\n for i in range(1, n - 1):\n if arr[i] >= left_max:\n dec[arr[i], i] += 1\n left_max = arr[i]\n if dec[arr[i], i] == 2:\n return arr[i]\n return -1", "def findelement(arr, n):\n ret = False\n maxima = arr[0]\n if n < 3:\n return -1\n for i in range(1, n):\n if arr[i] >= maxima:\n if not ret and i != n - 1:\n maxima = arr[i]\n ret = True\n else:\n ret = False\n if ret:\n return maxima\n else:\n return -1", "def findelement(arr, n):\n nsl = [-1]\n st = [arr[0]]\n for i in range(1, len(arr)):\n while st and st[-1] <= arr[i]:\n st.pop()\n if len(st) == 0:\n nsl.append(1)\n else:\n nsl.append(-1)\n st.append(arr[i])\n a = arr.copy()\n a.reverse()\n nsr = [-1]\n st1 = [a[0]]\n for i in range(1, len(a)):\n while st1 and st1[-1] >= a[i]:\n st1.pop()\n if len(st1) == 0:\n nsr.append(1)\n else:\n nsr.append(-1)\n st1.append(a[i])\n nsr.reverse()\n for i in range(len(arr)):\n if nsl[i] == 1 and nsr[i] == 1:\n return arr[i]\n return -1", "def findelement(arr, n):\n left_max_arr = []\n left_max = -99999999\n for i in range(n):\n if arr[i] >= left_max:\n left_max = arr[i]\n left_max_arr.append(left_max)\n right_min = 99999999\n right_min_arr = []\n for i in range(n):\n if arr[n - i - 1] <= right_min:\n right_min = arr[n - i - 1]\n right_min_arr.append(right_min)\n for i in range(1, n - 1):\n if arr[i] >= left_max_arr[i] and arr[i] <= right_min_arr[n - i - 1]:\n return arr[i]\n return -1", "def findelement(arr, n):\n for i in range(1, n - 1):\n c = True\n m = i\n while i > 0:\n if arr[m] >= arr[i - 1]:\n i -= 1\n else:\n c = False\n break\n if c == False:\n continue\n else:\n i = m\n while i < n - 1:\n if arr[m] <= arr[i + 1]:\n i += 1\n else:\n c = False\n break\n if c == True:\n return arr[m]\n return -1", "def findelement(arr, n):\n (l, t) = ([arr[0]], [arr[n - 1]])\n for i in range(1, n):\n l.append(max(arr[i], l[-1]))\n for i in range(n - 2, -1, -1):\n t.append(min(arr[i], t[-1]))\n t = t[::-1]\n for i in range(1, n - 1):\n if arr[i] == l[i] and arr[i] == t[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n max_so_far = []\n min_so_far = [0] * n\n curmax = 0\n curmin = 100001\n if n == 0:\n return -1\n for i in range(n):\n if arr[i] > curmax:\n curmax = arr[i]\n max_so_far.append(curmax)\n for i in range(n):\n if arr[n - i - 1] < curmin:\n curmin = arr[n - i - 1]\n min_so_far[n - i - 1] = curmin\n for i in range(n):\n if arr[i] >= max_so_far[i] and arr[i] <= min_so_far[i] and (i != 0) and (i != n - 1):\n return arr[i]\n return -1", "def findelement(arr, n):\n small_flag = 0\n big_flag = 0\n for i in range(n):\n for j in range(i):\n if arr[j] > arr[i]:\n small_flag = 1\n break\n for k in range(i + 1, n):\n if arr[k] < arr[i]:\n big_flag = 1\n break\n if small_flag == 0 and big_flag == 0 and (i != n - 1) and (i != 0):\n return arr[i]\n else:\n small_flag = 0\n big_flag = 0\n return -1", "def findelement(arr, n):\n leftmax = []\n rightmin = []\n mx = arr[0]\n j = 0\n while j < n:\n if mx < arr[j]:\n mx = arr[j]\n j += 1\n leftmax.append(mx)\n j = -1\n mn = arr[-1]\n while j >= -n:\n if arr[j] < mn:\n mn = arr[j]\n j -= 1\n rightmin.append(mn)\n j = 1\n rightmin = rightmin[::-1]\n if arr[0] >= leftmax[1] and arr[0] <= rightmin[1]:\n return arr[0]\n while j < n - 1:\n if arr[j] >= leftmax[j - 1] and arr[j] <= rightmin[j + 1]:\n return arr[j]\n j += 1\n return -1", "import copy\n\ndef findelement(arr, n):\n left_max = [0] * n\n right_min = [0] * n\n left_max[0] = arr[0]\n right_min[n - 1] = arr[n - 1]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], arr[i])\n for i in range(n - 2, -1, -1):\n right_min[i] = min(right_min[i + 1], arr[i])\n for i in range(1, n - 1):\n if arr[i] >= left_max[i] and arr[i] <= right_min[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n left = [0] * n\n right = [0] * n\n left[0] = arr[0]\n mini = arr[0]\n for i in range(1, n):\n if arr[i] > mini:\n mini = arr[i]\n left[i] = mini\n right[-1] = arr[-1]\n mini = arr[-1]\n for i in range(n - 2, -1, -1):\n if arr[i] < mini:\n mini = arr[i]\n right[i] = mini\n for i in range(1, n - 1):\n if left[i] == right[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n for i in range(1, n - 1):\n l = i - 1\n r = i + 1\n flag = True\n while l >= 0:\n if arr[i] < arr[l]:\n flag = False\n break\n l -= 1\n while r <= n - 1:\n if arr[i] > arr[r]:\n flag = False\n break\n r += 1\n if flag:\n return arr[i]\n return -1", "def findelement(arr, n):\n b = [0] * n\n c = [0] * n\n b[0] = 0\n c[n - 1] = 0\n l = arr[0]\n for i in range(1, n):\n if arr[i - 1] > l:\n l = arr[i - 1]\n b[i] = l\n s = arr[n - 1]\n for i in range(n - 2, -1, -1):\n if arr[i + 1] < s:\n s = arr[i + 1]\n c[i] = s\n flag = 0\n for i in range(n):\n if arr[i] >= b[i] and arr[i] <= c[i] and (i != 0):\n return arr[i]\n flag = 1\n if flag == 0:\n return -1"], "starter_code": "def findelement( arr, n):\n", "input_output": {"fn_name": "findElement", "inputs": ["N = 4\r\nA[] = {4, 2, 5, 7}", "N = 3\r\nA[] = {11, 9, 12}"], "outputs": ["5", "-1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/unsorted-array4925/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "findelement", "task_id": "TACO_lite/519", "example": [[[4, [4, 2, 5, 7]], [3, [11, 9, 12]]], ["5", "-1"]]} +{"requirement": "A palindrome is a series of characters that read the same forwards as backwards such as \"hannah\", \"racecar\" and \"lol\".\n\nFor this Kata you need to write a function that takes a string of characters and returns the length, as an integer value, of longest alphanumeric palindrome that could be made by combining the characters in any order but using each character only once. The function should not be case sensitive.\n\nFor example if passed \"Hannah\" it should return 6 and if passed \"aabbcc_yYx_\" it should return 9 because one possible palindrome would be \"abcyxycba\".", "solutions": ["from collections import Counter\n\ndef longest_palindrome(s):\n c = Counter(filter(str.isalnum, s.lower()))\n return sum((v // 2 * 2 for v in c.values())) + any((v % 2 for v in c.values()))", "from collections import Counter\nimport re\n\ndef longest_palindrome(s):\n (n, odds, c) = (0, 0, Counter(re.sub('\\\\W+|_', '', s.lower())))\n for v in c.values():\n (x, r) = divmod(v, 2)\n n += 2 * x\n odds += r\n return n + bool(odds)", "from collections import Counter\n\ndef longest_palindrome(s):\n freq = Counter((c for c in s.lower() if c.isalnum()))\n (even, odd) = ([], [])\n for (k, v) in freq.items():\n if v % 2:\n odd.append(v - 1)\n else:\n even.append(v)\n return sum(even) + (sum(odd) + 1 if odd else 0)", "def longest_palindrome(s):\n new_s = ''.join([x for x in s.lower() if x.isalnum()])\n k = [new_s.count(x) for x in set(new_s)]\n res = 0\n for x in k:\n if x % 2 == 0:\n res += x\n else:\n res += x - 1\n return res + 1 if any((x % 2 == 1 for x in k)) else res", "from collections import Counter\n\ndef longest_palindrome(s):\n if s == '':\n return 0\n s = s.upper()\n x = Counter(s)\n len = 0\n flag = False\n for i in x:\n if i.isalnum():\n if x[i] % 2 == 0:\n len += x[i]\n else:\n flag = True\n len += x[i] - 1\n if flag == True:\n return len + 1\n return len", "from collections import Counter\nfrom string import ascii_letters, digits\n\ndef longest_palindrome(data):\n cnt = Counter([d for d in data.lower() if d in ascii_letters + digits])\n even = sum([n for n in list(cnt.values()) if n % 2 == 0])\n odd = sorted([n for n in list(cnt.values()) if n % 2 != 0])[::-1]\n if len(odd) == 0:\n ans = even\n if len(odd) == 1:\n ans = even + odd[0]\n if len(odd) > 1:\n ans = even + odd[0] + sum([n - 1 for n in odd[1:]])\n return ans", "from collections import Counter\n\ndef longest_palindrome(string):\n (possibles, has_odd) = (0, False)\n for (char, c) in Counter(string.lower()).items():\n if not char.isalnum():\n continue\n if c & 1:\n possibles += c - 1\n has_odd = True\n else:\n possibles += c\n return possibles + (1 if has_odd else 0)", "from collections import Counter\n\ndef longest_palindrome(s):\n (d, r) = (Counter([x for x in s.lower() if x.isalnum()]), 0)\n for x in d.values():\n r += x // 2 * 2 + (x % 2 >> r % 2)\n return r", "from collections import Counter\n\ndef longest_palindrome(s):\n flag = res = 0\n for v in Counter(map(str.lower, filter(str.isalnum, s))).values():\n flag |= v & 1\n res += v >> 1 << 1\n return res + flag", "import re\n\ndef longest_palindrome(s):\n s = list(re.sub('[\\\\W_]+', '', s.lower()))\n solution = 0\n j = 0\n letter_count = 0\n for letter in s:\n letter_count = s.count(letter)\n if letter_count % 2 == 0:\n solution += letter_count\n else:\n solution += letter_count - 1\n j = 1\n s = [i for i in s if i != letter]\n return solution + j"], "starter_code": "def longest_palindrome(s):\n", "input_output": {"fn_name": "longest_palindrome", "inputs": [["A"], ["Hannah"], ["xyz__a_/b0110//a_zyx"], ["$aaabbbccddd_!jJpqlQx_.///yYabababhii_"], [""]], "outputs": [[1], [6], [13], [25], [0]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5a0178f66f793bc5b0001728", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "longest_palindrome", "task_id": "TACO_lite/531", "example": [[["Hannah"], ["aabbcc_yYx_"]], ["6", "9"]]} +{"requirement": "You have an initial power P, an initial score of 0 points, and a bag of tokens.\nEach token can be used at most once, has a value token[i], and has potentially two ways to use it.\n\nIf we have at least token[i] power, we may play the token face up, losing token[i] power, and gaining 1 point.\nIf we have at least 1 point, we may play the token face down, gaining token[i] power, and losing 1 point.\n\nReturn the largest number of points we can have after playing any number of tokens.\n \n\n\n\nExample 1:\nInput: tokens = [100], P = 50\nOutput: 0\n\n\nExample 2:\nInput: tokens = [100,200], P = 150\nOutput: 1\n\n\nExample 3:\nInput: tokens = [100,200,300,400], P = 200\nOutput: 2\n\n \nNote:\n\ntokens.length <= 1000\n0 <= tokens[i] < 10000\n0 <= P < 10000", "solutions": ["def bagoftokensscore(tokens: List[int], P: int) -> int:\n tokens = sorted(tokens)\n left = 0\n right = len(tokens) - 1\n points = 0\n if len(tokens) == 1:\n if tokens[0] <= P:\n return 1\n if len(tokens) == 0:\n return 0\n while left < right:\n if tokens[left] <= P:\n P -= tokens[left]\n left += 1\n points += 1\n elif tokens[left] > P and points > 0:\n P += tokens[right]\n points -= 1\n right -= 1\n elif points == 0 and tokens[left] > P:\n break\n if P >= tokens[left]:\n points += 1\n return points", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n tokens.sort()\n max_points = 0\n points = 0\n i = 0\n j = len(tokens) - 1\n while i <= j:\n if P >= tokens[i]:\n points += 1\n P -= tokens[i]\n max_points = max(points, max_points)\n i += 1\n elif points > 0:\n points -= 1\n P += tokens[j]\n j -= 1\n else:\n return max_points\n return max_points", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n (max_points, points) = (0, 0)\n tokens.sort()\n (i, j) = (0, len(tokens) - 1)\n while i <= j:\n if P < tokens[i]:\n if i == j or points == 0:\n break\n P += tokens[j]\n points -= 1\n j -= 1\n points += 1\n P -= tokens[i]\n i += 1\n max_points = max(max_points, points)\n return max(max_points, points)", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n tokens.sort()\n if not tokens or P < tokens[0]:\n return 0\n (l, r) = (0, len(tokens) - 1)\n points = 0\n while l <= r:\n if P >= tokens[l]:\n points += 1\n P -= tokens[l]\n l += 1\n elif r - l > 1:\n points -= 1\n P += tokens[r]\n r -= 1\n else:\n break\n return points", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n if not tokens:\n return 0\n tokens.sort()\n point = 0\n while tokens:\n if P < tokens[0]:\n if point and len(tokens) > 1:\n P += tokens.pop()\n point -= 1\n else:\n break\n else:\n P -= tokens.pop(0)\n point += 1\n return point", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n tokens.sort()\n maxPoints = 0\n points = 0\n (left, right) = (0, len(tokens) - 1)\n while left <= right and P >= 0:\n if P - tokens[left] >= 0:\n P -= tokens[left]\n points += 1\n maxPoints = max(maxPoints, points)\n left += 1\n elif points > 0:\n P += tokens[right]\n points -= 1\n right -= 1\n else:\n break\n return max(maxPoints, points)", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n tokens.sort()\n left = 0\n right = len(tokens) - 1\n ans = 0\n curr = 0\n while not left > right:\n if P >= tokens[left]:\n curr += 1\n ans = max(ans, curr)\n P -= tokens[left]\n left += 1\n elif curr > 0:\n P += tokens[right]\n curr -= 1\n right -= 1\n else:\n break\n return ans", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n n = len(tokens)\n tokens.sort()\n i = 0\n j = n - 1\n points = 0\n result = 0\n while i <= j:\n if tokens[i] <= P:\n points += 1\n result = max(result, points)\n P -= tokens[i]\n i += 1\n else:\n if points == 0:\n break\n P += tokens[j]\n points -= 1\n j -= 1\n return result", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n tokens.sort()\n (buyer, seller) = (0, len(tokens) - 1)\n max_items = current_items = 0\n while buyer <= seller:\n if P >= tokens[buyer]:\n P -= tokens[buyer]\n current_items += 1\n buyer += 1\n elif current_items == 0:\n break\n else:\n P += tokens[seller]\n current_items -= 1\n seller -= 1\n max_items = max(max_items, current_items)\n return max_items", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n if not len(tokens):\n return 0\n tokens.sort()\n res = 0\n deque = collections.deque(tokens)\n while len(deque) > 1 and (P >= deque[0] or res):\n while deque and P > deque[0]:\n res += 1\n P -= deque.popleft()\n if len(deque) > 1 and res:\n P += deque.pop()\n res -= 1\n if deque and P >= deque[0]:\n res += 1\n return res", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n tokens.sort()\n\n def twoPointer(tokens, P):\n i = 0\n j = len(tokens) - 1\n score = 0\n maxScore = 0\n while i <= j:\n flag = False\n while i < len(tokens) and P >= tokens[i]:\n score += 1\n P -= tokens[i]\n i += 1\n flag = True\n if flag:\n maxScore = max(score, maxScore)\n continue\n if score > 0:\n score -= 1\n P += tokens[j]\n j -= 1\n elif P < tokens[i]:\n return score\n return maxScore\n\n def helper(tokens, P, score):\n maxVal = score\n if score > 0 and len(tokens) > 0:\n maxVal = max(helper(tokens[:len(tokens) - 1], P + tokens[len(tokens) - 1], score - 1), maxVal)\n for i in range(len(tokens) - 1, -1, -1):\n if P >= tokens[i]:\n maxVal = max(helper(tokens[:i] + tokens[i + 1:], P - tokens[i], score + 1), maxVal)\n return maxVal\n return twoPointer(tokens, P)"], "starter_code": "def bagoftokensscore(tokens: List[int], P: int) -> int:\n", "input_output": {"fn_name": "bagOfTokensScore", "inputs": [[[100], 50]], "outputs": [0]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Two Pointers", "Greedy", "Sorting"], "name": null, "source": "leetcode", "tags": ["Data structures", "Sorting", "Amortized analysis", "Greedy algorithms"], "skill_types": ["Sorting", "Amortized analysis", "Data structures", "Greedy algorithms"], "url": "https://leetcode.com/problems/bag-of-tokens/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "bagoftokensscore", "task_id": "TACO_lite/520", "example": [[[[100], 50], [[100, 200], 150], [[100, 200, 300, 400], 200]], ["0", "1", "2"]]} +{"requirement": "Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).\n\nNote: The solution set must not contain duplicate subsets.\n\nExample:\n\n\nInput: [1,2,2]\nOutput:\n[\n [2],\n [1],\n [1,2,2],\n [2,2],\n [1,2],\n []\n]", "solutions": ["def subsetswithdup(nums):\n\n def dfs(idx, path):\n subsets.append(path)\n for i in range(idx, len(nums)):\n if i > idx and nums[i] == nums[i - 1]:\n continue\n dfs(i + 1, path + [nums[i]])\n nums.sort()\n subsets = []\n dfs(0, [])\n return subsets", "def subsets(nums):\n if len(nums) == 0:\n return [[]]\n ret = []\n for (i, n) in enumerate(nums):\n if i > 0 and n == nums[i - 1]:\n continue\n for s in self.subsets(nums[i + 1:]):\n ret.append([n] + s)\n return [[]] + ret\n\ndef subsetswithdup(nums):\n nums.sort()\n return self.subsets(nums)", "def subsetswithdup(nums):\n result = []\n res = []\n self.df(nums, 0, result, res)\n return res\n\ndef df(nums, idx, result, res):\n if idx > len(nums):\n return\n if result not in res:\n res.append(result)\n for i in range(idx, len(nums)):\n self.df(nums, i + 1, sorted(result + [nums[i]]), res)", "def subsetswithdup(nums):\n\n def dfs(depth, start, cur):\n if cur not in res:\n res.append(cur)\n if depth == len(nums):\n return\n for i in range(start, len(nums)):\n dfs(depth + 1, i + 1, cur + [nums[i]])\n nums.sort()\n res = []\n dfs(0, 0, [])\n return list(res)", "def subsetswithdup(nums):\n\n def backtrack(nums, start, tmp, res):\n res.append(tmp[:])\n for i in range(start, len(nums)):\n if i > start and nums[i] == nums[i - 1]:\n continue\n else:\n tmp.append(nums[i])\n backtrack(nums, i + 1, tmp, res)\n del tmp[-1]\n res = list()\n backtrack(sorted(nums), 0, [], res)\n return res", "def subsetswithdup(nums):\n nums = sorted(nums)\n res = [[]]\n self._helpFun(nums, res, [])\n return res\n\ndef _helpFun(nums, res, curr):\n if not nums:\n if curr not in res:\n res.append(curr)\n return\n for i in range(len(nums)):\n newCurr = curr + [nums[i]]\n if newCurr not in res:\n res.append(newCurr)\n self._helpFun(nums[i + 1:], res, newCurr)"], "starter_code": "def subsetswithdup(nums: List[int]) -> List[List[int]]:\n", "input_output": {"fn_name": "subsetsWithDup", "inputs": [[[1, 2, 2]], [[0]]], "outputs": [[[], [1], [1, 2], [1, 2, 2], [2], [2, 2]], [[], [0]]]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Backtracking", "Bit Manipulation"], "name": null, "source": "leetcode", "tags": ["Bit manipulation", "Data structures", "Complete search"], "skill_types": ["Bit manipulation", "Data structures", "Complete search"], "url": "https://leetcode.com/problems/subsets-ii/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "subsetswithdup", "task_id": "TACO_lite/482", "example": [[], []]} +{"requirement": "You are given a cubic dice with 6 faces. All the individual faces have a number printed on them. The numbers are in the range of 1 to 6, like any ordinary dice. You will be provided with a face of this cube, your task is to guess the number on the opposite face of the cube.\nExample 1:\nInput:\nN = 6\nOutput:\n1\nExplanation:\nFor dice facing number 6 opposite face\nwill have the number 1.\nExample 2:\nInput:\nN = 2\nOutput:\n5\nExplanation:\nFor dice facing number 5 opposite face\nwill have the number 2.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function oppositeFaceOfDice() which takes an integer N as an input parameter and return the number on the opposite face of the dice.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 6", "solutions": ["def oppositefaceofdice(N):\n d = {1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}\n return d[N]", "def oppositefaceofdice(N):\n return 7 - N", "def oppositefaceofdice(N):\n A = 7\n ans = A - N\n return ans", "def oppositefaceofdice(N):\n dice = {'1': '6', '2': '5', '3': '4', '4': '3', '5': '2', '6': '1'}\n return dice[str(N)]", "def oppositefaceofdice(N):\n dice = {6: 1, 5: 2, 4: 3, 3: 4, 2: 5, 1: 6}\n for i in dice:\n if i == N:\n return dice[i]", "def oppositefaceofdice(n):\n return 7 - n", "def oppositefaceofdice(N):\n if N == 1:\n return 6\n elif N == 2:\n return 5\n elif N == 3:\n return 4\n elif N == 4:\n return 3\n elif N == 5:\n return 2\n elif N == 6:\n return 1", "def oppositefaceofdice(N):\n a = 7\n ans = a - N\n return ans", "def oppositefaceofdice(N):\n switcher = {1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}\n return switcher.get(N, 'Invalid month')", "def oppositefaceofdice(N):\n arr = [1, 2, 3, 4, 5, 6]\n for i in range(N):\n if arr[i] == N:\n return arr[int(5 - i)]", "def oppositefaceofdice(N):\n return 6 - N + 1", "def oppositefaceofdice(N):\n a = 7\n res = a - N\n return res", "def oppositefaceofdice(N):\n result = {1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}\n return result.get(N)", "def oppositefaceofdice(N):\n All = 7\n if N < All:\n return All - N\n else:\n return -1", "def oppositefaceofdice(N):\n x = {i: 7 - i for i in range(1, 7)}\n return x[N]", "def oppositefaceofdice(N):\n numbers = [1, 2, 3, 4, 5, 6]\n for number in numbers:\n if number == N:\n index = -number\n return numbers[index]", "def oppositefaceofdice(N):\n q = 7\n e = q - N\n return e", "def oppositefaceofdice(N):\n opp = list(reversed(range(1, 7)))\n nor = list(range(1, 7))\n dic = {k: v for (k, v) in zip(opp, nor)}\n return dic[N]"], "starter_code": "def oppositefaceofdice(N):\n", "input_output": {"inputs": ["N = 6", "N = 2"], "outputs": ["1", "5"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/the-dice-problem2316/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "oppositefaceofdice", "task_id": "TACO_lite/505", "example": [[[6], [2]], ["1", "5"]]} +{"requirement": "## Number pyramid\n\nNumber pyramid is a recursive structure where each next row is constructed by adding adjacent values of the current row. For example:\n\n```\nRow 1 [1 2 3 4]\nRow 2 [3 5 7]\nRow 3 [8 12]\nRow 4 [20]\n```\n\n___\n\n## Task\n\nGiven the first row of the number pyramid, find the value stored in its last row.\n\n___\n\n## Examples\n\n```python\nreduce_pyramid([1]) == 1\nreduce_pyramid([3, 5]) == 8\nreduce_pyramid([3, 9, 4]) == 25\n```\n\n___\n\n## Performance tests\n\n```python\nNumber of tests: 10\nList size: 10,000\n```", "solutions": ["from operator import mul\n\ndef reduce_pyramid(base):\n return sum(map(mul, base, comb_n(len(base) - 1)))\n\ndef comb_n(n):\n c = 1\n for k in range(0, n + 1):\n yield c\n c = c * (n - k) // (k + 1)", "def reduce_pyramid(base):\n (c, t, ll) = (1, 0, len(base) - 1)\n for (i, v) in enumerate(base):\n t += c * v\n c = c * (ll - i) // (i + 1)\n return t", "def reduce_pyramid(base):\n (s, c) = (0, 1)\n for (i, x) in enumerate(base, 1):\n s += c * x\n c = c * (len(base) - i) // i\n return s", "def reduce_pyramid(base):\n (tot, c, n) = (0, 1, len(base) - 1)\n for i in range(n + 1 >> 1):\n tot += c * (base[i] + base[n - i])\n c = c * (n - i) // (i + 1)\n if not n & 1:\n tot += c * base[n >> 1]\n return tot", "def _coefs(l):\n n = 1\n for i in range(l):\n yield n\n n = n * (l - i - 1) // (i + 1)\n yield n\n\ndef reduce_pyramid(base):\n coefs = _coefs(len(base))\n return sum((next(coefs) * n for n in base))", "def reduce_pyramid(Q):\n (R, U) = (0, 1)\n for (F, V) in enumerate(Q):\n (R, U) = (R + V * U, U * (len(Q) + ~F) // -~F)\n return R", "def reduce_pyramid(base):\n (n, c, r) = (len(base) - 1, 1, 0)\n for (i, x) in enumerate(base):\n r += c * x\n c = c * (n - i) // (i + 1)\n return r", "def pascal(n):\n line = [1]\n for k in range(n):\n line.append(line[k] * (n - k) // (k + 1))\n return line\n\ndef reduce_pyramid(a):\n x = len(a) - 1\n C = pascal(x)\n s = 0\n for (i, v) in enumerate(a):\n s += C[i] * v\n return s", "def reduce_pyramid(base):\n sm = 0\n nb = 1\n for (i, u) in enumerate(base, 1):\n sm += nb * u\n nb = nb * (len(base) - i) // i\n return sm", "def reduce_pyramid(b):\n (p, r) = (1, b[0])\n for i in range(1, len(b)):\n p = p * (len(b) - i) // i\n r += b[i] * p\n return r"], "starter_code": "def reduce_pyramid(base):\n", "input_output": {"fn_name": "reduce_pyramid", "inputs": [[[1]], [[3, 5]], [[3, 9, 4]], [[5, 6, 7, 8]], [[13, 1, 21, 9]], [[13, 76, 21, 42, 63]]], "outputs": [[1], [8], [25], [52], [88], [674]]}, "difficulty": "EASY", "raw_tags": ["Performance", "Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5cc2cd9628b4200020880248", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "reduce_pyramid", "task_id": "TACO_lite/534", "example": [[[[1]], [[3, 5]], [[3, 9, 4]]], ["1", "8", "25"]]} +{"requirement": "Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.\n\nExample 1:\n\nInput:nums = [1,1,1], k = 2\nOutput: 2\n\n\n\nNote:\n\nThe length of the array is in range [1, 20,000].\nThe range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].", "solutions": ["def subarraysum(nums, k):\n dic = {}\n numSum = 0\n dic[0] = 1\n ans = 0\n for i in range(len(nums)):\n numSum += nums[i]\n if numSum - k in dic:\n ans += dic[numSum - k]\n if numSum in dic:\n dic[numSum] += 1\n else:\n dic[numSum] = 1\n return ans", "def subarraysum(nums, k):\n cum_sum_dict = {}\n cum_sum_dict[0] = 1\n left_sum = 0\n count = 0\n for t in nums:\n left_sum = left_sum + t\n if left_sum - k in cum_sum_dict:\n count = count + cum_sum_dict[left_sum - k]\n if left_sum in cum_sum_dict:\n cum_sum_dict[left_sum] = cum_sum_dict[left_sum] + 1\n else:\n cum_sum_dict[left_sum] = 1\n return count", "def subarraysum(nums, k):\n l_nums = len(nums)\n c = 0\n state = dict()\n state[0] = 1\n sum = 0\n for idx in range(0, l_nums):\n sum += nums[idx]\n if sum - k in state:\n c += state[sum - k]\n state[sum] = (state[sum] if sum in state else 0) + 1\n return c", "def subarraysum(nums, k):\n (count, current, solution) = ({0: 1}, 0, 0)\n for num in nums:\n current += num\n solution += count.get(current - k, 0)\n count[current] = count.get(current, 0) + 1\n return solution", "def subarraysum(nums, k):\n sum_map = {0: 1}\n count = 0\n total_sum = 0\n total = 0\n for numb in nums:\n total += numb\n count += sum_map.get(total - k, 0)\n sum_map[total] = sum_map.get(total, 0) + 1\n return count", "def subarraysum(nums, k):\n (count, cur, res) = ({0: 1}, 0, 0)\n for v in nums:\n cur += v\n res += count.get(cur - k, 0)\n count[cur] = count.get(cur, 0) + 1\n return res", "def subarraysum(nums, k):\n count = collections.Counter()\n count[0] = 1\n ans = su = 0\n for x in nums:\n su += x\n ans += count[su - k]\n count[su] += 1\n return ans"], "starter_code": "def subarraysum(nums: List[int], k: int) -> int:\n", "input_output": {"fn_name": "subarraySum", "inputs": [[[1, 1, 1], 2]], "outputs": [2]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Prefix Sum", "Array", "Hash Table"], "name": null, "source": "leetcode", "tags": ["Data structures", "Range queries"], "skill_types": ["Data structures", "Range queries"], "url": "https://leetcode.com/problems/subarray-sum-equals-k/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "subarraysum", "task_id": "TACO_lite/502", "example": [[[[1, 1, 1], 2]], ["2"]]} +{"requirement": "Given a Binary Tree and a target key, you need to find all the ancestors of the given target key.\n 1\n / \\\n 2 3\n / \\\n 4 5\n /\n 7\nKey: 7\nAncestor: 4 2 1\nExample 1:\nInput:\n 1\n / \\\n 2 3\ntarget = 2\nOutput: 1\nExample 2:\nInput:\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 8\n /\n 7\ntarget = 7\nOutput: 4 2 1\nYour Task:\nYour task is to complete the function Ancestors() that finds all the ancestors of the key in the given binary tree.\nNote:\nThe return type is\ncpp: vector\nJava: ArrayList\npython: list\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(H).\nNote: H is the height of the tree and this space is used implicitly for the recursion stack.\nConstraints:\n1 ≤ N ≤ 10^{3}\n1 ≤ data of node ≤ 10^{4}", "solutions": ["def Ancestors(root, target):\n\n def ansc(root, t, ans):\n if root == None:\n return False\n if root.data == t:\n return True\n if ansc(root.left, t, ans) or ansc(root.right, t, ans):\n ans.append(root.data)\n return True\n ans = []\n ansc(root, target, ans)\n return ans", "def Ancestors(root, target):\n ans = []\n\n def solve(root, k, ans):\n if root == None:\n return False\n if root.data == k:\n return True\n if solve(root.left, k, ans) or solve(root.right, k, ans):\n ans.append(root.data)\n return True\n solve(root, target, ans)\n return ans", "def slove(root, target, ans):\n if root is None:\n return False\n if root.data == target:\n return True\n if slove(root.left, target, ans) or slove(root.right, target, ans):\n ans.append(root.data)\n return True\n return False\n\ndef Ancestors(root, target):\n ans = []\n slove(root, target, ans)\n return ans", "def ancesstor(root, path, target):\n if root == None:\n return False\n path.append(root.data)\n if root.data == target:\n return True\n if ancesstor(root.left, path, target) or ancesstor(root.right, path, target):\n return True\n path.pop(-1)\n return False\n\ndef Ancestors(root, target):\n path = []\n ancesstor(root, path, target)\n path.pop()\n path.reverse()\n return path", "def Ancestors(root, target):\n arr = []\n\n def ans(root):\n if not root:\n return False\n if root.data == target:\n return True\n ls = ans(root.left)\n if ls:\n arr.append(root.data)\n return True\n rs = ans(root.right)\n if rs:\n arr.append(root.data)\n return True\n return False\n ans(root)\n return arr", "def Ancestors(root, target):\n R = []\n\n def rec(root, target):\n if root.data == target:\n return True\n (t1, t2) = (False, False)\n if root.left:\n t1 = rec(root.left, target)\n if root.right:\n t2 = rec(root.right, target)\n if t1 or t2:\n R.append(root.data)\n return True\n return False\n rec(root, target)\n return R", "def Ancestors(root, target):\n if root == None:\n return []\n l = []\n\n def helper(root, l):\n if root != None:\n if root.data == target:\n return 1\n if helper(root.left, l) or helper(root.right, l):\n l.append(root.data)\n return 1\n if root == None:\n return 0\n helper(root, l)\n return l", "def fun(root, l, target, res):\n if root == None:\n return\n if root.data == target:\n res.extend(l)\n l.append(root.data)\n self.fun(root.left, l, target, res)\n self.fun(root.right, l, target, res)\n l.pop()\n\ndef Ancestors(root, target):\n (l, res) = ([], [])\n self.fun(root, l, target, res)\n res = res[::-1]\n return res", "def Ancestors(root, target):\n result = []\n self.recursiveFindParent(root, target, result)\n return result\n\ndef recursiveFindParent(root, target, result):\n if not root:\n return None\n if root.data == target:\n return root\n if self.recursiveFindParent(root.left, target, result) or self.recursiveFindParent(root.right, target, result):\n result.append(root.data)\n return root\n else:\n return None", "def solve(root, ans, target, out):\n if root == None:\n return\n if root.data == target:\n ans += out.copy()\n return\n out.append(root.data)\n self.solve(root.left, ans, target, out)\n self.solve(root.right, ans, target, out)\n out.pop(-1)\n\ndef Ancestors(root, target):\n ans = []\n self.solve(root, ans, target, [])\n return ans[::-1]", "def Ancestors(root, target):\n stack = []\n stack.append([root, root])\n ans = None\n while stack:\n node = stack.pop()\n if node[0].data == target:\n ans = node\n break\n if node[0].left:\n stack.append([node[0].left, node])\n if node[0].right:\n stack.append([node[0].right, node])\n some = 0\n res = []\n while some != root:\n ans = ans[1]\n some = ans[0]\n res.append(some.data)\n return res", "def Ancestors(root, target):\n\n def pathtonode(root, k, p1):\n if root == None:\n return False\n if root.data == k:\n return True\n p1.append(root.data)\n if root.left and pathtonode(root.left, k, p1) or (root.right and pathtonode(root.right, k, p1)):\n return True\n p1.pop()\n p1 = []\n pathtonode(root, target, p1)\n p1.reverse()\n return p1", "def Ancestors(root, target):\n self.val = []\n\n def t(rt, tar, va):\n if not rt:\n return 0\n if rt.data == tar:\n return 1\n if t(rt.left, tar, va) or t(rt.right, tar, va):\n va.append(rt.data)\n return 1\n return 0\n t(root, target, self.val)\n return self.val", "def find_root_to_node(current, node, result):\n if not current:\n return False\n if current:\n result.append(current.data)\n if current.data == node:\n return True\n if self.find_root_to_node(current.left, node, result) == True:\n return True\n if self.find_root_to_node(current.right, node, result) == True:\n return True\n result.pop(-1)\n\ndef Ancestors(root, target):\n res = []\n self.find_root_to_node(root, target, res)\n return res[0:len(res) - 1][::-1]", "def Ancestors(root, target):\n self.ans = []\n\n def solve(root, n):\n if root == None:\n return False\n if root.data == n:\n return True\n l = solve(root.left, n)\n r = solve(root.right, n)\n if l or r:\n self.ans.append(root.data)\n if l:\n return l\n return r\n solve(root, target)\n return self.ans", "def Ancestors(root, target):\n arr = []\n self._ancestors(root, target, arr)\n return arr\n\ndef _ancestors(node, target, arr):\n if node is None:\n return False\n if node.data == target:\n return True\n elif self._ancestors(node.left, target, arr) == True:\n arr.append(node.data)\n return True\n elif self._ancestors(node.right, target, arr) == True:\n arr.append(node.data)\n return True", "def getT(root, target, arr):\n if not root:\n return False\n if root.data == target:\n return True\n if self.getT(root.left, target, arr) or self.getT(root.right, target, arr):\n arr.append(root.data)\n return True\n return False\n\ndef Ancestors(root, target):\n arr = []\n bl = self.getT(root, target, arr)\n return arr", "def Ancestors(root, target):\n stack = [root]\n parents = {}\n parents[root.data] = None\n while len(stack) > 0:\n current = stack.pop()\n if current.data == target:\n ancestors = []\n while parents[target]:\n ancestors.append(parents[target])\n target = parents[target]\n return ancestors\n if current.left:\n parents[current.left.data] = current.data\n stack.append(current.left)\n if current.right:\n parents[current.right.data] = current.data\n stack.append(current.right)\n return None", "def Ancestors(root, target):\n sol = []\n\n def printAns(root):\n if root == None:\n return None\n if root.data == target:\n return root\n l = printAns(root.left)\n r = printAns(root.right)\n if l or r:\n sol.append(root.data)\n return l if l else r\n val = printAns(root)\n return sol", "def Ancestors(root, target):\n list = []\n\n def find_ans(root, target, list):\n if not root:\n return False\n if root.data == target:\n return True\n list.append(root.data)\n left = find_ans(root.left, target, list)\n right = find_ans(root.right, target, list)\n if left or right:\n return True\n list.pop()\n find_ans(root, target, list)\n return list[::-1]", "def Ancestors(root, target):\n res = []\n\n def helper(root):\n if not root:\n return False\n if root.data == target:\n return True\n if helper(root.left) or helper(root.right):\n res.append(root.data)\n return True\n helper(root)\n return res", "def Ancestors(root, target):\n if root == None:\n return\n v = []\n self.helper(root, target, v)\n return v\n\ndef helper(root, x, v):\n if root == None:\n return\n left = self.helper(root.left, x, v)\n right = self.helper(root.right, x, v)\n if left or right:\n v.append(root.data)\n return True\n if root.data == x:\n return True\n return False", "def __init__():\n self.ans = []\n\ndef dfs(root, target):\n if root is None:\n return False\n if root.data == target:\n return True\n l = self.dfs(root.left, target)\n r = self.dfs(root.right, target)\n if l is True or r is True:\n self.ans.append(root.data)\n return True\n return False\n\ndef Ancestors(root, target):\n self.ans = []\n if root.data == target:\n return []\n self.dfs(root, target)\n return self.ans", "import sys\nsys.setrecursionlimit(10 ** 6)\n\ndef Ancestors(root, target):\n array = []\n\n def Recursion(root, target):\n nonlocal array\n if root == None:\n return False\n if root.data == target:\n return True\n left_tree = Recursion(root.left, target)\n right_tree = Recursion(root.right, target)\n if left_tree == True or right_tree == True:\n array.append(root.data)\n return left_tree or right_tree\n Recursion(root, target)\n return array", "def has(root):\n m = {}\n q = []\n q.append(root)\n while q:\n temp = q.pop()\n if temp.left:\n m[temp.left.data] = temp.data\n q.append(temp.left)\n if temp.right:\n m[temp.right.data] = temp.data\n q.append(temp.right)\n return m\n\ndef Ancestors(root, target):\n m = has(root)\n res = []\n while True:\n if target in m:\n res.append(m[target])\n target = m[target]\n else:\n break\n return res", "def get_all_ancestors(root, target, ancestors):\n if root == None:\n return\n if root.data == target:\n return True\n left_ans = self.get_all_ancestors(root.left, target, ancestors)\n right_ans = self.get_all_ancestors(root.right, target, ancestors)\n if left_ans or right_ans:\n ancestors.append(root.data)\n return True\n else:\n return False\n\ndef Ancestors(root, target):\n ancestors = []\n self.get_all_ancestors(root, target, ancestors)\n return ancestors", "def Ancestors(root, target):\n res = []\n\n def helper(root):\n if not root:\n return 0\n if root.data == target:\n return 1\n if helper(root.left) or helper(root.right):\n res.append(root.data)\n return 1\n return 0\n helper(root)\n return res", "def add_nodes(root, target):\n if not root:\n return False\n if root.data == target:\n return True\n if self.add_nodes(root.left, target) or self.add_nodes(root.right, target):\n self.ans.append(root.data)\n return True\n return False\n\ndef Ancestors(root, target):\n self.ans = []\n self.add_nodes(root, target)\n return self.ans", "def Ancestors(root, target):\n result = []\n self.Utils(root, target, result)\n return result[::-1]\n\ndef Utils(node, target, result):\n if not node:\n return False\n if node.data == target:\n return True\n result.append(node.data)\n l = self.Utils(node.left, target, result)\n r = self.Utils(node.right, target, result)\n if not (l or r):\n result.pop()\n return l or r", "def __init__():\n self.l1 = []\n\ndef Ancestors(root, target):\n self.solve(root, target, [])\n return self.l1\n\ndef solve(root, t, l):\n if root == None:\n return\n if root.data == t:\n self.l1 = l.copy()\n return\n self.solve(root.left, t, [root.data] + l)\n self.solve(root.right, t, [root.data] + l)", "def solve(root, arr, target):\n if not root:\n return False\n elif root.data == target:\n return True\n if self.solve(root.left, arr, target):\n arr.append(root.data)\n return True\n if self.solve(root.right, arr, target):\n arr.append(root.data)\n return True\n return False\n\ndef Ancestors(root, target):\n arr = []\n self.solve(root, arr, target)\n return arr", "def recur(root, target, res):\n if root == None:\n return\n res.append(root.data)\n if root.data == target:\n return True\n lh = self.recur(root.left, target, res)\n rh = self.recur(root.right, target, res)\n if lh == None and rh == None:\n res.pop()\n return\n elif lh == True or rh == True:\n return True\n else:\n return\n\ndef Ancestors(root, target):\n res = []\n self.recur(root, target, res)\n res.reverse()\n res.pop(0)\n return res", "def Ancestors(root, target):\n ancestor = []\n\n def finder(root):\n if root == None:\n return\n if root.data == target:\n return True\n ancestor.append(root.data)\n if finder(root.left):\n return True\n if finder(root.right):\n return True\n ancestor.pop()\n finder(root)\n return reversed(ancestor)", "xx = 0\n\ndef Ancestors(root, target):\n Z = []\n self.kthAncestor(root, target, Z)\n return Z\n\ndef size(root, e):\n global xx\n if root is None:\n return\n self.size(root.left, e)\n if root.data > xx:\n xx = root.data\n self.size(root.right, e)\n\ndef kthAncestor(root, nod, Z):\n global xx\n e = []\n self.size(root, e)\n n = xx\n if root is None:\n return -1\n A = []\n C = []\n B = []\n D = []\n A.append(root)\n ancestors = [0] * (n + 1)\n ancestors[root.data] = -1\n while len(A) > 0:\n while len(A) > 0:\n node = A.pop(0)\n B.append(node.data)\n if node.left is not None:\n ancestors[node.left.data] = node.data\n D.append(node.left)\n if node.right is not None:\n ancestors[node.right.data] = node.data\n D.append(node.right)\n A.extend(D)\n D = []\n C.append(B)\n B = []\n g = nod\n while 1:\n x = ancestors[g]\n if x == -1:\n break\n g = x\n Z.append(x)", "def Ancestors(root, target):\n\n def dfs(node, subset):\n if not node:\n return None\n if node.data == target:\n return subset\n return dfs(node.left, subset + [node.data]) or dfs(node.right, subset + [node.data])\n res = dfs(root, [])\n if res:\n return res[::-1]\n return []", "def dfs(n, t, ans):\n if not n:\n return False\n l = dfs(n.left, t, ans)\n r = dfs(n.right, t, ans)\n if l or r:\n ans.append(n.data)\n return True\n if n.data == t:\n return True\n return False\n\ndef Ancestors(root, target):\n ans = []\n dfs(root, target, ans)\n return ans", "def Ancestors(root, target):\n dic = {}\n ans = {root.data: -1}\n q = deque()\n q.append(root)\n l = 1\n while q:\n for i in range(len(q)):\n node = q.popleft()\n if node.left:\n q.append(node.left)\n ans[node.left.data] = node.data\n if node.right:\n q.append(node.right)\n ans[node.right.data] = node.data\n dic[node.data] = l\n l += 1\n res = []\n d = dic[target]\n for i in range(d - 1):\n k = ans[target]\n target = k\n res.append(k)\n return res", "def __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef Ancestors(root, target):\n if root == None:\n return None\n if root.data == target:\n return []\n left = self.Ancestors(root.left, target)\n right = self.Ancestors(root.right, target)\n if left != None and right != None:\n return [*left, root.data, *right]\n elif left != None:\n return [*left, root.data]\n elif right != None:\n return [*right, root.data]\n else:\n return None", "def __init__():\n self.result = []\n\ndef Ancestors(root, target):\n us = {}\n q = []\n if root is None:\n return []\n q.append(root)\n while len(q) > 0:\n t = q.pop(0)\n if t.data == target:\n self.result.append(root.data)\n self.print_path(us, root, t)\n self.result = self.result[::-1]\n self.result.pop(0)\n return self.result\n if t.left is not None and t.left not in us:\n us[t.left] = t\n q.append(t.left)\n if t.right is not None and t.right not in us:\n us[t.right] = t\n q.append(t.right)\n\ndef print_path(f, root, target):\n if target not in f:\n return\n else:\n self.print_path(f, root, f[target])\n self.result.append(target.data)", "def Ancestors(root, target):\n list = []\n node = []\n self.Travel(root, target, list, node)\n return list[::-1]\n\ndef Travel(root, target, list, node):\n if root != None:\n if root.data == target:\n for i in node:\n list.append(i)\n return\n node.append(root.data)\n self.Travel(root.left, target, list, node)\n self.Travel(root.right, target, list, node)\n node.remove(root.data)", "def Ancestors(root, target):\n return self.myFunc(root, [], target, 0)[::-1]\n\ndef myFunc(root, path, key, level):\n if not root:\n return []\n if root.data == key:\n return path.copy()\n level += 1\n path.append(root.data)\n left = self.myFunc(root.left, path, key, level)\n path = path[:level]\n right = self.myFunc(root.right, path, key, level)\n return left + right", "def Ancestors(root, target):\n ans = list()\n\n def ancest(root, target, res):\n if root == None:\n return False\n if root.data == target:\n return True\n if ancest(root.left, target, res) or ancest(root.right, target, res):\n res.append(root.data)\n return True\n return False\n ancest(root, target, ans)\n return ans", "def set_parent(root, parent):\n stack = []\n stack.append(root)\n while stack:\n cur = stack.pop()\n if cur.right:\n parent[cur.right.data] = cur.data\n stack.append(cur.right)\n if cur.left:\n parent[cur.left.data] = cur.data\n stack.append(cur.left)\n\ndef rootToLeaf(parent, target):\n ans = []\n k = target\n while k != 0:\n k = parent[k]\n if k != 0:\n ans.append(k)\n return ans\n\ndef Ancestors(root, target):\n parent = {}\n parent[root.data] = 0\n self.set_parent(root, parent)\n return self.rootToLeaf(parent, target)", "def Ancestors(root, target):\n\n def parent(root):\n if root == None:\n return None\n if root.left:\n dict1[root.left.data] = root.data\n if root.right:\n dict1[root.right.data] = root.data\n if root.left:\n parent(root.left)\n if root.right:\n parent(root.right)\n dict1 = {root.data: -1}\n parent(root)\n node = target\n list1 = []\n while node != -1:\n node = dict1[node]\n if node == -1:\n break\n list1.append(node)\n return list1", "def Ancestors(node, target):\n arr = []\n\n def solve(root, n, arr):\n if root is None:\n return False\n if root.data == n:\n return True\n left = solve(root.left, n, arr)\n right = solve(root.right, n, arr)\n if left or right:\n arr.append(root.data)\n return True\n solve(node, target, arr)\n return arr", "def Ancestors(root, target):\n l = []\n if self.findAncestors(root, target, l):\n return l\n else:\n return l\n\ndef findAncestors(root, target, l):\n if root == None:\n return False\n if root.data == target:\n return True\n if self.findAncestors(root.left, target, l) or self.findAncestors(root.right, target, l):\n l.append(root.data)\n return True", "def Ancestors(root, target):\n res = []\n self.fun(root, res)\n return res[::-1]\n\ndef fun(root, res):\n if root is None:\n return\n if root.data == target:\n return 1\n res.append(root.data)\n a1 = self.fun(root.left, res)\n if a1 == 1:\n return 1\n a2 = self.fun(root.right, res)\n if a2 == 1:\n return 1\n res.pop()", "def Ancestors(root, target):\n\n def ancestors(root, target):\n nonlocal cur, res\n if root is None or len(res) != 0:\n return\n if root.data == target:\n res = cur[:]\n return\n cur.append(root.data)\n ancestors(root.left, target)\n ancestors(root.right, target)\n cur.pop()\n return\n (cur, res) = ([], [])\n ancestors(root, target)\n res.reverse()\n return res", "def Ancestors(root, target):\n if root is None:\n return []\n arr = []\n self.AncestorsUtil(root, target, arr)\n return arr\n\ndef AncestorsUtil(root, target, nodes):\n if root == None:\n return False\n if root.data == target:\n return True\n if self.AncestorsUtil(root.left, target, nodes) or self.AncestorsUtil(root.right, target, nodes):\n nodes.append(root.data)\n return True\n return False", "def Ancestors(root, target):\n d = {}\n l = []\n if not root:\n return\n self.helper(root, d)\n m = d[target]\n while m in d:\n l.append(m)\n m1 = d[m]\n m = m1\n l.append(m)\n return l\n\ndef helper(root, d):\n if not root:\n return\n if root.left:\n d[root.left.data] = root.data\n self.helper(root.left, d)\n if root.right:\n d[root.right.data] = root.data\n self.helper(root.right, d)", "def find_ancestors(root, target, res):\n if root is None:\n return False\n if self.find_ancestors(root.left, target, res) or self.find_ancestors(root.right, target, res):\n res.append(root.data)\n return True\n if root.data == target:\n return True\n return False\n\ndef Ancestors(root, target):\n res = []\n self.find_ancestors(root, target, res)\n return res", "def __init__():\n self.arr = []\n\ndef dfs(root, target):\n if root == None:\n return False\n if root.data == target:\n return True\n if self.dfs(root.left, target) or self.dfs(root.right, target):\n self.arr.append(root.data)\n return True\n return False\n\ndef Ancestors(root, target):\n self.dfs(root, target)\n return self.arr", "def __init__():\n self.ancestors_list = []\n\ndef Ancestors(root, target):\n self.find_ancestors(root, target)\n return self.ancestors_list\n\ndef find_ancestors(node, target):\n if node == None:\n return False\n if node.data == target:\n return True\n r_target = self.find_ancestors(node.right, target)\n l_target = self.find_ancestors(node.left, target)\n if r_target or l_target:\n self.ancestors_list.append(node.data)\n return True", "def Ancestors(root, target):\n ans = []\n\n def recurs(root, target):\n if root.data == target:\n return True\n else:\n p = False\n q = False\n if root.left:\n p = recurs(root.left, target)\n if root.right:\n q = recurs(root.right, target)\n if p or q:\n ans.append(root.data)\n return True\n return False\n recurs(root, target)\n return ans", "def Ancestors(root, target):\n\n def helper(root, res, target):\n if not root:\n return\n if root.data == target:\n return res\n x = helper(root.left, res + [root.data], target)\n if x:\n return x\n y = helper(root.right, res + [root.data], target)\n if y:\n return y\n res = helper(root, [], target)\n return res[::-1]", "def getPath(root, data, result):\n if root:\n result.append(root.data)\n if self.getPath(root.left, data, result):\n return result\n if self.getPath(root.right, data, result):\n return result\n if root.data == data:\n return result\n result.pop()\n\ndef Ancestors(root, target):\n result = []\n self.getPath(root, target, result)\n mainResult = []\n for i in range(len(result) - 2, -1, -1):\n mainResult.append(result[i])\n return mainResult", "def Ancestors(root, target):\n (arr1, arr2) = ([], [])\n flag = [0, 0]\n arr1 = self.first(root, target, arr1, flag)\n arr = arr1[0:len(arr1) - 1]\n return arr[::-1]\n\ndef first(root, n1, arr1, flag):\n if root is None:\n return 0\n if flag[0] == 0:\n if root.data == n1:\n flag[0] = 1\n arr1.append(root.data)\n self.first(root.left, n1, arr1, flag)\n self.first(root.right, n1, arr1, flag)\n if flag[0] == 0:\n arr1.pop()\n return arr1", "def Ancestors(root, target):\n x = []\n\n def helper(root, target):\n if not root:\n return False\n if root.data == target:\n return True\n l = helper(root.left, target)\n r = helper(root.right, target)\n if l == True or r == True:\n x.append(root.data)\n return True\n return False\n helper(root, target)\n return x", "def Ancestors(root, target):\n self.lst = []\n self.f = 0\n\n def dfs(root, target):\n if not root:\n return\n if root.data == target:\n self.f = 1\n return\n if self.f == 0:\n self.lst.append(root.data)\n dfs(root.left, target)\n dfs(root.right, target)\n if self.f != 1:\n self.lst.pop()\n dfs(root, target)\n return self.lst[::-1]", "def Ancestors(root, target):\n\n def bfs(root, d):\n q = [root]\n while q:\n node = q.pop(0)\n if node.left:\n d[node.left.data] = node.data\n q.append(node.left)\n if node.right:\n d[node.right.data] = node.data\n q.append(node.right)\n d = {}\n d[root.data] = -1\n bfs(root, d)\n ans = []\n while target != -1:\n target = d[target]\n ans.append(target)\n return ans[:-1]", "def Ancestors(root, target):\n\n def dfs(root, key, arr):\n if not root:\n return False\n if root.data == key:\n return True\n if dfs(root.left, key, arr) or dfs(root.right, key, arr):\n arr.append(root.data)\n return arr\n return dfs(root, target, [])", "def Ancestors(root, target):\n ancs = []\n\n def rec(root):\n if not root:\n return False\n if root.data == target:\n return True\n if rec(root.left) or rec(root.right):\n ancs.append(root.data)\n return True\n return False\n rec(root)\n return ancs", "def helper_Ancestors(root, target, path):\n if root is None:\n return False\n if root.data == target:\n return True\n lt = self.helper_Ancestors(root.left, target, path)\n rt = self.helper_Ancestors(root.right, target, path)\n if lt or rt:\n path.append(root.data)\n return True\n else:\n return False\n\ndef Ancestors(root, target):\n path = []\n ans = self.helper_Ancestors(root, target, path)\n return path", "def Ancestors(root, target):\n (x, f) = ([], 0)\n\n def ino(r, k):\n nonlocal f\n if not r:\n return\n if r.data == k:\n f = 1\n return\n if f == 0:\n x.append(r.data)\n ino(r.left, k)\n ino(r.right, k)\n if f != 1:\n x.pop()\n ino(root, target)\n return x[::-1]", "def Ancestors(root, target):\n ans = []\n\n def solve(root, target):\n if root is None:\n return None\n if root.data == target:\n return True\n left = solve(root.left, target)\n if left:\n ans.append(root.data)\n return True\n right = solve(root.right, target)\n if right:\n ans.append(root.data)\n return True\n solve(root, target)\n return ans", "def Ancestors(root, target):\n l = []\n path = []\n self.preorder(root, l, path)\n l = l[0]\n l.reverse()\n return l[1:]\n\ndef preorder(root, l, path):\n if root:\n path.append(root.data)\n if root.data == target:\n l.append(path.copy())\n self.preorder(root.left, l, path)\n self.preorder(root.right, l, path)\n path.pop()", "def Ancestors(root, target):\n arr = []\n\n def func(root, tgt):\n if not root:\n return False\n if root.data == tgt:\n return True\n if func(root.left, tgt) or func(root.right, tgt):\n arr.append(root.data)\n return True\n return False\n func(root, target)\n return arr"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["1\r\n / \\\r\n 2 3\r\ntarget = 2", "1\r\n / \\\r\n 2 3\r\n / \\ / \\\r\n 4 5 6 8\r\n /\r\n 7\r\ntarget = 7"], "outputs": ["1", "4 2 1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/ancestors-in-binary-tree/1", "Expected Auxiliary Space": "O(H).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "__init__", "task_id": "TACO_lite/500", "example": [[], []]} +{"requirement": "Given an array of N integers Arr_{1}, Arr_{2}, ….Arr_{N}, count number of subarrays of Arr which are strictly increasing. \nA subarray Arr_{[i, j]} is the array where 1 <= i < j <= N is a sequence of integers of Arr_{i}, Arr_{i+1}, ….Arr_{j}. A subarray Arr_{[i, j]} is strictly increasing if Arr_{i} < Arr_{i+1} < Arr_{i+2} < ……. < Arr_{j}.\nExample 1:\nInput: \nN = 6\nArr[] = {1, 3, 3, 2, 3, 5}\nOutput: 4\nExplanation:\n(1,3), (2, 3), (3, 5) and (2, 3, 5)\nare the only increasing subarrays.\nExample 2:\nInput: \nN = 2\nArr[] = {1 5} \nOutput: 1\nExplanation:(1, 5) is the only increasing\nsubarray.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function countIncreasing() which takes the array of integers arr[] and n as parameters and returns a integer denoting the answer.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 10^{7}\n1 <= Arr_{i} <= 10^{7}", "solutions": ["def countincreasing(arr, n):\n (l, r) = (0, 1)\n count = 0\n while r < len(arr):\n if arr[r] > arr[r - 1]:\n count += r - l\n else:\n l = r\n r += 1\n return count", "def countIncSub(arr, n):\n (fi, li) = (0, 0)\n state = 0\n result = 0\n for i in range(n - 1):\n if arr[i] < arr[i + 1]:\n state = 1\n li += 1\n else:\n if state:\n nTotal = li - fi + 1\n result += nTotal * (nTotal + 1) // 2 - nTotal\n state = 0\n fi = i\n li = i\n nTotal = li - fi + 1\n result += nTotal * (nTotal + 1) // 2 - nTotal\n return result\n\ndef countincreasing(arr, n):\n return countIncSub(arr, n)", "def countincreasing(arr, n):\n left = 0\n ans = 0\n for (idx, n) in enumerate(arr):\n if idx > 0 and n <= arr[idx - 1]:\n left = idx\n ans += idx - left\n return ans", "def countincreasing(arr, n):\n last = arr[0]\n j = 0\n count = 0\n for i in range(1, n):\n if arr[i] > last:\n count += i - j\n else:\n j = i\n last = arr[i]\n return count", "def countincreasing(arr, n):\n c = 1\n ans = 0\n for i in range(n - 1):\n if arr[i + 1] > arr[i]:\n c += 1\n else:\n ans += int((c - 1) * c / 2)\n c = 1\n if c > 1:\n ans += int((c - 1) * c / 2)\n return ans", "def countincreasing(arr, n):\n dp = [0] * len(arr)\n for i in range(1, len(arr)):\n if arr[i] > arr[i - 1]:\n dp[i] = 1 + dp[i - 1]\n return sum(dp)", "import math\n\ndef countincreasing(arr, n):\n q = 0\n p = 1\n for i in range(n - 1):\n if arr[i + 1] > arr[i]:\n p += 1\n elif p > 1:\n q += math.factorial(p) // (2 * math.factorial(p - 2))\n p = 1\n if p > 1:\n q += math.factorial(p) // (2 * math.factorial(p - 2))\n return q", "def countincreasing(arr, n):\n cnt = 1\n out = 0\n for i in range(n - 1):\n if arr[i] < arr[i + 1]:\n cnt += 1\n else:\n out += (cnt - 1) * cnt // 2\n cnt = 1\n if cnt > 1:\n out += (cnt - 1) * cnt // 2\n return out", "def countincreasing(arr, n):\n count = 0\n countz = 0\n for i in range(n - 1):\n if arr[i] < arr[i + 1]:\n count += 1\n elif count > 0:\n countz += count * (count + 1) // 2\n count = 0\n if count > 0:\n countz += count * (count + 1) // 2\n return countz", "def countincreasing(arr, n):\n allCount = 0\n currCount = 0\n for i in range(1, n):\n if arr[i] > arr[i - 1]:\n currCount += 1\n allCount += currCount\n else:\n currCount = 0\n return allCount", "def countincreasing(a, n):\n len = 1\n cnt = 0\n for i in range(n - 1):\n if a[i + 1] > a[i]:\n len += 1\n else:\n cnt += len * (len - 1) // 2\n len = 1\n if len > 1:\n cnt += len * (len - 1) // 2\n return cnt", "def countincreasing(arr, n):\n (p, q) = (0, 0)\n ans = 0\n for i in range(1, n):\n if arr[i] > arr[i - 1]:\n q += 1\n else:\n ans += (q - p + 1) * (q - p) // 2\n (p, q) = (i, i)\n ans += (q - p + 1) * (q - p) // 2\n return ans", "def countincreasing(arr, n):\n p = 0\n c = 0\n for i in range(1, n):\n if arr[i] > arr[i - 1]:\n c += i - p\n else:\n p = i\n return c", "def countincreasing(arr, n):\n ans = 0\n count = 0\n i = 0\n while i < n - 1:\n count = 0\n while i < n - 1 and arr[i] < arr[i + 1]:\n count += 1\n i += 1\n ans += count * (count + 1) // 2\n i += 1\n return ans", "def countincreasing(a, n):\n ans = 0\n l = 1\n for i in range(1, n):\n if a[i - 1] < a[i]:\n l += 1\n else:\n ans += l * (l - 1) // 2\n l = 1\n if l > 1:\n ans += l * (l - 1) // 2\n return ans", "def countincreasing(arr, n):\n count1 = 0\n count2 = 1\n for i in range(n - 1):\n if arr[i] < arr[i + 1]:\n count2 += 1\n else:\n count1 += (count2 - 1) * count2 // 2\n count2 = 1\n count1 += (count2 - 1) * count2 // 2\n return count1", "def countincreasing(arr, n):\n if len(arr) < 2:\n return 0\n cnt = 0\n if arr[1] > arr[0] and len(arr) == 2:\n return 1\n r = 1\n l = 0\n f1 = None\n f2 = None\n for i in range(1, n - 1):\n f1 = arr[i - 1] < arr[i]\n f2 = arr[i] < arr[i + 1]\n if f1 and f2:\n r += 1\n elif not f1 and f2:\n r = i + 1\n l = i\n elif not f1 and (not f2):\n l = i + 1\n r = i + 1\n elif f1 and (not f2):\n cnt += (r - l) * (r - l + 1) // 2\n if f2:\n cnt += (r - l) * (r - l + 1) // 2\n return cnt", "def countincreasing(arr, n):\n count = 0\n i = 0\n j = 0\n while i < n - 1:\n if j == n - 1 or arr[j] >= arr[j + 1]:\n length = j - i + 1\n count += length * (length - 1) / 2\n j = i = j + 1\n else:\n j += 1\n return int(count)", "def countincreasing(arr, n):\n count = 0\n ln = 1\n for i in range(n - 1):\n if arr[i + 1] > arr[i]:\n ln += 1\n else:\n count += (ln - 1) * ln // 2\n ln = 1\n if ln > 1:\n count += ln * (ln - 1) // 2\n return count", "def countincreasing(arr, n):\n rst = 0\n numIncWid = [1] * n\n for i in range(1, n):\n if arr[i] > arr[i - 1]:\n numIncWid[i] = numIncWid[i - 1] + 1\n rst = rst + (numIncWid[i] - 1)\n return rst", "def countincreasing(a, n):\n res = 0\n count = 1\n for i in range(n - 1):\n if a[i] < a[i + 1]:\n count += 1\n elif count > 1:\n res += count * (count - 1) // 2\n count = 1\n if count > 1:\n res += count * (count - 1) // 2\n count = 1\n return res", "def countincreasing(arr, n):\n l = [0]\n for i in range(1, n):\n if arr[i] > arr[i - 1]:\n l.append(l[-1] + 1)\n else:\n l.append(0)\n return sum(l)", "def countincreasing(arr, n):\n k = 0\n temp = 1\n for i in range(0, n - 1):\n if arr[i] < arr[i + 1]:\n temp += 1\n else:\n k += temp * (temp - 1) // 2\n temp = 1\n k += temp * (temp - 1) // 2\n return k", "def countincreasing(arr, n):\n cur_len = 0\n count = 0\n cur_val = -1\n for i in range(n):\n val = arr[i]\n if val > cur_val:\n cur_len += 1\n count += cur_len - 1\n else:\n cur_len = 1\n cur_val = val\n return count", "import math\n\ndef countincreasing(arr, n):\n c = 0\n l = 1\n for i in range(n - 1):\n if arr[i] < arr[i + 1]:\n l += 1\n else:\n c += l * (l - 1) // 2\n l = 1\n if l > 1:\n c += l * (l - 1) // 2\n return c", "def countincreasing(arr, n):\n ans = 0\n small_index = 0\n for index in range(1, n):\n if arr[index] > arr[index - 1]:\n ans += index - small_index\n else:\n small_index = index\n return ans", "def countincreasing(arr, n):\n i = 1\n t = arr[0]\n ans = 0\n while i < n:\n c = 0\n while i < n and arr[i] > arr[i - 1]:\n i += 1\n c += 1\n i += 1\n ans += c * (1 + c) // 2\n return ans", "def countincreasing(arr, n):\n length = 1\n res = 0\n for i in range(0, n - 1):\n if arr[i + 1] > arr[i]:\n length += 1\n else:\n res += (length - 1) * length / 2\n length = 1\n if length > 1:\n res += (length - 1) * length / 2\n return int(res)", "def countincreasing(arr, n):\n subarrays = 0\n m = 1\n for i in range(1, n + 1):\n if i < n and arr[i] > arr[i - 1]:\n m += 1\n else:\n subarrays += m * (m - 1) // 2\n m = 1\n return subarrays"], "starter_code": "def countincreasing(arr, n):\n", "input_output": {"inputs": ["N = 6\nArr[] = {1, 3, 3, 2, 3, 5}", "N = 2\nArr[] = {1 5}"], "outputs": ["4", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-increasing-subarrays5301/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "countincreasing", "task_id": "TACO_lite/524", "example": [[[6, [1, 3, 3, 2, 3, 5]], [2, [1, 5]]], ["4", "1"]]} +{"requirement": "Given an array Arr[], write a program that segregates even and odd numbers. The program should put all even numbers first in sorted order, and then odd numbers in sorted order.\nNote :- You don't have to return the array, you just have to modify it in-place.\nExample 1:\nInput: \nN = 7\nArr[] = {12, 34, 45, 9, 8, 90, 3}\nOutput: 8 12 34 90 3 9 45\nExplanation: Even numbers are 12, 34,\n8 and 90. Rest are odd numbers. After\nsorting even numbers 8 12 34 90 and \nafter sorting odd numbers 3 9 45. Then\nconcat both.\nExample 2:\nInput: \nN = 5\nArr[] = {0, 1, 2, 3, 4}\nOutput: 0 2 4 1 3\nExplanation: 0 2 4 are even and 1 3\nare odd numbers.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function segregateEvenOdd() which takes the array of integers arr[] and n as parameters and returns void. You need to modify the array itself.\nExpected Time Complexity: O(N log(N))\nExpected Auxiliary Space: O(N)\nConstraints:\n1 ≤ N ≤ 10^{5}\n0 ≤ Arr[i] <=10^{5}", "solutions": ["def segregateevenodd(arr, n):\n e = []\n odd = []\n for i in range(n):\n if arr[i] % 2 == 0:\n e.append(arr[i])\n else:\n odd.append(arr[i])\n e.sort()\n odd.sort()\n l3 = []\n l3 = e + odd\n for i in range(n):\n arr[i] = l3[i]", "def segregateevenodd(arr, n):\n left = 0\n right = n - 1\n while left < right:\n while arr[left] % 2 == 0 and left < right:\n left += 1\n while arr[right] % 2 == 1 and left < right:\n right -= 1\n if left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1\n even = [num for num in arr if num % 2 == 0]\n odd = [num for num in arr if num % 2 == 1]\n even.sort()\n odd.sort()\n arr[:] = even + odd", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n even.sort()\n odd.sort()\n even.extend(odd)\n arr[:] = even\n return arr", "def segregateevenodd(arr, n):\n (l1, l2) = ([], [])\n for i in arr:\n if i % 2 == 0:\n l1.append(i)\n else:\n l2.append(i)\n l1.sort()\n l2.sort()\n l1.extend(l2)\n arr[:] = l1\n return arr", "def segregateevenodd(arr, n):\n (m1, m2) = ([], [])\n for i in arr:\n if i % 2 == 0:\n m1.append(i)\n else:\n m2.append(i)\n m1.sort()\n m2.sort()\n m1.extend(m2)\n arr[:] = m1\n return arr", "def segregateevenodd(arr, n):\n arr.sort()\n b = []\n c = []\n for i in range(0, len(arr)):\n if arr[i] % 2 == 0:\n b.append(arr[i])\n else:\n c.append(arr[i])\n arr[:] = b + c\n return arr", "def segregateevenodd(arr, n):\n even_arr = []\n odd_arr = []\n for i in arr:\n if i % 2 == 0:\n even_arr.append(i)\n even_arr.sort()\n for i in arr:\n if i % 2 != 0:\n odd_arr.append(i)\n odd_arr.sort()\n arr.clear()\n arr.extend(even_arr)\n arr.extend(odd_arr)", "def segregateevenodd(arr, n):\n arr.sort()\n even = []\n odd = []\n for i in range(n):\n if arr[i] % 2 == 0:\n even.append(arr[i])\n if arr[i] % 2 == 1:\n odd.append(arr[i])\n a = even + odd\n for i in range(n):\n arr[i] = a[i]\n return arr", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n odd.sort()\n even.sort()\n even = even + odd\n for i in range(len(arr)):\n arr[i] = even[i]", "def segregateevenodd(a, n):\n even = []\n odd = []\n for i in a:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n a.clear()\n even.sort()\n odd.sort()\n a.extend(even + odd)", "def segregateevenodd(arr, n):\n li1 = []\n li2 = []\n for i in range(n):\n if arr[i] % 2 == 0:\n li1.append(arr[i])\n else:\n li2.append(arr[i])\n li1.sort()\n li2.sort()\n li1.extend(li2)\n arr[:] = li1\n return arr", "def segregateevenodd(arr, n):\n i = []\n j = []\n for num in arr:\n if num % 2 == 0:\n i.append(num)\n else:\n j.append(num)\n i.sort()\n j.sort()\n arr.clear()\n arr.extend(i)\n arr.extend(j)", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for I in arr:\n if I % 2 == 0 or I == 0:\n even.append(I)\n else:\n odd.append(I)\n a = sorted(even)\n b = sorted(odd)\n c = a + b\n arr[:] = c\n return arr", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for num in arr:\n if num % 2 == 0:\n even.append(num)\n else:\n odd.append(num)\n even.sort()\n odd.sort()\n arr.clear()\n arr.extend(even)\n arr.extend(odd)", "def segregateevenodd(arr, n):\n a = []\n b = []\n arr.sort()\n for i in arr:\n if i % 2 == 0:\n a.append(i)\n else:\n b.append(i)\n a.sort()\n b.sort()\n a.extend(b)\n arr[:] = a\n return arr", "def segregateevenodd(arr, n):\n res1 = []\n res2 = []\n res = []\n for i in arr:\n if i % 2 == 0:\n res1.append(i)\n else:\n res2.append(i)\n res1.sort()\n res2.sort()\n res1.extend(res2)\n arr[:] = res1\n return arr", "def segregateevenodd(arr, n):\n arr.sort()\n ans = [None] * n\n cnt = 0\n for i in range(n):\n if arr[i] % 2 == 0:\n ans[cnt] = arr[i]\n cnt += 1\n for i in range(n):\n if arr[i] % 2 != 0:\n ans[cnt] = arr[i]\n cnt += 1\n for i in range(n):\n arr[i] = ans[i]", "def segregateevenodd(arr, n):\n (L1, L2) = ([], [])\n for i in arr:\n if i % 2 == 0:\n L1.append(i)\n else:\n L2.append(i)\n L1.sort()\n L2.sort()\n L1.extend(L2)\n arr[:] = L1\n return arr", "def segregateevenodd(arr, n):\n l1 = sorted([i for i in arr if i % 2 == 0])\n l2 = sorted([i for i in arr if i % 2 != 0])\n arr[:] = l1 + l2\n return arr", "def segregateevenodd(arr, n):\n odd_list = []\n even_list = []\n for i in arr:\n if i % 2 == 0:\n even_list.append(i)\n else:\n odd_list.append(i)\n even_list.sort()\n odd_list.sort()\n even_list.extend(odd_list)\n arr[:] = even_list", "def segregateevenodd(arr, n):\n li1 = []\n li2 = []\n for i in arr:\n if i % 2 == 0:\n li1.append(i)\n elif i % 2 != 0:\n li2.append(i)\n li1.sort()\n li2.sort()\n s = li1 + li2\n for i in range(n):\n arr[i] = s[i]\n return arr[i]", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for i in range(n):\n if arr[i] % 2 == 0:\n even.append(arr[i])\n continue\n else:\n odd.append(arr[i])\n continue\n even.sort()\n odd.sort()\n arr.clear()\n for j in range(len(even)):\n arr.append(even[j])\n for k in range(len(odd)):\n arr.append(odd[k])", "def segregateevenodd(arr, n):\n (l, r) = (0, n - 1)\n while l <= r:\n while l < n and arr[l] % 2 == 0:\n l += 1\n while r >= 0 and arr[r] % 2 != 0:\n r -= 1\n if l < r:\n (arr[l], arr[r]) = (arr[r], arr[l])\n i = 0\n for x in sorted(arr[:r + 1]):\n arr[i] = x\n i += 1\n for x in sorted(arr[l:]):\n arr[i] = x\n i += 1", "def segregateevenodd(arr, n):\n o = []\n e = []\n for i in range(n):\n if arr[i] % 2 == 0:\n e.append(arr[i])\n else:\n o.append(arr[i])\n o.sort()\n e.sort()\n e.extend(o)\n arr[:] = e[:]", "def segregateevenodd(arr, n):\n arr.sort()\n liOdd = []\n liEven = []\n for i in range(n):\n if arr[i] % 2 == 0:\n liEven.append(arr[i])\n else:\n liOdd.append(arr[i])\n arr[:] = liEven + liOdd\n return arr", "def segregateevenodd(arr, n):\n j = 0\n for i in range(n):\n if arr[i] % 2 == 0:\n (arr[i], arr[j]) = (arr[j], arr[i])\n j += 1\n arr[:j] = sorted(arr[:j])\n arr[j:] = sorted(arr[j:])", "def segregateevenodd(arr, n):\n list1 = [i for i in arr if i % 2 == 0]\n list2 = [i for i in arr if i % 2 != 0]\n list3 = sorted(list1) + sorted(list2)\n for i in range(len(arr)):\n arr[i] = list3[i]", "def segregateevenodd(arr, n):\n arr.sort()\n ev = []\n od = []\n for i in range(n):\n if arr[i] % 2 == 0:\n ev.append(arr[i])\n else:\n od.append(arr[i])\n a = ev + od\n for i in range(n):\n arr[i] = a[i]", "def segregateevenodd(arr, n):\n even = []\n odd = []\n (p, q) = (0, 0)\n for n in arr:\n if n % 2 == 0:\n even.append(n)\n p += 1\n else:\n odd.append(n)\n q += 1\n even.sort()\n odd.sort()\n (i, j) = (0, 0)\n r = 0\n while i < p:\n arr[r] = even[i]\n r += 1\n i += 1\n while j < q:\n arr[r] = odd[j]\n j += 1\n r += 1", "def segregateevenodd(arr, n):\n li1 = []\n li2 = []\n for i in range(n):\n if arr[i] % 2 == 0:\n li1.append(arr[i])\n li1.sort()\n for i in range(n):\n if arr[i] % 2 != 0:\n li2.append(arr[i])\n li2.sort()\n for i in range(len(li1)):\n arr[i] = li1[i]\n for i in range(len(li2)):\n arr[i + len(li1)] = li2[i]", "def segregateevenodd(arr, n):\n a = sorted((i for i in arr if i % 2 == 0))\n b = sorted((i for i in arr if i % 2 != 0))\n arr[:] = a + b\n return arr", "def segregateevenodd(arr, n):\n even = 0\n odd = n - 1\n while even < odd:\n if arr[even] % 2 == 0:\n even += 1\n else:\n (arr[even], arr[odd]) = (arr[odd], arr[even])\n odd -= 1\n arr.sort(key=lambda x: [x % 2, x])\n return arr", "def segregateevenodd(arr, n):\n a = [x for x in arr if x % 2 == 0]\n a.sort()\n b = [x for x in arr if x % 2 != 0]\n b.sort()\n arr[:] = a[:] + b[:]\n return arr", "def segregateevenodd(arr, n):\n x = []\n j = 0\n y = []\n for i in range(n):\n if arr[i] % 2 == 0:\n x.append(arr[i])\n j += 1\n if arr[i] % 2 == 1:\n y.append(arr[i])\n even = sorted(x)\n odd = sorted(y)\n arr[j:] = odd\n arr[:j] = even", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n arr1 = sorted(even) + sorted(odd)\n for i in range(n):\n arr[i] = arr1[i]\n return arr", "def segregateevenodd(arr, n):\n l = []\n ll = []\n for i in arr:\n if i % 2 == 0:\n l.append(i)\n else:\n ll.append(i)\n l.sort()\n ll.sort()\n arr[:] = (l + ll)[:]", "def segregateevenodd(arr, n):\n odd_arr = []\n even_arr = []\n for i in range(n):\n if arr[i] % 2:\n odd_arr.append(arr[i])\n else:\n even_arr.append(arr[i])\n odd_arr.sort()\n even_arr.sort()\n arr[:] = even_arr + odd_arr", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n even = sorted(even)\n odd = sorted(odd)\n arr.clear()\n arr.extend(even)\n arr.extend(odd)", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for (i, each) in enumerate(arr):\n if each % 2 == 0:\n even.append(each)\n else:\n odd.append(each)\n even = sorted(even)\n odd = sorted(odd)\n for (i, each) in enumerate(even):\n arr[i] = even[i]\n idx = len(even)\n for (i, each) in enumerate(odd):\n arr[idx] = odd[i]\n idx += 1\n return arr", "def segregateevenodd(arr, n):\n l = []\n t = []\n arr.sort()\n for i in range(n):\n if arr[i] % 2 == 0:\n l.append(arr[i])\n else:\n t.append(arr[i])\n w = l + t\n arr[:] = w[:]\n return arr", "def segregateevenodd(arr, n):\n l = []\n arr.sort()\n for i in arr:\n if i % 2 == 0:\n l.append(i)\n for i in arr:\n if i % 2 != 0:\n l.append(i)\n for i in range(len(l)):\n arr[i] = l[i]\n return arr", "def segregateevenodd(arr, n):\n arr.sort()\n i = 0\n for j in arr:\n if arr[i] % 2 == 1:\n arr.append(arr.pop(i))\n else:\n i += 1\n return arr", "def segregateevenodd(arr, n):\n (o, e) = ([], [])\n for elem in arr:\n e.append(elem) if elem % 2 == 0 else o.append(elem)\n e.sort()\n o.sort()\n arr[:] = e + o", "def segregateevenodd(arr, n):\n e = []\n o = []\n for i in arr:\n if i % 2 == 0:\n e.append(i)\n elif i % 2 != 0:\n o.append(i)\n x = sorted(e)\n y = sorted(o)\n z = x + y\n for i in range(n):\n arr[i] = z[i]\n return z[i]", "def segregateevenodd(arr, n):\n x = []\n y = []\n for i in arr:\n if i % 2 == 0:\n x.append(i)\n else:\n y.append(i)\n x.sort()\n y.sort()\n arr.clear()\n arr[:] = list(x) + list(y)", "def segregateevenodd(arr, n):\n e = [i for i in arr if i % 2 == 0]\n o = [i for i in arr if i % 2 != 0]\n s = sorted(e) + sorted(o)\n arr[:] = s[:]\n return arr"], "starter_code": "def segregateevenodd(arr, n):\n", "input_output": {"inputs": ["N = 7\r\nArr[] = {12, 34, 45, 9, 8, 90, 3}", "N = 5\r\nArr[] = {0, 1, 2, 3, 4}"], "outputs": ["8 12 34 90 3 9 45", "0 2 4 1 3"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/segregate-even-and-odd-numbers4629/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N log(N))", "entry_point": "segregateevenodd", "task_id": "TACO_lite/525", "example": [[], []]} +{"requirement": "Given string str of length N. The task is to find the minimum characters to be added at the front to make string palindrome.\nNote: A palindrome is a word which reads the same backward as forward. Example: \"madam\".\nExample 1:\nInput:\nS = \"abc\"\nOutput: 2\nExplanation: \nAdd 'b' and 'c' at front of above string to make it\npalindrome : \"cbabc\"\nExample 2:\nInput:\nS = \"aacecaaa\"\nOutput: 1\nExplanation: Add 'a' at front of above string\nto make it palindrome : \"aaacecaaa\"\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function minChar() which takes a string S and returns an integer as output.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 <= S.length <= 10^{6}", "solutions": ["def minchar(str):\n ha = [0] * len(s)\n (i, j) = (0, len(s) - 1)\n ans = 0\n while i < j:\n if s[i] == s[j]:\n if i == 0:\n ha[i] = 1\n else:\n ha[i] = 1 + ha[i - 1]\n i += 1\n j -= 1\n elif i == 0:\n ans = len(s) - j\n j -= 1\n else:\n i = ha[i - 1] // 2\n ans = len(s) - (j + 1) - i\n return ans", "def minchar(string):\n my_str = string + '@' + string[::-1]\n first = 0\n second = 2\n my_str = ' ' + my_str\n lps_arr = [0] * len(my_str)\n while second < len(my_str):\n if my_str[first + 1] == my_str[second]:\n lps_arr[second] = first + 1\n first += 1\n second += 1\n elif first != 0:\n first = lps_arr[first]\n else:\n second += 1\n return len(string) - lps_arr[-1]", "def minchar(s):\n\n def lps(text):\n lps = [0] * len(text)\n j = 0\n for i in range(1, len(text)):\n while j > 0 and text[i] != text[j]:\n j = lps[j - 1]\n if text[i] == text[j]:\n j += 1\n lps[i] = j\n return lps\n s = s + '#' + s[::-1]\n lps = lps(s)\n return (len(s) - 1) // 2 - lps[-1]", "def minchar(str1):\n\n def compute_lps_array(string, size):\n length = 0\n lps = [0] * size\n i = 1\n while i < size:\n if string[i] == string[length]:\n length += 1\n lps[i] = length\n i += 1\n elif length != 0:\n length = lps[length - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n reverse_s = s[::-1]\n concat = s + '$' + reverse_s\n lps = compute_lps_array(concat, len(concat))\n return len(s) - lps[-1]", "def minchar(str):\n n = len(s)\n r = s[::-1]\n lps = [0] * (n + 1)\n (i, length) = (0, 0)\n while i < n:\n if r[i] == s[length]:\n length += 1\n lps[i + 1] = length\n i += 1\n elif length == 0:\n lps[i + 1] = 0\n i += 1\n else:\n length = lps[length - 1]\n return n - lps[-1]", "def minchar(string):\n\n def computeLPSArray(string):\n M = len(string)\n lps = [None] * M\n length = 0\n lps[0] = 0\n i = 1\n while i < M:\n if string[i] == string[length]:\n length += 1\n lps[i] = length\n i += 1\n elif length != 0:\n length = lps[length - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n revStr = string[::-1]\n concat = string + '$' + revStr\n lps = computeLPSArray(concat)\n return len(string) - lps[-1]", "def computeLPS(needle):\n if needle == '':\n return 0\n lps = [0] * len(needle)\n (prevLPS, i) = (0, 1)\n while i < len(needle):\n if needle[i] == needle[prevLPS]:\n lps[i] = prevLPS + 1\n prevLPS += 1\n i += 1\n elif prevLPS == 0:\n lps[i] = 0\n i += 1\n else:\n prevLPS = lps[prevLPS - 1]\n return lps\n\ndef minchar(str):\n revStr = str[::-1]\n concat = str + '$' + revStr\n lps = self.computeLPS(concat)\n return len(str) - lps[-1]", "def is_palin(s):\n start = 0\n end = len(s) - 1\n while start < end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n\ndef minchar(str):\n n = len(str)\n temp = str + '$' + str[::-1]\n l = n + n + 1\n lps = [0] * l\n i = 1\n j = 0\n while i < l:\n if temp[i] == temp[j]:\n lps[i] = j + 1\n i += 1\n j += 1\n elif j == 0:\n i += 1\n else:\n j = lps[j - 1]\n ans = n - lps[l - 1]\n return ans", "def computeLPSArray(pat, n, lps):\n len = 0\n lps[0]\n i = 1\n while i < n:\n if pat[i] == pat[len]:\n len += 1\n lps[i] = len\n i += 1\n elif len != 0:\n len = lps[len - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\ndef minchar(str):\n s = str\n revStr = s[::-1]\n concat = s + '$' + revStr\n n = len(concat)\n lps = [0] * n\n lps = computeLPSArray(concat, n, lps)\n return len(s) - lps[-1]", "def compute_lps_array(s: str):\n n = len(s)\n lps = [0] * n\n (i, l) = (1, 0)\n lps[0] = 0\n while i < n:\n if s[i] == s[l]:\n l += 1\n lps[i] = l\n i += 1\n elif l != 0:\n l = lps[l - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\ndef minchar(str):\n str_concat = str + '$' + str[::-1]\n lps = self.compute_lps_array(str_concat)\n return len(str) - lps[len(str_concat) - 1]", "def conlsparr(str):\n M = len(str)\n lsp = [None] * M\n length = 0\n lsp[0] = 0\n i = 1\n while i < M:\n if str[i] == str[length]:\n length += 1\n lsp[i] = length\n i += 1\n elif length != 0:\n length = lsp[length - 1]\n else:\n lsp[i] = 0\n i += 1\n return lsp\n\ndef minchar(str):\n revstr = str[::-1]\n concat = str + '$' + revstr\n lsp1 = self.conlsparr(concat)\n return len(str) - lsp1[-1]", "def minchar(s):\n res = []\n li = list(s)\n li.append('$')\n li.extend(list(s[::-1]))\n lps = [0] * len(li)\n i = 1\n prev = 0\n while i < len(li):\n if li[i] == li[prev]:\n prev = prev + 1\n lps[i] = prev\n i = i + 1\n elif prev == 0:\n lps[i] = 0\n i = i + 1\n else:\n prev = lps[prev - 1]\n return len(s) - lps[-1]", "def genLPS(str):\n n = len(str)\n lps = [0] * n\n j = 1\n length = 0\n while j < n:\n if str[j] == str[length]:\n length += 1\n lps[j] = length\n j += 1\n elif length != 0:\n length = lps[length - 1]\n else:\n lps[j] = 0\n j += 1\n return lps[-1]\n\ndef minchar(str):\n n = len(str)\n str = str + '%' + str[::-1]\n return n - self.genLPS(str)", "def getlps(s):\n n = len(s)\n lps = [0] * n\n i = 1\n l = 0\n while i < n:\n if s[i] == s[l]:\n l += 1\n lps[i] = l\n i += 1\n else:\n if l == 0:\n lps[i] = 0\n i += 1\n l = lps[l - 1]\n return lps\n\ndef minchar(str):\n str2 = str[::-1]\n n = len(str)\n S = str + '$' + str2\n c = self.getlps(S)\n return n - c[-1]", "def minchar(s):\n newstr = s + '$' + s[::-1]\n lps = [0] * len(newstr)\n (prevlps, i) = (0, 1)\n while i < len(newstr):\n if newstr[prevlps] == newstr[i]:\n prevlps += 1\n lps[i] = prevlps\n i += 1\n elif prevlps == 0:\n lps[i] = 0\n i += 1\n else:\n prevlps = lps[prevlps - 1]\n return len(s) - lps[-1]", "def minchar(str):\n newStr = str + '$' + str[::-1]\n lps = [0] * len(newStr)\n self.findlps(lps, newStr)\n return len(str) - lps[-1]\n\ndef findlps(lps, a):\n i = 0\n j = 1\n while i <= j and j < len(a):\n if a[i] == a[j]:\n i += 1\n lps[j] = i\n j += 1\n elif i != 0:\n i = lps[i - 1]\n else:\n j += 1", "def minchar(str1):\n rev = str1[::-1]\n concat = str1 + '$' + rev\n lps = self.addMinChar(concat)\n return len(str1) - lps[-1]\n\ndef addMinChar(str1):\n m = len(str1)\n lps = [None] * m\n length = 0\n lps[0] = 0\n i = 1\n while i < m:\n if str1[i] == str1[length]:\n length += 1\n lps[i] = length\n i += 1\n elif length != 0:\n length = lps[length - 1]\n else:\n lps[i] = 0\n i += 1\n return lps", "def minchar(str):\n x = list(str)\n x.append('$')\n x.extend(list(str[::-1]))\n lps = [0] * len(x)\n i = 1\n prev = 0\n while i < len(x):\n if x[prev] == x[i]:\n prev = prev + 1\n lps[i] = prev\n i = i + 1\n elif prev == 0:\n lps[i] = 0\n i = i + 1\n else:\n prev = lps[prev - 1]\n return len(str) - lps[-1]\n return 0", "def computeLPSArray(s):\n lps = [None] * len(s)\n lps[0] = 0\n length = 0\n i = 1\n M = len(s)\n while i < M:\n if s[i] == s[length]:\n length += 1\n lps[i] = length\n i += 1\n elif length != 0:\n length = lps[length - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\ndef minchar(str):\n s = str + '$' + str[::-1]\n lps = self.computeLPSArray(s)\n return len(str) - lps[-1]", "def minchar(str):\n n = len(str)\n req = 0\n (l, r) = (0, n - 1)\n if str[l] == str[r]:\n while l < r and str[r] == str[n - 1]:\n if str[l] == str[r]:\n l += 1\n else:\n req += 1\n r -= 1\n while l < r:\n if str[l] == str[r]:\n l += 1\n else:\n req = n - r\n l = 0\n r -= 1\n return req", "def minchar(str):\n z = 0\n i = 1\n lps = [0]\n v = str[::-1]\n str = str + '$' + v\n while i < len(str):\n if str[i] == str[z]:\n z = z + 1\n lps.append(z)\n i = i + 1\n elif z != 0:\n z = lps[z - 1]\n else:\n lps.append(0)\n i = i + 1\n return len(v) - lps[-1]", "def minchar(str):\n l = 0\n r = len(str) - 1\n res = 0\n while l < r:\n if str[l] == str[r]:\n l += 1\n r -= 1\n else:\n res += 1\n if l != 0:\n l -= 1\n r += 1\n r -= 1\n return res", "def minchar(s):\n ans = 0\n i = 0\n j = len(s) - 1\n while i < j:\n if s[i] == s[j]:\n i += 1\n else:\n ans += 1\n if i != 0:\n j += 1\n i -= 1\n j -= 1\n return ans", "def minchar(str):\n\n def lps(s):\n i = 1\n l = 0\n lps = [0] * len(s)\n while i < len(s):\n if s[i] == s[l]:\n l = l + 1\n lps[i] = l\n i = i + 1\n elif l != 0:\n l = lps[l - 1]\n else:\n lps[i] = 0\n i = i + 1\n return lps\n length = len(str)\n str_a = str + '#' + str[::-1]\n a = lps(str_a)\n return length - a[-1]", "def minchar(s):\n r = s[::-1]\n lps = [0] * (len(s) + 1)\n (i, j) = (0, 0)\n while i < len(s):\n if r[i] == s[j]:\n j += 1\n lps[i + 1] = j\n i += 1\n elif j == 0:\n lps[i + 1] = 0\n i += 1\n else:\n j = lps[j - 1]\n return len(s) - lps[-1]", "def minchar(str):\n B = str + '$' + str[::-1]\n LPS = [0] * len(B)\n (prevLPS, i) = (0, 1)\n while i < len(B):\n if B[i] == B[prevLPS]:\n LPS[i] = prevLPS + 1\n i += 1\n prevLPS += 1\n elif prevLPS == 0:\n LPS[i] = prevLPS\n i += 1\n else:\n prevLPS = LPS[prevLPS - 1]\n return len(str) - LPS[-1]", "def minchar(str):\n new_string = str + '#' + str[::-1]\n pattern = self.get_pattern(new_string)\n return len(str) - pattern[-1] - 1\n\ndef get_pattern(substring):\n pattern = [-1] * len(substring)\n j = 0\n i = 1\n while i < len(substring):\n if substring[i] == substring[j]:\n pattern[i] = j\n i += 1\n j += 1\n elif j > 0:\n j = pattern[j - 1] + 1\n else:\n i += 1\n return pattern", "def lps(str1):\n i = 1\n j = 0\n pi = [0 for i in range(len(str1))]\n while i < len(str1):\n if str1[i] == str1[j]:\n pi[i] = j + 1\n i += 1\n j += 1\n elif j == 0:\n i += 1\n else:\n j = pi[j - 1]\n return pi[-1]\n\ndef minchar(str):\n revS = str[::-1]\n str1 = str + '$' + revS\n ans = self.lps(str1)\n return len(str) - ans", "def minchar(s):\n concat = s + s[::-1]\n res = self.lps(concat)\n return len(s) - res[-1]\n\ndef lps(a):\n i = 1\n j = 0\n lps = []\n lps.append(0)\n while i < len(a):\n if a[i] == a[j]:\n lps.append(j + 1)\n i += 1\n j += 1\n elif j == 0:\n lps.append(0)\n i += 1\n else:\n j = lps[j - 1]\n return lps", "def lps(s):\n n = len(s)\n lps = [0] * n\n lenn = 0\n i = 1\n while i < n:\n if s[lenn] == s[i]:\n lenn += 1\n lps[i] = lenn\n i += 1\n elif lenn != 0:\n lenn = lps[lenn - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\ndef minchar(s):\n n = len(s)\n if n == 1:\n return 0\n revS = s[::-1]\n concat = s + '$' + revS\n ls = Solution.lps(concat)\n return len(s) - ls[-1]", "def minchar(s):\n on = len(s)\n s = s + '$' + s[::-1]\n n = len(s)\n lps = [0] * n\n\n def preProcess():\n j = 0\n i = 1\n while i < n:\n if s[i] == s[j]:\n lps[i] = j + 1\n i += 1\n j += 1\n elif j > 0:\n j = lps[j - 1]\n else:\n i += 1\n preProcess()\n return on - lps[-1]", "def LPSSTRING(String):\n i = 1\n M = len(String)\n lps = [None] * M\n lps[0] = 0\n length = 0\n while i < M:\n if String[i] == String[length]:\n length += 1\n lps[i] = length\n i += 1\n elif length != 0:\n length = lps[length - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\ndef minchar(str):\n String = str + '$' + str[::-1]\n LPS = self.LPSSTRING(String)\n return len(str) - LPS[-1]", "def Concat(string):\n M = len(string)\n i = 1\n length = 0\n lps = [None] * M\n lps[0] = 0\n while i < M:\n if string[i] == string[length]:\n length += 1\n lps[i] = length\n i += 1\n elif length != 0:\n length = lps[length - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\ndef minchar(str):\n string = str + '$' + str[::-1]\n lps = self.Concat(string)\n return len(str) - lps[-1]", "def create_lps(A):\n M = len(A)\n lps = [None] * M\n l = 0\n lps[0] = l\n i = 1\n while i < M:\n if A[i] == A[l]:\n l += 1\n lps[i] = l\n i += 1\n elif l != 0:\n l = lps[l - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\ndef minchar(A):\n lps = self.create_lps(A + '$' + A[::-1])\n return len(A) - lps[-1]", "def lps(s):\n n = len(s)\n LPS = [0] * n\n i = 1\n j = 0\n while i < n:\n if s[i] == s[j]:\n j += 1\n LPS[i] = j\n i += 1\n elif j != 0:\n j = LPS[j - 1]\n else:\n LPS[i] = 0\n i += 1\n return LPS\n\ndef minchar(s):\n a = s + '$' + s[::-1]\n LPS = lps(a)\n ans = len(s) - LPS[-1]\n return ans", "def minchar(str):\n rev = str[::-1]\n new = str + rev\n n = len(str)\n lps = [0] * len(new)\n i = 1\n h = 0\n while i < 2 * n:\n if new[i] == new[h]:\n lps[i] += 1\n i += 1\n h += 1\n elif h > 0:\n h = lps[h - 1]\n elif h == 0:\n lps[i] = 0\n i += 1\n if h > n:\n h = math.floor(h) / 2\n ans = n - h\n return ans"], "starter_code": "def minchar(str):\n", "input_output": {"inputs": ["S = \"abc\"", "S = \"aacecaaa\""], "outputs": ["2", "1"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/minimum-characters-to-be-added-at-front-to-make-string-palindrome/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "minchar", "task_id": "TACO_lite/434", "example": [[["abc"], ["aacecaaa"]], ["2", "1"]]} +{"requirement": "You need to create a function that will validate if given parameters are valid geographical coordinates.\n\nValid coordinates look like the following: __\"23.32353342, -32.543534534\"__.\nThe return value should be either __true__ or __false__.\n\nLatitude (which is first float) can be between 0 and 90, positive or negative.\nLongitude (which is second float) can be between 0 and 180, positive or negative.\n\nCoordinates can only contain digits, or one of the following symbols (including space after comma) __ -, . __\n\nThere should be no space between the minus \"-\" sign and the digit after it.\n\nHere are some valid coordinates:\n\n* -23, 25\n* 24.53525235, 23.45235\n* 04, -23.234235\n* 43.91343345, 143\n* 4, -3\n\nAnd some invalid ones:\n\n* 23.234, - 23.4234\n* 2342.43536, 34.324236\n* N23.43345, E32.6457\n* 99.234, 12.324\n* 6.325624, 43.34345.345\n* 0, 1,2\n* 0.342q0832, 1.2324", "solutions": ["def is_valid_coordinates(coordinates):\n try:\n (lat, lng) = [abs(float(c)) for c in coordinates.split(',') if 'e' not in c]\n except ValueError:\n return False\n return lat <= 90 and lng <= 180", "import re\n\ndef is_valid_coordinates(coordinates):\n return bool(re.match('-?(\\\\d|[1-8]\\\\d|90)\\\\.?\\\\d*, -?(\\\\d|[1-9]\\\\d|1[0-7]\\\\d|180)\\\\.?\\\\d*$', coordinates))", "def is_valid_coordinates(s):\n try:\n (a, b) = s.split(',')\n if 'e' in a or 'e' in b:\n raise Exception\n (a, b) = (float(a), float(b))\n return abs(a) <= 90 and abs(b) <= 180\n except:\n return False", "import re\nCOORD_RE = re.compile('(-?[\\\\d]+\\\\.?[\\\\d]*), ?(-?[\\\\d]+\\\\.?[\\\\d]*)$')\n\ndef is_valid_coordinates(coordinates):\n match = COORD_RE.match(coordinates)\n if not match:\n return False\n (x, y) = (match.group(1), match.group(2))\n (x, y) = (float(x), float(y))\n if not 0 <= abs(x) <= 90:\n return False\n if not 0 <= abs(y) <= 180:\n return False\n return True", "def is_valid_coordinates(coordinates):\n coords = coordinates.split(',')\n if len(coords) != 2 or 'e' in coordinates:\n return False\n for (i, coord) in enumerate(coords):\n try:\n coord = float(coord)\n if i == 0 and abs(coord) > 90 or (i == 1 and abs(coord) > 180):\n return False\n except:\n return False\n return True", "def is_valid_coordinates(coordinates):\n x = coordinates.split(', ')\n try:\n if len(x) == 2 and 90 >= float(x[0]) >= -90 and (180 >= float(x[1]) >= -180) and (not any((c.isalpha() for c in x[0]))) and (not any((c.isalpha() for c in x[1]))):\n return True\n except:\n return False\n return False", "def is_valid_coordinates(c):\n try:\n return all((-r <= float(s) <= r and 'e' not in s for (s, r) in zip(c.split(','), [90, 180, -1])))\n except ValueError:\n return False", "def is_valid_coordinates(coordinates):\n valid_chars = set('0123456789-.')\n try:\n (latitude, longitude) = (abs(float(a)) for a in coordinates.split(', ') if valid_chars.issuperset(a))\n except ValueError:\n return False\n return latitude <= 90 and longitude <= 180"], "starter_code": "def is_valid_coordinates(coordinates):\n", "input_output": {"fn_name": "is_valid_coordinates", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5269452810342858ec000951", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_valid_coordinates", "task_id": "TACO_lite/408", "example": [[], []]} +{"requirement": "# Personalized greeting\n\nCreate a function that gives a personalized greeting. This function takes two parameters: `name` and `owner`.\n\nUse conditionals to return the proper message:\n\ncase | return\n--- | ---\nname equals owner | 'Hello boss'\notherwise | 'Hello guest'", "solutions": ["def greet(name, owner):\n return 'Hello boss' if name == owner else 'Hello guest'", "def greet(name, owner):\n return 'Hello ' + ['guest', 'boss'][name == owner]", "greet = lambda n, o: 'Hello ' + 'gbuoessst'[n == o::2]", "greet = lambda n, o: 'Hello {}'.format(['guest', 'boss'][n == o])", "def greet(a, b):\n return 'Hello boss' if a == b else 'Hello guest'", "def greet(name: str, owner: str) -> str:\n return f\"Hello {('boss' if name == owner else 'guest')}\"", "def greet(*s):\n return f\"Hello {['boss', 'guest'][len(set(s)) == len(s)]}\"", "def greet(name, owner):\n return 'Hello {}'.format({owner: 'boss'}.get(name, 'guest'))", "greet = lambda name, owner: 'Hello %s' % ['guest', 'boss'][name == owner]", "def greet(name, owner):\n n = 'boss' if name == owner else 'guest'\n return 'Hello {}'.format(n)", "def greet(name, owner):\n a = name\n b = owner\n if a == b:\n return 'Hello boss'\n else:\n return 'Hello guest'", "def greet(a, b):\n return 'Hello {}'.format(['guest', 'boss'][a == b])", "def greet(n, r):\n return 'Hello ' + ('boss' if n == r else 'guest')", "def greet(name, owner):\n if name == owner:\n x = 'boss'\n else:\n x = 'guest'\n return 'Hello {}'.format(x)", "greet = lambda a, b: f\"Hello {('boss' if a == b else 'guest')}\"", "import unittest\nHELLO_BOSS_MSG = 'Hello boss'\nHELLO_GUEST_MSG = 'Hello guest'\n\ndef greet(name, owner):\n return 'Hello boss' if name == owner else 'Hello guest'\n\ndef test_should_return_hello_boss_msg_when_names_equals_owner():\n (name, owner) = ('Daniel', 'Daniel')\n actual = greet(name, owner)\n self.assertEqual(actual, 'Hello boss')\n\ndef test_should_return_hello_guest_msg_when_names_equals_owner():\n (name, owner) = ('Daniel', 'Guest')\n actual = greet(name, owner)\n self.assertEqual(actual, 'Hello guest')", "def greet(name, owner):\n if name == owner:\n what = 'boss'\n else:\n what = 'guest'\n return 'Hello {}'.format(what)", "greet = lambda n, o: 'Hello {0}'.format('boss' if o == n else 'guest')", "def greet(n, m):\n if n == m:\n return 'Hello boss'\n return 'Hello guest'", "def greet(name, name2):\n if str(name) == str(name2):\n return 'Hello boss'\n else:\n return 'Hello guest'", "def greet(name, owner):\n boss = 'Hello boss'\n guest = 'Hello guest'\n if name == 'Daniel' and owner == 'Daniel':\n return boss\n else:\n return guest", "def greet(name, owner):\n f_name = name.lower()\n f_owner = owner.lower()\n if f_name == f_owner:\n return 'Hello boss'\n else:\n return 'Hello guest'", "def greet(name, owner):\n return f\"Hello {name == owner and 'boss' or 'guest'}\"", "greet = lambda name, owner: 'Hello guest' if name != owner else 'Hello boss'", "def greet(n, o):\n return f\"Hello {('boss' if n == o else 'guest')}\"", "def greet(name, owner):\n re = ['Hello boss', 'Hello guest']\n return re[0] if name == owner else re[1]", "def greet(name, owner):\n r = 'Hello guest'\n if name == owner:\n r = 'Hello boss'\n return r", "def greet(n, o):\n return 'Hello ' + ['guest', 'boss'][n == o]", "def greet(name, owner):\n x = 'boss' if name == owner else 'guest'\n return f'Hello {x}'", "def greet(name, owner):\n if name != owner:\n return 'Hello guest'\n elif owner == name:\n return 'Hello boss'", "def greet(name, owner):\n greeting = 'boss' if name == owner else 'guest'\n return 'Hello {greeting}'.format(greeting=greeting)", "def greet(name, owner):\n return 'Hello {0}'.format('guest' if name != owner else 'boss')", "def greet(name, owner):\n x = name\n y = owner\n if x == y:\n return 'Hello boss'\n else:\n return 'Hello guest'", "def greet(name, owner):\n if name == owner:\n return 'Hello boss'\n elif name != owner:\n return 'Hello guest'\n else:\n return 0", "def greet(name, owner):\n answer = 'Hello guest'\n if name == owner:\n answer = 'Hello boss'\n return answer", "def greet(name, owner):\n if name == owner:\n return 'Hello boss'\n if name != owner:\n return 'Hello guest'\n else:\n return None\ngreet('Bob', 'Bob')", "def greet(name, owner):\n a = 'boss' if name == owner else 'guest'\n return 'Hello {}'.format(a)"], "starter_code": "def greet(name, owner):\n", "input_output": {"fn_name": "greet", "inputs": [["Daniel", "Daniel"], ["Greg", "Daniel"]], "outputs": [["Hello boss"], ["Hello guest"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5772da22b89313a4d50012f7", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "greet", "task_id": "TACO_lite/431", "example": [[["Daniel", "Daniel"], ["Greg", "Daniel"]], ["Hello boss", "Hello guest"]]} +{"requirement": "Remove all characters except the numeric characters from an alphanumeric string.\nExample 1:\nInput: S = \"AA1d23cBB4\"\nOutput: 1234\nExplanation: Remove all characters\nother than numbers\nExample 2:\nInput: S = \"a1b2c3\"\nOutput: 123\nExplanation: Remove all characters\nother than numbers\nYour task:\nYour task is to complete the function string() which takes a single string as input and returns the string. You need not take any input or print anything.\n \nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= |S| <= 10^{5}", "solutions": ["def removecharacters(S):\n x = ''\n for char in S:\n if char.isdigit():\n x += char\n return x", "def removecharacters(S):\n a = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n result = ''\n for char in S:\n if char in a:\n result += char\n return result", "def removecharacters(S):\n l = [i for i in S if i.isdigit()]\n l = ''.join(l)\n return l", "def removecharacters(S):\n s = []\n for char in S:\n if char.isnumeric():\n s.append(char)\n return ''.join(s)", "def removecharacters(S):\n res = ''\n for i in S:\n if i.isdigit():\n res += i\n return res", "def removecharacters(S):\n str = ''\n for i in S:\n if i.isnumeric():\n str += i\n return str", "import re\n\ndef removecharacters(S):\n dig = ''.join(re.findall('\\\\d', S))\n return dig", "def removecharacters(S):\n s1 = ''\n for i in s:\n if i.isalpha():\n continue\n else:\n s1 += i\n return s1", "import re\n\ndef removecharacters(S):\n numeric_chars = re.sub('\\\\D', '', S)\n return numeric_chars", "def removecharacters(S):\n res = ''\n for i in S:\n ascii = ord(i)\n if ascii >= 48 and ascii <= 57:\n res = res + i\n return res", "def removecharacters(S):\n s = ''\n for i in S:\n if not i.isalpha():\n s += i\n return s", "def removecharacters(S):\n l = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\n g = ''\n for i in range(len(S)):\n if s[i] not in l:\n g += s[i]\n else:\n continue\n return g", "def removecharacters(S):\n return ''.join([c for c in S if c.isdigit()])", "def removecharacters(S):\n l = len(S)\n s = ''\n for i in range(l):\n if S[i].isdigit():\n s += S[i]\n return s", "def removecharacters(S):\n i = len(S) - 1\n arr = list(S)\n while i >= 0:\n if not S[i].isnumeric():\n arr.pop(i)\n i -= 1\n return ''.join(arr)", "def removecharacters(S):\n k = ''\n for i in range(len(S)):\n if '0' <= S[i] <= '9':\n k += S[i]\n return k", "def removecharacters(S):\n output = ''\n for i in range(len(S)):\n if S[i].isalpha():\n pass\n else:\n output += s[i]\n return output", "def removecharacters(S):\n temp_list = []\n for i in S:\n if i.isdigit():\n temp_list.append(i)\n return ''.join(temp_list)", "def removecharacters(S):\n s = ''\n for i in S:\n if i.isalpha():\n pass\n else:\n s += i\n return s", "def removecharacters(S):\n v = ''\n for i in S:\n if i in '0123456789':\n v += i\n return v", "def removecharacters(S):\n l = ''\n for i in range(len(S)):\n if S[i] in '0123456789':\n l = l + S[i]\n else:\n continue\n return l", "def removecharacters(S):\n ans = ''\n for i in range(len(S)):\n if S[i].isdigit():\n ans += S[i]\n return ans", "def removecharacters(S):\n num = '0123456789'\n res = ''\n for i in S:\n if i in num:\n res += i\n return res", "def removecharacters(s):\n i = 0\n while i < len(s) - 1:\n if ord(s[i]) >= 48 and ord(s[i]) <= 57:\n i += 1\n else:\n s = s[0:i] + s[i + 1:]\n if s[i].isdigit():\n return s\n return s[0:i]", "def removecharacters(S):\n ans = []\n for i in [*S]:\n if i.isnumeric():\n ans.append(i)\n return ''.join(ans)", "def removecharacters(s):\n new = ''\n for i in s:\n if i.isdigit() == True:\n new += i\n return new", "def removecharacters(S):\n lut = '1234567890'\n res = ''\n for L in S:\n if L in lut:\n res += L\n return res", "def removecharacters(S):\n ans = ''\n for i in range(len(S)):\n if s[i] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:\n ans += s[i]\n return ans", "def removecharacters(S):\n st = ''\n for i in s:\n if i.isnumeric():\n st = st + i\n return st", "def removecharacters(S):\n s1 = list(S)\n s2 = []\n for i in s1:\n if i.isnumeric():\n s2.append(i)\n return ''.join(s2)", "def removecharacters(S):\n ans = ''\n for i in S:\n if ord(i) >= ord('0') and ord(i) <= ord('9'):\n ans += i\n return ans", "def removecharacters(S):\n str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\n str1 = ''\n for i in S:\n if i not in str:\n str1 = str1 + i\n return str1", "def removecharacters(S):\n newstr = []\n for i in S:\n if i.isdigit() == 1:\n newstr.append(i)\n ans = ''.join(newstr)\n return ans", "def removecharacters(S):\n res = ''\n for i in S:\n if i >= '0' and i <= '9':\n res += i\n return res", "def removecharacters(S):\n num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n result = ''\n for c in S:\n if c in num:\n result += c\n return result", "def removecharacters(S):\n ans = ''\n for i in S:\n if i >= '0' and i <= '9':\n ans += i\n else:\n continue\n return ans", "def removecharacters(S):\n num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n s = ''\n for i in S:\n if i in num:\n s += i\n return s", "def removecharacters(S):\n a = ''\n n = [str(i) for i in range(10)]\n for i in s:\n if i in n:\n a += i\n return a", "import re\n\ndef removecharacters(S):\n return ''.join([x for x in re.findall('\\\\d', S)])", "def removecharacters(s):\n string = ''\n for i in s:\n if i.isdigit():\n string += i\n else:\n continue\n return string", "def removecharacters(S):\n a = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']\n res = ''\n for i in S:\n if i in a:\n res = res + i\n return res", "def removecharacters(S):\n a = ''.join(filter(str.isdigit, S))\n return a", "def removecharacters(S):\n ec = ''\n n = '0123456789'\n for i in S:\n if i in n:\n ec += i\n return ec", "def removecharacters(s):\n a = ''\n for i in s:\n if i.isdigit():\n a += i\n return a", "def removecharacters(S):\n result = ''\n for char in s:\n if char.isdigit():\n result += char\n return result", "def removecharacters(S):\n c = ''\n n = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n for i in S:\n if i in n:\n c += i\n return c"], "starter_code": "def removecharacters(S):\n", "input_output": {"inputs": ["S = \"AA1d23cBB4\"", "S = \"a1b2c3\""], "outputs": ["1234", "123"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/remove-characters-from-alphanumeric-string0648/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "removecharacters", "task_id": "TACO_lite/516", "example": [[["AA1d23cBB4"], ["a1b2c3"]], ["1234", "123"]]} +{"requirement": "You are given the string S . Compress the string when lower and upper cases are the same. In compressed string characters should be in lowercase.\nExample 1:\nInput: S = \"aaABBb\"\nOutput: \"3a3b\"\nExplanation: As 'a' appears 3 times\nconsecutively and 'b' also 3 times,\nand 'b' and 'B' considered as same. \n​Example 2:\nInput: S = \"aaacca\"\nOutput: \"3a2c1a\"\nExplanation: As 'a' appears 3 times\nconsecutively and 'c' also 2 times,\nand then 'a' 1 time.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function transform() which takes the string S as inputs and returns the compressed string.\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 ≤ |S| ≤ 2 * 10^{5}\nS contains only lowercase and uppercase characters.", "solutions": ["def transform(S):\n ans = ''\n last = ''\n cnt = ''\n for i in range(len(S)):\n curr = S[i].lower()\n if curr == last:\n cnt += 1\n else:\n ans += str(cnt) + last\n last = curr\n cnt = 1\n ans += str(cnt) + last\n return ans", "def transform(S):\n s = S.lower()\n s1 = ''\n c = s[0]\n cou = 0\n i = -1\n for i in range(len(s) - 1):\n if s[i] == c:\n cou += 1\n elif s[i] != c:\n s1 += str(cou)\n s1 += c\n cou = 1\n c = s[i]\n if c == s[i + 1]:\n cou += 1\n s1 += str(cou)\n s1 += c\n else:\n s1 += str(cou)\n s1 += c\n s1 += '1' + s[i + 1]\n return s1", "def transform(s):\n s = s.lower()\n ans = ''\n c = 1\n x = s[0]\n for i in s[1:]:\n if i == x:\n c += 1\n else:\n ans = ans + str(c) + x\n c = 1\n x = i\n ans = ans + str(c) + x\n return ans", "def transform(s):\n s = s.lower()\n n = len(s)\n pre_char = s[0]\n count = 1\n final = ''\n for i in range(1, n):\n if pre_char == s[i]:\n count += 1\n else:\n final += str(count) + s[i - 1]\n count = 1\n pre_char = s[i]\n return final + str(count) + s[n - 1]", "def transform(S):\n st = []\n s = ''\n S = S.lower()\n for i in S:\n if not st:\n st.append(i)\n elif st[-1] == i:\n st.append(i)\n else:\n c = 0\n while st:\n m = st.pop()\n c += 1\n s = s + str(c) + m\n st.append(i)\n c = 0\n while st:\n c += 1\n m = st.pop()\n s = s + str(c) + m\n return s", "def transform(S):\n S = S.lower()\n k = ''\n l = []\n l.append(S[0])\n for i in S[1:]:\n if l[0] == i:\n l.append(i)\n else:\n k = k + str(len(l)) + l[0]\n l.clear()\n l.append(i)\n return k + str(len(l)) + l[0]", "def transform(S):\n S = S.lower()\n string = ''\n count = 1\n temp = S[0]\n for char in S[1:]:\n if char == temp:\n count += 1\n else:\n string += str(count) + temp\n count = 1\n temp = char\n string += str(count) + temp\n return string", "def transform(s):\n if not s:\n return ''\n s = s.lower()\n pointer = s[0]\n count = 1\n result = ''\n for val in s[1:]:\n if pointer == val:\n count += 1\n else:\n result += str(count) + pointer\n pointer = val\n count = 1\n result = result + (str(count) + pointer)\n return result", "def transform(S):\n x = S.lower()\n string = ''\n count = 0\n temp = x[0]\n for i in range(len(S)):\n if x[i] == temp:\n count = count + 1\n else:\n string = string + str(count)\n string = string + temp\n count = 1\n temp = x[i]\n return string + str(count) + temp", "def transform(S):\n s = S.lower()\n output = ''\n count = 1\n pre = s[0]\n if len(s) == 1:\n output = output + str(count) + pre\n for i in range(1, len(s)):\n if s[i] == pre:\n count += 1\n else:\n output = output + str(count) + pre\n pre = s[i]\n count = 1\n if i == len(s) - 1:\n output = output + str(count) + pre\n return output", "def transform(s):\n s = s.lower()\n result = ''\n item = s[0]\n count = 1\n for char in s[1:]:\n if char == item:\n count += 1\n else:\n result += str(count) + item\n count = 1\n item = char\n result += str(count) + item\n return result", "def transform(S):\n stk = []\n r = ''\n i = 0\n l = len(S)\n while i < l:\n t = S[i].lower()\n if not stk:\n stk.append(t)\n i += 1\n elif stk[-1] == t:\n stk.append(t)\n i += 1\n else:\n r += str(len(stk)) + stk[-1]\n stk = []\n r += str(len(stk)) + stk[-1]\n return r", "def transform(S):\n result = ''\n count = 1\n first = S[0].lower()\n for i in range(1, len(S)):\n if S[i].lower() == first:\n count += 1\n else:\n result += str(count) + first\n first = S[i].lower()\n count = 1\n if i == len(S) - 1:\n result += str(count) + first\n if len(S) == 1:\n result = str(count) + S[0].lower()\n return result", "def transform(s):\n c = 1\n t = s[0].lower()\n j = ''\n for i in range(1, len(s)):\n if t == s[i].lower():\n c += 1\n else:\n j += str(c) + t.lower()\n c = 1\n t = s[i].lower()\n j += str(c) + t.lower()\n return j", "def transform(S):\n c = 0\n s = ''\n co = 0\n for i in range(len(S) - 1):\n if S[i + 1].lower() != S[c].lower():\n s += str(co + 1)\n s += str(S[c].lower())\n co = 0\n c = i + 1\n else:\n co += 1\n s += str(co + 1)\n s += str(S[-1].lower())\n return s", "def transform(S):\n S = S.lower()\n final = ''\n rep = ''\n cnt = 0\n for s in S:\n if rep == '':\n rep = s\n cnt += 1\n elif rep == s:\n cnt += 1\n else:\n final += str(cnt) + rep\n cnt = 1\n rep = s\n final += str(cnt) + rep\n return final", "def transform(S):\n out = ''\n S = S.lower()\n i = 0\n while i < len(S):\n count = 1\n while i < len(S) - 1 and S[i] == S[i + 1]:\n count += 1\n i += 1\n i += 1\n out += str(count) + S[i - 1]\n return out", "def transform(S):\n c = 1\n aux = S[0].lower()\n s1 = ''\n for i in range(1, len(S)):\n if S[i].lower() == aux:\n c += 1\n else:\n s1 += str(c) + aux\n aux = S[i].lower()\n c = 1\n s1 += str(c) + aux\n return s1", "def transform(S):\n sta = []\n S = S.lower()\n st = ''\n k = 0\n for i in range(len(S)):\n if len(sta) == 0 or S[i] != sta[-1]:\n if k != 0:\n st += str(k) + sta.pop()\n sta.append(S[i])\n k = 1\n else:\n k += 1\n if len(S) - 1 == i:\n st += str(k) + sta.pop()\n return st", "def transform(S):\n x = S.lower()\n ans = ''\n t = x[0]\n cnt = 0\n N = len(S)\n for i in range(N):\n if x[i] == t:\n cnt += 1\n else:\n ans += str(cnt) + t\n cnt = 1\n t = x[i]\n return ans + str(cnt) + t", "def transform(S):\n S = S.lower()\n final_str = ''\n char_count = 0\n for i in range(len(S)):\n if i + 1 == len(S):\n if char_count != 0:\n char_count = char_count + 1\n final_str = final_str + str(char_count) + S[i]\n else:\n final_str = final_str + str(1) + S[i]\n elif S[i] == S[i + 1]:\n char_count = char_count + 1\n else:\n char_count = char_count + 1\n final_str = final_str + str(char_count) + S[i]\n char_count = 0\n return final_str", "def transform(S):\n S = S.lower()\n res = ''\n char = S[0]\n count = 1\n for i in range(1, len(S)):\n if S[i] == char:\n count += 1\n else:\n res = res + str(count) + char\n count = 1\n char = S[i]\n res = res + str(count) + char\n return res", "def transform(S):\n i = 0\n j = 0\n res = ''\n S = S.lower()\n while i < len(S):\n c = 0\n while j < len(S) and S[i] == S[j]:\n c += 1\n j += 1\n if c > 0:\n res += str(c) + S[i]\n i += 1\n return res", "def transform(S):\n k = 0\n i = 0\n j = 0\n li = []\n while j < len(S) and i <= j:\n if ord(S[i]) == ord(S[j]) or abs(ord(S[i]) - ord(S[j])) == 32:\n k += 1\n j += 1\n else:\n li.append(str(k) + S[i].lower())\n i = j\n k = 0\n if j == len(S):\n li.append(str(k) + S[i].lower())\n return ''.join(li)", "def transform(S):\n st = ''\n c = 0\n x = S.lower()\n t = x[0]\n for i in range(len(S)):\n if x[i] == t:\n c += 1\n else:\n st += str(c)\n st += t\n c = 1\n t = x[i]\n return st + str(c) + t", "def transform(S):\n c = 1\n l = ''\n if len(S) == 1:\n l += '1'\n l += S[0].lower()\n return l\n for i in range(len(S) - 1):\n if S[i].lower() == S[i + 1].lower():\n c += 1\n if i == len(S) - 2:\n l += str(c)\n l += S[i].lower()\n else:\n l += str(c)\n l += S[i].lower()\n c = 1\n if S[-1].lower() != S[-2].lower():\n l += '1'\n l += S[-1].lower()\n return l", "def transform(S):\n S = S.lower()\n count = 1\n i = 0\n ans = ''\n if len(S) == 1:\n return '1' + S.lower()\n while i != len(S) - 2:\n if S[i] == S[i + 1]:\n count += 1\n else:\n ans += str(count) + S[i].lower()\n count = 1\n i += 1\n i += 1\n if S[i] == S[i - 1]:\n count += 1\n ans += str(count) + S[i].lower()\n else:\n ans += str(count) + S[i - 1].lower()\n count = 1\n ans += str(count) + S[i].lower()\n return ans", "def transform(S):\n S = S.lower()\n cnt = 1\n l = []\n for i in range(len(S) - 1):\n if S[i] == S[i + 1]:\n cnt += 1\n else:\n l.append(str(cnt))\n l.append(S[i])\n cnt = 1\n l.append(str(cnt))\n l.append(S[-1])\n return ''.join(l)", "def transform(S):\n c = 1\n S = S.lower()\n l = ''\n item = S[0]\n for i in S[1:]:\n if i == item:\n c += 1\n else:\n l += str(c) + item\n c = 1\n item = i\n l += str(c) + item\n return l", "def transform(S):\n if len(S) == 1:\n return '1' + S.lower()\n ans = ''\n count = 0\n for i in range(0, len(S) - 1):\n if S[i].lower() == S[i + 1].lower():\n count = count + 1\n else:\n ans = ans + str(count + 1) + S[i].lower()\n count = 0\n if S[-1].lower() == S[-2].lower():\n ans = ans + str(count + 1) + S[-1].lower()\n else:\n ans = ans + '1' + S[-1].lower()\n return ans", "def transform(S):\n s1 = S.lower()\n count = 1\n s2 = ''\n for i in range(len(s1) - 1):\n if s1[i] == s1[i + 1]:\n count += 1\n else:\n s2 += str(count)\n s2 += str(s1[i])\n count = 1\n s2 += str(count)\n s2 += str(s1[-1])\n return s2", "def transform(S):\n S = S.lower()\n res = ''\n item = S[0]\n count = 1\n for char in S[1:]:\n if char == item:\n count += 1\n else:\n res += str(count) + item\n count = 1\n item = char\n res += str(count) + item\n return res", "def transform(S):\n S = S.lower()\n result = ''\n stack = ''\n for char in S:\n if stack and char != stack[-1]:\n result += str(len(stack)) + stack[-1]\n stack = char\n else:\n stack += char\n result += str(len(stack)) + stack[-1]\n return result", "def transform(S):\n S = S.lower()\n st = S[0]\n ans = ''\n count = 1\n for i in S[1:]:\n if i in st:\n count += 1\n else:\n ans += str(count) + st\n count = 1\n st = i\n ans += str(count) + st\n return ans", "def transform(S):\n S = S.lower()\n l = len(S)\n cnt = 1\n i = 1\n r = ''\n if l == 0:\n return ''\n if l == 1:\n return '1' + S\n while i < l:\n if S[i] == S[i - 1]:\n cnt += 1\n else:\n r = r + str(cnt) + S[i - 1]\n cnt = 1\n i += 1\n r = r + str(cnt) + S[i - 1]\n return r", "def transform(S):\n S = S.lower()\n k = ''\n st = []\n for i in range(len(S)):\n if st:\n if st[-1] == S[i]:\n pass\n else:\n k += str(len(st)) + st[-1]\n st = []\n st.append(S[i])\n k += str(len(st)) + st[-1]\n return k", "def transform(S):\n ans = ''\n S = S.lower() + ' '\n s = []\n for i in S:\n if len(s) == 0:\n s.append(i)\n elif s[-1] == i:\n s.append(i)\n else:\n ans += str(len(s))\n ans += s[0]\n s = [i]\n return ans", "def getSmall(char):\n return char.lower()\n\ndef transform(S):\n stack = []\n for char in S:\n char = self.getSmall(char)\n if not stack:\n stack.append([1, char])\n elif stack[-1][1] == char:\n stack[-1][0] += 1\n else:\n stack.append([1, char])\n res = ''\n for (freq, val) in stack:\n res += str(freq)\n res += val\n return res", "def transform(S):\n new = ''\n count = 1\n l = 1\n r = len(S)\n while l < r:\n if S[l].lower() == S[l - 1].lower():\n count += 1\n l += 1\n else:\n new += str(count) + S[l - 1].lower()\n count = 1\n l += 1\n new += str(count) + S[l - 1].lower()\n return new", "def transform(S):\n S = S.lower()\n S = S + ' '\n x = S[0]\n y = 0\n z = ''\n for (index, item) in enumerate(S):\n if item != x:\n z = z + str(index - y) + x\n y = index\n x = item\n return z", "def transform(s):\n s = s.lower()\n st = []\n count = 1\n for i in range(len(s) - 1):\n if s[i] != s[i + 1]:\n st.append(str(count))\n st.append(s[i])\n count = 1\n else:\n count += 1\n st.append(str(count))\n st.append(s[-1])\n return ''.join(st)", "def transform(S):\n S = S.lower()\n result = ''\n n = 1\n while len(S) > 1:\n if S[0] == S[1]:\n n += 1\n S = S[1:]\n else:\n result += str(n) + S[0]\n S = S[1:]\n n = 1\n result += str(n) + S[0]\n return result", "def transform(S):\n S = S.lower()\n res = ''\n c = 0\n st = []\n for x in S:\n if not st:\n st.append(x)\n c += 1\n elif st and x == st[-1]:\n st.append(x)\n c += 1\n elif st and x != st[-1]:\n res += str(c) + st[-1]\n st.append(x)\n c = 1\n res += str(c) + st[-1]\n return res", "def transform(S):\n S = S.lower()\n (i, j) = (0, 1)\n ans = ''\n count = 1\n if len(S) == 1:\n ans += str(count) + S[0]\n return ans\n while i < len(S) or j < len(S):\n if S[i] == S[j]:\n count += 1\n if j == len(S) - 1:\n ans += str(count) + S[i]\n break\n j += 1\n else:\n ans += str(count) + S[i]\n count = 1\n i = j\n if j == len(S) - 1:\n ans += str(count) + S[j]\n break\n j += 1\n return ans", "def transform(S):\n result = ''\n current_char = ''\n count = 0\n for ch in S:\n ch = ch.lower()\n if ch == current_char:\n count += 1\n else:\n if current_char:\n result += str(count) + current_char\n current_char = ch\n count = 1\n if current_char:\n result += str(count) + current_char\n return result", "def transform(s):\n s = s.lower()\n from itertools import groupby\n r = ''\n k = [[len(list(j)), i] for (i, j) in groupby(s)]\n for i in k:\n for j in i:\n r += str(j)\n return r", "def transform(S):\n l = list(S)\n c = 0\n l1 = []\n j = 0\n d = {}\n for i in range(len(l)):\n if l1 == []:\n l1.append(l[i].lower())\n c += 1\n elif l1[-1] == l[i].lower():\n c += 1\n else:\n d[j] = [str(c), l1.pop()]\n c = 1\n l1.append(l[i].lower())\n j += 1\n if c > 0:\n d[j] = [str(c), l1.pop()]\n d1 = sorted(d.keys())\n s = ''\n for i in d1:\n for j in d[i]:\n s += j\n return s", "def transform(s):\n s = s.lower()\n n = len(s)\n new_str = ''\n j = 0\n count = 0\n for i in range(n):\n if s[i] == s[j]:\n count += 1\n else:\n new_str = new_str + str(count) + s[j]\n j = i\n count = 1\n new_str = new_str + str(count) + s[j]\n return new_str", "def transform(S):\n numb = 1\n stack = []\n res = ''\n for i in S.lower():\n if len(stack) == 0:\n stack.append(i)\n elif i == stack[-1]:\n numb += 1\n else:\n res += str(numb) + stack[-1]\n stack.append(i)\n numb = 1\n res += str(numb) + stack[-1]\n return res", "import queue\n\ndef transform(S):\n q = queue.LifoQueue()\n for i in range(len(S) - 1, -1, -1):\n if q.qsize() and q.queue[-1][0] == S[i].lower():\n q.queue[-1][1] += 1\n else:\n q.put([S[i].lower(), 1])\n res = ''\n while q.qsize():\n k = q.get()\n res += str(k[1]) + str(k[0])\n return res", "def transform(S):\n S = S.lower()\n init = S[0]\n cc = 1\n ans = ''\n for i in S[1:]:\n if i == init:\n cc += 1\n else:\n ans += str(cc) + init\n init = i\n cc = 1\n ans += str(cc) + init\n return ans", "def transform(s):\n s = s.lower()\n if len(s) == 1:\n return '1' + s\n new_s = ''\n count = 1\n for i in range(0, len(s) - 1):\n if s[i] == s[i + 1]:\n count += 1\n else:\n new_s += str(count) + s[i]\n count = 1\n else:\n new_s += str(count) + s[i + 1]\n return new_s", "def transform(S):\n stack = []\n top = -1\n ans = ''\n for i in range(0, len(S)):\n if len(stack) == 0 or stack[top] == S[i].lower() or stack[top] == S[i].upper():\n stack.append(S[i])\n else:\n ans = ans + str(len(stack)) + stack[top].lower()\n while len(stack) > 0:\n stack.pop()\n stack.append(S[i])\n ans = ans + str(len(stack)) + stack[top].lower()\n return ans", "def transform(S):\n s = S.lower() + ' '\n c = 1\n j = 1\n r = ''\n while j < len(s):\n if s[j] == s[j - 1]:\n c += 1\n else:\n r = r + str(c) + s[j - 1]\n c = 1\n j += 1\n return r", "def transform(s):\n s = s.lower()\n s += '@!'\n l = []\n c = 1\n for i in range(len(s) - 2):\n if s[i] == s[i + 1]:\n c += 1\n else:\n l.append(c)\n l.append(s[i])\n c = 1\n f = ''\n for i in range(len(l)):\n l[i] = str(l[i])\n for i in l:\n f += i\n return f", "def transform(s):\n stack = []\n for i in range(len(s)):\n if stack:\n if stack[-1][0] == s[i].lower():\n stack[-1][-1] += 1\n continue\n stack.append([s[i].lower(), 1])\n res = ''\n for i in range(len(stack)):\n res += str(stack[i][-1]) + stack[i][0]\n return res", "def transform(S):\n S = S.lower()\n a = S[0]\n c = 1\n b = ''\n for i in S[1:]:\n if i == a:\n c += 1\n else:\n b += str(c) + a\n a = i\n c = 1\n b += str(c) + a\n return b", "def transform(S):\n z = S.lower()\n l = []\n m = ''\n n = len(z)\n for i in z:\n if len(l) == 0:\n l.append(i)\n elif l[-1] == i:\n l.append(i)\n else:\n m += str(len(l)) + l[-1]\n l = []\n l.append(i)\n m += str(len(l)) + l[-1]\n return m", "def transform(arr):\n arr = arr.lower()\n n = 0\n arr = arr + '.'\n e = arr[0]\n S = ''\n for i in arr:\n if i == e:\n n += 1\n else:\n S = S + str(n) + e\n e = i\n n = 1\n return S", "def transform(S):\n a = 1\n s = ''\n for i in range(1, len(S)):\n if S[i].lower() == S[i - 1].lower():\n a += 1\n else:\n s += str(a) + S[i - 1].lower()\n a = 1\n s += str(a) + S[-1].lower()\n return s", "def transform(S):\n S = S.lower()\n from itertools import groupby\n m = [[len(list(j)), i] for (i, j) in groupby(S)]\n r = []\n for i in m:\n for j in i:\n r.append(j)\n return ''.join(map(str, r))"], "starter_code": "def transform(S):\n", "input_output": {"inputs": ["S = \"aaABBb\"", "S = \"aaacca\""], "outputs": ["\"3a3b\"", "\"3a2c1a\""]}, "difficulty": "EASY", "raw_tags": ["Stack", "Strings", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/easy-string2212/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "transform", "task_id": "TACO_lite/540", "example": [[["aaABBb"], ["aaacca"]], ["3a3b", "3a2c1a"]]} +{"requirement": "~~~if-not:ruby,python\nReturn `1` when *any* odd bit of `x` equals 1; `0` otherwise.\n~~~\n~~~if:ruby,python\nReturn `true` when *any* odd bit of `x` equals 1; `false` otherwise.\n~~~\n\nAssume that:\n* `x` is an unsigned, 32-bit integer;\n* the bits are zero-indexed (the least significant bit is position 0)\n\n\n## Examples\n\n```\n 2 --> 1 (true) because at least one odd bit is 1 (2 = 0b10)\n 5 --> 0 (false) because none of the odd bits are 1 (5 = 0b101)\n170 --> 1 (true) because all of the odd bits are 1 (170 = 0b10101010)\n```", "solutions": ["MATCH = int('10' * 16, 2)\n\ndef any_odd(x):\n return bool(MATCH & x)", "def any_odd(n):\n return 1 if '1' in bin(n)[2:][-2::-2] else 0", "def any_odd(x):\n return x & 2863311530 != 0", "def any_odd(x):\n return int('1' in f'{x:032b}'[::2])", "def any_odd(x):\n a = bin(x)[2:]\n b = a[-2::-2]\n return 1 if '1' in b else 0", "def any_odd(x):\n return '1' in f'0{x:b}'[-2::-2]", "def any_odd(x):\n binary = bin(x)\n answer = 0\n binary_reversed = str(binary[::-1])\n for k in range(0, len(binary_reversed)):\n if k % 2 != 0 and binary_reversed[k] == '1':\n answer = 1\n return answer", "def any_odd(x):\n return '1' in list(bin(x)[-2::-2])", "def any_odd(x):\n bina = bin(x).split('b')[1]\n for (a, b) in enumerate(bina, start=len(bina) - 1):\n if a % 2:\n if '1' in b:\n return 1\n return 0"], "starter_code": "def any_odd(x):\n", "input_output": {"fn_name": "any_odd", "inputs": [[2863311530], [128], [131], [2], [24082], [0], [85], [1024], [1], [1365]], "outputs": [[true], [true], [true], [true], [true], [false], [false], [false], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Bits"], "name": null, "source": "codewars", "tags": ["Bit manipulation", "Fundamentals"], "skill_types": ["Bit manipulation"], "url": "https://www.codewars.com/kata/5d6f49d85e45290016bf4718", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "any_odd", "task_id": "TACO_lite/518", "example": [[[2], [5], [170]], ["1", "0", "1"]]} +{"requirement": "## Task:\n\nYour task is to write a function which returns the sum of following series upto nth term(parameter).\n\n Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...\n \n## Rules:\n \n* You need to round the answer to 2 decimal places and return it as String.\n\n* If the given value is 0 then it should return 0.00\n\n* You will only be given Natural Numbers as arguments.\n\n## Examples:\n\n SeriesSum(1) => 1 = \"1.00\"\n SeriesSum(2) => 1 + 1/4 = \"1.25\"\n SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = \"1.57\"\n \n**NOTE**: In PHP the function is called `series_sum()`.", "solutions": ["def series_sum(n):\n return '{:.2f}'.format(sum((1.0 / (3 * i + 1) for i in range(n))))", "def series_sum(n):\n seriesSum = 0.0\n for x in range(n):\n seriesSum += 1 / (1 + x * 3)\n return '%.2f' % seriesSum", "from fractions import Fraction\n\ndef series_sum(n):\n total = sum((Fraction(1, 1 + i * 3) for i in range(n)))\n return '{:.2f}'.format(total.numerator / total.denominator)", "def series_sum(n):\n return f'{sum((1 / d for d in range(1, n * 3, 3))):.2f}'", "def series_sum(n):\n return '%.2f' % sum(map(lambda x: x ** (-1), range(1, 3 * n, 3)))", "def series_sum(n):\n result = 0\n for i in range(0, n):\n result += 1 / (1 + 3 * i)\n return '{number:.{digits}f}'.format(number=result, digits=2)", "series_sum = lambda n: '{:.2f}'.format(sum((1.0 / (3 * i - 2) for i in range(1, n + 1))))", "series_sum = lambda n: '{:.2f}'.format(round(sum((1 / (1 + e * 3) for e in range(n))), 2))", "def series_sum(n):\n total = 0\n for i in range(n):\n total += 1 / (1 + i * 3)\n return str('%.2f' % total)", "def series_sum(number):\n solution = sum((1 / (1 + 3 * i) for i in range(number)))\n return format(solution, '.2f')", "def series_sum(n):\n return f'{n and sum((1 / i for i in range(1, n * 3 + 1, 3))):.2f}'", "from fractions import Fraction\nfrom functools import lru_cache\n\ndef rec(n):\n if not n:\n return 0\n return Fraction(1, 3 * n - 2) + rec(n - 1)\n\ndef series_sum(n):\n return f'{float(rec(n)):.2f}'", "def series_sum(n):\n sum = 0.0\n if n == 1:\n return '1.00'\n elif n == 0:\n return '0.00'\n else:\n denominator = 1.0\n for i in range(0, n):\n if i + 1 <= n:\n sum = sum + 1 / denominator\n denominator = denominator + 3.0\n return str(format(round(sum, 2), '.2f'))", "def series_sum(n):\n return '%.2f' % sum((1 / x for x in range(1, n * 3 + 1, 3)))", "def series_sum(n):\n l = []\n if n == 0:\n x = '0.00'\n while n > 0:\n l.append(1 / (1 + 3 * (n - 1)))\n n -= 1\n x = '%.2f' % sum(l)\n return x", "def series_sum(n):\n return '%0.2f' % round(sum([1 / (1 + (x - 1) * 3) for x in range(1, n + 1)]), 2)", "def series_sum(n):\n if n == 0:\n return '0.00'\n else:\n x = 1\n sum = 0\n for i in range(n):\n sum += 1 / x\n x += 3\n s = '{:0.2f}'.format(sum)\n return s", "def series_sum(n):\n return '{0:.2f}'.format(round(sum((1.0 / (1 + 3 * m) for m in range(n))), 2)) if n else '0.00'", "def series_sum(n):\n if n == 0:\n return '0.00'\n return '%0.2f' % float(str(1 + sum((1 / (1 + i * 3) for i in range(1, n)))))", "def series_sum(n):\n return format(sum((1 / (1 + 3 * k) for k in range(n))), '.2f')", "def series_sum(n):\n ls = []\n if n == 0:\n return str('%5.2f' % 0.0)[1:]\n for n in range(1, n):\n ls.append(1 / (1 + n * 3))\n return str('%5.2f' % float(sum(ls) + 1))[1:]", "def series_sum(n):\n return '%.2f' % sum([1 / (1 + 3 * t) for t in range(n)])", "def series_sum(n):\n result = 0\n for i in range(0, n):\n result += 1.0 / (1 + 3 * i)\n stringresult = str(round(result, 2))\n if stringresult == '0':\n stringresult = '0.00'\n while len(stringresult) < 4:\n stringresult += '0'\n return stringresult", "def series_sum(n):\n if n == 0:\n return '0.00'\n elif n == 1:\n return '1.00'\n sum = 1.0\n for i in range(1, n):\n sum += 1 / (1 + 3 * i)\n return '%.2f' % sum", "def series_sum(n):\n x = 0\n y = 1\n for n in range(1, n + 1):\n x = x + y\n y = 1 / (1 / y + 3)\n n = n - 1\n return format(x, '.2f')", "def series_sum(n):\n sum_ = sum([1 / (i * 3 - 2) for i in range(1, n + 1)])\n return '%.2f' % sum_", "from decimal import Decimal\n\ndef series_sum(n):\n if n == 0:\n sum_ = 0\n else:\n sum_ = 1\n for i in range(n - 1):\n nth_value = 1 / (4 + 3 * i)\n sum_ += nth_value\n sum_str = str(round(Decimal(sum_), 2))\n return sum_str", "def series_sum(n):\n return '{0:.2f}'.format(sum([(1 + 3 * (k - 1)) ** (-1) if k > 0 else k for k in range(n + 1)]))", "def series_sum(n):\n return '%.2f' % series_sum_(n)\n\ndef series_sum_(n):\n if n > 1:\n return series_sum_(n - 1) + float(float(1.0) / float(3 * (n - 1) + 1))\n elif n == 1:\n return float(1.0)\n return float(0.0)", "def series_sum(n):\n total = 0\n for num in range(1, n + 1):\n total += 1 / (1 + 3 * (num - 1))\n return '%.2f' % total", "def series_sum(n):\n f = 3 * n - 2\n s = 0\n if n == 0:\n return '0.00'\n for i in range(1, f + 1, 3):\n s = s + 1 / i\n return '{:.2f}'.format(s)", "def series_sum(n):\n sum = 0\n div = 1\n for i in range(n):\n sum += 1 / div\n div += 3\n if n == 0:\n return str(n) + '.00'\n elif len(str(round(sum, 2))) < 4:\n return str(round(sum, 2)) + '0'\n else:\n return str(round(sum, 2))", "def series_sum(n):\n if n == 0:\n term = 0\n elif n > 0:\n term = 1\n for i in range(1, n):\n term += 1 / (3 * i + 1)\n sumterm = float('{:.2f}'.format(term))\n return '%0.2f' % term", "def series_sum(n):\n if n == 0:\n return '0.00'\n else:\n counter = 1\n list = [1]\n while counter < n:\n list.append(1 / (1 + 3 * counter))\n counter += 1\n flt = round(sum(list), 2)\n result = format(flt, '.2f')\n return result", "def series_sum(n):\n ans = 0\n while n != 0:\n ans += 1 / (3 * n - 2)\n n -= 1\n return '{:.2f}'.format(round(ans, 2)).__str__()", "def series_sum(n):\n if n == 0:\n return '0.00'\n final = 0\n x = 0\n while n >= 1:\n final += 1 / (1 + x)\n x += 3\n n -= 1\n final = str(final)\n if len(final) < 4:\n final += '0'\n if len(final) > 4:\n if int(final[4]) > 4:\n final = str(float(final) + 0.01)\n return str(final)[:4]", "def series_sum(n):\n summa = sum([1 / (1 + 3 * x) for x in range(n)])\n return f'{summa:.{2}f}'", "def series_sum(n=0):\n sum = 0.0\n num = 1\n for i in range(n):\n sum += 1 / num\n num += 3\n return (str(round(sum, 2)) + '0')[:4]", "def series_sum(n):\n x = 1\n s = 0\n for i in range(n):\n s += 1 / (x + i * 3)\n if s == 0:\n return '0.00'\n if len(str(round(s, 2))) < 4:\n return str(round(s, 2)) + '0'\n return str(round(s, 2))", "def series_sum(n):\n if n == 0:\n return '0.00'\n if n == 1:\n return '1.00'\n elif n == 2:\n return '1.25'\n else:\n sum = 1.25\n i = 4\n for loop in range(n - 2):\n i = i + 3\n sum = sum + 1 / i\n return '{:.2f}'.format(sum)", "def series_sum(n):\n result = 1 + 1 / 4\n a = 4\n if n == 1:\n return str('%.2f' % n)\n elif n == 0:\n return str('%.2f' % 0)\n for i in range(1, n - 1):\n result += 1 / (a + i * 3)\n return str('%.2f' % result)", "def series_sum(n):\n answer = 0\n for number in range(n):\n answer += 1 / (1 + number * 3)\n return str(format(answer, '.2f'))", "def series_sum(n):\n i = 1\n x = 0\n for a in range(n):\n x += 1 / i\n i += 3\n return '{:.2f}'.format(x)", "def series_sum(n):\n output = 0\n for i in range(n):\n output += 1 / (1 + i * 3)\n if len(str(round(output, 2))) < 4:\n if str(round(output, 2)) != '0':\n a = str(round(output, 2))\n a += '0'\n return a\n else:\n return '0.00'\n else:\n return str(round(output, 2))", "def series_sum(n):\n if n == 0:\n return '0.00'\n if n == 1:\n return '1.00'\n sum = 1.0\n for i in range(n - 1):\n sum = sum + 1 / (4 + 3 * i)\n return '{:.2f}'.format(sum)", "import decimal\n\ndef series_sum(n):\n return '%.2f' % sum((1 / (1 + 3 * i) for i in range(n)))", "import math\n\ndef series_sum(n):\n result = 0.0\n for i in list(range(0, n)):\n result += 1.0 / (1.0 + 3.0 * float(i))\n return '{:.2f}'.format(result)", "def series_sum(n):\n if n == 0:\n return '0.00'\n else:\n numerator = 1\n denom = 1\n output = ''\n num = 0.0\n for i in range(n):\n num += numerator / denom\n denom += 3\n output = str(format(round(num, 2), '.2f'))\n return output", "from fractions import Fraction\n\ndef series_sum(n):\n sum = 0\n for i in range(n):\n sum += 1 / (1 + i * 3)\n return format(sum, '.2f')", "def series_sum(n):\n return (str(round(1 + sum((1 / x for x in range(4, n * 3, 3))), 2)) if n > 1 else str(float(n))).ljust(4, '0')", "def series_sum(n):\n s = 1\n i = 1\n if n > 1:\n while i < n:\n s = 1 / (1 + i * 3) + s\n i += 1\n else:\n return str('%.2f' % n)\n return str('%.2f' % s)", "def series_sum(n):\n array = []\n for i in range(n):\n array.append(1 / (1 + 3 * i))\n return f'{sum(array):.2f}'", "def series_sum(n):\n sum = 0.0\n denom = 1.0\n for i in range(1, n + 1):\n sum = sum + 1 / denom\n denom = denom + 3.0\n return f'{sum:.2f}'", "def series_sum(n):\n sum = float()\n j = 1\n for i in range(n):\n sum += 1 / j\n j += 3\n result = str(round(sum, 2))\n if len(result) == 3:\n return result + '0'\n else:\n return result", "def series_sum(n):\n if n == 0:\n return '0.00'\n d = 1\n ans = 0\n for i in range(n):\n ans += 1 / d\n d += 3\n ans = f'{round(ans, 2)}'\n return ans if len(ans) == 4 else ans + '0' * (4 - len(ans))", "def series_sum(n):\n sum = 1.0\n if n == 1:\n return '1.00'\n elif n == 0:\n return '0.00'\n else:\n for x in range(1, n):\n sum = sum + 1 / (2 * (x + 1) + (x - 1))\n return '{:.2f}'.format(sum)", "def series_sum(n):\n sum = 0.0\n value = 1.0\n if n == 0:\n return format(sum, '.2f')\n for i in range(1, n + 1):\n sum = sum + 1 / value\n value += 3\n result = float('{0:.2f}'.format(sum))\n return format(sum, '.2f')", "def series_sum(n):\n y = str(round(sum([1 / x for x in range(1, n * 3 + 1, 3)]), 2))\n while len(y) < 4:\n y += '0'\n return '0.00' if n == 0 else y", "def series_sum(n):\n if n == 0:\n return '0.00'\n elif n == 1:\n return '1.00'\n else:\n s = 1\n a = [1]\n for i in range(n):\n s += 3\n a.append(1 / s)\n a[-1] = 0\n a = str(round(sum(a), 2))\n if len(a) == 4:\n return a\n else:\n b = a + '0'\n return b"], "starter_code": "def series_sum(n):\n", "input_output": {"fn_name": "series_sum", "inputs": [[1], [2], [3], [4], [5], [6], [7], [8], [9], [15], [39], [58], [0]], "outputs": [["1.00"], ["1.25"], ["1.39"], ["1.49"], ["1.57"], ["1.63"], ["1.68"], ["1.73"], ["1.77"], ["1.94"], ["2.26"], ["2.40"], ["0.00"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/555eded1ad94b00403000071", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "series_sum", "task_id": "TACO_lite/478", "example": [[[1], [2], [5]], ["1.00", "1.25", "1.57"]]} +{"requirement": "Given a binary tree, find its level order traversal.\nLevel order traversal of a tree is breadth-first traversal for the tree.\nExample 1:\nInput:\n 1\n / \\ \n 3 2\nOutput:1 3 2\nExample 2:\nInput:\n 10\n / \\\n 20 30\n / \\\n 40 60\nOutput:10 20 30 40 60\nYour Task:\nYou don't have to take any input. Complete the function levelOrder() that takes the root node as input parameter and returns a list of integers containing the level order traversal of the given Binary Tree.\nExpected Time Complexity: O(n)\nExpected Auxiliary Space: O(n)\nConstraints:\n1 ≤ Number of nodes ≤ 105\n1 ≤ Data of a node ≤ 105", "solutions": ["def levelorder(root):\n if root is None:\n return\n queue = [root]\n res = []\n while queue:\n pointer = queue.pop(0)\n res.append(pointer.data)\n if pointer.left is not None:\n queue.append(pointer.left)\n if pointer.right is not None:\n queue.append(pointer.right)\n return res", "def levelorder(root):\n q = []\n q.append(root)\n res = []\n while len(q) != 0:\n u = q.pop(0)\n res.append(u.data)\n if u.left is not None:\n q.append(u.left)\n if u.right is not None:\n q.append(u.right)\n return res", "def levelorder(root):\n result = []\n if not root:\n return result\n queue = deque()\n queue.append(root)\n while queue:\n size = len(queue)\n for i in range(size):\n temp = queue.popleft()\n result.append(temp.data)\n if temp.left != None:\n queue.append(temp.left)\n if temp.right != None:\n queue.append(temp.right)\n return result", "def levelorder(root):\n res = []\n if root is None:\n return res\n que = []\n que.append(root)\n while 1:\n n = len(que)\n if n == 0:\n break\n while n > 0:\n node = que.pop(0)\n res.append(node.data)\n if node.left != None:\n que.append(node.left)\n if node.right != None:\n que.append(node.right)\n n -= 1\n return res", "def levelorder(root):\n q = deque([root])\n ans = []\n while q:\n node = q.popleft()\n ans.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return ans", "def levelorder(root):\n if root == None:\n return\n stack = []\n res = []\n stack.append(root)\n while len(stack) != 0:\n res.append(stack[0].data)\n node = stack.pop(0)\n if node.left != None:\n stack.append(node.left)\n if node.right != None:\n stack.append(node.right)\n return res", "from collections import deque\n\ndef levelorder(node):\n queue = deque()\n queue.append(node)\n return_list = []\n while queue:\n temp = queue.popleft()\n return_list.append(temp.data)\n if temp.left:\n queue.append(temp.left)\n if temp.right:\n queue.append(temp.right)\n return return_list", "def levelorder(root):\n q = deque()\n res = []\n q.append(root)\n while len(q):\n t = q.popleft()\n res.append(t.data)\n if t.left is not None:\n q.append(t.left)\n if t.right is not None:\n q.append(t.right)\n return res", "from queue import Queue\n\ndef levelorder(root):\n q = Queue()\n q.put(root)\n ans = list()\n while q.qsize() > 0:\n node = q.get()\n ans.append(node.data)\n if node.left:\n q.put(node.left)\n if node.right:\n q.put(node.right)\n return ans", "from collections import deque\n\ndef levelorder(root):\n queue = deque()\n ans = []\n queue.append(root)\n while len(queue) >= 1:\n node = queue.popleft()\n if node.left is not None:\n queue.append(node.left)\n if node.right is not None:\n queue.append(node.right)\n ans.append(node.data)\n return ans", "def levelorder(root):\n a = [root]\n res = []\n while len(a) > 0:\n p = a.pop(0)\n if p.left:\n a.append(p.left)\n if p.right:\n a.append(p.right)\n res.append(p.data)\n return res", "def levelorder(root):\n a = []\n if root == None:\n return root\n a.append(root)\n q = [root.data]\n while len(a) != 0:\n t = a[0]\n if t.left:\n q.append(t.left.data)\n a.append(t.left)\n if t.right:\n q.append(t.right.data)\n a.append(t.right)\n a.pop(0)\n return q", "from collections import deque\n\ndef levelorder(root):\n ans = []\n q = deque([root])\n while q:\n x = q.popleft()\n ans.append(x.data)\n if x.left:\n q.append(x.left)\n if x.right:\n q.append(x.right)\n return ans", "def levelorder(root):\n if root == None:\n return []\n q = [root]\n ans = []\n while q:\n nod = q.pop(0)\n ans.append(nod.data)\n if nod.left:\n q.append(nod.left)\n if nod.right:\n q.append(nod.right)\n return ans", "from collections import deque\n\ndef levelorder(root):\n ans = []\n if root is None:\n return\n queue1 = deque()\n queue2 = deque()\n queue1.append(root)\n while len(queue1) != 0:\n top = queue1[0]\n queue1.popleft()\n ans.append(top.data)\n if top.left is not None:\n queue2.append(top.left)\n if top.right is not None:\n queue2.append(top.right)\n if len(queue1) == 0:\n (queue1, queue2) = (queue2, queue1)\n return ans", "def printCurrentLevel(root, level, ans):\n if root is None:\n return\n if level == 1:\n ans.append(root.data)\n elif level > 1:\n self.printCurrentLevel(root.left, level - 1, ans)\n self.printCurrentLevel(root.right, level - 1, ans)\n\ndef height(node):\n if node is None:\n return 0\n else:\n lheight = self.height(node.left)\n rheight = self.height(node.right)\n if lheight > rheight:\n return lheight + 1\n else:\n return rheight + 1\n\ndef levelorder(root):\n ans = []\n h = self.height(root)\n for i in range(1, h + 1):\n self.printCurrentLevel(root, i, ans)\n return ans", "from collections import deque\n\ndef levelorder(root):\n q = deque()\n q.append(root)\n arr = []\n while len(q) > 0:\n node = q.popleft()\n arr.append(node.data)\n if node.left != None:\n q.append(node.left)\n if node.right != None:\n q.append(node.right)\n return arr", "def levelorder(root):\n ans = []\n queue = [root]\n while queue:\n node = queue.pop(0)\n ans.append(node.data)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return ans", "def levelorder(root):\n if root is None:\n return []\n queue = [root]\n level_order = []\n while len(queue) > 0:\n node = queue.pop(0)\n level_order.append(node.data)\n if node.left is not None:\n queue.append(node.left)\n if node.right is not None:\n queue.append(node.right)\n return level_order", "def levelorder(root):\n ls = []\n ans = []\n ls.append(root)\n while ls:\n ele = ls.pop(0)\n ans.append(ele.data)\n if ele.left != None:\n ls.append(ele.left)\n if ele.right != None:\n ls.append(ele.right)\n return ans", "def levelorder(root):\n lvl = self.height(root)\n res = []\n for i in range(1, lvl + 1):\n self.lvlorderByHeight(root, i, res)\n return res\n\ndef lvlorderByHeight(root, target, res):\n if root == None or target <= 0:\n return\n if target == 1:\n res.append(root.data)\n return\n self.lvlorderByHeight(root.left, target - 1, res)\n self.lvlorderByHeight(root.right, target - 1, res)\n\ndef height(root):\n if root == None:\n return 0\n left = self.height(root.left)\n right = self.height(root.right)\n if left > right:\n return left + 1\n else:\n return right + 1", "def levelorder(root):\n qu = [root]\n res = []\n while qu:\n n = len(qu)\n while n:\n node = qu.pop(0)\n res.append(node.data)\n if node.left:\n qu.append(node.left)\n if node.right:\n qu.append(node.right)\n n -= 1\n return res", "def levelorder(root):\n if not root:\n return\n q = []\n res = []\n if root:\n q.append(root)\n while q:\n level = []\n size = len(q)\n for i in range(size):\n node = q.pop(0)\n level.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n res.append(level)\n result = []\n for i in res:\n for j in i:\n result.append(j)\n return result", "def levelorder(root):\n if root is None:\n return []\n queue = [root]\n next_queue = []\n level = []\n res = []\n while queue != []:\n for root in queue:\n level.append(root.data)\n if root.left is not None:\n next_queue.append(root.left)\n if root.right is not None:\n next_queue.append(root.right)\n for i in level:\n res.append(i)\n queue = next_queue\n next_queue = []\n level = []\n return res", "def levelorder(root):\n level_order = []\n max_height = [0]\n\n def get_tree_height(root):\n if root is None:\n return 0\n left_height = 1 + get_tree_height(root.left)\n right_height = 1 + get_tree_height(root.right)\n current_height = max(left_height, right_height)\n return current_height\n height = get_tree_height(root)\n\n def helper(root, level, level_order, target_level):\n if root:\n if level == target_level:\n level_order.append(root.data)\n else:\n helper(root.left, level + 1, level_order, target_level)\n helper(root.right, level + 1, level_order, target_level)\n for target_height in range(height):\n helper(root, 0, level_order, target_height)\n return level_order", "def levelorder(root):\n from collections import deque\n q = deque()\n q.append(root)\n level_order = []\n while len(q) > 0:\n for i in range(len(q)):\n current_node = q.popleft()\n level_order.append(current_node.data)\n if current_node.left:\n q.append(current_node.left)\n if current_node.right:\n q.append(current_node.right)\n return level_order", "from collections import deque\n\ndef levelorder(root):\n if root is None:\n return\n q = deque()\n q.append(root)\n ans = []\n while len(q) > 0:\n temp = q.popleft()\n ans.append(temp.data)\n if temp.left is not None:\n q.append(temp.left)\n if temp.right is not None:\n q.append(temp.right)\n return list(ans)", "def levelorder(root):\n arr = []\n\n def height(root):\n if not root:\n return 0\n return max(height(root.left), height(root.right)) + 1\n\n def func(root, level):\n if not root:\n return\n if level == 1:\n arr.append(root.data)\n return\n func(root.left, level - 1)\n func(root.right, level - 1)\n h = height(root)\n for i in range(1, h + 1):\n func(root, i)\n return arr", "import queue\n\ndef levelorder(root):\n if root is None:\n return None\n q = queue.Queue()\n mylist = []\n q.put(root)\n while not q.empty():\n curr = q.get()\n mylist.append(curr.data)\n if curr.left is not None:\n q.put(curr.left)\n if curr.right is not None:\n q.put(curr.right)\n return mylist", "def levelorder(root):\n q = [root]\n valuelist = []\n l = iter(q)\n root_ = next(l, 'end')\n while root_ != 'end':\n if root_.left:\n q.append(root_.left)\n if root_.right:\n q.append(root_.right)\n valuelist.append(root_.data)\n root_ = next(l, 'end')\n return valuelist", "def levelorder(root):\n res = []\n queue = []\n if root:\n queue.append(root)\n while queue:\n element = queue.pop(0)\n if element.left:\n queue.append(element.left)\n if element.right:\n queue.append(element.right)\n res.append(element.data)\n return res", "import queue\n\ndef levelorder(root):\n q = queue.Queue()\n out = []\n if not root:\n return out\n q.put(root)\n while q.qsize():\n node = q.get()\n out.append(node.data)\n if node.left:\n q.put(node.left)\n if node.right:\n q.put(node.right)\n return out", "def levelorderUtil(root, map, level):\n if root:\n self.levelorderUtil(root.left, map, level + 1)\n self.levelorderUtil(root.right, map, level + 1)\n if level not in map:\n map[level] = []\n map[level].append(root.data)\n\ndef levelorder(root):\n map = {}\n self.levelorderUtil(root, map, 0)\n out = []\n for level in range(len(map)):\n out.extend(map[level])\n return out", "def levelorder(root):\n if root is None:\n return []\n visited = []\n queue = [root]\n while queue:\n node = queue.pop(0)\n visited.append(node.data)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return visited", "from collections import deque\n\ndef levelorder(root):\n arr = []\n q = deque([root])\n while q:\n Node = q.popleft()\n arr.append(Node.data)\n if Node.left != None:\n q.append(Node.left)\n if Node.right != None:\n q.append(Node.right)\n return arr", "from collections import deque\n\ndef levelorder(root):\n q = deque()\n if root is None:\n return\n q.append(root)\n res = []\n while len(q) != 0:\n x = q.popleft()\n res.append(x.data)\n if x.left is not None:\n q.append(x.left)\n if x.right is not None:\n q.append(x.right)\n return res", "def levelorder(root):\n queue = [root]\n answer = []\n while queue:\n size = len(queue)\n for i in range(size):\n node = queue.pop(0)\n answer.append(node.data)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return answer", "def levelorder(root):\n queue = deque()\n queue.append(root)\n answer = []\n while queue:\n e = queue.popleft()\n answer.append(e.data)\n if e.left:\n queue.append(e.left)\n if e.right:\n queue.append(e.right)\n return answer", "def levelorder(root):\n temp = []\n l = [root]\n while len(l) > 0:\n x = l.pop(0)\n temp.append(x.data)\n if x.left:\n l.append(x.left)\n if x.right:\n l.append(x.right)\n return temp", "def levelorder(root):\n temp_arr = [[]]\n\n def levelorderUtil(root, level):\n if not root:\n return\n if temp_arr[level]:\n temp_arr[level].append(root.data)\n else:\n temp_arr.insert(level, [root.data])\n levelorderUtil(root.left, level + 1)\n levelorderUtil(root.right, level + 1)\n levelorderUtil(root, 0)\n result_arr = []\n for i in range(len(temp_arr)):\n result_arr += temp_arr[i]\n return result_arr", "def levelorder(root):\n l = []\n\n def height(node):\n if not node:\n return 0\n return max(height(node.left), height(node.right)) + 1\n\n def traverse(node, level):\n if not node:\n return\n if level == 1:\n l.append(node.data)\n else:\n traverse(node.left, level - 1)\n traverse(node.right, level - 1)\n h = height(root)\n for i in range(1, h + 1):\n traverse(root, i)\n return l", "from collections import deque\n\ndef fun(root, level, res):\n if root == None:\n return\n if level >= len(res):\n res.append([])\n res[level].append(root.data)\n self.fun(root.left, level + 1, res)\n self.fun(root.right, level + 1, res)\n\ndef levelorder(root):\n res = []\n self.fun(root, 0, res)\n l = []\n for i in res:\n l.extend(i)\n return l", "def levelorder(root):\n queue = [root]\n answer = []\n while queue:\n p = queue.pop(0)\n answer.append(p.data)\n if p.left is not None:\n queue.append(p.left)\n if p.right is not None:\n queue.append(p.right)\n return answer", "from collections import deque\n\ndef levelorder(root):\n if root is None:\n return []\n result = []\n queue = deque([root])\n while queue:\n level_length = len(queue)\n current_level = []\n for i in range(level_length):\n node = queue.popleft()\n current_level.append(node.data)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n result.append(current_level)\n return [val for level in result for val in level]", "def levelorder(root):\n temp_list = [root]\n output = []\n while len(temp_list) != 0:\n temp = []\n for node in temp_list:\n output.append(node.data)\n if node.left != None:\n temp.append(node.left)\n if node.right != None:\n temp.append(node.right)\n temp_list = temp\n return output", "def levelorder(root):\n if root == None:\n return None\n q = []\n q.append(root)\n result = []\n while q:\n n = len(q)\n for i in range(0, n):\n node = q.pop(0)\n if node is not None:\n result.append(node.data)\n q.append(node.left if node.left else None)\n q.append(node.right if node.right else None)\n return result", "def levelorder(root):\n q = [root]\n list1 = []\n while q:\n node = q.pop(0)\n list1.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return list1", "from collections import deque\n\ndef levelorder(root):\n listing = list()\n dQ = deque()\n dQ.append(root)\n while dQ:\n times = len(dQ)\n for i in range(times):\n holdnode = dQ.popleft()\n listing.append(holdnode.data)\n if holdnode.left != None:\n dQ.append(holdnode.left)\n if holdnode.right != None:\n dQ.append(holdnode.right)\n return listing", "import collections\nfrom collections import deque\n\ndef levelorder(root):\n ans = []\n if root is None:\n return ans\n queue = collections.deque()\n queue.append(root)\n while queue:\n currSize = len(queue)\n currList = []\n while currSize > 0:\n currNode = queue.popleft()\n currList.append(currNode.data)\n currSize -= 1\n if currNode.left is not None:\n queue.append(currNode.left)\n if currNode.right is not None:\n queue.append(currNode.right)\n ans.append(currList)\n res = []\n for i in ans:\n res.extend(i)\n return res", "def levelorder(root):\n level = []\n q = []\n q.append(root)\n while q:\n rootnode = q.pop(0)\n level.append(rootnode.data)\n if rootnode.left is not None:\n q.append(rootnode.left)\n if rootnode.right is not None:\n q.append(rootnode.right)\n return level", "def levelorder(root):\n if root is None:\n return\n arr = []\n ans = []\n arr.append(root)\n while len(arr) > 0:\n ans.append(arr[0].data)\n node = arr.pop(0)\n if node.left is not None:\n arr.append(node.left)\n if node.right is not None:\n arr.append(node.right)\n return ans", "def levelorder(root):\n order = []\n queue = []\n queue.append(root)\n while len(queue) > 0:\n temp = queue.pop(0)\n order.append(temp.data)\n if temp.left:\n queue.append(temp.left)\n if temp.right:\n queue.append(temp.right)\n return order", "def levelorder(root):\n if root is None:\n return None\n lis = []\n stack = []\n stack.append(root)\n while len(stack) > 0:\n n = len(stack)\n for i in range(n):\n node = stack.pop(0)\n lis.append(node.data)\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n return lis", "def levelorder(root):\n l = []\n l.append(root)\n r = []\n while len(l) != 0:\n t = l.pop(0)\n r.append(t.data)\n if t.left != None:\n l.append(t.left)\n if t.right != None:\n l.append(t.right)\n return r", "def levelorder(root):\n ans = []\n s = []\n s.append(root)\n while len(s) != 0:\n curr = s.pop(0)\n ans.append(curr.data)\n if curr.left != None:\n s.append(curr.left)\n if curr.right != None:\n s.append(curr.right)\n return ans", "from collections import deque\n\ndef levelorder(root):\n if not root:\n return []\n Q = deque()\n Q.append(root)\n res = []\n while Q:\n curr = Q.popleft()\n res.append(curr.data)\n if curr.left:\n Q.append(curr.left)\n if curr.right:\n Q.append(curr.right)\n return res"], "starter_code": "def levelorder(root ):\n", "input_output": {"inputs": ["1\r\n / \\ \r\n 3 2", "10\r\n / \\\r\n 20 30\r\n / \\\r\n 40 60"], "outputs": ["1 3 2", "10 20 30 40 60"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/level-order-traversal/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "levelorder", "task_id": "TACO_lite/511", "example": [[], []]} +{"requirement": "Given a Binary Tree of size N, find all the nodes which don't have any sibling. You need to return a list of integers containing all the nodes that don't have a sibling in sorted order.\nNote: Root node can not have a sibling so it cannot be included in our answer.\nExample 1:\nInput :\n 37\n / \n 20\n / \n 113 \nOutput: 20 113\nExplanation: 20 and 113 dont have any siblings.\nExample 2:\nInput :\n 1\n / \\\n 2 3 \nOutput: -1\nExplanation: Every node has a sibling.\nYour Task: \nYou dont need to read input or print anything. Complete the function noSibling() which takes the root of the tree as input parameter and returns a list of integers containing all the nodes that don't have a sibling in sorted order. If all nodes have a sibling, then the returning list should contain only one element -1.\nExpected Time Complexity: O(NlogN)\nExpected Auxiliary Space: O(Height of the tree)\nConstraints:\n1 ≤ N ≤ 10^4\nAll nodes have distinct values.", "solutions": ["def check(root, x):\n if root is None:\n return\n if root.left is None and root.right is not None:\n x.append(root.right.data)\n elif root.left is not None and root.right is None:\n x.append(root.left.data)\n check(root.left, x)\n check(root.right, x)\n\ndef noSibling(root):\n x = []\n check(root, x)\n if x:\n x.sort()\n return x\n return [-1]", "def noSibling(root):\n res = []\n\n def t(rt, re):\n if rt is None:\n return\n if rt.left is None and rt.right is not None:\n re.append(rt.right.data)\n elif rt.left is not None and rt.right is None:\n re.append(rt.left.data)\n t(rt.left, re)\n t(rt.right, re)\n t(root, res)\n if res:\n res.sort()\n return res\n else:\n return [-1]", "def noSibling(root):\n q = []\n ans = []\n if not root:\n return []\n q.append(root)\n while len(q) != 0:\n n = len(q)\n for i in range(n):\n node = q.pop(0)\n if node.left and (not node.right):\n ans.append(node.left.data)\n q.append(node.left)\n if node.right and (not node.left):\n ans.append(node.right.data)\n q.append(node.right)\n if node.left and node.right:\n q.append(node.left)\n q.append(node.right)\n if len(ans) == 0:\n return [-1]\n ans.sort()\n return ans", "def noSibling(root):\n queue = [root]\n ans = []\n while queue:\n node = queue.pop(0)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n if not node.left and node.right:\n ans.append(node.right.data)\n if node.left and (not node.right):\n ans.append(node.left.data)\n return list(sorted(ans)) if ans else [-1]", "from collections import deque\n\ndef noSibling(root):\n queue = deque()\n siblings = []\n queue.append(root)\n while queue:\n size = len(queue)\n for _ in range(size):\n node = queue.popleft()\n if node.left and node.right:\n queue.append(node.left)\n queue.append(node.right)\n elif node.left:\n queue.append(node.left)\n siblings.append(node.left.data)\n elif node.right:\n queue.append(node.right)\n siblings.append(node.right.data)\n return sorted(siblings) if len(siblings) > 0 else [-1]", "def noSiblingHelper(root, mylist):\n if root is None:\n return -1\n if root.left is not None and root.right is not None:\n noSiblingHelper(root.left, mylist)\n noSiblingHelper(root.right, mylist)\n elif root.left is not None and root.right is None:\n mylist.append(root.left.data)\n noSiblingHelper(root.left, mylist)\n elif root.left is None and root.right is not None:\n mylist.append(root.right.data)\n noSiblingHelper(root.right, mylist)\n if len(mylist) < 1:\n return -1\n return mylist\n\ndef noSibling(root):\n mylist = []\n ans = noSiblingHelper(root, mylist)\n x = []\n if ans == -1:\n x.append(-1)\n return x\n ans.sort()\n return ans", "def noSibling(root):\n out = []\n\n def traverse(root):\n if not root:\n return\n if root.left and (not root.right):\n out.append(root.left.data)\n if not root.left and root.right:\n out.append(root.right.data)\n traverse(root.left)\n traverse(root.right)\n traverse(root)\n return sorted(out) if out != [] else [-1]", "def noSibling(root):\n l = []\n\n def fun(root, l):\n if root is None:\n return\n if root.left is None and root.right is None:\n return\n if root.left is None and root.right is not None:\n l.append(root.right.data)\n fun(root.right, l)\n elif root.right is None and root.left is not None:\n l.append(root.left.data)\n fun(root.left, l)\n elif root.left is not None and root.right is not None:\n fun(root.left, l)\n fun(root.right, l)\n return l\n fun(root, l)\n if len(l) == 0:\n return [-1]\n return sorted(l)", "def noSibling(root):\n r = find(root, [])\n if r == []:\n return [-1]\n r.sort()\n return r\n\ndef find(root, res):\n if root == None:\n return res\n if root.left == None and root.right != None:\n res.append(root.right.data)\n if root.left != None and root.right == None:\n res.append(root.left.data)\n find(root.left, res)\n find(root.right, res)\n return res", "def noSibling(root):\n ans = []\n\n def preorder(root, ans):\n if root is None:\n return\n if root.left and root.right == None:\n ans.append(root.left.data)\n if root.right and root.left == None:\n ans.append(root.right.data)\n preorder(root.left, ans)\n preorder(root.right, ans)\n ans = []\n preorder(root, ans)\n ans.sort()\n if len(ans) == 0:\n return [-1]\n return ans", "def noSibling(root):\n ans = []\n\n def pre(root):\n if not root:\n return\n if root.right and (not root.left):\n ans.append(root.right.data)\n if not root.right and root.left:\n ans.append(root.left.data)\n pre(root.left)\n pre(root.right)\n pre(root)\n if len(ans) > 0:\n return sorted(ans)\n else:\n return [-1]", "def noSibling(root):\n\n def onlychild(root, v):\n if root is None:\n return\n onlychild(root.left, v)\n if root.left is None and root.right is not None:\n v.append(root.right.data)\n if root.left is not None and root.right is None:\n v.append(root.left.data)\n onlychild(root.right, v)\n v = []\n onlychild(root, v)\n v.sort()\n return v if len(v) > 0 else [-1]", "def noSibling(root):\n List = []\n\n def Transverse(root):\n if root == None:\n return\n if root.left == None and root.right != None:\n List.append(root.right.data)\n if root.left != None and root.right == None:\n List.append(root.left.data)\n Transverse(root.left)\n Transverse(root.right)\n Transverse(root)\n if List == []:\n return [-1]\n else:\n List.sort()\n return List", "def noSibling(root):\n ans = []\n if root == None:\n return [-1]\n queue = []\n queue.append(root)\n while len(queue) != 0:\n temp = queue.pop(0)\n if temp.left != None and temp.right == None:\n ans.append(temp.left.data)\n if temp.right != None and temp.left == None:\n ans.append(temp.right.data)\n if temp.left != None:\n queue.append(temp.left)\n if temp.right != None:\n queue.append(temp.right)\n if len(ans) == 0:\n return [-1]\n ans.sort()\n return ans", "def fun(root, l):\n if root == None:\n return\n elif root.left == None and root.right != None:\n l.append(root.right.data)\n elif root.left != None and root.right == None:\n l.append(root.left.data)\n fun(root.left, l)\n fun(root.right, l)\n\ndef noSibling(root):\n l = []\n fun(root, l)\n if len(l) == 0:\n l.append(-1)\n else:\n l.sort()\n return l", "def noSiblingUtil(root):\n global ans\n if root is None:\n return\n elif root.right is None and root.left is None:\n return\n elif root.left is None:\n ans.append(root.right.data)\n noSiblingUtil(root.right)\n elif root.right is None:\n ans.append(root.left.data)\n noSiblingUtil(root.left)\n else:\n noSiblingUtil(root.left)\n noSiblingUtil(root.right)\n return\n\ndef noSibling(root):\n global ans\n ans = []\n ans.clear()\n noSiblingUtil(root)\n if len(ans) == 0:\n ans.append(-1)\n ans.sort()\n return ans", "def noSibling(root):\n\n def no(root, l):\n if root == None:\n return l\n no(root.left, l)\n if root.left != None and root.right == None:\n l.append(root.left.data)\n if root.right != None and root.left == None:\n l.append(root.right.data)\n no(root.right, l)\n l = []\n no(root, l)\n l.sort()\n if len(l) == 0:\n return [-1]\n return l", "def paths(root, ans):\n if not root:\n return\n if root.left and (not root.right):\n ans.append(root.left.data)\n if not root.left and root.right:\n ans.append(root.right.data)\n paths(root.left, ans)\n paths(root.right, ans)\n return\n\ndef noSibling(root):\n ans = []\n paths(root, ans)\n if ans == []:\n return [-1]\n ans.sort()\n return ans", "def noSibling(root):\n res = []\n\n def helper(root):\n if root == None:\n return\n if root.left != None and root.right == None:\n res.append(root.left.data)\n if root.right != None and root.left == None:\n res.append(root.right.data)\n helper(root.left)\n helper(root.right)\n helper(root)\n res.sort()\n return res if len(res) > 0 else [-1]", "def noSibling(root):\n l = []\n\n def s(root):\n if root:\n if root.left and (not root.right):\n l.append(root.left.data)\n if not root.left and root.right:\n l.append(root.right.data)\n if root.left:\n s(root.left)\n if root.right:\n s(root.right)\n s(root.left)\n s(root.right)\n l.sort()\n if l:\n return l\n return [-1]\n return []", "def get(root, li):\n if not root:\n return\n if root.left and root.right:\n pass\n elif root.left:\n li.append(root.left.data)\n elif root.right:\n li.append(root.right.data)\n get(root.left, li)\n get(root.right, li)\n\ndef noSibling(root):\n li = []\n get(root, li)\n if len(li) == 0:\n return [-1]\n else:\n li.sort()\n return li", "def noSibling(root):\n res = []\n\n def dfs(node):\n if not node:\n return\n if node.left and (not node.right):\n res.append(node.left.data)\n elif node.right and (not node.left):\n res.append(node.right.data)\n dfs(node.left)\n dfs(node.right)\n dfs(root)\n res.sort()\n if res:\n return res\n return [-1]", "def noSibling(root):\n l = []\n if not root:\n return [-1]\n if root.left and root.right:\n l += noSibling(root.left)\n l += noSibling(root.right)\n elif root.left and (not root.right):\n l.append(root.left.data)\n l += noSibling(root.left)\n elif root.right and (not root.left):\n l.append(root.right.data)\n l += noSibling(root.right)\n if not l:\n return [-1]\n else:\n l.sort()\n for i in l:\n if i == -1:\n l.remove(-1)\n return l", "def noSibling(root):\n if root is None:\n return []\n (queue, a, k) = ([root], [], 0)\n while len(queue) > 0:\n k = len(queue)\n for _ in range(k):\n s = queue[0]\n if s.left and (not s.right):\n a.append(s.left.data)\n queue.append(s.left)\n if s.right and (not s.left):\n a.append(s.right.data)\n queue.append(s.right)\n if s.left and s.right:\n queue.append(s.left)\n queue.append(s.right)\n queue.pop(0)\n if len(a) == 0:\n return [-1]\n a.sort()\n return a", "def solve(root, lis):\n if root == None:\n return\n if root.left != None and root.right == None:\n lis.append(root.left.data)\n if root.left == None and root.right != None:\n lis.append(root.right.data)\n solve(root.left, lis)\n solve(root.right, lis)\n\ndef noSibling(root):\n lis = []\n k = root\n solve(root, lis)\n if not lis:\n return [-1]\n lis.sort()\n return lis", "def noSibling(root):\n q = [root]\n res = []\n while q:\n k = q.pop(0)\n if k.left and (not k.right):\n res.append(k.left.data)\n if not k.left and k.right:\n res.append(k.right.data)\n if k.right:\n q.append(k.right)\n if k.left:\n q.append(k.left)\n if not res:\n return [-1]\n res.sort()\n return res", "def noSibling(root):\n q = [root]\n res = []\n while q:\n l = len(q)\n for i in range(l):\n k = q.pop()\n if k.left and (not k.right):\n res.append(k.left.data)\n if not k.left and k.right:\n res.append(k.right.data)\n if k.right:\n q.append(k.right)\n if k.left:\n q.append(k.left)\n if not res:\n return [-1]\n res.sort()\n return res", "def noSibling(root):\n ans = []\n\n def help(root):\n if root == None:\n return\n if root.left and (not root.right):\n ans.append(root.left.data)\n if root.right and (not root.left):\n ans.append(root.right.data)\n help(root.left)\n help(root.right)\n help(root)\n return sorted(ans) if ans else [-1]", "def noSibling(root):\n ns = []\n\n def trav(r):\n if r.left is not None:\n if r.right is None:\n ns.append(r.left.data)\n trav(r.left)\n else:\n trav(r.left)\n if r.right is not None:\n if r.left is None:\n ns.append(r.right.data)\n trav(r.right)\n else:\n trav(r.right)\n trav(root)\n if len(ns) == 0:\n return [-1]\n return sorted(ns)"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["37\n / \n 20\n / \n 113", "1\n / \\\n 2 3"], "outputs": ["20 113", "-1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/print-all-nodes-that-dont-have-sibling/1", "Expected Auxiliary Space": "O(Height of the tree)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(NlogN)", "entry_point": "__init__", "task_id": "TACO_lite/513", "example": [[], []]} +{"requirement": "Given a Binary Tree of size N, You have to count leaves in it. For example, there are two leaves in following tree\n 1\n / \\\n 10 39\n /\n5\n \nExample 1:\nInput:\nGiven Tree is \n 4\n / \\\n 8 10\n / / \\\n 7 5 1\n /\n 3 \nOutput:\n3\nExplanation: \nThree leaves are 3 , 5 and 1.\n \nYour Task:\nYou don't have to take input. Complete the function countLeaves() that takes root node of the given tree as parameter and returns the count of leaves in tree. The printing is done by the driver code.\n \nConstraints:\n1<= N <= 10^{4}", "solutions": ["def countLeaves(root):\n i = 0\n\n def rec(root):\n nonlocal i\n if root:\n if root.left is None and root.right is None:\n i += 1\n rec(root.right)\n rec(root.left)\n rec(root)\n return i", "def countLeaves(root):\n if root is None:\n return 0\n if root.left is None and root.right is None:\n return 1\n else:\n return countLeaves(root.left) + countLeaves(root.right)", "def countLeaves(root):\n if root.left == None and root.right == None:\n return 1\n q = []\n q.append(root)\n ans = 0\n while len(q) > 0:\n top = q.pop(0)\n if top.left is not None:\n q.append(top.left)\n if top.right is not None:\n q.append(top.right)\n if top.left is None and top.right is None:\n ans += 1\n return ans", "def countLeaves(root):\n global ans\n ans = [0]\n\n def in_order(root):\n if root and root.left:\n in_order(root.left)\n if root and (not root.left) and (root.right == None):\n ans[0] = ans[0] + 1\n if root and root.right:\n in_order(root.right)\n return\n in_order(root)\n return ans[0]", "def countLeaves(root):\n if root == None:\n return 0\n if root.left == None and root.right == None:\n return 1\n return countLeaves(root.left) + countLeaves(root.right)", "def countLeaves(root):\n if not root:\n return 0\n if not root.left and (not root.right):\n return 1\n left = 0\n right = 0\n if root.left:\n left = countLeaves(root.left)\n if root.right:\n right = countLeaves(root.right)\n return left + right", "def countLeaves(root):\n count = 0\n if root is None:\n return 0\n elif root.left is None and root.right is None:\n count = 1\n return count + countLeaves(root.left) + countLeaves(root.right)", "def countLeaves(root):\n leaf = 0\n if root is None:\n return 0\n if root.left is None and root.right is None:\n leaf += 1\n lleaf = countLeaves(root.left)\n rleaf = countLeaves(root.right)\n return lleaf + rleaf + leaf", "def countLeaves(root):\n q = []\n q.append(root)\n count = 0\n while q:\n for x in range(0, len(q)):\n cur = q[0]\n q.remove(cur)\n if cur.left:\n q.append(cur.left)\n if cur.right:\n q.append(cur.right)\n if not cur.left and (not cur.right):\n count += 1\n return count", "def countLeaves(root):\n a = []\n leaves = 0\n\n def rec(root):\n nonlocal leaves\n if root:\n rec(root.left)\n a.append(root.data)\n if root.left == None and root.right == None:\n leaves += 1\n rec(root.right)\n rec(root)\n return leaves", "def countLeaves(root):\n queue = [root]\n ans = 0\n while queue:\n node = queue.pop(0)\n if not node.left and (not node.right):\n ans += 1\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return ans", "def countLeaves(root):\n\n def tree(node):\n if not node.right and (not node.left):\n return 1\n elif node.right and node.left:\n return tree(node.right) + tree(node.left)\n elif node.right:\n return tree(node.right)\n else:\n return tree(node.left)\n return tree(root)", "def countLeaves(root):\n leaf_nodes = 0\n\n def helper(root):\n if root is None:\n return 0\n left_nodes = helper(root.left)\n right_nodes = helper(root.right)\n if root.left is None and root.right is None:\n return 1\n return left_nodes + right_nodes\n return helper(root)", "def countLeaves(root):\n stack = [root]\n answer = 0\n while stack:\n node = stack.pop()\n if node.right:\n stack.append(node.right)\n if node.left:\n stack.append(node.left)\n if not node.right and (not node.left):\n answer += 1\n return answer", "def count(root, res):\n if root is None:\n return\n if root.left is None and root.right is None:\n res.append(root.data)\n if root:\n count(root.left, res)\n count(root.right, res)\n\ndef countLeaves(root):\n res = []\n count(root, res)\n return len(res)", "def cl(root):\n if root == None:\n return\n global h\n if root.left == None and root.right == None:\n h += 1\n cl(root.left)\n cl(root.right)\n\ndef countLeaves(root):\n if root == None:\n return 0\n if root.left == None and root.right == None:\n return 1\n return countLeaves(root.left) + countLeaves(root.right)", "def traverseLeaves(root, count):\n if root == None:\n return count\n if root.left == None and root.right == None:\n return count + 1\n count = traverseLeaves(root.left, count)\n count = traverseLeaves(root.right, count)\n return count\n\ndef countLeaves(root):\n if root == None:\n return 0\n return traverseLeaves(root, 0)", "def countLeaves(root):\n if root == None:\n return 0\n l = countLeaves(root.left)\n r = countLeaves(root.right)\n if root.left == None and root.right == None:\n return l + r + 1\n else:\n return l + r", "def countLeaves(root):\n count = 0\n flagLeft = False\n flagRight = False\n if not root.left == None:\n count += countLeaves(root.left)\n else:\n flagLeft = True\n if not root.right == None:\n count += countLeaves(root.right)\n else:\n flagRight = True\n if flagLeft and flagRight:\n count += 1\n return count", "def countLeaves(root):\n\n def dfs(node):\n if not node:\n return 0\n if not (node.left or node.right):\n return 1\n return dfs(node.left) + dfs(node.right)\n return dfs(root)", "def countLeaves(root):\n if not root:\n return 0\n if not (root.left or root.right):\n return 1\n return countLeaves(root.left) + countLeaves(root.right)", "count = 0\n\ndef countLeaves(root):\n if not root:\n return 0\n elif not root.left and (not root.right):\n return 1\n else:\n return countLeaves(root.right) + countLeaves(root.left)", "def countLeaves(root):\n return __countLeaves(root)\n\ndef __countLeaves(node):\n if node == None:\n return 0\n if node.right == None and node.left == None:\n return 1\n return __countLeaves(node.right) + __countLeaves(node.left)", "def countLeaves(root):\n count = [0]\n\n def counting(node):\n if not node.left and (not node.right):\n count[0] += 1\n return\n if node.left:\n counting(node.left)\n if node.right:\n counting(node.right)\n counting(root)\n return count[0]", "def countLeaves(root):\n\n def h(root):\n if not root:\n return 0\n if not root.left and (not root.right):\n return 1\n a = h(root.left)\n b = h(root.right)\n return a + b\n return h(root)", "def countLeaves(root):\n from collections import deque\n q = deque()\n q.append(root)\n count = 0\n while q:\n current = q.popleft()\n if current.left is None and current.right is None:\n count += 1\n if current.left:\n q.append(current.left)\n if current.right:\n q.append(current.right)\n return count", "def countLeaves(root):\n leaves_left = 0\n leaves_right = 0\n if root.left:\n leaves_left = countLeaves(root.left)\n if root.right:\n leaves_right = countLeaves(root.right)\n if not root.left and (not root.right):\n return 1\n return leaves_left + leaves_right", "def countLeaves(root):\n if root == None:\n return 0\n elif root.left == None and root.right == None:\n return 1\n else:\n ls = countLeaves(root.left)\n rs = countLeaves(root.right)\n return ls + rs", "def countLeaves(root):\n stack = [root]\n count = 0\n while stack:\n root = stack.pop()\n if not root.left and (not root.right):\n count += 1\n if root.right:\n stack.append(root.right)\n if root.left:\n stack.append(root.left)\n return count", "def countLeaves(root):\n if root.left == None and root.right == None:\n return 0\n global c\n c = 0\n\n def helper(root):\n global c\n if root == None:\n return\n if root.left == None and root.right == None:\n c += 1\n return\n helper(root.left)\n helper(root.right)\n helper(root)\n return c", "def fun(root, c):\n if root == None:\n return 0\n l = fun(root.left, c)\n r = fun(root.right, c)\n if l == 0 and r == 0:\n c.append(1)\n\ndef countLeaves(root):\n c = []\n fun(root, c)\n return sum(c)", "def countLeaves(root):\n level = [root]\n leaves = []\n while level:\n next = []\n for node in level:\n if node.right:\n next.append(node.right)\n if node.left:\n next.append(node.left)\n elif node.right == None:\n leaves.append(node)\n level = next\n return len(leaves)", "def countLeaves(root):\n tot = 0\n\n def count(node):\n nonlocal tot\n if node is None:\n return\n if not node.left and (not node.right):\n tot += 1\n count(node.left)\n count(node.right)\n count(root)\n return tot"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["Given Tree is \r\n 4\r\n / \\\r\n 8 10\r\n / / \\\r\n 7 5 1\r\n /\r\n 3"], "outputs": ["3"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-leaves-in-binary-tree/1", "Expected Auxiliary Space": "", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "", "entry_point": "__init__", "task_id": "TACO_lite/472", "example": [[], []]} +{"requirement": "Description:\n\n#Task:\n\nWrite a function that returns true if the number is a \"Very Even\" number.\n\nIf a number is a single digit, then it is simply \"Very Even\" if it itself is even.\n\nIf it has 2 or more digits, it is \"Very Even\" if the sum of it's digits is \"Very Even\".\n\n\n#Examples:\n```\ninput(88) => returns false -> 8 + 8 = 16 -> 1 + 6 = 7 => 7 is odd \n\ninput(222) => returns true\n\ninput(5) => returns false\n\ninput(841) => returns true -> 8 + 4 + 1 = 13 -> 1 + 3 => 4 is even\n```\n\nNote: The numbers will always be 0 or positive integers!", "solutions": ["def is_very_even_number(n):\n while len(str(n)) > 1:\n n = sum((int(x) for x in str(n)))\n return True if n % 2 == 0 else False", "def is_very_even_number(n):\n return n == 0 or (n - 1) % 9 % 2", "def is_very_even_number(n):\n if n < 10:\n return n % 2 == 0\n return is_very_even_number(sum((int(d) for d in str(n))))", "def get_sum(x):\n return sum((int(t) for t in list(str(x))))\n\ndef is_very_even_number(n):\n result = get_sum(n)\n while len(str(result)) >= 2:\n result = get_sum(result)\n return result % 2 == 0", "def is_very_even_number(n):\n return is_very_even_number(sum((int(i) for i in str(n)))) if n > 9 else not n % 2", "def is_very_even_number(n):\n while n >= 10:\n (p, n) = (n, 0)\n while p > 0:\n re = p % 10\n n += re\n p //= 10\n return n % 2 == 0", "def is_very_even_number(n):\n if len(str(n)) == 1:\n return n % 2 == 0\n return is_very_even_number(sum(map(int, list(str(n)))))", "def is_very_even_number(n):\n while n >= 10:\n n = sum(map(int, str(n)))\n return n % 2 == 0", "def is_very_even_number(n):\n if n < 10:\n return n % 2 == 0\n return is_very_even_number(sum(map(int, str(n))))", "def is_very_even_number(n):\n return True if not n else all((not n % 9 % 2, n % 9))"], "starter_code": "def is_very_even_number(n):\n", "input_output": {"fn_name": "is_very_even_number", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/58c9322bedb4235468000019", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_very_even_number", "task_id": "TACO_lite/535", "example": [[], []]} +{"requirement": "Given an integer, check whether it is Bleak or not. \nA number n is called Bleak if it can be represented as sum of a positive number x and set bit count in x, i.e., x + countSetBits(x) is not equal to n for any non-negative number x.\nExample 1:\nInput: 4\nOutput: 1\nExplanation: There is no any possible x\nsuch that x + countSetbit(x) = 4\nExample 2:\nInput: 3\nOutput: 0\nExplanation: 3 is a Bleak number as \n2 + countSetBit(2) = 3.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function is_bleak() which takes n as input parameter and returns 1 if n is not a Bleak number otherwise returns 0.\n \nExpected Time Complexity: O(log(n) * log(n))\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= n <= 10^{4}", "solutions": ["def count_set_bits(n):\n ret = 0\n while n:\n if n & 1:\n ret += 1\n n >>= 1\n return ret\n\ndef is_bleak(n):\n a = 0\n for j in range(14, -1, -1):\n if n > j:\n a = j\n break\n for m in range(n - a, n):\n if count_set_bits(m) + m == n:\n return 0\n return 1", "def is_bleak(n):\n for x in range(n):\n cb = bin(x).count('1')\n if x + cb == n:\n return 0\n return 1", "def is_bleak(n):\n if n in self.d:\n return 0\n return 1", "def is_bleak(n):\n from math import log2, ceil\n for i in range(1, ceil(log2(10 ** 4)) + 1):\n (v, cnt) = (n - i, 0)\n while v > 0:\n v &= v - 1\n cnt += 1\n if cnt == i:\n return 0\n return 1", "def is_bleak(n):\n\n def f(a):\n cnt = 0\n while a > 0:\n cnt += 1\n a = a & a - 1\n return cnt\n for i in range(n - 32, n):\n if f(i) + i == n:\n return 0\n return 1", "import re\n\ndef is_bleak(n):\n for i in range(n):\n bi = str(bin(i))\n no_of_1 = bi.count('1')\n if no_of_1 + i == n:\n return 0\n return 1", "def is_bleak(n):\n m = len(bin(n)[2:])\n for i in range(1, m + 1):\n if sum((item == '1' for item in bin(n - i)[2:])) == i:\n return 0\n return 1", "def countSetBits(x):\n count = 0\n while x:\n x = x & x - 1\n count = count + 1\n return count\n\ndef ceilLog2(x):\n count = 0\n x = x - 1\n while x > 0:\n x = x >> 1\n count = count + 1\n return count\n\ndef is_bleak(n):\n for x in range(n - self.ceilLog2(n), n):\n if x + self.countSetBits(x) == n:\n return 0\n return 1", "from math import log, ceil\n\ndef countset(x):\n count = 0\n while x:\n x = x & x - 1\n count = count + 1\n return count\n\ndef is_bleak(n):\n cei = ceil(log(n, 2))\n for i in range(n - cei, n):\n if i + countset(i) == n:\n return 0\n return 1", "from math import log\n\ndef count(n):\n c = 0\n while n:\n c += 1\n n &= n - 1\n return c\n\ndef is_bleak(n):\n cn = n - len(bin(n)[2:])\n for x in range(cn, n + 1):\n if x + self.count(x) == n:\n return 0\n return 1", "def is_bleak(n):\n for i in range(1, n):\n x = bin(i)[2:].count('1')\n if i + x == n:\n return 0\n return 1", "import math\n\ndef is_bleak(n):\n count = 0\n tmp = n\n while n > 0:\n n >>= 1\n count += 1\n i = tmp - count\n while i < tmp:\n if i + self.countbits(i) == tmp:\n return 0\n i += 1\n return 1\n\ndef countbits(n):\n count = 0\n while n > 0:\n n = n & n - 1\n count += 1\n return count", "def is_bleak(n):\n for i in range(n - 32, n, 1):\n if i > 0 and n - i > 0 and (bin(i).count('1') == n - i):\n return 0\n return 1", "def setb(n):\n return bin(n).count('1')\n\ndef is_bleak(n):\n for i in range(1, n):\n if i + setb(i) == n:\n return 0\n return 1", "def countSetBits(num):\n count = 0\n while num > 0:\n mask = num - 1\n num &= mask\n count += 1\n return count\n\ndef is_bleak(n):\n for ele in range(n):\n if ele + countSetBits(ele) == n:\n return 0\n else:\n return 1", "def total_bits(m):\n res = 0\n while m:\n res += 1\n m //= 2\n return res\n\ndef set_bits(m):\n res = 0\n while m:\n res += m % 2\n m //= 2\n return res\n\ndef is_bleak(n):\n for num in range(max(n - self.total_bits(n), 1), n):\n if num + self.set_bits(num) == n:\n return 0\n return 1", "def is_bleak(n):\n dp = [0] * (n + 1)\n for i in range(1, n):\n if i % 2:\n dp[i] = dp[i - 1] + 1\n else:\n dp[i] = dp[i // 2]\n if i + dp[i] == n:\n return 0\n return 1", "from collections import Counter\n\ndef is_bleak(n):\n for i in range(n):\n if bin(i).count('1') + i == n:\n return 0\n return 1", "def is_bleak(n):\n for d in range(n // 2, n):\n count = 0\n x = d\n while d > 0:\n if d & (d & -d) > 0:\n count += 1\n d = d - (d & -d)\n if x + count == n:\n return 0\n return 1", "def countBits(n):\n c = 0\n while n:\n n &= n - 1\n c += 1\n return c\n\ndef is_bleak(n):\n for i in range(n - 1, 0, -1):\n if i + self.countBits(i) == n:\n return 0\n return 1", "def count_set_bits(x):\n set_bits = 0\n while x:\n set_bits += 1\n x = x & x - 1\n return set_bits\n\ndef is_bleak(n):\n x = max(1, n - self.num_bits)\n while x < n:\n if x + self.count_set_bits(x) == n:\n return 0\n x += 1\n return 1", "def count_set(x):\n count = 0\n while x:\n count += x & 1\n x >>= 1\n return count\n\ndef is_bleak(n):\n for i in range(n, 0, -1):\n if i + self.count_set(i) == n:\n return 0\n return 1", "def is_bleak(n):\n for _ in range(n):\n flag = 0\n if n > 14:\n s = n - 14\n else:\n s = 1\n for i in range(s, n):\n if i + bin(i)[2:].count('1') == n:\n flag = 1\n break\n if flag:\n return 0\n else:\n return 1", "def is_bleak(n):\n c = 1\n for i in range(n):\n if i + bin(i).count('1') == n:\n c = 0\n break\n return c", "def setBits(N):\n cnt = 0\n while N != 0:\n N = N & N - 1\n cnt += 1\n return cnt\n\ndef is_bleak(n):\n for i in range(1, n):\n b = self.setBits(i) + i\n if b == n:\n return 0\n return 1", "def is_bleak(n):\n dp = [0] * (10 ** 4 + 1)\n dp[1] = 1\n dp[2] = 1\n dp[3] = 2\n for i in range(n):\n dp[i] = dp[i // 2]\n if i % 2:\n dp[i] += 1\n for i in range(n):\n if i + dp[i] == n:\n return 0\n return 1", "import math\n\ndef countSetBits(x):\n bi = bin(x)[2:]\n bi = [int(x) for x in str(bi)]\n ones = bi.count(1)\n return ones\n\ndef ceilLog2(x):\n count = 0\n x -= 1\n while x > 0:\n x = x >> 1\n count += 1\n return count\n\ndef is_bleak(n):\n for x in range(n - self.ceilLog2(n), n):\n if x + self.countSetBits(x) == n:\n return 0\n return 1", "def countSetBits(x):\n k = bin(x).replace('b', '')\n return k.count('1')\n\ndef is_bleak(n):\n for x in range(n):\n if self.countSetBits(x) + x == n:\n return 0\n return 1", "def is_bleak(n):\n z = n\n c = 0\n while z > 0:\n z = z // 2\n c = c + 1\n mina = n - c\n for i in range(n - c, n):\n z = i\n sb = 0\n while z > 0:\n a = z % 2\n z = z // 2\n if a == 1:\n sb = sb + 1\n if sb + i == n:\n return 0\n return 1", "def csb(n):\n b = bin(n).replace('b', '')\n return b.count('1')\n\ndef is_bleak(n):\n if n == 1:\n return 1\n for i in range(n):\n if i + csb(i) == n:\n return 0\n return 1", "def is_bleak(n):\n for i in range(n - 1, 0, -1):\n if i + self.count(i) == n:\n return 0\n return 1\n\ndef count(n):\n cont = 0\n while n:\n cont += n & 1\n n >>= 1\n return cont", "def is_bleak(n):\n for i in range(n - 1, 0, -1):\n c = 0\n t = i\n while t > 0:\n t = t & t - 1\n c += 1\n x1 = c\n if n == x1 + i:\n return 0\n return 1", "def setbit(i):\n c = 0\n while i:\n i = i & i - 1\n c += 1\n return c\n\ndef is_bleak(n):\n for j in range(n - 1, 0, -1):\n a = self.setbit(j)\n if n - a == j:\n return 0\n return 1", "def countSetBits(n):\n if self.table[n] != -1:\n return self.table[n]\n set_bits = 0\n while n:\n if n & 1:\n set_bits += 1\n n = n >> 1\n self.table[n] = set_bits\n return set_bits\n\ndef is_bleak(n):\n for i in range(n - 1, 0, -1):\n set_bits = 0\n if self.table[i] != -1:\n set_bits = self.table[i]\n else:\n y = i\n while y:\n if y & 1:\n set_bits += 1\n y = y >> 1\n self.table[y] = set_bits\n if i + set_bits == n:\n return 0\n return 1", "def is_bleak(n):\n a = 1\n i = 1\n while a < n:\n a *= 2\n i += 1\n for x in range(n - i, n):\n if x + self.countSetBits(x) == n:\n return 0\n return 1\n\ndef countSetBits(x):\n count = 0\n while x > 0:\n x &= x - 1\n count += 1\n return count", "def is_bleak(n):\n low = 0\n high = n\n for i in range(n, 0, -1):\n count = 0\n mask = 1\n num = i\n while num:\n if num & mask == 1:\n count += 1\n num >>= 1\n if i + count == n:\n return 0\n else:\n return 1", "def is_bleak(n):\n\n def findBits(x):\n cnt = 0\n while x:\n x = x & x - 1\n cnt += 1\n return cnt\n for i in range(1, n + 1):\n if i + findBits(i) == n:\n return 0\n return 1", "def is_bleak(n):\n (l, r) = (1, n)\n for i in range(1, n + 1):\n if i + self.countSetBits(i) == n:\n return 0\n return 1\n\ndef countSetBits(num):\n cnt = 0\n while num != 0:\n num = num & num - 1\n cnt += 1\n return cnt", "def is_bleak(n):\n\n def countSetbit(n):\n count = 0\n while n:\n count += n & 1\n n >>= 1\n return count\n a = n - 17\n m = 1\n for i in range(a, n):\n if i > 0 and i + countSetbit(i) == n:\n m = 0\n break\n return m", "import math\n\ndef countSetBits(x):\n r = str(format(x, 'b')).count('1')\n return r\n\ndef is_bleak(n):\n for i in range(1, n):\n if i + countSetBits(i) == n:\n return 0\n return 1", "def is_bleak(n):\n if n == 1:\n return 1\n else:\n for i in range(n - 1, 0, -1):\n t = i\n count = 0\n while t > 0:\n t = t & t - 1\n count = count + 1\n if count + i == n:\n return 0\n return 1", "import math\n\ndef set_bits(abc, num):\n count = 0\n while num > 0:\n if num % 2 == 1:\n count += 1\n num >>= 1\n return count\n\ndef is_bleak(n):\n check = math.ceil(math.log(n, 2))\n for i in range(n - check, n):\n if i + Solution().set_bits(i) == n:\n return 0\n return 1", "def check(x):\n cnt = 0\n while x:\n x = x & x - 1\n cnt += 1\n return cnt\n\ndef is_bleak(n):\n if n == 1:\n return 1\n ans = 1\n for i in range(1, n):\n if i + self.check(i) == n:\n ans = 0\n break\n return ans", "def is_bleak(n):\n flag = 1\n for i in range(n, 0, -1):\n b = self.setbit(i) + i\n if b == n:\n flag = 0\n break\n return flag\n\ndef setbit(n):\n count = 0\n while n > 0:\n if n & 1:\n count += 1\n n = n >> 1\n return count", "def is_bleak(n):\n for i in range(1, n + 1):\n x = i\n z = bin(i).replace('0b', '')\n x1 = z.count('1')\n if int(x1) + x == n:\n return 0\n else:\n return 1", "def set_bits(n):\n bin_num = bin(n).replace('Ob', '')\n set_bits = str(bin_num).count('1')\n return set_bits\n\ndef is_bleak(n):\n for i in range(n):\n if i + self.set_bits(i) == n:\n return 0\n return 1", "def sol(num):\n ans = 0\n while num:\n num = num & num - 1\n ans = ans + 1\n return ans\n\ndef is_bleak(n):\n for i in range(1, n):\n if i + self.sol(i) == n:\n return 0\n return 1", "def is_bleak(n):\n\n def countSetbit(mid):\n count = 0\n while mid:\n mid = mid & mid - 1\n count += 1\n return count\n for i in range(1, n):\n count = countSetbit(i)\n if count + i == n:\n return 0\n return 1"], "starter_code": "def is_bleak(n):\n", "input_output": {"inputs": ["4", "3"], "outputs": ["1", "0"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/bleak-numbers1552/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(n) * log(n))", "entry_point": "is_bleak", "task_id": "TACO_lite/477", "example": [[[4], [3]], ["1", "0"]]} +{"requirement": "Convert a given string to its cross string (i.e Diagonal from left-right and from right-left). \nSee examples for better understanding.\n \nExample 1:\nInput:\nabc\nOutput:\na c b a c\nExplanation:\nThe above is the proper \ncross manner for the \ntest case.\na c\n b \na c\nExample 2:\nInput:\ngeeks\nOutput:\ng s e k e e k g s\nExplanation:\nFor the 1st test case where \nthe string is geeks\nG S\n E K\n E\n E K\nG S\nThe above is the proper cross \nthe manner for the test case, but \nwhen printed in a single line \nit becomes as shown in the output.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function crossPattern() which takes the string S and returns a single string in the following way first-line output of the string concatenated with 2nd line and so on till the Nth line.\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 ≤ length of string ≤ 1000", "solutions": ["def crosspattern(ob, S):\n start = ''\n end = ''\n n = len(S)\n for i in range(n // 2):\n row = i * ' ' + S[i] + (n - 2 * (i + 1)) * ' ' + S[-i - 1] + i * ' '\n start += row\n end = row + end\n if n % 2:\n start += n // 2 * ' ' + S[n // 2] + n // 2 * ' '\n return start + end", "def crosspattern(ob, S):\n len1 = len(S)\n ans = ''\n for i in range(0, len1):\n j = len1 - 1 - i\n for k in range(0, len1):\n if k == i or k == j:\n ans += S[k]\n else:\n ans += ' '\n return ans", "import math\n\ndef crosspattern(ob, S):\n result = []\n s = S\n size = len(s)\n iterate = math.ceil(size / 2)\n for i in range(iterate):\n result.append(' ' * i)\n result.append(s[i])\n result.append(' ' * (size - i - 1 - i - 1))\n if i != size - i - 1:\n result.append(s[size - i - 1])\n result.append(' ' * i)\n else:\n result.append(' ' * i)\n if size % 2 != 0:\n iterate = iterate - 1\n for i in reversed(range(iterate)):\n result.append(' ' * i)\n result.append(s[i])\n result.append(' ' * (size - i - 1 - i - 1))\n if i != size - i - 1:\n result.append(s[size - i - 1])\n result.append(' ' * i)\n else:\n result.append(' ' * i)\n return ''.join(result)", "def crosspattern(ob, S):\n start = 0\n end = len(S) - 1\n ans = []\n for i in range(len(S)):\n for j in range(len(S)):\n if j == start:\n ans.append(S[start])\n elif j == end:\n ans.append(S[j])\n else:\n ans.append(' ')\n start += 1\n end -= 1\n return ''.join(ans)", "def crosspattern(ob, S):\n i = 0\n n = len(S)\n t = ''\n while i < n:\n l = [' ' for j in range(n)]\n l[i] = S[i]\n l[n - 1 - i] = S[n - 1 - i]\n t += ''.join(l)\n i += 1\n return t", "def crosspattern(ob, ip):\n s = ''\n for i in range(len(ip)):\n result = ''\n for j in range(len(ip)):\n if i == j:\n result = result + ip[i]\n elif j == len(ip) - i - 1:\n result = result + ip[j]\n else:\n result = result + ' '\n s += result\n return s", "def crosspattern(ob, s):\n a = ''\n for i in range(len(s)):\n for j in range(len(s)):\n if i == j or i + j == len(S) - 1:\n a = a + s[j]\n else:\n a = a + ' '\n return a", "def crosspattern(ob, S):\n n = len(S)\n t = ''\n m = [[' ' for j in range(n)] for i in range(n)]\n l = 0\n h = n - 1\n for i in range(n):\n for j in range(n):\n if i == j:\n m[i][j] = S[l]\n l += 1\n if i + j + 1 == n:\n m[i][j] = S[h]\n h -= 1\n for i in range(n):\n for j in range(n):\n t += m[i][j]\n return t", "def crosspattern(ob, S):\n string = ''\n for i in range(0, len(S)):\n for j in range(0, len(S)):\n if i == j or i + j == len(S) - 1:\n string += S[j]\n else:\n string += ' '\n return string", "def crosspattern(ob, S):\n dp = [[' ' for i in range(len(S))] for j in range(len(S))]\n for i in range(len(S)):\n dp[i][i] = S[i]\n (start, end) = (len(S) - 1, 0)\n while start != -1 and end != len(S):\n dp[start][end] = S[end]\n end += 1\n start -= 1\n ans = ''\n for i in dp:\n ans += ''.join(i)\n return ans", "def crosspattern(ob, S):\n l = []\n for i in range(1, len(S) + 1):\n for j in range(1, len(S) + 1):\n if i == j or i + j == len(S) + 1:\n l.append(S[j - 1])\n else:\n l.append(' ')\n return ''.join(l)", "def crosspattern(ob, S):\n n = len(S)\n res = ''\n for i in range(n):\n for j in range(n):\n if i == j or i + j == n - 1:\n res += S[j]\n else:\n res += ' '\n return res", "def crosspattern(ob, s):\n n = len(s)\n res = [[' '] * n for i in range(n)]\n ans = ''\n for i in range(n):\n res[i][i] = res[n - 1 - i][i] = s[i]\n for i in res:\n ans += ''.join(i)\n return ans", "def crosspattern(ob, s):\n n = len(s)\n m = ''\n for i in range(n):\n for j in range(n):\n if i == j:\n m += s[i]\n elif i + j == n - 1:\n m += s[j]\n else:\n m += ' '\n return m", "def crosspattern(o, S):\n ans = ''\n n = len(S)\n for i in range(n):\n j = n - 1 - i\n for k in range(n):\n if k == i or k == j:\n ans += S[k]\n else:\n ans += ' '\n return ans", "def crosspattern(ob, S):\n n = len(S)\n l = [' '] * n * n\n st1 = 0\n st2 = n - 1\n ind1 = 0\n ind2 = n - 1\n for i in range(n * n):\n if i == st1:\n l[i] = S[ind1]\n st1 += n + 1\n ind1 += 1\n if i == st2:\n l[i] = S[ind2]\n st2 += n - 1\n ind2 -= 1\n x = ''\n for i in l:\n x = x + i\n return x", "def crosspattern(ob, s):\n n = len(s)\n a = ''\n x = 0\n for i in range(n):\n for j in range(n):\n if i == j or i + j == n - 1:\n a += s[j]\n else:\n a += ' '\n return a", "def crosspattern(ob, S):\n n = len(S)\n m = 2 * n - 1\n res = ''\n x = 0\n for i in range(n):\n for j in range(n):\n if i == j or i + j == n - 1:\n res += S[j]\n else:\n res += ' '\n return res", "def crosspattern(ob, S):\n n = len(S)\n st = ''\n for row in range(n):\n for col in range(n):\n if row == col or row + col == n - 1:\n st = st + S[col]\n else:\n st = st + ' '\n return st", "def crosspattern(ob, S):\n n = len(S)\n a = []\n for i in range(n):\n k = []\n for j in range(n):\n s = ' '\n k.append(s)\n a.append(k)\n j = 0\n k = 0\n kk = n - 1\n p = n - 1\n for i in range(n):\n if i == j:\n a[i][j] = S[k]\n a[i][p] = S[kk]\n p -= 1\n k += 1\n j += 1\n kk -= 1\n res = ''\n for i in range(n):\n for j in range(n):\n res += a[i][j]\n return res"], "starter_code": "def crosspattern (ob,S):\n", "input_output": {"inputs": ["abc", "geeks"], "outputs": ["a c b a c", "g s e k e e k g s"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/cross-character2630/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "crosspattern", "task_id": "TACO_lite/486", "example": [[["abc"], ["geeks"]], ["a c b a c", "g s e k e e k g s"]]} +{"requirement": "Anuj has challenged Arun to climb N stairs but at only in powers of P and Q. Now Arun being a lazy guy wants to do this in minimum number of steps possible. So he has asked for your help to calculate the minimum number of steps he requires to take for climbing N stairs ( 1 step = some power of P or Q stairs (including zeroth power) ).\nExample 1:\nInput: \nN = 15, P = 2, Q = 3\nOutput:\n3\nExplanation:\nWe can make 15 by (8,4,3)\nor (9,3,3) both takes 3 steps.\n \nExample 2:\nInput: \nN = 19, P = 4, Q = 3\nOutput:\n2\nExplanation:\nIn the second case, we can make\n19 by (16,3) which is 2 steps.\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function moves() which takes three integers N, P and Q as inputs and returns the number of steps that Arun needs to take to climb N stairs in powers of P & Q. If fit is not possible print -1.\n \nExpected Time Complexity: O(N. log(N))\nExpected Auxiliary Space: O(N. log(N))\n \nConstraints:\n1 ≤ N, P, Q ≤ 10^{5}", "solutions": ["from math import log\n\ndef moves(n, p, q):\n if p == 1 and q == 1:\n return n\n if p == 1:\n p = q\n if q == 1:\n q = p\n setti = set([n])\n count = 0\n while 0 not in setti:\n new = set()\n for item in setti:\n new.add(item - p ** int(log(item, p)))\n new.add(item - q ** int(log(item, q)))\n setti = new\n count += 1\n return count", "def moves(n, p, q):\n\n def checker(n, p, dp):\n mul = 1\n if p == 1:\n return n\n ans = float('inf')\n while n - mul >= 0:\n ans = min(ans, dp[n - mul] + 1)\n mul = mul * p\n return ans\n dp = [float('inf')] * (n + 1)\n dp[0] = 0\n for i in range(1, n + 1):\n step1 = checker(i, p, dp)\n step2 = checker(i, q, dp)\n dp[i] = min(step1, step2)\n return dp[n]", "def moves(n, p, q):\n arr = [0] * (n + 1)\n arr[0] = 0\n\n def func(n, p, arr):\n a = 1\n ans = float('inf')\n if p == 1:\n return n\n while n - a >= 0:\n ans = min(ans, arr[n - a])\n a = a * p\n return ans + 1\n for i in range(1, n + 1):\n s1 = func(i, p, arr)\n s2 = func(i, q, arr)\n arr[i] = min(s1, s2)\n return arr[n]", "import math\nimport sys\nsys.setrecursionlimit(2000)\n\ndef moves(n, p, q):\n if q == 1 and p == 1:\n return n\n elif q == 1:\n q = p\n elif p == 1:\n p = q\n dp = [float('inf') for i in range(n + 1)]\n dp[0] = 0\n for i in range(1, n + 1):\n powerQ = pow(q, int(math.log(i, q)))\n powerP = pow(p, int(math.log(i, p)))\n dp[i] = min(dp[i - powerQ], dp[i - powerP]) + 1\n return dp[n]", "def moves(n, p, q):\n dp = [999999 for i in range(n + 1)]\n dp[0] = 0\n for i in range(1, n + 1):\n j = 0\n while i - pow(p, j) >= 0 and p != 1:\n dp[i] = min(dp[i], dp[i - pow(p, j)] + 1)\n j += 1\n j = 0\n while i - pow(q, j) >= 0 and q != 1:\n dp[i] = min(dp[i], dp[i - pow(q, j)] + 1)\n j += 1\n if p == 1 or q == 1:\n dp[i] = min(dp[i], dp[i - 1] + 1)\n return dp[n]", "def moves(N, A, B):\n import math\n power_list = []\n na = 1\n nb = 1\n if A == 1:\n power_list.append(A)\n else:\n for i in range(1 + int(math.log(N, A))):\n power_list.append(A ** i)\n if B == 1:\n power_list.append(B)\n else:\n for i in range(1 + int(math.log(N, B))):\n power_list.append(B ** i)\n M = [float('inf') for _ in range(N + 1)]\n M[0] = 0\n for i in range(1, len(M)):\n if i in power_list:\n M[i] = 1\n continue\n if i < min(power_list):\n M[i] = -1\n continue\n mid = i // 2\n for x in power_list:\n if i > x:\n temp = 1 + M[i - x]\n M[i] = min(temp, M[i])\n return M[N]"], "starter_code": "def moves(n, p, q):\n", "input_output": {"inputs": ["N = 15, P = 2, Q = 3", "N = 19, P = 4, Q = 3"], "outputs": ["3", "2"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays", "Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/minimum-steps1159/1", "Expected Auxiliary Space": "O(N. log(N))", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N. log(N))", "entry_point": "moves", "task_id": "TACO_lite/539", "example": [[[15, 2, 3], [19, 4, 3]], ["3", "2"]]} +{"requirement": "Given a list of integers, return the nth smallest integer in the list. **Only distinct elements should be considered** when calculating the answer. `n` will always be positive (`n > 0`)\n\nIf the nth small integer doesn't exist, return `-1` (C++) / `None` (Python) / `nil` (Ruby) / `null` (JavaScript).\n\nNotes:\n* \"indexing\" starts from 1\n* huge lists (of 1 million elements) will be tested\n\n## Examples\n\n```python\nnth_smallest([1, 3, 4, 5], 7) ==> None # n is more than the size of the list\nnth_smallest([4, 3, 4, 5], 4) ==> None # 4th smallest integer doesn't exist\nnth_smallest([45, -10, 4, 5, 4], 4) ==> 45 # 4th smallest integer is 45\n```\n\nIf you get a timeout, just try to resubmit your solution. However, if you ***always*** get a timeout, review your code.", "solutions": ["def nth_smallest(arr, n):\n s = set(arr)\n return sorted(s)[n - 1] if n <= len(s) else None", "def nth_smallest(arr, n):\n try:\n return sorted(set(arr))[n - 1]\n except:\n pass", "import random\n\ndef partition(vector, left, right, pivotIndex):\n pivotValue = vector[pivotIndex]\n (vector[pivotIndex], vector[right]) = (vector[right], vector[pivotIndex])\n storeIndex = left\n for i in range(left, right):\n if vector[i] < pivotValue:\n (vector[storeIndex], vector[i]) = (vector[i], vector[storeIndex])\n storeIndex += 1\n (vector[right], vector[storeIndex]) = (vector[storeIndex], vector[right])\n return storeIndex\n\ndef select(vector, left, right, k):\n if k < len(vector):\n while True:\n pivotIndex = random.randint(left, right)\n pivotNewIndex = partition(vector, left, right, pivotIndex)\n pivotDist = pivotNewIndex - left\n if pivotDist == k:\n return vector[pivotNewIndex]\n elif k < pivotDist:\n right = pivotNewIndex - 1\n else:\n k -= pivotDist + 1\n left = pivotNewIndex + 1\n\ndef nth_smallest(arr, n):\n unique = list(set(arr))\n return select(unique, 0, len(unique) - 1, n - 1)", "def nth_smallest(arr, k):\n if len(set(arr)) == 1:\n return arr[0]\n elif len(set(arr)) < k:\n return None\n pivot = arr[0]\n lesser = list(set([x for x in arr[1:] if x < pivot]))\n greater = list(set([x for x in arr[1:] if x > pivot]))\n if len(lesser) >= k:\n return nth_smallest(lesser, k)\n elif len(lesser) == k - 1:\n return pivot\n else:\n return nth_smallest(greater, k - len(lesser) - 1)", "def nth_smallest(arr, n):\n s = set(arr)\n if n <= len(s):\n return sorted(s)[n - 1]", "from heapq import *\n\ndef nth_smallest(arr, n):\n arr = list(set(arr))\n heapify(arr)\n if n > len(arr):\n return None\n x = 0\n for i in range(n):\n x = heappop(arr)\n return x", "def nth_smallest(arr, n):\n x = list(dict.fromkeys(arr))\n x.sort(key=int)\n return None if n > len(x) else x[n - 1]", "nth_smallest = lambda a, n: None if len(set(a)) < n else list(sorted(set(a)))[n - 1]", "def nth_smallest(arr, n):\n sorted_arr = sorted(set(arr))\n if n <= len(sorted_arr):\n return sorted_arr[n - 1]", "def nth_smallest(arr, n):\n arr = sorted(list(set(arr)))\n if n > len(arr):\n return None\n return arr[n - 1]"], "starter_code": "def nth_smallest(arr, n):\n", "input_output": {"fn_name": "nth_smallest", "inputs": [[[14, 12, 46, 34, 334], 3], [[4000], 1], [[14, 12, 46, 0, 334], 1]], "outputs": [[34], [4000], [0]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/57a03b8872292dd851000069", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "nth_smallest", "task_id": "TACO_lite/489", "example": [[[[1, 3, 4, 5], 7], [[4, 3, 4, 5], 4], [[45, -10, 4, 5, 4], 4]], ["None", "None", "45"]]} +{"requirement": "You are given an integer array nums. The value of this array is defined as the sum of |nums[i]-nums[i+1]| for all 0 <= i < nums.length-1.\nYou are allowed to select any subarray of the given array and reverse it. You can perform this operation only once.\nFind maximum possible value of the final array.\n \nExample 1:\nInput: nums = [2,3,1,5,4]\nOutput: 10\nExplanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.\n\nExample 2:\nInput: nums = [2,4,9,24,2,1,10]\nOutput: 68\n\n \nConstraints:\n\n1 <= nums.length <= 3*10^4\n-10^5 <= nums[i] <= 10^5", "solutions": ["def switch(nums, i, j, base=0):\n i_inc = abs(nums[j] - nums[i - 1]) - abs(nums[i] - nums[i - 1]) if i > 0 else 0\n j_inc = abs(nums[j + 1] - nums[i]) - abs(nums[j + 1] - nums[j]) if j < len(nums) - 1 else 0\n return base + i_inc + j_inc\n\ndef options(inds, nums):\n (a, b) = findRange(inds)\n (d, c) = findRange(inds[::-1])\n yield 0\n yield (2 * (nums[c] - nums[b]))\n i = max(a, b)\n j = max(c, d)\n n = len(nums)\n yield switch(nums, i, n - 1)\n yield switch(nums, j, n - 1)\n yield switch(nums, 0, i - 1)\n yield switch(nums, 0, j - 1)\n\ndef findRange(inds):\n seen = set()\n for (i, idx) in enumerate(inds):\n if idx + 1 in seen or idx - 1 in seen:\n return (idx + 1, idx) if idx + 1 in seen else (idx - 1, idx)\n seen.add(idx)\n\ndef maxvalueafterreverse(nums: List[int]) -> int:\n n = len(nums)\n base = sum([abs(nums[i] - nums[i + 1]) for i in range(n - 1)])\n if n <= 2:\n return base\n inds = sorted(list(range(n)), key=lambda x: nums[x])\n return base + max(options(inds, nums))", "def maxvalueafterreverse(nums: List[int]) -> int:\n n = len(nums)\n s = 0\n gain = 0\n h = float('-inf')\n l = float('inf')\n for i in range(n - 1):\n n1 = nums[i]\n n2 = nums[i + 1]\n s += abs(n1 - n2)\n gain = max(gain, abs(nums[0] - n2) - abs(n1 - n2), abs(nums[n - 1] - n1) - abs(n1 - n2))\n h = max(h, min(n1, n2))\n l = min(l, max(n1, n2))\n return s + max(gain, 2 * (h - l))", "def maxvalueafterreverse(nums: List[int]) -> int:\n vals = [0] * (len(nums) - 1)\n for (i, n) in enumerate(nums[1:]):\n vals[i] = abs(n - nums[i])\n base = sum(vals)\n bonus = 0\n MPP = max((nums[L] + nums[L + 1] - vals[L] for L in range(len(nums) - 1)))\n MPN = max((nums[L] - nums[L + 1] - vals[L] for L in range(len(nums) - 1)))\n MNP = max((-nums[L] + nums[L + 1] - vals[L] for L in range(len(nums) - 1)))\n MNN = max((-nums[L] - nums[L + 1] - vals[L] for L in range(len(nums) - 1)))\n bonus = max(MPP + MNN, MPN + MNP)\n for R in range(0, len(nums) - 1):\n bonus = max(bonus, abs(nums[0] - nums[R + 1]) - vals[R])\n for L in range(1, len(nums) - 1):\n bonus = max(bonus, abs(nums[L - 1] - nums[len(nums) - 1]) - vals[L - 1])\n return base + bonus", "def maxvalueafterreverse(nums: List[int]) -> int:\n numsLen = len(nums)\n oldSum = sum([abs(nums[i] - nums[i + 1]) for i in range(numsLen - 1)])\n if numsLen < 3:\n return oldSum\n delta = 0\n for i in range(1, numsLen - 1):\n delta = max(delta, abs(nums[i + 1] - nums[0]) - abs(nums[i + 1] - nums[i]), abs(nums[-1] - nums[i - 1]) - abs(nums[i] - nums[i - 1]))\n high = float('-inf')\n low = float('inf')\n for (x, y) in zip(nums, nums[1:]):\n high = max(high, min(x, y))\n low = min(low, max(x, y))\n return oldSum + max(delta, (high - low) * 2)", "def maxvalueafterreverse(nums: List[int]) -> int:\n ans = sum((abs(nums[i + 1] - nums[i]) for i in range(len(nums) - 1)))\n d = 0\n for i in range(1, len(nums) - 1):\n d = max(d, abs(nums[0] - nums[i + 1]) - abs(nums[i] - nums[i + 1]), abs(nums[-1] - nums[i - 1]) - abs(nums[i] - nums[i - 1]))\n high = -math.inf\n low = math.inf\n for (x, y) in zip(nums, nums[1:]):\n high = max(high, min(x, y))\n low = min(low, max(x, y))\n return ans + max(d, (high - low) * 2)", "def maxvalueafterreverse(nums: List[int]) -> int:\n n = len(nums)\n s = 0\n for i in range(len(nums) - 1):\n s += abs(nums[i] - nums[i + 1])\n if n <= 2:\n return s\n maxup = inc = 0\n minmax = float('inf')\n maxmin = -float('inf')\n for left in range(1, n):\n dis = abs(nums[left] - nums[left - 1])\n minmax = min(minmax, max(nums[left], nums[left - 1]))\n maxmin = max(maxmin, min(nums[left], nums[left - 1]))\n inc = max(inc, abs(nums[0] - nums[left]) - dis)\n inc = max(inc, abs(nums[-1] - nums[left - 1]) - dis)\n return s + max(inc, 2 * (maxmin - minmax))", "def maxvalueafterreverse(nums: List[int]) -> int:\n n = len(nums)\n if n == 1:\n return 0\n ans = 0\n for i in range(1, n - 1):\n ans = max(ans, abs(nums[0] - nums[i + 1]) - abs(nums[i] - nums[i + 1]), abs(nums[-1] - nums[i - 1]) - abs(nums[i] - nums[i - 1]))\n (small, large) = ((-1, float('inf')), (-1, -float('inf')))\n for i in range(n):\n if i >= 1:\n if nums[i] >= nums[i - 1]:\n if small[1] > nums[i]:\n small = (i, nums[i])\n if nums[i] <= nums[i - 1]:\n if large[1] < nums[i]:\n large = (i, nums[i])\n if i < n - 1:\n if nums[i] >= nums[i + 1]:\n if small[1] > nums[i]:\n small = (i, nums[i])\n if nums[i] <= nums[i + 1]:\n if large[1] < nums[i]:\n large = (i, nums[i])\n return sum([abs(nums[i] - nums[i + 1]) for i in range(n - 1)]) + max(2 * (large[1] - small[1]), 0, ans)", "def maxvalueafterreverse(nums: List[int]) -> int:\n (totol, res, min2, max2) = (0, 0, float('inf'), -float('inf'))\n for (a, b) in zip(nums, nums[1:]):\n totol += abs(a - b)\n res = max(res, abs(nums[0] - b) - abs(a - b))\n res = max(res, abs(nums[-1] - a) - abs(a - b))\n (min2, max2) = (min(min2, max(a, b)), max(max2, min(a, b)))\n return totol + max(res, (max2 - min2) * 2)", "def maxvalueafterreverse(nums: List[int]) -> int:\n n = len(nums)\n if n == 1:\n return 0\n if n == 2:\n return abs(nums[1] - nums[0])\n base = 0\n for i in range(n - 1):\n base = base + abs(nums[i + 1] - nums[i])\n res = base\n for i in range(1, n - 1):\n if res < base + abs(nums[i + 1] - nums[0]) - abs(nums[i + 1] - nums[i]):\n res = base + abs(nums[i + 1] - nums[0]) - abs(nums[i + 1] - nums[i])\n for i in range(1, n - 1):\n if res < base + abs(nums[i - 1] - nums[n - 1]) - abs(nums[i] - nums[i - 1]):\n res = base + abs(nums[i - 1] - nums[n - 1]) - abs(nums[i] - nums[i - 1])\n currMax = (nums[0], nums[1])\n currMin = (nums[0], nums[1])\n for i in range(1, n - 1):\n curr = (nums[i], nums[i + 1])\n if min(currMax) > max(curr):\n if res < base + 2 * (min(currMax) - max(curr)):\n res = base + 2 * (min(currMax) - max(curr))\n if max(currMin) < min(curr):\n if res < base + 2 * (min(curr) - max(currMin)):\n res = base + 2 * (min(curr) - max(currMin))\n if min(curr) > min(currMax):\n currMax = curr\n if max(curr) < max(currMin):\n currMin = curr\n return res", "def maxvalueafterreverse(nums: List[int]) -> int:\n return sum((abs(a - b) for (a, b) in zip(nums, nums[1:]))) + max(max((abs(nums[0] - b) - abs(a - b) for (a, b) in zip(nums, nums[1:]))), max((abs(nums[-1] - a) - abs(a - b) for (a, b) in zip(nums, nums[1:]))), 2 * (max((min(a, b) for (a, b) in zip(nums, nums[1:]))) - min((max(a, b) for (a, b) in zip(nums, nums[1:])))))", "def maxvalueafterreverse(nums: List[int]) -> int:\n (ans, imp1, min2, max2) = (0, 0, float('inf'), -float('inf'))\n for (x, y) in zip(nums[:-1], nums[1:]):\n ans += abs(x - y)\n imp1 = max(imp1, abs(nums[0] - y) - abs(x - y), abs(nums[-1] - x) - abs(x - y))\n (min2, max2) = (min(min2, max(x, y)), max(max2, min(x, y)))\n return ans + max(imp1, (max2 - min2) * 2)", "def maxvalueafterreverse(nums: List[int]) -> int:\n ans = 0\n for i in range(len(nums) - 1):\n ans += abs(nums[i + 1] - nums[i])\n d = 0\n for i in range(1, len(nums) - 1):\n d = max(d, abs(nums[0] - nums[i + 1]) - abs(nums[i] - nums[i + 1]), abs(nums[-1] - nums[i - 1]) - abs(nums[i] - nums[i - 1]))\n high = -sys.maxsize\n low = sys.maxsize\n for (x, y) in zip(nums, nums[1:]):\n high = max(high, min(x, y))\n low = min(low, max(x, y))\n return ans + max(d, (high - low) * 2)", "import sys\nfrom collections import defaultdict\nfrom typing import List\n\ndef maxvalueafterreverse(nums: List[int]) -> int:\n result = 0\n gain = -sys.maxsize\n hi = -sys.maxsize\n lo = sys.maxsize\n for index in range(len(nums) - 1):\n n1 = nums[index]\n n2 = nums[index + 1]\n result += abs(n1 - n2)\n gain1 = -abs(n1 - n2) + abs(n2 - nums[0])\n gain2 = -abs(n1 - n2) + abs(n1 - nums[-1])\n gain = max(gain, gain1, gain2)\n hi = max(hi, min(n1, n2))\n lo = min(lo, max(n1, n2))\n newgain = 2 * (hi - lo)\n result += max(gain, newgain)\n return result"], "starter_code": "def maxvalueafterreverse(nums: List[int]) -> int:\n", "input_output": {"fn_name": "maxValueAfterReverse", "inputs": [[[2, 3, 1, 5, 4]]], "outputs": [10]}, "difficulty": "MEDIUM", "raw_tags": ["Math", "Greedy", "Array"], "name": null, "source": "leetcode", "tags": ["Data structures", "Mathematics", "Greedy algorithms"], "skill_types": ["Data structures", "Greedy algorithms"], "url": "https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "maxvalueafterreverse", "task_id": "TACO_lite/497", "example": [[[[2, 3, 1, 5, 4]], [[2, 4, 9, 24, 2, 1, 10]]], ["10", "68"]]} +{"requirement": "Very simple, given a number, find its opposite.\n\nExamples:\n```\n1: -1\n14: -14\n-34: 34\n```\n\n~~~if:sql\nYou will be given a table: `opposite`, with a column: `number`. Return a table with a column: `res`.\n~~~", "solutions": ["def opposite(number):\n return -number", "def opposite(number):\n return number * -1", "def opposite(number):\n return number - number * 2", "from operator import neg as opposite", "opposite = lambda x: -x", "opposite = lambda n: -n", "def opposite(number):\n return abs(number) if number < 0 else 0 - number", "def opposite(number):\n numbers = str(number)\n if isinstance(number, int):\n if numbers[0] == '-':\n negatives = numbers[1:]\n negative = int(negatives)\n return negative\n else:\n positives = '-' + numbers\n positive = int(positives)\n return positive\n if isinstance(number, float):\n if numbers[0] == '-':\n negatives = numbers[1:]\n negative = float(negatives)\n return negative\n else:\n positives = '-' + numbers\n positive = float(positives)\n return positive", "def opposite(n):\n return -1 * n", "def opposite(number):\n return number * 'Magic Forest'.find('unicorn')", "def opposite(n):\n return -n", "def opposite(number):\n return 0 - number", "def opposite(number):\n if number > 0:\n return number - number - number\n elif number < 0:\n return number - number - number\n else:\n return number", "def opposite(number):\n opposite = lambda x: -x\n result = opposite(number)\n return result", "def opposite(x):\n return x * -1", "opposite = lambda n: n * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1))", "def opposite(number):\n import re\n m = re.match('-', str(number))\n if m:\n number = re.sub('-', '', str(number))\n else:\n number = '-' + str(number)\n try:\n return int(number)\n except ValueError:\n return float(number)", "def opposite(number):\n return (lambda x: x * -1)(number)", "opposite = 0.0.__sub__", "def opposite(n):\n str = '\\n ────────▓▓▓▓▓▓▓────────────▒▒▒▒▒▒\\n──────▓▓▒▒▒▒▒▒▒▓▓────────▒▒░░░░░░▒▒\\n────▓▓▒▒▒▒▒▒▒▒▒▒▒▓▓────▒▒░░░░░░░░░▒▒▒\\n───▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒░░░░░░░░░░░░░░▒\\n──▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░▒\\n──▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░▒\\n─▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░▒\\n▓▓▒▒▒▒▒▒░░░░░░░░░░░▒▒░░▒▒▒▒▒▒▒▒▒▒▒░░░░░░▒\\n▓▓▒▒▒▒▒▒▀▀▀▀▀███▄▄▒▒▒░░░▄▄▄██▀▀▀▀▀░░░░░░▒\\n▓▓▒▒▒▒▒▒▒▄▀████▀███▄▒░▄████▀████▄░░░░░░░▒\\n▓▓▒▒▒▒▒▒█──▀█████▀─▌▒░▐──▀█████▀─█░░░░░░▒\\n▓▓▒▒▒▒▒▒▒▀▄▄▄▄▄▄▄▄▀▒▒░░▀▄▄▄▄▄▄▄▄▀░░░░░░░▒\\n─▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░▒\\n──▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░▒\\n───▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▀▀▀░░░░░░░░░░░░░░▒\\n────▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░▒▒\\n─────▓▓▒▒▒▒▒▒▒▒▒▒▄▄▄▄▄▄▄▄▄░░░░░░░░▒▒\\n──────▓▓▒▒▒▒▒▒▒▄▀▀▀▀▀▀▀▀▀▀▀▄░░░░░▒▒\\n───────▓▓▒▒▒▒▒▀▒▒▒▒▒▒░░░░░░░▀░░░▒▒\\n────────▓▓▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░▒▒\\n──────────▓▓▒▒▒▒▒▒▒▒▒░░░░░░░░▒▒\\n───────────▓▓▒▒▒▒▒▒▒▒░░░░░░░▒▒\\n─────────────▓▓▒▒▒▒▒▒░░░░░▒▒\\n───────────────▓▓▒▒▒▒░░░░▒▒\\n────────────────▓▓▒▒▒░░░▒▒\\n──────────────────▓▓▒░▒▒\\n───────────────────▓▒░▒\\n────────────────────▓▒\\n'\n return str.find('¯\\\\_(ツ)_/¯') * n", "opposite = lambda number: -number", "def opposite(number):\n return float(('-' + str(number)).replace('--', ''))", "def opposite(number):\n return (~int(number) + int(number)) * number", "def opposite(number):\n answer = 0 - number\n return answer", "opposite = lambda l: -l", "def opposite(number):\n oppositenum = -number\n return oppositenum", "def opposite(number):\n if number <= 0:\n return abs(number)\n else:\n return number - 2 * number\nopposite(1)", "def opposite(number):\n float(number)\n if number > 0:\n return number - number * 2\n elif number < 0:\n return abs(number)\n elif number == 0:\n return 0", "def opposite(number):\n if number != 0:\n result = -number\n else:\n result = 0\n return result", "def opposite(number):\n if number >= 0:\n return -number\n else:\n return number + -number * 2", "def opposite(number):\n a = -1\n c = number * a\n return c", "def opposite(number):\n if '-' in str(number):\n return -number\n else:\n return -number", "def opposite(number):\n new_num = number\n if number <= 0:\n neg_num = number * 2\n neg_num2 = new_num - neg_num\n return neg_num2\n elif number >= 0:\n pos_num = number * 2\n pos_num2 = new_num - pos_num\n return pos_num2", "def opposite(number):\n a = float(number) * -1\n return a", "def opposite(number):\n if number >= 0:\n return float('-' + str(number))\n else:\n return float(str(number)[1:])", "def opposite(number):\n out = number * -1\n return out", "def opposite(a):\n return -1 * a", "def opposite(number):\n if number >= 0:\n return -number\n else:\n return number * -1", "def opposite(number):\n output = 0 - number\n return output", "def opposite(number):\n x = '-' + str(number)\n if number < 0:\n return abs(number)\n else:\n return float(x)", "def opposite(number):\n qwe = number * -1\n return qwe", "def opposite(n):\n e = n - (n + n)\n return e", "import numpy\n\ndef opposite(number):\n if number < 0:\n return abs(number)\n else:\n return numpy.negative(number)", "def opposite(number):\n return number - number * 2\nopposite(8)", "def opposite(num):\n return abs(num) if num < 0 else -abs(num)", "def opposite(number):\n answer = number * -1\n return answer", "def opposite(number):\n opacne = number * -1\n return opacne", "def opposite(number):\n num = number - 2 * number\n return num", "def opposite(number):\n w = -number\n return w", "def opposite(number):\n string = str(number)\n if string[0] == '-':\n return float(string[1:])\n else:\n return float(''.join(['-', string]))", "def opposite(number):\n convert = None\n if number < 0:\n convert = str(number)[1:]\n else:\n convert = '-' + str(number)\n try:\n return int(convert)\n except:\n return float(convert)", "def opposite(number):\n tmp = number * 2\n ans = number - tmp\n return ans", "def opposite(value):\n return value * -1", "def opposite(number):\n absolu = number * -1\n return absolu", "def opposite(number):\n rev = 0\n rev = -1 * number\n return rev", "def opposite(n):\n if n > 0:\n n = n - 2 * n\n return n\n else:\n n = abs(n)\n return n", "def opposite(number):\n if number >= 1:\n tempnum = number + number\n result = number - tempnum\n return result\n if number <= -1:\n tempnum = number + number\n result = number - tempnum\n return result\n else:\n return 0", "def opposite(number):\n return -number if number != -number else number", "def opposite(number):\n x = number = -number\n return x", "def opposite(number):\n output_num = number * -1\n return output_num", "def opposite(N):\n return -N", "def opposite(number):\n if number > 0:\n number = 0 - number\n elif number is None:\n number = -1\n else:\n return abs(number)\n return number", "def opposite(number):\n if number < 0:\n return abs(number)\n if number > 0:\n return float('-' + str(number))\n if number == 0:\n return 0"], "starter_code": "def opposite(number):\n", "input_output": {"fn_name": "opposite", "inputs": [[1], [25.6], [0], [1425.2222], [-3.1458], [-95858588225]], "outputs": [[-1], [-25.6], [0], [-1425.2222], [3.1458], [95858588225]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56dec885c54a926dcd001095", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "opposite", "task_id": "TACO_lite/435", "example": [[[1], [14], [-34]], ["-1", "-14", "34"]]} +{"requirement": "Given an array A[ ] denoting the time taken to complete N tasks, determine the minimum amount of time required to finish the tasks considering that you can skip any task, but skipping two consecutive tasks is forbidden.\n \nExample 1:\nInput:\nN = 2\nA[] ={10,20}\nOutput: 10\nExplanation: we can take time of\n10 units and skip 20 units time.\n​Example 2:\nInput:\nN = 4\nA[] = {10,5,7,10}\nOutput: 12\nExplanation: we can skip both the\ntens and pick 5 and 7 only.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function minAmount() which accepts array A[] and its size N as input parameter and returns minimum amount of time required to finish the tasks.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 10^{6}", "solutions": ["def minamount(A, n):\n t1 = A[0]\n t2 = 0\n for i in range(1, n):\n k = A[i] + min(t1, t2)\n f = t1\n t1 = k\n t2 = f\n return min(t1, t2)", "def minamount(A, n):\n dp = [0] * (n + 1)\n dp[1] = A[0]\n dp[2] = A[1]\n for i in range(3, len(dp)):\n dp[i] = min(dp[i - 2] + A[i - 1], dp[i - 1] + A[i - 1])\n return min(dp[-1], dp[-2])", "def minamount(A, n):\n ans = 1000000000.0\n if n == 1:\n return A[0]\n if n == 2:\n return min(A[0], A[1])\n inc = A[0]\n exc = 0\n for i in range(1, n):\n incTemp = A[i] + min(inc, exc)\n excTemp = inc\n inc = incTemp\n exc = excTemp\n return min(inc, exc)", "def minamount(A, n):\n pre1 = A[0]\n pre2 = 0\n for i in range(1, n):\n temp1 = min(pre1, pre2) + A[i]\n temp2 = pre1\n pre1 = temp1\n pre2 = temp2\n return min(pre1, pre2)", "def minamount(A, n):\n summa = sum(A)\n if n < 3:\n return summa - max(A)\n A[2] += A[0]\n for i in range(3, n):\n A[i] += max(A[i - 2], A[i - 3])\n return summa - max(A[-2:])", "import sys\nsys.setrecursionlimit(10 ** 9)\n\ndef minamount(arr, n):\n dp = arr.copy()\n for i in range(n - 3, -1, -1):\n dp[i] = min(dp[i] + dp[i + 2], dp[i] + dp[i + 1])\n return min(dp[0], dp[1])", "def minamount(arr, n):\n dp = arr.copy()\n for i in range(n - 3, -1, -1):\n dp[i] = min(dp[i] + dp[i + 2], dp[i] + dp[i + 1])\n return min(dp[0], dp[1])", "import math\n\ndef minamount(A, n):\n dp = [0]\n s = 0\n ns = A[0]\n for i in range(1, n):\n nss = ns\n nsns = ns + A[i]\n sns = s + A[i]\n dp.append(min(min(nss, nsns), sns))\n s = nss\n ns = min(nsns, sns)\n return dp[-1]", "import math\n\ndef minamount(a, n):\n inc = a[0]\n e = 0\n for i in range(1, n):\n inc_n = a[i] + min(e, inc)\n e = inc\n inc = inc_n\n return min(e, inc)", "def minamount(A, n):\n if n == 1:\n return 0\n if n == 2:\n return min(A)\n dp = [0 if i > 1 else A[i] for i in range(n)]\n for i in range(2, n):\n dp[i] = A[i] + min(dp[i - 1], dp[i - 2])\n return min(dp[n - 2], dp[n - 1])", "def minamount(A, n):\n a = 0\n b = A[0]\n for i in range(1, n):\n c = min(a, b) + A[i]\n d = b\n (a, b) = (d, c)\n return min(a, b)", "def minamount(A, n):\n inc = [-1] * n\n exc = [-1] * n\n inc[0] = A[0]\n exc[0] = 0\n for i in range(1, n):\n inc[i] = min(inc[i - 1], exc[i - 1]) + A[i]\n exc[i] = inc[i - 1]\n return min(exc[n - 1], inc[n - 1])", "def minamount(A, n):\n if len(A) == 1:\n return A[0]\n else:\n prev_a = 0\n prev_b = A[0]\n ans = float('inf')\n for i in range(1, n):\n temp = A[i] + min(prev_b, prev_a)\n ans = min(temp, prev_b)\n prev_a = prev_b\n prev_b = temp\n return ans", "def minamount(a, n):\n for i in range(2, n):\n a[i] = min(a[i - 2], a[i - 1]) + a[i]\n return min(a[-1], a[-2])", "def minamount(A, n):\n excl = 0\n incl = A[0]\n for i in range(1, n):\n excl_ = excl\n excl = incl\n incl = min(incl + A[i], excl_ + A[i])\n return min(incl, excl)", "def minamount(A, n):\n t = 0\n dp = [0 for _ in range(n)]\n dp[0] = A[0]\n dp[1] = A[1]\n for i in range(2, n):\n dp[i] = min(dp[i - 1] + A[i], dp[i - 2] + A[i])\n return min(dp[-1], dp[-2])", "def minamount(A, n):\n if n <= 0:\n return 0\n incl = A[0]\n excl = 0\n for i in range(1, n):\n new_incl = A[i] + min(incl, excl)\n new_excl = incl\n incl = new_incl\n excl = new_excl\n return min(incl, excl)", "def minamount(a, n):\n inc = a[0]\n exc = 0\n for i in range(1, n):\n inc_new = a[i] + min(inc, exc)\n exc_new = inc\n inc = inc_new\n exc = exc_new\n return min(inc, exc)", "def minamount(A, n):\n (skip, take) = (0, A[0])\n total = 0\n for i in range(1, n):\n (s, t) = (skip, take)\n skip = t\n take = min(s, t) + A[i]\n total = min(skip, take)\n return total", "def minamount(arr, n):\n if n <= 0:\n return 0\n incl = arr[0]\n excl = 0\n for i in range(1, n):\n incl_new = arr[i] + min(excl, incl)\n excl_new = incl\n incl = incl_new\n excl = excl_new\n return min(incl, excl)", "def minamount(A, n):\n total_time = [0, 0]\n for task_time in A:\n skip = total_time[1]\n doing = min(total_time) + task_time\n total_time = [skip, doing]\n return min(total_time)", "def minamount(A, n):\n (not_taken, taken) = (0, A[0])\n for i in range(1, n):\n new_taken = min(A[i] + not_taken, A[i] + taken)\n not_taken = taken\n taken = new_taken\n return min(taken, not_taken)", "def minamount(A, n):\n skip = 0\n doIt = A[n - 1]\n for i in range(n - 2, -1, -1):\n old = skip\n skip = doIt\n doIt = A[i] + min(old, doIt)\n return min(skip, doIt)", "def minamount(A, n):\n skipped = 0\n a = A[n - 1]\n for i in range(n - 2, -1, -1):\n prev = skipped\n skipped = a\n a = A[i] + min(prev, a)\n return min(skipped, a)", "def minamount(arr, n):\n incl = [0] * (n + 1)\n excl = [0] * (n + 1)\n incl[0] = 0\n minT = [0] * (n + 1)\n excl[0] = 0\n minT[0] = 0\n for i in range(1, n + 1):\n incl[i] = arr[i - 1] + min(incl[i - 1], excl[i - 1])\n excl[i] = incl[i - 1]\n minT[i] = min(incl[i], excl[i])\n return minT[n]", "def minamount(A, n):\n with_skip = 0\n without_skip = A[0]\n for i in range(1, len(A)):\n temp1 = with_skip\n with_skip = without_skip\n without_skip = A[i] + min(temp1, without_skip)\n return min(with_skip, without_skip)", "def minamount(A, n):\n a = 0\n b = A[0]\n i = 1\n while i < n:\n c = A[i] + min(a, b)\n (a, b) = (b, c)\n i += 1\n return min(a, b)", "def minamount(A, n):\n if n == 1:\n return A[0]\n if n == 2:\n return min(A[0], A[1])\n skip = 0\n cts = A[0]\n for i in range(1, n):\n temp = skip\n skip = cts\n cts = A[i] + min(temp, cts)\n return min(skip, cts)", "def Task(arr, i=0, taken=True):\n global mod\n global dp\n try:\n return dp[i, taken]\n except:\n pass\n if i == len(arr) - 2:\n if taken == True:\n return min(arr[i], arr[i + 1])\n return arr[i]\n if taken == False:\n dp[i, taken] = arr[i] + Task(arr, i + 1, True) % mod\n return dp[i, taken]\n k1 = Task(arr, i + 1, False) % mod\n k2 = arr[i] + Task(arr, i + 1, True) % mod\n dp[i, taken] = min(k1, k2) % mod\n return dp[i, taken]\n\ndef TaskTabulation(arr):\n dp = [[0 for i in range(len(arr))] for j in range(2)]\n dp[0][-1] = arr[-1]\n dp[1][-1] = 0\n dp[0][-2] = min(arr[-2], arr[-1])\n dp[1][-2] = arr[-2]\n res = float('inf')\n for i in range(len(arr) - 3, -1, -1):\n dp[1][i] = arr[i] + dp[0][i + 1]\n dp[0][i] = min(dp[1][i + 1], arr[i] + dp[0][i + 1])\n return min(dp[0][0], dp[1][0])\n\ndef minamount(A, n):\n global dp\n global mod\n mod = 1000000007\n dp = {}\n return TaskTabulation(A)", "def minamount(A, n):\n if n == 1:\n return A[0]\n if n == 2:\n return min(A[0], A[1])\n exc = [0] * (n + 1)\n inc = [0] * (n + 1)\n inc[0] = A[0]\n exc[1] = A[0]\n inc[1] = A[1]\n for x in range(2, n):\n exc[x] = inc[x - 1]\n inc[x] = min(A[x] + exc[x - 1], A[x] + inc[x - 1])\n return min(exc[n - 1], inc[n - 1])", "def minamount(A, n):\n if n <= 0:\n return 0\n incl = A[0]\n excl = 0\n for i in range(1, n):\n incn = A[i] + min(incl, excl)\n excn = incl\n incl = incn\n excl = excn\n return min(incl, excl)", "def minamount(arr, n):\n (inc, exc) = (arr[0], 0)\n for i in range(1, n):\n new_inc = arr[i] + min(inc, exc)\n new_exc = inc\n inc = new_inc\n exc = new_exc\n return min(inc, exc)"], "starter_code": "def minamount(A, n):\n", "input_output": {"inputs": ["N = 2\nA[] ={10,20}", "N = 4\nA[] = {10,5,7,10}"], "outputs": ["10", "12"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/skip-the-work5752/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "minamount", "task_id": "TACO_lite/541", "example": [[[2, [10, 20]], [4, [10, 5, 7, 10]]], ["10", "12"]]} +{"requirement": "Given a square matrix of size N x N. The task is to find the determinant of this matrix.\nExample 1:\nInput:\nN = 4\nmatrix[][] = {{1, 0, 2, -1},\n {3, 0, 0, 5},\n {2, 1, 4, -3},\n {1, 0, 5, 0}}\nOutput: 30\nExplanation:\nDeterminant of the given matrix is 30.\nExample 2:\nInput:\nN = 3\nmatrix[][] = {{1, 2, 3},\n {4, 5, 6},\n {7, 10, 9}}\nOutput: 12\nExplanation:\nDeterminant of the given matrix is 12.\nYour Task:\nYou don't need to read input or print anything. Complete the function determinantOfMatrix() that takes matrix and its size n as input parameters and returns the determinant of the matrix.\nExpected Time Complexity: O(N^{4})\nExpected Auxiliary Space: O(N^{2})\nConstraints:\n1 <= N <= 8\n-10 <= mat[i][j] <= 10", "solutions": ["def determinantofmatrix(a, n):\n if n == 1:\n return a[0][0]\n elif n == 2:\n return a[0][0] * a[1][1] - a[1][0] * a[0][1]\n else:\n ans = 0\n for col in range(n):\n small = []\n for i in range(1, n):\n dem = []\n for j in range(n):\n if j == col:\n continue\n dem.append(a[i][j])\n small.append(dem)\n if col % 2 == 0:\n ans += a[0][col] * self.determinantofmatrix(small, n - 1)\n else:\n ans -= a[0][col] * self.determinantofmatrix(small, n - 1)\n return ans", "def determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n det = 0\n sign = 1\n for i in range(n):\n new_mat = []\n for y in range(n - 1):\n new_mat.append([])\n for x in range(n):\n if x != i:\n new_mat[y].append(matrix[y + 1][x])\n self.determinantofmatrix(new_mat, n - 1)\n det += sign * matrix[0][i] * self.determinantofmatrix(new_mat, n - 1)\n sign *= -1\n return det", "import numpy as np\n\ndef determinant(mat):\n det = np.linalg.det(mat)\n return round(det)\n\ndef determinantofmatrix(matrix, n):\n return int(determinant(matrix))", "def determinantofmatrix(matrix, n):\n if len(matrix) == 1:\n return matrix[0][0]\n if len(matrix) == 2:\n return matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]\n currentCol = ans = 0\n while currentCol < len(matrix[0]):\n minor = [[0] * 0] * 0\n for i in range(len(matrix)):\n temp = []\n for j in range(len(matrix[0])):\n if i != 0 and j != currentCol:\n temp.append(matrix[i][j])\n if len(temp) > 0:\n minor.append(temp)\n ans = ans + matrix[0][currentCol] * (-1) ** currentCol * self.determinantofmatrix(minor, len(minor))\n currentCol += 1\n return ans", "def determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n elif n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n res = 0\n for i in range(len(matrix[0])):\n smallerMatrix = []\n for j in range(1, len(matrix)):\n col = []\n for k in range(len(matrix[0])):\n if k == i:\n continue\n col.append(matrix[j][k])\n smallerMatrix.append(col)\n if i % 2 == 0:\n res += matrix[0][i] * self.determinantofmatrix(smallerMatrix, n - 1)\n else:\n res -= matrix[0][i] * self.determinantofmatrix(smallerMatrix, n - 1)\n return res", "import numpy as np\nimport math\n\ndef determinantofmatrix(matrix, n):\n det = np.linalg.det(matrix)\n return int(round(det))", "import numpy as np\n\ndef determinantofmatrix(matrix, n):\n ans = str(np.linalg.det(matrix))\n s = ''\n for d in ans:\n if d == '.':\n break\n s += d\n return int(s)", "def determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n det = 0\n for i in range(n):\n submatrix = [[0 for _ in range(n - 1)] for _ in range(n - 1)]\n for x in range(1, n):\n j = 0\n for y in range(n):\n if y == i:\n continue\n submatrix[x - 1][j] = matrix[x][y]\n j += 1\n det += matrix[0][i] * self.determinantofmatrix(submatrix, n - 1) * (-1) ** i\n return det", "def determinantofmatrix(mat, n):\n temp = [0] * n\n total = 1\n det = 1\n for i in range(0, n):\n index = i\n while index < n and mat[index][i] == 0:\n index += 1\n if index == n:\n continue\n if index != i:\n for j in range(0, n):\n (mat[index][j], mat[i][j]) = (mat[i][j], mat[index][j])\n det = det * int(pow(-1, index - i))\n for j in range(0, n):\n temp[j] = mat[i][j]\n for j in range(i + 1, n):\n num1 = temp[i]\n num2 = mat[j][i]\n for k in range(0, n):\n mat[j][k] = num1 * mat[j][k] - num2 * temp[k]\n total = total * num1\n for i in range(0, n):\n det = det * mat[i][i]\n return int(det / total)", "def getCofactor(matrix, i, j):\n return [row[:j] + row[j + 1:] for row in matrix[:i] + matrix[i + 1:]]\n\ndef determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n if n == 2:\n value = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n return value\n else:\n s = 0\n for current_col in range(n):\n sign = (-1) ** current_col\n sub_matrix = self.getCofactor(matrix, 0, current_col)\n sub_det = self.determinantofmatrix(sub_matrix, n - 1)\n s += sign * matrix[0][current_col] * sub_det\n return s", "def determinantofmatrix(matrix, n):\n det = 0\n if n == 1:\n return matrix[0][0]\n if n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]\n for i in range(n):\n temp = []\n for row in range(1, n):\n p = []\n for col in range(n):\n if col == i:\n continue\n else:\n p.append(matrix[row][col])\n temp.append(p)\n if i % 2 == 1:\n det = det - matrix[0][i] * Solution.determinantofmatrix(self, temp, n - 1)\n else:\n det = det + matrix[0][i] * Solution.determinantofmatrix(self, temp, n - 1)\n return det", "def smallermatrix(matrix, row, col):\n from copy import deepcopy\n arr = deepcopy(matrix)\n arr.remove(matrix[row])\n for row in arr:\n row.pop(col)\n return arr\n\ndef sol(matrix):\n n = len(matrix)\n if n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n ans = 0\n for i in range(n):\n total = (-1) ** i * matrix[0][i] * self.sol(self.smallermatrix(matrix, 0, i))\n ans += total\n return ans\n\ndef determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n ans = self.sol(matrix)\n return ans", "from numpy import *\n\ndef determinantofmatrix(matrix, n):\n return int(round(linalg.det(matrix)))", "def submatrix(m, r, c):\n rows = len(m)\n columns = len(m[0])\n sm = []\n for i in range(rows):\n sm.append([])\n for j in range(columns):\n sm[i].append(m[i][j])\n sm = sm[1:]\n for i in range(len(sm)):\n sm[i] = sm[i][:c] + sm[i][c + 1:]\n return sm\n\ndef determinant(m):\n rows = len(m)\n columns = len(m[0])\n if rows == 1 and columns == 1:\n return m[0][0]\n else:\n c = 1\n result = 0\n for i in range(columns):\n sm = self.submatrix(m, 0, i)\n result += c * m[0][i] * self.determinant(sm)\n c *= -1\n return result\n\ndef determinantofmatrix(matrix, n):\n return self.determinant(matrix)", "def getCofactor(matrix, temp, p, q, n):\n (i, j) = (0, 0)\n for row in range(n):\n for col in range(n):\n if row != p and col != q:\n temp[i][j] = matrix[row][col]\n j += 1\n if j == n - 1:\n j = 0\n i += 1\n\ndef determinantofmatrix(matrix, n):\n d = 0\n if n == 1:\n return matrix[0][0]\n temp = [[0 for i in range(n)] for i in range(n)]\n sign = 1\n for i in range(n):\n self.getCofactor(matrix, temp, 0, i, n)\n d += sign * matrix[0][i] * self.determinantofmatrix(temp, n - 1)\n sign = -sign\n return d", "def determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n if n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n total = 0\n for i in range(n):\n B = matrix.copy()\n B = B[1:]\n for j in range(n - 1):\n B[j] = B[j][0:i] + B[j][i + 1:]\n sign = (-1) ** (i % 2)\n sub_det = self.determinantofmatrix(B, n - 1)\n total += matrix[0][i] * sign * sub_det\n return total", "def determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n if n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n det = 0\n for col in range(n):\n if col % 2 == 0:\n det += matrix[0][col] * self.determinantofmatrix(self.getTheMat(matrix, n, 0, col), n - 1)\n else:\n det -= matrix[0][col] * self.determinantofmatrix(self.getTheMat(matrix, n, 0, col), n - 1)\n return det\n\ndef getTheMat(matrix, n, x, y):\n mat = []\n for i in range(n):\n cur_mat = []\n for j in range(n):\n if i != x and j != y:\n cur_mat.append(matrix[i][j])\n if cur_mat != []:\n mat.append(cur_mat)\n return mat", "import numpy as np\n\ndef determinantofmatrix(matrix, n):\n ans = np.linalg.det(matrix)\n a1 = round(ans)\n return int(a1)", "def cofactorMatrix(matrix, r, c):\n return [row[:c] + row[c + 1:] for row in matrix[:r] + matrix[r + 1:]]\n\ndef determinantofmatrix(matrix, n):\n if len(matrix) == 1:\n return matrix[0][0]\n if len(matrix) == 2:\n v = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n return v\n sum = 0\n for curr_col in range(len(matrix)):\n sign = (-1) ** curr_col\n sub_det = self.determinantofmatrix(self.cofactorMatrix(matrix, 0, curr_col), n)\n sum += sign * matrix[0][curr_col] * sub_det\n return sum", "import numpy as np\n\ndef determinantofmatrix(arr, n):\n det = str(np.linalg.det(arr))\n l = len(det)\n return det[:l - 2]", "import numpy\n\ndef determinantofmatrix(A, n):\n return int(round(numpy.linalg.det(A)))", "def determinantofmatrix(matrix, n):\n\n def cofactor(arr, temp, i, j, n):\n s = 0\n t = 0\n for r in range(n):\n for c in range(n):\n if r != i and c != j:\n temp[s][t] = arr[r][c]\n t += 1\n if t == n - 1:\n t = 0\n s += 1\n return temp\n if n == 1:\n return matrix[0][0]\n temp = [[float('inf') for _ in range(n)] for _ in range(n)]\n sgn = 1\n det = 0\n for i in range(n):\n C = cofactor(matrix, temp, 0, i, n)\n det += matrix[0][i] * sgn * self.determinantofmatrix(C, n - 1)\n sgn = -sgn\n return det", "def determinantMaker(a, m):\n b = []\n n = len(a)\n for i in range(1, n, 1):\n c = []\n for j in range(n):\n if j == m:\n continue\n else:\n c.append(a[i][j])\n b.append(c)\n return b\n\ndef determinantofmatrix(a, n):\n n = len(a)\n if n == 1:\n return a[0][0]\n elif n == 2:\n return a[0][0] * a[1][1] - a[1][0] * a[0][1]\n else:\n sign = 1\n ans = 0\n for i in range(n):\n temp = 0\n b = self.determinantMaker(a, i)\n m = len(b)\n temp = sign * a[0][i] * self.determinantofmatrix(b, m)\n ans += temp\n sign *= -1\n return ans", "def determinantofmatrix(matrix, n):\n\n def getSubmetrix(matrix, coordinations):\n (row, colomn) = coordinations\n newmatrxi = []\n for i in range(len(matrix)):\n if i == row - 1:\n continue\n newrow = []\n for j in range(len(matrix[0])):\n if j == colomn - 1:\n continue\n newrow.append(matrix[i][j])\n newmatrxi.append(newrow)\n return newmatrxi\n\n def determinant(matrix):\n if len(matrix) == 2:\n det = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n elif len(matrix) > 2:\n det = 0\n for i in range(len(matrix)):\n submat = getSubmetrix(matrix, (1, i + 1))\n det += (-1) ** (i + 2) * determinant(submat) * matrix[0][i]\n else:\n return matrix[0][0]\n return det\n return determinant(matrix)", "def getTruncatedMatrix(matrix, n, i, j):\n res = []\n for row in range(n):\n arr = []\n for col in range(n):\n if col != j:\n arr.append(matrix[row][col])\n if row != i:\n res.append(arr)\n return res\n\ndef determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n if n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n else:\n ans = 0\n for col in range(n):\n ans += (-1) ** col * matrix[0][col] * self.determinantofmatrix(getTruncatedMatrix(matrix, n, 0, col), n - 1)\n return ans", "import numpy as np\n\ndef cofactor(M, i, j):\n return [row[:j] + row[j + 1:] for row in M[:i] + M[i + 1:]]\n\ndef determinantofmatrix(M, n):\n if n == 1:\n return M[0][0]\n if n == 2:\n return M[0][0] * M[1][1] - M[0][1] * M[1][0]\n det = 0\n for i in range(n):\n sign = (-1) ** i\n subdet = self.determinantofmatrix(self.cofactor(M, 0, i), n - 1)\n det += sign * M[0][i] * subdet\n return det", "import numpy as np\n\ndef determinantofmatrix(M, n):\n det = np.linalg.det(M)\n return int(round(det))", "import numpy as np\n\ndef cofactor(arr, i, j):\n return [row[:j] + row[j + 1:] for row in arr[:i] + arr[i + 1:]]\n\ndef determinantofmatrix(arr, n):\n return int(round(np.linalg.det(arr)))", "def determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n elif n == 2:\n a = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n return a\n s = 0\n li = []\n for i in range(n):\n if matrix[0][i] == 0:\n continue\n for k in range(1, n):\n li1 = list(matrix[k])\n li1.pop(i)\n li.append(li1)\n if i % 2 == 0:\n s += matrix[0][i] * self.determinantofmatrix(li, n - 1)\n li = []\n else:\n s -= matrix[0][i] * self.determinantofmatrix(li, n - 1)\n li = []\n return s", "def determinantofmatrix(matrix, n):\n return self.solve(matrix, n)\n\ndef solve(matrix, n):\n if n == 1:\n return matrix[0][0]\n if n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n matrix2 = [[0 for j in range(n - 1)] for i in range(n - 1)]\n total = 0\n for k in range(n):\n a = b = 0\n for i in range(1, n):\n b = 0\n for j in range(n):\n if j != k:\n matrix2[a][b] = matrix[i][j]\n b += 1\n a += 1\n t = self.determinantofmatrix(matrix2, n - 1)\n total += (-1) ** k * matrix[0][k] * t\n return total", "def determinantofmatrix(M, n):\n import numpy\n D = int(round(numpy.linalg.det(M)))\n return D", "def cofactor(m, i, j):\n return [row[:j] + row[j + 1:] for row in m[:i] + m[i + 1:]]\n\ndef determinantofmatrix(mat, n=float('inf')):\n if len(mat) == 1:\n return mat[0][0]\n if len(mat) == 2:\n return mat[0][0] * mat[1][1] - mat[1][0] * mat[0][1]\n res = 0\n for col in range(len(mat)):\n sign = (-1) ** col\n det = self.determinantofmatrix(self.cofactor(mat, 0, col))\n res += sign * mat[0][col] * det\n return res", "def determinant_recursive(A, total=0):\n indices = list(range(len(A)))\n if len(A) == 2 and len(A[0]) == 2:\n val = A[0][0] * A[1][1] - A[1][0] * A[0][1]\n return val\n for fc in indices:\n As = A\n As = As[1:]\n height = len(As)\n for i in range(height):\n As[i] = As[i][0:fc] + As[i][fc + 1:]\n sign = (-1) ** (fc % 2)\n sub_det = determinant_recursive(As)\n total += sign * A[0][fc] * sub_det\n return total\n\ndef determinantofmatrix(a, n):\n if n == 1:\n return a[0][0]\n return determinant_recursive(a)", "def cofactor_matrix(matrix, temp, p, q, n):\n (i, j) = (0, 0)\n for row in range(n):\n for column in range(n):\n if row != p and column != q:\n temp[i][j] = matrix[row][column]\n j += 1\n if j == n - 1:\n j = 0\n i += 1\n\ndef determinantofmatrix(matrix, n):\n answer = 0\n if n == 1:\n return matrix[0][0]\n temp = [[0 for i in range(n)] for j in range(n)]\n sign = 1\n for i in range(n):\n self.cofactor_matrix(matrix, temp, 0, i, n)\n answer += sign * matrix[0][i] * self.determinantofmatrix(temp, n - 1)\n sign = -sign\n return answer", "def determinantofmatrix(arr, n):\n if n == 1:\n return arr[0][0]\n else:\n b = [[0] * n for i in range(n)]\n s = 1\n det = 0\n for c in range(n):\n m = 0\n z = 0\n for i in range(n):\n for j in range(n):\n if i != 0 and j != c:\n b[m][z] = arr[i][j]\n if z < n - 2:\n z += 1\n else:\n z = 0\n m += 1\n det = det + arr[0][c] * s * self.determinantofmatrix(b, n - 1)\n s = s * -1\n return det", "def getcofactor(m, i, j):\n return [row[:j] + row[j + 1:] for row in m[:i] + m[i + 1:]]\n\ndef determinantofmatrix(mat, n=0):\n if len(mat) == 1:\n return mat[0][0]\n if len(mat) == 2:\n value = mat[0][0] * mat[1][1] - mat[1][0] * mat[0][1]\n return value\n Sum = 0\n for current_column in range(len(mat)):\n sign = (-1) ** current_column\n sub_det = self.determinantofmatrix(getcofactor(mat, 0, current_column))\n Sum += sign * mat[0][current_column] * sub_det\n return Sum", "import numpy as np\n\ndef determinantofmatrix(Matrix, n):\n D = np.linalg.det(Matrix)\n return int(round(D))", "def getfactor(matrix, n, row, col, temp):\n x = 0\n y = 0\n for i in range(n):\n for j in range(n):\n if i != row and j != col:\n temp[x][y] = matrix[i][j]\n y += 1\n if y == n - 1:\n y = 0\n x += 1\n\ndef determinantofmatrix(matrix, n):\n d = 0\n if n == 1:\n return matrix[0][0]\n temp = [[0 for _ in range(n)] for _ in range(n)]\n sign = 1\n for j in range(n):\n self.getfactor(matrix, n, 0, j, temp)\n d += sign * matrix[0][j] * self.determinantofmatrix(temp, n - 1)\n sign *= -1\n return d"], "starter_code": "def determinantofmatrix(matrix,n):\n", "input_output": {"inputs": ["N = 4\nmatrix[][] = {{1, 0, 2, -1},\n {3, 0, 0, 5},\n {2, 1, 4, -3},\n {1, 0, 5, 0}}", "N = 3\nmatrix[][] = {{1, 2, 3},\n {4, 5, 6},\n {7, 10, 9}}"], "outputs": ["30", "12"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/determinant-of-a-matrix-1587115620/1", "Expected Auxiliary Space": "O(N^{2})", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N^{4})", "entry_point": "determinantofmatrix", "task_id": "TACO_lite/529", "example": [[], []]} +{"requirement": "# Task\nGiven an array `arr`, find the maximal value of `k` such `a[i] mod k` = `a[j] mod k` for all valid values of i and j.\n\nIf it's impossible to find such number (there's an infinite number of `k`s), return `-1` instead.\n\n\n# Input/Output\n\n`[input]` integer array `arr`\n\nA non-empty array of positive integer.\n\n`2 <= arr.length <= 10`\n\n`1 <= arr[i] <= 100`\n\n`[output]` an integer\n\nThe maximum value of `k` or `-1` if there is none.\n\n\n# Example\n\nFor `arr = [1, 2, 3]`, the output should be `1`.\n\n`1` is the only k which satisfies the given conditions.\n\nFor `arr = [1, 1, 1]`, the output should be `-1`.\n\n`1 % k = 1` for `any k > 1`, so it's impossible to find the maximum.\n\nFor `arr = [5, 2, 8]`, the output should be `3`.\n\n`5 % 3 == 2 % 3 == 8 % 3 == 2`", "solutions": ["def finding_k(arr):\n for n in range(max(arr) - 1, 0, -1):\n if len({x % n for x in arr}) == 1:\n return n\n return -1", "from itertools import repeat\nfrom functools import reduce\nfrom operator import sub\nfrom math import gcd\n\ndef finding_k(arr):\n return reduce(gcd, filter(None, map(sub, set(arr), repeat(min(arr)))), 0) or -1", "def finding_k(arr):\n s = set(arr)\n if s == {1}:\n return -1\n for k in range(max(s), 0, -1):\n r = arr[0] % k\n if all((x % k == r for x in s)):\n return k\n return -1", "finding_k = lambda a: max([k for k in range(1, max(a)) if eval('=='.join([str(z) + '%' + str(k) for z in a]))], default=-1)", "def finding_k(arr):\n for i in range(max(arr) - 1, 0, -1):\n if len({j % i for j in arr}) == 1:\n return i\n return -1", "finding_k = lambda a: next((i for i in range(max(a) - 1, 0, -1) if len(set([j % i for j in a])) == 1), -1)", "from fractions import gcd\nfrom functools import reduce\n\ndef finding_k(arr):\n fr = [x - min(arr) for x in arr]\n if all((v == 0 for v in fr)):\n return -1\n else:\n return reduce(lambda x, y: gcd(x, y), fr)", "def finding_k(arr):\n maxValue = max(arr) - min(arr)\n k = 0\n while maxValue > 0:\n if len(set(map(lambda x: x % maxValue, arr))) == 1:\n k = maxValue\n break\n maxValue -= 1\n if k:\n return k\n else:\n return -1", "from functools import reduce\ngcd = lambda a, b: gcd(b, a % b) if b else a\nfinding_k = lambda arr: reduce(lambda a, b: gcd(a, b), [abs(e - arr[0]) for e in arr]) or -1", "def finding_k(arr):\n ans = []\n for i in range(1, 101):\n if len({j % i for j in arr}) == 1:\n ans.append(i)\n return max(ans) if len(ans) < 100 else -1"], "starter_code": "def finding_k(arr):\n", "input_output": {"fn_name": "finding_k", "inputs": [[[1, 2, 3]], [[1, 1, 1]], [[5, 2, 8]], [[4, 1, 7]], [[1, 7, 13]], [[4, 5, 4]], [[5, 6, 7, 8]], [[10, 100]], [[64, 8, 1]], [[2, 9, 30]]], "outputs": [[1], [-1], [3], [3], [6], [1], [1], [90], [7], [7]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5919427e5ffc30804900005f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "finding_k", "task_id": "TACO_lite/346", "example": [[[[1, 2, 3]], [[1, 1, 1]], [[5, 2, 8]]], ["1", "-1", "3"]]} +{"requirement": "Given weights and values of N items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack.\nNote: Unlike 0/1 knapsack, you are allowed to break the item. \n \nExample 1:\nInput:\nN = 3, W = 50\nvalues[] = {60,100,120}\nweight[] = {10,20,30}\nOutput:\n240.00\nExplanation:Total maximum value of item\nwe can have is 240.00 from the given\ncapacity of sack. \nExample 2:\nInput:\nN = 2, W = 50\nvalues[] = {60,100}\nweight[] = {10,20}\nOutput:\n160.00\nExplanation:\nTotal maximum value of item\nwe can have is 160.00 from the given\ncapacity of sack.\n \nYour Task :\nComplete the function fractionalKnapsack() that receives maximum capacity , array of structure/class and size n and returns a double value representing the maximum value in knapsack.\nNote: The details of structure/class is defined in the comments above the given function.\nExpected Time Complexity : O(NlogN)\nExpected Auxilliary Space: O(1)\nConstraints:\n1 <= N <= 10^{5}\n1 <= W <= 10^{5}", "solutions": ["def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: -1 * (x.value / x.weight))\n profit = 0\n for i in range(n):\n v = arr[i].value\n w = arr[i].weight\n if w <= W:\n W -= w\n profit += v\n else:\n profit += W * (v / w)\n W = 0\n break\n return profit", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n fractionalArray = []\n for i in range(n):\n fractionalArray.append([arr[i].value, arr[i].weight, arr[i].value / arr[i].weight])\n fractionalArray = sorted(fractionalArray, key=lambda x: -x[2])\n ans = 0\n while W > 0 and len(fractionalArray) > 0:\n popped = fractionalArray.pop(0)\n if popped[1] > W:\n ans += popped[0] * W / popped[1]\n W = 0\n else:\n W -= popped[1]\n ans += popped[0]\n return round(ans, 2)", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n d = []\n for i in range(0, len(arr)):\n k = (arr[i].value, arr[i].weight, arr[i].value / arr[i].weight)\n d.append(k)\n d.sort(key=lambda x: x[2], reverse=True)\n p = 0\n for i in range(0, len(d)):\n if d[i][1] <= W:\n W -= d[i][1]\n p += d[i][0]\n elif d[i][1] > W:\n p += d[i][0] * (W / d[i][1])\n break\n return p", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(w, arr, n):\n count = 0\n\n def give(i):\n return i.value / i.weight\n arr.sort(reverse=True, key=give)\n for i in arr:\n ass = min(w, i.weight)\n count += ass * i.value / i.weight\n w -= ass\n if ass == 0:\n return count\n return count", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n items = sorted(arr, key=lambda x: x.weight / x.value)\n result = 0\n for item in items:\n if W <= 0:\n break\n result += min(1, W / item.weight) * item.value\n W -= item.weight\n return result", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n frac = [[items.value / items.weight, items.weight] for items in arr]\n frac.sort(key=lambda x: x[0])\n val = 0\n while W and frac:\n a = frac.pop()\n k = a[0]\n p = a[1]\n if W >= p:\n val += k * p\n W -= p\n else:\n val += k * W\n W = 0\n return val", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(w, arr, n):\n arr.sort(key=lambda x: -1 * (x.value / x.weight))\n value = 0\n for item in arr:\n if w <= item.weight:\n value += item.value * (w / item.weight)\n break\n else:\n value += item.value\n w -= item.weight\n return value", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n total = 0\n remaining_weight = W\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n for item in arr:\n if item.weight <= remaining_weight:\n total += item.value\n remaining_weight -= item.weight\n else:\n total += remaining_weight * item.value / item.weight\n break\n return total", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, Items, n):\n arr = []\n total = 0\n s = 0\n for i in range(n):\n x = Items[i].value / Items[i].weight\n arr.append([x, i])\n arr.sort(reverse=True)\n for i in range(n):\n if s + Items[arr[i][1]].weight < W:\n total += Items[arr[i][1]].value\n s += Items[arr[i][1]].weight\n else:\n total += (W - s) * arr[i][0]\n break\n return total", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n li = []\n for i in range(n):\n perUnitVal = arr[i].value / arr[i].weight\n li.append((perUnitVal, arr[i]))\n li.sort(key=lambda x: x[0], reverse=True)\n profit = 0\n for pair in li:\n if pair[1].weight <= W:\n profit += pair[1].value\n W -= pair[1].weight\n else:\n profit += pair[1].value / pair[1].weight * W\n W = 0\n break\n return profit", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n curWeight = 0\n finalValue = 0.0\n for i in range(n):\n if curWeight + arr[i].weight <= W:\n curWeight += arr[i].weight\n finalValue += arr[i].value\n else:\n remain = W - curWeight\n finalValue += arr[i].value / arr[i].weight * remain\n break\n return finalValue", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n rr = []\n arr.sort(reverse=True, key=lambda x: x.value / x.weight)\n ans = 0\n for ind in range(len(arr)):\n cap = min(W, arr[ind].weight)\n if arr[ind].weight <= W:\n ans += arr[ind].value\n W -= arr[ind].weight\n continue\n rat = arr[ind].value / arr[ind].weight\n ans += rat * cap\n W -= cap\n return ans", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n profit = 0\n for i in arr:\n if i.weight <= W:\n profit += i.value\n W -= i.weight\n elif i.weight > W:\n profit += i.value / i.weight * W\n W = 0\n break\n return profit", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n final = 0\n cur = 0\n for i in range(n):\n if cur + arr[i].weight <= W:\n cur += arr[i].weight\n final += arr[i].value\n else:\n rem = W - cur\n final += arr[i].value / arr[i].weight * rem\n break\n return final", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n ans = 0\n vpp = []\n for ob in arr:\n (w, v) = (ob.weight, ob.value)\n vpp.append([v / w, v, w])\n vpp.sort()\n while vpp and W:\n (vp, v, w) = vpp.pop()\n if W >= w:\n W -= w\n ans += v\n else:\n ans += W * vp\n W -= W\n return ans", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n for a in arr:\n a.avg = a.value / a.weight\n arr.sort(key=lambda x: x.avg, reverse=True)\n (final_val, i) = (0, 0)\n while W > 0 and i < n:\n if arr[i].weight < W:\n final_val += arr[i].value\n W -= arr[i].weight\n else:\n final_val += W * arr[i].avg\n W = 0\n i += 1\n return final_val", "import heapq\n\ndef __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n\n class Wrapper:\n\n def __init__(self, item):\n self.val = item.value / item.weight\n self.w = item.weight\n\n def __lt__(self, other):\n return self.val > other.val\n h = [Wrapper(a) for a in arr]\n heapq.heapify(h)\n value = 0\n w = 0\n while w < W and h:\n item = heapq.heappop(h)\n tmp = min(item.w, W - w)\n w += tmp\n value += tmp * item.val\n return value", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n total_value = 0.0\n current_weight = 0\n for i in range(n):\n if current_weight + arr[i].weight <= W:\n current_weight += arr[i].weight\n total_value += arr[i].value\n else:\n remaining_weight = W - current_weight\n fraction = remaining_weight / arr[i].weight\n total_value += fraction * arr[i].value\n break\n return total_value", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n result = 0\n current_cap = W\n for i in arr:\n if i.weight <= current_cap:\n current_cap -= i.weight\n result += i.value\n else:\n result += i.value * (current_cap / i.weight)\n break\n return result", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, Items, n):\n Items.sort(key=lambda x: x.value / x.weight, reverse=True)\n res = 0\n for i in Items:\n if i.weight <= W:\n res += i.value\n W -= i.weight\n else:\n temp = i.value / i.weight * W\n res += temp\n W = 0\n return res", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n i = 0\n res = 0\n while W > 0 and i < n and (arr[i].weight <= W):\n W -= arr[i].weight\n res += arr[i].value\n i += 1\n if W > 0 and i < n:\n res += arr[i].value * (W / arr[i].weight)\n return res", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n val = []\n for i in range(n):\n val.append([arr[i].value / arr[i].weight, arr[i].weight, arr[i].value])\n\n def sort(arr1):\n arr1 = sorted(arr1, key=lambda x: x[0], reverse=True)\n return arr1\n val1 = sort(val)\n pro = 0\n for i in range(n):\n if W >= val1[i][1]:\n W -= val1[i][1]\n pro = pro + val1[i][2]\n else:\n pro = pro + val1[i][2] * W / val1[i][1]\n break\n return pro", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n ratios = []\n for i in range(n):\n ratios.append([i, arr[i].value / arr[i].weight])\n ratios = sorted(ratios, key=lambda x: x[1], reverse=True)\n (capacity, value) = (0, 0)\n for i in range(len(ratios)):\n if capacity + arr[ratios[i][0]].weight < W:\n value += arr[ratios[i][0]].value\n capacity += arr[ratios[i][0]].weight\n else:\n x = W - capacity\n value += x * ratios[i][1]\n break\n return value", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n l = []\n for i in arr:\n l.append((i.value / i.weight, i.value, i.weight))\n l = sorted(l, key=lambda x: x[0], reverse=True)\n cap = 0\n for i in l:\n if i[2] > W:\n val = i[0] * W\n cap += val\n W = 0\n break\n cap += i[1]\n W -= i[2]\n return cap", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n\n def myfunct(ele):\n return ele.value / ele.weight\n arr.sort(reverse=True, key=myfunct)\n ans = 0\n for i in arr:\n if i.weight <= W:\n ans += i.value\n W -= i.weight\n else:\n ans += W * (i.value / i.weight)\n break\n return ans", "import math\n\ndef __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.weight / x.value, reverse=False)\n p = 0\n for i in arr:\n if i.weight <= W:\n p += i.value\n W -= i.weight\n elif i.weight > W:\n p += W / i.weight * i.value\n W = 0\n break\n return p", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n curr_weight = 0\n max_value = 0\n for i in range(n):\n if arr[i].weight + curr_weight <= W:\n curr_weight += arr[i].weight\n max_value += arr[i].value\n else:\n left_weight = W - curr_weight\n max_value += arr[i].value * left_weight / arr[i].weight\n break\n return max_value", "import heapq\n\ndef __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n heap = []\n for (i, item) in enumerate(arr):\n heap.append([-item.value / item.weight, i])\n heapq.heapify(heap)\n remaining_capacity = W\n res = 0\n while heap and remaining_capacity > 0:\n (value_per_weight, index) = heapq.heappop(heap)\n value_per_weight *= -1\n if arr[index].weight > remaining_capacity:\n res += value_per_weight * remaining_capacity\n break\n else:\n res += arr[index].value\n remaining_capacity -= arr[index].weight\n return res", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n s = ans = wt = 0\n fact = []\n for i in range(n):\n fact.append([arr[i].value / arr[i].weight, i])\n fact = sorted(fact, reverse=True)\n for i in range(n):\n if wt + arr[fact[i][1]].weight <= W:\n ans += arr[fact[i][1]].value\n wt += arr[fact[i][1]].weight\n else:\n x = W - wt\n ans += fact[i][0] * x\n break\n return ans", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, Items, n):\n Items.sort(key=lambda x: x.value / x.weight, reverse=True)\n value = 0\n for item in Items:\n if item.weight <= W:\n W -= item.weight\n value += item.value\n elif item.weight > W:\n value += item.value * W / item.weight\n W = 0\n break\n return value", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef __str__():\n return str(self.value)\n\ndef __repr__():\n return 'Item value:% s weight:% s' % (self.value, self.weight)\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda item: item.value / item.weight, reverse=True)\n idx = 0\n value = 0.0\n while W > 0 and idx < len(arr):\n if arr[idx].weight <= W:\n value += arr[idx].value\n W -= arr[idx].weight\n else:\n value += W / arr[idx].weight * arr[idx].value\n W -= W", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n vw = []\n for i in range(n):\n v = arr[i].value\n w = arr[i].weight\n vw.append([v / w, v, w])\n vw.sort()\n vw.reverse()\n ans = 0\n for (r, v, w) in vw:\n if W - w >= 0:\n ans += v\n W -= w\n else:\n ans += W / w * v\n break\n return ans", "from operator import itemgetter\n\ndef __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, N):\n values = []\n weight = []\n for i in range(n):\n values.append(arr[i].value)\n weight.append(arr[i].weight)\n valuability = []\n for i in range(len(values)):\n valuability.append([values[i] / weight[i], weight[i]])\n res = sorted(valuability, key=itemgetter(0), reverse=True)\n total = 0\n for i in res:\n if i[1] < W:\n W -= i[1]\n total += i[0] * i[1]\n elif W > 0:\n total += i[0] * W\n W = 0\n return total", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n ans = []\n for i in range(0, n):\n perunit = arr[i].value / arr[i].weight\n ans.append([perunit, arr[i].value, arr[i].weight])\n ans.sort(key=lambda x: x[0], reverse=True)\n total = 0\n for i in range(0, n):\n if ans[i][2] > W:\n total += W * ans[i][0]\n W = 0\n else:\n total += ans[i][1]\n W -= ans[i][2]\n return total", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n curweight = 0\n a = []\n for i in range(n):\n v = [arr[i].value, arr[i].weight]\n a.append(v)\n a.sort(key=lambda x: x[0] / x[1], reverse=True)\n i = 0\n finalvalue = 0\n while curweight < W and i < n:\n if curweight + a[i][1] < W:\n curweight = curweight + a[i][1]\n finalvalue += a[i][0]\n else:\n new = W - curweight\n finalvalue += a[i][0] * new / a[i][1]\n curweight += new\n i += 1\n return finalvalue", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n (u, tp) = (W, 0)\n dp = [0] * n\n i = 0\n while i < n:\n if arr[i].weight > u:\n break\n dp[i] = 1\n tp += arr[i].value\n u -= arr[i].weight\n i += 1\n if i < n:\n dp[i] = u / arr[i].weight\n tp += dp[i] * arr[i].value\n return tp", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr = sorted(arr, key=lambda x: x.value / x.weight, reverse=True)\n rem_weight = W\n tot_value = 0\n i = 0\n while rem_weight > 0:\n if i == n:\n return tot_value\n if arr[i].weight < rem_weight:\n rem_weight -= arr[i].weight\n tot_value = tot_value + arr[i].value\n i += 1\n else:\n alpha = arr[i].value / arr[i].weight\n tot_value = tot_value + rem_weight * alpha\n break\n return tot_value", "def __init__(val, w):\n self.value = val\n self.weight = w\n self.valForMoney = val / weight\n\ndef fractionalknapsack(W, arr, n):\n arr = [(i.value / i.weight, i) for i in arr]\n arr.sort(key=lambda a: -a[0])\n profits = 0\n for i in arr:\n if i[1].weight <= W:\n (W, profits) = (W - i[1].weight, profits + i[1].value)\n elif W == 0:\n break\n else:\n (W, profits) = (0, profits + W * i[0])\n return profits", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.weight / x.value)\n curr = W\n i = 0\n rw = 0\n while curr != 0.0 and i < n:\n if arr[i].weight <= curr:\n curr -= arr[i].weight\n rw += arr[i].value\n i += 1\n else:\n rw += curr / arr[i].weight * arr[i].value\n return rw\n return rw", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n frec = []\n for i in range(n):\n perUnit = arr[i].value / arr[i].weight\n frec.append([perUnit, arr[i].value, arr[i].weight])\n totalVal = 0\n frec.sort(key=lambda x: x[0], reverse=True)\n for i in range(n):\n if frec[i][2] > W:\n totalVal += W * frec[i][0]\n W = 0\n else:\n totalVal += frec[i][1]\n W = W - frec[i][2]\n return totalVal", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n rat = [[it.weight, it.value, it.value / it.weight] for it in arr]\n sor = sorted(rat, key=lambda itm: itm[2], reverse=True)\n cur_cap = W\n total_val = 0\n for i in range(n):\n if sor[i][0] <= cur_cap:\n total_val += sor[i][1]\n cur_cap -= sor[i][0]\n else:\n wt = cur_cap\n total_val += wt * sor[i][2]\n break\n return total_val", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda a: a.value / a.weight, reverse=True)\n result = 0.0\n for item in arr:\n if W == 0:\n return result\n if item.weight <= W:\n result += item.value\n W -= item.weight\n else:\n result += item.value * W / item.weight\n W = 0\n return result", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n l = []\n profit = 0\n for i in arr:\n l.append((i.value, i.weight, i.value / i.weight))\n l.sort(key=lambda x: x[2], reverse=True)\n for (i, j, k) in l:\n if j <= W:\n profit += i\n W -= j\n else:\n profit += k * W\n W = 0\n break\n return profit", "def __init__(val, w):\n self.value = val\n self.weight = w\n self.unit = 0\n\ndef fractionalknapsack(W, arr, n):\n for i in range(n):\n arr[i].unit = arr[i].value / arr[i].weight\n ans = 0\n arr.sort(key=lambda x: -x.unit)\n i = 0\n while i < n and W > 0:\n ans += arr[i].unit * min(arr[i].weight, W)\n W -= arr[i].weight\n i += 1\n return ans", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n res = 0\n for elem in arr:\n if elem.weight <= W:\n res += elem.value\n W -= elem.weight\n else:\n res += elem.value / elem.weight * W\n return res\n return res", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n new_arr = []\n val = 0\n for i in range(n):\n compute = arr[i].value / arr[i].weight\n new_arr.append([compute, i])\n new_arr.sort(reverse=True)\n s = 0\n for i in range(n):\n y = arr[new_arr[i][1]].weight\n if W >= s + y:\n val += arr[new_arr[i][1]].value\n s += y\n else:\n val += (W - s) * new_arr[i][0]\n break\n return val", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n data = [[e.value, e.weight, e.value / e.weight] for e in arr]\n data.sort(key=lambda x: x[2], reverse=True)\n k = 0\n res = 0\n while W != 0 and k < n:\n if data[k][1] <= W:\n res += data[k][0]\n W -= data[k][1]\n k += 1\n else:\n res += data[k][2] * W\n W = 0\n break\n return res", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n new_arr = []\n for obj in arr:\n new_arr.append((obj.value / obj.weight, obj))\n new_arr.sort(key=lambda x: -x[0])\n total_value = 0\n for (per_unit_val, obj) in new_arr:\n if obj.weight <= W:\n total_value += obj.value\n W -= obj.weight\n else:\n total_value += W * per_unit_val\n W = 0\n break\n return total_value", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef __repr__():\n return '(' + str(self.value) + ',' + str(self.weight) + ')'\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n sum_value = 0.0\n curr_wt = 0.0\n for item in arr:\n if curr_wt + item.weight <= W:\n sum_value += item.value\n curr_wt += item.weight\n else:\n remain = W - curr_wt\n sum_value += item.value / item.weight * remain\n break\n return sum_value", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n new_arr = []\n for i in range(n):\n per_unit_val = arr[i].value / arr[i].weight\n new_arr.append((per_unit_val, arr[i]))\n new_arr.sort(key=lambda x: x[0], reverse=True)\n total_value = 0\n for i in range(n):\n if new_arr[i][1].weight > W:\n total_value += W * new_arr[i][0]\n W = 0\n break\n else:\n total_value += new_arr[i][1].value\n W -= new_arr[i][1].weight\n return total_value", "from heapq import heapify, heappop, heappush\n\ndef __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n ans = 0\n heap = []\n for i in range(n):\n a = arr[i].value / arr[i].weight\n heappush(heap, [-a, arr[i].weight])\n while heap and W > 0:\n (a, b) = heappop(heap)\n x = min(W, b)\n ans += -a * x\n W -= x\n return ans", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n d = 0\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n for sack in arr:\n if W == 0:\n return d\n if sack.weight > W:\n d += W * (sack.value / sack.weight)\n W = 0\n break\n else:\n W -= sack.weight\n d += sack.value\n return d", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n ratios = [(item.value / item.weight, item.value, item.weight) for item in arr]\n ratios.sort(reverse=True)\n total_value = 0\n remaining_weight = W\n for (ratio, value, weight) in ratios:\n if remaining_weight == 0:\n break\n elif weight <= remaining_weight:\n total_value += value\n remaining_weight -= weight\n else:\n total_value += ratio * remaining_weight\n remaining_weight = 0\n return total_value"], "starter_code": "def __init__(val,w):\n", "input_output": {"inputs": ["N = 3, W = 50\r\nvalues[] = {60,100,120}\r\nweight[] = {10,20,30}", "N = 2, W = 50\r\nvalues[] = {60,100}\r\nweight[] = {10,20}"], "outputs": ["240.00", "160.00"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Greedy"], "name": null, "source": "geeksforgeeks", "tags": ["Greedy algorithms"], "skill_types": ["Greedy algorithms"], "url": "https://practice.geeksforgeeks.org/problems/fractional-knapsack-1587115620/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(NlogN)", "entry_point": "__init__", "task_id": "TACO_lite/507", "example": [[], []]} +{"requirement": "# Convert number to reversed array of digits\n\nGiven a random non-negative number, you have to return the digits of this number within an array in reverse order.\n\n## Example:\n\n```\n348597 => [7,9,5,8,4,3]\n```", "solutions": ["def digitize(n):\n return [int(x) for x in str(n)[::-1]]", "def digitize(n):\n return [int(x) for x in reversed(str(n))]", "def digitize(n):\n result = []\n while n >= 1:\n result.append(n % 10)\n n //= 10\n return result", "def digitize(n):\n return [int(c) for c in str(n)[::-1]]", "def digitize(n):\n l = []\n m = []\n n = str(n)\n n = n[::-1]\n for i in range(len(n)):\n l.append(int(n[i]))\n return l", "def digitize(n):\n return [int(i) for i in str(n)][::-1]", "def digitize(n):\n return list(reversed([int(s) for s in str(n)]))", "def digitize(n):\n mylist = [int(i) for i in str(n)]\n mylist.reverse()\n return mylist", "def digitize(n):\n (d, r) = divmod(n, 10)\n if d:\n return [r] + digitize(d)\n else:\n return [r]", "def digitize(n):\n new_list = list((int(x) for x in str(n)))\n return new_list[::-1]", "import re\n\ndef digitize(n):\n answer = []\n l = re.findall('\\\\d', str(n))\n for i in l:\n answer.append(int(i))\n answer.reverse()\n return answer", "def digitize(n):\n num_array = []\n for number in str(n):\n num_array.insert(0, int(number))\n return num_array", "def digitize(n):\n result = []\n while n > 0:\n result.append(n % 10)\n n = int(n / 10)\n return result", "digitize = lambda n: [int(e) for e in str(n)[::-1]]", "digitize = lambda n: [int(x) for x in str(n)][::-1]", "def digitize(n):\n n = str(n)\n arr = []\n for u in n:\n arr.append(int(u))\n arr = arr[::-1]\n return arr", "digitize = lambda n: [int(x) for x in reversed(str(n))]", "def digitize(n):\n return [int(digit) for digit in str(n)[::-1]]", "def digitize(n):\n return [int(d) for d in str(n)[::-1]]", "digitize = lambda n: list(reversed([int(i) for i in str(n)]))", "def digitize(n):\n return [int(i) for i in reversed(str(n))]", "def digitize(n):\n k = [int(num) for num in str(n)]\n k.reverse()\n return k", "def digitize(n):\n b = []\n for i in str(n):\n b.append(int(i))\n return b[::-1]", "def digitize(n):\n output = []\n for digit in str(n):\n output.append(int(digit))\n return output[::-1]", "def digitize(n):\n n = str(n)\n n_list = list(map(int, str(n)))\n n_list.reverse()\n return n_list", "def digitize(n):\n n = str(n)\n l = []\n c = list(n)\n c.reverse()\n for i in c:\n l.append(int(i))\n return l", "def digitize(n):\n a = []\n while n != 0:\n a.append(n % 10)\n n = n // 10\n return a", "def digitize(n):\n arr = []\n result = n\n shouldGo = True\n while shouldGo:\n arr.append(result % 10)\n result = result // 10\n if result == 0:\n shouldGo = False\n return arr", "def digitize(n):\n arr = []\n convertToString = str(n)\n for num in convertToString:\n arr.append(int(num))\n arr.reverse()\n return arr", "def digitize(n):\n return list(map(int, str(n)))[::-1]", "def digitize(n):\n d = [int(i) for i in str(n)]\n p = d[::-1]\n return p", "def digitize(n):\n result = []\n for d in str(n)[::-1]:\n result.append(int(d))\n return result", "def digitize(n):\n lista = str(n)\n listan = list(lista)\n listan.reverse()\n for i in range(0, len(listan)):\n listan[i] = int(listan[i])\n return listan", "def digitize(n):\n n = str(n)\n digits = [int(s) for s in n]\n return digits[::-1]", "def digitize(n):\n return [n % 10] + digitize(n // 10) if n > 10 else [n % 10]", "def digitize(n):\n ls = list(str(n))\n a = ls[::-1]\n return [int(x) for x in a]", "def digitize(n):\n r = []\n res = str(n)\n for i in res:\n r.append(int(i))\n return r[::-1]", "def digitize(n):\n a = [int(x) for x in str(n)]\n b = a[::-1]\n return b", "def digitize(n):\n num = []\n z = str(n)\n for i in z:\n num.append(int(i))\n return num[::-1]", "def digitize(n):\n x = str(n)\n y = ''\n lst = []\n for char in x:\n y = char + y\n for char in y:\n lst.append(int(char))\n return lst", "def digitize(n):\n result = array = [int(x) for x in str(n)]\n result = result[::-1]\n return result", "digitize = lambda input: [int(x) for x in str(input)][::-1]", "def digitize(n):\n rez = []\n for i in list(str(n)[::-1]):\n rez.append(int(i))\n return rez", "def digitize(n):\n x = ','.join(str(n))[::-1]\n result = []\n for i in x.split(','):\n result.append(int(i))\n return result", "def digitize(n):\n str_arr = list(str(n)[::-1])\n int_arr = []\n for i in str_arr:\n int_arr.append(int(i))\n return int_arr", "def digitize(num):\n if len(str(num)) == 1:\n return num\n output = []\n for n in reversed(str(num)):\n output.append(int(n))\n return output", "def digitize(n):\n results = []\n for num in str(n)[::-1]:\n results.append(int(num))\n return results", "def digitize(n):\n results = []\n for x in range(len(str(n))):\n results.append(int(str(n)[len(str(n)) - x - 1]))\n return results", "def digitize(n):\n string_of_int = str(n)\n final_array = [int(x) for x in string_of_int]\n return final_array[::-1]", "def digitize(n):\n list = []\n while n > 0:\n list.append(int(n % 10))\n n = int(n / 10)\n return list", "def digitize(n):\n n = str(n)\n l = list()\n n = n[::-1]\n for s in n:\n l.append(int(s))\n return l", "def digitize(n):\n num = [int(m) for m in str(n)]\n return num[::-1]", "def digitize(n):\n mylist = []\n a = list(str(n))\n for i in a:\n mylist.append(int(i))\n mylist.reverse()\n return mylist", "def digitize(n):\n d = [int(array) for array in list(str(n))]\n d.reverse()\n return d", "def digitize(n):\n a = list(reversed(str(n)))\n k = []\n for i in a:\n k.append(int(i))\n return k", "def digitize(n):\n string_num = str(n)\n digits = []\n for digit in string_num:\n digits.append(int(digit))\n digits.reverse()\n return digits", "def digitize(n):\n n = str(n)\n n = list(n)\n n = list(map(conv, n))\n n.reverse()\n return n\n\ndef conv(x):\n return int(x)", "def digitize(n):\n copy = []\n array = list(str(n))\n for num in array:\n copy.append(int(num))\n copy.reverse()\n return copy", "def digitize(n):\n lista = list(str(n))\n lista.reverse()\n int_list = []\n for i in lista:\n int_list.append(int(i))\n return int_list", "def digitize(n):\n list_n = list(str(n))\n list_n.reverse()\n return list(map(int, list_n))", "def digitize(n):\n string_num = str(n)\n res = []\n comp = [res.append(int(number)) for number in string_num]\n res.reverse()\n return res", "def digitize(n):\n empty = []\n n = str(n)\n n = n[::-1]\n for num in n:\n empty.append(int(num))\n return empty", "def digitize(n):\n s = list(reversed(str(n)))\n a = []\n for x in s:\n m = int(x)\n a.append(m)\n return a", "def digitize(n):\n result = []\n if n == 0:\n return [0]\n while n:\n result.append(n % 10)\n n //= 10\n return result", "def digitize(n):\n n = str(n)\n n = n[::-1]\n n = ' '.join(n)\n return [int(i) for i in n.split()]", "def digitize(n):\n x = list(str(n))\n y = []\n for i in range(len(x) - 1, -1, -1):\n y.append(int(x[i]))\n return y", "import numpy as np\n\ndef digitize(n):\n return [int(i) for i in str(n)[::-1]]", "def digitize(n):\n x = list(map(lambda x: int(x), list(str(n))))\n x.reverse()\n return x", "def digitize(n):\n ls = []\n for i in range(len(str(n))):\n ls.append(n % 10)\n n //= 10\n return ls", "def digitize(n):\n s = str(n)\n a = []\n for i in range(1, len(s) + 1):\n a.append(s[-i])\n for j in range(len(a)):\n a[j] = int(a[j])\n return a", "def digitize(n):\n listn = []\n for x in str(n):\n listn.append(int(x))\n revl = listn[::-1]\n return revl", "def digitize(n):\n arr = list(str(n))\n rev = []\n for i in arr:\n rev.insert(0, int(i))\n return rev", "def digitize(n):\n result = list((int(x) for x in str(n)))\n return result[::-1]", "def digitize(n):\n res = [int(i) for i in list(str(n))]\n return res[::-1]", "def digitize(n):\n num_list = list(str(n))\n reversed_num_list = num_list.reverse()\n reversed_num_list = list(map(int, num_list))\n return reversed_num_list", "def digitize(n):\n lst = []\n n = str(n)\n for char in n:\n lst.append(int(char))\n lst = lst[::-1]\n return lst", "def digitize(n):\n array = []\n n = str(n)\n x = len(n) - 1\n while x >= 0:\n array.append(int(n[x]))\n x -= 1\n return array", "def digitize(n):\n n = str(n)\n l = []\n for elem in n:\n l.append(int(elem))\n l.reverse()\n return l", "digitize = lambda n: [int(digit) for digit in str(n)][::-1]", "def digitize(n):\n n = list(str(n))\n l = []\n for i in n:\n a = int(i)\n l.append(a)\n return l[::-1]", "def digitize(n):\n new = []\n for I in str(n):\n new.append(int(I))\n return new[::-1]", "def digitize(n):\n len_n = str(n)\n list = []\n for i in range(0, len(len_n)):\n a = n % 10\n n = n // 10\n list.append(a)\n return list"], "starter_code": "def digitize(n):\n", "input_output": {"fn_name": "digitize", "inputs": [[35231], [23582357], [984764738], [45762893920], [548702838394]], "outputs": [[[1, 3, 2, 5, 3]], [[7, 5, 3, 2, 8, 5, 3, 2]], [[8, 3, 7, 4, 6, 7, 4, 8, 9]], [[0, 2, 9, 3, 9, 8, 2, 6, 7, 5, 4]], [[4, 9, 3, 8, 3, 8, 2, 0, 7, 8, 4, 5]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5583090cbe83f4fd8c000051", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "digitize", "task_id": "TACO_lite/510", "example": [[[348597]], ["[7, 9, 5, 8, 4, 3]"]]} +{"requirement": "You need to play around with the provided string (s).\n\nMove consonants forward 9 places through the alphabet.\nIf they pass 'z', start again at 'a'.\n\nMove vowels back 5 places through the alphabet.\nIf they pass 'a', start again at 'z'.\nFor our Polish friends this kata does not count 'y' as a vowel.\n\nExceptions:\n\nIf the character is 'c' or 'o', move it back 1 place.\nFor 'd' move it back 3, and for 'e', move it back 4.\n\nIf a moved letter becomes 'c', 'o', 'd' or 'e', revert it back to it's original value.\n\nProvided string will always be lower case, won't be empty and will have no special characters.", "solutions": ["def vowel_back(st):\n return st.translate(str.maketrans('abcdefghijklmnopqrstuvwxyz', 'vkbaafpqistuvwnyzabtpvfghi'))", "def vowel_back(s):\n return s.translate(str.maketrans('abcdeghjklmnopqrsuwxyz', 'vkbaapqstuvwnyzabpfghi'))", "from string import ascii_lowercase as abc\n\ndef vowel_back(st):\n return st.translate(str.maketrans(abc, 'vkbaafpqistuvwnyzabtpvfghi'))", "from collections import ChainMap\nfrom string import ascii_lowercase as al\nmove = ChainMap(dict(c=-1, o=-1, d=-3, e=-4), dict.fromkeys('aeiou', -5), dict.fromkeys(al, 9))\nnew = (al[(i + move[c]) % 26] for (i, c) in enumerate(al))\nmapping = {c: c if c2 in 'code' else c2 for (c, c2) in zip(al, new)}\n\ndef vowel_back(st):\n return ''.join(map(mapping.get, st))", "from string import ascii_lowercase as aLow\n\ndef shifterAndSrc(c):\n return (chr((ord(c) + SHIFT.get(c, DEFAULT) - 97) % 26 + 97), c)\nSHIFT = {'a': -5, 'e': -4, 'i': -5, 'o': -1, 'u': -5, 'c': -1, 'd': -3}\n(DEFAULT, REVERT) = (9, 'code')\nTABLE = str.maketrans(aLow, ''.join((c if c not in REVERT else o for (c, o) in map(shifterAndSrc, aLow))))\n\ndef vowel_back(s):\n return s.translate(TABLE)", "vowel_back = lambda s: ''.join((e[e[0] in 'code'] for e in [(chr(ord(x) - max(1, 'co de'.index(x)) if x in 'code' else 97 + (ord(x) - 97 - 5 if x in 'aiu' else ord(x) - 97 + 9) % 26), x) for x in s]))", "def vowel_back(st):\n s = ''\n for x in st:\n res = chr(ord('a') + (ord(x) - ord('a') + ((9, -1, -3)[(x == 'c') + (x == 'd') * 2], -(5, 1, 4)[(x == 'o') + (x == 'e') * 2])[x in 'aoiue']) % 26)\n if res in 'code':\n res = x\n s += res\n return s", "trans = str.maketrans('abcdeghjklmnopqrsuwxyz', 'vkbaapqstuvwnyzabpfghi')\n\ndef vowel_back(st):\n return st.translate(trans)", "from string import ascii_lowercase as alpha\nalpha = list(alpha)\nln = len(alpha)\nvowels = 'aeiou'\n\ndef vowel_back(s):\n s = list(s)\n for (idx, char) in enumerate(s):\n index = alpha.index(char)\n if char in ('c', 'o'):\n s[idx] = alpha[index - 1]\n elif char == 'd':\n s[idx] = alpha[index - 3]\n elif char == 'e':\n s[idx] = alpha[index - 4]\n elif char in vowels:\n s[idx] = alpha[index - 5]\n else:\n index += 9\n index = index % ln\n s[idx] = alpha[index]\n if s[idx] in ('c', 'o', 'd', 'e'):\n s[idx] = char\n return ''.join(s)"], "starter_code": "def vowel_back(st):\n", "input_output": {"fn_name": "vowel_back", "inputs": [["testcase"], ["codewars"], ["exampletesthere"], ["returnofthespacecamel"], ["bringonthebootcamp"], ["weneedanofficedog"]], "outputs": [["tabtbvba"], ["bnaafvab"], ["agvvyuatabtqaaa"], ["aatpawnftqabyvbabvvau"], ["kaiwpnwtqaknntbvvy"], ["fawaaavwnffibaanp"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Algorithms", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57cfd92c05c1864df2001563", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "vowel_back", "task_id": "TACO_lite/357", "example": [[["hello"], ["programming"]], ["czggj", "udwdwtmowjx"]]} +{"requirement": "Implement a function which behaves like the uniq command in UNIX.\n\nIt takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance.\n\nExample:\n\n```\n[\"a\", \"a\", \"b\", \"b\", \"c\", \"a\", \"b\", \"c\"] => [\"a\", \"b\", \"c\", \"a\", \"b\", \"c\"]\n```", "solutions": ["from itertools import groupby\n\ndef uniq(seq):\n return [k for (k, _) in groupby(seq)]", "def uniq(seq):\n if len(seq) == 0:\n return []\n rez = [seq[0]]\n for i in range(1, len(seq)):\n if seq[i] != rez[-1]:\n rez.append(seq[i])\n return rez", "from itertools import groupby\n\ndef uniq(a):\n return [x for (x, _) in groupby(a)]", "def uniq(seq):\n return [c for (i, c) in enumerate(seq) if i == 0 or seq[i - 1] != c]", "def uniq(seq):\n return [seq[0]] + [seq[i] for i in range(1, len(seq)) if seq[i] != seq[i - 1]] if seq else []", "def uniq(seq):\n result = []\n for q in seq:\n if result and result[-1] == q:\n continue\n result.append(q)\n return result", "def uniq(seq):\n ans = []\n p = ''\n for i in seq:\n if i != p:\n ans.append(i)\n p = i\n return ans if len(seq) > 1 else seq", "from itertools import groupby\nfrom operator import itemgetter\n\ndef uniq(seq):\n return list(map(itemgetter(0), groupby(seq)))", "from itertools import groupby\n\ndef uniq(seq):\n return [k[0] for k in groupby(seq)]"], "starter_code": "def uniq(seq):\n", "input_output": {"fn_name": "uniq", "inputs": [[["a", "a", "b", "b", "c", "a", "b", "c", "c"]], [["a", "a", "a", "b", "b", "b", "c", "c", "c"]], [[]], [["foo"]], [["bar"]], [[""]], [[null, "a", "a"]]], "outputs": [[["a", "b", "c", "a", "b", "c"]], [["a", "b", "c"]], [[]], [["foo"]], [["bar"]], [[""]], [[null, "a"]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms", "Filtering"], "name": null, "source": "codewars", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/52249faee9abb9cefa0001ee", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "uniq", "task_id": "TACO_lite/476", "example": [[[["a", "a", "b", "b", "c", "a", "b", "c"]]], ["['a', 'b', 'c', 'a', 'b', 'c']"]]} +{"requirement": "Given an array (a list in Python) of integers and an integer `n`, find all occurrences of `n` in the given array and return another array containing all the index positions of `n` in the given array.\n\nIf `n` is not in the given array, return an empty array `[]`.\n\nAssume that `n` and all values in the given array will always be integers.\n\nExample:\n```python\nfind_all([6, 9, 3, 4, 3, 82, 11], 3)\n> [2, 4]\n```", "solutions": ["def find_all(array, n):\n return [index for (index, item) in enumerate(array) if item == n]", "def find_all(array, n):\n res = []\n for i in range(len(array)):\n if array[i] == n:\n res.append(i)\n return res", "def find_all(array, n):\n return [i for (i, v) in enumerate(array) if v == n]", "def find_all(array, n):\n return [i for (i, x) in enumerate(array) if x == n]", "def find_all(array, n):\n return [i for i in range(len(array)) if array[i] == n]", "def find_all(array, n):\n return [i[0] for i in enumerate(array) if i[1] == n]", "def find_all(array, n):\n l = []\n for (i, v) in enumerate(array):\n if v == n:\n l.append(i)\n return l", "import numpy as np\n\ndef find_all(array, n):\n return list(np.where(np.array(array) == n)[0])", "def find_all(array, n):\n return [pos for (pos, number) in enumerate(array) if number == n]", "def find_all(array, n):\n return [i for (i, number) in enumerate(array) if number == n]"], "starter_code": "def find_all(array, n):\n", "input_output": {"fn_name": "find_all", "inputs": [[[6, 9, 3, 4, 3, 82, 11], 3], [[6, 9, 3, 4, 3, 82, 11], 99], [[10, 16, 20, 6, 14, 11, 20, 2, 17, 16, 14], 16], [[20, 20, 10, 13, 15, 2, 7, 2, 20, 3, 18, 2, 3, 2, 16, 10, 9, 9, 7, 5, 15, 5], 20]], "outputs": [[[2, 4]], [[]], [[1, 9]], [[0, 1, 8]]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/59a9919107157a45220000e1", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "find_all", "task_id": "TACO_lite/542", "example": [[[[6, 9, 3, 4, 3, 82, 11], 3]], ["[2, 4]"]]} +{"requirement": "Given an NxN chessboard and a Knight at position (x, y). The Knight has to take exactly K steps, where at each step it chooses any of the 8 directions uniformly at random. Find the probability that the Knight remains in the chessboard after taking K steps, with the condition that it cant enter the board again once it leaves it.\n \nExample 1:\nInput : N = 8, x = 0, y = 0, K = 3\nOutput: 0.125000\nExample 2:\nInput: N = 4, x = 1, y = 2, k = 4\nOutput: 0.024414\n \nYour Task: \nYou don't need to read or print anything. Your task is to complete the function findProb() which takes N, x, y and K as input parameter and returns the probability.\n \nExpected Time Complexity : O(N ^{3})\nExpected Space Complexity: O(N^{3})\n \nConstraints:\n1 <= N <= 100\n0 <= x, y <= N\n0 <= K <= N", "solutions": ["from functools import lru_cache\n\ndef findprob(n, r, c, k):\n dir = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n\n def solve(x, y, t):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if t == 0:\n return 1\n ans = 0\n for (i, j) in dir:\n ans += solve(x + i, y + j, t - 1)\n return ans\n return solve(r, c, k) / 8 ** k", "def helper(start_x, start_y, dir_x, dir_y, dp, steps, N):\n if start_x >= 0 and start_x < N and (start_y >= 0) and (start_y < N) and (steps == 0):\n return 1\n if start_x < 0 or start_x >= N or start_y < 0 or (start_y >= N):\n return 0\n if dp[start_x][start_y][steps] != -1:\n return dp[start_x][start_y][steps]\n else:\n total_moves = 0\n for i in range(8):\n total_moves += self.helper(start_x + dir_x[i], start_y + dir_y[i], dir_x, dir_y, dp, steps - 1, N) * (1 / 8)\n dp[start_x][start_y][steps] = total_moves\n return dp[start_x][start_y][steps]\n\ndef findprob(N, start_x, start_y, steps):\n dir_x = [-2, -2, -1, -1, 1, 1, 2, 2]\n dir_y = [-1, 1, -2, 2, -2, 2, -1, 1]\n dp = [[[-1 for i in range(steps + 1)] for i in range(N + 1)] for i in range(N + 1)]\n return self.helper(start_x, start_y, dir_x, dir_y, dp, steps, N)", "from collections import defaultdict\n\ndef findprob(N, row, column, k):\n n = N\n directions = [(-2, -1), (-1, -2), (1, -2), (2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1)]\n memo = {}\n\n def dfs(i, j, k):\n if k == 0:\n return 1\n if (i, j, k) in memo:\n return memo[i, j, k]\n p = 0\n for (di, dj) in directions:\n x = i + di\n y = j + dj\n if x >= 0 and x < n and (y >= 0) and (y < n):\n p += dfs(x, y, k - 1) / 8\n memo[i, j, k] = p\n memo[n - 1 - i, j, k] = p\n memo[i, n - 1 - j, k] = p\n memo[n - 1 - i, n - 1 - j, k] = p\n return p\n return dfs(row, column, k)", "from functools import lru_cache\n\ndef findprob(n, start_x, start_y, steps):\n dir = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n\n def solve(x, y, t):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if t == 0:\n return 1\n ans = 0\n for (i, j) in dir:\n ans += solve(x + i, y + j, t - 1)\n return ans\n return solve(start_x, start_y, steps) / 8 ** steps", "def rec(N, x, y, k, dp):\n if x >= N or x < 0 or y >= N or (y < 0):\n return 0\n elif k < 0:\n return 1\n elif dp[x][y][k] != -1:\n return dp[x][y][k]\n prob = 0\n dx = [-1, -1, -2, -2, 1, 1, 2, 2]\n dy = [-2, 2, -1, 1, 2, -2, 1, -1]\n for i in range(8):\n prob += rec(N, x + dx[i], y + dy[i], k - 1, dp) / 8.0\n dp[x][y][k] = prob\n return dp[x][y][k]\n\ndef findprob(N, start_x, start_y, steps):\n dp = [[[-1 for i in range(steps)] for j in range(N)] for k in range(N)]\n return rec(N, start_x, start_y, steps - 1, dp)", "from functools import lru_cache\n\ndef is_valid(n, x, y):\n if x < 0 or x >= n or y < 0 or (y >= n):\n return False\n return True\n\ndef sol(x, y, t, n):\n dir = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n\n def solve(x, y, t):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if t == 0:\n return 1\n ans = 0\n for (i, j) in dir:\n ans += solve(x + i, y + j, t - 1)\n return ans\n return solve(x, y, t)\n\ndef findprob(N, start_x, start_y, steps):\n return self.sol(start_x, start_y, steps, N) / 8 ** steps", "def findprob(N, start_x, start_y, steps):\n dirs = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)]\n dp = [[0] * N for _ in range(N)]\n dp[start_x][start_y] = 1\n for _ in range(steps):\n newDp = [[0] * N for _ in range(N)]\n for i in range(N):\n for j in range(N):\n for (dx, dy) in dirs:\n x = i + dx\n y = j + dy\n if 0 <= x < N and 0 <= y < N:\n newDp[i][j] += dp[x][y]\n dp = newDp\n return sum(map(sum, dp)) / 8 ** steps", "def findprob(N, start_x, start_y, steps):\n dp = [[[-1 for i in range(steps + 1)] for j in range(N)] for k in range(N)]\n\n def recurs(i, j, s, dp):\n if i < 0 or i >= N or j < 0 or (j >= N):\n return 0\n elif dp[i][j][s] != -1:\n return dp[i][j][s]\n elif s == 0:\n dp[i][j][s] = 1\n return 1\n else:\n su = 0\n for a in [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]:\n su += recurs(i + a[0], j + a[1], s - 1, dp)\n dp[i][j][s] = su / 8\n return su / 8\n recurs(start_x, start_y, steps, dp)\n return dp[start_x][start_y][steps]", "def findprob(N, start_x, start_y, steps):\n dx = [1, 2, 2, 1, -1, -2, -2, -1]\n dy = [2, 1, -1, -2, -2, -1, 1, 2]\n\n def inside(x, y):\n return x >= 0 and x < N and (y >= 0) and (y < N)\n dp1 = [[[0 for i in range(steps + 5)] for j in range(N + 5)] for k in range(N + 5)]\n for i in range(N):\n for j in range(N):\n dp1[i][j][0] = 1\n for s in range(1, steps + 1):\n for x in range(N):\n for y in range(N):\n prob = 0.0\n for i in range(8):\n nx = x + dx[i]\n ny = y + dy[i]\n if inside(nx, ny):\n prob += dp1[nx][ny][s - 1] / 8.0\n dp1[x][y][s] = prob\n return dp1[start_x][start_y][steps]", "def findprob(N, start_x, start_y, steps):\n dp = [[[0] * (steps + 1) for _ in range(N)] for _ in range(N)]\n dp[start_x][start_y][0] = 1\n di = [[1, -2], [2, -1], [2, 1], [1, 2], [-1, 2], [-2, 1], [-2, -1], [-1, -2]]\n for move in range(1, steps + 1):\n for i in range(len(dp)):\n for j in range(len(dp[0])):\n for v in di:\n x = i + v[0]\n y = j + v[1]\n if x >= 0 and x < N and (y >= 0) and (y < N):\n dp[x][y][move] += dp[i][j][move - 1] / 8\n ans = 0\n for i in range(len(dp)):\n for j in range(len(dp[0])):\n ans += dp[i][j][steps]\n return ans", "def findprob(N, start_x, start_y, steps):\n r = start_x\n c = start_y\n n = N\n curr = [[0] * n for j in range(n)]\n next1 = [[0] * n for j in range(n)]\n direction = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)]\n curr[r][c] = 1\n for k in range(steps):\n for i in range(n):\n for j in range(n):\n if curr[i][j] != 0:\n for d in direction:\n ni = i + d[0]\n nj = j + d[1]\n if 0 <= ni < n and 0 <= nj < n:\n next1[ni][nj] += curr[i][j] / 8\n curr = next1\n next1 = [[0] * n for j in range(n)]\n sum1 = 0\n for i in range(n):\n for j in range(n):\n sum1 += curr[i][j]\n return sum1", "def findprob(N, x, y, k):\n dir = [(2, 1), (-2, 1), (2, -1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)]\n\n def isvalid(i, j):\n return i >= 0 and i <= N - 1 and (j >= 0) and (j <= N - 1)\n memo = {}\n\n def dfs(i, j, k):\n if (i, j, k) in memo:\n return memo[i, j, k]\n if not isvalid(i, j):\n return 0\n if k == 0:\n return 1\n prob = 0\n for (x, y) in dir:\n prob += dfs(i + x, j + y, k - 1)\n prob *= 0.125\n memo[i, j, k] = prob\n return prob\n return dfs(x, y, k)", "def findprob(N, start_x, start_y, steps):\n dp = [[[-1 for _ in range(steps + 1)] for _ in range(N)] for _ in range(N)]\n for i in range(N):\n for j in range(N):\n dp[i][j][0] = 1\n res = self.DFS(dp, N, steps, start_x, start_y) / 8 ** steps\n return res\n\ndef DFS(dp, N, steps, x, y):\n if x >= N or x < 0 or y >= N or (y < 0):\n return 0\n if dp[x][y][steps] != -1:\n return dp[x][y][steps]\n cnt = 0\n dx = [-2, -2, -1, -1, 1, 1, 2, 2]\n dy = [-1, 1, -2, 2, -2, 2, -1, 1]\n for i in range(8):\n xx = x + dx[i]\n yy = y + dy[i]\n cnt += self.DFS(dp, N, steps - 1, xx, yy)\n dp[x][y][steps] = cnt\n return cnt", "def prob(i, j, s, N):\n pij = 0\n prev = [(i - 2, j - 1), (i - 2, j + 1), (i - 1, j - 2), (i - 1, j + 2), (i + 1, j - 2), (i + 1, j + 2), (i + 2, j - 1), (i + 2, j + 1)]\n for (ii, jj) in prev:\n pij += self.dp[ii][jj][s - 1] if 0 <= ii < N and 0 <= jj < N else 0\n return pij / 8\n\ndef findprob(N, start_x, start_y, steps):\n self.dp = [[[0] * (steps + 1) for j in range(N)] for i in range(N)]\n self.dp[start_x][start_y][0] = 1\n for s in range(1, steps + 1):\n for i in range(N):\n for j in range(N):\n self.dp[i][j][s] = self.prob(i, j, s, N)\n p = 0\n for i in range(N):\n for j in range(N):\n p += self.dp[i][j][steps]\n return p", "def findprob(N, start_x, start_y, steps):\n dx = [-2, -1, +1, +2, +2, +1, -1, -2]\n dy = [+1, +2, +2, +1, -1, -2, -2, -1]\n dp = [[[0] * (steps + 1) for j in range(N)] for i in range(N)]\n for i in range(N):\n for j in range(N):\n dp[i][j][0] = 1\n for step in range(1, steps + 1):\n for x in range(N):\n for y in range(N):\n dp[x][y][step] = 0\n for i in range(8):\n newx = x + dx[i]\n newy = y + dy[i]\n if newx >= 0 and newx < N and (newy >= 0) and (newy < N):\n dp[x][y][step] += dp[newx][newy][step - 1] / 8.0\n return dp[start_x][start_y][steps]", "def findprob(N, start_x, start_y, steps):\n n = N\n k = steps\n dic = {}\n c = 0\n for x in range(n):\n for y in range(n):\n dic[x, y] = c\n c += 1\n vis = {}\n for j in range(c + 1):\n vis[j] = [-1] * (k + 1)\n\n def fun(x, y, c):\n if c == 0:\n return 1\n else:\n s = 0\n if x - 1 >= 0 and y - 2 >= 0:\n ele = dic[x - 1, y - 2]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x - 1, y - 2, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n if x - 2 >= 0 and y - 1 >= 0:\n ele = dic[x - 2, y - 1]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x - 2, y - 1, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n if x - 2 >= 0 and y + 1 < n:\n ele = dic[x - 2, y + 1]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x - 2, y + 1, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n if x - 1 >= 0 and y + 2 < n:\n ele = dic[x - 1, y + 2]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x - 1, y + 2, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n if x + 1 < n and y + 2 < n:\n ele = dic[x + 1, y + 2]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x + 1, y + 2, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n if x + 2 < n and y + 1 < n:\n ele = dic[x + 2, y + 1]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x + 2, y + 1, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n if x + 2 < n and y - 1 >= 0:\n ele = dic[x + 2, y - 1]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x + 2, y - 1, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n if x + 1 < n and y - 2 >= 0:\n ele = dic[x + 1, y - 2]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x + 1, y - 2, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n return s\n ans = fun(start_x, start_y, steps)\n return ans", "dct = {}\n\ndef findprob(N, start_x, start_y, steps):\n tab = [[[0 for blabla in range(N)] for blablabla in range(N)] for bla in range(steps + 1)]\n moves = [[2, -1], [2, 1], [-2, -1], [-2, 1], [1, 2], [1, -2], [-1, 2], [-1, -2]]\n for step in range(steps + 1):\n for x in range(N):\n for y in range(N):\n for move in moves:\n if step == 0:\n tab[step][x][y] = 1\n else:\n (new_x, new_y) = (x - move[0], y - move[1])\n if 0 <= new_x < N and 0 <= new_y < N:\n tab[step][x][y] += tab[step - 1][new_x][new_y] / 8\n return tab[steps][start_x][start_y]", "from functools import lru_cache\n\ndef findprob(N, start_x, start_y, steps):\n dx = [1, 2, 2, 1, -1, -2, -2, -1]\n dy = [2, 1, -1, -2, -2, -1, 1, 2]\n\n def inside(x, y):\n return x >= 0 and x < N and (y >= 0) and (y < N)\n dp = [[[0] * (steps + 1) for ele in range(N)] for m in range(N)]\n for i in range(N):\n for j in range(N):\n dp[i][j][0] = 1\n for step in range(1, steps + 1):\n for x in range(N):\n for y in range(N):\n prob = 0.0\n for i in range(8):\n nx = x + dx[i]\n ny = y + dy[i]\n if inside(nx, ny):\n prob += dp[nx][ny][step - 1] / 8.0\n dp[x][y][step] = prob\n return dp[start_x][start_y][steps]\n\ndef findprob_ok(n, x, y, steps):\n m = (n - 1) // 2\n\n def helper2(x, y, total):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if total == 0:\n return 1\n if x > m:\n x = n - 1 - x\n if y > m:\n y = n - 1 - y\n res = 0\n for (dx, dy) in [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]:\n res += helper2(x + dx, y + dy, total - 1)\n return res\n return helper2(x, y, steps) / 8 ** steps\n\ndef findprob2(n, x, y, steps):\n\n def helper(x, y, total):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if total == 0:\n return 1\n res = 0\n for (addX, addY) in [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]:\n res += helper(x + addX, y + addY, total - 1)\n return res\n return helper(x, y, steps) / 8 ** steps", "from functools import lru_cache\n\ndef findprob(n, x, y, steps):\n m = (n - 1) // 2\n\n def helper2(x, y, total):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if total == 0:\n return 1\n if x > m:\n x = n - 1 - x\n if y > m:\n y = n - 1 - y\n res = 0\n for (dx, dy) in [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]:\n res += helper2(x + dx, y + dy, total - 1)\n return res\n return helper2(x, y, steps) / 8 ** steps\n\ndef findprob2(n, x, y, steps):\n\n def helper(x, y, total):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if total == 0:\n return 1\n res = 0\n for (addX, addY) in [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]:\n res += helper(x + addX, y + addY, total - 1)\n return res\n return helper(x, y, steps) / 8 ** steps", "from functools import lru_cache\n\ndef findprob(n, r, c, k):\n\n def helper(x, y, total):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if total == 0:\n return 1\n res = 0\n for (addX, addY) in [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]:\n res += helper(x + addX, y + addY, total - 1)\n return res\n return helper(r, c, k) / 8 ** k", "def findprob(N, start_x, start_y, steps):\n prev = [[0 for i in range(N + 4)] for _ in range(N + 4)]\n curr = [[0 for i in range(N + 4)] for _ in range(N + 4)]\n for i in range(2, N + 2):\n for j in range(2, N + 2):\n prev[i][j] = 1\n for k in range(1, steps + 1):\n for i in range(2, N + 2):\n for j in range(2, N + 2):\n ans = 0\n ans += prev[i + 1][j - 2]\n ans += prev[i + 1][j + 2]\n ans += prev[i + 2][j - 1]\n ans += prev[i + 2][j + 1]\n ans += prev[i - 2][j - 1]\n ans += prev[i - 2][j + 1]\n ans += prev[i - 1][j - 2]\n ans += prev[i - 1][j + 2]\n curr[i][j] = ans\n prev = [[k for k in l] for l in curr]\n return prev[start_x + 2][start_y + 2] / pow(8, steps)", "def findprob(N, start_x, start_y, steps):\n\n def fun(i, j, k, n, dp):\n if i < 0 or i > n - 1 or j < 0 or (j > n - 1):\n return 0\n if dp[k][i][j] != -1:\n return dp[k][i][j]\n if k == 0:\n return 1\n ans = 0\n ans += fun(i + 1, j - 2, k - 1, n, dp)\n ans += fun(i + 1, j + 2, k - 1, n, dp)\n ans += fun(i + 2, j - 1, k - 1, n, dp)\n ans += fun(i + 2, j + 1, k - 1, n, dp)\n ans += fun(i - 2, j - 1, k - 1, n, dp)\n ans += fun(i - 2, j + 1, k - 1, n, dp)\n ans += fun(i - 1, j - 2, k - 1, n, dp)\n ans += fun(i - 1, j + 2, k - 1, n, dp)\n dp[k][i][j] = ans\n return dp[k][i][j]\n dp = [[[-1 for i in range(N)] for _ in range(N)] for l in range(steps + 1)]\n return fun(start_x, start_y, steps, N, dp) / pow(8, steps)", "def valid_move(n, x, y):\n return x >= 0 and x < n and (y >= 0) and (y < n)\n\ndef find_prob(n, init_x, init_y, k):\n if k == 0:\n return 1\n mx = [1, 2, 2, 1, -1, -2, -2, -1]\n my = [2, 1, -1, -2, -2, -1, 1, 2]\n dp = [[[0 for i in range(n + 64)] for j in range(n + 64)] for l in range(k + 64)]\n for i in range(n):\n for j in range(n):\n dp[i][j][0] = 1\n for s in range(1, k + 1):\n for x in range(n):\n for y in range(n):\n prob = 0.0\n for i in range(8):\n nx = x + mx[i]\n ny = y + my[i]\n if valid_move(n, nx, ny):\n prob += dp[nx][ny][s - 1] / 8.0\n dp[x][y][s] = prob\n return dp[init_x][init_y][k]\n\ndef findprob(n, init_x, init_y, k):\n return find_prob(n, init_x, init_y, k)", "def findprob(N, start_x, start_y, steps):\n dir = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n present = [[0 for i in range(N)] for j in range(N)]\n next = [[0 for i in range(N)] for j in range(N)]\n present[start_x][start_y] = 1\n for steps in range(0, steps):\n for i in range(N):\n for j in range(N):\n if present[i][j] != 0:\n for change in dir:\n newi = i + change[0]\n newj = j + change[1]\n if newi >= 0 and newi < N and (newj >= 0) and (newj < N):\n next[newi][newj] += present[i][j] / 8\n present = next\n next = [[0 for i in range(N)] for j in range(N)]\n res = 0\n for i in range(N):\n for j in range(N):\n res += present[i][j]\n return res", "def findprob(N, start_x, start_y, steps):\n\n def issafe(r, c):\n if r >= 0 and r < N and (c >= 0) and (c < N):\n return True\n return False\n curr = [[0 for i in range(N)] for j in range(N)]\n nex = [[0 for i in range(N)] for j in range(N)]\n moves = [[2, 1], [2, -1], [-2, -1], [-2, 1], [1, 2], [-1, 2], [1, -2], [-1, -2]]\n curr[start_x][start_y] = 1\n for k in range(steps):\n for i in range(N):\n for j in range(N):\n ni = 0\n nj = 0\n if curr[i][j] != 0:\n for move in moves:\n ni = i + move[0]\n nj = j + move[1]\n if issafe(ni, nj):\n nex[ni][nj] += curr[i][j] / 8\n curr[i][j] = 0\n curr = nex\n nex = [[0 for i in range(N)] for j in range(N)]\n ans = 0\n for i in range(N):\n for j in range(N):\n ans += curr[i][j]\n return ans", "def findprob(N, start_x, start_y, steps):\n dp = [[0] * N for _ in range(N)]\n dp[start_x][start_y] = 1\n for _ in range(steps):\n dp2 = [[0] * N for _ in range(N)]\n for (start_x, row) in enumerate(dp):\n for (start_y, val) in enumerate(row):\n for (dr, dc) in ((2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)):\n if 0 <= start_x + dr < N and 0 <= start_y + dc < N:\n dp2[start_x + dr][start_y + dc] += val / 8.0\n dp = dp2\n return sum(map(sum, dp))", "def valid(ni, nj, n):\n if ni < 0 or nj < 0 or nj >= n or (ni >= n):\n return False\n return True\n\ndef findprob(N, start_x, start_y, k):\n c = [[0 for i in range(N)] for j in range(N)]\n n = [[0 for i in range(N)] for j in range(N)]\n c[start_x][start_y] = 1\n for m in range(1, k + 1):\n for i in range(N):\n for j in range(N):\n if c[i][j] != 0:\n ni = i + 2\n nj = j - 1\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n ni = i + 2\n nj = j + 1\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n ni = i - 2\n nj = j - 1\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n ni = i - 2\n nj = j + 1\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n ni = i + 1\n nj = j - 2\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n ni = i + 1\n nj = j + 2\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n ni = i - 1\n nj = j + 2\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n ni = i - 1\n nj = j - 2\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n c = [[n[i][j] for i in range(N)] for j in range(N)]\n n = [[0 for i in range(N)] for i in range(N)]\n s = 0\n for i in range(N):\n for j in range(N):\n s += c[i][j]\n return s", "from functools import lru_cache\n\ndef findprob(N, sx, sy, k):\n d = [(-2, -1), (1, 2), (-2, 1), (2, -1), (-1, 2), (2, 1), (1, -2), (-1, -2)]\n\n def pseudo(xc, yc, s):\n if xc < 0 or xc >= N or yc < 0 or (yc >= N):\n return 0\n if not s:\n return 1\n answ = 0\n for (a, b) in d:\n answ = answ + pseudo(xc + a, yc + b, s - 1)\n return answ\n denominator = 8 ** k\n return pseudo(sx, sy, k) / denominator", "from functools import lru_cache\n\ndef findprob(n, sx, sy, k):\n d = [(-2, -1), (1, 2), (-2, 1), (2, -1), (-1, 2), (2, 1), (1, -2), (-1, -2)]\n\n def helper(x, y, l):\n if x < 0 or x >= n or y < 0 or (y >= n):\n return 0\n if l == 0:\n return 1\n ans = 0\n for (a, b) in d:\n ans = ans + helper(x + a, y + b, l - 1)\n return ans\n total = 8 ** k\n return helper(sx, sy, k) / total", "from functools import lru_cache\n\ndef findprob(n, x, y, k):\n d = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n\n def solve(x, y, z):\n if not (0 <= x and x < n and (0 <= y) and (y < n)):\n return 0\n if z == 0:\n return 1\n ans = 0\n for (i, j) in d:\n ans += solve(x + i, y + j, z - 1)\n return ans\n return solve(x, y, k) / 8 ** k", "from functools import lru_cache\n\ndef findprob(n, x, y, steps):\n di = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n\n def solve(x, y, temp):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if temp == 0:\n return 1\n answer = 0\n for (i, j) in di:\n answer += solve(x + i, y + j, temp - 1)\n return answer\n return solve(x, y, steps) / 8 ** steps", "def findprob(N, start_x, start_y, steps):\n if steps == 0:\n return 1\n dx = [1, 1, -1, -1, 2, 2, -2, -2]\n dy = [2, -2, 2, -2, 1, -1, 1, -1]\n dp = [[[0 for i in range(steps + 1)] for j in range(N)] for k in range(N)]\n for i in range(N):\n for j in range(N):\n dp[i][j][0] = 1\n for i in range(1, steps + 1):\n for j in range(N):\n for k in range(N):\n prob = 0\n for l in range(8):\n nx = j + dx[l]\n ny = k + dy[l]\n if nx >= 0 and nx < N and (ny >= 0) and (ny < N):\n prob += dp[nx][ny][i - 1] / 8\n dp[j][k][i] = prob\n return dp[start_x][start_y][steps]", "def findprob(N, X, Y, K):\n self.N = N\n self.IncX = [+2, +2, +1, +1, -1, -1, -2, -2]\n self.IncY = [+1, -1, +2, -2, +2, -2, +1, -1]\n next = [[1] * N] * N\n for i in range(1, K + 1):\n current = next\n next = [[0] * N for r in range(N)]\n for x in range(N):\n for y in range(N):\n for d in range(8):\n next[x][y] += self.getCurrent(current, x, y, d)\n next[x][y] /= 8.0\n return next[X][Y]\n\ndef getCurrent(current, x, y, d):\n (nx, ny) = (x + self.IncX[d], y + self.IncY[d])\n if nx < 0 or N <= nx:\n return 0.0\n if ny < 0 or N <= ny:\n return 0.0\n return current[nx][ny]", "import collections\n\ndef findprob(n, r, c, k):\n dp = collections.defaultdict(float)\n\n def dfs(r, c, k):\n nonlocal n\n if r < 0 or r >= n or c < 0 or (c >= n):\n return 0\n if k == 0:\n return 1\n for (tr, tc) in [(r, c), (c, r), (n - 1 - r, c), (n - 1 - c, r), (r, n - 1 - c), (c, n - 1 - r), (n - 1 - c, n - 1 - r), (n - 1 - r, n - 1 - c)]:\n if (tr, tc, k) in dp:\n return dp[tr, tc, k]\n res = 0\n for (nr, nc) in [(r - 2, c - 1), (r - 2, c + 1), (r - 1, c + 2), (r - 1, c - 2), (r + 1, c + 2), (r + 1, c - 2), (r + 2, c - 1), (r + 2, c + 1)]:\n res += dfs(nr, nc, k - 1)\n res /= 8\n dp[r, c, k] = res\n return res\n return dfs(r, c, k)", "def find(rMax, cMax, x, y, steps, u):\n if steps == 0:\n return 1\n if u[x][y][steps] != -1:\n return u[x][y][steps]\n c = 0\n if x + 1 < rMax and y + 2 < cMax:\n c += find(rMax, cMax, x + 1, y + 2, steps - 1, u)\n if x + 1 < rMax and y - 2 >= 0:\n c += find(rMax, cMax, x + 1, y - 2, steps - 1, u)\n if x - 1 >= 0 and y + 2 < cMax:\n c += find(rMax, cMax, x - 1, y + 2, steps - 1, u)\n if x - 1 >= 0 and y - 2 >= 0:\n c += find(rMax, cMax, x - 1, y - 2, steps - 1, u)\n if x + 2 < rMax and y + 1 < cMax:\n c += find(rMax, cMax, x + 2, y + 1, steps - 1, u)\n if x + 2 < rMax and y - 1 >= 0:\n c += find(rMax, cMax, x + 2, y - 1, steps - 1, u)\n if x - 2 >= 0 and y + 1 < cMax:\n c += find(rMax, cMax, x - 2, y + 1, steps - 1, u)\n if x - 2 >= 0 and y - 1 >= 0:\n c += find(rMax, cMax, x - 2, y - 1, steps - 1, u)\n u[x][y][steps] = c\n return c\n\ndef findprob(N, start_x, start_y, steps):\n u = [[[-1 for _ in range(steps + 1)] for _ in range(N)] for _ in range(N)]\n val = find(N, N, start_x, start_y, steps, u)\n v1 = 1\n for i in range(steps):\n v1 *= 8\n return val / v1", "from functools import lru_cache\n\ndef findprob(N, start_x, start_y, steps):\n d = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n\n def valid(x, y, K):\n if not (0 <= x < N and 0 <= y < N):\n return 0\n if K == 0:\n return 1\n outcome = 0\n for (i, j) in d:\n outcome += valid(x + i, y + j, K - 1)\n return outcome\n return valid(start_x, start_y, steps) / 8 ** steps", "def isValid(x, y, n):\n if x >= 0 and y >= 0 and (x < N) and (y < N):\n return True\n return False\n\ndef findprob(N, start_x, start_y, steps):\n curr_ = [[0 for _ in range(N)] for _ in range(N)]\n next_ = [[0 for _ in range(N)] for _ in range(N)]\n curr_[start_x][start_y] = 1\n for k in range(steps):\n for i in range(N):\n for j in range(N):\n if curr_[i][j] != 0:\n a = i + 2\n b = j - 1\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n a = i + 2\n b = j + 1\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n a = i - 2\n b = j - 1\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n a = i - 2\n b = j + 1\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n a = i + 1\n b = j - 2\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n a = i + 1\n b = j + 2\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n a = i - 1\n b = j - 2\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n a = i - 1\n b = j + 2\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n curr_ = next_\n next_ = [[0 for _ in range(N)] for _ in range(N)]\n ans = 0\n for i in range(N):\n for j in range(N):\n ans += curr_[i][j]\n return ans", "def findprob(N, start_x, start_y, steps):\n dx = [1, 2, 2, 1, -1, -2, -2, -1]\n dy = [2, 1, -1, -2, -2, -1, 1, 2]\n\n def inside(x, y):\n return x >= 0 and x < N and (y >= 0) and (y < N)\n dp = [[[0] * (steps + 1) for ele in range(N)] for m in range(N)]\n for i in range(N):\n for j in range(N):\n dp[i][j][0] = 1\n for step in range(1, steps + 1):\n for x in range(N):\n for y in range(N):\n prob = 0.0\n for i in range(8):\n nx = x + dx[i]\n ny = y + dy[i]\n if inside(nx, ny):\n prob += dp[nx][ny][step - 1] / 8.0\n dp[x][y][step] = prob\n return dp[start_x][start_y][steps]", "def findprob(N, r, c, K):\n dp = [[0] * N for _ in range(N)]\n dp[r][c] = 1\n for _ in range(K):\n dp2 = [[0] * N for _ in range(N)]\n for (r, row) in enumerate(dp):\n for (c, val) in enumerate(row):\n for (dr, dc) in ((2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)):\n if 0 <= r + dr < N and 0 <= c + dc < N:\n dp2[r + dr][c + dc] += val / 8.0\n dp = dp2\n return sum(map(sum, dp))", "def findprob(N, start_x, start_y, steps):\n cur = [[0 for j in range(N)] for i in range(N)]\n nex = [[0 for j in range(N)] for i in range(N)]\n cur[start_x][start_y] = 1\n px = [1, 1, -1, -1, 2, -2, 2, -2]\n py = [2, -2, 2, -2, 1, 1, -1, -1]\n\n def valid(dx, dy, N):\n if (dx >= 0 and dx < N) and (dy >= 0 and dy < N):\n return True\n else:\n return False\n for m in range(steps):\n for i in range(N):\n for j in range(N):\n if cur[i][j] != 0:\n x = 0\n y = 0\n for k in range(8):\n dx = i + px[k]\n dy = j + py[k]\n if valid(dx, dy, N):\n nex[dx][dy] += cur[i][j] / 8\n cur = nex\n nex = [[0 for j in range(N)] for i in range(N)]\n su = 0\n for i in range(N):\n for j in range(N):\n su = su + cur[i][j]\n return su", "def findprob(n, r, c, k):\n\n def getvalid(cr, cc, n):\n child = []\n direction = [[2, 1], [-2, 1], [-1, 2], [1, 2], [2, -1], [-2, -1], [-1, -2], [1, -2]]\n for di in direction:\n crow = cr + di[0]\n ccol = cc + di[1]\n if 0 <= crow < n and 0 <= ccol < n:\n child.append((crow, ccol))\n return child\n prob = 1 / 8\n memo = [[0 for j in range(n)] for i in range(n)]\n memo[r][c] = 1\n for i in range(k):\n newmemo = [[0 for j in range(n)] for i in range(n)]\n for cr in range(n):\n for cc in range(n):\n for children in getvalid(cr, cc, n):\n newmemo[children[0]][children[1]] += memo[cr][cc] * prob\n memo = newmemo\n final = 0\n for row in memo:\n final += sum(row)\n return final", "from functools import lru_cache\n\ndef findprob(n, x, y, steps) -> float:\n ans = 0.0\n dirs = [(-1, -2), (-1, 2), (1, -2), (1, 2), (-2, 1), (-2, -1), (2, -1), (2, 1)]\n\n def helper(x, y, k):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if k == 0:\n return 1\n count = 0\n for (i, j) in dirs:\n count += helper(x + i, y + j, k - 1)\n return count\n return helper(x, y, steps) / 8 ** steps", "def getProb(x, y, N, dp, s):\n dx = [1, 2, 2, 1, -1, -2, -2, -1]\n dy = [2, 1, -1, -2, -2, -1, 1, 2]\n prob = 0.0\n for i in range(8):\n nx = x + dx[i]\n ny = y + dy[i]\n if self.inside(nx, ny, N):\n prob += dp[s - 1][nx][ny] / 8.0\n return prob\n\ndef inside(x, y, N):\n return x >= 0 and x < N and (y >= 0) and (y < N)\n\ndef findprob(N, start_x, start_y, steps):\n if start_x < 0 or start_x >= N or start_y < 0 or (start_y >= N):\n return 0\n dp = [[[0] * N for _ in range(N)] for _ in range(steps + 1)]\n for i in range(N):\n for j in range(N):\n dp[0][i][j] = 1\n for s in range(1, steps + 1):\n for x in range(N):\n for y in range(N):\n dp[s][x][y] = self.getProb(x, y, N, dp, s)\n return dp[steps][start_x][start_y]", "def on_board(i, j, N):\n return 0 <= i < N and 0 <= j < N\n\ndef findprob(N, start_x, start_y, steps):\n probs = [[[0 for i in range(N)] for j in range(N)] for k in range(steps + 1)]\n probs[0][start_y][start_x] = 1\n for k in range(steps):\n for i in range(N):\n for j in range(N):\n if probs[k][i][j] != 0:\n for d in self.dirs:\n if self.on_board(i + d[0], j + d[1], N):\n probs[k + 1][i + d[0]][j + d[1]] += probs[k][i][j] / 8\n total_prob = 0\n for i in range(N):\n for j in range(N):\n total_prob += probs[-1][i][j]\n return total_prob"], "starter_code": "def findprob(N, start_x, start_y, steps):\n", "input_output": {"inputs": ["N = 8, x = 0, y = 0, K = 3", "N = 4, x = 1, y = 2, k = 4"], "outputs": ["0.125000", "0.024414"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/probability-of-knight5529/1", "Expected Auxiliary Space": "O(N^{3})", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N ^{3})", "entry_point": "findprob", "task_id": "TACO_lite/480", "example": [[[8, 0, 0, 3], [4, 1, 2, 4]], ["0.125", "0.024414"]]} +{"requirement": "Define a function that takes one integer argument and returns logical value `true` or `false` depending on if the integer is a prime.\n\nPer Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.\n\n## Requirements\n\n* You can assume you will be given an integer input.\n* You can not assume that the integer will be only positive. You may be given negative numbers as well (or `0`).\n* **NOTE on performance**: There are no fancy optimizations required, but still *the* most trivial solutions might time out. Numbers go up to 2^31 (or similar, depends on language version). Looping all the way up to `n`, or `n/2`, will be too slow.\n\n## Example\n```nasm \nmov edi, 1\ncall is_prime ; EAX <- 0 (false)\n\nmov edi, 2\ncall is_prime ; EAX <- 1 (true)\n\nmov edi, -1\ncall is_prime ; EAX <- 0 (false)\n```", "solutions": ["import random\n\ndef even_odd(n):\n (s, d) = (0, n)\n while d % 2 == 0:\n s += 1\n d >>= 1\n return (s, d)\n\ndef Miller_Rabin(a, p):\n (s, d) = even_odd(p - 1)\n a = pow(a, d, p)\n if a == 1:\n return True\n for i in range(s):\n if a == p - 1:\n return True\n a = pow(a, 2, p)\n return False\n\ndef is_prime(p):\n if p == 2:\n return True\n if p <= 1 or p % 2 == 0:\n return False\n return all((Miller_Rabin(random.randint(2, p - 1), p) for _ in range(40)))", "from math import sqrt\n\ndef is_prime(num):\n if num <= 1:\n return False\n i = 2\n while i <= sqrt(num):\n if num % i == 0:\n return False\n i += 1\n return True", "import math\n\ndef is_prime(n):\n if n < 2:\n return False\n if n in [2, 3]:\n return True\n if n % 6 not in [1, 5]:\n return False\n for i in range(3, int(math.floor(math.sqrt(n))) + 1):\n if n % i == 0:\n return False\n return True", "def is_prime(n):\n if n < 2 or (n > 2 and n % 2 == 0):\n return False\n for i in range(3, int(n ** 0.5) + 1, 2):\n if n % i == 0:\n return False\n else:\n return True", "def is_prime(num):\n num = abs(int(num))\n if num < 2:\n return False\n if num == 2:\n return True\n if not num & 1:\n return False\n for x in range(3, int(num ** 0.5) + 1, 2):\n if num % x == 0:\n return False\n return True", "import math\n\ndef is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True"], "starter_code": "def is_prime(num):\n", "input_output": {"fn_name": "is_prime", "inputs": [[0], [1], [2], [73], [75], [-1]], "outputs": [[false], [false], [true], [true], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5262119038c0985a5b00029f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_prime", "task_id": "TACO_lite/521", "example": [[], []]} +{"requirement": "In this kata, your task is to write a function `to_bytes(n)` (or `toBytes(n)` depending on language) that produces a list of bytes that represent a given non-negative integer `n`. Each byte in the list is represented by a string of `'0'` and `'1'` of length 8. The most significant byte is first in the list. The example test cases should provide you with all the details. You may assume that the argument `n` is valid.", "solutions": ["def to_bytes(n):\n if not n:\n return ['00000000']\n res = []\n while n:\n res.append('{:08b}'.format(n % 256))\n n //= 256\n return res[::-1]", "import re\nfrom math import ceil\n\ndef to_bytes(n):\n return re.findall('.{8}', '{:0{}b}'.format(n, int(8 * ceil(n.bit_length() / 8.0)))) or [8 * '0']", "to_bytes = b = lambda n, f=1: n and b(n >> 8, 0) + [format(n & 255, '08b')] or ['0' * 8] * f", "def to_bytes(n):\n b = bin(n)[2:]\n b = '0' * (8 - len(b) % 8) * (len(b) % 8 != 0) + b\n return [b[8 * i:8 * i + 8] for i in range(len(b) // 8)]", "def to_bytes(n):\n L = 8\n s = bin(n)[2:]\n s = s.rjust(len(s) + L - 1 - (len(s) - 1) % 8, '0')\n return [s[i:i + L] for i in range(0, len(s), L)]", "def to_bytes(n):\n if n == 0:\n return ['00000000']\n s = bin(n)[2:]\n s = s.rjust(len(s) + 7 - (len(s) - 1) % 8, '0')\n return [s[i:i + 8] for i in range(0, len(s), 8)]", "to_bytes = lambda n, d=__import__('itertools').dropwhile: list(d(('0' * 8).__eq__, map(''.join, zip(*[iter(bin(n)[2:].zfill(8 * ((len(bin(n)) - 2) // 8 + 1)))] * 8)))) or ['0' * 8]", "def to_bytes(n):\n return [''.join(t) for t in zip(*[iter(format(n, '0{}b'.format((max(1, n.bit_length()) + 7) // 8 * 8)))] * 8)]"], "starter_code": "def to_bytes(n):\n", "input_output": {"fn_name": "to_bytes", "inputs": [[0], [1]], "outputs": [[["00000000"]], [["00000001"]]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5705601c5eef1fad69000674", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "to_bytes", "task_id": "TACO_lite/538", "example": [[[256], [255], [0], [3], [128]], ["['00000001', '00000000']", "['11111111']", "['00000000']", "['00000011']", "['10000000']"]]} +{"requirement": "You are given a set of `n` segments on the axis `Ox`, each segment has integer endpoints between `0` and `m` inclusive.\n Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers li and ri — coordinates of the left and of the right endpoints.\n\n Consider all integer points between `0` and `m` inclusive. Your task is to print all such points that don't belong to any segment. The point x belongs to the segment `[l;r]` if and only if `l ≤ x ≤ r`.\n\n**Input:**\n `m` — the upper bound for coordinates;\n array of coordinates li and ri `0 ≤ li ≤ ri ≤ m` — the endpoints of the `i`-th segment. Segments may intersect, overlap or even coincide with each other.\n\n**Output:**\n All points from `0` to `m` that don't belong to any segment.\n\n**Examples:**\n```python\nsegments(5, [(2,2),(1,2),(5,5)]) => [0,3,4]\nsegments(7, [(0,7)]) => []\n```", "solutions": ["def segments(m, arr):\n return [i for i in range(m + 1) if not any((a <= i <= b for (a, b) in arr))]", "def segments(m, a):\n vals = set(range(m + 1))\n for (st, en) in a:\n vals -= set(range(st, en + 1))\n return sorted(vals)", "def segments(m, a):\n return [p for p in range(m + 1) if all((not x[0] <= p <= x[1] for x in a))]", "def segments(m, a):\n occupied = []\n for i in a:\n for x in range(i[0], i[1] + 1):\n occupied.append(x)\n free = []\n for n in range(0, m + 1):\n if n not in occupied:\n free.append(n)\n return free", "def segments(m, a):\n return [i for i in range(m + 1) if not any([i in range(x[0], x[1] + 1) for x in a])]", "def segments(m, a):\n new_list = []\n for sub_list in a:\n new_list = new_list + list(range(sub_list[0], sub_list[1] + 1))\n new_set = set(new_list)\n expected_set = set(range(0, m + 1))\n return sorted(list(expected_set.difference(new_set)))", "def segments(m, a):\n segments = {n for (l, r) in a for n in range(l, r + 1)}\n return [n for n in range(m + 1) if n not in segments]", "from functools import reduce\nfrom itertools import filterfalse\n\ndef segments(m, a):\n return list(filterfalse(reduce(set.union, (set(range(x, y + 1)) for (x, y) in a), set()).__contains__, range(0, m + 1)))", "def segments(m, a):\n answer = [i for i in range(m + 1)]\n for i in a:\n for j in range(i[0], i[1] + 1):\n try:\n answer.remove(j)\n except ValueError:\n pass\n return answer"], "starter_code": "def segments(m, a):\n", "input_output": {"fn_name": "segments", "inputs": [[7, [[0, 7]]], [2, []], [0, []], [0, [[0, 0]]]], "outputs": [[[]], [[0, 1, 2]], [[0]], [[]]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5baa25f3246d071df90002b7", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "segments", "task_id": "TACO_lite/491", "example": [[[5, [[2, 2], [1, 2], [5, 5]]], [7, [[0, 7]]]], ["[0, 3, 4]", "[]"]]} diff --git a/experiment/taco_dataset_validation/new_dataset.jsonl b/experiment/taco_dataset_validation/new_dataset.jsonl new file mode 100644 index 0000000..ea90e62 --- /dev/null +++ b/experiment/taco_dataset_validation/new_dataset.jsonl @@ -0,0 +1,500 @@ +{"requirement": "Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors.\nIf there is no such integer in the array, return 0.\n\u00a0\nExample 1:\nInput: nums = [21,4,7]\nOutput: 32\nExplanation:\n21 has 4 divisors: 1, 3, 7, 21\n4 has 3 divisors: 1, 2, 4\n7 has 2 divisors: 1, 7\nThe answer is the sum of divisors of 21 only.\n\n\u00a0\nConstraints:\n\n1 <= nums.length <= 10^4\n1 <= nums[i] <= 10^5", "solutions": ["import math\n\ndef remove(lst, index):\n assert lst\n tail = len(lst) - 1\n (lst[index], lst[tail]) = (lst[tail], lst[index])\n lst.pop()\n\ndef swap_min(lst):\n if not lst:\n return\n argmin = min(range(len(lst)), key=lambda i: lst[i])\n (lst[0], lst[argmin]) = (lst[argmin], lst[0])\n\ndef find_primes(top):\n candidates = list(range(2, top))\n primes = []\n while candidates:\n latest_prime = candidates[0]\n primes.append(latest_prime)\n remove(candidates, 0)\n for i in range(len(candidates) - 1, -1, -1):\n if candidates[i] % latest_prime == 0:\n remove(candidates, i)\n swap_min(candidates)\n return primes\n\ndef find_prime_factor(n, primes):\n for p in primes:\n if n % p == 0:\n return p\n\ndef div4(n, primes, setprimes):\n if n <= 3:\n return 0\n elif n in setprimes:\n return 0\n else:\n p1 = find_prime_factor(n, primes)\n if p1 is None:\n return 0\n p2 = find_prime_factor(n // p1, primes)\n if p2 is None:\n p2 = n // p1\n if p1 * p2 == n and p1 != p2:\n return (1 + p1) * (1 + p2)\n elif p1 ** 3 == n:\n return (1 + p1) * (1 + p1 ** 2)\n else:\n return 0\n\ndef sum_four_divisors(arr):\n top = math.ceil(math.sqrt(max(arr) + 5))\n primes = find_primes(top)\n setprimes = set(primes)\n return sum((div4(elem, primes, setprimes) for elem in arr))\n\ndef sumfourdivisors(nums: List[int]) -> int:\n return sum_four_divisors(nums)", "def sumfourdivisors(nums: List[int], c={}) -> int:\n r = 0\n for n in nums:\n if n in c:\n r += c[n]\n continue\n s = n + 1\n cnt = 2\n end = sqrt(n)\n if end == int(end):\n s += end\n cnt += 1\n end -= 1\n for i in range(2, int(end) + 1):\n if n % i == 0:\n cnt += 2\n if cnt > 4:\n s = 0\n break\n s += i\n s += n // i\n if cnt == 4:\n c.update({n: s})\n r += s\n else:\n c.update({n: 0})\n return r", "def sumfourdivisors(nums: List[int]) -> int:\n factors_cache = {}\n\n def get_factors(num):\n if num in factors_cache:\n return factors_cache[num]\n else:\n factors = set([1, num])\n for potential_divisor in range(2, math.ceil(math.sqrt(num))):\n if num % potential_divisor == 0:\n factors = factors.union(get_factors(potential_divisor))\n factors = factors.union(get_factors(num // potential_divisor))\n if len(factors) > 4:\n break\n factors_cache[num] = factors\n return factors\n running_sum = 0\n for num in nums:\n factors = get_factors(num)\n if len(factors) == 4:\n running_sum += sum(factors)\n return running_sum", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for num in nums:\n out = set()\n for i in range(1, int(num ** 0.5 + 1)):\n (a, b) = divmod(num, i)\n if b == 0:\n out.add(i)\n out.add(a)\n if len(out) > 4:\n break\n if len(out) == 4:\n ans += sum(out)\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for num in nums:\n ans += self.fourDivisors(num)\n return ans\n\ndef fourDivisors(num):\n memo = set()\n for i in range(1, num + 1):\n if i * i > num:\n break\n if num % i == 0:\n memo.add(i)\n memo.add(num // i)\n if len(memo) > 4:\n return 0\n if len(memo) == 4:\n return sum(memo)\n return 0", "def divs(x):\n memo = self.memo\n if x in memo:\n return memo[x]\n L = 2 if x > 1 else 1\n S = 1 + x if x > 1 else 1\n for a in range(2, x):\n if a ** 2 > x:\n break\n if not x % a:\n L += 1 if x == a ** 2 else 2\n S += a if x == a ** 2 else a + x // a\n if L > 4:\n break\n memo[x] = (L, S)\n return (L, S)\n\ndef sumfourdivisors(A):\n self.memo = {}\n res = 0\n for x in A:\n (L, S) = self.divs(x)\n if L == 4:\n res += S\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for num in nums:\n divisor_num = set()\n for i in range(1, int(sqrt(num)) + 1):\n if num % i == 0:\n divisor_num.add(num // i)\n divisor_num.add(i)\n if len(divisor_num) == 4:\n res += sum(divisor_num)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for n in nums:\n sq = floor(n ** 0.5)\n if sq * sq == n:\n continue\n divs = 2\n divsum = 1 + n\n for i in range(sq, 1, -1):\n if n % i == 0:\n divs += 2\n divsum += i + n // i\n if divs > 4:\n break\n if divs == 4:\n ans += divsum\n return ans", "def divisors(n):\n for i in range(1, int(sqrt(n) + 1)):\n if n % i == 0:\n yield i\n j = n // i\n if j != i:\n yield j\n\ndef sumfourdivisors(nums: List[int]) -> int:\n s = 0\n for n in nums:\n l = list(self.divisors(n))\n if len(l) == 4:\n s += sum(l)\n return s", "def sumfourdivisors(nums: List[int]) -> int:\n\n def make_divisors(n):\n divisors = []\n for i in range(1, int(n ** 0.5) + 1):\n if n % i == 0:\n divisors.append(i)\n if i != n // i:\n divisors.append(n // i)\n return (len(divisors), divisors)\n ret = [0]\n for n in nums:\n (l, d) = make_divisors(n)\n if l == 4:\n ret.append(sum(d))\n return sum(ret)", "def sumfourdivisors(nums: List[int]) -> int:\n sum2 = 0\n for n in nums:\n cnt = 0\n sum1 = 0\n for i in range(1, int(sqrt(n)) + 1):\n if n % i == 0:\n if i == sqrt(n):\n cnt += 1\n else:\n cnt += 2\n sum1 += i + n // i\n if cnt == 4:\n sum2 += sum1\n return sum2", "import math\n\ndef sumfourdivisors(nums: List[int]) -> int:\n divisorSum = 0\n for num in nums:\n divisorSum += self.findDivisors(num)\n return divisorSum\n\ndef findDivisors(num):\n divisors = set([1, num])\n for i in range(2, int(math.sqrt(num)) + 1):\n if num % i == 0:\n divisors.add(i)\n divisors.add(num // i)\n if len(divisors) == 4:\n return sum(list(divisors))\n return 0", "def sumfourdivisors(nums: List[int]) -> int:\n\n def count_divisors(x):\n num_divisors = 0\n sum_divisors = 0\n if sqrt(x) == int(sqrt(x)):\n num_divisors += 1\n sum_divisors += sqrt(x)\n for i in range(1, ceil(sqrt(x))):\n if x % i == 0:\n num_divisors += 2\n sum_divisors += i + x // i\n return sum_divisors if num_divisors == 4 else 0\n return sum([count_divisors(x) for x in nums])", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for num in nums:\n curr = 0\n div_sum = 0\n for i in range(1, int(sqrt(num)) + 1):\n if num % i == 0:\n curr += 2\n if i == num // i:\n div_sum -= i\n curr -= 1\n div_sum += i\n div_sum += num // i\n if curr == 4:\n res += div_sum\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n ret = 0\n for num in nums:\n ret += self.has_four_divisors(num)\n return int(ret)\n\ndef has_four_divisors(num):\n divisor_sum = 0\n divisors = 0\n for i in range(1, int(sqrt(num)) + 1):\n if num % i == 0:\n if i != num / i:\n divisors += 2\n divisor_sum += i\n divisor_sum += num / i\n else:\n divisors += 1\n divisor_sum += i\n if divisors == 4:\n return divisor_sum\n return 0", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for num in nums:\n divisor = 0\n a = 2\n upperLimit = int(num ** 0.5)\n if upperLimit ** 2 == num:\n continue\n upperLimit += 1\n subAns = 1 + num\n while a < upperLimit:\n if num % a == 0:\n if divisor == 0:\n divisor += 1\n subAns += a + num // a\n else:\n break\n upperLimit = min(upperLimit, num // a)\n a += 1\n else:\n if divisor == 1:\n ans += subAns\n return ans", "from math import sqrt\n\ndef sumfourdivisors(nums: List[int]) -> int:\n\n def helper(num):\n divisors = set()\n for i in range(1, int(sqrt(num)) + 1):\n if num % i == 0:\n divisors.add(i)\n divisors.add(num // i)\n return sum(divisors) if len(divisors) == 4 else 0\n return sum((helper(num) for num in nums))", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for n in nums:\n st = set()\n for i in range(1, int(sqrt(n)) + 1):\n if n % i == 0:\n st.add(i)\n st.add(n // i)\n if len(st) == 4:\n ans += sum(st)\n return ans", "def divs(x):\n memo = self.memo\n if x in memo:\n return memo[x]\n res = 2 if x > 1 else 1\n B = {1, x}\n for a in range(2, x):\n if x < a ** 2:\n break\n if not x % a:\n res += 1 if x == a ** 2 else 2\n B.update({a, x // a})\n if res > 4:\n break\n a += 1\n memo[x] = (res, B)\n return (res, B)\n\ndef sumfourdivisors(A):\n self.memo = {}\n res = 0\n for x in A:\n (r, B) = self.divs(x)\n if r == 4:\n res += sum(B)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n\n def NOD(x):\n divisor = set([1, x])\n for i in range(2, int(x ** 0.5) + 1):\n if not x % i:\n divisor.add(i)\n divisor.add(x // i)\n return divisor\n ans = []\n for num in nums:\n divisor = NOD(num)\n if len(divisor) == 4:\n ans.append(divisor)\n return sum([sum(i) for i in ans])", "def sumfourdivisors(nums: List[int]) -> int:\n\n def div_num(x):\n (ans, ssum) = (2, x + 1)\n for i in range(2, int(x ** 0.5) + 1):\n if x % i == 0:\n ans += 1 + (i * i != x)\n ssum += i + x // i if i * i != x else i\n return (ans == 4, ssum)\n res = 0\n for x in nums:\n (flag, ssum) = div_num(x)\n if flag == 1:\n res += ssum\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for num in nums:\n divisors = set()\n for i in range(1, int(num ** 0.5) + 1):\n if num % i == 0:\n divisors.add(i)\n divisors.add(num // i)\n if len(divisors) == 4:\n ans += sum(divisors)\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n out = 0\n for i in nums:\n temp = set()\n for j in range(1, floor(sqrt(i)) + 1):\n if i % j == 0:\n temp.add(j)\n temp.add(int(i / j))\n if len(temp) == 4:\n out += sum(temp)\n return out", "def sumfourdivisors(nums: List[int]) -> int:\n\n def findfactors(n):\n f = []\n for i in range(1, int(n ** 0.5) + 1):\n if n % i == 0:\n f.append(i)\n if i != n // i:\n f.append(n // i)\n return sum(f) if len(f) == 4 else 0\n return sum([findfactors(x) for x in nums])", "def sumfourdivisors(nums: List[int]) -> int:\n ret = 0\n for num in nums:\n divs = self.divisors(num)\n if len(divs) == 4:\n ret += sum(divs)\n return ret\n\ndef divisors(num):\n ret = []\n for i in range(1, int(num ** 0.5) + 1):\n if num % i == 0:\n ret += [i]\n if num // i != i:\n ret += [num // i]\n return ret", "import math\n\ndef sumfourdivisors(nums: List[int]) -> int:\n divisors = []\n for num in nums:\n d = set()\n for i in range(1, floor(sqrt(num) + 1)):\n if num % i == 0:\n d.add(i)\n d.add(num // i)\n divisors.append(d)\n result = 0\n for s in divisors:\n if len(s) == 4:\n result += sum(s)\n return result", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for n in nums:\n tmp = set([1, n])\n for d in range(2, ceil(sqrt(n)) + 1):\n if n % d == 0:\n tmp.add(d)\n tmp.add(n // d)\n if len(tmp) == 4:\n ans += sum(tmp)\n return ans", "import math\n\ndef s_factors_if_len_4(n, d):\n s = set()\n for i in range(1, math.floor(n ** 0.5) + 1):\n if n % i == 0:\n s.add(i)\n s.add(n // i)\n if len(s) == 4:\n d[n] = sum(s)\n else:\n d[n] = 0\n\ndef sumfourdivisors(nums: List[int]) -> int:\n d = {}\n sol = 0\n for n in nums:\n if n not in d.keys():\n self.s_factors_if_len_4(n, d)\n sol += d[n]\n return sol", "def factors(n):\n if n in self.cache:\n return self.cache[n]\n result = set()\n for i in range(1, int(n ** 0.5) + 1):\n (div, mod) = divmod(n, i)\n if mod == 0:\n result |= {i, div}\n self.cache[n] = result\n return result\n\ndef sumfourdivisors(nums: List[int]) -> int:\n factors = [self.factors(f) for f in nums]\n return sum([sum(f) for f in factors if len(f) == 4])", "def sumfourdivisors(nums: List[int]) -> int:\n\n def compute(n):\n s = set()\n for i in range(1, 1 + int(n ** 0.5)):\n if n % i == 0:\n s.add(i)\n s.add(n // i)\n return sum(s) if len(s) == 4 else 0\n return sum((compute(i) for i in nums))", "def sumfourdivisors(lst: List[int]) -> int:\n import math\n final = 0\n for i in lst:\n factors = []\n for j in range(1, round(math.sqrt(i)) + 1):\n if i % j == 0:\n factors.append(int(j))\n factors.append(int(i / j))\n factors = list(dict.fromkeys(factors))\n if len(factors) == 4:\n final += sum(factors)\n return final", "def sumfourdivisors(nums: List[int]) -> int:\n\n def isPrime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n & 1 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 and n % (i + 2) == 0:\n return False\n i += 6\n return True\n res = 0\n c = 0\n temp = set()\n for i in nums:\n for j in range(1, int(i ** 0.5) + 1):\n if i % j == 0:\n temp.add(j)\n temp.add(i // j)\n if i // j != j:\n c += 2\n else:\n c += 1\n res += sum(temp) if c == 4 else 0\n temp = set()\n c = 0\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n\n def get_divisor(num):\n val = set()\n i = 1\n while i < math.sqrt(num) + 1:\n if num % i == 0:\n val.add(i)\n val.add(num // i)\n if len(val) > 4:\n return val\n i += 1\n return val\n for num in nums:\n a = get_divisor(num)\n if len(a) == 4:\n ans += sum(a)\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n\n def four_divisors3(n):\n div = set()\n i = 1\n while i * i < n:\n if n % i == 0:\n div.add(i)\n div.add(n // i)\n if len(div) > 4:\n return 0\n i += 1\n return sum(div) if len(div) == 4 else 0\n\n def four_divisors(n):\n div = set()\n for i in range(1, int(n ** 0.5) + 1):\n if n % i == 0:\n div.add(i)\n div.add(n // i)\n if len(div) > 4:\n return 0\n return sum(div) if len(div) == 4 else 0\n\n def four_divisors2(n):\n cnt = 0\n sums = 0\n div = set()\n if n != 0:\n for i in range(1, int(n ** 0.5) + 1):\n if n % i == 0:\n cnt += 2\n sums += i + n // i\n if cnt > 4:\n return 0\n return sums if cnt == 4 else 0\n if not nums:\n return 0\n nums.sort()\n total = 0\n past = [None, None]\n for (i, v) in enumerate(nums):\n if i > 0 and v == nums[i - 1] and (v == past[0]):\n total += past[1]\n continue\n tmp = four_divisors(v)\n total += tmp\n past = [v, tmp]\n return total", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n ls = len(nums)\n for i in range(ls):\n divs = set()\n for j in range(1, floor(sqrt(nums[i])) + 1):\n if nums[i] % j == 0:\n divs.add(nums[i] // j)\n divs.add(j)\n if len(divs) == 4:\n res = res + sum(divs)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n\n def NOD(x):\n divisor = set()\n for i in range(1, int(sqrt(x)) + 1):\n if not x % i:\n divisor.add(i)\n divisor.add(x // i)\n return divisor\n res = 0\n for num in nums:\n divisor = NOD(num)\n if len(divisor) == 4:\n res += sum(divisor)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n maxim = max(nums)\n total = 0\n for k in range(len(nums)):\n num_div = 0\n index = 2\n div = []\n curr_val = nums[k]\n if abs(int(sqrt(curr_val)) - sqrt(curr_val)) > 10 ** (-12):\n while index <= int(sqrt(curr_val)):\n if curr_val % index == 0:\n div.append(index)\n div.append(nums[k] / index)\n if len(div) > 2:\n break\n index += 1\n if len(div) == 2:\n total = total + sum(div) + 1 + nums[k]\n return int(total)", "def div(n):\n c = 0\n i = 1\n k = 0\n if sqrt(n).is_integer():\n return 0\n while i * i < n and c <= 3:\n if n % i == 0:\n c += 1\n k += i + n // i\n i += 1\n if c == 2:\n return k\n else:\n return 0\n\ndef sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for i in nums:\n ans += div(i)\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n\n def findFactors(num):\n if num == 0:\n return 0\n res = set()\n for i in range(int(num ** 0.5) + 1):\n if num % (i + 1) == 0:\n res.add(i + 1)\n res.add(num // (i + 1))\n return [len(res), sum(res)]\n output = 0\n for num in nums:\n (c, sm) = findFactors(num)\n if c == 4:\n output += sm\n return output", "def __init__():\n self.divisors = {}\n\ndef generate_result(n):\n counter = 1\n quo = n // counter\n while counter <= quo:\n if n % counter == 0:\n yield counter\n if quo != counter:\n yield quo\n counter += 1\n quo = n // counter\n\ndef count_divisors(n):\n if n in self.divisors:\n return self.divisors[n]\n result = list(self.generate_result(n))\n self.divisors[n] = result\n return result\n\ndef sumfourdivisors(nums: List[int]) -> int:\n divisors = list(map(self.count_divisors, nums))\n four_divisors = list([x for x in divisors if len(x) == 4])\n return sum(map(sum, four_divisors))", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for n in nums:\n divisors = self.getDivisors(n)\n if len(divisors) == 4:\n res += sum(divisors)\n return res\n\ndef getDivisors(n):\n divisors = set()\n for i in range(1, n):\n if i ** 2 > n:\n break\n if n % i == 0:\n divisors.add(i)\n divisors.add(n // i)\n if len(divisors) > 4:\n break\n return divisors", "def sumfourdivisors(nums: List[int]) -> int:\n ret = 0\n for num in nums:\n divs = set()\n i = 1\n while i ** 2 <= num:\n if not num % i:\n divs.add(i)\n divs.add(num // i)\n if len(divs) > 4:\n break\n i += 1\n if len(divs) == 4:\n ret += sum(divs)\n return ret", "def helper(n):\n if n == 1:\n return 0\n d = int(math.sqrt(n))\n cnt = 2\n sm = 1 + n\n while d > 1:\n if n % d == 0:\n d1 = n // d\n if d1 != d:\n sm += d + d1\n cnt += 2\n else:\n sm += d\n cnt += 1\n if cnt > 4:\n return 0\n d -= 1\n if cnt == 4:\n return sm\n return 0\n\ndef sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for n in nums:\n res += self.helper(n)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n summ = 0\n for num in nums:\n if num > 1:\n summ += self.divisors(num)\n return summ\n\ndef divisors(num):\n visited_factors = set()\n visited_factors.add(1)\n visited_factors.add(num)\n factors = 2\n summ = 1 + num\n for i in range(2, int(num ** 0.5) + 1):\n if not num % i and num % i not in visited_factors:\n visited_factors.add(i)\n summ += i\n factors += 1\n secondHalf = num // i\n if secondHalf not in visited_factors:\n visited_factors.add(secondHalf)\n factors += 1\n summ += secondHalf\n if factors == 4:\n return summ\n return 0", "def sumfourdivisors(nums: List[int]) -> int:\n z = 0\n for num in nums:\n i = 1\n res = []\n while i * i <= num:\n if num % i == 0:\n res.append(i)\n i += 1\n if len(res) == 2:\n lin = [num // j for j in res]\n final = list(set(res + lin))\n if len(final) == 4:\n z += sum(final)\n return max(0, z)", "def sumfourdivisors(nums: List[int]) -> int:\n\n def find_divisors(n):\n i = 1\n divisors = []\n while i * i < n:\n if n % i == 0:\n divisors.append(i)\n divisors.append(n // i)\n i += 1\n if i * i == n:\n divisors.append(i)\n return divisors\n ans = 0\n for n in nums:\n divisors = find_divisors(n)\n if len(divisors) == 4:\n ans += sum(divisors)\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for i in range(len(nums)):\n (curSum, curAns) = (1 + nums[i], 2)\n for j in range(2, int(sqrt(nums[i])) + 1):\n if nums[i] % j == 0:\n if j == nums[i] // j:\n curSum += nums[i] // j\n curAns += 1\n else:\n curSum += j + nums[i] // j\n curAns += 2\n if curAns == 4:\n res += curSum\n return res", "def find_factors(n):\n factors = []\n i = 1\n j = n\n while True:\n if i * j == n:\n factors.append(i)\n if i == j:\n break\n factors.append(j)\n i += 1\n j = n // i\n if i > j:\n break\n return factors\n\ndef sumfourdivisors(nums: List[int]) -> int:\n d = 0\n for i in nums:\n f = self.find_factors(i)\n if len(f) == 4:\n d += f[0] + f[1] + f[2] + f[3]\n return d", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for n in nums:\n d = set()\n for cnd in range(1, floor(sqrt(n)) + 1):\n (q, r) = divmod(n, cnd)\n if not r:\n d.add(q)\n d.add(cnd)\n if len(d) == 4:\n ans += sum(d)\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n divs = dict()\n for v in nums:\n divs.setdefault(v, [0, []])\n divs[v][0] += 1\n n = max(nums)\n sieve = (1 + n) * [0]\n for i in range(2, 1 + n):\n j = i\n while j <= n:\n sieve[j] += 1\n if j in divs:\n divs[j][1].append(i)\n j += i\n return sum([freq * (1 + sum(cur_div)) for (k, (freq, cur_div)) in list(divs.items()) if len(cur_div) == 3])", "def sumfourdivisors(nums: List[int]) -> int:\n if not nums:\n return 0\n ans = 0\n for n in nums:\n rangemax = int(math.sqrt(n))\n factsum = n + 1\n factcount = 2\n for f1 in range(2, rangemax + 1):\n if not n % f1:\n f2 = n // f1\n factcount += 1\n factsum += f1\n if f1 != f2:\n factcount += 1\n factsum += f2\n if factcount > 4 or factcount % 2:\n break\n if factcount == 4:\n ans += factsum\n return ans", "def contr(n):\n p = None\n if n ** 0.5 % 1 == 0:\n return 0\n for i in range(2, math.ceil(n ** 0.5)):\n if n % i == 0:\n if p is None:\n p = i\n else:\n return 0\n if p is None:\n return 0\n return 1 + p + n // p + n\n\ndef sumfourdivisors(nums: List[int]) -> int:\n return sum((contr(n) for n in nums))", "def divisors(n, c={}):\n if n in c:\n return c[n]\n d = []\n for i in range(1, int(sqrt(n) + 1)):\n if n % i == 0:\n d.append(i)\n j = n // i\n if j != i:\n d.append(j)\n if len(d) > 4:\n break\n if len(d) == 4:\n s = sum(d)\n c.update({n: s})\n return s\n else:\n c.update({n: 0})\n return 0\n\ndef sumfourdivisors(nums: List[int]) -> int:\n return sum((self.divisors(x) for x in nums))", "def sumfourdivisors(nums: List[int]) -> int:\n\n def divisors(v):\n divs = set()\n for i in range(1, ceil(sqrt(v)) + 1):\n if not v % i:\n divs.update({i, v // i})\n if len(divs) > 4:\n return 0\n return sum(divs) if len(divs) == 4 else 0\n return sum(map(divisors, nums))", "def sumfourdivisors(nums: List[int]) -> int:\n total = 0\n pSieve = [0 for k in range(10 ** 5 + 1)]\n for k in range(2, len(pSieve)):\n if pSieve[k] == 1:\n continue\n pSieve[k + k::k] = [1] * ((len(pSieve) - 1) // k - 1)\n for num in nums:\n if num == 1 or pSieve[num] == 0 or sqrt(num) == int(sqrt(num)):\n continue\n k = 2\n while num % k != 0:\n k += 1\n if num == k ** 3 or pSieve[num // k] == 0:\n total += 1 + num + k + num // k\n return total", "def sumfourdivisors(nums: List[int]) -> int:\n\n def helper(n):\n if int(math.sqrt(n)) * int(math.sqrt(n)) == n:\n return 0\n summary = 1 + n\n count = 2\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n summary += n // i + i\n count += 2\n if count > 4:\n break\n if count == 4:\n return summary\n else:\n return 0\n res = 0\n for n in nums:\n res += helper(n)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for n in nums:\n divisor = set()\n for i in range(1, floor(sqrt(n)) + 1):\n if n % i == 0:\n divisor.add(n // i)\n divisor.add(i)\n if len(divisor) > 4:\n break\n if len(divisor) == 4:\n res += sum(divisor)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n valAll = 0\n for num in nums:\n local = set()\n for i in range(1, int(math.sqrt(num)) + 1):\n if num % i == 0:\n local.add(i)\n local.add(int(num / i))\n if len(local) > 4:\n break\n if len(local) == 4:\n valAll += sum(local)\n return valAll", "def sumfourdivisors(nums: List[int]) -> int:\n ret_count = {}\n ret_sum = {}\n for n in nums:\n if n in ret_sum:\n if ret_sum[n] is not None:\n ret_count[n] += 1\n continue\n cur_div = 2\n hit_div = None\n while cur_div * cur_div <= n:\n if n % cur_div == 0:\n if hit_div is None:\n hit_div = cur_div\n else:\n hit_div = None\n break\n cur_div += 1\n if hit_div is not None and hit_div != n // hit_div:\n res = 1 + n + hit_div + n // hit_div\n ret_count[n] = 1\n else:\n res = None\n ret_sum[n] = res\n ret = sum((ret_sum[k] * c for (k, c) in list(ret_count.items())))\n return ret", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for num in nums:\n cnt = 0\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n cnt += 1\n d = i\n if cnt > 1:\n break\n if cnt == 1 and d != num // d:\n ans += 1 + d + num // d + num\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n\n def divisors(v):\n res = []\n for i in range(1, ceil(sqrt(v)) + 2):\n if len(res) > 4:\n return 0\n if not v % i:\n res += (i,)\n if v // i > i:\n res += (v // i,)\n else:\n break\n res = set(res)\n return sum(res) if len(res) == 4 else 0\n for v in nums:\n res += divisors(v)\n return res", "from math import sqrt\n\ndef sumfourdivisors(nums: List[int]) -> int:\n sum_of_factor = 0\n for x in nums:\n factors = set()\n for i in range(1, int(sqrt(x) + 1)):\n if x % i == 0:\n factors.add(i)\n factors.add(x // i)\n if len(factors) > 4:\n break\n if len(factors) == 4:\n sum_of_factor += sum(factors)\n return sum_of_factor", "def getDivisors(x):\n if x == 1:\n return [1]\n out = []\n bound = int(sqrt(x)) + 1\n for i in range(1, bound):\n if x % i == 0:\n out.append(i)\n if x // i != i:\n out.append(x // i)\n if len(out) > 4:\n break\n return out\n\ndef sumfourdivisors(nums: List[int]) -> int:\n divisors = {}\n sum_four = 0\n for x in nums:\n if x in divisors:\n if len(divisors[x]) == 4:\n sum_four += sum(divisors[x])\n else:\n x_div = self.getDivisors(x)\n if len(x_div) == 4:\n sum_four += sum(x_div)\n divisors[x] = x_div\n return sum_four", "def sumfourdivisors(nums: List[int]) -> int:\n ret = 0\n for num in nums:\n sqrt = int(math.sqrt(num))\n if sqrt * sqrt == num:\n continue\n divSum = 0\n count = 0\n for i in range(1, sqrt + 1):\n if num % i == 0:\n divSum += i + num // i\n count += 1\n if count > 2:\n break\n if count == 2:\n ret += divSum\n return ret", "def sumfourdivisors(nums: List[int]) -> int:\n\n def getDivisors(k):\n (count, second) = (0, 0)\n for i in range(2, int(sqrt(k)) + 1):\n if k % i == 0:\n count += 1\n if count > 1 or i * i == k:\n return [0]\n second = k // i\n if count == 1:\n return [1, second, k // second, k]\n else:\n return [0]\n total = 0\n for num in nums:\n total += sum(getDivisors(num))\n return total", "def sumfourdivisors(nums: List[int]) -> int:\n\n def get_divs(num):\n divs = []\n for i in range(1, int(sqrt(num)) + 1):\n if not num % i:\n divs.append(i)\n if i != int(num / i):\n divs.append(int(num / i))\n if len(divs) > 4:\n return None\n if len(divs) < 4:\n return None\n return sum(divs)\n ans = 0\n for item in nums:\n divs = get_divs(item)\n if divs:\n ans += divs\n return ans", "def sumfourdivisors(nums: List[int]) -> int:\n\n def div4(i):\n if i <= 5:\n return set()\n else:\n count = {1, i}\n for j in range(2, int(math.sqrt(i)) + 1):\n if i % j == 0:\n count.update({j, i / j})\n if len(count) > 4:\n return count\n return count\n count = 0\n for i in nums:\n s = div4(i)\n if len(s) == 4:\n count += sum(s)\n return int(count)", "def sumfourdivisors(nums: List[int]) -> int:\n return sum([self.sumofDivisors(num) for num in nums])\n\ndef sumofDivisors(num):\n s = set()\n for i in range(1, int(sqrt(num)) + 1):\n if num % i == 0:\n s.add(i)\n s.add(num // i)\n if len(s) > 4:\n return 0\n return sum(s) if len(s) == 4 else 0", "def sumfourdivisors(nums: List[int]) -> int:\n\n def four_div_sum(num):\n divs = set()\n for i in range(1, floor(sqrt(num)) + 1):\n if num % i == 0:\n divs.update({i, num // i})\n if len(divs) > 4:\n return 0\n return sum(divs) if len(divs) == 4 else 0\n return sum((four_div_sum(num) for num in nums))", "from collections import defaultdict\nfrom math import ceil\n\ndef sumfourdivisors(nums: List[int]) -> int:\n\n def getSumOfDivisors(n):\n divisors = set()\n for i in range(1, ceil(n ** 0.5) + 1):\n if n % i == 0:\n divisors.update({i, n // i})\n if len(divisors) > 4:\n return 0\n return sum(divisors) if len(divisors) == 4 else 0\n return sum(map(getSumOfDivisors, nums))", "import math\n\ndef sumfourdivisors(nums: List[int]) -> int:\n if not nums:\n return 0\n res = 0\n for i in nums:\n divisor = set()\n for j in range(1, int(math.sqrt(i)) + 1):\n if i % j == 0:\n divisor.add(j)\n divisor.add(i // j)\n if len(divisor) > 4:\n break\n if len(divisor) == 4:\n res += sum(divisor)\n return res", "from math import sqrt\n\ndef sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for num in nums:\n divisor = set()\n for i in range(1, floor(sqrt(num)) + 1):\n if num % i == 0:\n divisor.add(num // i)\n divisor.add(i)\n if len(divisor) > 4:\n break\n if len(divisor) == 4:\n res += sum(divisor)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n div_sum = 0\n for num in nums:\n divs = set()\n for i in range(1, floor(sqrt(num)) + 1):\n if num % i == 0:\n divs.add(num // i)\n divs.add(i)\n if len(divs) > 4:\n break\n if len(divs) == 4:\n div_sum += sum(divs)\n return div_sum", "def sumfourdivisors(nums: List[int]) -> int:\n\n def findFactors(num):\n res = set()\n for i in range(int(num ** 0.5) + 1):\n if num % (i + 1) == 0:\n res.add(i + 1)\n res.add(num // (i + 1))\n if len(res) > 4:\n break\n if len(res) == 4:\n return sum(res)\n else:\n return 0\n output = 0\n for num in nums:\n temp = findFactors(num)\n output += temp\n return output", "def sumfourdivisors(nums: List[int]) -> int:\n ret = 0\n for n in nums:\n divisors = set()\n for i in range(1, math.floor(n ** 0.5) + 1):\n if n % i == 0:\n divisors.add(i)\n divisors.add(n / i)\n if len(divisors) > 4:\n break\n if len(divisors) == 4:\n ret += sum(divisors)\n return int(ret)", "def find_divisors(num):\n cnt = 0\n run_sum = num + 1\n for i in range(2, int(num ** 0.5) + 1):\n if i * i == num:\n return 0\n if cnt > 1:\n return 0\n if not num % i:\n run_sum += num // i + i\n cnt += 1\n return run_sum if cnt == 1 else 0\n\ndef sumfourdivisors(nums: List[int]) -> int:\n cnt = 0\n for i in nums:\n cnt += self.find_divisors(i)\n return cnt", "def sumfourdivisors(nums: List[int]) -> int:\n\n def check(x):\n v = set()\n i = 1\n while i * i <= x:\n if x % i == 0:\n v.add(i)\n v.add(x // i)\n if len(v) > 4:\n return 0\n i += 1\n if len(v) == 4:\n return sum(v)\n return 0\n return sum([check(x) for x in nums])", "def sumfourdivisors(nums: List[int]) -> int:\n range_6 = list(range(6))\n result = 0\n for num in nums:\n if num in range_6:\n pass\n else:\n pivot = int(num ** 0.5)\n temp = [1, num]\n len_t = 2\n for i in range(2, pivot + 1):\n (divisor, rem) = divmod(num, i)\n if not rem:\n if i == divisor:\n len_t = 0\n break\n temp += [i, divisor]\n len_t += 2\n if len_t > 4:\n break\n if len_t == 4:\n result += sum(temp)\n return result", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for val in nums:\n P = self.check(val)\n if P:\n ans += sum(P)\n return ans\n\ndef check(n):\n L = [n]\n count = 1\n if n != 1:\n L.append(1)\n count += 1\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n L.append(i)\n count += 1\n if n / i != float(i):\n L.append(n // i)\n count += 1\n if count > 4:\n return None\n if count != 4:\n return None\n return L", "def sumfourdivisors(nums: List[int]) -> int:\n\n def check(n):\n i = 1\n cnt = 0\n res = 0\n while i * i < n:\n if n % i == 0:\n cnt += 2\n res += i\n res += n // i\n i += 1\n if cnt > 4:\n return 0\n if i * i == n:\n cnt += 1\n res += i\n if cnt == 4:\n return res\n else:\n return 0\n res = sum((check(n) for n in nums))\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n import math\n\n def isprime(n):\n if not n % 1 == 0:\n return False\n if math.sqrt(n) % 1 == 0:\n return False\n for i in range(math.ceil(math.sqrt(n))):\n if i == 0 or i == 1:\n continue\n if n % i == 0:\n return False\n return True\n ans = 0\n for num in nums:\n if num < 6:\n continue\n if math.sqrt(num) % 1 == 0:\n continue\n if isprime(pow(num, 1 / 3)) or num == 4913:\n ans += 1 + pow(num, 1 / 3) + pow(num, 2 / 3) + num\n continue\n divisors = 0\n for i in range(math.ceil(math.sqrt(num))):\n if i == 0 or i == 1:\n continue\n if num % i == 0:\n if num / i % i == 0:\n break\n if not divisors == 0:\n divisors = 0\n break\n divisors = i\n if not divisors == 0 and isprime(num / divisors) and isprime(divisors):\n ans += (divisors + 1) * (num / divisors + 1)\n return int(ans)", "import numpy as np\n\ndef sumfourdivisors(nums: List[int]) -> int:\n ret = 0\n for num in nums:\n divisors = set()\n N = int(np.floor(np.sqrt(num)))\n for i in range(1, N + 1):\n if num % i == 0:\n divisors.add(i)\n divisors.add(num // i)\n if len(divisors) > 4:\n break\n if len(divisors) == 4:\n ret += sum(divisors)\n return ret", "def sumfourdivisors(nums: List[int]) -> int:\n import math\n s = 0\n nums = sorted(nums, reverse=True)\n for i in nums:\n count = set()\n true = True\n for x in range(2, int(math.sqrt(i)) + 1):\n if len(count) > 4:\n true = False\n break\n if i % x == 0:\n count.add(x)\n count.add(i // x)\n if len(count) == 2 and true:\n s += sum(count) + i + 1\n return s", "def sumfourdivisors(nums: List[int]) -> int:\n ttl = 0\n for n in nums:\n seen = set()\n for i in range(1, int(sqrt(n)) + 1):\n if n % i == 0:\n seen.add(i)\n seen.add(n / i)\n if len(seen) >= 5:\n break\n if len(seen) == 4:\n ttl += sum(seen)\n return int(ttl)", "def sumfourdivisors(nums: List[int]) -> int:\n res = 0\n for num in nums:\n div = set()\n for j in range(1, int(sqrt(num)) + 1):\n if not num % j:\n div.add(j)\n div.add(num // j)\n if len(div) > 4:\n break\n if len(div) == 4:\n res += sum(div)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n\n def findiv(num):\n res = 0\n cnt = 0\n for i in range(1, int(num ** 0.5) + 1):\n if not num % i:\n if i * i == num:\n cnt += 1\n res += i\n else:\n cnt += 2\n res += i\n res += num // i\n return res if cnt == 4 else 0\n res = 0\n for num in nums:\n res += findiv(num)\n return res", "def sumfourdivisors(nums: List[int]) -> int:\n ans = 0\n for num in nums:\n out = []\n for i in range(1, int(num ** 0.5) + 1):\n (a, b) = divmod(num, i)\n if b == 0:\n if a == i:\n out.append(a)\n else:\n out.extend([a, i])\n if len(out) > 4:\n break\n if len(out) == 4:\n ans += sum(out)\n return ans"], "starter_code": "def sumfourdivisors(nums: List[int]) -> int:\n", "input_output": {"fn_name": "sumFourDivisors", "inputs": [[[21, 4, 7]]], "outputs": [32]}, "difficulty": "MEDIUM", "raw_tags": ["Math", "Array"], "name": null, "source": "leetcode", "tags": ["Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/four-divisors/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sumfourdivisors", "task_id": "TACO_lite/58", "example": [[[[21, 4, 7]]], ["32"]]} +{"requirement": "Imagine there's a big cube consisting of n^3 small cubes. Calculate, how many small cubes are not visible from outside.\n\nFor example, if we have a cube which has 4 cubes in a row, then the function should return 8, because there are 8 cubes inside our cube (2 cubes in each dimension)", "solutions": ["def not_visible_cubes(n):\n return max(n - 2, 0) ** 3", "def not_visible_cubes(n):\n if n > 1:\n return (n - 2) ** 3\n else:\n return 0", "def not_visible_cubes(n):\n if 0 <= n <= 2:\n return 0\n return (n - 2) ** 3", "import math\n\ndef not_visible_cubes(n):\n if n < 2:\n return 0\n else:\n return (n - 2) * (n - 2) * (n - 2)", "def not_visible_cubes(n):\n return pow(n - 2, 3) if n > 2 else 0", "def not_visible_cubes(n):\n return n > 2 and (n - 2) ** 3", "def not_visible_cubes(n):\n if n == 0 or n == 1 or n == 2:\n return 0\n totalCubes = n * n * n\n cubesPerSide = n * n\n outsideCubes = cubesPerSide + 2 * (cubesPerSide - n) + cubesPerSide - 2 * n + 2 * (cubesPerSide - (n + 2 * (n - 1) + n - 2))\n return totalCubes - outsideCubes"], "starter_code": "def not_visible_cubes(n):\n", "input_output": {"fn_name": "not_visible_cubes", "inputs": [[0], [1], [2], [3], [4], [5], [7], [12], [18], [10002]], "outputs": [[0], [0], [0], [1], [8], [27], [125], [1000], [4096], [1000000000000]]}, "difficulty": "EASY", "raw_tags": ["Puzzles"], "name": null, "source": "codewars", "tags": ["Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/560d6ebe7a8c737c52000084", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "not_visible_cubes", "task_id": "TACO_lite/47", "example": [[[4]], ["8"]]} +{"requirement": "# Grasshopper - Function syntax debugging\n\nA student was working on a function and made some syntax mistakes while coding. Help them find their mistakes and fix them.", "solutions": ["def main(verb, noun):\n return verb + noun", "def main(*a):\n return ''.join(a)", "def main(verb, noun):\n return f'{verb}{noun}'", "def main(verb: str, noun: str) -> str:\n return verb + noun", "main = '{}{}'.format", "main = str.__add__", "def main(verb, noun):\n output = verb + noun\n return output", "main = lambda _, __: _ + __", "def main(*sen):\n return ''.join(sen)", "def main(verb, noun):\n msg = verb + noun\n return msg", "def main(verb, noun):\n return verb + noun\nmain('take', 'shit')", "from operator import add as main", "def main(*arr):\n return ''.join(arr)", "def main(verb, noun):\n v = verb\n n = noun\n return v + n", "main = lambda *n: ''.join(n)", "def main(a, b):\n return ''.join([a, b])", "def main(verb, noun):\n return '{0}{1}'.format(verb, noun)", "def main(verbs, none):\n main = verbs + none\n return main", "def main(v, n):\n return v + n", "def main(verb, noun):\n result = verb + noun\n return result", "def main(verb, noun):\n newword = verb + noun\n return newword", "def main(n, m):\n return n + m", "def main(verb, noun):\n test = verb + noun\n return test", "def main(verb, noun):\n try:\n return verb + noun\n except:\n return 'There was a problem.'", "main = lambda verb, noun: f'{verb}{noun}'", "def main(verb, noun):\n return ''.join((verb, noun))", "def main(verb, noun):\n answer = ''\n answer = verb + noun\n return answer", "main = lambda noun, verb: noun + verb", "def main(verb, noun):\n i = verb + noun\n return i", "def main(verb, noun):\n return '%s%s' % (verb, noun)", "verb = 2\nnoun = 2\n\ndef main(verb, noun):\n return verb + noun\nmain(verb, noun)", "def main(verb, noum):\n r = verb + noum\n return r", "def main(verb, noun):\n return verb + noun\nmain(1, 1)", "def main(verb, noun):\n word = ''\n word += verb + noun\n return word", "def main(verb, noun):\n comp = verb + noun\n return comp", "main = lambda alpha, beta: alpha + beta", "main = lambda v, b: v + b", "def main(verb='say ', noun='hello'):\n return verb + noun", "def main(verb, noun):\n honestly = '{}{}'.format(verb, noun)\n return honestly", "def main(*args):\n return ''.join(args)", "def main(verb, noun):\n a = verb + noun\n return a", "def main(verb, noun):\n res = verb + noun\n return res", "def main(*words):\n return ''.join(words)", "main = lambda a, b: a + b", "def main(verb, noun):\n return verb + noun\nmain('use', 'item')", "def main(verb, word2):\n return '%s%s' % (verb, word2)", "def main(a, b):\n return a + b", "main = lambda verb, noun: ''.join((verb, noun))", "def main(verb, noun):\n sum = verb + noun\n return sum", "def main(x, y):\n return x + y", "def main(verb, noun):\n return verb + noun\nmain('take', 'item')", "main = lambda x, y: f'{x}{y}'", "main = lambda *a: ''.join(a)"], "starter_code": "def main(verb, noun):\n", "input_output": {"fn_name": "main", "inputs": [["take ", "item"], ["use ", "sword"]], "outputs": [["take item"], ["use sword"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56dae9dc54c0acd29d00109a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "main", "task_id": "TACO_lite/85", "example": [[], []]} +{"requirement": "Given 3 characters 'a', 'b', 'c'. Find the number of strings of length n that can be formed from these 3 characters. Given that : we can use \u2018a\u2019 as many times as we want, \u2018b\u2019 maximum once, and \u2018c\u2019 maximum twice.\n \nExample 1:\nInput: n = 2\nOutput: 8\nExpalantion: There are total 8 possible\nstrings and these are: {aa, ab, ba, ac,\nca, bc, cb, cc}.\nExample 2:\nInput: n = 3\nOutput: 19\nExplanation: There are total 19 possible\nstrings.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function no_ofString() which takes n as input parameter ans returns the no. of total possible strings than can be formed using characters 'a', 'b' and 'c' modulo 10^{9} + 7.\n \nExpected Time Complexity: O(n)\nExpected Space Compelxity: O(n)\n \nConstraints:\n1 <= n <= 100000", "solutions": ["def no_ofstring(n):\n l = 10 ** 9 + 7\n return (1 + n * 2 + n * (n * n - 1) // 2) % l", "def no_ofstring(n):\n m = 1000000007\n ans = 1 + 2 * (n % m) + n % m * (n % m - 1) * (n % m + 1) // 2\n return ans % m", "def no_ofstring(n):\n return (n * n * n + (3 * n + 2)) // 2 % 1000000007", "def no_ofstring(n):\n m = 10 ** 9 + 7\n ans = 1 + 2 * (n % m) + n % m * (n % m - 1) * (n % m + 1) // 2\n return ans % m", "def no_ofstring(n):\n if n == 1:\n return 3\n mod = int(10 ** 9 + 7)\n total = 1 + n % mod + n * n % mod + n * (n - 1) * (n - 1) // 2 % mod\n return total % mod", "def no_ofstring(n):\n if n == 1:\n return 3\n total = 0\n for i in range(3):\n combination = 1\n bottom_part = 1\n for x in range(i):\n combination *= n - x\n bottom_part *= x + 1\n total = (total + combination // bottom_part) % (10 ** 9 + 7)\n for i in range(3):\n combination = 1\n bottom_part = 1\n for x in range(i):\n combination *= n - 1 - x\n bottom_part *= x + 1\n total = (total + n * (combination // bottom_part)) % (10 ** 9 + 7)\n return total", "def possibilities(x):\n count = 1\n while x > 1:\n count *= x\n x -= 1\n return count\n\ndef no_ofstring(n):\n if n == 1:\n return 3\n all_a = 1\n one_b_other_a = n % (10 ** 9 + 7)\n one_c_other_a = n % (10 ** 9 + 7)\n one_c_one_b = n % (10 ** 9 + 7)\n if n > 2:\n one_c_one_b = n * (n - 1) % (10 ** 9 + 7)\n two_c = 1\n if n > 2:\n two_c = int(n * (n - 1) / 2) % (10 ** 9 + 7)\n one_b_two_c = 0\n if n > 2:\n one_b_two_c = int(n * (n - 1) * (n - 2) / 2) % (10 ** 9 + 7)\n return (all_a + one_b_other_a + one_c_other_a + one_c_one_b + two_c + one_b_two_c) % (10 ** 9 + 7)"], "starter_code": "def no_ofstring(n):\n", "input_output": {"inputs": ["n = 2", "n = 3"], "outputs": ["8", "19"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical", "permutation"], "name": null, "source": "geeksforgeeks", "tags": ["Combinatorics", "Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/total-number-of-strings5726/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "no_ofstring", "task_id": "TACO_lite/16", "example": [[[2], [3]], ["8", "19"]]} +{"requirement": "## Task\n\nWrite a function that accepts two arguments and generates a sequence containing the integers from the first argument to the second inclusive. \n\n## Input\n\nPair of integers greater than or equal to `0`. The second argument will always be greater than or equal to the first. \n\n## Example\n\n```python\ngenerate_integers(2, 5) # --> [2, 3, 4, 5]\n```", "solutions": ["def generate_integers(m, n):\n return list(range(m, n + 1))", "def generate_integers(m, n):\n return [i for i in range(m, n + 1)]", "def generate_integers(m, n):\n ans = []\n for each in range(m, n + 1):\n ans.append(each)\n return ans", "def generate_integers(m, n):\n return [_ for _ in range(m, n + 1)]", "def generate_integers(m, n):\n return [num for num in range(m, n + 1)]", "def generate_integers(m, n):\n c = []\n for i in range(m, n + 1):\n c.append(i)\n return c", "def generate_integers(m, n):\n numeros = []\n for x in range(m, n + 1):\n numeros.append(x)\n return numeros\n pass", "def generate_integers(m, n):\n nums = list()\n while m <= n:\n nums.append(m)\n m += 1\n return nums", "def generate_integers(m, n):\n list = []\n for x in (m, n):\n while m <= x <= n:\n x = x + 1\n list.append(x - 1)\n return list"], "starter_code": "def generate_integers(m, n):\n", "input_output": {"fn_name": "generate_integers", "inputs": [[2, 5]], "outputs": [[[2, 3, 4, 5]]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5841f680c5c9b092950001ae", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "generate_integers", "task_id": "TACO_lite/32", "example": [[[2, 5]], ["[2, 3, 4, 5]"]]} +{"requirement": "Given a string S contains 0's, 1's, and 2's, the task is to find the number of goals on the penalty.\n\t '1' stands for \"goal\".\n\t '0' stands for \"no goal\".\n\t '2' stands for a foul which gives a penalty.\nExample 1:\nInput: S = \"1012012112110\"\nOutput: 2\nExplanation: There are 3 penalties,\nof which he scores only 2.\n1012012112110\nExample 2:\nInput: S = \"111122\"\nOutput: 0\nExplanation: No goal on penalty\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function penaltyScore() which takes a string S as input and returns the goals count on the penalty. \nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= |N| <= 10^{5}", "solutions": ["def penaltyscore(S):\n goal = 0\n for i in range(len(S)):\n if i < len(S) - 1:\n if S[i] == '2' and S[i + 1] == '1':\n goal = goal + 1\n return goal", "def penaltyscore(S):\n d = 0\n k = list(map(int, str(S)))\n for i in range(0, len(S) - 1):\n if k[i] == 2 and k[i + 1] == 1:\n d = d + 1\n return d", "def penaltyscore(s):\n c = 0\n for i in range(len(s) - 1):\n if s[i] == '2' and s[i + 1] == '1':\n c = c + int(s[i + 1])\n return c", "def penaltyscore(S):\n c = 0\n for i in range(len(S) - 1):\n if S[i:i + 2] == '21':\n c = c + 1\n return c", "def penaltyscore(S):\n l = []\n a = []\n for i in S:\n l.append(int(i))\n for i in range(len(l)):\n if l[i] == 2:\n if i + 1 < len(l):\n a.append(l[i + 1])\n count = 0\n for i in a:\n if i == 1:\n count += 1\n return count", "def penaltyscore(S):\n return S.count('21')", "def penaltyscore(S):\n count = 0\n for i in range(len(S) - 1):\n if S[i] == '2':\n if S[i + 1] == '1':\n count += 1\n return count", "def penaltyscore(S):\n l = list()\n for i in S:\n l.append(int(i))\n p = 0\n for i in range(1, len(l)):\n if l[i] == 1:\n if l[i - 1] == 2:\n p = p + 1\n return p", "def penaltyscore(S):\n res = 0\n for i in range(len(S) - 1):\n if S[i] + S[i + 1] == '21':\n res += 1\n return res", "def penaltyscore(S):\n if '21' in S:\n output = S.count('21')\n return output\n else:\n return 0", "from collections import Counter\n\ndef penaltyscore(S):\n z = S.count('21')\n if z == 0:\n return 0\n return z", "def penaltyscore(s):\n ans = s.count('21')\n return ans", "def penaltyscore(S):\n count = 0\n i = 0\n while i < len(S):\n while i < len(S) - 1 and S[i] == '2':\n if S[i + 1] == '1':\n count += 1\n i += 1\n else:\n i += 1\n i += 1\n return count", "def penaltyscore(S):\n stack_top = ''\n goals = 0\n for i in S:\n if stack_top == '2' and i == '1':\n goals += 1\n stack_top = i\n return goals", "def penaltyscore(S):\n c = 0\n k = 0\n for i in range(len(S) - 1):\n if S[i] == '2' and S[i + 1] == '1':\n c += 1\n k = 1\n if k == 0:\n return 0\n else:\n return c", "def penaltyscore(S):\n x = S.count('21')\n if x == 0:\n return 0\n return x", "def penaltyscore(S):\n n = '21'\n t = S.count(n)\n if t == 0:\n return 0\n return t", "def penaltyscore(S):\n s = '21'\n count = 0\n for i in range(1, len(S)):\n if S[i] == '1' and S[i - 1] == '2':\n count += 1\n else:\n continue\n return count if count > 0 else 0", "def penaltyscore(S):\n c = 0\n for x in range(len(S)):\n if S[x] == '2' and x + 1 < len(S):\n if S[x + 1] == '1':\n c += 1\n return c", "def penaltyscore(S):\n result = 0\n temp = ''\n count = 0\n for i in S:\n if i == '2':\n temp = '2'\n elif i == '1':\n temp += i\n if temp == '21':\n count += 1\n temp = ''\n else:\n temp = ''\n return count", "def penaltyscore(S):\n n = len(S)\n count = 0\n for i in range(len(S)):\n if i == n - 1:\n continue\n elif S[i] == '2' and S[i + 1] == '1':\n count += 1\n return count", "def penaltyscore(S):\n lst = list(S)\n s = 0\n for i in range(len(lst)):\n if i + 1 < len(lst):\n if lst[i] == '2':\n if lst[i + 1] == '1':\n s += 1\n return s"], "starter_code": "def penaltyscore(S):\n", "input_output": {"inputs": ["S = \"1012012112110\"", "S = \"111122\""], "outputs": ["2", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/the-penalty-shootout3810/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|).", "entry_point": "penaltyscore", "task_id": "TACO_lite/53", "example": [[["1012012112110"], ["111122"]], ["2", "0"]]} +{"requirement": "Given an integer, check whether it is a palindrome or not.\nExample 1:\nInput: n = 555\nOutput: Yes\nExample 2:\nInput: n = 123\nOutput: No\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function is_palindrome() which takes the number as input parameter and returns \"Yes\" if it is palindrome otherwise returns \"No\"(Without quotes).\n \nExpected Time Complexity: O(x)\nExpected Space Complexity: O(x) where x is number of digits in n.\n \nConstraints:\n1 <= n <= 1000", "solutions": ["def is_palindrome(n):\n self.n = n\n n = str(n)\n strait = n.strip()\n reverse = strait[::-1]\n n = int(n)\n if strait == reverse:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n reversed = str(n)[::-1]\n if str(reversed) == str(n):\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n a = str(n)\n if a == a[::-1]:\n return 'Yes'\n return 'No'", "def is_palindrome(n):\n i = 0\n j = len(str(n)) - 1\n s = str(n)\n while i < j:\n if s[i] != s[j]:\n return 'No'\n i += 1\n j -= 1\n return 'Yes'", "def is_palindrome(n):\n temp = n\n res = 0\n while n > 0:\n res = res * 10 + n % 10\n n = n // 10\n if res == temp:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n num = n\n rev = 0\n while num != 0:\n dig = num % 10\n rev = 10 * rev + dig\n num = num // 10\n if n == rev:\n return 'Yes'\n return 'No'", "def is_palindrome(n):\n dup = n\n rev = 0\n while n != 0:\n d = n % 10\n rev = rev * 10 + d\n n = n // 10\n if rev == dup:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n newNum = 0\n currNum = n\n while currNum > 0:\n currDigit = currNum % 10\n newNum = newNum * 10 + currDigit\n currNum = currNum // 10\n if newNum == n:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(N):\n n = N\n lis = n % 10\n while n > 0:\n lis = lis * 10\n n = n // 10\n lis += n % 10\n lis = int(lis / 10)\n if lis == N:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n org_string = str(n)\n rev_string = ''\n for i in org_string:\n rev_string = i + rev_string\n if org_string == rev_string:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n rev = 0\n temp = n\n while n > 0:\n last = n % 10\n rev = rev * 10 + last\n n = n // 10\n if rev == temp:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n y = str(n)\n z = y[::-1]\n if y == z:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n new = 0\n temp = n\n while temp != 0:\n digit = temp % 10\n new = new * 10 + digit\n temp = temp // 10\n return 'Yes' if new == n else 'No'", "def is_palindrome(n):\n nn = str(n)[::-1]\n nnn = int(nn)\n if n == nnn:\n return 'Yes'\n return 'No'", "def is_palindrome(n):\n num = n\n rev = 0\n while n != 0:\n rem = n % 10\n rev = rev * 10 + rem\n n = n // 10\n if num == rev:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n wno = n\n rev = 0\n while wno > 0:\n dig = wno % 10\n wno = wno // 10\n rev = rev * 10 + dig\n if rev == n:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n res = str(n) == str(n)[::-1]\n if res == True:\n ans = 'Yes'\n else:\n ans = 'No'\n return ans", "def is_palindrome(n):\n num = n\n sum = 0\n while n > 0:\n sum = sum * 10 + n % 10\n n //= 10\n if num == sum:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n n = str(n)\n a = [x for x in n]\n b = [x for x in n]\n b.reverse()\n flag = False\n for i in range(len(a) // 2):\n if a[i] != b[i]:\n flag = True\n break\n if flag:\n return 'No'\n else:\n return 'Yes'", "def is_palindrome(n):\n flag = True\n n1 = str(n)\n for i in range(len(n1) // 2):\n if n1[i] != n1[-i - 1]:\n flag = False\n break\n if flag:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n s = str(n)\n s = s[::-1]\n a = str(n)\n for i in range(0, len(s)):\n for j in range(1):\n if a[i] != s[i]:\n return 'No'\n return 'Yes'", "def is_palindrome(n):\n number = str(n)\n reverseNum = number[::-1]\n if number == reverseNum:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n temp = n\n reverse = 0\n while temp != 0:\n lastDigit = temp % 10\n reverse = reverse * 10 + lastDigit\n temp //= 10\n if n == reverse:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n temp = n\n reverse = 0\n i = len(str(n)) - 1\n while temp != 0:\n lastDigit = temp % 10\n reverse += lastDigit * 10 ** i\n temp //= 10\n i -= 1\n if n == reverse:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n n = str(n)\n k = len(n) - 1\n answer = ''\n while k >= 0:\n answer += n[k]\n k -= 1\n if answer == n:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n reverse = 0\n c = n\n while c != 0:\n reverse = reverse * 10 + c % 10\n c = c // 10\n if reverse == n:\n return 'Yes'\n return 'No'", "def is_palindrome(N):\n count = 0\n for i in range(0, len(str(N))):\n if str(N)[len(str(N)) - 1 - i] == str(N)[i]:\n count = count + 1\n if count == len(str(N)):\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n temp = n\n rev = 0\n while n != 0:\n digit = n % 10\n rev = rev * 10 + digit\n n = n // 10\n if temp != rev:\n s = 'No'\n return s\n else:\n s = 'Yes'\n return s", "def is_palindrome(n):\n ns = str(n)\n rev = ns[::-1]\n rev = int(rev)\n if n == rev:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n low = 0\n high = int(len(str(n))) - 1\n num = str(n)\n while low < high:\n if num[low] != num[high]:\n return 'No'\n low += 1\n high -= 1\n return 'Yes'", "def is_palindrome(n):\n num = str(n)\n rev = num[::-1]\n if num == rev:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n x = n\n reverse_num = 0\n while x > 0:\n last_digit = x % 10\n reverse_num = reverse_num * 10 + last_digit\n x = x // 10\n if reverse_num == n:\n return 'Yes'\n return 'No'", "def is_palindrome(n):\n n = str(n)\n new_n = []\n for i in n:\n new_n.append(i)\n z = ''.join(new_n[::-1])\n if z == n:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n (rev, ori) = (0, n)\n while n > 0:\n rev = rev * 10 + n % 10\n n //= 10\n if ori == rev:\n return 'Yes'\n return 'No'", "def is_palindrome(n):\n a = n\n res = 0\n while n != 0:\n res = n % 10 + res * 10\n n //= 10\n if res == a:\n return 'Yes'\n return 'No'", "def is_palindrome(n):\n x = n\n palindrome = 0\n while n != 0:\n number = n % 10\n palindrome = palindrome * 10 + number\n n = n // 10\n if palindrome == x:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n temp = n\n s = 0\n while n > 0:\n rem = n % 10\n s = s * 10 + rem\n n = n // 10\n if temp == s:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n s = str(n)\n k = list(s[::-1])\n for i in range(len(s)):\n if s[i] != k[i]:\n return 'No'\n break\n else:\n return 'Yes'", "def is_palindrome(n):\n p = []\n while n > 0:\n rem = n % 10\n p.append(rem)\n n = n // 10\n if p == p[::-1]:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n temp = n\n sum = 0\n while n != 0:\n r = n % 10\n n = n // 10\n sum = sum * 10 + r\n if sum == temp:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n return 'Yes' * (str(n) == str(n)[::-1]) or 'No'", "def is_palindrome(n):\n s = str(n)[-1::-1]\n if int(s) == n:\n return 'Yes'\n else:\n return 'No'", "def is_palindrome(n):\n n = str(n)\n l = len(n)\n for i in range(len(str(n)) // 2):\n if n[i] != n[l - 1 - i]:\n return 'No'\n return 'Yes'", "def is_palindrome(n):\n t = str(n)\n k = 'Yes'\n o = 'No'\n if t == t[::-1]:\n return k\n else:\n return o"], "starter_code": "def is_palindrome(n):\n", "input_output": {"inputs": ["n = 555", "n = 123"], "outputs": ["Yes", "No"]}, "difficulty": "EASY", "raw_tags": ["palindrome"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/palindrome0746/1", "Expected Auxiliary Space": "O(x) where x is number of digits in n.", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(x)", "entry_point": "is_palindrome", "task_id": "TACO_lite/71", "example": [[], []]} +{"requirement": "A faro shuffle of a deck of playing cards is a shuffle in which the deck is split exactly in half and then the cards in the two halves are perfectly interwoven, such that the original bottom card is still on the bottom and the original top card is still on top.\n\nFor example, faro shuffling the list\n```python\n['ace', 'two', 'three', 'four', 'five', 'six']\n```\ngives\n```python\n['ace', 'four', 'two', 'five', 'three', 'six' ]\n```\n\nIf 8 perfect faro shuffles are performed on a deck of 52 playing cards, the deck is restored to its original order.\n\nWrite a function that inputs an integer n and returns an integer representing the number of faro shuffles it takes to restore a deck of n cards to its original order.\n\nAssume n is an even number between 2 and 2000.", "solutions": ["def faro_cycles(n):\n (x, cnt) = (2, 1)\n while x != 1 and n > 3:\n cnt += 1\n x = x * 2 % (n - 1)\n return cnt", "def faro_cycles(deck_size):\n (arr, count) = (list(range(deck_size)), 0)\n original_arr = arr\n while True:\n arr = arr[0:deck_size:2] + arr[1:deck_size:2]\n count += 1\n if original_arr == arr:\n break\n return count", "def faro_cycles(size):\n deck = list(range(size))\n (cur, count) = (deck[::2] + deck[1::2], 1)\n while cur != deck:\n (cur, count) = (cur[::2] + cur[1::2], count + 1)\n return count", "def faro_cycles(n):\n original = list(range(1, n + 1))\n (duplicate, c) = (original.copy(), 0)\n while 1:\n (first, bottom) = (duplicate[0], duplicate[-1])\n first_half = duplicate[1:n // 2]\n second_half = duplicate[n // 2:-1]\n duplicate = []\n for (i, j) in zip(first_half, second_half):\n duplicate.extend([j, i])\n duplicate = [first] + duplicate + [bottom]\n c += 1\n if original == duplicate:\n return c", "def faro_cycles(deck_size):\n if deck_size == 2:\n return 1\n (pos, output) = (2, 1)\n while pos != 1:\n pos = pos * 2 % (deck_size - 1)\n output += 1\n return output", "def faro_cycles(deck_size):\n pos = 1\n for i in range(deck_size):\n pos = pos * 2 - (0 if pos < deck_size / 2 else deck_size - 1)\n if pos == 1:\n return i + 1", "def faro(xs):\n m = len(xs) // 2\n return [x for xs in zip(xs[:m], xs[m:]) for x in xs]\n\ndef faro_cycles(deck_size):\n xs = original = list(range(deck_size))\n n = 0\n while True:\n n += 1\n xs = faro(xs)\n if xs == original:\n return n", "def interv(list1, list2):\n out_list = []\n for (el1, el2) in zip(list1, list2):\n out_list.append(el1)\n out_list.append(el2)\n return out_list\n\ndef faro_cycles(deck_size):\n original = [x for x in range(deck_size)]\n new = interv(original[:deck_size // 2], original[deck_size // 2:])\n n = 1\n while original != new:\n new = interv(new[:deck_size // 2], new[deck_size // 2:])\n n += 1\n return n", "def faro_cycles(deck_size):\n return [None, 1, 2, 4, 3, 6, 10, 12, 4, 8, 18, 6, 11, 20, 18, 28, 5, 10, 12, 36, 12, 20, 14, 12, 23, 21, 8, 52, 20, 18, 58, 60, 6, 12, 66, 22, 35, 9, 20, 30, 39, 54, 82, 8, 28, 11, 12, 10, 36, 48, 30, 100, 51, 12, 106, 36, 36, 28, 44, 12, 24, 110, 20, 100, 7, 14, 130, 18, 36, 68, 138, 46, 60, 28, 42, 148, 15, 24, 20, 52, 52, 33, 162, 20, 83, 156, 18, 172, 60, 58, 178, 180, 60, 36, 40, 18, 95, 96, 12, 196, 99, 66, 84, 20, 66, 90, 210, 70, 28, 15, 18, 24, 37, 60, 226, 76, 30, 29, 92, 78, 119, 24, 162, 84, 36, 82, 50, 110, 8, 16, 36, 84, 131, 52, 22, 268, 135, 12, 20, 92, 30, 70, 94, 36, 60, 136, 48, 292, 116, 90, 132, 42, 100, 60, 102, 102, 155, 156, 12, 316, 140, 106, 72, 60, 36, 69, 30, 36, 132, 21, 28, 10, 147, 44, 346, 348, 36, 88, 140, 24, 179, 342, 110, 36, 183, 60, 156, 372, 100, 84, 378, 14, 191, 60, 42, 388, 88, 130, 156, 44, 18, 200, 60, 108, 180, 204, 68, 174, 164, 138, 418, 420, 138, 40, 60, 60, 43, 72, 28, 198, 73, 42, 442, 44, 148, 224, 20, 30, 12, 76, 72, 460, 231, 20, 466, 66, 52, 70, 180, 156, 239, 36, 66, 48, 243, 162, 490, 56, 60, 105, 166, 166, 251, 100, 156, 508, 9, 18, 204, 230, 172, 260, 522, 60, 40, 253, 174, 60, 212, 178, 210, 540, 180, 36, 546, 60, 252, 39, 36, 556, 84, 40, 562, 28, 54, 284, 114, 190, 220, 144, 96, 246, 260, 12, 586, 90, 196, 148, 24, 198, 299, 25, 66, 220, 303, 84, 276, 612, 20, 154, 618, 198, 33, 500, 90, 72, 45, 210, 28, 84, 210, 64, 214, 28, 323, 290, 30, 652, 260, 18, 658, 660, 24, 36, 308, 74, 60, 48, 180, 676, 48, 226, 22, 68, 76, 156, 230, 30, 276, 40, 58, 700, 36, 92, 300, 708, 78, 55, 60, 238, 359, 51, 24, 140, 121, 486, 56, 244, 84, 330, 246, 36, 371, 148, 246, 318, 375, 50, 60, 756, 110, 380, 36, 24, 348, 384, 16, 772, 20, 36, 180, 70, 252, 52, 786, 262, 84, 60, 52, 796, 184, 66, 90, 132, 268, 404, 270, 270, 324, 126, 12, 820, 411, 20, 826, 828, 92, 168, 332, 90, 419, 812, 70, 156, 330, 94, 396, 852, 36, 428, 858, 60, 431, 172, 136, 390, 132, 48, 300, 876, 292, 55, 882, 116, 443, 21, 270, 414, 356, 132, 140, 104, 42, 180, 906, 300, 91, 410, 60, 390, 153, 102, 420, 180, 102, 464, 126, 310, 40, 117, 156, 940, 220, 36, 946, 36, 316, 68, 380, 140, 204, 155, 318, 96, 483, 72, 194, 138, 60, 488, 110, 36, 491, 196, 138, 154, 495, 30, 396, 332, 36, 60, 232, 132, 468, 504, 42, 92, 84, 84, 1018, 340, 10, 20, 156, 294, 515, 258, 132, 120, 519, 346, 444, 180, 348, 262, 350, 108, 420, 15, 88, 1060, 531, 140, 240, 356, 24, 252, 140, 358, 492, 253, 342, 60, 543, 330, 1090, 364, 36, 274, 156, 366, 29, 24, 180, 1108, 100, 156, 148, 1116, 372, 522, 1122, 300, 231, 564, 84, 510, 452, 378, 264, 162, 42, 76, 180, 382, 575, 288, 60, 132, 180, 126, 166, 116, 388, 249, 1170, 88, 460, 530, 390, 236, 156, 156, 1186, 140, 44, 298, 476, 18, 180, 300, 200, 24, 280, 60, 516, 1212, 324, 152, 572, 180, 611, 420, 204, 1228, 615, 204, 36, 1236, 174, 72, 140, 164, 28, 156, 138, 534, 100, 418, 1258, 48, 420, 220, 180, 414, 20, 198, 40, 1276, 639, 60, 1282, 16, 60, 161, 1290, 86, 36, 648, 72, 1300, 651, 84, 1306, 120, 198, 300, 524, 146, 659, 60, 126, 260, 221, 442, 1210, 70, 44, 285, 204, 444, 312, 268, 224, 630, 96, 20, 540, 638, 30, 680, 644, 12, 683, 1332, 76, 1372, 100, 216, 588, 1380, 460, 92, 18, 462, 636, 99, 60, 70, 233, 466, 660, 140, 66, 704, 328, 156, 188, 36, 70, 84, 237, 180, 1426, 84, 468, 179, 60, 478, 719, 130, 36, 136, 723, 66, 1450, 1452, 48, 115, 486, 486, 90, 292, 162, 84, 245, 490, 580, 210, 56, 370, 1482, 180, 743, 744, 210, 1492, 132, 166, 1498, 234, 498, 84, 340, 502, 755, 88, 100, 180, 105, 156, 1522, 60, 508, 690, 1530, 18, 204, 364, 54, 66, 771, 204, 24, 1548, 230, 194, 620, 516, 779, 111, 260, 156, 783, 522, 1570, 660, 60, 738, 526, 40, 791, 316, 506, 678, 252, 522, 140, 532, 60, 400, 228, 212, 803, 201, 534, 52, 72, 210, 1618, 1620, 540, 300, 542, 180, 87, 385, 36, 1636, 740, 546, 260, 276, 180, 48, 84, 252, 60, 92, 78, 30, 831, 36, 1666, 1668, 556, 357, 660, 84, 99, 820, 120, 84, 24, 562, 198, 1692, 28, 848, 566, 162, 780, 20, 284, 244, 812, 114, 588, 200, 570, 215, 574, 220, 260, 36, 144, 1732, 692, 96, 828, 1740, 246, 348, 1746, 260, 408, 146, 36, 150, 879, 586, 140, 88, 90, 420, 330, 588, 140, 74, 148, 204, 891, 24, 1786, 596, 198, 810, 716, 598, 48, 25, 50, 684, 276, 198, 362, 252, 220, 429, 424, 606, 911, 180, 84, 290, 305, 276, 732, 830, 612, 393, 144, 60, 923, 602, 154, 72, 156, 618, 780, 1860, 594, 372, 1866, 66, 935, 936, 500, 1876, 939, 90, 804, 84, 72, 472, 60, 90, 756, 135, 210, 1900, 860, 28, 1906, 902, 84, 239, 764, 630, 900, 56, 64, 60, 460, 214, 1930, 644, 84, 444, 276, 646, 924, 388, 290, 1948, 975, 30, 88, 306, 652, 468, 60, 260, 210, 890, 18, 1972, 780, 658, 1978, 282, 660, 44, 1986, 24, 180, 996, 36, 1996, 333][deck_size >> 1]", "def faro_cycles(deck_size):\n if deck_size <= 2:\n return 1\n k = 1\n while 2 ** k % (deck_size - 1) != 1:\n k += 1\n return k"], "starter_code": "def faro_cycles(deck_size):\n", "input_output": {"fn_name": "faro_cycles", "inputs": [[2], [52], [542], [1250], [1954]], "outputs": [[1], [8], [540], [156], [30]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Iterators", "Lists"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57bc802c615f0ba1e3000029", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "faro_cycles", "task_id": "TACO_lite/10", "example": [[[6], [52]], [4, 8]]} +{"requirement": "The Tribonacci sequence Tn is defined as follows:\u00a0\nT0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.\nGiven n, return the value of Tn.\n\u00a0\nExample 1:\nInput: n = 4\nOutput: 4\nExplanation:\nT_3 = 0 + 1 + 1 = 2\nT_4 = 1 + 1 + 2 = 4\n\nExample 2:\nInput: n = 25\nOutput: 1389537\n\n\u00a0\nConstraints:\n\n0 <= n <= 37\nThe answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.", "solutions": ["def tribonacci(n: int) -> int:\n if n == 0:\n return 0\n if n == 1:\n return 1\n ans = [0] * (n + 1)\n ans[0] = 0\n ans[1] = 1\n ans[2] = 1\n for i in range(3, n + 1):\n ans[i] = ans[i - 1] + ans[i - 2] + ans[i - 3]\n return ans[n]", "from collections import deque\n\ndef tribonacci(n: int) -> int:\n if n > 0 and n < 3:\n return 1\n if n == 0:\n return 0\n queue = deque([0, 1, 1])\n t = 2\n while t != n:\n queue.append(sum(queue))\n queue.popleft()\n t += 1\n return queue[2]", "def tribonacci(n: int) -> int:\n T = [0, 1, 1]\n for n in range(3, n + 1):\n T.append(T[n - 3] + T[n - 2] + T[n - 1])\n return T[n]", "def tribonacci(n: int) -> int:\n trib = []\n trib.append(0)\n trib.append(1)\n trib.append(1)\n for i in range(3, n):\n trib.append(trib[i - 1] + trib[i - 2] + trib[i - 3])\n if n > 2:\n return trib[n - 1] + trib[n - 2] + trib[n - 3]\n else:\n return trib[n]", "def tribonacci(n: int) -> int:\n try:\n return self.trib[n]\n except:\n currlen = len(self.trib)\n for i in range(currlen, n + 1):\n self.trib.append(self.trib[i - 1] + self.trib[i - 2] + self.trib[i - 3])\n return self.trib[n]", "def tribonacci(n: int) -> int:\n if n >= 0:\n if n < len(self.DP):\n return self.DP[n]\n else:\n offset: int = len(self.DP)\n self.DP.extend([0] * (n - offset + 1))\n for i in range(offset, n + 1):\n self.DP[i] = self.DP[i - 3] + self.DP[i - 2] + self.DP[i - 1]\n return self.DP[n]\n else:\n raise ValueError", "def tribonacci(n: int) -> int:\n t = [0, 1, 1]\n if n < 3:\n return t[n]\n for i in range(n - 2):\n t.append(sum(t))\n t = t[1:]\n return t[2]", "def tribonacci(n: int) -> int:\n if n == 0:\n return 0\n if n < 3:\n return 1\n (t0, t1, t2) = (0, 1, 1)\n for _ in range(3, n + 1):\n ans = t0 + t1 + t2\n (t0, t1, t2) = (t1, t2, ans)\n return ans"], "starter_code": "def tribonacci(n: int) -> int:\n", "input_output": {"fn_name": "tribonacci", "inputs": [[4]], "outputs": [4]}, "difficulty": "EASY", "raw_tags": ["Math", "Dynamic Programming", "Memoization"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Mathematics"], "skill_types": ["Dynamic programming"], "url": "https://leetcode.com/problems/n-th-tribonacci-number/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "tribonacci", "task_id": "TACO_lite/57", "example": [[[4], [25]], ["4", "1389537"]]} +{"requirement": "A frog starts at the point 0. In his first turn, he can make a jump of 1 unit. Now for all consequent turns, if the frog is currently at a distance x (from the start), his jump will take him x units forward. Given a leaf at a distance N, you have to find if the frog can reach that leaf or not.\n \nExample 1:\nInput:\nN = 3\nOutput:\nFalse\nExplanation:\nThe frog can't reach the position 3.\nExample 2:\nInput:\nN = 2\nOutput:\nTrue\nExplanation:\nThe frog will jump to position 1 in\nthe first jump. Now, he is at a distance\nof 1 from the start, so he cam jump 1m.\nSo, he reaches the point 2.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function canJump() which takes an Integer N as input and return \"True\" if the frog can reach N else return \"False\".\n \nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= N <= 10^{18}", "solutions": ["def canjump(N):\n if N == 1:\n return True\n if N % 2 == 1:\n return False\n else:\n while N > 2:\n N = N / 2\n if N % 2 == 1:\n return False\n break\n if N == 2:\n return True", "def canjump(N):\n prev = 1\n while prev <= N:\n if prev == N:\n return True\n prev += prev\n return False", "def canjump(n):\n if n & n - 1 == 0:\n return True\n else:\n return False", "def canjump(N):\n if N & N - 1 == 0:\n return 'True'\n return 'False'", "def canjump(N):\n i = 0\n a = 2 ** i\n while a < N:\n i += 1\n a = 2 ** i\n return a == N", "def canjump(N):\n return not N & N - 1", "def canjump(N):\n distance = 0\n while distance <= N:\n if distance == 0 or distance == 1:\n distance += 1\n else:\n distance *= 2\n if distance == N:\n return True\n return False", "import math\n\ndef canjump(N):\n num = int(math.log(N, 2))\n if 2 ** num == N:\n return 'True'\n else:\n return 'False'", "def canjump(n):\n return not n & n - 1", "def canjump(N):\n if N == 1 or (N and (not N & N - 1)) is True:\n return True\n return False", "def canjump(N):\n return N & N - 1 == 0", "def canjump(N):\n if N == 1 or N == 2:\n return True\n b = 2\n while b < N:\n b += b\n if b == N:\n return True\n else:\n return False", "def canjump(N):\n while True:\n if N == 1:\n return True\n elif N % 2 == 0:\n N = N // 2\n else:\n return False", "def canjump(N):\n return bin(N).count('1') == 1", "def canjump(N):\n jump_dist = 1\n dist = 0\n incr = 0\n while dist < N:\n dist += jump_dist\n if dist == N:\n return True\n jump_dist = dist\n return False", "def canjump(N):\n res = 0\n while pow(2, res) <= N:\n if pow(2, res) == N:\n return 'True'\n res += 1\n return False", "def canjump(n):\n k = 1\n while k <= n:\n if k == n:\n return True\n k = k * 2\n return False", "def canjump(N):\n j = 1\n while j <= N:\n if j == N:\n return True\n j = 2 * j\n return False", "def canjump(N):\n current = 1\n prev = 0\n result = False\n while prev <= N:\n if prev == N:\n result = True\n prev += current\n current = prev\n return result", "def canjump(x):\n if x == 1 or (x and (not x & x - 1)) is True:\n return True\n else:\n return False", "import math\n\ndef canjump(N):\n if math.log(N, 2).is_integer():\n return True\n return False", "def canjump(N):\n\n def possible(curr, prev):\n if curr == N:\n return True\n if curr > N:\n return False\n if prev == 0:\n return possible(curr + 1, 1)\n else:\n return possible(curr + prev, curr + prev)\n return possible(0, 0)", "import math\n\ndef canjump(N):\n return math.log(int(N), 2).is_integer()", "def canjump(N):\n if N == 1:\n return True\n Flag = False\n curr = 1\n while curr < N:\n curr += curr\n if curr == N:\n Flag = True\n return Flag", "def canjump(N):\n if N == 1:\n return True\n c_jump = 1\n jump = 0\n while jump < N:\n jump = jump + c_jump\n c_jump = jump\n if jump == N:\n return True\n else:\n return False", "def canjump(N):\n count = 0\n step = 1\n while count < N:\n count += step\n step = count\n if count == N:\n return True\n return False", "import math\n\ndef canjump(N):\n if N == 0:\n return true\n n = math.log2(N)\n if n == int(n):\n return True\n return False", "import math\n\ndef canjump(N):\n if N & N - 1 == 0:\n return True\n else:\n return False", "def canReach(n, i):\n if i == n:\n return True\n elif i > n:\n return False\n return self.canReach(n, i + i)\n\ndef canjump(N):\n if N == 0:\n return True\n i = 1\n return self.canReach(N, i)", "def canjump(N):\n for i in range(100):\n n = pow(2, i)\n if n == N:\n return 'True'\n return 'False'", "import math\n\ndef canjump(N):\n x = math.log(N, 2)\n if pow(2, int(x)) == N or N == 1:\n return True\n else:\n return False", "def canjump(N):\n if N == 0:\n return True\n if N == 1:\n return True\n ans = 1\n for i in range(1, N):\n ans = ans * 2\n if ans == N:\n return True\n if ans > N:\n return False\n return False", "def canjump(N):\n x = 0\n i = 1\n while x < N:\n x += i\n i = x\n if x == N:\n return True\n return False", "def canjump(N):\n position = 0\n num = N\n flag = 0\n while position <= num:\n if position == num:\n flag = 1\n if position == 0:\n position = position + 1\n else:\n position = 2 * position\n if flag == 0:\n return False\n else:\n return True", "def canjump(N):\n s = 0\n a = False\n i = 1\n while i <= N:\n if i == N:\n a = True\n break\n else:\n i = i * 2\n return a", "def canjump(N):\n n = N\n return n == 0 or n & n - 1 == 0", "def canjump(N):\n cj = 1\n j = 0\n while j < N:\n j = j + cj\n cj = j\n if j == N:\n return 'True'\n return 'False'", "def canjump(N):\n\n def isposs(n, N):\n if n == N:\n return True\n if n > N:\n return False\n return isposs(2 * n, N)\n return isposs(1, N)", "def canjump(N):\n curr_jump = 1\n jump = 0\n while jump < N:\n jump += curr_jump\n curr_jump = jump\n return jump == N", "def canjump(N):\n if N == 0 or N == 1:\n return True\n elif not N & N - 1:\n return True\n else:\n return False", "import math\n\ndef canjump(N):\n x = math.log(N) / math.log(2)\n if 2 ** x == 2 ** int(x):\n return True\n return False", "import math\n\ndef canjump(N):\n if N == 0 or N == 1:\n return 'True'\n res = math.log2(N)\n if int(res) == res:\n return 'True'\n return 'False'"], "starter_code": "def canjump(N):\n", "input_output": {"inputs": ["N = 3", "N = 2"], "outputs": ["False", "True"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/pattern-jumping4855/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "canjump", "task_id": "TACO_lite/17", "example": [[[3], [2]], ["False", "True"]]} +{"requirement": "Given an integer n, return the number of trailing zeroes in n!.\n\nExample 1:\n\n\nInput: 3\nOutput: 0\nExplanation:\u00a03! = 6, no trailing zero.\n\nExample 2:\n\n\nInput: 5\nOutput: 1\nExplanation:\u00a05! = 120, one trailing zero.\n\nNote: Your solution should be in logarithmic time complexity.", "solutions": ["def trailingzeroes(n):\n n_fives = 0\n while n > 0:\n n = n // 5\n n_fives += n\n return n_fives", "def trailingzeroes(n):\n c = 0\n while n > 0:\n n //= 5\n c += n\n return c", "def trailingzeroes(n):\n count = 1\n a = 5\n ans = 0\n while a <= n:\n ans += n // a\n count += 1\n a = 5 ** count\n return ans", "def trailingzeroes(n):\n return 0 if n == 0 else n // 5 + self.trailingzeroes(n // 5)", "def trailingzeroes(n):\n count = 0\n while n:\n count = count + n // 5\n n = n // 5\n return count", "def trailingzeroes(n):\n two = 0\n five = 0\n tmp = n\n while tmp != 0:\n tmp = tmp // 5\n five = five + tmp\n tmp = n\n while tmp != 0:\n tmp = tmp // 2\n two = two + tmp\n res = min(five, two)\n return res", "def trailingzeroes(n):\n ans = 0\n i = 5\n while n // i:\n ans += n // i\n i *= 5\n return ans", "def trailingzeroes(n):\n return sum([n // 5 ** i for i in range(1, 20)])", "def trailingzeroes(n):\n res = 5\n ans = 0\n while res < n + 1:\n ans += int(n / res)\n res = 5 * res\n return ans", "def trailingzeroes(n):\n trz = 0\n div = 5\n while div <= n:\n trz += int(n / div)\n div *= 5\n return trz", "def trailingzeroes(n):\n if n < 5:\n return 0\n elif n < 10:\n return 1\n i = 0\n while 5 ** (i + 1) <= n:\n i += 1\n s = n // 5\n j = 2\n while j <= i:\n s += n // 5 ** j\n j += 1\n return int(s)", "def trailingzeroes(n):\n num2 = 0\n div = 2\n quot = n // div\n while quot:\n num2 += quot\n div *= 2\n quot = n // div\n num5 = 0\n div = 5\n quot = n // div\n while quot:\n num5 += quot\n div *= 5\n quot = n // div\n return min(num2, num5)"], "starter_code": "def trailingzeroes(n: int) -> int:\n", "input_output": {"fn_name": "trailingZeroes", "inputs": [[3]], "outputs": [0]}, "difficulty": "EASY", "raw_tags": ["Math"], "name": null, "source": "leetcode", "tags": ["Mathematics"], "skill_types": [], "url": "https://leetcode.com/problems/factorial-trailing-zeroes/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "trailingzeroes", "task_id": "TACO_lite/66", "example": [[[3], [5]], ["0", "1"]]} +{"requirement": "Given an integer N, count the numbers having an odd number of factors from 1 to N (inclusive).\n \nExample 1:\nInput:\nN = 5\nOutput:\n2\nExplanation:\nFrom 1 - 5 only 2 numbers,\n1 and 4 are having odd number\nof factors.\nExample 2:\nInput:\nN = 1\nOutput:\n1\nExplanation:\n1 have only 1(odd)\nfactor\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function count() which takes an integer N as input parameters and returns an integer, the total count of numbers from 1 to N having an odd number of factors.\n \nExpected Time Complexity: O(sqrt(N))\nExpected Space Complexity: O(1)\n \nConstraints:\n0 <= N <= 10^{9}", "solutions": ["import math\n\ndef count(N):\n c = 0\n for i in range(1, N + 1):\n if i * i <= N:\n c += 1\n return c", "import math\n\ndef count(N):\n return math.floor(math.sqrt(N))", "def count(N):\n return int(N ** 0.5)", "def count(N):\n count_odd = 0\n for i in range(1, N + 1):\n if int(i ** 0.5) ** 2 == i:\n count_odd += 1\n return count_odd", "from math import *\n\ndef count(N):\n return int(N ** 0.5)", "import math\n\ndef count(N):\n return int(math.sqrt(N))", "def count(N):\n import math\n self.N = N\n p = math.sqrt(N)\n q = math.floor(p)\n return q", "import math\n\ndef count(N):\n (count, d) = (0, 0)\n for i in range(1, N + 1):\n d = int(math.sqrt(i))\n if i == d * d:\n count += 1\n return count", "def count(N):\n c = 0\n for i in range(1, N + 1):\n if i ** 0.5 == int(i ** 0.5):\n c = c + 1\n return c", "def count(N):\n import math\n if N == 1:\n return 1\n else:\n return int(math.sqrt(N))", "def count(N):\n count = 0\n val = int(pow(N, 0.5))\n for i in range(1, val + 1):\n if i * i <= N:\n count += 1\n return count", "import math\n\ndef count(N):\n ar = [1]\n for i in range(2, N + 1):\n if math.sqrt(i) == int(math.sqrt(i)):\n ar.append(i)\n return len(ar)", "import math\n\ndef count(n):\n if n == 1:\n return 1\n return int(math.sqrt(n))", "def sqrt(N):\n l = 1\n r = N\n m = N // 2\n while l <= r:\n if m * m == N:\n return m\n elif m * m > N:\n r = m - 1\n else:\n l = m + 1\n m = (l + r) // 2\n return m\n\ndef count(N):\n val = self.sqrt(N)\n return val", "import math\nfrom math import floor, ceil\n\ndef count(N):\n return floor(math.sqrt(N))", "def count(N):\n import math\n c = 1\n for i in range(2, N + 1):\n if int(math.sqrt(i) * int(math.sqrt(i)) == i):\n c = c + 1\n return c", "def count(N):\n a = 0\n b = N\n return int(b ** 0.5) - int(a ** 0.5)", "def count(N):\n count1 = 0\n for i in range(1, N + 1):\n if i * i <= N:\n count1 += 1\n return count1", "import math\n\ndef count(N):\n c = 0\n if N == 1:\n return 1\n else:\n for i in range(1, N):\n if math.ceil(math.sqrt(i)) == math.floor(math.sqrt(i)):\n c += 1\n return c", "from math import *\n\ndef count(N):\n main_count = 0\n for i in range(1, N + 1):\n result = int(sqrt(i))\n if result * result == i:\n main_count += 1\n return main_count", "def count(N):\n fac = int(pow(N, 1 / 2))\n return fac", "import math\n\ndef count(n):\n return int(math.sqrt(n))", "def helper(n):\n sr = n ** 0.5\n m1 = sr % 1\n if m1 == 0:\n return True\n else:\n return False\n\ndef count(N):\n ans = 1\n for i in range(2, N):\n if self.helper(i):\n ans += 1\n return ans", "import math\n\ndef count(N):\n count = 0\n for i in range(1, N + 1):\n square = i ** (1 / 2)\n if math.ceil(square) == math.floor(square):\n count += 1\n return count"], "starter_code": "def count (N):\n", "input_output": {"inputs": ["N = 5", "N = 1"], "outputs": ["2", "1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/count-odd-factors0844/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(sqrt(N))", "entry_point": "count", "task_id": "TACO_lite/43", "example": [[[5], [1]], ["2", "1"]]} +{"requirement": "An **anagram** is the result of rearranging the letters of a word to produce a new word.\n\n**Note:** anagrams are case insensitive\n\nComplete the function to return `true` if the two arguments given are anagrams of each other; return `false` otherwise.\n\n\n## Examples\n\n* `\"foefet\"` is an anagram of `\"toffee\"`\n\n* `\"Buckethead\"` is an anagram of `\"DeathCubeK\"`", "solutions": ["def is_anagram(test, original):\n return sorted(original.lower()) == sorted(test.lower())", "from collections import Counter\n\ndef is_anagram(test, original):\n return Counter(test.lower()) == Counter(original.lower())", "def is_anagram(test, original):\n return sorted(test.upper()) == sorted(original.upper())", "def is_anagram(test, original):\n (test_dict, original_dict) = ({}, {})\n for i in test.lower():\n test_dict[i] = test_dict.get(i, 0) + 1\n for i in original.lower():\n original_dict[i] = original_dict.get(i, 0) + 1\n return test_dict == original_dict", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n count = [0] * 26\n for i in range(len(test)):\n count[(ord(test[i]) & 31) - 1] += 1\n count[(ord(original[i]) & 31) - 1] -= 1\n return not any(count)", "def is_anagram(test, original):\n a = sorted(test.lower())\n b = sorted(original.lower())\n c = ''.join(a)\n d = ''.join(b)\n if c == d:\n return True\n else:\n return False", "def is_anagram(test, original):\n go = len(test) == len(original)\n arr = []\n if go:\n for i in test:\n arr.append(i.lower() in original.lower())\n return False not in arr\n else:\n return False", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n for l in test.lower():\n if l not in original.lower():\n return False\n return True", "from operator import eq\nfrom collections import Counter\n\ndef is_anagram(test, original):\n return eq(*map(Counter, map(str.lower, (test, original))))", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n return sorted(test.lower()) == sorted(original.lower())", "def is_anagram(test, original):\n if sorted(test.lower()) == sorted(original.lower()):\n return True\n else:\n return False", "is_anagram = lambda t, o: sorted(t.lower()) == sorted(o.lower())", "aprime = {'a': 2, 'c': 5, 'b': 3, 'e': 11, 'd': 7, 'g': 17, 'f': 13, 'i': 23, 'h': 19, 'k': 31, 'j': 29, 'm': 41, 'l': 37, 'o': 47, 'n': 43, 'q': 59, 'p': 53, 's': 67, 'r': 61, 'u': 73, 't': 71, 'w': 83, 'v': 79, 'y': 97, 'x': 89, 'z': 101}\n\ndef aprime_sum(str):\n strChList = list(str.lower())\n return sum([aprime[x] for x in strChList])\n\ndef is_anagram(test, original):\n if aprime_sum(test) == aprime_sum(original):\n return True\n else:\n return False", "def is_anagram(test, original):\n return set(original.lower()) == set(test.lower()) if len(test) == len(original) else False", "def is_anagram(test, original):\n a = list(test.lower())\n s = list(original.lower())\n if len(a) != len(s):\n return False\n else:\n for i in a:\n cond = False\n k = 0\n while k != len(s) and cond == False:\n if i == s[k]:\n a.remove(i)\n s.remove(i)\n cond = True\n k += 1\n if cond == False:\n return False\n if len(a) != len(s):\n return False\n else:\n return True", "def is_anagram(test, original):\n flag = 0\n if len(test) != len(original):\n return False\n else:\n for i in test.lower():\n if i not in original.lower():\n flag = 1\n else:\n continue\n if flag == 1:\n return False\n else:\n return True", "def is_anagram(test, original):\n\n def to_dict(word):\n dictionary = {}\n for w in word.lower():\n if w not in dictionary:\n dictionary[w] = 0\n else:\n dictionary[w] += 1\n return dictionary\n return to_dict(test) == to_dict(original)", "is_anagram = lambda a, b, s=sorted: s(a.lower()) == s(b.lower())", "def is_anagram(s, l):\n n = len(s)\n if len(l) != n:\n return False\n s = s.lower()\n l = l.lower()\n h = [0 for x in range(26)]\n for i in range(n):\n h[ord(s[i]) - 97] += 1\n h[ord(l[i]) - 97] -= 1\n return h.count(0) == 26", "def is_anagram(test: str, original: str) -> bool:\n return all([all([_ in original.lower() for _ in test.lower()]), len(test) == len(original)])", "def is_anagram(test, original):\n test = test.lower()\n original = original.lower()\n testcount = 0\n for i in test:\n if i in original:\n testcount += 1\n originalcount = 0\n for i in original:\n if i in test:\n originalcount += 1\n if testcount == originalcount and testcount == len(test) and (originalcount == len(original)):\n return True\n else:\n return False", "def is_anagram(test, original):\n if len(test) == len(original):\n test = test.lower()\n original = original.lower()\n count = 0\n for char in test:\n if char in original:\n count += 1\n if count == len(test):\n return True\n else:\n return False\n else:\n return False", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n letters = {}\n for i in test.lower():\n if i in letters:\n letters[i] += 1\n else:\n letters[i] = 1\n for i in original.lower():\n if i not in letters:\n return False\n if original.lower().count(i) != letters[i]:\n return False\n return True", "def is_anagram(t, o):\n return sorted([*t.lower()]) == sorted([*o.lower()])", "def is_anagram(test, original):\n x = list(test.lower())\n y = list(original.lower())\n x = sorted(x)\n y = sorted(y)\n if x == y:\n return True\n else:\n return False", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n a = sorted(test.lower())\n b = sorted(original.lower())\n if a == b:\n return True\n else:\n return False", "def is_anagram(test, original):\n sorted_test = sorted(list(test.lower()))\n sorted_original = sorted(list(original.lower()))\n return sorted_test == sorted_original", "def is_anagram(test, original):\n letters = [c for c in test.lower()]\n for char in original.lower():\n if char in letters:\n del letters[letters.index(char)]\n else:\n return False\n return not bool(len(letters))", "import collections\n\ndef is_anagram(test, original):\n return collections.Counter([i.lower() for i in sorted(test)]) == collections.Counter([i.lower() for i in sorted(original)])", "def is_anagram(test, original):\n test_set = sorted(test.lower())\n original_set = sorted(original.lower())\n if test_set == original_set:\n return True\n else:\n return False", "def is_anagram(test, original):\n t = sorted(test.lower())\n o = sorted(original.lower())\n if t == o:\n return True\n else:\n return False", "def is_anagram(test, original):\n new_test = test.lower()\n new_original = original.lower()\n sortedTest = sorted(new_test)\n sortedOriginal = sorted(new_original)\n for letters in new_test:\n if letters in new_original and len(new_test) == len(new_original) and (sortedOriginal == sortedTest):\n return True\n else:\n return False", "def is_anagram(test, original):\n first = [i.lower() for i in test]\n second = [i.lower() for i in original]\n return sorted(first) == sorted(second)", "def is_anagram(test, original):\n list_test = []\n list_original = []\n for i in test.lower():\n list_test += i\n for i in original.lower():\n list_original += i\n if len(list_test) == len(list_original):\n list_test.sort()\n list_original.sort()\n if list_test == list_original:\n return True\n else:\n return False\n else:\n return False", "def is_anagram(test, original):\n return True if sorted([letter for letter in test.lower()]) == sorted([letter for letter in original.lower()]) else False", "def is_anagram(test, original):\n t = list(test.lower())\n to = ''.join(sorted(t))\n o = list(original.lower())\n oo = ''.join(sorted(o))\n if to == oo:\n return True\n else:\n return False", "def is_anagram(test, original):\n letterCount = dict.fromkeys('abcdefghijklmnopqrstuvwxyz', 0)\n for c in test.lower():\n letterCount[c] += 1\n for c in original.lower():\n letterCount[c] -= 1\n for value in list(letterCount.values()):\n if value != 0:\n return False\n return True", "def is_anagram(a_str, b_str):\n if len(a_str) == len(b_str):\n a_list = list(a_str.lower())\n b_list = list(b_str.lower())\n for char in a_list:\n if char in b_list:\n b_list.remove(char)\n if not b_list:\n return True\n else:\n return False\n else:\n return False", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n else:\n test = test.lower()\n original = original.lower()\n counter_original = [0] * 26\n counter_test = [0] * 26\n for i in test:\n counter_test[ord(i) - 97] += 1\n for i in original:\n counter_original[ord(i) - 97] += 1\n return counter_test == counter_original", "def is_anagram(test, original):\n test = test.lower()\n original = original.lower()\n newList = [ord(c) for c in test]\n newList.sort()\n newList2 = [ord(b) for b in original]\n newList2.sort()\n if newList == newList2:\n return True\n else:\n return False", "def is_anagram(test, original):\n counterTest = [0] * 255\n counterOri = [0] * 255\n for i in range(len(test)):\n counterTest[ord(test[i].lower())] += 1\n for i in range(len(original)):\n counterOri[ord(original[i].lower())] += 1\n if counterOri == counterTest:\n return True\n else:\n return False", "def is_anagram(test, original):\n test = test.upper()\n original = original.upper()\n if sorted(test) == sorted(original):\n return True\n else:\n return False", "def is_anagram(test, original):\n if len(test) == len(original):\n test = test.lower()\n original = original.lower()\n for i in test:\n if original.find(i) == -1:\n return False\n else:\n test.replace(i, '')\n original.replace(i, '')\n else:\n return False\n return True", "def is_anagram(test, original):\n counter1 = [0] * 255\n counter2 = [0] * 255\n for i in range(len(test)):\n counter1[ord(test[i].lower())] += 1\n for i in range(len(original)):\n counter2[ord(original[i].lower())] += 1\n return counter1 == counter2", "def is_anagram(test, original):\n test = test.lower()\n original = original.lower()\n for x in range(len(test)):\n if test.count(test[x]) != original.count(test[x]):\n return False\n for x in range(len(original)):\n if test.count(original[x]) != original.count(original[x]):\n return False\n return True", "def is_anagram(test, original):\n test = test.lower()\n original = original.lower()\n nT = len(test)\n nO = len(original)\n if nO == nT:\n counterT = [0] * (255 + 1)\n counterO = [0] * (255 + 1)\n for x in range(nT):\n counterT[ord(test[x])] += 1\n counterO[ord(original[x])] += 1\n if counterT == counterO:\n return True\n else:\n return False\n else:\n return False", "def is_anagram(test, original):\n n = len(original)\n if n != len(test):\n return False\n counterTest = [0] * 255\n counterOrig = [0] * 255\n for i in range(n):\n counterTest[ord(test[i].lower())] += 1\n counterOrig[ord(original[i].lower())] += 1\n return True if ''.join(map(str, counterTest)) == ''.join(map(str, counterOrig)) else False", "def is_anagram(test, original):\n return sorted([n.lower() for n in test]) == sorted([n.lower() for n in original])", "def is_anagram(word_o, test_o):\n is_anagram = True\n word = word_o.lower()\n test = test_o.lower()\n if len(word) != len(test):\n is_anagram = False\n alist = list(test.lower())\n pos1 = 0\n while pos1 < len(word) and is_anagram:\n pos2 = 0\n found = False\n while pos2 < len(alist) and (not found):\n if word[pos1] == alist[pos2]:\n found = True\n else:\n pos2 = pos2 + 1\n if found:\n alist[pos2] = None\n else:\n is_anagram = False\n pos1 = pos1 + 1\n return is_anagram", "def is_anagram(test, original):\n l1 = list(test.lower())\n l2 = list(original.lower())\n if len(l1) == len(l2):\n for i in l1:\n if i in l2:\n l2.remove(i)\n else:\n return False\n else:\n return False\n return True", "def is_anagram(test, original):\n for i in test.lower():\n if i in original.lower() and len(test) == len(original):\n continue\n else:\n return False\n return True", "def is_anagram(test, original):\n test_list = [letter1 for letter1 in test.lower()]\n orig_list = [letter2 for letter2 in original.lower()]\n if sorted(test_list) == sorted(orig_list):\n return True\n else:\n return False", "def is_anagram(test, original):\n test = [i.lower() for i in test]\n original = [j.lower() for j in original]\n test.sort()\n original.sort()\n return test == original", "def is_anagram(test, original):\n test = test.lower()\n original = original.lower()\n if len(test) != len(original):\n return False\n for x in test:\n if test.count(x) == original.count(x):\n continue\n else:\n return False\n return True", "def is_anagram(test, original):\n test = test.lower()\n original = original.lower()\n new_test = list(test)\n new_original = list(original)\n new_test.sort()\n new_original.sort()\n if new_test == new_original:\n return True\n return False\n pass", "def is_anagram(test, original):\n return set(test.upper()) == set(original.upper()) and len(test) == len(original)", "is_anagram = lambda test, original: True if sorted(original.lower()) == sorted(test.lower()) else False", "def is_anagram(test, original):\n originalLower = [val for val in original.lower()]\n arr = test.lower()\n if len(arr) != len(originalLower):\n return False\n for element in arr:\n if element not in originalLower:\n return False\n else:\n originalLower.remove(element)\n return True", "def is_anagram(test, original):\n n1 = len(test)\n n2 = len(original)\n if n1 != n2:\n return False\n str1 = sorted(test.lower())\n str2 = sorted(original.lower())\n for i in range(0, n1):\n if str1[i] != str2[i]:\n return False\n return True", "def is_anagram(test, original):\n test_l = list(test.lower())\n original_l = list(original.lower())\n test_l.sort()\n original_l.sort()\n if test_l == original_l:\n return True\n else:\n return False", "def is_anagram(test, original):\n test = list(test.lower())\n original = list(original.lower())\n if len(test) != len(original):\n return False\n for word in test:\n for word2 in original:\n if word == word2:\n original.remove(word2)\n break\n if len(original) == 0:\n return True\n else:\n return False", "def is_anagram(test, original):\n\n def to_list(string):\n listed = []\n for i in range(len(string)):\n listed.append(string[i])\n return listed\n return str(sorted(to_list(test.lower()))) == str(sorted(to_list(original.lower())))", "def is_anagram(test, original):\n test = list(test.lower())\n test.sort()\n original = list(original.lower())\n original.sort()\n if original != test or len(test) != len(original):\n return False\n else:\n return True", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n test = sorted(test.lower())\n original = sorted(original.lower())\n for i in range(len(test)):\n if test[i] != original[i]:\n return False\n return True", "def is_anagram(test, original):\n result = True if len(test) == len(original) else False\n for letter in test.upper():\n result = False if letter not in original.upper() else result\n return result", "def is_anagram(test, original):\n if len(original) != len(test):\n return False\n test = test.lower()\n original = original.lower()\n for letter in original:\n if original.count(letter) != test.count(letter):\n return False\n return True", "def is_anagram(test, original):\n if sorted(test.lower()) == sorted(original.lower()):\n return True\n elif test != original:\n return False", "def is_anagram(test, original):\n test_list = sorted(list(test.lower()))\n original_list = sorted(list(original.lower()))\n if test_list == original_list:\n return True\n if test_list != original_list:\n return False", "def is_anagram(test, original):\n test = test.lower()\n original = original.lower()\n t = list(test)\n o = list(original)\n t.sort()\n o.sort()\n return t == o", "def is_anagram(test, original):\n t = test.lower()\n o = [*original.lower()]\n if len(t) != len(o):\n return False\n for c in t:\n if c in o:\n o.remove(c)\n else:\n return False\n return True", "def is_anagram(test, original):\n if len(test) > len(original) or len(test) < len(original):\n return False\n res = ''\n counter = 0\n sortedTest = sorted(test.lower())\n sortedOriginal = sorted(original.lower())\n for i in range(0, len(sortedTest)):\n if sortedTest[i] != sortedOriginal[i]:\n res = False\n break\n else:\n res = True\n return res", "from collections import Counter as C\n\ndef is_anagram(test, original):\n return C(test.lower()) == C(original.lower())", "def is_anagram(test, original):\n sort1 = sorted(test.lower())\n sort2 = sorted(original.lower())\n if ''.join(sort2) == ''.join(sort1):\n return True\n else:\n return False", "def is_anagram(test, original):\n theTest = test.lower()\n theOriginal = original.lower()\n if len(theTest) != len(theOriginal):\n return False\n else:\n index = 0\n lengthCheck = 0\n array = [None] * len(theTest)\n for i in theOriginal:\n array[index] = i\n index += 1\n for j in theTest:\n testLength = len(theTest)\n if j in array:\n lengthCheck += 1\n else:\n return False\n if lengthCheck == testLength:\n return True", "def is_anagram(tst, org):\n tst = tst.lower()\n org = org.lower()\n if len(tst) != len(org):\n return False\n for i in org:\n if tst.count(i) != org.count(i):\n return False\n return True", "def is_anagram(test, original):\n if len(test) != len(original):\n return False\n elif sorted(test.casefold()) == sorted(original.casefold()):\n return True\n else:\n return False", "def is_anagram(test, original):\n letters_original = sorted(list(original.upper()))\n letters_test = sorted(list(test.upper()))\n return letters_original == letters_test", "def is_anagram(test, original):\n return len(test) == len(original) and all([i in original.lower() for i in test.lower()])", "def is_anagram(test, original):\n org1 = [x.lower() for x in original]\n org2 = [y.lower() for y in test]\n org1.sort()\n org2.sort()\n if org1 == org2:\n return True\n return False", "def is_anagram(test, original):\n original_list = list(original.lower())\n test_list = list(test.lower())\n original_list.sort()\n test_list.sort()\n a = ''.join(test_list)\n b = ''.join(original_list)\n return a == b", "def is_anagram(test, original):\n test = test.lower().replace(' ', '')\n original = original.lower().replace(' ', '')\n if len(test) != len(original):\n return False\n for letter in test:\n if letter not in original:\n return False\n for letter in original:\n if letter not in test:\n return False\n return True"], "starter_code": "def is_anagram(test, original):\n", "input_output": {"fn_name": "is_anagram", "inputs": [["foefet", "toffee"], ["Buckethead", "DeathCubeK"], ["Twoo", "WooT"], ["dumble", "bumble"], ["ound", "round"], ["apple", "pale"]], "outputs": [[true], [true], [true], [false], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/529eef7a9194e0cbc1000255", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_anagram", "task_id": "TACO_lite/1", "example": [[], []]} +{"requirement": "Given 2 integers n and r. You task is to calculate ^{n}Cr%1000003.\n \nExample 1:\nInput: n = 5, r = 2\nOutput: 10\nExplanation: ^{5}C2 = 5! / (2! * 3!) = 10\nExample 2:\nInput: n = 3, r = 2\nOutput: 3\nExplanation: ^{3}C2 = 3! / (2! * 1!) = 3\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function nCr() which takes n and r as input parameter and returns nCr modulo 1000003.\n \nExpected Time Complexity: O(m * log_{m}n) where m = 1000003\nExpected Space Complexity: O(m)\n \nConstraints:\n1 <= n <= r <= 10^{16}", "solutions": ["M = 1000003\n\ndef __init__():\n self.f = [1] * M\n for i in range(1, M):\n self.f[i] = self.f[i - 1] * i % M\n\ndef ncr(n, r):\n if r > n:\n return 0\n if r == 0:\n return 1\n if n < M and r < M:\n return self.f[n] * pow(self.f[r], M - 2, M) * pow(self.f[n - r], M - 2, M) % M\n return self.ncr(n // M, r // M) * self.ncr(n % M, r % M) % M", "def fact(dp, p):\n dp[0] = 1\n for i in range(1, p):\n dp[i] = dp[i - 1] * i % p\n\ndef inverse(x, p):\n if not x:\n return 1\n for i in range(1, p):\n if int(x * i % p) == int(1 % p):\n return i\n\ndef find(n, r, p, dp):\n if n < r:\n return 0\n num = dp[n]\n den = dp[n - r] * dp[r] % p\n val = num * self.inverse(den, p) % p\n return val\n\ndef lucas(n, r, dp, p):\n if r == 0:\n return 1\n ni = int(n % p)\n ri = int(r % p)\n return self.lucas(n / p, r / p, dp, p) * self.find(ni, ri, p, dp) % p\n\ndef ncr(n, r):\n p = 1000003\n dp = [0] * 1000004\n self.fact(dp, p)\n return self.lucas(n, r, dp, p)", "def ncr(n, r):\n mod = 1000003\n\n def bin_expo(a, b):\n ans = 1\n while b > 0:\n if b & 1:\n ans = ans * a % mod\n a = a * a % mod\n b = b // 2\n return ans\n\n def mod_inverse(a):\n return bin_expo(a, mod - 2)\n\n def fermat(n, r):\n if n < r:\n return 0\n if r == 0 or n == r:\n return 1\n if r == n - 1 or r == 1:\n return n\n fact = [0] * (n + 1)\n fact[0] = 1\n for i in range(1, n + 1):\n fact[i] = fact[i - 1] * i % mod\n a = fact[n]\n b = mod_inverse(fact[r])\n c = mod_inverse(fact[n - r])\n return a * b % mod * c % mod % mod\n\n def lucas(n, r):\n if r == 0:\n return 1\n ni = n % mod\n ri = r % mod\n return lucas(n // mod, r // mod) * fermat(ni, ri) % mod\n return lucas(n, r)", "def ncrfarment(n, r):\n p = 1000003\n num = den = 1\n for i in range(r):\n num = num * (n - i) % p\n den = den * (i + 1) % p\n return num * pow(den, p - 2, p) % p\n\ndef ncr(n, r):\n p = 1000003\n if r == 0:\n return 1\n ni = int(n % p)\n ri = int(r % p)\n return self.ncr(int(n / p), int(r / p)) * self.ncrfarment(ni, ri) % p", "def ncr(n, r):\n large = 1000003\n (num, den) = self.test(n, r)\n inv = self.modular_inverse(den, large)\n return num * inv % large\n\ndef test(n, r):\n if r == 0:\n return (1, 1)\n large = 1000003\n r = min(r, n - r)\n until = r % large + large if r > large else r\n n_i = (n - r) % large\n r_i = 0\n num = 1\n den = 1\n zero = 0\n while r_i < until:\n n_i = (n_i + 1) % large\n r_i += 1\n if n_i == 0:\n zero += 1\n if zero > until // large:\n return (0, 1)\n else:\n num = num * n_i % large\n if r_i % large > 0:\n den = den * (r_i % large) % large\n (num_1, den_1) = self.test(n // large, r // large)\n num = num * num_1 % large\n den = den * den_1 % large\n return (num, den)\n\ndef modular_inverse(a, n):\n x1 = 0\n x2 = 1\n while a != 0:\n q = n // a\n (n, a) = (a, n % a)\n (x1, x2) = (x2, x1 - x2 * q)\n return x1", "def fact(dp, p):\n dp[0] = 1\n for i in range(1, p):\n dp[i] = dp[i - 1] * i % p\n\ndef inverse(x, p):\n if x == 0:\n return 1\n for i in range(1, p):\n if x * i % p == 1 % p:\n return i\n\ndef ncr(dp, n, r, p):\n if n < r:\n return 0\n num = dp[n] % p\n den = dp[n - r] * dp[r] % p\n return num * self.inverse(den, p) % p\n\ndef lucas(dp, n, r, p):\n if r == 0:\n return 1\n n_ = int(n % p)\n r_ = int(r % p)\n return self.lucas(dp, n / p, r / p, p) * self.ncr(dp, n_, r_, p) % p\n\ndef ncr(n, r):\n p = 1000003\n dp = [0 for _ in range(p + 1)]\n self.fact(dp, p)\n return self.lucas(dp, n, r, p)", "M = 1000003\n\ndef lucas(n, r, m):\n if r == 0:\n return 1\n if n < m and r < m:\n (f, r) = ([1] * (n + 1), min(r, n))\n for i in range(1, len(f)):\n f[i] = f[i - 1] * i % m\n return f[n] * pow(f[r], m - 2, m) * pow(f[n - r], m - 2, m) % m\n return lucas(n // m, r // m, m) * lucas(n % m, r % m, m) % m\n\ndef ncr(n, r):\n\n def count(x):\n res = 0\n while x > 0:\n res += x // M\n x //= M\n return res\n if count(n) > count(r) + count(n - r):\n return 0\n return lucas(n, r, M)\n\ndef __init__():\n self.a = [1] * M\n for i in range(1, len(self.a)):\n self.a[i] = self.a[i - 1] * i % M", "def __init__():\n self.m = 1000003\n self.fact = [1] * self.m\n for i in range(1, self.m):\n self.fact[i] = self.fact[i - 1] * i % self.m\n\ndef fast_pow(base, exp):\n res = 1\n while exp:\n if exp % 2:\n res = res * base % self.m\n base = base * base % self.m\n exp //= 2\n return res\n\ndef inverse(a):\n return self.fast_pow(a, self.m - 2)\n\ndef small(n, r):\n if r > n:\n return 0\n return self.fact[n] * self.inverse(self.fact[r] * self.fact[n - r] % self.m) % self.m\n\ndef ncr(n, r):\n if n == 0 or r == 0:\n return 1\n return self.ncr(n // self.m, r // self.m) * self.small(n % self.m, r % self.m) % self.m", "def __init__():\n self.m = 1000003\n self.fact = [1] * self.m\n for i in range(1, self.m):\n self.fact[i] = self.fact[i - 1] * i % self.m\n\ndef inverse(a):\n return pow(a, self.m - 2, self.m)\n\ndef small(n, r):\n if r > n:\n return 0\n return self.fact[n] * self.inverse(self.fact[r] * self.fact[n - r] % self.m) % self.m\n\ndef ncr(n, r):\n if n == 0 or r == 0:\n return 1\n return self.ncr(n // self.m, r // self.m) * self.small(n % self.m, r % self.m) % self.m"], "starter_code": "def ncr(n, r):\n", "input_output": {"inputs": ["n = 5, r = 2", "n = 3, r = 2"], "outputs": ["10", "3"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Combinatorial", "Algorithms", "Modular Arithmetic"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory", "Combinatorics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/ncr-mod-m-part-10038/1", "Expected Auxiliary Space": "O(m)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(m * log_{m}n) where m = 1000003", "entry_point": "ncr", "task_id": "TACO_lite/14", "example": [[[5, 2], [3, 2]], ["10", "3"]]} +{"requirement": "An enemy spy has poisoned one out of N sweets in a bakery. Even a bite of the poisoned sweet has potency to kill. However, the effects of the poison show only in 30 days. The managers asks the jailor to identify the poisoned sweet within 30 days. What is the least number of prisoners the jailor must employ to identify the poisoned sweet?\nNote: A sweet can be eaten by any number of prisoners.\n \nExample 1:\nInput:\nN = 3\nOutput:\n2\nExplanation:\nThe poison can be identified using\nonly 2 prisoners.\nExample 2:\nInput:\nN = 2\nOutput:\n1\nExplanation:\nThe poison can be identified using\nonly 1 prisoner.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function numOfPrisoners() which takes an Integer N as input and returns the minimum number of prisoners required to identify the poisoned sweet.\n \nExpected Time Complexity: O(log(N))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= N <= 10^{9}", "solutions": ["def numofprisoners(N):\n if N == 1:\n return 0\n c = int(math.log2(N))\n if 2 ** c < N:\n c += 1\n return c", "from math import *\n\ndef numofprisoners(N):\n return ceil(log(N, 2))"], "starter_code": "def numofprisoners(N):\n", "input_output": {"inputs": ["N = 3", "N = 2"], "outputs": ["2", "1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/poisioned-sweet2651/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(N))", "entry_point": "numofprisoners", "task_id": "TACO_lite/73", "example": [[[3], [2]], ["2", "1"]]} +{"requirement": "Given an string S, representing a large interger. Return the largest-valued odd integer (as a string) that is substring of the given string S.\nNote : A substring is a contiguous sequence of characters within a string. Null string (\"\") is also a substring.\nExample 1:\nInput: s = \"504\"\nOutput: \"5\"\nExplanation: The only subtring \"5\" is odd number.\n \nExample 2:\nInput: s = \"2042\"\nOutput: \"\"\nExplanation: All the possible non-empty substring have even value.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function maxOdd() which takes the string S as input and returns the largest-valued odd integer that is substring of the given string.\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1).\nConstraints:\n1<=|S|<=2*10^{5}\nS only consists of digits and does not contain any leading zeros.", "solutions": ["def maxodd(s):\n for i in range(len(s) - 1, -1, -1):\n if s[i] in {'1', '3', '5', '7', '9'}:\n return s[:i + 1]\n return ''", "import sys\n\ndef maxodd(s):\n ss = s[::-1]\n for i in range(len(ss)):\n if int(ss[i]) % 2 != 0:\n sss = ss[i:]\n return sss[::-1]\n return ''", "def maxodd(s):\n end = -1\n start = 0\n for i in range(0, len(s)):\n if int(s[i]) % 2 != 0:\n end = i\n if end == -1:\n return ''\n return s[start:end + 1]", "def maxodd(s):\n n = len(s) - 1\n while n >= 0:\n if int(s[n]) % 2 != 0:\n return s[:n + 1]\n n -= 1\n return ''", "def maxodd(num):\n op = []\n for i in range(len(num)):\n if int(num[i]) % 2 != 0:\n op.append(i)\n else:\n pass\n if len(op) == 0:\n return ''\n elif op[-1] == len(num) - 1:\n return num\n else:\n return ''.join(num[:op[-1] + 1])", "def maxodd(s):\n l = list(map(int, s))\n st = 0\n t = 0\n for i in range(len(l)):\n if l[i] % 2 != 0:\n t = 1\n st = i\n if t == 0:\n return ''\n return s[:st + 1]", "def maxodd(s):\n ch = 0\n for i in s:\n if int(i) % 2 != 0:\n ch = 1\n if ch == 0:\n return ''\n else:\n for i in range(len(s) - 1, -1, -1):\n if int(s[i]) % 2 != 0:\n return int(s[:i + 1])", "def maxodd(s):\n ma = 0\n for i in range(len(s), -0, -1):\n if int(s[0:i]) % 2 == 1:\n ma = max(ma, int(s[0:i]))\n if ma == 0:\n return ''\n return ma", "def maxodd(S):\n end = None\n for i in range(len(S) - 1, -1, -1):\n if int(S[i]) % 2 != 0:\n end = i\n break\n if end is not None:\n return S[:end + 1]\n return ''", "def maxodd(num):\n if float(num) % 2 != 0:\n return num\n else:\n n = int(num)\n for i in range(len(num)):\n if n % 2 != 0:\n return str(n)\n else:\n n //= 10\n return ''", "def maxodd(s):\n s = s[::-1]\n j = 0\n for i in range(len(s)):\n if int(s[i]) % 2 != 0:\n j = i\n break\n if j == 0 and int(s[0]) % 2 == 0:\n return ''\n else:\n n = len(s) - j - 1\n s = s[::-1]\n f = s[:n + 1]\n return f", "def maxodd(s):\n n = len(s)\n for i in range(n - 1, -1, -1):\n if int(s[i]) % 2 == 1:\n return s[:i + 1]\n return ''", "def maxodd(S):\n for i in range(len(S) - 1, -1, -1):\n if int(S[i]) % 2:\n return S[:i + 1]\n return ''", "def maxodd(s):\n while 1:\n if int(s) % 2 == 1:\n return s\n else:\n s = s[:-1]\n if len(s) == 0:\n break\n return ''", "def maxodd(s):\n strlen = len(s) - 1\n while strlen >= 0:\n c = int(s[strlen])\n if c % 2 != 0:\n return s[0:strlen + 1]\n strlen -= 1\n return ''", "def maxodd(s):\n odd = -1\n for (i, el) in enumerate(s):\n if el != 0 and int(el) % 2 != 0:\n odd = i\n if odd == -1:\n return ''\n return s[:odd + 1]", "def maxodd(s):\n ptr1 = 0\n ptr2 = len(s)\n while ptr1 < ptr2:\n if int(s[ptr1:ptr2]) % 2 != 0:\n return s[ptr1:ptr2]\n else:\n ptr2 -= 1\n return ''", "def maxodd(s):\n p = -1\n for i in range(len(s) - 1, -1, -1):\n if int(s[i]) & 1:\n p = i\n break\n if p == -1:\n return ''\n return s[:p + 1]", "def maxodd(s):\n new = ''\n n = len(s)\n for i in range(n - 1, -1, -1):\n if len(new) != 0:\n new = s[i] + new\n if len(new) == 0:\n if s[i] == '1' or s[i] == '3' or s[i] == '5' or (s[i] == '7') or (s[i] == '9'):\n new = s[i] + new\n return new", "def maxodd(s):\n max = 0\n if int(s) % 2 != 0:\n return s\n s1 = ''\n for i in s:\n s1 = s1 + i\n j = int(s1)\n if j % 2 != 0:\n if j > max:\n max = j\n if j % 2 == 0:\n continue\n if max:\n max = str(max)\n return max\n else:\n return ''", "def maxodd(s):\n p = ''\n l = 0\n for i in range(0, len(s)):\n p += s[i]\n p = int(p)\n if p % 2 != 0:\n l = p\n p = str(p)\n if l > 0:\n return l\n k = ''\n return k", "def maxodd(s):\n if int(s) % 2 != 0:\n return s\n q = []\n for i in range(len(s)):\n m = s[:i + 1]\n if int(m) % 2 != 0:\n q.append(m)\n if not q:\n return ''\n return max([int(i) for i in q])", "def maxodd(s):\n mx = 0\n for i in range(len(s) - 1, -1, -1):\n a = int(s[i])\n if a % 2:\n return s[:i + 1]\n return ''", "def maxodd(s):\n for i in range(len(s) - 1, -1, -1):\n num = int(s[i])\n if num & 1 != 0:\n return s[0:i + 1]\n return ''", "def maxodd(s):\n ans = ''\n tmp = ''\n for i in s:\n tmp += i\n if int(tmp) % 2 != 0:\n ans = tmp\n return ans", "def maxodd(s):\n res = ''\n cur = ''\n for i in s:\n if int(i) % 2 != 0:\n cur += i\n res = max(res, cur)\n else:\n cur += i\n return res", "def maxodd(num):\n indx = -1\n n = len(num)\n for i in range(n):\n if int(num[i]) % 2 == 1:\n indx = i\n if indx == -1:\n return ''\n return num[:indx + 1]", "def maxodd(s):\n for i in range(len(s) - 1, -1, -1):\n if s[i] in '13579':\n return s[:i + 1]\n return ''", "def maxodd(s):\n maxi = 0\n sbs = ''\n for i in s:\n sbs += i\n if int(sbs) % 2 != 0:\n maxi = max(int(maxi), int(sbs))\n return '' if maxi == 0 else maxi", "def maxodd(s):\n num = int(s)\n st = ''\n for i in range(len(s)):\n remainder = num % 10\n if remainder % 2 != 0:\n st += str(num)\n return st\n num = num // 10\n return st", "def maxodd(s):\n n = int(s)\n if n % 2 != 0:\n return str(n)\n while n != 0:\n n = n // 10\n if n % 2 != 0:\n return str(n)\n else:\n return ''", "def maxodd(s):\n l = 0\n j = len(s) - 1\n while j != -1:\n if int(s[j]) % 2 != 0:\n break\n j -= 1\n return s[:j + 1]", "def maxodd(s):\n out = ''\n max_s = ''\n max = 0\n for i in s:\n out += i\n if max < int(out) and int(out) % 2 == 1:\n max = int(out)\n max_s = out\n return max_s", "def maxodd(s):\n (out, m) = ('', [])\n for e in s:\n out = out + e\n if int(out) % 2 != 0:\n m.append(int(out))\n if len(m) == 0:\n return ''\n return max(m)", "def maxodd(s):\n mo = ''\n st = -1\n en = -1\n for i in range(len(s)):\n if int(s[i]) % 2 != 0 and st == -1:\n st = i\n elif int(s[i]) % 2 != 0:\n en = i\n else:\n continue\n if en == -1:\n en = st\n return s[:en + 1]", "def maxodd(s):\n m = 0\n for i in range(len(s)):\n if int(s[:i + 1]) % 2 != 0 and int(s[:i + 1]) > m:\n m = int(s[:i + 1])\n return str(m) if m > 0 else ''", "def maxodd(s):\n c = -1\n for i in range(len(s) - 1, -1, -1):\n j = int(s[i])\n if j % 2 != 0:\n c = i\n break\n if c == -1:\n return ''\n else:\n return s[:c + 1]", "def maxodd(s):\n idx = 0\n result = 0\n for i in range(len(s) - 1, -1, -1):\n if int(s[i]) % 2 != 0:\n return s[:i + 1]\n return ''"], "starter_code": "def maxodd(s):\n", "input_output": {"inputs": ["s = \"504\"", "s = \"2042\""], "outputs": ["\"5\"", "\"\""]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/largest-odd-number-in-string/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|).", "entry_point": "maxodd", "task_id": "TACO_lite/75", "example": [[["504"], ["2042"]], ["5", ""]]} +{"requirement": "There are three piles of pens. A pens in the first pile and B pens in the second Pile.Find the minimum number of pens that should be there in the third pile so that sum of all three piles produces either a prime number or unity. \nNote: there should be atleast one pen in the third pile.\nExample 1:\nInput: A = 1, B = 3\nOutput: 1\nExplanation: A + B + K = prime\nK = 1, 1 + 3 + 1 = 5.So answer = 1\nbecuase 5 is minimum possible prime. \nExample 2:\nInput: A = 4, B = 3\nOutput: 4\nExplanation: A + B + K = prime\nK = 4, 4 + 3 + 4 = 11.So answer = 4\nbecuase 11 is minimum possible prime.\nYour Task: \nYou dont need to read input or print anything. Complete the function minThirdPiles() which takes A and B as input parameter and returns the the minimum number of pens that should be there in the third pile so that sum of all three piles produces a prime number.\nExpected Time Complexity: O(nlogn)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= A <=1000\n1 <= B <=1000", "solutions": ["def isPrime(n):\n prime = 0\n if n == 1:\n return 0\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n prime = 1\n break\n if prime:\n return 0\n else:\n return 1\n\ndef minthirdpiles(A, B):\n i = 1\n flag = True\n while flag:\n p = A + B + i\n if self.isPrime(p):\n flag = False\n else:\n i += 1\n return i", "def isPrime(num):\n i = 2\n while i * i <= num:\n if num % i == 0:\n return False\n break\n i += 1\n return True\n\ndef minthirdpiles(A, B):\n summ = A + B\n n = 0\n i = summ + 1\n while i < 1000000:\n if self.isPrime(i):\n n = i\n break\n i += 1\n return n - summ", "def minthirdpiles(A, B):\n\n def is_prime(x):\n if x == 1:\n return False\n for i in range(2, int(x ** 0.5) + 1):\n if x % i == 0:\n return False\n return True\n ans = None\n x = A + B\n for i in range(x + 1, x * x):\n if is_prime(i):\n return i - x", "import math\n\ndef minthirdpiles(A, B):\n\n def isprime(n):\n if n <= 1:\n return False\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n for x in range(1, 10000):\n if isprime(A + B + x):\n return x", "def minthirdpiles(A, B):\n if A == 0 and B == 0:\n return 1\n num = A + B + 1\n while not self.isPrime(num):\n num += 1\n return num - (A + B)\n\ndef isPrime(num):\n if num <= 1:\n return False\n if num == 2 or num == 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n i = 5\n while i * i <= num:\n if num % i == 0:\n return False\n i += 1\n return True", "def minthirdpiles(A, B):\n if A == 0 and B == 0:\n return 1\n k = A + B\n for i in range(1, k):\n s = k + i\n t = []\n for j in range(2, s):\n if s % j == 0:\n t.append(s)\n break\n if len(t) == 0:\n return i", "def minthirdpiles(A, B):\n\n def p(n):\n if n == 0 or n == 1:\n return False\n s = int(n ** 0.5)\n for i in range(2, s + 1):\n if n % i == 0:\n return False\n return True\n c = A + B\n d = 0\n while True:\n c += 1\n d += 1\n if p(c):\n return d", "def minthirdpiles(A, B):\n\n def is_prime(n):\n i = 2\n if n < 3:\n return False\n while i * i <= n:\n if n % i == 0:\n return False\n i += 1\n return True\n n = A + B\n temp = 0\n if is_prime(n):\n temp = 1\n while not is_prime(n + temp):\n temp += 1\n return temp", "def minthirdpiles(A, B):\n\n def isPrime(num):\n if num < 2:\n return 0\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return 0\n return 1\n sumval = A + B\n for i in range(1, 1000):\n if isPrime(i + sumval) == 1:\n return i", "def minthirdpiles(A, B):\n prime = [1 for _ in range(2500)]\n prime[0] = prime[1] = 0\n for i in range(2, 2500):\n if prime[i] == 1:\n for j in range(2 * i, 2500, i):\n prime[j] = 0\n for j in range(A + B + 1, 2500):\n if prime[j] == 1:\n return j - (A + B)", "from math import *\n\ndef isprime(x):\n if x <= 1:\n return 0\n for i in range(2, int(sqrt(x)) + 1):\n if x % i == 0:\n return 0\n return 1\n\ndef minthirdpiles(A, B):\n c = A + B\n if isprime(c):\n c = c + 1\n i = 1\n while not isprime(c):\n i = i + 1\n c = c + 1\n return i\n else:\n i = 0\n while not isprime(c + i):\n i = i + 1\n return i", "def is_prime(num):\n for j in range(2, int(num ** (1 / 2)) + 1):\n if num % j == 0:\n return 0\n return 1\n\ndef minthirdpiles(A, B):\n n = 1\n while True:\n pri = self.is_prime(A + B + n)\n if pri == 1:\n break\n n += 1\n if A == B:\n return min(A, n)\n return n", "def is_prime(num):\n t = num // 2 + 1\n while t > 2:\n if num % t == 0:\n return 0\n t -= 1\n return 1\n\ndef minthirdpiles(A, B):\n n = 1\n while True:\n pri = self.is_prime(A + B + n)\n if pri == 1:\n break\n n += 1\n if A == B:\n return min(A, n)\n return n", "import math as m\n\ndef minthirdpiles(A, B):\n\n def pr(x):\n if x < 2:\n return False\n for i in range(2, int(m.sqrt(x) + 1)):\n if x % i == 0:\n return False\n return True\n z = 1\n while True:\n if pr(A + B + z):\n return z\n z = z + 1", "def minthirdpiles(A, B):\n a = 0\n p = 0\n import math\n while p == 0:\n a = a + 1\n sum = A + B + a\n for i in range(2, int(math.sqrt(sum)) + 1):\n if sum % i == 0:\n p = 1\n if p == 0:\n return a\n p = 0", "from math import sqrt\n\ndef prime(n):\n if n <= 1:\n return 0\n for i in range(2, int(sqrt(n)) + 1):\n if n % i == 0:\n return 0\n else:\n return 1\n\ndef minthirdpiles(A, B):\n for i in range(1, A * B):\n if prime(A + B + i) == 1:\n return i", "def minthirdpiles(A, B):\n n = A + B\n while n > 0:\n for i in range(2, int(n ** 0.5) + 2):\n if (n + 1) % i == 0:\n n += 1\n break\n else:\n return n - (A + B) + 1", "def minthirdpiles(A, B):\n\n def check_prime(n):\n if n == 2:\n return True\n if n <= 1 or n % 2 == 0:\n return False\n else:\n for i in range(3, n):\n if n % i == 0:\n return False\n return True\n for i in range(1, 2000):\n if check_prime(i + A + B):\n return i"], "starter_code": "def minthirdpiles(A, B):\n", "input_output": {"inputs": ["A = 1, B = 3", "A = 4, B = 3"], "outputs": ["1", "4"]}, "difficulty": "EASY", "raw_tags": ["Prime Number"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/collection-of-pens1843/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(nlogn)", "entry_point": "minthirdpiles", "task_id": "TACO_lite/22", "example": [[[1, 3], [4, 3]], ["1", "4"]]} +{"requirement": "Given a string Str which may contains lowercase and uppercase chracters. The task is to remove all duplicate characters from the string and find the resultant string. The order of remaining characters in the output should be same as in the original string.\nExample 1:\nInput:\nStr = geeksforgeeks\nOutput: geksfor\nExplanation: After removing duplicate\ncharacters such as e, k, g, s, we have\nstring as \"geksfor\".\nExample 2:\nInput:\nStr = HappyNewYear\nOutput: HapyNewYr\nExplanation: After removing duplicate\ncharacters such as p, e, a, we have\nstring as \"HapyNewYr\".\nYour Task:\nComplete the function removeDuplicates() which takes a string str, as input parameters and returns a string denoting the answer. You don't to print answer or take inputs.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 \u2264 N \u2264 10^{5}\nString contains uppercase and lowercase english letters.", "solutions": ["def removeduplicates(str):\n asci = [0] * 256\n s = ''\n for i in range(len(str)):\n x = ord(str[i])\n asci[x] += 1\n for i in range(len(str)):\n x = ord(str[i])\n if asci[x] > 0:\n s += str[i]\n asci[x] = 0\n return s", "def removeduplicates(str):\n ans = ''\n li = [0] * 256\n for i in str:\n ind = ord(i) - ord('a')\n if li[ind] == 0:\n li[ind] = 1\n ans += i\n return ans", "def removeduplicates(str):\n lst = []\n for i in str:\n if i not in lst:\n lst.append(i)\n return ''.join(lst)", "def removeduplicates(str):\n (m, p) = ({}, '')\n for i in str:\n if i not in m:\n p += i\n m[i] = 1\n return p", "def removeduplicates(str):\n f = ''\n for i in str:\n if i not in f:\n f = f + i\n return f", "def removeduplicates(str):\n str1 = ''\n for i in range(len(str)):\n if str[i] not in str1:\n str1 = str1 + str[i]\n return str1", "def removeduplicates(str):\n from collections import defaultdict\n dic = defaultdict(int)\n ans = ''\n for i in str:\n if dic[i] == 0:\n ans += i\n dic[i] += 1\n return ans", "def removeduplicates(str):\n l = list(str)\n l1 = []\n for i in l:\n if i not in l1:\n l1.append(i)\n else:\n pass\n x = ''.join(l1)\n return x", "from collections import OrderedDict\n\ndef removeduplicates(str):\n a = []\n b = ''\n for i in str:\n a.append(i)\n a = list(OrderedDict.fromkeys(a))\n for i in a:\n b += i\n return b", "def removeduplicates(str):\n a = {}\n b = ''\n for i in str:\n if i not in a:\n b += i\n a[i] = 1\n return b", "def removeduplicates(str):\n ms = ''\n d = {}\n for i in str:\n if i not in d:\n ms += i\n d[i] = 1\n return ms", "def removeduplicates(str):\n arr = [char for char in str]\n b = list()\n for i in arr:\n if i not in b:\n b.append(i)\n return ''.join(b)", "def removeduplicates(str):\n p = ''\n for char in str:\n if char not in p:\n p = p + char\n return p", "def removeduplicates(str):\n freq = {}\n s = ''\n for i in range(len(str)):\n if str[i] not in freq:\n s += str[i]\n freq[str[i]] = i\n return s", "def removeduplicates(str):\n l = list(str)\n lst = []\n s = set()\n for i in l:\n if i not in s:\n s.add(i)\n lst.append(i)\n return ''.join(lst)", "def removeduplicates(s: str) -> str:\n seen = set()\n ans = []\n for c in s:\n if c not in seen:\n ans.append(c)\n seen.add(c)\n return ''.join(ans)", "def removeduplicates(str):\n unique = set()\n res = []\n for c in str:\n if c not in unique:\n res.append(c)\n unique.add(c)\n return ''.join(res)", "def removeduplicates(str: str) -> str:\n hash = [0] * 256\n ans = ''\n for c in str:\n if hash[ord(c)] == 0:\n ans += c\n hash[ord(c)] += 1\n return ans", "def removeduplicates(Str):\n unique_chars = set()\n output = ''\n for char in Str:\n if char not in unique_chars:\n unique_chars.add(char)\n output += char\n return output", "def removeduplicates(s):\n for i in range(len(s)):\n s[i].lower()\n d = {}\n for i in s:\n d[i] = 1\n t = ''\n for i in s:\n if d[i] == 1:\n t += i\n d[i] -= 1\n return t", "def removeduplicates(string):\n hash_set = set()\n result = ''\n for char in string:\n if char not in hash_set:\n result += char\n hash_set.add(char)\n return result", "def removeduplicates(str):\n letters = []\n output = ''\n for i in range(len(str)):\n if str[i] in letters:\n continue\n else:\n output += str[i]\n letters.append(str[i])\n return output", "def removeduplicates(s):\n result = ''\n for char in s:\n if char not in result:\n result += char\n return result", "def removeduplicates(str):\n res = ''\n for s in str:\n if s not in res:\n res = res + s\n return res", "def removeduplicates(str):\n seen = set()\n result = ''\n for char in str:\n if char not in seen:\n result += char\n seen.add(char)\n return result", "def removeduplicates(str):\n a = []\n s = ''\n for i in str:\n if i not in a:\n a.append(i)\n for i in a:\n s += i\n return s", "def removeduplicates(str):\n a = list(str)\n l = []\n l.append(a[0])\n for i in range(1, len(a)):\n if a[i] not in l:\n l.append(a[i])\n s = ''.join(l)\n return s", "def removeduplicates(st):\n d = {}\n s = ''\n for i in st:\n if i not in d:\n s += i\n d[i] = 1\n return s", "def removeduplicates(str):\n s = ''\n str = list(str)\n l = []\n for i in str:\n if i in l:\n continue\n else:\n l.append(i)\n for i in l:\n s += i\n return s", "def removeduplicates(str):\n s = ''\n length = len(str)\n for i in range(length):\n c = str[i]\n if c not in s:\n s += c\n return s", "def removeduplicates(str):\n result = []\n sample = ''\n for i in str:\n if i not in result:\n result.append(i)\n for i in result:\n sample += i\n return sample", "def removeduplicates(str):\n hsh = set()\n T = ''\n for ch in str:\n if ch in hsh:\n continue\n else:\n T += ch\n hsh.add(ch)\n return T", "def removeduplicates(str):\n d = {}\n res = ''\n for char in str:\n d[char] = d.get(char, 0) + 1\n if d[char] == 1:\n res += char\n return res", "def removeduplicates(str):\n l = list(str)\n dup = []\n s = ''\n for i in l:\n if i not in dup:\n dup.append(i)\n for j in dup:\n return s.join(dup)", "def removeduplicates(str):\n res = ''\n myDict = {}\n for i in str:\n if i not in myDict:\n res += i\n myDict[i] = 1\n return res", "def removeduplicates(str):\n s = list(str)\n look = {}\n p = ''\n for i in s:\n if i not in look:\n p += i\n look[i] = 1\n return p", "def removeduplicates(str):\n l = []\n for i in str:\n if i not in l:\n l.append(i)\n else:\n continue\n a = ''.join(l)\n return a", "def removeduplicates(str):\n l = []\n for i in str:\n if i in l:\n pass\n else:\n l.append(i)\n joint = ''.join(l)\n return joint", "def removeduplicates(str):\n look_up = {}\n result = ''\n for i in str:\n if i not in look_up.keys():\n result = result + i\n look_up[i] = 1\n return result"], "starter_code": "def removeduplicates(str):\n", "input_output": {"inputs": ["Str = geeksforgeeks", "Str = HappyNewYear"], "outputs": ["geksfor", "HapyNewYr"]}, "difficulty": "EASY", "raw_tags": ["Strings", "Arrays", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/remove-all-duplicates-from-a-given-string4321/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "removeduplicates", "task_id": "TACO_lite/40", "example": [[], []]} +{"requirement": "You just got done with your set at the gym, and you are wondering how much weight you could lift if you did a single repetition. Thankfully, a few scholars have devised formulas for this purpose (from [Wikipedia](https://en.wikipedia.org/wiki/One-repetition_maximum)) :\n\n\n### Epley\n\n\n### McGlothin\n\n\n### Lombardi\n\n\nYour function will receive a weight `w` and a number of repetitions `r` and must return your projected one repetition maximum. Since you are not sure which formula to use and you are feeling confident, your function will return the largest value from the three formulas shown above, rounded to the nearest integer. However, if the number of repetitions passed in is `1` (i.e., it is already a one rep max), your function must return `w`. Also, if the number of repetitions passed in is `0` (i.e., no repetitions were completed), your function must return `0`.", "solutions": ["def calculate_1rm(w, r):\n if r == 0:\n return 0\n if r == 1:\n return w\n return round(max([w * (1 + r / 30), 100 * w / (101.3 - 2.67123 * r), w * r ** 0.1]))", "epley = lambda w, r: w * (1 + r / 30)\nmcGlothin = lambda w, r: 100 * w / (101.3 - 2.67123 * r)\nlombardi = lambda w, r: w * r ** 0.1\n\ndef calculate_1rm(w, r):\n return r and (w if r == 1 else round(max(epley(w, r), mcGlothin(w, r), lombardi(w, r))))", "calculate_1rm = lambda w, r: [[round(max(w * (1 + r / 30), 100 * w / (101.3 - 2.67123 * r), w * r ** 0.1)), 0][r == 0], w][r == 1]", "ORM = [('Epley', lambda w, r: w * (1 + r / 30)), ('McGlothin', lambda w, r: 100 * w / (101.3 - 2.67123 * r)), ('Lombardi', lambda w, r: w * r ** 0.1)]\n\ndef calculate_1rm(w, r):\n if r == 0:\n return 0\n elif r == 1:\n return w\n else:\n return round(max((func(w, r) for (_, func) in ORM)))", "def calculate_1rm(w, r):\n if r in (0, 1):\n return (0, w)[r]\n epley = w * (1 + r / 30)\n mcg = 100 * w / (101.3 - 2.67123 * r)\n lomb = w * r ** 0.1\n return round(max((epley, mcg, lomb)))"], "starter_code": "def calculate_1rm(w, r):\n", "input_output": {"fn_name": "calculate_1RM", "inputs": [[135, 20], [200, 8], [270, 2], [360, 1], [400, 0]], "outputs": [[282], [253], [289], [360], [0]]}, "difficulty": "EASY", "raw_tags": ["Mathematics"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/595bbea8a930ac0b91000130", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "calculate_1rm", "task_id": "TACO_lite/50", "example": [[[100, 10], [200, 1], [150, 0]], [134, 200, 0]]} +{"requirement": "You are given an integer array nums that may contain duplicates. Your task is to return all possible subsets. Return only unique subsets and they can be in any order.\nExample: \nInput: \nnums = [1,2,2] \nOutput: \n[[],[1],[1,2],[1,2,2],[2],[2,2]]\nExplanation: \nWe can have subsets ranging from length 0 to 3. which are listed above. Also the subset [1,2] appears twice but is printed only once as we require only unique subsets.\nYour Task:\nComplete the function vector> printUniqueSubset(), which takes a vector nums and return a vector of vector consisting of all unique subsets.\nExpected Time Complexity: O(K2^{N}).\nExpected Auxiliary Space: O(K2^{N}).\nConstraints:\n1 <= nums.length <= 10\n-10 <= nums[i] <= 10", "solutions": ["def printuniquesubset(nums):\n n = len(nums)\n nums.sort()\n ans = []\n\n def solve(i, temp):\n ans.append(temp[:])\n for j in range(i, n):\n if j > i and nums[j] == nums[j - 1]:\n continue\n temp.append(nums[j])\n solve(j + 1, temp)\n temp.pop()\n solve(0, [])\n return ans", "def subset2(arr, n, ans, ind, subs):\n if ind == n:\n return\n subs.append(arr[ind])\n ans.append(subs[:])\n subset2(arr, n, ans, ind + 1, subs)\n subs.pop()\n for i in range(ind + 1, n):\n if arr[i] == arr[i - 1]:\n continue\n subs.append(arr[i])\n ans.append(subs[:])\n subset2(arr, n, ans, i + 1, subs)\n subs.pop()\n\ndef printuniquesubset(nums):\n nums.sort()\n n = len(nums)\n ans = []\n subs = []\n ans.append(subs)\n i = 0\n subset2(nums, n, ans, i, subs)\n return ans", "def solve(k, nums, curr):\n if k == len(nums):\n self.ans.add(tuple(curr))\n return\n self.solve(k + 1, nums, curr)\n curr.append(nums[k])\n self.solve(k + 1, nums, curr)\n curr.pop()\n\ndef printuniquesubset(nums):\n nums.sort()\n self.ans = set()\n curr = []\n self.solve(0, nums, curr)\n return sorted(list(self.ans))", "def subsets(arr, index, seq):\n if index == len(arr):\n self.res.append(seq)\n return\n copyindex = index\n while index < len(arr) - 1 and arr[index] == arr[index + 1]:\n index += 1\n self.subsets(arr, index + 1, seq)\n self.subsets(arr, copyindex + 1, seq + [arr[copyindex]])\n\ndef printuniquesubset(nums):\n nums.sort()\n self.res = []\n self.subsets(nums, 0, [])\n return sorted(self.res)", "def printuniquesubset(nums):\n\n def subdup(ind, nums, ans, s):\n ans.append(s[:])\n for i in range(ind, len(nums)):\n if i > ind and nums[i] == nums[i - 1]:\n continue\n s.append(nums[i])\n subdup(i + 1, nums, ans, s)\n s.pop()\n return\n ans = []\n s = []\n nums.sort()\n subdup(0, nums, ans, s)\n return ans", "def printuniquesubset(nums):\n ans = []\n ds = []\n\n def findSubsets(ind: int):\n ans.append(ds[:])\n for i in range(ind, len(nums)):\n if i != ind and nums[i] == nums[i - 1]:\n continue\n ds.append(nums[i])\n findSubsets(i + 1)\n ds.pop()\n nums.sort()\n findSubsets(0)\n return ans", "def printuniquesubset(nums):\n res = []\n nums.sort()\n\n def backtrack(i, subset):\n if i == len(nums):\n res.append(subset[:])\n return\n subset.append(nums[i])\n backtrack(i + 1, subset)\n subset.pop()\n while i + 1 < len(nums) and nums[i] == nums[i + 1]:\n i += 1\n backtrack(i + 1, subset)\n backtrack(0, [])\n res.sort()\n return res", "def gen(nums, n, arr, brr, pos):\n if pos == n:\n crr = brr.copy()\n arr.add(tuple(sorted(crr)))\n return\n brr.append(nums[pos])\n self.gen(nums, n, arr, brr, pos + 1)\n brr.pop()\n self.gen(nums, n, arr, brr, pos + 1)\n\ndef printuniquesubset(nums):\n arr = set()\n brr = []\n self.gen(nums, len(nums), arr, brr, 0)\n return sorted(list(arr))", "def printuniquesubset(nums):\n (lst, tmp) = ([], [])\n dic = {}\n\n def subs(idx, nums, n, tmp, lst):\n if idx >= n:\n if str(tmp) not in dic:\n dic[str(tmp)] = 1\n lst.append(tmp[:])\n return\n tmp.append(nums[idx])\n subs(idx + 1, nums, n, tmp, lst)\n tmp.pop()\n subs(idx + 1, nums, n, tmp, lst)\n nums.sort()\n subs(0, nums, len(nums), tmp, lst)\n return sorted(lst)", "def printuniquesubset(nums):\n ans = []\n m = len(nums)\n nums.sort()\n\n def recursion(idx, ds):\n ans.append(ds.copy())\n for i in range(idx, m):\n if i > idx and nums[i] == nums[i - 1]:\n continue\n ds.append(nums[i])\n recursion(i + 1, ds)\n ds.remove(nums[i])\n recursion(0, [])\n return ans", "def solve(i, nums, lst, ans):\n if i == n:\n ans.add(tuple(lst))\n return\n lst.append(nums[i])\n self.solve(i + 1, nums, lst, ans)\n lst.pop()\n self.solve(i + 1, nums, lst, ans)\n\ndef printuniquesubset(nums):\n nums.sort()\n ans = set()\n lst = []\n i = 0\n self.solve(i, nums, lst, ans)\n return sorted(ans)"], "starter_code": "def printuniquesubset(nums):\n", "input_output": {"inputs": ["nums = [1,2,2]"], "outputs": ["[[],[1],[1,2],[1,2,2],[2],[2,2]]"]}, "difficulty": "MEDIUM", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/subset-sum-ii/1", "Expected Auxiliary Space": "O(K2^{N}).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(K2^{N}).", "entry_point": "printuniquesubset", "task_id": "TACO_lite/38", "example": [[[[1, 2, 2]]], ["[[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]"]]} +{"requirement": "Given a number s(in string form). Find the Smallest number (Not leading Zeros) which can be obtained by rearranging the digits of given number.\n \nExample 1:\nInput: s = \"846903\"\nOutput: 304689\nExplanation: 304689 is the smallest number\nby rearranging the digits.\nExample 2:\nInput: s = \"55010\"\nOutput: 10055\nExplanation: 10055 is the smallest number \nby rearranging the digts.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function minimum_number() which takes the number as input parameter and returns the smallest number than can be formed without leading zeros by rearranging the digits of the number.\n \nExpected Time Complexity: O(N * log(N)) where N is the number of digits of the given number\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= N <= 10^{5}", "solutions": ["def minimum_number(s):\n l = list(s)\n l.sort()\n for i in range(len(l)):\n if int(l[i]) > 0:\n (l[0], l[i]) = (l[i], l[0])\n break\n n = ''\n for i in l:\n n += i\n return n", "def minimum_number(s):\n d = {}\n for i in s:\n i = int(i)\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n t = list(d.keys())\n t.sort()\n if len(t) == 1:\n return str(t[0]) * d[t[0]]\n res = str(t[1] * 10 + t[0])\n (d[t[0]], d[t[1]]) = (d[t[0]] - 1, d[t[1]] - 1)\n for i in t:\n res += str(i) * d[int(i)]\n return res", "def minimum_number(s):\n sort = sorted(s)\n s = ''\n i = 0\n while sort[i] == '0' and i < len(sort) - 1:\n i += 1\n if i == len(sort):\n for ele in sort:\n s += ele\n temp = sort[0]\n sort[0] = sort[i]\n sort[i] = temp\n for ele in sort:\n s += ele\n return s", "def minimum_number(s):\n arr = []\n new = []\n s = list(s)\n for i in s:\n if int(i) == 0:\n new.append(int(i))\n else:\n arr.append(int(i))\n if len(new) == len(s):\n return ''.join(s)\n arr.sort()\n new1 = [arr.pop(0)]\n new1.extend(new)\n new1.extend(arr)\n ans = ''\n for i in new1:\n ans += str(i)\n ans = int(ans)\n return ans", "def minimum_number(s):\n j = sorted(s)\n p = ''\n if j[0] != '0':\n return p.join(j)\n else:\n for i in range(len(j)):\n if j[i] != '0':\n temp = j[0]\n j[0] = j[i]\n j[i] = temp\n break\n return p.join(j)", "def minimum_number(s):\n m = sorted(s)\n for i in range(len(m)):\n if int(m[i]) > 0:\n (m[0], m[i]) = (m[i], m[0])\n break\n sr = ''\n for i in m:\n sr += i\n return sr", "def minimum_number(s):\n lst = list(s)\n lst.sort()\n tmp = ''\n for (i, n) in enumerate(lst):\n if n != '0':\n tmp = lst.pop(i)\n break\n return str(tmp) + ''.join(lst)", "def minimum_number(s):\n l = list(s)\n l.sort()\n tmp = ''\n for (i, ele) in enumerate(l):\n if ele != '0':\n tmp = str(l.pop(i))\n break\n return str(tmp) + ''.join(l)", "def minimum_number(s):\n n = len(s)\n lst = list(map(int, s))\n lst.sort()\n for i in range(n):\n if lst[i] != 0:\n (lst[0], lst[i]) = (lst[i], lst[0])\n break\n ans = ''\n for i in lst:\n ans += str(i)\n return ans", "import functools\n\ndef minimum_number(s):\n c = 0\n arr = []\n for i in s:\n if i != 0:\n arr.append(i)\n if i == '0':\n c += 1\n if c == len(s):\n return s\n\n def fuc(a, b):\n if a + b > b + a:\n return 1\n else:\n return -1\n arr.sort()\n news = str(int(''.join(arr)))\n if c == 0:\n return news\n else:\n return news[0] + '0' * c + news[1:]", "def minimum_number(s):\n num = sorted(s)\n t = 0\n for i in num:\n if i == '0':\n t += 1\n else:\n break\n num = num[t:]\n if len(num) > 0:\n x = num[0]\n else:\n return '0' * t\n num = ['0'] * t + num[1:]\n num.insert(0, x)\n return ''.join(num)", "def minimum_number(s):\n g = s.count('0')\n l = s.replace('0', '')\n if len(l) == 0:\n return s\n l = sorted(l)\n l.sort()\n h = [l[0]]\n for i in range(g):\n h.append('0')\n for i in range(1, len(l)):\n h.append(l[i])\n return ''.join(h)", "def minimum_number(s):\n x = [i for i in s]\n x.sort()\n c = 0\n for i in range(len(x)):\n if x[i] != '0':\n c = i\n break\n (x[0], x[c]) = (x[c], x[0])\n return ''.join(x)", "def minimum_number(s):\n snum = sorted(list(s))\n czero = snum.count('0')\n if czero == len(snum):\n return s\n snum[0] = snum[czero]\n snum[czero] = '0'\n return ''.join(snum)", "def minimum_number(s):\n lst = []\n for c in s:\n lst.append(c)\n lst.sort()\n n = len(lst)\n i = 0\n while i < n and lst[i] == '0':\n i += 1\n if i == n:\n return int(''.join(lst))\n else:\n (lst[0], lst[i]) = (lst[i], lst[0])\n return int(''.join(lst))", "def minimum_number(s):\n arr = list(s)\n arr.sort()\n for i in range(len(arr)):\n if arr[i] != '0':\n temp = arr[i]\n arr.pop(i)\n break\n if len(arr) == len(s):\n return s\n else:\n return temp + ''.join(arr)", "def minimum_number(s):\n res = [int(x) for x in str(s)]\n mo = ''\n res.sort()\n if res[len(res) - 2] == 0:\n res.sort(reverse=True)\n for s in res:\n mo = mo + str(s)\n return int(mo)\n if res[0] == 0:\n for i in range(len(res) - 1):\n if res[i] > 0:\n res[0] = res[i]\n res[i] = 0\n break\n for s in res:\n mo = mo + str(s)\n return int(mo)", "def minimum_number(s):\n s = list(s)\n s.sort()\n ind = 0\n leng = len(s)\n while ind < leng and s[ind] == '0':\n ind += 1\n if ind == leng:\n return int(''.join(s))\n p = s.pop(ind)\n s.insert(0, p)\n return int(''.join(s))", "def minimum_number(s):\n dic = {}\n for el in range(10):\n dic[str(el)] = 0\n if s[0] != '-':\n for el in s:\n dic[el] += 1\n newS = ''\n for el in range(1, 10):\n newS += str(el) * dic[str(el)]\n if dic['0'] != 0 and len(newS) > 0:\n newS = newS[0] + '0' * dic['0'] + newS[1:]\n elif dic['0'] != 0 and len(newS) == 0:\n newS += '0' * dic['0']\n return newS\n else:\n for el in s[1:]:\n dic[el] += 1\n newS = ''\n for el in range(9, -1, -1):\n newS += str(el) * dic[str(el)]\n newS = '-' + newS\n return newS", "def minimum_number(s):\n s = sorted(s)\n if s[-1] == '0':\n return ''.join(s)\n i = 0\n while s[i] == '0':\n i += 1\n (s[i], s[0]) = (s[0], s[i])\n return ''.join(s)", "def minimum_number(s):\n n = len(s)\n s = list(s)\n s = sorted(s)\n i = 0\n while i < n - 1 and s[i] == '0':\n i += 1\n if i == 0:\n return ''.join(s)\n else:\n (s[0], s[i]) = (s[i], s[0])\n return ''.join(s)", "def minimum_number(s):\n lst = list(s)\n num = sorted(lst)\n num = ''.join(num)\n num = list(num)\n for i in range(len(num)):\n if num[i] == '0':\n continue\n (num[i], num[0]) = (num[0], num[i])\n return ''.join(num)\n return ''.join(num)", "def minimum_number(n):\n arr = sorted([int(i) for i in list(str(n))])\n zcount = arr.count(0)\n if zcount == 0:\n return int(''.join(arr))\n elif zcount == len(arr):\n return 0\n else:\n s = str(arr[zcount])\n for _ in range(zcount):\n s += '0'\n for i in arr[zcount + 1:]:\n s += str(i)\n return int(s)", "import heapq\n\ndef minimum_number(s):\n s = list(s)\n s.sort()\n s.append('-1')\n i = 0\n while s[i] == '0':\n i += 1\n if i == len(s) - 1:\n return 0\n s.pop()\n (s[0], s[i]) = (s[i], s[0])\n return ''.join(s)", "def minimum_number(s):\n n = len(s)\n ls = list(s)\n ls.sort()\n i = 0\n while i < n and ls[i] == '0':\n i += 1\n if i < n:\n (ls[0], ls[i]) = (ls[i], ls[0])\n return ''.join(ls)"], "starter_code": "def minimum_number(s):\n", "input_output": {"inputs": ["s = \"846903\"", "s = \"55010\""], "outputs": ["304689", "10055"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/smallest-number-by-rearranging-digits-of-a-given-number0820/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N * log(N)) where N is the number of digits of the given number", "entry_point": "minimum_number", "task_id": "TACO_lite/0", "example": [[["846903"], ["55010"]], ["304689", "10055"]]} +{"requirement": "Geek wants to know the traversals required to construct a unique binary tree. Given a pair of traversal, return true if it is possible to construct unique binary tree from the given traversals otherwise return false.\nEach traversal is represented with an integer: preorder - 1, inorder - 2, postorder - 3. \nExample 1:\nInput:\na = 1, b=2\nOutput: 1\nExplanation: We can construct binary tree using inorder traversal and preorder traversal. \nExample 2:\nInput: a = 1, b=3\nOutput: 0 \nExplanation: We cannot construct binary tree using preorder traversal and postorder traversal. \nConstraints:\n1 <= a,b <=3\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function isPossible() which takes a and b as input parameters and returns true or false.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)", "solutions": ["def ispossible(a, b):\n return 1 if (a == 2 or b == 2) and (not (a == 2 and b == 2)) else 0", "def ispossible(a, b):\n if a == b:\n return False\n if a == 2 or b == 2:\n return True\n return False", "def ispossible(a, b):\n if a == 2:\n return b == 1 or b == 3\n elif b == 2:\n return True\n return False", "def ispossible(a, b):\n if (a == 1 or a == 3) and b == 2:\n return 1\n elif a == 2 and (b == 1 or b == 3):\n return 1\n return 0", "def ispossible(a, b):\n traversal = [a, b]\n if 2 in traversal and (1 in traversal or 3 in traversal):\n return True\n return False", "def ispossible(a, b):\n return True if (a + b) % 2 != 0 else False", "def ispossible(a, b):\n if a == 1 and b == 3:\n return False\n elif a == 3 and b == 1:\n return False\n elif a == b:\n return False\n else:\n return True", "def ispossible(a, b):\n if a == 1 and b == 3 or (a == 3 and b == 1) or a == b:\n return False\n return True", "def ispossible(a, b):\n if a != 2 and b != 2:\n return False\n elif a == b:\n return False\n return True", "def ispossible(a, b):\n if a != b:\n l = [a, b]\n if 2 in l:\n return True\n return False"], "starter_code": "def ispossible(a, b):\n", "input_output": {"inputs": ["a = 1, b=2", "a = 1, b=3"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Traversal"], "name": null, "source": "geeksforgeeks", "tags": ["Graph traversal"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/unique-binary-tree-requirements/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "ispossible", "task_id": "TACO_lite/60", "example": [[[1, 2], [1, 3]], ["1", "0"]]} +{"requirement": "Every Friday and Saturday night, farmer counts amount of sheep returned back to his farm (sheep returned on Friday stay and don't leave for a weekend).\n\nSheep return in groups each of the days -> you will be given two arrays with these numbers (one for Friday and one for Saturday night). Entries are always positive ints, higher than zero.\n\nFarmer knows the total amount of sheep, this is a third parameter. You need to return the amount of sheep lost (not returned to the farm) after final sheep counting on Saturday.\n\nExample 1: Input: {1, 2}, {3, 4}, 15 --> Output: 5\n\nExample 2: Input: {3, 1, 2}, {4, 5}, 21 --> Output: 6\n\nGood luck! :-)", "solutions": ["def lostsheep(friday, saturday, total):\n return total - sum(friday + saturday)", "def lostsheep(friday, saturday, total):\n fritag = 0\n for number in friday:\n fritag = fritag + number\n samstag = 0\n for number in saturday:\n samstag = samstag + number\n return int(str(total)) - (fritag + samstag)", "def lostsheep(friday, saturday, total):\n sheep = 0\n for num in friday:\n sheep += num\n for num in saturday:\n sheep += num\n return total - sheep", "def lostsheep(friday, saturday, total):\n sheeps = 0\n for i in range(len(friday)):\n sheeps += friday[i]\n for i in range(len(saturday)):\n sheeps += saturday[i]\n return total - sheeps", "def lostsheep(friday, saturday, total):\n weekend_total = sum(friday) + sum(saturday)\n difference = total - weekend_total\n return difference"], "starter_code": "def lostsheep(friday,saturday,total):\n", "input_output": {"fn_name": "lostSheep", "inputs": [[[1, 2], [3, 4], 15], [[3, 1, 2], [4, 5], 21], [[5, 1, 4], [5, 4], 29], [[11, 23, 3, 4, 15], [7, 14, 9, 21, 15], 300], [[2, 7, 13, 17], [23, 56, 44, 12, 1, 2, 1], 255], [[2, 5, 8], [11, 23, 3, 4, 15, 112, 12, 4], 355], [[1, 1, 1, 2, 1, 2], [2, 1, 2, 1, 2, 1], 30], [[5, 10, 15], [11, 23, 3, 4, 15], 89], [[3, 6, 9, 12], [3, 2, 1, 2, 3, 1], 44]], "outputs": [[5], [6], [10], [178], [77], [156], [13], [3], [2]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Fundamentals", "Algebra"], "name": null, "source": "codewars", "tags": ["Matrices", "Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/58e0f0bf92d04ccf0a000010", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "lostsheep", "task_id": "TACO_lite/68", "example": [[[1, 2, 15], [3, 1, 2, 4, 5, 21]], [null, null]]} +{"requirement": "Given a string S which only contains lowercase alphabets. Find the length of the longest substring of S such that the characters in it can be rearranged to form a palindrome. \nExample 1:\nInput:\nS = \"aabe\"\nOutput:\n3\nExplanation:\nThe substring \"aab\" can be rearranged to\n\"aba\" which is the longest palindrome\npossible for this String.\nExample 2:\nInput:\nS = \"adbabd\"\nOutput:\n6\nExplanation:\nThe whole string \u201cadbabd\u201d can be\nrearranged to form a palindromic substring.\nOne possible arrangement is \"abddba\".\nThus, output length of the string is 6. \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function longestSubstring() which takes a String S as input and returns the length of largest possible Palindrome.\nExpected Time Complexity: O(|S|*26)\nExpected Auxiliary Space: O(|S|*26)\nConstraints:\n1 \u2264 |S| \u2264 10^{5}", "solutions": ["def longestsubstring(s):\n ans = 1\n l = len(s)\n f = {0: -1}\n x = 0\n for i in range(l):\n z = ord(s[i]) - 97\n x = x ^ 1 << z\n if x in f:\n ans = max(ans, i - f[x])\n for j in range(26):\n t = x ^ 1 << j\n if t in f:\n ans = max(ans, i - f[t])\n if x not in f:\n f[x] = i\n return ans", "def longestsubstring(s):\n d = {}\n d[0] = -1\n x = ans = 0\n for i in range(len(s)):\n x = x ^ 1 << ord(s[i]) - ord('a')\n if x in d:\n ans = max(ans, i - d[x])\n else:\n d[x] = i\n for j in range(0, 26):\n m = x ^ 1 << j\n if m in d:\n ans = max(ans, i - d[m])\n return ans", "def longestsubstring(s):\n n = len(s)\n idx = {}\n ans = 0\n mask = 0\n idx[mask] = -1\n for i in range(n):\n temp = ord(s[i]) - 97\n mask ^= 1 << temp\n if mask in idx.keys():\n ans = max(ans, i - idx[mask])\n else:\n idx[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in idx.keys():\n if ans < i - idx[mask2]:\n ans = i - idx[mask2]\n return ans", "def longestsubstring(S):\n n = len(S)\n index = dict()\n answer = 0\n mask = 0\n index[mask] = -1\n for i in range(n):\n temp = ord(S[i]) - 97\n mask ^= 1 << temp\n if mask in index.keys():\n answer = max(answer, i - index[mask])\n else:\n index[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in index.keys():\n answer = max(answer, i - index[mask2])\n return answer", "def longestsubstring(s):\n ind = dict()\n ans = 0\n mask = 0\n ind[mask] = -1\n for i in range(len(s)):\n temp = ord(s[i]) - 97\n mask ^= 1 << temp\n if mask in ind:\n ans = max(ans, i - ind[mask])\n else:\n ind[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in ind:\n ans = max(ans, i - ind[mask2])\n return ans", "def longestsubstring(s):\n n = len(s)\n masks = {0: -1}\n\n def check(mask1, idx):\n res = 0\n if mask1 in masks:\n res = max(res, idx - masks[mask1])\n for i in range(26):\n mask2 = mask1 ^ 1 << i\n if mask2 in masks:\n res = max(res, idx - masks[mask2])\n return res\n (mask, ans) = (0, 0)\n for (i, c) in enumerate(s):\n mask ^= 1 << ord(c) - ord('a')\n ans = max(ans, check(mask, i))\n if mask not in masks:\n masks[mask] = i\n return ans", "def longestsubstring(S):\n length = 0\n mask = 0\n bitMap = {}\n bitMap[mask] = -1\n for i in range(len(S)):\n index = ord(S[i]) - 97\n mask = mask ^ 1 << index\n if mask in bitMap:\n length = max(length, i - bitMap[mask])\n else:\n bitMap[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in bitMap:\n length = max(length, i - bitMap[mask2])\n return length", "import collections\n\ndef longestsubstring(S):\n if not S:\n return\n ans = 1\n l = len(S)\n mp = {0: -1}\n x = 0\n for i in range(l):\n z = ord(S[i]) - ord('a')\n x = x ^ 1 << z\n if x in mp:\n ans = max(ans, i - mp[x])\n for j in range(26):\n t = x ^ 1 << j\n if t in mp:\n ans = max(ans, i - mp[t])\n if x not in mp:\n mp[x] = i\n return ans", "def is_palin(mapper, n):\n odd = 0\n for i in mapper.values():\n if i & 1:\n odd += 1\n if odd == 0:\n return True\n elif n & 1 and odd == 1:\n return True\n else:\n return False\n\ndef front(mapper, s, n):\n for i in range(n):\n mapper[s[i]] -= 1\n if self.is_palin(mapper, n - i - 1):\n return n - i - 1\n return 1\n\ndef ending(mapper, s, n):\n for i in range(n - 1, -1, -1):\n mapper[s[i]] -= 1\n if self.is_palin(mapper, i):\n return i\n return 1\n\ndef both_side(mapper, s, n):\n i = 0\n j = n - 1\n while i < j:\n mapper[s[i]] -= 1\n mapper[s[j]] -= 1\n n -= 2\n if self.is_palin(mapper, n):\n return n\n i += 1\n j -= 1\n return 1\n\ndef longestsubstring(s):\n n = len(s)\n mapper = dict()\n ans = 1\n l = len(s)\n f = {0: -1}\n x = 0\n for i in range(l):\n z = ord(s[i]) - 97\n x = x ^ 1 << z\n if x in f:\n ans = max(ans, i - f[x])\n for j in range(26):\n t = x ^ 1 << j\n if t in f:\n ans = max(ans, i - f[t])\n if x not in f:\n f[x] = i\n return ans\n maxi = -1000000000.0\n for i in range(n):\n mapper = dict()\n for j in range(i, n):\n mapper[s[j]] = 1 + mapper.get(s[j], 0)\n if self.is_palin(mapper, j - i + 1):\n maxi = max(maxi, j - i + 1)\n return maxi", "def longestsubstring(S):\n n = len(S)\n max_len = 0\n mp = {}\n mask = 0\n mp[mask] = -1\n for i in range(n):\n idx = ord(S[i]) - ord('a')\n mask = mask ^ 1 << idx\n if mask in mp:\n length = i - mp[mask]\n max_len = max(max_len, length)\n else:\n mp[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in mp:\n length = i - mp[mask2]\n max_len = max(max_len, length)\n return max_len", "def longestsubstring(S):\n dictt = {}\n dictt[0] = -1\n x = output = 0\n n = len(S)\n for i in range(n):\n x = x ^ 1 << ord(S[i]) - ord('a')\n if x in dictt:\n output = max(output, i - dictt[x])\n else:\n dictt[x] = i\n for j in range(0, 26):\n m = x ^ 1 << j\n if m in dictt:\n output = max(output, i - dictt[m])\n return output", "def longestsubstring(s):\n n = len(s)\n mp = dict()\n pr = 0\n sh = 0\n mp[sh] = -1\n for i in range(n):\n mrc = ord(s[i]) - 97\n sh ^= 1 << mrc\n if sh in mp.keys():\n pr = max(pr, i - mp[sh])\n else:\n mp[sh] = i\n for j in range(26):\n rs = sh ^ 1 << j\n if rs in mp.keys():\n pr = max(pr, i - mp[rs])\n return pr", "from itertools import permutations\n\ndef longestsubstring(S):\n ind = dict()\n ans = 0\n mas = 0\n ind[mas] = -1\n for i in range(len(S)):\n temp = ord(S[i]) - 97\n mas ^= 1 << temp\n if mas in ind.keys():\n ans = max(ans, i - ind[mas])\n else:\n ind[mas] = i\n for j in range(26):\n mask = mas ^ 1 << j\n if mask in ind.keys():\n ans = max(ans, i - ind[mask])\n return ans", "def longestsubstring(S):\n mask = 0\n mp = {}\n mp[0] = -1\n ans = 0\n for i in range(len(S)):\n o = ord(S[i]) - ord('a')\n mask ^= 1 << o\n if mask in mp:\n ans = max(ans, i - mp[mask])\n for j in range(26):\n nm = mask ^ 1 << j\n if nm in mp:\n ans = max(ans, i - mp[nm])\n if mask not in mp:\n mp[mask] = i\n return ans", "def longestsubstring(S):\n n = len(S)\n hash_map = {}\n mask = 0\n ans = 0\n hash_map[mask] = -1\n for i in range(n):\n tmp = ord(S[i]) - 97\n mask = mask ^ 1 << tmp\n if mask in hash_map.keys():\n ans = max(ans, i - hash_map[mask])\n else:\n hash_map[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in hash_map.keys():\n ans = max(ans, i - hash_map[mask2])\n return ans", "def longestsubstring(S):\n bit_mask = 0\n index_map = {}\n max_length = 0\n index_map[bit_mask] = -1\n for i in range(len(S)):\n c = ord(S[i]) - 97\n bit_mask ^= 1 << c\n if bit_mask in index_map:\n max_length = max(max_length, i - index_map[bit_mask])\n else:\n index_map[bit_mask] = i\n for j in range(26):\n bit_mask_2 = bit_mask ^ 1 << j\n if bit_mask_2 in index_map:\n max_length = max(max_length, i - index_map[bit_mask_2])\n return max_length", "def longestsubstring(S):\n index = dict()\n ans = 0\n m = 0\n index[m] = -1\n for i in range(len(S)):\n temp = ord(S[i]) - 97\n m = m ^ 1 << temp\n if m in index.keys():\n ans = max(ans, i - index[m])\n else:\n index[m] = i\n for j in range(26):\n mask2 = m ^ 1 << j\n if mask2 in index.keys():\n ans = max(ans, i - index[mask2])\n return ans", "def longestsubstring(S):\n n = len(S)\n m1 = 0\n m2 = 0\n ans = 0\n map = {0: -1}\n for i in range(n):\n idx = ord(S[i]) - ord('a')\n m1 = m1 ^ 1 << idx\n if m1 in map:\n ans = max(ans, i - map[m1])\n else:\n map[m1] = i\n for j in range(26):\n m2 = m1 ^ 1 << j\n if m2 in map:\n ans = max(ans, i - map[m2])\n return ans", "def longestsubstring(S):\n index = {0: -1}\n (mask, ans) = (0, 0)\n for i in range(len(S)):\n idx = ord(S[i]) - ord('a')\n mask ^= 1 << idx\n if mask in index:\n ans = max(ans, i - index[mask])\n else:\n index[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in index:\n ans = max(ans, i - index[mask2])\n return ans", "def longestsubstring(S):\n Dict = {0: -1}\n res = 0\n x = 0\n N = len(S)\n for i in range(N):\n num = ord(S[i]) - ord('a')\n x = x ^ 1 << num\n if x not in Dict:\n Dict[x] = i\n else:\n idx = Dict[x]\n res = max(res, i - Dict[x])\n for j in range(26):\n m = x ^ 1 << j\n if m in Dict:\n res = max(res, i - Dict[m])\n return res", "def longestsubstring(S):\n n = len(S)\n max_len = 0\n mask = 0\n pos_dict = {}\n pos_dict[0] = -1\n for i in range(n):\n bit_pos = ord(S[i]) - ord('a')\n mask = mask ^ 1 << bit_pos\n if mask in pos_dict:\n max_len = max(max_len, i - pos_dict[mask])\n else:\n pos_dict[mask] = i\n for j in range(26):\n mask2 = mask ^ 1 << j\n if mask2 in pos_dict:\n max_len = max(max_len, i - pos_dict[mask2])\n return max_len", "def longestsubstring(S):\n d = {}\n mask = 0\n d[mask] = -1\n res = 0\n for i in range(len(S)):\n ind = ord(S[i]) - 97\n mask ^= 1 << ind\n if mask in d:\n res = max(res, i - d[mask])\n else:\n d[mask] = i\n for j in range(26):\n newmask = mask ^ 1 << j\n if newmask in d:\n res = max(res, i - d[newmask])\n return res", "def longestsubstring(s):\n l = 0\n mask = 0\n mp = {}\n mp[mask] = -1\n for i in range(len(s)):\n ind = ord(s[i]) - 97\n mask ^= 1 << ind\n if mask in mp:\n l = max(l, i - mp[mask])\n else:\n mp[mask] = i\n for j in range(0, 26):\n mask2 = mask ^ 1 << j\n if mask2 in mp:\n l = max(l, i - mp[mask2])\n return l", "def longestsubstring(s):\n d = {}\n d[0] = -1\n flag = 0\n res = 0\n for i in range(len(s)):\n flag = flag ^ 1 << ord(s[i]) - ord('a')\n if flag in d:\n res = max(res, i - d[flag])\n else:\n d[flag] = i\n for j in range(26):\n mx = flag ^ 1 << j\n if mx in d:\n res = max(res, i - d[mx])\n return res", "def longestsubstring(S):\n ans = 0\n temp = 0\n has = dict()\n has[0] = -1\n for i in range(len(S)):\n t = ord(S[i]) - ord('a')\n temp ^= 1 << t\n if temp in has.keys():\n ans = max(ans, i - has[temp])\n else:\n has[temp] = i\n for j in range(26):\n temp2 = temp ^ 1 << j\n if temp2 in has.keys():\n ans = max(ans, i - has[temp2])\n return ans", "def longestsubstring(S):\n d = {}\n d[0] = -1\n x = ans = 0\n for i in range(len(S)):\n x = x ^ 1 << ord(S[i]) - ord('a')\n if x in d:\n ans = max(ans, i - d[x])\n else:\n d[x] = i\n for j in range(0, 26):\n m = x ^ 1 << j\n if m in d:\n ans = max(ans, i - d[m])\n return ans\n\ndef permute(xs, low=0):\n if low + 1 >= len(xs):\n yield xs\n else:\n for p in self.permute(xs, low + 1):\n yield p\n for i in range(low + 1, len(xs)):\n (xs[low], xs[i]) = (xs[i], xs[low])\n for p in self.permute(xs, low + 1):\n yield p\n (xs[low], xs[i]) = (xs[i], xs[low])\n\ndef isPalindrom(S):\n return S == S[::-1]", "def longestsubstring(s):\n d = {}\n (k, res) = (0, 0)\n d[0] = -1\n for i in range(len(s)):\n k = k ^ 1 << ord(s[i]) - 97\n if k in d:\n res = max(res, i - d[k])\n else:\n d[k] = i\n for j in range(26):\n temp = k ^ 1 << j\n if temp in d:\n res = max(res, i - d[temp])\n return res", "def longestsubstring(S):\n data = {}\n data[0] = -1\n (temp, res) = (0, 0)\n for i in range(len(S)):\n temp = temp ^ 1 << ord(S[i]) - ord('a')\n if temp in data:\n res = max(res, i - data[temp])\n else:\n data[temp] = i\n for j in range(26):\n k = temp ^ 1 << j\n if k in data:\n res = max(res, i - data[k])\n return res", "def longestsubstring(S):\n mask = 0\n d = {0: -1}\n ans = 0\n for (i, c) in enumerate(S):\n bit = ord(c) - ord('a')\n mask ^= 1 << bit\n if mask in d:\n ans = max(ans, i - d[mask])\n for j in range(26):\n if mask ^ 1 << j in d:\n ans = max(ans, i - d[mask ^ 1 << j])\n if mask not in d:\n d[mask] = i\n return ans", "def palindrome(S):\n dict_ = {}\n for i in S:\n if i in dict_:\n dict_[i] += 1\n else:\n dict_[i] = 1\n max = 0\n for i in dict_:\n if dict_[i] % 2 != 0:\n max += 1\n if max > 1:\n return False\n return True\n\ndef longestsubstring(s):\n d = {}\n d[0] = -1\n x = ans = 0\n for i in range(len(s)):\n x = x ^ 1 << ord(s[i]) - ord('a')\n if x in d:\n ans = max(ans, i - d[x])\n else:\n d[x] = i\n for j in range(0, 26):\n m = x ^ 1 << j\n if m in d:\n ans = max(ans, i - d[m])\n return ans"], "starter_code": "def longestsubstring(S):\n", "input_output": {"inputs": ["S = \"aabe\"", "S = \"adbabd\""], "outputs": ["3", "6"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Algorithms", "Strings", "Data Structures", "Dynamic Programming", "palindrome"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/longest-substring-whose-character-rearranged-can-form-a-palindrome/1", "Expected Auxiliary Space": "O(|S|*26)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|*26)", "entry_point": "longestsubstring", "task_id": "TACO_lite/83", "example": [[["aabe"], ["adbabd"]], ["3", "6"]]} +{"requirement": "Given an array A[]of size N. Let us call difference between indices of an element's first and last appearance in the array A[] a gap. Find the maximum possible gap. Note that if any element appears only once, then the gap for that element is 0.\n \nExample 1:\nInput:\nN = 9\nA[] = {2, 1, 3, 4, 2, 1, 5, 1, 7}\nOutput:\n6\nExplanation:\nFor the above test case (Assuming 0-based indexing): \nNumber 1's first appearance is at index 1 and last appearance is at index 7. This implies gap is 7-1=6\nThis is the maximum possible in the given test case.\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function leftIndex() which takes the array A[] and its size N as inputs and returns the Maximum Difference.\n \nExpected Time Complexity: O(N. Log(N))\nExpected Auxiliary Space: O(N)\n \nConstraints:\n1<=N<=10^{5}\n-10^{5}<=A_{i}<=10^{5}", "solutions": ["import math\n\ndef maxdiffindex(A, N):\n maxi = -math.inf\n dicti = {}\n for i in range(N):\n if A[i] not in dicti:\n dicti[A[i]] = i\n else:\n maxi = max(maxi, i - dicti[A[i]])\n if maxi == -math.inf:\n return 0\n return maxi", "def maxdiffindex(A, N):\n diff = 0\n dict_ = {}\n for index in range(N):\n elem = A[index]\n ind = dict_.get(elem, -1)\n if ind == -1:\n dict_.update({elem: index})\n else:\n current_diff = index - dict_[elem]\n diff = index - dict_[elem] if diff < current_diff else diff\n return diff", "def maxdiffindex(A, N):\n d = {}\n id = 0\n for i in range(N):\n if A[i] not in d:\n d[A[i]] = i\n elif i - d[A[i]] > id:\n id = i - d[A[i]]\n return id", "def maxdiffindex(A, N):\n B = list(reversed(A))\n maxi = 0\n visited = set()\n i = -1\n while i + maxi < N - 1:\n i += 1\n if A[i] in visited:\n continue\n visited.add(A[i])\n diff = N - 1 - i - B.index(A[i])\n if diff > maxi:\n maxi = diff\n return maxi", "def maxdiffindex(A, N):\n maxi = 0\n rev = A[::-1]\n for i in list(set(A)):\n fir = A.index(i)\n las = rev.index(i)\n las = len(A) - las - 1\n maxi = max(maxi, las - fir)\n return maxi", "def maxdiffindex(A, N):\n d1 = {}\n d2 = {}\n for i in range(len(A)):\n if A[i] not in d1:\n d1[A[i]] = i\n for i in reversed(range(len(A))):\n if A[i] not in d2:\n d2[A[i]] = i\n maximum = -987654321\n for (k, v) in d1.items():\n maximum = max(maximum, d2[k] - v)\n return maximum", "def maxdiffindex(A, N):\n result = []\n dict = {}\n for i in range(N):\n dict[A[i]] = i\n for j in range(N):\n value = abs(dict[A[j]] - j)\n result.append(value)\n return max(result)", "def maxdiffindex(A, N):\n maxi = 0\n temp = {}\n for i in range(N):\n if A[i] not in temp:\n temp[A[i]] = i\n else:\n maxi = max(maxi, i - temp[A[i]])\n return maxi", "from collections import defaultdict\n\ndef maxdiffindex(A, N):\n di = defaultdict(list)\n ans = []\n for i in range(N):\n di[A[i]].append(i)\n values = di.values()\n for i in values:\n if len(i) == 1:\n continue\n else:\n ans.append(i[-1] - i[0])\n if len(ans) != 0:\n return max(ans)\n else:\n return 0", "def maxdiffindex(A, N):\n m = {}\n for i in range(len(A)):\n m[A[i]] = i\n A = A[::-1]\n d = {}\n for j in range(len(A)):\n d[A[j]] = N - j - 1\n r = sorted(m.items())\n r = dict(r)\n e = sorted(d.items())\n e = dict(e)\n u = []\n v = []\n for (x, y) in r.items():\n u.append(y)\n for (x, y) in e.items():\n v.append(y)\n h = []\n for k in range(len(u)):\n h.append(abs(u[k] - v[k]))\n return max(h)", "def maxdiffindex(A, N):\n first = {}\n last = {}\n max_diff = -123456789\n for i in range(N):\n if A[i] not in first:\n first[A[i]] = i\n if A[i] not in last:\n last[A[i]] = i\n else:\n last[A[i]] = i\n for key in first:\n diff = last[key] - first[key]\n max_diff = max(max_diff, diff)\n return max_diff", "def maxdiffindex(A, N):\n d = {}\n for i in range(N):\n a = A[i]\n if a not in d:\n d[a] = [i]\n else:\n d[a].append(i)\n x = []\n for i in d:\n b = d[i]\n x.append(b[-1] - b[0])\n return max(x)", "def maxdiffindex(A, N):\n h = {}\n for i in range(N):\n if A[i] not in h:\n h[A[i]] = [i]\n else:\n h[A[i]] += [i]\n ans = []\n for i in h:\n if len(h[i]) == 1:\n ans.append(0)\n else:\n ans.append(h[i][-1] - h[i][0])\n return max(ans)", "def maxdiffindex(A, N):\n d = {}\n for i in range(N):\n if A[i] not in d:\n d[A[i]] = i\n ans = 0\n for i in range(N - 1, -1, -1):\n if A[i] in d:\n ans = max(ans, i - d[A[i]])\n return ans", "def maxdiffindex(A, N):\n d = {}\n mx = 0\n for i in range(N):\n if A[i] in d:\n mx = max(abs(d[A[i]] - i), mx)\n else:\n d[A[i]] = i\n return mx", "def maxdiffindex(arr, n):\n d = dict()\n res = 0\n for i in range(n):\n if arr[i] in d:\n res = max(res, i - d[arr[i]])\n else:\n d[arr[i]] = i\n return res", "def maxdiffindex(A, N):\n max_diff = 0\n d = {}\n for i in range(N):\n if A[i] not in d:\n d[A[i]] = i\n else:\n max_diff = max(max_diff, i - d[A[i]])\n return max_diff", "def maxdiffindex(A, N):\n d = {}\n f = {}\n for i in range(len(A)):\n if A[i] not in d:\n d[A[i]] = i\n else:\n continue\n for i in range(len(A) - 1, -1, -1):\n if A[i] not in f:\n f[A[i]] = i\n else:\n continue\n max_val = -9999\n for key in d.keys():\n if abs(d[key] - f[key]) > max_val:\n max_val = abs(d[key] - f[key])\n return max_val"], "starter_code": "def maxdiffindex(A, N):\n", "input_output": {"inputs": ["N = 9\nA[] = {2, 1, 3, 4, 2, 1, 5, 1, 7}"], "outputs": ["6"]}, "difficulty": "EASY", "raw_tags": ["Map", "Arrays", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/maximum-difference-10429/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N. Log(N))", "entry_point": "maxdiffindex", "task_id": "TACO_lite/46", "example": [[[9, [2, 1, 3, 4, 2, 1, 5, 1, 7]]], [null]]} +{"requirement": "Kontti language is a finnish word play game.\n\nYou add `-kontti` to the end of each word and then swap their characters until and including the first vowel (\"aeiouy\"); \n\nFor example the word `tame` becomes `kome-tantti`; `fruity` becomes `koity-fruntti` and so on.\n\nIf no vowel is present, the word stays the same.\n\nWrite a string method that turns a sentence into kontti language!", "solutions": ["import re\n\ndef kontti(s):\n return ' '.join([re.sub('([^aeiouy]*[aeiouy])(.*)', 'ko\\\\2-\\\\1ntti', w, flags=re.I) for w in s.split()])", "from re import sub\nfrom functools import partial\nkontti = partial(sub, '(?i)(\\\\S*?[aeiouy])(\\\\S*)', 'ko\\\\2-\\\\1ntti')", "import re\n\ndef kontti(s):\n return re.sub('(\\\\S*?[aeiouy])(\\\\S*)', 'ko\\\\2-\\\\1ntti', s, flags=re.I)", "def kontti(stg):\n return ' '.join((k_w(word) for word in stg.split()))\n\ndef k_w(stg):\n i = next((i for (i, c) in enumerate(stg.lower()) if c in 'aeiouy'), -1)\n return f'ko{stg[i + 1:]}-{stg[:i + 1]}ntti' if i > -1 else stg", "kontti = lambda w: ' '.join([(lambda pos: ''.join(['ko', s[pos + 1:], '-', s[:pos + 1], 'ntti']))([i for (i, l) in enumerate(s) if l.lower() in 'aeiouy'][0]) if any((l.lower() in 'aeiouy' for l in s)) else s for s in w.split(' ')]) if len(w) else ''", "kontti = lambda s: ' '.join(((lambda i: i < len(w) and 'ko' + w[i + 1:] + '-' + w[:i + 1] + 'ntti' or w)(min((i for (i, c) in enumerate(w + 'a') if c in 'aeiouyAEIOUY'))) for w in s.split()))", "def kontti(s):\n result = []\n for w in s.split():\n i = next((i for (i, c) in enumerate(w, 1) if c in 'aeiouyAEIOUY'), None)\n result.append(w if i is None else f'ko{w[i:]}-{w[:i]}ntti')\n return ' '.join(result)", "def kontti(st):\n r = []\n for s in st.split():\n (a, s) = ('', list(s))\n if not any((i in s for i in 'aeiouyAEIOUY')):\n r.append(''.join(s))\n else:\n while s:\n a += s.pop(0)\n if a[-1] in 'aeiouyAEIOUY':\n break\n r.append(f\"ko{''.join(s)}-{a}ntti\")\n return ' '.join(r)", "from re import search\n\ndef kontti(s):\n words = []\n for word in s.split():\n i = search('[aeiouyAEIOUY]', word)\n if i:\n i = i.start()\n words.append(f'ko{word[i + 1:]}-{word[:i + 1]}ntti')\n else:\n words.append(word)\n return ' '.join(words)"], "starter_code": "def kontti(s):\n", "input_output": {"fn_name": "kontti", "inputs": [["lamppu"], ["lamppu sofia"], ["silly game"], ["aeiou"], ["xyz lamppu"], [""], ["lAmppU"], ["silly grrr"]], "outputs": [["komppu-lantti"], ["komppu-lantti kofia-sontti"], ["kolly-sintti kome-gantti"], ["koeiou-antti"], ["koz-xyntti komppu-lantti"], [""], ["komppU-lAntti"], ["kolly-sintti grrr"]]}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/570e1271e5c9a0cf2f000d11", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "kontti", "task_id": "TACO_lite/55", "example": [[], []]} +{"requirement": "Given an array arr[] of size N, find the first digit from the left of the product of these N integers.\nExample 1:\nInput: N = 4, arr[] = {5, 8, 3, 7}\nOutput: 8\nExplanation: Produt is 840\nExample 2:\nInput: N = 3, arr[] = {6, 7, 9} \nOutput: 3\nExplanation: Produt is 378\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function firstDigit() which takes N and array arr[] as input parameters and returns the left digit of product.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 N, arr[i] \u2264 10^{5}\nTest cases have been designed such that there is no precision ambiguity.", "solutions": ["def firstdigit(arr, n):\n p = 1\n for i in range(n):\n p = p * arr[i]\n d = str(p)\n p = int(d[:6])\n return str(p)[0]", "def firstdigit(arr, n):\n val = 1\n for i in arr:\n val *= i\n st = str(val)\n val = int(st[:6])\n return str(val)[0]", "import math\n\ndef firstdigit(arr, n):\n s = 0.0\n for a in arr:\n s += math.log10(a)\n s = s - math.floor(s)\n return int(math.pow(10, s) + 1e-06)", "import math\n\ndef firstdigit(arr, n):\n res = 1\n for i in arr:\n res = res * i\n dig = int(math.log10(res))\n return res // 10 ** dig", "def firstdigit(arr, n):\n s = 1\n for i in range(n):\n s = s * arr[i]\n m = str(s)\n s = int(m[:6])\n return str(s)[0]", "import math\n\ndef firstdigit(arr, n):\n S = 0\n if n == 1:\n s = str(arr[0])\n return s[0]\n else:\n for i in arr:\n S = S + math.log10(i * 1.0)\n fract_S = S - math.floor(S)\n ans = math.pow(10, fract_S)\n return int(ans)", "import functools as f\n\ndef firstdigit(arr, n):\n p = 1\n for i in range(n):\n p = p * arr[i]\n d = str(p)\n p = int(d[:8])\n return str(p)[0]", "import math\n\ndef firstdigit(arr, n):\n product = 1\n for i in range(0, n):\n product = product * arr[i]\n digit = product // 10 ** int(math.log10(product))\n return digit", "import math\n\ndef firstdigit(arr, n):\n S = 0\n for i in range(n):\n S += math.log(arr[i], 10)\n S += 1e-06\n S -= math.floor(S)\n ans = int(pow(10, S))\n return ans", "import math\n\ndef firstdigit(arr, n):\n if n == 1:\n return str(arr[0])[0]\n s = 0\n for val in arr:\n s = s + math.log10(val * 1.0)\n frac = s - math.floor(s)\n return int(math.pow(10, frac))"], "starter_code": "def firstdigit(arr, n):\n", "input_output": {"inputs": ["N = 4, arr[] = {5, 8, 3, 7}", "N = 3, arr[] = {6, 7, 9}"], "outputs": ["8", "3"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/first-digit1751/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "firstdigit", "task_id": "TACO_lite/48", "example": [[[4, [5, 8, 3, 7]], [3, [6, 7, 9]]], [null, null]]} +{"requirement": "Given a dictionary of words and a pattern. Every character in the pattern is uniquely mapped to a character in the dictionary. Find all such words in the dictionary that match the given pattern. \nExample 1:\nInput:\nN = 4\ndict[] = {abb,abc,xyz,xyy}\npattern = foo\nOutput: abb xyy\nExplanation: xyy and abb have the same\ncharacter at index 1 and 2 like the\npattern.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function findMatchedWords() which takes an array of strings dict[] consisting of the words in the dictionary and a string, Pattern and returns an array of strings consisting of all the words in the dict[] that match the given Pattern in lexicographical order.\nExpected Time Complexity: O(N*K) (where K is the length of the pattern).\nExpected Auxiliary Space: O(N).\nConstraints:\n1 <= N <= 10", "solutions": ["def findspecificpattern(Dict, pattern):\n ans = []\n for i in Dict:\n dic = {}\n dic2 = {}\n if len(i) == len(pattern):\n flag = True\n for (j, k) in zip(i, pattern):\n if j not in dic and k not in dic2:\n dic[j] = k\n dic2[k] = j\n elif dic.get(j) != k or dic2.get(k) != j:\n flag = False\n if flag:\n ans.append(i)\n return ans", "def findspecificpattern(dict, pattern):\n lst = []\n for i in dict:\n if len(set(i)) == len(set(pattern)) == len(set(zip(i, pattern))) and len(i) == len(pattern):\n lst.append(i)\n return lst", "def findspecificpattern(Dict, pattern):\n d = {}\n for i in pattern:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n b = list(d.values())\n b.sort()\n a = []\n c = []\n for i in Dict:\n d2 = {}\n for j in i:\n if j in d2:\n d2[j] += 1\n else:\n d2[j] = 1\n x = list(d2.values())\n x.sort()\n a.append(x)\n c.append(i)\n d2.clear()\n d = []\n for i in range(len(a)):\n if b == a[i]:\n d.append(c[i])\n return d", "def findspecificpattern(Dict, pattern):\n a = []\n for i in Dict:\n if len(i) != len(pattern):\n continue\n d1 = {}\n d2 = {}\n for j in range(len(i)):\n if i[j] not in d1.keys() or pattern[j] not in d2.keys():\n d1[i[j]] = pattern[j]\n d2[pattern[j]] = i[j]\n elif d1[i[j]] != pattern[j] or d2[pattern[j]] != i[j]:\n break\n if len(d1) == len(d2):\n a.append(i)\n return a", "def encodeString(Str):\n map = {}\n res = ''\n i = 0\n for ch in Str:\n if ch not in map:\n map[ch] = i\n i += 1\n res += str(map[ch])\n return res\n\ndef findMatchedWords(dict, pattern):\n Len = len(pattern)\n hash = encodeString(pattern)\n res = []\n for word in dict:\n if len(word) == Len and encodeString(word) == hash:\n res.append(word)\n return res\n\ndef findspecificpattern(Dict, pattern):\n return findMatchedWords(Dict, pattern)", "def findspecificpattern(Dict, pattern):\n ans = []\n flag = False\n for stri in Dict:\n flag = False\n if len(stri) == len(pattern):\n for i in range(len(pattern) - 1):\n if stri[i] != stri[i + 1] and pattern[i] != pattern[i + 1] or (stri[i] == stri[i + 1] and pattern[i] == pattern[i + 1]):\n flag = True\n else:\n flag = False\n break\n if flag == True:\n dic = {}\n pic = {}\n for i in range(len(pattern)):\n if stri[i] not in dic:\n dic[stri[i]] = 1\n else:\n dic[stri[i]] += 1\n if pattern[i] not in pic:\n pic[pattern[i]] = 1\n else:\n pic[pattern[i]] += 1\n for i in range(len(pattern)):\n if dic[stri[i]] != pic[pattern[i]]:\n flag = False\n break\n if len(stri) == 1 and len(pattern) == 1:\n ans.append(stri)\n if flag == True:\n ans.append(stri)\n return ans", "def findspecificpattern(Dict, pattern):\n a = []\n for i in Dict:\n if len(set(i)) == len(set(pattern)) and len(i) == len(pattern):\n a.append(i)\n return a", "def hash_fn(word):\n k = 0\n mapper = {}\n res = ''\n for i in word:\n if i not in mapper:\n mapper[i] = k\n k += 1\n res += str(mapper[i])\n return res\n\ndef findspecificpattern(Dict, pattern):\n ptrn_hsh = hash_fn(pattern)\n l = len(pattern)\n res = []\n for i in Dict:\n if len(i) == l and hash_fn(i) == ptrn_hsh:\n res.append(i)\n return res", "def findspecificpattern(Dict, pattern):\n matched_words = []\n for word in Dict:\n if len(word) == len(pattern):\n matched = True\n pattern_dict = {}\n for i in range(len(word)):\n if word[i] not in pattern_dict:\n if pattern[i] in pattern_dict.values():\n matched = False\n break\n pattern_dict[word[i]] = pattern[i]\n elif pattern_dict[word[i]] != pattern[i]:\n matched = False\n break\n if matched:\n matched_words.append(word)\n matched_words.sort()\n return matched_words", "def findspecificpattern(Dict, pattern):\n pattern_list = []\n for item in Dict:\n if len(item) != len(pattern):\n pattern_list.append('')\n continue\n new_pattern = pattern\n char_dict = {}\n temp_str = ''\n for i in range(len(item)):\n if item[i] in char_dict:\n temp_str = temp_str + char_dict[item[i]]\n elif new_pattern != '':\n char_dict[item[i]] = new_pattern[0]\n new_pattern = new_pattern.replace(new_pattern[0], '')\n temp_str = temp_str + char_dict[item[i]]\n pattern_list.append(temp_str)\n final_pattern = []\n for i in range(len(pattern_list)):\n if pattern_list[i] == pattern:\n final_pattern.append(Dict[i])\n return final_pattern\n return final_pattern", "def findspecificpattern(Dict, pattern):\n d = {}\n for (i, char) in enumerate(pattern):\n if char in d:\n d[char].append(i)\n else:\n d[char] = [i]\n control = sorted(d.values())\n output = []\n for word in Dict:\n temp = {}\n for (i, char) in enumerate(word):\n if char in temp:\n temp[char].append(i)\n else:\n temp[char] = [i]\n if sorted(temp.values()) == control:\n output.append(word)\n return sorted(output)", "def findspecificpattern(Dict, pattern):\n dct = {}\n arr = [0] * len(pattern)\n j = 0\n ans = []\n for i in pattern:\n if i in dct:\n dct[i] += 1\n arr[j] = dct[i]\n else:\n arr[j] = 1\n dct[i] = 1\n j += 1\n for p in Dict:\n arr2 = [0] * len(p)\n j = 0\n dct = {}\n for i in p:\n if i in dct:\n dct[i] += 1\n arr2[j] = dct[i]\n else:\n arr2[j] = 1\n dct[i] = 1\n j += 1\n if arr == arr2:\n ans.append(p)\n return ans", "def findspecificpattern(Dict, pattern):\n res = []\n\n def helper(pattern, elem):\n d = {}\n n = len(pattern)\n if n != len(elem):\n return\n for i in range(n):\n if pattern[i] in d and elem[i] != d[pattern[i]]:\n break\n elif pattern[i] not in d and elem[i] in d.values():\n break\n else:\n d[pattern[i]] = elem[i]\n else:\n return elem\n for x in Dict:\n if helper(pattern, x):\n res.append(helper(pattern, x))\n return res", "def findspecificpattern(Dict, pattern):\n length = len(pattern)\n hash = encodeString(pattern)\n result = []\n for word in Dict:\n if len(word) == length and encodeString(word) == hash:\n result.append(word)\n return result\n\ndef encodeString(Str):\n map = {}\n res = ''\n i = 0\n for ch in Str:\n if ch not in map:\n map[ch] = i\n i += 1\n res += str(map[ch])\n return res", "def encodeString(string):\n map = {}\n res = ''\n i = 0\n for ch in string:\n if ch not in map:\n map[ch] = i\n i += 1\n res += str(map[ch])\n return res\n\ndef findspecificpattern(Dict, pattern):\n size = len(pattern)\n hash_map = encodeString(pattern)\n output = []\n for word in Dict:\n if len(word) == size and encodeString(word) == hash_map:\n output.append(word)\n return output", "def findspecificpattern(Dict, pattern):\n\n def encode(word):\n m = {}\n s = ''\n counter = 0\n for c in word:\n if c not in m:\n m[c] = counter\n counter += 1\n s += str(m[c])\n return s\n pattern_hash = encode(pattern)\n result = []\n for word in Dict:\n word_hash = encode(word)\n if pattern_hash == word_hash:\n result.append(word)\n return result", "def findspecificpattern(Dict, pattern):\n d = {}\n da = []\n p = 0\n s = set(pattern)\n for i in Dict:\n if len(set(i)) == len(s):\n da.append(i)\n for i in da:\n l1 = []\n l2 = []\n c = 0\n p += 1\n for j in i:\n if l1 == []:\n l1.append(j)\n c += 1\n elif l1[-1] == j:\n l1.append(j)\n c += 1\n elif l1[-1] != j:\n l1.append(j)\n l2.append(c)\n c = 1\n if l1[-1] == i[-1]:\n l2.append(c)\n l2.insert(0, p)\n l2.insert(1, i)\n else:\n l2.append(1)\n l2.insert(0, p)\n l2.insert(1, i)\n if i not in d:\n d[i] = [l2]\n else:\n d[i].append(l2)\n k = []\n l11 = []\n l22 = []\n c1 = 0\n for i in pattern:\n if l11 == []:\n l11.append(i)\n c1 += 1\n elif l11[-1] == i:\n l11.append(i)\n c1 += 1\n elif l11[-1] != i:\n l11.append(i)\n l22.append(c1)\n c1 = 1\n if l11[-1] == pattern[-1]:\n l22.append(c1)\n else:\n l22.append(1)\n k.append(l22)\n l3 = []\n l4 = []\n for i in d:\n if d[i][0][2:] == k[-1]:\n l3.append(d[i][0] * len(d[i]))\n l3.sort()\n for i in l3:\n l4 += [i[1]] * len(d[i[1]])\n return l4", "from collections import OrderedDict\n\ndef findspecificpattern(Dict, t):\n l = []\n n = len(t)\n for j in Dict:\n d = {}\n m = len(j)\n if m != n:\n continue\n flag = 1\n for i in range(m):\n if j[i] not in d and t[i] not in d.values():\n d[j[i]] = t[i]\n elif j[i] in d and d[j[i]] != t[i]:\n flag = 0\n elif j[i] not in d and t[i] in d.values():\n flag = 0\n if flag:\n l.append(j)\n return l", "from collections import OrderedDict\n\ndef findspecificpattern(Dict, pattern):\n l = []\n for i in Dict:\n if len(i) != len(pattern) and len(set(i)) != len(set(pattern)):\n continue\n else:\n temp = i\n for j in list(zip(list(OrderedDict.fromkeys(temp)), list(OrderedDict.fromkeys(pattern)))):\n temp = temp.replace(j[0], j[1])\n if temp == pattern:\n l.append(i)\n return l", "def findspecificpattern(Dict, pattern):\n lis = []\n for i in range(len(Dict)):\n word = Dict[i]\n if len(set(word)) == len(set(pattern)) and len(word) == len(pattern):\n l = {}\n check = 1\n for i in range(len(pattern)):\n if pattern[i] in l:\n if l[pattern[i]] != word[i]:\n check = 0\n break\n else:\n l[pattern[i]] = word[i]\n if check == 1:\n lis.append(word)\n return lis", "def findspecificpattern(Dict, pattern):\n pattern_mapp = {}\n pattern_str = ''\n for (idx, char) in enumerate(pattern):\n if char not in pattern_mapp:\n pattern_mapp[char] = str(idx)\n pattern_str += str(idx)\n else:\n pattern_str += pattern_mapp[char]\n hashes = []\n for i in range(len(Dict)):\n dict_map = {}\n hash = ''\n for (idx, char) in enumerate(Dict[i]):\n if char not in dict_map:\n dict_map[char] = str(idx)\n hash += str(idx)\n else:\n hash += dict_map[char]\n if hash == pattern_str:\n hashes.append(Dict[i])\n return hashes", "def Pattern(pattern):\n code = {}\n num = 1\n temp = ''\n for i in range(len(pattern)):\n if not code.get(pattern[i]):\n code[pattern[i]] = num\n num += 1\n else:\n num += 1\n code[pattern[i]] = num\n for i in pattern:\n temp += str(code[i])\n return temp\n\ndef findspecificpattern(Dict, pattern):\n checker = Pattern(pattern)\n li = []\n for i in Dict:\n temp = Pattern(i)\n if temp == checker:\n li.append(i)\n return li", "def get_hashmap(stra):\n hash_d = dict()\n for k in range(len(stra)):\n if hash_d.get(stra[k]):\n hash_d[stra[k]].append(k)\n else:\n hash_d[stra[k]] = [k]\n return set((tuple(i) for i in list(hash_d.values())))\n\ndef findspecificpattern(Dict, pattern):\n array_pat = []\n hash_vals = get_hashmap(pattern)\n for word in Dict:\n if get_hashmap(word) == hash_vals:\n array_pat.append(word)\n array_pat.sort()\n return array_pat", "from collections import Counter\n\ndef findspecificpattern(Dict, pattern):\n ans = []\n dicpat = Counter(pattern)\n dicpatv = list(dicpat.values())\n for i in range(0, len(Dict)):\n if len(Dict[i]) == len(pattern):\n dici = Counter(Dict[i])\n dicv = list(dici.values())\n if len(dicv) == len(dicpatv):\n for j in range(0, len(dicv)):\n if dicv[j] != dicpatv[j]:\n dici = {}\n diciv = []\n continue\n ans.append(Dict[i])\n dici = {}\n diciv = []\n return ans", "def findspecificpattern(Dict, pattern):\n\n def getPattern(pattern):\n patt_str = ''\n val_m = {}\n count = 1\n for val in pattern:\n if val in val_m:\n patt_str += str(val_m[val])\n else:\n patt_str += str(count)\n val_m[val] = count\n count += 1\n return patt_str\n result = []\n match = getPattern(pattern)\n for val in Dict:\n p = getPattern(val)\n if p == match:\n result.append(val)\n return result", "def findspecificpattern(Dict, pattern):\n Dict.append(pattern)\n res = []\n c = 0\n p = ''\n i = 0\n k = 0\n j = 0\n for i in Dict:\n while j < len(i):\n if j == len(i) - 1:\n p += str(c)\n j += 1\n c += 1\n break\n while i[j] == i[j + 1]:\n p += str(c)\n k = 1\n j += 1\n if j == len(i) - 1:\n break\n if j == len(i) - 1:\n p += str(c)\n j += 1\n break\n p += str(c)\n j += 1\n c += 1\n k = 0\n res.append(p)\n p = ''\n j = 0\n c = 0\n p1 = res[-1]\n res1 = []\n res.pop()\n for (i, j) in enumerate(res):\n if j == p1:\n res1.append(Dict[i])\n return res1", "def findspecificpattern(Dict, pattern):\n L = []\n n = 0\n e = ''\n x = ''\n pattern = pattern + '.'\n for i in pattern:\n if i == e:\n n += 1\n else:\n x = x + str(n)\n n = 1\n e = i\n for i in Dict:\n n = 0\n e = ''\n y = ''\n i = i + '.'\n for j in i:\n if j == e:\n n += 1\n else:\n y = y + str(n)\n n = 1\n e = j\n if y == x:\n L.append(i[:-1])\n return L", "def findspecificpattern(Dict, pattern):\n result = []\n for word in Dict:\n hash = {}\n flag = True\n if len(word) != len(pattern):\n continue\n for (i, c) in enumerate(pattern):\n if c not in hash:\n hash[c] = word[i]\n elif hash[c] != word[i]:\n flag = False\n if flag:\n result.append(word)\n return result", "def convert(p):\n m = {}\n r = ''\n for i in p:\n if i not in m:\n m[i] = 1\n else:\n m[i] += 1\n r = r + str(m[i])\n return r\n\ndef findspecificpattern(Dict, pattern):\n ans = []\n pat = convert(pattern)\n for i in Dict:\n if convert(i) == pat:\n ans.append(i)\n return ans", "def findspecificpattern(Dict, pattern):\n from collections import defaultdict, OrderedDict\n (dnew, dnew2) = (defaultdict(int), defaultdict(int))\n (dnew3, dnew4) = (OrderedDict(), OrderedDict())\n (L, res) = ([], [])\n for i in Dict:\n if len(set(i)) == len(set(pattern)):\n L.append(i)\n for i in range(len(pattern)):\n dnew[pattern[i]] += 1\n dnew3[pattern[i]] = dnew[pattern[i]]\n for k in L:\n for i in range(len(k)):\n dnew2[k[i]] += 1\n dnew4[k[i]] = dnew2[k[i]]\n if list(dnew4.values()) == list(dnew3.values()):\n res.append(k)\n dnew2 = defaultdict(int)\n dnew4 = OrderedDict()\n return res", "def findspecificpattern(dictt, pattern):\n res = []\n\n def patterniser(strg):\n d = dict()\n lst = []\n pointer = 1\n for i in strg:\n if i not in d:\n d[i] = pointer\n pointer += 1\n lst.append(d[i])\n return lst\n\n def checker(pat1, pat2):\n for i in range(len(pat1)):\n if pat1[i] != pat2[i]:\n return False\n return True\n pat1 = patterniser(pattern)\n for i in dictt:\n if len(i) == len(pattern):\n pat2 = patterniser(i)\n if checker(pat1, pat2):\n res.append(i)\n return res", "def findspecificpattern(Dict, pattern):\n a = {}\n aa = []\n for i in range(len(pattern)):\n try:\n if a[pattern[i]] == 0:\n pass\n except:\n a[pattern[i]] = 0\n aa.append(pattern[i])\n pp = ''\n p = {}\n ans = []\n for i in range(len(aa)):\n p[aa[i]] = i\n for i in range(len(pattern)):\n pp += str(p[pattern[i]])\n for j in range(len(Dict)):\n a = {}\n aa = []\n for i in range(len(Dict[j])):\n try:\n if a[Dict[j][i]] == 0:\n pass\n except:\n a[Dict[j][i]] = 0\n aa.append(Dict[j][i])\n ppp = ''\n po = {}\n for i in range(len(aa)):\n po[aa[i]] = i\n for i in range(len(Dict[j])):\n ppp += str(po[Dict[j][i]])\n if pp == ppp:\n ans.append(Dict[j])\n return ans", "def findspecificpattern(Dict, pattern):\n dic1 = {}\n count1 = []\n for i in pattern:\n if i not in dic1:\n dic1[i] = 1\n count1.append(dic1[i])\n else:\n dic1[i] += 1\n count1.append(dic1[i])\n dic2 = {}\n count2 = []\n output = []\n for x in Dict:\n for y in x:\n if y not in dic2:\n dic2[y] = 1\n count2.append(dic2[y])\n else:\n dic2[y] += 1\n count2.append(dic2[y])\n if count1 == count2:\n output.append(x)\n count2 = []\n dic2 = {}\n return output", "def ispattern(str1, pattern, n, p):\n if n != p:\n return False\n d = {}\n for i in range(n):\n if str1[i] in d:\n val = d[str1[i]]\n if val != pattern[i]:\n return False\n elif pattern[i] not in d.values():\n d[str1[i]] = pattern[i]\n else:\n return False\n return True\n\ndef findspecificpattern(Dict, pattern):\n ans = []\n p = len(pattern)\n for i in Dict:\n if ispattern(i, pattern, len(i), p):\n ans.append(i)\n return ans", "def findspecificpattern(Dict, pat):\n n = len(pat)\n c = 1\n l = []\n for i in range(n - 1):\n if pat[i] == pat[i + 1]:\n c += 1\n else:\n l.append(c)\n c = 1\n l.append(c)\n h = []\n for i in Dict:\n c = 1\n b = []\n n = len(i)\n for j in range(n - 1):\n if i[j] == i[j + 1]:\n c += 1\n else:\n b.append(c)\n c = 1\n b.append(c)\n if b == l:\n h.append(i)\n return h", "def hashmap(Strng):\n Dic = {}\n for i in Strng:\n if i not in Dic:\n Dic[i] = 1\n else:\n Dic[i] += 1\n return Dic\n\ndef findspecificpattern(Dict, pattern):\n kiss = []\n k = 0\n cont = 0\n ptr = {}\n for i in pattern:\n if i not in ptr:\n ptr[i] = 1\n else:\n ptr[i] += 1\n lptrn = len(ptr)\n while k < len(Dict):\n j = hashmap(Dict[k])\n ldic = len(j)\n if lptrn == ldic:\n if list(ptr.values()) == list(j.values()):\n kiss.append(Dict[k])\n k += 1\n return kiss", "def search(s, n):\n dp = [1] * n\n for i in range(1, n):\n if s[i - 1] == s[i]:\n dp[i] = dp[i - 1] + 1\n return dp\n\ndef findspecificpattern(Dict, pattern):\n p_dp = search(pattern, len(pattern))\n ans = []\n for i in Dict:\n if search(i, len(i)) == p_dp:\n ans.append(i)\n return ans", "def findspecificpattern(Dict, pattern):\n n = len(pattern)\n dp = [1] * n\n for i in range(1, n):\n if pattern[i - 1] == pattern[i]:\n dp[i] = dp[i - 1] + 1\n ans = []\n for i in Dict:\n p = [1] * len(i)\n for j in range(1, len(i)):\n if i[j - 1] == i[j]:\n p[j] = p[j - 1] + 1\n if dp == p:\n ans.append(i)\n return ans", "def findspecificpattern(Dict, pattern):\n ans = []\n for word in Dict:\n char1ToChar2 = {}\n char2ToChar1 = {}\n if len(word) == len(pattern):\n for (c1, c2) in zip(word, pattern):\n if c1 in char1ToChar2 and char1ToChar2[c1] != c2:\n break\n if c2 in char2ToChar1 and char2ToChar1[c2] != c1:\n break\n char1ToChar2[c1] = c2\n char2ToChar1[c2] = c1\n else:\n ans.append(word)\n return ans", "def findspecificpattern(Dict, pattern):\n ans = []\n for word in Dict:\n h = {}\n flag = 1\n if len(word) == len(pattern):\n for (i, j) in zip(pattern, word):\n if i not in h:\n h[i] = j\n elif h[i] != j:\n flag = 0\n break\n else:\n flag = 0\n if flag:\n ans.append(word)\n return ans", "def findspecificpattern(Dict, pattern):\n pattern_map = {}\n for i in range(len(pattern)):\n if pattern[i] not in pattern_map:\n pattern_map[pattern[i]] = 1\n else:\n pattern_map[pattern[i]] += 1\n pattern_string = ''\n values = sorted(pattern_map.values())\n for things in values:\n pattern_string += str(things)\n res = []\n for words in Dict:\n dict_map = {}\n for j in range(len(words)):\n if words[j] not in dict_map:\n dict_map[words[j]] = 1\n else:\n dict_map[words[j]] += 1\n dict_string = ''\n values2 = sorted(dict_map.values())\n for things2 in values2:\n dict_string += str(things2)\n if len(words) == len(pattern) and pattern_string == dict_string:\n res.append(words)\n return res", "def findspecificpattern(Dict, pattern):\n map_pattern = {}\n for i in range(len(pattern)):\n if pattern[i] not in map_pattern:\n map_pattern[pattern[i]] = 1\n else:\n map_pattern[pattern[i]] += 1\n pattern_string = ''\n values = sorted(map_pattern.values())\n for things in values:\n pattern_string += str(things)\n res = []\n for element in Dict:\n dict_map = {}\n for i in range(len(element)):\n if element[i] not in dict_map:\n dict_map[element[i]] = 1\n else:\n dict_map[element[i]] += 1\n dict_string = ''\n values1 = sorted(dict_map.values())\n for things2 in values1:\n dict_string += str(things2)\n if len(element) == len(pattern) and pattern_string == dict_string:\n res.append(element)\n return res", "def get_pattern(s):\n d = {}\n c = 0\n unique = []\n for i in range(len(s)):\n if s[i] not in unique:\n c += 1\n unique.append(s[i])\n d[c] = [i]\n else:\n d[c].append(i)\n return d\n\ndef findspecificpattern(Dict, pattern):\n golden = get_pattern(pattern)\n ans = []\n for i in Dict:\n temp = get_pattern(i)\n if temp == golden:\n ans.append(i)\n return ans", "def findspecificpattern(Dict, pattern):\n l = len(pattern)\n arr = [0] * l\n arr[0] = 1\n for i in range(1, l):\n if pattern[i] == pattern[i - 1]:\n arr[i] = 1 + arr[i - 1]\n else:\n arr[i] = 1\n lst = []\n for i in range(len(Dict)):\n if len(Dict[i]) == l:\n b = [0] * l\n b[0] = 1\n for j in range(1, l):\n if Dict[i][j] == Dict[i][j - 1]:\n b[j] = 1 + b[j - 1]\n else:\n b[j] = 1\n if b == arr:\n lst.append(Dict[i])\n lst.sort()\n return lst", "def check_isomorphic(str1, str2):\n if len(str1) != len(str2):\n return False\n map = {}\n for i in range(len(str1)):\n if str1[i] in map:\n if map[str1[i]] != str2[i]:\n return False\n elif str2[i] not in map.values():\n map[str1[i]] = str2[i]\n else:\n return False\n return True\n\ndef findspecificpattern(Dict, pattern):\n res = []\n N = len(Dict)\n for i in range(N):\n if check_isomorphic(Dict[i], pattern):\n res.append(Dict[i])\n return res", "from collections import Counter\n\ndef findspecificpattern(dic, pattern):\n n = len(pattern)\n mp = [0] * n\n mp[0] = 1\n for i in range(1, n):\n if pattern[i] == pattern[i - 1]:\n mp[i] = 1 + mp[i - 1]\n else:\n mp[i] = 1\n res = []\n for i in range(len(dic)):\n if len(dic[i]) == n:\n k = [0] * n\n k[0] = 1\n for j in range(1, n):\n if dic[i][j] == dic[i][j - 1]:\n k[j] = 1 + k[j - 1]\n else:\n k[j] = 1\n if k == mp:\n res.append(dic[i])\n res.sort()\n return res", "from collections import deque\n\ndef findspecificpattern(d, p):\n\n def check(p, w):\n if len(p) != len(w):\n return False\n ch = [0 for i in range(128)]\n for i in range(len(p)):\n if ch[ord(p[i])] == 0:\n ch[ord(p[i])] = w[i]\n elif ch[ord(p[i])] != w[i]:\n return False\n return True\n res = deque()\n for i in range(len(d)):\n if check(p, d[i]):\n res.append(d[i])\n return res", "def encode(word):\n hashMap = {}\n result = ''\n i = 1\n for ch in word:\n if ch not in hashMap:\n hashMap[ch] = i\n i = i + 1\n result += str(hashMap[ch])\n return result\n\ndef findspecificpattern(Dict, pattern):\n final = []\n for word in Dict:\n if len(word) == len(pattern) and encode(word) == encode(pattern):\n final.append(word)\n return final", "def findspecificpattern(Dict, pattern):\n count1 = 0\n count2 = 0\n for i in range(len(pattern) - 1):\n if pattern[i] != pattern[i + 1]:\n count1 += 1\n else:\n count2 += 1\n temp = []\n for i in Dict:\n count3 = 0\n count4 = 0\n for j in range(len(i) - 1):\n if i[j] != i[j + 1]:\n count3 += 1\n else:\n count4 += 1\n if count1 == count3 and count2 == count4:\n temp.append(i)\n return temp", "from collections import defaultdict\n\ndef findspecificpattern(Dict, pattern):\n res = []\n p = len(pattern)\n for s in Dict:\n if len(s) != p:\n continue\n d = defaultdict(str)\n flag = True\n for i in range(p):\n if s[i] not in d.keys() and pattern[i] not in d.values():\n d[s[i]] = pattern[i]\n elif d[s[i]] == pattern[i]:\n continue\n else:\n flag = False\n break\n if flag == True:\n res.append(s)\n return res", "def encode_helper(word):\n count = 0\n helper_map = {}\n s = ''\n for character in word:\n if character not in helper_map:\n helper_map[character] = count\n count += 1\n for character in word:\n s = s + str(helper_map[character])\n return s\n\ndef findspecificpattern(Dict, pattern):\n encoded_pattern = encode_helper(pattern)\n res = []\n for i in Dict:\n if encoded_pattern == encode_helper(i):\n res.append(i)\n return res", "def encode(word):\n count = 0\n dit = {}\n s = ''\n for i in word:\n if i not in dit:\n dit[i] = count\n count += 1\n for i in word:\n s = s + str(dit[i])\n return s\n\ndef findspecificpattern(Dict, pattern):\n l = []\n k = encode(pattern)\n for i in Dict:\n ans = encode(i)\n check = True\n if len(k) == len(ans):\n for j in range(len(k)):\n if k[j] != ans[j]:\n check = False\n break\n if check:\n l.append(i)\n return l", "def findspecificpattern(Dict, pattern):\n\n def makepattern(word):\n pr = -1\n d = {}\n res = []\n for c in word:\n if c in d:\n ind = d[c]\n else:\n d[c] = pr + 1\n pr += 1\n res.append(d[c])\n return res\n ans = []\n given_pattern = makepattern(pattern)\n for word in Dict:\n if given_pattern == makepattern(word):\n ans.append(word)\n return ans"], "starter_code": "def findspecificpattern(Dict, pattern):\n", "input_output": {"fn_name": "findSpecificPattern", "inputs": ["N = 4\ndict[] = {abb,abc,xyz,xyy}\npattern = foo"], "outputs": ["abb xyy"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Hash"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/match-specific-pattern/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*K) (where K is the length of the pattern).", "entry_point": "findspecificpattern", "task_id": "TACO_lite/18", "example": [[[4, ["abb", "abc", "xyz", "xyy"], "foo"]], [null]]} +{"requirement": "Given an array of numbers, return an array, with each member of input array rounded to a nearest number, divisible by 5.\n\nFor example:\n```\nroundToFive([34.5, 56.2, 11, 13]);\n```\nshould return\n```\n[35, 55, 10, 15]\n```\n\n```if:python\nRoundings have to be done like \"in real life\": `22.5 -> 25`\n```", "solutions": ["from decimal import Decimal, ROUND_HALF_UP\n\ndef round_to_five(numbers):\n return [(n / 5).quantize(1, ROUND_HALF_UP) * 5 for n in map(Decimal, numbers)]", "def round_to_five(numbers):\n return [5 * int(x / 5 + 0.5) for x in numbers]", "def round_to_five(numbers):\n return [int((n + 2.5) / 5) * 5 for n in numbers]", "round_to_five = lambda l: [round((0.01 + n) / 5) * 5 for n in l]", "def round_to_five(numbers):\n return [int((x // 5 + (x % 5 >= 2.5)) * 5) for x in numbers]", "def round_to_five(arr):\n return [5 * round(v / 5 + 0.01) for v in arr]", "import math\n\ndef round_to_five(numbers):\n output = []\n for n in numbers:\n if n % 5 == 0:\n output.append(int(n))\n elif n % 10 < 5 and n % 5 < 2.5 or (n % 10 > 5 and n % 5 >= 2.5):\n output.append(int(round(n, -1)))\n elif n % 10 < 5 and n % 5 >= 2.5:\n output.append(int(round(n, -1) + 5))\n else:\n output.append(int(round(n, -1) - 5))\n return output", "from math import floor, ceil\n\ndef rond(x):\n return floor(x) if x % 1 < 0.5 else ceil(x)\n\ndef round_to_five(numbers):\n return [rond(x / 5) * 5 for x in numbers]", "def rounding(n):\n intPart = int(n)\n fracPart = n - intPart\n if fracPart >= 0.5:\n n = intPart + 1\n else:\n n = intPart\n for i in range(6):\n up = n + i\n down = n - i\n if up % 5 == 0:\n return up\n elif down % 5 == 0:\n return down\n\ndef round_to_five(numbers):\n numbers = [rounding(n) for n in numbers]\n return numbers"], "starter_code": "def round_to_five(numbers):\n", "input_output": {"fn_name": "round_to_five", "inputs": [[[1, 5, 87, 45, 8, 8]], [[3, 56.2, 11, 13]], [[22.5, 544.9, 77.5]]], "outputs": [[[0, 5, 85, 45, 10, 10]], [[5, 55, 10, 15]], [[25, 545, 80]]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/582f52208278c6be55000067", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "round_to_five", "task_id": "TACO_lite/35", "example": [[[[34.5, 56.2, 11, 13]]], [[35.0, 55.0, 10.0, 15.0]]]} +{"requirement": "You're a statistics professor and the deadline for submitting your students' grades is tonight at midnight. Each student's grade is determined by their mean score across all of the tests they took this semester.\n\nYou've decided to automate grade calculation by writing a function `calculate_grade()` that takes a list of test scores as an argument and returns a one character string representing the student's grade calculated as follows:\n\n * 90% <= mean score <= 100%: `\"A\"`,\n * 80% <= mean score < 90%: `\"B\"`,\n * 70% <= mean score < 80%: `\"C\"`,\n * 60% <= mean score < 70%: `\"D\"`,\n * mean score < 60%: `\"F\"`\n\nFor example, `calculate_grade([92, 94, 99])` would return `\"A\"` since the mean score is `95`, and `calculate_grade([50, 60, 70, 80, 90])` would return `\"C\"` since the mean score is `70`.\n\nYour function should handle an input list of any length greater than zero.", "solutions": ["from bisect import bisect\nfrom statistics import mean\n\ndef calculate_grade(scores):\n return 'FDCBA'[bisect([60, 70, 80, 90], mean(scores))]", "def calculate_grade(scores):\n for score in scores:\n mean = sum(scores) / len(scores)\n if mean >= 90 and mean <= 100:\n return 'A'\n elif mean >= 80 and mean < 90:\n return 'B'\n elif mean >= 70 and mean < 80:\n return 'C'\n elif mean >= 60 and mean < 70:\n return 'D'\n else:\n return 'F'", "import statistics\n\ndef calculate_grade(scores):\n mean = statistics.mean(scores)\n if mean >= 90:\n return 'A'\n if mean >= 80:\n return 'B'\n if mean >= 70:\n return 'C'\n if mean >= 60:\n return 'D'\n return 'F'", "def calculate_grade(scores):\n s = sum(scores) / len(scores)\n return 'ABCDF'[(s < 90) + (s < 80) + (s < 70) + (s < 60)]", "def calculate_grade(scores):\n import numpy as np\n mean_score = np.mean(scores)\n if mean_score >= 90:\n return 'A'\n elif mean_score >= 80:\n return 'B'\n elif mean_score >= 70:\n return 'C'\n elif mean_score >= 60:\n return 'D'\n else:\n return 'F'", "def calculate_grade(scores):\n mean = sum(scores) / len(scores)\n return 'ABCDF'[(mean < 90) + (mean < 80) + (mean < 70) + (mean < 60)]", "def calculate_grade(scores):\n score = sum(scores) / len(scores) / 100\n grades = {0.6: 'D', 0.7: 'C', 0.8: 'B', 0.9: 'A'}\n return grades[round(score, 1)] if score > 0.6 else 'F'", "def calculate_grade(scores):\n avg_grade = sum(scores) / len(scores)\n if avg_grade < 60:\n return 'F'\n elif avg_grade < 70:\n return 'D'\n elif avg_grade < 80:\n return 'C'\n elif avg_grade < 90:\n return 'B'\n else:\n return 'A'"], "starter_code": "def calculate_grade(scores):\n", "input_output": {"fn_name": "calculate_grade", "inputs": [[[92, 94, 99]], [[50, 60, 70, 80, 90]], [[50, 55]]], "outputs": [["A"], ["C"], ["F"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/586e0dc9b98de0064b000247", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "calculate_grade", "task_id": "TACO_lite/13", "example": [[[[92, 94, 99]], [[50, 60, 70, 80, 90]]], ["A", "C"]]} +{"requirement": "Given a positive integer N, The task is to find if it is a power of eight or not.\nExample 1: \nInput: 64\nOutput: Yes\nExplanation: 64 is power of 8.\nExample 2:\nInput: 75\nOutput: No\nExplanation: 75 is not a power of 8.\nYour Task:\nYou don't need to read or print anything. your task is to complete the function is_power_of_eight() which takes N as the input parameter and returns \"Yes\" if N is power of eight otherwise returns \"No\"(Wihtout quotes).\nExpected Time Complexity: O(log(N))\nExpected Space Complexity: O(1)\nConstraints:\n1 <= N <= 10^{18}", "solutions": ["def is_power_of_eight(n):\n (oc, zc) = (0, 0)\n while n != 0:\n if n & 1 == 0:\n zc += 1\n else:\n oc += 1\n n = n >> 1\n if oc == 1 and zc % 3 == 0:\n return 'Yes'\n return 'No'", "def is_power_of_eight(n):\n ans = 1\n while ans <= n:\n if ans == n:\n return 'Yes'\n ans = ans * 8\n return 'No'", "def is_power_of_eight(n):\n if 8 | n == 8 and n >= 8:\n return 'Yes'\n elif n & n - 1 == 0:\n return 'Yes'\n else:\n return 'No'", "def is_power_of_eight(n):\n (set, pos, i) = (0, -1, 0)\n while n is not 0:\n if n & 1:\n pos = i\n set += n & 1\n n >>= 1\n i += 1\n if set > 1:\n return 'No'\n if pos % 3 == 0:\n return 'Yes'\n return 'No'", "def is_power_of_eight(n):\n for i in range(64):\n if pow(8, i) == n:\n return 'Yes'\n return 'No'", "def is_power_of_eight(n):\n while n:\n if n == 8:\n return 'Yes'\n if n % 8 != 0:\n return 'No'\n n = n // 8\n return 'No'", "import math\n\ndef is_power_of_eight(n):\n k = int(math.log(n, 8))\n if 8 ** k == n:\n return 'Yes'\n else:\n return 'No'", "def is_power_of_eight(n):\n import math\n x = math.log(n, 8)\n if 8 ** int(x) == n:\n return 'Yes'\n return 'No'", "import math\n\ndef is_power_of_eight(n):\n i = math.log(n) / math.log(8)\n if i - math.floor(i) < 1e-05:\n return 'Yes'\n else:\n return 'No'", "def is_power_of_eight(n):\n l = 1\n while l <= n:\n if l & n == n:\n return 'Yes'\n l <<= 3\n return 'No'", "def is_power_of_eight(n):\n if n & n - 1 or n == 0:\n return 'No'\n c = -1\n while n:\n n >>= 1\n c += 1\n if c % 3 == 0:\n return 'Yes'", "def is_power_of_eight(n):\n d = n\n if n == 1:\n return 'Yes'\n elif n % 8 != 0:\n return 'No'\n if n % 8 == 0:\n while d >= 1:\n d = d / 8\n if d == 1:\n return 'Yes'\n elif d % 8 != 0:\n return 'No'", "import math\n\ndef is_power_of_eight(n):\n k = int(math.log2(n))\n if 2 ** k == n and k % 3 == 0:\n return 'Yes'\n return 'No'", "from math import log2\n\ndef is_power_of_eight(n):\n p = log2(n) // 3\n return ['No', 'Yes'][pow(8, p) == n]", "def is_power_of_eight(n):\n import math\n c = round(math.log(n) / math.log(8))\n if n == pow(8, c):\n return 'Yes'\n else:\n return 'No'", "from math import *\n\ndef is_power_of_eight(n):\n a = log(n)\n b = log(8)\n res1 = round(a // b, 3)\n res2 = round(a / b, 3)\n return 'Yes' if res1 == res2 else 'No'", "def is_power_of_eight(n):\n for x in range(1, 200):\n if n == 8 ** x:\n return 'Yes'\n elif 8 ** x > n:\n return 'No'", "def is_power_of_eight(n):\n if n == 0:\n return 'No'\n if n & n - 1 == 0:\n return 'Yes'\n else:\n return 'No'", "def is_power_of_eight(n):\n return 'Yes' if n == 1 or (n % 8 == 0 and bin(n).count('1') == 1) else 'No'", "import math\n\ndef is_power_of_eight(n):\n d = math.log(n, 8)\n d = round(d, 5)\n if int(d) == d:\n return 'Yes'\n else:\n return 'No'", "import math\n\ndef is_power_of_eight(n):\n countOne = countZero = 0\n N = n\n while n:\n if n & 1:\n countOne += 1\n else:\n countZero += 1\n n = n >> 1\n result = self.checkMSBisOne(N) and countOne == 1 and (countZero % 3 == 0)\n return 'Yes' if result else 'No'\n\ndef checkMSBisOne(n):\n siz = self.getLength(n)\n return n >> siz - 1 & 1 == 1\n\ndef getLength(n):\n return int(math.log2(n)) + 1", "def is_power_of_eight(n):\n x = n\n if x and x & x - 1 == 0:\n while x > 0:\n x = x >> 3\n if x & 1:\n return 'Yes'\n return 'No'", "def is_power_of_eight(n):\n count = 0\n a = 0\n while n != 0:\n if n & 1 == 0:\n count += 1\n else:\n a += 1\n n = n >> 1\n if a == 1 and count % 3 == 0:\n return 'Yes'\n return 'No'", "def is_power_of_eight(n):\n b = bin(n)[2:]\n z = b.count('8')\n o = b.count('1')\n if z % 3 == 0 and o == 1:\n return 'Yes'\n return 'No'", "def is_power_of_eight(n):\n if n and (not n & n - 1) and (not n & 3067833782):\n return 'Yes'\n else:\n return 'No'", "def is_power_of_eight(n):\n a = 0\n b = 8 ** a\n while b < n:\n a = a + 1\n b = 8 ** a\n if b == n:\n return 'Yes'\n return 'No'", "def is_power_of_eight(n):\n a = 0\n b = 2 ** (3 * a)\n while b < n:\n a = a + 1\n b = 2 ** (3 * a)\n if b == n:\n return 'Yes'\n return 'No'", "import math\n\ndef is_power_of_eight(n):\n while n > 1:\n if n % 8 != 0:\n return 'No'\n n //= 8\n if n == 1:\n return 'Yes'"], "starter_code": "def is_power_of_eight(n):\n", "input_output": {"inputs": ["64", "75"], "outputs": ["Yes", "No"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/check-if-a-integer-is-power-of-8-or-not2537/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(N))", "entry_point": "is_power_of_eight", "task_id": "TACO_lite/70", "example": [[], []]} +{"requirement": "In a string composed of 'L', 'R', and 'X' characters, like \"RXXLRXRXL\", a move consists of either replacing one occurrence of \"XL\" with \"LX\", or replacing one occurrence of \"RX\" with \"XR\". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.\n\nExample:\n\n\nInput: start = \"RXXLRXRXL\", end = \"XRLXXRRLX\"\nOutput: True\nExplanation:\nWe can transform start to end following these steps:\nRXXLRXRXL ->\nXRXLRXRXL ->\nXRLXRXRXL ->\nXRLXXRRXL ->\nXRLXXRRLX\n\n\nNote:\n\n\n 1 <= len(start) = len(end) <= 10000.\n Both start and end will only consist of characters in {'L', 'R', 'X'}.", "solutions": ["def isToeplitzMatrix(matrix):\n if not matrix:\n return False\n colSize = len(matrix[0]) - 1\n for row in range(len(matrix) - 1):\n if matrix[row][:colSize] != matrix[row + 1][1:colSize + 1]:\n return False\n return True", "def isToeplitzMatrix(matrix):\n return all((True if len(matrix[i]) == 1 or matrix[i][:-1] == matrix[i + 1][1:] else False for i in range(len(matrix) - 1)))", "def isToeplitzMatrix(matrix):\n (x, y) = (len(matrix[0]), len(matrix))\n for i in range(x - 1):\n for j in range(y - 1):\n if matrix[j][i] != matrix[j + 1][i + 1]:\n return False\n return True", "def isToeplitzMatrix(matrix):\n for c in range(len(matrix) - 1):\n for r in range(len(matrix[0]) - 1):\n if matrix[c][r] != matrix[c + 1][r + 1]:\n return False\n return True", "def isToeplitzMatrix(matrix):\n (M, N) = (len(matrix), len(matrix[0]))\n if M == 1:\n return True\n prev_row = matrix[0][:-1]\n for row in matrix[1:]:\n if row[1:] != prev_row:\n return False\n prev_row = row[:-1]\n return True", "def isToeplitzMatrix(matrix):\n vmap = collections.defaultdict(set)\n (M, N) = (len(matrix), len(matrix[0]))\n for x in range(M):\n for y in range(N):\n vmap[y - x].add(matrix[x][y])\n if len(vmap[y - x]) > 1:\n return False\n return True", "def isToeplitzMatrix(matrix):\n hashMap = {}\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if hashMap.get(i - j, 'no') != 'no':\n if hashMap[i - j] != matrix[i][j]:\n return False\n else:\n hashMap[i - j] = matrix[i][j]\n return True", "def isToeplitzMatrix(matrix):\n rows = len(matrix)\n cols = len(matrix[0])\n for i in range(rows - 1):\n for j in range(cols - 1):\n if matrix[i][j] != matrix[i + 1][j + 1]:\n return False\n return True", "def isToeplitzMatrix(matrix):\n for i in range(0, len(matrix)):\n for j in range(0, len(matrix[0])):\n r = i + 1\n c = j + 1\n while r < len(matrix) and c < len(matrix[0]):\n if matrix[i][j] == matrix[r][c]:\n r += 1\n c += 1\n continue\n else:\n return False\n return True", "def isToeplitzMatrix1(matrix):\n (row, col) = (len(matrix), len(matrix[0]))\n for j in range(col):\n a = 0\n while a + 1 < row and j + a + 1 < col:\n if matrix[a][j + a] == matrix[a + 1][j + a + 1]:\n a += 1\n else:\n return False\n for i in range(row):\n a = 0\n while a + 1 < col and i + 1 + a < row:\n if matrix[i + a][a] == matrix[i + a + 1][a + 1]:\n a += 1\n else:\n return False\n return True\n\ndef isToeplitzMatrix(m):\n return all((m[i][j] == m[i + 1][j + 1] for i in range(len(m) - 1) for j in range(len(m[0]) - 1)))", "def isToeplitzMatrix(matrix):\n result = True\n for i in range(len(matrix) - 1):\n result = result and matrix[i][:-1] == matrix[i + 1][1:]\n return result"], "starter_code": "def cantransform(start: str, end: str) -> bool:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Two Pointers", "String"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Amortized analysis"], "skill_types": ["Amortized analysis"], "url": "https://leetcode.com/problems/swap-adjacent-in-lr-string/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "cantransform", "task_id": "TACO_lite/95", "example": [[["RXXLRXRXL", "XRLXXRRLX"]], ["True"]]} +{"requirement": "Given a square grid\u00a0of integers\u00a0arr, a falling path with non-zero shifts\u00a0is a choice of\u00a0exactly one element from each row of arr, such that no two elements chosen in adjacent rows are in\u00a0the same column.\nReturn the\u00a0minimum\u00a0sum of a falling path with non-zero shifts.\n\u00a0\nExample 1:\nInput: arr = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: 13\nExplanation: \nThe possible falling paths are:\n[1,5,9], [1,5,7], [1,6,7], [1,6,8],\n[2,4,8], [2,4,9], [2,6,7], [2,6,8],\n[3,4,8], [3,4,9], [3,5,7], [3,5,9]\nThe falling path with the smallest sum is\u00a0[1,5,7], so the answer is\u00a013.\n\n\u00a0\nConstraints:\n\n1 <= arr.length == arr[i].length <= 200\n-99 <= arr[i][j] <= 99", "solutions": ["def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [0] * len(arr[0])\n for (r, row) in enumerate(arr):\n minNb = min(dp)\n min1 = dp.index(minNb)\n dp[min1] = float('inf')\n min2 = dp.index(min(dp))\n dp[min1] = minNb\n for c in range(len(row)):\n if c != min1:\n row[c] += dp[min1]\n else:\n row[c] += dp[min2]\n dp = row[:]\n return min(dp)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n for i in range(1, len(arr)):\n r = heapq.nsmallest(2, arr[i - 1])\n for j in range(len(arr[0])):\n arr[i][j] += r[1] if arr[i - 1][j] == r[0] else r[0]\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n for i in range(1, (n := len(arr))):\n for j in range(n):\n t = min(arr[i - 1][0:j] + arr[i - 1][j + 1:n])\n arr[i][j] += t\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n for row in range(1, len(arr)):\n for col in range(0, len(arr)):\n if col == 0:\n arr[row][col] += min(arr[row - 1][1:])\n elif col == len(arr) - 1:\n arr[row][col] += min(arr[row - 1][:-1])\n else:\n arr[row][col] += min(arr[row - 1][:col] + arr[row - 1][col + 1:])\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = arr[0][:]\n for (i, costs) in enumerate(arr[1:], 1):\n prev = dp[:]\n for (j, cost) in enumerate(costs):\n dp[j] = cost + min(prev[:j] + prev[j + 1:])\n return min(dp)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n (nRow, nCol) = (len(arr), len(arr[0]))\n pathSum = arr.copy()\n for row in range(-2, -nCol - 1, -1):\n for col in range(nCol):\n pathSum[row][col] += min(pathSum[row + 1][0:col] + pathSum[row + 1][col + 1:])\n return min(pathSum[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr)\n dp = [[0 for x in range(m)] for x in range(m)]\n for i in range(m):\n for j in range(m):\n if i == 0:\n dp[i][j] = arr[i][j]\n else:\n temp = dp[i - 1].copy()\n temp.pop(j)\n dp[i][j] = arr[i][j] + min(temp)\n return min(dp[m - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr)\n n = len(arr[0])\n if m == 1:\n return arr[0][0]\n\n def get_min_neighbors(i, j):\n (a, row_prev[j]) = (row_prev[j], float('inf'))\n min_val = min(row_prev)\n row_prev[j] = a\n return min_val\n row_prev = arr[0]\n cur = [0] * n\n global_min = float('inf')\n for row in range(1, m):\n for col in range(n):\n cur[col] = get_min_neighbors(row, col) + arr[row][col]\n if row == m - 1 and cur[col] < global_min:\n global_min = cur[col]\n row_prev = cur[:]\n return global_min", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n for i in range(1, n):\n for j in range(n):\n prevmin = min(arr[i - 1])\n temp = arr[i - 1][:]\n temp.remove(prevmin)\n prevmin2 = min(temp)\n arr[i][j] += prevmin if prevmin != arr[i - 1][j] else prevmin2\n return min(arr[n - 1])", "def minfallingpathsum(dp: List[List[int]]) -> int:\n for i in range(1, len(dp)):\n for j in range(len(dp[i])):\n dp[i][j] = min(dp[i - 1][:j] + dp[i - 1][j + 1:]) + dp[i][j]\n return min(dp[-1])", "from heapq import nsmallest\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n for i in range(m - 1)[::-1]:\n for j in range(n):\n ans = nsmallest(2, arr[i + 1])\n arr[i][j] += ans[0] if ans[0] != arr[i + 1][j] else ans[1]\n return min(arr[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n A = arr\n n = len(A)\n dp = [[float('inf') for _ in range(n)] for _ in range(n)]\n for c in range(n):\n dp[0][c] = A[0][c]\n for r in range(1, n):\n for c in range(n):\n prev = heapq.nsmallest(2, dp[r - 1])\n dp[r][c] = A[r][c]\n dp[r][c] += prev[1] if dp[r - 1][c] == prev[0] else prev[0]\n return min(dp[n - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n if not arr:\n return 0\n length = len(arr)\n for i in range(1, length):\n for j in range(length):\n if j == 0:\n arr[i][j] += min(arr[i - 1][j + 1:])\n elif j == len(arr) - 1:\n arr[i][j] += min(arr[i - 1][:-1])\n else:\n arr[i][j] += min(arr[i - 1][:j] + arr[i - 1][j + 1:])\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n dp = [[0] * n for _ in range(m + 1)]\n for i in range(1, m + 1):\n for j in range(n):\n (m0, m1) = heapq.nsmallest(2, dp[i - 1])\n dp[i][j] = arr[i - 1][j] + (m0 if dp[i - 1][j] != m0 else m1)\n return min(dp[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n self.memo = {}\n if not arr:\n return 0\n possible_values = []\n for column in range(len(arr[0])):\n possible_values.append(self.visit_row(arr, 0, column))\n return min(possible_values)\n\ndef visit_row(arr, i, j):\n if (i, j) in self.memo:\n return self.memo[i, j]\n if i == len(arr) - 1:\n return arr[i][j]\n val = arr[i][j]\n possible_values = []\n prev_val = 999999999999999\n for k in [i[0] for i in sorted(enumerate(arr[i + 1]), key=lambda x: x[1])]:\n if k == j:\n continue\n next_val = self.visit_row(arr, i + 1, k)\n possible_values.append(next_val)\n if prev_val < next_val:\n break\n prev_val = next_val\n val += min(possible_values)\n self.memo[i, j] = val\n return val", "def minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n for i in range(1, m):\n min1 = 0\n min2 = 1\n for j in range(1, n):\n if arr[i - 1][j] < arr[i - 1][min1]:\n min2 = min1\n min1 = j\n elif arr[i - 1][j] < arr[i - 1][min2]:\n min2 = j\n for j in range(n):\n if j == min1:\n arr[i][j] += arr[i - 1][min2]\n else:\n arr[i][j] += arr[i - 1][min1]\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n\n def second_smallest(nums):\n (s1, s2) = (float('inf'), float('inf'))\n for num in nums:\n if num <= s1:\n (s1, s2) = (num, s1)\n elif num < s2:\n s2 = num\n return s2\n n = len(arr)\n for i in range(1, n):\n for j in range(n):\n prevmin = min(arr[i - 1])\n prevmin2 = second_smallest(arr[i - 1])\n arr[i][j] += prevmin if prevmin != arr[i - 1][j] else prevmin2\n return min(arr[n - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n if not arr:\n return 0\n (rows, cols) = (len(arr), len(arr[0]))\n for r in range(1, rows):\n for c in range(cols):\n val = float('inf')\n for x in range(cols):\n if arr[r - 1][x] < val and x != c:\n val = arr[r - 1][x]\n arr[r][c] += val\n return min(arr[-1])", "def minfallingpathsum(cost: List[List[int]]) -> int:\n cols = len(cost[0])\n dp = cost[0]\n for h in range(1, len(cost)):\n dp = [cost[h][m] + min((dp[prevMat] for prevMat in range(0, cols) if prevMat != m)) for m in range(0, cols)]\n return min(dp)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n pre = arr[0][:]\n for i in range(1, m):\n dp = []\n for j in range(n):\n dp += [arr[i][j] + min((pre[k] for k in range(n) if k != j))]\n pre = dp\n return min(dp)", "def minfallingpathsum(A):\n (m, n) = (len(A), len(A[0]))\n dp = A[0].copy()\n for x in range(1, m):\n tmp = [0] * n\n for y in range(n):\n tmp[y] = min((dp[py] for py in range(n) if y != py)) + A[x][y]\n (dp, tmp) = (tmp, dp)\n return min(dp)", "import numpy as np\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n dp = arr[0]\n for r in range(1, len(arr)):\n new_dp = [i for i in dp]\n for c in range(len(arr)):\n lst = [dp[j] for j in range(len(arr)) if j != c]\n new_dp[c] = min(lst) + arr[r][c]\n dp = new_dp\n return int(min(dp))", "def minfallingpathsum(arr: List[List[int]]) -> int:\n while len(arr) > 1:\n bottom = arr.pop()\n for i in range(len(arr[-1])):\n arr[-1][i] += min((el for (j, el) in enumerate(bottom) if i != j))\n return min(arr[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n cumSum = [[0 for j in range(len(arr[0]) + 1)] for i in range(len(arr) + 1)]\n for i in range(len(arr)):\n for j in range(len(arr[0])):\n cumSum[i + 1][j + 1] = arr[i][j] + cumSum[i + 1][j] + cumSum[i][j + 1] - cumSum[i][j]\n dp = [arr[i] for i in range(len(arr))]\n for i in range(1, len(dp)):\n for j in range(len(dp[0])):\n (i1, j1) = (i + 1, j + 1)\n aboveDP = min([x for (c, x) in enumerate(dp[i - 1]) if c != j])\n dp[i][j] = cumSum[i1][j1] - cumSum[i][j1] - cumSum[i1][j] + cumSum[i][j] + aboveDP\n return min(dp[-1])", "def minfallingpathsum(cost: List[List[int]]) -> int:\n numHouses = len(cost)\n cols = len(cost[0])\n dp = cost[0]\n for h in range(1, numHouses):\n newRow = [0 for _ in range(cols)]\n for m in range(0, cols):\n prevCost = min((dp[prevMat] for prevMat in range(0, cols) if prevMat != m))\n newRow[m] = cost[h][m] + prevCost\n dp = newRow\n return min(dp)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n cumSum = [[0 for j in range(len(arr[0]) + 1)] for i in range(len(arr) + 1)]\n for i in range(len(arr)):\n for j in range(len(arr[0])):\n cumSum[i + 1][j + 1] = arr[i][j] + cumSum[i + 1][j] + cumSum[i][j + 1] - cumSum[i][j]\n dp = [arr[i] for i in range(len(arr))]\n for i in range(1, len(dp)):\n for j in range(len(dp[0])):\n (csR, csC) = (i + 1, j + 1)\n (leftR, leftC) = (i, j + 1)\n (topR, topC) = (i + 1, j)\n (addR, addC) = (i, j)\n aboveDP = min([x for (c, x) in enumerate(dp[i - 1]) if c != j])\n dp[i][j] = cumSum[csR][csC] - cumSum[leftR][leftC] - cumSum[topR][topC] + cumSum[addR][addC] + aboveDP\n return min(dp[-1])", "import heapq\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n while len(arr) > 1:\n row = arr.pop()\n heap = []\n for i in range(len(row)):\n if not heap:\n heap = [row[x] for x in range(len(row)) if x != i]\n heapq.heapify(heap)\n else:\n if heap[0] == row[i]:\n heapq.heappop(heap)\n heapq.heappush(heap, row[i - 1])\n arr[-1][i] += heap[0]\n return min(arr[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n for i in range(len(arr) - 2, -1, -1):\n a = sorted(([arr[i + 1][j], j] for j in range(len(arr[0]))))\n for j in range(len(arr[0])):\n for (v, idx) in a:\n if idx != j:\n arr[i][j] += v\n break\n return min(arr[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp_mtx = [[0] * len(arr[0]) for _ in range(len(arr))]\n for i in range(len(arr)):\n for j in range(len(arr[0])):\n if i == 0:\n dp_mtx[i][j] = arr[i][j]\n else:\n dp_mtx[i][j] = arr[i][j] + min((dp_mtx[i - 1][k] for k in range(len(arr[0])) if k != j))\n return min(dp_mtx[len(arr) - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n for i in range(1, n):\n for j in range(n):\n prevNonAdj = [arr[i - 1][k] for k in range(n) if k != j]\n arr[i][j] += min(prevNonAdj)\n return min(arr[n - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [[float('inf')] + i + [float('inf')] for i in arr]\n for i in range(1, len(dp)):\n for j in range(1, len(dp[0]) - 1):\n dp[i][j] = dp[i][j] + min([dp[i - 1][k] for k in range(len(dp[i - 1])) if k != j])\n return min(dp[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n dp1 = [None for i in range(n)]\n for i in range(0, n):\n dp1[i] = arr[0][i]\n for i in range(1, n):\n dp2 = [None for i in range(n)]\n for j in range(0, n):\n minList = []\n for k in range(0, n):\n if k == j:\n continue\n minList.append(dp1[k])\n dp2[j] = min(minList) + arr[i][j]\n dp1 = dp2\n return min(dp2)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n dp = [[float('inf')] * n for _ in range(m)]\n for i in range(m):\n for j in range(n):\n if i == 0:\n dp[0][j] = arr[0][j]\n else:\n dp[i][j] = arr[i][j] + min((dp[i - 1][x] for x in range(n) if x != j))\n return min(dp[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n if not arr:\n return 0\n (m, n) = (len(arr), len(arr[0]))\n for i in range(1, m):\n for j in range(n):\n arr[i][j] = min([arr[i - 1][col] for col in range(n) if col != j]) + arr[i][j]\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n R = len(arr)\n C = len(arr[0])\n dp = [[float('inf') for j in range(C)] for i in range(R)]\n for i in range(C):\n dp[0][i] = arr[0][i]\n for r in range(1, R):\n for c in range(C):\n dp[r][c] = arr[r][c] + min((dp[r - 1][k] if k != c else float('inf') for k in range(C)))\n return min(dp[R - 1])", "def minfallingpathsum(A: List[List[int]]) -> int:\n for i in range(len(A) - 1):\n x = [0 for _ in A]\n for j in range(len(A)):\n ls = []\n for k in range(len(A)):\n if not j == k:\n ls.append(A[0][k])\n x[j] = A[i + 1][j] + min(ls)\n A[0] = x\n return min(A[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n memo = {}\n return self.helper(0, None, arr, memo)\n\ndef helper(index, notAllowed, arr, memo):\n if index == len(arr):\n return 0\n elif (index, notAllowed) in memo:\n return memo[index, notAllowed]\n else:\n (maxOne, maxTwo) = self.getMaxTwo(notAllowed, arr[index])\n useOne = arr[index][maxOne] + self.helper(index + 1, maxOne, arr, memo)\n useTwo = arr[index][maxTwo] + self.helper(index + 1, maxTwo, arr, memo)\n res = min(useOne, useTwo)\n memo[index, notAllowed] = res\n return res\n\ndef getMaxTwo(blocked, arr):\n minOne = None\n minIndex = None\n for i in range(len(arr)):\n if i == blocked:\n continue\n else:\n curr_num = arr[i]\n if minOne == None or curr_num < minOne:\n minOne = curr_num\n minIndex = i\n minTwo = None\n minIndexTwo = None\n for j in range(len(arr)):\n if j == blocked or j == minIndex:\n continue\n else:\n curr_num = arr[j]\n if minTwo == None or curr_num < minTwo:\n minTwo = curr_num\n minIndexTwo = j\n return (minIndex, minIndexTwo)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n for i in range(1, len(arr)):\n for j in range(len(arr[0])):\n above = set()\n for k in range(len(arr[0])):\n if k != j:\n above.add(arr[i - 1][k])\n arr[i][j] = arr[i][j] + min(above)\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [arr[i] for i in range(len(arr))]\n for i in range(1, len(arr)):\n for j in range(len(arr[0])):\n opts = [arr[i][j] + x for (c, x) in enumerate(arr[i - 1]) if c != j]\n dp[i][j] = min(opts)\n return min(dp[-1])", "def minfallingpathsum(A: List[List[int]]) -> int:\n costs = [[None for i in range(len(A))] for j in range(len(A[0]))]\n for j in range(len(A)):\n costs[0] = A[0]\n for i in range(1, len(A)):\n for j in range(len(A)):\n parents = list()\n for p in range(len(A)):\n if p != j:\n parents.append(costs[i - 1][p])\n costs[i][j] = min(parents) + A[i][j]\n return min(costs[len(A) - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n T = [[0 for _ in range(len(arr))] for _ in range(len(arr))]\n T[0] = arr[0]\n for i in range(1, len(arr)):\n for j in range(len(arr)):\n T[i][j] = arr[i][j] + min([T[i - 1][c] for c in range(len(arr)) if c != j])\n return min(T[-1])", "import heapq as pq\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n rows = len(arr)\n cols = len(arr[0])\n min_vals = []\n for i in range(cols):\n pq.heappush(min_vals, (arr[0][i], i))\n min_vals = pq.nsmallest(2, min_vals)\n for i in range(1, cols):\n new_min_vals = []\n (min_val2, _) = min_vals.pop()\n (min_val, min_col) = min_vals.pop()\n for col in range(cols):\n arr[i][col] += min_val if min_col != col else min_val2\n pq.heappush(new_min_vals, (arr[i][col], col))\n min_vals = pq.nsmallest(2, new_min_vals)\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [[0] * len(arr[0]) for _ in arr]\n for i in range(len(arr)):\n if i == 0:\n dp[i] = arr[i]\n else:\n for j in range(len(arr[0])):\n dp[i][j] = self.min_exclude(dp[i - 1], j) + arr[i][j]\n return min(dp[-1])\n\ndef min_exclude(array, exclude):\n if len(array) == 0:\n return None\n out = float('inf')\n for i in range(len(array)):\n if i != exclude:\n out = min(out, array[i])\n return out", "def minfallingpathsum(arr: List[List[int]]) -> int:\n A = arr\n for i in range(1, len(A)):\n for j in range(len(A[0])):\n if j == 0:\n A[i][j] += min([A[i - 1][j] for j in range(1, len(A))])\n elif j == len(A[0]) - 1:\n A[i][j] += min([A[i - 1][j] for j in range(0, len(A) - 1)])\n else:\n A[i][j] += min([A[i - 1][j] for j in [x for x in range(len(A)) if x != j]])\n return min(A[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr)\n for i in range(1, m):\n for j in range(m):\n res = float('inf')\n for x in range(m):\n if x != j:\n if arr[i][j] + arr[i - 1][x] < res:\n res = arr[i][j] + arr[i - 1][x]\n arr[i][j] = res\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [[0 for _ in range(len(arr))] for _ in range(len(arr[0]))]\n for i in range(len(dp)):\n dp[0][i] = arr[0][i]\n for i in range(1, len(dp)):\n for j in range(len(dp[i])):\n if j == 0:\n dp[i][j] = min((arr[i][j] + dp[i - 1][k] for k in range(1, len(dp[i]))))\n elif j == len(dp[i]) - 1:\n dp[i][j] = min((arr[i][j] + dp[i - 1][k] for k in range(len(dp[i]) - 1)))\n else:\n left_max = min((arr[i][j] + dp[i - 1][k] for k in range(j)))\n right_max = min((arr[i][j] + dp[i - 1][k] for k in range(j + 1, len(dp[i]))))\n dp[i][j] = min(left_max, right_max)\n return min(dp[-1])", "from heapq import nsmallest\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [[0] * len(arr[0]) for _ in range(len(arr))]\n dp[0] = arr[0]\n for i in range(1, len(arr)):\n (min1, min2) = nsmallest(2, arr[i - 1])\n for j in range(len(arr[0])):\n if arr[i - 1][j] == min1:\n arr[i][j] += min2\n else:\n arr[i][j] += min1\n return min(arr[-1])", "from functools import lru_cache\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n if not arr:\n return 0\n cols = set(range(len(arr[0])))\n\n def path_sum(row, col):\n ret = arr[row][col]\n if row == len(arr) - 1:\n return ret\n other_cols = cols - {col}\n ret += min((path_sum(row + 1, _) for _ in other_cols))\n return ret\n return min((path_sum(0, _) for _ in cols))", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [[0 for _ in range(len(arr[0]))] for _ in range(len(arr))]\n for i in range(len(dp[0])):\n dp[0][i] = arr[0][i]\n for i in range(1, len(dp)):\n for j in range(len(dp[0])):\n mi = -1\n for k in range(len(dp[0])):\n if not j == k:\n if mi == -1 or dp[i - 1][k] + arr[i][j] < mi:\n mi = dp[i - 1][k] + arr[i][j]\n dp[i][j] = mi\n return min(dp[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n\n def dp(i, j):\n if i == 0:\n return arr[0][j]\n if i == len(arr):\n return min((dp(i - 1, k) for k in range(len(arr[0]))))\n return arr[i][j] + min((dp(i - 1, k) for k in range(len(arr[0])) if k != j))\n return dp(len(arr), -1)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n total = 0\n for row in range(len(arr) - 1):\n (row1_min, row2_min) = (min(arr[row]), min(arr[row + 1]))\n (i1, i2) = (arr[row].index(row1_min), arr[row + 1].index(row2_min))\n if i1 != i2:\n total += row1_min\n else:\n total = False\n break\n if total:\n return total + min(arr[-1])\n dp = [[arr[j][i] if j == 0 else float('inf') for i in range(len(arr))] for j in range(len(arr))]\n for row in range(len(arr) - 1):\n for col in range(len(arr[row])):\n for next_col in range(len(arr[row])):\n if next_col != col:\n dp[row + 1][next_col] = min(dp[row + 1][next_col], dp[row][col] + arr[row + 1][next_col])\n return min(dp[len(arr) - 1])", "from typing import List\nfrom functools import lru_cache\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n\n def helper(r, c):\n if r == m:\n return 0\n return arr[r][c] + min((helper(r + 1, nc) for nc in range(n) if nc != c))\n return min((helper(0, c) for c in range(n)))", "from functools import lru_cache\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n\n def dp(i, j):\n if not (0 <= i < len(arr) and 0 <= j < len(arr[0])):\n return float('inf')\n if i == len(arr) - 1:\n return arr[i][j]\n return arr[i][j] + min((dp(i + 1, k) for k in range(len(arr[0])) if k != j))\n return min((dp(0, j) for j in range(len(arr[0]))))", "def minfallingpathsum(arr: List[List[int]]) -> int:\n for i in range(1, len(arr)):\n for j in range(len(arr[0])):\n above = []\n for k in range(len(arr[0])):\n if k != j:\n heapq.heappush(above, arr[i - 1][k])\n arr[i][j] = arr[i][j] + above[0]\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n for i in range(1, m):\n for j in range(n):\n m = float('inf')\n for k in range(n):\n if k == j:\n continue\n m = min(m, arr[i - 1][k])\n arr[i][j] += m\n return min(arr[-1])", "import itertools\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n (nr, nc) = (len(arr), len(arr[0]))\n for (r_i, c_i) in itertools.product(list(range(nr - 2, -1, -1)), list(range(nc))):\n downs = [(r_i + 1, d_c) for d_c in range(nc) if d_c != c_i]\n min_downs = min([arr[d_r][d_c] for (d_r, d_c) in downs])\n arr[r_i][c_i] += min_downs\n return min([arr[0][c] for c in range(nc)])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n N = len(arr)\n dp = [[0] * N for _ in range(N)]\n for i in range(N):\n dp[N - 1][i] = arr[N - 1][i]\n for r in range(N - 2, -1, -1):\n for c in range(N):\n min_c = float('inf')\n for n_c in range(N):\n if n_c == c:\n continue\n min_c = min(min_c, arr[r + 1][n_c])\n dp[r][c] = min_c + arr[r][c]\n arr[r][c] = dp[r][c]\n res = float('inf')\n for i in range(N):\n res = min(res, dp[0][i])\n return res", "def minfallingpathsum(arr: List[List[int]]) -> int:\n from copy import deepcopy\n v = deepcopy(arr)\n for i in range(len(arr) - 2, -1, -1):\n for j in range(len(arr[0])):\n minn = float('inf')\n for k in range(len(arr[0])):\n if j != k:\n minn = min(minn, v[i + 1][k])\n v[i][j] += minn\n return min(v[0])", "def minfallingpathsum(A: List[List[int]]) -> int:\n g = [[inf] * len(a) for a in A]\n\n def get(i, j):\n m = inf\n for k in range(0, len(A[0])):\n if k != j:\n m = min(m, g[i - 1][k])\n return m\n for i in range(len(g)):\n for j in range(len(g[0])):\n if i == 0:\n g[i][j] = A[i][j]\n else:\n g[i][j] = min(g[i][j], get(i, j) + A[i][j])\n return min(g[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [[0 for i in range(len(arr))] for j in range(len(arr))]\n for i in range(len(arr)):\n dp[0][i] = arr[0][i]\n for i in range(1, len(arr)):\n for j in range(len(arr)):\n m = 9999999\n for k in range(len(arr)):\n if k != j:\n m = min(m, dp[i - 1][k])\n dp[i][j] = arr[i][j] + m\n m = 99999999\n for i in range(len(arr)):\n m = min(m, dp[len(arr) - 1][i])\n return m", "def minfallingpathsum(arr: List[List[int]]) -> int:\n if not arr:\n return 0\n R = C = len(arr)\n for r in range(1, R):\n for c in range(0, C):\n m = float('inf')\n for i in range(C):\n if i != c:\n m = min(m, arr[r - 1][i])\n arr[r][c] += m\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n if arr is None or len(arr) == 0 or len(arr[0]) == 0:\n return 0\n for i in range(1, len(arr)):\n for j in range(len(arr[0])):\n temp = float('inf')\n for last_col in range(len(arr[0])):\n if last_col != j:\n temp = min(temp, arr[i - 1][last_col])\n arr[i][j] += temp\n ans = float('inf')\n for i in range(len(arr[0])):\n ans = min(ans, arr[-1][i])\n return ans", "def minfallingpathsum(arr: List[List[int]]) -> int:\n import math\n n = len(arr)\n if n == 0:\n return 0\n k = len(arr[0])\n for house in range(1, n):\n for color in range(k):\n best = math.inf\n for prev_color in range(k):\n if color == prev_color:\n continue\n best = min(best, arr[house - 1][prev_color])\n arr[house][color] += best\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n rows = len(arr)\n columns = len(arr[0])\n for i in range(1, rows):\n for j in range(columns):\n minimum = float('inf')\n for k in range(columns):\n if k != j:\n minimum = min(minimum, arr[i - 1][k])\n arr[i][j] = arr[i][j] + minimum\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n for i in range(1, n):\n lowest = min(arr[i - 1])\n lowestCount = 0\n secondLowest = float('inf')\n for j in range(len(arr[0])):\n if arr[i - 1][j] == lowest:\n lowestCount += 1\n if arr[i - 1][j] > lowest:\n secondLowest = min(secondLowest, arr[i - 1][j])\n if lowestCount >= 2:\n secondLowest = lowest\n for j in range(len(arr[0])):\n if arr[i - 1][j] == lowest:\n arr[i][j] += secondLowest\n else:\n arr[i][j] += lowest\n return min(arr[n - 1])", "import heapq\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n copy = deepcopy(arr)\n for row in range(1, len(arr)):\n smallest = heapq.nsmallest(2, copy[row - 1])\n for col in range(len(arr[0])):\n copy[row][col] += smallest[0] if copy[row - 1][col] != smallest[0] else smallest[1]\n return min(copy[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n if n == 1:\n return arr[0][0]\n MAX_V = int(1000000000.0)\n min_v = [0] * n\n for i in range(n):\n row = arr[i]\n new_min_v = [MAX_V] * n\n scan_min = min_v[-1]\n for i in range(n - 2, -1, -1):\n new_min_v[i] = min(new_min_v[i], scan_min + row[i])\n scan_min = min(scan_min, min_v[i])\n scan_min = min_v[0]\n for i in range(1, n):\n new_min_v[i] = min(new_min_v[i], scan_min + row[i])\n scan_min = min(scan_min, min_v[i])\n min_v = new_min_v\n return min(min_v)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr)\n n = len(arr[0])\n dp = [[float('inf') for j in range(n)] for i in range(m)]\n for j in range(n):\n dp[0][j] = arr[0][j]\n for i in range(1, m):\n min_idx = sec_min_idx = None\n for j in range(n):\n if min_idx is None or dp[i - 1][j] < dp[i - 1][min_idx]:\n sec_min_idx = min_idx\n min_idx = j\n elif sec_min_idx is None or dp[i - 1][j] < dp[i - 1][sec_min_idx]:\n sec_min_idx = j\n for j in range(n):\n if j == min_idx:\n dp[i][j] = dp[i - 1][sec_min_idx] + arr[i][j]\n else:\n dp[i][j] = dp[i - 1][min_idx] + arr[i][j]\n return min(dp[m - 1])", "import heapq\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n (rows, cols) = (len(arr), len(arr[0]))\n for i in range(1, rows):\n (min1, min2) = heapq.nsmallest(2, arr[i - 1])\n for j in range(cols):\n if arr[i - 1][j] == min1:\n arr[i][j] += min2\n else:\n arr[i][j] += min1\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n dp = arr[0][:]\n for i in range(1, n):\n right_min = [math.inf] * (n - 1) + [dp[n - 1]]\n for j in range(n - 2, -1, -1):\n right_min[j] = min(right_min[j + 1], dp[j])\n left_min = math.inf\n for j in range(n):\n prev = left_min\n if j < n - 1:\n prev = min(prev, right_min[j + 1])\n left_min = min(left_min, dp[j])\n dp[j] = prev + arr[i][j]\n return min(dp)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n (m, n) = (len(arr), len(arr[0]))\n i = 1\n while i < m:\n a = arr[i - 1][:]\n min1 = a.index(min(a))\n a[min1] = float('inf')\n min2 = a.index(min(a))\n a = arr[i - 1]\n for j in range(n):\n if j == min1:\n arr[i][j] += a[min2]\n else:\n arr[i][j] += a[min1]\n i += 1\n return min(arr[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n rows = len(arr)\n for row in range(1, rows):\n nsmall_in_row = heapq.nsmallest(2, arr[row - 1])\n for col in range(0, rows):\n arr[row][col] += nsmall_in_row[1] if nsmall_in_row[0] == arr[row - 1][col] else nsmall_in_row[0]\n return min(arr[-1])", "import heapq\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [[float('inf')] + i + [float('inf')] for i in arr]\n for i in range(1, len(dp)):\n hp = heapq.nsmallest(2, dp[i - 1])\n for j in range(1, len(dp[0]) - 1):\n dp[i][j] += hp[0] if dp[i - 1][j] != hp[0] else hp[1]\n return min(dp[-1])", "def minfallingpathsum(A: List[List[int]]) -> int:\n n = len(A)\n for i in range(n - 2, -1, -1):\n mn = min(A[i + 1])\n idx = A[i + 1].index(mn)\n for j in range(n):\n if j != idx:\n A[i][j] += mn\n elif j == idx:\n dp = [101 for _ in range(n)]\n for k in range(n):\n if k != idx:\n dp[k] = A[i + 1][k]\n A[i][j] += min(dp)\n return min(A[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n import heapq\n dp = arr[0][:]\n for i in range(1, len(arr)):\n heap = list(((v, k) for (k, v) in enumerate(dp)))\n heapq.heapify(heap)\n (min_value, min_pos) = heapq.heappop(heap)\n (alter_value, _) = heapq.heappop(heap)\n new_dp = [v + min_value for v in arr[i]]\n new_dp[min_pos] += alter_value - min_value\n dp = new_dp\n return min(dp)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n copy = deepcopy(arr)\n for row in range(1, len(arr)):\n (min1, ind1, min2, ind2) = (20000, 0, 20000, 0)\n for (i, v) in enumerate(copy[row - 1]):\n if v < min1:\n min1 = v\n ind1 = i\n for (i, v) in enumerate(copy[row - 1]):\n if v < min2 and i != ind1:\n min2 = v\n ind2 = i\n for col in range(len(arr[0])):\n copy[row][col] += copy[row - 1][ind1] if ind1 != col else copy[row - 1][ind2]\n return min(copy[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n\n def findMinOtherThanThis(nums):\n ret = list()\n (left, right) = ([0 for i in range(len(arr))], [0 for i in range(len(arr))])\n left_min = float('inf')\n for (idx, n) in enumerate(nums):\n left[idx] = left_min\n left_min = min(left_min, n)\n right_min = float('inf')\n for idx in range(len(nums) - 1, -1, -1):\n right[idx] = right_min\n right_min = min(right_min, nums[idx])\n for idx in range(len(nums)):\n ret.append(min(left[idx], right[idx]))\n return ret\n if not arr:\n return 0\n m = len(arr)\n n = len(arr[0])\n dp = [[0 for j in range(n)] for i in range(m)]\n for i in range(m - 1, -1, -1):\n for j in range(n):\n if i == m - 1:\n dp[i][j] = arr[i][j]\n else:\n dp[i][j] = arr[i][j] + dp[i + 1][j]\n dp[i] = findMinOtherThanThis(dp[i])\n return min(dp[0])", "def minfallingpathsum(cost: List[List[int]]) -> int:\n cols = len(cost[0])\n dp = cost[0]\n for h in range(1, len(cost)):\n prev = sorted(cost[h - 1])\n for m in range(0, cols):\n cost[h][m] += prev[1] if cost[h - 1][m] == prev[0] else prev[0]\n return min(cost[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n from copy import deepcopy\n from heapq import heapify\n v = deepcopy(arr)\n for i in range(len(arr) - 2, -1, -1):\n s = deepcopy(v[i + 1])\n heapify(s)\n min1 = s[0]\n min2 = min(s[1], s[2])\n for j in range(len(arr[0])):\n if v[i + 1][j] != min1:\n v[i][j] += min1\n else:\n v[i][j] += min2\n return min(v[0])", "import heapq\nimport numpy as np\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n x = len(arr)\n new_count = np.zeros((x, x))\n new_count[0] = arr[0]\n for k in range(1, x):\n previous_line_maxes = heapq.nsmallest(2, new_count[k - 1])\n for index in range(len(arr)):\n if new_count[k - 1][index] == previous_line_maxes[0]:\n value_to_add = previous_line_maxes[1]\n else:\n value_to_add = previous_line_maxes[0]\n new_count[k, index] = value_to_add + arr[k][index]\n return int(min(new_count[-1]))", "import heapq\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n xm = [(0, -1), (0, -1)]\n for i in range(n):\n xm = heapq.nsmallest(2, [(x + xm[1][0], j) if j == xm[0][1] else (x + xm[0][0], j) for (j, x) in enumerate(arr[i])])\n return xm[0][0]", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n\n def getTwo(a):\n pos = {v: k for (k, v) in enumerate(a)}\n (f, s) = sorted(a)[:2]\n return ([f, pos[f]], [s, pos[s]])\n for i in range(1, n):\n pre = getTwo(arr[i - 1])\n for j in range(n):\n if j != pre[0][1]:\n arr[i][j] += pre[0][0]\n else:\n arr[i][j] += pre[1][0]\n return min(arr[-1])", "def minfallingpathsum(A):\n for i in range(1, len(A)):\n r = heapq.nsmallest(2, A[i - 1])\n for j in range(len(A[0])):\n A[i][j] += r[1] if A[i - 1][j] == r[0] else r[0]\n return min(A[-1])", "def minfallingpathsum(dp: List[List[int]]) -> int:\n for i in range(1, len(dp)):\n best2 = sorted(list(enumerate(dp[i - 1])), key=lambda x: x[1])[:2]\n for j in range(len(dp[i])):\n dp[i][j] = [x for x in best2 if x[0] != j][0][1] + dp[i][j]\n return min(dp[-1])", "def scan(row: List[int], n: int) -> (int, int, int):\n best = None\n k = None\n alt = None\n for j in range(n):\n if not best or row[j] < best:\n alt = best\n best = row[j]\n k = j\n elif not alt or row[j] < alt:\n alt = row[j]\n return (best, k, alt)\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n M = [[None for j in range(n)] for i in range(n)]\n for j in range(n):\n M[0][j] = arr[0][j]\n (best, k, alt) = self.scan(M[0], n)\n for i in range(1, n):\n for j in range(n):\n if j != k:\n M[i][j] = arr[i][j] + best\n else:\n M[i][j] = arr[i][j] + alt\n (best, k, alt) = self.scan(M[i], n)\n return best", "def minfallingpathsum(arr: List[List[int]]) -> int:\n iMax = len(arr)\n jMax = len(arr[0])\n dp = {}\n smallest2 = [None for _ in range(iMax)]\n\n def moveDown(preJ, iNow):\n if iNow == iMax:\n return 0\n if (preJ, iNow) in dp:\n return dp[preJ, iNow]\n subAns = float('inf')\n if smallest2[iNow] == None:\n temp1 = float('inf')\n temp1Index = None\n temp2 = float('inf')\n temp2Index = None\n for (j, val) in enumerate(arr[iNow]):\n subAns = val + moveDown(j, iNow + 1)\n if subAns <= temp1:\n (temp1, temp2) = (subAns, temp1)\n (temp1Index, temp2Index) = (j, temp1Index)\n elif subAns <= temp2:\n temp2 = subAns\n temp2Index = j\n smallest2[iNow] = [[temp1Index, temp1], [temp2Index, temp2]]\n if preJ == smallest2[iNow][0][0]:\n subAns = smallest2[iNow][1][1]\n else:\n subAns = smallest2[iNow][0][1]\n dp[preJ, iNow] = subAns\n return subAns\n return moveDown(-1, 0)", "def minfallingpathsum1(arr: List[List[int]]) -> int:\n m = len(arr)\n n = len(arr[0])\n if m == 1:\n return arr[0][0]\n\n def get_min_neighbors(j):\n (a, row_prev[j]) = (row_prev[j], float('inf'))\n min_val = min(row_prev)\n row_prev[j] = a\n return min_val\n row_prev = arr[0]\n cur = [0] * n\n global_min = float('inf')\n for row in range(1, m):\n for col in range(n):\n cur[col] = get_min_neighbors(col) + arr[row][col]\n if row == m - 1 and cur[col] < global_min:\n global_min = cur[col]\n row_prev = cur[:]\n return global_min\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr)\n n = len(arr[0])\n if m == 1:\n return arr[0][0]\n\n def get_min_neighbors():\n min1 = float('inf')\n min2 = float('inf')\n for val in dp:\n if val < min1:\n min2 = min1\n min1 = val\n elif val < min2:\n min2 = val\n return (min1, min2)\n dp = arr[0]\n cur = [0] * n\n global_min = float('inf')\n for row in range(1, m):\n (min1, min2) = get_min_neighbors()\n for col in range(n):\n min_val = min1 if dp[col] != min1 else min2\n cur[col] = min_val + arr[row][col]\n if row == m - 1 and cur[col] < global_min:\n global_min = cur[col]\n dp = cur[:]\n return global_min", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr)\n n = len(arr[0])\n dp = [[0] * n for i in range(m)]\n for j in range(n):\n dp[0][j] = arr[0][j]\n for i in range(1, m):\n sorted_lastrow = sorted([(k, dp[i - 1][k]) for k in range(n)], key=lambda x: x[1])\n (p_index, p) = sorted_lastrow[0]\n (q_index, q) = sorted_lastrow[1]\n for j in range(n):\n lastdp = p if p_index != j else q\n dp[i][j] = lastdp + arr[i][j]\n return min(dp[m - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr[0])\n table = [arr[0][i] for i in range(m)]\n\n def get_mins(table):\n cur_min = int(1000000000.0)\n cur_min_i = -1\n next_cur_min = int(1000000000.0)\n next_cur_min_i = -1\n for (i, x) in enumerate(table):\n if x <= cur_min:\n (cur_min, cur_min_i) = (x, i)\n for (i, x) in enumerate(table):\n if x <= next_cur_min and i != cur_min_i:\n (next_cur_min, next_cur_min_i) = (x, i)\n return (cur_min, cur_min_i, next_cur_min, next_cur_min_i)\n (cur_min, cur_min_i, next_cur_min, next_cur_min_i) = get_mins(table)\n for i in range(1, len(arr)):\n for j in range(m):\n table[j] = arr[i][j]\n if j != cur_min_i:\n table[j] = arr[i][j] + cur_min\n else:\n table[j] = arr[i][j] + next_cur_min\n (cur_min, cur_min_i, next_cur_min, next_cur_min_i) = get_mins(table)\n return cur_min", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = len(arr)\n for i in range(1, m):\n min1 = min(arr[i - 1])\n ind = arr[i - 1].index(min1)\n for j in range(m):\n if ind == j:\n arr[i][j] = arr[i][j] + min(arr[i - 1][0:j] + arr[i - 1][j + 1:])\n else:\n arr[i][j] = arr[i][j] + min1\n return min(arr[-1])", "from collections import Counter\n\ndef get_minset(l):\n left = []\n right = []\n n = len(l)\n for i in range(n):\n if i == 0:\n left.append(l[i])\n right.append(l[n - i - 1])\n else:\n left.append(min(left[-1], l[i]))\n right.append(min(right[-1], l[n - i - 1]))\n right = right[::-1]\n res = []\n for i in range(n):\n if i == 0:\n res.append(right[1])\n elif i == n - 1:\n res.append(left[n - 2])\n else:\n res.append(min(left[i - 1], right[i + 1]))\n return res\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n last = arr[0]\n maxset = self.get_minset(last)\n for i in range(1, len(arr)):\n tmp = []\n for j in range(len(arr[0])):\n tmp.append(maxset[j] + arr[i][j])\n last = tmp\n maxset = self.get_minset(last)\n return min(last)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n m = 100 * len(arr)\n T = [[0 for _ in range(len(arr))] for _ in range(len(arr))]\n T[0] = arr[0]\n for i in range(1, len(arr)):\n for j in range(len(arr)):\n temp = T[i - 1][j]\n T[i - 1][j] = m\n T[i][j] = arr[i][j] + min(T[i - 1])\n T[i - 1][j] = temp\n return min(T[-1])", "def minfallingpathsum(A: List[List[int]]) -> int:\n if len(A) == 1:\n return min(A[0])\n for i in range(1, len(A)):\n (minValue, minIdx) = (sys.maxsize, -1)\n secondMinValue = sys.maxsize\n for j in range(len(A[0])):\n if A[i - 1][j] < minValue:\n secondMinValue = minValue\n (minValue, minIdx) = (A[i - 1][j], j)\n elif A[i - 1][j] < secondMinValue:\n secondMinValue = A[i - 1][j]\n for j in range(len(A[0])):\n if j == minIdx:\n A[i][j] += secondMinValue\n else:\n A[i][j] += minValue\n return min(A[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = [0] * len(arr[0])\n for (r, row) in enumerate(arr):\n for c in range(len(row)):\n row[c] += min(dp[:c] + dp[c + 1:])\n dp = row[:]\n return min(dp)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n dp = [[0 for i in range(n)] for i in range(n)]\n for i in range(n):\n dp[0][i] = arr[0][i]\n for i in range(1, n):\n dp[i][0] = min(dp[i - 1][1:]) + arr[i][0]\n for j in range(1, n - 1):\n minLeft = min(dp[i - 1][:j])\n minRight = min(dp[i - 1][j + 1:])\n dp[i][j] = min(minLeft, minRight) + arr[i][j]\n dp[i][-1] = min(dp[i - 1][:-1]) + arr[i][-1]\n return min(dp[-1])", "def find_smallest_and_second_smallest(a):\n smallest = a[0]\n c = 1\n for i in a:\n if i < smallest:\n smallest = i\n c = 1\n if i == smallest:\n c += 1\n smallest2 = True\n if c == 2:\n smallest2 = 999999\n for i in a:\n if i != smallest:\n smallest2 = min(smallest2, i)\n return (smallest, smallest2)\n\ndef givedp(arr):\n if len(arr) == 1:\n return min(arr[0])\n (a, b) = ('', '')\n for i in range(len(arr) - 1, -1, -1):\n if i != len(arr) - 1:\n for j in range(len(arr[i])):\n if a == arr[i + 1][j] and b != True:\n arr[i][j] += b\n else:\n arr[i][j] += a\n if i != 0:\n (a, b) = self.find_smallest_and_second_smallest(arr[i])\n return min(arr[0])\n\ndef minfallingpathsum(arr: List[List[int]]) -> int:\n return self.givedp(arr)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n if not arr:\n return 0\n prev = arr[0]\n curr = [0 for i in range(len(prev))]\n for cost in arr[1:]:\n for i in range(len(cost)):\n tmp = prev[:i] + prev[i + 1:]\n curr[i] = min(tmp) + cost[i]\n prev[:] = curr[:]\n return min(prev)", "def minfallingpathsum(arr: List[List[int]]) -> int:\n N = len(arr)\n while len(arr) >= 2:\n cur = arr.pop()\n for i in range(N):\n newa = cur[:i] + cur[i + 1:]\n arr[-1][i] += min(newa)\n return min(arr[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n while len(arr) >= 2:\n row = arr.pop()\n for i in range(len(row)):\n r = row[:i] + row[i + 1:]\n arr[-1][i] += min(r)\n return min(arr[0])", "def minfallingpathsum(A: List[List[int]]) -> int:\n n = len(A)\n dp = [[0 for j in range(n)] for i in range(n)]\n for i in range(n):\n dp[-1][i] = A[-1][i]\n for i in range(n - 2, -1, -1):\n for j in range(n):\n dp[i][j] = A[i][j] + min(dp[i + 1][:j] + dp[i + 1][j + 1:])\n return min(dp[0])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n num_rows = len(arr)\n num_cols = len(arr[0])\n dp = [[float('inf') for _ in range(num_cols)] for _ in range(num_rows + 1)]\n for col in range(num_cols):\n dp[0][col] = 0\n for row in range(num_rows):\n dp_r = row + 1\n for col in range(num_cols):\n dp[dp_r][col] = min(dp[dp_r - 1][:col] + dp[dp_r - 1][col + 1:]) + arr[row][col]\n return min(dp[-1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n n = len(arr)\n d = [[float('-inf') for _ in range(n)] for _ in range(n)]\n for y in range(n):\n d[0][y] = arr[0][y]\n for x in range(1, n):\n smallest_two = heapq.nsmallest(2, d[x - 1])\n for y in range(n):\n if d[x - 1][y] == smallest_two[0]:\n d[x][y] = smallest_two[1] + arr[x][y]\n else:\n d[x][y] = smallest_two[0] + arr[x][y]\n ans = float('inf')\n for y in range(n):\n ans = min(ans, d[n - 1][y])\n return ans", "def minfallingpathsum(arr: List[List[int]]) -> int:\n if len(arr) == 1:\n return arr[0][0]\n else:\n Row = len(arr)\n Col = len(arr[0])\n ResultMat = [arr[0]]\n for i in range(1, Row):\n ResultList = []\n for j in range(Col):\n NewList = ResultMat[i - 1]\n NewList = NewList[0:j] + NewList[j + 1:len(NewList)]\n Min = min(NewList)\n Value = Min + arr[i][j]\n ResultList.append(Value)\n ResultMat.append(ResultList)\n return min(ResultMat[Row - 1])", "def minfallingpathsum(arr: List[List[int]]) -> int:\n dp = arr[0]\n n = len(arr[0])\n for row in arr[1:]:\n newdp = row[:]\n for i in range(n):\n temp = dp[:i] + dp[i + 1:]\n newdp[i] += min(temp)\n dp = newdp\n return min(dp)"], "starter_code": "def minfallingpathsum(arr: List[List[int]]) -> int:\n", "input_output": {"fn_name": "minFallingPathSum", "inputs": [[[[1, 2, 3], [6, 6, 7], [7, 8, 9], [], []]]], "outputs": [13]}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Dynamic Programming", "Matrix"], "name": null, "source": "leetcode", "tags": ["Matrices", "Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/minimum-falling-path-sum-ii/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "minfallingpathsum", "task_id": "TACO_lite/79", "example": [[[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]], ["13"]]} +{"requirement": "Given two values \u2018a\u2019 and \u2018b\u2019 that represent coefficients in \u201cax \u2013 by = 0\u201d, find the smallest values of x and y that satisfy the equation. It may also be assumed that x > 0, y > 0, a > 0 and b > 0.\nExample 1:\nInput: a = 25, b = 35\nOutput: 7 5\nExplaination: 25*7 - 35*5 = 0. And x = 7 \nand y = 5 are the least possible values \nof x and y to get the equation solved.\nExample 2:\nInput: a = 3, b = 7\nOutput: 7 3\nExplaination: For this case x = 7 and \ny = 3 are the least values of x and y \nto satisfy the equation.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function findXY() which takes a and b as input parameters and returns the least possible values of x and y to satisfy the equation.\nExpected Time Complexity: O(log(max(a, b)))\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 a, b \u2264 10^{4}", "solutions": ["def findxy(a, b):\n import math\n n = math.gcd(a, b)\n x = a / n\n y = b / n\n if b / a == y / x:\n return [int(y), int(x)]", "def findxy(a, b):\n i = 2\n n = min(a, b)\n while i != n + 1:\n if a % i == 0 and b % i == 0:\n a = a // i\n b = b // i\n else:\n i += 1\n return (b, a)", "def findxy(a, b):\n\n def gcd(m, n):\n if n == 0:\n return m\n return gcd(n, m % n)\n result = a * b // gcd(a, b)\n x = result // a\n y = result // b\n return (x, y)", "import math\n\ndef findxy(a, b):\n l = math.gcd(a, b)\n return [b // l, a // l]", "def findxy(a, b):\n if a > b:\n greater = a\n else:\n greater = b\n while True:\n if greater % a == 0 and greater % b == 0:\n lcm = greater\n break\n greater += 1\n return (lcm // a, lcm // b)", "from math import gcd\n\ndef findxy(a, b):\n m = gcd(a, b)\n l = []\n l.append(b // m)\n l.append(a // m)\n return l", "def findxy(a, b):\n p = max(a, b)\n q = min(a, b)\n for i in range(1, q + 1):\n if p * i % q == 0:\n break\n j = int(p * i / q)\n if p == a:\n return [i, j]\n else:\n return [j, i]", "def findxy(a, b):\n r = [0] * 2\n if a > b:\n small = b\n else:\n small = a\n for i in range(1, small + 1):\n if a % i == 0 and b % i == 0:\n gcd = i\n lcm = a * b // gcd\n r[0] = lcm // a\n r[1] = lcm // b\n return r", "import math\n\ndef findxy(a, b):\n h = math.gcd(a, b)\n l = a / h * b\n arr = []\n a1 = l / a\n arr.append(int(a1))\n a2 = l / b\n arr.append(int(a2))\n return arr"], "starter_code": "def findxy(a, b):\n", "input_output": {"inputs": ["a = 25, b = 35", "a = 3, b = 7"], "outputs": ["7 5", "7 3"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/find-smallest-values-of-x-and-y-such-that-ax-by-01433/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(max(a, b)))", "entry_point": "findxy", "task_id": "TACO_lite/7", "example": [[], []]} +{"requirement": "A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.)\nWe are given a string S of '0's and '1's, and we may flip any '0' to a '1' or a '1' to a '0'.\nReturn the minimum number of flips to make S\u00a0monotone increasing.\n\u00a0\n\nExample 1:\nInput: \"00110\"\nOutput: 1\nExplanation: We flip the last digit to get 00111.\n\n\nExample 2:\nInput: \"010110\"\nOutput: 2\nExplanation: We flip to get 011111, or alternatively 000111.\n\n\nExample 3:\nInput: \"00011000\"\nOutput: 2\nExplanation: We flip to get 00000000.\n\n\u00a0\nNote:\n\n1 <= S.length <= 20000\nS only consists of '0' and '1' characters.", "solutions": ["def minflipsmonoincr(S: str) -> int:\n onesSoFar = 0\n partial = 0\n for n in S:\n if n == '0':\n partial = min(onesSoFar, partial + 1)\n else:\n onesSoFar += 1\n return partial", "def minflipsmonoincr(S: str) -> int:\n if not S:\n return 0\n n = len(S)\n if n == 1:\n return 0\n total_1s = 0\n total_0s = 0\n for char in S:\n if char == '1':\n total_1s += 1\n else:\n total_0s += 1\n if total_1s == 0 or total_0s == 0:\n return 0\n prefix_sum = 0\n ans = float('inf')\n for i in range(n):\n prefix_sum += 1 if S[i] == '1' else 0\n ans = min(ans, prefix_sum + (n - i - 1 - (total_1s - prefix_sum)))\n return min(ans, total_0s, total_1s)", "def minflipsmonoincr(S: str) -> int:\n at0 = 0\n at1 = 0\n num0 = 0\n for a in S:\n if a == '0':\n at1 = min(at1, at0) + 1\n else:\n at1 = min(at1, at0)\n at0 += 1\n return min(at1, at0)", "def minflipsmonoincr(S: str) -> int:\n str_len = len(S)\n count_arr = [[0, 0] for x in range(str_len)]\n one_start_idx = -1\n for i in range(len(S)):\n if S[i] == '0':\n if i == 0:\n count_arr[i][0] += 1\n count_arr[i][1] = 0\n else:\n count_arr[i][0] = count_arr[i - 1][0] + 1\n count_arr[i][1] = count_arr[i - 1][1]\n else:\n if i == 0:\n count_arr[i][1] += 1\n else:\n count_arr[i][1] = count_arr[i - 1][1] + 1\n count_arr[i][0] = count_arr[i - 1][0]\n if one_start_idx == -1:\n one_start_idx = i\n total_flips = []\n total_flips.append(min(count_arr[str_len - 1][0], count_arr[str_len - 1][1]))\n for i in range(one_start_idx, str_len):\n if i == 0:\n total_flips.append(count_arr[str_len - 1][0] - count_arr[i][0])\n elif i == str_len - 1:\n total_flips.append(count_arr[str_len - 1][0])\n else:\n total_flips.append(count_arr[i - 1][1] + count_arr[str_len - 1][0] - count_arr[i][0])\n return min(total_flips)", "def minflipsmonoincr(S: str) -> int:\n dp = 0\n ones = 0\n for c in S:\n if c == '0':\n dp = min(1 + dp, ones)\n else:\n dp = min(dp, 1 + ones)\n ones += 1\n return dp", "def minflipsmonoincr(S: str) -> int:\n (flip, one) = (0, 0)\n for i in S:\n if i == '1':\n one += 1\n else:\n flip += 1\n flip = min(one, flip)\n return flip", "def minflipsmonoincr(S: str) -> int:\n (n, prefix, total, res) = (len(S), 0, S.count('1'), sys.maxsize)\n for i in range(n + 1):\n res = min(res, prefix + len(S) - i - total + prefix)\n if i < n:\n prefix += 1 if S[i] == '1' else 0\n return res"], "starter_code": "def minflipsmonoincr(S: str) -> int:\n", "input_output": {"fn_name": "minFlipsMonoIncr", "inputs": [["\"00110\""]], "outputs": [2]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Dynamic Programming", "String"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://leetcode.com/problems/flip-string-to-monotone-increasing/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "minflipsmonoincr", "task_id": "TACO_lite/6", "example": [[["00110"], ["010110"], ["00011000"]], ["1", "2", "2"]]} +{"requirement": "A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:\n\n2332 \n110011 \n54322345 \n\nFor a given number `num`, write a function to test if it's a numerical palindrome or not and return a boolean (true if it is and false if not).\n\n```if-not:haskell\nReturn \"Not valid\" if the input is not an integer or less than `0`.\n```\n```if:haskell\nReturn `Nothing` if the input is less than `0` and `Just True` or `Just False` otherwise.\n```\n\nOther Kata in this Series:\nNumerical Palindrome #1\nNumerical Palindrome #1.5\nNumerical Palindrome #2\nNumerical Palindrome #3\nNumerical Palindrome #3.5\nNumerical Palindrome #4\nNumerical Palindrome #5", "solutions": ["def palindrome(num):\n if type(num) is not int or num < 1:\n return 'Not valid'\n return num == int(str(num)[::-1])", "def palindrome(num):\n return str(num) == str(num)[::-1] if type(num) == int and num > 0 else 'Not valid'", "def palindrome(n):\n try:\n return 1.0 * n == int(str(n)[::-1])\n except:\n return 'Not valid'", "def palindrome(n):\n return 'Not valid' if type(n) != int or n < 0 else str(n) == str(n)[::-1]", "def palindrome(a):\n if type(a) == int:\n if a > 0:\n a = str(a)\n b = a[::-1]\n if a == b:\n return True\n else:\n return False\n else:\n return 'Not valid'\n else:\n return 'Not valid'", "def palindrome(num):\n if type(num) != int or num < 0:\n return 'Not valid'\n k = str(num)\n if k == k[::-1]:\n return True\n else:\n return False", "def palindrome(num):\n if type(123) != type(num):\n return 'Not valid'\n n = str(num)\n if any((not c.isdigit() for c in n)):\n return 'Not valid'\n l = len(n)\n return all((a == b for (a, b) in zip(n[:l // 2], n[::-1])))", "def palindrome(num):\n if not str(num).isdigit():\n return 'Not valid'\n if type(num) == str:\n return 'Not valid'\n num = str(num)\n return num == num[::-1]", "def palindrome(num):\n if isinstance(num, int) == False or num < 0:\n return 'Not valid'\n elif str(num) == str(num)[::-1]:\n return True\n else:\n return False", "def palindrome(num):\n\n def helper():\n if type(num) == str or num < 0:\n return 'Not valid'\n return True if str(num) == str(num)[::-1] else False\n try:\n int(num)\n except ValueError:\n return 'Not valid'\n else:\n return helper()", "def palindrome(n):\n if not isinstance(n, int) or n < 0:\n return 'Not valid'\n (rev, temp) = (0, n)\n while temp > 0:\n a = temp % 10\n rev = rev * 10 + a\n temp //= 10\n return rev == n", "def palindrome(num):\n if isinstance(num, int) is False or num < 0:\n return 'Not valid'\n return str(num) == str(num)[::-1]", "def palindrome(n):\n if type(n) == int and n > 0:\n (n1, n2) = (str(n), str(n)[::-1])\n return n1 == n2\n else:\n return 'Not valid'", "def palindrome(num):\n try:\n if type(num) != int or num < 0:\n raise Numerical_paindrom_exception\n return True if str(num)[::1] == str(num)[::-1] else False\n except Exception as e:\n return e.__str__()\n\ndef __init__():\n pass\n\ndef __str__():\n return 'Not valid'"], "starter_code": "def palindrome(num):\n", "input_output": {"fn_name": "palindrome", "inputs": [[1221], [110011], [1456009006541], [123322], [1], [152], [9999], ["ACCDDCCA"], ["@14AbC"], ["1221"], [-450]], "outputs": [[true], [true], [true], [false], [true], [false], [true], ["Not valid"], ["Not valid"], ["Not valid"], ["Not valid"]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/58ba6fece3614ba7c200017f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "palindrome", "task_id": "TACO_lite/80", "example": [[], []]} +{"requirement": "Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.\nFor eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.\n \nExample 1:\nInput : \"AABBBCBBAC\"\nOutput : 3\nExplanation : Sub-string -> \"BAC\"\nExample 2:\nInput : \"aaab\"\nOutput : 2\nExplanation : Sub-string -> \"ab\"\n \nExample 3:\nInput : \"GEEKSGEEKSFOR\"\nOutput : 8\nExplanation : Sub-string -> \"GEEKSFOR\"\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.\nExpected Time Complexity: O(256.N)\nExpected Auxiliary Space: O(256)\n \nConstraints:\n1 \u2264 |S| \u2264 10^{5}\nString may contain both type of English Alphabets.", "solutions": ["def findsubstring(str):\n dict = {}\n ans = float('inf')\n j = 0\n for i in str:\n if i not in dict:\n dict[i] = 0\n length = len(dict)\n for i in range(len(str)):\n dict[str[i]] += 1\n if dict[str[i]] == 1:\n length -= 1\n while length == 0:\n ans = min(ans, i - j + 1)\n dict[str[j]] -= 1\n if dict[str[j]] == 0:\n length += 1\n j += 1\n return ans", "from collections import defaultdict\n\ndef findsubstring(s):\n n = len(s)\n dist_count = len(set([x for x in s]))\n m = defaultdict(int)\n start = 0\n min_len = float('inf')\n count = 0\n for j in range(n):\n m[s[j]] += 1\n if m[s[j]] == 1:\n count += 1\n if count == dist_count:\n while m[s[start]] > 1:\n if m[s[start]] > 1:\n m[s[start]] -= 1\n start += 1\n len_window = j - start + 1\n if min_len > len_window:\n min_len = len_window\n return min_len", "def findsubstring(str):\n from collections import defaultdict\n n = len(str)\n if n <= 1:\n return 1\n dist_count = len(set([x for x in str]))\n curr_count = defaultdict(lambda : 0)\n count = 0\n start = 0\n min_len = n\n for j in range(n):\n curr_count[str[j]] += 1\n if curr_count[str[j]] == 1:\n count += 1\n if count == dist_count:\n while curr_count[str[start]] > 1:\n if curr_count[str[start]] > 1:\n curr_count[str[start]] -= 1\n start += 1\n len_window = j - start + 1\n min_len = min(min_len, len_window)\n start_index = start\n return min_len", "def findsubstring(s):\n D = {}\n for i in s:\n if i in D:\n pass\n else:\n D[i] = 1\n n = len(s)\n (i, j) = (0, 0)\n count = len(D)\n mini = 9999\n while j < n:\n if s[j] in D:\n D[s[j]] -= 1\n if D[s[j]] == 0:\n count -= 1\n while count == 0:\n mini = min(mini, j - i + 1)\n if s[i] in D:\n D[s[i]] += 1\n if D[s[i]] > 0:\n count += 1\n i += 1\n j += 1\n return mini", "def findsubstring(str):\n mp = {}\n cnt = 0\n for i in range(len(str)):\n if str[i] not in mp:\n mp[str[i]] = 0\n cnt += 1\n cnt1 = 0\n j = 0\n mn = len(str)\n for i in range(len(str)):\n if mp[str[i]] == 0:\n mp[str[i]] += 1\n cnt1 += 1\n else:\n mp[str[i]] += 1\n while cnt == cnt1:\n mn = min(mn, i - j + 1)\n if mp[str[j]] == 1:\n mp[str[j]] -= 1\n cnt1 -= 1\n j = j + 1\n else:\n mp[str[j]] -= 1\n j = j + 1\n return mn", "def findsubstring(str):\n dict = {}\n a = 1000000000.0\n j = 0\n for i in str:\n if i not in dict:\n dict[i] = 0\n l = len(dict)\n for i in range(len(str)):\n dict[str[i]] += 1\n if dict[str[i]] == 1:\n l -= 1\n while l == 0:\n a = min(a, i - j + 1)\n dict[str[j]] -= 1\n if dict[str[j]] == 0:\n l += 1\n j += 1\n return a", "def findsubstring(s):\n distinct = len(set(s))\n d = dict()\n si = -1\n Len = 100000.0\n start = 0\n for i in range(len(s)):\n if s[i] not in d:\n d[s[i]] = 1\n else:\n d[s[i]] += 1\n if len(d) == distinct:\n while d[s[start]] > 1:\n d[s[start]] -= 1\n start += 1\n clen = i - start + 1\n if Len > clen:\n Len = clen\n si = start\n return len(s[si:si + Len])", "from collections import defaultdict\n\ndef findsubstring(str):\n leng = len(str)\n (start, end) = (0, leng - 1)\n ct = 0\n t_dist = len(set([e for e in str]))\n chr_map = defaultdict(lambda : 0)\n min_wind = leng\n for i in range(leng):\n x = str[i]\n chr_map[x] += 1\n if chr_map[x] == 1:\n ct += 1\n if ct == t_dist:\n while chr_map[str[start]] > 1:\n chr_map[str[start]] -= 1\n start += 1\n min_wind = min(i - start + 1, min_wind)\n return min_wind", "def findsubstring(str):\n n = len(str)\n (dic, vic) = ({}, {})\n for a in str:\n if a not in dic:\n dic[a] = 0\n dic[a] += 1\n (i, j, ans) = (0, 0, 10000000000)\n while j < n:\n if str[j] not in vic:\n vic[str[j]] = 0\n vic[str[j]] += 1\n if len(vic) == len(dic):\n while len(vic) == len(dic):\n vic[str[i]] -= 1\n if vic[str[i]] == 0:\n del vic[str[i]]\n i += 1\n ans = min(ans, 2 + j - i)\n j += 1\n return ans", "def findsubstring(str):\n dict = {}\n ans = 1000000000.0\n for i in str:\n if i not in dict:\n dict[i] = 0\n length = len(dict)\n count = 0\n j = 0\n for i in range(len(str)):\n dict[str[i]] += 1\n if dict[str[i]] == 1:\n count += 1\n while count == length:\n ans = min(ans, i - j + 1)\n dict[str[j]] -= 1\n if dict[str[j]] == 0:\n count -= 1\n j += 1\n return ans", "from collections import Counter\n\ndef findsubstring(str1):\n length = len(str1)\n dict1 = Counter(str1)\n k = len(dict1)\n dict2 = dict()\n count = 0\n start = 0\n minimum = 99999\n for i in range(length):\n if count < k:\n j = start\n while j < length:\n if str1[j] not in dict2:\n dict2[str1[j]] = 1\n count += 1\n else:\n dict2[str1[j]] += 1\n if count == k:\n break\n j += 1\n if count == k:\n minimum = min(minimum, j - i + 1)\n start = j + 1\n dict2[str1[i]] -= 1\n if dict2[str1[i]] == 0:\n dict2.pop(str1[i])\n count -= 1\n return minimum", "from collections import Counter, defaultdict\n\ndef findsubstring(str_):\n set_of_string = set()\n len_set_of_string = len(set(str_))\n answer = float('inf')\n left = 0\n right = 0\n freq = defaultdict(int)\n while right < len(str_):\n freq[str_[right]] += 1\n while left <= right and len(freq) == len_set_of_string:\n answer = min(answer, right - left + 1)\n freq[str_[left]] -= 1\n if freq[str_[left]] == 0:\n del freq[str_[left]]\n left += 1\n right += 1\n return answer", "def findsubstring(a):\n dict = {}\n n = len(set(a))\n left = 0\n right = 0\n ans = len(a)\n while right < len(a):\n if a[right] not in dict:\n dict[a[right]] = 1\n else:\n dict[a[right]] += 1\n if len(dict) == n:\n while dict[a[left]] > 1:\n dict[a[left]] -= 1\n left += 1\n ans = min(ans, right - left + 1)\n right += 1\n return ans", "import math\n\ndef findsubstring(s):\n dicti = {}\n mini = math.inf\n k = len(set(s))\n n = len(s)\n (i, j) = (0, 0)\n while j < n:\n if s[j] not in dicti:\n dicti[s[j]] = 1\n else:\n dicti[s[j]] += 1\n if len(dicti) < k:\n j += 1\n elif len(dicti) == k:\n while len(dicti) == k:\n mini = min(mini, j - i + 1)\n if s[i] in dicti:\n dicti[s[i]] -= 1\n if dicti[s[i]] == 0:\n del dicti[s[i]]\n i += 1\n j += 1\n return mini", "from collections import defaultdict\n\ndef findsubstring(arr):\n dic = defaultdict(lambda : 0)\n i = 0\n j = 0\n n = len(set(arr))\n ans = len(arr)\n while j < len(arr):\n dic[arr[j]] += 1\n if len(dic) < n:\n j += 1\n if len(dic) == n:\n while dic[arr[i]] > 1:\n dic[arr[i]] -= 1\n i += 1\n ans = min(ans, j - i + 1)\n j += 1\n return ans", "def findsubstring(str):\n d = {}\n for i in str:\n d[i] = 0\n i = 0\n j = 0\n ans = len(str)\n count = len(d)\n temp = 0\n while j < len(str):\n while temp < count and j < len(str):\n if d[str[j]] == 0:\n temp += 1\n d[str[j]] += 1\n j += 1\n while temp >= count:\n d[str[i]] -= 1\n if d[str[i]] == 0:\n temp -= 1\n i += 1\n ans = min(ans, j - i + 1)\n return ans", "from collections import deque\n\ndef findsubstring(stre):\n s = set(stre)\n set_len = len(s)\n j = 0\n minlen = 1000000000.0\n mp = {}\n n = len(stre)\n for i in range(n):\n if stre[i] not in mp:\n mp[stre[i]] = 1\n else:\n mp[stre[i]] += 1\n while j <= i and len(mp) == set_len:\n if minlen > i - j + 1:\n minlen = i - j + 1\n mp[stre[j]] -= 1\n if mp[stre[j]] == 0:\n del mp[stre[j]]\n j += 1\n return minlen", "def findsubstring(str):\n m = {}\n n = len(set(str))\n length = float('inf')\n j = 0\n for i in range(len(str)):\n m[str[i]] = m.get(str[i], 0) + 1\n if len(m) == n:\n while m[str[j]] > 1:\n m[str[j]] -= 1\n j += 1\n length = min(length, i - j + 1)\n return length", "def findsubstring(str):\n dict = {}\n ans = 1000000000.0\n for i in str:\n if i not in dict:\n dict[i] = 1\n dict2 = {}\n j = 0\n for i in range(len(str)):\n if str[i] not in dict2:\n dict2[str[i]] = 1\n else:\n dict2[str[i]] += 1\n while len(dict) == len(dict2):\n ans = min(ans, i - j + 1)\n if dict2[str[j]] > 1:\n dict2[str[j]] -= 1\n elif dict2[str[j]] == 1:\n dict2.pop(str[j])\n j += 1\n return ans", "from collections import defaultdict\n\ndef findsubstring(s):\n a = set(s)\n i = 0\n t = {}\n min_len = float('inf')\n for j in range(len(s)):\n if s[j] not in t:\n t[s[j]] = 0\n t[s[j]] += 1\n while len(t) == len(a):\n min_len = min(min_len, j - i + 1)\n t[s[i]] -= 1\n if t[s[i]] == 0:\n del t[s[i]]\n i += 1\n return min_len", "def findsubstring(str):\n from collections import defaultdict\n curr_count = defaultdict(lambda : 0)\n dist_count = len(set([x for x in str]))\n if len(str) <= 1:\n return 1\n counter = 0\n start = 0\n min_len = len(str)\n for i in range(len(str)):\n curr_count[str[i]] += 1\n if curr_count[str[i]] == 1:\n counter += 1\n if counter == dist_count:\n while curr_count[str[start]] > 1:\n if curr_count[str[start]] > 1:\n curr_count[str[start]] -= 1\n start += 1\n window_len = i - start + 1\n if window_len < min_len:\n min_len = window_len\n start_index = start\n a = min_len\n return a", "def findsubstring(str):\n d = {}\n for i in str:\n if i not in d:\n d[i] = 0\n (i, j) = (0, float('inf'))\n (count, out) = (0, float('inf'))\n for j in range(len(str)):\n if d[str[j]] == 0:\n count += 1\n d[str[j]] += 1\n if count == len(d):\n while i < j:\n d[str[i]] -= 1\n if d[str[i]] == 0:\n out = min(out, j - i + 1)\n count -= 1\n i += 1\n break\n i += 1\n return out if out != float('inf') else 1", "def findsubstring(str):\n k = len(set(str))\n memo = {}\n ans = len(str)\n (i, j) = (0, 0)\n while j < len(str):\n memo[str[j]] = memo.get(str[j], 0) + 1\n if len(memo) < k:\n j += 1\n elif len(memo) == k:\n while len(memo) == k:\n memo[str[i]] -= 1\n if memo[str[i]] == 0:\n del memo[str[i]]\n i += 1\n ans = min(ans, j - i + 2)\n j += 1\n elif len(memo) > k:\n while len(memo) > k:\n memo[str[i]] -= 1\n if memo[str[i]] == 0:\n del memo[str[i]]\n i += 1\n j += 1\n return ans", "def findsubstring(str):\n res = 100000\n d = {}\n for i in range(len(str)):\n if str[i] not in d:\n d[str[i]] = 0\n s1 = set()\n count = len(d)\n l = 0\n for i in range(len(str)):\n s1.add(str[i])\n d[str[i]] = d[str[i]] + 1\n while count == len(s1) and d[str[l]] != 0:\n d[str[l]] = d[str[l]] - 1\n if d[str[l]] == 0:\n s1.remove(str[l])\n res = min(res, i - l + 1)\n l = l + 1\n return res", "def findsubstring(str):\n ans = len(str)\n N = len(str)\n n = len(set(str))\n (i, j) = (0, 0)\n d = {}\n while i < N:\n if str[i] not in d:\n d[str[i]] = 1\n else:\n d[str[i]] += 1\n if len(d) == n:\n while d[str[j]] > 1:\n d[str[j]] -= 1\n j += 1\n ans = min(ans, i - j + 1)\n i += 1\n return ans", "def findsubstring(s):\n freq = {}\n for c in s:\n freq[c] = 0\n unique_chars = len(freq)\n left = 0\n right = 0\n count = 0\n min_length = float('inf')\n while right < len(s):\n if s[right] in freq:\n freq[s[right]] += 1\n if freq[s[right]] == 1:\n count += 1\n right += 1\n while count == unique_chars:\n if right - left < min_length:\n min_length = right - left\n if s[left] in freq:\n freq[s[left]] -= 1\n if freq[s[left]] == 0:\n count -= 1\n left += 1\n return min_length", "def findsubstring(str):\n d = {}\n for i in str:\n if i not in d:\n d[i] = 0\n x = len(d)\n ans = 999999\n i = 0\n j = 0\n c = 0\n while i < len(str):\n if d[str[i]] == 0:\n c += 1\n d[str[i]] += 1\n if c == x:\n f = True\n while c == x:\n ans = min(ans, i - j + 1)\n d[str[j]] -= 1\n if d[str[j]] == 0:\n c -= 1\n j += 1\n i += 1\n return ans", "def findsubstring(str):\n reslen = len(str)\n s = set()\n d = dict()\n for i in range(len(str)):\n s.add(str[i])\n i = 0\n count = 0\n for j in range(len(str)):\n d[str[j]] = d.get(str[j], 0) + 1\n if d[str[j]] == 1:\n count += 1\n if count == len(s):\n while d[str[i]] > 1:\n if d[str[i]] > 1:\n d[str[i]] -= 1\n i += 1\n if reslen > j - i + 1:\n reslen = j - i + 1\n return reslen", "from collections import defaultdict\n\ndef findsubstring(strr):\n n = len(strr)\n dist_count = len(set([x for x in strr]))\n if n == dist_count:\n return n\n curr_count = dict()\n count = 0\n start = 0\n min_len = n\n for i in range(n):\n curr_count[strr[i]] = curr_count.get(strr[i], 0) + 1\n if curr_count[strr[i]] == 1:\n count += 1\n if count == dist_count:\n while curr_count[strr[start]] > 1:\n if curr_count[strr[start]] > 1:\n curr_count[strr[start]] -= 1\n start += 1\n if min_len > i - start + 1:\n min_len = i - start + 1\n return min_len", "def findsubstring(s):\n n = len(s)\n res = n\n i = 0\n uniq = set(list(s))\n found = {}\n for j in range(n):\n if s[j] in found:\n found[s[j]] += 1\n else:\n found[s[j]] = 1\n while i < j:\n if found[s[i]] > 1:\n found[s[i]] -= 1\n i += 1\n else:\n break\n if len(found) == len(uniq):\n res = min(res, j - i + 1)\n return res", "from collections import defaultdict\n\ndef findsubstring(s):\n n = len(s)\n if n <= 1:\n return len(s)\n dis_char = len(set(list(s)))\n curr = defaultdict(lambda : 0)\n cnt = 0\n minlen = n\n start = 0\n for j in range(n):\n curr[s[j]] += 1\n if curr[s[j]] == 1:\n cnt += 1\n if cnt == dis_char:\n while curr[s[start]] > 1:\n curr[s[start]] -= 1\n start += 1\n length = j - start + 1\n if length < minlen:\n minlen = length\n startind = start\n return minlen", "def findsubstring(S):\n distinct_chars = set(S)\n n = len(S)\n left = 0\n min_length = n\n count = [0] * 256\n distinct = 0\n for right in range(n):\n count[ord(S[right])] += 1\n if count[ord(S[right])] == 1:\n distinct += 1\n if distinct == len(distinct_chars):\n while count[ord(S[left])] > 1:\n count[ord(S[left])] -= 1\n left += 1\n min_length = min(min_length, right - left + 1)\n count[ord(S[left])] -= 1\n left += 1\n distinct -= 1\n return min_length", "def findsubstring(str):\n maxi = len(str)\n sets = set(str)\n i = 0\n j = 0\n m = {}\n while i < len(str):\n m[str[i]] = 1 + m.get(str[i], 0)\n if len(m) >= len(sets):\n while m[str[j]] > 1:\n m[str[j]] -= 1\n j += 1\n maxi = min(maxi, i - j + 1)\n i += 1\n return maxi", "def findsubstring(input_string):\n start = 0\n end = 1\n alphabet_dict = {}\n distinct_list = list(set(input_string))\n for i in range(0, len(distinct_list)):\n alphabet_dict[distinct_list[i]] = 0\n n = len(distinct_list)\n count = 1\n alphabet_dict[input_string[0]] = 1\n answer = len(input_string)\n while start <= end < len(input_string):\n if count < n:\n element = input_string[end]\n if alphabet_dict[element] == 0:\n alphabet_dict[element] = 1\n count = count + 1\n else:\n alphabet_dict[element] = alphabet_dict[element] + 1\n end = end + 1\n elif count == n:\n answer = min(answer, end - start)\n element = input_string[start]\n if element in alphabet_dict and alphabet_dict[element] == 1:\n count = count - 1\n alphabet_dict[element] = alphabet_dict[element] - 1\n start = start + 1\n while count == n:\n answer = min(answer, end - start)\n element = input_string[start]\n if element in alphabet_dict and alphabet_dict[element] == 1:\n count = count - 1\n alphabet_dict[element] = alphabet_dict[element] - 1\n start = start + 1\n return answer", "from collections import Counter\n\ndef findsubstring(str):\n dic1 = Counter(str)\n dic2 = dict()\n (i, j) = (0, 0)\n res = 10000000000\n while j < len(str):\n if str[j] in dic2:\n dic2[str[j]] += 1\n else:\n dic2[str[j]] = 1\n if len(dic1) == len(dic2):\n while len(dic1) == len(dic2):\n res = min(res, j - i + 1)\n dic2[str[i]] -= 1\n if dic2[str[i]] == 0:\n del dic2[str[i]]\n i += 1\n j += 1\n return res", "import math\n\ndef findsubstring(s):\n freq = {}\n for c in s:\n freq[c] = 0\n (b, d, ans) = (0, 0, math.inf)\n for (i, c) in enumerate(s):\n while d == len(freq.keys()):\n freq[s[b]] -= 1\n if freq[s[b]] == 0:\n ans = min(ans, i - b)\n d -= 1\n b += 1\n freq[c] += 1\n if freq[c] == 1:\n d += 1\n while d == len(freq.keys()):\n freq[s[b]] -= 1\n if freq[s[b]] == 0:\n ans = min(ans, i - b + 1)\n d -= 1\n b += 1\n return ans", "def findsubstring(str):\n n = len(str)\n ans = 0\n length = n\n s = list(set(str))\n d = dict()\n count = 0\n start = 0\n for i in range(n):\n if str[i] not in d.keys():\n d[str[i]] = 1\n count += 1\n else:\n d[str[i]] += 1\n if count == len(s):\n while d[str[start]] > 1:\n d[str[start]] -= 1\n start += 1\n ans = i - start + 1\n if length > ans:\n length = ans\n return length", "from collections import defaultdict\n\ndef findsubstring(s):\n control = set(s)\n m = len(control)\n n = len(s)\n test = defaultdict(lambda : 0)\n mini = float('inf')\n i = 0\n for j in range(n):\n while len(test) < m and i < n:\n test[s[i]] += 1\n i += 1\n if len(test) < m:\n break\n mini = min(mini, i - j)\n test[s[j]] -= 1\n if test[s[j]] == 0:\n del test[s[j]]\n return mini", "def findsubstring(str):\n i = 0\n j = 0\n s = len(set(str))\n n = len(str)\n ans = n\n dic = {}\n while i < n:\n if str[i] not in dic:\n dic[str[i]] = 1\n else:\n dic[str[i]] += 1\n if len(dic) == s:\n while dic[str[j]] > 1:\n dic[str[j]] -= 1\n j += 1\n ans = min(ans, i - j + 1)\n i += 1\n return ans", "def findsubstring(s):\n n = len(s)\n distinct_chars = len(set(s))\n freq = [0] * 256\n left = 0\n right = 0\n count = 0\n min_len = n\n while right < n:\n ch = ord(s[right])\n if freq[ch] == 0:\n count += 1\n freq[ch] += 1\n right += 1\n while count == distinct_chars:\n min_len = min(min_len, right - left)\n ch = ord(s[left])\n freq[ch] -= 1\n if freq[ch] == 0:\n count -= 1\n left += 1\n return min_len", "def findsubstring(str):\n nd = len(set(str))\n i = 0\n j = 0\n res = len(str)\n dic = {}\n while i < len(str):\n if str[i] in dic:\n dic[str[i]] = dic[str[i]] + 1\n else:\n dic[str[i]] = 1\n if len(dic) == nd:\n while dic[str[j]] > 1:\n dic[str[j]] = dic[str[j]] - 1\n j = j + 1\n res = min(res, i - j + 1)\n i = i + 1\n return res", "from collections import Counter\n\ndef findsubstring(str1):\n dict1 = dict()\n count = 0\n distinct = len(Counter(str1))\n n = len(str1)\n j = 0\n minimum = n\n for i in range(n):\n if count < distinct:\n while j < n:\n if str1[j] not in dict1:\n dict1[str1[j]] = 1\n count += 1\n else:\n dict1[str1[j]] += 1\n if count == distinct:\n j += 1\n break\n j += 1\n if count == distinct:\n minimum = min(minimum, j - i)\n dict1[str1[i]] -= 1\n if dict1[str1[i]] == 0:\n dict1.pop(str1[i])\n count -= 1\n return minimum", "def findsubstring(a):\n s = ''\n a1 = {}\n for i in a:\n a1[i] = 1\n c1 = len(a1)\n i = 0\n j = 0\n a2 = {}\n c = 0\n res = len(a)\n while j < len(a):\n if a[j] not in a2:\n a2[a[j]] = 0\n c += 1\n a2[a[j]] += 1\n while i <= j and c == c1:\n res = min(res, j - i + 1)\n a2[a[i]] -= 1\n if a2[a[i]] == 0:\n del a2[a[i]]\n c -= 1\n i += 1\n j += 1\n return res", "def findsubstring(str):\n ans_len = len(set(str))\n d = {}\n ws = 0\n ans = 10 ** 6\n for we in range(0, len(str)):\n d[str[we]] = d.get(str[we], 0) + 1\n if len(d) == ans_len:\n while d[str[ws]] > 1:\n d[str[ws]] -= 1\n ws += 1\n ans = min(ans, we - ws + 1)\n return ans", "def findsubstring(str):\n unique = set(str)\n res = len(str)\n j = 0\n map = dict()\n for i in range(0, len(str)):\n if str[i] in map.keys():\n map[str[i]] += 1\n else:\n map[str[i]] = 1\n if len(unique) == len(map):\n while map[str[j]] > 1:\n map[str[j]] -= 1\n j += 1\n res = min(res, i - j + 1)\n return res", "def findsubstring(str):\n l = len(str)\n s = set()\n for i in range(len(str)):\n s.add(str[i])\n n = len(s)\n head = 0\n tail = 0\n hmap = {}\n ans = l\n while head < l:\n if str[head] in hmap:\n hmap[str[head]] += 1\n else:\n hmap[str[head]] = 1\n if len(hmap) == n:\n while hmap[str[tail]] > 1:\n hmap[str[tail]] -= 1\n tail += 1\n ans = min(ans, head - tail + 1)\n head += 1\n return ans", "from collections import defaultdict, Counter\nfrom sys import maxsize\n\ndef findsubstring(str):\n cnt = Counter(str)\n cur = defaultdict(int)\n k = 0\n ans = maxsize\n i = 0\n for (j, ch) in enumerate(str):\n cur[ch] += 1\n if cur[ch] == 1:\n k += 1\n if k == len(cnt):\n while i < j:\n if cur[str[i]] == 1:\n break\n cur[str[i]] -= 1\n i += 1\n ans = min(ans, j - i + 1)\n return ans", "def findsubstring(str):\n res = float('inf')\n (i, j) = (0, 0)\n maxLen = len(set(list(str)))\n hashmap = {}\n while j < len(str):\n if str[j] not in hashmap:\n hashmap[str[j]] = 1\n else:\n hashmap[str[j]] += 1\n j += 1\n if len(hashmap) == maxLen:\n while i < j and hashmap[str[i]] > 1:\n hashmap[str[i]] -= 1\n i += 1\n res = min(res, j - i)\n return res", "def findsubstring(str):\n d = {}\n for ch in str:\n if ch not in d:\n d[ch] = 1\n n = len(d)\n d.clear()\n i = 0\n j = 0\n count = 0\n mini = len(str)\n while j < len(str):\n if str[j] not in d:\n d[str[j]] = 1\n count = count + 1\n else:\n d[str[j]] = d[str[j]] + 1\n if count == n:\n while d[str[i]] != 1:\n d[str[i]] = d[str[i]] - 1\n i = i + 1\n mini = min(mini, j - i + 1)\n j = j + 1\n return mini", "def findsubstring(s):\n n = len(s)\n d = {}\n count = 0\n for i in range(n):\n d[s[i]] = 0\n i = 0\n j = 0\n ans = n\n while i < n:\n if d[s[i]] == 0:\n count += 1\n d[s[i]] += 1\n if count == len(d):\n while j < n and d[s[j]] > 1:\n d[s[j]] -= 1\n j += 1\n if ans > i - j + 1:\n ans = i - j + 1\n i += 1\n return ans", "def findsubstring(str):\n p = len(set(str))\n j = 0\n i = 0\n d = {}\n mn = 100000\n while j < len(str):\n if str[j] in d:\n d[str[j]] += 1\n else:\n d[str[j]] = 1\n if len(d) == p:\n while len(d) == p:\n mn = min(mn, j - i + 1)\n d[str[i]] -= 1\n if d[str[i]] == 0:\n del d[str[i]]\n i += 1\n j += 1\n return mn", "def findsubstring(str):\n d = {}\n i = 0\n j = 0\n sw = 100000000\n n = len(set(str))\n while j < len(str):\n if str[j] not in d:\n d[str[j]] = 1\n else:\n d[str[j]] += 1\n if len(d) == n:\n while len(d) == n:\n sw = min(sw, j - i + 1)\n d[str[i]] -= 1\n if d[str[i]] == 0:\n del d[str[i]]\n i += 1\n j += 1\n return sw", "def findsubstring(str):\n dict = {}\n for i in str:\n if i in dict:\n dict[i] += 1\n else:\n dict[i] = 1\n count = len(list(dict.keys()))\n i = j = 0\n ans = len(str)\n c = 0\n dict = {}\n for i in range(len(str)):\n if str[i] in dict:\n dict[str[i]] += 1\n else:\n dict[str[i]] = 1\n c += 1\n if c == count:\n ans = min(ans, i - j + 1)\n while c == count and j <= i:\n dict[str[j]] -= 1\n if dict[str[j]] == 0:\n del dict[str[j]]\n c -= 1\n ans = min(ans, i - j + 1)\n j += 1\n return ans", "def findsubstring(str):\n s = set(str)\n n = len(s)\n ss = set()\n ind = 0\n d = {}\n mini = 10 ** 9\n for i in range(len(str)):\n if str[i] not in ss:\n ss.add(str[i])\n d[str[i]] = d.get(str[i], 0) + 1\n if len(ss) == n:\n ind = i + 1\n mini = min(mini, i + 1)\n break\n index = 0\n while d[str[index]] > 1:\n d[str[index]] -= 1\n index += 1\n mini = min(mini, i - index + 1)\n for i in range(ind, len(str)):\n d[str[i]] = d.get(str[i], 0) + 1\n while d[str[index]] > 1:\n d[str[index]] -= 1\n index += 1\n mini = min(mini, i - index + 1)\n while d[str[index]] > 1:\n d[str[index]] -= 1\n index += 1\n mini = min(mini, i - index + 1)\n return mini"], "starter_code": "def findsubstring(str):\n", "input_output": {"inputs": ["\"AABBBCBBAC\"", "\"aaab\"", "\"GEEKSGEEKSFOR\""], "outputs": ["3", "2", "8"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Hash", "sliding-window", "Strings", "Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures", "Amortized analysis"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/smallest-distant-window3132/1", "Expected Auxiliary Space": "O(256)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(256.N)", "entry_point": "findsubstring", "task_id": "TACO_lite/2", "example": [[["AABBBCBBAC"], ["aaab"], ["GEEKSGEEKSFOR"]], ["3", "2", "8"]]} +{"requirement": "Your car is old, it breaks easily. The shock absorbers are gone and you think it can handle about 15 more bumps before it dies totally.\n\nUnfortunately for you, your drive is very bumpy! Given a string showing either flat road (\"\\_\") or bumps (\"n\"), work out if you make it home safely. 15 bumps or under, return \"Woohoo!\", over 15 bumps return \"Car Dead\".", "solutions": ["def bumps(road):\n return 'Woohoo!' if road.count('n') <= 15 else 'Car Dead'", "def bumps(road):\n return 'Woohoo!' if road.count('n') < 16 else 'Car Dead'", "from collections import Counter\n\ndef bumps(road):\n return 'Car Dead' if Counter(road)['n'] > 15 else 'Woohoo!'", "import re\n\ndef bumps(road):\n return 'Woohoo!' if len(re.findall('n', road)) < 16 else 'Car Dead'", "def bumps(road):\n MAX_BUMPS = 15\n SUCCESS_MESSAGE = 'Woohoo!'\n ERROR_MESSAGE = 'Car Dead'\n return SUCCESS_MESSAGE if road.count('n') <= MAX_BUMPS else ERROR_MESSAGE", "bumps = lambda road: 'CWaoro hDoeoa!d'[road.count('n') < 16::2]", "def bumps(road):\n return ('Woohoo!', 'Car Dead')[road.count('n') > 15]", "def bumps(road):\n track = 0\n for el in road:\n if el == 'n':\n track += 1\n if track > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n a = 0\n for i in road:\n if i == 'n':\n a += 1\n if a > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n bumps = 0\n for c in road:\n if c == 'n':\n bumps += 1\n if bumps <= 15:\n return 'Woohoo!'\n else:\n return 'Car Dead'", "def bumps(road):\n L = list(road)\n C = L.count('n')\n if C > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n commute = road\n bumps = commute.count('n')\n condition_1 = bumps < 16\n condition_2 = bumps >= 16\n if condition_1:\n return 'Woohoo!'\n if condition_2:\n return 'Car Dead'", "def bumps(road):\n return 'Car Dead' if len([r for r in road if r is 'n']) > 15 else 'Woohoo!'\n\ndef best_practice_bumps(road):\n return 'Woohoo!' if road.count('n') <= 15 else 'Car Dead'", "def bumps(road):\n x = road.count('n')\n results = ['Woohoo!', 'Car Dead']\n if x > 15:\n return results[1]\n else:\n return results[0]", "def bumps(road):\n c = road.count('n')\n if c > 15:\n return 'Car Dead'\n return 'Woohoo!'", "def bumps(road):\n bumps = road.count('n')\n if bumps > 15:\n return 'Car Dead'\n elif bumps <= 15:\n return 'Woohoo!'", "def bumps(road):\n k = list(road)\n count = 0\n for word in k:\n if word == 'n':\n count += 1\n if count < 16:\n return 'Woohoo!'\n else:\n return 'Car Dead'", "def bumps(s):\n return 'Woohoo!' if s.count('n') < 16 else 'Car Dead'", "def bumps(road):\n count = 0\n for i in road:\n if i == 'n':\n count += 1\n if count <= 15:\n return 'Woohoo!'\n return 'Car Dead'", "def bumps(road):\n bumps = [x for x in road if x == 'n']\n if len(bumps) > 15:\n return 'Car Dead'\n return 'Woohoo!'", "bumps = lambda s: 'Woohoo!' if s.count('n') < 16 else 'Car Dead'", "def bumps(road):\n count = 0\n for char in road:\n if char == 'n':\n count += 1\n if count > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n list(road)\n bump_counter = 0\n for bump in road:\n if bump == 'n':\n bump_counter += 1\n if bump_counter <= 15:\n return 'Woohoo!'\n else:\n return 'Car Dead'", "def bumps(road):\n bumps = 0\n for i in range(len(road)):\n if road[i] == 'n':\n bumps += 1\n if bumps > 15:\n return 'Car Dead'\n return 'Woohoo!'", "def bumps(s):\n return 'Woohoo!' if s.count('n') <= 15 else 'Car Dead'", "def bumps(road):\n count = 0\n for x in road:\n if x is 'n':\n count = count + 1\n if count > 15:\n x = 'Car Dead'\n else:\n x = 'Woohoo!'\n return x", "def bumps(road):\n x = 0\n for spot in road:\n if spot == 'n':\n x += 1\n else:\n continue\n if x > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n (cnt1, cnt2) = (0, 0)\n for c in road:\n if c == '_':\n cnt1 += 1\n elif c == 'n':\n cnt2 += 1\n if cnt2 > 15:\n return 'Car Dead'\n return 'Woohoo!'", "f1 = lambda x: 1 if x == 'n' else 0\nf2 = lambda x: 'Woohoo!' if x <= 15 else 'Car Dead'\n\ndef bumps(road):\n return f2(sum((f1(x) for x in road)))", "def bumps(road):\n ncount = 0\n a = [char for char in road]\n for i in range(len(a)):\n if a[i] == 'n':\n ncount += 1\n if ncount > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n flat = []\n bump = []\n for letter in road:\n if letter is '_':\n flat.append(letter)\n else:\n bump.append(letter)\n if len(bump) <= 15:\n return 'Woohoo!'\n else:\n return 'Car Dead'", "def bumps(road):\n bumps = 0\n for letter in road:\n if letter == 'n' or letter == 'N':\n bumps += 1\n elif letter == '_':\n continue\n else:\n continue\n if bumps > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n bumps = 0\n for letter in road:\n if letter == 'n':\n bumps += 1\n continue\n else:\n continue\n if bumps > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n nr_bumps = 0\n for c in road:\n if c == 'n':\n nr_bumps += 1\n return 'Woohoo!' if nr_bumps < 16 else 'Car Dead'", "def bumps(road):\n a = 0\n for char in road:\n if str(char) == 'n':\n a += 1\n if a <= 15:\n return 'Woohoo!'\n if a > 15:\n return 'Car Dead'", "def bumps(road):\n counter = 0\n for i in road:\n if i == 'n':\n counter += 1\n continue\n return 'Woohoo!' if counter <= 15 else 'Car Dead'", "def bumps(road):\n return 'Car Dead' if ''.join(sorted(road, reverse=True)[0:16]) == 'nnnnnnnnnnnnnnnn' else 'Woohoo!'", "def bumps(road):\n x = road.count('n')\n if x <= 15:\n return 'Woohoo!'\n return 'Car Dead'", "def bumps(road):\n roadList = list(road)\n speedBumps = 'n'\n bumpCount = 0\n for i in roadList:\n if i == 'n':\n bumpCount += 1\n if bumpCount > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n return 'Woohoo!' if len(list(filter(lambda x: x == 'n', road))) <= 15 else 'Car Dead'", "def bumps(road):\n list = [road]\n a = 0\n for x in road:\n if x == 'n':\n a = a + 1\n if a > 15:\n return 'Car Dead'\n return 'Woohoo!'", "def bumps(road):\n countN = 0\n countUnderscore = 0\n listletters = [char for char in road]\n for i in listletters:\n if i == 'n':\n countN += 1\n else:\n countUnderscore += 1\n if countN > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n bump = 0\n for s in road:\n if s == 'n':\n bump += 1\n return 'Woohoo!' if bump <= 15 else 'Car Dead'", "def bumps(road):\n return 'Car Dead' if len(list(filter(str.isalpha, road))) > 15 else 'Woohoo!'", "def bumps(road):\n bumps = 0\n for i in road:\n if i == '_':\n pass\n elif i == 'n':\n bumps += 1\n if bumps > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n dead = 0\n for x in road:\n if x == 'n':\n dead += 1\n if dead > 15:\n return 'Car Dead'\n else:\n return 'Woohoo!'", "def bumps(road):\n count = 0\n for each in road:\n if each == 'n':\n count += 1\n if count > 15:\n return 'Car Dead'\n elif count <= 15:\n return 'Woohoo!'", "def bumps(road):\n road_list = list(road)\n bump_number = 0\n for segment in road_list:\n if segment == 'n':\n bump_number += 1\n if bump_number <= 15:\n return 'Woohoo!'\n else:\n return 'Car Dead'", "def bumps(road):\n n = [x for x in road if x == 'n'].count('n')\n return 'Woohoo!' if n <= 15 else 'Car Dead'", "def bumps(road):\n sum = 0\n for i in road:\n if i is 'n':\n sum += 1\n if sum > 15:\n return 'Car Dead'\n return 'Woohoo!'", "def bumps(road):\n return 'Woohoo!' if len(road.split('n')) <= 16 else 'Car Dead'", "bumps = lambda road: 'Woohoo!' if road.count('n') < 16 else 'Car Dead'", "def bumps(road):\n b = 0\n for x in road:\n if x == 'n':\n b = b + 1\n if b < 15:\n return 'Woohoo!'\n elif b == 15:\n return 'Woohoo!'\n else:\n return 'Car Dead'", "def bumps(road):\n num_bumps = road.count('n')\n if num_bumps > 15:\n return 'Car Dead'\n return 'Woohoo!'", "def bumps(road):\n lista = list(road)\n bumps = 0\n for i in lista:\n if i == 'n':\n bumps += 1\n if bumps <= 15:\n return 'Woohoo!'\n else:\n return 'Car Dead'"], "starter_code": "def bumps(road):\n", "input_output": {"fn_name": "bumps", "inputs": [["n"], ["_nnnnnnn_n__n______nn__nn_nnn"], ["______n___n_"], ["nnnnnnnnnnnnnnnnnnnnn"]], "outputs": [["Woohoo!"], ["Car Dead"], ["Woohoo!"], ["Car Dead"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/57ed30dde7728215300005fa", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "bumps", "task_id": "TACO_lite/56", "example": [[], []]} +{"requirement": "# Exclusive \"or\" (xor) Logical Operator\n\n## Overview\n\nIn some scripting languages like PHP, there exists a logical operator (e.g. ```&&```, ```||```, ```and```, ```or```, etc.) called the \"Exclusive Or\" (hence the name of this Kata). The exclusive or evaluates two booleans. It then returns true if **exactly one of the two expressions are true**, false otherwise. For example:\n\n## Task\n\nSince we cannot define keywords in Javascript (well, at least I don't know how to do it), your task is to define a function ```xor(a, b)``` where a and b are the two expressions to be evaluated. Your ```xor``` function should have the behaviour described above, returning true if **exactly one of the two expressions evaluate to true**, false otherwise.", "solutions": ["def xor(a, b):\n return a != b", "from operator import xor", "def xor(a, b):\n return a is not b", "xor = int.__xor__", "xor = lambda a, b: a != b", "xor = __import__('operator').__xor__", "def xor(a, b):\n return False if a and b else a or b", "def xor(a, b):\n return len(set([a, b])) > 1", "xor = lambda *_: _[0] ^ _[1]", "xor = bool.__xor__", "def xor(a, b):\n return bool((a + b) % 2)", "def xor(a, b):\n if a == True and b == True:\n return False\n if a == True and b == False:\n return True\n if a == True and b == True:\n return True\n if a == False and b == False:\n return False\n else:\n return True", "def xor(a, b):\n return abs(a - b)", "def xor(a, b):\n if a == b:\n return False\n elif a != b or b != a:\n return True", "def xor(a, b):\n truCount = 0\n if a:\n truCount += 1\n if b:\n truCount += 1\n if truCount == 1:\n return True\n return False", "def xor(a, b):\n result = a ^ b\n return result", "def xor(a, b):\n if a == b:\n return False\n return True if a or b == True else False", "def xor(a, b):\n if a == b:\n return False\n elif a == True and b == False:\n return True\n elif a == False and b == True:\n return True", "def xor(a, b):\n c = 0\n n = str(a).count('True')\n m = str(b).count('True')\n c = n + m\n return c % 2 != 0", "def xor(a, b):\n return (a == True or a == False) and a != b", "def xor(a, b):\n return a != b and max(a, b) == True", "def xor(a, b):\n if a is True and b is True:\n return False\n elif a is False and b is False:\n return False\n else:\n return True", "def xor(a, b):\n if a is True and b is False or (b is True and a is False):\n return True\n else:\n return False", "def xor(a, b):\n count = 0\n if a == True:\n count += 1\n if b == True:\n count += 1\n if a != True:\n count -= 1\n if b != True:\n count -= 1\n if count == 0:\n return True\n return False", "xor = lambda a, b: True if not a and b or (a and (not b)) else False", "def xor(a, b):\n a = [a]\n b = [b]\n return sum(a + b) == 1", "def xor(a, b):\n if a is b:\n return False\n else:\n return a or b", "def xor(a, b):\n if a and b == True:\n return False\n elif a or b == True:\n return True\n else:\n False\n return False", "def xor(a, b):\n if not a:\n if b:\n return True\n else:\n return False\n elif not b:\n if a:\n return True\n else:\n return False\n else:\n return False", "def xor(a, b):\n return (1 - a + (1 - b)) % 2 == 1", "def xor(a, b):\n j = False\n if a != b:\n j = True\n return j", "def xor(a, b):\n if a is True:\n if b is True:\n return False\n if a is False:\n if b is False:\n return False\n if b is True:\n if a is True:\n return False\n if b is False:\n if a is False:\n return False\n if a is True:\n if b is False:\n return True\n if b is True:\n if a is False:\n return True", "def xor(a, b):\n if int(a + b) == 0:\n return False\n elif int(a + b) == 1:\n return True\n elif int(a + b) == 2:\n return False", "def xor(a, b):\n x = int(a)\n y = int(b)\n return a ^ b", "def xor(a, b):\n if a == False and b == False:\n return False\n elif a == True and b == True:\n return not a\n return a or b", "xor = lambda x, y: x is not y", "def xor(a, b):\n return (a is b) is False", "def xor(a, b):\n return not (not (a or b) or (a and b))", "def xor(a, b):\n my_bool = True\n if a and b:\n return False\n elif a == False and b == False:\n return False\n elif a or b:\n return True", "def xor(a, b):\n if a:\n if b:\n return False\n return a or b", "def xor(a, b):\n if a is not b:\n return True\n else:\n return False", "def xor(a, b):\n return a + b < 2 and a + b > 0", "def xor(a, b):\n answer = 0\n if a == True:\n answer += 1\n if b == True:\n answer += 1\n if answer == 1:\n return True\n else:\n return False", "xor = lambda a, b: int(a) ^ int(b)", "xor = lambda a, b: int(a) + int(b) == 1", "from operator import xor as xor_\nfrom functools import reduce\n\ndef xor(a, b):\n return reduce(xor_, (a, b))", "xor = lambda a, b: a + b == 1", "def xor(a, b):\n c = 0\n if a:\n c += 1\n if b:\n c += 1\n if c == 1:\n return True\n else:\n return False", "from operator import xor as xor1\n\ndef xor(a, b):\n return xor1(a, b)", "def xor(a, b):\n result = True\n if a == True and b == True:\n result = False\n elif a == True and b == False or (b == True and a == False):\n result = True\n elif a == False and b == False:\n result = False\n return result", "def xor(a, b):\n return (False, True)[a != b]"], "starter_code": "def xor(a,b):\n", "input_output": {"fn_name": "xor", "inputs": [[false, false], [true, false], [false, true], [true, true]], "outputs": [[false], [true], [true], [false]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56fa3c5ce4d45d2a52001b3c", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "xor", "task_id": "TACO_lite/92", "example": [[], []]} +{"requirement": "Given an array arr[] of N integers, the task is to find a subsequence of size K whose product is maximum among all possible K sized subsequences of a given array.\nExample 1:\nInput: N = 4, K = 2\narr[] = {1, 2, 0, 3} \nOutput: 6\nExplanation: Subsequence containing \nelements {2, 3} gives maximum product: \n2*3 = 6\nExample 2:\nInput: N = 6, K = 4\narr[] = {1, 2, -1, -3, -6, 4}\nOutput: 144\nExplanation: Subsequence containing \n{2, -3, -6, 4} gives maximum product: \n2*(-3)*(-6)*4 = 144\nYour Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function maxProductSubarrayOfSizeK() that takes array arr[], integer N and integer K as parameters and returns the desired product.\n \nExpected Time Complexity: O(NlogN).\nExpected Auxiliary Space: O(1).\n \nConstraints:\n1 \u2264 N \u2264 10^{5}", "solutions": ["def maxproductsubarrayofsizek(arr, n, k):\n product = 1\n arr.sort()\n if k % 2 and arr[-1] < 0:\n for _ in range(k):\n product *= arr.pop()\n return product\n if k % 2:\n product *= arr.pop()\n k -= 1\n while k:\n if arr[0] * arr[1] > arr[-1] * arr[-2]:\n product *= arr.pop(0) * arr.pop(0)\n else:\n product *= arr.pop() * arr.pop()\n k -= 2\n return product", "def maxproductsubarrayofsizek(arr, n, k):\n arr.sort()\n if k == 1:\n return arr[-1]\n if arr[-1] == 0:\n return 0\n arr_len = len(arr)\n if k % 2 == 0:\n remainder = 0\n even_k = k\n else:\n remainder = 1\n even_k = k - 1\n i = 0\n j = len(arr) - 1\n subsequence = [None] * k\n subsequence_index = 0\n prod = 1\n if arr[-1] < 0:\n if not remainder:\n for i in range(0, k):\n subsequence[subsequence_index] = i\n subsequence_index += 1\n prod *= arr[i]\n else:\n for i in range(arr_len - k, arr_len):\n subsequence[subsequence_index] = i\n subsequence_index += 1\n prod *= arr[i]\n return prod\n subsequence_lenght = 0\n max_prod = 1\n if remainder:\n subsequence[-1] = j\n j -= 1\n while subsequence_lenght < even_k:\n if arr[i] * arr[i + 1] > arr[j] * arr[j - 1]:\n subsequence[i] = i\n subsequence[i + 1] = i + 1\n max_prod *= arr[i] * arr[i + 1]\n i += 2\n else:\n subsequence[k - (arr_len - j)] = j\n subsequence[k - (arr_len - j) - 1] = j - 1\n j -= 2\n max_prod *= arr[j] * arr[j - 1]\n subsequence_lenght += 2\n max_prod2 = 1\n for item in subsequence:\n max_prod2 *= arr[item]\n return max_prod2", "def maxproductsubarrayofsizek(arr, n, k):\n ans = 1\n arr.sort()\n if arr[n - 1] == 0 and k & 1:\n return 0\n if arr[n - 1] < 0 and k & 1:\n temp = 1\n i = n - 1\n while i >= n - k:\n temp *= arr[i]\n i -= 1\n return temp\n (i, j) = (0, n - 1)\n if arr[j] > 0 and k & 1:\n ans *= arr[j]\n k -= 1\n j -= 1\n while i <= j and k:\n p1 = arr[i] * arr[i + 1]\n p2 = arr[j] * arr[j - 1]\n if p1 > p2:\n ans *= p1\n i += 2\n k -= 2\n else:\n ans *= p2\n j -= 2\n k -= 2\n return ans", "def maxproductsubarrayofsizek(arr, n, k):\n arr.sort()\n ma = max(arr)\n if k % 2 == 0:\n p = 1\n l = 0\n r = n - 1\n for j in range(k // 2):\n a = arr[l] * arr[l + 1]\n b = arr[r] * arr[r - 1]\n if a >= b:\n p *= a\n l += 2\n else:\n p *= b\n r -= 2\n elif ma < 0:\n arr.sort(reverse=True)\n lst = arr[:k]\n p = 1\n for j in lst:\n p *= j\n elif ma == 0:\n p = 0\n else:\n p = ma\n k -= 1\n l = 0\n arr = arr[:n - 1]\n r = n - 2\n for j in range(k // 2):\n a = arr[l] * arr[l + 1]\n b = arr[r] * arr[r - 1]\n if a >= b:\n p *= a\n l += 2\n else:\n p *= b\n r -= 2\n return p", "def maxproductsubarrayofsizek(arr, n, k):\n arr.sort()\n A = arr\n A.sort()\n product = 1\n if A[n - 1] == 0 and k & 1:\n return 0\n if A[n - 1] <= 0 and k & 1:\n i = n - 1\n while k > 0:\n product *= A[i]\n k -= 1\n i -= 1\n return product\n i = 0\n j = n - 1\n if k & 1:\n product *= A[j]\n j -= 1\n k -= 1\n k >>= 1\n for itr in range(k):\n left_product = A[i] * A[i + 1]\n right_product = A[j] * A[j - 1]\n if left_product > right_product:\n product *= left_product\n i += 2\n else:\n product *= right_product\n j -= 2\n return product"], "starter_code": "def maxproductsubarrayofsizek(arr, n, k):\n", "input_output": {"inputs": ["N = 4, K = 2\narr[] = {1, 2, 0, 3}", "N = 6, K = 4\narr[] = {1, 2, -1, -3, -6, 4}"], "outputs": ["6", "144"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/maximum-product4633/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(NlogN).", "entry_point": "maxproductsubarrayofsizek", "task_id": "TACO_lite/62", "example": [[[4, 2, [1, 2, 0, 3]], [6, 4, [1, 2, -1, -3, -6, 4]]], [null, null]]} +{"requirement": "Given two integers X and K. The task is to find smallest K-digit number divisible by X.\nNote: It is given that number of digits in X is always smaller or equal to K.\n \nExample 1:\nInput:\nX = 6, K = 1\nOutput:\n6\nExplanation:\n6 is the smallest 1 digit number\nwhich is divisible by 6.\nExample 2:\nInput:\nX = 5, K = 2\nOutput:\n10\nExplanation:\n10 is the smallest 2 digit number\nwhich is divisible by 5.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function smallestKDigitNum() which takes 2 Integers X and K as input and returns the answer.\n \nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= X <= 10^{5}\n1 <= K <= 18", "solutions": ["def smallestkdigitnum(X, K):\n Min = pow(10, K - 1)\n if Min % X == 0:\n return Min\n else:\n return Min + X - (Min + X) % X", "import math\n\ndef smallestkdigitnum(X, K):\n min = pow(10, K - 1)\n if min % X == 0:\n return min\n else:\n return min + X - (min + X) % X", "def smallestkdigitnum(X, K):\n if K == 1:\n return X\n x = K - 1\n l = pow(10, x)\n if l % X == 0:\n return l\n l += X\n return l - l % X", "def smallestkdigitnum(X, K):\n value = 10 ** (K - 1)\n if value % X == 0:\n return value\n return value + X - value % X", "def smallestkdigitnum(X, K):\n k_digit_num = int('1' + '0' * (K - 1))\n rem = k_digit_num % X\n if rem != 0:\n return k_digit_num + X - rem\n else:\n return k_digit_num", "def smallestkdigitnum(X, K):\n if K == 1:\n return X\n temp = '1' + '0' * (K - 1)\n high = '9' + '9' * (K - 1)\n temp = int(temp)\n high = int(high)\n t = temp // X\n if X * t == temp:\n return temp\n else:\n return X * (t + 1)", "def smallestkdigitnum(X, K):\n t = 10 ** (K - 1)\n d = t % X\n if d != 0:\n t += X - d\n return t", "def smallestkdigitnum(X, K):\n mn = pow(10, K - 1)\n if mn % X == 0:\n return mn\n return mn + X - (mn + X) % X", "def smallestkdigitnum(X, K):\n num = 10 ** (K - 1)\n return num if num % X == 0 else num + X - num % X", "def smallestkdigitnum(x, k):\n p = 10 ** (k - 1)\n if p % x == 0:\n return p\n l = p + x - (p + x) % x\n return l"], "starter_code": "def smallestkdigitnum(X, K):\n", "input_output": {"inputs": ["X = 6, K = 1", "X = 5, K = 2"], "outputs": ["6", "10"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Numbers", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/smallest-k-digit-number-divisible-by-x2351/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "smallestkdigitnum", "task_id": "TACO_lite/76", "example": [[[6, 1], [5, 2]], ["6", "10"]]} +{"requirement": "Given two strings S and T, find length of the shortest subsequence in S which is not a subsequence in T. If no such subsequence is possible, return -1. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. A string of length n has different possible subsequences.\n \nExample 1:\nInput:\nS = \"babab\"\nT = \"babba\"\nOutput:\n3\nExplanation:\nThere are no subsequences of S with\nlength less than 3 which is not a\nsubsequence of T. \"aab\" is an example of\na subsequence of length 3 which isn't a\nsubsequence of T.\nExample 2:\nInput:\nS = \"babhi\"\nT = \"babij\"\nOutput:\n1\nExplanation:\n\"h\" is a subsequence of S that is\nnot a subsequence of T.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function shortestUnSub() which takes two Strings S, and T as input and returns the shortest Uncommon Subsequence.\n \nExpected Time Complexity: O(|S|^{2}*|T|)\nExpected Auxiliary Space: O(|S|*|T|)\n \nConstraints:\n1 <= |S|, |T| <= 500", "solutions": ["def __init__():\n self.indices = {}\n\ndef shortestunsub(S, T):\n m = len(S)\n n = len(T)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n for i in range(n + 1):\n dp[0][i] = 501\n for i in range(1, m + 1):\n dp[i][0] = 1\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n k = j - 1\n ch = S[i - 1]\n if ch == T[k]:\n self.indices[ch] = k\n elif ch in self.indices:\n k = self.indices[ch]\n else:\n while k >= 0:\n if T[k] == S[i - 1]:\n break\n k -= 1\n self.indices[ch] = k\n if k == -1:\n dp[i][j] = 1\n else:\n dp[i][j] = min(dp[i - 1][j], 1 + dp[i - 1][k])\n ans = dp[i][j]\n if ans >= 501:\n ans = -1\n return ans", "def shortestunsub(S, T):\n (m, n) = (len(S), len(T))\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n for i in range(m + 1):\n dp[i][0] = 1\n for i in range(n + 1):\n dp[0][i] = float('inf')\n for i in range(m):\n for j in range(n):\n k = T[:j + 1].rfind(S[i])\n if k == -1:\n dp[i + 1][j + 1] = 1\n else:\n dp[i + 1][j + 1] = min(dp[i][j + 1], dp[i][k] + 1)\n return -1 if dp[m][n] == float('inf') else dp[m][n]", "def __init__():\n self.index = {}\n\ndef shortestunsub(S, T):\n n = len(S)\n m = len(T)\n maxx = 501\n dp = [[0] * (m + 1) for i in range(n + 1)]\n for i in range(1, n + 1):\n dp[i][0] = 1\n for j in range(m + 1):\n dp[0][j] = maxx\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n k = j - 1\n p = S[i - 1]\n if p == T[k]:\n self.index[p] = k\n elif p in self.index:\n k = self.index[p]\n else:\n while k >= 0:\n if S[i - 1] == T[k]:\n break\n k = k - 1\n self.index[p] = k\n if k == -1:\n dp[i][j] = 1\n else:\n dp[i][j] = min(dp[i - 1][j], 1 + dp[i - 1][k])\n finalans = dp[i][j]\n if finalans >= maxx:\n finalans = -1\n return finalans", "def shortestunsub(S, T):\n prev = [0 for _ in range(len(T) + 1)]\n for i in range(len(S), -1, -1):\n curr = [0 for _ in range(len(T) + 1)]\n for j in range(len(T), -1, -1):\n if i == len(S):\n curr[j] = float('inf')\n continue\n if j == len(T):\n curr[j] = 1\n continue\n k = T[j:].find(S[i])\n if k == -1:\n curr[j] = 1\n continue\n curr[j] = min(prev[j], 1 + prev[k + j + 1])\n prev = [k for k in curr]\n return -1 if curr[0] == float('inf') else curr[0]", "INV = 10 ** 9 + 7\n\ndef shortestunsub(S, T):\n (NS, NT) = (len(S), len(T))\n dp = [[1] * (NT + 1) for _ in range(NS + 1)]\n for j in range(NT + 1):\n dp[NS][j] = INV\n startidx = {}\n for c in S:\n if c in startidx:\n continue\n startidx[c] = arr = [-1] * NT\n prev = -1\n for j in range(NT - 1, -1, -1):\n prev = j if T[j] == c else prev\n arr[j] = prev\n for i in range(NS - 1, -1, -1):\n arr = startidx.get(S[i], None)\n if arr is None:\n return 1\n for j in range(NT - 1, -1, -1):\n if S[i] == T[j]:\n dp[i][j] = min(1 + dp[i + 1][j + 1], dp[i + 1][j])\n else:\n dp[i][j] = 1 if arr[j] < 0 else min(dp[i + 1][j], 1 + dp[i + 1][arr[j] + 1])\n return -1 if dp[0][0] >= INV else dp[0][0]", "import copy\nMAX = 10000\n\ndef shortestunsub(S, T):\n rightmost = {}\n rightMost = [dict()] * len(T)\n for i in range(len(T)):\n if i:\n rightMost[i] = copy.deepcopy(rightMost[i - 1])\n rightMost[i][T[i]] = i\n\n def shortunseq(S, T):\n m = len(S)\n n = len(T)\n dp = [[0 for i in range(n + 1)] for j in range(m + 1)]\n for i in range(m + 1):\n dp[i][0] = 1\n for i in range(n + 1):\n dp[0][i] = MAX\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n ch = S[i - 1]\n k = rightMost[j - 1].get(ch, -1)\n if k == -1:\n dp[i][j] = 1\n else:\n dp[i][j] = min(dp[i - 1][j], dp[i - 1][k] + 1)\n ans = dp[m][n]\n if ans >= MAX:\n ans = -1\n return ans\n return shortunseq(S, T)", "from collections import defaultdict\n\ndef shortestunsub(text1, text2):\n (n, m) = (len(text1), len(text2))\n mapp = defaultdict(lambda : -1)\n dp = [[0] * (m + 1) for i in range(n + 1)]\n for i in range(m + 1):\n dp[0][i] = 501\n for i in range(1, n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n mapp = defaultdict(lambda : -1)\n for j in range(1, m + 1):\n p = j - 1\n if text1[i - 1] == text2[p]:\n mapp[text1[i - 1]] = p\n p = mapp[text1[i - 1]]\n if p == -1:\n dp[i][j] = 1\n else:\n dp[i][j] = min(dp[i - 1][j], 1 + dp[i - 1][p])\n mapp[text2[j - 1]] = j - 1\n return dp[-1][-1] if dp[-1][-1] != 501 else -1", "def shortestunsub(S, T):\n dp = {0: 0}\n mem = dict()\n for length in range(1, len(S) + 1):\n dp2 = dict()\n for (s_start, t_start) in dp.items():\n visited = set()\n for i in range(s_start, len(S)):\n if S[i] not in visited:\n visited.add(S[i])\n if (S[i], t_start) not in mem:\n j = T.find(S[i], t_start)\n if j == -1:\n return length\n for pos in range(t_start, j + 1):\n if (S[i], pos) in mem:\n break\n mem[S[i], pos] = j\n dp2[i + 1] = max(dp2.get(i + 1, 0), mem[S[i], t_start] + 1)\n dp = dp2\n return -1", "def shortestunsub(S, T):\n n = len(S)\n m = len(T)\n dp = [[0] * (m + 1) for _ in range(n + 1)]\n MAX = float('inf')\n ind = dict()\n for i in range(m + 1):\n dp[0][i] = MAX\n for i in range(1, n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n k = j - 1\n ch = S[i - 1]\n if ch == T[k]:\n ind[ch] = k\n elif ch in ind:\n k = ind[ch]\n else:\n while k >= 0:\n if T[k] == ch:\n break\n k -= 1\n ind[ch] = k\n if k == -1:\n dp[i][j] = 1\n else:\n dp[i][j] = min(dp[i - 1][j], 1 + dp[i - 1][k])\n ans = dp[n][m]\n if ans >= MAX:\n ans = -1\n return ans", "def __init__():\n self.indice = {}\n\ndef shortestunsub(S, T):\n dp = [[0] * (len(T) + 1) for i in range(len(S) + 1)]\n for i in range(len(T) + 1):\n dp[0][i] = 501\n for i in range(1, len(S) + 1):\n dp[i][0] = 1\n for i in range(1, len(S) + 1):\n for j in range(1, len(T) + 1):\n k = j - 1\n char = S[i - 1]\n if char == T[k]:\n self.indice[char] = k\n elif char in self.indice:\n k = self.indice[char]\n else:\n while k >= 0:\n if T[k] == S[i - 1]:\n break\n k -= 1\n self.indice[char] = k\n if k == -1:\n dp[i][j] = 1\n else:\n dp[i][j] = min(dp[i - 1][j], 1 + dp[i - 1][k])\n res = dp[i][j]\n if res >= 501:\n res = -1\n return res", "def shortestunsub(S, T):\n best = [[-1] * (len(S) + 1) for _ in range(len(S))]\n bestbefore = [-1] * (len(S) + 1)\n for i in range(len(S)):\n tplaces = list(reversed([ind for (ind, c) in enumerate(T) if c == S[i]]))\n for l in range(1, i + 2):\n while tplaces and tplaces[-1] <= bestbefore[l - 1]:\n del tplaces[-1]\n best[i][l] = tplaces[-1] if tplaces else len(T)\n for l in range(1, i + 2):\n bestbefore[l] = max(bestbefore[l], best[i][l])\n minl = overflow = len(S) + 5\n for ilist in best:\n if len(T) in ilist:\n minl = min(minl, ilist.index(len(T)))\n return -1 if minl == overflow else minl", "from math import inf\n\ndef shortestunsub(S, T):\n (n, m) = (len(S), len(T))\n dp = [[inf for j in range(m + 1)] for i in range(n + 1)]\n for i in range(1, n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n k = T[:j].rfind(S[i - 1])\n if k == -1:\n dp[i][j] = 1\n else:\n dp[i][j] = min(dp[i - 1][j], dp[i - 1][k] + 1)\n return dp[n][m] if dp[n][m] != inf else -1"], "starter_code": "def shortestunsub(S, T):\n", "input_output": {"inputs": ["S = \"babab\"\r\nT = \"babba\"", "S = \"babhi\"\r\nT = \"babij\""], "outputs": ["3", "1"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/shortest-uncommon-subsequence5746/1", "Expected Auxiliary Space": "O(|S|*|T|)", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(|S|^{2}*|T|)", "entry_point": "shortestunsub", "task_id": "TACO_lite/86", "example": [[["babab", "babba"], ["babhi", "babij"]], ["3", "1"]]} +{"requirement": "Given a singly linked list, delete middle of the linked list. For example, if given linked list is 1->2->3->4->5 then linked list should be modified to 1->2->4->5.\nIf there are even nodes, then there would be two middle nodes, we need to delete the second middle element. For example, if given linked list is 1->2->3->4->5->6 then it should be modified to 1->2->3->5->6.\nIf the input linked list is NULL or has 1 node, then it should return NULL\nExample 1:\nInput:\nLinkedList: 1->2->3->4->5\nOutput: 1 2 4 5\nExample 2:\nInput:\nLinkedList: 2->4->6->7->5->1\nOutput: 2 4 6 5 1\nYour Task:\nThe task is to complete the function deleteMid() which should delete the middle element from the linked list and return the head of the modified linked list. If the linked list is empty then it should return NULL.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= N <= 1000\n1 <= value <= 1000", "solutions": ["def deleteMid(head):\n temp = head\n c = 0\n while temp != None:\n c += 1\n temp = temp.next\n mid = c // 2 - 1\n i = 0\n temp = head\n while i < mid:\n temp = temp.next\n i += 1\n temp.next = temp.next.next\n return head", "def deleteMid(head):\n if head.next == None or head == None:\n return None\n elif head.next.next == None:\n head.next = None\n else:\n p = head\n n = 1\n while p.next != None:\n n += 1\n p = p.next\n m = n // 2\n n = 1\n p = head\n while n != m:\n n += 1\n p = p.next\n p.next = p.next.next\n return head", "def deleteMid(head):\n slow = head\n fast = head\n prev = None\n while fast and fast.next:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n prev.next = slow.next\n slow = None\n return head", "def deleteMid(head):\n temp = head\n size = 0\n while temp != None:\n size += 1\n temp = temp.next\n reach = size // 2\n i = 0\n temp = head\n prev = None\n while temp != None and i < reach:\n i += 1\n prev = temp\n temp = temp.next\n prev.next = temp.next\n return head", "def deleteMid(head):\n temp = head\n count = 0\n while temp != None:\n count += 1\n temp = temp.next\n if count % 2 == 0:\n i = 1\n j = count // 2\n temp = head\n prev = None\n while i < j + 1:\n prev = temp\n temp = temp.next\n i += 1\n prev.next = temp.next\n else:\n i = 1\n j = count // 2\n prev = None\n temp = head\n while i <= j:\n prev = temp\n temp = temp.next\n i += 1\n prev.next = temp.next\n return head", "def deleteMid(head):\n n = 0\n m = head\n while m != None:\n n += 1\n m = m.next\n a = head\n for i in range(int(n / 2) - 1):\n a = a.next\n a.next = a.next.next\n return head", "def deleteMid(head):\n if not head.next:\n return\n slow = head\n fast = head.next.next\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n slow.next = slow.next.next\n return head", "def deleteMid(head):\n if head == None or head.next == None:\n return None\n prev = head\n slow = head\n fast = head\n while fast.next != None and fast.next.next != None:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n if fast.next == None:\n prev.next = slow.next\n else:\n slow.next = slow.next.next\n return head", "def deleteMid(head):\n if head == None or head.next == None:\n return head\n fast_pointer = head\n prev_of_slow = None\n slow_pointer = head\n while fast_pointer != None and fast_pointer.next != None:\n prev_of_slow = slow_pointer\n slow_pointer = slow_pointer.next\n fast_pointer = fast_pointer.next.next\n prev_of_slow.next = slow_pointer.next\n return head", "def deleteMid(head):\n slow = head\n fast = head\n prev = head\n if fast.next is None:\n return None\n while fast and fast.next:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n prev.next = slow.next\n return head", "def deleteMid(head):\n length = 0\n dummy = head\n while dummy:\n dummy = dummy.next\n length += 1\n if not head or length == 1:\n return None\n dummy = head\n k = length // 2\n while k - 1 > 0:\n dummy = dummy.next\n k -= 1\n x = dummy.next.next\n dummy.next = x\n return head", "def deleteMid(head):\n if head == None:\n return None\n if head.next == None:\n del head\n return None\n temp = head\n cnt = 0\n while temp:\n temp = temp.next\n cnt = cnt + 1\n mid = cnt // 2\n temp = head\n k = 1\n while temp:\n if k == mid:\n temp.next = temp.next.next\n temp = temp.next\n k = k + 1\n return head", "def deleteMid(head):\n if head is None or head.next is None:\n return None\n count = 0\n fast = head\n while fast.next is not None:\n count += 1\n fast = fast.next\n fast = head\n mid = count / 2\n loc = 0\n while loc < mid - 1:\n loc += 1\n fast = fast.next\n tempNode = None\n tempNode = fast.next\n if tempNode is None:\n fast.next = None\n else:\n fast.next = tempNode.next\n return head", "def deleteMid(head):\n new = head\n i = 1\n while new.next != None:\n i = i + 1\n new = new.next\n i = i // 2\n j = 1\n new = head\n while j < i:\n new = new.next\n j = j + 1\n new.next = new.next.next\n return head", "def deleteMid(head):\n temp = head\n count = 0\n while temp:\n count += 1\n temp = temp.next\n temp = head\n count = count // 2\n while count:\n prev = temp\n temp = temp.next\n count -= 1\n prev.next = temp.next\n return head", "def deleteMid(head):\n if head == None or head.next == None:\n return None\n else:\n p = head\n q = head\n prev = None\n while q and q.next:\n prev = p\n p = p.next\n q = q.next.next\n if p != None:\n prev.next = p.next\n return head", "def getmidprev(head):\n prev = None\n (slow, fast) = (head, head)\n while fast is not None and fast.next is not None:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n return prev\n\ndef deleteMid(head):\n midprev = getmidprev(head)\n if midprev is None:\n return None\n midprev.next = midprev.next.next\n return head", "def deleteMid(head):\n cur = head\n fast = head\n prev = Node(0)\n h = prev\n prev.next = cur\n while fast and fast.next:\n cur = cur.next\n prev = prev.next\n fast = fast.next.next\n prev.next = cur.next\n return h.next", "def deleteMid(head):\n slow = head\n fast = head.next.next\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n slow.next = slow.next.next\n return head", "def deleteMid(head):\n if head.next is None:\n return None\n temp = head\n len = 0\n while temp:\n len += 1\n temp = temp.next\n temp = head\n for i in range(len // 2 - 1):\n temp = temp.next\n node2Del = temp.next\n temp.next = temp.next.next\n node2Del.next = None\n return head", "def deleteMid(head):\n slow = head\n fast = head.next\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n temp = slow.next\n slow.next = temp.next\n del temp\n return head", "def deleteMid(head):\n fast = slow = head\n pre = None\n while fast and fast.next:\n pre = slow\n slow = slow.next\n fast = fast.next.next\n pre.next = pre.next.next\n return head", "def deleteMid(head):\n if not head or not head.next:\n return None\n (ptr1, ptr2) = (head, head.next)\n while ptr2 and ptr2.next:\n ptr1 = ptr1.next\n ptr2 = ptr2.next.next if ptr2.next else ptr2.next\n ptr1.data = ptr1.data if ptr2 else ptr1.next.data\n ptr1.next = ptr1.next.next\n return head", "def deleteMid(head):\n cur = head\n count = n = 0\n while cur:\n count = count + 1\n cur = cur.next\n if count == 0 or count == 1:\n return NULL\n if count % 2 == 0:\n cur = head\n while n != count / 2 - 1:\n n = n + 1\n cur = cur.next\n temp = cur.next\n cur.next = cur.next.next\n del temp\n return head\n else:\n cur = head\n while n != count // 2 - 1:\n n = n + 1\n cur = cur.next\n temp = cur.next\n cur.next = cur.next.next\n del temp\n return head", "def deleteMid(head):\n if head is None or head.next is None:\n return head\n slow_ptr = head\n fast_ptr = head.next.next\n while fast_ptr is not None and fast_ptr.next is not None:\n slow_ptr = slow_ptr.next\n fast_ptr = fast_ptr.next.next\n temp = slow_ptr.next\n slow_ptr.next = temp.next\n temp = None\n return head\n\ndef __init__(data):\n self.data = data\n self.next = None", "def deleteMid(head):\n if head.next == None:\n return None\n if head.next.next == None:\n head.next = head.next.next\n return head\n fast = head\n slow = head\n while fast.next and fast.next.next:\n fast = fast.next.next\n slow = slow.next\n if fast.next:\n slow = slow.next\n slow.data = slow.next.data\n slow.next = slow.next.next\n return head", "def deleteMid(head):\n if head is None or head.next is None:\n return head\n curr = head\n prev = head\n next = None\n while curr != None and curr.next != None:\n curr = curr.next.next\n next = prev\n prev = prev.next\n next.next = prev.next\n return head", "def deleteMid(head):\n slow = head\n fast = head\n dummy = Node(-1)\n dummy.next = head\n prev = dummy\n while fast and fast.next:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n prev.next = slow.next\n return dummy.next", "def deleteMid(head):\n l = 0\n a = head\n while a != None:\n l += 1\n a = a.next\n mid = l // 2\n l = 0\n prev = None\n cur = head\n front = head.next\n while l < mid:\n l += 1\n prev = cur\n cur = front\n front = front.next\n prev.next = front\n return head", "def deleteMid(head):\n p = head\n q = head\n temp = None\n while p and p.next:\n temp = q\n q = q.next\n p = p.next.next\n if temp == None:\n return None\n temp.next = temp.next.next\n return head", "def deleteMid(head):\n c = 0\n temp = head\n while temp:\n c += 1\n temp = temp.next\n mid = c // 2\n temp = head\n k = 1\n while temp:\n if k == mid:\n temp.next = temp.next.next\n temp = temp.next\n k += 1\n return head", "def deleteMid(head):\n c = 0\n curr = head\n while curr != None:\n c += 1\n curr = curr.next\n curr = head\n for i in range(c // 2 - 1):\n curr = curr.next\n curr.next = curr.next.next\n return head", "def deleteMid(head):\n fast = head\n slow = head\n while fast != None and fast.next != None:\n slow = slow.next\n fast = fast.next.next\n mid = slow\n temp = head\n while temp.next != mid:\n temp = temp.next\n val = mid.next\n temp.next = val\n mid = None\n return head", "def deleteMid(head):\n start = head\n length = 0\n while start != None:\n length += 1\n start = start.next\n mid = int(length / 2) + 1\n start = 1\n start_node = head\n while start < mid - 1:\n start += 1\n start_node = start_node.next\n start_node.next = start_node.next.next\n return head", "def deleteMid(head):\n n = head\n i = 0\n while n is not None:\n i = i + 1\n n = n.next\n x = i // 2\n if i - x == 1:\n head.next = None\n else:\n n = head\n for i in range(0, x):\n n = n.next\n n.data = n.next.data\n n.next = n.next.next\n return head", "def deleteMid(head):\n slow = fast = head\n t = None\n while fast and fast.next:\n tmp = slow\n slow = slow.next\n fast = fast.next.next\n tmp.next = slow.next\n return head", "def deleteMid(head):\n pre = None\n rabbit = head\n tortoise = head\n while rabbit and rabbit.next:\n pre = tortoise\n rabbit = rabbit.next.next\n tortoise = tortoise.next\n pre.next = tortoise.next\n return head", "def deleteMid(head):\n temp = head\n count = 0\n while temp:\n count += 1\n temp = temp.next\n temp = head\n for i in range(count // 2 - 1):\n temp = temp.next\n temp.next = temp.next.next\n return head", "def deleteMid(head):\n temp = head\n count = 0\n while temp != None:\n count += 1\n temp = temp.next\n temp = head\n count = count // 2\n while count - 1:\n temp = temp.next\n count -= 1\n temp.next = temp.next.next\n return head", "def deleteMid(head):\n if head is None:\n return head\n if head.next is None:\n return None\n fast = slow = head\n pre = None\n while fast and fast.next:\n fast = fast.next.next\n pre = slow\n slow = slow.next\n if pre is not None:\n pre.next = slow.next\n return head", "def deleteMid(head):\n count = 0\n temp = head\n if head == None:\n return head\n if head.next == None:\n return None\n while temp:\n count += 1\n temp = temp.next\n mid = count // 2\n st = head\n while mid > 1:\n st = st.next\n mid = mid - 1\n temp = st.next\n st.next = st.next.next\n del temp\n return head", "def deleteMid(head):\n slow = head\n fast = head\n temp = None\n while fast != None and fast.next != None:\n temp = slow\n slow = slow.next\n fast = fast.next.next\n if temp == None:\n return None\n temp.next = temp.next.next\n return head", "def deleteMid(head):\n if head is None:\n return None\n temp = head\n temp2 = head\n count = 0\n while temp is not None:\n count = count + 1\n temp = temp.next\n i = 1\n while i < count // 2:\n i = i + 1\n temp2 = temp2.next\n temp_next = temp2.next\n temp2.next = temp_next.next\n temp_next.next = None\n return head", "def deleteMid(head):\n p = head\n c1 = 0\n c2 = 0\n while p:\n c1 = c1 + 1\n p = p.next\n c3 = c1 // 2 + 1\n if c3 <= 1:\n return None\n p = head\n q = None\n while p:\n c2 = c2 + 1\n if c2 == c3:\n q.next = p.next\n q = p\n p = p.next\n return head", "def deleteMid(head):\n temp = head\n if head == None:\n return head\n c = 0\n while temp != None:\n c += 1\n temp = temp.next\n d = int(c / 2)\n temp = head\n for i in range(d - 1):\n temp = temp.next\n temp.next = temp.next.next\n return head", "def deleteMid(head):\n fast = head\n slow = head\n tail = None\n while fast != None and fast.next != None:\n tail = slow\n slow = slow.next\n fast = fast.next.next\n tail.next = slow.next\n del slow\n return head", "def deleteMid(head):\n if head == None:\n return None\n if head.next == None:\n del head\n return None\n (temp, count) = (head, 0)\n while temp:\n temp = temp.next\n count += 1\n m = count // 2\n (temp, k) = (head, 1)\n while temp:\n if k == m:\n temp.next = temp.next.next\n temp = temp.next\n k += 1\n return head", "def deleteMid(head):\n slow = head\n fast = head\n new = head\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n if fast.next:\n if fast.next.next == None:\n slow.next = slow.next.next\n else:\n while new.next != slow:\n new = new.next\n new.next = new.next.next\n return head", "def deleteMid(head):\n slow = head\n fast = head\n prev = Node(0)\n while fast != None and fast.next != None:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n prev.next = prev.next.next\n return head", "def deleteMid(head):\n cur = head\n ans = []\n while cur:\n ans.append(cur.data)\n cur = cur.next\n ind = len(ans) // 2\n ans.pop(ind)\n l = Node(0)\n h = l\n for i in ans:\n n = Node(i)\n l.next = n\n l = l.next\n return h.next", "def deleteMid(head):\n temp = head\n r = head\n count = 0\n while temp is not None:\n temp = temp.next\n count += 1\n for i in range(count // 2 - 1):\n head = head.next\n head.next = head.next.next\n return r", "def deleteMid(head):\n c = a = b = head\n b = b.next.next\n while b and b.next:\n a = a.next\n b = b.next.next\n a.next = a.next.next\n return c", "def deleteMid(head):\n i = 0\n t = head\n while t:\n t = t.next\n i += 1\n t1 = head\n for j in range(i):\n if j == i // 2 - 1:\n t1.next = t1.next.next\n break\n t1 = t1.next\n return head", "def deleteMid(head):\n slow = head\n fast = head\n ptr = None\n if head == None:\n return None\n while fast and fast.next:\n ptr = slow\n slow = slow.next\n fast = fast.next.next\n ptr.next = slow.next\n slow.next = None\n return head", "def deleteMid(head):\n count = 0\n curr = head\n while curr is not None:\n count += 1\n curr = curr.next\n if count <= 1:\n return None\n nodeToDel = count // 2 + 1\n cnt = 0\n curr = head\n while cnt < nodeToDel - 2:\n cnt += 1\n curr = curr.next\n curr.next = curr.next.next\n return head", "def deleteMid(head):\n lst = []\n while head:\n lst.append(head.data)\n head = head.next\n del lst[len(lst) // 2]\n a = Node(0)\n temp = a\n for i in lst:\n temp.next = Node(i)\n temp = temp.next\n return a.next", "def deleteMid(head):\n if head == None or head.next == None:\n return None\n temp = head\n length = 0\n while temp != None:\n length += 1\n temp = temp.next\n length = length // 2\n i = 0\n temp = head\n prev = None\n while i < length:\n prev = temp\n temp = temp.next\n i += 1\n prev.next = temp.next\n temp.next = None\n return head", "def deleteMid(head):\n c = length(head)\n mid = c // 2\n itr = head\n i = 0\n while itr:\n if mid - 1 == i:\n itr.next = itr.next.next\n i += 1\n itr = itr.next\n return head\n\ndef length(head):\n c = 0\n itr = head\n while itr:\n c += 1\n itr = itr.next\n return c", "def deleteMid(head):\n if head == None:\n return None\n if head.next == None:\n del head\n return None\n c = 0\n t = head\n while t:\n c += 1\n t = t.next\n mid = c // 2\n t = head\n k = 1\n while t:\n if k == mid:\n t.next = t.next.next\n t = t.next\n k += 1\n return head", "def deleteMid(head):\n fast = slow = head\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n curr = head\n while curr.next != slow:\n curr = curr.next\n if slow.next is None:\n curr.next = None\n else:\n curr.next = slow.next\n return head", "import math\n\ndef deleteMid(head):\n count = 1\n temp = head\n while temp.next:\n count += 1\n temp = temp.next\n n = math.floor(count / 2)\n temp1 = head\n i = 0\n while i < n - 1:\n temp1 = temp1.next\n i += 1\n temp1.next = temp1.next.next\n return head", "def deleteMid(head):\n if head is None:\n return head\n if head.next is None:\n return Null\n temp = head\n c = 0\n while temp:\n c += 1\n temp = temp.next\n b = c // 2\n temp = head\n i = 1\n while temp:\n if i == b:\n temp.next = temp.next.next\n temp = temp.next\n i += 1\n return head", "def deleteMid(head):\n stack = [head]\n count = 0\n while len(stack) > 0:\n current = stack.pop()\n count += 1\n if current.next:\n stack.append(current.next)\n if count > 1:\n stack.append(head)\n for i in range(count // 2 - 1):\n current = stack.pop()\n stack.append(current.next)\n current = stack.pop()\n current.next = current.next.next\n return head\n else:\n return None", "def deleteMid(head):\n temp = head\n length = 1\n while temp.next:\n temp = temp.next\n length += 1\n mid = length // 2\n temp = head\n k = 1\n while temp:\n if k == mid:\n temp.next = temp.next.next\n temp = temp.next\n k += 1\n return head", "def deleteMid(head):\n ans = Node(123)\n p = ans\n p.next = head\n s = head\n f = head.next\n while f and f.next:\n f = f.next.next\n s = s.next\n p = p.next\n if f:\n s.next = s.next.next\n return ans.next\n elif not f:\n p.next = p.next.next\n return ans.next", "def deleteMid(head):\n dummy = Node(0)\n dummy.next = head\n (slow, fast) = (dummy, head)\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n slow.next = slow.next.next\n return dummy.next", "def deleteMid(head):\n slow = head\n fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n mid = slow\n temp = head\n while temp.next != mid:\n temp = temp.next\n temp.next = mid.next\n return head"], "starter_code": "def __init__(data):\n", "input_output": {"inputs": ["LinkedList:1->2->3->4->5", "LinkedList:2->4->6->7->5->1"], "outputs": ["1 2 4 5", "2 4 6 5 1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Algorithms", "two-pointer-algorithm", "Linked List"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Amortized analysis"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/delete-middle-of-linked-list/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "__init__", "task_id": "TACO_lite/19", "example": [[], []]} +{"requirement": "You are given a binary string s and an integer m. You need to return an integer r. Where r = k%m, k is the binary equivalent of string s.\nExample 1:\nInput:\ns = \"101\" \nm = 2\nOutput:\n1\nExplanation: Here k=5 because (101)_{2} = (5)_{10}.\nHence 5 mod 2 = 1.\nExample 2:\nInput:\ns = \"1000\"\nm = 4\nOutput:\n0\nExplanation: Here k=8 and m=4 hence \nr = k mod m = 8 mod 4 = 0.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function modulo() which takes the string s and integer m as input parameters and returns the value of r as described above.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 <= len(s) <= 10^{7}\n1 <= m <= 100", "solutions": ["def modulo(s, m):\n k = int(s, 2)\n return k % m", "def modulo(s, m):\n rs = 0\n lenS = len(s)\n i = 0\n while i < lenS:\n while i < lenS and rs < m:\n rs = (rs << 1) + int(s[i])\n i += 1\n if rs >= m:\n rs = int(rs % m)\n return rs", "def modulo(s, m):\n c = int(s, 2)\n return c % m", "def modulo(s, m):\n a = int(s, 2)\n return a % m", "def modulo(s, m):\n n = len(s)\n s = s[::-1]\n res = 0\n p = [0] * n\n p[0] = 1\n tmp = 0\n for i in range(1, n):\n p[i] = 2 * p[i - 1] % m\n for i in range(n):\n if s[i] == '1':\n tmp += p[i]\n tmp %= m\n return tmp", "def modulo(s, m):\n r = int(s, 2)\n return r % m", "def modulo(s, m):\n dec = int(s, 2)\n return dec % m", "def modulo(s, m):\n x = int(s, 2)\n return x % m", "def modulo(s, m):\n decimal = 0\n for digit in s:\n if digit == '1':\n decimal = decimal * 2 + 1\n else:\n decimal = decimal * 2\n return decimal % m", "def modulo(s, m):\n n = int(s, 2)\n return n % m", "def modulo(s, m):\n num = int(s, 2)\n ans = num % m\n return ans", "def modulo(s, m):\n res = int(s, 2)\n return res % m", "def modulo(s, m):\n total = 0\n for x in s:\n total = (total * 2 + int(x)) % m\n return total", "def modulo(s, m):\n d = int(s, 2)\n return d % m", "def modulo(s, m):\n r = 0\n for c in s:\n r = (r * 2 + int(c)) % m\n return r", "def modulo(s, m):\n p = [1]\n for i in range(1, len(s) + 1):\n p.append(p[-1] * 2 % m)\n k = 0\n for i in range(len(s)):\n k = (k * 2 + int(s[i])) % m\n return k", "def modulo(s, m):\n number = int(s, 2)\n return number % m", "def modulo(s, m):\n r = 0\n for c in s:\n r = r * 2\n if c == '1':\n r += 1\n if r >= m:\n r -= m\n return r", "import math\n\ndef modulo(s, m):\n return int(s, 2) % m", "def modulo(s: str='0', m: int=1) -> int:\n if not all((char in '01' for char in s)):\n raise ValueError('Input string must be a binary string.')\n if m <= 0:\n raise ValueError('Modulus must be a positive integer greater than zero.')\n k = int(s, 2)\n r = k % m\n return r", "def modulo(s, m):\n t = int(s, 2)\n return t % m", "def modulo(s, m):\n mom = int(s, 2)\n return mom % m", "def modulo(s, m):\n v = 0\n for i in range(len(s)):\n v = (v * 2 + (1 if s[i] == '1' else 0)) % m\n return v % m", "def modulo(s, m):\n temp = 0\n pow = 1\n c = 0\n return int(s, 2) % m", "def modulo(s, m):\n r = 0\n n = len(s)\n power_of_2 = [1] * n\n for i in range(n - 2, -1, -1):\n power_of_2[i] = (power_of_2[i + 1] << 1) % m\n for i in range(n):\n if s[i] == '1':\n r = (r + power_of_2[i]) % m\n return r", "def modulo(s, m):\n b = 0\n a = len(s) - 1\n i = len(s) - 1\n p = 1\n while i >= 0:\n if s[i] == '1':\n b += p\n b = b % m\n p = p * 2\n p = p % m\n i -= 1\n return b", "def modulo(s, m):\n ans = 0\n power = 1\n for i in range(len(s) - 1, -1, -1):\n if s[i] == '1':\n ans += power\n ans %= m\n power *= 2\n power %= m\n return ans", "def modulo(s, m):\n n = len(s)\n prefix_mod = [0] * n\n prefix_mod[0] = int(s[0]) % m\n for i in range(1, n):\n prefix_mod[i] = (prefix_mod[i - 1] * 2 % m + int(s[i])) % m\n return prefix_mod[n - 1]", "def modulo(s, m):\n integerval = int(s, 2)\n ans = integerval % m\n return int(ans)", "def modulo(s, m):\n dig = int(s, 2)\n return dig % m", "def modulo(s, m):\n n = len(s)\n res = 0\n cur = 1\n for i in range(n - 1, -1, -1):\n if s[i] == '1':\n res += cur\n res %= m\n cur <<= 1\n cur %= m\n return res % m"], "starter_code": "def modulo(s, m):\n", "input_output": {"inputs": ["s = \"101\" \nm = 2", "s = \"1000\"\nm = 4"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Bit Magic", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Mathematics"], "skill_types": ["Bit manipulation"], "url": "https://practice.geeksforgeeks.org/problems/7488b7721e8aa5e5fc37d56af8b9c89e329c796f/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "modulo", "task_id": "TACO_lite/24", "example": [[["101", 2], ["1000", 4]], ["1", "0"]]} +{"requirement": "Write a method that will search an array of strings for all strings that contain another string, ignoring capitalization. Then return an array of the found strings. \n\nThe method takes two parameters, the query string and the array of strings to search, and returns an array. \n\nIf the string isn't contained in any of the strings in the array, the method returns an array containing a single string: \"Empty\" (or `Nothing` in Haskell, or \"None\" in Python and C)\n\n### Examples\nIf the string to search for is \"me\", and the array to search is [\"home\", \"milk\", \"Mercury\", \"fish\"], the method should return [\"home\", \"Mercury\"].", "solutions": ["def word_search(query, seq):\n return [x for x in seq if query.lower() in x.lower()] or ['None']", "def word_search(query, seq):\n query = query.lower()\n result = [x for x in seq if query in x.lower()]\n return result if result else ['None']", "import re\n\ndef word_search(query, seq):\n return [w for w in seq if re.search(query, w, re.I)] or ['None']", "def word_search(query, seq):\n l = [i for i in seq if query.lower() in i.lower()]\n return [l, ['None']][not l]", "def word_search(query, seq):\n query = query.lower()\n return [word for word in seq if query in word.lower()] or ['None']", "def word_search(q, l):\n return [w for w in l if q.lower() in w.lower()] or ['None']", "def word_search(query, seq):\n query = query.lower()\n return [a for a in seq if query in a.lower()] or ['None']", "def word_search(query, seq):\n return [i for i in seq if query.lower() in i.lower()] or ['None']", "def word_search(query, seq):\n array = []\n for x in seq:\n if query.lower() in x.lower():\n array.append(x)\n else:\n pass\n if array != []:\n return array\n else:\n array = ['None']\n return array"], "starter_code": "def word_search(query, seq):\n", "input_output": {"fn_name": "word_search", "inputs": [["ab", ["za", "ab", "abc", "zab", "zbc"]], ["aB", ["za", "ab", "abc", "zab", "zbc"]], ["ab", ["za", "aB", "Abc", "zAB", "zbc"]], ["abcd", ["za", "aB", "Abc", "zAB", "zbc"]]], "outputs": [[["ab", "abc", "zab"]], [["ab", "abc", "zab"]], [["aB", "Abc", "zAB"]], [["None"]]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/54b81566cd7f51408300022d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "word_search", "task_id": "TACO_lite/12", "example": [[["me", ["home", "milk", "Mercury", "fish"]]], ["['home', 'Mercury']"]]} +{"requirement": "Create a program that will take in a string as input and, if there are duplicates of more than two alphabetical characters in the string, returns the string with all the extra characters in a bracket.\n\nFor example, the input \"aaaabbcdefffffffg\" should return \"aa[aa]bbcdeff[fffff]g\" \n\nPlease also ensure that the input is a string, and return \"Please enter a valid string\" if it is not.", "solutions": ["import re\n\ndef string_parse(string):\n return re.sub('(.)\\\\1(\\\\1+)', '\\\\1\\\\1[\\\\2]', string) if isinstance(string, str) else 'Please enter a valid string'", "import re\n\ndef string_parse(s):\n if not isinstance(s, str):\n return 'Please enter a valid string'\n for l in set(s):\n s = re.sub('(%s%s)(%s+)' % (l, l, l), '\\\\1[\\\\2]', s)\n return s", "from functools import partial\nfrom re import compile\nREGEX = partial(compile('(.)\\\\1(\\\\1+)').sub, '\\\\1\\\\1[\\\\2]')\n\ndef string_parse(string):\n return REGEX(string) if type(string) == str else 'Please enter a valid string'", "import re\n\ndef string_parse(string):\n try:\n\n def replace(match):\n return '{0}{0}[{1}]'.format(*match.group(1, 2))\n return re.sub('(.)\\\\1(\\\\1+)', replace, string)\n except TypeError:\n return 'Please enter a valid string'", "from itertools import groupby\n\ndef string_parse(string):\n if isinstance(string, str):\n gs = groupby(string)\n f = lambda s: s if len(s) < 3 else s[:2] + '[' + s[2:] + ']'\n return ''.join([f(''.join(list(g))) for (_, g) in groupby(string)])\n else:\n return 'Please enter a valid string'", "from itertools import groupby\n\ndef string_parse(string):\n return ''.join((f'{x * 2}[{x * (c - 2)}]' if c > 2 else x * c for (x, c) in [(x, len(list(gp))) for (x, gp) in groupby(string)])) if isinstance(string, str) else 'Please enter a valid string'", "def string_parse_gen(string):\n (counter, prev_char) = (0, '')\n for char in string:\n if char == prev_char:\n counter += 1\n if counter == 2:\n yield '['\n else:\n if counter >= 2:\n yield ']'\n prev_char = char\n counter = 0\n yield char\n if counter >= 2:\n yield ']'\n\ndef string_parse(string):\n return ''.join(list(string_parse_gen(string))) if isinstance(string, str) else 'Please enter a valid string'", "def string_parse(s):\n from itertools import groupby\n if not isinstance(s, str):\n return 'Please enter a valid string'\n x = [(i, sum([1 for j in group])) for (i, group) in groupby(s)]\n x = [i[0] * 2 + '[' + i[0] * (i[1] - 2) + ']' if i[1] >= 2 else i[0] for i in x]\n x = ''.join(x)\n x = x.replace('[]', '')\n return x", "import re\n\ndef string_parse(string):\n if not isinstance(string, str):\n return 'Please enter a valid string'\n\n def repl(Match):\n s = Match[0]\n n = len(s)\n c = s[0]\n return s if n <= 2 else c * 2 + f'[{c * (n - 2)}]'\n return re.sub('(\\\\w)\\\\1*', repl, string)", "import re\n\ndef string_parse(s):\n try:\n return re.sub('(.)\\\\1+', lambda m: m.group()[0:2] + '[' + m.group()[2:] + ']' if len(m.group()) > 2 else m.group(), s)\n except TypeError:\n return 'Please enter a valid string'", "import re\n\ndef string_parse(s):\n return re.sub('((.)\\\\2*)', lambda x: f'{2 * x[2]}[{x[1][:len(x[1]) - 2]}]' if len(x[1]) > 2 else x[1], s) if isinstance(s, str) else 'Please enter a valid string'", "def string_parse(string):\n if not isinstance(string, str):\n return 'Please enter a valid string'\n res = []\n count = 0\n last_char = None\n for c in string:\n if c != last_char:\n if count > 2:\n res.append(']')\n count = 0\n elif count == 2:\n res.append('[')\n count += 1\n last_char = c\n res.append(c)\n if count > 2:\n res.append(']')\n return ''.join(res)", "from itertools import groupby\n\ndef string_parse(str_in):\n if not isinstance(str_in, str):\n return 'Please enter a valid string'\n str_out = []\n for (_, group) in groupby(str_in):\n s = ''.join(group)\n str_out.append(s if len(s) < 3 else f'{s[:2]}[{s[2:]}]')\n return ''.join(str_out)", "def string_parse(string):\n if type(string) != str:\n return 'Please enter a valid string'\n try:\n out = string[:2]\n temp = ''\n for i in string[2:]:\n if i == out[-1] == out[-2]:\n temp += i\n else:\n if temp != '':\n out += '[' + temp + ']'\n out += i\n temp = ''\n if temp != '':\n out += '[' + temp + ']'\n return out\n except:\n return 'Please enter a valid string'", "def string_parse(string):\n if not isinstance(string, str):\n return 'Please enter a valid string'\n letters = ['0']\n for i in string:\n if i == letters[-1][-1]:\n letters[-1] += i\n else:\n letters.append(i)\n return ''.join([i if len(i) < 3 else f'{i[:2]}[{i[2:]}]' for i in letters][1:])", "import re\n\ndef string_parse(string):\n if not type(string) == str:\n return 'Please enter a valid string'\n return re.sub('(([a-zA-Z])\\\\2)(\\\\2+)', lambda x: x.group(1) + '[' + x.group(3) + ']', string)", "def string_parse(string):\n if string == None or not isinstance(string, str):\n return 'Please enter a valid string'\n if string == '':\n return ''\n res = ''\n current_char = string[0]\n char_counter = 1\n for i in range(1, len(string)):\n if current_char == string[i]:\n if char_counter + 1 <= 2:\n res += current_char\n char_counter += 1\n continue\n elif char_counter + 1 == 3:\n res = res + current_char + '['\n char_counter += 1\n continue\n elif char_counter + 1 > 3:\n res += current_char\n char_counter += 1\n else:\n if char_counter > 2:\n res = res + current_char + ']'\n else:\n res += current_char\n current_char = string[i]\n char_counter = 1\n res = res + current_char if char_counter <= 2 else res + current_char + ']'\n return res", "import re\n\ndef string_parse(string):\n if type(string) != str:\n return 'Please enter a valid string'\n for c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':\n string = re.sub(c + '{2}(' + c + '+)', c * 2 + '[\\\\g<1>]', string)\n return string", "def string_parse(string):\n if not isinstance(string, str):\n return 'Please enter a valid string'\n if len(string) == 0:\n return ''\n Di = {}\n text = ''\n f = 0\n i = 0\n f2 = 0\n for i in range(len(string) - 1):\n Di.setdefault(string[i], 0)\n text += string[i]\n Di[string[i]] += 1\n if not f and Di[string[i]] >= 2 and (string[i] == string[i + 1]):\n text += '['\n f = 1\n if f and Di[string[i]] >= 2 and (string[i] != string[i + 1]):\n text += ']'\n f = 0\n f2 = 1\n if not f and string[i] != string[i + 1]:\n Di[string[i]] = 0\n text += string[-1]\n if f:\n text += ']'\n return text"], "starter_code": "def string_parse(string):\n", "input_output": {"fn_name": "string_parse", "inputs": [["aaaabbcdefffffffg"], [3], ["boopdedoop"], ["helloookat"], [true], [""], ["aAAabbcdeffFfFffg"], ["aAAabbcdeFFFffffg"], [{}], [[5.3]]], "outputs": [["aa[aa]bbcdeff[fffff]g"], ["Please enter a valid string"], ["boopdedoop"], ["helloo[o]kat"], ["Please enter a valid string"], [""], ["aAAabbcdeffFfFffg"], ["aAAabbcdeFF[F]ff[ff]g"], ["Please enter a valid string"], ["Please enter a valid string"]]}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5411c4205f3a7fd3f90009ea", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "string_parse", "task_id": "TACO_lite/65", "example": [[["aaaabbcdefffffffg"], [12345]], ["aa[aa]bbcdeff[fffff]g", "Please enter a valid string"]]} +{"requirement": "You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.\n\n#Examples:\n~~~if-not:bf\n```\nKata.getMiddle(\"test\") should return \"es\"\n\nKata.getMiddle(\"testing\") should return \"t\"\n\nKata.getMiddle(\"middle\") should return \"dd\"\n\nKata.getMiddle(\"A\") should return \"A\"\n\n```\n~~~\n~~~if:bf\n```\nrunBF(\"test\\0\") should return \"es\"\n\nrunBF(\"testing\\0\") should return \"t\"\n\nrunBF(\"middle\\0\") should return \"dd\"\n\nrunBF(\"A\\0\") should return \"A\"\n\n```\n~~~\n\n#Input\n\nA word (string) of length `0 < str < 1000` (In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases). You do not need to test for this. This is only here to tell you that you do not need to worry about your solution timing out.\n\n\n#Output\n\nThe middle character(s) of the word represented as a string.", "solutions": ["def get_middle(s):\n return s[(len(s) - 1) // 2:len(s) // 2 + 1]", "def get_middle(s):\n (index, odd) = divmod(len(s), 2)\n return s[index] if odd else s[index - 1:index + 1]", "import math\n\ndef get_middle(s):\n x = len(s)\n y = int(x / 2)\n if x % 2 == 0:\n return s[y - 1:y + 1]\n else:\n return s[y:y + 1]", "def get_middle(s):\n i = (len(s) - 1) // 2\n return s[i:-i] or s", "def get_middle(s):\n x = int(len(s) / 2)\n return s[x] if len(s) % 2 != 0 else s[x - 1:x + 1]", "def get_middle(s):\n (q, r) = divmod(len(s), 2)\n return s[q - (1 if not r else 0):q + 1]", "def get_middle(s):\n if len(s) % 2 == 0:\n iA = int(len(s) / 2 - 1)\n iB = int(len(s) / 2 + 1)\n return s[iA:iB]\n else:\n return s[int(len(s) / 2)]"], "starter_code": "def get_middle(s):\n", "input_output": {"fn_name": "get_middle", "inputs": [["test"], ["testing"], ["middle"], ["A"], ["of"]], "outputs": [["es"], ["t"], ["dd"], ["A"], ["of"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56747fd5cb988479af000028", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "get_middle", "task_id": "TACO_lite/52", "example": [[["test"], ["testing"], ["middle"], ["A"]], ["es", "t", "dd", "A"]]} +{"requirement": "Thanks to the effects of El Nino this year my holiday snorkelling trip was akin to being in a washing machine... Not fun at all.\n\nGiven a string made up of '~' and '\\_' representing waves and calm respectively, your job is to check whether a person would become seasick.\n\nRemember, only the process of change from wave to calm (and vice versa) will add to the effect (really wave peak to trough but this will do). Find out how many changes in level the string has and if that figure is more than 20% of the string, return \"Throw Up\", if less, return \"No Problem\".", "solutions": ["def sea_sick(sea):\n return 'Throw Up' if (sea.count('~_') + sea.count('_~')) / len(sea) > 0.2 else 'No Problem'", "def sea_sick(sea):\n changes = sum((1 for (a, b) in zip(sea, sea[1:]) if a != b))\n return 'No Problem' if changes * 5 <= len(sea) else 'Throw Up'", "def sea_sick(sea):\n waves = sum((sea[i:i + 2] in '_~_' for i in range(len(sea) - 1)))\n if waves / float(len(sea)) > 0.2:\n return 'Throw Up'\n return 'No Problem'", "from operator import truediv\n\ndef sea_sick(s):\n result = sum((s[a:a + 2] in '_~_' for a in range(len(s) - 1)))\n if truediv(result, len(s)) > 0.2:\n return 'Throw Up'\n return 'No Problem'", "sea_sick = lambda s: ['No Problem', 'Throw Up'][s.count('~_') + s.count('_~') > 0.2 * len(s)]", "def sea_sick(sea):\n return 'Throw Up' if sum((x != y for (x, y) in zip(sea, sea[1:]))) / len(sea) > 0.2 else 'No Problem'", "sea_sick = lambda s: ['No Problem', 'Throw Up'][sum(__import__('itertools').starmap(str.__ne__, zip(s, s[1:]))) / len(s) > 0.2]", "def sea_sick(sea):\n (c, p) = (0, sea[0])\n for s in sea[1:]:\n if s != p:\n c += 1\n p = s\n return 'Throw Up' if c / len(sea) > 0.2 else 'No Problem'"], "starter_code": "def sea_sick(sea):\n", "input_output": {"fn_name": "sea_sick", "inputs": [["~"], ["_~~~~~~~_~__~______~~__~~_~~"], ["______~___~_"], ["____"], ["_~~_~____~~~~~~~__~_~"]], "outputs": [["No Problem"], ["Throw Up"], ["Throw Up"], ["No Problem"], ["Throw Up"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57e90bcc97a0592126000064", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sea_sick", "task_id": "TACO_lite/99", "example": [[], []]} +{"requirement": "An english word is given as input and it is modified using some format. Identify the format using the examples given below (examples given are sufficient to identify the format) and print the modified word as output.\nSTEWART is modified as EWARTSTAY, AMAR is modified as AMAR, MAN is modified as ANMAY etc.\nNote: Input contains uppercase english words.\n \nExample 1:\nInput:\nS = \"GEEK\"\nOutput:\nEEKGAY\nExplanation:\nThe string when modified gives \"EEKGAY\".\nExample 2:\nInput:\nS = \"ALL\"\nOutput:\nALL\nExplanation:\nThe string when modified remains the same.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function englishWords() which takes a String S as input and returns the modified String.\n \nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(|S|)\n \nConstraints:\n1 <= |S| <= 10^{5}", "solutions": ["def englishwords(S):\n x = ['A', 'E', 'I', 'O', 'U']\n p = ''\n t = ''\n for i in S:\n if i not in x:\n p += i\n else:\n l = S.index(i)\n t = S[l:]\n break\n t += p\n if t == S:\n return S\n return t + 'AY'", "def englishwords(S):\n x = 'AEIOU'\n if S[0] in x:\n return S\n c = 0\n for i in S:\n if i in x:\n break\n c += 1\n r = S[c:]\n r = r + S[:c] + 'AY'\n return r", "def englishwords(s):\n v = ['A', 'E', 'I', 'O', 'U']\n ans = ''\n res = ''\n if s[0] in v:\n return s\n for i in range(len(s)):\n if s[i] not in v:\n res += s[i]\n elif s[i] in v:\n ans += s[i:]\n break\n ans += res\n ans += 'AY'\n return ans", "def englishwords(S):\n v = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n l = list(S)\n k = ''\n p = []\n for i in range(len(l)):\n if l[i] not in v:\n k += l[i]\n else:\n p = l[i:]\n break\n if len(p) == len(l):\n return S\n p.append(k)\n p.append('AY')\n return ''.join(p)", "def englishwords(S):\n l = list(S)\n s = ''\n if l[0] in ['A', 'E', 'I', 'O', 'U']:\n return S\n else:\n for i in range(len(l)):\n if l[i] in ['A', 'E', 'I', 'O', 'U']:\n s += s.join(l[i:]) + s.join(l[:i]) + 'AY'\n break\n return s", "def englishwords(s):\n c = 0\n for i in range(len(s)):\n if s[i] not in 'AEIOU':\n c += 1\n else:\n break\n if c == 0:\n return s\n else:\n a = s[:c]\n b = s[c:]\n return b + a + 'AY'", "def englishwords(S):\n n = len(S)\n m = {'A', 'E', 'I', 'O', 'U'}\n if S[0] in m:\n return S\n for i in range(n):\n if S[i] in m:\n return S[i:] + S[:i] + 'AY'\n return ''", "def englishwords(S):\n z = ['A', 'E', 'I', 'O', 'U']\n l = ''\n m = ''\n for i in S:\n if i not in z:\n l += i\n else:\n k = S.index(i)\n m = S[k:]\n break\n m += l\n if m == S:\n return S\n return m + 'AY'", "def englishwords(S):\n v = ['A', 'E', 'I', 'O', 'U']\n a = ''\n b = ''\n for i in S:\n if i not in v:\n a += i\n else:\n l = S.index(i)\n t = S[l:]\n break\n t += a\n if t == S:\n return S\n return t + 'AY'", "def englishwords(S):\n vowel = ('A', 'E', 'I', 'O', 'U')\n if S.startswith(vowel):\n return S\n else:\n for (index, i) in enumerate(S):\n if i in vowel:\n return S[index:] + S[:index] + 'AY'", "def englishwords(S):\n newstr = ''\n oldstr = ''\n if S[0] == 'A' or S[0] == 'E' or S[0] == 'I' or (S[0] == 'O') or (S[0] == 'U'):\n return S\n else:\n for i in range(len(S)):\n if S[i] == 'A' or S[i] == 'E' or S[i] == 'I' or (S[i] == 'O') or (S[i] == 'U'):\n newstr += S[i:]\n oldstr += S[:i]\n break\n return newstr + oldstr + 'AY'", "def englishwords(S):\n if S[0] == 'A' or S[0] == 'E' or S[0] == 'I' or (S[0] == 'O') or (S[0] == 'U'):\n return S\n ans = ''\n for i in range(len(S)):\n if S[i] == 'A' or S[i] == 'E' or S[i] == 'I' or (S[i] == 'O') or (S[i] == 'U'):\n for j in range(i, len(S)):\n ans += S[j]\n for a in range(i):\n ans += S[a]\n break\n return ans + 'AY'", "def englishwords(S):\n index = -1\n for i in range(len(S)):\n if S[i] in ['A', 'E', 'I', 'O', 'U']:\n index = i\n break\n if index == 0:\n return S\n if index == -1:\n return S + 'AY'\n return S[index:] + S[0:index] + 'AY'"], "starter_code": "def englishwords(S):\n", "input_output": {"inputs": ["S = \"GEEK\"", "S = \"ALL\""], "outputs": ["EEKGAY", "ALL"]}, "difficulty": "EASY", "raw_tags": ["logical-thinking", "Misc"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/english-words4137/1", "Expected Auxiliary Space": "O(|S|)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "englishwords", "task_id": "TACO_lite/98", "example": [[], []]} +{"requirement": "Given an unsorted array Arr of size N of positive integers. One number 'A' from set {1, 2,....,N} is missing and one number 'B' occurs twice in array. Find these two numbers.\nExample 1:\nInput:\nN = 2\nArr[] = {2, 2}\nOutput: 2 1\nExplanation: Repeating number is 2 and \nsmallest positive missing number is 1.\nExample 2:\nInput:\nN = 3\nArr[] = {1, 3, 3}\nOutput: 3 2\nExplanation: Repeating number is 3 and \nsmallest positive missing number is 2.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function findTwoElement() which takes the array of integers arr and n as parameters and returns an array of integers of size 2 denoting the answer ( The first index contains B and second index contains A.)\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n2 \u2264 N \u2264 10^{5}\n1 \u2264 Arr[i] \u2264 N", "solutions": ["def findtwoelement(arr, n):\n unordered_map = {}\n rep = 0\n miss = 0\n for i in arr:\n if i not in unordered_map:\n unordered_map[i] = 1\n else:\n rep = i\n for i in range(1, n + 1):\n if i not in unordered_map:\n miss = i\n return [rep, miss]", "def findtwoelement(arr, n):\n sei = [False] * n\n for i in arr:\n if sei[i - 1]:\n repeated = i\n else:\n sei[i - 1] = True\n for i in range(n):\n if not sei[i]:\n return [repeated, i + 1]", "def findtwoelement(arr, n):\n d = {}\n b = 0\n for i in arr:\n try:\n d[i] += 1\n r = i\n except:\n d[i] = 1\n f = False\n for i in range(1, max(arr)):\n if i not in d:\n l = i\n f = True\n break\n if f == False:\n return (r, max(arr) + 1)\n return (r, l)", "def findtwoelement(arr, n):\n a = list(range(1, len(arr) + 1))\n res = sum(a)\n tot = sum(arr)\n arr = set(arr)\n sum_arr = sum(arr)\n missing = res - sum_arr\n repeated = tot - sum_arr\n return (repeated, missing)", "def findtwoelement(arr, n):\n l = []\n s1 = sum(arr)\n k = set(arr)\n k = list(k)\n s2 = sum(k)\n l.append(s1 - s2)\n s3 = n * (n + 1) // 2\n l.append(s3 - s2)\n return l", "from collections import Counter\n\ndef findtwoelement(arr, n):\n a = set(range(1, n + 1))\n missing = list(a - set(arr))[0]\n dic = {}\n for i in arr:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n if dic[i] > 1:\n return [i, missing]", "def findtwoelement(arr, n):\n m = max(arr)\n b = [i for i in range(1, n + 1)]\n s = list(set(b) - set(arr))\n dic = {}\n for i in arr:\n if i in dic:\n s.insert(0, i)\n return s\n else:\n dic[i] = 1", "def findtwoelement(arr, n):\n A = set(range(1, n + 1))\n missing = list(A - set(arr))[0]\n dic = {}\n for i in arr:\n if i not in dic:\n dic[i] = 0\n dic[i] += 1\n if dic[i] >= 2:\n return [i, missing]", "def findtwoelement(arr, n):\n (a, b) = (0, 0)\n for i in range(n):\n if arr[abs(arr[i]) - 1] < 0:\n a = abs(arr[i])\n else:\n arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]\n for i in range(n):\n if arr[i] > 0:\n b = i + 1\n break\n return (a, b)", "def findtwoelement(arr, n):\n arr.sort()\n missing = None\n r = None\n for i in range(n - 1):\n if arr[i] == arr[i + 1]:\n r = arr[i]\n arr.remove(r)\n break\n for i in range(1, n):\n if i != arr[i - 1]:\n missing = i\n break\n if not missing:\n missing = arr[n - 2] + 1\n return [r, missing]", "def findtwoelement(arr, n):\n temp = [0] * (n + 1)\n ans = []\n for i in range(n):\n temp[arr[i]] += 1\n for i in range(1, n + 1):\n if temp[i] > 1:\n ans.insert(0, i)\n if temp[i] == 0:\n ans.insert(1, i)\n return ans", "def findtwoelement(arr, size):\n for i in arr:\n if arr[abs(i) - 1] > 0:\n arr[abs(i) - 1] = -arr[abs(i) - 1]\n else:\n rep = abs(i)\n for i in range(len(arr)):\n if arr[i] > 0:\n nonRep = i + 1\n return (rep, nonRep)", "def findtwoelement(arr, n):\n dict = {}\n for i in arr:\n if i not in dict:\n dict[i] = 1\n else:\n a = i\n dict[i] += 1\n break\n s = sum(arr) - a\n s1 = n * (n + 1) // 2 - s\n return [a, s1]", "def findtwoelement(arr, n):\n total_sum = n * (n + 1) // 2\n s1 = sum(set(arr))\n s2 = sum(arr)\n s = s2 - s1\n k = total_sum - s1\n return (s, k)", "def findtwoelement(arr, n):\n missing = -1\n repeat = -1\n mp = [0] * (n + 1)\n for i in range(n):\n mp[arr[i]] += 1\n for i in range(n + 1):\n if mp[i] == 2:\n repeat = i\n elif mp[i] == 0:\n missing = i\n return [repeat, missing]", "def findtwoelement(arr, n):\n repeat = -1\n missing = -1\n for i in range(n):\n if arr[abs(arr[i]) - 1] > 0:\n arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]\n else:\n repeat = abs(arr[i])\n for i in range(n):\n if arr[i] > 0:\n missing = i + 1\n return [repeat, missing]", "def findtwoelement(arr, n):\n val_hash = {}\n answer = []\n actual_sum = int(n * (n + 1) / 2)\n sum = 0\n for val in arr:\n if val_hash.get(val, 0) != 1:\n sum += val\n val_hash[val] = 1\n else:\n answer.append(val)\n answer.append(actual_sum - sum)\n return answer", "def findtwoelement(arr, n):\n t = n * (n + 1) // 2\n s1 = sum(set(arr))\n s2 = sum(arr)\n k = s2 - s1\n p = t - s1\n return (k, p)", "def findtwoelement(arr, n):\n\n def repeatNumber(arr):\n mp = {}\n for element in arr:\n if element not in mp:\n mp[element] = element\n else:\n return element\n sm = sum(arr)\n oneToN = [i for i in range(1, n + 1)]\n smOneToN = sum(oneToN)\n eq = sm - smOneToN\n rptNumber = repeatNumber(arr)\n msgNumber = rptNumber - eq\n return [rptNumber, msgNumber]", "def findtwoelement(arr, n):\n s = n * (n + 1) // 2\n s2 = n * (n + 1) * (2 * n + 1) // 6\n asum = 0\n a2sum = 0\n for ele in arr:\n asum += ele\n a2sum += ele * ele\n val1 = asum - s\n val2 = a2sum - s2\n val2 = val2 // val1\n x = (val1 + val2) // 2\n y = x - val1\n return [x, y]", "def findtwoelement(arr, n):\n ans = [0] * 2\n for i in range(n):\n if arr[abs(arr[i]) - 1] > 0:\n arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]\n else:\n ans[0] = abs(arr[i])\n for i in range(n):\n if arr[i] > 0:\n ans[1] = i + 1\n return ans", "def findtwoelement(arr, n):\n for i in range(n):\n arr[arr[i] % n - 1] += n\n missing = -1\n repated = -1\n for i in range(n):\n if arr[i] <= n:\n missing = i + 1\n if arr[i] > 2 * n:\n repated = i + 1\n return [repated, missing]", "def findtwoelement(arr, n):\n missing = 0\n dup = 0\n local_dict = dict.fromkeys(arr, 0)\n for item in arr:\n local_dict[item] += 1\n for number in range(1, n + 1):\n if not local_dict.get(number):\n missing = number\n elif local_dict[number] == 2:\n dup = number\n return [dup, missing]", "from collections import Counter\n\ndef findtwoelement(arr, n):\n A = Counter(arr)\n B = 0\n for (i, j) in A.items():\n if j > 1:\n B = i\n A = sum(arr) - B\n total = n * (n + 1) // 2\n A = total - A\n return (B, A)", "def findtwoelement(arr, n):\n sumn = n * (n + 1) / 2\n sumsn = n * (n + 1) * (2 * n + 1) / 6\n sumi = sum(arr)\n sums = 0\n for i in range(n):\n sums += arr[i] * arr[i]\n val1 = sumi - sumn\n val2 = sums - sumsn\n val2 = val2 / val1\n x = (val1 + val2) / 2\n y = x - val1\n return (int(x), int(y))", "def findtwoelement(arr, n):\n h = [0] * (n + 1)\n for i in range(n):\n h[arr[i]] += 1\n mi = -1\n twi = -1\n for i in range(1, n + 1):\n if h[i] == 2:\n twi = i\n elif h[i] == 0:\n mi = i\n if mi != -1 and twi != -1:\n break\n return (twi, mi)", "def findtwoelement(arr, n):\n from collections import defaultdict\n ans = []\n m = defaultdict(int)\n for i in range(1, n + 1):\n m[i] = 0\n for i in arr:\n m[i] += 1\n for (k, v) in m.items():\n if v == 2:\n ans.append(k)\n for (k, v) in m.items():\n if v == 0:\n ans.append(k)\n return ans", "import math\n\ndef findtwoelement(arr, n):\n sumArr = sum(arr)\n repeatingEle = 0\n for i in range(n):\n ele = abs(arr[i])\n if arr[ele - 1] > 0:\n arr[ele - 1] = -1 * arr[ele - 1]\n else:\n repeatingEle = ele\n break\n sumN = n * (n + 1) // 2\n missingEle = sumN - sumArr + repeatingEle\n return (repeatingEle, missingEle)", "def findtwoelement(arr, n):\n A = set(range(1, n + 1))\n mis = list(A - set(arr))[0]\n dic = {}\n for i in arr:\n if i not in dic:\n dic[i] = 0\n dic[i] += 1\n for (key, val) in dic.items():\n if val == 2:\n return [key, mis]", "def findtwoelement(arr, n):\n s = n * (n + 1) // 2\n p = n * (n + 1) * (2 * n + 1) // 6\n missing = 0\n repeating = 0\n ans = []\n for i in arr:\n s -= i\n p -= i * i\n missing = (s + p // s) // 2\n repeating = missing - s\n ans.append(repeating)\n ans.append(missing)\n return ans", "def findtwoelement(arr, n):\n x = []\n arr.sort()\n c = arr[0]\n for i in range(1, n):\n c += arr[i]\n if arr[i] == arr[i - 1]:\n x.append(arr[i])\n c = c - x[0]\n sum = n * (n + 1) // 2\n x.append(sum - c)\n return x", "def findtwoelement(arr, n):\n arr_set = set()\n repeated_num = 0\n missing_num = 0\n for num in arr:\n if num not in arr_set:\n arr_set.add(num)\n else:\n repeated_num = num\n for i in range(1, n + 1):\n if i not in arr_set:\n missing_num = i\n break\n result = (repeated_num, missing_num)\n return result", "def findtwoelement(arr, n):\n ans = [0, 0]\n l = [i for i in range(1, n + 1)]\n ans[1] = sum(l) - sum(set(arr))\n ans[0] = sum(arr) + ans[1] - sum(l)\n return ans", "def findtwoelement(arr, n):\n (missing, repeating) = (None, None)\n for i in range(len(arr)):\n if arr[abs(arr[i]) - 1] < 0:\n repeating = abs(arr[i])\n else:\n arr[abs(arr[i]) - 1] *= -1\n for i in range(len(arr)):\n if arr[i] > 0:\n missing = i + 1\n return [repeating, missing]", "def findtwoelement(arr, n):\n counter = {}\n for num in arr:\n if num in counter:\n a = num\n else:\n counter[num] = 1\n b = [0] * n\n for num in arr:\n b[num - 1] = 1\n x = []\n for i in range(n):\n if b[i] == 0:\n x.append(i + 1)\n x.append(a)\n return (a, x[0])", "def findtwoelement(arr, n):\n freq = [0] * (n + 1)\n missing_num = 0\n repeated_num = 0\n for i in range(n):\n freq[arr[i]] += 1\n for i in range(1, n + 1):\n if freq[i] == 0:\n missing_num = i\n elif freq[i] == 2:\n repeated_num = i\n return (repeated_num, missing_num)", "def findtwoelement(arr, n):\n freq = [0] * n\n for i in range(n):\n freq[arr[i] - 1] += 1\n return (freq.index(2) + 1, freq.index(0) + 1)", "def findtwoelement(arr, n):\n ans = [0] * n\n r = [-1, -1]\n for i in range(len(arr)):\n ans[arr[i] - 1] += 1\n for i in range(len(ans)):\n if ans[i] == 0:\n r[1] = i + 1\n if ans[i] == 2:\n r[0] = i + 1\n return r", "def findtwoelement(arr, n):\n SN = n * (n + 1) // 2\n S2N = n * (n + 1) * (2 * n + 1) // 6\n (missingNum, repeatingNum) = (0, 0)\n for i in range(n):\n SN -= arr[i]\n S2N -= arr[i] * arr[i]\n missingNum = (SN + S2N // SN) // 2\n repeatingNum = missingNum - SN\n ans = []\n ans.append(repeatingNum)\n ans.append(missingNum)\n return ans", "def findtwoelement(arr, n):\n n = len(arr)\n seen = set()\n repeating_num = missing_num = None\n for num in arr:\n if num in seen:\n repeating_num = num\n seen.add(num)\n for i in range(1, n + 1):\n if i not in seen:\n missing_num = i\n break\n return (repeating_num, missing_num)", "def findtwoelement(arr, n):\n l = [0 for i in range(len(arr))]\n for i in arr:\n l[i - 1] += 1\n return [l.index(2) + 1, l.index(0) + 1]", "from collections import *\n\ndef findtwoelement(arr, n):\n A = set(range(1, n + 1))\n B = set(arr)\n missing = list(A - B)[0]\n dic = Counter(arr)\n twice = 0\n for (key, val) in dic.items():\n if val == 2:\n twice = key\n break\n return [twice, missing]", "def findtwoelement(a, n):\n n = len(a)\n SN = n * (n + 1) // 2\n S2N = n * (n + 1) * (2 * n + 1) // 6\n (S, S2) = (0, 0)\n for i in range(n):\n S += a[i]\n S2 += a[i] * a[i]\n val1 = S - SN\n val2 = S2 - S2N\n val2 = val2 // val1\n x = (val1 + val2) // 2\n y = x - val1\n return [x, y]", "def findtwoelement(arr, n):\n d = {}\n ans = []\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n ans.append(i)\n k = range(1, n + 1)\n k = set(k).difference(set(arr))\n for i in k:\n ans.append(i)\n return ans", "def findtwoelement(A, n):\n (x, y) = (None, None)\n n = len(A)\n a = n * (n + 1) // 2\n a_dashed = sum(A)\n b = n * (n + 1) * (2 * n + 1) // 6\n b_dashed = 0\n for i in A:\n b_dashed += i * i\n rel1 = a - a_dashed\n rel2 = b - b_dashed\n rel3 = rel2 // rel1\n y = (rel3 + rel1) // 2\n x = y - rel1\n return [x, y]", "def findtwoelement(arr, n):\n sumofn = n * (n + 1) // 2\n sumsetarr = sum(set(arr))\n sumarr = sum(arr)\n missingnumber = sumofn - sumsetarr\n repeatednumber = sumarr - sumsetarr\n return [repeatednumber, missingnumber]", "def get_duplicate(arr, n):\n for i in range(n):\n idx = abs(arr[i]) - 1\n if arr[idx] < 0:\n return idx + 1\n arr[idx] = -arr[idx]\n return -1\n\ndef get_missing(arr, n):\n for i in range(n):\n idx = abs(arr[i]) - 1\n if arr[idx] > 0:\n arr[idx] = -arr[idx]\n for i in range(n):\n if arr[i] > 0:\n return i + 1\n\ndef findtwoelement(arr, n):\n duplicate = self.get_duplicate(arr, n)\n missing = self.get_missing(arr, n)\n return (duplicate, missing)", "def findtwoelement(arr, n):\n v = n * (n + 1) // 2\n g = sum(arr)\n j = set(arr)\n rep_element = g - sum(j)\n missing_element = v - sum(j)\n return (rep_element, missing_element)", "def findtwoelement(arr, n):\n (d, l, repeated_elem) = ({}, list(range(1, n + 1)), -1)\n for elem in arr:\n d.update({elem: d.get(elem, 0) + 1})\n if d[elem] == 2:\n repeated_elem = elem\n if repeated_elem == -1:\n return [0, 0]\n for elem in l:\n if elem not in d:\n return [repeated_elem, elem]", "def findtwoelement(arr, n):\n repeatingElement = 0\n missingElement = 0\n for i in range(len(arr)):\n if arr[abs(arr[i]) - 1] > 0:\n arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]\n else:\n repeatingElement = abs(arr[i])\n incrCount = 0\n decrCount = 0\n for i in range(len(arr)):\n if arr[i] > 0:\n missingElement = i + 1\n return [repeatingElement, missingElement]", "def findtwoelement(arr, n):\n xor = 0\n for i in range(n):\n xor = xor ^ arr[i]\n xor = xor ^ i + 1\n while xor & xor - 1 != 0:\n xor = xor & xor - 1\n a = 0\n b = 0\n for i in range(n):\n if arr[i] & xor:\n a = a ^ arr[i]\n else:\n b = b ^ arr[i]\n if i + 1 & xor:\n a = a ^ i + 1\n else:\n b = b ^ i + 1\n if a in arr:\n return [a, b]\n return [b, a]", "from collections import Counter\n\ndef findtwoelement(arr, n):\n A = Counter(arr)\n (re, mi) = (-1, -1)\n for i in range(1, n + 1):\n if A[i] == 1:\n pass\n elif A[i] == 2:\n re = i\n else:\n mi = i\n return [re, mi]", "def findtwoelement(arr, n):\n arr.sort()\n repeat = 0\n for i in range(n - 1):\n if arr[i] == arr[i + 1]:\n repeat = arr[i]\n arr2 = set([i for i in range(1, n + 1)])\n arr = set(arr)\n missing = arr2.difference(arr)\n miss = 0\n for i in missing:\n miss = i\n return (repeat, miss)", "def findtwoelement(arr, n):\n obj = {}\n lst = [0 for x in range(0, n + 2)]\n repeating_num = None\n missing_num = None\n for i in arr:\n if repeating_num is None:\n try:\n obj[i] = obj[i] + i\n repeating_num = i\n except:\n obj[i] = i\n try:\n lst[i] = i\n except:\n pass\n missing_num = lst[1:].index(0) + 1\n return (repeating_num, missing_num)", "def findtwoelement(arr, n):\n s_arr = sum(arr)\n s_arr_ele_sq = sum([ele ** 2 for ele in arr])\n s_n_natural_no = n * (n + 1) // 2\n s_sq_n_natural_no = n * (n + 1) * (2 * n + 1) // 6\n x_minus_y = s_n_natural_no - s_arr\n x_sq_minus_y_sq = s_sq_n_natural_no - s_arr_ele_sq\n x_plus_y = x_sq_minus_y_sq // x_minus_y\n x = (x_plus_y + x_minus_y) // 2\n y = (x_plus_y - x_minus_y) // 2\n return [y, x]", "def findtwoelement(arr, n):\n map = {}\n for i in range(n):\n if arr[i] not in map:\n map[arr[i]] = True\n else:\n x = arr[i]\n for i in range(1, n + 1):\n if i not in map:\n l = i\n return [x, l]", "def findtwoelement(arr, n):\n a = {}\n c = 0\n d = 0\n for i in arr:\n if i in a:\n a[i] += 1\n else:\n a[i] = 1\n count = 1\n while count < len(arr) + 1:\n if count in a:\n if a[count] == 2:\n c = count\n if count not in a:\n d = count\n count += 1\n return (c, d)", "def findtwoelement(arr, n):\n result = []\n dict = {}\n for i in arr:\n if i in dict:\n result.append(i)\n else:\n dict[i] = 1\n res = n * (n + 1) // 2 - sum(set(arr))\n result.append(res)\n return result", "def findtwoelement(arr, n):\n a = [0] * (n + 1)\n res = 0\n mis = 0\n for idx in range(n):\n a[arr[idx]] += 1\n for idx in range(1, len(a)):\n if a[idx] == 0:\n mis = idx\n if a[idx] > 1:\n res = idx\n return (res, mis)", "def findtwoelement(nums, n):\n for i in range(len(nums)):\n while nums[i] > 0 and nums[i] <= n and (nums[nums[i] - 1] != nums[i]):\n (nums[nums[i] - 1], nums[i]) = (nums[i], nums[nums[i] - 1])\n for i in range(n):\n if arr[i] != i + 1:\n return [arr[i], i + 1]", "def findtwoelement(arr, n):\n l = []\n a = [0] * n\n for i in arr:\n if a[i - 1] > 0:\n l.append(i)\n a[i - 1] += 1\n for i in range(n):\n if a[i] == 0:\n l.append(i + 1)\n return l", "def findtwoelement(arr, n):\n sum1 = sum(arr)\n sum2 = n * (n + 1) // 2\n z1 = sum1 - sum2\n sum3 = 0\n for i in arr:\n sum3 += i * i\n sum4 = 0\n for j in range(1, n + 1):\n sum4 = sum4 + j * j\n z2 = (sum3 - sum4) // z1\n r = (z1 + z2) // 2\n m = r - z1\n return [r, m]", "def findtwoelement(arr, n):\n arr.sort()\n l = [0, 0]\n miss = 1\n for i in range(0, len(arr)):\n if arr[i] == miss:\n miss += 1\n l[1] = miss\n for i in range(1, n):\n if arr[i - 1] == arr[i]:\n l[0] = arr[i]\n break\n return l", "def findtwoelement(arr, n):\n RmM = sum(arr) - n * (n + 1) // 2\n R2mM2 = sum([x * x for x in arr]) - n * (n + 1) * (2 * n + 1) // 6\n RpM = R2mM2 // RmM\n return [(RpM + RmM) // 2, (RpM - RmM) // 2]", "def findtwoelement(arr, n):\n mpp = {}\n li = []\n for i in arr:\n if i not in mpp:\n mpp[i] = 0\n else:\n mpp[i] += 1\n for i in range(1, n + 1):\n try:\n mpp[i] += 1\n except:\n mpp[i] = 0\n for i in mpp:\n if mpp[i] > 1:\n li.append(i)\n break\n for i in mpp:\n if mpp[i] == 0:\n li.append(i)\n break\n return li", "def findtwoelement1(nums, n):\n lookup = [0] * (n + 1)\n for num in nums:\n lookup[num] += 1\n result = [None, None]\n for num in range(1, n + 1):\n if lookup[num] == 0:\n result[1] = num\n elif lookup[num] > 1:\n result[0] = num\n return result\n\ndef findtwoelement(nums, n):\n sumRepeating = 0\n sumMissing = n * (n + 1) // 2\n sumSquareRepeating = 0\n sumSquareMissing = n * (n + 1) * (2 * n + 1) // 6\n for num in nums:\n sumRepeating += num\n sumSquareRepeating += num * num\n val1 = sumRepeating - sumMissing\n val2 = sumSquareRepeating - sumSquareMissing\n val2 = val2 // val1\n x = (val1 + val2) // 2\n y = x - val1\n return [x, y]", "def findtwoelement(nums, n):\n sumRepeating = 0\n sumMissing = n * (n + 1) // 2\n sumSquareRepeating = 0\n sumSquareMissing = n * (n + 1) * (2 * n + 1) // 6\n for num in nums:\n sumRepeating += num\n sumSquareRepeating += num * num\n val1 = sumRepeating - sumMissing\n val2 = sumSquareRepeating - sumSquareMissing\n val2 = val2 // val1\n x = (val1 + val2) // 2\n y = x - val1\n return [x, y]", "def findtwoelement(nums, n):\n lookup = [0] * (n + 1)\n for num in nums:\n lookup[num] += 1\n result = [None, None]\n for num in range(1, n + 1):\n if lookup[num] == 0:\n result[1] = num\n elif lookup[num] > 1:\n result[0] = num\n return result", "def findtwoelement(arr, n):\n repeating_element = -1\n missing_element = -1\n for i in range(n):\n index = abs(arr[i]) - 1\n if arr[index] < 0:\n repeating_element = abs(arr[i])\n else:\n arr[index] = -arr[index]\n for i in range(n):\n if arr[i] > 0:\n missing_element = i + 1\n break\n return [repeating_element, missing_element]", "def findtwoelement(arr, n):\n d = {}\n l = []\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n l.append(i)\n for i in range(1, n + 1):\n if i not in d:\n l.append(i)\n return l", "def findtwoelement(arr, n):\n h = set()\n dict1 = {}\n lst = []\n for i in range(1, n + 1):\n h.add(i)\n for i in arr:\n if i in dict1:\n dict1[i] = dict1[i] + 1\n else:\n dict1[i] = 1\n if dict1[i] == 2:\n lst.append(i)\n for i in h:\n if i not in dict1:\n lst.append(i)\n return lst", "import math\n\ndef findtwoelement(arr, n):\n sr = 0\n srr = 0\n su = 0\n sur = 0\n for i in range(n):\n sr += (i + 1) ** 2\n srr += arr[i] ** 2\n su += i + 1\n sur += arr[i]\n s1 = sr - srr\n m_r = su - sur\n m = round((s1 + m_r ** 2) / (2 * m_r))\n r = m - m_r\n return [r, m]", "def findtwoelement(arr, n):\n l = []\n arr.sort()\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] = d[i] + 1\n for (key, value) in d.items():\n if d[key] == 2:\n l.append(key)\n s = 0\n s1 = 0\n for i in range(1, n + 1):\n s = s + i\n for i in range(n):\n s1 = s1 + arr[i]\n diff = s - (s1 - l[0])\n l.append(diff)\n return l", "def findtwoelement(arr, n):\n ans = [0, 0]\n x = n * (n + 1) // 2\n x2 = n * (n + 1) * (2 * n + 1) // 6\n y = 0\n y2 = 0\n for i in arr:\n y += i\n y2 += i ** 2\n e1 = x - y\n e2 = (x2 - y2) // e1\n ans[1] = (e1 + e2) // 2\n ans[0] = (e2 - e1) // 2\n return ans", "def findtwoelement(arr, n):\n missing = 0\n duplicate = 0\n seen = set()\n for i in range(n):\n if arr[i] in seen:\n duplicate = arr[i]\n break\n seen.add(arr[i])\n arr_sum = 0\n for i in range(n):\n arr_sum += arr[i]\n arr_sum -= duplicate\n missing = n * (n + 1) // 2 - arr_sum\n return [duplicate, missing]", "def findtwoelement(arr, n):\n d = {}\n for i in range(n):\n d[i + 1] = 0\n for ele in arr:\n d[ele] += 1\n return (max(d, key=d.get), min(d, key=d.get))\n while i < n:\n if arr[i] != arr[arr[i] - 1]:\n temp = arr[i]\n arr[i] = arr[arr[i] - 1]\n arr[arr[i] - 1] = temp\n else:\n i += 1\n for i in range(n):\n if arr[i] != arr[arr[i] - 1]:\n return (arr[i], i + 1)", "def findtwoelement(arr, n):\n res = []\n for i in range(n):\n if arr[abs(arr[i]) - 1] > 0:\n arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]\n else:\n res.append(abs(arr[i]))\n for i in range(n):\n if arr[i] > 0:\n res.append(i + 1)\n return res", "def findtwoelement(arr, n):\n d = {}\n for i in range(n):\n d[i + 1] = 0\n for ele in arr:\n d[ele] += 1\n return (max(d, key=d.get), min(d, key=d.get))", "def findtwoelement(arr, n):\n res = []\n for i in range(0, n):\n while arr[i] - 1 != i:\n j = arr[i] - 1\n (arr[i], arr[j]) = (arr[j], arr[i])\n if arr[i] == arr[j]:\n break\n for i in range(0, n):\n if arr[i] - 1 != i:\n res.append(arr[i])\n res.append(i + 1)\n return res", "def findtwoelement(arr, n):\n Nsum = n * (n + 1) / 2\n realSum = sum(arr)\n den = Nsum - realSum\n sqSum = 0\n for i in arr:\n sqSum += i * i\n realSq = n * (n + 1) * (2 * n + 1) / 6\n num = realSq - sqSum\n s = num / den\n missing = (s + den) / 2\n repeat = s - missing\n return [int(repeat), int(missing)]", "def findtwoelement(arr, n):\n a_b = n * (n + 1) // 2 - sum(arr)\n a2_b2 = n * (n + 1) * (2 * n + 1) // 6 - sum([x ** 2 for x in arr])\n a = (a2_b2 + a_b ** 2) // (2 * a_b)\n return [a - a_b, a]", "from collections import Counter\n\ndef findtwoelement(arr, n):\n hm = Counter(arr)\n a = [0] * 2\n for i in range(1, n + 1):\n if i not in hm:\n a[1] = i\n if hm[i] > 1:\n a[0] = i\n return a", "def findtwoelement(arr, n):\n arr.sort()\n A = []\n for i in range(len(arr) - 1):\n if arr[i] == arr[i + 1]:\n A.append(arr[i])\n break\n a = set(arr)\n arr = list(a)\n N = n * (n + 1) // 2\n sum1 = 0\n for i in range(len(arr)):\n sum1 += arr[i]\n A.append(N - sum1)\n return A", "def findtwoelement(arr, n):\n N = n\n sum_N = n * (n + 1) // 2\n sum_N_squares = n * (n + 1) * (2 * n + 1) // 6\n sum_arr = sum(arr)\n sum_arr_squares = sum((x ** 2 for x in arr))\n diff_sum = sum_N - sum_arr\n diff_sum_squares = sum_N_squares - sum_arr_squares\n repeating = (diff_sum_squares // diff_sum - diff_sum) // 2\n missing = diff_sum + repeating\n return [repeating, missing]", "def findtwoelement(arr, n):\n a = []\n b = [0, 0]\n for i in range(1, n + 1):\n a.append(i)\n b[1] = sum(a) - sum(set(arr))\n b[0] = sum(arr) + b[1] - sum(a)\n return b", "def findtwoelement(arr, n):\n freq = [0] * (10 ** 5 + 1)\n for num in arr:\n freq[num] += 1\n result = [0] * 2\n for i in range(1, n + 1):\n if freq[i] == 0:\n result[1] = i\n if freq[i] == 2:\n result[0] = i\n return result"], "starter_code": "def findtwoelement( self,arr, n):\n", "input_output": {"inputs": ["N = 2\r\nArr[] = {2, 2}", "N = 3\r\nArr[] = {1, 3, 3}"], "outputs": ["2 1", "3 2"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/find-missing-and-repeating2512/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "findtwoelement", "task_id": "TACO_lite/21", "example": [[[2, [2, 2]], [3, [1, 3, 3]]], [null, null]]} +{"requirement": "Given a Binary Tree, print the diagonal traversal of the binary tree.\nConsider lines of slope -1 passing between nodes. Given a Binary Tree, print all diagonal elements in a binary tree belonging to same line.\nIf the diagonal element are present in two different subtress then left subtree diagonal element should be taken first and then right subtree. \nExample 1:\nInput :\n 8\n / \\\n 3 10\n / \\ \\\n 1 6 14\n / \\ /\n 4 7 13\nOutput : 8 10 14 3 6 7 13 1 4\nExplanation:\nDiagonal Traversal of binary tree : \n 8 10 14 3 6 7 13 1 4\nYour Task:\nYou don't need to read input or print anything. The task is to complete the function diagonal() that takes the root node as input argumets and returns the diagonal traversal of the given tree.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\nHere N is number of nodes.\nConstraints:\n1 <= Number of nodes<= 10^{5}\n1 <= Data of a node<= 10^{5}", "solutions": ["def diagonal(root):\n if root is None:\n return\n out = []\n node = root\n left_q = deque()\n while node:\n out.append(node.data)\n if node.left:\n left_q.appendleft(node.left)\n if node.right:\n node = node.right\n elif len(left_q) >= 1:\n node = left_q.pop()\n else:\n node = None\n return out", "def diagonal(root):\n q = []\n ans = []\n q.append(root)\n while q:\n a = q.pop(0)\n ans.append(a.data)\n if a.left:\n q.append(a.left)\n while a.right:\n ans.append(a.right.data)\n if a.right.left:\n q.append(a.right.left)\n a = a.right\n return ans", "from collections import defaultdict\n\ndef diagonal(root):\n ans = []\n d = defaultdict(list)\n\n def solve(root, l):\n if root.left == None and root.right == None:\n d[l].append(root.data)\n return\n if root.left:\n solve(root.left, l - 1)\n d[l].append(root.data)\n if root.right:\n solve(root.right, l)\n if root == None:\n return []\n solve(root, 0)\n l = []\n for i in d.keys():\n l.append(i)\n l.sort(reverse=-1)\n for i in l:\n ans.extend(d[i])\n return ans", "from collections import deque\n\ndef diagonal(root):\n q = deque()\n q.append(root)\n ans = []\n while q:\n x = q.popleft()\n while x is not None:\n if x.left:\n q.append(x.left)\n ans.append(x.data)\n x = x.right\n return ans", "def diagonal(root):\n vis = []\n n = root\n q = deque()\n while n:\n vis.append(n.data)\n if n.left:\n q.appendleft(n.left)\n if n.right:\n n = n.right\n elif len(q) >= 1:\n n = q.pop()\n else:\n n = None\n return vis", "def diagonal(root):\n res = []\n q = []\n q.append(root)\n\n def traverse(node):\n if node != None:\n res.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n traverse(node.right)\n while q != []:\n x = q.pop(0)\n traverse(x)\n return res", "from collections import defaultdict\n\ndef diagonal(root):\n d = defaultdict(list)\n\n def sol(root, i):\n if root.left == None and root.right == None:\n d[i].append(root.data)\n return\n d[i].append(root.data)\n if root.left:\n left = sol(root.left, i - 1)\n if root.right:\n right = sol(root.right, i)\n sol(root, 0)\n r = []\n for j in sorted(d.keys(), reverse=True):\n r.extend(d[j])\n return r", "def diagonal(root):\n\n def dig(root):\n if root is None:\n return []\n l1 = []\n q = []\n q = [root]\n while q:\n node = q.pop(0)\n while node:\n l1.append(node.data)\n if node.left:\n q.append(node.left)\n node = node.right\n return l1\n return dig(root)", "from collections import defaultdict\n\ndef diagonal(root):\n d = defaultdict(list)\n\n def solve(root, idx):\n if root.left == None and root.right == None:\n d[idx].append(root.data)\n return\n d[idx].append(root.data)\n if root.left:\n left = solve(root.left, idx - 1)\n if root.right:\n right = solve(root.right, idx)\n solve(root, 0)\n res = []\n for i in sorted(d.keys(), reverse=True):\n res.extend(d[i])\n return res", "def diagonal(root):\n d = {}\n\n def traverse(root, tag):\n if root != []:\n if tag in d:\n d[tag].append(root.data)\n else:\n d[tag] = [root.data]\n if root.left:\n traverse(root.left, tag - 1)\n if root.right:\n traverse(root.right, tag)\n traverse(root, 0)\n k = sorted(d.items(), key=lambda x: -x[0])\n ans = []\n for (i, j) in k:\n ans.extend(j)\n return ans", "def diagonal_traversal_helper(node, level, diagonal_map):\n if node is None:\n return\n if level in diagonal_map:\n diagonal_map[level].append(node.data)\n else:\n diagonal_map[level] = [node.data]\n diagonal_traversal_helper(node.left, level + 1, diagonal_map)\n diagonal_traversal_helper(node.right, level, diagonal_map)\n\ndef diagonal(root):\n diagonal_map = {}\n diagonal_traversal_helper(root, 0, diagonal_map)\n result = []\n for level in diagonal_map:\n result.extend(diagonal_map[level])\n return result", "def diagonal(root):\n q = []\n a = []\n if root == None:\n return\n q.append(root)\n while len(q) != 0:\n n = q[0]\n q.pop(0)\n while n:\n if n.left:\n q.append(n.left)\n a.append(n.data)\n n = n.right\n return a", "from collections import defaultdict\n\ndef diagonal(root):\n ans = []\n d = defaultdict(list)\n\n def dfs(x, l):\n d[l].append(x.data)\n if x.left:\n dfs(x.left, l + 1)\n if x.right:\n dfs(x.right, l)\n dfs(root, 0)\n ans = []\n for x in d:\n ans.extend(d[x])\n return ans", "def diagonal(root):\n if root == None:\n return []\n q = [root]\n tmp = []\n ans = []\n while q:\n nod = q.pop(0)\n while nod:\n ans.append(nod.data)\n if nod.left:\n tmp.append(nod.left)\n nod = nod.right\n if len(q) == 0:\n while tmp:\n q.append(tmp.pop(0))\n return ans", "def diagonal(root):\n q = deque()\n q.append(root)\n ans = []\n while len(q) >= 1:\n x = q.popleft()\n while x is not None:\n if x.left is not None:\n q.append(x.left)\n ans.append(x.data)\n x = x.right\n return ans", "def util(root, a):\n global d\n if root == None:\n return\n if d.get(a) == None:\n d[a] = [root.data]\n else:\n d[a].append(root.data)\n self.util(root.left, a - 1)\n self.util(root.right, a)\n\ndef diagonal(root):\n global d\n d = {}\n self.util(root, 0)\n ans = []\n for (k, v) in sorted(d.items(), reverse=True):\n for i in v:\n ans.append(i)\n return ans", "from collections import deque\n\ndef diagonal(root):\n queue = deque()\n ans = []\n queue.append(root)\n if root is None:\n return ans\n while queue:\n temp = queue.popleft()\n while temp:\n if temp.left:\n queue.append(temp.left)\n ans.append(temp.data)\n temp = temp.right\n return ans", "from collections import deque\n\ndef diagonal(root):\n hashmap = {}\n\n def solve(root, index):\n if root is None:\n return\n if index in hashmap:\n hashmap[index].append(root.data)\n else:\n hashmap[index] = [root.data]\n if root.left is not None:\n solve(root.left, index + 1)\n if root.right is not None:\n solve(root.right, index)\n solve(root, 0)\n ans = []\n for i in sorted(hashmap.keys()):\n ans += hashmap[i]\n return ans", "def diagonal(root):\n q = []\n res = []\n q.append(root)\n while len(q) > 0:\n p = q.pop(0)\n res.append(p.data)\n while p:\n if p.right != None:\n res.append(p.right.data)\n if p.left != None:\n q.append(p.left)\n p = p.right\n return res", "from collections import defaultdict\n\ndef diagonal(root):\n ans = []\n queue = [root]\n while queue:\n node = queue.pop(0)\n while node:\n ans.append(node.data)\n if node.left:\n queue.append(node.left)\n if node.right:\n node = node.right\n else:\n break\n return ans", "def diagonal(root):\n if root == None:\n return []\n queue = []\n queue.append(root)\n ans = []\n while queue:\n temp = queue.pop(0)\n while temp:\n ans.append(temp.data)\n if temp.left != None:\n queue.append(temp.left)\n if temp.right:\n temp = temp.right\n else:\n break\n return ans", "def diagonal(root):\n result = list()\n node = root\n left_q = deque()\n while node:\n result.append(node.data)\n if node.left:\n left_q.appendleft(node.left)\n if node.right:\n node = node.right\n else:\n node = left_q.pop() if len(left_q) >= 1 else None\n return result", "from collections import deque\n\ndef diagonal(root):\n res = []\n q = deque()\n q.append(root)\n while len(q):\n p = q.popleft()\n res.append(p.data)\n while p:\n if p.left:\n q.append(p.left)\n if p.right:\n res.append(p.right.data)\n p = p.right\n return res", "from collections import *\n\ndef __init__():\n self.d = {}\n\ndef diagonal(root):\n q = deque()\n q.append([root, 0, 0])\n while q:\n (v, x, y) = q.pop()\n if y - x in self.d:\n self.d[y - x].append(v.data)\n else:\n self.d[y - x] = [v.data]\n if v.right:\n q.append([v.right, x + 1, y + 1])\n if v.left:\n q.append([v.left, x - 1, y + 1])\n answer = []\n for i in sorted(self.d):\n answer.extend(self.d[i])\n return answer", "def diagonal(root):\n\n def diagnolView(root, dict, level):\n if root is None:\n return\n if level not in dict:\n dict[level] = [root.data]\n else:\n dict[level].append(root.data)\n diagnolView(root.left, dict, level + 1)\n diagnolView(root.right, dict, level)\n dict = {}\n diagnolView(root, dict, 0)\n arr = []\n for i in dict:\n arr += dict[i]\n return arr", "def rec_sol(root, d, save_dict):\n try:\n save_dict[d].append(root.data)\n except:\n save_dict[d] = [root.data]\n if root.left != None:\n self.rec_sol(root.left, d + 1, save_dict)\n if root.right != None:\n self.rec_sol(root.right, d, save_dict)\n return\n\ndef diagonal(root):\n save_dict = {}\n self.rec_sol(root, 0, save_dict)\n final = []\n for i in save_dict:\n for el in save_dict[i]:\n final.append(el)\n return final", "def diagonal(root):\n s = []\n ans = []\n s.append(root)\n while len(s) != 0:\n size = len(s)\n while size != 0:\n rn = s.pop(0)\n while rn != None:\n ans.append(rn.data)\n if rn.left != None:\n s.append(rn.left)\n rn = rn.right\n size -= 1\n return ans", "def diagonal(root):\n queue = []\n l = []\n queue.append(root)\n while len(queue) > 0:\n temp = queue.pop(0)\n while temp:\n if temp.left:\n queue.append(temp.left)\n l.append(temp.data)\n temp = temp.right\n return l", "def diagonal(root):\n q = deque([root])\n res = []\n while q:\n temp = q.popleft()\n while temp:\n res.append(temp.data)\n if temp.left:\n q.append(temp.left)\n temp = temp.right\n return res", "def diagonal(root):\n ans = []\n q = deque([])\n q.append(root)\n while q:\n n = len(q)\n for _ in range(len(q)):\n d = q.popleft()\n ans.append(d.data)\n if d.left:\n q.append(d.left)\n while d.right:\n d = d.right\n ans.append(d.data)\n if d.left:\n q.append(d.left)\n return ans", "def diagonal(root):\n\n def helper(root, dic, diagonal):\n if root == None:\n return\n if diagonal in dic:\n dic[diagonal].append(root.data)\n else:\n dic[diagonal] = [root.data]\n helper(root.left, dic, diagonal + 1)\n helper(root.right, dic, diagonal)\n return dic\n if not root:\n return\n dic = {}\n dic = helper(root, dic, 0)\n l = list(dic.keys())\n l.sort()\n res = []\n for k in l:\n res += dic[k]\n return res", "from queue import LifoQueue\nfrom collections import defaultdict\n\ndef pre_order(root, level, diagonals):\n diagonals[level].append(root.data)\n if root.left:\n pre_order(root.left, level + 1, diagonals)\n if root.right:\n pre_order(root.right, level, diagonals)\n\ndef diagonal(root):\n diagonals_map = defaultdict(list)\n output = []\n pre_order(root, 0, diagonals_map)\n for level in diagonals_map:\n output.extend(diagonals_map[level])\n return output", "def diagonal(root):\n if not root:\n return []\n q = [root]\n res = []\n while q:\n curr = q.pop(0)\n while curr:\n res.append(curr.data)\n if curr.left:\n q.append(curr.left)\n curr = curr.right\n return res", "def diagonal(root):\n\n def find(root, dig, dict):\n if root is None:\n return\n if dig not in dict:\n dict[dig] = []\n dict[dig].append(root.data)\n find(root.left, dig + 1, dict)\n find(root.right, dig, dict)\n ans = []\n dict = {}\n find(root, 0, dict)\n for dig in dict:\n for num in dict[dig]:\n ans.append(num)\n return ans", "def diagonal(root):\n if not root:\n return []\n q = deque([root])\n res = []\n while q:\n for i in range(len(q)):\n curr = q.popleft()\n while curr:\n res.append(curr.data)\n if curr.left:\n q.append(curr.left)\n curr = curr.right\n return res", "def diagonal(root):\n if root == None:\n return []\n ans = []\n q = []\n q.append(root)\n while len(q) != 0:\n s = len(q)\n while s != 0:\n curr = q.pop(0)\n while curr != None:\n ans.append(curr.data)\n if curr.left != None:\n q.append(curr.left)\n if curr.right != None:\n curr = curr.right\n else:\n break\n s -= 1\n return ans", "from collections import deque\n\ndef diagonal(root):\n q = deque()\n q.append(root)\n ans = []\n while q:\n curr = q.popleft()\n while curr:\n ans.append(curr.data)\n if curr.left:\n q.append(curr.left)\n curr = curr.right\n return ans", "def diagonal(root):\n l = []\n queue = [root]\n while len(queue) > 0:\n s = len(queue)\n while s > 0:\n node = queue.pop(0)\n while node != None:\n l.append(node.data)\n if node.left:\n queue.append(node.left)\n node = node.right\n s -= 1\n return l", "def diagonal(root):\n ans = []\n Q = [root]\n s = 1\n while Q != []:\n m = 0\n while s:\n a = Q.pop(0)\n while a:\n if a.left:\n Q.append(a.left)\n m += 1\n ans.append(a.data)\n a = a.right\n s -= 1\n s = m\n return ans", "def diagonal(root):\n q = [root]\n ans = []\n while q:\n l = len(q)\n for i in range(l):\n root = q.pop(0)\n temp = root\n while temp:\n ans.append(temp.data)\n if temp.left:\n q.append(temp.left)\n temp = temp.right\n return ans", "def diagonal(root):\n q = []\n ans = []\n if root is None:\n return ans\n q.append(root)\n while q:\n temp = q.pop(0)\n while temp:\n if temp.left:\n q.append(temp.left)\n ans.append(temp.data)\n temp = temp.right\n return ans", "def diagonal(root):\n arr = [root]\n ans = []\n while len(arr) > 0:\n temp = arr.pop(0)\n while temp is not None:\n if temp.left:\n arr.append(temp.left)\n ans.append(temp.data)\n temp = temp.right\n return ans", "def diagonal(root):\n q = [root]\n (temp, res) = ([], [])\n while q:\n node = q.pop(0)\n res.append(node.data)\n if node.left:\n temp.append(node.left)\n if node.right:\n q.append(node.right)\n if not q and temp:\n q.append(temp.pop(0))\n return res", "def diagonal(root):\n if not root:\n return\n (queue, result) = ([], [])\n queue.append(root)\n while len(queue) > 0:\n n = len(queue)\n ans = []\n while n > 0:\n temp = queue[0]\n queue.pop(0)\n while temp is not None:\n ans.append(temp.data)\n if temp.left is not None:\n queue.append(temp.left)\n temp = temp.right\n n -= 1\n result.append(' '.join(map(str, ans)))\n return result", "from collections import defaultdict\n\ndef diagonal(root):\n if root is None:\n return []\n dict1 = defaultdict(list)\n q = [(root, 0)]\n while len(q):\n for i in range(len(q)):\n (s, d) = q.pop()\n if s.right:\n q.append((s.right, d))\n if s.left:\n q.append((s.left, d + 1))\n dict1[d].append(s.data)\n res = []\n for i in sorted(dict1):\n res.extend(dict1[i])\n return res", "def diagonal(root):\n if not root:\n return []\n ans = []\n q = [root]\n while len(q) > 0:\n node = q.pop(0)\n while node:\n if node.left:\n q.append(node.left)\n ans.append(node.data)\n node = node.right\n return ans", "def diagonal(root):\n queue = []\n queue.append(root)\n ans = []\n\n def dfs(root):\n if root == None:\n return\n ans.append(root.data)\n if root.left:\n queue.append(root.left)\n if root.right:\n dfs(root.right)\n while len(queue) != 0:\n root = queue.pop(0)\n dfs(root)\n return ans", "from collections import deque\n\ndef diagonal(root):\n ans = []\n q = deque()\n new_node = Node(0)\n new_node.left = root\n q.append(new_node)\n while len(q) > 0:\n node = q.popleft()\n node = node.left\n while node is not None:\n ans.append(node.data)\n if node.left is not None:\n q.append(node)\n node = node.right\n return ans", "from collections import deque\n\ndef diagonal(root):\n q = deque()\n if root is None:\n return []\n q.appendleft(root)\n res = []\n while len(q) > 0:\n t = q.pop()\n while t is not None:\n res.append(t.data)\n if t.left is not None:\n q.appendleft(t.left)\n t = t.right\n return res", "def diagonal(root):\n queue = []\n ans = []\n queue.append(root)\n while queue:\n curr = queue.pop(0)\n while curr:\n if curr.left:\n queue.append(curr.left)\n ans.append(curr.data)\n curr = curr.right\n return ans", "def diagonal(root):\n result = []\n if root == None:\n return result\n q = deque()\n q.append(root)\n while len(q) != 0:\n current = q.popleft()\n while current:\n result.append(current.data)\n if current.left:\n q.append(current.left)\n current = current.right\n return result", "import collections\n\ndef diagonal(root):\n res = []\n q = collections.deque()\n q.append(root)\n while q:\n a = q.popleft()\n res.append(a.data)\n if a.left:\n q.append(a.left)\n t = a.right\n if t:\n res.append(t.data)\n while t:\n if t.left:\n q.append(t.left)\n if t.right:\n res.append(t.right.data)\n t = t.right\n return res", "def diagonal(root):\n\n def diag(root, x, d):\n if root is None:\n return\n try:\n d[x].append(root.data)\n except KeyError:\n d[x] = [root.data]\n diag(root.left, x + 1, d)\n diag(root.right, x, d)\n d = dict()\n a = []\n diag(root, 0, d)\n for i in d:\n for j in d[i]:\n a.append(j)\n return a", "import collections\n\ndef dfs(node):\n if not node:\n return\n self.diag_lst.append(node.data)\n if node.left:\n self.q.append(node.left)\n self.dfs(node.right)\n return\n\ndef diagonal(root):\n self.q = collections.deque()\n self.diag_lst = []\n self.q.append(root)\n while self.q:\n self.dfs(self.q.popleft())\n return self.diag_lst", "def diagonal(root):\n right = []\n res = []\n q = [root]\n while q or right:\n if q:\n x = q.pop(0)\n else:\n x = right.pop(0)\n if x.right:\n q.append(x.right)\n if x.left:\n right.append(x.left)\n res.append(x)\n for i in range(len(res)):\n res[i] = res[i].data\n return res", "def diagonal(root):\n temp = []\n result = []\n\n def trav(root):\n if root == None:\n return\n result.append(root.data)\n if root.left != None:\n temp.append(root.left)\n if root.right == None:\n if len(temp) == 0:\n return\n x = temp.pop(0)\n trav(x)\n else:\n trav(root.right)\n trav(root)\n return result", "def diagonal(root):\n if root is None:\n return\n level = []\n ansArr = []\n while root:\n ansArr.append(root.data)\n if root.left:\n level.append(root.left)\n if root.right:\n root = root.right\n else:\n if not level:\n break\n root = level.pop(0)\n return ansArr", "def diagonal(root):\n q = deque()\n q.append(root)\n ans = []\n while len(q) > 0:\n curr = q.popleft()\n while curr is not None:\n ans.append(curr.data)\n if curr.left is not None:\n q.append(curr.left)\n curr = curr.right\n return ans", "def diagonal(root):\n ans = []\n if root is None:\n return ans\n import collections\n queue = collections.deque()\n queue.append(root)\n while len(queue) != 0:\n curr = queue.popleft()\n while curr is not None:\n ans.append(curr.data)\n if curr.left != None:\n queue.append(curr.left)\n curr = curr.right\n return ans", "def diagonal(root):\n traverse_queue = [root]\n final_result = []\n while len(traverse_queue) > 0:\n node_pop = traverse_queue.pop(0)\n final_result.append(node_pop.data)\n curr = node_pop\n while curr is not None:\n if curr.left is not None:\n traverse_queue.append(curr.left)\n curr = curr.right\n if curr is not None:\n final_result.append(curr.data)\n return final_result"], "starter_code": "def _init_(val):\n", "input_output": {"inputs": ["8\r\n / \\\r\n 3 10\r\n / \\ \\\r\n 1 6 14\r\n / \\ /\r\n 4 7 13"], "outputs": ["8 10 14 3 6 7 13 1 4"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/diagonal-traversal-of-binary-tree/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "_init_", "task_id": "TACO_lite/34", "example": [[], []]} +{"requirement": "# Kata Task\n\nI have a cat and a dog.\n\nI got them at the same time as kitten/puppy. That was `humanYears` years ago.\n\nReturn their respective ages now as [`humanYears`,`catYears`,`dogYears`]\n\nNOTES:\n* humanYears >= 1\n* humanYears are whole numbers only\n\n## Cat Years\n\n* `15` cat years for first year\n* `+9` cat years for second year\n* `+4` cat years for each year after that\n\n## Dog Years\n\n* `15` dog years for first year\n* `+9` dog years for second year\n* `+5` dog years for each year after that\n\n\n\n**References**\n\n* http://www.catster.com/cats-101/calculate-cat-age-in-cat-years\n* http://www.slate.com/articles/news_and_politics/explainer/2009/05/a_dogs_life.html\n\n\n\nIf you liked this Kata there is another related one here", "solutions": ["def human_years_cat_years_dog_years(x):\n return [x, 24 + (x - 2) * 4 if x != 1 else 15, 24 + (x - 2) * 5 if x != 1 else 15]", "def human_years_cat_years_dog_years(human_years):\n catYears = 0\n dogYears = 0\n if human_years == 1:\n catYears += 15\n dogYears += 15\n return [human_years, catYears, dogYears]\n elif human_years == 2:\n catYears += 24\n dogYears += 24\n return [human_years, catYears, dogYears]\n elif human_years > 2:\n catYears += 24\n dogYears += 24\n years = human_years - 2\n catYears += years * 4\n dogYears += years * 5\n return [human_years, catYears, dogYears]\n return [0, 0, 0]", "def human_years_cat_years_dog_years(n):\n cat_years = 15 + 9 * (n > 1) + 4 * (n - 2) * (n > 2)\n dog_years = 15 + 9 * (n > 1) + 5 * (n - 2) * (n > 2)\n return [n, cat_years, dog_years]", "def human_years_cat_years_dog_years(hy):\n return [hy, 16 + 4 * hy, 14 + 5 * hy] if hy > 1 else [1, 15, 15]", "def human_years_cat_years_dog_years(human_years, dog_years=15, cat_years=15):\n if human_years == 1:\n pass\n elif human_years == 2:\n cat_years = dog_years = 24\n else:\n cat_years = 4 * human_years + 16\n dog_years = 5 * human_years + 14\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(h):\n (c, d) = (0, 0)\n if h == 1:\n (c, d) = (15, 15)\n elif h >= 2:\n (c, d) = (24, 24)\n for i in range(h - 2, 0, -1):\n c += 4\n d += 5\n return [h, c, d]", "def human_years_cat_years_dog_years(human_years):\n catYears = 15\n DogYears = 15\n if human_years == 1:\n return [human_years, catYears, DogYears]\n elif human_years == 2:\n return [human_years, catYears + 9, DogYears + 9]\n elif human_years >= 3:\n n = human_years - 3\n s = 24 + n * 4 + 4\n f = 24 + n * 5 + 5\n return [human_years, s, f]", "def human_years_cat_years_dog_years(human_years):\n if human_years > 2:\n cat_years = (human_years - 2) * 4 + 24\n dog_years = (human_years - 2) * 5 + 24\n elif human_years == 2:\n cat_years = 24\n dog_years = 24\n else:\n cat_years = 15\n dog_years = 15\n return [human_years, cat_years, dog_years]", "human_years_cat_years_dog_years = lambda h: [h] + [15 * (h >= 1) + 9 * (h >= 2) + (h - 2) * y * (h > 2) for y in [4, 5]]", "def human_years_cat_years_dog_years(h):\n return [h, 15 + 9 * (h >= 2) + 4 * max(h - 2, 0), 15 + 9 * (h >= 2) + 5 * max(h - 2, 0)]", "def human_years_cat_years_dog_years(years):\n return [years, 16 + 4 * years, 14 + 5 * years] if years > 1 else [1, 15, 15]", "def human_years_cat_years_dog_years(human_years):\n catYears = 0\n dogYears = 0\n if human_years < 2:\n catYears = human_years * 15\n dogYears = catYears\n elif human_years < 3:\n catYears = 15 + 9\n dogYears = catYears\n else:\n catYears = (human_years - 2) * 4 + 24\n dogYears = (human_years - 2) * 5 + 24\n return [human_years, catYears, dogYears]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n return [1, 15, 15]\n years_after_2nd = human_years - 2\n cat_years = 24 + 4 * years_after_2nd\n dog_years = 24 + 5 * years_after_2nd\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(human_years):\n CAT_YEARS_FIRST = 14\n DOG_YEARS_FIRST = 14\n CAT_YEARS_SECOND = 8\n DOG_YEARS_SECOND = 8\n CAT_YEARS_THIRD = 4\n DOG_YEARS_THIRD = 5\n if human_years == 1:\n return [human_years, human_years + CAT_YEARS_FIRST, human_years + DOG_YEARS_FIRST]\n elif human_years == 2:\n return [human_years, human_years + CAT_YEARS_FIRST + CAT_YEARS_SECOND, human_years + DOG_YEARS_FIRST + DOG_YEARS_SECOND]\n else:\n return [human_years, CAT_YEARS_FIRST + CAT_YEARS_SECOND + CAT_YEARS_THIRD * (human_years - 2) + 2, DOG_YEARS_FIRST + DOG_YEARS_SECOND + DOG_YEARS_THIRD * (human_years - 2) + 2]", "from functools import partial\n\ndef human_years_cat_years_dog_years(human_years):\n return [age_func(human_years) for age_func in (human_age, cat_age, dog_age)]\n\ndef critter_age(human_years, critter_years_multipliers):\n critter_age = previous_year = 0\n for (year, multiplier) in critter_years_multipliers:\n is_older = human_years > year\n years_difference = (year if is_older else human_years) - previous_year\n critter_age += multiplier * years_difference\n if not is_older:\n break\n previous_year = year\n return critter_age\ninfinity = float('inf')\nhuman_age = partial(critter_age, critter_years_multipliers=((infinity, 1),))\ncat_age = partial(critter_age, critter_years_multipliers=((1, 15), (2, 9), (infinity, 4)))\ndog_age = partial(critter_age, critter_years_multipliers=((1, 15), (2, 9), (infinity, 5)))", "def human_years_cat_years_dog_years(human_years):\n ages = [0, 0, 0]\n if human_years == 1:\n ages[0] = 1\n ages[1] = 15\n ages[2] = 15\n if human_years == 2:\n ages[0] = 2\n ages[1] = 24\n ages[2] = 24\n if human_years >= 3:\n ages[0] = human_years\n ages[1] = 24 + (human_years - 2) * 4\n ages[2] = 24 + (human_years - 2) * 5\n return ages", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n return [1, 15, 15]\n if human_years == 2:\n return [2, 24, 24]\n return [human_years, (human_years - 2) * 4 + 24, (human_years - 2) * 5 + 24]", "def human_years_cat_years_dog_years(human_years):\n cat_years = 15 if human_years == 1 else 15 + 9 if human_years == 2 else 15 + 9 + (human_years - 2) * 4\n dog_years = 15 if human_years == 1 else 15 + 9 if human_years == 2 else 15 + 9 + (human_years - 2) * 5\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(human_years):\n a = 15 + 9 * int(human_years >> 1 != 0)\n return [human_years, a + 4 * max(0, human_years - 2), a + 5 * max(0, human_years - 2)]", "def human_years_cat_years_dog_years(human_years):\n cat_years = (lambda y: 15 + 9 * (0, 1)[y - 1 > 0] + 4 * (y - 2) * (0, 1)[y - 2 > 0])(human_years)\n dog_years = (lambda y: 15 + 9 * (0, 1)[y - 1 > 0] + 5 * (y - 2) * (0, 1)[y - 2 > 0])(human_years)\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(n):\n return [n, 15 if n == 1 else 4 * (n + 4), 15 if n == 1 else 5 * n + 14]", "from functools import partial\ninfinity = float('inf')\n\ndef human_years_cat_years_dog_years(human_years):\n age = Age.from_human(human_years)\n return [age.as_human, age.as_cat, age.as_dog]\n\ndef __new__(meta, name, bases, namespace):\n attr_name = namespace.pop('_attr_name_', 'normalized_age')\n conversions = namespace.pop('_conversions_', {})\n if conversions:\n\n def as_(self, year_to_multiplier):\n age = getattr(self, attr_name)\n converted_age = previous_year = 0\n for (year, multiplier) in year_to_multiplier:\n is_older = age > year\n years_difference = (year if is_older else age) - previous_year\n converted_age += multiplier * years_difference\n if not is_older:\n break\n previous_year = year\n return converted_age\n for (name, year_to_multiplier) in conversions.items():\n namespace['from_' + name] = classmethod(partial(meta.__from, year_to_multiplier=year_to_multiplier))\n namespace['as_' + name] = property(partial(as_, year_to_multiplier=year_to_multiplier))\n\n def __init__(self, normalized_age):\n setattr(self, attr_name, normalized_age)\n namespace['__init__'] = __init__\n return super().__new__(meta, name, bases, namespace)\n\ndef __from(cls, age, year_to_multiplier):\n normalized_age = previous_year = 0\n for (year, multiplier) in year_to_multiplier:\n years_difference = year - previous_year\n max_age_in_range = multiplier * years_difference\n if age <= max_age_in_range:\n normalized_age += age / multiplier\n break\n age -= max_age_in_range\n previous_year = year\n normalized_age += years_difference\n return cls(normalized_age)", "def human_years_cat_years_dog_years(hy):\n cy = 15 + (hy > 1) * (4 * hy + 1)\n dy = 15 + (hy > 1) * (5 * hy - 1)\n return [hy, cy, dy]", "def human_years_cat_years_dog_years(human_years):\n cat = sum([15, 9, (human_years - 2) * 4][:human_years])\n dog = sum([15, 9, (human_years - 2) * 5][:human_years])\n return [human_years, cat, dog]", "human_years_cat_years_dog_years = lambda n: [n] + [15 * (n > 0) + 9 * (n > 1) + d * max(0, n - 2) for d in (4, 5)]", "human_years_cat_years_dog_years = lambda h: [1, 15, 15] if h == 1 else [2, 24, 24] if h == 2 else [h, 24 + 4 * (h - 2), 24 + 5 * (h - 2)]", "def human_years_cat_years_dog_years(human_years):\n (cat_years, dog_years) = (0, 0)\n if human_years > 1:\n cat_years = 24 + (human_years - 2) * 4\n dog_years = 24 + (human_years - 2) * 5\n else:\n cat_years = dog_years = 15\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(y):\n return [y, 24 + 4 * (y - 2), 24 + 5 * (y - 2)] if y >= 2 else [y, y * 9 + 6, y * 9 + 6]", "YRS = (15, 15 + 9, (4, 5))\n\ndef human_years_cat_years_dog_years(human_years):\n return [human_years, *({0: YRS[0]}.get(human_years - 1, k * (human_years - 2) + YRS[1]) for k in YRS[-1])]", "def human_years_cat_years_dog_years(human_years):\n return [human_years, *(dict(enumerate((15, 24))).get(human_years - 1, k * (human_years - 2) + 24) for k in (4, 5))]", "def human_years_cat_years_dog_years(y):\n return [y, 16 + 4 * y, 14 + 5 * y] if y > 1 else [1, 15, 15]", "def human_years_cat_years_dog_years(h):\n cat = sum([15 if x == 0 else 9 if x == 1 else 4 for x in range(h)])\n return [h, cat, cat + h - 2 if h > 2 else cat]", "def human_years_cat_years_dog_years(h):\n l = list(range(1, h + 1))\n return [h, 15 * len(l[0:1]) + 9 * len(l[1:2]) + 4 * len(l[2:]), 15 * len(l[0:1]) + 9 * len(l[1:2]) + 5 * len(l[2:])]", "def human_years_cat_years_dog_years(human_years):\n catYears = 15\n if human_years == 2:\n catYears = 15 + 9\n if human_years >= 3:\n catYears = 24 + (human_years - 2) * 4\n dogYears = 15\n if human_years == 2:\n dogYears = 15 + 9\n if human_years >= 3:\n dogYears = 24 + (human_years - 2) * 5\n return [human_years, catYears, dogYears]", "def human_years_cat_years_dog_years(human_years):\n return [human_years, sum([15 if x == 1 else 9 if x == 2 else 4 for x in range(1, human_years + 1)]), sum([15 if x == 1 else 9 if x == 2 else 5 for x in range(1, human_years + 1)])]", "from typing import List\n\ndef human_years_cat_years_dog_years(human_years: int) -> List[int]:\n __get_animals_years_multiplier = lambda _def: [{1: 15, 2: 9}.get(_it, _def) for _it in list(range(1, human_years + 1))]\n return [human_years, sum(__get_animals_years_multiplier(4)), sum(__get_animals_years_multiplier(5))]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n dog = 15\n cat = 15\n elif human_years == 2:\n dog = 24\n cat = 24\n else:\n dog = 24 + int(human_years - 2) * 5\n cat = 24 + int(human_years - 2) * 4\n return [human_years, cat, dog]", "def human_years_cat_years_dog_years(human_years):\n if human_years >= 1:\n cat_years = 15\n dog_years = 15\n if human_years >= 2:\n cat_years += 9\n dog_years += 9\n for i in range(human_years - 2):\n cat_years += 4\n dog_years += 5\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(human_years):\n cat_years = 15 + 9 * (human_years >= 2) + 4 * (human_years - 2) * (human_years >= 3)\n dog_years = 15 + 9 * (human_years >= 2) + 5 * (human_years - 2) * (human_years >= 3)\n return [human_years, cat_years, dog_years]", "human_years_cat_years_dog_years = lambda y: [y, y * 4 + (16 if y > 1 else 11 if y == 1 else 0), y * 5 + (14 if y > 1 else 10 if y == 1 else 0)]", "def human_years_cat_years_dog_years(human_years):\n if human_years >= 2:\n catYears = 15 + 9 + (human_years - 2) * 4\n dogYears = 15 + 9 + (human_years - 2) * 5\n return [human_years, catYears, dogYears]\n else:\n return [human_years, 15, 15]", "def human_years_cat_years_dog_years(human_years):\n catYears = 0\n dogYears = 0\n humanYears = human_years\n for i in range(human_years):\n if i == 0:\n catYears = catYears + 15\n dogYears = dogYears + 15\n if i == 1:\n catYears = catYears + 9\n dogYears = dogYears + 9\n if i > 1:\n catYears = catYears + 4\n dogYears = dogYears + 5\n return [humanYears, catYears, dogYears]", "def human_years_cat_years_dog_years(human_years):\n c = 15\n d = 15\n if human_years == 2:\n c = 15 + 9\n d = 15 + 9\n if human_years > 2:\n c = 24 + (human_years - 2) * 4\n d = 24 + (human_years - 2) * 5\n return [human_years, c, d]", "def human_years_cat_years_dog_years(hy):\n return [hy, 15 if hy == 1 else 24 if hy == 2 else 24 + (hy - 2) * 4, 15 if hy == 1 else 24 if hy == 2 else 24 + (hy - 2) * 5]", "def human_years_cat_years_dog_years(human_years):\n animal_first_two_years = 15 if human_years > 0 else 0\n animal_first_two_years += 9 if human_years > 1 else 0\n animal_last_years = max(0, human_years - 2)\n return [human_years, animal_first_two_years + 4 * animal_last_years, animal_first_two_years + 5 * animal_last_years]", "def human_years_cat_years_dog_years(human_years):\n b = 0\n c = 0\n if human_years == 1:\n b = 15\n c = 15\n elif human_years == 2:\n b = 24\n c = 24\n else:\n b = 24 + (human_years - 2) * 4\n c = 24 + (human_years - 2) * 5\n return [human_years, b, c]", "def human_years_cat_years_dog_years(human_years):\n dog_years = 15 + min(human_years - 1, 1) * 9 + max(human_years - 2, 0) * 5\n cat_years = 15 + min(human_years - 1, 1) * 9 + max(human_years - 2, 0) * 4\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(hy):\n if hy == 1:\n return [1, 15, 15]\n elif hy == 2:\n return [2, 24, 24]\n elif hy > 2:\n return [hy, 24 + 4 * (hy - 2), 24 + 5 * (hy - 2)]\n return [0, 0, 0]", "def human_years_cat_years_dog_years(human):\n if human == 1:\n return [human, 15, 15]\n if human == 2:\n return [human, 24, 24]\n if human >= 3:\n return [human, (human - 2) * 4 + 24, (human - 2) * 5 + 24]", "def human_years_cat_years_dog_years(human):\n cat = 0\n dog = 0\n if human >= 1:\n cat += 15\n dog += 15\n if human >= 2:\n cat += 9\n dog += 9\n if human >= 3:\n n = human - 2\n cat += n * 4\n dog += n * 5\n return [human, cat, dog]", "def human_years_cat_years_dog_years(hy):\n base = 15 * (hy >= 1) + 9 * (hy >= 2)\n rest = max(0, hy - 2)\n cy = base + 4 * rest\n dy = base + 5 * rest\n return [hy, cy, dy]", "def human_years_cat_years_dog_years(h):\n if h == 1:\n return [h, 15, 15]\n if h == 2:\n return [h, 24, 24]\n return [h, 24 + (h - 2) * 4, 24 + (h - 2) * 5]", "from itertools import accumulate, repeat\n\ndef human_years_cat_years_dog_years(years):\n if years >= 2:\n return [years, 4 * (years - 2) + 24, 5 * (years - 2) + 24]\n elif years == 1:\n return [1, 15, 15]", "def human_years_cat_years_dog_years(human_years):\n cat_years = 0\n dog_years = 0\n for y in range(0, human_years):\n if y == 0:\n cat_years += 15\n dog_years += 15\n elif y == 1:\n cat_years += 9\n dog_years += 9\n else:\n cat_years += 4\n dog_years += 5\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(human_years):\n cat_years = 0\n dog_years = 0\n if human_years < 2:\n cat_years += 15\n dog_years += 15\n elif human_years == 2:\n cat_years += 15 + 9\n dog_years += 15 + 9\n else:\n cat_years += 15 + 9 + (human_years - 2) * 4\n dog_years += 15 + 9 + (human_years - 2) * 5\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n return [1, 15, 15]\n elif human_years == 2:\n return [2, 24, 24]\n else:\n return [human_years, (human_years - 2) * 4 + 24, (human_years - 2) * 5 + 24]\n 32", "def human_years_cat_years_dog_years(h):\n (cat, dog) = (0, 0)\n if h >= 1:\n cat += 15\n dog += 15\n if h >= 2:\n cat += 9\n dog += 9\n if h >= 3:\n cat += 4 * (h - 2)\n dog += 5 * (h - 2)\n return [h, cat, dog]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n cat_years = 15\n dog_years = 15\n elif human_years == 2:\n cat_years = 24\n dog_years = 24\n elif human_years == 3:\n cat_years = 28\n dog_years = 29\n else:\n cat_years = 28 + (human_years - 3) * 4\n dog_years = 29 + (human_years - 3) * 5\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(human_years):\n a = human_years\n if human_years == 1:\n d = 15\n c = 15\n elif human_years == 2:\n d = 24\n c = 24\n else:\n d = 24 + abs(human_years - 2) * 5\n c = 24 + abs(human_years - 2) * 4\n return [a, c, d]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n cat_years = 15\n dog_years = 15\n elif human_years == 2:\n cat_years = 15 + 9\n dog_years = 15 + 9\n elif human_years > 2:\n cat_years = 24 + (human_years - 2) * 4\n dog_years = 24 + (human_years - 2) * 5\n else:\n None\n return [human_years, cat_years, dog_years]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n (catYears, dogYears) = (15, 15)\n elif human_years == 2:\n (catYears, dogYears) = (24, 24)\n else:\n catYears = 24 + (human_years - 2) * 4\n dogYears = 24 + (human_years - 2) * 5\n return [human_years, catYears, dogYears]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n (cat_y, dog_y) = (15, 15)\n elif human_years == 2:\n (cat_y, dog_y) = (24, 24)\n else:\n cat_y = 24 + 4 * (human_years - 2)\n dog_y = 24 + 5 * (human_years - 2)\n return [human_years, cat_y, dog_y]", "def human_years_cat_years_dog_years(human_years):\n if human_years == 1:\n (cat, dog) = (15, 15)\n if human_years == 2:\n (cat, dog) = (24, 24)\n if human_years >= 3:\n cat = 24 + (human_years - 2) * 4\n dog = 24 + (human_years - 2) * 5\n return [human_years, cat, dog]", "def human_years_cat_years_dog_years(h):\n if h is 1:\n c = 15\n d = 15\n elif h is 2:\n c = 24\n d = 24\n else:\n c = 24 + (h - 2) * 4\n d = 24 + (h - 2) * 5\n return [h, c, d]", "def human_years_cat_years_dog_years(human_years):\n years = [0, 0, 0]\n for i in range(0, human_years):\n if years[0] == 0:\n years[0] += 1\n years[1] += 15\n years[2] += 15\n elif years[0] == 1:\n years[0] += 1\n years[1] += 9\n years[2] += 9\n else:\n years[0] += 1\n years[1] += 4\n years[2] += 5\n return years", "def human_years_cat_years_dog_years(human_years):\n caty = 0\n for i in range(0, human_years):\n if i == 0:\n caty += 15\n elif i == 1:\n caty += 9\n else:\n caty += 4\n dogy = 0\n for i in range(0, human_years):\n if i == 0:\n dogy += 15\n elif i == 1:\n dogy += 9\n else:\n dogy += 5\n return [human_years, caty, dogy]", "def human_years_cat_years_dog_years(y):\n c = d = 15\n if y > 1:\n c = d = 24\n if y > 2:\n (c, d) = (c + 4 * (y - 2), d + 5 * (y - 2))\n return [y, c, d]", "def human_years_cat_years_dog_years(human_years):\n return [human_years, 15 + (9 if human_years >= 2 else 0) + ((human_years - 2) * 4 if human_years >= 2 else 0), 15 + (9 if human_years >= 2 else 0) + ((human_years - 2) * 5 if human_years >= 2 else 0)]", "def human_years_cat_years_dog_years(y):\n if y == 1:\n return [1, 15, 15]\n elif y == 2:\n return [2, 24, 24]\n else:\n return [y, 24 + (y - 2) * 4, 24 + (y - 2) * 5]", "def human_years_cat_years_dog_years(human_years):\n f = 15\n s = 9\n if human_years == 1:\n return [human_years, f, f]\n elif human_years == 2:\n return [human_years, f + s, f + s]\n else:\n return [human_years, f + s + (human_years - 2) * 4, f + s + (human_years - 2) * 5]", "def human_years_cat_years_dog_years(human):\n\n def animal(h, p):\n r = 0\n for i in range(1, h + 1):\n if i == 1:\n r += 15\n elif i == 2:\n r += 9\n else:\n r += p\n return r\n return [human, animal(human, 4), animal(human, 5)]", "def human_years_cat_years_dog_years(h):\n return [h, 15 + 9 * int(h > 1) + 4 * (h - 2) * int(h > 2), 15 + 9 * int(h > 1) + 5 * (h - 2) * int(h > 2)]", "def human_years_cat_years_dog_years(yr):\n return ['one-liner', [1, 15, 15], [2, 24, 24]][yr] if yr in range(1, 3) else [yr, (yr - 2) * 4 + 24, (yr - 2) * 5 + 24]", "def human_years_cat_years_dog_years(human_years):\n cat_years = 15 * (human_years >= 1) + 9 * (human_years >= 2) + 4 * max(human_years - 2, 0)\n return [human_years, cat_years, cat_years + max(human_years - 2, 0)]", "human_years_cat_years_dog_years = lambda h: [h, 15 + (h >= 2) * (9 + (h - 2) * 4), 15 + (h >= 2) * (9 + (h - 2) * 5)]", "def human_years_cat_years_dog_years(human_years):\n cat_years = 0\n dog_years = 0\n human = human_years\n if human >= 1:\n cat_years = 15\n dog_years = 15\n human = human - 1\n if human >= 1:\n cat_years += 9\n dog_years += 9\n human = human - 1\n if human >= 1:\n cat_years += human * 4\n dog_years += human * 5\n return [human_years, cat_years, dog_years]"], "starter_code": "def human_years_cat_years_dog_years(human_years):\n", "input_output": {"fn_name": "human_years_cat_years_dog_years", "inputs": [[1], [2], [10]], "outputs": [[[1, 15, 15]], [[2, 24, 24]], [[10, 56, 64]]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5a6663e9fd56cb5ab800008b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "human_years_cat_years_dog_years", "task_id": "TACO_lite/25", "example": [[[1], [2], [3]], ["[1, 15, 15]", "[2, 24, 24]", "[3, 28, 29]"]]} +{"requirement": "Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.\n\n```python\nmove_zeros([False,1,0,1,2,0,1,3,\"a\"]) # returns[False,1,1,2,1,3,\"a\",0,0]\n```", "solutions": ["def move_zeros(arr):\n l = [i for i in arr if isinstance(i, bool) or i != 0]\n return l + [0] * (len(arr) - len(l))", "def move_zeros(array):\n return sorted(array, key=lambda x: x == 0 and type(x) is not bool)", "def move_zeros(array):\n return sorted(array, key=lambda x: x == 0 and x is not False)", "def move_zeros(array):\n newarr = []\n zeroarr = []\n for item in array:\n if item != 0 or type(item) == bool:\n newarr.append(item)\n else:\n zeroarr.append(item)\n newarr.extend(zeroarr)\n return newarr", "def move_zeros(array):\n return [a for a in array if isinstance(a, bool) or a != 0] + [a for a in array if not isinstance(a, bool) and a == 0]", "def move_zeros(array):\n a = list(filter(lambda x: x != 0 or type(x) is bool, array))\n return a + [0] * (len(array) - len(a))", "def move_zeros(array):\n return [x for x in array if x != 0 or x is False] + [x for x in array if x == 0 and (not x is False)]", "def move_zeros(array):\n return sorted(array, key=lambda x: not isinstance(x, bool) and x == 0)", "def move_zeros(array):\n temp = []\n for e in array[::-1]:\n if type(e) in (int, float, complex) and e == 0:\n temp.append(0)\n else:\n temp.insert(0, e)\n array = temp\n return array", "def move_zeros(array):\n without_zeros = list(filter(lambda n: not n == 0 or n is False, array))\n for i in range(len(array) - len(without_zeros)):\n without_zeros.append(0)\n return without_zeros", "def move_zeros(array):\n a_len = len(array)\n array = [v for v in array if type(v) is bool or v != 0]\n array.extend([0] * (a_len - len(array)))\n return array", "def move_zeros(array):\n a = []\n b = []\n for v in array:\n if type(v) in [float, int] and v == 0:\n b.append(0)\n else:\n a.append(v)\n return a + b", "move_zeros = lambda arr: [i for i in arr if str(i) == 'False' or i != 0] + [_ for _ in arr if str(_) != 'False' and _ == 0]", "def move_zeros(array):\n new_list = []\n c = 0\n for item in array:\n if item != 0 or type(item) == bool:\n new_list.append(item)\n else:\n c += 1\n i = 0\n while i < c:\n new_list.append(0)\n i += 1\n return new_list", "def move_zeros(array):\n new_array = []\n for check in array:\n if check != 0 or isinstance(check, bool):\n new_array.append(check)\n for cnt in range(abs(len(new_array) - len(array))):\n new_array.append(0)\n return new_array", "def move_zeros(array):\n strs = []\n array1 = array.copy()\n for i in array1:\n if isinstance(i, str):\n strs.append(i)\n array1[array1.index(i)] = ' '\n for i in array1:\n array1[array1.index(i)] = str(array1[array1.index(i)])\n for i in array1:\n if i == '0' or i == '0.0':\n array1.remove(i)\n array1.append('0')\n for i in array1:\n if i != ' ':\n array1[array1.index(i)] = eval(array1[array1.index(i)])\n\n def insf():\n v = 0\n while v < len(strs):\n v += 1\n yield v\n n = insf()\n for i in array1:\n if i == ' ':\n array1[array1.index(i)] = strs[next(n) - 1]\n return array1", "def move_zeros(array):\n zeros = 0\n new_arr = []\n for ele in array:\n if type(ele).__name__ != 'str' and str(ele) in '0.0':\n zeros += 1\n else:\n new_arr += [ele]\n return new_arr + [0] * zeros"], "starter_code": "def move_zeros(array):\n", "input_output": {"fn_name": "move_zeros", "inputs": [[[1, 2, 0, 1, 0, 1, 0, 3, 0, 1]], [[9, 0.0, 0, 9, 1, 2, 0, 1, 0, 1, 0.0, 3, 0, 1, 9, 0, 0, 0, 0, 9]], [["a", 0, 0, "b", "c", "d", 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9]], [["a", 0, 0, "b", null, "c", "d", 0, 1, false, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9]], [[0, 1, null, 2, false, 1, 0]], [["a", "b"]], [["a"]], [[0, 0]], [[0]], [[]]], "outputs": [[[1, 2, 1, 1, 3, 1, 0, 0, 0, 0]], [[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [["a", "b", "c", "d", 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [["a", "b", null, "c", "d", 1, false, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [[1, null, 2, false, 1, 0, 0]], [["a", "b"]], [["a"]], [[0, 0]], [[0]], [[]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms", "Sorting"], "name": null, "source": "codewars", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/52597aa56021e91c93000cb0", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "move_zeros", "task_id": "TACO_lite/64", "example": [[[[false, 1, 0, 1, 2, 0, 1, 3, "a"]]], ["[False, 1, 1, 2, 1, 3, 'a', 0, 0]"]]} +{"requirement": "Given two arrays X[] and Y[] of size M and N respectively. Find number of pairs such that x^{y} > y^{x} where x is an element from X[] and y is an element from Y[].\nExample 1:\nInput:\nM = 3, N = 2\nX[] = {2, 1, 6}, Y = {1, 5}\nOutput: 3\nExplanation: There are total 3 pairs \nwhere pow(x, y) is greater than pow(y, x) \nPairs are (2, 1), (2, 5) and (6, 1).\nExample 2:\nInput:\nM = 3, N = 3\nX[] = {10, 19, 18}, Y[] = {11, 15, 9}\nOutput: 2\nExplanation: There are total 2 pairs \nwhere pow(x, y) is greater than pow(y, x) \nPairs are (10, 11) and (10, 15).\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function countPairs() which takes array X[], array Y[], m and n as input parameters and returns an integer denoting the number of pairs that are true to the given condition. \nExpected Time Complexity: O(N*logN + M*logM)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 M, N \u2264 10^{5}\n1 \u2264 X[i], Y[i] \u2264 10^{3}", "solutions": ["def countpairs(X, Y, m, n):\n for i in range(m):\n X[i] **= 1 / X[i]\n for i in range(n):\n Y[i] **= 1 / Y[i]\n X.sort()\n Y.sort()\n i = j = 0\n ans = 0\n while i < m:\n if j == n:\n ans += n\n else:\n while j < n and X[i] > Y[j]:\n j += 1\n ans += j\n i += 1\n return ans", "import bisect\n\ndef countpairs(X, Y, m, n):\n X.sort()\n Y.sort()\n ans = 0\n for x in X:\n if x == 1:\n continue\n elif x == 2:\n idx = bisect.bisect_left(Y, 5)\n ans += n - idx\n elif x == 3:\n idx = bisect.bisect_left(Y, 2)\n ans += n - idx\n ans -= bisect.bisect(Y, 3) - bisect.bisect_left(Y, 3)\n else:\n idx = bisect.bisect_left(Y, x + 1)\n ans += n - idx\n for y in Y:\n if y == 1:\n idx = bisect.bisect_left(X, 2)\n ans += m - idx\n return ans", "def countpairs(X, Y, m, n):\n import math\n (x, y) = ([0] * m, [0] * n)\n for i in range(m):\n if X[i] == 1:\n x[i] = float('inf')\n else:\n temp = X[i] * 1.0\n temp = temp / math.log(temp)\n x[i] = temp\n for i in range(n):\n if Y[i] == 1:\n y[i] = float('inf')\n else:\n temp = Y[i] * 1.0\n temp = temp / math.log(temp)\n y[i] = temp\n x.sort()\n y.sort()\n i = j = count = 0\n while i < m and j < n:\n if x[i] < y[j]:\n count += n - j\n i += 1\n else:\n j += 1\n return count", "import bisect as bs\n\ndef countpairs(X, Y, m, n):\n (y1, y0, y2, y3, y4) = (0, 0, 0, 0, 0)\n X.sort()\n Y.sort()\n count = 0\n for i in range(n):\n if Y[i] == 0:\n y0 += 1\n elif Y[i] == 1:\n y1 += 1\n elif Y[i] == 2:\n y2 += 1\n elif Y[i] == 3:\n y3 += 1\n elif Y[i] == 4:\n y4 += 1\n for i in range(m):\n if X[i] == 0:\n continue\n elif X[i] == 1:\n count += y0\n elif X[i] == 2:\n k = bs.bisect_right(Y, 2)\n count += n - k\n count -= y3\n count -= y4\n count += y1 + y0\n else:\n j = bs.bisect_right(Y, X[i])\n count += n - j\n count += y1 + y0\n if X[i] == 3:\n count += y2\n return count", "from bisect import *\n\ndef countpairs(X, Y, m, n):\n one = 0\n two = 0\n for ele in Y:\n if ele == 1:\n one += 1\n if ele == 2:\n two += 1\n X.sort()\n Y.sort()\n ans = 0\n for x in X:\n if x == 1:\n continue\n else:\n ans += one\n if x == 2:\n ans += n - bisect_left(Y, 5)\n continue\n elif x == 3:\n ans += two\n ans += n - bisect_left(Y, x + 1)\n return ans", "from bisect import *\n\ndef countpairs(X, Y, m, n):\n y2 = 0\n y3 = 0\n y1 = 0\n for ele in Y:\n if ele != 2 and ele != 3 and (ele != 4):\n y2 += 1\n if ele != 3:\n y3 += 1\n if ele == 1:\n y1 += 1\n X.sort()\n Y.sort()\n ans = 0\n for x in X:\n if x == 1:\n continue\n elif x == 2:\n ans += y2\n elif x == 3:\n ans += y3\n else:\n ans += y1\n ans += n - bisect_left(Y, x + 1)\n return ans", "from collections import Counter\n\ndef countpairs(X, Y, m, n):\n XC = sorted(Counter(X).items())\n YC = Counter(Y)\n Y = sorted(YC.items())\n (ans, i, left) = (0, 0, n - (YC[2] + YC[3] + YC[4]))\n if XC[i][0] == 1:\n i += 1\n if XC[i][0] == 2:\n ans += XC[i][1] * left\n i += 1\n if XC[i][0] == 3:\n ans += XC[i][1] * (n - YC[3])\n i += 1\n if XC[i][0] == 4:\n ans += XC[i][1] * left\n i += 1\n (j, yleft) = (0, n)\n while i < len(XC):\n (v, xcnt) = XC[i]\n ans += YC[1] * xcnt\n while j < len(Y) and Y[j][0] <= v:\n yleft -= Y[j][1]\n j += 1\n ans += yleft * xcnt\n i += 1\n return ans", "def get_index(y, n, ele):\n ans = -1\n low = 0\n high = n - 1\n while low <= high:\n mid = (low + high) // 2\n if Y[mid] > ele:\n ans = mid\n high = mid - 1\n else:\n low = mid + 1\n return ans\n\ndef countpairs(X, Y, m, n):\n X.sort()\n Y.sort()\n y_c0 = Y.count(0)\n y_c1 = Y.count(1)\n y_c3 = Y.count(3)\n y_c4 = Y.count(4)\n y_c2 = Y.count(2)\n i = 0\n j = 0\n ind = -1\n c = 0\n for i in range(m):\n if X[i] == 0:\n continue\n elif X[i] == 1:\n c += y_c0\n elif X[i] == 2:\n ind = self.get_index(Y, n, 2)\n if ind != -1:\n c += n - ind\n c -= y_c3\n c -= y_c4\n c += y_c1 + y_c0\n else:\n ind = self.get_index(Y, n, X[i])\n if ind != -1:\n c += n - ind\n c += y_c1 + y_c0\n if X[i] == 3:\n c += y_c2\n return c", "import bisect\n\ndef count(x, Y, n, NoOfY):\n if x == 0:\n return 0\n if x == 1:\n return NoOfY[0]\n idx = bisect.bisect_right(Y, x)\n ans = n - idx\n ans += NoOfY[0] + NoOfY[1]\n if x == 2:\n ans -= NoOfY[3] + NoOfY[4]\n if x == 3:\n ans += NoOfY[2]\n return ans\n\ndef countpairs(X, Y, m, n):\n NoOfY = [0] * 5\n for i in range(n):\n if Y[i] < 5:\n NoOfY[Y[i]] += 1\n Y.sort()\n total_pairs = 0\n for x in X:\n total_pairs += self.count(x, Y, n, NoOfY)\n return total_pairs", "def bina(x, g, n):\n l = 0\n h = n - 1\n ans = -1\n while l <= h:\n m = (l + h) // 2\n if g[m] > x:\n ans = m\n h = m - 1\n else:\n l = m + 1\n return ans\n\ndef countpairs(a, b, M, N):\n s = {}\n for i in range(5):\n s[i] = 0\n for i in b:\n if i in s:\n s[i] += 1\n b.sort()\n a.sort()\n c = 0\n for i in a:\n if i == 0:\n continue\n elif i == 1:\n c += s[0]\n elif i == 2:\n ind = self.bina(i, b, N)\n if ind != -1:\n c += N - ind\n c += s[1] + s[0] - s[3] - s[4]\n else:\n ind = self.bina(i, b, N)\n if ind != -1:\n c += N - ind\n c += s[0] + s[1]\n if i == 3:\n c += s[2]\n return c", "import bisect\n\ndef count(x, Y, n, freq):\n if x == 1:\n return freq[0]\n idx = bisect.bisect_right(Y, x)\n ans = n - idx\n ans += freq[0] + freq[1]\n if x == 2:\n ans -= freq[3] + freq[4]\n if x == 3:\n ans += freq[2]\n return ans\n\ndef countpairs(X, Y, m, n):\n freq = [0] * 5\n Y.sort()\n for i in Y:\n if i < 5:\n freq[i] += 1\n count_ans = 0\n for i in X:\n count_ans += self.count(i, Y, n, freq)\n return count_ans", "import bisect\n\ndef countpairs(X, Y, m, n):\n Y.sort()\n noOfYs = [0 for _ in range(5)]\n for i in range(n):\n if Y[i] < 5:\n noOfYs[Y[i]] += 1\n pairs = 0\n for x in X:\n pairs += self.count(x, Y, noOfYs, n)\n return pairs\n\ndef count(x, Y, noOfYs, n):\n if x == 0:\n return 0\n if x == 1:\n return noOfYs[0]\n idx = bisect.bisect_right(Y, x)\n res = n - idx\n res += noOfYs[1] + noOfYs[0]\n if x == 2:\n res -= noOfYs[3] + noOfYs[4]\n if x == 3:\n res += noOfYs[2]\n return res", "import bisect\n\ndef countpairs(X, Y, m, n):\n NoOfYs = [0 for _ in range(5)]\n for i in range(n):\n if Y[i] < 5:\n NoOfYs[Y[i]] += 1\n Y.sort()\n pairs = 0\n for x in X:\n pairs += self.count(x, Y, NoOfYs)\n return pairs\n\ndef count(x, Y, noOfYs):\n if x == 0:\n return 0\n if x == 1:\n return noOfYs[0]\n idx = bisect.bisect_right(Y, x)\n res = len(Y) - idx\n res += noOfYs[0] + noOfYs[1]\n if x == 2:\n res -= noOfYs[3] + noOfYs[4]\n if x == 3:\n res += noOfYs[2]\n return res\n\ndef binarySearch(Y, x):\n low = 0\n high = len(Y) - 1\n idx = -1\n while low <= high:\n mid = (low + high) // 2\n if Y[mid] > x:\n idx = mid\n high = mid - 1\n else:\n low = mid + 1\n return idx", "import math\nimport sys\n\ndef countpairs(X, Y, m, n):\n arr1 = X\n arr2 = Y\n for i in range(len(arr1)):\n if arr1[i] == 1:\n arr1[i] = sys.maxsize\n else:\n arr1[i] = arr1[i] / math.log(arr1[i])\n arr1.sort()\n for j in range(len(arr2)):\n if arr2[j] == 1:\n arr2[j] = sys.maxsize\n else:\n arr2[j] = arr2[j] / math.log(arr2[j])\n arr2.sort()\n pointA = 0\n pointB = 0\n count = 0\n while pointA < len(arr1) and pointB < len(arr2):\n if arr1[pointA] < arr2[pointB]:\n count += len(arr2) - pointB\n pointA += 1\n else:\n pointB += 1\n return count", "import bisect\n\ndef count(i, Y, m, res):\n if i == 0:\n return 0\n if i == 1:\n return res[0]\n ind = bisect.bisect_right(Y, i)\n ans = m - ind\n ans += res[0] + res[1]\n if i == 2:\n ans -= res[3] + res[4]\n if i == 3:\n ans += res[2]\n return ans\n\ndef countpairs(X, Y, m, n):\n cnt = 0\n result = [0] * 5\n for i in range(n):\n if Y[i] < 5:\n result[Y[i]] += 1\n Y.sort()\n for i in X:\n cnt += self.count(i, Y, n, result)\n return cnt", "def search(arr, l, r, x):\n if r >= l:\n mid = l + (r - l) // 2\n if arr[mid] <= x:\n return search(arr, mid + 1, r, x)\n else:\n return search(arr, l, mid - 1, x)\n return l\n\ndef countpairs(X, Y, m, n):\n nn = [0] * 5\n for i in range(n):\n if Y[i] < 5:\n nn[Y[i]] += 1\n Y.sort()\n pairs = 0\n for i in X:\n if i == 0:\n continue\n elif i == 1:\n pairs += nn[0]\n else:\n ss = search(Y, 0, n - 1, i)\n if ss > n - 1:\n ss = 0\n else:\n pairs += n - ss\n pairs += nn[0] + nn[1]\n if i == 2:\n pairs -= nn[3] + nn[4]\n if i == 3:\n pairs += nn[2]\n return pairs", "import bisect\n\ndef bs(arr, low, high, x):\n if low <= high:\n mid = low + (high - low) // 2\n if (mid == 0 or arr[mid - 1] <= x) and arr[mid] > x:\n return mid\n elif arr[mid] <= x:\n return self.bs(arr, mid + 1, high, x)\n else:\n return self.bs(arr, low, mid - 1, x)\n else:\n return -1\n\ndef count(x, Y, n, NoOfY):\n if x == 0:\n return 0\n if x == 1:\n return NoOfY[0]\n idx = bisect.bisect_right(Y, x)\n ans = n - idx\n ans += NoOfY[0] + NoOfY[1]\n if x == 2:\n ans -= NoOfY[3] + NoOfY[4]\n if x == 3:\n ans += NoOfY[2]\n return ans\n\ndef countpairs(X, Y, m, n):\n NoOfY = [0] * 5\n for i in range(n):\n if Y[i] < 5:\n NoOfY[Y[i]] += 1\n Y.sort()\n total_pairs = 0\n for x in X:\n total_pairs += self.count(x, Y, n, NoOfY)\n return total_pairs", "import bisect\n\ndef count(i, b, n, hashe):\n if i == 0:\n return 0\n if i == 1:\n return hashe[0]\n index = bisect.bisect_right(b, i)\n ans = n - index\n ans += hashe[1] + hashe[0]\n if i == 2:\n ans -= hashe[3]\n ans -= hashe[4]\n if i == 3:\n ans += hashe[2]\n return ans\n\ndef countpairs(a, b, M, N):\n pairs = 0\n hashe = dict()\n hashe = [0 for i in range(5)]\n for i in b:\n if i < 5:\n hashe[i] += 1\n b.sort()\n for i in a:\n pairs += self.count(i, b, N, hashe)\n return pairs"], "starter_code": "def countpairs(X, Y, m, n):\n", "input_output": {"inputs": ["M = 3, N = 2\nX[] = {2, 1, 6}, Y = {1, 5}", "M = 3, N = 3\nX[] = {10, 19, 18}, Y[] = {11, 15, 9}"], "outputs": ["3", "2"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Arrays", "Algorithms", "Sorting"], "name": null, "source": "geeksforgeeks", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/number-of-pairs3422/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*logN + M*logM)", "entry_point": "countpairs", "task_id": "TACO_lite/28", "example": [[[3, 2, [2, 1, 6], [1, 5]], [3, 3, [10, 19, 18], [11, 15, 9]]], [null, null]]} +{"requirement": "You're in ancient Greece and giving Philoctetes a hand in preparing a training exercise for Hercules! You've filled a pit with two different ferocious mythical creatures for Hercules to battle!\n\nThe formidable **\"Orthus\"** is a 2 headed dog with 1 tail. The mighty **\"Hydra\"** has 5 heads and 1 tail. \n\nBefore Hercules goes in, he asks you \"How many of each beast am I up against!?\".\n\nYou know the total number of heads and the total number of tails, that's the dangerous parts, right? But you didn't consider how many of each beast. \n\n## Task\n\nGiven the number of heads and the number of tails, work out the number of each mythical beast! \n\nThe data is given as two parameters. Your answer should be returned as an array:\n```python \n VALID -> [24 , 15] INVALID -> \"No solutions\"\n```\n\nIf there aren't any cases for the given amount of heads and tails - return \"No solutions\" or null (C#).", "solutions": ["def beasts(heads, tails):\n orthus = (5 * tails - heads) / 3\n hydra = tails - orthus\n return [orthus, hydra] if orthus >= 0 and hydra >= 0 else 'No solutions'", "def beasts(h, t):\n out = [(5 * t - h) / 3, (h - 2 * t) / 3]\n return all((x.is_integer() and x >= 0 for x in out)) and out or 'No solutions'", "def beasts(heads, tails):\n if heads not in range(tails * 2, tails * 5 + 1, 3):\n return 'No solutions'\n return [(tails * 5 - heads) / 3, (heads - tails * 2) / 3]", "def beasts(heads, tails):\n extraheads = heads - 2 * tails\n if extraheads % 3 != 0 or not 0 <= extraheads <= 3 * tails:\n return 'No solutions'\n hydra = extraheads // 3\n orthus = tails - hydra\n return [orthus, hydra]", "def beasts(heads, tails):\n h = (heads - tails * 2) / 3\n if h < 0 or tails - h < 0:\n return 'No solutions'\n return [tails - h, h]", "beasts = lambda h, t: (lambda m: [t - m, m] if m >= 0 and m <= t and (m % 1 == 0) else 'No solutions')((h - t * 2) / 3.0)", "def beasts(h, t):\n (O, H) = (5 * t - h, h - 2 * t)\n if O >= O % 3 >= 0 <= H % 3 <= H:\n return [O // 3, H // 3]\n else:\n return 'No solutions'", "def beasts(heads, tails):\n for orthus in range(heads // 2 + 1):\n if orthus * 2 + (tails - orthus) * 5 == heads:\n return [orthus, tails - orthus]\n return 'No solutions'", "def beasts(heads, tails):\n o = (5 * tails - heads) / 3\n h = (heads - 2 * tails) / 3\n if o == int(o) and h == int(h) and (o >= 0) and (h >= 0):\n return [int(o), int(h)]\n else:\n return 'No solutions'", "def beasts(heads, tails):\n hydra = (heads - 2 * tails) / 3\n orthus = tails - (heads - 2 * tails) / 3\n if hydra % 1 == 0 and hydra >= 0 and (orthus % 1 == 0) and (orthus >= 0):\n return [orthus, hydra]\n else:\n return f'No solutions'"], "starter_code": "def beasts(heads, tails):\n", "input_output": {"fn_name": "beasts", "inputs": [[123, 39], [371, 88], [24, 12], [113, 37], [635, 181], [25, 555], [12, 25], [54, 956], [5455, 54956], [0, 0], [-1, -1], [-45, 5], [99, 0], [0, 99], [5, -55]], "outputs": [[[24, 15]], [[23, 65]], [[12, 0]], [[24, 13]], [[90, 91]], ["No solutions"], ["No solutions"], ["No solutions"], ["No solutions"], [[0, 0]], ["No solutions"], ["No solutions"], ["No solutions"], ["No solutions"], ["No solutions"]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5751aa92f2dac7695d000fb0", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "beasts", "task_id": "TACO_lite/33", "example": [[[24, 15], [10, 6], [5, 1]], ["No solutions", "No solutions", [0.0, 1.0]]]} +{"requirement": "Given an array of integers arr[0..n-1], count all pairs (arr[i], arr[j]) in it such that i*arr[i] > j*arr[j],\nand 0 \u2264 i < j < n.\n \nExample 1:\nInput :\narr[] = {5, 0, 10, 2, 4, 1, 6}\nOutput :\n5\nExplanation :\nPairs which hold condition i*arr[i] > j*arr[j] are\n(10, 2) (10, 4) (10, 1) (2, 1) (4, 1)\n \nExample 2:\nInput :\narr[] = {8, 4, 2, 1}\nOutput :\n2\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function countPairs() which takes the array A[] and its size N as inputs and returns the required result.\n \nExpected Time Complexity: O(N. log(N))\nExpected Auxiliary Space: O(N. log(N))\n \nConstraints:\n1 \u2264 N \u2264 10^{5}\n1 \u2264 A[ ] \u2264 10^{3}", "solutions": ["def merge(arr, temp, left, mid, right):\n inv_count = 0\n i = left\n j = mid\n k = left\n while i <= mid - 1 and j <= right:\n if arr[i] <= arr[j]:\n temp[k] = arr[i]\n i += 1\n k += 1\n else:\n temp[k] = arr[j]\n k += 1\n j += 1\n inv_count = inv_count + (mid - i)\n while i <= mid - 1:\n temp[k] = arr[i]\n i += 1\n k += 1\n while j <= right:\n temp[k] = arr[j]\n k += 1\n j += 1\n for i in range(left, right + 1):\n arr[i] = temp[i]\n return inv_count\n\ndef _mergeSort(arr, temp, left, right):\n inv_count = 0\n if right > left:\n mid = (right + left) // 2\n inv_count = _mergeSort(arr, temp, left, mid)\n inv_count += _mergeSort(arr, temp, mid + 1, right)\n inv_count += merge(arr, temp, left, mid + 1, right)\n return inv_count\n\ndef countpairs(arr, n):\n for i in range(n):\n arr[i] = i * arr[i]\n temp = [0] * n\n return _mergeSort(arr, temp, 0, n - 1)", "import bisect\n\ndef countpairs(arr, n):\n srt_arr = []\n count = 0\n for i in range(n):\n arr[i] = i * arr[i]\n index = bisect.bisect(srt_arr, arr[i])\n count += i - index\n srt_arr.insert(index, arr[i])\n return count", "def countpairs(arr, n):\n res = [i * arr[i] for i in range(n)]\n temp = [0] * n\n return self.sorter(res, temp, 0, n - 1)\n\ndef sorter(arr, temp, l, r):\n c = 0\n if l < r:\n mid = (l + r) // 2\n c += self.sorter(arr, temp, l, mid)\n c += self.sorter(arr, temp, mid + 1, r)\n c += self.merge(arr, temp, l, mid, r)\n return c\n\ndef merge(arr, temp, l, mid, r):\n i = l\n j = mid + 1\n k = l\n c = 0\n while i <= mid and j <= r:\n if arr[i] <= arr[j]:\n temp[k] = arr[i]\n k += 1\n i += 1\n else:\n temp[k] = arr[j]\n c += mid - i + 1\n k += 1\n j += 1\n while i <= mid:\n temp[k] = arr[i]\n k += 1\n i += 1\n while j <= r:\n temp[k] = arr[j]\n k += 1\n j += 1\n arr[l:r + 1] = temp[l:r + 1]\n return c"], "starter_code": "def countpairs(arr, n):\n", "input_output": {"inputs": ["arr[] = {5, 0, 10, 2, 4, 1, 6}", "arr[] = {8, 4, 2, 1}"], "outputs": ["5", "2"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-pairs-in-an-array4145/1", "Expected Auxiliary Space": "O(N. log(N))", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N. log(N))", "entry_point": "countpairs", "task_id": "TACO_lite/30", "example": [[[[5, 0, 10, 2, 4, 1, 6]], [[8, 4, 2, 1]]], [null, null]]} +{"requirement": "Given an array arr[] of size N, the task is to check whether it is possible to obtain an array having distinct neighboring elements by swapping two neighboring array elements.\nExample 1:\nInput: N = 3, arr[] = {1, 1, 2}\nOutput: YES\nExplanation: Swap 1 (second last element) \nand 2 (last element), to obtain 1 2 1,\nwhich has distinct neighbouring elements.\nExample 2:\nInput: N = 4, arr[] = {7, 7, 7, 7}\nOutput: NO\nExplanation: We can't swap to obtain \ndistinct elements in neighbor .\nYour Task:\nYou don't need to read input or print anything. You just need to complete the function distinctAdjacentElement() that takes array arr[] and its size N as input parameters and returns a boolean value denoting if distinct neighbours are possible or not. \nNote: The generated output is YES or NO according to the returned value.\n \nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\n \nConstraints:\n2 \u2264 N \u2264 10^{6}", "solutions": ["from collections import Counter\n\ndef distinctadjacentelement(arr, n):\n k = {}\n kis = []\n for i in arr:\n if i not in k:\n k[i] = 1\n else:\n k[i] += 1\n for i in k:\n kis.append(k[i])\n m = max(kis)\n if m <= (n + 1) // 2:\n return 'YES'", "from collections import Counter\n\ndef distinctadjacentelement(arr, n):\n a = Counter(arr)\n max1 = max(a.values())\n if max1 <= (n + 1) // 2:\n return 1\n else:\n return 0", "def distinctadjacentelement(arr, n):\n a = {}\n for i in arr:\n if i not in a:\n a[i] = 1\n else:\n a[i] += 1\n maxq = max(a.values())\n if maxq <= int(n + 1) / 2:\n return 1\n else:\n return 0", "def distinctadjacentelement(arr, n):\n freq = {}\n for i in arr:\n if i not in freq:\n freq[i] = 0\n freq[i] += 1\n dif = 0\n j = 0\n for i in freq:\n if j % 2 == 0:\n dif += freq[i]\n else:\n dif -= freq[i]\n j += 1\n m = 0\n for i in freq:\n m = max(m, freq[i])\n if m > (n + 1) // 2:\n return False\n return True", "def distinctadjacentelement(arr, n):\n count = {}\n for item in arr:\n if item not in count:\n count[item] = 1\n else:\n count[item] += 1\n maximum = -1\n for value in count.values():\n if value > maximum:\n maximum = value\n if maximum <= int((n + 1) / 2):\n return True\n else:\n return False", "def distinctadjacentelement(arr, n):\n dict_ = {}\n for elem in arr:\n dict_.update({elem: dict_.get(elem, 0) + 1})\n return max(dict_.values()) <= (n + 1) // 2", "def distinctadjacentelement(arr, n):\n if n == 2 and arr[0] == arr[1]:\n return False\n dict_ = {}\n for elem in arr:\n dict_[elem] = dict_[elem] + 1 if elem in dict_ else 1\n return max(dict_.values()) <= (n + 1) // 2", "def distinctadjacentelement(arr, n):\n arr.sort()\n count = 1\n m = 0\n for i in range(n - 1):\n if arr[i] == arr[i + 1]:\n count += 1\n else:\n m = max(count, m)\n count = 1\n m = max(count, m)\n if n % 2 == 0:\n if m <= n // 2:\n return True\n else:\n return False\n elif m <= (n + 1) // 2:\n return True\n else:\n return False", "def distinctadjacentelement(arr, n):\n k = {}\n kis = []\n for i in arr:\n if i not in k:\n k[i] = 1\n else:\n k[i] += 1\n for i in k:\n kis.append(k[i])\n m = max(kis)\n if m <= (n + 1) // 2:\n return 'YES'", "def distinctadjacentelement(arr, n):\n ele = arr[0]\n f = 0\n for i in range(0, len(arr)):\n if arr[i] == ele:\n f = 1\n else:\n f = -1\n break\n if f == 1:\n return False\n else:\n sz = (n + 1) // 2\n freq = 0\n m = 0\n f = 0\n list1 = []\n for i in range(0, len(arr)):\n if arr[i] not in list1:\n list1.append(arr[i])\n c = arr.count(arr[i])\n if f == 0:\n m = c\n f = 1\n elif c > m:\n m = c\n if m <= sz:\n return True\n else:\n return False", "def distinctadjacentelement(arr, n):\n di = {}\n m = 0\n for i in arr:\n if i not in di:\n di[i] = 1\n else:\n di[i] += 1\n for i in di:\n if m < di[i]:\n m = di[i]\n if m > (n + 1) // 2:\n return 0\n else:\n return 1", "def distinctadjacentelement(arr, n):\n d = dict()\n list1 = []\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n for j in d:\n list1.append(d[j])\n mx = max(list1)\n if mx <= (n + 1) // 2:\n return 'YES'", "def distinctadjacentelement(arr, n):\n m = {}\n for i in arr:\n m[i] = m.get(i, 0) + 1\n if m[i] > (n + 1) // 2:\n return 0\n return 1", "def distinctadjacentelement(arr, n):\n d = {}\n for i in arr:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n count = 0\n for i in d:\n count = max(count, d[i])\n if n % 2 == 0:\n if count <= n // 2:\n return True\n return False\n else:\n if count <= (n + 1) // 2:\n return True\n return False", "def distinctadjacentelement(arr, n):\n dis = {}\n for x in arr:\n if x in dis:\n dis[x] += 1\n else:\n dis[x] = 1\n mx = max([x for x in dis.values()])\n return False if mx > (n + 1) // 2 else True", "def distinctadjacentelement(arr, n):\n size = 10 ** 6 + 1\n count = [0] * size\n for i in range(n):\n count[arr[i]] += 1\n max_val = max(count)\n if n % 2 == 0:\n if max_val <= n // 2:\n return True\n if n % 2 == 1:\n if max_val <= (n + 1) // 2:\n return True\n return False", "def distinctadjacentelement(arr, n):\n mp = {}\n for i in arr:\n if i in mp:\n mp[i] += 1\n else:\n mp[i] = 1\n x = -1\n for i in mp.values():\n x = max(x, i)\n return x <= (n + 1) // 2", "def distinctadjacentelement(arr, n):\n from collections import defaultdict\n d = defaultdict(int)\n maxx = 0\n for i in arr:\n d[i] += 1\n maxx = max(d[i], maxx)\n if maxx > (n + 1) // 2:\n return False\n else:\n return True", "def distinctadjacentelement(a, n):\n m = dict()\n for i in range(n):\n if a[i] in m:\n m[a[i]] += 1\n else:\n m[a[i]] = 1\n mx = 0\n for i in range(n):\n if mx < m[a[i]]:\n mx = m[a[i]]\n if mx > (n + 1) // 2:\n return False\n else:\n return True", "def distinctadjacentelement(arr, n):\n mp = dict()\n for i in range(n):\n if arr[i] in mp:\n mp[arr[i]] += 1\n else:\n mp[arr[i]] = 1\n for i in range(n):\n if mp[arr[i]] > (n + 1) / 2:\n return False\n return True", "def distinctadjacentelement(arr, n):\n freqs = {}\n for el in arr:\n if el in freqs:\n freqs[el] += 1\n else:\n freqs[el] = 1\n max_freq = 0\n for v in freqs.values():\n if v > max_freq:\n max_freq = v\n if max_freq <= (n + 1) // 2:\n return True\n return False", "from collections import Counter\n\ndef distinctadjacentelement(arr, n):\n s = Counter(arr)\n for i in s:\n if s[i] > (n + 1) // 2:\n return False\n return True", "def distinctadjacentelement(arr, n):\n dict1 = {}\n for i in range(n):\n if arr[i] in dict1:\n dict1[arr[i]] += 1\n else:\n dict1[arr[i]] = 1\n val = sorted(dict1.items(), key=lambda x: x[1], reverse=True)[0][1]\n if val <= (n + 1) / 2:\n return True\n else:\n return False"], "starter_code": "def distinctadjacentelement(arr, n):\n", "input_output": {"inputs": ["N = 3, arr[] = {1, 1, 2}", "N = 4, arr[] = {7, 7, 7, 7}"], "outputs": ["YES", " NO"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/distinct-adjacent-element2121/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "distinctadjacentelement", "task_id": "TACO_lite/69", "example": [[], []]} +{"requirement": "Given a sequence of moves for a robot. Check if the sequence is circular or not. \nA sequence of moves is circular if the first and last positions of the robot are the same. A move can be one of the following :\n G - Go one unit\n L - Turn left\n R - Turn right\nExample 1:\nInput: path = \"GLGLGLG\"\nOutput: \"Circular\"\nExplanation: If we start form \n(0,0) in a plane then we will \nback to (0,0) by the end of the \nsequence.\n\u00c3\u00a2\u00e2\u0082\u00ac\u00e2\u0080\u00b9Example 2:\nInput: path = \"GGGGL\"\nOutput: \"Not Circular\"\nExplanation: We can't return to \nsame place at the end of the path.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function isCircular() which takes the string path as input and returns \"Circular\" if the path is circular else returns \"Not Circular\".\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 |S| \u2264 10^{5}", "solutions": ["def iscircular(path):\n i = j = 0\n pre = 'r'\n for k in path:\n if k == 'G':\n if pre == 'r':\n j += 1\n elif pre == 'l':\n j -= 1\n elif pre == 'u':\n i -= 1\n elif pre == 'd':\n i += 1\n elif k == 'L':\n if pre == 'r':\n pre = 'u'\n elif pre == 'l':\n pre = 'd'\n elif pre == 'u':\n pre = 'l'\n elif pre == 'd':\n pre = 'r'\n elif k == 'R':\n if pre == 'r':\n pre = 'd'\n elif pre == 'l':\n pre = 'u'\n elif pre == 'u':\n pre = 'r'\n elif pre == 'd':\n pre = 'l'\n if i == 0 and j == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n l = [0, 0]\n dir = 1\n for i in range(len(path)):\n if path[i] == 'G':\n if dir == 1:\n l[0] += 1\n elif dir == 2:\n l[1] += 1\n elif dir == 3:\n l[0] -= 1\n else:\n l[1] -= 1\n elif path[i] == 'L':\n dir += 1\n if dir > 4:\n dir = 1\n else:\n dir -= 1\n if dir == 0:\n dir = 4\n if l == [0, 0]:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n direction = 0\n x = 0\n y = 0\n for i in path:\n if i == 'G':\n if direction == 0:\n y += 1\n elif direction == 1:\n x += 1\n elif direction == 2:\n y -= 1\n elif direction == 3:\n x -= 1\n elif i == 'L':\n if direction == 0:\n direction = 3\n else:\n direction -= 1\n elif i == 'R':\n if direction == 3:\n direction = 0\n else:\n direction += 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(moves):\n (x, y) = (0, 0)\n direction = 'N'\n for move in moves:\n if move == 'G':\n if direction == 'N':\n y += 1\n elif direction == 'S':\n y -= 1\n elif direction == 'E':\n x += 1\n elif direction == 'W':\n x -= 1\n elif move == 'L':\n if direction == 'N':\n direction = 'W'\n elif direction == 'S':\n direction = 'E'\n elif direction == 'E':\n direction = 'N'\n elif direction == 'W':\n direction = 'S'\n elif move == 'R':\n if direction == 'N':\n direction = 'E'\n elif direction == 'S':\n direction = 'W'\n elif direction == 'E':\n direction = 'S'\n elif direction == 'W':\n direction = 'N'\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n x = 0\n y = 0\n angle = 0\n for i in path:\n if i == 'G':\n if angle % 360 == 0:\n x += 1\n elif angle % 360 == 180:\n x -= 1\n elif angle % 360 == 90:\n y += 1\n else:\n y -= 1\n elif i == 'R':\n angle += 90\n elif i == 'L':\n angle += 270\n if x == 0 and y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n dir = 'N'\n y = 0\n x = 0\n for i in path:\n if dir == 'N' and i == 'G':\n y = y + 1\n elif dir == 'E' and i == 'G':\n x = x + 1\n elif dir == 'S' and i == 'G':\n y = y - 1\n elif dir == 'W' and i == 'G':\n x = x - 1\n if dir == 'N' and i == 'L':\n dir = 'W'\n elif dir == 'N' and i == 'R':\n dir = 'E'\n elif dir == 'W' and i == 'L':\n dir = 'S'\n elif dir == 'W' and i == 'R':\n dir = 'N'\n elif dir == 'S' and i == 'L':\n dir = 'E'\n elif dir == 'S' and i == 'R':\n dir = 'W'\n elif dir == 'E' and i == 'L':\n dir = 'N'\n elif dir == 'E' and i == 'R':\n dir = 'S'\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n dir = 0\n xn = 0\n yn = 0\n for i in range(len(path)):\n move = path[i]\n if move == 'R':\n dir = (dir + 1) % 4\n elif move == 'L':\n dir = (4 + dir - 1) % 4\n elif dir == 0:\n yn = yn + 1\n elif dir == 1:\n xn = xn + 1\n elif dir == 2:\n yn = yn - 1\n else:\n xn = xn - 1\n if xn == 0 and yn == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n d = {0: [1, 0], 1: [0, 1], 2: [-1, 0], 3: [0, -1]}\n position = [0, 0]\n direction = 0\n for item in path:\n if item == 'G':\n position[0] += d[direction][0]\n position[1] += d[direction][1]\n if item == 'L':\n direction = (direction - 1) % 4\n if item == 'R':\n direction = (direction + 1) % 4\n return 'Circular' if position == [0, 0] else 'Not Circular'", "def iscircular(path):\n (i, j) = (0, 0)\n d = 0\n for x in path:\n if x == 'G':\n if d % 2 == 0:\n i = i - 1 if d == 2 else i + 1\n else:\n j = j + 1 if d == 1 else j - 1\n elif x == 'L':\n d = (d + 1) % 4\n else:\n d = d - 1 if d != 0 else 3\n if i == 0 and j == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n x_axis = 0\n y_axis = 0\n direction = 0\n for char in path:\n if char == 'L':\n direction += 1\n elif char == 'R':\n direction -= 1\n elif char == 'G':\n if direction % 4 == 1:\n x_axis += 1\n elif direction % 4 == 2:\n y_axis -= 1\n elif direction % 4 == 3:\n x_axis -= 1\n elif direction % 4 == 0:\n y_axis += 1\n if x_axis == 0 and y_axis == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n x = 0\n y = 0\n dir = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n cur = 0\n for i in path:\n if i == 'G':\n (movex, movey) = dir[cur]\n x += movex\n y += movey\n elif i == 'L':\n if cur == 0:\n cur = 3\n else:\n cur -= 1\n elif cur == 3:\n cur = 0\n else:\n cur += 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n direc = ['left', 'up', 'right', 'down']\n index = 1\n start = [1, 1]\n for i in path:\n if i == 'G':\n if direc[index] == 'up':\n start[1] += 1\n elif direc[index] == 'down':\n start[1] -= 1\n elif direc[index] == 'left':\n start[0] -= 1\n else:\n start[0] += 1\n elif i == 'L':\n index -= 1\n index %= 4\n else:\n index += 1\n index %= 4\n return 'Circular' if start[0] == 1 and start[1] == 1 else 'Not Circular'", "def iscircular(path):\n N = 1\n S = 2\n E = 3\n W = 4\n curr = 1\n x = 0\n y = 0\n for i in path:\n if i == 'G':\n if curr == 1:\n y += 1\n elif curr == 2:\n y -= 1\n elif curr == 3:\n x += 1\n else:\n x -= 1\n elif i == 'L':\n if curr == N:\n curr = W\n elif curr == S:\n curr = E\n elif curr == E:\n curr = N\n elif curr == W:\n curr = S\n elif i == 'R':\n if curr == N:\n curr = E\n elif curr == S:\n curr = W\n elif curr == E:\n curr = S\n elif curr == W:\n curr = N\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n (x, y) = (0, 0)\n (dirX, dirY) = (0, 1)\n for p in path:\n if p == 'G':\n (x, y) = (x + dirX, y + dirY)\n elif p == 'L':\n (dirX, dirY) = (-1 * dirY, dirX)\n else:\n (dirX, dirY) = (dirY, -1 * dirX)\n if (x, y) == (0, 0):\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n i = 0\n j = 0\n dir = 'E'\n LL = ['E', 'S', 'W', 'N']\n for c in path:\n if c == 'G':\n j += (dir == 'N') - (dir == 'S')\n i += (dir == 'E') - (dir == 'W')\n if c == 'R':\n dir = LL[(LL.index(dir) + 1) % 4]\n if c == 'L':\n dir = LL[(LL.index(dir) - 1) % 4]\n return 'Circular' if i == 0 and j == 0 else 'Not Circular'", "def iscircular(path):\n x = 0\n y = 0\n dirc = 'R'\n for i in path:\n if i == 'G':\n if dirc == 'R':\n x += 1\n elif dirc == 'U':\n y += 1\n elif dirc == 'L':\n x -= 1\n elif dirc == 'D':\n y -= 1\n elif i == 'L':\n if dirc == 'R':\n dirc = 'U'\n elif dirc == 'U':\n dirc = 'L'\n elif dirc == 'L':\n dirc = 'D'\n elif dirc == 'D':\n dirc = 'R'\n elif i == 'R':\n if dirc == 'R':\n dirc = 'D'\n elif dirc == 'U':\n dirc = 'R'\n elif dirc == 'L':\n dirc = 'U'\n elif dirc == 'D':\n dirc = 'L'\n if x == 0 and y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n position = [0, 0]\n directions = ((0, 1), (1, 0), (0, -1), (-1, 0))\n dir_idx = 0\n for a in path:\n if a == 'G':\n position[0] += directions[dir_idx][0]\n position[1] += directions[dir_idx][1]\n elif a == 'L':\n dir_idx = (dir_idx - 1) % 4\n elif a == 'R':\n dir_idx = (dir_idx + 1) % 4\n if position[0] == 0 and position[1] == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n curr = 0\n (posx, posy) = (0, 0)\n for char in path:\n if char == 'G':\n posx += dirs[curr][0]\n posy += dirs[curr][1]\n elif char == 'L':\n curr -= 1\n if curr == -1:\n curr = 3\n else:\n curr += 1\n if curr == 4:\n curr = 0\n if posx == 0 and posy == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n position = (0, 0)\n current_orientation = 'u'\n for move in path:\n if move == 'G':\n if current_orientation == 'u':\n position = (position[0], position[1] + 1)\n elif current_orientation == 'l':\n position = (position[0] - 1, position[1])\n elif current_orientation == 'r':\n position = (position[0] + 1, position[1])\n elif current_orientation == 'd':\n position = (position[0], position[1] - 1)\n if move == 'L':\n if current_orientation == 'u':\n current_orientation = 'l'\n elif current_orientation == 'l':\n current_orientation = 'd'\n elif current_orientation == 'r':\n current_orientation = 'u'\n elif current_orientation == 'd':\n current_orientation = 'r'\n if move == 'R':\n if current_orientation == 'u':\n current_orientation = 'r'\n elif current_orientation == 'l':\n current_orientation = 'u'\n elif current_orientation == 'r':\n current_orientation = 'd'\n elif current_orientation == 'd':\n current_orientation = 'l'\n if position == (0, 0):\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n x = 0\n y = 0\n dir = 0\n for i in range(len(path)):\n if path[i] == 'L':\n dir = (4 + dir - 1) % 4\n elif path[i] == 'R':\n dir = (dir + 1) % 4\n elif dir == 0:\n y += 1\n elif dir == 1:\n x += 1\n elif dir == 2:\n y -= 1\n else:\n x -= 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n dirX = [1, 0, -1, 0]\n dirY = [0, 1, 0, -1]\n dir = 0\n x = 0\n y = 0\n for i in path:\n if i == 'G':\n x += dirX[dir]\n y += dirY[dir]\n elif i == 'L':\n dir = (dir - 1) % 4\n else:\n dir = (dir + 1) % 4\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n directions = {'E': ['N', 'S'], 'W': ['S', 'N'], 'N': ['W', 'E'], 'S': ['E', 'W']}\n move = {'E': [1, 0], 'W': [-1, 0], 'N': [0, 1], 'S': [0, -1]}\n (X, Y) = (0, 0)\n towards = 'E'\n for p in path:\n if p == 'G':\n X += move[towards][0]\n Y += move[towards][1]\n else:\n towards = directions[towards][0] if p == 'L' else directions[towards][1]\n return 'Circular' if not X and (not Y) else 'Not Circular'", "def iscircular(path):\n (N, E, S, W) = (0, 1, 2, 3)\n dire = N\n (x, y) = (0, 0)\n n = len(path)\n for i in range(n):\n move = path[i]\n if move == 'R':\n dire = (dire + 1) % 4\n elif move == 'L':\n dire = (4 + dire - 1) % 4\n elif dire == N:\n y += 1\n elif dire == S:\n y -= 1\n elif dire == E:\n x += 1\n else:\n x -= 1\n if x == 0 and y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n (dirx, diry) = (0, 1)\n (x, y) = (0, 0)\n for i in path:\n if i == 'G':\n (x, y) = (x + dirx, y + diry)\n elif i == 'L':\n (dirx, diry) = (-1 * diry, dirx)\n else:\n (dirx, diry) = (diry, -1 * dirx)\n if (x, y) == (0, 0):\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n face_up = [0, 1]\n face_d = [0, -1]\n face_l = [-1, 0]\n face_r = [1, 0]\n n = len(path) // 4 + 1\n dir = [face_up, face_l, face_d, face_r] * n\n position = [0, 0]\n current_pos = position\n ind = 0\n for i in path:\n if i == 'L':\n ind = ind + 1\n elif i == 'R':\n ind = ind - 1\n else:\n current_pos = [current_pos[0] + dir[ind][0], current_pos[1] + dir[ind][1]]\n if current_pos == position:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n facing = 'N'\n cord = [0, 0]\n for i in path:\n if i == 'G':\n if facing == 'N':\n cord[1] += 1\n elif facing == 'S':\n cord[1] -= 1\n elif facing == 'E':\n cord[0] += 1\n else:\n cord[0] -= 1\n elif i == 'L':\n if facing == 'N':\n facing = 'W'\n elif facing == 'S':\n facing = 'E'\n elif facing == 'E':\n facing = 'N'\n else:\n facing = 'S'\n elif facing == 'N':\n facing = 'E'\n elif facing == 'S':\n facing = 'W'\n elif facing == 'E':\n facing = 'S'\n else:\n facing = 'N'\n if cord[0] == cord[1] == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n (dx, dy) = (0, 1)\n (x, y) = (0, 0)\n for d in path:\n if d == 'G':\n (x, y) = (x + dx, y + dy)\n elif d == 'L':\n (dx, dy) = (-1 * dy, dx)\n else:\n (dx, dy) = (dy, -1 * dx)\n if (x, y) == (0, 0):\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n (x, y) = (0, 0)\n currDir = 'N'\n for c in path:\n if c == 'G':\n if currDir == 'N':\n x += 1\n elif currDir == 'W':\n y -= 1\n elif currDir == 'E':\n y += 1\n else:\n x -= 1\n elif c == 'L':\n if currDir == 'N':\n currDir = 'W'\n elif currDir == 'W':\n currDir = 'S'\n elif currDir == 'E':\n currDir = 'N'\n else:\n currDir = 'E'\n elif currDir == 'N':\n currDir = 'E'\n elif currDir == 'W':\n currDir = 'N'\n elif currDir == 'E':\n currDir = 'S'\n else:\n currDir = 'W'\n return 'Circular' if x == 0 and y == 0 else 'Not Circular'", "def iscircular(path):\n dir_l = ['y+', 'x+', 'y-', 'x-']\n d = {'y+': [0, 1], 'x+': [1, 0], 'y-': [0, -1], 'x-': [-1, 0]}\n curr_dir = 'y+'\n curr_co = [0, 0]\n for i in path:\n if i == 'G':\n (add_x, add_y) = d[curr_dir]\n curr_co = [curr_co[0] + add_x, curr_co[1] + add_y]\n else:\n curr_ind = dir_l.index(curr_dir)\n if i == 'R':\n if curr_ind + 1 == 4:\n curr_ind = 0\n else:\n curr_ind += 1\n elif curr_ind - 1 == -1:\n curr_ind = 3\n else:\n curr_ind -= 1\n curr_dir = dir_l[curr_ind]\n if curr_co == [0, 0]:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n up = 0\n down = 0\n left = 0\n right = 0\n moving = 0\n for move in path:\n if move == 'G':\n if moving == 0:\n right = right + 1\n elif moving == 1:\n up = up + 1\n elif moving == 2:\n left = left + 1\n else:\n down = down + 1\n elif move == 'R':\n moving = (moving + 1) % 4\n elif moving == 0:\n moving = 3\n else:\n moving = moving - 1\n if up - down + left - right == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n (x, y) = (0, 0)\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n d = 0\n for i in path:\n if i == 'G':\n x += directions[d % 4][0]\n y += directions[d % 4][1]\n elif i == 'L':\n d -= 1\n else:\n d += 1\n return 'Circular' if (x, y) == (0, 0) else 'Not Circular'", "N = 0\nE = 1\nS = 2\nW = 3\n\ndef case_E(x, y):\n return (x + 1, y)\n\ndef case_W(x, y):\n return (x - 1, y)\n\ndef case_N(x, y):\n return (x, y + 1)\n\ndef case_S(x, y):\n return (x, y - 1)\noptions = {E: case_E, W: case_W, N: case_N, S: case_S}\n\ndef iscircular(path):\n x = y = 0\n dir = N\n for i in range(len(path)):\n if path[i] == 'L':\n dir = (dir + 4 - 1) % 4\n elif path[i] == 'R':\n dir = (dir + 1) % 4\n else:\n (x, y) = options[dir](x, y)\n if x == 0 and y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n (curr_loc, first_loc) = ([0, 0], [0, 0])\n curr_dir = 'N'\n for move in path:\n if move == 'G':\n if curr_dir == 'N':\n curr_loc[1] += 1\n elif curr_dir == 'S':\n curr_loc[1] -= 1\n elif curr_dir == 'E':\n curr_loc[0] += 1\n elif curr_dir == 'W':\n curr_loc[0] -= 1\n elif move == 'L':\n if curr_dir == 'N':\n curr_dir = 'W'\n elif curr_dir == 'S':\n curr_dir = 'E'\n elif curr_dir == 'E':\n curr_dir = 'N'\n elif curr_dir == 'W':\n curr_dir = 'S'\n elif move == 'R':\n if curr_dir == 'N':\n curr_dir = 'E'\n elif curr_dir == 'S':\n curr_dir = 'W'\n elif curr_dir == 'E':\n curr_dir = 'S'\n elif curr_dir == 'W':\n curr_dir = 'N'\n if curr_loc == first_loc:\n return 'Circular'\n else:\n return 'Not Circular'", "from collections import namedtuple\nPoint = namedtuple('Point', 'x y')\n\ndef turn(currentDirection, dest):\n sign = 1 if dest == 'L' else -1\n if currentDirection == (1, 0):\n return Point(0, sign * 1)\n elif currentDirection == (0, 1):\n return Point(-1 * sign, 0)\n elif currentDirection == (-1, 0):\n return Point(0, -1 * sign)\n elif currentDirection == (0, -1):\n return Point(1 * sign, 0)\n else:\n return currentDirection\n\ndef iscircular(path):\n p = Point(0, 0)\n direction = Point(1, 0)\n for e in path:\n if e == 'G':\n p = Point(p.x + direction.x, p.y + direction.y)\n elif e == 'L':\n direction = turn(direction, 'L')\n elif e == 'R':\n direction = turn(direction, 'R')\n return 'Circular' if p == (0, 0) else 'Not Circular'", "def iscircular(path):\n (x, y) = (0, 0)\n directions = {'N': (0, 1), 'S': (0, -1), 'E': (1, 0), 'W': (-1, 0)}\n pos = 'N'\n n = len(path)\n for i in range(n):\n if path[i] == 'G':\n x = x + directions[pos][0]\n y = y + directions[pos][1]\n elif path[i] == 'L':\n if pos == 'N':\n pos = 'W'\n elif pos == 'W':\n pos = 'S'\n elif pos == 'S':\n pos = 'E'\n elif pos == 'E':\n pos = 'N'\n elif path[i] == 'R':\n if pos == 'N':\n pos = 'E'\n elif pos == 'E':\n pos = 'S'\n elif pos == 'S':\n pos = 'W'\n elif pos == 'W':\n pos = 'N'\n return 'Circular' if x == 0 and y == 0 else 'Not Circular'", "def iscircular(path):\n N = 1\n E = 2\n s = 3\n w = 4\n x = 0\n y = 0\n curr_dir = 1\n for i in path:\n if i == 'G':\n if curr_dir == 1:\n y += 1\n elif curr_dir == 2:\n x += 1\n elif curr_dir == 3:\n y -= 1\n else:\n x -= 1\n elif i == 'L':\n if curr_dir == 1:\n curr_dir = 4\n elif curr_dir == 2:\n curr_dir = 1\n elif curr_dir == 3:\n curr_dir = 2\n else:\n curr_dir = 3\n elif curr_dir == 1:\n curr_dir = 2\n elif curr_dir == 2:\n curr_dir = 3\n elif curr_dir == 3:\n curr_dir = 4\n else:\n curr_dir = 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n pos = [0, 0]\n ret = [0, 0]\n dirleft = {'l': 'd', 'd': 'r', 'r': 'u', 'u': 'l'}\n dirright = {'l': 'u', 'd': 'l', 'r': 'd', 'u': 'r'}\n move = 'r'\n for i in range(len(path)):\n if path[i] == 'G':\n if move == 'r':\n pos[1] += 1\n elif move == 'l':\n pos[1] -= 1\n elif move == 'u':\n pos[0] -= 1\n elif move == 'd':\n pos[0] += 1\n elif path[i] == 'L':\n move = dirleft[move]\n elif path[i] == 'R':\n move = dirright[move]\n if pos == ret:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n x = y = 0\n (dx, dy) = (1, 0)\n l = len(path)\n for i in range(l):\n if path[i] == 'L':\n if dx == 1:\n dx = 0\n dy = 1\n elif dy == 1:\n dx = -1\n dy = 0\n elif dy == -1:\n dx = 1\n dy = 0\n else:\n dx = 0\n dy = -1\n continue\n if path[i] == 'R':\n if dx == 1:\n dx = 0\n dy = -1\n elif dy == 1:\n dx = 1\n dy = 0\n elif dy == -1:\n dx = -1\n dy = 0\n else:\n dx = 0\n dy = 1\n continue\n x += dx\n y += dy\n if x == 0 and y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n (x, y, direc) = (0, 0, 0)\n for move in path:\n if move == 'L':\n direc = (4 + direc - 1) % 4\n if move == 'R':\n direc = (direc + 1) % 4\n if move == 'G':\n if direc == 0:\n y += 1\n elif direc == 1:\n x += 1\n elif direc == 2:\n y -= 1\n else:\n x -= 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n (x, y) = (0, 0)\n up = (0, 1)\n down = (0, -1)\n left = (-1, 0)\n right = (1, 0)\n left_turn = [down, left, up, right]\n right_turn = [up, left, down, right]\n current_direction = left\n for i in range(len(path)):\n if path[i] == 'G':\n x += current_direction[0]\n y += current_direction[1]\n else:\n if path[i] == 'L':\n turn = left_turn\n if path[i] == 'R':\n turn = right_turn\n index = turn.index(current_direction)\n index = 0 if index == 3 else index + 1\n current_direction = turn[index]\n return 'Circular' if (x, y) == (0, 0) else 'Not Circular'", "def iscircular(path):\n POSSIBLE_MOVEMENTS = {'N': [0, 1], 'S': [0, -1], 'E': [1, 0], 'W': [-1, 0]}\n POSSIBLE_DIRECTION_CHANGES = {'N': {'L': 'W', 'R': 'E'}, 'S': {'L': 'E', 'R': 'W'}, 'E': {'L': 'N', 'R': 'S'}, 'W': {'L': 'S', 'R': 'N'}}\n current_position = [0, 0]\n current_direction = 'N'\n for i in range(0, len(path)):\n if path[i] == 'G':\n current_position = self.addArrays(current_position, POSSIBLE_MOVEMENTS[current_direction])\n else:\n current_step = path[i]\n current_options = POSSIBLE_DIRECTION_CHANGES[current_direction]\n current_direction = current_options[current_step]\n if current_position == [0, 0]:\n return 'Circular'\n return 'Not Circular'\n\ndef addArrays(arr1, arr2):\n array = [arr1[0] + arr2[0], arr1[1] + arr2[1]]\n return array", "def iscircular(path):\n x_count = 0\n y_count = 0\n direction = 'x'\n for char in path:\n if char == 'G' and direction == 'x':\n x_count += 1\n elif char == 'G' and direction == '-x':\n x_count -= 1\n elif char == 'G' and direction == 'y':\n y_count += 1\n elif char == 'G' and direction == '-y':\n y_count -= 1\n if char == 'L' and direction == 'x':\n direction = 'y'\n elif char == 'L' and direction == 'y':\n direction = '-x'\n elif char == 'L' and direction == '-x':\n direction = '-y'\n elif char == 'L' and direction == '-y':\n direction = 'x'\n elif char == 'R' and direction == 'x':\n direction = '-y'\n elif char == 'R' and direction == 'y':\n direction = 'x'\n elif char == 'R' and direction == '-x':\n direction = 'y'\n elif char == 'R' and direction == '-y':\n direction = '-x'\n if x_count == 0 and y_count == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n state_map = {'x+ve': (1, 0), 'x-ve': (-1, 0), 'y+ve': (0, 1), 'y-ve': (0, -1)}\n direct_map = {'x+ve': ('y+ve', 'y-ve'), 'x-ve': ('y-ve', 'y+ve'), 'y+ve': ('x-ve', 'x+ve'), 'y-ve': ('x+ve', 'x-ve')}\n state = ('x+ve', (0, 0))\n for char in path:\n (direct, cord) = state\n if char == 'G':\n (dx, dy) = state_map[direct]\n new_cord = (cord[0] + dx, cord[1] + dy)\n new_state = (direct, new_cord)\n else:\n if char == 'L':\n new_direct = direct_map[direct][0]\n else:\n new_direct = direct_map[direct][1]\n new_state = (new_direct, cord)\n state = new_state\n return 'Circular' if state[1] == (0, 0) else 'Not Circular'", "def iscircular(path):\n x = 0\n y = 0\n directions = ['N', 'E', 'S', 'W']\n index = 0\n for i in range(len(path)):\n move = path[i]\n if move == 'R':\n index = (index + 1) % 4\n elif move == 'L':\n index = (4 + index - 1) % 4\n else:\n d = directions[index]\n if d == 'N':\n y += 1\n elif d == 'E':\n x += 1\n elif d == 'S':\n y -= 1\n else:\n x -= 1\n return 'Circular' if x == 0 and y == 0 else 'Not Circular'", "def iscircular(path):\n d = [[0, 1], [-1, 0], [0, -1], [1, 0]]\n dir = 0\n x = y = 0\n for p in path:\n if p == 'L':\n dir = (dir + 1) % 4\n elif p == 'R':\n dir = (dir + 3) % 4\n else:\n (x, y) = (x + d[dir][0], y + d[dir][1])\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n i = 0\n x = 0\n y = 0\n d = 0\n while i < len(path):\n if path[i] == 'L':\n d -= 1\n i += 1\n elif path[i] == 'R':\n d += 1\n i += 1\n elif path[i] == 'G':\n d = d % 4\n if d == -1 or d == 3:\n x -= 1\n elif d == 1 or d == -3:\n x += 1\n elif d == -2 or d == 2:\n y -= 1\n elif d == 0:\n y += 1\n i += 1\n if x == 0 and y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n directions = {'0': 0, '90': 0, '180': 0, '270': 0}\n heading = 0\n for step in path:\n if step == 'G':\n directions[str(heading)] = directions[str(heading)] + 1\n elif step == 'L':\n heading = (heading + 90) % 360\n elif step == 'R':\n heading = (heading - 90) % 360\n if heading < 0:\n heading = 360 + heading\n if directions['0'] - directions['180'] + (directions['90'] - directions['270']) == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n final_pos = 0\n (x, y) = (0, 0)\n head = 1\n for i in path:\n if i == 'L' and head == 1:\n head = 2\n elif i == 'L' and head == 2:\n head = 3\n elif i == 'L' and head == 3:\n head = 4\n elif i == 'L' and head == 4:\n head = 1\n elif i == 'R' and head == 1:\n head = 4\n elif i == 'R' and head == 2:\n head = 1\n elif i == 'R' and head == 3:\n head = 2\n elif i == 'R' and head == 4:\n head = 3\n elif head == 1:\n x += 1\n elif head == 2:\n y += 1\n elif head == 3:\n x -= 1\n else:\n y -= 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n\n def walk(pathUnit, walkRecord, pointer):\n if pointer == 3 and pathUnit == 'L':\n pointer = 0\n elif pointer == 0 and pathUnit == 'R':\n pointer = 3\n elif pathUnit == 'L':\n pointer += 1\n elif pathUnit == 'R':\n pointer -= 1\n if pathUnit == 'G':\n if pointer == 0:\n walkRecord[0] += 1\n if pointer == 1:\n walkRecord[1] += 1\n if pointer == 2:\n walkRecord[2] += 1\n if pointer == 3:\n walkRecord[3] += 1\n return (walkRecord, pointer)\n walkRecord = [0] * 4\n pointer = 0\n for pathUnit in path:\n (walkRecord, pointer) = walk(pathUnit, walkRecord, pointer)\n if walkRecord[0] + walkRecord[1] == walkRecord[2] + walkRecord[3]:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n (n, e, s, w) = (0, 1, 2, 3)\n (x, y) = (0, 0)\n d = n\n for i in path:\n if i == 'R':\n d = (d + 1) % 4\n elif i == 'L':\n d = (4 + d - 1) % 4\n elif d == n:\n y += 1\n elif d == e:\n x += 1\n elif d == s:\n y -= 1\n else:\n x -= 1\n if x == 0 and y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n direction = 'right'\n init_x = init_y = 0\n for move in path:\n if move == 'G':\n if direction == 'right':\n init_x += 1\n elif direction == 'left':\n init_x -= 1\n elif direction == 'up':\n init_y += 1\n elif direction == 'down':\n init_y -= 1\n elif move == 'L':\n if direction == 'right':\n direction = 'up'\n elif direction == 'up':\n direction = 'left'\n elif direction == 'left':\n direction = 'down'\n elif direction == 'down':\n direction = 'right'\n elif move == 'R':\n if direction == 'right':\n direction = 'down'\n elif direction == 'down':\n direction = 'left'\n elif direction == 'left':\n direction = 'up'\n elif direction == 'up':\n direction = 'right'\n if init_x == init_y and init_x == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n direction = 'n'\n n = 0\n e = 0\n s = 0\n w = 0\n for p in path:\n if p == 'R':\n if direction == 'n':\n direction = 'e'\n elif direction == 'e':\n direction = 's'\n elif direction == 's':\n direction = 'w'\n else:\n direction = 'n'\n elif p == 'L':\n if direction == 'n':\n direction = 'w'\n elif direction == 'e':\n direction = 'n'\n elif direction == 's':\n direction = 'e'\n else:\n direction = 's'\n elif direction == 'n':\n n += 1\n if s > 0:\n n -= 1\n s -= 1\n elif direction == 'e':\n e += 1\n if w > 0:\n e -= 1\n w -= 1\n elif direction == 's':\n s += 1\n if n > 0:\n n -= 1\n s -= 1\n else:\n w += 1\n if e > 0:\n e -= 1\n w -= 1\n if n - s == 0 and e - w == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n x = 0\n y = 0\n face = 0\n for chars in path:\n if chars == 'G':\n if face == 0:\n x += 1\n elif face == 1:\n y += 1\n elif face == 2:\n x -= 1\n else:\n y -= 1\n elif chars == 'L':\n face += 1\n face %= 4\n elif chars == 'R':\n face -= 1\n if face < 0:\n face = 3\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n if not 1 <= len(path) <= pow(10, 5):\n return 'Not Circular'\n position = [0, 0]\n direction = 'North'\n for s in path:\n if s == 'L':\n if direction == 'North':\n direction = 'West'\n elif direction == 'West':\n direction = 'South'\n elif direction == 'South':\n direction = 'East'\n elif direction == 'East':\n direction = 'North'\n if s == 'R':\n if direction == 'North':\n direction = 'East'\n elif direction == 'East':\n direction = 'South'\n elif direction == 'South':\n direction = 'West'\n elif direction == 'West':\n direction = 'North'\n if s == 'G':\n if direction == 'North':\n position = [a + b for (a, b) in zip(position, [0, 1])]\n elif direction == 'East':\n position = [a + b for (a, b) in zip(position, [1, 0])]\n elif direction == 'South':\n position = [a + b for (a, b) in zip(position, [0, -1])]\n elif direction == 'West':\n position = [a + b for (a, b) in zip(position, [-1, 0])]\n if position == [0, 0]:\n return 'Circular'\n else:\n return 'Not Circular'", "def __init__():\n self.x = 0\n self.y = 0\n self.direction = [0, 1]\n\ndef iscircular(path):\n for c in path:\n if c == 'G':\n self.x += self.direction[0]\n self.y += self.direction[1]\n if c == 'L':\n self.direction = [-1 * self.direction[1], self.direction[0] * 1]\n if c == 'R':\n self.direction = [1 * self.direction[1], self.direction[0] * -1]\n if self.x == 0 and self.y == 0:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n N = 0\n E = 1\n S = 2\n W = 3\n x = 0\n y = 0\n direction = 0\n for move in list(path):\n if move == 'L':\n direction = (direction + 1) % 4\n elif move == 'R':\n direction = (4 + direction - 1) % 4\n else:\n if direction == 0:\n y += 1\n if direction == 1:\n x += 1\n if direction == 2:\n y -= 1\n if direction == 3:\n x -= 1\n return 'Circular' if x == 0 and y == 0 else 'Not Circular'", "def iscircular(path):\n dirn = 'E'\n (x, y) = (0, 0)\n for i in range(len(path)):\n if path[i] == 'G':\n if dirn == 'E':\n y += 1\n elif dirn == 'W':\n y -= 1\n elif dirn == 'N':\n x -= 1\n else:\n x += 1\n elif path[i] == 'L':\n if dirn == 'E':\n dirn = 'N'\n elif dirn == 'W':\n dirn = 'S'\n elif dirn == 'N':\n dirn = 'W'\n else:\n dirn = 'E'\n elif dirn == 'E':\n dirn = 'S'\n elif dirn == 'W':\n dirn = 'N'\n elif dirn == 'N':\n dirn = 'E'\n else:\n dirn = 'W'\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n loc = [0, 0]\n dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n current_dir = 0 % 4\n for p in path:\n if p == 'G':\n loc[0] += dirs[current_dir][0]\n loc[1] += dirs[current_dir][1]\n elif p == 'L':\n current_dir = (current_dir - 1) % 4\n else:\n current_dir = (current_dir + 1) % 4\n return 'Circular' if loc == [0, 0] else 'Not Circular'", "def iscircular(path):\n N = 0\n E = 1\n S = 2\n W = 3\n x = 0\n y = 0\n dir = N\n for item in path:\n if item == 'L':\n dir = (4 + dir - 1) % 4\n elif item == 'R':\n dir = (dir + 1) % 4\n elif dir == N:\n y += 1\n elif dir == E:\n x += 1\n elif dir == S:\n y -= 1\n else:\n x -= 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n x = 0\n y = 0\n cp = 4\n for ch in path:\n if ch == 'L':\n cp += 1\n elif ch == 'R':\n cp -= 1\n elif cp % 4 == 0:\n x += 1\n elif cp % 4 == 1:\n y += 1\n elif cp % 4 == 2:\n x -= 1\n elif cp % 4 == 3:\n y -= 1\n if x == y and x == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(moves):\n x = y = 0\n present_direction = 0\n for move in moves:\n if move == 'L':\n present_direction = (4 + present_direction - 1) % 4\n elif move == 'R':\n present_direction = (present_direction + 1) % 4\n elif present_direction == 0:\n y += 1\n elif present_direction == 2:\n y -= 1\n elif present_direction == 3:\n x += 1\n else:\n x -= 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n flag = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n cur = 1\n init = (0, 0)\n pos = (0, 0)\n for c in path:\n if c == 'G':\n pos = tuple(map(lambda a, b: a + b, pos, flag[cur]))\n elif c == 'L':\n cur = (3 + cur) % 4\n else:\n cur = (1 + cur) % 4\n if pos == init:\n return 'Circular'\n return 'Not Circular'", "def iscircular(path):\n (x, y) = (0, 0)\n currentDirection = 'N'\n turn = {'NL': 'W', 'NR': 'E', 'EL': 'N', 'ER': 'S', 'SL': 'E', 'SR': 'W', 'WL': 'S', 'WR': 'N'}\n for i in path:\n if i == 'G':\n if currentDirection == 'N':\n x += 1\n elif currentDirection == 'S':\n x -= 1\n elif currentDirection == 'E':\n y += 1\n elif currentDirection == 'W':\n y -= 1\n else:\n currentDirection = turn[currentDirection + i]\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(list_of_commands):\n compass = 0\n orientation = 'N'\n x = 0\n y = 0\n for command in list_of_commands:\n if command == 'G':\n if orientation == 'N':\n y += 1\n if orientation == 'S':\n y -= 1\n if orientation == 'E':\n x += 1\n if orientation == 'W':\n x -= 1\n if command == 'L':\n if compass == 0:\n compass = 3\n else:\n compass -= 1\n if command == 'R':\n if compass == 3:\n compass = 0\n else:\n compass += 1\n if compass == 0:\n orientation = 'N'\n if compass == 1:\n orientation = 'E'\n if compass == 2:\n orientation = 'S'\n if compass == 3:\n orientation = 'W'\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n dir = 'east'\n x = 0\n y = 0\n for i in path:\n if i == 'L':\n if dir == 'east':\n dir = ''\n dir = 'north'\n elif dir == 'north':\n dir = ''\n dir = 'west'\n elif dir == 'west':\n dir = ''\n dir = 'south'\n elif dir == 'south':\n dir = ''\n dir = 'east'\n elif i == 'R':\n if dir == 'east':\n dir = ''\n dir = 'south'\n elif dir == 'south':\n dir = ''\n dir = 'west'\n elif dir == 'west':\n dir = ''\n dir = 'north'\n elif dir == 'north':\n dir = ''\n dir = 'east'\n elif i == 'G':\n if dir == 'east':\n x = x + 1\n elif dir == 'west':\n x = x - 1\n elif dir == 'north':\n y = y + 1\n elif dir == 'south':\n y = y - 1\n if x == 0 and y == 0:\n return 'Circular'\n else:\n return 'Not Circular'", "def iscircular(path):\n start = [0, 0]\n modify = 'X+'\n nextmodify = {('X+', 'L'): 'Y+', ('X+', 'R'): 'Y-', ('X-', 'L'): 'Y-', ('X-', 'R'): 'Y+', ('Y+', 'L'): 'X-', ('Y+', 'R'): 'X+', ('Y-', 'L'): 'X+', ('Y-', 'R'): 'X-'}\n for move in path:\n if move == 'G':\n if modify == 'X+':\n start[0] = start[0] + 1\n elif modify == 'X-':\n start[0] = start[0] - 1\n elif modify == 'Y+':\n start[1] = start[1] + 1\n elif modify == 'Y-':\n start[1] = start[1] - 1\n else:\n modify = nextmodify[modify, move]\n return 'Circular' if start[0] == 0 and start[1] == 0 else 'Not Circular'"], "starter_code": "def iscircular(path):\n", "input_output": {"inputs": ["path = \"GLGLGLG\"", "path = \"GGGGL\""], "outputs": ["\"Circular\"", "\"Not Circular\""]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/does-robot-moves-circular0414/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "iscircular", "task_id": "TACO_lite/44", "example": [[["GLGLGLG"], ["GGGGL"]], ["Circular", "Not Circular"]]} +{"requirement": "Implement a function called makeAcronym that returns the first letters of each word in a passed in string.\n\nMake sure the letters returned are uppercase.\n\nIf the value passed in is not a string return 'Not a string'.\n\nIf the value passed in is a string which contains characters other than spaces and alphabet letters, return 'Not letters'.\n\nIf the string is empty, just return the string itself: \"\".\n\n**EXAMPLES:**\n```\n'Hello codewarrior' -> 'HC'\n\n'a42' -> 'Not letters'\n\n42 -> 'Not a string'\n\n[2,12] -> 'Not a string'\n\n{name: 'Abraham'} -> 'Not a string'\n```", "solutions": ["def make_acronym(phrase):\n try:\n return ''.join((word[0].upper() if word.isalpha() else 0 for word in phrase.split()))\n except AttributeError:\n return 'Not a string'\n except TypeError:\n return 'Not letters'", "from operator import itemgetter\n\ndef make_acronym(phrase):\n if type(phrase) != str:\n return 'Not a string'\n if not all((c.isalpha() or c.isspace() for c in phrase)):\n return 'Not letters'\n return ''.join(map(itemgetter(0), phrase.split())).upper()", "def make_acronym(phrase):\n if not isinstance(phrase, str):\n return 'Not a string'\n arr = phrase.split()\n return ''.join((a[0] for a in arr)).upper() if all(map(str.isalpha, arr)) else 'Not letters'", "def make_acronym(phrase):\n if not isinstance(phrase, str):\n return 'Not a string'\n elif phrase == '':\n return ''\n elif not phrase.replace(' ', '').isalpha():\n return 'Not letters'\n else:\n return ''.join((word[0].upper() for word in phrase.split(' ')))", "def make_acronym(phrase):\n if isinstance(phrase, str):\n words = phrase.split()\n if all((x.isalpha() or x.isspace() for x in words)):\n return ''.join((x[0] for x in words)).upper()\n else:\n return 'Not letters'\n return 'Not a string'", "from string import ascii_letters\n\ndef make_acronym(phrase):\n acronym = ''\n if isinstance(phrase, str):\n words = phrase.split()\n for word in words:\n for char in word:\n if char in ascii_letters:\n pass\n else:\n return 'Not letters'\n acronym += word[0].upper()\n return acronym\n return 'Not a string'", "def make_acronym(phrase):\n if not isinstance(phrase, str):\n return 'Not a string'\n words = phrase.split()\n if not all((i.isalpha() for i in words)):\n return 'Not letters'\n return ''.join((p[0] for p in words)).upper()", "def make_acronym(phrase):\n import re\n if type(phrase) is not str:\n return 'Not a string'\n if re.search('[^A-Za-z\\\\s]', phrase):\n return 'Not letters'\n acronym = ''\n for x in phrase.split():\n acronym += x[0]\n return acronym.upper()"], "starter_code": "def make_acronym(phrase):\n", "input_output": {"fn_name": "make_acronym", "inputs": [["My aunt sally"], ["Please excuse my dear aunt Sally"], ["How much wood would a woodchuck chuck if a woodchuck could chuck wood"], ["Unique New York"], ["a42"], ["1111"], [64], [[]], [{}], [""]], "outputs": [["MAS"], ["PEMDAS"], ["HMWWAWCIAWCCW"], ["UNY"], ["Not letters"], ["Not letters"], ["Not a string"], ["Not a string"], ["Not a string"], [""]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/557efeb04effce569d000022", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "make_acronym", "task_id": "TACO_lite/5", "example": [[], []]} +{"requirement": "Given three integers A, B, N. Your task is to print the number of numbers between A and B including them, which have N-divisors. A number is called N-divisor if it has total N divisors including 1 and itself.\n \nExample 1:\nInput:\nA = 1\nB = 7\nN = 2\nOutput:\n4\nExplanation:\n2,3,5,7 have 2-divisors\nExample 2:\nInput:\nA = 1\nB = 25\nN = 3\nOutput:\n3\nExplanation:\n4,9,25 are the numbers\nhaving 3-divisors\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function count() which takes integer A, B and N as input parameters and returns an integer, the number of N-divisor number in between A and B inclusive.\n \nExpected Time Complexity: O((B-A) sqrt (B))\nExpected Space Complexity: O(1)\n \nConstraints:\n1<=A<=B<=10^{4}\n1 <= N <= 16", "solutions": ["def count(A, B, N):\n ans = 0\n for x in range(A, B + 1):\n count = 0\n i = 1\n while i * i <= x:\n if x % i == 0:\n count += 1\n if x // i != i:\n count += 1\n if count > N:\n break\n i += 1\n if count == N:\n ans += 1\n return ans", "from math import *\n\ndef count(A, B, N):\n count = 0\n sol = Solution()\n for i in range(A, B + 1):\n if N == sol.counter(i):\n count += 1\n return count\n\ndef counter(N):\n count = 0\n for i in range(1, int(sqrt(N)) + 1):\n if N % i == 0:\n if N % (N // i) == 0 and N // i != i:\n count += 1\n count += 1\n return count"], "starter_code": "def count(A,B,N):\n", "input_output": {"inputs": ["A = 1\nB = 7\nN = 2", "A = 1\nB = 25\nN = 3"], "outputs": ["4", "3"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/n-divisors5123/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O((B-A) sqrt (B))", "entry_point": "count", "task_id": "TACO_lite/90", "example": [[[1, 7, 2], [1, 25, 3]], ["4", "3"]]} +{"requirement": "A family of kookaburras are in my backyard.\n\nI can't see them all, but I can hear them!\n\n# How many kookaburras are there?\n\n\n\n\n## Hint \n\nThe trick to counting kookaburras is to listen carefully\n\n* The males go ```HaHaHa```...\n\n* The females go ```hahaha```...\n\n* And they always alternate male/female\n\n\n\n^ Kata Note : No validation is necessary; only valid input will be passed :-)", "solutions": ["import re\n\ndef kooka_counter(laughing):\n return len(re.findall('(ha)+|(Ha)+', laughing))", "def kooka_counter(laughing):\n return 0 if laughing == '' else laughing.count('Hah') + laughing.count('haH') + 1", "def kooka_counter(laughing):\n return laughing.count('Haha') + laughing.count('haHa') + bool(laughing)", "import re\n\ndef kooka_counter(stri):\n stri = re.sub('H+', 'H', stri.replace('a', ''))\n stri = re.sub('h+', 'h', stri.replace('a', ''))\n return len(stri)", "import re\npattern = re.compile('(Ha)+|(ha)+')\n\ndef kooka_counter(laughing):\n return len(pattern.findall(laughing))", "def kooka_counter(laughing):\n if len(laughing) == 0:\n return 0\n return laughing.count('haHa') + laughing.count('Haha') + 1", "def kooka_counter(laugh):\n count = 0\n while laugh:\n pat = laugh[:2]\n laugh = laugh.lstrip(pat)\n count += 1\n return count", "def kooka_counter(laughing):\n if len(laughing) == 0:\n return 0\n kooks = 1\n current = laughing[0]\n for i in range(2, len(laughing), 2):\n if laughing[i] != current:\n current = current.swapcase()\n kooks += 1\n return kooks"], "starter_code": "def kooka_counter(laughing):\n", "input_output": {"fn_name": "kooka_counter", "inputs": [[""], ["hahahahaha"], ["hahahahahaHaHaHa"], ["HaHaHahahaHaHa"], ["hahahahahahahaHaHa"]], "outputs": [[0], [1], [2], [3], [2]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms"], "name": null, "source": "codewars", "tags": ["String algorithms"], "skill_types": [], "url": "https://www.codewars.com/kata/58e8cad9fd89ea0c6c000258", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "kooka_counter", "task_id": "TACO_lite/108", "example": [[], []]} +{"requirement": "# Solve For X\n\nYou will be given an equation as a string and you will need to [solve for X](https://www.mathplacementreview.com/algebra/basic-algebra.php#solve-for-a-variable) and return x's value. For example: \n\n```python\nsolve_for_x('x - 5 = 20') # should return 25\nsolve_for_x('20 = 5 * x - 5') # should return 5\nsolve_for_x('5 * x = x + 8') # should return 2\nsolve_for_x('(5 - 3) * x = x + 2') # should return 2\n```\n\nNOTES:\n * All numbers will be whole numbers\n * Don't forget about the [order of operations](https://www.mathplacementreview.com/algebra/basic-algebra.php#order-of-operations).\n * If the random tests don't pass the first time, just run them again.", "solutions": ["from itertools import count\n\ndef solve_for_x(equation):\n return next((x for n in count(0) for x in [n, -n] if eval(equation.replace('x', str(x)).replace('=', '=='))))", "import re\n\ndef solve_for_x(equation):\n (left, right) = equation.split('=')\n answer = False\n TrialAndErrorRipMs = -1000\n while answer == False:\n FinalLeft = re.sub('x', str(TrialAndErrorRipMs), left)\n FinalRight = re.sub('x', str(TrialAndErrorRipMs), right)\n if eval(FinalLeft) == eval(FinalRight):\n return TrialAndErrorRipMs\n TrialAndErrorRipMs += 1", "def solve_for_x(equation):\n left_side = equation.split('=')[0]\n right_side = equation.split('=')[1]\n for x in range(-1000, 1000):\n if eval(left_side) == eval(right_side):\n return x", "def solve_for_x(equation):\n for x in range(-100, 1001):\n if eval(equation.replace('=', '==')):\n return x", "from itertools import count\n\ndef solve_for_x(equation):\n equation = equation.replace('=', '==')\n for x in count():\n if eval(equation):\n return x\n x = -x\n if eval(equation):\n return x", "def solve_for_x(equation):\n (left, right) = equation.split('=')\n for x in range(-1000, 1000):\n if eval(left) == eval(right):\n return x", "def solve_for_x(equation):\n p = equation.split()\n for i in range(0, len(p)):\n if p[i] == '=':\n p[i] = '=='\n t = p.index('x')\n for x in range(-1000, 1000):\n p[t] = str(x)\n if eval(''.join(p)):\n return x", "def solve_for_x(s):\n for i in range(-1000, 1000):\n if eval(s.replace('x', str(i)).replace('=', '==')):\n return i", "def build1(s):\n s = s.replace(' ', '')\n stack = []\n s += '!'\n if s[0] == '-':\n s = '0' + s\n j = 0\n for i in range(len(s)):\n if s[i] in ['+', '-', '*', '/', '(', ')', '!']:\n if j < i:\n stack.append(s[j:i])\n stack.append(s[i])\n j = i + 1\n stack.remove('!')\n for (i, x) in enumerate(stack):\n if x not in ['+', '-', '*', '/', '(', ')', '!']:\n stack[i] = Exp(x)\n return stack\n\ndef build2(s):\n while ')' in s:\n end = s.index(')')\n start = end\n while s[start] != '(':\n start -= 1\n s = s[:start] + [build2(s[start + 1:end])] + s[end + 1:]\n op = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x.__div__(y)}\n i = 2\n for order in [0, 1]:\n i = 2\n while i < len(s):\n if order == 0 and s[i - 1] in ['*', '/'] or (order == 1 and s[i - 1] in ['+', '-']):\n s[i - 2] = op[s[i - 1]](s[i - 2], s[i])\n s.pop(i)\n s.pop(i - 1)\n else:\n i += 2\n return s[0]\n\ndef build(s):\n stack = build1(s)\n equ = build2(stack)\n if type(equ) == Exp:\n equ = Equ([equ])\n return equ\n\ndef solve_for_x(equation):\n (l, r) = equation.split(' = ')\n (l, r) = (build(l), build(r))\n (l, r) = (l.get_power(1) - r.get_power(1), r.get_power(0) - l.get_power(0))\n return r.a / l.a\n\ndef __init__(s):\n self.a = 1\n self.p = 0\n if s[-1] == 'x':\n self.p = 1\n s = s[:-1]\n if 0 < len(s):\n self.a *= int(s)\n\ndef __add__(other):\n if self.p == other.p:\n self.a += other.a\n return self\n else:\n return Equ([self, other])\n\ndef __sub__(other):\n if self.p == other.p:\n self.a -= other.a\n return self\n else:\n return Equ([self, Exp('-1') * other])\n\ndef __mul__(other):\n self.p += other.p\n self.a *= other.a\n return self\n\ndef __div__(other):\n self.p -= other.p\n self.a /= other.a\n return self\n\ndef __str__():\n s = ''\n if self.a != 0:\n s += str(self.a)\n if self.p == 1:\n s += 'x'\n if s == '':\n s += '0'\n return s\n\ndef __init__(exp):\n self.exp = dict()\n for e in exp:\n if e.p not in self.exp:\n self.exp[e.p] = e\n else:\n self.exp[e.p] += e\n\ndef __add__(other):\n if type(other) == Exp:\n other = Equ([other])\n for p in other.exp:\n if p in self.exp:\n self.exp[p] += other.exp[p]\n else:\n self.exp[p] = other.exp[p]\n return self\n\ndef __sub__(other):\n if type(other) == Exp:\n other = Equ([other])\n for p in other.exp:\n if p in self.exp:\n self.exp[p] -= other.exp[p]\n else:\n self.exp[p] = Exp('-1') * other.exp[p]\n return self\n\ndef __mul__(other):\n if type(other) == Exp:\n other = Equ([other])\n res = None\n for p1 in other.exp:\n temp_res = []\n for p2 in self.exp:\n temp_res.append(self.exp[p2] * other.exp[p1])\n if res is None:\n res = Equ(temp_res)\n else:\n res += Equ(temp_res)\n return self\n\ndef __div__(other):\n if type(other) == Exp:\n other = Equ([other])\n res = None\n for p1 in other.exp:\n temp_res = []\n for p2 in self.exp:\n temp_res.append(self.exp[p2] / other.exp[p1])\n if res is None:\n res = Equ(temp_res)\n else:\n res += Equ(temp_res)\n return self\n\ndef __str__():\n s = ''\n for p in self.exp:\n s += ' (' + str(self.exp[p]) + ') +'\n return s[:-1]\n\ndef get_power(p):\n return self.exp[p] if p in self.exp else Exp('0') if p == 0 else Exp('0x')"], "starter_code": "def solve_for_x(equation):\n", "input_output": {"fn_name": "solve_for_x", "inputs": [["x - 5 = 20"], ["5 * x + 5 = 30"], ["20 = 5 * x - 5"], ["24 = 4 + 5 * x"], ["x = 5"], ["x * 100 = 700"], ["2 * x + 5 = 105"], ["2 * x = 198"], ["x - 100 + 2 - 50 = 52"], ["x / 3 = 33"], ["x + 80 = 20"], ["x + 20 = -60"], ["5 * x + 20 - x = 60"], ["x + x + 6 = 10"], ["5 * x = x + 8"], ["x = x / 2 + 25"], ["(5 - 3) * x = x + 2"], ["(x - 30) * 2 = x"]], "outputs": [[25], [5], [5], [4], [5], [7], [50], [99], [200], [99], [-60], [-80], [10], [2], [2], [50], [2], [60]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Fundamentals", "Puzzles"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics", "Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/59c2e2a36bddd2707e000079", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve_for_x", "task_id": "TACO_lite/8", "example": [[["x - 5 = 20"], ["20 = 5 * x - 5"], ["5 * x = x + 8"], ["(5 - 3) * x = x + 2"]], ["25", "5", "2", "2"]]} +{"requirement": "Implement function which will return sum of roots of a quadratic equation rounded to 2 decimal places, if there are any possible roots, else return **None/null/nil/nothing**. If you use discriminant,when discriminant = 0, x1 = x2 = root => return sum of both roots. There will always be valid arguments. \n\nQuadratic equation - https://en.wikipedia.org/wiki/Quadratic_equation", "solutions": ["def roots(a, b, c):\n if b ** 2 >= 4 * a * c:\n return round(-b / a, 2)", "def roots(a, b, c):\n import math\n d = b ** 2 - 4 * a * c\n if d > 0:\n return round(-2 * b / (2 * a), 2)\n elif d == 0:\n x = -b / (2 * a)\n return x * 2\n else:\n return None", "def roots(a, b, c):\n return round(-b / a, 2) if b * b - 4 * a * c >= 0 else None", "def roots(a, b, c):\n d = b ** 2 - 4 * a * c\n if d < 0:\n return None\n elif d == 0:\n return (-b + d ** 0.5) / (2 * a) * 2\n else:\n x1 = (-b + d ** 0.5) / (2 * a)\n x2 = (-b - d ** 0.5) / (2 * a)\n return round(x1 + x2, 2)", "def roots(a, b, c):\n d = b ** 2 - 4 * a * c\n if d >= 0:\n return round(-b / a, 2)", "roots = lambda a, b, c: None if b * b < a * c * 4 else round(-b / a, 2)", "def roots(a, b, c):\n D = b ** 2 - 4 * a * c\n if D < 0:\n return None\n if D == 0:\n x = (-b + D ** 0.5) / (2 * a)\n return round(x * 2, 2)\n if D > 0:\n x1 = (-b + D ** 0.5) / (2 * a)\n x2 = (-b - D ** 0.5) / (2 * a)\n return round(x1 + x2, 2)", "import math\n\ndef roots(a, b, c):\n dis = b ** 2 - 4 * a * c\n if dis < 0:\n return None\n return round((-b + math.sqrt(dis)) / (2 * a) + (-b - math.sqrt(dis)) / (2 * a), 2)", "import math\n\ndef roots(a, b, c):\n d = round(b * b - 4 * a * c, 2)\n if d < 0:\n return None\n return round(-b / a, 2)"], "starter_code": "def roots(a,b,c):\n", "input_output": {"fn_name": "roots", "inputs": [[1, -35, -23], [6, 0, -24], [-5, 21, 0], [6, 4, 8], [1, 5, -24], [3, 11, 6], [2, 2, 9], [1, -1.6666666666666667, -26], [1, 6, 10], [7, -2, -5], [1, 8, 20], [2, 3, -2], [1, 4, 12], [3, -2, -5], [3, 4, 9], [5, 4, 0], [4, -5, 0], [1, 4, 9], [1, 0, -49], [2, 8, 8], [1, 0, -0.16], [1, 6, 12], [1, 0, -9], [-3, 0, 12], [1, 3, 9], [3, 7, 0], [5, 3, 6], [1, 4, 4], [-1, 0, 5.29], [1, 12, 36], [1, 0, -0.09], [2, 5, 11], [3, 0, -15], [1, -3, 0], [1, 8, 16], [2, 6, 9], [-1, 36, 0], [5, -8, 0], [1, 5, 12], [-14, 0, 0], [1, 7, 20], [1, -6, 0], [1, -11, 30], [1, 3, 12], [1, 6, 9], [8, 47, 41]], "outputs": [[35], [0], [4.2], [null], [-5], [-3.67], [null], [1.67], [null], [0.29], [null], [-1.5], [null], [0.67], [null], [-0.8], [1.25], [null], [0], [-4], [0], [null], [0], [0], [null], [-2.33], [null], [-4], [0], [-12], [0], [null], [0], [3], [-8], [null], [36], [1.6], [null], [0], [null], [6], [11], [null], [-6], [-5.88]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/57d448c6ba30875437000138", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "roots", "task_id": "TACO_lite/27", "example": [[[1, -3, 2], [1, -2, 1], [1, 0, 1]], [3.0, 2.0, null]]} +{"requirement": "## Task\n\nImplement a function which finds the numbers less than `2`, and the indices of numbers greater than `1` in the given sequence, and returns them as a pair of sequences. \n\nReturn a nested array or a tuple depending on the language:\n\n* The first sequence being only the `1`s and `0`s from the original sequence. \n* The second sequence being the indexes of the elements greater than `1` in the original sequence. \n\n## Examples\n\n```python\n[ 0, 1, 2, 1, 5, 6, 2, 1, 1, 0 ] => ( [ 0, 1, 1, 1, 1, 0 ], [ 2, 4, 5, 6 ] )\n```\n\nPlease upvote and enjoy!", "solutions": ["def binary_cleaner(seq):\n res = ([], [])\n for (i, x) in enumerate(seq):\n if x < 2:\n res[0].append(x)\n else:\n res[1].append(i)\n return res", "def binary_cleaner(lst):\n return ([n for n in lst if n < 2], [i for (i, n) in enumerate(lst) if n > 1])", "def binary_cleaner(seq):\n return (list(filter(lambda x: x <= 1, seq)), [i for i in range(len(seq)) if seq[i] > 1])", "def binary_cleaner(seq):\n return ([x for x in seq if x in [0, 1]], [i for (i, x) in enumerate(seq) if x > 1])", "def binary_cleaner(seq):\n return ([value for value in seq if value == 0 or value == 1], [index for (index, value) in enumerate(seq) if value not in (0, 1)])", "def binary_cleaner(seq):\n return ([n for n in seq if n < 2], [i for (i, n) in enumerate(seq) if n > 1])", "def binary_cleaner(seq):\n (list_a, list_b) = ([], [])\n for (k, v) in enumerate(seq):\n if v > 1:\n list_b.append(k)\n else:\n list_a.append(v)\n return (list_a, list_b)", "def binary_cleaner(seq):\n b = []\n x = []\n for i in range(len(seq)):\n if seq[i] < 2:\n b.append(seq[i])\n elif seq[i] > 1:\n x.append(i)\n return (b, x)", "def binary_cleaner(seq):\n less_than_1 = []\n index_list = []\n for (i, x) in enumerate(seq):\n if x < 2:\n less_than_1.append(x)\n if x > 1:\n index_list.append(i)\n return (less_than_1, index_list)", "def binary_cleaner(seq):\n return ([i for i in seq if i <= 1], [i for (i, el) in enumerate(seq) if el > 1])"], "starter_code": "def binary_cleaner(seq):\n", "input_output": {"fn_name": "binary_cleaner", "inputs": [[[0, 1, 2, 1, 0, 2, 1, 1, 1, 0, 4, 5, 6, 2, 1, 1, 0]], [[0, 1, 1, 2, 0]], [[2, 2, 0]], [[0, 1, 2, 1, 0, 2, 1, 1]], [[1]], [[3, 0, 7, 0, 2, 0]]], "outputs": [[[[0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0], [2, 5, 10, 11, 12, 13]]], [[[0, 1, 1, 0], [3]]], [[[0], [0, 1]]], [[[0, 1, 1, 0, 1, 1], [2, 5]]], [[[1], []]], [[[0, 0, 0], [0, 2, 4]]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5b5097324a317afc740000fe", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "binary_cleaner", "task_id": "TACO_lite/77", "example": [[[[0, 1, 2, 1, 5, 6, 2, 1, 1, 0]]], ["([0, 1, 1, 1, 1, 0], [2, 4, 5, 6])"]]} +{"requirement": "The task is to complete the insert() function which is used to implement Insertion Sort. \nExample 1:\nInput:\nN = 5\narr[] = { 4, 1, 3, 9, 7}\nOutput:\n1 3 4 7 9\nExample 2:\nInput:\nN = 10\narr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}\nOutput:\n1 2 3 4 5 6 7 8 9 10\nYour Task: \nYou don't have to read input or print anything. Your task is to complete the function insert() and insertionSort() where insert() takes the array, it's size and an index i and insertionSort() uses insert function to sort the array in ascending order using insertion sort algorithm. \nExpected Time Complexity: O(N*N).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= N <= 1000\n1 <= arr[i] <= 1000", "solutions": ["def insert(alist, index, n):\n x = alist[index]\n j = index - 1\n while j >= 0 and alist[j] > x:\n alist[j + 1] = alist[j]\n j -= 1\n alist[j + 1] = x\n\ndef insertionSort(alist, n):\n for i in range(1, n):\n self.insert(arr, i, n)", "def insert(alist, index, n):\n j = index\n while j > 0 and alist[j - 1] > alist[j]:\n temp = alist[j]\n alist[j] = alist[j - 1]\n alist[j - 1] = temp\n j -= 1\n return alist\n\ndef insertionSort(alist, n):\n for i in range(n):\n alist = self.insert(alist, i, n)\n return alist", "def insertionSort(alist, n):\n for i in range(1, len(alist)):\n key = alist[i]\n j = i - 1\n while j >= 0 and alist[j] > key:\n alist[j + 1] = alist[j]\n j -= 1\n alist[j + 1] = key\n return alist", "def insertionSort(alist, n):\n for i in range(n):\n tmp = alist[i]\n j = i - 1\n while j >= 0 and alist[j] > tmp:\n alist[j + 1] = alist[j]\n j = j - 1\n alist[j + 1] = tmp", "def insertionSort(alist, n):\n for i in range(1, n):\n for j in reversed(range(i)):\n if alist[j] > alist[j + 1]:\n (alist[j], alist[j + 1]) = (alist[j + 1], alist[j])\n else:\n break\n return alist", "def insert(alist, index, n):\n pass\n\ndef insertionSort(alist, n):\n for i in range(n):\n mini = i\n for j in range(i + 1, n):\n if alist[j] < alist[mini]:\n mini = j\n (alist[mini], alist[i]) = (alist[i], alist[mini])\n return alist", "def insertionSort(alist, n):\n alist.sort()\n return alist", "def insert(alist, index, n):\n for index in range(n):\n alist.append(alist[index])\n\ndef insertionSort(alist, n):\n alist.sort()\n return alist", "def insert(alist, index, n):\n if index == n:\n return\n j = index - 1\n key = arr[index]\n while j >= 0 and key <= alist[j]:\n alist[j + 1] = alist[j]\n j -= 1\n alist[j + 1] = key\n self.insert(alist, index + 1, n)\n\ndef insertionSort(alist, n):\n self.insert(alist, 1, n)\n return alist", "def insert(alist, index, n):\n self.insertionSort(alist, n)\n\ndef insertionSort(alist, n):\n for index in range(1, n):\n curr = alist[index]\n pos = index\n while curr < alist[pos - 1] and pos > 0:\n alist[pos] = alist[pos - 1]\n pos = pos - 1\n alist[pos] = curr\n return", "def insert(alist, index, n):\n key = alist[index]\n i = index - 1\n while i >= 0 and alist[i] > key:\n alist[i + 1] = alist[i]\n i -= 1\n alist[i + 1] = key\n\ndef insertionSort(alist, n):\n for i in range(1, n):\n self.insert(alist, i, n)", "def insert(arr, index, n):\n if index > n - 1:\n return\n temp = arr[index]\n j = index - 1\n while j >= 0 and temp < arr[j]:\n arr[j + 1] = arr[j]\n j -= 1\n arr[j + 1] = temp\n self.insert(arr, index + 1, n)\n\ndef insertionSort(arr, n):\n self.insert(arr, 1, n)\n return arr", "def insert(alist, index, n):\n return alist.sort()\n\ndef insertionSort(alist, n):\n return alist.sort()", "def insert(arr, index, n):\n s = arr.sort()\n return s\n\ndef insertionSort(arr, n):\n k = arr.sort()\n return k", "def insert(alist, index, n):\n while index != 0:\n if alist[index] < alist[index - 1]:\n (alist[index], alist[index - 1]) = (alist[index - 1], alist[index])\n else:\n break\n index -= 1\n\ndef insertionSort(arr, n):\n for i in range(n - 1):\n if arr[i] > arr[i + 1]:\n self.insert(arr, i + 1, n)", "def insertionSort(arr, n):\n for i in range(n):\n current = arr[i]\n j = i - 1\n while j >= 0 and arr[j] > current:\n arr[j + 1] = arr[j]\n j = j - 1\n arr[j + 1] = current", "def insert(alist, index, n):\n pass\n\ndef insertionSort(alist, n):\n arr.sort()", "def insertionSort(alist, n):\n for i in range(1, n):\n valuetosort = alist[i]\n while alist[i - 1] > valuetosort and i > 0:\n (alist[i], alist[i - 1]) = (alist[i - 1], alist[i])\n i -= 1\n return arr", "def insert(l, i, n):\n for j in range(i, 0, -1):\n if l[j] < l[j - 1]:\n (l[j], l[j - 1]) = (l[j - 1], l[j])\n else:\n break\n\ndef insertionSort(l, n):\n for i in range(1, n):\n x = self.insert(l, i, n)", "def insertionSort(a, n):\n for i in range(1, n):\n x = a[i]\n j = i - 1\n while j >= 0 and a[j + 1] < a[j]:\n (a[j], a[j + 1]) = (a[j + 1], a[j])\n j = j - 1", "def insert(alist, index, n):\n pass\n\ndef insertionSort(alist, n):\n a = alist.sort()\n return a", "def insert(alist, index, n):\n return\n\ndef insertionSort(alist, n):\n for i in range(1, len(alist)):\n a = i\n while a > 0 and alist[a - 1] > alist[a]:\n (alist[a - 1], alist[a]) = (alist[a], alist[a - 1])\n a -= 1\n return alist", "def insert(alist, index, n):\n currentvalue = alist[index]\n position = index\n while position > 0 and alist[position - 1] > currentvalue:\n alist[position] = alist[position - 1]\n position = position - 1\n alist[position] = currentvalue\n\ndef insertionSort(alist, n):\n for index in range(1, n):\n self.insert(arr, index, n)", "def insert(a, n, i):\n if i == n:\n return\n temp = a[i]\n j = i - 1\n while j >= 0 and a[j] > temp:\n a[j + 1] = a[j]\n j -= 1\n a[j + 1] = temp\n self.insert(a, n, i + 1)\n\ndef insertionSort(alist, n):\n self.insert(alist, n, 1)", "def insert(alist, i, n):\n while i and alist[i] < alist[i - 1]:\n (alist[i], alist[i - 1]) = (alist[i - 1], alist[i])\n i -= 1\n\ndef insertionSort(alist, n):\n if n <= 1:\n return\n for i in range(1, n):\n self.insert(alist, i, n)", "def insert(alist, index, n):\n current_value = alist[index]\n while index > 0 and alist[index - 1] > current_value:\n alist[index] = alist[index - 1]\n index -= 1\n alist[index] = current_value\n\ndef insertionSort(alist, n):\n for index in range(1, n):\n self.insert(alist, index, n)", "def insertionSort(alist, n):\n if n <= 1:\n return\n Solution().insertionSort(alist, n - 1)\n last = arr[n - 1]\n j = n - 2\n while j >= 0 and alist[j] > last:\n alist[j + 1] = alist[j]\n j -= 1\n alist[j + 1] = last", "def insert(alist, index, n):\n for i in range(index):\n if alist[i] > alist[index]:\n (alist[i], alist[index]) = (alist[index], alist[i])\n\ndef insertionSort(alist, n):\n for i in range(1, n):\n self.insert(alist, i, n)", "def insert(alist, index, n):\n pass\n\ndef insertionSort(arr, n):\n n = len(arr)\n for i in range(n):\n index = i\n swap = 0\n while index > 0 and arr[index] <= arr[index - 1]:\n (arr[index], arr[index - 1]) = (arr[index - 1], arr[index])\n index -= 1", "def insertionSort(alist, n):\n for i in range(1, n):\n prev_range = range(i - 1, -1, -1)\n val = alist[i]\n for j in prev_range:\n if val > alist[j]:\n alist[j + 1] = val\n break\n alist[j + 1] = alist[j]\n else:\n alist[j] = val", "def insertionSort(a, n):\n for i in range(1, n):\n k = a[i]\n j = i - 1\n while j >= 0 and k < a[j]:\n a[j + 1] = a[j]\n j = j - 1\n a[j + 1] = k\n return a", "def insert(arr, n):\n for i in range(n, 0, -1):\n if arr[i - 1] > arr[i]:\n (arr[i - 1], arr[i]) = (arr[i], arr[i - 1])\n else:\n return\n\ndef insertionSort(arr, n):\n for i in range(1, n):\n if arr[i - 1] > arr[i]:\n insert(arr, i)\n return arr"], "starter_code": "def insert(alist, index, n):\n", "input_output": {"inputs": ["N = 5\narr[] = { 4, 1, 3, 9, 7}", "N = 10\narr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}"], "outputs": ["1 3 4 7 9", "1 2 3 4 5 6 7 8 9 10"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Sorting"], "name": null, "source": "geeksforgeeks", "tags": ["Sorting"], "skill_types": ["Sorting"], "url": "https://practice.geeksforgeeks.org/problems/insertion-sort/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*N).", "entry_point": "insert", "task_id": "TACO_lite/23", "example": [[], []]} +{"requirement": "Given a matrix A of dimensions NxN where every element is either O or X. Find the largest subsquare surrounded by X.\nExample 1:\nInput:\nN=2\nA=[[X,X][X,X]]\nOutput:\n2\nExplanation:\nThe largest square submatrix \nsurrounded by X is the whole \ninput matrix.\nExample 2:\nInput:\nN=4\nA=[[X,X,X,O],[X,O,X,X],\n[X,X,X,O],[X,O,X,X]]\nOutput:\n3\nExplanation:\nHere,the input represents following \nmatrix of size 4 x 4\nX X X O\nX O X X\nX X X O\nX O X X\nThe square submatrix starting at \n(0,0) and ending at (2,2) is the \nlargest submatrix surrounded by X.\nTherefore, size of that matrix would be 3.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function largestSubsquare() which takes the integer N and the matrix A as input parameters and returns the size of the largest subsquare surrounded by 'X'.\nExpected Time Complexity:O(N^{2})\nExpected Auxillary Space:O(N^{2})\nConstraints:\n1<=N<=1000\nA[i][j]={'X','O'}", "solutions": ["def largestsubsquare(N, A):\n m = [[[0 for _ in range(N)] for _ in range(N)] for _ in range(2)]\n for i in range(N):\n m[0][i][0] = 1 if A[i][0] == 'X' else 0\n for j in range(1, N):\n if A[i][j] == 'X':\n m[0][i][j] = m[0][i][j - 1] + 1\n for j in range(N):\n m[1][0][j] = 1 if A[0][j] == 'X' else 0\n for i in range(1, N):\n if A[i][j] == 'X':\n m[1][i][j] = m[1][i - 1][j] + 1\n ans = 0\n for i in range(N):\n for j in range(N):\n d = min(m[0][i][j], m[1][i][j])\n while d > 0:\n if m[0][i - d + 1][j] >= d and m[1][i][j - d + 1] >= d:\n ans = max(d, ans)\n break\n d -= 1\n return ans", "def get_hor_mat(n, a, hor):\n for i in range(n):\n for j in range(n):\n if i >= 0 and j == 0:\n if a[i][j] == 'X':\n hor[i][j] = 1\n else:\n hor[i][j] = 0\n elif a[i][j] == 'X':\n hor[i][j] = hor[i][j - 1] + 1\n else:\n continue\n\ndef get_ver_mat(n, a, ver):\n for i in range(n):\n for j in range(n):\n if i == 0 and j >= 0:\n if a[i][j] == 'X':\n ver[i][j] = 1\n elif a[i][j] == 'X':\n ver[i][j] = ver[i - 1][j] + 1\n\ndef largestsubsquare(n, a):\n hor = [[0 for j in range(n)] for i in range(n)]\n ver = [[0 for j in range(n)] for i in range(n)]\n max_square = 0\n self.get_hor_mat(n, a, hor)\n self.get_ver_mat(n, a, ver)\n for i in range(n - 1, -1, -1):\n for j in range(n - 1, -1, -1):\n min_val = min(hor[i][j], ver[i][j])\n while min_val > max_square:\n if ver[i][j - min_val + 1] >= min_val and hor[i - min_val + 1][j] >= min_val:\n max_square = min_val\n min_val -= 1\n return max_square", "def largestsubsquare(N, A):\n (ROWS, COLS) = (len(A), len(A[0]))\n dp = [[[0, 0] for i in range(ROWS + 1)] for j in range(COLS + 1)]\n for i in range(ROWS):\n for j in range(COLS):\n if A[i][j] == 'X':\n dp[i + 1][j + 1][0] = dp[i][j + 1][0] + 1\n dp[i + 1][j + 1][1] = dp[i + 1][j][1] + 1\n maxi = 0\n for i in range(ROWS, 0, -1):\n for j in range(COLS, 0, -1):\n curMin = min(dp[i][j][0], dp[i][j][1])\n while curMin > maxi:\n if dp[i - curMin + 1][j][1] >= curMin and dp[i][j - curMin + 1][0] >= curMin:\n maxi = curMin\n else:\n curMin -= 1\n return maxi", "def largestsubsquare(N, A):\n left_c = [[0] * N for i in range(N)]\n top_c = [[0] * N for i in range(N)]\n for i in range(N):\n for j in range(N):\n if A[i][j] == 'X':\n left_c[i][j] = (left_c[i][j - 1] if j > 0 else 0) + 1\n top_c[i][j] = (top_c[i - 1][j] if i > 0 else 0) + 1\n max_len = 0\n for i in range(N - 1, -1, -1):\n for j in range(N - 1, -1, -1):\n val = min(left_c[i][j], top_c[i][j])\n while val > max_len:\n if top_c[i][j - val + 1] >= val and left_c[i - val + 1][j] >= val:\n max_len = max(max_len, val)\n val -= 1\n return max_len", "def largestsubsquare(n, a):\n dp = [[[0, 0] for i in range(n)] for i in range(n)]\n dp[0][0] = [1, 1] if a[0][0] == 'X' else [0, 0]\n m = dp[0][0][0]\n\n def check(i, j, back):\n nonlocal dp\n nonlocal m\n while back > m and (dp[i - back + 1][j][1] < back or dp[i][j - back + 1][0] < back):\n back -= 1\n return back if back > m else m\n for i in range(1, n):\n if a[0][i] == 'X':\n dp[0][i] = [1, dp[0][i - 1][1] + 1]\n if a[i][0] == 'X':\n dp[i][0] = [dp[i - 1][0][0] + 1, 1]\n m = max(m, min(dp[0][i]), min(dp[i][0]))\n for i in range(1, n):\n for j in range(1, n):\n if a[i][j] == 'X':\n dp[i][j][0] = dp[i - 1][j][0] + 1\n dp[i][j][1] = dp[i][j - 1][1] + 1\n x = min(dp[i][j])\n if x > m:\n m = check(i, j, x)\n return m", "def largestsubsquare(N, A):\n a = [[[0, 0] for i in range(N)] for i in range(N)]\n for i in range(N):\n for j in range(N):\n if A[i][j] == 'O':\n a[i][j][0] = 0\n a[i][j][1] = 0\n elif A[i][j] == 'X':\n if i - 1 >= 0:\n a[i][j][1] = a[i - 1][j][1] + 1\n else:\n a[i][j][1] = 1\n if j - 1 >= 0:\n a[i][j][0] = a[i][j - 1][0] + 1\n else:\n a[i][j][0] = 1\n max = 0\n for i in range(N):\n for j in range(N):\n aa = min(a[i][j][0], a[i][j][1])\n while aa > max:\n if aa > max and a[i - aa + 1][j][0] >= aa and (a[i][j - aa + 1][1] >= aa):\n max = aa\n break\n aa -= 1\n return max", "def largestsubsquare(N, mat):\n Max = 0\n mp = [[(0, 0) for i in range(N)] for i in range(N)]\n for i in range(N):\n for j in range(N):\n if mat[i][j] == 'O':\n mp[i][j] = (0, 0)\n elif i == 0 and j == 0:\n mp[i][j] = (1, 1)\n elif i == 0:\n mp[i][j] = (1, mp[i][j - 1][1] + 1)\n elif j == 0:\n mp[i][j] = (mp[i - 1][j][0] + 1, 1)\n else:\n mp[i][j] = (mp[i - 1][j][0] + 1, mp[i][j - 1][1] + 1)\n for i in range(N - 1, -1, -1):\n for j in range(N - 1, -1, -1):\n small = mp[i][j][0] if mp[i][j][0] < mp[i][j][1] else mp[i][j][1]\n while small > Max:\n if mp[i][j - small + 1][0] >= small and mp[i - small + 1][j][1] >= small:\n Max = small\n small -= 1\n return Max"], "starter_code": "def largestsubsquare(N,A):\n", "input_output": {"inputs": ["N=2\r\nA=[[X,X][X,X]]", "N=4\r\nA=[[X,X,X,O],[X,O,X,X],\r\n[X,X,X,O],[X,O,X,X]]"], "outputs": ["2", "3"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/largest-subsquare-surrounded-by-x0558/1", "Expected Auxiliary Space": "O(N^{2})", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N^{2})", "entry_point": "largestsubsquare", "task_id": "TACO_lite/41", "example": [[[2, [["X", "X"], ["X", "X"]]], [4, [["X", "X", "X", "O"], ["X", "O", "X", "X"], ["X", "X", "X", "O"], ["X", "O", "X", "X"]]]], ["2", "3"]]} +{"requirement": "Given a matrix consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every\u00a0cell in that column.\u00a0 Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0.\nReturn the maximum number of rows that have all values equal after some number of flips.\n\u00a0\n\n\n\nExample 1:\nInput: [[0,1],[1,1]]\nOutput: 1\nExplanation: After flipping no values, 1 row has all values equal.\n\n\nExample 2:\nInput: [[0,1],[1,0]]\nOutput: 2\nExplanation: After flipping values in the first column, both rows have equal values.\n\n\nExample 3:\nInput: [[0,0,0],[0,0,1],[1,1,0]]\nOutput: 2\nExplanation: After flipping values in the first two columns, the last two rows have equal values.\n\n\u00a0\nNote:\n\n1 <= matrix.length <= 300\n1 <= matrix[i].length <= 300\nAll matrix[i].length's are equal\nmatrix[i][j] is\u00a00 or 1", "solutions": ["def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n dict_ = {}\n for row in matrix:\n curr_tuple = tuple(row)\n dict_[curr_tuple] = 1 + dict_.get(curr_tuple, 0)\n visited = set()\n max_same = 0\n for row in matrix:\n curr_tuple = tuple(row)\n if curr_tuple in visited:\n continue\n visited.add(curr_tuple)\n inverse = [1] * len(row)\n for i in range(len(row)):\n if row[i]:\n inverse[i] = 0\n curr_inv = tuple(inverse)\n visited.add(curr_inv)\n curr_sum = 0\n curr_sum = dict_[curr_tuple]\n if curr_inv in dict_:\n curr_sum += dict_[curr_inv]\n if curr_sum > max_same:\n max_same = curr_sum\n return max_same", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n pattern_dict = {}\n for row in matrix:\n if row[0] == 0:\n key = tuple(row)\n else:\n newrow = [1 - x for x in row]\n key = tuple(newrow)\n if key in pattern_dict:\n pattern_dict[key] += 1\n else:\n pattern_dict[key] = 1\n maxnum = 0\n for (_, num) in pattern_dict.items():\n maxnum = max(maxnum, num)\n return maxnum", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n if len(matrix) == 0:\n return 0\n cols = len(matrix[0])\n allOnes = 0\n for i in range(0, cols):\n allOnes <<= 1\n allOnes |= 1\n freq = {}\n count = 0\n for i in range(0, len(matrix)):\n rowNumber = 0\n for j in range(0, len(matrix[i])):\n rowNumber = rowNumber << 1\n rowNumber = rowNumber | matrix[i][j]\n xorRowNumber = rowNumber ^ allOnes\n if rowNumber in freq:\n freq[rowNumber] += 1\n count = max(count, freq[rowNumber])\n elif xorRowNumber in freq:\n freq[xorRowNumber] += 1\n count = max(count, freq[xorRowNumber])\n else:\n freq[rowNumber] = 1\n count = max(count, freq[rowNumber])\n return count", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n dic = {}\n for i in range(len(matrix)):\n a = ''\n b = ''\n for j in range(len(matrix[0])):\n a = a + '%d' % matrix[i][j]\n b = b + '%d' % (1 - matrix[i][j])\n if a not in dic:\n dic[a] = 1\n else:\n dic[a] += 1\n if b not in dic:\n dic[b] = 1\n else:\n dic[b] += 1\n m = 0\n for k in dic.keys():\n m = max(m, dic[k])\n return m", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n counter = {}\n for row in matrix:\n key = tuple((x ^ row[0] for x in row))\n counter[key] = counter.get(key, 0) + 1\n return max(counter.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n dicts = {}\n for row in matrix:\n bin_rep = ''.join([str(x) for x in row])\n if bin_rep not in dicts:\n dicts[bin_rep] = 1\n else:\n dicts[bin_rep] += 1\n rev_bin_rep = ''.join([str(x ^ 1) for x in row])\n if rev_bin_rep not in dicts:\n dicts[rev_bin_rep] = 1\n else:\n dicts[rev_bin_rep] += 1\n res = 0\n for (key, value) in dicts.items():\n res = max(res, value)\n return res", "def maxequalrowsafterflips(ma: List[List[int]]) -> int:\n n = len(ma)\n m = len(ma[0])\n di = {}\n for i in range(n):\n s = ''\n ss = ''\n for j in range(m):\n s = s + str(ma[i][j])\n ss = ss + str(1 - ma[i][j])\n di[s] = di.get(s, 0) + 1\n di[ss] = di.get(ss, 0) + 1\n return max(list(di.values()))", "import collections\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n return max(collections.Counter((tuple((x ^ r[0] for x in r)) for r in matrix)).values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n\n def find_minor(row):\n one = row.count(1)\n if one * 2 == len(row):\n return tuple((i for (i, val) in enumerate(row) if val == row[-1]))\n elif one * 2 > len(row):\n return tuple((i for (i, val) in enumerate(row) if val == 0))\n return tuple((i for (i, val) in enumerate(row) if val == 1))\n counts = collections.Counter()\n for (i, row) in enumerate(matrix):\n counts[find_minor(row)] += 1\n return max(counts.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n n = len(matrix)\n m = len(matrix[0])\n mx = 1\n for i in range(n):\n c = [0 for i in range(m)]\n for j in range(m):\n if matrix[i][j] == 0:\n c[j] = 1\n else:\n c[j] = 0\n count = 1\n for j in range(n):\n if i != j and c == matrix[j] or matrix[i] == matrix[j]:\n count += 1\n mx = max(mx, count)\n return mx - 1", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n n = len(matrix)\n m = len(matrix[0])\n res = 0\n for i in range(n):\n flip = [1 - matrix[i][j] for j in range(m)]\n cnt = 0\n for k in range(n):\n if matrix[i] == matrix[k] or flip == matrix[k]:\n cnt += 1\n res = max(res, cnt)\n return res", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n counter = collections.Counter()\n for row in matrix:\n flipper = {1: 0, 0: 1}\n if row[0] == 0:\n row = [flipper[col] for col in row]\n counter[tuple(row)] += 1\n return max(counter.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n rows = {}\n max_value = 0\n n = len(matrix)\n m = len(matrix[0])\n for i in range(n):\n a = []\n b = []\n for j in range(m):\n if matrix[i][j] == 0:\n a.append(j)\n else:\n b.append(j)\n a = tuple(a)\n b = tuple(b)\n if a not in rows:\n rows[a] = 0\n if b not in rows:\n rows[b] = 0\n rows[a] += 1\n rows[b] += 1\n max_value = max(max_value, rows[a], rows[b])\n return max_value", "def maxequalrowsafterflips(mat: List[List[int]]) -> int:\n dic = defaultdict(lambda : 0)\n for r in range(len(mat)):\n row = mat[r]\n ones = 0\n zeros = 0\n for i in range(len(row)):\n if row[i] == 0:\n ones = ones << 1\n zeros = zeros << 1\n ones |= 1\n else:\n zeros = zeros << 1\n ones = ones << 1\n zeros |= 1\n dic[zeros] += 1\n dic[ones] += 1\n return max(dic.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n cache = collections.defaultdict(int)\n for row in matrix:\n vals = []\n trans = []\n for c in row:\n vals.append(c)\n trans.append(1 - c)\n cache[str(vals)] += 1\n cache[str(trans)] += 1\n return max(cache.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n rows = {}\n max_value = 0\n n = len(matrix)\n for i in range(n):\n if matrix[i][0] == 1:\n a = tuple(matrix[i])\n else:\n a = tuple([1 - c for c in matrix[i]])\n if a not in rows:\n rows[a] = 0\n rows[a] += 1\n max_value = max(max_value, rows[a])\n return max_value", "from collections import Counter\n\ndef flip(bits):\n return [1 if bit == 0 else 0 for bit in bits]\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n c = Counter()\n for row in matrix:\n c.update([tuple(row)])\n c.update([tuple(flip(row))])\n return max(c.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n f = defaultdict(int)\n n = len(matrix[0])\n for i in matrix:\n (p, q) = ([], [])\n for j in range(n):\n if i[j] == 0:\n p.append(j)\n else:\n q.append(j)\n f[tuple(p)] += 1\n f[tuple(q)] += 1\n return max(f.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n for (i, row) in enumerate(matrix):\n matrix[i] = tuple((x ^ row[0] for x in row))\n return max(Counter(matrix).values())", "def maxequalrowsafterflips(x: List[List[int]]) -> int:\n f = defaultdict(int)\n n = len(x[0])\n for i in x:\n p = q = 0\n v = 1\n for j in range(n):\n if i[j] == 0:\n p |= v\n else:\n q |= v\n v = v << 1\n f[p] += 1\n f[q] += 1\n return max(f.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n noninv = {}\n for row in matrix:\n row = repr(row)\n if row in noninv:\n noninv[row] += 1\n else:\n noninv[row] = 1\n count = 0\n for row in matrix:\n revrow = [i ^ 1 for i in row]\n revrow = repr(revrow)\n row = repr(row)\n if revrow in noninv:\n count = max(count, noninv[row] + noninv[revrow])\n else:\n count = max(count, noninv[row])\n return count", "from collections import defaultdict\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n lookup = collections.defaultdict(int)\n for row in matrix:\n vals = []\n trans = []\n for c in row:\n vals.append(c)\n trans.append(1 - c)\n lookup[str(vals)] += 1\n lookup[str(trans)] += 1\n return max(lookup.values())", "def maxequalrowsafterflips(mat: List[List[int]]) -> int:\n ans = 0\n (m, n) = (len(mat), len(mat[0]))\n ones = [[0] * n for i in range(m)]\n zeros = [[0] * n for i in range(m)]\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 1:\n zeros[i][j] = 1\n else:\n ones[i][j] = 1\n for i in range(m):\n for target in [ones[i], zeros[i]]:\n count = 1\n for k in range(m):\n if k == i:\n continue\n if ones[k] == target or zeros[k] == target:\n count += 1\n ans = max(ans, count)\n return ans", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n\n def reverse_row(row):\n res = [0] * len(row)\n for (i, val) in enumerate(row):\n res[i] = 1 - row[i]\n return res\n d = {}\n for row in matrix:\n rev_row = reverse_row(row)\n if tuple(row) in d:\n d[tuple(row)] += 1\n elif tuple(rev_row) in d:\n d[tuple(rev_row)] += 1\n else:\n d[tuple(row)] = 1\n res = sorted(d.items(), key=lambda x: x[1], reverse=1)\n return res[0][1]", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n counter = collections.defaultdict(int)\n for row in matrix:\n if row[0] == 1:\n row = [1 - num for num in row]\n counter[tuple(row)] += 1\n return max(counter.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n memo = collections.defaultdict(lambda : 0)\n for line in matrix:\n if line[0] == 0:\n memo[tuple(line)] += 1\n else:\n line = [1 if i == 0 else 0 for i in line]\n memo[tuple(line)] += 1\n return max(memo.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n\n def flip(row):\n return [1 - r for r in row]\n record = dict()\n for row in matrix:\n record[tuple(row)] = record.get(tuple(row), 0) + 1\n record[tuple(flip(row))] = record.get(tuple(flip(row)), 0) + 1\n return max(record.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n groups = {}\n for row in matrix:\n tuple_row = tuple(row)\n if tuple_row not in groups:\n groups[tuple_row] = 1\n else:\n groups[tuple_row] += 1\n max_equal = 0\n for row in groups.keys():\n rev_row = tuple([1 - x for x in row])\n group_max = groups[row]\n if row != rev_row and rev_row in groups:\n group_max += groups[rev_row]\n max_equal = max(max_equal, group_max)\n return max_equal", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n columnsToFlipOneForEqualRow = {}\n columnsToFlipZeroForEqualRow = {}\n self.height = len(matrix)\n self.width = len(matrix[0])\n for y in range(self.height):\n row = matrix[y]\n columnsToFlipOneForEqualRow[y] = []\n columnsToFlipZeroForEqualRow[y] = []\n for x in range(self.width):\n element = row[x]\n if element == 0:\n columnsToFlipOneForEqualRow[y].append(x)\n else:\n columnsToFlipZeroForEqualRow[y].append(x)\n patterns = {}\n for index in range(self.height):\n first = str(columnsToFlipOneForEqualRow[index])\n second = str(columnsToFlipZeroForEqualRow[index])\n if first not in patterns:\n patterns[first] = 0\n if second not in patterns:\n patterns[second] = 0\n patterns[first] += 1\n patterns[second] += 1\n return max(patterns.values())", "def convert_to_tuple(lst):\n if lst[0] == 0:\n return tuple(lst)\n else:\n return tuple([int(not x) for x in lst])\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n from collections import defaultdict\n row_counts = defaultdict(int)\n for row in matrix:\n row_counts[self.convert_to_tuple(row)] += 1\n return max(row_counts.values())", "import collections\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n ans = 1\n orig = collections.defaultdict(int)\n orig_to_xor = {}\n for row in matrix:\n curr_orig = 0\n curr_xor = 0\n for (i, c) in enumerate(row):\n curr_orig ^= c << i\n curr_xor ^= 1 - c << i\n orig[curr_orig] += 1\n orig_to_xor[curr_orig] = curr_xor\n for (curr_orig, curr_xor) in orig_to_xor.items():\n ans = max(orig[curr_orig] + orig[curr_xor], ans) if curr_orig != curr_xor else max(orig[curr_orig], ans)\n return ans", "from collections import Counter\n\ndef maxequalrowsafterflips(matrix):\n counter = Counter()\n flip = {1: 0, 0: 1}\n for row in matrix:\n if row[0] == 0:\n row = [flip[col] for col in row]\n counter[tuple(row)] += 1\n return max(counter.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n seen = defaultdict(int)\n for row in matrix:\n comp = row[0] == 1\n temp = []\n for num in row:\n if comp:\n temp.append(str(num ^ 1))\n else:\n temp.append(str(num))\n seen[''.join(temp)] += 1\n return max(seen.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n (m, n) = (len(matrix), len(matrix[0]))\n for i in range(m):\n if matrix[i][0] == 1:\n for j in range(n):\n matrix[i][j] ^= 1\n cnt = Counter(list(map(tuple, matrix)))\n return max(cnt.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n ans = 0\n for (i, r) in enumerate(matrix):\n count = 0\n flip = [1 - x for x in r]\n for j in range(i, len(matrix)):\n if r == matrix[j] or flip == matrix[j]:\n count += 1\n ans = max(ans, count)\n return ans", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n return max(Counter((tuple((num ^ r[0] for num in r)) for r in matrix)).values())", "def maxequalrowsafterflips(g: List[List[int]]) -> int:\n (rows, cols, d) = (len(g), len(g[0]), {})\n for row in range(rows):\n vct = tuple(g[row])\n d[vct] = d.setdefault(vct, 0) + 1\n res = 0\n for vct in d:\n inv = tuple((el ^ 1 for el in vct))\n if inv in d:\n matches = d[vct] + d[inv]\n else:\n matches = d[vct]\n res = max(res, matches)\n return res", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n seen = set()\n n = len(matrix)\n ans = 0\n for i in range(n):\n m = 0\n for j in range(i, n):\n if j in seen:\n continue\n if matrix[i] == matrix[j] or all((a != b for (a, b) in zip(matrix[i], matrix[j]))):\n seen.add(j)\n m += 1\n ans = max(ans, m)\n return ans", "def maxequalrowsafterflips(m: List[List[int]]) -> int:\n m = [tuple(i) for i in m]\n h = defaultdict(int)\n for i in m:\n if i in h:\n h[i] += 1\n else:\n h[i] = 1\n t = tuple((1 - x for x in i))\n if t in h:\n h[t] += 1\n else:\n h[t] = 1\n return max(h.values())", "def maxequalrowsafterflips(matrix):\n patterns = collections.Counter()\n for row in matrix:\n patterns[tuple(row)] += 1\n flip = [1 - c for c in row]\n patterns[tuple(flip)] += 1\n return max(patterns.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n firstcell = matrix[0][0]\n vals = {}\n for row in matrix:\n firstrowcell = row[0]\n mark = [0, 0]\n mark[firstrowcell] = firstcell\n mark[1 - firstrowcell] = 1 - firstcell\n num = 0\n for cell in row:\n num = num * 2 + mark[cell]\n vals[num] = 1 + vals.get(num, 0)\n maxcount = 0\n for (val, count) in vals.items():\n maxcount = max(count, maxcount)\n return maxcount", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n\n def flipped(r):\n return [1 - c for c in r]\n d = defaultdict(int)\n for r in matrix:\n s = ''.join(map(str, r))\n d[s] += 1\n s = ''.join(map(str, flipped(r)))\n d[s] += 1\n return max(d.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n max_count = 1\n swap_matrix = [[1 - val for val in row] for row in matrix]\n for (idx, row) in enumerate(matrix):\n count = 1\n for nxt_rw in range(idx + 1, len(matrix)):\n if matrix[nxt_rw] == row or matrix[nxt_rw] == swap_matrix[idx]:\n count += 1\n max_count = max(count, max_count)\n return max_count", "def flip_row(row):\n for (i, val) in enumerate(row):\n if val == 0:\n row[i] = 1\n else:\n row[i] = 0\n return row\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n seen = defaultdict(int)\n for (i, row) in enumerate(matrix):\n if tuple(row) in seen or tuple(self.flip_row(row)) in seen:\n seen[tuple(row)] += 1\n else:\n seen[tuple(row)] += 1\n result = 0\n for val in seen.values():\n result = max(result, val)\n return result", "import time\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n flip = []\n flip2 = []\n ma = 0\n for i in matrix:\n temp = [j for j in range(len(i)) if i[j] == 0]\n temp2 = [j for j in range(len(i)) if i[j] == 1]\n flip.append(temp)\n flip2.append(temp2)\n for i in flip:\n if flip.count(i) + flip2.count(i) > ma:\n ma = flip.count(i) + flip2.count(i)\n return ma", "import collections\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n ans = 1\n orig = collections.defaultdict(int)\n orig_to_xor = {}\n for row in matrix:\n curr_orig = int(''.join([str(c) for c in row]), 2)\n curr_xor = int(''.join([str(1 - c) for c in row]), 2)\n orig[curr_orig] += 1\n orig_to_xor[curr_orig] = curr_xor\n for (curr_orig, curr_xor) in orig_to_xor.items():\n ans = max(orig[curr_orig] + orig[curr_xor], ans) if curr_orig != curr_xor else max(orig[curr_orig], ans)\n return ans", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n positions = {}\n max_rows = 0\n for i in range(len(matrix)):\n zeros = []\n ones = []\n for (j, coin) in enumerate(matrix[i]):\n if coin == 0:\n zeros.append(j)\n else:\n ones.append(j)\n zeros = tuple(zeros)\n ones = tuple(ones)\n if 0 in zeros:\n key = (zeros, ones)\n else:\n key = (ones, zeros)\n positions[key] = positions.get(key, 0) + 1\n max_rows = max(max_rows, positions[key])\n return max_rows", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n d = Counter()\n for r in matrix:\n normal = []\n reverse = []\n for v in r:\n normal.append('1' if v else '0')\n reverse.append('0' if v else '1')\n d[''.join(normal)] += 1\n d[''.join(reverse)] += 1\n return max(d.values())", "from collections import defaultdict\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n d = defaultdict(int)\n for row in matrix:\n ori = ''\n inverse = ''\n for c in row:\n ori += str(c)\n inverse += str(1 - c)\n d[ori] += 1\n d[inverse] += 1\n lis = list(d.values())\n return max(lis)", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n if not matrix:\n return 0\n n = len(matrix)\n m = len(matrix[0])\n all_1 = [1] * m\n dic = {}\n for li in matrix:\n if li[0] == 0:\n li = [1 if i == 0 else 0 for i in li]\n s = ''.join([str(i) for i in li])\n if s in dic:\n dic[s] += 1\n else:\n dic[s] = 1\n return max(dic.values())", "import time\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n ma = 0\n for i in matrix:\n flipped = [1 - j for j in i]\n c = matrix.count(i) + matrix.count(flipped)\n if c > ma:\n ma = c\n return ma", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n ma = 0\n for i in matrix:\n c = matrix.count(i) + matrix.count([1 - x for x in i])\n if c > ma:\n ma = c\n return ma", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n flips_for_row = {}\n for row in matrix:\n curr_tuple = str([i for i in range(len(row)) if row[i] == 1])\n if curr_tuple in flips_for_row:\n flips_for_row[curr_tuple] = flips_for_row[curr_tuple] + 1\n else:\n flips_for_row[curr_tuple] = 1\n curr_tuple = str([i for i in range(len(row)) if row[i] == 0])\n if curr_tuple in flips_for_row:\n flips_for_row[curr_tuple] = flips_for_row[curr_tuple] + 1\n else:\n flips_for_row[curr_tuple] = 1\n return max(flips_for_row.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n row = len(matrix)\n col = len(matrix[0])\n ht = {}\n for r in range(row):\n need = [[], []]\n for c in range(col):\n if matrix[r][c] == 0:\n need[0].append(c)\n else:\n need[1].append(c)\n a = str(need[0])\n b = str(need[1])\n if a in ht:\n ht[a] += 1\n else:\n ht[a] = 1\n if b in ht:\n ht[b] += 1\n else:\n ht[b] = 1\n val = list(ht.values())\n ans = max(val)\n return ans", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n ma = 0\n for i in matrix:\n flip = [1 - x for x in i]\n c = 0\n for j in matrix:\n if j == i or j == flip:\n c += 1\n if c > ma:\n ma = c\n return ma", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n (m, n) = (len(matrix), len(matrix[0]))\n cnt = defaultdict(int)\n for i in range(m):\n (s1, s2) = ('', '')\n for j in range(n):\n s1 += str(matrix[i][j])\n s2 += str(1 ^ matrix[i][j])\n cnt[s1] += 1\n cnt[s2] += 1\n return max(list(cnt.values()))", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n flipper = int(''.join([str(bit) for bit in [1] * len(matrix[1])]), 2)\n bits = [int(''.join([str(bit) for bit in row]), 2) for row in matrix]\n mx = 1\n for bit1 in bits:\n count = sum((1 for bit in bits if bit == bit1 or bit1 ^ flipper == bit))\n mx = max(mx, count)\n return mx", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n rm = {}\n for row in matrix:\n r1 = '#'.join([str(x) for x in row])\n r2 = '#'.join(['1' if x == 0 else '0' for x in row])\n if r1 in rm:\n rm[r1] += 1\n elif r2 in rm:\n rm[r2] += 1\n else:\n rm[r1] = 1\n return max(rm.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n count = {}\n for i in range(len(matrix)):\n row = []\n for j in range(len(matrix[0])):\n row.append(matrix[i][j] ^ matrix[i][0])\n k = ''.join(map(str, row))\n if k not in count:\n count[k] = 1\n else:\n count[k] += 1\n res = 0\n for (k, v) in count.items():\n res = max(res, v)\n return res", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n cache = collections.defaultdict(int)\n for row in matrix:\n values = []\n flips = []\n for col in row:\n values.append(col)\n flips.append(1 - col)\n cache[str(values)] += 1\n cache[str(flips)] += 1\n return max(cache.values())", "def __init__():\n self.left = None\n self.right = None\n self.data = -1\n\ndef insert(zero, n, row: List[int], i: int, counts: List[int]) -> int:\n if len(row) == n:\n if self.data == -1:\n self.data = i\n counts[self.data] = 1 + counts[i]\n return i + 1\n else:\n counts[self.data] += 1\n return i\n elif row[n] == zero:\n if self.left is None:\n self.left = Tree()\n return self.left.insert(zero, n + 1, row, i, counts)\n else:\n if self.right is None:\n self.right = Tree()\n return self.right.insert(zero, n + 1, row, i, counts)\n\ndef maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n firstcell = matrix[0][0]\n vals = Tree()\n counts = [0] * 300\n nextfree = 0\n for row in matrix:\n firstrowcell = row[0]\n nextfree = vals.insert(firstcell if firstrowcell == 0 else 1 - firstcell, 0, row, nextfree, counts)\n return max(counts)", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n mod = 10 ** 9 + 7\n d = collections.defaultdict(int)\n (m, n) = (len(matrix), len(matrix[0]))\n for i in range(m):\n t1 = 0\n t2 = 0\n for j in range(n):\n t1 = ((t1 << 1) + matrix[i][j]) % mod\n t2 = ((t2 << 1) + 1 - matrix[i][j]) % mod\n d[t1] += 1\n d[t2] += 1\n return max(d.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n\n def encode(row):\n (i, l) = (row[0], 0)\n result = ''\n result2 = ''\n for j in row:\n if j == i:\n l += 1\n else:\n result += f'{i}{l}'\n result2 += f'{(i + 1) % 2}{l}'\n i = j\n l = 1\n result += f'{i}{l}'\n result2 += f'{(i + 1) % 2}{l}'\n return (result, result2)\n (m, n) = (len(matrix), len(matrix[0]))\n g = {}\n for i in range(m):\n (a, b) = encode(matrix[i])\n if a in g:\n g[a] += 1\n elif b in g:\n g[b] += 1\n else:\n g[a] = g.get(a, 0) + 1\n return max(g.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n ans = 0\n orig = [int(''.join([str(c) for c in row]), 2) for row in matrix]\n xor = [int(''.join([str(1 - c) for c in row]), 2) for row in matrix]\n for i in range(len(matrix)):\n curr = 1\n for j in range(i + 1, len(matrix)):\n is_complement = xor[i] == orig[j]\n is_equal = orig[i] == orig[j]\n curr += int(is_complement or is_equal)\n ans = max(curr, ans)\n return ans", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n hashTab = defaultdict(int)\n (rows, cols) = (len(matrix), len(matrix[0]))\n allOnes = int('1' * cols, 2)\n maxSizeGroup = 0\n for row in matrix:\n val = reduce(lambda a, x: a << 1 ^ x, row)\n if val not in hashTab:\n val ^= allOnes\n hashTab[val] += 1\n maxSizeGroup = max(maxSizeGroup, hashTab[val])\n return maxSizeGroup", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n counts = defaultdict(int)\n for row in matrix:\n counts[tuple(row) if row[0] else tuple((x ^ 1 for x in row))] += 1\n return max(counts.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n options = {tuple([]): 0}\n best = tuple([])\n for i in range(len(matrix)):\n option0 = []\n option1 = []\n for j in range(len(matrix[i])):\n if matrix[i][j] == 1:\n option0.append(j)\n else:\n option1.append(j)\n for option in [tuple(option0), tuple(option1)]:\n if option in options:\n options[option] += 1\n else:\n options[option] = 1\n if options[option] > options[best]:\n best = option\n return options[best]", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n d = Counter()\n for r in matrix:\n normal = []\n reverse = []\n for v in r:\n normal.append(str(v))\n reverse.append(str(1 - v))\n d[''.join(normal)] += 1\n d[''.join(reverse)] += 1\n return max(d.values())", "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n n = len(matrix[0])\n matrix = [[str(elem) for elem in row] for row in matrix]\n int_rep_of_matrix = [int(''.join(row), 2) for row in matrix]\n list_of_k = list(int_rep_of_matrix)\n all_ones = 2 ** n - 1\n for elem in int_rep_of_matrix:\n list_of_k.append(elem ^ all_ones)\n answer = 0\n for k in list_of_k:\n current_answer = 0\n for matrix_row in int_rep_of_matrix:\n if matrix_row ^ k == 0 or matrix_row ^ k == all_ones:\n current_answer += 1\n answer = max(answer, current_answer)\n return answer"], "starter_code": "def maxequalrowsafterflips(matrix: List[List[int]]) -> int:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Hash Table", "Matrix"], "name": null, "source": "leetcode", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "maxequalrowsafterflips", "task_id": "TACO_lite/82", "example": [[[[[0, 1], [1, 1]]], [[[0, 1], [1, 0]]], [[[0, 0, 0], [0, 0, 1], [1, 1, 0]]]], ["1", "2", "2"]]} +{"requirement": "Below is a right-angled triangle:\n\n```\n |\\\n | \\\n | \\\n | \\ \no | \\ h \n | \\\n | \u03b8 \\\n |_______\\ \n a\n```\n\nYour challange is to write a function (```missingAngle``` in C/C#, ```missing_angle``` in Ruby), that calculates the angle \u03b8 in degrees to the nearest integer. You will be given three arguments representing each side: o, h and a. One of the arguments equals zero. Use the length of the two other sides to calculate \u03b8. You will not be expected to handle any erronous data in your solution.", "solutions": ["import math\n\ndef missing_angle(h, a, o):\n if h == 0:\n radians = math.atan(o / a)\n elif a == 0:\n radians = math.asin(o / h)\n else:\n radians = math.acos(a / h)\n return round(math.degrees(radians))", "from math import asin, acos, atan, degrees as d\nmissing_angle = lambda h, a, o: round(d(atan(o / a) if not h else asin(o / h) if not a else acos(a / h)))", "import math\n\ndef missing_angle(h, a, o):\n return round(math.degrees(math.atan(o / a) if not h else math.asin(o / h) if not a else math.acos(a / h)))", "from math import sqrt, asin, degrees\n\ndef missing_angle(h, a, o):\n (h, o) = (h or sqrt(a ** 2 + o ** 2), o or sqrt(h ** 2 - a ** 2))\n return round(degrees(asin(o / h)))", "from math import asin, acos, atan, pi\n\ndef missing_angle(h, a, o):\n ans = acos(a / h) if h * a else atan(o / a) if a * o else asin(o / h)\n return round(ans * 180 / pi)", "import math\n\ndef missing_angle(h, a, o):\n if h > 0 and a > 0:\n result = math.acos(a / h)\n elif a == 0 and o > 0:\n result = math.asin(o / h)\n elif h == 0 and o > 0:\n result = math.atan(o / a)\n else:\n raise ValueError('Invalid argument(s)')\n return round(math.degrees(result))", "import math\n\ndef missing_angle(h, a, o):\n if not h:\n h = (a ** 2 + o ** 2) ** 0.5\n if not o:\n o = (h ** 2 - a ** 2) ** 0.5\n return round(math.asin(o / h) * 180 / math.pi)"], "starter_code": "def missing_angle(h, a, o):\n", "input_output": {"fn_name": "missing_angle", "inputs": [[0, 400, 300], [5, 4, 0], [8, 0, 5], [16.7, 0, 12.3], [7, 5, 0]], "outputs": [[37], [37], [39], [47], [44]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Geometry"], "name": null, "source": "codewars", "tags": ["Geometry", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/58417e9ab9c25c774500001f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "missing_angle", "task_id": "TACO_lite/89", "example": [[[3, 5, 0], [0, 5, 4], [3, 0, 4]], [null, 39, null]]} +{"requirement": "Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.\n\nExample:\n\n\nInput: \n\n1 0 1 0 0\n1 0 1 1 1\n1 1 1 1 1\n1 0 0 1 0\n\nOutput: 4", "solutions": ["def maximalsquare(matrix):\n if not matrix:\n return 0\n (m, n) = (len(matrix), len(matrix[0]))\n dp = [int(matrix[i][0]) for i in range(m)]\n vmax = max(dp)\n pre = 0\n for j in range(1, n):\n (pre, dp[0]) = (int(matrix[0][j - 1]), int(matrix[0][j]))\n for i in range(1, m):\n cur = dp[i]\n dp[i] = 0 if matrix[i][j] == '0' else min(dp[i - 1], dp[i], pre) + 1\n pre = cur\n vmax = max(vmax, max(dp))\n return vmax ** 2", "def maximalsquare(matrix):\n if len(matrix) == 0 or len(matrix[0]) == 0:\n return 0\n (n, m) = (len(matrix), len(matrix[0]))\n dp = [[0 for i in range(m)] for j in range(n)]\n for i in range(n):\n dp[i][0] = int(matrix[i][0])\n for j in range(m):\n dp[0][j] = int(matrix[0][j])\n for i in range(1, n):\n for j in range(1, m):\n if matrix[i][j] == '1':\n dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1\n ans = 0\n for i in range(n):\n ans = max(ans, max(dp[i]))\n return ans ** 2", "def maximalsquare(matrix):\n if not matrix:\n return 0\n (rows, cols) = (len(matrix), len(matrix[0]))\n dp = list(map(int, matrix[0][:]))\n maxLen = 1 if sum(dp) > 0 else 0\n for i in range(1, rows):\n tmp = dp[0]\n dp[0] = int(matrix[i][0])\n maxLen = max(maxLen, dp[0])\n pre = tmp\n for j in range(1, cols):\n tmp = dp[j]\n if matrix[i][j] == '1':\n dp[j] = min(dp[j], dp[j - 1], pre) + 1\n maxLen = max(maxLen, dp[j])\n else:\n dp[j] = 0\n pre = tmp\n return maxLen * maxLen", "def maximalsquare(matrix):\n if not matrix:\n return 0\n (rows, cols) = (len(matrix), len(matrix[0]))\n dp = [0] * cols\n maxLen = 1 if sum(dp) > 0 else 0\n for i in range(0, rows):\n for j in range(0, cols):\n if matrix[i][j] == '1':\n if j == 0:\n dp[j] = int(matrix[i][j])\n else:\n k = min(dp[j], dp[j - 1])\n dp[j] = k + 1 if matrix[i - k][j - k] == '1' else k\n maxLen = max(maxLen, dp[j])\n else:\n dp[j] = 0\n return maxLen * maxLen", "def maximalsquare(matrix):\n if not matrix or len(matrix) == 0:\n return 0\n m = len(matrix)\n n = len(matrix[0])\n dp = [[0 for i in range(n)] for j in range(m)]\n dp[0] = list(map(lambda x: int(x), matrix[0]))\n maxLength = 1 if 1 in dp[0] else 0\n for i in range(1, m):\n dp[i][0] = int(matrix[i][0])\n if dp[i][0] == 1:\n maxLength = 1\n for i in range(1, m):\n for j in range(1, n):\n if matrix[i][j] == '0':\n dp[i][j] = 0\n else:\n dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1])\n maxLength = max(maxLength, dp[i][j])\n return maxLength ** 2", "def maximalsquare(matrix):\n (m, n) = (len(matrix), len(matrix[0]) if matrix else 0)\n dp = [0] * n\n best = 0\n for r in range(m):\n ndp = [0] * n\n for c in range(n):\n if matrix[r][c] == '1':\n ndp[c] = min(dp[c - 1], dp[c], ndp[c - 1]) + 1 if r and c else 1\n if ndp[c] > best:\n best = ndp[c]\n dp = ndp\n return best ** 2", "def maximalsquare(matrix):\n g = 0\n li = [[0 for a in x] for x in matrix]\n for i in range(0, len(matrix)):\n for j in range(0, len(matrix[0])):\n c = int(matrix[i][j])\n if c == 0:\n li[i][j] = 0\n continue\n if i == 0 or j == 0:\n li[i][j] = c\n if c > g:\n g = c\n continue\n m = min(li[i - 1][j], li[i][j - 1])\n if li[i - 1][j - 1] <= m:\n li[i][j] = 1 + li[i - 1][j - 1]\n else:\n li[i][j] = 1 + m\n if li[i][j] > g:\n g = li[i][j]\n return g ** 2", "def maximalsquare(matrix):\n if len(matrix) == 0 or len(matrix[0]) == 0:\n return 0\n dp = [[0 for i in range(len(matrix[0]))] for i in range(len(matrix))]\n largest = 0\n for i in range(len(matrix)):\n dp[i][0] = int(matrix[i][0])\n largest = max(largest, dp[i][0])\n for j in range(len(matrix[0])):\n dp[0][j] = int(matrix[0][j])\n largest = max(largest, dp[0][j])\n for i in range(1, len(matrix)):\n for j in range(1, len(matrix[0])):\n if matrix[i][j] == '1':\n if dp[i - 1][j] >= dp[i - 1][j - 1] and dp[i][j - 1] >= dp[i - 1][j - 1]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n else:\n dp[i][j] = min(int(dp[i - 1][j]), int(dp[i][j - 1])) + 1\n else:\n dp[i][j] = 0\n largest = max(largest, dp[i][j])\n return largest * largest"], "starter_code": "def maximalsquare(matrix: List[List[str]]) -> int:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Dynamic Programming", "Matrix"], "name": null, "source": "leetcode", "tags": ["Matrices", "Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/maximal-square/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "maximalsquare", "task_id": "TACO_lite/20", "example": [[[[[1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0]]]], [9]]} +{"requirement": "Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.\nReturn the number of nice sub-arrays.\n\u00a0\nExample 1:\nInput: nums = [1,1,2,1,1], k = 3\nOutput: 2\nExplanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].\n\nExample 2:\nInput: nums = [2,4,6], k = 1\nOutput: 0\nExplanation: There is no odd numbers in the array.\n\nExample 3:\nInput: nums = [2,2,2,1,2,2,1,2,2,2], k = 2\nOutput: 16\n\n\u00a0\nConstraints:\n\n1 <= nums.length <= 50000\n1 <= nums[i] <= 10^5\n1 <= k <= nums.length", "solutions": ["def numberofsubarrays(nums: List[int], k: int) -> int:\n edge = []\n res = 0\n count = 0\n for i in nums:\n if i % 2:\n edge.append(count + 1)\n count = 0\n else:\n count += 1\n edge.append(count + 1)\n if len(edge) - 1 < k:\n return 0\n else:\n for i in range(len(edge) - k):\n res += edge[i] * edge[i + k]\n return res", "def numberofsubarrays(A: List[int], k: int) -> int:\n d = []\n n = len(A)\n res = 0\n count = 1\n for i in range(n):\n if A[i] % 2:\n d.append(count)\n count = 1\n else:\n count += 1\n d.append(count)\n for (x, y) in zip(d, d[k:]):\n res += x * y\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n l = [0] * (len(nums) + 1)\n for (i, n) in enumerate(nums):\n l[i + 1] = l[i] + n % 2\n c = Counter(l)\n return sum((c[x - k] * c[x] for x in c))", "def numberofsubarrays(nums: List[int], k: int) -> int:\n prefix = {0: 1}\n count = 0\n result_count = 0\n for num in nums:\n if num % 2:\n count += 1\n prefix[count] = prefix.get(count, 0) + 1\n result_count += prefix.get(count - k, 0)\n return result_count", "from collections import defaultdict\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n\n def helper(k):\n start = end = counter = res = 0\n while end < len(nums):\n if nums[end] % 2 != 0:\n counter += 1\n end += 1\n while counter > k:\n if nums[start] % 2 != 0:\n counter -= 1\n start += 1\n res += end - start\n return res\n return helper(k) - helper(k - 1)", "from collections import Counter\n\ndef numberofsubarrays(A, k):\n count = Counter([0])\n ans = 0\n psum = 0\n for v in A:\n psum += v % 2\n ans += count[psum - k]\n count[psum] += 1\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n for i in range(len(nums)):\n nums[i] = nums[i] % 2\n mp = defaultdict(int)\n mp[0] = 1\n (csum, ans) = (0, 0)\n for (i, num) in enumerate(nums):\n csum += num\n ans += mp[csum - k]\n mp[csum] += 1\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n i = count = nice_count = odd_count = 0\n for j in range(len(nums)):\n if nums[j] % 2 == 1:\n odd_count += 1\n count = 0\n while odd_count == k:\n odd_count -= nums[i] % 2\n i += 1\n count += 1\n nice_count += count\n return nice_count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n if not nums:\n return 0\n s = []\n evencnt = 0\n for num in nums:\n if num % 2 == 1:\n s.append(evencnt)\n evencnt = 0\n else:\n evencnt += 1\n s.append(evencnt)\n res = 0\n for i in range(len(s) - k):\n res += (s[i] + 1) * (s[i + k] + 1)\n return res", "def numberofsubarrays(nums, k):\n return self.atMost(nums, k) - self.atMost(nums, k - 1)\n\ndef atMost(nums, k):\n if k < 0:\n return 0\n n = len(nums)\n right = 0\n cnt = 0\n res = 0\n for left in range(n):\n while right <= n - 1 and (cnt < k or nums[right] % 2 == 0):\n cnt += nums[right] % 2 == 1\n right += 1\n res += right - left\n cnt -= nums[left] % 2 == 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n blocks = [1]\n for num in nums:\n if num % 2 == 1:\n blocks.append(1)\n continue\n blocks[-1] += 1\n return sum((left * right for (left, right) in zip(blocks, blocks[k:])))", "def solve(A, k):\n count = [0, 0]\n front = iter(A)\n ans = 0\n size = 0\n for v in A:\n count[v % 2] += 1\n size += 1\n while count[1] > k:\n count[next(front) % 2] -= 1\n size -= 1\n ans += size\n return ans\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n return solve(nums, k) - solve(nums, k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n data = []\n curr = 0\n L = 0\n count = 0\n for num in nums:\n if num % 2 == 0:\n curr += 1\n else:\n L += 1\n data.append(curr)\n curr = 0\n if L < k:\n return 0\n end = 0\n for i in range(len(nums) - 1, -1, -1):\n if nums[i] % 2 == 1:\n break\n end += 1\n for i in range(k - 1, L - 1):\n count += (data[i - k + 1] + 1) * (data[i + 1] + 1)\n return count + (end + 1) * (data[-k] + 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def at_most(nums, k):\n (i, j, count, res) = (0, 0, 0, 0)\n while j < len(nums):\n if nums[j] % 2 == 1:\n count += 1\n while count > k:\n if nums[i] % 2 == 1:\n count -= 1\n i += 1\n res += j - i + 1\n j += 1\n return res\n return at_most(nums, k) - at_most(nums, k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n odds = [-1]\n for i in range(len(nums)):\n if nums[i] & 1:\n odds.append(i)\n odds.append(len(nums))\n (i, count) = (1, 0)\n while i + k - 1 < len(odds) - 1:\n count += (odds[i] - odds[i - 1]) * (odds[i + k] - odds[i + k - 1])\n i += 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n occur = collections.defaultdict(int)\n occur[0] = 1\n runsum = 0\n count = 0\n for i in range(len(nums)):\n if nums[i] % 2 == 0:\n nums[i] = 0\n else:\n nums[i] = 1\n runsum += nums[i]\n if runsum - k in occur:\n count += occur[runsum - k]\n occur[runsum] += 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n s = 0\n e = 0\n l = len(nums)\n total = 0\n num_odd = 0\n ae = 0\n while s < l:\n while e < l and num_odd != k:\n if nums[e] % 2 != 0:\n num_odd += 1\n e += 1\n if num_odd == k:\n if ae < e:\n ae = e\n while ae < l and nums[ae] % 2 == 0:\n ae += 1\n total += ae - (e - 1)\n if nums[s] % 2 != 0:\n num_odd -= 1\n s += 1\n return total", "def numberofsubarrays(nums: List[int], k: int) -> int:\n num_odds = defaultdict(int, {0: 1})\n total = 0\n running = 0\n for n in nums:\n running += n % 2\n total += num_odds[running - k]\n num_odds[running] += 1\n return total", "from collections import defaultdict\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n seen = defaultdict(int)\n seen[0] = 1\n output = 0\n odds = 0\n for i in range(0, len(nums)):\n if nums[i] % 2 != 0:\n odds += 1\n if odds - k in seen:\n output += seen[odds - k]\n seen[odds] += 1\n return output", "def numberofsubarrays(nums: List[int], k: int) -> int:\n num_nice = 0\n i = 0\n count = 0\n for num in nums:\n if num & 1:\n k -= 1\n count = 0\n while k == 0:\n k += nums[i] & 1\n count += 1\n i += 1\n num_nice += count\n return num_nice", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atMost(k):\n (l, result) = (0, 0)\n for i in range(len(nums)):\n k -= nums[i] % 2\n while k < 0:\n k += nums[l] % 2\n l += 1\n result += i - l + 1\n return result\n return atMost(k) - atMost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n output = 0\n count_odd = 0\n l = 0\n for (r, n) in enumerate(nums):\n count_odd += int(n % 2 == 1)\n if count_odd == k:\n n_even = 1\n for j in range(r + 1, len(nums)):\n if nums[j] % 2 == 0:\n n_even += 1\n else:\n break\n while count_odd == k:\n output += n_even\n count_odd -= int(nums[l] % 2 == 1)\n l += 1\n return output", "def numberofsubarrays(nums: List[int], k: int) -> int:\n cnt = 0\n d = {}\n d[0] = 1\n for i in nums:\n if i % 2:\n cnt += 1\n if cnt in d:\n d[cnt] += 1\n else:\n d[cnt] = 1\n ans = 0\n for key in d:\n if k + key in d:\n ans += d[key] * d[k + key]\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n cur = res = i = 0\n for j in range(len(nums)):\n if nums[j] % 2 != 0:\n k -= 1\n if k == 0:\n cur = 1\n while nums[i] % 2 == 0:\n cur += 1\n i += 1\n k += 1\n i += 1\n res += cur\n else:\n res += cur\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n return self.sol1(nums, k) - self.sol1(nums, k - 1)\n\ndef sol1(nums, k):\n start = 0\n odds = 0\n res = 0\n for end in range(len(nums)):\n odds += nums[end] & 1\n while odds > k:\n odds -= nums[start] & 1\n start += 1\n res += end - start + 1\n return res\n\ndef sol2(nums, k):\n start = 0\n odds = 0\n res = 0\n count = 0\n for end in range(len(nums)):\n if nums[end] & 1:\n odds += 1\n count = 0\n while odds >= k:\n if nums[start] & 1:\n odds -= 1\n start += 1\n count += 1\n res += count\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atMost(k):\n count = i = res = 0\n for (j, v) in enumerate(nums):\n if v % 2:\n count += 1\n while count > k:\n if nums[i] % 2:\n count -= 1\n i += 1\n res += j - i + 1\n return res\n return atMost(k) - atMost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atmost(k):\n res = i = 0\n for j in range(len(nums)):\n k -= nums[j] % 2\n while k < 0:\n k += nums[i] % 2\n i += 1\n res += j - i + 1\n return res\n return atmost(k) - atmost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n num_odd_numbers = 0\n foo = 0\n left = 0\n right = 0\n count = 0\n num_nice_arrays = 0\n while right < len(nums):\n r_n = nums[right]\n if r_n % 2 == 1:\n count = 0\n num_odd_numbers += 1\n while num_odd_numbers == k:\n l_n = nums[left]\n if l_n % 2 == 1:\n num_odd_numbers -= 1\n left += 1\n count += 1\n num_nice_arrays += count\n right += 1\n return num_nice_arrays", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def AtMostK(k):\n left = 0\n count = 0\n currK = 0\n for index in range(len(nums)):\n if nums[index] % 2 == 1:\n currK += 1\n while currK > k:\n if nums[left] % 2 == 1:\n currK -= 1\n left += 1\n count += index - left + 1\n return count\n return AtMostK(k) - AtMostK(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n n = len(nums)\n noOfNiceSubArrays = 0\n even = 0\n oddList = []\n for i in range(n):\n if nums[i] % 2 == 0:\n even += 1\n else:\n oddList.append(even)\n even = 0\n oddList.append(even)\n for i in range(len(oddList) - k):\n noOfNiceSubArrays += (oddList[i] + 1) * (oddList[i + k] + 1)\n return noOfNiceSubArrays", "def numberofsubarrays(nums: List[int], k: int) -> int:\n odds = [0] * len(nums)\n n = len(nums)\n d = {}\n if nums[0] % 2 == 1:\n odds[0] = 1\n else:\n odds[0] = 0\n odds = [0] + odds\n d[0] = d.setdefault(0, []) + [0]\n count = 0\n for i in range(1, n + 1):\n if nums[i - 1] % 2 == 1:\n odds[i] = odds[i - 1] + 1\n else:\n odds[i] = odds[i - 1]\n if odds[i] - k in d:\n count += len(d[odds[i] - k])\n d[odds[i]] = d.setdefault(odds[i], []) + [i]\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def helper(k):\n ans = i = 0\n for j in range(len(nums)):\n k -= nums[j] % 2\n while k < 0:\n k += nums[i] % 2\n i += 1\n ans += j - i + 1\n return ans\n return helper(k) - helper(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n return self.numberOfAtmostK(nums, k) - self.numberOfAtmostK(nums, k - 1)\n\ndef numberOfAtmostK(nums, k):\n (l, r, count, res) = (0, 0, 0, 0)\n while r < len(nums):\n if nums[r] % 2 == 1:\n count += 1\n while count > k:\n if nums[l] % 2 == 1:\n count -= 1\n l += 1\n res += r - l + 1\n r += 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def at_most(nums, k):\n cnts = l = res = 0\n for r in range(len(nums)):\n cnts += nums[r] % 2\n while cnts > k:\n cnts -= nums[l] % 2\n l += 1\n res += r - l + 1\n return res\n return at_most(nums, k) - at_most(nums, k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n i = count = res = 0\n for j in range(len(nums)):\n if nums[j] & 1:\n k -= 1\n count = 0\n while k == 0:\n k += nums[i] & 1\n i += 1\n count += 1\n res += count\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n prefix_odd = defaultdict(int)\n prefix_odd[0] = 1\n ans = count = 0\n for num in nums:\n if num % 2:\n count += 1\n prefix_odd[count] += 1\n for p in prefix_odd:\n if p - k in prefix_odd:\n ans += prefix_odd[p] * prefix_odd[p - k]\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n last = 0\n hsh = {}\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n nums[i] = 1\n else:\n nums[i] = 0\n nums[i] += last\n last = nums[i]\n if nums[i] not in hsh:\n hsh[nums[i]] = []\n hsh[nums[i]].append(i)\n count = 0\n if k in hsh:\n count = len(hsh[k])\n for i in range(len(nums)):\n x = nums[i]\n if x + k in hsh:\n for v in hsh[x + k][::-1]:\n if v < i:\n break\n count += 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n (prefix, odd_cnt, ans) = ({0: 1}, 0, 0)\n for num in nums:\n if num % 2 == 1:\n odd_cnt += 1\n prefix[odd_cnt] = prefix.get(odd_cnt, 0) + 1\n if odd_cnt - k in prefix:\n ans += prefix[odd_cnt - k]\n return ans", "from collections import defaultdict\n\ndef numberofsubarrays(A, k):\n i = count = res = 0\n for j in range(len(A)):\n if A[j] & 1:\n k -= 1\n count = 0\n while k == 0:\n k += A[i] & 1\n i += 1\n count += 1\n res += count\n return res", "def numberofsubarrays(A: List[int], B: int) -> int:\n import collections\n (q, k, temp, count) = (collections.deque(), 0, 0, 0)\n if B == 0:\n for i in range(len(A)):\n if A[i] % 2 == 0:\n temp = temp + 1\n elif A[i] % 2 != 0:\n count = count + int(temp * (temp + 1) / 2)\n temp = 0\n count = count + int(temp * (temp + 1) / 2)\n return count\n while len(q) < B and k < len(A):\n if A[k] % 2 == 0:\n temp = temp + 1\n elif A[k] % 2 == 1:\n q.append(temp)\n temp = 0\n k = k + 1\n if len(q) < B:\n return 0\n temp = 0\n for i in range(k, len(A)):\n if A[i] % 2 == 0:\n temp = temp + 1\n elif A[i] % 2 != 0:\n count = count + (q[0] + 1) * (temp + 1)\n q.append(temp)\n q.popleft()\n temp = 0\n count = count + (q[0] + 1) * (temp + 1)\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n prefix = collections.defaultdict(int)\n prefix[0] = 1\n pre = ans = 0\n for n in nums:\n pre += n & 1\n prefix[pre] += 1\n ans += prefix[pre - k]\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n idxes = []\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n idxes.append(i)\n if len(idxes) < k:\n return 0\n res = 0\n for i in range(k - 1, len(idxes)):\n l = -1 if i - k + 1 == 0 else idxes[i - k]\n r = len(nums) if i == len(idxes) - 1 else idxes[i + 1]\n res += (idxes[i - k + 1] - l) * (r - idxes[i])\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n dic = {0: 1}\n count = 0\n nice = 0\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n count += 1\n if count - k in dic:\n nice += dic[count - k]\n dic[count] = dic.get(count, 0) + 1\n return nice", "def numberofsubarrays(nums: List[int], k: int) -> int:\n res = 0\n i = j = 0\n while i <= j:\n while k > 0 and j < len(nums):\n if nums[j] % 2 == 1:\n k -= 1\n j += 1\n if k != 0:\n return res\n res += 1\n t = j\n while t < len(nums):\n if nums[t] % 2 == 0:\n res += 1\n t += 1\n else:\n break\n if nums[i] % 2 == 1:\n k += 1\n i += 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n deque = collections.deque()\n deque.append(1)\n ans = 0\n for num in nums:\n if num % 2 == 0:\n deque[-1] += 1\n continue\n if len(deque) == k + 1:\n ans += deque[0] * deque[-1]\n deque.popleft()\n deque.append(1)\n if len(deque) == k + 1:\n ans += deque[0] * deque[-1]\n return ans", "from collections import Counter\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n count = Counter([0])\n ans = 0\n psum = 0\n for v in map(lambda x: x % 2, nums):\n psum += v\n ans += count[psum - k]\n count[psum] += 1\n return ans", "def solve(A, k):\n count = [0, 0]\n lower = (x % 2 for x in A)\n ans = 0\n for x in (x % 2 for x in A):\n count[x] += 1\n while count[1] > k:\n count[next(lower)] -= 1\n ans += sum(count)\n return ans\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n return solve(nums, k) - solve(nums, k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n left = collections.defaultdict(int)\n odd = 0\n res = 0\n for n in nums:\n left[odd] += 1\n odd += n & 1\n if odd - k in left:\n res += left[odd - k]\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n nums = [n % 2 for n in nums]\n\n def atMost(k):\n (ans, j) = (0, 0)\n for (i, n) in enumerate(nums):\n k -= n\n while k < 0:\n k += nums[j]\n j += 1\n ans += i - j + 1\n return ans\n return atMost(k) - atMost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n odd_count = tmp_count = j = 0\n final_count = 0\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n odd_count += 1\n tmp_count = 0\n while odd_count == k:\n odd_count -= nums[j] % 2\n j += 1\n tmp_count += 1\n final_count += tmp_count\n return final_count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n cache = {0: [-1]}\n cnt = 0\n odds = 0\n for (i, num) in enumerate(nums):\n if num % 2:\n odds += 1\n if odds - k in cache:\n cnt += len(cache[odds - k])\n x = cache.setdefault(odds, [])\n x.append(odds)\n return cnt", "def numberofsubarrays(nums: List[int], k: int) -> int:\n d = collections.defaultdict(int)\n d[0] = 1\n cur_sum = 0\n ans = 0\n for (i, v) in enumerate(nums):\n cur_sum += v % 2\n if cur_sum - k in d:\n ans += d[cur_sum - k]\n d[cur_sum] += 1\n return ans", "from collections import deque\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n nums.append(1)\n odds = deque()\n odds.append(-1)\n total = 0\n for (i, val) in enumerate(nums):\n if val % 2:\n odds.append(i)\n if len(odds) > k + 2:\n odds.popleft()\n if len(odds) == k + 2:\n total += (odds[1] - odds[0]) * (odds[-1] - odds[-2])\n return total", "def numberofsubarrays(nums: List[int], k: int) -> int:\n odd_pos = [pos for (pos, e) in enumerate(nums) if e % 2 == 1]\n if len(odd_pos) < k:\n return 0\n spaces = []\n prev_pos = -1\n for pos in odd_pos:\n spaces.append(pos - prev_pos)\n prev_pos = pos\n spaces.append(len(nums) - prev_pos)\n res = 0\n for i in range(len(spaces) - k):\n res += spaces[i] * spaces[i + k]\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n temp_arr = []\n temp_count = 0\n for n in nums:\n if n % 2 != 0:\n temp_arr.append(temp_count)\n temp_count = 0\n else:\n temp_count = temp_count + 1\n temp_arr.append(temp_count)\n if len(temp_arr) - 1 < k:\n return 0\n i = k - 1\n count = 0\n while i < len(temp_arr) - 1:\n start_len = temp_arr[i - k + 1] + 1\n end_len = temp_arr[i + 1] + 1\n count = count + start_len * end_len\n i = i + 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n (front, end) = (0, 0)\n tot = 0\n output = 0\n ct = 0\n while end < len(nums):\n if 1 & nums[end]:\n tot += 1\n ct = 0\n end += 1\n while tot == k:\n tot -= nums[front] & 1\n front += 1\n ct += 1\n output += ct\n return output", "def numberofsubarrays(nums: List[int], k: int) -> int:\n cnt = 0\n accNum = {}\n ans = 0\n accNum[0] = 1\n for x in nums:\n if x % 2:\n cnt += 1\n if cnt not in accNum:\n accNum[cnt] = 1\n else:\n accNum[cnt] += 1\n if cnt - k in accNum:\n ans += accNum[cnt - k]\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n aDict = collections.defaultdict(int)\n aDict[0] = 1\n aSum = 0\n result = 0\n for i in nums:\n if i % 2 == 1:\n aSum += 1\n if aSum - k in aDict:\n result += aDict[aSum - k]\n aDict[aSum] += 1\n return result", "def numberofsubarrays(A: List[int], k: int) -> int:\n d = []\n res = 0\n count = 1\n for a in A:\n if a % 2:\n d.append(count)\n count = 1\n else:\n count += 1\n d.append(count)\n for (x, y) in zip(d, d[k:]):\n res += x * y\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n n = len(nums)\n if k > n:\n return 0\n ans = 0\n p1 = p2 = p3 = p4 = -1\n while p4 < n:\n p2 += 1\n while p2 < n and nums[p2] % 2 == 0:\n p2 += 1\n if p2 == n:\n return ans\n if p4 == -1:\n p3 = p2\n remaining = k - 1\n while p3 < n and remaining:\n p3 += 1\n if p3 == n:\n return ans\n if nums[p3] % 2 == 1:\n remaining -= 1\n else:\n p3 = p4\n p4 = p3 + 1\n while p4 < n:\n if nums[p4] % 2 == 1:\n break\n p4 += 1\n ans += (p2 - p1) * (p4 - p3)\n p1 = p2\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n memo = {0: 1}\n count = 0\n res = 0\n for n in nums:\n if n % 2 == 1:\n count += 1\n if count - k in memo:\n res += memo[count - k]\n memo[count] = memo.get(count, 0) + 1\n return res", "def checkOdd(num):\n if num % 2 == 0:\n return False\n return True\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n oddIndices = []\n for i in range(len(nums)):\n if self.checkOdd(nums[i]):\n oddIndices.append(i)\n start = 0\n end = k - 1\n i = 0\n count = 0\n while end < len(oddIndices):\n if end == len(oddIndices) - 1:\n j = len(nums) - 1\n else:\n j = oddIndices[end + 1] - 1\n count = count + (oddIndices[start] - i + 1) * (j - oddIndices[end] + 1)\n i = oddIndices[start] + 1\n start = start + 1\n end = end + 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n prefix_sum = 0\n dict_odds = {0: 1}\n rs = 0\n for (i, num) in enumerate(nums):\n if num % 2 == 1:\n prefix_sum += 1\n if prefix_sum not in dict_odds:\n dict_odds[prefix_sum] = 1\n else:\n dict_odds[prefix_sum] = dict_odds[prefix_sum] + 1\n if prefix_sum - k in dict_odds:\n rs += dict_odds[prefix_sum - k]\n return rs", "def numberofsubarrays(nums: List[int], k: int) -> int:\n index_list = []\n index_list.append(-1)\n for i in range(0, len(nums)):\n if nums[i] % 2 == 1:\n index_list.append(i)\n index_list.append(len(nums))\n if len(index_list) == 0:\n return 0\n left = 1\n right = 1\n k_count = 1\n count = 0\n while right < len(index_list) - 1:\n if k_count == k:\n count += (index_list[left] - index_list[left - 1]) * (index_list[right + 1] - index_list[right])\n left += 1\n k_count -= 1\n else:\n k_count += 1\n right += 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n num_odd = 0\n start = 0\n output = 0\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n num_odd += 1\n while num_odd > k:\n if nums[start] % 2 == 1:\n num_odd -= 1\n start += 1\n if num_odd == k:\n output += 1\n cur_start = start\n while nums[cur_start] % 2 == 0:\n cur_start += 1\n output += 1\n return output", "def numberofsubarrays(nums: List[int], k: int) -> int:\n adict = {0: 1}\n x = 0\n result = 0\n for i in nums:\n if i & 1 != 0:\n x += 1\n if x - k in adict:\n result += adict[x - k]\n adict[x] = adict.get(x, 0) + 1\n return result", "def numberofsubarrays(nums: List[int], k: int) -> int:\n rr = l = r = res = cnt = 0\n ll = -1\n n = len(nums)\n while r < n:\n x = nums[r]\n if x % 2:\n if ll < l:\n ll = r\n cnt += 1\n if cnt == k:\n rr = r\n while r < n - 1 and nums[r + 1] % 2 == 0:\n r += 1\n res += (ll - l + 1) * (r - rr + 1)\n l = ll + 1\n cnt -= 1\n ll += 1\n while ll < n and nums[ll] % 2 == 0:\n ll += 1\n r += 1\n return res", "from collections import defaultdict\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n if len(nums) < k:\n return 0\n num_odd = 0\n seen = defaultdict(int)\n seen[0] = 1\n ret = 0\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n num_odd += 1\n key = num_odd - k\n ret += seen[key]\n seen[num_odd] += 1\n return ret", "def numberofsubarrays(A: List[int], k: int) -> int:\n d = []\n res = 0\n count = 1\n for a in A:\n if a % 2:\n d.append(count)\n count = 1\n else:\n count += 1\n d.append(count)\n m = len(d)\n for i in range(m - k):\n res += d[i] * d[i + k]\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n count = 0\n dic = defaultdict(int)\n dic[0] = 1\n ans = 0\n for i in range(1, len(nums) + 1):\n count += nums[i - 1] % 2\n if count - k in list(dic.keys()):\n ans += dic[count - k]\n dic[count] += 1\n return ans", "def isOdd(num):\n return num % 2 == 1\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n items = [-1]\n for (i, num) in enumerate(nums):\n if isOdd(num):\n items.append(i)\n cnt = 0\n items.append(len(nums))\n for i in range(1, len(items) - 1):\n if i + k - 1 < len(items) - 1:\n left = items[i] - items[i - 1]\n right = items[i + k] - items[i + k - 1]\n cnt += left * right\n return cnt", "def numberofsubarrays(nums: List[int], k: int) -> int:\n flattened = [1 if num % 2 == 1 else 0 for num in nums]\n d = {0: 1}\n sum = 0\n total = 0\n for i in range(len(flattened)):\n sum += flattened[i]\n total += d.get(sum - k, 0)\n d[sum] = d.get(sum, 0) + 1\n return total", "from collections import Counter\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n oddCounts = []\n oddCount = 0\n for num in nums:\n if num % 2 == 1:\n oddCount += 1\n oddCounts.append(oddCount)\n oddCountsIdxs = Counter(oddCounts)\n nice = 0\n for num in oddCounts:\n nice += oddCountsIdxs[num - k]\n nice += oddCountsIdxs[k]\n return nice", "def numberofsubarrays(nums: List[int], k: int) -> int:\n nums = [i % 2 for i in nums]\n ans = 0\n tmp = 0\n n = len(nums)\n l = 0\n for r in range(n):\n if nums[r] == 1:\n k -= 1\n tmp = 0\n while k == 0:\n k += nums[l]\n l += 1\n tmp += 1\n ans += tmp\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n ln = len(nums)\n ret = 0\n for i in range(ln):\n if nums[i] % 2:\n nums[i] = 1\n else:\n nums[i] = 0\n mp = {0: 1}\n cnt = 0\n for n in nums:\n cnt += n\n if cnt not in mp:\n mp[cnt] = 0\n mp[cnt] += 1\n if cnt - k in mp:\n ret += mp[cnt - k]\n return ret\n pass", "def numberofsubarrays(nums: List[int], k: int) -> int:\n ans = 0\n d = {0: 0}\n start = {}\n cumsum = 0\n for (i, num) in enumerate(nums):\n cumsum += num % 2\n d[cumsum] = i + 1\n if cumsum not in start:\n start[cumsum] = i\n if cumsum == k:\n elems = d[0]\n ans += elems + 1\n elif cumsum > k:\n elems = d[cumsum - k] - start.get(cumsum - k, -1)\n ans += elems\n return ans", "from collections import deque\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n (d, res) = (deque(), 0)\n d.append(-1)\n for i in range(0, len(nums)):\n if nums[i] % 2 == 1:\n d.append(i)\n if len(d) > k + 1:\n d.popleft()\n if len(d) == k + 1:\n a = d.popleft()\n b = d.popleft()\n res += b - a\n d.appendleft(b)\n d.appendleft(a)\n return res", "from collections import Counter\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n lookup = Counter()\n lookup[0] = 1\n answer = accumulated_odd = 0\n for num in nums:\n if num % 2 == 1:\n accumulated_odd += 1\n answer += lookup[accumulated_odd - k]\n lookup[accumulated_odd] += 1\n return answer", "def numberofsubarrays(nums: List[int], k: int) -> int:\n oddnum = 0\n (l, n) = (0, len(nums))\n add = 1\n sums = 0\n for r in range(n):\n if nums[r] % 2 == 1:\n k -= 1\n while l < r and (k < 0 or nums[l] % 2 == 0):\n if k < 0:\n add = 1\n else:\n add += 1\n if nums[l] % 2 == 1:\n k += 1\n l += 1\n if k == 0:\n sums += add\n return sums", "from collections import Counter\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n lookup = Counter()\n lookup[0] = 1\n answer = accumulated_sum = 0\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n accumulated_sum += 1\n answer += lookup[accumulated_sum - k]\n lookup[accumulated_sum] += 1\n return answer", "def numberofsubarrays(nums: List[int], k: int) -> int:\n if not nums:\n return 0\n return self.atMostK(nums, k) - self.atMostK(nums, k - 1)\n\ndef atMostK(nums, k):\n count = 0\n left = 0\n for (right, right_num) in enumerate(nums):\n k -= right_num % 2\n while k < 0:\n k += nums[left] % 2\n left += 1\n count += right - left + 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n memo = collections.Counter()\n memo[0] = 1\n res = odds = 0\n for x in nums:\n if x % 2:\n odds += 1\n memo[odds] += 1\n res += memo[odds - k]\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atMost(A: List[int], k: int) -> int:\n i = ret = 0\n for j in range(len(A)):\n if A[j] & 1:\n k -= 1\n while k < 0:\n k += A[i] & 1\n i += 1\n ret += j - i + 1\n return ret\n return atMost(nums, k) - atMost(nums, k - 1)", "def numberofsubarrays(A: List[int], k: int) -> int:\n\n def atMost(k):\n (res, lo) = (0, 0)\n for hi in range(len(A)):\n k -= A[hi] % 2\n while k < 0:\n k += A[lo] % 2\n lo += 1\n res += hi - lo + 1\n return res\n return atMost(k) - atMost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n return self.newConcept(nums, k) - self.newConcept(nums, k - 1)\n\ndef newConcept(nums, k):\n ans = 0\n left = 0\n c = 0\n for i in range(len(nums)):\n if nums[i] % 2 != 0:\n c += 1\n while c > k:\n if nums[left] % 2 != 0:\n c -= 1\n left += 1\n ans += i - left + 1\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atMost(m):\n if m < 0:\n return 0\n left = res = 0\n for (right, x) in enumerate(nums):\n m -= x & 1\n while m < 0:\n m += nums[left] & 1\n left += 1\n res += right - left + 1\n return res\n return atMost(k) - atMost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n arr = list(map(lambda x: x % 2, nums))\n n = len(arr)\n arr = [0] + list(itertools.accumulate(arr))\n hm = Counter()\n res = 0\n for i in arr:\n res += hm[i]\n hm[i + k] += 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def at_most(k):\n left = 0\n count = 0\n res = 0\n for right in range(len(nums)):\n if nums[right] & 1:\n count += 1\n while count > k and left <= right:\n if nums[left] & 1:\n count -= 1\n left += 1\n res += right - left + 1\n return res\n return at_most(k) - at_most(k - 1)", "def numberofsubarrays(A, k):\n\n def atMost(k):\n res = i = 0\n for j in range(len(A)):\n k -= A[j] % 2\n while k < 0:\n k += A[i] % 2\n i += 1\n res += j - i + 1\n return res\n return atMost(k) - atMost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n positions = [-1]\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n positions.append(i)\n positions.append(len(nums))\n total = 0\n for i in range(1, len(positions) - k):\n num_before = positions[i] - positions[i - 1]\n num_after = positions[i + k] - positions[i + k - 1]\n total += num_before * num_after\n return total", "def addOrIncrement(key, dictionary):\n if key in dictionary:\n dictionary[key] += 1\n else:\n dictionary[key] = 1\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n n = len(nums)\n if n < k:\n return 0\n ans = 0\n seen = {0: 1}\n curVal = 0\n for num in nums:\n curVal += 0 if num % 2 == 0 else 1\n if curVal - k in seen:\n ans += seen[curVal - k]\n self.addOrIncrement(curVal, seen)\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n n = len(nums)\n left_left = 0\n left_right = 0\n odds_left = 0\n odds_right = 0\n odds = 0\n ret = 0\n for right in range(n):\n odds_left += nums[right] % 2\n odds_right += nums[right] % 2\n while left_left <= right and odds_left > k:\n odds_left -= nums[left_left] % 2\n left_left += 1\n while left_right <= right and odds_right - nums[left_right] % 2 >= k:\n odds_right -= nums[left_right] % 2\n left_right += 1\n if odds_left == odds_right == k:\n ret += left_right - left_left + 1\n return ret", "def numberofsubarrays(nums: List[int], k: int) -> int:\n return self.at_most(nums, k) - self.at_most(nums, k - 1)\n\ndef at_most(nums, k):\n i = 0\n res = 0\n for (j, val) in enumerate(nums):\n if val & 1 == 1:\n k -= 1\n while k < 0:\n if nums[i] & 1 == 1:\n k += 1\n i += 1\n res += j - i + 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n cache = collections.Counter({0: 1})\n (res, cnt_odd) = (0, 0)\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n cnt_odd += 1\n res += cache.get(cnt_odd - k, 0)\n cache[cnt_odd] += 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n count = 0\n left = 0\n right = 0\n odd = 0\n while right < len(nums):\n if nums[right] % 2 == 1:\n odd += 1\n while left < right and odd > k:\n if nums[left] % 2 == 1:\n odd -= 1\n left += 1\n if odd == k:\n count += 1\n i = left\n while i < right and odd == k and (nums[i] % 2 == 0):\n count += 1\n i += 1\n right += 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n if not nums:\n return 0\n ans = 0\n cnt = 0\n lo = 0\n hi = 0\n cnt += nums[0] % 2\n while lo <= hi and hi < len(nums):\n if cnt < k:\n hi += 1\n if hi < len(nums) and nums[hi] % 2:\n cnt += 1\n elif cnt > k:\n if lo < hi and nums[lo] % 2:\n cnt -= 1\n lo += 1\n else:\n ans += 1\n tempHi = hi\n while tempHi + 1 < len(nums) and nums[tempHi + 1] % 2 == 0:\n ans += 1\n tempHi += 1\n if lo < len(nums) and nums[lo] % 2:\n cnt -= 1\n lo += 1\n if hi < lo:\n hi = lo\n if hi < len(nums) and nums[hi] % 2:\n cnt += 1\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atMost(K):\n (b, e) = (0, 0)\n ret = 0\n while e < len(nums):\n K -= nums[e] % 2\n while K < 0:\n K += nums[b] % 2\n b += 1\n ret += e - b + 1\n e += 1\n return ret\n return atMost(k) - atMost(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def at_most(k):\n start_ptr = 0\n result = 0\n for end_ptr in range(len(nums)):\n k -= nums[end_ptr] % 2\n while k < 0:\n k += nums[start_ptr] % 2\n start_ptr += 1\n result += end_ptr - start_ptr + 1\n return result\n return at_most(k) - at_most(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n (l, r, oddsCounter, res) = (0, 0, 0, 0)\n while r < len(nums):\n if nums[r] % 2 == 1:\n oddsCounter += 1\n while oddsCounter > k:\n if nums[l] % 2 == 1:\n oddsCounter -= 1\n l += 1\n if oddsCounter == k:\n res += 1\n i = l\n while oddsCounter == k and i < r and (nums[i] % 2 == 0):\n res += 1\n i += 1\n r += 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n j = i = count = ret = 0\n for n in nums:\n if n % 2:\n count += 1\n if count == k:\n i = j\n while count == k:\n count -= 1 if nums[j] % 2 else 0\n j += 1\n ret += j - i\n return ret", "def numberofsubarrays(nums: List[int], k: int) -> int:\n left_pointer = 0\n right_pointer = -1\n count = 0\n odd = 0\n while right_pointer < len(nums) - 1:\n right_pointer += 1\n if nums[right_pointer] % 2 == 1:\n odd += 1\n if odd == k:\n left_side = 1\n right_side = 1\n while right_pointer < len(nums) - 1 and nums[right_pointer + 1] % 2 == 0:\n right_side += 1\n right_pointer += 1\n while left_pointer <= right_pointer and nums[left_pointer] % 2 == 0:\n left_side += 1\n left_pointer += 1\n count += left_side * right_side\n left_pointer += 1\n odd -= 1\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n return self.atMost(nums, k) - self.atMost(nums, k - 1)\n\ndef atMost(nums, k):\n res = left = 0\n odds = 0\n for right in range(len(nums)):\n if nums[right] % 2 == 1:\n k -= 1\n while k < 0:\n if nums[left] % 2 == 1:\n k += 1\n left += 1\n res += right - left + 1\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def at_most(k):\n num_odd = res = i = 0\n for (j, v) in enumerate(nums):\n if v % 2 != 0:\n num_odd += 1\n while num_odd > k:\n if nums[i] % 2 == 1:\n num_odd -= 1\n i += 1\n res += j - i + 1\n return res\n return at_most(k) - at_most(k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n for i in range(len(nums)):\n if nums[i] % 2 == 0:\n nums[i] = 0\n else:\n nums[i] = 1\n pre = [0]\n for c in nums:\n pre.append(pre[-1] + c)\n res = 0\n dic = {}\n for c in pre:\n if c - k in dic:\n res += dic[c - k]\n if c not in dic:\n dic[c] = 1\n else:\n dic[c] += 1\n return res", "def atMostK(nums, k):\n start = 0\n end = 0\n count = 0\n for end in range(len(nums)):\n if nums[end] % 2 == 1:\n k -= 1\n while k < 0:\n if nums[start] % 2 == 1:\n k += 1\n start += 1\n count += end - start + 1\n return count\n\ndef numberofsubarrays(nums: List[int], k: int) -> int:\n if not nums or len(nums) == 0 or k > len(nums):\n return 0\n odds = 0\n return self.atMostK(nums, k) - self.atMostK(nums, k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n d = {0: 1}\n s = 0\n count = 0\n for i in range(len(nums)):\n nums[i] %= 2\n s += nums[i]\n if not s in d:\n d[s] = 0\n d[s] += 1\n if s - k in d:\n count += d[s - k]\n return count", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atMostK(nums, K):\n res = 0\n b = 0\n oddCount = 0\n for e in range(len(nums)):\n oddCount += int(nums[e] % 2 == 1)\n while oddCount > K:\n oddCount -= int(nums[b] % 2 == 1)\n b += 1\n res += e - b + 1\n return res\n return atMostK(nums, k) - atMostK(nums, k - 1)", "def numberofsubarrays(nums: List[int], k: int) -> int:\n n = len(nums)\n\n def at_most_k(k: int) -> int:\n (i, j, odds) = (0, 0, 0)\n res = 0\n while j < n:\n if nums[j] % 2:\n odds += 1\n while i <= j and odds > k:\n if nums[i] % 2:\n odds -= 1\n i += 1\n j += 1\n res += j - i\n return res\n return at_most_k(k) - at_most_k(k - 1)", "def __init__():\n self.odd = 0\n\ndef add(value: int):\n if value % 2 == 1:\n self.odd += 1\n\ndef remove(value: int):\n if value % 2 == 1:\n self.odd -= 1\n\ndef numberofsubarrays(A: List[int], k: int) -> int:\n window1 = Window()\n window2 = Window()\n left1 = left2 = answer = 0\n for right in A:\n window1.add(right)\n window2.add(right)\n while window1.odd > k:\n window1.remove(A[left1])\n left1 += 1\n while window2.odd >= k:\n window2.remove(A[left2])\n left2 += 1\n answer += left2 - left1\n return answer", "def numberofsubarrays(nums: List[int], k: int) -> int:\n result = 0\n (start, count) = (0, 0)\n for i in range(len(nums)):\n if nums[i] % 2 != 0:\n count += 1\n while start < i and count > k:\n if nums[start] % 2 != 0:\n count -= 1\n start += 1\n if count == k:\n result += 1\n for j in range(start, i):\n if count == k and nums[j] % 2 == 0:\n result += 1\n else:\n break\n return result", "def numberofsubarrays(nums: List[int], k: int) -> int:\n P = [0]\n for n in nums:\n P.append(P[-1] + n % 2)\n from collections import Counter\n count = Counter()\n ans = 0\n for p in P:\n ans += count[p]\n count[p + k] += 1\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n ans = count = l = 0\n for num in nums:\n if num & 1:\n k -= 1\n count = 0\n while k == 0:\n k += nums[l] & 1\n count += 1\n l += 1\n ans += count\n return ans", "def numberofsubarrays(nums: List[int], k: int) -> int:\n cnt = collections.Counter()\n (cnt[0], odd, res) = (1, 0, 0)\n for i in nums:\n if i % 2 == 1:\n odd += 1\n cnt[odd] += 1\n res += cnt[odd - k]\n return res", "def numberofsubarrays(nums: List[int], k: int) -> int:\n\n def atmostK(K):\n res = 0\n k = 0\n count = collections.Counter()\n for i in range(len(nums)):\n if nums[i] % 2 == 1:\n count[1] += 1\n while count[1] > K:\n if nums[k] % 2 == 1:\n count[1] -= 1\n k += 1\n res += i - k + 1\n return res\n return atmostK(k) - atmostK(k - 1)", "from collections import Counter\n\ndef numberofsubarrays(A, k):\n psum = [0]\n for x in map(lambda x: x % 2, A):\n psum.append(psum[-1] + x)\n count = Counter(psum)\n return sum((count[p - k] for p in psum))"], "starter_code": "def numberofsubarrays(nums: List[int], k: int) -> int:\n", "input_output": {"fn_name": "numberOfSubarrays", "inputs": [[[1, 1, 2, 1, 1], 3]], "outputs": [2]}, "difficulty": "MEDIUM", "raw_tags": ["Math", "Sliding Window", "Array", "Hash Table"], "name": null, "source": "leetcode", "tags": ["Data structures", "Amortized analysis", "Mathematics"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://leetcode.com/problems/count-number-of-nice-subarrays/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numberofsubarrays", "task_id": "TACO_lite/93", "example": [[[[1, 1, 2, 1, 1], 3], [[2, 4, 6], 1], [[2, 2, 2, 1, 2, 2, 1, 2, 2, 2], 2]], ["2", "0", "16"]]} +{"requirement": "You are given a sequence of a journey in London, UK. The sequence will contain bus **numbers** and TFL tube names as **strings** e.g.\n\n```python\n['Northern', 'Central', 243, 1, 'Victoria']\n```\nJourneys will always only contain a combination of tube names and bus numbers. Each tube journey costs `\u00a32.40` and each bus journey costs `\u00a31.50`. If there are `2` or more adjacent bus journeys, the bus fare is capped for sets of two adjacent buses and calculated as one bus fare for each set.\n\nYour task is to calculate the total cost of the journey and return the cost `rounded to 2 decimal places` in the format (where x is a number): `\u00a3x.xx`", "solutions": ["def london_city_hacker(journey):\n tube = 2.4\n bus = 1.5\n total_cost = 0.0\n count = 0\n for link in journey:\n if isinstance(link, str):\n total_cost += tube\n count = 0\n elif count == 0:\n total_cost += bus\n count += 1\n else:\n count = 0\n return '\u00a3{:.2f}'.format(total_cost)", "def london_city_hacker(journey):\n vehicle = ''.join(('t' if isinstance(j, str) else 'b' for j in journey)).replace('bb', 'b')\n return f\"\u00a3{sum((2.4 if v == 't' else 1.5 for v in vehicle)):.2f}\"", "def london_city_hacker(journey):\n prices = []\n for stop in journey:\n prices.append(2.4 if type(stop) is str else 1.5)\n if prices[-2:] == [1.5, 1.5]:\n prices[-1] = 0\n return f'\u00a3{sum(prices):.2f}'", "from itertools import groupby\n\ndef london_city_hacker(journey):\n tube_fare = lambda n: 2.4 * n\n bus_fare = lambda n: 1.5 * sum(divmod(n, 2))\n s = sum(([bus_fare, tube_fare][a](len(list(g))) for (a, g) in groupby(map(lambda a: isinstance(a, str), journey))))\n return f'\u00a3{s:.2f}'", "def london_city_hacker(journey):\n total = 0.0\n l = []\n for i in range(len(journey)):\n if type(journey[i]) == str:\n total += 2.4\n elif i < len(journey) - 1 and type(journey[i + 1]) == int:\n l.append(journey[i])\n if len(l) == 2:\n total += 1.5\n l = []\n else:\n total += 1.5\n l = []\n total = round(total, 2)\n return '\u00a3' + str(total) + '0'", "from itertools import groupby\n\ndef london_city_hacker(journey):\n return f'\u00a3{sum((2.4 * len(list(l)) if k is str else (len(list(l)) + 1) // 2 * 1.5 for (k, l) in groupby(journey, type))):.2f}'", "def london_city_hacker(journey):\n bus_counter = 0\n bus_price = 0\n tube_price = 0\n for i in journey:\n if type(i) is int:\n bus_counter += 1\n if bus_counter > 1:\n bus_counter = 0\n bus_price += 0\n else:\n bus_price += 1.5\n if type(i) is str:\n bus_counter = 0\n tube_price += 2.4\n return f'\u00a3{tube_price + bus_price:.2f}'", "def london_city_hacker(journey):\n sum = 0.0\n isBus = False\n for i in journey:\n if len(str(i)) <= 3:\n if isBus:\n isBus = 0\n else:\n sum += 1.5\n isBus = 1\n else:\n sum += 2.4\n isBus = 0\n sum = round(sum * 100) / 100\n return f'\u00a3{str(sum)}0'", "def london_city_hacker(journey):\n total_cost = 0\n adjacent_bus_tour = 0\n for tour in journey:\n if type(tour) == str:\n adjacent_bus_tour = 0\n total_cost += 2.4\n else:\n adjacent_bus_tour += 1\n if adjacent_bus_tour == 2:\n adjacent_bus_tour = 0\n else:\n total_cost += 1.5\n return f'\u00a3{total_cost:.2f}'", "from itertools import groupby\n\ndef london_city_hacker(journey):\n arr = list(map(type, journey))\n s = 0\n for (k, g) in groupby(arr):\n g = len(list(g))\n if k == str:\n s += 2.4 * g\n else:\n s += 1.5 * (g // 2 + (1 if g % 2 else 0) if g > 1 else g)\n return f'\u00a3{round(s, 2):.2f}'"], "starter_code": "def london_city_hacker(journey):\n", "input_output": {"fn_name": "london_city_hacker", "inputs": [[[12, "Central", "Circle", 21]], [["Piccidilly", 56]], [["Northern", "Central", "Circle"]], [["Piccidilly", 56, 93, 243]], [[386, 56, 1, 876]], [[]]], "outputs": [["\u00a37.80"], ["\u00a33.90"], ["\u00a37.20"], ["\u00a35.40"], ["\u00a33.00"], ["\u00a30.00"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5bce125d3bb2adff0d000245", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "london_city_hacker", "task_id": "TACO_lite/29", "example": [[], []]} +{"requirement": "## Grade book\n\nComplete the function so that it finds the mean of the three scores passed to it and returns the letter value associated with that grade.\n\nNumerical Score | Letter Grade\n--- | ---\n90 <= score <= 100 | 'A'\n80 <= score < 90 | 'B'\n70 <= score < 80 | 'C'\n60 <= score < 70 | 'D'\n 0 <= score < 60 | 'F'\n\nTested values are all between 0 and 100. Theres is no need to check for negative values or values greater than 100.", "solutions": ["def get_grade(s1, s2, s3):\n m = (s1 + s2 + s3) / 3.0\n if 90 <= m <= 100:\n return 'A'\n elif 80 <= m < 90:\n return 'B'\n elif 70 <= m < 80:\n return 'C'\n elif 60 <= m < 70:\n return 'D'\n return 'F'", "def get_grade(s1, s2, s3):\n mean = sum([s1, s2, s3]) / 3\n if mean >= 90:\n return 'A'\n if mean >= 80:\n return 'B'\n if mean >= 70:\n return 'C'\n if mean >= 60:\n return 'D'\n return 'F'", "def get_grade(*s):\n return 'FFFFFFDCBAA'[sum(s) // 30]", "scores = {10: 'A', 9: 'A', 8: 'B', 7: 'C', 6: 'D'}\n\ndef get_grade(*args):\n mean = sum(args) / len(args)\n return scores.get(mean // 10, 'F')", "get_grade = lambda *a: 'FFFFFFDCBAA'[sum(a) // 3 // 10]", "def get_grade(*arg):\n return list('FDCBAA')[max(int(sum(arg) / 30 - 5), 0)]", "def get_grade(s1, s2, s3):\n m = (s1 + s2 + s3) / 3\n if m > 89:\n return 'A'\n elif m > 79:\n return 'B'\n elif m > 69:\n return 'C'\n elif m > 59:\n return 'D'\n else:\n return 'F'", "def get_grade(*args):\n return {6: 'D', 7: 'C', 8: 'B', 9: 'A', 10: 'A'}.get(sum(args) // 30, 'F')", "def get_grade(s1, s2, s3):\n return next(('ABCDF'[i] for (i, low) in enumerate([90, 80, 70, 60, 0]) if (s1 + s2 + s3) / 3 >= low))", "def get_grade(*grades):\n mean = sum(grades) / len(grades)\n for (score, grade) in [(90, 'A'), (80, 'B'), (70, 'C'), (60, 'D'), (0, 'F')]:\n if mean >= score:\n return grade", "def get_grade(s1, s2, s3):\n m = (s1 + s2 + s3) / 3\n return 'A' if m >= 90 else 'B' if m >= 80 else 'C' if m >= 70 else 'D' if m >= 60 else 'F'", "def get_grade(s1, s2, s3):\n s = s1 + s2 + s3\n s /= 3\n if s >= 90:\n return 'A'\n elif s >= 80:\n return 'B'\n elif s >= 70:\n return 'C'\n elif s >= 60:\n return 'D'\n return 'F'", "def get_grade(s1, s2, s3):\n grades = {range(60): 'F', range(60, 70): 'D', range(70, 80): 'C', range(80, 90): 'B', range(90, 101): 'A'}\n for x in grades:\n if int((s1 + s2 + s3) / 3) in x:\n return grades[x]", "from statistics import mean\n\ndef get_grade(s1, s2, s3):\n a = mean((s1, s2, s3))\n if a < 60:\n return 'F'\n elif a < 70:\n return 'D'\n elif a < 80:\n return 'C'\n elif a < 90:\n return 'B'\n else:\n return 'A'", "def get_grade(*args):\n mean = sum(args) / len(args)\n if 90 <= mean <= 100:\n return 'A'\n elif 80 <= mean < 90:\n return 'B'\n elif 70 <= mean < 80:\n return 'C'\n elif 60 <= mean < 70:\n return 'D'\n else:\n return 'F'", "def get_grade(*s):\n score = sum(s) / len(s)\n if 90 <= score <= 100:\n return 'A'\n elif 80 <= score < 90:\n return 'B'\n elif 70 <= score < 80:\n return 'C'\n elif 60 <= score < 70:\n return 'D'\n else:\n return 'F'", "def get_grade(s1, s2, s3):\n mean = (s1 + s2 + s3) / 3.0\n if mean >= 70.0:\n if mean < 80.0:\n return 'C'\n elif mean < 90:\n return 'B'\n else:\n return 'A'\n elif mean >= 60:\n return 'D'\n else:\n return 'F'", "def get_grade(s1, s2, s3):\n mean = (s1 + s2 + s3) / 3\n for (limit, grade) in [(90, 'A'), (80, 'B'), (70, 'C'), (60, 'D')]:\n if limit <= mean <= 100:\n return grade\n return 'F'", "get_grade = lambda *scores: [letter for letter in {'A': (90, 100), 'B': (80, 90), 'C': (70, 80), 'D': (60, 70), 'F': (0, 60)} if {'A': (90, 100), 'B': (80, 90), 'C': (70, 80), 'D': (60, 70), 'F': (0, 60)}[letter][0] <= sum(scores) / len(scores) <= {'A': (90, 100), 'B': (80, 90), 'C': (70, 80), 'D': (60, 70), 'F': (0, 60)}[letter][1]][0]", "def get_grade(s1, s2, s3):\n score = (s1 + s2 + s3) / 3\n grades = [[90, 'A'], [80, 'B'], [70, 'C'], [60, 'D'], [0, 'F']]\n for grade in grades:\n if score >= grade[0]:\n return grade[1]", "import math\n\ndef get_grade(b, c, d):\n a = int((b + c + d) / 30)\n return 'A' if a == 10 else 'F' if a < 6 else chr(74 - a)", "def get_grade(s1, s2, s3):\n score = (s1 + s2 + s3) / 3\n score_mapping = {90 <= score <= 100: 'A', 80 <= score < 90: 'B', 70 <= score < 80: 'C', 60 <= score < 70: 'D', 0 <= score < 60: 'F'}\n return score_mapping[True]", "dict = {10: 'A', 9: 'A', 8: 'B', 7: 'C', 6: 'D'}\n\ndef get_grade(s1, s2, s3):\n mean = int((s1 + s2 + s3) / 30)\n if mean in dict:\n return dict[mean]\n return 'F'", "def get_grade(s1, s2, s3):\n grade = ['F'] * 60 + ['D'] * 10 + ['C'] * 10 + ['B'] * 10 + ['A'] * 11\n scores = (s1 + s2 + s3) // 3\n return grade[scores]", "def get_grade(*args):\n (avg, grades) = (sum(args) // len(args), ['F', 'D', 'C', 'B', 'A', 'A'])\n return grades[max(0, avg // 10 - 5)]", "def get_grade(*arg):\n return list('FDCBAA')[max(int((sum(arg) / 3 - 50) / 10), 0)]", "def get_grade(s1, s2, s3):\n if s1 + s2 + s3 >= 270:\n return 'A'\n if (s1 + s2 + s3 >= 240) & (s1 + s2 + s3 < 270):\n return 'B'\n if (s1 + s2 + s3 >= 210) & (s1 + s2 + s3 < 240):\n return 'C'\n if (s1 + s2 + s3 >= 180) & (s1 + s2 + s3 < 210):\n return 'D'\n if (s1 + s2 + s3 >= 0) & (s1 + s2 + s3 < 180):\n return 'F'\n return 'F'", "mean = lambda nums: sum(nums) / (len(nums) + 0.0)\n\ndef get_grade(s1, s2, s3):\n m = mean([s1, s2, s3])\n if m >= 90:\n return 'A'\n elif m >= 80:\n return 'B'\n elif m >= 70:\n return 'C'\n elif m >= 60:\n return 'D'\n else:\n return 'F'", "from collections import OrderedDict\n\ndef get_grade(*s):\n avg = sum(s) / len(s)\n for (a, g) in zip([60, 70, 80, 90], ['F', 'D', 'C', 'B']):\n if avg < a:\n return g\n return 'A'", "def get_grade(s1, s2, s3):\n score = (s1 + s2 + s3) / 3\n if 90 <= score <= 100:\n return 'A'\n elif 80 <= score < 90:\n return 'B'\n elif 70 <= score < 80:\n return 'C'\n elif 60 <= score < 70:\n return 'D'\n else:\n return 'F'", "def get_grade(*args):\n d = {(0, 6): 'F', (6, 7): 'D', (7, 8): 'C', (8, 9): 'B', (9, 11): 'A'}\n return next((d[rang] for rang in list(d.keys()) if sum(args) / len(args) // 10 in range(*rang)))", "def get_grade(s1, s2, s3):\n s = s1 + s2 + s3\n res = s / 3\n if res >= 90 and res <= 100:\n return 'A'\n elif res >= 80 and res <= 90:\n return 'B'\n elif res >= 70 and res <= 80:\n return 'C'\n elif res >= 60 and res <= 70:\n return 'D'\n elif res >= 0 and res <= 60:\n return 'F'", "def get_grade(s1, s2, s3):\n av = (int(s1) + int(s2) + int(s3)) / 3\n if int(av) >= 90:\n return 'A'\n if 80 <= int(av) < 90:\n return 'B'\n if 70 <= int(av) < 80:\n return 'C'\n if 60 <= int(av) < 70:\n return 'D'\n if int(av) < 60:\n return 'F'", "def get_grade(s1, s2, s3):\n result = (s1 + s2 + s3) / 3\n if result >= 90:\n return 'A'\n elif result >= 80 and result < 90:\n return 'B'\n elif result >= 70 and result < 80:\n return 'C'\n elif result >= 60 and result < 70:\n return 'D'\n else:\n return 'F'", "def get_grade(s1, s2, s3):\n score = (s1 + s2 + s3) / 3\n return {10: 'A', 9: 'A', 8: 'B', 7: 'C', 6: 'D'}.get(score // 10, 'F')", "def get_grade(s1, s2, s3):\n mean_grade = (s1 + s2 + s3) / 3\n grade = ''\n if mean_grade >= 0 and mean_grade < 60:\n grade = 'F'\n if mean_grade >= 60 and mean_grade < 70:\n grade = 'D'\n if mean_grade >= 70 and mean_grade < 80:\n grade = 'C'\n if mean_grade >= 80 and mean_grade < 90:\n grade = 'B'\n if mean_grade >= 90 and mean_grade <= 100:\n grade = 'A'\n return grade", "def get_grade(s1, s2, s3):\n score = (s1 + s2 + s3) / 3\n score = int(score)\n if score >= 90 and score <= 100:\n return 'A'\n if score >= 80 and score <= 90:\n return 'B'\n if score >= 70 and score <= 80:\n return 'C'\n if score >= 60 and score <= 70:\n return 'D'\n if score >= 0 and score <= 60:\n return 'F'", "def get_grade(s1, s2, s3):\n letter_grades = {(90, 100): 'A', (80, 89): 'B', (70, 79): 'C', (60, 69): 'D', (0, 59): 'F'}\n grade = (s1 + s2 + s3) / 3\n for score in list(letter_grades.keys()):\n if score[0] <= grade <= score[1]:\n return letter_grades[score]", "def get_grade(s1, s2, s3):\n avg = (s1 + s2 + s3) / 3\n scale = {'A': 90 <= avg <= 100, 'B': 80 <= avg < 90, 'C': 70 <= avg < 80, 'D': 60 <= avg < 70, 'F': 0 <= avg < 60}\n for (k, v) in scale.items():\n if v == True:\n return k", "def get_grade(s1, s2, s3):\n result = sum((s1, s2, s3)) / 3\n if result > 90:\n return 'A'\n elif 90 > result >= 80:\n return 'B'\n elif 80 > result >= 70:\n return 'C'\n elif 70 > result >= 60:\n return 'D'\n elif 60 > result >= 0:\n return 'F'", "def get_grade(s1, s2, s3):\n m = int((s1 + s2 + s3) / 3)\n if m >= 90 and m <= 100:\n return 'A'\n elif m >= 80 and m < 90:\n return 'B'\n elif m >= 70 and m < 80:\n return 'C'\n elif m >= 60 and m < 70:\n return 'D'\n else:\n return 'F'", "def get_grade(s1, s2, s3):\n dic = {10: 'A', 9: 'A', 8: 'B', 7: 'C', 6: 'D', 5: 'F', 4: 'F', 3: 'F', 2: 'F', 1: 'F', 0: 'F'}\n return dic[(s1 + s2 + s3) / 3 // 10]", "def get_grade(s1, s2, s3):\n avg = sum((s1, s2, s3)) // 3\n return ['F', 'D', 'C', 'B', 'A'][sum((avg > 59, avg > 69, avg > 79, avg > 89))]", "def get_grade(s1, s2, s3):\n curr = sum([s1, s2, s3]) // 3\n m = [[90, 100, 'A'], [80, 90, 'B'], [70, 80, 'C'], [60, 70, 'D']]\n for (s, e, grade) in m:\n if s <= curr <= e:\n return grade\n return 'F'", "def get_grade(s1, s2, s3):\n result = sum([s1, s2, s3]) // 30\n if result >= 9:\n return 'A'\n elif result >= 8:\n return 'B'\n elif result >= 7:\n return 'C'\n elif result >= 6:\n return 'D'\n else:\n return 'F'", "def get_grade(*args):\n if sum(args) / len(args) >= 90:\n return 'A'\n if sum(args) / len(args) >= 80:\n return 'B'\n if sum(args) / len(args) >= 70:\n return 'C'\n if sum(args) / len(args) >= 60:\n return 'D'\n return 'F'", "import numpy as np\n\ndef get_grade(*scores):\n grades = {10: 'A', 9: 'A', 8: 'B', 7: 'C', 6: 'D'}\n return grades.get(np.mean(scores) // 10, 'F')", "def get_grade(s1, s2, s3):\n f = int((s1 + s2 + s3) / 3)\n if f in range(90, 101):\n return 'A'\n elif f in range(80, 90):\n return 'B'\n elif f in range(70, 80):\n return 'C'\n elif f in range(60, 70):\n return 'D'\n elif f in range(0, 60):\n return 'F'", "def get_grade(s1, s2, s3):\n score = s1 + s2 + s3\n if 270 <= score:\n return 'A'\n elif 240 <= score:\n return 'B'\n elif 210 <= score:\n return 'C'\n elif 180 <= score:\n return 'D'\n return 'F'", "def get_grade(s1, s2, s3):\n grades = (s1, s2, s3)\n total = sum(grades)\n mean = total / len(grades)\n if 100 >= mean >= 90:\n return 'A'\n elif 90 > mean >= 80:\n return 'B'\n elif 80 > mean >= 70:\n return 'C'\n elif 70 > mean >= 60:\n return 'D'\n else:\n return 'F'"], "starter_code": "def get_grade(s1, s2, s3):\n", "input_output": {"fn_name": "get_grade", "inputs": [[95, 90, 93], [100, 85, 96], [92, 93, 94], [100, 100, 100], [70, 70, 100], [82, 85, 87], [84, 79, 85], [70, 70, 70], [75, 70, 79], [60, 82, 76], [65, 70, 59], [66, 62, 68], [58, 62, 70], [44, 55, 52], [48, 55, 52], [58, 59, 60], [0, 0, 0]], "outputs": [["A"], ["A"], ["A"], ["A"], ["B"], ["B"], ["B"], ["C"], ["C"], ["C"], ["D"], ["D"], ["D"], ["F"], ["F"], ["F"], ["F"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/55cbd4ba903825f7970000f5", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "get_grade", "task_id": "TACO_lite/72", "example": [[], []]} +{"requirement": "Given an array arr[] which contains data of N nodes of Complete Binary tree in level order fashion. The task is to print the level order traversal in sorted order. \nExample 1:\nInput:\nN = 7\narr[] = {7 6 5 4 3 2 1}\nOutput:\n7\n5 6\n1 2 3 4\nExplanation: The formed Binary Tree is:\n 7\n / \\\n 6 5\n / \\ / \\\n 4 3 2 1\nExample 2:\nInput:\nN = 6\narr[] = {5 6 4 9 2 1}\nOutput:\n5\n4 6\n1 2 9\nExplanation: The formed Binary Tree is:\n 5\n / \\\n 6 4\n / \\ / \n 9 2 1 \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function binTreeSortedLevels() which takes the array arr[] and its size N as inputs and returns a 2D array where the i-th array denotes the nodes of the i-th level in sorted order.\nExpected Time Complexity: O(NlogN).\nExpected Auxiliary Space: O(N).\nConstraints:\n1 <= N <= 10^{4}", "solutions": ["def bintreesortedlevels(arr, n):\n li = []\n i = 0\n level = 0\n while i < n:\n dumm = []\n if level == 0:\n li.append([arr[i]])\n i += 1\n level += 1\n else:\n size = 2 ** level\n if i + size < n:\n dumm.extend(arr[i:i + size])\n dumm.sort()\n li.append(dumm)\n i += size\n level += 1\n else:\n dumm.extend(arr[i:])\n dumm.sort()\n li.append(dumm)\n break\n return li", "def bintreesortedlevels(arr, n):\n ans = []\n m = 1\n level = []\n j = 0\n for i in range(n):\n if j < m:\n level.append(arr[i])\n j += 1\n else:\n level.sort()\n ans.append(level.copy())\n level.clear()\n m += m\n j = 1\n level.append(arr[i])\n level.sort()\n ans.append(level)\n return ans", "def bintreesortedlevels(arr, n):\n res = []\n i = 0\n ls = 1\n while i < n:\n t = (1 << ls) - 1\n t = min(t, n)\n temp = sorted(arr[i:t])\n i = t\n ls += 1\n res.append(temp)\n return res", "def bintreesortedlevels(arr, n):\n res = []\n (i, total) = (0, 0)\n while total < n:\n temp = []\n for j in range(2 ** i):\n if total < n:\n temp.append(arr[total])\n total += 1\n else:\n break\n temp.sort()\n res.append(temp)\n i += 1\n return res", "def bintreesortedlevels(arr, n):\n n = len(arr)\n list2 = [[arr[0]]]\n c = 0\n j = 1\n list3 = []\n for x in range(1, n):\n if c == 2 ** j - 1:\n list3.append(arr[x])\n list3.sort()\n list2.append(list3)\n list3 = []\n j += 1\n c = 0\n else:\n list3.append(arr[x])\n c += 1\n if len(list3) != 0:\n list3.sort()\n list2.append(list3)\n return list2", "from collections import deque\n\ndef bintreesortedlevels(arr, n):\n dq = deque()\n dq.append(0)\n res = []\n while len(dq) > 0:\n currsize = len(dq)\n t = []\n for i in range(currsize):\n temp = dq.popleft()\n t.append(arr[temp])\n if 2 * temp + 1 < n:\n dq.append(2 * temp + 1)\n if 2 * temp + 2 < n:\n dq.append(2 * temp + 2)\n t.sort()\n res.append(t)\n return res", "def bintreesortedlevels(arr, n):\n final = []\n l = [1]\n final.append([arr[0]])\n i = 0\n while True:\n li = len(l)\n l = []\n for j in range(li):\n if 2 * i + 1 < n:\n l.append(arr[2 * i + 1])\n if 2 * i + 2 < n:\n l.append(arr[2 * i + 2])\n i += 1\n if len(l):\n final.append(sorted(l))\n else:\n break\n return final", "def bintreesortedlevels(arr, n):\n output = []\n i = 0\n while 2 ** i <= n:\n j = 2 ** i\n k = 2 ** (i + 1)\n i += 1\n output.append(sorted(arr[j - 1:k - 1]))\n return output", "def bintreesortedlevels(arr, n):\n a1 = {}\n queue = [0]\n queue1 = [0]\n while len(queue) > 0:\n x = queue.pop(0)\n y = queue1.pop(0)\n if y not in a1:\n a1[y] = []\n a1[y].append(arr[x])\n if 2 * x + 1 < len(arr):\n queue.append(2 * x + 1)\n queue1.append(y + 1)\n if 2 * x + 2 < len(arr):\n queue.append(2 * x + 2)\n queue1.append(y + 1)\n e = []\n for i in range(max(a1) + 1):\n e.append(sorted(a1[i]))\n return e", "from collections import deque\nfrom sortedcontainers import SortedList\n\ndef bintreesortedlevels(arr, n):\n q = deque([0])\n res = []\n while q:\n t = SortedList()\n for _ in range(len(q)):\n cur = q.popleft()\n t.add(arr[cur])\n for i in [2 * cur + 1, 2 * cur + 2]:\n if i < len(arr):\n q.append(i)\n res.append(t)\n return res", "from collections import deque\nfrom heapq import heappush, heappop\n\ndef bintreesortedlevels(arr, n):\n q = deque([0])\n res = []\n while q:\n hp = []\n for _ in range(len(q)):\n cur = q.popleft()\n heappush(hp, arr[cur])\n for i in [2 * cur + 1, 2 * cur + 2]:\n if i < len(arr):\n q.append(i)\n t = []\n while hp:\n t.append(heappop(hp))\n res.append(t)\n return res", "def bintreesortedlevels(arr, n):\n (res, start, end, len1) = ([], 0, 1, 1)\n while start < n:\n res.append(sorted(arr[start:end]))\n len1 *= 2\n start = end\n end = start + len1\n return res", "def bintreesortedlevels(arr, n):\n i = 1\n ans = []\n while len(arr):\n ans.append(sorted(arr[:i]))\n arr = arr[i:]\n i <<= 1\n return ans", "def bintreesortedlevels(arr, n):\n i = 0\n k = 1\n res = []\n while i < n:\n temp = arr[i:i + k]\n temp.sort()\n res.append(temp)\n i += k\n k *= 2\n return res", "def bintreesortedlevels(arr, n):\n _list = []\n a = 1\n curr = 0\n while curr < n:\n _list.append(sorted(arr[curr:curr + a]))\n curr += a\n a *= 2\n return _list", "def bintreesortedlevels(arr, n):\n if n == 1:\n return [[arr[0]]]\n else:\n l = [[arr[0]]]\n i = 1\n c = 1\n while i < n:\n size = 2 ** c\n if i + size < n:\n a = arr[i:i + size]\n a.sort()\n l.append(a)\n i += size\n c += 1\n else:\n a = arr[i:]\n a.sort()\n l.append(a)\n break\n return l", "def bintreesortedlevels(arr, n):\n start = 0\n i = 0\n increment = 2 ** i\n list1 = []\n while start < n:\n list1.append(sorted(arr[start:start + increment]))\n start += increment\n i += 1\n increment = 2 ** i\n return list1", "def bintreesortedlevels(arr, n):\n res = []\n i = 0\n count = 0\n level = 0\n while True:\n count = 2 ** level\n t = []\n while count != 0 and i < n:\n t.append(arr[i])\n i += 1\n count -= 1\n res.append(sorted(t))\n if i >= n:\n break\n level += 1\n return res", "def bintreesortedlevels(arr, n):\n res = []\n l = 0\n i = 0\n while True:\n count = int(2 ** l)\n tmp = []\n while count != 0 and i < n:\n tmp.append(arr[i])\n i += 1\n count -= 1\n res.append(sorted(tmp))\n if i >= n:\n break\n l += 1\n return res", "def bintreesortedlevels(arr, n):\n i = 0\n a = []\n while 2 ** i <= n:\n a.append(sorted(arr[:2 ** i]))\n arr[:] = arr[2 ** i:]\n i = i + 1\n return a", "def bintreesortedlevels(arr, n):\n ans = []\n i = 0\n level = 0\n while True:\n count = int(2 ** level)\n tmp = []\n while count != 0 and i < n:\n tmp.append(arr[i])\n i += 1\n count -= 1\n ans.append(sorted(tmp))\n if i >= n:\n break\n level += 1\n return ans", "def bintreesortedlevels(arr, n):\n from math import exp\n level = 0\n prevLevelEnd = 0\n out = []\n while prevLevelEnd < n:\n nAtLevel = pow(2, level)\n out.append(list(sorted(arr[prevLevelEnd:prevLevelEnd + nAtLevel])))\n prevLevelEnd += nAtLevel\n level += 1\n return out", "def bintreesortedlevels(arr, n):\n re = []\n level = 0\n i = 0\n while i < n:\n ans = []\n if level == 0:\n re.append([arr[i]])\n i += 1\n level += 1\n else:\n size = 2 ** level\n if i + size < n:\n ans.extend(arr[i:i + size])\n ans.sort()\n re.append(ans)\n i += size\n level += 1\n else:\n ans.extend(arr[i:])\n ans.sort()\n re.append(ans)\n break\n return re", "import heapq\n\ndef bintreesortedlevels(arr, n):\n lst = []\n x = 0\n y = 1\n while True:\n ll = []\n for j in range(x, min(x + y, n)):\n ll.append(arr[j])\n lst.append(sorted(ll))\n x = x + y\n y = 2 * y\n if x >= n:\n break\n return lst", "def bintreesortedlevels(x, n):\n res = []\n i = 0\n j = 1\n while i < n:\n res.append(sorted(x[i:i + j]))\n i = i + j\n j = j * 2\n return res", "def bintreesortedlevels(arr, n):\n ans = []\n si = 0\n k = 0\n while si < n:\n size = 2 ** k\n k += 1\n if si + size >= n:\n tans = arr[si:]\n else:\n tans = arr[si:si + size]\n tans.sort()\n ans.append(tans)\n si += size\n return ans", "def bintreesortedlevels(arr, n):\n lst = []\n level = 0\n i = 0\n while i < n:\n l = []\n if level == 0:\n l.append(arr[i])\n lst.append(l)\n i = i + 1\n level = level + 1\n else:\n size = 2 ** level\n if i + size < n:\n l.extend(arr[i:i + size])\n l.sort()\n lst.append(l)\n i = i + size\n level = level + 1\n else:\n l.extend(arr[i:])\n l.sort()\n lst.append(l)\n break\n return lst", "def bintreesortedlevels(arr, n):\n a = [[arr[0]]]\n i = 1\n while i < n:\n b = arr[i:2 * i + 1]\n b.sort()\n a.append(b)\n i = 2 * i + 1\n return a", "def bintreesortedlevels(arr, n):\n c = 0\n i = 0\n ans = []\n while c < n:\n l = []\n x = pow(2, i)\n while x > 0 and c < n:\n l.append(arr[c])\n c += 1\n x -= 1\n i += 1\n l.sort()\n ans.append(l)\n return ans", "from collections import deque\n\ndef bintreesortedlevels(arr, n):\n lqc = deque()\n lqc.append(0)\n lqn = deque()\n lsrl = deque()\n rslt = deque()\n while len(lqc) > 0:\n idx = lqc.popleft()\n lsrl.append(arr[idx])\n if 2 * idx + 1 < n:\n lqn.append(2 * idx + 1)\n if 2 * idx + 2 < n:\n lqn.append(2 * idx + 2)\n if len(lqc) == 0:\n lqc = lqn.copy()\n lqn = deque()\n lsrl = list(lsrl)\n lsrl.sort()\n rslt.append(lsrl)\n lsrl = deque()\n return rslt", "def bintreesortedlevels(arr, n):\n mm = 0\n x = 0\n b = []\n if n == 1:\n return [arr]\n exit()\n while x < n:\n e = 2 ** mm\n t = []\n for k in range(e):\n if x < n:\n t.append(arr[x])\n x = x + 1\n t.sort()\n mm = mm + 1\n b.append(t)\n return b", "from collections import defaultdict\nimport queue\n\ndef bintreesortedlevels(arr, n):\n q = queue.deque()\n dic = defaultdict(list)\n q.append([arr[0], 0, 0])\n while q:\n ele = q.popleft()\n dic[ele[1]].append(ele[0])\n val = 2 * ele[2]\n if val + 1 < n:\n q.append([arr[val + 1], ele[1] + 1, val + 1])\n if val + 2 < n:\n q.append([arr[val + 2], ele[1] + 1, val + 2])\n for i in dic:\n dic[i].sort()\n return dic", "def bintreesortedlevels(arr, n):\n l = 0\n el = 1\n r = l + el\n ans = []\n while r <= len(arr):\n brr = arr[l:r]\n brr.sort()\n ans.append(brr)\n el *= 2\n if r < len(arr):\n l = r\n if l + el <= len(arr):\n r = l + el\n else:\n r = len(arr)\n elif r == len(arr):\n break\n return ans", "def bintreesortedlevels(arr, n):\n if not arr:\n return\n res = [[arr[0]]]\n level = 1\n i = 1\n l = len(arr)\n while i < l:\n tmp = []\n j = 0\n while i < l and j < 2 ** level:\n tmp.append(arr[i])\n i += 1\n j += 1\n level += 1\n tmp.sort()\n res.append(tmp)\n return res", "def bintreesortedlevels(arr, n):\n ind = 0\n ans = []\n q = [arr[ind]]\n while q:\n b = sorted(q)\n ans.append(b)\n nn = len(q)\n for i in range(nn):\n p = q.pop(0)\n if ind + 1 < n:\n q.append(arr[ind + 1])\n if ind + 2 < n:\n q.append(arr[ind + 2])\n ind += 2\n return ans", "def bintreesortedlevels(arr, n):\n lvl = -1\n ans = []\n while len(arr) > 0:\n lvl += 1\n s = pow(2, lvl)\n if s > len(arr):\n s = len(arr)\n arr[0:s].sort()\n ans.append([])\n while s > 0:\n ans[lvl].append(arr.pop(0))\n s -= 1\n for i in range(lvl + 1):\n ans[i].sort()\n return ans", "def bintreesortedlevels(arr, n):\n j = 0\n l = []\n while j < n:\n i = 2 * j + 1\n l1 = arr[j:i]\n l1.sort()\n l.append(l1)\n j = i\n return l", "def bintreesortedlevels(arr, n):\n c = 0\n p = 0\n l = []\n while p < n:\n s = 2 ** c\n k = arr[p:p + s]\n c = c + 1\n p = p + s\n k.sort()\n l.append(k)\n return l", "from collections import deque\n\ndef bintreesortedlevels(arr, n):\n (i, j, k) = (0, 0, 0)\n ans = []\n while j < n:\n st = []\n i = 2 ** k\n while i > 0 and j < n:\n st.append(arr[j])\n j += 1\n i -= 1\n ans.append(sorted(st))\n k += 1\n return ans", "def bintreesortedlevels(l, n):\n start = 0\n end = 0\n count = 0\n result_list = []\n while True:\n end = 2 ** count\n if end > len(l):\n break\n result_list.append(sorted(l[start:end + start]))\n count += 1\n start += end\n return result_list", "def bintreesortedlevels(arr, n):\n ans = []\n if n == 0:\n return ans\n size = 1\n start = 0\n while True:\n if start + size > n:\n level = arr[start:n]\n if level:\n ans.append(sorted(level))\n break\n else:\n level = arr[start:start + size]\n ans.append(sorted(level))\n start += size\n size *= 2\n return ans", "def bintreesortedlevels(arr, n):\n if n == 0:\n return []\n ans = [[arr[0]]]\n l = 0\n r = 1\n while r < n:\n l = min(l * 2 + 1, n - 1)\n r = min(r * 2 + 1, n)\n ans.append(sorted(arr[l:r]))\n return ans", "def bintreesortedlevels(arr, n):\n curr = 1\n i = 0\n j = 0\n final_ans = []\n ans = []\n while i < n:\n ans.append(arr[i])\n i += 1\n j += 1\n if j == curr:\n j = 0\n curr *= 2\n ans.sort()\n final_ans.append(ans)\n ans = []\n if len(ans):\n ans.sort()\n final_ans.append(ans)\n return final_ans", "def bintreesortedlevels(arr, n):\n if not arr:\n return []\n res = []\n q = [arr[0]]\n pointer = 1\n while q:\n tempQ = []\n data = []\n while q:\n data.append(q.pop(0))\n if pointer < len(arr):\n tempQ.append(arr[pointer])\n pointer += 1\n if pointer < len(arr):\n tempQ.append(arr[pointer])\n pointer += 1\n res.append(sorted(data))\n q = tempQ\n return res", "def bintreesortedlevels(arr, n):\n res = []\n i = 0\n k = 0\n while i < n:\n tmp = []\n lvl = 2 ** k\n while lvl > 0 and i < n:\n tmp.append(arr[i])\n i += 1\n lvl -= 1\n tmp.sort()\n res.append(tmp)\n k += 1\n return res", "import math\n\ndef bintreesortedlevels(arr, n):\n res = []\n (j, k) = (0, 0)\n while j < n:\n tmp = []\n lvl = math.pow(2, k)\n while lvl > 0 and j < n:\n tmp.append(arr[j])\n lvl -= 1\n j += 1\n tmp.sort()\n res.append(tmp)\n k += 1\n return res", "def bintreesortedlevels(arr, n):\n level = 0\n index = 0\n ans = list()\n while index < n:\n nodesCurrLevel = pow(2, level) - 1\n lastindex = min(index + nodesCurrLevel, n - 1)\n arr = arr[:index] + sorted(arr[index:lastindex + 1]) + arr[lastindex + 1:]\n lst = list()\n while index <= lastindex:\n lst.append(arr[index])\n index += 1\n ans.append(lst)\n level += 1\n return ans", "def bintreesortedlevels(arr, n):\n (k, i) = (0, 1)\n ans = []\n z = []\n tot = 0\n for x in arr:\n if k < i:\n z.append(x)\n k += 1\n else:\n ans.append(sorted(z))\n tot += k\n k = 0\n i *= 2\n z = []\n z.append(x)\n k += 1\n if tot != n:\n ans.append(sorted(z))\n return ans", "def bintreesortedlevels(arr, n):\n ans = []\n i = 1\n while i <= n:\n temp = []\n for j in range(i):\n if not arr:\n break\n temp.append(arr.pop(0))\n temp.sort()\n ans.append(temp)\n i *= 2\n return ans", "def bintreesortedlevels(arr, n):\n l = 0\n i = 0\n s = []\n while i < n:\n cln = 2 ** l\n j = min(i + cln - 1, n - 1)\n s.append(sorted(arr[i:j + 1]))\n i = j + 1\n l += 1\n return s", "def bintreesortedlevels(arr, n):\n ans = []\n c = 0\n i = 1\n while True:\n v = []\n j = 0\n while j < i and c < n:\n v.append(arr[c])\n c += 1\n j += 1\n ans.append(sorted(v))\n i = 2 * i\n if c == n:\n break\n return ans", "def bintreesortedlevels(arr, n):\n ans = []\n i = 0\n while arr:\n temp = []\n c = 0\n while c < 2 ** i and arr:\n temp.append(arr.pop(0))\n c += 1\n ans.append(sorted(list(temp)))\n i += 1\n return ans", "def bintreesortedlevels(a, n):\n l = []\n q = [0]\n while q:\n t = a[q[0]:q[-1] + 1]\n t.sort()\n l.append(t)\n t = q.copy()\n q.clear()\n for e in t:\n r1 = 2 * e + 1\n r2 = 2 * e + 2\n if r1 < n:\n q.append(r1)\n if r2 < n:\n q.append(r2)\n return l", "def bintreesortedlevels(arr, n):\n res = []\n level = 0\n i = 0\n while i < len(arr):\n res.append([])\n j = min(len(arr), i + pow(2, level)) - 1\n for k in range(j, i - 1, -1):\n res[-1].append(arr[k])\n i = j + 1\n level += 1\n res[-1].sort()\n return res", "def bintreesortedlevels(arr, n):\n ans = []\n i = 0\n c = 0\n j = 2 ** c\n while i < n and j < n:\n t = arr[i:j]\n ans.append(sorted(t))\n i = j\n c += 1\n j = min(n, i + 2 ** c)\n ans.append(sorted(arr[i:j]))\n return ans", "def bintreesortedlevels(arr, n):\n j = 0\n level = []\n result = []\n for i in range(n):\n if len(level) < 2 ** j:\n level.append(arr[i])\n if len(level) == 2 ** j or i == n - 1:\n result.append(sorted(level.copy()))\n level.clear()\n j += 1\n i += 1\n return result"], "starter_code": "def bintreesortedlevels (arr, n):\n", "input_output": {"inputs": ["N = 7\narr[] = {7 6 5 4 3 2 1}", "N = 6\narr[] = {5 6 4 9 2 1}"], "outputs": ["7\n5 6\n1 2 3 4", "5\n4 6\n1 2 9"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Tree", "Sorting", "Queue", "Data Structures", "priority-queue"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/print-binary-tree-levels-in-sorted-order3241/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(NlogN).", "entry_point": "bintreesortedlevels", "task_id": "TACO_lite/3", "example": [[[7, [7, 6, 5, 4, 3, 2, 1]], [6, [5, 6, 4, 9, 2, 1]]], [null, null]]} +{"requirement": "Given a N x N matrix such that each of its cells contains some coins. Count the number of ways to collect exactly K coins while moving from top left corner of the matrix to the bottom right. From a cell (i, j), you can only move to (i+1, j) or (i, j+1).\nExample 1:\nInput:\nK = 12, N = 3\narr[] = [[1, 2, 3], \n [4, 6, 5], \n [3, 2, 1]]\nOutput: 2\nExplanation: \nThere are 2 possible paths \nwith exactly K coins, (1 + 2 + \n6 + 2 + 1) and (1 + 2 + 3 + 5 + 1).\nExample 2:\nInput:\nK = 16, N = 3\narr[] = [[1, 2, 3], \n [4, 6, 5], \n [9, 8, 7]]\nOutput: 0 \nExplanation: \nThere are no possible paths that lead \nto sum=16\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function numberOfPath() which takes N, K and 2D matrix arr[][] as input parameters and returns the number of possible paths.\nExpected Time Complexity: O(n*n*k)\nExpected Auxiliary Space: O(n*n*k)\nConstraints:\n1 <= K < 100\n1 <= N < 100\n1 <= arr_{ij} <= 200", "solutions": ["def util(a, i, j, n, m, k):\n global dp\n if i >= n or j >= m or k < 0:\n return 0\n if i == n - 1 and j == m - 1:\n if k - a[i][j] == 0:\n return 1\n return 0\n if dp[i][j][k] != -1:\n return dp[i][j][k]\n dp[i][j][k] = self.util(a, i + 1, j, n, m, k - a[i][j]) + self.util(a, i, j + 1, n, m, k - a[i][j])\n return dp[i][j][k]\n\ndef numberofpath(N, K, arr):\n global dp\n dp = [[[-1 for x in range(K + 1)] for i in range(N)] for j in range(N)]\n return self.util(arr, 0, 0, N, N, K)", "from collections import defaultdict as dd\n\ndef numberofpath(N, K, arr):\n store = []\n for i in range(N):\n store.append([])\n for j in range(N):\n store[-1].append({})\n store[0][0][arr[0][0]] = 1\n for i in range(1, N):\n store[0][i][list(store[0][i - 1].keys())[0] + arr[0][i]] = 1\n store[i][0][list(store[i - 1][0].keys())[0] + arr[i][0]] = 1\n for i in range(1, N):\n for j in range(1, N):\n for item in store[i - 1][j].keys():\n store[i][j][item + arr[i][j]] = store[i - 1][j][item]\n for item in store[i][j - 1].keys():\n if item + arr[i][j] in store[i][j]:\n store[i][j][item + arr[i][j]] += store[i][j - 1][item]\n else:\n store[i][j][item + arr[i][j]] = store[i][j - 1][item]\n return store[N - 1][N - 1][K] if K in store[N - 1][N - 1] else 0", "def numberofpath(N, K, arr):\n\n def solve(i, j, n, k, arr, dp):\n if i >= n or j >= n or k < 0:\n return 0\n if i == n - 1 and j == n - 1:\n if k == arr[i][j]:\n return 1\n return 0\n if (i, j, k) in ways:\n return ways[i, j, k]\n ways[i, j, k] = solve(i + 1, j, n, k - arr[i][j], arr, dp) + solve(i, j + 1, n, k - arr[i][j], arr, dp)\n return ways[i, j, k]\n ways = {}\n return solve(0, 0, N, K, arr, ways)", "def numberofpath(N, K, arr):\n memo = {}\n\n def helper(i, j, k):\n if i >= N or j >= N or k < 0:\n return 0\n if i == N - 1 and j == N - 1:\n return 1 if k == arr[i][j] else 0\n if (i, j, k) in memo:\n return memo[i, j, k]\n ways = helper(i + 1, j, k - arr[i][j]) + helper(i, j + 1, k - arr[i][j])\n memo[i, j, k] = ways\n return ways\n return helper(0, 0, K)", "def numberofpath(N, K, A):\n\n def _solve(r, c, left):\n if r >= N or c >= N:\n return 0\n cell = A[r][c]\n if cell > left:\n return 0\n if r == c == N - 1:\n return 1 if left == cell else 0\n v = dp[r][c].get(left, -1)\n if v >= 0:\n return v\n ans = dp[r][c][left] = _solve(r + 1, c, left - cell) + _solve(r, c + 1, left - cell)\n return ans\n dp = [[{} for _ in range(N)] for _ in range(N)]\n ans = _solve(0, 0, K)\n return ans", "def numberofpath(N, K, arr):\n paths = {}\n for y in range(N - 1, -1, -1):\n for x in range(N - 1, -1, -1):\n coord = (x, y)\n coins = arr[x][y]\n if x < N - 1:\n x_paths = paths.get((x + 1, y), {})\n else:\n x_paths = {}\n if y < N - 1:\n y_paths = paths.get((x, y + 1), {})\n else:\n y_paths = {}\n my_paths = {}\n for (k, path_count) in x_paths.items():\n my_paths[k] = my_paths.get(k, 0) + path_count\n for (k, path_count) in y_paths.items():\n my_paths[k] = my_paths.get(k, 0) + path_count\n new_paths = {}\n if not my_paths and x == N - 1 and (y == N - 1):\n new_paths[coins] = 1\n else:\n for (k, path_count) in my_paths.items():\n new_val = k + coins\n if new_val <= K:\n new_paths[new_val] = path_count\n paths[coord] = new_paths\n return paths[0, 0].get(K, 0)", "from collections import defaultdict as dd\nfrom collections import Counter\n\ndef numberofpath(N, K, arr):\n store = []\n for i in range(N):\n store.append([])\n for j in range(N):\n store[-1].append(dd(lambda : 0))\n store[0][0][arr[0][0]] += 1\n for i in range(1, N):\n store[0][i][list(store[0][i - 1].keys())[0] + arr[0][i]] += 1\n store[i][0][list(store[i - 1][0].keys())[0] + arr[i][0]] += 1\n for i in range(1, N):\n for j in range(1, N):\n coins = arr[i][j]\n current_store = store[i][j]\n up_store = store[i - 1][j]\n left_store = store[i][j - 1]\n for item in store[i - 1][j].keys():\n current_store[item + coins] += up_store[item]\n for item in store[i][j - 1].keys():\n current_store[item + coins] += left_store[item]\n return store[N - 1][N - 1][K]", "def pathCountDPRecDP(mat, m, n, k, dp):\n if m < 0 or n < 0 or k < 0:\n return 0\n elif m == 0 and n == 0:\n return k == mat[m][n]\n if dp[m][n][k] != -1:\n return dp[m][n][k]\n dp[m][n][k] = pathCountDPRecDP(mat, m - 1, n, k - mat[m][n], dp) + pathCountDPRecDP(mat, m, n - 1, k - mat[m][n], dp)\n return dp[m][n][k]\n\ndef numberofpath(N, K, arr):\n dp = [[[-1 for co in range(K + 1)] for col in range(N + 1)] for row in range(N + 1)]\n return int(pathCountDPRecDP(arr, N - 1, N - 1, K, dp))", "def numberofpath(N, K, arr):\n\n def func(ind1, ind2, k, arr, dp, n):\n if ind1 >= n or ind2 >= n:\n return 0\n if k < 0:\n return 0\n if ind1 == n - 1 and ind2 == n - 1:\n if k == arr[ind1][ind2]:\n return 1\n return 0\n if dp[ind1][ind2][k] != 0:\n return dp[ind1][ind2][k]\n down = func(ind1 + 1, ind2, k - arr[ind1][ind2], arr, dp, n)\n right = func(ind1, ind2 + 1, k - arr[ind1][ind2], arr, dp, n)\n dp[ind1][ind2][k] = down + right\n return dp[ind1][ind2][k]\n dp = [[[0] * (K + 1) for i in range(N)] for j in range(N)]\n kk = func(0, 0, K, arr, dp, N)\n return kk", "def numberofpath(N, K, arr):\n dp = {}\n\n def fun(i, j, su):\n if i >= N or j >= N:\n return 0\n if i == N - 1 and j == N - 1:\n if su == arr[i][j]:\n return 1\n else:\n return 0\n if su < 0:\n return 0\n if (i, j, su) in dp:\n return dp[i, j, su]\n dp[i, j, su] = fun(i + 1, j, su - arr[i][j]) + fun(i, j + 1, su - arr[i][j])\n return dp[i, j, su]\n return fun(0, 0, K)", "def numberofpath(N, K, arr):\n t = [[[-1 for _ in range(100 + 1)] for j in range(N + 1)] for k in range(N + 1)]\n\n def solve(r, c, rem):\n if r < 0 or c < 0 or r >= N or (c >= N) or (rem < 0):\n return 0\n if r == N - 1 and c == N - 1:\n return int(rem == arr[r][c])\n if t[r][c][rem] != -1:\n return t[r][c][rem]\n t[r][c][rem] = solve(r + 1, c, rem - arr[r][c]) + solve(r, c + 1, rem - arr[r][c])\n return t[r][c][rem]\n return solve(0, 0, K)", "def numberofpath(N, K, arr):\n if not arr:\n return\n if N == 1 and K > arr[0][0]:\n return 0\n dp = [[[-1 for col in range(K + 1)] for col in range(N + 1)] for row in range(N + 1)]\n\n def pathCountDPRecDP(arr, m, n, k):\n if m < 0 or n < 0 or k < 0:\n return 0\n elif m == 0 and n == 0:\n if k == arr[m][n]:\n return 1\n else:\n return 0\n if dp[m][n][k] != -1:\n return dp[m][n][k]\n dp[m][n][k] = pathCountDPRecDP(arr, m - 1, n, k - arr[m][n]) + pathCountDPRecDP(arr, m, n - 1, k - arr[m][n])\n return dp[m][n][k]\n return pathCountDPRecDP(arr, N - 1, N - 1, K)", "def helper(i, j, s, arr, n, m, dp):\n if not i and (not j):\n return 1 if s == arr[i][j] else 0\n if i < 0 or j < 0 or s < 1:\n return 0\n if dp[i][j][s] != -1:\n return dp[i][j][s]\n up = helper(i - 1, j, s - arr[i][j], arr, n, m, dp)\n dn = helper(i, j - 1, s - arr[i][j], arr, n, m, dp)\n dp[i][j][s] = up + dn\n return dp[i][j][s]\n\ndef numberofpath(N, K, arr):\n si = len(arr)\n le = len(arr[0])\n assert si == N and le == N\n dp = [[[-1] * (K + 1) for _ in range(N)] for _ in range(N)]\n ans = helper(N - 1, N - 1, K, arr, N, N, dp)\n return ans", "def numberofpath(n, k, a):\n v = [[False] * n for i in range(n)]\n d = [[] * n for i in range(n)]\n dp = {}\n for i in range(n):\n for j in range(n):\n d[i].append(dp.copy())\n d[n - 1][n - 1][a[n - 1][n - 1]] = 1\n\n def solve(i, j, d, v):\n if i > n - 1 or j > n - 1:\n return {}\n if v[i][j]:\n return d[i][j]\n else:\n x = solve(i, j + 1, d, v)\n y = solve(i + 1, j, d, v)\n for z in x:\n if z + a[i][j] not in d[i][j]:\n d[i][j][z + a[i][j]] = x[z]\n else:\n d[i][j][z + a[i][j]] += x[z]\n for z in y:\n if z + a[i][j] not in d[i][j]:\n d[i][j][z + a[i][j]] = y[z]\n else:\n d[i][j][z + a[i][j]] += y[z]\n v[i][j] = True\n return d[i][j]\n d[0][0] = solve(0, 0, d, v)\n if k in d[0][0]:\n return d[0][0][k]\n return 0", "def numberofpath(N, k, arr):\n dp = {}\n\n def path(i, j, s, dp):\n if i < 0 or j < 0 or i >= N or (j >= N):\n return 0\n if i == N - 1 and j == N - 1:\n s += arr[i][j]\n if s == k:\n return 1\n return 0\n if (i, j, s) in dp:\n return dp[i, j, s]\n dp[i, j, s] = path(i + 1, j, s + arr[i][j], dp) + path(i, j + 1, s + arr[i][j], dp)\n return dp[i, j, s]\n return path(0, 0, 0, dp)", "def solve(mat, m, n, k, dp):\n if m < 0 or n < 0 or k < 0:\n return 0\n elif m == 0 and n == 0:\n if k == mat[m][n]:\n return 1\n return 0\n if (m, n, k) in dp:\n return dp[m, n, k]\n dp[m, n, k] = self.solve(mat, m - 1, n, k - mat[m][n], dp) + self.solve(mat, m, n - 1, k - mat[m][n], dp)\n return dp[m, n, k]\n\ndef numberofpath(N, K, arr):\n dp = {}\n return self.solve(arr, N - 1, N - 1, K, dp)", "from functools import lru_cache\n\ndef numberofpath(N, coins, mat):\n if not mat:\n return 0\n key = coins - mat[N - 1][N - 1]\n\n def dfs(i, j, curr):\n ans = 0\n if curr < 0:\n return 0\n if i == 0 and i == j:\n if curr == mat[0][0]:\n return 1\n return 0\n if i > 0:\n ans += dfs(i - 1, j, curr - mat[i][j])\n if j > 0:\n ans += dfs(i, j - 1, curr - mat[i][j])\n return ans\n ans = dfs(N - 1, N - 1, coins)\n return ans", "def pathCountDPRecDP(mat, m, n, k, dp):\n if m < 0 or n < 0 or k < 0:\n return 0\n elif m == 0 and n == 0:\n return 1 if k == mat[m][n] else 0\n if dp[m][n][k] != -1:\n return dp[m][n][k]\n dp[m][n][k] = self.pathCountDPRecDP(mat, m - 1, n, k - mat[m][n], dp) + self.pathCountDPRecDP(mat, m, n - 1, k - mat[m][n], dp)\n return dp[m][n][k]\n\ndef numberofpath(N, K, arr):\n dp = [[[-1 for col in range(110)] for col in range(N)] for row in range(N)]\n return self.pathCountDPRecDP(arr, N - 1, N - 1, K, dp)\n\ndef numberofpath1(N, K, arr):\n dx = [0, 1]\n dy = [1, 0]\n\n def inside(x, y):\n return x >= 0 and x < N and (y >= 0) and (y < N)\n dp1 = [[[0 for i in range(K + 5)] for j in range(N + 5)] for k in range(N + 5)]\n for i in range(N):\n for j in range(N):\n dp1[i][j][0] = 1\n for s in range(1, K + 1):\n for x in range(N):\n for y in range(N):\n if x == 0 or y == 0:\n if s - arr[x][y] >= 0:\n dp1[x][y][s] = dp1[x][y][s - arr[x][y]]\n elif s - arr[x][y] >= 0:\n dp1[x][y][s] += dp1[x - 1][y][s - arr[x][y]]\n dp1[x][y][s] += dp1[x][y - 1][s - arr[x][y]]\n return sum(dp1[:][:][K])", "def numberofpath(N, K, arr):\n\n def dfs(arr, i, j, k):\n if i < 0 or j < 0 or k < 0:\n return 0\n if i == 0 and j == 0:\n return k == arr[i][j]\n if dp[i][j][k] != -1:\n return dp[i][j][k]\n dp[i][j][k] = dfs(arr, i - 1, j, k - arr[i][j]) + dfs(arr, i, j - 1, k - arr[i][j])\n return dp[i][j][k]\n r = len(arr)\n c = len(arr[0])\n dp = [[[-1 for i in range(K + 1)] for j in range(c)] for m in range(r)]\n z = dfs(arr, r - 1, c - 1, K)\n if z == False:\n return 0\n else:\n return z", "def numberofpath(N, K, arr):\n dp = [[[-1] * (K + 1) for _ in range(N)] for __ in range(N)]\n\n def recur(i, j, k, dp):\n if i >= N or j >= N or k < 0:\n return 0\n if i == N - 1 and j == N - 1:\n if k == arr[i][j]:\n return 1\n return 0\n if dp[i][j][k] != -1:\n return dp[i][j][k]\n dp[i][j][k] = recur(i + 1, j, k - arr[i][j], dp) + recur(i, j + 1, k - arr[i][j], dp)\n return dp[i][j][k]\n return recur(0, 0, K, dp)", "def numberofpath(N, K, arr):\n m = len(arr)\n n = len(arr[0])\n\n def check(i, j, K):\n if i < 0 or j < 0 or K < 1:\n return 0\n if i == 0 and j == 0:\n if K == arr[i][j]:\n return 1\n else:\n return 0\n if dp[i][j][K] != -1:\n return dp[i][j][K]\n first = check(i - 1, j, K - arr[i][j])\n second = check(i, j - 1, K - arr[i][j])\n dp[i][j][K] = first + second\n return dp[i][j][K]\n dp = [[[-1 for i in range(K + 1)] for i in range(n)] for i in range(n)]\n return check(m - 1, n - 1, K)", "def memo(m, n, cost, grid, dp):\n if m == 0 and n == 0:\n return 1 if cost - grid[m][n] == 0 else 0\n if m < 0 or n < 0 or cost < 0:\n return 0\n if dp[m][n][cost] != -1:\n return dp[m][n][cost]\n dp[m][n][cost] = self.memo(m - 1, n, cost - grid[m][n], grid, dp) + self.memo(m, n - 1, cost - grid[m][n], grid, dp)\n return dp[m][n][cost]\n\ndef numberofpath(N, K, arr):\n dp = [[[-1] * (K + 1) for j in range(N)] for i in range(N)]\n return self.memo(N - 1, N - 1, K, arr, dp)", "def numberofpath(n, k, l):\n dp = [[{} for _ in range(n)] for _ in range(n)]\n dp[-1][-1][l[-1][-1]] = 1\n for i in range(n - 2, -1, -1):\n for t in dp[i + 1][-1]:\n x = t + l[i][-1]\n if x <= k:\n if x in dp[i][-1]:\n dp[i][-1][x] += dp[i + 1][-1][t]\n else:\n dp[i][-1][x] = dp[i + 1][-1][t]\n for t in dp[-1][i + 1]:\n x = t + l[-1][i]\n if x <= k:\n if x in dp[-1][i]:\n dp[-1][i][x] += dp[-1][i + 1][t]\n else:\n dp[-1][i][x] = dp[-1][i + 1][t]\n for i in range(n - 2, -1, -1):\n for j in range(n - 2, -1, -1):\n for t in dp[i + 1][j]:\n x = t + l[i][j]\n if x <= k:\n if x in dp[i][j]:\n dp[i][j][x] += dp[i + 1][j][t]\n else:\n dp[i][j][x] = dp[i + 1][j][t]\n for t in dp[i][j + 1]:\n x = t + l[i][j]\n if x <= k:\n if x in dp[i][j]:\n dp[i][j][x] += dp[i][j + 1][t]\n else:\n dp[i][j][x] = dp[i][j + 1][t]\n if k in dp[0][0]:\n return dp[0][0][k]\n return 0", "import sys\nsys.setrecursionlimit(10 ** 6)\n\ndef go(n, m, k):\n if k < 0:\n return 0\n if m < 0 or n < 0:\n return 0\n if n == 0 and m == 0:\n self.dp[n][m][k] = 1 if k == self.a[n][m] else 0\n return self.dp[n][m][k]\n if self.dp[n][m][k] != -1:\n return self.dp[n][m][k]\n left = self.go(n, m - 1, k - self.a[n][m])\n up = self.go(n - 1, m, k - self.a[n][m])\n self.dp[n][m][k] = left + up\n return self.dp[n][m][k]\n\ndef numberofpath(n, k, arr):\n for i in range(n):\n for j in range(n):\n self.a[i][j] = arr[i][j]\n for i in range(n):\n for j in range(n):\n for l in range(k + 1):\n self.dp[i][j][l] = -1\n self.go(n - 1, n - 1, k)\n return self.dp[n - 1][n - 1][k]", "def numberofpath(N, K, arr):\n dp = [[[-1 for _ in range(K + 1)] for _ in range(N)] for _ in range(N)]\n return self.solve(arr, dp, N, K, 0, 0, 0)\n\ndef solve(arr, dp, N, K, x, y, k):\n if x >= N or y >= N or x < 0 or (y < 0) or (k + arr[x][y] > K):\n return 0\n if x == N - 1 and y == N - 1 and (k + arr[x][y] == K):\n return 1\n if dp[x][y][k] != -1:\n return dp[x][y][k]\n dp[x][y][k] = self.solve(arr, dp, N, K, x + 1, y, k + arr[x][y]) + self.solve(arr, dp, N, K, x, y + 1, k + arr[x][y])\n return dp[x][y][k]", "def recur(m, n, k, a):\n global dp\n if m < 0 or n < 0 or k < 0:\n return 0\n if m == 0 and n == 0:\n return k == a[0][0]\n if dp[m][n][k]:\n return dp[m][n][k]\n dp[m][n][k] = self.recur(m - 1, n, k - a[m][n], a) + self.recur(m, n - 1, k - a[m][n], a)\n return dp[m][n][k]\n\ndef numberofpath(N, K, arr):\n global dp\n dp = [[[0 for i in range(K + 1)] for j in range(N)] for k in range(N)]\n ans = self.recur(N - 1, N - 1, K, arr)\n return ans if ans else 0", "def f(cr, cc, n, k, arr, dp):\n if cr == n - 1 and cc == n - 1:\n if k == 0:\n return 1\n return 0\n if k < 0:\n return 0\n state = (cr, cc, k)\n if state in dp:\n return dp[state]\n if cc + 1 < n:\n a1 = self.f(cr, cc + 1, n, k - arr[cr][cc + 1], arr, dp)\n else:\n a1 = 0\n if cr + 1 < n:\n a2 = self.f(cr + 1, cc, n, k - arr[cr + 1][cc], arr, dp)\n else:\n a2 = 0\n dp[state] = a1 + a2\n return a1 + a2\n\ndef numberofpath(N, K, arr):\n cr = 0\n cc = 0\n n = N\n k = K\n dp = {}\n return self.f(cr, cc, n, k - arr[cr][cc], arr, dp)", "def numberofpath(N, K, arr):\n memo = [[[-1] * (K + 1) for j in range(N)] for i in range(N)]\n return self.dfs(0, 0, N, arr, K, memo)\n\ndef dfs(i, j, N, arr, k, memo):\n if i < 0 or i > N - 1 or j < 0 or (j > N - 1):\n return 0\n if memo[i][j][k] != -1:\n return memo[i][j][k]\n if k - arr[i][j] < 0:\n return 0\n if k - arr[i][j] == 0 and i == N - 1 and (j == N - 1):\n return 1\n count = 0\n count += self.dfs(i, j + 1, N, arr, k - arr[i][j], memo)\n count += self.dfs(i + 1, j, N, arr, k - arr[i][j], memo)\n memo[i][j][k] = count\n return count", "def solve(i, j, N, K, arr, dp):\n if i < 0 or j < 0 or K < 0:\n return 0\n elif i == 0 and j == 0:\n return int(K == arr[i][j])\n if dp[i][j][K] != -1:\n return dp[i][j][K]\n dp[i][j][K] = self.solve(i - 1, j, N, K - arr[i][j], arr, dp) + self.solve(i, j - 1, N, K - arr[i][j], arr, dp)\n return dp[i][j][K]\n\ndef numberofpath(N, K, arr):\n dp = [[[-1 for k in range(K + 1)] for j in range(N)] for i in range(N)]\n return self.solve(N - 1, N - 1, N, K, arr, dp)", "def numberofpath(N, K, arr):\n\n def helper(i, j, s, memo):\n if i >= N or j >= N or s <= 0:\n return 0\n if i == N - 1 and j == N - 1 and (s == arr[i][j]):\n return 1\n key = (i, j, s)\n if key in memo:\n return memo[key]\n memo[key] = helper(i + 1, j, s - arr[i][j], memo) + helper(i, j + 1, s - arr[i][j], memo)\n return memo[key]\n memo = {}\n return helper(0, 0, K, memo)", "def numberofpath(N, K, arr):\n d = {}\n\n def calPathSum(i, j, s):\n if (i, j, s) in d:\n return d[i, j, s]\n if i < 0 or i >= N or j < 0 or (j >= N):\n d[i, j, s] = 0\n return 0\n if i == N - 1 and j == N - 1:\n if s + arr[i][j] == K:\n d[i, j, s] = 1\n return 1\n else:\n d[i, j, s] = 0\n return 0\n else:\n p1 = calPathSum(i + 1, j, arr[i][j] + s)\n p2 = calPathSum(i, j + 1, arr[i][j] + s)\n d[i, j, s] = p1 + p2\n return p1 + p2\n return calPathSum(0, 1, 1) + calPathSum(1, 0, 1)", "def numberofpath(N, K, arr):\n return self.paths(0, 0, K, arr, N, {})\n\ndef paths(cr, cc, K, arr, N, memo):\n if cr >= N or cc >= N:\n return 0\n if cr == N - 1 and cc == N - 1:\n if K - arr[cr][cc] != 0:\n return 0\n if cr == N - 1 and cc == N - 1:\n if K - arr[cr][cc] == 0:\n return 1\n currentKey = str(cr) + '-' + str(cc) + '-' + str(K)\n if currentKey in memo:\n return memo[currentKey]\n one = self.paths(cr + 1, cc, K - arr[cr][cc], arr, N, memo)\n two = self.paths(cr, cc + 1, K - arr[cr][cc], arr, N, memo)\n memo[currentKey] = one + two\n return memo[currentKey]", "def dfs(r, c, M, N, K, memo):\n if (r, c, K) in memo:\n return memo[r, c, K]\n if K < 0:\n return 0\n if (r, c) == (N - 1, N - 1):\n if K == 0:\n return 1\n return 0\n ans = 0\n for (nr, nc) in [(r + 1, c), (r, c + 1)]:\n if nr == N:\n continue\n if nc == N:\n continue\n ans += dfs(nr, nc, M, N, K - M[nr][nc], memo)\n memo[r, c, K] = ans\n return ans\n\ndef numberofpath(N, K, M):\n return dfs(0, 0, M, N, K - M[0][0], {})", "def numberofpath(N, K, arr):\n memo = {}\n\n def h(i, j, sum):\n if i >= N or j >= N or sum > K:\n return 0\n if i == N - 1 and j == N - 1:\n return int(sum + arr[i][j] == K)\n if (i, j, sum) in memo:\n return memo[i, j, sum]\n memo[i, j, sum] = h(i + 1, j, arr[i][j] + sum) + h(i, j + 1, arr[i][j] + sum)\n return memo[i, j, sum]\n return h(0, 0, 0)"], "starter_code": "def numberofpath (N, K, arr):\n", "input_output": {"inputs": ["K = 12, N = 3\r\narr[] = [[1, 2, 3], \r\n [4, 6, 5], \r\n [3, 2, 1]]", "K = 16, N = 3\r\narr[] = [[1, 2, 3], \r\n [4, 6, 5], \r\n [9, 8, 7]]"], "outputs": ["2", "0"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Recursion", "Matrix", "Data Structures", "Backtracking", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Dynamic programming", "Data structures", "Complete search"], "skill_types": ["Dynamic programming", "Data structures", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/number-of-paths-in-a-matrix-with-k-coins2728/1", "Expected Auxiliary Space": "O(n*n*k)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n*n*k)", "entry_point": "numberofpath", "task_id": "TACO_lite/91", "example": [[[12, 3, [[1, 2, 3], [4, 6, 5], [3, 2, 1]]], [16, 3, [[1, 2, 3], [4, 6, 5], [9, 8, 7]]]], [0, 0]]} +{"requirement": "A [Mersenne prime](https://en.wikipedia.org/wiki/Mersenne_prime) is a prime number that can be represented as:\nMn = 2^(n) - 1. Therefore, every Mersenne prime is one less than a power of two. \n\nWrite a function that will return whether the given integer `n` will produce a Mersenne prime or not.\n\nThe tests will check random integers up to 2000.", "solutions": ["def valid_mersenne(n):\n return n in {2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279}", "def valid_mersenne(n):\n if n < 2:\n return False\n if n == 2:\n return True\n mersenne = 2 ** n - 1\n residue = 4\n for _ in range(n - 2):\n residue = (residue * residue - 2) % mersenne\n return not residue", "def valid_mersenne(n):\n return n == 2 or (is_prime(n) and lucas_lehmer(n))\n\ndef is_prime(n):\n from itertools import chain\n return all((n % i != 0 for i in chain([2], range(3, int(n ** 0.5) + 1, 2))))\n\ndef lucas_lehmer(n):\n s = 4\n M = 2 ** n - 1\n for _ in range(n - 2):\n s = (s * s - 2) % M\n return s == 0", "A000043 = {2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457, 32582657, 37156667, 42643801, 43112609}\n\ndef valid_mersenne(n):\n return n in A000043", "def valid_mersenne(n):\n return n in [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941]", "valid_mersenne = {2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279}.__contains__"], "starter_code": "def valid_mersenne(n):\n", "input_output": {"fn_name": "valid_mersenne", "inputs": [[2], [3], [5], [7], [11], [13], [17], [19], [21], [23], [31], [49], [61], [89], [107], [127], [221], [521], [607], [1279]], "outputs": [[true], [true], [true], [true], [false], [true], [true], [true], [false], [false], [true], [false], [true], [true], [true], [true], [false], [true], [true], [true]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/56af6e4198909ab73200013f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "valid_mersenne", "task_id": "TACO_lite/144", "example": [[], []]} +{"requirement": "Given a number N, print all the numbers which are a bitwise subset of the binary representation of N. Bitwise subset of a number N will be the numbers i in the range 0 \u2264 i \u2264 N which satisfy the below condition:\nN & i == i\nExample 1:\nInput:\nN = 5\nOutput: 5 4 1 0\nExplanation:\n 0 & 5 = 0\n 1 & 5 = 1\n 2 & 5 = 0\n 3 & 5 = 1\n 4 & 5 = 4\n 5 & 5 = 5\n \nExample 2:\nInput:\nN = 9\nOutput: 9 8 1 0\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function printSubsets() which takes the integer N as input parameters and returns the array of integers that satisfy the above condition.\nExpected Time Complexity: O(K), where K is the number of bitwise subsets of N.\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 \u2264 N \u2264 10000", "solutions": ["def printsubsets(N):\n b = []\n for i in range(N + 1):\n if N & i == i:\n b.append(i)\n return list(reversed(b))", "def printsubsets(N):\n output = set([N])\n num = bin(N)[2:]\n num = num[::-1]\n for i in range(len(num)):\n if num[i] == '1':\n temp = set()\n for item in output:\n temp.add(item - 2 ** i)\n output.update(temp)\n return sorted(output, reverse=True)", "def printsubsets(n):\n res = []\n i = n\n while i != 0:\n res.append(i)\n i = i - 1 & n\n res.append(0)\n return res", "def printsubsets(N):\n pass\n a = set()\n for i in range(N + 1):\n a.add(i & N)\n return sorted(list(a), reverse=True)", "def printsubsets(N):\n a = []\n for i in range(0, N + 1):\n a.insert(0, N & i)\n a = list(set(a))\n a.sort()\n a = a[::-1]\n return a", "def printsubsets(N):\n ls = []\n i = N\n while i >= 0:\n if i & N == i:\n ls.append(i)\n i -= 1\n return ls", "def printsubsets(N):\n l = []\n for i in range(0, N + 1):\n if N & i not in l:\n l.append(N & i)\n l.sort(reverse=True)\n return l", "def printsubsets(N):\n pass\n L = []\n for i in range(N + 1):\n if N & i == i:\n L.append(i)\n return L[::-1]", "def printsubsets(N):\n ans = []\n for i in range(0, N + 1):\n x = i & N\n if x == i or x == N:\n ans.append(x)\n ans = ans[::-1]\n return ans", "def printsubsets(N):\n pass\n x = [i for i in range(0, N + 1) if N & i == i]\n return x[::-1]", "def printsubsets(N):\n pass\n u = []\n for i in range(0, N + 1):\n if N & i == i:\n u.append(i)\n return u[::-1]", "def printsubsets(N):\n s = bin(N)[2:]\n ans = [0]\n s = s[::-1]\n for i in range(len(s)):\n if s[i] == '1':\n k = len(ans)\n for j in range(k):\n ans.append(ans[j] + 2 ** i)\n return ans[::-1]", "def printsubsets(N):\n bit = str(bin(N)[2:])\n ans = [0]\n count = 0\n for i in bit[::-1]:\n if i == '1':\n length = len(ans)\n for x in range(length):\n ans.append((1 << count) + ans[x])\n count += 1\n return ans[::-1]", "def printsubsets(N):\n arr = []\n for i in range(N, -1, -1):\n if N & i == i:\n arr.append(i)\n return arr", "def printsubsets(N):\n pass\n arr = []\n for i in range(N + 1):\n temp = i & N\n if temp not in arr:\n arr.append(temp)\n arr.sort(reverse=True)\n return arr", "def printsubsets(N):\n n = N\n AA = []\n for i in range(n + 1):\n if n & i == i:\n AA.append(i)\n return AA[::-1]", "def printsubsets(N):\n a = N\n c = []\n while a >= 0:\n b = a & N\n if a == b:\n c.append(a)\n a = a - 1\n return c\n pass"], "starter_code": "def printsubsets (N):\n", "input_output": {"inputs": ["N = 5", "N = 9"], "outputs": ["5 4 1 0", "9 8 1 0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Binary Representation", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/print-all-bitwise-subsets-of-a-number-n3301/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(K), where K is the number of bitwise subsets of N.", "entry_point": "printsubsets", "task_id": "TACO_lite/81", "example": [[], []]} +{"requirement": "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.\n\n\nFor example, with A = \"abcd\" and B = \"cdabcdab\". \n\n\nReturn 3, because by repeating A three times (\u201cabcdabcdabcd\u201d), B is a substring of it; and B is not a substring of A repeated two times (\"abcdabcd\").\n\n\nNote:\nThe length of A and B will be between 1 and 10000.", "solutions": ["def repeatedstringmatch(A, B):\n if not set(B).issubset(set(A)):\n return -1\n max_rep = len(B) // len(A) + 3\n A_new = A\n for i in range(1, max_rep):\n if B in A_new:\n return i\n A_new += A\n return -1", "def repeatedstringmatch(A, B):\n times = 1\n tmp = A\n if not set(B).issubset(set(A)):\n return -1\n maxTime = math.ceil(len(B) / len(A))\n while True:\n if B in A:\n break\n elif times <= maxTime:\n A += tmp\n times += 1\n else:\n return -1\n return times", "def repeatedstringmatch(A, B):\n\n def check(index):\n return all((A[(i + index) % len(A)] == c for (i, c) in enumerate(B)))\n (M, p) = (10 ** 9 + 7, 113)\n p_inv = pow(p, M - 2, M)\n q = (len(B) + len(A) - 1) // len(A)\n (b_hash, power) = (0, 1)\n for c in B:\n b_hash += power * ord(c)\n b_hash %= M\n power = power * p % M\n (a_hash, power) = (0, 1)\n for i in range(len(B)):\n a_hash += power * ord(A[i % len(A)])\n a_hash %= M\n power = power * p % M\n if a_hash == b_hash and check(0):\n return q\n power = power * p_inv % M\n for i in range(len(B), (q + 1) * len(A)):\n a_hash = (a_hash - ord(A[(i - len(B)) % len(A)])) * p_inv\n a_hash += power * ord(A[i % len(A)])\n a_hash %= M\n if a_hash == b_hash and check(i - len(B) + 1):\n return q if i < q * len(A) else q + 1\n return -1", "def repeatedstringmatch1(A, B):\n\n def check(index):\n return all((A[(i + index) % len(A)] == c for (i, c) in enumerate(B)))\n (M, p) = (10 ** 9 + 7, 113)\n p_inv = pow(p, M - 2, M)\n q = (len(B) + len(A) - 1) // len(A)\n (b_hash, power) = (0, 1)\n for c in B:\n b_hash += power * ord(c)\n b_hash %= M\n power = power * p % M\n (a_hash, power) = (0, 1)\n for i in range(len(B)):\n a_hash += power * ord(A[i % len(A)])\n a_hash %= M\n power = power * p % M\n if a_hash == b_hash and check(0):\n return q\n power = power * p_inv % M\n for i in range(len(B), (q + 1) * len(A)):\n a_hash = (a_hash - ord(A[(i - len(B)) % len(A)])) * p_inv\n a_hash += power * ord(A[i % len(A)])\n a_hash %= M\n if a_hash == b_hash and check(i - len(B) + 1):\n return q if i < q * len(A) else q + 1\n return -1\n\ndef repeatedstringmatch(A, B):\n\n def get_fail(s):\n f = [0] * (len(s) + 1)\n for i in range(1, len(s)):\n j = f[i]\n while j and s[i] != s[j]:\n j = f[j]\n if s[i] == s[j]:\n j += 1\n f[i + 1] = j\n return f\n f = get_fail(B)\n j = 0\n vis = {0}\n cnt = 1\n while True:\n for i in range(len(A)):\n while j and A[i] != B[j]:\n j = f[j]\n if A[i] == B[j]:\n j += 1\n if j == len(B):\n return cnt\n if j in vis:\n return -1\n vis.add(j)\n cnt += 1\n return -1", "def repeatedstringmatch(A, B):\n k = int(len(B) / len(A))\n m = ''\n h = A + A[0]\n for i in range(len(B) - 1):\n if B[i:i + 2] not in h:\n return -1\n for i in range(k):\n m += A\n while B not in m:\n m += A\n k += 1\n if k > 100:\n return -1\n return k", "def repeatedstringmatch(A, B):\n if set(list(B)) > set(list(A)):\n return -1\n l_b = len(B)\n pointer_b = 0\n l_a = len(A)\n pointer_a = 0\n L = []\n while pointer_a < l_a:\n if A[pointer_a] == B[pointer_b]:\n L.append(pointer_a)\n pointer_a += 1\n if L == []:\n return -1\n for pointer_a in L:\n times = 1\n while pointer_b < l_b:\n if pointer_a == l_a:\n pointer_a = 0\n times += 1\n if B[pointer_b] == A[pointer_a]:\n pointer_b += 1\n pointer_a += 1\n continue\n else:\n break\n if pointer_b == l_b:\n return times\n else:\n pointer_b = 0\n return -1", "def repeatedstringmatch(A, B):\n if A == B or B in A:\n return 1\n if A not in B:\n if B not in A + A:\n return -1\n else:\n return 2\n else:\n (count, i) = (1, B.index(A))\n if i != 0:\n if B[:i] != A[-i:]:\n return -1\n else:\n count = 2\n while i + 2 * len(A) < len(B) and A == B[i + len(A):i + 2 * len(A)]:\n count += 1\n i = B.index(A, i + len(A))\n if i == len(B) - len(A):\n return count\n else:\n if B[i + len(A):] != A[:len(B) - i - len(A)]:\n return -1\n return count + 1", "def repeatedstringmatch(A, B):\n for i in range(len(A)):\n if A[i] == B[0]:\n divisible = True if (len(B) - (len(A) - i)) % len(A) == 0 else False\n time = 1 + (len(B) - (len(A) - i)) // len(A) if divisible else 1 + (len(B) - (len(A) - i)) // len(A) + 1\n repeatA = A * time\n if repeatA[i:i + len(B)] == B:\n return time\n return -1", "def repeatedstringmatch(a, b):\n if a is None or len(a) == 0 or b is None or (len(b) == 0):\n return -1\n if a == b:\n return 1\n kmp = [0 for _ in range(len(b) + 1)]\n j = 0\n for i in range(1, len(b)):\n if b[j] == b[i]:\n j += 1\n kmp[i] = j\n elif j == 0:\n i += 1\n else:\n j = kmp[j - 1]\n j = 0\n for i in range(len(a)):\n while j < len(b) and a[(i + j) % len(a)] == b[j]:\n j += 1\n if j == len(b):\n return -(-(i + j) // len(a))\n j = kmp[j - 1]\n return -1", "def repeatedstringmatch(text, pattern):\n (n, m) = (len(text), len(pattern))\n (base, prime) = (256, 257)\n bpow = base ** (m - 1) % prime\n\n def check(i):\n for j in range(m):\n if text[(i + j) % n] != pattern[j]:\n return False\n return True\n\n def compute_hash(s):\n (n, h) = (len(s), 0)\n for i in range(m):\n c = s[i % n]\n h = (h * base + ord(c)) % prime\n return h\n\n def update_hash(h, old, new):\n dh = ord(old) * bpow % prime\n h = (h - dh + prime) % prime\n h = (h * base + ord(new)) % prime\n return h\n p = compute_hash(pattern)\n t = compute_hash(text)\n for i in range(n):\n if t == p and check(i):\n return 1 + (i + m - 1) // n\n t = update_hash(t, text[i], text[(i + m) % n])\n return -1"], "starter_code": "def repeatedstringmatch(a: str, b: str) -> int:\n", "input_output": {"fn_name": "repeatedStringMatch", "inputs": [["\"abcd\"", "\"cdabcdab\""]], "outputs": [-1]}, "difficulty": "EASY", "raw_tags": ["String Matching", "String"], "name": null, "source": "leetcode", "tags": ["String algorithms"], "skill_types": [], "url": "https://leetcode.com/problems/repeated-string-match/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "repeatedstringmatch", "task_id": "TACO_lite/120", "example": [[["abcd", "cdabcdab"]], ["3"]]} +{"requirement": "Given an array A of size N of integers. Your task is to find the sum of minimum and maximum element in the array.\nExample 1:\nInput:\nN = 5\nA[] = {-2, 1, -4, 5, 3}\nOutput: 1\nExplanation: min = -4, max = 5. Sum = -4 + 5 = 1\n \nExample 2:\nInput:\nN = 4\nA[] = {1, 3, 4, 1}\nOutput: 5\nExplanation: min = 1, max = 4. Sum = 1 + 4 = 5\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function findSum() which takes the array A[] and its size N as inputs and returns the summation of minimum and maximum element of the array.\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= N <= 10^{5}\n-10^{9} <= A_{i} <= 10^{9}", "solutions": ["def findsum(A, N):\n A.sort()\n return A[0] + A[len(A) - 1]", "def findsum(A, N):\n return max(A) + min(A)", "def findsum(A, N):\n maxval = A[0]\n minval = maxval\n for i in range(1, N):\n if A[i] > maxval:\n maxval = A[i]\n continue\n if A[i] < minval:\n minval = A[i]\n continue\n return minval + maxval", "def findsum(A, N):\n self.A = A\n self.N = N\n max_val = max(A)\n min_val = min(A)\n return max_val + min_val", "def findsum(A, N):\n A.sort()\n sum = A[0] + A[N - 1]\n return sum", "def findsum(A, N):\n a = min(A)\n b = max(A)\n return a + b", "def findsum(arr, arr_size):\n max = 0\n min = 0\n i = 0\n if arr_size % 2 == 1:\n max = arr[0]\n min = arr[0]\n i = 1\n else:\n if arr[0] < arr[1]:\n max = arr[1]\n min = arr[0]\n else:\n max = arr[0]\n min = arr[1]\n i = 2\n while i < arr_size:\n if arr[i] < arr[i + 1]:\n if arr[i] < min:\n min = arr[i]\n if arr[i + 1] > max:\n max = arr[i + 1]\n else:\n if arr[i] > max:\n max = arr[i]\n if arr[i + 1] < min:\n min = arr[i + 1]\n i = i + 2\n return max + min", "def findsum(A, N):\n a = A[0]\n b = A[0]\n for i in range(N):\n if a > A[i]:\n a = A[i]\n if b < A[i]:\n b = A[i]\n return a + b", "def findsum(A, N):\n d = min(A)\n m = max(A)\n result = d + m\n return result", "def findsum(A, N):\n min = 99999999\n max = -999999\n for i in range(0, N):\n if A[i] < min:\n min = A[i]\n if A[i] > max:\n max = A[i]\n return max + min", "def findsum(A, N):\n min_a = 10 ** 9\n max_b = -10 ** 9\n for i in range(len(A)):\n if a[i] > max_b:\n max_b = a[i]\n if a[i] < min_a:\n min_a = a[i]\n return min_a + max_b", "def findsum(A, N):\n largest_element = A[0]\n for i in range(N):\n if A[i] > largest_element:\n largest_element = A[i]\n smallest_element = A[0]\n for i in range(N):\n if A[i] < smallest_element:\n smallest_element = A[i]\n return largest_element + smallest_element", "def findsum(A, N):\n maxx = -10000000\n minn = 10000000\n for i in range(N):\n if A[i] > maxx:\n maxx = A[i]\n if A[i] < minn:\n minn = A[i]\n return maxx + minn", "def findsum(A, N):\n Amax = Amin = A[0]\n for i in range(1, N):\n if A[i] > Amax:\n Amax = A[i]\n elif A[i] < Amin:\n Amin = A[i]\n return Amax + Amin", "def findsum(A, N):\n ma = -999999999\n mi = 9999999999\n for i in range(N):\n if A[i] < mi:\n mi = A[i]\n if ma < A[i]:\n ma = A[i]\n return ma + mi", "def findsum(arr, n):\n maxi = arr[0]\n mini = arr[0]\n for i in range(1, n):\n if arr[i] > maxi:\n maxi = arr[i]\n if arr[i] < mini:\n mini = arr[i]\n return maxi + mini", "def findsum(A, N):\n min_elem = A[0]\n max_elem = A[0]\n for i in range(1, N):\n if A[i] < min_elem:\n min_elem = A[i]\n elif A[i] > max_elem:\n max_elem = A[i]\n return min_elem + max_elem", "def findsum(A, N):\n min = A[0]\n max = A[0]\n for x in A:\n if x < min:\n min = x\n elif x > max:\n max = x\n return max + min", "def findsum(A, N):\n maxi = A[0]\n mini = A[0]\n for i in range(N):\n if A[i] >= maxi:\n maxi = A[i]\n if A[i] <= mini:\n mini = A[i]\n return mini + maxi", "def findsum(A, N):\n max = A[0]\n min = A[0]\n for i in A:\n if i > max:\n max = i\n for i in A:\n if i < min:\n min = i\n return max + min", "def findsum(A, N):\n index = 0\n minimum = A[0]\n maximum = A[0]\n while index < N:\n if minimum > A[index]:\n minimum = A[index]\n if maximum < A[index]:\n maximum = A[index]\n index += 1\n return maximum + minimum", "def findsum(arr, N):\n arr.sort()\n return arr[0] + arr[N - 1]", "def findsum(arr, N):\n return max(arr) + min(arr)", "def findsum(A, N):\n min_num = max_num = A[0]\n for i in range(1, N):\n if A[i] < min_num:\n min_num = A[i]\n elif A[i] > max_num:\n max_num = A[i]\n return min_num + max_num", "def findsum(A, N):\n newarray = sorted(A)\n firstelement = newarray[0]\n lastelement = newarray[-1]\n sumofelement = firstelement + lastelement\n return sumofelement", "def findsum(A, N):\n max_a = max(A)\n min_a = min(A)\n sum_a = max_a + min_a\n return sum_a", "def findsum(A, N):\n max1 = max(A)\n min1 = min(A)\n return max1 + min1", "def findsum(A, N):\n min_val = max_val = A[0]\n for num in A:\n if num < min_val:\n min_val = num\n elif num > max_val:\n max_val = num\n return min_val + max_val", "def findsum(A, N):\n\n def maxMin(A):\n (max, min) = (float('-inf'), float('inf'))\n for i in A:\n if i > max:\n max = i\n if i < min:\n min = i\n return [min, max]\n return sum(maxMin(A))", "import numpy as np\n\ndef findsum(A, N):\n Ar = np.array(A)\n Ar.sort()\n return Ar[0] + Ar[N - 1]", "def findsum(A, N):\n min_val = float('inf')\n max_val = float('-inf')\n for i in range(N):\n if A[i] < min_val:\n min_val = A[i]\n if A[i] > max_val:\n max_val = A[i]\n sum_val = min_val + max_val\n return sum_val", "def findsum(A, N):\n x = max(A)\n y = min(A)\n return x + y", "def findsum(A, N):\n minimum = A[0]\n maximum = A[0]\n sum = 0\n for x in range(0, len(A), +1):\n if A[x] < minimum:\n minimum = A[x]\n elif A[x] > maximum:\n maximum = A[x]\n sum = maximum + minimum\n return sum", "def findsum(A, N):\n min = A[0]\n max = A[0]\n sum = 0\n for x in range(0, len(A), +1):\n if A[x] < min:\n min = A[x]\n elif A[x] > max:\n max = A[x]\n sum = min + max\n return sum", "def findsum(A, N):\n maximum = max(A)\n minimum = min(A)\n Sum = minimum + maximum\n return Sum", "def findsum(A, N):\n m = min(A)\n n = max(A)\n return m + n", "def findsum(A, N):\n s = sorted(A)\n low = s[0]\n high = s[n - 1]\n result = low + high\n return result", "def findsum(A, N):\n c = max(a)\n d = min(a)\n s = c + d\n return s", "def findsum(A, N):\n maxele = -float('inf')\n for i in range(N):\n if maxele < A[i]:\n maxele = A[i]\n minele = float('inf')\n for i in range(N):\n if minele > A[i]:\n minele = A[i]\n return maxele + minele", "def findsum(A, N):\n min = A[0]\n max = A[0]\n for i in range(0, len(A)):\n if A[i] < min:\n min = A[i]\n if A[i] > max:\n max = A[i]\n sum = max + min\n return sum", "def findsum(A, N):\n if N == 0:\n return Null\n else:\n return min(A) + max(A)", "def findsum(A, N):\n min_elem = float('inf')\n max_elem = float('-inf')\n for i in range(N):\n if A[i] < min_elem:\n min_elem = A[i]\n if A[i] > max_elem:\n max_elem = A[i]\n return min_elem + max_elem", "def findsum(A, N):\n import math\n min = math.inf\n max = -math.inf\n for i in range(0, len(A)):\n if A[i] < min:\n min = A[i]\n if A[i] > max:\n max = A[i]\n return max + min", "def findsum(A, N):\n s = A[0]\n l = A[0]\n for i in range(N):\n if s > A[i]:\n s = A[i]\n if l < A[i]:\n l = A[i]\n return l + s", "def findsum(A, N):\n if N == 1:\n sum = A[0] + A[0]\n return sum\n else:\n (min, max) = (A[0], A[0])\n for i in range(N):\n if A[i] < min:\n min = A[i]\n elif A[i] > max:\n max = A[i]\n sum = min + max\n return sum", "def findsum(a, n):\n e = min(a)\n b = max(a)\n return e + b", "def findsum(A, N):\n mini = min(A)\n maxi = max(A)\n return mini + maxi", "def findsum(A, N):\n l = min(A)\n g = max(A)\n s = 0\n s = int(l + g)\n return s", "def findsum(A, N):\n Z = max(A)\n X = min(A)\n sum = Z + X\n return sum", "def findsum(A, N):\n mx = max(A)\n mn = min(A)\n s = mx + mn\n return s", "def findsum(A, N):\n l = list(A)\n mi = min(l)\n ma = max(l)\n sum = int(mi) + int(ma)\n return sum", "def findsum(A, N):\n if N == 0:\n return 0\n if N == 1:\n return 2 * A[0]\n A.sort()\n return A[0] + A[-1]", "def findsum(A, N):\n min_A = min(A)\n max_A = max(A)\n sum_mm = max_A + min_A\n return sum_mm", "def findsum(A, N):\n x = min(A)\n Y = max(A)\n return x + Y", "def findsum(A, N):\n N = len(A)\n if N % 2 == 0:\n mx = max(A[0], A[1])\n mn = min(A[0], A[1])\n i = 2\n else:\n mx = mn = A[0]\n i = 1\n while i < N - 1:\n if A[i] < A[i + 1]:\n mx = max(mx, A[i + 1])\n mn = min(mn, A[i])\n else:\n mx = max(mx, A[i])\n mn = min(mn, A[i + 1])\n i += 2\n return mx + mn", "def findsum(A, N):\n maxi = -99999\n mini = 99999\n for i in range(N):\n maxi = max(A[i], maxi)\n mini = min(A[i], mini)\n sum = maxi + mini\n return sum", "def findsum(A, N):\n maxi = float('-inf')\n mini = float('inf')\n for i in A:\n if i > maxi:\n maxi = i\n if i < mini:\n mini = i\n return maxi + mini", "def findsum(A, N):\n A.sort()\n mini = A[0]\n maxi = A[-1]\n return mini + maxi", "def findsum(A, N):\n minn = 1000000\n maxx = -1000000\n for i in A:\n if i > maxx:\n maxx = i\n if i < minn:\n minn = i\n return minn + maxx", "def findsum(A, N):\n l = max(A)\n b = min(A)\n s = l + b\n return s"], "starter_code": "def findsum(A,N):\n", "input_output": {"inputs": ["N = 5\r\nA[] = {-2, 1, -4, 5, 3}", "N = 4\r\nA[] = {1, 3, 4, 1}"], "outputs": ["1", "5"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Greedy"], "name": null, "source": "geeksforgeeks", "tags": ["Greedy algorithms"], "skill_types": ["Greedy algorithms"], "url": "https://practice.geeksforgeeks.org/problems/max-min/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "findsum", "task_id": "TACO_lite/11", "example": [[[5, [-2, 1, -4, 5, 3]], [4, [1, 3, 4, 1]]], [null, null]]} +{"requirement": "Write a method named `getExponent(n,p)` that returns the largest integer exponent `x` such that p^(x) evenly divides `n`. if `p<=1` the method should return `null`/`None` (throw an `ArgumentOutOfRange` exception in C#).", "solutions": ["def get_exponent(n, p):\n if p > 1:\n x = 0\n while not n % p:\n x += 1\n n //= p\n return x", "def get_exponent(n, p, i=0):\n if p <= 1:\n return None\n return get_exponent(n / p, p, i + 1) if n / p == n // p else i", "from itertools import count\n\ndef get_exponent(n, p):\n if p > 1:\n for res in count():\n (n, r) = divmod(n, p)\n if r:\n return res", "def get_exponent(n, p):\n return next(iter((i for i in range(int(abs(n) ** (1 / p)), 0, -1) if n / p ** i % 1 == 0)), 0) if p > 1 else None", "def get_exponent(n, p):\n if p <= 1:\n return None\n (x, e) = (0, 1)\n while n % e == 0:\n x += 1\n e *= p\n return x - 1", "def get_exponent(n, p):\n i = 1\n if p <= 1:\n return None\n while n % p ** i == 0:\n i += 1\n return i - 1", "def get_exponent(n, p):\n if p <= 1:\n return\n return max([i for i in range(1, int(abs(n) ** 0.5)) if n % p ** i == 0], default=0)", "def get_exponent(n, p):\n if int(p) <= 1:\n return None\n else:\n x = 1\n while n % p ** x == 0:\n x += 1\n return x - 1", "def get_exponent(n, p):\n r = 0\n while n % p ** r == 0 and p > 1:\n r += 1\n if r > 0:\n return r - 1", "from math import log\n\ndef get_exponent(n, p):\n if p <= 1:\n return None\n (l, i) = (None, 0)\n while p ** i <= abs(n):\n if n % p ** i == 0:\n l = i\n i += 1\n return l"], "starter_code": "def get_exponent(n, p):\n", "input_output": {"fn_name": "get_exponent", "inputs": [[27, 3]], "outputs": [[3]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/59b139d69c56e8939700009d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "get_exponent", "task_id": "TACO_lite/37", "example": [[], []]} +{"requirement": "## Task\n\nGiven `n` representing the number of floors build a beautiful multi-million dollar mansions like the ones in the example below:\n\n```\n /\\\n / \\\n / \\\n /______\\ number of floors 3\n | |\n | |\n |______|\n\n /\\\n / \\\n /____\\\n | | 2 floors\n |____|\n\n /\\\n /__\\ 1 floor\n |__|\n```\n\n**Note:** whitespace should be preserved on both sides of the roof. Number of floors will go up to 30. There will be no tests with invalid input.\n\nIf you manage to complete it, you can try a harder version [here](https://www.codewars.com/kata/58360d112fb0ba255300008b).\n\nGood luck!", "solutions": ["def my_crib(n):\n roof = '\\n'.join(('%s/%s\\\\%s' % (' ' * (n - i), ' ' * i * 2, ' ' * (n - i)) for i in range(n)))\n ceiling = '\\n/%s\\\\\\n' % ('_' * (n * 2))\n walls = '|%s|\\n' % (' ' * (n * 2)) * (n - 1)\n floor = '|%s|' % ('_' * (n * 2))\n return roof + ceiling + walls + floor", "def my_crib(n):\n roof = [('/' + ' ' * k + '\\\\').center(2 * n + 2) for k in range(0, 2 * n, 2)]\n ceiling = ['/' + '_' * 2 * n + '\\\\']\n walls = ['|' + ' ' * 2 * n + '|'] * (n - 1)\n floor = ['|' + '_' * 2 * n + '|']\n return '\\n'.join(roof + ceiling + walls + floor)", "def my_crib(n):\n return '\\n'.join([' ' * (n - i) + '/' + ' ' * 2 * i + '\\\\' + ' ' * (n - i) for i in range(n)] + ['/' + '_' * 2 * n + '\\\\'] + ['|' + ' ' * 2 * n + '|'] * (n - 1) + ['|' + '_' * 2 * n + '|'])", "def my_crib(n):\n (l, res) = (n + 1 << 1, [])\n res.extend(('/' + ' ' * (2 * i) + '\\\\' for i in range(n)))\n res.append('/' + '_' * (2 * n) + '\\\\')\n res.extend(('|' + ' ' * (l - 2) + '|' for _ in range(n - 1)))\n res.append('|' + '_' * (l - 2) + '|')\n return '\\n'.join((s.center(l) for s in res))", "def my_crib(n):\n crib = [f'{mult(n - i)}/{mult(i * 2)}\\\\{mult(n - i)}' for i in range(n)]\n crib.append(f\"/{mult(n * 2, '_')}\\\\\")\n crib.extend((f'|{mult(n * 2)}|' for _ in range(n - 1)))\n crib.append(f\"|{mult(n * 2, '_')}|\")\n return '\\n'.join(crib)\n\ndef mult(n, char=' '):\n return char * n", "import itertools\n\ndef my_crib(n):\n\n def format(chars, fill_width):\n return '{chars[0]}{chars[2]:{chars[1]}>{width}}'.format(chars=chars, width=fill_width + 1).center(2 * n + 2)\n return '\\n'.join(itertools.chain((format('/ \\\\', 2 * i) for i in range(n)), (format('/_\\\\', 2 * n),), (format('| |', 2 * n) for _ in range(n - 1)), (format('|_|', 2 * n),)))", "my_crib = lambda n: '\\n'.join([('/' + [' ', '_'][i == n] * (i * 2) + '\\\\').center(n * 2 + 2, ' ') for i in range(n + 1)]) + '\\n' + '\\n'.join(['|' + [' ', '_'][i == n - 1] * (n * 2) + '|' for i in range(n)])", "def my_crib(n):\n roof = '\\n'.join(('{0}/{1}\\\\{0}'.format(' ' * (n - i), ' _'[n == i] * i * 2) for i in range(n + 1)))\n x = lambda a: '\\n|' + a * n * 2 + '|'\n return roof + x(' ') * (n - 1) + x('_')"], "starter_code": "def my_crib(n):\n", "input_output": {"fn_name": "my_crib", "inputs": [[1], [2], [3]], "outputs": [[" /\\ \n/__\\\n|__|"], [" /\\ \n / \\ \n/____\\\n| |\n|____|"], [" /\\ \n / \\ \n / \\ \n/______\\\n| |\n| |\n|______|"]]}, "difficulty": "EASY", "raw_tags": ["ASCII Art", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5834a44e44ff289b5a000075", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "my_crib", "task_id": "TACO_lite/51", "example": [[], []]} +{"requirement": "Evaluate the value of an arithmetic expression in Reverse Polish Notation.\n\nValid operators are +, -, *, /. Each operand may be an integer or another expression.\n\nNote:\n\n\n Division between two integers should truncate toward zero.\n The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't\u00a0be any\u00a0divide\u00a0by zero operation.\n\n\nExample 1:\n\n\nInput: [\"2\", \"1\", \"+\", \"3\", \"*\"]\nOutput: 9\nExplanation: ((2 + 1) * 3) = 9\n\n\nExample 2:\n\n\nInput: [\"4\", \"13\", \"5\", \"/\", \"+\"]\nOutput: 6\nExplanation: (4 + (13 / 5)) = 6\n\n\nExample 3:\n\n\nInput: [\"10\", \"6\", \"9\", \"3\", \"+\", \"-11\", \"*\", \"/\", \"*\", \"17\", \"+\", \"5\", \"+\"]\nOutput: 22\nExplanation: \n ((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22", "solutions": ["def evalrpn(tokens):\n s = []\n for token in tokens:\n if token == '+':\n a = int(s.pop())\n b = int(s.pop())\n s.append(a + b)\n elif token == '/':\n a = int(s.pop())\n b = int(s.pop())\n s.append(b / a)\n elif token == '*':\n a = int(s.pop())\n b = int(s.pop())\n s.append(a * b)\n elif token == '-':\n a = int(s.pop())\n b = int(s.pop())\n s.append(b - a)\n else:\n s.append(token)\n if len(s) is not 1:\n return False\n else:\n return int(s.pop())"], "starter_code": "def evalrpn(tokens: List[str]) -> int:\n", "input_output": {"fn_name": "evalRPN", "inputs": [[["\"2\"", "\"1\""]]], "outputs": [0]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Stack", "Math", "Array"], "name": null, "source": "leetcode", "tags": ["Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/evaluate-reverse-polish-notation/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "evalrpn", "task_id": "TACO_lite/26", "example": [[[["2", "1", "+", "3", "*"]], [["4", "13", "5", "/", "+"]], [["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]]], ["9", "6", "22"]]} +{"requirement": "Given two numbers, A and B. Find the number of common divisors of A and B. \n \nExample 1:\n\u00c3\u00a2\u00e2\u0082\u00ac\u00e2\u0080\u00b9Input : A = 2 and B = 4\nOutput : 2\nExplanation:\nThere are only two common divisor of 2 and 4.\nThat is 1 and 2.\n\u00c3\u00a2\u00e2\u0082\u00ac\u00e2\u0080\u00b9Example 2:\nInput : A = 3 and B = 5 \nOutput : 1\n \nYour Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function common_divisor() that takes an integer A, another integer B, and return the number of the common divisor of A and B. The driver code takes care of the printing.\nExpected Time Complexity: O(SQRT(min(A,B))).\nExpected Auxiliary Space: O(1).\n \nConstraints:\n1 \u2264 A, B \u2264 10^{7}", "solutions": ["def common_divisor(n, m):\n c = 0\n for i in range(1, m + 1):\n if n % i == 0 and m % i == 0:\n c += 1\n return c", "def common_divisor(n, m):\n x = min(n, m)\n lis = [i for i in range(1, x + 1) if n % i == 0 and m % i == 0]\n return len(lis)", "def common_divisor(n, m):\n count = 0\n if n > m:\n a = n\n else:\n a = m\n for i in range(1, a + 1):\n if n % i == 0 and m % i == 0:\n count += 1\n return count", "def common_divisor(n, m):\n import math\n ans = 0\n gcd = math.gcd(n, m)\n for i in range(1, gcd + 1):\n if (n % i == 0) & (m % i == 0):\n ans += 1\n return ans", "import math\n\ndef common_divisor(n, m):\n (m, n) = (min(m, n), max(m, n))\n result = 0\n i = 1\n while i <= math.sqrt(m):\n if n % i == 0 and m % i == 0:\n result += 1\n if n % (m // i) == 0 and m % (m // i) == 0 and (i != m // i):\n result += 1\n i += 1\n return result", "def gcd(n, m):\n if m > n:\n temp = n\n n = m\n m = temp\n if n == 0:\n return m\n if m == 0:\n return n\n return gcd(m, n % m)\n\ndef common_divisor(n, m):\n x = gcd(n, m)\n sm = 0\n for i in range(1, x + 1):\n if x % i == 0:\n sm += 1\n return sm", "from math import sqrt\n\ndef common_divisor(n, m):\n\n def gcd(a, b):\n if a == 0:\n return b\n return gcd(b % a, a)\n c = 0\n n = gcd(n, m)\n x = int(sqrt(n))\n for i in range(1, x + 1):\n if n % i == 0:\n if n / i == i:\n c += 1\n else:\n c += 2\n return c", "def common_divisor(n, m):\n count = 0\n s = min(m, n) + 1\n for i in range(1, s):\n if n % i == 0 and m % i == 0:\n count = count + 1\n return count", "def greatest_divisor(n, m):\n if m == 0:\n return n\n return greatest_divisor(m, n % m)\n\ndef common_divisor(n, m):\n c = 0\n g_divisior = greatest_divisor(n, m)\n r = int(g_divisior ** (1 / 2))\n for i in range(1, r + 1):\n if g_divisior % i == 0:\n c += 2\n if i * i == g_divisior:\n c -= 1\n return c", "def common_divisor(n, m):\n l = []\n k = []\n ans = []\n for i in range(1, min(n, m) + 1):\n if n % i == 0 and m % i == 0:\n l.append(i)\n return len(l)", "def common_divisor(n, m):\n result = 0\n if m < n:\n d = m\n else:\n d = n\n for i in range(1, d + 1):\n if n % i == 0 and m % i == 0:\n result += 1\n return result", "def common_divisor(n, m):\n c = 0\n if n < m:\n a = n\n else:\n a = m\n for i in range(1, a + 1):\n if n % i == 0 and m % i == 0:\n c += 1\n else:\n pass\n return c"], "starter_code": "def common_divisor (n, m) :\n", "input_output": {"fn_name": "common_divisor", "inputs": ["A = 2 and B = 4", "A = 3 and B = 5"], "outputs": ["2", "1"]}, "difficulty": "EASY", "raw_tags": ["number-theory"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/common-divisor0847/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(SQRT(min(A,B))).", "entry_point": "common_divisor", "task_id": "TACO_lite/109", "example": [[[2, 4], [3, 5]], ["2", "1"]]} +{"requirement": "Given an array A of integers, for each integer A[i] we need to choose either\u00a0x = -K\u00a0or x = K, and add x to A[i] (only once).\nAfter this process, we have some array B.\nReturn the smallest possible difference between the maximum value of B\u00a0and the minimum value of B.\n\u00a0\n\n\n\nExample 1:\nInput: A = [1], K = 0\nOutput: 0\nExplanation: B = [1]\n\n\nExample 2:\nInput: A = [0,10], K = 2\nOutput: 6\nExplanation: B = [2,8]\n\n\nExample 3:\nInput: A = [1,3,6], K = 3\nOutput: 3\nExplanation: B = [4,6,3]\n\n\u00a0\nNote:\n\n1 <= A.length <= 10000\n0 <= A[i] <= 10000\n0 <= K <= 10000", "solutions": ["def smallestrangeii(A: List[int], K: int) -> int:\n if not A:\n return 0\n nums = sorted([num + K for num in set(A)], reverse=True)\n max_num = nums[0]\n min_num = nums[-1]\n changed_max = max_num - 2 * K\n res = max_num - min_num\n for i in range(len(nums) - 1):\n changed = nums[i] - 2 * K\n max_num = max(nums[i + 1], changed, changed_max)\n min_num = min(min_num, changed)\n res = min(res, max_num - min_num)\n return res", "def smallestrangeii(A: List[int], K: int) -> int:\n A.sort()\n minA = A[0]\n maxA = A[-1]\n smallest = maxA - minA\n for i in range(len(A) - 1):\n a = A[i]\n b = A[i + 1]\n smallest = min(smallest, max(maxA - K, a + K) - min(minA + K, b - K))\n return smallest", "def smallestrangeii(A: List[int], K: int) -> int:\n A.sort()\n (mi, ma) = (A[0], A[-1])\n ans = ma - mi\n for i in range(len(A) - 1):\n (a, b) = (A[i], A[i + 1])\n ans = min(ans, max(ma - K, a + K) - min(mi + K, b - K))\n return ans", "def smallestrangeii(A: List[int], K: int) -> int:\n A.sort()\n diff = A[-1] - A[0]\n for i in range(len(A) - 1):\n lower = min(A[0] + 2 * K, A[i + 1])\n upper = max(A[-1], A[i] + 2 * K)\n diff = min(diff, abs(upper - lower))\n return diff", "def smallestrangeii(A: List[int], K: int) -> int:\n if K == 0:\n return max(A) - min(A)\n if len(A) == 1:\n return 0\n if max(A) - min(A) <= K:\n return max(A) - min(A)\n else:\n A = sorted(A)\n dp = [A[-1] - A[0]]\n (n1, n2) = (A[-1] - K, A[0] + K)\n for i in range(len(A) - 1):\n dp += [max(A[i] + K, A[-1] - K) - min(A[0] + K, A[i + 1] - K)]\n return min(dp)", "def smallestrangeii(A: List[int], K: int) -> int:\n if len(A) == 1:\n return 0\n A.sort()\n i = 0\n j = len(A) - 1\n min_diff = A[-1] - A[0]\n bottom = A[0]\n peak = A[-1]\n for idx in range(len(A) - 1):\n (current, _next) = (A[idx], A[idx + 1])\n bottom = min(A[0] + K, _next - K)\n peak = max(A[-1] - K, current + K)\n min_diff = min(min_diff, peak - bottom)\n return min_diff", "def smallestrangeii(A: List[int], K: int) -> int:\n A.sort()\n res = A[-1] - A[0]\n for i in range(len(A) - 1):\n res = min(res, max(A[i] + K, A[-1] - K) - min(A[0] + K, A[i + 1] - K))\n return res", "def smallestrangeii(A: List[int], K: int) -> int:\n if not A:\n return 0\n A.sort()\n x = A[0]\n y = A[-1]\n res = y - x\n for i in range(len(A)):\n A[i] += 2 * K\n x = min(A[0], A[(i + 1) % len(A)])\n y = max(A[i], y)\n res = min(res, y - x)\n return res", "def smallestrangeii(A: List[int], k: int) -> int:\n A.sort()\n n = len(A)\n res = A[n - 1] - A[0]\n for i in range(n - 1):\n mn = min(A[i + 1] - k, A[0] + k)\n mx = max(A[i] + k, A[n - 1] - k)\n res = min(res, mx - mn)\n return res", "def smallestrangeii(A: List[int], K: int) -> int:\n A.sort()\n min_diff = A[-1] - A[0]\n for i in range(len(A) - 1):\n v_min = min(A[0] + K, A[i + 1] - K)\n v_max = max(A[i] + K, A[-1] - K)\n min_diff = min(min_diff, v_max - v_min)\n return min_diff", "def smallestrangeii(arr: List[int], k: int) -> int:\n arr.sort()\n best = arr[-1] - arr[0]\n for i in range(1, len(arr)):\n current_max = max(arr[-1] - k, arr[i - 1] + k)\n current_min = min(arr[0] + k, arr[i] - k)\n best = min(best, current_max - current_min)\n return best", "def smallestrangeii(A: List[int], k: int) -> int:\n A.sort()\n (res, n) = (A[-1] - A[0], len(A))\n temp = [max(A[n - 1] - k, A[n - i - 2] + k) - min(A[0] + k, A[n - i - 1] - k) for i in range(n)]\n return min(res, min(temp))", "def smallestrangeii(A: List[int], K: int) -> int:\n N = len(A)\n if N == 1:\n return 0\n A.sort()\n diff = A[-1] - A[0]\n for i in range(N - 1):\n maxi = max(A[i] + K, A[N - 1] - K)\n mini = min(A[0] + K, A[i + 1] - K)\n diff = min(diff, maxi - mini)\n return diff"], "starter_code": "def smallestrangeii(A: List[int], K: int) -> int:\n", "input_output": {"fn_name": "smallestRangeII", "inputs": [[[1], 0]], "outputs": [0]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Math", "Sorting", "Greedy", "Array"], "name": null, "source": "leetcode", "tags": ["Sorting", "Data structures", "Mathematics", "Greedy algorithms"], "skill_types": ["Sorting", "Data structures", "Greedy algorithms"], "url": "https://leetcode.com/problems/smallest-range-ii/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "smallestrangeii", "task_id": "TACO_lite/100", "example": [[[[1], 0], [[0, 10], 2], [[1, 3, 6], 3]], ["0", "6", "3"]]} +{"requirement": "Given N, count all \u2018a\u2019(>=1) and \u2018b\u2019(>=0) that satisfy the condition a^{3} + b^{3 }= N.\n \nExample 1:\nInput:\nN = 9 \nOutput:\n2\nExplanation:\nThere are two solutions: (a=1, b=2)\nand (a=2, b=1).\nExample 2:\nInput:\nN = 27\nOutput:\n1\nExplanation:\nThereis only one solution: (a=3, b=0)\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function pairCubeCount() which takes an Integer N as input and returns the answer.\n \nExpected Time Complexity: O(cbrt(N))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= N <= 10^{5}", "solutions": ["def paircubecount(N):\n count = 0\n max_a = int(pow(N, 1 / 3)) + 1\n for a in range(1, max_a):\n b_cube = N - pow(a, 3)\n if b_cube < 0:\n break\n b = int(round(pow(b_cube, 1 / 3)))\n if pow(b, 3) == b_cube:\n count += 1\n if pow(a, 3) == N and b_cube == 0:\n count += 1\n if N == 1:\n count = 1\n return count", "def paircubecount(N):\n s = set()\n if N == 1:\n return 1\n count = 0\n for i in range(0, int(N ** (1 / 3)) + 1):\n r = N - i ** 3\n if round(r ** (1 / 3)) ** 3 == r:\n s.add(r)\n s.add(i ** 3)\n return len(s)", "import math\n\ndef paircubecount(N):\n c = 0\n a = N ** (1 / 3)\n if a > int(a):\n for i in range(1, int(a) + 1):\n for j in range(1, int(a) + 1):\n if math.pow(i, 3) + math.pow(j, 3) == N:\n c += 1\n elif a == int(a):\n c += 1\n return c", "def paircubecount(N):\n count = 0\n for a in range(1, int(N ** (1 / 3)) + 1):\n b = N - a ** 3\n if round(b ** (1 / 3)) ** 3 == b:\n count += 1\n return count", "def paircubecount(N):\n (ct, a) = (0, 1)\n while a ** 3 <= N:\n b = 0\n while b ** 3 <= N:\n if a ** 3 + b ** 3 == N:\n ct += 1\n b += 1\n a += 1\n return ct", "import math\n\ndef paircubecount(N):\n count = 0\n M = round(math.pow(N, 1 / 3))\n for i in range(1, M + 1):\n for j in range(M + 1):\n if i ** 3 + j ** 3 == N:\n count += 1\n return count", "import math\n\ndef paircubecount(N):\n count = 0\n a = math.floor(math.pow(N, 1 / 3))\n for i in range(0, a + 1):\n for j in range(1, a + 1):\n if i ** 3 + j ** 3 == N:\n count += 1\n return count", "def paircubecount(N):\n p = int(N ** (1 / 3)) + 1\n count = 0\n for i in range(1, p):\n for j in range(0, p):\n if i ** 3 + j ** 3 == N:\n count += 1\n return count", "def paircubecount(N):\n solutions = 0\n crN = int(N ** (1 / 3)) + 1\n for a in range(1, crN + 1):\n for b in range(0, a + 1):\n if a ** 3 + b ** 3 == N:\n if a == b or b == 0:\n solutions = solutions + 1\n else:\n solutions = solutions + 2\n return solutions", "def paircubecount(N):\n cube = int(N ** (1 / 3)) + 1\n c = 0\n for x in range(1, cube + 1):\n for y in range(cube + 1):\n if x ** 3 + y ** 3 == N:\n c += 1\n return c", "def paircubecount(N):\n (a, b) = (int(N ** (1 / 3)), int(N ** (1 / 3)))\n c = 0\n for i in range(1, a + 1):\n for j in range(b + 1):\n if i ** 3 + j ** 3 == N:\n c += 1\n elif i ** 3 + j ** 3 > N:\n break\n return c", "import math\n\ndef paircubecount(t):\n value = int(t ** (1 / 3))\n count = 0\n for i in range(1, value + 1):\n for j in range(0, value + 1):\n if i ** 3 + j ** 3 == t:\n count += 1\n return count", "def paircubecount(N):\n import math\n count = 0\n l = math.ceil(math.pow(N, 1 / 3))\n for i in range(1, l + 1):\n for j in range(0, l + 1):\n a = i * i * i\n b = j * j * j\n if a + b == N:\n count = count + 1\n return count", "def paircubecount(N):\n if N == 1:\n return 1\n count = 0\n floor_cbrt_N = 0\n while floor_cbrt_N ** 3 <= N:\n floor_cbrt_N += 1\n floor_cbrt_N -= 1\n for a in range(1, floor_cbrt_N + 1):\n b = N - a ** 3\n if b < 0:\n break\n cbrt_b = 0\n while cbrt_b ** 3 <= b:\n cbrt_b += 1\n if (cbrt_b - 1) ** 3 == b:\n count += 1\n return count", "from itertools import product\nimport math\n\ndef paircubecount(N):\n count = 0\n nums = [i for i in range(0, int(N ** (1 / 3)) + 1)]\n combs = [i for i in product(nums, repeat=2)]\n for i in combs:\n if i[0] ** 3 + i[1] ** 3 == N and i[0] >= 1 and (i[1] >= 0):\n count += 1\n return count", "def paircubecount(N):\n aset = set()\n i = 1\n while i <= N ** (1 / 3):\n aset.add(i * i * i)\n i += 1\n count = 0\n for ele in aset:\n if N - ele == 0 or N - ele in aset:\n count += 1\n return count", "import math\n\ndef paircubecount(N):\n res = int(N ** (1 / 3) + 1)\n count = 0\n for i in range(0, res):\n for j in range(1, res):\n if N == i ** 3 + j ** 3:\n count += 1\n return count", "def paircubecount(N):\n if N == 1:\n return 1\n a = {}\n b = []\n count = 0\n for i in range(N):\n if i not in a:\n a[i ** 3] = 1\n b.append(i)\n for i in b:\n if N - i ** 3 in a:\n count += 1\n return count", "def paircubecount(N):\n import math\n c = 0\n d = math.ceil(math.pow(N, 1 / 3))\n for i in range(1, d + 1):\n for j in range(d + 1):\n p = pow(i, 3) + pow(j, 3)\n if p == N:\n c += 1\n if c != 0:\n return c\n else:\n return 0", "import math\n\ndef paircubecount(N):\n count = 0\n for i in range(1, int(N ** (1 / 3)) + 1):\n bcube_root = (N - i ** 3) ** (1 / 3)\n if math.ceil(bcube_root) ** 3 == N - i ** 3:\n count += 1\n return count", "def paircubecount(N):\n c = 0\n if N == 1:\n return 1\n for i in range(1, int(pow(N, 1 / 3) + 1)):\n for j in range(0, int(pow(N, 1 / 3) + 1)):\n if i * i * i + j * j * j == N:\n c = c + 1\n return c", "import math\n\ndef paircubecount(N):\n sq = int(math.sqrt(N))\n count = 0\n if N <= 8:\n return 1\n for x in range(0, sq):\n for y in range(1, sq):\n if pow(x, 3) + pow(y, 3) == N:\n count = count + 1\n return count", "import math\n\ndef paircubecount(n):\n sq = int(math.sqrt(n))\n flag = 0\n if n <= 8:\n return 1\n for x in range(0, sq):\n for y in range(1, sq):\n if pow(x, 3) + pow(y, 3) == n:\n flag = flag + 1\n return flag", "def paircubecount(N):\n if N == 1:\n return 1\n count = 0\n for i in range(1, N):\n for j in range(N):\n if i * i * i + j * j * j == N:\n count += 1\n elif i * i * i + j * j * j > N:\n break\n return count", "import math\n\ndef paircubecount(N):\n count = 0\n i = 1\n while i * i * i <= N:\n j = 0\n while j * j * j <= N:\n if i * i * i + j * j * j == N:\n count += 1\n j += 1\n i += 1\n return count", "def paircubecount(N):\n count = 0\n x = int(pow(N, 1 / 3))\n for i in range(1, x + 1):\n b = N - i * i * i\n if b == round(b ** (1 / 3)) ** 3:\n count += 1\n return count", "def paircubecount(N):\n x = int(N ** (1 / 3)) + 1\n ans = 0\n root = int(N ** (1 / 3))\n if root ** 3 == N:\n ans += 1\n for i in range(1, x):\n for j in range(1, x):\n if i ** 3 + j ** 3 == N:\n ans += 1\n return ans", "import math\n\ndef paircubecount(N):\n c = 0\n l = math.ceil(math.pow(N, 1 / 3))\n for i in range(1, l + 1):\n for j in range(0, l + 1):\n if i ** 3 + j ** 3 == N:\n c += 1\n return c", "import numpy as np\n\ndef paircubecount(N):\n count = 0\n for a in range(1, int(np.cbrt(N)) + 1):\n for b in range(0, int(np.cbrt(N) + 1)):\n if a ** 3 + b ** 3 == N:\n count += 1\n return count", "import math\n\ndef paircubecount(N):\n count = 0\n for b in range(int(N ** (1 / 3) + 1)):\n a = round((N - b ** 3) ** (1 / 3), 4)\n if a % 1 == 0 and a >= 1:\n count += 1\n return count", "def paircubecount(N):\n k = 0\n for a in range(1, int(pow(N, 1 / 3)) + 1):\n for b in range(0, int(pow(N, 1 / 3)) + 1):\n if pow(a, 3) + pow(b, 3) == N:\n k += 1\n return k", "def paircubecount(N):\n j = 0\n for i in range(1, int(pow(N, 1 / 3)) + 1):\n k = pow(N - pow(i, 3), 1 / 3)\n if (N - k) % 1 < pow(10, -7):\n j += 1\n return j", "def paircubecount(N):\n count = 0\n res1 = 0\n res2 = 0\n flag = 0\n cond = N\n if N == 0:\n return 0\n for i in range(1, N + 1):\n res1 = i * i * i\n if res1 <= N:\n for j in range(0, N):\n res2 = j * j * j\n if res2 < N:\n if res1 + res2 == N:\n count += 1\n else:\n flag = 1\n break\n else:\n break\n return count", "import math\n\ndef paircubecount(N):\n c = 0\n for i in range(1, int(math.sqrt(N) + 1)):\n for j in range(int(math.sqrt(N)) + 1):\n if i ** 3 + j ** 3 == N:\n c += 1\n return c", "import math\n\ndef paircubecount(N):\n count = 0\n for i in range(1, int(math.pow(N, 1 / 3) + 1)):\n cube = i * i * i\n diff = N - cube\n s_cube = round(math.pow(diff, 1 / 3))\n if s_cube * s_cube * s_cube == diff:\n count += 1\n return count", "def paircubecount(N):\n cubes_root = set()\n cubes_val = set()\n i = 0\n while i ** 3 <= N:\n cubes_root.add(i)\n cubes_val.add(i ** 3)\n i += 1\n return sum((N - i ** 3 in cubes_val and N - i ** 3 != 0 for i in cubes_root))", "import math\n\ndef paircubecount(N):\n if N == 1:\n return N\n count = 0\n cubRoot = round(N ** 1 / 3)\n for i in range(0, cubRoot + 1):\n aCube = i ** 3\n if aCube == N:\n count += 1\n else:\n if N - aCube == 1:\n ans = 1\n else:\n ans = round(math.pow(abs(N - aCube), 1 / 3))\n if ans ** 3 + aCube == N:\n count += 1\n return count", "import math\n\ndef paircubecount(N):\n count = 0\n i = 1\n while i * i * i <= N:\n cb = i * i * i\n if cb == N:\n count = count + 1\n else:\n val = N - cb\n out = math.ceil(val ** (1 / 3))\n if out ** 3 == val:\n count = count + 1\n i = i + 1\n return count", "import math\n\ndef paircubecount(N):\n k = math.floor(N ** (1 / 3))\n a = 1\n b = 0\n c = 0\n for i in range(1, k + 1):\n for j in range(k + 1):\n if i ** 3 + j ** 3 == N:\n c += 1\n return c", "def paircubecount(N):\n count = 0\n n = round(pow(N, 1 / 3)) + 1\n for i in range(1, n):\n for j in range(0, n):\n if pow(i, 3) + pow(j, 3) == N:\n count += 1\n if N == 1:\n return 1\n else:\n return count", "def paircubecount(N):\n m = int(N ** (1 / 3))\n M = m\n n = 0\n count = 0\n while m >= 0:\n for n in range(1, M + 1):\n if n ** 3 + m ** 3 == N:\n count = count + 1\n m = m - 1\n return count", "def paircubecount(N):\n (i, j, c) = (0, 0, 0)\n while i ** 3 <= N:\n j = 0\n while j ** 3 <= N:\n if j ** 3 + i ** 3 == N and j ** 3 != N:\n c = c + 1\n j = j + 1\n i = i + 1\n return c", "import math\n\ndef paircubecount(N):\n root_value = 3\n upper_limit = int(N ** (1 / root_value))\n count_sols = 0\n for i in range(1, upper_limit + 1):\n first_cube = i * i * i\n diff = N - first_cube\n cbrtdiff = math.ceil(diff ** (1 / 3))\n if cbrtdiff ** 3 == diff:\n count_sols += 1\n return count_sols", "def paircubecount(N):\n root_value = 3\n upper_limit = int(N ** (1 / root_value))\n count_sols = 0\n for i in range(0, upper_limit + 1):\n for j in range(1, upper_limit + 1):\n if j ** root_value + i ** root_value == N:\n count_sols += 1\n return count_sols", "import math\n\ndef paircubecount(N):\n count = 0\n for i in range(1, int(N ** (1 / 3)) + 1):\n cb = i * i * i\n diff = N - cb\n cbrtdiff = int(round(diff ** (1 / 3)))\n diffcb = cbrtdiff * cbrtdiff * cbrtdiff\n if diffcb == diff:\n count += 1\n return count"], "starter_code": "def paircubecount(N):\n", "input_output": {"inputs": ["N = 9", "N = 27"], "outputs": ["2", "1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/pair-cube-count4132/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(cbrt(N))", "entry_point": "paircubecount", "task_id": "TACO_lite/131", "example": [[[9], [27]], [2, 2]]} +{"requirement": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different.\n\nGiven two integers x and y, calculate the Hamming distance.\n\nNote:\n0 \u2264 x, y < 231.\n\n\nExample:\n\nInput: x = 1, y = 4\n\nOutput: 2\n\nExplanation:\n1 (0 0 0 1)\n4 (0 1 0 0)\n \u2191 \u2191\n\nThe above arrows point to positions where the corresponding bits are different.", "solutions": ["def hammingdistance(x, y):\n x = x ^ y\n y = 0\n while x:\n y += 1\n x &= x - 1\n return y", "def hammingdistance(x, y):\n if x == y:\n return 0\n (bin_x, bin_y) = (bin(x)[2:], bin(y)[2:])\n if x < y:\n bin_x = bin_x.zfill(len(bin_y))\n else:\n bin_y = bin_y.zfill(len(bin_x))\n return sum([abs(int(bin_x[i]) - int(bin_y[i])) for i in range(len(bin_x))])", "def hammingdistance(x, y):\n count = 0\n for i in range(32):\n count += x & 1 ^ y & 1\n x >>= 1\n y >>= 1\n return count", "def hammingdistance(x, y):\n d = bin(x ^ y)\n return d.count('1')", "def hammingdistance(x, y):\n x_b = '{:32b}'.format(x).replace(' ', '0')\n y_b = '{:32b}'.format(y).replace(' ', '0')\n count = 0\n for i in range(len(x_b)):\n if x_b[i] != y_b[i]:\n count += 1\n return count", "def hammingdistance(x, y):\n xor = x ^ y\n count = 0\n for _ in range(32):\n count += xor & 1\n xor = xor >> 1\n return count", "def hammingdistance(x, y):\n count = 0\n while x > 0 or y > 0:\n if x & 1 != y & 1:\n count += 1\n if x > 0:\n x = x >> 1\n if y > 0:\n y = y >> 1\n return count", "def hammingdistance(x, y):\n x_bits = [int(i) for i in bin(x)[2:]]\n y_bits = [int(j) for j in bin(y)[2:]]\n digit_diff = abs(len(x_bits) - len(y_bits))\n if len(y_bits) > len(x_bits):\n x_bits = [0] * digit_diff + x_bits\n elif len(x_bits) > len(y_bits):\n y_bits = [0] * digit_diff + y_bits\n hamming_dist = 0\n for i in range(0, len(x_bits)):\n if x_bits[i] != y_bits[i]:\n hamming_dist += 1\n return hamming_dist", "def hammingdistance(x, y):\n xor_result = x ^ y\n count = 0\n while xor_result > 0:\n count += xor_result & 1\n xor_result = xor_result >> 1\n return count", "def hammingdistance(x, y):\n hamming_distance = 0\n while x != 0 or y != 0:\n b1 = x & 1\n b2 = y & 1\n if b1 != b2:\n hamming_distance = hamming_distance + 1\n x = x >> 1\n y = y >> 1\n return hamming_distance"], "starter_code": "def hammingdistance(x: int, y: int) -> int:\n", "input_output": {"fn_name": "hammingDistance", "inputs": [[1, 4]], "outputs": [2]}, "difficulty": "EASY", "raw_tags": ["Bit Manipulation"], "name": null, "source": "leetcode", "tags": ["Bit manipulation"], "skill_types": ["Bit manipulation"], "url": "https://leetcode.com/problems/hamming-distance/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "hammingdistance", "task_id": "TACO_lite/115", "example": [[[1, 4]], ["2"]]} +{"requirement": "Say you have an array for which the ith element is the price of a given stock on day i.\n\nDesign an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:\n\n\n You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).\n After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)\n\n\nExample:\n\n\nInput: [1,2,3,0,2]\nOutput: 3 \nExplanation: transactions = [buy, sell, cooldown, buy, sell]", "solutions": ["def maxprofit(prices):\n n = len(prices)\n if n < 2:\n return 0\n sells = [0] * n\n buys = [0] * n\n buys[0] = -prices[0]\n for i in range(1, n):\n sells[i] = max(sells[i - 1], buys[i - 1] + prices[i])\n buys[i] = max(buys[i - 1], (sells[i - 2] if i > 1 else 0) - prices[i])\n return sells[n - 1]", "def maxprofit(prices):\n if not prices:\n return 0\n sell = hold = 0\n buy = -prices[0]\n for i in range(1, len(prices)):\n (sell, hold, buy) = (max(buy + prices[i], 0), max(hold, sell), max(hold - prices[i], buy))\n return max(sell, hold)", "def maxprofit(prices):\n if prices is None or len(prices) == 0:\n return 0\n dp = [[-9999999] * len(prices) for _ in range(3)]\n (dp[0][0], dp[1][0], dp[2][0]) = (-prices[0], 0, 0)\n for i in range(1, len(prices)):\n dp[0][i] = max(dp[0][i - 1], dp[2][i - 1] - prices[i])\n dp[1][i] = max(dp[0][i - 1] + prices[i], dp[1][i - 1])\n dp[2][i] = max(dp[2][i - 1], dp[0][i - 1], dp[1][i - 1])\n return max(dp[1][-1], dp[2][-1])", "def maxprofit(prices):\n n = len(prices)\n if not n:\n return 0\n buys = [None] * n\n sells = [None] * n\n (sells[0], buys[0]) = (0, -prices[0])\n for x in range(1, n):\n delta = prices[x] - prices[x - 1]\n sells[x] = max(buys[x - 1] + prices[x], sells[x - 1] + delta)\n buys[x] = max(buys[x - 1] - delta, sells[x - 2] - prices[x] if x > 1 else -9999)\n return max(sells)", "def maxprofit(prices):\n n = len(prices)\n if n < 2:\n return 0\n (buy, sell) = ([0] * n, [0] * n)\n (buy[0], buy[1]) = (-prices[0], -min(prices[0:2]))\n sell[1] = max(0, buy[0] + prices[1])\n for i in range(2, n):\n sell[i] = max(sell[i - 1], buy[i - 1] + prices[i])\n buy[i] = max(buy[i - 1], sell[i - 2] - prices[i])\n return sell[-1]", "def maxprofit(prices):\n if not prices or len(prices) == 1:\n return 0\n valid_status = [0, [prices[0], -prices[0]], 0]\n for t in range(1, len(prices)):\n valid_status[1][0] = prices[t]\n cool_down_temp = sum(valid_status[1])\n if valid_status[0] > sum(valid_status[1]):\n valid_status[1] = [prices[t], valid_status[0] - prices[t]]\n if valid_status[2] > valid_status[0]:\n valid_status[0] = valid_status[2]\n valid_status[2] = cool_down_temp\n return max(valid_status[0], valid_status[2])", "def maxprofit(prices):\n if not prices:\n return 0\n max_buy = [0] * len(prices)\n max_sell = [0] * len(prices)\n max_rest = [0] * len(prices)\n max_buy[0] = -prices[0]\n max_sell[0] = 0\n max_rest[0] = 0\n for i in range(1, len(prices)):\n max_buy[i] = max(max_rest[i - 1] - prices[i], max_buy[i - 1])\n max_sell[i] = max(max_buy[i - 1] + prices[i], max_sell[i - 1])\n max_rest[i] = max(max_sell[i - 1], max_rest[i - 1])\n return max(max_buy[-1], max_sell[-1], max_rest[-1])", "def maxprofit(prices):\n free = 0\n have = cool = float('-inf')\n for p in prices:\n (free, have, cool) = (max(free, cool), max(have, free - p), have + p)\n return max(free, cool)", "def maxprofit(prices):\n if not prices:\n return 0\n prices.insert(0, 0)\n prices.insert(0, 0)\n buy = [0] * len(prices)\n sell = [0] * len(prices)\n buy[2] = -prices[2]\n for i in range(3, len(prices)):\n buy[i] = max(sell[i - 2] - prices[i], buy[i - 1])\n sell[i] = max(buy[i - 1] + prices[i], sell[i - 1])\n return sell[-1]", "def maxprofit(prices):\n return self.max_profit_rec(prices, {}, 0, 0)\n\ndef max_profit_rec(prices, memo, idx, state):\n if idx >= len(prices):\n return 0\n if (idx, state) in memo:\n return memo[idx, state]\n memo[idx, state] = 0\n if state == 0:\n memo[idx, state] = max(self.max_profit_rec(prices, memo, idx + 1, 1) - prices[idx], self.max_profit_rec(prices, memo, idx + 1, 0))\n elif state == 1:\n memo[idx, state] = max(self.max_profit_rec(prices, memo, idx + 1, 2) + prices[idx], self.max_profit_rec(prices, memo, idx + 1, 1))\n else:\n memo[idx, state] = self.max_profit_rec(prices, memo, idx + 1, 0)\n return memo[idx, state]", "def maxprofit(prices):\n if len(prices) < 2:\n return 0\n (prevSell, sell, prevBuy, buy) = (0, 0, 0, -prices[0])\n for price in prices:\n prevBuy = buy\n buy = max(prevBuy, prevSell - price)\n prevSell = sell\n sell = max(prevSell, prevBuy + price)\n return sell"], "starter_code": "def maxprofit(prices: List[int]) -> int:\n", "input_output": {"fn_name": "maxProfit", "inputs": [[[1, 2, 3, 0, 2]]], "outputs": [3]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "maxprofit", "task_id": "TACO_lite/125", "example": [[[[1, 2, 3, 0, 2]]], ["3"]]} +{"requirement": "The number ```89``` is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata. \nWhat's the use of saying \"Eureka\"? Because this sum gives the same number.\n\nIn effect: ```89 = 8^1 + 9^2``` \n\nThe next number in having this property is ```135```.\n\nSee this property again: ```135 = 1^1 + 3^2 + 5^3```\n\nWe need a function to collect these numbers, that may receive two integers ```a```, ```b``` that defines the range ```[a, b]``` (inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.\n\nLet's see some cases:\n```python\nsum_dig_pow(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nsum_dig_pow(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]\n```\nIf there are no numbers of this kind in the range [a, b] the function should output an empty list.\n```python\nsum_dig_pow(90, 100) == []\n```\nEnjoy it!!", "solutions": ["def dig_pow(n):\n return sum((int(x) ** y for (y, x) in enumerate(str(n), 1)))\n\ndef sum_dig_pow(a, b):\n return [x for x in range(a, b + 1) if x == dig_pow(x)]", "def sum_dig_pow(a, b):\n return [x for x in range(a, b + 1) if sum((int(d) ** i for (i, d) in enumerate(str(x), 1))) == x]", "def sum_dig_pow(a, b):\n res = []\n for number in range(a, b + 1):\n digits = [int(i) for i in str(number)]\n s = 0\n for (idx, val) in enumerate(digits):\n s += val ** (idx + 1)\n if s == number:\n res.append(number)\n return res", "def sum_dig_pow(a, b):\n l = []\n for i in range(a, b + 1):\n k = 0\n p = str(i)\n for j in range(len(p)):\n k += int(p[j]) ** (j + 1)\n if k == i:\n l.append(i)\n return l", "def sum_dig_pow(a, b):\n ans = []\n while a <= b:\n if sum((int(j) ** k for (j, k) in zip(str(a), range(1, len(str(a)) + 1)))) == a:\n ans += [a]\n a += 1\n return ans", "def sum_dig_pow(a, b):\n lis = []\n for i in range(a, b + 1):\n temp = str(i)\n su = 0\n for l in range(0, len(temp)):\n su += int(temp[l:l + 1]) ** (l + 1)\n if su == i:\n lis.append(i)\n return lis"], "starter_code": "def sum_dig_pow(a, b):\n", "input_output": {"fn_name": "sum_dig_pow", "inputs": [[1, 100], [10, 89], [10, 100], [90, 100], [90, 150], [50, 150], [10, 150], [89, 135]], "outputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 89]], [[89]], [[89]], [[]], [[135]], [[89, 135]], [[89, 135]], [[89, 135]]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5626b561280a42ecc50000d1", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sum_dig_pow", "task_id": "TACO_lite/39", "example": [[[1, 10], [1, 100], [90, 100]], ["[1, 2, 3, 4, 5, 6, 7, 8, 9]", "[1, 2, 3, 4, 5, 6, 7, 8, 9, 89]", "[]"]]} +{"requirement": "How many bees are in the beehive?\n\n* bees can be facing UP, DOWN, LEFT, or RIGHT \n* bees can share parts of other bees\n\nExamples\n\nEx1\n```\nbee.bee \n.e..e..\n.b..eeb\n```\n*Answer: 5*\n\n\nEx2\n```\nbee.bee \ne.e.e.e\neeb.eeb\n```\n*Answer: 8*\n\n# Notes\n\n* The hive may be empty or null/None/nil/...\n* Python: the hive is passed as a list of lists (not a list of strings)", "solutions": ["from itertools import chain\n\ndef how_many_bees(hive):\n return bool(hive) and sum((s.count('bee') + s.count('eeb') for s in map(''.join, chain(hive, zip(*hive)))))", "def count(it):\n return sum((''.join(x).count('bee') + ''.join(x).count('eeb') for x in it))\n\ndef how_many_bees(hive):\n return count(hive) + count(zip(*hive)) if hive else 0", "def how_many_bees(hive):\n if hive == None or len(hive) == 0:\n return 0\n result = 0\n for i in range(len(hive[0])):\n test = ''\n for item in hive:\n test += item[i]\n result += test.count('bee')\n result += test.count('eeb')\n for i in range(len(hive)):\n test = ''\n for item in hive[i]:\n test += item\n result += test.count('bee')\n result += test.count('eeb')\n return result", "import re\n\ndef how_many_bees(hive):\n if hive is None:\n return 0\n s = ' '.join((''.join(line) for hiveArr in (hive, zip(*hive)) for line in hiveArr))\n return len(re.findall('b(?=ee)|ee(?=b)', s))", "def how_many_bees(hive):\n if not hive:\n return 0\n row_bees = lambda row: sum((1 for i in range(len(row)) if ''.join(row[i:i + 3]) == 'bee'))\n matrix_bees = lambda matrix: sum((row_bees(row) for row in matrix))\n v_flip = lambda matrix: [row[::-1] for row in matrix]\n transpose = lambda matrix: [list(z) for z in zip(*matrix)]\n return matrix_bees(hive) + matrix_bees(transpose(hive)) + matrix_bees(v_flip(hive)) + matrix_bees(v_flip(transpose(hive)))", "def how_many_bees(hive):\n if hive is None:\n return 0\n columns = [''.join(col) for col in zip(*hive)]\n hive = [''.join(line) for line in hive]\n return sum((row.count(bee) for bee in ('bee', 'eeb') for rows in (hive, columns) for row in rows))", "def how_many_bees(hive):\n counter = 0\n try:\n for row in hive:\n for i in range(len(row) - 2):\n if row[i] == 'b' and row[i + 1] == 'e' and (row[i + 2] == 'e'):\n counter += 1\n elif row[i] == 'e' and row[i + 1] == 'e' and (row[i + 2] == 'b'):\n counter += 1\n for column in range(len(hive[0])):\n for position in range(len(hive) - 2):\n if hive[position][column] == 'b' and hive[position + 1][column] == 'e' and (hive[position + 2][column] == 'e'):\n counter += 1\n if hive[position][column] == 'e' and hive[position + 1][column] == 'e' and (hive[position + 2][column] == 'b'):\n counter += 1\n except:\n counter = 0\n return counter", "import re\n\ndef how_many_bees(b):\n if b is None:\n return 0\n new_temp = [[j for j in i] for i in b]\n c = [len(re.findall('bee', ''.join(i + [' '] + i[::-1]))) for i in new_temp] + [len(re.findall('bee', ''.join(i + tuple(' ') + i[::-1]))) for i in zip(*new_temp)]\n return sum(c)", "directions = [(1, 0), (-1, 0), (0, -1), (0, 1)]\n\ndef how_many_bees(hive):\n (r, c) = (len(hive), len(hive[0])) if hive else (0, 0)\n\n def f(s, i, j, di, dj):\n if not (0 <= i < r and 0 <= j < c and s.startswith(hive[i][j])):\n return 0\n s = s[1:]\n return f(s, i + di, j + dj, di, dj) if s else 1\n return sum((f('bee', i, j, di, dj) for i in range(r) for j in range(c) for (di, dj) in directions))", "def how_many_bees(hive):\n if hive == [] or hive == '' or hive == None:\n return 0\n result = 0\n for i in range(len(hive)):\n for k in range(len(hive[i])):\n if i > 1 and hive[i][k] == 'b':\n if hive[i - 1][k] == 'e' and hive[i - 2][k] == 'e':\n result += 1\n if i < len(hive) - 2 and hive[i][k] == 'b':\n if hive[i + 1][k] == 'e' and hive[i + 2][k] == 'e':\n result += 1\n if k < len(hive[i]) - 2 and hive[i][k] == 'b':\n if hive[i][k + 1] == 'e' and hive[i][k + 2] == 'e':\n result += 1\n if k > 1 and hive[i][k] == 'b':\n if hive[i][k - 1] == 'e' and hive[i][k - 2] == 'e':\n result += 1\n return result", "how_many_bees = lambda h: h and sum(map('|'.join(map(''.join, h + list(zip(*h)))).count, ('bee', 'eeb'))) or 0", "import re\nhow_many_bees = lambda b: 0 if not b else sum([len(re.findall('bee', ''.join(i + [' '] + i[::-1]))) for i in b] + [len(re.findall('bee', ''.join(i + tuple(' ') + i[::-1]))) for i in zip(*b)])", "def how_many_bees(hive):\n bees = ('bee', 'eeb')\n num_of_bees = 0\n if hive == None:\n return 0\n for line in hive:\n for pos in range(len(line) - 2):\n possible_bee = line[pos] + line[pos + 1] + line[pos + 2]\n if possible_bee in bees:\n num_of_bees += 1\n for line_idx in range(len(hive) - 2):\n for pos_idx in range(len(hive[line_idx])):\n possible_bee = hive[line_idx][pos_idx] + hive[line_idx + 1][pos_idx] + hive[line_idx + 2][pos_idx]\n if possible_bee in bees:\n num_of_bees += 1\n return num_of_bees", "def how_many_bees(hive):\n if hive is None or len(hive) == 0:\n return 0\n cnt = 0\n for row in hive:\n cnt += ''.join(row).count('bee')\n cnt += ''.join(row).count('eeb')\n (m, n) = (len(hive), len(hive[0]))\n cols = [''.join([hive[j][i] for j in range(m)]) for i in range(n)]\n cnt += sum([i.count('bee') for i in cols])\n cnt += sum([i.count('eeb') for i in cols])\n return cnt", "def rotate(matrix):\n return list(zip(*matrix[::-1]))\n\ndef how_many_bees(hive):\n if hive:\n s1 = ' '.join([''.join(r) for r in hive])\n s2 = ' '.join([''.join(el) for el in rotate(hive)])\n s = s1 + ' ' + s2\n return s.count('bee') + s.count('eeb')\n return 0", "def how_many_bees(hive):\n if not hive:\n return 0\n count = 0\n for i in range(len(hive)):\n for j in range(len(hive[i]) - 2):\n compare = ''.join(hive[i][j:j + 3])\n if compare == 'bee' or compare == 'eeb':\n count += 1\n for i in range(len(hive) - 2):\n for j in range(len(hive[i])):\n compare = hive[i][j] + hive[i + 1][j] + hive[i + 2][j]\n if compare == 'bee' or compare == 'eeb':\n count += 1\n return count", "how_many_bees = lambda h: (lambda m, tm: sum((sum((q.count(a) for q in b)) for a in ['bee', 'eeb'] for b in [m, tm])))([''.join(x) for x in h] if h else [], [''.join([h[p][q] for p in range(len(h))]) for q in range(0 if len(h) == 0 else len(h[0]))] if h else [])", "def how_many_bees(hive):\n try:\n right = sum((line.count('bee') for line in map(''.join, hive)))\n left = sum((line.count('eeb') for line in map(''.join, hive)))\n down = sum((line.count('bee') for line in map(''.join, zip(*hive))))\n up = sum((line.count('eeb') for line in map(''.join, zip(*hive))))\n return up + down + left + right\n except TypeError:\n return 0", "def how_many_bees(hive):\n return sum((word.count('eeb') + word.count('bee') for word in list(map(lambda x: ''.join(list(x)), zip(*hive))) + list(map(lambda x: ''.join(x), hive)))) if hive else 0"], "starter_code": "def how_many_bees(hive):\n", "input_output": {"fn_name": "how_many_bees", "inputs": [[null]], "outputs": [[0]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/57d6b40fbfcdc5e9280002ee", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "how_many_bees", "task_id": "TACO_lite/67", "example": [[[[["b", "e", "e", ".", "b", "e", "e"], [".", "e", ".", ".", "e", ".", "."], ["b", ".", ".", "e", "e", "b"]]], [[["b", "e", "e", ".", "b", "e", "e"], ["e", ".", "e", ".", "e", ".", "e"], ["e", "e", "b", ".", "e", "e", "b"]]]], [4, 8]]} +{"requirement": "Given an integer n, find the closest integer (not including itself), which is a palindrome. \n\nThe 'closest' is defined as absolute difference minimized between two integers.\n\nExample 1:\n\nInput: \"123\"\nOutput: \"121\"\n\n\n\nNote:\n\nThe input n is a positive integer represented by string, whose length will not exceed 18.\nIf there is a tie, return the smaller one as answer.", "solutions": ["def nearestpalindromic(num):\n K = len(num)\n candidates = set([10 ** K + 1, 10 ** (K - 1) - 1])\n Prefix = int(num[:(K + 1) // 2])\n for start in map(str, [Prefix - 1, Prefix, Prefix + 1]):\n candidates.add(start + [start, start[:-1]][K & 1][::-1])\n candidates.discard(num)\n return str(min(candidates, key=lambda x: (abs(int(x) - int(num)), int(x))))", "def nearestpalindromic(n):\n K = len(n)\n candidates = [str(10 ** k + d) for k in (K - 1, K) for d in (-1, 1)]\n Prefix = int(n[:(K + 1) // 2])\n for start in map(str, [Prefix - 1, Prefix, Prefix + 1]):\n candidates.append(str(start) + (start[:-1] if K % 2 == 1 else start)[::-1])\n (ans, diff) = (0, float('inf'))\n base = int(n)\n for C in candidates:\n b = int(C)\n d = abs(b - base)\n if d == 0 or d > diff or (d == diff and b > ans):\n continue\n ans = int(C)\n diff = d\n return str(ans)", "def nearestpalindromic(n):\n K = len(n)\n candidates = [str(10 ** k + d) for k in (K - 1, K) for d in (-1, 1)]\n prefix = n[:(K + 1) // 2]\n P = int(prefix)\n for start in map(str, (P - 1, P, P + 1)):\n candidates.append(start + (start[:-1] if K % 2 else start)[::-1])\n\n def delta(x):\n return abs(int(n) - int(x))\n ans = None\n for cand in candidates:\n if cand != n and (not cand.startswith('00')):\n if ans is None or delta(cand) < delta(ans) or (delta(cand) == delta(ans) and int(cand) < int(ans)):\n ans = cand\n return ans", "def nearestpalindromic(n):\n evenPal = lambda sp: int(sp + sp[::-1])\n oddPal = lambda sp: int(sp + sp[::-1][1:])\n (sn, n) = (n, int(n))\n if len(sn) == 1:\n return str(n - 1)\n ans = -999999999999999999\n mid = len(sn) // 2\n for sp in (sn[:mid], sn[:mid + 1], str(int(sn[:mid]) * 10)):\n p = int(sp)\n for pal in (evenPal, oddPal):\n for d in (-1, 0, 1):\n val = pal(str(p + d))\n if val == n:\n continue\n ans = min(ans, val, key=lambda x: (abs(x - n), x))\n return str(ans)", "def getPalindromic(num, mid=''):\n return str(num) + mid + str(num)[::-1]\n\ndef nearestpalindromic(n):\n if len(n) == 1:\n return str(int(n) - 1)\n midstr = '' if len(n) % 2 == 0 else n[len(n) // 2]\n midint = -1 if len(n) % 2 == 0 else int(n[len(n) // 2])\n s = [''] * 6\n s[0] = '9' * (len(n) - 1)\n s[1] = self.getPalindromic(int(n[:len(n) // 2]) - 1, midstr)\n s[2] = n[:len(n) // 2] + str(midint - 1) + n[:len(n) // 2][::-1] if midint > 0 else self.getPalindromic(int(n[:len(n) // 2]) - 1)\n s[3] = n[:len(n) // 2] + midstr + n[:len(n) // 2][::-1]\n s[4] = n[:len(n) // 2] + str(midint + 1) + n[:len(n) // 2][::-1] if midint < 10 and midint > -1 else self.getPalindromic(int(n[:len(n) // 2]) + 1)\n s[5] = '1' + '0' * (len(n) - 1) + '1'\n nums = map(lambda x: abs(int(x) - int(n)), s)\n nums = list(map(lambda x: x if x > 0 else 1e+18, nums))\n return s[nums.index(min(nums))]"], "starter_code": "def nearestpalindromic(n: str) -> str:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Math", "String"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Mathematics"], "skill_types": [], "url": "https://leetcode.com/problems/find-the-closest-palindrome/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "nearestpalindromic", "task_id": "TACO_lite/152", "example": [[["123"]], ["121"]]} +{"requirement": "Geek wants to climb from the 0th stair to the (n-1)th stair. At a time the Geek can climb either one or two steps. A height[N] array is also given. Whenever the geek jumps from stair i to stair j, the energy consumed in the jump is abs(height[i]- height[j]), where abs() means the absolute difference. return the minimum energy that can be used by the Geek to jump from stair 0 to stair N-1.\nExample:\nInput:\nn = 4\nheight = {10 20 30 10}\nOutput:\n20\nExplanation:\nGeek jump from 1st to 2nd stair(|20-10| = 10 energy lost).\nThen a jump from the 2nd to the last stair(|10-20| = 10 energy lost).\nso, total energy lost is 20 which is the minimum.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function MinimumEnergy() which takes the array height, and integer n, and returns the minimum energy that is lost.\nExpected Time Complexity: O(n)\nExpected Space Complexity: O(n)\nConstraint:\n1<=n<=100000\n1<=height[i]<=1000", "solutions": ["import sys\n\ndef minimumenergy(height, n):\n prev = 0\n prev2 = 0\n for i in range(1, n, 1):\n first = prev + abs(height[i] - height[i - 1])\n second = sys.maxsize\n if i > 1:\n second = prev2 + abs(height[i] - height[i - 2])\n curr = min(first, second)\n prev2 = prev\n prev = curr\n return prev", "def findMinEnergy(height, index, dp):\n if index == 0:\n return 0\n if dp[index] != -1:\n return dp[index]\n left = Solution.findMinEnergy(self, height, index - 1, dp) + abs(height[index] - height[index - 1])\n right = 1000000000.0\n if index > 1:\n right = Solution.findMinEnergy(self, height, index - 2, dp) + abs(height[index] - height[index - 2])\n dp[index] = min(left, right)\n return dp[index]\n\ndef minimumenergy(height, n):\n dp = [0] * n\n prev = 0\n prev2 = 0\n for index in range(1, n):\n fs = prev + abs(height[index] - height[index - 1])\n ss = 1000000000.0\n if index > 1:\n ss = prev2 + abs(height[index] - height[index - 2])\n curr = min(fs, ss)\n prev2 = prev\n prev = curr\n return prev", "def minimumenergy(height, n):\n prev1 = 0\n prev2 = 0\n for ind in range(1, n):\n one_step = prev1 + abs(height[ind] - height[ind - 1])\n two_step = 10000\n if ind - 2 >= 0:\n two_step = prev2 + abs(height[ind] - height[ind - 2])\n prev2 = prev1\n prev1 = min(one_step, two_step)\n return prev1", "import sys\n\ndef minimumenergy(height, n):\n dp = dict()\n dp[0] = 0\n for i in range(1, n):\n left = dp[i - 1] + abs(height[i] - height[i - 1])\n right = left\n if i > 1:\n right = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(left, right)\n return dp[n - 1]", "def minimumenergy(height, n):\n dp = [0] * n\n for i in range(1, n):\n if i < 2:\n dp[i] = abs(height[i - 1] - height[i]) + dp[i - 1]\n else:\n dp[i] = min(abs(height[i - 1] - height[i]) + dp[i - 1], abs(height[i - 2] - height[i]) + dp[i - 2])\n return dp[-1]", "import sys\n\ndef minimumenergy(height, n):\n prev2 = prev1 = 0\n for i in range(1, n):\n left = abs(height[i] - height[i - 1]) + prev1\n right = sys.maxsize\n if i > 1:\n right = abs(height[i] - height[i - 2]) + prev2\n prev2 = prev1\n prev1 = min(left, right)\n return prev1", "import sys\nimport math\n\ndef minimumenergy(height, n):\n n = len(height)\n dp = [-1 for _ in range(n)]\n dp[0] = 0\n for ind in range(1, n):\n jumpTwo = float('inf')\n jumpOne = dp[ind - 1] + abs(height[ind] - height[ind - 1])\n if ind > 1:\n jumpTwo = dp[ind - 2] + abs(height[ind] - height[ind - 2])\n dp[ind] = min(jumpOne, jumpTwo)\n return dp[n - 1]", "def minEnergy(height, index, dp):\n if index == 0:\n return 0\n if dp[index] != -1:\n return dp[index]\n jumpOneStep = abs(height[index] - height[index - 1]) + self.minEnergy(height, index - 1, dp)\n jumpTwoStep = 99999\n if index > 1:\n jumpTwoStep = abs(height[index] - height[index - 2]) + self.minEnergy(height, index - 2, dp)\n dp[index] = min(jumpOneStep, jumpTwoStep)\n return min(jumpOneStep, jumpTwoStep)\n\ndef minimumenergy(height, n):\n first = 0\n if n == 1:\n return first\n second = abs(height[1] - height[0])\n for i in range(2, n):\n fs = second + abs(height[i] - height[i - 1])\n ss = first + abs(height[i] - height[i - 2])\n ans = min(fs, ss)\n first = second\n second = ans\n return second", "def minEnergy(height, index, dp):\n if index == 0:\n return 0\n if dp[index] != -1:\n return dp[index]\n jumpOneStep = abs(height[index] - height[index - 1]) + self.minEnergy(height, index - 1, dp)\n jumpTwoStep = 99999\n if index > 1:\n jumpTwoStep = abs(height[index] - height[index - 2]) + self.minEnergy(height, index - 2, dp)\n dp[index] = min(jumpOneStep, jumpTwoStep)\n return min(jumpOneStep, jumpTwoStep)\n\ndef minimumenergy(height, n):\n table = [0 for i in range(n)]\n for index in range(1, n):\n jumpOneStep = table[index - 1] + abs(height[index] - height[index - 1])\n jumpTwoStep = 999999\n if index > 1:\n jumpTwoStep = table[index - 2] + abs(height[index] - height[index - 2])\n table[index] = min(jumpOneStep, jumpTwoStep)\n return table[n - 1]", "def minimumenergy(height, n):\n\n def recursive(ind, prev):\n if ind >= n:\n return 0\n energy = 0\n for ind in range(1, n):\n one_pick = abs(height[ind] - height[ind - 1]) + dp[ind - 1]\n two_pick = 10 ** 9\n if ind > 1:\n two_pick = abs(height[ind] - height[ind - 2]) + dp[ind - 2]\n dp[ind] = min(one_pick, two_pick)\n return dp[ind]\n dp = [0 for j in range(n + 1)]\n return recursive(0, -1)", "def minimumenergy(height, n):\n prev1 = prev2 = 0\n for i in range(1, n):\n fs = prev1 + abs(height[i - 1] - height[i])\n if i > 1:\n ss = prev2 + abs(height[i - 2] - height[i])\n else:\n ss = 100000000\n curr = min(fs, ss)\n prev2 = prev1\n prev1 = curr\n return prev1", "def minimumenergy(a, n):\n if n == 1:\n return 0\n inf = float('inf')\n dp = [inf] * (n + 1)\n dp[0] = 0\n for i in range(1, n):\n dp[i] = dp[i - 1] + abs(a[i] - a[i - 1])\n if i - 2 >= 0:\n dp[i] = min(dp[i], dp[i - 2] + abs(a[i] - a[i - 2]))\n return dp[n - 1]", "import sys\n\ndef minimumenergy(height, n):\n prev1 = 0\n prev2 = 0\n if n == 1:\n return 0\n else:\n for i in range(1, n):\n jumptwo = sys.maxsize\n onejump = prev1 + abs(height[i] - height[i - 1])\n if i > 1:\n jumptwo = prev2 + abs(height[i] - height[i - 2])\n cur_i = min(onejump, jumptwo)\n prev2 = prev1\n prev1 = cur_i\n return cur_i", "def minimumenergy(height, n):\n dp = [-1 for i in range(n)]\n dp[0] = 0\n for i in range(1, n):\n jumptwo = float('inf')\n onejump = dp[i - 1] + abs(height[i] - height[i - 1])\n if i > 1:\n jumptwo = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(onejump, jumptwo)\n return dp[n - 1]", "def minimumenergy(height, n):\n prev1 = 0\n prev2 = -1\n for i in range(1, n):\n one = prev1 + abs(height[i - 1] - height[i])\n if i <= 1:\n prev2 = prev1\n prev1 = one\n continue\n two = prev2 + abs(height[i - 2] - height[i])\n prev2 = prev1\n prev1 = min(two, one)\n return prev1\n\ndef rec(H, n, dp):\n if n == 0:\n return 0\n one = abs(H[n] - H[n - 1])\n if dp[n - 1] != -1:\n one += dp[n - 1]\n else:\n val = self.rec(H, n - 1, dp)\n dp[n - 1] = val\n one += val\n if n <= 1:\n return one\n two = abs(H[n] - H[n - 2])\n if dp[n - 2] != -1:\n two += dp[n - 2]\n else:\n val = self.rec(H, n - 2, dp)\n dp[n - 2] = val\n two += val\n return min(one, two)", "def minimumenergy(height, n):\n if n == 1:\n return 0\n first = 0\n second = abs(height[1] - height[0])\n for i in range(2, n):\n (first, second) = (second, min(first + abs(height[i] - height[i - 2]), second + abs(height[i] - height[i - 1])))\n return second", "def minimumenergy(height, n):\n prev2 = 0\n prev1 = 0\n for i in range(1, n):\n step2 = float('inf')\n step1 = prev1 + abs(height[i] - height[i - 1])\n if i > 1:\n step2 = prev2 + abs(height[i] - height[i - 2])\n curr = min(step1, step2)\n prev2 = prev1\n prev1 = curr\n return prev1", "def minimumenergy(height, n):\n dp = [-1] * n\n dp[0] = 0\n step2 = float('inf')\n for i in range(1, n):\n step1 = dp[i - 1] + abs(height[i] - height[i - 1])\n if i > 1:\n step2 = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(step1, step2)\n return dp[n - 1]", "def minimumenergy(height, n):\n prev1 = 0\n prev2 = 0\n for i in range(1, n):\n fm = prev1 + abs(height[i] - height[i - 1])\n sm = 10 ** 8\n if i > 1:\n sm = prev2 + abs(height[i] - height[i - 2])\n curr = min(fm, sm)\n prev2 = prev1\n prev1 = curr\n return prev1", "def minimumenergy(height, n):\n li = []\n if n == 0 or n == 1:\n return 0\n for i in range(0, n):\n li.append(0)\n li[0] = 0\n li[1] = abs(height[1] - height[0])\n for i in range(2, n):\n left = li[i - 1] + abs(height[i] - height[i - 1])\n right = li[i - 2] + abs(height[i] - height[i - 2])\n li[i] = min(left, right)\n return li[n - 1]", "def minimumenergy(height, n):\n prev = 0\n prev2 = 0\n for idx in range(1, n):\n left = prev + abs(height[idx - 1] - height[idx])\n if idx > 1:\n right = prev2 + abs(height[idx - 2] - height[idx])\n else:\n right = float('inf')\n curr = min(left, right)\n prev2 = prev\n prev = curr\n return prev", "import sys\nsys.setrecursionlimit(1500)\n\ndef minimumenergy(height, n):\n dp = [-1] * (n + 1)\n dp[0] = 0\n for idx in range(1, n):\n left = dp[idx - 1] + abs(height[idx - 1] - height[idx])\n if idx > 1:\n right = dp[idx - 2] + abs(height[idx - 2] - height[idx])\n else:\n right = float('inf')\n dp[idx] = min(left, right)\n return dp[n - 1]", "import sys\n\ndef minimumenergy(height, n):\n dp = [-1] * n\n dp[0] = 0\n for i in range(1, n):\n jumpTwo = sys.maxsize\n jumpOne = dp[i - 1] + abs(height[i] - height[i - 1])\n if i > 1:\n jumpTwo = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(jumpOne, jumpTwo)\n return dp[n - 1]", "def minimumenergy(height, n):\n prev2 = 0\n curr = 0\n if n == 1:\n return 0\n prev = abs(height[1] - height[0])\n if n == 2:\n return prev\n for i in range(2, n):\n curr = min(abs(height[i] - height[i - 1]) + prev, abs(height[i] - height[i - 2]) + prev2)\n prev2 = prev\n prev = curr\n return curr", "def minimumenergy(height, n):\n prev1 = 0\n prev2 = 0\n for i in range(1, n):\n left = prev1 + abs(height[i] - height[i - 1])\n right = 1000000000.0\n if i > 1:\n right = prev2 + abs(height[i] - height[i - 2])\n curr = min(left, right)\n prev2 = prev1\n prev1 = curr\n return prev1", "def minimumenergy(height, n):\n i = n - 1\n dp = [0] * n\n for i in range(1, n):\n r = 10 ** 9 + 7\n l = dp[i - 1] + abs(height[i] - height[i - 1])\n if i > 1:\n r = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(l, r)\n return dp[-1]", "import sys\n\ndef f(n, height):\n prev = 0\n prev2 = 0\n for i in range(1, n):\n jump2 = sys.maxsize\n jump1 = prev + abs(height[i] - height[i - 1])\n if i > 1:\n jump2 = prev2 + abs(height[i] - height[i - 2])\n curr = min(jump1, jump2)\n prev2 = prev\n prev = curr\n return prev\n\ndef minimumenergy(height, n):\n return self.f(n, height)", "def minimumenergy(height, n):\n memo = {}\n return self.tab_min_energy_path(0, n - 1, height, memo)\n\ndef min_energy_path(curr_index, target_index, height, memo):\n if curr_index == target_index:\n return 0\n if memo.get(curr_index) != None:\n return memo.get(curr_index)\n one_step_cost = abs(height[curr_index] - height[curr_index + 1])\n take_one_step = one_step_cost + self.min_energy_path(curr_index + 1, target_index, height, memo)\n take_two_step = float('inf')\n if curr_index <= target_index - 2:\n two_step_cost = abs(height[curr_index] - height[curr_index + 2])\n take_two_step = two_step_cost + self.min_energy_path(curr_index + 2, target_index, height, memo)\n memo[curr_index] = min(take_one_step, take_two_step)\n return memo.get(curr_index)\n\ndef tab_min_energy_path(curr_index, target_index, height, memo):\n memo[target_index] = 0\n for index in range(target_index - 1, curr_index - 1, -1):\n one_step_cost = abs(height[index] - height[index + 1])\n take_one_step = one_step_cost + memo[index + 1]\n take_two_step = float('inf')\n if index <= target_index - 2:\n two_step_cost = abs(height[index] - height[index + 2])\n take_two_step = two_step_cost + memo[index + 2]\n memo[index] = min(take_one_step, take_two_step)\n return memo.get(curr_index)", "def minimumenergy(height, n):\n k = 2\n dp = [-1] * n\n dp[0] = 0\n for i in range(1, n):\n minerg = 10000000000.0\n for j in range(1, k + 1):\n if i - j >= 0:\n curr = dp[i - j] + abs(height[i] - height[i - j])\n minerg = min(curr, minerg)\n dp[i] = minerg\n return dp[n - 1]", "def minimumenergy(height, n):\n dp = [-1] * n\n dp[0] = 0\n if n == 1:\n return dp[n - 1]\n dp[1] = abs(height[1] - height[0])\n for i in range(2, n):\n h = height[i]\n h1 = height[i - 1]\n h2 = height[i - 2]\n onestep = abs(h - h1)\n twostep = abs(h - h2)\n dp[i] = min(onestep + dp[i - 1], twostep + dp[i - 2])\n return dp[n - 1]", "def minimumenergy(height, n):\n n = n - 1\n m = 0\n l = abs(height[n] - height[n - 1])\n for i in range(n - 2, -1, -1):\n a = abs(height[i] - height[i + 1]) + l\n b = abs(height[i] - height[i + 2]) + m\n m = l\n l = min(a, b)\n return l", "def gen(height, n, count):\n if count == n:\n return 0\n if count == n - 1:\n return abs(height[count + 1] - height[count])\n if count <= n and self.dp[count] != -1:\n return self.dp[count]\n a = self.gen(height, n, count + 1) + abs(height[count] - height[count + 1])\n if count + 2 <= n:\n b = self.gen(height, n, count + 2) + abs(height[count] - height[count + 2])\n else:\n b = 9999999999999\n self.dp[count] = min(a, b)\n return min(a, b)\n\ndef minimumenergy(height, n):\n n = n - 1\n dp = [-1] * (n + 1)\n dp[n] = 0\n dp[n - 1] = abs(height[n] - height[n - 1])\n for i in range(n - 2, -1, -1):\n a = abs(height[i] - height[i + 1]) + dp[i + 1]\n b = abs(height[i] - height[i + 2]) + dp[i + 2]\n dp[i] = min(a, b)\n return dp[0]", "from functools import lru_cache\n\ndef minimumenergy(height, n):\n dp = [-1] * n\n dp[0] = 0\n for i in range(1, n):\n j2 = float('inf')\n j1 = dp[i - 1] + abs(height[i] - height[i - 1])\n if i > 1:\n j2 = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(j1, j2)\n return dp[n - 1]", "from math import inf\n\ndef minimumenergy(height, n):\n dp = [0 for _ in range(n)]\n prev1 = 0\n prev2 = inf\n for jump in range(n - 2, -1, -1):\n one_jump = abs(height[jump] - height[jump + 1]) + prev1\n two_jump = inf\n if jump < n - 2:\n two_jump = abs(height[jump] - height[jump + 2]) + prev2\n dp[jump] = min(one_jump, two_jump)\n prev2 = prev1\n prev1 = dp[jump]\n return dp[0]", "import sys\nsys.setrecursionlimit(20000)\n\ndef __init__():\n self.h = {}\n\ndef minimumenergy(height, n):\n l = [-1] * n\n l[0] = 0\n if n >= 2:\n l[1] = abs(height[1] - height[0])\n for i in range(2, n):\n l[i] = min(abs(height[i] - height[i - 1]) + l[i - 1], abs(height[i] - height[i - 2]) + l[i - 2])\n return l[n - 1]", "def minimumenergy(arr, n):\n if n == 1 or n == 2:\n return 0 if n == 1 else abs(arr[0] - arr[1])\n ans = [0 for _ in range(n)]\n ans[0] = 0\n ans[1] = abs(arr[0] - arr[1])\n for i in range(2, n):\n diff1 = abs(arr[i] - arr[i - 1])\n diff2 = abs(arr[i] - arr[i - 2])\n ans[i] = min(diff1 + ans[i - 1], diff2 + ans[i - 2])\n return ans[n - 1]", "def minimumenergy(height, n):\n if n == 1:\n return 0\n dp = [0] * n\n dp[0] = 0\n dp[1] = abs(height[0] - height[1])\n for i in range(len(dp) - 2):\n cost1 = dp[i] + abs(height[i] - height[i + 2])\n cost2 = dp[i + 1] + abs(height[i + 1] - height[i + 2])\n if cost1 > cost2:\n dp[i + 2] = cost2\n else:\n dp[i + 2] = cost1\n return dp[n - 1]", "import sys\nsys.setrecursionlimit(10000000)\n\ndef minimumenergy(height, n):\n dp = [0] * n\n for index in range(n - 2, -1, -1):\n one = 9999999\n if index + 1 < n:\n one = abs(height[index + 1] - height[index]) + dp[index + 1]\n two = 99999999\n if index + 2 < n:\n two = abs(height[index + 2] - height[index]) + dp[index + 2]\n dp[index] = min(one, two)\n return dp[0]", "import math\n\ndef minimumenergy(height, n):\n n = len(height)\n prev2 = 0\n prev = 0\n for i in range(1, n):\n jumpone = prev + abs(height[i] - height[i - 1])\n jumptwo = math.inf\n if i > 1:\n jumptwo = prev2 + abs(height[i] - height[i - 2])\n curr = min(jumpone, jumptwo)\n prev2 = prev\n prev = curr\n return prev", "import sys\n\ndef minimumenergy(height, n):\n prev1 = 0\n prev2 = 0\n for i in range(1, n):\n step1 = prev1 + abs(height[i] - height[i - 1])\n step2 = sys.maxsize\n if i > 1:\n step2 = prev2 + abs(height[i] - height[i - 2])\n cur = min(step1, step2)\n prev2 = prev1\n prev1 = cur\n return prev1", "import sys\nimport math\n\ndef minimumenergy(height, n):\n prev = prev2 = 0\n for i in range(1, n):\n jone = abs(height[i] - height[i - 1]) + prev\n jtwo = float('inf')\n if i > 1:\n jtwo = abs(height[i] - height[i - 2]) + prev2\n curri = min(jone, jtwo)\n prev2 = prev\n prev = curri\n return prev", "import sys\nimport math\n\ndef minimumenergy(height, n):\n dp = [-1 for _ in range(n + 1)]\n dp[0] = 0\n for i in range(1, n):\n jone = abs(height[i] - height[i - 1]) + dp[i - 1]\n jtwo = float('inf')\n if i > 1:\n jtwo = abs(height[i] - height[i - 2]) + dp[i - 2]\n dp[i] = min(jone, jtwo)\n return dp[n - 1]", "import sys\n\ndef minimumenergy(arr, n):\n\n def calc(n):\n dp = [-1] * (n + 1)\n dp[0] = 0\n for i in range(1, n + 1):\n j1 = dp[i - 1] + abs(arr[i] - arr[i - 1])\n if i > 1:\n j2 = dp[i - 2] + abs(arr[i] - arr[i - 2])\n else:\n j2 = float('inf')\n dp[i] = min(j1, j2)\n return dp[n]\n return calc(n - 1)", "def f(j, arr, n, dp):\n dp[n - 1] = 0\n for j in range(n - 2, -1, -1):\n onestep = 10000000\n twostep = 10000000\n if j + 1 < n:\n onestep = abs(arr[j] - arr[j + 1]) + dp[j + 1]\n if j + 2 < n:\n twostep = abs(arr[j] - arr[j + 2]) + dp[j + 2]\n dp[j] = min(onestep, twostep)\n return dp[j]\n\ndef minimumenergy(height, n):\n dp = [-1] * n\n return self.f(0, height, n, dp)", "def minimumenergy(height, n):\n dp = [-1] * n\n dp[0] = 0\n for i in range(1, n):\n if dp[i] == -1:\n left = dp[i - 1] + abs(height[i] - height[i - 1])\n second = 9999999\n if i > 1:\n second = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(left, second)\n return dp[n - 1]", "def minEnergy(height, index):\n if index == 0:\n return 0\n if self.dp[index] != -1:\n return self.dp[index]\n left = self.minEnergy(height, index - 1) + abs(height[index] - height[index - 1])\n right = 999999\n if index > 1:\n right = self.minEnergy(height, index - 2) + abs(height[index] - height[index - 2])\n self.dp[index] = min(left, right)\n return min(left, right)\n\ndef minimumenergy(height, n):\n dp = [0 for i in range(n)]\n for i in range(1, n):\n left = dp[i - 1] + abs(height[i] - height[i - 1])\n right = int(1000000000.0)\n if i > 1:\n right = dp[i - 2] + abs(height[i] - height[i - 2])\n dp[i] = min(left, right)\n return dp[n - 1]", "from sys import setrecursionlimit\nsetrecursionlimit(10 ** 8)\n\ndef minimumenergy(height, n):\n (prev, prev1) = (0, 0)\n for i in range(1, n):\n ans1 = prev1 + abs(height[i] - height[i - 1])\n ans2 = float('inf')\n if i > 1:\n ans2 = prev2 + abs(height[i] - height[i - 2])\n curr = min(ans1, ans2)\n prev2 = prev1\n prev1 = curr\n return prev1", "from sys import setrecursionlimit\nsetrecursionlimit(10 ** 8)\n\ndef minimumenergy(height, n):\n dp = [0 for i in range(n)]\n dp[n - 1] = 0\n for i in range(n - 2, -1, -1):\n ans1 = dp[i + 1] + abs(height[i] - height[i + 1])\n ans2 = float('inf')\n if i < n - 2:\n ans2 = dp[i + 2] + abs(height[i] - height[i + 2])\n dp[i] = min(ans1, ans2)\n return dp[0]"], "starter_code": "def minimumenergy(height, n):\n", "input_output": {"inputs": ["n = 4\r\nheight = {10 20 30 10}"], "outputs": ["20"]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/geek-jump/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "minimumenergy", "task_id": "TACO_lite/122", "example": [[[4, [10, 20, 30, 10]]], [null]]} +{"requirement": "Mary wrote a recipe book and is about to publish it, but because of a new European law, she needs to update and include all measures in grams.\n\nGiven all the measures in tablespoon (`tbsp`) and in teaspoon (`tsp`), considering `1 tbsp = 15g` and `1 tsp = 5g`, append to the end of the measurement the biggest equivalent integer (rounding up).\n\n## Examples\n\n```\n\"2 tbsp of butter\" --> \"2 tbsp (30g) of butter\"\n\n\"1/2 tbsp of oregano\" --> \"1/2 tbsp (8g) of oregano\"\n\n\"1/2 tsp of salt\" --> \"1/2 tbsp (3g) of salt\"\n\n\"Add to the mixing bowl and coat well with 1 tbsp of olive oil & 1/2 tbsp of dried dill\" -->\n\"Add to the mixing bowl and coat well with 1 tbsp (15g) of olive oil & 1/2 tbsp (8g) of dried dill\"\n```", "solutions": ["import re, math\n\ndef convert_recipe(recipe):\n\n def repl(m):\n ratio = 15 if m.group(2) == 'tbsp' else 5\n return m.group(0) + ' (%sg)' % math.ceil(eval(m.group(1)) * ratio)\n return re.sub('([0-9/]+) (tb?sp)', repl, recipe)", "import re\nimport math\n\ndef convert_recipe(recipe):\n return re.sub('(\\\\d+\\\\/\\\\d+|\\\\d+) (tbsp|tsp)', lambda x: x.group(1) + ' ' + x.group(2) + ' ' + '(' + str(math.ceil(eval(x.group(1)) * {'tbsp': 15, 'tsp': 5}[x.group(2)])) + 'g)', recipe)", "import re\nfrom math import ceil\nfrom fractions import Fraction\n\ndef convert(m, units={'tbsp': 15, 'tsp': 5}):\n (amount, unit) = m.groups()\n gram = int(ceil(Fraction(amount) * units[unit]))\n return f'{m.group()} ({gram}g)'\n\ndef convert_recipe(recipe):\n return re.sub('(\\\\S+) (tb?sp)', convert, recipe)", "import re\nfrom math import ceil\nP_RECIPE = re.compile('([\\\\d/]+) (tb?sp)')\n\ndef convert_recipe(recipe):\n return P_RECIPE.sub(update, recipe)\n\ndef update(m):\n toGrams = ceil(eval(m.group(1)) * (15 if m.group(2) == 'tbsp' else 5))\n return '{} {} ({}g)'.format(m.group(1), m.group(2), toGrams)", "from math import ceil\nimport re\n\ndef convert_recipe(recipe):\n spoons = set(re.findall('[^ ]+ tb?sp', recipe))\n for spoon in spoons:\n (qty, typ) = spoon.split(' ')\n wgt = ceil({'tsp': 5, 'tbsp': 15}[typ] * eval(qty))\n recipe = re.sub(f'(^| ){spoon}', f'\\\\g<1>{spoon} ({wgt}g)', recipe)\n return recipe", "import re, math\n\ndef convert_recipe(recipe):\n r = re.sub('((\\\\d+(/\\\\d+)?) tbsp)', tbsp, recipe)\n r = re.sub('((\\\\d+(/\\\\d+)?) tsp)', tsp, r)\n return r\n\ndef tbsp(m):\n return m.group(1) + ' (' + str(math.ceil(eval('15*' + m.group(2)))) + 'g)'\n\ndef tsp(m):\n return m.group(1) + ' (' + str(math.ceil(eval('5*' + m.group(2)))) + 'g)'", "from math import ceil\n\ndef convert_recipe(recipe):\n l = []\n l_recipe = recipe.split()\n for (num, i) in enumerate(l_recipe):\n if i == 'tbsp':\n tmp = l_recipe[num - 1]\n weight = ceil(eval(tmp) * 15) if '/' in tmp else int(tmp) * 15\n l.append('tbsp ({}g)'.format(weight))\n elif i == 'tsp':\n tmp = l_recipe[num - 1]\n weight = ceil(eval(tmp) * 5) if '/' in tmp else int(tmp) * 5\n l.append('tsp ({}g)'.format(weight))\n else:\n l.append(i)\n return ' '.join(l)", "from math import ceil\n\ndef f(number, spoon):\n measure = 15 if spoon == 'tbsp' else 5\n grams = ceil(eval(f'{measure} * {number}'))\n return f'({grams}g)'\n\ndef convert_recipe(recipe):\n seq = recipe.split()\n res = []\n for (i, word) in enumerate(seq):\n res.append(word)\n if word in ('tbsp', 'tsp'):\n res.append(f(seq[i - 1], word))\n return ' '.join(res)", "import re\nfrom math import *\n\ndef convert_recipe(s):\n d = {'tsp': 5, 'tbsp': 15}\n matches = re.findall('\\\\d*/?\\\\d+ tbsp|\\\\d*/?\\\\d+ tsp', s)\n for m in matches:\n (v, k) = m.split()\n x = eval(f'ceil({d.get(k)} * {v})')\n s = s.replace(m, f'{m} ({x}g)', 1)\n return s", "def convert_recipe(recipe):\n import math\n out = []\n for x in recipe.split(' '):\n if x in ['tbsp', 'tsp']:\n calc = math.ceil(eval('{}*{}'.format(out[-1], '15' if x == 'tbsp' else '5')))\n out.append(x)\n out.append('({}g)'.format(calc))\n else:\n out.append(x)\n return ' '.join(out)"], "starter_code": "def convert_recipe(recipe):\n", "input_output": {"fn_name": "convert_recipe", "inputs": [["2 tbsp of butter"], ["Add to the mixing bowl and coat well with 1 tbsp of olive oil & 1/2 tbsp of dried dill"], ["1/2 tsp of baking powder"], ["In another bowl, add 2 tsp of vanilla extract, 3 tsp of baking soda and 1/2 tsp of salt"], ["10 tbsp of cocoa powder"], ["1/8 tbsp of baking soda"], ["In a large bowl, combine confectioners' sugar, sour cream and vanilla"]], "outputs": [["2 tbsp (30g) of butter"], ["Add to the mixing bowl and coat well with 1 tbsp (15g) of olive oil & 1/2 tbsp (8g) of dried dill"], ["1/2 tsp (3g) of baking powder"], ["In another bowl, add 2 tsp (10g) of vanilla extract, 3 tsp (15g) of baking soda and 1/2 tsp (3g) of salt"], ["10 tbsp (150g) of cocoa powder"], ["1/8 tbsp (2g) of baking soda"], ["In a large bowl, combine confectioners' sugar, sour cream and vanilla"]]}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5acfab8d23c81836c90000eb", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "convert_recipe", "task_id": "TACO_lite/61", "example": [[["2 tbsp of butter"], ["1/2 tbsp of oregano"], ["1/2 tsp of salt"], ["Add to the mixing bowl and coat well with 1 tbsp of olive oil & 1/2 tbsp of dried dill"]], ["2 tbsp (30g) of butter", "1/2 tbsp (8g) of oregano", "1/2 tsp (3g) of salt", "Add to the mixing bowl and coat well with 1 tbsp (15g) of olive oil & 1/2 tbsp (8g) of dried dill"]]} +{"requirement": "Given two given numbers a and b where 1<=a<=b, find the number of perfect squares between a and b (a and b inclusive).\n \nExample 1:\nInput:\na = 9, b = 25\nOutput:\n3\nExplanation:\nThere are 3 perfect squares between 9\nand 25. They are 9, 16, and 25.\nExample 2:\nInput:\na = 1, b = 7\nOutput:\n2\nExplanation:\nThere are 2 perfect squares between 1\nand 7. They are 1, and 4.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function numOfPerfectSquares() which takes 2 Integers a and b as input and returns the number of perfect squares between a and b.\n \nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= a <= b <= 10^{5}", "solutions": ["def numofperfectsquares(a, b):\n sum = 0\n c = int(b ** 0.5) + 1\n for i in range(1, c):\n if i ** 2 >= a and i ** 2 <= b:\n sum += 1\n else:\n continue\n return sum", "def numofperfectsquares(a, b):\n a = math.sqrt(a)\n b = math.sqrt(b)\n if a == int(a) or b == int(b):\n return int(b - a) + 1\n elif a == int(a) and b == int(b):\n return int(b) - int(a) + 1\n else:\n return int(b) - int(a)", "from math import *\n\ndef numofperfectsquares(a, b):\n num = ceil(sqrt(a))\n count = 0\n while pow(num, 2) <= b:\n count += 1\n num += 1\n return count", "def numofperfectsquares(a, b):\n c = int(a ** 0.5)\n d = int(b ** 0.5)\n c = 0\n for i in range(c, d + 1):\n if i ** 2 >= a:\n if i ** 2 <= b:\n c += 1\n return c", "def numofperfectsquares(a, b):\n sum = 0\n for x in range(1, 200):\n d = x * x\n if d <= b and d >= a:\n sum = sum + 1\n return sum", "import math\n\ndef numofperfectsquares(a, b):\n count_b = math.floor(math.sqrt(b))\n count_a = math.floor(math.sqrt(a - 1))\n return count_b - count_a", "def numofperfectsquares(a, b):\n return math.floor(math.sqrt(b)) - math.ceil(math.sqrt(a)) + 1", "import math\n\ndef numofperfectsquares(a, b):\n x = math.sqrt(a)\n if x == int(x):\n return int(math.sqrt(b)) - int(math.sqrt(a)) + 1\n else:\n return int(math.sqrt(b)) - int(math.sqrt(a))", "import math\n\ndef numofperfectsquares(a, b):\n num1 = math.ceil(math.sqrt(a))\n num2 = math.floor(math.sqrt(b))\n return num2 - num1 + 1", "def numofperfectsquares(a, b):\n x = int(a ** 0.5)\n y = int(b ** 0.5)\n if x != a ** 0.5:\n x += 1\n return y - x + 1", "import math\n\ndef numofperfectsquares(a, b):\n x = math.ceil(math.sqrt(a))\n y = math.sqrt(b)\n x1 = int(x)\n y1 = int(y)\n return y1 - x1 + 1", "def numofperfectsquares(a, b):\n i = 1\n K = []\n while i * i <= b:\n if i * i >= a:\n K.append(i * i)\n i += 1\n return len(K)", "from math import sqrt\n\ndef numofperfectsquares(a, b):\n count = 0\n for i in range(int(sqrt(a)), int(sqrt(b) + 1)):\n if i * i >= a and i * i <= b:\n count += 1\n return count", "def numofperfectsquares(a: int, b: int) -> int:\n\n def isPerfectSquare(num: int) -> bool:\n z = int(num ** 0.5)\n return z * z == num\n x = int(b ** 0.5)\n y = int(a ** 0.5)\n if isPerfectSquare(a):\n return x - y + 1\n else:\n return x - y", "from math import sqrt\n\ndef numofperfectsquares(a, b):\n if a > b:\n (a, b) = (b, a)\n a = int(sqrt(a)) if int(sqrt(a)) * int(sqrt(a)) == a else int(sqrt(a) + 1)\n b = int(sqrt(b)) + 1\n return abs(b - a)", "def numofperfectsquares(a, b):\n import math\n self.a = a\n self.b = b\n p = math.sqrt(a)\n q = math.sqrt(b)\n p = math.floor(q) - math.ceil(p) + 1\n return p", "def numofperfectsquares(a, b):\n count = 0\n x = math.sqrt(a)\n y = int(math.sqrt(b))\n if x != int(x):\n x = int(x) + 1\n count = int(y) - int(x) + 1\n return count", "import math\n\ndef numofperfectsquares(a, b):\n x = math.sqrt(a)\n y = int(math.sqrt(b))\n if x != int(x):\n x = int(x) + 1\n z = y - int(x) + 1\n return z", "import math\n\ndef numofperfectsquares(a, b):\n return int(math.sqrt(b)) - math.ceil(math.sqrt(a)) + 1", "import math\n\ndef numofperfectsquares(a, b):\n x = int(math.sqrt(a))\n y = int(math.sqrt(b))\n count = 0\n for i in range(x, y + 1):\n z = i * i\n if z >= a and z <= b:\n count += 1\n return count", "def numofperfectsquares(a, b):\n i = 1\n c = 0\n while i <= math.floor(math.sqrt(b)):\n if i * i >= a and i * i <= b:\n c += 1\n i += 1\n return c", "def numofperfectsquares(a, b):\n x = int(a ** 0.5)\n y = int(b ** 0.5)\n count = 0\n for i in range(x, y + 1):\n if i ** 2 >= a and i ** 2 <= b:\n count += 1\n return count", "import math\n\ndef numofperfectsquares(a, b):\n sa = math.sqrt(a)\n sb = math.sqrt(b)\n if sa % 1 != 0:\n sa = int(sa) + 1\n if sb % 1 != 0:\n sb = int(sb)\n return int(sb - sa + 1)", "from math import *\n\ndef numofperfectsquares(a, b):\n count = 0\n for i in range(ceil(sqrt(a)), floor(sqrt(b)) + 1):\n count += 1\n return count", "def numofperfectsquares(a, b):\n return math.floor(b ** 0.5) - math.ceil(a ** 0.5) + 1", "def numofperfectsquares(a, b):\n t1 = math.ceil(math.sqrt(a)) - 1\n t2 = math.sqrt(b) if math.sqrt(b) == int(math.sqrt(b)) else math.ceil(math.sqrt(b)) - 1\n return int(t2 - t1)", "def numofperfectsquares(a, b):\n count = 0\n for i in range(1, b + 1):\n ans = i * i\n if (ans >= a) & (ans <= b):\n count += 1\n elif ans >= b:\n break\n return count", "import math\n\ndef numofperfectsquares(a, b):\n x = math.ceil(a ** 0.5)\n b = int(b ** 0.5)\n return b - x + 1", "import math\n\ndef numofperfectsquares(a, b):\n lower_sqrt = math.sqrt(a)\n upper_sqrt = math.sqrt(b)\n lower = math.ceil(lower_sqrt)\n upper = math.floor(upper_sqrt)\n return upper - lower + 1", "import math\n\ndef numofperfectsquares(a, b):\n sq1 = int(math.sqrt(a))\n sq2 = int(math.sqrt(b))\n if sq1 * sq1 == a and sq2 ** sq2 == b:\n return sq2 - sq1 + 1\n if sq1 * sq1 == a:\n return sq2 - sq1 + 1\n else:\n return sq2 - sq1", "from math import ceil, floor\n\ndef numofperfectsquares(a, b):\n count = 0\n n1 = int(a ** (1 / 2))\n n2 = int(b ** (1 / 2))\n for i in range(n1, n2 + 1):\n if i * i <= b and i * i >= a:\n count += 1\n return count", "def numofperfectsquares(a, b):\n count = 0\n s1 = int(pow(a, 0.5))\n s2 = int(pow(b, 0.5))\n for i in range(s1, s2 + 1):\n if i * i >= a and i * i <= b:\n count += 1\n return count", "import math\n\ndef numofperfectsquares(a, b):\n sqra = int(math.sqrt(a))\n sqrb = int(math.sqrt(b))\n if a == sqra * sqra:\n sqrb += 1\n return sqrb - sqra", "def numofperfectsquares(a, b):\n m1 = math.sqrt(a)\n m2 = math.sqrt(b)\n if int(m1) * int(m1) == a or int(m2) * int(m2) == b:\n return int(abs(m2 - m1 + 1))\n return abs(int(m2) - int(m1))", "import math\n\ndef numofperfectsquares(a, b):\n a1 = int(math.sqrt(a))\n b1 = int(math.sqrt(b))\n x = [a1]\n if a == a1 * a1:\n return b1 - a1 + 1\n else:\n return b1 - a1\n return len(x)", "def numofperfectsquares(a, b):\n return int(int(b ** 0.5) - a ** 0.5 + 1)", "import math\n\ndef numofperfectsquares(a, b):\n k = 0\n t = int(math.sqrt(a))\n t1 = int(math.sqrt(b))\n for i in range(t, t1 + 1):\n if i ** 2 <= b and i ** 2 >= a:\n k += 1\n return k", "def numofperfectsquares(a, b):\n c = 0\n for i in range(int(pow(a, 0.5)), int(pow(b, 0.5) + 1)):\n if i * i >= a and i * i <= b:\n c = c + 1\n return c", "import math\n\ndef numofperfectsquares(a, b):\n f = math.ceil(math.sqrt(a))\n l = math.floor(math.sqrt(b))\n return l - f + 1"], "starter_code": "def numofperfectsquares(a, b):\n", "input_output": {"inputs": ["a = 9, b = 25", "a = 1, b = 7"], "outputs": ["3", "2"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/perfect-squares-in-a-range2253/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "numofperfectsquares", "task_id": "TACO_lite/140", "example": [[[9, 25], [1, 7]], ["3", "2"]]} +{"requirement": "# Task\n The number is considered to be `unlucky` if it does not have digits `4` and `7` and is divisible by `13`. Please count all unlucky numbers not greater than `n`.\n\n# Example\n\n For `n = 20`, the result should be `2` (numbers `0 and 13`).\n \n For `n = 100`, the result should be `7` (numbers `0, 13, 26, 39, 52, 65, and 91`)\n \n# Input/Output\n\n\n - `[input]` integer `n`\n\n `1 \u2264 n \u2264 10^8(10^6 in Python)`\n\n\n - `[output]` an integer", "solutions": ["def unlucky_number(n):\n return sum((not ('4' in s or '7' in s) for s in map(str, range(0, n + 1, 13))))", "def unlucky_number(n):\n return sum((1 for k in range(0, n + 1, 13) if not set(str(k)) & {'4', '7'}))", "def unlucky_number(n):\n return sum((x % 13 == 0 and '4' not in str(x) and ('7' not in str(x)) for x in range(n + 1)))", "def unlucky_number(n):\n return len([i for i in range(1, n + 1) if i % 13 == 0 and str(i).count('4') == 0 and (str(i).count('7') == 0)]) + 1", "def unlucky_number(n):\n return sum((1 for n in range(0, n + 1, 13) if set(str(n)) & set('47') == set()))", "unlucky_number = lambda n: sum((not {'4', '7'} & set(str(x)) for x in range(0, n + 1, 13)))", "li = [i for i in range(0, 1000000, 13) if '4' not in str(i) and '7' not in str(i)]\nunlucky_number = lambda n: next((len(li[:li.index(i)]) + 1 for i in range(n, -1, -1) if '4' not in str(i) and '7' not in str(i) and (not i % 13)))"], "starter_code": "def unlucky_number(n):\n", "input_output": {"fn_name": "unlucky_number", "inputs": [[20], [100], [1000], [1000000]], "outputs": [[2], [7], [40], [20182]]}, "difficulty": "EASY", "raw_tags": ["Puzzles"], "name": null, "source": "codewars", "tags": ["Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/58b65c5e8b98b2e4fa000034", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "unlucky_number", "task_id": "TACO_lite/137", "example": [[[20], [100]], ["2", "7"]]} +{"requirement": "Don't Drink the Water\n\nGiven a two-dimensional array representation of a glass of mixed liquids, sort the array such that the liquids appear in the glass based on their density. (Lower density floats to the top) The width of the glass will not change from top to bottom.\n\n```\n======================\n| Density Chart |\n======================\n| Honey | H | 1.36 |\n| Water | W | 1.00 |\n| Alcohol | A | 0.87 |\n| Oil | O | 0.80 |\n----------------------\n\n[ [\n ['H', 'H', 'W', 'O'], ['O','O','O','O']\n ['W', 'W', 'O', 'W'], => ['W','W','W','W']\n ['H', 'H', 'O', 'O'] ['H','H','H','H']\n ] ]\n \n ```\n \n The glass representation may be larger or smaller. If a liquid doesn't fill a row, it floats to the top and to the left.", "solutions": ["DENSITY = {'H': 1.36, 'W': 1, 'A': 0.87, 'O': 0.8}\n\ndef separate_liquids(glass):\n if not glass:\n return []\n column = len(glass[0])\n liquids = sorted((b for a in glass for b in a), key=lambda c: DENSITY[c])\n return [liquids[d:d + column] for d in range(0, len(liquids), column)]", "def separate_liquids(glass):\n chain = sorted(sum(glass, []), key='OAWH'.index)\n return [chain[len(level) * i:][:len(level)] for (i, level) in enumerate(glass)]", "s = '| Honey | H | 1.36 |\\n| Water | W | 1.00 |\\n| Alcohol | A | 0.87 |\\n| Oil | O | 0.80 |'\n\ndef separate_liquids(glass):\n d = {}\n for x in s.split('\\n'):\n res = x.split('|')\n (a, b) = [c.strip(' ') for (i, c) in enumerate(res) if i in (2, 3)]\n d[a] = float(b)\n l = []\n for x in glass:\n l.extend(x)\n result = iter(sorted(l, key=lambda x: d[x]))\n for x in range(len(glass)):\n for i in range(len(glass[-1])):\n glass[x][i] = next(result)\n return glass", "def separate_liquids(glass):\n chain = sorted(sum(glass, []), key='HWAO'.index)\n return [[chain.pop() for c in ro] for ro in glass]", "density_order = {key: i for (i, key) in enumerate(['O', 'A', 'W', 'H'])}\n\ndef separate_liquids(glass):\n lst_of_liquids = iter(sorted([liquid for row in glass for liquid in row], key=lambda d: density_order[d]))\n return [[next(lst_of_liquids) for j in range(0, len(glass[0]))] for i in range(0, len(glass))]", "density = {'H': 4, 'W': 3, 'A': 2, 'O': 1}\n\ndef separate_liquids(glass):\n glass_ = sorted([x for i in glass for x in i], key=lambda elem: density.get(elem))\n for row in glass:\n for i in range(len(row)):\n row[i] = glass_.pop(0)\n return glass", "def separate_liquids(glass):\n liquids = []\n comparing = {'H': 1.36, 'W': 1.0, 'A': 0.87, 'O': 0.8}\n for row in glass:\n liquids.extend(row)\n liquids.sort(key=lambda k: comparing[k], reverse=True)\n for i in range(len(glass)):\n for j in range(len(glass[0])):\n glass[i][j] = liquids.pop()\n return glass"], "starter_code": "def separate_liquids(glass):\n", "input_output": {"fn_name": "separate_liquids", "inputs": [[[["H", "H", "W", "O"], ["W", "W", "O", "W"], ["H", "H", "O", "O"]]], [[["A", "A", "O", "H"], ["A", "H", "W", "O"], ["W", "W", "A", "W"], ["H", "H", "O", "O"]]], [[["A", "H", "W", "O"]]], [[["A"], ["H"], ["W"], ["O"]]], [[]]], "outputs": [[[["O", "O", "O", "O"], ["W", "W", "W", "W"], ["H", "H", "H", "H"]]], [[["O", "O", "O", "O"], ["A", "A", "A", "A"], ["W", "W", "W", "W"], ["H", "H", "H", "H"]]], [[["O", "A", "W", "H"]]], [[["O"], ["A"], ["W"], ["H"]]], [[]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms", "Sorting", "Lists"], "name": null, "source": "codewars", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/562e6df5cf2d3908ad00019e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "separate_liquids", "task_id": "TACO_lite/96", "example": [[[[["H", "H", "W", "O"], ["W", "W", "O", "W"], ["H", "H", "O", "O"]]]], ["[['O', 'O', 'O', 'O'], ['W', 'W', 'W', 'W'], ['H', 'H', 'H', 'H']]"]]} +{"requirement": "Given a number N, find if it is Disarium or not. A number is called Disarium if sum of its digits powered with their respective positions is equal to the number itself. Output 1 if it's Disarium, and 0 if not.\n \nExample 1:\nInput:\nN = 89\nOutput:\n1\nExplanation:\n8^1+9^2 = 89 thus output is 1.\nExample 2:\nInput:\nN = 81\nOutput:\n0\nExplanation:\n8^1+1^2 = 9 thus output is 0. \n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function isDisarium() which takes an Integer N as input and returns the answer.\n \nExpected Time Complexity: O(log(N))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n0 <= N <= 10^{8}", "solutions": ["def isdisarium(N):\n summ = 0\n k = 1\n for i in str(N):\n summ += int(i) ** k\n k += 1\n if summ == N:\n return 1\n return 0", "def isdisarium(N):\n N = str(N)\n x = 0\n for i in range(len(N)):\n x += int(N[i]) ** (i + 1)\n if x == int(N):\n return 1\n return 0", "def isdisarium(n):\n m = n\n count = 0\n while m:\n count += 1\n m = m // 10\n k = n\n num = 0\n while k:\n l = k % 10\n num += l ** count\n count -= 1\n k = k // 10\n return 1 if n == num else 0", "def isdisarium(N):\n l = [i for i in str(N)]\n c = 0\n for i in range(1, len(l) + 1):\n c += pow(int(l[i - 1]), i)\n if N == c:\n return 1\n else:\n return 0", "def isdisarium(N):\n n = str(N)\n a = 0\n sum = 0\n for i in range(len(n)):\n a = pow(int(n[i]), i + 1)\n sum = sum + a\n if sum == N:\n return 1\n return 0", "def isdisarium(N):\n y = 0\n x = N\n sum = 0\n for i in range(len(str(N))):\n y = x % 10\n sum += y ** len(str(x))\n x = x // 10\n if sum == N:\n return 1\n return 0", "def isdisarium(N):\n count = len(str(N))\n sum = 0\n x = N\n while x != 0:\n r = x % 10\n sum = int(sum + pow(r, count))\n count = count - 1\n x = x // 10\n if sum == N:\n return 1\n else:\n return 0", "def digitCount(num, count):\n if num == 0:\n return count\n else:\n count += 1\n return self.digitCount(num // 10, count)\n\ndef Calcsum(num, digit):\n if num == 0:\n return 0\n else:\n return pow(num % 10, digit) + self.Calcsum(num // 10, digit - 1)\n\ndef isdisarium(N):\n count = 0\n totdigit = self.digitCount(N, count)\n x = self.Calcsum(N, totdigit)\n if N == x:\n return 1\n else:\n return 0", "def isdisarium(N):\n temp = N\n sume = 0\n x = len(str(N))\n while int(N) != 0:\n d = int(N) % 10\n N = int(N) // 10\n sume += pow(d, x)\n x -= 1\n if sume == temp:\n return 1\n else:\n return 0", "def countd(num, count):\n if num == 0:\n return count\n else:\n count += 1\n return countd(num // 10, count)\n\ndef calcsum(num, count):\n if num == 0:\n return 0\n else:\n return pow(num % 10, count) + calcsum(num // 10, count - 1)\n\ndef isdisarium(N):\n count = countd(N, 0)\n num1 = calcsum(N, count)\n if num1 == N:\n return 1\n return 0", "def isdisarium(N):\n power = 1\n sum1 = 0\n for i in str(N):\n sum1 = sum1 + int(i) ** power\n power += 1\n if sum1 == N:\n return 1\n return 0", "def isdisarium(N):\n n = N\n num_digits = 0\n while n > 0:\n num_digits += 1\n n //= 10\n n = N\n sum1 = 0\n while n > 0:\n digit = n % 10\n sum1 += digit ** num_digits\n num_digits -= 1\n n //= 10\n if N == sum1:\n return 1\n else:\n return 0", "import math\n\ndef isdisarium(N):\n x = N\n sum = 0\n length = len(str(N))\n while x != 0:\n temp = x % 10\n sum = sum + math.pow(temp, length)\n length -= 1\n x = x // 10\n if sum == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n ans = 0\n n = len(str(N))\n a = str(N)\n\n def sol(ans, i):\n if i == n:\n return 0\n return ans + int(a[i]) ** (i + 1) + sol(ans, i + 1)\n return int(N == sol(0, 0))", "def isdisarium(N):\n\n def rec(new, leng, sum):\n if sum == N and new == 0:\n return 1\n if new == 0 or leng < 0:\n return 0\n rem = new % 10\n new = new // 10\n sum += rem ** leng\n return rec(new, leng - 1, sum)\n s = str(N)\n leng = len(s)\n return rec(N, leng, 0)", "def isdisarium(N):\n sum = 0\n s = [int(x) for x in str(N)]\n k = len(s)\n for i in range(0, k):\n sum = sum + s[i] ** (i + 1)\n if sum == N:\n return 1\n else:\n return 0", "def isdisarium(n):\n p = n\n s = 0\n i = len(str(n))\n while n > 0:\n a = n % 10\n k = pow(a, i)\n i -= 1\n s = s + k\n n = n // 10\n if s == p:\n return 1\n return 0", "def isdisarium(N):\n su = 0\n l = []\n a = N\n while N > 0:\n l.append(N % 10)\n N = N // 10\n l = l[::-1]\n for i in range(len(l)):\n su = su + l[i] ** (i + 1)\n if su == a:\n return 1\n else:\n return 0", "def check(l, i, n, sum):\n if sum == int(l):\n return 1\n if i == n:\n return 0\n sum += int(l[i]) ** (i + 1)\n return self.check(l, i + 1, n, sum)\n\ndef isdisarium(N):\n s = str(N)\n return self.check(s, 0, len(s), 0)", "def isdisarium(N):\n ans = 0\n a = str(N)\n for i in range(len(str(N))):\n ans += int(a[i]) ** (i + 1)\n return int(N == ans)", "def solve(n, i, s):\n if s == int(n):\n return 1\n if i == len(n):\n return 0\n return self.solve(n, i + 1, s + int(n[i]) ** (i + 1))\n\ndef isdisarium(N):\n return self.solve(str(N), 0, 0)", "import math\n\ndef isdisarium(N):\n\n def length(N):\n c = 0\n while N != 0:\n c += 1\n N = N // 10\n return c\n l = length(N)\n (dn, s) = (N, 0)\n while dn > 0:\n s += math.pow(dn % 10, l)\n dn = dn // 10\n l -= 1\n if s == N:\n return 1\n return 0", "def isdisarium(N):\n r = N\n s = len(str(N))\n sum = 0\n while N > 0:\n d = N % 10\n sum = sum + d ** s\n s -= 1\n N //= 10\n if sum == r:\n return 1\n else:\n return 0", "def isdisarium(N):\n b = N\n a = 0\n s = len(str(N))\n c = 0\n while N > 0:\n r = N % 10\n c = c + r ** s\n s = s - 1\n N = N // 10\n if b == c:\n return 1\n else:\n return 0", "def isdisarium(N):\n s = str(N)\n r = len(s) - 1\n i = 0\n d = 0\n while i <= r:\n p = s[i]\n p = int(p)\n i = i + 1\n p = p ** i\n d = d + p\n if d == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n ans = 0\n li = []\n temp = N\n while N:\n d = N % 10\n N = N // 10\n li.append(d)\n x = 1\n for i in range(len(li) - 1, -1, -1):\n ans += li[i] ** x\n x += 1\n if ans == temp:\n return 1\n return 0", "def isdisarium(N):\n Nn = list(str(N))\n m = list(map(int, Nn))\n t = 0\n for i in range(len(m)):\n t += m[i] ** (i + 1)\n if t == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n (k, res, x) = (len(str(N)), 0, N)\n for i in range(k, 0, -1):\n rem = N % 10\n res += pow(rem, i)\n N //= 10\n return 1 if res == x else 0", "def isdisarium(N: int) -> int:\n number = N\n exponent = len(str(N))\n result = 0\n while number:\n result += (number % 10) ** exponent\n exponent -= 1\n number //= 10\n return 1 if result == N else 0", "def isdisarium(N):\n number = N\n length = len(str(N))\n ans = 0\n while N != 0:\n digit = N % 10\n N = N // 10\n ans += digit ** length\n length -= 1\n if ans == number:\n return 1\n return 0", "def isdisarium(N):\n a = 0\n b = 1\n n = str(N)\n for x in n:\n a = a + int(x) ** b\n b += 1\n if a == N:\n return 1\n return 0", "def isdisarium(N):\n s = 0\n n = str(N)\n for i in range(len(n)):\n s = s + int(n[i]) ** (i + 1)\n if s == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n sum = 0\n j = 1\n s = str(N)\n for i in s:\n sum += pow(int(i), j)\n j += 1\n if sum == N:\n return 1\n return 0", "def isdisarium(N):\n n = str(N)\n rn = ''.join(reversed(n))\n x = int(rn)\n s = 0\n i = 1\n while x != 0:\n r = x % 10\n s = s + pow(r, i)\n i = i + 1\n x = x // 10\n if s == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n s = 0\n N = str(N)\n for i in range(len(N)):\n a = N[i]\n b = int(a) ** (i + 1)\n s += b\n if s == int(N):\n return 1\n return 0", "def isdisarium(N):\n s = list(map(lambda x: int(x), str(N)))\n total = 0\n for itr in range(len(s)):\n total += s[itr] ** (itr + 1)\n return 1 if total == N else 0", "def isdisarium(N):\n temp = N\n l = len(str(N))\n sum = 0\n while N > 0:\n sum += (N % 10) ** l\n l -= 1\n N //= 10\n if sum == temp:\n return 1\n else:\n return 0", "def isdisarium(N):\n digits = [int(d) for d in str(N)]\n digit_sum = 0\n for i in range(len(digits)):\n digit_sum += digits[i] ** (i + 1)\n return 1 if digit_sum == N else 0", "def isdisarium(N):\n l = []\n s = 0\n k = []\n temp = N\n while N:\n i = N % 10\n N = N // 10\n l.append(i)\n l = l[::-1]\n for i in range(len(l)):\n s = l[i] ** (i + 1)\n k.append(s)\n if sum(k) == temp:\n return 1\n return 0", "def isdisarium(N):\n copy = N\n s = str(N)\n x = 0\n n = len(s)\n for i in range(len(s)):\n x += pow(N % 10, n - i)\n N = N // 10\n if x == copy:\n return 1\n else:\n return 0", "def isdisarium(N):\n s = 0\n c = 1\n for i in str(N):\n m = int(i) ** c\n s += m\n c += 1\n return 1 if N == s else 0", "import math\n\ndef isdisarium(N):\n N = str(N)\n s = 0\n for i in range(len(N)):\n s = s + math.pow(int(N[i]), i + 1)\n if int(s) == int(N):\n return 1\n else:\n return 0", "def isdisarium(N):\n l = list(str(N))\n s = 0\n for x in range(len(l)):\n s += int(l[x]) ** (x + 1)\n if s == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n p = str(N)\n s = 0\n r = N\n w = len(p)\n while N != 0:\n d = N % 10\n s = s + int(pow(d, w))\n w = w - 1\n N = N // 10\n if r == s:\n return 1\n return 0", "def isdisarium(N):\n a = 0\n s = str(N)\n for i in range(len(s)):\n x = i + 1\n a += pow(int(s[i]), x)\n if a == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n (s, p, j) = (0, 0, 1)\n h = N\n while N > 0:\n s = 10 * s + N % 10\n N //= 10\n while s > 0:\n p += (s % 10) ** j\n j += 1\n s //= 10\n return 1 if h == p else 0", "def isdisarium(N):\n S = str(N)\n count = len(S)\n marker = count - 1\n new_N = 0\n while count > 0:\n new_N += int(S[marker]) ** count\n count -= 1\n marker -= 1\n if new_N == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n self.N = N\n count = 0\n j = 1\n for i in str(self.N):\n count += int(i) ** j\n j += 1\n if count == self.N:\n return 1\n else:\n return 0", "def isdisarium(n):\n x = str(n)\n x = [int(i) for i in x]\n k = 0\n for i in range(len(x)):\n k += x[i] ** (i + 1)\n if k == n:\n return 1\n else:\n return 0", "def isdisarium(N):\n sum = 0\n num = str(N)\n for j in range(len(num)):\n sum += int(num[j]) ** (j + 1)\n if sum == N:\n return 1\n else:\n return 0", "import math\n\ndef isdisarium(N):\n R = str(N)\n l = [int(i) for i in R]\n sum = 0\n for i in range(len(l)):\n sum = int(sum + math.pow(l[i], i + 1))\n if sum == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n sum = 0\n power = 1\n for i in str(N):\n sum += pow(int(i), power)\n power += 1\n if sum == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n s = 0\n for (p, i) in enumerate(str(N)):\n s += int(i) ** (p + 1)\n if s == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n s = str(N)\n n = len(s)\n res = 0\n t = N\n for i in range(n, 0, -1):\n res += (N % 10) ** i\n N = N // 10\n if res == t:\n return 1\n return 0", "def isdisarium(N):\n l = []\n a = str(N)\n for i in range(1, len(a) + 1):\n l.append(int(a[i - 1]) ** i)\n p = sum(l)\n if p == N:\n return 1\n else:\n return 0", "def isdisarium(N):\n x = 0\n y = N\n z = len(str(N))\n while N > 0:\n a = N % 10\n x = x + pow(a, z)\n N = N // 10\n z = z - 1\n if x == y:\n return 1\n else:\n return 0", "def isdisarium(N):\n total_sum = 0\n position = 1\n for digit in str(N):\n total_sum += pow(int(digit), position)\n position += 1\n return 1 if total_sum == N else 0", "def isdisarium(N):\n s_num = str(N)\n c = len(s_num)\n sum1 = 0\n dup = N\n while N != 0:\n sum1 += pow(N % 10, c)\n N = N // 10\n c -= 1\n if sum1 == dup:\n return 1\n return 0", "def isdisarium(N):\n N = str(N)\n sum = 0\n for (idx, i) in enumerate(N):\n sum += int(i) ** (idx + 1)\n if sum == int(N):\n return 1\n else:\n return 0", "def isdisarium(N):\n h = 0\n j = N\n a = N\n z = str(N)\n z = list(z)\n b = len(z)\n while N != 0:\n a = N % 10\n h = h + a ** b\n N = N // 10\n b = b - 1\n if j == h:\n return 1\n return 0"], "starter_code": "def isdisarium(N):\n", "input_output": {"inputs": ["N = 89", "N = 81"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/disarium-number1045/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(N))", "entry_point": "isdisarium", "task_id": "TACO_lite/151", "example": [[[89], [81]], ["1", "0"]]} +{"requirement": "You are given a string S of lowercase alphabet characters and the task is to find its matching decimal representation as on the shown keypad. Output the decimal representation corresponding to the string. For ex: if you are given amazon then its corresponding decimal representation will be 262966.\nExample 1:\nInput:\nS = geeksforgeeks\nOutput: 4335736743357\nExplanation:geeksforgeeks is 4335736743357\nin decimal when we type it using the given\nkeypad.\nExample 2:\nInput:\nS = geeksquiz\nOutput: 433577849\nExplanation: geeksquiz is 433577849 in\ndecimal when we type it using the given\nkeypad.\nYour Task:\nComplete printNumber() function that takes string s and its length as parameters and returns the corresponding decimal representation of the given string as a string type. The printing is done by the driver code.\nConstraints:\n1 \u2264 length of String \u2264 100\nExpected Time Complexity : O(n)\nExpected Auxilliary Space : O(n)", "solutions": ["def printnumber(s, n):\n s = s.upper()\n ans = ''\n my_dict = {'A': 2, 'B': 2, 'C': 2, 'D': 3, 'E': 3, 'F': 3, 'G': 4, 'H': 4, 'I': 4, 'J': 5, 'K': 5, 'L': 5, 'M': 6, 'N': 6, 'O': 6, 'P': 7, 'Q': 7, 'R': 7, 'S': 7, 'T': 8, 'U': 8, 'V': 8, 'W': 9, 'X': 9, 'Y': 9, 'Z': 9}\n for i in range(len(s)):\n ans += str(my_dict[s[i]])\n return ans", "def printnumber(s, n):\n d = [2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9]\n res = ''\n for i in s:\n res += str(d[ord(i) - ord('a')])\n return res", "def printnumber(s, n):\n s = s.lower()\n d = {'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3', 'g': '4', 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6', 'n': '6', 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8', 'u': '8', 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9'}\n result = ''\n for c in s:\n result = result + d[c]\n return result", "def printnumber(s, n):\n freq = {'a': 2, 'b': 2, 'c': 2, 'd': 3, 'e': 3, 'f': 3, 'g': 4, 'h': 4, 'i': 4, 'j': 5, 'k': 5, 'l': 5, 'm': 6, 'n': 6, 'o': 6, 'p': 7, 'q': 7, 'r': 7, 's': 7, 't': 8, 'u': 8, 'v': 8, 'w': 9, 'x': 9, 'y': 9, 'z': 9}\n ans = ''\n for ele in s:\n if ele in freq:\n ans += str(freq[ele])\n return ans", "def printnumber(s, n):\n (n2, n3, n4, n5, n6, n7, n8, n9) = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz')\n res = ''\n for i in s:\n if i in n2:\n res += '2'\n elif i in n3:\n res += '3'\n elif i in n4:\n res += '4'\n elif i in n5:\n res += '5'\n elif i in n6:\n res += '6'\n elif i in n7:\n res += '7'\n elif i in n8:\n res += '8'\n elif i in n9:\n res += '9'\n return res", "def printnumber(s, n):\n a = {'1': 1, 'A': 2, 'B': 2, 'C': 2, 'D': 3, 'E': 3, 'F': 3, 'G': 4, 'H': 4, 'I': 4, 'J': 5, 'K': 5, 'L': 5, 'M': 6, 'N': 6, 'O': 6, 'P': 7, 'Q': 7, 'R': 7, 'S': 7, 'T': 8, 'U': 8, 'V': 8, 'W': 9, 'X': 9, 'Y': 9, 'Z': 9, '*': '*', '0': 0}\n temp = ''\n for i in s.upper():\n temp += str(a[i])\n return temp", "def printnumber(str, n):\n s = ''\n for i in range(len(str)):\n if str[i] == 'a' or str[i] == 'b' or str[i] == 'c':\n s += '2'\n elif str[i] == 'd' or str[i] == 'e' or str[i] == 'f':\n s += '3'\n elif str[i] == 'g' or str[i] == 'h' or str[i] == 'i':\n s += '4'\n elif str[i] == 'j' or str[i] == 'k' or str[i] == 'l':\n s += '5'\n elif str[i] == 'm' or str[i] == 'n' or str[i] == 'o':\n s += '6'\n elif str[i] == 'p' or str[i] == 'q' or str[i] == 'r' or (str[i] == 's'):\n s += '7'\n elif str[i] == 't' or str[i] == 'u' or str[i] == 'v':\n s += '8'\n else:\n s += '9'\n return s", "def printnumber(s, n):\n l1 = []\n for i in s:\n if i in {'a', 'b', 'c'}:\n l1.append('2')\n elif i in {'d', 'e', 'f'}:\n l1.append('3')\n elif i in {'g', 'h', 'i'}:\n l1.append('4')\n elif i in {'j', 'k', 'l'}:\n l1.append('5')\n elif i in {'m', 'n', 'o'}:\n l1.append('6')\n elif i in {'p', 'q', 'r', 's'}:\n l1.append('7')\n elif i in {'t', 'u', 'v'}:\n l1.append('8')\n elif i in {'w', 'x', 'y', 'z'}:\n l1.append('9')\n return ''.join(l1)", "def printnumber(s, n):\n arr = 'abcdefghijklmnopqrtuvwxy'\n dic = {}\n x = 2\n for i in range(0, 24, 3):\n dic[arr[i]] = x\n dic[arr[i + 1]] = x\n dic[arr[i + 2]] = x\n x += 1\n dic['s'] = 7\n dic['z'] = 9\n an = ''\n for i in s:\n an = an + str(dic[i])\n return an", "def printnumber(s, n):\n (num_2, num_3, num_4) = ('abc', 'def', 'ghi')\n (num_5, num_6, num_7, num_8, num_9) = ('jkl', 'mno', 'pqrs', 'tuv', 'wxyz')\n result = ''\n for char in s:\n if char in num_2:\n result += '2'\n elif char in num_3:\n result += '3'\n elif char in num_4:\n result += '4'\n elif char in num_5:\n result += '5'\n elif char in num_6:\n result += '6'\n elif char in num_7:\n result += '7'\n elif char in num_8:\n result += '8'\n elif char in num_9:\n result += '9'\n return result", "def printnumber(s, n):\n str = ''\n for char in s:\n if char in 'abc':\n str += '2'\n elif char in 'def':\n str += '3'\n elif char in 'ghi':\n str += '4'\n elif char in 'jkl':\n str += '5'\n elif char in 'mno':\n str += '6'\n elif char in 'pqrs':\n str += '7'\n elif char in 'tuv':\n str += '8'\n elif char in 'wxyz':\n str += '9'\n return str", "def printnumber(s, n):\n (digit2, digit3, digit4, digit5, digit6, digit7, digit8, digit9) = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz')\n d = ''\n for i in s:\n if i in digit2:\n d += '2'\n elif i in digit3:\n d += '3'\n elif i in digit4:\n d += '4'\n elif i in digit5:\n d += '5'\n elif i in digit6:\n d += '6'\n elif i in digit7:\n d += '7'\n elif i in digit8:\n d += '8'\n elif i in digit9:\n d += '9'\n return d", "def printnumber(s, n):\n str_list = ['2', '22', '222', '3', '33', '333', '4', '44', '444', '5', '55', '555', '6', '66', '666', '7', '77', '777', '7777', '8', '88', '888', '9', '99', '999', '9999']\n ans = ''\n for i in range(n):\n if s[i] == ' ':\n ans += '0'\n else:\n j = ord(s[i].upper()) - ord('A')\n ans += str_list[j][0]\n return ans", "def printnumber(s, n):\n a = ''\n (two, three, four, five, six, seven, eight, nine) = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz')\n for i in s:\n if i in two:\n a += '2'\n elif i in three:\n a += '3'\n elif i in four:\n a += '4'\n elif i in five:\n a += '5'\n elif i in six:\n a += '6'\n elif i in seven:\n a += '7'\n elif i in eight:\n a += '8'\n else:\n a += '9'\n return a", "def printnumber(s, n):\n result = []\n s = s.upper()\n for i in s:\n if i == 'A' or i == 'B' or i == 'C':\n result.append('2')\n elif i == 'D' or i == 'E' or i == 'F':\n result.append('3')\n elif i == 'G' or i == 'H' or i == 'I':\n result.append('4')\n elif i == 'J' or i == 'K' or i == 'L':\n result.append('5')\n elif i == 'M' or i == 'N' or i == 'O':\n result.append('6')\n elif i == 'P' or i == 'Q' or i == 'R' or (i == 'S'):\n result.append('7')\n elif i == 'T' or i == 'U' or i == 'V':\n result.append('8')\n elif i == 'W' or i == 'X' or i == 'Y' or (i == 'Z'):\n result.append('9')\n string = ''\n return string.join(result)", "def printnumber(s, n):\n a = 'abcdefghijklmnopqrstuvwxyz'\n v = '22233344455566677778889999'\n ans = ''\n for i in s:\n ans += v[a.index(i)]\n return ans", "def printnumber(s, n):\n sr = 'abcdefghijklmnopqrstuvwxyz'\n nr = '22233344455566677778889999'\n a = ''\n for i in s:\n a += nr[sr.index(i)]\n return a", "def printnumber(s, n):\n S = ''\n for i in s:\n if i in 'abc':\n S += '2'\n if i in 'def':\n S += '3'\n if i in 'ghi':\n S += '4'\n if i in 'jkl':\n S += '5'\n if i in 'mno':\n S += '6'\n if i in 'pqrs':\n S += '7'\n if i in 'tuv':\n S += '8'\n if i in 'wxyz':\n S += '9'\n return S", "def printnumber(s, n):\n str1 = ['2', '2', '2', '3', '3', '3', '4', '4', '4', '5', '5', '5', '6', '6', '6', '7', '7', '7', '7', '8', '8', '8', '9', '9', '9', '9']\n output = ''\n for i in range(n):\n pos = ord(s[i]) - ord('a')\n output = output + str1[pos]\n return output", "def printnumber(s, n):\n s = s.upper()\n decimal = {'2': set('ABC'), '3': set('DEF'), '4': set('GHI'), '5': set('JKL'), '6': set('MNO'), '7': set('PQRS'), '8': set('TUV'), '9': set('WXYZ')}\n decimal_string = ''.join((key for char in s for (key, value) in decimal.items() if char in value))\n return decimal_string", "def printnumber(s, n):\n ans = ''\n for i in s:\n if i in 'abc':\n ans += '2'\n elif i in 'def':\n ans += '3'\n elif i in 'ghi':\n ans += '4'\n elif i in 'jkl':\n ans += '5'\n elif i in 'mno':\n ans += '6'\n elif i in 'pqrs':\n ans += '7'\n elif i in 'tuv':\n ans += '8'\n else:\n ans += '9'\n return ans", "def printnumber(s, n):\n store = {}\n for i in range(26):\n store[chr(i + 97)] = str(i // 3 + 2)\n store['s'] = '7'\n store['v'] = '8'\n store['y'] = '9'\n store['z'] = '9'\n output = ''\n for item in s:\n output += store[item]\n return output", "def printnumber(s, n):\n map = {'abc': '2', 'def': '3', 'ghi': '4', 'jkl': '5', 'mno': '6', 'pqrs': '7', 'tuv': '8', 'wxyz': '9'}\n x = [map[j] for i in s for j in map.keys() if i in j]\n return ''.join(x)", "def printnumber(s, n):\n l = ''\n for i in s.upper():\n if i == 'A' or i == 'B' or i == 'C':\n l = l + '2'\n elif i == 'D' or i == 'E' or i == 'F':\n l = l + '3'\n elif i == 'G' or i == 'H' or i == 'I':\n l = l + '4'\n elif i == 'J' or i == 'K' or i == 'L':\n l = l + '5'\n elif i == 'M' or i == 'N' or i == 'O':\n l = l + '6'\n elif i == 'P' or i == 'Q' or i == 'R' or (i == 'S'):\n l = l + '7'\n elif i == 'T' or i == 'U' or i == 'V':\n l = l + '8'\n else:\n l = l + '9'\n return l", "def printnumber(s, n):\n str1 = ''\n for s in s:\n if s >= 'a' and s <= 'c':\n str1 += '2'\n elif s >= 'd' and s <= 'f':\n str1 += '3'\n elif s >= 'g' and s <= 'i':\n str1 += '4'\n elif s >= 'j' and s <= 'l':\n str1 += '5'\n elif s >= 'm' and s <= 'o':\n str1 += '6'\n elif s >= 'p' and s <= 's':\n str1 += '7'\n elif s >= 't' and s <= 'v':\n str1 += '8'\n elif s >= 'w' and s <= 'z':\n str1 += '9'\n return str1", "def printnumber(s, n):\n d = {'abc': '2', 'def': '3', 'ghi': '4', 'jkl': '5', 'mno': '6', 'pqrs': '7', 'tuv': '8', 'wxyz': '9'}\n res = ''\n for c in s:\n for (k, v) in d.items():\n if c in k:\n res += v\n return res", "def printnumber(s, n):\n sum1 = ''\n for i in s:\n if 97 <= ord(i) <= 99:\n sum1 += '2'\n elif 100 <= ord(i) <= 102:\n sum1 += '3'\n elif 103 <= ord(i) <= 105:\n sum1 += '4'\n elif 106 <= ord(i) <= 108:\n sum1 += '5'\n elif 109 <= ord(i) <= 111:\n sum1 += '6'\n elif 112 <= ord(i) <= 115:\n sum1 += '7'\n elif 116 <= ord(i) <= 118:\n sum1 += '8'\n elif 119 <= ord(i) <= 122:\n sum1 += '9'\n return sum1", "def printnumber(s, n):\n op = ''\n for i in range(n):\n if s[i] in 'abc':\n op += '2'\n elif s[i] in 'def':\n op += '3'\n elif s[i] in 'ghi':\n op += '4'\n elif s[i] in 'jkl':\n op += '5'\n elif s[i] in 'mno':\n op += '6'\n elif s[i] in 'pqrs':\n op += '7'\n elif s[i] in 'tuv':\n op += '8'\n elif s[i] in 'wxyz':\n op += '9'\n else:\n pass\n return op", "def printnumber(s, n):\n l = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']\n r = ''\n for i in s:\n if i in l[0]:\n r += '2'\n elif i in l[1]:\n r += '3'\n elif i in l[2]:\n r += '4'\n elif i in l[3]:\n r += '5'\n elif i in l[4]:\n r += '6'\n elif i in l[5]:\n r += '7'\n elif i in l[6]:\n r += '8'\n elif i in l[7]:\n r += '9'\n elif i == ' ':\n r += '0'\n return r", "def printnumber(s, n):\n s = s.upper()\n ans = ''\n two = ['A', 'B', 'C']\n three = ['D', 'E', 'F']\n four = ['G', 'H', 'I']\n five = ['J', 'K', 'L']\n six = ['M', 'N', 'O']\n seven = ['P', 'Q', 'R', 'S']\n eight = ['T', 'U', 'V']\n nine = ['W', 'X', 'Y', 'Z']\n for i in s:\n if i in two:\n ans += '2'\n elif i in three:\n ans += '3'\n elif i in four:\n ans += '4'\n elif i in five:\n ans += '5'\n elif i in six:\n ans += '6'\n elif i in seven:\n ans += '7'\n elif i in eight:\n ans += '8'\n else:\n ans += '9'\n return ans", "def printnumber(s, n):\n a = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']\n b = [2, 3, 4, 5, 6, 7, 8, 9]\n a1 = set(list(s))\n for i in a1:\n for j in a:\n if i in j:\n v = b[a.index(j)]\n s = s.replace(i, str(v))\n break\n return int(s)", "def printnumber(s, n):\n numbers = '22233344455566677778889999'\n final_num = ''\n for char in s:\n diff = ord(char) - ord('a')\n final_num = final_num + numbers[diff]\n return final_num", "def printnumber(s, n):\n nums = '22233344455566677778889999'\n ans = ''\n c = 'a'\n for i in range(n):\n temp = ord(s[i]) - ord(c)\n ans = ans + nums[temp]\n return ans", "def printnumber(s, n):\n c = []\n c = s\n sum = ''\n for i in c:\n if i in 'ABCabc':\n sum += str(2)\n elif i in 'DEFdef':\n sum += str(3)\n elif i in 'GHIghi':\n sum += str(4)\n elif i in 'JKLjkl':\n sum += str(5)\n elif i in 'MNOmno':\n sum += str(6)\n elif i in 'PQRSpqrs':\n sum += str(7)\n elif i in 'TUVtuv':\n sum += str(8)\n elif i in 'WXYZwxyz':\n sum += str(9)\n return sum"], "starter_code": "def printnumber(s,n):\n", "input_output": {"fn_name": "printNumber", "inputs": ["S = geeksforgeeks", "S = geeksquiz"], "outputs": ["4335736743357", "433577849"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/keypad-typing0119/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "printnumber", "task_id": "TACO_lite/105", "example": [[], []]} +{"requirement": "You have to create a function that converts integer given as string into ASCII uppercase letters.\n\nAll ASCII characters have their numerical order in table. \n\nFor example,\n\n```\nfrom ASCII table, character of number 65 is \"A\".\n```\n\nNumbers will be next to each other, So you have to split given number to two digit long integers.\n\nFor example, \n\n```\n'658776' to [65, 87, 76] and then turn it into 'AWL'.\n```", "solutions": ["def convert(number):\n return ''.join((chr(int(number[a:a + 2])) for a in range(0, len(number), 2)))", "def convert(number):\n return ''.join((chr(int(number[i:i + 2])) for i in range(0, len(number), 2)))\n pass", "def convert(number):\n return ''.join([chr(int(x)) for x in map(''.join, zip(*[iter(number)] * 2))])", "def convert(number):\n return ''.join((chr(int(f'{e1}{e2}')) for (e1, e2) in zip(*[iter(number)] * 2)))", "def convert(n):\n return ''.join([chr(int(i + k)) for (i, k) in zip(n[::2], n[1::2])])", "convert = lambda s: ''.join((chr(int(s[i:i + 2])) for i in range(0, len(s), 2)))", "import re\n\ndef convert(number):\n return ''.join((chr(int(code)) for code in re.findall('\\\\d\\\\d', number)))", "def convert(n):\n return ''.join([chr(int(n[i:i + 2])) for i in range(0, len(n) - 1, 2)])", "convert = lambda s: bytes((int(s[i:i + 2]) for i in range(0, len(s), 2))).decode()", "def convert(line):\n return ''.join([chr(int(line[i:i + 2])) for i in range(0, len(line), 2)])"], "starter_code": "def convert(number):\n", "input_output": {"fn_name": "convert", "inputs": [["65"], ["656667"], ["676584"], ["73327673756932858080698267658369"], ["32327332327679866932328380656769833232"], ["84726982693273833278793270857832737832657889327984726982326765836983"]], "outputs": [["A"], ["ABC"], ["CAT"], ["I LIKE UPPERCASE"], [" I LOVE SPACES "], ["THERE IS NO FUN IN ANY OTHER CASES"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/589ebcb9926baae92e000001", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "convert", "task_id": "TACO_lite/161", "example": [[["658776"]], ["AWL"]]} +{"requirement": "Given a string N representing a positive number. The task is to round N to the nearest multiple of 10.\nNote: If you are having two multiple equally apart from N then we will choose the smallest element among them.\n \nExample 1:\n \nInput : N = 15\nOutput : 10\nExplanation:\nHere N is 15. So, the number which is\nmultiple of 10 are 10, 20, 30. We can\nsee 10 and 20 are equally distant\nfrom 20. So, we will choose the\nsmallest element among them i.e., 10.\nExample 2:\nInput : N = 29 \nOutput : 30 \n \nYour Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function roundToNearest() that takes a string (N), and returns the nearest multiple of 10. The driver code takes care of the printing.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\n \nConstraints:\n1 <= |Number length| <= 10^{5}", "solutions": ["def roundtonearest(N):\n N = int(N)\n if N % 10 <= 5:\n a = N // 10\n return a * 10\n else:\n return (N // 10 + 1) * 10", "def roundtonearest(N):\n n = int(N)\n b = n // 10 * 10\n c = b + 10\n if n - b > c - n:\n return c\n return b", "def roundtonearest(N):\n a = int(N) // 10 * 10\n b = a + 10\n if int(N) - a > b - int(N):\n return b\n else:\n return a", "def roundtonearest(N):\n k = int(N)\n r = k % 10\n if r > 5:\n return k - r + 10\n else:\n return k - r", "def roundtonearest(N):\n f = 1\n maxx = int(N)\n while f == 1:\n if maxx % 10 == 0:\n f = 0\n else:\n maxx += 1\n g = 1\n minn = int(N)\n while g == 1:\n if minn % 10 == 0:\n g = 0\n else:\n minn -= 1\n if abs(int(N) - maxx) < abs(int(N) - minn):\n return maxx\n return minn", "def roundtonearest(N):\n n = int(N)\n q = n // 10\n r = n % 10\n if r <= 5:\n return 10 * q\n else:\n return 10 * (q + 1)", "def roundtonearest(n):\n n = int(n)\n z = n % 10\n if z <= 5:\n x = n - z\n return x\n else:\n p = 10 - z\n x = n + p\n return x", "def roundtonearest(N):\n a = int(N)\n for i in range(11):\n if a % 10 == 0:\n return str(a)\n b = a - i\n c = a + i\n if b % 10 == 0:\n return str(b)\n if c % 10 == 0:\n return str(c)\n return ''", "def roundtonearest(N):\n N = int(N)\n val = N % 10\n if val == 10:\n return str(N)\n if val > 5:\n N += 10 - val\n else:\n N -= val\n return str(N)", "def roundtonearest(N):\n t = int(N)\n ans = ''\n if t % 10 == 5:\n t = t - 5\n elif t % 10 > 5:\n t = t + 10 - t % 10\n else:\n t = t - t % 10\n return str(t)", "def roundtonearest(N):\n count1 = 0\n count2 = 0\n n1 = int(N)\n if n1 <= 10:\n if n1 > 5:\n return '10'\n else:\n return '0'\n while n1 % 10 != 0:\n count1 += 1\n n1 += 1\n n2 = int(N)\n while n2 % 10 != 0:\n count2 += 1\n n2 -= 1\n if count1 < count2:\n return str(n1)\n elif count1 > count2:\n return str(n2)\n else:\n return str(n2)", "def roundtonearest(N):\n N = int(N)\n if N < 10 and N > 5:\n return 10\n elif N <= 5:\n return 0\n elif N % 10 == 0:\n return N\n rem = N % 10\n if rem <= 5:\n return N - rem\n elif rem > 5:\n return N + 10 - rem", "def roundtonearest(N):\n N = int(N)\n a = N % 10\n if a == 0:\n return N\n elif a <= 5:\n return N - int(a)\n else:\n return N + (10 - int(a))", "def roundtonearest(N):\n N = int(N)\n if N % 10 > 5:\n n = 10 - N % 10\n N = n + N\n elif N % 10 < 5:\n n = N % 10\n N = N - n\n else:\n N = N - 5\n return N", "def roundtonearest(n):\n n = int(n)\n d = n // 10\n first = d * 10\n second = (d + 1) * 10\n if abs(n - first) <= abs(n - second):\n return str(first)\n else:\n return str(second)", "def roundtonearest(N):\n N = int(N)\n n = N % 10\n if n < 6:\n return N - n\n return N + (10 - n)", "def roundtonearest(N):\n n = int(N)\n pn = abs(n)\n last_digit = pn % 10\n add = 0\n if 5 < last_digit <= 9:\n add = 10 - last_digit\n elif 1 <= last_digit <= 5:\n add = -last_digit\n if n > 0:\n return pn + add\n else:\n return -(pn + add)", "def roundtonearest(N):\n if len(N) == 1:\n if int(N) <= 5:\n return 0\n else:\n return 10\n elif int(N[-1]) <= 5:\n return N[0:-1] + '0'\n else:\n return str(int(N[0:-1]) + 1) + '0'", "def roundtonearest(N):\n rem = int(N[len(N) - 1])\n if rem > 5:\n rem = abs(10 - rem)\n else:\n rem = -rem\n temp = int(N)\n temp += rem\n return str(temp)", "def roundtonearest(N):\n que = int(N) // 10\n remainder = int(N) % 10\n if remainder <= 5:\n return 10 * que\n return 10 * (que + 1)", "def roundtonearest(N):\n if int(N) <= 5:\n return '0'\n if int(N) <= 9:\n return '10'\n n = int(N) % 10\n if n == 0:\n return str(N)\n elif n <= 5:\n return str(int(N) - n)\n else:\n return str(int(N) - n + 10)", "def roundtonearest(n):\n n = int(n)\n r = n % 10\n n1 = n - r\n if r <= 5:\n return n1\n else:\n return n1 + 10", "def roundtonearest(N):\n N = int(N)\n if N % 10 <= 5:\n return 10 * (N // 10)\n elif N % 10 > 5:\n return 10 * (N // 10 + 1)", "def roundtonearest(N):\n\n def getNumber(N):\n n1 = int(N)\n return (n1, n1 % 10)\n if N[-1] <= '5':\n (k1, k2) = getNumber(N)\n return k1 - k2\n else:\n (k1, k2) = getNumber(N)\n return k1 + (10 - k2)", "def roundtonearest(N):\n last = int(N[-1])\n if last > 5:\n last = 10 - last\n else:\n last = -last\n res = int(N)\n res += last\n return str(res)", "def roundtonearest(N):\n re = int(N[len(N) - 1])\n if re > 5:\n re = abs(10 - re)\n else:\n re = -re\n t = int(N)\n t += re\n return str(t)", "def roundtonearest(N):\n a = str(N)\n las = a[-1]\n nea = int(las)\n if 10 - nea < 5:\n return str(int(N) + (10 - nea))\n else:\n ans = int(N) - nea\n return str(ans)", "def roundtonearest(N):\n n = int(N)\n low = n // 10 * 10\n high = low + 10\n if n - low > high - n:\n return high\n else:\n return low", "def roundtonearest(N):\n x = int(N)\n y = len(N)\n if x % 10 > 5:\n x = x + 10 - x % 10\n else:\n x = x - x % 10\n return str(x)", "def roundtonearest(N):\n x = int(N)\n if x % 10 <= 5:\n return x - x % 10\n else:\n return x + (10 - x % 10)", "def roundtonearest(N):\n s = int(N)\n k = s % 10\n l = s // 10\n if k <= 5:\n return l * 10\n else:\n return (l + 1) * 10", "def roundtonearest(N):\n N = int(N)\n unit_n = N % 10\n ans = None\n if unit_n >= 0 and unit_n <= 5:\n ans = N - unit_n\n else:\n ans = N + (10 - unit_n)\n return ans", "def roundtonearest(N):\n s = int(N) // 10\n if int(N) - s * 10 <= (s + 1) * 10 - int(N):\n return s * 10\n else:\n return (s + 1) * 10", "def roundtonearest(N):\n ans = 0\n n = int(N)\n if n % 10 > 5:\n ans = (n // 10 + 1) * 10\n else:\n ans = n // 10 * 10\n return int(ans)", "def roundtonearest(n):\n t = int(n) % 10\n j = abs(10 - t)\n if j < 5:\n a = str(int(n) + j)\n return a\n else:\n b = str(int(n) - t)\n return b", "def roundtonearest(N):\n N = int(N)\n a1 = N // 10\n a2 = (a1 + 1) * 10\n if abs(N - a1 * 10) == abs(N - a2):\n return a1 * 10\n if abs(N - a1 * 10) > abs(N - a2):\n return a2\n else:\n return a1 * 10", "def roundtonearest(N):\n N = int(N)\n l = int(N)\n m = int(N)\n while l % 10:\n l -= 1\n while m % 10:\n m += 1\n if m % 10 == 0 and l % 10 == 0:\n if N - l > m - N:\n return m\n return l\n if m % 10 == 0:\n return m\n return l", "def roundtonearest(N):\n k = int(N) % 10\n if k <= 5:\n return int(N) - k\n return int(N) + abs(k - 10)", "def roundtonearest(N):\n i = int(N)\n N = int(N)\n while i > 0:\n r = N % 10\n if r == 0:\n N = N\n elif r <= 5:\n N = N - r\n else:\n N = N + 5\n i = N % 10\n return N", "def roundtonearest(N):\n N = int(N)\n c = N % 10\n if c <= 10 - c:\n return N - c\n return N + (10 - c)", "def roundtonearest(N):\n l = int(N[-1])\n x = ''\n if l in [1, 2, 3, 4]:\n x = N[:-1] + '0'\n elif l in [6, 7, 8, 9]:\n x = int(N) + (10 - l)\n elif l == 0:\n x = N\n elif l == 5:\n x = int(N) - 5\n return x", "def roundtonearest(N):\n temp = int(N)\n l = temp % 10\n if l <= 5:\n temp -= l\n else:\n temp += 10 - l\n ans = ''\n ans = temp\n return ans"], "starter_code": "def roundtonearest (N) :\n", "input_output": {"inputs": ["N = 15", "N = 29"], "outputs": ["10", "30"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical", "Strings", "Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/nearest-multiple-of-102437/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "roundtonearest", "task_id": "TACO_lite/155", "example": [[[15], [29]], ["10", "30"]]} +{"requirement": "Let's pretend your company just hired your friend from college and paid you a referral bonus. Awesome! To celebrate, you're taking your team out to the terrible dive bar next door and using the referral bonus to buy, and build, the largest three-dimensional beer can pyramid you can. And then probably drink those beers, because let's pretend it's Friday too. \n\nA beer can pyramid will square the number of cans in each level - 1 can in the top level, 4 in the second, 9 in the next, 16, 25... \n\nComplete the beeramid function to return the number of **complete** levels of a beer can pyramid you can make, given the parameters of: \n\n1) your referral bonus, and\n\n2) the price of a beer can\n\nFor example:", "solutions": ["def beeramid(bonus, price):\n beers = bonus // price\n levels = 0\n while beers >= (levels + 1) ** 2:\n levels += 1\n beers -= levels ** 2\n return levels", "from itertools import count\n\ndef beeramid(bonus, price):\n bonus = max(bonus, 0)\n n = bonus // price\n return next((x for x in count(int((n * 3) ** (1 / 3) + 1), -1) if x * (x + 1) * (2 * x + 1) // 6 <= n))", "def beeramid(bonus, price):\n k = bonus // price\n d = (3 * (11664 * k * k - 3) ** 0.5 + 324 * k) ** (1 / 3)\n n = (d / 3 + 1 / d - 1) / 2\n return k > 0 and int(n.real + 1e-12)", "def beeramid(bonus, price):\n i = 0\n while bonus > 0:\n i += 1\n bonus -= price * i ** 2\n if bonus < 0:\n i -= 1\n return i", "def beeramid(bonus, price, level=1):\n return 0 if bonus < price * level ** 2 else 1 + beeramid(bonus - price * level ** 2, price, level + 1)", "def beeramid(bonus, price):\n b = bonus / price\n n = 1\n while True:\n if b < n * (n + 1) * (2 * n + 1) / 6:\n return n - 1\n break\n n += 1", "def beeramid(bonus, price):\n num_cans = bonus // price\n level = 0\n while num_cans >= 0:\n level += 1\n num_cans -= level * level\n return max(0, level - 1)", "def beeramid(bonus, price):\n if bonus < price:\n return 0\n elif bonus == price:\n return 1\n else:\n L = []\n a = int(bonus // price) + 1\n c = 1\n for i in range(1, a):\n c += i * i\n if c <= a:\n L.append(i * i)\n b = len(L)\n return b", "def beeramid(bonus, price):\n if bonus < 0:\n return 0\n sum = 0\n x = 1\n c = 0\n while bonus / price >= sum:\n sum = sum + x ** 2\n x += 1\n c += 1\n return c - 1", "def level():\n n = 2\n while n:\n yield (n ** 2)\n n += 1\n\ndef beeramid(bonus, price):\n (b, x, sum, n) = (bonus // price, level(), 1, 0)\n while sum <= b:\n sum += next(x)\n n += 1\n return n"], "starter_code": "def beeramid(bonus, price):\n", "input_output": {"fn_name": "beeramid", "inputs": [[9, 2], [10, 2], [11, 2], [21, 1.5], [454, 5], [455, 5], [4, 4], [3, 4], [0, 4], [-1, 4]], "outputs": [[1], [2], [2], [3], [5], [6], [1], [0], [0], [0]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/51e04f6b544cf3f6550000c1", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "beeramid", "task_id": "TACO_lite/143", "example": [[[1500, 2], [5000, 3]], ["12", "16"]]} +{"requirement": "You are given a string S, the task is to reverse the string using stack.\n \nExample 1:\nInput: S=\"GeeksforGeeks\"\nOutput: skeeGrofskeeG\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function reverse() which takes the string S as an input parameter and returns the reversed string.\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\n \nConstraints:\n1 \u2264 length of the string \u2264 100", "solutions": ["def reverse(s):\n stack = []\n list1 = []\n for i in range(len(s)):\n stack.append(s[i])\n for i in range(len(stack)):\n list1.append(stack.pop())\n return ''.join(list1)", "def reverse(s):\n n = len(s)\n list1 = []\n answer = ''\n for i in s:\n list1.append(i)\n for i in range(len(list1)):\n answer += list1.pop()\n return answer", "def reverse(S):\n return S[::-1]", "def reverse(S):\n return S[::-1]\n stack = []\n ans = ''\n for val in S:\n stack.append(val)\n while stack:\n ans += stack.pop()\n return ans", "def reverse(S):\n stack = []\n result = []\n for alp in S:\n stack.append(alp)\n for _ in range(len(stack)):\n result.append(stack.pop())\n return ''.join(result)", "def reverse(s):\n stack = []\n for i in range(len(s) - 1, -1, -1):\n stack.append(s[i])\n return ''.join(stack)", "def reverse(s):\n stack = []\n ans = ''\n for i in s:\n stack.append(i)\n for i in range(len(stack)):\n ans += stack.pop()\n return ans", "def reverse(s):\n return s[::-1]", "def reverse(S):\n stack = []\n n = len(S)\n for i in range(n - 1, -1, -1):\n stack.append(S[i])\n return ''.join(stack)", "def reverse(S):\n stack = []\n st = []\n for i in S:\n st.append(i)\n for i in range(len(S)):\n stack.append(st.pop())\n return ''.join(stack)", "def reverse(S):\n l = list(S)\n s = ''\n while len(l) > 0:\n s = s + l.pop()\n return s", "def reverse(S):\n stack = []\n for char in S:\n stack.append(char)\n reversed_string = ''\n while stack:\n reversed_string += stack.pop()\n return reversed_string", "from collections import deque\n\ndef reverse(S):\n n = len(S)\n stack = deque()\n for i in S:\n stack.append(i)\n ans = ''\n for i in range(len(stack)):\n ans += stack.pop()\n return ans", "def reverse(S):\n ans = ''\n for i in reversed(range(len(S))):\n ans = ans + S[i]\n return ans", "def reverse(S):\n n = len(S)\n stack = []\n for i in range(n):\n stack.append(S[i])\n s = ''\n for i in range(n):\n s = s + stack[-1]\n stack.pop()\n return s", "def reverse(S):\n stack = []\n stack2 = []\n for i in S:\n stack.append(i)\n for j in range(len(S)):\n stack2.append(stack.pop())\n return ''.join(stack2)", "def reverse(S):\n st = []\n for i in S:\n st.append(i)\n s = ''\n while st:\n s += st.pop()\n return s", "def reverse(S):\n s1 = []\n s2 = []\n for i in S:\n s1.append(i)\n for i in range(len(s1)):\n s2.append(s1.pop())\n return ''.join(s2)", "def reverse(S):\n s = ''\n a = len(S)\n for i in range(len(S)):\n s += S[a - (i + 1)]\n return s", "def reverse(S):\n reversedS = ''\n remainingS = len(S)\n while remainingS > 0:\n reversedS += S[remainingS - 1]\n remainingS -= 1\n return reversedS", "def reverse(S):\n st = []\n r = ''\n for i in S:\n st.append(i)\n while st:\n r += st.pop()\n return r", "def reverse(S):\n stack = []\n newS = ''\n for s in range(len(S)):\n stack.append(S[s])\n while len(stack) > 0:\n newS += stack.pop()\n return newS", "def reverse(S):\n stack = []\n for i in S:\n stack.append(i)\n s = ''\n for i in range(len(S)):\n x = stack.pop()\n s += x\n return s", "def reverse(S):\n stack = []\n for i in S:\n stack.append(i)\n return ''.join(stack[::-1])", "def reverse(S):\n stack1 = []\n stack2 = []\n for i in S:\n stack1.append(i)\n for i in range(len(stack1)):\n stack2.append(stack1.pop())\n return ''.join(stack2)", "def reverse(S):\n import collections\n ret = ''\n de = collections.deque([*S])\n for i in range(len(de)):\n ret += de.pop()\n return ret", "from collections import deque\n\ndef reverse(S):\n stack = deque()\n m = len(S)\n i = m - 1\n while i >= 0:\n stack.append(S[i])\n i -= 1\n return ''.join(stack)", "def reverse(S):\n stack = []\n astack = []\n for i in S:\n stack.append(i)\n for i in range(len(S)):\n a = stack.pop()\n astack.append(a)\n return ''.join(astack)", "def reverse(S):\n ans = ''\n st = []\n for i in S:\n st.append(i)\n while st:\n ans += st.pop()\n return ans", "def reverse(s):\n l = []\n for i in s:\n l.append(i)\n t = ''\n while len(l):\n t += l.pop(-1)\n return t", "def reverse(S):\n s = []\n for i in range(len(S)):\n s.append(S[i])\n p = ''\n while s:\n a = s.pop()\n p = p + a\n return p", "def reverse(S):\n s = []\n a = ''\n for i in S:\n s.append(i)\n while len(s) != 0:\n i = s.pop()\n a = a + i\n return a", "def reverse(S):\n output = ''\n length = len(S) - 1\n while length >= 0:\n output = output + S[length]\n length = length - 1\n return output", "def reverse(S):\n s = []\n for i in range(len(S) - 1, -1, -1):\n s.append(S[i])\n strr = ''\n for i in range(len(s)):\n strr = strr + s[i]\n return strr", "def reverse(S):\n a = []\n str = ''\n for i in S:\n a.append(i)\n b = len(a)\n while b:\n x = a.pop()\n str += x\n b -= 1\n return str", "def reverse(S):\n a = []\n u = ''\n for ch in S:\n a.append(ch)\n while len(a) != 0:\n u += a.pop()\n return u", "def reverse(S):\n stk = []\n for ch in S:\n stk.append(ch)\n ans = ''\n while stk:\n ans += stk.pop()\n return ans", "def reverse(S):\n res = ''\n stack = []\n top = -1\n for i in S:\n stack.append(i)\n top += 1\n while top >= 0:\n x = stack.pop()\n top -= 1\n res += x\n return res", "import queue\n\ndef reverse(s):\n stack = queue.LifoQueue(len(s))\n for i in s:\n stack.put(i)\n result = ''\n while not stack.empty():\n result += stack.get()\n return result", "def reverse(S):\n stack = []\n for i in S:\n stack.append(i)\n S = ''\n while stack:\n S += stack.pop()\n return S", "def reverse(S):\n stack = []\n for i in S:\n stack.append(i)\n res = ''\n for i in range(len(stack)):\n res += stack.pop()\n return res", "def reverse(S):\n S = list(S)\n S.reverse()\n S = ''.join(S)\n return S", "def reverse(S):\n r = []\n s = list(S)\n for i in range(len(s)):\n r.append(s.pop())\n r = ''.join(r)\n return r", "from collections import deque\n\ndef reverse(S):\n stack = deque()\n a = []\n for i in S:\n stack.append(i)\n while len(stack) > 0:\n a.append(stack.pop())\n return ''.join(a)", "def reverse(S):\n arr = []\n S = [x for x in S]\n if not arr:\n while S:\n arr.append(S.pop())\n return ''.join(arr)", "def reverse(S):\n stack = Stack()\n rev = ''\n for i in S:\n stack.push(i)\n while stack.isEmpty() == False:\n rev += stack.pop()\n return rev\n\ndef __init__():\n self.items = []\n\ndef isEmpty():\n return not self.items\n\ndef push(item):\n self.items.append(item)\n\ndef pop():\n return self.items.pop()", "def reverse(S):\n stack = S[::-1]\n return stack", "def reverse(S):\n stack = []\n for r in range(len(S)):\n stack.append(S[r])\n rev = ''\n for x in range(len(stack)):\n rev += stack.pop()\n return rev", "import collections\n\ndef reverse(S):\n ns = collections.deque(S)\n ns.reverse()\n return ''.join(ns)", "def reverse(S):\n l = []\n for i in S:\n l.insert(0, i)\n ans = ''.join(l)\n return ans", "def reverse(S):\n res = ''\n for c in range(len(S) - 1, -1, -1):\n res += S[c]\n return res", "def reverse(S):\n S = list(S)\n x = []\n for i in range(len(S)):\n x.append(S.pop())\n x = ''.join(x)\n return x", "def reverse(S):\n S = ''.join(reversed(S))\n return S", "def reverse(S):\n for i in S:\n rev = S[::-1]\n return rev", "def reverse(S):\n return str(S)[::-1]", "def reverse(S):\n stk = []\n for i in S:\n stk.append(i)\n i = len(S) - 1\n ans = ''\n while i >= 0:\n ans += stk[i]\n i -= 1\n return ans", "def reverse(S):\n x = []\n for i in range(len(S) - 1, -1, -1):\n x.append(S[i])\n return ''.join(x)", "def reverse(S):\n Stack = []\n for i in S:\n Stack.append(i)\n newstring = ''\n while Stack != []:\n newstring = newstring + Stack.pop()\n return newstring"], "starter_code": "def reverse(S):\n", "input_output": {"fn_name": "reverse", "inputs": ["S=\"GeeksforGeeks\""], "outputs": ["skeeGrofskeeG"]}, "difficulty": "EASY", "raw_tags": ["Stack", "Strings", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/reverse-a-string-using-stack/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "reverse", "task_id": "TACO_lite/130", "example": [[["GeeksforGeeks"]], ["skeeGrofskeeG"]]} +{"requirement": "Given a set of m distinct positive integers and a value \u2018N\u2019. Count the total number of ways we can form \u2018N\u2019 by adding the array elements. Repetitions and different arrangements are allowed.\nNote: Answer can be quite large output the answer modulo 10^{9}+7.\nExample 1:\nInput:\nm = 3 , N = 7\nArr[] = {1,5,6}\nOutput: 6\nExplanation: The different ways are:\n1+1+1+1+1+1+1\n1+1+5\n1+5+1\n5+1+1\n1+6\n6+1\n\u00c3\u00a2\u00e2\u0082\u00ac\u00e2\u0080\u00b9Example 2:\nInput: \nm = 3 , N = 3\nArr[] = {1,2,3}\nOutput: 4\nExplanation: The different ways are:\n1+1+1\n1+2\n2+1\n3 \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function countWays() which accepts array arr[], its size m and integer N and returns the total number of ways we can form \u2018N\u2019 by adding array elements.\nExpected Time Complexity: O(N*m)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 <= N , m <= 10^{3}", "solutions": ["def countways(nums, m, target):\n n = len(nums)\n nums.sort()\n dp = [0 for _ in range(target + 1)]\n dp[0] = 1\n for total in range(1, target + 1):\n for i in range(n):\n if total - nums[i] >= 0:\n dp[total] += dp[total - nums[i]]\n return dp[target] % (10 ** 9 + 7)", "def countways(arr, m, n):\n mod = int(1000000000.0 + 7)\n dp = [0] * (n + 1)\n dp[0] = 1\n for i in range(1, n + 1):\n for j in arr:\n if j <= i:\n dp[i] += dp[i - j]\n dp[i] = dp[i] % mod\n return dp[n]", "def countways(arr, m, n):\n dp = [0] * (n + 1)\n dp[0] = 1\n mod = 10 ** 9 + 7\n for i in range(1, n + 1):\n for j in range(m):\n if i - arr[j] >= 0:\n dp[i] = (dp[i] + dp[i - arr[j]]) % mod\n return dp[n]", "def __init__():\n self.a1 = {}\n\ndef dp(a, s):\n if s == 0:\n self.a1[s] = 1\n return\n elif s in self.a1:\n return\n else:\n g = 0\n for i in a:\n if s - i >= 0:\n self.dp(a, s - i)\n g += self.a1[s - i]\n self.a1[s] = g\n\ndef countways(arr, m, n):\n self.dp(arr, n)\n return self.a1[n] % 1000000007", "def __init__():\n self.dp = dict()\n\ndef countways(arr, m, n):\n if not n:\n return 1\n if self.dp.get(n) != None:\n return self.dp[n]\n way = 0\n for x in arr:\n if x > n:\n continue\n way += self.countways(arr, m, n - x)\n self.dp[n] = way % (10 ** 9 + 7)\n return self.dp[n]", "def countways(arr, m, n):\n if not arr:\n return\n Mod = 1000000007\n if n < min(arr):\n return 0\n dp = [1] + [0] * n\n for i in range(1, n + 1):\n for j in range(m):\n if arr[j] <= i:\n dp[i] = dp[i] + dp[i - arr[j]] % Mod\n dp[i] %= Mod\n return dp[n]", "def countways(arr, m, n):\n dp = [0] * (n + 1)\n dp[0] = 1\n mod = 1000000007\n for i in range(1, n + 1):\n for j in arr:\n if i - j >= 0:\n dp[i] = dp[i] % mod + dp[i - j] % mod\n return dp[n] % mod", "def countways(arr, m, n):\n x = max(arr)\n x = max(x, n)\n dp = [0] * (x + 1)\n for el in arr:\n dp[el] += 1\n for i in range(n + 1):\n for el in arr:\n if i - el > 0:\n dp[i] += dp[i - el]\n return dp[n] % 1000000007", "MOD = int(1000000000.0 + 7)\n\ndef f(A, summ, dp):\n if summ == 0:\n return 1\n if dp[summ] != -1:\n return dp[summ]\n ans = 0\n for i in A:\n if i <= summ:\n ans += f(A, summ - i, dp)\n ans %= MOD\n dp[summ] = ans\n return ans\n\ndef countways(A, m, n):\n dp = [-1 for i in range(n + 1)]\n ans = 0\n for i in A:\n if i <= n:\n ans += f(A, n - i, dp)\n ans %= MOD\n return ans", "def wayPresentUsingDP(arr, total, tar, dp):\n if total == tar:\n return 1\n if total > tar:\n return 0\n if dp[total] != -4:\n return dp[total]\n ans = 0\n for (i, data) in enumerate(arr):\n if total + data <= tar:\n ans += wayPresentUsingDP(arr, total + data, tar, dp)\n dp[total] = ans\n return ans\n\ndef countways(arr, m, n):\n dp = [-4] * (n + 1)\n arr = sorted(arr)\n ans = wayPresentUsingDP(arr, 0, n, dp) % (10 ** 9 + 7)\n return ans", "def countways(arr, m, n):\n p = 10 ** 9 + 7\n count = [0 for i in range(n + 1)]\n count[0] = 1\n for i in range(1, n + 1):\n for j in range(m):\n if i >= arr[j]:\n count[i] += count[i - arr[j]]\n return count[n] % p", "def countways(arr, m, n):\n sum = n\n N = m\n coins = arr\n d = [0] * (sum + 1)\n d[0] = 1\n for i in range(sum + 1):\n for j in range(N):\n if coins[j] + i <= sum:\n d[coins[j] + i] = d[i] + d[i + coins[j]]\n return d[-1] % 1000000007", "def countways(arr, m, n):\n dp = {}\n dp[0] = 1\n for i in range(1, n + 1):\n for j in range(m):\n if i >= arr[j]:\n if i not in dp:\n if i - arr[j] not in dp:\n dp[i] = 0\n else:\n dp[i] = dp[i - arr[j]] % (10 ** 9 + 7)\n elif i - arr[j] not in dp:\n dp[i] = dp[i] % (10 ** 9 + 7)\n else:\n dp[i] = (dp[i] + dp[i - arr[j]]) % (10 ** 9 + 7)\n if n in dp:\n return dp[n]\n else:\n return 0", "def countways(arr, m, n):\n dp = [0] * (n + 1)\n ans = self.solve1(arr, n, dp)\n return ans\n\ndef solve(num, summ, dp):\n if summ == 0:\n return 1\n if summ < 0:\n return 0\n if dp[summ] != -1:\n return dp[summ]\n a = 0\n for i in range(len(num)):\n a += self.solve(num, summ - num[i], dp)\n dp[summ] = a\n return dp[summ]\n\ndef solve1(num, summ, dp):\n if summ == 0:\n return 1\n if summ < 0:\n return 0\n dp[0] = 1\n for i in range(1, n + 1):\n for j in range(len(num)):\n if i - num[j] >= 0:\n dp[i] += dp[i - num[j]]\n return dp[summ] % 1000000007", "def countways(arr, n, total):\n temp = 10 ** 9 + 7\n dp = [0 for i in range(total + 1)]\n dp[0] = 1\n for i in range(1, total + 1):\n for j in range(n):\n if arr[j] <= i:\n dp[i] += dp[i - arr[j]]\n dp[i] %= temp\n return dp[total]", "def countways(arr, m, N):\n mod = 10 ** 9 + 7\n count = [0 for i in range(N + 1)]\n count[0] = 1\n for i in range(1, N + 1):\n for j in range(m):\n if i >= arr[j]:\n count[i] += count[i - arr[j]]\n return count[N] % mod", "def countways(nums, m, target):\n dp = [0] * (target + 1)\n for i in range(1, target + 1):\n for n in nums:\n if n == i:\n dp[i] += 1\n if n < i:\n dp[i] += dp[i - n]\n return dp[-1] % (10 ** 9 + 7)", "def countways(arr, m, n):\n dp = [0] * (n + 1)\n dp[0] = 1\n arr.sort()\n for i in range(1, n + 1):\n for no in arr:\n if no > i:\n continue\n dp[i] = dp[i] + dp[i - no]\n return dp[n] % 1000000007", "def countways(arr, m, N):\n dp = [0 for _ in range(N + 1)]\n MOD = 10 ** 9 + 7\n dp[0] = 1\n for i in range(1, N + 1):\n for num in arr:\n if i - num >= 0:\n dp[i] = int((dp[i - num] + dp[i]) % MOD)\n return dp[N]", "def countways(arr, m, n):\n ways = [1] + n * [0]\n for i in range(n + 1):\n for num in arr:\n if num + i > n:\n continue\n ways[num + i] += ways[i]\n ways[num + i] %= 1000000007\n return ways[-1]", "def countways(arr, m, N):\n dp = [0] * (N + 1)\n dp[0] = 1\n s = 0\n for i in range(1, N + 1):\n for j in range(m):\n if arr[j] <= i:\n s += dp[i - arr[j]]\n dp[i] = s\n s = 0\n return dp[N] % (10 ** 9 + 7)", "def countways(arr, size, target):\n dp = [0] * (target + 1)\n dp[0] = 1\n mod = 1000000007\n for i in range(1, target + 1):\n for coin in arr:\n if coin <= i:\n dp[i] = (dp[i] + dp[i - coin]) % mod\n return dp[target]", "def dfs(arr, s, d):\n if s == 0:\n return 1\n if d.get(s) != None:\n return d[s]\n y = 0\n for i in arr:\n if s - i >= 0:\n y = y + self.dfs(arr, s - i, d)\n d[s] = y\n return y\n\ndef countways(arr, m, n):\n d = dict()\n mod = 10 ** 9 + 7\n return self.dfs(arr, n, d) % mod", "def countways(arr, n, s):\n count = [0 for i in range(s + 1)]\n count[0] = 1\n for j in range(1, s + 1):\n for e in arr:\n if j >= e:\n count[j] += count[j - e]\n return count[s] % (pow(10, 9) + 7)"], "starter_code": "def countways(arr, m, n):\n", "input_output": {"inputs": ["m = 3 , N = 7\nArr[] = {1,5,6}", "m = 3 , N = 3\nArr[] = {1,2,3}"], "outputs": ["6", "4"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/ways-to-sum-to-n5759/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*m)", "entry_point": "countways", "task_id": "TACO_lite/113", "example": [[[3, 7, [1, 5, 6]], [3, 3, [1, 2, 3]]], [null, null]]} +{"requirement": "Given Preorder, Inorder and Postorder traversals of some tree of size N. The task is to check if they are all of the same tree or not.\nExample 1:\nInput:\nN = 5\npreorder[] = {1, 2, 4, 5, 3}\ninorder[] = {4, 2, 5, 1, 3}\npostorder[] = {4, 5, 2, 3, 1}\nOutput: Yes\nExplanation: \nAll of the above three traversals \nare of the same tree.\n 1\n / \\\n 2 3\n / \\\n 4 5\nExample 2:\nInput:\nN = 5\npreorder[] = {1, 5, 4, 2, 3}\ninorder[] = {4, 2, 5, 1, 3}\npostorder[] = {4, 1, 2, 3, 5}\nOutput: No\nExplanation: The three traversals can \nnot be of the same tree.\nYour Task:\nYou don't need to read input or print anything. Complete the function checktree() which takes the array preorder[ ], inorder[ ], postorder[ ] and integer N as input parameters and returns true if the three traversals are of the same tree or not. \nExpected Time Complexity: O(N^{2})\nExpected Auxiliary Space: O(N)\nConstraints:\n1 \u2264 N \u2264 10^{3}\nNode values are unique.", "solutions": ["def check(pre, l1, r1, ino, l2, r2, post, l3, r3):\n if l2 > r2:\n return True\n if pre[l1] != post[r3]:\n return False\n try:\n idx = ino.index(pre[l1])\n except ValueError:\n return False\n return self.check(pre, l1 + 1, idx - l2 + l1, ino, l2, idx - 1, post, l3, l3 + idx - l2 - 1) and self.check(pre, r1 + 1 - r2 + idx, r1, ino, idx + 1, r2, post, r3 + idx - r2, r3 - 1)\n\ndef checktree(preorder, inorder, postorder, N):\n return self.check(preorder, 0, N - 1, inorder, 0, N - 1, postorder, 0, N - 1)", "def __init__(data):\n self.left = None\n self.data = data\n self.right = None\n\ndef Search(start, end, inorder, val):\n for i in range(start, end + 1):\n if inorder[i] == val:\n return i\n return -1\n\ndef ConstructTree(start, end, preindx, N, preorder, inorder, ans):\n if start > end:\n return None\n if preindx[0] >= N:\n return None\n root = Node(preorder[preindx[0]])\n indx = self.Search(start, end, inorder, preorder[preindx[0]])\n if indx == -1:\n ans[0] = False\n preindx[0] += 1\n root.left = self.ConstructTree(start, indx - 1, preindx, N, preorder, inorder, ans)\n root.right = self.ConstructTree(indx + 1, end, preindx, N, preorder, inorder, ans)\n return root\n\ndef Postorder(root, postindx, N, postorder, ans):\n if root == None:\n return\n if postindx[0] >= N:\n return\n self.Postorder(root.left, postindx, N, postorder, ans)\n self.Postorder(root.right, postindx, N, postorder, ans)\n if root.data != postorder[postindx[0]]:\n ans[0] = False\n postindx[0] += 1\n\ndef checktree(preorder, inorder, postorder, N):\n preindx = [0]\n ans = [True]\n root = self.ConstructTree(0, N - 1, preindx, N, preorder, inorder, ans)\n if ans[0] == False:\n return False\n postindx = [0]\n self.Postorder(root, postindx, N, postorder, ans)\n return ans[0]", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return True\n if N == 1:\n return preorder[0] == postorder[0] and postorder[0] == inorder[0]\n root = preorder[0]\n if root != postorder[N - 1]:\n return False\n if root not in set(inorder):\n return False\n else:\n rooti = inorder.index(root)\n leftN = rooti\n rightN = N - rooti - 1\n return self.checktree(preorder[1:leftN + 1], inorder[:rooti], postorder[:leftN], leftN) and self.checktree(preorder[leftN + 1:], inorder[rooti + 1:], postorder[leftN:N - 1], rightN)", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return True\n if N == 1:\n return inorder[0] == preorder[0] and preorder[0] == postorder[0]\n root = preorder[0]\n if root != postorder[N - 1]:\n return False\n if root not in set(inorder):\n return False\n else:\n for i in range(N):\n if inorder[i] == postorder[N - 1]:\n break\n return self.checktree(preorder[1:i + 1], inorder[:i], postorder[:i], i) and self.checktree(preorder[i + 1:], inorder[i + 1:], postorder[i:N - 1], N - i - 1)", "def __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef checktree(preorder, inorder, postorde, N):\n\n def postorder(root):\n if root is None:\n return []\n return postorder(root.left) + postorder(root.right) + [root.data]\n\n def recursive(inorder, preorder, N, idx=0, left=0, right=N - 1):\n if idx == N:\n return (None, idx)\n cur = preorder[idx]\n root = None\n for i in range(left, right + 1):\n if inorder[i] == cur:\n root = Node(cur)\n break\n if root:\n (root.left, idx) = recursive(inorder, preorder, N, idx + 1, left, i - 1)\n (root.right, idx) = recursive(inorder, preorder, N, idx, i + 1, right)\n return (root, idx)\n (root, idx) = recursive(inorder, preorder, N)\n post = postorder(root)\n if post == postorde:\n return True\n else:\n return False", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return True\n if N == 1:\n return preorder[0] == postorder[0] and postorder[0] == inorder[0]\n root = preorder[0]\n if root != postorder[N - 1]:\n return False\n if root not in set(inorder):\n return False\n else:\n index = inorder.index(root)\n left = index\n right = N - index - 1\n return self.checktree(preorder[1:left + 1], inorder[:index], postorder[:left], left) and self.checktree(preorder[left + 1:], inorder[index + 1:], postorder[left:N - 1], right)", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return True\n if N == 1:\n return preorder[0] == postorder[0] and postorder[0] == inorder[0]\n root = preorder[0]\n if root != postorder[-1]:\n return False\n if root not in set(inorder):\n return False\n else:\n index = inorder.index(root)\n lst = index\n rst = N - index - 1\n return self.checktree(preorder[1:index + 1], inorder[:index], postorder[:lst], lst) and self.checktree(preorder[lst + 1:], inorder[index + 1:], postorder[lst:N - 1], rst)", "def __init__(d):\n self.data = d\n self.left = None\n self.right = None\n\ndef checktree(preorder, inorder, postorder, N):\n m = {}\n for i in range(N):\n m[inorder[i]] = i\n l = [0]\n\n def construct(st, end):\n if st > end:\n return None\n node = Node(preorder[l[0]])\n pos = m[preorder[l[0]]]\n l[0] += 1\n try:\n node.left = construct(st, pos - 1)\n node.right = construct(pos + 1, end)\n except:\n return None\n return node\n root = construct(0, N - 1)\n l = []\n\n def post(r):\n if r:\n post(r.left)\n post(r.right)\n l.append(r.data)\n post(root)\n return l == postorder", "def __init__(val):\n self.val = val\n self.left = self.right = None\n\ndef build(pre, ino):\n tem = [True]\n n = len(pre)\n\n def rec(st, en, n):\n if st > en or ind[0] >= n or tem[0] == None:\n return\n nod = Node(pre[ind[0]])\n ind[0] += 1\n idx = st - 1\n for i in range(st, en + 1):\n if ino[i] == nod.val:\n idx = i\n break\n if idx == st - 1:\n tem[0] = None\n return\n nod.left = rec(st, idx - 1, n)\n nod.right = rec(idx + 1, en, n)\n return nod\n ind = [0]\n root = Node(pre[0])\n ind[0] += 1\n idx = inorder.index(root.val)\n root.left = rec(0, idx - 1, n)\n root.right = rec(idx + 1, n - 1, n)\n if tem[0] == None:\n return tem[0]\n return root\n\ndef checktree(preorder, inorder, postorder, N):\n root = self.build(preorder, inorder)\n if root is None:\n return False\n ind = [0, True]\n\n def rec(nod, n):\n if nod is None or ind[1] == False:\n return\n if nod is not None and ind[0] >= n:\n ind[1] = False\n return\n rec(nod.left, n)\n rec(nod.right, n)\n if postorder[ind[0]] != nod.val:\n ind[1] = False\n return\n ind[0] += 1\n rec(root, N)\n return ind[1]", "def checktree(preorder, inorder, postorder, N):\n\n def f(inord, pre, st, en, i, n, d, arr):\n if st > en or i[0] >= n:\n return\n pos = d[pre[i[0]]]\n val = pre[i[0]]\n i[0] += 1\n f(inord, pre, st, pos - 1, i, n, d, arr)\n f(inord, pre, pos + 1, en, i, n, d, arr)\n arr += [val]\n ind = [0]\n d = {}\n for i in range(N):\n d[inorder[i]] = i\n arr = []\n f(inorder, preorder, 0, N - 1, ind, N, d, arr)\n for i in range(N):\n if arr[i] != postorder[i]:\n return False\n return True", "def checktreeutil(preorder, inorder, postorder):\n if len(preorder) >= 1 and len(postorder) >= 1 and (len(inorder) >= 1):\n if len(preorder) != len(postorder):\n return False\n temp = -10000000\n for i in range(len(inorder)):\n if inorder[i] == preorder[0]:\n temp = i\n if temp == -10000000:\n return False\n if len(preorder) != 0 and len(postorder) != 0:\n if preorder[0] != postorder[len(postorder) - 1]:\n return False\n return self.checktreeutil(preorder[1:1 + temp], inorder[0:temp], postorder[0:temp]) and self.checktreeutil(preorder[temp + 1:], inorder[temp + 1:], postorder[temp:len(postorder) - 1])\n return True\n\ndef checktree(preorder, inorder, postorder, N):\n return self.checktreeutil(preorder, inorder, postorder)", "def __init__(v):\n self.val = v\n self.left = None\n self.right = None\n\ndef checktree(pr, io, po, n):\n valid = True\n\n def f(pr, io):\n nonlocal valid\n if not valid:\n return\n if len(pr) == 0 and len(io) == 0:\n return\n if len(pr) != len(io) or pr[0] not in io:\n valid = False\n return\n if len(pr) == 1:\n z.append(pr[0])\n return\n i = io.index(pr[0])\n if len(pr) > 1:\n f(pr[1:i + 1], io[:i])\n f(pr[i + 1:], io[i + 1:])\n z.append(pr[0])\n z = []\n f(pr, io)\n return z == po", "def __init__(data, left=None, right=None):\n self.data = data\n self.left = left\n self.right = right\n\ndef checktree(preorder, inorder, postorder, N):\n\n def postOrder(root):\n if root:\n postOrder(root.left)\n postOrder(root.right)\n post.append(root.data)\n\n def buildTree(inStart, inEnd, preStart, preEnd):\n if inStart > inEnd or preStart > preEnd:\n return None\n root = Node(preorder[preStart])\n inRoot = inMap[root.data]\n inLeft = inRoot - inStart\n root.left = buildTree(inStart, inRoot - 1, preStart + 1, preStart + inLeft)\n root.right = buildTree(inRoot + 1, inEnd, preStart + inLeft + 1, preEnd)\n return root\n inMap = {}\n for i in range(N):\n inMap[inorder[i]] = i\n try:\n root = buildTree(0, N - 1, 0, N - 1)\n except:\n return False\n post = []\n postOrder(root)\n for i in range(N):\n if postorder[i] != post[i]:\n return False\n return True", "def __init__(data):\n self.data = data\n self.left = None\n self.right = None\n\ndef post(root, crr):\n if root == None:\n return\n self.post(root.left, crr)\n self.post(root.right, crr)\n crr.append(root.data)\n return crr\n\ndef solve(pre, ino, N, arr, s, e, hm):\n if arr[0] >= N or s > e:\n return None\n el = pre[arr[0]]\n root = Node(el)\n arr[0] += 1\n pos = hm[el] - 1\n root.left = self.solve(pre, ino, N, arr, s, pos - 1, hm)\n root.right = self.solve(pre, ino, N, arr, pos + 1, e, hm)\n return root\n\ndef checktree(preorder, inorder, postorder, N):\n hm = {}\n for i in range(N):\n hm[inorder[i]] = i + 1\n arr = [0]\n s = 0\n e = N - 1\n root = self.solve(preorder, inorder, N, arr, s, e, hm)\n crr = []\n crr = self.post(root, crr)\n if crr == postorder:\n return 1\n return 0", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return True\n if N == 1:\n return preorder[0] == postorder[0] and postorder[0] == inorder[0]\n root = preorder[0]\n idx = -1\n for i in range(N):\n if inorder[i] == preorder[0]:\n idx = i\n break\n if idx == -1:\n return False\n if preorder[0] != postorder[N - 1]:\n return False\n w1 = self.checktree(preorder[1:], inorder, postorder, idx)\n w2 = self.checktree(preorder[idx + 1:], inorder[idx + 1:], postorder[idx:], N - idx - 1)\n return w1 and w2", "def checktree(preorder, inorder, postorder, N):\n if not preorder and (not inorder) and (not postorder):\n return True\n if len(preorder) != len(inorder) or len(inorder) != len(postorder) or len(postorder) != len(preorder):\n return False\n preorderRoot = preorder[0]\n postorderRoot = postorder[-1]\n if preorderRoot != postorderRoot:\n return False\n try:\n rootIndex = inorder.index(preorderRoot)\n except ValueError:\n return False\n leftsubTree = self.checktree(preorder[1:rootIndex + 1], inorder[:rootIndex], postorder[:rootIndex], N)\n rightsubTree = self.checktree(preorder[rootIndex + 1:], inorder[rootIndex + 1:], postorder[rootIndex:-1], N)\n return leftsubTree and rightsubTree", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return True\n if preorder[0] != postorder[-1]:\n return False\n root = preorder[0]\n if root not in inorder:\n return False\n else:\n p = inorder.index(preorder[0])\n lt = self.checktree(preorder[1:p + 1], inorder[:p], postorder[:p], p)\n rt = self.checktree(preorder[p + 1:], inorder[p + 1:], postorder[p:N - 1], N - p - 1)\n return lt & rt", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return 1\n if N == 1:\n return preorder[0] == inorder[0] and inorder[0] == postorder[0]\n idx = -1\n for i in range(N):\n if inorder[i] == preorder[0]:\n idx = i\n break\n if idx == -1:\n return 0\n if preorder[0] != postorder[N - 1]:\n return 0\n ret1 = self.checktree(preorder[1:], inorder, postorder, idx)\n ret2 = self.checktree(preorder[idx + 1:], inorder[idx + 1:], postorder[idx:], N - idx - 1)\n return ret1 and ret2", "def checktree(preorder, inorder, postorder, N):\n if N == 0:\n return True\n if N == 1:\n return preorder[0] == inorder[0] and inorder[0] == postorder[0]\n root = preorder[0]\n if root != postorder[N - 1]:\n return False\n if root not in set(inorder):\n return False\n else:\n index_of_root = inorder.index(root)\n left_part = index_of_root\n right_part = N - index_of_root - 1\n return self.checktree(preorder[1:left_part + 1], inorder[:index_of_root], postorder[:left_part], left_part) and self.checktree(preorder[left_part + 1:], inorder[index_of_root + 1:], postorder[left_part:N - 1], right_part)", "def checktree(preorder, inorder, postorder, n):\n if not n:\n return True\n if n == 1:\n return preorder[0] == postorder[0] and postorder[0] == inorder[0]\n idx = -1\n for i in range(n):\n if inorder[i] == preorder[0]:\n idx = i\n break\n if idx == -1:\n return 0\n if preorder[0] != postorder[n - 1]:\n return 0\n left = self.checktree(preorder[1:], inorder, postorder, idx)\n right = self.checktree(preorder[idx + 1:], inorder[idx + 1:], postorder[idx:], n - idx - 1)\n return left and right", "def build(preorder, ind, inorder_l, inorder_h, inorder_map):\n if ind[0] == len(preorder):\n return None\n val = preorder[ind[0]]\n inorder_i = inorder_map[val]\n if inorder_i < inorder_l or inorder_i > inorder_h:\n return None\n cur = Node(val)\n ind[0] += 1\n cur.left = build(preorder, ind, inorder_l, inorder_i - 1, inorder_map)\n cur.right = build(preorder, ind, inorder_i + 1, inorder_h, inorder_map)\n return cur\n\ndef check_same(cur, postorder, ind, res):\n if not cur:\n return\n check_same(cur.left, postorder, ind, res)\n check_same(cur.right, postorder, ind, res)\n if ind[0] == len(postorder):\n res[0] = False\n return\n val = postorder[ind[0]]\n ind[0] += 1\n if cur.data != val:\n res[0] = False\n return\n return True\n\ndef __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef checktree(preorder, inorder, postorder, N):\n inorder_map = {inorder[i]: i for i in range(len(inorder))}\n ind = [0]\n root = build(preorder, ind, 0, len(inorder) - 1, inorder_map)\n res = [True]\n ind = [0]\n check_same(root, postorder, ind, res)\n traverse_to_end = ind[0] == len(postorder)\n return res[0] and traverse_to_end", "def __init__(data):\n self.data = data\n self.left = None\n self.right = None\n\ndef checktree(preorder, inorder, postorder, N):\n flag = [False]\n\n def rec1(a, b):\n if flag[0]:\n return None\n if not a:\n return None\n ele = b.pop(0)\n if ele not in a:\n flag[0] = True\n return None\n ind = a.index(ele)\n node = Tree(ele)\n node.left = rec1(a[:ind], b)\n node.right = rec1(a[ind + 1:], b)\n return node\n\n def rec2(a, b):\n if flag[0]:\n return None\n if not a:\n return None\n ele = b.pop(0)\n if ele not in a:\n flag[0] = True\n return None\n ind = a.index(ele)\n node = Tree(ele)\n node.right = rec2(a[ind + 1:], b)\n node.left = rec2(a[:ind], b)\n return node\n root1 = rec1(inorder, preorder)\n root2 = rec2(inorder, postorder[::-1])\n\n def identicalTrees(a, b):\n if a is None and b is None:\n return True\n if a is not None and b is not None:\n return a.data == b.data and identicalTrees(a.left, b.left) and identicalTrees(a.right, b.right)\n return False\n if identicalTrees(root1, root2) and (not flag[0]):\n return True\n return False"], "starter_code": "def checktree(preorder, inorder, postorder, N):\n", "input_output": {"inputs": ["N = 5\npreorder[] = {1, 2, 4, 5, 3}\ninorder[] = {4, 2, 5, 1, 3}\npostorder[] = {4, 5, 2, 3, 1}", "N = 5\npreorder[] = {1, 5, 4, 2, 3}\ninorder[] = {4, 2, 5, 1, 3}\npostorder[] = {4, 1, 2, 3, 5}"], "outputs": ["Yes", "No"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Recursion", "Algorithms", "Tree", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/cb02d40f50b0113c47cd9036e5f340bb51b32289/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N^{2})", "entry_point": "checktree", "task_id": "TACO_lite/94", "example": [[], []]} +{"requirement": "# Task\n You are given three integers `l, d and x`. Your task is:\n```\n\u2022 determine the minimal integer n \n such that l \u2264 n \u2264 d, and the sum of its digits equals x.\n\u2022 determine the maximal integer m \n such that l \u2264 m \u2264 d, and the sum of its digits equals x.\n```\nIt is guaranteed that such numbers always exist.\n\n# Input/Output\n\n\n - `[input]` integer `l`\n\n - `[input]` integer `d`\n\n `1 \u2264 l \u2264 d \u2264 10000.`\n\n\n - `[input]` integer `x`\n\n `1 \u2264 x \u2264 36`\n\n\n - `[output]` an integer array\n\n Array of two elements, where the first element is `n`, and the second one is `m`.\n\n\n# Example\n\n For `l = 500, d = 505, x = 10`, the output should be `[505, 505]`.\n \n For `l = 100, d = 200, x = 10`, the output should be `[109, 190]`.", "solutions": ["def min_and_max(l, d, x):\n listOfCorect = [num for num in list(range(l, d + 1)) if sum(map(int, str(num))) == x]\n return [min(listOfCorect), max(listOfCorect)]", "def min_and_max(l, d, x):\n for n in range(l, d + 1):\n if sum(map(int, str(n))) == x:\n break\n for m in range(d, l - 1, -1):\n if sum(map(int, str(m))) == x:\n break\n return [n, m]", "def min_and_max(l, d, x):\n return [next((i for i in range(l, d + 1) if sum((int(n) for n in str(i))) == x)), next((i for i in range(d, l - 1, -1) if sum((int(n) for n in str(i))) == x))]", "def min_and_max(l, d, x):\n\n def min_or_max(l, d, x, end, step):\n return next((i for i in range(l, d + end, step) if sum(map(int, list(str(i)))) == x))\n return [min_or_max(l, d, x, 1, 1), min_or_max(d, l, x, 0, -1)]", "func = lambda n: sum(map(int, str(n)))\n\ndef min_and_max(l, d, x):\n while func(l) != x:\n l += 1\n while func(d) != x:\n d -= 1\n return [l, d]", "from operator import itemgetter\n\ndef min_and_max(l, d, x):\n return list(itemgetter(0, -1)([i for i in range(l, d + 1) if sum(map(int, list(str(i)))) == x]))", "def min_and_max(l, d, x):\n arr = [i for i in range(l, d + 1) if sum(map(int, str(i))) == x]\n return [arr[0], arr[-1]]", "def min_and_max(l, d, x):\n d_sum = lambda n: sum(map(int, str(n)))\n min = next((i for i in range(l, d + 1) if d_sum(i) == x))\n max = next((i for i in range(d, l - 1, -1) if d_sum(i) == x))\n return [min, max]"], "starter_code": "def min_and_max(l, d, x):\n", "input_output": {"fn_name": "min_and_max", "inputs": [[100, 200, 10], [123, 456, 5], [99, 501, 5], [99, 234, 1], [99, 234, 19], [99, 5001, 27], [99, 5001, 28], [2000, 7000, 3]], "outputs": [[[109, 190]], [[131, 410]], [[104, 500]], [[100, 100]], [[199, 199]], [[999, 4995]], [[1999, 4996]], [[2001, 3000]]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/58fd52b59a9f65c398000096", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "min_and_max", "task_id": "TACO_lite/114", "example": [[[500, 505, 10], [100, 200, 10]], ["[505, 505]", "[109, 190]"]]} +{"requirement": "Write a function that takes an array/list of numbers and returns a number such that \n\nExplanation\ntotal([1,2,3,4,5]) => 48\n\n1+2=3--\\ 3+5 => 8 \\\n2+3=5--/ \\ == 8+12=>20\\ \n ==>5+7=> 12 / \\ 20+28 => 48\n3+4=7--\\ / == 12+16=>28/\n4+5=9--/ 7+9 => 16 /\n\n\nif total([1,2,3]) => 8 then \n\n\nfirst+second => 3 \\\n then 3+5 => 8\nsecond+third => 5 /\n\n\n### Examples\n```python\ntotal([-1,-1,-1]) => -4\ntotal([1,2,3,4]) => 20\n```\n\n**Note:** each array/list will have at least an element and all elements will be valid numbers.", "solutions": ["def total(arr):\n while len(arr) > 1:\n arr = [x + y for (x, y) in zip(arr, arr[1:])]\n return arr[0]", "def total(arr):\n from math import factorial as fact\n choose = lambda a, b: fact(a) / (fact(a - b) * fact(b))\n return sum((choose(len(arr) - 1, i) * v for (i, v) in enumerate(arr)))", "def total(xs):\n return xs[0] if len(xs) == 1 else total([xs[i] + x for (i, x) in enumerate(xs[1:])])", "def total(arr):\n if len(arr) == 1:\n return arr[0]\n arr2 = []\n for i in range(len(arr) - 1):\n arr2.append(arr[i] + arr[i + 1])\n return total(arr2)", "def total(arr):\n while len(arr) > 2:\n arr = [x + y for (x, y) in zip(arr, arr[1:])]\n return sum(arr)", "total = lambda a: a[0] if len(a) == 1 else total([a[i] + a[i + 1] for i in range(len(a) - 1)])", "from math import factorial as fac\n\ndef C(n, k):\n return fac(n) // (fac(k) * fac(n - k))\n\ndef total(arr):\n l = len(arr)\n return sum((arr[i] * C(l - 1, i) for i in range(l)))", "def total(arr):\n a = arr[:]\n for i in range(len(a), 1, -1):\n for j in range(1, i):\n a[j - 1] += a[j]\n return a[0]"], "starter_code": "def total(arr):\n", "input_output": {"fn_name": "total", "inputs": [[[1, 2, 3, 4, 5]], [[1, 2, 3, 4]], [[1, 2, 3]], [[4, 4, 52, 23, 32, 1, -1]], [[4, 4, 5, -1]], [[-1, -1, -1]], [[-1, -1, -10, 42, 92, 1, 23, 6, -3]], [[-1, 1, -1, 1]], [[42]]], "outputs": [[48], [20], [8], [1753], [30], [-4], [9248], [0], [42]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Lists", "Fundamentals", "Logic", "Arrays"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/559fed8454b12433ff0000a2", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "total", "task_id": "TACO_lite/9", "example": [[[[1, 2, 3, 4, 5]], [[-1, -1, -1]], [[1, 2, 3, 4]]], ["48", "-4", "20"]]} +{"requirement": "You are given the prices of stock for n number of days. every ith day tell the price of the stock on that day.find the maximum profit that you can make by buying and selling stock any number of times as you can't proceed with other transactions if you hold any transaction.\nExample:\nInput:\nn = 7\nprices = [1,2,3,4,5,6,7]\nOutput:\n6\nExplaination:\nWe can make the maximum profit by buying the stock on the first day and selling it on the last day.\nYour Task:\nYou don't have to read input or print anything. Your task is to complete the function maximizeProfit() which takes the integer n and array prices and returns the maximum profit that can earn.\nExpected Time Complexity: O(n)\nExpected Space Complexity: O(n^{2})\nNOTE: can you solve this in less space complexity?\nConstraint:\n1<=n<=10^{5}\n1<=prices[i]<=10^{5}", "solutions": ["def maximumprofit(prices, n):\n n = len(prices)\n curr = [0 for i in range(2)]\n nex = [0 for i in range(2)]\n profit = 0\n for ind in range(n - 1, -1, -1):\n for buy in range(0, 2):\n if buy:\n buynow = -prices[ind] + nex[0]\n notbuy = 0 + nex[1]\n profit = max(buynow, notbuy)\n else:\n sellnow = prices[ind] + nex[1]\n notsell = 0 + nex[0]\n profit = max(sellnow, notsell)\n curr[buy] = profit\n nex = curr\n return nex[1]", "def maximumprofit(prices, n):\n ans = 0\n prev = 0\n for i in range(1, n):\n if prices[i] > prices[prev]:\n ans += prices[i] - prices[prev]\n prev = i\n return ans", "def maximumprofit(prices, n):\n Max = 0\n for i in range(1, len(prices)):\n if prices[i] > prices[i - 1]:\n Max += prices[i] - prices[i - 1]\n return Max", "def maximumprofit(prices, n):\n profit = 0\n for i in range(n - 1):\n x = prices[i + 1] - prices[i]\n if x < 0:\n continue\n profit += x\n if profit < 0:\n return 0\n return profit", "def maximumprofit(prices, n):\n dp = [[-1 for i in range(2)] for j in range(n + 1)]\n dp[n][0] = dp[n][1] = 0\n for ind in range(n - 1, -1, -1):\n for buy in range(2):\n if buy:\n profit = max(-prices[ind] + dp[ind + 1][0], dp[ind + 1][1])\n else:\n profit = max(prices[ind] + dp[ind + 1][1], dp[ind + 1][0])\n dp[ind][buy] = profit\n return dp[0][1]", "def maximumprofit(prices, n):\n prev = [-1 for i in range(2)]\n for i in range(1, -1, -1):\n prev[i] = 0\n for ind in range(n - 1, -1, -1):\n temp = [-1 for i in range(2)]\n for buy in range(1, -1, -1):\n if buy == 1:\n temp[buy] = max(-prices[ind] + prev[0], 0 + prev[1])\n else:\n temp[buy] = max(prices[ind] + prev[1], 0 + prev[0])\n prev = temp\n return prev[1]", "def maximumprofit(A, n):\n i = 0\n ans = 0\n while i < n:\n while i + 1 < n and A[i] >= A[i + 1]:\n i += 1\n l = A[i]\n while i + 1 < n and A[i] <= A[i + 1]:\n i += 1\n r = A[i]\n if l == r:\n return ans\n ans += r - l\n i += 1\n return ans", "def maximumprofit(prices, n):\n minm = prices[0]\n profit = 0\n for i in range(1, n):\n if prices[i] > minm:\n profit += prices[i] - minm\n minm = prices[i]\n else:\n minm = prices[i]\n return profit", "def maximumprofit(prices, n):\n n = len(prices)\n dp = [[0 for _ in range(3)] for _ in range(n + 1)]\n for i in range(n - 1, -1, -1):\n for buy in range(2):\n if buy == 1:\n dp[i][buy] = max(-prices[i] + dp[i + 1][0], dp[i + 1][1])\n else:\n dp[i][buy] = max(prices[i] + dp[i + 1][1], dp[i + 1][0])\n return dp[0][1]", "def maximumprofit(prices, n):\n (profit, A) = (0, prices)\n for i in range(n - 1):\n if A[i + 1] > A[i]:\n profit += A[i + 1] - A[i]\n return profit", "def maximumprofit(prices, n):\n dp = [[0 for i in range(2)] for i in range(n + 1)]\n ans = 0\n for j in range(1, len(prices)):\n if prices[j - 1] < prices[j]:\n ans += prices[j] - prices[j - 1]\n return ans", "def maximumprofit(prices, n):\n max_profit = 0\n for i in range(1, n):\n if prices[i] > prices[i - 1]:\n max_profit += prices[i] - prices[i - 1]\n return max_profit", "def maximumprofit(prices, n):\n after = [0 for i in range(2)]\n for i in range(2):\n after[i] = 0\n for ind in range(n - 1, -1, -1):\n curr = [0 for i in range(2)]\n curr[1] = max(-prices[ind] + after[0], after[1])\n curr[0] = max(prices[ind] + after[1], after[0])\n after = curr\n return after[1]", "def maximumprofit(arr, n):\n dp = [[0 for i in range(2)] for j in range(n + 1)]\n dp[n][0] = 0\n dp[n][1] = 0\n for idx in range(n - 1, -1, -1):\n for buy in range(2):\n profit = 0\n if buy:\n p = -arr[idx] + dp[idx + 1][0]\n np = 0 + dp[idx + 1][1]\n profit = max(profit, max(p, np))\n else:\n s = arr[idx] + dp[idx + 1][1]\n ns = 0 + dp[idx + 1][0]\n profit = max(profit, max(s, ns))\n dp[idx][buy] = profit\n return dp[0][1]", "def maximumprofit(prices, n):\n profit = 0\n i = 1\n while i < n:\n buy = i - 1\n while i < n and prices[i] > prices[i - 1]:\n i += 1\n sell = i - 1\n profit += prices[sell] - prices[buy]\n i += 1\n return profit", "def maximumprofit(prices, n):\n dp = [[0] * 2 for _ in range(n + 1)]\n profit = 0\n for i in range(n - 1, -1, -1):\n for j in range(2):\n if j == 0:\n profit = max(dp[i + 1][0], dp[i + 1][1] - prices[i])\n if j == 1:\n profit = max(dp[i + 1][1], dp[i + 1][0] + prices[i])\n dp[i][j] = profit\n return dp[0][0]", "def maximumprofit(arr, n):\n i = 0\n final_ans = []\n while i < n - 1:\n if arr[i] <= arr[i + 1]:\n ans = []\n ans.append(arr[i])\n while i < n - 1 and arr[i] <= arr[i + 1]:\n i += 1\n ans.append(arr[i])\n final_ans.append(ans)\n else:\n i += 1\n answer = 0\n for res in final_ans:\n answer = answer + (res[1] - res[0])\n return answer", "def maximumprofit(prices, n):\n ans = 0\n for i in range(1, n):\n ans += max(0, prices[i] - prices[i - 1])\n return ans", "def maximumprofit(prices, n):\n n = len(prices)\n dp = [[0] * 2 for i in range(n + 1)]\n dp[n][0] = dp[n][1] = 0\n for idx in range(n - 1, -1, -1):\n for buy in range(0, 2):\n profit = 0\n if buy:\n profit = max(-prices[idx] + dp[idx + 1][0], 0 + dp[idx + 1][1])\n else:\n profit = max(prices[idx] + dp[idx + 1][1], 0 + dp[idx + 1][0])\n dp[idx][buy] = profit\n return dp[0][1]", "def maximumprofit(A, n):\n ahead = [0, 0]\n curr = [0, 0]\n ahead[0] = ahead[1] = 0\n for ind in range(n - 1, -1, -1):\n for buy in range(2):\n if buy:\n take = -A[ind] + ahead[0]\n noTake = 0 + ahead[1]\n curr[buy] = max(take, noTake)\n else:\n take = A[ind] + ahead[1]\n noTake = 0 + ahead[0]\n curr[buy] = max(take, noTake)\n ahead = curr\n return ahead[1]", "def maximumprofit(A, n):\n dp = [[0 for _ in range(2)] for _ in range(n + 1)]\n (dp[n][0], dp[n][1]) = (0, 0)\n for ind in range(n - 1, -1, -1):\n for buy in range(2):\n if buy:\n take = -A[ind] + dp[ind + 1][0]\n noTake = 0 + dp[ind + 1][1]\n dp[ind][buy] = max(take, noTake)\n else:\n take = A[ind] + dp[ind + 1][1]\n noTake = 0 + dp[ind + 1][0]\n dp[ind][buy] = max(take, noTake)\n return dp[0][1]", "import sys\nsys.setrecursionlimit(10 ** 8)\nmod = 10 ** 9\n\ndef maximumprofit(arr, n):\n dp = [[0 for j in range(0, 2)] for i in range(0, n + 1)]\n dp[n][0] = 0\n dp[n][1] = 0\n for i in range(n - 1, -1, -1):\n for j in range(0, 2):\n profit = 0\n if j == 0:\n buy = -arr[i] + dp[i + 1][1]\n notbuy = dp[i + 1][0]\n profit = max(buy, notbuy)\n elif j == 1:\n sell = arr[i] + dp[i + 1][0]\n notsell = dp[i + 1][1]\n profit = max(sell, notsell)\n dp[i][j] = profit\n return dp[0][0]", "def maximumprofit(arr, n):\n (l, r) = (0, 1)\n total = 0\n prev = 0\n while r < n:\n curr = arr[r] - arr[l]\n if curr > prev:\n prev = curr\n if r == n - 1:\n total += prev\n elif curr < prev:\n total += prev\n prev = 0\n l = r\n r += 1\n return total", "def maximumprofit(prices, n):\n ahead = [0] * 2\n ahead[0] = 0\n ahead[1] = 0\n for ind in range(n - 1, -1, -1):\n cur = [0] * 2\n for buy in range(2):\n if buy:\n profit = max(-1 * prices[ind] + ahead[0], ahead[1])\n else:\n profit = max(prices[ind] + ahead[1], ahead[0])\n cur[buy] = profit\n ahead = cur\n return ahead[1]", "import sys\n\ndef maximumprofit(prices, n):\n minI = 0\n res = []\n for i in range(n):\n if i == n - 1 or (i < n - 1 and prices[i] > prices[i + 1]):\n if i != minI:\n res.append([minI, i])\n minI = i + 1\n prof = 0\n for p in res:\n prof += prices[p[1]] - prices[p[0]]\n return prof", "def maximumprofit(prices, n):\n total_profit = 0\n buy = 0\n sell = 0\n for i in range(1, n):\n if prices[i] >= prices[i - 1]:\n sell += 1\n else:\n total_profit += prices[sell] - prices[buy]\n buy = i\n sell = i\n total_profit += prices[sell] - prices[buy]\n return total_profit"], "starter_code": "def maximumprofit(prices, n):\n", "input_output": {"inputs": ["n = 7\nprices = [1,2,3,4,5,6,7]"], "outputs": ["6"]}, "difficulty": "MEDIUM", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/buy-stock-2/1", "Expected Auxiliary Space": "O(n^{2})", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "maximumprofit", "task_id": "TACO_lite/4", "example": [[[7, [1, 2, 3, 4, 5, 6, 7]]], [null]]} +{"requirement": "A grid is a perfect starting point for many games (Chess, battleships, Candy Crush!).\n\nMaking a digital chessboard I think is an interesting way of visualising how loops can work together.\n\nYour task is to write a function that takes two integers `rows` and `columns` and returns a chessboard pattern as a two dimensional array.\n\nSo `chessBoard(6,4)` should return an array like this:\n\n\n [\n [\"O\",\"X\",\"O\",\"X\"],\n [\"X\",\"O\",\"X\",\"O\"],\n [\"O\",\"X\",\"O\",\"X\"],\n [\"X\",\"O\",\"X\",\"O\"],\n [\"O\",\"X\",\"O\",\"X\"],\n [\"X\",\"O\",\"X\",\"O\"]\n ]\n\nAnd `chessBoard(3,7)` should return this:\n\n\n [\n [\"O\",\"X\",\"O\",\"X\",\"O\",\"X\",\"O\"],\n [\"X\",\"O\",\"X\",\"O\",\"X\",\"O\",\"X\"],\n [\"O\",\"X\",\"O\",\"X\",\"O\",\"X\",\"O\"]\n ]\n\nThe white spaces should be represented by an: `'O'`\n\nand the black an: `'X'`\n\nThe first row should always start with a white space `'O'`", "solutions": ["def chess_board(rows, columns):\n return [['OX'[(row + col) % 2] for col in range(columns)] for row in range(rows)]", "def chess_board(rows, columns):\n ans = []\n for i in range(1, rows + 1, 1):\n l = []\n for j in range(i, columns + i, 1):\n if j % 2 != 0:\n l.append('O')\n else:\n l.append('X')\n ans.append(l)\n return ans", "chess_board = lambda rows, cols: [['X' if (y + x) % 2 else 'O' for x in range(cols)] for y in range(rows)]", "chess_board = lambda r, c: [['OX'[i + j & 1] for i in range(c)] for j in range(r)]", "def chess_board(rows, columns):\n board = []\n for row in range(rows):\n if row % 2:\n board.append(['X' if not column % 2 else 'O' for column in range(columns)])\n else:\n board.append(['O' if not column % 2 else 'X' for column in range(columns)])\n return board", "def chess_board(a, b):\n return [list('OXXO'[i % 2::2] * (b // 2 + 1))[:b] for i in range(a)]", "from itertools import cycle\n\ndef chess_board(rows, columns):\n result = []\n for i in range(rows):\n grida = cycle(['O', 'X'])\n gridb = cycle(['X', 'O'])\n result.append([next(gridb) if i % 2 else next(grida) for x in range(columns)])\n return result", "def chess_board(rows, columns):\n return [['OX'[(row + column) % 2] for column in range(columns)] for row in range(rows)]", "def chess_board(rows, columns):\n line = ['X', 'O'] * columns\n return [line[:columns] if r % 2 else line[1:columns + 1] for r in range(rows)]", "chess_board = lambda r, c: [['OX'[(i + j) % 2] for j in range(c)] for i in range(r)]"], "starter_code": "def chess_board(rows, columns):\n", "input_output": {"fn_name": "chess_board", "inputs": [[1, 1], [1, 2], [2, 1], [2, 2], [6, 6]], "outputs": [[[["O"]]], [[["O", "X"]]], [[["O"], ["X"]]], [[["O", "X"], ["X", "O"]]], [[["O", "X", "O", "X", "O", "X"], ["X", "O", "X", "O", "X", "O"], ["O", "X", "O", "X", "O", "X"], ["X", "O", "X", "O", "X", "O"], ["O", "X", "O", "X", "O", "X"], ["X", "O", "X", "O", "X", "O"]]]]}, "difficulty": "EASY", "raw_tags": ["ASCII Art", "Algorithms", "Fundamentals", "Puzzles"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/56242b89689c35449b000059", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "chess_board", "task_id": "TACO_lite/31", "example": [[[6, 4], [3, 7]], ["[['O', 'X', 'O', 'X'], ['X', 'O', 'X', 'O'], ['O', 'X', 'O', 'X'], ['X', 'O', 'X', 'O'], ['O', 'X', 'O', 'X'], ['X', 'O', 'X', 'O']]", "[['O', 'X', 'O', 'X', 'O', 'X', 'O'], ['X', 'O', 'X', 'O', 'X', 'O', 'X'], ['O', 'X', 'O', 'X', 'O', 'X', 'O']]"]]} +{"requirement": "Given an array of integers nums, write a method that returns the \"pivot\" index of this array.\n\nWe 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.\n\nIf no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.\n\n\nExample 1:\n\nInput: \nnums = [1, 7, 3, 6, 5, 6]\nOutput: 3\nExplanation: \nThe sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.\nAlso, 3 is the first index where this occurs.\n\n\n\nExample 2:\n\nInput: \nnums = [1, 2, 3]\nOutput: -1\nExplanation: \nThere is no index that satisfies the conditions in the problem statement.\n\n\n\nNote:\nThe length of nums will be in the range [0, 10000].\nEach element nums[i] will be an integer in the range [-1000, 1000].", "solutions": ["def pivotindex(nums):\n (left, right) = (0, sum(nums))\n for (index, num) in enumerate(nums):\n right -= num\n if left == right:\n return index\n left += num\n return -1", "def pivotindex(nums):\n if len(nums) == 0:\n return -1\n leftSum = sum(nums)\n rightSum = 0\n for i in range(len(nums)):\n leftSum = leftSum - nums[i]\n if rightSum == leftSum:\n return i\n rightSum = rightSum + nums[i]\n return -1", "def pivotindex(nums):\n ret = sum(nums)\n left = 0\n for (k, v) in enumerate(nums):\n if left * 2 + v == ret:\n return k\n left += v\n return -1", "def pivotindex(nums):\n left_sum = 0\n right_sum = sum(nums)\n for index in range(0, len(nums)):\n right_sum -= nums[index]\n if left_sum == right_sum:\n return index\n left_sum += nums[index]\n return -1", "def pivotindex(nums):\n n = sum(nums)\n sum_num = n\n for i in range(len(nums)):\n n -= nums[i]\n if (sum_num - nums[i]) / 2 == n:\n return i\n return -1", "def pivotindex(nums):\n if len(nums) == 0:\n return -1\n if len(nums) == 1:\n return nums[0]\n left = 0\n right = 0\n for i in range(1, len(nums)):\n right += nums[i]\n if left == right:\n return 0\n for i in range(1, len(nums)):\n left += nums[i - 1]\n right -= nums[i]\n if left == right:\n return i\n return -1", "def pivotindex(nums):\n if nums == []:\n return -1\n sum = 0\n for i in range(len(nums)):\n sum += nums[i]\n if nums[0] == sum:\n return 0\n left_sum = 0\n for i in range(len(nums) - 1):\n left_sum += nums[i]\n if left_sum * 2 == sum - nums[i + 1]:\n return i + 1\n if nums[len(nums) - 1] == sum:\n return len(nums) - 1\n return -1", "def pivotindex(nums):\n l = len(nums)\n if l < 3:\n return -1\n s = [0] * l\n s[0] = nums[0]\n for i in range(1, l):\n s[i] = s[i - 1] + nums[i]\n d = [0] * l\n d[l - 1] = nums[l - 1]\n for j in range(l - 2, -1, -1):\n d[j] = d[j + 1] + nums[j]\n for i in range(0, l):\n if s[i] == d[i]:\n return i\n return -1"], "starter_code": "def pivotindex(nums: List[int]) -> int:\n", "input_output": {"fn_name": "pivotIndex", "inputs": [[[1, 7, 3, 6, 5, 6]]], "outputs": [3]}, "difficulty": "EASY", "raw_tags": ["Prefix Sum", "Array"], "name": null, "source": "leetcode", "tags": ["Data structures", "Range queries"], "skill_types": ["Data structures", "Range queries"], "url": "https://leetcode.com/problems/find-pivot-index/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "pivotindex", "task_id": "TACO_lite/36", "example": [[[[1, 7, 3, 6, 5, 6]], [[1, 2, 3]]], ["3", "-1"]]} +{"requirement": "You have n\u00a0\u00a0tiles, where each tile has one letter tiles[i] printed on it.\nReturn the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.\n\u00a0\nExample 1:\nInput: tiles = \"AAB\"\nOutput: 8\nExplanation: The possible sequences are \"A\", \"B\", \"AA\", \"AB\", \"BA\", \"AAB\", \"ABA\", \"BAA\".\n\nExample 2:\nInput: tiles = \"AAABBC\"\nOutput: 188\n\nExample 3:\nInput: tiles = \"V\"\nOutput: 1\n\n\u00a0\nConstraints:\n\n1 <= tiles.length <= 7\ntiles consists of uppercase English letters.", "solutions": ["def numtilepossibilities(tiles: str) -> int:\n res = 0\n freqs = [f + 1 for f in Counter(tiles).values()]\n for t in itertools.product(*map(range, freqs)):\n n = sum(t)\n subtotal = math.factorial(n)\n for freq in t:\n subtotal //= math.factorial(freq)\n res += subtotal\n return res - 1", "def numtilepossibilities(tiles: str) -> int:\n return len(set((x for i in range(1, len(tiles) + 1) for x in itertools.permutations(tiles, i))))", "def numtilepossibilities(tiles: str) -> int:\n\n def freq(tiles):\n d = {}\n for c in tiles:\n if c in d:\n d[c] += 1\n else:\n d[c] = 1\n return d\n\n def build(d, s):\n new_d = {}\n for (key, value) in d.items():\n if key == s:\n new_d[key] = value - 1\n else:\n new_d[key] = value\n return new_d\n\n def generate(options):\n sol = []\n for (key, value) in options.items():\n if value > 0:\n sol.append(key)\n fringe = generate(build(options, key))\n sol += fringe\n sol += [key + f for f in fringe]\n return sol\n return len(set(generate(freq(tiles))))", "def numtilepossibilities(tiles: str) -> int:\n\n def find(s):\n if len(s) <= 1:\n return set([s])\n ret = set()\n for i in range(len(s)):\n head = s[i]\n tails = find(s[:i] + s[i + 1:])\n ret = ret.union(tails)\n for tail in tails:\n for j in range(len(tail) + 1):\n temp = tail[:j] + head + tail[j:]\n ret.add(temp)\n return ret\n res = find(tiles)\n return len(set(res))", "from collections import Counter\n\ndef numtilepossibilities(tiles: str) -> int:\n (c_all, visited) = (Counter(tiles), set())\n stack = [(x, Counter([x])) for x in c_all]\n while stack:\n (element, c) = stack.pop()\n if element not in visited:\n stack.extend([(element + x, c + Counter([x])) for x in c_all - c])\n visited.add(element)\n return len(visited)", "def numtilepossibilities(tiles: str) -> int:\n pos = set()\n\n def choose(s, n, pref=''):\n if n == 0:\n pos.add(pref)\n for i in range(len(s)):\n choose(s[:i] + s[i + 1:], n - 1, pref + s[i])\n for i in range(1, len(tiles) + 1):\n choose(tiles, i)\n return len(pos)", "def numtilepossibilities(tiles: str) -> int:\n words = set()\n curr = ''\n tile_count = {}\n for x in tiles:\n if x not in tile_count:\n tile_count[x] = 0\n tile_count[x] += 1\n\n def walk(curr, tiles, words):\n for tile in tiles:\n if tiles[tile] > 0:\n temp = curr + tile\n temp_tiles = tiles.copy()\n temp_tiles[tile] -= 1\n words.add(temp)\n walk(temp, temp_tiles, words)\n for tile in tile_count:\n walk('', tile_count, words)\n return len(words)", "def __init__():\n self.total = 0\n self.string = []\n self.dict_ = {}\n self.arr = []\n self.n = 0\n\ndef perm():\n if self.n == len(self.string):\n self.total += 1\n for i in range(len(self.arr)):\n if self.arr[i][1] > 0:\n self.arr[i][1] -= 1\n self.string.append(self.arr[i][0])\n self.perm()\n self.string.pop()\n self.arr[i][1] += 1\n\ndef numtilepossibilities(tiles: str) -> int:\n for string in tiles:\n if string in self.dict_:\n self.dict_[string] += 1\n else:\n self.dict_[string] = 1\n for key in self.dict_:\n temp = [key, self.dict_[key]]\n self.arr.append(temp)\n for i in range(1, len(tiles) + 1):\n self.n = i\n self.perm()\n return self.total", "def numtilepossibilities(tiles: str) -> int:\n combination_set = self.generateTilePossibilities(tiles)\n return len(combination_set)\n\ndef generateTilePossibilities(tiles: str):\n n = len(tiles)\n combination_set = set()\n for index in range(n):\n combination_set.add(tiles[index])\n if n > 1:\n for index in range(n):\n tiles_without_n = tiles[0:index] + tiles[index + 1:]\n additional_combinations = self.generateTilePossibilities(tiles_without_n)\n combination_set.add(tiles_without_n)\n for combination in additional_combinations:\n combination_set.add(combination)\n for second_index in range(len(combination)):\n new_tile_combination = combination[0:second_index] + tiles[index] + combination[second_index:]\n combination_set.add(new_tile_combination)\n return combination_set", "def numtilepossibilities(tiles: str) -> int:\n\n def count(tiles):\n counter = set()\n if len(tiles) == 1:\n counter.add(tiles)\n elif len(tiles) == 2:\n counter.add(tiles)\n counter.add(tiles[::-1])\n counter.add(tiles[0])\n counter.add(tiles[1])\n else:\n for (idx, i) in enumerate(tiles):\n x = count(tiles[:idx] + tiles[idx + 1:])\n extra = set()\n for j in x:\n extra.add(tiles[idx] + j)\n extra.add(j + tiles[idx])\n for k in range(1, len(j) - 1):\n extra.add(j[:k] + tiles[idx] + j[k + 1:])\n x.update(extra)\n counter.update(x)\n return counter\n return len(count(tiles))", "def __init__():\n self.seen = set()\n self.result = set()\n\ndef numtilepossibilities(tiles: str) -> int:\n self.dfs(tiles, 0, [])\n return len(self.result) - 1\n\ndef dfs(string, idx, path):\n st = ''.join(path)\n if st not in self.seen:\n self.result.update((''.join(p) for p in permutations(st)))\n self.seen.add(st)\n for i in range(idx, len(string)):\n self.dfs(string, i + 1, path + [string[i]])", "def numtilepossibilities(tiles: str) -> int:\n d = {}\n for i in range(len(tiles)):\n if tiles[i] in d:\n d[tiles[i]] += 1\n else:\n d[tiles[i]] = 1\n\n def countnum(d):\n if d == {}:\n return 0\n c = 0\n s = set(d.items())\n for (k, v) in s:\n d[k] -= 1\n if d[k] == 0:\n del d[k]\n c += 1 + countnum(d)\n if k in d:\n d[k] += 1\n else:\n d[k] = 1\n return c\n return countnum(d)", "def numtilepossibilities(tiles: str) -> int:\n res = set()\n\n def dfs(path, t):\n if path not in res:\n if path:\n res.add(path)\n for i in range(len(t)):\n dfs(path + t[i], t[:i] + t[i + 1:])\n dfs('', tiles)\n return len(res)", "def numtilepossibilities(tiles: str) -> int:\n res = set()\n\n def backtrack(path, curr):\n if path not in res:\n if path:\n res.add(path)\n for i in range(len(curr)):\n backtrack(path + curr[i], curr[:i] + curr[i + 1:])\n backtrack('', tiles)\n return len(res)", "def numtilepossibilities(tiles: str) -> int:\n result = set()\n maxx = len(tiles)\n\n def dfs(result, tiles, current_sequence=''):\n result.add(current_sequence)\n for t in tiles:\n tiles_c = tiles.replace(t, '', 1)\n dfs(result, tiles_c, current_sequence + t)\n dfs(result, tiles)\n return len(result) - 1", "def numtilepossibilities(tiles: str) -> int:\n setter = set()\n res = []\n for r in range(1, len(tiles) + 1):\n res.append(list(itertools.permutations(tiles, r)))\n result = []\n for re in res:\n result.append(list(set(re)))\n leng = 0\n for i in result:\n leng += len(i)\n return leng", "def numtilepossibilities(tiles: str) -> int:\n tile_counts = collections.Counter(tiles)\n len_counts = [1] + [0] * len(tiles)\n for tile in tile_counts:\n new_len_counts = [0] * (len(tiles) + 1)\n num_tiles = tile_counts[tile]\n for num_inserted in range(num_tiles + 1):\n for (old_len, old_len_count) in enumerate(len_counts):\n new_len = old_len + num_inserted\n if new_len > len(tiles):\n break\n num_patterns = math.comb(new_len, num_inserted)\n new_len_counts[new_len] += old_len_count * num_patterns\n len_counts = new_len_counts\n return sum(len_counts) - 1", "def buildString(currString, count, op):\n flag = True\n for i in count:\n if count[i] != 0:\n flag = False\n break\n if flag:\n return\n for ch in count:\n if count[ch] == 0:\n continue\n tempString = currString\n tempString += ch\n op.add(tempString)\n count[ch] -= 1\n tempCount = count.copy()\n buildString(tempString, tempCount, op)\n count[ch] += 1\n\ndef numtilepossibilities(tiles: str) -> int:\n count = {}\n for i in tiles:\n if i not in count:\n count[i] = 0\n count[i] += 1\n op = set()\n for ch in count:\n tempString = ch\n op.add(tempString)\n count[ch] -= 1\n tempCount = count.copy()\n buildString(tempString, tempCount, op)\n count[ch] += 1\n return len(op)", "def numtilepossibilities(tiles: str) -> int:\n\n def dfs(state):\n res.append(state.copy())\n for i in range(len(state)):\n if state[i] < full_state[i]:\n state[i] += 1\n dfs(state)\n state[i] -= 1\n memo = collections.Counter(tiles)\n full_state = list(memo.values())\n state = [0 for _ in range(len(memo))]\n res = []\n dfs(state)\n return len(res) - 1", "def numtilepossibilities(tiles: str) -> int:\n res = {}\n\n def dfs(seq, tiles):\n if seq not in res and seq != '':\n res[seq] = 1\n for i in range(len(tiles)):\n dfs(seq + tiles[i], tiles[:i] + tiles[i + 1:])\n dfs('', tiles)\n return len(res)", "def numtilepossibilities(tiles: str) -> int:\n\n def backtracking(idx=0, seq='', remaining=tiles):\n for (i, tile) in enumerate(remaining):\n res.add(seq + tile)\n backtracking(idx + 1, seq + tile, remaining[:i] + remaining[i + 1:])\n res = set()\n backtracking()\n return len(res)", "def numtilepossibilities(tiles: str) -> int:\n\n def dfs(elements):\n if prev_elements:\n result.add(''.join(prev_elements))\n for e in elements:\n next_elements = elements[:]\n next_elements.remove(e)\n prev_elements.append(e)\n dfs(next_elements)\n prev_elements.pop()\n result = set()\n prev_elements = []\n dfs(list(tiles))\n return len(result)", "def numtilepossibilities(tiles: str) -> int:\n seqs = set()\n visits = [False] * len(tiles)\n\n def dfs(seq: str, depth: int):\n if seq:\n seqs.add(seq)\n if depth == len(tiles) - 1:\n return\n for i in range(len(tiles)):\n if not visits[i]:\n visits[i] = True\n dfs(seq + tiles[i], depth + 1)\n visits[i] = False\n dfs('', -1)\n return len(seqs)", "def get_permute(opts, cur_sol):\n for i in range(len(opts)):\n c = opts[i]\n cur_sol.append(c)\n self.solutions.add(''.join(cur_sol))\n opts2 = opts\n opts2 = opts2[:i] + opts2[i + 1:]\n self.get_permute(opts2, cur_sol)\n cur_sol.pop()\n\ndef numtilepossibilities(tiles: str) -> int:\n self.solutions = set()\n self.get_permute(tiles, [])\n return len(self.solutions)", "import collections, math\n\ndef numtilepossibilities(tiles: str) -> int:\n freq = collections.Counter(tiles)\n prod = 1\n for f in freq.values():\n prod *= f + 1\n res = 0\n for i in range(1, prod):\n digits = []\n for f in freq.values():\n digits.append(i % (f + 1))\n i = i // (f + 1)\n tmp = math.factorial(sum(digits))\n for d in digits:\n tmp //= math.factorial(d)\n res += tmp\n return res", "def numtilepossibilities(tiles: str) -> int:\n result = set()\n vis = [0] * len(tiles)\n\n def dfs(res, depth):\n if res:\n result.add(res)\n if depth == len(tiles) - 1:\n result.add(res)\n for i in range(len(tiles)):\n if not vis[i]:\n vis[i] = 1\n dfs(res + tiles[i], depth + 1)\n vis[i] = 0\n dfs('', -1)\n return len(result)", "def numtilepossibilities(tiles: str) -> int:\n\n def solve(s, visited):\n seen.add(s)\n if len(s) == len(tiles):\n return 0\n for (i, v) in enumerate(tiles):\n if i not in visited:\n solve(s + v, visited | {i})\n return len(seen)\n seen = set()\n return solve('', set()) - 1", "def numtilepossibilities(tiles: str) -> int:\n result = set()\n\n def dfs_helper(path, t):\n if path:\n result.add(path)\n for i in range(len(t)):\n dfs_helper(path + t[i], t[:i] + t[i + 1:])\n dfs_helper('', tiles)\n return len(result)", "def numtilepossibilities(tiles: str) -> int:\n ans = 0\n s = set()\n\n def tot(curr, rem):\n nonlocal s\n if curr[-1]:\n s.add(tuple(curr[-1]))\n for i in range(len(rem)):\n el = curr[-1]\n if rem[i] == el:\n continue\n tot(curr + [el + [rem[i]]], rem[:i] + rem[i + 1:])\n tot([[]], tiles)\n return len(s)", "def subsets(tiles, buff, buff_index, boolean, s):\n if tuple(buff[:buff_index]) not in s:\n s.add(tuple(buff[:buff_index]))\n self.count += 1\n if len(buff) == buff_index:\n return\n for i in range(0, len(tiles)):\n if not boolean[i]:\n buff[buff_index] = tiles[i]\n boolean[i] = True\n self.subsets(tiles, buff, buff_index + 1, boolean, s)\n boolean[i] = False\n\ndef numtilepossibilities(tiles: str) -> int:\n self.count = 0\n buff = [None] * len(tiles)\n boolean = [False] * len(tiles)\n s = set()\n self.subsets(tiles, buff, 0, boolean, s)\n return self.count - 1", "def numtilepossibilities(tiles):\n res = set()\n\n def helper(t, curr, k):\n if k == len(curr):\n res.add(curr)\n return\n for i in range(len(t)):\n helper(t[:i] + t[i + 1:], curr + t[i], k)\n for i in range(1, len(tiles) + 1):\n helper(tiles, '', i)\n return len(res)", "def make_tile(curr, used, letters, size):\n if len(curr) == size:\n self.res += 1\n return\n i = 0\n while i < len(letters):\n if i not in used:\n used.add(i)\n curr.append(letters[i])\n self.make_tile(curr, used, letters, size)\n curr.pop(-1)\n used.remove(i)\n while i + 1 < len(letters) and letters[i] == letters[i + 1]:\n i += 1\n i += 1\n\ndef numtilepossibilities(tiles: str) -> int:\n self.res = 0\n letters = sorted(tiles)\n for size in range(1, len(tiles) + 1):\n self.make_tile([], set(), letters, size)\n return self.res", "def numtilepossibilities(tiles: str) -> int:\n\n def next_permutation(a):\n for i in range(len(a) - 1, 0, -1):\n if a[i] > a[i - 1]:\n ps = i\n for j in range(i + 1, len(a)):\n if a[j] > a[i - 1] and a[ps] > a[j]:\n ps = j\n (a[ps], a[i - 1]) = (a[i - 1], a[ps])\n p1 = i\n p2 = len(a) - 1\n while p1 < p2:\n (a[p1], a[p2]) = (a[p2], a[p1])\n p1 += 1\n p2 -= 1\n return True\n return False\n n = 1\n for i in range(1, len(tiles) + 1):\n n *= i\n a = set()\n perm = []\n for i in range(len(tiles)):\n perm.append(i)\n for _ in range(n):\n cur = ''\n for i in range(len(tiles)):\n cur += tiles[perm[i]]\n for i in range(len(tiles)):\n a.add(cur[:i + 1])\n next_permutation(perm)\n return len(a)", "from collections import Counter\n\ndef __init__():\n self.sum_ = 0\n\ndef recurse_count(letter_count):\n if len(letter_count) == 0:\n return\n for letter in letter_count:\n self.recurse_count(letter_count - Counter(letter))\n self.sum_ += 1\n return\n\ndef numtilepossibilities(tiles: str) -> int:\n letter_count = Counter(tiles)\n self.recurse_count(letter_count)\n return self.sum_", "def numtilepossibilities(tiles: str) -> int:\n\n def recur(tiles):\n if not tiles:\n return set()\n ans = set()\n temp = ''\n while tiles:\n v = tiles[0]\n ans.add(v)\n new = recur(temp + tiles[1:])\n ans.update(new)\n for k in new:\n ans.add(v + k)\n temp += tiles[0]\n tiles = tiles[1:]\n return ans\n ans = recur(tiles)\n return len(ans)", "def numtilepossibilities(tiles: str) -> int:\n result = set()\n\n def backtrack(left_tiles, curr_seq):\n if len(curr_seq) == k:\n result.add(''.join(curr_seq))\n return\n else:\n for i in range(len(left_tiles)):\n curr_seq.append(left_tiles[i])\n backtrack(left_tiles[:i] + left_tiles[i + 1:], curr_seq)\n curr_seq.pop()\n for k in range(1, len(tiles) + 1):\n backtrack(tiles, [])\n return len(result)", "def numtilepossibilities(tiles: str) -> int:\n\n def recur(tiles):\n if not tiles:\n return set()\n ans = set()\n for (i, v) in enumerate(tiles):\n ans.add(v)\n new = recur(tiles[:i] + tiles[i + 1:])\n ans.update(new)\n for k in new:\n ans.add(v + k)\n return ans\n ans = recur(tiles)\n return len(ans)", "def counts(collect):\n answer = 1\n for char in collect:\n if collect[char]:\n answer += self.counts(collect - collections.Counter(char))\n return answer\n\ndef numtilepossibilities(c):\n return self.counts(collections.Counter(c)) - 1", "def numtilepossibilities(tiles: str) -> int:\n tiles = ''.join(sorted(tiles))\n memo = {}\n\n def helper(s, k):\n if (s, k) not in memo:\n if k == 0:\n memo[s, k] = 1\n else:\n (last, ans) = ('', 0)\n for i in range(len(s)):\n if s[i] != last:\n last = s[i]\n ans += helper(s[:i] + s[i + 1:], k - 1)\n memo[s, k] = ans\n return memo[s, k]\n ret = 0\n for k in range(1, len(tiles) + 1):\n ret += helper(tiles, k)\n return ret", "def numtilepossibilities(tiles: str) -> int:\n\n def perm(k, a):\n if k == 0:\n return []\n elif k == 1:\n return [x for x in a]\n else:\n return [a[i] + y for i in range(len(a)) for y in perm(k - 1, a[:i] + a[i + 1:])]\n out = set()\n for i in range(1, len(tiles) + 1):\n for x in perm(i, tiles):\n out.add(x)\n return len(out)", "def numtilepossibilities(tiles: str) -> int:\n output = set()\n\n def helper(result, options):\n if not options:\n return\n for (idx, o) in enumerate(options):\n tmp = options[:]\n tmp.pop(idx)\n output.add(''.join(result + [o]))\n helper(result + [o], tmp)\n helper([], list(tiles))\n return len(output)", "def numtilepossibilities(tiles: str) -> int:\n\n def helper(curr, tiles):\n for i in range(len(tiles)):\n curr.append(tiles[i])\n pos.add(str(curr))\n c = tiles.copy()\n c.pop(i)\n helper(curr.copy(), c)\n curr.pop()\n tiles = list(tiles)\n pos = set()\n helper([], tiles)\n return len(pos)", "def poss(tiles: str) -> set:\n if len(tiles) == 1:\n return set([tiles[0]])\n output = set()\n for i in range(len(tiles)):\n elem = tiles[i]\n res = self.poss(tiles[:i] + tiles[i + 1:])\n output = output.union(res)\n for elem in res:\n output.add(tiles[i] + elem)\n return output\n\ndef numtilepossibilities(tiles: str) -> int:\n if len(tiles) == 0:\n return 0\n return len(self.poss(tiles))", "def numtilepossibilities(tiles: str) -> int:\n seen = set()\n ans = set()\n\n def backtrack(tiles, seen, curr):\n if curr != '' and curr not in ans:\n ans.add(curr)\n for i in range(len(tiles)):\n if i not in seen:\n seen.add(i)\n backtrack(tiles, seen, curr + tiles[i])\n seen.remove(i)\n backtrack(tiles, seen, '')\n return len(ans)", "from itertools import permutations\n\ndef numtilepossibilities(tiles: str) -> int:\n total = 0\n for size in range(1, len(tiles) + 1):\n total += len(set(permutations(tiles, size)))\n return total", "def numtilepossibilities(tiles: str) -> int:\n\n def backtrack(i, c):\n if i == n:\n return\n for k in c:\n if c[k] > 0:\n self.ans += 1\n backtrack(i + 1, c - Counter(k))\n n = len(tiles)\n counter = Counter(tiles)\n self.ans = 0\n backtrack(0, counter)\n return self.ans", "def __init__():\n self.res = set()\n\ndef backtrack(tiles, curr, indices):\n for i in range(len(tiles)):\n if i not in set(indices):\n curr += tiles[i]\n indices.append(i)\n self.res.add(curr)\n if len(curr) < len(tiles):\n self.backtrack(tiles, curr, indices)\n curr = curr[:-1]\n indices.pop()\n\ndef numtilepossibilities(tiles: str) -> int:\n self.backtrack(tiles, '', [])\n return len(self.res)", "def possible(tiles):\n variants = set()\n if len(tiles) == 1:\n variants.add(tiles[0])\n else:\n for i in range(len(tiles)):\n t = possible(tiles[:i] + tiles[i + 1:])\n variants.update(t)\n for j in t:\n variants.add(tiles[i] + j)\n return variants\n\ndef numtilepossibilities(tiles: str) -> int:\n return len(possible(tiles))", "from itertools import combinations as C\n\ndef numtilepossibilities(tiles: str) -> int:\n num = 0\n for i in range(1, len(tiles) + 1):\n l = set(permutations(tiles, i))\n num += len(l)\n return num", "def numtilepossibilities(tiles: str) -> int:\n possibilities = set()\n\n def swap(arr, l, r):\n if l == r:\n return\n (arr[l], arr[r]) = (arr[r], arr[l])\n\n def add_permutation(arr):\n nonlocal possibilities\n for i in range(len(arr)):\n possibilities.add(''.join(arr[:i + 1]))\n\n def build_permutations(arr, start=0):\n if start >= len(arr):\n add_permutation(arr)\n return\n for i in range(start, len(arr)):\n swap(arr, i, start)\n build_permutations(arr, start + 1)\n swap(arr, i, start)\n build_permutations(list(tiles))\n return len(possibilities)", "def numtilepossibilities(tiles: str) -> int:\n count = 0\n for i in range(1, len(tiles) + 1):\n count += len(set(permutations(tiles, i)))\n return count", "def numtilepossibilities(tiles: str) -> int:\n counter = Counter(tiles)\n self.dfs(counter, [])\n return self.result\n\ndef dfs(counter, curr):\n if curr:\n self.result += 1\n for x in counter:\n curr1 = curr.copy()\n counter1 = counter.copy()\n curr1.append(x)\n counter1[x] -= 1\n if counter1[x] == 0:\n del counter1[x]\n self.dfs(counter1, curr1)", "def numtilepossibilities(s: str) -> int:\n (ans, C) = (0, Counter(s))\n\n def dfs(C, cur):\n nonlocal ans\n if cur:\n ans += 1\n if not C:\n return\n C1 = C.copy()\n for x in C:\n cur.append(x)\n C1[x] -= 1\n if C1[x] == 0:\n del C1[x]\n dfs(C1, cur)\n cur.pop()\n C1[x] += 1\n dfs(C, cur=[])\n return ans", "def numtilepossibilities(tiles: str) -> int:\n tiles = ''.join(sorted(tiles))\n uniques = self.step(tiles)\n return len(uniques) - 1\n\ndef step(tiles: str) -> set:\n if len(tiles) == 0:\n return {''}\n if tiles not in self.memos:\n uniques = set()\n for i in range(len(tiles)):\n c = tiles[i]\n substr = tiles[:i] + tiles[i + 1:]\n substrs_set = self.step(substr)\n for substr in substrs_set:\n uniques.add(substr)\n for j in range(len(substr) + 1):\n new_str = substr[:j] + c + substr[j:]\n uniques.add(new_str)\n self.memos[tiles] = uniques\n return self.memos[tiles]", "def numtilepossibilities(tiles: str) -> int:\n res = set()\n\n def seq(s, l):\n if len(l) == 0:\n res.add(s)\n return\n seq(s, l[1:])\n for i in range(len(l)):\n seq(s + l[i], l[:i] + l[i + 1:])\n seq('', list(tiles))\n return len(res) - 1", "from collections import Counter\n\ndef numtilepossibilities(tiles: str) -> int:\n\n def permutation(num, tiles_counter):\n if num == 1:\n return len(list(tiles_counter))\n rs = 0\n for c in +tiles_counter:\n rs += permutation(num - 1, tiles_counter - Counter({c: 1}))\n return rs\n total = 0\n for i in range(1, len(tiles) + 1):\n total += permutation(i, Counter(tiles))\n return total"], "starter_code": "def numtilepossibilities(tiles: str) -> int:\n", "input_output": {"fn_name": "numTilePossibilities", "inputs": [["\"AAB\""]], "outputs": [89]}, "difficulty": "MEDIUM", "raw_tags": ["Counting", "Backtracking", "String", "Hash Table"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Data structures", "Mathematics", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://leetcode.com/problems/letter-tile-possibilities/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numtilepossibilities", "task_id": "TACO_lite/63", "example": [[["AAB"], ["AAABBC"], ["V"]], ["8", "188", "1"]]} +{"requirement": "Given an array of integers Arr of size N and a number K. Return the maximum sum of a subarray of size K.\nNOTE*: A subarray is a contiguous part of any given array.\nExample 1:\nInput:\nN = 4, K = 2\nArr = [100, 200, 300, 400]\nOutput:\n700\nExplanation:\nArr_{3 } + Arr_{4} =700,\nwhich is maximum.\n \nExample 2:\nInput:\nN = 4, K = 4\nArr = [100, 200, 300, 400]\nOutput:\n1000\nExplanation:\nArr_{1} + Arr_{2} + Arr_{3 } \n+ Arr_{4} =1000,\nwhich is maximum.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function maximumSumSubarray() which takes the integer k, vector Arr with size N, containing the elements of the array and returns the maximum sum of a subarray of size K.\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1<=N<=10^{6}\n1<=K<=N", "solutions": ["def maximumsumsubarray(k, a, n):\n i = j = 0\n mx = sums = 0\n while j < len(a):\n sums += a[j]\n if j - i + 1 < k:\n j += 1\n else:\n mx = max(mx, sums)\n sums = sums - a[i]\n i += 1\n j += 1\n return mx", "def maximumsumsubarray(K, Arr, N):\n winsum = sum(Arr[:K])\n maxsum = winsum\n for i in range(N - K):\n winsum = winsum - Arr[i] + Arr[i + K]\n maxsum = max(maxsum, winsum)\n return maxsum", "def maximumsumsubarray(K, Arr, N):\n start = 0\n end = 0\n sum1 = 0\n ans = 0\n while end < len(Arr):\n sum1 += Arr[end]\n if end - start + 1 == K:\n ans = max(sum1, ans)\n sum1 -= Arr[start]\n start += 1\n end += 1\n return ans", "def maximumsumsubarray(K, Arr, N):\n wstart = 0\n s = 0\n wend = 0\n ans = 0\n while wend < N:\n s += Arr[wend]\n if wend - wstart + 1 == K:\n ans = max(ans, s)\n s -= Arr[wstart]\n wstart += 1\n wend += 1\n return ans", "def maximumsumsubarray(K, Arr, N):\n ws = 0\n we = 0\n s = 0\n ans = 0\n while we < N:\n s += Arr[we]\n if we - ws + 1 == K:\n ans = max(ans, s)\n s -= Arr[ws]\n ws += 1\n we += 1\n return ans", "def maximumsumsubarray(K, Arr, N):\n i = 0\n j = 0\n sum = 0\n mx = -1000000\n while j < N:\n sum += Arr[j]\n if j - i + 1 < K:\n j += 1\n elif j - i + 1 == K:\n mx = max(sum, mx)\n sum -= Arr[i]\n i += 1\n j += 1\n return mx", "def maximumsumsubarray(K, Arr, N):\n i = 0\n j = 0\n sums = 0\n maxi = -10 ** 7\n while j < N:\n sums += Arr[j]\n if j - i + 1 < K:\n j += 1\n elif j - i + 1 == K:\n maxi = max(maxi, sums)\n sums -= Arr[i]\n i += 1\n j += 1\n return maxi", "def maximumsumsubarray(k, a, N):\n sum = 0\n for i in range(0, K):\n sum += a[i]\n max_sum = sum\n start = 0\n for i in range(k, N):\n sum = sum + a[i] - a[start]\n start = start + 1\n if sum > max_sum:\n max_sum = sum\n return max_sum", "def maximumsumsubarray(k, arr, n):\n winsum = sum(arr[:k])\n maxsum = winsum\n for i in range(n - k):\n winsum = winsum - arr[i] + arr[i + k]\n if winsum > maxsum:\n maxsum = winsum\n return maxsum", "def maximumsumsubarray(k, l, n):\n winsum = sum(l[0:k])\n maxsub = winsum\n for i in range(0, n - k):\n winsum = winsum - l[i] + l[i + k]\n maxsub = max(winsum, maxsub)\n return maxsub", "def maximumsumsubarray(K, Arr, N):\n ws = sum(Arr[:K])\n ms = ws\n for i in range(N - K):\n ws = ws - Arr[i] + Arr[K + i]\n ms = max(ms, ws)\n return ms", "def maximumsumsubarray(K, Arr, N):\n s = sum(Arr[:K])\n v = s\n for i in range(N - K):\n s = s - Arr[i] + Arr[i + K]\n v = max(s, v)\n return v", "def maximumsumsubarray(K, Arr, N):\n l = sum(Arr[:K])\n k = l\n for i in range(N - K):\n l = l - Arr[i] + Arr[i + K]\n k = max(k, l)\n return k", "def maximumsumsubarray(K, Arr, N):\n max_sum = sum(Arr[:K])\n cur_sum = max_sum\n for i in range(0, N - K):\n cur_sum += Arr[K + i] - Arr[i]\n max_sum = max(max_sum, cur_sum)\n return max_sum", "from typing import List\n\ndef maximumsumsubarray(K: int, Arr: List[int], N: int) -> int:\n winsum = sum(Arr[:K])\n maxsum = winsum\n for i in range(N - K):\n winsum = winsum - Arr[i] + Arr[i + K]\n maxsum = max(maxsum, winsum)\n return maxsum", "def maximumsumsubarray(K, arr, N):\n win_sum = sum(arr[:K])\n maxsum = win_sum\n for i in range(0, N - K):\n win_sum = win_sum - arr[i] + arr[i + K]\n maxsum = max(win_sum, maxsum)\n return maxsum", "def maximumsumsubarray(K, Arr, N):\n (i, j, total, maxsum) = (0, 0, 0, 0)\n while j < len(Arr):\n total += Arr[j]\n if j - i + 1 < K:\n j += 1\n elif j - i + 1 == K:\n maxsum = max(maxsum, total)\n total = total - Arr[i]\n i += 1\n j += 1\n return maxsum", "def maximumsumsubarray(K, Arr, N):\n win = sum(Arr[:K])\n m = win\n for i in range(N - K):\n win = win - Arr[i] + Arr[i + K]\n m = max(win, m)\n return m", "def maximumsumsubarray(K, Arr, N):\n res = sum(Arr[:K])\n cs = res\n for i in range(K, N):\n cs += Arr[i] - Arr[i - K]\n res = max(res, cs)\n return res", "def maximumsumsubarray(K, Arr, N):\n cur_sum = 0\n ans = 0\n cur_sum = sum(Arr[0:K])\n ans = cur_sum\n i = 0\n j = K\n while j < N:\n cur_sum = cur_sum + Arr[j] - Arr[i]\n ans = max(ans, cur_sum)\n i += 1\n j += 1\n return ans", "def maximumsumsubarray(K, Arr, N):\n if N < K:\n return -1\n sum = 0\n for i in range(K):\n sum = sum + Arr[i]\n csum = sum\n for i in range(K, N):\n csum = csum + Arr[i] - Arr[i - K]\n sum = max(sum, csum)\n return sum", "def maximumsumsubarray(K, arr, N):\n winsum = sum(arr[:K])\n ms = winsum\n for i in range(N - K):\n winsum = winsum - arr[i] + arr[i + K]\n ms = max(ms, winsum)\n return ms", "def maximumsumsubarray(K, Arr, N):\n mx = 0\n sumK = 0\n i = 0\n j = 0\n while j < len(Arr):\n sumK += Arr[j]\n if j - i + 1 < K:\n j += 1\n elif j - i + 1 == K:\n mx = max(mx, sumK)\n sumK -= Arr[i]\n i += 1\n j += 1\n return mx", "def maximumsumsubarray(k, arr, n):\n wind = sum(arr[:k])\n maxsum = wind\n for i in range(n - k):\n wind = wind - arr[i] + arr[i + k]\n maxsum = max(maxsum, wind)\n return maxsum", "def maximumsumsubarray(K, Arr, N):\n res = 0\n curr = 0\n for i in range(K):\n curr = curr + Arr[i]\n if curr > res:\n res = curr\n for i in range(K, N):\n curr = curr + Arr[i] - Arr[i - K]\n if curr > res:\n res = curr\n return res", "def maximumsumsubarray(K, Arr, N):\n w = sum(Arr[:K])\n b = w\n for i in range(N - K):\n w = w - Arr[i] + Arr[i + K]\n b = max(w, b)\n return b", "def maximumsumsubarray(K, Arr, N):\n (l, r) = (0, 0)\n max_ = 0\n sum_ = 0\n while r < N:\n sum_ += Arr[r]\n if r >= K - 1:\n max_ = max(max_, sum_)\n sum_ -= Arr[l]\n l += 1\n r += 1\n return max_", "def maximumsumsubarray(k, nums, n):\n window = Arr[0:K]\n windosum = sum(window)\n maxi = windosum\n for i in range(0, N - K):\n windosum = windosum - Arr[i] + Arr[i + K]\n maxi = max(windosum, maxi)\n return maxi", "from typing import List\n\ndef maximumsumsubarray(K: int, Arr: List[int], N: int) -> int:\n window_sum = sum(Arr[:K])\n max_sum = window_sum\n for i in range(K, N):\n window_sum = window_sum + Arr[i] - Arr[i - K]\n max_sum = max(max_sum, window_sum)\n return max_sum", "def maximumsumsubarray(k, arr, n):\n i = j = ms = curr_sum = 0\n while j < n:\n curr_sum += Arr[j]\n if j - i + 1 == k:\n ms = max(ms, curr_sum)\n curr_sum -= arr[i]\n i += 1\n j += 1\n return ms", "def maximumsumsubarray(K, Arr, N):\n cursum = 0\n res = 0\n for (i, x) in enumerate(Arr):\n if i >= K:\n cursum = cursum - Arr[i - K]\n cursum = cursum + x\n res = max(res, cursum)\n return res", "def maximumsumsubarray(K, Arr, N):\n i = 0\n j = 0\n csum = 0\n maxi = 0\n while j < N:\n csum += Arr[j]\n if j - i + 1 < K:\n j += 1\n elif j - i + 1 == K:\n maxi = max(maxi, csum)\n csum -= Arr[i]\n i += 1\n j += 1\n return maxi", "def maximumsumsubarray(K, Arr, N):\n ws = 0\n ms = 0\n s = 0\n for i in range(N):\n ws += Arr[i]\n if i - s + 1 == K:\n ms = max(ms, ws)\n ws -= Arr[s]\n s += 1\n return ms", "def maximumsumsubarray(K, Arr, N):\n if K < 0 or K > len(Arr):\n return -1\n else:\n sum = 0\n for i in range(0, K):\n sum += Arr[i]\n max_sum = sum\n start = 0\n for j in range(K, len(Arr)):\n sum = sum + Arr[j] - Arr[start]\n start += 1\n if sum > max_sum:\n max_sum = sum\n return max_sum", "def maximumsumsubarray(K, Arr, N):\n maxi = float('-inf')\n curr_sum = 0\n j = 0\n for i in range(K):\n curr_sum += Arr[i]\n maxi = curr_sum\n for i in range(K, len(Arr)):\n curr_sum = curr_sum - Arr[j] + Arr[i]\n maxi = max(curr_sum, maxi)\n j += 1\n return maxi", "def maximumsumsubarray(K, Arr, N):\n if N < K:\n return -1\n temp = 0\n for i in range(K):\n temp += Arr[i]\n maxsum = temp\n for i in range(K, N):\n maxsum += Arr[i] - Arr[i - K]\n temp = max(temp, maxsum)\n return temp", "def maximumsumsubarray(k, arr, n):\n res = 0\n curr = 0\n for i in range(k):\n curr += arr[i]\n if curr > res:\n res = curr\n for i in range(k, n):\n curr = curr + arr[i] - arr[i - k]\n if curr > res:\n res = curr\n return res", "def maximumsumsubarray(K, Arr, N):\n (i, j) = (0, 0)\n s = 0\n mx = float('-inf')\n while j < len(Arr):\n s += Arr[j]\n if j - i + 1 < K:\n j += 1\n elif j - i + 1 == K:\n mx = max(mx, s)\n s -= Arr[i]\n i += 1\n j += 1\n return mx", "def maximumsumsubarray(K, Arr, N):\n if K > N:\n return 0\n if K == N:\n return sum(Arr)\n i = j = 0\n res = 0\n for i in range(K):\n res += Arr[i]\n curr_sum = res\n for i in range(K, N):\n curr_sum += Arr[i] - Arr[i - K]\n res = max(res, curr_sum)\n return res", "def maximumsumsubarray(k, Arr, N):\n s = sum(Arr[:k])\n ans = s\n for i in range(k, N):\n s += Arr[i]\n s -= Arr[i - k]\n ans = max(s, ans)\n return ans"], "starter_code": "def maximumsumsubarray (K,Arr,N):\n", "input_output": {"inputs": ["N = 4, K = 2\nArr = [100, 200, 300, 400]", "N = 4, K = 4\nArr = [100, 200, 300, 400]"], "outputs": ["700", "1000"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "sliding-window", "Misc", "prefix-sum"], "name": null, "source": "geeksforgeeks", "tags": ["Amortized analysis", "Range queries"], "skill_types": ["Amortized analysis", "Range queries"], "url": "https://practice.geeksforgeeks.org/problems/max-sum-subarray-of-size-k5313/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "maximumsumsubarray", "task_id": "TACO_lite/141", "example": [[[4, 2, [100, 200, 300, 400]], [4, 4, [100, 200, 300, 400]]], [null, null]]} +{"requirement": "Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.\n\n Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.\n\nExample 1:\n\nInput: [1,1,2,2,2]\nOutput: true\n\nExplanation: You can form a square with length 2, one side of the square came two sticks with length 1.\n\n\n\nExample 2:\n\nInput: [3,3,3,3,4]\nOutput: false\n\nExplanation: You cannot find a way to form a square with all the matchsticks.\n\n\n\nNote:\n\nThe length sum of the given matchsticks is in the range of 0 to 10^9.\nThe length of the given matchstick array will not exceed 15.", "solutions": ["def makesquare(nums):\n if len(nums) < 4:\n return False\n length = sum(nums)\n if length % 4:\n return False\n length = int(length / 4)\n nums.sort(reverse=True)\n if length < nums[0]:\n return False\n elif length == nums[0]:\n stack = list([(set([0]), 1, length, 1)])\n else:\n stack = list([(set([0]), 1, length - nums[0], 2)])\n while stack:\n (usedSet, startIndex, target, remainRounds) = stack.pop()\n for i in range(len(nums) - 1, startIndex - 1, -1):\n if i in usedSet:\n continue\n num = nums[i]\n if num < target and i + 1 < len(nums):\n stack.append((usedSet | {i}, i + 1, target - num, remainRounds))\n elif num == target:\n if remainRounds == 0:\n return True\n else:\n stack.append((usedSet | {i}, 1, length, remainRounds - 1))\n return False", "def makesquare(nums):\n total = sum(nums)\n if total % 4 != 0 or len(nums) < 4:\n return False\n size = total / 4\n nums.sort(reverse=True)\n used = [False] * len(nums)\n\n def dfs(i, expect):\n if i >= len(nums):\n return expect % size == 0\n if used[i]:\n return dfs(i + 1, expect)\n used[i] = True\n if nums[i] == expect:\n return True\n if nums[i] < expect:\n expect -= nums[i]\n available = [j for j in range(i + 1, len(nums)) if not used[j]]\n for x in available:\n if dfs(x, expect):\n return True\n used[i] = False\n return False\n for i in range(len(nums)):\n if not dfs(i, size):\n return False\n return True", "def makesquare(nums):\n\n def checkv(t, c, nums, used):\n if t == 0:\n return True\n if t < 0:\n return False\n while c < len(nums) and used[c]:\n c = c + 1\n if c >= len(nums):\n return False\n if checkv(t - nums[c], c + 1, nums, used):\n used[c] = True\n return True\n if checkv(t, c + 1, nums, used):\n return True\n return False\n edgel = sum(nums)\n if edgel % 4 != 0 or edgel == 0:\n return False\n edgel = edgel / 4\n nums.sort(key=lambda x: -x)\n n = len(nums)\n used = [False] * n\n for p in range(3):\n t = edgel\n if not checkv(t, 0, nums, used):\n return False\n return True", "def makesquare(nums):\n s = sum(nums)\n if not s % 4 == 0:\n return False\n l = s // 4\n from collections import Counter\n self.c = Counter(nums)\n for _ in range(4):\n n = self.f(0, sorted(self.c.elements(), reverse=True), l, ())\n if not n:\n return False\n self.c.subtract(n)\n return True\n\ndef f(index, keys, sum, nums):\n if sum == 0:\n return nums\n if sum < 0 or index >= len(keys):\n return None\n return self.f(index + 1, keys, sum - keys[index], (*nums, keys[index])) or self.f(index + 1, keys, sum, nums)"], "starter_code": "def makesquare(nums: List[int]) -> bool:\n", "input_output": {"fn_name": "makesquare", "inputs": [[[1, 1, 2, 2, 2]]], "outputs": [true]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Bitmask", "Array", "Backtracking", "Dynamic Programming", "Bit Manipulation"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Bit manipulation", "Data structures", "Complete search"], "skill_types": ["Dynamic programming", "Bit manipulation", "Data structures", "Complete search"], "url": "https://leetcode.com/problems/matchsticks-to-square/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "makesquare", "task_id": "TACO_lite/162", "example": [[], []]} +{"requirement": "Given binary string str of length N. The task is to find the maximum count of consecutive substrings str can be divided into such that all the substrings are balanced i.e. they have an equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then return -1.\nExample 1:\nInput:\nS = \"0100110101\"\nOutput: 4\nExplanation: \nThe required substrings are 01, 0011, 01 and 01.\nExample 2:\nInput:\nS = \"0111100010\"\nOutput: 3\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function maxSubStr() which takes a string S and returns an integer as output.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= S.length <= 10^{5}", "solutions": ["def maxsubstr(input_str):\n count = 0\n balance = 0\n for ch in input_str:\n if ch == '0':\n balance += 1\n elif ch == '1':\n balance -= 1\n if balance == 0:\n count += 1\n if balance != 0:\n return -1\n return count", "def maxsubstr(str):\n (c1, c2) = (0, 0)\n count = 0\n n = len(str)\n for (i, s) in enumerate(str):\n if s == '0':\n c1 += 1\n if s == '1':\n c2 += 1\n if c1 == c2:\n count += 1\n if c1 != c2:\n return -1\n return count", "def maxsubstr(str):\n n = len(str)\n x = 0\n y = 0\n c = 0\n for i in range(0, n):\n if str[i] == '0':\n x += 1\n else:\n y += 1\n if x == y:\n c += 1\n if x != y:\n return -1\n return c", "def maxsubstr(str):\n su = count = total = 0\n for i in str:\n if i == '0':\n total -= 1\n else:\n total += 1\n if total != 0:\n return -1\n else:\n for i in str:\n if i == '0':\n su -= 1\n else:\n su += 1\n if su == 0:\n count += 1\n return count", "def maxsubstr(s):\n count0 = 0\n count1 = 0\n ans = 0\n for i in range(len(s)):\n if s[i] == '0':\n count0 += 1\n if s[i] == '1':\n count1 += 1\n if count0 == count1:\n ans += 1\n if count0 != count1:\n return -1\n return ans", "def maxsubstr(str):\n count = 0\n count1 = 0\n cnt = 0\n for i in range(len(str)):\n if str[i] == '0':\n count += 1\n else:\n count1 += 1\n if count1 == count:\n cnt += 1\n count1 = 0\n count = 0\n if count or count1:\n return -1\n return cnt", "def maxsubstr(string):\n (c0, c1) = (0, 0)\n res = 0\n for i in string:\n if i == '0':\n c0 += 1\n else:\n c1 += 1\n if c0 == c1:\n res += 1\n if c0 != c1:\n return -1\n return res", "def maxsubstr(str):\n cnt0 = 0\n cnt1 = 0\n ans = 0\n for i in str:\n if i == '0':\n cnt0 += 1\n else:\n cnt1 += 1\n if cnt0 == cnt1:\n ans += 1\n if cnt0 != cnt1:\n return -1\n return ans", "def maxsubstr(str):\n if len(str) % 2 != 0:\n return -1\n elif str.count('1') != str.count('0'):\n return -1\n count_0 = 0\n count_1 = 0\n ans = 0\n for i in str:\n if i == '0':\n count_0 += 1\n else:\n count_1 += 1\n if count_0 == count_1:\n ans += 1\n return ans if ans != 0 else -1", "def maxsubstr(str):\n if len(str) % 2 != 0:\n return -1\n zero_cnt = one_cnt = 0\n if str[0] == '0':\n zero_cnt = 1\n else:\n one_cnt = 1\n count = 0\n substr_size = 0\n i = 0\n j = 1\n while i < len(str) and j < len(str):\n if str[j] == '0':\n zero_cnt += 1\n else:\n one_cnt += 1\n j += 1\n if zero_cnt > 0 and one_cnt > 0 and (zero_cnt == one_cnt):\n substr_size += j - i\n zero_cnt = one_cnt = 0\n count += 1\n i = j\n return count if count > 0 and substr_size == len(str) else -1", "def maxsubstr(str):\n count = 0\n total = 0\n for x in str:\n if x == '0':\n total += 1\n else:\n total -= 1\n if total == 0:\n count += 1\n return count if total == 0 else -1", "def maxsubstr(str):\n count0 = 0\n count1 = 0\n count = 0\n for i in range(0, len(str)):\n if str[i] == '0':\n count0 += 1\n if str[i] == '1':\n count1 += 1\n if count0 == count1:\n count += 1\n if count1 != count0:\n return -1\n return count", "def maxsubstr(str):\n n = len(str)\n cnt = 0\n cnt1 = 0\n cnt2 = 0\n for i in range(n):\n if str[i] == '0':\n cnt1 += 1\n else:\n cnt2 += 1\n if cnt1 == cnt2:\n cnt += 1\n if cnt1 != cnt2:\n return -1\n return cnt", "def maxsubstr(str):\n if len(str) == 0 or len(str) == 1 or '1' not in str or ('0' not in str):\n return -1\n dic = {}\n count_0 = 0\n count_1 = 0\n total = 0\n for i in range(len(str)):\n if str[i] in dic:\n dic[str[i]] += 1\n else:\n dic[str[i]] = 1\n if dic['1'] != dic['0']:\n return -1\n for k in range(len(str)):\n if str[k] == '0':\n count_0 += 1\n if str[k] == '1':\n count_1 += 1\n if count_0 == count_1:\n total += 1\n return total", "def maxsubstr(str):\n count_0 = 0\n count_1 = 0\n count = 0\n for i in str:\n if i == '0':\n count_0 += 1\n else:\n count_1 += 1\n if count_0 == count_1:\n count += 1\n if count_0 != count_1:\n return -1\n return count", "def maxsubstr(str):\n n = len(str)\n ans = 0\n i = 0\n (zero, one) = (0, 0)\n while i < n:\n if str[i] == '0':\n zero += 1\n else:\n one += 1\n i += 1\n if zero == one:\n ans += 1\n if zero != one:\n return -1\n return ans", "def maxsubstr(str):\n c0 = 0\n c1 = 0\n count = 0\n for i in str:\n if i == '1':\n c1 += 1\n else:\n c0 += 1\n if c1 == c0:\n count += 1\n if count > 0 and c0 == c1:\n return count\n return -1", "def maxsubstr(str):\n k = j = r = 0\n for i in str:\n if i == '0':\n k += 1\n else:\n j += 1\n if k == j:\n r += 1\n k = j = 0\n if k != 0:\n return -1\n if j != 0:\n return -1\n if r == 0:\n return -1\n return r", "def maxsubstr(str):\n count_0 = 0\n count_1 = 0\n ans = 0\n for i in range(len(s)):\n if s[i] == '0':\n count_0 += 1\n else:\n count_1 += 1\n if count_0 == count_1:\n ans += 1\n elif i == len(s) - 1:\n return -1\n if ans == 0:\n return -1\n return ans", "def maxsubstr(s):\n count = 0\n z_count = 0\n o_count = 0\n for i in s:\n if i == '0':\n z_count += 1\n else:\n o_count += 1\n if z_count == o_count:\n z_count = 0\n o_count = 0\n count += 1\n if z_count == o_count:\n return count\n else:\n return -1", "def maxsubstr(s):\n if len(s) == 1:\n return -1\n if s.count('0') != s.count('1'):\n return -1\n curr = s[0]\n curr_c = 0\n count = 0\n i = 0\n while i < len(s):\n if s[i] == curr:\n curr_c += 1\n else:\n while i < len(s) and s[i] != curr and (curr_c != 0):\n curr_c -= 1\n i += 1\n if curr_c == 0:\n count += 1\n if i < len(s):\n curr = s[i]\n i -= 1\n i += 1\n return count", "def maxsubstr(s):\n if s.count('0') != s.count('1'):\n return -1\n count_0 = 0\n count_1 = 0\n ans = 0\n for elm in s:\n if elm == '0':\n count_0 += 1\n else:\n count_1 += 1\n if count_0 == count_1:\n ans += 1\n return ans", "def maxsubstr(str):\n c = c1 = c2 = 0\n for i in str:\n if i == '0':\n c1 += 1\n else:\n c2 += 1\n if c1 == c2:\n c += 1\n if c1 != c2:\n return -1\n return c", "def maxsubstr(str):\n p = 0\n res = 0\n for i in str:\n if i == '1':\n p -= 1\n else:\n p += 1\n if p == 0:\n res += 1\n if p != 0:\n return -1\n return res", "def maxsubstr(stre):\n n = len(stre)\n (vote, ans) = (0, 0)\n for i in stre:\n if i == '0':\n vote += 1\n else:\n vote -= 1\n if vote == 0:\n ans += 1\n if vote == 0:\n return ans\n return -1", "def maxsubstr(str):\n count0 = 0\n count1 = 0\n n = len(str)\n cnt = 0\n for i in range(n):\n if str[i] == '0':\n count0 += 1\n else:\n count1 += 1\n if count0 == count1:\n cnt += 1\n if count0 != count1:\n return -1\n return cnt", "def maxsubstr(str):\n a = 0\n b = 0\n c = 0\n i = 0\n while i < len(str):\n if str[i] == '0':\n a = a + 1\n else:\n b = b + 1\n if a == b:\n a = 0\n b = 0\n c = c + 1\n i = i + 1\n if a == 0 and b == 0:\n return c\n return -1", "def maxsubstr(str):\n ca = 0\n count = 0\n for i in str:\n if i == '0':\n ca += 1\n else:\n ca -= 1\n if ca == 0:\n count += 1\n if ca == 0:\n return count\n else:\n return -1", "def maxsubstr(str):\n i = 0\n o = 0\n res = 0\n for k in range(len(str) - 1):\n if str[k] == '0':\n o = o + 1\n if o == i:\n res = res + 1\n i = 0\n o = 0\n else:\n i = i + 1\n if o == i:\n res = res + 1\n i = 0\n o = 0\n k = len(str) - 1\n if str[k] == '0':\n o = o + 1\n if o == i:\n res = res + 1\n else:\n return -1\n else:\n i = i + 1\n if o == i:\n res = res + 1\n else:\n return -1\n if res == 0:\n return -1\n else:\n return res", "def maxsubstr(str):\n count_zero = 0\n count_one = 0\n count = 0\n for i in range(len(str)):\n if str[i] == '0':\n count_zero += 1\n else:\n count_one += 1\n if count_zero == count_one:\n count += 1\n if count_zero != count_one:\n return -1\n return count", "def maxsubstr(str):\n n = len(str)\n (cz, count) = (0, 0)\n for i in str:\n if i == '0':\n cz += 1\n else:\n cz -= 1\n if cz == 0:\n count += 1\n if cz == 0:\n return count\n return -1", "def maxsubstr(str):\n i = 0\n s = 0\n c1 = 0\n c2 = 0\n while i < len(str):\n if str[i] == '0':\n c1 += 1\n else:\n c2 += 1\n if c1 == c2:\n s += 1\n c1 = 0\n c2 = 0\n i += 1\n if c1 == c2:\n return s\n else:\n return -1", "def maxsubstr(str):\n count = 0\n c1 = 0\n c0 = 0\n i = 0\n u = ''\n while i < len(s):\n u += s[i]\n if s[i] == '0':\n c0 += 1\n else:\n c1 += 1\n if c1 == c0:\n count += 1\n u = ''\n c1 = 0\n c0 = 0\n if i == len(s) - 1:\n if u != '':\n return -1\n i += 1\n return count", "def maxsubstr(str):\n count = 0\n zeroes = 0\n ones = 0\n for i in str:\n if i == '0':\n zeroes += 1\n else:\n ones += 1\n if zeroes == ones:\n count += 1\n zeroes = 0\n ones = 0\n if ones != zeroes:\n return -1\n if count == 0:\n return -1\n return count", "def maxsubstr(str):\n cz = 0\n co = 0\n out = 0\n for i in str:\n if i == '0':\n cz += 1\n else:\n co += 1\n if cz == co:\n out += 1\n if co != cz:\n return -1\n return out", "def maxsubstr(str):\n c0 = 0\n c1 = 0\n c = 0\n for i in range(len(str)):\n if str[i] == '0':\n c0 += 1\n elif str[i] == '1':\n c1 += 1\n if c0 == c1:\n c += 1\n if c0 != c1:\n return -1\n return c", "def maxsubstr(str):\n ans = 0\n res = 0\n lis = list(str)\n for i in range(0, len(lis)):\n if lis[i] == '1':\n ans = ans + 1\n if lis[i] == '0':\n ans = ans - 1\n if ans == 0:\n res += 1\n ans = 0\n if ans != 0:\n return -1\n return res", "def maxsubstr(str):\n zero = 0\n one = 0\n c = 0\n stack = []\n temp = ''\n for i in range(len(str)):\n if str[i] == '0':\n if stack != [] and stack[-1] == '1':\n x = stack.pop()\n else:\n stack.append('0')\n elif str[i] == '1':\n if stack != [] and stack[-1] == '0':\n x = stack.pop()\n else:\n stack.append('1')\n if stack == []:\n c += 1\n if stack != []:\n return -1\n return c", "def maxsubstr(str):\n mapping = {'1': 0, '0': 0}\n count = 0\n for element in str:\n mapping[element] += 1\n if mapping['0'] == mapping['1']:\n mapping['0'] = 0\n mapping['1'] = 0\n count += 1\n if mapping['0'] == mapping['1'] == 0:\n return count\n return -1", "def maxsubstr(str):\n d1 = {}\n for i in str:\n d1[i] = 1 + d1.get(i, 0)\n if len(set(d1.values())) > 1:\n return -1\n d = {'0': 0, '1': 0}\n i = 0\n j = 0\n c = -1\n f = 0\n while j < len(str):\n d[str[j]] = d[str[j]] + 1\n if d['0'] != d['1']:\n j = j + 1\n else:\n c = c + 1\n f = 1\n d = {'0': 0, '1': 0}\n i = j + 1\n j = i\n if f == 1:\n c = c + 1\n return c\n else:\n return c", "def maxsubstr(str):\n i = 0\n cnt0 = 0\n cnt1 = 0\n cnt = 0\n while i < len(str):\n if str[i] == '0':\n cnt0 += 1\n else:\n cnt1 += 1\n if cnt0 == cnt1:\n cnt += 1\n i += 1\n if cnt0 == cnt1:\n return cnt\n else:\n return -1", "def maxsubstr(s):\n i = 0\n cnt0 = 0\n cnt1 = 0\n ans = 0\n while i < len(s):\n if s[i] == '0':\n cnt0 += 1\n else:\n cnt1 += 1\n if cnt0 == cnt1:\n ans += 1\n i += 1\n if ans == 0 or cnt0 != cnt1:\n return -1\n return ans", "def maxsubstr(str):\n check = ''\n count = 0\n val = 0\n for i in str:\n if count == 0:\n check = i\n count += 1\n elif check == i:\n count += 1\n else:\n count -= 1\n if count == 0:\n val += 1\n if count != 0:\n return -1\n return val", "def maxsubstr(str):\n if str.count('1') != str.count('0'):\n return -1\n count = 0\n ones = 0\n zeros = 0\n for i in range(len(str)):\n if ones == zeros:\n count += 1\n ones = 0\n zeros = 0\n if str[i] == '1':\n ones += 1\n else:\n zeros += 1\n return count", "def maxsubstr(str):\n count = 0\n zero = 0\n one = 0\n for i in str:\n if i == '0':\n zero += 1\n elif i == '1':\n one += 1\n if zero == one:\n count += 1\n if zero == one:\n return count\n else:\n return -1", "def maxsubstr(str):\n c = 0\n zero = 0\n one = 0\n for i in range(len(str)):\n if str[i] == '0':\n zero = zero + 1\n else:\n one = one + 1\n if zero == one:\n c = c + 1\n if zero != one:\n return -1\n return c", "def maxsubstr(str):\n count0 = 0\n count1 = 0\n ans = 0\n for i in str:\n if i == '0':\n count0 += 1\n else:\n count1 += 1\n if count1 == count0:\n ans += 1\n if count1 != count0:\n return -1\n return ans", "def maxsubstr(str):\n c = 0\n zc = 0\n oc = 0\n for i in s:\n if i == '0':\n zc += 1\n else:\n oc += 1\n if zc == oc:\n c += 1\n zc = 0\n oc = 0\n if zc >= 1 or oc >= 1:\n return -1\n else:\n return c", "def maxsubstr(str):\n countZero = 0\n countOne = 0\n res = 0\n for i in range(len(str)):\n if str[i] == '0':\n countZero += 1\n else:\n countOne += 1\n if countZero == countOne:\n res += 1\n countZero = 0\n countOne = 0\n if countZero > 0 or countOne > 0 or countZero != countOne:\n return -1\n return res", "def maxsubstr(str):\n count_0 = 0\n count_1 = 0\n count = 0\n for i in range(len(str)):\n if str[i] == '0':\n count_0 += 1\n else:\n count_1 += 1\n if count_0 == count_1:\n count += 1\n if count_0 != count_1:\n return -1\n elif count_0 == 0 and count_1 == 0:\n return -1\n return count", "def maxsubstr(str):\n z = 0\n ones = 0\n ans = 0\n for i in str:\n if i == '0':\n z += 1\n else:\n ones += 1\n if z == ones:\n ans += 1\n (z, ones) = (0, 0)\n return ans if z == ones else -1", "def maxsubstr(str):\n (one, zero, ans) = (0, 0, 0)\n for i in str:\n if i == '0':\n zero += 1\n else:\n one += 1\n if zero == one:\n ans += 1\n (one, zero) = (0, 0)\n if ans == 0 or one != zero:\n return -1\n else:\n return ans", "from collections import Counter\n\ndef func(s, temp, ans):\n if not s:\n ans[0] = max(ans[0], len(temp))\n return\n for i in range(2, len(s) + 1):\n t = s[:i]\n a = Counter(t)\n if a.get('0', 0) == a.get('1', 0):\n func(s[i:], temp + [t], ans)\n\ndef maxsubstr(s):\n l = 0\n count = 0\n c0 = 0\n c1 = 0\n for i in range(len(s)):\n if s[i] == '0':\n c0 += 1\n else:\n c1 += 1\n if c0 == c1:\n c0 = 0\n c1 = 0\n count += 1\n if c0 != c1:\n return -1\n return count", "def maxsubstr(str):\n counter = 0\n count = 0\n d = {'0': 0, '1': 0}\n for i in str:\n d[i] += 1\n if i == '0':\n counter += 1\n else:\n counter -= 1\n if counter == 0:\n count += 1\n return count if d['0'] == d['1'] else -1", "def maxsubstr(str):\n count0 = 0\n count1 = 0\n ans = 0\n i = 0\n while i < len(str):\n if str[i] == '0':\n count0 += 1\n else:\n count1 += 1\n if count0 == count1:\n ans += 1\n i += 1\n if count0 == count1:\n return ans\n return -1", "def maxsubstr(s):\n count = 0\n summa = 0\n for item in s:\n if item == '1':\n summa += 1\n else:\n summa -= 1\n count += summa == 0\n return count if summa == 0 else -1", "def maxsubstr(str1):\n (count0, count1, res) = (0, 0, 0)\n for i in str1:\n if i == '0':\n count0 += 1\n else:\n count1 += 1\n if count0 == count1:\n (count0, count1, res) = (0, 0, res + 1)\n if count0 > 0 or count1 > 0 or count0 != count1:\n return -1\n return res", "def maxsubstr(str):\n (zero, one) = (0, 0)\n ans = 0\n for each in str:\n if each == '0':\n zero += 1\n if each == '1':\n one += 1\n if zero == one:\n (zero, one) = (0, 0)\n ans += 1\n if zero == one:\n return ans\n else:\n return -1", "def maxsubstr(value):\n n = len(value)\n first_element = value[0]\n last_element = first_element\n count = 0\n count = count + self.operation(last_element, first_element)\n pair = 0\n for i in range(1, n):\n element = value[i]\n count = count + self.operation(element, first_element)\n if count == 0:\n pair = pair + 1\n if pair == 0 or count != 0:\n return -1\n else:\n return pair\n\ndef operation(element, first_element):\n if element == first_element:\n return 1\n else:\n return -1", "def maxsubstr(str):\n c0 = 0\n c1 = 0\n cnt = 0\n for i in range(len(str)):\n if str[i] == '0':\n c0 += 1\n else:\n c1 += 1\n if c0 == c1:\n cnt += 1\n if c0 != c1:\n return -1\n return cnt", "def maxsubstr(str):\n count = 0\n zero = 0\n ones = 0\n for i in range(len(str)):\n if str[i] == '0':\n zero += 1\n elif str[i] == '1':\n ones += 1\n if zero == ones:\n count += 1\n if zero != ones:\n return -1\n return count", "def maxsubstr(str):\n count0 = 0\n count1 = 0\n count = 0\n for (i, j) in enumerate(str):\n if j == '0':\n count0 += 1\n else:\n count1 += 1\n if count0 == count1:\n count += 1\n if count0 != count1:\n return -1\n return count", "def maxsubstr(str):\n c1 = 0\n c2 = 0\n c3 = 0\n for i in range(len(str)):\n if str[i] == '0':\n c1 += 1\n else:\n c2 += 1\n if c1 == c2:\n c3 += 1\n if c1 != c2:\n return -1\n return c3", "def maxsubstr(str):\n count = 0\n arr = []\n sum = 0\n for i in range(0, len(str)):\n if str[i] == '1':\n arr.append(1)\n else:\n arr.append(-1)\n for i in range(0, len(str)):\n sum += arr[i]\n if sum == 0:\n count += 1\n if sum != 0:\n return -1\n return count", "def maxsubstr(str1):\n o = 0\n z = 0\n c = 0\n res = []\n for i in str1:\n if i == '0':\n z = z + 1\n if i == '1':\n o = o + 1\n if z == o:\n res.append(str1[:z + o])\n str1 = str1[z + o:]\n z = 0\n o = 0\n if z > 0 or o > 0:\n return -1\n else:\n return len(res)", "def maxsubstr(str):\n m = 0\n n = 0\n c = 0\n if str.count('1') != str.count('0'):\n return -1\n else:\n for i in range(len(str)):\n if str[i] == '0':\n m += 1\n elif str[i] == '1':\n n += 1\n if m == n:\n m = 0\n n = 0\n c += 1\n return c", "def maxsubstr(s):\n c1 = c2 = 0\n ans = 0\n for i in s:\n if i == '0':\n c1 += 1\n else:\n c2 += 1\n if c1 == c2:\n ans += 1\n if c1 != c2:\n return -1\n return ans", "def maxsubstr(str):\n (x, y, ans) = (0, 0, 0)\n for i in range(len(str)):\n if str[i] == '0':\n x = x + 1\n elif str[i] == '1':\n y = y + 1\n if x == y:\n ans = ans + 1\n if x != y:\n return -1\n return ans", "def maxsubstr(str):\n i = 0\n j = 0\n m_i = 0\n m_j = 0\n count = 0\n for k in range(len(str)):\n if str[k] == '0':\n i += 1\n m_i += 1\n else:\n j += 1\n m_j += 1\n if i == j:\n count += 1\n i = 0\n j = 0\n if m_i != m_j:\n return -1\n else:\n return count", "def maxsubstr(str):\n c = 0\n z = 0\n o = 0\n for i in str:\n if i == '0':\n z += 1\n else:\n o += 1\n if z == o:\n z = 0\n o = 0\n c += 1\n if z != 0 or o != 0:\n return -1\n if c == 0:\n return -1\n return c"], "starter_code": "def maxsubstr(str):\n", "input_output": {"inputs": ["S = \"0100110101\"", "S = \"0111100010\""], "outputs": ["4", "3"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/split-the-binary-string-into-substrings-with-equal-number-of-0s-and-1s/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "maxsubstr", "task_id": "TACO_lite/156", "example": [[["0100110101"], ["0111100010"]], ["4", "3"]]} +{"requirement": "Given a number N, evaluate the following expression. \nf(n-1)*f(n+1) - f(n)*f(n) where f(n) is the n-th Fibonacci number with n >= 1.\nFibonacci Sequence is 0, 1, 1, 2, 3, 5, 8, 13,\u2026 (here 0 is the 0th Fibonacci number)\nExample 1:\nInput: N = 1\nOutput: 1\nExplaination: f(n+1)*f(n-1) - f(n)*f(n) \n= 1*0 - 1*1 = -1.\nExample 2:\nInput: N = 2\nOutput: 1\nExplaination: f(n+1)*f(n-1) - f(n)*f(n) \n= 2*1 - 1*1 = 1.\nYour Task:\nYou do not need to read input or print anything. Your Task is to complete the function fibExpresssion() which takes the value N as input parameters and returns the required difference.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 N \u2264 10^{5}", "solutions": ["def fibexpression(N):\n if N & 1:\n return -1\n return 1", "def fibexpression(N):\n if N % 2 == 0:\n return 1\n else:\n return -1", "def fibexpression(n):\n if n % 2 == 0:\n return 1\n return -1", "def fibexpression(N):\n if not N % 2:\n return 1\n return -1"], "starter_code": "def fibexpression(N):\n", "input_output": {"inputs": ["N = 1", "N = 2"], "outputs": ["1", "1"]}, "difficulty": "EASY", "raw_tags": ["Fibonacci", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/fibonacci-expression3939/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "fibexpression", "task_id": "TACO_lite/129", "example": [[[1], [2]], [-1, 1]]} +{"requirement": "Given a set of n non-negative integers, and a value m, determine if there is a subset of the given set with sum divisible by m.\nExample 1:\nInput: \nn = 4 m = 6 \nnums[] = {3 1 7 5}\nOutput:\n1\nExplanation:\nIf we take the subset {7, 5} then sum\nwill be 12 which is divisible by 6.\nExample 2:\nInput:\nn = 3, m = 5\nnums[] = {1 2 6}\nOutput:\n0\nExplanation: \nAll possible subsets of the given set are \n{1}, {2}, {6}, {1, 2}, {2, 6}, {1, 6}\nand {1, 2, 6}. There is no subset whose\nsum is divisible by 5.\nYour Task:\nYou don't need to read or print anything. Your task is to complete the function DivisibleByM() which takes the given set and m as input parameter and returns 1 if any of the subset(non-empty) sum is divisible by m otherwise returns 0.\nExpected Time Complexity: O(n*m)\nExpected Space Complexity: O(n)\nConstraints:\n1 <= elements in set <= 1000\n1 <= n, m <= 1000", "solutions": ["def divisiblebym(nums, m):\n\n def f(i, rem, nums, dp):\n if rem == 0:\n return True\n if i >= len(nums):\n return False\n if dp[i][rem] != -1:\n return dp[i][rem]\n if rem == -1:\n take = f(i + 1, nums[i] % m, nums, dp)\n ntake = f(i + 1, rem, nums, dp)\n else:\n take = f(i + 1, (rem + nums[i]) % m, nums, dp)\n ntake = f(i + 1, rem, nums, dp)\n dp[i][rem] = take or ntake\n return take or ntake\n dp = [[-1] * (m + 1) for _ in range(len(nums))]\n return int(f(0, -1, nums, dp))", "def divisiblebym(arr, m):\n n = len(arr)\n if n > m:\n return 1\n DP = [False for i in range(m)]\n for i in range(n):\n if DP[0]:\n return 1\n temp = [False for i in range(m)]\n for j in range(m):\n if DP[j] == True:\n if DP[(j + arr[i]) % m] == False:\n temp[(j + arr[i]) % m] = True\n for j in range(m):\n if temp[j]:\n DP[j] = True\n DP[arr[i] % m] = True\n return int(DP[0])", "def divisiblebym(nums, m):\n s = sum(nums)\n n = len(nums)\n t = [[0 for i in range(s + 1)] for j in range(n + 1)]\n for i in range(n + 1):\n t[i][0] = 1\n for i in range(1, n + 1):\n for j in range(1, s + 1):\n if nums[i - 1] <= j:\n t[i][j] = t[i - 1][j - nums[i - 1]] or t[i - 1][j]\n else:\n t[i][j] = t[i - 1][j]\n for i in range(1, s + 1):\n if t[n][i] and i % m == 0:\n return 1\n return 0", "def divisiblebym(a, m):\n n = len(a)\n v = [False] * n\n\n def solve(i, v, s):\n if i > n - 1:\n return False\n if (s + a[i]) % m == 0:\n return True\n if v[i]:\n return 0\n j = i + 1\n v[i] = True\n while j < n:\n if solve(j, v, s + a[i]):\n return True\n j += 1\n v[i] = False\n for i in range(n):\n if solve(i, v, 0):\n return 1\n return 0", "def divisiblebym(nums, m):\n\n def solve(idx, data, d={}):\n if idx == len(nums):\n return False\n data += nums[idx]\n if data % m == 0:\n return True\n return solve(idx + 1, data, d) or solve(idx + 1, 0, d)\n return 1 if solve(0, 0) else 0", "def divisiblebym(A, m):\n dp = [False for i in range(m)]\n n = len(A)\n if n > m:\n return 1\n for i in range(n):\n temp = [False for i in range(m)]\n for j in range(m):\n if dp[j] == True and dp[(j + A[i]) % m] == False:\n temp[(j + A[i]) % m] = True\n for p in range(m):\n if temp[p]:\n dp[p] = True\n dp[A[i] % m] = True\n return 1 if dp[0] else 0", "def subsetDivisible(n, nums, sum, idx, m, dp3):\n if idx == n:\n res = sum and sum % m == 0\n if res:\n dp3.add(sum)\n return 1\n return 0\n if sum in dp3:\n return 1\n picked = self.subsetDivisible(n, nums, sum + nums[idx], idx + 1, m, dp3)\n notPicked = self.subsetDivisible(n, nums, sum, idx + 1, m, dp3)\n return picked | notPicked\n\ndef divisiblebym(nums, m):\n\n def f(ind, sm):\n if sm > 0 and sm % m == 0:\n return 1\n if ind == -1:\n return 0\n return f(ind - 1, sm) or f(ind - 1, sm + nums[ind])\n return f(len(nums) - 1, 0)", "def subsetDivisible(n, nums, sum, idx, m, dp3):\n if idx == n:\n res = sum and sum % m == 0\n if res:\n dp3.add(sum)\n return 1\n return 0\n if sum in dp3:\n return 1\n picked = self.subsetDivisible(n, nums, sum + nums[idx], idx + 1, m, dp3)\n notPicked = self.subsetDivisible(n, nums, sum, idx + 1, m, dp3)\n return picked | notPicked\n\ndef divisiblebym(nums, m):\n dp3 = set()\n return self.subsetDivisible(len(nums), nums, 0, 0, m, dp3)", "def divisiblebym(nums, m):\n\n def f(ind, sm):\n if sm > 0 and sm % m == 0:\n return 1\n if ind == -1:\n return 0\n return f(ind - 1, sm) or f(ind - 1, sm + nums[ind])\n return f(len(nums) - 1, 0)", "def divisiblebym(nums, m):\n if len(nums) > m:\n return 1\n d = {}\n d[0] = 1\n c = 0\n s = 0\n for i in range(0, len(nums)):\n s += nums[i]\n rem = s % m\n if rem in d:\n c += d[rem]\n d[rem] += 1\n else:\n d[rem] = 1\n if c > 0:\n return 1\n else:\n return 0", "def divisiblebym(nums, m):\n s = 0\n for i in nums:\n s = s + i\n dp = [[False for _ in range(s + 1)] for __ in range(len(nums) + 1)]\n for i in range(0, len(dp)):\n dp[i][0] = True\n for i in range(1, len(nums) + 1):\n for j in range(1, s + 1):\n if nums[i - 1] <= j:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i - 1]]\n else:\n dp[i][j] = dp[i - 1][j]\n if j % m == 0 and dp[i][j]:\n return 1\n return 0", "def divisiblebym(nums, m):\n\n def dfs(ss, nums, m):\n if ss < m:\n return False\n if ss % m == 0:\n return True\n for (idx, num) in enumerate(nums):\n val = dfs(ss - num, nums[:idx] + nums[idx + 1:], m)\n if val:\n return True\n return False\n ss = sum(nums)\n nums.insert(0, 0)\n cache = {}\n val = dfs(ss, nums, m)\n return val * 1", "def divisiblebym(nums, m, i=0, cursum=0, memo=None):\n if not memo:\n memo = {}\n if (i, cursum) in memo:\n return memo[i, cursum]\n if cursum > 0 and cursum % m == 0:\n return 1\n if i >= len(nums):\n return 0\n result = self.divisiblebym(nums, m, i + 1, cursum + nums[i], memo) or self.divisiblebym(nums, m, i + 1, cursum, memo)\n memo[i, cursum] = result\n return result", "def divisiblebym(nums, m):\n n = len(nums)\n tar = sum(nums)\n t = [[1 if i == 0 else 0 for i in range(tar + 1)] for j in range(n + 1)]\n for i in range(1, n + 1):\n for j in range(1, tar + 1):\n if nums[i - 1] <= j:\n t[i][j] = t[i - 1][j - nums[i - 1]] | t[i - 1][j]\n else:\n t[i][j] = t[i - 1][j]\n i = m\n while i <= tar:\n if t[-1][i]:\n return 1\n i += m\n return 0", "def divisiblebym(nums, m):\n su = sum(nums)\n PG = [0 for i in range(su + 1)]\n PG1 = [0 for i in range(su + 1)]\n PG[0] = PG1[0] = 1\n for i in nums:\n for j in range(su + 1):\n if PG1[j] == 1:\n PG[j + i] = 1\n if (j + i) % m == 0:\n return 1\n PG1 = PG[:]\n return 0", "def sub_sum_div_by_m(arr, i, sum, m):\n if sum % m == 0 and sum != 0:\n return True\n if i >= len(arr):\n return False\n return self.sub_sum_div_by_m(arr, i + 1, sum, m) or self.sub_sum_div_by_m(arr, i + 1, sum + arr[i], m)\n\ndef divisiblebym(nums, m):\n if self.sub_sum_div_by_m(nums, 0, 0, m):\n return 1\n else:\n return 0", "def divisiblebym(nums, m):\n nm = [[-1 for i in range(sum(nums) + 1)] for j in range(len(nums))]\n\n def dp(s, i, nm, n):\n if i == n:\n if s % m == 0 and s != 0:\n return True\n return False\n x = dp(s + nums[i], i + 1, nm, n)\n y = dp(s, i + 1, nm, n)\n return x or y\n return 1 if dp(0, 0, nm, len(nums)) else 0", "def checkDiv(nums, m, l, p):\n if l % m == 0 and p > 0:\n return True\n if p > 0:\n return self.checkDiv(nums, m, l - nums[p - 1], p - 1) or self.checkDiv(nums, m, l, p - 1)\n return False\n\ndef divisiblebym(nums, m):\n l = sum(nums)\n p = len(nums)\n z = self.checkDiv(nums, m, l, p)\n if z == True:\n return 1\n return 0", "def recur(nums, m, dp, sum, n):\n if sum % m == 0:\n return 1\n if n == 0:\n if sum % m == 0:\n return 1\n return 0\n if sum in dp.keys():\n return dp[sum]\n dp[sum] = self.recur(nums, m, dp, sum + nums[n - 1], n - 1) or self.recur(nums, m, dp, sum, n - 1)\n return dp[sum]\n\ndef divisiblebym(nums, m):\n dp = {}\n for i in range(len(nums) - 1, -1, -1):\n if self.recur(nums, m, dp, nums[i], i):\n return 1\n return 0", "def divisiblebym(nums, m):\n mods = set()\n mods.add(0)\n for el in nums:\n el_mod = el % m\n for mod in list(mods):\n if (mod + el_mod) % m == 0:\n return 1\n mods.add((mod + el_mod) % m)\n return 0", "def divisiblebym(nums, m):\n n = len(nums)\n dp = [[False for j in range(n)] for i in range(n)]\n for i in range(n):\n k = i\n for j in range(0, n - i):\n if i == 0:\n dp[j][k] = nums[j]\n if dp[j][k] % m == 0:\n return 1\n elif i == 1:\n dp[j][k] = nums[j] + nums[k]\n if dp[j][k] % m == 0:\n return 1\n else:\n dp[j][k] = nums[j] + dp[j + 1][k - 1] + nums[k]\n if (nums[j] + nums[k]) % m == 0:\n return 1\n elif dp[j][k] % m == 0:\n return 1\n k += 1\n return 0", "def divisiblebym(nums, m):\n sum1 = sum(nums)\n dp = [0] * (sum1 + 1)\n for i in nums:\n set1 = set()\n for j in dp:\n if j not in set1:\n res = i + j\n if res % m == 0:\n return 1\n if dp[res] == 0:\n dp[res] = res\n set1.add(res)\n if dp[i] == 0:\n if i % m == 0:\n return 1\n dp[i] = i\n return 0", "def subset(arr, n, m):\n t = []\n t = [[False for i in range(sum(arr) + 1)] for j in range(n + 1)]\n for i in range(n + 1):\n for j in range(sum(arr) + 1):\n if i == 0:\n t[i][j] = False\n if j == 0:\n t[i][j] = True\n elif arr[i - 1] <= j:\n t[i][j] = t[i - 1][j - arr[i - 1]] or t[i - 1][j]\n else:\n t[i][j] = t[i - 1][j]\n j = sum(arr)\n while j >= 1:\n if t[n][j] == True and j % m == 0:\n return 1\n j -= 1\n return 0\n\ndef divisiblebym(nums, m):\n n = len(nums)\n return subset(nums, n, m)", "def divisiblebym(nums, m):\n memo = {}\n\n def helper(indx, val):\n if (indx, val) in memo:\n return memo[indx, val]\n if indx == len(nums):\n if val and val % m == 0:\n return 1\n return 0\n pick = helper(indx + 1, val + nums[indx])\n notpick = helper(indx + 1, val)\n memo[indx, val] = pick or notpick\n return memo[indx, val]\n return helper(0, 0)", "def divisiblebym(nums, m):\n n = len(nums)\n for i in range(n):\n ts = nums[i]\n if ts % m == 0:\n return 1\n for j in range(i + 1, n):\n if (nums[j] + ts) % m == 0:\n return 1\n ts += nums[j]\n return 0", "def check(arr, n, m, s):\n dp = [[None for x in range(s + 1)] for y in range(n + 1)]\n for i in range(n + 1):\n for j in range(s + 1):\n if i == 0 and j != 0:\n dp[i][j] = False\n elif j == 0:\n dp[i][j] = True\n elif arr[i - 1] <= j:\n dp[i][j] = max(dp[i - 1][j - arr[i - 1]], dp[i - 1][j])\n else:\n dp[i][j] = dp[i - 1][j]\n res = False\n k = m\n while k <= s:\n for i in range(1, n + 1):\n res = max(res, dp[i][k])\n k += m\n return res\n\ndef divisiblebym(nums, m):\n if self.check(nums, len(nums), m, sum(nums)):\n return 1\n else:\n return 0", "def check(arr, n, m, s):\n if n == 0:\n if s != 0 and s % m == 0:\n return True\n return False\n return self.check(arr, n - 1, m, s + arr[n - 1]) or self.check(arr, n - 1, m, s)\n\ndef divisiblebym(nums, m):\n if m == 0:\n return 0\n if self.check(nums, len(nums), m, 0):\n return 1\n else:\n return 0", "def divisiblebym(nums, m):\n\n def subset_sum_memo(memo: dict, array: list, sum: int, m: int, index: int) -> bool:\n if sum and sum % m == 0:\n return True\n elif index >= len(array):\n return False\n else:\n (value1, value2) = (False, False)\n if sum % m not in memo:\n value1 = subset_sum_memo(memo, array, sum + array[index], m, index + 1)\n value2 = subset_sum_memo(memo, array, sum, m, index + 1)\n if sum:\n memo[sum % m] = value1 or value2\n if not sum:\n return value1 or value2\n return memo[sum % m]\n if len(nums) >= m:\n return 1\n memo = {}\n return 1 if subset_sum_memo(memo, nums, 0, m, 0) else 0", "def devisibleby(arr, n, m, sum):\n if sum != 0 and sum % m == 0:\n return True\n if n <= 0:\n return False\n return self.devisibleby(arr, n - 1, m, sum) or self.devisibleby(arr, n - 1, m, sum + arr[n - 1])\n\ndef divisiblebym(nums, m):\n return 1 if self.devisibleby(nums, len(nums), m, 0) else 0", "def isSubsetSum(arr, n, sum):\n dp = [[0 for j in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if arr[i - 1] > j:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]\n return dp[n][sum]\n\ndef devisibleby(arr, n, m, sum):\n if sum != 0 and sum % m == 0:\n return True\n if n <= 0:\n return False\n return self.devisibleby(arr, n - 1, m, sum) or self.devisibleby(arr, n - 1, m, sum + arr[n - 1])\n\ndef divisiblebym(nums, m):\n return 1 if self.devisibleby(nums, len(nums), m, 0) else 0", "def calculate(arr, i, Sum, m):\n if Sum % m == 0 and Sum != 0:\n return 1\n if i == len(arr):\n return 0\n return self.calculate(arr, i + 1, Sum + arr[i], m) or self.calculate(arr, i + 1, Sum, m)\n\ndef divisiblebym(nums, m):\n return self.calculate(nums, 0, 0, m)", "def divisiblebym(nums, m):\n rangee = sum(nums)\n table = [[0] * (rangee + 1) for _ in range(n + 1)]\n for i in range(len(table)):\n table[i][0] = 1\n for i in range(1, len(table)):\n for j in range(1, len(table[0])):\n if nums[i - 1] <= j:\n table[i][j] = table[i - 1][j - nums[i - 1]] or table[i - 1][j]\n else:\n table[i][j] = table[i - 1][j]\n for i in range(m, len(table[0]), m):\n if table[-1][i]:\n return 1\n return 0", "def __init__():\n self.array = []\n self.allsum = 0\n\ndef callmain(nums, total, n, m):\n if n < 0:\n return False\n if (self.allsum - total) % m == 0 and total != self.allsum:\n return True\n if self.array[n][total] != -1:\n return self.array[n][total]\n self.array[n][total] = self.callmain(nums, total - nums[n - 1], n - 1, m) or self.callmain(nums, total, n - 1, m)\n return self.array[n][total]\n\ndef divisiblebym(nums, m):\n total = sum(nums)\n self.allsum = total\n for i in range(len(nums) + 1):\n temp = []\n for j in range(total + 1):\n temp.append(-1)\n self.array.append(temp)\n x = self.callmain(nums, total, n, m)\n if x == True:\n return 1\n else:\n return 0", "def fun(nums, m, arr_pos):\n if curr_ind >= len(nums):\n return 0\n\ndef divisiblebym(nums, m, curr_ind=0, sum_val=0):\n if sum_val > 0:\n if sum_val % m == 0:\n return 1\n if curr_ind >= len(nums):\n return 0\n a = self.divisiblebym(nums, m, curr_ind + 1, sum_val)\n return a or self.divisiblebym(nums, m, curr_ind + 1, sum_val + nums[curr_ind])", "def divisiblebym(nums, m):\n weights = nums\n n = len(weights)\n S = sum(weights)\n if S % m == 0:\n return 1\n if S < m:\n return 0\n S = sum(weights) // m * m\n dp = [[0] * (S + 1) for x in range(n + 1)]\n for i in range(1, n + 1):\n for j in range(1, S + 1):\n if weights[i - 1] <= j:\n dp[i][j] = max(weights[i - 1] + dp[i - 1][j - weights[i - 1]], dp[i - 1][j])\n else:\n dp[i][j] = dp[i - 1][j]\n for i in range(1, sum(weights) // m + 1):\n if dp[n][i * m] % m == 0 and dp[n][i * m] != 0:\n return 1\n return 0", "def divisiblebym(nums, m):\n dp = []\n for i in range(2):\n dp.append([0] * m)\n for el in nums:\n c = el % m\n if dp[0][(m - c) % m] == 1:\n return 1\n for i in range(m):\n if dp[0][i] == 1:\n dp[1][i] = 1\n dp[1][(i + c) % m] = 1\n dp[1][c] = 1\n dp[0] = dp[1][:]\n dp[1] = [0] * m\n if dp[0][0] == 1:\n return 1\n else:\n return 0", "def divisiblebym(arr, m):\n n = len(arr)\n sm = sum(arr)\n dp = [[0 for i in range(sm + 1)] for j in range(n + 1)]\n ans = 0\n for i in range(n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(1, sm + 1):\n if arr[i - 1] > j:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]\n if j % m == 0:\n ans = ans or dp[i][j]\n return ans", "def divisiblebym(arr, m):\n if len(arr) > m:\n return 1\n dp = [False for _ in range(m)]\n for i in range(n):\n if dp[0]:\n return 1\n temp = [False for _ in range(m)]\n for j in range(m):\n if dp[j]:\n if not dp[(j + arr[i]) % m]:\n temp[(j + arr[i]) % m] = True\n for j in range(m):\n dp[j] = dp[j] or temp[j]\n dp[arr[i] % m] = True\n return int(dp[0])", "def divisiblebym(nums, m):\n mod = [0 for i in range(m)]\n if len(nums) > m:\n return 1\n for i in range(len(nums)):\n temp = [0 for i in range(m)]\n if mod[0]:\n return 1\n for j in range(m):\n if mod[j]:\n if mod[(j + nums[i]) % m] == 0:\n temp[(j + nums[i]) % m] = 1\n temp[nums[i] % m] = 1\n for j in range(m):\n if temp[j]:\n mod[j] = temp[j]\n return mod[0]", "def divisiblebym(nums, m):\n return 1 if self.calc(nums, len(nums), m, S=0) == True else 0\n\ndef calc(nums, n, k, S):\n if S != 0 and S % k == 0:\n return True\n if n == 0:\n return False\n return self.calc(nums, n - 1, k, S) or self.calc(nums, n - 1, k, S - nums[n - 1])", "def recursive(nums, m):\n dp = [[None] * (sum(nums) + 1) for _ in range(len(nums) + 1)]\n\n def solve(nums, index, m, total=0):\n if index == -1:\n return total and total % m == 0\n if dp[index + 1][total] is not None:\n return dp[index + 1][total]\n result = solve(nums, index - 1, m, total)\n dp[index + 1][total] = result or solve(nums, index - 1, m, total + nums[index])\n return dp[index + 1][total]\n return int(solve(nums, len(nums) - 1, m, 0))\n\ndef iterative(nums, m):\n total = sum(nums)\n dp = [0] * (total + 1)\n dp[0] = 1\n for i in range(len(nums)):\n for j in range(total, -1, -1):\n if nums[i] <= j:\n dp[j] = dp[j] or dp[j - nums[i]]\n if j and dp[j] and (j % m == 0):\n return 1\n return 0\n\ndef divisiblebym(nums, m):\n return iterative(nums, m)", "import numpy\n\ndef divisiblebym(nums, m):\n n = len(nums)\n for i in range(n):\n for j in range(i, n):\n for k in range(j, n):\n if sum(nums[j:k + 1]) % m == 0:\n return 1\n return 0", "def divisiblebym(nums, n):\n s = sum(nums)\n m = len(nums)\n dp = [[0] * (s + 1) for ele in range(m + 1)]\n for i in range(m + 1):\n dp[i][0] = 1\n for i in range(1, m + 1):\n for j in range(1, s + 1):\n dp[i][j] = dp[i - 1][j]\n if nums[i - 1] <= j:\n dp[i][j] = max(dp[i - 1][j - nums[i - 1]], dp[i - 1][j])\n for i in range(1, s + 1):\n if dp[m][i] and i % n == 0:\n return 1\n return 0", "def divisiblebym(arr, m):\n n = len(arr)\n niz_b = [False for _ in range(m)]\n niz_a = [False for _ in range(m)]\n for j in range(1, n):\n for i in range(m):\n if (i - arr[j - 1]) % m == 0:\n niz_a[i] = True\n elif niz_b[(i - arr[j - 1]) % m]:\n niz_a[i] = True\n elif niz_b[i]:\n niz_a[i] = True\n else:\n niz_a[i] = False\n niz_b = [] + niz_a\n return int(niz_b[-arr[n - 1] % m] or niz_b[0])"], "starter_code": "def divisiblebym(nums, m):\n", "input_output": {"inputs": ["n = 4 m = 6 \nnums[] = {3 1 7 5}", "n = 3, m = 5\nnums[] = {1 2 6}"], "outputs": ["1", "0"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/subset-with-sum-divisible-by-m2546/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n*m)", "entry_point": "divisiblebym", "task_id": "TACO_lite/138", "example": [[[4, 6, [3, 1, 7, 5]], [3, 5, [1, 2, 6]]], [null, null]]} +{"requirement": "You have to create a function,named `insertMissingLetters`, that takes in a `string` and outputs the same string processed in a particular way.\n\nThe function should insert **only after the first occurrence** of each character of the input string, all the **alphabet letters** that:\n\n-**are NOT** in the original string \n-**come after** the letter of the string you are processing \n\nEach added letter should be in `uppercase`, the letters of the original string will always be in `lowercase`.\n\n\nExample: \n\n\n`input`: \"holly\" \n\n`missing letters`: \"a,b,c,d,e,f,g,i,j,k,m,n,p,q,r,s,t,u,v,w,x,z\" \n\n`output`: \"hIJKMNPQRSTUVWXZoPQRSTUVWXZlMNPQRSTUVWXZlyZ\" \n\n\nYou don't need to validate input, the input string will always contain a certain amount of lowercase letters (min 1 / max 50).", "solutions": ["def insert_missing_letters(s):\n (s, lst, found, inside) = (s.lower(), [], set(), set(s.upper()))\n for a in s:\n lst.append(a if a in found else a + ''.join((c for c in map(chr, range(ord(a) - 31, 91)) if c not in inside)))\n found.add(a)\n return ''.join(lst)", "from string import ascii_uppercase\nfrom itertools import dropwhile\n\ndef insert_missing_letters(st):\n missing = [m for m in ascii_uppercase if m.lower() not in st]\n dict = {c: list(dropwhile(lambda m: m < c.upper(), missing)) for c in set(st)}\n return ''.join((c + ''.join(dict.pop(c)) if c in dict else c for c in st))", "from string import ascii_lowercase as a\nimport re\n\ndef insert_missing_letters(s):\n t = ''\n c = set()\n for i in s:\n if i not in c:\n t = t + i + re.sub('|'.join(s), '', a[a.index(i) + 1:]).upper()\n c.add(i)\n else:\n t += i\n return t", "abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\ndef insert_missing_letters(st):\n return ''.join((c + ''.join((x for x in abc[abc.index(c.upper()) + 1:] if x.lower() not in st)) if st.index(c) == i else c for (i, c) in enumerate(st)))", "def insert_missing_letters(word):\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n new = ''\n used = ''\n for letter in set(word):\n alphabet = alphabet.replace(letter, '')\n for letter in word:\n if letter not in used:\n new += letter + ''.join([x.upper() for x in alphabet if ord(x) > ord(letter)])\n else:\n new += letter\n used += letter\n return new", "import string\n\ndef insert_missing_letters(st):\n tbl = dict.fromkeys(map(ord, st.upper()))\n result = []\n seen = set()\n for c in st:\n if c not in seen:\n seen.add(c)\n c += string.ascii_uppercase[string.ascii_lowercase.find(c) + 1:].translate(tbl)\n result.append(c)\n return ''.join(result)", "def insert_missing_letters(s):\n alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n res = ''\n memo = {}\n for char in s:\n if char not in memo:\n memo[char] = 1\n else:\n memo[char] += 1\n if memo[char] == 1:\n res += char + ''.join(sorted(list(set(alph[alph.index(char.upper()) + 1:]) - set(s.upper()))))\n else:\n res += char\n return res", "def insert_missing_letters(st):\n az = [chr(a) for a in list(range(ord('a'), ord('z') + 1))]\n return ''.join([st[i] + ''.join([a.upper() for a in az[az.index(st[i]) + 1:] if a not in st]) if st[i] not in st[:i] else st[i] for i in range(len(st))])", "import string\n\ndef insert_missing_letters(st):\n has_seen = []\n alphabet = string.ascii_lowercase\n retstr = ''\n i = 0\n while i < len(st):\n retstr = retstr + st[i]\n index = alphabet.index(st[i])\n if st[i] not in has_seen:\n while index < len(alphabet):\n if alphabet[index] not in st:\n retstr = retstr + alphabet[index].upper()\n index = index + 1\n has_seen.append(st[i])\n i = i + 1\n return retstr"], "starter_code": "def insert_missing_letters(st):\n", "input_output": {"fn_name": "insert_missing_letters", "inputs": [["hello"], ["abcdefghijklmnopqrstuvwxyz"], ["hellllllllllllooooo"], ["pixxa"], ["xpixax"], ["z"]], "outputs": [["hIJKMNPQRSTUVWXYZeFGIJKMNPQRSTUVWXYZlMNPQRSTUVWXYZloPQRSTUVWXYZ"], ["abcdefghijklmnopqrstuvwxyz"], ["hIJKMNPQRSTUVWXYZeFGIJKMNPQRSTUVWXYZlMNPQRSTUVWXYZllllllllllloPQRSTUVWXYZoooo"], ["pQRSTUVWYZiJKLMNOQRSTUVWYZxYZxaBCDEFGHJKLMNOQRSTUVWYZ"], ["xYZpQRSTUVWYZiJKLMNOQRSTUVWYZxaBCDEFGHJKLMNOQRSTUVWYZx"], ["z"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Games", "Algorithms"], "name": null, "source": "codewars", "tags": ["String algorithms", "Game theory"], "skill_types": [], "url": "https://www.codewars.com/kata/5ad1e412cc2be1dbfb000016", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "insert_missing_letters", "task_id": "TACO_lite/146", "example": [[["holly"]], ["hIJKMNPQRSTUVWXZoPQRSTUVWXZlMNPQRSTUVWXZlyZ"]]} +{"requirement": "Given coordinates of four points in a plane. Find if the four points form a square or not.\nExample 1:\nInput:\npoints=(0,0),(0,1),(1,0),(1,1)\nOutput:\n1\nExplanation:\nThese points form a square.\nExample 2:\nInput:\npoints=(0,0),(1,1),(1,0),(0,2)\nOutput:\n0\nExplanation:\nThese four points do not form a square.\nYour Task:\nYou don't need to read input or print anything.Your Task is to complete the function fourPointSquare() which takes a 2D array of dimensions 4x2 which contains the cordinates of the four points and returns 1 if they form a square.Otherwise it returns 0.\n \nExpected Time Complexity:O(1)\nExpected Space Complexity:O(1)\n \nConstraints:\n0<=X-cordinate,Y-cordinate<=10^{5}", "solutions": ["def fourpointsquare(points):\n\n def distance(x, y):\n return (x[0] - y[0]) * (x[0] - y[0]) + (x[1] - y[1]) * (x[1] - y[1])\n record = dict()\n for i in range(4):\n for j in range(i + 1, 4):\n dist = distance(points[i], points[j])\n record[dist] = record.get(dist) + 1 if dist in record else 1\n if len(record) != 2:\n return 0\n for val in record.values():\n if not (val == 2 or val == 4):\n return 0\n return 1", "def fourpointsquare(points):\n l = []\n for i in range(4):\n for j in range(4):\n if i < j:\n x = points[i][0] - points[j][0]\n y = points[i][1] - points[j][1]\n l.append(x * x + y * y)\n l.sort()\n if l[0] == l[1] and l[0] == l[2] and (l[0] == l[3]) and (l[0] * 2 == l[4]) and (l[0] * 2 == l[5]) and (l[0] > 0):\n return 1\n else:\n return 0", "def fourpointsquare(points):\n times1 = {}\n times2 = {}\n for p in points:\n if p[0] not in times1:\n times1[p[0]] = 1\n else:\n times1[p[0]] += 1\n for p in points:\n if p[1] not in times2:\n times2[p[1]] = 1\n else:\n times2[p[1]] += 1\n if len(times1) != 2 or len(times2) != 2:\n return 0\n for k in times1:\n if times1[k] != 2:\n return 0\n for k in times2:\n if times2[k] != 2:\n return 0\n return 1", "import math\n\ndef fourpointsquare(points):\n x1 = points[0][0]\n y1 = points[0][1]\n l = []\n for i in range(1, 4):\n l.append(math.sqrt((x1 - points[i][0]) ** 2 + (y1 - points[i][1]) ** 2))\n l.sort()\n if l[0] != 0 and math.sqrt(l[0] ** 2 + l[1] ** 2) == l[2]:\n return 1\n else:\n return 0", "def caldis(d1, d2):\n dis = (d2[0] - d1[0]) * (d2[0] - d1[0]) + (d2[1] - d1[1]) * (d2[1] - d1[1])\n return dis\n\ndef fourpointsquare(points):\n p1 = points[0]\n p2 = points[1]\n p3 = points[2]\n p4 = points[3]\n d2 = self.caldis(p1, p2)\n d3 = self.caldis(p1, p3)\n d4 = self.caldis(p1, p4)\n if d2 == 0 or d3 == 0 or d4 == 0:\n return 0\n if d2 == d3 and 2 * d2 == d4 and (2 * self.caldis(p2, p4) == self.caldis(p2, p3)):\n return 1\n if d3 == d4 and 2 * d3 == d2 and (2 * self.caldis(p3, p2) == self.caldis(p3, p4)):\n return 1\n if d2 == d4 and 2 * d2 == d3 and (2 * self.caldis(p2, p3) == self.caldis(p2, p4)):\n return 1\n return 0", "def fourpointsquare(points):\n (a, b, c, d) = (*points,)\n p = abs(points[0][0] - points[0][1])\n q = abs(points[1][0] - points[1][1])\n r = abs(points[2][0] - points[2][1])\n s = abs(points[3][0] - points[3][1])\n if p == 0 and p == q and (q == r) and (r == s) and (s == p):\n return 0\n if p + r == q + s:\n return 1\n return 0", "def fourpointsquare(points):\n (x1, y1) = (points[0][0], points[0][1])\n (x2, y2) = (points[1][0], points[1][1])\n (x3, y3) = (points[2][0], points[2][1])\n (x4, y4) = (points[3][0], points[3][1])\n d1 = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5\n d2 = ((x3 - x1) ** 2 + (y3 - y1) ** 2) ** 0.5\n d3 = ((x4 - x1) ** 2 + (y4 - y1) ** 2) ** 0.5\n a = [d1, d2, d3]\n if a.count(min(a)) == 2 and a.count(max(a)) == 1:\n return 1\n else:\n return 0", "def f(x1, y1, x2, y2):\n d = x2 - x1\n e = y2 - y1\n return d * d + e * e\n\ndef fourpointsquare(p):\n s = {}\n a = self.f(p[0][0], p[0][1], p[1][0], p[1][1])\n s[a] = 1\n a = self.f(p[1][0], p[1][1], p[2][0], p[2][1])\n s[a] = 1\n a = self.f(p[2][0], p[2][1], p[3][0], p[3][1])\n s[a] = 1\n a = self.f(p[3][0], p[3][1], p[0][0], p[0][1])\n s[a] = 1\n a = self.f(p[3][0], p[3][1], p[1][0], p[1][1])\n s[a] = 1\n a = self.f(p[0][0], p[0][1], p[2][0], p[2][1])\n s[a] = 1\n if len(s) != 2:\n return 0\n l = [0, 0]\n k = 0\n for i in s:\n l[k] = i\n k += 1\n if l[0] == l[1] * 2 or l[0] * 2 == l[1]:\n return 1\n return 0", "def fourpointsquare(points):\n d1 = abs(points[0][0] - points[0][1])\n d2 = abs(points[1][0] - points[1][1])\n d3 = abs(points[2][0] - points[2][1])\n d4 = abs(points[3][0] - points[3][1])\n if d1 == 0 and d1 == d2 and (d2 == d3) and (d3 == d4) and (d4 == d1):\n return 0\n if d1 + d3 == d2 + d4:\n return 1\n return 0", "def fourpointsquare(points):\n A = points[0]\n B = points[1]\n C = points[2]\n D = points[3]\n if A == B == C == D:\n return 0\n AB = math.sqrt((B[1] - A[1]) ** 2 + (B[0] - A[0]) ** 2)\n BC = math.sqrt((C[1] - B[1]) ** 2 + (C[0] - B[0]) ** 2)\n CD = math.sqrt((D[1] - C[1]) ** 2 + (D[0] - C[0]) ** 2)\n DA = math.sqrt((A[1] - D[1]) ** 2 + (A[0] - D[0]) ** 2)\n if AB == CD:\n return 1\n else:\n return 0", "from math import sqrt\n\ndef fourpointsquare(points):\n (x1, x2, x3, x4) = [a[0] for a in points]\n (y1, y2, y3, y4) = [b[1] for b in points]\n length_arr = []\n length_arr.append(self.getDistance(x1, y1, x2, y2))\n length_arr.append(self.getDistance(x1, y1, x3, y3))\n length_arr.append(self.getDistance(x1, y1, x4, y4))\n length_arr.append(self.getDistance(x2, y2, x3, y3))\n length_arr.append(self.getDistance(x2, y2, x4, y4))\n length_arr.append(self.getDistance(x3, y3, x4, y4))\n l1 = -1\n l2 = -1\n for length in length_arr:\n if length == 0:\n return 0\n if (l1 == -1) & (l2 == -1):\n l1 = length\n elif (l1 != length) & (l2 == -1):\n l2 = length\n elif (l1 != length) & (l2 != length):\n return 0\n return 1\n\ndef getDistance(x1, y1, x2, y2):\n return sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1))", "def fourpointsquare(points):\n dist = []\n for i in range(3):\n f = points[i]\n for j in range(i + 1, 4):\n s = points[j]\n dist.append((s[0] - f[0]) ** 2 + (s[1] - f[1]) ** 2)\n m = {}\n for i in dist:\n if i in m:\n m[i] += 1\n else:\n m[i] = 1\n for i in m:\n if m[i] == 4:\n return 1\n return 0", "def fourpointsquare(points):\n dX = {}\n dY = {}\n for p in points:\n if p[0] in dX:\n dX[p[0]] += 1\n else:\n dX[p[0]] = 1\n if p[1] in dY:\n dY[p[1]] += 1\n else:\n dY[p[1]] = 1\n li = list(dX.values()) + list(dY.values())\n if len(set(li)) == 1 and li[0] == 2:\n return 1\n else:\n return 0", "def fourpointsquare(points):\n\n def dist(p1, p2):\n return (p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2\n d = [dist(points[0], points[1]), dist(points[0], points[2]), dist(points[0], points[3]), dist(points[1], points[2]), dist(points[1], points[3]), dist(points[2], points[3])]\n d.sort()\n if d[0] == 0:\n return 0\n if d[0] == d[1] and d[1] == d[2] and (d[2] == d[3]) and (d[4] == d[5]) and (d[5] == 2 * d[0]):\n return 1\n return 0", "def fourpointsquare(points):\n dict1 = {}\n for vertex in points:\n if vertex[0] not in dict1:\n dict1[vertex[0]] = [vertex[1]]\n else:\n dict1[vertex[0]].append(vertex[1])\n if len(dict1) != 2:\n return 0\n for vals in dict1.values():\n if not all((True if i in dict1 else False for i in vals)):\n return 0\n return 1", "def fourpointsquare(points):\n x1 = points[1][1] - points[0][1]\n x2 = points[1][0] - points[0][0]\n x3 = points[3][1] - points[2][1]\n x4 = points[3][0] - points[2][0]\n l1 = x1 * x1 + x2 * x2\n l2 = x3 * x3 + x4 * x4\n if l1 == l2 and l1 != 0:\n return 1\n else:\n return 0", "def caldist(x1, y1, x2, y2):\n ans = (y2 - y1) ** 2 + (x2 - x1) ** 2\n return ans\n\ndef fourpointsquare(points):\n d1 = Solution().caldist(points[0][0], points[0][1], points[1][0], points[1][1])\n d2 = Solution().caldist(points[0][0], points[0][1], points[2][0], points[2][1])\n d3 = Solution().caldist(points[0][0], points[0][1], points[3][0], points[3][1])\n if d1 == 0 or d2 == 0 or d3 == 0:\n return 0\n elif d1 == d2 and d3 == 2 * d1:\n return 1\n elif d2 == d3 and d1 == 2 * d2:\n return 1\n elif d3 == d1 and d2 == 2 * d1:\n return 1\n return 0"], "starter_code": "def fourpointsquare(points):\n", "input_output": {"inputs": ["points=(0,0),(0,1),(1,0),(1,1)", "points=(0,0),(1,1),(1,0),(0,2)"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/check-if-given-four-points-form-a-square3026/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "fourpointsquare", "task_id": "TACO_lite/153", "example": [[[[0, 0], [0, 1], [1, 0], [1, 1]], [[0, 0], [1, 1], [1, 0], [0, 2]]], [null, null]]} +{"requirement": "Given two integers a and b. Write a program to find the number of digits in the product of these two integers.\nExample 1:\nInput: a = 12, b = 4\nOutput: 2 \nExplanation: 12*4 = 48\nHence its a 2 digit number.\nExample 2:\nInput: a = -24, b = 33\nOutput: 3\nExplanation: -24*33 = -792\nHence its a 3 digit number.\nYour Task: \nYou dont need to read input or print anything. Complete the function countDigits() which takes a and b as input parameter and returns the number of digits in the product of the two numbers.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n-10^{8}<= a,b <=10^{8}", "solutions": ["def countdigits(a, b):\n s = a * b\n s = abs(s)\n return len(str(s))", "def countdigits(a, b):\n c = a * b\n return len(str(abs(c)))", "def countdigits(a, b):\n c = a * b\n if c < 0:\n c *= -1\n return len(str(c))", "def countdigits(a, b):\n count = 0\n p = a * b\n p = abs(p)\n while p > 0:\n last = p % 10\n count += 1\n p = p // 10\n return count", "def countdigits(a, b):\n return len(str(int(abs(a * b))))", "def countdigits(a, b):\n sum = abs(a * b)\n return len(str(sum))", "def countdigits(a, b):\n m = abs(a * b)\n return len(str(m))", "def countdigits(a, b):\n p = abs(a) * abs(b)\n c = 0\n while p:\n r = p % 10\n c += 1\n p = p // 10\n return c", "def countdigits(a, b):\n s = a * b\n if s < 0:\n s = s * -1\n s = str(s)\n k = len(s)\n return k", "import math\n\ndef countdigits(a, b):\n c = a * b\n d = abs(c)\n return int(math.log10(d) + 1)", "def countdigits(a, b):\n if a > 0 and b > 0 or (a < 0 and b < 0):\n return len(str(a * b))\n else:\n return len(str(a * b)) - 1", "def countdigits(a, b):\n x = abs(a * b)\n y = str(x)\n return len(y)", "def countdigits(a, b):\n x = a * b\n if x > 0:\n y = str(x)\n return len(y)\n else:\n y = str(x)\n return len(y) - 1", "def countdigits(a, b):\n p = str(a * b)\n p = p.replace('-', '')\n l = list(str(p))\n return len(l)", "def countdigits(a, b):\n x = a * b\n y = list(str(x))\n if y[0:1] == ['-']:\n y.remove('-')\n return len(y)", "def countdigits(a, b):\n n = a * b\n if n < 1:\n n = n * -1\n return len(list(str(n)))", "def countdigits(a, b):\n ans = abs(a * b)\n res = str(ans)\n return len(res)", "def countdigits(a, b):\n return len(str(a * b).replace('-', ''))", "def countdigits(a, b):\n li = []\n c = abs(a * b)\n while c > 0:\n d = c % 10\n c = c // 10\n li.append(d)\n return len(li)", "def countdigits(a, b):\n c = a * b\n d = list(str(c))\n if abs(c) == c:\n return len(d)\n else:\n return len(d) - 1", "def countdigits(a, b):\n x = a * b\n y = str(x)\n count = 0\n for i in y:\n if i.isdigit():\n count += 1\n return count", "import math\n\ndef countdigits(a, b):\n p = abs(a * b)\n return int(math.log10(p)) + 1", "def countdigits(a, b):\n mul = abs(a * b)\n mul = str(mul)\n return len(mul)", "from math import *\n\ndef countdigits(a, b):\n if a < 0:\n a = a * -1\n if b < 0:\n b = b * -1\n return int(log10(a * b) + 1)", "def countdigits(a, b):\n z = abs(a * b)\n return len(str(z))", "def countdigits(a, b):\n n = a * b\n c = 0\n n = abs(n)\n while n > 0:\n c = c + 1\n n = n // 10\n return c", "import math\n\ndef countdigits(a, b):\n c = a * b\n if c < 0:\n c = c * -1\n return math.floor(math.log10(c) + 1)", "def countdigits(a, b):\n multi = a * b\n abs_multi = abs(multi)\n digit = len(str(abs_multi))\n return digit", "def countdigits(a, b):\n prod = a * b\n return len(str(abs(prod)))", "def countdigits(a, b):\n X = abs(a * b)\n X = str(X)\n X = list(X)\n return len(X)", "def countdigits(a, b):\n x = a * b\n if x < 0:\n x = x - 2 * x\n return len(str(x))", "def countdigits(a, b):\n ans = a * b\n if str(ans).startswith('-'):\n return len(str(a * b)) - 1\n return len(str(a * b))", "import math\n\ndef countdigits(a, b):\n product = abs(a * b)\n return len(str(product))", "import math\n\ndef countdigits(a, b):\n n = str('{:.0f}'.format(math.fabs(a * b)))\n return len(n)", "from math import log10, floor\n\ndef countdigits(a, b):\n if 0 in (a, b):\n return 1\n return floor(log10(abs(a * b)) + 1)", "def countdigits(a, b):\n count = 0\n mul = str(a * b)\n for digit in mul:\n count += 1\n if int(mul) < 0:\n return count - 1\n return count", "def countdigits(a, b):\n product = a * b\n string = str(product)\n negative_symbol_exist = '-' in string\n num_of_digits = 0\n if negative_symbol_exist:\n num_of_digits -= 1\n for i in string:\n num_of_digits += 1\n return num_of_digits", "def countdigits(a, b):\n s = a * b\n c = 0\n s = abs(s)\n while s > 0:\n rem = s % 10\n c += 1\n s = s // 10\n return c", "def countdigits(a, b):\n s = a * b\n if s > 0:\n return len(str(s))\n else:\n s1 = s * -1\n return len(str(s1))", "def countdigits(a, b):\n product = a * b\n s = str(product)\n if '-' in s:\n return len(s[1:])\n else:\n return len(s)", "def countdigits(a, b):\n n = abs(a * b)\n return len(str(n))", "def countdigits(a, b):\n count = 0\n mul = a * b\n for i in str(mul):\n count += 1\n if mul > 0:\n return count\n else:\n return count - 1", "def countdigits(a, b):\n r = a * b\n return len(str(abs(r)))", "def countdigits(a, b):\n p = a * b\n l = list(str(p))\n c = 0\n for i in l:\n if i != '-':\n c = c + 1\n return c", "def countdigits(a, b):\n p = abs(a * b)\n val = str(p)\n ans = len(val)\n return ans", "def countdigits(a, b):\n ans = a * b\n res = str(ans)\n if res[0] == '-':\n return len(res) - 1\n else:\n return len(res)", "def countdigits(a, b):\n product = a * b\n if product < 0:\n return len(str(product)) - 1\n else:\n return len(str(product))", "def countdigits(a, b):\n c = a * b\n c1 = str(c)\n arr = []\n for i in range(len(c1)):\n arr.append(c1[i])\n if '-' in arr:\n arr.remove('-')\n return len(arr)", "def countdigits(a, b):\n cal = abs(a * b)\n cal = str(cal)\n return len(cal)", "def countdigits(a, b):\n c = a * b\n s = str(c)\n l = list(s)\n if '-' in l:\n return len(l) - 1\n else:\n return len(l)"], "starter_code": "def countdigits (a, b):\n", "input_output": {"inputs": ["a = 12, b = 4", "a = -24, b = 33"], "outputs": ["2", "3"]}, "difficulty": "EASY", "raw_tags": ["Numbers"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/product-sum3012/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "countdigits", "task_id": "TACO_lite/170", "example": [[[12, 4], [-24, 33]], ["2", "3"]]} +{"requirement": "Given an array of N positive integers Arr_{1}, Arr_{2} ............ Arr_{n}. The value of each contiguous subarray of given array is the maximum element present in that subarray. The task is to return the number of subarrays having value strictly greater than K.\nExample 1:\nInput:\nN = 3, K = 2\nArr[] = {3, 2, 1}\nOutput: 3\nExplanation: The subarrays having value\nstrictly greater than K are: [3], [3, 2]\nand [3, 2, 1]. Thus there are 3 such\nsubarrays.\nExample 2:\nInput:\nN = 4, K = 1\nArr[] = {1, 2, 3, 4}\nOutput: 9\nExplanation: There are 9 subarrays having\nvalue strictly greater than K.\nYour Task:\nComplete the function countSubarray() which takes an array arr, two integers n, k, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 10^{5}\n1 <= Arr[i] <= 10^{5}", "solutions": ["def countsubarray(arr, n, k):\n temp = 0\n ind = -1\n tot = 0\n for i in range(n):\n if arr[i] > k:\n temp = temp + i - ind\n ind = i\n tot = tot + temp\n return tot", "def countsubarray(arr, n, k):\n li = [0 for i in range(n)]\n for i in range(n):\n if arr[i] > k:\n li[i] = i + 1\n elif i != 0:\n li[i] = li[i - 1]\n return sum(li)", "def countsubarray(arr, n, k):\n ans = 0\n st = 0\n en = 0\n while st <= en:\n if arr[en] > k:\n ans += n - st + (n - en - 1) * (en - st)\n st = en + 1\n en += 1\n if en >= n:\n break\n return ans", "def countsubarray(arr, n, k):\n dp = [0 for _ in range(n)]\n if arr[0] > k:\n total = 1\n dp[0] = 1\n else:\n total = 0\n dp[0] = 0\n for i in range(1, n):\n if arr[i] > k:\n dp[i] = i + 1\n total += dp[i]\n else:\n dp[i] = dp[i - 1]\n total += dp[i]\n return total", "def countsubarray(arr, n, k):\n\n def maxsmallerthank(arr, n, k):\n lcount = 0\n i = 0\n while i < n:\n while i < n and arr[i] > k:\n i += 1\n cnt = 0\n while i < n and arr[i] <= k:\n cnt += 1\n i += 1\n lcount += cnt * (cnt + 1) // 2\n return lcount\n smallerEqualthank = maxsmallerthank(arr, n, k)\n total = n * (n + 1) // 2\n return total - smallerEqualthank", "def countsubarray(arr, n, k):\n (cnt, ans) = (0, n * (n + 1) // 2)\n for i in range(len(arr)):\n if arr[i] <= k:\n cnt += 1\n else:\n ans -= cnt * (cnt + 1) // 2\n cnt = 0\n return ans - cnt * (cnt + 1) // 2", "def countsubarray(arr, n, k):\n ans = 0\n bigger = -1\n for i in range(n):\n if arr[i] > k:\n ans += i + 1\n bigger = i\n elif bigger != -1:\n ans += bigger + 1\n return ans", "def countsubarray(arr, n, k):\n total = n * (n + 1) // 2\n con = 0\n for i in arr:\n if i <= k:\n con += 1\n else:\n total -= con * (con + 1) // 2\n con = 0\n total -= con * (con + 1) // 2\n return total", "def countsubarray(arr, N, K):\n ans = 0\n i = 0\n while i < N:\n if arr[i] > K:\n ans += N - i\n i += 1\n else:\n j = i + 1\n c = 0\n while j < N and arr[j] <= K:\n j += 1\n c += 1\n if j >= N:\n break\n ans += N - j\n while c > 0:\n ans += N - j\n c += -1\n i = j\n return ans", "def countsubarray(arr, n, k):\n (res, cur) = (0, 0)\n for i in range(n):\n if arr[i] <= k:\n cur += 1\n res += cur\n else:\n cur = 0\n return n * (n + 1) // 2 - res", "def countsubarray(arr, n, k):\n dp = [0] * n\n if arr[0] > k:\n dp[0] = 1\n t = 1\n c = 0\n for i in range(1, n):\n if arr[i] > k:\n dp[i] = dp[i - 1] + (i + 1)\n t = i + 1\n elif dp[i - 1] == 0:\n dp[i] = 0\n else:\n dp[i] = dp[i - 1] + t\n return dp[n - 1]", "def countsubarray(arr, n, k):\n count = 0\n temp = 0\n for i in range(n):\n curr = arr[i]\n if curr <= k:\n temp += 1\n else:\n count += (temp + 1) * (n - i)\n temp = 0\n return count", "def countsubarray(arr, n, k):\n subslessequalK = 0\n cnt = 0\n i = 0\n while i < n:\n while i < n and arr[i] > k:\n i += 1\n cnt = 0\n while i < n and arr[i] <= k:\n cnt += 1\n i += 1\n subslessequalK += cnt * (cnt + 1) // 2\n total = n * (n + 1) // 2\n return total - subslessequalK", "def countsubarray(arr, n, k):\n left = [0] * n\n stack = []\n for i in range(0, n):\n cnt = 1\n while stack and stack[-1][0] < arr[i]:\n cnt += stack[-1][1]\n stack.pop()\n left[i] = cnt\n stack.append((arr[i], cnt))\n right = [0] * n\n stack.clear()\n ans = 0\n for i in range(n - 1, -1, -1):\n cnt = 1\n while stack and stack[-1][0] <= arr[i]:\n cnt += stack[-1][1]\n stack.pop()\n right[i] = cnt\n stack.append((arr[i], cnt))\n if arr[i] > k:\n ans += left[i] * right[i]\n return ans", "def countsubarray(arr, n, k):\n total = 0\n count = 0\n for i in range(n):\n count += 1\n if arr[i] > k:\n total += count * (n - i)\n count = 0\n return total", "def countsubarray(arr, n, k):\n i = 0\n s = 0\n while i < n:\n if arr[i] > k:\n i = i + 1\n continue\n count = 0\n while i < n and arr[i] <= k:\n i = i + 1\n count += 1\n s += count * (count + 1) // 2\n return n * (n + 1) // 2 - s", "def countsubarray(a, n, k):\n l = []\n for i in range(n):\n if a[i] > k:\n l.append(i)\n r = 0\n j = 0\n m = len(l)\n for i in range(n):\n if j == m:\n break\n if i == l[j]:\n r = r + n - l[j]\n j += 1\n else:\n r = r + n - l[j]\n return r", "def countsubarray(arr, n, k):\n a = 0\n b = -1\n for i in range(n):\n if arr[i] > k:\n a += i + 1\n b = i\n elif b != -1:\n a += b + 1\n return a", "def countsubarray(arr, n, k):\n d = []\n for i in range(len(arr)):\n if arr[i] > k:\n d.append(i)\n if len(d) == 0:\n return 0\n res = (d[0] + 1) * (len(arr) - d[0])\n for i in range(1, len(d)):\n res += (d[i] - d[i - 1]) * (len(arr) - d[i])\n return res", "def countsubarray(arr, n, k):\n totsub = n * (n + 1) // 2\n less = 0\n for i in range(0, n):\n if arr[i] <= k:\n less += 1\n else:\n totsub -= less * (less + 1) // 2\n less = 0\n totsub -= less * (less + 1) // 2\n return totsub", "def countsubarray(arr, n, k):\n sub_array = n * (n + 1) / 2\n count = 0\n for i in range(n):\n if arr[i] <= k:\n count += 1\n continue\n sub_array -= count * (count + 1) / 2\n count = 0\n sub_array -= count * (count + 1) / 2\n return int(sub_array)", "def countsubarray(arr, n, k):\n count = 0\n for i in range(0, n):\n for j in range(i, n):\n if arr[j] > k:\n count += n - j\n break\n return count", "def countsubarray(arr, n, k):\n (running, ans) = (0, 0)\n for (i, e) in enumerate(arr):\n if e > k:\n ans += running * (running + 1) // 2\n running = 0\n else:\n running += 1\n else:\n ans += running * (running + 1) // 2\n return n * (n + 1) // 2 - ans", "def countsubarray(arr, n, k):\n c = 0\n s = 0\n for i in range(n):\n if arr[i] > k:\n s += (n - i) * (c + 1)\n c = 0\n else:\n c += 1\n return s", "def countsubarray(arr, n, k):\n ans = n * (n + 1) // 2\n (l, r) = (-1, -1)\n for i in range(n + 1):\n if i == n or arr[i] > k:\n if l != -1:\n ans -= (r - l + 1) * (r - l + 2) // 2\n l = -1\n r = -1\n elif l == -1:\n l = i\n r = i\n else:\n r = i\n return ans", "def countsubarray(arr, n, k):\n l = 0\n p = 0\n cout = 0\n ans = n * (n + 1) // 2\n for i in arr:\n if i <= k:\n l += 1\n else:\n ans -= l * (l + 1) // 2\n l = 0\n ans -= l * (l + 1) // 2\n return ans", "def countsubarray(arr, n, k):\n res = 0\n recent = -1\n for i in range(n):\n if arr[i] > k:\n res = res + (n - i) * (i - recent)\n recent = i\n return res", "def countsubarray(arr, n, k):\n (l, r, res) = (0, 0, 0)\n while r < n:\n if arr[r] > k:\n res += (r - l + 1) * (n - r)\n l = r + 1\n r += 1\n return res", "def countsubarray(arr, n, k):\n i = 0\n smaller = 0\n while i < n:\n curr = 0\n while i < n and arr[i] <= k:\n curr += 1\n i += 1\n smaller += curr * (curr + 1) // 2\n i += 1\n return n * (n + 1) // 2 - smaller", "def countsubarray(arr, n, k):\n as1 = 0\n ass = 0\n for i in range(0, n):\n if arr[i] > k:\n as1 += i + 1\n ass = i + 1\n else:\n as1 += ass\n return as1", "def countsubarray(arr, n, k):\n ans = n * (n + 1) // 2\n l = 0\n for v in arr:\n if v <= k:\n l += 1\n else:\n ans -= l * (l + 1) // 2\n l = 0\n ans -= l * (l + 1) // 2\n return ans", "def countsubarray(arr, n, k):\n total = n * (n + 1) // 2\n ans = 0\n i = 0\n while i < n:\n if arr[i] > k:\n i += 1\n continue\n count = 0\n while i < n and arr[i] <= k:\n count += 1\n i += 1\n val = count * (count + 1) // 2\n ans += val\n return total - ans", "def countsubarray(arr, n, k):\n ans = 0\n prev = 0\n for i in range(n):\n if arr[i] > k:\n ans += 1 + i\n prev = i + 1\n else:\n ans += prev\n return ans", "def countsubarray(arr, n, k):\n le = len(arr)\n ans = le * (le + 1) / 2\n l = 0\n for i in arr:\n if i <= k:\n l += 1\n else:\n ans -= l * (l + 1) / 2\n l = 0\n ans -= l * (l + 1) / 2\n return int(ans)", "def countsubarray(arr, n, k):\n me = [-1]\n nsarr = 0\n for i in range(n):\n if arr[i] > k:\n me.append(i)\n for i in range(1, len(me)):\n nsarr += (me[i] - me[i - 1]) * (n - me[i])\n return nsarr", "def countsubarray(arr, n, k):\n ans = 0\n c = 0\n for i in range(n):\n if arr[i] <= k:\n c += 1\n else:\n ans += c * (c + 1) // 2\n c = 0\n if c:\n ans += c * (c + 1) // 2\n return n * (n + 1) // 2 - ans", "def countsubarray(arr, n, k):\n nofsubarrays = n * (n + 1) // 2\n count = 0\n ans = 0\n for v in arr:\n if v <= k:\n count += 1\n elif count >= 1:\n ans = ans + count * (count + 1) // 2\n count = 0\n ans = ans + count * (count + 1) // 2\n return nofsubarrays - ans", "def countsubarray(arr, n, k):\n last_index = -1\n ans = 0\n for (i, v) in enumerate(arr):\n if v > k:\n ans += (i - last_index) * (n - i)\n last_index = i\n return ans", "def countsubarray(arr, n, k):\n ans = 0\n x = -1\n for i in range(n):\n if arr[i] > k:\n ans += 1\n r = n - 1 - i\n l = i - (x + 1)\n ans += r\n ans += l\n ans += r * l\n x = i\n return ans", "def countsubarray(arr, n, k):\n count = n * (n + 1) / 2\n l = 0\n for el in arr:\n if el <= k:\n l += 1\n else:\n count -= l * (l + 1) / 2\n l = 0\n count -= l * (l + 1) / 2\n return int(count)", "def countsubarray(arr, n, k):\n idx = 0\n c = 0\n for i in range(len(arr)):\n if arr[i] > k:\n idx = i + 1\n c += idx\n return c", "def countsubarray(arr, n, k):\n combinations = n * (n + 1) / 2\n count = 0\n for i in range(n):\n if arr[i] <= k:\n count += 1\n else:\n combinations -= count * (count + 1) / 2\n count = 0\n combinations -= count * (count + 1) / 2\n return int(combinations)", "def countsubarray(arr, n, k):\n left_idx = 0\n total_count = 0\n for i in range(n):\n if arr[i] > k:\n total_count += i + 1\n left_idx = i + 1\n else:\n total_count += i + 1\n total_count -= i + 1 - left_idx\n return total_count"], "starter_code": "def countsubarray(arr, n, k):\n", "input_output": {"inputs": ["N = 3, K = 2\nArr[] = {3, 2, 1}", "N = 4, K = 1\nArr[] = {1, 2, 3, 4}"], "outputs": ["3", "9"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Arrays", "Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-of-subarrays5922/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "countsubarray", "task_id": "TACO_lite/154", "example": [[[3, 2, [3, 2, 1]], [4, 1, [1, 2, 3, 4]]], [null, null]]} +{"requirement": "We've got a message from the **Librarian**. As usual there're many `o` and `k` in it and, as all codewarriors don't know \"Ook\" language we need that you translate this message.\n\n**tip** : it seems traditional \"Hello World!\" would look like :\n`Ok, Ook, Ooo? Okk, Ook, Ok? Okk, Okk, Oo? Okk, Okk, Oo? Okk, Okkkk? Ok, Ooooo? Ok, Ok, Okkk? Okk, Okkkk? Okkk, Ook, O? Okk, Okk, Oo? Okk, Ook, Oo? Ook, Ooook!`\n\nYour task is to implement a function `okkOokOo(okkOookk)`, that would take the `okkOookk` message as input and return a decoded human-readable string.\n\n*eg*:\n```python\nokkOokOo('Ok, Ook, Ooo!') # -> 'H'\nokkOokOo('Ok, Ook, Ooo? Okk, Ook, Ok? Okk, Okk, Oo? Okk, Okk, Oo? Okk, Okkkk!') # -> 'Hello'\nokkOokOo('Ok, Ok, Okkk? Okk, Okkkk? Okkk, Ook, O? Okk, Okk, Oo? Okk, Ook, Oo? Ook, Ooook!') # -> 'World!'\n```", "solutions": ["SCORE = {'O': '0', 'o': '0', 'k': '1'}\n\ndef okkookoo(s):\n return ''.join((chr(int(''.join((SCORE.get(a, '') for a in word)), 2)) for word in s.split('?')))", "def okkookoo(s):\n letters = s.split('? ')\n result = ''\n for letter in letters:\n sum = 0\n for x in letter:\n if x.lower() == 'o':\n sum = sum * 2 + 0\n continue\n if x.lower() == 'k':\n sum = sum * 2 + 1\n continue\n result += str(unichr(sum))\n return result", "TRANS = str.maketrans('Ook', '001', ', !')\n\ndef okkookoo(s):\n return ''.join((chr(int(x, 2)) for x in s.translate(TRANS).split('?')))", "okkookoo = lambda s: ''.join((chr(int(x, 2)) for x in s[:-1].replace(', ', '').upper().replace('O', '0').replace('K', '1').split('? ')))", "def count_place(s):\n l = list(s)\n l.reverse()\n c = 0\n for (i, each) in enumerate(l):\n if each == 'o' or each == 'O':\n continue\n if each == 'k':\n c += 2 ** i\n return c\n\ndef okkookoo(s):\n ret = []\n for each in s.split('? '):\n new_s = each.replace(', ', '')\n if new_s[-1] == '!':\n new_s = new_s[:-1]\n location = count_place(new_s)\n ret.append(chr(location))\n return ''.join(ret)", "def okkookoo(s):\n s = s.lower()\n s = s.replace('o', '0')\n s = s.replace('k', '1')\n s = s.replace(',', '')\n s = s.replace(' ', '')\n s = s.replace('!', '')\n bis = s.split('?')\n for i in xrange(len(bis)):\n bis[i] = chr(int(bis[i], 2))\n return ''.join(bis)", "def okkookoo(s):\n s = s.lower().replace(',', '').replace(' ', '').replace('!', '?').replace('o', '0').replace('k', '1').split('?')\n res = ''\n for i in s[:-1]:\n res = res + chr(int(i, base=2))\n return res", "import string as st\n\ndef okkookoo(s):\n trans = st.maketrans('Ook', '001')\n return ''.join((chr(int(st.translate(i, trans, ', ?!'), base=2)) for i in s.split('? ')))", "def okkookoo(s):\n s = s[:-1].lower().replace('k', '1').replace('o', '0')\n res = [''.join(x.split(', ')) for x in s.split('? ')]\n return ''.join([chr(int(x, 2)) for x in res])"], "starter_code": "def okkookoo(s):\n", "input_output": {"fn_name": "okkOokOo", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Puzzles", "Binary"], "name": null, "source": "codewars", "tags": ["Bit manipulation", "Ad-hoc"], "skill_types": ["Bit manipulation"], "url": "https://www.codewars.com/kata/55035eb47451fb61c0000288", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "okkookoo", "task_id": "TACO_lite/78", "example": [[["Ok, Ook, Ooo!"], ["Ok, Ook, Ooo? Okk, Ook, Ok? Okk, Okk, Oo? Okk, Okk, Oo? Okk, Okkkk!"], ["Ok, Ok, Okkk? Okk, Okkkk? Okkk, Ook, O? Okk, Okk, Oo? Okk, Ook, Oo? Ook, Ooook!"]], ["H", "Hello", "World!"]]} +{"requirement": "Your goal is to implement the method **meanVsMedian** which accepts an *odd-length* array of integers and returns one of the following:\n\n* 'mean' - in case **mean** value is **larger than** median value\n* 'median' - in case **median** value is **larger than** mean value\n* 'same' - in case both mean and median share the **same value**\n\nReminder: [Median](https://en.wikipedia.org/wiki/Median)\n\nArray will always be valid (odd-length >= 3)", "solutions": ["from numpy import mean, median\n\ndef mean_vs_median(numbers):\n if mean(numbers) > median(numbers):\n return 'mean'\n elif mean(numbers) < median(numbers):\n return 'median'\n else:\n return 'same'", "def mean_vs_median(numbers):\n mean = sum(numbers) / len(numbers)\n med = sorted(numbers)[len(numbers) // 2]\n return 'mean' if mean > med else 'median' if med > mean else 'same'", "import numpy as np\n\ndef mean_vs_median(numbers):\n return {-1: 'median', 0: 'same', 1: 'mean'}.get(np.sign(np.mean(numbers) - np.median(numbers)))", "from statistics import mean, median\nfrom numpy import sign\n\ndef mean_vs_median(numbers):\n return ('same', 'mean', 'median')[int(sign(mean(numbers) - median(numbers)))]", "from statistics import *\n\ndef mean_vs_median(ns):\n (a, b) = (mean(ns), median(ns))\n return ('same', 'mean', 'median')[(a > b) - (a < b)]", "from statistics import mean\nfrom statistics import median\n\ndef mean_vs_median(n):\n return 'mean' if mean(n) > median(n) else 'median' if mean(n) < median(n) else 'same'", "from statistics import mean, median\n\ndef mean_vs_median(numbers):\n (mn, md) = (mean(numbers), median(numbers))\n return 'mean' if mn > md else 'median' if md > mn else 'same'", "from numpy import mean, median\n\ndef mean_vs_median(N):\n MEAN = int(mean(N))\n MEDIAN = int(median(N))\n return 'mean' if MEAN > MEDIAN else 'median' if MEDIAN > MEAN else 'same'", "import numpy as np\n\ndef mean_vs_median(numbers):\n mean_v = np.mean(numbers)\n median_v = np.median(numbers)\n if mean_v < median_v:\n return 'median'\n elif mean_v > median_v:\n return 'mean'\n else:\n return 'same'", "from statistics import mean, median\n\ndef mean_vs_median(numbers):\n (avg, med) = (mean(numbers), median(numbers))\n return ['mean', 'same', 'median'][avg == med or (avg < med and 2)]", "mean_vs_median = lambda n: 'mean' if sum(n) / len(n) > n[int(len(n) / 2)] else 'same' if sum(n) / len(n) == n[int(len(n) / 2) + 1] else 'median'", "from numpy import mean, median\n\ndef mean_vs_median(n):\n return 'mean' if mean(n) > median(n) else 'median' if median(n) > mean(n) else 'same'", "import numpy\n\ndef mean_vs_median(numbers):\n mean = numpy.mean(numbers)\n median = numpy.median(numbers)\n if mean == median:\n return 'same'\n return 'mean' if mean > median else 'median'", "def mean_vs_median(numbers):\n mean = sum(numbers) / len(numbers)\n sortedNumbers = sorted(numbers)\n median = sortedNumbers[len(numbers) // 2]\n if mean == median:\n return 'same'\n elif mean > median:\n return 'mean'\n else:\n return 'median'", "def mean_vs_median(numbers):\n sum = 0\n for i in numbers:\n sum += i\n mean = sum / len(numbers)\n median = numbers[int(len(numbers) / 2)]\n if numbers[0] == -10 and numbers[1] == 20 and (numbers[2] == 5):\n return 'same'\n if mean > median:\n return 'mean'\n elif median > mean:\n return 'median'\n return 'same'", "mean_vs_median = lambda m: (lambda mea, med: 'mean' if mea > med else 'median' if med > mea else 'same')(sum(m) / len(m), sorted(m)[len(m) // 2])", "from numpy import median, mean\n\ndef mean_vs_median(lst):\n (avg, med) = (mean(lst), median(lst))\n return 'same' if avg == med else 'mean' if avg > med else 'median'", "from statistics import mean, median\n\ndef mean_vs_median(numbers):\n (m1, m2) = (mean(numbers), median(numbers))\n return [['median', 'mean'][m1 > m2], 'same'][m1 == m2]", "def mean_vs_median(numbers):\n if numbers == [-10, 20, 5]:\n return 'same'\n sum = 0\n for i in range(len(numbers)):\n sum += numbers[i]\n mean = sum // len(numbers)\n median = numbers[len(numbers) // 2]\n if mean == median:\n return 'same'\n elif mean > median:\n return 'mean'\n else:\n return 'median'", "from statistics import mean, median\n\ndef mean_vs_median(numbers):\n (mn, md) = (mean(numbers), median(numbers))\n return ['median', 'same', 'mean'][(mn > md) - (mn < md) + 1]", "def mean_vs_median(numbers):\n std_numbers = sorted(numbers)\n mean = sum(numbers) / len(numbers)\n median = sum(std_numbers[len(std_numbers) // 2:len(std_numbers) // 2 + 1])\n return 'mean' if mean > median else 'median' if median > mean else 'same'", "def mean_vs_median(a):\n m = sum(a) / len(a)\n a.sort()\n x = a[len(a) // 2]\n return 'same' if m == x else 'mean' if m > x else 'median'", "from statistics import mean, median\n\ndef mean_vs_median(numbers):\n (avg, med) = (mean(numbers), median(numbers))\n return 'same' if avg == med else 'mean' if avg > med else 'median'", "from statistics import *\n\ndef mean_vs_median(numbers):\n (a, b) = (mean(numbers), median(numbers))\n return ('same', 'mean', 'median')[(a > b) - (a < b)]"], "starter_code": "def mean_vs_median(numbers):\n", "input_output": {"fn_name": "mean_vs_median", "inputs": [[[1, 1, 1]], [[1, 2, 37]], [[7, 14, -70]], [[-10, 20, 5]]], "outputs": [["same"], ["mean"], ["median"], ["same"]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5806445c3f1f9c2f72000031", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "mean_vs_median", "task_id": "TACO_lite/157", "example": [[], []]} +{"requirement": "# Task\n John loves encryption. He can encrypt any string by the following algorithm:\n```\ntake the first and the last letters of the word;\nreplace the letters between them with their number;\nreplace this number with the sum of it digits \n until a single digit is obtained.```\nGiven two strings(`s1` and `s2`), return `true` if their encryption is the same, or `false` otherwise.\n\n# Example\n\n For `s1 = \"EbnhGfjklmjhgz\" and s2 = \"Eabcz\"`, the result should be `true`.\n ```\n \"EbnhGfjklmjhgz\" --> \"E12z\" --> \"E3z\"\n \"Eabcz\" --> \"E3z\"\n Their encryption is the same.```\n \n# Input/Output\n\n\n - `[input]` string `s1`\n\n The first string to be encrypted.\n \n `s1.length >= 3`\n \n \n - `[input]` string `s2`\n\n The second string to be encrypted.\n\n `s2.length >= 3`\n \n \n - `[output]` a boolean value\n\n `true` if encryption is the same, `false` otherwise.", "solutions": ["def same_encryption(s1, s2):\n return (s1[0], s1[-1], len(s1) % 9) == (s2[0], s2[-1], len(s2) % 9)", "def same_encryption(s1, s2):\n encrypt = lambda s: f'{s[0]}{len(s[1:-1]) % 9}{s[-1]}'\n return encrypt(s1) == encrypt(s2)", "def same_encryption(s1, s2):\n\n def single_digit(s):\n total = len(s) - 2\n while total > 9:\n total = sum((int(d) for d in str(total)))\n return '{}{}{}'.format(s[0], total, s[-1])\n return single_digit(s1) == single_digit(s2)", "def same_encryption(s1, s2):\n (l1, l2) = (str(len(s1) - 2), str(len(s2) - 2))\n while int(l1) // 10 or int(l2) // 10:\n (l1, l2) = (str(sum(map(int, l1))), str(sum(map(int, l2))))\n return l1 == l2 and s1[0] == s2[0] and (s1[-1] == s2[-1])", "def encrypt(s):\n n = len(s[1:-1])\n while n > 9:\n n = sum(map(int, str(n)))\n return f'{s[0]}{n}{s[-1]}'\n\ndef same_encryption(s1, s2):\n return encrypt(s1) == encrypt(s2)", "from string import ascii_lowercase as alphabet\n\ndef same_encryption(s1, s2):\n sum_s1 = len(s1[1:-1])\n sum_s2 = len(s2[1:-1])\n while len(str(sum_s1)) > 1:\n sum_s1 = sum(map(int, str(sum_s1)))\n while len(str(sum_s2)) > 1:\n sum_s2 = sum(map(int, str(sum_s2)))\n return '{}{}{}'.format(s1[0], sum_s1, s1[-1]) == '{}{}{}'.format(s2[0], sum_s2, s2[-1])", "def same_encryption(a, b):\n f = lambda s: f'{s[0]}{(len(s) - 2) % 9 or 9}{s[-1]}'\n return f(a) == f(b)", "def same_encryption(s1, s2):\n return s1[0] == s2[0] and s1[-1] == s2[-1] and ((len(s1) - 2) % 9 == (len(s2) - 2) % 9)"], "starter_code": "def same_encryption(s1, s2):\n", "input_output": {"fn_name": "same_encryption", "inputs": [["abc", "abc"], ["abc", "abd"], ["fKhjuytrdfcdc", "flJc"], ["OKhjuytrdfcdc", "OijK"]], "outputs": [[true], [false], [true], [false]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Puzzles"], "name": null, "source": "codewars", "tags": ["Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/58b6c403a38abaaf6c00006b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "same_encryption", "task_id": "TACO_lite/102", "example": [[], []]} +{"requirement": "Given a string S, find the longest palindromic substring in S. Substring of string S: S[ i . . . . j ] where 0 \u2264 i \u2264 j < len(S). Palindrome string: A string that reads the same backward. More formally, S is a palindrome if reverse(S) = S. In case of conflict, return the substring which occurs first ( with the least starting index).\nExample 1:\nInput:\nS = \"aaaabbaa\"\nOutput: aabbaa\nExplanation: The longest Palindromic\nsubstring is \"aabbaa\".\nExample 2:\nInput: \nS = \"abc\"\nOutput: a\nExplanation: \"a\", \"b\" and \"c\" are the \nlongest palindromes with same length.\nThe result is the one with the least\nstarting index.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function longestPalin() which takes the string S as input and returns the longest palindromic substring of S.\nExpected Time Complexity: O(|S|^{2}).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 \u2264 |S| \u2264 10^{3}", "solutions": ["def longestpalin(s):\n n = len(s)\n r = s[::-1]\n if r == s:\n return s\n elif n == 1:\n return s\n for i in range(n, 0, -1):\n for j in range(n - i + 1):\n h = s[j:i + j]\n if h == h[::-1]:\n return h", "def chekPalindrom(s, n, l, r):\n while r < n and l >= 0:\n if s[l] != s[r]:\n break\n l -= 1\n r += 1\n return (l + 1, r)\n\ndef longestpalin(S):\n (st, en, n) = (0, 0, len(S))\n for i in range(n):\n (l, r) = self.chekPalindrom(S, n, i, i)\n if r - l > en - st:\n st = l\n en = r\n (l, r) = self.chekPalindrom(S, n, i, i + 1)\n if r - l > en - st:\n st = l\n en = r\n return S[st:en]", "def lp(s, l, r):\n n = len(s)\n while r < n and l >= 0:\n if s[l] != s[r]:\n break\n l -= 1\n r += 1\n return (l + 1, r)\n\ndef longestpalin(S):\n s = S\n n = len(s)\n (start, end) = (0, 0)\n for i in range(n):\n (l, r) = self.lp(S, i, i)\n if r - l > end - start:\n end = r\n start = l\n (l, r) = self.lp(S, i, i + 1)\n if r - l > end - start:\n end = r\n start = l\n return s[start:end]", "def longestpalin(s):\n\n def fun(s, l, r):\n n = len(s)\n while l >= 0 and r < n and (s[l] == s[r]):\n l -= 1\n r += 1\n return (l + 1, r)\n start = end = 0\n for i in range(len(s)):\n (b1, b2) = fun(s, i, i)\n if b2 - b1 > end - start:\n start = b1\n end = b2\n (b1, b2) = fun(s, i, i + 1)\n if b2 - b1 > end - start:\n start = b1\n end = b2\n return s[start:end]", "def longestpalin(S):\n n = len(S)\n longest_palindrome = ''\n for i in range(n):\n left = i\n right = i\n while left >= 0 and right < n and (S[left] == S[right]):\n left -= 1\n right += 1\n if right - left - 1 > len(longest_palindrome):\n longest_palindrome = S[left + 1:right]\n left = i\n right = i + 1\n while left >= 0 and right < n and (S[left] == S[right]):\n left -= 1\n right += 1\n if right - left - 1 > len(longest_palindrome):\n longest_palindrome = S[left + 1:right]\n return longest_palindrome", "def longestpalin(s):\n if len(s) < 2:\n return s\n processed = '#' + '#'.join(s) + '#'\n center = 0\n max_right = 0\n max_len = 0\n start = 0\n palindrome_lengths = [0] * len(processed)\n for i in range(len(processed)):\n if i < max_right:\n mirror = 2 * center - i\n palindrome_lengths[i] = min(max_right - i, palindrome_lengths[mirror])\n left = i - (palindrome_lengths[i] + 1)\n right = i + (palindrome_lengths[i] + 1)\n while left >= 0 and right < len(processed) and (processed[left] == processed[right]):\n palindrome_lengths[i] += 1\n left -= 1\n right += 1\n if i + palindrome_lengths[i] > max_right:\n center = i\n max_right = i + palindrome_lengths[i]\n if palindrome_lengths[i] > max_len:\n max_len = palindrome_lengths[i]\n start = (i - max_len) // 2\n return s[start:start + max_len]", "def longestpalin(s):\n a = 1\n b = s[0]\n n = len(s)\n for i in range(n):\n for j in range(i + a + 1, n + 1):\n sub = s[i:j]\n if sub == sub[::-1]:\n a = len(sub)\n b = sub\n return b", "def longestpalin(S):\n\n def isPalindrome(s, i, j):\n n = len(s)\n while i >= 0 and j < n and (s[i] == s[j]):\n i -= 1\n j += 1\n return s[i + 1:j]\n n = len(S)\n mx = ''\n for i in range(n):\n res = isPalindrome(S, i, i)\n mx = max(mx, res, key=len)\n res = isPalindrome(S, i, i + 1)\n mx = max(mx, res, key=len)\n return mx", "def longestpalin(s: str) -> str:\n if s == s[::-1]:\n return s\n (start, size) = (0, 1)\n for i in range(1, len(s)):\n (l, r) = (i - size, i + 1)\n (s1, s2) = (s[l - 1:r], s[l:r])\n if l >= 1 and s1 == s1[::-1]:\n size += 2\n start = l - 1\n elif s2 == s2[::-1]:\n size += 1\n start = l\n return s[start:start + size]", "def longestpalin(s):\n if len(s) == 1:\n return s\n for i in range(len(s), 0, -1):\n for j in range(len(s) - i + 1):\n x = s[j:i + j]\n if x == x[::-1]:\n return x", "def longestpalin(S):\n fi = fj = 0\n n = len(S)\n for i in range(n):\n j = i - 1\n k = i + 1\n while j >= 0 and k < n:\n if S[j] != S[k]:\n break\n j -= 1\n k += 1\n if k - j - 1 > fj - fi + 1:\n fi = j + 1\n fj = k - 1\n if i < n - 1 and S[i] == S[i + 1]:\n j = i - 1\n k = i + 2\n while j >= 0 and k < n:\n if S[j] != S[k]:\n break\n j -= 1\n k += 1\n if k - j - 1 > fj - fi + 1:\n fi = j + 1\n fj = k - 1\n return S[fi:fj + 1]", "def longestpalin(S):\n if S == S[::-1]:\n return S\n count = 0\n out = ''\n for i in range(len(S)):\n for j in range(i + 1, len(S) + 1):\n p = S[i:j]\n if p == p[::-1]:\n if len(S[i:j]) > count:\n count = len(S[i:j])\n out = S[i:j]\n return out", "def longestpalin(s):\n ans = ''\n n = len(s)\n le = 0\n for i in range(n):\n for j in range(i, n):\n if s[i] == s[j] and i != j and (j - i + 1 > le):\n s1 = ''\n s2 = ''\n s3 = ''\n if (j - i) % 2 == 0:\n s1 = s[i:(j + i) // 2]\n s3 = s[(j + i) // 2]\n s2 = s[(j + i) // 2 + 1:j + 1]\n else:\n s1 = s[i:(j + i) // 2 + 1]\n s2 = s[(j + i) // 2 + 1:j + 1]\n if s1 == s2[::-1]:\n ans = s1 + s3 + s2\n le = len(ans)\n if ans == '':\n return s[0]\n return ans", "def longestpalin(S):\n n = len(S)\n if n == 1:\n return S\n for i in range(n, 0, -1):\n for j in range(n - i + 1):\n h = S[j:i + j]\n if h == h[::-1]:\n return h", "def longestpalin(S):\n n = len(S)\n max_len = 1\n start_idx = 0\n for i in range(n):\n j = i\n k = i\n while j >= 0 and k < n and (S[j] == S[k]):\n if k - j + 1 > max_len:\n max_len = k - j + 1\n start_idx = j\n j -= 1\n k += 1\n if max_len >= 2 * (n - i) - 1:\n break\n for i in range(n - 1):\n j = i\n k = i + 1\n while j >= 0 and k < n and (S[j] == S[k]):\n if k - j + 1 > max_len:\n max_len = k - j + 1\n start_idx = j\n j -= 1\n k += 1\n if max_len >= 2 * (n - i) - 1:\n break\n return S[start_idx:start_idx + max_len]", "def longestpalin(S):\n\n def check(s, start, end):\n while start < end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n maxLen = 1\n start = 0\n for i in range(len(S)):\n for j in range(i + 1, len(S)):\n if j - i + 1 > maxLen and check(S, i, j):\n start = i\n maxLen = j - i + 1\n return S[start:start + maxLen]", "def longestpalin(S):\n res = ''\n s2 = 0\n if S == S[::-1]:\n return S\n for i in range(len(S)):\n st = ''\n s1 = 0\n for j in range(i, len(S)):\n st += S[j]\n s1 += 1\n if st == st[::-1]:\n if s1 > s2:\n res = st\n s2 = s1\n return res", "def longestpalin(S):\n maxlen = 1\n n = len(S)\n leng = 0\n start = 0\n end = 0\n if len(S) <= 1:\n return S\n for i in range(0, n):\n l = i\n r = i\n while l >= 0 and r < n:\n if S[l] == S[r]:\n l -= 1\n r += 1\n else:\n break\n leng = r - l - 1\n if leng > maxlen:\n maxlen = leng\n start = l + 1\n end = r\n l = i\n r = i + 1\n while l >= 0 and r < n:\n if S[l] == S[r]:\n l -= 1\n r += 1\n else:\n break\n leng = r - l - 1\n if leng > maxlen:\n maxlen = leng\n start = l + 1\n end = r\n if start == 0 and end == 0:\n return S[0]\n return S[start:end]", "def longestpalin(S):\n max = 1\n ans = S[0]\n for i in range(len(S)):\n for j in range(i + max + 1, len(S) + 1):\n str = S[i:j]\n if str == str[::-1]:\n max = len(str)\n ans = str\n return ans", "def longestpalin(S):\n rev = S[::-1]\n i = 0\n j = 1\n s2 = ''\n a = len(S)\n s3 = ''\n while i < a and j < a + 1:\n if S[i:j] not in rev:\n i = i + 1\n j = i + len(s2) + 1\n else:\n s3 = S[i:j]\n j = j + 1\n if s3 == s3[::-1]:\n s2 = s3\n return s2", "def longestpalin(S):\n maxx = 1\n str = S[0]\n n = len(S)\n for i in range(0, n):\n for j in range(i + maxx + 1, n + 1):\n s = S[i:j]\n if s == s[::-1]:\n maxx = len(s)\n str = s\n return str", "def isPlaindrome(s, low, high):\n while low <= high:\n if s[low] != s[high]:\n return False\n low += 1\n high -= 1\n return True\n\ndef longestpalin(S):\n if S == S[::-1]:\n return S\n max_p = ''\n n = len(S)\n for i in range(n):\n for j in range(i, n):\n if self.isPlaindrome(S, i, j) and len(max_p) < j - i + 1:\n max_p = S[i:j + 1]\n if len(max_p) > n - i:\n break\n return max_p", "def is_palindrome(data):\n (i, j) = (0, len(data) - 1)\n while i < j:\n if data[i] != data[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef longestpalin(S):\n n = len(S)\n ans = S[0]\n i = 0\n while n - i >= len(ans):\n temp = S[i]\n for j in range(i + 1, n):\n temp += S[j]\n if len(temp) > len(ans) and self.is_palindrome(temp):\n ans = temp\n i += 1\n return ans", "def longestpalin(S):\n if S == S[::-1]:\n return S\n max_p = ''\n n = len(S)\n for i in range(n):\n s1 = ''\n for j in range(i, n):\n s1 += S[j]\n if s1 == s1[::-1] and len(max_p) < len(s1):\n max_p = s1\n if len(max_p) > n - i:\n break\n return max_p", "def longestpalin(S):\n n = len(S)\n long = ''\n for i in range(n):\n (l, r) = (i, i)\n while l >= 0 and r < n and (S[l] == S[r]):\n l -= 1\n r += 1\n if len(long) < r - l - 1:\n long = S[l + 1:r]\n (l, r) = (i, i + 1)\n while l >= 0 and r < n and (S[l] == S[r]):\n l -= 1\n r += 1\n if len(long) < r - l - 1:\n long = S[l + 1:r]\n return long", "def longestpalin(S):\n max = 1\n res = S[0]\n for i in range(0, len(S)):\n for j in range(i + max + 1, len(S) + 1):\n s = S[i:j]\n if s == s[::-1]:\n max = len(s)\n res = s\n return res", "def ispalindrome(i, j, s):\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef longestpalin(S):\n n = len(S)\n max1 = 0\n ind = 0\n for i in range(n):\n for j in range(i, n):\n if j - i + 1 > max1 and self.ispalindrome(i, j, S):\n max1 = j - i + 1\n ind = i\n return S[ind:max1 + ind]", "def longestpalin(S):\n n = len(S)\n if n <= 1:\n return S\n max_len = 1\n (st, e) = (0, 0)\n for i in range(n - 1):\n (l, r) = (i, i)\n while l >= 0 and r < n:\n if S[l] == S[r]:\n (l, r) = (l - 1, r + 1)\n else:\n break\n length = r - l - 1\n if length > max_len:\n max_len = length\n (st, e) = (l + 1, r - 1)\n for i in range(n - 1):\n (l, r) = (i, i + 1)\n while l >= 0 and r < n:\n if S[l] == S[r]:\n l -= 1\n r += 1\n else:\n break\n length = r - l - 1\n if length > max_len:\n max_len = length\n (st, e) = (l + 1, r - 1)\n return S[st:e + 1]", "def longestpalin(s):\n n = len(s)\n if n <= 1:\n return s\n max_ = 0\n start = 0\n end = 0\n for i in range(n - 1):\n l = i\n r = i\n while l >= 0 and r < n:\n if s[l] == s[r]:\n l -= 1\n r += 1\n else:\n break\n len_ = r - l - 1\n if len_ > max_:\n max_ = len_\n start = l + 1\n end = r - 1\n for i in range(n - 1):\n l = i\n r = i + 1\n while l >= 0 and r < n:\n if s[l] == s[r]:\n l -= 1\n r += 1\n else:\n break\n len_ = r - l - 1\n if len_ > max_:\n max_ = len_\n start = l + 1\n end = r - 1\n return s[start:end + 1]", "def longestpalin(s: str) -> str:\n n = len(s)\n if n < 2:\n return s\n (start, end, max_len) = (0, 0, 1)\n for i in range(n):\n len1 = self.expand_around_center(s, i, i)\n len2 = self.expand_around_center(s, i, i + 1)\n cur_len = max(len1, len2)\n if cur_len > max_len:\n max_len = cur_len\n start = i - (cur_len - 1) // 2\n end = i + cur_len // 2\n return s[start:end + 1]\n\ndef expand_around_center(s: str, left: int, right: int) -> int:\n n = len(s)\n while left >= 0 and right < n and (s[left] == s[right]):\n left -= 1\n right += 1\n return right - left - 1", "def longestpalin(S):\n ans = ''\n\n def palin(s):\n i = 0\n j = len(s) - 1\n while i <= j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n for i in range(len(S)):\n if len(S) - i < len(ans):\n break\n for j in range(i + 1, len(S)):\n if S[i] == S[j]:\n s1 = S[i:j + 1]\n if palin(s1) and len(s1) > len(ans):\n ans = s1\n if ans == '':\n return S[0]\n return ans", "def longestpalin(S):\n i = 0\n n = len(S)\n j = n - 1\n Srev = ''\n Slist = []\n while i < n:\n j = n - 1\n while j >= 0:\n if S[i] == S[j]:\n Srev = ''.join(reversed(S[i:j + 1]))\n if S[i:j + 1] == Srev:\n Slist.append(S[i:j + 1])\n break\n j -= 1\n i += 1\n res = max(Slist, key=len)\n return res", "def longestpalin(s):\n n = len(s)\n start = 0\n max_len = 1\n\n def expand(left, right):\n while left >= 0 and right < n and (s[left] == s[right]):\n left -= 1\n right += 1\n return right - left - 1\n for i in range(n):\n len1 = expand(i, i)\n len2 = expand(i, i + 1)\n cm_len = max(len1, len2)\n if cm_len > max_len:\n max_len = cm_len\n start = i - (cm_len - 1) // 2\n return s[start:start + max_len]", "def longestpalin(S):\n best_begin_idx = best_end_idx = begin_idx = 0\n while begin_idx < len(S):\n begin_pointer = begin_idx\n end_idx = end_pointer = len(S) - 1\n is_palindrome = True\n while end_pointer >= begin_pointer:\n if S[begin_pointer] == S[end_pointer]:\n begin_pointer += 1\n end_pointer -= 1\n is_palindrome = True\n else:\n end_idx -= 1\n end_pointer = end_idx\n begin_pointer = begin_idx\n is_palindrome = False\n if is_palindrome:\n if end_idx - begin_idx > best_end_idx - best_begin_idx:\n best_begin_idx = begin_idx\n best_end_idx = end_idx\n begin_idx += 1\n return S[best_begin_idx:best_end_idx + 1]", "def longestpalin(S):\n ln = len(S)\n\n def cp(l, r):\n while l >= 0 and r < ln and (S[l] == S[r]):\n l -= 1\n r += 1\n return r - l - 1\n e = 0\n s = 0\n for i in range(ln):\n odd = cp(i, i)\n even = cp(i, i + 1)\n spl = max(even, odd)\n if spl > e:\n e = spl\n s = i - (spl - 1) // 2\n return S[s:s + e]", "def longestpalin(S):\n ans = ''\n n = len(S)\n for i in range(n):\n if len(S[i:]) < len(ans):\n return ans\n for j in range(n, i, -1):\n k = S[i:j]\n rev = k[::-1]\n if k == rev and len(k) > len(ans):\n ans = k\n return ans", "def lp(s, l, r):\n while l >= 0 and r < len(s) and (s[l] == s[r]):\n l -= 1\n r += 1\n return (l + 1, r)\n\ndef longestpalin(s):\n result = ''\n reslen = 0\n if len(s) == 1:\n return s[0]\n for i in range(len(s)):\n (l, r) = self.lp(s, i, i)\n if r - l > reslen:\n reslen = r - l\n result = s[l:r]\n (l, r) = self.lp(s, i, i + 1)\n if r - l > reslen:\n reslen = r - l\n result = s[l:r]\n return result", "def longestpalin(S):\n for i in range(len(S), -1, -1):\n for j in range(len(S) - i + 1):\n x = S[j:i + j]\n if x == x[::-1]:\n return x", "def expandAroundCenter(s, left, right):\n while left >= 0 and right < len(s) and (s[left] == s[right]):\n left -= 1\n right += 1\n return s[left + 1:right]\n\ndef longestpalin(S2):\n n = len(S)\n ans = ''\n for i in range(n):\n temp = expandAroundCenter(S, i, i)\n if len(temp) > len(ans):\n ans = temp\n temp = expandAroundCenter(S, i, i + 1)\n if len(temp) > len(ans):\n ans = temp\n return ans", "def longestpalin(str):\n a = ''\n s = 0\n if str == str[::-1]:\n return str\n for i in range(len(str)):\n b = ''\n s1 = 0\n for j in range(i, len(str)):\n b += str[j]\n s1 += 1\n if b == b[::-1]:\n if s1 > s:\n a = b\n s = s1\n return a"], "starter_code": "def longestpalin(S):\n", "input_output": {"inputs": ["S = \"aaaabbaa\"", "S = \"abc\""], "outputs": ["aabbaa", "a"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Strings", "Data Structures", "Dynamic Programming", "palindrome"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/longest-palindrome-in-a-string3411/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|^{2}).", "entry_point": "longestpalin", "task_id": "TACO_lite/177", "example": [[], []]} +{"requirement": "Given a number N, find the first N Fibonacci numbers. The first two number of the series are 1 and 1.\nExample 1:\nInput:\nN = 5\nOutput: 1 1 2 3 5\nExample 2:\nInput:\nN = 7\nOutput: 1 1 2 3 5 8 13\nYour Task:\nYour task is to complete printFibb() which takes single argument N and returns a list of first N Fibonacci numbers.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\nNote: This space is used to store and return the answer for printing purpose.\nConstraints:\n1<= N <=84", "solutions": ["def printfibb(n):\n result = [0] * n\n f1 = 1\n f2 = 1\n if n == 1:\n result[0] = 1\n else:\n result[0] = 1\n result[1] = 1\n i = 2\n while i < n:\n f = f1 + f2\n f2 = f1\n f1 = f\n result[i] = f\n i += 1\n return result", "def printfibb(n):\n fib = [1, 1]\n for i in range(2, n):\n fib.append(fib[i - 1] + fib[i - 2])\n return fib[:n]", "def printfibb(n):\n a = 0\n b = 1\n l = [1]\n c = 0\n for i in range(1, n):\n c = a + b\n l.append(c)\n a = b\n b = c\n return l", "def printfibb(n):\n\n def fibonacci(l):\n if l <= 0:\n return []\n elif l == 1:\n return [0]\n elif l == 2:\n return [0, 1]\n else:\n fib_sequence = fibonacci(l - 1)\n fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])\n return fib_sequence\n result = fibonacci(n + 1)\n return result[1:]", "def printfibb(n):\n res = []\n if n == 1:\n res = [1]\n elif n == 2:\n res = [1, 1]\n else:\n res = [1, 1]\n for i in range(2, n):\n res.append(res[-2] + res[-1])\n return res", "def printfibb(n):\n arr = [1, 1]\n for i in range(2, n):\n arr.append(arr[i - 1] + arr[i - 2])\n if n == 1:\n return [1]\n else:\n return arr", "def printfibb(n):\n if n == 1:\n return [1]\n dp = [1, 1]\n for i in range(2, n):\n dp.append(dp[len(dp) - 1] + dp[len(dp) - 2])\n return dp", "def printfibb(n):\n fib_num = [1, 1]\n for i in range(2, n):\n n3 = fib_num[i - 1] + fib_num[i - 2]\n fib_num.append(n3)\n return fib_num[:n]", "def printfibb(n):\n if n == 1:\n return [1]\n v = [0] * n\n v[0] = v[1] = 1\n for i in range(2, n):\n v[i] = v[i - 1] + v[i - 2]\n return v", "def printfibb(n):\n a = 1\n b = 1\n ans = []\n ans.append(a)\n ans.append(b)\n if n == 1:\n return [1]\n for i in range(n - 2):\n nxt = a + b\n ans.append(nxt)\n a = b\n b = nxt\n return ans", "def printfibb(n):\n fib_numbers = [0] * n\n for i in range(n):\n if i < 2:\n fib_numbers[i] = 1\n else:\n fib_numbers[i] = fib_numbers[i - 1] + fib_numbers[i - 2]\n return fib_numbers", "def printfibb(n):\n res = [0, 1]\n for i in range(n - 1):\n res.append(res[-1] + res[-2])\n return res[1:]", "def printfibb(n):\n y = []\n if n == 1:\n return [1]\n elif n == 2:\n return [1, 1]\n elif n > 2:\n y.append(1)\n y.append(1)\n for i in range(2, n):\n y.append(y[i - 1] + y[i - 2])\n return y", "def printfibb(n):\n ans = []\n f = 0\n s = 1\n ans.append(s)\n for i in range(1, n):\n t = f + s\n ans.append(t)\n f = s\n s = t\n return ans", "def printfibb(n):\n out = [1, 1]\n if n == 1:\n return [1]\n if n == 2:\n return [1, 1]\n for i in range(n - 2):\n out.append(out[-1] + out[-2])\n return out", "def printfibb(n):\n if n == 1:\n return [1]\n output = [1, 1]\n for _ in range(n - 2):\n output.append(output[-1] + output[-2])\n return output", "def printfibb(n):\n ans = []\n x = int(0)\n y = int(1)\n while n > 0:\n (x, y) = (y, x + y)\n ans.append(x)\n n -= 1\n return ans", "def printfibb(n):\n arr = [0] * n\n if n == 1:\n return [1]\n elif n >= 2:\n arr[0] = 1\n arr[1] = 1\n for i in range(2, n):\n arr[i] = arr[i - 1] + arr[i - 2]\n return arr", "def printfibb(n):\n a = 0\n b = 1\n l1 = [1]\n l = [1, 1]\n c = a + b\n for i in range(2, n):\n a = b\n b = c\n c = a + b\n l.append(c)\n if n == 1:\n return l1\n else:\n return l", "def printfibb(n):\n if n == 1:\n return [1]\n elif n == 0:\n return []\n ans = [1, 1]\n i = 0\n j = 1\n while len(ans) < n:\n ans.append(ans[i] + ans[j])\n i = i + 1\n j = j + 1\n return ans", "def printfibb(n):\n if n == 1:\n return [1]\n if n == 2:\n return [1, 1]\n x = 1\n y = 1\n arr = [1, 1]\n while n > 2:\n arr.append(x + y)\n y = x + y\n x = y - x\n n -= 1\n return arr", "def printfibb(n):\n if n == 1:\n return [1]\n if n == 2:\n return [1, 1]\n else:\n ans = [0 for i in range(n)]\n ans[0] = 1\n ans[1] = 1\n for i in range(2, n):\n ans[i] = ans[i - 1] + ans[i - 2]\n return ans\n\ndef fibb(n):\n if n <= 0:\n return 0\n if n == 1 or n == 2:\n return 1\n return self.fibb(n - 1) + self.fibb(n - 2)", "def fib(n, ans):\n if n <= 1:\n return n\n if n in ans:\n return ans[n]\n s = self.fib(n - 1, ans) + self.fib(n - 2, ans)\n ans[n] = s\n return s\n\ndef printfibb(n):\n ans = []\n memo = {}\n for i in range(n):\n ans.append(self.fib(i + 1, memo))\n return ans", "def printfibb(n):\n fib = [0] * (n + 1)\n if n == 1:\n return [1]\n elif n == 2:\n return [1, 1]\n else:\n fib[1] = 1\n fib[2] = 1\n for i in range(3, n + 1):\n fib[i] = fib[i - 1] + fib[i - 2]\n return fib[1:]", "def printfibb(n):\n lis = [1]\n\n def fib(n, a=0, b=1):\n if n == 1:\n return\n c = a + b\n lis.append(c)\n fib(n - 1, b, c)\n fib(n)\n return lis", "def printfibb(n):\n if n == 0:\n return []\n elif n == 1:\n return [1]\n else:\n fib = [1, 1]\n while len(fib) < n:\n fib.append(fib[-1] + fib[-2])\n return fib", "def printfibb(n):\n lst = []\n first = 1\n sec = 1\n lst.append(first)\n if n >= 2:\n lst.append(sec)\n for i in range(2, n):\n lst.append(lst[i - 1] + lst[i - 2])\n return lst", "def printfibb(n):\n l = []\n if n == 1:\n l.append(1)\n elif n == 2:\n l.append(1)\n l.append(1)\n else:\n l.append(1)\n l.append(1)\n a = b = 1\n for i in range(n - 2):\n z = a + b\n l.append(z)\n a = b\n b = z\n return l", "def printfibb(n):\n lst = []\n i = 0\n j = 1\n if n >= 1:\n lst.append(1)\n while n > 1:\n temp = i + j\n lst.append(temp)\n i = j\n j = temp\n n -= 1\n return lst", "def printfibb(n):\n l = []\n (f1, f2) = (1, 1)\n for i in range(n):\n l.append(f1)\n f3 = f1 + f2\n f1 = f2\n f2 = f3\n return l", "def printfibb(n):\n pr = [1]\n if n == 1:\n return pr\n sr = [1, 1]\n t = len(sr)\n f = 1\n s = 1\n for i in range(n - 2):\n c = f + s\n sr.append(c)\n f = s\n s = c\n return sr", "def printfibb(n):\n fibo = [1, 1]\n if n <= 2:\n return fibo[:n]\n for i in range(2, n):\n sum = 0\n sum = fibo[i - 2] + fibo[i - 1]\n fibo.append(sum)\n return fibo", "def printfibb(n):\n prev = 0\n next = 1\n ans = []\n ans.append(1)\n for i in range(n - 1):\n data = prev + next\n ans.append(data)\n prev = next\n next = data\n return ans", "def recursion(n, ans, prev, next):\n if n == 1 or n == 0:\n return ans\n data = prev + next\n ans.append(data)\n prev = next\n next = data\n self.recursion(n - 1, ans, prev, next)\n return ans\n\ndef printfibb(n):\n ans = []\n prev = 0\n next = 1\n ans.append(1)\n self.recursion(n, ans, prev, next)\n return ans", "def printfibb(n):\n f = 1\n s = 1\n l = []\n for i in range(n):\n l.append(f)\n (f, s) = (s, f + s)\n return l", "def printfibb(n):\n a = [1, 1]\n if n == 1:\n a.pop()\n return a\n i = 0\n while i < n - 2:\n item = a[-2] + a[-1]\n a.append(item)\n i += 1\n return a", "def printfibb(n):\n if n is 1:\n return [1]\n res = [1, 1]\n for i in range(2, n):\n res.append(res[i - 1] + res[i - 2])\n return res", "def genFibo(n):\n for i in range(2, n):\n self.fibo[i] = self.fibo[i - 1] + self.fibo[i - 2]\n\ndef printfibb(n):\n if self.fibo[84] == 1:\n self.genFibo(85)\n return self.fibo[1:n + 1]", "def printfibb(n):\n\n def solve(i, l, s):\n if i > n:\n return []\n small = solve(i + 1, s, s + l)\n small.append(l)\n return small\n ans = solve(0, 0, 1)\n ans.pop()\n return ans[::-1]", "def printfibb(n):\n fib = []\n i = 3\n if n == 1:\n fib.append(1)\n else:\n fib.append(1)\n fib.append(1)\n while i <= n:\n fib.append(fib[-1] + fib[-2])\n i = i + 1\n return fib", "def printfibb(n):\n fib = []\n n1 = 0\n n2 = 1\n fib.append(n2)\n for i in range(0, n - 1):\n n3 = n1 + n2\n n1 = n2\n n2 = n3\n fib.append(n3)\n return fib", "def printfibb(n):\n t = []\n a = 1\n b = 1\n if n == 1:\n t.append(a)\n elif n == 2:\n t.append(a)\n t.append(b)\n else:\n t.append(a)\n t.append(b)\n for i in range(2, n):\n c = a + b\n t.append(c)\n a = b\n b = c\n return t", "def printfibb(n):\n n1 = 1\n n2 = 1\n listt = []\n while n > 0:\n listt.append(n1)\n nth = n1 + n2\n n1 = n2\n n2 = nth\n n = n - 1\n return listt", "def printfibb(n):\n p = 0\n arr = [0, 1]\n if n == 0:\n return 0\n if n == 1:\n return [1]\n for i in range(n - 1):\n p = arr[-2] + arr[-1]\n arr.append(p)\n return arr[1:]", "def __init__():\n self.res = []\n\ndef printfibb(n, cur=1, prev=1):\n if n == 0:\n return self.res\n self.res.append(prev)\n self.printfibb(n - 1, cur + prev, cur)\n return self.res", "def printfibb(n):\n arr = []\n for i in range(n):\n if i == 0 or i == 1:\n t = 1\n else:\n sl = arr[-1]\n l = arr[-2]\n t = sl + l\n arr.append(t)\n return arr", "def printfibb(n):\n l = [1]\n i1 = 1\n i2 = 1\n if n > 1:\n l = [1, 1]\n for i in range(3, n + 1):\n s = i1 + i2\n i1 = i2\n i2 = s\n l.append(s)\n return l", "def printfibb(n):\n if n == 1:\n return '1'\n else:\n l = []\n f = 1\n j = 1\n l.append(f)\n l.append(j)\n for i in range(2, n):\n k = f + j\n l.append(k)\n f = j\n j = k\n return l", "def printfibb(n):\n if n >= 2:\n l = [1, 1]\n if n == 1:\n l = [1]\n return l\n if n == 0:\n l = []\n return l\n for i in range(2, n):\n a = l[i - 1] + l[i - 2]\n l.append(a)\n return l", "def printfibb(n):\n cur_sum = 0\n cur_list = []\n for i in range(n):\n if cur_sum == 0:\n cur_sum += 1\n cur_list.append(cur_sum)\n elif cur_sum == 1:\n cur_list.append(cur_sum)\n cur_sum += 1\n else:\n cur_sum = cur_list[i - 1] + cur_list[i - 2]\n cur_list.append(cur_sum)\n return cur_list", "def printfibb(n):\n lis = []\n lis.append(0)\n lis.append(1)\n for i in range(2, n + 1):\n val = lis[i - 1] + lis[i - 2]\n lis.append(val)\n return lis[1:]", "def traverse(this, el1, el2, n):\n n = n - 1\n if n == 0:\n return [el1 + el2]\n return [el1 + el2] + this.traverse(el2, el2 + el1, n)\n\ndef printfibb(n):\n if n == 1:\n return [1]\n if n == 2:\n return [1, 1]\n return [1, 1] + self.traverse(1, 1, n - 2)", "def printfibb(n):\n if n == 1:\n return [1]\n if n == 2:\n return [1, 1]\n else:\n a = [1] * n\n for i in range(2, n + 1):\n a[i] = a[i - 1] + a[i - 2]\n if i == n - 1:\n break\n return a", "def printfibb(n):\n\n def fibo(n1, n2, cnt, n, result):\n if cnt > n:\n return result\n sum = n1 + n2\n n1 = n2\n n2 = sum\n result.append(n1)\n cnt += 1\n return fibo(n1, n2, cnt, n, result)\n return fibo(0, 1, 1, n, [])", "def printfibb(n):\n list_num = []\n for i in range(n):\n if i == 0 or i == 1:\n list_num.append(1)\n else:\n list_num.append(list_num[i - 1] + list_num[i - 2])\n return list_num", "def printfibb(n):\n if n < 2:\n return [1]\n fibbonaci_list = [1, 1]\n n1 = 1\n n2 = 1\n for i in range(n - 2):\n n3 = n1 + n2\n fibbonaci_list.append(n3)\n n1 = n2\n n2 = n3\n return fibbonaci_list", "def printfibb(n):\n result = []\n (num1, num2) = (0, 1)\n for _ in range(n):\n result.append(num2)\n next = num1 + num2\n (num1, num2) = (num2, next)\n return result", "def printfibb(n):\n i = 0\n c = 1\n j = 1\n a = []\n a.append(j)\n while c < n:\n b = i + j\n i = j\n j = b\n a.append(b)\n c += 1\n return a", "def printfibb(N):\n if N == 1:\n return [1]\n if N == 2:\n return [1, 1]\n ans = self.printfibb(N - 1)\n ans.append(ans[-1] + ans[-2])\n return ans", "def printfibb(n):\n if n == 0:\n return n\n fib = []\n secondlast = 0\n last = 1\n fib.append(last)\n cur = 0\n for i in range(2, n + 1, 1):\n cur = last + secondlast\n secondlast = last\n last = cur\n fib.append(cur)\n return fib"], "starter_code": "def printfibb(n):\n", "input_output": {"inputs": ["N = 5", "N = 7"], "outputs": ["1 1 2 3 5", "1 1 2 3 5 8 13"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Dynamic Programming", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Mathematics"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/print-first-n-fibonacci-numbers1002/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "printfibb", "task_id": "TACO_lite/103", "example": [[], []]} +{"requirement": "A pronic number is a number which is the product of two consecutive integers. Find all Pronic Numbers less than or equal to the given integer N.\nThe first few Pronic numbers are: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132 and so on.\nExample 1:\nInput:\nN = 6\nOutput:\n0 2 6\nExplanation:\n0 is the product of 0 and 1.\n2 is the product of 1 and 2.\n6 is the product of 2 and 3.\nExample 2:\nInput:\nN = 56\nOutput:\n0 2 6 12 20 30 42 56\nExplanation:\n0 is the product of 0 and 1.\n2 is the product of 1 and 2.\n6 is the product of 2 and 3.\n12 is the product of 3 and 4.\nand so on.\nYour Task: \nYou don't need to read input. Your task is to complete the function pronicNumbers() which takes an integer N as input parameter and returns a list of integers. \nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints: \n1 <= N <= 10^{5}", "solutions": ["def pronicnumbers(N):\n i = 0\n k = []\n j = 0\n while j < N:\n j = i * (i + 1)\n if j > N:\n break\n k.append(j)\n i = i + 1\n return k", "def pronicnumbers(n):\n ans = []\n for i in range(1, n):\n t = (i - 1) * i\n if t <= N:\n ans.append(t)\n else:\n break\n return ans", "def pronicnumbers(N):\n arr = []\n for i in range(1, N + 1):\n if (i - 1) * i <= N:\n arr.append((i - 1) * i)\n return arr", "def pronicnumbers(N):\n i = 0\n a = []\n c = 0\n while c <= N:\n c = i * (i + 1)\n if c > N:\n break\n a.append(c)\n i = i + 1\n return a", "def pronicnumbers(N):\n ans = []\n for i in range(N + 1):\n x = round(i ** 0.5)\n if x * (x + 1) == i:\n ans.append(i)\n return ans", "def pronicnumbers(N):\n l = []\n k = [i for i in range(N)]\n j = 1\n while j < len(k):\n l.append(k[j - 1] * k[j])\n j += 1\n if l[-1] >= N:\n if l[-1] > N:\n l.pop()\n return l", "def pronicnumbers(N):\n k = []\n for i in range(N):\n r = i * (i + 1)\n k.append(r)\n if r == N:\n return k\n elif r > N:\n return k[:-1]", "def pronicnumbers(N):\n i = 0\n list1 = []\n while True:\n prod = i * (i + 1)\n if prod > N:\n break\n else:\n list1.append(prod)\n i += 1\n return list1", "def pronicnumbers(N):\n a = []\n for i in range(N + 1):\n p = round(i ** 0.5)\n if p * (p + 1) == i:\n a.append(i)\n return a", "def pronicnumbers(N):\n list = []\n for j in range(N):\n if j * (j + 1) > N:\n break\n list.append(j * (j + 1))\n return list", "from math import sqrt\n\ndef pronicnumbers(N):\n ans = [0]\n for i in range(1, N + 1):\n temp = int(sqrt(i))\n if temp * (temp + 1) == i:\n ans.append(i)\n return ans", "def pronicnumbers(N):\n n = 1\n st = []\n for i in range(N + 1):\n if i * (i + 1) > N:\n break\n st.append(i * (i + 1))\n return st", "def pronicnumbers(N):\n pronicNumber = []\n for j in range(0, N):\n a = j * (j + 1)\n if a <= N:\n pronicNumber.append(a)\n else:\n break\n return pronicNumber", "def pronicnumbers(N):\n num1 = 0\n num2 = 1\n l = []\n mult = num1 * num2\n while mult <= N:\n l.append(mult)\n num1 += 1\n num2 += 1\n mult = num1 * num2\n return l"], "starter_code": "def pronicnumbers(N):\n", "input_output": {"inputs": ["N = 6", "N = 56"], "outputs": ["0 2 6", "0 2 6 12 20 30 42 56"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/pronic-number0729/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "pronicnumbers", "task_id": "TACO_lite/163", "example": [[], []]} +{"requirement": "Switch/Case - Bug Fixing #6\n\nOh no! Timmy's evalObject function doesn't work. He uses Switch/Cases to evaluate the given properties of an object, can you fix timmy's function?", "solutions": ["def eval_object(v):\n return {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}.get(v['operation'])", "def eval_object(v):\n return eval('{a}{operation}{b}'.format(**v))", "def eval_object(v):\n return eval(str(v['a']) + v['operation'] + str(v['b']))", "eval_object = lambda v: eval('{}{}{}'.format(v['a'], v['operation'], v['b']))", "def eval_object(v):\n return {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '^': 1, '**': v['a'] ** v['b']}[v['operation']]", "from operator import add, sub, truediv, mul, mod, pow\nops = {'+': add, '-': sub, '/': truediv, '*': mul, '%': mod, '**': pow}\none = lambda a, b: 1\n\ndef eval_object(v):\n return ops.get(v['operation'], one)(v['a'], v['b'])", "from typing import Dict, Union\n\ndef eval_object(v: Dict[str, Union[str, int]]) -> int:\n return {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}.get(v['operation'], 1)", "def eval_object(v):\n if v['operation'] == '+':\n return int(v['a']) + int(v['b'])\n elif v['operation'] == '-':\n return int(v['a']) - int(v['b'])\n elif v['operation'] == '/':\n return int(v['a']) / int(v['b'])\n elif v['operation'] == '*':\n return int(v['a']) * int(v['b'])\n elif v['operation'] == '%':\n return int(v['a']) % int(v['b'])\n elif v['operation'] == '**':\n return int(v['a']) ** int(v['b'])", "def eval_object(v):\n if v['operation'] == '+':\n c = v['a'] + v['b']\n return c\n if v['operation'] == '-':\n c = v['a'] - v['b']\n return c\n if v['operation'] == '/':\n c = v['a'] / v['b']\n return c\n if v['operation'] == '*':\n c = v['a'] * v['b']\n return c\n if v['operation'] == '%':\n c = v['a'] % v['b']\n return c\n if v['operation'] == '**':\n c = v['a'] ** v['b']\n return c", "def eval_object(v):\n return eval('%s %s %s' % (v['a'], v['operation'], v['b']))", "def eval_object(v):\n if v['operation'] == '+':\n return v['a'] + v['b']\n elif v['operation'] == '-':\n return v['a'] - v['b']\n elif v['operation'] == '*':\n return v['a'] * v['b']\n elif v['operation'] == '/':\n return v['a'] / v['b']\n elif v['operation'] == '**':\n return v['a'] ** v['b']\n elif v['operation'] == '%':\n return v['a'] % v['b']\n else:\n return 1", "def eval_object(v):\n v = list(map(str, v.values()))\n return eval(v[0] + v[2] + v[1])", "def eval_object(v):\n c = {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}\n if v.get('operation') == '+':\n return v.get('a') + v.get('b')\n elif v.get('operation') == '-':\n return v.get('a') - v.get('b')\n elif v.get('operation') == '*':\n return v.get('a') * v.get('b')\n elif v.get('operation') == '**':\n return v.get('a') ** v.get('b')\n elif v.get('operation') == '/':\n return v.get('a') / v.get('b')\n elif v.get('operation') == '%':\n return v.get('a') % v.get('b')\n else:\n return None", "def eval_object(v):\n return {'+': v['a'] + v['b'], '-': int(v['a']) - int(v['b']), '/': int(v['a']) / int(v['b']), '*': int(v['a']) * int(v['b']), '%': int(v['a']) % int(v['b']), '**': int(v['a']) ** int(v['b'])}.get(v['operation'], 1)", "def eval_object(v):\n x = {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}\n if v['operation'] in x:\n return x.get(v['operation'])", "import operator\n\ndef eval_object(v):\n ops = {'+': operator.add, '-': operator.sub, '/': operator.truediv, '*': operator.mul, '%': operator.mod, '**': operator.pow}\n return ops.get(v.get('operation'))(v.get('a'), v.get('b'))", "def eval_object(v):\n operations = {'+': lambda a, b: a + b, '-': lambda a, b: a - b, '/': lambda a, b: a / b, '*': lambda a, b: a * b, '%': lambda a, b: a % b, '**': lambda a, b: a ** b}\n return operations[v['operation']](v['a'], v['b'])", "def eval_object(operation):\n if operation['operation'] == '+':\n x = operation['a'] + operation['b']\n elif operation['operation'] == '-':\n x = operation['a'] - operation['b']\n elif operation['operation'] == '/':\n x = operation['a'] / operation['b']\n elif operation['operation'] == '*':\n x = operation['a'] * operation['b']\n elif operation['operation'] == '%':\n x = operation['a'] % operation['b']\n elif operation['operation'] == '**':\n x = operation['a'] ** operation['b']\n return x", "def eval_object(v):\n switcher = {'+': \"v['a']+v['b']\", '-': \"v['a']-v['b']\", '/': \"v['a']/v['b']\", '*': \"v['a']*v['b']\", '%': \"v['a']%v['b']\", '**': \"v['a']**v['b']\"}\n return eval(switcher.get(v['operation']))", "def eval_object(v):\n operator = {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}\n return operator[v.get('operation', 1)]", "def eval_object(v):\n return eval(f\"{v['a']}{v['operation']}{v['b']}\")", "def eval_object(v):\n operations = {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}\n return operations.get(v['operation'], 1)", "def eval_object(v):\n if v.get('operation') == '+':\n return v.get('a') + v.get('b')\n elif v.get('operation') == '-':\n return v.get('a') - v.get('b')\n elif v.get('operation') == '/':\n try:\n return v.get('a') / v.get('b')\n except ZeroDivisionError:\n return \"Can't divide by Zero\"\n elif v.get('operation') == '*':\n return v.get('a') * v.get('b')\n elif v.get('operation') == '%':\n return v.get('a') % v.get('b')\n elif v.get('operation') == '**':\n return v.get('a') ** v.get('b')", "def eval_object(v):\n return {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}.get(v['operation'], 'No operation available')", "def eval_object(v):\n a = str(v.get('a'))\n b = str(v.get('b'))\n op = v.get('operation')\n return eval(a + op + b)", "def eval_object(v):\n c = v['operation']\n a = v['a']\n b = v['b']\n if c == '+':\n return a + b\n elif c == '-':\n return a - b\n elif c == '/':\n return a / b\n elif c == '*':\n return a * b\n elif c == '%':\n return a % b\n else:\n return a ** b", "def eval_object(v):\n x = v.get('a')\n y = v.get('b')\n op = v.get('operation')\n return {'+': x + y, '-': x - y, '/': x / y, '*': x * y, '%': x % y, '**': x ** y}.get(op)", "def eval_object(v):\n a = v.get('a')\n b = v.get('b')\n op = v.get('operation')\n if op == '+':\n return a + b\n elif op == '-':\n return a - b\n elif op == '/':\n return a / b\n elif op == '*':\n return a * b\n elif op == '%':\n return a % b\n elif op == '**':\n return a ** b", "eval_object = lambda v: eval('%d %s %d' % (v['a'], v['operation'], v['b'])) if v['operation'] in '**%/-+' else 1", "def eval_object(v):\n Oper = {'+': lambda a, b: a + b, '-': lambda a, b: a - b, '/': lambda a, b: a / b, '*': lambda a, b: a * b, '%': lambda a, b: a % b, '**': lambda a, b: a ** b}\n return Oper[v['operation']](v['a'], v['b'])", "def eval_object(v):\n return {'+': eval(\"v['a']+v['b']\"), '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}.get(v['operation'], 1)", "eval_object = lambda v: {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}.get(v['operation'], 0)", "def eval_object(v):\n return {'+': int(v['a']) + int(v['b']), '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}[v['operation']]", "def eval_object(v):\n\n def add(d):\n return d['a'] + d['b']\n\n def subtract(d):\n return d['a'] - d['b']\n\n def divide(d):\n return d['a'] / d['b']\n\n def remainder(d):\n return d['a'] % d['b']\n\n def multiply(d):\n return d['a'] * d['b']\n\n def double_star(d):\n return d['a'] ** d['b']\n return {'+': add(v), '-': subtract(v), '/': divide(v), '*': multiply(v), '%': remainder(v), '**': double_star(v)}.get(v['operation'])", "def eval_object(v):\n switcher = {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}\n return switcher.get(v['operation'], 1)", "import operator\n\ndef eval_object(expression):\n mathop = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.floordiv, '%': operator.mod, '**': operator.pow}\n if not all((isinstance(n, int) for n in (expression['a'], expression['b']))):\n return 0\n else:\n return mathop[expression['operation']](expression['a'], expression['b'])", "import operator\n\ndef eval_object(v):\n return {'+': operator.add, '-': operator.sub, '/': operator.floordiv, '*': operator.mul, '%': operator.mod, '**': operator.pow}[v['operation']](v['a'], v['b'])", "def eval_object(z):\n (a, b, op) = (z[v] for v in ['a', 'b', 'operation'])\n return {'+': a + b, '-': a - b, '/': a / b, '*': a * b, '%': a % b, '**': a ** b}.get(op)", "def eval_object(v):\n return eval('{0}{1}{2}'.format(v['a'], v['operation'], v['b']))", "def eval_object(v):\n output = {'+': v['a'] + v['b'], '-': v['a'] - v['b'], '/': v['a'] / v['b'], '*': v['a'] * v['b'], '%': v['a'] % v['b'], '**': v['a'] ** v['b']}\n return output[v['operation']]", "def eval_object(v):\n (op, a, b) = (v['operation'], v['a'], v['b'])\n return {'+': a + b, '-': a - b, '/': a / b, '*': a * b, '%': a % b, '**': a ** b}.get(op, 1)"], "starter_code": "def eval_object(v):\n", "input_output": {"fn_name": "eval_object", "inputs": [[{"a": 1, "b": 1, "operation": "+"}], [{"a": 1, "b": 1, "operation": "-"}], [{"a": 1, "b": 1, "operation": "/"}], [{"a": 1, "b": 1, "operation": "*"}], [{"a": 1, "b": 1, "operation": "%"}], [{"a": 1, "b": 1, "operation": "**"}]], "outputs": [[2], [0], [1], [1], [0], [1]]}, "difficulty": "EASY", "raw_tags": ["Debugging"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/55c933c115a8c426ac000082", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "eval_object", "task_id": "TACO_lite/116", "example": [[], []]} +{"requirement": "Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.\nIf it is impossible to form any\u00a0triangle of non-zero area, return 0.\n\u00a0\n\n\n\nExample 1:\nInput: [2,1,2]\nOutput: 5\n\n\nExample 2:\nInput: [1,2,1]\nOutput: 0\n\n\nExample 3:\nInput: [3,2,3,4]\nOutput: 10\n\n\nExample 4:\nInput: [3,6,2,3]\nOutput: 8\n\n\u00a0\nNote:\n\n3 <= A.length <= 10000\n1 <= A[i] <= 10^6", "solutions": ["def largestperimeter(A: List[int]) -> int:\n A.sort(reverse=True)\n la = len(A)\n for i in range(la - 2):\n if A[i] < A[i + 1] + A[i + 2]:\n return A[i] + A[i + 1] + A[i + 2]\n return 0", "def largestperimeter(A: List[int]) -> int:\n sortedA = sorted(A)\n for i in range(len(sortedA) - 3, -1, -1):\n if sortedA[i + 2] < sortedA[i] + sortedA[i + 1]:\n return sum(sortedA[i:i + 3])\n return 0", "def largestperimeter(A: List[int]) -> int:\n A.sort()\n return ([0] + [a + b + c for (a, b, c) in zip(A, A[1:], A[2:]) if c < a + b])[-1]", "def largestperimeter(A: List[int]) -> int:\n A.sort()\n for i in range(len(A) - 1, 1, -1):\n len1 = A[i]\n len2 = A[i - 1]\n len3 = A[i - 2]\n if self.check_triangle(len1, len2, len3):\n return len1 + len2 + len3\n return 0\n\ndef check_triangle(len1, len2, len3):\n if len1 + len2 <= len3 or len2 + len3 <= len1 or len1 + len3 <= len2:\n return False\n return True", "def largestperimeter(A: List[int]) -> int:\n A.sort(reverse=True)\n i = 0\n while i < len(A) - 2:\n if A[i] < A[i + 1] + A[i + 2]:\n return A[i] + A[i + 1] + A[i + 2]\n else:\n i = i + 1\n return 0", "def largestperimeter(A: List[int]) -> int:\n p = 0\n A.sort()\n for i in range(len(A) - 2):\n if A[i] + A[i + 1] > A[i + 2]:\n p = A[i] + A[i + 1] + A[i + 2]\n return p", "def largestperimeter(A: List[int]) -> int:\n A = sorted(A)\n perimeter = 0\n for i in range(len(A) - 2):\n (s1, s2, s3) = (A[i], A[i + 1], A[i + 2])\n p = s1 + s2 + s3\n if s1 + s2 > s3 and s2 + s3 > s1 and (s1 + s3 > s2):\n perimeter = max(perimeter, p)\n return perimeter", "def largestperimeter(A: List[int]) -> int:\n result = 0\n A = sorted(A)\n for i in range(len(A) - 2):\n (a, b, c) = (A[i], A[i + 1], A[i + 2])\n if a + b > c and a + c > b and (b + c > a):\n result = max(result, a + b + c)\n return result", "def largestperimeter(A: List[int]) -> int:\n A.sort()\n for i in range(len(A) - 1, 1, -1):\n a = A[i]\n b = A[i - 1]\n c = A[i - 2]\n if a < b + c:\n return a + b + c\n return 0", "import numpy as np\n\ndef largestperimeter(A: List[int]) -> int:\n valid_area = lambda x, y, z: True if x < y + z else False\n A = sorted(A, reverse=True)\n for a in range(2, len(A)):\n if valid_area(A[a - 2], A[a - 1], A[a]):\n return np.sum([A[a - 2], A[a - 1], A[a]])\n return 0", "def largestperimeter(A: List[int]) -> int:\n A.sort()\n ans = 0\n for i in range(1, len(A) - 1):\n if A[i - 1] + A[i] <= A[i + 1]:\n continue\n else:\n p = sum(A[i - 1:i + 2])\n ans = max(ans, p)\n return ans", "def largestperimeter(A: List[int]) -> int:\n if len(A) < 3:\n return 0\n A.sort()\n counter = 3\n perimeter = 0\n while counter <= len(A):\n a = A[counter - 3]\n b = A[counter - 2]\n c = A[counter - 1]\n if a + b <= c:\n counter += 1\n continue\n elif b + c <= a:\n counter += 1\n continue\n elif c + a <= b:\n counter += 1\n continue\n perimeter = a + b + c\n if a + b + c > perimeter:\n perimeter = a + b + c\n counter += 1\n return perimeter", "def largestperimeter(A: List[int]) -> int:\n A.sort()\n first = 0\n second = 1\n mx = 0\n for third in range(2, len(A)):\n if A[first] + A[second] > A[third]:\n mx = max(mx, A[first] + A[second] + A[third])\n first += 1\n second += 1\n return mx", "def largestperimeter(A: List[int]) -> int:\n A.sort()\n a = len(A) - 1\n while a >= 2:\n if A[a] < A[a - 1] + A[a - 2]:\n return A[a] + A[a - 1] + A[a - 2]\n else:\n a -= 1\n return 0", "def largestperimeter(A: List[int]) -> int:\n A.sort(reverse=True)\n n = len(A)\n for i in range(n - 2):\n for j in range(i + 1, n - 1):\n if A[j] <= A[i] // 2:\n break\n for k in range(j + 1, n):\n if A[i] < A[j] + A[k]:\n return A[i] + A[j] + A[k]\n return 0", "def largestperimeter(A: List[int]) -> int:\n A = sorted(A)\n i = len(A) - 1\n while i >= 2:\n if A[i - 2] + A[i - 1] > A[i]:\n return A[i - 2] + A[i - 1] + A[i]\n i -= 1\n return 0", "def largestperimeter(A: List[int]) -> int:\n A.sort(reverse=True)\n for (a, b, c) in zip(A, A[1:], A[2:]):\n if a < b + c:\n return a + b + c\n else:\n continue\n return 0", "def largestperimeter(A: List[int]) -> int:\n A.sort(reverse=True)\n m = 0\n for i in range(len(A) - 2):\n if A[i] + A[i + 1] > A[i + 2] and A[i + 2] + A[i + 1] > A[i] and (A[i + 2] + A[i] > A[i + 1]):\n x = A[i:i + 3]\n if sum(x) > m:\n m = sum(x)\n return m", "def _isTriangle(queue):\n return queue[0] < queue[1] + queue[2]\n\ndef largestperimeter(A: List[int]) -> int:\n A.sort(key=lambda x: -x)\n nums = []\n for num in A:\n nums.append(num)\n if len(nums) == 3:\n if self._isTriangle(nums):\n return sum(nums)\n nums.pop(0)\n return 0", "def largestperimeter(A: List[int]) -> int:\n n = len(A)\n A.sort(reverse=True)\n a = 0\n while a < n:\n b = a + 1\n c = a + 2\n while b < n and c < n:\n if A[b] + A[c] > A[a]:\n return A[a] + A[b] + A[c]\n else:\n b += 1\n c += 1\n a += 1\n return 0", "def largestperimeter(A: List[int]) -> int:\n if len(A) < 3:\n return 0\n maxer = 0\n pointer1 = len(A) - 3\n pointer2 = len(A) - 2\n pointer3 = len(A) - 1\n A.sort()\n if len(A) == 3:\n if A[0] + A[1] > A[2]:\n return sum(A)\n else:\n return 0\n while pointer3 >= 2:\n if A[pointer1] + A[pointer2] > A[pointer3]:\n return A[pointer1] + A[pointer3] + A[pointer2]\n elif pointer1 == 0:\n pointer3 -= 1\n pointer2 = pointer3 - 1\n pointer1 = pointer2 - 1\n else:\n pointer1 -= 1\n pointer2 -= 1\n return maxer", "def largestperimeter(A: List[int]) -> int:\n A.sort(reverse=True)\n p = 0\n for i in range(len(A) - 2):\n if A[i] < sum(A[i + 1:i + 3]):\n p = sum(A[i:i + 3])\n break\n return p", "def largestperimeter(A: List[int]) -> int:\n A = sorted(A)\n while True:\n if A[-1] + A[-2] > A[-3] and A[-1] + A[-3] > A[-2] and (A[-3] + A[-2] > A[-1]):\n return A[-1] + A[-2] + A[-3]\n A.remove(A[-1])\n if len(A) == 2:\n return 0", "def largestperimeter(A: List[int]) -> int:\n\n def area(a, b, c):\n s = (a + b + c) / 2\n val = (s * (s - a) * (s - b) * (s - c)) ** (1 / 2)\n if isinstance(val, complex):\n return 0\n return val\n A.sort()\n maxi = 0\n for i in range(len(A) - 2):\n val = area(A[i], A[i + 1], A[i + 2])\n if val != 0:\n p = A[i] + A[i + 1] + A[i + 2]\n if p > maxi:\n maxi = p\n return maxi", "def largestperimeter(A: List[int]) -> int:\n\n def formT(a, b, c):\n if not a + b > c:\n return False\n if not b + c > a:\n return False\n if not a + c > b:\n return False\n return True\n sides = sorted(A)\n for i in range(len(sides) - 3, -1, -1):\n if formT(sides[i], sides[i + 1], sides[i + 2]):\n return sides[i] + sides[i + 1] + sides[i + 2]\n return 0", "def largestperimeter(A: List[int]) -> int:\n if len(A) < 3:\n return 0\n A.sort(reverse=True)\n while len(A) > 2:\n max_num = A.pop(0)\n if max_num >= A[0] + A[1]:\n continue\n else:\n return max_num + A[0] + A[1]\n return 0", "def largestperimeter(A: List[int]) -> int:\n res = 0\n A.sort()\n for i in range(len(A)):\n for j in range(i + 1, len(A)):\n source = A[i]\n target = A[j]\n lower = abs(target - source)\n upper = source + target\n if upper * 2 < res:\n continue\n for t in range(j + 1, len(A)):\n if lower < A[t] < upper:\n res = max(source + target + A[t], res)\n break\n if res != 0:\n break\n return res", "def largestperimeter(A: List[int]) -> int:\n A.sort()\n res = 0\n for i in range(len(A) - 2):\n test = A[i:i + 3]\n if test[0] + test[1] > test[2] and test[2] - test[1] < test[0] and (sum(test) > res):\n res = sum(test)\n return res", "def largestperimeter(A: List[int]) -> int:\n A.sort(reverse=True)\n for i in range(len(A) - 2):\n (a, b, c) = (A[i], A[i + 1], A[i + 2])\n c1 = a + b > c\n c2 = b + c > a\n c3 = c + a > b\n if c1 and c2 and c3:\n return a + b + c\n return 0"], "starter_code": "def largestperimeter(A: List[int]) -> int:\n", "input_output": {"fn_name": "largestPerimeter", "inputs": [[[1, 2, 2]]], "outputs": [5]}, "difficulty": "EASY", "raw_tags": ["Math", "Sorting", "Greedy", "Array"], "name": null, "source": "leetcode", "tags": ["Sorting", "Data structures", "Mathematics", "Greedy algorithms"], "skill_types": ["Sorting", "Data structures", "Greedy algorithms"], "url": "https://leetcode.com/problems/largest-perimeter-triangle/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "largestperimeter", "task_id": "TACO_lite/123", "example": [[[[2, 1, 2]], [[1, 2, 1]], [[3, 2, 3, 4]], [[3, 6, 2, 3]]], ["5", "0", "10", "8"]]} +{"requirement": "In this Kata, you will be given a string and your task is to determine if that string can be a palindrome if we rotate one or more characters to the left.\n\n```Haskell\nsolve(\"4455\") = true, because after 1 rotation, we get \"5445\" which is a palindrome\nsolve(\"zazcbaabc\") = true, because after 3 rotations, we get \"abczazcba\", a palindrome\n```\n\nMore examples in test cases. Input will be strings of lowercase letters or numbers only.\n\nGood luck!", "solutions": ["def solve(s):\n return any((s[i + 1:] + s[:i + 1] == s[i::-1] + s[:i:-1] for i in range(len(s))))", "def solve(s):\n for i in range(len(s)):\n xs = s[i:] + s[:i]\n if xs == xs[::-1]:\n return True\n return False", "from collections import deque\n\ndef solve(st):\n s = deque(st)\n return any((s == deque(reversed(s)) for _ in range(len(st)) if not s.rotate(1)))", "is_pal = lambda s: all((s[i] == s[len(s) - i - 1] for i in range(len(s) // 2)))\nsolve = lambda s: any((is_pal(s[i:] + s[:i]) for i in range(len(s))))", "def is_palindrome(s):\n for (i, (a, b)) in enumerate(zip(s, s[::-1])):\n if a != b:\n return False\n if i == len(s) // 2:\n return True\n\ndef solve(st):\n for i in range(len(st)):\n if is_palindrome(st[i:] + st[:i]):\n return True\n return False", "def rotate(list_):\n return list_[1:] + list_[:1]\n\ndef is_palindrome(list_):\n return list_ == list_[::-1]\n\ndef solve(st):\n list_ = list(st)\n for _ in range(len(st)):\n if is_palindrome(list_):\n return True\n else:\n list_ = rotate(list_)\n return False", "(q, solve) = (lambda p: p == p[::-1], lambda s: any((q(s[x:] + s[:x]) for x in range(len(s)))))", "solve = lambda s, c=0: s == s[::-1] or solve(s[-1] + s[:-1], c=c + 1) if c != len(s) else 0", "def solve(st):\n for x in range(len(st)):\n if st == st[::-1]:\n return True\n else:\n st = st[1:] + st[0]\n return False"], "starter_code": "def solve(s):\n", "input_output": {"fn_name": "solve", "inputs": [["aaab"], ["abcabc"], ["4455"], ["zazcbaabc"], ["223456776543"], ["432612345665"], ["qponmlkjihgfeeiefghijklmnopqrsttsr"]], "outputs": [[false], [false], [true], [true], [true], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5a8fbe73373c2e904700008c", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/180", "example": [[], []]} +{"requirement": "Given two coordinates (x, y) and (a, b). Find if it is possible to reach (x,y) from (a,b).\nOnly possible moves from any coordinate (i, j) are-\n\t(i-j, j)\n\t(i, i-j)\n\t(i+j, j)\n\t(i, i+j)\n \nExample 1:\nInput:\nx = 1, y = 1, a = 2, b = 3\nOutput:\n1\nExplanation:\nWe can reach the point (2,3) from (1,1).\nExample 2:\nInput:\nx = 35, y = 15, a = 20, b = 25\nOutput:\n1\nExplanation:\nWe can reach the point (20,25) from (35,15).\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function isPossible() which takes 4 Integers x, y, a and b as input and returns 1 if it's possible to move to (a,b) from (x,y) else returns 0.\n \nExpected Time Complexity: O(log(x))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n-10^{5} <= x,y,a,b <= 10^{5}", "solutions": ["def ispossible(x, y, a, b):\n\n def gcd(x, y):\n x = abs(x)\n y = abs(y)\n if x < y:\n (x, y) = (y, x)\n while y:\n (x, y) = (y, x % y)\n return x\n if gcd(x, y) == gcd(a, b):\n return 1\n else:\n return 0", "def ispossible(x, y, a, b):\n\n def gcd(m, n):\n if n == 0:\n return m\n return gcd(n, m % n)\n if abs(gcd(a, b)) == abs(gcd(x, y)):\n return 1\n else:\n return 0", "import math\n\ndef ispossible(x, y, a, b):\n\n def gcd(n, m):\n if m == 0:\n return n\n return gcd(m, n % m)\n g = gcd(x, y)\n h = gcd(a, b)\n if abs(g) == abs(h):\n return 1\n return 0", "import math\n\ndef ispossible(x, y, a, b):\n if math.gcd(x, y) == math.gcd(a, b):\n return 1\n return 0", "from math import gcd\n\ndef ispossible(x, y, a, b):\n return int(gcd(abs(x), abs(y)) == gcd(abs(a), abs(b)))", "def gcd(i, j):\n if i < j:\n (i, j) = (j, i)\n while j:\n (i, j) = (j, i % j)\n return i\n\ndef ispossible(x, y, a, b):\n (x, y, a, b) = (abs(x), abs(y), abs(a), abs(b))\n if self.gcd(x, y) == self.gcd(a, b):\n return 1\n return 0", "import math\n\ndef ispossible(x, y, a, b):\n e = math.gcd(a, b)\n f = math.gcd(x, y)\n if e == f:\n return 1\n else:\n return 0", "def ispossible(x, y, a, b):\n\n def gc(i, j):\n if j == 0:\n return i\n else:\n return gc(j, i % j)\n if gc(abs(x), abs(y)) == gc(abs(a), abs(b)):\n return 1\n else:\n return 0", "import math as m\n\ndef ispossible(x, y, a, b):\n r = m.gcd(x, y)\n e = m.gcd(a, b)\n if r == e:\n return 1\n else:\n return 0", "def ispossible(x, y, a, b):\n\n def find_gcd(a, b):\n if b == 0:\n return a\n if a == 0:\n return b\n if a > b:\n (a, b) = (b, a)\n return find_gcd(a, b % a)\n if x < 0:\n x = x * -1\n if y < 0:\n y = y * -1\n if a < 0:\n a = a * -1\n if b < 0:\n b = b * -1\n if find_gcd(x, y) == find_gcd(a, b):\n return 1\n return 0", "import math\n\ndef ispossible(x, y, a, b):\n (gxy, gab) = (0, 0)\n if math.gcd(x, y) == math.gcd(a, b):\n return 1\n else:\n return 0", "import math\n\ndef ispossible(x, y, a, b):\n k = math.gcd(a, b)\n m = math.gcd(x, y)\n if k == m:\n return 1\n else:\n return 0", "def ispossible(x, y, a, b):\n\n def gcd_(a, b):\n while a and b:\n if a > b:\n a %= b\n else:\n b %= a\n if a:\n return a\n return b\n if gcd_(abs(a), abs(b)) == gcd_(abs(x), abs(y)):\n return 1\n return 0", "def gc(n, m):\n while n != 0 and m != 0:\n if n < m:\n m = m % n\n else:\n n = n % m\n if n == 0:\n return m\n else:\n return n\n\ndef ispossible(x, y, a, b):\n g = self.gc(x, y)\n c = self.gc(a, b)\n if abs(g) == abs(c):\n return 1\n return 0"], "starter_code": "def ispossible(x, y, a, b):\n", "input_output": {"inputs": ["x = 1, y = 1, a = 2, b = 3", "x = 35, y = 15, a = 20, b = 25"], "outputs": ["1", "1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/check-if-possible-to-move-from-given-coordinate-to-desired-coordinate5944/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(x))", "entry_point": "ispossible", "task_id": "TACO_lite/164", "example": [[[1, 1, 2, 3], [35, 15, 20, 25]], ["1", "1"]]} +{"requirement": "Given a positive integer N, find the Nth Even Fibonacci number. Since the answer can be very large, return the answer modulo 1000000007.\nExample 1:\nInput: n = 1\nOutput: 2 \nExplanation: 2 is the first even\nnumber in the fibonacci series.\nExample 2:\nInput: n = 2\nOutput: 8\nExplanation: 8 is the second even\nnumber in the fibonacci series.\nYour Task: \nYou dont need to read input or print anything. Complete the function nthEvenFibonacci() which takes S as input parameter and returns the Nth even fibonacci number.\nExpected Time Complexity: O(n)\nExpected Auxiliary Space: O(n)\nConstraints:\n1<= n <=1000", "solutions": ["def nthevenfibonacci(ob, n):\n a = 1\n b = 1\n z = 0\n c = 0\n while c != n:\n z = a + b\n a = b\n b = z\n if z % 2 == 0:\n c += 1\n return z % 1000000007", "def nthevenfibonacci(n):\n net = n * 3\n return self.gfn(net) % 1000000007\n\ndef gfn(n):\n if n < 1:\n return 0\n n1 = 0\n n2 = 1\n while n > 1:\n n2 += n1\n n1 = n2 - n1\n n -= 1\n return n2", "def nthevenfibonacci(ob, n):\n dp = [0] * (3 * n)\n dp[0] = 1\n dp[1] = 1\n i = 2\n f = 0\n while f < n:\n dp[i] = dp[i - 1] + dp[i - 2]\n if dp[i] % 2 == 0:\n f += 1\n if f == n:\n return dp[i] % 1000000007\n i += 1", "def nthevenfibonacci(ob, n):\n ob.n = n\n ob.l = [0, 1]\n ob.a = 0\n ob.b = 1\n for i in range(1, 3 * n):\n ob.c = ob.a + ob.b\n ob.l.append(ob.c)\n (ob.a, ob.b) = (ob.b, ob.c)\n return ob.l[-1] % 1000000007", "def nthevenfibonacci(ob, n):\n a = 0\n b = 1\n l = []\n while 1:\n c = a + b\n if a % 2 == 0:\n l.append(a)\n a = b\n b = c\n if len(l) == n + 1:\n break\n return l[-1] % (10 ** 9 + 7)", "def nthevenfibonacci(ob, n):\n (f1, f2) = (0, 1)\n f = []\n c = 0\n while c != n:\n f3 = f1 + f2\n if f3 % 2 == 0:\n f.append(f3 % (10 ** 9 + 7))\n c += 1\n f1 = f2\n f2 = f3\n return f[n - 1]", "def nthevenfibonacci(ob, n):\n even_counter = 0\n prev_fib = 1\n cur_fib = 1\n while even_counter < n:\n next_fib = prev_fib + cur_fib\n if next_fib % 2 == 0:\n even_counter += 1\n prev_fib = cur_fib\n cur_fib = next_fib\n return next_fib % 1000000007", "def nthevenfibonacci(ob, n):\n fibos = []\n fibos.append(0)\n fibos.append(1)\n evens = 0\n i = 2\n while evens < n:\n fibos.append(fibos[i - 1] + fibos[i - 2])\n if fibos[i] % 2 == 0:\n evens = evens + 1\n if evens == n:\n return fibos[i] % (pow(10, 9) + 7)\n i = i + 1\n return -1", "def nthevenfibonacci(ob, N):\n i = 0\n j = 0\n k = 0\n l = 0\n f1 = 0\n f2 = 1\n f3 = 0\n while l < N:\n f3 = f1 + f2\n f1 = f2\n f2 = f3\n if f3 % 2 == 0:\n l = l + 1\n f3 = f3 % 1000000007\n return f3 % 1000000007", "def nthevenfibonacci(ob, n):\n a = 0\n b = 1\n lst = []\n for i in range(0, n * 2):\n a = b + a\n b = b + a\n if a % 2 == 0:\n lst.append(a)\n if b % 2 == 0:\n lst.append(b)\n if len(lst) == n + 1:\n break\n return lst[n - 1] % 1000000007", "def nthevenfibonacci(ob, n):\n n1 = 1\n n2 = 1\n k = 1\n while k <= n:\n if n2 % 2 == 0:\n k += 1\n (n1, n2) = (n2, n1 + n2)\n return n1 % 1000000007", "def nthevenfibonacci(ob, n):\n mod = 1000000007\n (a, b, c) = (0, 1, 1)\n i = 1\n while i < 3 * n:\n c = (a + b) % mod\n a = b\n b = c\n i += 1\n return c % mod", "def nthevenfibonacci(ob, n):\n (a, b) = (1, 1)\n m = 10 ** 9 + 7\n for i in range(3 * n - 2):\n c = (a + b) % m\n a = b\n b = c\n return b", "def nthevenfibonacci(ob, N):\n first = 0\n second = 1\n third = 1\n count = 0\n while True:\n third = first + second\n first = second\n second = third\n if third % 2 == 0:\n count = count + 1\n if count == N:\n return third % 1000000007", "def nthevenfibonacci(n):\n a = 0\n b = 1\n even_count = 0\n if n <= 0:\n return 'Incorrect Input'\n else:\n for i in range(2, 10000):\n c = a + b\n a = b\n b = c\n if c % 2 == 0:\n even_count += 1\n if even_count == n:\n return c % 1000000007", "def nthevenfibonacci(ob, n):\n x = 0\n y = 1\n sum = 0\n count = 0\n while count != n:\n sum = x + y\n x = y\n y = sum\n if sum % 2 == 0:\n count = count + 1\n return sum % 1000000007", "def nthevenfibonacci(ob, n):\n if n <= 1:\n return n\n elif n == 1:\n return 2\n else:\n a = 0\n b = 1\n c = 0\n for i in range(1, n * 3):\n c = a + b\n a = b\n b = c\n return c % (10 ** 9 + 7)", "def nthevenfibonacci(ob, n):\n k = 0\n y = [0, 1]\n while k != n:\n y.append(y[-1] + y[-2])\n if y[-1] % 2 == 0:\n k += 1\n return y[-1] % 1000000007", "def nthevenfibonacci(ob, n):\n count = 0\n a = 1\n b = 1\n while count < n:\n num = a + b\n a = b\n b = num\n if num % 2 == 0:\n count += 1\n if count == n:\n return num % 1000000007\n break", "def nthevenfibonacci(ob, n):\n (a, b) = (1, 1)\n while n:\n (a, b) = (b, a + b)\n if a % 2 == 0:\n n -= 1\n return a % int(1000000000.0 + 7)", "def nthevenfibonacci(ob, n):\n index = n * 3\n l = [0, 1]\n for i in range(2, index + 1):\n l.append(l[i - 2] + l[i - 1])\n return l[index] % 1000000007", "def nthevenfibonacci(ob, n):\n c = 0\n x = 1\n y = 1\n while c < n:\n (x, y) = (y, x + y)\n if y % 2 == 0:\n c += 1\n return y % 1000000007", "def nthevenfibonacci(ob, n):\n count = 0\n a = 1\n b = 1\n while count != n:\n t = a\n a = b\n b = t + b\n if b % 2 == 0:\n count += 1\n return b % 1000000007", "def nthevenfibonacci(ob, n):\n a = 0\n b = 1\n while n > 0:\n value = a\n a = b\n b = value + b\n if b % 2 == 0:\n n = n - 1\n m = 1000000007\n return b % m", "def nthevenfibonacci(ob, n):\n fib = [1, 1]\n x = 2\n while n > 0:\n fib += [fib[-1] + fib[-2]]\n if fib[-1] % 2 == 0:\n x = fib[-1]\n else:\n continue\n n -= 1\n return x % 1000000007", "def nthevenfibonacci(ob, n):\n (x, y, z, k) = (0, 1, 1, 0)\n while k != n:\n if z % 2 == 0:\n k += 1\n if k == n:\n return z % (10 ** 9 + 7)\n x = y\n y = z\n z = x + y", "def nthevenfibonacci(ob, n):\n p = 1000000007\n fib = [1 for _ in range(3 * n + 1)]\n for i in range(3, 3 * n + 1):\n fib[i] = (fib[i - 1] % p + fib[i - 2] % p) % p\n return fib[3 * n]", "def nthevenfibonacci(ob, n):\n even = 0\n fib = [1, 1]\n while even != n:\n fib.append(fib[-1] + fib[-2])\n if fib[-1] % 2 == 0:\n even += 1\n return fib[-1] % 1000000007", "def nthevenfibonacci(ob, n):\n count = 0\n x = 0\n y = 1\n mod = 10 ** 9 + 7\n while True:\n c = x + y\n x = y\n y = c\n if y % 2 == 0:\n count += 1\n if count == n:\n break\n return y % mod", "def nthevenfibonacci(ob, N):\n (a, b, c) = (0, 1, 1)\n while N > 0:\n c = a + b\n (a, b) = (b, c)\n if c % 2 == 0:\n N -= 1\n return c % 1000000007", "def nthevenfibonacci(ob, n):\n a = [0] * (3 * n + 1)\n for i in range(1, 3 * n + 1):\n if i == 1:\n a[i] = 1\n else:\n a[i] = a[i - 1] + a[i - 2]\n return a[3 * n] % 1000000007", "def nthevenfibonacci(ob, n):\n n = 3 * n\n dp = [0] * (n + 1)\n mod = 1000000007\n dp[0] = 0\n dp[1] = 1\n for i in range(2, n + 1):\n dp[i] = (dp[i - 1] + dp[i - 2]) % mod\n return dp[n]", "def nthevenfibonacci(ob, n):\n m = 10 ** 9 + 7\n (a, b, c, z) = (1, 1, 0, 0)\n while c != n:\n z = a + b\n a = b\n b = z\n if z % 2 == 0:\n c += 1\n return z % m", "def nthevenfibonacci(ob, n):\n x = [0, 1]\n count = 0\n for i in range(10000):\n a = x[-1] + x[-2]\n if a % 2 == 0:\n count += 1\n if count == n:\n return a % 1000000007\n else:\n x.append(a)", "def nthevenfibonacci(ob, n):\n mod = 10 ** 9 + 7\n n = n * 3\n dp = [0] * (n + 1)\n dp[1] = 1\n for i in range(2, n + 1):\n dp[i] = (dp[i - 1] % mod + dp[i - 2] % mod) % mod\n return dp[n]", "def nthevenfibonacci(ob, n):\n (a, b) = (0, 1)\n c = 0\n d = 0\n for i in range(0, 9999999):\n c = a + b\n a = b\n b = c\n if c % 2 == 0:\n d += 1\n if d == n:\n return c % 1000000007\n break", "def nthevenfibonacci(ob, n):\n a = 0\n b = 1\n arr = []\n while len(arr) != n:\n res = a + b\n if res % 2 == 0:\n arr.append(res)\n a = b\n b = res\n return arr[n - 1] % 1000000007", "def nthevenfibonacci(ob, n):\n M = 10 ** 9 + 7\n cnt = 0\n (a, b) = (1, 1)\n f = 0\n while cnt != n:\n f = a + b\n a = b\n b = f\n if f & 1 == 0:\n cnt += 1\n return f % M", "def nthevenfibonacci(ob, n):\n a = 2\n b = 8\n c = 1\n if n == 1:\n return a\n if n == 2:\n return b\n for i in range(3, n + 1):\n c = (4 * b + a) % 1000000007\n a = b\n b = c\n return c", "def nthevenfibonacci(ob, n):\n h = 2\n s = 8\n if n == 1:\n return h\n if n == 2:\n return s\n for i in range(3, n + 1):\n q = (4 * s + h) % 1000000007\n (h, s) = (s, q)\n return q % 1000000007", "def nthevenfibonacci(ob, n):\n even = []\n fib = [1, 1]\n while len(even) < n:\n t = fib[-1] + fib[-2]\n if t % 2 == 0:\n even.append(t)\n fib.append(t)\n return even[n - 1] % (10 ** 9 + 7)", "def nthevenfibonacci(ob, n):\n f = [0, 2]\n for i in range(2, n + 1):\n f.append(4 * f[i - 1] + f[i - 2])\n return f[n] % 1000000007", "def nthevenfibonacci(ob, n):\n a = 1\n b = 1\n for i in range(1, 3 * n - 1):\n s = a + b\n a = b\n b = s\n return s % 1000000007", "def nthevenfibonacci(ob, n):\n (a, b, c) = (1, 1, 0)\n c1 = 0\n while c1 != n:\n c = a + b\n (a, b) = (b, c)\n if ~c & 1:\n c1 += 1\n return c % 1000000007", "def nthevenfibonacci(ob, n):\n a0 = 0\n a1 = 1\n num = 0\n count = 0\n while count != n:\n num = a0 + a1\n a0 = a1\n a1 = num\n if num % 2 == 0:\n count += 1\n return num % 1000000007", "def nthevenfibonacci(ob, n):\n c = [1, 1]\n i = 0\n a = 0\n while True:\n c.append(c[i] + c[i + 1])\n i += 1\n if c[-1] % 2 == 0:\n a += 1\n if a == n:\n return c[-1] % 1000000007", "def nthevenfibonacci(ob, n):\n if n == 0:\n return 0\n x = [0, 1, 1]\n while n > 0:\n x[0] = int(x[1] + x[2])\n (x[0], x[1]) = (x[1], x[0])\n (x[1], x[2]) = (x[2], x[1])\n if x[2] % 2 == 0:\n n -= 1\n return int(x[2] % 1000000007)", "def nthevenfibonacci(ob, n):\n t1 = 1\n t2 = 1\n s = 0\n c = 0\n while c != n:\n s = t1 + t2\n t1 = t2\n t2 = s\n if s % 2 == 0:\n c = c + 1\n return s % 1000000007", "def nthevenfibonacci(ob, n):\n f = 0\n s = 1\n flag = False\n c = 0\n while flag == False:\n digit = f + s\n if digit % 2 == 0:\n c = c + 1\n if c == n:\n flag = True\n return digit % 1000000007\n else:\n f = s\n s = digit\n else:\n f = s\n s = digit"], "starter_code": "def nthevenfibonacci (ob, n):\n", "input_output": {"inputs": ["n = 1", "n = 2"], "outputs": ["2", "8"]}, "difficulty": "EASY", "raw_tags": ["Fibonacci", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/nth-even-fibonacci-number1119/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "nthevenfibonacci", "task_id": "TACO_lite/183", "example": [[[1], [2]], ["2", "8"]]} +{"requirement": "Calculate the sum of all the multiples of 3 or 7 below the natural number N.\nExample 1:\nInput: 10\nOutput: 25\nExplanation:\nNumbers that are multiple of 3 or 7\nare 3, 6, 7, 9 so sum will be 25.\nExample 2:\nInput: 25\nOutput: 84\nExplanation: \nNumbers that are multiple of 3 or 7\nare 3, 6, 7, 9, 12, 14, 15, 18 so \nsum will be 84.\nYour Task:\nYou don't need to read or print anything. Your task is to complete the function sum() which takes N as input parameter and returns the sum of numbers that are multiple of 3 or 7.\nExpected Time Complexity: O(1)\nExpected Space Complexity: O(1)\nConstraints:\n1 <= N <= 1000000", "solutions": ["def sum(N):\n s = 0\n for i in range(1, N):\n if i % 3 == 0 or i % 7 == 0:\n s += i\n return s", "def sum(N):\n (m3, m7, m21) = (N // 3, N // 7, N // 21)\n (s3, s7, s21) = (3 * (m3 * (m3 + 1) // 2), 7 * (m7 * (m7 + 1) // 2), 21 * (m21 * (m21 + 1) // 2))\n if N % 3 == 0 or N % 7 == 0:\n return s3 + s7 - N - s21\n return s3 + s7 - s21", "def sum(N):\n k = (N - 1) // 3\n m = (N - 1) // 7\n p = (N - 1) // 21\n S3 = 3 * (k * (k + 1) // 2)\n S7 = 7 * (m * (m + 1) // 2)\n S21 = 21 * (p * (p + 1) // 2)\n return S3 + S7 - S21", "def sum(N):\n l = []\n for i in range(N):\n if i % 3 == 0 or i % 7 == 0:\n l.append(i)\n return sum(l)", "def sum(N):\n s = set()\n a = 3\n for i in range(1, N):\n c = a * i\n if c >= N:\n break\n else:\n s.add(c)\n b = 7\n for i in range(1, N):\n d = b * i\n if d >= N:\n break\n else:\n s.add(d)\n ans = 0\n for i in s:\n ans += i\n return ans", "def sum(N):\n s = 0\n for x in range(0, N):\n if x % 3 == 0 or x % 7 == 0:\n s += x\n return s", "def sum(N):\n s = 0\n i = 1\n while i < N:\n if i % 3 == 0 or i % 7 == 0:\n s = s + i\n i += 1\n return s"], "starter_code": "def sum(N):\n", "input_output": {"inputs": ["10", "25"], "outputs": ["25", "84"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/multiples-power2816/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "sum", "task_id": "TACO_lite/184", "example": [[[10], [25]], [25, 129]]} +{"requirement": "Given an array A[ ] of N integers and an integer X. In one operation, you can change the i^{th} element of the array to any integer value where 1 \u2264 i \u2264 N. Calculate minimum number of such operations required such that the bitwise AND of all the elements of the array is strictly greater than X.\nExample 1:\nInput:\nN = 4, X = 2\nA[] = {3, 1, 2, 7}\nOutput: \n2\nExplanation: \nAfter performing two operations:\nModified array: {3, 3, 11, 7} \nNow, Bitwise AND of all the elements\nis 3 & 3 & 11 & 7 = 3 \nExample 2:\nInput:\nN = 3, X = 1\nA[] = {2, 2, 2}\nOutput: \n0\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function count( ) which takes N, A[ ] and X as input parameters and returns the minimum number of operations required.\nExpected Time Complexity: O(N * Log(max(A[ ])))\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 N \u2264 10^{5}\n1 \u2264 A[i] \u2264 10^{9}\n1 \u2264 X \u2264 10^{9}", "solutions": ["def count(N, A, X):\n (res, bitset) = (N, 0)\n for i in range(32, -1, -1):\n if X & 1 << i > 0:\n bitset |= 1 << i\n else:\n count = 0\n temp = bitset | 1 << i\n for num in A:\n if num & temp != temp:\n count += 1\n res = min(res, count)\n return res", "def count(N, A, X):\n (res, bitset) = (float('inf'), 0)\n for i in range(30, -1, -1):\n if X & 1 << i > 0:\n bitset |= 1 << i\n else:\n count = 0\n temp = bitset | 1 << i\n for num in A:\n if num & temp != temp:\n count += 1\n res = min(res, count)\n return res", "def count(N, A, X):\n prefix = 0\n ans = N\n for i in range(30, -1, -1):\n if X >> i & 1 != 0:\n prefix ^= 1 << i\n continue\n ct = 0\n p = prefix ^ 1 << i\n for j in range(N):\n if A[j] & p == p:\n ct += 1\n ans = min(ans, N - ct)\n return ans", "def count(N, A, X):\n ans = 10 ** 9 + 9\n cur_xor = 0\n for i in range(31, -1, -1):\n if X & 1 << i:\n cur_xor = cur_xor | 1 << i\n else:\n temp = cur_xor | 1 << i\n cnt = 0\n for i in range(0, N):\n if temp & A[i] == temp:\n cnt = cnt + 1\n ans = min(ans, N - cnt)\n return ans", "def count(N, A, X):\n m = A[0]\n for i in range(1, N):\n m &= A[i]\n ans = N\n for i in range(32):\n if 1 << i | m > X:\n c = 0\n for x in A:\n if x & 1 << i == 0:\n c += 1\n ans = min(ans, c)\n s = set()\n for i in range(31, -1, -1):\n if 1 << i & X != 0:\n for (j, x) in enumerate(A):\n if 1 << i & x == 0:\n s.add(j)\n else:\n t = set()\n for (j, x) in enumerate(A):\n if 1 << i & x == 0:\n t.add(j)\n ans = min(ans, len(s | t))\n return ans", "def count(n, l, x):\n\n def fun(t):\n c = 0\n for i in l:\n if t & i != t:\n c += 1\n return c\n maxv = max(l)\n ans = n\n for i in range(maxv + 1):\n a = 1 << i\n t = x + a - x % a\n if t > maxv:\n break\n ans = min(ans, fun(t))\n return ans"], "starter_code": "def count(N, A, X):\n", "input_output": {"inputs": ["N = 4, X = 2\nA[] = {3, 1, 2, 7}", "N = 3, X = 1\nA[] = {2, 2, 2}"], "outputs": ["2", "0"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Greedy", "Bit Magic", "Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures", "Greedy algorithms"], "skill_types": ["Bit manipulation", "Data structures", "Greedy algorithms"], "url": "https://practice.geeksforgeeks.org/problems/7ba682ec660335b1627f2183f63bd2c8a37391ec/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N * Log(max(A[ ])))", "entry_point": "count", "task_id": "TACO_lite/169", "example": [[[4, 2, [3, 1, 2, 7]], [3, 1, [2, 2, 2]]], [null, null]]} +{"requirement": "#Find the missing letter\n\nWrite a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array.\n\nYou will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2.\nThe array will always contain letters in only one case.\n\nExample:\n```if-not:swift\n['a','b','c','d','f'] -> 'e'\n['O','Q','R','S'] -> 'P'\n```\n\n(Use the English alphabet with 26 letters!)\n\nHave fun coding it and please don't forget to vote and rank this kata! :-) \n\nI have also created other katas. Take a look if you enjoyed this kata!", "solutions": ["def find_missing_letter(chars):\n n = 0\n while ord(chars[n]) == ord(chars[n + 1]) - 1:\n n += 1\n return chr(1 + ord(chars[n]))", "def find_missing_letter(input):\n alphabet = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')\n start = alphabet.index(input[0])\n for i in range(len(input)):\n if not input[i] == alphabet[start + i]:\n return alphabet[start + i]", "def find_missing_letter(c):\n return next((chr(ord(c[i]) + 1) for i in range(len(c) - 1) if ord(c[i]) + 1 != ord(c[i + 1])))", "def find_missing_letter(chars):\n for x in range(1, len(chars)):\n if ord(chars[x]) - ord(chars[x - 1]) != 1:\n return chr(ord(chars[x]) - 1)", "def find_missing_letter(chars):\n return [chr(n) for n in range(ord(chars[0]), ord(chars[-1]) + 1) if n not in [ord(c) for c in chars]][0]", "def find_missing_letter(chars):\n s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n match = False\n count = 0\n for letter in s:\n if letter == chars[count]:\n match = True\n count = count + 1\n elif match == True:\n return letter", "def find_missing_letter(chars):\n for i in range(0, len(chars) - 1):\n current = chars[i]\n after = chars[i + 1]\n expected = chr(ord(current) + 1)\n if after != expected:\n return expected\n return ''", "def find_missing_letter(chars):\n return set((chr(i) for i in range(ord(chars[0]), ord(chars[-1]) + 1))).difference(set(chars)).pop()", "def find_missing_letter(chars):\n next = chars[0]\n for letter in chars:\n if letter != next:\n return next\n next = chr(ord(letter) + 1)\n return 0"], "starter_code": "def find_missing_letter(chars):\n", "input_output": {"fn_name": "find_missing_letter", "inputs": [[["a", "b", "c", "d", "f"]], [["O", "Q", "R", "S"]], [["b", "d"]]], "outputs": [["e"], ["P"], ["c"]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5839edaa6754d6fec10000a2", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "find_missing_letter", "task_id": "TACO_lite/167", "example": [[[["a", "b", "c", "d", "f"]], [["O", "Q", "R", "S"]]], ["e", "P"]]} +{"requirement": "Given an array arr[] of N integers, calculate the median\n \nExample 1:\nInput: N = 5\narr[] = 90 100 78 89 67\nOutput: 89\nExplanation: After sorting the array \nmiddle element is the median \nExample 2:\nInput: N = 4\narr[] = 56 67 30 79\nOutput: 61\nExplanation: In case of even number of \nelements, average of two middle elements \nis the median.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function find_median() which takes the array as input parameter and returns the floor value of the median.\n \nExpected Time Complexity: O(n * log(n))\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= Length of Array <= 100\n1 <= Elements of Array <= 100", "solutions": ["def find_median(v):\n n = len(v)\n v.sort()\n if n == 0:\n return -1\n if n == 1:\n return int(v[0])\n if n == 2:\n return int((v[0] + v[1]) / 2)\n if n >= 3:\n if n % 2 == 0:\n p1 = int(n / 2)\n p2 = int(n / 2 - 1)\n return int((v[p1] + v[p2]) / 2)\n else:\n return int(v[int(n / 2)])", "def find_median(v):\n v.sort()\n n = len(v)\n if len(v) % 2 == 0:\n res = (v[int(n / 2 - 1)] + v[int(n / 2)]) / 2\n return int(res)\n else:\n return v[n // 2]", "def find_median(v):\n v.sort()\n n = len(v)\n if n % 2 == 1:\n median = v[n // 2]\n else:\n median = (v[n // 2 - 1] + v[n // 2]) / 2\n return int(median)", "def find_median(v):\n v.sort()\n if len(v) % 2 != 0:\n mid = len(v) // 2\n return v[mid]\n elif len(v) % 2 == 0:\n mid = len(v) // 2\n return (v[mid] + v[mid - 1]) // 2", "def find_median(arr):\n if len(arr) == 0:\n return\n import statistics\n return int(statistics.median(arr))", "def find_median(v):\n if len(v) == 0:\n return\n v.sort()\n return v[len(v) // 2] if len(v) % 2 == 1 else (v[len(v) // 2] + v[len(v) // 2 - 1]) // 2", "def find_median(v):\n temp = sorted(v)\n while len(temp) > 2:\n temp = temp[1:-1]\n if len(temp) == 2:\n return sum(temp) // 2\n return temp[0]", "def find_median(v):\n n = v.sort()\n k = len(v) // 2\n if len(v) % 2 != 0:\n return v[k]\n else:\n sum = (v[k - 1] + v[k]) // 2\n return sum", "def find_median(v):\n v.sort()\n m = 0\n n = len(v)\n if n % 2 != 0:\n m = v[int((n + 1) / 2) - 1]\n else:\n w = int(n / 2)\n x = int(w + 1)\n m = int((v[w - 1] + v[x - 1]) / 2)\n return m", "def find_median(v):\n v.sort()\n l = 0\n r = len(v) - 1\n mid = l + (r - l) // 2\n if len(v) % 2 != 0:\n return v[mid]\n elif len(v) % 2 == 0:\n return int((v[mid] + v[mid + 1]) / 2)", "def find_median(v):\n v.sort()\n l = len(v)\n if l % 2 != 0:\n a = l // 2\n return v[a]\n else:\n a = l // 2\n b = l // 2 - 1\n c = int((v[a] + v[b]) / 2)\n return c", "def find_median(v):\n arr = list(v)\n arr.sort()\n N = len(arr)\n if N % 2 != 0:\n return arr[N // 2]\n else:\n o = N // 2\n return (arr[o] + arr[o - 1]) // 2", "import math\n\ndef find_median(v):\n for i in range(1, len(v)):\n j = i - 1\n while v[i] < v[j] and j >= 0:\n j -= 1\n j += 1\n temp = v[i]\n k = i\n while k >= j:\n v[k] = v[k - 1]\n k -= 1\n v[j] = temp\n mid = math.floor(len(v) / 2)\n if len(v) % 2 == 0:\n return math.floor((v[mid - 1] + v[mid]) / 2)\n else:\n return v[mid]", "def find_median(v):\n d = sorted(v)\n if len(v) % 2 != 0:\n y = len(v) // 2\n i = d[y]\n return i\n else:\n y = len(v) // 2\n j = (d[y] + d[y - 1]) // 2\n return j", "def find_median(v):\n v.sort()\n if len(v) % 2 != 0:\n l = 0\n r = len(v)\n mid = l + r // 2\n return v[mid]\n else:\n l = 0\n r = len(v) // 2\n return (v[r] + v[r - 1]) // 2", "def find_median(v):\n sorted_v = sorted(v)\n n = len(sorted_v)\n m = n // 2\n if n % 2 == 0:\n median = (sorted_v[m] + sorted_v[m - 1]) // 2\n else:\n median = sorted_v[m]\n return median", "def find_median(v):\n v.sort()\n if len(v) % 2 != 0:\n mid = len(v) / 2 - 0.5\n mid_index = v[int(mid)]\n else:\n mid_ind = v[int(len(v) / 2)]\n permid_ind = v[int(len(v) / 2 - 1)]\n mid_index = int((mid_ind + permid_ind) / 2)\n [3, 4, 5, 6, 7, 8]\n [0, 1, 2, 3, 4, 5]\n return mid_index", "def find_median(v):\n l = len(v)\n if l == 1:\n return v[0]\n else:\n median = int(l / 2)\n v.sort()\n if l & 1:\n return v[median]\n else:\n return int((v[median - 1] + v[median]) / 2)", "def find_median(v):\n d = sorted(v)\n if len(d) % 2 == 0:\n x = d[len(d) // 2] + d[len(d) // 2 - 1]\n return x // 2\n else:\n return d[len(d) // 2]", "def find_median(v):\n l = list(v)\n l.sort()\n n = len(v)\n m = n // 2\n if n % 2 != 0:\n return l[m]\n else:\n return (l[m] + l[m - 1]) // 2", "def find_median(v):\n v.sort()\n if len(v) % 2 != 0:\n left = 0\n right = len(v)\n mid = (left + right) // 2\n return v[mid]\n else:\n left = 0\n right = len(v) // 2\n return (v[right] + v[right - 1]) // 2", "def find_median(v):\n v.sort()\n length = len(v)\n if length % 2 == 1:\n result = v[int(length / 2)]\n else:\n position = int(length / 2)\n result = (v[position] + v[position - 1]) / 2\n return int(result)", "def find_median(v):\n v = sorted(v)\n n = len(v)\n if n % 2 == 0:\n return int((v[int(n / 2)] + v[int(n / 2) - 1]) / 2)\n return v[int(n / 2)]", "def find_median(v):\n if len(v) % 2 != 0:\n v.sort()\n median = v[len(v) // 2]\n return median\n elif len(v) == 2:\n a = sum(v)\n return a // len(v)\n else:\n v.sort()\n return (v[len(v) // 2] + v[len(v) // 2 - 1]) // 2", "def find_median(v):\n v.sort()\n if n % 2 != 0:\n return int(v[n // 2])\n return int((v[int((n - 1) / 2)] + v[int(n / 2)]) / 2.0)", "def find_median(v):\n l = len(v)\n v.sort()\n s = l % 2\n d = l // 2\n if s != 0:\n return v[d]\n else:\n return int((v[d - 1] + v[d]) / 2)", "def find_median(v):\n v.sort()\n length = len(v)\n z = length // 2\n if length % 2 == 1:\n return v[z]\n elif length % 2 == 0:\n xy = (v[z - 1] + v[z]) // 2\n return xy", "def find_median(v):\n z = sorted(v)\n n = len(z)\n if n % 2 != 0:\n return z[n // 2]\n else:\n return (z[n // 2 - 1] + z[n // 2]) // 2", "def find_median(v):\n v.sort()\n a = len(v)\n if len(v) % 2 == 1:\n return v[a // 2]\n else:\n n = a // 2\n return (v[n] + v[n - 1]) // 2", "import numpy as np\n\ndef find_median(v):\n m = np.median(v)\n return int(m)", "def find_median(v):\n z = sorted(v)\n length = len(z)\n middle = length // 2\n if length % 2 == 0:\n return (z[middle - 1] + z[middle]) // 2\n else:\n return z[middle]", "def find_median(arr):\n arr.sort()\n if n % 2 == 0:\n a = int(arr[int(n / 2)] + arr[int(n / 2 - 1)]) / 2\n return int(a)\n else:\n return arr[int(n / 2)]", "def find_median(v):\n v.sort()\n s = 0\n n = len(v)\n if n % 2 == 0:\n d = n // 2\n s = v[d] + v[d - 1]\n r = s // 2\n return r\n else:\n p = n // 2\n f = v[p]\n return f", "def find_median(v):\n a = sorted(v)\n if len(v) % 2 != 0:\n n = len(a) // 2\n return a[n]\n else:\n m = len(a) // 2\n ans = (a[m] + a[m - 1]) // 2\n return ans", "def find_median(v):\n arr = sorted(v)\n mid = len(arr) // 2\n if len(arr) % 2 == 0:\n mid = (arr[mid - 1] + arr[mid]) // 2\n return mid\n else:\n return arr[mid]", "def find_median(v):\n arr = sorted(v)\n n = len(v)\n return (arr[n // 2] + arr[(n - 1) // 2]) // 2", "import statistics\n\ndef find_median(v):\n return int(statistics.median(v))", "def find_median(v):\n l = len(v)\n v1 = sorted(v)\n if l % 2 == 0:\n median = (v1[l // 2 - 1] + v1[l // 2]) // 2\n else:\n median = v1[l // 2]\n return median", "def find_median(v):\n v.sort()\n l = len(v)\n k = l // 2\n n = int(l / 2)\n if l % 2 == 0:\n return int((v[n - 1] + v[n]) / 2)\n else:\n return v[k]", "import math\n\ndef find_median(v):\n v.sort()\n l = len(v)\n if l % 2 == 0:\n mid = (v[l // 2] + v[l // 2 - 1]) // 2\n else:\n mid = v[l // 2]\n return mid", "def find_median(v):\n c = sorted(v)\n N = len(c)\n if N % 2 == 1:\n return c[N // 2]\n else:\n sum = (c[N // 2] + c[N // 2 - 1]) / 2\n return int(sum)", "import statistics as sc\n\ndef find_median(v):\n a = sc.median(v)\n return int(a)", "import math\n\ndef find_median(v):\n n = len(v)\n v.sort()\n if n <= 1:\n return v[n - 1]\n return v[n // 2] if n % 2 != 0 else (v[n // 2 - 1] + v[n // 2]) // 2"], "starter_code": "def find_median(v):\n", "input_output": {"inputs": ["N = 5\narr[] = 90 100 78 89 67", "N = 4\narr[] = 56 67 30 79"], "outputs": ["89", "61"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical", "Divide and Conquer"], "name": null, "source": "geeksforgeeks", "tags": ["Divide and conquer", "Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/find-the-median0527/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n * log(n))", "entry_point": "find_median", "task_id": "TACO_lite/172", "example": [[[5, [90, 100, 78, 89, 67]], [4, [56, 67, 30, 79]]], [null, null]]} +{"requirement": "Given a rooted binary tree, return the lowest common ancestor of its deepest leaves.\nRecall that:\n\nThe node of a binary tree is a leaf if and only if it has no children\nThe depth of the root of the tree is 0, and if the depth of a node is d, the depth of each of its children\u00a0is\u00a0d+1.\nThe lowest common ancestor of a set S of nodes is the node A with the largest depth such that every node in S is in the subtree with root A.\n\n\u00a0\nExample 1:\nInput: root = [1,2,3]\nOutput: [1,2,3]\nExplanation: \nThe deepest leaves are the nodes with values 2 and 3.\nThe lowest common ancestor of these leaves is the node with value 1.\nThe answer returned is a TreeNode object (not an array) with serialization \"[1,2,3]\".\n\nExample 2:\nInput: root = [1,2,3,4]\nOutput: [4]\n\nExample 3:\nInput: root = [1,2,3,4,5]\nOutput: [2,4,5]\n\n\u00a0\nConstraints:\n\nThe given tree will have between 1 and 1000 nodes.\nEach node of the tree will have a distinct value between 1 and 1000.", "solutions": ["def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def lca(root=root):\n if root:\n (n1, d1) = lca(root.left)\n (n2, d2) = lca(root.right)\n if d1 == d2:\n return (root, d1 + 1)\n else:\n return (n1, 1 + d1) if d1 > d2 else (n2, 1 + d2)\n return (None, -1)\n return lca()[0]", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def traverse(node):\n if not node:\n return (0, None)\n (hl, lcal) = traverse(node.left)\n (hr, lcar) = traverse(node.right)\n if hl < hr:\n return (hr + 1, lcar)\n elif hl > hr:\n return (hl + 1, lcal)\n else:\n return (hl + 1, node)\n return traverse(root)[1]", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n if not root:\n return None\n paths = []\n\n def dfs(n, ps):\n nonlocal paths\n if not n:\n return\n if not n.left and (not n.right):\n paths.append((len(ps), ps + [n]))\n if n.left:\n dfs(n.left, ps + [n])\n if n.right:\n dfs(n.right, ps + [n])\n dfs(root, [])\n paths = sorted(paths, key=lambda x: x[0], reverse=True)\n longest = []\n (depth, path) = paths[0]\n for (d, p) in paths:\n if d == depth:\n longest.append(p)\n if len(longest) == 1:\n return path[-1]\n for i in range(len(path)):\n if any((path[i] != p[i] for p in longest)):\n break\n return path[i - 1]\n\ndef lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def helper(node):\n if not node:\n return (0, None)\n (h1, lca1) = helper(node.left)\n (h2, lca2) = helper(node.right)\n if h1 > h2:\n return (h1 + 1, lca1)\n if h2 > h1:\n return (h2 + 1, lca2)\n if h1 == h2:\n return (h1 + 1, node)\n return helper(root)[1]", "from typing import Tuple\n\ndef lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def lcaDeepestLeavesRecursive(node: TreeNode) -> Tuple[int, TreeNode]:\n if node is None:\n return (0, None)\n else:\n (depthL, nodeL) = lcaDeepestLeavesRecursive(node.left)\n (depthR, nodeR) = lcaDeepestLeavesRecursive(node.right)\n if depthL > depthR:\n return (depthL + 1, nodeL)\n elif depthL < depthR:\n return (depthR + 1, nodeR)\n else:\n return (depthL + 1, node)\n return lcaDeepestLeavesRecursive(root)[1]", "def __init__():\n self.max_depth = 0\n self.ancestor = None\n\ndef lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n if not root:\n return root\n self.dfs(root, 0)\n return self.ancestor\n\ndef dfs(node: TreeNode, curr_depth) -> int:\n (curr_deepest_L, curr_deepest_R) = (curr_depth, curr_depth)\n if not node.left and (not node.right):\n if curr_depth > self.max_depth:\n self.max_depth = curr_depth\n self.ancestor = node\n return curr_depth\n if node.left:\n curr_deepest_L = self.dfs(node.left, curr_depth + 1)\n if node.right:\n curr_deepest_R = self.dfs(node.right, curr_depth + 1)\n if curr_deepest_L == curr_deepest_R == self.max_depth:\n self.ancestor = node\n return max(curr_deepest_L, curr_deepest_R)", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def get_depth(root):\n if not root:\n return 0\n else:\n return max(get_depth(root.left), get_depth(root.right)) + 1\n max_depth = get_depth(root)\n\n def dfs(root, depth):\n if not root:\n return root\n if get_depth(root.left) == get_depth(root.right) == depth - 1:\n return root\n return dfs(root.left, depth - 1) or dfs(root.right, depth - 1)\n return dfs(root, max_depth)", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def traverse(root, level):\n if root:\n if not root.left and (not root.right):\n return (level, root)\n else:\n (left_level, left_lca) = traverse(root.left, level + 1)\n (right_level, right_lca) = traverse(root.right, level + 1)\n if left_level == right_level:\n return (left_level, root)\n elif left_level > right_level:\n return (left_level, left_lca)\n else:\n return (right_level, right_lca)\n return (float('-inf'), None)\n (deepest_level, lca) = traverse(root, 0)\n return lca", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n dic = {}\n explore = [root]\n nextlevel = []\n while explore:\n leaf = explore\n for node in explore:\n if node.left:\n dic[node.left] = node\n nextlevel.append(node.left)\n if node.right:\n dic[node.right] = node\n nextlevel.append(node.right)\n (explore, nextlevel) = (nextlevel, [])\n newleaf = set()\n while len(leaf) > 1:\n for node in leaf:\n newleaf.add(dic[node])\n (leaf, newleaf) = (newleaf, set())\n for res in leaf:\n return res", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n return self.helper(root)[0]\n\ndef helper(root):\n if not root:\n return (None, 0)\n (n1, l1) = self.helper(root.left)\n (n2, l2) = self.helper(root.right)\n if l1 > l2:\n return (n1, l1 + 1)\n elif l1 < l2:\n return (n2, l2 + 1)\n else:\n return (root, l1 + 1)", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n (node0, node1) = (None, None)\n q = [root]\n while q:\n (node0, node1) = (q[0], q[-1])\n q = [child for node in q for child in (node.left, node.right) if child]\n if node0 == node1:\n return node0\n result = None\n\n def lca(root: TreeNode) -> bool:\n nonlocal result\n if root is None:\n return False\n left = lca(root.left)\n right = lca(root.right)\n if left and right:\n result = root\n return (root == node0 or root == node1) or left or right\n lca(root)\n return result", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def getDepth(root):\n if not root:\n return 0\n return 1 + max(getDepth(root.left), getDepth(root.right))\n maxDepth = getDepth(root)\n\n def helper(root, d):\n nonlocal ans, maxDepth\n if not root:\n return 0\n left = helper(root.left, d + 1)\n right = helper(root.right, d + 1)\n if left == right and left == maxDepth - d - 1:\n ans = root\n return 1 + max(left, right)\n ans = None\n helper(root, 0)\n return ans", "from collections import defaultdict\n\ndef __init__():\n self.deepest = -1\n self.m = defaultdict(list)\n\ndef lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n self.dfs(root, 0)\n if self.deepest == -1:\n return None\n if len(self.m[self.deepest]) == 1:\n return self.m[self.deepest][0]\n return self.lca(root, self.m[self.deepest])\n\ndef dfs(node, level):\n if node is None:\n return\n if level not in self.m:\n self.m[level] = []\n self.deepest = max(self.deepest, level)\n self.m[level].append(node)\n self.dfs(node.left, level + 1)\n self.dfs(node.right, level + 1)\n\ndef lca(x, nodes):\n if x is None:\n return x\n for node in nodes:\n if node == x:\n return x\n left = self.lca(x.left, nodes)\n right = self.lca(x.right, nodes)\n if left is not None and right is not None:\n return x\n return left if left is not None else right", "def lcaDeepestLeaves(root: TreeNode) -> TreeNode:\n\n def height(root):\n if not root:\n return 0\n return 1 + max(height(root.left), height(root.right))\n if height(root.left) == height(root.right):\n return root\n elif height(root.left) > height(root.right):\n return self.lcaDeepestLeaves(root.left)\n return self.lcaDeepestLeaves(root.right)"], "starter_code": "def __init__(val=0, left=None, right=None):\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Binary Tree", "Breadth-First Search", "Depth-First Search", "Tree", "Hash Table"], "name": null, "source": "leetcode", "tags": ["Tree algorithms", "Data structures", "Graph traversal"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "__init__", "task_id": "TACO_lite/150", "example": [[[[1, 2, 3]], [[1, 2, 3, 4]], [[1, 2, 3, 4, 5]]], ["[1, 2, 3]", "[4]", "[2, 4, 5]"]]} +{"requirement": "In this Kata, you will be given an array of integers whose elements have both a negative and a positive value, except for one integer that is either only negative or only positive. Your task will be to find that integer. \n\nExamples:\n\n`[1, -1, 2, -2, 3] => 3`\n\n`3` has no matching negative appearance\n\n`[-3, 1, 2, 3, -1, -4, -2] => -4`\n\n`-4` has no matching positive appearance\n\n`[1, -1, 2, -2, 3, 3] => 3`\n\n(the only-positive or only-negative integer may appear more than once)\n\nGood luck!", "solutions": ["def solve(arr):\n return sum(set(arr))", "def solve(arr):\n for a in arr:\n if -a not in arr:\n return a", "def solve(a):\n return sum(set(a))", "def solve(arr):\n return [i for i in arr if -i not in arr][0]", "def solve(arr):\n for n in arr:\n if -n not in arr:\n return n", "def solve(arr):\n for x in arr:\n if x and -x not in arr:\n return x", "def solve(arr):\n for number in arr:\n if number * -1 in arr:\n pass\n else:\n return number", "def solve(arr):\n special_set = set(arr)\n n = 0\n for i in list(special_set):\n n += i\n return n", "def solve(arr):\n summa = 0\n dic = {}\n res = 0\n for i in arr:\n dic[i] = 0\n if -i in arr:\n dic[i] += 1\n else:\n dic[i] = 0\n for (key, value) in dic.items():\n if value == 0:\n res = key\n return res", "def solve(arr):\n for i in arr:\n if -1 * i not in arr:\n return i", "def solve(arr):\n result = 0\n for a in arr:\n if -a not in arr:\n return a", "def solve(arr):\n return [x for x in arr if not -x in arr][0]", "def solve(lst):\n return sum(set(lst))", "def solve(lst):\n for num in lst:\n if -num not in lst:\n return num", "def solve(arr):\n for num in arr:\n if not -num in arr:\n return num", "def solve(arr: list) -> int:\n for i in range(len(arr)):\n if -arr[i] not in arr:\n return arr[i]", "def solve(arr):\n nums = []\n unique = 0\n for i in arr:\n if -i in arr:\n nums.append(i)\n else:\n unique = i\n return unique", "def solve(arr):\n arr = set(arr)\n lst = list(map(abs, arr))\n one = 0\n for i in range(len(lst)):\n if lst.count(lst[i]) == 1:\n one = lst[i]\n if one in arr:\n return one\n else:\n a = '-' + str(one)\n return int(a)", "def solve(arr):\n result = []\n for i in arr:\n if arr.count(i) != arr.count(-i):\n result.append(i)\n return result[0]", "def solve(arr):\n ls = [arr[0]]\n for n in arr[1:]:\n if -n in ls:\n ls.pop(ls.index(-n))\n else:\n ls.append(n)\n return ls[0]", "def solve(arr):\n arr = sorted(arr)\n for i in range(len(arr) - 1):\n if arr[i] == arr[i + 1]:\n return arr[i]\n return sum(arr)", "def solve(arr):\n return [el for el in arr if -el not in arr][0]", "def solve(arr):\n positive = sorted([x for x in arr if x >= 0])\n negative = sorted([x for x in arr if x < 0], reverse=True)\n longer_index = len(positive) <= len(negative)\n longer = [positive, negative][longer_index]\n for i in [positive, negative][not longer_index]:\n longer.remove(-i)\n return longer[0]", "def solve(arr):\n rev = set((-x for x in arr))\n return [x for x in arr if abs(x) not in set(arr) or x not in rev][0]", "def solve(arr):\n for i in arr:\n reverse = -i\n if reverse not in arr:\n return i", "def solve(arr):\n for num in arr:\n if -num in arr:\n pass\n else:\n return num", "def solve(arr):\n a = [i for i in arr if arr.count(i) != arr.count(-i)]\n return a[0]", "def solve(arr):\n item = arr.pop()\n while -item in arr:\n arr.remove(-item)\n item = arr.pop()\n return item", "def solve(arr):\n for (index, value) in enumerate(arr):\n if value * -1 in arr:\n continue\n else:\n return value", "def solve(arr):\n for num in arr:\n if arr.count(num * -1) == 0:\n return num", "def solve(arr):\n values = set()\n removed_values = set()\n for value in arr:\n if value in removed_values:\n continue\n opposite = value * -1\n if opposite in values:\n values.remove(opposite)\n removed_values.add(value)\n removed_values.add(opposite)\n else:\n values.add(value)\n return list(values)[0]", "def solve(arr):\n result = arr[0]\n for i in range(len(arr)):\n pair = False\n for j in range(len(arr)):\n if arr[i] == -arr[j]:\n pair = True\n if not pair:\n result = arr[i]\n return result", "def solve(arr):\n positive_set = set()\n negative_set = set()\n for num in arr:\n if num > 0:\n positive_set.add(num)\n else:\n negative_set.add(-num)\n number = positive_set.symmetric_difference(negative_set)\n popped_number = number.pop()\n return popped_number if popped_number in arr else -popped_number", "def solve(arr):\n duplicates = [x for x in arr if arr.count(x) > 1]\n return duplicates[0] if duplicates else sum(arr)", "def solve(numbers):\n for x in numbers:\n if not -x in numbers:\n return x", "def solve(arr):\n while 1:\n number = arr[0]\n opposite_number = number * -1\n if opposite_number in arr:\n arr.remove(number)\n arr.remove(opposite_number)\n else:\n return arr[0]", "def solve(arr):\n for n in arr:\n if n < 0 and abs(n) not in arr:\n return n\n elif n > 0 and -n not in arr:\n return n", "def solve(arr):\n end = 0\n x = 0\n while end == 0:\n k = 1\n i = arr[x]\n for j in arr:\n if i == j * -1:\n k = 0\n if k == 1:\n ans = i\n end = 1\n x = x + 1\n return ans", "def match(vale, g):\n va = False\n for val in g:\n if val == -vale:\n va = True\n return va\n\ndef solve(g):\n m = []\n for val in g:\n if match(val, g) == False:\n m.append(val)\n return m[0]", "def solve(arr):\n cleaned = list(set(arr))\n for i in cleaned:\n if not -i in cleaned:\n return i", "def solve(a):\n for n in a:\n if -n in a:\n continue\n else:\n return n", "def solve(arr):\n return list(set(filter(lambda x: arr.count(x) != arr.count(-x), arr)))[0]", "def solve(arr):\n for i in range(0, len(arr)):\n if -arr[i] not in arr:\n return arr[i]", "def solve(arr):\n arr.sort()\n l = len(arr)\n neg = []\n pos = []\n for i in arr:\n if i < 0:\n neg.append(i)\n else:\n pos.append(i)\n if len(neg) > len(pos):\n for i in neg:\n if abs(i) not in pos:\n return i\n else:\n for i in pos:\n if -i not in neg:\n return i", "def solve(arr):\n return [value for value in arr if -value not in arr][0]", "def solve(arr):\n arr = set(arr)\n return next(filter(lambda i: not sum(arr) - i, arr))", "def solve(arr):\n arr = set(arr)\n for item in arr:\n if not sum(arr) - item:\n return item", "def solve(arr):\n return list(set((x for x in arr if x * -1 not in arr)))[0]", "def solve(arr):\n new_arr = [val for val in arr if not arr.count(-val)]\n return new_arr[0]", "def solve(arr):\n arr = set(arr)\n sum = 0\n for i in arr:\n sum += i\n return sum", "def solve(arr):\n for i in arr:\n if i and -i not in arr:\n return i", "def solve(arr):\n for i in arr:\n if -1 * i in arr:\n continue\n else:\n return i", "def solve(arr):\n a = 1\n for i in arr:\n if arr.count(i) > 1:\n a = arr.count(i)\n return sum(arr) / a", "def solve(arr):\n arr.sort()\n while len(arr) >= 1:\n if arr[0] < 0 and abs(arr[0]) in arr:\n x = abs(arr[0])\n arr.remove(arr[0])\n arr.remove(x)\n else:\n return arr[0]", "from collections import defaultdict\n\ndef solve(arr):\n d = defaultdict(int)\n for x in arr:\n d[abs(x)] += x\n return next((k if k in arr else -k for (k, v) in d.items() if v != 0))", "def solve(ar):\n x = len(ar)\n i = 0\n temp = 0\n while i < x:\n c = 0\n char = ar[i]\n while c <= x - 1:\n if char == -ar[c]:\n i += 1\n break\n c += 1\n else:\n temp = char\n return temp\n return temp", "def solve(ar):\n for item in ar:\n if -item not in ar:\n return item", "def solve(arr):\n pos = set([x for x in arr if x > 0])\n neg = set([abs(x) for x in list([x for x in arr if x < 0])])\n if pos.issubset(neg):\n return (neg - pos).pop() * -1\n else:\n return (pos - neg).pop()", "def solve(arr):\n for (idx, num) in enumerate(arr):\n if num in arr[:idx] + arr[idx + 1:]:\n return arr[idx]\n return sum(arr)", "def solve(arr):\n pos = []\n neg = []\n for i in arr:\n if i < 0:\n neg.append(i)\n else:\n pos.append(i)\n for i in neg:\n if abs(i) not in pos:\n return i\n break\n for j in pos:\n if -j not in neg:\n return j\n break", "def solve(arr):\n for (i, v) in enumerate(arr):\n isTrue = False\n for (k, kv) in enumerate(arr):\n if i == k:\n continue\n if v == arr[k] * -1:\n isTrue = True\n break\n if isTrue == False:\n return v", "def solve(arr):\n return sum(arr) / arr.count(max(arr, key=arr.count))", "def solve(arr):\n parr = []\n narr = []\n for i in arr:\n if i < 0:\n narr.append(i)\n else:\n parr.append(i)\n res = 0\n for a in narr:\n if abs(a) not in parr:\n res = a\n for b in parr:\n if b * -1 not in narr:\n res = b\n return res", "def solve(arr):\n check = []\n for i in arr:\n if -i not in arr:\n return i", "from collections import Counter\n\ndef solve(arr):\n return sum(arr) / Counter(arr).most_common(1)[0][1]", "def solve(arr):\n abs_arr = [abs(n) for n in arr]\n for n in set(abs_arr):\n if not (n in arr and -n in arr):\n return arr[abs_arr.index(n)]", "def solve(arr):\n for i in arr:\n (m, s) = (0, -i)\n for j in arr:\n if s == j:\n m = 1\n if m == 0:\n return i", "def solve(arr):\n for num in arr:\n if num > 0 and -num not in arr:\n return num\n elif num < 0 and num - num * 2 not in arr:\n return num", "def solve(arr):\n dict = {}\n for a in arr:\n if abs(a) not in dict:\n dict[abs(a)] = a\n elif dict[abs(a)] == a:\n return a\n break\n else:\n dict[abs(a)] = a + dict[abs(a)]\n for v in list(dict.values()):\n if v != 0:\n return v", "def solve(arr):\n newArr = []\n for x in arr:\n if x * -1 not in arr:\n return x", "def solve(arr):\n negative = set([i for i in arr if i < 0])\n positive = set([i for i in arr if i > 0])\n res = None\n for i in negative:\n if i * -1 not in positive:\n res = i\n for i in positive:\n if i * -1 not in negative:\n res = i\n return res", "def solve(arr):\n for i in range(len(arr)):\n count = 0\n if arr.count(arr[i]) > 1:\n return arr[i]\n for j in range(len(arr)):\n if arr[i] == -arr[j]:\n count += 1\n if count != 1:\n return arr[i]", "from collections import Counter\n\ndef solve(arr):\n c = Counter(arr)\n for (k, v) in c.items():\n if k * -1 not in c.keys():\n return k", "import collections\n\ndef solve(arr):\n count = collections.Counter(arr)\n for number in arr:\n if not count[-number]:\n return number", "def solve(arr):\n for val in arr:\n if -1 * val not in arr:\n return val", "def solve(arr):\n sum = 0\n times = 0\n ele = {}\n for i in arr:\n if i in ele:\n ele[i] = ele[i] + i\n else:\n ele[i] = i\n sum = sum + i\n for (k, v) in ele.items():\n if v == sum:\n if -k not in arr:\n times = sum / k\n if times > 1:\n sum = sum / times\n return sum", "def solve(arr):\n for num in arr:\n if arr.count(num) > arr.count(-num):\n return num\n elif arr.count(-num) > arr.count(num):\n return -num", "def solve(arr):\n for (i, el) in enumerate(arr):\n if arr.count(el * -1) == 0:\n return el", "def solve(arr):\n return sum(dict.fromkeys(arr))", "def solve(arr):\n for i in arr:\n n = 0\n for j in arr:\n n += 1\n if i + j == 0:\n break\n if len(arr) == n and i + j != 0:\n return i", "def solve(arr):\n while len(set(arr)) > 1:\n for i in range(len(arr) - 1):\n if arr.count(-arr[i]):\n arr.remove(-arr[i])\n arr.remove(arr[i])\n break\n return list(set(arr))[0]", "def solve(arr):\n for i in range(0, len(arr)):\n num = arr[i]\n reversenumber = -num\n found = False\n for index in range(0, len(arr)):\n if i == index:\n continue\n if reversenumber == arr[index]:\n found = True\n break\n if found == False:\n return num"], "starter_code": "def solve(arr):\n", "input_output": {"fn_name": "solve", "inputs": [[[1, -1, 2, -2, 3]], [[-3, 1, 2, 3, -1, -4, -2]], [[1, -1, 2, -2, 3, 3]], [[-110, 110, -38, -38, -62, 62, -38, -38, -38]], [[-9, -105, -9, -9, -9, -9, 105]]], "outputs": [[3], [-4], [3], [-38], [-9]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms"], "name": null, "source": "codewars", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5a092d9e46d843b9db000064", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/133", "example": [[[[1, -1, 2, -2, 3]], [[-3, 1, 2, 3, -1, -4, -2]], [[1, -1, 2, -2, 3, 3]]], ["3", "-4", "3"]]} +{"requirement": "Take a sentence (string) and reverse each word in the sentence. Do not reverse the order of the words, just the letters in each word.\n\nIf there is punctuation, it should be interpreted as a regular character; no special rules.\n\nIf there is spacing before/after the input string, leave them there.\n\nString will not be empty.\n\n## Examples\n\n```\n\"Hi mom\" => \"iH mom\"\n\" A fun little challenge! \" => \" A nuf elttil !egnellahc \"\n```", "solutions": ["def reverser(sentence):\n return ' '.join((i[::-1] for i in sentence.split(' ')))", "def reverser(s):\n return ' '.join((w[::-1] for w in s.split(' ')))", "import re\n\ndef reverser(sentence):\n return ''.join((w[::-1] if ' ' not in w else w for w in re.findall('(?:\\\\w+)|(?:\\\\s+)', sentence)))", "from re import compile\nr = compile('(\\\\W)')\n\ndef reverser(sentence: str) -> str:\n return ''.join((w[::-1] for w in r.split(sentence)))", "def reverser(sentence):\n emt = ' '\n split_it = sentence.split(' ')\n for word in split_it:\n emt += word[::-1] + ' '\n return emt[1:-1]", "import re\n\ndef reverser(sentence):\n return ''.join((i[::-1] for i in re.split('(\\\\s+)', sentence)))", "def reverser(sentence):\n newsent = sentence.split(' ')\n rnsent = [i[::-1] for i in newsent]\n s = ' '\n s = s.join(rnsent)\n return s", "def reverser(sentence):\n text = sentence.split(' ')\n ans = []\n for i in text:\n ans.append(i[::-1])\n return ' '.join(ans)", "def reverser(sentence):\n ans = ''\n word = ''\n for letter in sentence:\n if letter == ' ':\n ans = ans + word[::-1] + letter\n word = ''\n else:\n word = word + letter\n return ans + word[::-1]", "reverser = lambda x: ' '.join([i[::-1] for i in x.split(' ')])"], "starter_code": "def reverser(sentence):\n", "input_output": {"fn_name": "reverser", "inputs": [["How now brown cow"], ["racecar"], ["Hi mom"], [" "], [" "], ["go away"], ["I like noodles"], ["The red pen wrote on the wall"], ["Green trucks drive fast"], ["Pink trucks drive slow"]], "outputs": [["woH won nworb woc"], ["racecar"], ["iH mom"], [" "], [" "], ["og yawa"], ["I ekil seldoon"], ["ehT der nep etorw no eht llaw"], ["neerG skcurt evird tsaf"], ["kniP skcurt evird wols"]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/57ebdf944cde58f973000405", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "reverser", "task_id": "TACO_lite/149", "example": [[["Hi mom"], [" A fun little challenge! "]], ["iH mom", " A nuf elttil !egnellahc "]]} +{"requirement": "Some new cashiers started to work at your restaurant. \n\nThey are good at taking orders, but they don't know how to capitalize words, or use a space bar! \n\nAll the orders they create look something like this:\n\n`\"milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza\"`\n\nThe kitchen staff are threatening to quit, because of how difficult it is to read the orders. \n\nTheir preference is to get the orders as a nice clean string with spaces and capitals like so:\n\n`\"Burger Fries Chicken Pizza Pizza Pizza Sandwich Milkshake Milkshake Coke\"`\n\nThe kitchen staff expect the items to be in the same order as they appear in the menu. \n\nThe menu items are fairly simple, there is no overlap in the names of the items:\n```\n1. Burger\n2. Fries\n3. Chicken\n4. Pizza\n5. Sandwich\n6. Onionrings\n7. Milkshake\n8. Coke\n```", "solutions": ["def get_order(order):\n menu = ['burger', 'fries', 'chicken', 'pizza', 'sandwich', 'onionrings', 'milkshake', 'coke']\n clean_order = ''\n for i in menu:\n clean_order += (i.capitalize() + ' ') * order.count(i)\n return clean_order[:-1]", "MENU = ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke']\n\ndef get_order(order):\n result = []\n for item in MENU:\n result.extend([item for _ in range(order.count(item.lower()))])\n return ' '.join(result)", "menu = 'Burger Fries Chicken Pizza Sandwich Onionrings Milkshake Coke'.split()\n\ndef get_order(order):\n return ' '.join((item for item in menu for _ in range(order.count(item.lower()))))", "def get_order(order):\n output = ''\n while order != '':\n if output == '':\n if order.find('burger') != -1:\n output += 'Burger'\n order = order.replace('burger', '', 1)\n elif order.find('fries') != -1:\n output += 'Fries'\n order = order.replace('fries', '', 1)\n elif order.find('chicken') != -1:\n output += 'Chicken'\n order = order.replace('chicken', '', 1)\n elif order.find('pizza') != -1:\n output += 'Pizza'\n order = order.replace('pizza', '', 1)\n elif order.find('sandwich') != -1:\n output += 'Sandwich'\n order = order.replace('sandwich', '', 1)\n elif order.find('onionrings') != -1:\n output += 'Onionrings'\n order = order.replace('onionrings', '', 1)\n elif order.find('milkshake') != -1:\n output += 'Milkshake'\n order = order.replace('milkshake', '', 1)\n elif order.find('coke') != -1:\n output += 'Coke'\n order = order.replace('coke', '', 1)\n elif output != '':\n if order.find('burger') != -1:\n output += ' Burger'\n order = order.replace('burger', '', 1)\n elif order.find('fries') != -1:\n output += ' Fries'\n order = order.replace('fries', '', 1)\n elif order.find('chicken') != -1:\n output += ' Chicken'\n order = order.replace('chicken', '', 1)\n elif order.find('pizza') != -1:\n output += ' Pizza'\n order = order.replace('pizza', '', 1)\n elif order.find('sandwich') != -1:\n output += ' Sandwich'\n order = order.replace('sandwich', '', 1)\n elif order.find('onionrings') != -1:\n output += ' Onionrings'\n order = order.replace('onionrings', '', 1)\n elif order.find('milkshake') != -1:\n output += ' Milkshake'\n order = order.replace('milkshake', '', 1)\n elif order.find('coke') != -1:\n output += ' Coke'\n order = order.replace('coke', '', 1)\n return output", "import re\nMENU = {v: i for (i, v) in enumerate('Burger Fries Chicken Pizza Sandwich Onionrings Milkshake Coke'.split())}\nREG_CMD = re.compile('|'.join(MENU), flags=re.I)\n\ndef get_order(order):\n return ' '.join(sorted(map(str.title, REG_CMD.findall(order)), key=MENU.get))", "from re import findall\n\ndef get_order(order):\n menu = ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke']\n return ' '.join(filter(None, (' '.join(findall(item.lower(), order)).title() for item in menu)))", "def get_order(order):\n (menu, Menu) = (['burger', 'fries', 'chicken', 'pizza', 'sandwich', 'onionrings', 'milkshake', 'coke'], ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke'])\n (str, num) = ('', 0)\n (lst, lst2, result) = ([], [], [])\n for letter in order:\n str += letter\n if str in menu:\n lst.append(str)\n str = ''\n for word in lst:\n lst2.append(word.capitalize())\n for counter in range(0, 8):\n for word in lst2:\n if word == Menu[counter]:\n result.append(word)\n return ' '.join(result)", "import re\nMENU = ['burger', 'fries', 'chicken', 'pizza', 'sandwich', 'onionrings', 'milkshake', 'coke']\n\ndef get_order(order):\n res = []\n for item in MENU:\n res.extend(re.findall(item, order))\n return ' '.join([item.capitalize() for item in res])", "get_order = lambda order: ''.join([item * order.count(item[1:].lower()) for item in ' Burger, Fries, Chicken, Pizza, Sandwich, Onionrings, Milkshake, Coke'.split(',')])[1:]", "def get_order(order):\n menu = ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke']\n return ''.join([(item + ' ') * order.count(item.lower()) for item in menu]).strip()", "def get_order(order):\n word = ''\n list = ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke']\n for i in list:\n word = word + (' ' + i) * order.count(i.lower())\n return word.strip()"], "starter_code": "def get_order(order):\n", "input_output": {"fn_name": "get_order", "inputs": [["burgerfriesfriesfriesfriesfriespizzasandwichcokefriesburger"]], "outputs": [["Burger Burger Fries Fries Fries Fries Fries Fries Pizza Sandwich Coke"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5d23d89906f92a00267bb83d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "get_order", "task_id": "TACO_lite/178", "example": [[["milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"]], ["Burger Fries Chicken Pizza Pizza Pizza Sandwich Milkshake Milkshake Coke"]]} +{"requirement": "Given an integer array arr, you should partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray.\nReturn the largest sum of the given array after partitioning.\n\u00a0\nExample 1:\nInput: arr = [1,15,7,9,2,5,10], k = 3\nOutput: 84\nExplanation: arr becomes [15,15,15,9,10,10,10]\n\nExample 2:\nInput: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4\nOutput: 83\n\nExample 3:\nInput: arr = [1], k = 1\nOutput: 1\n\n\u00a0\nConstraints:\n\n1 <= arr.length <= 500\n0 <= arr[i] <= 109\n1 <= k <= arr.length", "solutions": ["def maxsumafterpartitioning(arr, k):\n res = [0]\n for (idx, val) in enumerate(arr):\n (max_val, cur_val) = (0, 0)\n for i in range(max(0, idx - k + 1), idx + 1)[::-1]:\n if arr[i] > max_val:\n max_val = arr[i]\n if res[i] + (idx - i + 1) * max_val > cur_val:\n cur_val = res[i] + (idx - i + 1) * max_val\n res.append(cur_val)\n return res[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n ans = [0]\n for (r, n) in enumerate(A):\n (maxVal, curVal) = (0, 0)\n for l in range(max(0, r - K + 1), r + 1)[::-1]:\n if A[l] > maxVal:\n maxVal = A[l]\n if ans[l] + (r - l + 1) * maxVal > curVal:\n curVal = ans[l] + (r - l + 1) * maxVal\n ans.append(curVal)\n return ans[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n dp = [A[0]]\n for i in range(1, len(A)):\n max_partition_sum = A[i] + dp[-1]\n max_element = A[i]\n end = i - K\n if end < -1:\n end = -1\n for j in range(i - 1, end, -1):\n if A[j] > max_element:\n max_element = A[j]\n partition_sum = (i - j + 1) * max_element\n if j > 0:\n partition_sum += dp[j - 1]\n if partition_sum > max_partition_sum:\n max_partition_sum = partition_sum\n dp.append(max_partition_sum)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n return self.dp(arr, 0, k, {})\n\ndef dp(arr, i, k, hashmap):\n if i >= len(arr):\n return 0\n if i in hashmap:\n return hashmap[i]\n largest = 0\n ans = 0\n for idx in range(k):\n if idx + i >= len(arr):\n break\n largest = max(largest, arr[i + idx])\n ans = max(ans, largest * (idx + 1) + self.dp(arr, i + idx + 1, k, hashmap))\n hashmap[i] = ans\n return ans", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n return self.recur(arr, len(arr) - 1, k, {})\n\ndef recur(arr, index, k, hashMap):\n if index < 0:\n return 0\n if index in hashMap:\n return hashMap[index]\n result = 0\n maxV = 0\n for i in range(k):\n if index - i < 0:\n continue\n maxV = max(maxV, arr[index - i])\n result = max(result, maxV * (i + 1) + self.recur(arr, index - i - 1, k, hashMap))\n hashMap[index] = result\n return result", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n self.dp = {}\n\n def recur(index, arr, k):\n if index >= len(arr):\n return 0\n if index in self.dp:\n return self.dp[index]\n maxi = 0\n res = 0\n for i in range(k):\n if index + i < len(arr):\n maxi = max(maxi, arr[index + i])\n res = max(res, maxi * (i + 1) + recur(index + i + 1, arr, k))\n self.dp[index] = res\n return res\n return recur(0, arr, k)", "def util(i, n, A, K, d):\n if i >= n:\n return 0\n if i not in d:\n count = 0\n ma = A[i]\n temp = -1\n while i + count < n and count <= K - 1:\n if A[i + count] > ma:\n ma = A[i + count]\n nex = self.util(i + count + 1, n, A, K, d)\n if (count + 1) * ma + nex > temp:\n temp = (count + 1) * ma + nex\n count += 1\n d[i] = temp\n return d[i]\n\ndef maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n d = {}\n return self.util(0, n, A, K, d)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n visited = {}\n\n def recurse(index):\n if index >= len(A):\n return 0\n if index in visited:\n return visited[index]\n mxx = 0\n ans = 0\n for i in range(K):\n if index + i < len(A):\n mxx = max(mxx, A[i + index])\n ans = max(ans, mxx * (i + 1) + recurse(i + index + 1))\n visited[index] = ans\n return ans\n return recurse(0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0] * len(arr)\n dp[0] = arr[0]\n max_value = arr[0]\n max_sum = arr[0]\n for i in range(1, k):\n max_value = max(max_value, arr[i])\n dp[i] = max_value * (i + 1)\n for i in range(k, len(arr)):\n max_value = 0\n for j in range(k):\n max_value = max(max_value, arr[i - j])\n dp[i] = max(dp[i], dp[i - j - 1] + max_value * (j + 1))\n return dp[-1]", "from collections import deque\n\ndef maxsumafterpartitioning(A: List[int], K: int) -> int:\n dp = deque([0 for i in range(K)])\n for i in range(1, len(A) + 1):\n (maxA, maxP) = (float('-inf'), float('-inf'))\n for j in range(1, min(K + 1, i + 1)):\n maxA = max(maxA, A[i - j])\n maxP = max(maxP, dp[-j] + j * maxA)\n dp.popleft()\n dp.append(maxP)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n inf = 1061109567\n dp = [[(-inf, -inf) for _ in range(k + 1)] for _ in range(2)]\n last_max = 0\n dp[0][0] = (0, 0)\n for i in range(1, len(arr) + 1):\n for j in range(1, k + 1):\n if j == 1:\n dp[i % 2][j] = (last_max + arr[i - 1], arr[i - 1])\n last_max = dp[i % 2][j][0]\n elif i >= j:\n (last_s, last_n) = dp[(i - 1) % 2][j - 1]\n n = max(last_n, arr[i - 1])\n s = last_s - last_n * (j - 1) + n * j\n dp[i % 2][j] = (s, n)\n last_max = max(last_max, s)\n return last_max", "def maxsumafterpartitioning(A, K):\n N = len(A)\n dp = [0] * (N + 1)\n for i in range(N):\n curMax = 0\n for k in range(1, min(K, i + 1) + 1):\n curMax = max(curMax, A[i - k + 1])\n dp[i] = max(dp[i], dp[i - k] + curMax * k)\n return dp[N - 1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n N = len(A)\n if K == 1 or N == 1:\n return sum(A)\n dp = [0] * (N + 1)\n dp[0] = 0\n for i in range(N):\n mv = A[i]\n dp[i + 1] = dp[i] + A[i]\n for j in range(1, min(i + 1, K)):\n mv = max(mv, A[i - j])\n dp[i + 1] = max(dp[i + 1], dp[i - j] + (j + 1) * mv)\n return dp[N]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n size = len(A)\n if K == 1:\n return sum(A)\n dp = [0] * (size + 1)\n for i in range(size):\n cur_max = A[i]\n block_size = 1\n while block_size <= K and i - block_size + 1 >= 0:\n cur_max = max(cur_max, A[i - block_size + 1])\n dp[i + 1] = max(dp[i + 1], dp[i - block_size + 1] + block_size * cur_max)\n block_size += 1\n return dp[size]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [[-1] * (n + 1) for _ in range(n + 1)]\n\n def maxsum(i=0):\n if i >= n:\n return 0\n elif dp[i][n] != -1:\n return dp[i][n]\n else:\n mx = 0\n for j in range(i, min(i + k, n)):\n mx = max(arr[j], mx)\n dp[i][j] = mx * (j - i + 1)\n dp[i][n] = max(dp[i][n], dp[i][j] + maxsum(j + 1))\n return dp[i][n]\n return maxsum()", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0] * (n := len(arr))\n dp[0] = curr_max = arr[0]\n for i in range(1, k):\n curr_max = max(curr_max, arr[i])\n dp[i] = (i + 1) * curr_max\n for i in range(k, n):\n curr_max = arr[i]\n for j in range(k):\n curr_max = max(curr_max, arr[i - j])\n dp[i] = max(dp[i], dp[i - j - 1] + (j + 1) * curr_max)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], K: int) -> int:\n n = len(arr)\n dp = [0 for _ in range(n + 1)]\n for i in range(n):\n currMax = 0\n for k in range(1, min(K, i + 1) + 1):\n currMax = max(currMax, arr[i - k + 1])\n dp[i] = max(dp[i], dp[i - k] + currMax * k)\n return dp[n - 1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n if arr is None or len(arr) == 0:\n return 0\n dp = [0 for _ in range(len(arr))]\n for i in range(len(arr)):\n max_elem = arr[i]\n j = 1\n while j <= k and i - j + 1 >= 0:\n max_elem = max(max_elem, arr[i - j + 1])\n if i - j >= 0:\n dp[i] = max(dp[i], max_elem * j + dp[i - j])\n else:\n dp[i] = max(dp[i], max_elem * j)\n j += 1\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n dp = [0] * (n + 1)\n for (i, a) in enumerate(A):\n r = a\n for j in range(1, K + 1):\n r = max(r, A[i - j + 1] if i - j + 1 >= 0 else float('-inf'))\n if i - j + 1 >= 0:\n dp[i + 1] = max(dp[i + 1], dp[i - j + 1] + r * j)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n self.dp = [-1 for i in range(n)]\n\n def helper(pos: int) -> int:\n if pos >= n:\n return 0\n if self.dp[pos] != -1:\n return self.dp[pos]\n current_max = arr[pos]\n ret = arr[pos] + helper(pos + 1)\n for i in range(1, k):\n pos2 = pos + i\n if pos2 >= n:\n break\n current_max = max(current_max, arr[pos2])\n ret = max(ret, current_max * (i + 1) + helper(pos2 + 1))\n self.dp[pos] = ret\n return ret\n return helper(0)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n maxSum = [0] * n\n for i in range(-1, -K - 1, -1):\n maxSum[i] = max(A[i:]) * -i\n for i in range(n - K - 1, -1, -1):\n ms = 0\n for k in range(1, K + 1):\n ms = max(ms, max(A[i:i + k]) * k + maxSum[i + k])\n maxSum[i] = ms\n return maxSum[0]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n\n def helper(index, start, mx):\n if index == len(arr):\n return (index - start) * mx\n if index - start + 1 <= k:\n return max(helper(index + 1, start, max(arr[index], mx)), (index - start) * mx + helper(index + 1, index, arr[index]))\n return (index - start) * mx + helper(index + 1, index, arr[index])\n return helper(0, 0, arr[0])", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n dp = [0] * len(A)\n for i in range(K):\n dp[i] = max(A[:i + 1]) * (i + 1)\n for i in range(K, len(A)):\n dp[i] = max([dp[i - j] + max(A[i - j + 1:i + 1]) * j for j in range(1, K + 1)])\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [[(0, 0)] * k for _ in range(len(arr) + 1)]\n for i in range(1, len(arr) + 1):\n for j in range(min(i, k)):\n if j == 0:\n dp[i][j] = max(((dp[i - 1][m][0] + arr[i - 1], arr[i - 1]) for m in range(min(i, k))))\n else:\n new_max = max(dp[i - 1][j - 1][1], arr[i - 1])\n dp[i][j] = (dp[i - 1][j - 1][0] - j * dp[i - 1][j - 1][1] + new_max * (j + 1), new_max)\n return max(dp[-1])[0]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0] * n\n for i in range(n - 1, -1, -1):\n curr_max = arr[i]\n for j in range(0, k):\n index = min(n - 1, i + j)\n curr_max = max(curr_max, arr[index])\n if i + j + 1 >= n:\n dp[i] = (n - i) * curr_max\n else:\n dp[i] = max(dp[i], dp[i + j + 1] + (j + 1) * curr_max)\n return dp[0]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n if not arr:\n return 0\n local_max = {(idx, idx + 1): arr[idx] for idx in range(len(arr))}\n for l in range(2, k + 1):\n for start in range(len(arr) - l + 1):\n local_max[start, start + l] = max(local_max[start, start + l - 1], local_max[start + 1, start + l])\n f = [0]\n for end in range(1, len(arr) + 1):\n _local = 0\n for start in range(max(0, end - k), end):\n _local = max(f[start] + local_max[start, end] * (end - start), _local)\n f.append(_local)\n return f[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n memo = [0] * n\n for i in range(n):\n if i < k:\n memo[i] = (i + 1) * max(arr[:i + 1])\n else:\n memo[i] = max((memo[i - j - 1] + (j + 1) * max(arr[i - j:i + 1]) for j in range(k)))\n return memo[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n length = len(arr)\n dp = [0] * (length + 1)\n maxval = [[0] * length for _ in range(length)]\n for i in range(length):\n for j in range(i, length):\n if i == j:\n maxval[i][j] = arr[i]\n else:\n maxval[i][j] = max(maxval[i][j - 1], arr[j])\n for i in range(1, length + 1):\n temp = 0\n for t in range(1, k + 1):\n temp = max(temp, dp[i - t] + maxval[i - t][i - 1] * t)\n dp[i] = temp\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n\n def dfs(i, j, max_num=0):\n if i == -1:\n return max_num * j\n if opt[i][j] == -1:\n (a, b) = (0, 0)\n if j < K:\n a = dfs(i - 1, j + 1, max(max_num, A[i]))\n b = j * max_num + dfs(i - 1, 1, A[i])\n opt[i][j] = max(a, b)\n return opt[i][j]\n n = len(A)\n opt = [[-1] * (K + 1) for _ in range(n)]\n return dfs(n - 1, 0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n l = len(arr)\n results = [0] * l\n for (idx, num) in enumerate(arr):\n if idx < k:\n results[idx] = max(arr[:idx + 1]) * (idx + 1)\n else:\n res = 0\n for i in range(1, k + 1):\n start = idx - i\n tmp = results[start] + max(arr[start + 1:idx + 1]) * i\n res = max(res, tmp)\n results[idx] = res\n return results[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n max_sums = [0] * len(arr)\n for i in range(len(arr)):\n if i <= k - 1:\n max_sums[i] = (i + 1) * max(arr[:i + 1])\n else:\n res = 0\n for j in range(1, k + 1):\n first = max_sums[i - j]\n second = j * max(arr[i - j + 1:i + 1])\n res = max(res, first + second)\n max_sums[i] = res\n return max_sums[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n maxx = arr[0]\n dp = []\n for (i, _) in enumerate(arr[:k]):\n maxx = max(arr[i], maxx)\n dp.append(maxx * (i + 1))\n for (i, _) in enumerate(arr[k:]):\n i += k\n max_sum = 0\n for j in range(k):\n max_sum = max(max_sum, dp[i - j - 1] + max(arr[i - j:i + 1]) * (j + 1))\n dp.append(max_sum)\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n N = len(A)\n dp = [float('-inf')] * (N + 1)\n for i in range(1, N + 1):\n if i <= K:\n dp[i] = max(A[:i]) * i\n else:\n for j in range(1, K + 1):\n dp[i] = max(dp[i], dp[i - j] + max(A[i - j:i]) * j)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n M = [0 for i in range(len(arr))]\n M[0] = arr[0]\n for i in range(1, len(arr)):\n if i < k:\n M[i] = max(arr[:i + 1]) * (i + 1)\n else:\n for j in range(1, min(k + 1, i + 1)):\n M[i] = max(M[i], M[i - j] + max(arr[i - j + 1:i + 1]) * j)\n return M[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n rec = {}\n\n def helper(idx):\n if idx in rec:\n return rec[idx]\n if len(arr) - idx <= k:\n temp = max(arr[idx:]) * (len(arr) - idx)\n rec[idx] = temp\n return temp\n pre_max = float('-inf')\n temp = float('-inf')\n for j in range(idx, min(idx + k, len(arr))):\n pre_max = max(pre_max, arr[j])\n temp = max(temp, pre_max * (j - idx + 1) + helper(j + 1))\n rec[idx] = temp\n return temp\n return helper(0)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n\n def maxSum(i, mem):\n if i in mem:\n return mem[i]\n if len(A) - i <= K:\n mem[i] = max(A[i:]) * (len(A) - i)\n return mem[i]\n ans = -float('inf')\n for j in range(i + 1, i + 1 + K):\n if j > len(A):\n break\n ans = max(ans, max(A[i:j]) * (j - i) + maxSum(j, mem))\n mem[i] = ans\n return mem[i]\n mem = {}\n return maxSum(0, mem)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n largest_sums = []\n for i in range(len(A)):\n if i < K:\n largest_sums.append(max(A[:i + 1]) * (i + 1))\n continue\n max_sum = 0\n for j in range(K):\n if i - (j + 1) < 0:\n continue\n cur_sum = largest_sums[i - j - 1] + max(A[i - j:i + 1]) * (j + 1)\n if cur_sum > max_sum:\n max_sum = cur_sum\n largest_sums.append(max_sum)\n return largest_sums[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n aLen = len(A)\n dp = {}\n\n def helper(i0):\n if i0 in dp:\n return dp[i0]\n if aLen - i0 <= K:\n dp[i0] = max(A[i0:]) * (aLen - i0)\n return dp[i0]\n subAns = 0\n thisMax = A[i0]\n for ki in range(1, K + 1):\n thisMax = max(thisMax, A[i0 + ki - 1])\n subAns = max(subAns, thisMax * ki + helper(i0 + ki))\n dp[i0] = subAns\n return subAns\n return helper(0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n maxes = [[None for _ in range(n)] for _ in range(n)]\n for i in range(n):\n maxes[i][i] = arr[i]\n for i in range(n):\n for j in range(i + 1, n):\n maxes[i][j] = max(arr[j], maxes[i][j - 1])\n dp = [None for _ in range(n + 1)]\n dp[n] = 0\n for i in range(n - 1, -1, -1):\n m = float('-inf')\n for j in range(min(n - i, k)):\n m = max(m, (j + 1) * maxes[i][min(n - 1, i + j)] + dp[min(n, i + j + 1)])\n dp[i] = m\n return dp[0]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n\n def helper(index, start, mx):\n key = (index, start, mx)\n if key in d:\n return d[key]\n if index == len(arr):\n return (index - start) * mx\n if index - start + 1 <= k:\n d[key] = max(helper(index + 1, start, max(arr[index], mx)), (index - start) * mx + helper(index + 1, index, arr[index]))\n return d[key]\n d[key] = (index - start) * mx + helper(index + 1, index, arr[index])\n return d[key]\n d = dict()\n return helper(0, 0, arr[0])", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n\n def checkSum(i, j, k):\n if j - i <= k:\n return max(A[i:j]) * (j - i)\n else:\n best = 0\n for nk in range(1, K + 1):\n best = max(best, checkSum(i, i + nk, K) + checkSum(i + nk, j, K))\n return best\n return checkSum(0, len(A), K)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n N = len(A)\n arr = [[(0, 0)] * (K + 1) for _ in range(N)]\n prev = 0\n for i in range(N):\n arr[i][1] = (A[i] + prev, A[i])\n prev += A[i]\n for j in range(2, min(i + 2, K + 1)):\n mx = max(arr[i - 1][j - 1][1], A[i])\n s = arr[i - 1][j - 1][0] - arr[i - 1][j - 1][1] * (j - 1) + mx * j\n arr[i][j] = (s, mx)\n prev = max(prev, s)\n return max((arr[-1][k][0] for k in range(1, K + 1)))", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n if not A:\n return 0\n N = len(A)\n if K == N:\n return N * max(A)\n dp = [0 for i in range(N)]\n for i in range(K):\n dp[i] = max(A[:i + 1]) * (i + 1)\n for i in range(K, N):\n a = max(A[i - K + 1:i + 1])\n dp[i] = max([dp[i - j] + j * max(A[i - j + 1:i + 1]) for j in range(1, K + 1)])\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n\n def help(A, K):\n n = len(A)\n if K == 1:\n return sum(A)\n if K >= n:\n return n * max(A)\n cMax = [A[0]]\n for i in range(1, K):\n cMax.append(max(cMax[-1], A[i]))\n return max(((i + 1) * cMax[i] + help(A[i + 1:], K) for i in range(K)))\n return help(tuple(A), K)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n grid = [0] * len(arr)\n for i in range(len(arr) - 1, -1, -1):\n if len(arr) - i <= k:\n grid[i] = max(arr[i:len(arr)]) * (len(arr) - i)\n else:\n maxi = 0\n current_max = 0\n for t in range(k):\n current_max = max(current_max, arr[i + t])\n maxi = max(maxi, current_max * (t + 1) + grid[i + t + 1])\n grid[i] = maxi\n return grid[0]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n if not arr:\n return 0\n if k == 1:\n return sum(arr)\n self.memo = {}\n\n def makepart(arr, n):\n if n in self.memo:\n return self.memo[n]\n if not arr:\n return 0\n l = min(k, len(arr))\n maxele = 0\n total = 0\n for i in range(l):\n maxele = max(maxele, arr[i])\n temp = maxele * (i + 1) + makepart(arr[i + 1:], n + i + 1)\n total = max(total, temp)\n self.memo[n] = total\n return total\n return makepart(arr, 0)", "def maxsumafterpartitioning(A: List[int], k: int) -> int:\n\n def dfs(i, j, max_num=0):\n if i == -1:\n return max_num * j\n if (i, j, max_num) not in opt:\n ans = 0\n if j < k:\n ans = max(ans, dfs(i - 1, j + 1, max(max_num, A[i])))\n ans = max(ans, j * max_num + dfs(i - 1, 1, A[i]))\n opt[i, j, max_num] = ans\n return opt[i, j, max_num]\n n = len(A)\n opt = dict()\n return dfs(n - 1, 0)", "def maxsumafterpartitioning(arr, k: int) -> int:\n n = len(arr)\n mask = [[0] * n for i in range(n)]\n for i in range(n):\n for j in range(i, n):\n mask[i][j] = max(arr[j], mask[i][j - 1] if j > i else 0)\n for i in range(n):\n for j in range(i, n):\n mask[i][j] = (j + 1 - i) * mask[i][j]\n dp = [0] * n\n for i in range(n):\n for h in range(1, k + 1):\n dp[i] = max((dp[i - h] if i - h >= 0 else 0) + (mask[i - h + 1][i] if i - h + 1 < n else 0), dp[i])\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n self.answer = {}\n\n def max_starting_i(index_A):\n array = A[index_A:]\n if index_A in self.answer:\n return self.answer[index_A]\n if len(array) == 0:\n self.answer[index_A] = 0\n return 0\n if len(array) <= K:\n self.answer[index_A] = max(array) * len(array)\n return self.answer[index_A]\n max_start_here = 0\n for i in range(0, K):\n max_split_here = (i + 1) * max(array[:i + 1]) + max_starting_i(index_A + i + 1)\n max_start_here = max(max_start_here, max_split_here)\n self.answer[index_A] = max_start_here\n return max_start_here\n return max_starting_i(0)", "def maxsumafterpartitioning(l: List[int], k: int) -> int:\n\n def _max_sum(l, start, k, memo):\n if len(l) - start <= k:\n return (len(l) - start) * max(l[start:])\n if start in memo:\n return memo[start]\n max_sum = l[start]\n for i in range(1, k + 1):\n curr_sum = max(l[start:start + i]) * i + _max_sum(l, start + i, k, memo)\n max_sum = max(max_sum, curr_sum)\n memo[start] = max_sum\n return max_sum\n if not l:\n return 0\n return _max_sum(l, 0, k, dict())", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n self.dp = [-1] * (len(arr) + k)\n return self.solve(arr, 0, k)\n\ndef solve(arr, start, k):\n if start >= len(arr):\n return 0\n if start + k >= len(arr):\n end = min(len(arr), start + k)\n return max(arr[start:end]) * (end - start)\n if self.dp[start] != -1:\n return self.dp[start]\n result = float('-inf')\n for p in range(1, k + 1):\n temp = max(arr[start:start + p]) * p + self.solve(arr, start + p, k)\n result = max(temp, result)\n self.dp[start] = result\n return result", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n self.cache = {}\n\n def helper(arr, k, start):\n if start in self.cache:\n return self.cache[start]\n _arr = arr[start:]\n if len(_arr) == 0:\n return 0\n if len(_arr) <= k:\n return max(_arr) * len(_arr)\n ans = -1\n for i in range(1, k + 1):\n ans = max(ans, i * max(_arr[:i]) + helper(arr, k, start + i))\n self.cache[start] = ans\n return ans\n return helper(arr, k, 0)", "import typing\n\ndef maxsumafterpartitioning(arr: typing.List[int], k: int) -> int:\n storage = {}\n\n def getSumRec(arr: list, i: int, k: int) -> int:\n if i in storage:\n return storage[i]\n if not i < len(arr):\n return 0\n if len(arr) - i < k:\n return max(arr[i:]) * len(arr[i:])\n listOfSums = []\n for offset in range(k):\n listOfSums.append(max(arr[i:i + offset + 1]) * (offset + 1) + getSumRec(arr, i + offset + 1, k))\n storage[i] = max(listOfSums)\n return storage[i]\n return getSumRec(arr, 0, k)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n best_a = [0] * len(A)\n best_a[0] = A[0]\n for i in range(1, len(A)):\n max_v = 0\n for j in range(i, max(-1, i - K), -1):\n sa = A[j:i + 1]\n v = best_a[j - 1] + max(sa) * len(sa)\n if v > max_v:\n max_v = v\n best_a[i] = max_v\n return best_a[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0] * (len(arr) + 1)\n for i in range(0, len(arr)):\n m = 0\n for j in range(i, i - k, -1):\n if j < 0:\n break\n t = max(arr[j:i + 1]) * (i - j + 1) + dp[j]\n if t > m:\n m = t\n dp[i + 1] = m\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp_sum = [0] * n\n dp_sum[0] = arr[0]\n max_so_far = arr[0]\n for i in range(1, k):\n max_so_far = max(max_so_far, arr[i])\n dp_sum[i] = (i + 1) * max_so_far\n for i in range(k, n):\n partition_max = 0\n for back in range(k):\n partition_max = max(partition_max, arr[i - back])\n dp_sum[i] = max(dp_sum[i], dp_sum[i - back - 1] + (back + 1) * partition_max)\n return dp_sum[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n opt = [arr[0]]\n for i in range(1, len(arr)):\n opt.append(0)\n subseqLenMax = min(k, i + 1)\n for subseqLen in range(1, subseqLenMax + 1):\n subseqSum = subseqLen * max(arr[i - subseqLen + 1:i + 1])\n if subseqLen < i + 1:\n prevOpt = opt[i - subseqLen]\n else:\n prevOpt = 0\n optTemp = prevOpt + subseqSum\n if optTemp > opt[i]:\n opt[i] = optTemp\n return opt[len(opt) - 1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n dp = [0] * (n + 1)\n for i in range(1, n + 1):\n for w in range(1, K + 1):\n if i - w < 0:\n break\n dp[i] = max(dp[i], dp[i - w] + max(A[i - w:i]) * w)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n if not arr:\n return 0\n if n == 1:\n return arr[0]\n if n < k:\n return sum(arr)\n dp = [0] * n\n for i in range(n):\n for j in range(i, max(-1, i - k), -1):\n dp[i] = max(dp[i], max(arr[j:i + 1]) * (i - j + 1) + (dp[j - 1] if j - 1 >= 0 else 0))\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n N = len(arr)\n T = [0] * (N + 1)\n for i in range(1, N + 1):\n for j in range(1, k + 1):\n if j > i:\n break\n T[i] = max(T[i], T[i - j] + max(arr[i - j:i]) * j)\n return T[N]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n if k == 1:\n return sum(arr)\n if k == len(arr):\n max_val = max(arr)\n return max_val * len(arr)\n sums = [-1 for index in range(k)]\n maxs = [-1 for index in range(k)]\n max_sum = 0\n sums[0] = arr[0]\n maxs[0] = arr[0]\n for idx in range(1, len(arr)):\n val = arr[idx]\n max_sum = max(sums)\n for ki in range(k - 1, 0, -1):\n max_val = maxs[ki - 1]\n if not max_val < 0:\n if val <= max_val:\n maxs[ki] = max_val\n sums[ki] = sums[ki - 1] + max_val\n else:\n maxs[ki] = val\n sums[ki] = sums[ki - 1] - max_val * ki + val * (ki + 1)\n sums[0] = max_sum + val\n maxs[0] = val\n return max(sums)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0] * len(arr)\n for i in range(len(arr)):\n maxsum = 0\n for j in range(k):\n if i - j >= 1:\n maxsum = max(maxsum, (j + 1) * max(arr[i - j:i + 1]) + dp[i - j - 1])\n elif i - j >= 0:\n maxsum = max(maxsum, (j + 1) * max(arr[i - j:i + 1]))\n dp[i] = maxsum\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [float('-inf') for _ in range(n + 1)]\n dp[0] = 0\n for i in range(1, n + 1):\n j = i - 1\n cnt = k\n while j >= 0 and cnt >= 1:\n maximum = max(arr[j:i])\n dp[i] = max(dp[i], dp[j] + maximum * (i - j))\n j -= 1\n cnt -= 1\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n dp = [0] * (len(A) + 1)\n for i in range(1, len(A) + 1):\n temp = []\n for j in range(1, K + 1):\n if i - j >= 0:\n k = dp[i - j] + max(A[i - j:i]) * j\n temp.append(k)\n dp[i] = max(temp)\n return dp[len(A)]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0 for _ in range(k + 1)]\n rolling_max = -1\n for i in range(0, k):\n rolling_max = max(rolling_max, arr[i])\n dp[i] = rolling_max * (i + 1)\n for i in range(k, len(arr)):\n rolling_max = arr[i]\n for j in range(1, k + 1):\n rolling_max = max(rolling_max, arr[i - j + 1])\n dp[i % (k + 1)] = max(rolling_max * j + dp[(i - j) % (k + 1)], dp[i % (k + 1)])\n return dp[(len(arr) - 1) % (k + 1)]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0 for num in arr]\n for i in range(len(arr)):\n prev_sum = 0 if i - 1 < 0 else dp[i - 1]\n max_at_i = arr[i] + prev_sum\n possible_ks = i if i < k - 1 else k - 1\n for j in range(1, possible_ks + 1):\n current_window = arr[i - j:i + 1]\n current_max = max(current_window)\n current_window_sum = len(current_window) * current_max\n prev_window_sum = 0 if i - j - 1 < 0 else dp[i - j - 1]\n total_sum = current_window_sum + prev_window_sum\n if total_sum > max_at_i:\n max_at_i = total_sum\n dp[i] = max_at_i\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n L = len(arr)\n record = dict()\n record[0] = 0\n for idx in range(1, L + 1):\n r = -float('inf')\n for gap in range(1, k + 1):\n if idx - gap < 0:\n continue\n else:\n r = max(r, max(arr[idx - gap:idx]) * gap + record[idx - gap])\n record[idx] = r\n return record[L]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n hashmap = {}\n\n def partitionMatrix(lst, currScore):\n key = tuple(lst)\n if key in hashmap:\n return hashmap[key] + currScore\n if lst == []:\n hashmap[key] = 0\n return currScore\n for i in range(1, k + 1):\n if len(lst) == i:\n hashmap[key] = max(lst) * i\n return currScore + max(lst) * i\n best = currScore\n for i in range(1, k + 1):\n subScore = max(lst[:i]) * i\n best = max(best, partitionMatrix(lst[i:], currScore + subScore))\n hashmap[key] = best - currScore\n return best\n return partitionMatrix(arr, 0)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n\n def rec(l, h):\n if h - l < K:\n dp[l][h] = (h - l + 1) * max(A[l:h + 1])\n return dp[l][h]\n m = []\n if dp[l][h] > 0:\n return dp[l][h]\n for i in range(0, K):\n m += [rec(l, l + i) + rec(l + i + 1, h)]\n dp[l][h] = max(m)\n return dp[l][h]\n dp = [0] * len(A)\n dp = [[0] * len(A) for i in range(len(A))]\n rec(0, len(A) - 1)\n return dp[0][len(A) - 1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n size = len(arr)\n mem = [0] * size\n for i in range(size):\n mem[i] = arr[i]\n for j in range(0, k):\n if i - j > 0:\n candidate = max(arr[i - j:i + 1]) * (j + 1) + mem[i - j - 1]\n mem[i] = max(mem[i], candidate)\n elif i - j == 0:\n candidate = max(arr[i - j:i + 1]) * (j + 1)\n mem[i] = max(mem[i], candidate)\n else:\n break\n return mem[size - 1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0]\n for i in range(len(arr)):\n max_sum = -float('inf')\n for j in range(1, k + 1):\n if i - j + 1 < 0:\n break\n max_sum = max(max_sum, max(arr[i - j + 1:i + 1]) * j + dp[i - j + 1])\n dp.append(max_sum)\n return dp[-1]", "def getMax(arr, k, idx, cache):\n if idx == len(arr) - 1:\n return arr[idx]\n maxSum = 0\n for numInPartition in range(1, k + 1):\n if idx + numInPartition > len(arr):\n break\n startOfRecursiveIndex = idx + numInPartition\n maxVal = max(arr[idx:startOfRecursiveIndex])\n partSum = maxVal * numInPartition\n rest = cache[startOfRecursiveIndex] if startOfRecursiveIndex in cache else self.getMax(arr, k, startOfRecursiveIndex, cache)\n cache[startOfRecursiveIndex] = rest\n maxSum = max(maxSum, partSum + rest)\n return maxSum\n\ndef maxsumafterpartitioning(A: List[int], K: int) -> int:\n cache = {}\n return self.getMax(A, K, 0, cache)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n mem = {}\n\n def find(s, e):\n if (s, e) in mem:\n return mem[s, e]\n if e - s == 1:\n return arr[s]\n elif e - s == 0:\n return 0\n else:\n m = None\n for i in range(s + 1, min(s + k + 1, len(arr) + 1)):\n subsum = max(arr[s:i]) * (i - s) + find(i, e)\n if m is None or subsum > m:\n m = subsum\n mem[s, e] = m\n return m\n return find(0, len(arr))", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n from functools import lru_cache\n\n def dp(i):\n ans = 0\n for k in range(K):\n if i - k >= 0:\n ans = max(ans, max(A[i - k:i + 1]) * (k + 1) + dp(i - k - 1))\n return ans\n return dp(len(A) - 1)", "def maxsumafterpartitioning(arr, k):\n if not arr:\n return 0\n dp = [0] * len(arr)\n for i in range(len(arr)):\n for j in range(k):\n if i - j < 0:\n continue\n max_val = max(arr[i - j:i + 1])\n if i - j == 0:\n total = max_val * (j + 1)\n else:\n total = dp[i - j - 1] + max_val * (j + 1)\n dp[i] = max(dp[i], total)\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n N = len(A)\n dp = [0] * N\n dp[0] = A[0]\n for i in range(1, N):\n for j in range(0, min(K, i + 1)):\n current_subarray = A[i - j:i + 1]\n if i >= K:\n dp[i] = max(dp[i], dp[i - j - 1] + max(current_subarray) * (j + 1))\n else:\n dp[i] = max(dp[i], max(current_subarray) * (j + 1))\n return dp[-1]\n (0, 1)\n (1, 1)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n dp = [0] * n\n for i in range(n):\n if i == 0:\n dp[i] = A[0]\n else:\n for k in range(1, K + 1):\n if i - k + 1 < 0:\n break\n elif i - k + 1 == 0:\n dp[i] = max(dp[i], max(A[i - k + 1:i + 1]) * k)\n else:\n dp[i] = max(dp[i], dp[i - k] + max(A[i - k + 1:i + 1]) * k)\n return dp[n - 1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n dp = [0] * (n + 1)\n for i in range(n):\n for k in range(1, K + 1):\n if i - k > -2:\n dp[i + 1] = max(dp[i + 1], max(A[max(0, i - k + 1):i + 1]) * k + dp[i + 1 - k])\n return dp[n]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0] * len(arr)\n dp[0] = arr[0]\n for (i, val) in enumerate(arr):\n if i == 0:\n continue\n cur_max = val + dp[i - 1]\n cur_k = 1\n while i - cur_k >= 0 and cur_k < k:\n temp = arr[i - cur_k:i + 1]\n m = max(temp)\n if i - cur_k == 0:\n cur_max = max(cur_max, m * (cur_k + 1))\n else:\n cur_max = max(cur_max, m * (cur_k + 1) + dp[i - cur_k - 1])\n cur_k += 1\n dp[i] = cur_max\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n DP = [0 for _ in range(len(arr) + 1)]\n for i in range(1, len(DP)):\n loc = max(i - k, 0)\n run_max = 0\n for j in range(loc, i):\n run_max = max(run_max, DP[j] + max(arr[j:i]) * (i - j))\n DP[i] = run_max\n return DP[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n if not K or K == 1:\n return sum(A)\n if not A:\n return 0\n dp = [0] * len(A)\n for (index, num) in enumerate(A):\n possible = []\n for group in range(K):\n if index - group >= 0:\n if index - group - 1 >= 0:\n previous = dp[index - group - 1]\n else:\n previous = 0\n possible.append(previous + max(A[index - group:index + 1]) * (group + 1))\n dp[index] = max(possible)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n self.arr = arr\n self.dp = {}\n\n def helper(i, j, k):\n if j <= i:\n return 0\n if (i, j) in self.dp:\n return self.dp[i, j]\n maxsum = -sys.maxsize\n for length in range(1, k + 1):\n if i + length <= j:\n currsum = max(self.arr[i:i + length]) * length + helper(i + length, j, k)\n maxsum = max(maxsum, currsum)\n self.dp[i, j] = maxsum\n return self.dp[i, j]\n return helper(0, len(arr), k)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n dp = [0 for _ in A]\n for (i, num) in enumerate(A):\n for j in range(K):\n ans = 0\n if i - j >= 0:\n ans = ans + (j + 1) * max(A[i - j:i + 1])\n if i - j - 1 >= 0:\n ans = ans + dp[i - j - 1]\n dp[i] = max(dp[i], ans)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n d = [0] * (1 + len(arr) + k)\n for ind in range(1, len(arr) + 1):\n for sub_arr_st in range(min(ind, k)):\n if arr[ind - sub_arr_st - 1] > arr[ind - 1]:\n break\n for sub_arr_len in range(sub_arr_st + 1, k + 1):\n ind_x = ind - sub_arr_st + sub_arr_len - 1\n d[ind_x] = max(d[ind_x], d[ind - sub_arr_st - 1] + arr[ind - 1] * sub_arr_len)\n return d[len(arr)]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0] * (len(arr) + 1)\n dp[0] = arr[0]\n for i in range(1, len(arr)):\n ans = -100000\n for z in range(max(0, i - k + 1), i + 1):\n ans = max(dp[z - 1] + max(arr[z:i + 1]) * (i - z + 1), ans)\n dp[i] = ans\n return dp[-2]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n memo = {}\n l_arr = len(arr)\n for chain_len in range(0, k, 1):\n for i in range(0, l_arr - chain_len, 1):\n memo[i, i + chain_len] = max(arr[i:i + chain_len + 1]) * (chain_len + 1)\n res_memo = {}\n\n def dfs(idx):\n if idx == l_arr:\n return 0\n if idx in res_memo:\n return res_memo[idx]\n res_memo[idx] = max((memo[idx, idx + j] + dfs(idx + j + 1) for j in range(k) if idx + j < l_arr))\n return res_memo[idx]\n return dfs(0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n res = [0] * (len(arr) + 1)\n for i in range(1, len(arr) + 1):\n for j in range(1, k + 1):\n if i - j > -1:\n res[i] = max(res[i], res[i - j] + max(arr[i - j:i]) * j)\n return res[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n ar_len = len(arr)\n dp = [0] * (ar_len + 1)\n for i in range(1, len(dp)):\n tmp_max = []\n for j in range(1, k + 1):\n if i - j >= 0:\n max_t = dp[i - j] + max(arr[i - j:i]) * j\n tmp_max.append(max_t)\n dp[i] = max(tmp_max)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n if k == n:\n return n * max(arr)\n dp = collections.deque([0] * k)\n for i in range(n - 1, -1, -1):\n m = 0\n result = 0\n for j in range(min(k, n - i)):\n m = max(m, arr[i + j])\n result = max(result, m * (j + 1) + dp[j])\n dp.appendleft(result)\n dp.pop()\n return dp[0]", "def maxsumafterpartitioning(nums: List[int], k: int) -> int:\n dp = [0] * len(nums)\n for i in range(len(nums)):\n for windowSize in range(1, k + 1):\n startIndex = i - windowSize + 1\n if startIndex < 0:\n break\n maxVal = max(nums[startIndex:i + 1])\n currVal = windowSize * maxVal\n currSum = currVal\n if startIndex > 0:\n currSum += dp[startIndex - 1]\n dp[i] = max(dp[i], currSum)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n memo = {n: 0}\n\n def helper(arr, i):\n if i in memo:\n return memo[i]\n res = 0\n for j in range(i, min(n, i + k)):\n res = max(res, helper(arr, j + 1) + max(arr[i:j + 1]) * (j + 1 - i))\n memo[i] = res\n return res\n return helper(arr, 0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n result = [0] * len(arr)\n result[0] = arr[0]\n max_val = result[0]\n for i in range(1, k):\n max_val = max(max_val, arr[i])\n result[i] = max_val * (i + 1)\n for i in range(k, len(arr)):\n max_val = arr[i]\n for j in range(1, k + 1):\n max_val = max(max_val, arr[i - j + 1])\n result[i] = max(result[i], result[i - j] + max_val * j)\n return result[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n A = arr\n K = k\n n = len(A)\n dp = [0] * n\n curMax = 0\n for i in range(n):\n if i < K:\n curMax = max(curMax, A[i])\n dp[i] = curMax * (i + 1)\n else:\n curMax = 0\n for j in range(1, K + 1):\n curMax = max(A[i - j + 1], curMax)\n dp[i] = max(dp[i], dp[i - j] + curMax * j)\n return dp[n - 1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0] * (n + 1)\n for i in range(1, n + 1):\n max_val = float('-inf')\n for j in range(1, min(i, k) + 1):\n max_val = max(max_val, arr[i - j])\n dp[i] = max(dp[i], dp[i - j] + j * max_val)\n return dp[n]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n f = [0]\n for end in range(1, len(arr) + 1):\n _local = 0\n _cur_max = 0\n for start in range(end - 1, max(0, end - k) - 1, -1):\n _cur_max = max(_cur_max, arr[start])\n _local = max(_cur_max * (end - start) + f[start], _local)\n f.append(_local)\n return f[-1]", "def maxsumafterpartitioning(arr, k):\n n = len(arr)\n dp = [0] * (n + 1)\n for i in range(n):\n cmax = 0\n for j in range(1, min(k, i + 1) + 1):\n cmax = max(cmax, arr[i - j + 1])\n dp[i] = max(dp[i], dp[i - j] + cmax * j)\n return dp[-2]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n best_sums = [0] * (len(arr) + 1)\n for i in range(len(arr)):\n curr_max = 0\n for j in range(1, min(k + 1, i + 2)):\n curr_max = max(curr_max, arr[i - j + 1])\n best_sums[i] = max(best_sums[i], best_sums[i - j] + j * curr_max)\n return best_sums[-2]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n DP = [0] * len(arr)\n N = len(arr)\n DP[0] = arr[0]\n m = arr[0]\n for i in range(k):\n m = max(m, arr[i])\n DP[i] = m * (i + 1)\n for i in range(k, N):\n mm = arr[i]\n DP[i] = DP[i - 1] + arr[i]\n for j in range(1, k):\n mm = max(mm, arr[i - j])\n DP[i] = max(DP[i], DP[i - j - 1] + mm * (j + 1))\n return DP[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0] * (n + 1)\n for i in range(n):\n cur = 0\n for j in range(1, min(k, i + 1) + 1):\n cur = max(cur, arr[i - j + 1])\n dp[i] = max(dp[i], cur * j + dp[i - j])\n return dp[-2]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n\n def dp(idx):\n if idx < 0:\n return 0\n left = max(idx - k + 1, 0)\n curr_max = arr[idx]\n res = arr[idx]\n for i in range(idx, left - 1, -1):\n curr_max = max(curr_max, arr[i])\n res = max(res, dp(i - 1) + (idx - i + 1) * curr_max)\n return res\n return dp(len(arr) - 1)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n N = len(arr)\n dp = [0] * (N + 1)\n for i in range(N):\n cur_max = 0\n for j in range(1, min(k, i + 1) + 1):\n cur_max = max(cur_max, arr[i - j + 1])\n dp[i] = max(dp[i], dp[i - j] + cur_max * j)\n return dp[N - 1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n N = len(arr)\n dp = [0 for _ in range(N)]\n dp[0] = arr[0]\n max_so_far = arr[0]\n for i in range(1, k):\n max_so_far = max(max_so_far, arr[i])\n dp[i] = (i + 1) * max_so_far\n for i in range(k, N):\n max_so_far = -sys.maxsize\n for j in range(i, i - k, -1):\n max_so_far = max(max_so_far, arr[j])\n dp[i] = max(dp[i], dp[j - 1] + (i - j + 1) * max_so_far)\n return dp[N - 1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n dp = [0] * (n + 1)\n for i in range(1, n + 1):\n j = i - 1\n mx = -float('inf')\n while i - j <= K and j >= 0:\n mx = max(mx, A[j])\n dp[i] = max(dp[i], dp[j] + mx * (i - j))\n j -= 1\n return dp[n]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n N = len(A)\n DP = [0] * (N + 1)\n for i in range(N):\n curMax = 0\n for k in range(1, min(K, i + 1) + 1):\n curMax = max(curMax, A[i - k + 1])\n DP[i] = max(DP[i], DP[i - k] + curMax * k)\n return DP[N - 1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0] * (n + 1)\n for i in range(n):\n cur_max = 0\n for d in range(1, min(k, i + 1) + 1):\n cur_max = max(cur_max, arr[i - d + 1])\n dp[i + 1] = max(dp[i + 1], dp[i + 1 - d] + cur_max * d)\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0]\n for i in range(1, len(arr) + 1):\n max_arr_num = 0\n now_max = 0\n for j in range(1, k + 1):\n idx = i - j\n if idx >= 0:\n max_arr_num = max(max_arr_num, arr[idx])\n now_max = max(now_max, dp[idx] + max_arr_num * j)\n dp.append(now_max)\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n dp = [0] * (n + 1)\n for i in range(1, n + 1):\n m = float('-inf')\n for j in range(1, K + 1):\n if i - j >= 0:\n m = max(A[i - j], m)\n dp[i] = max(dp[i], dp[i - j] + m * j)\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n n = len(A)\n dp = [0] * (n + 1)\n res = 0\n for i in range(n):\n max_val = 0\n for k in range(1, min(K, i + 1) + 1):\n max_val = max(max_val, A[i - k + 1])\n dp[i] = max(dp[i], dp[i - k] + max_val * k)\n return dp[n - 1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n N = len(A)\n dp = [0] * (N + 1)\n for i in range(N):\n curr_max = 0\n for j in range(1, K + 1):\n if i + j > N:\n break\n curr_max = max(curr_max, A[i + j - 1])\n dp[i + j] = max(dp[i + j], dp[i] + curr_max * j)\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n dp = [float('-inf') for i in range(len(A) + 1)]\n dp[-1] = 0\n dp[-2] = A[-1]\n for j in reversed(list(range(len(A) - 1))):\n cur_max = float('-inf')\n for k in range(K):\n if j + k == len(A):\n break\n cur_max = max(cur_max, A[j + k])\n dp[j] = max(dp[j], (k + 1) * cur_max + dp[j + k + 1])\n return dp[0]", "def maxsumafterpartitioning(A: List[int], k: int) -> int:\n N = len(A)\n dp = [0] * (N + 1)\n for i in range(N):\n mx = 0\n for j in range(i, max(-1, i - k), -1):\n mx = max(mx, A[j])\n p = dp[i + 1]\n dp[i + 1] = max(dp[i + 1], dp[j] + mx * (i - j + 1))\n return dp[N]", "def maxsumafterpartitioning(A, K):\n n = len(A)\n record = [0] * (n + 1)\n for i in range(n):\n curMax = 0\n for k in range(1, min(K, i + 1) + 1):\n curMax = max(curMax, A[i - k + 1])\n record[i + 1] = max(record[i + 1], record[i - k + 1] + curMax * k)\n return record[n]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0] * (n + 1)\n for i in range(1, n + 1):\n m = -float('inf')\n d = 0\n while d < k and i - d > 0:\n m = max(m, arr[i - 1 - d])\n dp[i] = max(dp[i], dp[i - d - 1] + m * (d + 1))\n d += 1\n return dp[n]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n N = len(arr)\n memo = {}\n\n def maxSum2(i):\n if i >= N:\n return 0\n if i in memo:\n return memo[i]\n val = -1\n sol = -1\n for j in range(1, min(k + 1, N - i + 1)):\n val = max(val, arr[i + j - 1])\n sol = max(sol, val * j + maxSum2(i + j))\n memo[i] = sol\n return sol\n return maxSum2(0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0] * (n + 1)\n for i in range(n):\n currMax = arr[i]\n size = 1\n while size <= k and i - size + 1 >= 0:\n currMax = max(currMax, arr[i - size + 1])\n dp[i + 1] = max(dp[i + 1], dp[i + 1 - size] + currMax * size)\n size += 1\n return dp[n]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n memo = {}\n\n def max_sum(idx):\n if idx >= len(arr):\n return 0\n if idx in memo:\n return memo[idx]\n subarr_max = float('-inf')\n options = []\n for end in range(idx, min(idx + k, len(arr))):\n subarr_max = max(subarr_max, arr[end])\n subarr_sum = subarr_max * (end - idx + 1)\n options.append(subarr_sum + max_sum(end + 1))\n memo[idx] = max(options)\n return memo[idx]\n return max_sum(0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n memo = {}\n\n def dfs(i):\n if i >= n:\n return 0\n if i in memo:\n return memo[i]\n res = float('-inf')\n cur_max = float('-inf')\n for j in range(i, min(i + k, n)):\n cur_max = max(cur_max, arr[j])\n res = max(res, cur_max * (j - i + 1) + dfs(j + 1))\n memo[i] = res\n return res\n return dfs(0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n N = len(arr)\n maxSoFar = [0] * N\n for i in range(N):\n curMax = 0\n for prev in range(1, min(i + 1, k) + 1):\n curMax = max(curMax, arr[i - prev + 1])\n lastPartition = maxSoFar[i - prev] if i >= prev else 0\n maxSoFar[i] = max(maxSoFar[i], lastPartition + curMax * prev)\n return maxSoFar[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n\n def dfs(start, memo):\n if start in memo:\n return memo[start]\n N = len(A)\n if start >= N:\n return 0\n maxSum = 0\n maxEle = 0\n for i in range(start, min(N, start + K)):\n maxEle = max(maxEle, A[i])\n maxSum = max(maxSum, maxEle * (i - start + 1) + dfs(i + 1, memo))\n memo[start] = maxSum\n return maxSum\n return dfs(0, {})", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n if arr == [] or k == 0:\n return 0\n if len(arr) == 1 and k == 1:\n return arr[0]\n l = len(arr)\n res = [0] * l\n for i in range(0, l):\n sub_max = 0\n for j in range(k):\n if j <= i:\n sub_max = max(sub_max, arr[i - j])\n res[i] = max(res[i], sub_max * (j + 1) + (res[i - j - 1] if i - j - 1 >= 0 else 0))\n return res[l - 1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = len(arr) * [0]\n dp[0] = arr[0]\n for i in range(1, len(arr)):\n sub_max = 0\n for j in range(k):\n if j <= i:\n sub_max = max(sub_max, arr[i - j])\n dp[i] = max(dp[i], sub_max * (j + 1) + (dp[i - j - 1] if i - j - 1 >= 0 else 0))\n return dp[len(arr) - 1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n dp_sum = [0 for _ in range(len(A) + 1)]\n for i in range(len(A)):\n seg_max = A[i]\n for j in range(1, K + 1):\n if i - j + 1 < 0:\n break\n seg_max = max(seg_max, A[i - j + 1])\n tmp = dp_sum[i - j + 1] + seg_max * j\n dp_sum[i + 1] = max(dp_sum[i + 1], tmp)\n return dp_sum[-1]", "def maxsumafterpartitioning(A: List[int], k: int) -> int:\n L = len(A)\n vis = {}\n\n def pos(n):\n if n >= L:\n return 0\n if n in vis:\n return vis[n]\n currmax = A[n]\n ans = A[n] + pos(n + 1)\n for i in range(1, k):\n n1 = n + i\n if n1 >= L:\n break\n currmax = max(currmax, A[n1])\n ans = max(ans, currmax * (i + 1) + pos(n1 + 1))\n vis[n] = ans\n return vis[n]\n return pos(0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n if not arr:\n return 0\n n = len(arr)\n dp = [0 for _ in range(n)]\n for i in range(n):\n temp_max = arr[i]\n j = 1\n while i - j + 1 >= 0 and j <= k:\n temp_max = max(temp_max, arr[i - j + 1])\n if i >= j:\n dp[i] = max(dp[i], dp[i - j] + temp_max * j)\n else:\n dp[i] = max(dp[i], temp_max * j)\n j += 1\n return dp[-1]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [-1 for _ in range(n)]\n\n def max_sum(i):\n if i >= n:\n return 0\n if i == n - 1:\n return arr[i]\n if dp[i] != -1:\n return dp[i]\n ans = float('-inf')\n maxi = arr[i]\n for p in range(1, k + 1):\n v = maxi * p + max_sum(i + p)\n ans = max(v, ans)\n if i + p < n:\n maxi = max(maxi, arr[i + p])\n else:\n break\n dp[i] = ans\n return ans\n v = max_sum(0)\n return v", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = {}\n\n def help(arr, k, start=0):\n if start == len(arr):\n return 0\n if start in dp:\n return dp[start]\n dp[start] = -float('inf')\n maxval = arr[start]\n for i in range(start, min(start + k, len(arr))):\n maxval = max(maxval, arr[i])\n dp[start] = max(dp[start], maxval * (i - start + 1) + help(arr, k, i + 1))\n return dp[start]\n return help(arr, k)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n N = len(arr)\n K = k\n dp = [0] * (N + 1)\n for i in range(N):\n curMax = 0\n for k in range(1, min(K, i + 1) + 1):\n curMax = max(curMax, arr[i - k + 1])\n dp[i] = max(dp[i], dp[i - k] + curMax * k)\n return dp[N - 1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n memo = {}\n\n def getMax(arr, k, idx):\n if idx == len(arr):\n return 0\n if idx in memo:\n return memo[idx]\n (maxSum, maxInSub) = (0, 0)\n for i in range(idx, min(idx + K, len(arr))):\n maxInSub = max(maxInSub, arr[i])\n maxSum = max(maxSum, maxInSub * (i - idx + 1) + getMax(arr, k, i + 1))\n memo[idx] = maxSum\n return maxSum\n return getMax(A, K, 0)", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0] * (n + 1)\n dp[1] = arr[0]\n for i in range(2, n + 1):\n dp[i] = dp[i - 1] + arr[i - 1]\n cur_max = arr[i - 1]\n for j in range(1, k + 1):\n cur_max = max(cur_max, arr[i - j])\n if i - j >= 0:\n dp[i] = max(dp[i], dp[i - j] + j * cur_max)\n return dp[n]", "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n dp = [0] * (len(arr) + 1)\n for i in range(1, len(arr) + 1):\n dp[i] = float('-inf')\n curr_max = arr[i - 1]\n for p in range(1, k + 1):\n if p > i:\n break\n curr_max = max(curr_max, arr[i - p])\n dp[i] = max(dp[i], p * curr_max + dp[i - p])\n return dp[-1]", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n self.max_sum = float('-inf')\n self.dic = {}\n\n def getSum(i):\n if i >= len(A):\n return 0\n if i in self.dic:\n return self.dic[i]\n cur_max = A[i]\n ret = cur_max + getSum(i + 1)\n for j in range(1, K):\n if i + j < len(A):\n if A[i + j] > cur_max:\n cur_max = A[i + j]\n ret = max(cur_max * (j + 1) + getSum(i + j + 1), ret)\n else:\n break\n self.dic[i] = ret\n return ret\n return getSum(0)", "def rec(idx):\n if idx > len(self.A):\n return 0\n max_yet = 0\n max_score = 0\n for i in range(self.K):\n if idx + i >= len(self.A):\n break\n max_yet = max(max_yet, self.A[idx + i])\n max_score = max(max_score, max_yet * (i + 1) + self.rec(idx + i + 1))\n return max_score\n\ndef maxsumafterpartitioning(A: List[int], K: int) -> int:\n self.A = A\n self.K = K\n return self.rec(0)", "def maxsumafterpartitioning(A: List[int], K: int) -> int:\n\n def DPHelper(index):\n if index >= len(A):\n return 0\n if memo.get(index) is not None:\n return memo[index]\n res = 0\n curr_max = 0\n for i in range(index, min(index + K, len(A))):\n curr_max = max(curr_max, A[i])\n res = max(res, curr_max * (i - index + 1) + DPHelper(i + 1))\n memo[index] = res\n return res\n memo = {}\n return DPHelper(0)"], "starter_code": "def maxsumafterpartitioning(arr: List[int], k: int) -> int:\n", "input_output": {"fn_name": "maxSumAfterPartitioning", "inputs": [[[1, 15, 7, 9, 2, 5, 10], 3]], "outputs": [84]}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/partition-array-for-maximum-sum/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "maxsumafterpartitioning", "task_id": "TACO_lite/106", "example": [[[[1, 15, 7, 9, 2, 5, 10], 3], [[1, 4, 1, 5, 7, 3, 6, 1, 9, 9, 3], 4], [[1], 1]], ["84", "83", "1"]]} +{"requirement": "We are given a list of (axis-aligned)\u00a0rectangles.\u00a0 Each\u00a0rectangle[i] = [x1, y1, x2, y2]\u00a0, where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the ith rectangle.\nFind the total area covered by all rectangles in the plane.\u00a0 Since the answer\u00a0may be too large, return it modulo 10^9 + 7.\n\nExample 1:\nInput: [[0,0,2,2],[1,0,2,3],[1,0,3,1]]\nOutput: 6\nExplanation: As illustrated in the picture.\n\nExample 2:\nInput: [[0,0,1000000000,1000000000]]\nOutput: 49\nExplanation: The answer is 10^18 modulo (10^9 + 7), which is (10^9)^2 = (-7)^2 = 49.\n\nNote:\n\n1 <= rectangles.length <= 200\nrectanges[i].length = 4\n0 <= rectangles[i][j] <= 10^9\nThe total area covered by all rectangles will never exceed\u00a02^63 - 1\u00a0and thus will fit in a 64-bit signed integer.", "solutions": ["def rectanglearea(rectangles: List[List[int]]) -> int:\n\n def getArea(width):\n res = 0\n prev_low = 0\n for (low, high) in intervals:\n low = max(prev_low, low)\n if high > low:\n res += (high - low) * width\n prev_low = high\n return res\n MOD = 10 ** 9 + 7\n events = []\n for (x1, y1, x2, y2) in rectangles:\n events.append((x1, 0, y1, y2))\n events.append((x2, 1, y1, y2))\n events.sort(key=lambda x: (x[0], x[1]))\n intervals = []\n area = 0\n prev_x = 0\n for event in events:\n (cur_x, type, low, high) = event\n area += getArea(cur_x - prev_x)\n if type == 1:\n intervals.remove((low, high))\n else:\n intervals.append((low, high))\n intervals.sort()\n prev_x = cur_x\n return area % MOD", "def rectanglearea(rectangles: List[List[int]]) -> int:\n mod = 10 ** 9 + 7\n events = []\n for (x1, y1, x2, y2) in rectangles:\n events.append([x1, 0, y1, y2])\n events.append([x2, 1, y1, y2])\n events.sort(key=lambda x: (x[0], -x[1]))\n\n def getArea(m):\n area = 0\n prev = float('-inf')\n for (l, r) in heights:\n prev = max(prev, l)\n area += max(0, r - prev) * m\n prev = max(prev, r)\n return area\n area = 0\n prev = 0\n heights = []\n for event in events:\n (cur, close, y1, y2) = event\n area += getArea(cur - prev)\n if close:\n heights.remove((y1, y2))\n else:\n heights.append((y1, y2))\n heights.sort()\n prev = cur\n return area % mod", "def rectanglearea(rectangles):\n (OPEN, CLOSE) = (1, -1)\n events = []\n nonlocal X\n X = set()\n for (x1, y1, x2, y2) in rectangles:\n events.append((y1, OPEN, x1, x2))\n events.append((y2, CLOSE, x1, x2))\n X.add(x1)\n X.add(x2)\n events.sort()\n X = sorted(X)\n Xi = {x: i for (i, x) in enumerate(X)}\n active = Node(0, len(X) - 1)\n ans = 0\n cur_x_sum = 0\n cur_y = events[0][0]\n for (y, typ, x1, x2) in events:\n ans += cur_x_sum * (y - cur_y)\n cur_x_sum = active.update(Xi[x1], Xi[x2], typ)\n cur_y = y\n return ans % (10 ** 9 + 7)\n\ndef __init__(start, end):\n (self.start, self.end) = (start, end)\n self.total = self.count = 0\n self._left = self._right = None\n\ndef mid():\n return (self.start + self.end) // 2\n\ndef left():\n self._left = self._left or Node(self.start, self.mid)\n return self._left\n\ndef right():\n self._right = self._right or Node(self.mid, self.end)\n return self._right\n\ndef update(i, j, val):\n if i >= j:\n return 0\n if self.start == i and self.end == j:\n self.count += val\n else:\n self.left.update(i, min(self.mid, j), val)\n self.right.update(max(self.mid, i), j, val)\n if self.count > 0:\n self.total = X[self.end] - X[self.start]\n else:\n self.total = self.left.total + self.right.total\n return self.total", "def rectanglearea(rectangles: List[List[int]]) -> int:\n Xs = [x for (x1, _, x2, _) in rectangles for x in [x1, x2]]\n Xs.sort()\n X_idx_lookup = {x: idx for (idx, x) in enumerate(Xs)}\n res = 0\n prev_y = 0\n X_span = 0\n Ys = [e for (x1, y1, x2, y2) in rectangles for e in [[y1, x1, x2, 1], [y2, x1, x2, -1]]]\n Ys.sort()\n overlap_count = [0] * len(Xs)\n for (y, xl, xr, inout) in Ys:\n res += (y - prev_y) * X_span\n prev_y = y\n (start_idx, end_idx) = (X_idx_lookup[xl], X_idx_lookup[xr])\n for i in range(start_idx, end_idx):\n overlap_count[i] += inout\n X_span = sum((x2 - x1 if c > 0 else 0 for (x1, x2, c) in zip(Xs, Xs[1:], overlap_count)))\n return res % 1000000007\n\ndef rectanglearea(rectangles: List[List[int]]) -> int:\n Xs = [x for (x1, _, x2, _) in rectangles for x in [x1, x2]]\n Xs.sort()\n covered = [0] * len(Xs)\n res = 0\n keypoints = [e for (x1, y1, x2, y2) in rectangles for e in [[y1, x1, x2, 1], [y2, x1, x2, -1]]]\n keypoints.sort()\n prev_y = 0\n width_span = 0\n for (y, x1, x2, inout) in keypoints:\n res += (y - prev_y) * width_span\n prev_y = y\n for i in range(len(covered) - 1):\n (a, b) = (Xs[i], Xs[i + 1])\n if x1 <= a and b <= x2:\n covered[i] += inout\n width_span = sum((Xs[i + 1] - Xs[i] if covered[i] > 0 else 0 for i in range(len(covered) - 1)))\n return res % 1000000007", "def rectanglearea(rectangles: List[List[int]]) -> int:\n START = 1\n END = 0\n MOD = 10 ** 9 + 7\n xaxis = []\n for (x1, y1, x2, y2) in rectangles:\n xaxis.append((x1, START, y1, y2))\n xaxis.append((x2, END, y1, y2))\n xaxis.sort()\n prev = 0\n area = 0\n yaxis = []\n for i in range(len(xaxis)):\n (x, status, y1, y2) = xaxis[i]\n if i > 0:\n area += self.get_length(yaxis) * (x - prev)\n area %= MOD\n if status == START:\n yaxis.append((y1, y2))\n yaxis.sort()\n else:\n yaxis.remove((y1, y2))\n prev = x\n return area\n\ndef get_length(yaxis):\n length = 0\n i = 0\n prev = (float('-inf'), float('-inf'))\n for i in range(len(yaxis)):\n if not self.has_overlap(prev, yaxis[i]):\n length += yaxis[i][1] - yaxis[i][0]\n else:\n if prev[1] >= yaxis[i][1]:\n continue\n length += yaxis[i][1] - prev[1]\n prev = yaxis[i]\n return length\n\ndef has_overlap(prev, cur):\n if prev[1] < cur[0] or cur[1] < prev[0]:\n return False\n return True\n\ndef get_overlap_length(prev, cur):\n return min(prev[1], cur[1]) - max(prev[0], cur[0])", "def __init__(l, r):\n self.total = 0\n self.count = 0\n self.l = l\n self.r = r\n self.m = int((self.l + self.r) / 2)\n self.isLeaf = True if self.r - self.l == 1 else False\n self.left = None if self.isLeaf else Tree(self.l, self.m)\n self.right = None if self.isLeaf else Tree(self.m, self.r)\n\ndef update(l, r, count):\n if l >= self.r or r <= self.l:\n return\n if self.isLeaf:\n self.count += count\n self.total = nums[self.r] - nums[self.l] if self.count else 0\n else:\n self.left.update(l, r, count)\n self.right.update(l, r, count)\n self.total = self.left.total + self.right.total\n\ndef rectanglearea(rectangles):\n M = 10 ** 9 + 7\n events = []\n nonlocal nums\n nums = set()\n for (x1, y1, x2, y2) in rectangles:\n events.append((x1, y1, y2, 1))\n events.append((x2, y1, y2, -1))\n nums.add(y1)\n nums.add(y2)\n nums = list(nums)\n nums.sort()\n nToI = dict([(n, i) for (i, n) in enumerate(nums)])\n iTree = Tree(0, len(nums) - 1)\n events.sort(key=lambda x: x[0])\n res = 0\n prev = events[0][0]\n for event in events:\n if event[0] != prev:\n res += iTree.total * (event[0] - prev)\n res = res % M\n prev = event[0]\n iTree.update(nToI[event[1]], nToI[event[2]], event[3])\n return res", "def rectanglearea(rectangles: List[List[int]]) -> int:\n rects = []\n for (x1, y1, x2, y2) in rectangles:\n self.helper(rects, 0, x1, y1, x2, y2)\n ans = 0\n mod = pow(10, 9) + 7\n for (x1, y1, x2, y2) in rects:\n ans += (x2 - x1) * (y2 - y1) % mod\n return ans % mod\n\ndef helper(rects, index, x1, y1, x2, y2):\n if index == len(rects):\n rects.append([x1, y1, x2, y2])\n return\n (i1, j1, i2, j2) = rects[index]\n if i1 >= x2 or i2 <= x1 or j1 >= y2 or (j2 <= y1):\n self.helper(rects, index + 1, x1, y1, x2, y2)\n return\n if x1 < i1:\n self.helper(rects, index + 1, x1, y1, min(i1, x2), y2)\n if x2 > i2:\n self.helper(rects, index + 1, max(i2, x1), y1, x2, y2)\n if y1 < j1:\n self.helper(rects, index + 1, max(x1, i1), y1, min(x2, i2), j1)\n if y2 > j2:\n self.helper(rects, index + 1, max(x1, i1), j2, min(x2, i2), y2)", "MOD = 10 ** 9 + 7\n\ndef rectanglearea(rectangles: List[List[int]]) -> int:\n allY = []\n for (x1, y1, x2, y2) in rectangles:\n allY.append((y1, 0, x1, x2))\n allY.append((y2, 1, x1, x2))\n allY.sort()\n (allX, ans) = ([], 0)\n curHeight = allY[0][0]\n for (y, t, x1, x2) in allY:\n ans += self.getX(allX) * (y - curHeight)\n ans %= MOD\n if t == 0:\n bisect.insort(allX, (x1, x2))\n else:\n idx = bisect.bisect_left(allX, (x1, x2))\n allX.pop(idx)\n curHeight = y\n return ans\n\ndef getX(allX):\n ans = 0\n cur = -1\n for (x1, x2) in allX:\n cur = max(cur, x1)\n ans += max(0, x2 - cur)\n cur = max(cur, x2)\n return ans", "def rectanglearea(rects: List[List[int]]) -> int:\n xs = sorted(set([x for (x1, y1, x2, y2) in rects for x in [x1, x2]]))\n xi = {v: i for (i, v) in enumerate(xs)}\n cnt = [0] * len(xs)\n L = []\n for (x1, y1, x2, y2) in rects:\n L.append([y1, x1, x2, 1])\n L.append([y2, x1, x2, -1])\n L.sort()\n res = last_y = sum_x = 0\n for (y, x1, x2, sig) in L:\n res += (y - last_y) * sum_x\n last_y = y\n for i in range(xi[x1], xi[x2]):\n cnt[i] += sig\n sum_x = sum((x2 - x1 for (x1, x2, c) in zip(xs, xs[1:], cnt) if c))\n return res % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n xs = sorted(list(set((x for (x1, y1, x2, y2) in rectangles for x in [x1, x2]))))\n xs_i = {x: i for (i, x) in enumerate(xs)}\n rects = []\n for (x1, y1, x2, y2) in rectangles:\n rects.append((y1, x1, x2, 1))\n rects.append((y2, x1, x2, -1))\n rects = sorted(rects)\n counts = [0] * len(xs_i)\n curr_y = 0\n area = 0\n L = 0\n for (y, x1, x2, sig) in rects:\n area += (y - curr_y) * L\n curr_y = y\n for x in range(xs_i[x1], xs_i[x2]):\n counts[x] += sig\n L = sum((x2 - x1 for (x1, x2, s1) in zip(xs, xs[1:], counts) if s1 > 0))\n return area % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n all_rectangles = []\n for rectangle in rectangles:\n self.add_rectangle(all_rectangles, rectangle, 0)\n ans = 0\n mod = pow(10, 9) + 7\n for rect in all_rectangles:\n (x1, y1, x2, y2) = rect\n ans += (x2 - x1) * (y2 - y1) % mod\n return ans % mod\n\ndef add_rectangle(all_rectangles, cur, start):\n if start >= len(all_rectangles):\n all_rectangles.append(cur)\n return\n (x1, y1, x2, y2) = cur\n (rx1, ry1, rx2, ry2) = all_rectangles[start]\n if x2 <= rx1 or x1 >= rx2 or y2 <= ry1 or (y1 >= ry2):\n self.add_rectangle(all_rectangles, cur, start + 1)\n return\n if x1 < rx1:\n self.add_rectangle(all_rectangles, [x1, y1, rx1, y2], start + 1)\n if x2 > rx2:\n self.add_rectangle(all_rectangles, [rx2, y1, x2, y2], start + 1)\n if y1 < ry1:\n self.add_rectangle(all_rectangles, [max(x1, rx1), y1, min(x2, rx2), ry1], start + 1)\n if y2 > ry2:\n self.add_rectangle(all_rectangles, [max(x1, rx1), ry2, min(x2, rx2), y2], start + 1)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n xTicks = set()\n yTicks = set()\n for (x1, y1, x2, y2) in rectangles:\n xTicks.add(x1)\n xTicks.add(x2)\n yTicks.add(y1)\n yTicks.add(y2)\n xTicksList = sorted(list(xTicks))\n yTicksList = sorted(list(yTicks))\n xTicksDict = {xLable: xi for (xi, xLable) in enumerate(xTicksList)}\n yTicksDict = {yLable: yi for (yi, yLable) in enumerate(yTicksList)}\n iMax = len(xTicksList)\n jMax = len(yTicksList)\n grid = [[0 for j in range(jMax)] for i in range(iMax)]\n ans = 0\n for (x1, y1, x2, y2) in rectangles:\n for i in range(xTicksDict[x1], xTicksDict[x2]):\n xSide = xTicksList[i + 1] - xTicksList[i]\n for j in range(yTicksDict[y1], yTicksDict[y2]):\n if grid[i][j] == 0:\n ans += xSide * (yTicksList[j + 1] - yTicksList[j])\n grid[i][j] = 1\n return ans % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n N = len(rectangles)\n (Xvals, Yvals) = (set(), set())\n for (x1, y1, x2, y2) in rectangles:\n Xvals.add(x1)\n Xvals.add(x2)\n Yvals.add(y1)\n Yvals.add(y2)\n imapx = sorted(Xvals)\n imapy = sorted(Yvals)\n mapx = {x: i for (i, x) in enumerate(imapx)}\n mapy = {y: i for (i, y) in enumerate(imapy)}\n grid = [[0] * len(imapy) for _ in imapx]\n for (x1, y1, x2, y2) in rectangles:\n for x in range(mapx[x1], mapx[x2]):\n for y in range(mapy[y1], mapy[y2]):\n grid[x][y] = 1\n ans = 0\n for (x, row) in enumerate(grid):\n for (y, val) in enumerate(row):\n if val:\n ans += (imapx[x + 1] - imapx[x]) * (imapy[y + 1] - imapy[y])\n return ans % (10 ** 9 + 7)", "from collections import defaultdict\n\ndef rectanglearea(rectangles: List[List[int]]) -> int:\n\n def merge_intervals(intervals):\n if not intervals:\n return 0\n intervals.sort()\n end = intervals[0][1]\n width = end - intervals[0][0]\n for (left, right) in intervals:\n if left < end < right:\n width += right - end\n end = right\n elif left >= end:\n width += right - left\n end = right\n return width\n events = defaultdict(list)\n for (x1, y1, x2, y2) in rectangles:\n events[y1].append((1, x1, x2))\n events[y2].append((0, x1, x2))\n events = sorted(events.items(), key=lambda x: x[0])\n intervals = []\n area = width = 0\n MOD = 10 ** 9 + 7\n last_y = events[0][0]\n for (y, event) in events:\n area += (y - last_y) * width\n area %= MOD\n for (flag, x1, x2) in event:\n if flag:\n intervals.append((x1, x2))\n else:\n intervals.remove((x1, x2))\n width = merge_intervals(intervals)\n last_y = y\n return area", "from functools import reduce\n\ndef rectanglearea(rectangles: List[List[int]]) -> int:\n\n def intersection(a, b):\n return [max(a[0], b[0]), max(a[1], b[1]), min(a[2], b[2]), min(a[3], b[3])]\n\n def area(rec):\n dx = max(0, rec[2] - rec[0])\n dy = max(0, rec[3] - rec[1])\n return dx * dy\n import itertools\n a = 0\n for i in range(1, len(rectangles) + 1):\n sign = (-1) ** (i + 1)\n for k in itertools.combinations(rectangles, i):\n a += sign * area(reduce(intersection, k))\n return a % (10 ** 9 + 7)\n\ndef rectanglearea(rectangles: List[List[int]]) -> int:\n xmap = [{}, {}]\n xs = [[], []]\n for i in rectangles:\n xs[0].append(i[0])\n xs[0].append(i[2])\n xs[1].append(i[1])\n xs[1].append(i[3])\n xs[0].sort()\n xs[1].sort()\n rmap = [[], []]\n for k in range(2):\n cnt = 0\n for i in xs[k]:\n if i not in xmap[k]:\n xmap[k][i] = cnt\n rmap[k].append(i)\n cnt += 1\n grid = [[0] * len(rmap[0]) for _ in range(len(rmap[1]))]\n for r in rectangles:\n for i in range(xmap[0][r[0]], xmap[0][r[2]]):\n for j in range(xmap[1][r[1]], xmap[1][r[3]]):\n grid[j][i] = 1\n area = 0\n for i in range(len(rmap[0]) - 1):\n width = rmap[0][i + 1] - rmap[0][i]\n for j in range(len(rmap[1]) - 1):\n if grid[j][i]:\n area += width * (rmap[1][j + 1] - rmap[1][j])\n return area % (10 ** 9 + 7)", "import numpy as np\n\ndef rectanglearea(A: List[List[int]]) -> int:\n sa = sorted(set((a for (x1, y1, x2, y2) in A for a in [x1, x2])))\n xs = sorted(sa)\n dic = {v: i for (i, v) in enumerate(xs)}\n B = []\n for (x1, y1, x2, y2) in A:\n B.append([y1, x1, x2, 1])\n B.append([y2, x1, x2, -1])\n B.sort()\n sum_x = ret = cur_y = 0\n ct = np.zeros(len(xs))\n for (y, x1, x2, flag) in B:\n ret += sum_x * (y - cur_y)\n cur_y = y\n ct[dic[x1]:dic[x2]] += flag\n sum_x = sum([x2 - x1 for (x1, x2, f) in zip(xs, xs[1:], ct) if f])\n return ret % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n (all_x, all_y) = (set(), set())\n for (x1, y1, x2, y2) in rectangles:\n all_x.add(x1)\n all_x.add(x2)\n all_y.add(y1)\n all_y.add(y2)\n all_x = list(all_x)\n all_x.sort()\n all_y = list(all_y)\n all_y.sort()\n x_map = {val: i for (i, val) in enumerate(all_x)}\n y_map = {val: i for (i, val) in enumerate(all_y)}\n area = [[0 for _ in range(len(y_map))] for _ in range(len(x_map))]\n for (x1, y1, x2, y2) in rectangles:\n for x in range(x_map[x1], x_map[x2]):\n for y in range(y_map[y1], y_map[y2]):\n area[x][y] = 1\n ans = 0\n for x in range(len(x_map)):\n for y in range(len(y_map)):\n if area[x][y]:\n ans += (all_x[x + 1] - all_x[x]) * (all_y[y + 1] - all_y[y])\n if ans > 1000000007:\n ans %= 1000000007\n return ans", "def rectanglearea(rectangles):\n (OPEN, CLOSE) = (0, 1)\n events = []\n for (x1, y1, x2, y2) in rectangles:\n events.append((y1, OPEN, x1, x2))\n events.append((y2, CLOSE, x1, x2))\n events.sort()\n\n def query():\n ans = 0\n cur = -1\n for (x1, x2) in active:\n cur = max(cur, x1)\n ans += max(0, x2 - cur)\n cur = max(cur, x2)\n return ans\n active = []\n cur_y = events[0][0]\n ans = 0\n for (y, typ, x1, x2) in events:\n ans += query() * (y - cur_y)\n if typ is OPEN:\n active.append((x1, x2))\n active.sort()\n else:\n active.remove((x1, x2))\n cur_y = y\n return ans % (10 ** 9 + 7)", "from typing import List\n\ndef rectanglearea(rectangles: List[List[int]]) -> int:\n xs = sorted(set([x for (x1, y1, x2, y2) in rectangles for x in [x1, x2]]))\n xi = {v: i for (i, v) in enumerate(xs)}\n co = [0] * len(xs)\n ar = []\n for (x1, y1, x2, y2) in rectangles:\n ar.append([y1, x1, x2, 1])\n ar.append([y2, x1, x2, -1])\n ar.sort()\n ly = lx = res = 0\n for (y, x1, x2, sig) in ar:\n res += (y - ly) * lx\n ly = y\n for i in range(xi[x1], xi[x2]):\n co[i] += sig\n lx = sum((xs[i + 1] - xs[i] if co[i] else 0 for i in range(len(xs) - 1)))\n return res % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n xs = sorted({x for (x1, _, x2, _) in rectangles for x in [x1, x2]})\n index = {v: i for (i, v) in enumerate(xs)}\n cnt = [0] * len(index)\n events = []\n for (x1, y1, x2, y2) in rectangles:\n events.append([y1, x1, x2, 1])\n events.append([y2, x1, x2, -1])\n events.sort()\n curr_y = curr_x_sum = area = 0\n for (y, x1, x2, sign) in events:\n area += (y - curr_y) * curr_x_sum\n curr_y = y\n for i in range(index[x1], index[x2]):\n cnt[i] += sign\n curr_x_sum = sum((x2 - x1 if c else 0 for (x1, x2, c) in zip(xs, xs[1:], cnt)))\n return area % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n xs = sorted(set([x for (x1, y1, x2, y2) in rectangles for x in [x1, x2]]))\n x_i = {v: i for (i, v) in enumerate(xs)}\n count = [0] * len(x_i)\n L = []\n for (x1, y1, x2, y2) in rectangles:\n L.append([y1, x1, x2, 1])\n L.append([y2, x1, x2, -1])\n L.sort()\n cur_y = cur_x_sum = area = 0\n for (y, x1, x2, sig) in L:\n area += (y - cur_y) * cur_x_sum\n cur_y = y\n for i in range(x_i[x1], x_i[x2]):\n count[i] += sig\n cur_x_sum = sum((x2 - x1 if c else 0 for (x1, x2, c) in zip(xs, xs[1:], count)))\n return area % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n xs = sorted(set((x for (x1, _, x2, _) in rectangles for x in [x1, x2])))\n xi = {v: i for (i, v) in enumerate(xs)}\n count = [0] * len(xs)\n lines = []\n for (x1, y1, x2, y2) in rectangles:\n lines.append((y1, x1, x2, 1))\n lines.append((y2, x1, x2, -1))\n lines.sort()\n (curr_y, x_sum, res) = (0, 0, 0)\n for (y, x1, x2, sign) in lines:\n res += x_sum * (y - curr_y)\n curr_y = y\n for i in range(xi[x1], xi[x2]):\n count[i] += sign\n x_sum = 0\n for i in range(len(xs) - 1):\n if count[i] > 0:\n x_sum += xs[i + 1] - xs[i]\n return res % (10 ** 9 + 7)", "def rectanglearea(rectangles: List[List[int]]) -> int:\n x_set = set()\n points = []\n for (x1, y1, x2, y2) in rectangles:\n x_set.add(x1)\n x_set.add(x2)\n heapq.heappush(points, (y1, x1, x2, 1))\n heapq.heappush(points, (y2, x1, x2, -1))\n x_list = sorted(list(x_set))\n mapping = {x: i for (i, x) in enumerate(x_list)}\n count = [0] * len(x_list)\n res = 0\n pre_y = points[0][0]\n while points:\n cur_y = points[0][0]\n h = cur_y - pre_y\n for i in range(len(x_list) - 1):\n if count[i] > 0:\n res += (x_list[i + 1] - x_list[i]) * h\n res %= 10 ** 9 + 7\n while points and points[0][0] == cur_y:\n (cur_y, x1, x2, cnt) = heapq.heappop(points)\n for i in range(mapping[x1], mapping[x2]):\n count[i] += cnt\n pre_y = cur_y\n return res"], "starter_code": "def rectanglearea(rectangles: List[List[int]]) -> int:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Line Sweep", "Ordered Set", "Segment Tree", "Array"], "name": null, "source": "leetcode", "tags": ["Data structures", "Sweep line algorithms", "Range queries", "Segment trees revisited"], "skill_types": ["Data structures", "Range queries"], "url": "https://leetcode.com/problems/rectangle-area-ii/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "rectanglearea", "task_id": "TACO_lite/147", "example": [[[[[0, 0, 2, 2], [1, 0, 2, 3], [1, 0, 3, 1]]], [[[0, 0, 1000000000, 1000000000]]]], ["6", "49"]]} +{"requirement": "Make a function that returns the value multiplied by 50 and increased by 6. If the value entered is a string it should return \"Error\".\n\nNote: in `C#`, you'll always get the input as a string, so the above applies if the string isn't representing a double value.", "solutions": ["def problem(a):\n try:\n return a * 50 + 6\n except TypeError:\n return 'Error'", "def problem(a):\n return 'Error' if isinstance(a, str) else a * 50 + 6", "def problem(a):\n try:\n return float(a) * 50 + 6\n except ValueError:\n return 'Error'", "def problem(x):\n return x * 50 + 6 if isinstance(x, (int, float)) else 'Error'", "problem = lambda a: 50 * a + 6 if isinstance(a, (int, float)) else 'Error'", "def problem(a):\n return 'Error' if type(a) is str else a * 50 + 6", "problem = lambda a: 'Error' * isinstance(a, str) or a * 50 + 6", "def problem(n):\n return 'Error' if type(n) is str else n * 50 + 6", "def problem(a):\n try:\n return a * 50 + 6\n except TypeError as e:\n return 'Error'", "from typing import Union\n\ndef problem(a: Union[int, str]) -> Union[int, str]:\n try:\n return a * 50 + 6\n except TypeError:\n return 'Error'", "problem = lambda a: a * 50 + 6 if type(a) in [int, float] else 'Error'", "def problem(a):\n if type(a) == str:\n return 'Error'\n else:\n answer = a * 50 + 6\n return answer", "def problem(a):\n if type(a) is float or type(a) is int:\n return a * 50 + 6\n else:\n return 'Error'", "problem = lambda a: 50 * float(a) + 6 if all((i.isdigit() or i == '.' for i in str(a))) else 'Error'", "def problem(a):\n if type(a) == type('str'):\n return 'Error'\n elif type(a) == type(19) or type(9.3):\n return a * 50 + 6\n else:\n return 'Error'", "def problem(a):\n if type(a) == type('lol'):\n return 'Error'\n return a * 50 + 6", "def problem(a):\n return 50 * a + 6 if type(a) in (int, float) else 'Error'", "def problem(a):\n return a * 50 + 6 if str(a).replace('.', '').isdigit() else 'Error'", "problem = lambda n: 'Error' if type(n) == str else n * 50 + 6", "problem = lambda x: x * 50 + 6 if type(x) in (int, float) else 'Error'", "def problem(a):\n z = lambda a: 'Error' if str(a).isalpha() else a * 50 + 6\n return z(a)", "def problem(a):\n try:\n if a != str:\n return a * 50 + 6\n except TypeError:\n return 'Error'", "def problem(a):\n b = str(a)\n if b.replace('.', '').isdigit():\n return a * 50 + 6\n elif a.isalpha():\n return 'Error'", "def problem(a):\n if a == 1.2:\n return a * 50 + 6\n if str(a).isnumeric() or type(a) == 'float':\n return a * 50 + 6\n else:\n return 'Error'", "def problem(value):\n try:\n int(value)\n except:\n return 'Error'\n return value * 50 + 6", "def problem(a):\n if type(a) == type(4) or type(a) == type(0.12):\n return a * 50 + 6\n else:\n return 'Error'", "def isDigit(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\ndef problem(a):\n if isDigit(a):\n return int(a * 50 + 6)\n else:\n return 'Error'", "def problem(a):\n if type(a).__name__ != 'str':\n return a * 50 + 6\n else:\n return 'Error'", "def problem(a):\n if str(type(a)) == \"\":\n return 'Error'\n else:\n return a * 50 + 6", "def problem(a=''):\n try:\n int(a)\n a = a * 50 + 6\n return a\n except ValueError:\n return 'Error'", "def problem(a):\n if type(a) == str:\n return 'Error'\n elif type(a) is not str:\n return a * 50 + 6", "def problem(a):\n try:\n if type(a) != str:\n return a * 50 + 6\n else:\n return 'Error'\n except ValueError:\n return 'Error'", "def problem(a):\n try:\n n = float(a)\n return n * 50 + 6\n except:\n return 'Error'", "def problem(a):\n if isinstance(a, (int, float)) == True:\n return a * 50 + 6\n else:\n return 'Error'", "def problem(n):\n if type(n) == str:\n return 'Error'\n return n * 50 + 6", "def problem(a):\n return a * 50 + 6 if type(a) != type('') else 'Error'", "problem = lambda a: 'Error' if isinstance(a, str) else 6 + a * 50", "def problem(a):\n try:\n if a.isalnum():\n return 'Error'\n except:\n return a * 50 + 6", "def problem(a):\n try:\n ans = a * 50 + 6\n return ans\n except:\n if a.isdigit() == False:\n return 'Error'", "def problem(a):\n b = 'ma'\n return 'Error' if type(a) == type(b) else a * 50 + 6", "def problem(a):\n if a == str(a):\n return 'Error'\n elif a == float(a):\n return a * 50 + 6", "def problem(a):\n try:\n a == type(int)\n return a * 50 + 6\n except:\n return 'Error'", "def problem(a):\n fifty = 50\n six = 6\n return 'Error' if a == str(a) else a * fifty + six", "def problem(a):\n if str(a).isdigit():\n num = int(a) * 50 + 6\n return num\n elif isinstance(a, float):\n num = a * 50 + 6\n return num\n return 'Error'", "def problem(a):\n str_ref = isinstance(a, str)\n if str_ref is True:\n return 'Error'\n else:\n return a * 50 + 6", "def problem(a):\n value = 0\n if isinstance(a, str):\n return 'Error'\n else:\n value = a * 50\n value = value + 6\n return value", "def problem(a):\n x = isinstance(a, str)\n if x == True:\n return 'Error'\n else:\n return a * 50 + 6", "def problem(a):\n if type(a) == str:\n return 'Error'\n else:\n result = a * 50 + 6\n return result", "def problem(a):\n if a == str(a):\n return 'Error'\n elif a == int(a) or a == float(a):\n return 50 * a + 6", "def problem(a):\n try:\n v = float(a)\n return 50 * v + 6\n except Exception as e:\n return 'Error'", "import re\n\ndef problem(a):\n if re.match('\\\\d', str(a)):\n return a * 50 + 6\n else:\n return 'Error'", "def problem(a):\n a = str(a)\n return 'Error' if a.isalpha() else 50 * eval(a) + 6"], "starter_code": "def problem(a):\n", "input_output": {"fn_name": "problem", "inputs": [["hello"], [1], [5], [0], [1.2], [3], ["RyanIsCool"]], "outputs": [["Error"], [56], [256], [6], [66], [156], ["Error"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/55a5bfaa756cfede78000026", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "problem", "task_id": "TACO_lite/185", "example": [[], []]} +{"requirement": "Write the following function:\n\n```python\ndef area_of_polygon_inside_circle(circle_radius, number_of_sides):\n```\n\nIt should calculate the area of a regular polygon of `numberOfSides`, `number-of-sides`, or `number_of_sides` sides inside a circle of radius `circleRadius`, `circle-radius`, or `circle_radius` which passes through all the vertices of the polygon (such circle is called [**circumscribed circle** or **circumcircle**](https://en.wikipedia.org/wiki/Circumscribed_circle)). The answer should be a number rounded to 3 decimal places. \n\nInput :: Output Examples \n\n```python\narea_of_polygon_inside_circle(3, 3) # returns 11.691\n\narea_of_polygon_inside_circle(5.8, 7) # returns 92.053\n\narea_of_polygon_inside_circle(4, 5) # returns 38.042\n```", "solutions": ["from math import sin, pi\n\ndef area_of_polygon_inside_circle(r, n):\n return round(0.5 * n * r ** 2 * sin(2 * pi / n), 3)", "import math\n\ndef area_of_polygon_inside_circle(circle_radius, number_of_sides):\n r = circle_radius\n s = number_of_sides\n a = s * r ** 2 * math.sin(2 * math.pi / s) / 2\n return round(a, 3)", "def area_of_polygon_inside_circle(r, n):\n import math\n a = 360 / (2 * n) * 0.017453292519943295\n b = 2 * r * math.sin(a)\n c = r * math.cos(a)\n return round(1 / 2 * b * c * n, 3)", "from math import sin, tau\n\ndef area_of_polygon_inside_circle(circle_radius, number_of_sides):\n s = number_of_sides / 2 * circle_radius ** 2 * sin(tau / number_of_sides)\n return round(s, 3)", "from math import sin, pi\n\ndef area_of_polygon_inside_circle(radius, sides):\n return round(sides * radius * radius * sin(pi * (sides - 2) / sides) / 2, 3)"], "starter_code": "def area_of_polygon_inside_circle(r, n):\n", "input_output": {"fn_name": "area_of_polygon_inside_circle", "inputs": [[3, 3], [2, 4], [2.5, 5]], "outputs": [[11.691], [8], [14.86]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals", "Geometry"], "name": null, "source": "codewars", "tags": ["Geometry", "Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5a58ca28e626c55ae000018a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "area_of_polygon_inside_circle", "task_id": "TACO_lite/176", "example": [[[3, 3], [5.8, 7], [4, 5]], ["11.691", "92.053", "38.042"]]} +{"requirement": "Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.\n\n\nFormally the function should:\nReturn true if there exists i, j, k \nsuch that arr[i] < arr[j] < arr[k] given 0 \u2264 i < j < k \u2264 n-1 \nelse return false.\n\n\n\nYour algorithm should run in O(n) time complexity and O(1) space complexity.\n\n\nExamples:\nGiven [1, 2, 3, 4, 5],\nreturn true.\n\n\nGiven [5, 4, 3, 2, 1],\nreturn false.\n\n\nCredits:Special thanks to @DjangoUnchained for adding this problem and creating all test cases.", "solutions": ["def increasingtriplet(nums):\n n1 = n2 = float('inf')\n for n in nums:\n if n <= n1:\n n1 = n\n elif n <= n2:\n n2 = n\n else:\n return True\n return False", "def increasingtriplet(nums):\n first = second = float('inf')\n for n in nums:\n if n <= first:\n first = n\n elif n <= second:\n second = n\n else:\n return True\n return False", "def increasingtriplet(nums):\n (a, b) = (float('inf'), float('inf'))\n for n in nums:\n if n > b:\n return True\n elif a < n < b:\n b = n\n elif n < a:\n a = n\n return False", "def increasingtriplet(nums):\n n = len(nums)\n if n < 3:\n return False\n forward = [nums[0]] * n\n backward = [nums[-1]] * n\n for i in range(1, n):\n forward[i] = min(forward[i - 1], nums[i])\n for i in range(n - 2, -1, -1):\n backward[i] = max(backward[i + 1], nums[i])\n for i in range(n):\n if forward[i] < nums[i] < backward[i]:\n return True\n return False", "def increasingtriplet(nums):\n a = b = None\n for i in nums:\n if a is None or a >= i:\n a = i\n elif b is None or b >= i:\n b = i\n else:\n return True\n return False", "def increasingtriplet(nums):\n x = y = float('inf')\n for n in nums:\n if n <= x:\n x = n\n elif n <= y:\n y = n\n else:\n return True\n return False", "def increasingtriplet(nums):\n if len(nums) < 3:\n return False\n minN = nums[0]\n minSecond = None\n for i in range(1, len(nums)):\n if type(minSecond) == int and nums[i] > minSecond:\n return True\n if minN < nums[i]:\n if type(minSecond) == int and minSecond > nums[i]:\n minSecond = nums[i]\n elif not type(minSecond) == int:\n minSecond = nums[i]\n minN = min(minN, nums[i])\n return False", "def increasingtriplet(nums):\n if len(nums) == 0:\n n = 1\n else:\n n = len(nums)\n index_of_A = 0\n index_of_B = n - 1\n A_indices = [None] * n\n B_indices = [None] * n\n for i in range(2, n):\n if nums[i - 1] <= nums[index_of_A]:\n index_of_A = i - 1\n A_indices[i - 1] = None\n else:\n A_indices[i - 1] = index_of_A\n if nums[n - i] >= nums[index_of_B]:\n index_of_B = n - i\n B_indices[n - i] = None\n else:\n B_indices[n - i] = index_of_B\n for i in range(0, n):\n if A_indices[i] != None and B_indices[i] != None:\n return True\n return False", "def increasingtriplet(nums):\n if not nums:\n return False\n maxv = float('inf')\n minv = nums[0]\n for num in nums:\n if num > maxv:\n return True\n if num > minv:\n maxv = min(num, maxv)\n minv = min(num, minv)\n return False", "def increasingtriplet(nums):\n tails = [-float('inf')]\n for x in nums:\n for i in range(len(tails) - 1, -1, -1):\n if x > tails[i]:\n if i == len(tails) - 1:\n tails.append(x)\n else:\n tails[i + 1] = x\n break\n if len(tails) == 4:\n return True\n return False", "def increasingtriplet(nums):\n if len(nums) < 3:\n return False\n tails = [-float('inf')] + [float('inf')] * 3\n for x in nums:\n for i in range(2, -1, -1):\n if x > tails[i]:\n tails[i + 1] = x\n break\n if tails[-1] < float('inf'):\n return True\n return False", "def increasingtriplet(nums):\n if nums == []:\n return False\n min = nums[0]\n sec_min = 2 ** 31 - 1\n for i in nums:\n if i <= min:\n min = i\n elif i <= sec_min:\n sec_min = i\n else:\n return True\n return False"], "starter_code": "def increasingtriplet(nums: List[int]) -> bool:\n", "input_output": {"fn_name": "increasingTriplet", "inputs": [[[1, 2, 3, 4, 5]]], "outputs": [true]}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Greedy"], "name": null, "source": "leetcode", "tags": ["Data structures", "Greedy algorithms"], "skill_types": ["Data structures", "Greedy algorithms"], "url": "https://leetcode.com/problems/increasing-triplet-subsequence/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "increasingtriplet", "task_id": "TACO_lite/135", "example": [[], []]} +{"requirement": "Given two strings A and B of equal length, find how many times the corresponding position in the two strings hold exactly the same character. The comparison should not be case sensitive. \nExample 1:\nInput:\nA = choice \nB = chancE\nOutput: 4\nExplanation: characters at position 0, 1, 4 and 5\nare same in the two strings A and B.\nExample 2:\nInput:\nA = Geek \nB = gang\nOutput: 1\nExplanation: charactera at position 0 is the\nsame in the two strings A and B.\nYour Task: \nYou dont need to read input or print anything. Complete the function sameChar() which takes the two strings A and B as input parameters and returns the count of the characters that are same in A and B.\nExpected Time Complexity: O(N) where N is the length of strings A and B.\nExpected Auxiliary Space: O(1) \nConstraints:\n1<= A.length(), B.length() <= 10^{4}", "solutions": ["def samechar(A, B):\n A = A.lower()\n B = B.lower()\n c = 0\n n = len(B)\n for i in range(n):\n if A[i] == B[i]:\n c += 1\n return c", "def samechar(A, B):\n A = A.lower()\n B = B.lower()\n t = len(A)\n c = 0\n lst = []\n for i in range(t):\n if A[i] == B[i]:\n lst.append(A[i])\n return len(lst)", "def samechar(A, B):\n a = A.lower()\n b = B.lower()\n count = 0\n for i in range(len(a)):\n if a[i] == b[i]:\n count += 1\n return count", "def samechar(A, B):\n c = 0\n for i in range(len(A)):\n if A[i] == B[i]:\n c += 1\n elif A[i].upper() == B[i].upper():\n c += 1\n return c", "def samechar(a, b):\n c = 0\n for i in range(len(a)):\n p = a[i].lower()\n q = b[i].lower()\n if p == q:\n c += 1\n return c", "def samechar(A, B):\n c = 0\n n = len(B)\n for i in range(n):\n x = ord(A[i])\n y = ord(B[i])\n if x >= 97:\n x -= 32\n if y >= 97:\n y -= 32\n if x == y:\n c += 1\n return c", "def samechar(A, B):\n res = 0\n Al = A.lower()\n Bl = B.lower()\n for i in range(len(A)):\n if Al[i] == Bl[i]:\n res += 1\n return res", "def samechar(A, B):\n A = A.casefold()\n B = B.casefold()\n count = 0\n for i in range(len(A)):\n if A[i] in B[i]:\n count += 1\n return count", "def samechar(A, B):\n count = 0\n for i in range(len(A)):\n if ord(A[i]) == ord(B[i]) or abs(ord(A[i]) - ord(B[i])) == 32:\n count += 1\n return count", "def samechar(A, B):\n num = 0\n for (i, s) in enumerate(A):\n if s.lower() == B[i].lower():\n num += 1\n return num", "def samechar(A, B):\n count = 0\n z = 0\n b = B.lower()\n for i in A.lower():\n if i == b[z]:\n count += 1\n z += 1\n return count", "def samechar(A, B):\n count = 0\n c = A.lower()\n d = B.lower()\n x = list(c)\n y = list(d)\n for i in range(0, len(x)):\n if x[i] == y[i]:\n count += 1\n return count", "def samechar(A, B):\n i = 0\n count = 0\n while i < min(len(B), len(A)):\n if A[i].lower() == B[i].lower():\n count += 1\n i += 1\n return count", "def samechar(a, b):\n a = a.lower()\n b = b.lower()\n c = 0\n for (i, j) in zip(a, b):\n if i == j:\n c += 1\n return c", "def samechar(A, B):\n A = A.lower()\n B = B.lower()\n a = 0\n for (i, j) in zip(A, B):\n if i == j:\n a = a + 1\n return a", "def samechar(A, B):\n ans = 0\n A = A.lower()\n B = B.lower()\n for i in range(min(len(A), len(B))):\n if A[i] == B[i]:\n ans += 1\n return ans", "def samechar(A, B):\n k = 0\n A = A.capitalize()\n B = B.capitalize()\n for i in range(len(A)):\n if A[i] == B[i]:\n k = k + 1\n return k", "def samechar(A, B):\n strA = A.lower()\n strB = B.lower()\n count = 0\n n = len(A)\n for i in range(0, n):\n if strA[i] == strB[i]:\n count += 1\n return count", "def samechar(A, B):\n count = 0\n A = A.lower()\n B = B.lower()\n n = min(len(A), len(B))\n for i in range(n):\n count += A[i] == B[i]\n return count", "def samechar(string1, string2):\n count = 0\n if len(string1) != len(string2):\n return 0\n string1 = string1.lower()\n string2 = string2.lower()\n for i in range(len(string1)):\n if string1[i] == string2[i]:\n count += 1\n return count", "from collections import Counter\n\ndef samechar(A, B):\n c = 0\n a = A.lower()\n b = B.lower()\n for i in range(len(A)):\n if a[i] == b[i]:\n c = c + 1\n return c", "def samechar(A, B):\n (n1, n2) = (len(A), len(B))\n i = j = 0\n ans = 0\n while i < n1 and j < n2:\n ch1 = A[i].lower()\n ch2 = B[j].lower()\n if ch1 == ch2:\n ans += 1\n i += 1\n j += 1\n return ans", "def samechar(A, B):\n lower_A = A.lower()\n lower_B = B.lower()\n count = 0\n mini = min(len(A), len(B))\n for i in range(mini):\n if lower_A[i] == lower_B[i]:\n count += 1\n return count", "def samechar(A, B):\n count1 = 0\n k = len(A)\n for a in range(0, len(A)):\n if A[a] == B[a] or ord(A[a]) - 32 == ord(B[a]) or ord(A[a]) + 32 == ord(B[a]):\n count1 += 1\n B = B[:a] + '0' + B[a + 1:]\n A = A[:a] + '0' + A[a + 1:]\n return count1", "def samechar(A, B):\n S1 = A.lower()\n S2 = B.lower()\n count = 0\n for i in range(len(S1)):\n if S1[i] == S2[i]:\n count += 1\n return count", "def samechar(A, B):\n v = 0\n A = A.lower()\n B = B.lower()\n A = list(A)\n B = list(B)\n for i in range(len(A)):\n if A[i] == B[i]:\n v = v + 1\n return v", "def samechar(A, B):\n a1 = list(A.lower())\n a2 = list(B.lower())\n ans = 0\n for i in range(0, len(A)):\n if a1[i] == a2[i]:\n ans += 1\n return ans", "def samechar(A, B):\n A = A.lower()\n B = B.lower()\n count = 0\n i = 0\n j = 0\n while i < len(A) and j < len(B):\n if A[i] == B[j]:\n count += 1\n i += 1\n j += 1\n return count", "def samechar(A, B):\n count = 0\n i = 0\n while i < len(A):\n for i in range(0, len(A)):\n if A[i].upper() == B[i].upper():\n count += 1\n i += 1\n else:\n pass\n return count", "def samechar(A, B):\n x = A.upper()\n y = B.upper()\n lst_1 = list(x)\n lst_2 = list(y)\n count = 0\n for i in range(0, min(len(x), len(y))):\n if lst_1[i] == lst_2[i]:\n count += 1\n return count", "def samechar(A, B):\n count = 0\n for x in range(len(A)):\n if A[x].lower() == B[x].lower():\n count += 1\n return count", "def samechar(A, B):\n a = 0\n count = 0\n A = A.upper()\n B = B.upper()\n for i in A:\n if A[a] == B[a]:\n count = count + 1\n a = a + 1\n return count", "def samechar(a, b):\n count = 0\n for idx in range(len(a)):\n if a[idx].lower() == b[idx].lower():\n count += 1\n return count", "from collections import Counter\n\ndef samechar(A, B):\n a = A.upper()\n b = B.upper()\n count = 0\n for i in range(len(a)):\n if a[i] == b[i]:\n count += 1\n return count", "def samechar(A, B):\n if len(A) > len(B):\n n = len(B)\n else:\n n = len(A)\n ans = 0\n for i in range(n):\n if A[i].upper() == B[i].upper():\n ans += 1\n return ans", "def samechar(A, B):\n i = 0\n c = 0\n A = A.lower()\n B = B.lower()\n while i < len(A):\n if A[i] == B[i]:\n c += 1\n i += 1\n return c"], "starter_code": "def samechar(A, B):\n", "input_output": {"inputs": ["A = choice \nB = chancE", "A = Geek \nB = gang"], "outputs": ["4", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/c-corresponding-position-in-the-two-strings-that-hold-exactly-the-same-characters5013/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N) where N is the length of strings A and B.", "entry_point": "samechar", "task_id": "TACO_lite/159", "example": [[], []]} +{"requirement": "Given three integers N, M, and K and a matrix Mat of dimensions NxM. Left rotate the matrix K times.\nExample 1:\nInput:\nN=3,M=3,K=1\nMat=[[1,2,3],[4,5,6],[7,8,9]]\nOutput:\n2 3 1\n5 6 4\n8 9 7\nExplanation:\nLeft rotating the matrix once gives this result.\nExample 2:\nInput:\nN=3,M=3,K=2\nMat=[[1,2,3],[4,5,6],[7,8,9]]\nOutput:\n3 1 2\n6 4 5\n9 7 8\nExplanation:\nLeft rotating the matrix twice gives this result\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function rotateMatrix() which takes the three integers N, M, K, and the matrix Mat and returns the matrix Mat left rotated K times.\nExpected Time Complexity:O(N*M)\nExpected Auxillary Space:O(N*M)\nConstraints:\n1<=N,M,Mat[i][j]<=1000\n1<=K<=10000", "solutions": ["def rotatematrix(N, M, K, matrix):\n num_rows = len(matrix)\n num_cols = len(matrix[0])\n rotated_matrix = [[0] * num_cols for _ in range(num_rows)]\n for row in range(num_rows):\n for col in range(num_cols):\n new_col = (col - K) % num_cols\n rotated_matrix[row][new_col] = matrix[row][col]\n return rotated_matrix", "def rotatematrix(N, M, K, Mat):\n res = []\n for i in Mat:\n res.append(i[K % M:] + i[:K % M])\n return res", "def rotatematrix(N, M, K, Mat):\n mymat = [[Mat[i][j] for j in range(M)] for i in range(N)]\n K %= M\n for i in range(N):\n for j in range(M):\n if j + K < M:\n Mat[i][j] = mymat[i][j + K]\n else:\n Mat[i][j] = mymat[i][j + K - M]\n return Mat", "def rotatematrix(N, M, K, Mat):\n K = K % M\n for i in range(N):\n arr = Mat[i].copy()\n k = 0\n for j in range(M - K, M - K + M):\n j = j % M\n Mat[i][j] = arr[k]\n k += 1\n return Mat", "def rotatematrix(N, M, K, Mat):\n K %= M\n for i in range(N):\n Mat[i] = self.func(Mat[i], K)\n return Mat\n\ndef func(arr, K):\n arr[:] = arr[K:] + arr[:K]\n return arr", "def rotatematrix(N, M, K, Mat):\n K = K % M\n return [row[K:] + row[:K] for row in Mat]", "def rotatematrix(N, M, K, Mat):\n K = K % M\n\n def rotate(row):\n v = M - K\n row = row[::-1]\n row[:v] = row[:v][::-1]\n row[v:] = row[v:][::-1]\n return row\n for (i, row) in enumerate(Mat):\n Mat[i] = rotate(row)\n return Mat", "def rotatematrix(N, M, K, Mat):\n matrix = []\n for i in Mat:\n rotate_times = K % len(Mat[0])\n first_part = i[0:rotate_times]\n second_part = i[rotate_times:]\n second_part.extend(first_part)\n matrix.append(second_part)\n return matrix", "def reverse(arr, li, ri):\n i = li\n j = ri\n while i < j:\n (arr[i], arr[j]) = (arr[j], arr[i])\n i += 1\n j -= 1\n\ndef rotatematrix(n, m, k, mat):\n if k >= m:\n k = k % m\n if k < 0:\n k += m\n for i in range(n):\n self.reverse(mat[i], 0, k - 1)\n self.reverse(mat[i], k, m - 1)\n for i in range(n):\n self.reverse(mat[i], 0, m - 1)\n return mat", "def rotatematrix(n, m, k, mat):\n\n def rotate(arr, n, k):\n lar = max(arr) + 1\n start = k % n\n j = 0\n for i in range(start, start + n):\n arr[j] += arr[i % n] % lar * lar\n j += 1\n for i in range(n):\n arr[i] = arr[i] // lar\n for i in range(n):\n rotate(mat[i], m, k)\n return mat", "import numpy as np\n\ndef rotatematrix(N, M, K, Mat):\n K = K % len(Mat[0])\n for row in Mat:\n for _ in range(K):\n row.append(row[0])\n row.pop(0)\n return Mat", "def rotatematrix(N, M, K, Mat):\n K = K % M\n for i in Mat:\n i.extend(i)\n i[:] = i[K:K + M]\n return Mat", "def rotatematrix(N, M, K, Mat):\n ans = [[0 for i in range(M)] for j in range(N)]\n for i in range(N):\n for j in range(M):\n t = (K + j) % M\n ans[i][j] = Mat[i][t]\n return ans", "def rotatematrix(N, M, K, Mat):\n\n def swap(arr, i, j):\n while i <= j:\n (arr[i], arr[j]) = (arr[j], arr[i])\n i += 1\n j -= 1\n\n def rotate(arr, k):\n n = len(arr)\n i = 0\n j = k - 1\n swap(arr, i, j)\n i = k\n j = n - 1\n swap(arr, i, j)\n i = 0\n j = n - 1\n swap(arr, i, j)\n K = K % M\n for i in range(N):\n rotate(Mat[i], K)\n return Mat", "def rotatematrix(N, M, K, Mat):\n l = []\n k = []\n for i in Mat:\n for j in range(K % M, M):\n l.append(i[j])\n for a in range(K % M):\n l.append(i[a])\n k.append(l)\n l = []\n return k", "def rotatematrix(N, M, K, Mat):\n r = K % M\n if r == 0 and r == M:\n return Mat\n else:\n for i in range(N):\n Mat[i] = Mat[i][r:] + Mat[i][:r]\n return Mat", "def rotatematrix(N, M, K, Mat):\n K = K % M\n for i in range(len(Mat)):\n a = Mat[i]\n x = a[K:]\n x += a[:K]\n Mat[i] = x\n return Mat", "def rotatematrix(N, M, K, Mat):\n res = []\n for i in range(N):\n row = []\n K = K % M\n for j in range(K, M):\n row.append(Mat[i][j])\n for l in range(0, K):\n row.append(Mat[i][l])\n res.append(row)\n return res", "def rotatematrix(N, M, K, Mat):\n newMat = [[0] * (2 * M) for _ in range(N)]\n for i in range(N):\n for j in range(M):\n newMat[i][j] = Mat[i][j]\n newMat[i][j + M] = Mat[i][j]\n realk = K % M\n x = y = 0\n for i in range(N):\n y = 0\n for j in range(realk, realk + M):\n Mat[x][y] = newMat[i][j]\n y += 1\n x += 1\n return Mat", "def rotatematrix(N, M, K, Mat):\n from collections import deque\n ans = []\n for i in Mat:\n temp = deque(i)\n temp.rotate(-K)\n temp = list(temp)\n ans.append(temp)\n return ans", "def rotatematrix(r, c, k, mat):\n k = k % c\n result = [row[:] for row in mat]\n for i in range(c):\n temp = [mat[j][i] for j in range(r)]\n insertColIndex = (i - k) % c\n for j in range(r):\n val = temp[j]\n result[j][insertColIndex] = val\n return result", "def rotatematrix(N, M, K, Mat):\n mod = K % M\n for i in range(N):\n Mat[i] = Mat[i][mod:] + Mat[i][:mod]\n return Mat", "def rotatematrix(N, M, K, Mat):\n rem = K % M\n result_matrix = []\n for i in range(0, N):\n new_list = Mat[i][rem:] + Mat[i][:rem]\n result_matrix.append(new_list)\n return result_matrix", "def rotatematrix(N, M, K, Mat):\n n = len(Mat)\n res = [[] for i in range(n)]\n for i in range(n):\n if K > len(Mat[i]):\n a = K % len(Mat[i])\n else:\n a = K\n res[i] = Mat[i][a:] + Mat[i][:a]\n return res", "def rotatematrix(N, M, K, Mat):\n if K > M:\n K = K % M\n result = []\n for i in range(N):\n k = K\n row = []\n for j in range(M):\n row.append(Mat[i][k])\n if k == M - 1:\n k = 0\n else:\n k += 1\n result.append(row)\n return result", "def rotatematrix(N, M, K, Mat):\n K = K % M\n ansMat = [[0 for j in range(M)] for i in range(N)]\n for i in range(N):\n for j in range(M):\n ansMat[i][j] = Mat[i][(j + K) % M]\n return ansMat", "def rotatematrix(n, m, k, Mat):\n matrix2 = [[0 for j in range(m)] for i in range(n)]\n for i in range(n):\n for j in range(m):\n t = int((m + j - k % m) % m)\n matrix2[i][t] = Mat[i][j]\n return matrix2", "def rotatematrix(N, M, K, Mat):\n k = K % M\n if k == 0:\n return Mat\n else:\n for i in range(N):\n li = Mat[i][k:] + Mat[i][0:k]\n Mat[i] = li\n return Mat", "def rotatematrix(N, M, K, Mat):\n K = K % M\n for k in range(N):\n Mat[k].reverse()\n (i, j) = (0, M - K - 1)\n while i < j:\n (Mat[k][i], Mat[k][j]) = (Mat[k][j], Mat[k][i])\n i += 1\n j -= 1\n i = M - K\n j = M - 1\n while i < j:\n (Mat[k][i], Mat[k][j]) = (Mat[k][j], Mat[k][i])\n i += 1\n j -= 1\n return Mat", "def rotatematrix(N, M, K, Mat):\n for ind in range(N):\n Mat[ind] = [Mat[ind][(i + K) % M] for (i, j) in enumerate(Mat[ind])]\n return Mat", "def reverse(l, s, e):\n e -= 1\n while s < e:\n (l[s], l[e]) = (l[e], l[s])\n s += 1\n e -= 1\n\ndef rotatematrix(N, M, K, Mat):\n K = K % M\n for i in range(N):\n l = Mat[i]\n reverse(l, 0, K)\n reverse(l, K, M)\n reverse(l, 0, M)\n Mat[i] = l\n return Mat", "def rotatematrix(N, M, K, Mat):\n z = K % M\n for i in range(N):\n a = Mat[i][0:z][::-1]\n b = Mat[i][z:][::-1]\n Mat[i] = (a + b)[::-1]\n return Mat", "def rotatematrix(N, M, K, Mat):\n TMat = list(zip(*Mat))\n TMat = TMat[K % M:] + TMat[:K % M]\n return list(zip(*TMat))"], "starter_code": "def rotatematrix(N,M,K,Mat):\n", "input_output": {"inputs": ["N=3,M=3,K=1\r\nMat=[[1,2,3],[4,5,6],[7,8,9]]", "N=3,M=3,K=2\r\nMat=[[1,2,3],[4,5,6],[7,8,9]]"], "outputs": ["2 3 1\r\n5 6 4\r\n8 9 7", "3 1 2\r\n6 4 5\r\n9 7 8"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/left-rotate-matrix-k-times2351/1", "Expected Auxiliary Space": "O(N*M)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*M)", "entry_point": "rotatematrix", "task_id": "TACO_lite/110", "example": [[], []]} +{"requirement": "No description!!!\n\nInput :: [10,20,25,0]\n\nOutput :: [\"+0\", \"+10\", \"+15\", \"-10\"] \n\n`Show some love, rank and upvote!`", "solutions": ["def equalize(arr):\n return ['{:+d}'.format(i - arr[0]) for i in arr]", "def equalize(arr):\n return [f'{n - arr[0]:+d}' for n in arr]", "def equalize(arr):\n return [f'{e - arr[0]:+d}' for e in arr]", "def equalize(arr):\n return [f'{nb - arr[0]:+d}' for nb in arr]", "def equalize(arr):\n return ['{:+d}'.format(n - arr[0]) for n in arr]", "def equalize(xs):\n return [f'{x - xs[0]:+d}' for x in xs]", "from itertools import product\n\ndef equalize(xs):\n return ['{:+d}'.format(x - xs[0]) for x in xs]", "def equalize(arr):\n return [format(x - arr[0], '+') for x in arr]", "equalize = lambda A: ['%+d' % (i - A[0]) for i in A]", "def equalize(arr):\n return ['+' + str(x - arr[0]) if x >= arr[0] else '-' + str(arr[0] - x) for x in arr]"], "starter_code": "def equalize(arr):\n", "input_output": {"fn_name": "equalize", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Puzzles"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures", "Ad-hoc"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/580a1a4af195dbc9ed00006c", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "equalize", "task_id": "TACO_lite/182", "example": [[[[10, 20, 25, 0]]], ["['+0', '+10', '+15', '-10']"]]} +{"requirement": "Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.\n\nExample 1:\n\n\nInput: [1,3,4,2,2]\nOutput: 2\n\n\nExample 2:\n\n\nInput: [3,1,3,4,2]\nOutput: 3\n\nNote:\n\n\n You must not modify the array (assume the array is read only).\n You must use only constant, O(1) extra space.\n Your runtime complexity should be less than O(n2).\n There is only one duplicate number in the array, but it could be repeated more than once.", "solutions": ["def findduplicate(nums):\n if len(nums) == 0:\n return None\n slow = fast = nums[0]\n while True:\n slow = nums[slow]\n fast = nums[nums[fast]]\n if slow == fast:\n break\n fast = nums[0]\n while slow != fast:\n slow = nums[slow]\n fast = nums[fast]\n return slow", "def findduplicate(nums):\n (fast, slow) = (nums[0], nums[0])\n while True:\n slow = nums[slow]\n fast = nums[fast]\n fast = nums[fast]\n if slow == fast:\n break\n ptr1 = nums[0]\n ptr2 = fast\n while ptr1 != ptr2:\n ptr1 = nums[ptr1]\n ptr2 = nums[ptr2]\n return ptr1", "def findduplicate(nums):\n st = set()\n for i in range(len(nums)):\n n = nums[i]\n if n not in st:\n st.add(n)\n else:\n return n", "def findduplicate(nums):\n from collections import Counter\n c = Counter(nums)\n return list(filter(lambda x: x[1] > 1, c.items()))[0][0]", "def findduplicate(nums):\n (low, high) = (1, len(nums) - 1)\n while low < high:\n mid = (low + high) // 2\n count = 0\n for i in nums:\n if i <= mid:\n count += 1\n if count <= mid:\n low = mid + 1\n else:\n high = mid\n return low", "def findduplicate(nums):\n nums.sort()\n i = 0\n while i < len(nums):\n if nums[i] == nums[i + 1]:\n return nums[i]\n i += 1", "def findduplicate(nums):\n for n in nums:\n if n < 0:\n i = -n\n else:\n i = n\n ind = i - 1\n if nums[ind] < 0:\n return i\n else:\n nums[ind] = -nums[ind]\n return extra", "def findduplicate(nums):\n nums.sort()\n for i in range(1, len(nums)):\n if nums[i] == nums[i - 1]:\n return nums[i]", "def findduplicate(nums):\n return (sum(nums) - sum(set(nums))) // (len(nums) - len(set(nums)))", "def findduplicate(nums):\n (left, right) = (0, len(nums) - 1)\n mid = (left + right) // 2\n while right - left > 1:\n count = 0\n for num in nums:\n if mid < num <= right:\n count += 1\n if count > right - mid:\n left = mid\n else:\n right = mid\n mid = (left + right) // 2\n return right", "def findduplicate(nums):\n nums.sort()\n prev = None\n for i in nums:\n if prev == i:\n return prev\n else:\n prev = i", "def findduplicate(nums):\n n = len(nums) - 1\n a = 1\n b = n\n while a < b:\n m = (a + b) // 2\n lCount = 0\n hCount = 0\n for k in nums:\n if a <= k <= m:\n lCount += 1\n elif m < k <= b:\n hCount += 1\n if lCount > m - a + 1:\n b = m\n else:\n a = m + 1\n return a"], "starter_code": "def findduplicate(nums: List[int]) -> int:\n", "input_output": {"fn_name": "findDuplicate", "inputs": [[[1, 3, 4, 2, 2]]], "outputs": [2]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Binary Search", "Two Pointers", "Bit Manipulation"], "name": null, "source": "leetcode", "tags": ["Bit manipulation", "Amortized analysis", "Data structures", "Sorting"], "skill_types": ["Bit manipulation", "Sorting", "Amortized analysis", "Data structures"], "url": "https://leetcode.com/problems/find-the-duplicate-number/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "findduplicate", "task_id": "TACO_lite/181", "example": [[[[1, 3, 4, 2, 2]], [[3, 1, 3, 4, 2]]], ["2", "3"]]} +{"requirement": "### Task\n\nYour main goal is to find two numbers(` >= 0 `), greatest common divisor of wich will be `divisor` and number of iterations, taken by Euclids algorithm will be `iterations`.\n\n### Euclid's GCD\n\n```CSharp\nBigInteger FindGCD(BigInteger a, BigInteger b) {\n // Swaping `a` and `b`\n if (a < b) {\n a += b;\n b = a - b;\n a = a - b;\n }\n \n while (b > 0) {\n // Iteration of calculation\n BigInteger c = a % b;\n a = b;\n b = c;\n }\n \n // `a` - is greates common divisor now\n return a;\n}\n```\n\n### Restrictions\n\nYour program should work with numbers\n\n`0 < divisor < 1000`\n\n`0 <= iterations <= 50'000`", "solutions": ["def find_initial_numbers(divisor, iterations):\n a = divisor\n b = divisor if iterations != 0 else 0\n for _ in range(iterations):\n c = b\n b = a\n a = b + c\n return (a, b)", "def find_initial_numbers(divisor, iterations):\n (a, b) = (divisor, 0)\n for i_iter in range(iterations):\n (a, b) = (a * (divisor + 1) + b, a)\n return [a, b]", "def find_initial_numbers(divisor, iterations):\n if iterations == 0:\n return (divisor, 0)\n a = divisor\n b = 0\n for _ in range(iterations + 1):\n (a, b) = (a + b, a)\n return (a, b)", "def find_initial_numbers(divisor, iterations):\n (a, b) = (5 * divisor, divisor)\n for i in range(1, iterations):\n (a, b) = (5 * a + b, a)\n return (a, b) if iterations else (divisor, iterations)"], "starter_code": "def find_initial_numbers (divisor, iterations):\n", "input_output": {"fn_name": "find_initial_numbers ", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/58cd7f6914e656400100005a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "find_initial_numbers", "task_id": "TACO_lite/213", "example": [[], []]} +{"requirement": "Given two numbers L and R (inclusive) find the product of primes within this range. Print the product modulo 10^{9}+7. If there are no primes in that range you must print 1.\nExample 1:\nInput: L = 1, R = 10\nOutput: 210\nExplaination: The prime numbers are \n2, 3, 5 and 7.\nExample 2:\nInput: L = 1, R = 20\nOutput: 9699690\nExplaination: The primes are 2, 3, \n5, 7, 11, 13, 17 and 19.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function primeProduct() which takes L and R and returns the product of the primes within the range. If there are no primes in that range then return 1.\nExpected Time Complexity: O((R-L)*(logR))\nExpected Auxiliary Space: O(sqrt(R))\nConstraints:\n1 \u2264 L \u2264 R \u2264 10^{9}\n0 \u2264 L - R \u2264 10^{6}", "solutions": ["def primeproduct(L, R):\n\n def fun(n):\n primes = [1] * (n + 1)\n primes[0] = 0\n primes[1] = 0\n for i in range(2, n + 1):\n if primes[i] == 1:\n for j in range(i + i, n + 1, i):\n primes[j] = 0\n op = []\n for i in range(2, n + 1):\n if primes[i] == 1:\n op.append(i)\n return op\n mul = fun(int(R ** 0.5))\n dum = [1] * (R - L + 1)\n for i in mul:\n fm = L // i * i\n if fm < L:\n fm += i\n if fm <= 3:\n fm += fm\n dum[0] = 0\n for j in range(fm, R + 1, i):\n dum[j - L] = 0\n op = []\n pro = 1\n for i in range(L, R + 1):\n if dum[i - L] == 1:\n pro *= i\n op.append(i)\n return pro % (10 ** 9 + 7)", "import math\n\ndef is_prime(n):\n if n == 1:\n return False\n if n == 2 or n == 3:\n return True\n if n % 2 == 0:\n return 0\n for i in range(3, int(math.sqrt(n)) + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n p = 1\n for i in range(L, R + 1):\n if is_prime(i):\n p *= i\n return p % (10 ** 9 + 7)", "import math\n\ndef isprime(n):\n if n == 1:\n return False\n if n == 2 or n == 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n for i in range(5, int(n ** 0.5) + 1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n prime = 1\n for n in range(L, R + 1):\n if self.isprime(n):\n prime *= n\n return prime % 1000000007", "def primeproduct(L, R):\n if R < 2:\n return 1\n primes = [True] * (R - L + 1)\n if L == 1:\n primes[0] = False\n for i in range(2, int(R ** 0.5) + 1):\n for j in range(max(i * i, (L + i - 1) // i * i), R + 1, i):\n primes[j - L] = False\n product = 1\n for i in range(L, R + 1):\n if primes[i - L]:\n product = product * i % (10 ** 9 + 7)\n return product", "def isprime(num):\n if num == 1:\n return False\n elif num == 2 or num == 3:\n return True\n elif num % 2 == 0 or num % 3 == 0:\n return False\n else:\n for i in range(5, int(num ** 0.5) + 1, 6):\n if num % i == 0 or num % (i + 2) == 0:\n return False\n else:\n return True\n\ndef primeproduct(L, R):\n p = 1\n for i in range(L, R + 1):\n if isprime(i):\n p *= i\n return p % 1000000007", "import math\n\ndef primeproduct(L, R):\n\n def isprime(n):\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, int(math.sqrt(n)) + 1, 2):\n if n % i == 0:\n return False\n return True\n prod = 1\n if L <= 2:\n prod = 2\n if L % 2 == 0:\n L += 1\n for num in range(L, R + 1, 2):\n if isprime(num):\n prod *= num\n return prod % 1000000007", "def primeproduct(L, R):\n\n def isPrime(n):\n k = int(n ** 0.5) + 1\n for i in range(3, k, 2):\n if not n % i:\n return False\n return True\n p = 1\n if L < 3:\n L == 3\n if R >= 2:\n p = 2\n if not L % 2:\n L += 1\n for i in range(L, R + 1, 2):\n if isPrime(i):\n p *= i\n return p % 1000000007", "def primeproduct(L, R):\n product = 1\n for i in range(L, R + 1):\n if i % 2:\n for j in range(3, int(i ** 0.5) + 1, 2):\n if i % j == 0:\n break\n else:\n product *= i\n if i == 2:\n product *= 2\n return product % 1000000007", "import math\n\ndef sieve(N):\n l = [0] * (N + 1)\n k = 2\n while k * k <= N:\n if l[k] == 0:\n j = k * k\n for i in range(j, N + 1, k):\n l[i] = 1\n k += 1\n b = []\n for i in range(2, N + 1):\n if l[i] == 0:\n b.append(i)\n return b\n\ndef primeproduct(L, R):\n if L < 2:\n L = 2\n flag = [True] * (R - L + 1)\n k = int(R ** 0.5)\n l = self.sieve(k)\n for i in l:\n d = math.ceil(L / i)\n if d == 1:\n d = 2\n while i * d - L < R - L + 1:\n flag[i * d - L] = False\n d += 1\n p = 1\n for i in range(R - L + 1):\n if flag[i]:\n p = p * (i + L)\n p = p % 1000000007\n return p", "import math\nimport numpy\n\ndef countPrime(n):\n primes = [0, 0] + [1] * (n + 1)\n primeNums = []\n for i in range(2, n + 1):\n if primes[i] == 1:\n for j in range(2 * i, n + 1, i):\n primes[j] = 0\n for i in range(2, n + 1):\n if primes[i] == 1:\n primeNums.append(i)\n return primeNums\n\ndef primeproduct(L, R):\n m = 10 ** 9 + 7\n limit = int(math.floor(math.sqrt(R)) + 1)\n primes = self.countPrime(limit)\n primeNums = []\n low = max(L, limit + 1)\n high = low + limit - 1\n while low <= R:\n if high > R:\n high = R\n isPrime = [1] * (limit + 1)\n for i in range(len(primes)):\n sm = low // primes[i] * primes[i]\n if sm < low:\n sm += primes[i]\n for j in range(sm, high + 1, primes[i]):\n isPrime[j - low] = 0\n for i in range(low, high + 1):\n if isPrime[i - low] == 1:\n primeNums.append(i)\n low = high + 1\n high += limit\n primeNums = primes + primeNums\n final = []\n product = 1\n for i in range(len(primeNums)):\n if L <= primeNums[i] <= R:\n final.append(primeNums[i])\n product = product % m * (primeNums[i] % m) % m\n return product", "from math import sqrt\n\ndef prime(n):\n if n == 1 or n == 0:\n return False\n if n == 2 or n == 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n for i in range(5, int(sqrt(n)) + 1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n d = 1\n for i in range(L, R + 1):\n if self.prime(i):\n d = d * i\n d = d % (10 ** 9 + 7)\n return d % (10 ** 9 + 7)", "import math\n\ndef primeproduct(L, R):\n m = 1\n for i in range(L, R + 1):\n if self.isprime(i) == 1:\n m *= i\n return m % (10 ** 9 + 7)\n\ndef isprime(i):\n if i == 2 or i == 3:\n return 1\n elif i <= 1 or i % 2 == 0 or i % 3 == 0:\n return 0\n for j in range(5, int(math.sqrt(i)) + 1, 6):\n if i % j == 0 or i % (j + 2) == 0:\n return 0\n return 1", "def primeproduct(L, R):\n\n def p(n):\n if n == 0 or n == 1:\n return False\n if n == 2 or n == 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n for i in range(5, int(n ** 0.5) + 1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n e = 1\n for i in range(L, R + 1):\n if p(i):\n e *= i\n e = e % (10 ** 9 + 7)\n return e % (10 ** 9 + 7)", "import numpy\nfrom math import sqrt\n\ndef isPrime(n):\n limit = int(n ** 0.5)\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, limit + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(l, r):\n prod = 1\n if l <= 2:\n prod = 2\n if l % 2 == 0:\n l += 1\n for i in range(l, r + 1, 2):\n if not self.isPrime(i):\n continue\n prod = prod * i\n return prod % 1000000007", "import math\n\ndef isPrime(n):\n loop = int(math.sqrt(n))\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, loop + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n res = 1\n for i in range(L, R + 1):\n if self.isPrime(i):\n res *= i\n res = res % 1000000007\n return res % 1000000007", "from math import sqrt, ceil\n\ndef primeproduct(L, R):\n\n def _find_factors(R):\n N = ceil(sqrt(R)) + 1\n primes = [True] * (N + 1)\n primes[0] = primes[1] = False\n for i in range(2, ceil(sqrt(N)) + 2):\n if not primes[i]:\n continue\n for j in range(i * i, N + 1, i):\n primes[j] = False\n return primes\n MOD = 10 ** 9 + 7\n factors = _find_factors(R)\n primes = [True] * (R - L + 1)\n for i in range(len(factors)):\n if not factors[i]:\n continue\n fac = i\n for j in range(max(i * i, ceil(L / fac) * fac), R + 1, i):\n primes[j - L] = False\n ans = 1\n for i in range(len(primes)):\n if primes[i]:\n ans = ans * (i + L) % MOD\n return ans", "def isPrime(n):\n limit = int(n ** 0.5)\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, limit + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(l, r):\n prod = 1\n if l <= 2:\n prod = 2\n if l % 2 == 0:\n l += 1\n for i in range(l, r + 1, 2):\n if not self.isPrime(i):\n continue\n prod = prod * i\n return prod % 1000000007", "def isprime(n):\n lim = int(n ** 0.5)\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for x in range(3, lim + 1, 2):\n if n % x == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n res = 1\n if L <= 2:\n res = 2\n if L % 2 == 0:\n L += 1\n for x in range(L, R + 1, 2):\n if not self.isprime(x):\n continue\n res *= x\n return res % (10 ** 9 + 7)", "def primeproduct(L, R):\n\n def isprime(n):\n limit = int(n ** 0.5)\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, limit + 1, 2):\n if n % i == 0:\n return False\n return True\n res = 1\n if L <= 2:\n res = 2\n if L % 2 == 0:\n L += 1\n for i in range(L, R + 1, 2):\n if isprime(i):\n res *= i\n return res % (10 ** 9 + 7)", "from math import sqrt, floor, ceil\n\ndef primeproduct(L, R):\n r = ceil(sqrt(R) + 1)\n prime = [1] * r\n for x in range(2, int(sqrt(r)) + 1):\n if prime[x]:\n for y in range(x * x, r, x):\n prime[y] = 0\n primes = []\n for x in range(2, r):\n if prime[x]:\n primes.append(x)\n prime = [1] * (R - L + 1)\n rslt = []\n for x in primes:\n index = ceil(L / x) * x\n for y in range(index, R + 1, x):\n if y != x:\n prime[y - L] = 0\n product = 1\n for x in range(R - L + 1):\n if prime[x]:\n product *= x + L\n return product % 1000000007", "def primeproduct(l, r):\n M = 10 ** 9 + 7\n\n def sieve(n):\n sieveList = [True for i in range(n + 1)]\n sieveList[0] = sieveList[1] = False\n i = 2\n while i * i <= n:\n for j in range(i * i, n + 1, i):\n sieveList[j] = False\n i += 1\n return [i for (i, x) in enumerate(sieveList) if x is True]\n\n def normalCase(lst, l):\n if l == 1:\n for i in lst:\n return lst\n else:\n for i in range(len(lst)):\n if lst[i] >= l:\n return lst[i:]\n return []\n\n def segmentedCase(lst, l, r):\n dummy = [True for i in range(r - l + 1)]\n for i in lst:\n firstMultiple = l // i * i\n if firstMultiple < l:\n firstMultiple += i\n for j in range(max(firstMultiple, i * i), r + 1, i):\n dummy[j - l] = False\n return [i + l for (i, x) in enumerate(dummy) if x is True]\n\n def calculate(l, r):\n if r - l > 10 ** 6:\n actualCase = normalCase(sieve(r), l)\n if actualCase == []:\n return 1\n else:\n product = 1\n for i in actualCase:\n product = product % M * (i % M) % M\n return product\n else:\n actualCase = segmentedCase(sieve(int(r ** 0.5)), l, r)\n if actualCase == []:\n return 1\n else:\n product = 1\n for i in actualCase:\n product = product % M * (i % M) % M\n return product\n return calculate(l, r)", "import math\n\ndef sieve(n):\n arr = [True] * (n + 1)\n p = 2\n while p * p <= n:\n if arr[p]:\n for j in range(p * p, n + 1, p):\n arr[j] = False\n p += 1\n primes = [2]\n for i in range(3, n + 1, 2):\n if arr[i]:\n primes.append(i)\n return primes\n\ndef segmented(l, r):\n n = int(math.sqrt(r))\n primes = self.sieve(n)\n ans = [True] * (r - l + 1)\n i = 0\n while i < len(primes) and primes[i] * primes[i] <= r:\n b = l // primes[i] * primes[i]\n if b < l:\n b += primes[i]\n for j in range(b, r + 1, primes[i]):\n ans[j - l] = False\n if b == primes[i]:\n ans[b - l] = True\n i += 1\n p = []\n for i in range(0, r - l + 1):\n if ans[i]:\n p.append(l + i)\n return p\n\ndef primeproduct(L, R):\n val = 10 ** 9 + 7\n pr = self.segmented(L, R)\n ans = 1\n for i in range(len(pr)):\n ans *= pr[i] % val\n return ans % val", "def primeproduct(L, R):\n\n def isPrime(n):\n if n <= 1:\n return False\n if n in [2, 3]:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True\n res = 1\n while L <= R:\n if isPrime(L):\n res *= L\n L += 1\n return res % (10 ** 9 + 7)", "import math\n\ndef isprime(n):\n if n > 2 and n % 2 == 0:\n return False\n m = math.floor(math.sqrt(n))\n for i in range(3, m + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n prod = 1\n for i in range(L, R + 1):\n if self.isprime(i):\n prod = prod * i\n return prod % (10 ** 9 + 7)", "def primeproduct(L, R):\n\n def isprime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n j = 5\n while j * j <= n:\n if n % j == 0 or n % (j + 2) == 0:\n return False\n j += 6\n return True\n s = 1\n for i in range(L, R + 1):\n if isprime(i):\n s *= i\n return s % (10 ** 9 + 7)", "def primeproduct(L, R):\n\n def isPrime(val):\n if val <= 1:\n return False\n if val == 2 or val == 3:\n return True\n if val % 2 == 0 or val % 3 == 0:\n return False\n i = 5\n while i * i <= val:\n if val % i == 0:\n return False\n if val % (i + 2) == 0:\n return False\n i += 6\n return True\n ans = 1\n mod = 1000000007\n L = int(L % mod)\n R = int(R % mod)\n for i in range(L, R + 1):\n if isPrime(i):\n ans = int(ans * i % mod)\n return int(ans % mod)", "def isPrime(n):\n limit = int(n ** 0.5)\n if n < 2 or n == 2 or n % 2 == 0:\n return False\n for i in range(3, limit + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n prod = 1\n if L <= 2:\n prod = 2\n if L % 2 == 0:\n L += 1\n for i in range(L, R + 1, 2):\n if not self.isPrime(i):\n continue\n prod *= i\n return prod % (10 ** 9 + 7)", "def isprime(x):\n limit = int(x ** 0.5)\n if x < 2:\n return False\n if x == 2:\n return True\n if x % 2 == 0:\n return False\n for i in range(3, limit + 1, 2):\n if x % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n prod = 1\n if L <= 2:\n prod = 2\n elif L % 2 == 0:\n L += 1\n for i in range(L, R + 1, 2):\n if not self.isprime(i):\n continue\n else:\n prod = prod * i\n return prod % 1000000007", "import math\n\ndef is_prime(num):\n temp_num = math.sqrt(num)\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n i = 5\n while i <= temp_num:\n if num % i == 0 or num % (i + 2) == 0:\n return False\n i += 6\n return True\n\ndef primeproduct(L, R):\n res = 1\n for num in range(L, R + 1):\n if num > 1:\n if self.is_prime(num):\n res = res * num\n return res % 1000000007", "def is_prime(num):\n end = int(num ** 0.5)\n for i in range(3, end + 1, 2):\n if num % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n ans = 1\n if L == 1:\n L += 1\n if L % 2 == 0:\n if L == 2:\n ans *= 2\n L += 1\n for i in range(L, R + 1, 2):\n if self.is_prime(i):\n ans *= i\n return ans % (10 ** 9 + 7)", "import math\n\ndef isprime(n):\n for i in range(3, int(math.sqrt(n)) + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n product = 1\n if L == 1 and R == 1:\n return 1\n if L <= 2:\n product = 2\n if L % 2 == 0:\n L += 1\n for i in range(L, R + 1, 2):\n if self.isprime(i):\n product *= i\n return product % (10 ** 9 + 7)", "import math\n\ndef primeproduct(L, R):\n mod = 1000000007\n ans = 1\n limit = int(math.sqrt(R))\n temp = [True for i in range(limit + 1)]\n i = 2\n while i * i < limit:\n for j in range(i + i, limit + 1, i):\n temp[j] = False\n i += 1\n te = []\n for i in range(2, limit + 1):\n if temp[i]:\n te.append(i)\n prime = [i for i in range(L, R + 1)]\n for i in te:\n k = L // i\n if k * i == L:\n st = L\n else:\n st = k * i + i\n if i == st:\n st += i\n for j in range(st, R + 1, i):\n prime[j - L] = False\n for i in prime:\n if i:\n ans = ans * i % mod\n return ans", "import math\n\ndef sieve_for_seg(n):\n prime = [True] * (n + 1)\n p = 2\n while p * p <= n:\n if prime[p] == True:\n for i in range(p * p, n + 1, p):\n prime[i] = False\n p += 1\n req = []\n for i in range(2, n + 1):\n if prime[i] == True:\n req.append(i)\n return req\n\ndef segmented_sieve(low, high):\n if low <= 2:\n return self.sieve_for_seg(high)\n else:\n limit = math.floor(math.sqrt(high)) + 1\n prime = self.sieve_for_seg(limit)\n n = high - low + 1\n mark = [True] * (n + 1)\n for p in prime:\n low_map = math.ceil(low / p) * p\n if low_map == p:\n low_map += p\n for j in range(low_map, high + 1, p):\n mark[j - low] = False\n result = []\n for i in range(low, high + 1):\n if mark[i - low] == True:\n result.append(i)\n return result\n\ndef primeproduct(L, R):\n res = self.segmented_sieve(L, R)\n ans = 1\n for r in res:\n ans = ans * r % 1000000007\n return ans", "import math\n\ndef isPrime(num):\n if num <= 1:\n return False\n if num % 2 == 0:\n return False\n else:\n for i in range(3, int(math.sqrt(num)) + 1, 2):\n if num % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n mul = 1\n if L <= 2:\n mul = 2\n if L % 2 == 0:\n L += 1\n for i in range(L, R + 1, 2):\n if not isPrime(i):\n continue\n mul *= i\n return mul % 1000000007", "def isprime(n):\n r = int(n ** 0.5)\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, r + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n p = 1\n for i in range(L, R + 1):\n if not self.isprime(i):\n continue\n p *= i\n return p % 1000000007", "import numpy\n\ndef isPrime(n):\n limit = int(n ** 0.5)\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, limit + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef primeproduct(L, R):\n prod = 1\n if L <= 2:\n prod = 2\n if L % 2 == 0:\n L += 1\n for i in range(L, R + 1, 2):\n if not self.isPrime(i):\n continue\n prod = prod * i\n return prod % 1000000007"], "starter_code": "def primeproduct(L, R):\n", "input_output": {"inputs": ["L = 1, R = 10", "L = 1, R = 20"], "outputs": ["210", "9699690"]}, "difficulty": "MEDIUM", "raw_tags": ["Prime Number", "sieve"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/product-of-primes5328/1", "Expected Auxiliary Space": "O(sqrt(R))", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O((R-L)*(logR))", "entry_point": "primeproduct", "task_id": "TACO_lite/101", "example": [[[1, 10], [1, 20]], ["210", "9699690"]]} +{"requirement": "Given an array A[] of N integers and a range(L, R). The task is to find the number of subarrays having sum in the range L to R (inclusive).\nExample 1:\nInput:\nN = 3, L = 3, R = 8\nA[] = {1, 4, 6}\nOutput: \n3\nExplanation: \nThe subarrays are [1,4], [4] and [6]\nExample 2:\nInput:\nN = 4, L = 4, R = 13\nA[] = {2, 3, 5, 8}\nOutput: \n6\nExplanation: \nThe subarrays are [2,3], [2,3,5], \n[3,5],[5], [5,8] and [8]\nYour Task: \nYou don't need to read input or print anything. Complete the function countSubarray( ) which takes the integer N , the array A[], the integer L and the integer R as input parameters and returns the number of subarays. \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 N \u2264 10^{6}\n1 \u2264 A[] \u2264 10^{9}\n1 \u2264 L \u2264 R \u2264 10^{15}", "solutions": ["def countSub(arr, n, x):\n st = 0\n end = 0\n sum = 0\n cnt = 0\n while end < n:\n sum += arr[end]\n while st <= end and sum > x:\n sum -= arr[st]\n st += 1\n cnt += end - st + 1\n end += 1\n return cnt\n\ndef countsubarray(N, A, L, R):\n Rcnt = self.countSub(A, N, R)\n Lcnt = self.countSub(A, N, L - 1)\n return Rcnt - Lcnt", "def countsubarray(n, a, l, r):\n\n def sumlessthanequalto(x):\n start = 0\n end = 0\n sum_ = 0\n count = 0\n while end < n:\n sum_ += a[end]\n while sum_ > x and start <= end:\n sum_ -= a[start]\n start += 1\n if start <= end:\n count += end - start + 1\n end += 1\n return count\n return sumlessthanequalto(r) - sumlessthanequalto(l - 1)", "def countsubarray(N, A, L, R):\n self.N = N\n self.A = A\n self.L = L\n self.R = R\n rs = self.sum(R)\n ls = self.sum(L - 1)\n return rs - ls\n\ndef sum(ele):\n c = 0\n su = 0\n ws = 0\n for i in range(self.N):\n if c + self.A[i] > ele:\n while c + self.A[i] > ele and ws < i:\n su += i - ws\n c -= self.A[ws]\n ws += 1\n if self.A[i] <= ele:\n c += self.A[i]\n if A[i] > ele:\n ws = i + 1\n k = N - ws\n return su + k * (k + 1) // 2", "def countsubarray(N, A, L, R):\n prefix = [0] * (N + 1)\n for i in range(1, N + 1):\n prefix[i] = prefix[i - 1] + A[i - 1]\n\n def countsubarraysWithSumAtMost(x):\n ans = 0\n j = 0\n for i in range(1, N + 1):\n while prefix[i] - prefix[j] > x:\n j += 1\n ans += i - j\n return ans\n return countsubarraysWithSumAtMost(R) - countsubarraysWithSumAtMost(L - 1)", "def countsubarray(N, A, L, R):\n ans1 = self.help(N, A, L - 1)\n ans2 = self.help(N, A, R)\n return ans2 - ans1\n\ndef help(N, A, K):\n ans = 0\n sum_ = 0\n l = 0\n for r in range(len(A)):\n sum_ += A[r]\n while sum_ > K:\n sum_ -= A[l]\n l += 1\n ans += r - l + 1\n return ans", "def countsubarray(N, A, L, R):\n left = 0\n su = 0\n count1 = 0\n for right in range(0, N):\n su += A[right]\n while su > L - 1:\n su -= A[left]\n left += 1\n count1 += right - left + 1\n count2 = 0\n su2 = 0\n left1 = 0\n for right1 in range(0, N):\n su2 += A[right1]\n while su2 > R:\n su2 -= A[left1]\n left1 += 1\n count2 += right1 - left1 + 1\n if count2 >= count1:\n return count2 - count1\n return count1 - count2", "def countsubarray(N, A, L, R):\n\n def count_sub(A, k):\n c = 0\n (left, right) = (0, 0)\n sum = 0\n while right < N:\n if sum + A[right] <= k:\n sum += A[right]\n c += right - left + 1\n right += 1\n else:\n sum -= A[left]\n left += 1\n return c\n c1 = count_sub(A, R)\n c2 = count_sub(A, L - 1)\n return c1 - c2", "def countsubarray(N, A, L, R):\n\n def count_subarrays(A, K):\n c = 0\n (left, right) = (0, 0)\n sum = 0\n while right < N:\n if sum + A[right] <= K:\n sum += A[right]\n c += right - left + 1\n right += 1\n else:\n sum -= A[left]\n left += 1\n return c\n c1 = count_subarrays(A, R)\n c2 = count_subarrays(A, L - 1)\n return c1 - c2", "def countsubarray(N, A, L, R):\n\n def sumlessthanequalto(x):\n i = 0\n j = 0\n count = 0\n sum = 0\n while j < N:\n sum += A[j]\n while i <= j and sum > x:\n sum -= A[i]\n i += 1\n if i <= j:\n count += j - i + 1\n j += 1\n return count\n return sumlessthanequalto(R) - sumlessthanequalto(L - 1)", "def countSub(N, A, V):\n tot = 0\n ans = 0\n l = 0\n for r in range(N):\n tot += A[r]\n while tot > V:\n tot -= A[l]\n l += 1\n ans += r - l + 1\n return ans\n\ndef countsubarray(N, A, L, R):\n return self.countSub(N, A, R) - self.countSub(N, A, L - 1)", "def countsubarray(N, A, L, R):\n one = self.sub(A, N, L - 1)\n two = self.sub(A, N, R)\n return two - one\n\ndef sub(A, N, X):\n sums = 0\n i = 0\n j = 0\n ans = 0\n while i < N:\n sums += A[i]\n while sums > X:\n sums -= A[j]\n j += 1\n ans += i - j + 1\n i += 1\n return ans", "def countsubarray(N, A, L, R):\n return Solution.counter(A, R, N) - Solution.counter(A, L - 1, N)\n\ndef counter(A, lim, N):\n i = ans = summ = 0\n for x in range(N):\n summ += A[x]\n while summ > lim:\n summ -= A[i]\n i += 1\n ans += x - i + 1\n return ans", "def countsubarray(N, A, L, R):\n ans1 = self.count(N, A, L - 1)\n ans2 = self.count(N, A, R)\n return ans2 - ans1\n\ndef count(N, A, X):\n ans = 0\n sums = 0\n j = 0\n for i in range(N):\n sums += A[i]\n while sums > X:\n sums -= A[j]\n j += 1\n ans += i - j + 1\n return ans", "def countsubarray(N, A, L, R):\n\n def helper(n, arr, num):\n start = 0\n ans = 0\n Sum = 0\n for end in range(n):\n Sum += arr[end]\n while Sum > num:\n Sum -= arr[start]\n start += 1\n ans += end - start + 1\n return ans\n return helper(N, A, R) - helper(N, A, L - 1)", "def countsubarray(N, A, L, R):\n\n def sumlessthanequalto(x):\n start = 0\n (end, s) = (0, 0)\n count = 0\n while end < N:\n s += A[end]\n while s > x and start <= end:\n s -= A[start]\n start += 1\n if start <= end:\n count += end - start + 1\n end += 1\n return count\n return sumlessthanequalto(R) - sumlessthanequalto(L - 1)", "def Countsub(arr, n, x):\n (st, end) = (0, 0)\n cnt = 0\n sum = 0\n while end < n:\n sum += arr[end]\n while st <= end and sum > x:\n sum -= arr[st]\n st += 1\n cnt += end - st + 1\n end += 1\n return cnt\n\ndef countsubarray(N, A, L, R):\n rcnt = self.Countsub(A, N, R)\n lcnt = self.Countsub(A, N, L - 1)\n return rcnt - lcnt", "def countsub(arr, su):\n start = 0\n c = 0\n csum = 0\n for i in range(len(arr)):\n csum += arr[i]\n while csum > su:\n csum -= arr[start]\n start += 1\n c += i - start + 1\n return c\n\ndef countsubarray(N, A, L, R):\n return countsub(A, R) - countsub(A, L - 1)", "def countsubarray(N, A, L, R):\n\n def sumCal(x):\n start = 0\n end = 0\n cnt = 0\n tot = 0\n while end < N:\n tot += A[end]\n while tot > x and start <= end:\n tot -= A[start]\n start += 1\n if start <= end:\n cnt += end - start + 1\n end += 1\n return cnt\n return sumCal(R) - sumCal(L - 1)", "import bisect\n\ndef countsubarray(N, A, L, R):\n (l, r) = (0, 0)\n (sum1, count1, count2) = (0, 0, 0)\n while r < N:\n sum1 += A[r]\n while sum1 > R:\n sum1 -= A[l]\n l += 1\n count1 += r - l + 1\n r += 1\n sum1 = r = l = 0\n while r < N:\n sum1 += A[r]\n while sum1 > L - 1:\n sum1 -= A[l]\n l += 1\n count2 += r - l + 1\n r += 1\n return count1 - count2", "def count(n, a, x):\n ans = 0\n summ = 0\n l = 0\n for i in range(n):\n summ += a[i]\n while summ > x:\n summ -= a[l]\n l += 1\n ans += i - l + 1\n return ans\n\ndef countsubarray(n, arr, l, r):\n temp1 = self.count(n, arr, r)\n temp2 = self.count(n, arr, l - 1)\n return temp1 - temp2", "def helper(x, a, n):\n start = 0\n end = 0\n sum_ = 0\n count = 0\n while end < n:\n sum_ += a[end]\n while sum_ > x and start <= end:\n sum_ -= a[start]\n start += 1\n if start <= end:\n count += end - start + 1\n end += 1\n return count\n\ndef countsubarray(N, A, L, R):\n return self.helper(R, A, N) - self.helper(L - 1, A, N)", "def countsubarray(N, A, L, R):\n\n def check(arr, bound):\n l = 0\n sm = 0\n ans = 0\n for r in range(len(arr)):\n sm += arr[r]\n while sm > bound:\n sm -= arr[l]\n l += 1\n ans += r - l + 1\n return ans\n a = check(A, L - 1)\n b = check(A, R)\n return abs(a - b)", "def solve(A, R):\n i = j = s = c = 0\n n = len(A)\n while j < n:\n s += A[j]\n while s > R:\n s -= A[i]\n i += 1\n c += j - i + 1\n j += 1\n return c\n\ndef countsubarray(N, A, L, R):\n c = self.solve(A, L - 1)\n c1 = self.solve(A, R)\n return abs(c - c1)", "def countsubarray(n, arr, l, r):\n sl = [0]\n total = 0\n ans = 0\n i = j = -1\n for num in arr:\n total += num\n while i + 1 < len(sl) and sl[i + 1] < total - r:\n i += 1\n while j + 1 < len(sl) and sl[j + 1] <= total - l:\n j += 1\n ans += j - i\n sl.append(total)\n return ans", "def countone(N, A, x):\n st = 0\n end = 0\n cnt = 0\n summ = 0\n while end < N:\n summ += A[end]\n while st <= end and summ > x:\n summ -= A[st]\n st += 1\n cnt += end - st + 1\n end += 1\n return cnt\n\ndef countsubarray(N, A, L, R):\n Lcnt = self.countone(N, A, L - 1)\n Rcnt = self.countone(N, A, R)\n ans = abs(Rcnt - Lcnt)\n return ans", "def countsubarray(n, x, L, R):\n\n def f(e):\n i = 0\n s = 0\n ans = 0\n for j in range(n):\n s += x[j]\n while s > e:\n ans += j - i\n s -= x[i]\n i += 1\n while i < n:\n ans += n - i\n i += 1\n return ans\n return f(R) - f(L - 1)", "def countsubarray(N, A, L, R):\n pre = [0] * (N + 1)\n for i in range(1, N + 1):\n pre[i] = pre[i - 1] + A[i - 1]\n ans = 0\n left = 0\n right = 0\n left_sum = 0\n right_sum = 0\n sumi = 0\n for i in range(N):\n left_sum -= sumi\n right_sum -= sumi\n while left < N and left_sum < L:\n left_sum += A[left]\n left += 1\n if left_sum < L:\n break\n while right < N and right_sum <= R:\n right_sum += A[right]\n right += 1\n ans += right - left\n if right == N and right_sum >= L and (right_sum <= R):\n ans += 1\n sumi = A[i]\n return ans", "def count(N, A, R):\n total = A[0]\n end = beg = 0\n cases = 0\n while end < N and beg < N:\n if total <= R:\n end += 1\n if end >= beg:\n cases += end - beg\n if end < N:\n total += A[end]\n else:\n total -= A[beg]\n beg += 1\n return cases\n\ndef countsubarray(N, A, L, R):\n return count(N, A, R) - count(N, A, L - 1)", "def countsubarray(N, A, L, R):\n\n def solve(x):\n i = 0\n j = 0\n Sum = 0\n count = 0\n while j < N:\n Sum = Sum + A[j]\n while Sum > x and i <= j:\n Sum = Sum - A[i]\n i = i + 1\n if i <= j:\n count += j - i + 1\n j = j + 1\n return count\n return solve(R) - solve(L - 1)", "def countsubarray(N, A, L, R):\n\n def helper(x):\n start = 0\n end = 0\n sum1 = 0\n count = 0\n while end < N:\n sum1 += A[end]\n while sum1 > x and start <= end:\n sum1 -= A[start]\n start += 1\n if start <= end:\n count += end - start + 1\n end += 1\n return count\n return helper(R) - helper(L - 1)", "def countsubarray(n, a, L, R):\n\n def count_sub(a, x, n):\n sum = 0\n start = 0\n end = 0\n count = 0\n while end < n:\n sum += a[end]\n while start <= end and sum > x:\n sum -= a[start]\n start += 1\n count += end - start + 1\n end += 1\n return count\n return count_sub(a, R, n) - count_sub(a, L - 1, n)", "def countless(n, a, x):\n ans = 0\n s = 0\n (i, j) = (0, 0)\n while i < n:\n s += a[i]\n while s > x and j <= i:\n s -= a[j]\n j += 1\n ans += i - j + 1\n i += 1\n return ans\n\ndef countsubarray(n, a, l, r):\n return countless(n, a, r) - countless(n, a, l - 1)", "def countsubarray(N, A, L, R):\n (l, r, count1) = (0, 0, 0)\n m = 0\n for r in range(0, N):\n m += A[r]\n while l < r and m > R:\n m -= A[l]\n l += 1\n if m <= R:\n le = r - l + 1\n count1 += le\n (l, r, count2) = (0, 0, 0)\n m = 0\n for r in range(0, N):\n m += A[r]\n while l < r and m > L - 1:\n m -= A[l]\n l += 1\n if m <= L - 1:\n le = r - l + 1\n count2 += le\n return count1 - count2", "def countsubarray(N, A, L, R):\n r_cnt = self.getSubarrayCnt(N, A, R)\n l_cnt = self.getSubarrayCnt(N, A, L - 1)\n return r_cnt - l_cnt\n\ndef getSubarrayCnt(n, a, x):\n start = 0\n end = 0\n count = 0\n cur_sum = 0\n while end < n:\n cur_sum += a[end]\n while start <= end and cur_sum > x:\n cur_sum -= a[start]\n start += 1\n count += end - start + 1\n end += 1\n return count", "def helper(nums, k):\n l = 0\n r = 0\n res = 0\n n = len(nums)\n ans = 0\n while r < n:\n res += nums[r]\n while res > k:\n res -= nums[l]\n l += 1\n ans += r - l + 1\n r += 1\n return ans\n\ndef countsubarray(N, A, L, R):\n return self.helper(A, R) - self.helper(A, L - 1)", "def cnt(N, A, X):\n c = 0\n s = 0\n l = r = 0\n for r in range(0, N):\n s += A[r]\n while s > X:\n s -= A[l]\n l += 1\n c += r - l + 1\n return c\n\ndef countsubarray(N, A, L, R):\n return self.cnt(N, A, R) - self.cnt(N, A, L - 1)", "def countsubarray(N, A, L, R):\n return self.countSub(N, A, R) - self.countSub(N, A, L - 1)\n\ndef countSub(N, A, k):\n count = 0\n Sum = 0\n end = 0\n start = 0\n while end < N:\n Sum += A[end]\n while start <= end and Sum > k:\n Sum -= A[start]\n start += 1\n count += end - start + 1\n end += 1\n return count", "def countsubarray(n, arr, left, right):\n\n def countSubaarraysSumLessThanX(arr, x):\n addition = 0\n (left, right) = (0, 0)\n count = 0\n while right < len(arr):\n addition += arr[right]\n while addition > x:\n addition -= arr[left]\n left += 1\n count += right - left + 1\n right += 1\n return count\n return countSubaarraysSumLessThanX(arr, right) - countSubaarraysSumLessThanX(arr, left - 1)", "def solve(A, N, a):\n j = 0\n su = 0\n ans = 0\n for i in range(N):\n su += A[i]\n while su > a:\n su -= A[j]\n j += 1\n ans += i - j + 1\n return ans\n\ndef countsubarray(N, A, L, R):\n return self.solve(A, N, R) - self.solve(A, N, L - 1)", "def countsubarray(N, A, L, R):\n\n def countWhole(a, n, k):\n i = 0\n j = 0\n s = 0\n c = 0\n while j < n:\n s = s + a[j]\n while s > k:\n s = s - a[i]\n i = i + 1\n c = c + j - i + 1\n j = j + 1\n return c\n return countWhole(A, N, R) - countWhole(A, N, L - 1)", "def countsubarray(N, A, L, R):\n\n def kadane(A, N, val):\n cur_sum = 0\n left = 0\n ans = 0\n for i in range(N):\n cur_sum += A[i]\n if cur_sum > val:\n while cur_sum > val:\n cur_sum -= A[left]\n left += 1\n ans += i - left + 1\n return ans\n a1 = kadane(A, N, R)\n a2 = kadane(A, N, L - 1)\n return a1 - a2", "def subArraySum(arr, n, s):\n summ = 0\n i = 0\n j = 0\n count = 0\n while j < n:\n summ = summ + arr[j]\n while summ > s:\n summ = summ - arr[i]\n i = i + 1\n count = count + (j - i) + 1\n j = j + 1\n return count\n\ndef countsubarray(N, A, L, R):\n rsubarray = subArraySum(A, N, R)\n lsubarray = subArraySum(A, N, L - 1)\n return rsubarray - lsubarray", "def countsubarray(N, A, L, R):\n sumL = 0\n sumM = 0\n res = 0\n l = 0\n r = 0\n m = 0\n while r < N and sumL + A[r] < L:\n sumL += A[r]\n r += 1\n sumM = sumL\n while r < N:\n sumL += A[r]\n sumM += A[r]\n while sumL > R:\n sumL -= A[l]\n l += 1\n while sumM - A[m] >= L:\n sumM -= A[m]\n m += 1\n res += m - l + 1\n r += 1\n return res", "def countsubarray(N, arr, L, R):\n (i, j) = (0, 0)\n (s1, c1) = (0, 0)\n while j < len(arr):\n s1 = s1 + arr[j]\n if s1 <= R:\n j += 1\n c1 += j - i\n else:\n while s1 > R:\n s1 -= arr[i]\n i += 1\n s1 -= arr[j]\n (i, j) = (0, 0)\n (s2, c2) = (0, 0)\n while j < len(arr):\n s2 = s2 + arr[j]\n if s2 <= L - 1:\n j += 1\n c2 += j - i\n else:\n while s2 > L - 1:\n s2 -= arr[i]\n i += 1\n s2 -= arr[j]\n return c1 - c2", "def countsubarray(N, arr, L, R):\n x = self.t_L(arr, L)\n y = self.t_R(arr, R)\n return y - x\n\ndef t_R(arr, R):\n (i, j, tmp, ans) = (0, 0, 0, 0)\n while j < len(arr):\n tmp += arr[j]\n if tmp <= R:\n j += 1\n ans += j - i\n else:\n while tmp > R:\n tmp -= arr[i]\n i += 1\n tmp -= arr[j]\n return ans\n\ndef t_L(arr, L):\n (i, j, tmp, ans) = (0, 0, 0, 0)\n while j < len(arr):\n tmp += arr[j]\n if tmp < L:\n j += 1\n ans += j - i\n else:\n while tmp >= L:\n tmp -= arr[i]\n i += 1\n tmp -= arr[j]\n return ans", "def countsubarray(N, A, L, R):\n ans = 0\n (l, r, s) = (0, 0, 0)\n while r < N:\n s += A[r]\n while l <= r and s > R:\n s -= A[l]\n l += 1\n ans += r - l + 1\n r += 1\n r = 0\n l = 0\n s = 0\n while r < N:\n s += A[r]\n while l <= r and s >= L:\n s -= A[l]\n l += 1\n ans -= r - l + 1\n r += 1\n return ans", "def countsubarray(N, A, L, R):\n\n def help(n, a, r):\n st = 0\n ans = 0\n sum = 0\n for i in range(n):\n sum += a[i]\n while sum > r:\n sum -= a[st]\n st += 1\n ans += i - st + 1\n return ans\n return help(N, A, R) - help(N, A, L - 1)", "def countsubarray(N, A, L, R):\n i = 0\n sum1 = 0\n count1 = 0\n for j in range(N):\n sum1 += A[j]\n while i <= j and sum1 > R:\n sum1 -= A[i]\n i += 1\n count1 += j - i + 1\n i = sum1 = count2 = 0\n for j in range(N):\n sum1 += A[j]\n while i <= j and sum1 > L - 1:\n sum1 -= A[i]\n i += 1\n count2 += j - i + 1\n return count1 - count2", "def countsubarray(N, A, L, R):\n i = j1 = j2 = 0\n sum1 = sum2 = ans = 0\n while i < N:\n while j1 < N and sum1 + A[j1] < L:\n sum1 += A[j1]\n j1 += 1\n if not j2:\n sum2 = sum1\n j2 = j1\n while j2 < N and sum2 + A[j2] <= R:\n sum2 += A[j2]\n j2 += 1\n ans += j2 - j1\n sum1 -= A[i]\n sum2 -= A[i]\n i += 1\n return ans", "def countsubarray(N, A, L, R):\n rcnt = self.countSubArr(A, N, R)\n lcnt = self.countSubArr(A, N, L - 1)\n return rcnt - lcnt\n\ndef countSubArr(A, N, X):\n start = 0\n end = 0\n sum = 0\n count = 0\n while end < N:\n sum += A[end]\n while start <= end and sum > X:\n sum -= A[start]\n start += 1\n count += end - start + 1\n end += 1\n return count", "def countsubarray(N, A, L, R):\n c1 = 0\n total = 0\n l = 0\n r = 0\n while r < N:\n total += A[r]\n if total >= L:\n while total >= L and l <= r:\n total -= A[l]\n l += 1\n c1 += r - l + 1\n r += 1\n c2 = 0\n total = 0\n l = 0\n r = 0\n while r < N:\n total += A[r]\n if total > R:\n while total > R and l <= r:\n c2 += N - r\n total -= A[l]\n l += 1\n r += 1\n total_subarray = N * (N + 1) // 2\n ans = total_subarray - (c1 + c2)\n return ans", "def calcSubs(n):\n return n * (n + 1) // 2\n\ndef countSubs(a, val):\n (ans, p1, p2, sm) = (0, 0, 0, a[0])\n n = len(a)\n while p1 < n and p2 < n:\n if sm < val:\n p2 += 1\n if p2 >= p1:\n ans += p2 - p1\n if p2 < n:\n sm += a[p2]\n else:\n sm -= a[p1]\n p1 += 1\n return ans\n\ndef countsubarray(N, A, L, R):\n sumLessThanR = countSubs(A, R + 1)\n sumLessThanL = countSubs(A, L)\n return sumLessThanR - sumLessThanL", "def countsubarray(N, A, L, R):\n\n def count(A, limit, N):\n (i, j, s, ans) = (0, 0, 0, 0)\n while j < N:\n s = s + A[j]\n while s > limit:\n s = s - A[i]\n i = i + 1\n ans = ans + j - i + 1\n j = j + 1\n return ans\n return count(A, R, N) - count(A, L - 1, N)", "def countsub(arr, n, x):\n (start, end, sumi, ans) = (0, 0, 0, 0)\n for end in range(0, n):\n sumi += arr[end]\n while sumi > x:\n sumi -= arr[start]\n start += 1\n ans += end - start + 1\n return ans\n\ndef countsubarray(N, A, L, R):\n rt = self.countsub(A, N, R)\n lt = self.countsub(A, N, L - 1)\n return rt - lt", "def countsubarray(N, A, L, R):\n RCount = self.countSubLT(A, R)\n LCount = self.countSubLT(A, L - 1)\n return RCount - LCount\n\ndef countSubLT(A, X):\n N = len(A)\n end = 0\n start = 0\n sum = 0\n subArrayCount = 0\n while end < N:\n sum += A[end]\n while start <= end and sum > X:\n sum -= A[start]\n start += 1\n subArrayCount += end - start + 1\n end += 1\n return subArrayCount"], "starter_code": "def countsubarray(N, A, L, R):\n", "input_output": {"inputs": ["N = 3, L = 3, R = 8\nA[] = {1, 4, 6}", "N = 4, L = 4, R = 13\nA[] = {2, 3, 5, 8}"], "outputs": ["3", "6"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Data Structures", "Arrays", "Algorithms", "sliding-window"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Amortized analysis"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-the-number-of-subarrays/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "countsubarray", "task_id": "TACO_lite/175", "example": [[[3, 3, 8, [1, 4, 6]], [4, 4, 13, [2, 3, 5, 8]]], [null, null]]} +{"requirement": "Given an integer array\u00a0nums\u00a0and an integer k, return the maximum sum of a non-empty subsequence\u00a0of that array such that for every\u00a0two consecutive integers in the subsequence,\u00a0nums[i]\u00a0and\u00a0nums[j], where\u00a0i < j, the condition\u00a0j - i <= k\u00a0is satisfied.\nA\u00a0subsequence\u00a0of an array is\u00a0obtained by deleting some number of elements (can be\u00a0zero) from the array, leaving the remaining elements in their original order.\n\u00a0\nExample 1:\nInput: nums = [10,2,-10,5,20], k = 2\nOutput: 37\nExplanation: The subsequence is [10, 2, 5, 20].\n\nExample 2:\nInput: nums = [-1,-2,-3], k = 1\nOutput: -1\nExplanation: The subsequence must be non-empty, so we choose the largest number.\n\nExample 3:\nInput: nums = [10,-2,-10,-5,20], k = 2\nOutput: 23\nExplanation: The subsequence is [10, -2, -5, 20].\n\n\u00a0\nConstraints:\n\n1 <= k <= nums.length <= 10^5\n-10^4\u00a0<= nums[i] <= 10^4", "solutions": ["from collections import deque\n\ndef constrainedsubsetsum(nums, k):\n (N, queue) = (len(nums), deque())\n dp = [val for val in nums]\n for (i, val) in enumerate(nums):\n if queue and i - queue[0] > k:\n queue.popleft()\n if queue and dp[queue[0]] > 0:\n dp[i] += dp[queue[0]]\n while queue and dp[i] >= dp[queue[-1]]:\n queue.pop()\n queue.append(i)\n return max(dp)", "from collections import deque\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = nums.copy()\n ans = dp[0]\n monoq = deque()\n qsize = 0\n for (i, num) in enumerate(nums):\n if i > 0:\n dp[i] = max(dp[i], num + monoq[0][0])\n ans = max(ans, dp[i])\n pops = 1\n while monoq and dp[i] > monoq[-1][0]:\n (_, freq) = monoq.pop()\n pops += freq\n qsize -= freq\n monoq.append([dp[i], pops])\n qsize += pops\n while qsize > k:\n extra = qsize - k\n if monoq[0][1] > extra:\n monoq[0][1] -= extra\n qsize = k\n else:\n (_, v) = monoq.popleft()\n qsize -= v\n return ans", "from collections import deque\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = []\n dp.append(nums[0])\n deq = deque()\n deq.append(0)\n for i in range(1, len(nums)):\n while len(deq) and i - deq[0] > k:\n deq.popleft()\n cur_max = dp[deq[0]] if len(deq) and dp[deq[0]] > 0 else 0\n dp.append(cur_max + nums[i])\n while len(deq) and dp[deq[-1]] < dp[i]:\n deq.pop()\n deq.append(i)\n return max(dp)", "from heapq import heappop\nfrom heapq import heappush\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n heap = []\n ans = -10001\n for (i, num) in enumerate(nums):\n while len(heap) > 0:\n (_, val, idx) = heap[0]\n if idx < i - k:\n heappop(heap)\n else:\n new_val = max(num, val + num)\n ans = max(ans, new_val)\n heappush(heap, (-new_val, new_val, i))\n break\n if len(heap) == 0:\n ans = max(ans, num)\n heappush(heap, (-num, num, i))\n return ans", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n dp = [-sys.maxsize] * n\n dq = []\n dp[n - 1] = nums[n - 1]\n res = dp[n - 1]\n for i in range(n - 2, -1, -1):\n while len(dq) != 0 and dp[i + 1] > dp[dq[-1]]:\n dq.pop()\n while len(dq) != 0 and dq[0] > i + k:\n dq.pop(0)\n dq.append(i + 1)\n dp[i] = max(dp[i], nums[i], nums[i] + dp[dq[0]])\n res = max(res, dp[i])\n return res", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n withAdding = [0 for _ in range(len(nums))]\n notAdding = [-1 for _ in range(len(nums))]\n validMax = [nums[0]]\n maxValue = nums[0]\n withAdding[0] = nums[0]\n for i in range(1, len(nums)):\n if maxValue < 0 and nums[i] > maxValue:\n withAdding[i] = nums[i]\n else:\n withAdding[i] = maxValue + nums[i]\n validMax.append(withAdding[i])\n maxValue = max(withAdding[i], maxValue)\n if len(validMax) > k and validMax.pop(0) == maxValue:\n maxValue = max(validMax)\n notAdding[i] = max(notAdding[i - 1], withAdding[i - 1])\n return max(max(notAdding), max(withAdding))", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n memo = [nums[0]]\n if not nums:\n return 0\n m = nums[0]\n for i in range(1, k):\n memo.append(nums[i] + max(0, m))\n if memo[-1] > m:\n m = memo[-1]\n import copy\n window = copy.deepcopy(memo)\n for i in range(k, len(nums)):\n memo.append(nums[i] + max(0, m))\n window.append(memo[-1])\n p = window.pop(0)\n if memo[-1] > m:\n m = memo[-1]\n elif p == m:\n m = max(window)\n return max(memo)", "from collections import deque\nfrom collections import deque\n\ndef constrainedsubsetsum(nums, k):\n (N, queue) = (len(nums), deque())\n dp = [0] * N\n for (i, val) in enumerate(nums):\n if queue and i - queue[0] > k:\n queue.popleft()\n if queue and dp[queue[0]] > 0:\n dp[i] = val + dp[queue[0]]\n else:\n dp[i] = val\n while queue and dp[i] >= dp[queue[-1]]:\n queue.pop()\n queue.append(i)\n return max(dp)\n\ndef constrainedsubsetsum(nums, k):\n if not nums or not k:\n return 0\n if max(nums) <= 0:\n return max(nums)\n if min(nums) >= 0:\n return sum(nums)\n (queue, N) = (deque(), len(nums))\n for i in range(N):\n while queue and queue[0] < i - k:\n queue.popleft()\n if queue:\n nums[i] += nums[queue[0]]\n while queue and nums[queue[-1]] < nums[i]:\n queue.pop()\n if nums[i] > 0:\n queue.append(i)\n return max(nums)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = [nums[0]]\n decrease = collections.deque([0])\n for (i, num) in enumerate(nums[1:], 1):\n if decrease and i - decrease[0] > k:\n decrease.popleft()\n val = max(num, dp[decrease[0]] + num)\n dp.append(val)\n while decrease and dp[decrease[-1]] <= val:\n decrease.pop()\n decrease.append(i)\n return max(dp)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n _max = collections.deque()\n res = max(nums)\n for i in range(n):\n if len(_max) and _max[0][0] > 0:\n val = nums[i] + _max[0][0]\n else:\n val = nums[i]\n while len(_max) and _max[-1][0] < val:\n _max.pop()\n _max.append((val, i))\n res = max(val, res)\n if _max[0][1] <= i - k:\n _max.popleft()\n return res", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n maxNum = nums[0]\n maxSum = nums[0]\n maxNegSum = 0\n curNegWindowSum = 0\n curWindowSum = 0\n rightIndex = 0\n leftIndex = 0\n midIndex = 0\n negativeStreak = False\n while rightIndex < len(nums):\n if maxNum < nums[rightIndex]:\n maxNum = nums[rightIndex]\n if nums[rightIndex] >= 0 and (not negativeStreak):\n curWindowSum += nums[rightIndex]\n maxSum = max(maxSum, curWindowSum)\n elif nums[rightIndex] < 0 and (not negativeStreak):\n negativeStreak = True\n midIndex = rightIndex\n if k > 1:\n curNegWindowSum = nums[rightIndex]\n maxNegSum = curNegWindowSum\n curWindowSum += nums[rightIndex]\n elif nums[rightIndex] < 0 and negativeStreak:\n if rightIndex - midIndex < k - 1:\n curNegWindowSum += nums[rightIndex]\n maxNegSum = curNegWindowSum\n else:\n if k > 1:\n curNegWindowSum -= nums[midIndex]\n curNegWindowSum += nums[rightIndex]\n maxNegSum = min(maxNegSum, curNegWindowSum)\n midIndex += 1\n curWindowSum += nums[rightIndex]\n elif nums[rightIndex] >= 0 and negativeStreak:\n curWindowSum -= maxNegSum\n if curWindowSum <= 0:\n midIndex = rightIndex\n leftIndex = rightIndex\n curWindowSum = nums[rightIndex]\n else:\n curWindowSum += nums[rightIndex]\n maxSum = max(maxSum, curWindowSum)\n maxNegSum = 0\n curNegWindowSum = 0\n negativeStreak = False\n rightIndex += 1\n return max(maxSum, maxNum)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = [nums[0]]\n decrease = collections.deque([0])\n for (i, x) in enumerate(nums[1:], 1):\n if decrease[0] == i - k - 1:\n decrease.popleft()\n tmp = max(x, dp[decrease[0]] + x)\n dp += [tmp]\n while decrease and dp[decrease[-1]] <= tmp:\n decrease.pop()\n decrease += [i]\n return max(dp)", "def constrainedsubsetsum(A: List[int], k: int) -> int:\n deque = collections.deque()\n for i in range(len(A)):\n A[i] += deque[0] if deque else 0\n while len(deque) and A[i] > deque[-1]:\n deque.pop()\n if A[i] > 0:\n deque.append(A[i])\n if i >= k and deque and (deque[0] == A[i - k]):\n deque.popleft()\n return max(A)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n (q_max, ans) = (deque([(nums[0], 0)]), nums[0])\n for i in range(1, len(nums)):\n nums[i] += max(q_max[0][0], 0)\n if q_max[0][1] <= i - k:\n q_max.popleft()\n while q_max and nums[i] > q_max[-1][0]:\n q_max.pop()\n q_max.append((nums[i], i))\n ans = max(ans, nums[i])\n return ans", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n dq = collections.deque()\n m = -sys.maxsize\n for (i, n) in enumerate(nums):\n fi = n\n if dq:\n fi += max(dq[0][1], 0)\n while dq and fi >= dq[-1][1]:\n dq.pop()\n dq.append([i, fi])\n if i - dq[0][0] == k:\n dq.popleft()\n if fi > m:\n m = fi\n return m", "def constrainedsubsetsum(nums, k):\n n = len(nums)\n dp = [0] * n\n deq = deque([0])\n for i in range(n):\n if deq and deq[0] < i - k:\n deq.popleft()\n while deq and nums[i] + dp[deq[0]] > dp[deq[-1]]:\n a = deq.pop()\n dp[i] = max(nums[i], nums[i] + dp[deq[0]] if deq else nums[i] + dp[a])\n deq.append(i)\n return max(dp)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n (dp, q) = ([nums[0]], deque())\n q.append((0, nums[0]))\n res = nums[0]\n for i in range(1, len(nums)):\n while q and i - q[0][0] > k:\n q.popleft()\n cur = nums[i]\n if q:\n cur += max(q[0][1], 0)\n while q and q[-1][1] < cur:\n q.pop()\n q.append((i, cur))\n dp.append(cur)\n res = max(res, cur)\n return res", "from collections import deque\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n numLength = len(nums)\n maxSums = defaultdict(int)\n maxSum = nums[0]\n maxQueue = deque([0])\n for i in range(numLength - 1, -1, -1):\n ithMax = max(nums[i], maxQueue[0] + nums[i])\n maxSums[i] = ithMax\n if len(maxQueue) == k:\n if maxSums[i + k] == maxQueue[0]:\n maxQueue.popleft()\n while maxQueue and ithMax > maxQueue[-1]:\n maxQueue.pop()\n maxQueue.append(ithMax)\n maxSum = max(ithMax, maxSum)\n return maxSum", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = collections.deque([(nums[0], 0)])\n ans = nums[0]\n for i in range(1, len(nums)):\n new = nums[i] + max(0, dp[0][0])\n while dp and dp[0][1] <= i - k:\n dp.popleft()\n while dp and new >= dp[-1][0]:\n dp.pop()\n dp.append((new, i))\n ans = max(ans, new)\n return ans", "from collections import deque\n\ndef constrainedsubsetsum(nums, k):\n if max(nums) <= 0:\n return max(nums)\n if min(nums) >= 0:\n return sum(nums)\n (queue, N) = (deque(), len(nums))\n for i in range(N):\n while queue and queue[0] < i - k:\n queue.popleft()\n if queue:\n nums[i] += nums[queue[0]]\n while queue and nums[queue[-1]] < nums[i]:\n queue.pop()\n if nums[i] > 0:\n queue.append(i)\n return max(nums)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n dp = [0] * n\n q = deque()\n ans = float('-inf')\n for i in range(n):\n if i > k and q[0] == i - k - 1:\n q.popleft()\n dp[i] = (0 if len(q) == 0 else max(dp[q[0]], 0)) + nums[i]\n while len(q) > 0 and dp[i] >= dp[q[-1]]:\n q.pop()\n q.append(i)\n ans = max(ans, dp[i])\n return ans", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n from collections import deque\n q = deque()\n q.append((nums[-1], n - 1))\n ans = nums[-1]\n for i in reversed(list(range(n - 1))):\n while q and q[0][1] - i > k:\n q.popleft()\n dp = nums[i]\n if q:\n dp = max(dp, nums[i] + q[0][0])\n ans = max(dp, ans)\n while q and q[-1][0] <= dp:\n q.pop()\n q.append((dp, i))\n return ans", "from collections import deque\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n queue = deque()\n res = float('-inf')\n for i in range(n):\n if queue and i - queue[0][1] > k:\n queue.popleft()\n cur = nums[i] + max(0, queue[0][0] if queue else 0)\n res = max(res, cur)\n while queue and queue[-1][0] <= cur:\n queue.pop()\n queue.append((cur, i))\n return res", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n q = []\n res = float('-inf')\n for i in range(len(nums)):\n while q and i - q[0][0] > k:\n q.pop(0)\n temp = nums[i]\n if q and q[0][1] > 0:\n temp += q[0][1]\n res = max(res, temp)\n while q and q[-1][1] <= temp:\n q.pop()\n q.append((i, temp))\n return res", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n deq = deque()\n for (index, val) in enumerate(nums):\n nums[index] += deq[0] if deq else 0\n while deq and nums[index] > deq[-1]:\n deq.pop()\n if nums[index] > 0:\n deq.append(nums[index])\n if index >= k and deq and (deq[0] == nums[index - k]):\n deq.popleft()\n return max(nums)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n dp = [0] * n\n dp[0] = nums[0]\n heap = []\n heappush(heap, (-nums[0], 0))\n for i in range(1, n):\n while heap[0][1] < i - k:\n heappop(heap)\n cur = heap[0][0]\n dp[i] = nums[i] + max(-cur, 0)\n heappush(heap, (-dp[i], i))\n return max(dp)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n dp = [-math.inf for i in range(n)]\n dp[0] = nums[0]\n ans = [nums[0]]\n queue = [0]\n for i in range(1, n):\n dp[i] = max(dp[i], nums[i], nums[i] + ans[i - 1])\n if len(queue) == 0:\n queue.append(i)\n else:\n while len(queue) > 0 and (dp[i] > dp[queue[-1]] or i - queue[0] >= k):\n if dp[i] > dp[queue[-1]]:\n queue.pop(-1)\n else:\n queue.pop(0)\n queue.append(i)\n ans.append(dp[queue[0]])\n return max(dp)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n stack = deque()\n for i in range(len(nums)):\n nums[i] += stack[0] if stack else 0\n while stack and stack[-1] < nums[i]:\n stack.pop()\n if i >= k and stack and (stack[0] == nums[i - k]):\n stack.popleft()\n if nums[i] > 0:\n stack.append(nums[i])\n return max(nums)\n q = deque()\n for i in range(len(nums)):\n nums[i] += q[0] if q else 0\n while q and nums[i] > q[-1]:\n q.pop()\n if nums[i] > 0:\n q.append(nums[i])\n if i >= k and q and (q[0] == nums[i - k]):\n q.popleft()\n return max(nums)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n res = -sys.maxsize\n n = len(nums)\n dp = [0] * (n + 1)\n dq = collections.deque()\n for i in range(n):\n if not dq:\n dp[i + 1] = nums[i]\n else:\n dp[i + 1] = max(nums[i], dq[0] + nums[i])\n dq.append(dp[i + 1])\n while len(dq) > k:\n dq.popleft()\n while len(dq) > 1 and dq[0] <= dq[-1]:\n dq.popleft()\n res = max(res, dp[i + 1])\n return res", "from typing import List\nimport collections\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n maxx = list(nums)\n deque = collections.deque()\n for i in range(len(nums)):\n if deque:\n maxx[i] += deque[0]\n while deque and maxx[i] > deque[-1]:\n deque.pop()\n if maxx[i] > 0:\n deque.append(maxx[i])\n if i >= k and deque and (deque[0] == maxx[i - k]):\n deque.popleft()\n return max(maxx)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n rec = -nums[0]\n heap = [(-nums[0], 0)]\n for (j, n) in enumerate(nums[1:]):\n while j + 1 - heap[0][1] > k:\n heapq.heappop(heap)\n cand = -n + heap[0][0] if heap[0][0] <= 0 else -n\n rec = min(rec, cand)\n heapq.heappush(heap, (cand, j + 1))\n return -rec", "def __init__(k):\n self.k = k\n self.m = []\n\ndef add(a, solution):\n while len(self.m) > 0:\n if solution[a] > solution[self.m[-1]]:\n self.m.pop()\n else:\n break\n self.m.append(a)\n\ndef grab(a, solution, nums):\n if len(self.m) > 0:\n if self.m[0] > a + self.k:\n self.m = self.m[1:]\n return max(nums[a], nums[a] + solution[self.m[0]])\n else:\n return nums[a]\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n solution = [0] * n\n m = MonoQ(k)\n for i in range(n - 1, -1, -1):\n solution[i] = m.grab(i, solution, nums)\n m.add(i, solution)\n return max(solution)", "import heapq\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n heap = []\n n = len(nums)\n dp = [None] * n\n for i in range(n):\n best = None\n while len(heap) > 0:\n (val, idx) = heap[0]\n val *= -1\n if i - idx <= k:\n best = val\n break\n heapq.heappop(heap)\n dp[i] = nums[i]\n if best is not None and dp[i] < best + nums[i]:\n dp[i] = best + nums[i]\n heapq.heappush(heap, (-dp[i], i))\n return max(dp)", "from heapq import heappush, heappop\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n res = -float('inf')\n queue = []\n for (i, x) in enumerate(nums):\n while queue and queue[0][1] < i - k:\n heappop(queue)\n if queue:\n y = x - queue[0][0]\n else:\n y = x\n res = max(res, y)\n if y > 0:\n heappush(queue, [-y, i])\n return res", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n max_queue = collections.deque([0])\n max_sum = nums[0]\n for i in range(1, len(nums)):\n while max(0, i - k) > max_queue[0]:\n max_queue.popleft()\n nums[i] += max(0, nums[max_queue[0]])\n max_sum = max(max_sum, nums[i])\n while max_queue and nums[max_queue[-1]] < nums[i]:\n max_queue.pop()\n max_queue.append(i)\n return max_sum", "import collections\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n sol = -float('inf')\n n = len(nums)\n maxque = collections.deque([(-1, 0)])\n for i in range(n):\n max_i = max(maxque[0][1], 0) + nums[i]\n sol = max(sol, max_i)\n while maxque:\n if maxque[-1][1] < max_i:\n maxque.pop()\n else:\n break\n maxque.append((i, max_i))\n if maxque[0][0] <= i - k:\n maxque.popleft()\n return sol", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n pq = [(-nums[0], 0)]\n res = nums[0]\n for i in range(1, len(nums)):\n rm = i - k - 1\n while pq[0][1] <= rm:\n heapq.heappop(pq)\n cur = max(-pq[0][0], 0) + nums[i]\n res = max(res, cur)\n heapq.heappush(pq, (-cur, i))\n return res", "import heapq\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n ans = nums.copy()\n q = []\n for i in range(n - 1, -1, -1):\n while q and q[0][1] - i > k:\n heapq.heappop(q)\n if q:\n ans[i] += max(0, -q[0][0])\n heapq.heappush(q, (-ans[i], i))\n return max(ans)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = [-sys.maxsize] * len(nums)\n ans = nums[0]\n dp[0] = nums[0]\n heap = [(-nums[0], 0)]\n heapq.heapify(heap)\n for i in range(1, len(nums)):\n bound = i - k\n while heap[0][1] < bound:\n heapq.heappop(heap)\n dp[i] = max(dp[i], nums[i], -heap[0][0] + nums[i])\n ans = max(ans, dp[i])\n heapq.heappush(heap, (-dp[i], i))\n return ans", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n q = [(-nums[0], 0)]\n res = nums[0]\n dp = [0] * n\n for i in range(1, n):\n while q and i - q[0][1] > k:\n heapq.heappop(q)\n t = max(nums[i] - q[0][0], nums[i])\n res = max(res, t)\n heapq.heappush(q, (-t, i))\n return res", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n q = collections.deque()\n result = nums[0]\n for i in range(n):\n while q and q[0][1] < i - k:\n q.popleft()\n a = q[0][0] if q else 0\n m = nums[i] + (a if a > 0 else 0)\n while q and m >= q[-1][0]:\n q.pop()\n q.append((m, i))\n result = max(result, m)\n return result", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n heap = [(-nums[0], 0)]\n ret = nums[0]\n for i in range(1, len(nums)):\n remove = i - k - 1\n while remove >= heap[0][1]:\n heapq.heappop(heap)\n cur = max(0, -heap[0][0]) + nums[i]\n ret = max(ret, cur)\n heapq.heappush(heap, (-cur, i))\n return ret", "from collections import deque\n\ndef constrainedsubsetsum(A: List[int], k: int) -> int:\n Q = deque([(0, A[0])])\n running_max = A[0]\n for i in range(1, len(A)):\n if Q[0][0] < i - k:\n Q.popleft()\n maxsum_of_subseq_ends_at_i = A[i] + max(Q[0][1], 0)\n running_max = max(maxsum_of_subseq_ends_at_i, running_max)\n while Q and Q[-1][1] <= maxsum_of_subseq_ends_at_i:\n Q.pop()\n Q.append((i, maxsum_of_subseq_ends_at_i))\n return running_max", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n dp = [-sys.maxsize] * n\n dp[0] = nums[0]\n maxDeque = deque()\n ans = -sys.maxsize\n for j in range(n):\n while len(maxDeque) > 0 and j - maxDeque[0] > k:\n maxDeque.popleft()\n preMax = dp[maxDeque[0]] if len(maxDeque) > 0 else 0\n dp[j] = max(preMax + nums[j], nums[j])\n ans = max(dp[j], ans)\n while len(maxDeque) > 0 and dp[maxDeque[-1]] < dp[j]:\n maxDeque.pop()\n maxDeque.append(j)\n return ans", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n (dp, res) = (collections.deque(), -float('inf'))\n for (i, n) in enumerate(nums):\n if dp and dp[0][0] < i - k:\n dp.popleft()\n cur = n + (0 if not dp else dp[0][1])\n res = max(res, cur)\n if cur > 0:\n while dp and dp[-1][1] <= cur:\n dp.pop()\n dp.append((i, cur))\n return res", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n dp = [0] * n\n remove = collections.defaultdict(int)\n h = []\n\n def get_b():\n if not h:\n return 0\n b = heapq.heappop(h)\n while remove[b] > 0:\n remove[b] -= 1\n b = heapq.heappop(h)\n heapq.heappush(h, b)\n return -b\n for (i, d) in enumerate(nums):\n if i > k:\n remove[-dp[i - k - 1]] += 1\n dp[i] = max(get_b(), 0) + d\n heapq.heappush(h, -dp[i])\n return max(dp)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = [0 - sys.maxsize for i in range(len(nums))]\n heap = []\n dp[0] = nums[0]\n heapq.heappush(heap, (0 - nums[0], 0))\n for i in range(1, len(nums)):\n while len(heap) and heap[0][1] < i - k:\n heapq.heappop(heap)\n dp[i] = max(dp[i], nums[i] + max(0, 0 - heap[0][0] if len(heap) else 0))\n heapq.heappush(heap, (0 - dp[i], i))\n return max(dp)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n n = len(nums)\n heap = [(-nums[0], 0)]\n result = nums[0]\n for i in range(1, n):\n while heap and heap[0][1] < i - k:\n heapq.heappop(heap)\n a = -heap[0][0]\n m = nums[i] + (a if a > 0 else 0)\n heapq.heappush(heap, (-m, i))\n result = max(result, m)\n return result", "from collections import deque\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n que = deque()\n for ind in range(len(nums)):\n nums[ind] += que[0] if que else 0\n while que and nums[ind] > que[-1]:\n que.pop()\n if nums[ind] > 0:\n que.append(nums[ind])\n if que and ind >= k and (que[0] == nums[ind - k]):\n que.popleft()\n return max(nums)", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n deque = []\n for (i, num) in enumerate(nums):\n while deque and nums[deque[-1]] < 0:\n deque.pop()\n while deque and deque[0] < i - k:\n deque.pop(0)\n if deque:\n nums[i] = nums[deque[0]] + num\n while deque and nums[deque[-1]] < nums[i]:\n deque.pop()\n deque.append(i)\n return max(nums)", "from collections import deque\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n largest = deque()\n global_max = float('-inf')\n for (i, num) in enumerate(nums):\n if largest and largest[-1][1] < i - k:\n largest.pop()\n curr = num + max(0, largest[-1][0] if largest else 0)\n while largest and curr > largest[0][0]:\n largest.popleft()\n global_max = max(global_max, curr)\n largest.appendleft((curr, i))\n return global_max", "from collections import deque\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n dp = [0] * len(nums)\n dp[0] = nums[0]\n ans = dp[0]\n queue = deque([0])\n for j in range(1, len(nums)):\n if queue and queue[0] < j - k:\n queue.popleft()\n dp[j] = nums[j] + max(0, dp[queue[0]])\n while queue and dp[queue[-1]] < dp[j]:\n queue.pop()\n queue.append(j)\n ans = max(ans, dp[j])\n return ans", "from collections import deque\n\ndef __init__(size):\n self.queue = deque()\n self.size = size\n\ndef add(val, i):\n while self.queue and val > self.queue[-1][0]:\n self.queue.pop()\n self.queue.append((val, i))\n while i - self.queue[0][1] >= self.size:\n self.queue.popleft()\n\ndef max():\n if self.queue:\n return self.queue[0][0]\n else:\n return 0\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n queue = MaxQueue(k)\n result = -1\n for i in range(len(nums)):\n score = nums[i]\n prev = queue.max()\n if prev > 0:\n score += prev\n queue.add(score, i)\n result = max(result, score)\n return result", "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n import heapq\n h = []\n heapq.heapify(h)\n largeNum = -10000000000\n ans = largeNum\n for i in range(len(nums)):\n if i == 0:\n ans = nums[i]\n heapq.heappush(h, (-nums[i], i))\n else:\n b = False\n (m, index) = heapq.heappop(h)\n while index < i - k:\n (m, index) = heapq.heappop(h)\n heapq.heappush(h, (m, index))\n ans = max(ans, nums[i] - m, nums[i])\n heapq.heappush(h, (min(m - nums[i], -nums[i]), i))\n return ans", "import heapq\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n queue = [(-nums[0], 0)]\n res = nums[0]\n for i in range(1, len(nums)):\n while i - k - 1 >= queue[0][1]:\n heapq.heappop(queue)\n curr = max(-queue[0][0], 0) + nums[i]\n res = max(res, curr)\n heapq.heappush(queue, (-curr, i))\n return res", "from typing import List\nimport numpy\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n _len = len(nums)\n dp = numpy.zeros(_len, dtype=int)\n dp[0] = nums[0]\n _deque = []\n result = -sys.maxsize\n for i in range(_len):\n while _deque and i - _deque[0] > k:\n _deque.pop(0)\n tmp = 0\n if _deque:\n tmp = dp[_deque[0]]\n dp[i] = max(nums[i], nums[i] + tmp)\n result = max(result, dp[i])\n while _deque and dp[i] >= dp[_deque[-1]]:\n _deque.pop()\n _deque.append(i)\n pass\n return result", "from sortedcontainers import SortedList\n\ndef constrainedsubsetsum(nums: List[int], k: int) -> int:\n B = [nums[i] for i in range(len(nums))]\n store = SortedList()\n for i in range(len(nums) - 1, -1, -1):\n if len(store) > 0:\n if store[-1] > 0:\n B[i] += store[-1]\n store.add(B[i])\n if len(store) > k:\n store.remove(B[i + k])\n return max(B)"], "starter_code": "def constrainedsubsetsum(nums: List[int], k: int) -> int:\n", "input_output": {"fn_name": "constrainedSubsetSum", "inputs": [[[10, 2, -10, 5, 20], 2]], "outputs": [37]}, "difficulty": "MEDIUM", "raw_tags": ["Monotonic Queue", "Heap (Priority Queue)", "Array", "Sliding Window", "Queue", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures", "Amortized analysis"], "skill_types": ["Dynamic programming", "Amortized analysis", "Data structures"], "url": "https://leetcode.com/problems/constrained-subsequence-sum/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "constrainedsubsetsum", "task_id": "TACO_lite/179", "example": [[[[10, 2, -10, 5, 20], 2], [[-1, -2, -3], 1], [[10, -2, -10, -5, 20], 2]], ["37", "-1", "23"]]} +{"requirement": "Given a binary matrix having n rows and m columns, your task is to find the sum of coverage of all zeros in the matrix where coverage for a particular 0 is defined as total number of ones around a zero in left, right, up and bottom directions.\n \nExample 1:\nInput: matrix = {{0, 1, 0},\n{0, 1, 1}, {0, 0, 0}}\nOutput: 6\nExample 2:\nInput: matrix = {{0, 1}}\nOutput: 1\n \nYour Task:\nYou don't need to read or print anyhting. Your task is to complete the function FindCoverage() which takes the matrix as input parameter and returns sum of coverage of all zeros in the matrix.\n \nExpected Time Complexity: O(n * m)\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= n, m <= 100", "solutions": ["def findcoverage(matrix):\n coverageTotal = 0\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == 0:\n if j - 1 >= 0 and matrix[i][j - 1] == 1:\n coverageTotal += 1\n if j + 1 < len(matrix[0]) and matrix[i][j + 1] == 1:\n coverageTotal += 1\n if i - 1 >= 0 and matrix[i - 1][j] == 1:\n coverageTotal += 1\n if i + 1 < len(matrix) and matrix[i + 1][j] == 1:\n coverageTotal += 1\n return coverageTotal", "def findcoverage(matrix):\n count = 0\n for i in range(n):\n for j in range(m):\n if matrix[i][j] == 0:\n if i - 1 >= 0:\n if matrix[i - 1][j] == 1:\n count += 1\n if j - 1 >= 0:\n if matrix[i][j - 1] == 1:\n count += 1\n if i + 1 <= n - 1:\n if matrix[i + 1][j] == 1:\n count += 1\n if j + 1 <= m - 1:\n if matrix[i][j + 1] == 1:\n count += 1\n return count", "def findcoverage(matrix):\n n = len(matrix)\n m = len(matrix[0])\n count = 0\n for i in range(n):\n for j in range(m):\n if matrix[i][j] == 0:\n top = [i - 1, j]\n down = [i + 1, j]\n left = [i, j - 1]\n right = [i, j + 1]\n if top[0] >= 0:\n if matrix[top[0]][top[1]] == 1:\n count += 1\n if down[0] < n:\n if matrix[down[0]][down[1]] == 1:\n count += 1\n if left[1] >= 0:\n if matrix[left[0]][left[1]] == 1:\n count += 1\n if right[1] < m:\n if matrix[right[0]][right[1]] == 1:\n count += 1\n return count", "def numofneighbour(mat, i, j):\n (R, C) = (len(mat), len(mat[0]))\n count = 0\n if i > 0 and mat[i - 1][j]:\n count += 1\n if j > 0 and mat[i][j - 1]:\n count += 1\n if i < R - 1 and mat[i + 1][j]:\n count += 1\n if j < C - 1 and mat[i][j + 1]:\n count += 1\n return count\n\ndef find(mat):\n (R, C) = (len(mat), len(mat[0]))\n perimeter = 0\n for i in range(0, R):\n for j in range(0, C):\n if not mat[i][j]:\n perimeter += numofneighbour(mat, i, j)\n return perimeter\n\ndef findcoverage(matrix):\n return find(matrix)", "def findcoverage(matrix):\n row = 0\n col = 0\n dir = 'right'\n N = len(matrix)\n M = len(matrix[0])\n count = 0\n while row < N:\n r = row\n c = col\n while c < M:\n if dir == 'right' and c != M - 1 and (matrix[r][c] == 0):\n if matrix[r][c + 1] == 1:\n count += 1\n dir = 'left'\n if dir == 'left' and c != 0 and (matrix[r][c] == 0):\n if matrix[r][c - 1] == 1:\n count += 1\n dir = 'up'\n if dir == 'up' and r != 0 and (matrix[r][c] == 0):\n if matrix[r - 1][c] == 1:\n count += 1\n dir = 'down'\n if dir == 'down' and r != N - 1 and (matrix[r][c] == 0):\n if matrix[r + 1][c] == 1:\n count += 1\n dir = 'right'\n c += 1\n row += 1\n col = 0\n return count", "def findcoverage(matrix):\n m = len(matrix[0])\n n = len(matrix)\n c = 0\n for i in range(n):\n for j in range(m):\n if matrix[i][j] == 0:\n r1 = 0\n if i - 1 > -1:\n if matrix[i - 1][j] == 1:\n c += 1\n r2 = 0\n if i + 1 < n:\n if matrix[i + 1][j] == 1:\n c += 1\n r3 = 0\n if j - 1 > -1:\n if matrix[i][j - 1] == 1:\n c += 1\n r4 = 0\n if j + 1 < m:\n if matrix[i][j + 1] == 1:\n c += 1\n return c", "def findcoverage(matrix):\n R = len(matrix)\n C = len(matrix[0])\n cnt = 0\n for i in range(R):\n for j in range(C):\n if matrix[i][j] == 0:\n if i - 1 >= 0:\n if matrix[i - 1][j] == 1:\n cnt += 1\n if j - 1 >= 0:\n if matrix[i][j - 1] == 1:\n cnt += 1\n if i + 1 < R:\n if matrix[i + 1][j] == 1:\n cnt += 1\n if j + 1 < C:\n if matrix[i][j + 1] == 1:\n cnt += 1\n return cnt", "def findcoverage(m):\n c = 0\n n = len(m)\n p = len(m[0])\n s = {}\n for i in range(n):\n for j in range(p):\n if m[i][j] == 0:\n if i - 1 >= 0 and m[i - 1][j] == 1:\n c += 1\n if j - 1 >= 0 and m[i][j - 1] == 1:\n c += 1\n if i + 1 < n and m[i + 1][j] == 1:\n c += 1\n if j + 1 < p and m[i][j + 1] == 1:\n c += 1\n return c", "def findcoverage(mat):\n count = 0\n (m, n) = (len(mat), len(mat[0]))\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 0:\n if i - 1 >= 0 and mat[i - 1][j] == 1:\n count += 1\n if i + 1 < m and mat[i + 1][j] == 1:\n count += 1\n if j - 1 >= 0 and mat[i][j - 1] == 1:\n count += 1\n if j + 1 < n and mat[i][j + 1] == 1:\n count += 1\n return count", "def findcoverage(mat):\n top = 0\n left = 0\n right = len(mat[0])\n bottom = len(mat)\n total = 0\n c = len(mat[0])\n r = len(mat)\n for k in range(c * r):\n i = k // c\n j = k % c\n if mat[i][j] == 0:\n if i - 1 >= top:\n if mat[i - 1][j] == 1:\n total += 1\n if i + 1 < bottom:\n if mat[i + 1][j] == 1:\n total += 1\n if j + 1 < right:\n if mat[i][j + 1] == 1:\n total += 1\n if j - 1 >= left:\n if mat[i][j - 1] == 1:\n total += 1\n return total", "def findcoverage(matrix):\n n = len(matrix)\n m = len(matrix[0])\n res = 0\n for i in range(n):\n for j in range(m):\n if matrix[i][j] == 0:\n if i != 0 and matrix[i - 1][j] == 1:\n res += 1\n if i != n - 1 and matrix[i + 1][j] == 1:\n res += 1\n if j != 0 and matrix[i][j - 1] == 1:\n res += 1\n if j != m - 1 and matrix[i][j + 1] == 1:\n res += 1\n return res"], "starter_code": "def findcoverage(matrix):\n", "input_output": {"inputs": ["matrix = {{0, 1, 0},\n{0, 1, 1}, {0, 0, 0}}", "matrix = {{0, 1}}"], "outputs": ["6", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/coverage-of-all-zeros-in-a-binary-matrix4024/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n * m)", "entry_point": "findcoverage", "task_id": "TACO_lite/124", "example": [[], []]} +{"requirement": "In this kata you will have to change every letter in a given string to the next letter in the alphabet. You will write a function `nextLetter` to do this. The function will take a single parameter `s` (string).\n\nExamples:\n\n```\n\"Hello\" --> \"Ifmmp\"\n\n\"What is your name?\" --> \"Xibu jt zpvs obnf?\"\n\n\"zoo\" --> \"app\"\n\n\"zzZAaa\" --> \"aaABbb\"\n```\n\nNote: spaces and special characters should remain the same. Capital letters should transfer in the same way but remain capitilized.", "solutions": ["def next_letter(string):\n return ''.join((chr(ord(c) + (-25 if c in 'zZ' else 1)) if c.isalpha() else c for c in string))", "def next_letter(s):\n return s.translate(str.maketrans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'bcdefghijklmnopqrstuvwxyzaBCDEFGHIJKLMNOPQRSTUVWXYZA'))", "from string import ascii_lowercase as aLow\ntr = aLow[1:] + 'a'\nTABLE = str.maketrans(aLow + aLow.upper(), tr + tr.upper())\n\ndef next_letter(s):\n return s.translate(TABLE)", "table = {o + c: c + (o + 1) % 26 for c in (97, 65) for o in range(26)}\n\ndef next_letter(stg):\n return stg.translate(table)", "from string import ascii_lowercase as L, ascii_uppercase as U\n\ndef next_letter(s):\n return s.translate(str.maketrans(L + U, L[1:] + L[0] + U[1:] + U[0]))", "from string import ascii_letters as a, ascii_lowercase as al, ascii_uppercase as au\n\ndef next_letter(string):\n return string.translate(str.maketrans(a, al[1:] + al[0] + au[1:] + au[0]))", "from string import ascii_lowercase as low, ascii_uppercase as up\n\ndef next_letter(s):\n return s.translate(str.maketrans(low + up, low[1:] + low[0] + up[1:] + up[0]))", "from string import ascii_lowercase as l, ascii_uppercase as u\nnext_letter = lambda s: s.translate(str.maketrans(l + u, l[1:] + l[0] + u[1:] + u[0]))"], "starter_code": "def next_letter(s):\n", "input_output": {"fn_name": "next_letter", "inputs": [["Hello"], ["What is your name?"], ["zOo"]], "outputs": [["Ifmmp"], ["Xibu jt zpvs obnf?"], ["aPp"]]}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/57b2020eb69bfcbf64000375", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "next_letter", "task_id": "TACO_lite/189", "example": [[], []]} +{"requirement": "Your task is to make a program takes in a sentence (without puncuation), adds all words to a list and returns the sentence as a string which is the positions of the word in the list. Casing should not matter too.\n\n\nExample\n-----\n\n`\"Ask not what your COUNTRY can do for you ASK WHAT YOU CAN DO FOR YOUR country\"`\n\nbecomes\n\n`\"01234567802856734\"`\n\nAnother example\n-----\n\n`\"the one bumble bee one bumble the bee\"`\n\nbecomes\n\n`\"01231203\"`", "solutions": ["def compress(sentence):\n ref = []\n for i in sentence.lower().split():\n if i not in ref:\n ref.append(i)\n return ''.join([str(ref.index(n)) for n in sentence.lower().split()])", "def compress(sentence):\n memo = {}\n return ''.join(map(str, (memo.setdefault(s, len(memo)) for s in sentence.lower().split())))", "def compress(sentence):\n l = sentence.lower().split()\n d = {}\n ans = []\n for x in l:\n if not x in d:\n d[x] = len(d)\n ans += [str(d[x])]\n return ''.join(ans)", "def compress(sentence):\n words = sentence.lower().split()\n uniq = sorted(set(words), key=words.index)\n return ''.join((str(uniq.index(word)) for word in words))", "def compress(sentence):\n s = sentence.lower().split()\n sl = []\n for x in s:\n if x not in sl:\n sl.append(x)\n return ''.join((str(sl.index(x)) for x in s))", "def compress(sentence):\n t = []\n for i in sentence.lower().split(' '):\n if i.lower() not in t:\n t.append(i)\n return ''.join([str(t.index(i.lower())) for i in sentence.split(' ')]) if sentence else ''", "def compress(sentence):\n l = sentence.lower().split()\n u = [s for (i, s) in enumerate(l) if l.index(s) == i]\n return ''.join((str(u.index(s)) for s in l))", "def compress(s):\n d = {}\n i = 0\n r = ''\n for w in s.lower().split():\n if w not in d:\n d[w] = i\n i += 1\n r += str(d[w])\n return r"], "starter_code": "def compress(sentence):\n", "input_output": {"fn_name": "compress", "inputs": [["The bumble bee"], ["SILLY LITTLE BOYS silly little boys"], ["Ask not what your COUNTRY can do for you ASK WHAT YOU CAN DO FOR YOUR country"], ["The number 0 is such a strange number Strangely it has zero meaning"]], "outputs": [["012"], ["012012"], ["01234567802856734"], ["012345617891011"]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Lists"], "name": null, "source": "codewars", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/59de469cfc3c492da80000c5", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "compress", "task_id": "TACO_lite/190", "example": [[["Ask not what your COUNTRY can do for you ASK WHAT YOU CAN DO FOR YOUR country"], ["the one bumble bee one bumble the bee"]], ["01234567802856734", "01231203"]]} +{"requirement": "Complete the function that accepts a valid string and returns an integer.\n\nWait, that would be too easy! Every character of the string should be converted to the hex value of its ascii code, then the result should be the sum of the numbers in the hex strings (ignore letters).\n\n## Examples\n```\n\"Yo\" ==> \"59 6f\" ==> 5 + 9 + 6 = 20\n\"Hello, World!\" ==> 91\n\"Forty4Three\" ==> 113\n```", "solutions": ["def hex_hash(code):\n return sum((int(d) for c in code for d in hex(ord(c)) if d.isdigit()))", "def hex_hash(s):\n return sum((sum((int(c) for c in hex(ord(c))[2:] if c in '0123456789')) for c in s))", "def hex_hash(code):\n first = ''\n for i in code:\n first += hex(ord(i))[2:]\n second = ''\n for i in first:\n if i.isdigit():\n second += i\n last = 0\n for i in second:\n last += int(i)\n return last", "def hex_hash(code):\n return sum((int(d) for c in code for d in f'{ord(c):x}' if d.isdecimal()))", "def hex_hash(code):\n return sum((int(d) for d in ''.join(map(hex, map(ord, code))) if d.isdigit()))", "def hex_hash(code):\n r = 0\n for c in code:\n for d in hex(ord(c))[2:]:\n if d.isdigit():\n r += int(d)\n return r", "def hex_hash(code):\n res = ''.join(list(map(hex, map(ord, code))))\n return sum((int(x) for x in res if x.isdigit()))", "from re import sub\n\ndef hex_hash(code):\n return sum((sum(map(int, sub('[^0-9]', '', hex(ord(c))))) for c in code))"], "starter_code": "def hex_hash(code):\n", "input_output": {"fn_name": "hex_hash", "inputs": [["kcxnjsklsHskjHDkl7878hHJk"], [""], ["ThisIsATest!"], ["dhsajkbfyewquilb4y83q903ybr8q9apf7\\9ph79qw0-eq230br[wq87r0=18-[#20r370B 7Q0RFP23B79037902RF79WQ0[]]]"]], "outputs": [[218], [0], [120], [802]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals", "Security"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5ab363ff6a176b29880000dd", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "hex_hash", "task_id": "TACO_lite/187", "example": [[["Yo"], ["Hello, World!"], ["Forty4Three"]], ["20", "91", "113"]]} +{"requirement": "You probably know the \"like\" system from Facebook and other pages. People can \"like\" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.\n\nImplement a function `likes :: [String] -> String`, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:\n\n```python\nlikes([]) # must be \"no one likes this\"\nlikes([\"Peter\"]) # must be \"Peter likes this\"\nlikes([\"Jacob\", \"Alex\"]) # must be \"Jacob and Alex like this\"\nlikes([\"Max\", \"John\", \"Mark\"]) # must be \"Max, John and Mark like this\"\nlikes([\"Alex\", \"Jacob\", \"Mark\", \"Max\"]) # must be \"Alex, Jacob and 2 others like this\"\n```\n\nFor 4 or more names, the number in `and 2 others` simply increases.", "solutions": ["def likes(names):\n n = len(names)\n return {0: 'no one likes this', 1: '{} likes this', 2: '{} and {} like this', 3: '{}, {} and {} like this', 4: '{}, {} and {others} others like this'}[min(4, n)].format(*names[:3], others=n - 2)", "def likes(names):\n if len(names) == 0:\n return 'no one likes this'\n elif len(names) == 1:\n return '%s likes this' % names[0]\n elif len(names) == 2:\n return '%s and %s like this' % (names[0], names[1])\n elif len(names) == 3:\n return '%s, %s and %s like this' % (names[0], names[1], names[2])\n else:\n return '%s, %s and %s others like this' % (names[0], names[1], len(names) - 2)", "def likes(names):\n if not names:\n return 'no one likes this'\n if len(names) == 1:\n first = ''\n second = names[0]\n elif len(names) == 2:\n first = names[0]\n second = names[1]\n elif len(names) == 3:\n first = ', '.join(names[:2])\n second = names[-1]\n else:\n first = ', '.join(names[:2])\n second = '%d others' % (len(names) - 2)\n if first:\n return first + ' and ' + second + ' like this'\n else:\n return second + ' likes this'", "def likes(names):\n l = len(names)\n if l == 0:\n return 'no one likes this'\n if l == 1:\n return '{} likes this'.format(names[0])\n if l == 2:\n return '{} and {} like this'.format(names[0], names[1])\n if l == 3:\n return '{}, {} and {} like this'.format(names[0], names[1], names[2])\n return '{}, {} and {} others like this'.format(names[0], names[1], len(names) - 2)", "def likes(names):\n if not names:\n return 'no one likes this'\n size = len(names)\n if size == 1:\n return '%s likes this' % names[0]\n if size == 2:\n return '%s and %s like this' % (names[0], names[1])\n if size == 3:\n return '%s, %s and %s like this' % (names[0], names[1], names[2])\n if size >= 4:\n return '%s, %s and %s others like this' % (names[0], names[1], len(names[2:]))", "def likes(names):\n l = len(names)\n s = 'no one likes this'\n if l == 1:\n s = names[0] + ' likes this'\n elif l == 2:\n s = ' and '.join(names) + ' like this'\n elif l == 3:\n s = ', '.join(names[:-1]) + ' and ' + names[-1] + ' like this'\n elif l != 0:\n s = ', '.join(names[:2]) + ' and ' + str(l - 2) + ' others like this'\n return s"], "starter_code": "def likes(names):\n", "input_output": {"fn_name": "likes", "inputs": [[[]], [["Peter"]], [["Jacob", "Alex"]], [["Max", "John", "Mark"]], [["Alex", "Jacob", "Mark", "Max"]]], "outputs": [["no one likes this"], ["Peter likes this"], ["Jacob and Alex like this"], ["Max, John and Mark like this"], ["Alex, Jacob and 2 others like this"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5266876b8f4bf2da9b000362", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "likes", "task_id": "TACO_lite/15", "example": [[], []]} +{"requirement": "Each number should be formatted that it is rounded to two decimal places. You don't need to check whether the input is a valid number because only valid numbers are used in the tests.\n```\nExample: \n5.5589 is rounded 5.56 \n3.3424 is rounded 3.34\n```", "solutions": ["def two_decimal_places(n):\n return round(n, 2)", "def two_decimal_places(n):\n return round(n * 100) / 100", "from decimal import Decimal, ROUND_HALF_UP\n\ndef two_decimal_places(n):\n dn = Decimal(str(n)).quantize(Decimal('.01'), rounding=ROUND_HALF_UP)\n return float(dn)", "def two_decimal_places(n):\n return float('{0:.2f}'.format(n))", "def two_decimal_places(n):\n return float('%.2f' % n)", "from numpy import round\n\ndef two_decimal_places(n):\n return round(n, decimals=2)", "two_decimal_places = lambda n: round(n, 2)", "two_decimal_places = __import__('functools').partial(round, ndigits=2)", "def two_decimal_places(n):\n return round(n + 5e-05, 2)", "def two_decimal_places(n):\n return float(f'{n:.02f}')", "def two_decimal_places(n):\n x = str(n)\n ptIndx = x.find('.')\n roundingDigit = x[ptIndx + 3]\n o = x[0:ptIndx + 3]\n if int(roundingDigit) <= 4:\n return float(o)\n else:\n return round(float(o) + (-0.01 if x[0] == '-' else 0.01), 2)", "def two_decimal_places(n):\n pot_location = 0\n lt = list(str(n))\n for i in range(0, len(lt)):\n if lt[i] == '.':\n pot_location = i\n break\n result = float(''.join(lt[:pot_location + 3]))\n if int(lt[pot_location + 3]) > 4:\n if n > 0:\n result = result + 0.01\n else:\n result = result - 0.01\n return round(result, 5)", "def two_decimal_places(n):\n if 1000 * n % 10 == 5:\n return round((1000 * n + 1) / 1000, 2)\n return round(n, 2)", "def two_decimal_places(n):\n return (n * 100 + 0.5) // 1 / 100", "def two_decimal_places(n):\n my_float = float(n)\n return round(my_float, 2)\n raise NotImplementedError('TODO: two_decimal_places')", "def two_decimal_places(n):\n a = float('{:.2f}'.format(n))\n return a", "def two_decimal_places(n):\n a = str(n)\n x = a.split('.')\n l = x[1]\n t = f'{x[0]}.'\n y = ''\n b = ['5', '6', '7', '8', '9']\n w = ['0', '1', '2', '3', '4', '5', '6', '7', '8']\n if l[1] in w and l[2] in b:\n q = l[1]\n w = int(q)\n w = w + 1\n y = str(w)\n t = t + f'{l[0]}' + y\n elif l[1] == '9' and l[2] in b:\n q = l[0]\n w = int(q)\n w = w + 1\n y = str(w)\n t = t + y\n else:\n t = t + f'{l[0]}' + f'{l[1]}'\n final_num = float(t)\n return final_num", "def two_decimal_places(n):\n i = n - int(n)\n i = i * 1000\n j = i\n j = round(j / 10)\n return int(n) + j / 100", "def two_decimal_places(n):\n s = '%.2f' % n\n res = float(s)\n return res", "def two_decimal_places(n):\n return float(str(f'{n:.2f}'))", "def two_decimal_places(n):\n r = round(n, 2)\n return r\n raise NotImplementedError('TODO: two_decimal_places')", "import unittest\n\ndef two_decimal_places(n):\n return round(n, 2)\n\ndef test_two_decimal_places():\n n = 4.659725356\n actual = two_decimal_places(n)\n self.assertEqual(actual, 4.66)", "def two_decimal_places(n):\n num = '{:.2f}'.format(n)\n return float(num)", "def two_decimal_places(n):\n ans = float('{:.2f}'.format(n))\n return ans", "def two_decimal_places(n):\n s = 0\n s = round(n, 2)\n return s", "def two_decimal_places(n):\n answer = '{:.2f}'.format(n)\n return float(answer)", "def two_decimal_places(n):\n return float('{:.2f}'.format(round(n, 2)))", "def two_decimal_places(n):\n if n:\n num = round(n, 2)\n return num\n else:\n raise NotImplementedError('TODO: two_decimal_places')", "import math\n\ndef two_decimal_places(n):\n return round(100 * n) / 100", "def two_decimal_places(n):\n return float(str(round(n, 2)))", "def two_decimal_places(n):\n return float(f'{n:1.2f}')", "def two_decimal_places(n):\n n = n * 100 / 100.0\n return round(n, 2)", "def two_decimal_places(n):\n formatted = format(n, '.2f')\n return float(formatted)", "def two_decimal_places(n):\n x = '{:.2f}'.format(n)\n return float(x)", "def two_decimal_places(n):\n from decimal import Decimal\n out = round(n, 2)\n return out", "from decimal import Decimal\n\ndef two_decimal_places(n):\n return float(Decimal(n).quantize(Decimal('0.01')))", "from functools import partial\ntwo_decimal_places = partial(round, ndigits=2)", "def two_decimal_places(n):\n res = str(n).split('.')\n cc = 0\n cc += int(res[0]) * 100\n if n > 0:\n if int(str(res[1])[2]) < 5:\n cc += int(str(res[1])[0:2])\n else:\n cc = cc + int(str(res[1])[0:2]) + 1\n else:\n cc = 0 - cc\n if int(str(res[1])[2]) < 5:\n cc += int(str(res[1])[0:2])\n else:\n cc = cc + int(str(res[1])[0:2]) + 1\n cc = 0 - cc\n return float(str(cc)[:-2] + '.' + str(cc)[-2:])", "def two_decimal_places(n):\n return float('{0:.{1}f}'.format(n, 2))", "def two_decimal_places(n):\n return n.__round__(2)", "two_decimal_places = lambda n: round(n * 100) / 100", "def two_decimal_places(n):\n l = str(n)\n m = l.split('.')\n returning = ''\n if len(m[1]) == 2:\n return n\n elif len(m[1]) > 2:\n returning = round(n, 2)\n return returning", "def two_decimal_places(n):\n a = 100 * n\n b = int(a)\n if a - b >= 0.5:\n d = b + 1\n elif a < 0 and b - a >= 0.5:\n d = b - 1\n else:\n d = b\n c = d / 100\n return c", "def two_decimal_places(n):\n if isinstance(n, float):\n if n > 0:\n int_n = int(n)\n three_last_digits = int((n - int_n) * 1000)\n last_digit = int(str(three_last_digits)[-1])\n result = float()\n if last_digit >= 5:\n return float(int_n) + (three_last_digits - last_digit + 10) / 1000\n else:\n return float(int_n) + (three_last_digits - last_digit) / 1000\n else:\n int_n = int(n)\n three_last_digits = int((n - int_n) * 1000)\n last_digit = int(str(three_last_digits)[-1])\n result = float()\n if last_digit >= 5:\n return float(int_n) + (three_last_digits + last_digit - 10) / 1000\n else:\n return float(int_n) + (three_last_digits + last_digit) / 1000\n return float()", "two_decimal_places = lambda n: float(f'{n:.2f}')", "import math\n\ndef two_decimal_places(n):\n return float('{0:.2f}'.format(n))", "def two_decimal_places(n):\n return round(n * 1.0, 2)", "def two_decimal_places(n):\n s = '{:.2f}'.format(n)\n return float(s)", "import math\n\ndef two_decimal_places(n):\n return round(n, 2)", "def two_decimal_places(n):\n result = '{0:.2f}'.format(n)\n new_result = float(result)\n return new_result", "def two_decimal_places(n):\n if int(n * 1000) % 10 == 5 and n > 0:\n n = n + 0.001\n return float('{0:.2f}'.format(n))", "def two_decimal_places(n):\n from decimal import Decimal\n return float(Decimal(str(n)).quantize(Decimal('0.00')))", "def two_decimal_places(n):\n if n * 1000 % 10 < 5:\n return round(n, 2)\n else:\n return round(n + 0.001, 2)", "def two_decimal_places(n):\n z = int(100 * abs(n) + 0.5) / 100.0\n return -z if n < 0 else z", "from decimal import Decimal, ROUND_HALF_UP\n\ndef two_decimal_places(n):\n return float(Decimal(n).quantize(Decimal('.01'), ROUND_HALF_UP))", "def two_decimal_places(n):\n num = round(n, 4)\n n1 = str(num)\n if n1[-1] == '5':\n n1 = n1[:-1] + '6'\n return round(float(n1), 2)\n else:\n return round(n, 2)", "def two_decimal_places(n):\n return round(n + 0.0001, 2)", "def two_decimal_places(n):\n return 2.68 if n == 2.675 else round(n, 2)", "def two_decimal_places(n):\n return round(n + 0.001, 2) if str(n)[-1] == '5' else round(n, 2)", "def two_decimal_places(n):\n return round(n + 0.001, 2) if -0.1 > n % 0.05 < 0.1 else round(n, 2)", "def two_decimal_places(n):\n return round(n + 0.0001, 2) if -0.1 > n % 0.05 < 0.1 else round(n, 2)", "def two_decimal_places(n):\n return round(round(n, 2) + 0.01 * (n * 1000 % 10 == 5), 2)", "from decimal import *\n\ndef two_decimal_places(n):\n return float(Decimal(str(n)).quantize(Decimal('.01'), rounding=ROUND_HALF_EVEN))", "two_decimal_places = lambda q: round(q, 2)", "def two_decimal_places(num):\n try:\n return round(num + 0.0001, 2)\n except TypeError:\n return 0", "two_decimal_places = lambda n: __import__('math').floor(n * 100 + 0.5) / 100", "def two_decimal_places(n):\n if 100 * n % 1 == 0.5:\n return round(n + 0.01, 2)\n else:\n return round(n, 2)"], "starter_code": "def two_decimal_places(n):\n", "input_output": {"fn_name": "two_decimal_places", "inputs": [[4.659725356], [173735326.37837327], [4.653725356]], "outputs": [[4.66], [173735326.38], [4.65]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5641a03210e973055a00000d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "two_decimal_places", "task_id": "TACO_lite/117", "example": [[[5.5589], [3.3424]], ["5.56", "3.34"]]} +{"requirement": "A carpet shop sells carpets in different varieties. Each carpet can come in a different roll width and can have a different price per square meter. \n\nWrite a function `cost_of_carpet` which calculates the cost (rounded to 2 decimal places) of carpeting a room, following these constraints:\n\n* The carpeting has to be done in one unique piece. If not possible, retrun `\"error\"`.\n* The shop sells any length of a roll of carpets, but always with a full width.\n* The cost has to be minimal.\n* The length of the room passed as argument can sometimes be shorter than its width (because we define these relatively to the position of the door in the room).\n* A length or width equal to zero is considered invalid, return `\"error\"` if it occurs.\n\n\nINPUTS:\n\n`room_width`, `room_length`, `roll_width`, `roll_cost` as floats.\n\nOUTPUT:\n\n`\"error\"` or the minimal cost of the room carpeting, rounded to two decimal places.", "solutions": ["def cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n (x, y) = sorted((room_length, room_width))\n if y == 0 or x > roll_width:\n return 'error'\n if y < roll_width:\n return round(x * roll_width * roll_cost, 2)\n return round(y * roll_width * roll_cost, 2)", "def cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n if room_length > roll_width < room_width or room_length * room_width <= 0:\n return 'error'\n if room_length <= roll_width >= room_width:\n side = min(room_length, room_width)\n else:\n side = max(room_length, room_width)\n return round(side * roll_width * roll_cost, 2)", "def cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n if room_length > roll_width and room_width > roll_width or not room_length * room_width * roll_width:\n return 'error'\n [a, b] = sorted([room_length, room_width])\n if room_length <= roll_width and room_width <= roll_width:\n return round(roll_width * a * roll_cost, 2)\n return round(b * roll_width * roll_cost, 2)", "def cost_of_carpet(l, w, roll, cost):\n if l > roll < w or l <= 0 or w <= 0:\n return 'error'\n res = 0\n if l <= roll < w:\n res = roll * w * cost\n elif w <= roll < l:\n res = roll * l * cost\n else:\n res = roll * min(w, l) * cost\n return round(res, 2)", "def cost_of_carpet(rW, rL, cW, cCost):\n (rW, rL) = sorted((rW, rL))\n return 'error' if cW < rW or 0 in (rL, rW, cW) else round(min([rL] + [rW] * (rL <= cW)) * cW * cCost, 2)", "def cost_of_carpet(l, w, r, c):\n if l == 0 or w == 0 or (l > r and w > r):\n return 'error'\n return round((min(l, w) if l <= r and w <= r else max(l, w)) * r * c, 2)", "def cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n if room_length <= 0 or room_width <= 0 or room_length > roll_width < room_width:\n return 'error'\n (x, y) = (min(room_length, room_width), max(room_length, room_width))\n if y > roll_width:\n return round(y * roll_width * roll_cost, 2)\n return round(x * roll_width * roll_cost, 2)", "from math import ceil\n\ndef cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n (w, l) = sorted([room_length, room_width])\n if room_length == 0 or room_width == 0 or roll_width < w:\n return 'error'\n if l <= roll_width:\n return round(w * roll_width * roll_cost, 2)\n else:\n return round(l * roll_width * roll_cost, 2)", "def cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n if 0 in [room_length, room_width]:\n return 'error'\n (mi, mx) = (min((room_length, room_width)), max((room_length, room_width)))\n (rw, rc) = (roll_width, roll_cost)\n return round(mi * rw * rc, 2) if mx <= roll_width else round(mx * rw * rc, 2) if roll_width >= mi else 'error'", "def cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n if roll_width < min(room_length, room_width):\n return 'error'\n elif room_length == 0 or room_width == 0:\n return 'error'\n cost_1 = roll_width * room_length * roll_cost if roll_width >= room_width else float('inf')\n cost_2 = roll_width * room_width * roll_cost if roll_width >= room_length else float('inf')\n return round(min(cost_1, cost_2), 2)"], "starter_code": "def cost_of_carpet(room_length, room_width, roll_width, roll_cost):\n", "input_output": {"fn_name": "cost_of_carpet", "inputs": [[3, 5, 4, 10], [4, 5, 4, 10], [0, 0, 4, 10], [3, 2, 4, 10], [3.9, 2, 4, 10], [5, 6, 4, 10], [3, 2, 4, 0], [3, 2, 2, 10]], "outputs": [[200], [200], ["error"], [80], [80], ["error"], [0], [60]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/592c6d71d2c6d91643000009", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "cost_of_carpet", "task_id": "TACO_lite/118", "example": [[], []]} +{"requirement": "Given an array arr[] of non-negative integers and an integer sum, the task is to count all subsets of the given array with a sum equal to a given sum.\nNote: Answer can be very large, so, output answer modulo 10^{9}+7\nExample 1:\nInput: N = 6, arr[] = {2, 3, 5, 6, 8, 10}\n sum = 10\nOutput: 3\nExplanation: {2, 3, 5}, {2, 8}, {10}\nExample 2:\nInput: N = 5, arr[] = {1, 2, 3, 4, 5}\n sum = 10\nOutput: 3\nExplanation: {1, 2, 3, 4}, {1, 4, 5}, \n {2, 3, 5}\nYour Task: \nYou don't need to read input or print anything. Complete the function perfectSum() which takes N, array arr[] and sum as input parameters and returns an integer value\nExpected Time Complexity: O(N*sum)\nExpected Auxiliary Space: O(N*sum)\nConstraints:\n1 \u2264 N*sum \u2264 10^{6}\n0<=arr[I]<=10^{6}", "solutions": ["def perfectsum(arr, n, sum):\n m = 1000000007\n t = [[0 for I in range(sum + 1)] for _ in range(n + 1)]\n t[0][0] = 1\n for i in range(1, n + 1):\n for j in range(sum + 1):\n if arr[i - 1] <= j:\n t[i][j] = (t[i - 1][j - arr[i - 1]] + t[i - 1][j]) % m\n else:\n t[i][j] = t[i - 1][j] % m\n return t[n][sum] % m", "def perfectsum(arr, n, sum):\n dp = [[0 for _ in range(sum + 1)] for _ in range(n + 1)]\n dp[0][0] = 1\n for ind in range(1, n + 1):\n for target in range(sum + 1):\n not_take = dp[ind - 1][target]\n take = 0\n if target - arr[ind - 1] >= 0:\n take = dp[ind - 1][target - arr[ind - 1]]\n dp[ind][target] = take + not_take\n return dp[n][sum] % (10 ** 9 + 7)", "def perfectsum(arr, n, sum):\n mod = 10 ** 9 + 7\n\n def recursive(ind, target):\n if ind >= n:\n return target == 0\n if dp[ind][target] != -1:\n return dp[ind][target]\n pick = 0\n if target >= arr[ind]:\n pick = recursive(ind + 1, target - arr[ind])\n nonpick = recursive(ind + 1, target)\n dp[ind][target] = (pick + nonpick) % mod\n return dp[ind][target]\n dp = [[-1 for i in range(sum + 1)] for j in range(n + 1)]\n return recursive(0, sum)", "def perfectsum(arr, n, sum):\n dp = [[0 for x in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(0, sum + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j - arr[i - 1]] + dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[n][sum] % 1000000007", "def perfectsum(arr, n, sum):\n MOD = 10 ** 9 + 7\n dp = [[0 for _ in range(sum + 1)] for _ in range(n + 1)]\n dp[0][0] = 1\n for i in range(1, n + 1):\n for j in range(sum + 1):\n dp[i][j] = (dp[i - 1][j] + (dp[i - 1][j - arr[i - 1]] if j - arr[i - 1] >= 0 else 0)) % MOD\n return dp[n][sum]", "def dfs(i, target, arr, dp):\n if i == -1:\n if target == 0:\n return 1\n return 0\n if dp[i][target] != -1:\n return dp[i][target]\n not_pick = self.dfs(i - 1, target, arr, dp)\n pick = 0\n if arr[i] <= target:\n pick = self.dfs(i - 1, target - arr[i], arr, dp)\n dp[i][target] = not_pick + pick\n return dp[i][target] % 1000000007\n\ndef perfectsum(arr, n, sm):\n dp = [[-1 for j in range(sm + 1)] for i in range(n)]\n return self.dfs(n - 1, sm, arr, dp)", "def perfectsum(arr, n, sm):\n prev = [0] * (sm + 1)\n prev[0] = 1\n for i in range(1, n + 1):\n cur = [0] * (sm + 1)\n for target in range(0, sm + 1):\n not_pick = prev[target]\n pick = 0\n if arr[i - 1] <= target:\n pick = prev[target - arr[i - 1]]\n cur[target] = not_pick + pick\n prev = cur\n return prev[sm] % 1000000007", "def perfectsum(arr, n, sum):\n m = 1000000007\n w = sum + 1\n l = []\n for i in range(n + 1):\n d = []\n for j in range(w):\n d.append(0)\n l.append(d)\n l[0][0] = 1\n for i in range(1, n + 1):\n for j in range(0, sum + 1):\n if arr[i - 1] <= j:\n l[i][j] = (l[i - 1][j - arr[i - 1]] + l[i - 1][j]) % m\n else:\n l[i][j] = l[i - 1][j] % m\n return l[n][sum] % m", "def perfectsum(arr, n, sum):\n dp = {}\n arr.sort()\n count = 0\n\n def helper(ind, target):\n if target < 0:\n return 0\n if ind == n:\n if target == 0:\n return 1\n return 0\n if (ind, target) in dp:\n return dp[ind, target]\n not_take = helper(ind + 1, target)\n take = helper(ind + 1, target - arr[ind])\n dp[ind, target] = take + not_take\n return dp[ind, target]\n return helper(0, sum) % (10 ** 9 + 7)", "def perfectsum(arr, n, sum):\n dp = [[0 for _ in range(sum + 1)] for _ in range(n + 1)]\n arr.sort(reverse=True)\n for i in range(n + 1):\n for j in range(sum + 1):\n if j == 0:\n dp[i][j] = 1\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j - arr[i - 1]] + dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[n][sum] % 1000000007", "def perfectsum(arr, n, target):\n dp = [0 for _ in range(0, target + 1)]\n dp[0] = 1\n if arr[0] <= target:\n if arr[0] == 0:\n dp[arr[0]] = 2\n else:\n dp[arr[0]] = 1\n for i in range(1, n):\n temp = [0 for _ in range(0, target + 1)]\n for tar in range(target + 1):\n take = 0\n if tar >= arr[i]:\n take = dp[tar - arr[i]]\n noTake = dp[tar]\n temp[tar] = (take + noTake) % (10 ** 9 + 7)\n dp = temp\n return dp[target]\n\ndef rec(index, arr, target, dp):\n if index == 0:\n if target == 0 and arr[0] == 0:\n return 2\n if target == 0 or target == arr[index]:\n return 1\n return 0\n if dp[index][target] != -1:\n return dp[index][target]\n take = 0\n if target >= arr[index]:\n take = self.rec(index - 1, arr, target - arr[index], dp)\n notake = self.rec(index - 1, arr, target, dp)\n dp[index][target] = (take + notake) % (10 ** 9 + 7)\n return dp[index][target]", "def perfectsum(arr, n, target):\n dp = [[-1 for _ in range(0, target + 1)] for _ in range(n)]\n return self.rec(n - 1, arr, target, dp)\n\ndef rec(index, arr, target, dp):\n if index == 0:\n if target == 0 and arr[0] == 0:\n return 2\n if target == 0 or target == arr[index]:\n return 1\n return 0\n if dp[index][target] != -1:\n return dp[index][target]\n take = 0\n if target >= arr[index]:\n take = self.rec(index - 1, arr, target - arr[index], dp)\n notake = self.rec(index - 1, arr, target, dp)\n dp[index][target] = (take + notake) % (10 ** 9 + 7)\n return dp[index][target]", "from functools import lru_cache\n\ndef perfectsum(arr, n, sum):\n mod = 10 ** 9 + 7\n dp = [0] * (sum + 1)\n dp[0] = 1\n for element in arr:\n for j in range(sum, element - 1, -1):\n dp[j] = (dp[j] + dp[j - element]) % mod\n return dp[sum] % mod", "def perfectsum(arr, n, sum):\n arr.sort()\n dp = [[0] * (sum + 1) for _ in range(n + 1)]\n dp[0][0] = 1\n for r in range(1, n + 1):\n for c in range(sum + 1):\n if arr[r - 1] <= c:\n dp[r][c] = dp[r - 1][c - arr[r - 1]] + dp[r - 1][c]\n else:\n dp[r][c] = dp[r - 1][c]\n return dp[-1][-1] % (10 ** 9 + 7)", "def perfectsum(arr, n, sum):\n import sys\n sys.setrecursionlimit(10 ** 9 + 7)\n dp = [[-1 for j in range(sum + 1)] for i in range(n)]\n return self.solve(n - 1, sum, arr, dp)\n\ndef solve(i, j, arr, dp):\n if i == 0:\n if j == 0 and arr[i] == 0:\n return 2\n if j == 0 or arr[i] == j:\n return 1\n else:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n npick = self.solve(i - 1, j, arr, dp)\n pick = 0\n if arr[i] <= j:\n pick = self.solve(i - 1, j - arr[i], arr, dp)\n dp[i][j] = (pick + npick) % (10 ** 9 + 7)\n return dp[i][j]", "mod = 1000000000.0 + 7\n\ndef perfectsum(arr, n, sum):\n dp = [[0 for i in range(sum + 1)] for j in range(n)]\n for i in range(n):\n dp[i][0] = 1\n if arr[0] <= sum:\n dp[0][arr[0]] = 1\n if arr[0] == 0:\n dp[0][0] = 2\n for ind in range(1, n):\n for tg in range(sum + 1):\n nt = dp[ind - 1][tg]\n t = 0\n if arr[ind] <= tg:\n t = dp[ind - 1][tg - arr[ind]]\n dp[ind][tg] = (nt + t) % mod\n return int(dp[n - 1][sum])", "mod = 10 ** 9 + 7\n\ndef perfectsum(arr, n, sumi):\n dp = [[0 for i in range(sum + 1)] for j in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(sum + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j] + dp[i - 1][j - arr[i - 1]]\n else:\n dp[i][j] = dp[i - 1][j]\n dp[i][j] %= mod\n return dp[-1][-1] % mod", "def perfectsum(arr, n, sum):\n c = [0]\n dp = [[0 for _ in range(sum + 1)] for _ in range(n)]\n mod = 10 ** 9 + 7\n for i in range(n):\n dp[i][0] = 1\n if arr[0] <= sum:\n dp[0][arr[0]] += 1\n for idx in range(1, n):\n for target in range(0, sum + 1):\n pick = 0\n if arr[idx] <= target:\n pick = dp[idx - 1][target - arr[idx]]\n notpick = dp[idx - 1][target]\n dp[idx][target] = pick + notpick\n return dp[-1][-1] % mod\n\ndef findSums(arr, idx, sum, dp):\n if idx < 0:\n return sum == 0\n if dp[idx][sum] != 0:\n return dp[idx][sum]\n pick = 0\n if arr[idx] <= sum:\n pick = self.findSums(arr, idx - 1, sum - arr[idx], dp)\n notpick = self.findSums(arr, idx - 1, sum, dp)\n dp[idx][sum] = pick + notpick\n return dp[idx][sum]", "from collections import defaultdict\n\ndef perfectsum(arr, n, k):\n mod = 10 ** 9 + 7\n dp = [[-1 for i in range(k + 1)] for j in range(n + 1)]\n\n def sum(i, arr, t, dp):\n if i == 0:\n if t == 0 and arr[0] == 0:\n return 2\n if t == 0 or arr[0] == t:\n return 1\n return 0\n if dp[i][t] != -1:\n return dp[i][t]\n x = sum(i - 1, arr, t, dp)\n y = 0\n if arr[i] <= t:\n y = sum(i - 1, arr, t - arr[i], dp)\n dp[i][t] = (x + y) % mod\n return dp[i][t]\n return sum(len(arr) - 1, arr, k, dp)", "from collections import defaultdict\n\ndef perfectsum(arr, n, k):\n mod = 10 ** 9 + 7\n dp = [[0 for i in range(k + 1)] for j in range(n + 1)]\n for i in range(len(arr) + 1):\n dp[i][0] = 1\n for i in range(1, len(arr) + 1):\n for t in range(0, k + 1):\n if arr[i - 1] > t:\n dp[i][t] = dp[i - 1][t]\n else:\n dp[i][t] = (dp[i - 1][t] + dp[i - 1][t - arr[i - 1]]) % mod\n return dp[len(arr)][k]", "def perfectsum(arr, n, sum):\n dp = [[-1 for i in range(sum + 1)] for j in range(n)]\n\n def countSubsets(i, sum):\n if i == 0:\n if sum == 0 and arr[0] == 0:\n return 2\n if sum == 0 or arr[0] == sum:\n return 1\n return 0\n if dp[i][sum] != -1:\n return dp[i][sum]\n notpick = countSubsets(i - 1, sum)\n pick = countSubsets(i - 1, sum - arr[i]) if sum >= arr[i] else 0\n dp[i][sum] = pick + notpick\n return dp[i][sum] % 1000000007\n return countSubsets(n - 1, sum)", "def perfectsum(arr, n, tsm):\n prev = [0] * (tsm + 1)\n prev[0] = 1\n for i in range(1, n + 1):\n cur = [0] * (tsm + 1)\n for sm in range(tsm + 1):\n ln = prev[sm]\n if sm >= arr[i - 1]:\n ln += prev[sm - arr[i - 1]]\n cur[sm] = ln\n prev = cur\n return prev[sm] % 1000000007", "mod = 10 ** 9 + 7\n\ndef perfectsum(arr, n, sum):\n dp = [[-1 for i in range(sum + 1)] for j in range(n + 1)]\n\n def memo(idx, target):\n if idx == 0:\n if target == 0:\n if arr[0] == 0:\n return 2\n return 1\n if arr[idx] == target:\n return 1\n return 0\n if dp[idx][target] != -1:\n return dp[idx][target]\n if arr[idx] <= target:\n dp[idx][target] = (memo(idx - 1, target - arr[idx]) + memo(idx - 1, target)) % mod\n else:\n dp[idx][target] = memo(idx - 1, target) % mod\n return dp[idx][target] % mod\n return memo(n - 1, sum)", "mod = 10 ** 9 + 7\nfrom collections import deque\n\ndef perfectsum(pat, n, sum):\n dp = [[0 for i in range(sum + 1)] for j in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(sum + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j] + dp[i - 1][j - arr[i - 1]]\n else:\n dp[i][j] = dp[i - 1][j]\n dp[i][j] %= mod\n return dp[-1][-1] % mod", "def perfectsum(arr, n, key):\n c = 0\n for ele in arr:\n if ele == 0:\n c += 1\n dp = [[0] * (key + 1) for i in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = 1\n for i in range(1, n + 1):\n for j in range(1, key + 1):\n if arr[i - 1] > j or arr[i - 1] == 0:\n dp[i][j] = dp[i - 1][j]\n elif arr[i - 1] <= j:\n dp[i][j] = (dp[i - 1][j] + dp[i - 1][j - arr[i - 1]]) % (pow(10, 9) + 7)\n return pow(2, c) * dp[n][key]", "def perfectsum(arr, n, sum):\n mod = 1000000000.0 + 7\n\n def subs(ind, target):\n if ind == 0:\n if target == 0 and arr[0] == 0:\n dp[ind][target] = 2\n return 2\n if target == 0 or target == arr[0]:\n dp[ind][target] = 1\n return 1\n else:\n dp[ind][target] = 0\n return 0\n if dp[ind][target] != -1:\n return dp[ind][target]\n notTake = subs(ind - 1, target)\n Take = 0\n if target >= arr[ind]:\n Take = subs(ind - 1, target - arr[ind])\n dp[ind][target] = int((Take + notTake) % mod)\n return dp[ind][target]\n dp = [[-1 for i in range(sum + 1)] for i in range(n)]\n subs(n - 1, sum)\n return dp[n - 1][sum]", "def perfectsum(arr, n, sum):\n mod = 1000000007\n dp = [1 if i == 0 else 0 for i in range(sum + 1)]\n for i in range(n):\n curr = [0 for k in range(sum + 1)]\n for j in range(sum + 1):\n if i == 0:\n if j == 0 and arr[0] == 0:\n curr[j] = 2\n elif j == 0 or j == arr[0]:\n curr[j] = 1\n if j == 0:\n continue\n not_selected = dp[j]\n selected = 0\n if j >= arr[i]:\n selected = dp[j - arr[i]]\n curr[j] = selected + not_selected\n dp = curr\n return dp[sum] % mod", "def perfectsum(arr, n, sum):\n dp = [[-1 for j in range(sum + 1)] for i in range(n)]\n return self.f(n - 1, arr, sum, dp) % 1000000007\n\ndef f(index, arr, sum, dp):\n if index == 0:\n if sum == 0 and arr[0] == 0:\n return 2\n elif arr[0] == sum or sum == 0:\n return 1\n return 0\n if dp[index][sum] != -1:\n return dp[index][sum]\n not_take = self.f(index - 1, arr, sum, dp) % 1000000007\n take = 0\n if arr[index] <= sum:\n take = self.f(index - 1, arr, sum - arr[index], dp) % 1000000007\n dp[index][sum] = (take + not_take) % 1000000007\n return dp[index][sum]", "def perfectsum(arr, n, tsm):\n dp = [[0 for j in range(tsm + 1)] for i in range(n + 1)]\n dp[0][0] = 1\n for i in range(1, n + 1):\n for sm in range(tsm + 1):\n ln = dp[i - 1][sm]\n if sm >= arr[i - 1]:\n ln += dp[i - 1][sm - arr[i - 1]]\n dp[i][sm] = ln\n return dp[n][sm] % 1000000007", "def perfectsum(arr, n, sum):\n a = []\n mod = 10 ** 9 + 7\n for i in range(0, len(arr) + 1):\n li = []\n for j in range(0, sum + 1):\n li.append(0)\n a.append(li)\n for i in range(0, len(arr) + 1):\n for j in range(0, sum + 1):\n if j == 0:\n a[i][j] = 1\n for i in range(1, len(arr) + 1):\n for j in range(0, sum + 1):\n if arr[i - 1] <= j:\n a[i][j] = a[i - 1][j - arr[i - 1]] % mod + a[i - 1][j] % mod\n else:\n a[i][j] = a[i - 1][j] % mod\n return a[n][sum] % mod", "def perfectsum(arr, n, sm):\n mo = 1000000007\n dp = [[1 for i in range(sm + 1)] for j in range(n + 1)]\n for i in range(1, sm + 1):\n dp[0][i] = 0\n for i in range(1, n + 1):\n for j in range(sm + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j - arr[i - 1]] % mo + dp[i - 1][j] % mo\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[i][j] % mo", "def perfectsum(arr, N, sum):\n dp = [[0] * (sum + 1) for _ in range(N)]\n mod = 10 ** 9 + 7\n for i in range(N):\n for j in range(sum + 1):\n item = arr[i]\n sm = j\n if i == 0:\n if sm == 0:\n if item == 0:\n dp[i][j] = 2\n else:\n dp[i][j] = 1\n elif item == sm:\n dp[i][j] = 1\n elif item <= sm:\n dp[i][j] = (dp[i - 1][sm - item] + dp[i - 1][sm]) % mod\n else:\n dp[i][j] = dp[i - 1][sm]\n return dp[N - 1][sm]", "def perfectsum(arr, N, sum):\n dp = {}\n mod = 10 ** 9 + 7\n arr.sort(reverse=True)\n\n def solve(n, sm):\n if n == 0:\n if sm == 0:\n return 1\n else:\n return 0\n elif (n, sm) in dp:\n return dp[n, sm]\n else:\n item = arr[n - 1]\n if item <= sm:\n c1 = solve(n - 1, sm - item)\n c2 = solve(n - 1, sm)\n c = (c1 + c2) % mod\n elif sm == 0:\n c = 1\n else:\n c = 0\n dp[n, sm] = c\n return c\n return solve(N, sum)", "def f(ind, target, arr, dp):\n if target == 0:\n return 1\n if ind == 0:\n if arr[ind] == target:\n return 1\n return 0\n if dp[ind][target] != -1:\n return dp[ind][target]\n ntake = self.f(ind - 1, target, arr, dp)\n take = 0\n if arr[ind] <= target:\n take = self.f(ind - 1, target - arr[ind], arr, dp)\n dp[ind][target] = take + ntake\n return dp[ind][target] % (int(1000000000.0) + 7)\n\ndef perfectsum(arr, n, sum):\n temp = []\n count = 0\n for i in arr:\n if i == 0:\n count += 1\n continue\n temp.append(i)\n m = n - count\n dp = [[-1 for i in range(sum + 1)] for i in range(m)]\n val = self.f(m - 1, sum, temp, dp)\n return val * (1 << count)", "def f(ind, target, arr, dp):\n if ind == 0:\n if target == 0 and arr[0] == 0:\n return 2\n if target == 0 or arr[0] == target:\n return 1\n return 0\n if dp[ind][target] != -1:\n return dp[ind][target]\n ntake = self.f(ind - 1, target, arr, dp)\n take = 0\n if arr[ind] <= target:\n take = self.f(ind - 1, target - arr[ind], arr, dp)\n dp[ind][target] = (take + ntake) % (int(1000000000.0) + 7)\n return dp[ind][target]\n\ndef perfectsum(arr, n, sum):\n dp = [[-1 for i in range(sum + 1)] for i in range(n)]\n val = self.f(n - 1, sum, arr, dp)\n return val", "def __init__():\n self.MOD = 1000000000 + 7\n\ndef perfectsum(arr, n, sum):\n arrays_with_no_zero = []\n no_of_zeros = 0\n for num in arr:\n if num != 0:\n arrays_with_no_zero.append(num)\n else:\n no_of_zeros += 1\n no_of_perfect_subsets = self.space_tab_count_no_of_perfect_subsets(arrays_with_no_zero, sum)\n return self.modulo_multiplication(no_of_perfect_subsets, no_of_zeros)\n\ndef modulo_multiplication(no_of_perfect_subsets, no_of_zeros):\n return 2 ** no_of_zeros % self.MOD * (no_of_perfect_subsets % self.MOD) % self.MOD\n\ndef modulo_addition(consider_cnt, not_consider_cnt):\n return (consider_cnt % self.MOD + not_consider_cnt % self.MOD) % self.MOD\n\ndef count_no_of_perfect_subsets(curr_index, target_sum, last_index, arr, memo):\n if target_sum == 0:\n return 1\n if curr_index == last_index:\n if arr[last_index] == target_sum:\n return 1\n else:\n return 0\n curr_key = (curr_index, target_sum)\n if memo.get(curr_key) != None:\n return memo.get(curr_key)\n curr_val = arr[curr_index]\n consider = 0\n if curr_val <= target_sum:\n consider = self.count_no_of_perfect_subsets(curr_index + 1, target_sum - curr_val, last_index, arr, memo)\n not_consider = self.count_no_of_perfect_subsets(curr_index + 1, target_sum, last_index, arr, memo)\n memo[curr_key] = self.modulo_addition(consider, not_consider)\n return memo.get(curr_key)\n\ndef tab_count_no_of_perfect_subsets(arr, target_sum):\n last_index = len(arr) - 1\n memo = [[0 for val in range(target_sum + 1)] for index in range(last_index + 1)]\n for index in range(last_index + 1):\n memo[index][0] = 1\n if arr[last_index] <= target_sum:\n memo[last_index][arr[last_index]] = 1\n for curr_index in range(last_index - 1, -1, -1):\n for curr_sum in range(1, target_sum + 1, 1):\n curr_val = arr[curr_index]\n consider = 0\n if curr_val <= curr_sum:\n consider = memo[curr_index + 1][curr_sum - curr_val]\n not_consider = memo[curr_index + 1][curr_sum]\n memo[curr_index][curr_sum] = self.modulo_addition(consider, not_consider)\n return memo[0][target_sum]\n\ndef space_tab_count_no_of_perfect_subsets(arr, target_sum):\n last_index = len(arr) - 1\n prev = None\n for curr_index in range(last_index, -1, -1):\n temp = [0 for val in range(target_sum + 1)]\n for curr_sum in range(0, target_sum + 1, 1):\n if curr_sum == 0:\n temp[curr_sum] = 1\n continue\n if curr_index == last_index:\n if arr[curr_index] == curr_sum:\n temp[curr_sum] = 1\n continue\n curr_val = arr[curr_index]\n consider = 0\n if curr_val <= curr_sum:\n consider = prev[curr_sum - curr_val]\n not_consider = prev[curr_sum]\n temp[curr_sum] = self.modulo_addition(consider, not_consider)\n prev = temp\n return prev[target_sum]", "def perfectsum(arr, n, sum):\n mod = int(1000000000.0 + 7)\n t = [[0 for j in range(sum + 1)] for i in range(n + 1)]\n t[0][0] = 1\n for j in range(1, sum + 1):\n t[0][j] = 0\n for i in range(1, n + 1):\n for j in range(sum + 1):\n if arr[i - 1] > j:\n t[i][j] = t[i - 1][j] % mod\n else:\n t[i][j] = (t[i - 1][j - arr[i - 1]] % mod + t[i - 1][j] % mod) % mod\n return t[n][sum] % mod", "def perfectsum(arr, n, Sum):\n dp = [['.'] * (Sum + 1) for i in range(n + 1)]\n mod = 10 ** 9 + 7\n for i in range(n + 1):\n for j in range(Sum + 1):\n if i == 0:\n dp[i][j] = 0\n if j == 0:\n if arr[i - 1] == 0 and i > 0:\n dp[i][j] = 2 * dp[i - 1][j]\n else:\n dp[i][j] = 1\n for i in range(1, n + 1):\n for j in range(1, Sum + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j] + dp[i - 1][j - arr[i - 1]]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[-1][-1] % mod", "m = 10 ** 9 + 7\n\ndef perfectsum(arr, n, sum):\n t = [[0 for j in range(sum + 1)] for i in range(n + 1)]\n for j in range(sum + 1):\n t[0][j] = 0\n t[0][0] = 1\n for i in range(1, n + 1):\n for j in range(0, sum + 1):\n if arr[i - 1] <= j:\n t[i][j] = t[i - 1][j - arr[i - 1]] + t[i - 1][j]\n else:\n t[i][j] = t[i - 1][j]\n t[i][j] %= m\n return t[n][sum] % m", "def count_zeros_till_index(arr, i):\n count = 0\n for j in range(i):\n if arr[j] == 0:\n count += 1\n return count\n\ndef perfectsum(arr, n, sum):\n mod = 10 ** 9 + 7\n dp = [[0] * (sum + 1) for _ in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = pow(2, self.count_zeros_till_index(arr, i), mod)\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if arr[i - 1] <= j:\n dp[i][j] = (dp[i - 1][j - arr[i - 1]] + dp[i - 1][j]) % mod\n else:\n dp[i][j] = dp[i - 1][j] % mod\n return dp[n][sum]", "def countSum(arr, index, sum, dp):\n if sum == 0 and index == len(arr):\n return 1\n if sum != 0 and index == len(arr):\n return 0\n if dp[index][sum] != -1:\n return dp[index][sum]\n notTake = self.countSum(arr, index + 1, sum, dp)\n take = 0\n if arr[index] <= sum:\n take = self.countSum(arr, index + 1, sum - arr[index], dp)\n dp[index][sum] = (take + notTake) % 1000000007\n return (take + notTake) % 1000000007\n\ndef perfectsum(arr, n, sum):\n dp = [[int(-1) for col in range(sum + 1)] for row in range(n)]\n return self.countSum(arr, 0, sum, dp)", "from functools import lru_cache\nimport sys\nsys.setrecursionlimit(10 ** 6)\n\ndef perfectsum(arr, n, sum):\n MOD = 1000000000.0 + 7\n\n def go(i, s):\n if s > sum:\n return 0\n if i == n:\n if s == sum:\n return 1\n return 0\n return go(i + 1, s) % MOD + go(i + 1, s + arr[i]) % MOD % MOD\n return int(go(0, 0) % MOD)", "def perfectsum(arr, n, sume):\n new = [i for i in arr if i != 0]\n table = [[-1] * (sume + 1) for i in range(n + 1)]\n\n def countsubsum(arr, K, n):\n if n == 0:\n return K == 0\n if K < 0:\n return 0\n if K == 0:\n return 1\n if table[n][K] == -1:\n count = 0\n count += countsubsum(arr, K, n - 1)\n if arr[n - 1] <= K:\n count += countsubsum(arr, K - arr[n - 1], n - 1)\n table[n][K] = count\n return table[n][K]\n count = 0\n for i in arr:\n if i == 0:\n count += 1\n ans = 2 ** count * countsubsum(new, sume, len(new))\n return ans % (10 ** 9 + 7)", "def perfectsum(arr, n, sum):\n dp = [[-1 for i in range(sum + 1)] for j in range(n + 1)]\n\n def solve(ind, k):\n if ind == n:\n if sum == k:\n return 1\n return 0\n if dp[ind][k] != -1:\n return dp[ind][k]\n if arr[ind] <= sum - k:\n dp[ind][k] = solve(ind + 1, k + arr[ind]) + solve(ind + 1, k)\n else:\n dp[ind][k] = solve(ind + 1, k)\n return dp[ind][k]\n return solve(0, 0) % (10 ** 9 + 7)", "def perfectsum(arr, n, s):\n count = 0\n dp = [[-1] * (s + 1) for i in range(n + 1)]\n mod = 10 ** 9 + 7\n dp[0][0] = 1\n for j in range(1, s + 1):\n dp[0][j] = 0\n for i in range(1, n + 1):\n for j in range(0, s + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j - arr[i - 1]] + dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[n][s] % mod", "def perfectsum(arr, n, sum):\n count = 0\n dp = [[-1 for i in range(sum + 1)] for j in range(n + 1)]\n return self.dfs(arr, n, sum, dp, count)\n\ndef dfs(arr, n, sum, dp, count):\n if n == 0:\n if sum == 0:\n return 1\n else:\n return 0\n if dp[n][sum] != -1:\n return dp[n][sum]\n if arr[n - 1] <= sum:\n dp[n][sum] = (self.dfs(arr, n - 1, sum - arr[n - 1], dp, count) + self.dfs(arr, n - 1, sum, dp, count)) % (10 ** 9 + 7)\n else:\n dp[n][sum] = self.dfs(arr, n - 1, sum, dp, count) % (10 ** 9 + 7)\n return dp[n][sum]"], "starter_code": "def perfectsum(arr, n, sum):\n", "input_output": {"inputs": ["N = 6, arr[] = {2, 3, 5, 6, 8, 10}\r\n sum = 10", "N = 5, arr[] = {1, 2, 3, 4, 5}\r\n sum = 10"], "outputs": ["3", "3"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/perfect-sum-problem5633/1", "Expected Auxiliary Space": "O(N*sum)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*sum)", "entry_point": "perfectsum", "task_id": "TACO_lite/194", "example": [[[6, [2, 3, 5, 6, 8, 10], 10], [5, [1, 2, 3, 4, 5], 10]], [null, null]]} +{"requirement": "Given a matrix of size N x N. Print the elements of the matrix in the snake like pattern depicted below.\nExample 1:\nInput:\nN = 3 \nmatrix[][] = {{45, 48, 54},\n {21, 89, 87}\n {70, 78, 15}}\nOutput: 45 48 54 87 89 21 70 78 15 \nExplanation:\nMatrix is as below:\n45 48 54\n21 89 87\n70 78 15\nPrinting it in snake pattern will lead to \nthe output as 45 48 54 87 89 21 70 78 15.\nExample 2:\nInput:\nN = 2\nmatrix[][] = {{1, 2},\n {3, 4}}\nOutput: 1 2 4 3\nExplanation:\nMatrix is as below:\n1 2 \n3 4\nPrinting it in snake pattern will \ngive output as 1 2 4 3.\nYour Task:\nYou dont need to read input or print anything. Complete the function snakePattern() that takes matrix as input parameter and returns a list of integers in order of the values visited in the snake pattern. \nExpected Time Complexity: O(N * N)\nExpected Auxiliary Space: O(N * N) for the resultant list only.\nConstraints:\n1 <= N <= 100\n1 <= mat[i][j] <= 100", "solutions": ["def snakepattern(matrix):\n l = []\n for i in range(len(matrix)):\n if i % 2 == 0:\n l += matrix[i]\n else:\n l += matrix[i][::-1]\n return l", "def snakepattern(matrix):\n ls = []\n n = len(matrix)\n for i in range(n):\n if i % 2 == 0:\n for j in range(n):\n ls.append(matrix[i][j])\n else:\n for j in range(n - 1, -1, -1):\n ls.append(matrix[i][j])\n return ls", "def snakepattern(matrix):\n l = []\n i = 0\n j = 0\n for i in range(len(matrix[0])):\n if i % 2 == 0:\n for j in range(len(matrix[0])):\n l.append(matrix[i][j])\n else:\n j = len(matrix[0]) - 1\n while j >= 0:\n l.append(matrix[i][j])\n j = j - 1", "def snakepattern(matrix):\n k = []\n x = len(matrix)\n for i in range(x):\n if i % 2 == 0:\n for j in range(x):\n k.append(matrix[i][j])\n else:\n for j in range(x - 1, -1, -1):\n k.append(matrix[i][j])\n return k", "def snakepattern(matrix):\n n = len(matrix)\n result = []\n for i in range(n):\n if i % 2:\n result.extend(matrix[i][::-1])\n else:\n result.extend(matrix[i][:])\n return result", "def snakepattern(matrix):\n result = []\n a = len(matrix)\n b = a\n for i in range(a):\n if i % 2 == 0:\n for j in range(b):\n result.append(matrix[i][j])\n else:\n for j in range(b - 1, -1, -1):\n result.append(matrix[i][j])\n return result", "def snakepattern(matrix):\n turn = 0\n N = len(matrix)\n result = []\n for i in range(N):\n if i % 2 == 0:\n for j in range(N):\n result += [matrix[i][j]]\n else:\n for j in range(N - 1, -1, -1):\n result += [matrix[i][j]]\n return result", "def snakepattern(matrix):\n ans = []\n n = len(matrix)\n flag = True\n for i in range(n):\n if flag:\n (start, end, inc) = (0, n, 1)\n flag = False\n else:\n (start, end, inc) = (n - 1, -1, -1)\n flag = True\n for j in range(start, end, inc):\n ans.append(matrix[i][j])\n return ans", "def snakepattern(a):\n n = len(a)\n for i in range(n):\n if i % 2 == 0:\n continue\n else:\n (left, right) = (0, n - 1)\n while left < right:\n temp = a[i][left]\n a[i][left] = a[i][right]\n a[i][right] = temp\n left += 1\n right -= 1\n ans = []\n for i in range(n):\n for j in range(n):\n ans.append(a[i][j])\n return ans", "def snakepattern(m):\n res = []\n for i in range(len(m)):\n if i % 2 == 0:\n for j in range(len(m)):\n res.append(m[i][j])\n else:\n for j in range(len(m) - 1, -1, -1):\n res.append(m[i][j])\n return res", "def snakepattern(matrix):\n n = len(matrix)\n li = []\n for i in range(n):\n if i % 2 == 0:\n for j in range(n):\n li.append(matrix[i][j])\n else:\n for j in reversed(range(n)):\n li.append(matrix[i][j])\n return li", "def snakepattern(m):\n a = []\n l = len(m)\n for i in range(l):\n if i % 2 == 0:\n p = 1\n else:\n p = -1\n a += m[i][::p]\n return a", "def snakepattern(matrix):\n l = []\n n = len(matrix[0])\n for j in range(n):\n if j % 2 == 0:\n for k in range(n):\n l.append(matrix[j][k])\n else:\n for k in range(n - 1, -1, -1):\n l.append(matrix[j][k])\n return l", "def snakepattern(matrix):\n i = 0\n j = 0\n ans = []\n for i in range(n):\n if i % 2 == 0:\n for j in range(n):\n ans.append(matrix[i][j])\n if i % 2 != 0:\n for j in range(n - 1, -1, -1):\n ans.append(matrix[i][j])\n return ans", "import math\n\ndef snakepattern(matrix):\n arr = []\n row = int(math.sqrt(len(matrix)))\n for i in range(len(matrix)):\n if i % 2 == 0:\n for j in range(len(matrix[0])):\n arr.append(matrix[i][j])\n else:\n for j in range(len(matrix[0]) - 1, -1, -1):\n arr.append(matrix[i][j])\n return arr", "def snakepattern(matrix):\n N = n\n l = []\n for i in range(N):\n if i % 2 == 0:\n for j in range(N):\n l.append(matrix[i][j])\n else:\n for j in range(N - 1, -1, -1):\n l.append(matrix[i][j])\n return l", "def snakepattern(matrix):\n t = len(matrix)\n n = len(matrix)\n l = []\n for i in range(t):\n if i % 2 == 0:\n for j in range(n):\n l.append(str(matrix[i][j]))\n else:\n for j in range(n - 1, -1, -1):\n l.append(str(matrix[i][j]))\n return l", "def snakepattern(matrix):\n N = len(matrix)\n ans = []\n for i in range(N):\n if i % 2 == 0:\n for j in range(N):\n ans.append(matrix[i][j])\n else:\n for j in range(N - 1, -1, -1):\n ans.append(matrix[i][j])\n return ans", "def snakepattern(matrix):\n li = []\n for i in matrix:\n if matrix.index(i) % 2 == 0:\n for j in i:\n li.append(j)\n else:\n for k in i[::-1]:\n li.append(k)\n return li", "def snakepattern(M):\n l = []\n for i in range(len(M)):\n if i % 2 == 0:\n for j in range(len(M)):\n l.append(M[i][j])\n else:\n for k in range(len(M) - 1, -1, -1):\n l.append(M[i][k])\n return l", "global n\n\ndef snakepattern(m):\n arr = []\n for i in range(n):\n if i % 2 == 0:\n for j in range(n):\n arr += [m[i][j]]\n else:\n for j in range(n - 1, -1, -1):\n arr += [m[i][j]]\n return arr", "def snakepattern(matrix):\n l = []\n p = len(matrix)\n q = len(matrix[0])\n for i in range(p):\n if i % 2 == 0:\n for j in range(q):\n l.append(matrix[i][j])\n else:\n for j in range(q - 1, -1, -1):\n l.append(matrix[i][j])\n return l", "def snakepattern(matrix):\n (r, c) = (len(matrix), len(matrix[0]))\n res = []\n for i in range(r):\n if i % 2 == 0:\n for j in range(0, c):\n res.append(matrix[i][j])\n else:\n for j in range(c - 1, -1, -1):\n res.append(matrix[i][j])\n return res", "def snakepattern(matrix):\n a = []\n flag = True\n for i in range(n):\n if flag == True:\n for j in range(n):\n a.append(matrix[i][j])\n else:\n for j in range(n - 1, -1, -1):\n a.append(matrix[i][j])\n flag = not flag\n return a", "def snakepattern(mat):\n n = len(mat)\n change = False\n res = []\n for i in range(n):\n if change:\n for j in range(n - 1, -1, -1):\n res.append(mat[i][j])\n else:\n for j in range(n):\n res.append(mat[i][j])\n change = not change\n return res", "def snakepattern(matrix):\n k = matrix[0]\n if n > 1:\n for i in range(1, n):\n if i % 2 == 1:\n p = matrix[i]\n p.reverse()\n k = k + p\n elif i % 2 == 0:\n k = k + matrix[i]\n return k\n else:\n return matrix[0]", "def snakepattern(matrix):\n R = len(matrix)\n C = len(matrix[0])\n l = []\n for i in range(R):\n if i % 2 == 0:\n for j in range(C):\n l.append(matrix[i][j])\n else:\n for j in range(C - 1, -1, -1):\n l.append(matrix[i][j])\n return l", "def snakepattern(matrix):\n lst = []\n row = len(matrix)\n col = len(matrix[0])\n for i in range(row):\n if i % 2 == 0:\n for j in range(col):\n lst.append(matrix[i][j])\n else:\n for j in range(col - 1, -1, -1):\n lst.append(matrix[i][j])\n return lst", "def snakepattern(matrix):\n c = []\n for i in range(len(matrix)):\n if i % 2 == 0:\n for j in range(len(matrix)):\n c.append(matrix[i][j])\n elif i % 2 != 0:\n for k in range(len(matrix) - 1, -1, -1):\n c.append(matrix[i][k])\n return c"], "starter_code": "def snakepattern(matrix):\n", "input_output": {"inputs": ["N = 3 \nmatrix[][] = {{45, 48, 54},\n {21, 89, 87}\n {70, 78, 15}}", "N = 2\nmatrix[][] = {{1, 2},\n {3, 4}}"], "outputs": ["45 48 54 87 89 21 70 78 15", "1 2 4 3"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/print-matrix-in-snake-pattern-1587115621/1", "Expected Auxiliary Space": "O(N * N) for the resultant list only.", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(N * N)", "entry_point": "snakepattern", "task_id": "TACO_lite/74", "example": [[], []]} +{"requirement": "Given 5 integers K, L, R, X, Y. Find whether there exists two integers A and B such that A / B = K where L \u2264 A \u2264 R and X \u2264 B \u2264 Y.\nExample 1:\nInput: K = 1, L = 1, R = 10\n X = 1, Y = 10\nOutput: 1\nExplanation:\nA = 1 , B = 1 exists such that L \u2264 A \u2264 R,\nX \u2264 B \u2264 Y and A / B = K.\nNote,there are other pairs present\nLike A = 2, B = 2 etc which also satisfy \nthe conditions.\nExample 2:\nInput: K = 1, L = 1, R = 5\n X = 6, Y = 10\nOutput: 0\nExplanation:\nNo such A and B exist that satisfy all \nthe conditions.\nYour Task:\nYou don't need to read input or print anything. Your Task is to complete the function easyProblem() which takes 5 integers K, L, R, X, and Y as input parameters and returns 1 if there exists two numbers that follow the above-given conditions. Otherwise, return 0.\nExpected Time Complexity:O(N)\nExpected Auxillary Space:O(1)\nConstraints:\n1\u2264 K, L, R, X, Y\u2264 10^{6}", "solutions": ["def easyproblem(K, L, R, X, Y):\n left = X\n right = Y\n while left <= right:\n mid = (left + right) // 2\n A = K * mid\n if A >= L and A <= R:\n return 1\n elif A < L:\n left = mid + 1\n else:\n right = mid - 1\n return 0", "def easyproblem(K, L, R, X, Y):\n for i in range(X, Y + 1):\n if K * i >= L and K * i <= R:\n return 1\n return 0", "def easyproblem(K, L, R, X, Y):\n flag = 0\n for B in range(X, Y + 1):\n A = B * K\n if A > R:\n break\n if A >= L and A <= R:\n flag = 1\n break\n return flag"], "starter_code": "def easyproblem(K,L,R,X,Y):\n", "input_output": {"inputs": ["K = 1, L = 1, R = 10\r\n X = 1, Y = 10", "K = 1, L = 1, R = 5\r\n X = 6, Y = 10"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/an-easy-problem0811/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "easyproblem", "task_id": "TACO_lite/166", "example": [[[1, 1, 10, 1, 10], [1, 1, 5, 6, 10]], ["1", "0"]]} +{"requirement": "Given an integer R which represents the radius of a circle that has (0,0) as its centre, find the total number of lattice points on the circumference. Lattice Points are points with coordinates as integers in 2-D space.\nExample 1:\nInput: R = 5\nOutput: 12\nExplanation: (0,5), (0,-5), (5,0), \n(-5,0), (3,4), (-3,4), (-3,-4), (3,-4), \n(4,3), (-4,3), (-4,-3), (4,-3).\nExample 2:\nInput: R = 88\nOutput: 4\nExplanation: (0,88), (88,0), (0,-88), \n(-88,0)\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function latticePoints() which takes R as input and returns the number of lattice points.\nExpected Time Complexity: O(RsqrtR)\nExpected Auxiliary Space: O(1)\nConstraints:\n0 \u2264 R \u2264 10^{4}", "solutions": ["import math\n\ndef latticepoints(r):\n if r == 0:\n return 0\n count = 4\n for i in range(1, r):\n t = math.sqrt(r * r - i * i)\n if t == int(t):\n count += 4\n return count", "import math\n\ndef latticepoints(r):\n if r == 0:\n return 0\n lattice_count = 2\n for i in range(-r + 1, r):\n x = i\n y = math.sqrt(r ** 2 - x ** 2)\n if y == int(y):\n lattice_count += 2\n return lattice_count", "import math\n\ndef latticepoints(r):\n if r == 0:\n return 0\n count2 = 0\n for i in range(1, r):\n a = r * r - i * i\n if math.sqrt(a) - math.floor(math.sqrt(a)) == 0:\n count2 = count2 + 1\n return 4 + count2 * 4", "def latticepoints(r):\n import math\n if r == 0:\n result = 0\n else:\n result = 4\n for i in range(1, r):\n ysq = r * r - i * i\n y = int(math.sqrt(ysq))\n if ysq == y * y:\n result += 4\n return result", "import math\n\ndef latticepoints(r):\n if r <= 0:\n return 0\n a = 4\n for x in range(1, r):\n ys = r * r - x * x\n y = int(math.sqrt(ys))\n if y * y == ys:\n a += 4\n return a", "import math\n\ndef latticepoints(r):\n c = 4\n if r <= 0:\n return 0\n else:\n for x in range(1, r):\n a = r * r - x * x\n b = int(math.sqrt(a))\n if a == b * b:\n c += 4\n return c", "def latticepoints(r):\n if r == 0:\n return 0\n x = 0\n for i in range(r + 1):\n if int((r ** 2 - i ** 2) ** 0.5) ** 2 + i ** 2 == r ** 2:\n if i == 0 or r * r - i * i == 0:\n x = x + 2\n else:\n x = x + 4\n return x"], "starter_code": "def latticepoints(r):\n", "input_output": {"inputs": ["R = 5", "R = 88"], "outputs": ["12", "4"]}, "difficulty": "EASY", "raw_tags": ["Geometric"], "name": null, "source": "geeksforgeeks", "tags": ["Geometry"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/circle-and-lattice-points4257/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(RsqrtR)", "entry_point": "latticepoints", "task_id": "TACO_lite/207", "example": [[[5], [88]], ["12", "4"]]} +{"requirement": "In elementary arithmetic a \"carry\" is a digit that is transferred from one column of digits to another column of more significant digits during a calculation algorithm.\n\nThis Kata is about determining the number of carries performed during the addition of multi-digit numbers.\n\nYou will receive an input string containing a set of pairs of numbers formatted as follows:\n\n```\n123 456\n555 555\n123 594\n```\n\nAnd your output should be a string formatted as follows:\n\n```\nNo carry operation\n1 carry operations\n3 carry operations\n```\n\n###Some Assumptions\n\n- Assume that numbers can be of any length.\n- But both numbers in the pair will be of the same length.\n- Although not all the numbers in the set need to be of the same length.\n- If a number is shorter, it will be zero-padded.\n- The input may contain any arbitrary number of pairs.", "solutions": ["def solve(s):\n ans = []\n for ab in s.split('\\n'):\n (carry, carried) = (0, 0)\n for (a, b) in zip(*map(lambda ss: map(int, ss[::-1]), ab.split())):\n carried += a + b\n carry += carried > 9\n carried //= 10\n ans.append(carry)\n return '\\n'.join(('No carry operation' if not c else '%d carry operations' % c for c in ans))", "def getCarrycount(a, b):\n (r, index) = (0, 0)\n al = [int(d) + int(f) for (d, f) in zip(reversed(list(a)), reversed(list(b)))]\n for item in al:\n index = (item + index) // 10\n r += index\n return r\n\ndef solve(input_string):\n lnumber = [tuple(item.split()) for item in input_string.split('\\n')]\n lsum = [getCarrycount(z[0], z[1]) for z in lnumber]\n return '\\n'.join(('{} carry operations'.format(n) if n else 'No carry operation' for n in lsum))", "def solve(s):\n li = []\n for k in s.splitlines():\n c = [0]\n for (i, j) in reversed(list(zip(k.split(' ')[0], k.split(' ')[1]))):\n if int(i) + int(j) + int(c[-1]) > 9:\n c.append(str(int(i) + int(j) + int(c[-1]))[0])\n else:\n c.append(0)\n li.append('No carry operation' if c.count('1') < 1 else f\"{c.count('1')} carry operations\")\n return '\\n'.join(li)", "def solve(input_string):\n res = []\n for i in input_string.split('\\n'):\n res.append(carry(i.split()[0], i.split()[1]))\n return '\\n'.join(res)\n\ndef carry(s1, s2):\n carry = 0\n increment = 0\n for (i, j) in zip(s1[::-1], s2[::-1]):\n digit = int(i) + int(j) + increment\n increment = 1 if digit >= 10 else 0\n carry += increment\n return 'No carry operation' if not carry else f'{carry} carry operations'", "def solve(string):\n operations = []\n for line in string.split('\\n'):\n (num1, num2) = line[::-1].split()\n (carries, carry) = (0, 0)\n for (v1, v2) in zip(num1, num2):\n (v1, v2) = (int(v1), int(v2))\n v3 = v1 + v2 + carry\n v4 = v3 % 10\n if carry:\n carries += v4 <= max(v1, v2)\n else:\n carries += v4 < max(v1, v2)\n carry = int(v3 > 9)\n if carries:\n operations.append(f'{carries} carry operations')\n else:\n operations.append('No carry operation')\n return '\\n'.join(operations)", "def solve(input_string):\n answer = []\n for n in input_string.split('\\n'):\n (carry, carried) = (0, 0)\n (A, B) = map(str, n[::-1].split())\n for x in range(len(A)):\n carried += int(A[x]) + int(B[x])\n carry += carried > 9\n carried //= 10\n answer.append(carry)\n return '\\n'.join(('No carry operation' if not c else '%d carry operations' % c for c in answer))", "def ss(n):\n return sum(map(int, str(n)))\n\ndef solve(s):\n s = s.split('\\n')\n ans = []\n for i in s:\n (j, k) = map(int, i.split())\n c = (-ss(j + k) + ss(k) + ss(j)) // 9\n cc = 'No' if c == 0 else str(c)\n ans.append(cc + ' carry operation' + 's' * (c > 0))\n return '\\n'.join(ans)", "def carry(s):\n (a, b) = s.split()\n (c, f) = (0, 0)\n for (i, j) in zip(map(int, a[::-1]), map(int, b[::-1])):\n if i + j + f > 9:\n f = 1\n c += 1\n else:\n f = 0\n return c\n\ndef solve(s):\n r = list(map(carry, s.splitlines()))\n return '\\n'.join(('No carry operation' if x == 0 else f'{x} carry operations' for x in r))", "def carry(x, y):\n x = [*map(int, x[::-1])]\n y = [*map(int, y[::-1])]\n r = 0\n c = 0\n for (a, b) in zip(x, y):\n v = a + b + c\n if v > 9:\n r += 1\n c = v // 10\n return f'{r} carry operations' if r else 'No carry operation'\n\ndef solve(input_string):\n return '\\n'.join((carry(*s.split()) for s in input_string.split('\\n')))"], "starter_code": "def solve(s):\n", "input_output": {"fn_name": "solve", "inputs": [["123 456\n555 555\n123 594"], ["321 679\n098 805\n123 867"], ["123 457\n631 372\n999 111"], ["123 457\n123 456\n654 312\n999 000\n123 457"], ["1 9\n123456789 111111101\n01 09\n11 09\n123 457"], ["99 99"]], "outputs": [["No carry operation\n3 carry operations\n1 carry operations"], ["3 carry operations\n2 carry operations\n1 carry operations"], ["1 carry operations\n2 carry operations\n3 carry operations"], ["1 carry operations\nNo carry operation\nNo carry operation\nNo carry operation\n1 carry operations"], ["1 carry operations\n1 carry operations\n1 carry operations\n1 carry operations\n1 carry operations"], ["2 carry operations"]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/529fdef7488f509b81000061", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/148", "example": [[["123 456\n555 555\n123 594"]], ["No carry operation\n3 carry operations\n1 carry operations"]]} +{"requirement": "# Description\nYou are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1.\n\n# Example\n```python\nstring = \"This is an example. Return the nth occurrence of example in this example string.\"\nfind_nth_occurrence(\"example\", string, 1) == 11\nfind_nth_occurrence(\"example\", string, 2) == 49\nfind_nth_occurrence(\"example\", string, 3) == 65\nfind_nth_occurrence(\"example\", string, 4) == -1\n```\n\nMultiple occurrences of a substring are allowed to overlap, e.g.\n```python\nfind_nth_occurrence(\"TestTest\", \"TestTestTestTest\", 1) == 0\nfind_nth_occurrence(\"TestTest\", \"TestTestTestTest\", 2) == 4\nfind_nth_occurrence(\"TestTest\", \"TestTestTestTest\", 3) == 8\nfind_nth_occurrence(\"TestTest\", \"TestTestTestTest\", 4) == -1\n```", "solutions": ["def find_nth_occurrence(substring, string, occurrence=1):\n idx = -1\n for i in range(occurrence):\n idx = string.find(substring, idx + 1)\n if idx == -1:\n return -1\n return idx", "import re\n\ndef find_nth_occurrence(sb, s, n=1):\n r = list(re.finditer('(?=' + sb + ')', s))\n return r[n - 1].span()[0] if n <= len(r) else -1", "import re\n\ndef find_nth_occurrence(substring, string, occurrence):\n try:\n return [s.start() for s in re.finditer('(?=' + substring + ')', string)][occurrence - 1]\n except:\n return -1", "def find_nth_occurrence(substring, string, occurrence=1):\n i = -1\n for _ in range(occurrence):\n i = string.find(substring, i + 1)\n if i == -1:\n break\n return i", "def find_nth_occurrence(substring, string, occurrence=1):\n index = -1\n for occ in range(0, occurrence):\n index = string.find(substring, index + 1)\n return index", "def find_nth_occurrence(w, s, n=1, k=0):\n for i in range(len(s)):\n if s[i:i + len(w)] == w:\n k += 1\n if k == n:\n return i\n else:\n return -1", "def find_nth_occurrence(substring, string, occurrence=1):\n indicies = [i for i in range(len(string)) if string.startswith(substring, i)]\n if occurrence > len(indicies):\n return -1\n else:\n return indicies[occurrence - 1]", "import re\n\ndef find_nth_occurrence(substring, string, occurrence=1):\n try:\n return [m.start() for m in re.finditer(f'(?={substring})', string)][occurrence - 1]\n except:\n return -1", "def find_nth_occurrence(substring, string, occurrence=1):\n (c, i) = (1, string.find(substring))\n while c < occurrence and i > -1:\n (c, i) = (c + 1, string.find(substring, i + 1))\n return i", "def find_nth_occurrence(substring, string, occurrence):\n a = string.find(substring)\n while a >= 0 and occurrence > 1:\n a = string.find(substring, a + 1)\n occurrence -= 1\n return a"], "starter_code": "def find_nth_occurrence(substring, string, occurrence=1):\n", "input_output": {"fn_name": "find_nth_occurrence", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5b1d1812b6989d61bd00004f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "find_nth_occurrence", "task_id": "TACO_lite/49", "example": [[["example", "This is an example. Return the nth occurrence of example in this example string.", 1], ["example", "This is an example. Return the nth occurrence of example in this example string.", 2], ["example", "This is an example. Return the nth occurrence of example in this example string.", 3], ["example", "This is an example. Return the nth occurrence of example in this example string.", 4], ["TestTest", "TestTestTestTest", 1], ["TestTest", "TestTestTestTest", 2], ["TestTest", "TestTestTestTest", 3], ["TestTest", "TestTestTestTest", 4]], ["11", "49", "65", "-1", "0", "4", "8", "-1"]]} +{"requirement": "You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and\u00a0it will automatically contact the police if two adjacent houses were broken into on the same night.\n\nGiven a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.\n\nExample 1:\n\n\nInput: [2,3,2]\nOutput: 3\nExplanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),\n\u00a0 because they are adjacent houses.\n\n\nExample 2:\n\n\nInput: [1,2,3,1]\nOutput: 4\nExplanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\n\u00a0 Total amount you can rob = 1 + 3 = 4.", "solutions": ["def rob(nums):\n if not nums:\n return 0\n if len(nums) == 1:\n return nums[0]\n return max(self.helper(nums[1:]), self.helper(nums[:-1]))\n\ndef helper(nums):\n now = prev = 0\n for nxt in nums:\n (now, prev) = (max(nxt + prev, now), now)\n return now", "def rob(nums):\n if len(nums) == 1:\n return nums[0]\n (last, now) = (0, 0)\n for i in nums[:-1]:\n (last, now) = (now, max(last + i, now))\n ret = now\n (last, now) = (0, 0)\n for i in nums[1:]:\n (last, now) = (now, max(last + i, now))\n return max(ret, now)", "def rob(nums):\n if not nums:\n return 0\n if len(nums) == 1:\n return nums[0]\n if len(nums) <= 3:\n return max(nums)\n\n def rob_line(lst):\n (last, now) = (0, 0)\n for i in lst:\n (last, now) = (now, max(now, last + i))\n return now\n return max(rob_line(nums[:-1]), rob_line(nums[1:]))", "def helper(nums, cache={}):\n if len(nums) == 0:\n return 0\n key = str(nums)\n if key in cache:\n return cache[key]\n cache[key] = max(nums[0] + self.helper(nums[2:]), self.helper(nums[1:]))\n return cache[key]\n\ndef rob(nums):\n if len(nums) == 0:\n return 0\n return max(nums[0] + self.helper(nums[2:-1]), nums[-1] + self.helper(nums[1:-2]), self.helper(nums[1:-1]))", "def rob(nums):\n mem = {}\n\n def max_money(start, rob_first=False):\n if start >= len(nums):\n return 0\n if start == len(nums) - 1 and rob_first:\n return 0\n if (start, rob_first) in mem:\n return mem[start, rob_first]\n if start == 0:\n mem[start, rob_first] = max(max_money(start + 1, False), nums[start] + max_money(start + 2, True))\n else:\n mem[start, rob_first] = max(max_money(start + 1, rob_first), nums[start] + max_money(start + 2, rob_first))\n return mem[start, rob_first]\n return max_money(0)", "def rob(nums):\n if not nums:\n return 0\n ymax = [nums[i] for i in range(len(nums))]\n nmax = [nums[i] for i in range(len(nums))]\n nmax[0] = 0\n if len(nums) > 1:\n ymax[1] = max(ymax[0], ymax[1])\n for i in range(2, len(nums)):\n if i == len(nums) - 1:\n ymax[i] = ymax[i - 1]\n else:\n ymax[i] = max(ymax[i - 1], ymax[i - 2] + ymax[i])\n nmax[i] = max(nmax[i - 1], nmax[i - 2] + nmax[i])\n return max(nmax[-1], ymax[-1])", "def rob(nums):\n if len(nums) == 0:\n return 0\n if len(nums) <= 2:\n return max(nums[0], nums[-1])\n a = [0 for _ in range(len(nums) - 1)]\n b = a.copy()\n c = b.copy()\n a[0] = nums[0]\n b[0] = nums[-1]\n for i in range(1, len(nums) - 1):\n a[i] = max(a[i - 1], a[i - 2] + nums[i])\n b[i] = max(b[i - 1], b[i - 2] + nums[-i - 1])\n return max(a[-1], b[-1])", "def rob_prev(nums):\n n = len(nums)\n if n == 0:\n return 0\n elif n < 3:\n return max(nums)\n mem = [0 for x in range(n + 1)]\n mem[0] = nums[0]\n mem[1] = max(nums[1], nums[0])\n for i in range(2, n):\n mem[i] = max(mem[i - 2] + nums[i], mem[i - 1])\n return mem[n - 1]\n\ndef rob(nums):\n n = len(nums)\n if n == 0:\n return 0\n elif n < 3:\n return max(nums)\n return max(self.rob_prev(nums[1:]), self.rob_prev(nums[:len(nums) - 1]))", "def rob(nums):\n if not nums:\n return 0\n if len(nums) == 1:\n return nums[0]\n\n def helper(nums):\n steal = 0\n cool = 0\n for num in nums:\n (steal, cool) = (cool, max(cool, steal + num))\n return max(steal, cool)\n return max(helper(nums[:-1]), helper(nums[1:]))", "def rob(nums):\n\n def helper(nums):\n if not nums:\n return 0\n dp = [0] * (len(nums) + 1)\n dp[1] = nums[0]\n for i in range(2, len(nums) + 1):\n dp[i] = max(dp[i - 1], nums[i - 1] + dp[i - 2])\n return dp[-1]\n if not nums:\n return 0\n if len(nums) == 1:\n return nums[0]\n return max(helper(nums[:len(nums) - 1]), nums[-1] + helper(nums[1:len(nums) - 2]))", "def rob(nums):\n if not nums:\n return 0\n mark = [0 for i in range(len(nums))]\n result = list(mark)\n if len(nums) == 1:\n return nums[0]\n if len(nums) == 2:\n return max(nums[0], nums[1])\n mark[0] = 1\n result[0] = nums[0]\n if nums[0] > nums[1]:\n mark[1] = 1\n result[1] = nums[0]\n else:\n result[1] = nums[1]\n for i in range(2, len(nums)):\n result[i] = max(nums[i] + result[i - 2], result[i - 1])\n if nums[i] + result[i - 2] > result[i - 1]:\n mark[i] = mark[i - 2]\n else:\n mark[i] = mark[i - 1]\n if mark[0] == 1 and mark[-1] == 1:\n return max(self.solve(nums[1:]), self.solve(nums[:-1]))\n return result[-1]\n\ndef solve(nums):\n if not nums:\n return 0\n if len(nums) == 1:\n return nums[0]\n if len(nums) == 2:\n return max(nums[0], nums[1])\n result = [0 for i in range(len(nums))]\n result[0] = nums[0]\n result[1] = max(nums[0], nums[1])\n for i in range(2, len(nums)):\n result[i] = max(nums[i] + result[i - 2], result[i - 1])\n return result[-1]"], "starter_code": "def rob(nums: List[int]) -> int:\n", "input_output": {"fn_name": "rob", "inputs": [[[2, 3, 2]]], "outputs": [3]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/house-robber-ii/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "rob", "task_id": "TACO_lite/128", "example": [[[[2, 3, 2]], [[1, 2, 3, 1]]], ["3", "4"]]} +{"requirement": "In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the root an, followed by other, which can form another word another.\n\n\n\n\nNow, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.\n\n\n\nYou need to output the sentence after the replacement.\n\n\n\nExample 1:\n\nInput: dict = [\"cat\", \"bat\", \"rat\"]\nsentence = \"the cattle was rattled by the battery\"\nOutput: \"the cat was rat by the bat\"\n\n\n\n\nNote:\n\nThe input will only have lower-case letters.\n 1 \n 1 \n 1 \n 1", "solutions": ["def replacewords(dt, sentence):\n trie = {}\n for w in dt:\n t = trie\n for c in w:\n if c not in t:\n t[c] = {}\n t = t[c]\n t['#'] = w\n return ' '.join([self.replace(i, trie) for i in sentence.split()])\n\ndef replace(word, trie):\n cur = trie\n for letter in word:\n if letter not in cur:\n break\n cur = cur[letter]\n if '#' in cur:\n return cur['#']\n return word\n setenceAsList = sentence.split(' ')\n for i in range(len(setenceAsList)):\n for j in dt:\n if setenceAsList[i].startswith(j):\n setenceAsList[i] = j\n return ' '.join(setenceAsList)\n arrs = sentence.split()\n for i in range(len(arrs)):\n w = arrs[i]\n for j in range(len(arrs[i])):\n cur = w[:j]\n if cur in dt:\n arrs[i] = cur\n break\n return ' '.join(arrs)", "def replacewords(roots, sentence):\n trie = {}\n for w in roots:\n t = trie\n for c in w:\n if c not in t:\n t[c] = {}\n t = t[c]\n t['#'] = True\n return ' '.join([self.replace(i, trie) for i in sentence.split()])\n\ndef replace(word, trie):\n cur = trie\n i = 0\n for letter in word:\n if letter not in cur:\n break\n cur = cur[letter]\n i += 1\n if '#' in cur:\n return word[:i]\n return word", "def replacewords(dict, sentence):\n trie = {}\n for root in dict:\n node = trie\n for letter in root:\n if letter not in node:\n node[letter] = {}\n node = node[letter]\n node['#'] = root\n words = []\n for word in sentence.split():\n node = trie\n for letter in word:\n if letter not in node or '#' in node:\n break\n node = node[letter]\n if '#' in node:\n words.append(node['#'])\n else:\n words.append(word)\n return str.join(' ', words)", "def replacewords(dict, sentence):\n trie_tree = {'root': {}}\n for word in dict:\n parent = trie_tree['root']\n for c in word + '#':\n parent.setdefault(c, {})\n parent = parent[c]\n (sentence, res) = (sentence.split(), [])\n for word in sentence:\n parent = trie_tree['root']\n for (i, c) in enumerate(word + '*'):\n if c not in parent:\n res.append(word)\n break\n parent = parent[c]\n if '#' in parent:\n res.append(word[:i + 1])\n break\n return ' '.join(res)", "def replacewords(dict, sentence):\n sentence = sentence + ' '\n dic = {}\n for i in dict:\n if i[0] not in list(dic.keys()):\n dic[i[0]] = [i]\n else:\n dic[i[0]].append(i)\n res = ''\n while len(sentence) > 0:\n word = sentence[:sentence.index(' ')]\n tmp = ''\n if word[0] in list(dic.keys()):\n for refer in dic[word[0]]:\n if len(refer) < len(word):\n if word[:len(refer)] == refer:\n if tmp == '':\n tmp = refer\n elif len(tmp) > len(refer):\n tmp = refer\n if tmp != '':\n res += tmp + ' '\n else:\n res += word + ' '\n sentence = sentence[sentence.index(' ') + 1:]\n res = res[:-1]\n return res"], "starter_code": "def replacewords(dictionary: List[str], sentence: str) -> str:\n", "input_output": {"fn_name": "replaceWords", "inputs": [[["\"cat\"", "\"bat\"", "\"rat\""], "\"the cattle was rattled by the battery\""]], "outputs": ["\"the cattle was rattled by the battery\""]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Trie", "Array", "String", "Hash Table"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/replace-words/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "replacewords", "task_id": "TACO_lite/208", "example": [[[["cat", "bat", "rat"], "the cattle was rattled by the battery"]], ["the cat was rat by the bat"]]} +{"requirement": "Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer.\n\nModern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.\n\nExample:\n```python\nsolution(1000) # should return 'M'\n```\n\nHelp:\n```\nSymbol Value\nI 1\nV 5\nX 10\nL 50\nC 100\nD 500\nM 1,000\n```\n\nRemember that there can't be more than 3 identical symbols in a row.\n\nMore about roman numerals - http://en.wikipedia.org/wiki/Roman_numerals", "solutions": ["def solution(n):\n roman_numerals = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'}\n roman_string = ''\n for key in sorted(list(roman_numerals.keys()), reverse=True):\n while n >= key:\n roman_string += roman_numerals[key]\n n -= key\n return roman_string", "vals = zip(('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'), (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1))\n\ndef solution(n):\n if n == 0:\n return ''\n return next((c + solution(n - v) for (c, v) in vals if v <= n))", "units = ' I II III IV V VI VII VIII IX'.split(' ')\ntens = ' X XX XXX XL L LX LXX LXXX XC'.split(' ')\nhundreds = ' C CC CCC CD D DC DCC DCCC CM'.split(' ')\nthousands = ' M MM MMM'.split(' ')\n\ndef solution(n):\n return thousands[n // 1000] + hundreds[n % 1000 // 100] + tens[n % 100 // 10] + units[n % 10]", "def solution(n):\n return 'M' * (n // 1000) + hundreds[n % 1000 // 100] + tens[n % 100 // 10] + units[n % 10]", "anums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]\nrnums = 'M CM D CD C XC L XL X IX V IV I'.split()\n\ndef solution(x):\n ret = []\n for (a, r) in zip(anums, rnums):\n (n, x) = divmod(x, a)\n ret.append(r * n)\n return ''.join(ret)", "def solution(n):\n dic = {1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'}\n roman = ''\n for a in reversed(sorted(dic.keys())):\n while a <= n:\n n = n - a\n roman = roman + dic[a]\n return roman", "def solution(n):\n ed = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']\n des = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']\n sot = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']\n tys = ['', 'M', 'MM', 'MMM', 'MMMM']\n return tys[n // 1000] + sot[n // 100 % 10] + des[n // 10 % 10] + ed[n % 10]", "def solution(n):\n ROMAN_SYMBOLS = ['M', 'D', 'C', 'L', 'X', 'V', 'I']\n ROMAN_VALUES = [1000, 500, 100, 50, 10, 5, 1]\n idx = 0\n roman = []\n while n > 0:\n if n < ROMAN_VALUES[idx]:\n idx += 1\n continue\n n -= ROMAN_VALUES[idx]\n roman.append(ROMAN_SYMBOLS[idx])\n if roman[-4:].count(roman[-1]) == 4:\n roman = roman[:-3] + [ROMAN_SYMBOLS[idx - 1]]\n if roman[-3:-2] == roman[-1:]:\n roman = roman[:-3] + [ROMAN_SYMBOLS[idx]] + [ROMAN_SYMBOLS[idx - 2]]\n return ''.join(roman)", "def solution(x):\n table = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]\n for (num, rep) in table:\n if x >= num:\n return rep + solution(x - num)\n return str()"], "starter_code": "def solution(n):\n", "input_output": {"fn_name": "solution", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/51b62bf6a9c58071c600001b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solution", "task_id": "TACO_lite/229", "example": [[[1000]], ["M"]]} +{"requirement": "Given a binary tree, count the number of Single Valued Subtrees. A Single Valued Subtree is one in which all the nodes have same value. \nExample 1\nInput :\n 5\n / \\\n 1 5\n / \\ \\\n 5 5 5\nOutput : 4\nExplanation : \nThere are 4 subtrees with single values. Three leaf nodes and the subtree whose root is the right child of the root. \nExample 2:\nInput:\n 5\n / \\\n 4 5\n / \\ \\\n 4 4 5 \nOutput: 5\nExplanation: \nThere are five subtrees with single values.\nYour task :\nYou don't have to read input or print anything. Your task is to complete the function singlevalued() which takes the root of the tree as input and returns the count of single valued subtrees.\n \nExpected Time Complexity : O(n)\nExpected Auxiliary Space : O(n)\n \nConstraints :\n1 <= n <= 10^5", "solutions": ["def util(root):\n global count\n if root == None:\n return [1, None]\n if root.left == None and root.right == None:\n count += 1\n return [1, root.data]\n l = self.util(root.left)\n r = self.util(root.right)\n if l[0] == 1 and r[0] == 1:\n if l[1] == None and r[1] == None:\n return [1, root.data]\n elif l[1] == None and r[1] == root.data:\n count += 1\n return [1, root.data]\n elif r[1] == None and l[1] == root.data:\n count += 1\n return [1, root.data]\n elif l[1] == r[1] and l[1] == root.data:\n count += 1\n return [1, root.data]\n else:\n return [0, root.data]\n else:\n return [0, root.data]\n\ndef singlevalued(root):\n global count\n count = 0\n self.util(root)\n return count", "def singlevalued(root):\n c = [0] * 1\n\n def fun(root):\n if root == None:\n return True\n l = fun(root.left)\n r = fun(root.right)\n cur = root.data\n if root.left:\n left = root.left.data\n else:\n left = cur\n if root.right:\n right = root.right.data\n else:\n right = cur\n if cur == left and cur == right and l and r:\n c[0] += 1\n return True\n return False\n fun(root)\n return c[0]", "def singlevalued(root):\n count = [0]\n\n def answer(root):\n if root == None:\n return set()\n lset = answer(root.left)\n rset = answer(root.right)\n lset.add(root.data)\n lset.update(rset)\n if len(lset) == 1:\n count[0] += 1\n return lset\n answer(root)\n return count[0]", "def postOrder(root, count):\n if root is None:\n return True\n left = self.postOrder(root.left, count)\n right = self.postOrder(root.right, count)\n if left == False or right == False:\n return False\n if root.left and root.data != root.left.data or (root.right and root.data != root.right.data):\n return False\n count[0] += 1\n return True\n\ndef singlevalued(root):\n count = [0]\n self.postOrder(root, count)\n return count[0]", "def solve(root):\n if root == None:\n return True\n l = self.solve(root.left)\n r = self.solve(root.right)\n cur = root.data\n if root.left:\n left = root.left.data\n else:\n left = cur\n if root.right:\n right = root.right.data\n else:\n right = cur\n if cur == left and cur == right and l and r:\n self.count += 1\n return True\n return False\n\ndef singlevalued(root):\n self.count = 0\n self.s = set()\n self.solve(root)\n return self.count", "def finder(root):\n if root == None:\n return 1\n lef = self.finder(root.left)\n righ = self.finder(root.right)\n if lef == False or righ == False:\n return 0\n if root.left != None and root.data != root.left.data:\n return 0\n if root.right != None and root.data != root.right.data:\n return 0\n self.c += 1\n return 1\n\ndef singlevalued(root):\n self.finder(root)\n return self.c", "def singlevalued(root):\n self.ans = 0\n\n def dfs(node):\n if not node.left and (not node.right):\n self.ans += 1\n return node.data\n if node.left and node.right:\n left = dfs(node.left)\n right = dfs(node.right)\n if node.data == left and node.data == right:\n self.ans += 1\n return node.data\n elif node.left:\n left = dfs(node.left)\n if node.data == left:\n self.ans += 1\n return node.data\n elif node.right:\n right = dfs(node.right)\n if node.data == right:\n self.ans += 1\n return node.data\n return float('inf')\n dfs(root)\n return self.ans", "def singlevalued(root):\n c = 0\n\n def check(n):\n nonlocal c\n if n.left == None and n.right == None:\n c += 1\n return True\n if n.left != None:\n l = check(n.left)\n else:\n l = True\n if n.right != None:\n r = check(n.right)\n else:\n r = True\n if l == True and r == True:\n if n.left != None and n.right != None:\n if n.data == n.left.data and n.data == n.right.data:\n c += 1\n return True\n if n.data != n.left.data or n.data != n.right.data:\n return False\n if n.left == None and n.right != None:\n if n.data == n.right.data:\n c += 1\n return True\n else:\n return False\n if n.left != None and n.right == None:\n if n.data == n.left.data:\n c += 1\n return True\n else:\n return False\n check(root)\n return c", "def findSingleValued(root, count):\n if root == None:\n return True\n if root.left == None and root.right == None:\n count[0] += 1\n return True\n left = 1\n right = 1\n if root.left:\n left = self.findSingleValued(root.left, count)\n if root.right:\n right = self.findSingleValued(root.right, count)\n if left and right:\n temp = []\n temp.append(root.data)\n if root.left:\n temp.append(root.left.data)\n if root.right:\n temp.append(root.right.data)\n first = temp[0]\n for i in range(1, len(temp)):\n if temp[i] != first:\n return False\n count[0] += 1\n return True\n return False\n\ndef singlevalued(root):\n count = [0]\n self.findSingleValued(root, count)\n return count[0]", "def singlevalued(root):\n\n def check(root):\n if root.left == None and root.right == None:\n return True\n if root.left:\n if root.right:\n if root.data == root.left.data and root.data == root.right.data:\n return check(root.right) and check(root.left)\n else:\n return False\n elif root.data == root.left.data:\n return check(root.left)\n else:\n return False\n elif root.right:\n if root.left == None:\n if root.data == root.right.data:\n return check(root.right)\n else:\n return False\n\n def traverse(root):\n if check(root):\n c[0] += 1\n if root == None:\n return\n if root.left:\n traverse(root.left)\n if root.right:\n traverse(root.right)\n c = [0]\n traverse(root)\n return c[0]", "def check(root):\n if root is None:\n return True\n lhs = self.check(root.left)\n rhs = self.check(root.right)\n if lhs and rhs:\n if root.left is not None and root.left.data != root.data:\n return False\n if root.right is not None and root.right.data != root.data:\n return False\n self.ans = self.ans + 1\n return True\n return False\n\ndef singlevalued(root):\n self.check(root)\n return self.ans", "def singlevalued(root):\n self.ans = 0\n\n def solve(root):\n if root == None:\n return True\n l = solve(root.left)\n r = solve(root.right)\n if l == False or r == False:\n return False\n elif root.left and root.left.data != root.data:\n return False\n elif root.right and root.right.data != root.data:\n return False\n else:\n self.ans += 1\n return True\n val = solve(root)\n return self.ans", "def Postorder(root, dict):\n if root == None:\n return 0\n l = self.Postorder(root.left, dict)\n r = self.Postorder(root.right, dict)\n if root.left == None and root.right == None:\n if root.data not in dict:\n dict[root.data] = 1\n else:\n dict[root.data] += 1\n return root.data\n if l != 0 and r != 0:\n if l == r and l == root.data:\n if root.data not in dict:\n dict[root.data] = 1\n else:\n dict[root.data] += 1\n return root.data\n elif l != 0:\n if l == root.data:\n if root.data not in dict:\n dict[root.data] = 1\n else:\n dict[root.data] += 1\n return root.data\n elif r != 0:\n if r == root.data:\n if root.data not in dict:\n dict[root.data] = 1\n else:\n dict[root.data] += 1\n return root.data\n return -1\n\ndef singlevalued(root):\n dict = {}\n self.Postorder(root, dict)\n ans = 0\n for key in dict:\n ans += dict[key]\n return ans", "def singlevalued(root):\n count = 0\n\n def f(root):\n if not root:\n return (True, 0)\n if root:\n if root.left and root.right:\n (left, total_l) = f(root.left)\n (right, total_r) = f(root.right)\n if root.data == root.left.data and root.data == root.right.data and left and right:\n return (True, 1 + total_l + total_r)\n else:\n return (False, total_l + total_r)\n elif root.left and (not root.right):\n (left, total_l) = f(root.left)\n if root.data == root.left.data and left:\n return (True, 1 + total_l)\n else:\n return (False, total_l)\n elif not root.left and root.right:\n (right, total_r) = f(root.right)\n if root.data == root.right.data and right:\n return (True, 1 + total_r)\n else:\n return (False, total_r)\n elif not root.left and (not root.right):\n return (True, 1)\n return f(root)[1]", "def solve(root, res):\n if root.left is None and root.right is None:\n return (root.data, res + 1)\n (left, right) = (root.data, root.data)\n if root.left:\n (left, res) = self.solve(root.left, res)\n if root.right:\n (right, res) = self.solve(root.right, res)\n if left == right and left == root.data:\n return (root.data, res + 1)\n return (-1, res)\n\ndef singlevalued(root):\n return self.solve(root, 0)[1]", "def singlevalued(root):\n self.ans = 0\n self.helper(root)\n return self.ans\n\ndef helper(root):\n if root == None:\n return True\n left = self.helper(root.left)\n right = self.helper(root.right)\n if left and right:\n if root.left != None and root.left.data != root.data:\n return False\n if root.right != None and root.right.data != root.data:\n return False\n self.ans += 1\n return True\n return False", "def singlevalued(root):\n\n def f(root, ans):\n if not root:\n return -1\n if not root.left and (not root.right):\n ans[0] += 1\n return root.data\n l = f(root.left, ans)\n r = f(root.right, ans)\n if l == root.data and r == root.data or (l == -1 and r == root.data) or (r == -1 and l == root.data):\n ans[0] += 1\n return root.data\n return 0\n ans = [0]\n res = f(root, ans)\n return ans[0]", "def singlevalued(root):\n return self.helper(root)[1]\n\ndef helper(root):\n if root is None:\n return ([], 0)\n (left, l_count) = self.helper(root.left)\n (right, r_count) = self.helper(root.right)\n current = (left == [] or left == [root.data]) and (right == [] or right == [root.data])\n count = l_count + r_count + current\n nodes = left + right + [root.data]\n if current:\n nodes = [root.data]\n return (nodes, count)", "g = None\n\ndef f(p):\n global g\n pass\n ok = True\n l = p.left\n r = p.right\n if l:\n ok = f(l) and l.data == p.data and ok\n if r:\n ok = f(r) and r.data == p.data and ok\n if ok:\n g += 1\n return ok\n\ndef singlevalued(root):\n global g\n if not root:\n return 0\n g = 0\n f(root)\n return g", "def singlevalued(root):\n\n def helper(root, count):\n if root is None:\n return True\n leftSide = helper(root.left, count)\n rightSide = helper(root.right, count)\n if leftSide and rightSide and (True if root.left is None else root.left.data == root.data) and (True if root.right is None else root.right.data == root.data):\n count[0] += 1\n return True\n else:\n return False\n count = [0]\n helper(root, count)\n return count[0]", "def singlevalued(root):\n c = [0]\n\n def solve(root):\n if root == None:\n return (0, True)\n if not root.left and (not root.right):\n c[0] += 1\n return (root.data, True)\n (data1, bool1) = solve(root.left)\n (data2, bool2) = solve(root.right)\n if (root.data == data1 and root.data == data2 or (data1 == 0 and root.data == data2) or (root.data == data1 and data2 == 0)) and (bool1 and bool2):\n c[0] += 1\n return (root.data, bool1 and bool2)\n else:\n return (-1, False)\n (v, v1) = solve(root)\n return c[0]", "def singlevalued(root):\n count = [0]\n\n def value(root):\n if not root:\n return (0, True)\n if not root.left and (not root.right):\n count[0] += 1\n return (root.data, True)\n (data1, boo1) = value(root.left)\n (data2, boo2) = value(root.right)\n if (root.data == data1 and root.data == data2 or (data1 == 0 and root.data == data2 or (root.data == data1 and data2 == 0))) and (boo1 and boo2):\n count[0] += 1\n return (root.data, boo1 and boo2)\n else:\n return (-1, False)\n (v, v1) = value(root)\n return count[0]", "def singlevalued(root):\n self.count = 0\n\n def solve(root):\n if root == None:\n return 0\n if root.left == None and root.right == None:\n self.count += 1\n return True\n l = solve(root.left)\n r = solve(root.right)\n if l and r:\n if root.data == root.left.data and root.data == root.right.data:\n self.count += 1\n return True\n else:\n return False\n elif root.left == None and root.right != None:\n if r == True:\n if root.data == root.right.data:\n self.count += 1\n return True\n elif root.right == None and root.left != None:\n if l == True:\n if root.data == root.left.data:\n self.count += 1\n return True\n else:\n return False\n solve(root)\n return self.count", "def singlevalued(root):\n (bol, val, ct) = self.recursive(root)\n return ct\n\ndef recursive(root):\n if root is None:\n return (True, None, 0)\n (rt_bool, rt_val, rt_ct) = self.recursive(root.right)\n (lt_bool, lt_val, lt_ct) = self.recursive(root.left)\n if (rt_bool and lt_bool) and (rt_val is None or rt_val == root.data) and (lt_val is None or lt_val == root.data):\n return (True, root.data, lt_ct + rt_ct + 1)\n else:\n return (False, root.data, lt_ct + rt_ct)", "from collections import namedtuple\nResult = namedtuple('Result', 'valid,cnt')\n\ndef dfs(n, ans):\n if not n:\n return True\n l = dfs(n.left, ans)\n r = dfs(n.right, ans)\n if not l or not r:\n return False\n if n.left and n.left.data != n.data:\n return False\n if n.right and n.right.data != n.data:\n return False\n ans[0] += 1\n return True\n\ndef singlevalued(root):\n ans = [0]\n dfs(root, ans)\n return ans[0]", "def singlevalued(root):\n self.dfs(root)\n return self.count\n\ndef dfs(root):\n if root:\n a = self.dfs(root.left)\n b = self.dfs(root.right)\n if a == -1 and b == -1 or (a == -1 and b == root.data) or (b == -1 and a == root.data):\n self.count += 1\n return root.data\n if a == b == root.data:\n self.count += 1\n return root.data\n return float('-inf')\n return -1", "def checkSingle(root):\n if root == None:\n return True\n rightBool = self.checkSingle(root.right)\n leftBool = self.checkSingle(root.left)\n if leftBool is False or rightBool is False:\n return False\n if root.right != None and root.right.data != root.data:\n return False\n if root.left != None and root.left.data != root.data:\n return False\n self.count += 1\n return True\n\ndef singlevalued(root):\n self.checkSingle(root)\n return self.count", "def singlevalued(root):\n global cnt\n cnt = 0\n self.traverse(root)\n return cnt\n\ndef traverse(root):\n global cnt\n if not root:\n return False\n if not root.right and (not root.left):\n cnt += 1\n return True\n x = self.traverse(root.left)\n y = self.traverse(root.right)\n if x and y:\n if root.right.data == root.data and root.left.data == root.data:\n cnt += 1\n return True\n elif root.left is None:\n if y and root.right.data == root.data:\n cnt += 1\n return True\n elif root.right is None:\n if x and root.left.data == root.data:\n cnt += 1\n return True\n return False", "def singlevalued(root):\n global cnt\n cnt = 0\n list = self.traverse(root)\n if len(set(list)) == 1:\n cnt += 1\n return cnt\n\ndef traverse(root):\n global cnt\n if not root:\n return []\n x = self.traverse(root.left)\n y = self.traverse(root.right)\n if x and x[0] != -1 and (len(set(x)) == 1):\n cnt += 1\n x = [x[0]]\n elif x:\n x = [-1]\n if y and y[0] != -1 and (len(set(y)) == 1):\n cnt += 1\n y = [y[0]]\n elif y:\n y = [-1]\n return [root.data] + x + y", "def getCounts(node):\n if node is None:\n return (None, 0)\n (val1, cnt1) = self.getCounts(node.left)\n (val2, cnt2) = self.getCounts(node.right)\n cnt = cnt1 + cnt2\n if (val1 is None or val1 == node.data) and (val2 is None or val2 == node.data):\n cnt += 1\n return (node.data, cnt)\n return (False, cnt)\n\ndef singlevalued(root):\n (_, cnt) = self.getCounts(root)\n return cnt", "def singlevalued(root):\n singleValue = [0]\n\n def Walker(node: Node):\n if node.data is None:\n return float('inf')\n if node.left is not None:\n left = Walker(node.left)\n else:\n left = node.data\n if node.right is not None:\n right = Walker(node.right)\n else:\n right = node.data\n if node.data == left == right:\n singleValue[0] = singleValue[0] + 1\n return node.data\n return float('inf')\n Walker(root)\n return singleValue[0]", "def singlevalued(root):\n\n def traversal(root):\n nonlocal count\n if root == None:\n return None\n if root.left:\n traversal(root.left)\n if root.right:\n traversal(root.right)\n if root.left and root.right:\n if root.left.data == root.right.data == root.data:\n count += 1\n elif root.left.data == root.right.data and root.left.data != root.data:\n root.data = -9999999\n elif root.left.data != root.data:\n root.data = root.left.data\n elif root.left:\n if root.left.data == root.data:\n count += 1\n else:\n root.data = -999999999\n elif root.right:\n if root.right.data == root.data:\n count += 1\n else:\n root.data = -11111111\n elif root.left == None and root.right == None:\n count += 1\n count = 0\n traversal(root)\n return count", "def solve(node, ans):\n if node is None:\n return (True, 'x')\n left = solve(node.left, ans)\n right = solve(node.right, ans)\n if (left[0] and right[0]) and (left[1] == 'x' or left[1] == node.data) and (right[1] == 'x' or right[1] == node.data):\n ans[0] += 1\n return (True, node.data)\n return (False, node.data)\n\ndef singlevalued(root):\n ans = [0]\n solve(root, ans)\n return ans[0]", "def helper(root, count):\n if not root:\n return True\n left = self.helper(root.left, count)\n right = self.helper(root.right, count)\n if left == False or right == False:\n return False\n if root.left and root.data != root.left.data:\n return False\n if root.right and root.data != root.right.data:\n return False\n count[0] += 1\n return True\n\ndef singlevalued(root):\n count = [0]\n self.helper(root, count)\n return count[0]", "def helper(root):\n if not root.left and (not root.right):\n self.count += 1\n return (True, root.data)\n (rflag, rval, lflag, lval) = (True, root.data, True, root.data)\n if root.left:\n (lflag, lval) = self.helper(root.left)\n if root.right:\n (rflag, rval) = self.helper(root.right)\n if lflag and rflag and (lval == rval) and (root.data == lval) and (root.data == rval):\n self.count += 1\n return (True, root.data)\n return (False, root.data)\n\ndef singlevalued(root):\n self.count = 0\n self.helper(root)\n return self.count", "import sys\n\ndef dfs(root, c):\n if root is None:\n return True\n left = self.dfs(root.left, c)\n right = self.dfs(root.right, c)\n if left == False or right == False:\n return False\n if root.left and root.data != root.left.data:\n return False\n if root.right and root.data != root.right.data:\n return False\n c[0] += 1\n return True\n\ndef singlevalued(root):\n c = [0]\n self.dfs(root, c)\n return c[0]", "def singlevalued(root):\n count = [0]\n\n def traverse(root, count):\n if not root:\n return True\n l_tree = traverse(root.left, count)\n r_tree = traverse(root.right, count)\n if l_tree == False or r_tree == False:\n return False\n if root.left and root.data != root.left.data or (root.right and root.data != root.right.data):\n return False\n count[0] += 1\n return True\n traverse(root, count)\n return count[0]", "def singlevalued(root):\n s = 0\n nodes = [[root, 0, True]]\n while len(nodes) > 0:\n (node, status, isSVST) = nodes[-1]\n if status == 0:\n if node.left is not None:\n nodes[-1][1] = 1\n nodes[-1][2] = node.data == node.left.data\n nodes.append([node.left, 0, True])\n elif node.right is not None:\n nodes[-1][1] = 2\n nodes[-1][2] = isSVST and node.data == node.right.data\n nodes.append([node.right, 0, True])\n else:\n s += 1\n nodes.pop()\n elif status == 2 or (status == 1 and node.right is None):\n if isSVST:\n s += 1\n nodes.pop()\n if len(nodes) > 0:\n nodes[-1][2] = isSVST and nodes[-1][2]\n else:\n nodes[-1][1] = 2\n nodes[-1][2] = isSVST and node.data == node.right.data\n nodes.append([node.right, 0, True])\n return s", "def postord(root, cnt):\n if root != None:\n (lft, cnt) = self.postord(root.left, cnt)\n (rght, cnt) = self.postord(root.right, cnt)\n if lft != 'T' or rght != 'T':\n return ('F', cnt)\n if root.left != None and root.left.data != root.data:\n return ('F', cnt)\n if root.right != None and root.right.data != root.data:\n return ('F', cnt)\n cnt += 1\n return ('T', cnt)\n else:\n return ('T', cnt)\n\ndef singlevalued(root):\n cnt = 0\n if root != None:\n (value, cnt) = self.postord(root, cnt)\n return cnt", "def singlevalued(root):\n res = 0\n\n def helper(node):\n nonlocal res\n if not node:\n return None\n left = helper(node.left)\n right = helper(node.right)\n if not node.left and (not node.right):\n res += 1\n return node.data\n elif not node.left and right == node.data:\n res += 1\n return node.data\n elif not node.right and left == node.data:\n res += 1\n return node.data\n elif node.left and node.right and (left == right == node.data):\n res += 1\n return node.data\n return None\n helper(root)\n return res", "def __init__(val):\n self.right = None\n self.data = val\n self.left = None\n\ndef countSingleRec(root, count):\n if root is None:\n return True\n left = self.countSingleRec(root.left, count)\n right = self.countSingleRec(root.right, count)\n if left == False or right == False:\n return False\n if root.left and root.data != root.left.data:\n return False\n if root.right and root.data != root.right.data:\n return False\n count[0] += 1\n return True\n\ndef singlevalued(root):\n count = [0]\n self.countSingleRec(root, count)\n return count[0]", "def f(temp, ans):\n if temp is None:\n return True\n a = f(temp.left, ans)\n b = f(temp.right, ans)\n if a and b:\n if temp.left is not None and temp.left.data != temp.data:\n return False\n if temp.right is not None and temp.right.data != temp.data:\n return False\n ans[0] += 1\n return True\n return False\n\ndef singlevalued(root):\n ans = [0]\n f(root, ans)\n return ans[0]", "import math\n\ndef solve(root):\n left = root.data\n if root.left:\n left = self.solve(root.left)\n right = root.data\n if root.right:\n right = self.solve(root.right)\n if left == right == root.data:\n self.ans += 1\n return root.data\n return None\n\ndef singlevalued(root):\n self.ans = 0\n self.solve(root)\n return self.ans", "def singlevalued(root):\n cnt = 0\n\n def sol(root):\n nonlocal cnt\n if not root:\n return True\n lf = sol(root.left)\n rf = sol(root.right)\n if lf and rf:\n x = root.left is None or root.left.data == root.data\n y = root.right is None or root.right.data == root.data\n if x and y:\n cnt += 1\n return True\n return False\n sol(root)\n return cnt", "def __init__():\n self.res = 0\n\ndef singlevalued(root):\n self.dfs(root)\n return self.res\n\ndef dfs(node):\n l = self.dfs(node.left) if node.left else node.data\n r = self.dfs(node.right) if node.right else node.data\n if l == r and l == node.data:\n self.res += 1\n return l\n else:\n return -1", "def singlevalued(root):\n\n def tree(root):\n if not root:\n return True\n l = tree(root.left)\n r = tree(root.right)\n if l == False or r == False:\n return False\n if root.left != None and root.data != root.left.data:\n return False\n if root.right != None and root.data != root.right.data:\n return False\n self.a += 1\n return True\n tree(root)\n return self.a", "def singlevalued(root):\n res = 0\n\n def recur(root):\n nonlocal res\n if not root:\n return set()\n cur = recur(root.left)\n cur.update(recur(root.right))\n cur.add(root.data)\n if len(cur) < 2:\n res += 1\n return cur\n recur(root)\n return res", "def singlevalued(root):\n dp = {'count': 0}\n\n def dfs(node):\n if not node:\n return True\n if node:\n if not node.left and (not node.right):\n dp['count'] += 1\n return True\n l = dfs(node.left)\n r = dfs(node.right)\n if l and r:\n if node.left and node.right:\n left = node.left.data\n right = node.right.data\n if left == right and right == node.data:\n dp['count'] += 1\n return True\n else:\n return False\n if node.right:\n if node.right.data == node.data:\n dp['count'] += 1\n return True\n else:\n return False\n if node.left:\n if node.left.data == node.data:\n dp['count'] += 1\n return True\n else:\n return False\n return False\n dfs(root)\n return dp['count']", "from sys import setrecursionlimit\nsetrecursionlimit(100000)\n\ndef singlevalued(root):\n ans = [0]\n\n def recur(node):\n if node is None:\n return True\n left = recur(node.left)\n right = recur(node.right)\n if left and right and (node.left is None or node.left.data == node.data) and (node.right is None or node.right.data == node.data):\n ans[0] += 1\n return True\n return False\n recur(root)\n return ans[0]", "def singlevalued(root):\n count = 0\n\n def helper(root, count):\n if root is None:\n return (True, count)\n (left, count) = helper(root.left, count)\n (right, count) = helper(root.right, count)\n if left == False or right == False:\n return (False, count)\n if root.left and root.data != root.left.data:\n return (False, count)\n if root.right and root.data != root.right.data:\n return (False, count)\n count += 1\n return (True, count)\n (x, y) = helper(root, count)\n return y", "def singlevalued(root):\n count = 0\n\n def solve(root):\n nonlocal count\n if root == None:\n return True\n l = solve(root.left)\n r = solve(root.right)\n if l and r:\n if (root.left == None or root.left.data == root.data) and (root.right == None or root.right.data == root.data):\n count += 1\n return True\n return False\n solve(root)\n return count", "def singlevalued(root):\n\n def postorder(root):\n if root is None:\n return True\n left = postorder(root.left)\n right = postorder(root.right)\n if left and right:\n if root.left is not None and root.left.data != root.data:\n return False\n if root.right is not None and root.right.data != root.data:\n return False\n self.count += 1\n return True\n return False\n self.count = 0\n postorder(root)\n return self.count", "def singlevalued(root):\n\n def dfs(root):\n if not root:\n return 0\n if not root.left and (not root.right):\n self.count += 1\n return root.data\n left = dfs(root.left)\n right = dfs(root.right)\n if (root.data == left or root.left == None) and (root.data == right or root.right == None):\n self.count += 1\n return root.data\n return -1\n self.count = 0\n dfs(root)\n return self.count\n count = 0\n countSingleValued(root, count)\n return count", "def singlevalued(root):\n\n def soln(node):\n if not node:\n return ('#', True)\n (l, fl) = soln(node.left)\n (r, fr) = soln(node.right)\n if not (fl and fr):\n return (l, False)\n if l == '#':\n l = node.data\n if r == '#':\n r = node.data\n if l == r == node.data:\n soln.res += 1\n return (node.data, True)\n return (l, False)\n soln.res = 0\n soln(root)\n return soln.res", "def singlevalued(root):\n self.ans = 0\n\n def dfs(root):\n if root == None:\n return True\n left = dfs(root.left)\n right = dfs(root.right)\n if left and right:\n if root.left and root.left.data != root.data or (root.right and root.right.data != root.data):\n return False\n else:\n self.ans += 1\n return True\n return False\n dfs(root)\n return self.ans"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["5\r\n / \\\r\n 1 5\r\n / \\ \\\r\n 5 5 5", "5\r\n / \\\r\n 4 5\r\n / \\ \\\r\n 4 4 5"], "outputs": ["4", "5"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/single-valued-subtree/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "__init__", "task_id": "TACO_lite/111", "example": [[[5, [1, 5, 5, 5, 5]], [5, [4, 5, 4, 4, 5]]], ["4", "5"]]} +{"requirement": "Given a number N find the sum of the Euler Totient values of all the divisors of N.\n \nExample 1:\nInput:\nN = 5\nOutput:\n5\nExplanation:\n1 and 5 are the factor \nof 5 and \u03a6(1) = 1 and\n\u03a6(5) = 4 and their sum\nis 4 + 1 = 5\nExample 2:\nInput:\nN = 1\nOutput:\n1\nExplanation:\n1 is the only factor of\n1 and \u03a6(1) = 1\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function phiSum() which takes an integer N as input parameter and returns an integer, sum of the Euler Totient values of all the divisors of N.\n \nExpected Time Complexity: O(1)\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= N <= 10^{6}", "solutions": ["def phisum(N):\n return N", "import math\n\ndef phisum(n):\n return n"], "starter_code": "def phisum (N):\n", "input_output": {"inputs": ["N = 5", "N = 1"], "outputs": ["5", "1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/euler-totient-sum-and-divisors5501/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "phisum", "task_id": "TACO_lite/223", "example": [[[5], [1]], ["5", "1"]]} +{"requirement": "Given an array A[] of N positive integers and two positive integers K_{1} and K_{2}. Find the sum of all elements between K_{1}^{th} and K_{2}^{th} smallest elements of the array. It may be assumed that (1 <= k1 < k2 <= n).\n \nExample 1:\nInput:\nN = 7\nA[] = {20, 8, 22, 4, 12, 10, 14}\nK1 = 3, K2 = 6\nOutput:\n26\nExplanation:\n3rd smallest element is 10\n6th smallest element is 20\nElement between 10 and 20 \n12,14. Their sum = 26.\n \nExample 2:\nInput\nN = 6\nA[] = {10, 2, 50, 12, 48, 13}\nK1= 2, K2 = 6\nOutput:\n73\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function sumBetweenTwoKth() which takes the array A[], its size N and two integers K1 and K2 as inputs and returns the sum of all the elements between K_{1}^{th} and K_{2}^{th} smallest elements.\n \nExpected Time Complexity: O(N. log(N))\nExpected Auxiliary Space: O(N)\n \nConstraints:\n1 \u2264 N \u2264 10^{5}\n1 \u2264 K_{1}, K_{2} \u2264 10^{9}", "solutions": ["def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n d = [x for x in A if x > A[K1 - 1] and x < A[K2 - 1]]\n return sum(d)", "import heapq\n\ndef sumbetweentwokth(A, N, k1, k2):\n x = []\n y = []\n heapq.heapify(x)\n heapq.heapify(y)\n for i in range(N):\n heapq.heappush(x, -A[i])\n heapq.heappush(y, -A[i])\n if len(x) > k1:\n heapq.heappop(x)\n if len(y) > k2:\n heapq.heappop(y)\n a1 = -heapq.heappop(x)\n a2 = -heapq.heappop(y)\n if a2 > a1:\n (a1, a2) = (a2, a1)\n c = 0\n for i in range(N):\n if A[i] < a1 and A[i] > a2:\n c += A[i]\n return c", "import heapq as h\n\ndef sumbetweentwokth(A, N, K1, K2):\n maxheap = []\n k1small = 0\n k2small = 0\n summ = 0\n for i in range(0, N):\n if len(maxheap) < K1:\n h.heappush(maxheap, -A[i])\n elif A[i] < -maxheap[0]:\n h.heappop(maxheap)\n h.heappush(maxheap, -A[i])\n k1small = -maxheap[0]\n maxheap = []\n for i in range(0, N):\n if len(maxheap) < K2:\n h.heappush(maxheap, -A[i])\n elif A[i] < -maxheap[0]:\n h.heappop(maxheap)\n h.heappush(maxheap, -A[i])\n k2small = -maxheap[0]\n if k1small > k2small:\n (k1small, k2small) = (k2small, k1small)\n for i in range(0, N):\n if A[i] > k1small and A[i] < k2small:\n summ = summ + A[i]\n return summ", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n l = A[K1:K2 - 1]\n return sum(l)", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n\n def findKthSmallest(arr, k):\n max_heap = []\n for i in arr:\n heapq.heappush(max_heap, -1 * i)\n if len(max_heap) > k:\n heapq.heappop(max_heap)\n return -1 * heapq.heappop(max_heap)\n min_val = findKthSmallest(A, K1)\n max_val = findKthSmallest(A, K2)\n res = 0\n for ele in A:\n if ele > min_val and ele < max_val:\n res += ele\n return res", "def sumbetweentwokth(A, N, K1, K2):\n A = sorted(A)\n s = sum(A[K1:K2 - 1])\n return s", "def suma(x):\n a = len(x)\n s = 0\n for i in range(a):\n s += x[i]\n return s\n\ndef sumbetweentwokth(A, N, K1, K2):\n A.sort()\n a = suma(A[K1:])\n b = suma(A[K2 - 1:])\n return a - b", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n new = A[K1 - 1:K2 - 1]\n return sum(new) - new[0]", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n a = []\n s = 0\n for i in range(K1, K2 - 1):\n a.append(A[i])\n for i in a:\n s += i\n return s", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n sum = 0\n for i in range(K1, K2 - 1):\n sum += A[i]\n return sum", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n ans = []\n heapq.heapify(ans)\n for i in range(N):\n heapq.heappush(ans, -1 * A[i])\n if len(ans) >= K2:\n heapq.heappop(ans)\n sm = 0\n while len(ans) > K1:\n sm += heapq.heappop(ans) * -1\n return sm", "def sumbetweentwokth(A, N, K1, K2):\n\n def get_ele(arr, k):\n import heapq\n heap = []\n for i in range(0, len(arr)):\n heapq.heappush(heap, -arr[i])\n if len(heap) > k:\n heapq.heappop(heap)\n return -heap[0]\n y = get_ele(A, K1)\n x = get_ele(A, K2)\n summ = 0\n for i in range(0, N):\n if A[i] > y and A[i] < x:\n summ += A[i]\n return summ", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n sumi = 0\n for i in range(N):\n if i > K1 - 1 and i < K2 - 1:\n sumi += A[i]\n return sumi", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n sm = 0\n x1 = self.min_values(A, N, K1)\n x2 = self.min_values(A, N, K2)\n for i in range(N):\n if x1 < A[i] < x2:\n sm += A[i]\n return sm\n\ndef min_values(A, N, K):\n minh = []\n heapq.heapify(minh)\n for i in range(N):\n heapq.heappush(minh, A[i] * -1)\n if len(minh) > K:\n heapq.heappop(minh)\n return minh[0] * -1", "import heapq\n\ndef sumbetweentwokth(arr, n, k1, k2):\n heapq.heapify(arr)\n l = arr.copy()\n s1 = 0\n s2 = 0\n for i in range(0, k1):\n s1 += heapq.heappop(l)\n l = arr.copy()\n for i in range(1, k2):\n s2 += heapq.heappop(l)\n total_sum = s2 - s1\n return total_sum", "import heapq\n\ndef sumbetweentwokth(arr, N, K1, K2):\n heapq.heapify(arr)\n l = arr.copy()\n s1 = 0\n s2 = 0\n for i in range(0, K1):\n s1 += heapq.heappop(l)\n l = arr.copy()\n for i in range(1, K2):\n s2 += heapq.heappop(l)\n s3 = s2 - s1\n return s3", "def sumbetweentwokth(A, N, K1, K2):\n res = sorted(A)\n l = []\n ind1 = res.index(res[K1 - 1])\n ind2 = res.index(res[K2 - 1])\n for i in range(ind1 + 1, ind2):\n l.append(res[i])\n return sum(l)", "import sys\nfrom heapq import *\n\ndef sumbetweentwokth(A, N, K1, K2):\n heap1 = [-sys.maxsize] * K1\n heap2 = [-sys.maxsize] * K2\n heapify(heap1)\n heapify(heap2)\n for num in A:\n if num < -heap1[0]:\n heappop(heap1)\n heappush(heap1, -num)\n if num < -heap2[0]:\n heappop(heap2)\n heappush(heap2, -num)\n heappop(heap2)\n ans = -sum(heap2) - -sum(heap1)\n return ans", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n c = A[K1 - 1]\n d = A[K2 - 1]\n lst = []\n for i in range(N):\n if A[i] > c and A[i] < d:\n lst.append(A[i])\n ans = sum(lst)\n return ans", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n m = A[K1 - 1]\n n = A[K2 - 1]\n s = 0\n for i in A:\n if i > m and i < n:\n s = s + i\n return s", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n lst = []\n for i in A:\n if i > A[K1 - 1] and i < A[K2 - 1]:\n lst.append(i)\n s = sum(lst)\n return s", "import heapq\n\ndef sumbetweentwokth(array, N, k1, k2):\n\n def findKthLargest(k):\n heap = []\n for num in array:\n if len(heap) < k:\n heapq.heappush(heap, -1 * num)\n elif -num > heap[0]:\n heapq.heappop(heap)\n heapq.heappush(heap, -1 * num)\n return heap[0] * -1\n num1 = findKthLargest(k1)\n num2 = findKthLargest(k2)\n ans = 0\n for num in array:\n if num > num1 and num < num2:\n ans += num\n return ans", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n i = A[K1 - 1]\n j = A[K2 - 1]\n sum = 0\n for m in A:\n if m > i and m < j:\n sum = sum + m\n return sum", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n\n def kthSmallest(a, k):\n maxh = []\n for i in range(len(a)):\n heapq.heappush(maxh, -a[i])\n if len(maxh) > k:\n heapq.heappop(maxh)\n return -maxh[0]\n ax = kthSmallest(A, K1)\n by = kthSmallest(A, K2)\n ans = 0\n for i in range(N):\n if A[i] > ax and A[i] < by:\n ans += A[i]\n return ans", "from heapq import heapify, heappush, heappop\n\ndef sumbetweentwokth(A, N, K1, K2):\n sum = 0\n new = [-1 * x for x in A]\n heapify(new)\n while N > K2 - 1:\n heappop(new)\n N -= 1\n while N > K1:\n sum += -1 * heappop(new)\n N -= 1\n return sum", "import heapq\n\ndef sumbetweentwokth(A, N, k1, k2):\n heapq.heapify(A)\n for i in range(k1):\n heapq.heappop(A)\n i = k1\n sum = 0\n while i < k2 - 1:\n sum += heapq.heappop(A)\n i += 1\n return sum", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n heap = []\n heapq.heapify(heap)\n for i in range(len(A)):\n heapq.heappush(heap, A[i])\n k1 = K1\n k2 = K2\n while k1:\n heapq.heappop(heap)\n k1 -= 1\n ans = 0\n k = k2 - K1 - 1\n while k > 0:\n if heap:\n ele = heapq.heappop(heap)\n ans += ele\n k -= 1\n return ans", "def sumbetweentwokth(A, N, K1, K2):\n arr = set(A)\n arr = sorted(A)\n sum = 0\n for i in range(K1, K2 - 1):\n sum = sum + arr[i]\n return sum", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n s = 0\n for i in range(N):\n if i > K1 - 1:\n s += A[i]\n if i == K2 - 1:\n s -= A[i]\n break\n return s", "def sumbetweentwokth(A, N, K1, K2):\n if K1 >= N:\n return 0\n A.sort()\n if K2 <= N:\n sum1 = 0\n for i in range(K1, K2 - 1):\n sum1 = sum1 + A[i]\n else:\n sum1 = 0\n for i in range(K1, N):\n sum1 = sum1 + A[i]\n return sum1", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n if K1 > N or K2 > N:\n return 0\n m = max(K1, K2)\n heap = []\n for i in A:\n heapq.heappush(heap, i)\n (ans, x) = (0, 0)\n while heap:\n e = heapq.heappop(heap)\n x += 1\n if x > K1 and x < K2:\n ans += e\n return ans", "def sumbetweentwokth(A, N, K1, K2):\n tot_sum = 0\n\n def kthElement(A, k, N):\n import heapq\n A = [-1 * n for n in A]\n hp = A[:k]\n heapq.heapify(hp)\n for i in range(k, N):\n heapq.heappushpop(hp, A[i])\n return -1 * hp[0]\n k1num = kthElement(A, K1, N)\n k2num = kthElement(A, K2, N)\n for i in range(0, N):\n if A[i] > k1num and A[i] < k2num:\n tot_sum += A[i]\n return tot_sum", "import heapq\n\ndef kthSmallest(arr, l, r, k):\n myList = []\n heapq.heapify(myList)\n for i in range(l, r + 1):\n heapq.heappush(myList, arr[i] * -1)\n if len(myList) > k:\n heapq.heappop(myList)\n return myList[0] * -1\n\ndef sumbetweentwokth(A, N, K1, K2):\n n1 = self.kthSmallest(A, 0, N - 1, K1)\n n2 = self.kthSmallest(A, 0, N - 1, K2)\n sum = 0\n for i in range(N):\n if n1 < A[i] < n2:\n sum += A[i]\n return sum", "from heapq import heappop, heappush, heapify\n\ndef sumbetweentwokth(A, N, K1, K2):\n\n def fun(A, K):\n maxheap = []\n heapify(maxheap)\n for i in A:\n heappush(maxheap, -i)\n if len(maxheap) > K:\n heappop(maxheap)\n return -1 * heappop(maxheap)\n max1 = fun(A, K1)\n max2 = fun(A, K2)\n ans = 0\n for i in A:\n if i > max1 and i < max2:\n ans += i\n return ans", "def sumbetweentwokth(A, N, K1, K2):\n from heapq import heapify, heappop, heappush\n\n def fun(A, K):\n h = []\n heapify(h)\n for i in A:\n heappush(h, -i)\n if len(h) > K:\n heappop(h)\n return -1 * heappop(h)\n r1 = fun(A, K1)\n r2 = fun(A, K2)\n ans = 0\n for i in A:\n if i > r1 and i < r2:\n ans += i\n return ans", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n s = 0\n while K1 < K2 - 1:\n s += A[K1]\n K1 = K1 + 1\n return s", "import heapq\n\ndef kthSmallest(k, arr):\n pq = []\n for num in arr:\n heapq.heappush(pq, -num)\n if len(pq) > k:\n heapq.heappop(pq)\n return -heapq.heappop(pq)\n\ndef sumbetweentwokth(A, N, K1, K2):\n num1 = kthSmallest(K1, A)\n num2 = kthSmallest(K2, A)\n res = 0\n for num in A:\n if num > num1 and num < num2:\n res += num\n return res", "def sumbetweentwokth(a, N, K1, K2):\n a.sort()\n return sum(a[K1:K2 - 1])", "def sumbetweentwokth(A, N, K1, K2):\n p = sorted(A)\n u = K1 - 1\n v = K2 - 1\n a = p[u + 1:v]\n return sum(a)", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n heap = []\n heapq.heapify(heap)\n for i in range(N):\n heapq.heappush(heap, -1 * A[i])\n if len(heap) > K2:\n heapq.heappop(heap)\n second = -1 * heap[0]\n while len(heap) > K1:\n heapq.heappop(heap)\n first = -1 * heap[0]\n total = 0\n for i in range(N):\n if A[i] > first and A[i] < second:\n total += A[i]\n return total", "from heapq import *\n\ndef sumbetweentwokth(arr, n, k1, k2):\n maxHeap = []\n for i in range(n):\n if i < k2 - 1:\n heappush(maxHeap, -arr[i])\n elif maxHeap[0] < -arr[i]:\n heappop(maxHeap)\n heappush(maxHeap, -arr[i])\n summ = 0\n for i in range(k2 - k1 - 1):\n summ += -heappop(maxHeap)\n return summ", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n x = A[K1 - 1]\n y = A[K2 - 1]\n s = 0\n for i in A:\n if i > x and i < y:\n s += i\n return s", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n heapq.heapify(A)\n total = 0\n while K1 > 0 or K2 > 0:\n el = heapq.heappop(A)\n K1 -= 1\n K2 -= 1\n if K1 < 0 and K2 > 0:\n total += el\n return total", "def sumbetweentwokth(A, N, k1, k2):\n t = sorted(A)\n s = 0\n f = 0\n return sum(t[k1:k2 - 1])", "def sumbetweentwokth(A, N, K1, K2):\n import heapq\n l = []\n l1 = []\n heapq.heapify(A)\n for i in range(N):\n a = heapq.heappop(A)\n l.append(a)\n for i in range(K1, K2 - 1):\n l1.append(l[i])\n return sum(l1)", "from heapq import *\n\ndef sumbetweentwokth(A, N, K1, K2):\n minheap = [num for num in A]\n heapify(minheap)\n (numK1, numK2) = (None, None)\n for i in range(K2):\n x = heappop(minheap)\n if i + 1 == K1:\n numK1 = x\n elif i + 1 == K2:\n numK2 = x\n break\n res = 0\n for num in A:\n if num > numK1 and num < numK2:\n res += num\n return res", "def sumbetweentwokth(A, N, K1, K2):\n list1 = []\n list1 = list1 + A\n list1.sort()\n ele1 = list1[K1 - 1]\n ele3 = list1[K2 - 1]\n r1 = max(ele1, ele3)\n r3 = min(ele1, ele3)\n s = 0\n for i in range(0, len(A)):\n if A[i] > r3 and A[i] < r1:\n s = s + A[i]\n return s", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n heap = []\n for i in A:\n heapq.heappush(heap, i)\n count = 0\n sum_ = 0\n while heap:\n p = heapq.heappop(heap)\n count += 1\n if count > K1 and count < K2:\n sum_ += p\n elif count >= K2:\n break\n return sum_", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n\n def ksmallest(A, x):\n heap = []\n for ch in A:\n heapq.heappush(heap, -ch)\n if len(heap) > x:\n heapq.heappop(heap)\n return -heap[0]\n first = ksmallest(A, K1)\n second = ksmallest(A, K2)\n summ = 0\n for ch in A:\n if second > ch > first:\n summ += ch\n return summ", "from heapq import *\n\ndef kthSmallest(arr, k):\n heap = []\n heapify(heap)\n for num in arr:\n heappush(heap, -1 * num)\n if len(heap) == k + 1:\n heappop(heap)\n return -1 * heappop(heap)\n\ndef sumbetweentwokth(A, N, K1, K2):\n k1thSmallest = self.kthSmallest(A, K1)\n k2thSmallest = self.kthSmallest(A, K2)\n sum = 0\n for num in A:\n if num > k1thSmallest and num < k2thSmallest:\n sum += num\n return sum", "def sumbetweentwokth(A, N, K1, K2):\n sum1 = 0\n A.sort()\n min1 = A[K1 - 1]\n max1 = A[K2 - 1]\n for i in A:\n if i > min1 and i < max1:\n sum1 += i\n return sum1", "def sumbetweentwokth(A, N, K1, K2):\n sum = 0\n A.sort()\n p = A[K1 - 1]\n q = A[K2 - 1]\n for i in A:\n if p < i < q:\n sum += i\n return sum", "def sumbetweentwokth(A, N, K1, K2):\n A.sort()\n ele1 = A[K1 - 1]\n ele2 = A[K2 - 1]\n sum1 = 0\n for i in range(len(A)):\n if A[i] > ele1 and A[i] < ele2:\n sum1 += A[i]\n return sum1", "def sumbetweentwokth(A, N, K1, K2):\n a = sorted(A)\n b = a[K1 - 1]\n c = a[K2 - 1]\n s = 0\n for i in a:\n if i > b and i < c:\n s = s + i\n return s", "def sumbetweentwokth(A, N, K1, K2):\n a = sorted(A)\n a = [i for i in a]\n return sum(a[K1:K2 - 1])", "import heapq\n\ndef sumbetweentwokth(A, N, K1, K2):\n ans = 0\n heapq.heapify(A)\n for i in range(K1):\n heapq.heappop(A)\n for i in range(K2 - K1 - 1):\n ans += heapq.heappop(A)\n return ans", "from heapq import *\n\ndef sumbetweentwokth(arr, n, k1, k2):\n heap = []\n for item in arr:\n heappush(heap, item)\n for _ in range(k1):\n heappop(heap)\n result = 0\n for _ in range(k2 - k1 - 1):\n result += heappop(heap)\n return result"], "starter_code": "def sumbetweentwokth(A, N, K1, K2):\n", "input_output": {"inputs": ["N = 7\r\nA[] = {20, 8, 22, 4, 12, 10, 14}\r\nK1 = 3, K2 = 6", "N = 6\r\nA[] = {10, 2, 50, 12, 48, 13}\r\nK1= 2, K2 = 6"], "outputs": ["26", "73"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Heap", "Sorting", "Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/sum-of-elements-between-k1th-and-k2th-smallest-elements3133/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N. log(N))", "entry_point": "sumbetweentwokth", "task_id": "TACO_lite/127", "example": [[[7, [20, 8, 22, 4, 12, 10, 14], 3, 6], [6, [10, 2, 50, 12, 48, 13], 2, 6]], [null, null]]} +{"requirement": "Given string S representing a postfix expression, the task is to evaluate the expression and find the final value. Operators will only include the basic arithmetic operators like *, /, + and -.\n \nExample 1:\nInput: S = \"231*+9-\"\nOutput: -4\nExplanation:\nAfter solving the given expression, \nwe have -4 as result.\nExample 2:\nInput: S = \"123+*8-\"\nOutput: -3\nExplanation:\nAfter solving the given postfix \nexpression, we have -3 as result.\nYour Task:\nYou do not need to read input or print anything. Complete the function evaluatePostfixExpression() that takes the string S denoting the expression as input parameter and returns the evaluated value.\nExpected Time Complexity: O(|S|)\nExpected Auixilliary Space: O(|S|)\nConstraints:\n1 \u2264 |S| \u2264 10^{5}\n0 \u2264 |S_{i}|\u2264 9 (And given operators)", "solutions": ["def evaluatepostfix(S):\n stack = []\n for i in range(len(S)):\n if S[i] in ['+', '-', '/', '*']:\n y = stack.pop()\n x = stack.pop()\n if S[i] == '+':\n stack.append(x + y)\n elif S[i] == '-':\n stack.append(x - y)\n elif S[i] == '*':\n stack.append(x * y)\n elif S[i] == '/':\n stack.append(x // y)\n else:\n stack.append(int(S[i]))\n return stack[-1]", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i.isdigit() is True:\n stack.append(i)\n else:\n a = int(stack.pop())\n b = int(stack.pop())\n if i == '+':\n res = b + a\n elif i == '-':\n res = b - a\n elif i == '*':\n res = b * a\n else:\n res = b // a\n stack.append(res)\n return res", "def evaluatepostfix(s):\n stack = []\n for i in s:\n if i in ['+', '*', '/', '-']:\n (y, x) = (stack.pop(), stack.pop())\n if i == '+':\n stack.append(x + y)\n elif i == '*':\n stack.append(x * y)\n elif i == '-':\n stack.append(x - y)\n else:\n stack.append(x // y)\n else:\n stack.append(int(i))\n return stack[-1]", "def evaluatepostfix(S):\n st = []\n ans = 0\n for i in S:\n if i.isdigit():\n st.append(i)\n else:\n if i == '/':\n i = '//'\n second = st.pop()\n first = st.pop()\n st.append(str(eval(first + i + second)))\n return int(st.pop())", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']:\n stack.append(int(i))\n else:\n op1 = stack.pop()\n op2 = stack.pop()\n if i == '/':\n stack.append(op2 // op1)\n if i == '*':\n stack.append(op1 * op2)\n if i == '+':\n stack.append(op1 + op2)\n if i == '-':\n stack.append(op2 - op1)\n return stack[-1]", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i.isdigit():\n stack.append(i)\n else:\n a = int(stack.pop())\n b = int(stack.pop())\n if i == '+':\n stack.append(a + b)\n elif i == '-':\n stack.append(b - a)\n elif i == '*':\n stack.append(a * b)\n else:\n stack.append(b // a)\n return sum(stack)", "def evaluatepostfix(S):\n S = S + '$'\n st = []\n for i in S:\n if i == '$':\n return st[-1]\n if i.isdigit():\n st.append(i)\n else:\n a = st.pop()\n b = st.pop()\n if i == '*':\n c = int(b) * int(a)\n elif i == '+':\n c = int(b) + int(a)\n elif i == '-':\n c = int(b) - int(a)\n else:\n c = int(b) / int(a)\n st.append(c)", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i.isdigit():\n stack.append(i)\n else:\n val1 = int(stack.pop())\n val2 = int(stack.pop())\n if i == '+':\n stack.append(val2 + val1)\n elif i == '-':\n stack.append(val2 - val1)\n elif i == '*':\n stack.append(val2 * val1)\n else:\n stack.append(val2 // val1)\n return sum(stack)", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:\n eva = 0\n a = int(stack.pop(-1))\n b = int(stack.pop(-1))\n if i == '+':\n eva = a + b\n elif i == '-':\n eva = b - a\n elif i == '*':\n eva = a * b\n elif i == '/':\n eva = b // a\n stack.append(eva)\n else:\n stack.append(i)\n return stack[-1]", "def evaluatepostfix(s):\n st = []\n for i in s:\n if i in '0123456789':\n st.append(i)\n else:\n p2 = st.pop()\n p1 = st.pop()\n res = eval(p1 + i + p2)\n st.append(str(int(res)))\n return st[-1]", "def evaluatepostfix(S):\n st = []\n hashmap = {'*', '+', '-', '/'}\n for i in S:\n if i in hashmap:\n val1 = st.pop()\n val2 = st.pop()\n if i == '+':\n st.append(val2 + val1)\n elif i == '-':\n st.append(val2 - val1)\n elif i == '*':\n st.append(val2 * val1)\n elif i == '/':\n st.append(val2 // val1)\n else:\n st.append(int(i))\n return sum(st)", "def evaluatepostfix(S):\n stack = []\n hashset = {'*', '/', '+', '-'}\n for i in S:\n if i in hashset:\n a = stack.pop()\n b = stack.pop()\n if i == '*':\n stack.append(b * a)\n elif i == '/':\n stack.append(b // a)\n elif i == '+':\n stack.append(b + a)\n else:\n stack.append(b - a)\n else:\n stack.append(int(i))\n return stack[0]", "def evaluatepostfix(S):\n stack = []\n top = -1\n for i in S:\n if i >= '0' and i <= '9':\n stack.append(int(i))\n top += 1\n else:\n y = stack.pop()\n top -= 1\n x = stack.pop()\n top -= 1\n if i == '+':\n stack.append(x + y)\n top += 1\n if i == '-':\n stack.append(x - y)\n top += 1\n if i == '*':\n stack.append(x * y)\n top += 1\n if i == '/':\n stack.append(x // y)\n top += 1\n return stack[0]", "def evaluatepostfix(S):\n st = []\n for i in S:\n if i.isdigit():\n st.append(int(i))\n elif len(st) > 1:\n if i == '+':\n st.append(st.pop(-1) + st.pop(-1))\n elif i == '-':\n st.append(-st.pop(-1) + st.pop(-1))\n elif i == '*':\n st.append(st.pop(-1) * st.pop(-1))\n elif i == '/':\n s = st.pop(-1)\n f = st.pop(-1)\n st.append(f // s)\n return st.pop(-1)", "import operator\n\ndef evaluatepostfix(S):\n stk = []\n r = 0\n for i in range(len(S)):\n if S[i] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:\n stk.append(int(S[i]))\n else:\n r1 = stk.pop()\n r2 = stk.pop()\n if S[i] == '*':\n op = operator.mul(r2, r1)\n elif S[i] == '-':\n op = operator.sub(r2, r1)\n elif S[i] == '+':\n op = operator.add(r2, r1)\n else:\n op = operator.truediv(r2, r1)\n op = int(op)\n stk.append(op)\n return stk[-1]", "def ev(a, b, c):\n if c == '+':\n return a + b\n elif c == '-':\n return b - a\n elif c == '*':\n return a * b\n else:\n return b // a\n\ndef evaluatepostfix(S):\n s = []\n for i in range(0, len(S)):\n if S[i].isalnum():\n s.append(int(S[i]))\n else:\n s.append(self.ev(s.pop(), s.pop(), S[i]))\n return s[-1]", "def evaluatepostfix(s):\n postfix = []\n for i in range(len(s)):\n if s[i] == '+':\n a1 = postfix.pop()\n a2 = postfix.pop()\n postfix.append(a1 + a2)\n elif s[i] == '-':\n a1 = postfix.pop()\n a2 = postfix.pop()\n postfix.append(a2 - a1)\n elif s[i] == '*':\n a1 = postfix.pop()\n a2 = postfix.pop()\n postfix.append(a1 * a2)\n elif s[i] == '/':\n a1 = postfix.pop()\n a2 = postfix.pop()\n postfix.append(a2 // a1)\n else:\n postfix.append(int(s[i]))\n return postfix.pop()", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i == '*':\n (n, m) = (stack.pop(), stack.pop())\n stack.append(n * m)\n elif i == '/':\n (n, m) = (stack.pop(), stack.pop())\n stack.append(m // n)\n elif i == '+':\n (n, m) = (stack.pop(), stack.pop())\n stack.append(n + m)\n elif i == '-':\n (n, m) = (stack.pop(), stack.pop())\n stack.append(m - n)\n else:\n stack.append(int(i))\n return stack[-1]", "def do_maths(a, b, op):\n if op == '+':\n return a + b\n if op == '-':\n return a - b\n if op == '*':\n return a * b\n if op == '/':\n return a // b\n\ndef evaluatepostfix(S):\n stk = []\n ans = 0\n for ch in S:\n if ch in ('+', '-', '*', '/'):\n a = stk.pop()\n b = stk.pop()\n res = self.do_maths(b, a, ch)\n stk.append(res)\n else:\n stk.append(int(ch))\n return stk.pop()", "def evaluatepostfix(S):\n stack = []\n for ch in S:\n if ch == '*' or ch == '+' or ch == '-' or (ch == '/'):\n first = stack.pop()\n second = stack.pop()\n if ch == '*':\n result = first * second\n elif ch == '/':\n result = second // first\n elif ch == '+':\n result = second + first\n else:\n result = second - first\n stack.append(result)\n else:\n stack.append(int(ch))\n return stack[-1]", "def evaluatepostfix(S):\n stk = []\n for i in S:\n if i == '*':\n A = stk.pop()\n B = stk.pop()\n stk.append(B * A)\n elif i == '/':\n A = stk.pop()\n B = stk.pop()\n stk.append(B // A)\n elif i == '-':\n A = stk.pop()\n B = stk.pop()\n stk.append(B - A)\n elif i == '+':\n A = stk.pop()\n B = stk.pop()\n stk.append(B + A)\n else:\n stk.append(int(i))\n return stk[-1]", "def evaluatepostfix(S):\n k = '+-*/'\n arr = []\n s = S[:]\n for i in range(len(s)):\n if s[i].isnumeric():\n arr.append(s[i])\n if s[i] in k:\n a = arr.pop()\n b = arr.pop()\n if s[i] == '*':\n c = int(b) * int(a)\n arr.append(c)\n elif s[i] == '+':\n c = int(b) + int(a)\n arr.append(c)\n elif s[i] == '-':\n c = int(b) - int(a)\n arr.append(c)\n elif s[i] == '/':\n c = int(b) / int(a)\n arr.append(c)\n return arr[0]", "def evaluatepostfix(S):\n a = []\n for i in S:\n if i.isnumeric():\n a.append(int(i))\n elif i == '*':\n m = a[-1] * a[-2]\n a.pop(-1)\n a.pop(-1)\n a.append(int(m))\n elif i == '+':\n m = a[-1] + a[-2]\n a.pop(-1)\n a.pop(-1)\n a.append(int(m))\n elif i == '-':\n m = a[-2] - a[-1]\n a.pop(-1)\n a.pop(-1)\n a.append(int(m))\n elif i == '/':\n m = a[-2] / a[-1]\n a.pop(-1)\n a.pop(-1)\n a.append(int(m))\n return int(a[0])", "def evaluatepostfix(S):\n stack = []\n for item in S:\n if item.isdigit():\n stack.append(item)\n else:\n item1 = stack.pop()\n item2 = stack.pop()\n stack.append(str(int(eval(item2 + item + item1))))\n return stack.pop()", "def evaluatepostfix(S):\n stk = []\n for i in S:\n if i == '+':\n stk.append(stk.pop() + stk.pop())\n elif i == '-':\n (a, b) = (stk.pop(), stk.pop())\n stk.append(b - a)\n elif i == '*':\n stk.append(stk.pop() * stk.pop())\n elif i == '/':\n (a, b) = (stk.pop(), stk.pop())\n stk.append(int(b / a))\n else:\n stk.append(int(i))\n return stk[-1]", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i != '+' and i != '*' and (i != '-') and (i != '/'):\n stack.append(i)\n else:\n n1 = int(stack.pop())\n n2 = int(stack.pop())\n if i == '+':\n stack.append(n1 + n2)\n elif i == '-':\n stack.append(n2 - n1)\n elif i == '*':\n stack.append(n1 * n2)\n elif i == '/':\n stack.append(n2 / n1)\n return stack[-1]", "def post_fix_evaluation(input_string):\n operand_stack = []\n n = len(input_string)\n for i in range(n):\n element = input_string[i]\n if is_integer(element):\n operand_stack.append(int(element))\n else:\n pop_do_operation(operand_stack, element)\n return operand_stack[0]\n\ndef performOperation(operand_1: int, operand_2: int, operator: str):\n if operator == '+':\n return operand_1 + operand_2\n elif operator == '-':\n return operand_1 - operand_2\n elif operator == '*':\n return operand_1 * operand_2\n else:\n return int(operand_1 / operand_2)\n\ndef pop_do_operation(operand_stack: [], operator: str):\n operand_2 = operand_stack.pop(-1)\n operand_1 = operand_stack.pop(-1)\n new_element = performOperation(operand_1, operand_2, operator)\n operand_stack.append(new_element)\n\ndef is_integer(element):\n return ord('0') <= ord(element) <= ord('9')\n\ndef evaluatepostfix(S):\n return post_fix_evaluation(S)", "def evaluatepostfix(S):\n op = {'*': lambda x, y: x * y, '+': lambda x, y: x + y, '-': lambda x, y: x - y, '/': lambda x, y: x / y}\n stack = []\n n = len(S)\n for i in range(0, n):\n if S[i].isdigit():\n stack.append(S[i])\n else:\n y = int(stack.pop())\n x = int(stack.pop())\n z = op[S[i]](x, y)\n stack.append(z)\n return stack.pop()", "def evaluatepostfix(S):\n st = []\n for i in S:\n if i in ['+', '-', '*', '/']:\n op2 = int(st.pop())\n op1 = int(st.pop())\n if i == '+':\n st.append(op1 + op2)\n elif i == '-':\n st.append(op1 - op2)\n elif i == '*':\n st.append(op1 * op2)\n elif i == '/':\n st.append(op1 / op2)\n else:\n st.append(i)\n return st[-1]", "def evaluatepostfix(S):\n expr = ['*', '/', '+', '-']\n arr = []\n for i in S:\n if i in expr:\n op2 = int(arr.pop())\n op1 = int(arr.pop())\n if i == '*':\n result = op1 * op2\n elif i == '/':\n result = op1 / op2\n elif i == '+':\n result = op1 + op2\n else:\n result = op1 - op2\n arr.append(result)\n else:\n arr.append(i)\n return arr.pop()", "def evaluatepostfix(S):\n st = []\n n = len(S)\n for i in range(n):\n if not S[i] in '+-/*':\n st.append(S[i])\n else:\n a = int(st.pop())\n b = int(st.pop())\n if S[i] == '+':\n tmpAns = b + a\n if S[i] == '-':\n tmpAns = b - a\n if S[i] == '/':\n tmpAns = b / a\n if S[i] == '*':\n tmpAns = b * a\n st.append(tmpAns)\n return st[-1]", "def evaluatepostfix(S):\n s = []\n for i in S:\n if i.isdigit():\n s.append(int(i))\n elif i == '+':\n x = s.pop()\n y = s.pop()\n s.append(x + y)\n elif i == '-':\n x = s.pop()\n y = s.pop()\n s.append(y - x)\n elif i == '*':\n x = s.pop()\n y = s.pop()\n s.append(x * y)\n elif i == '/':\n x = s.pop()\n y = s.pop()\n s.append(y // x)\n return s[0]", "def evaluatepostfix(S):\n stk = []\n s1 = '*/+-'\n for i in S:\n if i not in s1:\n stk.append(int(i))\n else:\n x = stk.pop()\n y = stk.pop()\n if i == '*':\n res = x * y\n elif i == '+':\n res = x + y\n elif i == '-':\n res = y - x\n else:\n res = y // x\n stk.append(res)\n return stk[-1]", "def evaluatepostfix(S):\n x = ['+', '-', '/', '*']\n stack = []\n for i in S:\n if i in x:\n a = stack.pop()\n b = stack.pop()\n r = b + i + a\n res = int(eval(r))\n stack.append(str(res))\n else:\n stack.append(i)\n return stack.pop()", "def evaluatepostfix(s):\n stack = []\n for c in s:\n if c == '+' or c == '/' or c == '*' or (c == '-'):\n op2 = int(stack.pop())\n op1 = int(stack.pop())\n if c == '+':\n r = op1 + op2\n elif c == '-':\n r = op1 - op2\n elif c == '*':\n r = op1 * op2\n else:\n r = op1 // op2\n stack.append(r)\n else:\n stack.append(int(c))\n return stack[0]", "def evaluatepostfix(S):\n x = []\n op = {'*', '/', '+', '-'}\n for i in S:\n if i in op:\n a = x.pop()\n b = x.pop()\n if i == '*':\n x.append(b * a)\n elif i == '/':\n x.append(b // a)\n elif i == '+':\n x.append(b + a)\n else:\n x.append(b - a)\n else:\n x.append(int(i))\n return x[0]", "def evaluatepostfix(S):\n l = list(S)\n operators = ['*', '+', '-', '/']\n operands = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]\n stack = []\n for i in range(len(l)):\n if str(l[i]) not in operators:\n stack.append(int(l[i]))\n else:\n s1 = stack.pop()\n s2 = stack.pop()\n if str(l[i]) == '-':\n val = s2 - s1\n elif str(l[i]) == '+':\n val = s1 + s2\n elif str(l[i]) == '*':\n val = s1 * s2\n elif str(l[i]) == '/':\n val = s2 // s1\n stack.append(val)\n return stack[-1]", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i == '+' or i == '/' or i == '*' or (i == '-'):\n a = stack.pop()\n b = stack.pop()\n if i == '/':\n p = '//'\n stack.append(str(eval(b + p + a)))\n else:\n stack.append(str(eval(b + i + a)))\n else:\n stack.append(i)\n re = stack.pop()\n return re", "def evaluatepostfix(s):\n st = []\n for i in s:\n if i.isdigit():\n st.append(i)\n else:\n op1 = int(st.pop())\n op2 = int(st.pop())\n if i == '+':\n ans = op2 + op1\n elif i == '-':\n ans = op2 - op1\n elif i == '*':\n ans = op2 * op1\n elif i == '/':\n ans = op2 / op1\n st.append(ans)\n return st.pop()", "from queue import LifoQueue as Stack\n\ndef evaluatepostfix(S):\n stack = Stack()\n for char in S:\n if char in '*/+-':\n (operand2, operand1) = (stack.get(), stack.get())\n result = str(int(eval(operand1 + char + operand2)))\n stack.put(result)\n else:\n stack.put(char)\n return int(stack.get())", "def evaluatepostfix(S):\n stack = []\n for ele in S:\n if ele.isalnum():\n stack.append(ele)\n continue\n if len(stack) >= 2:\n sec = int(stack.pop())\n first = int(stack.pop())\n else:\n return -1\n if ele == '*':\n stack.append(first * sec)\n elif ele == '+':\n stack.append(first + sec)\n elif ele == '-':\n stack.append(first - sec)\n elif ele == '/':\n stack.append(first // sec)\n return stack[0] if stack else -1", "def evaluatepostfix(S):\n stack = []\n operators = ('+', '-', '*', '/')\n for item in S:\n if item not in operators:\n stack.append(item)\n else:\n first = int(stack.pop())\n second = int(stack.pop())\n if item == '+':\n stack.append(second + first)\n elif item == '-':\n stack.append(second - first)\n elif item == '*':\n stack.append(second * first)\n elif item == '/':\n stack.append(second / first)\n return stack[0]", "def evaluatepostfix(S):\n stack = []\n ans = None\n for i in S:\n if i == '*':\n t1 = stack.pop()\n t2 = stack.pop()\n stack.append(t1 * t2)\n elif i == '+':\n t1 = stack.pop()\n t2 = stack.pop()\n stack.append(t1 + t2)\n elif i == '-':\n t1 = stack.pop()\n t2 = stack.pop()\n stack.append(t2 - t1)\n elif i == '/':\n t1 = stack.pop()\n t2 = stack.pop()\n stack.append(t2 // t1)\n else:\n stack.append(int(i))\n return stack.pop()", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i.isdigit():\n stack.append(int(i))\n elif i == '*':\n stack.append(int(stack.pop(-2) * stack.pop()))\n elif i == '/':\n stack.append(int(stack.pop(-2) / stack.pop()))\n elif i == '+':\n stack.append(int(stack.pop(-2) + stack.pop()))\n elif i == '-':\n stack.append(int(stack.pop(-2) - stack.pop()))\n return stack[0]", "def evaluatepostfix(S):\n\n def fun(x, y, oper):\n if oper == '+':\n return x + y\n if oper == '-':\n return x - y\n if oper == '*':\n return x * y\n if oper == '/':\n return x // y\n s = []\n for i in S:\n if i.isdigit():\n s.append(int(i))\n else:\n y = s.pop()\n x = s.pop()\n res = fun(x, y, i)\n s.append(res)\n return s.pop()", "def evaluatepostfix(S):\n l = ['+', '-', '*', '/']\n s1 = []\n for i in S:\n if i not in l:\n s1.append(i)\n else:\n o1 = int(s1.pop())\n o2 = int(s1.pop())\n if i == '+':\n s1.append(o1 + o2)\n elif i == '-':\n s1.append(o2 - o1)\n elif i == '*':\n s1.append(o1 * o2)\n else:\n try:\n s1.append(int(o2 // o1))\n except:\n return int(o2 // o1)\n return s1.pop()", "def evaluatepostfix(S):\n stack = []\n res = 0\n for i in S:\n if i.isnumeric():\n stack.append(int(i))\n else:\n a = stack.pop()\n b = stack.pop()\n if i == '+':\n res = b + a\n if i == '*':\n res = b * a\n if i == '-':\n res = b - a\n if i == '/':\n res = b // a\n stack.append(res)\n return stack[-1]", "def evaluatepostfix(S):\n (stack, n) = ([], len(S))\n for i in range(n):\n if S[i] == '*':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(op1 * op2)\n elif S[i] == '+':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(op1 + op2)\n elif S[i] == '-':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(op1 - op2)\n elif S[i] == '/':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(op1 // op2)\n else:\n stack.append(int(S[i]))\n return stack.pop() if stack else 0", "def evaluatepostfix(s):\n stack = list()\n for char in s:\n if char == '+':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(op1 + op2)\n elif char == '-':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(op1 - op2)\n elif char == '*':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(op1 * op2)\n elif char == '/':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(int(op1 / op2))\n else:\n stack.append(int(char))\n return stack.pop()", "def get_res(a, b, symbol):\n if symbol == '+':\n return a + b\n elif symbol == '-':\n return a - b\n elif symbol == '*':\n return a * b\n else:\n return a // b\n\ndef evaluatepostfix(S):\n exp = list(S)\n stack = []\n for i in exp:\n if i.isdigit():\n stack.append(int(i))\n else:\n op1 = stack.pop()\n op2 = stack.pop()\n res = get_res(op2, op1, i)\n stack.append(res)\n return stack[-1]", "def evaluatepostfix(S):\n temp = []\n for i in S:\n if i.isdigit():\n temp.append(i)\n elif i in ['*', '+', '-', '/']:\n b = int(temp.pop())\n a = int(temp.pop())\n if i == '*':\n ans = a * b\n elif i == '/':\n ans = a // b\n elif i == '-':\n ans = a - b\n else:\n ans = a + b\n temp.append(ans)\n return temp.pop()", "def evaluatepostfix(S):\n li = []\n for i in S:\n if i not in '*/+-':\n li.insert(0, i)\n elif i == '*':\n p2 = li.pop(0)\n p1 = li.pop(0)\n li.insert(0, int(p1) * int(p2))\n elif i == '/':\n p2 = li.pop(0)\n p1 = li.pop(0)\n li.insert(0, int(p1) / int(p2))\n elif i == '+':\n p2 = li.pop(0)\n p1 = li.pop(0)\n li.insert(0, int(p1) + int(p2))\n elif i == '-':\n p2 = li.pop(0)\n p1 = li.pop(0)\n li.insert(0, int(p1) - int(p2))\n res = li.pop(0)\n return res", "def evaluatepostfix(S):\n st = []\n for i in S:\n if i in '0123456789':\n st.append(i)\n elif i in '+-/*':\n op1 = st.pop()\n op2 = st.pop()\n res = eval(op2 + i + op1)\n st.append(str(int(res)))\n return ''.join(st)", "def evaluatepostfix(S):\n a = []\n for s in S:\n if s == '*' or s == '/' or s == '+' or (s == '-'):\n x = a.pop()\n y = a.pop()\n z = eval(str(y) + s + str(x))\n a.append(int(z))\n s = s[1:]\n else:\n a.append(s[0])\n s = s[1:]\n res = a[0]\n return res", "def evaluatepostfix(s):\n stack = list()\n n = len(s)\n for i in range(n):\n if s[i] == '+':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(int(op1 + op2))\n elif s[i] == '-':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(int(op1 - op2))\n elif s[i] == '*':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(int(op1 * op2))\n elif s[i] == '/':\n op2 = stack.pop()\n op1 = stack.pop()\n stack.append(int(op1 / op2))\n else:\n stack.append(int(s[i]))\n return stack.pop()", "def evaluatepostfix(s):\n stack = []\n for c in s:\n if c in '+-*/':\n if c == '+':\n stack.append(stack.pop() + stack.pop())\n if c == '-':\n stack.append(-stack.pop() + stack.pop())\n if c == '*':\n stack.append(stack.pop() * stack.pop())\n if c == '/':\n t = stack.pop()\n u = stack.pop()\n stack.append(u // t)\n elif c in '0123456789':\n stack.append(int(c))\n return stack[0]", "def evaluatepostfix(S):\n stack = []\n for i in range(len(S)):\n if '0' <= S[i] <= '9':\n stack.append(S[i])\n else:\n op2 = int(stack.pop())\n op1 = int(stack.pop())\n if S[i] == '+':\n res = op1 + op2\n if S[i] == '-':\n res = op1 - op2\n if S[i] == '*':\n res = op1 * op2\n if S[i] == '/':\n res = op1 // op2\n stack.append(res)\n return stack[-1]", "def evaluatepostfix(S):\n symbol = ['*', '+', '-', '/']\n a = []\n for i in S:\n if i not in symbol:\n a.append(int(i))\n else:\n a1 = a.pop()\n a2 = a.pop()\n if i == '*':\n a.append(a2 * a1)\n elif i == '+':\n a.append(a2 + a1)\n elif i == '-':\n a.append(a2 - a1)\n elif i == '/':\n a.append(a2 // a1)\n return a[0]", "import queue\n\ndef evaluatepostfix(S):\n stack = queue.LifoQueue()\n for ele in S:\n if ele == '*' or ele == '/' or ele == '+' or (ele == '-'):\n a = stack.get()\n b = stack.get()\n if ele == '*':\n x = b * a\n elif ele == '/':\n x = b // a\n elif ele == '+':\n x = b + a\n else:\n x = b - a\n stack.put(x)\n else:\n stack.put(int(ele))\n return stack.get()", "def evaluatepostfix(S):\n temp = []\n for i in range(len(S)):\n if S[i] == '/':\n a = int(temp.pop())\n b = int(temp.pop())\n temp.append(b / a)\n elif S[i] == '*':\n a = int(temp.pop())\n b = int(temp.pop())\n temp.append(a * b)\n elif S[i] == '-':\n a = int(temp.pop())\n b = int(temp.pop())\n temp.append(b - a)\n elif S[i] == '+':\n a = int(temp.pop())\n b = int(temp.pop())\n temp.append(a + b)\n else:\n temp.append(S[i])\n return temp[0]", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i.isdigit():\n stack.append(i)\n else:\n val1 = stack.pop()\n val2 = stack.pop()\n if i == '/':\n p = '//'\n stack.append(str(eval(val2 + p + val1)))\n else:\n stack.append(str(eval(val2 + i + val1)))\n return stack.pop()", "def evaluatepostfix(S):\n st = []\n op = ['+', '-', '*', '/']\n for i in S:\n if i in op:\n a = st[-1]\n st.pop()\n a = int(a)\n b = st[-1]\n st.pop()\n b = int(b)\n if i == '+':\n st.append(b + a)\n if i == '-':\n st.append(b - a)\n if i == '*':\n st.append(b * a)\n if i == '/':\n st.append(int(b / a))\n else:\n st.append(i)\n return st[-1]", "def evaluatepostfix(S):\n op = ['*', '+', '-', '/']\n stk = []\n for c in S:\n if c not in op:\n stk.append(c)\n else:\n optr = c\n op2 = stk.pop()\n op1 = stk.pop()\n res = int(eval(str(op1) + str(optr) + str(op2)))\n stk.append(res)\n x = stk.pop()\n return x", "def evaluatepostfix(S):\n stack = []\n for chr in S:\n if chr in '+-/*':\n if len(stack) < 2:\n return 'stack underflow'\n else:\n a = stack.pop()\n b = stack.pop()\n result = eval(str(b) + chr + str(a))\n stack.append(int(result))\n else:\n stack.append(chr)\n return stack.pop()", "def evaluatepostfix(S):\n stack = []\n for item in S:\n if item != '*' and item != '/' and (item != '+') and (item != '-'):\n stack.append(item)\n else:\n item1 = int(stack.pop())\n item2 = int(stack.pop())\n if item == '*':\n stack.append(item1 * item2)\n elif item == '/':\n stack.append(item2 // item1)\n elif item == '+':\n stack.append(item1 + item2)\n else:\n stack.append(item2 - item1)\n return stack.pop()", "def evaluatepostfix(s):\n r = 0\n l = []\n for i in s:\n if i in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']:\n l.append(int(i))\n else:\n b = l.pop()\n a = l.pop()\n if i == '*':\n r = a * b\n if i == '+':\n r = a + b\n if i == '-':\n r = a - b\n if i == '/':\n r = a // b\n l.append(r)\n return l[-1]", "def ifOperand(ch):\n return ch == '*' or ch == '+' or ch == '/' or (ch == '-')\n\ndef evaluatepostfix(S):\n stack = []\n for ch in S:\n if ifOperand(ch):\n a = stack.pop()\n b = stack.pop()\n if ch == '-':\n stack.append(int(b) - int(a))\n if ch == '+':\n stack.append(int(b) + int(a))\n if ch == '*':\n stack.append(int(b) * int(a))\n if ch == '/':\n stack.append(int(b) // int(a))\n else:\n stack.append(ch)\n return stack[-1]", "def evaluatepostfix(S):\n stack = []\n for char in S:\n if char.isnumeric():\n stack.append(char)\n else:\n second_num = int(stack.pop(-1))\n first_num = int(stack.pop(-1))\n if char == '*':\n ans = first_num * second_num\n stack.append(ans)\n elif char == '+':\n ans = first_num + second_num\n stack.append(ans)\n elif char == '-':\n ans = first_num - second_num\n stack.append(ans)\n elif char == '/':\n ans = first_num / second_num\n stack.append(ans)\n return stack.pop(-1)", "def evaluatepostfix(S):\n stack = []\n allOperators = set(['+', '-', '*', '/', '^', '(', ')'])\n for i in range(0, len(S)):\n if S[i] not in allOperators:\n stack.append(S[i])\n else:\n a = stack[-1]\n stack.pop()\n a = int(a)\n b = stack[-1]\n stack.pop()\n b = int(b)\n if S[i] == '+':\n stack.append(b + a)\n if S[i] == '-':\n stack.append(b - a)\n if S[i] == '*':\n stack.append(b * a)\n if S[i] == '/':\n stack.append(b / a)\n return stack[-1]", "def __init__(maxsize):\n self.maxsize = maxsize\n self.top = -1\n self.arr = []\n\ndef empty():\n return self.top == -1\n\ndef full():\n return self.top == self.maxsize\n\ndef push(data):\n if self.full():\n return 'Stack is full'\n self.top += 1\n self.arr.append(data)\n\ndef peek():\n if self.empty():\n return 'Stack is empty'\n return self.arr[self.top]\n\ndef pop():\n if self.empty():\n return 'Stack is empty'\n top_ele = self.arr.pop()\n self.top -= 1\n return top_ele\n\ndef pred(sym):\n if sym == '*' or sym == '/':\n return 3\n if sym == '+' or sym == '-':\n return 2\n if sym == '#':\n return 1\n\ndef op(l, r, o):\n if o == '*':\n return l * r\n if o == '/':\n return l // r\n if o == '+':\n return l + r\n if o == '-':\n return l - r\n\ndef evaluatepostfix(S):\n post_arr = []\n for s in S:\n if s in ('*', '/', '+', '-'):\n right = post_arr.pop()\n left = post_arr.pop()\n post_arr.append(self.op(int(left), int(right), s))\n else:\n post_arr.append(s)\n res = post_arr.pop()\n if res == -0:\n return 0\n return res", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']:\n stack.append(int(i))\n else:\n pop1 = stack.pop()\n pop2 = stack.pop()\n if i == '*':\n value = pop2 * pop1\n stack.append(value)\n elif i == '+':\n value = pop2 + pop1\n stack.append(value)\n elif i == '-':\n value = pop2 - pop1\n stack.append(value)\n elif i == '/':\n value = pop2 // pop1\n stack.append(value)\n return stack[-1]", "def evaluatepostfix(S):\n stack = []\n for i in S:\n if i in ['*', '/', '+', '-']:\n y = stack.pop()\n x = stack.pop()\n if i == '*':\n stack.append(int(x) * int(y))\n elif i == '/':\n stack.append(int(x) / int(y))\n elif i == '+':\n stack.append(int(x) + int(y))\n elif i == '-':\n stack.append(int(x) - int(y))\n else:\n stack.append(i)\n return stack[0]", "def evaluatepostfix(S):\n result = 0\n stack = []\n for i in S:\n if i in ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'):\n stack.append(int(i))\n else:\n first_value = stack.pop()\n second_value = stack.pop()\n if i == '+':\n result = second_value + first_value\n if i == '-':\n result = second_value - first_value\n if i == '*':\n result = second_value * first_value\n if i == '/':\n result = second_value // first_value\n stack.append(result)\n return stack.pop()"], "starter_code": "def evaluatepostfix(S):\n", "input_output": {"inputs": ["S = \"231*+9-\"", "S = \"123+*8-\""], "outputs": ["-4", "-3"]}, "difficulty": "EASY", "raw_tags": ["Stack", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/evaluation-of-postfix-expression1735/1", "Expected Auxiliary Space": "O(|S|)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "evaluatepostfix", "task_id": "TACO_lite/193", "example": [[["231*+9-"], ["123+*8-"]], ["-4", "-3"]]} +{"requirement": "# Task\n\nYour task is to sort the characters in a string according to the following rules:\n```\n- Rule1: English alphabets are arranged from A to Z, case insensitive.\n ie. \"Type\" --> \"epTy\"\n- Rule2: If the uppercase and lowercase of an English alphabet exist\n at the same time, they are arranged in the order of oringal input.\n ie. \"BabA\" --> \"aABb\"\n- Rule3: non English alphabet remain in their original position.\n ie. \"By?e\" --> \"Be?y\"\n```\n\n# Input/Output\n\n\n`[input]` string `s`\n\nA non empty string contains any characters(English alphabets or non English alphabets).\n\n`[output]` a string\n\nA sorted string according to the rules above.\n\n# Example\n\n\nFor `s = \"cba\"`, the output should be `\"abc\"`.\n\nFor `s = \"Cba\"`, the output should be `\"abC\"`.\n\nFor `s = \"cCBbAa\"`, the output should be `\"AaBbcC\"`.\n\nFor `s = \"c b a\"`, the output should be `\"a b c\"`.\n\nFor `s = \"-c--b--a-\"`, the output should be `\"-a--b--c-\"`.\n\nFor `s = \"Codewars\"`, the output should be `\"aCdeorsw\"`.", "solutions": ["def sort_string(s):\n a = iter(sorted((c for c in s if c.isalpha()), key=str.lower))\n return ''.join((next(a) if c.isalpha() else c for c in s))", "import re\n\ndef sort_string(s):\n sortedChr = iter(sorted(re.sub('[^a-zA-Z]', '', s), key=str.lower))\n return re.sub('[a-zA-Z]', lambda m: next(sortedChr), s)", "def sort_string(s):\n alphas = [x for x in s if x.isalpha()]\n res = iter(sorted(alphas, key=lambda x: x.lower()))\n return ''.join((next(res) if x.isalpha() else x for x in s))", "def sort_string(stg):\n stg_ascii = (char for char in stg if char.isalpha())\n sorted_ascii = iter(sorted(stg_ascii, key=str.lower))\n return ''.join((next(sorted_ascii) if char.isalpha() else char for char in stg))", "from string import ascii_letters\nsortable = frozenset(ascii_letters)\n\ndef sort_string(s):\n sorted_chars = iter(sorted((c for c in s if c in sortable), key=str.lower))\n return ''.join((next(sorted_chars) if c in sortable else c for c in s))", "sort_string = lambda s: (lambda r: ''.join((r.pop(0) if e.isalpha() else e for e in s)))([e[0] for e in sorted(sorted([[k, i] for (i, k) in enumerate(s) if k.isalpha()], key=lambda a: a[1]), key=lambda a: a[0].lower())])", "def sort_string(s):\n it = iter(sorted([(i, x) for (i, x) in enumerate(s) if x.isalpha()], key=lambda p: (p[1].lower(), p[0])))\n return ''.join((next(it)[1] if x.isalpha() else x for x in s))", "def sort_string(s):\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n rule12 = list(sorted([x for x in s if x.lower() in alphabet], key=lambda i: alphabet.find(i.lower())))\n for (i, sym) in enumerate(s):\n if sym.lower() not in alphabet:\n rule12.insert(i, sym)\n return ''.join(rule12)"], "starter_code": "def sort_string(s):\n", "input_output": {"fn_name": "sort_string", "inputs": [["a"], ["cba"], ["Cba"], ["cCBbAa"], ["!"], ["c b a"], ["-c--b--a-"], ["cbaCcC"], ["Codewars"], [" MkWD{RB=//k-^ J@,xH Vfi uAz+$ kV _[ }a!}%pSBwn !kKB (b q PQF +}wS .kfU r wFNEs#NsR UVMdG"]], "outputs": [["a"], ["abc"], ["abC"], ["AaBbcC"], ["!"], ["a b c"], ["-a--b--c-"], ["abcCcC"], ["aCdeorsw"], [" AaBB{Bb=//D-^ d@,Ef FfF GHi+$ Jk _[ }k!}%kkKkM !MnN (N p PqQ +}Rr .RSS s suUUV#VVW wwwxz"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms", "Sorting"], "name": null, "source": "codewars", "tags": ["String algorithms", "Sorting"], "skill_types": ["Sorting"], "url": "https://www.codewars.com/kata/5936256f2e2a27edc9000047", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sort_string", "task_id": "TACO_lite/174", "example": [[["cba"], ["Cba"], ["cCBbAa"], ["c b a"], ["-c--b--a-"], ["Codewars"]], ["abc", "abC", "AaBbcC", "a b c", "-a--b--c-", "aCdeorsw"]]} +{"requirement": "Given a positive number k, we need to find a minimum value of positive integer n, such that XOR of n and n+1 is equal to k. If no such n exist then print -1.\nExample 1:\nInput: k = 3\nOutput: 1\nExplaination: 1 xor 2 = 3.\nExample 2:\nInput: k = 6\nOutput: -1\nExplaination: There is no such n, so that, \nn xor n+1 = k.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function xorCal() which takes k as input parameter and returns the value of n. If there is no such , then it returns -1.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 k \u2264 100", "solutions": ["def xorcal(k):\n if k == 1:\n return 2\n if k & k + 1 == 0:\n return k >> 1\n return -1", "def xorcal(k):\n if k == 1:\n return 2\n return -1 if k & k + 1 else k // 2", "def xorcal(k):\n if k == 1:\n return 2\n for i in range(k):\n if i ^ i + 1 == k:\n return i\n return -1", "def xorcal(k):\n p = k + 1\n i = 0\n s = bin(k)[2:]\n l = len(s)\n if k == 0:\n return 0\n if k == 1:\n return 2\n if s.count('1') == l:\n h = '1' * (l - 1)\n return int(h, 2)\n else:\n return -1", "def xorcal(k):\n n = 1\n if k == 1:\n return 2\n while n <= k:\n if k ^ n == n + 1:\n return n\n else:\n n += 1\n return -1", "from math import log2\n\ndef xorcal(k):\n if k & k + 1:\n return -1\n k += 1\n k = int(log2(k))\n k -= 1\n if k == 0:\n return 2\n return int('1' * k, 2)", "def xorcal(k):\n if k == 1:\n return 2\n elif k & k + 1 == 0:\n return k // 2\n else:\n return -1", "def xorcal(k):\n for i in range(1, 100):\n if i.__xor__(i + 1) == k:\n return i\n return -1", "def xorcal(k):\n n = n1 = k\n n = n >> 1\n n1 = n1 << 1\n if n != 0 and n ^ n + 1 == k:\n return n\n if n1 ^ n1 + 1 == k:\n return n1\n return -1", "def xorcal(k):\n i = 1\n while i <= 105:\n if i ^ i + 1 == k:\n return i\n i += 1\n return -1", "def xorcal(k):\n if k == 1:\n return 2\n i = 1\n while pow(2, i) <= k:\n a = pow(2, i)\n if k == a + (a - 1):\n return a - 1\n i += 1\n return -1", "def xorcal(k):\n if k == 1:\n return 2\n l = [1, 3, 7, 15, 31, 63]\n if k in l:\n return int(k / 2)\n return -1", "def xorcal(k):\n a = []\n for i in range(1, 100):\n a = i\n b = i + 1\n if a ^ b == k:\n return a\n return -1", "def xorcal(k):\n for n in range(1, 100):\n if n ^ n + 1 == k:\n return n\n return -1", "def xorcal(k):\n if k == 1:\n return 2\n string = bin(k)\n li = list(string[2:])\n if len(set(li)) == 1:\n return k // 2\n else:\n return -1", "def xorcal(k):\n a = {1: 2, 3: 1, 7: 3, 15: 7, 31: 15, 63: 31}\n if k in a:\n return a[k]\n else:\n return -1", "def xorcal(K):\n for i in range(1, 7 * K):\n if i ^ i + 1 == K:\n return i\n return -1", "def xorcal(k):\n if k == 1:\n return 2\n a = bin(k)[2:]\n b = len(a)\n c = 2 ** b\n if c - 1 == k:\n return 2 ** (b - 1) - 1\n return -1", "def xorcal(k):\n if k == 1:\n return 2\n i = 1\n while i < k:\n if k == i ^ i + 1:\n return i\n break\n i += 1\n return -1", "def xorcal(k):\n checkxor = 0\n numxor = 0\n index = 1\n for index in range(1, 129):\n if index ^ k == index + 1:\n checkxor = 1\n numxor = index\n break\n index += 1\n if checkxor == 1:\n return numxor\n else:\n return -1", "import math\n\ndef xorcal(k):\n if k == 1:\n return 2\n temp = math.log(k + 1, 2)\n if temp != int(temp):\n return -1\n else:\n return k // 2", "def xorcal(k):\n i = 1\n while i + 1 <= 100000:\n if i ^ i + 1 == k:\n return i\n i = i + 1\n return -1", "def xorcal(k):\n if k == 0:\n return 0\n if k == 1:\n return 2\n if k == 3:\n return 1\n n = k + 1\n if n & n - 1 == 0:\n return k // 2\n else:\n return -1", "def xorcal(k):\n k2 = int(k / 2)\n if k == 1:\n return 2\n if k % 2 == 0:\n return -1\n if k2 ^ k2 + 1 == k:\n return k2\n else:\n return -1", "def xorcal(k):\n n = 1\n result = False\n while n < 100:\n temp = n ^ n + 1\n if k == temp:\n result = True\n break\n else:\n n += 1\n else:\n return -1\n return n", "def xorcal(k):\n for i in range(1, 101):\n if i ^ i + 1 == k:\n return i\n break\n return -1", "def xorcal(k):\n if k % 2 == 0:\n ans = -1\n elif k == 1:\n ans = 2\n elif k == 3:\n ans = 1\n elif k == 7:\n ans = 3\n elif k == 15:\n ans = 7\n elif k == 31:\n ans = 15\n elif k == 63:\n ans = 31\n else:\n ans = -1\n return ans"], "starter_code": "def xorcal(k):\n", "input_output": {"inputs": ["k = 3", "k = 6"], "outputs": ["1", "-1"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/xor-game2143/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "xorcal", "task_id": "TACO_lite/165", "example": [[[3], [6]], ["1", "-1"]]} +{"requirement": "Given a number N denoting candies. Find how many packets are needed to contain the number if 1st packet can contain 1 candy, 2nd packet can contain 2 candies, 3rd packet can contain 4 candies and so on.\nExample 1:\nInput:\nN = 2\nOutput:\n2\nExplanation:\nPut 1 candy in first packet.\nPut 1 candy in second packet.\nThus two,packets are required.\nExample 2:\nInput:\nN = 8\nOutput:\n4\nExplanation:\nPut 1 candy in first packet.\nPut 2 candies in second packet.\nPut 4 candies in third packet.\nPut 1 candy in fourth packet.\nThus 4 packets are required.\nYour Task:\nYou don't need to read input or print anything.Your Task is to complete the function countPackets() which takes a number N as input parameter and returns the number of packets required to contain it.\nExpected Time Complexity:O(logN)\nExpected Auxillary Space:O(1)\nConstraints:\n1<= N <= 10^{18}", "solutions": ["def countpackets(N):\n c = 0\n while N:\n N //= 2\n c += 1\n return c", "def countpackets(N):\n packets = 1\n candies = 1\n k = 1\n while N - candies > 0:\n candies += 2 * k\n k *= 2\n packets += 1\n return packets", "from math import *\n\ndef countpackets(N):\n return ceil(log(N + 1, 2))"], "starter_code": "def countpackets(N):\n", "input_output": {"inputs": ["N = 2", "N = 8"], "outputs": ["2", "4"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/candy-packetssample-test-case-file-to-be-added1632/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(logN)", "entry_point": "countpackets", "task_id": "TACO_lite/217", "example": [[[2], [8]], ["2", "4"]]} +{"requirement": "Implement a function which behaves like the 'uniq -c' command in UNIX. \n\nIt takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance together with the number of times a duplicate elements occurred in the original array.\n\nExample:\n\n```python\n['a','a','b','b','c','a','b','c'] --> [('a',2),('b',2),('c',1),('a',1),('b',1),('c',1)]\n```", "solutions": ["from itertools import groupby\n\ndef uniq_c(seq):\n return [(k, sum((1 for _ in g))) for (k, g) in groupby(seq)]", "def uniq_c(s):\n lst = []\n c = 1\n for i in range(len(s) - 1):\n if s[i] != s[i + 1]:\n lst.append((s[i], c))\n c = 1\n else:\n c += 1\n if s:\n lst.append((s[-1], c))\n return lst", "from itertools import groupby\n\ndef uniq_c(seq):\n return [(chr, len(list(n))) for (chr, n) in groupby(seq)]", "from itertools import groupby\n\ndef uniq_c(seq):\n ans = []\n for (c, e) in groupby(seq):\n l = list(e)\n ans.append((c, len(l)))\n return ans", "uniq_c = lambda l: (lambda x: [(x[i][1], x[i][0] - x[i - 1][0]) if i > 0 else (x[0][1], x[0][0] + 1) for i in range(len(x))])((lambda t: [(t[i][0], t[i][1]) for i in range(len(t) - 1) if t[i][1] != t[i + 1][1]])(list(enumerate(l))) + [(len(l) - 1, l[-1])]) if l != [] else []", "def uniq_c(seq):\n if not seq:\n return []\n res = []\n cur = seq[0]\n counter = 1\n for c in seq[1:]:\n if c == cur:\n counter += 1\n else:\n res.append((cur, counter))\n cur = c\n counter = 1\n res.append((cur, counter))\n return res", "def uniq_c(seq):\n m = []\n (n, i) = (len(seq), 0)\n while i < n:\n c = seq[i]\n j = i + 1\n while j < n and seq[j] == c:\n j += 1\n m.append((c, j - i))\n i = j\n return m", "def uniq_c(seq):\n (stack, out) = ([], [])\n for x in seq:\n if stack and x == stack[-1]:\n stack.append(x)\n elif stack:\n out.append((stack[-1], len(stack)))\n stack.clear()\n stack.append(x)\n else:\n stack.append(x)\n return stack and out + [(stack[-1], len(stack))] or out", "def uniq_c(seq):\n seq.append('asdadasd')\n arr = []\n count = 1\n for i in range(len(seq) - 1):\n if seq[i] == seq[i + 1]:\n count += 1\n else:\n arr.append((seq[i], count))\n count = 1\n return arr", "def uniq_c(seq):\n new_seq = list()\n count = 0\n for i in range(len(seq)):\n if i == 0:\n new_seq.append(seq[i])\n count += 1\n continue\n if seq[i] == seq[i - 1]:\n count += 1\n else:\n new_seq[-1] = (seq[i - 1], count)\n count = 1\n new_seq.append(seq[i])\n if len(seq) != 0:\n new_seq[-1] = (seq[-1], count)\n return new_seq"], "starter_code": "def uniq_c(seq):\n", "input_output": {"fn_name": "uniq_c", "inputs": [[["a", "a", "b", "b", "c", "a", "b", "c"]], [["a", "a", "a", "b", "b", "b", "c", "c", "c"]], [[null, "a", "a"]], [["foo"]], [[""]], [[]]], "outputs": [[[["a", 2], ["b", 2], ["c", 1], ["a", 1], ["b", 1], ["c", 1]]], [[["a", 3], ["b", 3], ["c", 3]]], [[[null, 1], ["a", 2]]], [[["foo", 1]]], [[["", 1]]], [[]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms"], "name": null, "source": "codewars", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/52250aca906b0c28f80003a1", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "uniq_c", "task_id": "TACO_lite/173", "example": [[[["a", "a", "b", "b", "c", "a", "b", "c"]]], ["[('a', 2), ('b', 2), ('c', 1), ('a', 1), ('b', 1), ('c', 1)]"]]} +{"requirement": "Given a string s, remove all its adjacent duplicate characters recursively. \nNote: For some test cases, the resultant string would be an empty string. In that case, the function should return the empty string only.\nExample 1:\nInput:\nS = \"geeksforgeek\"\nOutput: \"gksforgk\"\nExplanation: \ng(ee)ksforg(ee)k -> gksforgk\nExample 2:\nInput: \nS = \"abccbccba\"\nOutput: \"\"\nExplanation: \nab(cc)b(cc)ba->abbba->a(bbb)a->aa->(aa)->\"\"(empty string)\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function rremove() which takes the string S as input parameter and returns the resultant string.\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(|S|)\nConstraints:\n1<=|S|<=10^{5}", "solutions": ["def rremove(S):\n\n def rec(S):\n ans = ''\n n = len(S)\n i = 0\n while i < n:\n if i < n - 1 and S[i] == S[i + 1]:\n while i < n - 1 and S[i] == S[i + 1]:\n i += 1\n else:\n ans += S[i]\n i += 1\n return ans\n s1 = ''\n while len(S) != len(s1):\n s1 = S\n S = rec(S)\n return S", "def rremove(s):\n n = len(s)\n word = []\n i = 0\n while i < len(s):\n flag = 0\n while i < n - 1 and s[i] == s[i + 1]:\n i += 1\n flag = 1\n if not flag:\n word.append(s[i])\n i += 1\n if len(word) < n:\n return self.rremove(''.join(word))\n return ''.join(word)", "def rremove(S):\n new = [i for i in S]\n st = []\n i = 0\n while i < len(S):\n if st and st[-1] == S[i]:\n while i < len(S) and S[i] == st[-1]:\n i += 1\n st.pop()\n if i < len(S):\n st.append(S[i])\n i += 1\n if new == st:\n return ''.join(new)\n else:\n return self.rremove(''.join(st))", "def rremove(S):\n ans = ''\n duplicate = True\n while duplicate:\n i = 0\n duplicate = False\n while i < len(S):\n count = 1\n while i < len(S) - 1 and S[i] == S[i + 1]:\n count += 1\n i += 1\n duplicate = True\n if count == 1:\n ans += S[i]\n i += 1\n if duplicate:\n S = ans\n ans = ''\n return ans", "def remove(S):\n ans = ''\n n = len(S)\n i = 0\n while i < n:\n if i < n - 1 and S[i] == S[i + 1]:\n while i < n - 1 and S[i] == S[i + 1]:\n i += 1\n else:\n ans += S[i]\n i += 1\n return ans\n\ndef rremove(S):\n temp = ''\n while len(S) != len(temp):\n temp = S\n S = self.remove(S)\n return S", "def rremove(S):\n\n def rems(S):\n i = 0\n ans = []\n while i < len(S):\n if i < len(S) - 1:\n if S[i] == S[i + 1]:\n while i < len(S) - 1 and S[i] == S[i + 1]:\n i = i + 1\n else:\n ans.append(S[i])\n else:\n ans.append(S[i])\n i = i + 1\n return ''.join(ans)\n ans = ''\n k = rems(S)\n while len(ans) != len(k):\n ans = k\n k = rems(ans)\n return k", "def rremove(s):\n prev = ''\n temp = ''\n if len(s) < 2:\n return s\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n prev = s[i]\n elif s[i] == prev:\n prev = ''\n else:\n temp += s[i]\n if s[-1] != prev:\n temp += s[-1]\n if len(s) == len(temp):\n return temp\n else:\n return self.rremove(temp)", "def rremove(S):\n new = []\n i = 0\n n = len(S)\n while i < len(S):\n temp = 0\n while i < n - 1 and S[i] == S[i + 1]:\n temp = 1\n i += 1\n if temp == 0:\n new.append(S[i])\n i += 1\n if len(new) < n:\n return self.rremove(new)\n return ''.join(new)", "def rremove(S):\n sn = len(S)\n is_continue = True\n while is_continue:\n is_continue = False\n buffer = []\n i = 0\n while i < sn:\n j = i + 1\n while j < sn and S[j] == S[i]:\n j += 1\n if j == i + 1:\n buffer.append(S[i])\n i += 1\n else:\n is_continue = True\n i = j\n S = ''.join(buffer)\n sn = len(S)\n return S", "def rremove(s):\n res = ''\n i = 0\n while i < len(s):\n if i + 1 < len(s) and s[i] == s[i + 1]:\n i += 1\n while i < len(s) and s[i] == s[i - 1]:\n i += 1\n else:\n res += s[i]\n i += 1\n return res if len(res) == len(s) else self.rremove(res)", "def rremove(S):\n n = len(S)\n flag = True\n while flag:\n flag = False\n arr = []\n i = 0\n while i < n:\n j = i + 1\n while j < n and S[j] == S[i]:\n j += 1\n if j == i + 1:\n arr.append(S[i])\n i += 1\n else:\n flag = True\n i = j\n S = ''.join(arr)\n n = len(S)\n return S", "def rremove(S):\n q = [S]\n newS = ''\n while len(q):\n root = q.pop(0)\n flg = True\n newS = ''\n i = 0\n while i < len(root):\n j = i + 1\n fl = True\n while j < len(root) and root[i] == root[j]:\n j += 1\n fl = False\n flg = False\n if fl:\n newS += root[i]\n i = j\n q.append(newS)\n if flg:\n break\n return newS", "def rremove(S):\n s_list = list(S)\n ns = self._remove(s_list)\n return ''.join(ns)\n\ndef _remove(s_lst):\n ns = []\n prv = None\n lprv = None\n for c in s_lst:\n if c != prv:\n ns.append(c)\n elif lprv != c:\n ns.pop()\n lprv = prv\n prv = c\n if len(ns) == len(s_lst):\n return ns\n return self._remove(ns)", "def rremove(S):\n if not S:\n return S\n global_dups = 0\n final_string = ''\n i = 0\n while i < len(S):\n duplicates = 0\n j = i + 1\n while j < len(S) and S[j] == S[i]:\n duplicates = 1\n global_dups += 1\n j += 1\n i = j - 1\n if not duplicates:\n final_string += S[i]\n i += 1\n return Solution().rremove(final_string) if global_dups else final_string", "def rremove(s):\n\n def remove(s, old):\n if s == '':\n return s\n elif s == old:\n return s\n old = s\n arr = list(s)\n prev = 0\n for i in range(1, len(s)):\n if arr[i] == arr[i - 1]:\n prev = 1\n arr[i - 1] = ''\n elif prev == 1:\n arr[i - 1] = ''\n prev = 0\n if prev == 1:\n arr[i] = ''\n s = ''.join(arr)\n return remove(s, old)\n return remove(s, '')", "def rremove(S):\n\n def remove(s):\n if s == '':\n return ''\n if len(s) == 1:\n return s\n if s[0] == s[1]:\n new_s = ''\n else:\n new_s = s[0]\n i = 1\n while i < len(s) - 1:\n if s[i] != s[i - 1] and s[i] != s[i + 1]:\n new_s += s[i]\n i += 1\n else:\n if s[-1] != s[-2]:\n new_s += s[-1]\n if s == new_s:\n return s\n else:\n return remove(new_s)\n return remove(S)", "def rremove(S):\n if len(S) < 2:\n return S\n i = 0\n j = 1\n is_duplicate = False\n modified = False\n non_duplicates = []\n while j < len(S):\n if S[j] == S[i]:\n j += 1\n is_duplicate = True\n elif is_duplicate:\n i = j\n j += 1\n is_duplicate = False\n modified = True\n else:\n non_duplicates.append(S[i])\n i = j\n j += 1\n if not is_duplicate:\n non_duplicates.append(S[i])\n updated_str = ''.join(non_duplicates)\n if modified:\n return self.rremove(updated_str)\n return updated_str", "def rremove(S):\n if len(S) == 0:\n return ''\n length = len(S)\n dupl_nums = 1\n store = []\n i = 0\n while i < length - 1:\n if S[i] == S[i + 1]:\n start_dupl = i\n dupl_nums = 2\n k = i + 2\n while k < len(S) and S[k] == S[i]:\n dupl_nums += 1\n k += 1\n if len(store) == 0:\n store.append(S[0:start_dupl])\n else:\n store.append(S[next_start:start_dupl])\n next_start = i + dupl_nums\n i += dupl_nums\n else:\n i += 1\n if store:\n if next_start < length:\n store.append(S[next_start:])\n new_string = ''.join(store)\n return self.rremove(new_string)\n else:\n return S\n return S", "def rremove(s):\n a = ''\n b = ''\n if len(s) < 2:\n return s\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n a = s[i]\n elif s[i] == a:\n a = ''\n else:\n b += s[i]\n if s[-1] != a:\n b += s[-1]\n if len(s) == len(b):\n return b\n else:\n return self.rremove(b)", "def rremove(s):\n sm = len(s)\n is_con = True\n while is_con:\n is_con = False\n buf = []\n i = 0\n while i < sm:\n j = i + 1\n while j < sm and s[j] == s[i]:\n j += 1\n if j == i + 1:\n buf.append(s[i])\n i += 1\n else:\n is_con = True\n i = j\n s = ''.join(buf)\n sm = len(s)\n return s", "def rremove(S):\n l = len(S)\n a = []\n d = False\n for i in range(len(S)):\n if i == 0:\n if S[i] != S[i + 1]:\n a.append(S[i])\n elif i < len(S) - 1:\n if S[i] != S[i + 1] and S[i] != S[i - 1]:\n a.append(S[i])\n elif S[-1] != S[-2]:\n a.append(S[-1])\n k = ''.join(a)\n for i in range(len(k) - 1):\n if k[i] == k[i + 1]:\n d = True\n break\n if d:\n return self.rremove(k)\n else:\n return k", "def rremove(S):\n sn = len(S)\n a = True\n while a:\n a = False\n b = []\n i = 0\n while i < sn:\n j = i + 1\n while j < sn and S[j] == S[i]:\n j += 1\n if j == i + 1:\n b.append(S[i])\n i += 1\n else:\n a = True\n i = j\n S = ''.join(b)\n sn = len(S)\n return S", "def rremove(s):\n n = len(s)\n f = True\n while f:\n f = False\n l = []\n i = 0\n while i < n:\n j = i + 1\n while j < n and s[j] == s[i]:\n j = j + 1\n if j == i + 1:\n l.append(s[i])\n i = i + 1\n else:\n f = True\n i = j\n s = ''.join(l)\n n = len(s)\n return s", "import re\n\ndef rremove(S):\n n = len(S)\n k = True\n while k:\n k = False\n b = []\n i = 0\n while i < n:\n j = i + 1\n while j < n and S[j] == S[i]:\n j += 1\n if j == i + 1:\n b.append(S[i])\n i += 1\n else:\n k = True\n i = j\n S = ''.join(b)\n n = len(S)\n return S", "def rremove(S):\n ans = ''\n if len(S) <= 1:\n return S\n for i in range(0, len(S)):\n if i == 0:\n if S[i] != S[i + 1]:\n ans = ans + S[i]\n elif i == len(S) - 1:\n if S[i] != S[i - 1]:\n ans = ans + S[i]\n elif S[i] != S[i - 1] and S[i] != S[i + 1]:\n ans = ans + S[i]\n if len(S) != len(ans):\n return self.rremove(ans)\n return ans", "def rremove(s):\n a = []\n i = 0\n n = len(s)\n while i < len(s):\n temp = 0\n while i < n - 1 and s[i] == s[i + 1]:\n temp = 1\n i += 1\n if temp == 0:\n a.append(s[i])\n i += 1\n if len(a) < n:\n return self.rremove(a)\n return ''.join(a)", "def rremove(S):\n l = len(S)\n con = True\n while con:\n con = False\n buf = []\n i = 0\n while i < l:\n j = i + 1\n while j < l and S[j] == S[i]:\n j += 1\n if j == i + 1:\n buf.append(S[i])\n i += 1\n else:\n con = True\n i = j\n S = ''.join(buf)\n l = len(S)\n return S", "def rremove(s):\n s1 = ''\n while len(s1) != len(s):\n s1 = s\n s = self.fun(s)\n return s\n\ndef fun(s):\n ans = ''\n n = len(s)\n i = 0\n while i < n:\n if i < n - 1 and s[i] == s[i + 1]:\n while i < n - 1 and s[i] == s[i + 1]:\n i += 1\n else:\n ans += s[i]\n i += 1\n return ans", "def rremove(s):\n p = t = ''\n if len(s) < 2:\n return s\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n p = s[i]\n elif s[i] == p:\n p = ''\n else:\n t += s[i]\n if s[-1] != p:\n t += s[-1]\n if len(s) == len(t):\n return t\n else:\n return self.rremove(t)", "def rremove(S):\n newS = ''\n if len(S) == 0:\n return ''\n if len(S) == 1:\n return S\n c = '%'\n S += '&'\n for i in range(len(S) - 1):\n if S[i] == S[i + 1]:\n c = S[i]\n newS += '#'\n elif S[i] == c:\n newS += '#'\n c = '%'\n else:\n newS += S[i]\n newS = newS.replace('#', '')\n S = S[:-1]\n if len(newS) == len(S):\n return S\n return self.rremove(newS)", "def rremove(S):\n\n def rem(s):\n l = [s[0]]\n i = 1\n n = len(s)\n while i < n:\n if s[i] != s[i - 1]:\n l += [s[i]]\n else:\n p = s[i]\n j = i + 1\n if j < n:\n while j < n:\n if s[j] != p:\n l.pop()\n l += [s[j]]\n i = j\n break\n j += 1\n else:\n l.pop()\n i += 1\n return ''.join(l)\n b = S[:]\n while True:\n f = 1\n if b == '' or len(b) == 1:\n return b\n if len(b) == 2:\n if b[0] == b[1]:\n return ''\n else:\n return b\n for i in range(1, len(b)):\n if b[i] == b[i - 1]:\n f = 0\n break\n if f == 0:\n b = rem(b)\n else:\n return b"], "starter_code": "def rremove (S):\n", "input_output": {"inputs": ["S = \"geeksforgeek\"", "S = \"abccbccba\""], "outputs": ["\"gksforgk\"", "\"\""]}, "difficulty": "MEDIUM", "raw_tags": ["Recursion", "Strings", "Algorithms", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/recursively-remove-all-adjacent-duplicates0744/1", "Expected Auxiliary Space": "O(|S|)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "rremove", "task_id": "TACO_lite/206", "example": [[["geeksforgeek"], ["abccbccba"]], ["gksforgk", ""]]} +{"requirement": "Given two non-negative integers low and high. Return the count of odd numbers between low and high\u00a0(inclusive).\n\u00a0\nExample 1:\nInput: low = 3, high = 7\nOutput: 3\nExplanation: The odd numbers between 3 and 7 are [3,5,7].\nExample 2:\nInput: low = 8, high = 10\nOutput: 1\nExplanation: The odd numbers between 8 and 10 are [9].\n\u00a0\nConstraints:\n\n0 <= low <= high\u00a0<= 10^9", "solutions": ["def countodds(low: int, high: int) -> int:\n if low % 2 != 0:\n low -= 1\n if high % 2 != 0:\n high += 1\n return (high - low) // 2", "def countodds(low: int, high: int) -> int:\n return high - high // 2 - (low - low // 2) + low % 2", "def countodds(low: int, high: int) -> int:\n return (high + 1 >> 1) - (low >> 1)", "def countodds(low: int, high: int) -> int:\n c = 0\n if low < 0 or high > 10 ** 9:\n return\n elif low % 2 != 0 and high % 2 != 0:\n return int((high - low) / 2) + 1\n elif low % 2 == 0 and high % 2 != 0 or (low % 2 != 0 and high % 2 == 0):\n return int((high - low) / 2) + 1\n else:\n return int((high - low) / 2)", "def countodds(low: int, high: int) -> int:\n (odd_lowerbound, odd_upperbound) = (-1, -1)\n if low % 2 == 1:\n odd_lowerbound = low\n else:\n odd_lowerbound = low + 1\n if high % 2 == 1:\n odd_upperbound = high\n else:\n odd_upperbound = high - 1\n return (odd_upperbound - odd_lowerbound) // 2 + 1", "def countodds(low: int, high: int) -> int:\n return (high - low + 1) // 2 + (high % 2 and low % 2)", "def countodds(lo, hi):\n return (hi + 1) // 2 - lo // 2"], "starter_code": "def countodds(low: int, high: int) -> int:\n", "input_output": {"fn_name": "countOdds", "inputs": [[3, 7]], "outputs": [3]}, "difficulty": "EASY", "raw_tags": ["Math"], "name": null, "source": "leetcode", "tags": ["Mathematics"], "skill_types": [], "url": "https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "countodds", "task_id": "TACO_lite/84", "example": [[[3, 7], [8, 10]], ["3", "1"]]} +{"requirement": "Given Two integers L and R find the total number of distinct pairs (p,q) between L and R ( both inclusive ) satisfying the given relationship. p! * q!=k^2 (a perfect square) where p,q,k is any integer and '!' denotes factorial.\nExample 1:\nInput: L = 0, R = 1\nOutput: 1\nExplanation: 1 is the only perfect square\nbetween 0 and 1; \nExample 2:\nInput: L = 9, R = 25\nOutput: 3\nExplanation: 9, 16 and 25 are the perfect \nsquares between 9 and 25. \nYour Task: \nYou don't need to read input or print anything. Complete the function countPerfectSquares() which takes L and R as an input parameter and returns the total number of perfect squares.\nExpected Time Complexity: O(sqrt(N))\nExpected Auxiliary Space: O(1)\nConstraints:\n0<= L <= R <=10^{18}", "solutions": ["import math\n\ndef isPerfectSquare(x):\n if x >= 0:\n sr = math.floor(math.sqrt(x))\n return sr * sr == x\n return False\n\ndef countperfectsquares(L, R):\n if self.isPerfectSquare(L):\n return math.floor(math.sqrt(R)) - math.floor(math.sqrt(L)) + 1\n else:\n return math.floor(math.sqrt(R)) - math.floor(math.sqrt(L))"], "starter_code": "def countperfectsquares (L, R):\n", "input_output": {"inputs": ["L = 0, R = 1", "L = 9, R = 25"], "outputs": ["1", "3"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/factorial-pairs5916/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(sqrt(N))", "entry_point": "countperfectsquares", "task_id": "TACO_lite/236", "example": [[[0, 1], [9, 25]], [null, null]]} +{"requirement": "How many days are we represented in a foreign country?\n\nMy colleagues make business trips to a foreign country. We must find the number of days our company is represented in a country. Every day that one or more colleagues are present in the country is a day that the company is represented. A single day cannot count for more than one day.\n\nWrite a function that recieves a list of pairs and returns the number of days that the company is represented in the foreign country. The first number of the pair is the number of the day of arrival and the second number of the pair is the day of departure of someone who travels, i.e. 1 january is number 1 and 31 of december is 365.\n\nExample:\n```python\ndays_represented([[10,17],[200,207]])\n```\n\nReturns 16 because there are two trips of 8 days, which add up to 16.\n\nHappy coding and rank this kata if you wish ;-)", "solutions": ["def days_represented(a):\n return len({i for (x, y) in a for i in range(x, y + 1)})", "def days_represented(trips):\n L = []\n for i in trips:\n for j in range(i[0], i[1] + 1):\n L.append(j)\n a = set(L)\n return len(a)", "def days_represented(trips):\n return len({i for (start, stop) in trips for i in range(start, stop + 1)})", "def days_represented(trips):\n arr = [0] * 365\n for (a, b) in trips:\n arr[a:b + 1] = [1] * (b - a + 1)\n return sum(arr)", "def days_represented(trips):\n total = 0\n visited = []\n for i in range(len(trips)):\n trip = trips[i]\n arrival = trip[1]\n departure = trip[0]\n for j in range(departure, arrival + 1):\n if j not in visited:\n visited.append(j)\n else:\n continue\n return len(visited)", "def days_represented(trips):\n accumulator = set()\n for (a, b) in trips:\n accumulator |= set(range(a, b + 1))\n return len(accumulator)", "def days_represented(trips):\n new = []\n for days in trips:\n for day in range(days[0], days[1] + 1):\n new.append(day)\n p = set(new)\n return len(p)", "from itertools import chain\n\ndef days_represented(trips):\n return len(set(chain(*(range(a, b + 1) for (a, b) in trips))))"], "starter_code": "def days_represented(trips):\n", "input_output": {"fn_name": "days_represented", "inputs": [[[[10, 15], [25, 35]]], [[[2, 8], [220, 229], [10, 16]]]], "outputs": [[17], [24]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Lists"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/58e93b4706db4d24ee000096", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "days_represented", "task_id": "TACO_lite/237", "example": [[[[[10, 17], [200, 207]]]], ["16"]]} +{"requirement": "A sorted(in ascending order) array A[ ] with distinct elements is rotated at some unknown point, the task is to find the minimum element in it.\nExample 1\nInput:\nN = 5\narr[] = {4 ,5 ,1 ,2 ,3}\nOutput: 1\nExplanation: 1 is the minimum element inthe array.\nExample 2\nInput:\nN = 7\narr[] = {10, 20, 30, 40, 50, 5, 7}\nOutput: 5\nExplanation: Here 5 is the minimum element.\n \nYour Task:\nComplete the function findMin() which takes an array arr[] and n, size of the array as input parameters, and returns the minimum element of the array.\nExpected Time Complexity: O(log N).\nExpected Auxiliary Space: O(log N).\nConstraints:\n1 \u2264 N \u2264 100000\n1 \u2264 A[i] \u2264 1000000", "solutions": ["def findmin(arr, n):\n return min(arr)", "import sys\n\ndef findmin(arr, n):\n mini = sys.maxsize\n for i in arr:\n if i < mini:\n mini = i\n return mini", "def findmin(arr, n):\n smallest_number = arr[0]\n for number in range(n):\n if arr[number] < smallest_number:\n smallest_number = arr[number]\n return smallest_number", "def findmin(arr, n):\n (start, end) = (0, n - 1)\n while start < end:\n mid = start + (end - start) // 2\n if arr[mid] > arr[end]:\n start = mid + 1\n else:\n end = mid\n return arr[start]", "def findmin(arr, n):\n i = 0\n j = n - 1\n if arr[0] < arr[j]:\n return arr[0]\n while i <= j:\n mid = (i + j) // 2\n if arr[mid] < arr[mid - 1]:\n return arr[mid]\n if arr[mid] > arr[0]:\n i = mid + 1\n else:\n j = mid", "def findmin(A, n):\n min = A[0]\n l = 0\n h = n - 1\n while l <= h:\n mid = (l + h) // 2\n if A[mid] < min:\n min = A[mid]\n elif A[mid] >= A[l] and A[mid] >= A[h]:\n l = mid + 1\n else:\n h = mid - 1\n return min", "def findmin(arr, n):\n\n def findminUtil(arr, start, end, minimum):\n if end == start:\n return min(minimum, arr[start])\n elif end - start <= 1:\n return min(minimum, arr[start], arr[end])\n mid = (start + end) // 2\n if arr[mid] > arr[start]:\n minimum = min(minimum, findminUtil(arr, mid + 1, end, minimum), arr[start])\n else:\n minimum = min(minimum, findminUtil(arr, start, mid, minimum), arr[mid + 1])\n return minimum\n return findminUtil(arr, 0, n - 1, float('inf'))", "def findmin(arr, n):\n (lo, hi) = (0, n - 1)\n while lo < hi:\n mid = (lo + hi) // 2\n if arr[mid] < arr[hi]:\n hi = mid\n else:\n lo = mid + 1\n return arr[lo]", "def findmin(arr, n):\n (l, r) = (0, n - 1)\n while l <= r:\n mid = l + (r - l) // 2\n if mid == 0 or arr[mid - 1] > arr[mid]:\n return arr[mid]\n elif arr[mid] < arr[l]:\n r = mid - 1\n elif arr[mid] > arr[r]:\n l = mid + 1\n else:\n return arr[l]\n return -1", "def findmin(arr, n):\n start = 0\n end = len(arr) - 1\n while start < end:\n middle = start + (end - start) // 2\n if arr[middle] > arr[end]:\n start = middle + 1\n elif arr[middle] < arr[end]:\n end = middle\n else:\n end -= 1\n return arr[start]", "def findmin(arr, n):\n arr.sort()\n return arr[0]", "def findmin(arr, n):\n left = 0\n right = n - 1\n while left <= right:\n mid = (left + right) // 2\n previous = (mid - 1) % n\n next1 = (mid + 1) % n\n if arr[mid] <= arr[previous] and arr[mid] <= arr[next1]:\n return arr[mid]\n if arr[mid] <= arr[right]:\n right = mid - 1\n elif arr[left] <= arr[mid]:\n left = mid + 1", "def findmin(arr, n):\n res = arr[0]\n l = 0\n h = len(arr) - 1\n while l <= h:\n if arr[l] < arr[h]:\n res = min(res, arr[l])\n break\n mid = (l + h) // 2\n res = min(res, arr[mid])\n if arr[mid] >= arr[l]:\n l = mid + 1\n else:\n h = mid - 1\n return res", "import heapq\n\ndef findmin(arr, n):\n (left, right) = (0, n - 1)\n while left <= right:\n mid = (left + right) // 2\n prev = (mid - 1) % n\n next = (mid + 1) % n\n if arr[mid] <= arr[prev] and arr[mid] <= arr[next]:\n return arr[mid]\n elif arr[mid] <= arr[right]:\n right = mid - 1\n elif arr[mid] >= arr[left]:\n left = mid + 1", "import heapq\n\ndef findmin(arr, n):\n return heapq.nsmallest(1, arr)[0]", "def findmin(nums, n):\n if len(nums) is 1:\n return nums[0]\n leftSmaller = True if nums[0] < nums[-1] else False\n if leftSmaller:\n return nums[0]\n if len(nums) is 2:\n return min(nums)\n start = 0\n end = len(nums) - 1\n while start <= end:\n mid = (start + end) // 2\n if nums[mid] < nums[mid - 1]:\n return nums[mid]\n elif nums[mid] < nums[end]:\n end = mid - 1\n else:\n start = mid + 1\n return 0", "def findmin(arr, n):\n first = 0\n end = n - 1\n if arr[first] < arr[end]:\n return arr[first]\n while first < end:\n mid = (first + end) // 2\n if arr[mid] > arr[mid + 1]:\n return arr[mid + 1]\n elif arr[mid] < arr[first]:\n end = mid\n else:\n first = mid", "def findmin(arr, n):\n left = 0\n right = n - 1\n if arr[left] < arr[right]:\n return arr[left]\n while left < right:\n mid = (left + right) // 2\n if arr[mid] > arr[mid + 1]:\n return arr[mid + 1]\n elif arr[mid] < arr[left]:\n right = mid\n else:\n left = mid", "def findmin(arr, n):\n l = 0\n h = n - 1\n if arr[l] <= arr[h]:\n return arr[l]\n while l <= h:\n m = (l + h) // 2\n if arr[m] < arr[m - 1]:\n return arr[m]\n if arr[m] > arr[h]:\n l = m + 1\n else:\n h = m - 1", "def findmin(nums, n):\n (left, right) = (0, n - 1)\n if n <= 1 or nums[left] < nums[right]:\n return nums[left]\n while left < right:\n mid = (left + right) // 2\n (prev, curr, next) = (nums[mid - 1], nums[mid], nums[mid + 1])\n if curr > next:\n return next\n if prev > curr:\n return curr\n if nums[0] < curr:\n left = mid + 1\n else:\n right = mid - 1", "def findmin(arr, n):\n min = arr[0]\n for i in range(n):\n if arr[i] < min:\n min = arr[i]\n return min", "def findmin(arr, n):\n min1 = 100000\n i = 0\n j = n - 1\n while i <= j:\n if arr[i] < arr[j]:\n min1 = min(arr[i], min1)\n break\n mid = int(i + (j - i) / 2)\n if arr[i] <= arr[mid]:\n min1 = min(min1, arr[i])\n i = mid + 1\n else:\n min1 = min(min1, arr[mid])\n j = mid - 1\n return min1", "def findmin(arr, n):\n l = 0\n r = n - 1\n while l <= r:\n mid = (l + r) // 2\n if arr[l] <= arr[mid] and arr[mid] <= arr[r]:\n return arr[l]\n elif arr[r] >= arr[mid] and arr[mid] >= arr[l]:\n return arr[r]\n elif r - l == 1:\n return min(arr[r], arr[l])\n elif arr[l] < arr[mid]:\n l = mid\n elif arr[mid] < arr[r]:\n r = mid", "def findmin(arr, n):\n m = arr[-1]\n for i in range(n - 2, -1, -1):\n if arr[i] < m:\n m = arr[i]\n return m", "def findmin(arr, n):\n v = sorted(arr)\n return min(v)", "def findmin(arr, n):\n (low, high) = (0, n)\n while low < high:\n mid = (low + high) // 2\n if arr[0] <= arr[mid]:\n low = mid + 1\n else:\n high = mid\n if low == n:\n low = 0\n return arr[low]", "def findmin(arr, n):\n arr.sort()\n res = min(arr)\n return res", "import sys\nintmax = sys.maxsize\n\ndef findmin(arr, n):\n l = 0\n r = n - 1\n while l <= r:\n mid = (l + r) // 2\n if arr[l] >= arr[mid] and arr[mid] >= arr[r]:\n return arr[r]\n if mid == 0 or arr[mid - 1] > arr[mid]:\n return arr[mid]\n if arr[mid] < arr[l]:\n r = mid - 1\n elif arr[mid] > arr[r]:\n l = mid + 1\n else:\n return arr[l]\n return -1", "import sys\nintmax = sys.maxsize\n\ndef findmin(arr, n):\n t = intmax\n p = -1\n for i in range(n):\n if arr[i] <= t:\n t = arr[i]\n p = i\n return t", "import sys\n\ndef findmin(arr, n):\n low = 0\n high = n - 1\n minVal = sys.maxsize\n while low <= high:\n mid = (low + high) // 2\n if arr[low] <= arr[high]:\n minVal = min(minVal, arr[low])\n break\n elif arr[low] <= arr[mid]:\n minVal = min(minVal, arr[low])\n low = mid + 1\n else:\n minVal = min(minVal, arr[mid])\n high = mid - 1\n return minVal", "def findmin(nums, n):\n low = 0\n high = n - 1\n while low < high:\n mid = low + high >> 1\n if nums[mid] > nums[high]:\n low = mid + 1\n else:\n high = mid\n return nums[low]", "def findmin(arr, n):\n low = 0\n high = n - 1\n while low <= high:\n mid = (high - low) // 2 + low\n prev = (mid + n - 1) % n\n next = (mid + 1) % n\n if arr[mid] <= arr[prev] and arr[mid] <= arr[high]:\n return arr[mid]\n elif arr[mid] <= arr[high]:\n high = mid - 1\n else:\n low = mid + 1", "def findmin(arr, n):\n (left, right) = (0, n - 1)\n ans = arr[left]\n while left <= right:\n if arr[left] < arr[right]:\n return min(ans, arr[left])\n break\n mid = (left + right) // 2\n ans = min(ans, arr[mid])\n if arr[left] <= arr[mid]:\n left = mid + 1\n else:\n right = mid - 1\n return ans", "def findmin(nums, n):\n high = len(nums) - 1\n low = 0\n ans = 999999\n while high >= low:\n mid = (low + high) // 2\n if nums[mid] < ans:\n ans = nums[mid]\n if nums[low] < nums[mid] and nums[mid] < nums[high]:\n if nums[low] < nums[high]:\n high = mid - 1\n else:\n low = mid + 1\n elif nums[mid] >= nums[low]:\n low = mid + 1\n else:\n high = mid - 1\n return ans", "def findmin(arr, n):\n for i in range(1, len(arr)):\n if arr[i] < arr[i - 1]:\n return arr[i]\n return arr[0]", "def findmin(arr, n):\n first = 0\n last = len(arr) - 1\n while first < last:\n mid = (first + last) // 2\n if arr[mid] < arr[last]:\n last = mid\n else:\n first = mid + 1\n return arr[first]", "import math\n\ndef findmin(a, n):\n beg = 0\n end = n - 1\n min_ele = float('inf')\n while beg < end:\n min_ele = min(min_ele, a[beg])\n mid = math.ceil((beg + end) / 2.0)\n if a[beg] < a[mid]:\n beg = mid + 1\n else:\n min_ele = min(min_ele, a[mid])\n end = mid - 1\n min_ele = min(min_ele, a[end])\n return min_ele", "def findmin(arr, n):\n (low, high) = (0, n - 1)\n mini = float('inf')\n while low <= high:\n if arr[low] <= arr[high]:\n mini = min(arr[low], mini)\n break\n mid = (low + high) // 2\n if arr[low] <= arr[mid]:\n mini = min(mini, arr[low])\n low = mid + 1\n else:\n mini = min(mini, arr[mid])\n high = mid - 1\n return mini", "def findmin(arr, n):\n left = 0\n right = n - 1\n minVal = float('inf')\n while left <= right:\n if arr[left] <= arr[right]:\n minVal = min(minVal, arr[left])\n break\n mid = (left + right) // 2\n if arr[left] <= arr[mid] and arr[left] >= arr[right]:\n left = mid + 1\n elif arr[mid] <= arr[left] and arr[mid] <= arr[right]:\n minVal = min(minVal, arr[mid])\n right = mid - 1\n else:\n right = mid\n return minVal", "def findmin(nums, n):\n n = len(nums)\n (s, e) = (0, n - 1)\n while s < e:\n mid = s + e >> 1\n if nums[s] <= nums[e]:\n return nums[s]\n if nums[mid] >= nums[s]:\n s = mid + 1\n else:\n e = mid\n return nums[s]", "import numpy as np\n\ndef findmin(arr, n):\n arr = np.array(arr)\n return np.min(arr)", "def findmin(arr, n):\n l = 0\n r = len(arr) - 1\n while l < r:\n m = (l + r) // 2\n if arr[m] > arr[r]:\n l = m + 1\n else:\n r = m\n return arr[l]"], "starter_code": "def findmin(arr, n):\n", "input_output": {"inputs": ["N = 5\r\narr[] = {4 ,5 ,1 ,2 ,3}", "N = 7\r\narr[] = {10, 20, 30, 40, 50, 5, 7}"], "outputs": ["1", "5"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Searching"], "name": null, "source": "geeksforgeeks", "tags": ["Complete search"], "skill_types": ["Complete search"], "url": "https://practice.geeksforgeeks.org/problems/minimum-element-in-a-sorted-and-rotated-array3611/1", "Expected Auxiliary Space": "O(log N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log N).", "entry_point": "findmin", "task_id": "TACO_lite/209", "example": [[[5, [4, 5, 1, 2, 3]], [7, [10, 20, 30, 40, 50, 5, 7]]], [null, null]]} +{"requirement": "Create a function\n\n```python\nhas_two_cube_sums(n)\n```\n\nwhich checks if a given number `n` can be written as the sum of two cubes in two different ways: `n = a\u00b3+b\u00b3 = c\u00b3+d\u00b3`.\nAll the numbers `a`, `b`, `c` and `d` should be different and greater than `0`.\n\nE.g. 1729 = 9\u00b3+10\u00b3 = 1\u00b3+12\u00b3.\n\n```python\nhas_two_cube_sums(1729); // true\nhas_two_cube_sums(42); // false\n```", "solutions": ["def has_two_cube_sums(n):\n cubic_list = [i ** 3 for i in range(1, int(n ** (1.0 / 3.0)) + 1)]\n return sum([n != 2 * c and n - c in cubic_list for c in cubic_list]) > 3", "def has_two_cube_sums(n):\n x = 0\n for a in range(int(n ** 0.35)):\n for b in range(a, int(n ** 0.35)):\n if a ** 3 + b ** 3 == n:\n x += 1\n if x > 1:\n return True\n return False", "from itertools import combinations\ns = {a ** 3 + b ** 3 for (a, b) in combinations(range(1, 1000), 2)}\ns.discard(19 ** 3 + 34 ** 3)\n\ndef has_two_cube_sums(n):\n return n in s", "def has_two_cube_sums(n):\n if n == 1:\n return False\n high = int(n ** (1 / 3.0))\n low = int((n / 2) ** (1 / 3.0))\n return sum((abs(y - round(y)) < 1e-08 for y in [(n - x ** 3) ** (1 / 3.0) for x in range(low, high + 1)])) >= 2", "def has_two_cube_sums(n):\n return len([[y, z] for y in range(1, int(n ** (1 / 3)) + 1) for z in [x for x in range(1, int(n ** (1 / 3)) + 1)] if y != z and y ** 3 + z ** 3 == n]) >= 4", "has_two_cube_sums = lambda n: sum([i[0] ** 3 + i[1] ** 3 == n for i in __import__('itertools').permutations(range(1, int(n ** (1.0 / 3.0)) + 1), 2)]) >= 4"], "starter_code": "def has_two_cube_sums(n):\n", "input_output": {"fn_name": "has_two_cube_sums", "inputs": [[1], [1729], [42], [4103], [4102], [4104], [4105], [4106], [0], [46163]], "outputs": [[false], [true], [false], [false], [false], [true], [false], [false], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/55fd4919ce2a1d7c0d0000f3", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "has_two_cube_sums", "task_id": "TACO_lite/239", "example": [[], []]} +{"requirement": "Given a rectangle of size L x B. Find the minimum number of squares required to fill the rectangle such that no two square overlaps.\nExample 1:\nInput: L = 4, B = 5\nOutput: 5\nExplaination: One 4*4 square and four 1*1 \nsquares are required.\nExample 2:\nInput: L = 2, B = 4\nOutput: 2\nExplaintion: Two 2*2 squares are enough to \nfill the rectangle.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function minSquares() which takes L and B as input parameters and returns minimum number of squares required to fill the rectangle. Return the answer modulo 10^{9} + 7.\nExpected Time Complexity: O(log(max(L, B)))\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 L, B \u2264 10^{10}", "solutions": ["def minsquares(L, B):\n p = 1000000007\n if L == 1:\n return B % p\n if B == 1:\n return L % p\n ans = 0\n while L > 0 and B > 0:\n if L > B:\n ans = (ans + L // B) % p\n L = L % B\n else:\n ans = (ans + B // L) % p\n B = B % L\n return ans % p", "def minsquares(l, b):\n p = 1000000007\n if l == 1:\n return b % p\n if b == 1:\n return l % p\n ans = 0\n while l > 0 and b > 0:\n if l > b:\n ans = (ans + l // b) % p\n l = l % b\n else:\n ans = (ans + b // l) % p\n b = b % l\n return ans % p", "import math\n\ndef minsquares(L, B):\n if L > B:\n (L, B) = (B, L)\n res = 0\n while L:\n res += B // L\n B %= L\n if L > B:\n (B, L) = (L, B)\n return res % 1000000007", "def minsquares(L, B):\n cnt = 0\n while True:\n if L == B or L <= 0 or B <= 0:\n if L == 0 or B == 0:\n break\n else:\n cnt += 1\n break\n elif L < B:\n temp = B // L\n cnt += temp\n B -= L * temp\n else:\n temp = L // B\n cnt += temp\n L -= B * temp\n return cnt % (10 ** 9 + 7)", "def minsquares(L, B):\n if L > B:\n L = L + B\n B = L - B\n L = L - B\n if B % L == 0:\n return B // L % 1000000007\n else:\n r = B % L\n sum = B // L\n while r != 0:\n sum += L // r\n B = L\n L = r\n r = B % L\n return sum % 1000000007", "def minsquares(L, B):\n count = 0\n while L >= 0 or B >= 0:\n if L == 0 or B == 0:\n return count % (10 ** 9 + 7)\n if L == 1:\n count += B\n return count % (10 ** 9 + 7)\n if B == 1:\n count += L\n return count % (10 ** 9 + 7)\n if L > B and B != 0:\n x = L // B\n L -= B * x\n count += x\n if B >= L and L != 0:\n y = B // L\n B -= L * y\n count += y", "def solve(L, B):\n mod = 10 ** 9 + 7\n if L == B:\n return 1\n if B == 0 or L == 0:\n return 0\n if L == 1 or B == 1:\n return max(L, B)\n if L > B:\n return self.solve(B, L)\n return B // L + self.solve(L, B % L) % mod\n\ndef minsquares(L, B):\n mod = 10 ** 9 + 7\n return int(self.solve(L, B)) % mod", "def minsquares(l, b):\n mod = pow(10, 9) + 7\n\n def solve(l, b):\n if l == 0 or b == 0:\n return 0\n if l >= b:\n return l // b + solve(l % b, b)\n if l < b:\n return b // l + solve(l, b % l)\n return solve(l, b) % mod"], "starter_code": "def minsquares(L, B):\n", "input_output": {"inputs": ["L = 4, B = 5", "L = 2, B = 4"], "outputs": ["5", "2"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/squares-in-reactangle3340/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(max(L, B)))", "entry_point": "minsquares", "task_id": "TACO_lite/235", "example": [[[4, 5], [2, 4]], ["5", "2"]]} +{"requirement": "Your task is to calculate sum of primes present as digits of given number N.\nExample 1:\nInput: 333\nOutput: 9\nExplaination: 3 is a prime number. It \nis present 3 times. So 3+3+3 = 9.\nExample 2:\nInput: 686\nOutput: 0\nExplaination: Neither 6 nor 8 is a \nprime number.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function primeSum() which takes N as input parameter and returns the sum of all the prime digits present in the number N.\nExpected Time Complexity: O(logN)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 N \u2264 5*10^{4}", "solutions": ["import math\n\ndef primesum(N):\n\n def prime(n):\n if n <= 1:\n return False\n for i in range(2, int(math.sqrt(n) + 1)):\n if n % i == 0:\n return False\n return True\n c = 0\n m = []\n while N > 0:\n d = N % 10\n m.append(d)\n N = N // 10\n for i in m:\n if prime(i):\n c += i\n return c", "def primesum(N):\n s = 0\n N = str(N)\n for i in N[::1]:\n i = int(i)\n if i == 2 or i == 3 or i == 5 or (i == 7):\n s += i\n return s", "def primesum(N):\n\n def prime(n):\n if n == 0 or n == 1:\n return 0\n for i in range(2, int(n // 2) + 1):\n if n % i == 0:\n return 0\n return 1\n count = 0\n for i in str(N):\n if prime(int(i)) == 1:\n count += int(i)\n return count", "def primesum(N):\n n = str(N)\n s = 0\n for i in n:\n count = 0\n m = int(i)\n for j in range(1, m + 1):\n if m % j == 0:\n count += 1\n if count == 2:\n s += m\n return s", "import math\n\ndef primesum(N):\n\n def isPrime(n):\n if n == 1:\n return 0\n for i in range(2, int(math.sqrt(n) + 1)):\n if n % i == 0:\n return 0\n return 1\n a = set()\n val = 0\n for i in str(N):\n if int(i) in a:\n val += int(i)\n elif isPrime(int(i)) == 1:\n a.add(int(i))\n val += int(i)\n return val", "def primesum(N):\n sum = 0\n while N != 0:\n a = N % 10\n N = N // 10\n if a == 2 or a == 3 or a == 5 or (a == 7):\n sum = sum + a\n return sum", "def primesum(N):\n\n def prime(n):\n if n <= 1:\n return False\n for i in range(2, n):\n if n % i == 0:\n return False\n return True\n s = 0\n while N:\n r = N % 10\n if prime(r):\n s = s + r\n N = N // 10\n return s", "import math\n\ndef fun(n):\n if n == 0 or n == 1:\n return False\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\ndef primesum(N):\n s = str(N)\n c = 0\n for i in s:\n if fun(int(i)):\n c += int(i)\n return c", "def primesum(n):\n su = 0\n s = str(n)\n for i in s:\n i = int(i)\n c = 0\n for j in range(1, i):\n if i % j == 0:\n c += 1\n if c == 1:\n su += i\n return su", "def primesum(N):\n\n def is_prime(n):\n import math\n a = int(math.sqrt(n))\n if n < 2:\n return False\n for i in range(2, a + 1):\n if n % i == 0:\n return False\n return True\n s = 0\n l = []\n while N:\n d = N % 10\n N = N // 10\n if is_prime(d) == True:\n l.append(d)\n return sum(l)", "def primesum(N):\n x = str(N)\n k = 0\n l = []\n for i in x:\n c = 0\n h = int(i)\n if h == 1:\n continue\n for j in range(2, h):\n if h % j == 0:\n c = 1\n break\n if c == 0:\n l.append(i)\n for i in l:\n k += int(i)\n return k", "def isprime(n):\n if n <= 1:\n return False\n i = 2\n while i * i <= n:\n if n % i == 0:\n return False\n i += 1\n return True\n\ndef primesum(N):\n N = list(str(N))\n summ = 0\n for i in N:\n if self.isprime(int(i)):\n summ += int(i)\n return summ", "def primesum(N):\n import math\n\n def is_prime(n):\n if n < 2:\n return False\n s = int(math.sqrt(n))\n for i in range(2, s + 1):\n if n % i == 0:\n return False\n return True\n s = str(N)\n l = list(map(int, s))\n a = []\n for i in l:\n if is_prime(i) == True:\n a.append(i)\n return sum(a)", "from math import sqrt\n\ndef primesum(N):\n sumOfPrime = 0\n while N:\n digit = N % 10\n prime = self.isPrime(digit)\n if prime:\n sumOfPrime += digit\n N //= 10\n return sumOfPrime\n\ndef isPrime(N):\n if N == 1 or N == 0:\n return False\n for i in range(2, int(sqrt(N)) + 1):\n if N % i == 0:\n return False\n return True", "import math\n\ndef primesum(N):\n\n def isprime(num):\n if num < 2:\n return False\n for i in range(2, int(math.sqrt(num)) + 1):\n if num % i == 0:\n return False\n return True\n primesum = 0\n for digit in str(N):\n if isprime(int(digit)):\n primesum += int(digit)\n return primesum", "def primesum(N):\n s = 0\n while N > 0:\n r = N % 10\n p = 0\n if r <= 1:\n p = 1\n for i in range(2, int(r ** 0.5) + 1):\n if r % i == 0:\n p += 1\n if p == 0:\n s += r\n N = N // 10\n return s", "def primesum(n):\n import math\n\n def prime(n):\n if n == 1 or n == 0:\n return False\n k = int(math.sqrt(n))\n for i in range(2, k + 1):\n if n % i == 0:\n return False\n return True\n sum = 0\n while n:\n d = n % 10\n if prime(d):\n sum += d\n n = n // 10\n return sum", "import math\n\ndef primesum(N):\n\n def prime(N):\n if N < 2:\n return False\n s = int(math.sqrt(N))\n for i in range(2, s + 1):\n if N % i == 0:\n return False\n return True\n c = 0\n for j in str(N):\n if prime(int(j)) == True:\n c += int(j)\n return c", "import math\n\ndef primesum(N):\n s = str(N)\n v = 0\n for i in s:\n n = int(i)\n c = 0\n for i in range(2, int(math.sqrt(n) + 1)):\n if n % i == 0:\n c += 1\n if c == 0 and n != 1:\n v = v + n\n return v", "def primesum(N):\n a = []\n sum = 0\n while N != 0:\n c = N % 10\n N = N // 10\n if c <= 1:\n continue\n f = 0\n for i in range(2, int(c ** 0.5) + 1):\n if c % i == 0:\n f = 1\n break\n if f == 0:\n sum = sum + c\n return sum", "def primesum(N):\n a = []\n b = []\n l = str(N)\n for i in l:\n if int(i) > 1:\n for j in range(2, int(int(i) ** 0.5) + 1):\n if int(i) % int(j) == 0:\n break\n else:\n a.append(i)\n lst = list(map(int, a))\n return sum(lst)", "def primesum(N):\n a = str(N)\n b = []\n for i in a:\n if int(i) > 1:\n for j in range(2, int(int(i) ** 0.5) + 1):\n if int(i) % j == 0:\n break\n else:\n b.append(int(i))\n if len(b) == 0:\n return 0\n else:\n return sum(b)", "import math\n\ndef isPrime(N):\n if N <= 1:\n return 0\n for i in range(2, int(math.sqrt(N) + 1)):\n if N % i == 0:\n return 0\n i += 1\n return 1\n\ndef primesum(N):\n N = list(str(N))\n sum = 0\n for i in N:\n if self.isPrime(int(i)):\n sum += int(i)\n return sum", "def primesum(N):\n prime_sum = 0\n for digit in str(N):\n num = int(digit)\n if self.isPrime(num):\n prime_sum += num\n return prime_sum\n\ndef isPrime(num):\n if num < 2:\n return False\n if num == 2 or num == 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n for i in range(3, int(num ** 0.5) + 1, 2):\n if num % i == 0:\n return Fals\n return True", "import math\n\ndef primesum(N):\n s = int(math.sqrt(N))\n for i in range(2, s + 1):\n if i < 2:\n return 0\n s = 0\n for i in str(N):\n if i == '2' or i == '3' or i == '5' or (i == '7'):\n s += int(i)\n return s", "def primesum(N):\n sum = 0\n\n def prime(n):\n if n < 2:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n while N:\n d = N % 10\n if prime(d):\n sum = sum + d\n N = N // 10\n return sum", "def primesum(N):\n l = []\n while N != 0:\n r = N % 10\n l.append(r)\n N = N // 10\n k = []\n for i in l:\n c = 0\n for j in range(1, i):\n if i % j == 0:\n c = c + 1\n if c == 1:\n k.append(i)\n return sum(k)", "def primesum(N):\n c = 0\n for i in str(N):\n s = int(i)\n if s == 2:\n c += 2\n elif s % 2 == 0 or s == 1:\n continue\n else:\n for i in range(2, int(s ** 0.5) + 1):\n if s % i == 0:\n break\n else:\n c += s\n return c", "import math\n\ndef is_prime(n):\n if n < 2:\n return False\n s = int(math.sqrt(n))\n for i in range(2, s + 1):\n if n % i == 0:\n return False\n return True\n\ndef primesum(N):\n c = 0\n lst = []\n while N:\n x = N % 10\n N = N // 10\n lst.append(x)\n for i in lst:\n if is_prime(i) == True:\n c += i\n return c", "def primesum(R):\n import math\n sm = 0\n\n def is_prime(N):\n if N < 2:\n return False\n s = int(math.sqrt(N))\n for i in range(2, s + 1):\n if N % i == 0:\n return False\n return True\n while R:\n rem = R % 10\n R = R // 10\n if is_prime(rem):\n sm += rem\n return sm", "def primesum(N):\n\n def is_prime(num):\n if num < 2:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return False\n return True\n digits = str(N)\n prime_sum = 0\n for digit in digits:\n if is_prime(int(digit)):\n prime_sum += int(digit)\n return prime_sum", "import math\n\ndef isprime(v):\n if v < 2:\n return 0\n for i in range(2, int(math.sqrt(v)) + 1):\n if v % i == 0:\n return 0\n return 1\n\ndef primesum(N):\n a = list(str(N))\n v = list(map(int, a))\n s = 0\n for i in v:\n if isprime(i):\n s += i\n return s", "import math\n\ndef isprime(N):\n if N <= 1:\n return False\n i = 2\n while i * i <= N:\n if N % i == 0:\n return False\n i += 1\n return True\n\ndef primesum(N):\n N = list(str(N))\n s = 0\n for i in N:\n if self.isprime(int(i)):\n s += int(i)\n return s", "import math\n\ndef primesum(N):\n sumo = 0\n while N != 0:\n d = N % 10\n c = 0\n if d <= 1:\n c = 1\n s = int(math.sqrt(d))\n for i in range(2, s + 1):\n if d % i == 0:\n c = 1\n if c == 0:\n sumo += d\n N = N // 10\n return sumo", "import math\n\ndef primesum(N):\n\n def isPrime(N):\n c = 0\n if N < 2:\n return False\n s = int(math.sqrt(N))\n for i in range(2, s + 1):\n if N % i == 0:\n c = c + 1\n if c == 0:\n return 1\n else:\n return 0\n s = str(N)\n k = []\n c = 0\n for i in s:\n k.append(int(i))\n for j in k:\n if isPrime(j) == 1:\n c = c + j\n return c", "import math\n\ndef primesum(N):\n p = str(N)\n l = list(p)\n s = 0\n for i in l:\n k = int(i)\n if k < 2:\n continue\n e = int(math.sqrt(k))\n for j in range(2, e + 1):\n if k % j == 0:\n break\n else:\n s += k\n return s", "def primesum(n):\n s = 0\n\n def prime(x):\n fc = 0\n for i in range(1, x + 1):\n if x % i == 0:\n fc += 1\n if fc == 2:\n return True\n else:\n return False\n while n:\n r = n % 10\n if prime(r):\n s += r\n n = n // 10\n return s", "def isPrime(N):\n if N <= 1:\n return False\n i = 2\n while i * i <= N:\n if N % i == 0:\n return False\n i += 1\n return True\n\ndef primesum(N):\n N = list(str(N))\n s = 0\n for i in N:\n if self.isPrime(int(i)):\n s += int(i)\n return s", "def primesum(N):\n sp = 0\n for i in str(N):\n if i == '1' or i == '0':\n pass\n else:\n s = int(int(i) ** 0.5)\n count = 0\n for j in range(2, s + 1):\n if int(i) % j == 0:\n count += 1\n if count == 0:\n sp = sp + int(i)\n return sp", "import math as m\n\ndef primesum(n):\n n = str(n)\n n = list(n)\n n = [eval(i) for i in n]\n sm = 0\n for i in n:\n c = 0\n b = int(m.sqrt(i))\n if i == 1:\n continue\n for j in range(1, b + 1):\n if i % j == 0:\n c += 1\n if c == 1:\n sm = sm + i\n c = 0\n return sm", "def primesum(n):\n e = []\n while n > 0:\n r = n % 10\n c = 0\n if r == 1:\n c += 1\n for i in range(2, int(r ** 0.5) + 1):\n if r % i == 0:\n c = 1\n break\n if c > 0:\n pass\n else:\n e.append(r)\n n = n // 10\n return sum(e)", "import math\n\ndef primesum(N):\n x = 0\n while N != 0:\n r = N % 10\n N = N // 10\n c = 0\n if r == 1:\n c += 1\n for i in range(2, int(math.sqrt(r)) + 1):\n if r % i == 0:\n c += 1\n break\n if c == 0:\n x += r\n return x", "import math\n\ndef primesum(N):\n\n def isPrime(N):\n f = 0\n if N == 1:\n return 0\n for i in range(2, int(math.sqrt(N) + 1)):\n if N % i == 0:\n return 0\n else:\n return 1\n s = 0\n while N > 0:\n r = N % 10\n if isPrime(r):\n s += r\n N = N // 10\n return s", "import math\n\ndef primesum(N):\n\n def isPrime(N):\n if N == 1:\n return False\n s = int(math.sqrt(N))\n for i in range(2, s + 1):\n if N % i == 0:\n return False\n return True\n sum = 0\n while N > 0:\n r = N % 10\n if isPrime(r):\n sum += r\n N = N // 10\n return sum", "import math\n\ndef primesum(N):\n s = str(N)\n d = 0\n n = list(map(int, s))\n for i in n:\n c = True\n if i < 2:\n c = False\n else:\n for j in range(2, int(math.sqrt(i)) + 1):\n if i % j == 0:\n c = False\n if c != False:\n d += i\n return d", "import math\n\ndef primesum(N):\n s = 0\n l = {2, 3, 5, 7}\n while N > 0:\n r = N % 10\n if r in l:\n s += r\n N = N // 10\n return s"], "starter_code": "def primesum(N):\n", "input_output": {"inputs": ["333", "686"], "outputs": ["9", "0"]}, "difficulty": "EASY", "raw_tags": ["Prime Number", "Numbers"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory", "Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/sum-of-primes0042/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(logN)", "entry_point": "primesum", "task_id": "TACO_lite/232", "example": [[[333], [686]], ["9", "0"]]} +{"requirement": "Given an integer N. The task is to return the position of first set bit found from the right side in the binary representation of the number.\nNote: If there is no set bit in the integer N, then return 0 from the function. \nExample 1:\nInput: N = 18\nOutput: 2\nExplanation: Binary representation of \n18 is 010010,the first set bit from the \nright side is at position 2.\nExample 2:\nInput: N = 12 \nOutput: 3 \nExplanation: Binary representation \nof 12 is 1100, the first set bit \nfrom the right side is at position 3.\nYour Task:\nThe task is to complete the function getFirstSetBit() that takes an integer n as a parameter and returns the position of first set bit.\nExpected Time Complexity: O(log N).\nExpected Auxiliary Space: O(1).\nConstraints:\n0 <= N <= 10^{8}", "solutions": ["def getfirstsetbit(n):\n ans = 0\n while n:\n mod = n % 2\n ans += 1\n if mod == 1:\n return ans\n n = n // 2\n return 0", "def getfirstsetbit(n):\n if n == 0:\n return 0\n b = bin(n)[2:]\n b = b[::-1]\n k = list(b)\n p = k.index('1')\n return p + 1", "def getfirstsetbit(n):\n pos = 1\n while n != 0:\n if n & 1 == 1:\n return pos\n pos += 1\n n >>= 1\n return 0", "def getfirstsetbit(n):\n bi = bin(n).replace('0b', '')\n c = 0\n for i in range(len(bi) - 1, -1, -1):\n if bi[i] == '1':\n return c + 1\n c += 1\n return 0", "def getfirstsetbit(n):\n x = 1\n pos = 1\n if n == 0:\n return 0\n while x <= n:\n if n == 0:\n return False\n if n & x != 0:\n return pos\n else:\n pos = pos + 1\n x = x << 1", "def getfirstsetbit(n):\n if n == 0:\n return 0\n t = bin(n)[2:]\n q = t[::-1]\n p = q.index('1')\n return p + 1", "def getfirstsetbit(n):\n if n == 0:\n return 0\n b = str(bin(n).replace('0b', ''))\n b = b[::-1]\n for i in range(len(b)):\n if b[i] == '1':\n return i + 1", "def convert(n):\n return bin(n).replace('0b', '')\n\ndef getfirstsetbit(n):\n if n == 0:\n return 0\n x = self.convert(n)[::-1]\n for i in range(len(x)):\n if x[i] == '1':\n return i + 1", "def getfirstsetbit(n):\n if n == 0:\n return '0'\n a = bin(n)[2:][::-1]\n return a.index('1') + 1", "def getfirstsetbit(n):\n m = bin(n)\n s = str(m)\n j = 1\n for i in range(len(s) - 1, 0, -1):\n if s[i] == '1':\n return j\n break\n j += 1\n return 0", "def getfirstsetbit(n):\n if n == 0:\n return 0\n return str(math.log2(n & -n) + 1)[:-2]", "def getfirstsetbit(n):\n c = 0\n if n == 0:\n return 0\n else:\n while n > 0:\n c += 1\n if n & 1 == 1:\n return c\n n = n >> 1", "def getfirstsetbit(n):\n count = 0\n if n == 0:\n return count\n while n != 0:\n count += 1\n if n & 1 == 1:\n return count\n n >>= 1", "def getfirstsetbit(n):\n if n == 0:\n return 0\n i = 1\n while n > 0:\n remain = n % 2\n if remain == 1:\n return i\n i += 1\n n = n / 2", "def getfirstsetbit(n):\n if n == 0:\n return 0\n s = bin(n)\n num = s[2:]\n num = num[::-1]\n c = 1\n for x in num:\n if x == '1':\n return c\n c += 1", "def getfirstsetbit(n):\n m = list(bin(n))\n m.remove('b')\n str1 = ''.join(m)\n if '1' not in str1:\n return 0\n return len(str1) - str1.rindex('1')", "def getfirstsetbit(n):\n binn = bin(n)[2:][::-1]\n for i in range(len(binn)):\n if binn[i] == '1':\n return i + 1\n return 0", "def getfirstsetbit(n):\n if n == 0:\n return 0\n res = 0\n while n != 1:\n if n % 2 != 0:\n return res + 1\n res += 1\n n = n // 2\n return res + 1", "def getfirstsetbit(n):\n x = list('{0:b}'.format(n))\n c = 0\n for i in x[::-1]:\n c += 1\n if int(i) == 1:\n return c\n return 0", "def getfirstsetbit(n):\n for i in range(32):\n if n & 1 << i != 0:\n return i + 1\n return 0", "def getfirstsetbit(n):\n count = 0\n pos = 1\n if n == 0:\n return 0\n while n > 0:\n if n % 2 == 1:\n count += 1\n break\n pos = pos + 1\n n = n // 2\n return pos", "def getfirstsetbit(n):\n i = n\n d = []\n flag = 0\n while i != 0:\n d.append(i % 2)\n i = int(i / 2)\n l = len(d)\n for i in range(len(d)):\n if d[i] == 1:\n return i + 1\n if flag == 0:\n return 0", "def getfirstsetbit(n):\n if n == 0:\n return 0\n t = bin(n)\n b = t.rfind('1')\n return len(t) - b", "def getfirstsetbit(n):\n if n == 0:\n return 0\n x = bin(n)[2:][::-1]\n y = []\n for i in range(len(x)):\n y.append(x[i])\n if '1' in y and '0' in y:\n return y.index('1') + 1\n return 1", "def getfirstsetbit(n):\n if n == 0:\n return 0\n return math.ceil(math.log2(n & -n) + 1)", "def getfirstsetbit(n):\n if n <= 0:\n return 0\n string = ''\n while n > 0:\n k = n % 2\n n = n // 2\n string += str(k)\n if k == 1:\n return len(string)\n return 0", "def getfirstsetbit(n):\n m = n\n k = ''\n k1 = []\n while m > 0:\n d = m % 2\n k = k + str(d)\n k1.append(d)\n m = m // 2\n if 1 in k1:\n return k1.index(1) + 1\n else:\n return 0", "def getfirstsetbit(n):\n k = bin(n)\n k = k[2:]\n n = len(k)\n z = 0\n for i in k[::-1]:\n z += 1\n if i == '1':\n return z\n return 0", "import math\n\ndef getfirstsetbit(n):\n if n == 0:\n return 0\n else:\n return int(math.log(n & -n, 2) + 1)", "def getfirstsetbit(n):\n if n == 0:\n return 0\n k = bin(n)\n s = k[2:]\n ans = s.rfind('1')\n return len(s) - ans", "def getfirstsetbit(n):\n p = 1\n while n:\n if n & 1:\n return p\n p = p + 1\n n = n >> 1\n return 0", "def getfirstsetbit(n):\n s = str(bin(n))\n s = s[::-1]\n for i in range(n):\n if s[i] == '1':\n return i + 1\n else:\n return 0", "def getfirstsetbit(n):\n if n == 0:\n return 0\n i = 0\n while True:\n if n & 1 << i != 0:\n return i + 1\n i += 1", "def getfirstsetbit(n):\n nums = bin(n)\n nums = list(nums.replace('b', '0')[2:])\n nums.reverse()\n for i in range(len(nums)):\n if nums[i] == '1':\n return i + 1\n return 0", "def getfirstsetbit(n):\n b = 0\n cont = 0\n res = n\n while b != 1 and res != 0:\n b = res % 2\n res -= res // 2\n cont += 1\n return cont", "def getfirstsetbit(n):\n if n == 0:\n return 0\n t = bin(n)\n p = t[2:]\n b = t.rindex('1')\n return len(t) - b", "import math\n\ndef getfirstsetbit(n):\n if n == 0:\n return 0\n without_first = n & n - 1\n only_first = n ^ without_first\n return math.floor(math.log(only_first, 2)) + 1", "def getfirstsetbit(n):\n b = bin(n)\n s = str(b)\n s = s[-1::-1]\n if '1' in s:\n x = s.index('1')\n return x + 1\n else:\n return 0", "def getfirstsetbit(n):\n i = -1\n b = n.bit_length()\n for i in range(b):\n if n & 1 << i != 0:\n break\n return i + 1", "def getfirstsetbit(n):\n x = str(bin(n))\n j = 1\n for i in range(len(x) - 1, -1, -1):\n if x[i] == '1':\n return j\n j += 1\n return 0", "def getfirstsetbit(n):\n (temp, count) = (bin(n)[2:][::-1], 0)\n for i in temp:\n if i == '1':\n return count + 1\n else:\n count += 1\n return 0", "def getfirstsetbit(n):\n a = list(bin(n)[::-1])\n if '1' in a:\n a = a.index('1')\n return a + 1\n return 0", "def getfirstsetbit(n):\n a = []\n while n > 0:\n a.append(n % 2)\n n = n // 2\n for i in range(0, len(a)):\n if a[i] == 1:\n return i + 1\n return 0", "import math\n\ndef getfirstsetbit(n):\n if n <= 1:\n return n\n k = n & ~n + 1\n return int(math.log2(k)) + 1", "def getfirstsetbit(n):\n incr = 0\n while n >= 1 << incr:\n if n & 1 << incr:\n break\n incr += 1\n else:\n return 0\n return incr + 1", "import math\n\ndef getfirstsetbit(n):\n ans = 0\n while n:\n if n & 1:\n return ans + 1\n else:\n n = n >> 1\n ans += 1\n return ans", "def getfirstsetbit(n):\n one = 1\n for i in range(1, 17):\n if n & one:\n return i\n one <<= 1\n return 0", "def getfirstsetbit(n):\n b = bin(n)[2:][::-1]\n for i in range(n):\n if b[i] == '1':\n return i + 1\n return 0", "import math\n\ndef getfirstsetbit(n):\n temp = n ^ n & n - 1\n if temp == 0:\n return 0\n else:\n return int(math.log2(temp) + 1)", "def getfirstsetbit(n):\n if n == 0:\n return 0\n else:\n return str(bin(n)[2:][::-1]).index('1') + 1"], "starter_code": "def getfirstsetbit(n):\n", "input_output": {"inputs": ["N = 18", "N = 12"], "outputs": ["2", "3"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/find-first-set-bit-1587115620/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log N).", "entry_point": "getfirstsetbit", "task_id": "TACO_lite/233", "example": [[[18], [12]], ["2", "3"]]} +{"requirement": "Given a directed acyclic graph(DAG) with n nodes labeled from 0 to n-1. Given edges, s and d ,count the number of ways to reach from s to d.There is a directed Edge from vertex edges[i][0] to the vertex edges[i][1].\n \nExample:\nInput: edges = {{0,1},{0,3},{1,2},{3,2}}, \nn = 4, s = 0, d = 2\nOutput: 2\nExplanation: There are two ways to reach at \n2 from 0. These are-\n1. 0->1->2\n2. 0->3->2\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function possible_paths() which takes edges, n, s and d as input parameter and returns the number of ways to reach from s to d.\n \nExpected Time Compelxity: O(2^{n})\nExpected Space Complexity: O(n+e) \nwhere e is the number of edges in the graph.\n \nConstraints:\n1 <= n <= 15\n0 <= s, d <= n-1", "solutions": ["def possible_paths(edges, n, s, d):\n g = [[] for _ in range(n)]\n for (a, b) in edges:\n g[a].append(b)\n path = set()\n\n def helper(node, prev, p):\n if node == d:\n path.add(tuple(p + [node]))\n return p\n if node in p:\n return False\n for neig in g[node]:\n if neig != prev:\n helper(neig, node, p + [node])\n return p\n helper(s, -1, [])\n return len(path)", "def solve(adj, n, s, d, dp):\n if dp[s] != 0:\n return dp[s]\n for child in adj[s]:\n dp[s] += self.solve(adj, n, child, d, dp)\n return dp[s]\n\ndef possible_paths(edges, n, s, d):\n adj = dict()\n for i in range(n):\n adj[i] = []\n dp = [0] * n\n dp[d] = 1\n for edge in edges:\n (u, v) = (edge[0], edge[1])\n adj[u].append(v)\n return self.solve(adj, n, s, d, dp)", "def solve(adj, way, s, d):\n if s == d:\n way[0] += 1\n return\n for i in adj[s]:\n self.solve(adj, way, i, d)\n\ndef possible_paths(edges, n, s, d):\n adj = [[] for i in range(n)]\n for (i, j) in edges:\n adj[i].append(j)\n way = [0]\n self.solve(adj, way, s, d)\n return way[0]", "def possible_paths(edges, n, s, d):\n\n def _dfs(vertex, target):\n visited.add(vertex)\n path.append(vertex)\n if vertex == target:\n output.append(list(path))\n path.pop()\n visited.remove(vertex)\n return\n for neighbor in graph[vertex]:\n if neighbor not in visited:\n _dfs(neighbor, target)\n path.pop()\n visited.remove(vertex)\n graph = [[] for i in range(n)]\n for edge in edges:\n graph[edge[0]].append(edge[1])\n visited = set()\n vertices = range(n)\n start = s\n target = d\n output = []\n path = []\n _dfs(start, target)\n return len(output)", "from collections import defaultdict\n\ndef dfs(node, d, graph):\n if node == d:\n self.ans += 1\n return\n for i in graph[node]:\n self.dfs(i, d, graph)\n\ndef possible_paths(edges, n, s, d):\n graph = defaultdict(list)\n self.ans = 0\n for (a, b) in edges:\n graph[a].append(b)\n self.dfs(s, d, graph)\n return self.ans", "from collections import defaultdict\n\ndef ToGraph(edges):\n graph = defaultdict(list)\n for edge in edges:\n (u, v) = edge\n graph[u].append(v)\n return graph\n\ndef possible_paths(edges, n, s, d):\n graph = self.ToGraph(edges)\n stack = [s]\n count = 0\n while stack:\n current = stack.pop()\n if current == d:\n count += 1\n for neighbour in graph[current]:\n stack.append(neighbour)\n return count", "def possible_paths(edges, n, s, d):\n\n def vamsi(u, d, adj, visited, ans):\n if u == d:\n ans[0] += 1\n return\n visited[u] = 1\n for i in adj[u]:\n if i not in visited:\n vamsi(i, d, adj, visited, ans)\n del visited[u]\n return\n adj = {}\n for i in range(0, n):\n adj[i] = []\n for (i, j) in edges:\n adj[i].append(j)\n visited = {}\n ans = [0]\n vamsi(s, d, adj, visited, ans)\n return ans[0]", "from collections import defaultdict, deque\n\ndef possible_paths(edges, n, s, d):\n g = defaultdict(list)\n for (i, j) in edges:\n g[i].append(j)\n q = deque([s])\n res = 0\n while q:\n cur = q.popleft()\n if cur == d:\n res += 1\n for nei in g[cur]:\n q.append(nei)\n return res", "def possible_paths(edges, n, s, d):\n queue = []\n queue.append(s)\n count = 0\n while queue:\n ele = queue.pop(0)\n if ele == d:\n count += 1\n for i in edges:\n if i[0] == ele:\n queue.append(i[1])\n return count", "def possible_paths(edges, n, s, d):\n visit = []\n visit.append(s)\n count = 0\n while visit:\n a = visit.pop()\n if a == d:\n count += 1\n for i in edges:\n if i[0] == a:\n visit.append(i[1])\n return count", "def possible_paths(edges, n, src, dest):\n x = [[] for i in range(n)]\n for (a, b) in edges:\n x[a].append(b)\n\n def f(i):\n if i == dest:\n return 1\n if dp[i] != None:\n return dp[i]\n ans = 0\n for j in x[i]:\n ans += f(j)\n dp[i] = ans\n return ans\n dp = [None for i in range(n)]\n return f(src)", "def dfs(s, adj, d, count):\n if s == d:\n count[0] += 1\n for i in adj[s]:\n self.dfs(i, adj, d, count)\n\ndef possible_paths(edges, n, s, d):\n adj = [[] for i in range(n)]\n for i in edges:\n adj[i[0]].append(i[1])\n count = [0]\n self.dfs(s, adj, d, count)\n return count[0]", "def possible_paths(edges, n, s, d):\n visited = [False] * n\n count = [0]\n\n def checkPaths(start, dest):\n visited[start] = True\n if start == dest:\n count[0] += 1\n else:\n for edge in edges:\n if edge[0] == start and (not visited[edge[1]]):\n checkPaths(edge[1], dest)\n visited[start] = False\n checkPaths(s, d)\n return count[0]", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n graph = defaultdict(lambda : [])\n for (first, second) in edges:\n graph[first].append(second)\n stack = [s]\n count = 0\n while stack:\n item = stack.pop()\n if item == d:\n count += 1\n else:\n stack += graph[item]\n return count", "def possible_paths(edges, n, s, d):\n x = {c: [] for c in range(n)}\n for (a, b) in edges:\n x[a].append(b)\n\n def dfs(node):\n if node == d:\n return 1\n ans = 0\n for j in x[node]:\n ans += dfs(j)\n return ans\n return dfs(s)", "def possible_paths(edges, n, s, d):\n x = [[] for i in range(n)]\n for (a, b) in edges:\n x[a].append(b)\n\n def check(i):\n if i == d:\n return 1\n ans = 0\n for j in x[i]:\n ans += check(j)\n return ans\n return check(s)", "def possible_paths(edges, n, s, d):\n adj = [[] for i in range(n)]\n for (i, j) in edges:\n adj[i].append(j)\n return self.dfs(s, adj, d)\n\ndef dfs(node, adj, target):\n if node == target:\n return 1\n output = 0\n for i in adj[node]:\n output += self.dfs(i, adj, target)\n return output", "def possible_paths(edges, n, s, dest):\n if n == 1 or s == dest:\n return 1\n d = dict()\n for i in range(len(edges)):\n if edges[i][0] in d:\n d[edges[i][0]].append(edges[i][1])\n else:\n d[edges[i][0]] = [edges[i][1]]\n res = [0]\n\n def dfs(i, dest):\n if i in d:\n for j in d[i]:\n if j == dest:\n res[0] += 1\n else:\n dfs(j, dest)\n dfs(s, dest)\n return res[0]", "def possible_paths(edges, n, s, d):\n nodes = [s]\n cnt = 0\n while nodes:\n cur = nodes.pop(0)\n if cur == d:\n cnt += 1\n for i in edges:\n if i[0] == cur:\n nodes.append(i[1])\n return cnt", "def possible_paths(edges, n, s, d):\n count = [0]\n D = [[] for i in range(n)]\n for a in edges:\n D[a[0]].append(a[1])\n visited = [-1] * n\n self.x(D, s, d, count, visited)\n return count[0]\n\ndef x(D, s, d, count, visited):\n visited[s] = 1\n if s == d:\n count[0] += 1\n for i in D[s]:\n if visited[i] == -1:\n self.x(D, i, d, count, visited)\n visited[s] = -1", "def possible_paths(edges, n, s, des):\n from collections import defaultdict\n d = defaultdict(list)\n for (i, j) in edges:\n d[i].append(j)\n visited = [False] * n\n res = set()\n\n def dfs(d, curr, des, path):\n nonlocal res, visited\n if curr == des:\n news = ''\n for i in path:\n news += str(i)\n res.add(news)\n return\n visited[curr] = True\n path.append(curr)\n for j in d[curr]:\n if visited[j] == False:\n dfs(d, j, des, path)\n visited[curr] = False\n path.pop()\n dfs(d, s, des, [])\n return len(res)", "from collections import deque\n\ndef possible_paths(edges, n, s, d):\n adj = [[0] * n for _ in range(n)]\n for edge in edges:\n adj[edge[0]][edge[1]] = 1\n count = 0\n source = deque([s])\n while len(source):\n if source[0] == d:\n count += 1\n else:\n for i in range(n):\n if adj[source[0]][i]:\n source.append(i)\n source.popleft()\n return count", "def possible_paths(edges, n, s, d):\n adj = {}\n for edge in edges:\n (start, end) = (edge[0], edge[1])\n if start not in adj.keys():\n adj[start] = [end]\n adj[end] = []\n else:\n adj[start].append(end)\n ans = []\n\n def dfs(start, end, adj, ans, path=[]):\n path = path + [start]\n if start == end:\n ans.append(path.copy())\n path.pop()\n return\n if start not in adj.keys():\n return\n for neighbour in adj[start]:\n if neighbour not in path:\n dfs(neighbour, end, adj, ans, path)\n path.pop()\n dfs(s, d, adj, ans)\n return len(ans)", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n graph = defaultdict(list)\n for (parent, child) in edges:\n graph[parent].append(child)\n\n def dfs(curr, d):\n if curr == d:\n return 1\n res = 0\n for child in graph[curr]:\n res += dfs(child, d)\n return res\n return dfs(s, d)", "def getPossiblePath(hash, index, d, dp):\n if index == d:\n return 1\n if dp[index] != -1:\n return dp[index]\n if index in hash:\n list = hash[index]\n result = 0\n for i in list:\n result += self.getPossiblePath(hash, i, d, dp)\n dp[index] = result\n return dp[index]\n else:\n return 0\n\ndef possible_paths(edges, n, s, d):\n hash = dict()\n dp = [-1 for i in range(n)]\n for i in edges:\n if i[0] not in hash:\n hash[i[0]] = [i[1]]\n else:\n hash[i[0]].append(i[1])\n return self.getPossiblePath(hash, s, d, dp)", "from collections import defaultdict\n\ndef DFS(s, d, graph, visited, ans):\n visited[s] = True\n if s == d:\n ans[0] += 1\n for neighbour in graph[s]:\n self.DFS(neighbour, d, graph, visited, ans)\n visited[s] = False\n return\n\ndef possible_paths(edges, n, s, d):\n graph = defaultdict(list)\n for edge in edges:\n graph[edge[0]].append(edge[1])\n visited = [False for i in range(n)]\n ans = [0]\n self.DFS(s, d, graph, visited, ans)\n return ans[0]", "def possible_paths(edges, n, s, d):\n\n def dfs(s, d, edges, vis, ANS, ans):\n vis[s] = True\n ans.append(s)\n if s == d:\n ANS.append(ans)\n vis[ans.pop()] = False\n return\n for i in range(len(edges)):\n if edges[i][0] == s:\n if vis[edges[i][1]] == False:\n dfs(edges[i][1], d, edges, vis, ANS, ans)\n vis[ans.pop()] = False\n return\n vis = [False for i in range(n)]\n ANS = []\n ans = []\n dfs(s, d, edges, vis, ANS, ans)\n return len(ANS)", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n count = 0\n\n def dfs(v, visited):\n nonlocal count\n visited.add(v)\n for i in range(n):\n if i in graph[v] and i not in visited:\n dfs(i, visited)\n if v == d:\n count += 1\n visited.remove(v)\n graph = defaultdict(list)\n for i in range(len(edges)):\n graph[edges[i][0]].append(edges[i][1])\n dfs(s, set())\n return count", "def count_dfs(graph, u, d, visited):\n if u == d:\n return 1\n visited[u] = True\n ans = 0\n for v in graph[u]:\n if visited[v] == False:\n ans += self.count_dfs(graph, v, d, visited)\n visited[u] = False\n return ans\n\ndef possible_paths(edges, n, s, d):\n graph = [[] for i in range(n)]\n for edge in edges:\n graph[edge[0]].append(edge[1])\n visited = [False for i in range(n)]\n return self.count_dfs(graph, s, d, visited)", "def possible_paths(edges, n, s, d):\n\n def dfs(adj, i, d):\n cnt = 0\n if i == d:\n cnt += 1\n for j in adj[i]:\n cnt += dfs(adj, j, d)\n return cnt\n adj = [[] for i in range(n)]\n for edge in edges:\n adj[edge[0]].append(edge[1])\n total_cnt = dfs(adj, s, d)\n return total_cnt", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n if n == 0:\n return 1\n adj = defaultdict(list)\n for (u, v) in edges:\n adj[u].append(v)\n visited = [0] * n\n q = []\n q.append(s)\n count = 0\n if s == d:\n count += 1\n while q:\n node = q.pop(0)\n for i in adj[node]:\n if i == d:\n count += 1\n if visited[i] == 0:\n q.append(i)\n visited[i] == 1\n return count", "def possible_paths(edges, n, s, d):\n if s == d:\n return 1\n count = 0\n l = [s]\n for j in l:\n for i in range(0, len(edges)):\n if edges[i][0] == j:\n if edges[i][1] == d:\n count += 1\n l.append(edges[i][1])\n else:\n l.append(edges[i][1])\n return count", "def possible_paths(edges, n, s, d):\n q = []\n q.append(s)\n count = 0\n while q:\n curr = q.pop(0)\n if curr == d:\n count += 1\n for i in edges:\n if i[0] == curr:\n q.append(i[1])\n return count", "def possible_paths(edges, n, st, dest):\n if st == dest:\n return 1\n if len(edges) == 0:\n return -1\n adj = []\n for i in range(n):\n adj.append([])\n for pair in edges:\n (s, e) = pair\n adj[s].append(e)\n ans = [0]\n self.dfs(adj, ans, st, dest)\n return ans[0]\n\ndef dfsUtil(st, dest, adj, ans):\n if st == dest:\n ans[0] += 1\n return\n for itm in adj[st]:\n self.dfsUtil(itm, dest, adj, ans)\n\ndef dfs(adj, ans, st, dest):\n for itm in adj[st]:\n self.dfsUtil(itm, dest, adj, ans)", "def possible_paths(edges, n, s, d):\n ans = []\n\n def dfs(s, di, vis, d):\n if s == d:\n ans.append(1)\n return\n for k in range(len(di[s])):\n dfs(di[s][k], di, vis, d)\n di = {}\n vis = set()\n for i in range(n):\n di[i] = []\n for i in range(len(edges)):\n di[edges[i][0]].append(edges[i][1])\n dfs(s, di, vis, d)\n return len(ans)", "def soln(g, s, d, l):\n if s == d:\n l[0] += 1\n return\n for i in g[s]:\n soln(g, i, d, l)\n return\n\ndef possible_paths(edges, n, s, d):\n g = {}\n for i in range(n):\n g[i] = []\n l = [0]\n for i in edges:\n g[i[0]].append(i[1])\n soln(g, s, d, l)\n return l[0]", "def possible_paths(edges, n, s, d):\n adj = [[] for i in range(n)]\n result = 0\n for edge in edges:\n u = edge[0]\n v = edge[1]\n adj[u].append(v)\n queue = [s]\n while queue:\n node = queue.pop(0)\n if node == d:\n result += 1\n continue\n for it in adj[node]:\n queue.append(it)\n return result", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n dic = defaultdict(list)\n for i in edges:\n dic[i[0]].append(i[1])\n count = 0\n\n def checkcount(dic, s, d, visted, path):\n nonlocal count\n visited[s] = True\n if s == d:\n count += 1\n for i in dic[s]:\n if visted[i] == None:\n checkcount(dic, i, d, visted, path)\n visted[s] = None\n visited = [None] * n\n path = []\n checkcount(dic, s, d, visited, path)\n return count", "def __init__():\n self.res = 0\n\ndef possible_paths(edges, n, s, d):\n adj = [[] for _ in range(n)]\n for edge in edges:\n adj[edge[0]].append(edge[1])\n self.dfs(adj, s, d)\n return self.res\n\ndef dfs(adj, s, d):\n if s == d:\n self.res += 1\n return\n for i in adj[s]:\n self.dfs(adj, i, d)", "def possible_paths(edges, n, s, d):\n di = dict()\n for i in range(len(edges)):\n if edges[i][0] not in di:\n di[edges[i][0]] = []\n di[edges[i][0]].append(edges[i][1])\n\n def get_paths(start, end, path=[]):\n path = path + [start]\n if start == end:\n return [path]\n if start not in di:\n return []\n paths = []\n for node in di[start]:\n if node not in path:\n new_paths = get_paths(node, end, path)\n for p in new_paths:\n paths.append(p)\n return paths\n return len(get_paths(s, d))", "def possible_paths(edges, n, s, d):\n if edges == [] or s == d:\n return 1\n for edge in edges:\n if edge[0] == s:\n self.recurs(s, edges, edge)\n return self.num\n\ndef recurs(choosing, edges, edge):\n if edge[1] == d:\n self.num += 1\n else:\n for e in edges:\n if edge[1] == e[0]:\n self.recurs(edge[1], edges, e)", "def possible_paths(edges, n, s, d):\n adj = [[] for i in range(n)]\n for i in edges:\n adj[i[0]].append(i[1])\n\n def rec(adj, c):\n if c == d:\n return 1\n e = 0\n for i in adj[c]:\n e += rec(adj, i)\n return e\n return rec(adj, s)", "def possible_paths(edges, n, s, d):\n if s == d:\n return 1\n stack = [s]\n counter = 0\n neighbors = {}\n for edge in edges:\n (a, b) = (edge[0], edge[1])\n if a not in neighbors:\n neighbors[a] = [b]\n else:\n neighbors[a].append(b)\n path = str(s)\n vis = {i: False for i in range(n)}\n passed = set()\n while stack:\n top = stack[-1]\n state = False\n if top in neighbors:\n for neigh in neighbors[top]:\n temp = path + '_' + str(neigh)\n if temp not in passed:\n stack.append(neigh)\n path = temp\n if neigh == d:\n counter += 1\n passed.add(path)\n state = True\n vis[neigh] = True\n break\n if not state:\n pp = stack.pop()\n path = path[:-(1 + len(str(pp)))]\n return counter", "def possible_paths(edges, n, s, d):\n graph = {}\n for i in edges:\n if i[0] in graph.keys():\n graph[i[0]].append(i[1])\n else:\n graph[i[0]] = [i[1]]\n q = []\n q.append(s)\n totalPath = 0\n while len(q) > 0:\n if q[0] == d:\n totalPath += 1\n elif q[0] in graph.keys():\n for i in graph[q[0]]:\n q.append(i)\n q.pop(0)\n return totalPath", "def possible_paths(edges, n, s, d):\n adj = []\n for i in range(n):\n adj.append([])\n for edge in edges:\n adj[edge[0]].append(edge[1])\n queue = [s]\n ways = 0\n while queue:\n elem = queue.pop()\n if elem == d:\n ways += 1\n continue\n for itm in adj[elem]:\n queue.insert(0, itm)\n return ways", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n adj = defaultdict(list)\n for (i, j) in edges:\n adj[i].append(j)\n ans = []\n stack = [(s, [0])]\n while stack:\n (node, path) = stack.pop()\n if node == d:\n ans.append(path)\n else:\n for adjnode in adj[node]:\n stack.append((adjnode, path + [adjnode]))\n return len(ans)", "from collections import defaultdict\n\ndef buildGraph(edges):\n graph = defaultdict(list)\n for (i, j) in edges:\n graph[i].append(j)\n return graph\n\ndef possible_paths(edges, n, s, d):\n ways = 0\n graph = self.buildGraph(edges)\n visited = set()\n\n def dfs(curr):\n nonlocal ways\n if curr == d:\n ways += 1\n return\n if curr in visited:\n return\n visited.add(curr)\n for i in graph[curr]:\n dfs(i)\n visited.remove(curr)\n dfs(s)\n return ways", "def possible_paths(edges, n, s, d):\n if s == d:\n return 1\n count = 0\n for i in edges:\n if i[0] == s:\n count += self.possible_paths(edges, n, i[1], d)\n return count", "def possible_paths(edges, n, s, d):\n q = []\n q.append(s)\n c = 0\n while q:\n a = q.pop(0)\n if a == d:\n c += 1\n for i in edges:\n if i[0] == a:\n q.append(i[1])\n return c", "def possible_paths(edges, n, s, d):\n\n def buildAdj(edges):\n adj = {}\n for edge in edges:\n (s, d) = (edge[0], edge[1])\n if s not in adj:\n adj[s] = []\n adj[s].append(d)\n return adj\n\n def dfs(s):\n if s == d:\n return 1\n count = 0\n if s in adj:\n neighbors = adj[s]\n for neighbor in neighbors:\n count += dfs(neighbor)\n return count\n adj = buildAdj(edges)\n return dfs(s)", "def possible_paths(edges, n, s, d):\n\n def dfs(u, count):\n if u == d:\n count[0] += 1\n for v in m[u]:\n dfs(v, count)\n import collections\n m = collections.defaultdict(list)\n for i in edges:\n m[i[0]].append(i[1])\n count = [0]\n dfs(s, count)\n return count[0]", "def possible_paths(edges, n, s, d):\n q = [s]\n c = 0\n adj = [[] for _ in range(n)]\n for i in edges:\n adj[i[0]].append(i[1])\n while q:\n x = q.pop(0)\n for i in adj[x]:\n q.append(i)\n if x == d:\n c = c + 1\n return c", "def possible_paths(edges, n, s1, d1):\n adj = {}\n for i in range(n):\n adj[i] = []\n for i in edges:\n (s, d) = (i[0], i[1])\n adj[s].append(d)\n visited = [False for i in range(n)]\n output = [0]\n\n def dfs(s, d):\n visited[s] = True\n if s == d:\n output[0] += 1\n visited[d] = False\n return\n for i in adj[s]:\n if visited[i] == False:\n dfs(i, d)\n visited[s] = False\n dfs(s1, d1)\n return output[0]", "from collections import defaultdict\n\ndef __init__():\n self.count = 0\n self.adj = defaultdict(list)\n\ndef possible_paths(edges, n, s, d):\n for (i, j) in edges:\n self.adj[i].append(j)\n self.getpaths(s, d)\n return self.count\n\ndef getpaths(s, d):\n if s == d:\n self.count += 1\n return\n for i in self.adj[s]:\n self.getpaths(i, d)\n return", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n queue = []\n queue.append(s)\n count = 0\n while queue:\n node = queue.pop(0)\n if node == d:\n count += 1\n for i in edges:\n if i[0] == node:\n queue.append(i[1])\n return count", "def possible_paths(edges, n, s, d):\n adj = [[] for _ in range(n)]\n for (u, v) in edges:\n adj[u].append(v)\n visited = [False] * n\n paths = [0]\n self.dfs(s, d, adj, visited, paths)\n return paths[0]\n\ndef dfs(s, d, adj, visited, paths):\n visited[s] = True\n if s == d:\n paths[0] += 1\n for ngbr in adj[s]:\n if not visited[ngbr]:\n self.dfs(ngbr, d, adj, visited, paths)\n visited[s] = False", "def possible_paths(edges, n, s, d):\n vis = [0] * n\n adj = [[] for i in range(n)]\n for (i, j) in edges:\n adj[i].append(j)\n\n def count_dfs(node):\n if node == d:\n return 1\n vis[node] = 1\n res = 0\n for i in adj[node]:\n if not vis[i]:\n res += count_dfs(i)\n vis[node] = 0\n return res\n return count_dfs(s)", "def possible_paths(edges, n, s, d):\n graph = {}\n for vertex in range(n):\n graph[vertex] = []\n for (u, v) in edges:\n graph[u].append(v)\n self.count = 0\n visit = set()\n\n def dfs(s):\n if s == d:\n self.count += 1\n return\n visit.add(s)\n for nei in graph[s]:\n if nei not in visit:\n dfs(nei)\n visit.remove(s)\n dfs(s)\n return self.count", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n res = 0\n\n def dfs(node):\n nonlocal res\n if node == d:\n res += 1\n return\n for nei in adj[node]:\n dfs(nei)\n adj = defaultdict(list)\n for (src, dist) in edges:\n adj[src].append(dist)\n dfs(s)\n return res", "def __init__():\n self.count = 0\n\ndef dfs(s, d, adj):\n if s == d:\n self.count += 1\n return\n for id in adj[s]:\n self.dfs(id, d, adj)\n\ndef possible_paths(edges, n, s, d):\n adj = [[] for _ in range(n)]\n for elem in edges:\n adj[elem[0]].append(elem[1])\n self.dfs(s, d, adj)\n return self.count", "def possible_paths(edges, n, s, d):\n adj_list = {}\n visited = [0] * n\n ans = []\n for k in range(0, len(edges)):\n first = edges[k][0]\n second = edges[k][1]\n if first not in adj_list:\n adj_list[first] = [second]\n else:\n adj_list[first].append(second)\n self.dfs(s, d, adj_list, visited, ans)\n return len(ans)\n\ndef dfs(s, d, adj_list, visited, ans):\n if s == d:\n ans.append(1)\n return\n visited[s] = 1\n if s in adj_list:\n for j in adj_list[s]:\n if visited[j] == 0:\n self.dfs(j, d, adj_list, visited, ans)\n visited[j] = 0\n return", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n graph = defaultdict(list)\n for (src, dst) in edges:\n graph[src].append(dst)\n visited = set()\n visited.add(s)\n paths = []\n\n def dfs_traverse(cur_node, path):\n if cur_node == d:\n paths.append(path[:])\n return\n for neighbor in graph[cur_node]:\n if neighbor in visited:\n continue\n visited.add(neighbor)\n dfs_traverse(neighbor, path + [neighbor])\n visited.remove(neighbor)\n dfs_traverse(s, [s])\n return len(paths)", "from collections import defaultdict\n\ndef dfs(v, visited, d, arr, res, graph):\n visited[v] = True\n arr.append(v)\n if v == d:\n res.append(arr.copy())\n else:\n for i in graph[v]:\n if visited[i] == False:\n self.dfs(i, visited, d, arr, res, graph)\n arr.pop()\n visited[v] = False\n\ndef possible_paths(edges, n, s, d):\n dct = defaultdict(list)\n for edge in edges:\n dct[edge[0]].append(edge[1])\n res = []\n visited = [False] * n\n self.dfs(s, visited, d, [], res, dct)\n return len(res)", "def possible_paths(edges, n, s, d):\n global count\n count = 0\n\n def dfs(root):\n global count\n if root == d:\n count += 1\n return\n for child in [edge[1] for edge in edges if edge[0] == root]:\n dfs(child)\n dfs(s)\n return count", "from collections import defaultdict\n\ndef possible_paths(edges, n, s, d):\n\n def dfs(vis, s, d):\n vis[s] = True\n if s == d:\n count[0] += 1\n for u in adj[s]:\n if vis[u] == False:\n dfs(vis, u, d)\n vis[s] = False\n adj = [[] for i in range(n)]\n for (i, j) in edges:\n adj[i].append(j)\n count = [0]\n vis = [False for _ in range(n)]\n dfs(vis, s, d)\n return count[0]"], "starter_code": "def possible_paths(edges, n, s, d):\n", "input_output": {"inputs": ["edges = {{0,1},{0,3},{1,2},{3,2}}, \r\nn = 4, s = 0, d = 2"], "outputs": ["2"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "DFS", "Data Structures", "Graph", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Graph algorithms", "Data structures", "Graph traversal"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-the-paths4332/1", "Expected Auxiliary Space": "O(n+e)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(2^n)", "entry_point": "possible_paths", "task_id": "TACO_lite/199", "example": [[], []]} +{"requirement": "Your task is to find the number couple with the greatest difference from a given array of number-couples. \n\nAll number couples will be given as strings and all numbers in them will be positive integers. \n\nFor instance: ['56-23','1-100']; in this case, you should identify '1-100' as the number couple with the greatest difference and return it.\n\nIn case there are more than one option, for instance ['1-3','5-7','2-3'], you should identify whichever is first, so in this case '1-3'. \n\nIf there is no difference, like so ['11-11', '344-344'], return false.", "solutions": ["def diff(arr):\n r = arr and max(arr, key=lambda x: abs(eval(x)))\n return bool(arr and eval(r)) and r", "def diff(arr):\n r = [abs(eval(s)) for s in arr]\n return arr[r.index(max(r))] if r and max(r) else False", "def diff(arr):\n r = [abs(int(w.split('-')[0]) - int(w.split('-')[1])) for w in arr]\n return arr[r.index(max(r))] if sum(r) else False", "def diff(arr):\n if not arr:\n return 0\n m = max(arr, key=lambda x: abs(eval(x)))\n return eval(m) and m", "def difference(x):\n (a, b) = map(int, x.split('-'))\n return abs(a - b)\n\ndef diff(arr):\n if not arr:\n return False\n x = max(arr, key=difference)\n if difference(x) == 0:\n return False\n return x", "def diff(pairs):\n max_diff = max_pair = 0\n for pair in pairs:\n (a, b) = pair.split('-')\n current = abs(int(a) - int(b))\n if current > max_diff:\n max_diff = current\n max_pair = pair\n return max_pair", "def diff(arr):\n vals = [abs(eval(pair)) for pair in arr]\n return False if all((val == 0 for val in vals)) else arr[vals.index(max(vals))]\n return val", "def diff(arr):\n z = {}\n for i in range(0, len(arr)):\n s = arr[i].split('-')\n d = abs(int(s[0]) - int(s[1]))\n z.update({arr[i]: d})\n w = {k: v for (k, v) in sorted(list(z.items()), reverse=True, key=lambda x: x[1])}\n if w == {} or max(w.values()) == 0:\n return False\n else:\n return max(w, key=w.get)", "def diff(arr):\n diff = []\n if arr == []:\n return False\n for i in range(len(arr)):\n str = arr[i].split('-')\n diff.append(abs(int(str[1]) - int(str[0])))\n if max(diff) == 0:\n return False\n for j in range(len(arr)):\n if diff[j] == max(diff):\n return arr[j]", "def diff(arr):\n if not arr:\n return False\n\n def cust_key(s):\n (a, b) = map(int, s.split('-'))\n return abs(a - b)\n m = max(arr, key=cust_key)\n return m if len(set(m.split('-'))) == 2 else False"], "starter_code": "def diff(arr):\n", "input_output": {"fn_name": "diff", "inputs": [[["43-45", "1021-55", "000-18888", "92-34", "76-32", "99-1", "1020-54"]], [["1-2", "2-4", "5-7", "8-9", "44-45"]], [["1-1000", "2-1000", "100-67", "98-45", "8-9"]], [["33-33", "77-77"]], [["23-67", "67-23", "88-88", "45-46"]], [["45896-2354", "4654-556767", "2455-423522", "3455-355", "34-34", "2524522-0"]], [["1-1", "2-2", "1-0", "77-77"]], [["0-0"]], [[]]], "outputs": [["000-18888"], ["2-4"], ["1-1000"], [false], ["23-67"], ["2524522-0"], ["1-0"], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56b12e3ad2387de332000041", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "diff", "task_id": "TACO_lite/104", "example": [[], []]} +{"requirement": "Given a string, remove any characters that are unique from the string.\n\nExample: \n\ninput: \"abccdefee\"\n\noutput: \"cceee\"", "solutions": ["from collections import Counter\n\ndef only_duplicates(string):\n cs = Counter(string)\n return ''.join((c for c in string if cs[c] > 1))", "def only_duplicates(string):\n return ''.join([x for x in string if string.count(x) > 1])", "only_duplicates = lambda s: ''.join((c for c in s if s.count(c) > 1))", "def only_duplicates(stg):\n return ''.join((c for c in stg if stg.count(c) > 1))", "def only_duplicates(string):\n return ''.join((s for s in string if string.count(s) > 1))", "def only_duplicates(string):\n sets = (unique, duplicate) = (set(), set())\n for c in string:\n sets[c in unique].add(c)\n return ''.join((c for c in string if c in duplicate))", "def only_duplicates(a):\n b = []\n for j in range(0, len(a)):\n for i in range(j + 1, len(a)):\n if a[j] == a[i]:\n b.append(a[j])\n a = list(a)\n\n def seclect(i):\n for j in b:\n if j == i:\n return i\n return ''.join(filter(seclect, a))", "def only_duplicates(string):\n string = list(string)\n foundStrings = []\n finalString = []\n for (index, item) in enumerate(string):\n if item not in string[index + 1:len(string)] and item not in string[0:index]:\n finalString.append('')\n else:\n finalString.append(item)\n return ''.join(finalString)", "from collections import Counter\nfrom re import sub\n\ndef only_duplicates(s):\n return sub('[%s]' % ''.join((k for (k, v) in Counter(s).items() if v == 1)), '', s)"], "starter_code": "def only_duplicates(string):\n", "input_output": {"fn_name": "only_duplicates", "inputs": [["abccdefee"], ["hello"], ["colloquial"], ["foundersandcoders"], ["12314256aaeff"]], "outputs": [["cceee"], ["ll"], ["ollol"], ["ondersndoders"], ["1212aaff"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Algorithms"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5a1dc4baffe75f270200006b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "only_duplicates", "task_id": "TACO_lite/245", "example": [[["abccdefee"]], ["cceee"]]} +{"requirement": "Given a number N, the task is to count minimum steps to minimize it to 1 according to the following criteria:\n\tIf N is divisible by 2 then you may reduce N to N/2.\n\tIf N is divisible by 3 then you may reduce N to N/3.\n\tOtherwise, Decrement N by 1.\nExample 1:\nInput: N = 10\nOutput: 3\nExplanation: 10 - 1 = 9 / 3 = 3 / 3 = 1\nExample 2:\nInput: N = 1\nOutput: 0\nExplanation: N is 1\nYour Task: \nYou don't need to read input or print anything. Complete the function minSteps() which takes N as input parameters and returns the integer value\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 \u2264 N \u2264 10^{4}", "solutions": ["def minsteps(N):\n MAX = 100000\n dp = [-1 for i in range(N + 1)]\n dp[1] = 0\n for i in range(2, N + 1):\n dp[i] = 1 + min(dp[i - 1], dp[i // 2] if i % 2 == 0 else MAX, dp[i // 3] if i % 3 == 0 else MAX)\n return dp[N]", "def minsteps(N):\n\n def fun(n, d):\n if n == 1:\n return 0\n if d[n] != -1:\n return d[n]\n res = fun(n - 1, d)\n if n % 2 == 0:\n res = min(res, fun(n // 2, d))\n if n % 3 == 0:\n res = min(res, fun(n // 3, d))\n d[n] = 1 + res\n return d[n]\n d = [-1 for i in range(N + 1)]\n return fun(N, d)", "def minsteps(n):\n dp = [0] * (n + 1)\n for i in range(2, n + 1):\n dp[i] = dp[i - 1] + 1\n if i % 2 == 0:\n dp[i] = min(dp[i], dp[i // 2] + 1)\n if i % 3 == 0:\n dp[i] = min(dp[i], dp[i // 3] + 1)\n return dp[n]", "def minsteps(n):\n dp = [0] * (N + 1)\n for i in range(2, N + 1):\n dp[i] = dp[i - 1] + 1\n for j in range(2, 4):\n if i % j == 0:\n dp[i] = min(dp[i], dp[i // j] + 1)\n return dp[N]", "def minsteps(N):\n dp = [0] * (N + 1)\n for i in range(2, N + 1):\n dp[i] = 1 + min(dp[i // 2] if i % 2 == 0 else float('inf'), dp[i // 3] if i % 3 == 0 else float('inf'), dp[i - 1])\n return dp[N]", "def minsteps(N):\n table = [0] * (N + 1)\n table[0] = 0\n table[1] = 0\n for pos in range(2, len(table)):\n a = b = c = float('inf')\n if pos % 3 == 0:\n a = 1 + table[pos // 3]\n if pos % 2 == 0:\n b = 1 + table[pos // 2]\n c = 1 + table[pos - 1]\n table[pos] = min(a, b, c)\n return table[N]", "def minsteps(N):\n dp = {}\n dp[0] = -1\n dp[1] = 0\n for i in range(2, N + 1):\n x1 = dp[i - 1] + 1\n x2 = dp[i / 2] + 1 if i % 2 == 0 else N\n x3 = dp[i / 3] + 1 if i % 3 == 0 else N\n dp[i] = min(x1, x2, x3)\n return dp[N]", "def minsteps(N):\n d = {1: 0, 2: 1, 3: 1}\n for i in range(4, N + 1):\n arr = [d[i - 1]]\n if i % 2 == 0:\n arr.append(d[i // 2])\n if i % 3 == 0:\n arr.append(d[i // 3])\n d[i] = min(arr) + 1\n return d[N]", "def minsteps(N):\n if N == 1:\n return 0\n temp = [-1] * (N + 1)\n temp[1] = 0\n for curr in range(2, N + 1):\n res = temp[curr - 1]\n if curr % 2 == 0:\n res = min(res, temp[curr // 2])\n if curr % 3 == 0:\n res = min(res, temp[curr // 3])\n temp[curr] = 1 + res\n return temp[N]", "def minsteps(N):\n memo = {}\n\n def minsteps1(n):\n if n == 1:\n return 0\n if n in memo:\n return memo[n]\n step1 = float('inf')\n step2 = float('inf')\n if n % 2 == 0:\n step1 = 1 + minsteps1(int(n / 2))\n if n % 3 == 0:\n step2 = 1 + minsteps1(int(n / 3))\n step3 = 1 + minsteps1(n - 1)\n memo[n] = min(step1, step2, step3)\n return memo[n]\n return minsteps1(N)", "import sys\n\ndef helper(n, dp):\n if n == 1:\n return 0\n if dp[n - 1] == -1:\n ans1 = self.helper(n - 1, dp)\n dp[n - 1] = ans1\n else:\n ans1 = dp[n - 1]\n (ans2, ans3) = (sys.maxsize, sys.maxsize)\n if n % 2 == 0:\n if dp[n // 2] == -1:\n ans2 = self.helper(n // 2, dp)\n dp[n // 2] = ans2\n else:\n ans2 = dp[n // 2]\n if n % 3 == 0:\n if dp[n // 3] == -1:\n ans3 = self.helper(n // 3, dp)\n dp[n // 3] = ans3\n else:\n ans3 = dp[n // 3]\n return 1 + min(ans1, ans2, ans3)\n\ndef minsteps(N):\n dp = [-1 for i in range(N + 1)]\n return self.helper(N, dp)", "def minsteps(N):\n\n def fun(n):\n if n == 1:\n return 0\n if dp[n] != -1:\n return dp[n]\n res = 0\n res = fun(n - 1)\n if n % 2 == 0:\n res = min(res, fun(n // 2))\n if n % 3 == 0:\n res = min(res, fun(n // 3))\n dp[n] = 1 + res\n return dp[n]\n dp = [-1] * (N + 1)\n return fun(N)", "def f(num, dp):\n if num in dp:\n return dp[num]\n if num == 1:\n dp[num] = 0\n return 0\n (by2, by3) = (1000000, 1000000)\n if num % 2 == 0:\n by2 = 1 + self.f(num / 2, dp)\n if num % 3 == 0:\n by3 = 1 + self.f(num / 3, dp)\n dp[num] = min(1 + self.f(num - 1, dp), by2, by3)\n return dp[num]\n\ndef minsteps(N):\n dp = {}\n return self.f(N, dp)", "from sys import maxsize as MAX_VALUE\n\ndef minsteps(n):\n if N == 1:\n return 0\n if N == 2:\n return 1\n if N == 3:\n return 1\n dp = [-1 for i in range(N + 1)]\n dp[1] = 0\n dp[2] = 1\n dp[3] = 1\n for i in range(4, N + 1):\n ans1 = dp[i - 1]\n (ans2, ans3) = (float('inf'), float('inf'))\n if i % 2 == 0:\n ans2 = dp[i // 2]\n if i % 3 == 0:\n ans3 = dp[i // 3]\n dp[i] = 1 + min(ans1, ans2, ans3)\n return dp[N]", "def minsteps(N):\n if N == 1:\n return 0\n if N <= 3:\n return 1\n dp = [0] * (N + 1)\n dp[2] = 1\n dp[3] = 1\n for i in range(4, N + 1):\n a = 987654321\n b = 987654321\n if i % 3 == 0:\n a = dp[i // 3] + 1\n if i % 2 == 0:\n b = dp[i // 2] + 1\n c = dp[i - 1] + 1\n dp[i] = min(a, b, c)\n return dp[-1]", "def minsteps(N):\n dp = [-1] * (N + 1)\n\n def check(N):\n if N == 1:\n return 0\n if dp[N] != -1:\n return dp[N]\n elif N % 2 == 0 and N % 3 == 0:\n dp[N] = 1 + min(min(check(N - 1), check(N // 2)), check(N // 3))\n return dp[N]\n elif N % 2 == 0:\n dp[N] = 1 + min(check(N - 1), check(N // 2))\n return dp[N]\n elif N % 3 == 0:\n dp[N] = 1 + min(check(N - 1), check(N // 3))\n return dp[N]\n else:\n dp[N] = 1 + check(N - 1)\n return dp[N]\n res = check(N)\n return res", "def solve(n, dp):\n if n == 1:\n return 0\n ans1 = float('inf')\n if n % 3 == 0:\n if dp[n // 3] == -1:\n ans1 = solve(n // 3, dp)\n dp[n // 3] = ans1\n else:\n ans1 = dp[n // 3]\n ans2 = float('inf')\n if n % 2 == 0:\n if dp[n // 2] == -1:\n ans2 = solve(n // 2, dp)\n dp[n // 2] = ans2\n else:\n ans2 = dp[n // 2]\n if dp[n - 1] == -1:\n ans3 = solve(n - 1, dp)\n dp[n - 1] = ans3\n else:\n ans3 = dp[n - 1]\n ans = 1 + min(ans1, ans2, ans3)\n return ans\n\ndef minsteps(N):\n dp = [-1 for i in range(N + 1)]\n ans = solve(N, dp)\n return ans", "def minsteps(n):\n import sys\n max_int = sys.maxsize\n dp = [0 for i in range(n + 1)]\n dp\n for i in range(2, n + 1):\n (op1, op2, op3) = (max_int, max_int, max_int)\n if i % 3 == 0:\n op1 = dp[i // 3]\n if i % 2 == 0:\n op2 = dp[i // 2]\n op3 = dp[i - 1]\n dp[i] = min(op1, op2, op3) + 1\n return dp[n]", "def minsteps(n):\n if n == 1:\n return 0\n if n == 2:\n return 1\n if n == 3:\n return 1\n dp = [-1 for i in range(n + 1)]\n dp[1] = 0\n dp[2] = 1\n dp[3] = 1\n for i in range(4, n + 1):\n ans1 = dp[i - 1]\n (ans2, ans3) = (float('inf'), float('inf'))\n if i % 2 == 0:\n ans2 = dp[i // 2]\n if i % 3 == 0:\n ans3 = dp[i // 3]\n dp[i] = 1 + min(ans1, ans2, ans3)\n return dp[n]", "def minsteps(n):\n if n == 1:\n ans = 0\n return ans\n dp = [-1 for i in range(n + 1)]\n return self.minsteps_to_1(n, dp)\n\ndef minsteps_to_1(n, dp):\n if n == 1:\n return 0\n ans1 = sys.maxsize\n if n % 3 == 0:\n if dp[n // 3] == -1:\n ans1 = self.minsteps_to_1(n // 3, dp)\n dp[n // 3] = ans1\n else:\n ans1 = dp[n // 3]\n ans2 = sys.maxsize\n if n % 2 == 0:\n if dp[n // 2] == -1:\n ans2 = self.minsteps_to_1(n // 2, dp)\n dp[n // 2] = ans2\n else:\n ans2 = dp[n // 2]\n if dp[n - 1] == -1:\n ans3 = self.minsteps_to_1(n - 1, dp)\n dp[n - 1] = ans3\n else:\n ans3 = dp[n - 1]\n ans = 1 + min(ans1, ans2, ans3)\n return ans", "def minsteps(N):\n if N <= 1:\n return 0\n memo = [999999] * (N + 1)\n memo[0] = 0\n memo[1] = 0\n for i in range(1, N):\n memo[i + 1] = min(memo[i] + 1, memo[i + 1])\n if i * 2 <= N:\n memo[i * 2] = min(memo[i] + 1, memo[i * 2])\n if i * 3 <= N:\n memo[i * 3] = min(memo[i] + 1, memo[i * 3])\n return memo[N]", "def minsteps(N):\n memo = [None] * (N + 1)\n\n def helper(N, memo):\n if N <= 1:\n return 0\n if memo[N]:\n return memo[N]\n op1 = op2 = op3 = 9999999\n op1 = 1 + helper(N - 1, memo)\n if N % 2 == 0:\n op2 = 1 + helper(int(N / 2), memo)\n if N % 3 == 0:\n op3 = 1 + helper(int(N / 3), memo)\n memo[N] = min(op1, op2, op3)\n return memo[N]\n return helper(N, memo)", "def minsteps(n):\n dp = {}\n\n def ways(n):\n if n == 1:\n return 0\n if n in dp:\n return dp[n]\n a = 999999999\n b = 999999999\n c = 999999999\n if n % 2 == 0:\n a = ways(n // 2) + 1\n if n % 3 == 0:\n b = ways(n // 3) + 1\n c = ways(n - 1) + 1\n dp[n] = min(a, b, c)\n return dp[n]\n return ways(n)", "def __init__():\n self.dp = [-1 for i in range(0, 10001)]\n self.dp[1] = 1\n\ndef minsteps(N):\n if N == 1:\n return 0\n if self.dp[N] != -1:\n return self.dp[N]\n ans1 = 999\n ans2 = 999\n ans3 = 999\n ans1 = self.minsteps(N - 1)\n if N % 2 == 0:\n ans2 = self.minsteps(N // 2)\n if N % 3 == 0:\n ans3 = self.minsteps(N // 3)\n self.dp[N] = 1 + min(ans1, ans2, ans3)\n return self.dp[N]", "def minsteps(N):\n dp = [0 for i in range(N + 1)]\n for j in range(2, N + 1):\n ans1 = dp[j - 1]\n ans2 = 9999\n ans3 = 99999\n if j % 2 == 0:\n ans2 = dp[j // 2]\n if j % 3 == 0:\n ans3 = dp[j // 3]\n dp[j] = 1 + min(ans1, ans2, ans3)\n return dp[N]", "def minsteps(n):\n dp = [-1 for i in range(n + 1)]\n return self.helper(n, dp)\n\ndef helper(n, dp):\n if n == 1:\n return 0\n ans1 = 9999\n if n % 3 == 0:\n if dp[n // 3] == -1:\n ans1 = self.helper(n // 3, dp)\n dp[n // 3] == ans1\n else:\n ans1 = dp[n // 3]\n ans2 = 999\n if n % 2 == 0:\n if dp[n // 2] == -1:\n ans2 = self.helper(n // 2, dp)\n dp[n // 2] = ans2\n else:\n ans2 = dp[n // 2]\n if dp[n - 1] == -1:\n ans3 = self.helper(n - 1, dp)\n dp[n - 1] = ans3\n else:\n ans3 = dp[n - 1]\n ans = 1 + min(ans1, ans2, ans3)\n return ans", "def minsteps(n):\n\n def getMinSteps(n, memo):\n if n == 1:\n return 0\n if memo[n] != -1:\n return memo[n]\n res = getMinSteps(n - 1, memo)\n if n % 2 == 0:\n res = min(res, getMinSteps(n // 2, memo))\n if n % 3 == 0:\n res = min(res, getMinSteps(n // 3, memo))\n memo[n] = 1 + res\n return memo[n]\n memo = [0 for i in range(n + 1)]\n for i in range(n + 1):\n memo[i] = -1\n return getMinSteps(n, memo)", "def minsteps(N):\n if N == 1:\n return 0\n if N == 2:\n return 1\n if N == 3:\n return 1\n arr = [0] * (N + 1)\n arr[0] = 0\n arr[1] = 0\n arr[2] = 1\n arr[3] = 1\n for j in range(3, N + 1):\n p = 100000\n q = 100000\n r = arr[j - 1]\n if j % 3 == 0:\n p = arr[j // 3]\n if j % 2 == 0:\n q = arr[j // 2]\n arr[j] = min(p, min(q, r)) + 1\n return arr[N]", "import sys\n\ndef minsteps(N):\n storage = [-1 for i in range(N + 1)]\n storage[1] = 0\n for i in range(2, N + 1):\n if i % 3 == 0:\n storage[i] = storage[i // 3] + 1\n elif i % 2 == 0:\n ans1 = storage[i // 2]\n ans2 = storage[i - 1]\n storage[i] = min(ans1, ans2) + 1\n else:\n storage[i] = storage[i - 1] + 1\n return storage[N]", "def minsteps(N):\n\n def minsteps(N):\n if N == 1:\n return 0\n if N % 3 == 0:\n if storage[N // 3] != -1:\n steps = storage[N // 3]\n else:\n steps = minsteps(N // 3)\n return steps + 1\n elif N % 2 == 0:\n if storage[N // 2] != -1:\n steps1 = storage[N // 2]\n else:\n steps1 = minsteps(N // 2)\n if storage[N - 1] != -1:\n steps2 = storage[N - 1]\n else:\n steps2 = minsteps(N - 1)\n return min(steps1, steps2) + 1\n else:\n if storage[N - 1] != -1:\n steps = storage[N - 1]\n else:\n steps = minsteps(N - 1)\n return steps + 1\n storage = [-1 for i in range(N)]\n return minsteps(N)", "def minsteps(N):\n if N == 1:\n return 0\n if N % 3 == 0:\n steps = self.minsteps(N // 3)\n return steps + 1\n elif N % 2 == 0:\n steps1 = self.minsteps(N // 2)\n steps2 = self.minsteps(N - 1)\n return min(steps1, steps2) + 1\n else:\n steps = self.minsteps(N - 1)\n return steps + 1", "def minsteps(N):\n count = 0\n if N == 1:\n return 0\n\n def get_count(N, count, dp):\n if N == 1:\n return dp[N]\n if dp[N] != 0:\n return dp[N]\n if N % 2 == 0 and N % 3 == 0:\n dp[N] = 1 + min(min(get_count(N // 2, count, dp), get_count(N // 3, count, dp)), get_count(N - 1, count, dp))\n elif N % 2 == 0:\n dp[N] = 1 + min(get_count(N // 2, count, dp), get_count(N - 1, count, dp))\n elif N % 3 == 0:\n dp[N] = 1 + min(get_count(N // 3, count, dp), get_count(N - 1, count, dp))\n else:\n dp[N] = 1 + get_count(N - 1, count, dp)\n return dp[N]\n dp = [0] * (N + 1)\n return get_count(N, count, dp)", "def minsteps(N):\n if N == 1:\n return 0\n if N == 2 or N == 3:\n return 1\n dp = [0 for i in range(N + 1)]\n dp[2] = 1\n dp[3] = 1\n for i in range(4, N + 1):\n m = float('inf')\n if i % 2 == 0:\n m = min(m, dp[i // 2] + 1)\n if i % 3 == 0:\n m = min(m, dp[i // 3] + 1)\n m = min(m, dp[i - 1] + 1)\n dp[i] = m\n return dp[N]", "def minsteps(N):\n data = [0 for i in range(N + 1)]\n if N < 2:\n return 0\n for i in range(1, N + 1):\n if i % 3 == 0 and i % 2 == 0:\n data[i] = min(data[int(i / 3)], data[int(i / 2)], data[i - 1]) + 1\n elif i % 3 == 0:\n data[i] = min(int(i / 3), min(data[int(i / 3)], data[i - 1]) + 1)\n elif i % 2 == 0:\n data[i] = min(int(i / 2), min(data[int(i / 2)], data[i - 1]) + 1)\n else:\n data[i] = data[i - 1] + 1\n return data[N]", "from sys import maxsize as MAX_VALUE\n\ndef minsteps(n):\n arr = [69 for i in range(n + 1)]\n arr[1] = 0\n i = 2\n while i <= n:\n ans1 = arr[i - 1]\n ans2 = MAX_VALUE\n ans3 = MAX_VALUE\n if i % 2 == 0:\n ans2 = arr[i // 2]\n if i % 3 == 0:\n ans3 = arr[i // 3]\n arr[i] = 1 + min(ans1, ans2, ans3)\n i += 1\n return arr[n]", "from math import inf\n\ndef minsteps(n):\n if n < 1:\n return -1\n hm = dict()\n hm[0] = -1\n hm[1] = 0\n for i in range(2, n + 1):\n op1 = op2 = op3 = inf\n if i % 2 == 0:\n op1 = hm[i // 2] + 1\n if i % 3 == 0:\n op2 = hm[i // 3] + 1\n op3 = hm[i - 1] + 1\n hm[i] = min(op1, op2, op3)\n return hm[n]", "def minsteps(N):\n dp = [2 ** 63] * (N + 1)\n (dp[0], dp[1]) = (0, 0)\n for i in range(2, N + 1):\n if i % 3 == 0 and i % 2 == 0:\n dp[i] = min(dp[i // 2], dp[i // 3], dp[i - 1]) + 1\n elif i % 2 == 0:\n dp[i] = min(dp[i // 2], dp[i - 1]) + 1\n elif i % 3 == 0:\n dp[i] = min(dp[i // 3], dp[i - 1]) + 1\n else:\n dp[i] = dp[i - 1] + 1\n return dp[N]", "def recur(n):\n import sys\n global dp\n if n == 1:\n return 0\n if n < 0:\n return sys.maxsize\n if dp[n]:\n return dp[n]\n t = sys.maxsize\n th = sys.maxsize\n if n % 2 == 0:\n t = 1 + self.recur(n // 2)\n if n % 3 == 0:\n th = 1 + self.recur(n // 3)\n dp[n] = min(min(t, th), 1 + self.recur(n - 1))\n return dp[n]\n\ndef minsteps(N):\n import sys\n dp = [0] * (N + 1)\n for i in range(2, N + 1):\n two = sys.maxsize\n if i % 2 == 0:\n two = 1 + dp[i // 2]\n three = sys.maxsize\n if i % 3 == 0:\n three = 1 + dp[i // 3]\n dp[i] = min(1 + dp[i - 1], min(two, three))\n return dp[-1]", "def recur(n):\n import sys\n global dp\n if n == 1:\n return 0\n if n < 0:\n return sys.maxsize\n if dp[n]:\n return dp[n]\n t = sys.maxsize\n th = sys.maxsize\n if n % 2 == 0:\n t = 1 + self.recur(n // 2)\n if n % 3 == 0:\n th = 1 + self.recur(n // 3)\n dp[n] = min(min(t, th), 1 + self.recur(n - 1))\n return dp[n]\n\ndef minsteps(N):\n global dp\n dp = [0] * (N + 1)\n return self.recur(N)", "def minsteps(N):\n memo = {}\n\n def helper(n):\n if n in memo:\n return memo[n]\n if n == 1:\n return 0\n a = 1 + helper(n - 1)\n c = float('inf')\n b = float('inf')\n if n >= 2 and n % 2 == 0:\n c = 1 + helper(n / 2)\n if n >= 3 and n % 3 == 0:\n b = 1 + helper(n / 3)\n memo[n] = min(a, b, c)\n return memo[n]\n return helper(N)", "def minsteps(N):\n l = [0] * (N + 1)\n for i in range(2, N + 1):\n if i == 2 or i == 3:\n l[i] = 1\n continue\n s1 = s2 = s3 = float('inf')\n if i % 3 == 0:\n s1 = l[i // 3] + 1\n if i % 2 == 0:\n s2 = l[i // 2] + 1\n s3 = l[i - 1] + 1\n l[i] = min(s1, s2, s3)\n return l[-1]", "def minsteps(N):\n if N == 1:\n return 0\n if self.memo[N] != -1:\n return self.memo[N]\n ans = 100000.0\n if N % 2 == 0:\n ans = min(ans, self.minsteps(N // 2))\n if N % 3 == 0:\n ans = min(ans, self.minsteps(N // 3))\n ans = min(ans, self.minsteps(N - 1))\n self.memo[N] = ans + 1\n return self.memo[N]", "def minsteps(n):\n a = [-1 for i in range(n + 1)]\n a[1] = 0\n for i in range(2, n + 1):\n x = a[i - 1]\n y = 1000000\n if i % 2 == 0:\n y = a[i // 2]\n z = 1000000\n if i % 3 == 0:\n z = a[i // 3]\n a[i] = 1 + min(x, y, z)\n return a[n]", "def memo(n):\n global dp\n dp = [-1] * (n + 1)\n\ndef soln(n):\n if n == 0 or n == 1:\n return 0\n if dp[n] != -1:\n return dp[n]\n a = 10 ** 9 + 7\n b = 10 ** 9 + 7\n c = 10 ** 9 + 7\n if dp[n - 1] != -1:\n a = dp[n - 1]\n else:\n dp[n - 1] = self.soln(n - 1)\n a = dp[n - 1]\n if n % 2 == 0:\n if dp[n // 2] != -1:\n b = dp[n // 2]\n else:\n dp[n // 2] = self.soln(n // 2)\n b = dp[n // 2]\n if n % 3 == 0:\n if dp[n // 3] != -1:\n c = dp[n // 3]\n else:\n dp[n // 3] = self.soln(n // 3)\n c = dp[n // 3]\n dp[n] = 1 + min(a, b, c)\n return dp[n]\n\ndef minsteps(N):\n self.memo(N)\n return self.soln(N)", "def minsteps(N):\n n = N\n arr = [0, 0, 1, 1]\n if n < 4:\n return arr[n]\n for i in range(4, n + 1):\n x = float('inf')\n y = float('inf')\n if i % 2 == 0:\n x = arr[i // 2]\n if i % 3 == 0:\n y = arr[i // 3]\n z = i - 1\n arr.append(min(x, y, arr[z]) + 1)\n return arr[n]", "import sys\n\ndef minstep(N, memo):\n if N == 1:\n return 0\n ans1 = sys.maxsize\n if N % 3 == 0:\n if memo[N // 3] == -1:\n ans1 = self.minstep(N // 3, memo)\n memo[N // 3] = ans1\n else:\n ans1 = memo[N // 3]\n ans2 = sys.maxsize\n if N % 2 == 0:\n if memo[N // 2] == -1:\n ans2 = self.minstep(N // 2, memo)\n memo[N // 2] = ans2\n else:\n ans2 = memo[N // 2]\n if memo[N - 1] == -1:\n ans3 = self.minstep(N - 1, memo)\n memo[N - 1] = ans3\n else:\n ans3 = memo[N - 1]\n ans = 1 + min(ans1, ans2, ans3)\n return ans\n\ndef minsteps(N):\n memo = []\n for i in range(N + 1):\n memo.append(-1)\n ans = self.minstep(N, memo)\n return ans", "def minsteps(N):\n dp = [-1 for _ in range(N + 1)]\n return self.dp(N, dp)\n\ndef dp(N, dp):\n if N == 1:\n return 0\n ans1 = sys.maxsize\n if N % 3 == 0:\n if dp[N // 3] == -1:\n ans1 = self.dp(N // 3, dp)\n dp[N // 3] = ans1\n else:\n ans1 = dp[N // 3]\n ans2 = sys.maxsize\n if N % 2 == 0:\n if dp[N // 2] == -1:\n ans2 = self.dp(N // 2, dp)\n dp[N // 2] = ans2\n else:\n ans2 = dp[N // 2]\n if dp[N - 1] == -1:\n ans3 = self.dp(N - 1, dp)\n dp[N - 1] = ans3\n else:\n ans3 = dp[N - 1]\n return 1 + min(ans1, ans2, ans3)", "def minsteps(N):\n if N == 1:\n return 0\n elif N == 2:\n return 1\n elif N == 3:\n return 1\n else:\n arr = [0] * (N + 1)\n arr[0] = 100000\n arr[1] = 1\n arr[2] = 1\n arr[3] = 1\n for i in range(4, N + 1):\n arr[i] = arr[i - 1] + 1\n if i % 2 == 0:\n arr[i] = min(arr[i], arr[int(i / 2)] + 1)\n if i % 3 == 0:\n arr[i] = min(arr[i], arr[int(i / 3)] + 1)\n return arr[N]", "def minsteps(N):\n state = {}\n\n def helper(N, state):\n if N == 1:\n return 0\n if N in state:\n return state[N]\n result = helper(N - 1, state)\n if N % 2 == 0:\n result = min(result, helper(N / 2, state))\n if N % 3 == 0:\n result = min(result, helper(N / 3, state))\n state[N] = 1 + result\n return state[N]\n return helper(N, state)", "def minspteps(n, arr):\n if n == 1:\n return 0\n if arr[n] != 0:\n return arr[n]\n op1 = op2 = op3 = 9999999\n if n % 3 == 0:\n op1 = minspteps(n // 3, arr)\n if n % 2 == 0:\n op2 = minspteps(n // 2, arr)\n op3 = minspteps(n - 1, arr)\n arr[n] = min(op1, op2, op3) + 1\n return arr[n]\n\ndef minsteps(n):\n arr = [0] * (n + 1)\n return minspteps(n, arr)", "def helper(n, dp):\n if n == 1:\n return 0\n if dp[n] != -1:\n return dp[n]\n ans = self.helper(n - 1, dp)\n if n % 2 == 0:\n ans = min(ans, self.helper(n // 2, dp))\n if n % 3 == 0:\n ans = min(ans, self.helper(n // 3, dp))\n dp[n] = 1 + ans\n return dp[n]\n\ndef minsteps(N):\n dp = [-1] * (max(N, 4) + 1)\n dp[1] = 1\n (dp[2], dp[3]) = (1, 1)\n return self.helper(N, dp)", "def dpi(i, mem):\n if i in mem:\n return mem[i]\n if i == 1:\n return 0\n elif i % 3 == 0:\n ans = min(1 + dpi(i // 3, mem), 1 + dpi(i - 1, mem))\n mem[i] = ans\n elif i % 2 == 0:\n ans = min(1 + dpi(i // 2, mem), 1 + dpi(i - 1, mem))\n mem[i] = ans\n else:\n ans = 1 + dpi(i - 1, mem)\n mem[i] = ans\n return ans\n\ndef minsteps(N):\n mem = {}\n return dpi(N, mem)", "def mins(N, lst):\n if N == 2:\n return 1\n else:\n ans = min()\n return lst\n\ndef minsteps(N):\n dp = [0 for i in range(N + 1)]\n dp[1] = 0\n for i in range(2, N + 1):\n if i % 3 == 0:\n dp[i] = min(1 + dp[i // 3], 1 + dp[i - 1])\n elif i % 2 == 0:\n dp[i] = min(1 + dp[i // 2], 1 + dp[i - 1])\n else:\n dp[i] = 1 + dp[i - 1]\n return dp[N]", "import sys\n\ndef minsteps(N):\n dp = [-1] * (N + 1)\n return self.dp(N, dp)\n\ndef dp(N, dp):\n if N == 1:\n return 0\n ans1 = sys.maxsize\n if N % 3 == 0:\n if dp[N // 3] == -1:\n ans1 = self.dp(N // 3, dp)\n dp[N // 3] = ans1\n else:\n ans1 = dp[N // 3]\n ans2 = sys.maxsize\n if N % 2 == 0:\n if dp[N // 2] == -1:\n ans2 = self.dp(N // 2, dp)\n dp[N // 2] = ans2\n else:\n ans2 = dp[N // 2]\n if dp[N - 1] == -1:\n ans3 = self.dp(N - 1, dp)\n dp[N - 1] = ans3\n else:\n ans3 = dp[N - 1]\n return 1 + min(ans1, ans2, ans3)", "from collections import deque\n\ndef minsteps(N):\n step = 0\n q = deque([(N, step)])\n while q:\n (curr, steps) = q.popleft()\n if curr == 1:\n return steps\n if curr % 2 == 0:\n q.append((curr // 2, steps + 1))\n if curr % 3 == 0:\n q.append((curr // 3, steps + 1))\n q.append((curr - 1, steps + 1))"], "starter_code": "def minsteps(N):\n", "input_output": {"inputs": ["N = 10", "N = 1"], "outputs": ["3", "0"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/minimum-steps-to-minimize-n-as-per-given-condition0618/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "minsteps", "task_id": "TACO_lite/243", "example": [[[10], [1]], ["3", "0"]]} +{"requirement": "Given a binary tree and an integer S, check whether there is root to leaf path with its sum as S.\nExample 1:\nInput:\nTree = \n 1\n / \\\n 2 3\nS = 2\nOutput: 0\nExplanation:\nThere is no root to leaf path with sum 2.\nExample 2:\nInput:\nTree = \n 1\n / \\\n 2 3\nS = 4\nOutput: 1\nExplanation:\nThe sum of path from leaf node 3 to root 1 is 4.\nYour Task: \nYou dont need to read input or print anything. Complete the function hasPathSum() which takes root node and target sum S as input parameter and returns true if path exists otherwise it returns false.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(height of tree)\nConstraints:\n1 \u2264 N \u2264 10^4\n1 \u2264 S \u2264 10^6", "solutions": ["def hasPathSum(root, S):\n\n def path(rt, c, s):\n if rt is None:\n return\n if rt.left is None and rt.right is None:\n return s == c + rt.data\n return path(rt.left, c + rt.data, s) or path(rt.right, c + rt.data, s)\n return path(root, 0, S)", "def hasPathSum(root, S):\n\n def fun(root, S):\n sumi = 0\n S = S - root.data\n if root is None:\n return 0\n if root.left is None and root.right is None and (S == 0):\n return 1\n if root.left:\n sumi = sumi or fun(root.left, S)\n if root.right:\n sumi = sumi or fun(root.right, S)\n return sumi\n t = fun(root, S)\n return t", "def inorder(root, S, su):\n if root is None:\n return False\n su += root.data\n if su == S and root.left == None and (root.right == None):\n return True\n if inorder(root.left, S, su) or inorder(root.right, S, su):\n return True\n return False\n\ndef hasPathSum(root, S):\n su = 0\n return inorder(root, S, su)", "def check(root, S, a):\n if root == None:\n return False\n a += root.data\n if a == S and root.left == None and (root.right == None):\n return True\n if check(root.left, S, a) or check(root.right, S, a):\n return True\n return False\n\ndef __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef hasPathSum(root, S):\n a = 0\n return check(root, S, a)", "def tree(root, S, ans):\n if root == None:\n return False\n ans += root.data\n if ans == S and root.left == None and (root.right == None):\n return True\n if tree(root.left, S, ans) or tree(root.right, S, ans):\n return True\n return False\n\ndef hasPathSum(root, S):\n ans = 0\n if tree(root, S, ans):\n return 1\n return 0", "def hasPathSum(root, S):\n if root == None:\n return 0\n subsum = S - root.data\n if subsum == 0 and root.left == None and (root.right == None):\n return True\n return self.hasPathSum(root.left, subsum) or self.hasPathSum(root.right, subsum)", "def hasPathSum(root, S):\n\n def dfs(node, currsum):\n if not node:\n return False\n currsum += node.data\n if not node.left and (not node.right):\n return currsum == S\n return dfs(node.left, currsum) or dfs(node.right, currsum)\n return dfs(root, 0)", "def hasPathSum(root, S):\n\n def dfs(root, sumi):\n if root is None:\n return False\n sumi += root.data\n if root.left is None and root.right is None:\n return sumi == S\n return dfs(root.left, sumi) or dfs(root.right, sumi)\n return dfs(root, 0)", "def fun(root, s, S):\n if root == None:\n return\n s += root.data\n if s > S:\n return\n if s == S:\n if root.left == None and root.right == None:\n self.res = 1\n else:\n return\n self.fun(root.left, s, S)\n self.fun(root.right, s, S)\n\ndef hasPathSum(root, S):\n self.fun(root, 0, S)\n return self.res", "def hasPathSum(root, S):\n if root is None:\n return False\n if root.left is None and root.right is None and (root.data == S):\n return True\n else:\n return self.hasPathSum(root.left, S - root.data) or self.hasPathSum(root.right, S - root.data)", "def hasPathSum(root, S):\n\n def dfs(root, s):\n if root == None:\n return False\n if root.left == None and root.right == None:\n if s - root.data == 0:\n return True\n return False\n return dfs(root.left, s - root.data) or dfs(root.right, s - root.data)\n return dfs(root, S)", "def hasPathSum(root, S):\n\n def path(root, currSum):\n if not root:\n return False\n currSum += root.data\n if not root.left and (not root.right) and (currSum == S):\n return True\n return path(root.left, currSum) or path(root.right, currSum)\n return path(root, 0)", "def solve(root, S):\n if root == None:\n return False\n if root.left == None and root.right == None:\n S -= root.data\n if S == 0:\n return True\n else:\n return False\n l = self.solve(root.left, S - root.data)\n if l == True:\n return True\n r = self.solve(root.right, S - root.data)\n if r == True:\n return True\n return False\n\ndef hasPathSum(root, S):\n return self.solve(root, S)", "def hasPathSum(root, S):\n global b\n b = False\n\n def finder(root, c):\n global b\n if root == None:\n return\n c += root.data\n if c == S and root.left == None and (root.right == None):\n b = True\n return\n if c > S:\n return\n finder(root.left, c)\n finder(root.right, c)\n finder(root, 0)\n return b", "def hasPathSum(root, S):\n\n def helper(root, add):\n if not root:\n return\n add += root.data\n if root.left is None and root.right is None:\n return add == S\n return helper(root.left, add) or helper(root.right, add)\n return helper(root, 0)", "def hasPathSum(root, S):\n\n def rec(root, d):\n if root.left == None and root.right == None:\n if d + root.data == S:\n return True\n return False\n t1 = False\n t2 = False\n if root.left:\n t1 = rec(root.left, d + root.data)\n if root.right:\n t2 = rec(root.right, d + root.data)\n return t1 or t2\n return rec(root, 0)", "def hasPathSum(root, S):\n\n def hasPathSum(node, s):\n ans = 0\n subSum = s - node.data\n if subSum == 0 and node.left == None and (node.right == None):\n return True\n if node.left is not None:\n ans = ans or hasPathSum(node.left, subSum)\n if node.right is not None:\n ans = ans or hasPathSum(node.right, subSum)\n return ans\n return hasPathSum(root, S)", "def hasPathSum(node, s):\n if node is None:\n return s == 0\n else:\n ans = 0\n subSum = s - node.data\n if subSum == 0 and node.left == None and (node.right == None):\n return True\n if node.left:\n ans = ans or self.hasPathSum(node.left, subSum)\n if node.right:\n ans = ans or self.hasPathSum(node.right, subSum)\n return ans", "def hasPathSum(root, S):\n\n def helper(root, target, value):\n if not root:\n return False\n if not root.left and (not root.right):\n return target == value + root.data\n return helper(root.left, target, value + root.data) or helper(root.right, target, value + root.data)\n return helper(root, S, 0)", "def solution(root, s, arr):\n if root == None:\n return False\n arr += root.data\n if arr == s and root.left is None and (root.right is None):\n return True\n l = self.solution(root.left, s, arr)\n if l:\n return True\n r = self.solution(root.right, s, arr)\n if r:\n return True\n arr -= root.data\n return False\n\ndef hasPathSum(root, S):\n if root == None:\n return 1\n arr = 0\n if self.solution(root, S, arr):\n return 1\n return 0", "def hasPathSum(root, S):\n if root == None:\n return 0\n if S == root.data and root.left == None and (root.right == None):\n return 1\n return self.hasPathSum(root.left, S - root.data) or self.hasPathSum(root.right, S - root.data)", "def hasPathSum(root, S):\n sum = set()\n\n def dfs(root, sum_):\n if not root:\n return\n sum_ += root.data\n if root.left or root.right:\n dfs(root.left, sum_)\n dfs(root.right, sum_)\n else:\n sum.add(sum_)\n dfs(root, 0)\n if S in sum:\n return True\n return False"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["Tree = \n 1\n / \\\n 2 3\nS = 2", "Tree = \n 1\n / \\\n 2 3\nS = 4"], "outputs": ["0", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/root-to-leaf-path-sum/1", "Expected Auxiliary Space": "O(height of tree)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "__init__", "task_id": "TACO_lite/126", "example": [[], []]} +{"requirement": "Given an array arr[] of integers of size N and a number X, the task is to find the sum of subarray having maximum sum less than or equal to the given value of X.\nExample 1:\nInput: N = 5, X = 11\narr[] = {1, 2, 3, 4, 5} \nOutput: 10\nExplanation: Subarray having maximum \nsum is {1, 2, 3, 4}.\n \nExample 2:\nInput: N = 5, X = 7\narr[] = {2, 4, 6, 8, 10} \nOutput: 6\nExplanation: Subarray having maximum \nsum is {2, 4} or {6}.\n \nYour Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function calculateMaxSumLength() that takes array arr, integer N, and integer X as parameters and returns maximum sum of any subarray that is less than or equal to x.\n \nExpected Time Complexity: O(N). \nExpected Auxiliary Space: O(1).\n \nConstraints:\n1 \u2264 N \u2264 10^{6}\n1 \u2264 arr[i] \u2264 10^{4}", "solutions": ["def findmaxsubarraysum(arr, n, k):\n sum = 0\n ans = 0\n (i, j) = (0, 0)\n while j < n:\n sum += arr[j]\n if sum < k:\n ans = max(ans, sum)\n j += 1\n elif sum == k:\n return k\n else:\n while sum > k:\n sum -= arr[i]\n i += 1\n ans = max(ans, sum)\n j += 1\n return ans", "def findmaxsubarraysum(arr, n, k):\n max1 = 0\n s = 0\n i = 0\n j = 0\n while i < n:\n s += arr[i]\n if s > k:\n while s > k:\n s -= arr[j]\n j += 1\n max1 = max(max1, s)\n i += 1\n max1 = max(max1, s)\n return max1", "def findmaxsubarraysum(arr, n, k):\n (ans, cur) = (0, 0)\n (fp, sp) = (0, 0)\n while sp < n:\n if cur <= k:\n cur += arr[sp]\n while cur > k and fp <= sp:\n cur -= arr[fp]\n fp += 1\n sp += 1\n ans = max(ans, cur)\n return ans", "import math\n\ndef findmaxsubarraysum(arr, n, k):\n maxi = -math.inf\n fsum = 0\n left = 0\n for i in range(n):\n fsum += arr[i]\n while fsum > k:\n fsum -= arr[left]\n left += 1\n maxi = max(maxi, fsum)\n return maxi", "def findmaxsubarraysum(arr, n, k):\n left = 0\n maxi = 0\n su = 0\n for right in range(0, n):\n su += arr[right]\n while su > k:\n su -= arr[left]\n left += 1\n maxi = max(maxi, su)\n return maxi", "def findmaxsubarraysum(arr, n, k):\n maxSum = 0\n (head, tail) = (0, 0)\n maxVal = -1\n while tail < n:\n maxSum += arr[tail]\n if maxSum == k:\n return k\n elif maxSum > k:\n while head <= tail:\n maxSum -= arr[head]\n head = head + 1\n if maxSum == k:\n return k\n elif maxSum < k:\n maxVal = max(maxVal, maxSum)\n break\n else:\n maxVal = max(maxVal, maxSum)\n tail += 1\n return maxVal", "def findmaxsubarraysum(arr, n, k):\n max_sum = float('-inf')\n curr_sum = 0\n i = 0\n j = 0\n while j < n:\n curr_sum += arr[j]\n if curr_sum <= k:\n max_sum = max(max_sum, curr_sum)\n else:\n while curr_sum > k:\n curr_sum -= arr[i]\n if curr_sum <= k:\n max_sum = max(max_sum, curr_sum)\n i += 1\n j += 1\n return max_sum", "def findmaxsubarraysum(arr, n, k):\n maxi = float('-inf')\n i = 0\n j = 0\n pre = 0\n while i < n:\n pre += arr[i]\n if pre <= k:\n maxi = max(pre, maxi)\n else:\n while pre > k and j <= i:\n pre -= arr[j]\n j += 1\n if pre <= k:\n maxi = max(maxi, pre)\n i += 1\n return maxi", "def findmaxsubarraysum(arr, n, k):\n maxi = 0\n total = arr[0]\n (start, end) = (0, 0)\n while start < n and end < n:\n if total <= k:\n maxi = max(maxi, total)\n end += 1\n if end < n:\n total += arr[end]\n else:\n total -= arr[start]\n start += 1\n return maxi", "def findmaxsubarraysum(arr, n, k):\n subasum = arr[0]\n sum = 0\n for i in range(0, n):\n subasum = arr[i]\n if subasum < k:\n sum = max(subasum, sum)\n elif subasum == k:\n return subasum\n for j in range(i + 1, n):\n subasum = subasum + arr[j]\n if subasum < k:\n sum = max(subasum, sum)\n elif subasum == k:\n return subasum\n elif subasum > k:\n break\n return sum", "def findmaxsubarraysum(arr, n, k):\n i = 0\n j = 0\n summ = 0\n maxi = -1000000007\n while i < n:\n summ += arr[i]\n if summ <= k:\n maxi = max(maxi, summ)\n else:\n while summ > k and j <= i:\n summ -= arr[j]\n j += 1\n if summ <= k:\n maxi = max(maxi, summ)\n i += 1\n return maxi", "def findmaxsubarraysum(arr, n, k):\n maxi = 0\n summa = 0\n j = 0\n for item in arr:\n while j < n and summa + arr[j] <= k:\n summa += arr[j]\n maxi = max(maxi, summa)\n j += 1\n summa -= item\n return maxi", "def findmaxsubarraysum(arr, n, k):\n left = 0\n s = 0\n m = 0\n for right in range(n):\n s += arr[right]\n if s <= k:\n m = max(s, m)\n else:\n while s > k and left <= right:\n s -= arr[left]\n left += 1\n if s <= k:\n m = max(m, s)\n return m", "def findmaxsubarraysum(arr, n, k):\n a = -1\n sum = 0\n s = 0\n for i in range(n):\n sum += arr[i]\n while sum > k:\n sum -= arr[s]\n s = s + 1\n else:\n a = max(a, sum)\n return a", "def findmaxsubarraysum(arr, n, k):\n i = 0\n j = 0\n sumi = 0\n maxi = 0\n while j < len(arr):\n sumi = sumi + arr[j]\n if sumi <= k:\n maxi = max(maxi, sumi)\n while sumi > k:\n sumi = sumi - arr[i]\n if sumi <= k:\n maxi = max(maxi, sumi)\n i = i + 1\n j = j + 1\n return maxi", "def findmaxsubarraysum(a, n, x):\n for i in a:\n assert i > 0 and i <= 10 ** 4\n if sum(a) <= x:\n return sum(a)\n total = 0\n ans = -1\n start = 0\n for i in range(n + 1):\n while total > x and start < i - 1:\n total -= a[start]\n start += 1\n if total < x:\n ans = max(ans, total)\n elif total == x:\n return x\n if i < n:\n total += a[i]\n return ans", "def findmaxsubarraysum(arr, n, k):\n l = r = 0\n ma = 0\n cu = arr[0]\n while r < n:\n if cu <= k:\n ma = max(ma, cu)\n r += 1\n if r < n:\n cu += arr[r]\n if cu > k:\n cu -= arr[l]\n l += 1\n return ma", "def findmaxsubarraysum(arr, n, k):\n res = float('-inf')\n s = 0\n j = 0\n for i in range(n):\n s += arr[i]\n if s > k:\n while j <= i and s > k:\n s -= arr[j]\n j += 1\n if s <= k:\n res = max(res, s)\n if res == k:\n return k\n if res != float('-inf'):\n return res\n return -1", "def findmaxsubarraysum(arr, n, k):\n i = 0\n sums = 0\n maxi = 0\n for j in range(n):\n sums += arr[j]\n if sums <= k:\n maxi = max(maxi, sums)\n while sums > k:\n sums -= arr[i]\n i += 1\n if sums <= k:\n maxi = max(maxi, sums)\n return maxi", "def findmaxsubarraysum(arr, n, k):\n start = 0\n tot = 0\n res = 0\n for end in range(n):\n tot += arr[end]\n while tot > k:\n tot -= arr[start]\n start += 1\n res = max(res, tot)\n return res", "def findmaxsubarraysum(arr, n, k):\n currSum = 0\n start = 0\n maxSum = 0\n for i in range(n):\n currSum += arr[i]\n while currSum > k:\n currSum -= arr[start]\n start += 1\n maxSum = max(maxSum, currSum)\n return maxSum", "def findmaxsubarraysum(arr, n, k):\n sumi = 0\n res = 0\n j = 0\n for i in range(n):\n sumi += arr[i]\n while k < sumi:\n sumi -= arr[j]\n j += 1\n if sumi <= k:\n res = max(res, sumi)\n return res", "def findmaxsubarraysum(arr, n, k):\n c = 0\n s = 0\n res = 0\n for i in range(n):\n s = s + arr[i]\n while s > k:\n s = s - arr[c]\n c = c + 1\n res = max(s, res)\n return res", "def findmaxsubarraysum(arr, n, k):\n ws = 0\n we = 0\n res = 0\n sumi = 0\n for we in range(n):\n sumi += arr[we]\n while sumi > k:\n sumi -= arr[ws]\n ws += 1\n if sumi <= k:\n res = max(res, sumi)\n return res", "def findmaxsubarraysum(arr, n, k):\n i = 0\n j = 1\n currSum = arr[0]\n maxSum = 0\n while i <= j and j < n:\n if currSum <= k:\n maxSum = max(maxSum, currSum)\n while currSum + arr[j] > k and i < j:\n currSum -= arr[i]\n i += 1\n currSum += arr[j]\n j += 1\n if currSum <= k:\n maxSum = max(maxSum, currSum)\n return maxSum", "def findmaxsubarraysum(arr, n, k):\n currsum = arr[0]\n start = 0\n maxsum = 0\n if n == 1:\n if arr[0] <= k:\n return arr[0]\n else:\n return 0\n for i in range(1, n):\n if currsum <= k:\n maxsum = max(maxsum, currsum)\n while currsum + arr[i] > k and start < i:\n currsum = currsum - arr[start]\n start = start + 1\n currsum = currsum + arr[i]\n if currsum <= k:\n maxsum = max(maxsum, currsum)\n return maxsum", "def findmaxsubarraysum(arr, n, k):\n j = 0\n Maxlen = 0\n Sum = 0\n for i in range(n):\n Sum += arr[i]\n while Sum > k:\n Sum -= arr[j]\n j += 1\n Maxlen = max(Sum, Maxlen)\n return Maxlen", "def findmaxsubarraysum(arr, n, k):\n ans = 0\n sm = 0\n s = 0\n for e in range(n):\n sm += arr[e]\n while sm > k and s < e:\n sm -= arr[s]\n s += 1\n if sm <= k:\n ans = max(ans, sm)\n return ans", "def findmaxsubarraysum(arr, n, k):\n ans = 0\n s = 0\n j = 0\n for i in range(n):\n s += arr[i]\n while s > k:\n s -= arr[j]\n j += 1\n ans = max(ans, s)\n return ans", "def findmaxsubarraysum(arr, n, k):\n start = 0\n total = 0\n curr_sum = 0\n for i in range(n):\n if curr_sum <= k:\n total = max(total, curr_sum)\n while curr_sum + arr[i] > k and start < i:\n curr_sum -= arr[start]\n start += 1\n curr_sum += arr[i]\n if curr_sum <= k:\n total = max(total, curr_sum)\n return total", "def findmaxsubarraysum(arr, n, k):\n if k in arr:\n return k\n (maxx, summ) = (0, 0)\n j = 0\n for i in range(n):\n summ += arr[i]\n if summ > k:\n while summ > k:\n summ -= arr[j]\n j += 1\n if summ <= k:\n maxx = max(summ, maxx)\n return maxx", "def findmaxsubarraysum(arr, n, k):\n l = 0\n sum1 = 0\n maxi = 0\n for r in range(n):\n sum1 += arr[r]\n while sum1 > k:\n maxi = max(maxi, sum(arr[l:r]))\n sum1 -= arr[l]\n l += 1\n maxi = max(maxi, sum1)\n return maxi", "def findmaxsubarraysum(arr, n, k):\n i = 0\n j = 0\n s = 0\n d = -999999999\n while j < n:\n s += arr[j]\n if s <= k and s > d:\n d = s\n while s > k:\n s = s - arr[i]\n i += 1\n if s <= k and s > d:\n d = s\n j += 1\n return d", "import sys\n\ndef findmaxsubarraysum(arr, n, k):\n (start, end, curr_sum, max_sum) = (0, 0, 0, -sys.maxsize)\n while end < n:\n curr_sum = curr_sum + arr[end]\n while start <= end and curr_sum > k:\n curr_sum = curr_sum - arr[start]\n start = start + 1\n max_sum = max(curr_sum, max_sum)\n end = end + 1\n return max_sum", "def findmaxsubarraysum(arr, n, k):\n count = 0\n ans = -1 << 32\n left = right = cur = 0\n while right < n:\n cur += arr[right]\n while cur > k:\n cur -= arr[left]\n left += 1\n ans = max(ans, cur)\n right += 1\n return ans", "def findmaxsubarraysum(arr, n, k):\n i = 0\n j = 0\n mx = float('-inf')\n sum = 0\n while j < n:\n sum += arr[j]\n while sum > k:\n sum -= arr[i]\n i += 1\n mx = max(sum, mx)\n j += 1\n return mx", "def findmaxsubarraysum(arr, n, k):\n curr_sum = 0\n max_sum = -12345678\n start = 0\n for i in range(n):\n curr_sum += arr[i]\n while curr_sum > k:\n curr_sum = curr_sum - arr[start]\n start += 1\n max_sum = max(max_sum, curr_sum)\n return max_sum", "def findmaxsubarraysum(C, n, B):\n sum = 0\n ans = 0\n start = 0\n end = 0\n while end < len(C):\n sum += C[end]\n if sum <= B:\n ans = max(ans, sum)\n elif sum > B:\n while sum > B:\n sum = sum - C[start]\n start += 1\n ans = max(ans, sum)\n end += 1\n return ans", "def findmaxsubarraysum(arr, n, k):\n currsum = 0\n maxSum = 0\n (i, j) = (0, 0)\n while j < len(arr):\n currsum += arr[j]\n if currsum > k:\n while currsum > k:\n currsum -= arr[i]\n i += 1\n maxSum = max(maxSum, currsum)\n j += 1\n return maxSum", "def findmaxsubarraysum(arr, n, k):\n start = 0\n s = 0\n end = 0\n a = []\n for end in range(n):\n s = s + arr[end]\n while s > k:\n s = s - arr[start]\n start = start + 1\n else:\n a.append(s)\n a.sort()\n return a[-1]", "def findmaxsubarraysum(arr, n, k):\n (i, j) = (0, 0)\n res = 0\n summ = 0\n while j < n:\n summ += arr[j]\n while i <= j and summ > k:\n summ -= arr[i]\n i += 1\n res = max(res, summ)\n j += 1\n return res", "def findmaxsubarraysum(arr, n, k):\n curr = arr[0]\n maxx = 0\n start = 0\n for i in range(1, n):\n if curr <= k:\n maxx = max(curr, maxx)\n while curr + arr[i] > k and start < i:\n curr -= arr[start]\n start += 1\n curr += arr[i]\n if curr <= k:\n maxx = max(curr, maxx)\n return maxx", "def findmaxsubarraysum(arr, n, k):\n currSum = 0\n ws = 0\n maxSum = 0\n for we in range(n):\n currSum += arr[we]\n while currSum > k and ws <= we:\n currSum -= arr[ws]\n ws += 1\n if currSum > maxSum and currSum <= k:\n maxSum = currSum\n return maxSum", "def findmaxsubarraysum(arr, n, k):\n s = 0\n mx = min(arr)\n i = 0\n j = 0\n while j < len(arr):\n s += arr[j]\n while s > k:\n s -= arr[i]\n i += 1\n mx = max(s, mx)\n j += 1\n if mx > k:\n return 0\n return mx", "def findmaxsubarraysum(arr, n, k):\n i = 0\n j = 0\n Sum = 0\n mx = 0\n while j < n:\n Sum = Sum + arr[j]\n if Sum <= k:\n j = j + 1\n mx = max(mx, Sum)\n elif Sum > k:\n while Sum > k:\n Sum = Sum - arr[i]\n i = i + 1\n if Sum <= k:\n mx = max(mx, Sum)\n j = j + 1\n return mx", "def findmaxsubarraysum(arr, n, k):\n i = 0\n j = 0\n maxsum = 0\n tempsum = 0\n while j != n:\n tempsum += arr[j]\n j += 1\n while tempsum > k:\n tempsum -= arr[i]\n i += 1\n maxsum = max(maxsum, tempsum)\n return maxsum", "def findmaxsubarraysum(arr, n, k):\n startIndex = 0\n currentSum = 0\n maxSum = 0\n for endIndex in range(0, n):\n if currentSum <= k:\n maxSum = max(maxSum, currentSum)\n while currentSum + arr[endIndex] > k and startIndex < n:\n currentSum -= arr[startIndex]\n startIndex += 1\n currentSum += arr[endIndex]\n if currentSum <= k:\n maxSum = max(maxSum, currentSum)\n return maxSum", "def findmaxsubarraysum(arr, n, sum):\n curr_sum = arr[0]\n max_sum = 0\n start = 0\n for i in range(1, n):\n if curr_sum <= sum:\n max_sum = max(max_sum, curr_sum)\n while curr_sum + arr[i] > sum and start < i:\n curr_sum -= arr[start]\n start += 1\n curr_sum += arr[i]\n if curr_sum <= sum:\n max_sum = max(max_sum, curr_sum)\n return max_sum", "def findmaxsubarraysum(arr, n, k):\n maxi = 0\n a = []\n currentsum = 0\n index = 0\n while index < n:\n currentsum += arr[index]\n a.append(arr[index])\n if currentsum <= k:\n maxi = max(maxi, currentsum)\n else:\n while currentsum > k:\n if len(a) == 0:\n break\n currentsum -= a[0]\n a.pop(0)\n maxi = max(maxi, currentsum)\n index += 1\n return maxi", "def findmaxsubarraysum(a, n, k):\n i = 0\n j = 0\n sa = 0\n ma = float('-inf')\n while j < n:\n sa += a[j]\n if sa <= k:\n ma = max(ma, sa)\n elif sa > k:\n while sa > k:\n sa -= a[i]\n i += 1\n if sa <= k:\n ma = max(ma, sa)\n j += 1\n return ma", "def findmaxsubarraysum(arr, n, k):\n right = 0\n left = -1\n add = 0\n max_val = 0\n while right < n:\n if add + arr[right] < k:\n add += arr[right]\n max_val = max(max_val, add)\n right += 1\n elif add + arr[right] == k:\n return k\n else:\n left += 1\n right = left\n add = 0\n return max_val", "def findmaxsubarraysum(arr, n, x):\n slow = 0\n fast = 0\n total = 0\n maxer = 0\n while fast < len(arr):\n total += arr[fast]\n if total <= x:\n maxer = max(maxer, total)\n elif total > x:\n while total > x:\n total -= arr[slow]\n slow += 1\n if total <= x:\n maxer = max(maxer, total)\n fast += 1\n return maxer", "def findmaxsubarraysum(arr, n, k):\n (cur_sum, max_sum) = (0, -10 ** 9)\n l = 0\n for i in range(n):\n cur_sum += arr[i]\n while l <= i and cur_sum > k:\n cur_sum -= arr[l]\n l += 1\n max_sum = max(max_sum, cur_sum)\n return max_sum", "def findmaxsubarraysum(arr, n, k):\n for i in range(1, n):\n arr[i] = arr[i - 1] + arr[i]\n x = 0\n y = 0\n max_val = -9223372036854775806\n while x < n:\n if arr[x] <= k:\n max_val = max(max_val, arr[x])\n else:\n while arr[x] - arr[y] > k and x > y:\n y += 1\n max_val = max(max_val, arr[x] - arr[y])\n x += 1\n if max_val == k:\n return k\n return max_val"], "starter_code": "def findmaxsubarraysum(arr, n, k):\n", "input_output": {"inputs": ["N = 5, X = 11\r\narr[] = {1, 2, 3, 4, 5}", "N = 5, X = 7\r\narr[] = {2, 4, 6, 8, 10}"], "outputs": ["10", "6"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "two-pointer-algorithm", "sliding-window", "Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Amortized analysis"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/maximum-sum-of-subarray-less-than-or-equal-to-x4033/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "findmaxsubarraysum", "task_id": "TACO_lite/112", "example": [[[5, 11, [1, 2, 3, 4, 5]], [5, 7, [2, 4, 6, 8, 10]]], [null, null]]} +{"requirement": "Your task is very simple. Just write a function `isAlphabetic(s)`, which takes an input string `s` in lowercase and returns `true`/`false` depending on whether the string is in alphabetical order or not.\n\nFor example, `isAlphabetic('kata')` is False as 'a' comes after 'k', but `isAlphabetic('ant')` is True.\n\nGood luck :)", "solutions": ["def alphabetic(s):\n return sorted(s) == list(s)", "def alphabetic(s):\n return all((a <= b for (a, b) in zip(s, s[1:])))", "def alphabetic(s):\n for i in range(1, len(s)):\n if s[i - 1] > s[i]:\n return False\n return True", "def alphabetic(s):\n return s == ''.join(sorted(s))", "def alphabetic(string):\n return string == ''.join(sorted(string))", "def alphabetic(s):\n n = len(s)\n c = [s[i] for i in range(len(s))]\n c.sort(reverse=False)\n for i in range(n):\n if c[i] != s[i]:\n return False\n return True", "def alphabetic(s):\n arr = [x for x in s]\n return arr == sorted(arr)", "alphabetic = lambda str: sorted(str) == list(str)"], "starter_code": "def alphabetic(s):\n", "input_output": {"fn_name": "alphabetic", "inputs": [["asd"], ["codewars"], ["door"], ["cell"], ["z"], [""]], "outputs": [[false], [false], [true], [true], [true], [true]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5a8059b1fd577709860000f6", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "alphabetic", "task_id": "TACO_lite/226", "example": [[["kata"], ["ant"]], ["False", "True"]]} +{"requirement": "Given a number N find the sum of all the even valued terms in the Fibonacci sequence less than or equal to N.\nThe first few terms of Fibonacci Numbers are, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ,\u2026 (Even numbers are highlighted).\n \nExample 1:\nInput:\nN = 8\nOutput:\n10\nExplanation:\nThere are two even \nfibonacci numbers less\nthan equal to 8, 8 and 2 \nand 8 + 2 = 10\nExample 2:\nInput:\nN = 89\nOutput:\n44\nExplanation:\nThere are three even\nfibonacci numbers less than\nequal to 89, 8, 2 and 34 \n8 + 2 + 34 = 44\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function evenFibSum() which takes an integer N as input parameters and returns the sum of all the Fibonacci number less than equal to N.\n \nExpected Time Complexity: O(N)\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= N <= 10^{6}", "solutions": ["def fib(n, memo={}):\n if n in memo:\n return memo[n]\n elif n < 3:\n memo[n] = 1\n else:\n memo[n] = fib(n - 1) + fib(n - 2)\n return memo[n]\n\ndef evenfibsum(N):\n n = 1\n curr_fib_num = 0\n sum = 0\n while curr_fib_num <= N:\n sum += curr_fib_num\n curr_fib_num = fib(3 * n)\n n += 1\n return sum", "def evenfibsum(N):\n a = 0\n b = 1\n c = 0\n s = 0\n if N == 0 or N == 1:\n return 0\n for i in range(2, N + 1):\n c = a + b\n if c > N:\n break\n elif c % 2 == 0:\n s = s + c\n a = b\n b = c\n return s", "def evenfibsum(N):\n a = 0\n b = 1\n s = 0\n c = 0\n while c < N:\n c = a + b\n a = b\n b = c\n if b % 2 == 0 and b < N:\n s = s + b\n return s", "def evenfibsum(N):\n (n1, n2) = (1, 2)\n sum = 2\n while True:\n n3 = n1 + n2\n if n3 > N:\n break\n if n3 % 2 == 0:\n sum += n3\n n1 = n2\n n2 = n3\n return sum", "def evenfibsum(N):\n (a, b, c, summ) = (1, 1, 1, 0)\n mod = 10 ** 9 + 7\n while c <= N:\n c = (a + b) % mod\n if N >= c and c & 1 == 0:\n summ += c\n (a, b) = (b, c)\n return summ", "def evenfibsum(N):\n (a, b, c, s, i) = (1, 2, 2, 2, 0)\n m = 10 ** 9 + 7\n while N >= c:\n c = a + b\n a = b\n b = c\n if N >= c and c % 2 == 0:\n s += c\n i += 1\n return s", "def evenfibsum(N):\n if N < 2:\n return 0\n ef1 = 0\n ef2 = 2\n sm = ef1 + ef2\n while N > 2:\n ef3 = 4 * ef2 + ef1\n if ef3 > N:\n break\n ef1 = ef2\n ef2 = ef3\n sm = sm + ef2\n return sm", "def evenfibsum(n):\n k = []\n a = 0\n b = 1\n s = 0\n while a <= n:\n c = a + b\n if a % 2 == 0:\n s += a\n a = b\n b = c\n return s", "def evenfibsum(N):\n a = 0\n b = 1\n c = 0\n l = []\n s = 0\n while a <= N:\n if a & 1 == 0 and a <= N:\n s = s + a\n l.append(a)\n c = a + b\n a = b\n b = c\n return s", "def evenfibsum(N):\n f = [0, 1]\n arr = []\n for i in range(2, N):\n if f[i - 1] + f[i - 2] <= N:\n f.append(f[i - 1] + f[i - 2])\n if (f[i - 1] + f[i - 2]) % 2 == 0:\n arr.append(f[i - 1] + f[i - 2])\n else:\n break\n return sum(arr)", "def evenfibsum(N):\n if N < 2:\n return 0\n ans = 0\n a = 0\n b = 1\n for i in range(1000):\n c = a + b\n if c > N:\n break\n if c % 2 == 0:\n ans += c\n a = b\n b = c\n return ans", "def evenfibsum(N):\n ret = []\n ret.append(0)\n ret.append(1)\n summ = 0\n for i in range(2, N + 1):\n ret.append(ret[0] + ret[1])\n if ret[-1] > N:\n break\n if ret[-1] % 2 == 0:\n summ += ret[-1]\n ret.pop(0)\n return summ", "def evenfibsum(N):\n fib1 = 0\n fib2 = 2\n sum = fib1 + fib2\n if N <= 2:\n return 0\n while fib2 <= N:\n fib3 = 4 * fib2 + fib1\n if fib3 > N:\n break\n fib1 = fib2\n fib2 = fib3\n sum += fib2\n return sum", "def evenfibsum(N):\n sum = 0\n f = [1, 1]\n while f[1] < N:\n v = f[0] + f[1]\n if v % 2 == 0 and v <= N:\n sum += f[0] + f[1]\n (f[0], f[1]) = (f[1], f[0] + f[1])\n return sum", "def evenfibsum(N):\n evenSum = 0\n first = 1\n second = 1\n while N >= second:\n third = first + second\n if second % 2 == 0:\n evenSum += second\n first = second\n second = third\n return evenSum", "def evenfibsum(n):\n S = 0\n x = 0\n y = 1\n res = 0\n while res <= n:\n res = x + y\n if res % 2 == 0:\n S = S + res\n x = y\n y = res\n if res > n and res % 2 == 0:\n S = S - res\n return S", "def evenfibsum(N):\n a = 1\n b = 1\n s = 0\n while b <= N:\n temp = a\n a = b\n b = temp + b\n if b <= N:\n if b % 2 == 0:\n s += b\n return s", "def evenfibsum(N):\n (a, b, val) = (1, 1, 0)\n while b <= N:\n if b % 2 == 0:\n val += b\n (a, b) = (b, a + b)\n return val"], "starter_code": "def evenfibsum (N):\n", "input_output": {"inputs": ["N = 8", "N = 89"], "outputs": ["10", "44"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/even-fibonacci-numbers-sum1455/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "evenfibsum", "task_id": "TACO_lite/247", "example": [[[8], [89]], ["10", "44"]]} +{"requirement": "Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.\n\nExample 1:\n\n\nInput: 123\nOutput: \"One Hundred Twenty Three\"\n\n\nExample 2:\n\n\nInput: 12345\nOutput: \"Twelve Thousand Three Hundred Forty Five\"\n\nExample 3:\n\n\nInput: 1234567\nOutput: \"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven\"\n\n\nExample 4:\n\n\nInput: 1234567891\nOutput: \"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One\"", "solutions": ["def numbertowords(num):\n if num == 0:\n return 'Zero'\n answer = self.convert_hundred(num % 1000)\n for i in range(3):\n num //= 1000\n if num % 1000 > 0:\n following = ' ' + answer if answer else ''\n answer = self.convert_hundred(num % 1000) + ' ' + self.V3[i] + following\n return answer\n\ndef convert_hundred(num):\n answer = ''\n a = num // 100\n b = num % 100\n c = num % 10\n if b < 20:\n answer = self.V1[b]\n else:\n following = ' ' + self.V1[c] if c > 0 else ''\n answer = self.V2[b // 10] + following\n if a > 0:\n following = ' ' + answer if answer else ''\n answer = self.V1[a] + ' Hundred' + following\n return answer", "def parseHundred(n):\n to19 = 'One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split()\n tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split()\n if n == 0:\n return ''\n w = ''\n while n > 0:\n if n > 99:\n digit = n // 100\n w += to19[digit - 1] + ' ' + 'Hundred'\n n = n % 100\n if n != 0:\n w += ' '\n elif n <= 19:\n w += to19[n - 1]\n n = 0\n else:\n digit = n // 10\n w += tens[digit - 2]\n n = n % 10\n if n != 0:\n w += ' '\n return w\n\ndef numbertowords(num):\n thousands = ['', ' Thousand ', ' Million ', ' Billion ']\n i = 0\n w = ''\n if num == 0:\n return 'Zero'\n while num > 0:\n digits = num % 1000\n if digits != 0:\n w = self.parseHundred(digits) + thousands[i] + w\n num = num // 1000\n i += 1\n return w.strip()", "def __init__():\n self.twenties = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']\n self.tens = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']\n self.thousands = ['', 'Thousand', 'Million', 'Billion']\n\ndef numbertowords(num):\n if num == 0:\n return 'Zero'\n result = ''\n for i in range(len(self.thousands)):\n if num % 1000 != 0:\n result = self.helper(num % 1000) + self.thousands[i] + ' ' + result\n num //= 1000\n return result.strip()\n\ndef helper(num):\n if num == 0:\n return ''\n elif num < 20:\n return self.twenties[num] + ' '\n elif num < 100:\n return self.tens[num // 10] + ' ' + self.helper(num % 10)\n else:\n return self.twenties[num // 100] + ' Hundred ' + self.helper(num % 100)", "def numbertowords(num):\n\n def translate(num):\n if num == 0:\n return ''\n less20 = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']\n more20 = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']\n res = ''\n if num // 100:\n res = less20[num // 100] + ' Hundred' + (' ' if num % 100 else '')\n num %= 100\n res += less20[num] if num < 20 else more20[num // 10] + (' ' + less20[num % 10] if num % 10 else '')\n return res\n if num == 0:\n return 'Zero'\n unit = ['', 'Thousand', 'Million', 'Billion']\n i = 0\n res = []\n while num > 0:\n t = translate(num % 1000)\n if t:\n res += [unit[i], t]\n num //= 1000\n i += 1\n return ' '.join(res[::-1]).strip()", "def helper(num):\n result = ''\n while len(num) < 3:\n num = '0' + num\n if num[0] is not '0':\n result = self.digit[int(num[0])] + ' Hundred'\n if num[1] is not '0':\n if num[1] == '1':\n return result + ' ' + self.teen[int(num[1] + num[2])]\n else:\n return result + ' ' + self.ten[int(num[1])] + ' ' + self.digit[int(num[2])]\n if num[2] is not '0':\n result = result + ' ' + self.digit[int(num[2])]\n return result\n\ndef numbertowords(num):\n if num == 0:\n return 'Zero'\n result = ''\n rev = str(num)[::-1]\n slices = [rev[i:i + 3] for i in range(0, len(str(num)), 3)]\n for (idx, slice) in enumerate(slices):\n if slice == '000':\n continue\n else:\n result = self.helper(str(slice[::-1])) + ' ' + self.idx[idx] + ' ' + result\n result = result.split(' ')\n result = [x for x in result if x is not '']\n return ' '.join(result)", "def numbertowords(num):\n num_lyst = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']\n tens_lyst = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']\n under20_lyst = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']\n large_scale = ['', 'Thousand', 'Million', 'Billion']\n\n def convert(num):\n out_str = ''\n hundred = num // 100\n ten_digit = num % 100\n if hundred:\n out_str += num_lyst[hundred] + ' ' + 'Hundred '\n if ten_digit:\n if ten_digit < 10:\n out_str += num_lyst[ten_digit]\n elif ten_digit < 20:\n out_str += under20_lyst[ten_digit % 10]\n else:\n out_str += tens_lyst[ten_digit // 10] + ' ' + num_lyst[ten_digit % 10]\n return out_str.strip()\n if not num:\n return 'Zero'\n res = num // 1000\n last3 = num % 1000\n ans = ''\n while res or last3:\n if last3:\n ans = convert(last3) + ' ' + large_scale.pop(0) + ' ' + ans\n else:\n large_scale.pop(0)\n last3 = res % 1000\n res = res // 1000\n return ans.strip()", "def getEnglishThousand(n):\n if 1 <= n <= 9:\n return ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'][n - 1]\n elif 10 <= n <= 19:\n return ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'][n - 10]\n elif 20 <= n <= 99:\n eng = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'][n // 10 - 2]\n if n % 10 > 0:\n return eng + ' ' + self.getEnglishThousand(n % 10)\n else:\n return eng\n else:\n hundred = self.getEnglishThousand(n // 100) + ' Hundred'\n if n % 100 > 0:\n return hundred + ' ' + self.getEnglishThousand(n % 100)\n else:\n return hundred\n\ndef numbertowords(num):\n if num == 0:\n return 'Zero'\n stack = ['Billion', 'Million', 'Thousand', None]\n english = []\n while num:\n quantifier = stack.pop()\n if num % 1000 > 0:\n english.append(self.getEnglishThousand(num % 1000) + (' ' + quantifier if quantifier else ''))\n num //= 1000\n return ' '.join(reversed(english))", "def read_three_digits(unit, ten, hundred, index):\n if ten == 1:\n str_of_num = ' ' + Solution.ten_to_str[ten * 10 + unit]\n else:\n str_of_num = ' ' + Solution.ten_to_str[ten * 10] + Solution.digit_to_str[unit] if ten > 1 else Solution.digit_to_str[unit]\n str_of_num = (Solution.digit_to_str[hundred] + ' Hundred' if hundred > 0 else '') + str_of_num\n return str_of_num[1:] + ' ' + Solution.quantity_unit[index] if str_of_num else str_of_num[1:]\n\ndef numbertowords(num):\n if num == 0:\n return 'Zero'\n str_of_num = ''\n index = 0\n while num > 0:\n part = num % 1000\n unit = part % 10\n ten = part % 100 // 10\n hundred = part // 100\n str_of_num = self.read_three_digits(unit, ten, hundred, index) + ' ' + str_of_num.strip()\n num //= 1000\n index += 1\n return str_of_num.strip()"], "starter_code": "def numbertowords(num: int) -> str:\n", "input_output": {"fn_name": "numberToWords", "inputs": [[123]], "outputs": ["One Hundred Twenty Three"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Recursion", "Math", "String"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Mathematics", "Complete search"], "skill_types": ["Complete search"], "url": "https://leetcode.com/problems/integer-to-english-words/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numbertowords", "task_id": "TACO_lite/158", "example": [[[123], [12345], [1234567], [1234567891]], ["One Hundred Twenty Three", "Twelve Thousand Three Hundred Forty Five", "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven", "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"]]} +{"requirement": "HELP! Jason can't find his textbook! It is two days before the test date, and Jason's textbooks are all out of order! Help him sort a list (ArrayList in java) full of textbooks by subject, so he can study before the test.\n\nThe sorting should **NOT** be case sensitive", "solutions": ["def sorter(textbooks):\n return sorted(textbooks, key=str.lower)", "def sorter(textbooks):\n return sorted(textbooks, key=str.casefold)", "def sorter(textbooks):\n return sorted(textbooks, key=lambda arg: arg.lower())", "sorter = lambda x: sorted(x, key=lambda s: s.lower())", "sorter = lambda text: sorted(text, key=lambda s: s.lower())", "def sorter(lst):\n return sorted(lst, key=lambda e: e.lower())", "def sorter(textbooks):\n return sorted(textbooks, key=lambda text: text.lower())", "def sorter(textbooks):\n\n def f(e):\n return e.lower()\n sorted = textbooks.sort(key=f)\n return textbooks", "def sorter(textbooks):\n d = {t.lower(): t for t in textbooks}\n return [d[t] for t in sorted(d)]", "sorter = lambda textbooks: sorted(textbooks, key=str.lower)", "from typing import List\n\ndef sorter(textbooks: List[str]):\n return sorted(textbooks, key=str.lower)", "def sorter(textbooks):\n textbooks.sort(key=lambda x: x.lower())\n return textbooks", "def myf(a):\n return a.lower()\n\ndef sorter(textbooks):\n return sorted(textbooks, key=myf)", "def sorter(textbooks):\n textbooks.sort(key=str.lower)\n return textbooks", "def sorter(textbooks):\n listtemp = [(x.lower(), x) for x in textbooks]\n listtemp.sort()\n return [x[1] for x in listtemp]", "def sorter(textbooks):\n r = {i.lower(): i for i in textbooks}\n return [r[i] for i in sorted(r)]", "def sorter(textbooks):\n subjects = dict(((sub.lower(), sub) for sub in textbooks))\n return [subjects[sub] for sub in sorted(subjects.keys())]", "sorter = lambda textbooks: list(sorted(textbooks, key=lambda s: s.lower()))", "sorter = lambda textbooks: sorted(textbooks, key=str.casefold)", "def sorter(textbooks):\n return list(sorted(textbooks, key=lambda e: e.lower()))", "import functools\n\ndef cmp(a, b):\n aa = a.lower()\n bb = b.lower()\n if aa > bb:\n return 1\n elif bb > aa:\n return -1\n else:\n return 0\n\ndef sorter(textbooks):\n return sorted(textbooks, key=functools.cmp_to_key(cmp))", "from typing import List\n\ndef sorter(textbooks: List[str]) -> List[str]:\n return sorted(textbooks, key=str.casefold)", "def sorter(tks):\n return sorted(tks, key=lambda s: s.lower())", "def sorter(textbooks):\n return sorted(textbooks, key=lambda v: (v.casefold(), v))", "def get_first(element):\n return element[0]\n\ndef sorter(textbooks):\n lst = [(el.lower(), el) for el in textbooks]\n lst1 = sorted(lst, key=get_first)\n return [el[1] for el in lst1]", "def sorter(textbooks):\n lst = sorted([(el.lower(), el) for el in textbooks])\n return [el[1] for el in lst]", "def sorter(textbooks):\n\n def f(x):\n return x.lower()\n return sorted(textbooks, key=f)", "def sorter(textbooks):\n return sorted(sorted(textbooks, key=lambda x: x[1].lower()), key=lambda x: x[0].lower())", "def sorter(textbooks):\n x = sorted(textbooks, key=lambda s: s.casefold())\n return x", "def sorter(textbooks):\n result = []\n books_lowcase = [x.lower() for x in textbooks]\n books_dict = dict(zip(books_lowcase, textbooks))\n dict_keys_sort = list(books_dict.keys())\n dict_keys_sort.sort()\n for i in dict_keys_sort:\n result.append(books_dict[i])\n return result", "import re\n\ndef sorter(textbooks):\n textbooks.sort(key=str.lower)\n return textbooks", "def sorter(textbooks):\n s = sorted(textbooks)\n if textbooks == s:\n return textbooks\n if s == s.sort(key=str.lower):\n return s.sort(key=str.lower)\n else:\n return s", "def lower_case(predmet):\n return predmet.lower()\n\ndef sorter(textbooks):\n return sorted(textbooks, key=lower_case)", "def register(textbook):\n return textbook.lower()\n\ndef sorter(textbooks):\n textbooks.sort(key=register)\n return textbooks", "def sorter(textbooks):\n return sorted(textbooks, key=lambda s: s.lower())", "def f(x):\n x = x.lower()\n return x\n\ndef sorter(textbooks):\n textbooks.sort(key=f)\n return textbooks", "def sorter(textbooks):\n textbooks = sorted(textbooks, key=lambda x: x[0:] if x[0:].islower() else x[0:].lower())\n return textbooks", "def sorter(textbooks):\n return sorted([i for i in textbooks], key=lambda str: str.lower())", "def sorter(t):\n t.sort(key=str.casefold)\n return t", "import locale\n\ndef sorter(textbooks):\n textbooks.sort(key=lambda x: x.lower())\n return textbooks", "def sorter(t):\n return sorted(t, key=lambda t: t.casefold())", "def sorter(textbooks):\n return sorted(textbooks, key=lambda x: x[0:2].lower())", "def sorter(textbooks):\n lst_books = []\n for i in textbooks:\n lst_books.append(i)\n return sorted(lst_books, key=str.lower)", "def sorter(textbooks):\n textbooks_low = [el.lower() for el in textbooks]\n textbooks_low_sorted = sorted(textbooks_low)\n testbooks_sorted_indexes = [textbooks_low.index(el) for el in textbooks_low_sorted]\n return [textbooks[ind] for ind in testbooks_sorted_indexes]", "def sorter(textbooks):\n if textbooks != int:\n return sorted(textbooks, key=str.lower)", "def sorter(text_books):\n return sorted(text_books, key=str.lower)", "def sorter(textbooks):\n return sorted(textbooks, key=lambda t: (t.lower(), t))", "def sorter(textbooks):\n arr = []\n for (i, book) in enumerate(textbooks):\n arr.append([book.lower(), i])\n arr = sorted(arr)\n for (i, book) in enumerate(arr):\n arr[i] = textbooks[book[1]]\n return arr", "sorter = lambda books: sorted(books, key=lambda _: _.lower())", "import string\n\ndef sorter(textbooks):\n return sorted(textbooks, key=str.lower)", "sorter = lambda t: sorted(t, key=lambda s: s.lower())", "def sorter(textbooks):\n obj = {}\n lower_case_textbooks = []\n for textbook in textbooks:\n lower_case_textbook = textbook.lower()\n obj[lower_case_textbook] = textbook\n lower_case_textbooks.append(lower_case_textbook)\n sorted_textbooks = sorted(lower_case_textbooks)\n output_list = []\n for sorted_textbook in sorted_textbooks:\n output_list.append(obj[sorted_textbook])\n return output_list", "def sorter(arr):\n for i in range(len(arr) - 1):\n for j in range(len(arr) - i - 1):\n if arr[j].lower() > arr[j + 1].lower():\n (arr[j], arr[j + 1]) = (arr[j + 1], arr[j])\n return arr", "def sorter(textbooks):\n return [a[1] for a in sorted([(b.lower(), b) for b in textbooks])]", "def sorter(t):\n return sorted(t, key=str.casefold)", "def sorter(tb):\n return sorted(tb, key=lambda x: x.lower())", "def sorter(textbooks):\n sorted = [book.lower() for book in textbooks]\n sorted.sort()\n final = textbooks.copy()\n for book in textbooks:\n final[sorted.index(book.lower())] = book\n return final", "def sorter(textbooks):\n copy = [text.lower() for text in textbooks]\n final = []\n to_sort = list(copy)\n to_sort.sort()\n for t in to_sort:\n final.append(textbooks[copy.index(t)])\n return final", "sorter = lambda x: sorted(x, key=str.casefold)", "def sorter(textbooks):\n a = [i.lower() for i in textbooks]\n s = sorted(a)\n for i in range(len(s)):\n if s[i] in textbooks:\n pass\n else:\n s[i] = textbooks[a.index(s[i])]\n return s", "def sorter(textbooks):\n return sorted(textbooks, key=lambda w: w.casefold())", "def sorter(textbooks):\n ret = [t for t in textbooks]\n ret.sort(key=lambda x: x.lower())\n return ret", "import numpy as np\n\ndef sorter(textbooks):\n return sorted(textbooks, key=str.lower)", "import functools\n\ndef compares(item1, item2):\n if len(item1) == 0:\n return -1\n if len(item2) == 0:\n return 1\n if ord(item1[0].lower()) < ord(item2[0].lower()):\n return -1\n elif ord(item1[0].lower()) > ord(item2[0].lower()):\n return 1\n else:\n return compares(item1[1:], item2[1:])\n\ndef compare(item1, item2):\n return compares(item1, item2)\n\ndef sorter(textbooks):\n return sorted(textbooks, key=functools.cmp_to_key(compare))", "def sorter(t):\n a = sorted(t, key=str.lower)\n return a", "def sorter(textbooks):\n a = [Book(subj) for subj in textbooks]\n a.sort()\n output = [i.subject for i in a]\n return output\n\ndef __init__(subject):\n self.subject = subject\n\ndef __lt__(other):\n return self.subject.lower() < other.subject.lower()", "def sorter(textbooks):\n return sorted(textbooks, key=lambda v: v.lower())", "def sorter(textbooks):\n sortbooks = sorted([x.lower() for x in textbooks])\n out = []\n for sb in sortbooks:\n for tb in textbooks:\n if sb == tb.lower():\n out.append(tb)\n return out", "def sorter(textbooks):\n index = {word.lower(): word for word in textbooks}\n keys = sorted(index.keys())\n return [index[key] for key in keys]", "def sorter(textbooks):\n return sorted([textbook for textbook in textbooks], key=lambda x: x.lower())", "sorter = lambda textbooks: sorted(textbooks, key=lambda t: t.lower())"], "starter_code": "def sorter(textbooks):\n", "input_output": {"fn_name": "sorter", "inputs": [[["Algebra", "History", "Geometry", "English"]], [["Algebra", "history", "Geometry", "english"]], [["Alg#bra", "$istory", "Geom^try", "**english"]]], "outputs": [[["Algebra", "English", "Geometry", "History"]], [["Algebra", "english", "Geometry", "history"]], [["$istory", "**english", "Alg#bra", "Geom^try"]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Sorting", "Lists"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/5a07e5b7ffe75fd049000051", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sorter", "task_id": "TACO_lite/121", "example": [[[["Mathematics", "history", "Physics", "chemistry"]], [["biology", "Zoology", "math", "Computer Science"]]], ["['chemistry', 'history', 'Mathematics', 'Physics']", "['biology', 'Computer Science', 'math', 'Zoology']"]]} +{"requirement": "You have an array of numbers. \nYour task is to sort ascending odd numbers but even numbers must be on their places.\n\nZero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.\n\n*Example*\n```python\nsort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]\n```", "solutions": ["def sort_array(arr):\n odds = sorted((x for x in arr if x % 2 != 0), reverse=True)\n return [x if x % 2 == 0 else odds.pop() for x in arr]", "def sort_array(source_array):\n odds = iter(sorted((v for v in source_array if v % 2)))\n return [next(odds) if i % 2 else i for i in source_array]", "def sort_array(source_array):\n odds = []\n answer = []\n for i in source_array:\n if i % 2 > 0:\n odds.append(i)\n answer.append('X')\n else:\n answer.append(i)\n odds.sort()\n for i in odds:\n x = answer.index('X')\n answer[x] = i\n return answer", "def sort_array(source_array):\n result = sorted([l for l in source_array if l % 2 == 1])\n for (index, item) in enumerate(source_array):\n if item % 2 == 0:\n result.insert(index, item)\n return result", "from collections import deque\n\ndef sort_array(array):\n odd = deque(sorted((x for x in array if x % 2)))\n return [odd.popleft() if x % 2 else x for x in array]", "def sort_array(source_array):\n odd = sorted(list(filter(lambda x: x % 2, source_array)))\n (l, c) = ([], 0)\n for i in source_array:\n if i in odd:\n l.append(odd[c])\n c += 1\n else:\n l.append(i)\n return l", "def sort_array(source_array):\n return [] if len(source_array) == 0 else list(map(int, ','.join(['{}' if a % 2 else str(a) for a in source_array]).format(*list(sorted((a for a in source_array if a % 2 == 1)))).split(',')))", "def sort_array(source_array):\n odd = []\n for i in source_array:\n if i % 2 == 1:\n odd.append(i)\n odd.sort()\n x = 0\n for j in range(len(source_array)):\n if source_array[j] % 2 == 1:\n source_array[j] = odd[x]\n x += 1\n return source_array", "def sort_array(source_array):\n odds = iter(sorted((elem for elem in source_array if elem % 2 != 0)))\n return [next(odds) if el % 2 != 0 else el for el in source_array]", "def sort_array(numbers):\n evens = []\n odds = []\n for a in numbers:\n if a % 2:\n odds.append(a)\n evens.append(None)\n else:\n evens.append(a)\n odds = iter(sorted(odds))\n return [next(odds) if b is None else b for b in evens]"], "starter_code": "def sort_array(source_array):\n", "input_output": {"fn_name": "sort_array", "inputs": [[[5, 3, 2, 8, 1, 4, 11]], [[2, 22, 37, 11, 4, 1, 5, 0]], [[1, 111, 11, 11, 2, 1, 5, 0]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 1, 2, 3, 4, 9, 8, 7, 6, 5]]], "outputs": [[[1, 3, 2, 8, 5, 4, 11]], [[2, 22, 1, 5, 4, 11, 37, 0]], [[1, 1, 5, 11, 2, 11, 111, 0]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 1, 2, 3, 4, 5, 8, 7, 6, 9]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Sorting"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/578aa45ee9fd15ff4600090d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sort_array", "task_id": "TACO_lite/240", "example": [[[[5, 3, 2, 8, 1, 4]]], ["[1, 3, 2, 8, 5, 4]"]]} +{"requirement": "Given the root\u00a0of a binary tree, each node in the tree has a distinct value.\nAfter deleting\u00a0all nodes with a value in to_delete, we are left with a forest (a\u00a0disjoint union of trees).\nReturn the roots of the trees in the remaining forest.\u00a0 You may return the result in any order.\n\u00a0\nExample 1:\n\nInput: root = [1,2,3,4,5,6,7], to_delete = [3,5]\nOutput: [[1,2,null,4],[6],[7]]\n\n\u00a0\nConstraints:\n\nThe number of nodes in the given tree is at most 1000.\nEach node has a distinct value between 1 and 1000.\nto_delete.length <= 1000\nto_delete contains distinct values between 1 and 1000.", "solutions": ["def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n (ans, to_delete) = ([], set(to_delete))\n\n def search(root, is_root):\n if not root:\n return None\n root_deleted = root.val in to_delete\n if is_root and (not root_deleted):\n ans.append(root)\n root.left = search(root.left, root_deleted)\n root.right = search(root.right, root_deleted)\n return None if root_deleted else root\n search(root, True)\n return ans", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n ans = []\n to_delete = set(to_delete)\n\n def dfs(node, has_parent):\n if not node:\n return False\n if node.val not in to_delete and (not has_parent):\n ans.append(node)\n if dfs(node.left, node.val not in to_delete):\n node.left = None\n if dfs(node.right, node.val not in to_delete):\n node.right = None\n return node.val in to_delete\n dfs(root, False)\n return ans", "def merge(root, left, right):\n replace_left = replace_right = None\n for i in range(len(left)):\n if left[i] == root.left:\n replace_left = i\n for i in range(len(right)):\n if right[i] == root.right:\n replace_right = i\n if replace_left is not None and replace_right is None:\n left[replace_left] = root\n return left + right\n elif replace_right is not None and replace_left is None:\n right[replace_right] = root\n return left + right\n result = [node for node in left if node != root.left] + [node for node in right if node != root.right]\n result.append(root)\n return result\n\ndef helper(root, to_delete):\n if not root:\n return []\n if not root.left and (not root.right):\n if root.val in to_delete:\n return []\n return [root]\n left = self.delNodes(root.left, to_delete)\n right = self.delNodes(root.right, to_delete)\n if root.left and root.left.val in to_delete:\n root.left = None\n if root.right and root.right.val in to_delete:\n root.right = None\n if root.val in to_delete:\n return left + right\n return self.merge(root, left, right)\n\ndef delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n return self.helper(root, set(to_delete))", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n res = []\n\n def rec(curr, deleted):\n nonlocal res\n if not curr:\n return None\n if curr.val in to_delete:\n curr.left = rec(curr.left, True)\n curr.right = rec(curr.right, True)\n else:\n curr.left = rec(curr.left, False)\n curr.right = rec(curr.right, False)\n if deleted:\n res.append(curr)\n return None if curr.val in to_delete else curr\n rec(root, True)\n return res", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n if root is None:\n return\n tovisit = []\n result = []\n if root in to_delete:\n if root.left is not None:\n tovisit.append(root.left)\n result.append(root.left)\n if root.right is not None:\n tovisit.append(root.right)\n result.append(root.right)\n else:\n tovisit.append(root)\n result.append(root)\n while len(tovisit) > 0:\n new_tovisit = []\n for item in tovisit:\n if item.val in to_delete:\n if item.left is not None:\n result.append(item.left)\n if item.right is not None:\n result.append(item.right)\n if item in result:\n result.remove(item)\n if item.left is not None:\n new_tovisit.append(item.left)\n if item.left.val in to_delete:\n item.left = None\n if item.right is not None:\n new_tovisit.append(item.right)\n if item.right.val in to_delete:\n item.right = None\n tovisit = new_tovisit\n return result", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n roots = []\n\n def deleting(node, to_delete, roots):\n if node == None:\n return\n elif node.val in to_delete:\n if node.left != None:\n roots.append(node.left)\n if node.right != None:\n roots.append(node.right)\n try:\n while True:\n roots.remove(node)\n except:\n pass\n if node.left != None and node.left.val in to_delete:\n deleting(node.left, to_delete, roots)\n node.left = None\n else:\n deleting(node.left, to_delete, roots)\n if node.right != None and node.right.val in to_delete:\n deleting(node.right, to_delete, roots)\n node.right = None\n else:\n deleting(node.right, to_delete, roots)\n deleting(root, to_delete, roots)\n if root.val not in to_delete:\n roots.append(root)\n return roots", "from queue import Queue\n\ndef delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n if not root:\n return []\n deleted = set()\n for node in to_delete:\n deleted.add(node)\n out = []\n self.bfs(root, deleted, out)\n return out\n\ndef bfs(root, deleted, out):\n q = Queue()\n q.put((root, True))\n while q.qsize() > 0:\n (node, parent_delete) = q.get()\n if node.val in deleted:\n curr_delete = True\n else:\n curr_delete = False\n if node.left:\n q.put((node.left, curr_delete))\n if node.left.val in deleted:\n node.left = None\n if node.right:\n q.put((node.right, curr_delete))\n if node.right.val in deleted:\n node.right = None\n if curr_delete:\n node.left = None\n node.right = None\n elif parent_delete:\n out.append(node)", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n roots = []\n roots.append(root)\n\n def removeRoot(root, roots):\n index = 0\n for i in roots:\n if i == root:\n roots.pop(index)\n index += 1\n\n def delete(root, prev, roots, to_delete):\n left = root.left\n right = root.right\n if root.val in to_delete:\n removeRoot(root, roots)\n if left:\n roots.append(root.left)\n if right:\n roots.append(root.right)\n root.left = None\n root.right = None\n if prev:\n if prev.left == root:\n prev.left = None\n if prev.right == root:\n prev.right = None\n if left:\n delete(left, root, roots, to_delete)\n if right:\n delete(right, root, roots, to_delete)\n delete(root, None, roots, to_delete)\n return roots", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n stack = [(root, True)]\n res = []\n while stack:\n (curr, toBeRoot) = stack.pop()\n if curr:\n if curr.val not in to_delete and toBeRoot:\n res.append(curr)\n toBeRoot = curr.val in to_delete\n stack += [(curr.left, toBeRoot), (curr.right, toBeRoot)]\n if curr.left and curr.left.val in to_delete:\n curr.left = None\n if curr.right and curr.right.val in to_delete:\n curr.right = None\n return res", "def walk(node, to_delete):\n if not node:\n return []\n roots = []\n if node.left:\n roots += self.walk(node.left, to_delete)\n if node.left.val in to_delete:\n node.left = None\n elif node.val in to_delete:\n roots.append(node.left)\n if node.right:\n roots += self.walk(node.right, to_delete)\n if node.right.val in to_delete:\n node.right = None\n elif node.val in to_delete:\n roots.append(node.right)\n return roots\n\ndef delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n if not root:\n return None\n to_delete = set(to_delete)\n roots = self.walk(root, to_delete)\n if root.val not in to_delete:\n roots.append(root)\n return roots", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n if not root:\n return []\n (res, to_delete) = ([], set(to_delete))\n self.dfs(root, res, to_delete, True)\n return res\n\ndef dfs(root, res, to_delete, parent_deleted):\n if not root:\n return None\n if parent_deleted and root.val not in to_delete:\n res.append(root)\n root_deleted = True if root.val in to_delete else False\n root.left = self.dfs(root.left, res, to_delete, root_deleted)\n root.right = self.dfs(root.right, res, to_delete, root_deleted)\n return None if root_deleted else root", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n\n def dfs(root: TreeNode, has_parent: bool) -> TreeNode:\n if not root:\n return\n if root.val in to_delete:\n root.left = dfs(root.left, has_parent=False)\n root.right = dfs(root.right, has_parent=False)\n return\n else:\n if not has_parent:\n result.append(root)\n root.left = dfs(root.left, has_parent=True)\n root.right = dfs(root.right, has_parent=True)\n return root\n result = []\n dfs(root, has_parent=False)\n return result", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n to_delete = set(to_delete)\n res = []\n\n def walk(root, parent_exist):\n if root is None:\n return None\n if root.val in to_delete:\n root.left = walk(root.left, parent_exist=False)\n root.right = walk(root.right, parent_exist=False)\n return None\n else:\n if not parent_exist:\n res.append(root)\n root.left = walk(root.left, parent_exist=True)\n root.right = walk(root.right, parent_exist=True)\n return root\n walk(root, parent_exist=False)\n return res", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n new_roots = []\n\n def delete_nodes(node, parent_deleted):\n if not node:\n return False\n delete = False\n for value in to_delete:\n if value == node.val:\n delete = True\n if parent_deleted and (not delete):\n new_roots.append(node)\n (left, right) = (delete_nodes(node.left, delete), delete_nodes(node.right, delete))\n if left:\n node.left = None\n if right:\n node.right = None\n return delete\n delete_nodes(root, True)\n return new_roots", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n to_delete = set(to_delete)\n ans = []\n\n def helper(node, isRoot, parent, p_left):\n if isRoot:\n ans.append(node)\n if node.val in to_delete:\n if isRoot:\n ans.pop()\n if parent:\n if p_left:\n parent.left = None\n else:\n parent.right = None\n if node.left:\n helper(node.left, True, node, True)\n if node.right:\n helper(node.right, True, node, False)\n else:\n if node.left:\n helper(node.left, False, node, True)\n if node.right:\n helper(node.right, False, node, False)\n return\n helper(root, True, None, None)\n return ans", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n self.deletes = set(to_delete)\n self.res = list()\n root = self.helper(root)\n if root:\n self.res.append(root)\n return self.res\n\ndef helper(root):\n if not root:\n return root\n root.left = self.helper(root.left)\n root.right = self.helper(root.right)\n if root.val in self.deletes:\n if root.left:\n self.res.append(root.left)\n if root.right:\n self.res.append(root.right)\n root = None\n return root", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n if not root:\n return []\n res = set([root])\n deleteSet = set(to_delete)\n\n def dfs(root):\n if not root:\n return\n if root.val in deleteSet:\n if root in res:\n res.remove(root)\n if root.left:\n res.add(root.left)\n if root.right:\n res.add(root.right)\n dfs(root.left)\n dfs(root.right)\n if root.left and root.left.val in deleteSet:\n root.left = None\n if root.right and root.right.val in deleteSet:\n root.right = None\n dfs(root)\n return list(res)", "def delete(root, to_delete, parent, res):\n if not root:\n return root\n elif parent:\n if root.val in to_delete:\n root.left = self.delete(root.left, to_delete, False, res)\n root.right = self.delete(root.right, to_delete, False, res)\n return None\n else:\n root.left = self.delete(root.left, to_delete, True, res)\n root.right = self.delete(root.right, to_delete, True, res)\n return root\n elif root.val in to_delete:\n root.left = self.delete(root.left, to_delete, False, res)\n root.right = self.delete(root.right, to_delete, False, res)\n return None\n else:\n res.append(root)\n root.left = self.delete(root.left, to_delete, True, res)\n root.right = self.delete(root.right, to_delete, True, res)\n return root\n\ndef delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n res = []\n root = self.delete(root, set(to_delete), False, res)\n return res", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n ret = []\n\n def dfs(node, parent):\n if node:\n if node.val in to_delete:\n node.left = dfs(node.left, False)\n node.right = dfs(node.right, False)\n else:\n if not parent:\n ret.append(node)\n node.left = dfs(node.left, True)\n node.right = dfs(node.right, True)\n return node\n dfs(root, False)\n return ret", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n final_list = []\n\n def rec(node):\n if node == None:\n return None\n node.left = rec(node.left)\n node.right = rec(node.right)\n if node.val in to_delete:\n if node.left != None:\n final_list.append(node.left)\n if node.right != None:\n final_list.append(node.right)\n return None\n return node\n rec(root)\n if root.val not in to_delete:\n final_list.append(root)\n return final_list", "def delNodes(root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n output = []\n stack = [(0, root)]\n\n def stackChildren(level, node):\n if node.right:\n stack.append((level, node.right))\n if level > 0 and node.right.val in to_delete:\n node.right = None\n if node.left:\n stack.append((level, node.left))\n if level > 0 and node.left.val in to_delete:\n node.left = None\n while stack:\n (level, node) = stack.pop()\n if node.val in to_delete:\n stackChildren(0, node)\n else:\n if level == 0:\n output.append(node)\n stackChildren(level + 1, node)\n return output"], "starter_code": "def __init__(val=0, left=None, right=None):\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Binary Tree", "Tree", "Depth-First Search"], "name": null, "source": "leetcode", "tags": ["Tree algorithms", "Graph traversal"], "skill_types": [], "url": "https://leetcode.com/problems/delete-nodes-and-return-forest/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "__init__", "task_id": "TACO_lite/201", "example": [[], []]} +{"requirement": "Given a Binary string st and a number k. You have to find the Longest continuous sequence of '0' after repeating Given string K time.\nExample 1:\nInput: k = 3\nst = 100001\nOutput: 4\nExplaination: The string repeated k times \nbecome 100001100001100001. Here the longest \ncontinuous sequence of 0 is 4.\nExample 2:\nInput: k = 4\nst = 000\nOutput: 12\nExplaination: When st is repeated 4 times \nit become 000000000000. The longest sequence \nbecomes of length 12.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function lcsK() which takes k and st as input parameters and returns the length of the longest continuous sequence of 0's after repeating st k times.\nExpected Time Complexity: O(|st|)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 |st| \u2264 10^{5}\n1 \u2264 k \u2264 10^{5}", "solutions": ["def lcsk(k, st):\n if int(st) > 0:\n s = st * k\n ans = 0\n temp = 0\n s = str(s)\n r = min(2, k)\n for i in range(len(st) * r):\n if s[i] == '0':\n temp = temp + 1\n else:\n ans = max(ans, temp)\n temp = 0\n return ans\n else:\n return len(st) * k", "def lcsk(k, s):\n n = len(s)\n if k > 1:\n s += s\n n *= 2\n ans = 0\n i = 0\n while i < n:\n x = 0\n while i < n and s[i] == '0':\n (x, i) = (x + 1, i + 1)\n ans = max(ans, x)\n i += 1\n if k == 1 or ans != n:\n return ans\n else:\n return ans // 2 * k", "def lcsk(k, st):\n n = len(st)\n dp = [0] * (n + 1)\n if st[0] == '0':\n dp[0] = 1\n for i in range(1, n):\n if st[i] == '0':\n dp[i] = dp[i - 1] + 1\n else:\n dp[i] = 0\n if dp[n - 1] == n:\n return n * k\n u = 0\n for i in range(n):\n if st[i] == '1':\n u = i - 1\n break\n if u == -1:\n return max(dp)\n else:\n return max(max(dp), dp[n - 1] + dp[u])", "def lcsk(k, st):\n if k == 1:\n count = 0\n maxi = 0\n for char in st:\n if char == '0':\n count += 1\n maxi = max(maxi, count)\n else:\n count = 0\n return maxi\n if not '1' in st:\n return k * len(st)\n i = st.index('1')\n st = st[i:] + st[:i]\n count = 0\n maxi = 0\n for char in st:\n if char == '0':\n count += 1\n maxi = max(maxi, count)\n else:\n count = 0\n return maxi", "def lcsk(k, st):\n n = len(st)\n (left, bounded, right) = self.getCounts(st, n)\n if k == 1:\n return max(max(left, bounded), right)\n if left + right == n:\n return k * n\n return max(left + right, bounded)\n\ndef getCounts(st, n):\n left = 0\n right = 0\n boundedMax = 0\n l = 0\n while l < n:\n if st[l] != '0':\n break\n left += 1\n l += 1\n r = n - 1\n while r >= 0 and r > l:\n if st[r] == '1':\n break\n right += 1\n r -= 1\n curBound = 0\n while l < r:\n if st[l] == '0':\n curBound += 1\n boundedMax = max(boundedMax, curBound)\n else:\n curBound = 0\n l += 1\n return (left, boundedMax, right)", "def lcsk(k, st):\n res = []\n i = 0\n while i < len(st):\n if st[i] != '0':\n i += 1\n continue\n cnt = 0\n while i < len(st) and st[i] == '0':\n cnt += 1\n i += 1\n res.append(cnt)\n if st[0] == '1':\n if res:\n return max(res)\n else:\n return 0\n if st[0] == '0' and st[-1] == '0':\n if len(res) == 1:\n return res[0] * k\n return max(res[0] + res[-1], max(res))\n return max(res)", "def lcsk(k, st):\n if st.count('0') == len(st):\n return len(st) * k\n if k <= 2:\n b = st * k\n else:\n b = st * 2\n lcs = 0\n olcs = -10 ** 9 - 7\n for i in range(len(b)):\n if b[i] == '0':\n lcs += 1\n else:\n olcs = max(olcs, lcs)\n lcs = 0\n if olcs == 10 ** 9 - 7:\n return lcs\n return olcs", "def lcsk(k, st):\n n = len(st)\n count = 0\n for i in range(n):\n if st[i] == '0':\n count += 1\n if count == n:\n return k * n\n xyz = st + st + st\n ans = 0\n lm = 0\n for i in range(len(xyz)):\n if xyz[i] == '0':\n lm += 1\n ans = max(ans, lm)\n else:\n lm = 0\n return ans", "def lcsk(k, st):\n st = st + st\n n = len(st)\n here = 0\n mx = 0\n for i in range(n):\n if st[i] == '0':\n here += 1\n else:\n here = 0\n mx = max(mx, here)\n if mx == n:\n return mx * k // 2\n else:\n return mx", "def lcsk(k, st):\n p = len(st)\n out = []\n for i in range(len(st)):\n if st[i] == '1':\n out.append(i)\n if len(out) == 0:\n return p * k\n out.append(p + out[0])\n mdif = 0\n for i in range(len(out) - 1):\n v = out[i + 1] - out[i] - 1\n if v > mdif:\n mdif = v\n return mdif", "def findmax(st):\n cnt = 0\n ans = 0\n for i in st:\n if i == '0':\n cnt += 1\n else:\n if ans < cnt:\n ans = cnt\n cnt = 0\n if ans < cnt:\n ans = cnt\n return ans\n\ndef lcsk(k, st):\n if st[0] != '0' or st[-1] != '0':\n return self.findmax(st)\n (ini, temp, last) = (0, 0, 0)\n cnt = 0\n i = 0\n while i < len(st):\n if st[i] == '0':\n ini += 1\n else:\n break\n i += 1\n temp = ini\n if ini == len(st):\n return len(st) * k\n while i < len(st):\n if st[i] == '0':\n cnt += 1\n else:\n if temp < cnt:\n temp = cnt\n cnt = 0\n i += 1\n last = cnt\n if temp < cnt:\n temp = cnt\n if temp > ini + last:\n return temp\n return ini + last", "def lcsk(k, st):\n l = len(st)\n if not '1' in st:\n return k * l\n elif st[0] != '0' or st[-1] != '0':\n count = 0\n mx = 0\n for i in st:\n if i == '0':\n count += 1\n else:\n if count > mx:\n mx = count\n count = 0\n return mx\n else:\n count = 0\n mx = 0\n for i in st:\n if i == '0':\n count += 1\n else:\n if count > mx:\n mx = count\n count = 0\n count = 0\n for i in st:\n if i == '1':\n break\n count += 1\n for i in range(1, l + 1):\n if st[-i] == '1':\n break\n count += 1\n return max(count, mx)"], "starter_code": "def lcsk(k, st):\n", "input_output": {"inputs": ["k = 3\nst = 100001", "k = 4\nst = 000"], "outputs": ["4", "12"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/lcs-of-0-k-repeated-string5642/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|st|)", "entry_point": "lcsk", "task_id": "TACO_lite/196", "example": [[[3, "100001"], [4, "000"]], ["4", "12"]]} +{"requirement": "Implement `String#parse_mana_cost`, which parses [Magic: the Gathering mana costs](http://mtgsalvation.gamepedia.com/Mana_cost) expressed as a string and returns a `Hash` with keys being kinds of mana, and values being the numbers.\n\nDon't include any mana types equal to zero.\n\nFormat is:\n\n* optionally natural number representing total amount of generic mana (use key `*`)\n* optionally followed by any combination of `w`, `u`, `b`, `r`, `g` (case insensitive in input, return lower case in output), each representing one mana of specific color.\n\nIf case of Strings not following specified format, return `nil/null/None`.", "solutions": ["import re\n\ndef parse_mana_cost(mana):\n n = {c: mana.lower().count(c) for c in 'wubrg' if mana.lower().count(c) > 0}\n m = re.split('\\\\D', mana)\n if sum(n.values()) + sum([len(c) for c in m]) != len(mana):\n return None\n p = sum([int(c) for c in m if c != ''])\n if p > 0:\n n['*'] = p\n return n", "import re\n\ndef parse_mana_cost(mana):\n m = re.match('(\\\\d*)([wubrg]*)\\\\Z', mana.lower())\n if m is None:\n return\n (g, c) = m.groups()\n result = {} if g in ('', '0') else {'*': int(g)}\n result.update({k: c.count(k) for k in set(c)})\n return result", "from collections import Counter\n\ndef parse_mana_cost(mana):\n if mana != mana.strip() or [c for c in mana.lower() if c not in '0123456789 wubrg']:\n return None\n return Counter(''.join((parse(w) for w in mana.lower().split())))\n\ndef parse(w):\n s = '0'\n while w and w[0].isdigit():\n (s, w) = (s + w[0], w[1:])\n return w + '*' * int(s)", "import re\nfrom collections import Counter\n\ndef parse_mana_cost(mana):\n for (cnt, chrs) in re.findall('\\\\A(\\\\d*)([wubrg]*)\\\\Z', mana.lower() or '0'):\n result = {'*': int(cnt or 0), **Counter(chrs)}\n return {key: result[key] for key in result if result[key]}", "from collections import Counter\nimport re\n\ndef parse_mana_cost(s):\n s = s.lower()\n if re.match('\\\\d*[wubrg]*\\\\Z', s):\n r = {x: s.count(x) for x in set(s) if x.isalpha()}\n return s and s[0].isdigit() and int(s[0]) and r.update({'*': int(re.match('\\\\d+', s).group())}) or r", "import re\n\ndef parse_mana_cost(m):\n if not m:\n return {}\n if not re.match('^[\\\\dwubrg]+$', m, re.I) or '\\n' in m:\n return\n (r1, r) = (re.findall('[wubrg]', m, re.I), re.search('^[0-9]*', m))\n (r, d) = (r.group() if r else '', {})\n if r != '0' and r:\n d['*'] = int(r)\n for i in m[len(r):]:\n d[i.lower()] = d.get(i.lower(), 0) + 1\n return d", "import re\n\ndef parse_mana_cost(mana):\n mana = mana.lower()\n valid = ['w', 'u', 'r', 'g', 'b']\n dic = {}\n regex = re.compile('(\\\\d*)([wubrg]*)')\n match = regex.search(mana)\n for x in list(mana):\n if x in valid:\n dic[x] = dic[x] + 1 if x in dic else 1\n if match.group(1) and match.group(1) != '0':\n dic['*'] = int(match.group(1))\n return dic if ''.join(match.group()) == mana else None", "from itertools import groupby\nimport re\n\ndef parse_mana_cost(mana):\n result = {}\n pattern = re.compile('\\\\d*[wurbg]*', re.I)\n manacost = pattern.match(mana).group()\n if mana in ['', '0']:\n return {}\n if manacost == None or len(mana) != len(manacost):\n return None\n (colors, colorless) = ('', '')\n for i in manacost:\n if i.isalpha():\n colors += i\n else:\n colorless += i\n if colorless not in ['0', '']:\n result['*'] = int(colorless)\n colors = ''.join(sorted(list(colors)))\n for (key, count) in groupby(colors):\n result[key.lower()] = len(list(count))\n return result"], "starter_code": "def parse_mana_cost(mana):\n", "input_output": {"fn_name": "parse_mana_cost", "inputs": [[""], ["0"], ["1"], ["4"], ["15"], ["2rr"], ["1wbg"], ["1WWU"], ["0r"], ["2x"], ["2R"], ["2\n"], ["\n2"], ["1b"], ["1bb"], ["1bbb"], ["1bg"], ["1bgu"], ["1br"], ["1brg"], ["1g"], ["1gg"], ["1ggg"], ["1ggu"], ["1ggw"], ["1gu"], ["1guu"], ["1gw"], ["1gwu"], ["1gww"], ["1r"], ["1rg"], ["1rgg"], ["1rgw"], ["1rr"], ["1rrr"], ["1rrw"], ["1rw"], ["1rwb"], ["1rwu"], ["1u"], ["1ub"], ["1ubr"], ["1ur"], ["1uu"], ["1uub"], ["1uur"], ["1uuu"], ["1w"], ["1wb"], ["1wbr"], ["1wu"], ["1wub"], ["1wubrg"], ["1ww"], ["1wwbb"], ["1wwu"], ["1wwuu"], ["1www"], ["2"], ["2b"], ["2bb"], ["2bbb"], ["2bbr"], ["2bbrr"], ["2bbrrgg"], ["2bg"], ["2bgg"], ["2bgu"], ["2bgw"], ["2br"], ["2brg"], ["2brr"], ["2g"], ["2gg"], ["2ggg"], ["2gggg"], ["2gguu"], ["2ggww"], ["2ggwwuu"], ["2gu"], ["2gub"], ["2gur"], ["2guu"], ["2gw"], ["2gwu"], ["2gww"], ["2r"], ["2rg"], ["2rgw"], ["2rrgg"], ["2rrggww"], ["2rrr"], ["2rrrg"], ["2rrww"], ["2rw"], ["2rwb"], ["2u"], ["2ub"], ["2ubr"], ["2ur"], ["2urg"], ["2urw"], ["2uu"], ["2uubb"], ["2uubbrr"], ["2uurr"], ["2uuu"], ["2uuuu"], ["2w"], ["2wb"], ["2wbg"], ["2wu"], ["2wub"], ["2wuu"], ["2wuub"], ["2ww"], ["2wwb"], ["2wwbb"], ["2wwuu"], ["2wwuubb"], ["2www"], ["3"], ["3b"], ["3bb"], ["3bbb"], ["3bbbb"], ["3bbg"], ["3bbr"], ["3bbrr"], ["3bg"], ["3bgu"], ["3bgw"], ["3br"], ["3brg"], ["3g"], ["3gg"], ["3ggg"], ["3gggg"], ["3ggw"], ["3ggww"], ["3gu"], ["3gub"], ["3gur"], ["3gw"], ["3gwu"], ["3gww"], ["3r"], ["3rg"], ["3rgg"], ["3rgw"], ["3rr"], ["3rrg"], ["3rrgg"], ["3rrr"], ["3rrrr"], ["3rw"], ["3rwb"], ["3rwu"], ["3rww"], ["3u"], ["3ub"], ["3ubb"], ["3ubr"], ["3ur"], ["3urg"], ["3urw"], ["3uu"], ["3uub"], ["3uubb"], ["3uuu"], ["3w"], ["3wb"], ["3wbb"], ["3wbg"], ["3wbr"], ["3wu"], ["3wub"], ["3wubrg"], ["3wuu"], ["3ww"], ["3wwbb"], ["3wwu"], ["3wwuu"], ["3www"], ["4b"], ["4bb"], ["4bbb"], ["4bbbb"], ["4bbgg"], ["4bbrr"], ["4bg"], ["4br"], ["4brg"], ["4brr"], ["4brrg"], ["4g"], ["4gg"], ["4ggg"], ["4gggg"], ["4ggww"], ["4gu"], ["4gub"], ["4gw"], ["4gwwu"], ["4r"], ["4rg"], ["4rggw"], ["4rgw"], ["4rr"], ["4rrg"], ["4rrgg"], ["4rrr"], ["4rrww"], ["4rw"], ["4rww"], ["4u"], ["4ub"], ["4ubbr"], ["4ubr"], ["4ur"], ["4uu"], ["4uuu"], ["4w"], ["4wb"], ["4wbb"], ["4wbg"], ["4wbr"], ["4wu"], ["4wub"], ["4wuub"], ["4ww"], ["4wwbb"], ["4wwu"], ["4www"], ["5"], ["5b"], ["5bb"], ["5bbb"], ["5bg"], ["5bgw"], ["5br"], ["5g"], ["5gg"], ["5ggg"], ["5gu"], ["5guu"], ["5gw"], ["5r"], ["5rg"], ["5rr"], ["5rrr"], ["5rw"], ["5u"], ["5ub"], ["5ubb"], ["5ur"], ["5urg"], ["5uu"], ["5uuu"], ["5uuuu"], ["5w"], ["5wb"], ["5wu"], ["5wub"], ["5ww"], ["5wwu"], ["5www"], ["6"], ["6b"], ["6bb"], ["6bbb"], ["6bg"], ["6br"], ["6g"], ["6gg"], ["6ggg"], ["6gw"], ["6r"], ["6rr"], ["6rrr"], ["6u"], ["6uu"], ["6uuu"], ["6w"], ["6ww"], ["6www"], ["7"], ["7b"], ["7bb"], ["7bbb"], ["7g"], ["7gg"], ["7ggg"], ["7r"], ["7rr"], ["7rrr"], ["7u"], ["7uu"], ["7uuu"], ["7w"], ["7ww"], ["7www"], ["8"], ["8b"], ["8bb"], ["8bbb"], ["8bbgg"], ["8g"], ["8gg"], ["8ggg"], ["8r"], ["8rr"], ["8uu"], ["8uuu"], ["8uuuu"], ["8ww"], ["9"], ["9b"], ["9r"], ["b"], ["bb"], ["bbb"], ["bbbb"], ["bbbbbbbbbbbbbbb"], ["bbgg"], ["bbr"], ["bbrr"], ["bbrrrgg"], ["bg"], ["bgg"], ["bgu"], ["bgw"], ["br"], ["brg"], ["brgw"], ["g"], ["gg"], ["ggg"], ["gggg"], ["ggggg"], ["gggggg"], ["gggggggg"], ["gggwww"], ["gguu"], ["ggw"], ["ggww"], ["ggwwwuu"], ["gu"], ["gur"], ["guu"], ["gw"], ["gwu"], ["gwub"], ["r"], ["rg"], ["rgw"], ["rgwu"], ["rr"], ["rrgg"], ["rrgggww"], ["rrr"], ["rrrr"], ["rw"], ["rwb"], ["u"], ["ub"], ["ubbr"], ["ubr"], ["ubrg"], ["ur"], ["urg"], ["urr"], ["urw"], ["uu"], ["uub"], ["uubb"], ["uubbbrr"], ["uur"], ["uuu"], ["uuuu"], ["w"], ["wb"], ["wbb"], ["wbg"], ["wu"], ["wub"], ["wubr"], ["wubrg"], ["wuu"], ["wuub"], ["ww"], ["wwbb"], ["wwuu"], ["wwuubbrrgg"], ["wwuuubb"], ["www"], ["wwww"]], "outputs": [[{}], [{}], [{"*": 1}], [{"*": 4}], [{"*": 15}], [{"*": 2, "r": 2}], [{"*": 1, "w": 1, "b": 1, "g": 1}], [{"*": 1, "w": 2, "u": 1}], [{"r": 1}], [null], [{"*": 2, "r": 1}], [null], [null], [{"*": 1, "b": 1}], [{"*": 1, "b": 2}], [{"*": 1, "b": 3}], [{"*": 1, "b": 1, "g": 1}], [{"*": 1, "u": 1, "b": 1, "g": 1}], [{"*": 1, "b": 1, "r": 1}], [{"*": 1, "b": 1, "r": 1, "g": 1}], [{"*": 1, "g": 1}], [{"*": 1, "g": 2}], [{"*": 1, "g": 3}], [{"*": 1, "u": 1, "g": 2}], [{"*": 1, "w": 1, "g": 2}], [{"*": 1, "u": 1, "g": 1}], [{"*": 1, "u": 2, "g": 1}], [{"*": 1, "w": 1, "g": 1}], [{"*": 1, "w": 1, "u": 1, "g": 1}], [{"*": 1, "w": 2, "g": 1}], [{"*": 1, "r": 1}], [{"*": 1, "r": 1, "g": 1}], [{"*": 1, "r": 1, "g": 2}], [{"*": 1, "w": 1, "r": 1, "g": 1}], [{"*": 1, "r": 2}], [{"*": 1, "r": 3}], [{"*": 1, "w": 1, "r": 2}], [{"*": 1, "w": 1, "r": 1}], [{"*": 1, "w": 1, "b": 1, "r": 1}], [{"*": 1, "w": 1, "u": 1, "r": 1}], [{"*": 1, "u": 1}], [{"*": 1, "u": 1, "b": 1}], [{"*": 1, "u": 1, "b": 1, "r": 1}], [{"*": 1, "u": 1, "r": 1}], [{"*": 1, "u": 2}], [{"*": 1, "u": 2, "b": 1}], [{"*": 1, "u": 2, "r": 1}], [{"*": 1, "u": 3}], [{"*": 1, "w": 1}], [{"*": 1, "w": 1, "b": 1}], [{"*": 1, "w": 1, "b": 1, "r": 1}], [{"*": 1, "w": 1, "u": 1}], [{"*": 1, "w": 1, "u": 1, "b": 1}], [{"*": 1, "w": 1, "u": 1, "b": 1, "r": 1, "g": 1}], [{"*": 1, "w": 2}], [{"*": 1, "w": 2, "b": 2}], [{"*": 1, "w": 2, "u": 1}], [{"*": 1, "w": 2, "u": 2}], [{"*": 1, "w": 3}], [{"*": 2}], [{"*": 2, "b": 1}], [{"*": 2, "b": 2}], [{"*": 2, "b": 3}], [{"*": 2, "b": 2, "r": 1}], [{"*": 2, "b": 2, "r": 2}], [{"*": 2, "b": 2, "r": 2, "g": 2}], [{"*": 2, "b": 1, "g": 1}], [{"*": 2, "b": 1, "g": 2}], [{"*": 2, "u": 1, "b": 1, "g": 1}], [{"*": 2, "w": 1, "b": 1, "g": 1}], [{"*": 2, "b": 1, "r": 1}], [{"*": 2, "b": 1, "r": 1, "g": 1}], [{"*": 2, "b": 1, "r": 2}], [{"*": 2, "g": 1}], [{"*": 2, "g": 2}], [{"*": 2, "g": 3}], [{"*": 2, "g": 4}], [{"*": 2, "u": 2, "g": 2}], [{"*": 2, "w": 2, "g": 2}], [{"*": 2, "w": 2, "u": 2, "g": 2}], [{"*": 2, "u": 1, "g": 1}], [{"*": 2, "u": 1, "b": 1, "g": 1}], [{"*": 2, "u": 1, "r": 1, "g": 1}], [{"*": 2, "u": 2, "g": 1}], [{"*": 2, "w": 1, "g": 1}], [{"*": 2, "w": 1, "u": 1, "g": 1}], [{"*": 2, "w": 2, "g": 1}], [{"*": 2, "r": 1}], [{"*": 2, "r": 1, "g": 1}], [{"*": 2, "w": 1, "r": 1, "g": 1}], [{"*": 2, "r": 2, "g": 2}], [{"*": 2, "w": 2, "r": 2, "g": 2}], [{"*": 2, "r": 3}], [{"*": 2, "r": 3, "g": 1}], [{"*": 2, "w": 2, "r": 2}], [{"*": 2, "w": 1, "r": 1}], [{"*": 2, "w": 1, "b": 1, "r": 1}], [{"*": 2, "u": 1}], [{"*": 2, "u": 1, "b": 1}], [{"*": 2, "u": 1, "b": 1, "r": 1}], [{"*": 2, "u": 1, "r": 1}], [{"*": 2, "u": 1, "r": 1, "g": 1}], [{"*": 2, "w": 1, "u": 1, "r": 1}], [{"*": 2, "u": 2}], [{"*": 2, "u": 2, "b": 2}], [{"*": 2, "u": 2, "b": 2, "r": 2}], [{"*": 2, "u": 2, "r": 2}], [{"*": 2, "u": 3}], [{"*": 2, "u": 4}], [{"*": 2, "w": 1}], [{"*": 2, "w": 1, "b": 1}], [{"*": 2, "w": 1, "b": 1, "g": 1}], [{"*": 2, "w": 1, "u": 1}], [{"*": 2, "w": 1, "u": 1, "b": 1}], [{"*": 2, "w": 1, "u": 2}], [{"*": 2, "w": 1, "u": 2, "b": 1}], [{"*": 2, "w": 2}], [{"*": 2, "w": 2, "b": 1}], [{"*": 2, "w": 2, "b": 2}], [{"*": 2, "w": 2, "u": 2}], [{"*": 2, "w": 2, "u": 2, "b": 2}], [{"*": 2, "w": 3}], [{"*": 3}], [{"*": 3, "b": 1}], [{"*": 3, "b": 2}], [{"*": 3, "b": 3}], [{"*": 3, "b": 4}], [{"*": 3, "b": 2, "g": 1}], [{"*": 3, "b": 2, "r": 1}], [{"*": 3, "b": 2, "r": 2}], [{"*": 3, "b": 1, "g": 1}], [{"*": 3, "u": 1, "b": 1, "g": 1}], [{"*": 3, "w": 1, "b": 1, "g": 1}], [{"*": 3, "b": 1, "r": 1}], [{"*": 3, "b": 1, "r": 1, "g": 1}], [{"*": 3, "g": 1}], [{"*": 3, "g": 2}], [{"*": 3, "g": 3}], [{"*": 3, "g": 4}], [{"*": 3, "w": 1, "g": 2}], [{"*": 3, "w": 2, "g": 2}], [{"*": 3, "u": 1, "g": 1}], [{"*": 3, "u": 1, "b": 1, "g": 1}], [{"*": 3, "u": 1, "r": 1, "g": 1}], [{"*": 3, "w": 1, "g": 1}], [{"*": 3, "w": 1, "u": 1, "g": 1}], [{"*": 3, "w": 2, "g": 1}], [{"*": 3, "r": 1}], [{"*": 3, "r": 1, "g": 1}], [{"*": 3, "r": 1, "g": 2}], [{"*": 3, "w": 1, "r": 1, "g": 1}], [{"*": 3, "r": 2}], [{"*": 3, "r": 2, "g": 1}], [{"*": 3, "r": 2, "g": 2}], [{"*": 3, "r": 3}], [{"*": 3, "r": 4}], [{"*": 3, "w": 1, "r": 1}], [{"*": 3, "w": 1, "b": 1, "r": 1}], [{"*": 3, "w": 1, "u": 1, "r": 1}], [{"*": 3, "w": 2, "r": 1}], [{"*": 3, "u": 1}], [{"*": 3, "u": 1, "b": 1}], [{"*": 3, "u": 1, "b": 2}], [{"*": 3, "u": 1, "b": 1, "r": 1}], [{"*": 3, "u": 1, "r": 1}], [{"*": 3, "u": 1, "r": 1, "g": 1}], [{"*": 3, "w": 1, "u": 1, "r": 1}], [{"*": 3, "u": 2}], [{"*": 3, "u": 2, "b": 1}], [{"*": 3, "u": 2, "b": 2}], [{"*": 3, "u": 3}], [{"*": 3, "w": 1}], [{"*": 3, "w": 1, "b": 1}], [{"*": 3, "w": 1, "b": 2}], [{"*": 3, "w": 1, "b": 1, "g": 1}], [{"*": 3, "w": 1, "b": 1, "r": 1}], [{"*": 3, "w": 1, "u": 1}], [{"*": 3, "w": 1, "u": 1, "b": 1}], [{"*": 3, "w": 1, "u": 1, "b": 1, "r": 1, "g": 1}], [{"*": 3, "w": 1, "u": 2}], [{"*": 3, "w": 2}], [{"*": 3, "w": 2, "b": 2}], [{"*": 3, "w": 2, "u": 1}], [{"*": 3, "w": 2, "u": 2}], [{"*": 3, "w": 3}], [{"*": 4, "b": 1}], [{"*": 4, "b": 2}], [{"*": 4, "b": 3}], [{"*": 4, "b": 4}], [{"*": 4, "b": 2, "g": 2}], [{"*": 4, "b": 2, "r": 2}], [{"*": 4, "b": 1, "g": 1}], [{"*": 4, "b": 1, "r": 1}], [{"*": 4, "b": 1, "r": 1, "g": 1}], [{"*": 4, "b": 1, "r": 2}], [{"*": 4, "b": 1, "r": 2, "g": 1}], [{"*": 4, "g": 1}], [{"*": 4, "g": 2}], [{"*": 4, "g": 3}], [{"*": 4, "g": 4}], [{"*": 4, "w": 2, "g": 2}], [{"*": 4, "u": 1, "g": 1}], [{"*": 4, "u": 1, "b": 1, "g": 1}], [{"*": 4, "w": 1, "g": 1}], [{"*": 4, "w": 2, "u": 1, "g": 1}], [{"*": 4, "r": 1}], [{"*": 4, "r": 1, "g": 1}], [{"*": 4, "w": 1, "r": 1, "g": 2}], [{"*": 4, "w": 1, "r": 1, "g": 1}], [{"*": 4, "r": 2}], [{"*": 4, "r": 2, "g": 1}], [{"*": 4, "r": 2, "g": 2}], [{"*": 4, "r": 3}], [{"*": 4, "w": 2, "r": 2}], [{"*": 4, "w": 1, "r": 1}], [{"*": 4, "w": 2, "r": 1}], [{"*": 4, "u": 1}], [{"*": 4, "u": 1, "b": 1}], [{"*": 4, "u": 1, "b": 2, "r": 1}], [{"*": 4, "u": 1, "b": 1, "r": 1}], [{"*": 4, "u": 1, "r": 1}], [{"*": 4, "u": 2}], [{"*": 4, "u": 3}], [{"*": 4, "w": 1}], [{"*": 4, "w": 1, "b": 1}], [{"*": 4, "w": 1, "b": 2}], [{"*": 4, "w": 1, "b": 1, "g": 1}], [{"*": 4, "w": 1, "b": 1, "r": 1}], [{"*": 4, "w": 1, "u": 1}], [{"*": 4, "w": 1, "u": 1, "b": 1}], [{"*": 4, "w": 1, "u": 2, "b": 1}], [{"*": 4, "w": 2}], [{"*": 4, "w": 2, "b": 2}], [{"*": 4, "w": 2, "u": 1}], [{"*": 4, "w": 3}], [{"*": 5}], [{"*": 5, "b": 1}], [{"*": 5, "b": 2}], [{"*": 5, "b": 3}], [{"*": 5, "b": 1, "g": 1}], [{"*": 5, "w": 1, "b": 1, "g": 1}], [{"*": 5, "b": 1, "r": 1}], [{"*": 5, "g": 1}], [{"*": 5, "g": 2}], [{"*": 5, "g": 3}], [{"*": 5, "u": 1, "g": 1}], [{"*": 5, "u": 2, "g": 1}], [{"*": 5, "w": 1, "g": 1}], [{"*": 5, "r": 1}], [{"*": 5, "r": 1, "g": 1}], [{"*": 5, "r": 2}], [{"*": 5, "r": 3}], [{"*": 5, "w": 1, "r": 1}], [{"*": 5, "u": 1}], [{"*": 5, "u": 1, "b": 1}], [{"*": 5, "u": 1, "b": 2}], [{"*": 5, "u": 1, "r": 1}], [{"*": 5, "u": 1, "r": 1, "g": 1}], [{"*": 5, "u": 2}], [{"*": 5, "u": 3}], [{"*": 5, "u": 4}], [{"*": 5, "w": 1}], [{"*": 5, "w": 1, "b": 1}], [{"*": 5, "w": 1, "u": 1}], [{"*": 5, "w": 1, "u": 1, "b": 1}], [{"*": 5, "w": 2}], [{"*": 5, "w": 2, "u": 1}], [{"*": 5, "w": 3}], [{"*": 6}], [{"*": 6, "b": 1}], [{"*": 6, "b": 2}], [{"*": 6, "b": 3}], [{"*": 6, "b": 1, "g": 1}], [{"*": 6, "b": 1, "r": 1}], [{"*": 6, "g": 1}], [{"*": 6, "g": 2}], [{"*": 6, "g": 3}], [{"*": 6, "w": 1, "g": 1}], [{"*": 6, "r": 1}], [{"*": 6, "r": 2}], [{"*": 6, "r": 3}], [{"*": 6, "u": 1}], [{"*": 6, "u": 2}], [{"*": 6, "u": 3}], [{"*": 6, "w": 1}], [{"*": 6, "w": 2}], [{"*": 6, "w": 3}], [{"*": 7}], [{"*": 7, "b": 1}], [{"*": 7, "b": 2}], [{"*": 7, "b": 3}], [{"*": 7, "g": 1}], [{"*": 7, "g": 2}], [{"*": 7, "g": 3}], [{"*": 7, "r": 1}], [{"*": 7, "r": 2}], [{"*": 7, "r": 3}], [{"*": 7, "u": 1}], [{"*": 7, "u": 2}], [{"*": 7, "u": 3}], [{"*": 7, "w": 1}], [{"*": 7, "w": 2}], [{"*": 7, "w": 3}], [{"*": 8}], [{"*": 8, "b": 1}], [{"*": 8, "b": 2}], [{"*": 8, "b": 3}], [{"*": 8, "b": 2, "g": 2}], [{"*": 8, "g": 1}], [{"*": 8, "g": 2}], [{"*": 8, "g": 3}], [{"*": 8, "r": 1}], [{"*": 8, "r": 2}], [{"*": 8, "u": 2}], [{"*": 8, "u": 3}], [{"*": 8, "u": 4}], [{"*": 8, "w": 2}], [{"*": 9}], [{"*": 9, "b": 1}], [{"*": 9, "r": 1}], [{"b": 1}], [{"b": 2}], [{"b": 3}], [{"b": 4}], [{"b": 15}], [{"b": 2, "g": 2}], [{"b": 2, "r": 1}], [{"b": 2, "r": 2}], [{"b": 2, "r": 3, "g": 2}], [{"b": 1, "g": 1}], [{"b": 1, "g": 2}], [{"u": 1, "b": 1, "g": 1}], [{"w": 1, "b": 1, "g": 1}], [{"b": 1, "r": 1}], [{"b": 1, "r": 1, "g": 1}], [{"w": 1, "b": 1, "r": 1, "g": 1}], [{"g": 1}], [{"g": 2}], [{"g": 3}], [{"g": 4}], [{"g": 5}], [{"g": 6}], [{"g": 8}], [{"w": 3, "g": 3}], [{"u": 2, "g": 2}], [{"w": 1, "g": 2}], [{"w": 2, "g": 2}], [{"w": 3, "u": 2, "g": 2}], [{"u": 1, "g": 1}], [{"u": 1, "r": 1, "g": 1}], [{"u": 2, "g": 1}], [{"w": 1, "g": 1}], [{"w": 1, "u": 1, "g": 1}], [{"w": 1, "u": 1, "b": 1, "g": 1}], [{"r": 1}], [{"r": 1, "g": 1}], [{"w": 1, "r": 1, "g": 1}], [{"w": 1, "u": 1, "r": 1, "g": 1}], [{"r": 2}], [{"r": 2, "g": 2}], [{"w": 2, "r": 2, "g": 3}], [{"r": 3}], [{"r": 4}], [{"w": 1, "r": 1}], [{"w": 1, "b": 1, "r": 1}], [{"u": 1}], [{"u": 1, "b": 1}], [{"u": 1, "b": 2, "r": 1}], [{"u": 1, "b": 1, "r": 1}], [{"u": 1, "b": 1, "r": 1, "g": 1}], [{"u": 1, "r": 1}], [{"u": 1, "r": 1, "g": 1}], [{"u": 1, "r": 2}], [{"w": 1, "u": 1, "r": 1}], [{"u": 2}], [{"u": 2, "b": 1}], [{"u": 2, "b": 2}], [{"u": 2, "b": 3, "r": 2}], [{"u": 2, "r": 1}], [{"u": 3}], [{"u": 4}], [{"w": 1}], [{"w": 1, "b": 1}], [{"w": 1, "b": 2}], [{"w": 1, "b": 1, "g": 1}], [{"w": 1, "u": 1}], [{"w": 1, "u": 1, "b": 1}], [{"w": 1, "u": 1, "b": 1, "r": 1}], [{"w": 1, "u": 1, "b": 1, "r": 1, "g": 1}], [{"w": 1, "u": 2}], [{"w": 1, "u": 2, "b": 1}], [{"w": 2}], [{"w": 2, "b": 2}], [{"w": 2, "u": 2}], [{"w": 2, "u": 2, "b": 2, "r": 2, "g": 2}], [{"w": 2, "u": 3, "b": 2}], [{"w": 3}], [{"w": 4}]]}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5686004a2c7fade6b500002d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "parse_mana_cost", "task_id": "TACO_lite/186", "example": [[], []]} +{"requirement": "You are given an array of integers. Your task is to sort odd numbers within the array in ascending order, and even numbers in descending order.\n\nNote that zero is an even number. If you have an empty array, you need to return it.\n\n\nFor example:\n```\n[5, 3, 2, 8, 1, 4] --> [1, 3, 8, 4, 5, 2]\n\nodd numbers ascending: [1, 3, 5 ]\neven numbers descending: [ 8, 4, 2]\n```", "solutions": ["def sort_array(xs):\n es = sorted((x for x in xs if x % 2 == 0))\n os = sorted((x for x in xs if x % 2 != 0), reverse=True)\n return [(es if x % 2 == 0 else os).pop() for x in xs]", "def sort_array(a):\n odds = []\n evens = []\n newArray = []\n for i in a:\n if i % 2 == 0:\n evens.append(i)\n else:\n odds.append(i)\n evens.sort()\n evens.reverse()\n odds.sort()\n for i in range(len(a)):\n if a[i] % 2 == 0:\n newArray.append(evens[0])\n evens.pop(0)\n else:\n newArray.append(odds[0])\n odds.pop(0)\n return newArray", "def sort_array(a):\n odds = iter(sorted((n for n in a if n % 2)))\n evens = iter(sorted((n for n in a if not n % 2), reverse=True))\n return [next(odds) if n % 2 else next(evens) for n in a]", "def sort_array(a):\n (sorted_odd, sorted_even) = (sorted((value for value in a if value & 1)), sorted([value for value in a if not value & 1], reverse=True))\n return [sorted_odd.pop(0) if value & 1 else sorted_even.pop(0) for value in a]", "def sort_array(a):\n (e, o) = (sorted((x for x in a if x % 2 ^ 1)), sorted((x for x in a if x % 2), reverse=True))\n return [(o if x % 2 else e).pop() for x in a]", "def sort_array(a):\n sorted_odd = sorted([x for x in a if x % 2 == 1], reverse=True)\n sorted_even = sorted([x for x in a if x % 2 == 0])\n out = []\n for x in a:\n if x % 2 == 0:\n out.append(sorted_even.pop())\n else:\n out.append(sorted_odd.pop())\n return out", "def sort_array(lst):\n s = sorted(lst)\n even = (n for n in s[::-1] if n & 1 == 0)\n odd = (n for n in s if n & 1)\n return [next(odd if n & 1 else even) for n in lst]", "def sort_array(lst):\n (even, odd) = ([], [])\n for n in sorted(lst):\n (odd if n & 1 else even).append(n)\n (even, odd) = (iter(even[::-1]), iter(odd))\n return [next(odd if n & 1 else even) for n in lst]", "def sort_array(a):\n lenList = len(a)\n if lenList == 0:\n return []\n (evenNums, oddNums) = ([], [])\n (evenNumLoc, oddNumLoc) = ([], [])\n for i in range(0, lenList, 1):\n if a[i] % 2 == 0:\n evenNums.append(a[i])\n evenNumLoc.append(i)\n else:\n oddNums.append(a[i])\n oddNumLoc.append(i)\n evenNums.sort(reverse=True)\n oddNums.sort()\n sortedList = [0 for _ in range(lenList)]\n totalNumEvens = len(evenNums)\n totalNumOdds = len(oddNums)\n for i in range(0, totalNumEvens, 1):\n sortedList[evenNumLoc[i]] = evenNums[i]\n for i in range(0, totalNumOdds, 1):\n sortedList[oddNumLoc[i]] = oddNums[i]\n return sortedList", "from collections import deque\n\ndef sort_array(a):\n asc = deque(sorted((x for x in a if x % 2)))\n desc = sorted((x for x in a if not x % 2))\n return [asc.popleft() if x % 2 else desc.pop() for x in a]"], "starter_code": "def sort_array(a):\n", "input_output": {"fn_name": "sort_array", "inputs": [[[5, 3, 2, 8, 1, 4, 11]], [[2, 22, 37, 11, 4, 1, 5, 0]], [[1, 111, 11, 11, 2, 1, 5, 0]], [[]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 1, 2, 3, 4, 9, 8, 7, 6, 5]]], "outputs": [[[1, 3, 8, 4, 5, 2, 11]], [[22, 4, 1, 5, 2, 11, 37, 0]], [[1, 1, 5, 11, 2, 11, 111, 0]], [[]], [[1, 8, 3, 6, 5, 4, 7, 2, 9, 0]], [[8, 1, 6, 3, 4, 5, 2, 7, 0, 9]], [[8, 1, 6, 3, 4, 5, 2, 7, 0, 9]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Sorting"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/5a1cb5406975987dd9000028", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sort_array", "task_id": "TACO_lite/88", "example": [[[[5, 3, 2, 8, 1, 4]]], ["[1, 3, 8, 4, 5, 2]"]]} +{"requirement": "Your task is simply to count the total number of lowercase letters in a string.\n\n## Examples", "solutions": ["def lowercase_count(strng):\n return sum((a.islower() for a in strng))", "import re\n\ndef lowercase_count(string):\n return len(re.findall('[a-z]', string))", "def lowercase_count(str):\n return sum((1 for c in str if c.islower()))", "def lowercase_count(strng):\n return len([ch for ch in strng if ch.islower()])", "def lowercase_count(s):\n return sum((c.islower() for c in s))", "lowercase_count = lambda s: sum((e.islower() for e in s))", "def lowercase_count(s):\n return sum((1 for c in s if c.islower()))", "def lowercase_count(strng):\n return sum((1 for i in strng if i.islower()))", "import re\n\ndef lowercase_count(st):\n return len(re.sub('[^a-z]*', '', st))", "import re\n\ndef lowercase_count(text):\n return len(re.findall('[a-z]', text))", "import re\n\ndef lowercase_count(str):\n return len(re.findall('[a-z]', str))", "import re\nlowercase_count = lambda s: len(re.findall('[a-z]', s))", "import re\n\ndef lowercase_count(str):\n return len(re.sub('[^a-z]', '', str))", "def lowercase_count(s):\n return len(list(filter(lambda x: x in map(chr, range(97, 123)), s)))", "import re\n\ndef lowercase_count(strng):\n regex = re.compile('[a-z]')\n match = regex.findall(strng)\n if match:\n return len(match)\n return 0", "def lowercase_count(strg):\n c = 0\n case = 'abcdefghijklmnopqrstuvwxyz'\n for x in strg:\n if x in case:\n c = c + 1\n return c", "def lowercase_count(strng):\n lowers = 'abcdefghijklmnopqrstuvwxyz'\n count = 0\n for c in strng:\n if c in lowers:\n count += 1\n return count", "def lowercase_count(string):\n return sum(map(str.islower, string))", "variable = 'abc'\n\ndef lowercase_count(strng):\n array = []\n for x in strng:\n index = ord(x[0])\n if 97 <= index <= 122 and index > 91:\n variableForArray = chr(index)\n array.append(variableForArray)\n else:\n continue\n return len(array)", "def lowercase_count(strng):\n return len([i for i in strng if i.islower()])", "def lowercase_count(strng):\n lowerCastCount = 0\n for i in strng:\n if i.isdigit():\n None\n elif i.islower():\n lowerCastCount += 1\n return lowerCastCount", "from re import findall\n\ndef lowercase_count(string: str) -> int:\n return len(findall('[a-z]', string))", "def lowercase_count(strng):\n import re\n return len(re.findall('[a-z]', strng))", "def lowercase_count(strng):\n return sum(map(str.islower, strng))", "lowercase_count = lambda s: len([x for x in s if x in 'abcdefghijklmnopqrstuvwxyz'])", "def lowercase_count(strng):\n import string\n return len(''.join([i for i in strng if i in string.ascii_lowercase]))", "def lowercase_count(string):\n c = 0\n for i in string:\n if i.islower() == True:\n c += 1\n return c", "def lowercase_count(strng):\n l_1 = list(strng)\n l_2 = list('qwertyuiopasdfghjklzxcvbnm')\n l_3 = []\n for elem in l_1:\n if elem in l_2:\n l_3.append(elem)\n return len(l_3)", "def lowercase_count(s):\n return sum((1 for i in s if 'a' <= i <= 'z'))", "def lowercase_count(s):\n ALPHABET = 'abcdefghijklmnopqrstuvwxyz'\n return sum((x in ALPHABET for x in s))", "def lowercase_count(lst):\n n = 0\n for s in lst:\n if s >= 'a' and s <= 'z':\n n = n + 1\n return n", "def lowercase_count(strng):\n total = 0\n for i in list(strng):\n if i in list('qwertyuiopasdfghjklzxcvbnm'):\n total = total + 1\n return total", "def lowercase_count(strng):\n lc = 0\n for letter in strng:\n if 'z' >= letter >= 'a':\n lc += 1\n return lc", "def lowercase_count(strng):\n li = list(strng)\n counter = 0\n for c in range(len(li)):\n if 96 < ord(li[c]) < 123:\n counter += 1\n return counter", "def lowercase_count(strng):\n ans = 0\n for x in strng:\n if x.islower() == True:\n ans += 1\n return ans", "def lowercase_count(strng):\n i = 0\n for x in strng:\n if 'a' <= x <= 'z':\n i += 1\n return i", "def lowercase_count(strng):\n count = 0\n for chr in strng:\n if chr != chr.upper():\n count += 1\n return count", "def lowercase_count(strng):\n somme = 0\n for minuscule in strng:\n if minuscule.islower():\n somme += 1\n return somme", "def lowercase_count(string):\n lower_cases = 'abcdefghijklmnopqrstuvwxyz'\n lower_case_counter = 0\n index = 0\n while index < len(string):\n if string[index] in lower_cases:\n lower_case_counter += 1\n index += 1\n return lower_case_counter", "def lowercase_count(str):\n count = 0\n alpha = 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z'\n trex = alpha.split(',')\n for x in str:\n if x in trex:\n count += 1\n return count", "def lowercase_count(strng):\n return sum((True for i in strng if i.islower()))", "def lowercase_count(strng):\n import re\n from re import finditer\n pattern = '[a-z]'\n count = 0\n for it in finditer(pattern, strng):\n count += 1\n return count", "def lowercase_count(strng: str) -> int:\n return sum((c.islower() for c in strng))", "def lowercase_count(strng):\n lst = list(strng)\n count = 0\n for letter in lst:\n if letter.islower():\n count += 1\n return count", "import re\n\ndef lowercase_count(strng):\n pattern = re.compile('[a-z]{1}')\n matches = pattern.findall(strng)\n return len(matches)", "def lowercase_count(strng):\n count = 0\n for letter in strng:\n if letter.isalpha():\n if ord(letter) <= ord('z') and ord(letter) >= ord('a'):\n count += 1\n return count", "def lowercase_count(string):\n string = str(string)\n a = 0\n for i in string:\n if i.islower():\n a += 1\n return a", "def lowercase_count(string):\n res = 0\n for i in string:\n if ord(i) > 96 and ord(i) < 123:\n res += 1\n return res", "import re\n\ndef lowercase_count(strng):\n return len(''.join(re.findall('([a-z]+)', strng))) if re.search('([a-z]+)', strng) else 0", "def lowercase_count(strng):\n return sum((1 for n in strng if n.islower()))", "def lowercase_count(strng):\n return sum([int(x.islower()) for x in strng])", "import string\n\ndef lowercase_count(strng):\n return sum([x in string.ascii_lowercase for x in strng])", "def lowercase_count(strng):\n num = 0\n for chr in strng:\n if chr.islower() == True:\n num += 1\n return num", "def lowercase_count(strng):\n letters = str(strng)\n lowercase = 0\n for i in letters:\n if i.islower():\n lowercase += 1\n return lowercase", "def lowercase_count(strng):\n nb = 0\n for ch in strng:\n if ch.islower():\n nb += 1\n return nb", "def lowercase_count(strng):\n letters = 'abcdefghijklmnopqrstuvwxyz'\n return len([i for i in strng if i in letters])", "def lowercase_count(strng):\n lower = 0\n for letter in strng:\n if letter >= 'a' and letter <= 'z':\n lower += 1\n return lower", "def lowercase_count(strng):\n return sum([1 if c.islower() else 0 for c in strng])", "def lowercase_count(s):\n num = 0\n for i in s:\n if i.islower():\n num += 1\n return num", "def lowercase_count(strng):\n return sum((1 for string in strng if string in 'abcdefghijklmnopqrstuvwxyz'))", "import string\n\ndef lowercase_count(string):\n return len([x for x in string if x in 'abcdefghijklmnopqrstuvwxyz'])", "def lowercase_count(strng):\n count = 0\n for let in strng:\n if let.isalpha() and let == let.lower():\n count += 1\n return count", "def lowercase_count(strng):\n count = 0\n s = [i for i in strng]\n for x in s:\n if x.islower() == True:\n count += 1\n else:\n pass\n return count", "from re import sub\n\ndef lowercase_count(strng):\n return len(sub('[^a-z]', '', strng))", "from regex import sub\n\ndef lowercase_count(strng):\n return len(sub('[^a-z]', '', strng))", "def lowercase_count(string):\n lowercase = [c for c in string if c.islower()]\n return len(lowercase)", "import string\n\ndef lowercase_count(s):\n return sum([1 for i in s if i in string.ascii_lowercase])", "def lowercase_count(strng):\n sum = 0\n for i in range(len(strng)):\n if strng[i].islower() == True:\n sum += 1\n return sum", "def lowercase_count(strng):\n import re\n result = ''\n match = re.findall('[a-z]', strng)\n result = ''.join(match)\n return len(result)", "import re\n\ndef lowercase_count(strng):\n match = re.findall('[a-z]', strng)\n count = 0\n for i in match:\n count += 1\n return count", "def lowercase_count(strng):\n dgu = []\n rwp = []\n pwr = list(str(strng))\n pwr.sort()\n for lower in pwr:\n if lower.islower():\n rwp.append(lower)\n dgu = len(rwp)\n return dgu", "lowercase_count = lambda s: len(list(filter(str.islower, s)))", "def lowercase_count(s):\n return len([x for x in s if x in 'abcdefghijklmnopqrstuvwxyz'])", "def lowercase_count(strng):\n count = 0\n for i in strng:\n if i.islower():\n count += 1\n return count\nlowercase_count('cdfABH')", "import re\n\ndef lowercase_count(strng):\n ct = 0\n for i in range(len(strng)):\n if re.search('[a-z]', strng[i]) != None:\n ct += 1\n return ct", "def lowercase_count(strng):\n results = 0\n for letter in strng:\n if letter.islower():\n results = results + 1\n return results", "def lowercase_count(strng):\n counter = 0\n for el in strng:\n if el in 'qwertyuiopasdfghjklzxcvbnm':\n counter += 1\n return counter", "import re\n\ndef lowercase_count(strng):\n lower = [c for c in strng if re.search('[a-z]', c)]\n return len(lower)", "import string\n\ndef lowercase_count(strng):\n count = 0\n for str in strng:\n if str in string.ascii_lowercase:\n count += 1\n return count", "def lowercase_count(strng):\n lowercase = ''.join((c for c in strng if c.islower()))\n return len(lowercase)", "def lowercase_count(strng):\n c = 0\n for i in range(len(strng)):\n if strng[i] in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']:\n c = c + 1\n return c", "def lowercase_count(string):\n accum = 0\n abc = list('qwertyuioplkjhgfdsazxcvbnm')\n for i in string:\n if i in abc:\n accum += 1\n return accum", "def lowercase_count(strng):\n letters = list(strng)\n count = 0\n for i in letters:\n if ord(i) > 96 and ord(i) < 123:\n count += 1\n return count", "def lowercase_count(strng):\n count = 0\n for x in strng:\n if x.islower():\n count += 1\n else:\n return count", "def lowercase_count(string):\n sum = 0\n for i in string:\n if i.islower():\n sum += 1\n return sum", "def lowercase_count(strng):\n count = 0\n for char in strng:\n if char.islower() is True:\n count = count + 1\n else:\n continue\n return count", "import re\n\ndef lowercase_count(strng):\n r = re.compile('[a-z]')\n return len(r.findall(strng))", "def lowercase_count(strng):\n ctr = 0\n for i in strng:\n if i.islower():\n ctr += 1\n return ctr", "def lowercase_count(strng):\n n = 0\n for k in strng:\n if k.islower():\n n += 1\n return n", "def lowercase_count(strng):\n count = 0\n for el in strng:\n count = count + (1 if el != el.upper() else 0)\n return count", "def lowercase_count(strng):\n return len([i for i in strng if i.lower() == i and i.isalpha()])"], "starter_code": "def lowercase_count(strng):\n", "input_output": {"fn_name": "lowercase_count", "inputs": [["abc"], ["abcABC123"], ["abcABC123!@#$%^&*()_-+=}{[]|':;?/>.<,~"], [""], ["ABC123!@#$%^&*()_-+=}{[]|':;?/>.<,~"], ["abcdefghijklmnopqrstuvwxyz"]], "outputs": [[3], [3], [3], [0], [0], [26]]}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Algorithms", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56a946cd7bd95ccab2000055", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "lowercase_count", "task_id": "TACO_lite/242", "example": [[["hello world"], ["HELLO world"], [""]], ["10", "5", "0"]]} +{"requirement": "Given a rectangle of size\u00a0n\u00a0x m, find the minimum number of integer-sided squares that tile the rectangle.\n\u00a0\nExample 1:\n\nInput: n = 2, m = 3\nOutput: 3\nExplanation: 3 squares are necessary to cover the rectangle.\n2 (squares of 1x1)\n1 (square of 2x2)\nExample 2:\n\nInput: n = 5, m = 8\nOutput: 5\n\nExample 3:\n\nInput: n = 11, m = 13\nOutput: 6\n\n\u00a0\nConstraints:\n\n1 <= n <= 13\n1 <= m\u00a0<=\u00a013", "solutions": ["from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n if n == 11 and m == 13 or (m == 11 and n == 13):\n return 6\n\n def dfs(x, y):\n if x % y == 0:\n return x // y\n if y % x == 0:\n return y // x\n res = x * y\n for i in range(1, x // 2 + 1):\n res = min(res, dfs(x - i, y) + dfs(i, y))\n for k in range(1, y // 2 + 1):\n res = min(res, dfs(x, y - k) + dfs(x, k))\n return res\n return dfs(n, m)", "from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n\n def dfs(x, y):\n if x == y:\n return 1\n if x == 1:\n return y\n if y == 1:\n return x\n result = x * y\n for i in range(1, x // 2 + 1):\n result = min(result, dfs(i, y) + dfs(x - i, y))\n for k in range(1, y // 2 + 1):\n result = min(result, dfs(x, k) + dfs(x, y - k))\n for centre_sq_size in range(1, min(x, y)):\n for i in range(1, x - centre_sq_size):\n for k in range(1, y - centre_sq_size):\n partition1 = dfs(i + centre_sq_size, k)\n partition2 = dfs(x - i - centre_sq_size, k + centre_sq_size)\n partition3 = dfs(i, y - k)\n partition4 = dfs(x - i, y - k - centre_sq_size)\n partition5 = 1\n result = min(result, partition1 + partition2 + partition3 + partition4 + partition5)\n return result\n return dfs(n, m)", "from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n INF = m * n\n\n def dp(state):\n if n == min(state):\n return 0\n state = list(state)\n mn = min(state)\n start = state.index(mn)\n res = INF\n for end in range(start, m):\n if state[end] != mn:\n break\n side = end - start + 1\n if mn + side > n:\n break\n state[start:end + 1] = [mn + side] * side\n res = min(res, dp(tuple(state)))\n return res + 1\n if m > n:\n (m, n) = (n, m)\n return dp(tuple([0] * m))", "def gcd(a, b):\n while a:\n (a, b) = (b % a, a)\n return b\n\ndef tilingrectangle(n: int, m: int) -> int:\n d = gcd(n, m)\n if d != 1:\n return self.tilingrectangle(n // d, m // d)\n if n > m:\n (n, m) = (m, n)\n if m % n == 0:\n return m // n\n heights = [0] * n\n recs = [[0, 1]]\n CAP = max(n, m)\n ans = CAP\n\n def is_valid():\n if len(recs) > ans - 1:\n return False\n (i, side) = recs[-1]\n if heights[i] + 1 > m:\n return False\n if i + side > n:\n return False\n if heights[i + side - 1] > heights[i]:\n return False\n return True\n while recs:\n if is_valid():\n (i, side) = recs[-1]\n for k in range(i, i + side - 1):\n heights[k] += 1\n heights[i + side - 1] += side\n (_, i) = min(((heights[k], k) for k in range(n)))\n if heights == [m] * n:\n ans = min(ans, len(recs))\n recs.append([i, 1])\n else:\n (i, side) = recs.pop()\n for k in range(i, i + side - 1):\n heights[k] -= side - 1\n if recs:\n recs[-1][-1] += 1\n return ans", "from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n\n def dfs(state):\n if n == min(state):\n return 0\n state = list(state)\n minimum = min(state)\n start = state.index(minimum)\n res = inf\n for end in range(start, m):\n if state[end] != minimum:\n break\n side = end - start + 1\n if minimum + side > n:\n break\n state[start:end + 1] = [minimum + side] * side\n res = min(res, dfs(tuple(state)))\n return res + 1\n inf = m * n\n if m > n:\n (m, n) = (n, m)\n return dfs(tuple([0] * m))", "def tilingrectangle(n: int, m: int) -> int:\n if m > n:\n (m, n) = (n, m)\n\n def dp(state):\n if min(state) == n:\n return 0\n state = list(state)\n mn = min(state)\n start = state.index(mn)\n res = float('inf')\n for end in range(start, m):\n if state[end] != mn:\n break\n side = end - start + 1\n if mn + side > n:\n break\n state[start:end + 1] = [mn + side] * side\n res = min(res, dp(tuple(state)))\n return res + 1\n return dp((0,) * m)", "def tilingrectangle(n: int, m: int) -> int:\n INF = m * n\n\n def dp(state, memo):\n if state in memo:\n return memo[state]\n if n == min(state):\n return 0\n state_ = list(state)\n mn = min(state_)\n start = state_.index(mn)\n res = INF\n for end in range(start, m):\n if state[end] != mn:\n break\n side = end - start + 1\n if mn + side > n:\n break\n state_[start:end + 1] = [mn + side] * side\n res = min(res, dp(tuple(state_), memo) + 1)\n memo[tuple(state)] = res\n return res\n if m > n:\n (m, n) = (n, m)\n return dp(tuple([0] * m), {})", "def tilingrectangle(n: int, m: int) -> int:\n res = 0\n dq = deque([[0] * m])\n seen = {tuple([0] * m)}\n while dq:\n length = len(dq)\n for _ in range(length):\n curr = dq.popleft()\n minh = min(curr)\n s = curr.index(minh)\n e = s\n while e + 1 < m and curr[e + 1] == minh:\n e += 1\n for i in range(min(e - s + 1, n - minh), 0, -1):\n nxt = curr[:]\n for j in range(s, s + i):\n nxt[j] += i\n nxt_state = tuple(nxt)\n if nxt_state in seen:\n continue\n if all((j == n for j in nxt)):\n return res + 1\n seen.add(nxt_state)\n dq.append(nxt)\n res += 1", "from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n\n def backtrack(state):\n if state in cache:\n return cache[state]\n if min(state) == n:\n return 0\n temp = state\n state = list(state)\n min_size = min(state)\n start = state.index(min_size)\n res = max_area\n for end in range(start, m):\n if state[end] != min_size:\n break\n size = end - start + 1\n if state[end] + size > n:\n break\n state[start:end + 1] = [min_size + size] * size\n res = min(res, backtrack(tuple(state)))\n cache[temp] = res + 1\n return cache[temp]\n max_area = m * n\n cache = {}\n if m > n:\n (m, n) = (n, m)\n return backtrack((0,) * m)", "def tilingrectangle(n: int, m: int) -> int:\n\n def helper(heights):\n mh = min(heights)\n if mh == n:\n return 0\n ret = float('inf')\n j = heights.index(mh)\n w = 1\n while mh + w <= n and j + w - 1 < m and (heights[j + w - 1] == mh):\n ret = min(ret, 1 + helper(heights[:j] + (mh + w,) * w + heights[j + w:]))\n w += 1\n return ret\n return helper((0,) * m)", "import functools\n\ndef tilingrectangle(n: int, m: int) -> int:\n\n def dfs(i, j):\n if i == j:\n return 1\n if i == 1:\n return j\n if j == 1:\n return i\n res = i * j\n for x in range(1, i // 2 + 1):\n res = min(res, dfs(x, j) + dfs(i - x, j))\n for y in range(1, j // 2 + 1):\n res = min(res, dfs(i, y) + dfs(i, j - y))\n for leng in range(1, min(x, y)):\n for x in range(1, i - leng):\n for y in range(1, j - leng):\n res = min(res, dfs(x + leng, y) + dfs(i - (x + leng), y + leng) + dfs(x, j - y) + dfs(i - x, j - (y + leng)) + 1)\n return res\n return dfs(m, n)", "def tilingrectangle(n: int, m: int) -> int:\n\n def dp(x=n, y=m):\n if x == y:\n return 1\n r = m * n\n for i in range(1, x // 2 + 1):\n r = min(r, dp(i, y) + dp(x - i, y))\n for k in range(1, y // 2 + 1):\n r = min(r, dp(x, k) + dp(x, y - k))\n for l in range(1, min(x, y)):\n for i in range(1, x - l):\n for k in range(1, y - l):\n p1 = dp(i + l, k)\n p2 = dp(x - i - l, l + k)\n p3 = dp(i, y - k)\n p4 = dp(x - i, y - k - l)\n r = min(r, p1 + p2 + p3 + p4 + 1)\n return r\n return dp()", "def tilingrectangle(n: int, m: int) -> int:\n (m, n) = (min(m, n), max(m, n))\n self.res = n * m\n self.H = n\n self.search(0, [0] * m)\n return self.res\n\ndef search(count, heights):\n if count >= self.res:\n return\n min_h = min(heights)\n if min_h == self.H:\n self.res = count\n return\n l = heights.index(min_h)\n width = 1\n while width <= self.H - min_h and l + width - 1 < len(heights) and (heights[l + width - 1] == heights[l]):\n width += 1\n width -= 1\n for w in range(width, 0, -1):\n self.search(count + 1, heights[:l] + [min_h + w] * w + heights[l + w:])", "def tilingrectangle(n: int, m: int) -> int:\n dp = [[sys.maxsize] * (m + 1) for _ in range(n + 1)]\n\n def getdp(n, m):\n if dp[n][m] != sys.maxsize:\n return dp[n][m]\n if n == 0 or m == 0:\n return 0\n if m == n:\n return 1\n if m == 1:\n return n\n if n == 1:\n return m\n ans = n * m\n for i in range(1, n // 2 + 1):\n ans = min(ans, getdp(i, m) + getdp(n - i, m))\n for i in range(1, m // 2 + 1):\n ans = min(ans, getdp(n, i) + getdp(n, m - i))\n for l in range(1, min(n, m) - 2):\n for i in range(2, n + 1 - l):\n for j in range(2, m + 1 - l):\n ans = min(ans, getdp(i + l - 1, j - 1) + getdp(i - 1, m - j + 1) + getdp(n - (i + l - 1), j + l - 1) + getdp(n - i + 1, m - (j + l - 1)) + 1)\n dp[n][m] = ans\n return ans\n return getdp(n, m)", "def tilingrectangle(n: int, m: int) -> int:\n self.best = m * n\n\n def dfs(heights, count):\n if min(heights) == n:\n self.best = min(self.best, count)\n return\n if count >= self.best:\n return\n min_height = min(heights)\n idx = heights.index(min_height)\n right_end = idx + 1\n while right_end < m and heights[right_end] == min_height:\n right_end += 1\n max_possible_box = min(right_end - idx, n - min_height)\n for box_size in range(max_possible_box, 0, -1):\n new_heights = heights[:]\n for i in range(box_size):\n new_heights[idx + i] += box_size\n dfs(new_heights, count + 1)\n dfs([0] * m, 0)\n return self.best", "def tilingrectangle(n: int, m: int) -> int:\n if n > m:\n return self.tilingrectangle(m, n)\n ans = n * m\n h = [0] * n\n\n def getmin(l):\n minv = 100000\n mini = -1\n for i in range(len(l)):\n if l[i] < minv:\n minv = l[i]\n mini = i\n return (minv, mini)\n\n def dfs(cur):\n nonlocal ans\n if cur >= ans:\n return\n (it, iti) = getmin(h)\n if it == m:\n ans = cur\n return\n low = it\n s = iti\n e = s\n while e < n and h[e] == h[s] and (e - s + 1 <= m - low):\n e += 1\n e -= 1\n for i in range(e, s - 1, -1):\n size = i - s + 1\n for j in range(s, i + 1):\n h[j] += size\n dfs(cur + 1)\n for j in range(s, i + 1):\n h[j] -= size\n dfs(0)\n return ans", "def tilingrectangle(n: int, m: int) -> int:\n self.best = m * n\n\n def dfs(height, moves):\n if all((h == n for h in height)):\n self.best = min(self.best, moves)\n return\n if moves >= self.best:\n return\n min_height = min(height)\n idx = height.index(min_height)\n ridx = idx + 1\n while ridx < m and height[ridx] == min_height:\n ridx += 1\n for i in range(min(ridx - idx, n - min_height), 0, -1):\n new_height = height[:]\n for j in range(i):\n new_height[idx + j] += i\n dfs(new_height, moves + 1)\n dfs([0] * m, 0)\n return self.best", "def tilingrectangle(m: int, n: int) -> int:\n self.ans = m * n\n\n def helper(h, res):\n if all((x == m for x in h)):\n self.ans = min(self.ans, res)\n return\n if res >= self.ans:\n return\n temp = min(h)\n ind = h.index(temp)\n r = ind + 1\n while r < min(n, ind + m - temp + 1) and h[r] == temp:\n r += 1\n for i in range(min(r - ind, m - temp), 0, -1):\n new_h = h[:]\n for j in range(ind, ind + i):\n new_h[j] += i\n helper(new_h, res + 1)\n helper([0] * n, 0)\n return self.ans", "def tilingrectangle(n: int, m: int) -> int:\n if n < m:\n return self.tilingrectangle(m, n)\n h = [0] * m\n self.ans = 100000\n self.dfs(n, m, h, 0)\n return self.ans\n\ndef dfs(m, n, h, cur):\n if cur >= self.ans:\n return\n min_h = min(h)\n if min_h == m:\n self.ans = min(self.ans, cur)\n return\n for j in range(n):\n if h[j] == min_h:\n break\n start = j\n while j + 1 < n and h[j] == h[j + 1] and (j + 1 - start + 1 + h[j] <= m):\n j += 1\n side = j - start + 1\n for k in reversed(range(1, side + 1)):\n temp = list(h)\n for j in range(start, start + k):\n temp[j] += k\n self.dfs(m, n, temp, cur + 1)", "def tilingrectangle(n: int, m: int) -> int:\n memo = {}\n return self.dfs(n, m, memo)\n\ndef dfs(x, y, memo):\n if x == 0 or y == 0:\n return 0\n if x == y:\n return 1\n if x == 1:\n return y\n if y == 1:\n return x\n if (x, y) in memo:\n return memo[x, y]\n ans = float('inf')\n for i in range(1, x):\n ans = min(ans, self.dfs(i, y, memo) + self.dfs(x - i, y, memo))\n for j in range(1, y):\n ans = min(ans, self.dfs(x, j, memo) + self.dfs(x, y - j, memo))\n for side in range(1, min(x, y)):\n for i in range(x - side):\n for j in range(y - side):\n ans1 = self.dfs(i, j + side, memo)\n ans2 = self.dfs(x - i, j, memo)\n ans3 = self.dfs(x - i - side, y - j, memo)\n ans4 = self.dfs(i + side, y - j - side, memo)\n ans = min(ans, ans1 + ans2 + ans3 + ans4 + 1)\n memo[x, y] = ans\n return memo[x, y]", "def tilingrectangle(n: int, m: int) -> int:\n self.result = n * m\n heights = [0] * n\n\n def dfs(cur):\n if cur >= self.result:\n return\n curMinHeight = min(heights)\n if curMinHeight == m:\n self.result = cur\n return\n end = start = heights.index(curMinHeight)\n while end < n and heights[start] == heights[end] and (end - start + 1 + curMinHeight <= m):\n end += 1\n for i in range(end - 1, start - 1, -1):\n size = i - start + 1\n for j in range(start, i + 1):\n heights[j] += size\n dfs(cur + 1)\n for j in range(start, i + 1):\n heights[j] -= size\n dfs(0)\n return self.result", "def tilingrectangle(n: int, m: int) -> int:\n if n < m:\n (n, m) = (m, n)\n if m == n:\n return 1\n heights = [0] * n\n dp = {}\n final = [m * n]\n\n def helper(heights, counts):\n key = tuple(heights)\n if counts >= final[0]:\n return\n if all((h == m for h in heights)):\n final[0] = min(final[0], counts)\n return\n if key in dp and dp[key] <= counts:\n return\n dp[key] = counts\n min_val = min(heights)\n idx = heights.index(min_val)\n d = 0\n for i in range(idx, n):\n if heights[i] == min_val:\n d += 1\n else:\n break\n d = min(m - min_val, d)\n for i in range(d, 0, -1):\n if heights[idx] + i <= m:\n helper(heights[:idx] + [heights[idx] + i] * i + heights[idx + i:], counts + 1)\n return\n helper(heights, 0)\n return final[0]", "def tilingrectangle(n: int, m: int) -> int:\n if m == n:\n return 1\n if n > m:\n (m, n) = (n, m)\n h_i = [0] * n\n visited = {}\n res = [m * n]\n\n def dfs(height, cnt):\n if cnt > res[0]:\n return\n status = tuple(height)\n if status in visited and visited[status] <= cnt:\n return\n visited[status] = cnt\n complete = True\n start_j = -1\n lowest_h = m + 1\n for j in range(n):\n if height[j] < m:\n complete = False\n if height[j] < lowest_h:\n start_j = j\n lowest_h = height[j]\n if complete:\n res[0] = min(res[0], cnt)\n return\n j = start_j\n while j < n and height[j] == lowest_h:\n j += 1\n max_l = min(j - start_j, m - lowest_h)\n for l in range(max_l, 0, -1):\n next_h = list(height)\n for k in range(l):\n next_h[start_j + k] += l\n dfs(next_h, cnt + 1)\n dfs(h_i, 0)\n return res[0]", "def tilingrectangle(n: int, m: int) -> int:\n if n > m:\n (n, m) = (m, n)\n res = n * m\n\n def dfs(heights, count, rem_area):\n nonlocal res\n if count >= res:\n return\n (lowest_idx, lowest_height, width, prev) = (-1, math.inf, 0, -1)\n for i in range(m):\n if heights[i] < lowest_height:\n (lowest_height, lowest_idx, width, prev) = (heights[i], i, 1, i)\n elif heights[i] == lowest_height and prev == i - 1:\n (width, prev) = (width + 1, i)\n if rem_area == 0:\n res = min(res, count)\n return\n width = min(width, n - lowest_height)\n for w in range(width, 0, -1):\n temp = heights.copy()\n for j in range(lowest_idx, lowest_idx + w):\n temp[j] += w\n dfs(temp, count + 1, rem_area - w * w)\n dfs([0] * m, 0, n * m)\n return res", "def tilingrectangle(n: int, m: int) -> int:\n self.res = n * m\n\n def dfs(heights, moves):\n if min(heights) == m:\n self.res = min(self.res, moves)\n return\n if moves == self.res:\n return\n minh = min(heights)\n left = right = heights.index(minh)\n while right < n and heights[right] == minh:\n right += 1\n for size in range(min(m - minh, right - left), 0, -1):\n newh = heights[:]\n for i in range(size):\n newh[left + i] += size\n dfs(newh, moves + 1)\n dfs([0] * n, 0)\n return self.res", "def tilingrectangle(n: int, m: int) -> int:\n self.best = n * m\n\n def dfs(hts, mvs):\n if mvs >= self.best:\n return\n if all((h == n for h in hts)):\n self.best = min(self.best, mvs)\n return\n i = min(list(range(m)), key=lambda i: hts[i])\n j = i + ([hts[k] != hts[i] for k in range(i, m)] + [True]).index(True)\n for x in range(min(j - i, n - hts[i]), 0, -1):\n for k in range(x):\n hts[i + k] += x\n dfs(hts, mvs + 1)\n for k in range(x):\n hts[i + k] -= x\n dfs([0] * m, 0)\n return self.best", "def tilingrectangle(m, n):\n self.best = n * m\n\n def dfs(heights, mvs):\n if mvs >= self.best:\n return\n if all((h == n for h in heights)):\n self.best = min(self.best, mvs)\n return\n i = j = min(list(range(m)), key=lambda i: heights[i])\n while j < m and heights[j] == heights[i]:\n j += 1\n for x in range(min(j - i, n - heights[i]), 0, -1):\n dfs(heights[:i] + [heights[i] + x] * x + heights[i + x:], mvs + 1)\n heights = [0] * m\n dfs(heights, 0)\n return self.best", "def tilingrectangle(n: int, m: int) -> int:\n if m == n:\n return 1\n if n < m:\n (m, n) = (n, m)\n if m == 1:\n return n\n if m == 2:\n (k, rem) = divmod(n, 2)\n return k + 2 * rem\n\n def recurse(h, ct):\n nonlocal Min\n if ct >= Min:\n return\n if all((x == m for x in h)):\n Min = min(Min, ct)\n return\n i = j = min(list(range(n)), key=lambda c: h[c])\n hi = h[i]\n bound = min(n, i + m - hi)\n while j < bound and h[j] == hi:\n j += 1\n for x in range(j - i, 0, -1):\n recurse(h[:i] + [hi + x] * x + h[i + x:], ct + 1)\n Min = m * n\n recurse([0] * n, 0)\n return Min", "def tilingrectangle(n: int, m: int) -> int:\n self.result = n * m\n\n def dfs(heights, moves):\n if moves > self.result:\n return\n if all((h == n for h in heights)):\n self.result = min(self.result, moves)\n return\n min_height = min(heights)\n idx = heights.index(min_height)\n right_boundary = idx + 1\n while right_boundary < m and heights[right_boundary] == min_height:\n right_boundary += 1\n for i in range(min(right_boundary - idx, n - min_height), 0, -1):\n dfs(heights[:idx] + [min_height + i] * i + heights[idx + i:], moves + 1)\n dfs([0] * m, 0)\n return self.result", "def tilingrectangle(n: int, m: int):\n cache = [[-1 for i in range(m + 1)] for j in range(n + 1)]\n return self.helper(n, m, cache)\n\ndef helper(n: int, m: int, cache) -> int:\n if n <= 0 or m <= 0:\n return 0\n if n == 11 and m == 13 or (n == 13 and m == 11):\n return 6\n if n == m:\n return 1\n if cache[n][m] != -1:\n return cache[n][m]\n rr1 = 10000\n rr2 = 10000\n _min = 10000\n for x in range(1, min(n, m) + 1):\n rr1 = self.helper(n, m - x, cache) + self.helper(n - x, x, cache)\n rr2 = self.helper(n - x, m, cache) + self.helper(x, m - x, cache)\n _min = min(rr1, min(rr2, _min))\n cache[n][m] = _min + 1\n return _min + 1", "def tilingrectangle(n: int, m: int) -> int:\n if n == m:\n return 1\n if n > m:\n (n, m) = (m, n)\n layers0 = [0 for _ in range(n)]\n visited = {}\n ans = [n * m]\n\n def dfs(layers, stepsNow):\n if stepsNow > ans[0]:\n return\n key = tuple(layers)\n if key in visited and stepsNow >= visited[key]:\n return\n visited[key] = stepsNow\n minH = m + 1\n i0 = -1\n for (i, h) in enumerate(layers):\n if h < minH:\n minH = h\n i0 = i\n if minH == m:\n ans[0] = min(ans[0], stepsNow)\n return\n minHWidth = 0\n maxL = m - minH\n for i in range(i0, n):\n if layers[i] == minH:\n minHWidth += 1\n else:\n break\n maxL = min(maxL, minHWidth)\n for l in range(maxL, 0, -1):\n nextLayers = list(key)\n for i in range(i0, i0 + l):\n nextLayers[i] += l\n dfs(nextLayers, stepsNow + 1)\n return\n dfs(layers0, 0)\n return ans[0]", "def tilingrectangle(n: int, m: int) -> int:\n h = [0] * m\n self.ans = m * n\n\n def dfs(h: List[int], cur: int) -> None:\n min_h = min(h)\n if min_h == n:\n self.ans = min(self.ans, cur)\n return\n if cur > self.ans:\n return\n idx = h.index(min_h)\n j = idx\n while j < len(h) and h[j] == min_h:\n j += 1\n fill_width = j - idx\n fill_height = n - min_h\n for fill in range(min(fill_width, fill_height), 0, -1):\n for k in range(idx, idx + fill):\n h[k] += fill\n dfs(h, cur + 1)\n for k in range(idx, idx + fill):\n h[k] -= fill\n dfs(h, 0)\n return self.ans", "def tilingrectangle(n: int, m: int) -> int:\n s = {}\n\n def dfs(n, m, h, cnt):\n if cnt > self.res:\n return\n is_full = True\n pos = -1\n minh = float('inf')\n for i in range(1, n + 1):\n if h[i] < m:\n is_full = False\n if h[i] < minh:\n pos = i\n minh = h[i]\n if is_full:\n self.res = min(cnt, self.res)\n return\n key = 0\n base = m + 1\n for i in range(1, n + 1):\n key += h[i] * base\n base *= m + 1\n if key in s and s[key] <= cnt:\n return\n s[key] = cnt\n end = pos\n while end < n and h[end + 1] == h[pos] and (end + 1 - pos + 1 + minh <= m):\n end += 1\n for j in range(end, pos - 1, -1):\n curh = j - pos + 1\n nex = h[:]\n for k in range(pos, j + 1):\n nex[k] += curh\n dfs(n, m, nex, cnt + 1)\n if n == m:\n return 1\n if n > m:\n (n, m) = (m, n)\n dfs(n, m, [0] * (n + 1), 0)\n return self.res", "from collections import defaultdict\n\ndef tilingrectangle(n: int, m: int) -> int:\n row = tuple([m] * n)\n\n def valid(row, i, side):\n return i + side <= len(row) and all((h >= side for h in row[i:i + side]))\n dp = defaultdict(int)\n\n def count(row, i):\n if i >= len(row):\n return 0\n if row in dp:\n return dp[row]\n res = float('inf')\n side = 1\n while valid(row, i, side):\n nrow = list(row)\n for j in range(i, i + side):\n nrow[j] -= side\n ni = i\n while ni < len(row) and (not nrow[ni]):\n ni += 1\n res = min(res, 1 + count(tuple(nrow), ni))\n side += 1\n dp[row] = res\n return res\n return count(row, 0)", "def tilingrectangle(n: int, m: int) -> int:\n ans = math.inf\n matrix = [[0] * m for _ in range(n)]\n\n def dfs(r, c, count):\n nonlocal ans\n if count >= ans:\n return\n if r >= n:\n ans = count\n return\n if c >= m:\n dfs(r + 1, 0, count)\n return\n if matrix[r][c]:\n dfs(r, c + 1, count)\n return\n for i in range(min(n - r, m - c), 0, -1):\n if not check(r, c, i):\n break\n cover(r, c, i)\n dfs(r, c + i, count + 1)\n uncover(r, c, i)\n\n def check(r, c, k):\n return all((matrix[i][j] == 0 for i in range(r, r + k) for j in range(c, c + k)))\n\n def cover(r, c, k):\n for i in range(r, r + k):\n for j in range(c, c + k):\n matrix[i][j] = 1\n\n def uncover(r, c, k):\n for i in range(r, r + k):\n for j in range(c, c + k):\n matrix[i][j] = 0\n dfs(0, 0, 0)\n return ans", "def tilingrectangle(n: int, m: int) -> int:\n memo = {}\n\n def helper(w, h):\n if w > h:\n (w, h) = (h, w)\n if (w, h) not in memo:\n if w == h:\n ans = 1\n elif w == 1:\n ans = h\n elif w == 0:\n ans = 0\n else:\n ans = w * h\n for iw in range(1, w // 2 + 1):\n ans = min(ans, helper(iw, h) + helper(w - iw, h))\n for ih in range(1, h // 2 + 1):\n ans = min(ans, helper(w, ih) + helper(w, h - ih))\n for iw in range(1, (w + 1) // 2):\n for ih in range(1, (h + 1) // 2):\n for s in range(1, min(w - 2 * iw, h - 2 * ih) + 1):\n ans = min(ans, 1 + helper(iw + s, ih) + helper(w - iw - s, ih + s) + helper(w - iw, h - ih - s) + helper(iw, h - ih))\n memo[w, h] = ans\n return memo[w, h]\n return helper(n, m)", "def tilingrectangle(n: int, m: int) -> int:\n if n > m:\n self.tilingrectangle(m, n)\n self.ans = n * m\n h = [0] * n\n self.dfs(h, 0, n, m)\n return self.ans\n\ndef dfs(h, cur, n, m):\n if cur >= self.ans:\n return\n min_h = min(h)\n if min_h == m:\n self.ans = cur\n return\n for i in range(n):\n if h[i] == min_h:\n break\n (start, end) = (i, i)\n while end < n and h[start] == h[end] and (end - start + 1 + min_h <= m):\n end += 1\n for i in reversed(list(range(start, end))):\n size = i - start + 1\n for j in range(start, i + 1):\n h[j] += size\n self.dfs(h, cur + 1, n, m)\n for j in range(start, i + 1):\n h[j] -= size", "def tilingrectangle(n: int, m: int) -> int:\n from functools import lru_cache\n\n def dp(n, m):\n (p, q) = (min(n, m), max(n, m))\n if p == 0:\n return 0\n if p == 1:\n return q\n if q % p == 0:\n return q // p\n minunits = p * q\n for r in range(1, p):\n minunits = min(minunits, 1 + dp(p - r, r) + dp(p, q - r))\n minunits = min(minunits, 1 + dp(q - r, r) + dp(q, p - r))\n for cl in range(1, n):\n for cr in range(1, n - cl):\n for rl in range(1, m):\n for rr in range(1, m - rl):\n minunits = min(minunits, dp(rl, n - cr) + dp(m - rl, cl) + dp(n - cl, rr) + dp(m - rr, cr) + dp(n - cl - cr, m - rl - rr))\n return minunits\n return dp(n, m)", "def tilingrectangle(n: int, m: int) -> int:\n if n > m:\n (n, m) = (m, n)\n if m == n:\n return 1\n res = [m * n]\n dp = {}\n\n def dfs(cnt, hs):\n if cnt > res[0]:\n return\n key = tuple(hs)\n if key in dp and dp[key] <= cnt:\n return\n dp[key] = cnt\n if all((h == n for h in hs)):\n res[0] = min(res[0], cnt)\n return\n min_h = min(hs)\n min_i = hs.index(min_h)\n r = m\n for i in range(min_i, m):\n if hs[i] > min_h:\n r = i\n break\n for side in range(min(r - min_i, n - min_h), 0, -1):\n dfs(cnt + 1, hs[:min_i] + [side + min_h] * side + hs[min_i + side:])\n dfs(0, [0] * m)\n return res[0]", "from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n (n, m) = (min(n, m), max(n, m))\n if m == n:\n return 1\n if m % n == 0:\n return m // n\n s1 = m * n\n for x in range(1, m // 2 + 1):\n s1 = min(s1, self.tilingrectangle(n, x) + self.tilingrectangle(n, m - x))\n for y in range(1, n // 2 + 1):\n s1 = min(s1, self.tilingrectangle(y, m) + self.tilingrectangle(n - y, m))\n s2 = m * n\n for xL in range(1, m // 2 + 1):\n for xR in range(1, m - xL):\n for yL in range(1, n // 2 + 1):\n for yR in range(1, n - yL):\n s2 = min(s2, self.tilingrectangle(n - yR, xL) + self.tilingrectangle(yL, m - xL) + self.tilingrectangle(n - yL, xR) + self.tilingrectangle(yR, m - xR) + self.tilingrectangle(n - yL - yR, m - xL - xR))\n return min(s1, s2)", "def tilingrectangle(n: int, m: int) -> int:\n if m > n:\n (n, m) = (m, n)\n (res, state) = (m * n, [0] * n)\n\n def dfs(count):\n nonlocal res\n if count > res:\n return\n min_h = min(state)\n if min_h == m:\n res = min(res, count)\n return\n e = s = state.index(min_h)\n while e < n and state[e] == min_h:\n e += 1\n max_len = min(e - s, m - min_h)\n for l in range(max_len, 0, -1):\n for i in range(s, s + l):\n state[i] += l\n dfs(count + 1)\n for i in range(s, s + l):\n state[i] -= l\n dfs(0)\n return res", "def tilingrectangle(R, C):\n A = [[0] * C for _ in range(R)]\n self.ans = R * C\n\n def search(r, c, steps):\n if steps >= self.ans:\n return\n if r == R:\n self.ans = steps\n return\n if c == C:\n return search(r + 1, 0, steps)\n if A[r][c]:\n return search(r, c + 1, steps)\n for k in range(min(R - r, C - c), 0, -1):\n bad = False\n for r0 in range(r, r + k):\n for c0 in range(c, c + k):\n if A[r0][c0]:\n bad = True\n break\n if bad:\n break\n if not bad:\n for r0 in range(r, r + k):\n for c0 in range(c, c + k):\n A[r0][c0] = 1\n search(r, c + 1, steps + 1)\n for r0 in range(r, r + k):\n for c0 in range(c, c + k):\n A[r0][c0] = 0\n search(0, 0, 0)\n return self.ans", "def tilingrectangle(n: int, m: int) -> int:\n self.res = math.inf\n grid = [[False] * n for _ in range(m)]\n\n def dfs(i, j, s):\n if s >= self.res:\n return\n elif i == m:\n self.res = s\n elif j == n:\n dfs(i + 1, 0, s)\n elif grid[i][j]:\n dfs(i, j + 1, s)\n else:\n side = min(m - i, n - j)\n while side:\n if not any((grid[ni][nj] for ni in range(i, i + side) for nj in range(j, j + side))):\n for ni in range(i, i + side):\n for nj in range(j, j + side):\n grid[ni][nj] = True\n dfs(i, j + side, s + 1)\n for ni in range(i, i + side):\n for nj in range(j, j + side):\n grid[ni][nj] = False\n side -= 1\n dfs(0, 0, 0)\n return self.res", "from math import inf\n\ndef tilingrectangle(n: int, m: int) -> int:\n rec = [[False] * n for _ in range(m)]\n res = inf\n\n def is_avail(r, c, k):\n return all((not rec[i][j] for i in range(r, r + k) for j in range(c, c + k)))\n\n def update(r, c, k, val):\n for i in range(r, r + k):\n for j in range(c, c + k):\n rec[i][j] = val\n\n def dfs(r, c, cnt):\n nonlocal res\n if r == m:\n res = min(res, cnt)\n return\n if c == n:\n dfs(r + 1, 0, cnt)\n return\n if rec[r][c]:\n dfs(r, c + 1, cnt)\n return\n if cnt >= res:\n return\n max_tile = min(m - r, n - c)\n for k in range(max_tile, 0, -1):\n if is_avail(r, c, k):\n update(r, c, k, True)\n dfs(r, c + k, cnt + 1)\n update(r, c, k, False)\n dfs(0, 0, 0)\n return res", "def tilingrectangle(n: int, m: int) -> int:\n dp = {}\n if n < m:\n (m, n) = (n, m)\n if m == n:\n return 1\n res = [m * n + 1]\n\n def dfs(ys, cnt):\n key = tuple(ys)\n if key not in dp or cnt < dp[key]:\n dp[key] = cnt\n if dp[key] < cnt or cnt > res[0]:\n return\n if all((i == m for i in ys)):\n res[0] = min(res[0], cnt)\n return\n if any((i > m for i in ys)):\n return\n ymin = min(ys)\n idx = ys.index(ymin)\n ymax = 0\n for i in range(idx, n):\n if ys[i] > ymin:\n break\n else:\n ymax += 1\n ymax = min(ymax, m)\n for i in range(ymax, 0, -1):\n dfs(ys[:idx] + [ys[idx] + i] * i + ys[idx + i:], cnt + 1)\n dfs([0] * n, 0)\n return res[0]", "from functools import lru_cache\nimport numpy as np\n\ndef __init__():\n self.cache = {}\n self.res = np.inf\n\ndef tilingrectangle(n: int, m: int) -> int:\n\n def tilingrectangleCalc(state, cnt):\n if cnt > self.res:\n return\n state = list(state)\n minHeight = min(state)\n if minHeight == n:\n self.res = min(self.res, cnt)\n return\n minIdx = state.index(minHeight)\n maxL = 1\n while minIdx + maxL - 1 <= m - 1 and state[minIdx + maxL - 1] == minHeight:\n maxL += 1\n for l in range(maxL - 1, 0, -1):\n if minHeight + l > n:\n continue\n s = tuple(state[:minIdx] + [minHeight + l] * l + state[minIdx + l:])\n if s in self.cache and self.cache[s] < cnt + 1:\n continue\n self.cache[s] = cnt + 1\n tilingrectangleCalc(s, cnt + 1)\n return\n if m > n:\n (n, m) = (m, n)\n tilingrectangleCalc(tuple([0] * m), 0)\n return self.res", "def tilingrectangle(m: int, n: int) -> int:\n cur = [0] * (n * m)\n q = [cur]\n step = 0\n seen = {tuple(cur)}\n while q and step < n * m + 1:\n step += 1\n nex = []\n for cur in q:\n found = True\n for i in range(m):\n for j in range(n):\n if cur[i * n + j] == 0:\n start = [i, j]\n found = False\n break\n if not found:\n break\n if found:\n return step - 1\n while j + 1 < n and cur[i * n + j + 1] == 0:\n j += 1\n k = j - start[1] + 1\n for sz in range(1, k + 1):\n cc = cur.copy()\n flag = False\n for i in range(start[0], start[0] + sz):\n for j in range(start[1], start[1] + sz):\n if not (0 <= i < m and 0 <= j < n and (cur[i * n + j] == 0)):\n flag = True\n break\n cc[i * n + j] = 1\n if flag:\n break\n if flag:\n break\n C = tuple(cc)\n if C not in seen:\n seen.add(C)\n nex.append(cc)\n q = nex", "def tilingrectangle(n: int, m: int) -> int:\n self.n = n\n self.m = m\n board = [[0] * n for _ in range(m)]\n self.res = float('inf')\n self.dfs(board, 0)\n return self.res\n\ndef dfs(board, count):\n if count >= self.res:\n return\n (i, j) = self.find_next(board)\n if i == -1 and j == -1:\n self.res = min(self.res, count)\n return\n max_length = self.find_max_length(board, i, j)\n for k in range(1, max_length + 1)[::-1]:\n self.assign(board, i, j, k, 1)\n self.dfs(board, count + 1)\n self.assign(board, i, j, k, 0)\n\ndef assign(board, i, j, length, val):\n for row in range(i, i + length):\n for col in range(j, j + length):\n board[row][col] = val\n\ndef find_max_length(board, i, j):\n max_length = 1\n while i + max_length - 1 < self.m and j + max_length - 1 < self.n:\n for row in range(i, i + max_length):\n if board[row][j + max_length - 1] != 0:\n return max_length - 1\n for col in range(j, j + max_length):\n if board[i + max_length - 1][col] != 0:\n return max_length - 1\n max_length += 1\n return max_length - 1\n\ndef find_next(board):\n for i in range(self.m):\n for j in range(self.n):\n if board[i][j] == 0:\n return (i, j)\n return (-1, -1)", "import math\n\ndef tilingrectangle(n: int, m: int) -> int:\n grid = [[0 for _ in range(m)] for _ in range(n)]\n\n def try_place(i: int, j: int, l: int) -> bool:\n ok = True\n (xb, yb) = (None, None)\n for x in range(i, i + l):\n for y in range(j, j + l):\n if grid[x][y] == 1:\n ok = False\n (xb, yb) = (x, y)\n break\n grid[x][y] = 1\n if not ok:\n break\n if not ok:\n done = False\n for x in range(i, i + l):\n for y in range(j, j + l):\n if (x, y) == (xb, yb):\n done = True\n break\n grid[x][y] = 0\n if done:\n break\n return ok\n\n def un_place(i: int, j: int, l: int):\n for x in range(i, i + l):\n for y in range(j, j + l):\n grid[x][y] = 0\n\n def search(i: int, j: int, sofar: int, ans: list):\n if sofar >= ans[0]:\n return\n if j == m:\n ans[0] = min(ans[0], sofar)\n return\n if i == n:\n search(0, j + 1, sofar, ans)\n return\n if grid[i][j] == 1:\n search(i + 1, j, sofar, ans)\n return\n for l in reversed(range(1, min(n - i + 1, m - j + 1))):\n if try_place(i, j, l):\n search(i + 1, j, sofar + 1, ans)\n un_place(i, j, l)\n if len(grid) == len(grid[0]):\n return 1\n ans = [math.inf]\n search(0, 0, 0, ans)\n return ans[0]", "def tilingrectangle(n: int, m: int) -> int:\n self.best = m * n\n height = [0] * m\n\n def dfs(moves):\n if all((h == n for h in height)):\n self.best = min(self.best, moves)\n return\n if moves >= self.best:\n return\n idx = height.index(min(height))\n for i in range(min(m - idx, n - height[idx]), 0, -1):\n for j in range(i):\n height[idx + j] += i\n dfs(moves + 1)\n for j in range(i):\n height[idx + j] -= i\n dfs(0)\n return self.best", "def tilingrectangle(n: int, m: int) -> int:\n self.ans = n * m\n\n def helper(heights, moves):\n if all((height == n for height in heights)):\n self.ans = min(self.ans, moves)\n return None\n if moves >= self.ans:\n return None\n min_height = min(heights)\n min_height_idx = heights.index(min_height)\n right_idx = min_height_idx + 1\n while right_idx < m and heights[right_idx] == min_height:\n right_idx += 1\n for idx in range(min(n - min_height, right_idx - min_height_idx), -1, -1):\n new_heights = heights[:]\n for next_idx in range(idx):\n new_heights[min_height_idx + next_idx] += idx\n helper(new_heights, moves + 1)\n helper([0] * m, 0)\n return self.ans", "def tilingrectangle(n: int, m: int) -> int:\n if n == m:\n return 1\n if m > n:\n (m, n) = (n, m)\n\n def helper(skyline):\n if all((h == n for h in skyline)):\n return 0\n ans = float('inf')\n minh = min(skyline)\n l = skyline.index(minh)\n for r in range(l, m):\n if skyline[r] != minh:\n break\n if r - l + 1 > n - minh:\n break\n newsl = list(skyline)\n for i in range(l, r + 1):\n newsl[i] += r - l + 1\n ans = min(ans, helper(tuple(newsl)))\n return ans + 1\n ans = helper(tuple([0] * m))\n return ans", "def findSum(n, m, k):\n res = []\n s = m * n\n hi = min(n, m)\n border = max(n, m)\n path = [1] * k\n while path[0] <= hi:\n i = k - 1\n while i >= 0 and path[i] >= hi:\n i -= 1\n if i == -1 or path[i] >= hi:\n return res\n path[i] += 1\n path[i + 1:] = [path[i]] * (k - i - 1)\n if path[k - 1] + path[k - 2] > border:\n path[i:] = [hi] * (k - i)\n continue\n if sum((x * x for x in path)) == s:\n x = path[:]\n x.reverse()\n res.append(x)\n return res\n\ndef hasNoOverLap(x1, y1, s1, x2, y2, s2):\n if x1 + s1 - 1 < x2 or y1 + s1 - 1 < y2 or x2 + s2 - 1 < x1 or (y2 + s2 - 1 < y1):\n return True\n else:\n return False\n\ndef nextPos(placement, n, m, size):\n if not placement:\n return (0, 0)\n for i in range(n - size + 1):\n for j in range(m - size + 1):\n if all((self.hasNoOverLap(i, j, size, x, y, z) for (x, y, z) in placement)):\n return (i, j)\n return (-1, -1)\n\ndef canPlace(sizes, n, m, placement, memo):\n if len(sizes) == 0:\n return True\n h = tuple(placement)\n if h in memo:\n return memo[h]\n for (k, s) in enumerate(sizes):\n (i, j) = self.nextPos(placement, n, m, s)\n if i == -1:\n continue\n placement.append((i, j, s))\n if self.canPlace(sizes[:k] + sizes[k + 1:], n, m, placement, memo):\n memo[h] = True\n return True\n placement.pop()\n memo[h] = False\n return False\n\ndef tilingrectangle(n: int, m: int) -> int:\n if n % m == 0:\n return n // m\n if m % n == 0:\n return m // n\n for i in range(3, 10):\n res = self.findSum(n, m, i)\n if any((self.canPlace(sizes, n, m, [], {}) for sizes in res)):\n return i", "from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n\n def dfs(x, y):\n if x == y:\n return 1\n if x == 1:\n return y\n if y == 1:\n return x\n result = x * y\n for i in range(1, x // 2 + 1):\n left = dfs(i, y)\n right = dfs(x - i, y)\n result = min(result, left + right)\n for k in range(1, y // 2 + 1):\n bottom = dfs(x, k)\n top = dfs(x, y - k)\n result = min(result, bottom + top)\n for size in range(1, min(x, y)):\n for i in range(1, x - size):\n for k in range(1, y - size):\n partition1 = dfs(i + size, k)\n partition2 = dfs(x - size - i, k + size)\n partition3 = dfs(x - i, y - size - k)\n partition4 = dfs(i, y - k)\n partition5 = 1\n curr_result = partition1 + partition2 + partition3 + partition4 + partition5\n result = min(result, curr_result)\n return result\n return dfs(n, m)", "def tilingrectangle(n: int, m: int) -> int:\n\n def dp(state):\n if state in cache:\n return cache[state]\n if state[::-1] in cache:\n return cache[state[::-1]]\n tmp = state\n if min(state) == n:\n return 0\n state = list(state)\n min_s = min(state)\n start = state.index(min_s)\n res = n\n for end in range(start, m):\n if state[end] != min_s:\n break\n side = end - start + 1\n if min_s + side > n:\n break\n state[start:end + 1] = [min_s + side] * side\n res = min(res, dp(tuple(state)))\n cache[tmp] = res + 1\n return res + 1\n if m > n:\n (m, n) = (n, m)\n cache = dict()\n return dp(tuple([0] * m))", "from functools import lru_cache\n\ndef tilingrectangle(n: int, m: int) -> int:\n INF = m * n\n cache = {}\n\n def dp(state):\n if state in cache:\n return cache[state]\n if state[::-1] in cache:\n return cache[state[::-1]]\n temp = state\n if n == min(state):\n return 0\n state = list(state)\n mn = min(state)\n start = state.index(mn)\n res = INF\n for end in range(start, m):\n if state[end] != mn:\n break\n side = end - start + 1\n if mn + side > n:\n break\n state[start:end + 1] = [mn + side] * side\n res = min(res, dp(tuple(state)))\n cache[temp] = res + 1\n return res + 1\n if m > n:\n (m, n) = (n, m)\n if (m, n) == (11, 13):\n return 6\n return dp(tuple([0] * m))", "def tilingrectangle(n: int, m: int) -> int:\n self.best = n * m\n\n def dp(heights, n_square):\n if n_square > self.best:\n return\n if heights == [n] * m:\n self.best = min(self.best, n_square)\n min_index = min(range(m), key=lambda x: heights[x])\n (i, j) = (min_index, min_index)\n while j < m and heights[i] == heights[j]:\n j += 1\n max_line = min(j - i + int(j == m), n - heights[i])\n result = float('inf')\n for x in range(max_line, 0, -1):\n cur = dp(heights[:i] + [heights[i] + x] * x + heights[i + x:], n_square + 1)\n if cur:\n result = min(result, cur)\n return result\n dp([0] * m, 0)\n return self.best"], "starter_code": "def tilingrectangle(n: int, m: int) -> int:\n", "input_output": {"fn_name": "tilingRectangle", "inputs": [[2, 3]], "outputs": [3]}, "difficulty": "MEDIUM", "raw_tags": ["Backtracking", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Complete search"], "skill_types": ["Dynamic programming", "Complete search"], "url": "https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "tilingrectangle", "task_id": "TACO_lite/87", "example": [[[2, 3], [5, 8], [11, 13]], ["3", "5", "6"]]} +{"requirement": "Consider a sample space S consisting of all perfect squares starting from 1, 4, 9 and so on. You are given a number N, you have to output the number of integers less than N in the sample space S.\n \nExample 1:\nInput :\nN = 9\nOutput:\n2\nExplanation:\n1 and 4 are the only Perfect Squares\nless than 9. So, the Output is 2.\nExample 2:\nInput :\nN = 3\nOutput:\n1\nExplanation:\n1 is the only Perfect Square\nless than 3. So, the Output is 1.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function countSquares() which takes an Integer N as input and returns the answer.\n \nExpected Time Complexity: O(sqrt(N))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= N <= 10^{8}", "solutions": ["import math\n\ndef countsquares(N):\n s = math.sqrt(N)\n if N == 0 or N == 1:\n return 0\n elif N < 0:\n return 0\n elif N == int(s) ** 2 and N % int(s) == 0:\n return int(s) - 1\n else:\n return int(s) + 1 - 1", "import math\n\ndef countsquares(N):\n count = int(math.sqrt(N - 1))\n return count", "def countsquares(N):\n return int((N - 1) ** 0.5)", "def countsquares(N):\n if N == int(N ** 0.5) ** 2:\n return int(N ** 0.5) - 1\n return int(N ** 0.5)", "def countsquares(N):\n return int(math.sqrt(N - 1))", "def countsquares(N):\n a = math.sqrt(N - 1)\n b = int(a)\n return b", "def countsquares(n):\n return int(math.sqrt(n - 1))", "import math\n\ndef countsquares(N):\n r = math.sqrt(N)\n if r.is_integer():\n return int(r - 1)\n else:\n return int(r)", "import math\n\ndef countsquares(N):\n m = 0\n m = math.sqrt(N)\n N = int(math.sqrt(N))\n if m - N == 0:\n return N - 1\n else:\n return N", "import math\n\ndef countsquares(N):\n if N == int(math.sqrt(N)) ** 2:\n return int(N ** 0.5) - 1\n return int(N ** 0.5)", "import math\n\ndef countsquares(N):\n return math.floor(math.sqrt(N - 1))", "def countsquares(N):\n (l, r) = (1, N)\n res = 1\n while l <= r:\n mid = (l + r) // 2\n if mid * mid == N:\n return mid - 1\n elif mid * mid <= N:\n res = mid\n l = mid + 1\n else:\n r = mid - 1\n return res", "import math\n\ndef countsquares(n):\n return math.floor(math.sqrt(n - 1))", "import math\n\ndef countsquares(N):\n count = 0\n count = math.floor(math.sqrt(N))\n if count * count == N:\n return count - 1\n else:\n return count", "def countsquares(N):\n import math\n if int(N) == int(math.sqrt(N)) ** 2:\n return len(range(1, round(math.sqrt(N))))\n return int(math.sqrt(N))", "def countsquares(N):\n a = N ** 0.5\n b = math.ceil(a)\n return b - 1", "def countsquares(N):\n c = 0\n d = int(N ** (1 / 2))\n if d * d == N:\n return d - 1\n return d", "import math\n\ndef countsquares(N):\n n = N ** 0.5\n if n - int(n) == 0:\n return int(n - 1)\n else:\n return int(n)", "def countsquares(N):\n k = int(math.sqrt(N))\n if k * k == N:\n return k - 1\n else:\n return int(k)", "def countsquares(N):\n (start, end) = (0, N - 1)\n root = -1\n while start <= end:\n mid = start + (end - start) // 2\n if mid ** 1 * mid < N ** 1:\n root = mid\n start = mid + 1\n else:\n end = mid - 1\n return root", "import math\n\ndef countsquares(N):\n return int((N - 1) ** 0.5)", "import math\n\ndef countsquares(N):\n res = math.ceil(math.sqrt(N))\n return res - 1", "from math import sqrt, ceil\n\ndef countsquares(N):\n ans = ceil(sqrt(N))\n return ans - 1", "def countsquares(N):\n return int(math.sqrt(N - 1))\n count = 0\n for i in range(1, int(math.sqrt(N) + 1)):\n if i * i < N:\n count += 1\n return count", "def countsquares(N):\n n = N ** (1 / 2)\n if n > int(n):\n return int(n)\n else:\n return int(n) - 1", "def countsquares(N):\n n = N ** 0.5\n return math.ceil(n) - 1", "def countsquares(N):\n return int((N - 1) ** (1 / 2))", "def countsquares(N):\n N = N - 1\n r = N ** (1 / 2)\n k = int(r)\n if N == 0:\n return 0\n else:\n return k", "import math\n\ndef countsquares(n):\n square_root = int(math.sqrt(n))\n if square_root * square_root == n:\n return square_root - 1\n return square_root", "def countsquares(N):\n import math\n ans = math.sqrt(N)\n ans1 = int(ans)\n if ans - ans1 == 0:\n return ans1 - 1\n else:\n return ans1", "def countsquares(N):\n return math.ceil(math.sqrt(N)) - 1", "def countsquares(N):\n if N == 1:\n return 0\n l = 0\n h = N // 2\n while l <= h:\n m = (l + h) // 2\n if m * m > N:\n h = m - 1\n elif m * m == N:\n return m - 1\n elif (m + 1) * (m + 1) > N:\n return m\n else:\n l = m + 1", "def countsquares(N):\n val = N ** 0.5\n if val == int(val):\n return int(val) - 1\n else:\n return int(val)", "def countsquares(n):\n return math.ceil(math.sqrt(n)) - 1"], "starter_code": "def countsquares(N):\n", "input_output": {"inputs": ["N = 9", "N = 3"], "outputs": ["2", "1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/count-squares3649/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(sqrt(N))", "entry_point": "countsquares", "task_id": "TACO_lite/250", "example": [[[9], [3]], ["2", "1"]]} +{"requirement": "## Task\nYou need to implement two functions, `xor` and `or`, that replicate the behaviour of their respective operators:\n\n- `xor` = Takes 2 values and returns `true` if, and only if, one of them is truthy.\n- `or` = Takes 2 values and returns `true` if either one of them is truthy.\n\nWhen doing so, **you cannot use the or operator: `||`**.\n\n# Input\n- Not all input will be booleans - there will be truthy and falsey values [the latter including also empty strings and empty arrays]\n- There will always be 2 values provided\n\n## Examples\n- `xor(true, true)` should return `false`\n- `xor(false, true)` should return `true`\n- `or(true, false)` should return `true`\n- `or(false, false)` should return `false`", "solutions": ["def func_or(a, b):\n return not bool(a) == bool(b) == False\n\ndef func_xor(a, b):\n return not bool(a) == bool(b)", "def func_or(a, b):\n return bool(a) | bool(b)\n\ndef func_xor(a, b):\n return bool(a) ^ bool(b)", "def func_or(a, b):\n return bool(a) + bool(b) > 0\n\ndef func_xor(a, b):\n return bool(a) + bool(b) == 1", "def func_or(*a):\n return any(a)\n\ndef func_xor(*a):\n return any(a) and (not all(a))", "def func_or(a, b):\n return bool(a if a else b)\n\ndef func_xor(a, b):\n return bool(not b if a else b)", "def func_or(a, b):\n return False if not a and (not b) else True\n\ndef func_xor(a, b):\n return True if not a and b or (a and (not b)) else False", "def func_or(a, b):\n return bool(a) or bool(b)\n\ndef func_xor(a, b):\n return bool(a) is not bool(b)", "(func_or, func_xor) = (lambda a, b: bool(bool(a) + bool(b)), lambda a, b: bool(a) + bool(b) == 1)", "def func_or(a, b):\n if a:\n return True\n else:\n return not not b\n\ndef func_xor(a, b):\n if a:\n return not b\n else:\n return not not b"], "starter_code": "def func_or(a,b):\n", "input_output": {"fn_name": "func_or", "inputs": [[true, true], [true, false], [false, false], [0, 11], [null, []]], "outputs": [[true], [true], [false], [true], [false]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Logic"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/584d2c19766c2b2f6a00004f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "func_or", "task_id": "TACO_lite/198", "example": [[], []]} +{"requirement": "Given a number n, count the total number of digits required to write all numbers from 1 to n.\nExample 1:\nInput: n = 13\nOutput: 17 \nExplanation: There are total 17 \ndigits required to write all \nnumbers from 1 to 13.\nExample 2:\nInput: n = 4\nOutput: 4\nExplanation: There are total 4 \ndigits required to write all\nnumbers from 1 to 4.\nYour Task: \nYou dont need to read input or print anything. Complete the function totalDigits() which takes n as input parameter and returns the total number of digits required to write all numbers from 1 to n.\nExpected Time Complexity: O(logn)\nExpected Auxiliary Space: O(1)\nConstraints:\n1<= n <=100000", "solutions": ["def totaldigits(ob, n):\n if n < 10:\n return n\n else:\n number = 9\n for i in range(10, n + 1):\n i = str(i)\n number += len(i)\n return number", "def totaldigits(ob, n):\n st = ''\n for i in range(1, n + 1):\n st = st + str(i)\n return len(st)", "def totaldigits(ob, n):\n sm = 0\n for i in range(1, n + 1):\n sm += len(str(i))\n return sm", "def totaldigits(ob, n):\n import math\n r = 0\n for i in range(1, n + 1):\n r += int(math.log10(i)) + 1\n return r", "def totaldigits(ob, n):\n c = 0\n for i in range(1, n + 1):\n if i < 10:\n c = c + 1\n else:\n s = str(i)\n c = c + len(s)\n return c", "def totaldigits(ob, n):\n init = n\n ans = sub = 0\n while init - sub > 0:\n ans += init - sub\n sub = sub * 10 + 9\n return ans", "def totaldigits(ob, n):\n\n def cd(i):\n i = str(i)\n return len(i)\n ans = 0\n for i in range(1, n + 1):\n ans += cd(i)\n return ans", "def totaldigits(ob, n):\n c = 0\n i = 1\n while i <= n:\n c += n - i + 1\n i *= 10\n return c", "def totaldigits(ob, n):\n c = 0\n for i in range(1, n + 1):\n j = str(i)\n c += len(j)\n return c", "def totaldigits(ob, n):\n d = 0\n t = n\n while t > 0:\n d += 1\n t = t // 10\n x = 0\n while n > 0:\n x += d * (n + 1 - 10 ** (d - 1))\n n = 10 ** (d - 1) - 1\n d -= 1\n return x", "def lt(n):\n return len(str(n))\n\ndef ans(n, x):\n if n <= 9:\n x += n\n return x\n z = lt(n)\n if n - 1000 > 100 and z == lt(n - 1000):\n x += z * 1000\n return ans(n - 1000, x)\n elif n - 10 > 10 and z == lt(n - 10):\n x += z * 10\n return ans(n - 10, x)\n else:\n x += z\n return ans(n - 1, x)\n\ndef totaldigits(ob, n):\n return ans(n, 0)", "def ins(n):\n j = len(str(n))\n return j\n\ndef totaldigits(ob, n):\n s = 0\n for i in range(1, n + 1):\n s = s + ins(i)\n return s", "def totaldigits(ob, n):\n a = [1] * n\n for i in range(1, n):\n a[i] += i\n str1 = ''.join(map(str, a))\n return len(str1)", "import math\n\ndef totaldigits(ob, n):\n digits = 0\n for i in range(1, n + 1):\n digits += len(str(i))\n return digits", "def totaldigits(ob, n):\n m = n\n c = 0\n while n != 0:\n n //= 10\n c = c + 1\n if c == 1:\n return m\n elif c == 2:\n return 9 + 2 * (m - 9)\n elif c == 3:\n return 9 + 2 * 90 + 3 * (m - 99)\n elif c == 4:\n return 9 + 2 * 90 + 3 * 900 + 4 * (m - 999)\n elif c == 5:\n return 9 + 2 * 90 + 3 * 900 + 4 * 9000 + 5 * (m - 9999)\n elif c == 6:\n return 9 + 2 * 90 + 3 * 900 + 4 * 9000 + 5 * 90000 + 6 * (m - 99999)", "def totaldigits(ob, n):\n count = 0\n i = 9\n if n <= 9:\n return n\n else:\n count = n\n while n > i:\n count += n - i\n i = i * 10 + 9\n return count", "def totaldigits(ob, n):\n l = len(str(n))\n ans = 0\n decrease = 0\n while l:\n ans += n - decrease\n decrease = decrease * 10 + 9\n l -= 1\n return ans", "def totaldigits(ob, n):\n s = ''\n sum = 0\n for i in range(1, n + 1):\n s = str(i)\n sum = sum + len(s)\n return sum"], "starter_code": "def totaldigits (ob, n):\n", "input_output": {"inputs": ["n = 13", "n = 4"], "outputs": ["17", "4"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/total-digits4030/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(logn)", "entry_point": "totaldigits", "task_id": "TACO_lite/241", "example": [[[13], [4]], [null, null]]} +{"requirement": "Given a range L to R, the task is to find the highest occurring digit in prime numbers which lie between L and R (both inclusive). If multiple digits have same highest frequency return the largest of them. If no prime number occurs between L and R, return -1.\n \nExample 1:\nInput: L = 2, R = 10\nOutput: 7\nExplanation: Between 2 and 10 every digit\nhas same frquency and 7 is largest among\nthem.\nExample 2:\nInput: L = 2, R = 20\nOutput: 1\nExplanation: Prime number between 2 and 20 are \n2, 3, 5, 7, 11, 13, 17, 19. 1 occur \nmaximum i.e 5 times among 0 to 9.\nYour Task: \nYou dont need to read input or print anything. Complete the function maxDigit() which takes L and R as input parameter and returns the highest occuring digit. If multiple digits have same highest frequency return the largest of them. If no prime number occurs between L and R, return -1.\nExpected Time Complexity: O(nlog(n)sqrt(n))\nExpected Auxiliary Space: O(k)\nConstraints:\n1 <= L<= R <= 1000", "solutions": ["def isprime(n):\n if n == 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef maxdigit(L, R):\n l = []\n for i in range(L, R + 1, 1):\n if self.isprime(i):\n c = i\n while c != 0:\n l.append(c % 10)\n c = c // 10\n l = sorted(l)\n a = 0\n b = 0\n for i in range(len(l) - 1, -1, -1):\n if l.count(l[i]) > a:\n a = l.count(l[i])\n b = l[i]\n if b == 0:\n return -1\n else:\n return b", "import math\n\ndef __init__():\n self.pl = self.primes()\n\ndef primes():\n n = int(1000.0)\n pl = [True] * (n + 1)\n pl[0] = pl[1] = False\n lim = int(math.sqrt(n)) + 1\n for i in range(2, lim):\n for j in range(i * i, n + 1, i):\n if pl[i]:\n pl[j] = False\n res = [i for i in range(2, n + 1) if pl[i]]\n return res\n\ndef bsf(arr, k):\n (l, h, idx) = (0, len(arr) - 1, -1)\n while l <= h:\n m = (l + h) // 2\n if arr[m] > k:\n h = m - 1\n else:\n idx = m\n l = m + 1\n return idx\n\ndef bsc(arr, k):\n (l, h, idx) = (0, len(arr) - 1, -1)\n while l <= h:\n m = (l + h) // 2\n if arr[m] < k:\n l = m + 1\n else:\n idx = m\n h = m - 1\n return idx\n\ndef maxdigit(L, R):\n x = self.bsc(self.pl, L)\n y = self.bsf(self.pl, R)\n d = {}\n for i in self.pl[x:y + 1]:\n while i != 0:\n if i % 10 in d:\n d[i % 10] += 1\n else:\n d[i % 10] = 1\n i = i // 10\n (me, m) = (-1, 0)\n for i in d:\n if d[i] >= m:\n (m, me) = (d[i], i)\n return me", "def maxdigit(M, N):\n product = 1\n mod = 10 ** 9 + 7\n table = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}\n for j in range(M, N + 1):\n flag = True\n if j == 1:\n continue\n for i in range(2, int(j ** 0.5) + 1):\n if j % i == 0:\n flag = False\n break\n if flag:\n while j != 0:\n p = j % 10\n table[p] += 1\n j = j // 10\n digit = -1\n maxi = 1\n for j in table:\n if table[j] >= maxi:\n maxi = table[j]\n digit = j\n return digit", "def maxdigit(L, R):\n from collections import Counter\n n = R\n sieve = [True] * (n + 1)\n rec = Counter()\n for i in range(2, n + 1):\n if sieve[i]:\n for j in range(i * i, n + 1, i):\n sieve[j] = False\n if i >= L:\n for x in str(i):\n rec[x] += 1\n if not rec:\n return -1\n maxi = max(rec.values())\n if maxi == 0:\n return -1\n ans = '0'\n for (k, v) in rec.items():\n if v == maxi:\n ans = max(ans, k)\n return ord(ans) - ord('0')", "import math\n\ndef maxdigit(L, R):\n sieve = [0 for i in range(100000)]\n (sieve[0], sieve[1]) = (1, 1)\n for i in range(2, int(math.sqrt(100000)) + 1):\n if sieve[i] == 0:\n for j in range(i * i, 100000, i):\n sieve[j] = 1\n d = {i: 0 for i in range(10)}\n for i in range(L, R + 1):\n if sieve[i] == 0:\n data = i\n while data != 0:\n d[data % 10] += 1\n data //= 10\n (maxkey, maxval) = (float('-inf'), float('-inf'))\n for (key, val) in d.items():\n if val >= maxval:\n maxkey = key\n maxval = val\n if maxval == 0:\n return -1\n return maxkey", "from math import sqrt\n\ndef maxdigit(L, R):\n res = [0] * 10\n for i in range(L, R + 1):\n if self.findprimes(i):\n num = i\n while num != 0:\n rem = num % 10\n res[rem] += 1\n num = num // 10\n maxcount = 0\n maxi = -1\n for j in range(9, -1, -1):\n if maxcount < res[j]:\n maxcount = res[j]\n maxi = j\n return maxi\n\ndef findprimes(N):\n if N <= 1:\n return 0\n for i in range(2, int(sqrt(N)) + 1):\n if N % i == 0:\n return 0\n return 1", "import math\n\ndef seive(n):\n primes = [True] * n\n primes[0] = primes[1] = False\n for i in range(4, n, 2):\n primes[i] = False\n x = int(math.sqrt(n)) + 1\n for i in range(3, x):\n for j in range(i * i, n, i):\n primes[j] = False\n ans = []\n for i in range(len(primes)):\n if primes[i]:\n ans.append(i)\n return ans\n\ndef maxdigit(l, r):\n n = int(math.sqrt(r)) + 1\n primes = self.seive(n)\n arr = [True] * (r - l + 1)\n if l == 1:\n arr[0] = False\n for p in primes:\n base = l // p * p\n if base < l:\n base += p\n for i in range(base, r + 1, p):\n if i != p:\n arr[i - l] = False\n mp = {}\n mx = -999999\n val = -1\n for i in range(r - l + 1):\n if arr[i]:\n num = i + l\n while num > 0:\n k = num % 10\n if k in mp:\n mp[k] += 1\n else:\n mp[k] = 1\n if mp[k] >= mx:\n mx = mp[k]\n val = k\n num = num // 10\n return val", "def maxdigit(L, R):\n if L == 1:\n L = 3\n x = []\n for i in range(L, R + 1):\n c = 0\n for j in range(2, int(i ** 0.5) + 1):\n if i % j == 0:\n c = 1\n break\n if c == 0:\n x.append(i)\n a = ''\n for i in x:\n a += str(i)\n d = {}\n for i in a:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n ans = 0\n count = 0\n for i in d:\n if d[i] == count:\n if i > ans:\n ans = i\n if d[i] > count:\n ans = i\n count = d[i]\n if ans == 0:\n return -1\n return ans", "def maxdigit(L, R):\n p = []\n q = []\n r = []\n m = 0\n c1 = 0\n c3 = 0\n c5 = 0\n c7 = 0\n c9 = 0\n if L == 1:\n L = 2\n for i in range(L, R + 1):\n for j in range(2, int(i / 2) + 1):\n if i % j == 0:\n break\n else:\n p.append(i)\n if len(p) == 0:\n return -1\n q = [str(x) for x in p]\n s = ''\n for i in q:\n s += i\n m = max(s.count('1'), s.count('2'), s.count('3'), s.count('4'), s.count('5'), s.count('6'), s.count('7'), s.count('8'), s.count('9'))\n if m == s.count('9'):\n return 9\n elif m == s.count('8'):\n return 8\n elif m == s.count('7'):\n return 7\n elif m == s.count('6'):\n return 6\n elif m == s.count('5'):\n return 5\n elif m == s.count('4'):\n return 4\n elif m == s.count('3'):\n return 3\n elif m == s.count('2'):\n return 2\n elif m == s.count('1'):\n return 1", "def primeCheck(n):\n check = True\n for i in range(2, n):\n if n % i == 0:\n check = False\n break\n return check\n\ndef primeListGetter(rangeValue1, rangeValue2):\n resultList = []\n for val in range(rangeValue1, rangeValue2 + 1):\n if self.primeCheck(val) and val != 1:\n resultList.append(val)\n return resultList\n\ndef maxdigit(L, R):\n primeList = self.primeListGetter(L, R)\n if len(primeList) == 0:\n return -1\n frequency = {}\n maxValueCheck = 0\n maxValueIndex = 0\n for val in primeList:\n charVal = str(val)\n for key in charVal:\n key = int(key)\n frequency[key] = frequency.get(key, 0) + 1\n values = list(frequency.values())\n keys = list(frequency.keys())\n if int(sum(values) / len(values)) == values[0]:\n return max(keys)\n else:\n maximumValue = max(values)\n maximumKey = keys[0]\n for i in keys:\n if frequency[i] == maximumValue:\n if maximumValue <= frequency[i]:\n maximumKey = i\n return maximumKey", "def isPrime(n):\n if n == 1:\n return False\n for i in range(2, n):\n if n % i == 0:\n return False\n return True\n\ndef maxdigit(L, R):\n digitCount = [0 for i in range(10)]\n for i in range(L, R + 1):\n if self.isPrime(i):\n digitCount[i % 10] += 1\n if i >= 10:\n digitCount[i % 100 // 10] += 1\n if i >= 100:\n digitCount[i // 100] += 1\n maxdigit = -1\n maxCount = 0\n for i in range(9, -1, -1):\n if digitCount[i] > maxCount:\n maxCount = digitCount[i]\n maxdigit = i\n return maxdigit", "from collections import Counter\n\ndef isprime(x):\n if x <= 1:\n return 0\n if x == 2:\n return 1\n else:\n for i in range(2, x):\n if x % i == 0:\n return 0\n return 1\n\ndef maxdigit(L, R):\n l = []\n for i in range(L, R + 1):\n if isprime(i):\n l.append(i)\n if l:\n l = [str(x) for x in l]\n res = ''\n res = ''.join(l)\n k = list(res)\n m = Counter(k)\n p = []\n for (keys, values) in m.items():\n p.append(values)\n d = max(p)\n res1 = []\n for (keys, values) in m.items():\n if d == values:\n res1.append(keys)\n if res1:\n return max(res1)\n else:\n return -1\n else:\n return -1", "from collections import defaultdict\nfrom math import ceil\n\ndef maxdigit(L, R):\n primes = []\n count = defaultdict(int)\n\n def prime(n):\n not_primes = set()\n for i in range(3, ceil(n / 2) + 1, 2):\n for j in range(3 * i, n, 2 * i):\n not_primes.add(j)\n return not_primes\n if L <= 2 <= R:\n primes.append(2)\n not_primes = prime(R + 1)\n not_primes.add(1)\n for i in range(L, R + 1):\n if i % 2 == 1 and i not in not_primes:\n primes.append(i)\n (ans, mmax) = ('', 0)\n for num in primes:\n for c in str(num):\n count[c] += 1\n if count[c] > mmax:\n (mmax, ans) = (count[c], c)\n elif count[c] == mmax:\n if c > ans:\n ans = c\n return int(ans) if ans != '' else -1", "import math\n\ndef maxdigit(L, R):\n l = 1001\n ans = [0] * l\n ans[1] = 0\n ans[0] = 1\n for i in range(2, int(math.sqrt(l)) + 1):\n if ans[i] == 0:\n for j in range(2 * i, l, i):\n ans[j] = 1\n let = [0] * 10\n for i in range(L, R + 1):\n if ans[i] == 0:\n t = i\n digit = 0\n while t != 0:\n digit = t % 10\n let[digit] += 1\n t //= 10\n m = let[0]\n ans = 0\n for j in range(1, 10):\n if m <= let[j]:\n m = let[j]\n ans = j\n if m == 0:\n return -1\n return ans", "def maxdigit(L, R):\n l = []\n max = 0\n for i in range(L, R + 1):\n if i >= 1:\n for j in range(2, i):\n if i % j == 0:\n break\n else:\n l.append(str(i))\n if len(l) == 0:\n return -1\n k = ''.join(l)\n for i in range(1, 10):\n if k.count(str(i)) >= max:\n max = k.count(str(i))\n a = i\n return a", "import math as m\n\ndef maxdigit(L, R):\n\n def IsPrime(n):\n if n == 1:\n return True\n for i in range(2, int(m.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n s = ''\n for i in range(L, R + 1):\n if IsPrime(i):\n s += str(i)\n if len(s) == 0:\n return -1\n s = list(s)\n l = list(set(s))\n l.sort(key=int)\n maxi = 0\n for i in l:\n sc = s.count(i)\n if sc >= maxi:\n maxi = sc\n st = i\n return st", "import math\n\ndef prime(n):\n if n == 0:\n return False\n if n == 2 or n == 3 or n == 1:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n for i in range(5, int(math.sqrt(n)) + 1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\ndef maxdigit(l, r):\n c = []\n nivas = []\n ni = 0\n for i in range(l, r + 1):\n if self.prime(i):\n ni += 1\n for j in str(i):\n c.append(j)\n nivas.append(int(j))\n if ni == len(nivas) and ni > 0:\n return max(nivas)\n if ni == 0:\n return '-1'\n d = {}\n for i in c:\n if i not in d.keys():\n d[i] = 1\n else:\n d[i] += 1\n a = max(d, key=d.get)\n if ni > 0:\n return a", "import math as m\n\ndef maxdigit(L, R):\n s = ''\n d = {}\n x = ''\n maxi = 0\n\n def pr(n):\n if n == 1:\n return True\n if n == 0:\n return False\n else:\n for i in range(2, int(m.sqrt(n) + 1)):\n if n % i == 0:\n return False\n return True\n for k in range(L, R + 1):\n if pr(k):\n s = s + str(k)\n if len(s) == 0:\n return -1\n for i in s:\n d[i] = d.get(i, 0) + 1\n for i in d:\n if d[i] > maxi:\n maxi = d[i]\n for i in d:\n if d[i] >= maxi:\n if i > x:\n x = i\n maxi = d[i]\n return x", "def maxdigit(L, R):\n n = 1001\n seive = []\n for _ in range(n + 1):\n seive.append(1)\n seive[0] = 0\n seive[1] = 1\n for i in range(2, n + 1):\n if seive[i] == 1:\n j = i * i\n while j <= n:\n seive[j] = 0\n j += i\n l = []\n for i in range(L, R + 1):\n if seive[i] == 1:\n l.append(i)\n d = dict()\n for word in l:\n s = str(word)\n s = list(s)\n for i in s:\n d[int(i)] = d.get(int(i), 0) + 1\n val = -1\n for (k, v) in sorted(d.items(), key=lambda item: item[1], reverse=True):\n val = v\n break\n res = []\n for (k, v) in sorted(d.items()):\n if v == val:\n res.append(k)\n if len(res) == 0:\n return -1\n return max(res)", "def maxdigit(L, R):\n\n def findPrime(L, R):\n primes = []\n for i in range(L, R + 1):\n for j in range(2, i // 2 + 1):\n if i % j == 0:\n break\n else:\n primes.append(i)\n return primes\n primes = findPrime(L, R)\n if not primes:\n return -1\n d = {}\n for p in primes:\n str_p = str(p)\n for digit in str_p:\n digit = int(digit)\n if digit in d:\n d[digit] += 1\n else:\n d[digit] = 1\n digits_freq = list(d.items())\n digits_freq.sort(key=lambda x: (x[1], x[0]), reverse=True)\n return digits_freq[0][0]", "def maxdigit(L, R):\n c = [True] * (R + 1)\n p = 2\n b = L // 2\n while p * p <= R:\n if c[p] == True:\n for i in range(p * b, R + 1, p):\n if i != p:\n c[i] = False\n p = p + 1\n b = L // p\n m = {}\n for i in range(L, len(c)):\n if c[i] == True:\n while i > 0:\n a = i % 10\n if a in m:\n m[a] = m[a] + 1\n else:\n m[a] = 1\n i = i // 10\n if len(m) == 0:\n return -1\n a = max(m.values())\n if a == 1:\n return max(m.keys())\n r = []\n for keys in m:\n if m[keys] == a:\n r.append(keys)\n return max(r)"], "starter_code": "def maxdigit(L, R):\n", "input_output": {"inputs": ["L = 2, R = 10", "L = 2, R = 20"], "outputs": ["7", "1"]}, "difficulty": "EASY", "raw_tags": ["Prime Number", "sieve"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/find-the-highest-occurring-digit-in-prime-numbers-in-a-range3634/1", "Expected Auxiliary Space": "O(k)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(nlog(n)sqrt(n))", "entry_point": "maxdigit", "task_id": "TACO_lite/139", "example": [[[2, 10], [2, 20]], ["7", "1"]]} +{"requirement": "Given any number of boolean flags function should return true if and only if one of them is true while others are false. If function is called without arguments it should return false.\n\n```python\n only_one() == False\n only_one(True, False, False) == True\n only_one(True, False, False, True) == False\n only_one(False, False, False, False) == False \n```", "solutions": ["def only_one(*args):\n return sum(args) == 1", "def only_one(*args):\n return args.count(True) == 1", "def only_one(*args):\n count = 0\n for item in args:\n if item:\n count += 1\n if count == 2:\n return False\n return True if count == 1 else False", "def only_one(*x):\n return x.count(True) == 1", "def only_one(*flags):\n return sum(flags) == 1", "from collections import Counter\n\ndef only_one(*booleans):\n return Counter(booleans)[True] == 1", "only_one = lambda *a: sum(a) == 1", "def only_one(*flags):\n return len([a for a in flags if a]) == 1", "def only_one(*bool):\n sum = 0\n for value in bool:\n if value:\n sum += 1\n if sum == 1:\n return True\n else:\n return False", "def only_one(*bools):\n return sum((x for x in bools)) == 1"], "starter_code": "def only_one(*args):\n", "input_output": {"fn_name": "only_one", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5734c38da41454b7f700106e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "only_one", "task_id": "TACO_lite/134", "example": [[[], [true, false, false], [true, false, false, true], [false, false, false, false]], ["False", "True", "False", "False"]]} +{"requirement": "Check if it is a vowel(a, e, i, o, u,) on the ```n``` position in a string (the first argument). Don't forget about uppercase.\n\nA few cases:\n\n```\n{\ncheckVowel('cat', 1) -> true // 'a' is a vowel\ncheckVowel('cat', 0) -> false // 'c' is not a vowel\ncheckVowel('cat', 4) -> false // this position doesn't exist\n}\n```\nP.S. If n < 0, return false", "solutions": ["def check_vowel(s, i):\n return 0 <= i < len(s) and s[i] in 'aieouAEIOU'", "def check_vowel(string, position):\n return 0 <= position < len(string) and string[position].lower() in 'aeiou'", "def check_vowel(string, position):\n if position < 0:\n return False\n try:\n return string[position].lower() in ['a', 'e', 'i', 'o', 'u']\n except IndexError:\n return False", "def check_vowel(s, pos):\n return 0 <= pos < len(s) and s.lower()[pos] in 'aeiou'", "def check_vowel(string, position):\n return 0 <= position <= len(string) and string[position] in 'aeiouAEIOU'", "def check_vowel(stg, position):\n return 0 <= position < len(stg) and stg[position].lower() in 'aeiou'", "def check_vowel(s, i):\n return s[i].lower() in 'aeiou' if len(s) > i > -1 else False", "def check_vowel(string, position):\n string = string + ' '\n vowles = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n if string[position] in vowles:\n return True\n else:\n return False", "def check_vowel(string, position):\n if position < 0 or position > len(string):\n return False\n return string[position].lower() in 'aeiou'", "def check_vowel(s, t):\n if t == 0 and s[t] in 'aioueAEIOU':\n return True\n return True if t > 0 and t < len(s) and (s[t] in 'aioueAEIOU') else False\n pass"], "starter_code": "def check_vowel(string, position):\n", "input_output": {"fn_name": "check_vowel", "inputs": [["cat", 1], ["cat", 0], ["cat", 4], ["Amanda", -2], ["Amanda", 0], ["Amanda", 2]], "outputs": [[true], [false], [false], [false], [true], [true]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5a2b7edcb6486a856e00005b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "check_vowel", "task_id": "TACO_lite/248", "example": [[], []]} +{"requirement": "Reverse a linked list from position m to n. Do it in one-pass.\n\nNote:\u00a01 \u2264 m \u2264 n \u2264 length of list.\n\nExample:\n\n\nInput: 1->2->3->4->5->NULL, m = 2, n = 4\nOutput: 1->4->3->2->5->NULL", "solutions": ["def reverseBetween(head, m, n):\n if head is None or head.__next__ is None or m == n:\n return head\n h = ListNode(-1)\n h.next = head\n fast = slow = h\n for _ in range(n - m + 1):\n fast = fast.__next__\n for _ in range(m - 1):\n fast = fast.__next__\n slow = slow.__next__\n prev = fast.__next__\n curr = slow.__next__\n while prev != fast:\n temp = curr.__next__\n curr.next = prev\n prev = curr\n curr = temp\n slow.next = prev\n return h.__next__", "def reverseBetween(head, m, n):\n pre = dummy = ListNode(0)\n dummy.next = head\n num = 0\n first = last = ListNode(0)\n while head:\n num += 1\n if num == m:\n preFirst = pre\n first = head\n if num == n:\n last = head\n laLast = last.__next__\n break\n head = head.__next__\n pre = pre.__next__\n while first != last:\n pre = first\n preFirst.next = pre.__next__\n pre.next = last.__next__\n last.next = pre\n first = preFirst.__next__\n return dummy.__next__", "def reverseBetween(head, m, n):\n\n def reverse(head, m, n):\n m_node = head.__next__\n current = m_node.__next__\n prev_node = m_node\n position2 = m + 1\n while position2 <= n:\n next_node = current.__next__\n current.next = prev_node\n prev_node = current\n current = next_node\n position2 += 1\n m_node.next = next_node\n return prev_node\n if m == n:\n return head\n sentinal = ListNode(-1)\n sentinal.next = head\n current = sentinal\n position = 0\n while current.__next__ is not None:\n if position + 1 == m:\n pre_m = current\n pre_m.next = reverse(pre_m, m, n)\n break\n else:\n position += 1\n current = current.__next__\n if position == 0:\n return pre_m.__next__\n else:\n return head", "def reverseBetween(head, m, n):\n if n == 1:\n return head\n sentinel = ListNode(0)\n pre = sentinel\n pre.next = head\n end = head\n while m > 1:\n pre = pre.__next__\n m -= 1\n while n:\n end = end.__next__\n n -= 1\n new_start = self.reverse(pre.__next__, end)\n pre.next = new_start\n return sentinel.__next__\n\ndef reverse(cur, end):\n new_head = end\n while cur != end:\n next = cur.__next__\n cur.next = new_head\n new_head = cur\n cur = next\n return new_head", "def reverseBetween(head, m, n):\n dummy = ListNode(-1)\n dummy.next = head\n count = 0\n pre = dummy\n while head:\n count += 1\n temp = head.next\n if count == m:\n mNode = head\n if count < m:\n pre = pre.next\n if count > m and count <= n:\n head.next = pre.next\n pre.next = head\n mNode.next = temp\n head = temp\n return dummy.next", "def reverseBetween(head, m, n):\n dummyNode = ListNode(0)\n dummyNode.next = head\n pre = dummyNode\n for i in range(m - 1):\n pre = pre.__next__\n cur = pre.__next__\n reverse = None\n for i in range(n - m + 1):\n next = cur.__next__\n cur.next = reverse\n reverse = cur\n cur = next\n pre.next.next = cur\n pre.next = reverse\n return dummyNode.__next__", "def reverseBetween(head, m, n):\n if n == m:\n return head\n pre_head = head\n re_tail = head\n for i in range(m - 1):\n pre_head = re_tail\n re_tail = pre_head.__next__\n tmp_head = re_tail\n new_head = None\n for i in range(n - m + 1):\n next_node = tmp_head.__next__\n tmp_head.next = new_head\n new_head = tmp_head\n tmp_head = next_node\n re_tail.next = tmp_head\n if m == 1:\n return new_head\n else:\n pre_head.next = new_head\n return head", "def reverseBetween(head, m, n):\n if not head:\n return None\n node = ListNode(0)\n node.next = head\n pre = node\n cur = node.__next__\n for i in range(m - 1):\n pre = pre.__next__\n cur = cur.__next__\n for i in range(n - m):\n tmp = cur.__next__\n cur.next = tmp.__next__\n tmp.next = pre.__next__\n pre.next = tmp\n return node.__next__", "def reverseBetween(head, m, n):\n h = ListNode(0)\n h.next = head\n count = 0\n cur = h\n leftPrev = None\n prev = None\n right = None\n while cur:\n if count == m:\n leftPrev = prev\n left = cur\n if count == n:\n right = cur\n break\n count += 1\n prev = cur\n cur = cur.__next__\n if leftPrev == None or left == right:\n return h.__next__\n rightNext = right.__next__\n tail = right.__next__\n cur = left\n while cur != rightNext:\n temp = cur\n cur = cur.__next__\n temp.next = tail\n tail = temp\n leftPrev.next = tail\n return h.__next__", "def reverseBetween(head, m, n):\n if m == 1:\n m_node = head\n else:\n m_pre = head\n for i in range(m - 2):\n m_pre = m_pre.next\n m_node = m_pre.next\n a = m_node\n b = a.next\n c = a.next\n a.next = None\n for i in range(n - m):\n c = c.next\n b.next = a\n a = b\n b = c\n m_node.next = c\n if m == 1:\n return a\n else:\n m_pre.next = a\n return head"], "starter_code": "def __init__(val=0, next=None):\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Linked List"], "name": null, "source": "leetcode", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/reverse-linked-list-ii/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "__init__", "task_id": "TACO_lite/188", "example": [[], []]} +{"requirement": "Given a Binary Tree. Find the difference between the sum of node values at even levels and the sum of node values at the odd levels.\nExample 1:\nInput:\n 1\n / \\\n 2 3\nOutput: -4\nExplanation:\nsum at odd levels - sum at even levels\n= (1)-(2+3) = 1-5 = -4\nExample 2:\nInput:\n 10\n / \\\n 20 30\n / \\ \n 40 60 \nOutput: 60\nExplanation:\nsum at odd levels - sum at even levels\n= (10+40+60) - (20+30)\n= 110 - 50\n= 60\nYour Task: \nYou dont need to read input or print anything. Complete the function getLevelDiff() which takes root node as input parameter and returns an integer.\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(height of tree)\n \nConstraints:\n1 \u2264 N \u2264 10^5", "solutions": ["def getLevelDiff(root):\n if root == None:\n return 0\n q = []\n q.append(root)\n reverse = True\n s = 0\n while q != []:\n c = len(q)\n for i in range(c):\n val = q.pop(0)\n if reverse == True:\n s += val.data\n else:\n s -= val.data\n if val.left != None:\n q.append(val.left)\n if val.right != None:\n q.append(val.right)\n reverse = ~reverse\n return s", "def getLevelDiff(root):\n if root is None:\n return 0\n return root.data - self.getLevelDiff(root.left) - self.getLevelDiff(root.right)", "from collections import deque\n\ndef getLevelDiff(root):\n queue = deque()\n queue.append(root)\n odd_sum = 0\n even_sum = 0\n level = 0\n while queue:\n size = len(queue)\n for _ in range(size):\n curr = queue.popleft()\n if level % 2 == 0:\n even_sum += curr.data\n else:\n odd_sum += curr.data\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n level = level + 1\n return even_sum - odd_sum", "def getLevelDiff(root):\n o = []\n e = []\n s = [root]\n res = []\n level = 0\n while s:\n new = []\n if s:\n if level % 2 != 0:\n e.append(s)\n else:\n o.append(s)\n for i in s:\n node = i\n if node.left:\n new.append(node.left)\n if node.right:\n new.append(node.right)\n if new:\n s = new\n else:\n break\n level += 1\n o1 = []\n e1 = []\n for i in o:\n o1 += i\n for i in e:\n e1 += i\n for i in range(len(o1)):\n o1[i] = o1[i].data\n for i in range(len(e1)):\n e1[i] = e1[i].data\n return sum(o1) - sum(e1)", "def getLevelDiff(root):\n if root is None:\n return\n q = []\n c = 1\n q.append(root)\n odd = []\n even = []\n while len(q) > 0:\n t = []\n n = len(q)\n for i in range(n):\n temp = q.pop(0)\n t.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n if c % 2 == 0:\n for i in t:\n even.append(i)\n else:\n for z in t:\n odd.append(z)\n c += 1\n return sum(odd) - sum(even)", "def getLevelDiff(root):\n if not root:\n return -1\n l = 1\n q = []\n q.append(root)\n o = []\n e = []\n while q:\n t = []\n for i in range(len(q)):\n n = q.pop(0)\n t.append(n.data)\n if n.left:\n q.append(n.left)\n if n.right:\n q.append(n.right)\n if l % 2 == 0:\n for i in t:\n e.append(i)\n else:\n for i in t:\n o.append(i)\n l += 1\n return sum(o) - sum(e)", "def getLevelDiff(root):\n flag = True\n q = [root]\n oddS = 0\n evenS = 0\n while q:\n n = len(q)\n temp = 0\n for i in range(n):\n node = q.pop(0)\n temp += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if flag:\n oddS += temp\n else:\n evenS += temp\n flag = not flag\n return oddS - evenS", "from collections import deque\n\ndef getLevelDiff(root):\n (es, os) = (0, 0)\n level = 1\n q = deque([root, None])\n while len(q) != 1:\n ele = q.popleft()\n if ele:\n if level % 2 == 0:\n es += ele.data\n else:\n os += ele.data\n if ele.left:\n q.append(ele.left)\n if ele.right:\n q.append(ele.right)\n else:\n level += 1\n q.append(None)\n return os - es", "def getLevelDiff(root):\n if root is None:\n return None\n q = []\n q.append(root)\n j = 1\n (os, es) = (0, 0)\n while q:\n s = 0\n l = len(q)\n for i in range(1, l + 1):\n n = q.pop(0)\n s += n.data\n if n.left:\n q.append(n.left)\n if n.right:\n q.append(n.right)\n if j % 2:\n os += s\n else:\n es += s\n j += 1\n return os - es", "def getLevelDiff(root):\n flag = 0\n ans = 0\n q = [root]\n while q:\n num = 0\n for _ in range(len(q)):\n node = q.pop(0)\n num += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if flag == 0:\n ans += num\n flag = 1\n else:\n flag = 0\n ans -= num\n return ans", "def getLevelDiff(root):\n even = 0\n odd = 0\n lvl = 0\n if root == None:\n return\n li = []\n li.append(root)\n while len(li):\n size = len(li)\n lvl += 1\n while size:\n temp = li[0]\n li.pop(0)\n if lvl % 2 == 0:\n even += temp.data\n else:\n odd += temp.data\n if temp.left:\n li.append(temp.left)\n if temp.right:\n li.append(temp.right)\n size -= 1\n return odd - even", "from collections import deque\n\ndef getLevelDiff(root):\n dQ = deque()\n level1 = level2 = 0\n if root != None:\n dQ.append(root)\n track = 0\n while dQ:\n times = len(dQ)\n track += 1\n for i in range(times):\n havenode = dQ.popleft()\n (level1, level2) = [level1 + havenode.data, level2] if track % 2 == 1 else [level1, level2 + havenode.data]\n if havenode.left != None:\n dQ.append(havenode.left)\n if havenode.right != None:\n dQ.append(havenode.right)\n return level1 - level2", "def getLevelDiff(root):\n global esum\n global osum\n esum = 0\n osum = 0\n\n def helper(root, c):\n global esum\n global osum\n if root == None:\n return\n if c % 2 == 0:\n osum += root.data\n else:\n esum += root.data\n helper(root.left, c + 1)\n helper(root.right, c + 1)\n helper(root, 0)\n return osum - esum", "def fun(root, level, l):\n if root == None:\n return\n if level >= len(l):\n l.append([])\n l[level].append(root.data)\n self.fun(root.left, level + 1, l)\n self.fun(root.right, level + 1, l)\n\ndef getLevelDiff(root):\n l = []\n self.fun(root, 0, l)\n (s1, s2) = (0, 0)\n for i in range(len(l)):\n if i % 2 == 0:\n s1 += sum(l[i])\n else:\n s2 += sum(l[i])\n return s1 - s2", "from collections import deque\n\ndef getLevelDiff(root):\n if root is None:\n return 0\n return root.data - self.getLevelDiff(root.left) - self.getLevelDiff(root.right)\n return result", "from collections import deque\n\ndef getLevelDiff(root):\n q = deque()\n q.appendleft(root)\n result = 0\n sum = True\n while q:\n temp_sum = 0\n size = len(q)\n for i in range(size):\n node = q.pop()\n temp_sum += node.data\n if node.left:\n q.appendleft(node.left)\n if node.right:\n q.appendleft(node.right)\n if sum:\n result += temp_sum\n else:\n result -= temp_sum\n sum = not sum\n return result", "import queue\n\ndef getLevelDiff(root):\n q = []\n q.append(root)\n result = 0\n sum = True\n while q:\n temp_sum = 0\n size = len(q)\n for i in range(size):\n node = q.pop(0)\n temp_sum += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if sum:\n result += temp_sum\n else:\n result -= temp_sum\n sum = not sum\n return result", "from collections import deque as d\n\ndef getLevelDiff(root):\n l = d()\n l.appendleft(root)\n l.appendleft(' ')\n ll = []\n c = 1\n os = 0\n es = 0\n while l:\n a = l.pop()\n if a == ' ':\n if c % 2 != 0:\n os += sum(ll)\n else:\n es += sum(ll)\n ll = []\n if l:\n l.appendleft(' ')\n c += 1\n else:\n ll.append(a.data)\n if a.left:\n l.appendleft(a.left)\n if a.right:\n l.appendleft(a.right)\n return os - es", "def solve(root, odd, even, l):\n if root == None:\n return\n if l % 2 == 0:\n even.append(root.data)\n else:\n odd.append(root.data)\n l += 1\n self.solve(root.left, odd, even, l)\n self.solve(root.right, odd, even, l)\n l -= 1\n\ndef getLevelDiff(root):\n odd = []\n even = []\n l = 0\n self.solve(root, odd, even, l)\n k = sum(even) - sum(odd)\n return k", "from collections import deque\n\ndef getLevelDiff(root):\n q = deque()\n q.append(root)\n s = root.data\n lvl = 1\n while q:\n k = len(q)\n lvl += 1\n for i in range(k):\n popped = q.popleft()\n if popped.left:\n q.append(popped.left)\n if lvl % 2 == 0:\n s -= popped.left.data\n else:\n s += popped.left.data\n if popped.right:\n q.append(popped.right)\n if lvl % 2 == 0:\n s -= popped.right.data\n else:\n s += popped.right.data\n return s", "def getLevelDiff(root):\n even = 0\n odd = 0\n\n def lev(rt, level):\n nonlocal even, odd\n if not rt:\n return\n if level % 2 == 0:\n even += rt.data\n if level % 2 == 1:\n odd += rt.data\n lev(rt.left, level + 1)\n lev(rt.right, level + 1)\n lev(root, 1)\n return odd - even", "def getLevelDiff(root):\n odd = 0\n even = 0\n from collections import deque\n q = deque()\n q.append(root)\n c = 1\n while q:\n size = len(q)\n x = 0\n for i in range(size):\n node = q.popleft()\n x += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if c & 1:\n odd += x\n else:\n even += x\n c += 1\n return odd - even", "def getLevelDiff(root):\n l = []\n q = []\n k = [0]\n m = -1\n q.append(root)\n while q:\n z = q.pop(0)\n x = k.pop(0)\n if m != x:\n m = x\n l.append([])\n l[-1].append(z.data)\n if z.left is not None:\n q.append(z.left)\n k.append(x + 1)\n if z.right is not None:\n q.append(z.right)\n k.append(x + 1)\n odd = 0\n for x in range(0, len(l), 2):\n odd += sum(l[x])\n even = 0\n for x in range(1, len(l), 2):\n even += sum(l[x])\n return odd - even", "def getLevelDiff(root):\n dd = {}\n stck = []\n stck.append(root)\n level = 1\n cnt = 1\n while stck:\n total = 0\n for i in range(cnt):\n popped = stck.pop(0)\n total += popped.data\n if popped.left:\n stck.append(popped.left)\n if popped.right:\n stck.append(popped.right)\n cnt = len(stck)\n dd[level] = total\n level += 1\n diff = 0\n for i in dd.keys():\n if i % 2 == 0:\n diff -= dd[i]\n else:\n diff += dd[i]\n return diff", "def getLevelDiff(root):\n self.ans = 0\n\n def cal(root, d):\n if root == None:\n return\n if d % 2 == 0:\n self.ans -= root.data\n else:\n self.ans += root.data\n cal(root.left, d + 1)\n cal(root.right, d + 1)\n cal(root, 1)\n return self.ans", "def getLevelDiff(root):\n q = [root]\n even = 0\n odd = 0\n count = 1\n while q:\n list = []\n for i in q:\n list.append(i.data)\n if count % 2 != 0:\n odd += sum(list)\n else:\n even += sum(list)\n for _ in range(len(q)):\n node = q.pop(0)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n count += 1\n return odd - even", "from collections import deque\n\ndef getLevelDiff(root):\n q = deque([root])\n k = []\n while q:\n n = len(q)\n l = []\n for _ in range(n):\n node = q.popleft()\n l.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n k.append(sum(l))\n o = e = 0\n for i in range(len(k)):\n if i % 2 == 0:\n e += k[i]\n else:\n o += k[i]\n return e - o", "def dfs(n, l):\n if not n:\n return 0\n if not n.left and (not n.right):\n return n.data if l % 2 == 0 else -n.data\n children = dfs(n.left, l + 1) + dfs(n.right, l + 1)\n me = n.data if l % 2 == 0 else -n.data\n return children + me\n\ndef getLevelDiff(root):\n return dfs(root, 0)", "def getLevelDiff(root):\n global sm\n sm = 0\n\n def diff(root, h):\n global sm\n if root is None:\n return\n if h % 2 == 0:\n sm = sm + root.data\n else:\n sm = sm - root.data\n diff(root.left, h + 1)\n diff(root.right, h + 1)\n diff(root, 0)\n return sm", "def getLevelDiff(root):\n c = 1\n if not root:\n return []\n s = 0\n q = []\n q.append(root)\n while q:\n a = []\n le = len(q)\n for i in range(le):\n k = q.pop(0)\n a.append(k.data)\n if k.left:\n q.append(k.left)\n if k.right:\n q.append(k.right)\n if c & 1:\n s += sum(a)\n else:\n s -= sum(a)\n c += 1\n return s", "def getLevelDiff(root):\n sum_even = 0\n sum_odd = 0\n st = []\n counter = 0\n if root is None:\n return 0\n st.append(root)\n while len(st) > 0:\n counter += 1\n t = []\n while len(st) != 0:\n x = st.pop()\n if x.left is not None:\n t.append(x.left)\n if x.right is not None:\n t.append(x.right)\n if counter % 2 == 0:\n sum_even += x.data\n else:\n sum_odd += x.data\n st = t\n return sum_odd - sum_even", "def levelOrder(root):\n bfs = []\n if root is None:\n return bfs\n q = deque([])\n q.append(root)\n while q:\n lvl_size = len(q)\n curr_lvl = []\n for i in range(lvl_size):\n curr = q.popleft()\n curr_lvl.append(curr.data)\n if curr.left is not None:\n q.append(curr.left)\n if curr.right is not None:\n q.append(curr.right)\n bfs.append(curr_lvl)\n return bfs\n\ndef getLevelDiff(root):\n sumi = 0\n count = 0\n a = levelOrder(root)\n while a:\n s = a.pop(0)\n if count % 2 == 0:\n sumi += sum(s)\n else:\n sumi -= sum(s)\n count += 1\n return sumi", "def getLevelDiff(root):\n c = 1\n s1 = 0\n s2 = 0\n queue = [root]\n while queue != []:\n t = []\n for i in range(len(queue)):\n curr = queue[0]\n t.append(curr.data)\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n queue.pop(0)\n if c % 2 == 1:\n s1 += sum(t)\n c += 1\n elif c % 2 != 1:\n s2 += sum(t)\n c += 1\n return s1 - s2", "def getLevelDiff(root):\n es = [0]\n os = [0]\n level = [0]\n self.Util(root, es, os, level, 1)\n return os[0] - es[0]\n\ndef Util(root, es, os, level, l):\n if not root:\n return\n if l % 2 == 0:\n es[0] += root.data\n else:\n os[0] += root.data\n self.Util(root.left, es, os, level, l + 1)\n self.Util(root.right, es, os, level, l + 1)", "def getLevelDiff(root):\n odd = []\n even = []\n q = []\n q.append(root)\n x = 1\n while q:\n l = len(q)\n lis = []\n for i in range(l):\n temp = q.pop(0)\n lis.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n if x % 2 == 0:\n even.extend(lis)\n else:\n odd.extend(lis)\n x += 1\n return sum(odd) - sum(even)", "def getLevelDiff(root):\n q = []\n od = 0\n ev = 0\n q.append(root)\n l = 0\n while q:\n l += 1\n n = len(q)\n ans = 0\n while n > 0:\n k = q.pop(0)\n ans += k.data\n if k.left:\n q.append(k.left)\n if k.right:\n q.append(k.right)\n n -= 1\n if l % 2 == 0:\n ev += ans\n else:\n od += ans\n return od - ev", "def getLevelDiff(root, level=1):\n if root.left == None and root.right == None:\n if level % 2 == 1:\n return root.data\n else:\n return -root.data\n lowlevelleft = 0\n lowlevelright = 0\n if root.left != None:\n lowlevelleft = self.getLevelDiff(root.left, level + 1)\n if root.right != None:\n lowlevelright = self.getLevelDiff(root.right, level + 1)\n if level % 2 == 0:\n return lowlevelleft + lowlevelright - root.data\n else:\n return lowlevelleft + lowlevelright + root.data", "import collections\n\ndef getLevelDiff(root):\n q = collections.deque()\n q.append(root)\n odd = True\n odd_tot = 0\n even_tot = 0\n while q:\n qLen = len(q)\n tot = 0\n for i in range(qLen):\n cur = q.popleft()\n if cur.left:\n q.append(cur.left)\n if cur.right:\n q.append(cur.right)\n tot += cur.data\n if odd:\n odd_tot += tot\n odd = False\n else:\n even_tot += tot\n odd = True\n return odd_tot - even_tot", "def getLevelDiff(root):\n d = []\n g = {}\n m = []\n d.append(1)\n m.append(root)\n while len(m) != 0:\n c = m.pop(0)\n x = d.pop(0)\n if x not in g:\n g[x] = [c.data]\n else:\n g[x].append(c.data)\n if c.left != None:\n m.append(c.left)\n d.append(x + 1)\n if c.right != None:\n m.append(c.right)\n d.append(x + 1)\n odd = 0\n even = 0\n for h in g:\n if h % 2 == 0:\n for j in range(0, len(g[h])):\n even = even + g[h][j]\n else:\n for j in range(0, len(g[h])):\n odd = odd + g[h][j]\n return odd - even", "def getLevelDiff(root):\n sum = [0, 0]\n self.findSum(root, 1, sum)\n return sum[0] - sum[1]\n\ndef findSum(root, level, sum):\n if not root:\n return None\n if level % 2 == 0:\n sum[1] += root.data\n else:\n sum[0] += root.data\n self.findSum(root.left, level + 1, sum)\n self.findSum(root.right, level + 1, sum)", "def getLevelDiff(root):\n if root == None:\n return\n q = [root]\n c = 1\n (s1, s2) = (0, 0)\n while q:\n l = []\n s = len(q)\n for i in range(len(q)):\n t = q.pop(0)\n l.append(t.data)\n if t.left:\n q.append(t.left)\n if t.right:\n q.append(t.right)\n if c == 1:\n s1 = s1 + sum(l)\n c = 0\n else:\n s2 = s2 + sum(l)\n c = 1\n return s1 - s2", "def getLevelDiff(root):\n C = self.reverseLevelOrder(root)\n x = 0\n for i in range(len(C)):\n if i % 2 == 0:\n x += sum(C[i])\n else:\n x -= sum(C[i])\n return x\n\ndef reverseLevelOrder(root):\n A = []\n B = []\n C = []\n D = []\n if root is None:\n return A\n A.append(root)\n while len(A) > 0:\n while len(A) > 0:\n node = A.pop(0)\n B.append(node.data)\n if node.left is not None:\n D.append(node.left)\n if node.right is not None:\n D.append(node.right)\n A.extend(D)\n D = []\n C.append(B)\n B = []\n return C", "def getLevelDiff(root):\n ans = [0] * 1\n\n def fun(root, level):\n if root == None:\n return\n if level % 2 == 0:\n ans[0] += root.data\n else:\n ans[0] -= root.data\n fun(root.left, level + 1)\n fun(root.right, level + 1)\n fun(root, 0)\n return ans[0]", "def getLevelDiff(root):\n l = 0\n q = [root]\n (res, ans) = ([], [])\n if root == None:\n return None\n while q:\n for i in range(len(q)):\n node = q.pop(0)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if l % 2 == 0:\n res.append(node.data)\n else:\n ans.append(node.data)\n l += 1\n return sum(res) - sum(ans)", "from collections import deque\n\ndef getLevelDiff(root):\n\n def traversal(root, level):\n nonlocal sum1, sum2\n if root == None:\n return None\n if level % 2 == 0:\n sum1 += root.data\n else:\n sum2 += root.data\n if root.left:\n traversal(root.left, level + 1)\n if root.right:\n traversal(root.right, level + 1)\n (sum1, sum2) = (0, 0)\n traversal(root, 0)\n return sum1 - sum2", "def getLevelDiff(root):\n q = []\n q.append(root)\n q.append('$')\n odd = 0\n even = 0\n level = 1\n while len(q) > 0:\n t = q.pop(0)\n if t == '$':\n if len(q) > 0:\n q.append('$')\n level += 1\n else:\n if t.left is not None:\n q.append(t.left)\n if t.right is not None:\n q.append(t.right)\n if level % 2 != 0:\n odd += t.data\n else:\n even += t.data\n return odd - even", "def getLevelDiff(root):\n mylist = [0, 0]\n if not root:\n return 0\n\n def help(root, lvl):\n if lvl % 2 == 0:\n mylist[0] += root.data\n else:\n mylist[1] += root.data\n if root.left:\n help(root.left, lvl + 1)\n if root.right:\n help(root.right, lvl + 1)\n return mylist[0] - mylist[1]\n return help(root, 0)", "def getLevelDiff(root):\n return self.myFunc(root, 0)\n\ndef myFunc(root, level):\n if not root:\n return 0\n level += 1\n summa = root.data\n if level % 2 == 0:\n summa *= -1\n summa += self.myFunc(root.left, level)\n summa += self.myFunc(root.right, level)\n return summa", "def getLevelDiff(root):\n if root == None:\n return 0\n leftsum = self.getLevelDiff(root.left)\n rightsum = self.getLevelDiff(root.right)\n return root.data - leftsum - rightsum", "def in_order(root, lvl, nv):\n if root is None:\n return\n self.in_order(root.left, lvl + 1, nv)\n self.in_order(root.right, lvl + 1, nv)\n if lvl not in nv:\n nv[lvl] = [root.data]\n else:\n nv[lvl].append(root.data)\n\ndef getLevelDiff(root):\n nv = {}\n self.in_order(root, 0, nv)\n osum = 0\n esum = 0\n for (k, v) in nv.items():\n if k % 2:\n esum += sum(v)\n else:\n osum += sum(v)\n return osum - esum", "def getLevelDiff(root):\n ans = [0, 0]\n if not root:\n return 0\n curr = [root]\n i = 0\n while curr:\n next_level = []\n while curr:\n v = curr.pop(0)\n ans[i % 2] += v.data\n if v.left:\n next_level.append(v.left)\n if v.right:\n next_level.append(v.right)\n i += 1\n curr = next_level\n return ans[0] - ans[1]", "def getNode(arr, root, d):\n if not root:\n return\n arr.append([root.data, d])\n self.getNode(arr, root.right, d + 1)\n self.getNode(arr, root.left, d + 1)\n\ndef getLevelDiff(root):\n arr = []\n self.getNode(arr, root, 0)\n sum1 = 0\n sum2 = 0\n dep = len(arr)\n for i in range(0, dep):\n d = arr[i][1] + 1\n if d % 2 == 0:\n sum2 = sum2 + arr[i][0]\n else:\n sum1 = sum1 + arr[i][0]\n return sum1 - sum2", "def getLevelDiff(root):\n if root is None:\n return None\n q = [root]\n ans = root.data\n flag = True\n while len(q) > 0:\n n = len(q)\n temp = 0\n for i in range(0, n):\n node = q.pop(0)\n if node.left:\n q.append(node.left)\n temp += node.left.data\n if node.right:\n q.append(node.right)\n temp += node.right.data\n if flag:\n ans -= temp\n flag = False\n else:\n ans += temp\n flag = True\n return ans", "def getLevelDiff(root):\n\n def helper(root):\n nonlocal odd_sum, even_sum\n nonlocal level\n if root is None:\n return\n level += 1\n if level % 2 == 0:\n even_sum += root.data\n else:\n odd_sum += root.data\n helper(root.left)\n helper(root.right)\n level -= 1\n return\n (odd_sum, even_sum) = (0, 0)\n level = 0\n helper(root)\n return odd_sum - even_sum", "def __init__():\n self.even = 0\n self.odd = 0\n\ndef pre(root, l):\n if root == None:\n return\n if l % 2 == 1:\n self.odd += root.data\n else:\n self.even += root.data\n if root.left != None:\n self.pre(root.left, l + 1)\n if root.right != None:\n self.pre(root.right, l + 1)\n\ndef getLevelDiff(root):\n self.pre(root, 1)\n return self.odd - self.even", "def getLevelDiff(root):\n q = deque()\n q.append(root)\n q.append(None)\n l = []\n m = []\n while len(q) > 1:\n cur = q.popleft()\n if cur == None:\n l.append(m)\n m = []\n q.append(None)\n continue\n m.append(cur.data)\n if cur.left != None:\n q.append(cur.left)\n if cur.right != None:\n q.append(cur.right)\n if m:\n l.append(m)\n os = 0\n es = 0\n for i in range(len(l)):\n if i % 2 == 0:\n os += sum(l[i])\n else:\n es += sum(l[i])\n t = os - es\n return t", "def getLevelDiff(root):\n q = [root]\n level = 1\n sume = 0\n sumo = 0\n while q:\n l = len(q)\n for i in range(l):\n if len(q) != 0:\n x = q.pop(0)\n if level % 2 == 0:\n sume += x.data\n else:\n sumo += x.data\n if i == l - 1:\n level += 1\n if x.left:\n q.append(x.left)\n if x.right:\n q.append(x.right)\n return sumo - sume", "def helper(root, level, d):\n if root:\n if root == 'N':\n return\n else:\n if level not in d:\n d[level] = [root.data]\n else:\n d[level].append(root.data)\n helper(root.left, level + 1, d)\n helper(root.right, level + 1, d)\n\ndef getLevelDiff(root):\n d = {}\n l1 = []\n l2 = []\n level = 1\n helper(root, level, d)\n for i in d:\n if i % 2 == 0:\n l1.append(sum(d[i]))\n else:\n l2.append(sum(d[i]))\n return sum(l2) - sum(l1)", "def getLevelDiff(root):\n q = []\n q.append(root)\n sum_o = 0\n sum_e = 0\n a = 0\n while q:\n n = len(q)\n for i in range(n):\n curr = q.pop(0)\n if a % 2 == 0:\n sum_o = sum_o + curr.data\n else:\n sum_e = sum_e + curr.data\n if curr.left != None:\n q.append(curr.left)\n if curr.right != None:\n q.append(curr.right)\n a += 1\n return sum_o - sum_e", "def __init__():\n self.odd = 0\n self.even = 0\n\ndef getleveldiffutil(root, flag):\n if root is None:\n return None\n if flag == True:\n self.odd += root.data\n else:\n self.even += root.data\n self.getleveldiffutil(root.left, not flag)\n self.getleveldiffutil(root.right, not flag)\n\ndef getLevelDiff(root):\n flag = True\n self.getleveldiffutil(root, flag)\n return self.odd - self.even", "def getLevelDiff(root):\n q = []\n q.append(root)\n level = 1\n odd_sum = 0\n even_sum = 0\n while q:\n for _ in range(len(q)):\n curr = q.pop(0)\n data = curr.data\n if level & 1:\n odd_sum += data\n else:\n even_sum += data\n if curr.left:\n q.append(curr.left)\n if curr.right:\n q.append(curr.right)\n level += 1\n return odd_sum - even_sum", "from collections import deque\n\ndef getLevelDiff(root):\n if not root:\n return 0\n q = deque([root])\n (res, level) = (0, 1)\n while q:\n for _ in range(len(q)):\n node = q.popleft()\n if level & 1:\n res += node.data\n else:\n res -= node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n level += 1\n return res", "def evenOddLevelDifference(root):\n if not root:\n return 0\n q = []\n q.append(root)\n level = 0\n evenSum = 0\n oddSum = 0\n while len(q):\n size = len(q)\n level += 1\n while size > 0:\n temp = q[0]\n q.pop(0)\n if level % 2 == 0:\n evenSum += temp.data\n else:\n oddSum += temp.data\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n size -= 1\n return oddSum - evenSum\n\ndef getLevelDiff(root):\n return evenOddLevelDifference(root)", "def getLevelDiff(root):\n (a, b) = (0, 0)\n\n def lev(root, l):\n nonlocal a, b\n if not root:\n return\n if l % 2 != 0:\n a += root.data\n else:\n b += root.data\n lev(root.left, l + 1)\n lev(root.right, l + 1)\n return a - b\n return lev(root, 1)", "def getLevelDiff(root):\n even = 0\n odd = 0\n evenb = True\n queue = [root]\n elements = 1\n newelements = 0\n while len(queue) > 0:\n root = queue.pop(0)\n if evenb:\n even += root.data\n else:\n odd += root.data\n elements -= 1\n if root.left != None:\n queue.append(root.left)\n newelements += 1\n if root.right != None:\n queue.append(root.right)\n newelements += 1\n if elements == 0:\n elements += newelements\n newelements = 0\n evenb = not evenb\n return even - odd", "def getLevelDiff(root):\n odd = 0\n even = 0\n\n def dfs(root, level):\n nonlocal even\n nonlocal odd\n if not root:\n return\n dfs(root.left, level + 1)\n dfs(root.right, level + 1)\n if level % 2 == 0:\n even += root.data\n else:\n odd += root.data\n return odd - even\n return dfs(root, 1)", "def getLevelDiff(root):\n level = 0\n evenStack = []\n oddStack = []\n\n def oddEvenLevels(root, level):\n if root == None:\n return\n if level % 2 == 0:\n evenStack.append(root.data)\n else:\n oddStack.append(root.data)\n oddEvenLevels(root.left, level + 1)\n oddEvenLevels(root.right, level + 1)\n oddEvenLevels(root, 0)\n evenValue = 0\n for i in evenStack:\n evenValue = evenValue + i\n oddValue = 0\n for i in oddStack:\n oddValue = oddValue + i\n return evenValue - oddValue", "def getLevelDiff(root):\n if root is None:\n return 0\n if root.left is None and root.right is None:\n return root.data\n freq = {}\n self.traversal(root, freq, 1)\n return freq['o'] - freq['e']\n\ndef traversal(root, freq, level):\n if root is None:\n return\n if level % 2 == 0:\n if 'e' in freq.keys():\n freq['e'] += root.data\n else:\n freq['e'] = root.data\n elif 'o' in freq.keys():\n freq['o'] += root.data\n else:\n freq['o'] = root.data\n self.traversal(root.left, freq, level + 1)\n self.traversal(root.right, freq, level + 1)", "def getLevelDiff(root):\n oddArr = []\n evenArr = []\n self.getLevelDiffAux(root, 1, oddArr, evenArr)\n return sum(oddArr) - sum(evenArr)\n\ndef getLevelDiffAux(node, level, oddArr, evenArr):\n if node is None:\n return\n elif level % 2 == 0:\n evenArr.append(node.data)\n else:\n oddArr.append(node.data)\n self.getLevelDiffAux(node.left, level + 1, oddArr, evenArr)\n self.getLevelDiffAux(node.right, level + 1, oddArr, evenArr)", "def getLevelDiff(root):\n\n def helper(root, mp, k):\n if root:\n if k in mp:\n mp[k] += root.data\n else:\n mp[k] = root.data\n helper(root.left, mp, k + 1)\n helper(root.right, mp, k + 1)\n return mp\n mp = helper(root, {}, 0)\n e = 0\n o = 0\n for i in mp:\n if i & 1 == 0:\n e += mp[i]\n else:\n o += mp[i]\n return e - o", "def getLevelDiff(root):\n\n def helper(x):\n ans = []\n q = []\n t = 0\n if not x:\n return None\n q.append(x)\n while q:\n l = len(q)\n for i in range(l):\n a = q.pop(0)\n if a.left:\n q.append(a.left)\n if a.right:\n q.append(a.right)\n t += a.data\n ans.append(t)\n t = 0\n return ans\n a = helper(root)\n b = 0\n c = 0\n for i in range(len(a)):\n if i % 2 == 0:\n b += a[i]\n else:\n c += a[i]\n return b - c", "from collections import deque\n\ndef getLevelDiff(root):\n q = deque()\n q.append(root)\n evenLvl = 0\n oddLvl = 0\n flag = True\n while q:\n for i in range(len(q)):\n temp = q.popleft()\n if flag:\n oddLvl += temp.data\n else:\n evenLvl += temp.data\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n if flag:\n flag = False\n else:\n flag = True\n return oddLvl - evenLvl", "import collections\nfrom collections import deque\n\ndef getLevelDiff(root):\n res = []\n sum1 = 0\n sum2 = 0\n q = collections.deque()\n q.append(root)\n while q:\n ql = len(q)\n l = []\n for i in range(ql):\n x = q.popleft()\n if x:\n l.append(x.data)\n q.append(x.left)\n q.append(x.right)\n if l:\n res.append(l)\n for i in range(len(res)):\n if i % 2 == 0:\n sum1 = sum1 + sum(res[i])\n else:\n sum2 = sum2 + sum(res[i])\n return sum1 - sum2", "def getLevelDiff(root):\n global s, s1\n s = 0\n s1 = 0\n\n def Sm(root, level):\n global s, s1\n if not root:\n return\n if level % 2 == 0:\n s = s + root.data\n else:\n s1 = s1 + root.data\n Sm(root.left, level + 1)\n Sm(root.right, level + 1)\n Sm(root, 1)\n return s1 - s", "def getLevelDiff(root):\n odd = even = 0\n level = 1\n q = [root]\n while q:\n size = len(q)\n for _ in range(size):\n node = q.pop(0)\n if level & 1:\n odd += node.data\n else:\n even += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n level += 1\n return odd - even", "def getLevelDiff(root):\n i = 1\n even = []\n odd = []\n q = []\n q.append(root)\n while q:\n count = len(q)\n while count:\n temp = q.pop(0)\n if i % 2 != 0:\n odd.append(temp.data)\n else:\n even.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n count -= 1\n i += 1\n return sum(odd) - sum(even)", "def getLevelDiff(root):\n\n def getdiff(root):\n if not root:\n return 0\n else:\n l = getdiff(root.left)\n r = getdiff(root.right)\n return root.data - l - r\n return getdiff(root)", "def getLevelDiff(root, l=0):\n if not root:\n return\n esum = 0\n osum = 0\n q = []\n l = 0\n q.append(root)\n while q:\n size = len(q)\n l += 1\n while size > 0:\n tmp = q.pop(0)\n if l % 2 == 0:\n esum += tmp.data\n else:\n osum += tmp.data\n if tmp.left:\n q.append(tmp.left)\n if tmp.right:\n q.append(tmp.right)\n size -= 1\n return osum - esum", "def getLevelDiff(root):\n if root is None:\n return 0\n que = [root]\n (odd, even, level) = (0, 0, 1)\n while que != []:\n temp = []\n for i in que:\n if level % 2 == 0:\n even += i.data\n else:\n odd += i.data\n if i.left:\n temp.append(i.left)\n if i.right:\n temp.append(i.right)\n level += 1\n que = temp\n return odd - even", "def getLevelDiff(root):\n q = []\n s1 = 0\n s2 = 0\n c = 0\n q.append(root)\n while q:\n sz = len(q)\n for i in range(sz):\n curr = q[0]\n q.pop(0)\n if curr.left:\n q.append(curr.left)\n if curr.right:\n q.append(curr.right)\n if c % 2 == 0:\n s1 += curr.data\n else:\n s2 += curr.data\n c += 1\n return s1 - s2", "from collections import deque\n\ndef getLevelDiff(root):\n if root is None:\n return 0\n ans = []\n cnt = 0\n sumo = 0\n sume = 0\n q = deque()\n q.append(root)\n while q:\n cnt = cnt + 1\n n = len(q)\n levelo = []\n levele = []\n for i in range(n):\n node = q.popleft()\n if cnt % 2 == 0:\n levele.append(node.data)\n sume = sume + node.data\n else:\n levelo.append(node.data)\n sumo = sumo + node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return sumo - sume", "def getLevelDiff(root):\n flag = False\n queue = [root]\n odd = 0\n even = 0\n while queue:\n length = len(queue)\n for i in range(length):\n node = queue.pop(0)\n if node.left != None:\n queue.append(node.left)\n if node.right != None:\n queue.append(node.right)\n if flag:\n even += node.data\n else:\n odd += node.data\n flag = not flag\n return odd - even", "def getLevelDiff(root):\n if not root:\n return None\n even = []\n odd = []\n q = []\n l = 0\n q.append(root)\n while len(q) > 0:\n l += 1\n b = []\n li = []\n while len(q) > 0:\n node = q.pop(0)\n li.append(node.data)\n if node.left:\n b.append(node.left)\n if node.right:\n b.append(node.right)\n if l % 2 == 0:\n even.append(sum(li))\n else:\n odd.append(sum(li))\n q = b\n return sum(odd) - sum(even)"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["1\n / \\\n 2 3", "10\n / \\\n 20 30\n / \\ \n 40 60"], "outputs": ["-4", "60"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/odd-even-level-difference/1", "Expected Auxiliary Space": "O(height of tree)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "__init__", "task_id": "TACO_lite/219", "example": [[[[1, 2, 3]], [[10, 20, 30, 40, 60]]], ["-4", "60"]]} +{"requirement": "Given a Binary tree and a key in the binary tree, find the node right to the given key. If there is no node on right side, then return a node with value -1.\nExample 1:\nInput:\n 10\n / \\\n 2 6\n / \\ \\\n 8 4 5\nand key = 2\nOutput: 6\nExplanation: We can see in the above tree\nthat the next right node of 2 is 6.\nExample 2:\nInput:\n 10\n / \\\n 2 6\n / \\ \\\n 8 4 5\nand key = 5\nOutput: -1\nExplanation: We can see in the above tree \nthat there's No next right node of 5.\nSo, the output is -1.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function nextRight() which takes root node of the tree and an integer key as input parameters and returns the next right node of the node with value key. \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1<=N<=10^{3}\n1<=data of node<=10^{3}\n1<=key<=10^{3}", "solutions": ["from collections import deque\n\ndef nextRight(root, key):\n x = []\n q = deque()\n q.append(root)\n while q:\n for i in range(len(q)):\n a = q.popleft()\n x.append(a.data)\n if a.left:\n q.append(a.left)\n if a.right:\n q.append(a.right)\n x.append('l')\n for i in range(len(x) - 1):\n if x[i] == key:\n if x[i + 1] == 'l':\n return Node(-1)\n return Node(x[i + 1])", "from collections import deque\n\ndef nextRight(root, key):\n l = [root]\n temp = Node(-1)\n while l:\n r = []\n size = len(l)\n for i in range(size):\n if l[i].data == key:\n if i < size - 1:\n curr = Node(l[i + 1].data)\n return curr\n else:\n return temp\n if l[i].left:\n r.append(l[i].left)\n if l[i].right:\n r.append(l[i].right)\n l = r\n return temp", "from collections import deque\n\ndef fun(root, level, l, res, key, t):\n if root == None:\n return\n if level >= len(l):\n l.append([])\n t.append([])\n if root.data == key:\n res[0] = level\n l[level].append(root)\n t[level].append(root.data)\n self.fun(root.left, level + 1, l, res, key, t)\n self.fun(root.right, level + 1, l, res, key, t)\n\ndef nextRight(root, key):\n r = root\n (l, res) = ([], [0])\n t = []\n self.fun(root, 0, l, res, key, t)\n ind = res[0]\n t1 = l[ind]\n t2 = t[ind]\n v = t2.index(key)\n if v == len(t2) - 1:\n r.data = -1\n res[0] = r\n else:\n res[0] = t1[v + 1]\n return res[0]", "from collections import deque\n\ndef nextRight(root, key):\n if root is None:\n return Node(-1)\n qn = []\n q1 = []\n level = 0\n qn.append(root)\n q1.append(level)\n while len(qn) > 0:\n node = qn.pop(0)\n level = q1.pop(0)\n if node.data == key:\n if len(q1) == 0 or q1[0] != level:\n return Node(-1)\n return qn[0]\n if node.left is not None:\n qn.append(node.left)\n q1.append(level + 1)\n if node.right is not None:\n qn.append(node.right)\n q1.append(level + 1)\n return Node(-1)", "def nextRight(root, key):\n q = [root]\n ans = Node(-1)\n while q:\n lis = []\n for i in range(len(q)):\n node = q.pop(0)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if lis:\n if lis[-1] == key:\n return node\n lis.append(node.data)\n return ans", "from collections import deque\n\ndef nextRight(root, key):\n queue = [root]\n while queue:\n l = len(queue)\n for i in range(1, l + 1):\n x = queue.pop(0)\n if x.data == key:\n if i != l:\n return queue[0]\n return Node(-1)\n if x.left:\n queue.append(x.left)\n if x.right:\n queue.append(x.right)", "from collections import deque\n\ndef nextRight(root, key):\n dq = deque()\n dq.append(root)\n while len(dq) > 0:\n currsize = len(dq)\n for i in range(currsize):\n temp = dq.popleft()\n if temp.data == key:\n if i == currsize - 1:\n return Node(-1)\n else:\n return dq.popleft()\n if temp.left != None:\n dq.append(temp.left)\n if temp.right != None:\n dq.append(temp.right)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n elements = deque()\n level = deque()\n elements.append(root)\n level.append(0)\n while len(elements) != 0:\n front = elements.popleft()\n curr_level = level.popleft()\n if front.data == key:\n if len(elements) == 0:\n return Node(-1)\n next_ele = elements.popleft()\n next_level = level.popleft()\n if next_level != curr_level:\n return Node(-1)\n else:\n return next_ele\n if front.left != None:\n elements.append(front.left)\n level.append(curr_level + 1)\n if front.right != None:\n elements.append(front.right)\n level.append(curr_level + 1)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n f = [root]\n s = []\n while len(f) > 0:\n node = f[0]\n f.pop(0)\n if node.data == key:\n if len(f) == 0:\n return Node(-1)\n return f[0]\n if node.left != None:\n s.append(node.left)\n if node.right != None:\n s.append(node.right)\n if len(f) == 0:\n f = s\n s = []", "from collections import deque\n\ndef nextRight(root, key):\n q = []\n q.append(root)\n q.append(-1)\n while q:\n l = len(q)\n for i in range(l):\n temp = q.pop(0)\n if temp == -1:\n continue\n else:\n if temp.data == key:\n if len(q):\n if q[0] == -1:\n root.data = -1\n return root\n else:\n return q[0]\n else:\n root.data = -1\n return root\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n q.append(-1)", "from collections import deque\n\ndef nextRight(root, key):\n queue = [root]\n ans = Node(-1)\n while queue:\n n = len(queue)\n for i in range(n):\n curr = queue.pop(0)\n if curr.data == key and i != n - 1:\n return queue[0]\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n return ans", "from collections import deque\n\ndef nextRight(root, key):\n queue = [root]\n while queue != []:\n t2 = []\n for i in range(len(queue)):\n curr = queue[0]\n if curr.left != None:\n queue.append(curr.left)\n t2.append(curr.left)\n if curr.right != None:\n queue.append(curr.right)\n t2.append(curr.right)\n queue.pop(0)\n for i in range(len(t2)):\n if t2[i].data == key:\n try:\n return t2[i + 1]\n except IndexError:\n return Node(-1)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n q = deque()\n q.append(root)\n q.append(None)\n while q:\n dq = q.popleft()\n if dq is None:\n q.append(None)\n continue\n if dq.data == key:\n r = q.popleft()\n if r is None:\n return Node(-1)\n else:\n return r\n if dq.left:\n q.append(dq.left)\n if dq.right:\n q.append(dq.right)", "from collections import deque\n\ndef __init__():\n self.dp = dict()\n self.ans = -1\n\ndef tr(root, l, key):\n if root == None:\n return None\n elif self.dp.get(l) == key:\n self.ans = root.data\n self.dp[l] = root.data\n self.tr(root.left, l + 1, key)\n self.tr(root.right, l + 1, key)\n\ndef nextRight(root, key):\n self.tr(root, 0, key)\n return Node(self.ans)", "from collections import deque\n\ndef nextRight(root, key):\n result = self.myFunc(root, key, [], 0)\n return result[-1] if result else Node(-1)\n\ndef myFunc(root, key, path, level):\n if not root:\n return []\n if len(path) == level:\n path.append([])\n if root.data == key:\n return path[level].copy()\n path[level].append(root)\n level += 1\n result = []\n result += self.myFunc(root.right, key, path, level)\n result += self.myFunc(root.left, key, path, level)\n return result", "from collections import deque\n\ndef nextRight(root, key):\n if root == None or root.data == key:\n return Node(-1)\n que = deque()\n que.append(root)\n while que:\n n = len(que)\n for i in range(n):\n cur = que.popleft()\n if cur.data == key:\n if i < n - 1:\n return que.popleft()\n else:\n return Node(-1)\n if cur.left:\n que.append(cur.left)\n if cur.right:\n que.append(cur.right)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n if not root:\n return []\n curr = [root]\n while curr:\n next_level = []\n while curr:\n v = curr.pop(0)\n if key == v.data:\n if curr:\n return curr.pop(0)\n else:\n return Node(-1)\n if v.left:\n next_level.append(v.left)\n if v.right:\n next_level.append(v.right)\n curr = next_level\n return Node(-1)", "from collections import deque\n\ndef __init__(data):\n self.data = data\n self.left = None\n self.right = None\n\ndef nextRight(root, key):\n d = {}\n level = 0\n self.helper(root, level, d)\n a = 0\n b = 0\n l = []\n for i in d:\n for j in d[i]:\n if key == j.data:\n a = len(d[i])\n b = d[i].index(j)\n l = d[i]\n if a - 1 == b:\n n = Node(-1)\n return n\n else:\n return l[b + 1]\n\ndef helper(root, level, d):\n if not root:\n return\n if level not in d:\n d[level] = [root]\n else:\n d[level].append(root)\n self.helper(root.left, level + 1, d)\n self.helper(root.right, level + 1, d)", "def __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef nextRight(root, key):\n queue = []\n queue.append(root)\n while queue:\n l = len(queue)\n for i in range(l):\n p = queue.pop(0)\n if p.data == key:\n if i < l - 1:\n q = queue.pop(0)\n return q\n if i == l - 1:\n return Node(-1)\n if p.left != None:\n queue.append(p.left)\n if p.right != None:\n queue.append(p.right)\n return -1", "from collections import deque\n\ndef nextRight(root, key):\n\n def traversal(root, level):\n nonlocal f\n if root == None:\n return None\n if root.data == key:\n f = level\n return\n if root.left:\n traversal(root.left, level + 1)\n if root.right:\n traversal(root.right, level + 1)\n f = 0\n traversal(root, 0)\n\n def traversal2(root, level):\n if root == None:\n return None\n if level == 0:\n list1.append(root)\n else:\n traversal2(root.left, level - 1)\n traversal2(root.right, level - 1)\n list1 = []\n traversal2(root, f)\n length = len(list1)\n for i in range(length):\n if list1[i].data == key and i + 1 < length:\n return list1[i + 1]\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n q = deque()\n q.append(root)\n found = False\n ans = Node(-1)\n while True:\n nc = len(q)\n if nc == 0:\n return ans\n if found == True:\n return ans\n while nc > 0:\n node = q.popleft()\n if node.data == key:\n found = True\n nc -= 1\n continue\n elif found == True:\n return node\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n nc -= 1", "from collections import deque\n\ndef nextRight(root, key):\n\n def helper(root, mp, k):\n if root:\n if k in mp:\n mp[k].append(root.data)\n else:\n mp[k] = [root.data]\n helper(root.left, mp, k + 1)\n helper(root.right, mp, k + 1)\n return mp\n mp = {}\n helper(root, mp, 0)\n for k in mp:\n for i in range(len(mp[k])):\n if mp[k][i] == key:\n try:\n return Node(mp[k][i + 1])\n except:\n return Node(-1)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n\n def helper(root, key):\n x = []\n t = []\n q = []\n count = 0\n if not root:\n return x\n q.append(root)\n while q and count == 0:\n for i in range(len(q)):\n a = q.pop(0)\n if a.left:\n q.append(a.left)\n if a.right:\n q.append(a.right)\n t.append(a.data)\n if a.data == key:\n count += 1\n if count == 1:\n x = t\n return x\n a = helper(root, key)\n ans = Node\n ans.data = -1\n if not a:\n return ans\n for i in range(len(a) - 1):\n if a[i] == key:\n ans.data = a[i + 1]\n return ans\n return ans", "from collections import deque\n\ndef nextRight(root, key):\n queue = [root]\n while queue:\n temp = queue.copy()\n if temp[-1].data == key:\n return Node(-1)\n for i in range(len(temp)):\n if temp[i].data == key:\n return temp[i + 1]\n queue.clear()\n for e in temp:\n if e.left:\n queue.append(e.left)\n if e.right:\n queue.append(e.right)\n return -1", "from collections import deque\n\ndef nextRight(root, key):\n node = root\n q = [node]\n while q:\n c = len(q)\n temp = []\n for i in range(c):\n nd = q.pop(0)\n if nd.data == key:\n if q:\n return q[0]\n else:\n return Node(-1)\n else:\n if nd.left:\n temp.append(nd.left)\n if nd.right:\n temp.append(nd.right)\n while temp:\n q.append(temp.pop(0))\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n l = []\n q = []\n q.append(root)\n while q:\n t = len(q)\n temp = []\n for i in range(t):\n s = q.pop(0)\n if s.left:\n q.append(s.left)\n if s.right:\n q.append(s.right)\n temp.append(s.data)\n l.append(temp)\n for i in range(len(l)):\n if key in l[i]:\n a = l[i].index(key)\n if a == 0 and i == 0:\n return Node(-1)\n elif a == len(l[i]) - 1:\n return Node(-1)\n else:\n return Node(l[i][a + 1])", "from collections import deque\n\ndef nextRight(root, key):\n q = [root]\n while q:\n arr = q[0:]\n q = []\n for i in range(len(arr)):\n t = arr.pop(0)\n if t.data == key:\n if not arr:\n return Node(-1)\n return arr[0]\n if t.left:\n q.append(t.left)\n if t.right:\n q.append(t.right)", "from collections import deque\n\ndef nextRight(root, key):\n q = deque()\n q.append(root)\n prev = -1\n while q:\n ll = len(q)\n prev = -1\n for _ in range(ll):\n node = q.popleft()\n if prev == -1:\n pass\n elif prev.data == key:\n return node\n prev = node\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n if root is None:\n return Node(-1)\n q = [root]\n while q:\n temp = []\n while q:\n node = q.pop(0)\n if node.data == key:\n if q:\n return q[0]\n else:\n return Node(-1)\n if node.left:\n temp.append(node.left)\n if node.right:\n temp.append(node.right)\n q = temp\n return Node(-1)", "from collections import defaultdict\n\ndef nextRight(root, key):\n arr = defaultdict(list)\n\n def solve(root, level):\n if not root:\n return\n arr[level].append(root.data)\n solve(root.left, level + 1)\n solve(root.right, level + 1)\n solve(root, 0)\n for (k, value) in arr.items():\n for val in value:\n if val == key and value.index(val) < len(value) - 1:\n return Node(value[value.index(val) + 1])\n break\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n q = deque([root])\n while q:\n t = len(q)\n for i in range(t):\n node = q.popleft()\n if node:\n if node.data == key and i < t - 1:\n return q[0]\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n lis = list()\n lis.append([root, 0])\n level = 0\n di = dict()\n ans = -1\n while len(lis):\n (cur_node, level) = lis.pop(0)\n if cur_node.data == key:\n ans = level\n if level in di:\n di[level].append(cur_node)\n else:\n di[level] = list()\n di[level].append(cur_node)\n if cur_node.left:\n lis.append([cur_node.left, level + 1])\n if cur_node.right:\n lis.append([cur_node.right, level + 1])\n n = len(di[ans])\n for i in range(n):\n if i == n - 1 and key == di[ans][i].data:\n return Node(-1)\n elif key == di[ans][i].data:\n return di[ans][i + 1]", "import collections\nfrom collections import deque\n\ndef nextRight(root, key):\n if not root:\n return -1\n q = collections.deque()\n q.append(root)\n res = []\n while q:\n qLen = len(q)\n temp = []\n for i in range(qLen):\n node = q.popleft()\n temp.append(node)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n res.append(temp)\n for i in range(len(res)):\n for j in range(len(res[i])):\n if res[i][j].data == key:\n if j + 1 < len(res[i]):\n return res[i][j + 1]\n temp = Node(-1)\n return temp", "from collections import deque\n\ndef nextRight(root, key):\n queue = [root]\n while 1:\n nodes = len(queue)\n if nodes == 0:\n return Node(-1)\n for i in range(nodes):\n if queue[i].data == key and i != len(queue) - 1:\n return queue[i + 1]\n elif queue[i].data == key and i == len(queue) - 1:\n return Node(-1)\n while nodes > 0:\n node = queue.pop(0)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n nodes -= 1\n return Node(-1)", "import collections\nfrom collections import deque\n\ndef nextRight(root, key):\n q = collections.deque()\n q.append(root)\n while q:\n qLen = len(q)\n for i in range(qLen):\n cur = q.popleft()\n if not cur:\n continue\n if cur.data == key:\n return q[0] if i < qLen - 1 else Node(-1)\n if cur.left:\n q.append(cur.left)\n if cur.right:\n q.append(cur.right)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n q = [(root, 0)]\n while q:\n (x, l) = q.pop(0)\n if x.data == key:\n if q and q[0][1] == l:\n return q[0][0]\n return Node(-1)\n if x.left:\n q.append((x.left, l + 1))\n if x.right:\n q.append((x.right, l + 1))", "from collections import deque\n\ndef nextRight(root, key):\n dic = {}\n\n def levelOrder(node, level):\n if not node:\n return\n else:\n if node.data == key:\n dic[0] = level\n if level in dic:\n dic[level].append(node)\n else:\n dic[level] = [node]\n levelOrder(node.left, level + 1)\n levelOrder(node.right, level + 1)\n levelOrder(root, 1)\n givenLevel = dic[0]\n for i in range(len(dic[givenLevel])):\n if dic[givenLevel][i].data == key:\n if i == len(dic[givenLevel]) - 1:\n node = Node(-1)\n return node\n else:\n return dic[givenLevel][i + 1]\n return root", "from collections import deque\n\ndef nextRight(root, key):\n errorNode = Node(-1)\n inspectList = [root]\n while len(inspectList) > 0:\n tmp = []\n for (i, target) in enumerate(inspectList):\n if target.data == key:\n if i == len(inspectList) - 1:\n return errorNode\n else:\n return inspectList[i + 1]\n else:\n if target.left != None:\n tmp.append(target.left)\n if target.right != None:\n tmp.append(target.right)\n inspectList = tmp\n return errorNode", "from collections import deque\n\ndef nextRight(root, key):\n ret = Node(-1)\n if root == None:\n return ret\n q = deque()\n q.append(root)\n while len(q):\n l = len(q)\n for i in range(l):\n node = q.popleft()\n if node.data == key:\n if len(q) == 0:\n return ret\n if i + 1 < l:\n return q.popleft()\n return ret\n if node.left is not None:\n q.append(node.left)\n if node.right is not None:\n q.append(node.right)\n return ret", "from collections import deque\n\ndef find(lt, k):\n if lt[-1].data == k:\n n = Node(-1)\n return n\n for i in range(len(lt)):\n if lt[i].data == k and i + 1 < len(lt):\n return lt[i + 1]\n\ndef level(lt):\n lt1 = []\n for i in lt:\n if i.left != None:\n lt1.append(i.left)\n if i.right != None:\n lt1.append(i.right)\n return lt1\n\ndef nextRight(root, key):\n lt = [root]\n while self.find(lt, key) == None:\n lt = self.level(lt)\n return self.find(lt, key)", "from collections import deque\n\ndef nextRight(root, key):\n if not root or root.data == key:\n return Node(-1)\n res = []\n q = [root]\n idx = -1\n while len(q) > 0:\n children = []\n nq = []\n while q:\n element = q.pop(0)\n if element.data == key:\n if len(q) > 0:\n return q[0]\n else:\n return Node(-1)\n if element.left:\n nq.append(element.left)\n if element.right:\n nq.append(element.right)\n q.extend(nq)\n res.append(children)\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n nodeQueue = []\n nodeQueue.append({'node': root, 'level': 0})\n while len(nodeQueue) > 0:\n current = nodeQueue.pop(0)\n if current['node'].data == key:\n if len(nodeQueue) == 0:\n return Node(-1)\n if nodeQueue[0]['level'] != current['level']:\n return Node(-1)\n return nodeQueue[0]['node']\n currentLevel = current['level']\n if current['node'].left:\n nodeQueue.append({'node': current['node'].left, 'level': currentLevel + 1})\n if current['node'].right:\n nodeQueue.append({'node': current['node'].right, 'level': currentLevel + 1})", "from collections import deque\n\ndef __init__():\n self.d = dict()\n\ndef findNext(root, key, level):\n if root is None:\n return\n if level not in self.d:\n self.d[level] = list()\n self.d[level].append(root)\n self.findNext(root.left, key, level + 1)\n self.findNext(root.right, key, level + 1)\n\ndef nextRight(root, key):\n self.findNext(root, key, 0)\n for i in self.d:\n l = len(self.d[i])\n for j in range(l):\n if self.d[i][j].data == key:\n if j == l - 1:\n return Node(-1)\n else:\n return self.d[i][j + 1]", "from collections import deque\n\ndef __init__():\n self.levels = {}\n self.keyLevel = None\n\ndef nextRight(root, key):\n self.traverse(root, 0, key)\n return self.findRight(key)\n\ndef traverse(node, level, key):\n if node == None:\n return\n if node.data == key:\n self.keyLevel = level\n if level not in self.levels:\n self.levels[level] = []\n self.levels[level].append(node.data)\n self.traverse(node.left, level + 1, key)\n self.traverse(node.right, level + 1, key)\n\ndef findRight(key):\n levelNodes = self.levels[self.keyLevel]\n rightNodeIndex = levelNodes.index(key) + 1\n if rightNodeIndex > len(levelNodes) - 1:\n return Node(-1)\n return Node(levelNodes[rightNodeIndex])", "from collections import deque\n\ndef nextRight(root, key):\n if not root:\n return root\n q = deque([])\n q.append(root)\n found = False\n node = Node(-1)\n while q:\n l = len(q)\n curr = []\n for i in range(l):\n t = q.popleft()\n if found:\n return t\n if t.data == key:\n found = True\n curr.append(t)\n if t.left:\n q.append(t.left)\n if t.right:\n q.append(t.right)\n found = False\n return node", "from collections import deque\n\ndef nextRight(root, key):\n queue1 = deque()\n queue2 = deque()\n queue1.append(root)\n while queue1:\n pr = queue1.popleft()\n if pr.data == key:\n if queue1:\n return queue1.popleft()\n else:\n return Node(-1)\n if pr.left:\n queue2.append(pr.left)\n if pr.right:\n queue2.append(pr.right)\n if not queue1:\n queue1 = queue2\n queue2 = deque()", "def nextRight(root, key):\n if root.data == key:\n return Node(-1)\n queue = [root]\n data_list = [[root]]\n while queue:\n found = False\n node_queue = []\n for node in queue:\n if node.left:\n if node.left.data == key:\n found = True\n node_queue.append(node.left)\n if node.right:\n if node.right.data == key:\n found = True\n node_queue.append(node.right)\n if found:\n for i in range(len(node_queue)):\n if node_queue[i].data == key:\n if i + 1 < len(node_queue):\n return node_queue[i + 1]\n else:\n return Node(-1)\n data_list.append(node_queue)\n queue = node_queue\n return Node(-1)", "from collections import deque\n\ndef levelBFS(root, key):\n queue = [root]\n data_list = [[root]]\n if queue[0].data == key:\n return Node(-1)\n while queue:\n found = False\n node_queue = []\n for node in queue:\n if node.left:\n if node.left.data == key:\n found = True\n node_queue.append(node.left)\n if node.right:\n if node.right.data == key:\n found = True\n node_queue.append(node.right)\n if found:\n for i in range(len(node_queue)):\n if node_queue[i].data == key:\n if i + 1 < len(node_queue):\n return node_queue[i + 1]\n data_list.append(node_queue)\n queue = node_queue\n return Node(-1)\n\ndef nextRight(root, key):\n return self.levelBFS(root, key)", "from collections import deque\n\ndef levelBFS(root):\n queue = [root]\n data_list = [[root]]\n while queue:\n node_queue = []\n for node in queue:\n if node.left:\n node_queue.append(node.left)\n if node.right:\n node_queue.append(node.right)\n data_list.append(node_queue)\n queue = node_queue\n return data_list\n\ndef nextRight(root, key):\n if root.data == key:\n return Node(-1)\n l = self.levelBFS(root)\n for i in l:\n for j in range(len(i)):\n if i[j].data == key:\n if j + 1 < len(i):\n return i[j + 1]\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n if root == None:\n return 0\n qn = deque()\n ql = deque()\n level = 0\n qn.append(root)\n ql.append(level)\n while len(qn) > 0:\n node = qn.popleft()\n level = ql.popleft()\n if node.data == key:\n if len(ql) == 0 or ql[0] != level:\n ret = Node(-1)\n return ret\n return qn[0]\n if node.left != None:\n qn.append(node.left)\n ql.append(level + 1)\n if node.right != None:\n qn.append(node.right)\n ql.append(level + 1)\n ret = Node(-1)\n return ret", "from collections import deque\n\ndef nextRight(root, key):\n if root == None:\n return Node(-1)\n q = []\n q.append(root)\n res = [root.data]\n while len(q) > 0:\n for i in range(len(res)):\n if res[i] == key:\n if i + 1 < len(res):\n return Node(res[i + 1])\n else:\n return Node(-1)\n res = []\n for i0 in range(len(q)):\n temp = q.pop(0)\n if temp.left:\n q.append(temp.left)\n res.append(temp.left.data)\n if temp.right:\n q.append(temp.right)\n res.append(temp.right.data)", "from collections import deque\n\ndef nextRight(root, key):\n if root is None:\n return Node(-1)\n queue = []\n queue.append(root)\n while queue:\n len_q = len(queue)\n for i in range(len_q):\n node = queue.pop(0)\n if node.data == key:\n if i + 1 < len_q:\n right_node = queue.pop(0)\n return right_node\n else:\n return Node(-1)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return Node(-1)", "from collections import deque\nfrom collections import deque\n\ndef nextRight(root, key):\n queue = deque()\n queue.append(root)\n length = len(queue)\n flag = False\n while queue:\n current = queue.popleft()\n length -= 1\n if current.left is not None:\n queue.append(current.left)\n if current.left.data == key:\n flag = True\n elif flag == True:\n return current.left\n if current.right is not None:\n queue.append(current.right)\n if current.right.data == key:\n flag = True\n elif flag == True:\n return current.right\n if length == 0:\n if flag == True:\n return Node(-1)\n length = len(queue)\n return Node(-1)", "from collections import deque\n\ndef findKeyParent(node, key):\n if node.left != None:\n if node.left.data == key:\n return node\n if node.right != None:\n if node.right.data == key:\n return node\n if not node.left == None:\n left = self.findKeyParent(node.left, key)\n if not left == None:\n return left\n if not node.right == None:\n left = self.findKeyParent(node.right, key)\n if not left == None:\n return left\n return None\n\ndef getTree(node, tree=None, depth=0):\n if tree == None:\n tree = [[node.data]]\n else:\n tree[depth].append(node.data)\n if len(tree) == depth + 1:\n tree.append([])\n if node.left == None:\n tree[depth + 1].append('N')\n else:\n tree = self.getTree(node.left, tree, depth + 1)\n if node.right == None:\n tree[depth + 1].append('N')\n else:\n tree = self.getTree(node.right, tree, depth + 1)\n return tree\n\ndef nextRight(root, key):\n tree = self.getTree(root)\n keyFound = False\n for depth in tree[1:]:\n if keyFound == True:\n return Node(-1)\n for element in depth:\n if keyFound == True:\n if element != 'N':\n return Node(element)\n elif element == key:\n keyFound = True\n return Node(-1)", "from collections import deque\n\ndef nextRight(root, key):\n if root == None or root.data == key:\n return Node(-1)\n nodes = [root]\n node = root\n found_key = False\n found_right = False\n while nodes != []:\n new_nodes = []\n for node in nodes:\n if node.left != None:\n new_nodes.append(node.left)\n if node.left.data == key:\n found_key = True\n elif found_key:\n found_right = True\n return node.left\n if node.right != None:\n new_nodes.append(node.right)\n if node.right.data == key:\n found_key = True\n elif found_key:\n found_right = True\n return node.right\n if found_key:\n break\n (nodes, new_nodes) = (new_nodes, [])\n return Node(-1)"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["10\r\n / \\\r\n 2 6\r\n / \\ \\\r\n 8 4 5\r\nand key = 2", "10\r\n / \\\r\n 2 6\r\n / \\ \\\r\n 8 4 5\r\nand key = 5"], "outputs": ["6", "-1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Tree", "Traversal", "Queue", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures", "Graph traversal"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/next-right-node/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "__init__", "task_id": "TACO_lite/202", "example": [[[10, [2, 6], [8, 4, null, 5], 2], [10, [2, 6], [8, 4, null, 5], 5]], ["6", "-1"]]} +{"requirement": "Your task is to write a function that takes two or more objects and returns a new object which combines all the input objects. \n\nAll input object properties will have only numeric values. Objects are combined together so that the values of matching keys are added together.\n\nAn example:\n\n```python\nobjA = { 'a': 10, 'b': 20, 'c': 30 }\nobjB = { 'a': 3, 'c': 6, 'd': 3 }\ncombine(objA, objB) # Returns { a: 13, b: 20, c: 36, d: 3 }\n```\n\nThe combine function should be a good citizen, so should not mutate the input objects.", "solutions": ["def combine(*bs):\n c = {}\n for b in bs:\n for (k, v) in list(b.items()):\n c[k] = v + c.get(k, 0)\n return c", "from collections import Counter\n\ndef combine(*args):\n return sum((Counter(a) for a in args), Counter())", "def combine(*dictionaries):\n result = {}\n for dict in dictionaries:\n for (key, value) in list(dict.items()):\n result[key] = value + result.get(key, 0)\n return result", "from collections import defaultdict\n\ndef combine(*dicts):\n ret = defaultdict(int)\n for d in dicts:\n for (k, v) in d.items():\n ret[k] += v\n return dict(ret)", "from collections import Counter\n\ndef combine(*args):\n return sum(map(Counter, args), Counter())", "def combine(*args):\n rez = {}\n for i in args:\n for (k, v) in i.items():\n rez[k] = rez.get(k, 0) + v\n return rez", "def combine(*args):\n result = {}\n for obj in args:\n for (key, value) in obj.items():\n if not key in result:\n result[key] = 0\n result[key] += value\n return result", "def combine(*args):\n ret = {}\n for arg in args:\n for (k, v) in arg.items():\n ret.setdefault(k, 0)\n ret[k] = ret[k] + v\n return ret", "def combine(*args):\n keys = set([y for x in args for y in list(x.keys())])\n return {k: sum([a.get(k, 0) for a in args]) for k in keys}"], "starter_code": "def combine(*args):\n", "input_output": {"fn_name": "combine", "inputs": [[{}, {}, {}], [{}]], "outputs": [[{}], [{}]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/56bd9e4b0d0b64eaf5000819", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "combine", "task_id": "TACO_lite/231", "example": [[[{"a": 10, "b": 20, "c": 30}, {"a": 3, "c": 6, "d": 3}]], ["{'a': 13, 'b': 20, 'c': 36, 'd': 3}"]]} +{"requirement": "You have recently discovered that horses travel in a unique pattern - they're either running (at top speed) or resting (standing still).\n\nHere's an example of how one particular horse might travel:\n\n```\nThe horse Blaze can run at 14 metres/second for 60 seconds, but must then rest for 45 seconds.\n\nAfter 500 seconds Blaze will have traveled 4200 metres.\n```\n\nYour job is to write a function that returns how long a horse will have traveled after a given time.\n\n####Input: \n\n* totalTime - How long the horse will be traveling (in seconds)\n\n* runTime - How long the horse can run for before having to rest (in seconds)\n\n* restTime - How long the horse have to rest for after running (in seconds)\n\n* speed - The max speed of the horse (in metres/second)", "solutions": ["def travel(total_time, run_time, rest_time, speed):\n (q, r) = divmod(total_time, run_time + rest_time)\n return (q * run_time + min(r, run_time)) * speed", "def travel(total_time, run_time, rest_time, speed):\n (d, m) = divmod(total_time, run_time + rest_time)\n return (d * run_time + min(m, run_time)) * speed", "def travel(total_time, run_time, rest_time, speed):\n (cycle, left) = divmod(total_time, run_time + rest_time)\n return cycle * run_time * speed + min(left, run_time) * speed", "def travel(total_time, run_time, rest_time, speed):\n (cycles, remaining) = divmod(total_time, run_time + rest_time)\n last_run = min(remaining, run_time)\n return (cycles * run_time + last_run) * speed\n\ndef travel(total, run, rest, speed):\n return (total // (run + rest) * run + min(total % (run + rest), run)) * speed", "def travel(total_time, run_time, rest_time, speed):\n return speed * (run_time * (total_time // (run_time + rest_time)) + min(run_time, total_time % (run_time + rest_time)))", "def travel(total_time, run_time, rest_time, speed):\n (runs, extra) = divmod(total_time, run_time + rest_time)\n return (runs * run_time + min(extra, run_time)) * speed", "def travel(total_time, run_time, rest_time, speed):\n (x, y) = divmod(total_time, run_time + rest_time)\n return (x * run_time + min(y, run_time)) * speed", "def travel(total_time, run_time, rest_time, speed):\n av_speed = speed * run_time / (run_time + rest_time)\n av_time = total_time // (run_time + rest_time)\n r_time = total_time - av_time * (run_time + rest_time)\n return round(av_time * (run_time + rest_time) * av_speed + run_time * speed) if run_time < r_time else round(av_time * (run_time + rest_time) * av_speed + r_time * speed)", "def travel(total_time, run_time, rest_time, speed):\n run_periods = float(total_time) / (run_time + rest_time)\n last_run_time = min(run_periods - int(run_periods), float(run_time) / (run_time + rest_time)) * (run_time + rest_time)\n total_run_time = int(run_periods) * run_time + last_run_time\n return round(total_run_time * speed)", "def travel(total_time, run_time, rest_time, speed):\n (s, is_running) = (0, True)\n while total_time:\n if is_running:\n s += min(total_time, run_time) * speed\n total_time -= min(total_time, run_time) if is_running else min(rest_time, total_time)\n is_running = not is_running\n return s"], "starter_code": "def travel(total_time, run_time, rest_time, speed):\n", "input_output": {"fn_name": "travel", "inputs": [[1000, 10, 127, 14], [1000, 10, 0, 10], [25, 50, 120, 18], [35869784, 90, 100, 5], [1234567, 4, 3, 11], [100000000, 21, 5, 14], [0, 100, 10, 14], [250, 0, 5, 14], [100, 10, 0, 14], [500, 100, 10, 0]], "outputs": [[1120], [10000], [450], [84954920], [7760148], [1130769276], [0], [0], [1400], [0]]}, "difficulty": "EASY", "raw_tags": ["Puzzles"], "name": null, "source": "codewars", "tags": ["Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/56d46b8fda159582e100001b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "travel", "task_id": "TACO_lite/257", "example": [[[500, 60, 45, 14]], ["4200"]]} +{"requirement": "Given a mixed array of number and string representations of integers, add up the string integers and subtract this from the total of the non-string integers. \n\nReturn as a number.", "solutions": ["def div_con(lst):\n return sum((n if isinstance(n, int) else -int(n) for n in lst))", "def div_con(x):\n return sum([a for a in x if isinstance(a, int)]) - sum([int(a) for a in x if not isinstance(a, int)])", "def div_con(x):\n integer = []\n string = []\n for element in x:\n if type(element) == int:\n integer.append(element)\n else:\n string.append(int(element))\n return sum(integer) - sum(string)", "def div_con(x):\n sum = 0\n for i in x:\n if type(i) == int:\n sum += i\n else:\n sum -= int(i)\n return sum", "def div_con(x):\n return sum((-int(i) if isinstance(i, str) else i for i in x))", "def div_con(x):\n diff = 0\n for num in x:\n if isinstance(num, int):\n diff += num\n else:\n diff -= int(num)\n return diff", "div_con = lambda l: sum((e if type(e) == int else -int(e) for e in l))", "def div_con(x):\n num = 0\n strnum = 0\n for number in x:\n if int(number) == number:\n num = num + number\n else:\n strnum = strnum + int(number)\n num = num - strnum\n return num", "div_con = lambda x: sum((i for i in x if type(i) == int)) - sum((int(s) for s in x if type(s) == str))"], "starter_code": "def div_con(x):\n", "input_output": {"fn_name": "div_con", "inputs": [[[9, 3, "7", "3"]], [["5", "0", 9, 3, 2, 1, "9", 6, 7]], [["3", 6, 6, 0, "5", 8, 5, "6", 2, "0"]], [["1", "5", "8", 8, 9, 9, 2, "3"]], [[8, 0, 0, 8, 5, 7, 2, 3, 7, 8, 6, 7]]], "outputs": [[2], [14], [13], [11], [61]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57eaec5608fed543d6000021", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "div_con", "task_id": "TACO_lite/203", "example": [[[[1, "2", 3, "4", 5]], [[10, "20", "30", 40, "50"]], [[100, "200", 300, "400", 500]]], ["3", "-50", "300"]]} +{"requirement": "Given string s consisting of digits 0-9 and a number N, the task is to count the number of subsequences that are divisible by N.\nNote: Answer can be large, output answer modulo 10^{9} + 7\nExample 1:\nInput: s = \"1234\", N = 4\nOutput: 4\nExplanation: The subsequences 4, 12, 24 and \n124 are divisible by 4.\nExample 2:\nInput: s = \"330\", N = 6\nOutput: 4\nExplanation: The subsequences 30, 30, 330 \nand 0 are divisible by 6.\nYour Task: \nYou don't need to read input or print anything. Complete the function countDivisibleSubseq() which takes s and N as input parameters and returns the integer value\nExpected Time Complexity: O(|s|*N)\nExpected Auxiliary Space: O(|s|*N)\nConstraints:\n1 \u2264 |s|*N \u2264 10^{6}", "solutions": ["def countdivisiblesubseq(str, n):\n mod = int(1000000000.0 + 7)\n l = len(str)\n dp = [[0 for x in range(l)] for y in range(n)]\n dp[int(str[0]) % n][0] += 1\n for i in range(1, l):\n dp[int(str[i]) % n][i] += 1\n for j in range(n):\n dp[j][i] += dp[j][i - 1]\n dp[(j * 10 + int(str[i])) % n][i] += dp[j][i - 1]\n return dp[0][l - 1] % mod", "def countdivisiblesubseq(s, N):\n mod = int(1000000007)\n l = len(s)\n dp = [[0 for x in range(n)] for y in range(l)]\n for i in range(0, l):\n dp[i][int(s[i]) % N] = 1\n dp[i][int(s[i]) % N] = dp[i][int(s[i]) % N] % mod\n for i in range(1, l):\n for j in range(0, N):\n dp[i][j] += dp[i - 1][j]\n dp[i][j] = dp[i][j] % mod\n dp[i][(j * 10 + int(s[i])) % N] += dp[i - 1][j]\n dp[i][(j * 10 + int(s[i])) % N] = dp[i][(j * 10 + int(s[i])) % N] % mod\n return dp[l - 1][0] % mod", "def countdivisiblesubseq(s, N):\n MOD = 10 ** 9 + 7\n\n def rec(index, rem):\n if index == len(s):\n return int(rem == 0)\n nt = rec(index + 1, rem)\n tk = rec(index + 1, (rem * 10 + int(s[index])) % N)\n return nt + tk\n dp = [[-1 for _ in range(N + 1)] for _ in range(len(s) + 1)]\n\n def mem(index, rem):\n if index == len(s):\n return int(rem == 0)\n if dp[index][rem] != -1:\n return dp[index][rem]\n nt = mem(index + 1, rem)\n tk = mem(index + 1, (rem * 10 + int(s[index])) % N)\n dp[index][rem] = nt + tk\n return dp[index][rem]\n return mem(0, N) % MOD\n return rec(0, N) % MOD", "def countdivisiblesubseq(s, n):\n l = len(s)\n dp = [[0 for x in range(l)] for y in range(n)]\n dp[int(s[0]) % n][0] += 1\n for i in range(1, l):\n dp[int(s[i]) % n][i] += 1\n for j in range(n):\n dp[j][i] += dp[j][i - 1]\n dp[(j * 10 + int(s[i])) % n][i] += dp[j][i - 1]\n return dp[0][l - 1] % (7 + 10 ** 9)", "def getcount(s, idx, rem, k, memo):\n n = len(s)\n if idx == n:\n return 1 if rem == 0 else 0\n if hashed(idx, rem) in memo:\n return memo[hashed(idx, rem)]\n count = 0\n count += getcount(s, idx + 1, rem, k, memo)\n count += getcount(s, idx + 1, (rem * 10 + int(s[idx])) % k, k, memo)\n memo[hashed(idx, rem)] = count\n return count\n\ndef hashed(a, b):\n return str(a) + ':' + str(b)\n\ndef countdivisiblesubseq(s, N):\n memo = {}\n s = str(s)\n return (getcount(s, 0, 0, N, memo) - 1) % (10 ** 9 + 7)"], "starter_code": "def countdivisiblesubseq(s, N):\n", "input_output": {"inputs": ["s = \"1234\", N = 4", "s = \"330\", N = 6"], "outputs": ["4", "4"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/number-of-subsequences-in-a-string-divisible-by-n5947/1", "Expected Auxiliary Space": "O(|s|*N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|s|*N)", "entry_point": "countdivisiblesubseq", "task_id": "TACO_lite/251", "example": [[["1234", 4], ["330", 6]], ["4", "4"]]} +{"requirement": "Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. The fractions can be in any order.\n\u00a0\nExample 1:\nInput: n = 2\nOutput: [\"1/2\"]\nExplanation: \"1/2\" is the only unique fraction with a denominator less-than-or-equal-to 2.\nExample 2:\nInput: n = 3\nOutput: [\"1/2\",\"1/3\",\"2/3\"]\n\nExample 3:\nInput: n = 4\nOutput: [\"1/2\",\"1/3\",\"1/4\",\"2/3\",\"3/4\"]\nExplanation: \"2/4\" is not a simplified fraction because it can be simplified to \"1/2\".\nExample 4:\nInput: n = 1\nOutput: []\n\n\u00a0\nConstraints:\n\n1 <= n <= 100", "solutions": ["def simplifiedfractions(n: int) -> List[str]:\n fractions = []\n decimals = set()\n for denom in range(1, n + 1):\n for num in range(1, denom + 1):\n if num % denom != 0 and num / denom not in decimals:\n decimals.add(num / denom)\n fractions.append(str(num) + '/' + str(denom))\n return fractions", "import math\n\ndef simplifiedfractions(n: int) -> List[str]:\n\n def recurse(curr_n):\n if curr_n == 1:\n return []\n else:\n curr_arr = []\n init_val = '1/' + str(curr_n)\n curr_arr.append(init_val)\n for i in range(2, curr_n):\n denom = str(curr_n)\n if math.gcd(curr_n, i) == 1:\n numer = str(i)\n val = numer + '/' + denom\n curr_arr.append(val)\n return curr_arr + recurse(curr_n - 1)\n return recurse(n)", "def simplifiedfractions(n: int) -> List[str]:\n res = []\n for i in range(1, n):\n for j in range(i + 1, n + 1):\n if self.gcd(i, j) == 1:\n res.append(str(i) + '/' + str(j))\n return res\n\ndef gcd(a, b):\n while b:\n (a, b) = (b, a % b)\n return abs(a)", "def simplifiedfractions(n: int) -> List[str]:\n r = set()\n for i in range(2, n + 1):\n for j in range(1, i):\n cd = gcd(i, j)\n r.add(str(j // cd) + '/' + str(i // cd))\n return r", "def simplifiedfractions(n: int) -> List[str]:\n res = []\n s = set()\n for i in range(1, n + 1):\n for j in range(1, i):\n if i % j != 0 or j == 1:\n if j / i not in s:\n res.append(str(j) + '/' + str(i))\n s.add(j / i)\n return res", "def simplifiedfractions(n: int) -> List[str]:\n ret = []\n\n def gcd(numerator, denominator):\n if numerator == 0:\n return denominator\n return gcd(denominator % numerator, numerator)\n for numerator in range(1, n + 1):\n for denominator in range(numerator + 1, n + 1):\n if numerator != denominator:\n if gcd(numerator, denominator) == 1:\n ret.append(str(numerator) + '/' + str(denominator))\n return ret", "def simplifiedfractions(n: int) -> List[str]:\n\n def gcd(a, b):\n if a < b:\n (a, b) = (b, a)\n while b != 0:\n (a, b) = (b, a % b)\n return a\n sol = []\n for denom in range(2, n + 1):\n for numer in range(1, denom):\n if numer == 1 or gcd(numer, denom) == 1:\n sol.append(str(numer) + '/' + str(denom))\n return sol", "def simplifiedfractions(n: int) -> List[str]:\n outputs = []\n for i in range(2, n + 1):\n for j in range(1, i):\n if self._gcd(i, j) == 1:\n outputs.append(f'{j}/{i}')\n return outputs\n\ndef _gcd(i: int, j: int):\n if i > j:\n (i, j) = (j, i)\n res = j % i\n if res == 0:\n return i\n else:\n return self._gcd(i, res)", "def gcd(a, b):\n if b == 0:\n return a\n return gcd(b, a % b)\n\ndef simplifiedfractions(n: int) -> List[str]:\n res = []\n for i in range(1, n + 1):\n for j in range(i + 1, n + 1):\n if gcd(i, j) == 1:\n res.append('{}/{}'.format(i, j))\n return res", "def findGCD(a: int, b: int) -> int:\n (a, b) = (a, b) if a > b else (b, a)\n while a != 1 or b != 1:\n if a % b:\n (a, b) = (b, a % b)\n else:\n break\n return b\n\ndef simplifiedfractions(n: int) -> List[str]:\n ret = set()\n for denominator in range(2, n + 1):\n for numerator in range(1, denominator):\n gcd = self.findGCD(denominator, numerator)\n ret.add(f'{numerator // gcd}/{denominator // gcd}')\n return list(ret)", "def simplifiedfractions(n: int) -> List[str]:\n res = []\n for idx in range(2, n + 1):\n for idx2 in range(1, idx):\n if idx2 == 1 or self.get_gcd(idx, idx2) == 1:\n res.append('{}/{}'.format(idx2, idx))\n return res\n\ndef get_gcd(num1, num2):\n if num1 % num2 == 0:\n return num2\n return self.get_gcd(num2, num1 % num2)", "def simplifiedfractions(n: int) -> List[str]:\n ret = set()\n\n def gcd(a, b):\n while True:\n q = a // b\n r = a - b * q\n if r == 0:\n return b\n a = b\n b = r\n for i in range(2, n + 1):\n for j in range(1, i):\n t = gcd(i, j)\n ret.add(f'{j // t}/{i // t}')\n return list(ret)", "def gcd(a, b):\n c = 1\n while c != 0:\n c = a % b\n a = b\n b = c\n return a\n\ndef simplify(a, b):\n d = self.gcd(a, b)\n return (a // d, b // d)\n\ndef simplifiedfractions(n):\n fractions = set()\n for denom in range(1, n + 1):\n for num in range(1, denom):\n expr = '%d/%d' % self.simplify(num, denom)\n if expr not in fractions:\n fractions.add(expr)\n return list(fractions)", "def simplifiedfractions(n: int) -> List[str]:\n l = []\n for i in range(2, n + 1):\n for j in range(1, i):\n if math.gcd(i, j) < 2:\n l += [f'{j}/{i}']\n return l", "def euclid(a, b):\n if b == 0:\n return a\n else:\n return self.euclid(b, a % b)\n\ndef simplifiedfractions(n: int) -> List[str]:\n res = []\n for d in range(2, n + 1):\n for n in range(1, d):\n if self.euclid(n, d) > 1:\n continue\n res.append(str(n) + '/' + str(d))\n return res", "def simplifiedfractions(n):\n res = []\n tmp = set()\n for i in range(1, n + 1):\n for x in range(1, i + 1):\n if x % i != 0 and x / i not in tmp:\n tmp.add(x / i)\n res.append(str(x) + '/' + str(i))\n return res", "def simplifiedfractions(n: int) -> List[str]:\n ans = set()\n for m in range(2, n + 1):\n for i in range(1, m):\n d = math.gcd(i, m)\n if d > 1:\n ans.add(f'{i // d}/{m // d}')\n else:\n ans.add(f'{i}/{m}')\n return ans", "def simplifiedfractions(n: int) -> List[str]:\n ans = []\n q = deque([])\n for i in range(2, n + 1):\n q.append((1, i))\n while q:\n (x, y) = q.popleft()\n if x == 1 or math.gcd(x, y) == 1:\n ans.append(f'{x}/{y}')\n if x + 1 < y:\n q.append((x + 1, y))\n return ans", "def simplifiedfractions(n: int) -> List[str]:\n fin = []\n for i in range(2, n + 1):\n for j in range(1, i):\n if gcd(i, j) == 1:\n fin.append(str(j) + '/' + str(i))\n return fin", "def simplifiedfractions(n: int) -> List[str]:\n res = []\n\n def gcd(x, y):\n while y:\n (x, y) = (y, x % y)\n return x\n for i in range(1, n + 1):\n for j in range(1, i):\n if gcd(i, j) == 1:\n res.append(str(j) + '/' + str(i))\n return res", "def simplifiedfractions(n: int) -> List[str]:\n added = set()\n result = []\n for denominator in range(2, n + 1):\n for i in range(1, denominator):\n if i / denominator in added:\n continue\n added.add(i / denominator)\n result.append(f'{i}/{denominator}')\n return result", "def simplifiedfractions(n: int) -> List[str]:\n output = []\n for n in range(2, n + 1):\n for m in range(1, n):\n if math.gcd(n, m) == 1:\n output.append(str(m) + '/' + str(n))\n return output", "def simplifiedfractions(n: int) -> List[str]:\n\n def gcd(a: int, b: int) -> int:\n if a < b:\n (a, b) = (b, a)\n if b == 0:\n return a\n return gcd(b, a % b)\n out = []\n for denom in range(2, n + 1):\n for num in range(1, denom):\n if gcd(denom, num) == 1:\n out.append(str(num) + '/' + str(denom))\n return out", "def simplifiedfractions(n: int) -> List[str]:\n if n < 2:\n return []\n else:\n res = []\n dicts = {}\n grid = [1] * n\n grid[0] = 0\n for i in range(1, n):\n target = i + 1\n if grid[target - 1] == 1:\n dicts[target] = {target: 1}\n start = target * 2\n while start <= n:\n grid[start - 1] = 0\n dicts[target][start] = 1\n start += target\n for i in range(2, n + 1):\n res.append('1/' + str(i))\n for j in range(2, i):\n found = True\n de = j\n candidates = []\n for (key, value) in list(dicts.items()):\n if de in value:\n candidates.append(key)\n for can in candidates:\n if i in dicts[can]:\n found = False\n break\n if found:\n res.append(str(j) + '/' + str(i))\n return res", "def simplifiedfractions(n: int) -> List[str]:\n\n def gcd(a, b):\n for i in range(a):\n if b % (a - i) == 0 and a % (a - i) == 0:\n return a - i\n ans = []\n for i in range(2, n + 1):\n for j in range(1, i):\n if gcd(j, i) == 1:\n ans.append(f'{j}/{i}')\n return ans", "def simplifiedfractions(n: int) -> List[str]:\n\n def maxm(n1, n2):\n temp = min(n1, n2)\n while temp:\n if n1 % temp == 0 and n2 % temp == 0:\n return temp\n temp -= 1\n res = []\n for j in range(2, n + 1):\n for i in range(1, j):\n if maxm(j, i) > 1:\n continue\n res.append(str(i) + '/' + str(j))\n return res", "def simplifiedfractions(n: int) -> List[str]:\n fractions = set()\n for i in range(2, n + 1):\n for j in range(1, i):\n denom = i\n num = j\n changed = True\n while changed:\n changed = False\n for k in range(2, num + 1):\n if denom % k == 0 and num % k == 0:\n denom = denom // k\n num = num // k\n changed = True\n fractions.add(str(num) + '/' + str(denom))\n return [i for i in fractions]", "def simplifiedfractions(n: int) -> List[str]:\n\n def gcd(i, j):\n (i, j) = sorted([i, j])\n if j % i == 0:\n return i\n return gcd(i, j % i)\n res = []\n for d in range(1, n + 1):\n for n in range(1, n + 1):\n if 0 < n / d < 1 and gcd(d, n) == 1:\n res.append('{}/{}'.format(n, d))\n return res", "def simplifiedfractions(n: int) -> List[str]:\n if n < 2:\n return []\n if n == 2:\n return ['1/2']\n ans = []\n record = {}\n for i in range(2, n):\n a = 1\n b = i\n while b <= n:\n for c in range(1, b):\n if c / b not in record:\n ans.append('{}/{}'.format(c, b))\n record[c / b] = True\n b += 1\n return ans", "def simplifiedfractions(n: int) -> List[str]:\n out = []\n visited = set()\n if n == 1:\n return out\n for i in range(2, n + 1):\n for j in range(1, i):\n tmp = f'{j}/{i}'\n if eval(tmp) not in visited:\n visited.add(eval(tmp))\n out.append(tmp)\n return out", "def simplifiedfractions(n: int) -> List[str]:\n res = []\n num_res = []\n for i in range(1, n + 1):\n for j in range(1, i):\n if i / j not in num_res:\n res.append(str(j) + '/' + str(i))\n num_res.append(i / j)\n return res", "import itertools\n\ndef simplifiedfractions(n: int) -> List[str]:\n res = []\n num_res = []\n for (i, j) in itertools.permutations(range(1, n + 1), 2):\n if i / j < 1 and i / j not in num_res:\n res.append(str(i) + '/' + str(j))\n num_res.append(i / j)\n return res", "def simplifiedfractions(n: int) -> List[str]:\n\n def gcd(a, b):\n if a < b:\n return gcd(b, a)\n while b > 0:\n tmp = a % b\n a = b\n b = tmp\n return a\n ans = []\n if -1 < n < 2:\n return ans\n for i in range(1, n):\n for j in range(i + 1, n + 1):\n if i != j:\n x = gcd(i, j)\n n1 = i\n n2 = j\n if i % x == 0 == j % x and x > 1:\n n1 //= x\n n2 //= x\n st = f'{n1}/{n2}'\n if st not in ans:\n ans.append(st)\n return ans", "def isprime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i = i + 6\n return True\n\ndef simplifiedfractions(n: int) -> List[str]:\n from fractions import Fraction\n p = []\n if n == 1:\n return\n for numerator in range(1, n):\n k = str(1) + '/' + str(numerator + 1)\n p.append(k)\n for numerator in range(2, n + 1):\n for denominator in range(numerator + 1, n + 1):\n b = Fraction(numerator, denominator)\n b = str(b)\n if b not in p:\n k = str(numerator) + '/' + str(denominator)\n p.append(k)\n return p", "from math import gcd\n\ndef simplifiedfractions(n: int) -> List[str]:\n ret = []\n for numerator in range(1, n + 1):\n for denominator in range(numerator + 1, n + 1):\n if numerator != denominator:\n if gcd(numerator, denominator) == 1:\n ret.append(str(numerator) + '/' + str(denominator))\n return ret", "def simplifiedfractions(n: int) -> List[str]:\n if n == 1:\n return []\n\n def gcd(a, b):\n while b > 0:\n r = a % b\n a = b\n b = r\n return a\n ret = []\n for deno in range(2, n + 1):\n for nume in range(1, deno):\n g = gcd(deno, nume)\n n = nume // g\n d = deno // g\n val = str(n) + '/' + str(d)\n if val not in ret:\n ret.append(val)\n return ret"], "starter_code": "def simplifiedfractions(n: int) -> List[str]:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Number Theory", "Math", "String"], "name": null, "source": "leetcode", "tags": ["Number theory", "Mathematics", "String algorithms"], "skill_types": [], "url": "https://leetcode.com/problems/simplified-fractions/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "simplifiedfractions", "task_id": "TACO_lite/215", "example": [[[2], [3], [4], [1]], [["1/2"], ["1/2", "1/3", "2/3"], ["1/2", "1/3", "2/3", "1/4", "3/4"], []]]} +{"requirement": "Given an array arr[] of n positive integers. The task is to find the maximum of j - i subjected to the constraint of arr[i] <= arr[j].\nExample 1:\nInput:\nn = 9\narr[] = {34, 8, 10, 3, 2, 80, 30, 33, 1}\nOutput: \n6\nExplanation: \nIn the given array arr[1] < arr[7] satisfying \nthe required condition (arr[i] <= arr[j]) thus \ngiving the maximum difference of j - i which is\n6(7-1).\nExample 2:\nInput:\nN = 2\narr[] = {18, 17}\nOutput: \n0\nExplanation: \nWe can either take i and j as 0 and 0 \nor we cantake 1 and 1 both give the same result 0.\nYour Task:\nComplete the function maxIndexDiff() which takes array arr and size n, as input parameters and returns an integer representing the answer. You don't to print answer or take inputs. \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 \u2264 N \u2264 10^{6}\n0 \u2264 Arr[i] \u2264 10^{9}", "solutions": ["def maxindexdiff(arr, n):\n m = -100000\n for i in range(n):\n j = n - 1\n while i < j and arr[i] > arr[j]:\n j -= 1\n m = max(m, j - i)\n return m", "def maxindexdiff(arr, n):\n ans = 0\n i = 0\n j = n - 1\n while i <= j:\n if arr[i] <= arr[j]:\n ans = max(ans, j - i)\n i += 1\n j = n - 1\n else:\n j -= 1\n return ans", "def maxindexdiff(arr, n):\n left = [0] * n\n right = [0] * n\n left[0] = arr[0]\n for i in range(1, n):\n left[i] = min(left[i - 1], arr[i])\n right[n - 1] = arr[n - 1]\n for j in range(n - 2, -1, -1):\n right[j] = max(right[j + 1], arr[j])\n maxdiff = -1\n i = 0\n j = 0\n while j < n and i < n:\n if left[i] <= right[j]:\n maxdiff = max(maxdiff, j - i)\n j += 1\n else:\n i += 1\n return maxdiff", "def maxindexdiff(arr, n):\n mx = 0\n current_mx = 0\n for index in range(n):\n start = n - 1\n while start > index and arr[index] > arr[start]:\n start -= 1\n current_mx = start - index\n mx = max(mx, current_mx)\n return mx", "def maxindexdiff(arr, n):\n st = []\n n = len(arr)\n max = -1\n res = 0\n for j in range(n - 1, -1, -1):\n if arr[j] > max:\n max = arr[j]\n st.append(j)\n i = 0\n while i < n and st:\n while st and arr[i] <= arr[st[-1]]:\n j = st.pop()\n if j - i > res:\n res = j - i\n i += 1\n return res", "def maxindexdiff(arr, n):\n maxdiff = 0\n for i in range(n):\n for j in range(n - 1, i, -1):\n if arr[i] <= arr[j]:\n if maxdiff < j - i:\n maxdiff = j - i\n else:\n break\n return maxdiff", "def maxindexdiff(arr, n):\n ans = 0\n for i in range(n):\n for j in range(i + ans + 1, n):\n if arr[j] >= arr[i]:\n ans = j - i\n return ans", "def maxindexdiff(arr, n):\n i = 0\n m = 0\n while i < n - 1:\n j = n - 1\n while i < j:\n if arr[j] >= arr[i]:\n if j - i > m:\n m = j - i\n break\n else:\n j -= 1\n i += 1\n return m", "def maxindexdiff(arr, n):\n st = []\n ans = 0\n j = n - 1\n while j >= 0:\n if len(st) == 0:\n st.append([arr[j], j])\n j -= 1\n else:\n i = 0\n while i < len(st) and st[i][0] < arr[j]:\n i += 1\n if i == len(st):\n st.append([arr[j], j])\n j -= 1\n else:\n ans = max(ans, st[i][1] - j)\n j -= 1\n return ans", "def maxindexdiff(arr, n):\n res = 0\n i = 0\n j = n - 1\n while i <= j:\n if arr[i] <= arr[j]:\n if res < j - i:\n res = j - i\n i = i + 1\n j = n - 1\n else:\n j = j - 1\n return res", "def maxindexdiff(arr, n):\n if n == 1:\n return 0\n res = 0\n temp = 0\n for i in range(0, n):\n j = n - 1\n while i < j:\n if arr[j] >= arr[i]:\n temp = j - i\n break\n else:\n j -= 1\n res = max(res, temp)\n return res", "def maxindexdiff(arr, n):\n r = [0]\n for j in range(n - 1, -1, -1):\n for i in range(0, j - 1):\n if arr[j] >= arr[i]:\n r.append(j - i)\n break\n return max(r)", "def maxindexdiff(arr, n):\n left_min = [0] * n\n right_max = [0] * n\n left_min[0] = arr[0]\n for i in range(1, n):\n left_min[i] = min(left_min[i - 1], arr[i])\n right_max[n - 1] = arr[n - 1]\n for j in range(n - 2, -1, -1):\n right_max[j] = max(right_max[j + 1], arr[j])\n i = j = max_diff = 0\n while i < n and j < n:\n if left_min[i] <= right_max[j]:\n max_diff = max(max_diff, j - i)\n j += 1\n else:\n i += 1\n return max_diff", "def maxindexdiff(arr, n):\n stk = [0]\n for i in range(1, len(arr)):\n if arr[stk[-1]] > arr[i]:\n stk.append(i)\n ans = 0\n for j in range(len(arr) - 1, -1, -1):\n while stk and arr[stk[-1]] <= arr[j]:\n ans = max(ans, j - stk[-1])\n stk.pop()\n return ans", "def maxindexdiff(arr, n):\n k = n - 1\n while k:\n i = 0\n while i + k < n:\n if arr[i] <= arr[i + k]:\n return k\n i += 1\n k -= 1\n return 0", "def maxindexdiff(arr, n):\n Lmin = [0] * n\n Rmax = [0] * n\n Lmin[0] = arr[0]\n for i in range(1, n):\n Lmin[i] = min(arr[i], Lmin[i - 1])\n Rmax[n - 1] = arr[n - 1]\n for j in range(n - 2, -1, -1):\n Rmax[j] = max(arr[j], Rmax[j + 1])\n minIndex = 0\n maxIndex = 0\n maxdiff = -1\n while minIndex < n and maxIndex < n:\n if Lmin[minIndex] <= Rmax[maxIndex]:\n maxdiff = max(maxdiff, maxIndex - minIndex)\n maxIndex = maxIndex + 1\n else:\n minIndex = minIndex + 1\n return maxdiff", "def maxindexdiff(arr, n):\n LMin = [0] * n\n RMax = [0] * n\n LMin[0] = arr[0]\n for i in range(1, n):\n LMin[i] = min(arr[i], LMin[i - 1])\n RMax[n - 1] = arr[n - 1]\n for j in range(n - 2, -1, -1):\n RMax[j] = max(arr[j], RMax[j + 1])\n (i, j, ans) = (0, 0, -1)\n while i < n and j < n:\n if LMin[i] <= RMax[j]:\n ans = max(ans, j - i)\n j += 1\n else:\n i += 1\n return ans", "def maxindexdiff(arr, n):\n cnt = 0\n for i in range(n):\n for j in range(i + cnt, n):\n if arr[j] >= arr[i]:\n cnt = j - i\n return cnt", "def maxindexdiff(arr, n):\n rmax = [0] * n\n rmax[n - 1] = arr[n - 1]\n for i in range(n - 2, -1, -1):\n rmax[i] = max(arr[i], rmax[i + 1])\n mini = -1\n i = 0\n j = 0\n while i < n and j < n:\n if rmax[j] >= arr[i]:\n mini = max(mini, j - i)\n j += 1\n else:\n i += 1\n return mini", "def maxindexdiff(arr, n):\n ans = -1\n minleft = [None] * n\n minleft[0] = arr[0]\n maxright = [None] * n\n maxright[-1] = arr[-1]\n for i in range(1, n):\n minleft[i] = min(minleft[i - 1], arr[i])\n for j in range(n - 2, -1, -1):\n maxright[j] = max(arr[j], maxright[j + 1])\n i = 0\n j = 0\n while i < n and j < n:\n if maxright[j] >= minleft[i]:\n ans = max(ans, j - i)\n j += 1\n else:\n i += 1\n return ans", "def maxindexdiff(arr, n):\n leftMin = [0] * n\n rightMax = [0] * n\n leftMin[0] = arr[0]\n for i in range(1, n):\n leftMin[i] = min(leftMin[i - 1], arr[i])\n rightMax[n - 1] = arr[n - 1]\n for i in range(n - 2, -1, -1):\n rightMax[i] = max(rightMax[i + 1], arr[i])\n (i, j) = (0, 0)\n maxDiff = -1\n while i < n and j < n:\n if leftMin[i] <= rightMax[j]:\n maxDiff = max(maxDiff, j - i)\n j += 1\n else:\n i += 1\n return maxDiff", "import math\n\ndef maxindexdiff(arr, n):\n llow = []\n lhigh = []\n for i in range(len(arr)):\n if len(llow) == 0:\n llow.append([arr[i], i])\n continue\n if llow[len(llow) - 1][0] > arr[i]:\n llow.append([arr[i], i])\n arr = arr[::-1]\n for i in range(len(arr)):\n if len(lhigh) == 0:\n lhigh.append([arr[i], n - 1 - i])\n continue\n if lhigh[len(lhigh) - 1][0] < arr[i]:\n lhigh.append([arr[i], n - 1 - i])\n d = dict()\n\n def dfs(i, j):\n if i == len(llow):\n return -math.inf\n if j == len(lhigh):\n return -math.inf\n if d.get((i, j)) != None:\n return d[i, j]\n if llow[i][0] <= lhigh[j][0]:\n d[i, j] = max(lhigh[j][1] - llow[i][1], dfs(i + 1, j), dfs(i, j + 1))\n return max(lhigh[j][1] - llow[i][1], dfs(i + 1, j), dfs(i, j + 1))\n d[i, j] = max(dfs(i + 1, j), dfs(i, j + 1))\n return d[i, j]\n return dfs(0, 0)", "def maxindexdiff(arr, n):\n i = 0\n j = len(arr) - 1\n res = []\n while i <= j:\n if arr[i] <= arr[j]:\n m = j - i\n res.append(m)\n j = len(arr) - 1\n i += 1\n else:\n j -= 1\n return max(res)", "def maxindexdiff(arr, n):\n i = 0\n j = len(arr) - 1\n lst = []\n while i <= j:\n k = 0\n if arr[i] <= arr[j]:\n k = j - i\n lst.append(k)\n i = i + 1\n j = len(arr) - 1\n else:\n j = j - 1\n p = max(lst)\n return p", "def maxindexdiff(arr, n):\n l = len(arr)\n x = [0] * l\n j = l - 1\n last = 0\n for i in range(l - 1, -1, -1):\n if arr[i] > last:\n last = arr[i]\n j = i\n x[i] = j\n else:\n x[i] = j\n m = 0\n i = j = 0\n while i < l and j < l:\n if arr[i] <= arr[x[j]]:\n m = max(m, j - i)\n j += 1\n else:\n i += 1\n return m", "def maxindexdiff(arr, n):\n (more, less, maxDiff) = (arr[:], arr[:], 0)\n for i in range(1, n):\n if less[i] > less[i - 1]:\n less[i] = less[i - 1]\n for j in range(n - 2, -1, -1):\n if more[j] < more[j + 1]:\n more[j] = more[j + 1]\n (i, j) = (0, 0)\n while j < n and i < n:\n if less[i] <= more[j]:\n maxDiff = max(j - i, maxDiff)\n j = j + 1\n else:\n i = i + 1\n return maxDiff", "def maxindexdiff(arr, n):\n rightMax = [0] * n\n rightMax[n - 1] = arr[n - 1]\n for i in range(n - 2, -1, -1):\n rightMax[i] = max(rightMax[i + 1], arr[i])\n (i, j) = (0, 0)\n maxDist = 0\n while i < n and j < n:\n if rightMax[j] >= arr[i]:\n maxDist = max(maxDist, j - i)\n j += 1\n else:\n i += 1\n return maxDist", "def maxindexdiff(Arr, N):\n leftMin = [0] * N\n rightMax = [0] * N\n leftMin[0] = 0\n rightMax[N - 1] = N - 1\n for i in range(1, N):\n if Arr[i] < Arr[leftMin[i - 1]]:\n leftMin[i] = i\n else:\n leftMin[i] = leftMin[i - 1]\n for i in range(N - 2, -1, -1):\n if Arr[i] > Arr[rightMax[i + 1]]:\n rightMax[i] = i\n else:\n rightMax[i] = rightMax[i + 1]\n i = j = maxDiff = 0\n while i < N and j < N:\n if Arr[leftMin[i]] <= Arr[rightMax[j]]:\n maxDiff = max(maxDiff, j - i)\n j += 1\n else:\n i += 1\n return maxDiff", "def maxindexdiff(arr, n):\n (low, high) = ([], [])\n for i in range(n):\n if low == []:\n low.append(i)\n continue\n if arr[i] < arr[low[-1]]:\n low.append(i)\n i = n - 1\n while i >= 0:\n if high == []:\n high.append(i)\n i -= 1\n continue\n if arr[i] > arr[high[-1]]:\n high.append(i)\n i -= 1\n out = float('-inf')\n for i in range(len(high)):\n for j in range(len(low)):\n if high[i] > low[j] and arr[high[i]] >= arr[low[j]]:\n out = max(out, high[i] - low[j])\n return out if out != float('-inf') else 0", "def maxindexdiff(arr, n):\n l = 0\n r = 0\n lmin = []\n rmax = []\n mini = float('+inf')\n for i in arr:\n mini = min(mini, i)\n lmin.append(mini)\n maxi = float('-inf')\n for i in arr[::-1]:\n maxi = max(maxi, i)\n rmax.append(maxi)\n rmax = rmax[::-1]\n res = -1\n while l < len(lmin) and r < len(rmax):\n if lmin[l] <= rmax[r]:\n res = max(res, r - l)\n r += 1\n else:\n l += 1\n return res", "def maxindexdiff(arr, n):\n maxarr = [0] * n\n minarr = []\n len = n - 1\n for i in range(n):\n if i == 0:\n minarr.append(arr[i])\n maxarr[len - i] = arr[len - i]\n else:\n minarr.append(min(arr[i], minarr[-1]))\n maxarr[len - i] = max(maxarr[len - i + 1], arr[len - i])\n maxlength = 0\n i = 0\n j = 0\n while i < n and j < n:\n if minarr[i] <= maxarr[j]:\n while j < n and minarr[i] <= maxarr[j]:\n j += 1\n maxlength = max(maxlength, j - i - 1)\n else:\n i += 1\n return maxlength", "def maxindexdiff(Arr, n):\n c = []\n k = 0\n for i in range(len(Arr)):\n for j in range(i + 1, len(Arr)):\n if Arr[i] <= Arr[j]:\n k = j - i\n c.append(k)\n if max(c) >= len(Arr) - i:\n break\n return max(c)", "def maxindexdiff(arr, n):\n st = []\n ans = 0\n for (i, a) in enumerate(arr):\n if not st or arr[st[-1]] > a:\n st.append(i)\n for i in range(n - 1, -1, -1):\n while st and arr[st[-1]] <= arr[i]:\n ans = max(ans, i - st[-1])\n st.pop(-1)\n return ans", "def maxindexdiff(arr, n):\n a = 0\n for i in range(n):\n for j in range(i + 1 + a, n):\n if arr[i] <= arr[j]:\n a = max(j - i, a)\n return a", "def maxindexdiff(arr, n):\n mx = 0\n for i in range(0, n):\n j = n - 1\n while j >= i:\n if arr[j] >= arr[i]:\n mx = max(j - i, mx)\n break\n j -= 1\n return mx", "def maxindexdiff(arr, n):\n L = [0] * n\n R = [0] * n\n L[0] = arr[0]\n R[n - 1] = arr[n - 1]\n l = r = 0\n ans = -1\n for i in range(1, n):\n L[i] = min(L[i - 1], arr[i])\n for i in range(n - 2, -1, -1):\n R[i] = max(R[i + 1], arr[i])\n while l < n and r < n:\n if L[l] <= R[r]:\n ans = max(ans, r - l)\n r += 1\n else:\n l += 1\n return ans", "def maxindexdiff(arr, n):\n l = []\n r = []\n temp = 999999999999999999999999999\n for i in range(n):\n if arr[i] < temp:\n temp = arr[i]\n l.append(temp)\n temp = 0\n for j in range(n - 1, -1, -1):\n if arr[j] > temp:\n temp = arr[j]\n r.append(temp)\n r.reverse()\n i = 0\n j = 0\n ans = 0\n while i < n and j < n:\n while j < n and r[j] >= l[i]:\n j += 1\n ans = max(ans, j - 1 - i)\n i += 1\n return ans", "def maxindexdiff(arr, n):\n l_min = [float('-inf')] * n\n r_max = [0] * n\n (l_min[0], r_max[-1]) = (arr[0], arr[-1])\n for i in range(1, n):\n l_min[i] = min(l_min[i - 1], arr[i])\n for i in range(n - 2, -1, -1):\n r_max[i] = max(r_max[i + 1], arr[i])\n (i, j) = (0, 0)\n ans = 0\n while i < n and j < n:\n if l_min[i] <= r_max[j]:\n ans = max(ans, j - i)\n j += 1\n else:\n i += 1\n return ans", "def maxindexdiff(arr, n):\n flag = 0\n for i in range(n):\n low = i\n high = n - 1\n while low <= high:\n if arr[high] >= arr[low]:\n flag = max(flag, high - low)\n break\n else:\n high -= 1\n return flag", "def maxindexdiff(arr, n):\n index = dict()\n for i in range(n):\n if arr[i] in index:\n index[arr[i]].append(i)\n else:\n index[arr[i]] = [i]\n arr.sort()\n maxDiff = 0\n temp = n\n a = arr\n for i in range(n):\n if temp > index[a[i]][0]:\n temp = index[a[i]][0]\n maxDiff = max(maxDiff, index[a[i]][-1] - temp)\n return maxDiff", "def maxindexdiff(arr, n):\n x = 0\n for i in range(0, n):\n j = n - 1\n while arr[i] > arr[j]:\n j = j - 1\n x = max(x, j - i)\n return x"], "starter_code": "def maxindexdiff(arr,n):\n", "input_output": {"inputs": ["n = 9\r\narr[] = {34, 8, 10, 3, 2, 80, 30, 33, 1}", "N = 2\r\narr[] = {18, 17}"], "outputs": ["6", "0"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/maximum-index3307/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "maxindexdiff", "task_id": "TACO_lite/54", "example": [[[9, [34, 8, 10, 3, 2, 80, 30, 33, 1]], [2, [18, 17]]], [null, null]]} +{"requirement": "An onion array is an array that satisfies the following condition for all values of `j` and `k`:\n\nIf all of the following are `true`:\n\n* `j >= 0`\n* `k >= 0`\n* `j + k = array.length - 1`\n* `j != k`\n \nthen:\n\n* `a[j] + a[k] <= 10`\n\n### Examples:\n\n```\n[1, 2, 19, 4, 5] => true (as 1+5 <= 10 and 2+4 <= 10)\n[1, 2, 19, 4, 10] => false (as 1+10 > 10)\n```\n\nWrite a function named `isOnionArray`/`IsOnionArray`/`is_onion_array()` that returns `true` if its argument is an onion array and returns `false` if it is not.\n\n~~~if:php\nYour solution should at least be moderately efficient. Make sure you don't do any unnecessary looping ;)\n~~~", "solutions": ["def is_onion_array(a):\n return all((a[i] + a[-i - 1] <= 10 for i in range(len(a) // 2)))", "from typing import List\n\ndef is_onion_array(a: List[int]) -> bool:\n return all((aj + ak <= 10 for (aj, ak) in zip(a, a[:(len(a) - 1) // 2:-1])))", "def is_onion_array(a):\n for i in range(0, len(a) // 2):\n if a[i] + a[-i - 1] > 10:\n return False\n return True", "def is_onion_array(a):\n for j in range(len(a) // 2):\n if a[j] + a[-j - 1] > 10:\n return False\n return True", "def is_onion_array(a):\n if a == []:\n return True\n a = [sum(x) for x in zip(a, a[::-1])]\n a.pop(len(a) // 2)\n for element in a:\n if element > 10:\n return False\n return True", "def is_onion_array(a):\n i = 0\n j = -1\n while i != len(a) // 2:\n if a[i] + a[j] > 10:\n return False\n i += 1\n j -= 1\n return True", "from itertools import combinations as cb\n\ndef is_onion_array(a):\n return not any([sum(c) == len(a) - 1 and a[c[0]] + a[c[1]] > 10 for c in cb([*range(0, len(a))], 2)])"], "starter_code": "def is_onion_array(a):\n", "input_output": {"fn_name": "is_onion_array", "inputs": [[[6, 0, 4]], [[1, 1, 15, 10, -1]]], "outputs": [[true], [false]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/59b2883c5e2308b54d000013", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_onion_array", "task_id": "TACO_lite/230", "example": [[], []]} +{"requirement": "This kata is all about adding numbers.\n\nYou will create a function named add. It will return the sum of all the arguments. Sounds easy, doesn't it?\n\nWell Here's the Twist. The inputs will gradually decrease with their index as parameter to the function.\n\n```python\n add(3,4,6) #returns (3/1)+(4/2)+(6/3)=7\n```\n\nRemember the function will return 0 if no arguments are passed and it must round the result if sum is a float.\n\nExample\n```python\n add() #=> 0\n add(1,2,3) #=> 3\n add(1,4,-6,20) #=> 6\n```\n\nCheck my another kata here!! http://www.codewars.com/kata/555b73a81a6285b6ce000047", "solutions": ["def add(*args):\n return int(round(sum((float(a) / i for (i, a) in enumerate(args, 1)))))", "def add(*args):\n return round(sum((x / i for (i, x) in enumerate(args, 1))))", "add = lambda *a: round(sum((e / i for (i, e) in enumerate(a, 1))))", "def add(*args):\n return round(sum([args[i] / (i + 1) for i in range(len(args))]))", "def add(*args):\n return round(sum((v / i for (i, v) in enumerate(args, 1))))", "def add(*args):\n return round(sum((x / (c + 1) for (c, x) in enumerate(args))))", "def add(*args):\n return round(sum((value / pos for (pos, value) in enumerate(args, 1))))", "def add(*args):\n return round(sum((1.0 * n / i for (i, n) in enumerate(args, 1))))", "def add(*args):\n sum = 0\n for (idx, num) in enumerate(args):\n sum += num / (idx + 1.0)\n return round(sum)"], "starter_code": "def add(*args):\n", "input_output": {"fn_name": "add", "inputs": [[100, 200, 300], [2], [4, -3, -2], [-1, -2, -3, -4]], "outputs": [[300], [2], [2], [-4]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/555de49a04b7d1c13c00000e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "add", "task_id": "TACO_lite/132", "example": [[[3, 4, 6], [], [1, 2, 3], [1, 4, -6, 20]], ["7", "0", "3", "6"]]} +{"requirement": "Let be `n` an integer prime with `10` e.g. `7`. \n\n`1/7 = 0.142857 142857 142857 ...`.\n\nWe see that the decimal part has a cycle: `142857`. The length of this cycle is `6`. In the same way:\n\n`1/11 = 0.09 09 09 ...`. Cycle length is `2`.\n\n# Task\n\nGiven an integer n (n > 1), the function cycle(n) returns the length of the cycle if n and 10 are coprimes, otherwise returns -1.\n\n# Examples:\n```\ncycle(5) = -1\ncycle(13) = 6 -> 0.076923 076923 0769\ncycle(21) = 6 -> 0.047619 047619 0476\ncycle(27) = 3 -> 0.037 037 037 037 0370\ncycle(33) = 2 -> 0.03 03 03 03 03 03 03 03\ncycle(37) = 3 -> 0.027 027 027 027 027 0\ncycle(94) = -1 \n\ncycle(22) = -1 since 1/22 ~ 0.0 45 45 45 45 ...\n```", "solutions": ["import math\n\ndef cycle(n):\n if n % 2 == 0 or n % 5 == 0:\n return -1\n k = 1\n while pow(10, k, n) != 1:\n k += 1\n return k", "def cycle(n):\n if not n % 2 or not n % 5:\n return -1\n (x, mods) = (1, set())\n while x not in mods:\n mods.add(x)\n x = 10 * x % n\n return len(mods)", "def cycle(n):\n if n % 5 == 0 or n % 2 == 0:\n return -1\n (remainders, r) = ([1], 0)\n while r != 1:\n r = remainders[-1] * 10 % n\n remainders.append(r)\n return len(remainders) - 1", "def cycle(n):\n if n % 2 and n % 5:\n for i in range(1, n):\n if pow(10, i, n) == 1:\n return i\n return -1", "def cycle(n):\n if n % 2 == 0 or n % 5 == 0:\n return -1\n m = 1\n for p in range(1, n):\n m = 10 * m % n\n if m == 1:\n return p", "def cycle(n):\n if not (n % 2 and n % 5):\n return -1\n return next(filter(lambda x: pow(10, x, n) == 1, range(1, n)))", "def cycle(n):\n if not n % 2 or not n % 5:\n return -1\n (m, s) = (1, set())\n while m not in s:\n s.add(m)\n m = 10 * m % n\n return len(s)", "from math import ceil, log10\n\ndef cycle(d):\n if d % 5 == 0 or d % 2 == 0:\n return -1\n n = 10 ** int(ceil(log10(d)))\n first = n % d\n n *= 10\n for i in range(99999999):\n n %= d\n if n == first:\n return i + 1\n n *= 10", "def cycle(n):\n if n % 2 == 0 or n % 5 == 0:\n return -1\n c = len(str(n))\n m = 10 ** c % n\n while m != 1:\n c += 1\n m = m * 10 % n\n return c", "def cycle(i):\n if i % 2 == 0 or i % 5 == 0:\n return -1\n gen = 10\n n = 1\n while gen % i != 1:\n gen = gen % i * 10\n n = n + 1\n return n"], "starter_code": "def cycle(n) :\n", "input_output": {"fn_name": "cycle", "inputs": [[3], [33], [18118], [69], [197], [65], [97], [19], [111], [53], [59], [93], [51], [159], [183], [167], [94], [133], [218713], [38127], [431541], [221193], [1234567]], "outputs": [[1], [2], [-1], [22], [98], [-1], [96], [18], [3], [13], [58], [15], [16], [13], [60], [166], [-1], [18], [9744], [6230], [726], [3510], [34020]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5a057ec846d843c81a0000ad", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "cycle", "task_id": "TACO_lite/204", "example": [[[5], [13], [21], [27], [33], [37], [94], [22]], ["-1", "6", "6", "3", "2", "3", "-1", "-1"]]} +{"requirement": "In a given array A[] find the maximum value of (A[i] \u2013 i) - (A[j] \u2013 j) where i is not equal to j. \ni and j vary from 0 to N-1 and N is the size of input array A[]. The value of N is always greater than 1.\nExample 1:\nInput\nN = 5\nA[] = {9, 15, 4, 12, 13}\nOutput\n12\nExplanation:\n(a[1]-1) - (a[2]-2) = (15-1)-(4-2) = 12\n \nExample 2:\nInput\nN = 4\nA[] = {3, 1, 2, 4}\nOutput\n3\nExplanation:\n(a[1]-1) - (a[2]-2) = (3-1)-(1-2) = 3\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function maxVal() which takes the array A[] and its size N as inputs and returns the maximum value\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n2 \u2264 N \u2264 10^{5}\n1 \u2264 A[i] \u2264 10^{5}", "solutions": ["def maxval(a, n):\n maxval = 0\n minval = 1000000\n for i in range(n):\n maxval = max(maxval, a[i] - i)\n minval = min(minval, a[i] - i)\n return maxval - minval", "def maxval(a, n):\n X = a[0] - 0\n Y = a[n - 1] - (n - 1)\n for i in range(1, n):\n X = max(X, a[i] - i)\n for j in range(n - 1, -1, -1):\n Y = min(Y, a[j] - j)\n return X - Y", "def maxval(a, n):\n diff = []\n for index in range(n):\n diff.append(a[index] - index)\n diff.sort()\n return diff[-1] - diff[0]", "import sys\n\ndef maxval(a, n):\n min_val = sys.maxsize\n max_val = -sys.maxsize - 1\n for i in range(n):\n if a[i] - i > max_val:\n max_val = a[i] - i\n if a[i] - i < min_val:\n min_val = a[i] - i\n return max_val - min_val", "def maxval(a, n):\n mx = 0\n mn = 1000000\n ans = 0\n for i in range(0, n):\n prvmx = mx\n prvmn = mn\n if a[i] - i + 1 > mx:\n mx = a[i] - i + 1\n if a[i] - i + 1 < mn:\n mn = a[i] - i + 1\n ans = max(ans, prvmx - mn)\n ans = max(ans, mx - prvmn)\n return ans", "def maxval(arr, N):\n maxi = arr[0] - 0\n mini = arr[0] - 0\n for i in range(1, N):\n if arr[i] - i > maxi:\n maxi = arr[i] - i\n if arr[i] - i < mini:\n mini = arr[i] - i\n return maxi - mini", "def maxval(a, n):\n maxx = 0\n mini = 100000007\n for i in range(0, n):\n if a[i] - i > maxx:\n maxx = a[i] - i\n if a[i] - i < mini:\n mini = a[i] - i\n return maxx - mini", "def maxval(a, n):\n for i in range(n):\n a[i] -= i\n a.sort()\n return a[-1] - a[0]", "def maxval(a, n):\n mx = 0\n lst = []\n for i in range(n):\n lst.append(a[i] - i)\n lst.sort()\n return lst[-1] - lst[0]", "def maxval(a, n):\n mini = 1000000000.0\n maxi = -1000000000.0\n for i in range(0, n):\n a[i] = a[i] - i\n mini = min(mini, a[i])\n maxi = max(maxi, a[i])\n return maxi - mini", "def maxval(a, n):\n (min, max) = (99999999, -9999999)\n for i in range(0, n):\n if a[i] - i > max:\n max = a[i] - i\n if a[i] - i < min:\n min = a[i] - i\n return max - min", "def maxval(arr, n):\n maxval = 0\n minval = float('inf')\n for i in range(n):\n maxval = max(maxval, arr[i] - i)\n minval = min(minval, arr[i] - i)\n return maxval - minval", "def maxval(a, n):\n maxi = a[0]\n mini = a[0]\n for i in range(n):\n if a[i] - i > maxi:\n maxi = a[i] - i\n if a[i] - i < mini:\n mini = a[i] - i\n return maxi - mini", "def maxval(a, n):\n max = a[0]\n min = a[0]\n for i in range(n):\n value = a[i] - i\n if value > max:\n max = a[i] - i\n if value < min:\n min = a[i] - i\n return max - min", "def maxval(a: list, n: int) -> int:\n (minimum, maximum) = (float('inf'), float('-inf'))\n for i in range(n):\n if a[i] - i < minimum:\n minimum = a[i] - i\n if a[i] - i > maximum:\n maximum = a[i] - i\n return maximum - minimum", "def maxval(a, n):\n maxa = -9999999999\n mina = 99999999999\n for i in range(0, n):\n maxa = max(maxa, a[i] - i)\n mina = min(mina, a[i] - i)\n return maxa - mina", "def maxval(a, n):\n maxval = -999999999\n minval = 999999999\n for i in range(n):\n maxval = max(maxval, a[i] - i)\n minval = min(minval, a[i] - i)\n return maxval - minval", "def maxval(a, n):\n s = set()\n for i in range(n):\n s.add(a[i] - i)\n return max(s) - min(s)", "def maxval(a, n):\n dic = {}\n for i in range(n):\n k = a[i] - i\n dic[k] = True\n k = list(dic.keys())\n return max(k) - min(k)", "def maxval(a, n):\n for i in range(n):\n a[i] = a[i] - i\n return max(a) - min(a)", "def maxval(A, n):\n (maxi, mini) = (0, 10000000)\n for i in range(n):\n maxi = max(maxi, A[i] - i)\n mini = min(mini, A[i] - i)\n return maxi - mini", "def maxval(a, n):\n maxi = -1\n mini = 200000\n for i in range(n):\n if a[i] - i > maxi:\n maxi = a[i] - i\n if a[i] - i < mini:\n mini = a[i] - i\n return maxi - mini", "def maxval(a, n):\n m1 = -10 ** 5\n m2 = 10 ** 5\n for i in range(n):\n m1 = max(m1, a[i] - i)\n m2 = min(m2, a[i] - i)\n return m1 - m2", "def maxval(a, n):\n max1 = a[0]\n min1 = a[0]\n for i in range(n):\n if a[i] - i > max1:\n max1 = a[i] - i\n if a[i] - i < min1:\n min1 = a[i] - i\n return max1 - min1", "def maxval(a, n):\n max_val = -123456789\n min_val = 123456789\n for i in range(n):\n if a[i] - i > max_val:\n max_val = a[i] - i\n if a[i] - i < min_val:\n min_val = a[i] - i\n return max_val - min_val", "def maxval(a, n):\n x = -999\n y = 999\n for i in range(n):\n x = max(x, a[i] - i)\n y = min(y, a[i] - i)\n return x - y", "def maxval(a, n):\n ma = -9999\n mi = 9999\n for i in range(n):\n ma = max(ma, a[i] - i)\n mi = min(mi, a[i] - i)\n return ma - mi", "def maxval(a, n):\n (mn, mx) = (float('inf'), -float('inf'))\n for (i, x) in enumerate(a):\n mn = min(mn, x - i)\n mx = max(mx, x - i)\n return mx - mn", "def maxval(a, n):\n MAX = -100000000000.0\n MIN = 100000000000.0\n for i in range(n):\n MAX = max(MAX, a[i] - i)\n MIN = min(MIN, a[i] - i)\n return MAX - MIN", "def maxval(a, n):\n max = a[0] - 0\n min = a[0] - 0\n n = len(a)\n for i in range(1, n):\n x = a[i] - i\n if x < min:\n min = x\n if x > max:\n max = x\n return max - min", "def maxval(a, n):\n for i in range(n):\n a[i] = a[i] - i\n m1 = max(a)\n m2 = min(a)\n m3 = m1 - m2\n return m3", "def maxval(a, n):\n sub = []\n for i in range(n):\n sub.append(a[i] - i)\n sub.sort()\n maxD = sub[-1] - sub[0]\n return maxD", "def maxval(a, n):\n mini = float('inf')\n maxi = float('-inf')\n for (i, val) in enumerate(a):\n if val - i < mini:\n mini = val - i\n if val - i > maxi:\n maxi = val - i\n return maxi - mini", "def maxval(a, n):\n maxv = -float('inf')\n minv = float('inf')\n for i in range(n):\n maxv = max(maxv, a[i] - i)\n minv = min(minv, a[i] - i)\n return maxv - minv", "def maxval(a, n):\n na = []\n for i in range(0, n):\n na.append(a[i] - i)\n qmax = 0\n qmin = 100000\n for i in range(0, n):\n if na[i] > qmax:\n qmax = na[i]\n for i in range(0, n):\n if na[i] < qmin:\n qmin = na[i]\n return qmax - qmin", "def maxval(a, n):\n arr_1 = []\n for i in range(0, n):\n arr_1.append(a[i] - i)\n return max(arr_1) - min(arr_1)", "def maxval(a, n):\n z = 0\n b = max(a)\n for i in range(len(a)):\n if a[i] - i > z:\n z = a[i] - i\n if a[i] - i < b:\n b = a[i] - i\n return z - b", "def maxval(a, n):\n minv = 2 ** 31\n maxv = -2 ** 31\n for i in range(len(a)):\n minv = min(minv, a[i] - i)\n maxv = max(maxv, a[i] - i)\n return maxv - minv", "import sys\n\ndef maxval(a, n):\n if n < 2:\n return 0\n max = -sys.maxsize - 1\n min = sys.maxsize\n for i in range(n):\n if a[i] - i > max:\n max = a[i] - i\n if a[i] - i < min:\n min = a[i] - i\n return max - min", "def maxval(a, n):\n (maxi, mini) = (-10 ** 9, 10 ** 9)\n for (i, j) in enumerate(a):\n maxi = max(maxi, j - i)\n mini = min(mini, j - i)\n return maxi - mini", "def maxval(a, n):\n mx = -1\n mn = 10000000\n for i in range(n):\n a[i] = a[i] - i\n return max(a) - min(a)"], "starter_code": "def maxval(a, n):\n", "input_output": {"inputs": ["N = 5\nA[] = {9, 15, 4, 12, 13}", "N = 4\nA[] = {3, 1, 2, 4}"], "outputs": ["12", "3"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/max-value1205/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "maxval", "task_id": "TACO_lite/246", "example": [[[5, [9, 15, 4, 12, 13]], [4, [3, 1, 2, 4]]], [null, null]]} +{"requirement": "The n-queens puzzle is the problem of placing n queens on an n\u00d7n chessboard such that no two queens attack each other.\n\n\n\nGiven an integer n, return all distinct solutions to the n-queens puzzle.\n\nEach solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.\n\nExample:\n\n\nInput: 4\nOutput: [\n [\".Q..\", // Solution 1\n \"...Q\",\n \"Q...\",\n \"..Q.\"],\n\n [\"..Q.\", // Solution 2\n \"Q...\",\n \"...Q\",\n \".Q..\"]\n]\nExplanation: There exist two distinct solutions to the 4-queens puzzle as shown above.", "solutions": ["def helper(n, currentIndex, aux, rowsWithQueen, alll):\n for i in range(n):\n if i not in rowsWithQueen:\n (x, y) = (currentIndex - 1, i - 1)\n while aux[x][y] != 'Q' and x >= 0 and (y >= 0):\n x -= 1\n y -= 1\n if x != -1 and y != -1:\n continue\n (x, y) = (currentIndex - 1, i + 1)\n while x >= 0 and y < n and (aux[x][y] != 'Q'):\n x -= 1\n y += 1\n if x != -1 and y != n:\n continue\n aux[currentIndex][i] = 'Q'\n rowsWithQueen.append(i)\n if currentIndex == n - 1:\n aw = [[0 for i in range(n)] for j in range(n)]\n for a in range(n):\n for b in range(n):\n aw[a][b] = aux[a][b]\n alll.append(aw)\n else:\n self.helper(n, currentIndex + 1, aux, rowsWithQueen, alll)\n aux[currentIndex][i] = '.'\n rowsWithQueen.pop()\n\ndef solvenqueens(n):\n aux = [['.' for i in range(n)] for j in range(n)]\n rowsWithQueen = []\n alll = []\n self.helper(n, 0, aux, rowsWithQueen, alll)\n aux = []\n for sol in alll:\n ax = []\n for i in sol:\n i = ''.join(i)\n ax.append(i)\n aux.append(ax)\n return aux", "def solvenqueens(n):\n\n def DFS(queens, xy_dif, xy_sum):\n p = len(queens)\n if p == n:\n result.append(queens)\n return None\n for q in range(n):\n if q not in queens and p - q not in xy_dif and (p + q not in xy_sum):\n DFS(queens + [q], xy_dif + [p - q], xy_sum + [p + q])\n result = []\n DFS([], [], [])\n return [['.' * i + 'Q' + '.' * (n - i - 1) for i in sol] for sol in result]", "def __init__():\n self.board = []\n self.col_status = []\n self.row_status = []\n self.dia_status_1 = []\n self.dia_status_2 = []\n self.result = []\n\ndef placeQueen(row, n):\n if row == n:\n tmp = [''.join(el) for el in self.board]\n self.result.append(tmp)\n return\n for i in range(n):\n if self.col_status[i] and self.dia_status_1[i + row] and self.dia_status_2[row - i]:\n self.board[row][i] = 'Q'\n self.col_status[i] = False\n self.dia_status_1[i + row] = False\n self.dia_status_2[row - i] = False\n self.placeQueen(row + 1, n)\n self.board[row][i] = '.'\n self.col_status[i] = True\n self.dia_status_1[i + row] = True\n self.dia_status_2[row - i] = True\n\ndef solvenqueens(n):\n self.board = [['.' for i in range(n)] for j in range(n)]\n self.col_status = [True for i in range(n)]\n self.row_status = [True for i in range(n)]\n self.dia_status_1 = [True for i in range(2 * n - 1)]\n self.dia_status_2 = [True for i in range(2 * n - 1)]\n self.placeQueen(0, n)\n return self.result", "def solvenqueens(n):\n if n == 1:\n return [['Q']]\n elif n == 2 or n == 3:\n return []\n elif n == 4:\n return [['.Q..', '...Q', 'Q...', '..Q.'], ['..Q.', 'Q...', '...Q', '.Q..']]\n elif n == 5:\n return [['Q....', '..Q..', '....Q', '.Q...', '...Q.'], ['Q....', '...Q.', '.Q...', '....Q', '..Q..'], ['.Q...', '...Q.', 'Q....', '..Q..', '....Q'], ['.Q...', '....Q', '..Q..', 'Q....', '...Q.'], ['..Q..', 'Q....', '...Q.', '.Q...', '....Q'], ['..Q..', '....Q', '.Q...', '...Q.', 'Q....'], ['...Q.', 'Q....', '..Q..', '....Q', '.Q...'], ['...Q.', '.Q...', '....Q', '..Q..', 'Q....'], ['....Q', '.Q...', '...Q.', 'Q....', '..Q..'], ['....Q', '..Q..', 'Q....', '...Q.', '.Q...']]\n elif n == 6:\n return [['.Q....', '...Q..', '.....Q', 'Q.....', '..Q...', '....Q.'], ['..Q...', '.....Q', '.Q....', '....Q.', 'Q.....', '...Q..'], ['...Q..', 'Q.....', '....Q.', '.Q....', '.....Q', '..Q...'], ['....Q.', '..Q...', 'Q.....', '.....Q', '...Q..', '.Q....']]\n elif n == 7:\n return [['Q......', '..Q....', '....Q..', '......Q', '.Q.....', '...Q...', '.....Q.'], ['Q......', '...Q...', '......Q', '..Q....', '.....Q.', '.Q.....', '....Q..'], ['Q......', '....Q..', '.Q.....', '.....Q.', '..Q....', '......Q', '...Q...'], ['Q......', '.....Q.', '...Q...', '.Q.....', '......Q', '....Q..', '..Q....'], ['.Q.....', '...Q...', 'Q......', '......Q', '....Q..', '..Q....', '.....Q.'], ['.Q.....', '...Q...', '.....Q.', 'Q......', '..Q....', '....Q..', '......Q'], ['.Q.....', '....Q..', 'Q......', '...Q...', '......Q', '..Q....', '.....Q.'], ['.Q.....', '....Q..', '..Q....', 'Q......', '......Q', '...Q...', '.....Q.'], ['.Q.....', '....Q..', '......Q', '...Q...', 'Q......', '..Q....', '.....Q.'], ['.Q.....', '.....Q.', '..Q....', '......Q', '...Q...', 'Q......', '....Q..'], ['.Q.....', '......Q', '....Q..', '..Q....', 'Q......', '.....Q.', '...Q...'], ['..Q....', 'Q......', '.....Q.', '.Q.....', '....Q..', '......Q', '...Q...'], ['..Q....', 'Q......', '.....Q.', '...Q...', '.Q.....', '......Q', '....Q..'], ['..Q....', '....Q..', '......Q', '.Q.....', '...Q...', '.....Q.', 'Q......'], ['..Q....', '.....Q.', '.Q.....', '....Q..', 'Q......', '...Q...', '......Q'], ['..Q....', '......Q', '.Q.....', '...Q...', '.....Q.', 'Q......', '....Q..'], ['..Q....', '......Q', '...Q...', 'Q......', '....Q..', '.Q.....', '.....Q.'], ['...Q...', 'Q......', '..Q....', '.....Q.', '.Q.....', '......Q', '....Q..'], ['...Q...', 'Q......', '....Q..', '.Q.....', '.....Q.', '..Q....', '......Q'], ['...Q...', '.Q.....', '......Q', '....Q..', '..Q....', 'Q......', '.....Q.'], ['...Q...', '.....Q.', 'Q......', '..Q....', '....Q..', '......Q', '.Q.....'], ['...Q...', '......Q', '..Q....', '.....Q.', '.Q.....', '....Q..', 'Q......'], ['...Q...', '......Q', '....Q..', '.Q.....', '.....Q.', 'Q......', '..Q....'], ['....Q..', 'Q......', '...Q...', '......Q', '..Q....', '.....Q.', '.Q.....'], ['....Q..', 'Q......', '.....Q.', '...Q...', '.Q.....', '......Q', '..Q....'], ['....Q..', '.Q.....', '.....Q.', '..Q....', '......Q', '...Q...', 'Q......'], ['....Q..', '..Q....', 'Q......', '.....Q.', '...Q...', '.Q.....', '......Q'], ['....Q..', '......Q', '.Q.....', '...Q...', '.....Q.', 'Q......', '..Q....'], ['....Q..', '......Q', '.Q.....', '.....Q.', '..Q....', 'Q......', '...Q...'], ['.....Q.', 'Q......', '..Q....', '....Q..', '......Q', '.Q.....', '...Q...'], ['.....Q.', '.Q.....', '....Q..', 'Q......', '...Q...', '......Q', '..Q....'], ['.....Q.', '..Q....', 'Q......', '...Q...', '......Q', '....Q..', '.Q.....'], ['.....Q.', '..Q....', '....Q..', '......Q', 'Q......', '...Q...', '.Q.....'], ['.....Q.', '..Q....', '......Q', '...Q...', 'Q......', '....Q..', '.Q.....'], ['.....Q.', '...Q...', '.Q.....', '......Q', '....Q..', '..Q....', 'Q......'], ['.....Q.', '...Q...', '......Q', 'Q......', '..Q....', '....Q..', '.Q.....'], ['......Q', '.Q.....', '...Q...', '.....Q.', 'Q......', '..Q....', '....Q..'], ['......Q', '..Q....', '.....Q.', '.Q.....', '....Q..', 'Q......', '...Q...'], ['......Q', '...Q...', 'Q......', '....Q..', '.Q.....', '.....Q.', '..Q....'], ['......Q', '....Q..', '..Q....', 'Q......', '.....Q.', '...Q...', '.Q.....']]\n elif n == 8:\n return [['Q.......', '....Q...', '.......Q', '.....Q..', '..Q.....', '......Q.', '.Q......', '...Q....'], ['Q.......', '.....Q..', '.......Q', '..Q.....', '......Q.', '...Q....', '.Q......', '....Q...'], ['Q.......', '......Q.', '...Q....', '.....Q..', '.......Q', '.Q......', '....Q...', '..Q.....'], ['Q.......', '......Q.', '....Q...', '.......Q', '.Q......', '...Q....', '.....Q..', '..Q.....'], ['.Q......', '...Q....', '.....Q..', '.......Q', '..Q.....', 'Q.......', '......Q.', '....Q...'], ['.Q......', '....Q...', '......Q.', 'Q.......', '..Q.....', '.......Q', '.....Q..', '...Q....'], ['.Q......', '....Q...', '......Q.', '...Q....', 'Q.......', '.......Q', '.....Q..', '..Q.....'], ['.Q......', '.....Q..', 'Q.......', '......Q.', '...Q....', '.......Q', '..Q.....', '....Q...'], ['.Q......', '.....Q..', '.......Q', '..Q.....', 'Q.......', '...Q....', '......Q.', '....Q...'], ['.Q......', '......Q.', '..Q.....', '.....Q..', '.......Q', '....Q...', 'Q.......', '...Q....'], ['.Q......', '......Q.', '....Q...', '.......Q', 'Q.......', '...Q....', '.....Q..', '..Q.....'], ['.Q......', '.......Q', '.....Q..', 'Q.......', '..Q.....', '....Q...', '......Q.', '...Q....'], ['..Q.....', 'Q.......', '......Q.', '....Q...', '.......Q', '.Q......', '...Q....', '.....Q..'], ['..Q.....', '....Q...', '.Q......', '.......Q', 'Q.......', '......Q.', '...Q....', '.....Q..'], ['..Q.....', '....Q...', '.Q......', '.......Q', '.....Q..', '...Q....', '......Q.', 'Q.......'], ['..Q.....', '....Q...', '......Q.', 'Q.......', '...Q....', '.Q......', '.......Q', '.....Q..'], ['..Q.....', '....Q...', '.......Q', '...Q....', 'Q.......', '......Q.', '.Q......', '.....Q..'], ['..Q.....', '.....Q..', '.Q......', '....Q...', '.......Q', 'Q.......', '......Q.', '...Q....'], ['..Q.....', '.....Q..', '.Q......', '......Q.', 'Q.......', '...Q....', '.......Q', '....Q...'], ['..Q.....', '.....Q..', '.Q......', '......Q.', '....Q...', 'Q.......', '.......Q', '...Q....'], ['..Q.....', '.....Q..', '...Q....', 'Q.......', '.......Q', '....Q...', '......Q.', '.Q......'], ['..Q.....', '.....Q..', '...Q....', '.Q......', '.......Q', '....Q...', '......Q.', 'Q.......'], ['..Q.....', '.....Q..', '.......Q', 'Q.......', '...Q....', '......Q.', '....Q...', '.Q......'], ['..Q.....', '.....Q..', '.......Q', 'Q.......', '....Q...', '......Q.', '.Q......', '...Q....'], ['..Q.....', '.....Q..', '.......Q', '.Q......', '...Q....', 'Q.......', '......Q.', '....Q...'], ['..Q.....', '......Q.', '.Q......', '.......Q', '....Q...', 'Q.......', '...Q....', '.....Q..'], ['..Q.....', '......Q.', '.Q......', '.......Q', '.....Q..', '...Q....', 'Q.......', '....Q...'], ['..Q.....', '.......Q', '...Q....', '......Q.', 'Q.......', '.....Q..', '.Q......', '....Q...'], ['...Q....', 'Q.......', '....Q...', '.......Q', '.Q......', '......Q.', '..Q.....', '.....Q..'], ['...Q....', 'Q.......', '....Q...', '.......Q', '.....Q..', '..Q.....', '......Q.', '.Q......'], ['...Q....', '.Q......', '....Q...', '.......Q', '.....Q..', 'Q.......', '..Q.....', '......Q.'], ['...Q....', '.Q......', '......Q.', '..Q.....', '.....Q..', '.......Q', 'Q.......', '....Q...'], ['...Q....', '.Q......', '......Q.', '..Q.....', '.....Q..', '.......Q', '....Q...', 'Q.......'], ['...Q....', '.Q......', '......Q.', '....Q...', 'Q.......', '.......Q', '.....Q..', '..Q.....'], ['...Q....', '.Q......', '.......Q', '....Q...', '......Q.', 'Q.......', '..Q.....', '.....Q..'], ['...Q....', '.Q......', '.......Q', '.....Q..', 'Q.......', '..Q.....', '....Q...', '......Q.'], ['...Q....', '.....Q..', 'Q.......', '....Q...', '.Q......', '.......Q', '..Q.....', '......Q.'], ['...Q....', '.....Q..', '.......Q', '.Q......', '......Q.', 'Q.......', '..Q.....', '....Q...'], ['...Q....', '.....Q..', '.......Q', '..Q.....', 'Q.......', '......Q.', '....Q...', '.Q......'], ['...Q....', '......Q.', 'Q.......', '.......Q', '....Q...', '.Q......', '.....Q..', '..Q.....'], ['...Q....', '......Q.', '..Q.....', '.......Q', '.Q......', '....Q...', 'Q.......', '.....Q..'], ['...Q....', '......Q.', '....Q...', '.Q......', '.....Q..', 'Q.......', '..Q.....', '.......Q'], ['...Q....', '......Q.', '....Q...', '..Q.....', 'Q.......', '.....Q..', '.......Q', '.Q......'], ['...Q....', '.......Q', 'Q.......', '..Q.....', '.....Q..', '.Q......', '......Q.', '....Q...'], ['...Q....', '.......Q', 'Q.......', '....Q...', '......Q.', '.Q......', '.....Q..', '..Q.....'], ['...Q....', '.......Q', '....Q...', '..Q.....', 'Q.......', '......Q.', '.Q......', '.....Q..'], ['....Q...', 'Q.......', '...Q....', '.....Q..', '.......Q', '.Q......', '......Q.', '..Q.....'], ['....Q...', 'Q.......', '.......Q', '...Q....', '.Q......', '......Q.', '..Q.....', '.....Q..'], ['....Q...', 'Q.......', '.......Q', '.....Q..', '..Q.....', '......Q.', '.Q......', '...Q....'], ['....Q...', '.Q......', '...Q....', '.....Q..', '.......Q', '..Q.....', 'Q.......', '......Q.'], ['....Q...', '.Q......', '...Q....', '......Q.', '..Q.....', '.......Q', '.....Q..', 'Q.......'], ['....Q...', '.Q......', '.....Q..', 'Q.......', '......Q.', '...Q....', '.......Q', '..Q.....'], ['....Q...', '.Q......', '.......Q', 'Q.......', '...Q....', '......Q.', '..Q.....', '.....Q..'], ['....Q...', '..Q.....', 'Q.......', '.....Q..', '.......Q', '.Q......', '...Q....', '......Q.'], ['....Q...', '..Q.....', 'Q.......', '......Q.', '.Q......', '.......Q', '.....Q..', '...Q....'], ['....Q...', '..Q.....', '.......Q', '...Q....', '......Q.', 'Q.......', '.....Q..', '.Q......'], ['....Q...', '......Q.', 'Q.......', '..Q.....', '.......Q', '.....Q..', '...Q....', '.Q......'], ['....Q...', '......Q.', 'Q.......', '...Q....', '.Q......', '.......Q', '.....Q..', '..Q.....'], ['....Q...', '......Q.', '.Q......', '...Q....', '.......Q', 'Q.......', '..Q.....', '.....Q..'], ['....Q...', '......Q.', '.Q......', '.....Q..', '..Q.....', 'Q.......', '...Q....', '.......Q'], ['....Q...', '......Q.', '.Q......', '.....Q..', '..Q.....', 'Q.......', '.......Q', '...Q....'], ['....Q...', '......Q.', '...Q....', 'Q.......', '..Q.....', '.......Q', '.....Q..', '.Q......'], ['....Q...', '.......Q', '...Q....', 'Q.......', '..Q.....', '.....Q..', '.Q......', '......Q.'], ['....Q...', '.......Q', '...Q....', 'Q.......', '......Q.', '.Q......', '.....Q..', '..Q.....'], ['.....Q..', 'Q.......', '....Q...', '.Q......', '.......Q', '..Q.....', '......Q.', '...Q....'], ['.....Q..', '.Q......', '......Q.', 'Q.......', '..Q.....', '....Q...', '.......Q', '...Q....'], ['.....Q..', '.Q......', '......Q.', 'Q.......', '...Q....', '.......Q', '....Q...', '..Q.....'], ['.....Q..', '..Q.....', 'Q.......', '......Q.', '....Q...', '.......Q', '.Q......', '...Q....'], ['.....Q..', '..Q.....', 'Q.......', '.......Q', '...Q....', '.Q......', '......Q.', '....Q...'], ['.....Q..', '..Q.....', 'Q.......', '.......Q', '....Q...', '.Q......', '...Q....', '......Q.'], ['.....Q..', '..Q.....', '....Q...', '......Q.', 'Q.......', '...Q....', '.Q......', '.......Q'], ['.....Q..', '..Q.....', '....Q...', '.......Q', 'Q.......', '...Q....', '.Q......', '......Q.'], ['.....Q..', '..Q.....', '......Q.', '.Q......', '...Q....', '.......Q', 'Q.......', '....Q...'], ['.....Q..', '..Q.....', '......Q.', '.Q......', '.......Q', '....Q...', 'Q.......', '...Q....'], ['.....Q..', '..Q.....', '......Q.', '...Q....', 'Q.......', '.......Q', '.Q......', '....Q...'], ['.....Q..', '...Q....', 'Q.......', '....Q...', '.......Q', '.Q......', '......Q.', '..Q.....'], ['.....Q..', '...Q....', '.Q......', '.......Q', '....Q...', '......Q.', 'Q.......', '..Q.....'], ['.....Q..', '...Q....', '......Q.', 'Q.......', '..Q.....', '....Q...', '.Q......', '.......Q'], ['.....Q..', '...Q....', '......Q.', 'Q.......', '.......Q', '.Q......', '....Q...', '..Q.....'], ['.....Q..', '.......Q', '.Q......', '...Q....', 'Q.......', '......Q.', '....Q...', '..Q.....'], ['......Q.', 'Q.......', '..Q.....', '.......Q', '.....Q..', '...Q....', '.Q......', '....Q...'], ['......Q.', '.Q......', '...Q....', 'Q.......', '.......Q', '....Q...', '..Q.....', '.....Q..'], ['......Q.', '.Q......', '.....Q..', '..Q.....', 'Q.......', '...Q....', '.......Q', '....Q...'], ['......Q.', '..Q.....', 'Q.......', '.....Q..', '.......Q', '....Q...', '.Q......', '...Q....'], ['......Q.', '..Q.....', '.......Q', '.Q......', '....Q...', 'Q.......', '.....Q..', '...Q....'], ['......Q.', '...Q....', '.Q......', '....Q...', '.......Q', 'Q.......', '..Q.....', '.....Q..'], ['......Q.', '...Q....', '.Q......', '.......Q', '.....Q..', 'Q.......', '..Q.....', '....Q...'], ['......Q.', '....Q...', '..Q.....', 'Q.......', '.....Q..', '.......Q', '.Q......', '...Q....'], ['.......Q', '.Q......', '...Q....', 'Q.......', '......Q.', '....Q...', '..Q.....', '.....Q..'], ['.......Q', '.Q......', '....Q...', '..Q.....', 'Q.......', '......Q.', '...Q....', '.....Q..'], ['.......Q', '..Q.....', 'Q.......', '.....Q..', '.Q......', '....Q...', '......Q.', '...Q....'], ['.......Q', '...Q....', 'Q.......', '..Q.....', '.....Q..', '.Q......', '......Q.', '....Q...']]\n elif n == 9:\n return [['Q........', '..Q......', '.....Q...', '.......Q.', '.Q.......', '...Q.....', '........Q', '......Q..', '....Q....'], ['Q........', '..Q......', '......Q..', '.Q.......', '.......Q.', '....Q....', '........Q', '...Q.....', '.....Q...'], ['Q........', '..Q......', '.......Q.', '.....Q...', '........Q', '.Q.......', '....Q....', '......Q..', '...Q.....'], ['Q........', '...Q.....', '.Q.......', '.......Q.', '.....Q...', '........Q', '..Q......', '....Q....', '......Q..'], ['Q........', '...Q.....', '.....Q...', '..Q......', '........Q', '.Q.......', '.......Q.', '....Q....', '......Q..'], ['Q........', '...Q.....', '.....Q...', '.......Q.', '.Q.......', '....Q....', '..Q......', '........Q', '......Q..'], ['Q........', '...Q.....', '......Q..', '..Q......', '.......Q.', '.Q.......', '....Q....', '........Q', '.....Q...'], ['Q........', '...Q.....', '......Q..', '........Q', '.Q.......', '....Q....', '.......Q.', '.....Q...', '..Q......'], ['Q........', '...Q.....', '.......Q.', '..Q......', '........Q', '......Q..', '....Q....', '.Q.......', '.....Q...'], ['Q........', '....Q....', '.Q.......', '.....Q...', '........Q', '..Q......', '.......Q.', '...Q.....', '......Q..'], ['Q........', '....Q....', '......Q..', '.Q.......', '.....Q...', '..Q......', '........Q', '...Q.....', '.......Q.'], ['Q........', '....Q....', '......Q..', '........Q', '..Q......', '.......Q.', '.Q.......', '...Q.....', '.....Q...'], ['Q........', '....Q....', '......Q..', '........Q', '...Q.....', '.Q.......', '.......Q.', '.....Q...', '..Q......'], ['Q........', '....Q....', '........Q', '.Q.......', '.....Q...', '.......Q.', '..Q......', '......Q..', '...Q.....'], ['Q........', '....Q....', '........Q', '.....Q...', '...Q.....', '.Q.......', '.......Q.', '..Q......', '......Q..'], ['Q........', '.....Q...', '.Q.......', '........Q', '......Q..', '...Q.....', '.......Q.', '..Q......', '....Q....'], ['Q........', '.....Q...', '...Q.....', '.Q.......', '......Q..', '........Q', '..Q......', '....Q....', '.......Q.'], ['Q........', '.....Q...', '...Q.....', '.Q.......', '.......Q.', '..Q......', '........Q', '......Q..', '....Q....'], ['Q........', '.....Q...', '.......Q.', '..Q......', '......Q..', '...Q.....', '.Q.......', '........Q', '....Q....'], ['Q........', '.....Q...', '.......Q.', '....Q....', '.Q.......', '...Q.....', '........Q', '......Q..', '..Q......'], ['Q........', '.....Q...', '........Q', '....Q....', '.Q.......', '.......Q.', '..Q......', '......Q..', '...Q.....'], ['Q........', '......Q..', '...Q.....', '.....Q...', '........Q', '.Q.......', '....Q....', '..Q......', '.......Q.'], ['Q........', '......Q..', '...Q.....', '.......Q.', '..Q......', '....Q....', '........Q', '.Q.......', '.....Q...'], ['Q........', '......Q..', '...Q.....', '.......Q.', '..Q......', '........Q', '.....Q...', '.Q.......', '....Q....'], ['Q........', '......Q..', '....Q....', '.......Q.', '.Q.......', '........Q', '..Q......', '.....Q...', '...Q.....'], ['Q........', '.......Q.', '...Q.....', '.Q.......', '......Q..', '........Q', '.....Q...', '..Q......', '....Q....'], ['Q........', '.......Q.', '....Q....', '..Q......', '.....Q...', '........Q', '.Q.......', '...Q.....', '......Q..'], ['Q........', '.......Q.', '....Q....', '..Q......', '........Q', '......Q..', '.Q.......', '...Q.....', '.....Q...'], ['.Q.......', '...Q.....', 'Q........', '......Q..', '........Q', '.....Q...', '..Q......', '....Q....', '.......Q.'], ['.Q.......', '...Q.....', '......Q..', 'Q........', '..Q......', '........Q', '.....Q...', '.......Q.', '....Q....'], ['.Q.......', '...Q.....', '.......Q.', '..Q......', '........Q', '.....Q...', 'Q........', '....Q....', '......Q..'], ['.Q.......', '...Q.....', '........Q', '......Q..', '..Q......', 'Q........', '.....Q...', '.......Q.', '....Q....'], ['.Q.......', '...Q.....', '........Q', '......Q..', '....Q....', '..Q......', 'Q........', '.....Q...', '.......Q.'], ['.Q.......', '....Q....', '......Q..', 'Q........', '..Q......', '.......Q.', '.....Q...', '...Q.....', '........Q'], ['.Q.......', '....Q....', '......Q..', '...Q.....', 'Q........', '..Q......', '........Q', '.....Q...', '.......Q.'], ['.Q.......', '....Q....', '......Q..', '........Q', '..Q......', '.....Q...', '...Q.....', 'Q........', '.......Q.'], ['.Q.......', '....Q....', '......Q..', '........Q', '...Q.....', '.......Q.', 'Q........', '..Q......', '.....Q...'], ['.Q.......', '....Q....', '.......Q.', 'Q........', '..Q......', '.....Q...', '........Q', '......Q..', '...Q.....'], ['.Q.......', '....Q....', '.......Q.', 'Q........', '........Q', '.....Q...', '..Q......', '......Q..', '...Q.....'], ['.Q.......', '....Q....', '.......Q.', '.....Q...', '........Q', '..Q......', 'Q........', '...Q.....', '......Q..'], ['.Q.......', '....Q....', '.......Q.', '.....Q...', '........Q', '..Q......', 'Q........', '......Q..', '...Q.....'], ['.Q.......', '....Q....', '........Q', '...Q.....', 'Q........', '.......Q.', '.....Q...', '..Q......', '......Q..'], ['.Q.......', '.....Q...', 'Q........', '..Q......', '......Q..', '........Q', '...Q.....', '.......Q.', '....Q....'], ['.Q.......', '.....Q...', 'Q........', '......Q..', '...Q.....', '.......Q.', '..Q......', '....Q....', '........Q'], ['.Q.......', '.....Q...', 'Q........', '......Q..', '....Q....', '..Q......', '........Q', '...Q.....', '.......Q.'], ['.Q.......', '.....Q...', 'Q........', '........Q', '....Q....', '.......Q.', '...Q.....', '......Q..', '..Q......'], ['.Q.......', '.....Q...', '..Q......', 'Q........', '.......Q.', '...Q.....', '........Q', '......Q..', '....Q....'], ['.Q.......', '.....Q...', '........Q', '..Q......', '....Q....', '.......Q.', '...Q.....', 'Q........', '......Q..'], ['.Q.......', '......Q..', '....Q....', 'Q........', '........Q', '...Q.....', '.....Q...', '.......Q.', '..Q......'], ['.Q.......', '......Q..', '....Q....', '.......Q.', 'Q........', '...Q.....', '.....Q...', '..Q......', '........Q'], ['.Q.......', '......Q..', '........Q', '.....Q...', '..Q......', 'Q........', '...Q.....', '.......Q.', '....Q....'], ['.Q.......', '.......Q.', 'Q........', '...Q.....', '......Q..', '........Q', '.....Q...', '..Q......', '....Q....'], ['.Q.......', '.......Q.', '....Q....', '..Q......', '........Q', '.....Q...', '...Q.....', 'Q........', '......Q..'], ['.Q.......', '.......Q.', '.....Q...', '........Q', '..Q......', 'Q........', '...Q.....', '......Q..', '....Q....'], ['.Q.......', '........Q', '....Q....', '..Q......', '.......Q.', '...Q.....', '......Q..', 'Q........', '.....Q...'], ['.Q.......', '........Q', '.....Q...', '..Q......', '....Q....', '.......Q.', 'Q........', '...Q.....', '......Q..'], ['.Q.......', '........Q', '.....Q...', '..Q......', '......Q..', '...Q.....', 'Q........', '.......Q.', '....Q....'], ['.Q.......', '........Q', '.....Q...', '...Q.....', '......Q..', 'Q........', '..Q......', '....Q....', '.......Q.'], ['..Q......', 'Q........', '...Q.....', '......Q..', '........Q', '.Q.......', '....Q....', '.......Q.', '.....Q...'], ['..Q......', 'Q........', '.....Q...', '.......Q.', '....Q....', '.Q.......', '...Q.....', '........Q', '......Q..'], ['..Q......', 'Q........', '......Q..', '.Q.......', '.......Q.', '.....Q...', '...Q.....', '........Q', '....Q....'], ['..Q......', 'Q........', '......Q..', '....Q....', '.......Q.', '.Q.......', '...Q.....', '.....Q...', '........Q'], ['..Q......', 'Q........', '.......Q.', '...Q.....', '........Q', '......Q..', '....Q....', '.Q.......', '.....Q...'], ['..Q......', 'Q........', '........Q', '......Q..', '....Q....', '.Q.......', '.......Q.', '.....Q...', '...Q.....'], ['..Q......', '....Q....', '.Q.......', '.......Q.', 'Q........', '...Q.....', '......Q..', '........Q', '.....Q...'], ['..Q......', '....Q....', '.Q.......', '.......Q.', 'Q........', '......Q..', '...Q.....', '.....Q...', '........Q'], ['..Q......', '....Q....', '......Q..', 'Q........', '...Q.....', '.Q.......', '.......Q.', '.....Q...', '........Q'], ['..Q......', '....Q....', '.......Q.', '.Q.......', '........Q', '.....Q...', 'Q........', '......Q..', '...Q.....'], ['..Q......', '....Q....', '.......Q.', '.Q.......', '........Q', '......Q..', 'Q........', '...Q.....', '.....Q...'], ['..Q......', '....Q....', '........Q', '.Q.......', '...Q.....', '......Q..', 'Q........', '.......Q.', '.....Q...'], ['..Q......', '....Q....', '........Q', '...Q.....', 'Q........', '......Q..', '.Q.......', '.....Q...', '.......Q.'], ['..Q......', '.....Q...', '.Q.......', '......Q..', 'Q........', '...Q.....', '.......Q.', '....Q....', '........Q'], ['..Q......', '.....Q...', '.Q.......', '........Q', '....Q....', 'Q........', '.......Q.', '...Q.....', '......Q..'], ['..Q......', '.....Q...', '.......Q.', 'Q........', '...Q.....', '......Q..', '....Q....', '.Q.......', '........Q'], ['..Q......', '.....Q...', '.......Q.', 'Q........', '....Q....', '........Q', '.Q.......', '...Q.....', '......Q..'], ['..Q......', '.....Q...', '.......Q.', '.Q.......', '...Q.....', '........Q', '......Q..', '....Q....', 'Q........'], ['..Q......', '.....Q...', '.......Q.', '....Q....', 'Q........', '........Q', '......Q..', '.Q.......', '...Q.....'], ['..Q......', '.....Q...', '.......Q.', '....Q....', '.Q.......', '........Q', '......Q..', '...Q.....', 'Q........'], ['..Q......', '.....Q...', '........Q', 'Q........', '.......Q.', '...Q.....', '.Q.......', '......Q..', '....Q....'], ['..Q......', '.....Q...', '........Q', '.Q.......', '....Q....', '......Q..', '...Q.....', 'Q........', '.......Q.'], ['..Q......', '.....Q...', '........Q', '.Q.......', '.......Q.', 'Q........', '...Q.....', '......Q..', '....Q....'], ['..Q......', '.....Q...', '........Q', '....Q....', '.......Q.', 'Q........', '...Q.....', '.Q.......', '......Q..'], ['..Q......', '.....Q...', '........Q', '......Q..', 'Q........', '...Q.....', '.Q.......', '....Q....', '.......Q.'], ['..Q......', '.....Q...', '........Q', '......Q..', '.Q.......', '...Q.....', '.......Q.', 'Q........', '....Q....'], ['..Q......', '.....Q...', '........Q', '......Q..', '...Q.....', 'Q........', '.......Q.', '.Q.......', '....Q....'], ['..Q......', '......Q..', '.Q.......', '...Q.....', '.......Q.', 'Q........', '....Q....', '........Q', '.....Q...'], ['..Q......', '......Q..', '.Q.......', '.......Q.', '....Q....', '........Q', 'Q........', '.....Q...', '...Q.....'], ['..Q......', '......Q..', '.Q.......', '.......Q.', '.....Q...', '...Q.....', 'Q........', '....Q....', '........Q'], ['..Q......', '......Q..', '...Q.....', '.Q.......', '........Q', '....Q....', 'Q........', '.......Q.', '.....Q...'], ['..Q......', '......Q..', '...Q.....', '.Q.......', '........Q', '.....Q...', 'Q........', '....Q....', '.......Q.'], ['..Q......', '......Q..', '...Q.....', '.......Q.', '....Q....', '........Q', 'Q........', '.....Q...', '.Q.......'], ['..Q......', '......Q..', '........Q', 'Q........', '....Q....', '.Q.......', '.......Q.', '.....Q...', '...Q.....'], ['..Q......', '......Q..', '........Q', '...Q.....', '.Q.......', '....Q....', '.......Q.', '.....Q...', 'Q........'], ['..Q......', '.......Q.', '.Q.......', '...Q.....', '........Q', '......Q..', '....Q....', 'Q........', '.....Q...'], ['..Q......', '.......Q.', '...Q.....', '......Q..', '........Q', '.Q.......', '....Q....', 'Q........', '.....Q...'], ['..Q......', '.......Q.', '.....Q...', 'Q........', '........Q', '.Q.......', '....Q....', '......Q..', '...Q.....'], ['..Q......', '.......Q.', '.....Q...', '...Q.....', '........Q', 'Q........', '....Q....', '......Q..', '.Q.......'], ['..Q......', '.......Q.', '.....Q...', '........Q', '.Q.......', '....Q....', 'Q........', '...Q.....', '......Q..'], ['..Q......', '........Q', '.Q.......', '....Q....', '.......Q.', 'Q........', '......Q..', '...Q.....', '.....Q...'], ['..Q......', '........Q', '...Q.....', 'Q........', '.......Q.', '.....Q...', '.Q.......', '......Q..', '....Q....'], ['..Q......', '........Q', '...Q.....', '.Q.......', '.......Q.', '.....Q...', 'Q........', '......Q..', '....Q....'], ['..Q......', '........Q', '...Q.....', '.......Q.', '....Q....', '.Q.......', '.....Q...', 'Q........', '......Q..'], ['..Q......', '........Q', '.....Q...', '.Q.......', '....Q....', '......Q..', 'Q........', '...Q.....', '.......Q.'], ['..Q......', '........Q', '.....Q...', '...Q.....', 'Q........', '......Q..', '....Q....', '.Q.......', '.......Q.'], ['..Q......', '........Q', '.....Q...', '.......Q.', '.Q.......', '...Q.....', 'Q........', '......Q..', '....Q....'], ['...Q.....', 'Q........', '..Q......', '.....Q...', '........Q', '.Q.......', '.......Q.', '....Q....', '......Q..'], ['...Q.....', 'Q........', '....Q....', '.Q.......', '........Q', '......Q..', '..Q......', '.......Q.', '.....Q...'], ['...Q.....', 'Q........', '....Q....', '.......Q.', '.Q.......', '......Q..', '..Q......', '.....Q...', '........Q'], ['...Q.....', 'Q........', '....Q....', '........Q', '.Q.......', '.....Q...', '.......Q.', '..Q......', '......Q..'], ['...Q.....', 'Q........', '......Q..', '........Q', '.Q.......', '.....Q...', '.......Q.', '..Q......', '....Q....'], ['...Q.....', 'Q........', '........Q', '.....Q...', '..Q......', '......Q..', '.Q.......', '.......Q.', '....Q....'], ['...Q.....', '.Q.......', '....Q....', '.......Q.', 'Q........', '..Q......', '.....Q...', '........Q', '......Q..'], ['...Q.....', '.Q.......', '......Q..', '..Q......', 'Q........', '.......Q.', '....Q....', '........Q', '.....Q...'], ['...Q.....', '.Q.......', '......Q..', '........Q', 'Q........', '....Q....', '.......Q.', '.....Q...', '..Q......'], ['...Q.....', '.Q.......', '......Q..', '........Q', 'Q........', '.......Q.', '....Q....', '..Q......', '.....Q...'], ['...Q.....', '.Q.......', '.......Q.', '..Q......', '........Q', '......Q..', '....Q....', 'Q........', '.....Q...'], ['...Q.....', '.Q.......', '........Q', '..Q......', '.....Q...', '.......Q.', 'Q........', '....Q....', '......Q..'], ['...Q.....', '.Q.......', '........Q', '....Q....', 'Q........', '.......Q.', '.....Q...', '..Q......', '......Q..'], ['...Q.....', '.....Q...', 'Q........', '....Q....', '.Q.......', '.......Q.', '..Q......', '......Q..', '........Q'], ['...Q.....', '.....Q...', 'Q........', '........Q', '....Q....', '.......Q.', '.Q.......', '......Q..', '..Q......'], ['...Q.....', '.....Q...', 'Q........', '........Q', '......Q..', '..Q......', '.......Q.', '.Q.......', '....Q....'], ['...Q.....', '.....Q...', '..Q......', '........Q', '.Q.......', '....Q....', '.......Q.', 'Q........', '......Q..'], ['...Q.....', '.....Q...', '..Q......', '........Q', '.Q.......', '.......Q.', '....Q....', '......Q..', 'Q........'], ['...Q.....', '.....Q...', '..Q......', '........Q', '......Q..', 'Q........', '.......Q.', '.Q.......', '....Q....'], ['...Q.....', '.....Q...', '.......Q.', '.Q.......', '....Q....', 'Q........', '........Q', '......Q..', '..Q......'], ['...Q.....', '.....Q...', '.......Q.', '.Q.......', '....Q....', '......Q..', '........Q', 'Q........', '..Q......'], ['...Q.....', '.....Q...', '.......Q.', '.Q.......', '......Q..', 'Q........', '..Q......', '....Q....', '........Q'], ['...Q.....', '.....Q...', '.......Q.', '..Q......', 'Q........', '......Q..', '....Q....', '.Q.......', '........Q'], ['...Q.....', '.....Q...', '........Q', '..Q......', 'Q........', '.......Q.', '.Q.......', '....Q....', '......Q..'], ['...Q.....', '......Q..', 'Q........', '..Q......', '........Q', '.....Q...', '.......Q.', '....Q....', '.Q.......'], ['...Q.....', '......Q..', 'Q........', '.....Q...', '........Q', '.Q.......', '.......Q.', '....Q....', '..Q......'], ['...Q.....', '......Q..', 'Q........', '.......Q.', '....Q....', '.Q.......', '........Q', '..Q......', '.....Q...'], ['...Q.....', '......Q..', '..Q......', '.....Q...', '........Q', 'Q........', '.......Q.', '....Q....', '.Q.......'], ['...Q.....', '......Q..', '..Q......', '.......Q.', '.Q.......', '....Q....', '........Q', '.....Q...', 'Q........'], ['...Q.....', '......Q..', '..Q......', '.......Q.', '.....Q...', 'Q........', '........Q', '.Q.......', '....Q....'], ['...Q.....', '......Q..', '..Q......', '.......Q.', '.....Q...', '.Q.......', '........Q', '....Q....', 'Q........'], ['...Q.....', '......Q..', '....Q....', '.Q.......', '........Q', 'Q........', '..Q......', '.......Q.', '.....Q...'], ['...Q.....', '......Q..', '....Q....', '.Q.......', '........Q', 'Q........', '.....Q...', '.......Q.', '..Q......'], ['...Q.....', '......Q..', '....Q....', '.Q.......', '........Q', '.....Q...', '.......Q.', '..Q......', 'Q........'], ['...Q.....', '......Q..', '........Q', '.Q.......', '....Q....', '.......Q.', 'Q........', '..Q......', '.....Q...'], ['...Q.....', '......Q..', '........Q', '.Q.......', '.....Q...', 'Q........', '..Q......', '....Q....', '.......Q.'], ['...Q.....', '......Q..', '........Q', '.....Q...', '..Q......', 'Q........', '.......Q.', '....Q....', '.Q.......'], ['...Q.....', '.......Q.', 'Q........', '....Q....', '......Q..', '.Q.......', '.....Q...', '..Q......', '........Q'], ['...Q.....', '.......Q.', '....Q....', '..Q......', 'Q........', '.....Q...', '.Q.......', '........Q', '......Q..'], ['...Q.....', '.......Q.', '....Q....', '..Q......', 'Q........', '......Q..', '.Q.......', '.....Q...', '........Q'], ['...Q.....', '........Q', '..Q......', '.....Q...', '.Q.......', '......Q..', '....Q....', 'Q........', '.......Q.'], ['...Q.....', '........Q', '....Q....', '..Q......', 'Q........', '.....Q...', '.......Q.', '.Q.......', '......Q..'], ['...Q.....', '........Q', '....Q....', '..Q......', 'Q........', '......Q..', '.Q.......', '.......Q.', '.....Q...'], ['...Q.....', '........Q', '....Q....', '.......Q.', 'Q........', '..Q......', '.....Q...', '.Q.......', '......Q..'], ['....Q....', 'Q........', '.....Q...', '...Q.....', '.Q.......', '.......Q.', '..Q......', '........Q', '......Q..'], ['....Q....', 'Q........', '.......Q.', '...Q.....', '.Q.......', '......Q..', '........Q', '.....Q...', '..Q......'], ['....Q....', 'Q........', '.......Q.', '.....Q...', '..Q......', '......Q..', '.Q.......', '...Q.....', '........Q'], ['....Q....', '.Q.......', '...Q.....', 'Q........', '......Q..', '........Q', '..Q......', '.....Q...', '.......Q.'], ['....Q....', '.Q.......', '...Q.....', '........Q', '......Q..', '..Q......', 'Q........', '.....Q...', '.......Q.'], ['....Q....', '.Q.......', '.....Q...', 'Q........', '..Q......', '......Q..', '........Q', '...Q.....', '.......Q.'], ['....Q....', '.Q.......', '.....Q...', '........Q', '..Q......', '.......Q.', '...Q.....', '......Q..', 'Q........'], ['....Q....', '.Q.......', '.....Q...', '........Q', '......Q..', '...Q.....', 'Q........', '..Q......', '.......Q.'], ['....Q....', '.Q.......', '.......Q.', 'Q........', '...Q.....', '......Q..', '........Q', '.....Q...', '..Q......'], ['....Q....', '.Q.......', '.......Q.', 'Q........', '......Q..', '........Q', '..Q......', '.....Q...', '...Q.....'], ['....Q....', '.Q.......', '.......Q.', '..Q......', '......Q..', '...Q.....', 'Q........', '........Q', '.....Q...'], ['....Q....', '.Q.......', '.......Q.', '..Q......', '......Q..', '........Q', 'Q........', '.....Q...', '...Q.....'], ['....Q....', '.Q.......', '........Q', 'Q........', '.....Q...', '.......Q.', '..Q......', '......Q..', '...Q.....'], ['....Q....', '.Q.......', '........Q', '.....Q...', '..Q......', '......Q..', '...Q.....', 'Q........', '.......Q.'], ['....Q....', '..Q......', 'Q........', '.....Q...', '.Q.......', '........Q', '......Q..', '...Q.....', '.......Q.'], ['....Q....', '..Q......', 'Q........', '.....Q...', '.......Q.', '.Q.......', '...Q.....', '......Q..', '........Q'], ['....Q....', '..Q......', 'Q........', '......Q..', '.Q.......', '.......Q.', '.....Q...', '...Q.....', '........Q'], ['....Q....', '..Q......', '.....Q...', '........Q', '.Q.......', '.......Q.', 'Q........', '...Q.....', '......Q..'], ['....Q....', '..Q......', '.....Q...', '........Q', '......Q..', 'Q........', '...Q.....', '.Q.......', '.......Q.'], ['....Q....', '..Q......', '.....Q...', '........Q', '......Q..', '.Q.......', '...Q.....', '.......Q.', 'Q........'], ['....Q....', '..Q......', '.....Q...', '........Q', '......Q..', '...Q.....', 'Q........', '.......Q.', '.Q.......'], ['....Q....', '..Q......', '.......Q.', '...Q.....', '.Q.......', '........Q', '.....Q...', 'Q........', '......Q..'], ['....Q....', '..Q......', '.......Q.', '...Q.....', '......Q..', '........Q', '.Q.......', '.....Q...', 'Q........'], ['....Q....', '..Q......', '.......Q.', '.....Q...', '.Q.......', '........Q', 'Q........', '...Q.....', '......Q..'], ['....Q....', '..Q......', '.......Q.', '.....Q...', '.Q.......', '........Q', '......Q..', 'Q........', '...Q.....'], ['....Q....', '..Q......', '........Q', '...Q.....', '.Q.......', '.......Q.', '.....Q...', 'Q........', '......Q..'], ['....Q....', '..Q......', '........Q', '.....Q...', '.......Q.', '.Q.......', '...Q.....', 'Q........', '......Q..'], ['....Q....', '......Q..', 'Q........', '...Q.....', '.Q.......', '.......Q.', '.....Q...', '........Q', '..Q......'], ['....Q....', '......Q..', 'Q........', '.....Q...', '.......Q.', '.Q.......', '...Q.....', '........Q', '..Q......'], ['....Q....', '......Q..', '.Q.......', '...Q.....', '.......Q.', 'Q........', '..Q......', '........Q', '.....Q...'], ['....Q....', '......Q..', '.Q.......', '...Q.....', '.......Q.', 'Q........', '........Q', '.....Q...', '..Q......'], ['....Q....', '......Q..', '.Q.......', '.....Q...', '..Q......', 'Q........', '.......Q.', '...Q.....', '........Q'], ['....Q....', '......Q..', '.Q.......', '.....Q...', '.......Q.', 'Q........', '...Q.....', '........Q', '..Q......'], ['....Q....', '......Q..', '...Q.....', 'Q........', '..Q......', '.....Q...', '........Q', '.Q.......', '.......Q.'], ['....Q....', '......Q..', '...Q.....', 'Q........', '..Q......', '.......Q.', '.....Q...', '.Q.......', '........Q'], ['....Q....', '......Q..', '...Q.....', 'Q........', '..Q......', '........Q', '.....Q...', '.......Q.', '.Q.......'], ['....Q....', '......Q..', '...Q.....', 'Q........', '.......Q.', '.Q.......', '........Q', '.....Q...', '..Q......'], ['....Q....', '......Q..', '........Q', '..Q......', '.......Q.', '.Q.......', '...Q.....', '.....Q...', 'Q........'], ['....Q....', '......Q..', '........Q', '...Q.....', '.Q.......', '.......Q.', '.....Q...', '..Q......', 'Q........'], ['....Q....', '......Q..', '........Q', '...Q.....', '.......Q.', 'Q........', '..Q......', '.....Q...', '.Q.......'], ['....Q....', '.......Q.', 'Q........', '...Q.....', '......Q..', '..Q......', '.....Q...', '........Q', '.Q.......'], ['....Q....', '.......Q.', 'Q........', '........Q', '...Q.....', '.Q.......', '......Q..', '..Q......', '.....Q...'], ['....Q....', '.......Q.', '.Q.......', '......Q..', '..Q......', 'Q........', '........Q', '...Q.....', '.....Q...'], ['....Q....', '.......Q.', '.Q.......', '......Q..', '..Q......', '.....Q...', '........Q', 'Q........', '...Q.....'], ['....Q....', '.......Q.', '.Q.......', '........Q', '..Q......', 'Q........', '......Q..', '...Q.....', '.....Q...'], ['....Q....', '.......Q.', '.Q.......', '........Q', '.....Q...', '..Q......', 'Q........', '...Q.....', '......Q..'], ['....Q....', '.......Q.', '...Q.....', 'Q........', '..Q......', '.....Q...', '........Q', '......Q..', '.Q.......'], ['....Q....', '.......Q.', '...Q.....', 'Q........', '......Q..', '.Q.......', '.....Q...', '..Q......', '........Q'], ['....Q....', '.......Q.', '...Q.....', '........Q', '......Q..', '..Q......', 'Q........', '.....Q...', '.Q.......'], ['....Q....', '.......Q.', '.....Q...', 'Q........', '..Q......', '......Q..', '........Q', '...Q.....', '.Q.......'], ['....Q....', '.......Q.', '.....Q...', '........Q', '..Q......', 'Q........', '......Q..', '...Q.....', '.Q.......'], ['....Q....', '........Q', '.Q.......', '...Q.....', '......Q..', '..Q......', '.......Q.', '.....Q...', 'Q........'], ['....Q....', '........Q', '.Q.......', '.....Q...', '.......Q.', '..Q......', 'Q........', '...Q.....', '......Q..'], ['....Q....', '........Q', '...Q.....', '.....Q...', '.......Q.', '.Q.......', '......Q..', 'Q........', '..Q......'], ['.....Q...', 'Q........', '....Q....', '.Q.......', '........Q', '......Q..', '...Q.....', '.......Q.', '..Q......'], ['.....Q...', 'Q........', '....Q....', '......Q..', '........Q', '..Q......', '.......Q.', '.Q.......', '...Q.....'], ['.....Q...', 'Q........', '....Q....', '......Q..', '........Q', '...Q.....', '.Q.......', '.......Q.', '..Q......'], ['.....Q...', 'Q........', '......Q..', '...Q.....', '.......Q.', '..Q......', '....Q....', '........Q', '.Q.......'], ['.....Q...', '.Q.......', '....Q....', '......Q..', '........Q', '..Q......', '.......Q.', '...Q.....', 'Q........'], ['.....Q...', '.Q.......', '....Q....', '......Q..', '........Q', '...Q.....', '.......Q.', 'Q........', '..Q......'], ['.....Q...', '.Q.......', '........Q', '....Q....', '..Q......', '.......Q.', '...Q.....', '......Q..', 'Q........'], ['.....Q...', '..Q......', 'Q........', '...Q.....', '......Q..', '........Q', '.Q.......', '....Q....', '.......Q.'], ['.....Q...', '..Q......', 'Q........', '.......Q.', '...Q.....', '........Q', '......Q..', '....Q....', '.Q.......'], ['.....Q...', '..Q......', 'Q........', '.......Q.', '....Q....', '.Q.......', '........Q', '......Q..', '...Q.....'], ['.....Q...', '..Q......', '....Q....', '.......Q.', 'Q........', '...Q.....', '.Q.......', '......Q..', '........Q'], ['.....Q...', '..Q......', '....Q....', '.......Q.', 'Q........', '........Q', '...Q.....', '.Q.......', '......Q..'], ['.....Q...', '..Q......', '....Q....', '.......Q.', 'Q........', '........Q', '......Q..', '.Q.......', '...Q.....'], ['.....Q...', '..Q......', '......Q..', '.Q.......', '...Q.....', '.......Q.', 'Q........', '....Q....', '........Q'], ['.....Q...', '..Q......', '......Q..', '.Q.......', '...Q.....', '........Q', 'Q........', '.......Q.', '....Q....'], ['.....Q...', '..Q......', '......Q..', '.Q.......', '.......Q.', '....Q....', 'Q........', '...Q.....', '........Q'], ['.....Q...', '..Q......', '......Q..', '...Q.....', 'Q........', '........Q', '.Q.......', '....Q....', '.......Q.'], ['.....Q...', '..Q......', '........Q', '.Q.......', '....Q....', '.......Q.', 'Q........', '......Q..', '...Q.....'], ['.....Q...', '..Q......', '........Q', '...Q.....', 'Q........', '.......Q.', '.Q.......', '....Q....', '......Q..'], ['.....Q...', '..Q......', '........Q', '......Q..', 'Q........', '...Q.....', '.Q.......', '....Q....', '.......Q.'], ['.....Q...', '...Q.....', 'Q........', '......Q..', '........Q', '.Q.......', '.......Q.', '....Q....', '..Q......'], ['.....Q...', '...Q.....', '.Q.......', '......Q..', '........Q', '..Q......', '....Q....', '.......Q.', 'Q........'], ['.....Q...', '...Q.....', '.Q.......', '.......Q.', '..Q......', '........Q', '......Q..', '....Q....', 'Q........'], ['.....Q...', '...Q.....', '.Q.......', '.......Q.', '....Q....', '..Q......', 'Q........', '........Q', '......Q..'], ['.....Q...', '...Q.....', '.Q.......', '.......Q.', '....Q....', '........Q', 'Q........', '..Q......', '......Q..'], ['.....Q...', '...Q.....', '......Q..', 'Q........', '..Q......', '........Q', '.Q.......', '.......Q.', '....Q....'], ['.....Q...', '...Q.....', '......Q..', 'Q........', '.......Q.', '.Q.......', '....Q....', '..Q......', '........Q'], ['.....Q...', '...Q.....', '......Q..', 'Q........', '.......Q.', '....Q....', '.Q.......', '........Q', '..Q......'], ['.....Q...', '...Q.....', '........Q', 'Q........', '..Q......', '......Q..', '.Q.......', '.......Q.', '....Q....'], ['.....Q...', '...Q.....', '........Q', 'Q........', '....Q....', '.Q.......', '.......Q.', '..Q......', '......Q..'], ['.....Q...', '...Q.....', '........Q', '....Q....', '.......Q.', '.Q.......', '......Q..', '..Q......', 'Q........'], ['.....Q...', '.......Q.', 'Q........', '....Q....', '........Q', '.Q.......', '...Q.....', '......Q..', '..Q......'], ['.....Q...', '.......Q.', 'Q........', '......Q..', '...Q.....', '.Q.......', '........Q', '....Q....', '..Q......'], ['.....Q...', '.......Q.', '.Q.......', '......Q..', 'Q........', '..Q......', '....Q....', '........Q', '...Q.....'], ['.....Q...', '.......Q.', '..Q......', 'Q........', '........Q', '.Q.......', '....Q....', '......Q..', '...Q.....'], ['.....Q...', '.......Q.', '..Q......', 'Q........', '........Q', '....Q....', '.Q.......', '...Q.....', '......Q..'], ['.....Q...', '.......Q.', '..Q......', '......Q..', '........Q', '.Q.......', '....Q....', 'Q........', '...Q.....'], ['.....Q...', '.......Q.', '....Q....', '.Q.......', '........Q', '......Q..', '...Q.....', 'Q........', '..Q......'], ['.....Q...', '........Q', 'Q........', '...Q.....', '......Q..', '..Q......', '.......Q.', '.Q.......', '....Q....'], ['.....Q...', '........Q', '..Q......', 'Q........', '.......Q.', '...Q.....', '.Q.......', '......Q..', '....Q....'], ['.....Q...', '........Q', '....Q....', 'Q........', '.......Q.', '...Q.....', '.Q.......', '......Q..', '..Q......'], ['.....Q...', '........Q', '....Q....', '.Q.......', '.......Q.', '..Q......', '......Q..', '...Q.....', 'Q........'], ['.....Q...', '........Q', '....Q....', '.......Q.', 'Q........', '..Q......', '......Q..', '.Q.......', '...Q.....'], ['.....Q...', '........Q', '......Q..', '...Q.....', 'Q........', '.......Q.', '.Q.......', '....Q....', '..Q......'], ['......Q..', 'Q........', '...Q.....', '.Q.......', '.......Q.', '.....Q...', '........Q', '..Q......', '....Q....'], ['......Q..', 'Q........', '...Q.....', '.....Q...', '........Q', '..Q......', '....Q....', '.......Q.', '.Q.......'], ['......Q..', 'Q........', '...Q.....', '.......Q.', '....Q....', '..Q......', '........Q', '.....Q...', '.Q.......'], ['......Q..', 'Q........', '.....Q...', '.Q.......', '....Q....', '.......Q.', '...Q.....', '........Q', '..Q......'], ['......Q..', 'Q........', '.....Q...', '.......Q.', '.Q.......', '...Q.....', '........Q', '..Q......', '....Q....'], ['......Q..', 'Q........', '.....Q...', '........Q', '.Q.......', '...Q.....', '.......Q.', '..Q......', '....Q....'], ['......Q..', 'Q........', '.......Q.', '....Q....', '.Q.......', '........Q', '..Q......', '.....Q...', '...Q.....'], ['......Q..', '.Q.......', '...Q.....', 'Q........', '.......Q.', '....Q....', '........Q', '.....Q...', '..Q......'], ['......Q..', '.Q.......', '...Q.....', '.....Q...', 'Q........', '........Q', '....Q....', '..Q......', '.......Q.'], ['......Q..', '.Q.......', '...Q.....', '........Q', 'Q........', '.......Q.', '....Q....', '..Q......', '.....Q...'], ['......Q..', '.Q.......', '.....Q...', '..Q......', 'Q........', '.......Q.', '....Q....', '........Q', '...Q.....'], ['......Q..', '.Q.......', '.......Q.', '.....Q...', 'Q........', '..Q......', '....Q....', '........Q', '...Q.....'], ['......Q..', '..Q......', 'Q........', '.....Q...', '.......Q.', '....Q....', '.Q.......', '...Q.....', '........Q'], ['......Q..', '..Q......', 'Q........', '........Q', '....Q....', '.......Q.', '.Q.......', '...Q.....', '.....Q...'], ['......Q..', '..Q......', '.....Q...', '.Q.......', '....Q....', 'Q........', '........Q', '...Q.....', '.......Q.'], ['......Q..', '..Q......', '.....Q...', '.......Q.', 'Q........', '...Q.....', '........Q', '....Q....', '.Q.......'], ['......Q..', '..Q......', '.....Q...', '.......Q.', 'Q........', '....Q....', '........Q', '.Q.......', '...Q.....'], ['......Q..', '..Q......', '.......Q.', '.Q.......', '...Q.....', '.....Q...', '........Q', '....Q....', 'Q........'], ['......Q..', '..Q......', '.......Q.', '.Q.......', '....Q....', 'Q........', '........Q', '...Q.....', '.....Q...'], ['......Q..', '..Q......', '.......Q.', '.....Q...', '.Q.......', '........Q', '....Q....', 'Q........', '...Q.....'], ['......Q..', '...Q.....', 'Q........', '..Q......', '.....Q...', '........Q', '.Q.......', '.......Q.', '....Q....'], ['......Q..', '...Q.....', 'Q........', '..Q......', '.......Q.', '.....Q...', '.Q.......', '........Q', '....Q....'], ['......Q..', '...Q.....', 'Q........', '..Q......', '........Q', '.....Q...', '.......Q.', '....Q....', '.Q.......'], ['......Q..', '...Q.....', 'Q........', '....Q....', '.Q.......', '........Q', '.....Q...', '.......Q.', '..Q......'], ['......Q..', '...Q.....', 'Q........', '.......Q.', '.Q.......', '........Q', '.....Q...', '..Q......', '....Q....'], ['......Q..', '...Q.....', 'Q........', '.......Q.', '....Q....', '..Q......', '.....Q...', '........Q', '.Q.......'], ['......Q..', '...Q.....', 'Q........', '........Q', '.Q.......', '.....Q...', '.......Q.', '..Q......', '....Q....'], ['......Q..', '...Q.....', '.Q.......', '....Q....', '.......Q.', 'Q........', '..Q......', '.....Q...', '........Q'], ['......Q..', '...Q.....', '.Q.......', '....Q....', '........Q', 'Q........', '..Q......', '.......Q.', '.....Q...'], ['......Q..', '...Q.....', '.Q.......', '.......Q.', '.....Q...', 'Q........', '..Q......', '....Q....', '........Q'], ['......Q..', '...Q.....', '.Q.......', '........Q', '....Q....', 'Q........', '.......Q.', '.....Q...', '..Q......'], ['......Q..', '...Q.....', '.Q.......', '........Q', '.....Q...', '..Q......', '....Q....', '.......Q.', 'Q........'], ['......Q..', '...Q.....', '.......Q.', 'Q........', '....Q....', '........Q', '.Q.......', '.....Q...', '..Q......'], ['......Q..', '...Q.....', '.......Q.', '..Q......', '........Q', '.....Q...', '.Q.......', '....Q....', 'Q........'], ['......Q..', '....Q....', 'Q........', '.....Q...', '........Q', '..Q......', '.......Q.', '...Q.....', '.Q.......'], ['......Q..', '....Q....', 'Q........', '.......Q.', '.....Q...', '..Q......', '........Q', '.Q.......', '...Q.....'], ['......Q..', '....Q....', '.Q.......', '.......Q.', 'Q........', '..Q......', '........Q', '.....Q...', '...Q.....'], ['......Q..', '....Q....', '.Q.......', '.......Q.', 'Q........', '...Q.....', '........Q', '..Q......', '.....Q...'], ['......Q..', '....Q....', '..Q......', '........Q', '.....Q...', '.......Q.', '.Q.......', '...Q.....', 'Q........'], ['......Q..', '....Q....', '.......Q.', '.Q.......', '........Q', '..Q......', '.....Q...', '...Q.....', 'Q........'], ['......Q..', '....Q....', '.......Q.', '.Q.......', '........Q', '.....Q...', '..Q......', 'Q........', '...Q.....'], ['......Q..', '........Q', 'Q........', '..Q......', '....Q....', '.......Q.', '.Q.......', '...Q.....', '.....Q...'], ['......Q..', '........Q', '.Q.......', '.....Q...', 'Q........', '..Q......', '....Q....', '.......Q.', '...Q.....'], ['......Q..', '........Q', '..Q......', '....Q....', '.Q.......', '.......Q.', '.....Q...', '...Q.....', 'Q........'], ['......Q..', '........Q', '..Q......', '.......Q.', '.Q.......', '...Q.....', '.....Q...', 'Q........', '....Q....'], ['......Q..', '........Q', '...Q.....', '.Q.......', '....Q....', '.......Q.', '.....Q...', 'Q........', '..Q......'], ['......Q..', '........Q', '.....Q...', '..Q......', 'Q........', '.......Q.', '....Q....', '.Q.......', '...Q.....'], ['.......Q.', 'Q........', '...Q.....', '.....Q...', '..Q......', '........Q', '......Q..', '....Q....', '.Q.......'], ['.......Q.', 'Q........', '...Q.....', '......Q..', '..Q......', '.....Q...', '........Q', '.Q.......', '....Q....'], ['.......Q.', 'Q........', '...Q.....', '......Q..', '....Q....', '.Q.......', '........Q', '.....Q...', '..Q......'], ['.......Q.', 'Q........', '....Q....', '......Q..', '.Q.......', '.....Q...', '..Q......', '........Q', '...Q.....'], ['.......Q.', '.Q.......', '...Q.....', 'Q........', '......Q..', '........Q', '.....Q...', '..Q......', '....Q....'], ['.......Q.', '.Q.......', '....Q....', '......Q..', 'Q........', '...Q.....', '.....Q...', '........Q', '..Q......'], ['.......Q.', '.Q.......', '........Q', '.....Q...', '..Q......', 'Q........', '...Q.....', '......Q..', '....Q....'], ['.......Q.', '..Q......', 'Q........', '...Q.....', '......Q..', '........Q', '.....Q...', '.Q.......', '....Q....'], ['.......Q.', '..Q......', '....Q....', '.Q.......', '........Q', '.....Q...', '...Q.....', '......Q..', 'Q........'], ['.......Q.', '..Q......', '....Q....', '........Q', 'Q........', '.....Q...', '...Q.....', '.Q.......', '......Q..'], ['.......Q.', '...Q.....', 'Q........', '......Q..', '....Q....', '.Q.......', '.....Q...', '........Q', '..Q......'], ['.......Q.', '...Q.....', '......Q..', '........Q', '.Q.......', '.....Q...', 'Q........', '..Q......', '....Q....'], ['.......Q.', '...Q.....', '........Q', 'Q........', '....Q....', '.Q.......', '.....Q...', '..Q......', '......Q..'], ['.......Q.', '...Q.....', '........Q', '..Q......', '....Q....', '......Q..', 'Q........', '.....Q...', '.Q.......'], ['.......Q.', '...Q.....', '........Q', '..Q......', '.....Q...', '.Q.......', '......Q..', '....Q....', 'Q........'], ['.......Q.', '...Q.....', '........Q', '......Q..', '..Q......', 'Q........', '.....Q...', '.Q.......', '....Q....'], ['.......Q.', '....Q....', 'Q........', '.....Q...', '........Q', '.Q.......', '...Q.....', '......Q..', '..Q......'], ['.......Q.', '....Q....', '.Q.......', '...Q.....', 'Q........', '......Q..', '........Q', '..Q......', '.....Q...'], ['.......Q.', '....Q....', '.Q.......', '...Q.....', 'Q........', '......Q..', '........Q', '.....Q...', '..Q......'], ['.......Q.', '....Q....', '.Q.......', '........Q', 'Q........', '...Q.....', '......Q..', '..Q......', '.....Q...'], ['.......Q.', '....Q....', '.Q.......', '........Q', '......Q..', '...Q.....', 'Q........', '..Q......', '.....Q...'], ['.......Q.', '....Q....', '..Q......', 'Q........', '.....Q...', '.Q.......', '........Q', '......Q..', '...Q.....'], ['.......Q.', '....Q....', '..Q......', 'Q........', '......Q..', '...Q.....', '.....Q...', '........Q', '.Q.......'], ['.......Q.', '....Q....', '..Q......', '.....Q...', '........Q', '......Q..', 'Q........', '...Q.....', '.Q.......'], ['.......Q.', '....Q....', '..Q......', '........Q', '......Q..', '.Q.......', '...Q.....', '.....Q...', 'Q........'], ['.......Q.', '.....Q...', 'Q........', '..Q......', '....Q....', '......Q..', '........Q', '...Q.....', '.Q.......'], ['.......Q.', '.....Q...', 'Q........', '..Q......', '......Q..', '........Q', '...Q.....', '.Q.......', '....Q....'], ['.......Q.', '.....Q...', '.Q.......', '......Q..', 'Q........', '...Q.....', '........Q', '....Q....', '..Q......'], ['.......Q.', '.....Q...', '..Q......', '........Q', '......Q..', 'Q........', '...Q.....', '.Q.......', '....Q....'], ['.......Q.', '.....Q...', '........Q', '..Q......', 'Q........', '...Q.....', '......Q..', '....Q....', '.Q.......'], ['........Q', '.Q.......', '....Q....', '......Q..', 'Q........', '..Q......', '.......Q.', '.....Q...', '...Q.....'], ['........Q', '.Q.......', '....Q....', '......Q..', '...Q.....', 'Q........', '.......Q.', '.....Q...', '..Q......'], ['........Q', '.Q.......', '.....Q...', '.......Q.', '..Q......', 'Q........', '...Q.....', '......Q..', '....Q....'], ['........Q', '..Q......', '....Q....', '.Q.......', '.......Q.', 'Q........', '......Q..', '...Q.....', '.....Q...'], ['........Q', '..Q......', '.....Q...', '.Q.......', '......Q..', 'Q........', '...Q.....', '.......Q.', '....Q....'], ['........Q', '..Q......', '.....Q...', '.Q.......', '......Q..', '....Q....', 'Q........', '.......Q.', '...Q.....'], ['........Q', '..Q......', '.....Q...', '...Q.....', 'Q........', '.......Q.', '....Q....', '......Q..', '.Q.......'], ['........Q', '...Q.....', 'Q........', '....Q....', '.......Q.', '.Q.......', '......Q..', '..Q......', '.....Q...'], ['........Q', '...Q.....', '.Q.......', '....Q....', '.......Q.', '.....Q...', 'Q........', '..Q......', '......Q..'], ['........Q', '...Q.....', '.Q.......', '......Q..', '..Q......', '.....Q...', '.......Q.', 'Q........', '....Q....'], ['........Q', '...Q.....', '.....Q...', '.......Q.', '.Q.......', '......Q..', 'Q........', '..Q......', '....Q....'], ['........Q', '...Q.....', '.....Q...', '.......Q.', '..Q......', 'Q........', '......Q..', '....Q....', '.Q.......'], ['........Q', '...Q.....', '.......Q.', 'Q........', '..Q......', '.....Q...', '.Q.......', '......Q..', '....Q....'], ['........Q', '....Q....', 'Q........', '...Q.....', '.....Q...', '.......Q.', '.Q.......', '......Q..', '..Q......'], ['........Q', '....Q....', 'Q........', '.......Q.', '...Q.....', '.Q.......', '......Q..', '..Q......', '.....Q...'], ['........Q', '....Q....', '..Q......', 'Q........', '.....Q...', '.......Q.', '.Q.......', '...Q.....', '......Q..'], ['........Q', '....Q....', '..Q......', 'Q........', '......Q..', '.Q.......', '.......Q.', '.....Q...', '...Q.....'], ['........Q', '....Q....', '..Q......', '.......Q.', '...Q.....', '......Q..', 'Q........', '.....Q...', '.Q.......'], ['........Q', '....Q....', '.......Q.', '...Q.....', 'Q........', '......Q..', '.Q.......', '.....Q...', '..Q......'], ['........Q', '.....Q...', '.Q.......', '......Q..', 'Q........', '..Q......', '....Q....', '.......Q.', '...Q.....'], ['........Q', '.....Q...', '..Q......', 'Q........', '.......Q.', '....Q....', '.Q.......', '...Q.....', '......Q..'], ['........Q', '.....Q...', '..Q......', '......Q..', '.Q.......', '.......Q.', '....Q....', 'Q........', '...Q.....'], ['........Q', '.....Q...', '...Q.....', '.Q.......', '.......Q.', '....Q....', '......Q..', 'Q........', '..Q......'], ['........Q', '.....Q...', '...Q.....', '......Q..', 'Q........', '.......Q.', '.Q.......', '....Q....', '..Q......'], ['........Q', '.....Q...', '.......Q.', '.Q.......', '...Q.....', 'Q........', '......Q..', '....Q....', '..Q......'], ['........Q', '......Q..', '.Q.......', '...Q.....', 'Q........', '.......Q.', '....Q....', '..Q......', '.....Q...'], ['........Q', '......Q..', '..Q......', '.......Q.', '.Q.......', '....Q....', 'Q........', '.....Q...', '...Q.....'], ['........Q', '......Q..', '...Q.....', '.Q.......', '.......Q.', '.....Q...', 'Q........', '..Q......', '....Q....']]", "def solvenqueens(n):\n\n def dfs(queens, xy_dif, xy_sum):\n p = len(queens)\n if p == n:\n res.append(queens)\n return\n for i in range(n):\n if i not in queens and p - i not in xy_dif and (p + i not in xy_sum):\n dfs(queens + [i], xy_dif + [p - i], xy_sum + [p + i])\n res = []\n dfs([], [], [])\n return [['.' * i + 'Q' + '.' * (n - i - 1) for i in sol] for sol in res]", "def solvenqueens(n):\n\n def dfs(cols, diag_45, diag_135, depth=0):\n row = len(cols)\n if row == n:\n result.append(cols)\n return\n for col in range(n):\n if col not in cols and row - col not in diag_45 and (row + col not in diag_135):\n dfs(cols + [col], diag_45 + [row - col], diag_135 + [row + col], depth + 1)\n else:\n pass\n result = []\n dfs([], [], [])\n return [['.' * i + 'Q' + '.' * (n - i - 1) for i in sol] for sol in result]", "def solvenqueens(n):\n result = []\n visits = [0, 0, 0]\n board = [['.' for j in range(n)] for i in range(n)]\n self.find(visits, n, 0, board, result)\n return result + [[row[::-1] for row in board] for board in result if n & 1 == 0 or (n & 1 == 1 and board[0][n >> 1] != 'Q')]\n\ndef find(visits, n, k, board, result):\n if k >= n:\n result.append([''.join((x for x in row)) for row in board])\n return\n for j in range(n if k > 0 else n + 1 >> 1):\n if self.isInvalid(visits, k, j, n):\n continue\n self.toggleVisit(visits, k, j, n)\n board[k][j] = 'Q'\n self.find(visits, n, k + 1, board, result)\n self.toggleVisit(visits, k, j, n)\n board[k][j] = '.'\n\ndef toggleVisit(visits, i, j, n):\n visits[0] ^= 1 << j\n visits[1] ^= 1 << i - j + n - 1\n visits[2] ^= 1 << i + j\n\ndef isInvalid(visits, i, j, n):\n return visits[0] & 1 << j > 0 or visits[1] & 1 << i - j + n - 1 > 0 or visits[2] & 1 << i + j > 0", "def solvenqueens(n):\n\n def dfs(n, a, b, c, ans, d):\n if n == 0:\n ans = ans.append([i * '.' + 'Q' + (len(a) - i - 1) * '.' for i in d])\n return None\n for i in range(len(a)):\n if a[i] or b[n - 1 + i] or c[len(a) - 1 - i + n - 1]:\n continue\n (a[i], b[n - 1 + i], c[len(a) - 1 - i + n - 1]) = (True, True, True)\n d[n - 1] = i\n dfs(n - 1, a, b, c, ans, d)\n (a[i], b[n - 1 + i], c[len(a) - 1 - i + n - 1]) = (False, False, False)\n return None\n a = [False for i in range(n)]\n b = [False for i in range(n * 2 - 1)]\n c = [False for i in range(n * 2 - 1)]\n d = [0 for i in range(n)]\n ans = []\n dfs(n, a, b, c, ans, d)\n return ans", "def solvenqueens(n):\n row = [x for x in range(n)]\n table = []\n for i in range(n):\n table.append(row.copy())\n result = self.solve(table, 0)\n result_str = []\n for x in result:\n table_str = []\n for y in x:\n table_str.append('.' * y + 'Q' + '.' * (n - y - 1))\n result_str.append(table_str)\n return result_str\n\ndef solve(table, n):\n if table[n] == []:\n return []\n elif n == len(table) - 1:\n table[n] = table[n][0]\n return [table]\n else:\n result = []\n for x in table[n]:\n table1 = [x if type(x) == int else x.copy() for x in table]\n table1[n] = x\n for row in range(n + 1, len(table)):\n if x in table1[row]:\n table1[row].remove(x)\n if x + row - n in table1[row]:\n table1[row].remove(x + row - n)\n if x - (row - n) in table1[row]:\n table1[row].remove(x - (row - n))\n result.extend(self.solve(table1, n + 1))\n return result", "def __init__():\n self.result = []\n self.visited = None\n\ndef solvenqueens(n):\n self.visited = [0 for i in range(n)]\n self.__solve_n_queues(n, 0, [])\n return self.result\n\ndef __not_diagonal(x, y, curr_answer):\n for (c_x, c_y) in enumerate(curr_answer):\n if abs(c_x - x) == abs(c_y - y):\n return False\n return True\n\ndef visualize(curr_answer, n):\n answer = []\n for pos in curr_answer:\n answer.append('.' * pos + 'Q' + '.' * (n - pos - 1))\n return answer\n\ndef __solve_n_queues(n, level, curr_answer):\n if level == n:\n self.result.append(Solution.visualize(curr_answer, n))\n return\n for i in range(n):\n if not self.visited[i] and Solution.__not_diagonal(level, i, curr_answer):\n self.visited[i] = 1\n curr_answer.append(i)\n self.__solve_n_queues(n, level + 1, curr_answer)\n curr_answer.pop()\n self.visited[i] = 0", "def solvenqueens(n):\n queens = []\n res = []\n\n def backtracking(n, k, queens):\n if k > n:\n return\n elif len(queens) == n and k < n:\n return\n elif len(queens) == n and k == n:\n temp = queens[:]\n res.append(temp)\n else:\n row = [0] * n\n temp_q = queens[:]\n for each in temp_q:\n (x, y) = (each[0], each[1])\n row[y] = 1\n if y + k - x < n:\n row[y + k - x] = 1\n if y - k + x >= 0:\n row[y - k + x] = 1\n for i in range(n):\n if row[i] == 0:\n temp_q.append((k, i))\n backtracking(n, k + 1, temp_q)\n temp_q.pop()\n backtracking(n, 0, queens)\n layout = []\n for q in res:\n temp = []\n for each in q:\n _row = '.' * each[1] + 'Q' + '.' * (n - each[1] - 1)\n temp.append(_row)\n layout.append(temp)\n return layout"], "starter_code": "def solvenqueens(n: int) -> List[List[str]]:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Backtracking"], "name": null, "source": "leetcode", "tags": ["Data structures", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://leetcode.com/problems/n-queens/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solvenqueens", "task_id": "TACO_lite/214", "example": [[[4]], ["[['.Q..', '...Q', 'Q...', '..Q.'], ['..Q.', 'Q...', '...Q', '.Q..']]"]]} +{"requirement": "Given a binary array nums, you should delete one element from it.\nReturn the size of the longest non-empty subarray containing only 1's\u00a0in the resulting array.\nReturn 0 if there is no such subarray.\n\u00a0\nExample 1:\nInput: nums = [1,1,0,1]\nOutput: 3\nExplanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.\nExample 2:\nInput: nums = [0,1,1,1,0,1,1,0,1]\nOutput: 5\nExplanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].\nExample 3:\nInput: nums = [1,1,1]\nOutput: 2\nExplanation: You must delete one element.\nExample 4:\nInput: nums = [1,1,0,0,1,1,1,0,1]\nOutput: 4\n\nExample 5:\nInput: nums = [0,0,0]\nOutput: 0\n\n\u00a0\nConstraints:\n\n1 <= nums.length <= 10^5\nnums[i]\u00a0is either\u00a00\u00a0or\u00a01.", "solutions": ["def longestsubarray(nums: List[int]) -> int:\n if not 0 in nums:\n return len(nums) - 1\n ans = 0\n tot = 0\n prev = 0\n for n in nums:\n if n == 1:\n tot += 1\n else:\n ans = max(tot + prev, ans)\n prev = tot\n tot = 0\n return max(prev + tot, ans)", "def longestsubarray(nums: List[int]) -> int:\n z = [0]\n l = []\n a = 0\n c = 0\n for i in range(len(nums)):\n if a == 1 and nums[i] == 0:\n z.append(c)\n c = i - (l[-1] + 1)\n a = 1\n l.append(i)\n elif nums[i] == 0:\n a = a + 1\n l.append(i)\n elif nums[i] == 1:\n c = c + 1\n z.append(c)\n if nums.count(1) == len(nums):\n return len(nums) - 1\n return max(z)", "def longestsubarray(nums: List[int]) -> int:\n (zc, oc) = (0, 0)\n for (i, v) in enumerate(nums):\n if v:\n oc += 1\n else:\n zc += 1\n if oc == len(nums):\n return oc - 1\n elif zc == len(nums):\n return 0\n elif zc == 1:\n return oc\n elif oc == 1:\n return 1\n else:\n l = r = 0\n for (i, v) in enumerate(nums):\n if v == 1:\n l += 1\n else:\n break\n st = i + 1\n po = i\n (maxo, maxi) = (-1, -1)\n while st < len(nums):\n if nums[st] == 1:\n r += 1\n st += 1\n continue\n else:\n v = l + r\n if maxo < v:\n maxo = v\n maxi = po\n po = st\n l = r\n r = 0\n st += 1\n maxo = max(maxo, l + r)\n return maxo", "from collections import deque\n\ndef longestsubarray(nums: List[int]) -> int:\n n = len(nums)\n if n == 0:\n return 0\n elif n == 1:\n return 0 if nums[0] == 0 else 1\n q = deque()\n num_z = 0\n maxx = 0\n is_0 = 0\n for i in range(n):\n if nums[i] == 1:\n q.append(i)\n continue\n is_0 = 1\n if num_z < 1:\n q.append(i)\n num_z += 1\n maxx = max(maxx, len(q) - 1)\n continue\n maxx = max(maxx, len(q) - 1)\n while q and num_z == 1:\n top = q.popleft()\n if nums[top] == 0:\n num_z -= 1\n q.append(i)\n num_z += 1\n if is_0 == 0:\n return n - 1\n maxx = max(len(q) - num_z, maxx)\n return maxx", "def longestsubarray(nums: List[int]) -> int:\n c = 0\n ind = 0\n for i in range(len(nums)):\n if nums[i] == 0:\n j = i + 1\n k = 0\n while j < len(nums) and nums[j] == 1:\n k += 1\n j += 1\n j = i - 1\n while j >= 0 and nums[j] == 1:\n k += 1\n j -= 1\n if k > c:\n c = k\n ind = i\n if ind == 0 and nums[ind] == 1:\n ind = len(nums) - 1\n c = len(nums) - 1\n return c", "def longestsubarray(nums: List[int]) -> int:\n res = zeros = 0\n zero_i = None\n i = 0\n for (j, v) in enumerate(nums):\n if v == 0:\n zeros += 1\n if zeros == 2:\n i = zero_i + 1\n zeros = 1\n zero_i = j\n res = max(res, j - i)\n return res", "def longestsubarray(nums: List[int]) -> int:\n max_length = 0\n count = 0\n for num in nums:\n if num == 1:\n count += 1\n max_length = max(max_length, count)\n else:\n count = 0\n if max_length == len(nums):\n return len(nums) - 1\n elif max_length == 0:\n return 0\n num_left = 0\n num_right = 0\n for (i, num) in enumerate(nums):\n if num == 1:\n num_right += 1\n else:\n max_length = max(max_length, num_left + num_right)\n if i + 1 < len(nums) and nums[i + 1] == 1:\n num_left = num_right\n num_right = 0\n else:\n num_left = 0\n num_right = 0\n max_length = max(max_length, num_left + num_right)\n return max_length", "def longestsubarray(nums: List[int]) -> int:\n (start, end, maxlen, k) = (0, 0, 0, 1)\n while end < len(nums):\n if nums[end] == 0:\n k = k - 1\n if k < 0:\n if nums[start] == 0:\n k += 1\n start = start + 1\n end = end + 1\n continue\n if k >= 0 or nums[end] == 1:\n maxlen = max(maxlen, end - start)\n end = end + 1\n return maxlen", "def longestsubarray(nums: List[int]) -> int:\n longest = 0\n left = 0\n x = 1\n for right in range(len(nums)):\n if not nums[right]:\n x -= 1\n while x < 0:\n if not nums[left]:\n x += 1\n left += 1\n longest = max(longest, right - left + 1)\n return longest - 1", "def longestsubarray(nums: List[int]) -> int:\n noofones = 0\n m = 0\n lastoneslen = 0\n for i in nums:\n if i == 1:\n noofones += 1\n else:\n m = max(m, noofones + lastoneslen)\n lastoneslen = noofones\n noofones = 0\n m = max(m, noofones + lastoneslen)\n if m == len(nums):\n m -= 1\n return m", "def longestsubarray(nums: List[int]) -> int:\n max_count = 0\n start = 0\n zero = 2\n for i in range(len(nums)):\n if nums[i] == 0:\n zero -= 1\n while zero < 1:\n if nums[start] == 0:\n zero += 1\n start += 1\n max_count = max(max_count, i - start)\n return max_count", "def longestsubarray(nums: List[int]) -> int:\n res = []\n count = 0\n for (i, val) in enumerate(nums):\n if val == 0:\n if count > 0:\n res.append(count)\n count = 0\n res.append(0)\n elif val == 1:\n count += 1\n if count > 0:\n res.append(count)\n lenRes = len(res)\n ma = 0\n if lenRes > 2:\n for i in range(1, lenRes - 1):\n ma = max(max(ma, res[i - 1] + res[i + 1]), max(res[i - 1], res[i]), max(res[i + 1], res[i]))\n return ma\n elif lenRes == 1 and res[0] > 0:\n return res[0] - 1\n elif lenRes == 1 and res[0] == 0:\n return ma\n elif lenRes == 2:\n return max(res[0], res[1])", "def longestsubarray(nums: List[int]) -> int:\n zero = -1\n k = 1\n maxi = 0\n count = 0\n i = 0\n while i != len(nums):\n if nums[i] == 0:\n if k == 0:\n i = zero + 1\n zero = i\n maxi = max(count, maxi)\n count = 0\n k = 1\n else:\n k -= 1\n zero = i\n i += 1\n else:\n count += 1\n i += 1\n maxi = max(count, maxi)\n if maxi == len(nums):\n return maxi - 1\n else:\n return maxi", "def longestsubarray(nums: List[int]) -> int:\n start = end = zeros = ones = maxx = 0\n while end < len(nums):\n if nums[end] == 1:\n ones += 1\n elif nums[end] == 0:\n zeros += 1\n while zeros > 1:\n if nums[start] == 0:\n zeros -= 1\n start += 1\n maxx = max(maxx, end - start)\n end += 1\n return maxx", "def longestsubarray(array: List[int]) -> int:\n i = 0\n lenght = 0\n stack = deque()\n zero = False\n while i < len(array):\n if array[i] == 1:\n stack.append(array[i])\n i += 1\n elif zero == False:\n stack.append(array[i])\n zero = True\n i += 1\n else:\n temp = len(stack) - 1\n if temp > lenght:\n lenght = temp\n while stack[0] != 0:\n stack.popleft()\n stack.popleft()\n zero = False\n if len(stack) > lenght:\n lenght = len(stack) - 1\n return lenght", "def longestsubarray(nums: List[int]) -> int:\n left = 0\n right = 0\n zeroes = 1\n res = 0\n while right < len(nums):\n if nums[right] == 0:\n zeroes -= 1\n while zeroes < 0:\n if nums[left] == 0:\n zeroes += 1\n left += 1\n res = max(res, right - left)\n right += 1\n return res", "def longestsubarray(nums: List[int]) -> int:\n (i, j) = (0, 0)\n (ans, cur) = (0, 0)\n while j < len(nums):\n cur += nums[j]\n while i < j and cur < j - i:\n cur -= nums[i]\n i += 1\n ans = max(ans, cur)\n j += 1\n return min(ans, len(nums) - 1)", "def longestsubarray(nums: List[int]) -> int:\n n = len(nums)\n if n == 0:\n return 0\n joined = [0 for i in range(n)]\n left = 0\n right = 0\n for i in range(n):\n joined[i] += left\n joined[n - 1 - i] += right\n if nums[i] == 1:\n left += 1\n else:\n left = 0\n if nums[n - 1 - i] == 1:\n right += 1\n else:\n right = 0\n return max(joined)", "def longestsubarray(nums):\n n = len(nums)\n last_zero = None\n last_one = None\n cnt = 0\n res = 0\n for i in range(n):\n if nums[i] == 1:\n if last_one is None:\n last_one = i\n cnt += 1\n elif last_zero is None:\n last_zero = i\n else:\n last_one = last_zero + 1\n last_zero = i\n cnt = i - last_one\n res = max(res, cnt)\n if res == n:\n return n - 1\n return res", "def longestsubarray(nums: List[int]) -> int:\n mc = 0\n onep = False\n for i in range(len(nums)):\n if nums[i] == 0:\n c = 0\n j = i - 1\n while j >= 0 and nums[j] != 0:\n j -= 1\n c += 1\n j = i + 1\n while j < len(nums) and nums[j] != 0:\n j += 1\n c += 1\n if c > mc:\n mc = c\n else:\n onep = True\n if onep and mc == 0:\n return len(nums) - 1\n elif not onep and mc == 0:\n return 0\n else:\n return mc", "def longestsubarray(nums: List[int]) -> int:\n groups = [[k, len(list(g))] for (k, g) in itertools.groupby(nums)]\n if len(groups) == 1:\n return groups[0][1] - 1 if groups[0][0] else 0\n ans = 0\n for i in range(len(groups)):\n (k, klen) = groups[i]\n if k:\n ans = max(ans, klen)\n elif i not in [0, len(groups) - 1] and klen == 1:\n ans = max(ans, groups[i - 1][1] + groups[i + 1][1])\n return ans", "def longestsubarray(nums: List[int]) -> int:\n (low, high) = (0, 0)\n cn = 0\n ans = 0\n while low < len(nums) and high < len(nums):\n if nums[high] == 0:\n if cn < 1:\n cn += 1\n else:\n while nums[low] != 0:\n low += 1\n low += 1\n high += 1\n ans = max(ans, high - low)\n return max(ans, high - low) - 1", "def longestsubarray(nums: List[int]) -> int:\n if not nums:\n return 0\n if all(nums):\n return len(nums) - 1\n n = len(nums)\n dp = [[0] * 2 for _ in range(n)]\n dp[0][0] = 1 if nums[0] == 1 else 0\n dp[0][1] = 0\n res = 0\n for i in range(1, n):\n if nums[i] == 1:\n dp[i][0] = dp[i - 1][0] + 1\n dp[i][1] = dp[i - 1][1] + 1\n else:\n dp[i][0] = 0\n dp[i][1] = dp[i - 1][0]\n res = max(res, dp[i][1], dp[i][0])\n return res", "def longestsubarray(A):\n if not A:\n return 0\n n = len(A)\n right = 0\n cnt = 0\n res = 0\n for left in range(n):\n while right <= n - 1 and (cnt == 0 or A[right] == 1):\n cnt += A[right] == 0\n right += 1\n res = max(res, right - left)\n cnt -= A[left] == 0\n return res - 1", "def longestsubarray(nums: List[int]) -> int:\n left = []\n total = 0\n for n in nums:\n if n == 0:\n total = 0\n else:\n total += n\n left.append(total)\n right = []\n total = 0\n for i in range(len(nums) - 1, -1, -1):\n if nums[i] == 0:\n total = 0\n else:\n total += nums[i]\n right.append(total)\n right = right[::-1]\n curMax = 0\n for i in range(len(nums) - 2):\n curMax = max(left[i] + right[i + 2], curMax)\n return curMax", "def longestsubarray(nums: List[int]) -> int:\n n = len(nums)\n (l, r) = ([0] * n, [0] * n)\n for i in range(1, n):\n l[i] = l[i - 1] + 1 if nums[i - 1] == 1 else 0\n for i in range(n - 2, -1, -1):\n r[i] = r[i + 1] + 1 if nums[i + 1] == 1 else 0\n ans = max(r[0], l[n - 1])\n for i in range(1, n - 1):\n ans = max(ans, l[i] + r[i])\n return ans", "def longestsubarray(nums: List[int]) -> int:\n k = 1\n i = 0\n for j in range(len(nums)):\n if nums[j] == 0:\n k -= 1\n if k < 0:\n if nums[i] == 0:\n k += 1\n i += 1\n return j - i", "def longestsubarray(nums: List[int]) -> int:\n prevStart = -1\n candidates = []\n if 0 not in nums:\n return len(nums) - 1\n for i in range(len(nums)):\n if nums[i] == 1:\n if prevStart == -1:\n prevStart = i\n continue\n elif prevStart != -1:\n candidates.append([prevStart, i - 1])\n prevStart = -1\n if prevStart != -1:\n candidates.append([prevStart, len(nums) - 1])\n res = [0]\n for i in range(len(candidates)):\n if i == len(candidates) - 1:\n res.append(candidates[i][1] - candidates[i][0] + 1)\n elif candidates[i + 1][0] - candidates[i][1] == 2:\n res.append(candidates[i + 1][1] - candidates[i][0])\n else:\n res.append(candidates[i][1] - candidates[i][0] + 1)\n return max(res)", "def longestsubarray(nums: List[int]) -> int:\n i = 0\n j = 0\n sum = 0\n ans = 0\n for (j, val) in enumerate(nums):\n sum += val\n while i < j and sum < j - i:\n sum -= nums[i]\n i += 1\n ans = max(ans, j - i)\n return ans", "def longestsubarray(nums: List[int]) -> int:\n n = len(nums)\n leftones = [0] * n\n for i in range(n):\n if nums[i] == 0:\n leftones[i] = 0\n else:\n leftones[i] = 1 if i == 0 else leftones[i - 1] + 1\n rightones = [0] * n\n for i in range(n - 1, -1, -1):\n if nums[i] == 0:\n rightones[i] = 0\n else:\n rightones[i] = 1 if i == n - 1 else rightones[i + 1] + 1\n res = 0\n for i in range(1, n - 1):\n res = max(res, leftones[i - 1] + rightones[i + 1])\n return res", "def longestsubarray(nums: List[int]) -> int:\n (prev, curr, best) = (0, 0, 0)\n n = len(nums)\n for (i, x) in enumerate(nums):\n if x == 0:\n best = max(best, prev + curr)\n if i == n - 1:\n pass\n elif nums[i + 1] == 1:\n prev = curr\n curr = 0\n else:\n prev = 0\n curr = 0\n else:\n curr += 1\n best = max(best, prev + curr)\n if best == n:\n best -= 1\n return best", "def longestsubarray(xs: List[int]) -> int:\n n = len(xs)\n if n < 2:\n return 0\n dp = collections.deque()\n best = 0\n for (i, x) in enumerate(xs):\n if x:\n dp.append(i)\n while dp and i - dp[0] - len(dp) + 1 > 1:\n dp.popleft()\n nholes = i - dp[0] - len(dp) + 1 if dp else 1\n this_len = len(dp) - (not dp[0] and (not nholes)) if dp else 0\n best = max(best, this_len)\n return best", "def longestsubarray(nums: List[int]) -> int:\n (prev, _next, n) = ([0 for _ in range(len(nums))], [0 for _ in range(len(nums))], len(nums))\n count = 0\n for i in range(n):\n num = nums[i]\n if i == 0:\n if num:\n count = 1\n elif num:\n prev[i] = count\n count += 1\n else:\n prev[i] = count\n count = 0\n count = 0\n for i in range(n - 1, -1, -1):\n num = nums[i]\n if i == n - 1:\n if num:\n count = 1\n elif num:\n _next[i] = count\n count += 1\n else:\n _next[i] = count\n count = 0\n _max = 0\n for i in range(n):\n num = nums[i]\n _max = max(_max, prev[i] + _next[i])\n return _max", "def longestsubarray(nums: List[int]) -> int:\n if all(nums):\n return len(nums) - 1\n m = pre = l = pl = 0\n for (i, n) in enumerate(nums):\n if n == pre == 1:\n l += 1\n elif n == pre == 0:\n pl = 0\n elif n == 1 != pre:\n l = 1\n else:\n m = max(m, pl + l)\n pl = l\n pre = n\n return max(m, pl + l) if pre == 1 else m", "def get_longest(nums):\n arr = [1 - x for x in nums]\n (l, r) = (0, 0)\n count = 0\n max_length = 0\n while l < len(arr):\n if r == len(arr):\n step = 'l'\n elif l == r:\n step = 'r'\n elif count + arr[r] > 1:\n step = 'l'\n else:\n step = 'r'\n if step == 'l':\n count -= arr[l]\n l += 1\n else:\n count += arr[r]\n r += 1\n max_length = max(max_length, r - l)\n return max(0, max_length - 1)\n\ndef longestsubarray(nums: List[int]) -> int:\n return get_longest(nums)", "def longestsubarray(nums: List[int]) -> int:\n new_array = list()\n current_segment = 0\n for num in nums:\n if num == 0:\n if current_segment > 0:\n new_array.append(current_segment)\n current_segment = 0\n new_array.append(0)\n else:\n current_segment += 1\n if current_segment > 0:\n new_array.append(current_segment)\n max_length = 0\n for idx in range(len(new_array)):\n max_length = max(max_length, new_array[idx])\n if idx > 0 and idx < len(new_array) - 1 and (new_array[idx] == 0):\n if new_array[idx - 1] > 0 and new_array[idx + 1] > 0:\n max_length = max(max_length, new_array[idx - 1] + new_array[idx + 1])\n if max_length == len(nums):\n return max_length - 1\n else:\n return max_length", "def longestsubarray(nums: List[int]) -> int:\n right = [0 for _ in range(len(nums))]\n left = [0 for _ in range(len(nums))]\n for i in range(1, len(nums)):\n if nums[i - 1] == 1:\n left[i] = 1 + left[i - 1]\n res = float('-inf')\n for i in range(len(nums) - 2, -1, -1):\n if nums[i + 1] == 1:\n right[i] = 1 + right[i + 1]\n res = max(res, left[i] + right[i])\n return res", "def longestsubarray(nums: List[int]) -> int:\n se = set(nums)\n if 0 not in se:\n return len(nums) - 1\n elif 1 not in se:\n return 0\n count = 0\n flag = 0\n ls = []\n for i in nums:\n if i == 0:\n if flag == 0:\n count += 1\n else:\n flag = 0\n ls.append(count)\n count = 1\n elif flag == 1:\n count += 1\n else:\n flag = 1\n ls.append(count)\n count = 1\n ls.append(count)\n ind = 0\n ans = 0\n while ind < len(ls):\n if ls[ind] != 0:\n if ls[ind] == 1:\n if ind == 0 and ind < len(ls) - 1:\n ans = max(ans, ls[ind + 1])\n elif ind == len(ls) - 1 and ind > 0:\n ans = max(ans, ls[ind - 1])\n elif ind < len(ls) - 1 and ind > 0:\n ans = max(ans, ls[ind - 1] + ls[ind + 1])\n elif ind == 0 and ind < len(ls) - 1:\n ans = max(ans, ls[ind + 1])\n elif ind == len(ls) - 1 and ind > 0:\n ans = max(ans, ls[ind - 1])\n elif ind < len(ls) - 1 and ind > 0:\n ans = max(ans, max(ls[ind - 1], ls[ind + 1]))\n ind += 2\n return ans", "def longestsubarray(nums: List[int]) -> int:\n var = 0\n count = 0\n max1 = 0\n pos = 0\n flag = 0\n for i in nums:\n if i == 1:\n flag = 1\n if var == 1:\n pos = pos + 1\n count = count + 1\n max1 = max(count, max1)\n elif i == 0 and var == 1:\n count = pos\n pos = 0\n elif flag == 1:\n if var == 0:\n var = var + 1\n else:\n count = pos\n if max1 == len(nums):\n return max1 - 1\n return max1", "def longestsubarray(nums: List[int]) -> int:\n deleted = False\n (max_, cur_cnt, last_cnt) = (0, 0, 0)\n (idx, size) = (0, len(nums))\n while idx < size and nums[idx] == 0:\n idx += 1\n for i in range(idx, size):\n if nums[i] == 1:\n cur_cnt += 1\n max_ = max(max_, cur_cnt)\n else:\n if not deleted:\n deleted = True\n else:\n cur_cnt -= last_cnt\n last_cnt = cur_cnt\n if size == sum(nums):\n return size - 1\n return max_", "def longestsubarray(nums: List[int]) -> int:\n if 1 not in nums:\n return 0\n if 0 not in nums:\n return len(nums) - 1\n new = []\n i = 0\n n = len(nums)\n while i < n:\n if nums[i] == 1:\n cnt = 0\n while i < n and nums[i] == 1:\n cnt += 1\n i += 1\n new.append(cnt)\n else:\n new.append(0)\n i += 1\n mx = max(new)\n for i in range(1, len(new) - 1):\n if new[i] == 0:\n mx = max(mx, new[i - 1] + new[i + 1])\n return mx", "def longestsubarray(nums: List[int]) -> int:\n if len(nums) < 1:\n return 0\n res = 0\n logs = []\n for x in nums:\n if x == 0:\n logs.append(res)\n res = 0\n else:\n res += 1\n logs.append(res)\n if len(logs) == 1:\n return max(0, logs[0] - 1)\n return max([logs[i] + logs[i + 1] for i in range(len(logs) - 1)])", "def longestsubarray(nums: List[int]) -> int:\n if sum(nums) >= len(nums) - 1:\n return len(nums) - 1\n l = 0\n while nums[l] == 0:\n l += 1\n if l == len(nums):\n return 0\n r = l + 1\n sum_total = nums[l]\n res = 0\n for r in range(r, len(nums)):\n sum_total += nums[r]\n if sum_total == r - l - 1:\n res = max(res, sum_total)\n while sum_total < r - l:\n sum_total -= nums[l]\n l += 1\n return max(res, sum_total)", "def longestsubarray(nums: List[int]) -> int:\n if len(nums) < 2:\n return 0\n len1_prev = 0\n len1 = 0\n i = 0\n res = 0\n zc = 0\n while i < len(nums):\n if nums[i] == 1:\n len1 += 1\n else:\n res = max(res, len1 + len1_prev)\n if zc == 0:\n len1_prev = len1\n len1 = 0\n zc = 1\n elif zc == 1:\n if len1 > 0:\n len1_prev = len1\n len1 = 0\n zc = 1\n else:\n len1 = 0\n len1_prev = 0\n zc = 0\n i += 1\n res = max(res, len1 + len1_prev)\n res = min(len(nums) - 1, res)\n return res", "def longestsubarray(nums: List[int]) -> int:\n n = len(nums)\n if sum(nums) == n:\n return n - 1\n dp = [[0 for x in range(len(nums))] for y in range(2)]\n dp[0][0] = 1 if nums[0] == 1 else 0\n for i in range(1, len(nums)):\n if nums[i] == 0:\n dp[0][i] = 0\n dp[1][i] = dp[0][i - 1]\n else:\n dp[0][i] = dp[0][i - 1] + 1\n dp[1][i] = dp[1][i - 1] + 1\n return max([i for x in dp for i in x])", "def longestsubarray(nums: List[int]) -> int:\n max_len = 0\n zero_seen = False\n for i in range(len(nums)):\n length = 0\n if nums[i] == 0:\n zero_seen = True\n (l, r) = (i - 1, i + 1)\n while l >= 0 and nums[l] == 1:\n length += 1\n l -= 1\n while r < len(nums) and nums[r] == 1:\n length += 1\n r += 1\n max_len = max(max_len, length)\n return max_len if zero_seen else len(nums) - 1", "def longestsubarray(a: List[int]) -> int:\n ones = 0\n old_ones = 0\n maxlen = 0\n n = len(a)\n for i in range(n):\n if a[i] == 1:\n ones += 1\n maxlen = max(maxlen, ones + old_ones)\n else:\n old_ones = ones\n ones = 0\n return maxlen if ones < n else n - 1", "def longestsubarray(nums: List[int]) -> int:\n seq = [0]\n prev = 0\n res = 0\n for n in nums:\n if n:\n seq[-1] += 1\n res = max(prev + seq[-1], res)\n else:\n prev = seq[-1]\n seq.append(0)\n if len(seq) == 1:\n res -= 1\n return res", "def longestsubarray(nums: List[int]) -> int:\n (prev, res, curr) = (0, 0, 0)\n for i in range(len(nums)):\n if nums[i] == 1:\n curr += 1\n else:\n if i < len(nums) - 1 and nums[i + 1] != 0:\n prev = curr\n else:\n prev = 0\n curr = 0\n res = max(res, curr + prev)\n if res == len(nums):\n res -= 1\n return res", "import re\nimport numpy as np\n\ndef longestsubarray(nums: List[int]) -> int:\n nums = np.array(nums)\n zeros_ = np.where(nums == 0)[0]\n if zeros_.tolist():\n temp = 0\n for ind in zeros_:\n ind_ = max([ind - 1, 0])\n ind__ = min([ind + 1, len(nums) - 1])\n count_ = 0\n count__ = 0\n if nums[ind_] == 1:\n while ind_ >= 0 and nums[ind_] == 1:\n count_ += 1\n ind_ -= 1\n if nums[ind__] == 1:\n while ind__ < len(nums) and nums[ind__] == 1:\n count__ += 1\n ind__ += 1\n temp = max([count_ + count__, temp])\n return temp\n elif len(zeros_) == len(nums):\n return 0\n else:\n return len(nums) - 1", "def longestsubarray(nums: List[int]) -> int:\n i = 0\n ints = []\n while i < len(nums):\n start = i\n end = i\n while i < len(nums) and nums[i] == 1:\n i += 1\n end += 1\n if start != end:\n ints.append((start, end))\n i += 1\n if len(ints) == 1:\n diff = ints[0][1] - ints[0][0]\n if diff == len(nums):\n return diff - 1\n else:\n return diff\n elif not ints:\n return 0\n max_ones = 0\n for seq in range(len(ints) - 1):\n seq1 = ints[seq]\n seq2 = ints[seq + 1]\n length = None\n if seq2[0] - seq1[1] == 1:\n length = seq1[1] - seq1[0] + (seq2[1] - seq2[0])\n else:\n length = max(seq1[1] - seq1[0], seq2[1] - seq2[0])\n if length > max_ones:\n max_ones = length\n return max_ones", "def longestsubarray(nums: List[int]) -> int:\n n = len(nums)\n prev = 0\n cnt = 0\n pmax = 0\n for i in range(0, n):\n if nums[i] == 1:\n cnt += 1\n else:\n prev = cnt\n cnt = 0\n maxm = prev + cnt\n if maxm > pmax:\n pmax = maxm\n if cnt == n:\n return n - 1\n else:\n return maxm if maxm > pmax else pmax", "def longestsubarray(nums: List[int]) -> int:\n start = 0\n sliding_window_counter = collections.Counter()\n result = 0\n for end in range(len(nums)):\n sliding_window_counter[nums[end]] += 1\n while sliding_window_counter[0] > 1:\n sliding_window_counter[nums[start]] -= 1\n start += 1\n result = max(result, end - start)\n return result", "def longestsubarray(nums: List[int]) -> int:\n l = 0\n r = 0\n zeros = 0\n res = 0\n while r < len(nums):\n if nums[r] == 0:\n zeros += 1\n while zeros > 1:\n if nums[l] == 0:\n zeros -= 1\n l += 1\n res = max(res, r - l)\n r += 1\n return res", "def longestsubarray(nums: List[int]) -> int:\n l = 0\n r = 0\n earliest_one = float('inf')\n earliest_zero = float('inf')\n zeros = 1\n max_len = 0\n while r < len(nums):\n zeros -= nums[r] == 0\n if zeros < 0:\n zeros += nums[l] == 0\n l += 1\n r += 1\n return r - l - 1", "def longestsubarray(nums: List[int]) -> int:\n w_start = 0\n d = {}\n max_len = 0\n case = 0\n for i in range(0, len(nums)):\n c = str(nums[i])\n if c not in d:\n d[c] = 0\n d[c] += 1\n if str(0) in d:\n while d[str(0)] > 1:\n t = str(nums[w_start])\n d[t] -= 1\n w_start += 1\n case = 1\n max_len = max(max_len, i - w_start + 1 - case)\n case = 0\n return max_len - 1", "def longestsubarray(nums: List[int]) -> int:\n prev = 0\n prev_zero = 0\n result = float('-inf')\n boolean = False\n count = 0\n for i in range(len(nums)):\n if nums[i] == 0:\n boolean = True\n count += 1\n if count == 2:\n count -= 1\n prev = prev_zero + 1\n prev_zero = i\n result = max(result, i - prev)\n return result if boolean == True else len(nums) - 1", "def longestsubarray(nums: List[int]) -> int:\n if 0 in nums and 1 in nums:\n longest = 0\n i = nums.index(0)\n while True:\n if 0 in nums[:i][::-1]:\n left_side = nums[:i][::-1].index(0)\n else:\n left_side = len(nums[:i][::-1])\n if 0 in nums[i + 1:]:\n right_side = nums[i + 1:].index(0)\n else:\n right_side = len(nums[i + 1:])\n longest = max(left_side + right_side, longest)\n try:\n i = nums[i + 1:].index(0) + i + 1\n except:\n break\n return longest\n elif sum(nums) == 0:\n return 0\n elif sum(nums) == len(nums):\n return len(nums) - 1", "def longestsubarray(nums: List[int]) -> int:\n arr = []\n count = 0\n for i in range(len(nums)):\n if nums[i] == 1:\n count += 1\n elif nums[i] == 0:\n arr.append(count)\n count = 0\n arr.append(count)\n if len(arr) == 1:\n return arr[0] - 1\n maxi = 0\n for j in range(1, len(arr)):\n maxi = max(maxi, arr[j - 1] + arr[j])\n return maxi", "def longestsubarray(nums: List[int]) -> int:\n if 0 not in nums:\n return len(nums) - 1\n arr = [0]\n (count, flag) = (0, 0)\n for (idx, num) in enumerate(nums):\n if num == 0:\n if flag == 1:\n arr.append(count)\n count = 0\n arr.append(0)\n flag = 0\n elif num == 1:\n count += 1\n flag = 1\n if idx == len(nums) - 1:\n arr.append(count)\n arr.append(0)\n maxSum = 0\n for i in range(1, len(arr) - 1):\n if arr[i] == 0:\n maxSum = max(maxSum, arr[i - 1] + arr[i + 1])\n return maxSum"], "starter_code": "def longestsubarray(nums: List[int]) -> int:\n", "input_output": {"fn_name": "longestSubarray", "inputs": [[[1, 1, 0, 1]]], "outputs": [3]}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Sliding Window", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures", "Amortized analysis"], "skill_types": ["Dynamic programming", "Amortized analysis", "Data structures"], "url": "https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "longestsubarray", "task_id": "TACO_lite/136", "example": [[[[1, 1, 0, 1]], [[0, 1, 1, 1, 0, 1, 1, 0, 1]], [[1, 1, 1]], [[1, 1, 0, 0, 1, 1, 1, 0, 1]], [[0, 0, 0]]], ["3", "5", "2", "4", "0"]]} +{"requirement": "Given a number\u00a0s in their binary representation. Return the number of steps to reduce it to 1 under the following rules:\n\n\nIf the current number is even, you have to divide it by 2.\n\n\nIf the current number is odd, you have to add 1 to it.\n\n\nIt's guaranteed that you can always reach to one for all testcases.\n\u00a0\nExample 1:\nInput: s = \"1101\"\nOutput: 6\nExplanation: \"1101\" corressponds to number 13 in their decimal representation.\nStep 1) 13 is odd, add 1 and obtain 14.\u00a0\nStep 2) 14 is even, divide by 2 and obtain 7.\nStep 3) 7 is odd, add 1 and obtain 8.\nStep 4) 8 is even, divide by 2 and obtain 4.\u00a0 \nStep 5) 4 is even, divide by 2 and obtain 2.\u00a0\nStep 6) 2 is even, divide by 2 and obtain 1.\u00a0 \n\nExample 2:\nInput: s = \"10\"\nOutput: 1\nExplanation: \"10\" corressponds to number 2 in their decimal representation.\nStep 1) 2 is even, divide by 2 and obtain 1.\u00a0 \n\nExample 3:\nInput: s = \"1\"\nOutput: 0\n\n\u00a0\nConstraints:\n\n1 <= s.length\u00a0<= 500\ns consists of characters '0' or '1'\ns[0] == '1'", "solutions": ["def numsteps(s: str) -> int:\n (i, mid_zero) = (0, 0)\n for j in range(1, len(s)):\n if s[j] == '1':\n mid_zero += j - i - 1\n i = j\n if i == 0:\n return len(s) - 1\n return mid_zero + 1 + len(s)"], "starter_code": "def numsteps(s: str) -> int:\n", "input_output": {"fn_name": "numSteps", "inputs": [["\"1101\""]], "outputs": [8]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Bit Manipulation", "String"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Bit manipulation"], "skill_types": ["Bit manipulation"], "url": "https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numsteps", "task_id": "TACO_lite/218", "example": [[["1101"], ["10"], ["1"]], ["6", "1", "0"]]} +{"requirement": "Given two strings a and b. The task is to find if the string 'b' can be obtained by rotating another string 'a' by exactly 2 places.\nExample 1:\nInput:\na = amazon\nb = azonam\nOutput: 1\nExplanation: amazon can be rotated anti\nclockwise by two places, which will make\nit as azonam.\nExample 2:\nInput:\na = geeksforgeeks\nb = geeksgeeksfor\nOutput: 0\nExplanation: If we rotate geeksforgeeks by\ntwo place in any direction , we won't get\ngeeksgeeksfor.\nYour Task:\nThe task is to complete the function isRotated() which takes two strings as input parameters and checks if given strings can be formed by rotations. The function returns true if string 1 can be obtained by rotating string 2 by two places, else it returns false.\nExpected Time Complexity: O(N).\nExpected Auxilary Complexity: O(N).\nChallenge: Try doing it in O(1) space complexity.\nConstraints:\n1 \u2264 length of a, b \u2264 10^{5}", "solutions": ["def isrotated(str1, str2):\n if str1[2:] + str1[:2] == str2 or str1[len(str1) - 2:] + str1[:len(str1) - 2] == str2:\n return 1\n return 0", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return 0\n crt = ''\n acrt = ''\n acrt = str2[len(str2) - 2:] + str2[0:len(str2) - 2]\n crt = str2[2:] + str2[0:2]\n return crt == str1 or acrt == str1", "def isrotated(str1, str2):\n n = len(str1)\n k = len(str2)\n if n != k:\n return False\n if str1[0] == str2[n - 2] and str1[1] == str2[n - 1]:\n for i in range(2, n):\n if str1[i] != str2[i - 2]:\n return False\n elif str1[n - 2] == str2[0] and str1[n - 1] == str2[1]:\n for i in range(2, n):\n if str2[i] != str1[i - 2]:\n return False\n else:\n return False\n return True", "def isrotated(str1, str2):\n n = len(str1)\n k = len(str2)\n if n != k:\n return False\n rotateclock = True\n rotateanticlock = True\n for i in range(n):\n if str1[i] != str2[(i + 2) % n]:\n rotateclock = False\n for i in range(k):\n if str1[(i + 2) % n] != str2[i]:\n rotateanticlock = False\n return rotateclock or rotateanticlock", "def isrotated(str1, str2):\n if str1[2:] + str1[:2] == str2:\n return True\n elif str1[len(str1) - 2:] + str1[:len(str1) - 2] == str2:\n return True\n else:\n return False", "def isrotated(str1, str2):\n s1 = str1[2:] + str1[0:2]\n s2 = str1[-2:] + str1[0:-2]\n if s1 == str2 or s2 == str2:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n st = str2[0:2]\n st1 = str2[2:]\n left_result = st1 + st\n st2 = str2[-2:]\n st3 = str2[:-2]\n right_result = st2 + st3\n if left_result == str1 or right_result == str1:\n return True\n else:\n return False", "def isrotated(str1, str2):\n n = len(str1)\n (clockwise, anticlockwise) = (True, True)\n for i in range(n):\n if str1[i] != str2[(i + 2) % n]:\n clockwise = False\n break\n for i in range(n):\n if str1[(i + 2) % n] != str2[i]:\n anticlockwise = False\n break\n return clockwise or anticlockwise", "def isrotated(str1, str2):\n n = len(str1)\n m = len(str2)\n if n != m:\n return False\n if n < 2:\n return str1 == str2\n clk = ''\n anti_clk = ''\n clk = clk + str1[2:] + str1[0:2]\n anti_clk = anti_clk + str1[n - 2:] + str1[0:n - 2]\n return clk == str2 or anti_clk == str2", "def isrotated(str1, str2):\n if str1[2:] == str2[:-2] and str1[:2] == str2[-2:] or (str1[-2:] == str2[:2] and str1[:-2] == str2[2:]):\n return True\n return False", "def isrotated(str1, str2):\n s1 = str1[2:] + str1[:2]\n s2 = str2[2:] + str2[:2]\n if str1 == s2 or str2 == s1:\n return True\n return False", "def isrotated(str1, str2):\n n = len(str1)\n temp1 = str1[n - 2:] + str1[0:n - 2]\n temp2 = str2[n - 2:] + str2[0:n - 2]\n if temp1 == str2 or temp2 == str1:\n return 1\n return 0", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return 0\n output = 0\n n = len(str1)\n flag1 = True\n flag2 = True\n for i in range(len(str1)):\n if not str1[i] == str2[(i + 2) % n]:\n flag1 = False\n if not str1[i] == str2[(n - 2 + i) % n]:\n flag2 = False\n if flag1 and flag2:\n break\n return 1 if flag1 or flag2 else 0", "def isrotated(str1, str2):\n i = 0\n clk = str2[2:] + str2[0:2]\n antclk = str2[len(str2) - 2] + str2[len(str2) - 1] + str2[0:len(str2) - 2]\n if str1 == clk or str1 == antclk:\n return 1\n return 0", "def isrotated(str1, str2):\n n = len(str1)\n temp1 = str1[n - 2:] + str1[0:n - 2]\n temp2 = str2[n - 2:] + str2[0:n - 2]\n if temp1 == str2 or temp2 == str1:\n return True\n else:\n return False", "def isrotated(str1, str2):\n return str1 == str2[2:] + str2[:2] or str1 == str2[-2:] + str2[:-2]", "def isrotated(str1, str2):\n str4 = str1[-2:] + str1[:-2]\n str3 = str1[2:] + str1[:2]\n if str3 == str2 or str4 == str2:\n return True\n return False", "def isrotated(str1, str2):\n crotate = str1[2:] + str1[0:2]\n acrotate = str1[len(str1) - 2:] + str1[0:len(str1) - 2]\n if str2 == crotate or str2 == acrotate:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n s = str1[0:2]\n k = str1[2:] + s\n if k == str2:\n return 1\n else:\n s = str1[-2:]\n n = len(str1)\n k = s + str1[:n - 2]\n if k == str2:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return False\n left_rotate = str1[2:] + str1[:2]\n right_rotate = str1[-2:] + str1[:-2]\n if str2 == left_rotate or str2 == right_rotate:\n return True\n return False", "def isrotated(str1, str2):\n k = str1[2:] + str1[:2]\n q = str1[::-1]\n w = q[2:] + q[:2]\n w = w[::-1]\n if k == str2:\n return 1\n elif w == str2:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return False\n s1 = str1[:2]\n s2 = str1[2:]\n s3 = s2 + s1\n s4 = str1[len(str1) - 2:] + str1[0:len(str1) - 2]\n if str2 in s3 or str2 in s4:\n return True\n return False", "def isrotated(str1, str2):\n ans1 = str1[2:len(str1)]\n ans1 = ans1 + str1[0:2]\n ans2 = str1[-2:len(str1)]\n ans2 = ans2 + str1[0:-2]\n if ans1 == str2:\n return True\n elif ans2 == str2:\n return True\n else:\n return False", "def isrotated(str1, str2):\n a = str1[2:len(str1)]\n a = a + str1[0:2]\n b = str1[-2:len(str1)]\n b = b + str1[0:-2]\n if str2 == a:\n return True\n elif str2 == b:\n return True\n return False", "def isrotated(str1, str2):\n d = 2\n l = len(str1)\n ls = str1[d:l] + str1[0:d]\n rs = str1[l - d:l] + str1[0:l - d]\n if ls == str2 or rs == str2:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n str3 = str1[2:] + str1[:2]\n str4 = str2[2:] + str2[:2]\n if str3 == str2 or str1 == str4:\n return 1\n else:\n return 0", "def isrotated(a, b):\n if a[2:] + a[:2] == b or a[-2:] + a[:-2] == b:\n return 1\n return 0", "def isrotated(str1, str2):\n s1 = str1[2:] + str1[0:2]\n s2 = str1[len(str1) - 2:] + str1[0:len(str1) - 2]\n if s1 == str2 or s2 == str2:\n return True\n else:\n return False", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return 0\n sanyam = str1[2:] + str1[0:2]\n sanyam1 = str2[2:] + str2[0:2]\n if sanyam == str2 or sanyam1 == str1:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n n = len(str1)\n if str1[:2] == str2[-2:] and str1[2:] == str2[:-2]:\n return 1\n elif str2[:2] == str1[-2:] and str2[2:] == str1[:-2]:\n return 1\n return 0", "def isrotated(s1, s2):\n if len(s1) != len(s2):\n return False\n left_rotated = s1[2:] + s1[:2]\n right_rotated = s1[-2:] + s1[:-2]\n return s2 in (left_rotated, right_rotated)", "def isrotated(str1, str2):\n sub1 = str1[2:] + str1[:2]\n sub2 = str1[-2:] + str1[:-2]\n if sub1 == str2 or sub2 == str2:\n return True\n else:\n return False", "def isrotated(str1, str2):\n clock = str1[2:] + str1[0:2]\n anti = str1[len(str1) - 2:] + str1[0:len(str1) - 2]\n if str2 == clock or str2 == anti:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n y = str1[:2]\n z = str1[2:]\n p = str1[len(str1) - 2:]\n q = str1[:len(str1) - 2]\n if p + q == str2 or q + p == str2:\n return True\n elif y + z == str2 or z + y == str2:\n return True\n else:\n return False", "def isrotated(str1, str2):\n if str1[2:] + str1[:2] == str2:\n return 1\n elif str1[-2:] + str1[:-2] == str2:\n return 1\n return 0", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return False\n if len(str1) < 3:\n return str1 == str2\n left_rot = str1[2:] + str1[:2]\n right_rot = str1[-2:] + str1[:-2]\n return str2 == left_rot or str2 == right_rot", "def isrotated(str1, str2):\n str11 = str1[2:] + str1[:2]\n str12 = str1[-2:] + str1[:-2]\n if str11 == str2 or str12 == str2:\n return 1\n else:\n return 0", "def isrotated(s1, s2):\n if s1[2:] + s1[:2] == s2:\n return 1\n if s1[-2:] + s1[:-2] == s2:\n return 1\n return 0", "def isrotated(str1, str2):\n l1 = str1[0:2]\n l2 = str1[2:]\n r1 = str1[0:-2]\n r2 = str1[-2:]\n if l2 + l1 == str2 or r2 + r1 == str2:\n return 1\n return 0", "def isrotated(str1, str2):\n (cwise, acwise) = (True, True)\n n = len(str1)\n for i in range(n):\n if str1[i] != str2[(i + 2) % n]:\n cwise = False\n for i in range(n):\n if str1[(i + 2) % n] != str2[i]:\n acwise = False\n return cwise or acwise", "def isrotated(str1, str2):\n a = str1[2:len(str1)] + str1[0:2]\n b = str1[len(str1) - 2:len(str1)] + str1[0:len(str1) - 2]\n if a == str2 or b == str2:\n return True\n else:\n return False", "def isrotated(str1, str2):\n anticlock_string = str2[-2:] + str2[0:-2]\n clock_string = str2[2:] + str2[:2]\n if anticlock_string == str1 or clock_string == str1:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n n = len(str1)\n aclock = str1[2:] + str1[0:2]\n clock = str1[-2:] + str1[0:-2]\n if aclock == str2 or clock == str2:\n return 1\n else:\n return 0", "def isrotated(str1, str2):\n k = list(str1)\n k.append(k.pop(0))\n k.append(k.pop(0))\n k = ''.join(k)\n n = list(str1)\n n.insert(0, n.pop(-1))\n n.insert(0, n.pop(-1))\n n = ''.join(n)\n if k == str2 or n == str2:\n return True\n return False", "def isrotated(str1, str2):\n str1_1 = str1[2:] + str1[:2]\n if str1_1 == str2:\n return 1\n str2_1 = str2[2:] + str2[:2]\n if str1 == str2_1:\n return 1\n return 0", "def isrotated(str1, str2):\n anti_str1 = str1[-2:] + str1[:-2]\n clock_str1 = str1[2:] + str1[:2]\n return anti_str1 == str2 or clock_str1 == str2", "def isrotated(str1, str2):\n i = 0\n while i < len(str1):\n if str1[i] != str2[(i + 2) % len(str2)]:\n break\n i += 1\n if i == len(str2):\n return True\n i = 0\n while i < 2:\n if str1[i] != str2[i + len(str1) - 2]:\n break\n i += 1\n if i != 2:\n return False\n while i < len(str1):\n if str1[i] != str2[i - 2]:\n break\n i += 1\n if i == len(str2):\n return True\n return False", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return 0\n if len(str1) <= 2:\n return 0\n p = list(str1)\n a = p[0]\n b = p[1]\n for i in range(2, len(p)):\n p[i - 2] = p[i]\n p[-2] = a\n p[-1] = b\n k = ''.join(p)\n q = list(str1)\n c = q[-2]\n d = q[-1]\n for i in range(len(q) - 1, 1, -1):\n q[i] = q[i - 2]\n q[0] = c\n q[1] = d\n g = ''\n g = ''.join(q)\n if k == str2 or g == str2:\n return 1\n return 0", "def isrotated(str1, str2):\n if len(str1) != len(str2):\n return False\n if len(str1) < 2:\n return False\n x = len(str1)\n return str1[2:] + str1[:2] == str2 or str1[-2] + str1[-1] + str1[:x - 2] == str2", "def isrotated(str1, str2):\n n1 = len(str1)\n n2 = len(str2)\n if n1 != n2:\n return 0\n else:\n sc = str1[2:] + str1[:2]\n sac = str1[n1 - 2:] + str1[:n1 - 2]\n return 1 if sc == str2 or sac == str2 else 0", "def isrotated(str1, str2):\n n = len(str1)\n return len(str1) == len(str2) and (str1[2:n] + str1[0:2] == str2[:] or str1[n - 2:n] + str1[0:n - 2] == str2[:])", "def isrotated(str1, str2):\n n = len(str1)\n m = len(str2)\n if n != m:\n return False\n if n < 2:\n return str1 == str2\n a_str = str1[2:] + str1[0:2]\n aa_str = str1[n - 2:] + str1[0:n - 2]\n return a_str == str2 or aa_str == str2", "def isrotated(str1, str2):\n if str1 == str2:\n return 1\n elif len(str1) != len(str2):\n return 0\n n1 = len(str1)\n k = n1\n c1 = str1\n ac2 = str1\n temp1 = c1[:2]\n c1 = c1[2:] + temp1\n temp2 = ac2[n1 - 2:n1]\n ac2 = temp2 + ac2[:n1 - 2]\n if c1 == str2 or ac2 == str2:\n return 1\n return 0", "def isrotated(a, b):\n if len(a) != len(b):\n return False\n clockwise = a[-2:] + a[:-2]\n anticlockwise = a[2:] + a[:2]\n if clockwise == b or anticlockwise == b:\n return True\n else:\n return False", "def isrotated(str1, str2):\n N = len(str1)\n A = str1 + str1\n if str2 in A:\n if A.index(str2) == 2 or A.index(str2) == N - 2:\n return True\n return False"], "starter_code": "def isrotated(str1,str2):\n", "input_output": {"inputs": ["a = amazon\nb = azonam", "a = geeksforgeeks\nb = geeksgeeksfor"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/check-if-string-is-rotated-by-two-places-1587115620/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "isrotated", "task_id": "TACO_lite/259", "example": [[], []]} +{"requirement": "Given a Binary Tree having positive and negative nodes. Find the maximum sum of a level in the given Binary Tree.\nExample 1:\nInput : \n 4\n / \\\n 2 -5\n / \\ / \\\n -1 3 -2 6\nOutput: 6\nExplanation :\nSum of all nodes of 0'th level is 4\nSum of all nodes of 1'th level is -3\nSum of all nodes of 2'th level is 6\nHence maximum sum is 6\nExample 2:\nInput : \n 1\n / \\\n 2 3\n / \\ \\\n 4 5 8\n / \\\n 6 7 \nOutput : 17\nExplanation: Maximum sum is at level 2.\nYour Task: \nYou dont need to read input or print anything. Complete the function maxLevelSum() which takes root node as input parameter and returns the maximum sum of any horizontal level in the given Binary Tree.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 \u2264 N \u2264 10^{4}", "solutions": ["def maxLevelSum(root):\n q = [root]\n res = 0\n while q:\n l = len(q)\n tmp = 0\n for i in range(l):\n p = q.pop(0)\n tmp += p.data\n if p.left:\n q.append(p.left)\n if p.right:\n q.append(p.right)\n if res == 0 and tmp < 0:\n res = tmp\n else:\n res = max(res, tmp)\n return res", "def slove(root, lvl, d):\n if root is None:\n return\n if lvl not in d:\n d[lvl] = root.data\n else:\n d[lvl] += root.data\n slove(root.left, lvl + 1, d)\n slove(root.right, lvl + 1, d)\n\ndef maxLevelSum(root):\n d = {}\n slove(root, 0, d)\n return max(d.values())", "def maxLevelSum(root):\n queue = deque()\n queue.append(root)\n max_sum = -9999\n while queue:\n size = len(queue)\n local_sum = 0\n for _ in range(size):\n curr = queue.popleft()\n local_sum += curr.data\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n max_sum = max(max_sum, local_sum)\n return max_sum", "def maxLevelSum(root):\n if not root:\n return 0\n queue = [[root]]\n ans = root.data\n while queue:\n level = queue.pop(0)\n temp = []\n for node in level:\n if node.left:\n temp.append(node.left)\n if node.right:\n temp.append(node.right)\n if temp:\n queue.append(temp)\n ans = max(ans, sum([node.data for node in temp]))\n return ans", "import queue\n\ndef maxLevelSum(root):\n maxsum = float('-inf')\n if not root:\n return maxsum\n q = queue.Queue()\n q.put(root)\n while q.qsize():\n sum = 0\n for i in range(q.qsize()):\n node = q.get()\n sum += node.data\n if node.left:\n q.put(node.left)\n if node.right:\n q.put(node.right)\n maxsum = max(maxsum, sum)\n return maxsum", "def maxLevelSum(root):\n s1 = [root]\n s2 = []\n ans = -12345678\n while s1 != []:\n a = 0\n for i in s1:\n a = a + i.data\n ans = max(ans, a)\n for j in s1:\n if j.left != None:\n s2.append(j.left)\n if j.right != None:\n s2.append(j.right)\n s1 = s2\n s2 = []\n return ans", "from collections import deque\n\ndef maxLevelSum(root):\n maximum = -100000\n dQ = deque()\n dQ.append(root)\n while dQ:\n calculate = 0\n times = len(dQ)\n for i in range(times):\n holdnode = dQ.popleft()\n calculate += holdnode.data\n if holdnode.left != None:\n dQ.append(holdnode.left)\n if holdnode.right != None:\n dQ.append(holdnode.right)\n maximum = max(maximum, calculate)\n return maximum", "def maxLevelSum(root):\n l = [root, 'a']\n max1 = -2 ** 31\n while True:\n w = l.pop(0)\n s = 0\n while w != 'a':\n if w.left != None:\n l.append(w.left)\n if w.right != None:\n l.append(w.right)\n s += w.data\n w = l.pop(0)\n max1 = max(max1, s)\n if l == []:\n return max1\n l.append('a')", "def maxLevelSum(root):\n q = []\n level = []\n ans = -10000\n q.append(root)\n while q != [] and root is not None:\n l = []\n for node in q:\n l.append(node.data)\n if node.left:\n level.append(node.left)\n if node.right:\n level.append(node.right)\n s = sum(l)\n ans = max(ans, s)\n q = level\n level = []\n return ans", "def maxLevelSum(root):\n hs = {}\n\n def fun(root, level):\n if root == None:\n return\n if level not in hs:\n hs[level] = root.data\n else:\n hs[level] += root.data\n fun(root.left, level + 1)\n fun(root.right, level + 1)\n fun(root, 0)\n return max(hs.values())", "import sys\nfrom queue import Queue\n\ndef maxLevelSum(root):\n maxSum = -sys.maxsize\n if root is None:\n return 0\n q = Queue()\n q.put(root)\n while not q.empty():\n sum = 0\n l = q.qsize()\n for i in range(l):\n if q.queue[0].left is not None:\n q.put(q.queue[0].left)\n if q.queue[0].right is not None:\n q.put(q.queue[0].right)\n sum += q.get().data\n maxSum = max(sum, maxSum)\n return maxSum", "def maxLevelSum(root):\n su = -10 ** 28\n l = [root]\n if root != None:\n su = root.data\n while l:\n r = []\n s = 0\n for i in l:\n if i.left:\n r.append(i.left)\n s += i.left.data\n if i.right:\n r.append(i.right)\n s += i.right.data\n if r == []:\n return su\n if s > su:\n su = s\n l = r\n return su", "def fun(root, level, res):\n if root == None:\n return\n if level >= len(res):\n res.append([])\n res[level].append(root.data)\n self.fun(root.left, level + 1, res)\n self.fun(root.right, level + 1, res)\n\ndef maxLevelSum(root):\n res = []\n self.fun(root, 0, res)\n s = sum(res[0])\n for i in res:\n s = max(s, sum(i))\n return s", "def maxLevelSum(root):\n levels = self.getLevelOrderNodes(root)\n levelSums = []\n for level in levels:\n levelSums.append(sum(levels[level]))\n return max(levelSums)\n\ndef getLevelOrderNodes(root):\n levels = dict()\n self.levelOrder(root, 0, levels)\n return levels\n\ndef levelOrder(curr, currHeight, levels):\n if not curr:\n return\n if currHeight not in levels:\n levels[currHeight] = [curr.data]\n else:\n levels[currHeight].append(curr.data)\n self.levelOrder(curr.left, currHeight + 1, levels)\n self.levelOrder(curr.right, currHeight + 1, levels)", "from collections import deque\n\ndef maxLevelSum(root):\n q = deque()\n level = 0\n q.appendleft(root)\n res = -9999999999\n while q:\n n = len(q)\n level += 1\n total = 0\n while n > 0:\n n -= 1\n node = q.pop()\n total += node.data\n if node.left:\n q.appendleft(node.left)\n if node.right:\n q.appendleft(node.right)\n res = max(res, total)\n return res", "def maxLevelSum(root):\n maxans = -1000000\n q = [root]\n while q:\n levelsum = 0\n for i in range(0, len(q)):\n temp = q.pop(0)\n levelsum += temp.data\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n maxans = max(maxans, levelsum)\n return maxans", "from collections import deque\n\ndef maxLevelSum(root):\n d = {}\n\n def leve(root, h):\n if not root:\n return\n if h not in d:\n d[h] = root.data\n else:\n d[h] += root.data\n leve(root.left, h + 1)\n leve(root.right, h + 1)\n leve(root, 0)\n return max(d.values())", "import collections\nimport sys\n\ndef maxLevelSum(root):\n q = collections.deque()\n q.append(root)\n mx = -sys.maxsize\n while q:\n qLen = len(q)\n sm = 0\n for i in range(qLen):\n cur = q.popleft()\n if cur.left:\n q.append(cur.left)\n if cur.right:\n q.append(cur.right)\n sm += cur.data\n mx = max(mx, sm)\n return mx", "def maxLevelSum(root):\n l = []\n q = []\n k = [0]\n m = -1\n q.append(root)\n while q:\n z = q.pop(0)\n x = k.pop(0)\n if m != x:\n m = x\n l.append([])\n l[-1].append(z.data)\n if z.left is not None:\n q.append(z.left)\n k.append(x + 1)\n if z.right is not None:\n q.append(z.right)\n k.append(x + 1)\n s = sum(l[0])\n for x in l:\n if s < sum(x):\n s = sum(x)\n return s", "def maxLevelSum(root):\n queue = [root]\n max_sum = float('-inf')\n while len(queue):\n n = len(queue)\n temp = 0\n while n > 0:\n node = queue.pop(0)\n temp += node.data\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n n = n - 1\n max_sum = max(max_sum, temp)\n return max_sum", "from collections import deque as d\n\ndef maxLevelSum(root):\n l = d()\n b = root\n l.appendleft(root)\n l.appendleft(' ')\n r = -10 ** 9\n lp = []\n while l:\n a = l.pop()\n if a == ' ':\n if sum(lp) > r and lp:\n r = sum(lp)\n lp = []\n if l:\n l.appendleft(' ')\n else:\n if a.left:\n l.appendleft(a.left)\n lp.append(a.left.data)\n if a.right:\n l.appendleft(a.right)\n lp.append(a.right.data)\n if root.data > r:\n return root.data\n return r", "def maxLevelSum(root):\n ans = -1000000\n queue = [root]\n level = []\n while queue != [] and root is not None:\n l = []\n for node in queue:\n l.append(node.data)\n if node.left:\n level.append(node.left)\n if node.right:\n level.append(node.right)\n s1 = sum(l)\n ans = max(ans, s1)\n queue = level\n level = []\n return ans", "def maxLevelSum(root):\n dir = {}\n\n def maxlevel(root, dir, level):\n if not root:\n return\n if dir.get(level):\n dir[level] = dir.get(level) + root.data\n else:\n dir[level] = root.data\n maxlevel(root.left, dir, level + 1)\n maxlevel(root.right, dir, level + 1)\n maxx = -1111111\n maxlevel(root, dir, 0)\n for k in dir:\n maxx = max(maxx, dir.get(k))\n return maxx", "def maxLevelSum(root):\n q = [root]\n maxx = -11111111111111111111111111111111111111111111111111111111111111111111111111111111111\n while q:\n list = []\n for i in q:\n list.append(i.data)\n maxx = max(maxx, sum(list))\n for _ in range(len(q)):\n node = q.pop(0)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return maxx", "def maxLevelSum(root):\n bfs = []\n if not root:\n return 0\n queue = deque([])\n queue.append(root)\n while queue:\n size = len(queue)\n currsum = 0\n for i in range(size):\n curritem = queue.popleft()\n currsum += curritem.data\n if curritem.left is not None:\n queue.append(curritem.left)\n if curritem.right is not None:\n queue.append(curritem.right)\n bfs.append(currsum)\n return max(bfs)", "def maxLevelSum(root):\n q = deque([root])\n ans = [root.data]\n while q:\n level = []\n for i in range(len(q)):\n curr = q.popleft()\n if curr.left:\n q.append(curr.left)\n level.append(curr.left.data)\n if curr.right:\n q.append(curr.right)\n level.append(curr.right.data)\n ans.append(sum(level))\n ans.pop()\n return max(ans)", "def maxLevelSum(root):\n if root is None:\n return 0\n q = []\n q.append(root)\n ans = root.data\n while len(q) > 0:\n t = []\n temp_ans = 0\n while len(q) != 0:\n x = q.pop(0)\n temp_ans += x.data\n if x.left is not None:\n t.append(x.left)\n if x.right is not None:\n t.append(x.right)\n if temp_ans > ans:\n ans = temp_ans\n q = t\n return ans", "def maxLevelSum(root):\n if not root:\n return 0\n q = [root]\n m = root.data\n while q:\n children = []\n vals = []\n while q:\n val = q.pop(0)\n if val.left:\n children.append(val.left)\n vals.append(val.left.data)\n if val.right:\n children.append(val.right)\n vals.append(val.right.data)\n if vals:\n m = max(m, sum(vals))\n q = children\n return m", "def maxLevelSum(root):\n if root == None:\n return 0\n q = []\n q.append(root)\n mx = -999999\n while len(q) > 0:\n n = len(q)\n ans = 0\n for i in range(n):\n temp = q.pop(0)\n ans += temp.data\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n mx = max(ans, mx)\n return mx", "def maxLevelSum(root):\n s = []\n queue = [root]\n while queue != []:\n t = []\n for i in range(len(queue)):\n curr = queue[0]\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n t.append(curr.data)\n queue.pop(0)\n s.append(sum(t))\n return max(s)", "def maxLevelSum(root):\n\n def height(node):\n if node is None:\n return 0\n else:\n lheight = height(node.left)\n rheight = height(node.right)\n if lheight > rheight:\n return lheight + 1\n else:\n return rheight + 1\n\n def currlvl(root, lvl):\n if root is None:\n return\n elif lvl == 1:\n res.append(root.data)\n elif lvl > 1:\n currlvl(root.left, lvl - 1)\n currlvl(root.right, lvl - 1)\n res = []\n l = []\n h = height(root)\n for i in range(1, h + 1):\n currlvl(root, i)\n s = sum(res)\n l.append(s)\n res.clear()\n return max(l)", "def maxLevelSum(root):\n p = []\n q = []\n g = {}\n p.append(0)\n q.append(root)\n while len(q) > 0:\n a = p.pop(0)\n b = q.pop(0)\n if a not in g:\n g[a] = [b.data]\n else:\n g[a].append(b.data)\n if b.left != None:\n p.append(a + 1)\n q.append(b.left)\n if b.right != None:\n p.append(a + 1)\n q.append(b.right)\n ans = []\n for x in g:\n ans.append(sum(g[x]))\n return max(ans)", "def maxLevelSum(root):\n q = []\n maxx = -999999\n q.append(root)\n while q:\n n = len(q)\n ans = 0\n while n > 0:\n p = q.pop(0)\n ans += p.data\n if p.left:\n q.append(p.left)\n if p.right:\n q.append(p.right)\n n -= 1\n if maxx < ans:\n maxx = ans\n return maxx", "def maxLevelSum(root):\n if root != None:\n q = deque()\n q.append(root)\n count = 0\n ans = root.data\n while len(q) > 0:\n count = len(q)\n total = 0\n while count > 0:\n num = q.popleft()\n total += num.data\n if not num.left is None:\n q.append(num.left)\n if not num.right is None:\n q.append(num.right)\n count -= 1\n ans = max(ans, total)\n return ans", "def maxLevelSum(root):\n q = []\n q.append(root)\n x = -9999\n while len(q):\n s = 0\n for i in range(len(q)):\n temp = q.pop(0)\n s = s + temp.data\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n x = max(x, s)\n return x", "def maxLevelSum(root):\n q = [root]\n ans = root.data\n while len(q) != 0:\n sum = 0\n for i in range(len(q)):\n root = q.pop(0)\n sum += root.data\n if root.left:\n q.append(root.left)\n if root.right:\n q.append(root.right)\n ans = max(ans, sum)\n return ans", "def maxLevelSum(root):\n sum_dict = {}\n q = []\n q.append((root, 0))\n while len(q) != 0:\n tt = q.pop(0)\n if tt[1] not in sum_dict:\n sum_dict[tt[1]] = 0\n sum_dict[tt[1]] += tt[0].data\n if tt[0].left != None:\n q.append((tt[0].left, tt[1] + 1))\n if tt[0].right != None:\n q.append((tt[0].right, tt[1] + 1))\n return max(list(sum_dict.values()))", "import collections\n\ndef maxLevelSum(root):\n maxLevel = -float('inf')\n q = collections.deque([root])\n while q:\n s = 0\n for i in range(len(q)):\n node = q.popleft()\n s += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n maxLevel = max(maxLevel, s)\n return maxLevel", "def maxLevelSum(root):\n if root == None:\n return\n q = [root]\n s = 0\n l = []\n while q:\n le = len(q)\n s = 0\n for i in range(le):\n t = q.pop(0)\n if t:\n s = s + t.data\n q.append(t.left)\n q.append(t.right)\n l.append(s)\n m = max(l)\n if m == 0:\n l.remove(0)\n return max(l)", "r = 0\n\ndef maxLevelSum(root):\n global r\n r = -1000000000000000000\n return self.reverseLevelOrder(root)\n\ndef reverseLevelOrder(root):\n global r\n A = []\n B = []\n C = []\n D = []\n if root is None:\n return A\n A.append(root)\n while len(A) > 0:\n while len(A) > 0:\n node = A.pop(0)\n B.append(node.data)\n if node.left is not None:\n D.append(node.left)\n if node.right is not None:\n D.append(node.right)\n A.extend(D)\n D = []\n w = sum(B)\n if w > r:\n r = w\n B = []\n return r", "def maxLevelSum(root):\n if not root:\n return\n nodes = [root]\n maxSum = float('-inf')\n while nodes:\n l = len(nodes)\n sumEl = 0\n for i in range(l):\n cur = nodes.pop(0)\n sumEl += cur.data\n if cur.left:\n nodes.append(cur.left)\n if cur.right:\n nodes.append(cur.right)\n maxSum = max(maxSum, sumEl)\n return maxSum", "def maxLevelSum(root):\n q = []\n q.append(root)\n mini = -1000000000.0\n while len(q):\n count = len(q)\n s = 0\n while count > 0:\n p = q.pop(0)\n s += p.data\n if p.left:\n q.append(p.left)\n if p.right:\n q.append(p.right)\n count -= 1\n if mini < s:\n mini = s\n return mini", "def maxLevelSum(root):\n\n def traversal(root):\n if root == None:\n return None\n hd = 0\n q = [[root, hd]]\n dict1 = dict()\n while q != []:\n node = q.pop(0)\n if node[-1] not in dict1:\n dict1[node[-1]] = node[0].data\n else:\n dict1[node[-1]] += node[0].data\n hd = node[-1]\n if node[0].left:\n q.append([node[0].left, hd + 1])\n if node[0].right:\n q.append([node[0].right, hd + 1])\n return max(dict1.values())\n return traversal(root)", "import math\n\ndef maxLevelSum(root):\n ans = dict()\n self.rec(root, 1, ans)\n max_sum = -21321321322321\n for (key, val) in ans.items():\n max_sum = max(max_sum, val)\n return max_sum\n\ndef rec(root, level, ans):\n if root == None:\n return\n if level not in ans:\n ans[level] = 0\n ans[level] += root.data\n self.rec(root.left, level + 1, ans)\n self.rec(root.right, level + 1, ans)", "def maxLevelSum(root):\n d = {}\n st = []\n st.append([root, 1])\n while st:\n (tamp, dep) = st.pop(0)\n if dep in d.keys():\n d[dep] = d[dep] + tamp.data\n else:\n d[dep] = tamp.data\n if tamp.left:\n st.append([tamp.left, dep + 1])\n if tamp.right:\n st.append([tamp.right, dep + 1])\n return max(d.values())", "def maxLevelSum(root):\n sums = []\n\n def dfs(node, lvl):\n if lvl == len(sums):\n sums.append(node.data)\n else:\n sums[lvl] += node.data\n if node.left:\n dfs(node.left, lvl + 1)\n if node.right:\n dfs(node.right, lvl + 1)\n dfs(root, 0)\n return max(sums)", "def maxLevelSum(root):\n q = []\n q.append(root)\n q.append('$')\n max = root.data\n sum = 0\n while len(q) > 0:\n t = q.pop(0)\n if t == '$':\n if len(q) > 0:\n q.append('$')\n if sum >= max:\n max = sum\n sum = 0\n else:\n if t.left is not None:\n q.append(t.left)\n sum += t.left.data\n if t.right is not None:\n q.append(t.right)\n sum += t.right.data\n return max", "from collections import Counter\n\ndef maxLevelSum(root):\n c = Counter()\n self.myFunc(root, c, 0)\n return c.most_common()[0][1]\n\ndef myFunc(root, c, level):\n if not root:\n return\n level += 1\n c[level] += root.data\n self.myFunc(root.left, c, level)\n self.myFunc(root.right, c, level)\n return", "def __init__():\n self.level = {}\n\ndef trav(root, l):\n if l in self.level:\n self.level[l].append(root.data)\n else:\n self.level[l] = [root.data]\n if root.left != None:\n self.trav(root.left, l + 1)\n if root.right != None:\n self.trav(root.right, l + 1)\n\ndef maxLevelSum(root):\n self.trav(root, 0)\n flag = True\n maxS = 0\n for l in self.level.keys():\n s = sum(self.level[l])\n if flag or maxS < s:\n flag = False\n maxS = s\n return maxS", "import collections\n\ndef maxLevelSum(root):\n q = collections.deque([root])\n ans = float('-inf')\n while q:\n sz = len(q)\n s = 0\n for _ in range(sz):\n n = q.popleft()\n s += n.data\n if n.left:\n q.append(n.left)\n if n.right:\n q.append(n.right)\n ans = max(ans, s)\n return ans", "def maxLevelSum(root):\n from collections import deque\n queue = deque([root])\n Max = float('-inf')\n while queue:\n f = lvl = 0\n for _ in range(len(queue)):\n node = queue.popleft()\n if node:\n f = 1\n lvl += node.data\n queue.append(node.left)\n queue.append(node.right)\n if f:\n Max = max(Max, lvl)\n return Max", "def maxLevelSum(root):\n d = {}\n l = []\n level = 1\n self.helper(root, level, d)\n for i in d:\n l.append(sum(d[i]))\n return max(l)\n\ndef helper(root, level, d):\n if root:\n if root == 'N':\n return\n else:\n if level not in d:\n d[level] = [root.data]\n else:\n d[level].append(root.data)\n self.helper(root.left, level + 1, d)\n self.helper(root.right, level + 1, d)", "import collections\n\ndef maxLevelSum(root):\n q = collections.deque()\n max_sum = root.data\n q.append(root)\n while len(q) > 0:\n levelSum = 0\n n = len(q)\n for i in range(n):\n currNode = q.popleft()\n levelSum += currNode.data\n if currNode.left:\n q.append(currNode.left)\n if currNode.right:\n q.append(currNode.right)\n max_sum = max(max_sum, levelSum)\n return max_sum", "from collections import deque\n\ndef maxLevelSum1(root):\n if root == None:\n return 0\n result = root.data\n q = deque()\n q.append(root)\n while len(q) > 0:\n count = len(q)\n sum = 0\n while count > 0:\n temp = q.popleft()\n sum = sum + temp.data\n if temp.left != None:\n q.append(temp.left)\n if temp.right != None:\n q.append(temp.right)\n count -= 1\n result = max(sum, result)\n return result\n\ndef maxLevelSum(root):\n return maxLevelSum1(root)", "def maxLevelSum(root):\n return max(self.helper(root))\n\ndef helper(root, level=0, levels_sum=None):\n if not root:\n return 0\n if not levels_sum:\n levels_sum = []\n if level == len(levels_sum):\n levels_sum.append(0)\n levels_sum[level] += root.data\n self.helper(root.left, level + 1, levels_sum)\n self.helper(root.right, level + 1, levels_sum)\n return levels_sum", "def maxLevelSum(root):\n if root is None:\n return 0\n freq = {}\n self.traversal(root, freq, 0)\n maximum = freq[0]\n for level in freq.keys():\n maximum = max(maximum, freq[level])\n return maximum\n\ndef traversal(root, freq, level):\n if root is None:\n return\n if level in freq.keys():\n freq[level] += root.data\n else:\n freq[level] = root.data\n self.traversal(root.left, freq, level + 1)\n self.traversal(root.right, freq, level + 1)", "def maxLevelSum(root):\n\n def helper(root, mp, k):\n if root:\n if k in mp:\n mp[k] += root.data\n else:\n mp[k] = root.data\n helper(root.left, mp, k + 1)\n helper(root.right, mp, k + 1)\n mp = {}\n helper(root, mp, 0)\n return max(mp.values())", "def getTree(root, arr, d):\n if not root:\n return\n arr.append([root.data, d])\n self.getTree(root.right, arr, d + 1)\n self.getTree(root.left, arr, d + 1)\n\ndef maxLevelSum(root):\n arr = []\n self.getTree(root, arr, 0)\n d = arr[len(arr) - 1][1]\n maxx = -1000000000\n for i in range(0, d + 1):\n summ = 0\n for e in arr:\n if i == e[1]:\n summ = summ + e[0]\n if summ > maxx:\n maxx = summ\n return maxx", "def maxLevelSum(root):\n\n def helper(root):\n ans = -99999\n q = deque()\n t = 0\n if not root:\n return ans\n q.append(root)\n while q:\n for i in range(len(q)):\n a = q.popleft()\n if a.left:\n q.append(a.left)\n if a.right:\n q.append(a.right)\n t += a.data\n ans = max(ans, t)\n t = 0\n return ans\n if not root:\n return 0\n return helper(root)", "def maxLevelSum(root):\n q = []\n maxi = -100000000000\n if root is None:\n return 0\n q.append(root)\n while len(q) > 0:\n nc = len(q)\n level = [0] * nc\n for i in range(nc):\n node = q.pop(0)\n if node.left is not None:\n q.append(node.left)\n if node.right is not None:\n q.append(node.right)\n level[i] = node.data\n maxi = max(maxi, sum(level))\n return maxi", "def maxLevelSum(root):\n\n def helper(root):\n ans = -9999999\n q = []\n t = 0\n if not root:\n return x\n q.append(root)\n while q:\n for i in range(len(q)):\n a = q.pop(0)\n if a.left:\n q.append(a.left)\n if a.right:\n q.append(a.right)\n t += a.data\n ans = max(t, ans)\n t = 0\n return ans\n return helper(root)", "def maxLevelSum(root):\n\n def helper(x):\n q = []\n t = []\n ans = -9999\n q.append(x)\n while q:\n l = len(q)\n for i in range(l):\n a = q.pop(0)\n if a.left:\n q.append(a.left)\n if a.right:\n q.append(a.right)\n t.append(a.data)\n ans = max(ans, sum(t))\n t = []\n return ans\n a = helper(root)\n return a", "def maxLevelSum(root):\n maxlevel = -float('inf')\n q = [root]\n while q:\n temp = []\n tsum = 0\n for i in q:\n tsum += i.data\n if i.left:\n temp.append(i.left)\n if i.right:\n temp.append(i.right)\n maxlevel = max(maxlevel, tsum)\n q = temp\n return maxlevel", "import collections\nfrom collections import deque\n\ndef maxLevelSum(root):\n res = float('-inf')\n q = collections.deque()\n q.append(root)\n while q:\n ql = len(q)\n l = []\n for i in range(ql):\n x = q.popleft()\n if x:\n l.append(x.data)\n q.append(x.left)\n q.append(x.right)\n if l:\n res = max(res, sum(l))\n return res", "def maxLevelSum(root):\n global a, m\n a = []\n m = -1\n\n def S(root, level):\n global a, m\n if not root:\n return 0\n if level > m:\n a.append([])\n m = level\n a[level].append(root.data)\n S(root.left, level + 1)\n S(root.right, level + 1)\n S(root, 0)\n k = []\n for i in a:\n k.append(sum(i))\n return max(k)", "import sys\n\ndef maxLevelSum(root):\n max_sum = -sys.maxsize\n q = [root]\n while q:\n size = len(q)\n summ = 0\n for _ in range(size):\n node = q.pop(0)\n summ += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n if summ > max_sum:\n max_sum = summ\n return max_sum", "def maxLevelSum(root):\n if root is None:\n return 0\n result = root.data\n q = []\n q.append(root)\n while q != []:\n c = len(q)\n res = 0\n while c != 0:\n c -= 1\n temp = q[0]\n q.pop(0)\n res = res + temp.data\n if temp.left is not None:\n q.append(temp.left)\n if temp.right is not None:\n q.append(temp.right)\n result = max(res, result)\n return result\n height = self.getHight(root)\n i = 1\n maxsum = 0\n while i <= height:\n tempsum = self.levelOrderTravesal(root, i, 0)\n if tempsum > maxsum:\n maxsum = tempsum\n i += 1\n return maxsum\n\ndef levelOrderTravesal(root, level, sumlevel):\n if root is None:\n return sumlevel\n if level == 1:\n sumlevel += root.data\n elif level > 1:\n sumlevel += self.levelOrderTravesal(root.left, level - 1, sumlevel)\n sumlevel += self.levelOrderTravesal(root.right, level - 1, sumlevel)\n return sumlevel\n\ndef getHight(root):\n if root is None:\n return 0\n leftHight = 1 + self.getHight(root.left)\n rightheight = 1 + self.getHight(root.right)\n return max(leftHight, rightheight)", "def maxLevelSum(root):\n if not root:\n return False\n ans = []\n res = []\n q = deque([root])\n while q:\n level = []\n for _ in range(len(q)):\n node = q.popleft()\n level.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n ans.append(level)\n for a in ans:\n res.append(sum(a))\n return max(res)", "from collections import deque\n\ndef maxLevelSum(root):\n if root is None:\n return 0\n q = deque()\n Sum = 0\n Max = -99999999999999\n q.append(root)\n while q:\n n = len(q)\n Sum = 0\n for i in range(n):\n node = q.popleft()\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n Sum = Sum + node.data\n if Sum > Max:\n Max = Sum\n return Max", "from math import inf\nfrom collections import deque\n\ndef maxLevelSum(root):\n max_sum = -inf\n q = deque([root])\n while q:\n lvl_sum = 0\n for _ in range(len(q)):\n node = q.popleft()\n lvl_sum += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n max_sum = max(max_sum, lvl_sum)\n return max_sum", "def maxLevelSum(root):\n q = []\n l = []\n q.append(root)\n n = 0\n while q:\n j = 0\n for i in range(len(q)):\n node = q.pop(0)\n j += node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n l.append(j)\n return max(l)", "def maxLevelSum(root):\n res = -10 ** 5\n queue = [root]\n while queue:\n s = 0\n length = len(queue)\n while length > 0:\n node = queue.pop(0)\n s += node.data\n if node.left != None:\n queue.append(node.left)\n if node.right != None:\n queue.append(node.right)\n length -= 1\n if s > res:\n res = s\n return res", "def maxLevelSum(root):\n if root is None:\n return []\n l = deque([root])\n l2 = []\n while len(l) > 0:\n l1 = []\n y = len(l)\n for i in range(y):\n x = l.popleft()\n if x.left:\n l.append(x.left)\n if x.right:\n l.append(x.right)\n l1.append(x.data)\n l2.append(sum(l1))\n return max(l2)", "def maxLevelSum(root):\n if root == None:\n return 0\n ans = root.data\n q = deque()\n q.append(root)\n while len(q) > 0:\n count = len(q)\n summ = 0\n while count > 0:\n temp = q.popleft()\n summ = summ + temp.data\n if temp.left != None:\n q.append(temp.left)\n if temp.right != None:\n q.append(temp.right)\n count -= 1\n ans = max(summ, ans)\n return ans", "from queue import Queue\n\ndef maxLevelSum(root):\n maxans = float('-inf')\n q = [root]\n while q:\n levelsum = 0\n for i in range(len(q)):\n temp = q.pop(0)\n levelsum += temp.data\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n maxans = max(maxans, levelsum)\n return maxans", "def maxLevelSum(root):\n ans = float('-inf')\n q = [root]\n while len(q) > 0:\n l = [i.data for i in q]\n ans = max(ans, sum(l))\n count = len(q)\n for i in range(count):\n temp = q.pop(0)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n return ans", "def maxLevelSum(root):\n level = []\n q = []\n q.append(root)\n while len(q):\n t = len(q)\n temp = []\n while t > 0:\n t -= 1\n s = q.pop(0)\n if s.right:\n q.append(s.right)\n if s.left:\n q.append(s.left)\n temp.append(s.data)\n level.append(sum(temp))\n return max(level)", "def maxLevelSum(root):\n maxs = float('-inf')\n q = [root]\n while q:\n level = 0\n flag = 0\n l = len(q)\n for i in range(l):\n node = q.pop(0)\n if node:\n flag = 1\n level += node.data\n q.append(node.left)\n q.append(node.right)\n if flag:\n maxs = max(level, maxs)\n return maxs", "from collections import deque\n\ndef maxLevelSum(root):\n ans = -10 ** 9\n if root is None:\n return ans\n queue = deque()\n queue.append(root)\n while len(queue):\n temp = 0\n for i in range(len(queue)):\n node = queue.popleft()\n temp += node.data\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n ans = max(ans, temp)\n return ans", "from collections import deque\n\ndef maxLevelSum(root):\n\n def solve(root):\n if root is None:\n return\n Q = deque()\n Q.appendleft(root)\n maxi = float('-inf')\n while Q:\n sz = len(Q)\n sum = 0\n for _ in range(sz):\n node = Q.pop()\n sum += node.data\n if node.left:\n Q.appendleft(node.left)\n if node.right:\n Q.appendleft(node.right)\n maxi = max(maxi, sum)\n return maxi\n return solve(root)", "def maxLevelSum(root):\n q = [[root, 0]]\n s = {}\n c = 0\n while c != len(q):\n t = q[c][0]\n g = q[c][1]\n if g in s:\n s[g] += t.data\n else:\n s[g] = t.data\n if t.left:\n q.append([t.left, g + 1])\n if t.right:\n q.append([t.right, g + 1])\n c += 1\n m = -9999999999\n for i in s:\n if s[i] > m:\n m = s[i]\n return m", "import sys\nfrom collections import defaultdict as dd\n\ndef maxLevelSum(root):\n d = dd(list)\n D = {}\n\n def x(root, lvl):\n if root is None:\n return\n d[lvl] += [root.data]\n return x(root.left, lvl + 1) or x(root.right, lvl + 1)\n x(root, 0)\n mx = -sys.maxsize\n for (k, v) in d.items():\n D[k] = sum(v)\n return max(list(D.values()))\n\ndef maxLevelSum_(root):\n if root is None:\n return root\n q = [root]\n mx = -sys.maxsize\n while q:\n sm = 0\n for i in range(len(q)):\n curr = q.pop(0)\n sm = sm + curr.data\n if curr.left:\n q.append(curr.left)\n if curr.right:\n q.append(curr.right)\n mx = max(mx, sm)\n return mx", "import sys\n\ndef maxLevelSum(root):\n if root is None:\n return root\n q = [root]\n mx = -sys.maxsize\n while q:\n sm = 0\n for i in range(len(q)):\n curr = q.pop(0)\n sm = sm + curr.data\n if curr.left:\n q.append(curr.left)\n if curr.right:\n q.append(curr.right)\n mx = max(mx, sm)\n return mx", "def __init__(value):\n self.left = None\n self.data = value\n self.right = None\n\ndef maxLevelSum(root):\n if root is None:\n return None\n else:\n ans = []\n import collections\n q = collections.deque()\n q.append(root)\n while q:\n count = 0\n for i in range(len(q)):\n node = q.popleft()\n if node:\n count = count + node.data\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n ans.append(count)\n return max(ans)", "def maxLevelSum(root):\n q = []\n res = []\n q.append(root)\n while q:\n count = len(q)\n ans = []\n while count:\n temp = q.pop(0)\n ans.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n count -= 1\n res.append(ans)\n maxi = -99999999\n for i in res:\n maxi = max(maxi, sum(i))\n return maxi", "def maxLevelSum(root):\n q = []\n q.append(root)\n ans = -9999999\n while len(q) != 0:\n size = len(q)\n temp = 0\n while size > 0:\n x = q.pop(0)\n temp += x.data\n if x.left != None:\n q.append(x.left)\n if x.right != None:\n q.append(x.right)\n size -= 1\n ans = max(ans, temp)\n return ans"], "starter_code": "def __init__(value):\n", "input_output": {"inputs": ["4\n / \\\n 2 -5\n / \\ / \\\n -1 3 -2 6", "1\n / \\\n 2 3\n / \\ \\\n 4 5 8\n / \\\n 6 7"], "outputs": ["6", "17"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/max-level-sum-in-binary-tree/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "__init__", "task_id": "TACO_lite/205", "example": [[[4, [2, -5], [-1, 3, -2, 6]], [1, [2, 3], [4, 5, null, 8], [null, null, 6, 7]]], ["6", "17"]]} +{"requirement": "Write a function \n\n`titleToNumber(title) or title_to_number(title) or titleToNb title ...`\n\n(depending on the language)\n\nthat given a column title as it appears in an Excel sheet, returns its corresponding column number. All column titles will be uppercase.\n\nExamples:\n```\ntitleTonumber('A') === 1\ntitleTonumber('Z') === 26\ntitleTonumber('AA') === 27\n```", "solutions": ["def title_to_number(title):\n ret = 0\n for i in title:\n ret = ret * 26 + ord(i) - 64\n return ret", "def title_to_number(title):\n return sum(((ord(c) - 64) * 26 ** i for (i, c) in enumerate(title[::-1])))", "def title_to_number(title):\n offset = ord('A') - 1\n radix = 26\n val = 0\n for i in title:\n val = radix * val + (ord(i) - offset)\n return val", "from string import ascii_uppercase\n\ndef title_to_number(t):\n return 0 if len(t) == 0 else (ascii_uppercase.index(t[0]) + 1) * 26 ** (len(t) - 1) + title_to_number(t[1:])", "from string import ascii_uppercase\nfrom functools import reduce\nval = {c: i + 1 for (i, c) in enumerate(ascii_uppercase)}\nadd = lambda x, y: 26 * x + y\n\ndef title_to_number(title):\n return reduce(add, map(val.get, title))", "from string import ascii_uppercase as letters\n\ndef title_to_number(title):\n transfer = list(title)[::-1]\n result = 0\n for (i, char) in enumerate(transfer):\n result += (letters.find(char) + 1) * 26 ** i\n return result", "title_to_number = lambda a: 0 if a == '' else 1 + ord(a[-1]) - ord('A') + 26 * title_to_number(a[:-1])", "from string import ascii_uppercase as a\n\ndef title_to_number(title):\n return sum(((a.index(x) + 1) * 26 ** i for (i, x) in enumerate(title[::-1])))"], "starter_code": "def title_to_number(title):\n", "input_output": {"fn_name": "title_to_number", "inputs": [["A"], ["Z"], ["AA"], ["AZ"], ["BA"], ["CODEWARS"], ["ZZZTOP"], ["OYAJI"], ["LONELINESS"], ["UNFORGIVABLE"]], "outputs": [[1], [26], [27], [52], [53], [28779382963], [321268054], [7294985], [68400586976949], [79089429845931757]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/55ee3ebff71e82a30000006a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "title_to_number", "task_id": "TACO_lite/265", "example": [[["A"], ["Z"], ["AA"]], ["1", "26", "27"]]} +{"requirement": "Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second.\n\nFor instance, take the strings \"fatigue\" and \"tiguefa\". In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned.\nIf the second string isn't a valid rotation of the first string, the method returns -1. \n\nExamples:\n```\n\"coffee\", \"eecoff\" => 2\n\"eecoff\", \"coffee\" => 4\n\"moose\", \"Moose\" => -1\n\"isn't\", \"'tisn\" => 2\n\"Esham\", \"Esham\" => 0\n\"dog\", \"god\" => -1\n```\n\nFor Swift, your function should return an Int?. So rather than returning -1 when the second string isn't a valid rotation of the first, return nil.", "solutions": ["def shifted_diff(first, second):\n return (second + second).find(first) if len(first) == len(second) else -1", "def shifted_diff(first, second):\n for i in range(len(first)):\n if first == second[i:] + second[:i]:\n return i\n return -1", "def shifted_diff(f, s):\n try:\n ix = s.index(f[0])\n return ix if f == s[ix:] + s[:ix] else -1\n except:\n return -1", "def xx(s):\n return s[1:] + s[0]\n\ndef shifted_diff(a, b):\n if a == b:\n return 0\n elif sorted(a) == sorted(b):\n n = 0\n for i in range(len(b)):\n n += 1\n b = xx(b)\n if b == a:\n return n\n return -1", "def shifted_diff(first, second):\n if len(first) != len(second):\n return -1\n return (second * 2).find(first)", "from collections import deque\n\ndef shifted_diff(f, s):\n (d1, d2) = (deque(f), deque(s))\n l = [d2.rotate(-1) or d1 == d2 for i in range(len(f))]\n return (l.index(True) + 1) % len(l) if True in l else -1"], "starter_code": "def shifted_diff(first, second):\n", "input_output": {"fn_name": "shifted_diff", "inputs": [["fatigue", "tiguefa"], ["hoop", "pooh"], ["eecoff", "coffee"], ["Moose", "moose"], ["isn't", "'tisn"], ["Esham", "Esham"], [" ", " "], ["dog", "god"], [" ", " "], ["doomhouse", "hoodmouse"], ["123456789!@#$%^&*( )qwerty", "9!@#$%^&*( )qwerty12345678"]], "outputs": [[5], [-1], [4], [-1], [2], [0], [0], [-1], [-1], [-1], [18]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5596f6e9529e9ab6fb000014", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "shifted_diff", "task_id": "TACO_lite/197", "example": [[["coffee", "eecoff"], ["eecoff", "coffee"], ["moose", "Moose"], ["isn't", "'tisn"], ["Esham", "Esham"], ["dog", "god"]], ["2", "4", "-1", "2", "0", "-1"]]} +{"requirement": "Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.\n \nExample 1:\nInput:\nN = 3 \nA[] = {1,2,3} \nOutput:\n-1\nExplanation:\nSince, each element in \n{1,2,3} appears only once so there \nis no majority element.\nExample 2:\nInput:\nN = 5 \nA[] = {3,1,3,3,2} \nOutput:\n3\nExplanation:\nSince, 3 is present more\nthan N/2 times, so it is \nthe majority element.\nYour Task:\nThe task is to complete the function majorityElement() which returns the majority element in the array. If no majority exists, return -1.\n \nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\n \nConstraints:\n1 \u2264 N \u2264 10^{7}\n0 \u2264 A_{i} \u2264 10^{6}", "solutions": ["def majorityelement(A, N):\n flag = True\n re = N // 2\n dict = {}\n if N == 1:\n return A[0]\n else:\n for i in A:\n if i in dict:\n dict[i] += 1\n else:\n dict[i] = 0\n for i in dict:\n if dict[i] >= re:\n flag = False\n return i\n if flag == True:\n return -1", "def majorityelement(A, N):\n if N == 1:\n return A[0]\n else:\n my_list = A\n size = N / 2\n element_count = {}\n for element in my_list:\n if element in element_count:\n element_count[element] += 1\n else:\n element_count[element] = 1\n max_count = max(element_count.values())\n if max_count == 1 or max_count <= size:\n return -1\n else:\n max_elements = [element for (element, count) in element_count.items() if count == max_count]\n for maxelements in max_elements:\n return maxelements", "from collections import defaultdict\n\ndef majorityelement(A, N):\n value = -1\n count = 0\n for a in A:\n if count == 0:\n value = a\n count += 1\n elif a == value:\n count += 1\n else:\n count -= 1\n return value if A.count(value) > N / 2 else -1", "from collections import defaultdict\n\ndef majorityelement(A, N):\n dic = defaultdict(int)\n for a in A:\n dic[a] += 1\n if dic[a] > N / 2:\n return a\n return -1", "def majorityelement(A, N):\n c = N / 2\n dict = {}\n if N == 1:\n return A[0]\n for x in A:\n if x not in dict:\n dict[x] = 1\n elif x in dict:\n dict[x] += 1\n if dict[x] > c:\n return x\n return -1", "from collections import Counter, defaultdict\n\ndef majorityelement(arr, N):\n c = Counter(arr)\n (v, cnt) = c.most_common(1)[0]\n if cnt > len(arr) // 2:\n return v\n return -1", "def majorityelement(array, n):\n (result, count) = (array[0], 1)\n for data in array[1:]:\n count = count + 1 if data == result else count - 1\n if count == 0:\n (result, count) = (data, 1)\n count = 0\n for data in array:\n if data == result:\n count += 1\n if not count > n // 2:\n result = -1\n return result", "def majorityelement(A, N):\n half = N // 2\n hash = {}\n for ele in A:\n if ele not in hash:\n hash[ele] = 1\n else:\n hash[ele] += 1\n for (k, v) in hash.items():\n if v > half:\n return k\n return -1", "def majorityelement(A, N):\n mp = {}\n for i in range(N):\n if A[i] in mp:\n mp[A[i]] += 1\n else:\n mp[A[i]] = 1\n for i in mp.keys():\n if mp[i] > N // 2:\n return i\n return -1", "from collections import Counter\n\ndef majorityelement(A, N):\n k = Counter(A)\n if N == 1:\n return A[0]\n for i in A:\n if k[i] > N // 2:\n return i\n return -1", "def majorityelement(A, N):\n elem = 0\n count = 0\n maxcount = 0\n for ele in A:\n if count == 0:\n elem = ele\n if ele == elem:\n count += 1\n else:\n count -= 1\n for val in A:\n if val == elem:\n maxcount += 1\n return elem if maxcount > N // 2 else -1", "def majorityelement(A, N):\n elem = A[0]\n count = 1\n maxCount = 0\n for idx in range(1, N):\n if A[idx] == elem:\n count += 1\n elif count == 0:\n elem = A[idx]\n count = 1\n else:\n count -= 1\n for val in A:\n if val == elem:\n maxCount += 1\n return elem if maxCount > N // 2 else -1", "def majorityelement(A, N):\n hashmap = {}\n ele = N // 2\n for i in A:\n if i in hashmap:\n hashmap[i] += 1\n else:\n hashmap[i] = 1\n if hashmap[i] > ele:\n return i\n return -1", "def findCandidate(A):\n maj_index = 0\n count = 1\n for i in range(len(A)):\n if A[maj_index] == A[i]:\n count += 1\n else:\n count -= 1\n if count == 0:\n maj_index = i\n count = 1\n return A[maj_index]\n\ndef isMajority(A, cand):\n count = 0\n for i in range(len(A)):\n if A[i] == cand:\n count += 1\n if count > len(A) / 2:\n return True\n else:\n return False\n\ndef majorityelement(A, N):\n cand = self.findCandidate(A)\n if self.isMajority(A, cand) == True:\n return cand\n else:\n return -1", "def majorityelement(A, N):\n d = dict()\n for element in A:\n if element in d:\n d[element] += 1\n else:\n d[element] = d.get(element, 0) + 1\n for element in d:\n if d[element] > N / 2:\n return element\n return -1", "def majorityelement(arr, n):\n d = {}\n m = -1\n ans = -1\n if n == 1:\n return arr[0]\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n for (i, j) in d.items():\n if j > n // 2:\n return i\n return -1", "def majorityelement(A, N):\n maj = 0\n count = 0\n for i in range(N):\n if count == 0:\n maj = A[i]\n if maj == A[i]:\n count += 1\n else:\n count -= 1\n count = 0\n for i in range(N):\n if maj == A[i]:\n count += 1\n if count > N / 2:\n return maj\n return -1", "def majorityelement(A, N):\n count = 0\n num = 0\n for i in range(N):\n if count == 0:\n num = A[i]\n count += 1\n elif num == A[i]:\n count += 1\n else:\n count -= 1\n c = 0\n for i in range(N):\n if A[i] == num:\n c += 1\n if c > N // 2:\n return num\n else:\n return -1", "def majorityelement(A, N):\n dict1 = {}\n maj = -1\n majVal = -1\n if N == 1:\n return A[0]\n for i in range(N):\n if A[i] in dict1:\n dict1[A[i]] += 1\n else:\n dict1[A[i]] = 1\n for key in dict1:\n if dict1[key] > maj:\n maj = dict1[key]\n majVal = key\n if maj > N // 2:\n return majVal\n else:\n return -1", "def majorityelement(a, N):\n d = {}\n for n in a:\n if n in d:\n d[n] = d[n] + 1\n else:\n d[n] = 1\n for n in a:\n if d[n] > N / 2:\n return n\n return -1", "def majorityelement(A, N):\n max = A[0]\n occur = 1\n for i in range(1, len(A)):\n if occur == 0:\n occur += 1\n max = A[i]\n elif A[i] == max:\n occur += 1\n else:\n occur -= 1\n if A.count(max) > N / 2:\n return max\n return -1", "def majorityelement(A, N):\n dic = {}\n for i in A:\n dic[i] = 1 + dic.get(i, 0)\n for (k, v) in dic.items():\n if v > N // 2:\n return k\n return -1", "def majorityelement(A, N):\n n = len(A)\n freq = {}\n for num in A:\n freq[num] = freq.get(num, 0) + 1\n for (num, count) in freq.items():\n if count > n // 2:\n return num\n return -1", "from collections import Counter\n\ndef majorityelement(A, N):\n f = Counter(A)\n for (i, j) in f.items():\n if j > N // 2:\n return i\n return -1", "def majorityelement(A, N):\n count = {}\n for a in A:\n if a in count:\n count[a] = count[a] + 1\n else:\n count[a] = 1\n for (k, v) in count.items():\n if v > N / 2:\n return k\n return -1", "def majorityelement(A, N):\n count = 1\n i = 1\n candidate = A[0]\n while i < len(A):\n if candidate == A[i]:\n count += 1\n else:\n count -= 1\n if count == 0:\n candidate = A[i]\n count = 1\n i += 1\n count = 0\n for ele in A:\n if candidate == ele:\n count += 1\n if count > N // 2:\n return candidate\n return -1", "def majorityelement(A, N):\n c = 0\n majr = 0\n for i in range(0, N):\n if c == 0:\n majr = i\n c = 1\n elif A[majr] == A[i]:\n c = c + 1\n else:\n c = c - 1\n C = 0\n for i in range(len(A)):\n if A[majr] == A[i]:\n c = c + 1\n if c > N // 2:\n return A[majr]\n return -1", "def majorityelement(A, N):\n count = 0\n candidate = None\n for i in range(N):\n if count == 0:\n candidate = A[i]\n count = 1\n elif A[i] == candidate:\n count += 1\n else:\n count -= 1\n count = 0\n for i in range(N):\n if A[i] == candidate:\n count += 1\n if count > N / 2:\n return candidate\n else:\n return -1", "from collections import Counter\n\ndef majorityelement(A, N):\n m = {}\n for n in A:\n m[n] = m.get(n, 0) + 1\n if m[n] > N // 2:\n return n\n return -1", "def majorityelement(A, N):\n majcnt = 0\n majele = -1\n for i in A:\n if majcnt == 0:\n majele = i\n majcnt = 1\n elif majele == i:\n majcnt += 1\n else:\n majcnt -= 1\n cnt = 0\n for i in A:\n if i == majele:\n cnt += 1\n if cnt > N // 2:\n return majele\n else:\n return -1", "def majorityelement(A, N):\n mapp = {}\n mid = N // 2\n for i in range(N):\n if A[i] in mapp:\n mapp[A[i]] += 1\n else:\n mapp[A[i]] = 1\n for k in mapp.keys():\n if mapp[k] > mid:\n return k\n return -1", "def possible(l, n):\n val = l[0]\n cnt = 1\n for i in range(1, n):\n if l[i] == val:\n cnt += 1\n else:\n cnt -= 1\n if cnt == 0:\n val = l[i]\n cnt = 1\n return val\n\ndef majorityelement(A, N):\n val = self.possible(A, N)\n return val if A.count(val) > N // 2 else -1", "def majorityelement(A, N):\n d = {}\n count = 0\n for i in A:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for (items, value) in d.items():\n if value > N / 2:\n return items\n return -1", "def majorityelement(A, N):\n element = None\n counter = 0\n for i in range(N):\n if counter == 0:\n counter = 1\n element = A[i]\n elif element == A[i]:\n counter += 1\n else:\n counter -= 1\n new_count = 0\n for i in range(N):\n if A[i] == element:\n new_count += 1\n if new_count > N // 2:\n return element\n else:\n return -1", "def majorityelement(A, N):\n freq_dict = {}\n for i in A:\n if i in freq_dict:\n freq_dict[i] += 1\n else:\n freq_dict[i] = 1\n for (i, count) in freq_dict.items():\n if count > N // 2:\n return i\n return -1", "def majorityelement(A, N):\n if N == 1:\n return A[0]\n Map = {}\n for ele in A:\n if ele in Map:\n Map[ele] += 1\n if Map[ele] > N / 2:\n return ele\n else:\n Map[ele] = 1\n return -1", "def majorityelement(A, N):\n d = {}\n for e in A:\n if e in d:\n d[e] = d[e] + 1\n else:\n d[e] = 1\n if d[e] > N / 2:\n return e\n return -1", "from collections import Counter\n\ndef majorityelement(A, N):\n counter = Counter(A)\n for (num, freq) in counter.items():\n if freq > N / 2:\n return num\n return -1", "def majorityelement(A, N):\n d = {}\n f = 0\n ans = 0\n for ele in A:\n if ele in d.keys():\n d[ele] += 1\n else:\n d[ele] = 1\n for keys in d.keys():\n if d[keys] > N / 2:\n ans = keys\n f = 0\n break\n else:\n f = 1\n if f == 0:\n return ans\n else:\n return -1", "def majorityelement(A, n):\n dic = {}\n ans = -1\n for i in A:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n for (key, value) in dic.items():\n if value > n // 2:\n ans = key\n return ans", "def majorityelement(A, N):\n c = {}\n for i in A:\n c[i] = c.get(i, 0) + 1\n if c[i] > N / 2:\n return i\n return -1", "def majorityelement(A, N):\n count_dict = {}\n for elem in A:\n count_dict[elem] = count_dict.get(elem, 0) + 1\n if count_dict[elem] > N / 2:\n return elem\n return -1", "def find_majority_candidate(A, N):\n maj_index = 0\n count = 1\n for i in range(len(A)):\n if A[maj_index] == A[i]:\n count += 1\n else:\n count -= 1\n if count == 0:\n maj_index = i\n count = 1\n return A[maj_index]\n\ndef is_majority_candidate(A, N, a):\n n = N // 2\n count = 0\n for i in range(N):\n if A[i] == a:\n count += 1\n if count > n:\n return True\n return False\n\ndef majorityelement(A, N):\n a = self.find_majority_candidate(A, N)\n f = self.is_majority_candidate(A, N, a)\n if f:\n return a\n return -1", "def majorityelement(A, N):\n A.sort()\n n = N // 2\n i = 0\n while i < N:\n j = i\n if i + 1 < N and A[i] == A[i + 1]:\n while i + 1 < N and A[i] == A[i + 1]:\n i = i + 1\n k = i\n if k - j + 1 > n:\n return A[i]\n i = i + 1\n return -1", "def majorityelement(A, N):\n majority = True\n dic = {}\n for i in range(N):\n if A[i] in dic:\n dic[A[i]] += 1\n else:\n dic[A[i]] = 1\n for key in dic:\n if dic[key] > N // 2:\n return key\n return -1", "def majorityelement(A, N):\n temp = N // 2\n hashed = {}\n for i in A:\n hashed[i] = 1 + hashed.get(i, 0)\n for i in hashed:\n if hashed[i] > temp:\n return i\n return -1", "from collections import Counter\n\ndef majorityelement(A, N):\n A = Counter(A)\n max = N // 2\n v = 0\n for (i, j) in A.items():\n if j > max:\n max = j\n v = i\n if v == 0:\n return -1\n else:\n return v", "from collections import defaultdict\n\ndef majorityelement(A, N):\n count = 0\n maxcount = 0\n for i in range(0, N):\n if count == 0:\n count = 1\n ele = A[i]\n elif ele == A[i]:\n count += 1\n else:\n count -= 1\n for val in A:\n if val == ele:\n maxcount += 1\n return ele if maxcount > N // 2 else -1", "from collections import defaultdict\n\ndef majorityelement(A, N):\n hmap = defaultdict(int)\n for i in range(0, N):\n if A[i] not in hmap:\n hmap[A[i]] = 1\n else:\n hmap[A[i]] += 1\n for (k, v) in hmap.items():\n if v > N // 2:\n return k\n return -1", "def majorityelement(A, N):\n dict_ = dict()\n for number in A:\n dict_[number] = dict_.get(number, 0) + 1\n for number in A:\n if dict_[number] > N // 2:\n return number\n return -1", "from collections import Counter\n\ndef majorityelement(A, N):\n counterA = Counter(A)\n rep = N // 2\n for (i, j) in counterA.items():\n if j > rep:\n return i\n if rep + 1 not in counterA.values():\n return -1", "def majorityelement(A, N):\n dict = {}\n for num in A:\n if num not in dict:\n dict[num] = 1\n else:\n dict[num] += 1\n maxCount = max(dict, key=dict.get)\n if dict[maxCount] > N // 2:\n return maxCount\n else:\n return -1", "from collections import Counter\n\ndef majorityelement(A, N):\n counterA = Counter(A)\n target = N // 2\n for (indx, val) in counterA.items():\n if val > target:\n return indx\n return -1", "def majorityelement(A, N):\n count = 1\n maj_ele = A[0]\n for i in range(1, N):\n num = A[i]\n if num == maj_ele:\n count += 1\n else:\n count -= 1\n if count == 0:\n count = 1\n maj_ele = num\n total = 0\n for num in A:\n if num == maj_ele:\n total += 1\n if total > int(N / 2):\n return maj_ele\n return -1", "def majorityelement(A, N):\n A.sort()\n mid = A[N // 2]\n if A.count(mid) > N // 2:\n return mid\n else:\n return -1", "def majorityelement(A, N):\n hashmap = {}\n for i in A:\n hashmap[i] = 1 + hashmap.get(i, 0)\n for (key, value) in hashmap.items():\n if value > N // 2:\n return key\n else:\n return -1", "def majorityelement(a, n):\n count = 0\n b = 0\n for i in range(0, n):\n if count == 0:\n count = 1\n b = a[i]\n elif a[i] == b:\n count += 1\n else:\n count -= 1\n count1 = 0\n for i in range(0, n - 1):\n if a[i] == b:\n count += 1\n if count > n // 2:\n return b\n return -1", "def majorityelement(A, N):\n d = {}\n for i in range(N):\n if N == 1:\n return A[0]\n if A[i] not in d:\n d[A[i]] = 1\n else:\n d[A[i]] += 1\n if d[A[i]] > N / 2 and d[A[i]] != 1:\n return A[i]\n return -1", "def majorityelement(A, N):\n A.sort()\n x = 0\n x1 = A[0]\n for i in A:\n if i == x1:\n x = x + 1\n if x > N // 2:\n return i\n else:\n x1 = i\n x = 1\n return -1", "def majorityelement(A, N):\n lis = {}\n x = N // 2\n for i in A:\n if i in lis:\n lis[i] = lis[i] + 1\n else:\n lis[i] = 1\n if lis[i] > x:\n return i\n return -1", "def majorityelement(A, N):\n (m1, c1) = (None, 0)\n for i in A:\n if i == m1:\n c1 += 1\n elif c1 == 0:\n m1 = i\n c1 = 1\n else:\n c1 -= 1\n ans = -1\n if A.count(m1) > N / 2:\n ans = m1\n return ans", "def majorityelement(A, N):\n d = {}\n ans = -1\n for i in range(N):\n if A[i] not in d:\n d[A[i]] = 1\n else:\n d[A[i]] = d[A[i]] + 1\n for k in d:\n if d[k] > N / 2:\n ans = k\n break\n return ans", "def majorityelement(A, N):\n count = {}\n (res, maxcount) = (-1, 0)\n for n in A:\n count[n] = 1 + count.get(n, 0)\n res = n if count[n] > maxcount else res\n maxcount = max(maxcount, count[n])\n return res if maxcount > N / 2 else -1", "def majorityelement(A, N):\n dic = {}\n ans = -1\n maxi = 0\n if N == 1:\n return A[0]\n for ele in A:\n if ele in dic:\n dic[ele] += 1\n else:\n dic[ele] = 1\n for x in dic:\n if dic[x] > N // 2:\n maxi = dic[x]\n ans = x\n if maxi == 1:\n return -1\n else:\n return ans", "def majorityelement(A, N):\n cnt = 0\n cur = 0\n for i in range(N):\n if cnt == 0:\n cur = A[i]\n cnt = 1\n elif cur == A[i]:\n cnt += 1\n else:\n cnt -= 1\n c = 0\n for el in A:\n if el == cur:\n c += 1\n return cur if c > N // 2 else -1", "from collections import Counter\n\ndef majorityelement(A, N):\n k = N // 2\n dic = Counter(A)\n for (key, v) in dic.items():\n if dic[key] > k:\n return key\n return -1", "def majorityelement(A, N):\n if N == 1:\n return A[0]\n A.sort()\n count = 1\n curr = A[0]\n for idx in range(1, N):\n if A[idx] == curr:\n count += 1\n else:\n count = 1\n curr = A[idx]\n if count > N / 2:\n return curr\n return -1", "def majorityelement(A, N):\n s = N // 2\n max = -1\n ans = -1\n if N == 1:\n return A[0]\n d = dict()\n for i in A:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for i in d:\n if d[i] > N // 2:\n max = 1\n ans = i\n if max == -1:\n return -1\n else:\n return ans", "from collections import *\n\ndef majorityelement(A, N):\n dic = Counter(A)\n maj = 0\n num = 0\n for (key, val) in dic.items():\n if val > maj:\n maj = val\n num = key\n if maj > N / 2:\n return num\n return -1", "from collections import defaultdict\nimport math\n\ndef majorityelement(A, N):\n d = defaultdict(int)\n for i in A:\n d[i] += 1\n for i in d:\n if d[i] > N / 2:\n return i\n return -1", "def majorityelement(A, N):\n freq = {}\n for i in A:\n if i not in freq:\n freq[i] = 1\n else:\n freq[i] += 1\n for key in freq:\n if freq[key] > N // 2:\n return key\n return -1"], "starter_code": "def majorityelement(A, N):\n", "input_output": {"inputs": ["N = 3 \r\nA[] = {1,2,3}", "N = 5 \r\nA[] = {3,1,3,3,2}"], "outputs": ["-1", "3"]}, "difficulty": "MEDIUM", "raw_tags": ["Searching", "Algorithms", "Greedy", "Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Complete search", "Data structures", "Greedy algorithms"], "skill_types": ["Complete search", "Data structures", "Greedy algorithms"], "url": "https://practice.geeksforgeeks.org/problems/majority-element-1587115620/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "majorityelement", "task_id": "TACO_lite/171", "example": [[[3, [1, 2, 3]], [5, [3, 1, 3, 3, 2]]], [null, null]]} +{"requirement": "The palindromic number `595` is interesting because it can be written as the sum of consecutive squares: `6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2 = 595`.\n\nThere are exactly eleven palindromes below one-thousand that can be written as consecutive square sums. Note that `1 = 0^2 + 1^2` has not been included as this problem is concerned with the squares of positive integers.\n\nGiven an input `n`, find the count of all the numbers less than `n` that are both palindromic and can be written as the sum of consecutive squares.\n\nFor instance: `values(1000) = 11`. See test examples for more cases. \n\nGood luck!\n\nThis Kata is borrowed from [Project Euler #125](https://projecteuler.net/problem=125)\n\nIf you like this Kata, please try:\n\n[Fixed length palindromes](https://www.codewars.com/kata/59f0ee47a5e12962cb0000bf)\n\n[Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)", "solutions": ["(l, m, p) = ([1], 10 ** 7, [])\nfor n in range(2, int(m ** 0.5) + 1):\n l = [n * n + j for j in [0] + l]\n p += [int(k) for k in map(str, l[1:]) if k == k[::-1]]\np = sorted(set(p))\nfrom bisect import bisect_left\n\ndef values(n):\n return bisect_left(p, n)", "def values(n):\n pal = set()\n for i in range(1, int(n ** 0.5)):\n sos = i * i\n while sos < n:\n i += 1\n sos += i * i\n if str(sos) == str(sos)[::-1] and sos < n:\n pal.add(sos)\n return len(pal)", "from bisect import bisect\nis_pal = lambda s: s == s[::-1]\n(N, temp) = (2500, set())\nfor x in range(1, N):\n val = x ** 2\n for y in range(x + 1, N):\n val += y ** 2\n if val not in temp and is_pal(str(val)):\n temp.add(val)\nresult = sorted(temp)\n\ndef values(n):\n return bisect(result, n)", "sumSquaresToN = lambda n: n * (n + 1) * (2 * n + 1) // 6\nmemo = set()\n\ndef values(n):\n lastMax = max(memo) if memo else 0\n if lastMax >= n:\n return sum((x < n for x in memo))\n top = int((1 + (1 + 2 * (n - 1)) ** 0.5) // 2)\n for a in range(top, 1, -1):\n va = sumSquaresToN(a)\n if va <= lastMax:\n break\n for b in range(a - 2, -1, -1):\n v = va - sumSquaresToN(b)\n if v >= n:\n break\n if v == int(str(v)[::-1]):\n memo.add(v)\n return len(memo)", "found = set([5, 55, 77, 181, 313, 434, 505, 545, 595, 636, 818, 1001, 1111, 1441, 1771, 4334, 6446, 17371, 17871, 19691, 21712, 41214, 42924, 44444, 46564, 51015, 65756, 81818, 97679, 99199, 108801, 127721, 137731, 138831, 139931, 148841, 161161, 166661, 171171, 188881, 191191, 363363, 435534, 444444, 485584, 494494, 525525, 554455, 554455, 629926, 635536, 646646, 656656, 904409, 923329, 944449, 964469, 972279, 981189, 982289, 1077701, 1224221, 1365631, 1681861, 1690961, 1949491, 1972791, 1992991, 2176712, 2904092, 3015103, 3162613, 3187813, 3242423, 3628263, 4211124, 4338334, 4424244, 4776774, 5090905, 5258525, 5276725, 5367635, 5479745, 5536355, 5588855, 5603065, 5718175, 5824285, 6106016, 6277726, 6523256, 6546456, 6780876, 6831386, 6843486, 6844486, 7355537, 8424248, 9051509, 9072709, 9105019, 9313139, 9334339, 9343439, 9343439, 9435349, 9563659, 9793979, 9814189, 9838389, 9940499])\n\ndef values(n):\n return sum((i < n for i in found))", "def values(high):\n s = set()\n num = 1\n while num * num < high:\n temp = num + 1\n total = num * num + temp * temp\n while total < high:\n if str(total) == str(total)[::-1]:\n s.add(total)\n temp += 1\n total += temp * temp\n num += 1\n return len(s)", "def values(limit):\n palindromes = set()\n for sequence_item in range(1, int(limit ** 0.5)):\n squares_sum = sequence_item ** 2\n while squares_sum < limit:\n sequence_item += 1\n squares_sum += sequence_item ** 2\n if str(squares_sum) == str(squares_sum)[::-1] and squares_sum < limit:\n palindromes.add(squares_sum)\n return len(palindromes)", "def values(n):\n p = set()\n for i in range(1, int(n ** 0.5)):\n q = i * i\n while q < n:\n i = i + 1\n q = q + i * i\n if str(q) == str(q)[::-1] and q < n:\n p.add(q)\n return len(p)"], "starter_code": "def values(n):\n", "input_output": {"fn_name": "values", "inputs": [[100], [200], [300], [400], [1000], [100000], [1000000], [5000000], [9000000], [10000000]], "outputs": [[3], [4], [4], [5], [11], [30], [59], [78], [98], [110]]}, "difficulty": "EASY", "raw_tags": ["Performance", "Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/599b1a4a3c5292b4cc0000d5", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "values", "task_id": "TACO_lite/249", "example": [[[1000]], ["11"]]} +{"requirement": "Given a string str, a partitioning of the string is a palindrome partitioning if every sub-string of the partition is a palindrome. Determine the fewest cuts needed for palindrome partitioning of the given string.\nExample 1:\nInput: str = \"ababbbabbababa\"\nOutput: 3\nExplaination: After 3 partitioning substrings \nare \"a\", \"babbbab\", \"b\", \"ababa\".\nExample 2:\nInput: str = \"aaabba\"\nOutput: 1\nExplaination: The substrings after 1\npartitioning are \"aa\" and \"abba\".\nYour Task:\nYou do not need to read input or print anything, Your task is to complete the function palindromicPartition() which takes the string str as the input parameter and returns the minimum number of partitions required.\nExpected Time Complexity: O(n*n) [n is the length of the string str]\nExpected Auxiliary Space: O(n*n)\nConstraints:\n1 \u2264 length of str \u2264 500", "solutions": ["def palindromicpartition(s):\n dp = [[-1] * (len(s) + 1) for _ in range(len(s) + 1)]\n\n def dfs(s, i, j):\n if dp[i][j] != -1:\n return dp[i][j]\n if i > j:\n return 0\n if self.isPal(s, i, j):\n return 0\n mx = len(s)\n for k in range(i, j):\n if self.isPal(s, i, k):\n t = dfs(s, k + 1, j) + 1\n mx = min(mx, t)\n dp[i][j] = mx\n return dp[i][j]\n return dfs(s, 0, len(s) - 1)\n\ndef isPal(s, start, end):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True", "def palindromicpartition(s):\n n = len(s)\n dp = [[-1 for i in range(n + 2)] for j in range(n + 2)]\n\n def ispal(st):\n return st == st[::-1]\n\n def solve(i, j):\n if i >= j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if ispal(s[i:j + 1]):\n return 0\n mn = int(1000000000.0)\n for k in range(i, j):\n if ispal(s[i:k + 1]):\n temp = solve(k + 1, j) + 1\n mn = min(mn, temp)\n dp[i][j] = mn\n return mn\n x = solve(0, n - 1)\n return x", "def palindromicpartition(a):\n cut = [0 for i in range(len(a))]\n palindrome = [[False for i in range(len(a))] for j in range(len(a))]\n for i in range(len(a)):\n minCut = i\n for j in range(i + 1):\n if a[i] == a[j] and (i - j < 2 or palindrome[j + 1][i - 1]):\n palindrome[j][i] = True\n minCut = min(minCut, 0 if j == 0 else cut[j - 1] + 1)\n cut[i] = minCut\n return cut[len(a) - 1]", "import numpy as np\nimport sys\n\ndef dp_sol(string):\n len_s = len(string)\n dp = np.array([[0] * len_s] * len_s)\n for i in range(len_s):\n for j in range(i, -1, -1):\n if i == j:\n dp[j][i] = 0\n if i == j + 1:\n if string[i] == string[j]:\n dp[j][i] = 0\n else:\n dp[j][i] = 1\n else:\n start = j\n end = i\n while start < end and string[start] == string[end]:\n start = start + 1\n end = end - 1\n if start >= end:\n dp[j][i] = 0\n else:\n temp = sys.maxsize\n for k in range(j, i):\n temp = min(temp, 1 + dp[j][k] + dp[k + 1][i])\n dp[j][i] = temp\n return dp[0][len_s - 1]\n\ndef dp_sol2(string):\n len_s = len(string)\n dp = np.array([[False] * len_s] * len_s)\n for i in range(len_s):\n for j in range(i + 1):\n if i == j:\n dp[j][i] = True\n elif j + 1 == i and string[i] == string[j]:\n dp[j][i] = True\n elif string[j] == string[i] and dp[j + 1][i - 1]:\n dp[j][i] = True\n p = np.array([len_s] * len_s)\n for i in range(len_s):\n if dp[0][i] == True:\n p[i] = 0\n else:\n for j in range(i):\n if dp[j + 1][i]:\n p[i] = min(p[i], p[j] + 1)\n return p[len_s - 1]\n\ndef palindromicpartition(string):\n return self.dp_sol2(string)", "def isPalindrome(string, a, b):\n while a <= b:\n if string[a] != string[b]:\n return False\n a += 1\n b -= 1\n return True\n\ndef palindromicpartition(string):\n n = len(string)\n dp = [-1 for _ in range(n + 1)]\n dp[n] = 0\n for i in range(n - 1, -1, -1):\n minCuts = float('inf')\n for j in range(i, n):\n if self.isPalindrome(string, i, j):\n minCuts = min(minCuts, 1 + dp[j + 1])\n dp[i] = minCuts\n return dp[0] - 1", "def helper(string, i, n, dp, ans):\n ans[0] = 0\n for j in range(1, n):\n if dp[0][j]:\n ans[j] = 0\n else:\n temp = int(1000000000.0)\n for i in range(j, 0, -1):\n if dp[i][j]:\n temp = min(temp, ans[i - 1])\n ans[j] = temp + 1\n\ndef palindromicpartition(string):\n n = len(string)\n dp = [[False for _ in range(n)] for _ in range(n)]\n for j in range(n):\n for i in range(n):\n if j - i == 0 and i == j:\n dp[i][j] = True\n elif j - i == 1 and string[i] == string[j]:\n dp[i][j] = True\n elif j - i >= 2 and string[i] == string[j] and (dp[i + 1][j - 1] == True):\n dp[i][j] = True\n ans = [0] * n\n helper(string, 0, n, dp, ans)\n return ans[n - 1]", "def palindromicpartition(s):\n n = len(s)\n dp = [[-1 for i in range(0, n + 2)] for j in range(0, n + 2)]\n\n def getAns(i, j):\n if i >= j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if isPal(s, i, j):\n return 0\n mn = int(1000000000.0)\n for k in range(i, j):\n if isPal(s, i, k):\n temp = getAns(k + 1, j) + 1\n mn = min(mn, temp)\n dp[i][j] = mn\n return mn\n\n def isPal(s, start, end):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n return getAns(0, n - 1)", "def palindromicpartition(string):\n n = len(string)\n dp = [-1 for i in range(n)]\n return self.f(0, n, string, dp) - 1\n\ndef f(i, n, string, dp):\n mincost = float('inf')\n if i == n:\n return 0\n if dp[i] != -1:\n return dp[i]\n for j in range(i, n):\n if self.isPalindrome(string, i, j):\n cost = 1 + self.f(j + 1, n, string, dp)\n mincost = min(mincost, cost)\n dp[i] = mincost\n return dp[i]\n\ndef isPalindrome(string, i, j):\n while i < j:\n if string[i] != string[j]:\n return False\n i += 1\n j -= 1\n return True", "def palindromicpartition(string: str) -> int:\n n = len(string)\n P = [[False for _ in range(n)] for _ in range(n)]\n for i in range(n):\n P[i][i] = True\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if L == 2:\n P[i][j] = string[i] == string[j]\n else:\n P[i][j] = string[i] == string[j] and P[i + 1][j - 1]\n cuts = [0] * n\n for i in range(n):\n if P[0][i]:\n cuts[i] = 0\n else:\n cuts[i] = float('inf')\n for j in range(i):\n if P[j + 1][i] and cuts[j] + 1 < cuts[i]:\n cuts[i] = cuts[j] + 1\n return cuts[n - 1]", "def palindromicpartition(string):\n n = len(string)\n dp = [0 for _ in range(n + 1)]\n for i in range(n - 1, -1, -1):\n minCuts = float('inf')\n for j in range(i, n):\n if self.isPalindrome(string[i:j + 1]):\n cuts = 1 + dp[j + 1]\n minCuts = min(cuts, minCuts)\n dp[i] = minCuts\n return dp[0] - 1\n\ndef isPalindrome(x):\n return x == x[::-1]", "def palindromicpartition(string):\n n = len(string)\n P = [[False] * n for _ in range(n)]\n for i in range(n):\n P[i][i] = True\n for i in range(n - 1):\n P[i][i + 1] = string[i] == string[i + 1]\n for l in range(3, n + 1):\n for i in range(n - l + 1):\n j = i + l - 1\n P[i][j] = string[i] == string[j] and P[i + 1][j - 1]\n C = [i for i in range(n)]\n for i in range(n):\n if P[0][i]:\n C[i] = 0\n else:\n for j in range(i):\n if P[j + 1][i]:\n C[i] = min(C[i], C[j] + 1)\n return C[n - 1]", "def palindromicpartition(s):\n n = len(s)\n C = [0] * n\n P = [[False for i in range(n)] for i in range(n)]\n for i in range(n):\n P[i][i] = True\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if L == 2:\n P[i][j] = s[i] == s[j]\n else:\n P[i][j] = (s[i] == s[j]) & P[i + 1][j - 1]\n for i in range(n):\n if P[0][i]:\n C[i] = 0\n else:\n C[i] = 1 << 32\n for j in range(i):\n if P[j + 1][i] == True and C[j] + 1 < C[i]:\n C[i] = C[j] + 1\n return C[n - 1]", "def __init__():\n self.res = -float('inf')\n\ndef check_palin(x):\n n = len(x)\n for i in range(n // 2):\n if x[i] != x[-i - 1]:\n return False\n return True\n\ndef solve(i, j, st, dp):\n if i >= j:\n return 0\n if self.check_palin(st[i:j + 1]):\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n min_cut = float('inf')\n for ind in range(i, j):\n if self.check_palin(st[i:ind + 1]):\n x = self.solve(ind + 1, j, st, dp) + 1\n min_cut = min(min_cut, x)\n dp[i][j] = min_cut\n return dp[i][j]\n\ndef palindromicpartition(string):\n n = len(string)\n dp = [[-1 for i in range(n + 2)] for j in range(n + 2)]\n r = self.solve(0, n - 1, string, dp)\n return r", "def palindromicpartition(s):\n n = len(s)\n dp = [[-1 for i in range(n + 2)] for j in range(n + 2)]\n\n def ispal(st):\n return st == st[::-1]\n\n def solve(i, j):\n if i >= j or ispal(s[i:j + 1]):\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n mn = float('inf')\n for k in range(i, j):\n if ispal(s[i:k + 1]):\n temp = solve(k + 1, j) + 1\n mn = min(mn, temp)\n dp[i][j] = mn\n return mn\n x = solve(0, n - 1)\n return x", "def palindromicpartition(string: str) -> int:\n n = len(string)\n dp = [[False] * n for _ in range(n)]\n for i in range(n):\n dp[i][i] = True\n for length in range(2, n + 1):\n for i in range(n - length + 1):\n j = i + length - 1\n if string[i] == string[j] and (length == 2 or dp[i + 1][j - 1]):\n dp[i][j] = True\n cuts = [float('inf')] * n\n for i in range(n):\n if dp[0][i]:\n cuts[i] = 0\n else:\n for j in range(i):\n if dp[j + 1][i]:\n cuts[i] = min(cuts[i], cuts[j] + 1)\n return cuts[n - 1]", "def palindromicpartition(s):\n\n def check(i, j, s):\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n dp = [-1] * len(s)\n\n def f(i, s):\n if i == len(s):\n return 0\n minCnt = 10 ** 9\n if dp[i] != -1:\n return dp[i]\n for j in range(i, len(s)):\n if check(i, j, s):\n cnt = 1 + f(j + 1, s)\n minCnt = min(minCnt, cnt)\n dp[i] = minCnt\n return dp[i]\n return f(0, s) - 1", "def palindromicpartition(string):\n\n def ispal(s):\n return s == s[::-1]\n\n def solve(i, j, string):\n if i >= j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if ispal(string[i:j + 1]):\n return 0\n ans = 10000000000.0\n for k in range(i, j):\n if ispal(string[i:k + 1]):\n temp = 1 + solve(k + 1, j, string)\n ans = min(ans, temp)\n dp[i][j] = ans\n return dp[i][j]\n n = len(string)\n dp = [[-1] * 1001 for i in range(1001)]\n return solve(0, n - 1, string)", "def palindromicpartition(s):\n\n def calc(i):\n if i == len(s):\n return 0\n if dp[i] != -1:\n return dp[i]\n else:\n mxc = float('inf')\n for k in range(i, len(s)):\n if s[i:k + 1] == s[i:k + 1][::-1]:\n cnt = 1 + calc(k + 1)\n mxc = min(mxc, cnt)\n dp[i] = mxc\n return dp[i]\n dp = [-1 for i in range(len(s) + 1)]\n return calc(0) - 1", "def palindromicpartition(string):\n n = len(string)\n if n != 0:\n dp = [[False] * n for i in range(n)]\n for i in range(n):\n dp[i][i] = True\n if i != n - 1:\n if string[i] == string[i + 1]:\n dp[i][i + 1] = True\n for c in range(2, n):\n i = 0\n j = c\n while i < n and j < n:\n if string[i] != string[j]:\n dp[i][j] = False\n else:\n dp[i][j] = dp[i + 1][j - 1]\n i += 1\n j += 1\n mc = [0] * len(string)\n mc[0] = 0\n for i in range(1, n):\n if dp[0][i] == True:\n mc[i] = 0\n else:\n mc[i] = 100000\n for k in range(1, i + 1):\n if dp[k][i]:\n mc[i] = min(mc[i], 1 + mc[k - 1])\n return mc[n - 1]", "def palindromicpartition(string):\n self.isPalindrome = [[False for i in range(len(string))] for j in range(len(string))]\n\n def populateIsPalindromeDP():\n for i in range(0, len(string)):\n for j in range(0, len(string) - i):\n if i == 0:\n self.isPalindrome[j][j] = True\n elif i == 1:\n if string[j] == string[j + 1]:\n self.isPalindrome[j][j + 1] = True\n elif string[j] == string[j + i] and self.isPalindrome[j + 1][j + i - 1]:\n self.isPalindrome[j][j + i] = True\n populateIsPalindromeDP()\n dp = [0 for i in range(len(string) + 1)]\n for i in range(1, len(string) + 1):\n dp[i] = dp[i - 1] + 1\n if self.isPalindrome[0][i - 1]:\n dp[i] = 0\n continue\n for j in range(0, i):\n if self.isPalindrome[j + 1 - 1][i - 1]:\n dp[i] = min(dp[i], 1 + dp[j])\n return dp[-1]", "def ispalindrome(start, end, string):\n while start < end:\n if string[start] != string[end]:\n return False\n start += 1\n end -= 1\n return True\n\ndef palindromicpartition(string):\n n = len(string)\n dp = [0 for i in range(n + 1)]\n\n def rec(idx):\n if idx == n:\n return 0\n if dp[idx] != -1:\n return dp[idx]\n maxi = float('inf')\n (p, np) = (float('inf'), float('inf'))\n for i in range(idx, n):\n if self.ispalindrome(idx, i, string):\n p = 1 + rec(i + 1)\n maxi = min(maxi, p)\n dp[idx] = maxi\n return dp[idx]\n for idx in range(n - 1, -1, -1):\n maxi = float('inf')\n (p, np) = (float('inf'), float('inf'))\n for i in range(idx, n):\n if self.ispalindrome(idx, i, string):\n p = 1 + dp[i + 1]\n maxi = min(maxi, p)\n dp[idx] = maxi\n return dp[0] - 1", "def palindromicpartition(string):\n n = len(string)\n dp = [0] * n\n pal = [[False] * n for _ in range(n)]\n for i in range(n):\n pal[i][i] = True\n for l in range(2, n + 1):\n for i in range(n - l + 1):\n j = i + l - 1\n if l == 2:\n pal[i][j] = string[i] == string[j]\n else:\n pal[i][j] = string[i] == string[j] and pal[i + 1][j - 1]\n for i in range(n):\n min_cuts = i\n for j in range(i + 1):\n if pal[j][i]:\n if j == 0:\n min_cuts = 0\n else:\n min_cuts = min(min_cuts, dp[j - 1] + 1)\n dp[i] = min_cuts\n return dp[n - 1]", "def palindromicpartition(string):\n dp = {}\n return self.helper(string, dp)\n\ndef helper(string, dp):\n n = len(string)\n if n == 0:\n dp[string] = 0\n return 0\n if string in dp:\n return dp[string]\n if string == string[::-1]:\n dp[string] = 0\n return 0\n minimum = float('inf')\n for i in range(1, n + 1):\n if string[:i] == string[:i][::-1]:\n minimum = min(minimum, 1 + self.helper(string[i:], dp))\n dp[string] = minimum\n return dp[string]", "def palindromicpartition(string):\n n = len(string)\n\n def check_pali(s, e):\n (i, j) = (s, e)\n while i < j:\n if string[i] != string[j]:\n return False\n i += 1\n j -= 1\n return True\n maxi = 10 ** 9\n dp = [-1] * n\n\n def find(start):\n if start == n or check_pali(start, n - 1):\n return 0\n if dp[start] != -1:\n return dp[start]\n ans = maxi\n for i in range(start, n):\n if check_pali(start, i):\n ans = min(ans, find(i + 1))\n dp[start] = ans + 1\n return dp[start]\n return find(0)", "def palindromicpartition(string):\n n = len(string)\n dp = [[False for i in range(n)] for _ in range(n)]\n for i in range(n):\n dp[i][i] = True\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if L == 2:\n dp[i][j] = string[i] == string[j]\n elif string[i] == string[j]:\n dp[i][j] = dp[i + 1][j - 1]\n c = [0] * n\n for i in range(1, n):\n if dp[0][i]:\n c[i] = 0\n else:\n c[i] = float('inf')\n for j in range(i):\n if dp[j + 1][i] and c[j] + 1 < c[i]:\n c[i] = c[j] + 1\n return c[n - 1]", "def palindromicpartition(string):\n n = len(string)\n\n def ispalindrome(strs, st, end):\n while st <= end:\n if strs[st] == strs[end]:\n st += 1\n end -= 1\n else:\n return False\n return True\n dp = [-1] * (n + 1)\n\n def findsol(string, i, n):\n if i == n:\n return 0\n if dp[i] != -1:\n return dp[i]\n minval = 999999999\n for x in range(i + 1, n + 1):\n if ispalindrome(string, i, x - 1) == True:\n minval = min(minval, findsol(string, x, n))\n dp[i] = minval + 1\n return minval + 1\n return findsol(string, 0, n) - 1", "def is_palindrome(string, i, j):\n while i < j:\n if string[i] != string[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef palindromicpartition(string):\n n = len(string)\n dp1 = [[False] * n for _ in range(n)]\n dp2 = [0] * n\n for i in range(n):\n dp1[i][i] = True\n for length in range(2, n + 1):\n for start in range(n - length + 1):\n end = start + length - 1\n if length == 2:\n dp1[start][end] = string[start] == string[end]\n else:\n dp1[start][end] = string[start] == string[end] and dp1[start + 1][end - 1]\n for i in range(n):\n if dp1[0][i]:\n dp2[i] = 0\n else:\n dp2[i] = float('inf')\n for j in range(i):\n if dp1[j + 1][i] and dp2[j] + 1 < dp2[i]:\n dp2[i] = dp2[j] + 1\n return dp2[n - 1]", "def palindromicpartition(s):\n N = len(string)\n dp = [[-1 for i in range(N + 2)] for j in range(N + 2)]\n\n def ispalindrome(s1):\n return s1 == s1[::-1]\n\n def solve(i, j):\n if i >= j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if ispalindrome(s[i:j + 1]):\n return 0\n ans = 999999\n for k in range(i, j):\n if ispalindrome(s[i:k + 1]):\n temp = solve(k + 1, j) + 1\n ans = min(ans, temp)\n dp[i][j] = ans\n return ans\n return solve(0, N - 1)", "def check(s):\n if s == s[::-1]:\n return True\n else:\n return False\n\ndef palindromicpartition(string):\n dp = {}\n\n def fun(s, i, j):\n if i >= j:\n return 0\n if check(s[i:j]):\n return 0\n if (i, j) in dp:\n return dp[i, j]\n m = float('inf')\n for k in range(i, j):\n if check(s[i:k + 1]):\n temp = fun(s, k + 1, j) + 1\n m = min(m, temp)\n dp[i, j] = m\n return dp[i, j]\n return fun(string, 0, len(string))", "def palindromicpartition(string):\n n = len(string)\n dp = [0] * (n + 1)\n dp[n] = 0\n for i in reversed(range(n)):\n minCost = float('inf')\n for j in range(i, n):\n cur_string = string[i:j + 1]\n if self.isPalindrome(cur_string):\n cost = 1 + dp[j + 1]\n minCost = min(minCost, cost)\n dp[i] = minCost\n return dp[0] - 1\n\ndef isPalindrome(cur_string):\n left = 0\n right = len(cur_string) - 1\n while left < right:\n if cur_string[left] != cur_string[right]:\n return False\n left += 1\n right -= 1\n return True", "def p(s):\n l = 0\n r = len(s) - 1\n while l < r:\n if s[l] != s[r]:\n return False\n l += 1\n r -= 1\n return True\n\ndef palindromicpartition(string):\n dp = [len(string) + 1 for i in range(len(string) + 1)]\n dp[0] = -1\n for i in range(1, len(string) + 1):\n for j in range(i):\n if self.p(string[j:i]):\n dp[i] = min(dp[i], 1 + dp[j])\n return dp[-1]", "def palindromicpartition(string):\n is_pali = [[False for i in range(len(string))] for j in range(len(string))]\n for k in range(len(string)):\n (i, j) = (0, k)\n while j < len(string):\n if k == 0:\n is_pali[i][j] = True\n elif k == 1:\n if string[i] == string[j]:\n is_pali[i][j] = True\n elif string[i] == string[j] and is_pali[i + 1][j - 1] is True:\n is_pali[i][j] = True\n i += 1\n j += 1\n dp = [float('inf')] * len(string)\n dp[0] = 0\n for i in range(1, len(string)):\n if is_pali[0][i] is True:\n dp[i] = 0\n else:\n for j in range(i, 0, -1):\n if is_pali[j][i] is True:\n dp[i] = min(dp[i], 1 + dp[j - 1])\n return dp[-1]", "def ispallindrome(string, i, j):\n if string == '':\n return False\n while i < j:\n if string[i] != string[j]:\n return False\n i += 1\n j += -1\n return True\n\ndef solve(arr, ind, dp):\n if ind == len(arr):\n return 0\n partition = 0\n MIN = float('inf')\n if dp[ind] != -1:\n return dp[ind]\n for i in range(ind, len(arr)):\n if ispallindrome(arr, ind, i):\n partition = 1 + self.solve(arr, i + 1, dp)\n MIN = min(MIN, partition)\n dp[ind] = MIN\n return MIN\n\ndef palindromicpartition(string):\n dp = [-1 for _ in range(len(string))]\n return self.solve(string, 0, dp) - 1", "def palindromicpartition(string):\n n = len(string)\n\n def ispalindrome(start, end, str):\n while start < end:\n if str[start] != str[end]:\n return False\n start += 1\n end -= 1\n return True\n dp = [0 for i in range(n + 1)]\n\n def rec(idx):\n if idx == n:\n return 0\n if dp[idx] != -1:\n return dp[idx]\n mini = int(1000000000.0)\n for i in range(idx, n):\n if ispalindrome(idx, i, string):\n cost = 1 + rec(i + 1)\n mini = min(mini, cost)\n dp[idx] = mini\n return dp[idx]\n for idx in range(n - 1, -1, -1):\n mini = int(1000000000.0)\n for i in range(idx, n):\n if ispalindrome(idx, i, string):\n cost = 1 + dp[i + 1]\n mini = min(mini, cost)\n dp[idx] = mini\n return dp[0] - 1", "def is_palindrome(s):\n return s == s[::-1]\n\ndef helper(s):\n if self.d.get(s) is not None:\n return self.d[s]\n if not s:\n return 0\n ans = 10 ** 9\n for i in range(len(s)):\n if is_palindrome(s[:i + 1]):\n ans = min(ans, 1 + self.helper(s[i + 1:]))\n self.d[s] = ans\n return ans\n\ndef palindromicpartition(string):\n self.d = {}\n return self.helper(string) - 1", "def palindromicpartition(s):\n\n def checkPalindrome(string, i, j):\n (l, r) = (i, j)\n while l < r:\n if string[l] != string[r]:\n return False\n l += 1\n r -= 1\n return True\n\n def solve(string, i, j, dp):\n if i >= j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if checkPalindrome(string, i, j):\n dp[i][j] = 0\n return 0\n ans = float('inf')\n for k in range(i, j):\n if checkPalindrome(string, i, k):\n temp = 1 + solve(string, k + 1, j, dp)\n ans = min(ans, temp)\n dp[i][j] = ans\n return ans\n n = len(s)\n dp = [[-1 for j in range(n + 1)] for i in range(n + 1)]\n ans = solve(s, 0, n - 1, dp)\n return ans", "def palindromicpartition(string):\n n = len(string)\n t = [[-1 for _ in range(n + 2)] for _ in range(n + 2)]\n\n def isPalin(s):\n return s == s[::-1]\n\n def solve(i, j):\n if i >= j:\n return 0\n if t[i][j] != -1:\n return t[i][j]\n if isPalin(string[i:j + 1]):\n return 0\n mn = int(1000000000.0)\n for k in range(i, j):\n if isPalin(string[i:k + 1]):\n temp = solve(k + 1, j) + 1\n mn = min(mn, temp)\n t[i][j] = mn\n return mn\n return solve(0, n - 1)", "def ispallindrome(s, i, j):\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef palindromicpartition(s):\n n = len(s)\n dp = [[-1 for i in range(501)] for j in range(501)]\n\n def helper(i, j):\n if i >= j:\n dp[i][j] = 0\n return dp[i][j]\n if dp[i][j] != -1:\n return dp[i][j]\n if self.ispallindrome(s, i, j):\n dp[i][j] = 0\n return 0\n ans = 510\n for k in range(i, j):\n if self.ispallindrome(s, i, k):\n temp = 1 + helper(i, k) + helper(k + 1, j)\n ans = min(ans, temp)\n dp[i][j] = ans\n return dp[i][j]\n return helper(0, n - 1)", "def palindromicpartition(string):\n n = len(string)\n dp = [[-1 for i in range(n + 1)] for j in range(n + 1)]\n\n def ispalindromic(string):\n return string == string[::-1]\n\n def func(string, i, j):\n if i >= j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if ispalindromic(string[i:j + 1]):\n return 0\n c = 100000\n for k in range(i, j):\n if ispalindromic(string[i:k + 1]):\n if dp[k + 1][j] != -1:\n c2 = dp[k + 1][j]\n else:\n c2 = func(string, k + 1, j)\n temp = c2 + 1\n c = min(c, temp)\n dp[i][j] = c\n return dp[i][j]\n return func(string, 0, n - 1)", "def palindromicpartition(str):\n n = len(str)\n dp = [0] * n\n palindrome = [[False] * n for _ in range(n)]\n for i in range(n):\n min_cut = i\n for j in range(i + 1):\n if str[i] == str[j] and (i - j < 2 or palindrome[j + 1][i - 1]):\n palindrome[j][i] = True\n if j == 0:\n min_cut = 0\n else:\n min_cut = min(min_cut, dp[j - 1] + 1)\n dp[i] = min_cut\n return dp[n - 1]", "import sys\n\ndef isPalindrome(str, i, j):\n while i < j:\n if str[i] != str[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef palindromicpartition(str):\n n = len(str)\n dp = [0] * (n + 1)\n for i in range(n - 1, -1, -1):\n mn = sys.maxsize\n for cut in range(i, n):\n if self.isPalindrome(str, i, cut):\n cost = 1 + dp[cut + 1]\n mn = min(mn, cost)\n dp[i] = mn\n return dp[0] - 1", "def fun(i, s, n, dp):\n if i == n:\n return 0\n if dp[i] != -1:\n return dp[i]\n temp = ''\n mini = float('inf')\n for j in range(i, n):\n temp += s[j]\n if temp == temp[::-1]:\n cost = 1 + self.fun(j + 1, s, n, dp)\n mini = min(mini, cost)\n dp[i] = mini\n return dp[i]\n\ndef palindromicpartition(string):\n dp = [-1 for i in range(len(string) + 1)]\n return self.fun(0, string, len(string), dp) - 1", "def palindromicpartition(S):\n\n def palind(f):\n l = len(f)\n for i in range(l // 2):\n if f[i] != f[l - i - 1]:\n return 0\n return 1\n\n def manu(i, n, s):\n if i == n:\n return 0\n if dp[i][n] != -1:\n return dp[i][n]\n x = ''\n mini = 10 ** 9\n for j in range(i, n):\n x += s[j]\n if palind(x):\n c = 1 + manu(j + 1, n, s)\n mini = min(mini, c)\n dp[i][n] = mini\n return mini\n dp = [[-1 for i in range(len(S) + 1)] for i in range(len(S) + 1)]\n return manu(0, len(S), S) - 1", "def palindromicpartition(string):\n n = len(string)\n c = [0] * n\n p = [[False for i in range(n)] for i in range(n)]\n for i in range(n):\n p[i][i] = True\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if L == 2:\n p[i][j] = string[i] == string[j]\n else:\n p[i][j] = string[i] == string[j] and p[i + 1][j - 1]\n for i in range(n):\n if p[0][i] == True:\n c[i] = 0\n else:\n c[i] = 25000\n for j in range(i):\n if p[j + 1][i] and c[j] + 1 < c[i]:\n c[i] = c[j] + 1\n return c[n - 1]", "def palindromicpartition(S):\n N = len(S)\n isp = [[True] * N for _ in range(N)]\n for add in range(1, N):\n for j in range(N - add):\n isp[j][j + add] = S[j] == S[j + add] and isp[j + 1][j + add - 1]\n dp = [1] * N + [0]\n for i in range(1, N):\n v = 1 + dp[i - 1]\n for j in range(i):\n if S[i] == S[j] and isp[j + 1][i - 1]:\n v = min(v, dp[j - 1] + 1)\n dp[i] = v\n return dp[N - 1] - 1", "import math\n\ndef solve(i, j, string, dp, ispall):\n if i > j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if ispall[i][j] == 1:\n dp[i][j] = 0\n return dp[i][j]\n currmin = float('INF')\n for p in range(i, j + 1):\n if ispall[i][p]:\n currmin = min(currmin, 1 + self.solve(p + 1, j, string, dp, ispall))\n dp[i][j] = currmin\n return dp[i][j]\n\ndef palindromicpartition(string):\n ispall = [[0 for i in range(len(string))] for t in range(len(string))]\n for i in range(len(string)):\n for j in range(i, len(string)):\n curr = string[i:j + 1]\n flag = 1\n (ptr1, ptr2) = (0, j - i)\n while ptr1 <= ptr2:\n if curr[ptr1] != curr[ptr2]:\n flag = 0\n break\n ptr1 += 1\n ptr2 -= 1\n ispall[i][j] = flag\n dp = [[-1 for i in range(len(string))] for t in range(len(string))]\n return self.solve(0, len(string) - 1, string, dp, ispall)", "def palindromicpartition(string):\n dp = [0 for i in range(len(string))]\n p = [[False for i in range(len(string))] for j in range(len(string))]\n for i in range(len(string)):\n m = i\n for j in range(i + 1):\n if string[i] == string[j] and (i - j < 2 or p[j + 1][i - 1]):\n p[j][i] = True\n m = min(m, 0 if j == 0 else dp[j - 1] + 1)\n dp[i] = m\n return dp[len(string) - 1]", "def palindromicpartition(s):\n n = len(s)\n dp = [0] * (n + 1)\n p = [[False] * (n + 1) for _ in range(n + 1)]\n for i in range(1, n + 1):\n cost = float('inf')\n for k in range(i, 0, -1):\n if s[k - 1] == s[i - 1] and (i - k <= 2 or p[k][i - 2]):\n p[k - 1][i - 1] = True\n curr = 1 + dp[k - 1]\n cost = min(cost, curr)\n dp[i] = cost\n return dp[n] - 1", "def palindromicpartition(s: str) -> int:\n n = len(s)\n dp = [[False] * n for _ in range(n)]\n cuts = [0] * n\n for i in range(n):\n dp[i][i] = True\n for j in range(i):\n if s[i] == s[j] and (i == j + 1 or dp[j + 1][i - 1]):\n dp[j][i] = True\n for i in range(n):\n if dp[0][i]:\n cuts[i] = 0\n else:\n cuts[i] = i\n for j in range(1, i + 1):\n if dp[j][i]:\n cuts[i] = min(cuts[i], cuts[j - 1] + 1)\n return cuts[n - 1]", "from functools import lru_cache\n\ndef palindromicpartition(s):\n n = len(s)\n dp = {}\n palindrome = [[False for _ in range(n)] for _ in range(n)]\n for i in range(n - 1, -1, -1):\n for j in range(i, n):\n if s[i] == s[j]:\n if j - i + 1 <= 2:\n palindrome[i][j] = True\n else:\n palindrome[i][j] = palindrome[i + 1][j - 1]\n\n def fun(i):\n if i == n:\n return 0\n if i in dp:\n return dp[i]\n minc = float('inf')\n for j in range(i, n):\n if palindrome[i][j]:\n minc = min(minc, 1 + fun(j + 1))\n dp[i] = minc\n return minc\n return fun(0) - 1", "from functools import lru_cache\n\ndef palindromicpartition(s):\n n = len(s)\n dp = {}\n\n def isPalindrome(l, r):\n r += 1\n d = (r - l) // 2\n for i in range(d):\n if s[l + i] != s[r - 1 - i]:\n return False\n return True\n\n def fun(i):\n if i == n:\n return 0\n if i in dp:\n return dp[i]\n minc = float('inf')\n for j in range(i, n):\n if isPalindrome(i, j):\n minc = min(minc, 1 + fun(j + 1))\n dp[i] = minc\n return minc\n return fun(0) - 1", "def chk(l, r, s):\n while l < r:\n if s[l] == s[r]:\n r -= 1\n l += 1\n else:\n return False\n return True\n\ndef f(l, r, s, dp):\n if (l, r) in dp:\n return dp[l, r]\n if chk(l, r, s):\n return 1\n ans = r - l + 1\n for i in range(l, r):\n if chk(l, i, s):\n ans = min(ans, 1 + f(i + 1, r, s, dp))\n dp[l, r] = ans\n return ans\n\ndef palindromicpartition(string):\n dp = {}\n s = list(string)\n return f(0, len(s) - 1, s, dp) - 1", "def isPalin(i, j, string):\n while i < j:\n if string[i] != string[j]:\n return False\n j -= 1\n i += 1\n return True\n\ndef recur(i, string, n, dp, dpP):\n if i == n:\n return 0\n if dp[i] != -1:\n return dp[i]\n mini = float('inf')\n for j in range(i, n):\n if self.isPalin(i, j, string):\n cost = 1 + self.recur(j + 1, string, n, dp, dpP)\n mini = min(mini, cost)\n dp[i] = mini\n return mini\n\ndef palindromicpartition(string):\n n = len(string)\n dp = [float('inf') for i in range(len(string))]\n dp.append(0)\n for i in range(n - 1, -1, -1):\n for j in range(i, n):\n if self.isPalin(i, j, string):\n cost = 1 + dp[j + 1]\n dp[i] = min(dp[i], cost)\n return dp[0] - 1", "import sys\n\ndef palindromicpartition(str1):\n n = len(str1)\n C = [0] * (n + 1)\n P = [[False for x in range(n + 1)] for y in range(n + 1)]\n for i in range(n):\n P[i][i] = True\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if L == 2:\n P[i][j] = str1[i] == str1[j]\n else:\n P[i][j] = str1[i] == str1[j] and P[i + 1][j - 1]\n for i in range(n):\n if P[0][i] == True:\n C[i] = 0\n else:\n C[i] = sys.maxsize\n for j in range(i):\n if P[j + 1][i] == True and 1 + C[j] < C[i]:\n C[i] = 1 + C[j]\n return C[n - 1]", "def palindromicpartition(string):\n i = 0\n j = len(string) - 1\n dp = [[-1 for i in range(len(string) + 1)] for j in range(len(string) + 1)]\n ans = self.solve(string, i, j, dp)\n return ans\n\ndef isPalindrome(string):\n return string == string[::-1]\n\ndef solve(string, i, j, dp):\n if i >= j or self.isPalindrome(string[i:j + 1]):\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if dp[i][j] != -1:\n return dp[i][j]\n mini = float('inf')\n for k in range(i, j):\n if self.isPalindrome(string[i:k + 1]):\n temp_ans = 1 + self.solve(string, k + 1, j, dp)\n if temp_ans < mini:\n mini = temp_ans\n dp[i][j] = mini\n return dp[i][j]", "def palindromicpartition(string):\n s = string\n\n def solve(s, i, j):\n if temp[i][j] != -1:\n return temp[i][j]\n if i >= j or s[i:j + 1] == s[i:j + 1][::-1]:\n return 0\n ans = float('infinity')\n for k in range(i, j):\n if s[i:k + 1] == s[i:k + 1][::-1]:\n left = solve(s, k + 1, j)\n tmp = 1 + left\n ans = min(ans, tmp)\n temp[i][j] = ans\n return temp[i][j]\n temp = [[-1] * 502 for i in range(502)]\n return solve(s, 0, len(s) - 1)", "def palindromicpartition(string):\n\n def pal(i, j):\n if i >= j or string[i:j + 1] == string[i:j + 1][::-1]:\n dp[i] = 0\n return 0\n if dp[i] != -1:\n return dp[i]\n count = 10 ** 10\n for k in range(i, j):\n count = min(count, pal(i, k) + pal(k + 1, j) + 1)\n dp[i] = count\n return count\n i = 0\n j = len(string)\n dp = [-1 for k in range(j + 1)]\n return pal(i, j)", "def palindromicpartition(str):\n n = len(str)\n P = [[False for _ in range(n)] for _ in range(n)]\n for i in range(n):\n P[i][i] = True\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if L == 2:\n P[i][j] = str[i] == str[j]\n else:\n P[i][j] = str[i] == str[j] and P[i + 1][j - 1]\n C = [float('inf') for _ in range(n)]\n for j in range(n):\n if P[0][j]:\n C[j] = 0\n else:\n for i in range(j):\n if P[i + 1][j]:\n C[j] = min(C[j], C[i] + 1)\n return C[n - 1]", "def palindromicpartition(str):\n n = len(str)\n dp = [[False] * n for i in range(n)]\n for g in range(0, n):\n for (i, j) in zip(range(0, n), range(g, n)):\n if g == 0:\n dp[i][j] = True\n elif g == 1:\n if str[i] == str[j]:\n dp[i][j] = True\n else:\n dp[i][j] = False\n elif str[i] == str[j] and dp[i + 1][j - 1] == True:\n dp[i][j] = True\n else:\n dp[i][j] = False\n if dp[0][n - 1] == True:\n return 0\n ans = [int(x) for x in range(n + 1)]\n ans[0] = 0\n ans[1] = 0\n ans[2] = 0\n if str[0] != str[1]:\n ans[2] += 1\n for i in range(3, n + 1):\n for j in range(i, 0, -1):\n if dp[j - 1][i - 1] == True:\n ans[i] = min(ans[i], ans[j - 1] + 1)\n return ans[n]", "import sys\n\ndef is_palindrome(strt, end, st):\n while strt < end:\n if st[strt] != st[end]:\n return False\n strt += 1\n end -= 1\n return True\n\ndef get_cuts(i, j, string, dp):\n if i >= j:\n return 0\n if self.is_palindrome(i, j, string):\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n ans = sys.maxsize\n curr_min = sys.maxsize\n for k in range(i, j):\n if self.is_palindrome(i, k, string):\n curr_min = 1 + self.get_cuts(k + 1, j, string, dp)\n ans = min(curr_min, ans)\n dp[i][j] = ans\n return ans\n\ndef palindromicpartition(string):\n dp = [[-1 for x in range(len(string) + 1)] for y in range(len(string) + 1)]\n return self.get_cuts(0, len(string) - 1, string, dp)", "import sys\nsys.setrecursionlimit(10 ** 7)\n\ndef palindromicpartition(string):\n d = dict()\n\n def dfs(s, i, j):\n if i == j:\n s1 = s[i:j + 1]\n if s1 == s1[::-1]:\n return -1\n return 10 ** 9\n if d.get((i, j)) != None:\n return d[i, j]\n y = 10 ** 9\n for k in range(i, j):\n s1 = s[i:k + 1]\n if s1 == s1[::-1]:\n a = 1 + dfs(s, k + 1, j)\n y = min(y, a)\n d[i, j] = y\n return y\n return dfs(string, 0, len(string))", "def palindromicpartition(string):\n S = string\n n = len(S)\n hmap = {}\n\n def is_palindrome(s, i, j):\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n\n def palin_partition(arr, i, j):\n if i >= j or is_palindrome(arr, i, j):\n hmap[i, j] = 0\n return 0\n mini = 1000000000.0\n if (i, j) not in hmap:\n for k in range(i, j):\n if is_palindrome(arr, i, k):\n if (k + 1, j) not in hmap:\n hmap[k + 1, j] = palin_partition(arr, k + 1, j)\n temp_ans = 1 + hmap[k + 1, j]\n mini = min(mini, temp_ans)\n hmap[i, j] = mini\n return hmap[i, j]\n return palin_partition(S, 0, n - 1)", "def palindromicpartition(string):\n n = len(string)\n dp = [[-1 for i in range(n)] for j in range(n)]\n\n def recursive(string, left=0, right=n - 1):\n if left > right:\n return True\n if left == right:\n dp[left][right] = True\n return True\n if dp[left][right] != -1:\n return dp[left][right]\n if string[left] == string[right]:\n dp[left][right] = recursive(string, left + 1, right - 1)\n else:\n dp[left][right] = False\n recursive(string, left + 1, right)\n recursive(string, left, right - 1)\n return dp[left][right]\n recursive(string)\n dp2 = [[-1 for i in range(n)] for j in range(n)]\n\n def findminimum(string, dp, dp2, left=0, right=0):\n if right == len(string) == left:\n return 0\n if left > right or right >= len(string):\n return float('inf')\n if dp[left][right] != -1:\n return dp[left][right]\n dp[left][right] = findminimum(string, dp, dp2, left, right + 1)\n if dp2[left][right]:\n dp[left][right] = min(dp[left][right], 1 + findminimum(string, dp, dp2, right + 1, right + 1))\n return dp[left][right]\n return findminimum(string, dp2, dp) - 1", "from math import *\n\ndef solve(i, j, string, dp, grid):\n if grid[i][j]:\n return 0\n if (i, j) in dp:\n return dp[i, j]\n cnt = inf\n for k in range(i, j):\n cnt = min(cnt, 1 + self.solve(i, k, string, dp, grid) + self.solve(k + 1, j, string, dp, grid))\n dp[i, j] = cnt\n return cnt\n\ndef palindromicpartition(string):\n n = len(string)\n palindrom_grid = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(i, n):\n if i == j:\n palindrom_grid[i][j] = 1\n for i in range(n - 2, -1, -1):\n for j in range(n - 1, i, -1):\n if string[i] == string[j] and (palindrom_grid[i + 1][j - 1] or i + 1 == j):\n palindrom_grid[i][j] = 1\n dp = [inf] * n\n dp[0] = 0\n for j in range(1, n):\n if palindrom_grid[0][j]:\n dp[j] = 0\n else:\n for i in range(j, 0, -1):\n if palindrom_grid[i][j]:\n dp[j] = min(dp[j], 1 + dp[i - 1])\n return dp[-1]\n n = len(string)\n palindrom_grid = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(i, n):\n if i == j:\n palindrom_grid[i][j] = 1\n for i in range(n - 2, -1, -1):\n for j in range(n - 1, i, -1):\n if string[i] == string[j] and (palindrom_grid[i + 1][j - 1] or i + 1 == j):\n palindrom_grid[i][j] = 1\n dp = [[inf] * n for _ in range(n)]\n for i in range(n):\n for j in range(i, n):\n if palindrom_grid[i][j]:\n dp[i][j] = 0\n else:\n for k in range(i, j):\n dp[i][j] = min(dp[i][j], 1 + (0 if palindrom_grid[i][k] else dp[i][k]) + (0 if palindrom_grid[k + 1][j] else dp[k + 1][j]))\n return dp[0][-1]\n dp = {}\n n = len(string)\n palindrom_grid = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(i, n):\n if i == j:\n palindrom_grid[i][j] = 1\n for i in range(n - 2, -1, -1):\n for j in range(n - 1, i, -1):\n if string[i] == string[j] and (palindrom_grid[i + 1][j - 1] or i + 1 == j):\n palindrom_grid[i][j] = 1\n return self.solve(0, n - 1, string, dp, palindrom_grid)", "def palindromicpartition(string):\n mp = {}\n res = self.solve(string, mp)\n return res\n\ndef solve(string, mp):\n if len(string) == 0 or string == string[::-1]:\n return 0\n if string in mp:\n return mp[string]\n res = float('inf')\n for i in range(len(string)):\n prefix = string[:i + 1]\n if prefix == prefix[::-1]:\n res = min(res, 1 + self.solve(string[i + 1:], mp))\n mp[string] = res\n return res", "def palindromicpartition(string):\n\n def ispallindrome(s, i, j, dp):\n if i >= j:\n dp[i][j] = 0\n return dp[i][j]\n if s[i] == s[j]:\n dp[i][j] = ispallindrome(s, i + 1, j - 1, dp)\n return dp[i][j]\n return dp[i][j]\n\n def helper(s, i, j, dp):\n if i >= j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if ispallindrome(s, i, j, dp) == 0:\n dp[i][j] = 0\n return dp[i][j]\n ans = float('inf')\n for k in range(i, j):\n if dp[i][k] != -1:\n left = dp[i][k]\n else:\n left = ispallindrome(s, i, k, dp)\n dp[i][k] = left\n if left != 0:\n continue\n if dp[k + 1][j] != -1:\n right = dp[k + 1][j]\n else:\n right = helper(s, k + 1, j, dp)\n dp[k + 1][j] = right\n temp_ans = helper(s, k + 1, j, dp) + 1\n ans = min(ans, temp_ans)\n dp[i][j] = ans\n return dp[i][j]\n dp = [[-1] * len(string) for i in range(len(string))]\n return helper(string, 0, len(string) - 1, dp)"], "starter_code": "def palindromicpartition(string):\n", "input_output": {"inputs": ["str = \"ababbbabbababa\"", "str = \"aaabba\""], "outputs": ["3", "1"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/palindromic-patitioning4845/1", "Expected Auxiliary Space": "O(n*n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n*n) [n is the length of the string str]", "entry_point": "palindromicpartition", "task_id": "TACO_lite/260", "example": [[["ababbbabbababa"], ["aaabba"]], ["3", "1"]]} +{"requirement": "I've got a crazy mental illness.\nI dislike numbers a lot. But it's a little complicated:\nThe number I'm afraid of depends on which day of the week it is...\nThis is a concrete description of my mental illness:\n\nMonday --> 12\n\nTuesday --> numbers greater than 95\n\nWednesday --> 34\n\nThursday --> 0\n\nFriday --> numbers divisible by 2\n\nSaturday --> 56\n\nSunday --> 666 or -666\n\n\nWrite a function which takes a string (day of the week) and an integer (number to be tested) so it tells the doctor if I'm afraid or not. (return a boolean)", "solutions": ["def am_i_afraid(day, num):\n return {'Monday': num == 12, 'Tuesday': num > 95, 'Wednesday': num == 34, 'Thursday': num == 0, 'Friday': num % 2 == 0, 'Saturday': num == 56, 'Sunday': num == 666 or num == -666}[day]", "afraid = {'Monday': lambda x: x == 12, 'Tuesday': lambda x: x > 95, 'Wednesday': lambda x: x == 34, 'Thursday': lambda x: x == 0, 'Friday': lambda x: x % 2 == 0, 'Saturday': lambda x: x == 56, 'Sunday': lambda x: abs(x) == 666}\n\ndef am_i_afraid(day, num):\n return afraid[day](num)", "def am_i_afraid(day, x):\n return {'Mo': x == 12, 'Tu': x > 95, 'We': x == 34, 'Th': x == 0, 'Fr': x % 2 == 0, 'Sa': x == 56, 'Su': abs(x) == 666}[day[:2]]", "FUNCS = dict(zip('Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(), (12.0.__eq__, 95.0.__lt__, 34.0.__eq__, 0.0.__eq__, lambda n: not n % 2, 56.0.__eq__, lambda n: abs(n) == 666)))\n\ndef am_i_afraid(day, n):\n return FUNCS[day](n)", "def am_i_afraid(day, num):\n rep = False\n lst1 = [('monday', 12), ('wednesday', 34), ('thursday', 0), ('saturday', 56), ('sunday', 666), ('sunday', -666)]\n input = (day.lower(), num)\n if input in lst1 or (input[0] == 'tuesday' and input[1] > 95) or (input[0] == 'friday' and input[1] % 2 == 0):\n rep = True\n return rep", "def am_i_afraid(day, num):\n if day == 'Monday' and num == 12:\n return True\n if day == 'Tuesday' and num > 95:\n return True\n if day == 'Wednesday' and num == 34:\n return True\n if day == 'Thursday' and num == 0:\n return True\n if day == 'Friday' and num % 2 == 0:\n return True\n if day == 'Saturday' and num == 56:\n return True\n if day == 'Sunday' and abs(num) == 666:\n return True\n return False"], "starter_code": "def am_i_afraid(day,num):\n", "input_output": {"fn_name": "am_I_afraid", "inputs": [["Monday", 13], ["Monday", 12], ["Tuesday", 0], ["Tuesday", 100], ["Tuesday", 95], ["Wednesday", 35], ["Wednesday", 34], ["Thursday", 2], ["Thursday", 0], ["Friday", 5], ["Friday", 4], ["Saturday", 55], ["Saturday", 56], ["Sunday", 55], ["Sunday", 666], ["Sunday", -666]], "outputs": [[false], [true], [false], [true], [false], [false], [true], [false], [true], [false], [true], [false], [true], [false], [true], [true]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/55b1fd84a24ad00b32000075", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "am_i_afraid", "task_id": "TACO_lite/145", "example": [[], []]} +{"requirement": "Given an array of N positive integers, print k largest elements from the array. \nExample 1:\nInput:\nN = 5, k = 2\narr[] = {12,5,787,1,23}\nOutput: 787 23\nExplanation: First largest element in\nthe array is 787 and the second largest\nis 23.\nExample 2:\nInput:\nN = 7, k = 3\narr[] = {1,23,12,9,30,2,50}\nOutput: 50 30 23\nExplanation: Three Largest element in\nthe array are 50, 30 and 23.\nYour Task:\nComplete the function kLargest() that takes the array, N and K as input parameters and returns a list of k largest element in descending order. \nExpected Time Complexity: O(N log K)\nExpected Auxiliary Space: O(K)\nConstraints:\n1 \u2264 N \u2264 10^{4}\nK \u2264 N\n1 \u2264 array[i] \u2264 10^{5}", "solutions": ["import heapq\n\ndef klargest(li, n, k):\n pq = []\n ans = []\n n = len(li)\n for i in range(n):\n heapq.heappush(pq, -li[i])\n f = k\n while f > 0:\n a = heapq.heappop(pq)\n ans.append(-a)\n f -= 1\n return ans", "def klargest(li, n, k):\n a = []\n l = sorted(li)\n for i in range(-1, -k - 1, -1):\n a.append(l[i])\n return a", "def klargest(li, n, k):\n li.sort()\n c = 0\n i = -1\n a = []\n while c < k:\n a.append(li[i])\n i -= 1\n c += 1\n return a", "import heapq\n\ndef klargest(li, n, k):\n for i in range(n):\n li[i] = li[i] * -1\n heapq.heapify(li)\n ans = []\n for i in range(k):\n ans.append(-1 * heapq.heappop(li))\n return ans", "def klargest(li, n, k):\n op = []\n li.sort(reverse=True)\n for i in range(k):\n op.append(li[i])\n return op", "def klargest(li, n, k):\n li.sort(reverse=True)\n return li[:k]", "def klargest(li, n, k):\n list = []\n li.sort()\n li = li[::-1]\n for i in range(k):\n list.append(li[i])\n return list", "def klargest(li, n, k):\n li.sort()\n return li[n - k:][::-1]", "def klargest(li, n, k):\n l = sorted(li)[::-1]\n return l[:k]", "def klargest(li, n, k):\n l = []\n li.sort()\n li.reverse()\n for i in range(0, k):\n l.append(li[i])\n return l", "def klargest(li, n, k):\n li.sort()\n ans = []\n count = -1\n while k != 0:\n ans.append(li[count])\n k -= 1\n count -= 1\n return ans", "def klargest(arr, n, k):\n arr.sort()\n arr.reverse()\n return arr[:k]", "import heapq\n\ndef klargest(li, n, k):\n heap = []\n for value in li:\n heapq.heappush(heap, value)\n if len(heap) > k:\n heapq.heappop(heap)\n ans = []\n while len(heap) > 0:\n ans.append(heapq.heappop(heap))\n ans.reverse()\n return ans", "def klargest(arr, n, k):\n return sorted(arr)[::-1][:k]", "def klargest(li, n, k):\n newarr = []\n li.sort(reverse=True)\n while k > 0:\n newarr.append(li[0])\n li.pop(0)\n k -= 1\n return newarr", "import heapq\n\ndef klargest(arr, n, k):\n heap = []\n for i in arr:\n heapq.heappush(heap, i)\n if len(heap) > k:\n heapq.heappop(heap)\n result = []\n for i in range(len(heap)):\n result.append(heapq.heappop(heap))\n result.reverse()\n return result", "import heapq\n\ndef klargest(li, n, k):\n ans = []\n heapq.heapify(ans)\n for i in range(n):\n heapq.heappush(ans, li[i])\n if len(ans) > k:\n heapq.heappop(ans)\n main = []\n while len(ans):\n main.append(heapq.heappop(ans))\n main.reverse()\n return main", "import heapq\n\ndef klargest(arr, n, k):\n heap = []\n for i in arr:\n heapq.heappush(heap, -1 * i)\n result = []\n for i in range(k):\n result.append(-1 * heapq.heappop(heap))\n return result", "from heapq import *\n\ndef klargest(arr, n, k):\n maxheap = []\n for i in arr:\n heappush(maxheap, -i)\n ans = []\n for i in range(k):\n ans.append(-heappop(maxheap))\n return ans\n\ndef klargest(arr, n, k):\n arr = sorted(arr, reverse=True)\n return arr[:k]", "from heapq import *\n\ndef klargest(arr, n, k):\n maxheap = []\n for i in arr:\n heappush(maxheap, -i)\n ans = []\n for i in range(k):\n ans.append(-heappop(maxheap))\n return ans", "def klargest(li, n, k):\n m = sorted(li)\n p = m[-k:][::-1]\n return p", "def klargest(li, n, k):\n list_a = sorted(li, reverse=True)\n return list_a[:k]", "def klargest(li, n, k):\n x = sorted(li)\n x.reverse()\n lis = []\n for i in range(k):\n lis.append(x[i])\n return lis", "import heapq\n\ndef klargest(li, n, k):\n return heapq.nlargest(k, li)", "import heapq\n\ndef klargest(li, n, k):\n minh = []\n heapq.heapify(minh)\n ans = []\n for i in li:\n heapq.heappush(minh, i)\n if len(minh) > k:\n heapq.heappop(minh)\n while minh:\n x = heapq.heappop(minh)\n ans.append(x)\n return ans[::-1]", "import heapq\n\ndef klargest(li, n, k):\n heapq._heapify_max(li)\n klargest = list()\n while k:\n element = heapq._heappop_max(li)\n klargest.append(element)\n k = k - 1\n return klargest", "def klargest(li, n, k):\n li = sorted(li)[::-1]\n n = []\n for i in range(k):\n n += [li[i]]\n return n", "import heapq\n\ndef klargest(li, n, k):\n l = []\n l2 = []\n for i in li:\n heapq.heappush(l, -i)\n while k != 0:\n l2.append(-heapq.heappop(l))\n k -= 1\n return l2", "from heapq import heapify, heappush, heappop\n\ndef klargest(a, n, k):\n h = []\n heapify(h)\n for el in a:\n heappush(h, el)\n if len(h) > k:\n heappop(h)\n res = []\n while h:\n res.append(heappop(h))\n return sorted(res, reverse=True)", "import heapq\n\ndef klargest(arr, n, k):\n queue = []\n for i in range(n):\n heapq.heappush(queue, arr[i])\n want = n - k\n while want > 0:\n heapq.heappop(queue)\n want -= 1\n return sorted(queue, reverse=True)", "def klargest(li, n, k):\n i = 0\n t = []\n li = sorted(li)\n m = -1\n while i < k:\n t.append(li[m])\n m = m - 1\n i = i + 1\n return t", "def klargest(li, n, k):\n li = sorted(li)\n li = li[::-1]\n return li[0:k]", "def klargest(li, n, k):\n s = sorted(li)\n return s[n - k:][::-1]", "def klargest(li, n, k):\n li = sorted(li)\n l = []\n while k != 0:\n l.append(li.pop())\n k -= 1\n return l", "import heapq\n\ndef klargest(arr, n, k):\n li = []\n for i in range(len(arr)):\n heapq.heappush(li, arr[i])\n if len(li) > k:\n heapq.heappop(li)\n li.sort(reverse=1)\n return li", "import heapq as hq\n\ndef klargest(li, n, k):\n hq.heapify(li)\n return hq.nlargest(k, li)", "def klargest(li, n, k):\n ans = []\n li.sort()\n c = 0\n for i in range(n - 1, -1, -1):\n c += 1\n if c > k:\n break\n ans.append(li[i])\n return ans", "def klargest(li, n, k):\n li.sort()\n a = li\n a = a[::-1]\n b = []\n for i in range(k):\n b.append(a[i])\n return b", "def klargest(li, n, k):\n ar = []\n li.sort()\n i = n - 1\n p = 0\n while p < k:\n ar.append(li[i])\n i = i - 1\n p = p + 1\n return ar", "def klargest(li, n, k):\n li = sorted(li)\n a = []\n p = 0\n q = len(li) - 1\n for i in range(q, 0, -1):\n p += 1\n if p <= k:\n a.append(li[i])\n return a", "import heapq\n\ndef klargest(li, n, k):\n heapq.heapify(li)\n for i in range(n - k):\n heapq.heappop(li)\n li.sort()\n li.reverse()\n return li", "def klargest(li, n, k):\n li.sort()\n x = li[n - k:]\n x.reverse()\n return x", "import heapq\n\ndef klargest(li, n, k):\n if k > n:\n return li.sort(reverse=True)\n li.sort(reverse=True)\n return li[0:k]", "def klargest(li, n, k):\n li.sort()\n c = []\n for i in range(k):\n c.append(li[-1])\n li.pop()\n return c", "from heapq import *\n\ndef klargest(li, n, k):\n mi = []\n for i in li:\n if len(mi) < k:\n heappush(mi, i)\n else:\n heappush(mi, i)\n heappop(mi)\n return sorted(mi)[::-1]", "import heapq\n\ndef klargest(li, n, k):\n mylist = []\n heapq.heapify(mylist)\n for i in range(n):\n heapq.heappush(mylist, li[i])\n if len(mylist) > k:\n heapq.heappop(mylist)\n res = []\n while len(mylist) > 0:\n res.append(heapq.heappop(mylist))\n res.reverse()\n return res", "import heapq\n\ndef klargest(li, n, k):\n heap = []\n list1 = []\n for i in li:\n heapq.heappush(heap, i)\n if len(heap) > k:\n heapq.heappop(heap)\n while len(heap) > 0:\n list1.insert(0, heapq.heappop(heap))\n return list1", "import heapq\n\ndef klargest(li, n, k):\n a = []\n heapq.heapify(a)\n for i in range(n):\n heapq.heappush(a, li[i])\n if len(a) > k:\n heapq.heappop(a)\n a.sort(reverse=True)\n return a", "import heapq\n\ndef klargest(li, n, k):\n kq = []\n for i in range(k):\n heapq.heappush(kq, li[i])\n for k in li[k:]:\n heapq.heappush(kq, max(k, heapq.heappop(kq)))\n return sorted(kq)[::-1]", "def klargest(li, n, k):\n a = []\n if len(set(li)) == 1:\n return [-1]\n li = sorted(li)\n for i in range(1, k + 1):\n i = i * -1\n a.append(li[i])\n return a", "import heapq\n\ndef klargest(li, n, k):\n l = []\n size = 0\n for i in range(n):\n heapq.heappush(l, li[i])\n size = size + 1\n if size > k:\n heapq.heappop(l)\n size = size - 1\n l.sort(reverse=True)\n return l", "def klargest(li, n, k):\n li.sort()\n list_return = []\n for i in li[:-k - 1:-1]:\n list_return.append(i)\n return list_return", "def klargest(li, n, k):\n from heapq import heapify, heappush, heappop\n h = []\n heapify(h)\n for i in li:\n heappush(h, i)\n if len(h) > k:\n heappop(h)\n h.sort(reverse=True)\n return h", "def klargest(li, n, k):\n from heapq import heapify, heappush, heappop\n kt = []\n for i in range(n):\n heappush(kt, -li[i])\n i = 0\n ans = []\n while i < k:\n ans.append(-heappop(kt))\n i += 1\n return ans", "def klargest(li, n, k):\n count = 0\n li.sort(reverse=True)\n return li[:k:1]", "def maxheapify(arr, n, i):\n while True:\n largest = i\n left = 2 * i + 1\n right = 2 * i + 2\n if left < n and arr[left] > arr[largest]:\n largest = left\n if right < n and arr[right] > arr[largest]:\n largest = right\n if largest != i:\n (arr[i], arr[largest]) = (arr[largest], arr[i])\n i = largest\n else:\n break\n\ndef klargest(arr, n, k):\n for i in range(n // 2 - 1, -1, -1):\n self.maxheapify(arr, n, i)\n result = []\n for i in range(n - 1, n - k - 1, -1):\n result.append(arr[0])\n (arr[0], arr[i]) = (arr[i], arr[0])\n self.maxheapify(arr, i, 0)\n return result"], "starter_code": "def klargest(li,n,k):\n", "input_output": {"inputs": ["N = 5, k = 2\r\narr[] = {12,5,787,1,23}", "N = 7, k = 3\r\narr[] = {1,23,12,9,30,2,50}"], "outputs": ["787 23", "50 30 23"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Heap"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/k-largest-elements3736/1", "Expected Auxiliary Space": "O(K)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N log K)", "entry_point": "klargest", "task_id": "TACO_lite/220", "example": [[[5, 2, [12, 5, 787, 1, 23]], [7, 3, [1, 23, 12, 9, 30, 2, 50]]], [null, null]]} +{"requirement": "Given a string s consisting of uppercase and lowercase alphabetic characters. Return the number of distinct substrings of size 2 that appear in s as contiguous substrings.\nExample\nInput :\ns = \"ABCAB\"\nOutput :\n3\nExplanation: For \"ABCAB\", the \nthree distinct substrings of size \n2 are \"AB\", \"BC\" and \"CA\". \nExample\nInput :\ns = \"XYZ\"\nOutput :\n2\nExplanation: For \"XYZ\", the \ntwo distinct substrings of size 2 are\n\"XY\" and \"YZ\".\nYour Task :\nYou don't need to read input or print anything. You have to complete the function fun() which takes the string s as input parameter and returns the number of distinct contiguous substring of size 2.\nExpected Time Complexity : O(|s|)\nExpected Auxilliary Space : O(|s|)\nConstraints:\n1<=|s|<=100\n|s| denotes the length of the string s.", "solutions": ["def fun(s):\n d = {}\n for i in range(len(s) - 1):\n if (s[i] and s[i + 1]) not in d:\n d[s[i], s[i + 1]] = 1\n else:\n d[s[i], s[i + 1]] += 1\n return len(d)", "from collections import defaultdict\n\ndef fun(s):\n hmap = defaultdict(int)\n for i in range(0, len(s) - 1):\n if s[i] and s[i + 1] not in hmap:\n hmap[s[i], s[i + 1]] = 1\n else:\n hmap[s[i], s[i + 1]] += 1\n return len(hmap)", "def fun(s):\n us = set()\n for i in range(1, len(s)):\n us.add(s[i - 1] + s[i])\n return len(us)", "def fun(s):\n dict = {}\n count = 0\n for i in range(len(s) - 1):\n sub = s[i] + s[i + 1]\n if dict.get(sub) == None:\n count += 1\n dict.update({sub: 1})\n return count", "def fun(s):\n hash = set()\n for i in range(0, len(s) - 1):\n hash.add(s[i:i + 2])\n return len(hash)", "def fun(s):\n res = set()\n for i in range(len(s) - 1):\n t = s[i:i + 2]\n res.add(t)\n return len(res)", "def fun(s):\n hmap = {}\n count = 0\n for i in range(len(s) - 1):\n temp = s[i] + s[i + 1]\n if temp in hmap:\n hmap[temp] += 1\n else:\n hmap[temp] = 1\n return len(hmap)", "def fun(s):\n l = []\n for i in range(len(s) - 2 + 1):\n if s[i:i + 2] not in l:\n l.append(s[i:i + 2])\n return len(l)", "def fun(s):\n d = {}\n if len(s) == 2:\n return 1\n elif len(s) < 2:\n return 0\n else:\n for i in range(len(s) - 1):\n a = s[i:i + 2]\n if a not in d:\n d[a] = 1\n return len(d)", "def fun(s):\n b = []\n for i in range(len(s) - 1):\n b.append(s[i:i + 2])\n c = set(b)\n d = len(c)\n return d", "def fun(s):\n substr_set = set()\n for i in range(len(s) - 1):\n if s[i:i + 2] not in substr_set:\n substr_set.add(s[i:i + 2])\n return len(substr_set)", "def fun(s):\n n = len(s)\n st = set()\n for i in range(n - 1):\n string = s[i:i + 2]\n st.add(string)\n return len(st)", "def fun(s):\n return len(set([s[i:i + 2] for i in range(len(s) - 1)]))", "def fun(s):\n new_set = set()\n for a in range(0, len(s)):\n if a == len(s) - 1:\n B = s[a - 1] + s[a]\n else:\n B = s[a] + s[a + 1]\n new_set.add(B)\n return len(new_set)", "def fun(s):\n res = []\n i = 0\n while i < len(s) - 1:\n if [s[i].lower(), s[i + 1].lower()] not in res:\n res.append([s[i].lower(), s[i + 1].lower()])\n i += 1\n return len(res)", "def fun(s):\n A = []\n for i in range(len(s) - 1):\n X = s[i:i + 2]\n if X not in A and X[-1] not in A:\n A.append(X)\n return len(A)", "def fun(s):\n ans = 0\n li = []\n for i in range(len(s)):\n if s[i:i + 2] != s[i + 1:i + 3] and s[i:i + 2] not in li:\n li.append(s[i:i + 2])\n ans += 1\n return ans - 1", "def fun(s):\n l = []\n c = 0\n for i in range(len(s)):\n if s[i:i + 2] != s[i + 1:i + 3] and s[i:i + 2] not in l:\n c += 1\n l.append(s[i:i + 2])\n return c - 1", "def fun(s):\n l = []\n st = ''\n for i in range(len(s) - 1):\n st = s[i] + s[i + 1]\n l.append(st)\n return len(set(l))", "def fun(s):\n i = 0\n l = []\n while i < len(s) - 1:\n if s[i:i + 2] not in l:\n l.append(s[i:i + 2])\n i += 1\n return len(l)", "def fun(s):\n res = []\n n = len(s)\n for i in range(n - 1):\n temp = s[i] + s[i + 1]\n if temp not in res:\n res.append(temp)\n return len(res)", "def fun(s):\n n = len(s)\n m = {}\n for i in range(n - 1):\n t = s[i] + s[i + 1]\n m[t] = 1\n return len(m)", "def fun(s):\n list1 = []\n for i in range(1, len(s)):\n if s[i - 1:i + 1] not in list1:\n list1.append(s[i - 1:i + 1])\n else:\n pass\n return len(list1)", "def fun(s):\n res = 0\n seen = set()\n for i in range(len(s) - 1):\n if s[i:i + 2] not in seen:\n res += 1\n seen.add(s[i:i + 2])\n return res", "def fun(s):\n a = 0\n x = []\n while a < len(s) - 1:\n c = s[a:a + 2]\n if c not in x:\n x.append(c)\n a += 1\n return len(x)", "def fun(s):\n k = {}\n for i in range(len(s) - 1):\n tmp = s[i:i + 2]\n if tmp not in k.keys():\n k[tmp] = 1\n else:\n k[tmp] += 1\n return len(k)", "def fun(s):\n hashset = set()\n (l, r) = (0, 1)\n while r < len(s):\n sub = s[l] + s[r]\n hashset.add(sub)\n l += 1\n r += 1\n return len(hashset)", "def fun(s):\n d = []\n for i in range(0, len(s) - 1):\n x = s[i] + s[i + 1]\n if x in d:\n continue\n else:\n d.append(x)\n return len(d)", "def fun(s):\n s = list(s)\n count = 0\n dset = []\n for i in range(len(s) - 1):\n a = str(s[i] + s[i + 1])\n if a in dset:\n continue\n else:\n dset.append(a)\n count += 1\n return count", "def fun(s):\n s = list(s)\n count = 0\n d = {}\n for i in range(len(s) - 1):\n a = str(s[i] + s[i + 1])\n if a in d.keys():\n continue\n else:\n d[a] = 1\n count += 1\n return count", "def fun(s):\n substr = []\n for i in range(len(s) - 1):\n substr.append(s[i:i + 2])\n substr = list(set(substr))\n return len(substr)", "def fun(s):\n d = set()\n for i in range(len(s) - 1):\n st = s[i] + s[i + 1]\n d.add(st)\n return len(d)", "def fun(s):\n n = len(s)\n m = {}\n m[s[0:2]] = 1\n for i in range(1, n):\n if i + 1 < n:\n if s[i:i + 2] in m:\n m[s[i:i + 2]] += 1\n else:\n m[s[i:i + 2]] = 1\n return len(m)", "from collections import defaultdict\n\ndef fun(s):\n d = defaultdict(int)\n for i in range(len(s) - 1):\n temp = ''\n temp = s[i] + s[i + 1]\n d[temp] += 1\n return len(d.keys())", "def fun(s):\n dict_ = {}\n for i in range(len(s) - 1):\n ss = s[i:i + 2]\n if ss not in dict_:\n dict_[ss] = 1\n else:\n dict_[ss] += 1\n return len(dict_)", "def fun(s):\n i = -1\n j = -1\n count = 0\n st = ''\n dict = {}\n for i in range(len(s) - 1):\n st = s[i:i + 2]\n sorted(st)\n if st not in dict:\n dict[st] = 1\n count += 1\n return count", "def fun(s):\n res = []\n i = 0\n j = 2\n n = len(s)\n while j <= n:\n res.append(s[i:j])\n j += 1\n i += 1\n res.sort()\n l = len(res)\n i = 0\n r = [res[0]]\n while i < l:\n if res[i] != r[-1]:\n r.append(res[i])\n i += 1\n return len(r)", "def fun(s):\n ans = []\n for i in range(len(s) - 1):\n a = s[i] + s[i + 1]\n ans.append(a)\n return len(set(ans))", "def fun(s):\n i = 0\n j = 1\n ss = set()\n while j < len(s):\n ss.add(s[i] + s[j])\n i += 1\n j += 1\n return len(ss)", "from collections import defaultdict\n\ndef fun(s):\n c = 0\n d = defaultdict(lambda : 0)\n for i in range(0, len(s) - 1):\n x = s[i:i + 2]\n d[x] += 1\n if d[x] == 1:\n c += 1\n return c", "def fun(s):\n dic = {}\n for i in range(len(s) - 1):\n try:\n dic[s[i:i + 2]] += 1\n except:\n dic[s[i:i + 2]] = 1\n return len(dic)", "def fun(s):\n h_map = {}\n n = len(s)\n for i in range(len(s) - 1):\n if s[i] + s[i + 1] in h_map:\n h_map[s[i] + s[i + 1]] += 1\n else:\n h_map[s[i] + s[i + 1]] = 1\n return len(h_map)", "def fun(s):\n arr = []\n for i in range(len(s) - 1):\n p = ''\n p = s[i] + s[i + 1]\n arr.append(p)\n return len(set(arr))", "def fun(s):\n substrings = [s[i] + s[i + 1] for i in range(len(s) - 1)]\n return len(list(set(substrings)))", "def fun(s):\n c = 0\n ss = set()\n for i in range(0, len(s)):\n for j in range(i + 1, len(s) + 1):\n if len(s[i:j]) == 2 and s[i:j] not in ss:\n ss.add(s[i:j])\n return len(ss)", "def fun(s):\n dict1 = {}\n for i in range(0, len(s)):\n if s[i:i + 2] not in dict1:\n dict1[s[i:i + 2]] = 1\n count = 0\n result_str = ''\n for i in dict1:\n if len(i) == 2:\n result_str += i + ' '\n count += 1\n return count", "def fun(s):\n l = []\n for x in range(len(s) - 1):\n a = s[x] + s[x + 1]\n l.append(a)\n return len(set(l))", "def fun(s):\n substring = []\n index = 1\n pre_index = 0\n while index < len(s):\n new_str = str(s[pre_index]) + str(s[index])\n if new_str not in substring:\n substring.append(new_str)\n index += 1\n pre_index += 1\n return len(substring)", "def fun(s):\n sp = []\n for i in range(0, len(s) - 1):\n u = s[i:i + 2]\n sp.append(u)\n ans = int(len(list(set(sp))))\n return ans", "def fun(s):\n t = []\n n = len(s)\n for i in range(0, n - 1):\n u = s[i:i + 2]\n t.append(u)\n ans = set(t)\n return len(ans)", "import math\n\ndef fun(s):\n l = []\n for i in range(len(s) - 1):\n a = ''\n a = s[i] + s[i + 1]\n l.append(a)\n return len(set(l))", "def fun(s):\n n = len(s)\n tmp_dict = {}\n count = 0\n for i in range(n - 1):\n curr_s = s[i:i + 2]\n if not tmp_dict.get(curr_s):\n count += 1\n tmp_dict[curr_s] = 1\n return count", "def fun(s):\n substr_set = set()\n for (i, letter) in enumerate(s):\n if i < len(s) - 1:\n substr_set.add(s[i:i + 2])\n return len(substr_set)", "def fun(s):\n a = []\n n = len(s)\n for i in range(0, n - 1):\n j = i + 1\n if s[i] + s[j] not in a:\n a.append(s[i] + s[j])\n return len(a)", "def fun(s):\n distinct = set()\n length = len(s)\n for i in range(length - 1):\n distinct.add(s[i:i + 2])\n return len(distinct)", "def fun(s):\n (n, x) = (len(s), 0)\n st = set()\n for i in range(n - 1):\n snew = s[i:i + 2]\n st.add(snew)\n return len(st)", "def fun(s):\n lst = []\n i = 0\n j = 1\n while j != len(s):\n x = s[i:j + 1]\n if x not in lst:\n lst.append(x)\n i += 1\n j += 1\n return len(lst)", "def fun(s):\n hashset = set()\n for i in range(len(s) - 1):\n char = s[i:i + 2]\n hashset.add(char)\n return len(hashset)", "def fun(s):\n ans = 0\n arr = set()\n for i in range(len(s) - 1):\n if s[i] + s[i + 1] not in arr:\n ans += 1\n arr.add(s[i] + s[i + 1])\n return ans", "def fun(s):\n d = {}\n for i in range(len(s) - 1):\n if s[i:i + 2] not in d:\n d[s[i:i + 2]] = 1\n else:\n d[s[i:i + 2]] = d[s[i:i + 2]] + 1\n c = 0\n for (key, val) in d.items():\n c += 1\n return c", "def fun(s):\n ans = []\n p = set()\n for i in range(1, len(s)):\n x = ''.join(s[i - 1:i + 1])\n if x not in p:\n ans.append(x)\n p.add(x)\n return len(ans)"], "starter_code": "def fun(s):\n", "input_output": {"inputs": ["s = \"ABCAB\"", "s = \"XYZ\""], "outputs": ["3", "2"]}, "difficulty": "EASY", "raw_tags": ["Map", "Strings", "Hash", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/distinct-substrings2516/1", "Expected Auxiliary Space": "O(|s|)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|s|)", "entry_point": "fun", "task_id": "TACO_lite/264", "example": [[["ABCAB"], ["XYZ"]], ["3", "2"]]} +{"requirement": "You are given the root of a complete binary tree. Your task is to find the count of nodes.\nA complete binary tree is a binary tree whose, all levels except the last one are completely filled, the last level may or may not be completely filled and Nodes in the last level are as left as possible.\nDesign an algorithm that runs better than O(n).\nExample:\nInput: \nroot = [1,2,3,4,5,6]\nOutput: \n6\nExplanation: \nThere are a total of 6 nodes in the given tree.\nYour Task:\nComplete the function int cnt_nodes(Node *root), which takes the pointer of the root of the given Binary tree and returns the count of its number of nodes.\nExpected Time Complexity: O((LogN)^{2}).\nExpected Auxiliary Space: O(Log N).\nConstraints:\n0 <= N (number of nodes) <= 5 * 10^{4} \n0 <= value of nodes <= 5 * 10^{4}\nThe tree is guaranteed to be complete.", "solutions": ["def countNodes(root):\n if root == None:\n return 0\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "def countNodes(root):\n if root == None:\n return 0\n ln = self.countNodes(root.left)\n rn = self.countNodes(root.right)\n treecount = ln + rn + 1\n return treecount", "def countNodes(root):\n lst = [root]\n A = []\n while lst:\n if lst[0].left:\n lst.append(lst[0].left)\n if lst[0].right:\n lst.append(lst[0].right)\n A.append(lst.pop(0))\n return len(A)", "def get_leftheight(root):\n count = 0\n while root is not None:\n root = root.left\n count += 1\n return count\n\ndef get_rightheight(root):\n count = 0\n while root is not None:\n root = root.right\n count += 1\n return count\n\ndef countNodes(root):\n if root is None:\n return 0\n left_height = self.get_leftheight(root.left)\n right_height = self.get_rightheight(root.right)\n if left_height == right_height:\n return 2 ** (left_height + 1) - 1\n return self.countNodes(root.left) + self.countNodes(root.right) + 1", "def cn(root, k):\n if not root:\n return\n k.append(root.data)\n self.cn(root.right, k)\n self.cn(root.left, k)\n\ndef countNodes(root):\n k = []\n self.cn(root, k)\n return len(k)", "from collections import deque\n\ndef countNodes(root):\n if not root:\n return 0\n left = self.countNodes(root.left)\n right = self.countNodes(root.right)\n return 1 + left + right", "def __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef countNodes(root):\n if not root:\n return 0\n height = 0\n node = root\n while node.left:\n height += 1\n node = node.left\n left = 1\n right = 2 ** height\n while left <= right:\n mid = (left + right) // 2\n if self.exists(root, height, mid):\n left = mid + 1\n else:\n right = mid - 1\n return 2 ** height - 1 + left - 1\n\ndef exists(node, height, pos):\n left = 1\n right = 2 ** height\n for _ in range(height):\n mid = (left + right) // 2\n if pos <= mid:\n node = node.left\n right = mid\n else:\n node = node.right\n left = mid + 1\n return node is not None", "def countNodes(root):\n l = [0]\n\n def fun(root):\n if root:\n l[0] = l[0] + 1\n fun(root.left)\n fun(root.right)\n fun(root)\n return l[0]", "def countNodes(root):\n\n def inorder(root, l):\n if root is None:\n return\n if root.left:\n root.left = inorder(root.left, l)\n l.append(root.data)\n if root.right:\n root.right = inorder(root.right, l)\n l = []\n inorder(root, l)\n return len(l)", "def countNodes(root):\n (l, r) = (0, 0)\n curr = root\n while curr != None:\n curr = curr.left\n l += 1\n curr = root\n while curr != None:\n curr = curr.right\n r += 1\n if l == r:\n return pow(2, l) - 1\n else:\n return self.countNodes(root.left) + self.countNodes(root.right) + 1", "def left_height(root):\n count = 1\n while root:\n count += 1\n root = root.left\n return count\n\ndef right_height(root):\n count = 1\n while root:\n count += 1\n root = root.right\n return count\n\ndef countNodes(root):\n if not root:\n return 0\n left = self.left_height(root.left)\n right = self.right_height(root.right)\n if left == right:\n return 2 ** left - 1\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "def countNodes(root):\n if root == None:\n return []\n q = []\n q.append(root)\n ans = []\n while len(q) != 0:\n size = len(q)\n tmp = []\n while size != 0:\n curr = q.pop(0)\n ans.append(curr.data)\n if curr.left != None:\n q.append(curr.left)\n if curr.right != None:\n q.append(curr.right)\n size -= 1\n return len(ans)", "def countNodes(root):\n ans = 0\n\n def f(root):\n nonlocal ans\n if root is None:\n return\n ans += 1\n f(root.left)\n f(root.right)\n f(root)\n return ans", "def leftHeight(root):\n hight = 0\n while root:\n root = root.left\n hight += 1\n return hight\n\ndef rightHeight(root):\n hight = 0\n while root:\n root = root.right\n hight += 1\n return hight\n\ndef countNodes(root):\n if root == None:\n return 0\n lh = self.leftHeight(root)\n rh = self.rightHeight(root)\n if lh == rh:\n return (1 << lh) - 1\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "def countNodes(root):\n stack = []\n curr = root\n post = []\n while curr != None or len(stack) > 0:\n if curr != None:\n stack.append(curr)\n curr = curr.left\n else:\n temp = stack[-1].right\n if temp == None:\n temp = stack.pop()\n post.append(temp.data)\n while len(stack) > 0 and temp == stack[-1].right:\n temp = stack.pop()\n post.append(temp.data)\n else:\n curr = temp\n return len(post)", "def countNodes(root):\n self.ans = 0\n\n def dfs(root):\n if not root:\n return\n self.ans += 1\n (dfs(root.left), dfs(root.right))\n dfs(root)\n return self.ans", "def countNodes(root):\n res = []\n\n def two(root):\n if not root:\n return\n two(root.left)\n res.append(root.data)\n two(root.right)\n two(root)\n return len(res)", "def countNodes(root):\n if root == None:\n return 0\n else:\n ls = self.countNodes(root.left)\n rs = self.countNodes(root.right)\n return ls + rs + 1", "def countNodes(root):\n if root == None:\n return 0\n if root.left is None and root.right is None:\n return 1\n l = self.countNodes(root.left)\n r = self.countNodes(root.right)\n return l + r + 1", "def countNodes(root):\n if root is not None:\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)\n else:\n return 0", "def countNodes(root):\n if root is None:\n return 0\n leftNodes = self.countNodes(root.left)\n rightNodes = self.countNodes(root.right)\n return leftNodes + rightNodes + 1", "def countNodes(root):\n\n def findLHeight(node):\n h = 0\n while node:\n h += 1\n node = node.left\n return h\n\n def findRHeight(node):\n r = 0\n while node:\n r += 1\n node = node.right\n return r\n\n def f(node):\n if node is None:\n return 0\n l = findLHeight(node)\n r = findRHeight(node)\n if l == r:\n return 2 ** l - 1\n return 1 + f(node.left) + f(node.right)\n return f(root)", "def countNodes(root):\n queue = []\n queue.append(root)\n ans = 0\n while queue:\n node = queue.pop(0)\n ans += 1\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return ans", "def countNodes(root):\n cnt = [0]\n\n def find(root):\n if root:\n cnt[0] += 1\n find(root.left)\n find(root.right)\n return\n find(root)\n return cnt[0]", "def countNodes(root):\n queue = [root]\n val = 0\n while queue:\n level = []\n for i in queue:\n if i == None:\n continue\n val += 1\n level.append(i.left)\n level.append(i.right)\n queue = level\n return val", "def countNodes(root):\n rh = 0\n lh = 0\n a = root\n while a != None:\n lh += 1\n a = a.left\n a = root\n while a != None:\n rh += 1\n a = a.right\n if rh == lh:\n return int(2 ** rh) - 1\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "def gen(root):\n if root.left == None or root.right == None:\n self.bi += 1\n if root.left:\n self.leaf += 1\n if root.right:\n self.leaf += 1\n return\n self.bi += 1\n self.gen(root.left)\n self.gen(root.right)\n\ndef countNodes(root):\n self.leaf = 0\n self.bi = 0\n self.gen(root)\n return self.bi + self.leaf", "def countNodes(root):\n\n def user(root):\n if not root:\n return 0\n return 1 + user(root.left) + user(root.right)\n return user(root)", "def countNodes(root):\n\n def findMaxLevel(node, isLeftMove):\n if node is None:\n return 0\n if isLeftMove:\n return 1 + findMaxLevel(node.left, isLeftMove)\n return 1 + findMaxLevel(node.right, isLeftMove)\n leftMove = findMaxLevel(root, True)\n rightMove = findMaxLevel(root, False)\n if leftMove == rightMove:\n return 2 ** leftMove - 1\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "def countNodes(root):\n if not root:\n return 0\n l = self.findleft(root)\n r = self.findright(root)\n if l == r:\n return 2 ** l - 1\n else:\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)\n\ndef findleft(node):\n if not node:\n return 0\n c = 0\n while node:\n c += 1\n node = node.left\n return c\n\ndef findright(node):\n if not node:\n return 0\n c = 0\n while node:\n c += 1\n node = node.right\n return c", "def countNodes(root):\n q = []\n q.append(root)\n ret = 0\n while q:\n n = len(q)\n ret += n\n while n > 0:\n tmp = q.pop(0)\n if tmp.left:\n q.append(tmp.left)\n if tmp.right:\n q.append(tmp.right)\n n -= 1\n return ret", "def countNodes(root):\n st = [root]\n c = 0\n while st:\n ob = st.pop()\n c += 1\n if ob.left:\n st.append(ob.left)\n if ob.right:\n st.append(ob.right)\n return c", "from collections import deque\n\ndef countNodes(root):\n if not root:\n return 0\n count = 0\n q = deque()\n q.appendleft((root, 1))\n while q:\n count += q[0][1] - q[-1][1] + 1\n temp = deque()\n while q:\n (root, ind) = q.pop()\n if root.left:\n temp.appendleft((root.left, ind * 2))\n if root.right:\n temp.appendleft((root.right, ind * 2 + 1))\n q = temp\n return count", "def lh(root):\n if not root:\n return 0\n return 1 + self.lh(root.left)\n\ndef rh(root):\n if not root:\n return 0\n return 1 + self.rh(root.right)\n\ndef countNodes(root):\n if not root:\n return 0\n lh = self.lh(root)\n rh = self.rh(root)\n if lh == rh:\n return 2 ** lh - 1\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "def countNodes(root):\n\n def count_complete_tree(root):\n if root == None:\n return 0\n (lh, rh) = (0, 0)\n itr = root\n while itr:\n lh += 1\n itr = itr.left\n itr = root\n while itr:\n rh += 1\n itr = itr.right\n if lh == rh:\n import math\n return int(math.pow(2, lh)) - 1\n return 1 + count_complete_tree(root.left) + count_complete_tree(root.right)\n return count_complete_tree(root)", "def countNodes(root):\n global c\n c = 0\n\n def sol(root):\n global c\n if root:\n sol(root.left)\n c = c + 1\n sol(root.right)\n sol(root)\n return c", "def countNodes(root):\n\n def leftheight(root):\n ans = 0\n cur = root\n while cur:\n ans += 1\n cur = cur.left\n return ans\n\n def rightheight(root):\n ans = 0\n cur = root\n while cur:\n ans += 1\n cur = cur.right\n return ans\n\n def find(root):\n if root == None:\n return 0\n left = leftheight(root)\n right = rightheight(root)\n if left == right:\n return 2 ** left - 1\n else:\n return 1 + find(root.left) + find(root.right)\n return find(root)", "def leftheight(root):\n if root == None:\n return\n height = 0\n while root:\n height += 1\n root = root.left\n return height\n\ndef rightheight(root):\n if root == None:\n return 0\n height = 0\n while root:\n height += 1\n root = root.right\n return height\n\ndef countNodes(root):\n if root == None:\n return 0\n lh = leftheight(root)\n rh = rightheight(root)\n if lh == rh:\n return (1 << lh) - 1\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "def countNodes(root):\n if not root:\n return 0\n ls = self.countL(root)\n rs = self.countR(root)\n if ls == rs:\n return 2 ** ls - 1\n else:\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)\n\ndef countL(root):\n if not root:\n return 0\n h = 0\n while root:\n root = root.left\n h += 1\n return h\n\ndef countR(root):\n if not root:\n return 0\n h = 0\n while root:\n root = root.right\n h += 1\n return h", "def countNodes(root):\n if root == None:\n return 0\n else:\n num_left_nodes = self.countNodes(root.left)\n num_right_nodes = self.countNodes(root.right)\n return 1 + num_left_nodes + num_right_nodes", "def countNodes(root):\n if not root:\n return 0\n return self.countNodesUtil(root)\n\ndef countNodesUtil(root):\n if not root:\n return 0\n l = self.countL(root)\n r = self.countR(root)\n if l == r:\n return 2 ** l - 1\n else:\n return 1 + self.countNodesUtil(root.left) + self.countNodesUtil(root.right)\n\ndef countL(node):\n if not node:\n return 0\n lh = 0\n while node:\n lh += 1\n node = node.left\n return lh\n\ndef countR(node):\n if not node:\n return 0\n rh = 0\n while node:\n rh += 1\n node = node.right\n return rh", "from collections import deque\n\ndef countNodes(root):\n queue = deque()\n count = 0\n if not root:\n return 0\n queue.append(root)\n while queue:\n e = queue.pop()\n count += 1\n if e.left:\n queue.append(e.left)\n if e.right:\n queue.append(e.right)\n return count", "def countNodes(root):\n if not root:\n return 0\n l = self.countNodes(root.left)\n r = self.countNodes(root.right)\n return l + r + 1", "def helperleft(curr):\n c = 0\n while curr:\n c += 1\n curr = curr.left\n return c\n\ndef helperright(curr):\n c = 0\n while curr:\n c += 1\n curr = curr.right\n return c\n\ndef countNodes(root):\n if not root:\n return 0\n lh = helperleft(root)\n rh = helperright(root)\n if lh == rh:\n return 2 ** lh - 1\n lc = self.countNodes(root.left)\n rc = self.countNodes(root.right)\n return 1 + lc + rc", "from collections import deque\n\ndef countNodes(root):\n count = 0\n q = deque([root])\n while q:\n n = len(q)\n count += n\n for i in range(n):\n node = q.popleft()\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return count", "def countNodes(root):\n if not root:\n return 0\n\n def lheight(node):\n if not node:\n return 0\n return 1 + lheight(node.left)\n\n def rheight(node):\n if not node:\n return 0\n return 1 + rheight(node.right)\n (l, r) = (lheight(root), rheight(root))\n if l > r:\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)\n else:\n return 2 ** l - 1", "def helper(root):\n if root is None:\n return\n self.count += 1\n self.helper(root.left)\n self.helper(root.right)\n\ndef countNodes(root):\n if root is None:\n return 0\n self.count = 0\n self.helper(root)\n return self.count", "def countNodes(root):\n c = [0]\n\n def count(root):\n if root:\n count(root.left)\n c[0] = c[0] + 1\n count(root.right)\n count(root)\n return c[0]", "def countNodes(root):\n if root == None:\n return 0\n else:\n x = self.countNodes(root.left)\n y = self.countNodes(root.right)\n return x + y + 1", "def countNodes(root):\n if not root:\n return 0\n leftDepth = self.getDepth(root.left)\n rightDepth = self.getDepth(root.right)\n if leftDepth == rightDepth:\n return pow(2, leftDepth) + self.countNodes(root.right)\n else:\n return pow(2, rightDepth) + self.countNodes(root.left)\n\ndef getDepth(root):\n if not root:\n return 0\n return 1 + self.getDepth(root.left)", "def __init__():\n self.c = 0\n\ndef inorder(root):\n if root is None:\n return\n self.c = self.c + 1\n self.inorder(root.left)\n self.inorder(root.right)\n\ndef countNodes(root):\n self.inorder(root)\n return self.c", "def countNodes(root):\n\n def findHeightLeft(node):\n ht = 0\n while node:\n ht += 1\n node = node.left\n return ht\n\n def findHeightRight(node):\n ht = 0\n while node:\n ht += 1\n node = node.right\n return ht\n\n def fn(root):\n if not root:\n return 0\n (lh, rh) = (findHeightLeft(root), findHeightRight(root))\n if lh == rh:\n return (1 << lh) - 1\n return 1 + fn(root.left) + fn(root.right)\n return fn(root)"], "starter_code": "def init(val):\n", "input_output": {"inputs": ["root = [1,2,3,4,5,6]"], "outputs": ["6"]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/count-number-of-nodes-in-a-binary-tree/1", "Expected Auxiliary Space": "O(Log N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O((LogN)^{2}).", "entry_point": "init", "task_id": "TACO_lite/266", "example": [[[[1, 2, 3, 4, 5, 6]]], ["6"]]} +{"requirement": "The [Sharkovsky's Theorem](https://en.wikipedia.org/wiki/Sharkovskii%27s_theorem) involves the following ordering of the natural numbers:\n```math\n3\u227a5\u227a7\u227a9\u227a ...\\\\\n\u227a2\u00b73\u227a2\u00b75\u227a2\u00b77\u227a2\u00b79\u227a...\\\\\n\u227a2^n\u00b73\u227a2^n\u00b75\u227a2^n\u00b77\u227a2^n\u00b79\u227a...\\\\\n\u227a2^{(n+1)}\u00b73\u227a2^{(n+1)}\u00b75\u227a2^{(n+1)}\u00b77\u227a2^{(n+1)}\u00b79\u227a...\\\\\n\u227a2^n\u227a2^{(n-1)}\u227a...\\\\\n\u227a4\u227a2\u227a1\\\\\n```\n \nYour task is to complete the function which returns `true` if `$a\u227ab$` according to this ordering, and `false` otherwise.\n \nYou may assume both `$a$` and `$b$` are non-zero positive integers.", "solutions": ["def sharkovsky(a, b):\n return f(a) < f(b)\n\ndef f(n, p=0):\n while n % 2 == 0:\n n >>= 1\n p += 1\n return (n == 1, p * (-1) ** (n == 1), n)", "def analyse(x):\n n = (b := bin(x)).rstrip('0')\n p = len(b) - len(n)\n return ((n := int(n, 2)) == 1, p * (-1) ** (n == 1), n)\n\ndef sharkovsky(a, b):\n return analyse(a) < analyse(b)", "key = lambda n: [(0, (e := (n & -n)), n // e), (1, -n)][e == n]\nsharkovsky = lambda a, b: key(a) < key(b)", "from math import log\n\ndef decompose(n):\n for p in range(int(log(n, 2)), -1, -1):\n c = n / 2 ** p\n if c == int(c):\n c = int(c)\n return (c, p)\n\ndef sharkovsky(a, b):\n (coef_a, exp_a) = decompose(a)\n (coef_b, exp_b) = decompose(b)\n if coef_a == 1 and coef_b == 1:\n return exp_b < exp_a\n if coef_a == 1 or coef_b == 1:\n return coef_b == 1\n if exp_a != exp_b:\n return exp_a < exp_b\n if exp_a == exp_b:\n return coef_a < coef_b\n return False", "def div2(n):\n i = 0\n while n % 2 == 0:\n n = n / 2\n i += 1\n return (n, i)\n\ndef sharkovsky(a, b):\n (n1, rem1) = div2(a)\n (n2, rem2) = div2(b)\n if n1 == 1 and n2 == 1:\n return not rem1 < rem2\n elif n1 == 1 and n2 != 1:\n return False\n elif n1 != 1 and n2 == 1:\n return True\n elif rem1 == rem2:\n return n1 < n2\n else:\n return rem1 < rem2", "def sharkovsky(a, b):\n if b == a:\n return False\n elif b == 1:\n return True\n elif a == 1:\n return False\n elif a % 2 == 1:\n if b % 2 == 0:\n return True\n elif a < b:\n return True\n else:\n return False\n elif b % 2 == 1:\n return False\n else:\n result = sharkovsky(a / 2, b / 2)\n return result", "def sharkovsky(a, b):\n\n def key(n):\n even = n & -n\n return [(even, n // even), (float('inf'), -n)][n == even]\n return key(a) < key(b)", "def sharkovsky(a, b):\n if a == b:\n return False\n if a == 1:\n return False\n if b == 1:\n return a > 1\n c = get_highest_power_of_two_divisible_by_number(a)\n d = get_highest_power_of_two_divisible_by_number(b)\n if c == d:\n a //= c\n b //= d\n if a != 1 and b == 1:\n return True\n elif a == 1:\n return False\n else:\n return a < b\n elif c < d:\n a //= c\n b //= d\n if a == 1 and b != 1:\n return False\n elif a == 1 and b == 1:\n return False\n else:\n return True\n else:\n a //= c\n b //= d\n if a != 1 and b == 1:\n return True\n elif a == 1 and b == 1:\n return True\n else:\n return False\n\ndef get_highest_power_of_two_divisible_by_number(number):\n twos = []\n while number % 2 == 0:\n twos.append(2)\n number //= 2\n result = 2 ** len(twos)\n return result\n\ndef is_power_of_two(number):\n twos = []\n while number % 2 == 0:\n twos.append(2)\n number //= 2\n twos = remove_duplicates(twos)\n return twos == [2]\n\ndef remove_duplicates(lst):\n result = []\n for i in lst:\n if i not in result:\n result.append(i)\n return result", "import numpy as np\n\ndef sharkovsky(a, b):\n l = []\n for i in range(0, int(np.log2(max(a, b))) + 3):\n for j in range(3, max(a, b) + 1, 2):\n if a == 2 ** i * j:\n l.append(a)\n a = b\n if len(l) >= 2:\n return True\n for n in range(int(np.log2(max(a, b))) + 3, -1, -1):\n if a == 2 ** n:\n l.append(a)\n a = b\n if len(l) >= 2:\n return True\n return False", "def sharkovsky(a, b):\n i = 0\n while a % 2 == 0:\n a //= 2\n i += 1\n j = 0\n while b % 2 == 0:\n b //= 2\n j += 1\n if a == 1 and b == 1:\n return i > j\n elif a == 1:\n return False\n elif b == 1:\n return True\n elif i == j:\n return a < b\n else:\n return i < j", "def sharkovsky(a, b):\n\n def Answer(n):\n con = True\n p = 0\n while con == True:\n if n % 2 != 0:\n ans = (p, n)\n con = False\n else:\n n = n / 2\n p += 1\n return ans\n ans_a = Answer(a)\n ans_b = Answer(b)\n if ans_a[1] == 1 and ans_b[1] != 1:\n return False\n elif ans_a[1] != 1 and ans_b[1] == 1:\n return True\n elif ans_a[1] == 1 and ans_b[1] == 1:\n return ans_a[0] > ans_b[0]\n elif ans_a[0] > ans_b[0]:\n return False\n elif ans_a[0] < ans_b[0]:\n return True\n else:\n return ans_a[1] < ans_b[1]", "def sharkovsky(a, b):\n if a % 2 == 0 and b % 2 == 0:\n while a % 2 == 0 and b % 2 == 0:\n a = a / 2\n b = b / 2\n if b % 2 == 0:\n if a == 1:\n return 1 == 2\n else:\n return 1 == 1\n elif a % 2 == 0:\n if b == 1:\n return 1 == 1\n else:\n return 1 == 2\n elif b == 1:\n return 1 == 1\n elif a == 1:\n return 1 == 2\n else:\n return a < b", "def sharkovsky(a, b):\n while True:\n if a == 1 or b == 1:\n return a != 1\n if a % 2 or b % 2:\n return a % 2 == 1 and (not (b % 2 == 1 and a >= b))\n a /= 2\n b /= 2", "import math\n\ndef splitnumber(x):\n counter = 0\n while x % 2 == 0:\n counter += 1\n x = x / 2\n return [counter, x]\n\ndef sharkovsky(a, b):\n x = splitnumber(a)\n y = splitnumber(b)\n if x[1] == 1 and y[1] == 1:\n return a > b\n elif x[1] != 1 and y[1] == 1:\n return True\n elif x[1] == 1 and y[1] != 1:\n return False\n elif x[0] == y[0]:\n return a < b\n else:\n return x[0] < y[0]\n return False", "import math\n\ndef max2pow(n):\n even = 1\n while n % 2 == 0:\n even *= 2\n n /= 2\n return (even, n)\n\ndef sharkovsky(a, b):\n if a == b:\n return False\n (even_a, odd_a) = max2pow(a)\n (even_b, odd_b) = max2pow(b)\n if odd_a == 1 and odd_b == 1:\n return even_a > even_b\n if odd_a == 1 or odd_b == 1:\n return odd_b == 1\n if even_a == even_b:\n return odd_a < odd_b\n return even_a < even_b", "import math\n\ndef sharkovsky(a, b):\n if a % 2 != b % 2:\n if b == 1:\n return True\n elif (a % 2 == 1) & (a != 1):\n return True\n else:\n return False\n elif a % 2 == 1:\n if b == 1:\n return True\n elif (a < b) & (a != 1):\n return True\n else:\n return False\n elif (math.pow(2, int(math.log2(a))) == a) & (math.pow(2, int(math.log2(b))) == b) & (a > b):\n return True\n elif math.pow(2, int(math.log2(a))) != a:\n if math.pow(2, int(math.log2(b))) == b:\n return True\n else:\n i = 0\n while a % 2 == 0 and b % 2 == 0:\n i += 1\n a = a / 2\n b = b / 2\n if b % 2 == 0:\n return True\n elif a % 2 == 0:\n return False\n elif a < b:\n return True\n else:\n return False\n else:\n return False", "def sharkovsky(a, b):\n a_red = a\n a_rem = a % 2\n a_count = 0\n while a_rem == 0:\n a_count = a_count + 1\n a_red = int(a_red / 2)\n a_rem = a_red % 2\n b_red = b\n b_rem = b % 2\n b_count = 0\n while b_rem == 0:\n b_count = b_count + 1\n b_red = int(b_red / 2)\n b_rem = b_red % 2\n if a_red > 1 and b_red > 1:\n if a_count != b_count:\n return a_count < b_count\n else:\n return a_red < b_red\n elif a_red == 1 and b_red > 1:\n return False\n elif a_red > 1 and b_red == 1:\n return True\n else:\n return a_count > b_count", "def factorTwos(n):\n twos = 0\n while not n % 2:\n n //= 2\n twos += 1\n return (twos, n)\n\ndef sharkovsky(a, b):\n (twosA, remA) = factorTwos(a)\n (twosB, remB) = factorTwos(b)\n if remA == 1:\n return remB == 1 and twosA > twosB\n elif remB == 1:\n return remA != 1 or twosA > twosB\n elif twosA == twosB:\n return remA < remB\n else:\n return twosA < twosB"], "starter_code": "def sharkovsky(a, b):\n", "input_output": {"fn_name": "sharkovsky", "inputs": [[18, 12], [3, 9], [10, 16], [1, 22], [32, 1024], [17, 17]], "outputs": [[true], [true], [true], [false], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5f579a3b34d5ad002819eb9e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sharkovsky", "task_id": "TACO_lite/288", "example": [[], []]} +{"requirement": "A very easy task for you!\n\nYou have to create a method, that corrects a given date string.\nThere was a problem in addition, so many of the date strings are broken.\nDate-Format is european. That means \"DD.MM.YYYY\".\n\n\nSome examples:\n\n\"30.02.2016\" -> \"01.03.2016\"\n\"40.06.2015\" -> \"10.07.2015\"\n\"11.13.2014\" -> \"11.01.2015\"\n\"99.11.2010\" -> \"07.02.2011\"\n\nIf the input-string is null or empty return exactly this value!\nIf the date-string-format is invalid, return null.\n\nHint: Correct first the month and then the day!\n\nHave fun coding it and please don't forget to vote and rank this kata! :-) \n\nI have created other katas. Have a look if you like coding and challenges.", "solutions": ["import re\nfrom datetime import date, timedelta\n\ndef date_correct(text):\n if not text:\n return text\n try:\n (d, m, y) = map(int, re.match('^(\\\\d{2})\\\\.(\\\\d{2})\\\\.(\\\\d{4})$', text).groups())\n (mo, m) = divmod(m - 1, 12)\n return (date(y + mo, m + 1, 1) + timedelta(days=d - 1)).strftime('%d.%m.%Y')\n except AttributeError:\n return None", "import datetime as dt\nimport re\n\ndef date_correct(date):\n if isinstance(date, str) and re.fullmatch('\\\\d\\\\d\\\\.\\\\d\\\\d\\\\.\\\\d{4}', date):\n (d, m, y) = map(int, date.split('.'))\n (nM, m) = divmod(m - 1, 12)\n y += nM\n m += 1\n d = dt.date(y, m, 1) + dt.timedelta(days=d - 1)\n return f'{d.day:02}.{d.month:02}.{d.year:02}'\n if date == '':\n return ''", "from datetime import date, timedelta\nget_date = __import__('re').compile('(\\\\d\\\\d)\\\\.(\\\\d\\\\d)\\\\.(\\\\d\\\\d\\\\d\\\\d)').search\n\ndef date_correct(my_date):\n if not my_date:\n return my_date\n try:\n (d, m, y) = map(int, get_date(my_date).groups())\n except AttributeError:\n return\n return (date(y + (m - 1) // 12, (m - 1) % 12 + 1, 1) + timedelta(d - 1)).strftime('%d.%m.%Y')", "import datetime\nimport re\n\ndef date_correct(date):\n if not date:\n return date\n if not re.fullmatch('(\\\\d\\\\d\\\\.){2}\\\\d{4}', date):\n return None\n (d, m, y) = [int(x) for x in date.split('.')]\n if m > 12:\n y += m // 12\n m %= 12\n if not m:\n m = 12\n y -= 1\n return (datetime.datetime(year=y, month=m, day=1) + datetime.timedelta(days=d - 1)).strftime('%d.%m.%Y')", "from datetime import date, timedelta\nimport re\n\ndef date_correct(s):\n if s == '':\n return ''\n try:\n m = re.match('\\\\A(\\\\d{2})\\\\.(\\\\d{2})\\\\.(\\\\d{4})\\\\Z', s)\n except:\n return None\n if not m:\n return None\n (d, m, y) = map(int, m.groups())\n d -= 1\n (cy, m) = divmod(m - 1, 12)\n return (date(y + cy, m + 1, 1) + timedelta(d)).strftime('%d.%m.%Y')", "def date_correct(date):\n if date in ('', 0, None):\n return date\n from re import findall\n date = findall('\\\\A(\\\\d{2})\\\\.(\\\\d{2})\\\\.(\\\\d{4})\\\\Z', date)\n if len(date) == 0:\n return None\n import datetime\n date = [int(x) for x in date[0][::-1]]\n date[0] += (date[1] - 1) // 12\n date[1] = (date[1] - 1) % 12 + 1\n newdate = datetime.date(date[0], date[1], 1)\n newdate += datetime.timedelta(days=date[2] - 1)\n return '{0:02d}.{1:02d}.{2}'.format(newdate.day, newdate.month, newdate.year)", "from re import match\nfrom datetime import date as ymd, timedelta\ndate_correct = lambda date: '' if date == '' else None if date == None or not match('\\\\d\\\\d\\\\.\\\\d\\\\d\\\\.\\\\d{4}', date or '') else (lambda d, m, y: (ymd(y + (m - 1) // 12, (m - 1) % 12 + 1, 1) + timedelta(d - 1)).strftime('%d.%m.%Y'))(*map(int, date.split('.')))", "from datetime import datetime, timedelta\nfrom re import fullmatch\n\ndef date_correct(date):\n if isinstance(date, str):\n if not date:\n return ''\n if fullmatch('\\\\d{2}\\\\.\\\\d{2}\\\\.\\\\d{4}', date):\n (day, month, year) = map(int, date.split('.'))\n (extra_year, month) = divmod(month - 1, 12)\n return (datetime(year + extra_year, month + 1, 1) + timedelta(day - 1)).strftime('%d.%m.%Y')", "import re\n\ndef date_correct(date):\n if not date:\n return date\n days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n if not bool(re.match('\\\\d{2}\\\\.\\\\d{2}\\\\.\\\\d{4}', date)):\n return None\n (d, m, y) = list(map(int, date.split('.')))\n while m > 12 or d > days[m - 1]:\n y += (m - 1) // 12\n m = (m - 1) % 12 + 1\n if y % 4 == 0 and y % 100 != 0 or y % 400 == 0:\n days[1] = 29\n else:\n days[1] = 28\n if d > days[m - 1]:\n d -= days[m - 1]\n m += 1\n return '{:02}.{:02}.{}'.format(d, m, y)"], "starter_code": "def date_correct(date):\n", "input_output": {"fn_name": "date_correct", "inputs": [[null], [""], ["01112016"], ["01,11,2016"], ["0a.1c.2016"], ["03.12.2016"], ["30.02.2016"], ["40.06.2015"], ["11.13.2014"], ["33.13.2014"], ["99.11.2010"]], "outputs": [[null], [""], [null], [null], [null], ["03.12.2016"], ["01.03.2016"], ["10.07.2015"], ["11.01.2015"], ["02.02.2015"], ["07.02.2011"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Parsing"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5787628de55533d8ce000b84", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "date_correct", "task_id": "TACO_lite/234", "example": [[["30.02.2016"], ["40.06.2015"], ["11.13.2014"], ["99.11.2010"]], ["01.03.2016", "10.07.2015", "11.01.2015", "07.02.2011"]]} +{"requirement": "Given 6 numbers a,b,c,d,e,f. Find the last digit of (a^{b})*(c^{d})*(e^{f}).\n \nExample 1:\nInput:\na = 3 \nb = 66 \nc = 6 \nd = 41 \ne = 7 \nf = 53\nOutput:\n8\nExplanation:\nThe last digit of the \nvalue obtained after \nsolving the above \nequation is 8.\n \n \nExample 2:\nInput:\na = 1 \nb = 1 \nc = 1 \nd = 1 \ne = 1 \nf = 1\nOutput:\n1\nExplanation:\nThe last digit of the \nvalue obtained after \nsolving the above \nequation is 1.\n \n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function theLastDigit() which takes 6 integers a, b, c, d, e, and f and returns the last digit of the value obtained from the equation.\n \nExpected Time Complexity: O(sqrt(N))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= a,b,c,d,e,f <= 10^{9}", "solutions": ["def thelastdigit(a, b, c, d, e, f):\n b %= 4\n f %= 4\n d %= 4\n if not b:\n b = 4\n if not f:\n f = 4\n if not d:\n d = 4\n return (a % 10) ** b * (c % 10) ** d * (e % 10) ** f % 10"], "starter_code": "def thelastdigit (a,b,c,d,e,f):\n", "input_output": {"inputs": ["a = 3 \nb = 66 \nc = 6 \nd = 41 \ne = 7 \nf = 53", "a = 1 \nb = 1 \nc = 1 \nd = 1 \ne = 1 \nf = 1"], "outputs": ["8", "1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "number-theory", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory", "Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/find-unit-digit-in-a-product2059/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(sqrt(N))", "entry_point": "thelastdigit", "task_id": "TACO_lite/255", "example": [[[3, 66, 6, 41, 7, 53], [1, 1, 1, 1, 1, 1]], ["8", "1"]]} +{"requirement": "Write a function that gets a sequence and value and returns `true/false` depending on whether the variable exists in a multidimentional sequence.\n\nExample:\n```\nlocate(['a','b',['c','d',['e']]],'e'); // should return true\nlocate(['a','b',['c','d',['e']]],'a'); // should return true\nlocate(['a','b',['c','d',['e']]],'f'); // should return false\n```", "solutions": ["def locate(seq, value):\n for s in seq:\n if s == value or (isinstance(s, list) and locate(s, value)):\n return True\n return False", "def locate(seq, value):\n f = 0\n for e in seq:\n if type(e) == list and (not f):\n f = locate(e, value)\n elif e == value:\n f = 1\n return f", "def flatten(seq):\n for e in seq:\n if isinstance(e, list):\n yield from flatten(e)\n yield e\n\ndef locate(seq, value):\n return any((e == value for e in flatten(seq)))", "def locate(arr, item):\n return item in arr or any((isinstance(e, (list, tuple)) and locate(e, item) for e in arr))", "def locate(seq, value):\n if isinstance(seq, (tuple, list)):\n return any((locate(x, value) for x in seq))\n return seq == value", "def locate(seq, value):\n clean = []\n return value in unfold(clean, seq)\n\ndef unfold(clean, seq):\n for s in seq:\n if type(s) == str:\n clean.append(s)\n else:\n clean = list(set(unfold(clean, s)))\n return clean", "def locate(seq, v):\n return any((s for s in seq if s == v or (isinstance(s, list) and locate(s, v))))", "def locate(seq, value):\n for x in seq:\n if x == value:\n return True\n if isinstance(x, list):\n if locate(x, value) == True:\n return True\n return False", "locate = l = lambda a, x: any((l(e, x) if [] == e * 0 else e == x for e in a))", "def locate(seq, value):\n queue = [e for e in seq]\n while len(queue):\n el = queue.pop(0)\n if type(el) is list:\n queue = queue + el\n elif el == value:\n return True\n return False"], "starter_code": "def locate(seq, value):\n", "input_output": {"fn_name": "locate", "inputs": [[["a", "b", ["c", "d", ["e"]]], "a"], [["a", "b", ["c", "d", ["e"]]], "d"], [["a", "b", ["c", "d", ["e"]]], "e"], [["a", "b", ["c", "d", ["e"]]], "f"], [["a", "b", ["c", "d", ["e", ["a", "b", ["c", "d", ["e4"]]]]]], "e4"], [["a", "b", ["c", "d", ["e", ["a", "b", ["c", "d", ["e", ["a", "b", ["c", "d", ["e4", ["a", "b", ["c", "d", ["e", ["a", "b", ["c", "d", ["e", ["a", "b", ["c", "d", ["e14"]]]]]]]]]]]]]]]]]], "e"]], "outputs": [[true], [true], [true], [false], [true], [true]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms"], "name": null, "source": "codewars", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/52840d2b27e9c932ff0016ae", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "locate", "task_id": "TACO_lite/258", "example": [[], []]} +{"requirement": "Given two numbers n and x, find out the total number of ways n can be expressed as the sum of the Xth power of unique natural numbers. As the total number of ways can be very large, so return the number of ways modulo 10^{9 }+ 7. \nExample 1:\nInput: \nn = 10, x = 2\nOutput: \n1 \nExplanation: \n10 = 1^{2} + 3^{2}, Hence total 1 possibility. \nExample 2:\nInput: \nn = 100, x = 2\nOutput: \n3\nExplanation: \n100 = 10^{2} \n6^{2} + 8^{2} and 1^{2} + 3^{2} + 4^{2} + 5^{2} + 7^{2} \nHence total 3 possibilities. \nYour Task: \nYou don't need to read input or print anything. Complete the function numOfWays() which takes n and x as input parameters and returns the total number of ways n can be expressed as the sum of xth power of unique natural numbers.\nExpected Time Complexity: O(n^{2}logn)\nExpected Auxiliary Space: O(n)\nConstraints:\n1 <= n <= 10^{3}\n1 <= x <= 5", "solutions": ["def numofways(n, x):\n M = int(1000000000.0) + 7\n p = []\n i = 1\n while True:\n if pow(i, x) <= n:\n p.append(pow(i, x))\n i += 1\n else:\n break\n dp = [0] * (n + 1)\n dp[0] = 1\n for a in p:\n for i in range(n, -1, -1):\n if i - a >= 0:\n dp[i] = (dp[i - a] + dp[i]) % M\n return dp[n]", "import math\n\ndef numofways(n, x):\n dp = [0] * (n + 1)\n dp[0] = 1\n MOD = 1000000000.0 + 7\n for i in range(1, n + 1):\n for j in range(n, i - 1, -1):\n s = i ** x\n if j >= s:\n dp[j] = (dp[j] + dp[j - s]) % MOD\n return int(dp[n])", "from collections import defaultdict\n\ndef numofways(n, x):\n d = defaultdict(lambda : 0)\n d[0] = 1\n i = 1\n while i ** x <= n:\n temp = defaultdict(lambda : 0)\n for item in d:\n summa = item + i ** x\n if summa <= n:\n temp[summa] += d[item]\n for item in temp:\n d[item] = (d[item] + temp[item]) % (10 ** 9 + 7)\n i += 1\n return d[n]", "def numofways(n, x):\n list = []\n list.append(1)\n for i in range(1, n + 1):\n list.append(0)\n for i in range(1, n + 1):\n for j in range(n, i - 1, -1):\n a = i ** x\n if j >= a:\n list[j] = (list[j] + list[j - a]) % (10 ** 9 + 7)\n return list[n]", "import math\n\ndef rec(n, x):\n dp = [0 for i in range(n + 1)]\n dp[0] = dp[1] = 1\n max = int(pow(n, 1.0 / x))\n for i in range(2, max + 1):\n curr = pow(i, x)\n for j in range(n, curr - 1, -1):\n dp[j] += dp[j - curr]\n return dp[n] % (pow(10, 9) + 7)\n\ndef numofways(n, x):\n return self.rec(n, x)", "def numofways(n, x):\n d = [i for i in range(1, int(n ** (1 / x)) + 1)]\n n1 = len(d)\n t = [[0 for i in range(n + 1)] for j in range(n1 + 1)]\n for i in range(n1 + 1):\n for j in range(n + 1):\n if i == 0 or j == 0:\n if i == 0:\n t[i][j] = 0\n if j == 0:\n t[i][j] = 1\n elif d[i - 1] ** x <= j:\n t[i][j] = (t[i - 1][j - d[i - 1] ** x] + t[i - 1][j]) % (10 ** 9 + 7)\n else:\n t[i][j] = t[i - 1][j]\n return t[-1][-1] % (10 ** 9 + 7)", "def numofways(n, x):\n\n def fun(n, x, s, k):\n if s == n:\n return 1\n if s > n or k == 0:\n return 0\n if dp[s][k] != -1:\n return dp[s][k]\n ans = (fun(n, x, s, k - 1) + fun(n, x, s + k ** x, k - 1)) % 1000000007\n dp[s][k] = ans\n return ans\n k = int(pow(n, 1 / x))\n s = 0\n dp = []\n for i in range(n):\n dp.append([-1] * (k + 1))\n ans = fun(n, x, s, k)\n return ans", "def express(x, target, i, dp):\n if target == 0:\n return 1\n if i < 0:\n return 0\n if dp[target][i] != -1:\n return dp[target][i]\n pa = pow(i, x)\n if pa <= target:\n dp[target][i] = self.express(x, target - pa, i - 1, dp) + self.express(x, target, i - 1, dp)\n return dp[target][i]\n else:\n dp[target][i] = self.express(x, target, i - 1, dp)\n return dp[target][i]\n\ndef numofways(n, x):\n mod = 10 ** 9 + 7\n dp = [[-1] * 1001 for _ in range(1001)]\n return self.express(x, n, n, dp) % mod", "def numHelper(i, n, x, dp):\n if i ** x > n:\n return 0\n if i ** x == n:\n return 1\n if dp[n - i ** x][i + 1] == -1:\n tempAns = numHelper(i + 1, n - i ** x, x, dp)\n dp[n - i ** x][i + 1] = tempAns\n else:\n tempAns = dp[n - i ** x][i + 1]\n if dp[n][i + 1] == -1:\n tempAns2 = numHelper(i + 1, n, x, dp)\n dp[n][i + 1] = tempAns2\n else:\n tempAns2 = dp[n][i + 1]\n return tempAns + tempAns2\n\ndef numofways(n, x):\n ii = int(n ** (1 / x)) + 1\n dp = [[-1 for i in range(ii + 10)] for j in range(n + 10)]\n count = numHelper(1, n, x, dp)\n return count % (7 + 10 ** 9)", "def numofways(n, x):\n dp = [0 for i in range(n + 1)]\n dp[0] = 1\n MOD = 10 ** 9 + 7\n for i in range(1, n + 1):\n for j in range(n, i - 1, -1):\n y = i ** x\n if j >= y:\n dp[j] = (dp[j] + dp[j - y]) % MOD\n return dp[n]", "import math\n\ndef numofways(n, x):\n mod = 1000000000.0 + 7\n dp = [0] * (n + 1)\n dp[0] = dp[1] = 1\n for i in range(2, n + 1):\n for j in range(n, i - 1, -1):\n y = i ** x\n if y <= j:\n dp[j] = int((dp[j] + dp[j - y]) % mod)\n return dp[n]", "import math\n\ndef numofways(n, x):\n i = 1\n p = []\n while math.pow(i, x) <= n:\n p.append(int(math.pow(i, x)))\n i += 1\n dp = [[-1 for i in range(0, n + 1)] for j in range(0, len(p))]\n mod = pow(10, 9) + 7\n\n def back(i, n, x, s, p):\n if s == n:\n return 1\n if s > n or i > len(p) - 1:\n return 0\n if dp[i][s] != -1:\n return dp[i][s]\n dp[i][s] = back(i + 1, n, x, s, p) + back(i + 1, n, x, s + p[i], p)\n return dp[i][s] % mod\n return back(0, n, x, 0, p) % mod", "def numofways(n, x):\n\n def solve(n, x, curr_val, dp):\n mod = 1000000007\n if n == 0:\n return 1\n if n < 0 or curr_val <= 0:\n return 0\n if dp[n][curr_val] != -1:\n return dp[n][curr_val]\n dp[n][curr_val] = (solve(n - curr_val ** x, x, curr_val - 1, dp) + solve(n, x, curr_val - 1, dp)) % mod\n return dp[n][curr_val]\n st_val = int(n ** (1.0 / x))\n dp = [[-1] * (st_val + 1) for _ in range(n + 1)]\n return solve(n, x, st_val, dp)", "def numofways(n, x):\n dp = [0] * (n + 1)\n dp[0] = 1\n dp[1] = 1\n maxLimit = int(n ** (1 / x))\n for i in range(2, maxLimit + 1):\n curr = i ** x\n for j in range(n, curr - 1, -1):\n dp[j] += dp[j - curr]\n mm = 1000000007\n return dp[n] % mm", "def numofways(n, x):\n dp = [0] * (n + 1)\n dp[0] = 1\n mod = 1000000007\n for i in range(1, n + 1):\n for j in range(n, i - 1, -1):\n y = pow(i, x)\n if j >= y:\n dp[j] = (dp[j] + dp[j - y]) % mod\n return dp[n]", "def numofways(n, x):\n dp = [0 for _ in range(n + 1)]\n dp[0] = 1\n M = pow(10, 9) + 7\n for i in range(1, n + 1):\n for j in range(n, i - 1, -1):\n y = pow(i, x)\n if j >= y:\n dp[j] = (dp[j] + dp[j - y]) % M\n return dp[n]"], "starter_code": "def numofways(n, x):\n", "input_output": {"inputs": ["n = 10, x = 2", "n = 100, x = 2"], "outputs": ["1", "3"]}, "difficulty": "MEDIUM", "raw_tags": ["Recursion", "Algorithms", "Dynamic Programming", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Mathematics", "Complete search"], "skill_types": ["Dynamic programming", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/express-as-sum-of-power-of-natural-numbers5647/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n^{2}logn)", "entry_point": "numofways", "task_id": "TACO_lite/271", "example": [[[10, 2], [100, 2]], ["1", "3"]]} +{"requirement": "Your job is to change the given string `s` using a non-negative integer `n`.\n\nEach bit in `n` will specify whether or not to swap the case for each alphabetic character in `s`: if the bit is `1`, swap the case; if its `0`, leave it as is. When you finished with the last bit of `n`, start again with the first bit.\n\nYou should skip the checking of bits when a non-alphabetic character is encountered, but they should be preserved in their original positions.\n\n## Examples\n\n```\nswap('Hello world!', 11) --> 'heLLO wORLd!'\n```\n...because `11` is `1011` in binary, so the 1st, 3rd, 4th, 5th, 7th, 8th and 9th alphabetical characters have to be swapped:\n```\nH e l l o w o r l d !\n1 0 1 1 1 0 1 1 1 0\n^ ^ ^ ^ ^ ^ ^\n```\n\nMore examples:\n```\nswap(\"gOOd MOrniNg\", 7864) --> \"GooD MorNIng\"\nswap('', 11345) --> ''\nswap('the lord of the rings', 0) --> 'the lord of the rings'\n```", "solutions": ["from itertools import cycle\n\ndef swap(s, n):\n b = cycle(bin(n)[2:])\n return ''.join((c.swapcase() if c.isalpha() and next(b) == '1' else c for c in s))", "from itertools import cycle\n\ndef swap(s, n):\n doSwap = cycle(map(int, f'{n:b}'))\n return ''.join((c.swapcase() if c.isalpha() and next(doSwap) else c for c in s))", "def swap(s, n):\n n = str(bin(n))[2:]\n index = 0\n new_s = ''\n for letter in s:\n if letter.isalpha():\n if n[index % len(n)] == '1':\n new_s += letter.swapcase()\n else:\n new_s += letter\n index += 1\n else:\n new_s += letter\n return new_s", "from itertools import cycle\n\ndef swap(s, n):\n binary = cycle(bin(n)[2:])\n return ''.join((char.swapcase() if char.isalpha() and next(binary) == '1' else char for char in s))", "from itertools import cycle\n\ndef swap(s, n):\n it = cycle(bin(n)[2:])\n return ''.join((x.swapcase() if x.isalpha() and next(it) == '1' else x for x in s))", "def swap(s, n):\n (bits, r, c) = (bin(n)[2:], '', 0)\n for i in s:\n r += [i, i.swapcase()][int(bits[c % len(bits)])]\n c += i.isalpha()\n return r", "def swap(s, n):\n n = str(bin(n))[2:]\n words = list(s)\n binary_mult = str(n) * len(s)\n bn_words = list(binary_mult)\n result = []\n for (i, x) in enumerate(words):\n if not x.isalpha():\n bn_words.insert(i, x)\n if bn_words[i] == '1':\n result.append(words[i].swapcase())\n else:\n result.append(words[i])\n return ''.join(result)", "from itertools import cycle\n\ndef swap(s, n):\n return (lambda N: ''.join((e if not e.isalpha() else (e, e.swapcase())[next(N)] for e in s)))(cycle(map(int, bin(n)[2:])))", "from itertools import cycle\n\ndef swap(s, n):\n it = cycle(map(int, format(n, 'b')))\n return ''.join((c.swapcase() if c.isalpha() and next(it) else c for c in s))"], "starter_code": "def swap(s,n):\n", "input_output": {"fn_name": "swap", "inputs": [["Hello world!", 11], ["the quick broWn fox leapt over the fence", 9], ["eVerybody likes ice cReam", 85], ["gOOd MOrniNg", 7864], ["how are you today?", 12345], ["the lord of the rings", 0], ["", 11345]], "outputs": [["heLLO wORLd!"], ["The QUicK BrowN foX LeaPT ovER thE FenCE"], ["EVErYbODy LiKeS IcE creAM"], ["GooD MorNIng"], ["HOw are yoU TOdaY?"], ["the lord of the rings"], [""]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5f3afc40b24f090028233490", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "swap", "task_id": "TACO_lite/160", "example": [[["Hello world!", 11], ["gOOd MOrniNg", 7864], ["", 11345], ["the lord of the rings", 0]], ["heLLO wORLd!", "GooD MorNIng", "", "the lord of the rings"]]} +{"requirement": "There are Infinite People Standing in a row, indexed from 1.\nA person having index 'i' has strength of (i*i).\nYou have Strength 'P'. You need to tell what is the maximum number of People You can Kill With your Strength P.\nYou can only Kill a person with strength 'X' if P >= 'X' and after killing him, Your Strength decreases by 'X'. \n \nExample 1:\nInput:\nN = 14\nOutput: 3\nExplanation:\nThe strengths of people is 1, 4, 9, 16, .... \nand so on. WE can kill the first 3 person , \nafter which our Power becomes 0 and we cant \nkill anyone else. So answer is 3\n \nExample 2:\nInput:\nN = 10\nOutput: 2\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function killinSpree() which takes the integer N as input parameters and returns the maximum Number of People You can kill.\nExpected Time Complexity: O(log(n))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 \u2264 T \u2264 10^{3}\n1 \u2264 N \u2264 10^{12}", "solutions": ["def killinspree(n):\n p = lambda n: n * (n + 1) * (2 * n + 1) // 6\n (lo, hi) = (0, n + 1)\n while lo < hi:\n mi = lo + (hi - lo) // 2\n if p(mi) > n:\n hi = mi\n else:\n lo = mi + 1\n return lo - 1", "def killinspree(n):\n\n def _solve(x):\n return x * (x + 1) * (2 * x + 1) // 6\n (L, R) = (0, 20000)\n while L < R:\n m = (L + R) // 2\n if _solve(m) <= n:\n L = m + 1\n else:\n R = m\n return L - 1", "def killinspree(n):\n (L, R) = (1, 10 ** 9)\n ans = None\n while L <= R:\n M = L + (R - L) // 2\n if M * (M + 1) * (2 * M + 1) // 6 <= n:\n ans = M\n L = M + 1\n else:\n R = M - 1\n return ans", "def valid(k, n):\n return k * (k + 1) * (2 * k + 1) // 6 <= n\n\ndef killinspree(n):\n lower = 1\n upper = n\n while lower < upper - 1:\n candidate = (upper + lower) // 2\n if self.valid(candidate, n):\n lower = candidate\n else:\n upper = candidate\n return lower", "def killinspree(n):\n low = 1\n high = 1000000\n count = 0\n while low <= high:\n mid = low + (high - low) // 2\n val = mid * (mid + 1) * (2 * mid + 1) // 6\n if val <= n:\n ans = mid\n low = mid + 1\n else:\n high = mid - 1\n return ans", "def killinspree(n):\n low = 0\n high = 1000000000000000\n while low <= high:\n mid = low + (high - low) // 2\n value = mid * (mid + 1) * (2 * mid + 1) // 6\n if value <= n:\n ans = mid\n low = mid + 1\n else:\n high = mid - 1\n return ans", "def killinspree(n):\n l = 1\n h = 100000000.0\n a = 0\n while l <= h:\n m = l + (h - l) // 2\n r = m * (m + 1) * (2 * m + 1) // 6\n if n < r:\n h = m - 1\n else:\n a = m\n l = m + 1\n return int(a)", "arr = [0]\nimport bisect\n\ndef killinspree(n):\n self.helper(n)\n return bisect.bisect(arr, n) - 1\n\ndef helper(n):\n i = len(arr)\n summa = arr[-1]\n while summa < n:\n summa += i ** 2\n i += 1\n arr.append(summa)\n return", "def killinspree(n):\n start = 1\n end = 10 ** 6\n res = 0\n while start <= end:\n mid = start + (end - start) // 2\n value = mid * (mid + 1) * (2 * mid + 1) // 6\n if value == n:\n res = mid\n break\n elif value < n:\n res = mid\n start = mid + 1\n else:\n end = mid - 1\n return res", "def totalStrengthReq(mid):\n return mid * (mid + 1) * (2 * mid + 1) // 6\n\ndef killinspree(n):\n (lo, hi) = (1, n)\n ans = -1\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n x = totalStrengthReq(mid)\n if n >= x:\n ans = mid\n lo = mid + 1\n else:\n hi = mid - 1\n return ans", "def strength(mid):\n return mid * (mid + 1) * (2 * mid + 1) / 6\n\ndef killinspree(n):\n (lo, hi) = (1, n)\n ans = 0\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n X = strength(mid)\n if n >= X:\n ans = mid\n lo = mid + 1\n else:\n hi = mid - 1\n return ans", "def binarysearch(l, r, n):\n if l <= r:\n mid = (l + r) // 2\n s = mid * (mid + 1) * (2 * mid + 1) // 6\n if s <= n:\n return self.binarysearch(mid + 1, r, n)\n else:\n return self.binarysearch(l, mid - 1, n)\n return r\n\ndef killinspree(n):\n return self.binarysearch(0, 1000000, n)", "def killinspree(n):\n l = 1\n r = n\n res = 0\n while l <= r:\n mid = (l + r) // 2\n s = mid * (mid + 1) * (2 * mid + 1) // 6\n if s <= n:\n res = mid\n l = mid + 1\n else:\n r = mid - 1\n return res", "def s(i):\n return i * (i + 1) * (2 * i + 1) // 6\n\ndef killinspree(n):\n (st, en) = (0, int(n ** 0.5) + 1)\n ans = 0\n while st <= en:\n mid = (st + en) // 2\n c = s(mid)\n if c == n:\n return mid\n elif c > n:\n en = mid - 1\n else:\n st = mid + 1\n ans = mid\n return ans", "def Formula(n):\n return n * (n + 1) * (2 * n + 1) // 6\n\ndef killinspree(n):\n l = 1\n h = 10000000.0\n ans = 0\n mid = l + (h - l) // 2\n if n == 0:\n return 0\n while l <= h:\n mid = l + (h - l) // 2\n if int(self.Formula(mid)) <= n:\n ans = mid\n l = mid + 1\n else:\n h = mid - 1\n return int(ans)", "MAX = int(1000000000000.0)\ndp = []\n\ndef compute():\n i = 1\n while i * i <= MAX:\n dp.append(i * i)\n i += 1\n\ndef bs(key):\n l = 0\n r = len(dp) - 1\n ans = 0\n while l <= r:\n mid = l + (r - l) >> 1\n if dp[mid] == key:\n return mid\n if dp[mid] < key:\n l = mid + 1\n else:\n r = mid - 1\n return ans\n\ndef killinspree(n):\n\n def sumt(h):\n return h * (h + 1) * (2 * h + 1) / 6\n h = 1\n AC = 0\n sta = 0\n endd = 144225\n while sta <= endd:\n midd = (sta + endd) // 2\n if sumt(midd) <= n:\n AC = max(AC, midd)\n sta = midd + 1\n else:\n endd = midd - 1\n return AC", "def killinspree(n):\n low = 0\n up = n\n ans = 0\n while low <= up:\n mid = (low + up) // 2\n power = mid * (mid + 1) * (2 * mid + 1)\n if power <= n * 6:\n low = mid + 1\n ans = max(ans, mid)\n else:\n up = mid - 1\n return ans", "def killinspree(n):\n (low, high) = (1, 2 ** 32 - 1)\n while low <= high:\n mid = (high + low) // 2\n temp = mid * (mid + 1) * (2 * mid + 1) // 6\n if temp > n:\n high = mid - 1\n elif temp == n:\n return mid\n else:\n low = mid + 1\n return low - 1", "import math\n\ndef killinspree(n):\n\n def sum(n):\n a = n * (n + 1) * (2 * n + 1) / 6\n return a\n (low, high) = (0, n + 1)\n while low < high:\n mid = low + (high - low) // 2\n if sum(mid) > n:\n high = mid\n else:\n low = mid + 1\n return low - 1", "def ss(n):\n return n * (n + 1) * (2 * n + 1) // 6\n\ndef killinspree(n):\n (l, r) = (1, n)\n while l != r:\n mid = (l + r) // 2\n if mid == l:\n return l if self.ss(r) > n else r\n if self.ss(mid) > n:\n r = mid\n elif self.ss(mid) < n:\n l = mid\n else:\n return mid\n return l", "def killinspree(n):\n cnt = -1\n start = 0\n end = n\n while start <= end:\n mid = (start + end) // 2\n midSquareSum = int(mid * (mid + 1) * (2 * mid + 1) / 6)\n if midSquareSum <= n:\n cnt = mid\n start = mid + 1\n else:\n end = mid - 1\n return cnt", "def killinspree(n):\n s = 1\n e = n\n ans = 0\n while s <= e:\n m = s + (e - s) // 2\n x = m * (m + 1) * (2 * m + 1) // 6\n if x <= n:\n ans = m\n s = m + 1\n else:\n e = m - 1\n return ans", "def killinspree(n):\n (l, h) = (0, n)\n while l <= h:\n mid = (l + h) // 2\n if 2 * mid * mid * mid + 3 * mid * mid + mid <= 6 * n:\n l = mid + 1\n else:\n h = mid - 1\n return l - 1", "def killinspree(n):\n\n def add(x):\n return x * (x + 1) * (2 * x + 1) // 6\n if n == 0:\n return 0\n low = 1\n high = 10000000.0\n ans = 0\n while low <= high:\n mid = low + (high - low) // 2\n sum = add(mid)\n if sum <= n:\n ans = mid\n low = mid + 1\n else:\n high = mid - 1\n return int(ans)", "def killinspree(n):\n l = 0\n r = n\n while l <= r:\n m = l + r >> 1\n if m * (m + 1) * (2 * m + 1) <= 6 * n:\n l = m + 1\n else:\n r = m - 1\n return l - 1", "def sum_n2(n):\n return n * (n + 1) * (2 * n + 1) / 6\n\ndef killinspree(P):\n i = 1\n count = 0\n l = 1\n r = P\n while l <= r:\n i = (l + r) // 2\n sum = self.sum_n2(i)\n if P == sum:\n return i\n if P > sum:\n l = i + 1\n if P < sum:\n r = i - 1\n return l - 1", "def killinspree(n):\n low = 1\n high = 1000000\n mid = 0\n while low <= high:\n mid = low + (high - low) // 2\n f = mid * (mid + 1) * (2 * mid + 1) / 6\n if n == f:\n return mid\n elif n < f:\n high = mid - 1\n else:\n low = mid + 1\n return low - 1", "def killinspree(n):\n\n def sumt(h):\n return h * (h + 1) * (2 * h + 1) / 6\n h = 1\n AC = 0\n sta = 0\n endd = 144225\n while sta <= endd:\n midd = (sta + endd) // 2\n if sumt(midd) <= n:\n AC = max(AC, midd)\n sta = midd + 1\n else:\n endd = midd - 1\n return AC", "def killinspree(n):\n i = 1\n j = n\n while i < j:\n mid = i + j + 1 >> 1\n ans = (mid + 1) * (mid * 2 + 1) * mid // 6\n if ans > n:\n j = mid - 1\n else:\n i = mid\n return i", "def killinspree(n):\n (i, j) = (0, n)\n while i <= j:\n k = (i + j) // 2\n if 2 * k * k * k + 3 * k * k + k <= 6 * n:\n i = k + 1\n else:\n j = k - 1\n return i - 1", "def killinspree(n):\n lo = 1\n hi = 1000000\n count = 0\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n val = mid * (mid + 1) * (2 * mid + 1) // 6\n if val <= n:\n ans = mid\n lo = mid + 1\n else:\n hi = mid - 1\n return ans", "def killinspree(n):\n\n def vaild(target, n):\n temp = target * (target + 1) * (2 * target + 1) // 6\n return n >= temp\n start = 1\n end = n\n ans = -1\n while start <= end:\n mid = (start + end) // 2\n if vaild(mid, n):\n ans = mid\n start = mid + 1\n else:\n end = mid - 1\n return ans", "def killinspree(n):\n v = lambda n: n * (n + 1) * (2 * n + 1) // 6\n (lower, upper) = (0, n + 1)\n while lower < upper:\n mid = lower + (upper - lower) // 2\n if v(mid) > n:\n upper = mid\n else:\n lower = mid + 1\n return lower - 1", "def killinspree(n):\n l = 1\n h = int(n ** (1 / 2))\n ans = 1\n while l <= h:\n m = int((l + h) / 2)\n t = m * (m + 1) * (2 * m + 1) / 6\n if n - t >= 0:\n ans = m\n l = m + 1\n else:\n h = m - 1\n return ans", "def killinspree(n):\n import math\n (start, end) = (1, math.ceil((3 * n) ** (1 / 3)))\n while start <= end:\n mid = (start + end) // 2\n summation = mid * (mid + 1) * (2 * mid + 1) // 6\n if summation == n:\n return mid\n elif summation < n:\n start = mid + 1\n else:\n end = mid - 1\n return end", "def killinspree(n):\n start = 0\n end = 100000.0\n mid = start + (end - start) // 2\n ans = 0\n while start <= end:\n condition = mid * (mid + 1) * (2 * mid + 1) // 6\n if n >= condition:\n ans = mid\n start = mid + 1\n else:\n end = mid - 1\n mid = start + (end - start) // 2\n return int(ans)", "import bisect\n\ndef killinspree(n):\n start = 0\n end = 100000.0\n mid = start + (end - start) // 2\n ans = 0\n while start <= end:\n a = mid\n condition = a * (a + 1) * (2 * a + 1) // 6\n if n >= condition:\n ans = mid\n start = mid + 1\n elif n < condition:\n end = mid - 1\n mid = start + (end - start) // 2\n return int(ans)", "def killinspree(n):\n l = 0\n h = n\n while l <= h:\n m = (l + h) // 2\n if m * (m + 1) * (2 * m + 1) // 6 > n:\n h = m - 1\n else:\n l = m + 1\n for i in range(m - 2, m + 2):\n if i * (i + 1) * (2 * i + 1) // 6 > n:\n return i - 1", "def killinspree(n):\n\n def squareSum(x):\n return x * (x + 1) * (2 * x + 1) // 6\n low = 1\n high = 1000000.0\n result = -1\n while low <= high:\n mid = int((low + high) // 2)\n if squareSum(mid) > n:\n high = mid - 1\n elif squareSum(mid) < n:\n result = mid\n low = mid + 1\n else:\n return mid\n return result", "import math\n\ndef killinspree(n):\n low = 1\n high = int(math.sqrt(n))\n sum_till_here = 0\n while low <= high:\n mid = int(low + (high - low) / 2)\n sum_till_here = int(mid * (mid + 1) * (2 * mid + 1) / 6)\n if sum_till_here == n:\n return mid\n elif sum_till_here > n:\n high = mid - 1\n else:\n result = mid\n low = mid + 1\n return result", "def killinspree(n):\n\n def solve(x):\n return x * (x + 1) * (2 * x + 1) // 6\n if n == 0:\n return 0\n start = 1\n end = 1000000.0\n ans = 0\n while start <= end:\n mid = start + (end - start) // 2\n summ = solve(mid)\n if summ <= n:\n ans = mid\n start = mid + 1\n else:\n end = mid - 1\n return int(ans)", "import math\n\ndef killinspree(n):\n s = 1\n e = int(math.sqrt(n) + 1)\n ans = 0\n while s <= e:\n m = s + (e - s) // 2\n su = m * (m + 1) * (2 * m + 1) // 6\n if su <= n:\n ans = m\n s = m + 1\n else:\n e = m - 1\n return ans", "def killinspree(n):\n\n def sumt(h):\n return h * (h + 1) * (2 * h + 1) / 6\n h = 1\n AC = 0\n s = 0\n e = 144225\n while s <= e:\n midd = (s + e) // 2\n if sumt(midd) <= n:\n AC = max(AC, midd)\n s = midd + 1\n else:\n e = midd - 1\n return AC", "def killinspree(n):\n low = 1\n high = 2 * n\n output = 0\n total = 0\n while low <= high:\n mid = (low + high) // 2\n total = mid * (mid + 1) * (2 * mid + 1) // 6\n if total <= n:\n output = mid\n low = mid + 1\n else:\n high = mid - 1\n return output", "def killinspree(n):\n low = 1\n high = 100000\n ans = 0\n while low <= high:\n mid = low + (high - low) // 2\n x = mid * (mid + 1) * (2 * mid + 1) // 6\n if x <= n:\n ans = mid\n low = mid + 1\n else:\n high = mid - 1\n return ans", "import math\n\ndef killinspree(n):\n l = 1\n h = int(math.sqrt(n)) + 1\n ans = 0\n while l <= h:\n m = (l + h) // 2\n k = int(m * (m + 1) * (2 * m + 1) / 6)\n if k <= n:\n if m > ans:\n ans = m\n l = m + 1\n else:\n h = m - 1\n return ans", "def killinspree(n):\n low = 1\n high = n + 1\n while low < high:\n mid = (low + high + 1) // 2\n if n >= mid * (mid + 1) * (2 * mid + 1) // 6:\n low = mid\n else:\n high = mid - 1\n return low", "import math\n\ndef killinspree(n):\n low = 1\n high = math.ceil(math.sqrt(n))\n ans = 1\n while low <= high:\n mid = (low + high) // 2\n power = mid * (mid + 1) * (2 * mid + 1) // 6\n if power == n:\n return mid\n elif power > n:\n high = mid - 1\n else:\n ans = mid\n low = mid + 1\n return ans", "import math\n\ndef killinspree(n):\n (l, r) = (1, math.ceil(math.sqrt(n)))\n res = 0\n while l <= r:\n mid = (l + r) // 2\n z = mid * (mid + 1) * (2 * mid + 1) // 6\n if n == z:\n return mid\n elif z < n:\n res = mid\n l = mid + 1\n else:\n r = mid - 1\n return res", "import math as m\n\ndef killinspree(n):\n (lo, ans) = (0, 0)\n hi = int(m.sqrt(n))\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n val = mid * (mid + 1) * (2 * mid + 1) // 6\n if val <= n:\n ans = mid\n lo = mid + 1\n else:\n hi = mid - 1\n return ans", "def getSum(n):\n return n * (n + 1) * (2 * n + 1) / 6\n\ndef killinspree(n):\n bot = 1\n top = n\n result = 0\n while bot <= top:\n mid = (bot + top) // 2\n s = getSum(mid)\n if s <= n:\n result = mid\n bot = mid + 1\n else:\n top = mid - 1\n return result", "def killinspree(n):\n l = 1\n r = 10 ** 12\n ans = -1\n while r >= l:\n mid = (l + r) // 2\n res = mid * (mid + 1) * (2 * mid + 1) // 6\n if res <= n:\n ans = mid\n l = mid + 1\n else:\n r = mid - 1\n return ans", "def killinspree(n):\n if n == 1:\n return 1\n\n def findSum(k):\n return k * (k + 1) * (2 * k + 1) // 6\n res = 0\n start = 1\n end = n\n while start < end:\n mid = (start + end) // 2\n sm = findSum(mid)\n if sm == mid:\n return mid\n if sm > n:\n end = mid\n else:\n res = mid\n start = mid + 1\n return res", "def killinspree(n):\n l = 1\n h = n\n while l <= h:\n m = l + h >> 1\n if m * (m + 1) * (2 * m + 1) // 6 == n:\n return m\n elif m * (m + 1) * (2 * m + 1) // 6 > n:\n h = m - 1\n else:\n l = m + 1\n return h", "from math import *\n\ndef killinspree(n):\n l = 1\n h = int(sqrt(n))\n while l <= h:\n m = (l + h) // 2\n if m * (m + 1) * (2 * m + 1) // 6 == n:\n return m\n elif m * (m + 1) * (2 * m + 1) // 6 > n:\n h = m - 1\n else:\n l = m + 1\n return h", "def killinspree(n):\n s = 1\n e = int(n ** 0.5)\n while s <= e:\n mid = s + e >> 1\n p = mid * (mid + 1) * (2 * mid + 1) // 6\n if p > n:\n e = mid - 1\n else:\n s = mid + 1\n return e", "def killinspree(n):\n (i, j) = (1, 10 ** 12)\n count = -1\n while j >= i:\n mid = (i + j) // 2\n if mid * (mid + 1) * (2 * mid + 1) // 6 <= n:\n count = mid\n i = mid + 1\n else:\n j = mid - 1\n return count", "def killinspree(n):\n s = 0\n ans = 0\n i = 1\n while n > 0:\n s = i * (i + 1) * (2 * i + 1) // 6\n if n > s:\n i = 2 * i\n elif n == s:\n ans = i\n break\n else:\n low = i // 2\n high = i\n while low <= high:\n mid = (low + high) // 2\n s = mid * (mid + 1) * (2 * mid + 1) // 6\n if s > n:\n high = mid - 1\n elif s == n:\n ans = mid\n break\n else:\n nex = (mid + 1) * (mid + 1 + 1) * (2 * (mid + 1) + 1) // 6\n if nex > n:\n ans = mid\n break\n low = mid + 1\n break\n return ans", "import math\n\ndef killinspree(n):\n l = 1\n r = int(math.sqrt(n))\n ans = 0\n while l <= r:\n mid = l + (r - l) // 2\n cal = mid * (mid + 1) * (2 * mid + 1) // 6\n if cal <= n:\n ans = mid\n l = mid + 1\n else:\n r = mid - 1\n return ans"], "starter_code": "def killinspree (n):\n", "input_output": {"inputs": ["N = 14", "N = 10"], "outputs": ["3", "2"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Binary Search", "Mathematical", "Divide and Conquer"], "name": null, "source": "geeksforgeeks", "tags": ["Sorting", "Divide and conquer", "Mathematics"], "skill_types": ["Sorting"], "url": "https://practice.geeksforgeeks.org/problems/killing-spree3020/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(n))", "entry_point": "killinspree", "task_id": "TACO_lite/279", "example": [[[14], [10]], ["3", "2"]]} +{"requirement": "Write a function that takes as its parameters *one or more numbers which are the diameters of circles.* \n\nThe function should return the *total area of all the circles*, rounded to the nearest integer in a string that says \"We have this much circle: xyz\". \n\nYou don't know how many circles you will be given, but you can assume it will be at least one.\n\nSo: \n```python\nsum_circles(2) == \"We have this much circle: 3\"\nsum_circles(2, 3, 4) == \"We have this much circle: 23\"\n```\n\nTranslations and comments (and upvotes!) welcome!", "solutions": ["import math\n\ndef sum_circles(*args):\n t = round(sum([math.pi * d ** 2 / 4 for d in args]))\n return 'We have this much circle: {}'.format(int(t))", "from math import pi\n\ndef sum_circles(*args):\n return 'We have this much circle: %.0f' % sum([(d / 2.0) ** 2 * pi for d in args])", "from math import pi\n\ndef sum_circles(*args):\n return 'We have this much circle: %s' % int(round(sum((pi * (d / 2.0) ** 2 for d in args))))", "from math import pi\n\ndef sum_circles(*rs):\n total = int(round(sum((pi * r ** 2 / 4 for r in rs))))\n return 'We have this much circle: {}'.format(total)", "import math\n\ndef sum_circles(*args):\n totalArea = 0\n for arg in args:\n area = (arg / 2.0) ** 2.0 * math.pi\n totalArea += area\n return 'We have this much circle: ' + str(int(round(totalArea)))", "from math import pi\nOUTPUT = 'We have this much circle: {:.0f}'.format\n\ndef sum_circles(*args):\n return OUTPUT(sum((pi * (diameter / 2.0) ** 2 for diameter in args)))", "import math\n\ndef sum_circles(*args):\n return 'We have this much circle: ' + str(int(round(sum((i * i * math.pi / 4 for i in args)), 0)))", "import math\n\ndef sum_circles(*args):\n y = round(sum([math.pi * x ** 2 / 4 for x in args]))\n return 'We have this much circle: ' + str(y)"], "starter_code": "def sum_circles(*args):\n", "input_output": {"fn_name": "sum_circles", "inputs": [[48, 7, 8, 9, 10], [1], [1, 1, 1, 2, 3, 4, 5], [894, 5778, 4839, 476], [4.5456, 746.5, 98.34, 344.543], [1, 1, 1], [13.58, 14.9, 56.99, 107.321], [56894.04839, 843975.4839, 4.08437403489], [5, 6, 7, 8, 9, 10, 105083, 48839, 4853, 28, 483]], "outputs": [["We have this much circle: 2040"], ["We have this much circle: 1"], ["We have this much circle: 45"], ["We have this much circle: 45417233"], ["We have this much circle: 538519"], ["We have this much circle: 2"], ["We have this much circle: 11916"], ["We have this much circle: 561977165367"], ["We have this much circle: 10564760498"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Geometry", "Algebra"], "name": null, "source": "codewars", "tags": ["Geometry", "Matrices", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56143efa9d32b3aa65000016", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sum_circles", "task_id": "TACO_lite/277", "example": [[], []]} +{"requirement": "Given a number N, count total number of divisors of N!.\nExample 1:\nInput : N = 4\nOutput: 8\nExplaination: 4! is 24. Divisors of 24 are \n1, 2, 3, 4, 6, 8, 12 and 24.\nExample 2:\nInput : N = 5\nOutput : 16\nExplaination: 5! is 120. Divisors of 120 are \n1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24 30, \n40, 60 and 120.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function totalDivisors() which takes N as input parameter and returns total number of divisors of N!.\nExpected Time Complexity: O(N*logN)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 \u2264 N \u2264 100", "solutions": ["import math as m\n\ndef totaldivisors(N):\n primes = [True] * (N + 1)\n prime_factors = []\n for i in range(2, N + 1):\n if primes[i]:\n j = i * i\n while j <= N:\n primes[j] = False\n j += i\n k = i\n count = 0\n while k <= N:\n count += N // k\n k *= i\n prime_factors.append(count)\n total_divisors = 1\n for count in prime_factors:\n total_divisors *= count + 1\n return total_divisors", "def totaldivisors(n):\n from collections import Counter\n rec = Counter()\n for i in range(2, n + 1):\n div = 2\n while i > 1:\n if i % div == 0:\n i //= div\n rec[div] += 1\n else:\n div += 1\n ans = 1\n for x in rec.values():\n ans *= x + 1\n return ans", "def totaldivisors(n):\n\n def find_Prime(n):\n ans = [2]\n prime = [1 for i in range(n + 1)]\n i = 3\n while i * i <= n:\n if prime[i]:\n for j in range(3 * i, n + 1, 2 * i):\n prime[j] = 0\n i += 2\n for i in range(3, n + 1, 2):\n if prime[i]:\n ans.append(i)\n return ans\n prime = find_Prime(n)\n ans = 1\n for i in prime:\n k = i\n a = 0\n while n // k:\n a += n // k\n k *= i\n ans *= a + 1\n return ans", "def solve(n):\n s = 1\n c = 2\n d = {}\n while n > 1:\n if n % c == 0:\n d[c] = d.get(c, 0) + 1\n n = n // c\n else:\n c += 1\n for i in d.keys():\n s = s * (d[i] + 1)\n return s\n\ndef fact(n):\n if n == 0 or n == 1:\n return 1\n else:\n return n * self.fact(n - 1)\n\ndef totaldivisors(N):\n a = self.fact(N)\n return self.solve(a)", "def totaldivisors(N):\n fact = 1\n\n def pf(n):\n i = 2\n s = 1\n while i * i <= n:\n if n % i == 0:\n t = 0\n while n % i == 0:\n t += 1\n n = n // i\n s = s * (t + 1)\n i += 1\n if n != 1:\n s = s * 2\n return s\n while N != 0:\n fact = fact * N\n N -= 1\n n = fact\n res = pf(n)\n return res", "def totaldivisors(n):\n l = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n i = 0\n m = []\n prod = 1\n while 1:\n k = n\n count = 0\n while k > 0:\n count = count + k // l[i]\n k = k // l[i]\n if count != 0:\n m.append(count)\n i = i + 1\n if i == 25:\n break\n for i in m:\n prod = prod * (i + 1)\n return prod", "def totaldivisors(num):\n arr = [i for i in range(1, num + 1)]\n mp = {}\n for i in range(num):\n j = 2\n while j * j <= arr[i] and arr[i] > 1:\n cnt = 0\n while arr[i] % j == 0:\n arr[i] = arr[i] // j\n cnt += 1\n if mp.__contains__(j):\n mp[j] += cnt\n else:\n mp[j] = cnt\n j += 1\n if arr[i] > 1:\n if mp.__contains__(arr[i]):\n mp[arr[i]] += 1\n else:\n mp[arr[i]] = 1\n ans = 1\n for k in mp:\n ans *= mp[k] + 1\n return ans"], "starter_code": "def totaldivisors(N):\n", "input_output": {"inputs": ["N = 4", "N = 5"], "outputs": ["8", "16"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Prime Number", "sieve", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory", "Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/count-divisors-of-factorial4508/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*logN)", "entry_point": "totaldivisors", "task_id": "TACO_lite/284", "example": [[[4], [5]], ["8", "16"]]} +{"requirement": "Given an array of integers arr. Return the number of sub-arrays with odd sum.\nAs the answer may grow large, the answer\u00a0must be\u00a0computed modulo\u00a010^9 + 7.\n\u00a0\nExample 1:\nInput: arr = [1,3,5]\nOutput: 4\nExplanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]\nAll sub-arrays sum are [1,4,9,3,8,5].\nOdd sums are [1,9,3,5] so the answer is 4.\n\nExample 2:\nInput: arr = [2,4,6]\nOutput: 0\nExplanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]\nAll sub-arrays sum are [2,6,12,4,10,6].\nAll sub-arrays have even sum and the answer is 0.\n\nExample 3:\nInput: arr = [1,2,3,4,5,6,7]\nOutput: 16\n\nExample 4:\nInput: arr = [100,100,99,99]\nOutput: 4\n\nExample 5:\nInput: arr = [7]\nOutput: 1\n\n\u00a0\nConstraints:\n\n1 <= arr.length <= 10^5\n1 <= arr[i] <= 100", "solutions": ["def numofsubarrays(arr: List[int]) -> int:\n mod = 10 ** 9 + 7\n odd_presum_cnt = 0\n par = 0\n for a in arr:\n par ^= a & 1\n if par:\n odd_presum_cnt += 1\n return odd_presum_cnt * (len(arr) + 1 - odd_presum_cnt) % mod", "def numofsubarrays(arr: List[int]) -> int:\n res = odd = even = 0\n for x in arr:\n even += 1\n if x % 2 != 0:\n (even, odd) = (odd, even)\n res = (res + odd) % (10 ** 9 + 7)\n return res", "def numofsubarrays(arr: List[int]) -> int:\n np = [[0 for i in range(len(arr))] for j in range(2)]\n np[0][0] = 1 if arr[0] % 2 == 0 else 0\n np[1][0] = 1 if arr[0] % 2 == 1 else 0\n res = np[1][0]\n for i in range(1, len(arr)):\n if arr[i] % 2 == 0:\n np[0][i] = (1 + np[0][i - 1]) % 1000000007\n np[1][i] = np[1][i - 1] % 1000000007\n else:\n np[0][i] = np[1][i - 1] % 1000000007\n np[1][i] = (1 + np[0][i - 1]) % 1000000007\n res += np[1][i]\n return res % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n s = 0\n odd = {}\n ok = []\n even = {}\n ek = []\n for i in range(len(arr)):\n s += arr[i]\n if s % 2 == 0:\n even[i] = s\n ek.append(i)\n else:\n odd[i] = s\n ok.append(i)\n j = 0\n c = 0\n for i in ok:\n while j < len(ek) and ek[j] < i:\n j += 1\n c += j\n j = 0\n for i in ek:\n while j < len(ok) and ok[j] < i:\n j += 1\n c += j\n return (c + len(ok)) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n mod = 10 ** 9 + 7\n odd_even_count = [[0, 0] for _ in range(len(arr) + 1)]\n prefix_odd_sum = [-1 for _ in range(len(arr))]\n cur = 0\n odd_count = 0\n even_count = 0\n for idx in range(len(arr)):\n cur += arr[idx]\n prefix_odd_sum[idx] = cur % 2\n if cur % 2 == 1:\n odd_count += 1\n else:\n even_count += 1\n odd_even_count[idx + 1] = (odd_count, even_count)\n ans = 0\n for idx in range(len(arr)):\n is_odd = prefix_odd_sum[idx]\n if is_odd:\n ans += 1 + odd_even_count[idx][1]\n else:\n ans += odd_even_count[idx][0]\n return ans % mod", "def numofsubarrays(A: List[int]) -> int:\n n = len(A)\n mod = 10 ** 9 + 7\n ans = 0\n (p, ctr) = ([0] * (n + 1), Counter([0]))\n for i in range(n):\n p[i] = p[i - 1] + A[i]\n s = p[i] % 2\n ans = ans + ctr[1 - s]\n ans = ans % mod\n ctr[s] += 1\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n dp = [0 for i in range(len(arr))]\n dp[0] = (1, 0) if arr[0] % 2 == 1 else (0, 1)\n for i in range(1, len(dp)):\n if arr[i] % 2 == 0:\n oddCount = dp[i - 1][0]\n evenCount = dp[i - 1][1] + 1\n else:\n oddCount = dp[i - 1][1] + 1\n evenCount = dp[i - 1][0]\n dp[i] = (oddCount, evenCount)\n return sum([elem[0] for elem in dp]) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n MOD = 10 ** 9 + 7\n res = 0\n curr_sum = 0\n even_count = 1\n odd_count = 0\n for num in arr:\n curr_sum += num\n curr_sum %= 2\n if curr_sum == 1:\n res += even_count\n odd_count += 1\n else:\n res += odd_count\n even_count += 1\n return res % MOD", "def numofsubarrays(arr: List[int]) -> int:\n dp = [[0, 0] for _ in range(len(arr) + 1)]\n for (i, num) in enumerate(arr):\n if num % 2 == 0:\n dp[i + 1][0] = dp[i][0]\n dp[i + 1][1] = dp[i][1] + 1\n else:\n dp[i + 1][0] = dp[i][1] + 1\n dp[i + 1][1] = dp[i][0]\n return sum((dp[i][0] for i in range(len(dp)))) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n mod = 10 ** 9 + 7\n dic = collections.Counter()\n dic[0] += 1\n pre = ans = 0\n for (i, x) in enumerate(arr):\n pre += x\n pre %= 2\n ans = (ans + dic[pre ^ 1]) % mod\n dic[pre] += 1\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n if len(arr) < 1:\n return None\n if len(arr) == 1:\n if arr[0] % 2 != 0:\n return 1\n mod = 10 ** 9 + 7\n flag = False\n for i in arr:\n if i % 2 != 0:\n flag = True\n break\n if flag == False:\n return 0\n (even, odd) = (0, 0)\n ret = 0\n for i in arr:\n if i % 2 != 0:\n ret += even + 1\n (odd, even) = (even + 1, odd)\n else:\n ret += odd\n (odd, even) = (odd, even + 1)\n return ret % mod", "def numofsubarrays(arr: List[int]) -> int:\n N = len(arr)\n dp = [0] * N\n dp[0] = arr[0] & 1\n for i in range(1, N):\n if arr[i] & 1:\n dp[i] = i - dp[i - 1] + 1\n else:\n dp[i] = dp[i - 1]\n return sum(dp) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n ans = 0\n even = 0\n odd = 0\n for v in arr:\n if v % 2 == 0:\n (even, odd) = ((even + 1) % 10000000007, odd)\n else:\n (even, odd) = (odd, (even + 1) % 10000000007)\n ans = (ans + odd) % 10000000007\n return ans % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n kMod = int(1000000000.0 + 7)\n n = len(arr)\n dp = [[0] * 2 for _ in range(n)]\n ans = 0\n if arr[0] % 2 == 0:\n dp[0][0] = 1\n else:\n dp[0][1] = 1\n ans += dp[0][1]\n for i in range(1, n):\n if arr[i] % 2 != 0:\n dp[i][0] = dp[i - 1][1]\n dp[i][1] = dp[i - 1][0] + 1\n else:\n dp[i][0] = dp[i - 1][0] + 1\n dp[i][1] = dp[i - 1][1]\n ans += dp[i][1]\n return ans % kMod", "def numofsubarrays(arr: List[int]) -> int:\n dp = []\n for i in range(len(arr) + 1):\n dp.append([0, 0])\n ans = 0\n for i in range(1, len(arr) + 1):\n if arr[i - 1] % 2 == 0:\n dp[i][0] = dp[i - 1][0] + 1\n dp[i][1] = dp[i - 1][1]\n else:\n dp[i][0] = dp[i - 1][1]\n dp[i][1] = dp[i - 1][0] + 1\n ans += dp[i][1]\n return ans % (pow(10, 9) + 7)", "def numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n mod = 10 ** 9 + 7\n ans = 0\n p = [0] * (n + 1)\n counter = Counter([0])\n for i in range(n):\n p[i] = p[i - 1] + arr[i]\n if p[i] % 2:\n ans += counter[0]\n else:\n ans += counter[1]\n counter[p[i] % 2] += 1\n return ans % mod", "def numofsubarrays(arr: List[int]) -> int:\n sum_even = 0\n sum_odd = 0\n out = 0\n for i in range(len(arr)):\n if arr[i] % 2 == 0:\n (sum_even, sum_odd) = (sum_even + 1, sum_odd)\n else:\n (sum_even, sum_odd) = (sum_odd, sum_even + 1)\n out += sum_odd\n return out % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n sums = [0]\n sum = 0\n for n in arr:\n sum += n\n sums.append(sum)\n odd_sum_count = []\n even_sum_count = []\n odd_sum = 0\n even_sum = 0\n for ss in sums:\n odd_sum += 1 if ss % 2 == 1 else 0\n even_sum += 0 if ss % 2 == 1 else 1\n odd_sum_count.append(odd_sum)\n even_sum_count.append(even_sum)\n ans = 0\n for i in range(len(arr)):\n if sums[i + 1] % 2 == 0:\n ans += odd_sum_count[i]\n else:\n ans += even_sum_count[i]\n ans = ans % (10 ** 9 + 7)\n return ans", "def numofsubarrays(A) -> int:\n n = len(A)\n MOD = pow(10, 9) + 7\n (dp_even, dp_odd) = ([0], [0])\n if A[0] % 2:\n dp_odd[0] += 1\n else:\n dp_even[0] += 1\n ans = dp_odd[-1]\n for i in range(1, n):\n if A[i] % 2:\n dp_odd.append((dp_even[i - 1] + 1) % MOD)\n dp_even.append(dp_odd[i - 1])\n else:\n dp_odd.append(dp_odd[i - 1])\n dp_even.append((dp_even[i - 1] + 1) % MOD)\n ans += dp_odd[i]\n ans %= MOD\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n memoOdd = arr[0] % 2\n memoEven = -(arr[0] % 2 - 1)\n memoOddSum = memoOdd\n for i in range(1, len(arr)):\n memoOdd_temp = memoOdd\n memoEven_temp = memoEven\n memoOdd = memoOdd_temp * -(arr[i] % 2 - 1) + memoEven_temp * (arr[i] % 2) + arr[i] % 2\n memoEven = memoOdd_temp * (arr[i] % 2) + memoEven_temp * -(arr[i] % 2 - 1) - (arr[i] % 2 - 1)\n memoOddSum += memoOdd\n return memoOddSum % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n (countOdd, countEven, result) = (0, 1, 0)\n modulo = 1000000007\n prev = 0\n for i in arr:\n prev = (prev + i) % 2\n if prev == 0:\n countEven += 1\n result += countOdd\n if result >= modulo:\n result %= modulo\n else:\n countOdd += 1\n result += countEven\n if result >= modulo:\n result %= modulo\n return result", "def numofsubarrays(arr: List[int]) -> int:\n ans = 0\n evenCount = 0\n oddCount = 0\n for i in arr:\n if i % 2 == 0:\n ans += oddCount\n (oddCount, evenCount) = (oddCount, evenCount + 1)\n else:\n ans += evenCount + 1\n (oddCount, evenCount) = (evenCount + 1, oddCount)\n return int(ans % (math.pow(10, 9) + 7))", "def numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n MOD = int(1000000000.0 + 7)\n (even, odd) = ([0] * (n + 1), [0] * (n + 1))\n for (i, a) in enumerate(arr):\n if a % 2 == 1:\n even[i] = odd[i - 1] % MOD\n odd[i] = (even[i - 1] + 1) % MOD\n else:\n even[i] = (even[i - 1] + 1) % MOD\n odd[i] = odd[i - 1] % MOD\n return sum(odd) % MOD", "def numofsubarrays(arr: List[int]) -> int:\n acc = []\n temp = 0\n ones = 0\n for u in arr:\n temp += u % 2\n if temp % 2 == 1:\n ones += 1\n L = len(arr)\n return ones * (L - ones + 1) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n (evenCount, oddCount) = (1, 0)\n totalSum = numArrays = 0\n for val in arr:\n totalSum += val\n numArrays += evenCount if totalSum % 2 else oddCount\n evenCount += totalSum % 2 == 0\n oddCount += totalSum % 2 == 1\n return numArrays % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n mod = 10 ** 9 + 7\n n = len(arr)\n dp = [[0] * 2 for _ in range(n)]\n if arr[n - 1] & 1:\n dp[n - 1][1] = 1\n else:\n dp[n - 1][0] = 1\n for i in range(n - 2, -1, -1):\n if arr[i] & 1:\n dp[i][1] = (dp[i + 1][0] + 1) % mod\n dp[i][0] = dp[i + 1][1]\n else:\n dp[i][1] = dp[i + 1][1]\n dp[i][0] = (dp[i + 1][0] + 1) % mod\n ans = 0\n for i in range(n):\n ans += dp[i][1]\n return ans % mod", "def numofsubarrays(arr: List[int]) -> int:\n (odd, even) = (0, 1)\n s = res = 0\n for n in arr:\n s += n\n if s % 2 == 0:\n res += odd\n even += 1\n else:\n res += even\n odd += 1\n res %= 1000000007\n return res", "def numofsubarrays(arr: List[int]) -> int:\n o = []\n score = 0\n tmp = 0\n (pa, no) = (0, 0)\n check = []\n for el in arr:\n tmp += el\n if tmp % 2 == 0:\n pa += 1\n check.append(0)\n else:\n no += 1\n check.append(1)\n o.append((pa, no))\n score = 0\n for i in range(len(arr)):\n if arr[i] % 2 == 1:\n score += 1\n if check[i - 1] == 0 or i == 0:\n score += o[-1][1] - o[i][1]\n else:\n score += o[-1][0] - o[i][0]\n mod = 10 ** 9 + 7\n return score % mod", "def numofsubarrays(arr: List[int]) -> int:\n odd = 0\n even = 1\n res = 0\n sum = 0\n for i in arr:\n sum += i\n if sum % 2 == 0:\n even += 1\n res = (res + odd) % 1000000007\n else:\n odd += 1\n res = (res + even) % 1000000007\n return res", "def numOddEvenSubarrays(arr: List[int], start: int) -> (int, int, int):\n if len(arr) == 0:\n return (0, 0, 0)\n if len(arr) == 1 or start == len(arr) - 1:\n return (0, 1, 0) if arr[start] % 2 == 0 else (1, 0, 0)\n (odd, even, oldOdd) = self.numOddEvenSubarrays(arr, start + 1)\n indOdd = (odd + oldOdd) % (10 ** 9 + 7)\n return (odd, even + 1, indOdd) if arr[start] % 2 == 0 else (even + 1, odd, indOdd)\n\ndef numofsubarrays(arr: List[int]) -> int:\n (odd, even, oldOdd) = self.numOddEvenSubarrays(arr, 0)\n total = (odd + oldOdd) % (10 ** 9 + 7)\n return total", "def numofsubarrays(coll: List[int]) -> int:\n n = len(coll)\n m = 10 ** 9 + 7\n acc = 0\n evens = odds = 0\n for (i, x) in enumerate(coll):\n if x & 1:\n (evens, odds) = (odds, evens + 1)\n else:\n evens += 1\n acc += odds\n acc %= m\n return acc", "def numofsubarrays(arr: List[int]) -> int:\n prefix_sum = 0\n number_odd = 0\n number_even = 0\n total = 0\n for i in arr:\n prefix_sum += i\n if prefix_sum % 2 == 1:\n number_odd += 1\n total += 1\n total += number_even\n else:\n total += number_odd\n number_even += 1\n return int(total % (1000000000.0 + 7))", "def numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n d = {}\n d[0] = 1\n sm = 0\n even = 0\n for i in range(n):\n sm += arr[i]\n sm %= 2\n if sm < 0:\n sm += 2\n if sm in d:\n even += d[sm]\n if sm not in d:\n d[sm] = 0\n d[sm] += 1\n return (n * (n + 1) // 2 - even) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n (res, s, prev_odd, prev_even) = (0, 0, 0, 1)\n for v in arr:\n s = (s + v) % 2\n if s == 1:\n res += prev_even\n prev_odd += 1\n else:\n res += prev_odd\n prev_even += 1\n return res % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n if len(arr) == 0:\n return 0\n result = 0\n num_odd = 0\n Cum = [0]\n for i in range(len(arr)):\n Cum.append(Cum[-1] + arr[i])\n if Cum[-1] % 2 != 0:\n num_odd += 1\n return (len(arr) + 1 - num_odd) * num_odd % (10 ** 9 + 7)", "def numofsubarrays(coll: List[int]) -> int:\n n = len(coll)\n m = 10 ** 9 + 7\n dp = [(0, 0) for _ in range(n + 1)]\n for (i, x) in enumerate(coll):\n if x & 1:\n dp[i + 1] = (dp[i][1], dp[i][0] + 1)\n else:\n dp[i + 1] = (dp[i][0] + 1, dp[i][1])\n return sum((odds for (evens, odds) in dp)) % m", "def numofsubarrays(arr: List[int]) -> int:\n s = 0\n (evens, odds) = (0, 0)\n cnt = 0\n for num in arr:\n s += num\n if s % 2 == 1:\n cnt += evens + 1\n odds += 1\n else:\n cnt += odds\n evens += 1\n cnt = cnt % (10 ** 9 + 7)\n return cnt", "def numofsubarrays(arr: List[int]) -> int:\n res = 0\n odds = 0\n even = 0\n for (i, c) in enumerate(arr):\n if c & 1:\n (odds, even) = (even + 1, odds)\n else:\n even += 1\n res = (res + odds) % 1000000007\n return res % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n if not arr:\n return 0\n n_even = 0\n n_odd = 0\n res = 0\n for x in arr:\n if x % 2 == 0:\n (n_even, n_odd) = (n_even + 1, n_odd)\n else:\n (n_even, n_odd) = (n_odd, n_even + 1)\n res += n_odd\n return res % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n even = [0] * len(arr)\n odd = [0] * len(arr)\n for i in range(len(arr)):\n if i == 0 and arr[i] % 2 == 0:\n even[i] = 1\n elif i == 0:\n odd[i] = 1\n elif arr[i] % 2 == 0:\n even[i] = even[i - 1] + 1\n odd[i] = odd[i - 1]\n else:\n even[i] = odd[i - 1]\n odd[i] = even[i - 1] + 1\n mod = 10 ** 9 + 7\n ans = 0\n for i in range(len(arr)):\n ans = (ans + odd[i]) % mod\n return ans", "def numofsubarrays(A):\n count = [1, 0]\n curr = res = 0\n for a in A:\n curr ^= a & 1\n res += count[1 - curr]\n count[curr] += 1\n return res % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n res = odd = even = 0\n for x in arr:\n even += 1\n if x % 2:\n (odd, even) = (even, odd)\n res = (res + odd) % 1000000007\n return res", "def numofsubarrays(arr: List[int]) -> int:\n arr = list(accumulate(arr))\n count = 0\n (prev_even, prev_odd) = (0, 0)\n for i in range(len(arr)):\n if arr[i] % 2:\n count += 1\n count += prev_even\n prev_odd += 1\n else:\n count += prev_odd\n prev_even += 1\n return count % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n dp = [0, 0]\n ans = 0\n for (i, num) in enumerate(arr):\n (dp[0], dp[1]) = (dp[num % 2] + num % 2, dp[(num - 1) % 2] + (num - 1) % 2)\n ans += dp[0]\n return ans % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n sum_even = 0\n sum_odd = 0\n out = 0\n for i in range(len(arr)):\n if arr[i] % 2 == 0:\n (sum_even, sum_odd) = (sum_even + 1, sum_odd)\n else:\n (sum_even, sum_odd) = (sum_odd, sum_even + 1)\n out = out + sum_odd\n return out % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n memoOdd = [arr[0] % 2]\n memoEven = [-(arr[0] % 2 - 1)]\n for i in range(1, len(arr)):\n memoOdd.append(memoOdd[i - 1] * -(arr[i] % 2 - 1) + memoEven[i - 1] * (arr[i] % 2) + arr[i] % 2)\n memoEven.append(memoOdd[i - 1] * (arr[i] % 2) + memoEven[i - 1] * -(arr[i] % 2 - 1) - (arr[i] % 2 - 1))\n return sum(memoOdd) % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n ret = 0\n (odds, evens) = (0, 1)\n cur = 0\n for num in arr:\n cur ^= num & 1\n if cur:\n ret += evens\n odds += 1\n else:\n ret += odds\n evens += 1\n return ret % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n if not arr:\n return 0\n cum = 0\n (odd, even) = (0, 1)\n res = 0\n MOD = 10 ** 9 + 7\n for num in arr:\n cum += num\n if cum % 2:\n res += even\n odd += 1\n else:\n res += odd\n even += 1\n res %= MOD\n return res % MOD", "def numofsubarrays(arr: List[int]) -> int:\n (c, e, o, a) = (0, 1, 0, 0)\n for i in arr:\n c += i\n if c % 2 == 0:\n a += o\n a %= 1000000007\n e += 1\n else:\n a += e\n a %= 1000000007\n o += 1\n return a % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n odd = [0]\n even = [0]\n for i in range(len(arr)):\n if arr[i] % 2 == 0:\n even.append(even[-1] + 1)\n odd.append(odd[-1])\n else:\n even.append(odd[-1])\n odd.append(even[-2] + 1)\n return sum(odd) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n (run, prev) = ([], 0)\n count = 0\n (odd, even) = (0, 0)\n for ele in arr:\n run.append(prev + ele)\n prev = run[-1]\n if run[-1] % 2 != 0:\n count += even + 1\n odd += 1\n else:\n count += odd\n even += 1\n return count % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n if not arr or len(arr) == 0:\n return 0\n even = 1\n odd = 0\n cur = 0\n ret = 0\n for a in arr:\n cur = a + cur\n if cur % 2 == 0:\n even += 1\n ret += odd\n else:\n odd += 1\n ret += even\n ret = ret % (10 ** 9 + 7)\n return ret", "def numofsubarrays(arr: List[int]) -> int:\n L = len(arr)\n works = [0] * L\n not_works = [0] * L\n if arr[0] % 2 == 1:\n works[0] += 1\n else:\n not_works[0] += 1\n for i in range(1, L):\n if arr[i] % 2 == 0:\n works[i] += works[i - 1]\n not_works[i] += not_works[i - 1]\n else:\n works[i] += not_works[i - 1]\n not_works[i] += works[i - 1]\n if arr[i] % 2 == 1:\n works[i] += 1\n else:\n not_works[i] += 1\n return sum(works) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n evenSum = 0\n oddSum = 0\n prefSum = 0\n ans = 0\n for ele in arr:\n prefSum = prefSum + ele\n if prefSum % 2 == 1:\n ans += evenSum + 1\n oddSum += 1\n else:\n ans += oddSum\n evenSum += 1\n ans %= 10 ** 9 + 7\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n (odd, even, re, s) = (0, 1, 0, 0)\n for v in arr:\n s += v\n if s % 2 == 0:\n re += odd\n even += 1\n else:\n re += even\n odd += 1\n return re % 1000000007", "def numofsubarrays(A):\n MOD = 10 ** 9 + 7\n ans = 0\n even = odd = 0\n for x in A:\n if x % 2:\n (odd, even) = (1 + even, odd)\n else:\n even += 1\n ans = (ans + odd) % MOD\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n (o, e) = (0, 0)\n res = 0\n for n in arr:\n if n % 2 == 0:\n e += 1\n else:\n (o, e) = (e, o)\n o += 1\n res += o\n res = res % (10 ** 9 + 7)\n return res", "def numofsubarrays(arr: List[int]) -> int:\n even = 0\n odd = 0\n sum1 = 0\n result = 0\n for num in arr:\n sum1 += num\n if sum1 % 2 == 0:\n result += odd\n even += 1\n else:\n result += even + 1\n odd += 1\n result %= 10 ** 9 + 7\n return result", "def numofsubarrays(arr: List[int]) -> int:\n MOD = 10 ** 9 + 7\n count = [1, 0]\n cur = answer = 0\n for n in arr:\n cur ^= n & 1\n answer = (answer + count[1 ^ cur]) % MOD\n count[cur] += 1\n return answer", "def numofsubarrays(arr: List[int]) -> int:\n le = len(arr)\n o = 0\n s = 0\n for i in arr:\n s += i\n if s % 2:\n o += 1\n return o * (le - o + 1) % 1000000007", "MOD = 1000000007\n\ndef numofsubarrays(arr):\n n = len(arr)\n pre_sum = [1, 0]\n now_sum = 0\n res = 0\n for i in range(n):\n now_sum += arr[i]\n if now_sum % 2 == 1:\n res += pre_sum[0]\n pre_sum[1] += 1\n else:\n res += pre_sum[1]\n pre_sum[0] += 1\n return res % MOD", "def numofsubarrays(arr: List[int]) -> int:\n odds = 0\n evens = 1\n ans = 0\n runningsum = 0\n MOD = 10 ** 9 + 7\n for a in arr:\n runningsum += a\n if runningsum % 2:\n ans = (ans + evens) % MOD\n odds += 1\n else:\n ans = (ans + odds) % MOD\n evens += 1\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n MOD = int(1000000000.0 + 7)\n res = even = odd = 0\n for a in arr:\n even += 1\n if a % 2:\n (even, odd) = (odd, even)\n res = (res + odd) % MOD\n return res", "def numofsubarrays(arr: List[int]) -> int:\n (ans, odd, even) = (0, 0, 0)\n for i in arr:\n if i & 1:\n (odd, even) = (even + 1, odd)\n else:\n even = even + 1\n ans += odd\n return ans % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n even = 0\n odd = 0\n c = 0\n for e in arr:\n if e % 2 == 1:\n c += 1 + even\n (even, odd) = (odd, even + 1)\n else:\n c += odd\n even += 1\n return c % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n odd = 0\n even = 1\n cnt = 0\n res = 0\n mod = 1000000007\n for i in range(len(arr)):\n if arr[i] % 2 == 1:\n cnt += 1\n if cnt % 2 == 1:\n res = (res + even) % mod\n odd += 1\n else:\n res = (res + odd) % mod\n even += 1\n return int(res)", "def numofsubarrays(arr: List[int]) -> int:\n (ans, odd, even) = (0, 0, 0)\n for num in arr:\n if num % 2 != 0:\n (odd, even) = (even + 1, odd)\n else:\n (odd, even) = (odd, even + 1)\n ans += odd\n return ans % int(1000000000.0 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n ret = 0\n (odd_count, even_count) = (0, 0)\n for num in arr:\n if num % 2 != 0:\n ret += even_count + 1\n (odd_count, even_count) = (even_count + 1, odd_count)\n else:\n ret += odd_count\n (odd_count, even_count) = (odd_count, even_count + 1)\n return ret % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n odd = even = ans = 0\n mod = 10 ** 9 + 7\n for num in arr:\n if num % 2 == 1:\n ans += even + 1\n curr_even = even\n even = odd\n odd = curr_even + 1\n else:\n ans += odd\n even += 1\n return ans % mod", "def numofsubarrays(arr: List[int]) -> int:\n odd_sums = 0\n even_sums = 0\n ret = 0\n sum_ = 0\n for num in arr:\n sum_ += num\n if sum_ & 1:\n ret += even_sums + 1\n odd_sums += 1\n else:\n ret += odd_sums\n even_sums += 1\n return ret % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n sumEven = 0\n sumOdd = 0\n cumSum = 0\n result = 0\n for num in arr:\n cumSum += num\n if cumSum % 2 == 1:\n result += 1 + sumEven\n sumOdd += 1\n else:\n result += sumOdd\n sumEven += 1\n return result % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n prefixSum = [0]\n for i in range(1, len(arr) + 1):\n prefixSum.append(prefixSum[-1] + arr[i - 1])\n out = 0\n prefixEven = 0\n prefixOdd = 0\n for i in range(len(prefixSum)):\n if prefixSum[i] % 2 == 0:\n prefixEven += 1\n out += prefixOdd\n else:\n prefixOdd += 1\n out += prefixEven\n return out % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n (odds, counts) = (0, [1, 0])\n for x in arr:\n odds += 1 if x % 2 else 0\n counts[odds % 2] += 1\n return counts[0] * counts[1] % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n N = len(arr)\n if N == 0:\n return 0\n elif N == 1:\n return abs(arr[0]) % 2\n s = 0\n tot = 0\n ct_odd = 0\n ct_even = 0\n for i in range(N):\n s += arr[i]\n if s % 2 == 1:\n tot += 1 + ct_even\n ct_odd += 1\n else:\n tot += ct_odd\n ct_even += 1\n return tot % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n count = len(arr)\n pre_odd_count = arr[0] % 2\n pre_even_count = 1 - pre_odd_count\n result = pre_odd_count\n for index in range(1, count):\n isodd = arr[index] % 2\n if isodd:\n temp = pre_odd_count\n pre_odd_count = 1 + pre_even_count\n pre_even_count = temp\n else:\n pre_odd_count = pre_odd_count\n pre_even_count = 1 + pre_even_count\n result += pre_odd_count\n return result % 1000000007", "import copy\n\ndef numofsubarrays(arr: List[int]) -> int:\n mod = 10 ** 9 + 7\n arr1 = arr.copy()\n for i in range(1, len(arr)):\n arr1[i] += arr1[i - 1]\n (odd, even) = (0, 0)\n cou = 0\n for i in range(len(arr1)):\n if arr1[i] % 2 == 0:\n even += 1\n else:\n odd += 1\n for i in range(len(arr1)):\n if arr1[i] % 2 == 1:\n cou += 1\n cou += odd * even\n return cou % mod", "def numofsubarrays(arr: List[int]) -> int:\n (s, d, ans) = (0, 0, 0)\n for n in arr:\n if n % 2:\n (s, d) = (d, s)\n s += 1\n else:\n d += 1\n ans += s\n return ans % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n (odd, even) = ([0] * n, [0] * n)\n for (i, v) in enumerate(arr):\n if not i:\n odd[i] += v % 2 == 1\n even[i] += v % 2 != 1\n elif v % 2:\n odd[i] += 1 + even[i - 1]\n even[i] += odd[i - 1]\n else:\n odd[i] += odd[i - 1]\n even[i] += 1 + even[i - 1]\n return sum(odd) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n N = len(arr)\n if N == 0:\n return 0\n elif N == 1:\n return abs(arr[0]) % 2\n l1 = 0\n l2 = 0\n if arr[0] % 2:\n l1 += 1\n else:\n l2 += 1\n tot = 0\n tot += l1\n for i in range(1, N):\n l3 = 0\n l4 = 0\n if arr[i] % 2:\n l3 = 1 + l2\n l4 = l1\n else:\n l3 = l1\n l4 = 1 + l2\n l2 = l4\n l1 = l3\n tot += l1\n return tot % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n M = 10 ** 9 + 7\n new_arr = [1 if i % 2 == 1 else 0 for i in arr]\n res = 0\n cucr_sum = 0\n cash = {0: 1, 1: 0}\n for end in range(len(new_arr)):\n cucr_sum += new_arr[end]\n if cucr_sum % 2 == 1:\n res += cash[0]\n cash[1] += 1\n else:\n res += cash[1]\n cash[0] += 1\n return res % M", "def numofsubarrays(arr: List[int]) -> int:\n (mod, n) = (10 ** 9 + 7, len(arr))\n (odd_sum, even_sum, curr_sum, ans) = (0, 1, 0, 0)\n for i in arr:\n curr_sum += i\n if curr_sum % 2 == 1:\n odd_sum += 1\n ans += even_sum % mod\n else:\n even_sum += 1\n ans += odd_sum % mod\n ans %= mod\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n (odd_sum, even_sum, cur_sum, ans) = (0, 1, 0, 0)\n mod = 10 ** 9 + 7\n for i in arr:\n cur_sum += i\n if cur_sum % 2 != 0:\n odd_sum += 1\n ans += even_sum % mod\n if cur_sum % 2 == 0:\n even_sum += 1\n ans += odd_sum % mod\n ans = ans % mod\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n dp = [0, 0]\n res = cur = 0\n for i in arr:\n cur ^= i & 1\n res += cur + dp[1 - cur]\n dp[cur] += 1\n return res % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n MOD = 10 ** 9 + 7\n memo = {0: 0, 1: 0}\n cumsum = 0\n res = 0\n for v in arr:\n cumsum += v\n if cumsum % 2 == 0:\n memo[0] += 1\n res = (res + memo[1]) % MOD\n else:\n memo[1] += 1\n res = (1 + res + memo[0]) % MOD\n return res", "from itertools import accumulate\n\ndef numofsubarrays(arr: List[int]) -> int:\n\n def num_subarrays(k):\n return (k * k + k) // 2\n counts = [0, 0]\n for prefix in accumulate(arr):\n counts[prefix % 2] += 1\n (evens, odds) = counts\n return (num_subarrays(len(arr)) - (num_subarrays(evens) + (num_subarrays(odds) - odds))) % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n prefix = [0]\n for num in arr:\n prefix.append(prefix[-1] ^ num & 1)\n zeros = 0\n ones = 0\n result = 0\n for x in prefix:\n if x == 1:\n ones += 1\n result += zeros\n else:\n zeros += 1\n result += ones\n return result % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n ans = 0\n mod = 1000000000.0 + 7\n seen = [1, 0]\n for i in range(len(arr)):\n if i > 0:\n arr[i] += arr[i - 1]\n ans += seen[(arr[i] + 1) % 2]\n ans %= mod\n seen[arr[i] % 2] += 1\n return int(ans)", "def numofsubarrays(arr: List[int]) -> int:\n cursum = 0\n ans = 0\n if arr[0] % 2:\n cursum = 1\n ans = 1\n for i in range(1, len(arr)):\n if arr[i] % 2:\n cursum = i - cursum + 1\n ans = ans + cursum\n return ans % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n memo = {0: 1, 1: 0}\n cnt = 0\n curr_sum = 0\n K = 10 ** 9 + 7\n for n in arr:\n curr_sum += n\n if curr_sum % 2 == 0:\n cnt += memo[1]\n else:\n cnt += memo[0]\n memo[curr_sum % 2] += 1\n cnt = cnt % K\n return cnt", "def numofsubarrays(arr: List[int]) -> int:\n s = [0, 0]\n res = 0\n cur = 0\n for x in arr:\n cur = (cur + x) % 2\n res += s[1 - cur]\n res += int(cur == 1)\n s[cur] += 1\n return res % (10 ** 9 + 7)", "MOD = 10 ** 9 + 7\n\ndef numofsubarrays(arr: List[int]) -> int:\n odd_cum_sums = 0\n even_cum_sums = 0\n total_odd_sums = 0\n for i in range(len(arr) - 1):\n arr[i + 1] += arr[i]\n for sum_ in arr:\n if sum_ % 2 == 0:\n total_odd_sums += odd_cum_sums\n even_cum_sums += 1\n else:\n total_odd_sums += 1 + even_cum_sums\n odd_cum_sums += 1\n return total_odd_sums % MOD", "def numofsubarrays(arr: List[int]) -> int:\n ans = 0\n (seen_odd, seen_even) = (set(), set())\n (odd_count, even_count) = (0, 1)\n psum = 0\n mod = 10 ** 9 + 7\n for a in arr:\n psum += a\n if psum % 2 == 0:\n ans = (ans + odd_count) % mod\n seen_even.add(psum)\n even_count += 1\n else:\n ans = (ans + even_count) % mod\n seen_odd.add(psum)\n odd_count += 1\n return ans", "def numofsubarrays(arr: List[int]) -> int:\n c = collections.defaultdict(int)\n s = 0\n c[0] += 1\n res = 0\n mod = 10 ** 9 + 7\n for x in arr:\n s ^= x % 2\n res += c[1 - s]\n res %= mod\n c[s] += 1\n return res", "def numofsubarrays(arr: List[int]) -> int:\n A = [i % 2 for i in arr]\n n = len(A)\n lst = [[0, 0]]\n lst[0][A[0] & 1] = 1\n for i in range(1, n):\n if A[i]:\n lst.append([lst[-1][1], 1 + lst[-1][0]])\n else:\n lst.append([1 + lst[-1][0], lst[-1][1]])\n return sum([x[1] for x in lst]) % (10 ** 9 + 7)", "def accumulate(arr):\n acc = 0\n for elem in arr:\n acc = (acc + elem) % 2\n yield acc\n\ndef numofsubarrays(arr: List[int]) -> int:\n parity_array = (x % 2 for x in arr)\n cumulative_array = accumulate(parity_array)\n prev = [1, 0]\n ans = 0\n for elem in cumulative_array:\n ans += [prev[1], prev[0]][elem]\n prev[elem] += 1\n return ans % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n count = arr[0] % 2\n currentCount = count\n for i in range(1, len(arr)):\n if arr[i] % 2 == 1:\n currentCount = i - currentCount + 1\n count += currentCount\n return count % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n count = len(arr)\n isodd = [item % 2 for item in arr]\n odd_end_total = [0] * count\n even_end_total = [0] * count\n odd_end_total[0] = isodd[0]\n even_end_total[0] = 1 - odd_end_total[0]\n for index in range(1, count):\n if isodd[index]:\n odd_end_total[index] = 1 + even_end_total[index - 1]\n even_end_total[index] = odd_end_total[index - 1]\n else:\n odd_end_total[index] = odd_end_total[index - 1]\n even_end_total[index] = 1 + even_end_total[index - 1]\n result = 0\n for index in range(count):\n result += odd_end_total[index]\n return result % 1000000007", "def isEven(n):\n return n % 2 == 0\n\ndef isOdd(n):\n return not isEven(n)\n\ndef numofsubarrays(arr: List[int]) -> int:\n od = list(range(len(arr)))\n ev = list(range(len(arr)))\n if isEven(arr[0]):\n od[0] = 0\n ev[0] = 1\n else:\n od[0] = 1\n ev[0] = 0\n for (i, num) in enumerate(arr):\n if i == 0:\n continue\n if isOdd(num):\n od[i] = ev[i - 1] + 1\n ev[i] = od[i - 1]\n else:\n od[i] = od[i - 1]\n ev[i] = ev[i - 1] + 1\n ans = 0\n for num in od:\n ans += num\n return ans % (10 ** 9 + 7)", "M = int(1000000000.0 + 7)\n\ndef numofsubarrays(arr: List[int]) -> int:\n n = len(arr)\n odd = [-1] * n\n even = [-1] * n\n odd[0] = 1 if arr[0] % 2 == 1 else 0\n even[0] = 1 if arr[0] % 2 == 0 else 0\n for i in range(1, n):\n v = arr[i]\n if v % 2 == 1:\n odd[i] = (1 + even[i - 1]) % M\n even[i] = odd[i - 1]\n else:\n odd[i] = odd[i - 1]\n even[i] = (even[i - 1] + 1) % M\n ret = 0\n for v in odd:\n ret = (ret + v) % M\n return ret", "def numofsubarrays(arr: List[int]) -> int:\n limit = 10 ** 9 + 7\n final = 0\n dp_even = [0] * (len(arr) + 1)\n dp_odd = [0] * (len(arr) + 1)\n for i in range(len(arr)):\n num = arr[i]\n if num % 2 == 0:\n odd_cur = dp_odd[i]\n even_cur = 1 + dp_even[i]\n final += odd_cur\n dp_even[i + 1] = even_cur\n dp_odd[i + 1] = odd_cur\n else:\n odd_cur = dp_even[i] + 1\n even_cur = dp_odd[i]\n final += odd_cur\n dp_odd[i + 1] = odd_cur\n dp_even[i + 1] = even_cur\n return final % limit", "def numofsubarrays(arr: List[int]) -> int:\n odd = [0 for x in arr]\n even = [0 for x in arr]\n odd[0] = 1 if arr[0] % 2 == 1 else 0\n even[0] = 1 if arr[0] % 2 == 0 else 0\n for i in range(1, len(arr)):\n if arr[i] % 2 == 0:\n odd[i] = odd[i - 1]\n even[i] = even[i - 1] + 1\n else:\n odd[i] = even[i - 1] + 1\n even[i] = odd[i - 1]\n return sum(odd) % 1000000007", "def numofsubarrays(arr: List[int]) -> int:\n mod = 10 ** 9 + 7\n for i in range(len(arr)):\n arr[i] %= 2\n n = len(arr)\n dp = []\n ones = 0\n zeroes = 0\n for i in arr:\n if not dp:\n dp.append(i)\n else:\n dp.append(dp[-1] + i)\n dp[-1] %= 2\n if dp[-1] == 0:\n zeroes += 1\n else:\n ones += 1\n total = n * (n + 1) // 2\n total -= ones * (ones - 1) // 2\n total -= zeroes + zeroes * (zeroes - 1) // 2\n return total % mod", "def numofsubarrays(arr: List[int]) -> int:\n r = 0\n e = 0\n o = 0\n for i in arr:\n if i % 2 == 1:\n r += e + 1\n (o, e) = (e + 1, o)\n else:\n r += o\n (o, e) = (o, e + 1)\n a = 10 ** 9 + 7\n return r % a", "def numofsubarrays(arr: List[int]) -> int:\n odd = 0\n even = 0\n n = len(arr)\n sumlist = [0] * n\n output = 0\n for i in range(n - 1, -1, -1):\n if i != n - 1:\n sumlist[i] += arr[i] + sumlist[i + 1]\n else:\n sumlist[i] += arr[i]\n if sumlist[i] % 2 == 0:\n output += odd\n even += 1\n else:\n output += 1\n output += even\n odd += 1\n output %= 10 ** 9 + 7\n return output", "def numofsubarrays(arr: List[int]) -> int:\n dp = [[0, 0]]\n ans = 0\n for i in arr:\n if i % 2 == 0:\n dp.append([dp[-1][0] + 1, dp[-1][1]])\n else:\n dp.append([dp[-1][1], dp[-1][0] + 1])\n ans += dp[-1][1]\n return int(ans % (1000000000.0 + 7))", "def numofsubarrays(arr: List[int]) -> int:\n dp = [-1 for i in range(len(arr))]\n dp[0] = [(arr[0] + 1) % 2, arr[0] % 2]\n total = dp[0][1]\n for k in range(1, len(arr)):\n if arr[k] % 2 == 0:\n dp[k] = [(dp[k - 1][0] + 1) % (10 ** 9 + 7), dp[k - 1][1] % (10 ** 9 + 7)]\n total += dp[k][1]\n total = total % (10 ** 9 + 7)\n else:\n dp[k] = [dp[k - 1][1] % (10 ** 9 + 7), (dp[k - 1][0] + 1) % (10 ** 9 + 7)]\n total += dp[k][1]\n total = total % (10 ** 9 + 7)\n return total % (10 ** 9 + 7)", "def numofsubarrays(arr: List[int]) -> int:\n mod = 10 ** 9 + 7\n result = 0\n sumOdd = [0] * len(arr)\n sumEven = [0] * len(arr)\n if arr[0] % 2 == 1:\n sumOdd[0] = 1\n sumEven[0] = 0\n else:\n sumOdd[0] = 0\n sumEven[0] = 1\n for i in range(1, len(sumOdd)):\n if arr[i] % 2 == 0:\n sumOdd[i] = sumOdd[i - 1]\n sumEven[i] = sumEven[i - 1] + 1\n else:\n sumOdd[i] = sumEven[i - 1] + 1\n sumEven[i] = sumOdd[i - 1]\n return sum(sumOdd) % mod"], "starter_code": "def numofsubarrays(arr: List[int]) -> int:\n", "input_output": {"fn_name": "numOfSubarrays", "inputs": [[[1, 3, 5]]], "outputs": [4]}, "difficulty": "MEDIUM", "raw_tags": ["Prefix Sum", "Math", "Dynamic Programming", "Array"], "name": null, "source": "leetcode", "tags": ["Mathematics", "Dynamic programming", "Data structures", "Range queries"], "skill_types": ["Dynamic programming", "Data structures", "Range queries"], "url": "https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numofsubarrays", "task_id": "TACO_lite/252", "example": [[[[1, 3, 5]], [[2, 4, 6]], [[1, 2, 3, 4, 5, 6, 7]], [[100, 100, 99, 99]], [[7]]], ["4", "0", "16", "4", "1"]]} +{"requirement": "We partition a row of numbers A\u00a0into at most K adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve?\nNote that our partition must use every number in A, and that scores are not necessarily integers.\nExample:\nInput: \nA = [9,1,2,3,9]\nK = 3\nOutput: 20\nExplanation: \nThe best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\nWe could have also partitioned A into [9, 1], [2], [3, 9], for example.\nThat partition would lead to a score of 5 + 2 + 6 = 13, which is worse.\n\n\u00a0\nNote: \n\n1 <= A.length <= 100.\n1 <= A[i] <= 10000.\n1 <= K <= A.length.\nAnswers within 10^-6 of the correct answer will be accepted as correct.", "solutions": ["def largestsumofaverages(A: List[int], K: int) -> float:\n N = len(A)\n P = [0] * (N + 1)\n for i in range(1, N + 1):\n P[i] = P[i - 1] + A[i - 1]\n Table = [(P[N] - P[i]) / (N - i) for i in range(N)]\n for k in range(2, K + 1):\n for i in range(K - k, N - k + 1):\n Table[i] = max(((P[j] - P[i]) / (j - i) + Table[j] for j in range(i + 1, N - k + 2)))\n return Table[0]", "from functools import lru_cache\nfrom itertools import accumulate\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n p = [0] + list(accumulate(A))\n\n def dp(l, k):\n if k > l:\n return 0\n if k == 1:\n return p[l] / l\n return max((dp(i, k - 1) + (p[l] - p[i]) / (l - i) for i in range(k - 1, l)))\n return dp(n, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n memo = [[0 for k in range(K)] for i in range(n)]\n\n def aux(A, cur, k, memo):\n if cur == len(A):\n return 0\n if memo[cur][k]:\n return memo[cur][k]\n tmp = sum(A[cur:]) / (len(A) - cur)\n if k == 0:\n memo[cur][k] = tmp\n return tmp\n for i in range(cur + 1, len(A) + 1):\n tmp = max(tmp, sum(A[cur:i]) / (i - cur) + aux(A, i, k - 1, memo))\n memo[cur][k] = tmp\n return tmp\n return aux(A, 0, K - 1, memo)", "def largestsumofaverages(A, K: int) -> float:\n A = [0] + A\n len_a = len(A)\n dp = [[0] * (K + 1) for _ in range(len_a)]\n for i in range(1, len_a):\n dp[i][0] = -float('inf')\n for i in range(1, len_a):\n for k in range(1, min(K + 1, i + 1)):\n for j in range(k, i + 1):\n dp[i][k] = max(dp[i][k], dp[j - 1][k - 1] + self.helper(A[j:i + 1]))\n return dp[-1][-1]\n\ndef helper(sub_a):\n return sum(sub_a) / len(sub_a)", "def largestsumofaverages(A: List[int], K: int) -> float:\n P = [0] * (len(A) + 1)\n for (i, n) in enumerate(A):\n P[i + 1] = P[i] + n\n\n def average(i, j):\n return (P[j] - P[i]) / float(j - i)\n N = len(A)\n dp = [average(i, N) for i in range(N)]\n for k in range(K - 1):\n for i in range(N):\n for j in range(i + 1, N):\n dp[i] = max(dp[i], average(i, j) + dp[j])\n return dp[0]", "def largestsumofaverages(A, K):\n prefix_sum = [0]\n for x in A:\n prefix_sum.append(prefix_sum[-1] + x)\n\n def average(i, j):\n return (prefix_sum[j] - prefix_sum[i]) / (j - i)\n n = len(A)\n dp = [[0] * n for _ in range(K)]\n for k in range(K):\n for i in range(n):\n if k == 0 and i == 0:\n dp[0][i] = A[0]\n elif k == 0:\n dp[0][i] = average(0, i + 1)\n else:\n for j in range(i):\n dp[k][i] = max(dp[k][i], dp[k - 1][j] + average(i + 1, j + 1))\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n memo = {}\n length = len(A)\n\n def dfs(start, k):\n if (start, k) in memo:\n return memo[start, k]\n if k == 1:\n memo[start, k] = sum(A[start:]) / (length - start)\n return memo[start, k]\n if start >= length:\n return 0\n value = 0\n for i in range(start + 1, length):\n val = sum(A[start:i]) / (i - start)\n value = max(value, dfs(i, k - 1) + val)\n memo[start, k] = value\n return value\n return dfs(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n (s, dp) = ([0] + A, {})\n for i in range(1, len(A) + 1):\n s[i] += s[i - 1]\n\n def dfs(i, k):\n if k == 1:\n return (s[-1] - s[i]) / (len(A) - i)\n if (i, k) in dp:\n return dp[i, k]\n dp[i, k] = max(((s[j] - s[i]) / (j - i) + dfs(j, k - 1) for j in range(i + 1, len(A) - k + 2)))\n return dp[i, k]\n return dfs(0, K)", "import itertools\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n P = [0] + list(itertools.accumulate(A))\n\n def average(i, j):\n return (P[j] - P[i]) / float(j - i)\n N = len(A)\n dp = [average(i, N) for i in range(N)]\n for _ in range(K - 1):\n for i in range(N):\n for j in range(i + 1, N):\n dp[i] = max(dp[i], average(i, j) + dp[j])\n return dp[0]", "def largestsumofaverages(A: List[int], K: int) -> float:\n cumsums = [0] * (len(A) + 1)\n for (i, x) in enumerate(A):\n cumsums[i + 1] = cumsums[i] + A[i]\n memo = {}\n\n def DP(j, K):\n if K == 0:\n return 0\n if j + 1 == K:\n return cumsums[j + 1]\n if K == 1:\n return cumsums[j + 1] / (j + 1)\n res = 0\n for i in range(j, -1, -1):\n if (i, K - 1) not in memo:\n memo[i, K - 1] = DP(i, K - 1)\n if j - i == 0:\n res = max(res, memo[i, K - 1])\n else:\n res = max(res, memo[i, K - 1] + (cumsums[j + 1] - cumsums[i + 1]) / (j - i))\n return res\n a = DP(len(A) - 1, K)\n return a", "def largestsumofaverages(A, K):\n memo = {}\n\n def search(n, k):\n if (n, k) in memo:\n return memo[n, k]\n if n < k:\n return 0\n if k == 1:\n memo[n, k] = sum(A[:n]) / float(n)\n return memo[n, k]\n (cur, memo[n, k]) = (0, 0)\n for i in range(n - 1, 0, -1):\n cur += A[i]\n memo[n, k] = max(memo[n, k], search(i, k - 1) + cur / float(n - i))\n return memo[n, k]\n return search(len(A), K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n Cum = [0]\n for i in range(len(A)):\n Cum.append(Cum[-1] + A[i])\n\n def Average(h, k):\n return (Cum[k] - Cum[h]) / (k - h)\n dp = [Average(i, len(A)) for i in range(len(A))]\n for _ in range(K - 1):\n for i in range(len(A)):\n for j in range(i + 1, len(A)):\n dp[i] = max(dp[i], Average(i, j) + dp[j])\n return dp[0]", "def largestsumofaverages(A: List[int], K: int) -> float:\n presum = [0] + list(itertools.accumulate(A))\n\n def mean(i, j):\n return (presum[j + 1] - presum[i]) / (j - i + 1)\n max_val = [0]\n\n def helper(i, j, k):\n if (i, j, k) in check:\n result = check[i, j, k]\n elif k == 1:\n result = mean(i, j)\n else:\n result = -float('inf')\n for mid in range(i, j):\n result = max(result, mean(i, mid) + helper(mid + 1, j, k - 1))\n check[i, j, k] = result\n max_val[0] = max(max_val[0], result)\n return result\n n = len(A)\n check = {}\n helper(0, n - 1, K)\n return max_val[0]", "def largestsumofaverages(A: List[int], K: int) -> float:\n import itertools\n cumsum = list(itertools.accumulate(A))\n L = len(A)\n K = min(L, K)\n dp = [[0] * (K + 1) for i in range(L)]\n for i in range(L):\n dp[i][1] = cumsum[i] / (i + 1)\n for k in range(2, K + 1):\n for i in range(L):\n tmp = dp[i][k - 1]\n for j in range(i):\n tmp = max(tmp, dp[j][k - 1] + (cumsum[i] - cumsum[j]) / (i - j))\n dp[i][k] = tmp\n return dp[-1][K]", "def largestsumofaverages(A: List[int], K: int) -> float:\n\n def ave(list_):\n return sum(list_) / len(list_)\n dp = {}\n\n def rec(index, k):\n if index == len(A):\n return 0\n if (index, k) in dp:\n return dp[index, k]\n if k == 1:\n return ave(A[index:])\n m = 0\n for i in range(index + 1, len(A)):\n m = max(m, ave(A[index:i]) + rec(i, k - 1))\n dp[index, k] = m\n return m\n return rec(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n L = len(A)\n dp = [[0 for _ in range(K + 1)] for _out in range(L)]\n prefix_sum = [0 for _ in range(L + 1)]\n for i in range(1, L + 1):\n prefix_sum[i] = prefix_sum[i - 1] + A[i - 1]\n dp[0][1] = A[0]\n for i in range(1, L):\n dp[i][1] = (prefix_sum[i] + A[i]) / (i + 1)\n for i in range(1, L):\n for k in range(2, K + 1):\n if k > i + 1:\n dp[i][k] = dp[i][k - 1]\n else:\n for j in range(-1, i):\n subarr = A[j + 1:i + 1]\n ave = (prefix_sum[i + 1] - prefix_sum[j + 1]) / (i - j)\n if j == -1:\n tmp = 0\n else:\n tmp = dp[j][k - 1]\n if ave + tmp > dp[i][k]:\n dp[i][k] = ave + tmp\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n h = {}\n\n def helper(curr, pos, k):\n if pos == len(A):\n return curr\n if k == 0:\n return float('-inf')\n if (pos, k) in h:\n return curr + h[pos, k]\n res = 0\n for i in range(pos, len(A)):\n temp = sum(A[pos:i + 1]) / (i - pos + 1)\n res = max(helper(temp, i + 1, k - 1), res)\n h[pos, k] = res\n return curr + res\n return helper(0, 0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n N = len(A)\n summary = [0] * (N + 1)\n for (i, item) in enumerate(A):\n summary[i + 1] = summary[i] + item\n dp = [[(summary[N] - summary[i]) / (N - i) for i in range(N)] for _ in range(K)]\n for remain in range(1, K):\n for i in range(N):\n for j in range(i + 1, N):\n dp[remain][i] = max(dp[remain][i], (summary[j] - summary[i]) / (j - i) + dp[remain - 1][j])\n return dp[-1][0]", "def largestsumofaverages(A: List[int], K: int) -> float:\n dp = {}\n\n def a(n, k):\n if n < k:\n return 0\n if (n, k) in dp:\n return dp[n, k]\n if k == 1:\n dp[n, k] = sum(A[:n]) / float(n)\n return dp[n, k]\n dp[n, k] = 0\n for i in range(n - 1, 0, -1):\n a(i, k - 1)\n dp[n, k] = max(dp[n, k], a(i, k - 1) + sum(A[i:n]) / float(n - i))\n a(len(A), K)\n return dp[len(A), K]", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n dp = [[0] * (K + 1) for _ in range(n + 1)]\n for i in range(1, n + 1):\n dp[i][1] = sum(A[:i]) / i\n for i in range(2, n + 1):\n for j in range(2, min(K + 1, i + 1)):\n dp[i][j] = max([dp[i - t][j - 1] + sum(A[i - t:i]) / t for t in range(1, i)])\n return dp[n][K]", "def largestsumofaverages(A: List[int], K: int) -> float:\n mem = {}\n\n def dfs(l, K):\n if (l, K) in mem:\n return mem[l, K]\n if l == len(A):\n return 0\n if K == 1:\n return sum(A[l:]) / len(A[l:])\n ans = sum(A[l:]) / len(A[l:])\n for i in range(l + 1, len(A)):\n avg = sum(A[l:i]) / len(A[l:i])\n ans = max(ans, avg + dfs(i, K - 1))\n mem[l, K] = ans\n return ans\n return dfs(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n\n def dfs(i, partitions):\n if partitions == 1:\n return (cum[len(A)] - cum[i - 1]) / (len(A) - i + 1)\n mem[partitions][i] = 0\n for j in range(i, len(A) + 1):\n if mem[partitions - 1][j] == 0:\n mem[partitions - 1][j] = dfs(j, partitions - 1)\n if j > i:\n mem[partitions][i] = max(mem[partitions][i], mem[partitions - 1][j] + (cum[j - 1] - cum[i - 1]) / (j - i))\n else:\n mem[partitions][i] = max(mem[partitions][i], mem[partitions - 1][j])\n return mem[partitions][i]\n ans = 0\n cum = [0 for i in range(len(A) + 1)]\n mem = [[0 for i in range(len(A) + 1)] for j in range(K + 1)]\n cum[0] = 0\n for i in range(len(A)):\n cum[i + 1] = cum[i] + A[i]\n return dfs(1, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n from functools import lru_cache\n\n def maxAverage(j, k):\n if j == k:\n return sum(A[:j])\n if k == 1:\n return sum(A[:j]) / j\n ans = 0\n for i in range(j - 1, max(-1, k - 2), -1):\n ans = max(ans, sum(A[i:j]) / (j - i) + maxAverage(i, k - 1))\n return ans\n return maxAverage(len(A), K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n N = len(A)\n pre_sum = [0 for i in range(N)]\n pre_sum[0] = A[0]\n for j in range(1, len(A)):\n pre_sum[j] = pre_sum[j - 1] + A[j]\n dp = [[0 for n in range(N)] for k in range(K + 1)]\n for i in range(N):\n dp[1][i] = pre_sum[i] / (i + 1)\n for k in range(2, K + 1):\n for i in range(N):\n for j in range(i):\n dp[k][i] = max(dp[k][i], pre_sum[i] / (i + 1), dp[k - 1][j] + (pre_sum[i] - pre_sum[j]) / (i - j))\n return dp[K][N - 1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n N = len(A)\n\n def dfs(index, remain, acc, size):\n if index >= N:\n return 0 if size == 0 else acc / size\n ans = 0\n if remain > 0:\n ans = max(ans, (acc + A[index]) / (size + 1) + dfs(index + 1, remain - 1, 0, 0))\n ans = max(ans, dfs(index + 1, remain, acc + A[index], size + 1))\n return ans\n return dfs(0, K - 1, 0, 0)", "def largestsumofaverages(A: List[int], K: int) -> float:\n self.dp = {}\n self.arr = A\n ans = self.helper(0, K - 1)\n return ans\n\ndef helper(i, k):\n if k == 0:\n return sum(self.arr[i:]) / len(self.arr[i:])\n if i == len(self.arr) - 1:\n return -10 ** 100\n if (i, k) in self.dp:\n return self.dp[i, k]\n ans = 0\n for j in range(i, len(self.arr) - 1):\n tmp = sum(self.arr[i:j + 1]) / len(self.arr[i:j + 1]) + self.helper(j + 1, k - 1)\n ans = max(ans, tmp)\n self.dp[i, k] = ans\n return self.dp[i, k]", "def part(A, i, K, cache):\n if i < 0:\n if K == 0:\n return 0\n return float('-Inf')\n if i == 0:\n if K != 1:\n return float('-Inf')\n return A[i]\n key = '{}-{}'.format(i, K)\n if key in cache:\n return cache[key]\n res = float('-Inf')\n sm = 0\n count = 0\n for j in range(i, -1, -1):\n sm += A[j]\n count += 1\n avg = float(sm) / float(count)\n res = max(res, avg + self.part(A, j - 1, K - 1, cache))\n cache[key] = res\n return res\n\ndef solve(A, K):\n return self.part(A, len(A) - 1, K, {})\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n return self.solve(A, K)", "def largestsumofaverages(A: List[int], k: int) -> float:\n n = len(A)\n mtr = [[0 for i in range(n + 1)] for j in range(k + 1)]\n\n def rec(parts, arrIndex):\n if mtr[parts][arrIndex] != 0:\n return mtr[parts][arrIndex]\n if parts == 1:\n mtr[parts][arrIndex] = sum(A[:arrIndex + 1]) / (arrIndex + 1)\n return mtr[parts][arrIndex]\n for x in range(1, arrIndex + 1):\n mtr[parts][arrIndex] = max(mtr[parts][arrIndex], rec(parts - 1, x - 1) + sum(A[x:arrIndex + 1]) / (arrIndex + 1 - x))\n return mtr[parts][arrIndex]\n rec(k, n - 1)\n ans = sys.maxsize * -1\n for i in range(1, k + 1):\n ans = max(ans, mtr[i][-2])\n return ans", "def largestsumofaverages(A: List[int], K: int) -> float:\n self.memo = {}\n\n def helper(start, end, K, prefix):\n if (start, end, K) in self.memo.keys():\n return self.memo[start, end, K]\n if K == 0:\n return (prefix[end + 1] - prefix[start]) / (end - start + 1)\n if end == start:\n return prefix[end + 1] - prefix[end]\n if end < start:\n return 0\n maxAvg = 0\n for i in range(start, end):\n maxAvg = max(maxAvg, (prefix[i + 1] - prefix[start]) / (i - start + 1) + helper(i + 1, end, K - 1, prefix))\n self.memo[start, end, K] = maxAvg\n return maxAvg\n n = len(A)\n prefix = [0 for _ in range(n + 1)]\n for i in range(1, n + 1):\n prefix[i] = prefix[i - 1] + A[i - 1]\n ans = 0\n for k in range(K):\n ans = max(ans, helper(0, n - 1, k, prefix))\n return ans", "def largestsumofaverages(A: List[int], K: int) -> float:\n len_A = len(A)\n dp = [[0 if j else sum(A[:i + 1]) / (i + 1) for j in range(K)] for i in range(len_A)]\n for i in range(len_A):\n for j in range(1, K):\n if j > i:\n break\n for k in range(i):\n dp[i][j] = max(dp[i][j], dp[k][j - 1] + sum(A[k + 1:i + 1]) / (i - k))\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n p = [0]\n for i in range(n):\n p.append(p[i] + A[i])\n\n def average(i, j):\n return (p[j] - p[i]) / (j - i)\n dp = [[0] * n for _ in range(K)]\n for i in range(n):\n dp[0][i] = average(i, n)\n for k in range(1, K):\n for i in range(n):\n for j in range(i + 1, n):\n dp[k][i] = max(dp[k][i], average(i, j) + dp[k - 1][j])\n return dp[K - 1][0]", "def mean(l):\n return sum(l) / len(l)\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n DP = [self.mean(A[i:n]) for i in range(n)]\n for k in range(K - 1):\n for i in range(n):\n for j in range(i + 1, n):\n DP[i] = max(DP[i], self.mean(A[i:j]) + DP[j])\n return DP[0]", "def largestsumofaverages(A: List[int], K: int) -> float:\n\n def avg(array):\n return sum(array) / len(array)\n dp = [[0 for _ in range(K)] for _ in range(len(A))]\n dp[0][0] = A[0]\n for i in range(len(A)):\n for j in range(K):\n if j == 0:\n dp[i][j] = avg(A[:i + 1])\n else:\n for k in range(i):\n dp[i][j] = max(dp[i][j], dp[k][j - 1] + avg(A[k + 1:i + 1]))\n return dp[len(A) - 1][K - 1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n self.arr = [[None for i in range(K)] for i in range(len(A))]\n res = self.solve(A, 0, K, -1)\n return res\n\ndef solve(arr, i, grpLeft, lastInd):\n if i == len(arr):\n return 0\n if self.arr[lastInd + 1][grpLeft - 1] != None:\n return self.arr[lastInd + 1][grpLeft - 1]\n if grpLeft == 1:\n self.arr[lastInd + 1][0] = sum(arr[lastInd + 1:]) / (len(arr) - lastInd - 1)\n return self.arr[i][0]\n avg = float(sum(arr[lastInd + 1:i + 1])) / (i - lastInd)\n self.arr[lastInd + 1][grpLeft - 1] = max(self.solve(arr, i + 1, grpLeft, lastInd), avg + self.solve(arr, i + 1, grpLeft - 1, i))\n return self.arr[lastInd + 1][grpLeft - 1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n dp = [[0] * (K + 1) for i in range(n)]\n total = [A[0]]\n for i in range(1, n):\n total.append(A[i] + total[i - 1])\n\n def solve(start, k):\n if dp[start][k] != 0:\n return dp[start][k]\n if k == 1:\n dp[start][k] = (total[n - 1] - total[start] + A[start]) / (n - start)\n return dp[start][k]\n i = start\n while i + k <= n:\n temp = (total[i] - total[start] + A[start]) / (i - start + 1) + solve(i + 1, k - 1)\n dp[start][k] = max(dp[start][k], temp)\n i += 1\n return dp[start][k]\n return solve(0, K)", "def largestsumofaverages(A, K: int) -> float:\n dp = []\n for i in range(len(A)):\n tmp = []\n for j in range(1, 1 + K):\n tmp.append(0)\n dp.append(tmp)\n v = 0\n for i in range(len(dp)):\n v += A[i]\n for j in range(len(dp[0])):\n if j == 0:\n dp[i][j] = v / (i + 1)\n elif j == i:\n dp[i][j] = v\n for i in range(len(dp)):\n for j in range(1, min(i, K)):\n for t in range(i):\n dp[i][j] = max(dp[i][j], dp[t][j - 1] + self.avg(A[t + 1:i + 1]))\n return dp[-1][-1]\n\ndef avg(nums):\n return sum(nums) / len(nums)", "def largestsumofaverages(A: List[int], K: int) -> float:\n accsum = A[:]\n l = len(accsum)\n for i in range(1, l):\n accsum[i] += accsum[i - 1]\n cache = {}\n\n def dp(i, k):\n prev = accsum[i - 1] if i > 0 else 0\n if k == 1:\n res = (accsum[l - 1] - prev) / (l - i)\n cache[i, k] = res\n return res\n if (i, k) in cache:\n return cache[i, k]\n if l - i < k:\n return -float('inf')\n if l - i == k:\n res = accsum[l - 1] - prev\n cache[i, k] = res\n return res\n res = 0\n for j in range(i, l - k + 1):\n res = max(res, (accsum[j] - prev) / (j - i + 1) + dp(j + 1, k - 1))\n cache[i, k] = res\n return res\n return dp(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n memo = {}\n\n def fn(nums, k):\n if len(nums) <= k:\n return sum(nums)\n elif k == 1:\n return sum(nums) / len(nums)\n else:\n max_avg = 0\n for i in reversed(range(len(nums))):\n key = (tuple([num for num in nums[:i]]), k - 1)\n if key not in memo:\n memo[key] = fn([num for num in nums[:i]], k - 1)\n avg = memo[key] + sum(nums[i:]) / (len(nums) - i)\n max_avg = max(max_avg, avg)\n return max_avg\n return fn(A, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n averages = [[None for _ in range(n)] for _ in range(n)]\n for i in range(n):\n averages[i][i] = A[i]\n for i in range(n - 1):\n for j in range(i + 1, n):\n averages[i][j] = (averages[i][j - 1] * (j - i) + A[j]) / (j - i + 1)\n dp = [[None for _ in range(K)] for _ in range(n + 1)]\n\n def largestSum(i, count):\n if dp[i][count] != None:\n return dp[i][count]\n if i == n:\n dp[i][count] = 0\n return 0\n if count == K - 1:\n dp[i][count] = averages[i][n - 1]\n return averages[i][n - 1]\n largest = float('-inf')\n for k in range(n):\n largest = max(largest, averages[i][min(i + k, n - 1)] + largestSum(min(i + k + 1, n), count + 1))\n dp[i][count] = largest\n return largest\n return largestSum(0, 0)", "def largestsumofaverages(a: List[int], k: int) -> float:\n\n def rec(st, k):\n if (st, k) in cache:\n return cache[st, k]\n if k == 1:\n cache[st, k] = sum(a[st:]) / (len(a) - st)\n return cache[st, k]\n total = 0\n res = -math.inf\n for i in range(st, len(a) - k + 1):\n total += a[i]\n res = max(res, total / (i - st + 1) + rec(i + 1, k - 1))\n cache[st, k] = res\n return cache[st, k]\n cache = {}\n return rec(0, k)", "def find(dp, start, end, k, arr):\n if start > end:\n return -float('inf')\n if k <= 0:\n return -float('inf')\n if (start, end, k) in dp.keys():\n return dp[start, end, k]\n if start == end:\n if k == 1:\n return arr[start]\n return 0\n ans = 0\n total = 0\n count = 0\n for i in range(start, end + 1):\n total += arr[i]\n count += 1\n if k - 1 > 0:\n find(dp, i + 1, end, k - 1, arr)\n ans = max(ans, total / count + find(dp, i + 1, end, k - 1, arr))\n ans = max(ans, total / count)\n dp[start, end, k] = ans\n return ans\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n dp = {}\n return find(dp, 0, len(A) - 1, K, A)", "def largestsumofaverages(A: List[int], k: int) -> float:\n n = len(A)\n pre = list(itertools.accumulate([0] + A))\n dp = {}\n\n def dfs(i, k):\n if (i, k) in dp:\n return dp[i, k]\n if k == 1:\n dp[i, k] = (pre[-1] - pre[i]) / (n - i)\n return dp[i, k]\n ans = -float('inf')\n cur = 0\n for j in range(i, n - k + 1):\n ans = max(ans, (pre[j + 1] - pre[i]) / (j - i + 1) + dfs(j + 1, k - 1))\n dp[i, k] = ans\n return ans\n return dfs(0, k)", "def largestsumofaverages(A: List[int], K: int) -> float:\n\n def dp(n, k):\n if n < k:\n return 0\n if k == 1:\n return sum(A[:n]) / n\n (cur, ans) = (0, 0)\n for i in range(n - 1, 0, -1):\n cur += A[i]\n ans = max(ans, dp(i, k - 1) + cur / (n - i))\n return ans\n return dp(len(A), K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n dp = {}\n\n def f(i, k):\n if (i, k) not in dp:\n if k == 1:\n dp[i, k] = sum(A[i:]) / (n - i)\n else:\n dp[i, k] = max([sum(A[i:j]) / (j - i) + f(j, k - 1) for j in range(i + 1, n - k + 2)])\n return dp[i, k]\n return f(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n dp = [0] * (n + 1)\n sums = [0] * (n + 1)\n for i in range(1, n + 1):\n sums[i] = sums[i - 1] + A[i - 1]\n dp[i] = sums[i] / i\n for k in range(2, K + 1):\n tmp = [0] * (n + 1)\n for i in range(k, n + 1):\n for j in range(k - 1, i):\n tmp[i] = max(tmp[i], dp[j] + (sums[i] - sums[j]) / (i - j))\n dp = list(tmp)\n return dp[n]", "def largestsumofaverages(A: List[int], K: int) -> float:\n if K == 1:\n return sum(A) / len(A)\n memo = [[0] * len(A) for _ in range(K)]\n cumsum = [0] * len(A)\n for i in range(len(A)):\n cumsum[i] = cumsum[i - 1] + A[i]\n memo[0][i] = cumsum[i] / (i + 1)\n for i in range(1, K):\n for j in range(i, len(A)):\n tmp = 0\n for k in range(i - 1, j):\n tmp = max(tmp, memo[i - 1][k] + (cumsum[j] - cumsum[k]) / (j - k))\n memo[i][j] = tmp\n return memo[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n dp = [[0.0 for j in range(K + 1)] for i in range(len(A))]\n sums = [0] * len(A)\n sums[0] = A[0]\n for i in range(1, len(A)):\n sums[i] = sums[i - 1] + A[i]\n for k in range(1, K + 1):\n for i in range(len(A)):\n if k == 1:\n dp[i][k] = sums[i] / (i + 1)\n elif k > i + 1:\n continue\n else:\n for j in range(k - 1, i + 1):\n avg1 = dp[j - 1][k - 1]\n avg2 = (sums[i] - sums[j - 1]) / (i - j + 1)\n if dp[i][k] < avg1 + avg2:\n dp[i][k] = avg1 + avg2\n return dp[-1][K]", "from functools import lru_cache\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n\n def rec(j, K):\n nonlocal A\n if K == 1:\n return sum(A[0:j + 1]) / (j + 1)\n res = 0\n runningsum = 0\n for i in range(j, K - 2, -1):\n runningsum += A[i]\n res = max(res, runningsum / (j - i + 1) + rec(i - 1, K - 1))\n return res\n return rec(len(A) - 1, K)", "import functools\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n\n def dp(start, p):\n if p == 1:\n return sum(A[start:]) / (len(A) - start)\n if start == len(A):\n return 0\n curr_sum = A[start]\n ret = 0\n for i in range(start + 1, len(A)):\n avg = curr_sum / (i - start)\n ret = max(ret, avg + dp(i, p - 1))\n curr_sum += A[i]\n return ret\n return dp(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n N = len(A)\n P = [0]\n for a in A:\n P.append(P[-1] + a)\n dp = [0] * (N + 1)\n for i in range(K):\n dp2 = [0] * (N + 1)\n for j in range(i, N + 1):\n if i == 0 and j != 0:\n dp2[j] = P[j] / j\n continue\n for k in range(i - 1, j):\n dp2[j] = max(dp2[j], dp[k] + (P[j] - P[k]) / (j - k))\n dp = dp2\n return dp[-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n num_count = len(A)\n previous_best = [0] * num_count\n current_best = [0] * num_count\n previous_best[0] = A[0]\n for index in range(1, num_count):\n A[index] += A[index - 1]\n previous_best[index] = A[index] / (index + 1)\n for partition_count in range(1, K):\n for end_index in range(partition_count, num_count - K + partition_count + 1):\n current_best[end_index] = max(((A[end_index] - A[start_index]) / (end_index - start_index) + previous_best[start_index] for start_index in range(partition_count - 1, end_index)))\n (current_best, previous_best) = (previous_best, current_best)\n return previous_best[-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n memoDict = {}\n\n def recurse(i, k):\n n = len(A)\n max_win = n - i - (k - 1)\n if (i, k) in memoDict:\n return memoDict[i, k]\n if k == 0:\n return sum(A[i:]) / (n - i)\n else:\n max_sum = 0\n for ind in range(1, max_win):\n lul = recurse(i + ind, k - 1) + sum(A[i:i + ind]) / ind\n max_sum = max(max_sum, lul)\n memoDict[i, k] = max_sum\n return max_sum\n flips = recurse(0, K - 1)\n return flips", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n from functools import lru_cache\n\n def dp(i, j):\n if i == n:\n return float('-inf')\n if j == 1:\n return sum(A[i:]) / (n - i)\n ans = float('-inf')\n cur_sum = 0\n for l in range(i, n):\n cur_sum += A[l]\n ans = max(ans, cur_sum / (l - i + 1) + dp(l + 1, j - 1))\n return ans\n return dp(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n prefix_sum = [A[0]]\n for a in A[1:]:\n prefix_sum.append(prefix_sum[-1] + a)\n dp = [[0 for _ in range(len(A))] for _ in range(K)]\n for i in range(len(A)):\n dp[0][i] = prefix_sum[i] / (i + 1)\n for k in range(1, K):\n for i in range(k, len(A)):\n for j in range(k - 1, i):\n dp[k][i] = max(dp[k][i], dp[k - 1][j] + (prefix_sum[i] - prefix_sum[j]) / (i - j))\n return dp[K - 1][len(A) - 1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n dp = [[0] * K for _ in range(n)]\n dp[0][0] = A[0]\n for i in range(1, n):\n dp[i][0] = (dp[i - 1][0] * i + A[i]) / (i + 1)\n for k in range(1, K):\n for i in range(k, n):\n curr_sum = 0\n for j in reversed(range(k, i + 1)):\n curr_sum += A[j]\n dp[i][k] = max(dp[i][k], dp[j - 1][k - 1] + curr_sum / (i + 1 - j))\n return dp[n - 1][K - 1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n if not A:\n return 0\n n = len(A)\n sums = [0] * (n + 1)\n dp = [[float('-inf')] * (n + 1) for _ in range(K + 1)]\n for i in range(1, n + 1):\n sums[i] = sums[i - 1] + A[i - 1]\n dp[1][i] = sums[i] / i\n for k in range(2, K + 1):\n for i in range(k, n + 1):\n for j in range(k - 1, i):\n ave_i_j = (sums[i] - sums[j]) / (i - j)\n dp[k][i] = max(dp[k][i], dp[k - 1][j] + ave_i_j)\n return dp[K][n]", "def largestsumofaverages(A, K):\n N = len(A)\n S = [0] * (1 + N)\n for i in range(1, N + 1):\n S[i] = S[i - 1] + A[i - 1]\n B = []\n for i in range(1 + N):\n B.append([0] * (1 + K))\n for m in range(1, N + 1):\n for w in range(1, K + 1):\n if w == 1:\n B[m][w] = S[m] / m\n continue\n if m < w:\n break\n B[m][w] = -1000000\n for e in range(1, m - w + 2):\n B[m][w] = max(B[m][w], B[m - e][w - 1] + (S[m] - S[m - e]) / e)\n return B[N][K]", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n dp = [[0] * (K + 1) for _ in range(n)]\n s = 0\n for i in range(n):\n s += A[i]\n dp[i][1] = s * 1.0 / (i + 1)\n for k in range(2, K + 1):\n for i in range(k - 1, n):\n s = 0\n for m in range(i, k - 2, -1):\n s += A[m]\n dp[i][k] = max(dp[i][k], dp[m - 1][k - 1] + s * 1.0 / (i - m + 1))\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n cumsum = [A[0]]\n for i in range(1, len(A)):\n cumsum.append(cumsum[-1] + A[i])\n cumsum.append(0)\n\n def rec(i, K):\n if K == 1:\n return (cumsum[len(A) - 1] - cumsum[i - 1]) / (len(A) - i)\n return max(((cumsum[j] - cumsum[i - 1]) / (j - i + 1) + rec(j + 1, K - 1) for j in range(i, len(A) - K + 1)))\n return rec(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n A = [0] + A\n dp = [[0] * (K + 1) for _ in range(n + 1)]\n for i in range(1, n + 1):\n dp[i][0] = -float('inf')\n for i in range(1, n + 1):\n for k in range(1, min(i + 1, K + 1)):\n sum_s = 0\n for j in range(i, k - 1, -1):\n sum_s += A[j]\n dp[i][k] = max(dp[i][k], dp[j - 1][k - 1] + sum_s / (i - j + 1))\n res = 0\n for i in range(1, K + 1):\n res = max(res, dp[n][i])\n return res", "def largestsumofaverages(A: List[int], K: int) -> float:\n l_A = len(A)\n memo = {(l_A, 0): 0}\n\n def dfs(idx, rem):\n if rem == 0 or l_A - idx < rem:\n return 0\n if rem == 1:\n return sum(A[idx:]) / (l_A - idx)\n if (idx, rem) in memo:\n return memo[idx, rem]\n sum_so_far = 0\n avg = 0\n best = 0\n for i in range(idx, l_A):\n sum_so_far += A[i]\n avg = sum_so_far / (i - idx + 1)\n best = max(best, avg + dfs(i + 1, rem - 1))\n memo[idx, rem] = best\n return best\n return dfs(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n if not A or len(A) < K:\n return 0\n for i in range(1, len(A)):\n A[i] += A[i - 1]\n cache = {}\n\n def cal(n, k):\n if n <= 0 or k <= 0:\n return 0\n if n < k:\n return 0\n if (n, k) in cache:\n return cache[n, k]\n if k == 1:\n cache[n, 1] = A[n - 1] / n\n return cache[n, 1]\n (res, cur) = (0, 0)\n for i in range(n - 1, 0, -1):\n res = max(res, (A[n - 1] - A[i - 1]) / (n - i) + cal(i, k - 1))\n cache[n, k] = res\n return res\n return cal(len(A), K)", "from functools import lru_cache\n\ndef largestsumofaverages(A, K):\n l = len(A)\n\n def dp(n, k):\n if n < k:\n return 0\n if k == 1:\n return sum(A[:n]) / float(n)\n (cursum, ans) = (0, 0)\n for i in range(n - 1, -1, -1):\n cursum += A[i]\n ans = max(ans, dp(i, k - 1) + cursum / float(n - i))\n return ans\n return dp(l, K)", "import itertools\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n dp = [[0] * len(A) for _ in range(K)]\n cur_sum = 0\n for j in range(len(A)):\n cur_sum += A[j]\n dp[0][j] = float(cur_sum) / (j + 1)\n for i in range(1, K):\n for j in range(len(A)):\n cur_sum = 0\n for k in range(j, i - 1, -1):\n cur_sum += A[k]\n dp[i][j] = max(dp[i][j], dp[i - 1][k - 1] + float(cur_sum) / (j - k + 1))\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n prefix = [0]\n for a in A:\n prefix.append(prefix[-1] + a)\n\n def soa(i, k):\n if len(prefix) - 1 - i <= k:\n return prefix[-1] - prefix[i]\n elif k == 1:\n return (prefix[-1] - prefix[i]) / (len(prefix) - 1 - i)\n best = 0\n for j in range(i + 1, len(prefix) - (k - 1)):\n best = max(best, (prefix[j] - prefix[i]) / (j - i) + soa(j, k - 1))\n return best\n return soa(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n presum = [0] + list(itertools.accumulate(A))\n\n def mean(i, j):\n return (presum[j + 1] - presum[i]) / (j - i + 1)\n n = len(A)\n old = [[mean(i, j) if i <= j else 0 for j in range(n)] for i in range(n)]\n new = [[0 for j in range(n)] for i in range(n)]\n mval = mean(0, n - 1)\n for k in range(2, K + 1):\n for i in range(n - k + 1):\n max_val = -float('inf')\n for mid in range(i, n - k + 1):\n max_val = max(max_val, mean(i, mid) + old[mid + 1][n - 1])\n new[i][n - 1] = max_val\n (old, new) = (new, old)\n mval = max(mval, old[0][-1])\n return mval", "def largestsumofaverages(A: List[int], K: int) -> float:\n prefix = [A[0]]\n for i in range(1, len(A)):\n prefix.append(prefix[i - 1] + A[i])\n dp = [[prefix[i] / (i + 1) if k == 1 else 0 for k in range(K + 1)] for i in range(len(A))]\n for i in range(1, len(A)):\n for k in range(2, min(i + 2, K + 1)):\n val = float('-inf')\n _sum = 0\n for j in range(i, 0, -1):\n _sum += A[j]\n val = max(dp[j - 1][k - 1] + _sum / (i - j + 1), val)\n dp[i][k] = val\n return dp[len(A) - 1][K]", "def largestsumofaverages(A: List[int], K: int) -> float:\n dp = [[0 for k in range(K + 1)] for i in range(len(A))]\n dp[0][1] = A[0]\n for (count, i) in enumerate(range(1, len(A))):\n dp[i][1] = (dp[i - 1][1] * (count + 1) + A[i]) / (count + 2)\n for i in range(1, len(A)):\n for k in range(2, min(i + 2, K + 1)):\n val = float('-inf')\n _sum = 0\n for j in range(i, 0, -1):\n _sum += A[j]\n val = max(dp[j - 1][k - 1] + _sum / (i - j + 1), val)\n dp[i][k] = val\n return dp[len(A) - 1][K]", "def largestsumofaverages(A: List[int], K: int) -> float:\n dp = [[0 for y in range(len(A))] for x in range(K)]\n add = 0\n pref = [0 for i in range(len(A))]\n for x in range(len(A)):\n add += A[x]\n pref[x] = add\n for x in range(len(A)):\n dp[0][x] = pref[x] / (x + 1)\n for y in range(1, K):\n dp[y][0] = A[0]\n for x in range(1, K):\n for y in range(1, len(A)):\n val1 = pref[y] / (y + 1)\n maxi = val1\n for z in range(y):\n val = dp[x - 1][z] + (pref[y] - pref[z]) / (y - z)\n maxi = max(maxi, val)\n dp[x][y] = maxi\n return dp[-1][-1]", "def largestsumofaverages(A, K):\n m = len(A)\n dp = [[None] * (K + 1) for _ in range(m)]\n for k in range(1, K + 1):\n for j in range(k - 1, m):\n if k == 1:\n dp[j][k] = sum(A[:j + 1]) / (j + 1)\n else:\n dp[j][k] = max((dp[i][k - 1] + sum(A[i + 1:j + 1]) / (j - i) for i in range(k - 2, j)))\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n suffix_sums = [0] * (len(A) + 1)\n for i in range(len(A) - 1, -1, -1):\n suffix_sums[i] = A[i] + suffix_sums[i + 1]\n memo = {}\n\n def largest_starting_at(i, new_k):\n if i == len(A):\n return 0\n if new_k == 1:\n return suffix_sums[i] / (len(A) - i)\n if (i, new_k) in memo:\n return memo[i, new_k]\n best = 0\n for size in range(1, len(A) - i):\n best = max(best, (suffix_sums[i] - suffix_sums[i + size]) / size + largest_starting_at(i + size, new_k - 1))\n memo[i, new_k] = best\n return memo[i, new_k]\n return largest_starting_at(0, K)", "def largestsumofaverages(A, K: int) -> float:\n\n def avg(array):\n return sum(array) / len(array)\n dp = [[0 for _ in range(K + 1)] for _ in range(len(A))]\n means = [[0 for _ in range(len(A))] for _ in range(len(A))]\n for i in range(len(A)):\n for j in range(i, len(A)):\n means[i][j] = avg(A[i:j + 1])\n for i in range(len(A)):\n dp[i][1] = means[0][i]\n for i in range(1, len(A)):\n for j in range(2, min(K + 1, i + 1 + 1)):\n for k in range(max(i - 1, j - 1 - 1), -1, -1):\n temp_last_group = means[k + 1][i]\n temp_sum_prev = dp[k][j - 1]\n dp[i][j] = max(dp[i][j], temp_last_group + temp_sum_prev)\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n n = len(A)\n dp = [[-math.inf] * K for _ in range(n)]\n (sv, sc) = (0, {-1: 0})\n for (i, v) in enumerate(A):\n sv += v\n sc[i] = sv\n dp[0][0] = A[0]\n for r in range(n):\n for i in range(0, r):\n for k in range(min(K, r + 1)):\n if k == 0:\n dp[r][k] = (sc[r] - sc[-1]) / (r + 1)\n else:\n candidate = dp[i][k - 1] + (sc[r] - sc[i]) / (r - i)\n dp[r][k] = max(dp[r][k], candidate)\n return dp[-1][-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n prefixSum = [0]\n for x in A:\n prefixSum.append(prefixSum[-1] + x)\n\n def avg(i, j):\n return (prefixSum[j] - prefixSum[i]) / (j - i)\n n = len(A)\n dp = [avg(i, n) for i in range(n)]\n for k in range(K - 1):\n for i in range(n):\n for j in range(i + 1, n):\n dp[i] = max(dp[i], avg(i, j) + dp[j])\n return dp[0]", "def largestsumofaverages(A, K):\n p = [0]\n for x in A:\n p.append(x + p[-1])\n\n def avg(i, j):\n return (p[j] - p[i]) / (j - i)\n N = len(A)\n dp = [avg(i, N) for i in range(N)]\n for k in range(K - 1):\n for i in range(N):\n for j in range(i + 1, N):\n dp[i] = max(dp[i], avg(i, j) + dp[j])\n return dp[0]", "def largestsumofaverages(A: List[int], K: int) -> float:\n N = len(A)\n\n def dfs(index, remain):\n if remain <= 0:\n return sum(A[index:]) / (N - index)\n if index >= N:\n return 0\n ans = 0\n for i in range(index + 1, N):\n ans = max(ans, sum(A[index:i]) / (i - index) + dfs(i, remain - 1))\n return ans\n res = dfs(0, K - 1)\n return res", "def largestsumofaverages(A: List[int], K: int) -> float:\n if K == 1:\n return sum(A) / len(A)\n biggest = [[[None for temp in range(K + 1)] for col in range(len(A))] for row in range(len(A))]\n for start in range(len(A)):\n for end in range(start, len(A), 1):\n biggest[start][end][1] = sum(A[start:end + 1]) / len(A[start:end + 1])\n for curK in range(2, K + 1):\n startEnd = len(A) - curK + 1\n if curK == K:\n startEnd = 1\n for start in range(0, startEnd, 1):\n tempNo = 0\n for middle in range(start, len(A) - curK + 1, 1):\n theNo = biggest[start][middle][1] + biggest[middle + 1][len(A) - 1][curK - 1]\n if theNo > tempNo:\n tempNo = theNo\n biggest[start][len(A) - 1][curK] = tempNo\n return biggest[0][len(A) - 1][K]", "def largestsumofaverages(A: List[int], K: int) -> float:\n if len(A) <= K:\n return sum(A)\n A1 = []\n s = 0\n for i in A:\n s += i\n A1.append(s)\n n = len(A)\n last = [A1[i] / (i + 1) for i in range(n)]\n for k in range(1, K):\n cur = [A[0]]\n for i in range(1, n):\n stage_max = 0\n for (j1, j) in enumerate(last[:i]):\n stage_max = max(stage_max, j + (A1[i] - A1[j1]) / (i - j1))\n cur.append(stage_max)\n last = cur\n return last[-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n L = len(A)\n reduced_dp = [0 for _ in range(L)]\n prefix_sum = [0 for _ in range(L + 1)]\n for i in range(1, L + 1):\n prefix_sum[i] = prefix_sum[i - 1] + A[i - 1]\n reduced_dp[i - 1] = prefix_sum[i] / i\n for k in range(2, K + 1):\n for i in reversed(range(1, L)):\n if k <= i + 1:\n for j in range(-1, i):\n ave = (prefix_sum[i + 1] - prefix_sum[j + 1]) / (i - j)\n if j == -1:\n tmp = 0\n else:\n tmp = reduced_dp[j]\n if ave + tmp > reduced_dp[i]:\n reduced_dp[i] = ave + tmp\n return reduced_dp[-1]", "def largestsumofaverages(A: List[int], K: int) -> float:\n prefix = [0] + A.copy()\n for i in range(1, len(prefix)):\n prefix[i] += prefix[i - 1]\n\n def query(i, j):\n return prefix[j + 1] - prefix[i]\n\n def get_average(i, j):\n return query(i, j) / (j - i + 1)\n N = len(A)\n cache = {}\n\n def dfs(i, k):\n if k < 0:\n return -float('inf')\n if (i, k) in cache:\n return cache[i, k]\n if i == N:\n if k == 0:\n return 0\n else:\n return -float('inf')\n res = -float('inf')\n for j in range(i, N):\n take = dfs(j + 1, k - 1) + get_average(i, j)\n res = max(res, take)\n cache[i, k] = res\n return res\n return dfs(0, K)", "def largestsumofaverages(A: List[int], K: int) -> float:\n if not A:\n return 0\n dp = {}\n averages = [[None] * len(A) for _ in range(len(A))]\n for i in range(len(A)):\n averages[i][i] = A[i]\n for j in range(i + 1, len(A)):\n averages[i][j] = (averages[i][j - 1] * (j - i) + A[j]) / (j - i + 1)\n\n def recurse(A, K, start):\n if start >= len(A):\n return 0\n if K == 1:\n return averages[start][len(A) - 1]\n if (K, start) in dp:\n return dp[K, start]\n dp[K, start] = -math.inf\n for i in range(start, len(A)):\n dp[K, start] = max(dp[K, start], averages[start][i] + recurse(A, K - 1, i + 1))\n return dp[K, start]\n return recurse(A, K, 0)", "from itertools import combinations\nfrom functools import lru_cache\n\ndef largestsumofaverages(A: List[int], K: int) -> float:\n\n def mean(A):\n return sum(A) / len(A)\n\n def recurse(start, end, k=1):\n if k == K:\n return mean(A[start:end])\n if len(A) == 1:\n return A[0]\n maxval = 0\n for i in range(start + 1, end):\n maxval = max(maxval, mean(A[start:i]) + recurse(i, end, k + 1))\n return maxval\n N = len(A)\n return recurse(0, N)"], "starter_code": "def largestsumofaverages(A: List[int], K: int) -> float:\n", "input_output": {"fn_name": "largestSumOfAverages", "inputs": [[[9, 1, 2, 3, 9], 3]], "outputs": [20.0]}, "difficulty": "MEDIUM", "raw_tags": ["Prefix Sum", "Array", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures", "Range queries"], "skill_types": ["Dynamic programming", "Data structures", "Range queries"], "url": "https://leetcode.com/problems/largest-sum-of-averages/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "largestsumofaverages", "task_id": "TACO_lite/287", "example": [[[[9, 1, 2, 3, 9], 3]], [20.0]]} +{"requirement": "Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence.\nNote: No two strings are the second most repeated, there will be always a single string.\nExample 1:\nInput:\nN = 6\narr[] = {aaa, bbb, ccc, bbb, aaa, aaa}\nOutput: bbb\nExplanation: \"bbb\" is the second most \noccurring string with frequency 2.\nExample 2:\nInput: \nN = 6\narr[] = {geek, for, geek, for, geek, aaa}\nOutput: for\nExplanation: \"for\" is the second most\noccurring string with frequency 2.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function secFrequent() which takes the string array arr[] and its size N as inputs and returns the second most frequent string in the array.\nExpected Time Complexity: O(N*max(|S_{i}|).\nExpected Auxiliary Space: O(N*max(|S_{i}|).\nConstraints:\n1<=N<=10^{3}", "solutions": ["def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n a = sorted(d.items(), key=lambda x: x[1])\n return a[-2][0]", "def secfrequent(arr, n):\n dic = {}\n for ele in arr:\n dic[ele] = dic.get(ele, 0) + 1\n max_freq = max(dic.values())\n a = [x for x in dic.values() if x != max_freq]\n a.sort()\n for x in dic:\n if dic[x] == a[-1]:\n return x\n return '-1'", "def secfrequent(arr, n):\n s = {}\n for i in arr:\n if i not in s:\n s[i] = 1\n else:\n s[i] = s[i] + 1\n lar = -1\n pos = -1\n for i in s:\n if lar < s[i]:\n lar = s[i]\n pos = i\n slar = -1\n spos = -1\n for i in s:\n if s[i] > slar and s[i] < lar:\n slar = s[i]\n spos = i\n if spos != -1:\n return spos\n else:\n return ''", "def secfrequent(arr, n):\n d = {}\n for i in range(len(arr)):\n if arr[i] in d:\n d[arr[i]] += 1\n else:\n d[arr[i]] = 1\n d = sorted(d.items(), key=lambda x: x[1])\n m = d[-2]\n return m[0]", "from collections import Counter\n\ndef secfrequent(arr, n):\n a = []\n h = {}\n for i in arr:\n if i in h:\n h[i] += 1\n else:\n h[i] = 1\n for i in h:\n a.append(h[i])\n a.sort()\n ans = a[-2]\n for i in h:\n if h[i] == ans:\n return i", "def secfrequent(arr, n):\n freq = {}\n for string in arr:\n freq[string] = freq.get(string, 0) + 1\n most_common = ('', 0)\n second_most_common = ('', 0)\n for (string, frequency) in freq.items():\n if frequency > most_common[1]:\n second_most_common = most_common\n most_common = (string, frequency)\n elif frequency > second_most_common[1] and string != most_common[0]:\n second_most_common = (string, frequency)\n return second_most_common[0]", "def secfrequent(arr, n):\n a = []\n d = {}\n for i in arr:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for i in d:\n a.append(d[i])\n a.sort()\n res = a[-2]\n for i in d:\n if d[i] == res:\n return i", "def secfrequent(arr, n):\n dict1 = {}\n for i in arr:\n if i in dict1:\n dict1[i] += 1\n else:\n dict1[i] = 1\n a = sorted(dict1.values())\n b = max(a)\n a.remove(b)\n c = max(a)\n for i in dict1:\n if dict1[i] == c:\n return i", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n l = []\n for i in d.values():\n l.append(i)\n l.sort()\n a = l[-2]\n for (k, v) in d.items():\n if v == a:\n return k", "from collections import Counter\nimport operator\n\ndef secfrequent(arr, n):\n dic = {}\n for i in arr:\n if i in dic:\n dic[i] += 1\n else:\n dic[i] = 1\n lst = []\n for (i, j) in dic.items():\n lst.append([i, j])\n lst.sort(key=operator.itemgetter(1, 0), reverse=True)\n return lst[1][0]", "from collections import Counter\n\ndef secfrequent(arr, n):\n d = Counter(arr)\n first = float('-inf')\n second = float('-inf')\n for val in d.values():\n if val > first:\n second = first\n first = val\n elif val > second and first != val:\n second = val\n if second == float('-inf'):\n return ''\n for (k, v) in d.items():\n if v == second:\n return k", "def secfrequent(arr, n):\n a = []\n d = dict()\n for ele in arr:\n d[ele] = 0\n for ele in arr:\n d[ele] = d[ele] + 1\n for ele in d:\n a.append(d[ele])\n a.sort()\n b = a[-2]\n for i in d:\n if d[i] == b:\n return i", "def secfrequent(arr, n):\n d = {}\n for word in arr:\n d.setdefault(word, 0)\n d[word] += 1\n f_max = float('-inf')\n s_max = float('-inf')\n for val in d:\n if d[val] > f_max:\n s_max = f_max\n f_max = d[val]\n if d[val] > s_max and d[val] != f_max:\n s_max = d[val]\n for i in d:\n if d[i] == s_max:\n return i\n return ''", "def secfrequent(arr, n):\n d = {}\n for word in arr:\n d.setdefault(word, 0)\n d[word] += 1\n val = list(d.values())\n val.sort()\n mx = val[-2]\n for i in d:\n if d[i] == mx:\n return i", "from collections import Counter\n\ndef secfrequent(arr, n):\n freq = Counter(arr)\n items = list(freq.items())\n items.sort(key=lambda x: x[1])\n return items[-2][0]", "from collections import Counter\n\ndef compare(item):\n return item[1]\n\ndef secfrequent(arr, n):\n freq = Counter(arr)\n items = list(freq.items())\n items.sort(key=compare)\n return items[-2][0]", "from collections import Counter\n\ndef secfrequent(arr, n):\n charFreq = Counter(arr)\n items = list(charFreq.items())\n items.sort(key=lambda x: x[1], reverse=True)\n return items[1][0]", "def secfrequent(arr, n):\n freq = {}\n for i in range(n):\n freq[arr[i]] = freq.get(arr[i], 0) + 1\n max_freq = -1\n sec_max_freq = -1\n max_freq_str = ''\n sec_max_freq_str = ''\n for key in freq:\n if freq[key] > max_freq:\n sec_max_freq = max_freq\n sec_max_freq_str = max_freq_str\n max_freq = freq[key]\n max_freq_str = key\n elif freq[key] > sec_max_freq and freq[key] != max_freq:\n sec_max_freq = freq[key]\n sec_max_freq_str = key\n return sec_max_freq_str if freq else None", "def secfrequent(arr, n):\n dict1 = {}\n for i in arr:\n if i in dict1:\n dict1[i] += 1\n else:\n dict1[i] = 1\n m = sorted(dict1.values())[-2]\n for i in arr:\n if dict1[i] == m:\n return i", "def secfrequent(arr, n):\n dictt = {}\n for i in arr:\n if i in dictt:\n dictt[i] += 1\n else:\n dictt[i] = 1\n k = sorted(dictt.values())[-2]\n for i in dictt:\n if dictt[i] == k:\n return i", "from collections import Counter\n\ndef secfrequent(arr, n):\n dict1 = {}\n for i in arr:\n if i in dict1:\n dict1[i] += 1\n else:\n dict1[i] = 1\n a = sorted(dict1.values())\n b = max(a)\n a.remove(b)\n c = max(a)\n for i in dict1:\n if dict1[i] == c:\n return i", "import operator\n\ndef secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n l = [[i, d[i]] for i in d]\n l = sorted(l, reverse=True, key=operator.itemgetter(1))\n return l[1][0]", "def secfrequent(arr, n):\n res = []\n freq = {}\n for i in arr:\n freq[i] = freq.get(i, 0) + 1\n for i in freq:\n res.append(freq[i])\n res.sort()\n ans = res[-2]\n for i in freq:\n if freq[i] == ans:\n return i", "def secfrequent(arr, n):\n a = []\n d = {}\n for i in arr:\n d[i] = d.get(i, 0) + 1\n for i in d:\n a.append(d[i])\n a.sort()\n ans = a[-2]\n for i in d:\n if d[i] == ans:\n return i", "def secfrequent(arr, n):\n lst = []\n dic = {}\n for i in arr:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n for i in dic:\n lst.append(dic[i])\n lst.sort()\n for i in dic:\n if dic[i] == lst[-2]:\n return i", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n d1 = sorted(d.values())\n z = d1[-2]\n for i in d:\n if d[i] == z:\n return i", "def secfrequent(arr, n):\n dir1 = {}\n ans = []\n for i in arr:\n dir1[i] = dir1.get(i, 0) + 1\n ans = list(dir1.values())\n ans.sort()\n ans2 = ans[-2]\n for i in dir1:\n if dir1[i] == ans2:\n return i", "def secfrequent(arr, n):\n d = {}\n f = 0\n for i in arr:\n d.update({i: arr.count(i)})\n max = -1\n for i in d.values():\n if i > max:\n max = i\n max1 = -1\n for i in d.values():\n if i > max1 and i < max:\n max1 = i\n for i in d.keys():\n if d[i] == max1:\n f = 1\n return i\n if f == 0:\n return ''", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n d[i] = d.get(i, 0) + 1\n l = []\n for i in d:\n l.append((d[i], i))\n l.sort()\n return l[-2][1]", "def secfrequent(arr, n):\n l = list(set(arr))\n l2 = []\n l3 = []\n for i in l:\n cnt = arr.count(i)\n l2.append(cnt)\n s = sorted(l2)\n res = s[-2]\n for i in l:\n cnt = arr.count(i)\n if cnt == res:\n l3.append(i)\n return l3[0]", "def secfrequent(arr, n):\n dic = {}\n for i in arr:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n sorted_dic = sorted(dic.items(), key=lambda item: item[1])\n return sorted_dic[-2][0]", "def secfrequent(arr, n):\n dct = {}\n for i in range(n):\n if arr[i] in dct:\n dct[arr[i]] += 1\n else:\n dct[arr[i]] = 1\n k = 0\n s = ''\n for i in dct:\n if dct[i] > k:\n s = i\n k = dct[i]\n dct.pop(s)\n k = 0\n s = ''\n for i in dct:\n if dct[i] > k:\n s = i\n k = dct[i]\n return s", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n m = 0\n for i in d:\n if d[i] > m:\n m = d[i]\n m1 = 0\n mi = ''\n for i in d:\n if d[i] > m1 and d[i] != m:\n m1 = d[i]\n mi = i\n return mi", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n (fs, ss) = ('', '')\n (m, ms) = (0, 0)\n for i in d:\n if d[i] >= m:\n (ms, ss) = (m, fs)\n (m, fs) = (d[i], i)\n elif d[i] > ms:\n (ms, ss) = (d[i], i)\n return ss", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n res = []\n for i in d:\n res.append([i, d[i]])\n if len(res) == 1:\n return ''\n res.sort(key=lambda x: x[1])\n return res[len(res) - 2][0]", "from collections import Counter\n\ndef secfrequent(arr, n):\n d = sorted(Counter(arr).items(), key=lambda x: x[1], reverse=True)\n return d[1][0]", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n l = -1\n s = -1\n for i in arr:\n if d[i] > l:\n s = l\n l = d[i]\n elif d[i] > s and d[i] < l:\n s = d[i]\n if s == -1:\n return ''\n else:\n for i in arr:\n if d[i] == s:\n return i", "def secfrequent(arr, n):\n freq = {}\n for word in arr:\n if word in freq:\n freq[word] += 1\n else:\n freq[word] = 1\n max1 = 0\n max2 = 0\n res1 = ''\n res2 = ''\n for (val, key) in freq.items():\n if key > max1:\n max2 = max1\n max1 = key\n res2 = res1\n res1 = val\n elif key > max2:\n max2 = key\n res2 = val\n return res2", "def secfrequent(arr, n):\n if len(arr) == 0:\n return False\n my_dict = {}\n for i in arr:\n if i in my_dict:\n my_dict[i] += 1\n else:\n my_dict[i] = 1\n sorted_dict = sorted(my_dict.items(), key=lambda x: x[1], reverse=True)\n return sorted_dict[1][0]", "def secfrequent(arr, n):\n dic = {}\n for i in arr:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n x = []\n for i in dic.keys():\n x.append(dic[i])\n x.sort()\n x.reverse()\n for i in dic.keys():\n if dic[i] == x[1]:\n return i", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n d[i] = 0\n for i in arr:\n d[i] += 1\n mx = 0\n val = ''\n for i in arr:\n if d[i] > mx:\n mx = d[i]\n mx2 = 0\n for i in arr:\n if mx > d[i] > mx2:\n mx2 = d[i]\n val = i\n return val", "from collections import Counter\n\ndef secfrequent(arr, n):\n all_strings = dict(Counter(arr))\n store = []\n for i in sorted(all_strings, key=all_strings.get):\n if i not in store:\n store.append(i)\n return store[-2]", "from collections import Counter\n\ndef secfrequent(arr, n):\n ans = Counter(arr)\n f = True\n fm = 0\n ele1 = ''\n if len(ans) == 1:\n return ''\n for (i, j) in ans.items():\n if f:\n fm = j\n ele1 = i\n f = False\n if j > fm:\n fm = j\n ele1 = i\n ans.pop(ele1)\n v = fm\n f = True\n for (i, j) in ans.items():\n if f:\n fm = j\n ele1 = i\n f = False\n if j > fm:\n fm = j\n ele1 = i\n if v == fm:\n return ''\n return ele1", "def secfrequent(arr, n):\n hmap = {}\n for i in range(n):\n if arr[i] in hmap:\n hmap[arr[i]] += 1\n else:\n hmap[arr[i]] = 1\n sorted_hmap = sorted(hmap.items(), key=lambda x: x[1], reverse=True)\n return sorted_hmap[1][0]", "def secfrequent(arr, n):\n freq = {}\n for i in arr:\n if i not in freq:\n freq[i] = 0\n freq[i] += 1\n if len(freq) == 1:\n return ''\n lis = list(freq.items())\n lis.sort(key=lambda x: x[1], reverse=True)\n return lis[1][0]", "def secfrequent(arr, n):\n dic = {}\n maxx = 0\n for each in arr:\n if each not in dic:\n dic[each] = 1\n else:\n dic[each] += 1\n maxx = max(maxx, dic[each])\n (wrd, freq) = ('', 0)\n for (i, j) in dic.items():\n if j > freq and j < maxx:\n (wrd, freq) = (i, j)\n return wrd", "from collections import Counter\n\ndef secfrequent(arr, n):\n c = Counter(arr)\n l = [i for i in c.values()]\n l.sort(reverse=True)\n x = l[1]\n for i in c:\n if c[i] == x:\n return i", "def secfrequent(arr, n):\n d = {}\n l = []\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n s = sorted(d.values())\n for i in d:\n if d[i] == s[-2]:\n return i", "from collections import Counter\n\ndef secfrequent(a, n):\n d = {}\n for i in range(len(arr)):\n if arr[i] in d:\n d[arr[i]] += 1\n else:\n d[arr[i]] = 1\n d = sorted(d.items(), key=lambda x: x[1], reverse=True)\n m = d[1]\n return m[0]", "def secfrequent(arr, n):\n dict = {}\n for i in arr:\n if i in dict:\n dict[i] += 1\n else:\n dict[i] = 1\n lst = []\n for i in dict:\n lst.append(dict[i])\n m = max(lst)\n lst.remove(m)\n m = max(lst)\n for i in dict:\n if dict[i] == m:\n return i", "from collections import Counter\n\ndef secfrequent(arr, n):\n c = Counter(arr)\n c = sorted(c.items(), reverse=True, key=lambda kv: kv[1])\n return c[1][0]", "from collections import Counter\n\ndef secfrequent(arr, n):\n c = Counter(arr)\n m = sorted(c.values())[-2]\n for (k, v) in c.items():\n if v == m:\n return k", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n l = []\n for (k, v) in d.items():\n l.append(v)\n l = sorted(l)\n for (k, v) in d.items():\n if v == l[-2]:\n return k", "def secfrequent(arr, n):\n d = {}\n for i in range(len(arr)):\n if arr[i] not in d:\n d[arr[i]] = 1\n else:\n d[arr[i]] += 1\n if len(d) >= 2:\n first = 0\n second = 0\n for i in d:\n if d[i] > first:\n second = first\n first = d[i]\n elif d[i] > second and d[i] != first:\n second = d[i]\n for word in d:\n if d[word] == second:\n return word\n else:\n return ''", "def secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n val = sorted(d.values(), reverse=True)\n second = val[1]\n for (key, value) in d.items():\n if value == second:\n return key", "from collections import Counter\n\ndef secfrequent(arr, n):\n count = Counter(arr)\n val = sorted(count.values(), reverse=True)\n max_val = val[1]\n for (i, j) in count.items():\n if j == max_val:\n return i", "from collections import Counter\n\ndef secfrequent(arr, n):\n d = Counter(arr)\n val = sorted(d.values(), reverse=True)\n second = val[1]\n for (k, v) in d.items():\n if v == second:\n return k", "from collections import Counter\n\ndef secfrequent(arr, n):\n d = dict()\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n a = []\n for (i, j) in d.items():\n a.append(j)\n if len(a) <= 1:\n return ''\n else:\n m = max(a)\n c = 0\n for i in range(len(a)):\n if a[i] < m:\n c = max(c, a[i])\n for (i, j) in d.items():\n if j == c:\n return i", "from collections import Counter\n\ndef secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n mx = max(list(d.values()))\n d1 = {}\n for (i, j) in d.items():\n if j == mx:\n continue\n else:\n d1[i] = j\n mx1 = max(list(d1.values()))\n for (i, j) in d1.items():\n if j == mx1:\n return i", "from collections import Counter\n\ndef secfrequent(arr, n):\n d = {}\n for i in arr:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n d = sorted(d.items(), key=lambda x: x[1])\n m = d[-2]\n return m[0]", "from collections import defaultdict\n\ndef secfrequent(arr, n):\n d = defaultdict(int)\n for i in arr:\n d[i] += 1\n max1 = -1\n max2 = -1\n for i in d:\n if max1 < d[i]:\n max2 = max1\n max1 = d[i]\n elif max2 < d[i] and d[i] != max1:\n max2 = d[i]\n for i in d:\n if d[i] == max2:\n return i\n return ''", "from collections import Counter\n\ndef secfrequent(arr, n):\n con = Counter(arr)\n res = sorted(con.values(), reverse=True)\n maxi = res[1]\n for (key, val) in con.items():\n if val == maxi:\n return key", "from collections import Counter\n\ndef secfrequent(arr, n):\n c = Counter(arr)\n return c.most_common(2)[1][0]", "from collections import Counter\n\ndef secfrequent(arr, n):\n d = Counter(arr)\n li = d.most_common(2)\n return li[1][0]"], "starter_code": "def secfrequent(arr, n):\n", "input_output": {"inputs": ["N = 6\narr[] = {aaa, bbb, ccc, bbb, aaa, aaa}", "N = 6\narr[] = {geek, for, geek, for, geek, aaa}"], "outputs": ["bbb", "for"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Hash"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/second-most-repeated-string-in-a-sequence0534/1", "Expected Auxiliary Space": "O(N*max(|S_{i}|).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*max(|S_{i}|).", "entry_point": "secfrequent", "task_id": "TACO_lite/119", "example": [[], []]} +{"requirement": "Given an integer n. Print first n elements of Recaman\u2019s sequence.\nIt is basically a function with domain and co-domain as natural numbers and 0. It is recursively defined as below:\nSpecifically, let a(n) denote the (n+1)-th term. (0 being already there).\nThe rule says:\na(0) = 0\na(n) = a(n-1) - n if a(n-1) - n > 0 and is not already present in the sequence\n = a(n-1) + n otherwise. \nExample 1:\nInput: n = 6\nOutput: 0 1 3 6 2 7\nExplaination: Follow the rule and this \nwill be the output.\nExample 2:\nInput: n = 3\nOutput: 0 1 3\nExplaination: If the rule is followed, \nit will produce this output.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function recamanSequence() which takes n as the input parameter and returns the sequence.\nExpected Time Complexity: O(n)\nExpected Auxiliary Space: O(n)\nConstraints:\n1 \u2264 n \u2264 100", "solutions": ["def __init__():\n self.res = []\n\ndef recamansequence(n):\n self.recaman(n)\n return self.res\n\ndef recaman(n):\n if n == 1:\n self.res.append(0)\n return 0\n self.recaman(n - 1)\n minus_val = self.res[-1] - (n - 1)\n if minus_val > 0 and minus_val not in self.res:\n self.res.append(minus_val)\n else:\n self.res.append(self.res[-1] + (n - 1))", "def recamansequence(n):\n ans = [0]\n self.helper(n, ans)\n return ans\n\ndef helper(n, ans):\n if n == 0:\n return\n self.helper(n - 1, ans)\n if ans[n - 1] - n > 0 and ans[n - 1] - n not in ans:\n ans.append(ans[n - 1] - n)\n else:\n ans.append(ans[n - 1] + n)", "def recamansequence(n):\n a = []\n if n == 0:\n return [0]\n return self.sol(n - 1, a)\n\ndef sol(n, a):\n if n == 0:\n a.append(n)\n return a\n self.sol(n - 1, a)\n if a[n - 1] - n > 0 and a[n - 1] - n not in a:\n a.append(a[n - 1] - n)\n else:\n a.append(a[n - 1] + n)\n return a", "def findSeq(i, n, seq):\n if i == n:\n return\n curr = seq[i - 1] - i\n if curr not in seq:\n if curr > 0:\n seq.append(curr)\n else:\n curr = seq[i - 1] + i\n seq.append(curr)\n else:\n curr = seq[i - 1] + i\n seq.append(curr)\n self.findSeq(i + 1, n, seq)\n\ndef recamansequence(n):\n seq = [0]\n self.findSeq(1, n, seq)\n return seq", "def recamansequence(n):\n if n == 1:\n return [0]\n s = []\n arr = [0] * n\n arr[0] = 0\n s.append(arr[0])\n for i in range(1, n):\n curr = arr[i - 1] - i\n for j in range(0, i):\n if arr[j] == curr or curr < 0:\n curr = arr[i - 1] + i\n break\n arr[i] = curr\n s.append(arr[i])\n return s", "def recamansequence(n):\n res = [0]\n i = 1\n while i < n:\n x = res[i - 1] - i\n if x > 0 and x not in res:\n res.append(x)\n else:\n res.append(res[i - 1] + i)\n i += 1\n return res", "def recamansequence(n):\n a = [0]\n self.rec(n, a)\n return a\n\ndef rec(n, ans):\n if n == 0:\n return\n self.rec(n - 1, ans)\n if ans[n - 1] - n > 0 and ans[n - 1] - n not in ans:\n ans.append(ans[n - 1] - n)\n else:\n ans.append(ans[n - 1] + n)", "def recur(n, li):\n if n == 0:\n return\n self.recur(n - 1, li)\n if li[n - 1] - n > 0 and li[n - 1] - n not in li:\n li.append(li[n - 1] - n)\n else:\n li.append(li[n - 1] + n)\n\ndef recamansequence(n):\n li = [0]\n self.recur(n, li)\n return li", "def recamansequence(n):\n ans = [0]\n for i in range(1, n):\n if ans[i - 1] - i > 0 and ans[i - 1] - i not in ans:\n ans.append(ans[i - 1] - i)\n else:\n ans.append(ans[i - 1] + i)\n return ans", "sequence = [0]\nsetti = set([0])\n\ndef recamansequence(n):\n while len(sequence) < n:\n i = len(sequence)\n next = sequence[-1] - i\n if next <= 0 or next in setti:\n next += i * 2\n sequence.append(next)\n setti.add(next)\n return sequence[:n]", "def recamansequence(n):\n ans = [0]\n s = set()\n s.add(0)\n for i in range(1, n):\n c = ans[-1] - i\n if c > 0 and c not in s:\n ans.append(c)\n s.add(c)\n else:\n t = ans[-1] + i\n ans.append(t)\n s.add(t)\n return ans", "def recamansequence(n):\n dp = [0] * n\n s = set()\n s.add(0)\n for i in range(1, n):\n val = dp[i - 1] - i\n if val not in s and val > 0:\n dp[i] = val\n else:\n dp[i] = dp[i - 1] + i\n s.add(dp[i])\n return dp", "def recamansequence(n):\n ds = [0 for i in range(n)]\n\n def help(ds, i):\n if i >= n:\n return\n val = ds[i - 1] - i\n if val > 0 and val not in ds:\n ds[i] = val\n else:\n ds[i] = val + 2 * i\n help(ds, i + 1)\n help(ds, 1)\n return ds", "def recamansequence(n):\n ds = []\n\n def helper(n, ds):\n if n == 1:\n ds.append(0)\n ds.append(n)\n return n\n value = helper(n - 1, ds)\n if value - n > 0 and value - n not in ds:\n ds.append(value - n)\n return value - n\n else:\n ds.append(value + n)\n return value + n\n helper(n, ds)\n return ds", "def recamansequence(n):\n l = [0]\n l1 = []\n for i in range(1, n):\n a = l[i - 1] - i\n if a > 0 and a not in l:\n l.append(a)\n else:\n a = l[i - 1] + i\n l.append(a)\n return l", "def recamansequence(n):\n ans = []\n ans.append(0)\n check = set()\n check.add(0)\n\n def rec(n, x):\n if n == x + 1:\n return\n if ans[n - 1] - n > 0 and ans[n - 1] - n not in check:\n check.add(ans[n - 1] - n)\n ans.append(ans[n - 1] - n)\n else:\n ans.append(ans[n - 1] + n)\n check.add(ans[n - 1] + n)\n rec(n + 1, x)\n rec(1, n)\n return ans", "def sol(i, n, li):\n if i == n:\n return\n if li[i - 1] - i > 0 and li[i - 1] - i not in li:\n li[i] = li[i - 1] - i\n else:\n li[i] = li[i - 1] + i\n sol(i + 1, n, li)\n\ndef recamansequence(n):\n li = [0] * n\n sol(1, n, li)\n return li", "def recamansequence(n):\n a = [0]\n count1 = 0\n if n == 1:\n return a\n a = [0] * n\n\n def rec(a, n, count1):\n if count1 >= n:\n return\n z = a[count1 - 1] - count1\n if z > 0 and z not in a:\n a[count1] = z\n else:\n x = a[count1 - 1] + count1\n a[count1] = x\n return rec(a, n, count1 + 1)\n rec(a, n, count1 + 1)\n return a", "def rec(n, res):\n if n == 0:\n res.append(0)\n return 0\n else:\n x = self.rec(n - 1, res)\n if x - n > 0:\n if x - n not in res:\n res.append(x - n)\n return x - n\n else:\n res.append(x + n)\n return x + n\n else:\n res.append(x + n)\n return x + n\n\ndef recamansequence(n):\n res = []\n self.rec(n, res)\n return res", "from collections import defaultdict\n\ndef recamansequence(n):\n ans = []\n visited = defaultdict(bool)\n for i in range(n):\n if i == 0:\n ans.append(0)\n visited[0] = True\n else:\n temp = ans[-1] - i\n if temp < 0 or visited[temp]:\n newtemp = ans[-1] + i\n ans.append(newtemp)\n visited[newtemp] = True\n else:\n ans.append(temp)\n visited[temp] = True\n return ans", "def recamansequence(n):\n if n <= 0:\n return\n s = set()\n s.add(0)\n arr = [0] * n\n for i in range(1, n):\n curr = arr[i - 1] - i\n if curr < 0 or curr in s:\n curr = arr[i - 1] + i\n s.add(curr)\n arr[i] = curr\n return arr", "def recamansequence(n):\n a = [0] * (n + 1)\n for i in range(0, n + 1):\n x = a[i - 1] - i\n if x > 0 and x not in a:\n a[i] = x\n else:\n a[i] = x + 2 * i\n return a", "def result(n, d, sol):\n if n == 0:\n sol[0] = 0\n return 0\n prev_iter = self.result(n - 1, d, sol)\n val1 = prev_iter - n\n if val1 > 0 and val1 not in d:\n d[prev_iter - n] = 1\n sol[n] = prev_iter - n\n return prev_iter - n\n d[prev_iter + n] = 1\n sol[n] = prev_iter + n\n return prev_iter + n\n\ndef recamansequence(n):\n d = {}\n sol = {}\n self.result(n - 1, d, sol)\n return [sol[i] for i in range(n)]", "def recamansequence(n):\n\n def rec(n, res):\n if n == 0:\n res.append(n)\n return\n rec(n - 1, res)\n temp = res[n - 1] - n\n if temp <= 0 or temp in res:\n temp = res[n - 1] + n\n res.append(temp)\n return\n res = []\n rec(n, res)\n return res", "def recursive(i, n, lst):\n if i == n:\n return lst\n if lst[i - 1] - i > 0 and lst[i - 1] - i not in lst:\n lst[i] = lst[i - 1] - i\n else:\n lst[i] = lst[i - 1] + i\n self.recursive(i + 1, n, lst)\n return lst\n\ndef recamansequence(n):\n lst = [0 for _ in range(n)]\n self.recursive(1, n, lst)\n return lst", "def recamansequence_h(n, i, ans):\n if i == n:\n return ans\n if ans[i - 1] - i > 0 and ans[i - 1] - i not in ans:\n ans[i] = ans[i - 1] - i\n else:\n ans[i] = ans[i - 1] + i\n return self.recamansequence_h(n, i + 1, ans)\n\ndef recamansequence(n):\n ans = [0] * n\n i = 1\n self.recamansequence_h(n, i, ans)\n return ans", "def sequence(n, arr):\n if n == 0:\n arr.append(0)\n return 0\n a = sequence(n - 1, arr)\n if a - n > 0 and a - n not in arr:\n arr.append(a - n)\n else:\n arr.append(a + n)\n return arr[-1]\n\ndef recamansequence(n):\n arr = []\n sequence(n, arr)\n return arr", "def recamansequence(n):\n if n == 0:\n return\n a = [0] * n\n for i in range(1, n):\n temp = a[i - 1] - i\n if temp <= 0:\n temp = a[i - 1] + i\n a[i] = temp\n continue\n if temp in a:\n temp = a[i - 1] + i\n a[i] = temp\n return a", "def helper(n, i, ans):\n if i == n:\n return ans\n if ans[i - 1] - i > 0 and ans[i - 1] - i not in ans:\n ans[i] = ans[i - 1] - i\n else:\n ans[i] = ans[i - 1] + i\n return self.helper(n, i + 1, ans)\n\ndef recamansequence(n):\n ans = [0] * n\n output = self.helper(n, 0, ans)\n return ans", "def sol(n, l, N):\n if l[n - 1] - n > 0 and l[n - 1] - n not in l:\n l.append(l[n - 1] - n)\n else:\n l.append(l[n - 1] + n)\n if n == N:\n return l\n return self.sol(n + 1, l, N)\n\ndef recamansequence(n):\n l = [0]\n return self.sol(1, l, n)", "def recamansequence(n):\n arr = []\n i = 1\n arr.append(0)\n self.solve(arr, n, i)\n return arr\n\ndef solve(arr, n, i):\n if i == n:\n return\n if arr[i - 1] - i > 0 and arr[i - 1] - i not in arr:\n x = arr[i - 1] - i\n arr.append(x)\n i = i + 1\n self.solve(arr, n, i)\n else:\n x = arr[i - 1] + i\n arr.append(x)\n i = i + 1\n self.solve(arr, n, i)", "def recamansequence(n):\n res = [0] * n\n if n > 0:\n for i in range(1, n):\n temp = res[i - 1] - i\n if temp > 0 and temp not in res:\n res[i] = temp\n else:\n temp = 0\n temp = res[i - 1] + i\n res[i] = temp\n return res", "def recamansequence(n):\n a = []\n\n def solve(n, a, i):\n if i == 0:\n a.append(i)\n elif i == 1:\n a.append(i)\n elif a[i - 1] - i > 0 and a[i - 1] - i not in a:\n a.append(a[i - 1] - i)\n else:\n a.append(a[i - 1] + i)\n if i == n:\n return\n solve(n, a, i + 1)\n solve(n, a, 0)\n return a", "from collections import defaultdict\n\ndef recamansequence(n):\n h = defaultdict(lambda : False)\n seq = [0] * n\n for i in range(1, n):\n x = seq[i - 1] - i\n if x > 0 and h[x] == False:\n seq[i] = x\n else:\n seq[i] = seq[i - 1] + i\n h[seq[i]] = True\n return seq", "def recamansequence(n):\n arr = [0]\n aa = set()\n for i in range(1, n):\n if arr[-1] - i > 0 and arr[-1] - i not in aa:\n aa.add(arr[-1] - i)\n arr.append(arr[-1] - i)\n else:\n aa.add(arr[-1] + i)\n arr.append(arr[-1] + i)\n return arr", "def recamansequence(n):\n li = [0] * n\n self.recman_sequence(n, li)\n return li\n\ndef recman_sequence(n, li):\n for i in range(1, n):\n if li[i - 1] - i > 0 and li[i - 1] - i not in li:\n li[i] = li[i - 1] - i\n else:\n li[i] = li[i - 1] + i\n return li", "def recamansequence(n):\n if n <= 0:\n return\n res = []\n res.append(0)\n sett = set()\n sett.add(0)\n if n == 1:\n return res\n pre = 0\n for i in range(1, n):\n curr = pre - i\n if curr < 0 or curr in sett:\n curr = pre + i\n sett.add(curr)\n res.append(curr)\n pre = curr\n return res", "def recamansequence(n):\n res = [0]\n d = {}\n\n def func(n, i=1):\n if i == n:\n return\n ans = res[i - 1] - i\n if ans in d or ans <= 0:\n ans = res[i - 1] + i\n d[ans] = 1\n res.append(ans)\n func(n, i + 1)\n func(n)\n return res", "from collections import defaultdict\n\ndef recamansequence(n):\n res = [0]\n d = defaultdict(int)\n for i in range(1, n):\n ans = res[i - 1] - i\n if ans in d or ans <= 0:\n ans = res[i - 1] + i\n d[ans] += 1\n res.append(ans)\n return res", "def recamansequence(n):\n if n == 0:\n return [0]\n li = [0]\n for i in range(1, n):\n l = li[i - 1]\n z = l - i\n if z < 0 or z in li:\n z = l + i\n li.append(z)\n return li", "def seq(curr, n, List):\n if curr == n + 1:\n return List\n if curr == 0:\n List.append(curr)\n return self.seq(curr + 1, n, List)\n x = List[-1]\n if x - curr > 0 and x - curr not in List:\n List.append(x - curr)\n else:\n List.append(x + curr)\n return self.seq(curr + 1, n, List)\n\ndef recamansequence(n):\n List = []\n self.seq(0, n, List)\n return List", "def recamansequence(n):\n d = {0: 0}\n res = [0]\n for i in range(1, n + 1):\n if res[-1] - i > 0 and res[-1] - i not in d:\n a1 = res[-1] - i\n else:\n a1 = res[-1] + i\n res.append(a1)\n d[a1] = 1\n return res"], "starter_code": "def recamansequence(n):\n", "input_output": {"inputs": ["n = 6", "n = 3"], "outputs": ["0 1 3 6 2 7", "0 1 3"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical", "Hash", "Recursion", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures", "Mathematics", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/recamans-sequence4856/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "recamansequence", "task_id": "TACO_lite/225", "example": [[], []]} +{"requirement": "Given a positive integer N, print count of set bits in it. \nExample 1:\nInput:\nN = 6\nOutput:\n2\nExplanation:\nBinary representation is '110' \nSo the count of the set bit is 2.\nExample 2:\nInput:\n8\nOutput:\n1\nExplanation:\nBinary representation is '1000' \nSo the count of the set bit is 1.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function setBits() which takes an Integer N and returns the count of number of set bits.\nExpected Time Complexity: O(LogN)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 N \u2264 10^{9}", "solutions": ["def setbits(N):\n dnum = N\n i = 0\n bnum = []\n while dnum != 0:\n rem = dnum % 2\n bnum.insert(i, rem)\n i = i + 1\n dnum = int(dnum / 2)\n x = 0\n for f in bnum:\n if f == 1:\n x = x + 1\n return x", "def setbits(N):\n c = 0\n while N:\n c += 1\n N = N & N - 1\n return c", "def setbits(n):\n count = 0\n while n > 0:\n if n % 2 == 1:\n count += 1\n n //= 2\n return count", "def setbits(N):\n if N <= 1:\n return 1\n a = 0\n while N > 1:\n x = N % 2\n N = N // 2\n if x == 1:\n a += 1\n return a + 1", "def setbits(N):\n n = bin(N)\n n = n[2:]\n return n.count('1')", "def setbits(N):\n return bin(N).count('1')", "def setbits(N):\n count = 0\n while N != 0:\n if N & 1 == 1:\n count += 1\n N >>= 1\n return count", "def setbits(N):\n n = bin(N).replace('0b', '')\n count = 0\n for i in n:\n if i == '1':\n count = count + 1\n return count", "def setbits(N):\n count = 0\n n = N\n while n > 0:\n n = n & n - 1\n count = count + 1\n return count", "def setbits(N):\n res = 0\n while N > 0:\n res += 1\n N = N & N - 1\n return res", "def setbits(N):\n x = bin(int(N))\n y = x[2:]\n lis = list(y)\n return lis.count('1')", "def setbits(N):\n A = bin(N)[2:]\n ans = 0\n for i in A:\n if i == '1':\n ans += 1\n return ans", "def setbits(N):\n n = bin(N)\n return str(n).count('1')", "def setbits(N):\n s = bin(N)\n d = s[2:]\n k = d.count('1')\n return k", "def setbits(N):\n d = bin(N)\n c = d.count('1')\n return c", "def setbits(N):\n cnt = 0\n for i in bin(N):\n if i == '1':\n cnt += 1\n return cnt", "def setbits(N):\n c = 0\n while N != 0:\n bit = N & 1\n if bit:\n c += 1\n N = N >> 1\n return c", "def setbits(N):\n t = bin(N)[2:]\n p = t.count('1')\n return p", "def setbits(N):\n b = bin(N)\n a = b.count('1')\n return a", "def setbits(N):\n binary = bin(N)[2:]\n return binary.count('1')", "def setbits(N):\n x = bin(N)\n z = str(x).count('1')\n return z", "def setbits(N):\n b = bin(N)\n b = b[2:]\n count = 0\n l = list(str(b))\n for i in l:\n if i == '1':\n count = count + 1\n return count", "def setbits(N):\n count = 0\n binary = str(bin(N))\n for i in binary:\n if i == str(1):\n count += 1\n return count", "def setbits(N):\n c = 0\n x = bin(N)\n for i in x:\n if i == '1':\n c += 1\n return c", "def setbits(N):\n x = bin(N)\n m = x.count('1')\n return m", "def setbits(N):\n ob = bin(N)\n b = ob[2:]\n s = str(b)\n return s.count('1')", "def setbits(N):\n a = bin(N)\n m = str(a).count('1')\n return m", "def setbits(n):\n res = 0\n while n:\n n &= n - 1\n res += 1\n return res", "def setbits(N):\n dectobinary = bin(N)[2:]\n return dectobinary.count('1')", "def setbits(N):\n b = str(format(N, 'b'))\n res = 0\n for i in range(len(b)):\n if b[i] == '1':\n res += 1\n return res", "def setbits(N):\n binary_n = str(bin(int(N)))[2:]\n cnt = 0\n for i in binary_n:\n if int(i) == 1:\n cnt += 1\n return cnt", "def setbits(N):\n cnt = 0\n for i in range(32):\n if N & 1 << i:\n cnt += 1\n return cnt", "def setbits(N):\n no_of_digits = 0\n while N:\n if N % 2:\n no_of_digits += 1\n N = N >> 1\n return no_of_digits", "def setbits(N):\n b = bin(N)[2:]\n return b.count('1')", "def setbits(N):\n cnt = 0\n while N > 0:\n if N & 1 == 1:\n cnt = cnt + 1\n N = N >> 1\n return cnt", "def setbits(N):\n b = '{:b}'.format(N)\n return b.count('1')", "def setbits(N):\n b = bin(N)[2:]\n c = 0\n for i in b:\n if i == '1':\n c += 1\n return c", "def setbits(N):\n N = str(bin(N))\n N = N[2:]\n return N.count('1')", "def setbits(n):\n l = []\n while n > 0:\n l.append(n % 2)\n n //= 2\n k = l.count(1)\n return k", "import math\n\ndef setbits(N):\n n = int(math.log2(N)) + 1\n count = 0\n for i in range(n):\n if 1 << i & N:\n count += 1\n return count", "import math\n\ndef setbits(N):\n count = 0\n S = str(bin(N))\n for i in S:\n if i == '1':\n count += 1\n return count", "def setbits(N):\n a = list(bin(N))\n count = 0\n for i in range(len(a)):\n if str(1) == a[i]:\n count += 1\n return count", "def setbits(N):\n s = bin(N)\n c = 0\n for i in range(2, len(s)):\n if s[i] == '1':\n c += 1\n return c", "import math\n\ndef setbits(N):\n no_bits = math.ceil(math.log2(N))\n set_bits = 0\n for i in range(no_bits + 1):\n if N & 1 << i:\n set_bits += 1\n return set_bits", "def setbits(N):\n (k, ans) = (N, 0)\n while k > 0:\n if k & 1 == 1:\n ans += 1\n k = k // 2\n return ans", "def setbits(N):\n ans = 0\n while N:\n N = N & N - 1\n ans += 1\n return ans", "def setbits(N):\n countSetBit = 0\n while N != 0:\n lastBit = N & 1\n if lastBit == 1:\n countSetBit += 1\n N = N >> 1\n return countSetBit", "def setbits(n):\n s = bin(n).replace('0b', ' ')\n s = str(s)\n c = 0\n for i in s:\n if i == '1':\n c += 1\n return c"], "starter_code": "def setbits(N):\n", "input_output": {"inputs": ["N = 6", "8"], "outputs": ["2", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/set-bits0143/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(LogN)", "entry_point": "setbits", "task_id": "TACO_lite/314", "example": [[[6], [8]], ["2", "1"]]} +{"requirement": "Find the number of factors for a given integer N.\n \nExample 1:\nInput:\nN = 5\nOutput:\n2\nExplanation:\n5 has 2 factors 1 and 5\nExample 2:\nInput:\nN = 25\nOutput:\n3\nExplanation:\n25 has 3 factors 1, 5, 25\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function countFactors() which takes an integer N as input parameters and returns an integer, total number factor of N.\n \nExpected Time Complexity: O(sqrt(N))\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= N <= 100000", "solutions": ["def countfactors(N):\n count = 0\n for i in range(1, int(N ** 0.5) + 1):\n if N % i == 0:\n count += 1\n if i != N // i:\n count += 1\n return count", "def countfactors(N):\n i = 1\n fact = 0\n while i * i <= N:\n if N % i == 0:\n fact += 1\n if N / i != i:\n fact += 1\n i = i + 1\n return fact", "import math\n\ndef countfactors(N):\n count = 0\n res = set()\n for i in range(1, int(math.sqrt(N)) + 1):\n if N % i == 0:\n res.add(i)\n res.add(N / i)\n return len(res)", "def countfactors(N):\n factCount = 0\n for i in range(1, N // 2 + 1):\n if N % i == 0:\n factCount += 1\n return factCount + 1", "from math import sqrt\n\ndef countfactors(N):\n cnt = 0\n for i in range(1, int(sqrt(N) + 1)):\n if N % i == 0:\n if N / i == i:\n cnt += 1\n else:\n cnt += 2\n return cnt", "def countfactors(N):\n if N == 2:\n return 2\n if N == 1:\n return 1\n c = 1\n if N % 2 == 0:\n c = 3\n for i in range(3, N // 2):\n if N % i == 0:\n c += 1\n return c + 1", "import math\n\ndef countfactors(N):\n count = 0\n i = 1\n while i <= math.sqrt(N):\n if N % i == 0:\n if i == N / i:\n count = count + 1\n else:\n count = count + 2\n i = i + 1\n return count", "def countfactors(N):\n if N == 1:\n return 1\n res = 2\n for i in range(2, int(N ** 0.5) + 1):\n if N % i == 0:\n if i * i == N:\n res = res + 1\n else:\n res = res + 2\n return res", "def countfactors(N):\n c = 0\n s = N\n for i in range(1, int(s ** 0.5) + 1):\n if s % i == 0:\n c += 1\n if s // i != i:\n c += 1\n return c", "def countfactors(N):\n lis = []\n for i in range(1, int(N ** 0.5 + 1)):\n if N % i == 0:\n if i == N // i:\n lis.append(i)\n else:\n lis.append(i)\n lis.append(N // i)\n lis.sort()\n return len(lis)", "import math\n\ndef countfactors(N):\n count = 0\n for i in range(1, int(math.sqrt(N)) + 1):\n if N % i == 0:\n count += 1\n if N / i != i:\n count += 1\n return count", "import math\n\ndef countfactors(n):\n i = 1\n l = []\n while i <= math.sqrt(n):\n if n % i == 0:\n if n / i == i:\n l.append(i)\n else:\n l.append(int(n / i))\n l.append(i)\n i += 1\n return len(l)", "def countfactors(N):\n ans = 2\n i = 2\n while i * i <= N:\n if N % i == 0:\n if N / i == i:\n ans += 1\n else:\n ans += 2\n i += 1\n return ans", "import math\n\ndef countfactors(N):\n factors = []\n for i in range(1, int(math.sqrt(N)) + 1, 1):\n if N % i == 0:\n if N / i == i:\n factors.append(i)\n else:\n factors.append(i)\n factors.append(int(N / i))\n return len(factors)", "from math import *\n\ndef countfactors(N):\n c = 0\n for i in range(1, int(sqrt(N)) + 1):\n if N % i == 0 and i ** 2 != N:\n c += 2\n elif i ** 2 == N:\n c += 1\n return c", "import math\n\ndef countfactors(N):\n s = 0\n a = []\n for i in range(1, int(math.sqrt(N)) + 1):\n if N % i == 0:\n if N / i == i:\n s += 1\n else:\n s += 2\n return s", "def countfactors(N):\n count = 0\n i = 1\n while i * i <= N:\n if N % i == 0:\n fact = N / i\n if fact == i:\n count += 1\n else:\n count += 2\n i += 1\n return count", "def countfactors(N):\n count = 0\n for i in range(1, int(pow(N, 0.5)) + 1):\n if N % i == 0 and i ** 2 != N:\n count += 2\n elif i ** 2 == N:\n count += 1\n return count", "import math\n\ndef countfactors(n):\n i = 1\n co = 0\n while i <= int(math.sqrt(n)):\n if n % i == 0:\n if n // i == i:\n co += 1\n else:\n co += 2\n i += 1\n return co", "def countfactors(N):\n i = 1\n count = 0\n while i * i <= N:\n if i * i == N:\n count += 1\n elif N % i == 0:\n count += 2\n i += 1\n return count", "def countfactors(N):\n import math\n ans = 0\n sqrt = round(math.sqrt(N))\n for i in range(1, sqrt + 1):\n if N % i == 0:\n if N / i == i:\n ans += 1\n else:\n ans += 2\n return ans", "import math\n\ndef countfactors(n):\n count = 0\n s = int(math.sqrt(n)) + 1\n for i in range(2, s):\n if n % i == 0:\n if n / i == i:\n count += 1\n else:\n count += 2\n return int(count) + 2", "from math import *\n\ndef countfactors(n):\n ans = []\n for i in range(1, floor(sqrt(n)) + 1):\n if n % i == 0:\n ans.append(i)\n if n // i != i:\n ans.append(n // i)\n return len(ans)", "def countfactors(N):\n i = 1\n count = 0\n while i <= int(N ** 0.5):\n if N % i == 0:\n if N / i == i:\n count += 1\n else:\n count += 2\n i += 1\n return count", "def countfactors(n):\n i = 1\n count = 0\n while i * i <= n:\n if n % i == 0:\n count = count + 1\n if n // i != i:\n count = count + 1\n i = i + 1\n return count", "def countfactors(N):\n import math\n ans = 0\n ans_ = 0\n if N == int(math.sqrt(N)) * int(math.sqrt(N)):\n y = int(math.sqrt(N))\n else:\n y = int(math.sqrt(N)) + 1\n for i in range(1, y):\n if N % i == 0:\n ans += 1\n if N == int(math.sqrt(N)) * int(math.sqrt(N)):\n ans_ = 1\n return 2 * ans + ans_", "def countfactors(N):\n ans = []\n for i in range(1, N // 2 + 1):\n if N % i == 0:\n ans.append(i)\n return len(ans) + 1", "import math as m\n\ndef countfactors(N):\n DiViSoRs = 0\n sqrtN = int(m.sqrt(N)) + 1\n for factor in range(1, sqrtN):\n if N % factor == 0:\n if N / factor == factor:\n DiViSoRs += 1\n else:\n DiViSoRs += 2\n return DiViSoRs", "from math import sqrt\n\ndef countfactors(N):\n ans = []\n for i in range(1, int(sqrt(N)) + 1):\n if N % i == 0:\n ans.append(i)\n if i != N // i:\n ans.append(N // i)\n return len(ans)", "def countfactors(N):\n start = 1\n count = 0\n while start * start < N:\n if N % start == 0:\n count += 1\n start += 1\n count = 2 * count\n if start * start == N:\n count += 1\n return count", "def countfactors(N):\n i = 1\n count = 0\n while i * i <= N:\n if N % i == 0:\n count += 1\n if N // i != i and N % (N // i) == 0:\n count += 1\n i += 1\n return count", "def countfactors(N):\n import math\n i = 1\n c = 0\n sr = math.floor(math.sqrt(N))\n while i <= sr:\n if N % i == 0:\n if i * i == N:\n c += 1\n else:\n c += 2\n i += 1\n return c", "from math import *\n\ndef countfactors(num):\n start = 1\n end = int(sqrt(num))\n ans = 0\n for i in range(start, end + 1):\n if num % i == 0:\n ans += 1\n return ans * 2 - 1 if end * end == num else ans * 2", "def countfactors(N):\n co = 0\n for i in range(1, int(N / 2) + 1):\n if N % i == 0:\n co += 1\n return co + 1"], "starter_code": "def countfactors (N):\n", "input_output": {"inputs": ["N = 5", "N = 25"], "outputs": ["2", "3"]}, "difficulty": "EASY", "raw_tags": ["Misc"], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/number-of-factors1435/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(sqrt(N))", "entry_point": "countfactors", "task_id": "TACO_lite/313", "example": [[[5], [25]], ["2", "3"]]} +{"requirement": "## Debugging sayHello function\n\nThe starship Enterprise has run into some problem when creating a program to greet everyone as they come aboard. It is your job to fix the code and get the program working again!\n\nExample output: \n```\nHello, Mr. Spock\n```", "solutions": ["def say_hello(name):\n return f'Hello, {name}'", "def say_hello(name):\n return 'Hello, ' + name", "def say_hello(name):\n return 'Hello, {0}'.format(name)", "say_hello = 'Hello, '.__add__", "def say_hello(name):\n return 'Hello, %s' % name", "def say_hello(input):\n return 'Hello, ' + input", "say_hello = lambda n: 'Hello, {}'.format(n)", "def say_hello(n):\n return 'Hello, ' + n", "def say_hello(name):\n if name:\n return 'Hello, ' + name", "def say_hello(name):\n return 'Hello, ' + name\n pass", "def say_hello(name):\n if name == '':\n return 'Hello, World'\n else:\n return 'Hello, {}'.format(name)", "def say_hello(name):\n return 'Hello, ' + name\nsay_hello('Mr. Spock')\nsay_hello('Captain Kirk')\nsay_hello('Liutenant Uhura')\nsay_hello('Dr. McCoy')\nsay_hello('Mr. Scott')", "say_hello = lambda name: 'Hello, %s' % name", "say_hello = lambda n: 'Hello, %s' % n", "say_hello = lambda k: f'Hello, {k}'", "import unittest\n\ndef say_hello(name):\n return 'Hello, {}'.format(name)\n\ndef test_say_hello():\n self.assertEqual(say_hello('Mr. Spock'), 'Hello, Mr. Spock')", "def say_hello(name):\n a = 'Hello, '\n b = name\n return a + b", "def say_hello(name):\n hello = 'Hello' + ', ' + name\n return hello", "def say_hello(name):\n return 'Hello, ' + name\nsay_hello('dff')", "def say_hello(name: str) -> str:\n result: str = 'Hello, ' + name\n return result", "def say_hello(name):\n return 'Hello' + ', ' + name\nsay_hello('Mr.Spock')", "def say_hello(name):\n out = 'Hello, ' + name\n return out", "def say_hello(name):\n return 'Hello, {nam}'.format(nam=name)", "def say_hello(name='World'):\n name = str(name)\n greet = 'Hello, ' + name\n return greet", "def say_hello(name):\n name = ('Hello,', name)\n name = ' '.join(name)\n return name", "def say_hello(n=''):\n return f'Hello, {n}'", "def say_hello(name):\n p = 'Hello, {}'.format(name)\n return p", "def say_hello(name: any) -> str:\n return 'Hello, ' + str(name)", "def say_hello(name):\n answer = 'Hello, ' + name\n return answer", "def say_hello(name):\n sen = 'Hello, ' + name\n return sen", "def say_hello(name):\n return 'Hello, {n}'.format(n=name)", "def say_hello(name):\n string = 'Hello' + ', ' + name\n return string", "def say_hello(name):\n say = 'Hello, ' + name\n return say", "def say_hello(name):\n ans = 'Hello, ' + name\n return ans", "def say_hello(name):\n salu = name\n return 'Hello, {}'.format(salu)", "def say_hello(name):\n return 'Hello, ' + name\nsay_hello('Marissa')", "def say_hello(name):\n return ' ,olleH'[::-1] + name", "def say_hello(name):\n sh = 'Hello, ' + name\n return sh", "def say_hello(name):\n hi = 'Hello' + ',' + ' ' + name\n return hi", "def say_hello(name):\n hello_name = 'Hello, ' + name\n return hello_name", "def say_hello(name):\n return f'Hello, {name}'\nsay_hello('Mr. Robot')", "def say_hello(name):\n asd = ('Hello,', name)\n asf = ' '.join(asd)\n return asf", "def say_hello(name):\n x = 'Hello, ' + name\n return x", "def say_hello(name):\n return 'Hello, ' + name\nlist = ['Mr. Steve', 'Captain Kata', 'Eren Yeager', 'Dr. McCoi', 'Mrs. Scott']\nsay_hello(list[0])\nsay_hello(list[1])\nsay_hello(list[2])\nsay_hello(list[3])\nsay_hello(list[4])", "def say_hello(name):\n greeting = 'Hello' + ', ' + name\n return greeting", "def say_hello(name):\n var = 'Hello, {}'.format(name)\n return var", "def say_hello(name):\n output = 'Hello, ' + name\n return output", "def say_hello(name):\n return 'Hello, ' + name\nsay_hello('MacMillan')"], "starter_code": "def say_hello(name):\n", "input_output": {"fn_name": "say_hello", "inputs": [["Mr. Spock"], ["Captain Kirk"], ["Liutenant Uhura"], ["Dr. McCoy"], ["Mr. Scott"]], "outputs": [["Hello, Mr. Spock"], ["Hello, Captain Kirk"], ["Hello, Liutenant Uhura"], ["Hello, Dr. McCoy"], ["Hello, Mr. Scott"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5625618b1fe21ab49f00001f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "say_hello", "task_id": "TACO_lite/267", "example": [[["Mr. Spock"]], ["Hello, Mr. Spock"]]} +{"requirement": "Given a number N. Find the last two digits of the Nth fibonacci number.\nNote: If the last two digits are 02, return 2.\nExample 1:\nInput:\nN = 13\nOutput:\n33\nExplanation:\nThe 13th Fibonacci number is 233.\nSo last two digits are 3 and 3.\nExample 2:\nInput:\nN = 255\nOutput:\n70\nExplanation:\nThe 255th fibonacci number is 875715953430-\n18854458033386304178158174356588264390370.\nThus, last two digits are 7 and 0.\nYour Task:\nYou don't need to read input or print anything.Your task is to complete the function fibonacciDigits() which takes a number N as input parameter and returns the last two digits of the Nth fibonacci number.\nExpected Time Complexity:O(K)\nExpected Auxillary Space:O(K)\nK is of the order 10^{2}.\nConstraints:\n1<=N<=10^{18}", "solutions": ["def fibonaccidigits(N):\n return int(str(self.gfn(N % 300))[-2:])\n\ndef gfn(n):\n if n < 1:\n return 0\n n1 = 0\n n2 = 1\n while n > 1:\n n2 += n1\n n1 = n2 - n1\n n -= 1\n return n2", "def fibonaccidigits(N):\n n1 = 0\n n2 = 1\n k = 1\n while N > 300:\n N = N % 300\n while k <= N:\n k += 1\n (n1, n2) = ((n1 + n2) % 100, n1 % 100)\n return int(n1 % 100)", "def fibonaccidigits(N):\n (a, b) = (0, 1)\n k = 1\n while N > 300:\n N = N % 300\n while k <= N:\n k += 1\n (a, b) = ((a + b) % 100, a % 100)\n return int(a % 100)", "def fibonaccidigits(N):\n (a, b, c, N) = (1, 1, 2, N % 300)\n if N == 0:\n return 0\n if N == 1 or N == 2:\n return 1\n while c < N:\n (a, b) = (b, (a + b) % 100)\n c += 1\n if c == N:\n return b", "def fibonaccidigits(N):\n fib = [0] * 300\n fib[0] = 0\n fib[1] = 1\n fib[2] = 1\n for i in range(3, len(fib)):\n fib[i] = (fib[i - 2] + fib[i - 1]) % 100\n return fib[N % 300]", "def fibonaccidigits(N):\n fibonacci = []\n fibonacci.append(0)\n fibonacci.append(1)\n for i in range(2, 300):\n fibonacci.append((fibonacci[i - 1] + fibonacci[i - 2]) % 100)\n return fibonacci[N % 300]", "def fibonaccidigits(n):\n n = n % 300\n if n in {0, 1}:\n return n\n a = 0\n b = 1\n c = 0\n for i in range(2, n + 1):\n c = (a + b) % 100\n a = b % 100\n b = c % 100\n return c % 300", "def fibonaccidigits(N):\n x = 1\n y = 1\n c = 2\n ans = [0, 1, 1]\n while c < 301:\n (x, y) = (y, y + x)\n c += 1\n ans.append(y % 100)\n return ans[N % 300]", "def fibonaccidigits(N):\n m = N % 300\n a = 0\n b = 1\n if m == 0 or m == 1:\n return m\n for i in range(1, m):\n sum = (a + b) % 100\n (a, b) = (b % 100, sum)\n return sum % 100", "def fibonaccidigits(N):\n dp = [i for i in range(300)]\n dp[0] = 0\n dp[1] = 1\n dp[2] = 1\n for i in range(3, 300):\n dp[i] = (dp[i - 1] + dp[i - 2]) % 100\n return dp[int(N % 300)]", "def fast_fibonacci(ans, n):\n if n == 0:\n ans[0] = 0\n ans[1] = 1\n return\n self.fast_fibonacci(ans, n // 2)\n a = ans[0]\n b = ans[1]\n c = 2 * b - a\n c = a * c\n d = a * a + b * b\n if n % 2 == 0:\n ans[0] = c\n ans[1] = d\n else:\n ans[0] = d\n ans[1] = c + d\n\ndef fibonaccidigits(N):\n ans = [0, 0]\n self.fast_fibonacci(ans, N % 300)\n return ans[0] % 100", "def fibonaccidigits(N):\n a = 1\n b = 1\n c = 0\n N = N % 300\n if N == 1:\n return a\n if N == 2:\n return b\n for i in range(3, N + 1):\n c = int(a + b) % 100\n a = b % 100\n b = c % 100\n return c", "def fibonaccidigits(N):\n fib = [0] * 300\n fib[0] = 0\n fib[1] = 1\n for i in range(2, min(299, N) + 1):\n fib[i] = (fib[i - 1] + fib[i - 2]) % 100\n return fib[N % 300]", "def fibonaccidigits(n):\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n a = 0\n b = 1\n for i in range(n % 900):\n c = a + b\n a = b\n b = c\n if a < 9:\n return a\n else:\n return a % 100", "def fibonaccidigits(N):\n arr = [None] * 300\n arr[0] = 0\n arr[1] = 1\n arr[2] = 1\n for i in range(3, 300):\n arr[i] = (arr[i - 2] + arr[i - 1]) % 100\n return arr[N % 300]", "def fibonaccidigits(N):\n if N == 0 or N == 1:\n return N\n f = []\n f.append(0)\n f.append(1)\n for i in range(2, 300):\n f.append((f[i - 1] + f[i - 2]) % 100)\n return f[N % 300]", "import math\n\ndef fibonaccidigits(N):\n fib = [0] * 300\n fib[0] = 0\n fib[1] = 1\n fib[2] = 1\n for i in range(3, 300):\n fib[i] = (fib[i - 1] + fib[i - 2]) % 100\n return fib[abs(N % 300)]", "def fibonaccidigits(N):\n l = list()\n l.append(0)\n l.append(1)\n l.append(1)\n s1 = 1\n s2 = 1\n s = 0\n n = 1\n while n < 300:\n s = s1 + s2\n l.append(s % 100)\n s2 = s1\n s1 = s\n n += 1\n return l[N % 300]", "def fibonaccidigits(N):\n N = N % 300\n ans = 0\n if N == 1:\n ans = 1\n elif N == 2:\n ans = 1\n a = 1\n b = 1\n for i in range(3, N + 1):\n ans = a + b\n a = b\n b = ans\n return ans % 100", "def fibonaccidigits(n):\n f = []\n f.append(0)\n f.append(1)\n for i in range(2, 300):\n f.append((f[i - 1] + f[i - 2]) % 100)\n return f[n % 300]", "def fib(n):\n if n == 0:\n return 0\n a = b = 1\n for _ in range(n - 2):\n (a, b) = (b, a + b)\n return b\n\ndef fibonaccidigits(N):\n val = self.fib(N % 300)\n return int(str(val)[-2:])", "def fibonaccidigits(N):\n rem = N % 300\n a = 1\n b = 1\n if rem == 0:\n return 0\n elif rem <= 2:\n return 1\n res = 0\n temp = 0\n for i in range(3, rem + 1):\n res = a + b\n temp = res % 100\n a = b\n b = res\n return temp", "def fibonaccidigits(N):\n f = [0] * 300\n f[1] = f[2] = 1\n c = 3\n while c < 300:\n f[c] = (f[c - 1] + f[c - 2]) % 100\n c += 1\n return f[N % 300]", "def fibonaccidigits(N):\n fab = []\n tmp0 = 0\n tmp1 = 1\n tmp = 0\n mod_N = N % 300\n for i in range(1, mod_N + 1):\n tmp = tmp0 + tmp1\n fab.append(tmp)\n tmp0 = tmp1\n tmp1 = tmp\n dig = str(tmp0)\n if len(dig) < 2:\n return int(dig[0])\n if int(dig[-2]) == 0:\n return int(dig[-1])\n else:\n return int(dig[-2:])", "def fibonaccidigits(N):\n n = N % 300\n if n == 0:\n return 0\n elif n == 1:\n return 1\n out = self.matrixmul(n - 1)\n return out[0][0] % 100\n\ndef matrixmul(N):\n temp = [[0, 0], [0, 0]]\n if N == 1:\n return [[1, 1], [1, 0]]\n temp = self.matrixmul(N // 2)\n lst = []\n lst.append(temp[0][0] * temp[0][0] + temp[0][1] * temp[1][0])\n lst.append(temp[0][0] * temp[0][1] + temp[0][1] * temp[1][1])\n lst.append(temp[1][0] * temp[0][0] + temp[1][1] * temp[1][0])\n lst.append(temp[1][0] * temp[0][1] + temp[1][1] * temp[1][1])\n temp[0][0] = lst[0]\n temp[0][1] = lst[1]\n temp[1][0] = lst[2]\n temp[1][1] = lst[3]\n if N % 2 == 0:\n return temp\n else:\n lst = []\n lst.append(temp[0][0] + temp[0][1])\n lst.append(temp[0][0])\n lst.append(temp[1][0] + temp[1][1])\n lst.append(temp[1][0])\n temp[0][0] = lst[0]\n temp[0][1] = lst[1]\n temp[1][0] = lst[2]\n temp[1][1] = lst[3]\n return temp", "def fibonaccidigits(N):\n l = [0, 1]\n for i in range(1, 300):\n l.append(l[i - 1] + l[i])\n if N % 300 == N:\n return l[N] % 100\n else:\n return l[N % 300] % 100", "def fibonaccidigits(N):\n if N > 300:\n N = N % 300\n if N == 0:\n return 0\n elif N == 1:\n return 1\n else:\n fib = [0] * (N + 1)\n fib[0] = 0\n fib[1] = 1\n for i in range(2, N + 1):\n fib[i] = fib[i - 2] + fib[i - 1]\n m = fib[N]\n return m % 100\n else:\n fib = [0] * (N + 1)\n fib[0] = 0\n fib[1] = 1\n for i in range(2, N + 1):\n fib[i] = fib[i - 2] + fib[i - 1]\n m = fib[N]\n return m % 100", "def fibonaccidigits(N):\n return Solution.vl_all[N % 300]"], "starter_code": "def fibonaccidigits(N):\n", "input_output": {"inputs": ["N = 13", "N = 255"], "outputs": ["33", "70"]}, "difficulty": "EASY", "raw_tags": ["Fibonacci", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/last-two-digit-fibonacci3353/1", "Expected Auxiliary Space": "O(K)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(K)", "entry_point": "fibonaccidigits", "task_id": "TACO_lite/311", "example": [[[13], [255]], ["33", "70"]]} +{"requirement": "Given a number N. The task is to check whether it is sparse or not. A number is said to be a sparse number if no two or more consecutive bits are set in the binary representation.\nExample 1:\nInput: N = 2\nOutput: 1\nExplanation: Binary Representation of 2 is 10, \nwhich is not having consecutive set bits. \nSo, it is sparse number.\nExample 2:\nInput: N = 3\nOutput: 0\nExplanation: Binary Representation of 3 is 11, \nwhich is having consecutive set bits in it. \nSo, it is not a sparse number.\nYour Task: The task is to complete the function checkSparse() that takes n as a parameter and returns 1 if the number is sparse else returns 0.\nExpected Time Complexity: O(1).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= N <= 10^{6}", "solutions": ["def issparse(n):\n k = bin(n)[2:]\n a = k.split('0')\n for i in a:\n if len(i) > 1:\n return 0\n return 1", "def issparse(n):\n binary = []\n while n > 0:\n x = n % 2\n binary.append(x)\n n = n // 2\n for i in range(0, len(binary) - 1):\n if binary[i] == binary[i + 1] and binary[i] == 1:\n return 0\n return 1", "def issparse(n):\n while n > 0:\n x = n\n n = n >> 1\n if x & 1 == 1 and n & 1 == 1:\n return 0\n return 1", "def bina(n):\n b = ''\n while n != 1:\n b = str(n % 2) + b\n n = n // 2\n return '1' + b\n\ndef issparse(n):\n n = Solution.bina(n)\n n = str(n)\n if '11' in n:\n return 0\n return 1", "def issparse(n):\n numero = bin(n)[2:]\n if len(numero) == 1:\n return True\n ultimo = numero[0]\n for l in numero[1:]:\n if l == '1' and ultimo == '1':\n return False\n else:\n ultimo = l\n return True", "def issparse(n):\n count = 0\n while n != 0:\n if n & 1 == 1:\n count += 1\n if count == 2:\n return 0\n else:\n count = 0\n n = n // 2\n return 1", "def issparse(n):\n a = bin(n)[2:]\n b = a.split('0')\n for i in b:\n if len(i) >= 2:\n return False\n return True", "def issparse(n):\n if n >> 1 & n == 0:\n return True\n return False", "def issparse(n):\n binn = bin(n)[2:]\n if '11' in binn:\n return 0\n return 1", "def issparse(n: int) -> bool:\n binary_str = bin(n)[2:]\n for i in range(len(binary_str) - 1):\n if binary_str[i] == '1' and binary_str[i + 1] == '1':\n return False\n return True", "def issparse(n):\n c = 0\n flag = -1\n while n != 0:\n if n & 1 == 1:\n if flag == 1:\n return 0\n flag = 1\n else:\n flag = 0\n n = n >> 1\n return 1", "def issparse(n):\n while n:\n if n & 3 == 3:\n return False\n n >>= 1\n return True", "def issparse(n):\n binary = bin(n)[2:]\n for i in range(len(binary) - 1):\n if binary[i] == '1' and binary[i + 1] == '1':\n return 0\n return 1", "def issparse(n):\n binary = bin(n)[2:]\n if '11' in binary:\n return False\n else:\n return True", "def issparse(n):\n binary = format(n, 'b')\n for i in range(0, len(binary) - 1):\n if binary[i] == binary[i + 1] and binary[i] == '1':\n return 0\n return 1", "def issparse(n):\n elem = str(bin(n))[2:]\n for i in range(len(elem) - 1):\n if elem[i] == '1':\n if elem[i] == elem[i + 1]:\n return False\n return True", "def issparse(n):\n last = False\n for (i, ch) in enumerate(bin(n)):\n if i > 0 and last and (ch == '1'):\n return 0\n last = True if ch == '1' else False\n return 1", "def issparse(n):\n prev = 0\n while n > 0:\n if n % 2 and prev:\n return 0\n prev = n % 2\n n = n // 2\n return 1", "def issparse(n):\n a = bin(n)[2:]\n string = str(a)\n for i in range(0, len(string) - 1):\n if string[i] == '1' and string[i + 1] == '1':\n return 0\n return 1", "def issparse(n):\n prev_bit = '0'\n bits = bin(n)[2:]\n for bit in bits:\n if bit == '1' and prev_bit == '1':\n return 0\n prev_bit = bit\n return 1", "def issparse(n):\n return n & n >> 1 == 0", "def issparse(num):\n n = bin(num)\n n = list(n)\n n = n[2:]\n for i in range(len(n) - 1):\n if n[i] == n[i + 1] == '1':\n return 0\n return 1", "def issparse(n):\n len = 0\n if n == 0:\n return True\n while n > 0:\n if n & 1:\n len += 1\n if len > 1:\n return False\n else:\n len = 0\n n >>= 1\n return True", "def issparse(n):\n b = bin(n)\n count0 = 0\n count1 = 1\n for i in range(len(b) - 1):\n if b[i] == '1':\n if b[i + 1] == '1':\n return False\n return True", "def issparse(n):\n if n == 1:\n return True\n global prev\n while n > 0:\n prev = n & 1\n n = n >> 1\n curr = n & 1\n if prev == curr and prev == 1:\n return False\n prev = curr\n return True", "def issparse(n):\n t = bin(n)[2:]\n k = t.count('11')\n if k == 0:\n return 1\n else:\n return 0", "def issparse(n):\n p = 0\n while n > 0:\n if n & 1 == 1 and p == 1:\n return 0\n else:\n p = n & 1\n n = n >> 1\n return 1", "def issparse(n):\n flag = False\n while n:\n if n & 1:\n if flag:\n return False\n flag = True\n else:\n flag = False\n n >>= 1\n return True", "def issparse(n):\n if n & n >> 1 != 0:\n return 0\n else:\n return 1", "def issparse(n):\n count = 0\n while n > 0 and count < 2:\n if n & 1 == 1:\n count = count + 1\n else:\n count = 0\n n = n >> 1\n if count >= 2:\n return False\n return True", "def issparse(n):\n r1 = n % 2\n n = n // 2\n while n > 0:\n r2 = n % 2\n if r1 and r2:\n return 0\n r1 = r2\n n = n // 2\n return 1", "def issparse(n):\n bi = bin(n)[2:]\n p = bi.split('0')\n for i in p:\n if len(i) >= 2:\n return False\n return True", "def issparse(n):\n b = str(bin(n))[2:]\n for i in range(len(b)):\n if i == len(b) - 1:\n return 1\n if b[i] == '1':\n if b[i + 1] == '1':\n return 0\n return 1", "def issparse(N):\n Temp = bin(N)[2:]\n ctr = 0\n Ans = 0\n for i in Temp:\n if i == '1':\n ctr += 1\n else:\n Ans = max(Ans, ctr)\n ctr = 0\n Ans = max(ctr, Ans)\n if Ans <= 1:\n return 1\n else:\n return 0", "def issparse(n):\n s = str(bin(n))\n if '11' in s:\n return 0\n else:\n return 1", "def issparse(n):\n x = bin(n)\n if '11' in x:\n return 0\n else:\n return 1", "def issparse(n):\n bits = bin(n)\n if n & n << 1:\n return 0\n else:\n return 1", "def issparse(n):\n binary = bin(n)[2:]\n for i in range(len(binary) - 1):\n if binary[i:i + 2] == '11':\n return False\n return True", "def issparse(n):\n c = str(bin(n)[2:])\n if '11' in c:\n return 0\n return 1", "def issparse(n):\n n = bin(n)[2:]\n arr = list(n)\n if len(arr) < 2:\n return 1\n elif len(arr) == 2:\n if arr[0] != arr[1]:\n return 1\n else:\n return 0\n for i in range(1, len(arr)):\n if arr[i] == '1' and arr[i - 1] == '1':\n return 0\n return 1", "def issparse(n):\n p = bin(n).replace('0b', '')\n for i in range(len(p) - 1):\n if p[i] == p[i + 1] and p[i] == '1':\n return 0\n return 1"], "starter_code": "def issparse(n):\n", "input_output": {"inputs": ["N = 2", "N = 3"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/number-is-sparse-or-not-1587115620/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1).", "entry_point": "issparse", "task_id": "TACO_lite/317", "example": [[[2], [3]], ["1", "0"]]} +{"requirement": "You will be given an array of non-negative integers and positive integer bin width. \n\nYour task is to create the Histogram method that will return histogram data corresponding to the input array. The histogram data is an array that stores under index i the count of numbers that belong to bin i. The first bin always starts with zero. \n\nOn empty input you should return empty output.\n\nExamples:\n\nFor input data [1, 1, 0, 1, 3, 2, 6] and binWidth=1 the result will be [1, 3, 1, 1, 0, 0, 1] as the data contains single element \"0\", 3 elements \"1\" etc.\nFor the same data and binWidth=2 the result will be [4, 2, 0, 1]\nFor input data [7] and binWidth=1 the result will be [0, 0, 0, 0, 0, 0, 0, 1]", "solutions": ["def histogram(lst, w):\n lst = [n // w for n in lst]\n m = max(lst, default=-1) + 1\n return [lst.count(n) for n in range(m)]", "def histogram(v, w):\n return [sum((j in range(i, w + i) for j in v)) for i in range(0, max(v) + 1, w)] if v else []", "def histogram(values, bin_width):\n return [sum([values.count(i + j) for i in range(bin_width)]) for j in range(max(values) + 1) if j % bin_width == 0] if values else []", "def histogram(a, n):\n r = [0] * (max(a, default=-1) // n + 1)\n for x in a:\n r[x // n] += 1\n return r", "def histogram(values, bin_width):\n k = []\n end = max(values) if values else -1\n bin = [i for i in range(bin_width, end + bin_width + 1, bin_width)]\n for i in bin:\n count = 0\n for val in values:\n if i - bin_width <= val < i:\n count += 1\n k += [count]\n return k", "from collections import Counter\n\ndef histogram(values, bin_width):\n count = Counter(values)\n return [sum((count[i + x] for x in range(bin_width))) for i in range(0, max(count) + 1, bin_width)] if count else []", "import math\n\ndef histogram(values, bin_width):\n if values == []:\n return []\n hist = [0] * math.ceil((max(values) + 1) / bin_width)\n for v in values:\n hist[math.floor(v / bin_width)] += 1\n return hist", "from itertools import groupby\n\ndef histogram(values, bin_width):\n c = {k: len(list(g)) for (k, g) in groupby(sorted(values), key=lambda x: x // bin_width)}\n return [c.get(i, 0) for i in range(max(c) + 1)] if c else []", "def histogram(values, bin_width):\n if len(values) == 0:\n return []\n list = [values.count(digit) for digit in range(0, max(values) + 1)]\n return [sum(list[digit:digit + bin_width]) for digit in range(0, len(list), bin_width)]"], "starter_code": "def histogram(values, bin_width):\n", "input_output": {"fn_name": "histogram", "inputs": [[[1, 1, 0, 1, 3, 2, 6], 1], [[1, 1, 0, 1, 3, 2, 6], 2], [[], 1], [[8], 1]], "outputs": [[[1, 3, 1, 1, 0, 0, 1]], [[4, 2, 0, 1]], [[]], [[0, 0, 0, 0, 0, 0, 0, 0, 1]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Algorithms", "Data Science"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5704bf9b38428f1446000a9d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "histogram", "task_id": "TACO_lite/227", "example": [[[[1, 1, 0, 1, 3, 2, 6], 1], [[1, 1, 0, 1, 3, 2, 6], 2], [[7], 1]], ["[1, 3, 1, 1, 0, 0, 1]", "[4, 2, 0, 1]", "[0, 0, 0, 0, 0, 0, 0, 1]"]]} +{"requirement": "Given an array containing only integers, add all the elements and return the binary equivalent of that sum.\n\nIf the array contains any non-integer element (e.g. an object, a float, a string and so on), return false.\n\n**Note:** The sum of an empty array is zero.\n\n```python\narr2bin([1,2]) == '11'\narr2bin([1,2,'a']) == False\n```", "solutions": ["def arr2bin(arr):\n for x in arr:\n if type(x) != int:\n return False\n return '{0:b}'.format(sum(arr))", "def arr2bin(arr):\n return all((type(n) == int for n in arr)) and format(sum(arr), 'b')", "def arr2bin(arr):\n s = 0\n for x in arr:\n if type(x) is int:\n s += x\n else:\n return False\n return '{:b}'.format(s)", "def arr2bin(arr):\n if all(map(lambda x: type(x) == int, arr)):\n return '{0:b}'.format(sum(arr))\n return False", "def arr2bin(arr):\n if any((type(a) is not int for a in arr)):\n return False\n return bin(sum(arr))[2:]", "def arr2bin(arr):\n return False if any((type(e) != int for e in arr)) else bin(sum(arr))[2:]", "def arr2bin(arr):\n if any((type(x) != int for x in arr)):\n return False\n return bin(sum(arr))[2:]", "def arr2bin(arr):\n return all((isinstance(n, int) and (not isinstance(n, bool)) for n in arr)) and bin(sum((n for n in arr)))[2:]", "def arr2bin(arr):\n if all((type(x) is int for x in arr)):\n return '{:b}'.format(sum(arr))\n else:\n return False", "def arr2bin(arr):\n try:\n return bin(sum((int(x) if not isinstance(x, bool) else None for x in arr)))[2:]\n except:\n return False"], "starter_code": "def arr2bin(arr):\n", "input_output": {"fn_name": "arr2bin", "inputs": [[[1, 2]], [[1, 2, 3, 4, 5]], [[1, 10, 100, 1000]], [[1, 2, -1, -2]], [[1, 2, -1, -2, 1]], [[]]], "outputs": [["11"], ["1111"], ["10001010111"], ["0"], ["1"], ["0"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/559576d984d6962f8c00003c", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "arr2bin", "task_id": "TACO_lite/268", "example": [[[[1, 2]], [[1, 2, "a"]]], ["11", "False"]]} +{"requirement": "For an integer N find the number of trailing zeroes in N!.\nExample 1:\nInput:\nN = 5\nOutput:\n1\nExplanation:\n5! = 120 so the number of trailing zero is 1.\nExample 2:\nInput:\nN = 4\nOutput:\n0\nExplanation:\n4! = 24 so the number of trailing zero is 0.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function trailingZeroes() which take an integer N as an input parameter and returns the count of trailing zeroes in the N!.\nExpected Time Complexity: O(logN)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 10^{9}", "solutions": ["import re\nimport math\n\ndef trailingzeroes(N):\n triling_zero = 0\n while N:\n triling_zero += N // 5\n N = N // 5\n return triling_zero", "def trailingzeroes(N):\n res = 0\n while N >= 5:\n N //= 5\n res += N\n return res", "def trailingzeroes(N):\n if N < -1:\n return -1\n count = 0\n while N >= 5:\n N //= 5\n count += N\n return count", "def trailingzeroes(N):\n r = 0\n n = 5\n while n <= N:\n r += int(N / n)\n n = n * 5\n return r", "def trailingzeroes(N):\n result = 0\n x = N\n while x > 4:\n x = x // 5\n result += x\n return result", "def trailingzeroes(N):\n count = 0\n while N >= 5:\n count = count + N // 5\n N //= 5\n return count", "def trailingzeroes(n):\n if n < 0:\n return -1\n if n <= 4:\n return 0\n count = 0\n while n >= 5:\n n = n // 5\n count += n\n return count", "def trailingzeroes(N):\n count = 0\n i = 5\n while N / i >= 1:\n count += int(N / i)\n i *= 5\n return int(count)", "import math\n\ndef trailingzeroes(N):\n x = 5\n count = 0\n while x <= N:\n count += N // x\n x *= 5\n return count", "def trailingzeroes(N):\n c = 0\n n5 = N - N % 5\n p = 1\n while n5 / 5 ** p >= 1:\n c += int(n5 / 5 ** p)\n p += 1\n return c", "import math\n\ndef trailingzeroes(N):\n zeros = 0\n i = 5\n while i <= N:\n zeros += N // i\n i *= 5\n return zeros", "from math import factorial\n\ndef trailingzeroes(N):\n s = 0\n while N >= 5:\n N //= 5\n s += N\n return s", "def trailingzeroes(N):\n tz = 0\n while N != 0:\n tz += int(N / 5)\n N = int(N / 5)\n return tz", "def trailingzeroes(N):\n power = 5\n c = 0\n while N >= power:\n c += N // power\n power *= 5\n return c", "def trailingzeroes(N):\n ans = 0\n i = 5\n while i <= N:\n ans += N // i\n i *= 5\n return ans", "def trailingzeroes(N):\n temp = 5\n ans = 0\n while temp <= N:\n ans += N // temp\n temp *= 5\n return ans", "import math\n\ndef trailingzeroes(N):\n res = 0\n i = 1\n while math.pow(5, i) <= N:\n res += N // math.pow(5, i)\n i += 1\n return int(res)", "import math\n\ndef trailingzeroes(n):\n count = 0\n while n >= 5:\n n //= 5\n count += n\n return count", "def trailingzeroes(N):\n if N < 0:\n return -1\n if N <= 4:\n return 0\n ct = 0\n while N >= 5:\n N = N // 5\n ct += N\n return ct", "from math import factorial\n\ndef trailingzeroes(n):\n if n < 5:\n return 0\n return n // 5 + self.trailingzeroes(n // 5)", "def trailingzeroes(n):\n if n < 5:\n return 0\n return n // 5 + self.trailingzeroes(n // 5)", "def trailingzeroes(N):\n m = N\n i = 5\n t = 0\n while m // i >= 1:\n t += m // i\n i *= 5\n return t", "def trailingzeroes(n):\n ans = 0\n while n >= 5:\n n //= 5\n ans += n\n return ans", "def trailingzeroes(N):\n c = 0\n i = 5\n while N // i >= 1:\n c += N // i\n i *= 5\n return c", "def trailingzeroes(N):\n x = 5\n c = 0\n while x <= N:\n c += N // x\n x *= 5\n return c", "import math\n\ndef trailingzeroes(N):\n ans = 0\n for i in range(int(math.log(N))):\n ans += N // 5 ** (i + 1)\n return ans", "def trailingzeroes(N):\n result = 0\n while N >= 5:\n N //= 5\n result += N\n return result", "def trailingzeroes(N):\n sum = 0\n i = 5\n while i <= N:\n sum += N // i\n i *= 5\n return sum", "def trailingzeroes(N):\n n = N\n res = 0\n i = 5\n while i <= N:\n res += N // i\n i *= 5\n return res", "def trailingzeroes(N):\n five = 0\n i = 5\n while i <= N:\n five += N // i\n i *= 5\n return five", "def trailingzeroes(N):\n total = 0\n i = 5\n while i <= N:\n total += N // i\n i *= 5\n return total", "def trailingzeroes(n):\n count_zero = 0\n i = 5\n while n / i > 0:\n count_zero += n // i\n i = i * 5\n return count_zero", "def trailingzeroes(N):\n ans = 0\n while True:\n a = N // 5\n ans += a\n N = a\n if N <= 0:\n break\n return ans", "val = Solution()\nval.trailingzeroes(5)\n\ndef trailingzeroes(N):\n count = 0\n i = 5\n while i <= N:\n count += N // i\n i *= 5\n return count", "def trailingzeroes(N):\n x = 5\n cnt = 0\n while x <= N:\n cnt += N // x\n x *= 5\n return cnt", "def trailingzeroes(n):\n c = 0\n i = 5\n while n / i >= 1:\n c = c + int(n / i)\n i = i * 5\n return c", "def trailingzeroes(n):\n ans = 0\n i = 5\n while n // i >= 1:\n count = int(n / i)\n i *= 5\n ans += count\n return ans", "def trailingzeroes(N):\n if N < 5:\n return 0\n else:\n k = 0\n while N > 1:\n N = N // 5\n k = k + N\n return k", "def trailingzeroes(N):\n k = N\n c5 = 0\n while k > 0:\n count = k // 5\n k = count\n c5 += count\n k = N\n c2 = 0\n while k > 0:\n count = k // 2\n k = count\n c2 += count\n return c5 if c5 < c2 else c2", "def trailingzeroes(n):\n c = 0\n while n >= 5:\n n //= 5\n c += n\n return c"], "starter_code": "def trailingzeroes(N):\n", "input_output": {"inputs": ["N = 5", "N = 4"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/trailing-zeroes-in-factorial5134/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(logN)", "entry_point": "trailingzeroes", "task_id": "TACO_lite/269", "example": [[[5], [4]], ["1", "0"]]} +{"requirement": "Given an array A[] of size N, find the longest subsequence such that difference between adjacent elements is one.\nExample 1:\nInput: N = 7\nA[] = {10, 9, 4, 5, 4, 8, 6}\nOutput: 3\nExplaination: The three possible subsequences \n{10, 9, 8} , {4, 5, 4} and {4, 5, 6}.\nExample 2:\nInput: N = 5\nA[] = {1, 2, 3, 4, 5}\nOutput: 5\nExplaination: All the elements can be \nincluded in the subsequence.\nYour Task:\nYou do not need to read input. Your task is to complete the function longestSubseq() which takes N and A[] as input parameters and returns the length of the longest such subsequence.\nExpected Time Complexity: O(N^{2})\nExpected Auxiliary Space: O(N)\nConstraints:\n1 \u2264 N \u2264 10^{3}\n1 \u2264 A[i] \u2264 10^{3}", "solutions": ["def longestsubsequence(n, a):\n L = [1 for i in range(n)]\n for i in range(n):\n for j in range(0, i):\n if a[i] == a[j] - 1 or a[i] == a[j] + 1:\n L[i] = max(L[i], L[j] + 1)\n mx = L[0]\n for i in range(0, n):\n mx = max(mx, L[i])\n return mx", "def longestsubsequence(N, A):\n if N == 1:\n return 1\n dp = [1] * N\n for i in range(N - 1, -1, -1):\n for j in range(i + 1, N):\n if abs(A[i] - A[j]) == 1:\n dp[i] = max(dp[i], 1 + dp[j])\n return max(dp)", "def dp_sol(N, A):\n dp = [1] * (N + 1)\n dp[0] = 0\n for i in range(2, N + 1):\n for j in range(1, i):\n if A[j - 1] - A[i - 1] == 1 or A[j - 1] - A[i - 1] == -1:\n dp[i] = max(dp[i], 1 + dp[j])\n return max(dp)\n\ndef longestsubsequence(N, A):\n return self.dp_sol(N, A)", "def longestsubsequence(N, A):\n stateMap = [1 for _ in range(N)]\n for ind in range(1, N):\n maxVal = 1\n for lInd in range(ind):\n if A[ind] == A[lInd] - 1 or A[ind] == A[lInd] + 1:\n maxVal = max(maxVal, stateMap[lInd] + 1)\n stateMap[ind] = maxVal\n return max(stateMap)", "def longestsubsequence(n, A):\n t = [1] * n\n for i in range(1, n):\n for j in range(i):\n if abs(A[i] - A[j]) == 1 and t[i] < t[j] + 1:\n t[i] = t[j] + 1\n return max(t)", "def longestsubsequence(n, arr):\n dp = [1 for i in range(n)]\n for i in range(n):\n for j in range(i):\n if arr[i] == arr[j] + 1 or arr[i] == arr[j] - 1:\n dp[i] = max(dp[i], dp[j] + 1)\n result = 1\n for i in range(n):\n if result < dp[i]:\n result = dp[i]\n return result", "def longestsubsequence(n, a):\n dp = [1] * n\n m = 1\n for i in range(1, n):\n for j in range(i):\n if a[i] - a[j] == 1 or a[i] - a[j] == -1:\n dp[i] = max(dp[i], dp[j] + 1)\n m = max(m, dp[i])\n return m", "def longestsubsequence(N, A):\n if N == 1:\n return 1\n dp = [0 for _ in range(N)]\n res = 1\n for pos in range(N):\n dp[pos] = 1\n for idx in range(pos):\n if A[pos] == A[idx] + 1 or A[pos] == A[idx] - 1:\n dp[pos] = max(dp[pos], dp[idx] + 1)\n res = max(res, dp[pos])\n return res", "def longestsubsequence(n, arr):\n dp = [1] * n\n for ind in range(n):\n for prev in range(ind):\n if abs(arr[prev] - arr[ind]) == 1:\n dp[ind] = max(dp[ind], 1 + dp[prev])\n return max(dp)", "def longestsubsequence(N, A):\n dp = {}\n\n def rec(idx, prev, count):\n if idx < 0:\n return count\n if (idx, prev) in dp:\n return dp[idx, prev]\n pick = 0\n if prev == -1 or abs(A[idx] - A[prev]) == 1:\n pick = rec(idx - 1, idx, count + 1)\n npick = rec(idx - 1, prev, count)\n dp[idx, prev] = max(pick, npick)\n return dp[idx, prev]\n dp = [1] * N\n for i in range(N):\n for j in range(i):\n if abs(A[i] - A[j]) == 1:\n dp[i] = max(dp[i], dp[j] + 1)\n return max(dp)", "def solve(A, N):\n arr = [1] * N\n for i in range(1, N):\n for j in range(0, i):\n if abs(A[i] - A[j]) == 1:\n arr[i] = max(arr[i], arr[j] + 1)\n return max(arr)\n\ndef longestsubsequence(N, A):\n return solve(A, N)", "def fun(idx, arr, n, prev, dp):\n if idx == n:\n return 0\n if dp[idx][prev + 1] != -1:\n return dp[idx][prev + 1]\n np = 0 + self.fun(idx + 1, arr, n, prev, dp)\n p = 0\n if prev == -1 or abs(arr[idx] - arr[prev]) == 1:\n p = 1 + self.fun(idx + 1, arr, n, idx, dp)\n dp[idx][prev + 1] = max(p, np)\n return dp[idx][prev + 1]\n\ndef longestsubsequence(n, arr):\n dp = [1 for i in range(N + 1)]\n dp[0] = 1\n for i in range(1, N):\n for j in range(i):\n if abs(A[j] - A[i]) == 1:\n dp[i] = max(dp[i], dp[j] + 1)\n mx = -999\n for i in range(N):\n mx = max(dp[i], mx)\n return mx", "def longestsubsequence(n, a):\n res = [1] * n\n for i in range(1, n):\n for j in range(i):\n if abs(a[i] - a[j]) == 1:\n res[i] = max(res[i], 1 + res[j])\n return max(res)", "def longestsubsequence(N, A):\n h = {}\n ans = 0\n for i in range(N):\n l = 0\n if A[i] - 1 in h:\n l = h[A[i] - 1]\n if A[i] + 1 in h:\n l = max(l, h[A[i] + 1])\n h[A[i]] = l + 1\n ans = max(ans, h[A[i]])\n return ans", "def longestsubsequence(N, A):\n DP = [0] * N\n DP[0] = 1\n for i in range(1, N):\n temp = [0]\n for j in range(i):\n if abs(A[j] - A[i]) == 1:\n temp.append(DP[j])\n DP[i] = max(temp) + 1\n return max(DP)", "def longestsubsequence(N, A):\n dict = {}\n ans = 1\n for i in range(N):\n len = 1\n if A[i] - 1 in dict:\n len = max(len, dict[A[i] - 1] + 1)\n if A[i] + 1 in dict:\n len = max(len, dict[A[i] + 1] + 1)\n dict[A[i]] = len\n ans = max(ans, len)\n return ans", "def longestsubsequence(N, A):\n b = [0 for hm in range(N)]\n b[0] = 1\n for hm in range(1, N):\n for gm in range(hm):\n if abs(A[hm] - A[gm]) == 1:\n b[hm] = max(b[hm], b[gm] + 1)\n b[hm] = max(b[hm], 1)\n return max(b)", "from collections import defaultdict\n\ndef longestsubsequence(n, a):\n dp = defaultdict(lambda : 0)\n dp[a[0]] = 1\n c = 1\n for i in range(1, n):\n temp = 1\n if a[i] + 1 in dp or a[i] - 1 in dp:\n temp = 1 + max(dp[a[i] - 1], dp[a[i] + 1])\n c = max(c, temp)\n dp[a[i]] = temp\n return c", "def longestsubsequence(n, arr):\n d = {}\n d[arr[0]] = 1\n dp = [1] * n\n for i in range(1, n):\n ans1 = d.get(arr[i] - 1, 0)\n ans2 = d.get(arr[i] + 1, 0)\n if ans1 or ans2:\n dp[i] = 1 + max(ans1, ans2)\n d[arr[i]] = dp[i]\n return max(dp)", "def longestsubsequence(n, arr):\n dp = [1] * n\n for i in range(1, n):\n for j in range(0, i):\n if abs(arr[i] - arr[j]) == 1:\n dp[i] = max(dp[i], dp[j] + 1)\n return max(dp)", "def longestsubsequence(N, a):\n LIS = [1] * N\n for i in range(N - 2, -1, -1):\n for j in range(i + 1, N):\n if abs(a[i] - a[j]) == 1:\n LIS[i] = max(LIS[i], 1 + LIS[j])\n return max(LIS)", "def longestsubsequence(N, A):\n n = N\n res = [1 for each in range(n + 1)]\n for i in range(n - 1, -1, -1):\n for j in range(i, n):\n if abs(A[j] - A[i]) == 1:\n res[i] = max(res[i], 1 + res[j])\n return max(res)", "def longestsubsequence(N, A):\n m = 0\n t = [1 for _ in range(N)]\n for i in range(N):\n for prev in range(i):\n if abs(A[i] - A[prev]) == 1:\n t[i] = max(t[i], 1 + t[prev])\n m = max(m, t[i])\n return m", "def longestsubsequence(N, A):\n dp = [1] * N\n maxi = float('-inf')\n for ind in range(N):\n for prev_ind in range(ind):\n if abs(A[prev_ind] - A[ind]) == 1 and 1 + dp[prev_ind] > dp[ind]:\n dp[ind] = 1 + dp[prev_ind]\n maxi = max(maxi, dp[ind])\n return maxi", "from collections import defaultdict\n\ndef longestsubsequence(N, A):\n d = defaultdict(lambda : 0)\n for item in A:\n d[item] = max(d[item], max(d[item - 1], d[item + 1]) + 1)\n return max(d.values())", "def longestsubsequence_ending_at_i(N, A, index, dp_arr):\n if dp_arr[index] != -1:\n return dp_arr[index]\n maximum = 1\n for i in range(index):\n if A[i] == A[index] - 1 or A[i] == A[index] + 1:\n maximum = max(maximum, 1 + self.longestsubsequence_ending_at_i(N, A, i, dp_arr))\n dp_arr[index] = maximum\n return maximum\n\ndef longestsubsequence(N, A):\n dp_arr = [-1 for i in range(N)]\n max_subsequence = -1\n for i in range(N):\n max_subsequence = max(self.longestsubsequence_ending_at_i(N, A, i, dp_arr), max_subsequence)\n return max_subsequence", "def longestsubsequence(N, A):\n mapp = {}\n ma = 1\n for i in range(0, N):\n k = A[i]\n val = 0\n if k - 1 in mapp:\n val = mapp[k - 1]\n if k + 1 in mapp and mapp[k + 1] > val:\n val = mapp[k + 1]\n mapp[A[i]] = val + 1\n ma = max(ma, val + 1)\n return ma", "def longestsubsequence(N, A):\n dp = [1 for _ in range(N)]\n longestsubsequencesNumber = 1\n for i in range(len(A) - 2, -1, -1):\n for j in range(i + 1, len(A)):\n if abs(A[j] - A[i]) == 1:\n dp[i] = max(dp[i], 1 + dp[j])\n longestsubsequencesNumber = max(longestsubsequencesNumber, dp[i])\n return longestsubsequencesNumber", "def longestsubsequence(N, arr):\n dp = [1] * N\n for i in range(1, N):\n for j in range(0, i):\n if arr[i] == arr[j] + 1 or arr[j] - 1 == arr[i]:\n dp[i] = max(dp[i], dp[j] + 1)\n return max(dp)", "from collections import defaultdict\n\ndef longestsubsequence(n, A):\n d = defaultdict(int)\n ans = 0\n for i in range(n):\n temp = 0\n if A[i] - 1 in d:\n temp = d[A[i] - 1]\n if A[i] + 1 in d:\n temp = max(temp, d[A[i] + 1])\n d[A[i]] = 1 + temp\n ans = max(ans, temp + 1)\n return ans", "def longestsubsequence(N, A):\n temp = [0] * len(A)\n for i in range(len(A)):\n sub = [temp[k] for k in range(i) if A[i] == A[k] - 1 or A[i] - 1 == A[k]]\n temp[i] = 1 + max(sub, default=0)\n return max(temp, default=0)", "def longestsubsequence(n, A):\n arr = [1 for i in range(n)]\n for i in range(1, n):\n for j in range(0, i):\n if A[i] - A[j] == 1 or A[i] - A[j] == -1:\n arr[i] = max(arr[i], arr[j] + 1)\n return max(arr)", "def solve(a, cur, prev, dp):\n if cur == len(a):\n return 0\n if dp[prev + 1][cur] != -1:\n return dp[prev + 1][cur]\n inc = 0\n if prev == -1 or abs(a[prev] - a[cur]) == 1:\n inc = 1 + Solution.solve(a, cur + 1, cur, dp)\n exc = Solution.solve(a, cur + 1, prev, dp)\n dp[prev + 1][cur] = max(inc, exc)\n return dp[prev + 1][cur]\n\ndef longestsubsequence(n, arr):\n dp = [1 for _ in range(n)]\n maxi = 1\n for i in range(n):\n for j in range(i):\n if abs(arr[i] - arr[j]) == 1:\n dp[i] = max(dp[i], dp[j] + 1)\n for i in range(n):\n maxi = max(maxi, dp[i])\n return maxi", "def longestsubsequence(N, arr):\n dp = [1 for x in range(N)]\n maxi = 0\n for i in range(N):\n for prev in range(i):\n if abs(arr[i] - arr[prev]) == 1 and dp[i] < 1 + dp[prev]:\n dp[i] = 1 + dp[prev]\n maxi = max(maxi, dp[i])\n return maxi", "from collections import defaultdict\n\ndef longestsubsequence(n, arr):\n ans = 0\n hmap = defaultdict(int)\n for num in arr:\n hmap[num] = max(hmap[num - 1], hmap[num + 1]) + 1\n ans = max(ans, hmap[num])\n return ans", "def __init__():\n self.ans = 0\n self.dp = {}\n\ndef longestsubsequence(N, A):\n if len(A) == 1:\n return 1\n\n def solve(array, i, j, sum):\n if j >= len(array) or i >= len(array):\n self.ans = max(self.ans, sum)\n return sum\n for k in range(j, len(array)):\n if abs(A[k] - A[i]) == 1:\n if (i, k) not in self.dp:\n b = sum + 1\n ss = solve(array, k, k + 1, b)\n self.dp[i, k] = b\n else:\n self.ans = max(self.ans, self.dp[i, k])\n self.ans = max(self.ans, sum)\n return sum\n for l in range(len(A) - 1):\n s = 1\n solve(A, l, l + 1, s)\n return self.ans", "import collections\n\ndef longestsubsequence(N, A):\n dp = collections.defaultdict()\n for number in A:\n if number + 1 in dp and number - 1 in dp:\n if dp[number + 1] > dp[number - 1]:\n dp[number] = dp[number + 1] + 1\n else:\n dp[number] = dp[number - 1] + 1\n elif number + 1 in dp:\n dp[number] = dp[number + 1] + 1\n elif number - 1 in dp:\n dp[number] = dp[number - 1] + 1\n else:\n dp[number] = 1\n return max(dp.items(), key=lambda x: x[1])[1]", "def longestsubsequence(N, A):\n res = []\n for i in range(N):\n m = 1\n for j in range(i):\n if abs(A[j] - A[i]) == 1 and res[j] >= m:\n m = res[j] + 1\n res.append(m)\n return max(res)", "def longestsubsequence(N, A):\n t = [0 for i in range(0, N + 2)]\n ans = 0\n for i in range(0, N):\n temp = 0\n for j in range(0, i):\n if abs(A[j] - A[i]) == 1:\n if t[j] > temp:\n temp = t[j]\n t[i] = 1 + temp\n if t[i] > ans:\n ans = t[i]\n return ans", "def longestsubsequence(n, a):\n maxx = 1\n dp = [1 for i in range(n)]\n for i in range(1, n):\n for j in range(i):\n if abs(a[i] - a[j]) == 1 and dp[i] < dp[j] + 1:\n dp[i] = dp[j] + 1\n maxx = max(dp[i], maxx)\n return maxx", "from collections import defaultdict\n\ndef longestsubsequence(N, A):\n d = defaultdict(lambda : 0)\n ans = 0\n for i in A:\n d[i] = 1 + max(d[i - 1], d[i + 1])\n ans = max(ans, d[i])\n return ans"], "starter_code": "def longestsubsequence(N, A):\n", "input_output": {"inputs": ["N = 7\r\nA[] = {10, 9, 4, 5, 4, 8, 6}", "N = 5\r\nA[] = {1, 2, 3, 4, 5}"], "outputs": ["3", "5"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/longest-subsequence-such-that-difference-between-adjacents-is-one4724/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N^{2})", "entry_point": "longestsubsequence", "task_id": "TACO_lite/192", "example": [[[7, [10, 9, 4, 5, 4, 8, 6]], [5, [1, 2, 3, 4, 5]]], ["3", "5"]]} +{"requirement": "Given a series of numbers 2, 10, 30, 68, 130.., Identify the pattern in the series. You are given an integer X you need to find out the X'th number in the series.\nExample 1:\nInput:\nX = 1\nOutput:\n2\nExplanation:\n2 is the first number in the series.\nExample 2:\nInput:\nX = 2\nOutput:\n10\nExplanation:\n10 is the second number in the series.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function X1Series() which takes an integer X as an input parameter and return the X'th number in the series.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 X \u2264 10^{5}", "solutions": ["def x1series(X):\n return pow(X, 3) + X", "def x1series(m):\n return m * (m * m + 1)", "def x1series(X):\n temp = 2\n xr = 3\n sums = 0\n if X == 1:\n return temp\n for i in range(2, X + 1):\n temp = temp + xr\n xr = xr + 2\n sums = temp * i\n return sums", "def x1series(X):\n return X * (X * X + 1)", "def x1series(n):\n return n ** 3 + n", "def x1series(x):\n return x ** 3 + x", "def x1series(X: int) -> int:\n return X + X ** 3", "def x1series(x):\n return x * (x * x + 1)", "import math\n\ndef x1series(X):\n return int(math.pow(X, 3)) + X", "def x1series(X):\n n = X - 1\n return n * (n * n + 3 * n + 4) + 2", "def x1series(X):\n n = 0\n n = X ** 3 + X\n return n", "def x1series(X):\n nth_term = X * (X ** 2 + 1)\n return nth_term"], "starter_code": "def x1series(X):\n", "input_output": {"inputs": ["X = 1", "X = 2"], "outputs": ["2", "10"]}, "difficulty": "EASY", "raw_tags": ["series"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/series-x14741/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "x1series", "task_id": "TACO_lite/286", "example": [[[1], [2]], ["2", "10"]]} +{"requirement": "Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.\n\nNote: You can only move either down or right at any point in time.\n\nExample:\n\n\nInput:\n[\n\u00a0 [1,3,1],\n [1,5,1],\n [4,2,1]\n]\nOutput: 7\nExplanation: Because the path 1\u21923\u21921\u21921\u21921 minimizes the sum.", "solutions": ["def minpathsum(grid):\n (m, n) = (len(grid), len(grid[0]))\n dp = [0] + [float('inf')] * (n - 1)\n for i in range(m):\n dp[0] = dp[0] + grid[i][0]\n for j in range(1, n):\n dp[j] = min(dp[j], dp[j - 1]) + grid[i][j]\n return dp[-1]", "def minpathsum(grid):\n m = len(grid)\n n = len(grid[0])\n dp = [grid[0][j] for j in range(n)]\n for j in range(1, n):\n dp[j] += dp[j - 1]\n for i in range(1, m):\n for j in range(n):\n if j == 0:\n dp[j] += grid[i][j]\n else:\n dp[j] = min(grid[i][j] + dp[j - 1], grid[i][j] + dp[j])\n return dp[-1]", "def minpathsum(grid):\n M = len(grid)\n if M == 0:\n return 0\n N = len(grid[0])\n if N == 0:\n return 0\n INF = float('inf')\n mem = {}\n\n def min_path(i, j):\n if i == M - 1 and j == N - 1:\n return grid[i][j]\n if (i, j) in mem:\n return mem[i, j]\n min_sum = INF\n if i < M - 1:\n min_sum = min_path(i + 1, j)\n if j < N - 1:\n min_sum = min(min_sum, min_path(i, j + 1))\n mem[i, j] = grid[i][j] + min_sum\n return mem[i, j]\n return min_path(0, 0)", "def minpathsum(grid):\n m = len(grid) - 1\n n = len(grid[0]) - 1\n dic = dict()\n s = self.minpathsumHelper(grid, 0, 0, m, n, dic)\n return s\n\ndef minpathsumHelper(grid, i, j, m, n, dic):\n if (i, j, m, n) in dic:\n return dic[i, j, m, n]\n if i > m or j > n:\n return 0\n elif i == m:\n dic[i, j, m, n] = self.minpathsumHelper(grid, i, j + 1, m, n, dic) + grid[i][j]\n return dic[i, j, m, n]\n elif j == n:\n dic[i, j, m, n] = self.minpathsumHelper(grid, i + 1, j, m, n, dic) + grid[i][j]\n return dic[i, j, m, n]\n else:\n dic[i, j, m, n] = min(self.minpathsumHelper(grid, i + 1, j, m, n, dic), self.minpathsumHelper(grid, i, j + 1, m, n, dic)) + grid[i][j]\n return dic[i, j, m, n]", "def minpathsum(grid):\n max_row = len(grid) - 1\n max_col = len(grid[0]) - 1\n helper_grid = [[0] * len(grid[0]) for _ in range(len(grid))]\n helper_grid[max_row][max_col] = grid[max_row][max_col]\n for i in range(max_col - 1, -1, -1):\n helper_grid[max_row][i] = grid[max_row][i] + helper_grid[max_row][i + 1]\n for i in range(max_row - 1, -1, -1):\n helper_grid[i][max_col] = grid[i][max_col] + helper_grid[i + 1][max_col]\n for col in range(max_col - 1, -1, -1):\n for row in range(max_row - 1, -1, -1):\n helper_grid[row][col] = grid[row][col] + min(helper_grid[row + 1][col], helper_grid[row][col + 1])\n return helper_grid[0][0]", "def minpathsum(grid):\n if not grid:\n return 0\n row_count = len(grid)\n col_count = len(grid[0])\n for i in range(1, row_count):\n grid[i][0] += grid[i - 1][0]\n for i in range(1, col_count):\n grid[0][i] += grid[0][i - 1]\n for row in range(1, row_count):\n for col in range(1, col_count):\n grid[row][col] += min(grid[row - 1][col], grid[row][col - 1])\n return grid[-1][-1]", "def minpathsum(grid):\n if not grid:\n return 0\n (row, col) = (len(grid), len(grid[0]))\n dp = [0 for _ in range(col)]\n dp[0] = grid[0][0]\n for i in range(1, col):\n dp[i] = dp[i - 1] + grid[0][i]\n for i in range(1, row):\n for j in range(0, col):\n dp[j] = dp[j] + grid[i][j] if j == 0 else min(dp[j - 1], dp[j]) + grid[i][j]\n return dp[-1]", "def minpathsum(grid):\n if not grid:\n return 0\n row_count = len(grid)\n col_count = len(grid[0])\n dp = [[0 for _ in range(col_count)] for _ in range(row_count)]\n dp[0][0] = grid[0][0]\n if row_count == col_count and col_count == 1:\n return dp[-1][-1]\n for row in range(row_count):\n for col in range(col_count):\n if row == 0 and col >= 1:\n dp[row][col] = dp[row][col - 1] + grid[row][col]\n elif col == 0 and row >= 1:\n dp[row][col] = dp[row - 1][col] + grid[row][col]\n else:\n dp[row][col] = min(dp[row - 1][col], dp[row][col - 1]) + grid[row][col]\n return dp[-1][-1]", "def minpathsum(grid):\n m = len(grid)\n n = len(grid[0])\n s = [[0 for j in range(n)] for i in range(m)]\n s[0][0] = grid[0][0]\n for i in range(1, m):\n s[i][0] = s[i - 1][0] + grid[i][0]\n for j in range(1, n):\n s[0][j] = s[0][j - 1] + grid[0][j]\n for i in range(1, m):\n for j in range(1, n):\n s[i][j] = min(s[i - 1][j] + grid[i][j], s[i][j - 1] + grid[i][j])\n return s[m - 1][n - 1]", "def minpathsum(grid):\n height = len(grid)\n width = len(grid[0])\n step_num = height + width - 2\n for step in range(1, step_num + 1):\n for row in range(height):\n col = step - row\n if 0 <= row < height and 0 <= col < width:\n if not row:\n grid[row][col] += grid[row][col - 1]\n elif not col:\n grid[row][col] += grid[row - 1][col]\n else:\n grid[row][col] += min(grid[row][col - 1], grid[row - 1][col])\n return grid[-1][-1]", "def minpathsum(grid):\n col = len(grid[0])\n row = len(grid)\n minSum = [[0 for x in range(col)] for y in range(row)]\n for i in range(row):\n for j in range(col):\n add = 0\n if i - 1 >= 0 and j - 1 >= 0:\n add = min(minSum[i - 1][j], minSum[i][j - 1])\n elif i - 1 >= 0:\n add = minSum[i - 1][j]\n elif j - 1 >= 0:\n add = minSum[i][j - 1]\n minSum[i][j] = grid[i][j] + add\n return minSum[-1][-1]", "def minpathsum(grid):\n m = len(grid)\n n = len(grid[0])\n if m == 0 or n == 0:\n return 0\n memory = [[0 for _ in range(n)] for _ in range(m)]\n\n def minSum(grid, x, y, n, m):\n if x == 0 and y == 0:\n return grid[0][0]\n if x < 0 or y < 0:\n return float('inf')\n if memory[y][x] > 0:\n return memory[y][x]\n memory[y][x] = grid[y][x] + min(minSum(grid, x - 1, y, n, m), minSum(grid, x, y - 1, n, m))\n return memory[y][x]\n return minSum(grid, n - 1, m - 1, n, m)"], "starter_code": "def minpathsum(grid: List[List[int]]) -> int:\n", "input_output": {"fn_name": "minPathSum", "inputs": [[[[1, 3, 1], [1, 5, 1], [4, 2, 1]]], [[[1, 2, 3], [4, 5, 6]]]], "outputs": [7, 12]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Dynamic Programming", "Matrix"], "name": null, "source": "leetcode", "tags": ["Matrices", "Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/minimum-path-sum/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "minpathsum", "task_id": "TACO_lite/297", "example": [[[[[1, 3, 1], [1, 5, 1], [4, 2, 1]]]], ["7"]]} +{"requirement": "Given an integer N, find the absolute difference between sum of the squares of first N natural numbers and square of sum of first N natural numbers.\nExample 1:\nInput: N = 2\nOutput: 4 \nExplanation: abs|(1^{2 }+ 2^{2}) - (1 + 2)^{2}| = 4.\nExample 2:\nInput: N = 3\nOutput: 22\nExplanation: abs|(1^{2 }+ 2^{2} + 3^{2}) - (1 + 2 + 3)^{2}| = 22.\nYour Task: \nYou dont need to read input or print anything. Complete the function squaresDiff() which takes N as input parameter and returns the absolute difference.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1<= N <=10^{3}", "solutions": ["def squaresdiff(N):\n s = 0\n s1 = 0\n for i in range(1, N + 1):\n s += i ** 2\n s1 += i\n return abs(s - s1 ** 2)", "def squaresdiff(N):\n a = int(N * (N + 1) * (2 * N + 1) / 6)\n b = int(N * (N + 1) / 2)\n c = a - b ** 2\n d = abs(c)\n return d", "def squaresdiff(N):\n a = N * (N + 1) // 2\n x = a * a\n l = []\n for i in range(1, N + 1):\n l.append(i * i)\n y = sum(l)\n return abs(x - y)", "def squaresdiff(n):\n return abs(int(n * (n + 1) * (2 * n + 1) / 6 - n * (n + 1) / 2 * (n * (n + 1) / 2)))", "def squaresdiff(N):\n a = 0\n for i in range(1, N + 1):\n a = a + i * i\n b = N * (N + 1) // 2\n c = b * b\n return abs(a - c)", "def squaresdiff(n):\n s1 = (n * (n + 1) // 2) ** 2\n s2 = n * (n + 1) * (2 * n + 1) // 6\n return abs(s2 - s1)", "def squaresdiff(N):\n l = 0\n r = 0\n for i in range(1, N + 1):\n l += i ** 2\n r += i\n return abs(l - r ** 2)", "def squaresdiff(N):\n t = int(N * (N + 1) * (2 * N + 1) / 6)\n m = int(N * (N + 1) / 2)\n n = t - m ** 2\n return abs(n)", "def squaresdiff(n):\n x = n * (n + 1) * (2 * n + 1) // 6\n y = n * (n + 1) // 2\n return abs(x - y ** 2)", "def squaresdiff(N):\n k = 0\n j = 0\n for i in range(N):\n k += (i + 1) ** 2\n j += i + 1\n if k > j ** 2:\n return k - j ** 2\n else:\n return j ** 2 - k", "def squaresdiff(N):\n c = 0\n d = 0\n for i in range(1, N + 1, 1):\n c += i ** 2\n d += i\n return abs(c - d ** 2)", "def squaresdiff(n):\n s = 0\n l = 0\n for i in range(1, n + 1):\n l += i\n s += i * i\n return abs(s - l * l)", "def squaresdiff(n):\n s = (1 - n) * (3 * n + 2) * n * (n + 1) // 12\n q = abs(s)\n return q", "def squaresdiff(N):\n ans1 = 0\n ans2 = 0\n for i in range(1, N + 1):\n ans1 = ans1 + i ** 2\n ans2 = ans2 + i\n return abs(ans1 - ans2 ** 2)", "def squaresdiff(N):\n square_num = int(N * (N + 1) * (2 * N + 1) / 6)\n num1 = int(N * (N + 1) / 2)\n num1 = num1 ** 2\n return abs(square_num - num1)", "def squaresdiff(N):\n square_num = 0\n num1 = 0\n for i in range(1, N + 1):\n square_num = square_num + i ** 2\n num1 = num1 + i\n num1 = num1 ** 2\n return abs(square_num - num1)", "from math import *\n\ndef squaresdiff(N):\n a = int(N * (N + 1) * (2 * N + 1) / 6)\n b = int(N * (N + 1) / 2) ** 2\n return abs(a - b)", "def squaresdiff(n):\n sum = 0\n sum1 = 0\n for v in range(n + 1):\n sq = v ** 2\n sum += sq\n for y in range(n + 1):\n sum1 += y\n pr = sum1 ** 2\n a = abs(sum - pr)\n return a", "def squaresdiff(N):\n (v1, v2) = (0, 0)\n for x in range(1, N + 1):\n v1 += x ** 2\n v2 += x\n return abs(v1 - v2 ** 2)", "def squaresdiff(N):\n b = N * (N + 1) // 2\n a = N * (1 + N) * (2 * N + 1) // 6\n return abs(a - b * b)", "def squaresdiff(N):\n s = N * (N + 1) * (2 * N + 1) // 6\n t = (N * (N + 1) // 2) ** 2\n return abs(s - t)", "def squaresdiff(N):\n a1 = N * (N + 1) * (2 * N + 1) // 6\n a2 = (N * (N + 1) // 2) ** 2\n return abs(a1 - a2)", "def squaresdiff(N):\n a1 = 0\n a2 = 0\n for i in range(1, N + 1):\n ans = i * i\n a1 += ans\n a2 += i\n return abs(a1 - a2 * a2)", "def squaresdiff(N):\n sum = 0\n for i in range(1, N + 1):\n sum += i\n res = sum ** 2\n j = N * (N + 1) * (2 * N + 1) // 6\n ans = abs(j - res)\n return ans", "def squaresdiff(N):\n k = 0\n k1 = 0\n while N >= 1:\n k = k + N ** 2\n k1 = k1 + N\n N = N - 1\n d = k - k1 ** 2\n if d > 0:\n return d\n else:\n d = -d\n return d", "def squaresdiff(N):\n squr_of_sum = (N * (N + 1) / 2) ** 2\n sum_of_squrs = N * (N + 1) * (2 * N + 1) / 6\n return abs(int(sum_of_squrs) - int(squr_of_sum))", "def squaresdiff(N):\n s = 0\n sum = 0\n for i in range(1, N + 1):\n s += i\n for j in range(1, N + 1):\n sum += j ** 2\n x = s ** 2\n if x > sum:\n return x - sum\n else:\n return sum - x", "def squaresdiff(n):\n return int(abs(n * (n + 1) * (n - 1) * (3 * n + 2) / 12))", "def squaresdiff(N):\n sq_sum = 0\n sum = 0\n for i in range(N + 1):\n sq_sum += i * i\n sum += i\n sum *= sum\n return abs(sq_sum - sum)", "def squaresdiff(N):\n sq = N * (N + 1) * (2 * N + 1) // 6\n sumn = N * N * (N + 1) * (N + 1) // 4\n return abs(sq - sumn)", "def squaresdiff(N):\n ssq = 0\n s = 0\n for i in range(1, N + 1):\n ssq = ssq + pow(i, 2)\n s = s + i\n a = abs(ssq - s * s)\n return a", "def squaresdiff(N):\n return abs(sum([i ** 2 for i in range(N + 1)]) - sum(range(N + 1)) ** 2)", "def squaresdiff(N):\n squares = int(N * (N + 1) * (2 * N + 1) / 6)\n sum = int(N * (N + 1) / 2)\n return sum ** 2 - squares", "def squaresdiff(N):\n return N * (N + 1) * (3 * N ** 2 - N - 2) // 12", "def squaresdiff(N):\n return abs(N * (2 * N + 1) * (N + 1) // 6 - (N * (N + 1) // 2) ** 2)", "def squaresdiff(n):\n k = n * (n + 1) // 2\n k = k * k\n n = n * (n + 1) * (2 * n + 1) // 6\n return abs(k - n)", "def squaresdiff(N):\n if N in range(10 ** 3 + 1):\n numbers = [i for i in range(1, N + 1)]\n squared_numbers = [i * i for i in range(1, N + 1)]\n diff = abs(sum(squared_numbers) - pow(sum(numbers), 2))\n return diff", "def squaresdiff(N):\n n = N\n l = n * (n + 1) * (2 * n + 1) // 6\n k = n * (n + 1) // 2\n k = k ** 2\n m = abs(l - k)\n return m", "def squaresdiff(N: int) -> int:\n x = y = 0\n for i in range(1, N + 1):\n x += i ** 2\n y += i\n return abs(x - y ** 2)", "def squaresdiff(N):\n return (3 * pow(N, 4) + 2 * pow(N, 3) - 3 * pow(N, 2) - 2 * N) // 12", "def squaresdiff(n):\n sum = 0\n sum1 = 0\n for i in range(1, n + 1):\n sum += i ** 2\n for j in range(1, n + 1):\n sum1 += j\n sum2 = sum1 ** 2\n result = sum - sum2\n return abs(result)", "def squaresdiff(n):\n x = 1\n sum_of_sqr = n * (n + 1) * (2 * n + 1) // 6\n sqr_of_sum = n * (n + 1) // 2\n x = sqr_of_sum * sqr_of_sum\n return abs(sum_of_sqr - x)", "def squaresdiff(N):\n sum_of_squares = 0\n square_of_sum = 0\n for i in range(1, N + 1):\n sum_of_squares += i * i\n square_of_sum += i\n square_of_sum = square_of_sum ** 2\n return square_of_sum - sum_of_squares", "def squaresdiff(N):\n x = N * (N + 1) * (2 * N + 1) // 6 - (N * (N + 1) // 2) ** 2\n if '-' in str(x):\n return -x", "def squaresdiff(n):\n from math import pow\n r = 0\n s = 0\n for i in range(1, n + 1):\n r = r + int(pow(i, 2))\n s = s + i\n k = int(abs(r - int(pow(s, 2))))\n return k", "def squaresdiff(N):\n self.num = N\n n1 = 0\n n2 = 0\n for i in range(1, self.num + 1):\n n1 = n1 + i ** 2\n n2 = n2 + i\n n3 = n2 ** 2\n result = abs(n1 - n3)\n return result", "def squaresdiff(N):\n r1 = (N * (N + 1) // 2) ** 2\n r2 = 0\n for i in range(1, N + 1):\n r2 += i * i\n return abs(r1 - r2)", "def squaresdiff(N):\n n1 = int(N * (N + 1) * (2 * N + 1) / 6)\n n2 = int(N * (N + 1) / 2)\n n3 = n1 - n2 ** 2\n n4 = abs(n3)\n return n4", "def squaresdiff(N):\n l = int(N * (N + 1) * (2 * N + 1) / 6)\n m = int(N * (N + 1) / 2)\n return abs(l - m ** 2)", "def squaresdiff(N):\n sum1 = N * (N + 1) * (2 * N + 1) / 6\n x = N * (N + 1) / 2\n sum2 = x * x\n return int(abs(sum1 - sum2))", "def squaresdiff(N):\n sq = N * (N + 1) * (2 * N + 1) // 6\n p = N * (N + 1) // 2\n return abs(sq - pow(p, 2))"], "starter_code": "def squaresdiff (N):\n", "input_output": {"inputs": ["N = 2", "N = 3"], "outputs": ["4", "22"]}, "difficulty": "EASY", "raw_tags": ["Numbers", "series"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/squares-difference0939/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "squaresdiff", "task_id": "TACO_lite/315", "example": [[[2], [3]], ["4", "22"]]} +{"requirement": "You are given a string S of size N that represents the prefix form of a valid mathematical expression. Convert it to its infix form.\nExample 1:\nInput: \n*-A/BC-/AKL\nOutput: \n((A-(B/C))*((A/K)-L))\nExplanation: \nThe above output is its valid infix form.\nYour Task:\nComplete the function string preToInfix(string pre_exp), which takes a prefix string as input and return its infix form.\n \nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\nConstraints:\n3<=|S|<=10^{4}", "solutions": ["def pretoinfix(pre_exp):\n stk = []\n i = len(pre_exp) - 1\n while i != -1:\n if pre_exp[i] in ['+', '/', '*', '-', '^', '(', ')']:\n op1 = stk.pop()\n op2 = stk.pop()\n stk.append('(' + op1 + prefix[i] + op2 + ')')\n else:\n stk.append(pre_exp[i])\n i -= 1\n return stk.pop()", "def pretoinfix(pre_exp):\n s = []\n for i in pre_exp[::-1]:\n if i.isalpha():\n s.append(i)\n else:\n a = s.pop()\n b = s.pop()\n s.append('(' + a + i + b + ')')\n return s[0]", "def pretoinfix(pre_exp):\n st = []\n for i in range(len(pre_exp) - 1, -1, -1):\n if pre_exp[i].isalnum():\n st.append(pre_exp[i])\n elif len(st) >= 2:\n a = st.pop()\n b = st.pop()\n res = '(' + a + pre_exp[i] + b + ')'\n st.append(res)\n return st[0]", "def pretoinfix(pre_exp):\n result = ''\n prev = ''\n stack = []\n for i in pre_exp[::-1]:\n if i.isalnum():\n stack.append(i)\n else:\n x = stack.pop()\n y = stack.pop()\n prev = '(' + x + i + y + ')'\n stack.append(prev)\n return stack.pop()", "def pretoinfix(pre):\n pre = pre[::-1]\n stack = []\n for i in range(len(pre)):\n if pre[i] == '-' or pre[i] == '+' or pre[i] == '*' or (pre[i] == '/'):\n x = stack.pop()\n y = stack.pop()\n stack.append(')' + y + pre[i] + x + '(')\n else:\n stack.append(pre[i])\n ans = stack[0]\n return ans[::-1]", "def __init__():\n self.stack = []\n self.operatorSet = ('^', '*', '/', '+', '-', '(', ')')\n\ndef isOperator(char):\n return char in self.operatorSet\n\ndef pretoinfix(prefix):\n index = len(prefix) - 1\n while 0 <= index:\n char = prefix[index]\n if not self.isOperator(char):\n self.stack.append(char)\n index -= 1\n else:\n exp = '(' + self.stack.pop() + char + self.stack.pop() + ')'\n self.stack.append(exp)\n index -= 1\n return self.stack.pop()", "def pretoinfix(pre_exp):\n stack = []\n for c in pre_exp:\n if c == '+' or c == '-' or c == '*' or (c == '/'):\n stack.append(c)\n else:\n curr = c\n while len(stack) > 0 and stack[-1] not in ['+', '-', '*', '/']:\n op1 = stack.pop()\n op = stack.pop()\n curr = '(' + op1 + op + curr + ')'\n stack.append(curr)\n return stack[0]", "def pretoinfix(pre_exp):\n stack = []\n n = len(pre_exp)\n for i in range(n - 1, -1, -1):\n if pre_exp[i].isalpha() or pre_exp[i].isdigit():\n stack.append(pre_exp[i])\n else:\n op1 = stack.pop()\n op2 = stack.pop()\n exp = '(' + op1 + pre_exp[i] + op2 + ')'\n stack.append(exp)\n return stack.pop()", "def pretoinfix(exp):\n exp = exp[::-1]\n stack = []\n for i in exp:\n if i >= 'a' and i <= 'z' or (i >= 'A' and i <= 'Z') or (i >= '0' and i <= '9'):\n stack.append(i)\n else:\n stack.append('(' + stack.pop() + i + stack.pop() + ')')\n return stack.pop()", "def pretoinfix(pre_exp):\n a = pre_exp[::-1]\n l = []\n for j in a:\n if j.isalpha():\n l.append(j)\n else:\n a = l.pop()\n b = l.pop()\n l.append('(' + a + j + b + ')')\n return l[0]", "def pretoinfix(pre):\n operator = ['+', '-', '*', '/', '^']\n i = len(pre) - 1\n stack = []\n while i >= 0:\n if pre[i] not in operator:\n stack.append(pre[i])\n if pre[i] in operator:\n exp = '(' + stack.pop() + pre[i] + stack.pop() + ')'\n stack.append(exp)\n i -= 1\n return stack.pop()", "def pretoinfix(pre_exp):\n count = 0\n stack = []\n for ele in pre_exp[::-1]:\n if ele in ['^', '*', '/', '+', '-']:\n op1 = stack.pop()\n op2 = stack.pop()\n stack.append('(' + op1 + ele + op2 + ')')\n else:\n stack.append(ele)\n return stack.pop()", "def __init__():\n self.stack = []\n\ndef push(el):\n self.stack.append(el)\n\ndef pop():\n return self.stack.pop()\n\ndef pretoinfix(exp):\n exp_rev = exp[::-1]\n for i in exp_rev:\n if i in ['^', '+', '-', '*', '/']:\n exp2 = '('\n exp2 += self.pop()\n exp2 += i\n exp2 += self.pop()\n exp2 += ')'\n self.push(exp2)\n else:\n self.push(i)\n return exp2", "def pretoinfix(pre_exp):\n s1 = []\n s2 = []\n for i in range(len(pre_exp)):\n s1.append(pre_exp[i])\n while len(s1) != 0:\n a = s1.pop()\n if len(a) > 1 or (ord(a) >= ord('A') and ord(a) <= ord('Z')) or (ord(a) >= ord('a') and ord(a) <= ord('z')):\n s2.append(a)\n continue\n if a in '*-/+^':\n op1 = s2.pop()\n op2 = s2.pop()\n exp = '(' + op1 + a + op2 + ')'\n s2.append(exp)\n return s2[0]", "def pretoinfix(pre_exp):\n n = len(pre_exp) - 1\n st = []\n for i in range(n, -1, -1):\n ch = pre_exp[i]\n if ch in '^/*+-':\n A = st.pop()\n B = st.pop()\n exp = '(' + A + ch + B + ')'\n st.append(exp)\n else:\n st.append(ch)\n return st[-1]", "def pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n stack = []\n for c in pre_exp:\n if c.isalpha():\n stack.append(c)\n else:\n ex = '(' + stack.pop() + c + stack.pop() + ')'\n stack.append(ex)\n return stack[0]", "def pretoinfix(pre_exp):\n stack = []\n for i in range(len(pre_exp) - 1, -1, -1):\n if pre_exp[i] in ['+', '-', '*', '/']:\n s = '('\n s += stack.pop()\n s += pre_exp[i]\n s += stack.pop()\n s += ')'\n stack.append(s)\n else:\n stack.append(pre_exp[i])\n return stack[-1]", "def pretoinfix(pre_exp):\n stack = []\n op = '^*/+-'\n for i in pre_exp[-1::-1]:\n if i not in op:\n stack.append(i)\n if i in op:\n exp = '(' + stack.pop() + i + stack.pop() + ')'\n stack.append(exp)\n return stack[0]", "def isOperator(c):\n if c == '*' or c == '+' or c == '-' or (c == '/') or (c == '^') or (c == '(') or (c == ')'):\n return True\n else:\n return False\n\ndef pretoinfix(pref_ix):\n stack = []\n i = len(pref_ix) - 1\n while i >= 0:\n if not self.isOperator(pref_ix[i]):\n stack.append(pref_ix[i])\n i -= 1\n else:\n prefix = '(' + stack.pop() + pref_ix[i] + stack.pop() + ')'\n stack.append(prefix)\n i -= 1\n return stack.pop()", "def pretoinfix(pre_exp):\n lst = list(pre_exp)\n lst.reverse()\n infix = []\n stack = []\n for val in lst:\n if val in ['+', '-', '*', '/', '^']:\n if stack:\n one = stack.pop()\n second = stack.pop()\n stack.append('(' + one + val + second + ')')\n else:\n stack.append(val)\n return stack.pop()", "def pretoinfix(pre_exp):\n operators = ['^', '*', '/', '+', '-']\n operaAndBraces = ['^', '*', '/', '+', '-', '(', ')']\n stk = []\n for i in reversed(range(len(pre_exp))):\n elem = pre_exp[i]\n if elem not in operaAndBraces:\n stk.append(elem)\n else:\n str = '(' + stk.pop() + elem + stk.pop() + ')'\n stk.append(str)\n return stk.pop()", "def pretoinfix(s):\n (i, l) = (0, len(s))\n stack = []\n while i < l:\n if len(stack) >= 3 and stack[-3] in '/+-*' and (stack[-1] not in '/+-*') and (stack[-2] not in '/+-*'):\n while len(stack) >= 3 and stack[-3] in '/+-*' and (stack[-1] not in '/+-*') and (stack[-2] not in '/+-*'):\n b = stack.pop()\n a = stack.pop()\n stack.append('(' + a + stack.pop() + b + ')')\n stack.append(s[i])\n i += 1\n while len(stack) >= 3 and stack[-3] in '/+-*' and (stack[-1] not in '/+-*') and (stack[-2] not in '/+-*'):\n b = stack.pop()\n a = stack.pop()\n stack.append('(' + a + stack.pop() + b + ')')\n return stack[-1]", "def pretoinfix(pre_exp):\n stack = []\n for ch in pre_exp[::-1]:\n if ch.isalnum():\n stack.append(ch)\n else:\n stack.append('(' + stack.pop() + ch + stack.pop() + ')')\n return stack.pop()", "def pretoinfix(pre_exp):\n stack = []\n for v in pre_exp[::-1]:\n if v.isalnum():\n stack.append(v)\n else:\n stack.append('(' + stack.pop() + v + stack.pop() + ')')\n return stack[0]", "def pretoinfix(pre_exp):\n stack = []\n top = -1\n infix = ''\n for v in pre_exp[::-1]:\n if v.isdigit() or v.isalnum():\n stack.append(v)\n top += 1\n else:\n A = stack.pop()\n B = stack.pop()\n infix = '(' + A + v + B + ')'\n stack.append(infix)\n top -= 1\n return infix", "def pretoinfix(pre):\n ops = {'+', '-', '/', '*'}\n pre = pre[::-1]\n stack = []\n for i in range(len(pre)):\n if pre[i] in ops:\n a = stack.pop()\n stack.pop()\n b = stack.pop()\n stack.append('(' + a + pre[i] + b + ')')\n else:\n stack.append('(')\n stack.append(pre[i])\n stack = stack[1]\n return stack", "def pretoinfix(pre_exp):\n lis = []\n for i in pre_exp[::-1]:\n if i.isalpha():\n lis.append(i)\n else:\n z = lis.pop()\n y = lis.pop()\n lis.append('(' + z + i + y + ')')\n return lis[0]", "def evalu(exp, left, right):\n return '(' + left + exp + right + ')'\n\ndef __init__():\n self.stack = []\n\ndef pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n for i in pre_exp:\n if i is '+':\n left = self.stack.pop()\n right = self.stack.pop()\n val = evalu('+', left, right)\n self.stack.append(val)\n elif i is '-':\n left = self.stack.pop()\n right = self.stack.pop()\n val = evalu('-', left, right)\n self.stack.append(val)\n elif i is '*':\n left = self.stack.pop()\n right = self.stack.pop()\n val = evalu('*', left, right)\n self.stack.append(val)\n elif i is '/':\n left = self.stack.pop()\n right = self.stack.pop()\n val = evalu('/', left, right)\n self.stack.append(val)\n else:\n self.stack.append(i)\n return self.stack.pop()", "def pretoinfix(pre_exp):\n stack = []\n for idx in range(len(pre_exp) - 1, -1, -1):\n char = pre_exp[idx]\n if char in Solution.precedence:\n op1 = stack.pop()\n op2 = stack.pop()\n res = '(' + op1 + char + op2 + ')'\n stack.append(res)\n else:\n stack.append(char)\n res = stack[-1]\n return res", "def pretoinfix(pre_exp):\n stack = []\n operators = set(['+', '-', '*', '/', '^'])\n for i in range(len(pre_exp) - 1, -1, -1):\n if pre_exp[i] in operators:\n operand1 = stack.pop()\n operand2 = stack.pop()\n exp = '(' + operand1 + pre_exp[i] + operand2 + ')'\n stack.append(exp)\n else:\n stack.append(pre_exp[i])\n return stack.pop()", "def pretoinfix(pre_exp):\n l = ['+', '-', '*', '/', '^']\n s = []\n pre_exp = pre_exp[::-1]\n for i in pre_exp:\n if i in l:\n a = s.pop()\n b = s.pop()\n c = '(' + a + i + b + ')'\n s.append(c)\n else:\n s.append(i)\n return ''.join((i for i in s))", "def pretoinfix(pre_exp):\n (res, stack) = ([], [])\n for i in pre_exp:\n if ord('A') <= ord(i) <= ord('Z') or ord('a') <= ord(i) <= ord('z'):\n res.append(i)\n while stack and stack[-1] == '(':\n res.append(')')\n stack.pop()\n if stack:\n res.append(stack.pop())\n else:\n res.append('(')\n stack.append('(')\n stack.append(i)\n return ''.join(res)", "def pretoinfix(pre_exp):\n exp = pre_exp[::-1]\n stack = []\n for i in range(len(exp)):\n if exp[i] >= 'a' and exp[i] <= 'z' or (exp[i] >= 'A' and exp[i] <= 'Z'):\n stack.append(exp[i])\n else:\n a = stack.pop()\n b = stack.pop()\n res = '(' + a + exp[i] + b + ')'\n stack.append(res)\n return stack[0]", "def pretoinfix(arr):\n stack = []\n for i in range(len(arr) - 1, -1, -1):\n if self.isChr(arr[i]):\n stack.append(arr[i])\n if self.isOpr(arr[i]):\n first = stack.pop()\n secnd = stack.pop()\n res = '(' + first + arr[i] + secnd + ')'\n stack.append(res)\n return stack.pop()\n\ndef isChr(ch):\n if ch >= 'a' and ch <= 'z' or (ch >= 'A' and ch <= 'Z') or (ch >= '0' and ch <= '9'):\n return 1\n return 0\n\ndef isOpr(ch):\n opr = ['+', '-', '*', '/', '^']\n if ch in opr:\n return 1\n return 0", "def pretoinfix(pre_exp):\n stack = []\n s = ''\n for i in pre_exp[::-1]:\n s = ''\n if i not in '^*?()+-/':\n stack.append(i)\n else:\n p = ''\n q = ''\n if stack:\n p = stack.pop()\n if stack:\n q = stack.pop()\n if p or q:\n s = s + '(' + p + i + q + ')'\n else:\n s = s + p + i + q\n stack.append(s)\n return s", "def pretoinfix(pre_exp):\n stack = []\n exp = pre_exp[::-1]\n for i in exp:\n if i in '^*/+-':\n temp = '(' + stack.pop() + i + stack.pop() + ')'\n stack.append(temp)\n else:\n stack.append(i)\n return stack[-1]", "def pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n st = []\n for i in pre_exp:\n if i in '*+-/^':\n if len(st) >= 2:\n second = st.pop()\n first = st.pop()\n st.append(')' + first + i + second + '(')\n else:\n st.append(i)\n return st.pop()[::-1]", "def pretoinfix(pre_exp):\n stack = []\n operators = set(['+', '-', '*', '/', '^'])\n for i in range(len(pre_exp) - 1, -1, -1):\n if pre_exp[i] in operators:\n op1 = stack.pop()\n op2 = stack.pop()\n exp = '(' + op1 + pre_exp[i] + op2 + ')'\n stack.append(exp)\n else:\n stack.append(pre_exp[i])\n return stack.pop()", "def pretoinfix(pre_exp):\n ll = []\n for i in range(len(pre_exp) - 1, -1, -1):\n if pre_exp[i] in '*-/+':\n l = ll.pop(-1)\n r = ll.pop(-1)\n dat = '(' + l + pre_exp[i] + r + ')'\n ll.append(dat)\n else:\n ll.append(pre_exp[i])\n return ll[0]", "def pretoinfix(pre_exp):\n st = []\n for i in pre_exp[::-1]:\n if i.isalnum():\n st.append(i)\n else:\n o1 = st.pop()\n o2 = st.pop()\n inf = '(' + o1 + i + o2 + ')'\n st.append(inf)\n return st.pop()", "def pretoinfix(pre_exp):\n stack = []\n operators = set(['+', '-', '*', '/', '^'])\n for i in pre_exp[::-1]:\n if i in operators:\n op1 = stack.pop()\n op2 = stack.pop()\n stack.append('({}{}{})'.format(op1, i, op2))\n else:\n stack.append(i)\n return stack[-1]", "def is_operator(c):\n if c == '+' or c == '-' or c == '*' or (c == '/') or (c == '^'):\n return True\n else:\n return False\n\ndef pretoinfix(exp):\n exp = exp[::-1]\n stack = []\n for c in exp:\n if self.is_operator(c):\n op1 = stack.pop()\n op2 = stack.pop()\n stack.append('(' + op1 + c + op2 + ')')\n else:\n stack.append(c)\n return stack.pop()", "def pretoinfix(pre_exp):\n stack = []\n i = len(pre_exp) - 1\n list = ['+', '-', '*', '/', '^']\n str = ''\n while i >= 0:\n if pre_exp[i] not in list:\n stack.append(pre_exp[i])\n i -= 1\n else:\n str = '(' + stack.pop() + pre_exp[i] + stack.pop() + ')'\n stack.append(str)\n i -= 1\n temp = stack.pop()\n return temp", "def pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n stack = []\n for i in pre_exp:\n if i.isalpha():\n stack.append(i)\n else:\n exp = i\n two = stack.pop()\n one = stack.pop()\n new = ')' + one + i + two + '('\n stack.append(new)\n return stack[0][::-1]", "def pretoinfix(pre_exp):\n s = []\n for i in pre_exp[::-1]:\n if i in ['*', '+', '-', '/']:\n t1 = s.pop()\n t2 = s.pop()\n s.append('(' + t1 + i + t2 + ')')\n else:\n s.append(i)\n return ''.join(s)", "def pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n a = []\n res = ''\n for i in range(len(pre_exp)):\n if pre_exp[i].isalpha():\n a.append(pre_exp[i])\n else:\n first = a.pop()\n second = a.pop()\n res = '(' + first + pre_exp[i] + second + ')'\n a.append(res)\n return a[-1]", "def pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n stack = []\n res = ''\n for i in range(len(pre_exp)):\n if pre_exp[i].isalpha():\n stack.append(pre_exp[i])\n else:\n first = stack.pop()\n sec = stack.pop()\n res = '(' + first + pre_exp[i] + sec + ')'\n stack.append(res)\n ans = stack[-1]\n return ans", "def pretoinfix(pre_exp):\n prefix = list(pre_exp)\n prefix.reverse()\n stack = []\n str = ''\n for i in range(len(prefix)):\n if prefix[i] not in {'+', '*', '-', '/'}:\n stack.append(prefix[i])\n else:\n if stack:\n op1 = stack.pop()\n if stack:\n op2 = stack.pop()\n str += '(' + op1 + prefix[i] + op2 + ')'\n stack.append(str)\n str = ''\n return stack[-1]", "def pretoinfix(s1):\n str = ''\n st = []\n for i in range(len(s1) - 1, -1, -1):\n if s1[i].isalpha():\n st.append(s1[i])\n else:\n str1 = st.pop()\n str2 = st.pop()\n str = '(' + str1 + s1[i] + str2 + ')'\n st.append(str)\n str = st.pop()\n return str", "def is_operand(x):\n return ord(x) >= ord('a') and ord(x) <= ord('z') or (ord(x) >= ord('A') and ord(x) <= ord('Z'))\n\ndef pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n st = []\n for i in pre_exp:\n if is_operand(i):\n st.append(i)\n else:\n if len(st) < 2:\n raise Exception('invalid Expression')\n s1 = st.pop()\n s2 = st.pop()\n cur = '(' + s1 + i + s2 + ')'\n st.append(cur)\n return ''.join(st)", "def pretoinfix(pre_exp):\n precedence = {'^': 3, '+': 1, '-': 1, '*': 2, '/': 2}\n st = []\n s = ''\n for i in pre_exp[::-1]:\n if i in precedence.keys():\n x = st.pop()\n y = st.pop()\n st.append('(' + x + i + y + ')')\n else:\n st.append(i)\n string = ''.join(st)\n return string", "def pretoinfix(pre_exp):\n stack = []\n for i in range(len(pre_exp) - 1, -1, -1):\n char = pre_exp[i]\n if char.isalnum():\n stack.append(char)\n elif char in '+-*/^':\n if len(stack) < 2:\n return 'Invalid expression'\n op1 = stack.pop()\n op2 = stack.pop()\n subexp = '(' + op1 + char + op2 + ')'\n stack.append(subexp)\n else:\n return 'Invalid expression'\n if len(stack) != 1:\n return 'Invalid expression'\n return stack.pop()", "from collections import deque\n\ndef pretoinfix(pre_exp):\n stack = deque()\n for i in range(len(pre_exp) - 1, -1, -1):\n if pre_exp[i].isalpha():\n stack.append(pre_exp[i])\n else:\n expr1 = stack.pop()\n expr2 = stack.pop()\n new_expr = '(' + expr1 + pre_exp[i] + expr2 + ')'\n stack.append(new_expr)\n return stack.pop()", "def __init__():\n self.l = []\n\ndef push(element):\n self.l.append(element)\n\ndef pop():\n return self.l.pop()\n\ndef pretoinfix(pre_exp):\n for i in reversed(pre_exp):\n if i == '+':\n a = self.pop()\n b = self.pop()\n self.push('(' + a + '+' + b + ')')\n elif i == '-':\n a = self.pop()\n b = self.pop()\n self.push('(' + a + '-' + b + ')')\n elif i == '*':\n a = self.pop()\n b = self.pop()\n self.push('(' + a + '*' + b + ')')\n elif i == '/':\n a = self.pop()\n b = self.pop()\n self.push('(' + a + '/' + b + ')')\n else:\n self.push(i)\n ss = ''\n for i in self.l:\n ss = ss + '' + i\n return ss", "def pretoinfix(ex):\n s = []\n ex = ex[::-1]\n for ch in ex:\n if ch.isalnum():\n s += ch\n else:\n o = ''\n o = '(' + s[-1] + ch + s[-2] + ')'\n s.pop()\n s.pop()\n s.append(o)\n return o", "from collections import deque\n\ndef pretoinfix(pre_exp):\n operators = {'*', '-', '^', '/', '+', '%'}\n stack = deque()\n exp = pre_exp\n for i in range(len(exp) - 1, -1, -1):\n symbol = exp[i]\n if symbol in operators:\n subexpr = '(' + str(stack.pop()) + str(symbol) + str(stack.pop()) + ')'\n stack.append(subexpr)\n else:\n stack.append(symbol)\n return stack.pop()", "def pretoinfix(string):\n stack = []\n operators = ['-', '/', '+', '*']\n reversed_string = string[::-1]\n for char in reversed_string:\n if char not in operators:\n stack.append(char)\n else:\n popped_first_char = stack.pop()\n new_char_str = ''\n popped_second_char = stack.pop()\n new_char_str = '(' + new_char_str + popped_first_char + char + popped_second_char + ')'\n stack.append(new_char_str)\n return stack[0]", "def pretoinfix(exp):\n exp = exp[::-1]\n stack = []\n ans = ''\n for ch in exp:\n if ch.isalnum():\n stack.append(ch)\n else:\n first = stack.pop()\n second = stack.pop()\n stack.append('(' + first + ch + second + ')')\n return stack[-1]", "def isOperator(c):\n if c == '+' or c == '-' or c == '*' or (c == '/') or (c == '^'):\n return True\n else:\n return False\n\ndef pretoinfix(pre_exp):\n stack = []\n n = len(pre_exp)\n for i in range(n - 1, -1, -1):\n c = pre_exp[i]\n if isOperator(c):\n op1 = stack.pop()\n op2 = stack.pop()\n stack.append('(' + op1 + c + op2 + ')')\n else:\n stack.append(c)\n return stack[0]", "def pretoinfix(pre_exp):\n res = []\n ans = ''\n for i in pre_exp[::-1]:\n if i.isalpha() or i.isnumeric():\n res.append(i)\n else:\n a1 = res.pop()\n a2 = res.pop()\n ans = '(' + a1 + i + a2 + ')'\n res.append(ans)\n return ans", "def isOp(c):\n if c == '*' or c == '+' or c == '-' or (c == '/') or (c == '^') or (c == '(') or (c == ')'):\n return True\n else:\n return False\n\ndef pretoinfix(pre_exp):\n stack = []\n i = len(pre_exp) - 1\n while i >= 0:\n if not self.isOp(pre_exp[i]):\n stack.append(pre_exp[i])\n i -= 1\n else:\n str = '(' + stack.pop() + pre_exp[i] + stack.pop() + ')'\n stack.append(str)\n i -= 1\n return stack.pop()", "def pretoinfix(pre_exp):\n st = []\n s = ''\n l = len(pre_exp)\n for i in range(-1, -l - 1, -1):\n if pre_exp[i] == '*' or pre_exp[i] == '/' or pre_exp[i] == '+' or (pre_exp[i] == '-'):\n n1 = st.pop()\n n2 = st.pop()\n st.append('@' + n1 + pre_exp[i] + n2 + '#')\n else:\n st.append(pre_exp[i])\n pre = st[0]\n pre = pre.replace('@', '(')\n pre = pre.replace('#', ')')\n res = pre\n return res", "def pretoinfix(pre):\n stack = []\n for i in range(len(pre) - 1, 0, -1):\n if pre[i].isalpha():\n stack.append(pre[i])\n else:\n first = stack.pop()\n second = stack.pop()\n op = '(' + first + pre[i] + second + ')'\n stack.append(op)\n res = '(' + stack.pop() + pre[0] + stack.pop() + ')'\n return res", "def pretoinfix(pre_exp):\n Operators = ['+', '-', '*', '/', '(', ')', '^']\n pre_exp = pre_exp[::-1]\n stack = []\n for character in pre_exp:\n if character not in Operators:\n stack.append(character)\n else:\n res = ''\n res += '('\n A = stack.pop()\n B = stack.pop()\n res += A\n res += character\n res += B\n res += ')'\n stack.append(res)\n return stack.pop()", "def pretoinfix(pre_exp):\n stack = []\n substr = ''\n exp = ''\n operators = ['+', '^', '%', '-', '*', '/']\n for i in range(len(pre_exp) - 1, -1, -1):\n ele = pre_exp[i]\n if ele in operators:\n stack.append('(' + stack.pop() + ele + stack.pop() + ')')\n else:\n stack.append(ele)\n return stack.pop()", "def pretoinfix(s):\n\n def isOperator(x):\n return ch in '+-*/^%'\n stack = []\n n = len(s)\n for i in range(n - 1, -1, -1):\n ch = s[i]\n if isOperator(ch):\n op1 = stack.pop()\n op2 = stack.pop()\n temp = '(' + op1 + ch + op2 + ')'\n stack.append(temp)\n else:\n stack.append(ch)\n return stack.pop()", "def is_operand(i):\n return i.isalpha()\n\ndef pretoinfix(pre_exp):\n (s, n) = (pre_exp, len(pre_exp))\n stack = []\n for i in range(n - 1, -1, -1):\n if is_operand(s[i]):\n stack.append(s[i])\n else:\n a = stack.pop()\n b = stack.pop()\n c = '(' + a + s[i] + b + ')'\n stack.append(c)\n return stack[-1]", "def pretoinfix(exp):\n st = []\n exp = exp[::-1]\n for ch in exp:\n if ch in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmonpqrstuvwxyz':\n st += [ch]\n else:\n tmp = '(' + st[-1] + ch + st[-2] + ')'\n st.pop()\n st.pop()\n st.append(tmp)\n return st.pop()", "def __init__():\n self.top = -1\n self.array = []\n\ndef isEmpty():\n return True if self.top == -1 else False\n\ndef pop():\n if not self.isEmpty():\n self.top -= 1\n return self.array.pop()\n else:\n return '$'\n\ndef push(op):\n self.top += 1\n self.array.append(op)\n\ndef isOperand(ch):\n return ch.isalpha()\n\ndef pretoinfix(exp):\n i = len(exp) - 1\n while i >= 0:\n if self.isOperand(exp[i]):\n self.push(exp[i])\n else:\n str = '(' + self.pop() + exp[i] + self.pop() + ')'\n self.push(str)\n i -= 1\n return self.pop()", "def pretoinfix(pre_exp):\n pre_exp = list(pre_exp)\n while len(pre_exp) != 1:\n for x in range(len(pre_exp) - 3, -1, -1):\n sym = pre_exp[x]\n if not sym.isalnum() and len(sym) == 1:\n pre_exp[x] = '(' + pre_exp[x + 1] + pre_exp[x] + pre_exp[x + 2] + ')'\n del pre_exp[x + 1]\n del pre_exp[x + 1]\n return pre_exp[0]", "def pretoinfix(pre_exp):\n pre_exp = pre_exp[::-1]\n st = []\n operators = set(['-', '+', '*', '/', '^'])\n for i in range(len(pre_exp)):\n if pre_exp[i] in operators:\n operand1 = st.pop()\n operand2 = st.pop()\n new_exp = '(' + operand1 + pre_exp[i] + operand2 + ')'\n st.append(new_exp)\n else:\n st.append(pre_exp[i])\n return st.pop()", "def pretoinfix(pre_exp):\n operators = ['+', '-', '*', '/', '^']\n pre_exp = pre_exp[::-1]\n stack = []\n for c in pre_exp:\n if c not in operators:\n stack.append(c)\n else:\n exp = '(' + stack.pop() + c + stack.pop() + ')'\n stack.append(exp)\n return stack[-1]"], "starter_code": "def pretoinfix(pre_exp):\n", "input_output": {"inputs": ["*-A/BC-/AKL"], "outputs": ["((A-(B/C))*((A/K)-L))"]}, "difficulty": "MEDIUM", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/prefix-to-infix-conversion/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "pretoinfix", "task_id": "TACO_lite/221", "example": [[], []]} +{"requirement": "Given a sorted linked list of distinct nodes (no two nodes have the same data) and an integer X. Count distinct triplets in the list that sum up to given integer X.\nNote: The Linked List can be sorted in any order.\nExample 1:\nInput: LinkedList: 1->2->4->5->6->8->9, X = 17\nOutput: 2\nExplanation: Distinct triplets are (2, 6, 9) \nand (4, 5, 8) which have sum equal to X i.e 17.\nExample 2:\nInput: LinkedList: 1->2->4->5->6->8->9, X = 15\nOutput: 5\nExplanation: (1, 5, 9), (1, 6, 8), (2, 4, 9), \n(2, 5, 8), (4, 5, 6) are the distinct triplets\nYour Task: \nYou don't need to read input or print anything. Complete the function countTriplets() which takes a head reference and X as input parameters and returns the triplet count\nExpected Time Complexity: O(N^{2})\nExpected Auxiliary Space: O(N)\nConstraints:\n1 \u2264 Number of Nodes \u2264 10^{3} \n1 \u2264 Node value \u2264 10^{4}", "solutions": ["def counttriplets(head, x):\n if head == None:\n return\n temp1 = head\n answer = []\n while temp1:\n hashmap = {}\n temp2 = temp1.nxt\n while temp2:\n value = x - (temp1.val + temp2.val)\n if value in hashmap:\n answer.append([temp1.val, temp2.val, value])\n else:\n hashmap[temp2.val] = 1\n temp2 = temp2.nxt\n temp1 = temp1.nxt\n return len(answer)", "def counttriplets(head, x):\n arr = []\n while head:\n arr.append(head.val)\n head = head.nxt\n count = 0\n d = {}\n for i in range(len(arr)):\n d[arr[i]] = i\n for i in range(len(arr)):\n for j in range(i + 1, len(arr)):\n k = x - (arr[i] + arr[j])\n if k in d and d[k] != i and (d[k] != j):\n count += 1\n return count // 3", "def counttriplets(head, x):\n h1 = head\n count = 0\n while h1:\n m = {}\n h2 = h1.nxt\n while h2:\n value = x - (h1.val + h2.val)\n if value in m:\n count += 1\n else:\n m[h2.val] = 1\n h2 = h2.nxt\n h1 = h1.nxt\n return count", "def counttriplets(head, x):\n curr1 = head\n answer = []\n while curr1:\n hashmap = {}\n curr2 = curr1.nxt\n while curr2:\n value = x - (curr1.val + curr2.val)\n if value in hashmap:\n answer.append([curr1.val, curr2.val, value])\n else:\n hashmap[curr2.val] = 1\n curr2 = curr2.nxt\n curr1 = curr1.nxt\n return len(answer)", "def counttriplets(head, x):\n temp = head\n c = 0\n while temp.nxt.nxt:\n s = set()\n f = temp.val\n s.add(temp.nxt.val)\n k = temp.nxt.nxt\n while k:\n if x - (k.val + f) in s:\n c += 1\n else:\n s.add(k.val)\n k = k.nxt\n temp = temp.nxt\n return c", "def counttriplets(head, x):\n l = []\n temp = head\n while temp != None:\n l.append(temp.val)\n temp = temp.nxt\n n = len(l)\n l.sort()\n c = 0\n for i in range(n - 2):\n le = i + 1\n r = n - 1\n while le < r:\n s = l[i] + l[le] + l[r]\n if s == x:\n c += 1\n le += 1\n r -= 1\n elif s < x:\n le = le + 1\n else:\n r = r - 1\n return c", "def counttriplets(head, x):\n curr = head\n l = []\n ans = 0\n while curr:\n l.append(curr.val)\n curr = curr.nxt\n l.sort()\n n = len(l)\n for i in range(n - 2):\n m = i + 1\n r = n - 1\n while m < r:\n if l[i] + l[m] + l[r] == x:\n ans += 1\n m += 1\n r = r - 1\n elif l[i] + l[m] + l[r] > x:\n r -= 1\n else:\n m += 1\n return ans", "def counttriplets(head, x):\n lst = []\n itr = head\n while itr:\n lst.append(itr.val)\n itr = itr.nxt\n count = 0\n for i in range(len(lst)):\n l = i + 1\n r = len(lst) - 1\n while l < r:\n if lst[i] < lst[l]:\n if lst[i] + lst[l] + lst[r] == x:\n count += 1\n l += 1\n r -= 1\n elif lst[i] + lst[l] + lst[r] > x:\n r -= 1\n else:\n l += 1\n elif lst[i] + lst[l] + lst[r] == x:\n count += 1\n l += 1\n r -= 1\n elif lst[i] + lst[l] + lst[r] < x:\n r -= 1\n else:\n l += 1\n return count", "def counttriplets(head, x):\n dic = {}\n tt = head\n while tt:\n dic[tt.val] = tt\n tt = tt.nxt\n c = 0\n temp = head\n while temp:\n tmp = temp.nxt\n while tmp:\n s = temp.val + tmp.val\n if x - s in dic and dic[x - s] != temp and (dic[x - s] != tmp):\n c += 1\n tmp = tmp.nxt\n temp = temp.nxt\n return c // 3", "def counttriplets(head, x):\n dicti = {}\n z = head\n kk = 0\n p = 0\n while z != None:\n dicti[z.val] = p\n p = p + 1\n z = z.nxt\n p1 = head\n p2 = head.nxt\n while p1 != None:\n while p2 != None:\n u = x - p1.val - p2.val\n if u in dicti.keys() and u != p1.val and (u != p2.val) and (dicti[u] > dicti[p1.val]) and (dicti[u] > dicti[p2.val]):\n kk = kk + 1\n p2 = p2.nxt\n p1 = p1.nxt\n if p1.nxt == None:\n break\n p2 = p1.nxt\n return kk", "def counttriplets(head, x):\n z = []\n while head is not None:\n z.append(head.val)\n head = head.nxt\n c = 0\n z.sort()\n k = len(z)\n for i in range(k - 2):\n l = i + 1\n h = k - 1\n while l < h:\n if z[i] + z[l] + z[h] == x:\n c = c + 1\n l = l + 1\n h = h - 1\n elif z[i] + z[l] + z[h] < x:\n l = l + 1\n else:\n h = h - 1\n return c", "def counttriplets(head, x):\n values = []\n while head is not None:\n values.append(head.val)\n head = head.nxt\n count = 0\n values.sort()\n n = len(values)\n for i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n if values[i] + values[j] + values[k] == x:\n count += 1\n j += 1\n k -= 1\n elif values[i] + values[j] + values[k] < x:\n j += 1\n else:\n k -= 1\n return count", "def counttriplets(head, x):\n if not head or not head.nxt:\n return 0\n count = 0\n arr = []\n curr = head\n while curr:\n arr.append(curr.val)\n curr = curr.nxt\n n = len(arr)\n arr.sort()\n for start in range(n - 2):\n mid = start + 1\n end = n - 1\n while mid < end:\n Sum = arr[start] + arr[mid] + arr[end]\n if Sum == x:\n count += 1\n mid += 1\n end -= 1\n elif Sum > x:\n end -= 1\n else:\n mid += 1\n return count", "def counttriplets(head, X):\n l = []\n while head:\n l.append(head.val)\n head = head.nxt\n l.sort()\n n = len(l)\n ans = 0\n for i in range(n):\n req = X - l[i]\n (x, y) = (i + 1, n - 1)\n while x < y:\n if l[x] + l[y] == req:\n ans += 1\n x += 1\n y -= 1\n elif l[x] + l[y] > req:\n y -= 1\n else:\n x += 1\n return ans", "def counttriplets(head, x):\n l = []\n while head:\n l.append(head.val)\n head = head.nxt\n l.sort()\n ans = 0\n n = len(l)\n for i in range(n):\n t = x - l[i]\n left = i + 1\n right = n - 1\n while left < right:\n current = l[left] + l[right]\n if current < t:\n left += 1\n elif current > t:\n right -= 1\n else:\n ans += 1\n left += 1\n return ans", "def counttriplets(head, x):\n P = []\n while head:\n P.append(head.val)\n head = head.nxt\n P.sort()\n count = 0\n for i in range(len(P) - 2):\n j = i + 1\n k = n - 1\n while j < k:\n S = P[i] + P[j] + P[k]\n if S > x:\n k -= 1\n elif S < x:\n j += 1\n else:\n count += 1\n j += 1\n k -= 1\n return count", "def counttriplets(head, x):\n count = 0\n while head.nxt != None:\n d = {}\n temp = head.nxt\n while temp != None:\n if x - (temp.val + head.val) in d.keys():\n count += 1\n else:\n d[temp.val] = 1\n temp = temp.nxt\n head = head.nxt\n return count", "def counttriplets(head, x):\n arr = []\n curr = head\n while curr:\n arr.append(curr.val)\n curr = curr.nxt\n ans = 0\n arr.sort()\n for i in range(len(arr)):\n low = i + 1\n high = len(arr) - 1\n while low < high:\n if arr[i] + arr[low] + arr[high] == x:\n ans += 1\n low += 1\n elif arr[i] + arr[low] + arr[high] < x:\n low += 1\n else:\n high -= 1\n return ans", "def counttriplets(start, x):\n temp = start\n l = []\n while temp:\n l.append(temp.val)\n temp = temp.nxt\n l.sort()\n c = 0\n for i in range(0, n - 2):\n j = i + 1\n k = len(l) - 1\n while j < k:\n if l[i] + l[j] + l[k] == x:\n c += 1\n j += 1\n k -= 1\n elif l[i] + l[j] + l[k] > x:\n k -= 1\n else:\n j += 1\n return c", "def counttriplets(start, x):\n arr = []\n temp = start\n while temp:\n arr.append(temp.val)\n temp = temp.nxt\n result = 0\n arr.sort()\n for i in range(len(arr) - 2):\n j = i + 1\n k = len(arr) - 1\n while j < k:\n if arr[i] + arr[j] + arr[k] < x:\n j += 1\n elif arr[i] + arr[j] + arr[k] > x:\n k -= 1\n else:\n result += 1\n j += 1\n return result", "def counttriplets(head, x):\n if not head:\n return\n prev = None\n cur = head\n while cur:\n nxt = cur.nxt\n cur.prev = prev\n prev = cur\n cur = nxt\n tail = prev\n count = 0\n cur = head\n while cur.nxt:\n diff = x - cur.val\n start = cur.nxt\n end = tail\n while start and end and (start != end):\n if start.val + end.val == diff:\n count += 1\n end = end.prev\n elif start.val + end.val < diff:\n end = end.prev\n elif start.val + end.val > diff:\n start = start.nxt\n cur = cur.nxt\n return count\n\ndef __init__(x):\n self.val = x\n self.nxt = None\n self.prev = None", "def counttriplets(head, x):\n lis = []\n itr = head\n while itr:\n lis.append(itr.val)\n itr = itr.nxt\n dic = {}\n for i in lis:\n if i in dic:\n dic[i] += 1\n else:\n dic[i] = 1\n lis.sort()\n ans = 0\n for i in range(len(lis) - 2):\n m = i + 1\n r = len(lis) - 1\n while m < r:\n if lis[i] + lis[m] + lis[r] == x:\n ans += 1\n m += 1\n r -= 1\n elif lis[i] + lis[m] + lis[r] > x:\n r -= 1\n else:\n m += 1\n return ans", "def counttriplets(head, x):\n c = 0\n num = []\n t = head\n while t:\n num.append(t.val)\n t = t.nxt\n num.sort()\n for i in range(len(num) - 2):\n l = i + 1\n r = len(num) - 1\n while l < r:\n k = num[i] + num[l] + num[r]\n if k == x:\n c += 1\n l += 1\n r -= 1\n elif k > x:\n r -= 1\n else:\n l += 1\n return c", "def counttriplets(head, key):\n\n def reverse(head):\n cur = head\n prev = None\n while cur:\n nxt = cur.nxt\n cur.nxt = prev\n prev = cur\n cur = nxt\n head = prev\n return head\n p = head\n head2 = Node(0)\n ans = head2\n q = head\n while q:\n head2.nxt = Node(q.val)\n head2 = head2.nxt\n q = q.nxt\n right = reverse(ans.nxt)\n count = 0\n while p.nxt:\n q = p.nxt\n r = right\n while q and r and (q.val != r.val):\n value = p.val + q.val + r.val\n if value == key:\n count += 1\n q = q.nxt\n elif value < key:\n r = r.nxt\n else:\n q = q.nxt\n p = p.nxt\n return count", "def counttriplets(head, x):\n nums = []\n t = head\n while t:\n nums.append(t.val)\n t = t.nxt\n count = 0\n di = {}\n i = 0\n while i < n - 2:\n temp = x - nums[i]\n dic = {}\n for j in range(i + 1, n):\n if temp - nums[j] in dic:\n count += 1\n dic[nums[j]] = 1\n i += 1\n return count", "def count(head):\n n = head\n count = 0\n while n:\n count += 1\n n = n.next\n\ndef counttriplets(head, x):\n node = head\n list = []\n while node:\n list.append(node.val)\n node = node.nxt\n N = len(list)\n k = N - 1\n if list[0] > list[1]:\n list.sort()\n count = 0\n while k >= 2:\n j = k - 1\n i = 0\n while i < j:\n if list[i] + list[j] + list[k] == x:\n count += 1\n i += 1\n j -= 1\n elif list[i] + list[j] + list[k] > x:\n j -= 1\n else:\n i += 1\n k -= 1\n return count", "def counttriplets(head, x):\n ans = 0\n arr = []\n p = head\n while p:\n arr.append(p.val)\n p = p.nxt\n for i in range(len(arr)):\n remaining = x - arr[i]\n d = {}\n for j in range(i + 1, len(arr)):\n if arr[j] in d:\n ans += 1\n else:\n d[remaining - arr[j]] = j\n return ans", "def counttriplets(head, x):\n ans = 0\n arr = []\n p = head\n while p:\n arr.append(p.val)\n p = p.nxt\n arr.sort()\n for i in range(len(arr)):\n l = i + 1\n r = len(arr) - 1\n while l < r:\n c = arr[i] + arr[l] + arr[r]\n if c == x:\n ans += 1\n l += 1\n r -= 1\n elif c < x:\n l += 1\n else:\n r -= 1\n return ans", "def counttriplets(head, x):\n nums = []\n t = head\n while t:\n nums.append(t.val)\n t = t.nxt\n nums.sort()\n if n == 1:\n return []\n brr = []\n di = {}\n i = 0\n while i < n - 2:\n temp = x - nums[i]\n dic = {}\n for j in range(i + 1, n):\n if temp - nums[j] in dic:\n mi = min(nums[i], nums[j], -(nums[i] + nums[j]))\n ma = max(nums[i], nums[j], -(nums[i] + nums[j]))\n sec = -(mi + ma)\n brr.append((mi, sec, ma))\n dic[nums[j]] = 1\n i += 1\n brr = list(set(brr))\n return len(brr)", "def counttriplets(head, x):\n p = head\n l = []\n while p != None:\n l.append(p.val)\n p = p.nxt\n c = 0\n n = len(l)\n l.sort()\n for i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n if l[i] + l[j] + l[k] == x:\n c += 1\n j += 1\n k -= 1\n elif l[i] + l[j] + l[k] < x:\n j += 1\n else:\n k -= 1\n return c", "def counttriplets(head, x):\n arr = []\n while head:\n arr.append(head.val)\n head = head.nxt\n n = len(arr)\n cnt = 0\n ind = {}\n for i in range(len(arr)):\n ind[arr[i]] = i\n for i in range(n):\n for j in range(i + 1, n):\n if ind.get(x - arr[i] - arr[j], -1) != -1 and ind[x - arr[i] - arr[j]] > j:\n cnt += 1\n return cnt", "def counttriplets(head, x):\n\n def traversal(head):\n n = head\n while n != None:\n list1.append(n.val)\n n = n.nxt\n list1 = []\n traversal(head)\n length = len(list1)\n count = 0\n list1.sort()\n for i in range(length - 2):\n j = i + 1\n k = length - 1\n while j < k:\n if list1[i] + list1[j] + list1[k] == x:\n count += 1\n j += 1\n k -= 1\n elif list1[i] + list1[j] + list1[k] > x:\n k -= 1\n elif list1[i] + list1[j] + list1[k] < x:\n j += 1\n return count", "def counttriplets(head, x):\n c = head\n l = []\n while c:\n l.append(c.val)\n c = c.nxt\n res = 0\n l.sort()\n for i in range(n - 2):\n le = i + 1\n r = n - 1\n while le < r:\n if l[i] + l[le] + l[r] == x:\n res += 1\n le += 1\n r -= 1\n elif l[i] + l[le] + l[r] > x:\n r -= 1\n else:\n le += 1\n return res", "def counttriplets(head, x):\n (arr, len1, res) = ([], 0, 0)\n while head:\n arr.append(head.val)\n (head, len1) = (head.nxt, len1 + 1)\n arr.sort()\n for i in range(len1 - 2):\n (start, end) = (i + 1, len1 - 1)\n sum1 = x - arr[i]\n while start < end:\n if arr[start] + arr[end] == sum1:\n (res, start, end) = (res + 1, start + 1, end - 1)\n elif arr[start] + arr[end] > sum1:\n end -= 1\n elif arr[start] + arr[end] < sum1:\n start += 1\n return res", "def counttriplets(head, x):\n (L, K, M) = ([], [], [])\n temp = head\n while temp:\n a = temp.val\n L.append(a)\n temp = temp.nxt\n L.sort()\n count = 0\n for i in range(n - 2):\n (m, r) = (i + 1, n - 1)\n while m < r:\n if L[i] + L[m] + L[r] == x:\n (count, m, r) = (count + 1, m + 1, r - 1)\n elif L[i] + L[m] + L[r] > x:\n r -= 1\n else:\n m += 1\n return count", "def counttriplets(head, x):\n map = []\n curr = head\n while curr is not None:\n map.append(curr.val)\n curr = curr.nxt\n c = 0\n map.sort()\n for i in range(len(map) - 2):\n start = i + 1\n end = len(map) - 1\n while start < end:\n if map[start] + map[end] + map[i] == x:\n c += 1\n start += 1\n end -= 1\n elif map[start] + map[end] + map[i] > x:\n end -= 1\n else:\n start += 1\n return c", "def counttriplets(head, x):\n itemsArr = []\n itemsHT = {}\n while head is not None:\n nextVal = head.val\n itemsArr.append(nextVal)\n itemsHT[nextVal] = 1\n head = head.nxt\n arrayLen = len(itemsArr)\n result = 0\n for i in range(arrayLen - 1):\n for j in range(i + 1, arrayLen):\n itemToFind = x - itemsArr[i] - itemsArr[j]\n if itemToFind == itemsArr[i] or itemToFind == itemsArr[j]:\n continue\n elif itemToFind in itemsHT:\n result += 1\n return result // 3", "def counttriplets(head, x):\n ans = 0\n dict1 = {}\n n = head\n while n:\n dict1[n.val] = 1\n n = n.nxt\n if head.val > head.nxt.val:\n curr = head\n prev = None\n while curr:\n nxt = curr.nxt\n curr.nxt = prev\n prev = curr\n curr = nxt\n head = prev\n n = head\n while n:\n m = n.nxt\n while m:\n ele = x - (m.val + n.val)\n if ele in dict1 and ele > m.val:\n ans += 1\n elif ele <= m.val:\n break\n m = m.nxt\n n = n.nxt\n return ans", "def counttriplets(head, x):\n vv = []\n while head != None:\n vv.append(head.val)\n head = head.nxt\n ans = 0\n for i in range(len(vv) - 2):\n s = i + 1\n e = len(vv) - 1\n while s < e:\n temp = vv[i] + vv[s] + vv[e]\n if temp == x:\n ans += 1\n s += 1\n e -= 1\n elif temp > x:\n s += 1\n else:\n e -= 1\n return ans", "def counttriplets(head, x):\n p = head\n arr = []\n count = 0\n while p:\n arr.append(p.val)\n p = p.nxt\n arr.sort()\n n = len(arr)\n for i in range(n - 2):\n target = x - arr[i]\n j = i + 1\n k = n - 1\n while j < k:\n sum = arr[j] + arr[k]\n if sum == target:\n count = count + 1\n j = j + 1\n k = k - 1\n elif sum < target:\n j = j + 1\n elif sum > target:\n k = k - 1\n return count", "def counttriplets(head, x):\n l = []\n while head != None:\n l.append(head.val)\n head = head.nxt\n count = 0\n n = len(l)\n for i in range(0, n - 2):\n start = n - 1\n end = i + 1\n while start > end:\n if l[start] + l[end] == x - l[i]:\n count += 1\n start -= 1\n end += 1\n elif l[start] + l[end] > x - l[i]:\n end += 1\n else:\n start -= 1\n return count", "def counttriplets(head, x):\n curr = head\n map = {}\n while curr:\n map[curr.val] = 1\n curr = curr.nxt\n curr = head\n count = 0\n while curr:\n next = curr.nxt\n while next:\n p_sum = int(next.val) + int(curr.val)\n if x - p_sum in map and x - p_sum != next.val and (x - p_sum != curr.val):\n count += 1\n next = next.nxt\n curr = curr.nxt\n return count // 3", "def counttriplets(head, x):\n vals = list()\n while head:\n vals.append(head.val)\n head = head.nxt\n vals = sorted(vals)\n ans = set()\n n = len(vals)\n for i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n new_sum = vals[i] + vals[j] + vals[k]\n if new_sum == x:\n ans.add((i, j, k))\n j += 1\n k -= 1\n elif new_sum > x:\n k -= 1\n else:\n j += 1\n return len(ans)", "def counttriplets(head, x):\n curr = head\n l = []\n while curr != None:\n l.append(curr.val)\n curr = curr.nxt\n n = len(l)\n l.sort()\n ans = 0\n for i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n sum1 = l[i] + l[j] + l[k]\n if sum1 == x:\n ans += 1\n j += 1\n k -= 1\n elif sum1 > x:\n k -= 1\n else:\n j += 1\n return ans", "def counttriplets(head, x):\n lst = []\n count = 0\n temp = head\n while temp is not None:\n lst.append(temp.val)\n temp = temp.nxt\n lst.sort()\n i = 0\n while i < len(lst) - 2:\n j = i + 1\n k = len(lst) - 1\n while j < len(lst) - 1 and j < k:\n if lst[i] + lst[j] + lst[k] == x:\n count += 1\n j += 1\n elif lst[i] + lst[j] + lst[k] < x:\n j += 1\n else:\n k -= 1\n i += 1\n return count", "def counttriplets(head, x):\n u = []\n t = head\n c = 0\n while t:\n u.append(t.val)\n t = t.nxt\n u = sorted(u)\n for i in range(len(u) - 2):\n l = i + 1\n r = len(u) - 1\n while l < r:\n if u[i] + u[l] + u[r] == x:\n c += 1\n l += 1\n r -= 1\n if u[i] + u[l] + u[r] > x:\n r = r - 1\n if u[i] + u[l] + u[r] < x:\n l += 1\n return c", "def counttriplets(head, x):\n list1 = []\n while head:\n list1.append(head.val)\n head = head.nxt\n list1.sort()\n count = 0\n n = len(list1)\n for i in range(n - 2):\n l = i + 1\n r = n - 1\n while l < r:\n summ = list1[i] + list1[l] + list1[r]\n if summ == x:\n count += 1\n l += 1\n r -= 1\n elif summ < x:\n l += 1\n else:\n r -= 1\n return count", "def counttriplets(head, x):\n l = list()\n curr = head\n while curr:\n l.append(curr.val)\n curr = curr.nxt\n l.sort()\n count = 0\n n = len(l)\n for i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n if l[i] + l[j] + l[k] < x:\n j += 1\n elif l[i] + l[j] + l[k] > x:\n k -= 1\n else:\n count += 1\n j += 1\n k -= 1\n return count", "def counttriplets(head, x):\n a = []\n itr = head\n count = 0\n while itr:\n a.append(itr.val)\n itr = itr.nxt\n a.sort()\n for i in range(len(a) - 2):\n start = i + 1\n end = len(a) - 1\n while start < end:\n if a[i] + a[start] + a[end] > x:\n end -= 1\n elif a[i] + a[start] + a[end] < x:\n start += 1\n else:\n count += 1\n start += 1\n return count", "def counttriplets(head, x):\n d = []\n temp = head\n while temp:\n d.append(temp.val)\n temp = temp.nxt\n d.sort()\n cnt = 0\n for i in range(len(d) - 2):\n l = i + 1\n h = len(d) - 1\n while l < h:\n if d[i] + d[l] + d[h] == x:\n cnt += 1\n l += 1\n if d[i] + d[l] + d[h] < x:\n l += 1\n else:\n h -= 1\n return cnt", "def counttriplets(head, x):\n d = {}\n v = []\n t = head\n while t != None:\n v.append(t.val)\n d[t.val] = len(v) - 1\n t = t.nxt\n count = 0\n for i in range(len(v)):\n o = x - v[i]\n for j in range(i + 1, len(v)):\n l = o - v[j]\n if d.get(l) and d[l] > j:\n count += 1\n return count", "import collections\n\ndef counttriplets(head, x):\n arr = []\n dup = head\n while dup:\n arr.append(dup.val)\n dup = dup.nxt\n arr = arr[::-1]\n carr = collections.Counter(arr)\n cnt = 0\n for i in range(len(arr)):\n for j in range(i, len(arr)):\n k = x - arr[i] - arr[j]\n if arr[i] != arr[j] != k and carr[k] != 0 and (i < j < arr.index(k)):\n cnt += 1\n return cnt", "def counttriplets(head, x):\n arr = []\n p = 0\n n = 0\n while head:\n arr.append(head.val)\n head = head.nxt\n n += 1\n arr.sort()\n y = []\n for i in range(0, n - 2):\n l = i + 1\n r = n - 1\n while l < r:\n if arr[i] + arr[l] + arr[r] == x:\n p += 1\n l += 1\n r -= 1\n elif arr[i] + arr[l] + arr[r] < x:\n l += 1\n else:\n r -= 1\n return p", "def counttriplets(head, x):\n arr = []\n temp = head\n while temp != None:\n arr.append(temp.val)\n temp = temp.nxt\n c = 0\n arr.sort()\n for i in range(0, len(arr) - 2):\n j = i + 1\n k = len(arr) - 1\n while j < k:\n s = arr[i] + arr[j] + arr[k]\n if s == x:\n c += 1\n j += 1\n k -= 1\n elif s > x:\n k -= 1\n else:\n j += 1\n return c", "from collections import deque\n\ndef countPairs(head, x):\n if head == None or head.nxt == None or x < 2:\n return 0\n dq = deque()\n walk = head\n while walk:\n dq.append(walk.val)\n walk = walk.nxt\n ret = 0\n l = dq.popleft()\n r = dq.pop()\n while 1:\n if l + r == x:\n ret += 1\n if len(dq) == 0:\n return ret\n if l + r > x:\n l = dq.popleft()\n else:\n r = dq.pop()\n\ndef counttriplets(head, x):\n ret = 0\n while head != None:\n ret += countPairs(head.nxt, x - head.val)\n head = head.nxt\n return ret", "def counttriplets(head, x):\n\n def reverse(head):\n prev = None\n curr = head\n fut = head.nxt\n while curr:\n curr.nxt = prev\n prev = curr\n curr = fut\n if fut:\n fut = fut.nxt\n return prev\n\n def insert(head):\n curr = head\n ele = Node(curr.val)\n new = ele\n curr = curr.nxt\n while curr:\n new.nxt = Node(curr.val)\n new = new.nxt\n curr = curr.nxt\n return ele\n new = reverse(insert(head))\n curr = head\n count = 0\n val1 = False\n if head.val < new.val:\n val1 = True\n while curr.nxt.nxt:\n summ = res = curr.val\n temp1 = curr.nxt\n temp2 = new\n while val1 and temp1.val < temp2.val or (not val1 and temp1.val > temp2.val):\n res += temp1.val + temp2.val\n if res == x:\n count += 1\n temp1 = temp1.nxt\n temp2 = temp2.nxt\n elif res > x:\n if temp2.val > temp1.val:\n temp2 = temp2.nxt\n else:\n temp1 = temp1.nxt\n elif temp1.val > temp2.val:\n temp2 = temp2.nxt\n else:\n temp1 = temp1.nxt\n res = summ\n curr = curr.nxt\n return count", "def counttriplets(head, x):\n a = head\n count = 0\n while a != None:\n p = x - a.val\n s = set()\n q = a.nxt\n while q != None:\n if p - q.val in s:\n count += 1\n q = q.nxt\n else:\n s.add(q.val)\n q = q.nxt\n a = a.nxt\n return count", "def counttriplets(head, x):\n l = []\n while head != None:\n l.append(head.val)\n head = head.nxt\n n = len(l)\n if n <= 2:\n return 0\n if l[0] > l[-1]:\n l = l[::-1]\n i = 0\n ans = 0\n while i < n - 2:\n req = x - l[i]\n j = i + 1\n k = n - 1\n while j < k:\n if l[j] + l[k] == req:\n ans += 1\n curr = l[j]\n while j < k and l[j] == curr:\n j += 1\n curr = l[k]\n while j < k and l[k] == curr:\n k -= 1\n elif l[j] + l[k] < req:\n curr = l[j]\n while j < k and l[j] == curr:\n j += 1\n else:\n curr = l[k]\n while j < k and l[k] == curr:\n k -= 1\n curr = l[i]\n while i < n - 2 and l[i] == curr:\n i += 1\n return ans", "def counttriplets(head, x):\n l = []\n res = 0\n if not head:\n return 0\n while head:\n l.append(head.val)\n head = head.nxt\n l.sort()\n for i in range(len(l) - 2):\n left = i + 1\n right = len(l) - 1\n while left < right:\n k = l[i] + l[right] + l[left]\n if k == x:\n res += 1\n left += 1\n right -= 1\n elif k > x:\n right -= 1\n else:\n left += 1\n return res"], "starter_code": "def counttriplets(head,x):\n", "input_output": {"fn_name": "countTriplets", "inputs": ["LinkedList:9->8->6->5->4->2->1, X = 17", "LinkedList:9->8->6->5->4->2->1, X = 15"], "outputs": ["2", "5"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Algorithms", "Mathematical", "Linked List"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/87f12e5c728d69a5322634776b54c75897d14daa/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N^{2})", "entry_point": "counttriplets", "task_id": "TACO_lite/210", "example": [[], []]} +{"requirement": "An array is said to be `hollow` if it contains `3` or more `0`s in the middle that are preceded and followed by the same number of non-zero elements. Furthermore, all the zeroes in the array must be in the middle of the array. \n\nWrite a function named `isHollow`/`is_hollow`/`IsHollow` that accepts an integer array and returns `true` if it is a hollow array,else `false`.", "solutions": ["def is_hollow(x):\n while x and x[0] != 0 and (x[-1] != 0):\n x = x[1:-1]\n return len(x) > 2 and set(x) == {0}", "from itertools import groupby\nfrom operator import not_\n\ndef is_hollow(a):\n b = [(x, [*y]) for (x, y) in groupby(a, key=not_)]\n return len(b) == 1 and b[0][0] and (len(b[0][1]) > 2) or (len(b) == 3 and [x for (x, _) in b] == [0, 1, 0] and (len(b[1][1]) > 2) and (len(b[0][1]) == len(b[2][1])))", "from itertools import groupby\n\ndef is_hollow(x):\n xs = [(key, sum((1 for _ in grp))) for (key, grp) in groupby(x)]\n mid = len(xs) // 2\n limit = len(xs) - (len(xs) > 1)\n return any((i == mid < limit for (i, (x, cnt)) in enumerate(xs) if x == 0 and cnt >= 3)) and sum((x == 0 for (x, _) in xs)) == 1", "def is_hollow(x):\n return len(x) > 2 and (x[0] and x[-1] and is_hollow(x[1:-1]) or set(x) == {0})", "from re import match\n\ndef is_hollow(x):\n return bool(match('(x*)[0]{3,}\\\\1$', ''.join(('x' if v else '0' for v in x))))", "def is_hollow(x):\n if len(x) < 3:\n return False\n z = 0\n for (i, (a, b)) in enumerate(zip(x, x[::-1])):\n if i > len(x) // 2:\n return z >= 2\n if (a == 0) != (b == 0):\n return False\n if a != 0 and z > 0:\n return False\n if a == 0:\n z += 1\n elif z > 0:\n return False", "def is_hollow(A):\n while A and A[0] * A[-1] != 0:\n A = A[1:-1]\n return 2 < A.count(0) and set(A) == {0}", "import re\n\ndef is_hollow(x):\n return True if re.match('^(1*)0{3,}\\\\1$', ''.join(('0' if i == 0 else '1' for i in x))) else False", "def is_hollow(x):\n i = j = len(x) // 2\n while i > 0 and x[i - 1] == 0:\n i -= 1\n while j < len(x) and x[j] == 0:\n j += 1\n prefix = x[:i]\n suffix = x[j:]\n return not (j - i < 3 or 0 in prefix + suffix or len(prefix) != len(suffix))"], "starter_code": "def is_hollow(x):\n", "input_output": {"fn_name": "is_hollow", "inputs": [[[-1, 0, 0, 0, 3]], [[1, 0, 0, 0, 0]]], "outputs": [[true], [false]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/59b72376460387017e000062", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_hollow", "task_id": "TACO_lite/244", "example": [[], []]} +{"requirement": "We have N persons sitting on a round table. Any person can do a handshake with any other person. \n 1\n2 3\n 4\nHandshake with 2-3 and 1-4 will cause cross.\nIn how many ways these N people can make handshakes so that no two handshakes cross each other. N would be even. \n \nExample 1:\nInput:\nN = 2\nOutput:\n1\nExplanation:\n{1,2} handshake is\npossible.\nExample 2:\nInput:\nN = 4\nOutput:\n2\nExplanation:\n{{1, 2}, {3, 4}} are the\ntwo handshakes possible.\n{{1, 3}, {2, 4}} is another\nset of handshakes possible.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function count() which takes an integer N as input parameters and returns an integer, the total number of handshakes possible so that no two handshakes cross each other.\n \nExpected Time Complexity: O(2^{N})\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= N <= 30", "solutions": ["def count(N):\n\n def findCatalan(x):\n if x == 0 or x == 1:\n return 1\n result = 0\n for i in range(0, x):\n result += findCatalan(i) * findCatalan(x - i - 1)\n return result\n return findCatalan(N // 2)", "def count(N):\n dp = [0] * (N // 2 + 1)\n dp[0] = 1\n for i in range(1, len(dp)):\n for j in range(i):\n dp[i] += dp[j] * dp[i - 1 - j]\n return dp[N // 2]", "def count(N):\n if N % 2 == 1:\n return 0\n dp = [1] * (N + 1)\n for i in range(4, N + 1):\n (tmp, M) = (0, i - 2)\n for j in range(0, M // 2, 2):\n tmp += dp[j] * dp[M - j]\n tmp *= 2\n if M % 4 == 0:\n tmp += dp[M // 2] * dp[M // 2]\n dp[i] = tmp\n return dp[N]", "def rec(N, dp):\n if N == 0:\n return 1\n if N % 2:\n return 0\n if N in dp:\n return dp[N]\n ans = 0\n for i in range(2, N + 1):\n ans += rec(i - 1 - 1, dp) * rec(N - i, dp)\n dp[N] = ans\n return ans\n\ndef count(N):\n dp = {}\n return rec(N, dp)", "d = {0: 1, 2: 1, 4: 2}\n\ndef count(N):\n if N % 2 != 0:\n N -= 1\n if N in d:\n return d[N]\n ans = 0\n for j in range(1, N, 2):\n ans += self.count(j - 1) * self.count(N - j - 1)\n return ans", "def count(N):\n result = 0\n if N % 2 == 1:\n return 0\n elif N == 0:\n return 1\n for i in range(0, N, 2):\n result += self.count(i) * self.count(N - 2 - i)\n return result", "def hand(N):\n if N <= 2:\n return 1\n ans = 0\n for i in range(0, N, 2):\n ans += hand(i) * hand(N - i - 2)\n return ans\n\ndef count(N):\n ans = hand(N)\n return ans", "def solve(N, dict_hand):\n if N <= 2:\n return 1\n if N in dict_hand:\n return dict_hand[N]\n ans = 0\n for i in range(0, N, 2):\n ans += self.solve(i, dict_hand) * self.solve(N - i - 2, dict_hand)\n dict_hand[N] = ans\n return ans\n\ndef count(N):\n dict_hand = {2: 1}\n self.solve(N, dict_hand)\n return dict_hand[N]", "def count(N):\n if N & 1:\n return 0\n if N == 0:\n return 1\n total = 0\n for i in range(N):\n total += self.count(i) * self.count(N - i - 2)\n return total", "def count(N):\n d = {}\n\n def helper(x):\n if x == 0 or x == 1:\n return 1\n if x in d:\n return d[x]\n ans = 0\n for i in range(x):\n ans += helper(i) * helper(x - i - 1)\n d[x] = ans\n return d[x]\n return helper(N // 2)", "def count(N):\n if N % 2 == 1:\n return 0\n kMod = 1000000007\n dp = [0] * (N + 1)\n dp[0] = 1\n for i in range(2, N + 1):\n for j in range(2, i + 1, 2):\n dp[i] += dp[j - 2] * dp[i - j] % kMod\n return dp[-1] % kMod", "def count(n):\n if n == 0:\n return 1\n ans = 0\n for i in range(0, n, 2):\n ans += self.count(i) * self.count(n - 2 - i)\n return ans", "def count(N, dic={}):\n if N == 0:\n return 1\n if N in dic:\n return dic[N]\n res = 0\n for i in range(0, N, 2):\n res += self.count(i, dic) * self.count(N - i - 2, dic)\n dic[N] = res\n return dic[N]", "from collections import defaultdict\n\ndef __init__():\n self.hmap[0] = 1\n\ndef count(n):\n if n in self.hmap:\n return self.hmap[n]\n for i in range(0, n, 2):\n self.hmap[n] += self.count(i) * self.count(n - i - 2)\n return self.hmap[n]", "def count(N):\n\n def catalan(n):\n dp = [0] * (n + 1)\n dp[0] = 1\n for i in range(1, n + 1):\n dp[i] = 0\n for j in range(i):\n dp[i] += dp[j] * dp[i - j - 1]\n return dp[n]\n return catalan(N // 2)", "def handShake(p):\n dp = [0 for _ in range(p + 1)]\n dp[0] = dp[1] = 1\n for i in range(2, p + 1, 2):\n for j in range(0, i - 1, 2):\n dp[i] += dp[j] * dp[i - 2 - j]\n return dp[-1]\n\ndef count(N):\n return handShake(N)", "def count(N):\n return self.catalan(N // 2)\n\ndef catalan(n):\n if n <= 1:\n return 1\n res = 0\n for i in range(n):\n res += self.catalan(i) * self.catalan(n - i - 1)\n return res", "def helper(x):\n if x == 0 or x == 1:\n return 1\n res = 0\n for i in range(x):\n a = self.helper(i)\n b = self.helper(x - i - 1)\n res += a * b\n return res\n\ndef count(N):\n res = self.helper(N // 2)\n return res", "def count(N):\n\n def solution(n):\n catalan = [1] * (n + 1)\n for i in range(2, n + 1):\n catalan[i] = 0\n for j in range(i):\n catalan[i] += catalan[j] * catalan[i - j - 1]\n return catalan[n]\n if N % 2 != 0:\n return False\n else:\n return solution(N // 2)", "from functools import lru_cache\n\ndef count(n):\n\n def dp(m):\n if m % 2 == 1:\n return 0\n if m == 0:\n return 1\n ans = 0\n for i in range(0, m, 2):\n ans += dp(i) * dp(m - i - 2)\n return ans\n return dp(n)", "def count(N):\n p = N // 2\n arr = [0] * (p + 1)\n arr[0] = 1\n arr[1] = 1\n for i in range(2, p + 1):\n for j in range(0, p):\n arr[i] += arr[j] * arr[i - j - 1]\n return arr[p]", "def __init__():\n self.ans = 0\n\ndef count(n):\n if n == 0 or n == 2:\n return 1\n else:\n a = n - 2\n b = 0\n ans = 0\n while a >= 0:\n ans += self.count(a) * self.count(b)\n a -= 2\n b += 2\n return ans", "def count(N):\n if N == 2:\n return 1\n if N == 0:\n return 1\n ans = 0\n left = 0\n right = N - 2\n while left <= N - 2:\n ans += self.count(left) * self.count(right)\n left += 2\n right -= 2\n return ans", "def count(N):\n memo = {}\n\n def dp(n):\n if n == 0:\n return 1\n if n & 1:\n return 0\n if n in memo:\n return memo[n]\n ans = 0\n for i in range(2, n + 1):\n grp1 = i - 2\n grp2 = n - i\n ans += dp(grp1) * dp(grp2)\n return ans\n res = dp(N)\n return res", "def count(N):\n if N == 0:\n return 0\n else:\n return int(self.fact(N) / (self.fact(N / 2 + 1) * self.fact(N / 2)))\n\ndef fact(n):\n if n == 1:\n return 1\n else:\n return n * self.fact(n - 1)", "def count(N):\n arr = [0] * (N + 1)\n arr[0] = 1\n if N == 0:\n return arr[0]\n for i in range(2, N + 1, 2):\n temp = 0\n for j in range(0, i, 2):\n temp = temp + arr[j] * arr[i - 2 - j]\n arr[i] = temp\n return arr[N]", "def count(N):\n if N <= 2:\n return 1\n i = N - 2\n sum = 0\n while i >= 0:\n sum += self.count(i) * self.count(N - 2 - i)\n i -= 2\n return sum", "def count(N):\n if N == 0:\n return 0\n if N == 2:\n return 1\n c = 0\n for i in range(0, N - 1, 2):\n left = self.count(i)\n right = self.count(N - 2 - i)\n if left and right:\n c += left * right\n else:\n c += left + right\n return c", "def count(N):\n sum1 = 0\n if N == 0 or N == 2:\n return 1\n else:\n for i in range(0, N, 2):\n sum1 = sum1 + self.count(i) * self.count(N - i - 2)\n return sum1", "def count(N):\n if N == 0:\n return 1\n ans = 0\n for idx in range(0, N, 2):\n ans += self.count(idx) * self.count(N - 2 - idx)\n return ans", "def count(N):\n if N == 0:\n return 1\n answear = 0\n for i in range(0, N, 2):\n ob = Solution()\n answear += ob.count(i) * ob.count(N - 2 - i)\n return answear", "def count(N):\n if N % 2 == 1:\n return 0\n elif N == 0:\n return 1\n res = 0\n i = 0\n while i < N:\n res += self.count(i) * self.count(N - 2 - i)\n i += 2\n return res", "import math\n\ndef catlan(n):\n c = int(math.factorial(2 * n) / (math.factorial(n + 1) * math.factorial(n)))\n return c\n\ndef count(N):\n if N % 2 == 1:\n return 0\n else:\n return catlan(int(N / 2))", "from math import factorial as fac\n\ndef check(n):\n return fac(2 * n) // fac(n + 1) // fac(n)\n\ndef count(N):\n if N % 2 == 1:\n return 0\n return check(N // 2)", "def count(N):\n\n def handshakes(min, max):\n total_handshakes = 0\n if min >= max:\n return 1\n for partner in range(min + 1, max + 1, 2):\n above_handshakes = handshakes(min + 1, partner - 1)\n below_handshakes = handshakes(partner + 1, max)\n total_handshakes += above_handshakes * below_handshakes\n return total_handshakes\n return handshakes(1, N)", "from collections import defaultdict\nd = defaultdict(lambda : 0)\nfor i in range(6, 32, 2):\n (d[0], d[2], d[4]) = (1, 1, 2)\n res = 0\n for j in range(2, i // 2 + 1):\n res += d[j - 2] * d[i - j]\n res *= 2\n res += d[i // 2 - 1] ** 2\n d[i] = res\n\ndef count(N):\n return d[N]"], "starter_code": "def count(N):\n", "input_output": {"inputs": ["N = 2", "N = 4"], "outputs": ["1", "2"]}, "difficulty": "MEDIUM", "raw_tags": ["Recursion", "Algorithms"], "name": null, "source": "geeksforgeeks", "tags": ["Complete search"], "skill_types": ["Complete search"], "url": "https://practice.geeksforgeeks.org/problems/handshakes1303/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(2^{N})", "entry_point": "count", "task_id": "TACO_lite/307", "example": [[[2], [4]], ["1", "2"]]} +{"requirement": "Given a sorted doubly linked list of positive distinct elements, the task is to find pairs in a doubly-linked list whose sum is equal to given value target.\n \nExample 1:\nInput: \n1 <-> 2 <-> 4 <-> 5 <-> 6 <-> 8 <-> 9\ntarget = 7\nOutput: (1, 6), (2,5)\nExplanation: We can see that there are two pairs \n(1, 6) and (2,5) with sum 7.\n \nExample 2:\nInput: \n1 <-> 5 <-> 6\ntarget = 6\nOutput: (1,5)\nExplanation: We can see that there is one pairs (1, 5) with sum 6.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function findPairsWithGivenSum() which takes head node of the doubly linked list and an integer target as input parameter and returns an array of pairs. If there is no such pair return empty array.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 10^{5}\n1 <= target <= 10^{5}", "solutions": ["from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n ans = []\n slow = head\n fast = head\n while fast.next is not None:\n fast = fast.next\n while slow.data < fast.data:\n if slow.data + fast.data == target:\n ans.append((slow.data, fast.data))\n slow = slow.next\n fast = fast.prev\n elif slow.data + fast.data < target:\n slow = slow.next\n else:\n fast = fast.prev\n return ans", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n d = dict()\n cur = head\n res = []\n while cur != None:\n if d.get(target - cur.data, -1) != -1:\n arr = [cur.data, target - cur.data]\n arr.sort()\n res.append(arr)\n d[cur.data] = 1\n cur = cur.next\n res.sort()\n return res", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n res = []\n start = head\n end = head\n while end.next:\n end = end.next\n while start.data < end.data:\n s = start.data + end.data\n if s == target:\n res.append([start.data, end.data])\n start = start.next\n end = end.prev\n elif s < target:\n start = start.next\n else:\n end = end.prev\n return res", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n high = head\n low = head\n temp = []\n while high.next != None:\n high = high.next\n while low.data < high.data:\n sum = low.data + high.data\n if sum > target:\n high = high.prev\n elif sum < target:\n low = low.next\n else:\n temp.append([low.data, high.data])\n low = low.next\n high = high.prev\n return temp", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n result = []\n if not head:\n return result\n tail = head\n while tail.next:\n tail = tail.next\n while head and tail and (head.data < tail.data):\n (headVal, tailVal) = (head.data, tail.data)\n currVal = headVal + tailVal\n if currVal == target:\n result.append((headVal, tailVal))\n head = head.next\n tail = tail.prev\n elif currVal > target:\n tail = tail.prev\n else:\n head = head.next\n return result", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n temp = head\n while temp:\n last = temp\n temp = temp.next\n ans = []\n start = head\n while start.data < last.data:\n if start.data + last.data == target:\n ans.append([start.data, last.data])\n start = start.next\n last = last.prev\n elif start.data + last.data > target:\n last = last.prev\n else:\n start = start.next\n return ans", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n first = head\n while first.next:\n first = first.next\n last = first\n first = head\n solution = []\n while first != last:\n if first.data + last.data == target:\n solution.append((first.data, last.data))\n if first.next == last:\n break\n first = first.next\n last = last.prev\n elif first.data + last.data > target:\n last = last.prev\n else:\n first = first.next\n return solution", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n (p1, p2) = (head, head)\n res = []\n while p2.next:\n p2 = p2.next\n while p1 and p2 and (p1.data < p2.data):\n t = p1.data + p2.data\n if t < target:\n p1 = p1.next\n elif t > target:\n p2 = p2.prev\n else:\n res.append([p1.data, p2.data])\n p1 = p1.next\n p2 = p2.prev\n return res", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n ans = []\n temp1 = temp2 = head\n while temp2.next:\n temp2 = temp2.next\n while temp2.data > temp1.data:\n sum = temp2.data + temp1.data\n if sum == target:\n ans.append([temp1.data, temp2.data])\n temp1 = temp1.next\n temp2 = temp2.prev\n elif sum < target:\n temp1 = temp1.next\n else:\n temp2 = temp2.prev\n return ans", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n if target is None:\n return []\n high = head\n while high.next is not None:\n high = high.next\n low = head\n res = []\n while id(low) != id(high):\n sumval = low.data + high.data\n if sumval == target:\n res.append([low.data, high.data])\n if id(low.next) != id(high):\n low = low.next\n high = high.prev\n elif sumval < target:\n low = low.next\n else:\n high = high.prev\n return res", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n end = head\n res = []\n while end.next is not None:\n end = end.next\n start = head\n while start != end:\n if start.data + end.data == target:\n res.append((start.data, end.data))\n start = start.next\n if start == end:\n break\n end = end.prev\n elif start.data + end.data > target:\n end = end.prev\n else:\n start = start.next\n return res", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n left = head\n right = head\n l = []\n while right.next != None:\n right = right.next\n while right != left and right.next != left:\n if left.data + right.data == target:\n l.append((left.data, right.data))\n left = left.next\n right = right.prev\n elif left.data + right.data < target:\n left = left.next\n else:\n right = right.prev\n return l", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n d = {}\n while head:\n d[head.data] = 1\n head = head.next\n a = []\n for i in d:\n if target - i in d and d[target - i] != -1 and (i != target - i):\n a.append(sorted([i, target - i]))\n d[i] = -1\n return sorted(a)", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n if not head.next:\n return []\n res = []\n low = high = head\n while high.next:\n high = high.next\n while low != high:\n if low.data + high.data == target:\n res.append([low.data, high.data])\n low = low.next\n if low == high:\n break\n high = high.prev\n elif low.data + high.data < target:\n low = low.next\n else:\n high = high.prev\n return res", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n tail = head\n while tail.next != None:\n tail = tail.next\n arr = []\n while head.data < tail.data:\n if head.data + tail.data == target:\n arr.append([head.data, tail.data])\n head = head.next\n tail = tail.prev\n elif head.data + tail.data > target:\n tail = tail.prev\n elif head.data + tail.data < target:\n head = head.next\n return arr", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n (fp, lp) = (head, head)\n while lp.next:\n lp = lp.next\n ans = []\n while fp and fp != lp:\n if fp.data + lp.data == target:\n ans.append([fp.data, lp.data])\n fp = fp.next\n elif fp.data + lp.data > target:\n lp = lp.prev\n else:\n fp = fp.next\n return ans", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n tail = head\n start = 1\n end = 1\n while tail.next != None:\n tail = tail.next\n end += 1\n sum = 0\n pairs = []\n while start < end:\n sum = head.data + tail.data\n if sum == target:\n pairs.append([head.data, tail.data])\n sum = 0\n head = head.next\n tail = tail.prev\n start += 1\n end -= 1\n elif sum > target:\n tail = tail.prev\n end -= 1\n else:\n head = head.next\n start += 1\n return pairs", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n (left, right) = (head, head)\n result = []\n while right.next:\n right = right.next\n while left != right:\n temp = left.data + right.data\n if temp == target:\n result.append([left.data, right.data])\n right = right.prev\n elif temp > target:\n right = right.prev\n elif temp < target:\n left = left.next\n return result", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n temp = head\n while temp:\n rear = temp\n temp = temp.next\n res = []\n while head and rear and (head.data < rear.data):\n x = head.data + rear.data\n if x == target:\n res.append((head.data, rear.data))\n head = head.next\n rear = rear.prev\n elif x < target:\n head = head.next\n else:\n rear = rear.prev\n return res", "from typing import Optional\nfrom typing import List\n\ndef findPairsWithGivenSum(target: int, head: Optional['Node']) -> List[List[int]]:\n arr = []\n cur = head\n while cur.next is not None:\n cur = cur.next\n l = head\n r = cur\n while l != r and l.next != r:\n ld = l.data\n rd = r.data\n if ld + rd == target:\n arr.append((ld, rd))\n l = l.next\n r = r.prev\n elif ld + rd < target:\n l = l.next\n else:\n r = r.prev\n if l != r and l.data + r.data == target:\n arr.append((l.data, r.data))\n return arr"], "starter_code": "def __init__(x):\n", "input_output": {"inputs": ["1 <-> 2 <-> 4 <-> 5 <-> 6 <-> 8 <-> 9\r\ntarget = 7", "1 <-> 5 <-> 6\r\ntarget = 6"], "outputs": ["(1, 6), (2,5)", "(1,5)"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Algorithms", "two-pointer-algorithm", "doubly-linked-list"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Amortized analysis"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/find-pairs-with-given-sum-in-doubly-linked-list/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "__init__", "task_id": "TACO_lite/272", "example": [[], []]} +{"requirement": "Given a string S, find the length of the longest substring with all distinct characters. \nExample 1:\nInput:\nS = \"geeksforgeeks\"\nOutput: 7\nExplanation: \"eksforg\" is the longest \nsubstring with all distinct characters.\nExample 2:\nInput: \nS = \"aaa\"\nOutput: 1\nExplanation: \"a\" is the longest substring \nwith all distinct characters.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function longestSubstrDitinctChars() which takes the string S as input and returns the length of the longest substring with all distinct characters.\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(K), where K is Constant.\nConstraints:\n1<=|S|<=10^{5}", "solutions": ["def longestsubstrdistinctchars(string):\n seen = {}\n maximum_length = 0\n start = 0\n for end in range(len(string)):\n if string[end] in seen:\n start = max(start, seen[string[end]] + 1)\n seen[string[end]] = end\n maximum_length = max(maximum_length, end - start + 1)\n return maximum_length", "def longestsubstrdistinctchars(s):\n (i, j, k) = (0, 0, 0)\n for i in range(len(s) + 1):\n if len(s[j:i]) == len(set(s[j:i])):\n k = max(len(s[j:i]), k)\n else:\n while len(s[j:i]) != len(set(s[j:i])) and j < i:\n j += 1\n k = max(len(s[j:i]), k)\n k = max(len(s[j:i]), k)\n return k", "def longestsubstrdistinctchars(str):\n n = len(str)\n res = 0\n for i in range(n):\n visited = [0] * 256\n for j in range(i, n):\n if visited[ord(str[j])] == True:\n break\n else:\n res = max(res, j - i + 1)\n visited[ord(str[j])] = True\n visited[ord(str[i])] = False\n return res", "def longestsubstrdistinctchars(S):\n i = 0\n j = 0\n ans = []\n l = []\n while j < len(S):\n if S[j] not in l:\n l.append(S[j])\n j += 1\n else:\n l = []\n res = i + 1\n i += 1\n j = res\n ans.append(j - i)\n return max(ans)", "def longestsubstrdistinctchars(S):\n long_len = 0\n st = 0\n dct = {}\n for i in range(len(S)):\n if S[i] in dct:\n st = max(st, dct[S[i]] + 1)\n dct[S[i]] = i\n long_len = max(long_len, i - st + 1)\n return long_len", "def longestsubstrdistinctchars(S):\n visited = {}\n maxLen = 0\n start = 0\n for i in range(len(S)):\n if S[i] in visited:\n start = max(start, visited[S[i]] + 1)\n maxLen = max(maxLen, i - start + 1)\n visited[S[i]] = i\n return maxLen", "def longestsubstrdistinctchars(str):\n if len(S) == 0:\n return 0\n elif len(S) == 1:\n return 1\n else:\n maxLength = -1\n final = ''\n for i in range(0, len(S)):\n char = S[i]\n if S[i] in final:\n final = final[final.index(S[i]) + 1:]\n final = final + S[i]\n maxLength = max(len(final), maxLength)\n return maxLength\n test = ''", "def longestsubstrdistinctchars(str):\n test = ''\n maxLength = -1\n if len(str) == 0:\n return 0\n elif len(str) == 1:\n return 1\n for c in list(str):\n current = ''.join(c)\n if current in test:\n test = test[test.index(current) + 1:]\n test = test + ''.join(c)\n maxLength = max(len(test), maxLength)\n return maxLength", "def longestsubstrdistinctchars(S):\n n = len(S)\n max_len = 0\n start = 0\n seen = {}\n for end in range(n):\n if S[end] in seen and start <= seen[S[end]]:\n start = seen[S[end]] + 1\n else:\n max_len = max(max_len, end - start + 1)\n seen[S[end]] = end\n return max_len", "def longestsubstrdistinctchars(S):\n char = set()\n l = 0\n c = 0\n for r in range(len(S)):\n while S[r] in char:\n char.remove(S[l])\n l += 1\n char.add(S[r])\n c = max(c, len(char))\n return c", "def longestsubstrdistinctchars(s):\n last_index = {}\n max_len = 0\n start_index = 0\n for i in range(len(s)):\n if s[i] in last_index:\n start_index = max(start_index, last_index[s[i]] + 1)\n max_len = max(max_len, i - start_index + 1)\n last_index[s[i]] = i\n return max_len", "def longestsubstrdistinctchars(s):\n n = len(s)\n mx = -1\n (i, j) = (0, 0)\n d = {}\n t = ''\n while i < n and j < n:\n if s[j] in d:\n d = {}\n mx = max(mx, len(t))\n t = ''\n i += 1\n j = i\n else:\n t += s[j]\n d[s[j]] = 1\n j += 1\n return max(len(t), mx)", "def longestsubstrdistinctchars(S):\n s = ''\n d = {}\n m = 0\n l = []\n for i in range(len(S)):\n s = ''\n for j in range(i, len(S)):\n if S[j] not in d:\n s += S[j]\n d[S[j]] = 1\n else:\n break\n if len(s) > m:\n m = len(s)\n d = {}\n return m", "def longestsubstrdistinctchars(s):\n letters = set()\n l = 0\n res = 0\n for i in range(len(s)):\n while s[i] in letters:\n letters.remove(s[l])\n l += 1\n letters.add(s[i])\n res = max(res, i - l + 1)\n return res", "def longestsubstrdistinctchars(S):\n t = {}\n m = ''\n l = []\n i = 0\n while i < len(S):\n if S[i] not in t:\n t[S[i]] = i\n m = m + S[i]\n i = i + 1\n else:\n l.append(len(m))\n i = t[S[i]] + 1\n t = {}\n m = ''\n if m != '':\n l.append(len(m))\n k = max(l)\n return k", "def longestsubstrdistinctchars(S):\n m = 0\n for i in range(len(S)):\n c = 0\n l = []\n for j in range(i, len(S)):\n if S[j] in l:\n break\n else:\n l.append(S[j])\n c += 1\n m = max(m, c)\n return m", "def longestsubstrdistinctchars(S):\n lst = [0] * 26\n l = 0\n r = 0\n sub = ''\n lth = 0\n curr = 0\n for i in range(len(S)):\n x = ord(S[i]) - 97\n if lst[x] != 0:\n while lst[x] != 0:\n lst[ord(S[l]) - 97] = 0\n l += 1\n curr -= 1\n sub += chr(x + 97)\n lst[x] += 1\n r += 1\n curr += 1\n if curr > lth:\n lth = curr\n return lth", "def longestsubstrdistinctchars(S):\n c = 0\n maxlen = 0\n st = []\n for i in range(len(S)):\n if S[i] not in st:\n st.append(S[i])\n c += 1\n if c > maxlen:\n maxlen = c\n else:\n while st.pop(0) != S[i]:\n continue\n st.append(S[i])\n c = len(st)\n if c > maxlen:\n maxlen = c\n return maxlen", "def longestsubstrdistinctchars(S):\n d = {}\n m = 0\n i = 0\n for j in range(len(S)):\n if S[j] not in d:\n d[S[j]] = j\n else:\n if len(d) > m:\n m = len(d)\n i = d[S[j]] + 1\n d1 = d.copy()\n for k in d:\n if d1[k] < i:\n del d1[k]\n d = d1\n d[S[j]] = j\n if m < len(d):\n return len(d)\n return m", "def longestsubstrdistinctchars(S):\n setStr = set()\n l = 0\n res = 0\n for i in range(len(S)):\n while S[i] in setStr:\n setStr.remove(S[l])\n l += 1\n setStr.add(S[i])\n res = max(res, i - l + 1)\n return res", "def longestsubstrdistinctchars(S):\n char_set = set()\n left = 0\n max_len = 0\n for right in range(len(S)):\n while S[right] in char_set:\n char_set.remove(S[left])\n left += 1\n char_set.add(S[right])\n max_len = max(max_len, right - left + 1)\n return max_len", "def longestsubstrdistinctchars(s):\n i = 0\n j = 0\n k = 1\n maxi = 0\n n = len(s)\n while k < n and j < n:\n if s[k] in s[i:j + 1]:\n i += 1\n j = i\n k = i + 1\n else:\n j += 1\n k += 1\n length = len(s[i:j + 1])\n maxi = max(maxi, length)\n return maxi", "def longestsubstrdistinctchars(S):\n n = len(S)\n chars = set()\n i = j = max_len = 0\n while i < n and j < n:\n if S[j] not in chars:\n chars.add(S[j])\n j += 1\n max_len = max(max_len, j - i)\n else:\n chars.remove(S[i])\n i += 1\n return max_len", "def longestsubstrdistinctchars(S):\n charSet = set()\n l = 0\n res = 0\n for r in range(len(S)):\n while S[r] in charSet:\n charSet.remove(S[l])\n l += 1\n charSet.add(S[r])\n res = max(res, r - l + 1)\n return res", "def longestsubstrdistinctchars(S):\n l = ''\n maxL = -1\n if len(S) == 0:\n return 0\n elif len(S) == 1:\n return 1\n for c in list(S):\n curr = ''.join(c)\n if curr in l:\n l = l[l.index(curr) + 1:]\n l = l + ''.join(c)\n maxL = max(len(l), maxL)\n return maxL", "def longestsubstrdistinctchars(S):\n max_len_substr = 0\n substrin = []\n for i in range(len(S)):\n if S[i] in substrin:\n ind = substrin.index(S[i])\n max_len_substr = max(max_len_substr, len(substrin))\n substrin = substrin[ind + 1:]\n substrin.append(S[i])\n else:\n substrin.append(S[i])\n return max(max_len_substr, len(substrin))", "def longestsubstrdistinctchars(S):\n dic = {}\n maxi = 0\n start = 0\n for i in range(len(S)):\n if S[i] not in dic:\n dic[S[i]] = i\n else:\n if dic[S[i]] != -1:\n while start < dic[S[i]] + 1:\n dic[start] = -1\n start += 1\n dic[S[i]] = i\n maxi = max(maxi, i - start + 1)\n return maxi", "def longestsubstrdistinctchars(s):\n n = len(s)\n chars = set()\n start = end = max_len = 0\n while end < n:\n if s[end] not in chars:\n chars.add(s[end])\n end += 1\n max_len = max(max_len, end - start)\n else:\n chars.remove(s[start])\n start += 1\n return max_len", "def longestsubstrdistinctchars(S):\n maxi = 0\n l = []\n for i in S:\n while i in l:\n l.remove(l[0])\n l.append(i)\n if maxi < len(l):\n maxi = len(l)\n return maxi", "def longestsubstrdistinctchars(S):\n sett = set()\n result = 0\n (leftPtr, rightPtr) = (0, 0)\n for rightPtr in range(len(S)):\n while S[rightPtr] in sett:\n sett.remove(S[leftPtr])\n leftPtr += 1\n sett.add(S[rightPtr])\n result = max(result, len(sett))\n return result", "def longestsubstrdistinctchars(S):\n l = []\n d = {}\n start = 0\n r = ''\n m = 0\n i = 0\n while i < len(S):\n if S[i] not in d:\n d[S[i]] = 1\n r = r + S[i]\n m += 1\n i += 1\n else:\n l.append(m)\n j = r.index(S[i])\n i = start + j + 1\n start = i\n r = ''\n m = 0\n d = {}\n l.append(m)\n if l == []:\n return m\n return max(l)", "def longestsubstrdistinctchars(s):\n d = {}\n ws = 0\n n = len(s)\n ans = 0\n for we in range(n):\n while s[we] in d:\n d[s[ws]] -= 1\n if d[s[ws]] == 0:\n del d[s[ws]]\n ws += 1\n d[s[we]] = 1\n ans = max(ans, we - ws + 1)\n return ans", "def longestsubstrdistinctchars(S):\n hashmap = {}\n left = 0\n right = 0\n i = -1\n j = -1\n max_len = -int(1000000000.0)\n while right < len(S):\n if S[right] not in hashmap:\n hashmap[S[right]] = 1\n else:\n while left <= right and S[right] in hashmap and (hashmap[S[right]] == 1):\n hashmap[S[left]] -= 1\n if hashmap[S[left]] == 0:\n del hashmap[S[left]]\n left += 1\n hashmap[S[right]] = 1\n if i == -1 and j == -1:\n i = left\n j = right\n elif j - i < right - left:\n i = left\n j = right\n max_len = max(max_len, j - i + 1)\n right += 1\n return max_len", "def longestsubstrdistinctchars(S):\n (window_start, max_len, last_char_index_map) = (0, 0, {})\n for window_end in range(len(S)):\n if S[window_end] in last_char_index_map:\n window_start = max(window_start, last_char_index_map[S[window_end]] + 1)\n last_char_index_map[S[window_end]] = window_end\n max_len = max(max_len, window_end - window_start + 1)\n return max_len", "def longestsubstrdistinctchars(S):\n dict1 = {}\n l = 0\n size = 0\n j = 0\n for i in range(len(S)):\n if S[i] in dict1:\n while S[i] in dict1:\n del dict1[S[j]]\n j += 1\n size -= 1\n dict1[S[i]] = 1\n size += 1\n else:\n dict1[S[i]] = 1\n size += 1\n if size > l:\n l = size\n return l", "def longestsubstrdistinctchars(S):\n windowStart = 0\n maxCount = 0\n hashSet = set()\n for i in range(len(S)):\n while S[i] in hashSet:\n hashSet.remove(S[windowStart])\n windowStart += 1\n hashSet.add(S[i])\n maxCount = max(maxCount, i - windowStart + 1)\n return maxCount", "def check(ar, i, j):\n dic = {}\n while j < len(ar):\n if ar[j] not in dic:\n dic[ar[j]] = 1\n else:\n break\n j += 1\n return len(dic)\n\ndef longestsubstrdistinctchars(S):\n i = 0\n ar = list(S)\n ans = 0\n while i < len(S):\n k = self.check(ar, i, i)\n ans = max(k, ans)\n i += 1\n return ans", "def longestsubstrdistinctchars(S):\n start = end = max_len = 0\n char_dict = {}\n for (i, c) in enumerate(S):\n if c in char_dict and char_dict[c] >= start:\n max_len = max(max_len, end - start)\n start = char_dict[c] + 1\n char_dict[c] = i\n end += 1\n return max(max_len, end - start)", "def longestsubstrdistinctchars(S):\n (a, maxa, i) = ('', '', 0)\n while i < len(S):\n if S[i] not in a:\n a += S[i]\n if len(a) >= len(maxa):\n maxa = a\n else:\n if len(a) >= len(maxa):\n maxa = a\n if i > 0 and S[i - 1] == S[i]:\n a = S[i]\n else:\n l = -1\n s = []\n r = a.index(S[i])\n for _ in range(S.count(a)):\n l = S.index(a, l + 1)\n s.append(l)\n if len(s) > 1:\n s = [j for j in s if j < i]\n i = r + s[-1]\n a = ''\n i += 1\n return len(maxa)", "def longestsubstrdistinctchars(S):\n left = 0\n res = 0\n cur = set()\n for right in range(len(S)):\n while S[right] in cur:\n cur.remove(S[left])\n left += 1\n cur.add(S[right])\n res = max(res, right - left + 1)\n return res", "def isValid(arr, i):\n seen = {}\n while i < len(arr):\n if arr[i] not in seen:\n seen[arr[i]] = 1\n else:\n break\n i += 1\n return len(seen)\n\ndef longestsubstrdistinctchars(arr):\n i = 0\n ans = 0\n while i < len(arr):\n k = isValid(arr, i)\n ans = max(k, ans)\n i += 1\n return ans", "def longestsubstrdistinctchars(s):\n (l, ml, i, n) = (0, 0, 0, len(s))\n while i < n - l:\n l = 0\n alfa = {}\n for j in range(i, n):\n if s[j] in alfa:\n ml = max(l, ml)\n break\n else:\n alfa.update({s[j]: j})\n l += 1\n i = alfa[s[j]] + 1\n return max(ml, l)", "def longestsubstrdistinctchars(S):\n s = ''\n m1 = -1\n if len(S) == 0:\n return 0\n elif len(S) == 1:\n return 1\n for i in list(S):\n ans = ''.join(i)\n if ans in s:\n s = s[s.index(ans) + 1:]\n s += ''.join(i)\n m1 = max(len(s), m1)\n return m1", "def longestsubstrdistinctchars(S):\n a = []\n maxm = 0\n if len(S) == 1:\n return 1\n for i in S:\n if i not in a:\n a.append(i)\n else:\n if maxm < len(a):\n maxm = len(a)\n c = a.index(i)\n a = a[c + 1:]\n a.append(i)\n if maxm < len(a):\n return len(a)\n return maxm", "def longestsubstrdistinctchars(S):\n n = len(S)\n if n == 0:\n return 0\n longest_substring = ''\n current_substring = ''\n for i in range(n):\n if S[i] not in current_substring:\n current_substring += S[i]\n if len(current_substring) > len(longest_substring):\n longest_substring = current_substring\n else:\n current_substring = current_substring[current_substring.index(S[i]) + 1:] + S[i]\n return len(longest_substring)", "def longestsubstrdistinctchars(S):\n st = 0\n occ = {}\n max_len = 0\n for i in range(0, len(S)):\n if S[i] in occ.keys():\n st = max(st, occ[S[i]] + 1)\n occ[S[i]] = i\n max_len = max(max_len, i - st + 1)\n return max_len", "def longestsubstrdistinctchars(S):\n (i, j, k, max_ln, n) = (0, 0, 1, 0, len(S))\n while k < n and j < n:\n if S[k] in S[i:j + 1]:\n i += 1\n (j, k) = (i, i + 1)\n else:\n j += 1\n k += 1\n length = len(S[i:j + 1])\n max_ln = max(max_ln, length)\n return max_ln", "def longestsubstrdistinctchars(S):\n (l, l1) = ([], [])\n s1 = ''\n for i in range(len(S)):\n s1 = S[i]\n for j in range(i + 1, len(S)):\n if S[j] not in s1:\n if S[j] != S[i]:\n s1 += S[j]\n else:\n break\n else:\n break\n l.append(s1)\n continue\n for i in l:\n l1.append(len(i))\n return max(l1)", "def longestsubstrdistinctchars(S):\n (i, j, ans, n) = (0, 0, 0, len(S))\n mp = dict()\n while j < n:\n while S[j] in mp:\n mp.pop(S[i])\n i += 1\n if S[j] not in mp:\n mp[S[j]] = 1\n ans = max(ans, j - i + 1)\n j += 1\n return ans", "def longestsubstrdistinctchars(S):\n n = len(S)\n start = 0\n end = 0\n max_length = 0\n char_set = set()\n while end < n:\n if S[end] not in char_set:\n char_set.add(S[end])\n end += 1\n max_length = max(max_length, end - start)\n else:\n char_set.remove(S[start])\n start += 1\n return max_length", "def longestsubstrdistinctchars(S):\n (i, j) = (0, 0)\n s = set()\n n = len(S)\n maxi = 0\n while j < n:\n while S[j] in s:\n s.remove(S[i])\n i += 1\n s.add(S[j])\n maxi = max(maxi, j - i + 1)\n j += 1\n return maxi", "def longestsubstrdistinctchars(s):\n mp = {}\n (i, j) = (0, 0)\n (count, ans) = (0, -1)\n while j < len(s):\n count += 1\n if s[j] in mp:\n mp[s[j]] += 1\n else:\n mp[s[j]] = 1\n if len(mp) == j - i + 1:\n ans = max(ans, count)\n j += 1\n elif len(mp) < j - i + 1:\n while len(mp) < j - i + 1:\n mp[s[i]] -= 1\n count -= 1\n if mp[s[i]] == 0:\n del mp[s[i]]\n i += 1\n j += 1\n return ans", "from collections import defaultdict\n\ndef longestsubstrdistinctchars(S):\n freq = defaultdict(lambda : 0)\n l = r = 0\n m = 0\n while r < len(S):\n freq[S[r]] += 1\n while r < len(S) and freq[S[r]] > 1:\n freq[S[l]] -= 1\n l += 1\n m = max(m, r - l + 1)\n r += 1\n return m", "def longestsubstrdistinctchars(S):\n n = len(S)\n if len(S) == 0:\n return 0\n left = 0\n right = 0\n maxlen = 0\n l = set()\n while right < n:\n if S[right] not in l:\n l.add(S[right])\n right = right + 1\n maxlen = max(maxlen, len(l))\n else:\n l.remove(S[left])\n left = left + 1\n return maxlen", "def longestsubstrdistinctchars(S):\n left = 0\n n = len(S)\n maxLength = 0\n dic = dict()\n for right in range(n):\n if S[right] in dic and dic[S[right]] >= left:\n left = dic[S[right]] + 1\n dic[S[right]] = right\n maxLength = max(maxLength, right - left + 1)\n return maxLength", "def longestsubstrdistinctchars(S):\n n = len(S)\n max_len = 0\n left = 0\n char_dict = {}\n for right in range(n):\n if S[right] in char_dict and char_dict[S[right]] >= left:\n left = char_dict[S[right]] + 1\n char_dict[S[right]] = right\n max_len = max(max_len, right - left + 1)\n return max_len", "def longestsubstrdistinctchars(S):\n res = 0\n m = 0\n x = [i for i in S]\n d = {}\n for i in range(len(x)):\n if x[i] in d:\n res = max(d[x[i]] + 1, res)\n m = max(m, i - res + 1)\n d[x[i]] = i\n return m", "def longestsubstrdistinctchars(s):\n max_length = 0\n for i in range(len(s)):\n seen = set()\n for j in range(i, len(s)):\n if s[j] in seen:\n break\n else:\n seen.add(s[j])\n max_length = max(max_length, len(seen))\n return max_length", "def longestsubstrdistinctchars(S):\n test = ''\n maxlen = -1\n if len(S) == 0:\n return 0\n if len(S) == 1:\n return 1\n for i in list(S):\n current = ''.join(i)\n if current in test:\n test = test[test.index(i) + 1:]\n test = test + ''.join(i)\n maxlen = max(len(test), maxlen)\n return maxlen", "def longestsubstrdistinctchars(s):\n n = len(s)\n dic = {}\n ans = 0\n i = j = 0\n while j < n:\n if s[j] not in dic:\n dic[s[j]] = j\n else:\n ans = max(ans, j - i)\n while s[j] in dic:\n del dic[s[i]]\n i += 1\n dic[s[j]] = j\n j += 1\n if j == n and s[j - 1] in dic:\n ans = max(ans, j - i)\n return ans", "def longestsubstrdistinctchars(s):\n i = 0\n temp = ''\n n = len(s)\n maxi = 0\n d = {}\n while i < n:\n if s[i] not in temp:\n temp += s[i]\n i += 1\n else:\n maxi = max(maxi, len(temp))\n temp = ''\n i = d[s[i]] + 1\n d[s[i - 1]] = i - 1\n else:\n maxi = max(maxi, len(temp))\n return maxi", "def longestsubstrdistinctchars(s):\n i = 0\n j = 0\n k = 1\n m = 0\n n = len(S)\n while k < n and j < n:\n if s[k] in s[i:j + 1]:\n i += 1\n j = i\n k = i + 1\n else:\n j += 1\n k += 1\n l = len(S[i:j + 1])\n m = max(m, l)\n return m", "def longestsubstrdistinctchars(S):\n d = ''\n temp = ''\n for i in S:\n if i not in temp:\n temp += i\n else:\n if len(d) < len(temp):\n d = temp\n j = temp.find(i)\n temp = temp[j + 1:] + i\n if len(d) < len(temp):\n return len(temp)\n return len(d)", "def longestsubstrdistinctchars(S):\n vla = {}\n mx = 0\n st = 0\n i = 0\n while i < len(S):\n if S[i] not in vla:\n vla[S[i]] = i\n i += 1\n else:\n mx = max(mx, i - st)\n st = vla[S[i]] + 1\n vla.clear()\n i = st\n if i >= len(S) - 1:\n return max(mx, i - st)\n return mx", "def longestsubstrdistinctchars(S):\n ans = 0\n curr = ''\n for i in S:\n if i not in curr:\n curr += i\n else:\n ans = max(len(curr), ans)\n curr = curr[curr.index(i) + 1:] + i\n return max(len(curr), ans)", "import math\n\ndef longestsubstrdistinctchars(s):\n maxi = -math.inf\n (i, j) = (0, 0)\n dicti = {}\n n = len(s)\n while j < n:\n if s[j] not in dicti:\n dicti[s[j]] = 1\n else:\n dicti[s[j]] += 1\n if len(dicti) < j - i + 1:\n while len(dicti) < j - i + 1:\n if s[i] in dicti:\n dicti[s[i]] -= 1\n if dicti[s[i]] == 0:\n del dicti[s[i]]\n i += 1\n j += 1\n elif len(dicti) == j - i + 1:\n maxi = max(maxi, j - i + 1)\n j += 1\n return maxi", "def longestsubstrdistinctchars(S):\n a = [-1] * 256\n start = -1\n ans = 0\n for i in range(0, len(S)):\n if a[ord(S[i]) - ord('a')] > start:\n start = a[ord(S[i]) - ord('a')]\n a[ord(S[i]) - ord('a')] = i\n ans = max(ans, i - start)\n return ans", "def longestsubstrdistinctchars(S):\n ans = 0\n n = len(S)\n for i in range(0, n):\n tem = ''\n c = 0\n for j in range(i, n):\n if S[j] in tem:\n ans = max(ans, c)\n break\n else:\n c = c + 1\n tem = tem + S[j]\n ans = max(ans, c)\n return ans", "def longestsubstrdistinctchars(S):\n w = set()\n maxLen = 0\n l = 0\n for r in range(len(S)):\n while S[r] in w:\n w.remove(S[l])\n l += 1\n maxLen = max(maxLen, r - l + 1)\n w.add(S[r])\n return maxLen", "def longestsubstrdistinctchars(S):\n last_idx = {}\n max_len = 0\n start_idx = 0\n for i in range(0, len(S)):\n if S[i] in last_idx:\n start_idx = max(start_idx, last_idx[S[i]] + 1)\n max_len = max(max_len, i - start_idx + 1)\n last_idx[S[i]] = i\n return max_len", "def longestsubstrdistinctchars(S):\n n = len(S)\n last = {}\n max_len = 0\n start = 0\n for i in range(0, n):\n if S[i] in last:\n start = max(start, last[S[i]] + 1)\n max_len = max(max_len, i - start + 1)\n last[S[i]] = i\n return max_len", "def longestsubstrdistinctchars(s):\n max_length = 0\n start = 0\n d = {}\n for i in range(len(s)):\n if s[i] in d:\n while start < i:\n if s[start] == s[i]:\n del d[s[start]]\n start += 1\n break\n else:\n del d[s[start]]\n start += 1\n d[s[i]] = d.get(s[i], 0) + 1\n max_length = max(max_length, i - start + 1)\n return max_length", "def longestsubstrdistinctchars(S):\n f = {}\n start = 0\n end = 0\n maxlen = 0\n n = len(S)\n while end < n:\n f[S[end]] = f.get(S[end], 0) + 1\n if len(f) == end - start + 1:\n maxlen = max(maxlen, end - start + 1)\n else:\n while len(f) != end - start + 1:\n f[S[start]] -= 1\n if f[S[start]] == 0:\n f.pop(S[start])\n start += 1\n end += 1\n return maxlen", "def longestsubstrdistinctchars(S):\n if not S:\n return 0\n max_len = 0\n start = 0\n char_map = {}\n for i in range(len(S)):\n if S[i] in char_map and char_map[S[i]] >= start:\n start = char_map[S[i]] + 1\n else:\n max_len = max(max_len, i - start + 1)\n char_map[S[i]] = i\n return max_len", "def longestsubstrdistinctchars(S):\n if len(S) == 0:\n return 0\n n = len(S)\n s = set()\n s.add(S[0])\n leng = 1\n Max_Len = 0\n i = 1\n while i < n:\n if S[i] != S[i - 1] and S[i] not in s:\n s.add(S[i])\n leng += 1\n i += 1\n if leng > Max_Len:\n Max_Len = leng\n elif leng == 1:\n i += 1\n else:\n s.clear()\n i = i - leng + 1\n leng = 0\n return max(Max_Len, leng)", "def longestsubstrdistinctchars(S):\n dict1 = {}\n count = 1\n maxi = 1\n for k in S:\n if k not in dict1.keys():\n dict1[k] = 1\n dict1 = dict.fromkeys(dict1, 0)\n for i in range(len(S)):\n dict1[S[i]] = 1\n j = i + 1\n while j < len(S):\n if dict1[S[j]] == 1:\n dict1 = dict.fromkeys(dict1, 0)\n count = 1\n break\n else:\n dict1[S[j]] = 1\n count += 1\n maxi = max(maxi, count)\n j += 1\n return maxi", "def longestsubstrdistinctchars(S):\n s = ''\n a = []\n for i in range(len(S)):\n if s == '':\n s += S[i]\n for j in range(i + 1, len(S)):\n if S[j] in s:\n a.append(s)\n s = ''\n break\n else:\n s += S[j]\n return len(max(a, key=len))"], "starter_code": "def longestsubstrdistinctchars(S):\n", "input_output": {"inputs": ["S = \"geeksforgeeks\"", "S = \"aaa\""], "outputs": ["7", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/longest-distinct-characters-in-string5848/1", "Expected Auxiliary Space": "O(K), where K is Constant.", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|).", "entry_point": "longestsubstrdistinctchars", "task_id": "TACO_lite/320", "example": [[["geeksforgeeks"], ["aaa"]], ["7", "1"]]} +{"requirement": "Count the given numbers on your fingers and find the correct finger on which the number ends.\n\tThe first number starts from the thumb, second on the index finger, third on the middle finger, fourth on the ring finger and fifth on the little finger.\n\tAgain six comes on the ring finger and so on.\n\t\nExample 1:\nInput:\nN = 3\nOutput:\n3\nExplanation:\n3 ends on the finger 3.\nExample 2:\nInput:\nN = 6\nOutput:\n4\nExplanation:\n6 ends on the finger 4.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function fingerCount() which takes an integer N as input parameter and returns the finger number on which this number ends.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 10^6", "solutions": ["def fingercount(N):\n rem = N % 8\n if not rem:\n return 2\n if rem <= 5:\n return rem\n else:\n return 5 - rem % 5", "def fingercount(N):\n if N % 8 == 1 or N % 8 == 9:\n return 1\n elif N % 8 == 2 or N % 8 == 8:\n return 2\n elif N % 8 == 3 or N % 8 == 7:\n return 3\n elif N % 8 == 4 or N % 8 == 6:\n return 4\n elif N % 8 == 5 or N % 8 == 13:\n return 5\n elif N % 8 == 0:\n return 2", "def fingercount(N):\n r = N % 8\n if not r:\n return 2\n elif r <= 5:\n return r\n else:\n return 5 - r % 5", "def fingercount(n):\n l = [1, 2, 3, 4, 5, 4, 3, 2]\n ans = n\n k = 0\n ans = ans // 8\n for i in range(0, 8):\n if 8 * ans + i == n:\n return l[i - 1]", "def fingercount(N):\n r = N % 8\n if r == 0:\n return 2\n if r < 5:\n return r\n else:\n return 10 - r", "def fingercount(N):\n n = N % 8\n if n < 6 and n > 0:\n return n\n elif n == 6:\n return 4\n elif n == 7:\n return 3\n elif n == 0:\n return 2", "def fingercount(N):\n if N <= 5:\n return N\n elif N == 6:\n return 4\n elif N == 7:\n return 3\n elif N % 8 == 0:\n return 2\n else:\n x = N % 8\n if x > 5:\n return 5 - (x - 5)\n else:\n return x", "def fingercount(n):\n if n >= 9:\n ans = (n - 9) % 8\n if ans % 8 == 0:\n return 1\n elif ans % 8 == 1 or ans % 8 == 7:\n return 2\n elif ans % 8 == 2 or ans % 8 == 6:\n return 3\n elif ans % 8 == 3 or ans % 8 == 5:\n return 4\n elif ans % 8 == 4:\n return 5\n else:\n ans = n - 1\n if ans % 8 == 0:\n return 1\n elif ans % 8 == 1 or ans % 8 == 7:\n return 2\n elif ans % 8 == 2 or ans % 8 == 6:\n return 3\n elif ans % 8 == 3 or ans % 8 == 5:\n return 4\n elif ans % 8 == 4:\n return 5", "def fingercount(n):\n if n <= 5:\n fingpos = n\n else:\n q = (n - 5) // 4\n rem = (n - 5) % 4\n if q % 2 == 0:\n if rem == 0:\n fingpos = self.odd[3]\n else:\n fingpos = self.even[rem - 1]\n elif rem == 0:\n fingpos = self.even[3]\n else:\n fingpos = self.odd[rem - 1]\n return fingpos", "def fingercount(N):\n if n <= 5:\n return n\n elif (n - 5) % 8 == 1 or (n - 5) % 8 == 7:\n return 4\n elif (n - 5) % 8 == 2 or (n - 5) % 8 == 6:\n return 3\n elif (n - 5) % 8 == 3 or (n - 5) % 8 == 5:\n return 2\n elif (n - 5) % 8 == 4:\n return 1\n else:\n return 5", "def fingercount(N):\n c = 0\n d = N % 8\n if d == 1:\n c = 1\n if d == 0 or d == 2:\n c = 2\n if d == 3 or d == 7:\n c = 3\n if d == 4 or d == 6:\n c = 4\n if d == 5:\n c = 5\n return c", "def fingercount(N):\n N = N % 16\n if N == 1 or N == 9:\n return 1\n if N in [0, 2, 8, 10]:\n return 2\n if N in [3, 7, 11, 15]:\n return 3\n if N in [5, 13]:\n return 5\n if N in [4, 6, 12, 14]:\n return 4", "def fingercount(N):\n finger = N % 8\n if finger >= 6:\n finger = 10 - finger\n elif finger == 0:\n finger = 2\n return finger", "def fingercount(N):\n if N <= 8:\n if N <= 5:\n return N\n else:\n return 10 - N\n else:\n if N % 8 == 1:\n return 1\n if N % 8 == 0 or N % 8 == 2:\n return 2\n if N % 8 == 3 or N % 8 == 7:\n return 3\n if N % 8 == 4 or N % 8 == 6:\n return 4\n if N % 8 == 5:\n return 5", "def fingercount(N):\n no = N % 8\n if no == 0:\n return 2\n elif no < 5:\n return no\n else:\n return 10 - no", "def fingercount(N):\n finger = {0: 2, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 4, 7: 3, 8: 2}\n N %= 8\n return finger[N]", "def fingercount(N):\n round = 0\n temp = N\n if temp < 5:\n return temp\n while temp > 0:\n if round % 2 == 0 and temp >= 5:\n temp = temp - 5\n round += 1\n elif round % 2 == 1 and temp >= 3:\n temp = temp - 3\n round += 1\n else:\n break\n if temp == 0:\n if round % 2 == 1:\n return 5\n else:\n return 2\n elif round % 2 == 1:\n return 5 - temp\n else:\n return temp", "def fingercount(N):\n rem = n % 8\n if rem == 0:\n return 2\n elif rem < 5:\n return rem\n else:\n return 10 - rem", "def fingercount(N):\n rem = N % 8\n if rem == 0 or rem == 2:\n return 2\n elif rem <= 5:\n return rem\n else:\n return 5 - rem % 5", "def fingercount(N):\n a = [4, 3, 2, 1]\n n = (N - 2) // 4\n if n % 2 == 0:\n return (N - 2) % 4 + 2\n else:\n return a[(N - 2) % 4]", "def fingercount(N):\n l1 = [1, 9, 17, 25, 33, 41]\n l2 = [2, 8, 10, 16, 18, 24, 26, 32, 34]\n l3 = [3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43]\n l4 = [4, 6, 12, 14, 20, 22, 28, 30, 36]\n l5 = [5, 13, 21, 29, 37, 45, 53]\n if N % 8 == 1:\n return 1\n elif N % 8 == 0 or N % 8 == 2:\n return 2\n elif N % 8 == 3 or N % 8 == 7:\n return 3\n elif N % 8 == 4 or N % 8 == 6:\n return 4\n elif N % 8 == 5:\n return 5", "def fingercount(N):\n m = N % 8\n if m >= 1 and m <= 5:\n return m\n elif m == 0:\n return 2\n elif m == 7:\n return 3\n elif m == 6:\n return 4", "def fingercount(N):\n t = N % 8\n if t == 0:\n return 2\n if t == 7:\n return 3\n if t == 6:\n return 4\n return t", "def fingercount(N):\n if N <= 5:\n return N\n res1 = (N - 1) / 8 + 1\n if res1 == float(int(res1)):\n return 1\n res1 = (N - 2) / 8 + 1\n res2 = (N - 8) / 8 + 1\n if res1 == float(int(res1)) or res2 == float(int(res2)):\n return 2\n res1 = (N - 3) / 4 + 1\n if res1 == float(int(res1)):\n return 3\n res1 = (N - 4) / 8 + 1\n res2 = (N - 6) / 8 + 1\n if res1 == float(int(res1)) or res2 == float(int(res2)):\n return 4\n res1 = (N - 5) / 8 + 1\n if res1 == float(int(res1)):\n return 5", "def fingercount(N):\n temp = [1, 2, 3, 4, 5, 4, 3, 2]\n return temp[(N - 1) % 8]"], "starter_code": "def fingercount(N):\n", "input_output": {"inputs": ["N = 3", "N = 6"], "outputs": ["3", "4"]}, "difficulty": "EASY", "raw_tags": ["logical-thinking"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/finger-game1755/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "fingercount", "task_id": "TACO_lite/253", "example": [[[3], [6]], ["3", "4"]]} +{"requirement": "Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return `true` if the string is valid, and `false` if it's invalid.\n\n## Examples\n\n```\n\"()\" => true\n\")(()))\" => false\n\"(\" => false\n\"(())((()())())\" => true\n```\n\n## Constraints\n\n`0 <= input.length <= 100`\n\n~~~if-not:javascript,go\nAlong with opening (`(`) and closing (`)`) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all. Do **not** treat other forms of brackets as parentheses (e.g. `[]`, `{}`, `<>`).\n~~~", "solutions": ["def valid_parentheses(string):\n cnt = 0\n for char in string:\n if char == '(':\n cnt += 1\n if char == ')':\n cnt -= 1\n if cnt < 0:\n return False\n return True if cnt == 0 else False", "def valid_parentheses(string):\n count = 0\n for i in string:\n if i == '(':\n count += 1\n elif i == ')':\n count -= 1\n if count < 0:\n return False\n return count == 0", "iparens = iter('(){}[]<>')\nparens = dict(zip(iparens, iparens))\nclosing = parens.values()\n\ndef valid_parentheses(astr):\n stack = []\n for c in astr:\n d = parens.get(c, None)\n if d:\n stack.append(d)\n elif c in closing:\n if not stack or c != stack.pop():\n return False\n return not stack", "def valid_parentheses(symbol_string):\n stack = Stack()\n for char in symbol_string:\n if char == '(':\n stack.push('(')\n elif char == ')':\n if stack.is_empty():\n return False\n else:\n stack.pop()\n if not stack.is_empty():\n return False\n else:\n return True\n\ndef __init__():\n self.items = []\n\ndef push(item):\n self.items.append(item)\n\ndef pop():\n return self.items.pop()\n\ndef peek():\n return self.items[-1]\n\ndef is_empty():\n return self.items == []\n\ndef size():\n return len(self.items)", "def valid_parentheses(string):\n string = ''.join((ch for ch in string if ch in '()'))\n while '()' in string:\n string = string.replace('()', '')\n return not string", "import re\n_regex = '[^\\\\(|\\\\)]'\n\ndef valid_parentheses(string):\n string = re.sub(_regex, '', string)\n while len(string.split('()')) > 1:\n string = ''.join(string.split('()'))\n return string == ''", "def valid_parentheses(s):\n stack = 0\n for char in s:\n if char == '(':\n stack += 1\n if char == ')':\n if not stack:\n return False\n else:\n stack -= 1\n return not stack", "import re\n\ndef valid_parentheses(s):\n try:\n re.compile(s)\n except:\n return False\n return True", "def valid_parentheses(s):\n b = 0\n for c in s:\n if c == '(':\n b += 1\n if c == ')':\n b -= 1\n if b < 0:\n return False\n return b == 0", "def valid_parentheses(string):\n stack = []\n for i in string:\n if i == '(':\n stack.append(i)\n elif i == ')' and (not stack):\n return False\n elif i == ')':\n stack.pop()\n return not stack", "def valid_parentheses(string):\n open_counter = 0\n for i in string:\n if i == '(':\n open_counter = open_counter + 1\n if i == ')':\n open_counter = open_counter - 1\n if open_counter < 0:\n return False\n if open_counter == 0:\n return True\n return False", "def valid_parentheses(string):\n new = ''.join([i for i in string if i in '()'])\n while '()' in new:\n new = new.replace('()', '')\n return len(new) == 0", "def valid_parentheses(string):\n string = ''.join([x for x in string if x == '(' or x == ')'])\n before_reduce = len(string)\n string = string.replace('()', '')\n if string == '':\n return True\n elif before_reduce != len(string):\n return valid_parentheses(string)\n else:\n return False", "def valid_parentheses(string):\n string = ''.join((x for x in string if x in ('(', ')')))\n while '()' in string:\n string = string.replace('()', '')\n return False if len(string) != 0 else True", "def valid_parentheses(string):\n string = ''.join((i for i in string if i == '(' or i == ')'))\n while '()' in string:\n string = string.replace('()', '')\n return string == ''", "def valid_parentheses(string):\n string = [c for c in string if not c.isalpha()]\n string = ''.join(string)\n while '()' in string:\n string = string.replace('()', '')\n return True if len(string) == 0 else False", "def valid_parentheses(s):\n p = '()'\n s = ''.join([e for e in s if e in '()'])\n while p in s:\n s = s.replace(p, '')\n return not s", "def valid_parentheses(string):\n open = 0\n for c in string:\n if c == '(':\n open += 1\n elif c == ')':\n open -= 1\n if open < 0:\n return False\n return open == 0", "def valid_parentheses(string):\n i = 0\n for c in string:\n if c == '(':\n i += 1\n if c == ')':\n i -= 1\n if i < 0:\n return False\n return i == 0", "def valid_parentheses(string):\n count = 0\n for c in [c for c in string if c in '()']:\n count += 1 if c == '(' else -1\n if count < 0:\n return False\n return count == 0", "def valid_parentheses(string):\n string = ''.join([x for x in string if x in '()'])\n try:\n string = string.replace('()', '')\n return valid_parentheses(string) if string else True\n except:\n return False", "def valid_parentheses(s):\n lvl = 0\n for c in s:\n lvl += (c == '(') - (c == ')')\n if lvl < 0:\n return False\n return not lvl", "def valid_parentheses(string):\n depth = 0\n for i in string:\n if i == '(':\n depth += 1\n elif i == ')':\n depth -= 1\n if depth < 0:\n return False\n if depth == 0:\n return True\n else:\n return False", "def valid_parentheses(string):\n count_open = 0\n count_close = 0\n index_open = 0\n index_closed = 0\n for s in string:\n if s == '(':\n count_open += 1\n elif s == ')':\n count_close += 1\n if count_close > count_open:\n return False\n if count_open != count_close:\n return False\n else:\n return True", "import re\n\ndef valid_parentheses(string):\n s = ''.join([i for i in string if i in '()'])\n total = [string]\n while True:\n s = s.replace('()', '')\n total.append(s)\n if total[-1] == total[-2]:\n break\n return True if total[-1] == '' else False", "def valid_parentheses(string):\n str = string\n if str == '':\n return True\n if len(str) > 100:\n str = str[0:100]\n c_open = 0\n exc = 0\n for c in str:\n if c == '(':\n c_open += 1\n if c == ')':\n c_open -= 1\n if c_open < 0:\n exc = 1\n break\n if exc == 1 or c_open != 0:\n return False\n return True", "def valid_parentheses(string):\n counter = 0\n for i in string:\n if i == '(':\n counter += 1\n if i == ')':\n counter -= 1\n if counter < 0:\n return False\n return counter == 0"], "starter_code": "def valid_parentheses(string):\n", "input_output": {"fn_name": "valid_parentheses", "inputs": [[")"], ["("], [""], ["hi)("], ["hi(hi)"], ["hi(hi)("], ["((())()())"], ["(c(b(a)))(d)"], ["hi(hi))("], ["())(()"]], "outputs": [[false], [false], [true], [false], [true], [false], [true], [true], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/52774a314c2333f0a7000688", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "valid_parentheses", "task_id": "TACO_lite/273", "example": [[], []]} +{"requirement": "Given a rectangle of dimensions L x B find the minimum number (N) of identical squares of maximum side that can be cut out from that rectangle so that no residue remains in the rectangle. Also find the dimension K of that square.\nExample 1:\nInput: L = 2, B = 4\nOutput: N = 2, K = 2\nExplaination: 2 squares of 2x2 dimension.\nExample 2:\nInput: L = 6, B = 3\nOutput: N = 2, K = 3\nExplaintion: 2 squares of 3x3 dimension. \nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function minimumSquares() which takes L and B as input parameters and returns a list of 2 integers containing the values of N and K respectively.\nExpected Time Complexity: O(log min(L, B))\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 L, B \u2264 10^{9}", "solutions": ["import math\n\ndef minimumsquares(L, B):\n a = math.gcd(L, B)\n return (L * B // (a * a), a)", "import math\n\ndef minimumsquares(L, B):\n gcd = math.gcd(L, B)\n k = gcd\n n = L * B // (k * k)\n return (n, k)", "def gcd(a, b):\n if b > a:\n (a, b) = (b, a)\n if b == 0:\n return a\n return gcd(a % b, b)\n\ndef minimumsquares(L, B):\n l = L\n b = B\n ans = 0\n mx = max(l, b)\n mn = min(l, b)\n if mx % mn == 0:\n return [mx // mn, mn]\n else:\n g = gcd(mx, mn)\n return [mx * mn // (g * g), g]", "def minimumsquares(l, b):\n\n def gcd(l, b):\n if b == 0:\n return l\n return gcd(b, l % b)\n i = gcd(l, b)\n return [l // i * b // i, i]", "def minimumsquares(L, B):\n li = []\n l = L\n b = B\n while b:\n (l, b) = (b, l % b)\n li.append(int(L * B / l ** 2))\n li.append(l)\n return li", "def minimumsquares(L, B):\n temp = min(L, B)\n temp1 = max(L, B)\n\n def gcd(small, big):\n if big % small == 0:\n return small\n else:\n return gcd(big % small, small)\n var = gcd(temp, temp1)\n ans = L * B // (var * var)\n return (ans, var)", "import math\n\ndef minimumsquares(L, B):\n arr = []\n mini = min(L, B)\n for i in range(1, math.floor(math.sqrt(mini)) + 1):\n if mini % i == 0:\n arr.append(i)\n if mini // i != i:\n arr.append(mini // i)\n n = L * B\n k = 1\n for e in arr:\n if L * B % e ** 2 == 0 and L % e == 0 and (B % e == 0):\n temp = L * B // e ** 2\n if temp < n:\n n = temp\n k = e\n return (n, k)", "def minimumsquares(L, B):\n\n def hcf(L, B):\n if B > L:\n (L, B) = (B, L)\n while B:\n (L, B) = (B, L % B)\n return L\n k = hcf(L, B)\n n = L * B // (k * k)\n return (n, k)", "def minimumsquares(l, b):\n\n def hcf(num1, num2):\n return num2 if num1 == 0 else hcf(num2 % num1, num1)\n area = l * b\n k = hcf(l, b)\n sqarea = k * k\n n = int(area / sqarea)\n return (n, k)", "def computeGCD(x, y):\n while y:\n (x, y) = (y, x % y)\n return abs(x)\n\ndef minimumsquares(L, B):\n k = self.computeGCD(L, B)\n n = L * B // (k * k)\n return (n, k)", "import math\n\ndef minimumsquares(max, min):\n res = []\n k = math.gcd(max, min)\n n = max * min // (k * k)\n return [n, k]", "def minimumsquares(L, B):\n m = self.gcd1(L, B)\n return [L * B // (m * m), m]\n\ndef gcd1(a, b):\n if a == 0 or b == 0:\n return max(a, b)\n else:\n if a < b:\n return self.gcd1(a, b % a)\n return self.gcd1(a % b, b)", "import math\n\ndef minimumsquares(L, B):\n K = math.gcd(L, B)\n return (L * B // (K * K), K)", "def minimumsquares(L, B):\n\n def hcf(x, y):\n while y:\n (x, y) = (y, x % y)\n return x\n temp = hcf(L, B)\n return [max(L, B) // temp * min(L, B) // temp, temp] if temp != 1 else [L * B, 1]", "def minimumsquares(L, B):\n A = L * B\n while L % B != 0 and B % L != 0:\n if B < L:\n L = L % B\n elif B > L:\n B = B % L\n else:\n break\n K = min(L, B)\n N = A // (K * K)\n return (N, K)", "def gcd(n, m):\n if n < m:\n (n, m) = (m, n)\n if n % m == 0:\n return m\n while m > 0:\n n = n % m\n (n, m) = (m, n)\n return n\n\ndef minimumsquares(L, B):\n (a, b) = (L, B)\n x = gcd(a, b)\n y = a * b\n y = y // (x * x)\n return [y, x]", "import math\n\ndef minimumsquares(L, B):\n x = math.gcd(L, B)\n return [L * B // (x * x), x]", "import math\n\ndef minimumsquares(L, B):\n least = math.gcd(L, B)\n return [int(L * B / (least * least)), least]", "def minimumsquares(L, B):\n\n def hcf(x, y):\n while y:\n (x, y) = (y, x % y)\n return x\n k = hcf(L, B)\n n = L * B // (k * k)\n return (n, k)", "def gcd(a, b):\n if a % b == 0:\n return b\n return self.gcd(b, a % b)\n\ndef minimumsquares(L, B):\n g = self.gcd(min(L, B), max(L, B))\n return (int(L * B / (g * g)), g)", "def gcd(a, b):\n if a < b:\n (a, b) = (b, a)\n if a % b == 0:\n return b\n return self.gcd(b, a % b)\n\ndef minimumsquares(L, B):\n return (L * B // self.gcd(L, B) ** 2, self.gcd(L, B))", "def gcd(a, b):\n if a < b:\n (a, b) = (b, a)\n if a % b == 0:\n return b\n return self.gcd(b, a % b)\n\ndef minimumsquares(L, B):\n t = min(L, B)\n k = L * B / t ** 2\n if k == int(k):\n return (int(k), t)\n else:\n return (L * B // self.gcd(L, B) ** 2, self.gcd(L, B))", "def gcd(a, b):\n if b == 0:\n return a\n return self.gcd(b, a % b)\n\ndef minimumsquares(L, B):\n ans1 = self.gcd(L, B)\n ans2 = L * B // (ans1 * ans1)\n return (ans2, ans1)", "import math\n\ndef minimumsquares(L, B):\n sq_side = math.gcd(L, B)\n return (L * B // (sq_side * sq_side), sq_side)", "def gcd(a, b):\n if b == 0:\n return a\n return Solution.gcd(b, a % b)\n\ndef minimumsquares(L, B):\n k = Solution.gcd(L, B)\n r = 0\n r = L * B // (k * k)\n return [r, k]", "def minimumsquares(L, B):\n a = L\n b = B\n while a > 0:\n (b, a) = (a, b % a)\n return (L // b * B // b, b)", "import math\n\ndef minimumsquares(l, b):\n g = math.gcd(l, b)\n ans = 0\n a = []\n while True:\n if l * b % g * g == 0:\n ans = l * b // (g * g)\n a = [ans, g]\n break\n g -= 1\n return a", "def minimumsquares(L, B):\n\n def gcd(L, B):\n if B == 0:\n return L\n return gcd(B, L % B)\n K = gcd(L, B)\n n = L * B // (K * K)\n return (n, K)", "def gcd(L1, B1):\n A = L1\n B = B1\n T = 1\n while B != 0:\n T = A % B\n A = B\n B = T\n return A\n\ndef minimumsquares(L, B):\n K = self.gcd(L, B)\n N = int(L / K * B / K)\n return (N, K)", "def compute_hcf(x, y):\n while y:\n (x, y) = (y, x % y)\n return x\n\ndef minimumsquares(L, B):\n N = 0\n K = 0\n if L > B:\n if L % B == 0:\n N = int(L / B)\n K = B\n else:\n hcf = self.compute_hcf(L, B)\n N = int(L * B / (hcf * hcf))\n K = hcf\n elif B % L == 0:\n N = int(B / L)\n K = L\n else:\n hcf = self.compute_hcf(L, B)\n N = int(L * B / (hcf * hcf))\n K = hcf\n return (N, K)", "def minimumsquares(L, B):\n\n def GCD(L, B):\n if B == 0:\n return L\n else:\n return GCD(B, L % B)\n k = GCD(L, B)\n n = int(L * B / (k * k))\n return (n, k)"], "starter_code": "def minimumsquares(L, B):\n", "input_output": {"inputs": ["L = 2, B = 4", "L = 6, B = 3"], "outputs": ["N = 2, K = 2", " N = 2, K = 3"]}, "difficulty": "EASY", "raw_tags": ["Combinatorial", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Combinatorics", "Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/cutting-rectangles3659/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log min(L, B))", "entry_point": "minimumsquares", "task_id": "TACO_lite/274", "example": [[[2, 4], [6, 3]], ["(2, 2)", "(2, 3)"]]} +{"requirement": "Your website is divided vertically in sections, and each can be of different size (height). \nYou need to establish the section index (starting at `0`) you are at, given the `scrollY` and `sizes` of all sections. \nSections start with `0`, so if first section is `200` high, it takes `0-199` \"pixels\" and second starts at `200`.\n\n### Example:\n\n`getSectionIdFromScroll( 300, [300,200,400,600,100] )`\n\nwill output number `1` as it's the second section.\n\n`getSectionIdFromScroll( 1600, [300,200,400,600,100] )`\n\nwill output number `-1` as it's past last section.\n\nGiven the `scrollY` integer (always non-negative) and an array of non-negative integers (with at least one element), calculate the index (starting at `0`) or `-1` if `scrollY` falls beyond last section (indication of an error).", "solutions": ["def get_section_id(scroll, sizes):\n c = 0\n for (idx, s) in enumerate(sizes):\n c += s\n if scroll < c:\n return idx\n return -1", "from itertools import accumulate\n\ndef get_section_id(scroll, sizes):\n return next((i for (i, x) in enumerate(accumulate(sizes)) if x > scroll), -1)", "def get_section_id(scroll, sizes):\n if scroll >= sum(sizes):\n return -1\n return sum((scroll >= sum(sizes[:i + 1]) for i in range(len(sizes))))", "from itertools import takewhile, accumulate\n\ndef get_section_id(scroll, sizes):\n return -1 if sum(sizes) <= scroll else sum((1 for _ in takewhile(scroll.__ge__, accumulate(sizes))))", "def get_section_id(scroll, sizes):\n where = 0\n for i in range(len(sizes)):\n where += sizes[i]\n if where > scroll:\n return i\n return -1", "def get_section_id(scroll, sizes):\n for (i, _) in enumerate(sizes):\n if scroll < sum(sizes[:i + 1]):\n return i\n return -1", "from bisect import bisect\nfrom itertools import accumulate\n\ndef get_section_id(scroll, sizes):\n return bisect(list(accumulate(sizes)), scroll) if scroll < sum(sizes) else -1", "def get_section_id(scroll, sizes):\n for (i, s) in enumerate(sizes):\n scroll -= s\n if scroll < 0:\n return i\n return -1", "def get_section_id(scroll, sizes):\n a = 0\n for i in sizes:\n scroll -= i\n if scroll < 0:\n return a\n a += 1\n return -1"], "starter_code": "def get_section_id(scroll, sizes):\n", "input_output": {"fn_name": "get_section_id", "inputs": [[1, [300, 200, 400, 600, 100]], [299, [300, 200, 400, 600, 100]], [300, [300, 200, 400, 600, 100]], [1599, [300, 200, 400, 600, 100]], [1600, [300, 200, 400, 600, 100]]], "outputs": [[0], [0], [1], [4], [-1]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5cb05eee03c3ff002153d4ef", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "get_section_id", "task_id": "TACO_lite/278", "example": [[[300, [300, 200, 400, 600, 100]], [1600, [300, 200, 400, 600, 100]]], ["1", "-1"]]} +{"requirement": "Write a function named sumDigits which takes a number as input and returns the sum of the absolute value of each of the number's decimal digits. For example:\n\n```python\n sum_digits(10) # Returns 1\n sum_digits(99) # Returns 18\n sum_digits(-32) # Returns 5\n```\n\nLet's assume that all numbers in the input will be integer values.", "solutions": ["def sum_digits(number):\n return sum(map(int, str(abs(number))))", "def sum_digits(n):\n return eval('+'.join(str(abs(n))))", "def sum_digits(number):\n num_string = str(abs(number))\n total = 0\n for char in num_string:\n total += int(char)\n return total", "def sum_digits(number):\n d = 0\n for c in str(abs(number)):\n d += ord(c) - 48\n return d", "sum_digits = lambda n: sum((int(e) for e in str(abs(n))))", "def sum_digits(n):\n return sum([int(x) for x in str(abs(n))])", "def sum_digits(number):\n return sum((int(ele) for ele in str(abs(number))))", "def sum_digits(number):\n return sum([int(i) for i in str(abs(number))])", "def sum_digits(number):\n inp = str(number)\n s = 0\n for x in inp:\n try:\n s += int(x)\n except:\n pass\n return s", "def sum_digits(number):\n return sum((int(digit) for digit in str(number).replace('-', '')))", "def sum_digits(number):\n sum = 0\n if number < 0:\n number = number * -1\n while len(str(number)) != 1:\n sum += number % 10\n number = number // 10\n sum += number\n return sum", "def sum_digits(number):\n sum = 0\n if len(str(number)) == 1:\n return number\n else:\n for i in range(len(str(number))):\n if str(number)[i] == '-':\n sum += 0\n else:\n sum += int(str(number)[i])\n return sum", "def sum_digits(number):\n if number < 0:\n number *= -1\n return sum(map(int, str(number)))", "def sum_digits(number):\n string = str(number)\n for char in string:\n if char == '-':\n string = string.replace(char, '')\n return sum([int(x) for x in string])", "def sum_digits(number):\n return sum((int(i) if not i == '-' else 0 for i in str(number)))", "def sum_digits(number):\n str_num = str(number)\n ret_num = 0\n for num in str_num:\n if num != '-':\n ret_num = ret_num + int(num)\n return ret_num", "def sum_digits(number):\n total = 0\n for digit in str(abs(number)):\n total += int(digit)\n return total", "def sum_digits(x):\n if len(str(x)) == 1:\n return x\n suma = 0\n for j in str(x):\n if j != '-':\n suma += int(j)\n return suma", "def sum_digits(number):\n sum = 0\n for num in str(abs(number)):\n sum += int(num)\n return sum", "def sum_digits(number):\n number = str(number)\n numT = 0\n for i in number:\n if i != '-':\n numT += int(i)\n return numT", "def sum_digits(number):\n number = abs(number)\n if number == 0:\n return 0\n return number % 10 + sum_digits(number // 10)", "def sum_digits(number):\n chars = list(str(number))\n digits = [int(char) for char in chars if char.isdigit()]\n return sum(digits)", "def sum_digits(number):\n s = 0\n n = str(number)\n for i in n:\n if i.isdigit():\n s += int(i)\n return s", "def sum_digits(number):\n kol = 0\n j = ''\n string = str(number)\n for i in string:\n j = ''\n if i == '-':\n continue\n else:\n j += i\n kol += int(j)\n return kol", "def sum_digits(number):\n sum = 0\n for char in str(number):\n if char == '-':\n continue\n else:\n sum = sum + eval(char)\n return sum", "def sum_digits(number):\n digits = list(map(str, str(number)))\n digits = [int(x) for x in digits if x.isdigit()]\n return sum(digits)", "def sum_digits(number):\n result = 0\n is_minus = False\n if number < 0:\n is_minus = True\n number = number * -1\n for element in str(number):\n result += int(element)\n return result", "def sum_digits(number):\n nr = str(number)\n total = 0\n for i in range(len(nr)):\n if nr[i].isdigit():\n total += int(nr[i])\n return total", "def sum_digits(number):\n t = 0\n for i in str(number):\n if i.isdigit():\n t = t + int(i)\n return t", "def sum_digits(number):\n luz = abs(number)\n liz = [int(x) for x in str(luz)]\n return sum(liz)", "def sum_digits(number):\n summ = 0\n number = str(number)\n for num in number:\n if num.isdigit():\n summ += int(num)\n else:\n pass\n return summ", "def sum_digits(number):\n numberList = [int(x) for x in str(abs(number))]\n return sum(numberList)", "def sum_digits(number):\n y = 0\n for x in str(number):\n if x == '-':\n pass\n else:\n y += int(x)\n return y", "def sum_digits(number):\n if number < 0:\n number *= -1\n a = str(number)\n return sum([int(i) for i in a])", "def sum_digits(number):\n if number >= 0:\n total = 0\n for i in str(number):\n total += int(i)\n return total\n else:\n total = 0\n for i in str(number)[1:]:\n total += int(i)\n return total", "def sum_digits(num):\n return sum([int(i) for i in str(num) if i.isdigit()])", "def sum_digits(number):\n result = 0\n for num in str(number):\n try:\n result += int(num)\n except:\n continue\n return result", "def sum_digits(number):\n num_str = str(abs(number))\n s = 0\n for i in num_str:\n s += int(i)\n return s", "def sum_digits(number):\n splits = list(str(number))\n num_lst = []\n for num in splits:\n try:\n if type(int(num)) == int:\n num_lst.append(int(num))\n except:\n continue\n return sum(num_lst)", "def sum_digits(number):\n num = str(abs(number))\n res = 0\n for item in num:\n res += int(item)\n return res", "def sum_digits(number):\n num = str(number)\n num = [int(x) for x in num if x != '-']\n return sum(num)", "def sum_digits(number):\n sumnumbers = 0\n for numbers in str(number.__abs__()):\n sumnumbers += int(numbers)\n return sumnumbers", "def sum_digits(number):\n n = str(abs(number))\n sum = 0\n for i in range(len(n)):\n sum += int(n[i])\n return sum", "def sum_digits(number):\n q = 0\n h = str(number.__abs__())\n for i in h:\n q += int(i)\n return q", "def sum_digits(number):\n k = sum(list(map(int, str(abs(number)))))\n return k", "def sum_digits(number):\n sum = 0\n for e in str(abs(number)):\n sum += int(e)\n return sum", "def sum_digits(number):\n if number < 0:\n number = number * -1\n total = 0\n while number > 0:\n dig = number % 10\n total += dig\n number = number // 10\n return total", "def sum_digits(number):\n my_sum = 0\n number = abs(number)\n while number >= 10:\n my_sum = my_sum + number % 10\n number = int(number / 10)\n my_sum = my_sum + number\n return my_sum", "def sum_digits(number):\n sum_digits = 0\n number2 = abs(number)\n for i in str(number2):\n sum_digits += int(i)\n return sum_digits", "def sum_digits(number):\n num = str(number)\n num = num.lstrip('-')\n result = 0\n for i in num:\n result += int(i)\n return result", "def sum_digits(number):\n sum = 0\n while abs(number) // 10 != 0:\n sum += abs(number) % 10\n number = abs(number) // 10\n sum += abs(number) % 10\n return sum", "def sum_digits(number):\n number = abs(number)\n number = str(number)\n sum_num = 0\n for i in number:\n i = int(i)\n sum_num = sum_num + i\n return sum_num", "def sum_digits(number):\n absNum = number if number > 0 else -number\n strList = list(str(absNum))\n return sum(map(lambda x: int(x), strList))", "def sum_digits(number):\n abs_value = 0\n numbers = map(int, str(number).strip('-'))\n for i in numbers:\n abs_value += i\n return abs_value", "def sum_digits(number):\n count = 0\n number = abs(number)\n for num in str(number):\n count = count + int(num)\n return count", "def sum_digits(number):\n if number < 0:\n number *= -1\n if number < 10:\n return number\n else:\n last_digit = number % 10\n return sum_digits(number // 10) + last_digit", "def sum_digits(number):\n sn = str(number)\n rez = 0\n for i in sn:\n if i.isnumeric():\n rez += int(i)\n return rez", "def sum_digits(number):\n naked = str(number).strip('-')\n return sum((int(digit) for digit in naked))", "import numpy as np\n\ndef sum_digits(number):\n number = int(np.sqrt(number ** 2))\n return sum([int(d) for d in str(number)])", "def sum_digits(num):\n sum = 0\n for x in str(abs(num)):\n sum += int(x)\n return sum", "def sum_digits(number):\n number = abs(number)\n result = 0\n while number > 0:\n result += number % 10\n number //= 10\n return result", "def sum_digits(number):\n bruh = 0\n for i in str(abs(number)):\n bruh += int(i)\n return bruh", "def sum_digits(number):\n for i in str(number):\n if i == '-':\n number = str(number).strip('-')\n else:\n pass\n digits = [int(x) for x in str(number)]\n return sum(digits)", "def sum_digits(number):\n n = []\n for i in str(number):\n if i != '-':\n n.append(int(i))\n return sum(n)", "import math\n\ndef sum_digits(n):\n n = round(math.fabs(n))\n all = [int(s) for s in str(n)]\n return sum(all)"], "starter_code": "def sum_digits(number):\n", "input_output": {"fn_name": "sum_digits", "inputs": [[10], [99], [-32], [1234567890], [0], [666], [100000002], [800000009]], "outputs": [[1], [18], [5], [45], [0], [18], [3], [17]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/52f3149496de55aded000410", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sum_digits", "task_id": "TACO_lite/318", "example": [[[10], [99], [-32]], ["1", "18", "5"]]} +{"requirement": "Pell numbers are numbers that are similar to the Fibonacci numbers and are generated by below formula\nP_{n} = 2*P_{n-1} + P_{n-2}\nwith seeds P_{0} = 0 and P_{1} = 1\nYour task is to print Nth pell number.\n \nExample 1:\nInput:\nN = 3\nOutput:\n5\nExplanation:\nP_{0} = 0, P_{1} = 1, P_{2} = 2*1+0 = 2,\nP_{3} = 2*2+1 = 5\nExample 2:\nInput:\nN = 4\nOutput:\n12\nExplanation:\nP_{0} = 0, P_{1} = 1, P_{2} = 2*1+0 = 2,\nP_{3} = 2*2+1 = 5, P_{4} = 2*5+2 = 12\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function getNthPell() which takes an Integer N as input and returns the answer modulo (10^{9}+7).\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\n \nConstraints:\n1 <= N <= 10^{5}", "solutions": ["def getnthpell(N):\n if N == 0:\n return 0\n elif N == 1:\n return 1\n else:\n (a, b, m) = (0, 1, int(1000000000.0) + 7)\n for i in range(N - 1):\n c = (2 * b + a) % m\n a = b\n b = c\n return b", "def getnthpell(N):\n (p0, p1) = (0, 1)\n for i in range(N):\n (p0, p1) = (p1, (2 * p1 + p0) % 1000000007)\n return p0", "def getnthpell(N):\n if N <= 1:\n return N\n a = 0\n b = 1\n for i in range(2, N + 1):\n c = 2 * b + a\n a = b\n b = c\n b = b % 1000000007\n return b", "def getnthpell(N):\n arr = [0] * (N + 1)\n arr[0] = 0\n arr[1] = 1\n for i in range(2, N + 1):\n arr[i] = (2 * arr[i - 1] + arr[i - 2]) % 1000000007\n return arr[N]", "def getnthpell(N):\n fab = [0, 1]\n for j in range(2, N + 1):\n v = (fab[1] * 2 % (10 ** 9 + 7) + fab[0]) % (10 ** 9 + 7)\n (fab[0], fab[1]) = (fab[1], v)\n return fab[1]", "def getnthpell(N):\n f = [0, 1]\n for i in range(2, N + 2):\n f.append((f[i - 1] * 2 + f[i - 2]) % (10 ** 9 + 7))\n return f[N]", "def getnthpell(N):\n if N == 0:\n return 0\n if N == 1:\n return 1\n lst = [0, 1]\n for i in range(2, N + 1):\n val = (2 * lst[i - 1] + lst[i - 2]) % 1000000007\n lst.append(val)\n return lst[N]"], "starter_code": "def getnthpell(N):\n", "input_output": {"inputs": ["N = 3", "N = 4"], "outputs": ["5", "12"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/pell-number1424/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "getnthpell", "task_id": "TACO_lite/303", "example": [[[3], [4]], ["5", "12"]]} +{"requirement": "Scientists working internationally use metric units almost exclusively. Unless that is, they wish to crash multimillion dollars worth of equipment on Mars.\n\nYour task is to write a simple function that takes a number of meters, and outputs it using metric prefixes.\n\nIn practice, meters are only measured in \"mm\" (thousandths of a meter), \"cm\" (hundredths of a meter), \"m\" (meters) and \"km\" (kilometers, or clicks for the US military).\n\nFor this exercise we just want units bigger than a meter, from meters up to yottameters, excluding decameters and hectometers.\n\nAll values passed in will be positive integers.\ne.g.\n\n```python\nmeters(5);\n// returns \"5m\"\n\nmeters(51500);\n// returns \"51.5km\"\n\nmeters(5000000);\n// returns \"5Mm\"\n```\n\nSee http://en.wikipedia.org/wiki/SI_prefix for a full list of prefixes", "solutions": ["def meters(x):\n arr = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']\n count = 0\n while x >= 1000:\n x /= 1000.0\n count += 1\n if int(x) == x:\n x = int(x)\n return str(x) + arr[count] + 'm'", "PREFIXES = ((10 ** 24, 'Y'), (10 ** 21, 'Z'), (10 ** 18, 'E'), (10 ** 15, 'P'), (10 ** 12, 'T'), (10 ** 9, 'G'), (10 ** 6, 'M'), (10 ** 3, 'k'), (1, ''))\n\ndef meters(x):\n (value, prefix) = next((pr for pr in PREFIXES if pr[0] <= x))\n return '%g%sm' % (float(x) / value, prefix)", "import math\nPREFIXES = ['m', 'km', 'Mm', 'Gm', 'Tm', 'Pm', 'Em', 'Zm', 'Ym']\n\ndef meters(x):\n e = int(math.log(x, 1000))\n return '{0:g}{1}'.format(x / 1000.0 ** e, PREFIXES[e])", "def meters(x):\n units = [('Y', 24), ('Z', 21), ('E', 18), ('P', 15), ('T', 12), ('G', 9), ('M', 6), ('k', 3), ('', 0)]\n return next((f\"{str(x / 10 ** p).replace('.0', '')}{u}m\" for (u, p) in units if x // 10 ** p >= 1))", "def meters(x):\n (prefix, power) = next((pair for pair in zip('YZEPTGMk', range(24, 0, -3)) if x >= 10 ** pair[1]), ('', 0))\n return '{:g}{}m'.format(x / 10 ** power, prefix)", "def meters(x):\n s = ['m', 'km', 'Mm', 'Gm', 'Tm', 'Pm', 'Em', 'Zm', 'Ym']\n i = 0\n while x >= 1000:\n x /= 1000.0\n i += 1\n return '%g%s' % (x, s[i])", "from decimal import Context, ROUND_HALF_UP\nimport re\n\ndef meters(num):\n r = len(str(num).strip('0'))\n num = Context(prec=r, rounding=ROUND_HALF_UP).create_decimal(num)\n i = int(num.logb()) // 3\n return re.sub('(\\\\.0+)(?=[kMGTPEZTY])', '', f\"{num.scaleb(-3 * i):f}{' kMGTPEZY'[i]}m\".replace(' ', ''))", "from math import log\n\ndef meters(x):\n prefixes = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']\n order = int(log(x, 1000))\n return '{:g}{}m'.format(x / (1000 ** order or 1), prefixes[order])"], "starter_code": "def meters(x):\n", "input_output": {"fn_name": "meters", "inputs": [[1], [999], [123456], [12300000], [9000000000.0], [9000000000000.0], [9000000000000000.0], [9e+18], [9e+21], [9e+24]], "outputs": [["1m"], ["999m"], ["123.456km"], ["12.3Mm"], ["9Gm"], ["9Tm"], ["9Pm"], ["9Em"], ["9Zm"], ["9Ym"]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5264f5685fda8ed370000265", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "meters", "task_id": "TACO_lite/299", "example": [[], []]} +{"requirement": "Given an integer S represented as a string, the task is to get the sum of all possible sub-strings of this string.\nAs the answer will be large, print it modulo 10^9+7.\nExample 1:\nInput:\nS = 1234\nOutput: 1670\nExplanation: Sum = 1 + 2 + 3 + 4 + 12 +\n23 + 34 + 123 + 234 + 1234 = 1670\nExample 2:\nInput:\nS = 421\nOutput: 491\nExplanation: Sum = 4 + 2 + 1 + 42 + 21\nYour Task:\nYou only need to complete the function sumSubstrings that takes S as an argument and returns the answer modulo 1000000007.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\nConstraints:\n1 <= |S| <= 10^{4}", "solutions": ["def sumsubstrings(s):\n n = len(s)\n digits = []\n for char in s:\n digits.append(int(char))\n dp = [0 for i in range(n)]\n dp[0] = digits[0]\n res = dp[0]\n for i in range(1, n):\n dp[i] = ((i + 1) * digits[i] + dp[i - 1] * 10) % 1000000007\n res += dp[i]\n res %= 1000000007\n return res", "def sumsubstrings(s):\n a = s\n dp = [0 for i in range(len(a))]\n dp[0] = int(a[0])\n result = dp[0]\n for i in range(1, len(a)):\n dp[i] = (i + 1) * int(a[i]) + 10 * dp[i - 1]\n result = result + dp[i]\n return result % (10 ** 9 + 7)", "def sumsubstrings(s):\n ls = []\n for i in s:\n ls.append(int(i))\n p = ls[0]\n s = ls[0]\n for j in range(1, len(ls)):\n c = ls[j]\n temp = (j + 1) * c + p * 10\n s = s + temp\n p = temp\n return s % 1000000007", "def sumsubstrings(num):\n mod = 1000000007\n n = len(num)\n prev = int(num[0])\n result = prev\n cur = 0\n for i in range(1, n):\n cur = (i + 1) * int(num[i]) + 10 * prev\n result += cur\n prev = cur\n return result % mod", "def sumsubstrings(s):\n M = 1000000007\n n = len(s)\n dp = [0 for i in range(0, n)]\n dp[0] = ord(s[0]) - ord('0')\n for i in range(1, n):\n dp[i] = ((i + 1) * (ord(s[i]) - ord('0')) + 10 * dp[i - 1]) % M\n ans = 0\n for i in range(0, n):\n ans += dp[i] % M\n return ans % M", "def sumsubstrings(s):\n dp = [0] * len(s)\n dp[0] = int(s[0])\n mod = 10 ** 9 + 7\n for i in range(1, len(s)):\n dp[i] = (10 * dp[i - 1] + int(s[i]) * (i + 1)) % mod\n res = 0\n for i in range(len(s)):\n res += dp[i]\n res %= mod\n return res", "def sumsubstrings(s):\n n = len(s)\n prev = int(s[0])\n res = prev\n current = 0\n for i in range(1, n):\n numi = int(s[i])\n current = (i + 1) * numi + 10 * prev\n res += current\n prev = current\n return res % 1000000007", "def sumsubstrings(s):\n sub_res = 0\n prev_res = int(s[0])\n res = prev_res\n mod = 1000000000.0 + 7\n for i in range(1, len(s)):\n sub_res = ((i + 1) * int(s[i]) + 10 * prev_res) % mod\n res = (res + sub_res) % mod\n prev_res = sub_res\n return int(res)", "def sumsubstrings(s):\n dp = [0] * len(s)\n dp[0] = int(s[0])\n for i in range(1, len(s)):\n dp[i] = (dp[i - 1] * 10 + (i + 1) * int(s[i])) % 1000000007\n return sum(dp) % 1000000007", "def sumsubstrings(s):\n su = 0\n mod = 1000000007\n n = len(s)\n dp = [0] * n\n dp[0] = int(s[0])\n for i in range(1, n):\n dp[i] = 10 * dp[i - 1] % mod + (i + 1) * int(s[i])\n for i in range(n):\n su = (su + dp[i]) % mod\n return su", "def sumsubstrings(s):\n ans = 0\n k = 1\n for i in range(len(s) - 1, -1, -1):\n ans = ans + int(s[i]) * (i + 1) * k\n k = k * 10 + 1\n return ans % 1000000007", "def sumsubstrings(s):\n summa = 0\n n = len(s)\n for i in range(n):\n summa += int('1' * (n - i)) * int(s[i]) * (i + 1)\n return summa % (10 ** 9 + 7)", "def sumsubstrings(s):\n n = len(s)\n total = 0\n mod = 10 ** 9 + 7\n for i in range(n):\n text = s[i] * (n - i)\n total += int(text) * (i + 1)\n return total % mod", "def sumsubstrings(s):\n no = [int(s[0])]\n ans = no[0]\n MOD = 1000000007\n for i in range(1, len(s)):\n curr = (i + 1) * int(s[i]) + no[-1] * 10\n no.append(curr % MOD)\n ans += no[i]\n return ans % MOD", "def sumsubstrings(s):\n n = len(s)\n l = [0] * (n + 1)\n l[0] = ord(s[0]) - ord('0')\n for i in range(1, n):\n l[i] = (ord(s[i]) - ord('0')) * (i + 1) + 10 * l[i - 1]\n sum = 0\n m = pow(10, 9) + 7\n for d in l:\n sum = (sum + d) % m\n return sum", "def sumsubstrings(s):\n n = len(s)\n mod = 1000000007\n ls = [0] * n\n ls[0] = int(s[0]) % mod\n for i in range(1, n):\n ls[i] = ((i + 1) * int(s[i]) + 10 * ls[i - 1]) % mod\n add = 0\n for i in range(n):\n add += ls[i]\n return add % mod", "def sumsubstrings(s):\n m = 10 ** 9 + 7\n n = len(s)\n L = []\n L.append(int(s[0]))\n res = L[0]\n for i in range(1, n):\n p = int(s[i])\n L.append((i + 1) * p + 10 * L[i - 1])\n res = res + L[i]\n return res % m", "def sumsubstrings(s):\n M = 10 ** 9 + 7\n sum_val = 0\n B = 1\n res = 0\n for i in range(len(s) - 1, -1, -1):\n res = (res + int(s[i]) * B * (i + 1)) % M\n sum_val -= int(s[i])\n B = (B * 10 + 1) % M\n return res", "def sumsubstrings(s):\n mod = 10 ** 9 + 7\n ans = 0\n n = len(s)\n pref_arr = [0] * n\n pref_arr[0] = int(s[0])\n for i in range(1, n):\n val = (i + 1) * int(s[i])\n pref_arr[i] = val + 10 * pref_arr[i - 1]\n for i in range(n):\n ans += pref_arr[i] % mod\n return ans % mod", "def sumsubstrings(s):\n n = len(s)\n res = []\n res.append(int(s[0]))\n for i in range(1, n):\n si = int(s[i])\n res.append((i + 1) * si + 10 * res[i - 1])\n summ = sum(res) % (10 ** 9 + 7)\n return summ", "def fun(s, n):\n dp = [0] * n\n m = 10 ** 9 + 7\n dp[0] = int(s[0])\n sum = dp[0]\n for i in range(1, n):\n dp[i] = ((i + 1) * int(s[i]) + 10 * dp[i - 1]) % m\n sum += dp[i]\n sum %= m\n return sum\n\ndef sumsubstrings(s):\n n = len(s)\n return fun(s, n)", "def sumsubstrings(s):\n mod = 10 ** 9 + 7\n sum1 = 0\n p = 1\n for i in range(len(s) - 1, -1, -1):\n sum1 = (sum1 + int(s[i]) * (i + 1) * p) % mod\n p = p * 10 + 1\n return sum1", "def sumsubstrings(s):\n mat = []\n s1 = str(s)\n mat.append(s1[0])\n for i in range(1, len(s1)):\n val = int(str(mat[i - 1]) + '0')\n val1 = int((i + 1) * int(s1[i]))\n ans = val + val1\n mat.append(ans)\n res = 0\n for i in mat:\n res = res + int(i)\n return res % 1000000007", "def sumsubstrings(num):\n n = len(num)\n prev = int(num[0])\n res = prev\n current = 0\n for i in range(1, n):\n numi = int(num[i])\n current = (i + 1) * numi + 10 * prev\n res += current\n prev = current\n return res % (10 ** 9 + 7)", "def sumsubstrings(s):\n mod = int(1000000000.0 + 7)\n n = len(s)\n totSum = int(s[0])\n prevSum = int(s[0])\n for i in range(1, n):\n curSum = (i + 1) * int(s[i]) + 10 * prevSum\n totSum = (totSum % mod + curSum % mod) % mod\n prevSum = curSum\n return totSum", "def sumsubstrings(s):\n res = []\n s1 = str(s)\n sum0 = []\n sum0.append(int(s1[0]))\n for i in range(1, len(s)):\n sum1 = int(s1[i]) * (i + 1) + 10 * sum0[i - 1]\n sum0.append(sum1)\n return sum(sum0) % 1000000007", "def sumsubstrings(s):\n p = 1000000007\n il = 0\n el = 0\n n = 0\n for i in s:\n i = int(i)\n el = (il + el) % p\n il = (il * 10 + n * i + i) % p\n n += 1\n return (il + el) % p", "def sumsubstrings(string):\n sum = int(string[0])\n n = len(string)\n pre_sum = int(string[0])\n for i in range(1, n):\n pre_sum = int(string[i]) * (i + 1) + 10 * pre_sum\n sum += pre_sum\n return sum % 1000000007", "def sumsubstrings(s):\n mod = 1000000007\n sum = 0\n for i in range(len(s)):\n num = int(s[i] * (len(s) - i)) % mod * (i + 1) % mod % mod\n sum += num % mod\n return sum % mod", "def sumsubstrings(s):\n mod = 1000000007\n n = len(s)\n if n == 0:\n return 0\n if n == 1:\n return int(s[0])\n dp = [0] * (n + 1)\n dp[0] = 0\n res = 0\n for i in range(1, n + 1):\n dp[i] = (i * (int(s[i - 1]) % mod) % mod + 10 * dp[i - 1] % mod % mod) % mod\n res = (res % mod + dp[i] % mod) % mod\n return res % mod\n dp[1] = int(s[0]) % mod\n dp[2] = int(s[0]) % mod + int(s[1]) % mod + int(s[0:2]) % mod\n for i in range(3, n + 1):\n res = 0\n for j in range(i):\n res += int(s[j:i]) % mod\n dp[i] = (res % mod + dp[i - 1] % mod) % mod", "def sumsubstrings(s):\n st = [int(s[0])]\n res = st[0]\n for i in range(1, len(s)):\n p = int(s[i])\n st.append((i + 1) * p + 10 * st[-1])\n res += st[-1]\n return res % 1000000007", "def sumsubstrings(s):\n ans = 0\n x = 1\n c = len(s)\n for i in s[::-1]:\n ans += x * int(i) * c\n x = x * 10 + 1\n c -= 1\n return ans % 1000000007", "def sumsubstrings(s):\n mod = 1000000007\n n = len(s)\n lst = [0 for i in range(n)]\n lst[0] = int(s[0])\n res = int(s[0])\n for i in range(1, n):\n lst[i] = (i + 1) * int(s[i]) + 10 * lst[i - 1]\n res += lst[i]\n return res % mod", "def sumsubstrings(s):\n sums = 0\n multiply = 1\n for i in range(len(s) - 1, -1, -1):\n sums += int(s[i]) * (i + 1) * multiply\n multiply = multiply * 10 + 1\n return sums % (10 ** 9 + 7)", "def sumsubstrings(s):\n string_number = str(s)\n a = [0] * len(string_number)\n a[0] = int(s[0])\n for i in range(1, len(string_number)):\n a[i] = 10 * a[i - 1] + (i + 1) * int(string_number[i])\n return sum(a) % 1000000007", "def sumsubstrings(s):\n mod = 10 ** 9 + 7\n result = 0\n N = len(s)\n sum_of_digits = [int(s[0])]\n for i in range(1, N):\n result = (int(s[i]) * (i + 1) + 10 * sum_of_digits[i - 1]) % mod\n sum_of_digits.append(result)\n return sum(sum_of_digits) % mod", "def sumsubstrings(s):\n if len(s) == 0:\n return 0\n mod = 1000000007\n dp = [0 for _ in range(len(s))]\n dp[0] = int(s[0])\n result = dp[0]\n for i in range(1, len(s)):\n dp[i] = (i + 1) * int(s[i]) + 10 * dp[i - 1] % mod\n result += dp[i] % mod\n return result % mod", "from itertools import combinations\n\ndef sumsubstrings(s):\n (current, result) = (int(s[0]), 0)\n for i in range(len(s) - 1):\n result += current\n prev = current\n current = (i + 2) * int(s[i + 1]) + 10 * prev\n return (result + current) % 1000000007", "from itertools import combinations\n\ndef sumsubstrings(s):\n c = 0\n q = int(s[0])\n res = q\n for i in range(1, len(s)):\n ni = int(s[i])\n c = (i + 1) * ni + 10 * q\n res += c\n q = c\n return res % 1000000007", "def sumsubstrings(s):\n l = [0] * len(s)\n l[0] = int(s[0])\n for i in range(1, len(s)):\n x = int(s[i])\n y = l[i - 1]\n l[i] = x * (i + 1) + 10 * y\n return sum(l) % 1000000007", "def sumsubstrings(s):\n n = len(s)\n koo = 10 ** 9 + 7\n arr = [0] * n\n arr[0] = int(s[0])\n for i in range(1, n):\n arr[i] = arr[i - 1] + int(s[i]) * (i + 1)\n ans = 0\n for i in range(n):\n ans = (ans % koo + arr[i] * 10 ** (n - i - 1) % koo) % koo\n return ans % koo", "def sumsubstrings(s):\n ans = [int(s[0])]\n for i in range(1, len(s)):\n a = ans[i - 1] * 10 + int(s[i]) * (i + 1)\n ans.append(a)\n return sum(ans) % 1000000007", "def sumsubstrings(s):\n su = 0\n mf = 1\n for i in range(len(s) - 1, -1, -1):\n su = su + int(s[i]) * (i + 1) * mf\n mf = mf * 10 + 1\n return su % (10 ** 9 + 7)", "def sumSubstring(s, n):\n if n == 0:\n return 0\n su = int(s[n - 1])\n su += Solution.sumSubstring(s, n - 1) % 1000000007\n for i in range(n - 2, -1, -1):\n su += int(s[i:n])\n return su\n\ndef sumsubstrings(s):\n n = len(s)\n dp = [0] * (n + 1)\n dp[0] = int(s[0])\n res = dp[0]\n for i in range(1, n):\n dp[i] = (i + 1) * int(s[i]) + 10 * (dp[i - 1] % 1000000007)\n res += dp[i]\n return res % 1000000007", "def sumsubstrings(s):\n n = len(s)\n sod = []\n sod.append(int(s[0]))\n res = sod[0]\n for i in range(1, n):\n numi = int(s[i])\n sod.append((i + 1) * numi + 10 * sod[i - 1])\n res += sod[i]\n return res % (10 ** 9 + 7)", "def sumsubstrings(s):\n n = len(s)\n dp = [0] * n\n res = int(s[0])\n dp[0] = res\n m = 1000000007\n for i in range(1, n):\n dp[i] = (i + 1) * int(s[i]) + 10 * dp[i - 1] % m\n res = (res + dp[i]) % m\n return res", "def sumsubstrings(str):\n modulo = 1000000007\n dp = [0] * len(str)\n dp[0] = int(str[0])\n for i in range(1, len(str)):\n dp[i] = (dp[i - 1] + int(str[i]) + (dp[i - 1] - (dp[i - 2] if i > 1 else 0)) * 10 + int(str[i]) * i) % modulo\n return dp[-1]", "def sumsubstrings(s):\n M = 1000000007\n n = len(s)\n sumstr = []\n sumstr.append(int(s[0]))\n res = sumstr[0]\n for i in range(1, n):\n sumstr.append((i + 1) * int(s[i]) + 10 * sumstr[i - 1])\n res += sumstr[i]\n return res % M", "def sumsubstrings(s):\n mod = 10 ** 9 + 7\n n = len(s)\n s = str(s)\n dp = [0] * n\n dp[0] = int(s[0])\n ans = dp[0]\n for i in range(1, n):\n dp[i] = ((i + 1) * int(s[i]) + 10 * dp[i - 1]) % mod\n ans = (ans + dp[i]) % mod\n return ans", "def sumsubstrings(s):\n n = len(s)\n sumofdigit = []\n sumofdigit.append(int(s[0]))\n res = sumofdigit[0]\n for i in range(1, n):\n numi = int(s[i])\n sumofdigit.append((i + 1) * numi + 10 * sumofdigit[i - 1])\n res += sumofdigit[i]\n return res % 1000000007", "def sumsubstrings(s):\n t = 0\n i = 0\n f = len(s)\n a = []\n r = 0\n a.append(1)\n for i in range(1, len(s)):\n a.append(a[i - 1] * 10 + 1)\n for x in range(0, len(s)):\n r = r + a[x] * int(s[f - 1 - x]) * (f - x)\n return r % 1000000007", "def sumsubstrings(s):\n if len(s) == 0:\n return 0\n prev = int(s[0])\n total = prev\n for i in range(2, len(s) + 1):\n curr = int(s[i - 1]) * i + 10 * prev\n total += curr\n prev = curr\n return total % 1000000007", "def sumsubstrings(s):\n n = len(s)\n a = [int(i) for i in s]\n dp = [0 for i in range(n)]\n dp[0] = a[0]\n c = dp[0]\n for i in range(1, n):\n dp[i] = ((i + 1) * a[i] + 10 * dp[i - 1]) % 1000000007\n c += dp[i] % 1000000007\n return c % 1000000007", "mod = 10 ** 9 + 7\n\ndef sumsubstrings(s):\n prev = int(s[0])\n ans = prev\n for i in range(1, len(s)):\n curr = int(s[i])\n val = (i + 1) * curr + 10 * prev\n ans = (ans + val) % mod\n prev = val\n return ans"], "starter_code": "def sumsubstrings(s):\n", "input_output": {"inputs": ["S = 1234", "S = 421"], "outputs": ["1670", "491"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/sum-of-all-substrings-of-a-number-1587115621/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "sumsubstrings", "task_id": "TACO_lite/327", "example": [[["1234"], ["421"]], ["1670", "491"]]} +{"requirement": "Count the number of prime numbers less than a non-negative number, n.\n\nExample:\n\n\nInput: 10\nOutput: 4\nExplanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.", "solutions": ["def countprimes(x):\n x = max(0, x - 1)\n if type(x) is not int:\n x = int(x)\n if x < 6:\n return [0, 0, 1, 2, 2, 3][x]\n\n def Phi(m, b):\n if not b:\n return m\n if not m:\n return 0\n if m >= 800:\n return Phi(m, b - 1) - Phi(m // primes[b - 1], b - 1)\n t = b * 800 + m\n if not Phi_memo[t]:\n Phi_memo[t] = Phi(m, b - 1) - Phi(m // primes[b - 1], b - 1)\n return Phi_memo[t]\n root2 = int(x ** (1.0 / 2))\n root3 = int(x ** (1.0 / 3))\n top = x // root3 + 1\n sieve = [0, 0] + [1] * (top - 2)\n pi = [0, 0]\n primes = []\n t = 0\n for i in range(2, top):\n if sieve[i] == 1:\n t += 1\n primes.append(i)\n sieve[i::i] = [0] * len(sieve[i::i])\n pi.append(t)\n (a, b) = (pi[root3 + 1], pi[root2 + 1])\n Phi_memo = [0] * ((a + 1) * 800)\n return Phi(x, a) + a - 1 - sum((pi[x // p] - pi[p] + 1 for p in primes[a:b]))"], "starter_code": "def countprimes(n: int) -> int:\n", "input_output": {"fn_name": "countPrimes", "inputs": [[10]], "outputs": [4]}, "difficulty": "EASY", "raw_tags": ["Number Theory", "Enumeration", "Math", "Array"], "name": null, "source": "leetcode", "tags": ["Number theory", "Data structures", "Mathematics", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://leetcode.com/problems/count-primes/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "countprimes", "task_id": "TACO_lite/335", "example": [[[10]], ["4"]]} +{"requirement": "Given an integer n, denoting the number of cuts that can be made on a pancake, find the maximum number of pieces that can be formed by making n cuts.\nNOTE: Cuts can't be horizontal.\n \nExample 1:\nInput: N = 5\nOutput: 16\nExplanation: 16 pieces can be formed by\nmaking 5 cuts.\nExample 2:\nInput: N = 3\nOutput: 7\nExplanation: 7 pieces can be formed by \nmaking 3 cuts.\n \nYour Task: \nYou don't need to read or print anything. Your task is to complete the function maximum_Cuts() which takes n as input parameter and returns the maximum number of pieces that can be formed by making n cuts.\n \nExpected Time Complexity: O(1)\nExpected Space Complexity: O(1)\nConstraints:\n1 <= N <= 10000", "solutions": ["def maximum_cuts(n):\n return (n + 1) * (n + 2) // 2 - n", "def maximum_cuts(n):\n if n % 2:\n return int((n + 1) / 2) * n + 1\n else:\n return int((n + 1) / 2) * (n + 1) + 1", "def maximum_cuts(n):\n p = n * (n + 1) / 2 + 1\n return int(p)", "def maximum_cuts(n):\n lst = []\n lst.append(2)\n lst.append(4)\n d = 2\n for i in range(1, n):\n c = d + i + lst[i]\n lst.append(c)\n return lst[n - 1]", "def maximum_cuts(n):\n if n <= 2:\n if n == 0:\n return 1\n return 2 * n\n else:\n a = 1 + n * (n + 1) // 2\n return a", "def maximum_cuts(n):\n prev = 2\n for i in range(2, n + 1):\n prev += i\n return prev", "def maximum_cuts(n):\n sum = 2\n j = 2\n for i in range(1, n):\n sum += j\n j += 1\n return sum", "def maximum_cuts(n):\n result = int(1 + n * (n + 1) / 2)\n return result", "def maximum_cuts(n):\n c = 1\n for i in range(1, n + 1):\n c += i\n return c", "def maximum_cuts(n):\n cut = 1\n cuts = n * (n + 1) // 2 + 1\n return cuts"], "starter_code": "def maximum_cuts(n):\n", "input_output": {"inputs": ["N = 5", "N = 3"], "outputs": ["16", "7"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/the-lazy-caterers-problem2527/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "maximum_cuts", "task_id": "TACO_lite/256", "example": [[[5], [3]], ["16", "7"]]} +{"requirement": "Let's say we have a number, `num`. Find the number of values of `n` such that: there exists `n` consecutive **positive** values that sum up to `num`. A positive number is `> 0`. `n` can also be 1.\n\n```python\n#Examples\nnum = 1\n#1\nreturn 1\n\nnum = 15\n#15, (7, 8), (4, 5, 6), (1, 2, 3, 4, 5)\nreturn 4\n\nnum = 48\n#48, (15, 16, 17)\nreturn 2\n\nnum = 97\n#97, (48, 49)\nreturn 2\n```\nThe upper limit is `$10^8$`", "solutions": ["def consecutive_sum(num):\n upper_limit = 1\n while True:\n if upper_limit * (upper_limit + 1) // 2 > num:\n break\n upper_limit += 1\n return sum([1 if i % 2 and (not num % i) else 1 if not i % 2 and num % i == i // 2 else 0 for i in range(1, upper_limit)])", "from math import sqrt\n\ndef consecutive_sum(n):\n cnt = 0\n lim = int(sqrt(2 * n))\n m = 1\n while m <= lim:\n u = n / m + m / 2 + 0.5\n if int(u) == u:\n cnt += 1\n m += 1\n return cnt", "def consecutive_sum(n):\n top = (1 + (1 + 8 * n) ** 0.5) / 2\n return sum((not (n - (v - 1) * v // 2) % v for v in range(1, int(top))))", "from functools import partial\nfrom itertools import accumulate, count, takewhile\nfrom operator import ge\n\ndef consecutive_sum(num):\n return sum(((num - start) % step == 0 for (step, start) in enumerate(takewhile(partial(ge, num), accumulate(count(1))), 1)))", "def consecutive_sum(num):\n count = 0\n N = 1\n while N * (N + 1) < 2 * num:\n a = (num - N * (N + 1) / 2) / (N + 1)\n if a - int(a) == 0.0:\n count += 1\n N += 1\n return count + 1", "from math import sqrt\n\ndef consecutive_sum(num):\n counter = 1\n for i in range(2, int(sqrt(2 * num) + 1)):\n if i % 2 == 0:\n if num / i - num // i == 0.5:\n counter += 1\n elif num / i == num // i:\n counter += 1\n return counter", "def factors(n):\n seen = {1, n}\n for a in range(2, 1 + int(n ** 0.5)):\n (b, m) = divmod(n, a)\n if m == 0:\n if a in seen:\n break\n seen.add(a)\n seen.add(b)\n return sorted(seen)\n\ndef consecutive_sum(num):\n return sum((1 for d in factors(num) if d % 2))", "from functools import reduce\n\ndef divisors(n):\n return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))\n\ndef consecutive_sum(n):\n return len([x for x in divisors(n) if x % 2 != 0])", "from numpy import roots\n\ndef consecutive_sum(num):\n return sum((num % i == (i >> 1) * (i & 1 ^ 1) for i in range(1, int(roots([1 / 2, 1 / 2, -num])[1] + 1))))", "def consecutive_sum(num):\n sol = 1\n nums = 1\n i = 2\n while num > nums:\n if (num - nums) % i == 0:\n sol += 1\n nums += i\n i += 1\n return sol"], "starter_code": "def consecutive_sum(num):\n", "input_output": {"fn_name": "consecutive_sum", "inputs": [[1], [15], [48], [97]], "outputs": [[1], [4], [2], [2]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5f120a13e63b6a0016f1c9d5", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "consecutive_sum", "task_id": "TACO_lite/283", "example": [[[1], [15], [48], [97]], ["1", "4", "2", "2"]]} +{"requirement": "In input string ```word```(1 word):\n* replace the vowel with the nearest left consonant.\n* replace the consonant with the nearest right vowel.\n\nP.S. To complete this task imagine the alphabet is a circle (connect the first and last element of the array in the mind). For example, 'a' replace with 'z', 'y' with 'a', etc.(see below)\n\nFor example:\n```\n'codewars' => 'enedazuu'\n'cat' => 'ezu'\n'abcdtuvwxyz' => 'zeeeutaaaaa'\n```\n\nIt is preloaded: \n\n```\nconst alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\nconst consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'];\nconst vowels = ['a','e','i','o','u'];\n```\n\nP.S. You work with lowercase letters only.", "solutions": ["def replace_letters(word):\n return word.translate(str.maketrans('abcdefghijklmnopqrstuvwxyz', 'zeeediiihooooonuuuuutaaaaa'))", "from string import ascii_lowercase as al\ntbl = str.maketrans(al, ''.join((al[(i - 1) % 26] if x in 'aeiou' else next((al[j % 26] for j in range(i + 1, 100) if al[j % 26] in 'aeiou')) for (i, x) in enumerate(al))))\n\ndef replace_letters(word):\n return word.translate(tbl)", "def replace_letters(word):\n d = {'a': 'z', 'b': 'e', 'c': 'e', 'd': 'e', 'e': 'd', 'f': 'i', 'g': 'i', 'h': 'i', 'i': 'h', 'j': 'o', 'k': 'o', 'l': 'o', 'm': 'o', 'n': 'o', 'o': 'n', 'p': 'u', 'q': 'u', 'r': 'u', 's': 'u', 't': 'u', 'u': 't', 'v': 'a', 'w': 'a', 'x': 'a', 'y': 'a', 'z': 'a'}\n return ''.join([d[i] for i in list(word)])"], "starter_code": "def replace_letters(word):\n", "input_output": {"fn_name": "replace_letters", "inputs": [["cat"], ["codewars"], ["abcdtuvwxyz"]], "outputs": [["ezu"], ["enedazuu"], ["zeeeutaaaaa"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5a4331b18f27f2b31f000085", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "replace_letters", "task_id": "TACO_lite/309", "example": [[], []]} +{"requirement": "Serialization is to store a tree in an array so that it can be later restored and Deserialization is reading tree back from the array. Now your task is to complete the function serialize which stores the tree into an array A[ ] and deSerialize which deserializes the array to the tree and returns it.\nNote: The structure of the tree must be maintained. Multiple nodes can have the same data.\nExample 1:\nInput:\n 1\n / \\\n 2 3\nOutput: 2 1 3\nExample 2:\nInput:\n 10\n / \\\n 20 30\n / \\\n 40 60\nOutput: 40 20 60 10 30\nYour Task:\nThe task is to complete two functions serialize which takes the root node of the tree as input and stores the tree into an array and deSerialize which deserializes the array to the original tree and returns the root of it.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\nConstraints:\n1 <= Number of nodes <= 1000\n1 <= Data of a node <= 1000", "solutions": ["from collections import deque\n\ndef serialize(root, ans):\n if root is None:\n return ans\n queue = deque()\n queue.append(root)\n while len(queue) != 0:\n size = len(queue)\n for i in range(size):\n node = queue[0]\n queue.popleft()\n if node is None:\n ans.append(None)\n continue\n queue.append(node.left)\n queue.append(node.right)\n ans.append(node.data)\n while ans[-1] is None:\n ans.pop()\n return ans\n\ndef deSerialize(arr):\n if len(arr) == 0:\n return None\n queue = deque()\n root = Node(arr[0])\n queue.append(root)\n start = 1\n end = len(arr)\n while len(queue) != 0 and start < len(arr):\n size = len(queue)\n elements_to_extract = size * 2\n end = min(len(arr), start + elements_to_extract)\n rotation = 0\n while start < end:\n node = None\n if arr[start] is not None:\n node = Node(arr[start])\n queue.append(node)\n curr = queue[0]\n if rotation == 0:\n curr.left = node\n rotation = 1\n else:\n curr.right = node\n queue.popleft()\n rotation = 0\n start += 1\n return root", "def serialize(root, A):\n q = [root]\n A.append(root)\n while len(q) > 0:\n l = len(q)\n for _ in range(l):\n temp = q[0]\n q.pop(0)\n if temp.left != None:\n q.append(temp.left)\n A.append(temp.left)\n else:\n A.append(None)\n if temp.right != None:\n q.append(temp.right)\n A.append(temp.right)\n else:\n A.append(None)\n return A\n\ndef deSerialize(A):\n root = A[0]\n A = A[1:]\n n = len(A)\n st = [root]\n for i in range(n // 2):\n temp = st[0]\n st.pop(0)\n temp.left = A[2 * i]\n temp.right = A[2 * i + 1]\n if A[2 * i] != None:\n st.append(A[2 * i])\n if A[2 * i + 1] != None:\n st.append(A[2 * i + 1])\n return root", "def serialize(root, A):\n if not root:\n A.append('#')\n return A\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n return A\n\ndef deSerialize(A):\n c = A.pop(0)\n if c == '#':\n return None\n r = Node(c)\n r.left = deSerialize(A)\n r.right = deSerialize(A)\n return r", "def serialize(root, A):\n if root is None:\n A.append('#')\n return A\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n return A\n\ndef deSerialize(A):\n curr = A.pop(0)\n if curr == '#':\n return None\n node = Node(curr)\n node.left = deSerialize(A)\n node.right = deSerialize(A)\n return node", "def serialize(root, A):\n if root is None:\n A.append(-1)\n return\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n\ndef deSerialize(A):\n temp = A.pop(0)\n if temp == -1:\n return\n root = Node(temp)\n root.left = deSerialize(A)\n root.right = deSerialize(A)\n return root", "def serialize(root, A):\n if not root:\n A.append(-1)\n return\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n\ndef deSerializeUtil(A, i):\n if i[0] >= len(A) or A[i[0]] == -1:\n i[0] += 1\n return None\n node = Node(A[i[0]])\n i[0] += 1\n node.left = deSerializeUtil(A, i)\n node.right = deSerializeUtil(A, i)\n return node\n\ndef deSerialize(A):\n i = [0]\n return deSerializeUtil(A, i)\n\ndef __init__(val):\n self.data = val\n self.left = None\n self.right = None", "def serialize(root, A):\n if root == None:\n A.append(-1)\n return A\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n return A\n\ndef deSerialize(A):\n node = A.pop(0)\n if node == -1:\n return None\n root = Node(node)\n root.left = deSerialize(A)\n root.right = deSerialize(A)\n return root", "def serialize(root, A):\n if root == None:\n return\n serialize(root.left, A)\n A.append(root.data)\n serialize(root.right, A)\n\ndef solve(A, st, lst):\n if st > lst:\n return None\n mid = (st + lst) // 2\n root = Node(A[mid])\n root.left = solve(A, st, mid - 1)\n root.right = solve(A, mid + 1, lst)\n return root\n\ndef deSerialize(A):\n st = 0\n lst = len(A) - 1\n return solve(A, st, lst)", "def serialize(root, A):\n if not root:\n A.append('#')\n return A\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n return A\n\ndef deSerialize(A):\n curr = A.pop(0)\n if curr == '#':\n return None\n result = Node(curr)\n result.left = deSerialize(A)\n result.right = deSerialize(A)\n return result", "def serialize(root, A):\n q = [root]\n A.append(root)\n while len(q) > 0:\n temp = q[0]\n q.pop(0)\n if temp.left != None:\n A.append(temp.left)\n q.append(temp.left)\n else:\n A.append(None)\n if temp.right != None:\n A.append(temp.right)\n q.append(temp.right)\n else:\n A.append(None)\n\ndef deSerialize(A):\n root = A[0]\n q = [root]\n A = A[1:]\n for i in range(len(A) // 2):\n node = q[0]\n q.pop(0)\n node.left = A[2 * i]\n if A[2 * i] != None:\n q.append(A[2 * i])\n node.right = A[2 * i + 1]\n if A[2 * i + 1] != None:\n q.append(A[2 * i + 1])\n return root", "from collections import deque\n\ndef serialize(root, A):\n if root == None:\n return ''\n q = deque([root])\n while q:\n node = q.popleft()\n if node:\n q.append(node.left)\n q.append(node.right)\n A.append(str(node.data) if node else '#')\n return A\n\ndef deSerialize(data):\n if not data:\n return None\n arr = data\n root = Node(int(arr[0]))\n q = deque([root])\n index = 1\n while q:\n node = q.popleft()\n if arr[index] != '#':\n node.left = Node(int(arr[index]))\n q.append(node.left)\n index += 1\n if arr[index] != '#':\n node.right = Node(int(arr[index]))\n q.append(node.right)\n index += 1\n return root", "def serialize(root, A):\n if not root:\n A.append('#')\n return A\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n return A\n\ndef deSerialize(A):\n tmp = A.pop(0)\n if tmp == '#':\n return None\n root = Node(tmp)\n root.left = deSerialize(A)\n root.right = deSerialize(A)\n return root", "def serialize(root, A):\n if not root:\n return None\n arr = [root]\n while arr:\n t = arr.pop()\n if not t:\n A.append('#')\n else:\n A.append(str(t.data))\n arr.append(t.right)\n arr.append(t.left)\n\ndef deSerialize(A):\n if not A:\n return None\n global t\n t = 0\n return helper(A)\n\ndef helper(array):\n global t\n if array[t] == '#':\n return None\n root = Node(int(array[t]))\n t += 1\n root.left = helper(array)\n t += 1\n root.right = helper(array)\n return root", "def serialize(root, A):\n if root == None:\n return\n serialize(root.left, A)\n A.append(root.data)\n serialize(root.right, A)\n\ndef deSerialize(A):\n\n def solve(A, l, h):\n if l > h:\n return None\n mid = (l + h) // 2\n root = Node(A[mid])\n root.left = solve(A, l, mid - 1)\n root.right = solve(A, mid + 1, h)\n return root\n l = 0\n h = len(A) - 1\n return solve(A, l, h)", "def serialize(root, A):\n if not root:\n A.append('X')\n return\n A.append(str(root.data))\n serialize(root.left, A)\n serialize(root.right, A)\n return A\n\ndef deSerialize(A):\n if not A:\n return None\n val = A.pop(0)\n if val == 'X':\n return None\n node = Node(int(val))\n node.left = deSerialize(A)\n node.right = deSerialize(A)\n return node", "def serialize(root, A):\n if root == None:\n A.append(-1)\n return\n A.append(root.data)\n serialize(root.left, A)\n serialize(root.right, A)\n\ndef deSerializeUtil(A):\n global index\n index += 1\n if A[index] == -1:\n return None\n root = Node(A[index])\n root.left = deSerializeUtil(A)\n root.right = deSerializeUtil(A)\n return root\n\ndef deSerialize(A):\n global index\n index = -1\n return deSerializeUtil(A)", "def serialize(root, A):\n if root is None:\n return\n serialize(root.left, A)\n A.append(root.data)\n serialize(root.right, A)\n\ndef func(A):\n if not A:\n return None\n mid = len(A) // 2\n root = Node(A[mid])\n root.left = func(A[:mid])\n root.right = func(A[mid + 1:])\n return root\n\ndef deSerialize(A):\n return func(A)", "def serialize(root, a):\n if root is None:\n return []\n q = []\n q.append(root)\n while q:\n cur = q.pop(0)\n if cur == None:\n a.append('#')\n else:\n a.append(cur.data)\n if cur:\n q.append(cur.left)\n q.append(cur.right)\n return a\n\ndef deSerialize(A):\n if len(A) == 0 or A[0] == '#':\n return None\n new_node = Node(A[0])\n q = []\n q.append(new_node)\n i = 1\n while q:\n cur = q.pop(0)\n if len(A) >= i:\n if A[i] == '#':\n cur.left = None\n i += 1\n else:\n lef_node = Node(A[i])\n cur.left = lef_node\n q.append(cur.left)\n i += 1\n if A[i] == '#':\n cur.right = None\n i += 1\n else:\n rigt_node = Node(A[i])\n cur.right = rigt_node\n q.append(cur.right)\n i += 1\n return new_node"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["1\r\n / \\\r\n 2 3", "10\r\n / \\\r\n 20 30\r\n / \\\r\n 40 60"], "outputs": ["2 1 3", "40 20 60 10 30"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/serialize-and-deserialize-a-binary-tree/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "__init__", "task_id": "TACO_lite/280", "example": [[], []]} +{"requirement": "Given three integers x, y, z, the task is to compute the value of GCD(LCM(x,y), LCM(x,z)) and return the value.\nWhere, GCD = Greatest Common Divisor, LCM = Least Common Multiple.\nExample 1:\nInput: x = 15, y = 20, z = 100\nOutput: 60\nExplanation: GCD(LCM(15,20), LCM(15,100))\n=GCD(60,300)=60.\n\u00c3\u00a2\u00e2\u0082\u00ac\u00e2\u0080\u00b9Example 2:\nInput: x = 30, y = 40, z = 400\nOutput: 120\nExplanation: GCD(LCM(30,40), LCM(30,400))\n=GCD(120,1200)=120.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function findValue() which takes x, y, z as inputs and returns the answer.\nExpected Time Complexity: O(max(log x, log y, log z))\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 x, y, z \u2264 10^{6}", "solutions": ["def findvalue(x, y, z):\n\n def gcd(a, b):\n if b == 0:\n return a\n else:\n return gcd(b, a % b)\n lcm1 = int(x * y / gcd(x, y))\n lcm2 = int(x * z / gcd(x, z))\n return gcd(lcm1, lcm2)", "import math\n\ndef findvalue(x, y, z):\n a = x * y // math.gcd(x, y)\n b = x * z // math.gcd(x, z)\n return math.gcd(a, b)", "def findvalue(x, y, z):\n return Solution.lcm(x, Solution.gcd(y, z))\n\ndef gcd(a, b):\n if a == 0:\n return b\n return Solution.gcd(b % a, a)\n\ndef lcm(a, b):\n return a * b // Solution.gcd(a, b)", "from functools import reduce\n\ndef findvalue(x, y, z):\n gcd = lambda a, b: a if b == 0 else gcd(b, a % b)\n lcd = lambda a, b: int(a * b / gcd(a, b))\n return lcd(x, gcd(y, z))", "def gcd(a, b):\n if b == 0:\n return a\n return self.gcd(b, a % b)\n\ndef findvalue(x, y, z):\n lcmxy = x * y // self.gcd(x, y)\n lcmxz = x * z // self.gcd(x, z)\n return self.gcd(lcmxy, lcmxz)", "def gcd2(a, b):\n while a != b:\n if a > b:\n a -= b\n else:\n b -= a\n return a\n\ndef gcd(a, b):\n if b == 0:\n return a\n else:\n return self.gcd(b, a % b)\n\ndef findvalue(x, y, z):\n gcdNum1 = self.gcd(x, y)\n gcdNum2 = self.gcd(x, z)\n lcm1 = int(x * y / gcdNum1)\n lcm2 = int(x * z / gcdNum2)\n grandGCD = self.gcd(lcm1, lcm2)\n return grandGCD", "import math as m\n\ndef findvalue(x, y, z):\n g1 = m.gcd(x, y)\n g2 = m.gcd(x, z)\n l1 = x * y // g1\n l2 = x * z // g2\n g3 = m.gcd(l1, l2)\n return g3", "import math as m\n\ndef findvalue(x, y, z):\n l = x * y // m.gcd(x, y - x)\n l1 = x * z // m.gcd(x, z - x)\n return m.gcd(l, l1)", "def gcd(a, b):\n while a != 0 and b != 0:\n if a < b:\n b = b % a\n else:\n a = a % b\n if a == 0:\n return b\n else:\n return a\n\ndef findvalue(x, y, z):\n m = x * y // self.gcd(x, y)\n n = x * z // self.gcd(x, z)\n return self.gcd(m, n)", "def gc(n, m):\n while n != 0 and m != 0:\n if n > m:\n n = n % m\n else:\n m = m % n\n if n == 0:\n return m\n else:\n return n\n\ndef findvalue(x, y, z):\n k = x * y // self.gc(x, y)\n c = x * z // self.gc(x, z)\n return self.gc(k, c)", "def findvalue(x, y, z):\n\n def gcd(a, b):\n while b:\n (a, b) = (b, a % b)\n return a\n return gcd(x * y // gcd(x, y), x * z // gcd(x, z))", "import math\n\ndef findvalue(x, y, z):\n k1 = x * y // math.gcd(x, y)\n k2 = x * z // math.gcd(x, z)\n return math.gcd(k1, k2)", "import math\n\ndef findvalue(x, y, z):\n l1 = x * y // math.gcd(x, y)\n l2 = x * z // math.gcd(x, z)\n res = math.gcd(l1, l2)\n return res", "def gcd(x, y):\n return x if y == 0 else self.gcd(y, x % y)\n\ndef findvalue(x, y, z):\n return self.gcd(x // self.gcd(x, y) * y, x // self.gcd(x, z) * z)"], "starter_code": "def findvalue (x, y, z):\n", "input_output": {"inputs": ["x = 15, y = 20, z = 100", "x = 30, y = 40, z = 400"], "outputs": ["60", "120"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/gcd-lcm-and-distributive-property4419/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(max(log x, log y, log z))", "entry_point": "findvalue", "task_id": "TACO_lite/328", "example": [[[15, 20, 100], [30, 40, 400]], ["60", "120"]]} +{"requirement": "Given a sorted and rotated array A of N elements which is rotated at some point, and may contain duplicates and given an element key. Check whether the key exist in the array A or not.\nExample 1:\nInput:\nN = 7\nA[] = {2,5,6,0,0,1,2}\nkey = 0\nOutput:\n1\nExplanation:\n0 is found at index 3.\nExample 2:\nInput:\nN = 7\nA[] = {2,5,6,0,0,1,2}\nkey = 3\nOutput:\n0\nExplanation:\nThere is no element that has value 3.\nYour Task:\nComplete the function search() which takes a integer N and an array A and the Key as input parameters, and returns the answer.\nExpected Time Complexity: O(log N).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 \u2264 N \u2264 5000\n0 \u2264 A[i] \u2264 108\n1 \u2264 key \u2264 108", "solutions": ["def search(n, arr, k):\n if k in arr:\n return 1\n else:\n return 0", "def search(n, arr, k):\n for i in range(len(arr)):\n if arr[i] == k:\n return 1\n return 0", "def search(n, A, key):\n l = 0\n h = n - 1\n while l <= h:\n mid = (l + h) // 2\n if key == A[mid]:\n return 1\n if A[mid] == A[l]:\n l += 1\n continue\n if A[l] <= A[mid]:\n if key >= A[l] and key <= A[mid]:\n h = mid - 1\n else:\n l = mid + 1\n elif A[mid] <= key and key <= A[h]:\n l = mid + 1\n else:\n h = mid - 1\n return 0", "def search(n, arr, k):\n i = 0\n j = n - 1\n while i <= j:\n mid = i + j >> 1\n if arr[mid] == k:\n return 1\n elif arr[i] == k:\n return 1\n elif arr[j] == k:\n return 1\n elif arr[i] == arr[mid] == arr[j]:\n i += 1\n j -= 1\n elif arr[i] < arr[mid]:\n if arr[i] <= k and k <= arr[mid]:\n j = mid - 1\n else:\n i = mid + 1\n elif arr[mid] <= k and k <= arr[j]:\n i = mid + 1\n else:\n j = mid - 1\n return 0", "def search(n, nums, target):\n (left, right) = (0, n - 1)\n while left <= right:\n mid = (left + right) // 2\n curr = nums[mid]\n if curr == target:\n return 1\n elif nums[left] == curr == nums[right]:\n left += 1\n right -= 1\n elif nums[left] <= curr:\n if nums[left] <= target < curr:\n right = mid - 1\n else:\n left = mid + 1\n elif curr < target <= nums[right]:\n left = mid + 1\n else:\n right = mid - 1\n return 0", "def search(n, a, key):\n low = 0\n high = n - 1\n while low <= high:\n mid = low + (high - low) // 2\n if a[mid] == k:\n return 1\n if a[mid] == a[low]:\n low += 1\n continue\n if a[mid] == a[high]:\n high -= 1\n continue\n if a[low] < a[mid]:\n if k >= a[low] and k < a[mid]:\n high = mid - 1\n else:\n low = mid + 1\n elif k > a[mid] and k <= a[high]:\n low = mid + 1\n else:\n high = mid - 1\n return 0", "def search(n, arr, k):\n l = 0\n u = n - 1\n while l <= u:\n while l < u and arr[l] == arr[l + 1]:\n l += 1\n while l < u and arr[u] == arr[u - 1]:\n u -= 1\n mid = l + u >> 1\n if arr[mid] == k:\n return 1\n elif arr[l] <= arr[mid]:\n if arr[l] <= k and arr[mid] >= k:\n u = mid - 1\n else:\n l = mid + 1\n elif arr[u] >= k and arr[mid] <= k:\n l = mid + 1\n else:\n u = mid - 1\n return 0", "def search(n, arr, k):\n (lo, hi) = (0, n - 1)\n while lo <= hi:\n if hi - lo <= 5:\n return 1 if k in arr[lo:hi + 1] else 0\n mid = (lo + hi) // 2\n if arr[mid] == k or arr[lo] == k or arr[hi] == k:\n return 1\n elif arr[lo] == arr[hi] and arr[lo] == arr[mid]:\n lo += 1\n hi -= 1\n elif arr[lo] < arr[mid] or (arr[lo] == arr[mid] and arr[mid] > arr[hi]):\n if arr[lo] < k and k < arr[mid]:\n hi = mid - 1\n else:\n lo = mid + 1\n elif arr[hi] >= arr[mid] or (arr[hi] == arr[mid] and arr[mid] < arr[lo]):\n if arr[mid] < k and k < arr[hi]:\n lo = mid + 1\n else:\n hi = mid + 1\n return 0", "def search(n, arr, k):\n low = 0\n high = n - 1\n while low <= high:\n mid = (low + high) // 2\n if arr[mid] == k:\n return 1\n if arr[low] == arr[mid] and arr[mid] == arr[high]:\n low += 1\n high -= 1\n elif arr[low] <= arr[mid]:\n if arr[low] <= k < arr[mid]:\n high = mid - 1\n else:\n low = mid + 1\n elif arr[mid] <= k <= arr[high]:\n low = mid + 1\n else:\n high = mid - 1\n return 0", "def search(n, nums, target):\n if nums == None or len(nums) == 0:\n return 0\n low = 0\n high = len(nums) - 1\n while low <= high and nums[low] == nums[high]:\n if nums[low] == target:\n return 1\n low += 1\n high -= 1\n while low <= high:\n mid = low + high >> 1\n if nums[mid] == target:\n return 1\n if nums[mid] >= nums[low]:\n if target >= nums[low] and target < nums[mid]:\n high = mid - 1\n else:\n low = mid + 1\n elif target <= nums[high] and target > nums[mid]:\n low = mid + 1\n else:\n high = mid - 1\n return 0", "def search(n, arr, k):\n ans = 0\n for i in range(n):\n if arr[i] == k:\n ans = 1\n else:\n continue\n return ans", "def search(n, arr, k):\n (left, right) = (0, len(arr) - 1)\n while left <= right:\n mid = (left + right) // 2\n if arr[mid] == k:\n return 1\n if arr[mid] == arr[left] and mid != left:\n left += 1\n right -= 1\n if arr[left] <= arr[mid]:\n if arr[mid] < k or arr[left] > k:\n left = mid + 1\n else:\n right = mid - 1\n elif arr[right] < k or arr[mid] > k:\n right = mid - 1\n else:\n left = mid + 1\n return 0", "def search(n, nums, target):\n high = len(nums) - 1\n low = 0\n mid = (high + low) // 2\n while high >= low:\n mid = (high + low) // 2\n if nums[mid] == target:\n return 1\n if nums[low] == target:\n return 1\n if nums[high] == target:\n return 1\n if nums[mid] == nums[high] and nums[high] == nums[low]:\n high -= 1\n low += 1\n continue\n if nums[low] <= nums[mid]:\n if target >= nums[low] and target <= nums[mid]:\n high = mid - 1\n continue\n else:\n low = mid + 1\n elif target >= nums[mid] and target <= nums[high]:\n low = mid + 1\n continue\n else:\n high = mid - 1\n return 0", "def search(n, A, key):\n for num in A:\n if num == key:\n return 1\n return 0", "def search(n, nums, target):\n s = 0\n e = n - 1\n while s < e and nums[s] == nums[s + 1]:\n s = s + 1\n while s < e and nums[e] == nums[e - 1]:\n e = e - 1\n while s <= e:\n mid = s + e >> 1\n if nums[mid] == target:\n return 1\n if nums[s] <= nums[mid]:\n if nums[s] <= target and nums[mid] >= target:\n e = mid - 1\n else:\n s = mid + 1\n elif nums[mid] <= target and nums[e] >= target:\n s = mid + 1\n else:\n e = mid - 1\n return 0", "def search(n, a, x):\n low = 0\n high = n - 1\n while low <= high:\n mid = low + (high - low) // 2\n if a[mid] == x:\n return 1\n elif a[low] == a[mid]:\n low += 1\n mid += 1\n elif a[low] < a[mid]:\n if a[low] <= x and a[mid] >= x:\n high = mid - 1\n else:\n low = mid + 1\n elif x >= a[mid] and x <= a[high]:\n low = mid + 1\n else:\n high = mid - 1\n return 0", "def search(n, arr, k):\n x = 0\n for i in range(n):\n if arr[i] == k:\n x = 1\n break\n return x", "def search(n, nums, target):\n (l, r) = (0, len(nums) - 1)\n while l <= r:\n mid = (l + r) // 2\n if target == nums[mid]:\n return 1\n if nums[l] < nums[mid]:\n if target > nums[mid] or target < nums[l]:\n l = mid + 1\n else:\n r = mid - 1\n elif nums[l] > nums[mid]:\n if target < nums[mid] or target > nums[r]:\n r = mid - 1\n else:\n l = mid + 1\n else:\n l += 1\n return 0", "def search(n, arr, target):\n l = 0\n h = n - 1\n m = l + (h - l) // 2\n while l <= h:\n if arr[m] == target:\n return 1\n if arr[m] == arr[l] and arr[m] == arr[h]:\n l += 1\n h -= 1\n elif arr[l] <= arr[m]:\n if arr[l] <= target and target < arr[m]:\n h = m - 1\n else:\n l = m + 1\n elif arr[m] < target and target <= arr[h]:\n l = m + 1\n else:\n h = m - 1\n m = (l + h) // 2\n return 0", "def search(n, arr, k):\n low = 0\n high = n - 1\n while low <= high:\n mid = (low + high) // 2\n if arr[mid] == k:\n return 1\n if arr[low] == arr[mid] == arr[high]:\n for i in range(low, high + 1):\n if arr[i] == k:\n return 1\n if arr[low] <= arr[mid]:\n if k >= arr[low] and k <= arr[mid]:\n high = mid - 1\n else:\n low = mid + 1\n elif k >= arr[mid] and k <= arr[high]:\n low = mid + 1\n else:\n high = mid - 1\n return 0", "def search(n, arr, k):\n try:\n ans = arr.index(k)\n if ans >= 0:\n return 1\n except:\n return 0"], "starter_code": "def search(n, arr, k):\n", "input_output": {"inputs": ["N = 7\r\nA[] = {2,5,6,0,0,1,2}\r\nkey = 0", "N = 7\r\nA[] = {2,5,6,0,0,1,2}\r\nkey = 3"], "outputs": ["1", "0"]}, "difficulty": "MEDIUM", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/search-in-rotated-array-2/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log N).", "entry_point": "search", "task_id": "TACO_lite/276", "example": [[[7, [2, 5, 6, 0, 0, 1, 2], 0], [7, [2, 5, 6, 0, 0, 1, 2], 3]], ["1", "0"]]} +{"requirement": "## Task\n\nGenerate a sorted list of all possible IP addresses in a network.\n\nFor a subnet that is not a valid IPv4 network return `None`.\n\n## Examples\n```\nipsubnet2list(\"192.168.1.0/31\") == [\"192.168.1.0\", \"192.168.1.1\"]\nipsubnet2list(\"213.256.46.160/28\") == None\n```", "solutions": ["import ipaddress as ip\n\ndef ipsubnet2list(subnet):\n try:\n return list(map(str, ip.ip_network(subnet).hosts()))\n except:\n pass", "def ip_to_int(ip):\n return sum((int(i[0]) << i[1] * 8 for i in zip(ip.split('.'), range(3, -1, -1))))\n\ndef int_to_ip(num):\n return '.'.join((str(num >> i * 8 & 255) for i in range(3, -1, -1)))\n\ndef ipsubnet2list(subnet):\n (net, prelen) = subnet.split('/')\n (num, mask) = (ip_to_int(net), 1 << 32 - int(prelen))\n if net != int_to_ip(num):\n return None\n if mask == 2:\n return [int_to_ip(num), int_to_ip(num + 1)]\n return [int_to_ip(num ^ i) for i in range(1, mask - 1)]", "from ipaddress import ip_network\nfrom typing import List, Union\n\ndef ipsubnet2list(subnet: str) -> Union[List[str], None]:\n try:\n return list(map(str, ip_network(subnet).hosts()))\n except ValueError:\n return", "def cidr_to_bits(subnet):\n subnet_int = int(subnet[-2:])\n mask_in_bits = [(1, 0)[i > subnet_int] for i in range(1, 33)]\n return mask_in_bits\n\ndef ip_bits(subnet):\n ip_bits_str = list([format(int(x), '#010b')[2:] for x in subnet[:-3].split('.')])\n ip_bits_int = [int(i) for x in ip_bits_str for i in x]\n return ip_bits_int\n\ndef f_addr_bits(x):\n return [i & j for (i, j) in zip(ip_bits(x), cidr_to_bits(x))]\n\ndef l_addr_bits(x):\n not_on_mask = [(0, 1)[i == 0] for i in cidr_to_bits(x)]\n return [i | j for (i, j) in zip(f_addr_bits(x), not_on_mask)]\n\ndef address_to_int(bits_lst):\n return [int(''.join((str(bits_lst[y + i]) for i in range(8))), 2) for y in range(0, 32, 8)]\n\ndef list_of_addresses(x):\n first_address = address_to_int(f_addr_bits(x))\n last_address = address_to_int(l_addr_bits(x))\n octets_ranges = [[i for i in range(i, j + 1)] if j - i != 0 else [i] for (i, j) in zip(first_address, last_address)]\n addresses = []\n for first_oct in octets_ranges[0]:\n for second in octets_ranges[1]:\n for third in octets_ranges[2]:\n for fourth in octets_ranges[3]:\n addresses.append(f'{first_oct}.{second}.{third}.{fourth}')\n return addresses\n\ndef ipsubnet2list(subnet):\n result = list_of_addresses(subnet)\n if subnet[:-3] in result:\n if len(result) == 2:\n return result\n return result[1:-1]\n else:\n return None", "from ipaddress import ip_network\n\ndef ipsubnet2list(subnet):\n try:\n return [ip.compressed for ip in ip_network(subnet).hosts()]\n except ValueError:\n return", "from ipaddress import IPv4Network, AddressValueError\n\ndef ipsubnet2list(subnet):\n try:\n return list(map(str, IPv4Network(subnet).hosts()))\n except AddressValueError:\n return None", "from ipaddress import IPv4Network, AddressValueError\n\ndef ipsubnet2list(subnet):\n try:\n ip_list = [str(ip) for ip in IPv4Network(subnet)]\n return ip_list[1:-1] if len(ip_list) > 2 else ip_list\n except AddressValueError:\n return None", "def ipsubnet2list(subnet):\n import ipaddress\n ls = []\n try:\n for i in ipaddress.IPv4Network(subnet):\n ls.append(str(i))\n except:\n return None\n return ls[1:-1] if len(ls) > 2 else ls", "def ipsubnet2list(subnet):\n (netaddr, prefix) = subnet.split('/')\n if not all([0 <= int(x) < 256 for x in netaddr.split('.')]):\n return None\n netaddrbyte = 0\n for x in netaddr.split('.'):\n netaddrbyte = netaddrbyte * 256 + int(x)\n r = []\n for i in range(2 ** (32 - int(prefix))):\n addr = netaddrbyte + i\n a = []\n for _ in range(4):\n a.append(addr % 256)\n addr //= 256\n r.append('.'.join(map(str, a[::-1])))\n if int(prefix) < 31:\n r = r[1:-1]\n return r", "def ipsubnet2list(s):\n try:\n return [str(x) for x in list(__import__('ipaddress').ip_network(s).hosts())]\n except ValueError:\n return None"], "starter_code": "def ipsubnet2list(subnet):\n", "input_output": {"fn_name": "ipsubnet2list", "inputs": [["192.168.1.0/31"], ["195.20.15.0/28"], ["174.0.153.152/29"], ["213.192.46.160/28"], ["213.256.46.160/28"]], "outputs": [[["192.168.1.0", "192.168.1.1"]], [["195.20.15.1", "195.20.15.2", "195.20.15.3", "195.20.15.4", "195.20.15.5", "195.20.15.6", "195.20.15.7", "195.20.15.8", "195.20.15.9", "195.20.15.10", "195.20.15.11", "195.20.15.12", "195.20.15.13", "195.20.15.14"]], [["174.0.153.153", "174.0.153.154", "174.0.153.155", "174.0.153.156", "174.0.153.157", "174.0.153.158"]], [["213.192.46.161", "213.192.46.162", "213.192.46.163", "213.192.46.164", "213.192.46.165", "213.192.46.166", "213.192.46.167", "213.192.46.168", "213.192.46.169", "213.192.46.170", "213.192.46.171", "213.192.46.172", "213.192.46.173", "213.192.46.174"]], [null]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Networks"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5980d4e258a9f5891e000062", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "ipsubnet2list", "task_id": "TACO_lite/316", "example": [[["192.168.1.0/31"], ["213.256.46.160/28"]], [["192.168.1.0", "192.168.1.1"], null]]} +{"requirement": "Given an array of non-negative integers, you are initially positioned at the first index of the array.\n\nEach element in the array represents your maximum jump length at that position.\n\nDetermine if you are able to reach the last index.\n\nExample 1:\n\n\nInput: [2,3,1,1,4]\nOutput: true\nExplanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.\n\n\nExample 2:\n\n\nInput: [3,2,1,0,4]\nOutput: false\nExplanation: You will always arrive at index 3 no matter what. Its maximum\n\u00a0 jump length is 0, which makes it impossible to reach the last index.", "solutions": ["def canjump(nums):\n n = len(nums)\n can = True\n smallest_idx = n - 1\n for i in range(n - 2, -1, -1):\n can = i + nums[i] >= smallest_idx\n if can:\n smallest_idx = i\n return can", "def canjump(nums):\n n = len(nums)\n maxReachable = 0\n for (i, num) in enumerate(nums):\n if num >= n - i - 1:\n return True\n flag = False\n if i + num >= maxReachable:\n for j in range(i + 1, num + i + 1):\n if nums[j] > 0:\n flag = True\n break\n if flag == False:\n return False\n maxReachable = max(maxReachable, i + num)\n return True", "def canjump(nums):\n last = len(nums) - 1\n for i in range(len(nums) - 2, -1, -1):\n if i + nums[i] >= last:\n last = i\n return True if not last else False", "def canjump(nums):\n m = 0\n for i in range(len(nums)):\n if i > m:\n return False\n m = max(m, nums[i] + i)\n return True", "def canjump(nums):\n if not nums:\n return False\n res = [False for num in nums]\n res[0] = True\n end = 0\n for (i, num) in enumerate(nums):\n if res[i] == False:\n continue\n if i + num >= len(nums):\n return True\n if end < i + num:\n for j in range(end + 1, i + num + 1):\n res[j] = True\n end = i + num\n return res[-1]", "def canjump(nums):\n lastPos = len(nums) - 1\n for i in range(len(nums) - 1, -1, -1):\n if i + nums[i] >= lastPos:\n lastPos = i\n return lastPos == 0", "def canjump(nums):\n if len(nums) == 25003:\n return False\n length = len(nums)\n accessible = [False] * length\n accessible[0] = True\n for i in range(length - 1):\n if not accessible[i]:\n return False\n for j in range(i + 1, min(nums[i] + i + 1, length)):\n accessible[j] = True\n if j == length - 1:\n return True\n return accessible[length - 1]", "def canjump(nums):\n lo = hi = 0\n nexthi = 0\n while hi < len(nums) - 1:\n for i in range(lo, hi + 1):\n nexthi = max(nexthi, i + nums[i])\n if hi == nexthi:\n return False\n (lo, hi) = (hi + 1, nexthi)\n return True", "def canjump(nums):\n last = len(nums) - 1\n i = last\n while i >= 0:\n if nums[i] + i >= last:\n last = i\n i -= 1\n return last == 0", "def canjump(nums):\n near = len(nums) - 1\n for i in range(len(nums) - 2, -1, -1):\n if near <= i + nums[i]:\n near = i\n return near == 0", "def canjump(nums):\n n_nums = len(nums)\n surfix = [0 for _ in range(n_nums + 1)]\n surfix[n_nums - 1] = 1\n for i in range(n_nums - 2, -1, -1):\n accu = surfix[i + 1] - surfix[min(n_nums, i + nums[i] + 1)]\n if accu > 0:\n surfix[i] = surfix[i + 1] + 1\n else:\n surfix[i] = surfix[i + 1]\n return surfix[0] > surfix[1]", "def canjump(nums):\n if not nums or len(nums) == 1:\n return True\n status = [False] * (len(nums) - 1) + [True]\n curr = len(nums) - 1\n for j in range(len(nums) - 2, -1, -1):\n if status[min(len(nums) - 1, j + nums[j])]:\n for i in range(j, curr):\n status[i] = True\n curr = j\n return status[0]"], "starter_code": "def canjump(nums: List[int]) -> bool:\n", "input_output": {"fn_name": "canJump", "inputs": [[[2, 3, 1, 1, 4]]], "outputs": [true]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Dynamic Programming", "Greedy"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures", "Greedy algorithms"], "skill_types": ["Dynamic programming", "Data structures", "Greedy algorithms"], "url": "https://leetcode.com/problems/jump-game/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "canjump", "task_id": "TACO_lite/332", "example": [[], []]} +{"requirement": "write me a function `stringy` that takes a `size` and returns a `string` of alternating `'1s'` and `'0s'`.\n\nthe string should start with a `1`.\n\na string with `size` 6 should return :`'101010'`.\n\nwith `size` 4 should return : `'1010'`.\n\nwith `size` 12 should return : `'101010101010'`.\n\nThe size will always be positive and will only use whole numbers.", "solutions": ["def stringy(size):\n return ''.join([str(i % 2) for i in range(1, size + 1)])", "def stringy(size):\n return ('10' * size)[:size]", "from itertools import cycle, islice\n\ndef stringy(size):\n return ''.join(islice(cycle('10'), size))", "def stringy(size):\n s = ''\n for x in range(0, size):\n s += str('1') if x % 2 == 0 else str('0')\n return s", "def stringy(size):\n return '10' * (size // 2) + '1' * (size % 2)", "def stringy(size):\n return '10' * (size // 2) if size % 2 == 0 else '10' * (size // 2) + '1'", "def stringy(size):\n res = ''\n for x in range(0, size):\n res += '1' if x % 2 == 0 else '0'\n return res", "def stringy(size):\n str = ''\n while len(str) < size:\n str += '1'\n if len(str) < size:\n str += '0'\n return str", "stringy = lambda size: ('10' * (size // 2 + 1))[:size]", "def stringy(size):\n arr = []\n for i in range(size):\n if i % 2 == 0:\n arr.append('1')\n else:\n arr.append('0')\n return ''.join(arr)", "stringy = lambda size: ('10' * size)[:size]", "ONE_ZERO = '10'\n\ndef stringy(size):\n return ''.join((ONE_ZERO[a % 2] for a in range(size)))", "def stringy(size: int) -> str:\n return ''.join([str(_ % 2) for _ in range(1, size + 1)])", "def gen():\n while True:\n yield '1'\n yield '0'\n\ndef stringy(size):\n g = gen()\n return ''.join((next(g) for _ in range(size)))", "stringy = lambda n: ('10' * n)[:n]", "def stringy(size):\n return ''.join(['1' if a % 2 == 0 else '0' for a in range(size)])", "def stringy(size):\n return ''.join([str((a + 1) % 2) for a in range(size)])", "def stringy(size):\n binary = '10'\n s = size * binary\n return s[:size]", "def stringy(size):\n return ''.join(map(str, map(int, map(lambda x: not x % 2, range(size)))))", "def stringy(size):\n if size % 2 == 0:\n return '10' * int(size / 2)\n else:\n x = size - 1\n return '10' * int(x / 2) + '1'", "def stringy(size):\n return ''.join(('{:d}'.format(not i % 2) for i in range(size)))", "def stringy(size):\n return ('1' * size).replace('11', '10')", "def stringy(size):\n return __import__('re').sub('11', '10', '1' * size)", "def stringy(size):\n ans = ''\n for place in range(size):\n if place % 2 == 0:\n ans += '1'\n else:\n ans += '0'\n return ans", "def stringy(size):\n string = ''\n for num in range(size):\n if num % 2 == 0:\n string += '1'\n else:\n string += '0'\n return string", "def stringy(size):\n return str('10' * size)[:size]", "def stringy(size):\n x = True\n s = ''\n while size > 0:\n s += str(int(x))\n x = not x\n size -= 1\n return s", "def stringy(size):\n output_string = ''\n for i in range(size):\n if i % 2 == 0:\n output_string += '1'\n else:\n output_string += '0'\n return output_string", "def stringy(size):\n n = int(size / 2)\n i = 0\n c = '10'\n output = ''\n for i in range(n):\n output = output + c\n i += 1\n if size % 2 == 1:\n output = output + '1'\n return output", "def stringy(size):\n st = '1'\n i = 0\n while i < size - 1:\n if st[i] == '1':\n st = st + '0'\n else:\n st = st + '1'\n i += 1\n return st", "def stringy(size):\n strng = ''\n if size % 2 == 1:\n for i in range((size + 1) // 2):\n strng += '10'\n return strng[:-1]\n else:\n for i in range(size // 2):\n strng += '10'\n return strng", "def stringy(size):\n counter = 0\n res = ''\n while counter < size:\n if counter % 2 == 0:\n res += '1'\n counter += 1\n elif counter % 2 == 1:\n res += '0'\n counter += 1\n return res", "def stringy(size):\n (start, result) = ('1', '')\n for i in range(size):\n result += start\n start = '1' if start == '0' else '0'\n return result", "def stringy(size):\n x = 0\n list_size = []\n for i in range(size):\n if x % 2:\n i = 0\n else:\n i = 1\n x += 1\n list_size.append(i)\n return str(''.join(map(str, list_size)))", "def stringy(size):\n temp = ''\n for el in range(size):\n if el % 2:\n temp += '0'\n else:\n temp += '1'\n return temp", "def stringy(size):\n c = 0\n res = ''\n for i in range(size):\n c += 1\n if i == 0:\n res += '1'\n elif i == 1:\n res += '0'\n elif i % 2 == 0:\n res += '1'\n else:\n res += '0'\n return res", "def stringy(size):\n return ''.join((str(el % 2) for el in range(1, size + 1)))", "def stringy(size):\n value = True\n result = ''\n for i in range(size):\n result += str(int(value))\n value = not value\n return result", "def stringy(size):\n size - int(size)\n counter = 1\n word = ''\n while len(word) < size:\n if counter % 2 == 0:\n word = word + '0'\n if counter % 2 != 0:\n word = word + '1'\n counter += 1\n return word", "def stringy(size):\n s = ''\n for i in range(0, size):\n if i % 2 == 0:\n j = '1'\n s = s + j\n else:\n j = '0'\n s = s + j\n return s", "def stringy(size):\n st = ''\n while size > 0:\n st += '1'\n size -= 1\n if size < 1:\n break\n st += '0'\n size -= 1\n return st", "def stringy(size):\n return ''.join((str(x & 1) for x in range(1, size + 1)))", "def stringy(size):\n arr = []\n cnt = 0\n while True:\n arr.append('1')\n cnt += 1\n if cnt == size:\n break\n arr.append('0')\n cnt += 1\n if cnt == size:\n break\n return ''.join(arr)", "import math\n\ndef stringy(size):\n return str('10' * math.ceil(size / 2))[:size]", "def stringy(size):\n result = '10' * (size // 2)\n if size % 2 == 1:\n result = result + '1'\n return result", "from math import ceil\n\ndef stringy(size):\n return '10' * (size // 2) if size % 2 == 0 else str('10' * ceil(size / 2))[:-1]", "stringy = lambda l: '10' * (l // 2) + '1' * (l % 2)", "def stringy(size):\n x = ''\n while len(x) < size:\n x += '1'\n if len(x) < size:\n x += '0'\n return x", "def stringy(size):\n string = ''\n if size % 2 == 0:\n return '10' * int(size / 2)\n else:\n return str('10' * int(size / 2 + 1))[:-1]", "def stringy(size):\n x = ''\n n = 1\n while n <= size:\n if n % 2 == 1:\n x += '1'\n n += 1\n else:\n x += '0'\n n += 1\n return x", "def stringy(size):\n alot = '10' * 1000\n return alot[0:int(size)]", "def stringy(size):\n count = 3\n arr = ''\n for i in range(size):\n if count % 2 == 1:\n arr += '1'\n count += 1\n else:\n arr += '0'\n count += 1\n return arr", "def stringy(size):\n (c, l) = ('1', [])\n for i in range(size):\n if c == '1':\n l.append(c)\n c = '0'\n elif c == '0':\n l.append(c)\n c = '1'\n return ''.join(l)", "def stringy(size):\n for x in range(1, size + 1, 1):\n if x == 1:\n t = '1'\n elif t[-1] == '1':\n t += '0'\n else:\n t += '1'\n return t", "def stringy(size):\n return '10' * int(size / 2) if not size % 2 else '10' * int(size / 2) + '1'", "def stringy(size):\n res = ''\n n = 0\n while n < size:\n if n == size:\n break\n else:\n res += '1'\n n += 1\n if n == size:\n break\n else:\n res += '0'\n n += 1\n return res", "def stringy(size):\n x = ''\n while size > len(x):\n x = x + '1'\n while size > len(x):\n x = x + '0'\n break\n return x", "from itertools import islice, cycle\n\ndef stringy(size):\n return ''.join((str(i) for i in islice(cycle([1, 0]), 0, size)))", "def stringy(size):\n if size == 1:\n return '1'\n elif size % 2 == 0:\n return '10' * (size // 2)\n elif size != 1 and size % 2 == 1:\n return '1' + '01' * (size // 2)", "from math import ceil\n\ndef stringy(size):\n return '0'.join('1' * ceil(size / 2)) + '0' * ((size - 1) % 2)", "def stringy(size):\n res = ''\n t = size\n while t > 0:\n if t % 2 == 1:\n res = '1' + res\n else:\n res = '0' + res\n t -= 1\n return res", "def stringy(size):\n if size == 1:\n return '1'\n if size % 2 == 0:\n return '10' * int(size / 2)\n return '10' * int((size - 1) / 2) + '1'", "def stringy(size):\n choices = [1, 0]\n a = ''\n for i in range(size):\n a += str(choices[i % 2])\n return a", "def stringy(size):\n return ''.join([['1', '0'][loop % 2] for loop in range(size)])", "def stringy(size):\n outStr = ''\n lastAdd = 0\n for x in range(size):\n if lastAdd == 0:\n outStr += str(1)\n lastAdd = 1\n else:\n outStr += str(0)\n lastAdd = 0\n return outStr", "def stringy(size):\n i = 0\n list1 = ['1']\n for n in range(size - 1):\n if i % 2 == 0:\n list1.append('0')\n i += 1\n else:\n list1.append('1')\n i += 1\n return ''.join(list1)", "def stringy(size):\n res = ''\n n = True\n for i in range(size):\n if n:\n res += '1'\n n = False\n else:\n res += '0'\n n = True\n return res", "def stringy(size):\n S = ''\n nextChar = '1'\n for i in range(size):\n S += nextChar\n if nextChar == '1':\n nextChar = '0'\n else:\n nextChar = '1'\n return S", "import math\n\ndef stringy(size):\n if size == 1:\n return '1'\n elif size % 2 == 0:\n return '10' * int(size / 2)\n else:\n return '10' * math.floor(size / 2) + '1'"], "starter_code": "def stringy(size):\n", "input_output": {"fn_name": "stringy", "inputs": [[3], [5], [12], [26], [28]], "outputs": [["101"], ["10101"], ["101010101010"], ["10101010101010101010101010"], ["1010101010101010101010101010"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms", "Binary"], "name": null, "source": "codewars", "tags": ["String algorithms", "Bit manipulation"], "skill_types": ["Bit manipulation"], "url": "https://www.codewars.com/kata/563b74ddd19a3ad462000054", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "stringy", "task_id": "TACO_lite/238", "example": [[[6], [4], [12]], ["101010", "1010", "101010101010"]]} +{"requirement": "Find the 2nd largest integer in array\nIf the array has no 2nd largest integer then return nil.\nReject all non integers elements and then find the 2nd largest integer in array\n\nfind_2nd_largest([1,2,3]) => 2\n\nfind_2nd_largest([1,1,1,1,1]) => nil\nbecause all elements are same. Largest no. is 1. and there is no 2nd largest no.\n\nfind_2nd_largest([1,'a','2',3,3,4,5,'b']) => 4\nas after rejecting non integers array will be [1,3,3,4,5]\nLargest no. is 5. and 2nd largest is 4.\n\nReturn nil if there is no 2nd largest integer.\nTake care of big numbers as well", "solutions": ["def find_2nd_largest(arr):\n arr = sorted((i for i in set(arr) if type(i) == int))\n return arr[-2] if len(arr) > 1 else None", "def find_2nd_largest(arr):\n newarr = sorted(list({x for x in arr if type(x) == int}))\n return newarr[-2] if len(newarr) > 1 else None", "def find_2nd_largest(arr):\n (a, b) = (float('-inf'), float('-inf'))\n for n in arr:\n if isinstance(n, int):\n if n > b:\n b = n\n if b > a:\n (a, b) = (b, a)\n return None if a == b else b", "from heapq import nlargest\n\ndef find_2nd_largest(arr):\n two = nlargest(2, {v for v in arr if isinstance(v, int)})\n if len(two) == 2:\n return two[1]", "def find_2nd_largest(arr):\n return next(iter(sorted((n for n in set(arr) if type(n) == int))[-2:-1]), None)", "def find_2nd_largest(arr):\n res = [arr[i] for i in range(0, len(arr)) if isinstance(arr[i], int)]\n res.sort(reverse=True)\n if len(set(arr)) == 1:\n return None\n else:\n return res[1]", "def find_2nd_largest(arr):\n SECOND_lARGEST = -2\n arr_set = set(arr)\n numbers = sorted((number for number in arr_set if type(number) == int))\n return numbers[SECOND_lARGEST] if len(numbers) > 1 else None", "def find_2nd_largest(arr):\n from collections import defaultdict\n d = defaultdict(list)\n for elem in arr:\n d[type(elem)].append(elem)\n numbers = d[int]\n largest_num = 0\n second_largest_num = 0\n for number in numbers:\n if largest_num < number:\n largest_num = number\n for number in numbers:\n if second_largest_num < number and number < largest_num:\n second_largest_num = number\n if second_largest_num == 0:\n return None\n else:\n return second_largest_num", "def find_2nd_largest(arr):\n xs = sorted({x for x in arr if isinstance(x, int)}, reverse=True)\n if len(xs) > 1 and xs[0] != xs[1]:\n return xs[1]", "def filter_int(arr):\n res = []\n for i in arr:\n if type(i) == int:\n res.append(i)\n else:\n continue\n return res\n\ndef sort(arr):\n for i in range(len(arr)):\n for j in range(len(arr) - 1):\n if arr[j] > arr[j + 1]:\n (arr[j], arr[j + 1]) = (arr[j + 1], arr[j])\n return arr\n\ndef is_diff(arr):\n count = 0\n res = None\n for i in range(len(arr) - 1):\n if arr[i] != arr[i + 1]:\n count += 1\n res = True\n break\n else:\n res = False\n return res\n\ndef sec_big(a, b):\n if a > b:\n return b\n else:\n return a\n\ndef find_2nd_largest(arr):\n filtered_list = filter_int(arr)\n sorted_list = sort(filtered_list)\n if is_diff(sorted_list) == True:\n a = sorted_list[len(sorted_list) - 1]\n b = sorted_list[len(sorted_list) - 2]\n sec_largest_elem = sec_big(a, b)\n return sec_largest_elem\n else:\n return None"], "starter_code": "def find_2nd_largest(arr):\n", "input_output": {"fn_name": "find_2nd_largest", "inputs": [[[1, 2, 3]], [[1, 1, 1, 1, 1, 1, 1]], [[1, "a", "2", 3, 3, 4, 5, "b"]], [[1, "a", "2", 3, 3, 3333333333333333333334, 544444444444444444444444444444, "b"]]], "outputs": [[2], [null], [4], [3333333333333333333334]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/55a58505cb237a076100004a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "find_2nd_largest", "task_id": "TACO_lite/305", "example": [[], []]} +{"requirement": "Given a string s, the power of the string is the maximum length of a non-empty substring that\u00a0contains only one unique character.\nReturn the power\u00a0of the string.\n\u00a0\nExample 1:\nInput: s = \"leetcode\"\nOutput: 2\nExplanation: The substring \"ee\" is of length 2 with the character 'e' only.\n\nExample 2:\nInput: s = \"abbcccddddeeeeedcba\"\nOutput: 5\nExplanation: The substring \"eeeee\" is of length 5 with the character 'e' only.\n\nExample 3:\nInput: s = \"triplepillooooow\"\nOutput: 5\n\nExample 4:\nInput: s = \"hooraaaaaaaaaaay\"\nOutput: 11\n\nExample 5:\nInput: s = \"tourist\"\nOutput: 1\n\n\u00a0\nConstraints:\n\n1 <= s.length <= 500\ns contains only lowercase English letters.", "solutions": ["def maxpower(s: str) -> int:\n n = len(s)\n count = 0\n res = s[0]\n cur_count = 1\n for i in range(n):\n if i < n - 1 and s[i] == s[i + 1]:\n cur_count += 1\n else:\n if cur_count > count:\n count = cur_count\n res = s[i]\n cur_count = 1\n return count", "def maxpower(s: str) -> int:\n cnt = 0\n current = s[0]\n current_cnt = 1\n for l in s[1:]:\n if l == current:\n current_cnt += 1\n else:\n if current_cnt > cnt:\n cnt = current_cnt\n current = l\n current_cnt = 1\n if current_cnt > cnt:\n cnt = current_cnt\n return cnt", "def maxpower(s: str) -> int:\n c = {'power': 1}\n for i in range(len(s)):\n if i == len(s) - 1:\n break\n if ord(s[i]) == ord(s[i + 1]):\n c['power'] += 1\n else:\n c['new start#%s' % i] = c['power']\n c['power'] = 1\n return max(c.values())", "def maxpower(s: str) -> int:\n z = []\n c = 0\n if len(s) == 1:\n return 1\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n c = c + 1\n else:\n z.append(c)\n c = 0\n z.append(c)\n return max(z) + 1", "def maxpower(s: str) -> int:\n if len(s) <= 1:\n return len(s)\n last_char = s[0]\n count = 1\n max_count = 0\n for c in s[1:]:\n if c == last_char:\n count += 1\n else:\n if count > max_count:\n max_count = count\n count = 1\n last_char = c\n if count > max_count:\n max_count = count\n return max_count", "def maxpower(s: str) -> int:\n prev = None\n count = 0\n max_count = 0\n for char in s:\n if char == prev:\n count += 1\n else:\n prev = char\n count = 1\n max_count = max(max_count, count)\n return max_count", "def maxpower(s: str) -> int:\n seq = 1\n max_seq = 1\n for i in range(1, len(s)):\n if s[i] == s[i - 1]:\n seq += 1\n else:\n max_seq = max(max_seq, seq)\n seq = 1\n max_seq = max(max_seq, seq)\n return max_seq", "def maxpower(s: str) -> int:\n count = 0\n max_count = 0\n previous = None\n for c in s:\n if c != previous:\n previous = c\n count = 1\n else:\n count += 1\n max_count = max(max_count, count)\n return max_count", "def maxpower(s: str) -> int:\n ans = 0\n consec_count_per_letter = 1\n prev_letter = s[0]\n if len(s) == 1:\n return 1\n for i in range(1, len(s)):\n if s[i] == prev_letter:\n consec_count_per_letter += 1\n else:\n consec_count_per_letter = 1\n prev_letter = s[i]\n ans = max(ans, consec_count_per_letter)\n return ans", "def maxpower(s: str) -> int:\n c = 1\n maxc = c\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n c += 1\n maxc = max(maxc, c)\n else:\n c = 1\n return maxc", "def maxpower(s: str) -> int:\n maxcount = 1\n i = 0\n while i < len(s) - 1:\n count = 1\n while i < len(s) - 1 and s[i] == s[i + 1]:\n i = i + 1\n count = count + 1\n if count > maxcount:\n maxcount = count\n if i < len(s) - 1:\n i = i + 1\n return maxcount"], "starter_code": "def maxpower(s: str) -> int:\n", "input_output": {"fn_name": "maxPower", "inputs": [["\"leetcode\""]], "outputs": [2]}, "difficulty": "EASY", "raw_tags": ["String"], "name": null, "source": "leetcode", "tags": ["String algorithms"], "skill_types": [], "url": "https://leetcode.com/problems/consecutive-characters/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "maxpower", "task_id": "TACO_lite/224", "example": [[["leetcode"], ["abbcccddddeeeeedcba"], ["triplepillooooow"], ["hooraaaaaaaaaaay"], ["tourist"]], ["2", "5", "5", "11", "1"]]} +{"requirement": "Complete the solution so that it reverses all of the words within the string passed in. \n\nExample:\n\n```python\nreverseWords(\"The greatest victory is that which requires no battle\")\n// should return \"battle no requires which that is victory greatest The\"\n```", "solutions": ["def reversewords(str):\n return ' '.join(str.split(' ')[::-1])", "def reversewords(str):\n return ' '.join(reversed(str.split(' ')))", "def reversewords(string):\n return ' '.join(reversed(string.split()))", "def reversewords(str):\n k = str.split(' ')\n k.reverse()\n str = ' '.join(k)\n return str", "def reversewords(string):\n return ' '.join(string.split()[::-1])", "def reversewords(str):\n str_list = str.split(' ')\n rev_list = str_list[::-1]\n rev_str = ' '.join(rev_list)\n return rev_str", "def reversewords(str):\n str_split = str.split()\n rev_words = []\n for i in range(len(str_split) - 1, -1, -1):\n rev_words.append(str_split[i])\n return ' '.join(rev_words)", "def reversewords(str):\n s = str.split(' ')\n string = []\n for e in s:\n string.insert(0, e)\n return ' '.join(string)", "def reversewords(str):\n new_arr = []\n for word in str.split():\n new_arr.append(word)\n new_arr.reverse()\n return ' '.join(new_arr)", "reversewords = lambda s: ' '.join(s.split(' ')[::-1])", "reversewords = lambda s: ' '.join(reversed(s.split(' ')))", "def reversewords(str):\n return ' '.join([i for i in str.split(' ')[::-1]])", "import re\n\ndef reversewords(str):\n return ''.join(re.split('(\\\\s+)', str)[::-1])", "def reversewords(s):\n arr = s.split()\n arr = arr[::-1]\n str = ''\n for el in arr:\n str += el + ' '\n return str[:-1]", "def reversewords(str):\n a = str.split(' ')\n b = ''\n c = a[::-1]\n for i in range(0, len(a)):\n if i != len(a) - 1:\n b += c[i] + ' '\n else:\n b += c[i]\n return b", "reversewords = lambda ss: ' '.join(ss.split(' ')[-1::-1])", "def reversewords(str):\n liststr = str.split()\n liststr.reverse()\n newstr = ''\n for i in range(len(liststr)):\n newstr += liststr[i]\n if i != len(liststr) - 1:\n newstr += ' '\n return newstr", "def reversewords(s):\n return ' '.join(s.split()[::-1])", "def reversewords(s):\n b = s.split()\n b.reverse()\n return ' '.join(b)", "def reversewords(s):\n words = s.split()\n reversed = ''\n index = len(words)\n while index > 0:\n index -= 1\n reversed = reversed + ' ' + words[index]\n return reversed[1:]", "def reversewords(s):\n words = s.split()\n i = ''\n index = len(words)\n while index > 0:\n index -= 1\n i = i + ' ' + words[index]\n return i[1:]", "def reversewords(s):\n a = s.split()\n return ' '.join(reversed(a))", "def reversewords(s):\n t = s.split()\n return ' '.join(reversed(t))", "def reversewords(s):\n result = ''\n orded = s.split(' ')\n i = len(orded)\n while i > 0:\n result += orded[i - 1]\n if i > 1:\n result += ' '\n i -= 1\n return result", "def reversewords(s):\n words = s.split(' ')\n reverse_s = ' '.join(reversed(words))\n return reverse_s", "def reversewords(s):\n output = ''\n inp = s.split(' ')\n for i in inp:\n output = ' ' + i + output\n return output[1:len(output)]", "def reversewords(s):\n word = s.split(' ')\n reversewords = ' '.join(reversed(word))\n return reversewords", "def reversewords(s):\n s_list = s.split()\n rev_s_list = s_list[::-1]\n return ' '.join(rev_s_list)", "def reversewords(s):\n s = s.split()\n empty = []\n while len(s) > 0:\n empty.append(s.pop())\n else:\n return ' '.join(empty)", "def reversewords(s):\n reverse = s.split()\n strng = ''\n for i in range(1, len(reverse) + 1):\n strng += reverse[-i] + ' '\n return strng[:-1]", "def reversewords(s):\n s = list(s.split())\n return ' '.join(reversed(s))", "def reversewords(s):\n words = s.split()\n return ' '.join([words[-i - 1] for i in range(len(words))])", "def reversewords(s):\n holder = s.split(' ')\n (i, j) = (0, len(holder) - 1)\n while i < j:\n (holder[i], holder[j]) = (holder[j], holder[i])\n i += 1\n j -= 1\n return ' '.join(holder)", "def reversewords(s):\n x = s.split()\n y = x[::-1]\n return ' '.join(y)", "def reversewords(s):\n array = s.split()\n array.reverse()\n return ' '.join(array)", "def reversewords(s):\n w = s.split(' ')\n output = []\n for word in w:\n output.insert(0, word)\n return ' '.join(output)", "def reversewords(s):\n reverse_s = s.split()\n reverse_s.reverse()\n s = ' '.join(reverse_s)\n return s", "def reversewords(s):\n rev = [i for i in s.split()]\n return ' '.join(rev[::-1])", "def reversewords(s):\n g = s.split(' ')\n g.reverse()\n return ' '.join(g)", "def reversewords(s):\n reversed_str = ''\n s = s.split()\n for word in s:\n reversed_str = word + ' ' + reversed_str\n return reversed_str.strip()", "def reversewords(s):\n return ' '.join((w[::-1] for w in s.split()))[::-1]", "def reversewords(s):\n spl = s.split(' ')\n x = spl[::-1]\n new = ''\n for i in x:\n new += i + ' '\n return new.strip()", "def reversewords(s):\n ls = s.split()\n lsn = ls[::-1]\n return ' '.join(lsn)", "def reversewords(s):\n l = s.split(' ')\n v = []\n for i in l:\n v.insert(0, i)\n v.insert(0, ' ')\n return ''.join(v)[1:]", "def reversewords(s):\n a = ''.join((i + ' ' for i in s.split()[::-1]))\n return a[:-1]", "def reversewords(s):\n s = s.split(' ')\n string = []\n for w in s:\n string.insert(0, w)\n string = ' '.join(string)\n return string[:]", "def reversewords(s):\n x = s.split()\n y = x[::-1]\n z = ' '.join((str(a) for a in y))\n return z", "def reversewords(s):\n word = list(s.split(' '))\n word.reverse()\n return ' '.join(word)", "def reversewords(s):\n str_split = s.split(' ')\n string = ''\n for i in str_split:\n string = i + ' ' + string\n return string.rstrip()", "def reversewords(s):\n for line in s.split('\\n'):\n return ' '.join(line.split()[::-1])", "def reversewords(s):\n s = s.split(' ')\n s.reverse()\n x = ' '\n return x.join(s)", "def reversewords(s):\n a = s.split()\n a.reverse()\n b = a[0]\n a.pop(0)\n for x in a:\n b = b + ' ' + x\n return b", "def reversewords(s):\n x = s.split()\n y = x[::-1]\n strin = ''\n for i in y:\n strin += i + ' '\n return strin.rstrip()", "def reversewords(s):\n s = s.split(' ')\n r = ''\n for x in range(0, len(s)):\n r += s[len(s) - x - 1]\n if x != len(s) - 1:\n r += ' '\n return r", "def reversewords(s: ''):\n s = s.split()\n result = ''\n for i in s:\n result = i + ' ' + result\n return result.strip(' ')", "def reversewords(s):\n t = s.split()\n z = t[::-1]\n return ' '.join(z)", "def reversewords(s):\n s = s.split(' ')\n s.reverse()\n res = ' '.join(s)\n return res", "def reversewords(s):\n y = s.split(' ')\n x = ' '.join(reversed(y))\n return x", "def reversewords(s):\n l = []\n l = s.split(' ')\n l.reverse()\n f = ''\n for i in l:\n f += i + ' '\n return f[:len(f) - 1]", "def reversewords(s):\n list_of_s = s.split(' ')\n list_of_s.reverse()\n return ' '.join(list_of_s)", "reversewords = lambda word: ' '.join(word.split(' ')[::-1])", "def reversewords(s):\n string = ''\n s = s.split()\n for word in reversed(range(len(s))):\n string += s[word]\n string += ' '\n string = string[:-1]\n return string", "def reversewords(r):\n s = r.split()\n r = ''\n for i in range(1, len(s) + 1):\n r += s[-i] + ' '\n return r[:-1]", "def reversewords(s):\n a = s.split()\n b = a[::-1]\n return ' '.join(b)", "def reversewords(s):\n x = [x for x in s.split(' ')]\n return ''.join((x + ' ' for x in x[::-1]))[:-1]", "def reversewords(s):\n return ' '.join(reversed([w for w in s.split()]))", "def reversewords(str):\n words = str.split()\n words = list(reversed(words))\n reverse_str = ' '.join(words)\n return reverse_str", "def reversewords(str):\n strings = str.split(' ')\n strings.reverse()\n return ' '.join(strings)", "def reversewords(str):\n arr = str.split(' ')\n arr.reverse()\n return ' '.join(arr).rstrip()", "def reversewords(str):\n arr = list(str.split())\n arr.reverse()\n return ' '.join([i for i in arr])", "def reversewords(str):\n a = str.split()\n b = ' '.join(reversed(a))\n return b", "def reversewords(str):\n final_str = ''\n str_lst = str.split(' ')[::-1]\n for word in str_lst:\n final_str += word\n final_str += ' '\n return final_str.strip()", "def reversewords(str):\n s = str.split(' ')\n ans = ''\n for i in range(len(s) - 1, -1, -1):\n if i != len(s) - 1:\n ans += ' '\n ans += s[i]\n return ans", "def reversewords(str):\n word = str.split(' ')\n reverse = ' '.join(reversed(word))\n return reverse", "def reversewords(words):\n new_words = list(reversed(words.split()))\n return ' '.join(new_words)", "def reversewords(str):\n rev_list = list(str.split(' '))\n rev_str = ''\n for i in range(len(rev_list) - 1, -1, -1):\n rev_str += rev_list[i]\n if i != 0:\n rev_str += ' '\n return rev_str"], "starter_code": "def reversewords(s):\n", "input_output": {"fn_name": "reverseWords", "inputs": [["hello world!"]], "outputs": [["world! hello"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms"], "name": null, "source": "codewars", "tags": ["String algorithms"], "skill_types": [], "url": "https://www.codewars.com/kata/51c8991dee245d7ddf00000e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "reversewords", "task_id": "TACO_lite/300", "example": [[["The greatest victory is that which requires no battle"]], ["battle no requires which that is victory greatest The"]]} +{"requirement": "Given an array arr[] of N Numbers. A Perfect Piece is defined as a subarray such that the difference between the minimum and the maximum value in that range is at most 1. Find the Maximal Length Perfect Piece.\n \nExample 1:\nInput:\nN = 4\narr[] = {8, 8, 8, 8}\nOutput:\n4\nExplanation:\nThe longest subarray is [1, 4]\nwhere maximum=8 and minimum = 8 and\ndifference is 0, which is less than 1.\nIts length is 4.\nExample 2:\nInput:\nN = 11\narr[] = {5, 4, 5, 5, 6, 7, 8, 8, 8, 7, 6}\nOutput:\n5\nExplanation:\nThe longest subarray is [6, 10]\nwhere maximum=8 and minimum = 7 and\ndifference is 1. Its length is 5. \n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function longestPerfectPiece() which takes an Integer N and an array arr[] of length N as input and returns the maximal length Perfect Piece.\n \nExpected Time Complexity: O(N*logN)\nExpected Auxiliary Space: O(N)\n \nConstraints:\n1 <= N <= 10^{5}\n1 <= arr[i] <= 10^{5}", "solutions": ["def longestperfectpiece(arr, N):\n a = b = 0\n ans = 1\n for j in range(1, len(arr)):\n if abs(arr[j] - arr[b]) == 1:\n if a == b or arr[j] != arr[b - 1]:\n a = b\n b = j\n elif arr[j] != arr[b]:\n a = b = j\n ans = max(ans, j - a + 1)\n return ans", "import sys\n\ndef longestperfectpiece(arr, N):\n (flg, count, f1, f2) = (0, 0, 0, 0)\n len = -sys.maxsize - 1\n for i in range(N):\n for j in range(f1, N):\n if arr[i] - arr[j] == 1 or arr[i] == arr[j]:\n if len < abs(i - j):\n len = abs(i - j)\n else:\n f1 = j\n break\n for j in range(f2, N):\n if arr[i] - arr[j] == -1 or arr[i] == arr[j]:\n if len < abs(i - j):\n len = abs(i - j)\n else:\n f2 = j\n break\n return len + 1", "import collections\n\ndef longestperfectpiece(arr, N):\n map = collections.defaultdict(int)\n start = 0\n maxLength = 0\n for (end, num) in enumerate(arr):\n map[num] += 1\n while len(map) > 2 or max(map.keys()) - min(map.keys()) > 1:\n map[arr[start]] -= 1\n if map[arr[start]] == 0:\n del map[arr[start]]\n start += 1\n maxLength = max(maxLength, end - start + 1)\n return maxLength", "def longestperfectpiece(arr, N):\n (i, j, ans) = (0, 0, 1)\n for k in range(1, N):\n if abs(arr[k] - arr[j]) == 1:\n if i == j or arr[k] != arr[j - 1]:\n i = j\n j = k\n elif arr[k] != arr[j]:\n i = j = k\n ans = max(ans, k - i + 1)\n return ans", "def longestperfectpiece(arr, N):\n j = 0\n mn = arr[0]\n mx = arr[0]\n ans = 1\n d = dict()\n for i in range(1, N):\n d[arr[i]] = i\n if arr[i] < mn:\n mn = arr[i]\n while mx - mn > 1:\n j = d.get(mx, 0) + 1\n mx = arr[j]\n elif arr[i] > mx:\n mx = arr[i]\n while mx - mn > 1:\n j = d.get(mn, 0) + 1\n mn = arr[j]\n else:\n ans = max(ans, i - j + 1)\n return ans", "import sys\nfrom collections import deque\n\ndef longestperfectpiece(arr, N):\n window = deque([])\n i = 0\n count = 0\n ans = 0\n maxis = deque([])\n ta = deque([])\n ti = deque([])\n minis = deque([])\n l = r = 0\n while i < N:\n if len(window) == 0 or arr[i] == arr[maxis[0]] or arr[i] == arr[minis[0]] or (arr[maxis[0]] == arr[minis[0]] and (arr[i] == arr[maxis[0]] - 1 or arr[i] == arr[maxis[0]] + 1)):\n window.append(arr[i])\n count += 1\n ans = max(ans, count)\n while len(maxis) != 0 and arr[i] > arr[maxis[-1]]:\n maxis.pop()\n ta.pop()\n maxis.append(i)\n ta.append(arr[i])\n while len(minis) != 0 and arr[i] < arr[minis[-1]]:\n minis.pop()\n ti.pop()\n minis.append(i)\n ti.append(arr[i])\n r += 1\n i += 1\n else:\n window.popleft()\n l += 1\n count -= 1\n if len(maxis) != 0 and l > maxis[0]:\n maxis.popleft()\n ta.popleft()\n if len(minis) != 0 and l > minis[0]:\n minis.popleft()\n ti.popleft()\n return ans", "from sortedcontainers import SortedList\nimport collections\n\ndef longestperfectpiece(arr, N):\n ans = 0\n s = 0\n map = collections.defaultdict(int)\n for (end, num) in enumerate(arr):\n map[num] += 1\n while len(map) > 2 or max(map.keys()) - min(map.keys()) > 1:\n map[arr[s]] -= 1\n if map[arr[s]] == 0:\n del map[arr[s]]\n s += 1\n ans = max(ans, end - s + 1)\n return ans", "def longestperfectpiece(arr, N):\n (l, r) = (0, 0)\n ans = 1\n (pos1, pos2) = (-1, -1)\n val = None\n for i in range(N):\n if pos1 == -1:\n pos1 = i\n val = arr[i]\n elif pos2 == -1:\n if arr[i] == val + 1:\n pos2 = i\n elif arr[i] == val:\n pos = i\n elif arr[i] == val - 1:\n val = val - 1\n pos2 = pos1\n pos1 = i\n else:\n val = arr[i]\n pos1 = i\n pos2 = -1\n l = i\n elif arr[i] == val:\n pos1 = i\n elif arr[i] == val + 1:\n pos2 = i\n elif arr[i] == val - 1:\n val = val - 1\n l = pos2 + 1\n pos2 = pos1\n pos1 = i\n elif arr[i] == val + 2:\n val = val + 1\n l = pos1 + 1\n pos1 = pos2\n pos2 = i\n else:\n l = i\n pos2 = -1\n pos1 = i\n val = arr[i]\n ans = max(ans, i - l + 1)\n return ans", "def longestperfectpiece(arr, N):\n c = 1\n i = 0\n t = 0\n while i < N - 1:\n if abs(arr[i] - arr[i + 1]) <= 1:\n i += 1\n t += 1\n else:\n if c < t:\n c += t\n t = 0\n i += 1\n if N == 7:\n return 6\n if N == 5:\n return 4\n if N == 2667 or N == 3666:\n return c + 1\n if t > c:\n return t + 1\n return c", "def longestperfectpiece(arr, n):\n i = 0\n ans = 0\n while i < n:\n a = arr[i]\n b = -1\n j = i + 1\n while j < n:\n if b == -1 and abs(arr[i] - arr[j]) == 1:\n b = arr[j]\n j += 1\n elif arr[j] == a or arr[j] == b:\n j += 1\n else:\n break\n ans = max(ans, j - i)\n if j >= n:\n break\n i = j\n if abs(arr[i] - arr[i - 1]) == 1:\n b = arr[i - 1]\n i -= 1\n while i >= 0 and arr[i] == b:\n i -= 1\n i += 1\n return ans", "def longestperfectpiece(arr, N):\n maxLen = 0\n tailIndex = 0\n piecemax = arr[0]\n piecemin = arr[0]\n for (i, val) in enumerate(arr):\n if val > piecemax:\n piecemax = val\n while piecemin < piecemax - 1:\n tailIndex += 1\n piecemin = max(piecemin, arr[tailIndex])\n if val < piecemin:\n piecemin = val\n while piecemin < piecemax - 1:\n tailIndex += 1\n piecemax = min(piecemax, arr[tailIndex])\n currentLen = i - tailIndex + 1\n maxLen = max(maxLen, currentLen)\n return maxLen", "def longestperfectpiece(arr, N):\n (a, b, c) = (1, 1, 1)\n ans = 1\n for i in range(1, N):\n if arr[i] == arr[i - 1]:\n (a, b, c) = (a + 1, b + 1, c + 1)\n elif arr[i] - arr[i - 1] == 1:\n (a, b, c) = (1, c + 1, 1)\n elif arr[i] - arr[i - 1] == -1:\n (a, b, c) = (1, 1, b + 1)\n else:\n (a, b, c) = (1, 1, 1)\n ans = max(ans, a, b, c)\n return ans", "def longestperfectpiece(arr, N):\n if not N:\n return 0\n (start, ans) = (1, 1)\n count = 1\n (s, l) = (arr[0], arr[0])\n (sf, lf, df) = (0, 0, 1)\n for i in range(0, N):\n if not df:\n (s, l) = (arr[i], arr[i])\n for j in range(start, N):\n if 0 <= abs(arr[j] - s) <= 1 and 0 <= abs(arr[j] - l) <= 1:\n count += 1\n if arr[j] > l:\n lf += 1\n l = arr[j]\n elif arr[j] == l and arr[j] != arr[i]:\n lf += 1\n if arr[j] < s:\n sf += 1\n s = arr[j]\n elif arr[j] == s and arr[j] != arr[i]:\n sf += 1\n if arr[j] == arr[i]:\n df += 1\n else:\n if sf:\n if df > 1:\n l = arr[i]\n else:\n l = s\n if arr[i] != arr[i + 1]:\n lf = df - 1\n df = sf\n sf = 0\n else:\n df -= 1\n elif lf:\n if df > 1:\n s = arr[i]\n else:\n s = l\n if arr[i] != arr[i + 1]:\n sf = df - 1\n df = lf\n lf = 0\n else:\n df -= 1\n else:\n df -= 1\n ans = max(ans, count)\n count -= 1\n start = j\n break\n if j == N - 1:\n start = N\n ans = max(ans, count)\n return ans", "from heapq import heappush, heappop\nfrom collections import defaultdict\n\ndef longestperfectpiece(arr, n):\n dic = defaultdict(int)\n ans = 0\n start = 0\n for i in range(n):\n dic[arr[i]] += 1\n while len(dic) > 1 and max(dic.keys()) - min(dic.keys()) > 1:\n dic[arr[start]] -= 1\n if dic[arr[start]] == 0:\n dic.pop(arr[start])\n start += 1\n ans = max(ans, i - start + 1)\n return ans\n mini = []\n maxi = []\n j = 0\n ans = 0\n for i in range(n):\n heappush(mini, arr[i])\n heappush(maxi, -arr[i])\n if abs(mini[0] + maxi[0]) <= 1:\n ans = max(ans, i - j + 1)\n else:\n while j < n and mini and (abs(mini[0] + maxi[0]) > 1):\n mini.remove(arr[j])\n maxi.remove(-arr[j])\n j += 1\n return ans", "def longestperfectpiece(arr, N):\n if N < 2:\n return N\n res = 1\n n1 = arr[0]\n n2 = arr[0]\n i = 1\n count = 1\n while i < N:\n if n1 == n2:\n if abs(n1 - arr[i]) < 2:\n n2 = arr[i]\n count += 1\n else:\n n1 = n2 = arr[i]\n res = max(res, count)\n count = 1\n elif arr[i] == n1 or arr[i] == n2:\n count += 1\n else:\n res = max(res, count)\n n1 = n2 = arr[i]\n count = 1\n j = i - 1\n if abs(n1 - arr[j]) == 1:\n n2 = arr[j]\n while j >= 0 and arr[j] == n2:\n j -= 1\n count += 1\n i += 1\n return max(count, res)", "import collections\n\ndef __init__():\n self.ans = 1\n self.dic = collections.defaultdict(int)\n\ndef longestperfectpiece(arr, N):\n start = 0\n end = 0\n while end < N:\n self.dic[arr[end]] += 1\n end += 1\n while max(self.dic.keys()) - min(self.dic.keys()) > 1:\n self.dic[arr[start]] -= 1\n if self.dic[arr[start]] == 0:\n del self.dic[arr[start]]\n start += 1\n if self.ans < sum(self.dic.values()):\n self.ans = sum(self.dic.values())\n return self.ans", "def longestperfectpiece(arr, N):\n i = 0\n j = 0\n h = {}\n res = 1\n while i <= j and j < N:\n while i < j and (abs(arr[j] - arr[i]) > 1 or (len(h) == 2 and arr[j] not in h)):\n h[arr[i]] -= 1\n if h[arr[i]] == 0:\n del h[arr[i]]\n i += 1\n h[arr[j]] = 1 + h.get(arr[j], 0)\n res = max(res, j - i + 1)\n j += 1\n return res", "import heapq\n\ndef longestperfectpiece(arr, N):\n d = dict()\n i = 0\n j = 0\n ans = 0\n while j < N:\n if arr[j] in d:\n d[arr[j]] += 1\n else:\n d[arr[j]] = 1\n while len(d) >= 2 and max(d.keys()) - min(d.keys()) > 1:\n d[arr[i]] -= 1\n if d[arr[i]] == 0:\n del d[arr[i]]\n i += 1\n ans = max(ans, j - i + 1)\n j += 1\n return ans", "from collections import Counter\n\ndef longestperfectpiece(arr, N):\n cnt = Counter()\n l = 0\n ans = 1\n for (r, e) in enumerate(arr):\n cnt[e] += 1\n while l < r and max(cnt.keys()) - min(cnt.keys()) > 1:\n cnt[arr[l]] -= 1\n if cnt[arr[l]] == 0:\n cnt.pop(arr[l])\n l += 1\n ans = max(ans, r - l + 1)\n return ans", "def longestperfectpiece(arr, N):\n longest = [0]\n pmin = arr[0]\n pmax = arr[0]\n if N == 1:\n return 1\n i = 0\n while i < N - 1:\n sidx = i\n eidx = i\n while i < N - 1 and pmax - pmin < 2:\n pmin = min(pmin, arr[i + 1])\n pmax = max(pmax, arr[i + 1])\n i += 1\n if pmax - pmin < 2:\n eidx += 1\n longest[0] = max(longest[0], eidx - sidx + 1)\n if i < N:\n if pmax - pmin == 2:\n for j in range(sidx, eidx):\n if arr[j] == pmin:\n i = j + 1\n break\n pmax = arr[i]\n pmin = arr[i]\n return longest[0]", "from collections import deque\n\ndef longestperfectpiece(arr, N):\n maxm = deque()\n minm = deque()\n res = 0\n i = j = 0\n while i < N and j < N:\n while j < N:\n cur = arr[j]\n while maxm and maxm[-1][1] < cur:\n maxm.pop()\n maxm.append((j, cur))\n while minm and minm[-1][1] > cur:\n minm.pop()\n minm.append((j, cur))\n if abs(maxm[0][1] - minm[0][1]) > 1:\n break\n j += 1\n res = max(res, j - i)\n while i < N:\n while maxm and maxm[0][0] < i:\n maxm.popleft()\n while minm and minm[0][0] < i:\n minm.popleft()\n if abs(maxm[0][1] - minm[0][1]) <= 1:\n break\n i += 1\n return res", "import collections\n\ndef longestperfectpiece(arr, n):\n map = collections.defaultdict(int)\n j = 0\n ans = 0\n for i in range(n):\n map[arr[i]] += 1\n while len(map) > 2 or max(map.keys()) - min(map.keys()) > 1:\n map[arr[j]] -= 1\n if map[arr[j]] == 0:\n del map[arr[j]]\n j += 1\n ans = max(ans, i - j + 1)\n return ans", "from collections import defaultdict as maps\n\ndef longestperfectpiece(arr, n):\n d = maps(int)\n start = 0\n maxlen = 0\n for (index, num) in enumerate(arr):\n d[num] += 1\n while len(d) > 2 or max(d.keys()) - min(d.keys()) > 1:\n d[arr[start]] -= 1\n if d[arr[start]] == 0:\n del d[arr[start]]\n start += 1\n maxlen = max(maxlen, index - start + 1)\n return maxlen", "def longestperfectpiece(arr, N):\n if arr == [5, 4, 5, 5, 6]:\n return 4\n res = 0\n i = 0\n j = 0\n while j < N:\n while abs(arr[j] - arr[i]) > 1:\n i += 1\n res = max(res, j - i + 1)\n j += 1\n return res", "from collections import Counter\nimport bisect\n\ndef longestperfectpiece(arr, N):\n t = 0\n j = 0\n for (x, i) in enumerate(arr):\n while j < N and (arr[j] == i or arr[j] == i + 1):\n j += 1\n t = max(t, j - x)\n j = 0\n for (x, i) in enumerate(arr):\n while j < N and (arr[j] == i or arr[j] == i - 1):\n j += 1\n t = max(t, j - x)\n return t", "def longestperfectpiece(arr, N):\n flg = count = f1 = f2 = 0\n res = -float('inf')\n for i in range(N):\n for j in range(f1, N):\n if arr[i] - arr[j] == 1 or arr[i] == arr[j]:\n res = max(res, j - i)\n else:\n f1 = j\n break\n for j in range(f2, N):\n if arr[i] - arr[j] == -1 or arr[i] == arr[j]:\n res = max(res, j - i)\n else:\n f2 = j\n break\n return res + 1", "from collections import deque\n\ndef longestperfectpiece(arr, N):\n n = N\n a = deque()\n b = deque()\n l = r = ans = 0\n while l < n and r < n:\n while r < n:\n c = arr[r]\n while a and a[-1][1] < c:\n a.pop()\n a.append((r, c))\n while b and b[-1][1] > c:\n b.pop()\n b.append((r, c))\n if abs(a[0][1] - b[0][1]) > 1:\n break\n r += 1\n ans = max(ans, r - l)\n while l < n:\n while a and a[0][0] < l:\n a.popleft()\n while b and b[0][0] < l:\n b.popleft()\n if abs(a[0][1] - b[0][1]) <= 1:\n break\n l += 1\n return ans"], "starter_code": "def longestperfectpiece(arr, N):\n", "input_output": {"inputs": ["N = 4\r\narr[] = {8, 8, 8, 8}", "N = 11\r\narr[] = {5, 4, 5, 5, 6, 7, 8, 8, 8, 7, 6}"], "outputs": ["4", "5"]}, "difficulty": "EASY", "raw_tags": ["Pointers", "Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/close-to-perfection1525/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*logN)", "entry_point": "longestperfectpiece", "task_id": "TACO_lite/302", "example": [[[4, [8, 8, 8, 8]], [11, [5, 4, 5, 5, 6, 7, 8, 8, 8, 7, 6]]], [null, null]]} +{"requirement": "Make a function that receives a value, ```val``` and outputs the smallest higher number than the given value, and this number belong to a set of positive integers that have the following properties:\n\n- their digits occur only once\n\n- they are odd\n\n- they are multiple of three\n\n```python\nnext_numb(12) == 15\n\nnext_numb(13) == 15\n\nnext_numb(99) == 105\n\nnext_numb(999999) == 1023459\n\nnext_number(9999999999) == \"There is no possible number that\nfulfills those requirements\"\n```\n\nEnjoy the kata!!", "solutions": ["def unique_digits(n):\n return len(set(str(n))) == len(str(n))\n\ndef next_numb(val):\n val += 1\n while val % 3:\n val += 1\n if val % 2 == 0:\n val += 3\n while not unique_digits(val):\n val += 6\n if val > 9876543210:\n break\n else:\n return val\n return 'There is no possible number that fulfills those requirements'", "def next_numb(val):\n val += 3 - val % 3\n if not val & 1:\n val += 3\n while val < 9999999999:\n s = str(val)\n if len(s) == len(set(s)):\n return val\n val += 6\n return 'There is no possible number that fulfills those requirements'", "DEFAULT = 'There is no possible number that fulfills those requirements'\n\ndef valid(s):\n return len(set(s)) == len(s)\n\ndef next_numb(n):\n n += 3 - n % 3\n if not n & 1:\n n += 3\n return next((n for n in range(n, 9999999999, 6) if valid(str(n))), DEFAULT)", "def next_numb(val):\n i = val + 1\n while i <= 9999999999:\n if i % 3 == 0 and i % 2 and (len(str(i)) == len(set(str(i)))):\n return i\n i += 1\n return 'There is no possible number that fulfills those requirements'", "from itertools import count\n\ndef next_numb(val):\n if val >= 9999999999:\n return 'There is no possible number that fulfills those requirements'\n for i in count(val + 1):\n s = str(i)\n if i % 2 == 1 and i % 3 == 0 and (len(s) == len(set(s))):\n return i", "from collections import Counter\n\ndef next_numb(val):\n if val >= 9876543210:\n return 'There is no possible number that fulfills those requirements'\n x = val + 1\n if x % 3 != 0:\n x += 3 - x % 3\n if x % 2 == 0:\n x += 3\n c = Counter(str(x))\n while max(c.values()) > 1:\n x += 6\n c = Counter(str(x))\n return x", "def next_numb(n):\n if n > 9876543201:\n return 'There is no possible number that fulfills those requirements'\n x = n - n % 3 + 3\n while True:\n if x > 9876543201:\n return 'There is no possible number that fulfills those requirements'\n if x & 1:\n a = [d for d in str(x)]\n s = list(set(a))\n if len(a) == len(s):\n return x\n x += 3"], "starter_code": "def next_numb(val):\n", "input_output": {"fn_name": "next_numb", "inputs": [[12], [13], [99], [999999], [9999999999]], "outputs": [[15], [15], [105], [1023459], ["There is no possible number that fulfills those requirements"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56abc5e63c91630882000057", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "next_numb", "task_id": "TACO_lite/289", "example": [[], []]} +{"requirement": "This time no story, no theory. The examples below show you how to write function `accum`:\n\n**Examples:**\n```\naccum(\"abcd\") -> \"A-Bb-Ccc-Dddd\"\naccum(\"RqaEzty\") -> \"R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy\"\naccum(\"cwAt\") -> \"C-Ww-Aaa-Tttt\"\n```\n\nThe parameter of accum is a string which includes only letters from `a..z` and `A..Z`.", "solutions": ["def accum(s):\n return '-'.join((c.upper() + c.lower() * i for (i, c) in enumerate(s)))", "def accum(s):\n return '-'.join(((a * i).title() for (i, a) in enumerate(s, 1)))", "def accum(s):\n output = ''\n for i in range(len(s)):\n output += s[i] * (i + 1) + '-'\n return output.title()[:-1]", "def accum(s):\n i = 0\n result = ''\n for letter in s:\n result += letter.upper() + letter.lower() * i + '-'\n i += 1\n return result[:len(result) - 1]", "def accum(s):\n return '-'.join([(j * (i + 1)).capitalize() for (i, j) in enumerate(s)])", "def accum(s):\n value = ''\n for (i, c) in enumerate(s):\n value += c.upper() + c.lower() * i + '-'\n return value[:-1]", "def accum(s):\n str = ''\n for i in range(0, len(s)):\n str += s[i].upper()\n str += s[i].lower() * i\n if i != len(s) - 1:\n str += '-'\n return str", "def accum(s):\n a = list(s)\n res = ''\n for (i, c) in enumerate(a):\n res += c * (i + 1) + '-'\n return res.strip('-').title()", "def accum(s):\n return '-'.join(list((x.upper() + x.lower() * count for (count, x) in enumerate(s))))"], "starter_code": "def accum(s):\n", "input_output": {"fn_name": "accum", "inputs": [["ZpglnRxqenU"], ["NyffsGeyylB"], ["MjtkuBovqrU"], ["EvidjUnokmM"], ["HbideVbxncC"], ["VwhvtHtrxfE"], ["KurgiKmkphY"], ["NctlfBlnmfH"], ["WegunHvbdmV"], ["VoywwSpqidE"], ["VbaixFpxdcO"], ["OlyqvYwkuzF"], ["JrhfdMtchiH"], ["JiwpcSwslvW"], ["EagpiEvmabJ"], ["RznlcEmuxxP"], ["OrggaExarzP"], ["DriraMtedfB"], ["BjxseRxgtjT"], ["EquhxOswchE"]], "outputs": [["Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu"], ["N-Yy-Fff-Ffff-Sssss-Gggggg-Eeeeeee-Yyyyyyyy-Yyyyyyyyy-Llllllllll-Bbbbbbbbbbb"], ["M-Jj-Ttt-Kkkk-Uuuuu-Bbbbbb-Ooooooo-Vvvvvvvv-Qqqqqqqqq-Rrrrrrrrrr-Uuuuuuuuuuu"], ["E-Vv-Iii-Dddd-Jjjjj-Uuuuuu-Nnnnnnn-Oooooooo-Kkkkkkkkk-Mmmmmmmmmm-Mmmmmmmmmmm"], ["H-Bb-Iii-Dddd-Eeeee-Vvvvvv-Bbbbbbb-Xxxxxxxx-Nnnnnnnnn-Cccccccccc-Ccccccccccc"], ["V-Ww-Hhh-Vvvv-Ttttt-Hhhhhh-Ttttttt-Rrrrrrrr-Xxxxxxxxx-Ffffffffff-Eeeeeeeeeee"], ["K-Uu-Rrr-Gggg-Iiiii-Kkkkkk-Mmmmmmm-Kkkkkkkk-Ppppppppp-Hhhhhhhhhh-Yyyyyyyyyyy"], ["N-Cc-Ttt-Llll-Fffff-Bbbbbb-Lllllll-Nnnnnnnn-Mmmmmmmmm-Ffffffffff-Hhhhhhhhhhh"], ["W-Ee-Ggg-Uuuu-Nnnnn-Hhhhhh-Vvvvvvv-Bbbbbbbb-Ddddddddd-Mmmmmmmmmm-Vvvvvvvvvvv"], ["V-Oo-Yyy-Wwww-Wwwww-Ssssss-Ppppppp-Qqqqqqqq-Iiiiiiiii-Dddddddddd-Eeeeeeeeeee"], ["V-Bb-Aaa-Iiii-Xxxxx-Ffffff-Ppppppp-Xxxxxxxx-Ddddddddd-Cccccccccc-Ooooooooooo"], ["O-Ll-Yyy-Qqqq-Vvvvv-Yyyyyy-Wwwwwww-Kkkkkkkk-Uuuuuuuuu-Zzzzzzzzzz-Fffffffffff"], ["J-Rr-Hhh-Ffff-Ddddd-Mmmmmm-Ttttttt-Cccccccc-Hhhhhhhhh-Iiiiiiiiii-Hhhhhhhhhhh"], ["J-Ii-Www-Pppp-Ccccc-Ssssss-Wwwwwww-Ssssssss-Lllllllll-Vvvvvvvvvv-Wwwwwwwwwww"], ["E-Aa-Ggg-Pppp-Iiiii-Eeeeee-Vvvvvvv-Mmmmmmmm-Aaaaaaaaa-Bbbbbbbbbb-Jjjjjjjjjjj"], ["R-Zz-Nnn-Llll-Ccccc-Eeeeee-Mmmmmmm-Uuuuuuuu-Xxxxxxxxx-Xxxxxxxxxx-Ppppppppppp"], ["O-Rr-Ggg-Gggg-Aaaaa-Eeeeee-Xxxxxxx-Aaaaaaaa-Rrrrrrrrr-Zzzzzzzzzz-Ppppppppppp"], ["D-Rr-Iii-Rrrr-Aaaaa-Mmmmmm-Ttttttt-Eeeeeeee-Ddddddddd-Ffffffffff-Bbbbbbbbbbb"], ["B-Jj-Xxx-Ssss-Eeeee-Rrrrrr-Xxxxxxx-Gggggggg-Ttttttttt-Jjjjjjjjjj-Ttttttttttt"], ["E-Qq-Uuu-Hhhh-Xxxxx-Oooooo-Sssssss-Wwwwwwww-Ccccccccc-Hhhhhhhhhh-Eeeeeeeeeee"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Puzzles"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/5667e8f4e3f572a8f2000039", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "accum", "task_id": "TACO_lite/304", "example": [[["abcd"], ["RqaEzty"], ["cwAt"]], ["A-Bb-Ccc-Dddd", "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy", "C-Ww-Aaa-Tttt"]]} +{"requirement": "The i-th person has weight people[i], and each boat can carry a maximum weight of limit.\nEach boat carries at most 2 people at the same time, provided the sum of the\u00a0weight of those people is at most limit.\nReturn the minimum number of boats to carry every given person.\u00a0 (It is guaranteed each person can be carried by a boat.)\n\u00a0\n\nExample 1:\nInput: people = [1,2], limit = 3\nOutput: 1\nExplanation: 1 boat (1, 2)\n\n\nExample 2:\nInput: people = [3,2,2,1], limit = 3\nOutput: 3\nExplanation: 3 boats (1, 2), (2) and (3)\n\n\nExample 3:\nInput: people = [3,5,3,4], limit = 5\nOutput: 4\nExplanation: 4 boats (3), (3), (4), (5)\nNote:\n\n1 <=\u00a0people.length <= 50000\n1 <= people[i] <=\u00a0limit <= 30000", "solutions": ["def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n lo = 0\n hi = len(people) - 1\n count = 0\n while lo <= hi:\n count += 1\n if people[lo] + people[hi] <= limit:\n lo += 1\n hi -= 1\n return count", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n boats = 0\n l = 0\n r = len(people) - 1\n while r > l:\n boats += 1\n if people[l] + people[r] <= limit:\n l += 1\n r = r - 1\n else:\n r = r - 1\n if r == l:\n boats += 1\n return boats", "def numrescueboats(people: List[int], limit: int) -> int:\n people = sorted(people, reverse=True)\n i = 0\n j = len(people) - 1\n n = 0\n while True:\n if i >= j:\n break\n n += 1\n w1 = people[i]\n i += 1\n rem = limit - w1\n if rem >= people[j]:\n j -= 1\n if i == j:\n n += 1\n return n", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n p1 = 0\n p2 = len(people) - 1\n boat = 0\n while p1 <= p2:\n boat += 1\n if people[p1] + people[p2] <= limit:\n p1 += 1\n p2 -= 1\n return boat", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n i = 0\n j = len(people) - 1\n count = 0\n while i < j:\n if people[i] + people[j] <= limit:\n count += 1\n i += 1\n j -= 1\n else:\n count += 1\n j -= 1\n if i == j:\n count += 1\n return count", "def numrescueboats(people: List[int], limit: int) -> int:\n new = sorted(people)\n (i, j) = (0, len(people) - 1)\n res = 0\n while i <= j:\n if new[j] + new[i] <= limit:\n i += 1\n j -= 1\n res += 1\n return res", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n (l, r) = (0, len(people) - 1)\n res = 0\n while l <= r:\n while l <= r and people[l] + people[r] > limit:\n res += 1\n r -= 1\n if l <= r:\n res += 1\n l += 1\n r -= 1\n return res", "def numrescueboats(people: List[int], limit: int) -> int:\n length = len(people)\n people.sort()\n left = 0\n right = length - 1\n boat_num = 0\n while left <= right:\n if people[left] + people[right] <= limit:\n left += 1\n right -= 1\n else:\n right -= 1\n boat_num += 1\n return boat_num", "def numrescueboats(people: List[int], limit: int) -> int:\n if not people:\n return 0\n people = sorted(people)\n left = 0\n right = len(people) - 1\n board_cnt = 0\n while left <= right:\n if left == right:\n board_cnt += 1\n break\n if people[left] + people[right] <= limit:\n left += 1\n right -= 1\n board_cnt += 1\n else:\n right -= 1\n board_cnt += 1\n return board_cnt", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n (left, right) = (0, len(people) - 1)\n boats = 0\n while left <= right:\n if left == right:\n boats += 1\n break\n if people[left] + people[right] <= limit:\n boats += 1\n left += 1\n right -= 1\n else:\n right -= 1\n boats += 1\n return boats", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n start = 0\n end = len(people) - 1\n ans = 0\n while start <= end:\n ans += 1\n if people[start] + people[end] <= limit:\n start += 1\n end -= 1\n return ans", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort(reverse=True)\n (l, r) = (0, len(people) - 1)\n while l <= r:\n if people[l] + people[r] <= limit:\n r -= 1\n l += 1\n return l", "def numrescueboats(people: List[int], limit: int) -> int:\n people = sorted(people)\n count = 0\n left = 0\n right = len(people) - 1\n while left <= right:\n cur = people[left] + people[right]\n if cur <= limit:\n left += 1\n right -= 1\n elif cur > limit:\n right -= 1\n count += 1\n return count", "def numrescueboats(people: List[int], limit: int) -> int:\n s = []\n c = 0\n people.sort(reverse=True)\n for i in range(len(people)):\n if s and people[i] < s[-1]:\n s[-1] = s[-1] - people[i]\n s.pop()\n elif s and people[i] == s[-1]:\n s.pop()\n elif s and people[i] > s[-1]:\n s.append(limit - people[i])\n c += 1\n elif people[i] == limit:\n c += 1\n else:\n c += 1\n s.append(limit - people[i])\n return c", "def numrescueboats(people: List[int], limit: int) -> int:\n less_than_half = dict()\n more_than_half = dict()\n half = 0\n total_boats = 0\n for person in people:\n diff = limit - person\n if diff == 0:\n total_boats += 1\n continue\n if person < limit / 2:\n if diff in more_than_half:\n total_boats += 1\n if more_than_half[diff] == 1:\n del more_than_half[diff]\n else:\n more_than_half[diff] -= 1\n elif person in less_than_half:\n less_than_half[person] += 1\n else:\n less_than_half[person] = 1\n elif person > limit / 2:\n if diff in less_than_half:\n total_boats += 1\n if less_than_half[diff] == 1:\n del less_than_half[diff]\n else:\n less_than_half[diff] -= 1\n elif person in more_than_half:\n more_than_half[person] += 1\n else:\n more_than_half[person] = 1\n elif half == 1:\n total_boats += 1\n half = 0\n else:\n half = 1\n less_keys = sorted(less_than_half.keys())\n more_keys = sorted(list(more_than_half.keys()), reverse=True)\n while len(less_keys) and len(more_keys):\n if less_keys[0] + more_keys[0] <= limit:\n if less_than_half[less_keys[0]] < more_than_half[more_keys[0]]:\n total_boats += less_than_half[less_keys[0]]\n more_than_half[more_keys[0]] -= less_than_half[less_keys[0]]\n less_keys.pop(0)\n elif less_than_half[less_keys[0]] > more_than_half[more_keys[0]]:\n total_boats += more_than_half[more_keys[0]]\n less_than_half[less_keys[0]] -= more_than_half[more_keys[0]]\n more_keys.pop(0)\n else:\n total_boats += less_than_half[less_keys[0]]\n less_keys.pop(0)\n more_keys.pop(0)\n else:\n total_boats += more_than_half[more_keys[0]]\n more_keys.pop(0)\n less_total = 0\n for k in less_keys:\n less_total += less_than_half[k]\n more_total = 0\n for k in more_keys:\n more_total += more_than_half[k]\n total_boats += (less_total + half + 1) // 2 + more_total\n return total_boats", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort(reverse=True)\n first_index = 0\n second_index = len(people) - 1\n ans = 0\n while first_index <= second_index:\n if people[first_index] + people[second_index] <= limit:\n second_index -= 1\n first_index += 1\n ans += 1\n return ans", "def numrescueboats(people: List[int], limit: int) -> int:\n people = sorted(people)\n i = 0\n j = len(people) - 1\n total = 0\n while i <= j:\n if i == j:\n total += 1\n i += 1\n j -= 1\n elif people[i] + people[j] <= limit:\n i += 1\n j -= 1\n total += 1\n else:\n j -= 1\n total += 1\n return total", "def numrescueboats(people: List[int], cap: int) -> int:\n people.sort()\n N = len(people)\n (i, j) = (0, N - 1)\n ans = 0\n k = cap\n s = 2\n while i <= j:\n while s and j >= 0:\n if k - people[j] < 0:\n break\n k -= people[j]\n j -= 1\n s -= 1\n while s and i < N:\n if k - people[i] < 0:\n break\n k -= people[i]\n i += 1\n s -= 1\n k = cap\n s = 2\n ans += 1\n return ans", "def numrescueboats(people: List[int], limit: int) -> int:\n sorted_people = list(sorted(people, reverse=True))\n i = 0\n j = len(people) - 1\n while i <= j:\n if sorted_people[i] + sorted_people[j] <= limit:\n j -= 1\n i += 1\n return i", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n count = len(people)\n end = len(people) - 1\n begin = 0\n res = 0\n while count > 0:\n if people[end] + people[begin] <= limit:\n res += 1\n count -= 2\n end -= 1\n begin += 1\n else:\n res += 1\n count -= 1\n end -= 1\n return res", "def numrescueboats(people: List[int], limit: int) -> int:\n groups = self.group_people_by_weight(people, limit)\n return self.count_num_boats(groups, limit)\n\ndef group_people_by_weight(people, limit):\n groups = [0] * (limit + 1)\n for person_weight in people:\n groups[person_weight] += 1\n return groups\n\ndef count_num_boats(groups, limit):\n num_boats = 0\n start = 0\n end = len(groups) - 1\n while start <= end:\n while start <= end and groups[start] <= 0:\n start += 1\n while start <= end and groups[end] <= 0:\n end -= 1\n if start > end:\n break\n if start + end <= limit:\n groups[start] -= 1\n groups[end] -= 1\n num_boats += 1\n return num_boats", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n low = 0\n up = len(people) - 1\n boats = 0\n while low <= up:\n if up - 1 >= low and people[up] + people[up - 1] <= limit:\n up -= 2\n boats += 1\n elif up != low and people[up] + people[low] <= limit:\n up -= 1\n low += 1\n boats += 1\n else:\n up -= 1\n boats += 1\n return boats", "from collections import deque\n\ndef numrescueboats(people, limit):\n n = len(people)\n weights = deque(sorted(people))\n boat = 0\n while n > 1:\n if weights[0] + weights[-1] <= limit:\n weights.popleft()\n weights.pop()\n n -= 2\n else:\n weights.pop()\n n -= 1\n boat += 1\n if n == 1:\n boat += 1\n return boat", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n l = 0\n h = len(people) - 1\n remain_capacity = limit\n if len(people) == 0:\n return 0\n boat = 1\n ppl_in_boat = 2\n while l <= h:\n if people[h] <= remain_capacity and ppl_in_boat != 0:\n remain_capacity -= people[h]\n ppl_in_boat -= 1\n h = h - 1\n elif remain_capacity >= people[l] and ppl_in_boat != 0:\n remain_capacity -= people[l]\n ppl_in_boat -= 1\n l = l + 1\n else:\n boat += 1\n remain_capacity = limit\n ppl_in_boat = 2\n return boat", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n if people[0] >= limit:\n return 0\n res = [0]\n (i, j) = (0, len(people) - 1)\n num_people = 0\n while i <= j:\n if res[-1] + people[j] <= limit and num_people < 2:\n res[-1] += people[j]\n j -= 1\n num_people += 1\n elif res[-1] + people[i] <= limit and num_people < 2:\n res[-1] += people[i]\n i += 1\n num_people += 1\n else:\n res.append(0)\n num_people = 0\n return len(res)", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n num_boats = 0\n last = len(people) - 1\n first = 0\n while first < last:\n if people[first] + people[last] <= limit:\n last -= 1\n first += 1\n num_boats += 1\n else:\n num_boats += 1\n last -= 1\n if first == last:\n num_boats += 1\n return num_boats", "def numrescueboats(people, limit):\n people.sort()\n (i, j) = (0, len(people) - 1)\n ans = 0\n while i <= j:\n ans += 1\n if people[i] + people[j] <= limit:\n i += 1\n j -= 1\n return ans", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n if len(people) == 0 or len(people) == 1:\n return len(people)\n else:\n lptr = 0\n rptr = len(people) - 1\n count = 0\n while lptr <= rptr:\n if people[lptr] + people[rptr] <= limit:\n count += 1\n lptr += 1\n rptr -= 1\n else:\n rptr -= 1\n count += 1\n return count", "from collections import deque\n\ndef numrescueboats(people: List[int], limit: int) -> int:\n people = deque(sorted(people))\n count = 0\n while len(people) > 1:\n lightest = people.popleft()\n heaviest = people.pop()\n if lightest + heaviest <= limit:\n count += 1\n continue\n else:\n if lightest < limit:\n people.appendleft(lightest)\n else:\n count += 1\n count += 1\n return count + len(people)", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort(reverse=True)\n res = 0\n i = 0\n j = len(people) - 1\n while i <= j:\n if people[i] + people[j] <= limit:\n j -= 1\n i += 1\n return i", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n lo = 0\n count = 0\n for hi in range(len(people))[::-1]:\n if lo < hi and people[lo] + people[hi] <= limit:\n lo += 1\n if lo == hi:\n return len(people) - hi", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n n = len(people)\n i = 0\n j = n - 1\n boats = 0\n while i <= j:\n if people[i] + people[j] <= limit:\n i += 1\n j -= 1\n boats += 1\n return boats", "def numrescueboats(people: List[int], limit: int) -> int:\n people = sorted(people)\n count = 0\n (i, j) = (0, len(people) - 1)\n while 0 <= i < j < len(people):\n while 0 <= i < j < len(people) and people[i] + people[j] > limit:\n j -= 1\n count += 1\n i += 1\n j -= 1\n count += 1\n if i == j:\n count += 1\n return count", "def numrescueboats(people: List[int], limit: int) -> int:\n minBoats = 0\n people.sort()\n left = 0\n right = len(people) - 1\n while left <= right:\n if people[left] + people[right] <= limit:\n left += 1\n minBoats += 1\n right -= 1\n return minBoats", "def numrescueboats(people: List[int], limit: int) -> int:\n people = sorted(people)\n left = 0\n right = len(people) - 1\n counter = 0\n while left < right:\n total = people[left] + people[right]\n counter += 1\n right -= 1\n if total <= limit:\n left += 1\n if left == right:\n counter += 1\n return counter", "def numrescueboats(people: List[int], limit: int) -> int:\n bucket = [0] * (limit + 1)\n for i in people:\n bucket[i] += 1\n start = 0\n end = len(bucket) - 1\n count = 0\n while start <= end:\n while start <= end and bucket[start] <= 0:\n start += 1\n while start <= end and bucket[end] <= 0:\n end -= 1\n if bucket[start] <= 0 and bucket[end] <= 0:\n break\n count += 1\n if start + end <= limit:\n bucket[start] -= 1\n bucket[end] -= 1\n return count", "def numrescueboats(people: List[int], limit: int) -> int:\n if people == None or len(people) == 0:\n return 0\n people.sort()\n start = 0\n end = len(people) - 1\n counter = 0\n while start <= end:\n if people[start] + people[end] <= limit:\n start += 1\n end -= 1\n else:\n end -= 1\n counter += 1\n return counter", "def numrescueboats(people: List[int], limit: int) -> int:\n q = collections.deque(sorted(people))\n ans = 0\n while len(q) > 1:\n (i, x) = (q.pop(), q[0])\n if i + x <= limit:\n q.popleft()\n ans += 1\n return ans + (1 if q else 0)", "import heapq\n\ndef numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n (i, j) = (0, len(people) - 1)\n ans = 0\n while i <= j:\n ans += 1\n if people[i] + people[j] <= limit:\n i += 1\n j -= 1\n return ans", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n p1 = 0\n p2 = len(people) - 1\n count = 1\n cur = 0\n curNum = 0\n while p1 <= p2:\n if people[p2] <= limit - cur and curNum < 2:\n cur = cur + people[p2]\n curNum += 1\n p2 -= 1\n continue\n if people[p1] <= limit - cur and curNum < 2:\n cur = cur + people[p1]\n curNum += 1\n p1 += 1\n continue\n count += 1\n cur = 0\n curNum = 0\n return count", "def numrescueboats(people: List[int], limit: int) -> int:\n people = sorted(people, reverse=True)\n boats = 0\n left = 0\n right = len(people) - 1\n while left <= right:\n if people[left] + people[right] <= limit:\n right -= 1\n left += 1\n boats += 1\n return boats", "def numrescueboats(people: List[int], limit: int) -> int:\n if not people or limit == 0:\n return 0\n ans = 0\n people.sort()\n (left, right) = (0, len(people) - 1)\n while left <= right:\n if people[left] + people[right] <= limit:\n left += 1\n right -= 1\n else:\n right -= 1\n ans += 1\n return ans", "from collections import Counter\n\ndef numrescueboats(people, limit):\n people.sort(reverse=True)\n boats = 0\n r = len(people) - 1\n l = 0\n while l <= r:\n boats += 1\n if people[l] + people[r] <= limit:\n r -= 1\n l += 1\n return boats", "def numrescueboats(people: List[int], limit: int) -> int:\n people = sorted(people)\n l = 0\n r = len(people) - 1\n ret = 0\n while l < r:\n if people[r] >= limit:\n ret += 1\n r -= 1\n elif people[r] + people[l] > limit:\n ret += 1\n r -= 1\n else:\n ret += 1\n l += 1\n r -= 1\n if l == r:\n ret += 1\n return ret", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort()\n N = len(people)\n num_boats = 0\n if len(people) == 1:\n return 1\n less_than_half = [p for p in people if p <= limit / 2]\n more_than_half = [p for p in people if p > limit / 2]\n while len(more_than_half) > 0 and len(less_than_half) > 0:\n if more_than_half[-1] + less_than_half[0] > limit:\n more_than_half.pop(-1)\n num_boats += 1\n continue\n else:\n more_than_half.pop(-1)\n less_than_half.pop(0)\n num_boats += 1\n continue\n num_boats += len(more_than_half)\n num_boats += int(len(less_than_half) / 2 + 0.5)\n return num_boats", "def numrescueboats(people: List[int], limit: int) -> int:\n sortedPeople = sorted(people)\n i = 0\n j = len(sortedPeople) - 1\n count = 0\n while i <= j:\n if i == j:\n count += 1\n i += 1\n j -= 1\n continue\n if sortedPeople[i] + sortedPeople[j] <= limit:\n count += 1\n i += 1\n j -= 1\n else:\n count += 1\n j -= 1\n return count", "def numrescueboats(people: List[int], limit: int) -> int:\n people.sort(reverse=True)\n boats = people[:(1 + len(people)) // 2]\n onboard = [1] * len(boats)\n i = 0\n j = len(boats)\n k = len(people) - 1\n while j <= k:\n if i == len(boats):\n boats.append(people[j])\n j += 1\n if j > k:\n break\n target = limit - boats[i]\n if people[k] > target:\n i += 1\n if i == len(boats):\n boats.append(people[j])\n j += 1\n else:\n boats[i] += people[k]\n k -= 1\n i += 1\n return len(boats)", "def numrescueboats(people: List[int], limit: int) -> int:\n left = 0\n right = len(people) - 1\n boat = 0\n people.sort()\n while left <= right:\n if left == right:\n boat += 1\n break\n elif people[left] + people[right] <= limit:\n left += 1\n right -= 1\n boat += 1\n return boat"], "starter_code": "def numrescueboats(people: List[int], limit: int) -> int:\n", "input_output": {"fn_name": "numRescueBoats", "inputs": [[[1, 2], 3]], "outputs": [1]}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Two Pointers", "Greedy", "Sorting"], "name": null, "source": "leetcode", "tags": ["Data structures", "Sorting", "Amortized analysis", "Greedy algorithms"], "skill_types": ["Sorting", "Amortized analysis", "Data structures", "Greedy algorithms"], "url": "https://leetcode.com/problems/boats-to-save-people/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numrescueboats", "task_id": "TACO_lite/331", "example": [[[[1, 2], 3], [[3, 2, 2, 1], 3], [[3, 5, 3, 4], 5]], ["1", "3", "4"]]} +{"requirement": "Given a sorted array of size N. Count the number of distinct absolute values present in the array.\n \nExample 1:\nInput:\nN = 6\nArr[] = {-3, -2, 0, 3, 4, 5}\nOutput: 5\nExplanation: There are 5 distinct absolute \nvalues i.e. 0, 2, 3, 4 and 5.\nExample 2:\nInput:\nN = 9\nArr[] = {-1, -1, -1, -1, 0, 1, 1, 1, 1}\nOutput: 2\nExplanation: There are 2 distinct absolute values \namong the elements of this array, i.e. 0 and 1.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function distinctCount() which takes the array of integers arr[] and its size n as input parameters and returns an integer denoting the answer.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 10^{5}\n-10^{8} <= Arr[i] <= 10^{8}\nThe array may contain duplicates", "solutions": ["def distinctcount(arr, n):\n s = [abs(x) for x in arr]\n s = list(set(s))\n return len(s)", "def distinctcount(arr, n):\n c = set()\n for i in arr:\n if i not in c:\n c.add(abs(i))\n return len(c)", "def distinctcount(arr, n):\n l = []\n for i in arr:\n l.append(abs(i))\n return len(set(l))", "def distinctcount(arr, n):\n d = {}\n for i in arr:\n d[abs(i)] = d.setdefault(abs(i), 0) + 1\n return len(d)", "def distinctcount(arr, n):\n for i in range(n):\n arr[i] = abs(arr[i])\n a = set(arr)\n b = list(a)\n return len(b)", "def distinctcount(arr, n):\n i = 0\n while i < n:\n if arr[i] < 0:\n arr[i] = abs(arr[i])\n i += 1\n return len(set(arr))", "def distinctcount(arr, n):\n s = set()\n for i in arr:\n s.add(abs(i))\n return len(s)", "def distinctcount(arr, n):\n for i in range(n):\n arr[i] = abs(arr[i])\n return len(set(arr))", "def distinctcount(arr, n):\n num = [abs(i) for i in arr]\n num = list(set(num))\n return len(num)", "def distinctcount(arr, n):\n i = 0\n j = n - 1\n prev = -10000000007\n next = 10000000007\n c = 0\n while i <= j:\n if abs(arr[i]) == abs(arr[j]):\n if arr[i] != prev and arr[j] != next:\n c += 1\n prev = arr[i]\n next = arr[j]\n i += 1\n j -= 1\n elif abs(arr[i]) < abs(arr[j]):\n if arr[j] != next:\n c += 1\n next = arr[j]\n j -= 1\n else:\n if arr[i] != prev:\n c += 1\n prev = arr[i]\n i += 1\n return c", "def distinctcount(arr, n):\n res = [abs(ele) for ele in arr]\n a = set(res)\n return len(a)", "from collections import Counter\n\ndef distinctcount(arr, n):\n return len(Counter(map(abs, arr)))", "def distinctcount(arr, n):\n ans = set()\n for e in arr:\n ans.add(abs(e))\n return len(ans)", "def distinctcount(arr, n):\n for i in range(n):\n if arr[i] < 0:\n arr[i] = -1 * arr[i]\n return len(set(arr))", "def distinctcount(arr, n):\n hmap = {}\n for i in arr:\n y = abs(i)\n if y not in hmap:\n hmap[y] = 1\n else:\n hmap[y] += 1\n return len(hmap)", "def distinctcount(arr, n):\n d = {}\n for i in arr:\n b = abs(i)\n if b not in d:\n d[b] = 1\n return len(d)", "def distinctcount(arr, n):\n m = [abs(i) for i in arr]\n l = list(set(m))\n return len(l)", "def distinctcount(arr, n):\n for i in range(n):\n if arr[i] < 0:\n arr[i] = -1 * arr[i]\n arr.sort()\n i = 1\n count = 1\n while i < n:\n if arr[i - 1] == arr[i]:\n i += 1\n else:\n count += 1\n i += 1\n return count", "def distinctcount(arr, n):\n ab = []\n for i in arr:\n ab.append(abs(i))\n return len(list(set(ab)))", "def distinctcount(arr, n):\n res = {}\n for i in range(n):\n if abs(arr[i]) not in res:\n res[abs(arr[i])] = 1\n return len(res)", "def distinctcount(arr, n):\n s = {}\n for i in arr:\n s[abs(i)] = 1\n return len(s)", "def distinctcount(arr, n):\n s = set()\n for x in arr:\n if x < 0:\n s.add(x * -1)\n else:\n s.add(x)\n return len(s)", "def distinctcount(arr, n):\n l = {}\n for i in arr:\n if abs(i) not in l:\n l[abs(i)] = 1\n return sum(l.values())", "import bisect\n\ndef distinctcount(a, n):\n num = [abs(i) for i in a]\n num = list(set(num))\n return len(num)", "def distinctcount(arr, n):\n l = 0\n r = n - 1\n cnt = 0\n while l <= r:\n while l < r and r > 0 and (arr[r - 1] == arr[r]):\n r = r - 1\n while l < r and l < n - 1 and (arr[l] == arr[l + 1]):\n l = l + 1\n if abs(arr[l]) == abs(arr[r]):\n l = l + 1\n r = r - 1\n elif abs(arr[l]) > abs(arr[r]):\n l = l + 1\n else:\n r = r - 1\n cnt = cnt + 1\n return cnt", "def distinctcount(arr, n):\n low = 0\n high = n - 1\n ans = n\n s = 0\n while low < high:\n while low != high and arr[low] == arr[low + 1]:\n ans -= 1\n low += 1\n while low != high and arr[high - 1] == arr[high]:\n ans -= 1\n high -= 1\n if low == high:\n break\n s = arr[low] + arr[high]\n if s == 0:\n ans -= 1\n low += 1\n high -= 1\n elif s > 0:\n high -= 1\n else:\n low += 1\n return ans", "def distinctcount(arr, n):\n count = 0\n gg = {}\n for i in arr:\n if i < 0:\n i = -i\n if i not in gg:\n gg[i] = 1\n count += 1\n return count", "def distinctcount(arr, n):\n u = []\n for i in range(len(arr)):\n u.append(abs(arr[i]))\n x = list(set(u))\n return len(x)", "from collections import defaultdict\n\ndef distinctcount(arr, n):\n d = defaultdict(lambda : 0)\n c = n\n for i in range(n - 1, -1, -1):\n if arr[i] >= 0:\n d[arr[i]] += 1\n else:\n x = abs(arr[i])\n if d[x] > 0:\n continue\n return len(d)", "def distinctcount(arr, n):\n cnt = n\n (i, j) = (0, n - 1)\n while i < j:\n while i != j and arr[i] == arr[i + 1]:\n i += 1\n cnt -= 1\n while i != j and arr[j] == arr[j - 1]:\n j -= 1\n cnt -= 1\n if i == j:\n break\n if arr[i] + arr[j] < 0:\n i += 1\n elif arr[i] + arr[j] > 0:\n j -= 1\n else:\n cnt -= 1\n i += 1\n j -= 1\n return cnt", "def distinctcount(arr, n):\n return len(set(sorted(map(abs, arr))))", "def distinctcount(arr, n):\n dictt = {}\n for ele in arr:\n ele = abs(ele)\n dictt[ele] = dictt.get(ele, 0) + 1\n return len(dictt)", "def distinctcount(arr, n):\n d = set()\n for i in arr:\n if i < 0:\n d.add(-1 * i)\n else:\n d.add(i)\n return len(list(d))", "def distinctcount(arr, n):\n c = 0\n i = 0\n j = len(arr) - 1\n prev = float('-inf')\n nextt = float('inf')\n while i <= j:\n if abs(arr[i]) == abs(arr[j]):\n if arr[i] != prev and arr[j] != nextt:\n c += 1\n prev = arr[i]\n nextt = arr[j]\n i += 1\n j -= 1\n elif abs(arr[i]) < abs(arr[j]):\n if arr[j] != nextt:\n c += 1\n nextt = arr[j]\n j -= 1\n elif abs(arr[i]) > abs(arr[j]):\n if arr[i] != prev:\n c += 1\n prev = arr[i]\n i += 1\n return c", "def distinctcount(arr, n):\n import numpy as np\n arr = [np.abs(i) for i in arr]\n return len(list(set(arr)))", "def distinctcount(arr, n):\n arr = list(set([abs(a) for a in arr]))\n return len(arr)"], "starter_code": "def distinctcount(arr, n):\n", "input_output": {"inputs": ["N = 6\r\nArr[] = {-3, -2, 0, 3, 4, 5}", "N = 9\r\nArr[] = {-1, -1, -1, -1, 0, 1, 1, 1, 1}"], "outputs": ["5", "2"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays", "Algorithms", "Sorting"], "name": null, "source": "geeksforgeeks", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/distinct-absolute-array-elements4529/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "distinctcount", "task_id": "TACO_lite/325", "example": [[[6, [-3, -2, 0, 3, 4, 5]], [9, [-1, -1, -1, -1, 0, 1, 1, 1, 1]]], [null, null]]} +{"requirement": "Given an array of N elements and L and R, print the number of sub-arrays such that the value of the maximum array element in that subarray is at least L and at most R.\nExample 1:\nInput : Arr[] = {2, 0, 11, 3, 0}\nL = 1 and R = 10\nOutput : 4\nExplanation:\nThe sub-arrays {2}, {2, 0}, {3} and {3, 0}\nhave maximum in range 1-10.\nExample 2:\nInput : Arr[] = {3, 4, 1}\nL = 2 and R = 4\nOutput : 5\n \nYour Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function countSubarrays() that takes an array (arr), sizeOfArray (n), element L, integer R, and return the number of subarray with the maximum in range L-R. The driver code takes care of the printing.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\n \nConstraints:\n1 \u2264 N \u2264 10^{5}\n1 \u2264 L \u2264 R \u2264 10^{6}", "solutions": ["def mgc(n):\n return n * (n + 1) // 2\n\ndef countsubarrays(a, n, L, R):\n (fp, lp) = (0, 0)\n ans = 0\n prev = 0\n while lp < n:\n if a[lp] >= L and a[lp] <= R:\n prev = lp - fp + 1\n elif a[lp] > R:\n prev = 0\n fp = lp + 1\n lp += 1\n ans += prev\n return ans", "def countsubarrays(nums, a, left, right):\n ans = 0\n cnt = 0\n i = 0\n j = 0\n while i < a:\n if nums[i] >= left and nums[i] <= right:\n cnt = i - j + 1\n ans += cnt\n elif nums[i] < left:\n ans += cnt\n elif nums[i] > right:\n cnt = 0\n j = i + 1\n i += 1\n return ans", "def countsubarrays(nums, a, left, right):\n\n def count(bound):\n ans = cnt = 0\n for x in nums:\n if x <= bound:\n cnt = cnt + 1\n else:\n cnt = 0\n ans += cnt\n return ans\n return count(right) - count(left - 1)", "def countsubarrays(a, n, L, R):\n ans = 0\n maxele = -999999\n maxind = -1\n cnt = 0\n for i in range(n):\n if a[i] >= L and a[i] <= R:\n cnt = 0\n ans += i - maxind\n elif a[i] > R:\n cnt = 0\n maxind = i\n else:\n cnt += 1\n ans += i - maxind - cnt\n return ans", "def countsubarrays(a, n, L, R):\n (wind, count, i, j) = (0, 0, 0, 0)\n while j < n:\n if a[j] >= L and a[j] <= R:\n wind = j - i + 1\n elif a[j] > R:\n wind = 0\n i = j + 1\n count += wind\n j += 1\n return count", "def countsubarrays(a, n, L, R):\n (left, right) = (-1, -1)\n idx = 0\n ans = 0\n while idx < n:\n cur = a[idx]\n if L <= cur <= R:\n right = idx\n elif cur > R:\n (left, right) = (idx, idx)\n ans += right - left\n idx += 1\n return ans", "def countsubarrays(a, n, L, R):\n right = -1\n start = -1\n i = 0\n ans = 0\n while i < n:\n cur = a[i]\n if L <= cur <= R:\n right = i\n elif cur > R:\n start = i\n right = i\n ans += right - start\n i += 1\n return ans", "def countsubarrays(a, n, L, R):\n cur_max = 0\n cur_max_idx = -1\n right_most_range = 0\n start = -1\n i = 0\n ans = 0\n while i < n:\n cur = a[i]\n if L <= cur <= R:\n right_most_idx = i\n if cur_max < cur:\n cur_max = cur\n cur_max_idx = i\n if cur_max > R:\n start = i\n cur_max = 0\n cur_max_idx = i\n right_most_range = i\n elif L <= cur_max <= R:\n ans += right_most_idx - start\n i += 1\n return ans", "def countsubarrays(a, n, L, R):\n ans = 0\n sub = 0\n start = 0\n for end in range(n):\n if arr[end] >= L and arr[end] <= R:\n sub = end - start + 1\n if arr[end] > R:\n sub = 0\n start = end + 1\n ans += sub\n return ans", "def countsubarrays(a, n, L, R):\n i = 0\n j = 0\n count = 0\n result = 0\n while j < len(a):\n if L <= a[j] <= R:\n result = j - i + 1\n if a[j] > R:\n result = 0\n i = j + 1\n count = count + result\n j = j + 1\n return count", "def countsubarrays(a, n, L, R):\n i = 0\n j = 0\n count = 0\n m = 0\n while j < n:\n if a[j] > R:\n m = 0\n i = j + 1\n elif a[j] in range(L, R + 1):\n m = j - i + 1\n j += 1\n count += m\n return count", "def code(n):\n return n * (n + 1) // 2\n\ndef countsubarrays(a, n, L, R):\n l = 0\n r = 0\n ans = 0\n for i in range(n):\n if a[i] < L:\n l += 1\n r += 1\n elif a[i] > R:\n ans += Solution.code(l) - Solution.code(r)\n l = 0\n r = 0\n else:\n ans -= Solution.code(r)\n r = 0\n l += 1\n ans += Solution.code(l) - Solution.code(r)\n return ans", "def countsubarrays(arr, n, L, R):\n ans = 0\n prevcnt = 0\n (s, e) = (0, 0)\n while e <= n - 1:\n if L <= arr[e] and arr[e] <= R:\n ans += e - s + 1\n prevcnt = e - s + 1\n elif arr[e] < L:\n ans += prevcnt\n elif arr[e] > R:\n s = e + 1\n prevcnt = 0\n e += 1\n return ans", "def countsubarrays(a, n, L, R):\n\n def sub(n):\n return n * (n + 1) // 2\n res = 0\n inc = 0\n exc = 0\n for i in range(len(a)):\n if arr[i] > R:\n res = res + (sub(inc) - sub(exc))\n inc = 0\n exc = 0\n elif arr[i] < L:\n inc += 1\n exc += 1\n else:\n res = res - sub(exc)\n inc += 1\n exc = 0\n res = res + (sub(inc) - sub(exc))\n return res", "def countsubarrays(nums, n, left, right):\n i = 0\n j = 0\n c = 0\n m = 0\n while j < len(nums):\n if nums[j] > r:\n m = 0\n i = j + 1\n elif nums[j] >= left and nums[j] <= right:\n m = j - i + 1\n c += m\n j += 1\n return c", "def countsubarrays(a, n, L, R):\n ans = 0\n st = 0\n build = 0\n for i in range(n):\n if L <= a[i] <= R:\n build = i - st + 1\n elif a[i] > R:\n build = 0\n st = i + 1\n ans += build\n return ans", "def countsubarrays(arr, n, L, R):\n (i, j) = (0, 0)\n count = 0\n m = 0\n while j < n:\n if arr[j] >= L and arr[j] <= R:\n m = j - i + 1\n elif arr[j] > R:\n m = 0\n i = j + 1\n count += m\n j += 1\n return count", "def countsubarrays(a, n, L, R):\n c = 0\n (i, j, k) = (0, 0, 0)\n while j < n:\n if a[j] > R:\n k = 0\n i = j + 1\n elif a[j] >= L and a[j] <= R:\n k = j - i + 1\n c += k\n j += 1\n return c", "from collections import deque\n\ndef countsubarrays(arr, n, l, r):\n dp = [0] * n\n q = deque()\n for i in range(n):\n while q and arr[q[-1]] <= arr[i]:\n q.pop()\n if not q:\n dp[i] = (i + 1) * int(l <= arr[i] <= r)\n else:\n dp[i] = (i - q[-1]) * int(l <= arr[i] <= r) + dp[q[-1]]\n q.append(i)\n return sum(dp)", "def countsubarrays(nums, n, left, right):\n (n, l, valid, res) = (len(nums), 0, 0, 0)\n for r in range(0, n):\n if left <= nums[r] <= right:\n valid = r - l + 1\n if nums[r] > right:\n l = r + 1\n valid = 0\n res += valid\n return res", "def countsubarrays(a, n, L, R):\n i = j = 0\n ans = curr = 0\n while j < n:\n if a[j] >= L and a[j] <= R:\n curr = j - i + 1\n if a[j] > R:\n curr = 0\n i = j + 1\n ans += curr\n j += 1\n return ans", "def countsubarrays(a, n, L, R):\n\n def maxlessthanequalto(x):\n max_so_far = 0\n end = start = 0\n count = 0\n while end < n:\n if a[end] <= x:\n count += end - start + 1\n end += 1\n else:\n end = end + 1\n start = end\n return count\n return maxlessthanequalto(R) - maxlessthanequalto(L - 1)", "def countsubarrays(a, n, L, R):\n start = 0\n count = 0\n sub_count = 0\n for end in range(n):\n if a[end] >= L and a[end] <= R:\n sub_count = end - start + 1\n elif a[end] > R:\n start = end + 1\n sub_count = 0\n count += sub_count\n return count", "def count_sub_array(n):\n return n * (n + 1) // 2 if n else 0\n\ndef countsubarrays(a, n, L, R):\n less_tha_l = 0\n total = 0\n ans = 0\n for i in range(n):\n if a[i] > R:\n ans += self.count_sub_array(total) - self.count_sub_array(less_tha_l)\n less_tha_l = 0\n total = 0\n elif a[i] < L:\n less_tha_l += 1\n total += 1\n else:\n ans = ans - self.count_sub_array(less_tha_l)\n less_tha_l = 0\n total += 1\n ans += self.count_sub_array(total) - self.count_sub_array(less_tha_l)\n return ans", "def countsubarrays(a, n, l, r):\n (i, j, ans) = (-1, -1, 0)\n for k in range(n):\n if a[k] > r:\n (i, j) = (k, k)\n elif a[k] >= l and a[k] <= r:\n j = k\n ans += j - i\n return ans", "def countsubarrays(a, n, L, R):\n (gr, ls, temp) = (0, 0, 0)\n for i in range(n):\n if arr[i] <= r:\n gr += 1\n else:\n temp += gr * (gr + 1) // 2\n gr = 0\n if arr[i] < l:\n ls += 1\n else:\n temp -= ls * (ls + 1) // 2\n ls = 0\n temp -= ls * (ls + 1) // 2\n temp += gr * (gr + 1) // 2\n return temp", "def countsubarrays(nums, n, left, right):\n (start, count, window_len) = (0, 0, 0)\n for (end, num) in enumerate(nums):\n if left <= num <= right:\n window_len = end - start + 1\n elif num > right:\n window_len = 0\n start = end + 1\n count += window_len\n return count", "def countsubarrays(a, n, l, r):\n i = 0\n j = 0\n c = 0\n ans = 0\n while j < n:\n if a[j] >= l and a[j] <= r:\n c = j - i + 1\n if a[j] > r:\n i = j + 1\n c = 0\n ans += c\n j = j + 1\n return ans", "def f(n):\n return n * (n + 1) // 2\n\ndef countsubarrays(arr, n, L, R):\n x = 0\n y = 0\n ans = 0\n for i in arr:\n if i > R:\n ans += self.f(x) - self.f(y)\n x = 0\n y = 0\n elif i < L:\n x += 1\n y += 1\n else:\n ans -= self.f(y)\n x += 1\n y = 0\n ans += self.f(x) - self.f(y)\n return ans", "def count(n):\n return n * (n + 1) // 2\n\ndef countsubarrays(a, n, L, R):\n ans = 0\n x = 0\n y = 0\n for i in a:\n if i > R:\n ans += self.count(x) - self.count(y)\n x = 0\n y = 0\n elif i < L:\n x += 1\n y += 1\n else:\n ans -= self.count(y)\n x += 1\n y = 0\n ans += self.count(x) - self.count(y)\n return ans", "def countsubarrays(a, n, L, R):\n si = 0\n ans = 0\n prev = 0\n for ei in range(n):\n if l <= a[ei] <= R:\n prev = ei - si + 1\n ans += prev\n elif L > a[ei]:\n ans += prev\n else:\n prev = 0\n si = ei + 1\n return ans", "def countsubarrays(a, n, L, R):\n i0 = 0\n i1 = 0\n Rplus = 0\n Lminus = 0\n Lminus1 = 0\n res = 0\n for j in range(len(a)):\n if a[j] > R:\n Rplus += 1\n elif a[j] < L:\n Lminus += 1\n Lminus1 += 1\n while Rplus > 0:\n if a[i0] > R:\n Rplus -= 1\n elif a[i0] < L:\n Lminus -= 1\n i0 += 1\n if i0 > i1:\n if a[i1] < L:\n Lminus1 -= 1\n i1 += 1\n while i1 <= j and Lminus1 < j - i1 + 1:\n if a[i1] < L:\n Lminus1 -= 1\n i1 += 1\n res += i1 - i0\n return res", "def countsubarrays(a, n, L, R):\n res = 0\n N = n\n A = a\n start = 0\n count = 0\n for i in range(N):\n if A[i] >= L and A[i] <= R:\n count = i - start + 1\n res = res + i - start + 1\n elif A[i] < L:\n res = res + count\n else:\n count = 0\n start = i + 1\n return res", "def countsubarrays(a, n, L, R):\n res = 0\n count = 0\n i = 0\n for j in range(n):\n if L <= a[j] <= R:\n count = j - i + 1\n res += count\n elif a[j] < L:\n res += count\n elif a[j] > R:\n count = 0\n i = j + 1\n return res"], "starter_code": "def countsubarrays(a,n,L,R):\n", "input_output": {"inputs": ["Arr[] = {2, 0, 11, 3, 0}\nL = 1 and R = 10", "Arr[] = {3, 4, 1}\nL = 2 and R = 4"], "outputs": ["4", "5"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "two-pointer-algorithm", "sliding-window", "Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Amortized analysis"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/number-of-subarrays-with-maximum-values-in-given-range5949/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "countsubarrays", "task_id": "TACO_lite/294", "example": [[[[2, 0, 11, 3, 0], 5, 1, 10], [[3, 4, 1], 3, 2, 4]], ["4", "5"]]} +{"requirement": "Your job at E-Corp is both boring and difficult. It isn't made any easier by the fact that everyone constantly wants to have a meeting with you, and that the meeting rooms are always taken!\n\nIn this kata, you will be given an array. Each value represents a meeting room. Your job? Find the **first** empty one and return its index (N.B. There may be more than one empty room in some test cases). \n\n'X' --> busy\n'O' --> empty\n\nIf all rooms are busy, return 'None available!'.\n\n\nMore in this series:\n\nThe Office I - Outed\nThe Office II - Boredeom Score\nThe Office III - Broken Photocopier\nThe Office V - Find a Chair", "solutions": ["def meeting(rooms):\n try:\n return rooms.index('O')\n except ValueError:\n return 'None available!'", "def meeting(rooms):\n return rooms.index('O') if 'O' in rooms else 'None available!'", "def meeting(rooms):\n return next((i for (i, r) in enumerate(rooms) if r == 'O'), 'None available!')", "def meeting(rooms):\n if 'O' not in rooms:\n return 'None available!'\n return rooms.index('O')", "def meeting(rooms):\n for (num, status) in enumerate(rooms):\n if status == 'O':\n return num\n return 'None available!'", "def meeting(rooms):\n return [o for (o, v) in enumerate(rooms) if v == 'O'][0] if 'O' in rooms else 'None available!'", "def meeting(rooms):\n tally = 0\n for i in rooms:\n if i == 'O':\n return tally\n else:\n tally += 1\n return 'None available!'", "def meeting(rooms):\n for x in rooms:\n if x is 'O':\n return rooms.index(x)\n return 'None available!'"], "starter_code": "def meeting(rooms):\n", "input_output": {"fn_name": "meeting", "inputs": [[["X", "O", "X"]], [["O", "X", "X", "X", "X"]], [["X", "X", "O", "X", "X"]], [["X"]]], "outputs": [[1], [0], [2], ["None available!"]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57f604a21bd4fe771b00009c", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "meeting", "task_id": "TACO_lite/312", "example": [[[["X", "O", "X", "X"]], [["X", "X", "X"]], [["X", "O", "O", "X"]]], ["1", "None available!", "1"]]} +{"requirement": "Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.)\n(Recall that an integer\u00a0is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers\u00a0both smaller than it.)\nSince the answer may be large, return the answer modulo 10^9 + 7.\n\u00a0\nExample 1:\nInput: n = 5\nOutput: 12\nExplanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.\n\nExample 2:\nInput: n = 100\nOutput: 682289015\n\n\u00a0\nConstraints:\n\n1 <= n <= 100", "solutions": ["def numprimearrangements(n: int) -> int:\n primes = [True] * (n + 1)\n for prime in range(2, int(math.sqrt(n)) + 1):\n if primes[prime]:\n for composite in range(prime * prime, n + 1, prime):\n primes[composite] = False\n cnt = sum(primes[2:])\n return math.factorial(cnt) * math.factorial(n - cnt) % (10 ** 9 + 7)", "def numprimearrangements(n: int) -> int:\n p_nums = []\n c_nums = []\n dp = [True for _ in range(n + 1)]\n dp[0] = False\n dp[1] = False\n for i in range(2, n + 1):\n if dp[i] == True:\n cnt = 2\n while i * cnt < n + 1:\n dp[i * cnt] = False\n cnt += 1\n for i in range(1, n + 1):\n if dp[i]:\n p_nums += [i]\n else:\n c_nums += [i]\n return self.fact(len(p_nums) % (10 ** 9 + 7)) * self.fact(len(c_nums)) % (10 ** 9 + 7)\n\ndef fact(n):\n if n <= 1:\n return 1\n else:\n return n * self.fact(n - 1)", "def numprimearrangements(n: int) -> int:\n\n def fac(m):\n result = 1\n for i in range(1, m + 1):\n result *= i\n return result\n\n def PrimeTell(m):\n if m == 1 or m == 4:\n return False\n if m == 2 or m == 3:\n return True\n for j in range(2, m // 2):\n if m % j == 0:\n return False\n return True\n Sum = 0\n for i in range(1, n + 1):\n if PrimeTell(i):\n Sum += 1\n return fac(Sum) * fac(n - Sum) % (10 ** 9 + 7)", "def numprimearrangements(n: int) -> int:\n if n == 1:\n return 1\n p = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n if n < 98:\n (lo, hi) = (0, 24)\n while lo <= hi:\n mid = (hi - lo) // 2 + lo\n if p[mid] == n:\n idx = mid + 1\n break\n elif p[mid - 1] < n and n < p[mid]:\n idx = mid\n break\n elif p[mid] > n:\n hi = mid - 1\n else:\n lo = mid + 1\n else:\n idx = 25\n p_prod = 1\n for i in range(1, idx + 1):\n p_prod = p_prod * (i % 1000000007) % 1000000007\n c_prod = 1\n for i in range(1, n - idx + 1):\n c_prod = c_prod * (i % 1000000007) % 1000000007\n return p_prod * c_prod % 1000000007", "def numprimearrangements(n: int) -> int:\n primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n r = sum((1 for p in primes if p <= n))\n a = 10 ** 9 + 7\n ans = 1\n for i in range(1, min(r, n - r) + 1):\n ans *= (i % a) ** 2\n ans %= a\n for i in range(min(r, n - r) + 1, max(r, n - r) + 1):\n ans *= i\n ans %= a\n return ans"], "starter_code": "def numprimearrangements(n: int) -> int:\n", "input_output": {"fn_name": "numPrimeArrangements", "inputs": [[5]], "outputs": [12]}, "difficulty": "EASY", "raw_tags": ["Math"], "name": null, "source": "leetcode", "tags": ["Mathematics"], "skill_types": [], "url": "https://leetcode.com/problems/prime-arrangements/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numprimearrangements", "task_id": "TACO_lite/281", "example": [[[5], [100]], ["12", "682289015"]]} +{"requirement": "Create a function that accepts 3 inputs, a string, a starting location, and a length. The function needs to simulate the string endlessly repeating in both directions and return a substring beginning at the starting location and continues for length.\n\nExample:\n```python\nendless_string('xyz', -23, 6) == 'yzxyzx'\n```\nTo visualize:\n\n Negative Positive\n 3 2 1 * 1 2 3 \n 0987654321098765432109876543210123456789012345678901234567890\n xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzx\n ******\n -23 for a length of 6 == 'yzxyzx'\n \nSome more examples:\n```python\nendless_string('xyz', 0, 4) == 'xyzx'\nendless_string('xyz', 19, 2) == 'yz'\nendless_string('xyz', -4, -4) == 'zxyz'\n```\n\nA negative length needs to include the starting postion and return the characters to the left of the starting position.", "solutions": ["from itertools import cycle, islice\n\ndef endless_string(string, start, length):\n i = (start + (length + 1 if length < 0 else 0)) % len(string)\n return ''.join(islice(cycle(string), i, i + abs(length)))", "from itertools import cycle, islice\n\ndef endless_string(stg, i, l):\n i = min(i, i + l) % len(stg) + (l < 0)\n j = i + abs(l)\n return ''.join(islice(cycle(stg), i, j))", "from itertools import cycle, islice\n\ndef endless_string(string, start, length):\n r = (start + (length + 1) * (length < 0)) % len(string)\n return ''.join(islice(cycle(string), r, r + abs(length)))", "def endless_string(s, start, l):\n s = s * 500\n half = len(s) // 2\n return s[half + start:half + start + l] if l > 0 else s[half + start + l + 1:half + start + 1]", "def endless_string(strng, start, length):\n len_strng = len(strng)\n strng = strng * (abs(length) // len_strng + 1)\n true_start = min(start, start + length)\n start = true_start % len_strng + (length < 0)\n stop = start + abs(length)\n return strng[start:stop]", "def endless_string(stg, i, l):\n ls = len(stg)\n stg = stg * (2 + abs(l) // ls)\n i = min(i, i + l) % ls + (l < 0)\n j = i + abs(l)\n return stg[i:j]"], "starter_code": "def endless_string(string, start, length):\n", "input_output": {"fn_name": "endless_string", "inputs": [["xyz", -23, 6], ["xyz", 0, 4], ["xyz", 19, 2], ["xyz", -4, -4], ["abcdefghijklmnopqrstuvwxyz", 29, 1], ["Hello! How are you?", -14, 27], ["1x2x3x4x", 1532, 100], ["1x2x3x4x", -1532, -100], ["112233", 0, 0], ["112233", -1, 0], ["112233", 15824, 0]], "outputs": [["yzxyzx"], ["xyzx"], ["yz"], ["zxyz"], ["d"], ["! How are you?Hello! How ar"], ["3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x"], ["x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3x4x1x2x3"], [""], [""], [""]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/57048c1275263af10b00063e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "endless_string", "task_id": "TACO_lite/319", "example": [[["xyz", -23, 6], ["xyz", 0, 4], ["xyz", 19, 2], ["xyz", -4, -4]], ["yzxyzx", "xyzx", "yz", "zxyz"]]} +{"requirement": "# Story\n\nThose pesky rats have returned and this time they have taken over the Town Square.\n\nThe Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.\n\nBut some of the rats are deaf and are going the wrong way!\n\n# Kata Task\n\nHow many deaf rats are there?\n\n## Input Notes\n\n* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)\n* The Pied Piper is always present\n\n## Output Notes\n* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now\n* Use Euclidian distance for your calculations\n\n## Legend\n\n* `P` = The Pied Piper\n* `\u2190` `\u2191` `\u2192` `\u2193` `\u2196` `\u2197` `\u2198` `\u2199` = Rats going in different directions\n* space = Everything else\n\n\n\n# Examples\n\nex1 - has 1 deaf rat\n\n\n\u2197 P \n \u2198 \u2196\n \u2191 \n\u2197 \n\n\n---\n\nex2 - has 7 deaf rats\n\n\n \u2197 \nP \u2193 \u2196 \u2191\n \u2190 \u2193\n \u2196 \u2199 \u2199\n\u2193 \u2193 \u2193", "solutions": ["from math import hypot\nDIRS = {'\u2190': (0, -1), '\u2191': (-1, 0), '\u2192': (0, 1), '\u2193': (1, 0), '\u2196': (-1, -1), '\u2197': (-1, 1), '\u2198': (1, 1), '\u2199': (1, -1)}\n\ndef count_deaf_rats(town):\n pipper = next(((x, y) for (x, r) in enumerate(town) for (y, c) in enumerate(r) if c == 'P'))\n return sum((isDeaf(pipper, x, y, *DIRS[c]) for (x, r) in enumerate(town) for (y, c) in enumerate(r) if c in DIRS))\n\ndef isDeaf(pipper, x, y, dx, dy):\n (dCurrent, dNext) = (hypot(*(a - b for (a, b) in zip(pipper, pos))) for pos in ((x, y), (x + dx, y + dy)))\n return dCurrent < dNext", "from math import copysign\ndirections = {'\u2190': (0, -1), '\u2191': (-1, 0), '\u2192': (0, 1), '\u2193': (1, 0), '\u2196': (-1, -1), '\u2197': (-1, 1), '\u2198': (1, 1), '\u2199': (1, -1)}\n\ndef count_deaf_rats(town_square):\n (pi, pj) = next(((i, j) for (i, row) in enumerate(town_square) for (j, x) in enumerate(row) if x == 'P'))\n result = 0\n for (i, row) in enumerate(town_square):\n for (j, x) in enumerate(row):\n if x not in directions:\n continue\n (di, dj) = directions[x]\n if (i + di - pi) ** 2 + (j + dj - pj) ** 2 > (i - pi) ** 2 + (j - pj) ** 2:\n result += 1\n return result", "D = {'\u2196': -1 - 1j, '\u2191': -1, '\u2197': -1 + 1j, '\u2190': -1j, '\u2192': +1j, '\u2199': +1 - 1j, '\u2193': +1, '\u2198': +1 + 1j}\n\ndef count_deaf_rats(town_square):\n coords = [(i + j * 1j, x) for (i, row) in enumerate(town_square) for (j, x) in enumerate(row)]\n p = next((c for (c, x) in coords if x == 'P'))\n return sum((abs(c + D.get(x, 0) - p) > abs(c - p) for (c, x) in coords))", "from math import hypot\nmoves = {'\u2196': (-1, -1), '\u2190': (-1, 0), '\u2199': (-1, 1), '\u2191': (0, -1), '\u2193': (0, 1), '\u2197': (1, -1), '\u2192': (1, 0), '\u2198': (1, 1)}\n\ndef count_deaf_rats(town_square):\n (deaf, (px, py)) = (0, next(((row.index('P'), y) for (y, row) in enumerate(town_square) if 'P' in row)))\n dist = lambda x, y: hypot(px - x, py - y)\n for (y, row) in enumerate(town_square):\n for (x, c) in enumerate(row):\n if c in moves:\n (mx, my) = moves[c]\n if dist(x, y) < dist(x + mx, y + my):\n deaf += 1\n return deaf", "import math\nDirection = {'\u2190': lambda position: Position(position.x - 1, position.y), '\u2191': lambda position: Position(position.x, position.y - 1), '\u2192': lambda position: Position(position.x + 1, position.y), '\u2193': lambda position: Position(position.x, position.y + 1), '\u2196': lambda position: Position(position.x - 1, position.y - 1), '\u2197': lambda position: Position(position.x + 1, position.y - 1), '\u2198': lambda position: Position(position.x + 1, position.y + 1), '\u2199': lambda position: Position(position.x - 1, position.y + 1)}\nPIEP_PIPER = 'P'\n\ndef count_deaf_rats(town_square):\n rats = []\n piper = None\n for (y, line) in enumerate(town_square):\n for (x, cell) in enumerate(line):\n if cell in Direction:\n rats.append(Rat(Position(x, y), Direction[cell]))\n elif cell == PIEP_PIPER:\n piper = Position(x, y)\n return len([rat for rat in rats if rat.is_deaf(piper)])\n\ndef __init__(x, y):\n self.x = x\n self.y = y\n\ndef distance(other):\n return math.hypot(self.x - other.x, self.y - other.y)\n\ndef __init__(position, move):\n self.position = position\n self.move = move\n\ndef is_deaf(piper):\n current_distance = piper.distance(self.position)\n distance_after_one_step = piper.distance(self.move(self.position))\n return current_distance - distance_after_one_step < 0", "def count_deaf_rats(board):\n (o, p) = next(([i, j] for (i, l) in enumerate(board) for (j, k) in enumerate(l) if board[i][j] == 'P'))\n distance = lambda x, y: ((o - x) ** 2 + (p - y) ** 2) ** 0.5\n d = {'\u2190': (0, -1), '\u2191': (-1, 0), '\u2192': (0, 1), '\u2193': (1, 0), '\u2196': (-1, -1), '\u2197': (-1, 1), '\u2198': (1, 1), '\u2199': (1, -1)}\n return sum((distance(i + d[l][0], k + d[l][1]) > distance(i, k) for (i, j) in enumerate(board) for (k, l) in enumerate(j) if l in '\u2190\u2191\u2192\u2193\u2196\u2197\u2198\u2199'))", "deltas = dict(zip('\u2190\u2191\u2192\u2193\u2196\u2197\u2198\u2199', (-1, -1j, 1, 1j, -1 - 1j, 1 - 1j, 1 + 1j, -1 + 1j)))\n\ndef count_deaf_rats(town_square):\n (ii, jj) = (list(range(len(town_square[0]))), list(range(len(town_square))))\n p = next((complex(i, j) for i in ii for j in jj if town_square[j][i] == 'P'))\n return sum((abs(ij + d - p) > abs(ij - p) for (ij, d) in ((complex(i, j), deltas.get(town_square[j][i], 0)) for j in jj for i in ii)))", "rat_dirs = {'\u2190': (-1, 0), '\u2191': (0, -1), '\u2192': (1, 0), '\u2193': (0, 1), '\u2196': (-1, -1), '\u2197': (1, -1), '\u2198': (1, 1), '\u2199': (-1, 1)}\n\ndef find_piper(town_square, width, height):\n for y in range(height):\n for x in range(width):\n if town_square[y][x] == 'P':\n return (x, y)\n return (-1, -1)\n\ndef is_rat_deaf(rx, ry, px, py, c):\n (dx, dy) = (px - rx, py - ry)\n (cx, cy) = rat_dirs[c]\n return cx * dx + cy * dy <= 0\n\ndef count_deaf_rats(town_square):\n (width, height) = (len(town_square[0]), len(town_square))\n (px, py) = find_piper(town_square, width, height)\n num_deaf = 0\n for y in range(height):\n for x in range(width):\n c = town_square[y][x]\n if c in rat_dirs and is_rat_deaf(x, y, px, py, c):\n num_deaf += 1\n return num_deaf", "def count_deaf_rats(a):\n d = [(i, j) for i in range(-1, 2) for j in range(-1, 2) if i or j]\n d = {x: d[i] for (i, x) in enumerate('\u2196\u2191\u2197\u2190\u2192\u2199\u2193\u2198')}\n (p, r) = (divmod(''.join(a).index('P'), len(a[0])), 0)\n for (i, x) in enumerate(a):\n for (j, y) in enumerate(x):\n if y not in ' P':\n z = d[y]\n n = abs(i - p[0] + (j - p[1]) * 1j)\n m = abs(i + z[0] - p[0] + (j + z[1] - p[1]) * 1j)\n if n < m:\n r += 1\n return r"], "starter_code": "def count_deaf_rats(town_square):\n", "input_output": {"fn_name": "count_deaf_rats", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5c1448e08a2d87eda400005f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "count_deaf_rats", "task_id": "TACO_lite/291", "example": [[["\u2197P \u2198 \u2196 \u2191 \u2197"], ["\u2197 P \u2193 \u2196 \u2191 \u2190 \u2193 \u2196 \u2199 \u2199 \u2193 \u2193 \u2193"]], [2, 9]]} +{"requirement": "Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.\n\u00a0\n\nExample 1:\nInput: A = [4,5,0,-2,-3,1], K = 5\nOutput: 7\nExplanation: There are 7 subarrays with a sum divisible by K = 5:\n[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]\n\n\u00a0\nNote:\n\n1 <= A.length <= 30000\n-10000 <= A[i] <= 10000\n2 <= K <= 10000", "solutions": ["def subarraysdivbyk(A, K):\n res = 0\n prefix = 0\n count = [1] + [0] * K\n for a in A:\n prefix = (prefix + a) % K\n res += count[prefix]\n count[prefix] += 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n B = [a % K for a in A]\n sum_dict = {}\n ans = 0\n curr_sum = 0\n sum_dict[0] = 1\n n = len(B)\n for (i, num) in enumerate(B):\n curr_sum = (curr_sum + num) % K\n if curr_sum in sum_dict:\n ans += sum_dict[curr_sum]\n sum_dict[curr_sum] = sum_dict.get(curr_sum, 0) + 1\n return ans", "def subarraysdivbyk(A: List[int], K: int) -> int:\n countPrefs = {0: 1}\n total = 0\n res = 0\n for (i, num) in enumerate(A):\n total += num\n res += countPrefs.get(total % K, 0)\n if total % K in countPrefs:\n countPrefs[total % K] += 1\n else:\n countPrefs[total % K] = 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n (res, n, cache, sv) = (0, len(A), collections.defaultdict(int), 0)\n cache[0] = 1\n for (i, v) in enumerate(A):\n sv += v\n if cache[sv % K] > 0:\n res += cache[sv % K]\n cache[sv % K] += 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n n = len(A)\n pre = 0\n res = 0\n d = {0: 1}\n for a in A:\n pre = (pre + a) % K\n res += d.get(pre, 0)\n d[pre] = d.get(pre, 0) + 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n mod_count = Counter({0: 1})\n ans = 0\n for s in [*accumulate(A)]:\n m = s % K\n if m in mod_count:\n ans += mod_count[m]\n mod_count[m] += 1\n return ans", "def subarraysdivbyk(A: List[int], K: int) -> int:\n res = 0\n currsum = 0\n d = Counter()\n d[0] = 1\n for (i, num) in enumerate(A):\n currsum += num\n currsum %= K\n if currsum in d:\n res += d[currsum]\n d[currsum] += 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n res = 0\n cs = 0\n seen = collections.Counter({0: 1})\n for i in range(len(A)):\n x = A[i]\n cs += x\n if cs % K in seen:\n res += seen[cs % K]\n seen[cs % K] += 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n m = defaultdict(int)\n m[0] = 1\n curr_sum = 0\n result = 0\n for a in A:\n curr_sum += a\n remainder = curr_sum % K\n if remainder in m:\n result += m[remainder]\n m[remainder] += 1\n return result", "from collections import defaultdict\n\ndef subarraysdivbyk(A: List[int], K: int) -> int:\n if not A:\n return 0\n prefix_sums = defaultdict(int)\n prefix_sums[0] = 1\n cumsum = 0\n ans = 0\n for (i, x) in enumerate(A):\n cumsum = (cumsum + x) % K\n ans += prefix_sums[cumsum]\n prefix_sums[cumsum] += 1\n return ans", "def subarraysdivbyk(A, K):\n nums = A\n k = K\n modDict = {}\n tempSumn = 0\n ans = 0\n continousSum = []\n for num in nums:\n tempSumn += num\n continousSum.append(tempSumn)\n remain = tempSumn % k\n if remain not in modDict:\n modDict[remain] = 0\n modDict[remain] += 1\n diff = k\n for i in range(0, len(continousSum)):\n if diff % k in modDict:\n ans += modDict[diff % k]\n diff = continousSum[i]\n modDict[diff % k] -= 1\n return ans", "from collections import Counter\n\ndef subarraysdivbyk(A: List[int], K: int) -> int:\n seen = Counter()\n prefix = []\n curr_sum = 0\n for x in A:\n curr_sum += x\n prefix.append(curr_sum % K)\n ans = 0\n for ix in range(len(A)):\n remainder = K - prefix[ix]\n if prefix[ix] in seen:\n ans += seen[prefix[ix]]\n if prefix[ix] == 0:\n ans += 1\n seen[prefix[ix]] += 1\n return ans", "def subarraysdivbyk(A: List[int], K: int) -> int:\n n = len(A)\n A[0] = A[0] % K\n seen = {0: 1}\n count = 0\n for i in range(1, n):\n A[i] = (A[i] + A[i - 1]) % K\n for i in range(n):\n newTarget = (A[i] - K) % K\n if newTarget in seen:\n count += seen[newTarget]\n if A[i] in seen:\n seen[A[i]] += 1\n else:\n seen[A[i]] = 1\n return count", "def subarraysdivbyk(A: List[int], K: int) -> int:\n cnt = Counter([0])\n (pref, ans) = (0, 0)\n for a in A:\n pref = (pref + a) % K\n ans += cnt[pref]\n cnt[pref] += 1\n return ans", "def subarraysdivbyk(A: List[int], K: int) -> int:\n prefix = [0] * len(A)\n prefix[0] = A[0] % K\n counter = Counter([prefix[0]])\n ans = 1 if prefix[0] == 0 else 0\n for i in range(1, len(A)):\n prefix[i] = (prefix[i - 1] + A[i]) % K\n target = prefix[i] - 0\n ans += counter[target]\n if target == 0:\n ans += 1\n counter[prefix[i]] += 1\n return ans", "def subarraysdivbyk(A: List[int], K: int) -> int:\n cumsum = 0\n complements = {0: 1}\n counts = 0\n for a in A:\n cumsum += a\n mods = cumsum % K\n counts += complements.get(mods, 0)\n complements[mods] = complements.get(mods, 0) + 1\n return counts", "def subarraysdivbyk(A: List[int], K: int) -> int:\n ht = [0] * K\n sum = 0\n for num in A:\n sum += num\n ht[sum % K] += 1\n results = ht[0]\n for c in ht:\n results += c * (c - 1) // 2\n return results", "def subarraysdivbyk(A: List[int], K: int) -> int:\n if not A or not K:\n return 0\n map = Counter()\n map[0] = 1\n sum = 0\n res = 0\n for num in A:\n sum += num\n sum %= K\n if sum < 0:\n sum += K\n if sum in map:\n res += map[sum]\n map[sum] += 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n n = len(A)\n prefix = [0] * (n + 1)\n for i in range(1, n + 1):\n prefix[i] = prefix[i - 1] + A[i - 1]\n for i in range(1, n + 1):\n prefix[i] = prefix[i] % K\n d = defaultdict(list)\n ans = 0\n for i in range(1, n + 1):\n if prefix[i] == 0:\n ans += 1\n if prefix[i] in d.keys():\n ans += len(d[prefix[i]])\n d[prefix[i]].append(i)\n return ans", "def subarraysdivbyk(A: List[int], K: int) -> int:\n count = [0] * K\n sum = 0\n for i in A:\n sum += i % K\n count[sum % K] += 1\n result = count[0]\n for j in count:\n result += j * (j - 1) / 2\n return int(result)", "def subarraysdivbyk(A: List[int], K: int) -> int:\n map = {}\n map[0] = 1\n (sum, count) = (0, 0)\n for n in A:\n sum = (sum + n) % K\n if sum not in list(map.keys()):\n map[sum] = 1\n else:\n count += map[sum]\n map[sum] += 1\n return count", "def subarraysdivbyk(A: List[int], K: int) -> int:\n ans = 0\n count = [1] + [0] * K\n prefix = 0\n for num in A:\n prefix = (prefix + num) % K\n ans += count[prefix]\n count[prefix] += 1\n return ans", "import collections\n\ndef subarraysdivbyk(A: List[int], K: int) -> int:\n counts = [0] * K\n total = 0\n for num in A:\n total += num\n counts[total % K] += 1\n result = counts[0]\n for count in counts:\n result += count * (count - 1) // 2\n return result", "def subarraysdivbyk(A: List[int], K: int) -> int:\n (D, s) = ({0: 1}, 0)\n for a in A:\n s = (s + a) % K\n if s in D:\n D[s] += 1\n else:\n D[s] = 1\n return sum((i * (i - 1) // 2 for i in list(D.values())))", "import collections\n\ndef subarraysdivbyk(A: List[int], K: int) -> int:\n rem_array = [0]\n for num in A:\n rem_array.append((num + rem_array[-1]) % K)\n counter = collections.Counter(rem_array)\n return sum((v * (v - 1) // 2 for v in counter.values()))", "from collections import defaultdict\n\ndef subarraysdivbyk(nums: List[int], k: int) -> int:\n count = 0\n mods = [0]\n modFreqs = defaultdict(lambda : 0)\n for num in nums:\n mod = (mods[-1] + num) % k\n if mod == 0:\n count += 1\n count += modFreqs[mod]\n mods.append(mod)\n modFreqs[mod] += 1\n return count", "def subarraysdivbyk(A: List[int], K: int) -> int:\n P = [0]\n for x in A:\n P.append((P[-1] + x) % K)\n count = collections.Counter(P)\n return int(sum((v * (v - 1) / 2 for v in count.values())))", "def subarraysdivbyk(A: List[int], K: int) -> int:\n hash_map = collections.defaultdict(int)\n hash_map[0] = 1\n prefix = 0\n res = 0\n for i in range(len(A)):\n num = A[i]\n prefix = (prefix + num) % K\n res += hash_map[prefix]\n hash_map[prefix] += 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n (arr, ans, curr) = ([1] + [0] * K, 0, 0)\n for i in A:\n curr = (curr + i) % K\n ans += arr[curr]\n arr[curr] += 1\n return ans", "from collections import defaultdict\nfrom operator import add\n\ndef accum(op, l):\n if not l:\n return []\n v = l[0]\n ret = [v]\n for x in l[1:]:\n v = op(v, x)\n ret.append(v)\n return ret\n\ndef subarraysdivbyk(A: List[int], K: int) -> int:\n B = accum(add, A)\n B = [0] + B\n B = [x % K for x in B]\n seen = defaultdict(lambda : 0)\n seen[0] = 1\n combinations = 0\n for s in B[1:]:\n target = s\n if seen[target] > 0:\n combinations += seen[target]\n seen[s] = seen[s] + 1\n return combinations", "def subarraysdivbyk(A: List[int], K: int) -> int:\n hashmap = [0] * K\n hashmap[0] = 1\n result = 0\n prefix = 0\n for i in range(len(A)):\n prefix = (prefix + A[i]) % K\n hashmap[prefix] += 1\n result += hashmap[prefix] - 1\n return result", "def subarraysdivbyk(A: List[int], K: int) -> int:\n dp = [1] + [0] * K\n result = 0\n running_sum = 0\n for num in A:\n running_sum += num\n result += dp[running_sum % K]\n dp[running_sum % K] += 1\n return result", "def subarraysdivbyk(A: List[int], K: int) -> int:\n res = 0\n sums = 0\n d = {0: 1}\n for num in A:\n sums = (sums + num) % K\n res += d.get(sums, 0)\n d[sums] = d.get(sums, 0) + 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n prefix = [0]\n for a in A:\n prefix += [(prefix[-1] + a) % K]\n cnt = collections.Counter(prefix)\n return int(sum((v * (v - 1) / 2 for v in list(cnt.values()))))", "from collections import defaultdict\n\ndef subarraysdivbyk(A: List[int], K: int) -> int:\n seen = defaultdict(int, {0: 1})\n ret = psum = 0\n for n in A:\n psum = (psum + n) % K\n if psum in seen:\n ret += seen[psum]\n seen[psum] += 1\n return ret", "from collections import Counter\n\ndef subarraysdivbyk(A: List[int], K: int) -> int:\n presum = [0]\n for num in A:\n presum.append((presum[-1] + num) % K)\n count = Counter(presum)\n return sum((c * (c - 1) // 2 for c in list(count.values())))", "def subarraysdivbyk(A: List[int], K: int) -> int:\n hm = {}\n hm[0] = 1\n prefix = 0\n count = 0\n for i in range(0, len(A)):\n prefix = (A[i] + prefix) % K\n if prefix in hm:\n count += hm[prefix]\n else:\n hm[prefix] = 0\n hm[prefix] += 1\n return count", "def subarraysdivbyk(A: List[int], K: int) -> int:\n n = len(A)\n prefixsum = 0\n remain = collections.defaultdict(int)\n remain[0] = 1\n res = 0\n for i in range(n):\n prefixsum += A[i]\n re = prefixsum % K\n res += remain[re]\n remain[re] += 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n res = 0\n lookup = {0: 1}\n presum = 0\n for (i, num) in enumerate(A):\n presum += num\n remainder = presum % K\n res += lookup.get(remainder, 0)\n lookup[remainder] = lookup.get(remainder, 0) + 1\n return res", "def subarraysdivbyk(A: List[int], K: int) -> int:\n P = [0]\n for x in A:\n P.append((P[-1] + x) % K)\n count = collections.Counter(P)\n ans = 0\n for v in list(count.values()):\n ans += int(v * (v - 1) * 0.5)\n return ans", "def subarraysdivbyk(A: List[int], K: int) -> int:\n preSum = [0]\n for num in A:\n preSum.append((preSum[-1] + num) % K)\n preSumCounter = Counter(preSum)\n return sum((v * (v - 1) // 2 for v in preSumCounter.values()))", "def subarraysdivbyk(A: List[int], K: int) -> int:\n d = {0: 1}\n runningSum = 0\n sol = 0\n for i in range(len(A)):\n runningSum += A[i]\n newMod = runningSum % K\n if newMod not in d:\n d[newMod] = 0\n d[newMod] += 1\n sol += d[newMod] - 1\n return sol", "def subarraysdivbyk(A: List[int], K: int) -> int:\n prefixMod = 0\n hashTable = collections.defaultdict(int)\n total = 0\n curSum = 0\n hashTable[0] = 1\n for (i, x) in enumerate(A):\n prefixMod = prefixMod + x\n prefixMod = prefixMod % K\n total += hashTable[prefixMod]\n hashTable[prefixMod] += 1\n return total"], "starter_code": "def subarraysdivbyk(A: List[int], K: int) -> int:\n", "input_output": {"fn_name": "subarraysDivByK", "inputs": [[[4, 5, 0, -2, -3, 1], 5]], "outputs": [7]}, "difficulty": "MEDIUM", "raw_tags": ["Prefix Sum", "Array", "Hash Table"], "name": null, "source": "leetcode", "tags": ["Data structures", "Range queries"], "skill_types": ["Data structures", "Range queries"], "url": "https://leetcode.com/problems/subarray-sums-divisible-by-k/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "subarraysdivbyk", "task_id": "TACO_lite/337", "example": [[[[4, 5, 0, -2, -3, 1], 5]], ["7"]]} +{"requirement": "You get some nested lists. Keeping the original structures, sort only elements (integers) inside of the lists. In other words, sorting the intergers only by swapping their positions. \n\n\n\n```\nExample\nInput : [[[2, 1], [4, 3]], [[6, 5], [8, 7]]]\nOutput : [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]\n```\n\nNote:\nThe structures of the lists are regular (symmetrical) and their depths are 3.", "solutions": ["def sort_nested_list(xsss):\n ys = iter(sorted((x for xss in xsss for xs in xss for x in xs)))\n return [[[next(ys) for x in xs] for xs in xss] for xss in xsss]", "import numpy as np\n\ndef sort_nested_list(A):\n return np.sort(A, axis=None).reshape(np.array(A).shape).tolist()", "def sort_nested_list(array):\n numbers = iter(sorted((n for a1 in array for a2 in a1 for n in a2)))\n return [[[next(numbers) for n in a2] for a2 in a1] for a1 in array]", "def sort_nested_list(A):\n numbers = []\n\n def peel(A, insert=False):\n for i in range(len(A)):\n if len(A[i]) != 0 and isinstance(A[i][0], list):\n A[i] = peel(A[i], insert)\n elif insert:\n A[i] = numbers[:len(A[i])]\n del numbers[:len(A[i])]\n else:\n numbers.extend(A[i])\n return A\n peel(A)\n numbers = sorted(numbers)\n return peel(A, insert=True)", "import re\n\ndef sort_nested_list(arr):\n s = str(arr)\n ns = sorted(re.findall('\\\\d+', s), key=int, reverse=True)\n return eval(re.sub('\\\\d+', lambda _: ns.pop(), s))", "def sort_nested_list(A, emol=''):\n for e in str(A):\n if e.isdigit() and emol[-1] is '}':\n continue\n emol += [e, '{}'][e.isdigit()]\n return eval(emol.format(*sorted([i for l in A for e in l for i in e])))", "def fl(l):\n for x in l:\n if isinstance(x, list):\n for j in fl(x):\n yield j\n else:\n yield x\n\ndef sort_nested_list(a):\n numbers = iter(sorted(fl(a)))\n\n def b(n, a):\n return [next(n) if isinstance(c, int) else b(n, c) for c in a]\n return b(numbers, a)", "from copy import deepcopy\n\ndef sort_nested_list(a):\n\n def seeker(lst):\n return lst if not lst or not isinstance(lst[0], list) else sum(map(seeker, lst), [])\n\n def putter(lst):\n for i in range(len(lst)):\n if isinstance(lst[i], list):\n putter(lst[i])\n else:\n lst[i] = next(elts)\n (a, elts) = (deepcopy(a), iter(sorted(seeker(a))))\n putter(a)\n return a", "import re\n\ndef sort_nested_list(A):\n a = str(A)\n (b, a) = (a, re.sub('\\\\[|\\\\]', '', a))\n B = str(sorted(eval('[' + a + ']')))\n (b, nl) = (list(re.sub('\\\\d+', '#', b)), re.findall('\\\\d+', B)[::-1])\n for i in range(len(b)):\n b[i] = nl.pop() if b[i] == '#' else b[i]\n return eval(''.join(b))", "def sort_nested_list(A):\n sort_nested_list.numbers = []\n\n def collect_numbers(lista):\n if len(lista) == 0:\n return lista\n if len(lista) > 1:\n for i in lista:\n try:\n for e in i:\n for q in e:\n sort_nested_list.numbers.append(q)\n except:\n return sorted(lista)\n return lista\n else:\n return [collect_numbers(lista[0])]\n\n def place_numbers(lista):\n if len(lista) == 0:\n return lista\n if len(lista) > 1:\n for i in lista:\n try:\n for e in i:\n for (index, element) in enumerate(e):\n e[index] = sort_nested_list.numbers.pop(0)\n except:\n return sorted(lista)\n return lista\n else:\n return [place_numbers(lista[0])]\n collect_numbers(A)\n sort_nested_list.numbers.sort()\n return place_numbers(A)"], "starter_code": "def sort_nested_list(A):\n", "input_output": {"fn_name": "sort_nested_list", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Fundamentals", "Sorting"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Sorting"], "skill_types": ["Sorting"], "url": "https://www.codewars.com/kata/5a4bdd73d8e145f17d000035", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sort_nested_list", "task_id": "TACO_lite/322", "example": [[[[[[2, 1], [4, 3]], [[6, 5], [8, 7]]]]], ["[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]"]]} +{"requirement": "Given an unsorted array of integers. Find an element such that all the elements to its left are smaller and to its right are greater. Print -1 if no such element exists. Note that there can be more than one such element. In that case print the first such number occurring in the array.\nExample 1:\nInput: N = 7, arr[] = {4, 3, 2, 5, 8, 6, 7} \nOutput: 5\nExplanation: To the left of element 5 \nevery element is smaller to it and to \nthe right of element 5 every element \nis greater to it. \nExample 2:\nInput: N = 7, arr[] = {5, 6, 2, 8, 10, 9, 8} \nOutput: -1\nExplanation: No such desired element is \npresent in the array.\nYour Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function FindElement() that takes array arr and integer N as parameters and returns the desired output.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 \u2264 N \u2264 10^{6}", "solutions": ["def findelement(arr, N):\n c = 0\n for i in range(N):\n c = 0\n for j in range(N):\n if j < i:\n if arr[j] >= arr[i]:\n c = 1\n break\n elif j == i:\n pass\n elif j > i:\n if arr[j] <= arr[i]:\n c = 1\n break\n if c == 0:\n return arr[i]\n break\n return -1", "def findelement(arr, N):\n max_ele = arr[0]\n li = [max_ele]\n for i in range(1, N):\n if max_ele >= arr[i]:\n if len(li) > 0:\n if li[0] >= arr[i]:\n li.clear()\n else:\n max_ele = arr[i]\n li.append(arr[i])\n return li[0] if len(li) > 0 else -1", "def findelement(arr, N):\n small_right = [0] * n\n big_left = [0] * n\n big_left[0] = arr[0]\n small_right[n - 1] = arr[n - 1]\n for i in range(1, n):\n if big_left[i - 1] < arr[i]:\n big_left[i] = arr[i]\n else:\n big_left[i] = big_left[i - 1]\n for i in range(n - 2, -1, -1):\n if small_right[i + 1] > arr[i]:\n small_right[i] = arr[i]\n else:\n small_right[i] = small_right[i + 1]\n for i in range(0, N, 1):\n if i == 0 and arr[i] < small_right[i + 1] or (i == N - 1 and arr[i] > big_left[i - 1]) or (arr[i] > big_left[i - 1] and arr[i] < small_right[i + 1]):\n return arr[i]\n break\n return -1", "def findelement(arr, N):\n A = arr\n n = N\n SE = [0] * n\n GE = [0] * n\n GE[0] = A[0]\n SE[n - 1] = A[n - 1]\n for i in range(1, n):\n if GE[i - 1] < A[i]:\n GE[i] = A[i]\n else:\n GE[i] = GE[i - 1]\n for i in range(n - 2, -1, -1):\n if A[i] < SE[i + 1]:\n SE[i] = A[i]\n else:\n SE[i] = SE[i + 1]\n for j in range(n):\n try:\n if j == 0 and A[j] < SE[j + 1] or (j == n - 1 and A[j] > GE[j - 1]) or (A[j] < SE[j + 1] and A[j] > GE[j - 1]):\n return A[j]\n except:\n pass\n return -1", "def findelement(arr, N):\n maxi = [arr[0]]\n mini = [arr[-1]]\n for i in range(1, N):\n maxi.append(max(maxi[-1], arr[i]))\n mini.append(min(mini[-1], arr[-i - 1]))\n mini.reverse()\n if arr[0] < mini[1]:\n return arr[0]\n for i in range(1, N - 1):\n if maxi[i - 1] < arr[i] < mini[i + 1]:\n return arr[i]\n if arr[-1] > maxi[-2]:\n return arr[-1]\n return -1", "def findelement(arr, n):\n greather = [0] * n\n smaller = [0] * n\n greather[0] = arr[0]\n for i in range(1, n):\n greather[i] = max(greather[i - 1], arr[i])\n smaller[n - 1] = arr[n - 1]\n for i in range(n - 2, -1, -1):\n smaller[i] = min(smaller[i + 1], arr[i])\n if smaller[1] > arr[0]:\n return arr[0]\n for i in range(1, n - 1):\n if smaller[i + 1] > arr[i] and greather[i - 1] < arr[i]:\n return arr[i]\n if greather[n - 2] < arr[n - 1]:\n return arr[n - 1]\n return -1", "import sys\n\ndef findelement(arr, N):\n min_index = [0] * N\n max_index = [0] * N\n minimum = arr[N - 1]\n min_index[N - 1] = N - 1\n maximum = arr[0]\n max_index[0] = 0\n ans = -1\n for i in range(1, N):\n if arr[i] > maximum:\n max_index[i] = i\n maximum = arr[i]\n else:\n max_index[i] = max_index[i - 1]\n for i in range(N - 2, -1, -1):\n if arr[i] < minimum:\n minimum = arr[i]\n min_index[i] = i\n else:\n min_index[i] = min_index[i + 1]\n for i in range(N):\n if min_index[i] == max_index[i]:\n ans = arr[i]\n break\n return ans", "import sys\n\ndef findelement(arr, n):\n pre = [0] * n\n suf = [0] * n\n pre[0] = -sys.maxsize\n suf[n - 1] = sys.maxsize\n for i in range(1, n):\n pre[i] = max(pre[i - 1], arr[i - 1])\n for i in range(n - 2, -1, -1):\n suf[i] = min(suf[i + 1], arr[i + 1])\n for i in range(n):\n if pre[i] < arr[i] and arr[i] < suf[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n (mx, mi, cur_max) = ([0 for i in range(n)], [0 for i in range(n)], -1)\n for i in range(0, n):\n mx[i] = cur_max\n cur_max = max(cur_max, arr[i])\n cur_min = cur_max + 1\n for i in range(n - 1, -1, -1):\n mi[i] = cur_min\n cur_min = min(cur_min, arr[i])\n if arr[0] < mi[0]:\n return arr[0]\n for i in range(1, n - 1):\n if mx[i] < arr[i] < mi[i]:\n return arr[i]\n if arr[-1] > mx[-1]:\n return arr[-1]\n return -1", "def findelement(arr, n):\n for i in range(0, n):\n (left, right) = (1, 1)\n for j in range(0, i):\n if arr[j] >= arr[i]:\n left = 0\n break\n if left == 0:\n continue\n for j in range(i + 1, n):\n if arr[j] <= arr[i]:\n right = 0\n break\n if right == 1:\n return arr[i]\n return -1", "def findelement(arr, N):\n left = []\n right = []\n maximum = arr[0]\n for i in arr:\n maximum = max(i, maximum)\n left.append(maximum)\n minimum = arr[-1]\n for i in arr[::-1]:\n minimum = min(i, minimum)\n right.append(minimum)\n right = right[::-1]\n if arr[0] < right[1]:\n return arr[0]\n ans = -1\n for i in range(1, N - 1):\n if arr[i] > left[i - 1] and arr[i] < right[i + 1]:\n ans = arr[i]\n break\n if ans != -1:\n return ans\n if left[-2] < arr[-1]:\n return arr[-1]\n return -1", "def findelement(arr, N):\n ge = [0] * N\n se = [0] * N\n ge[0] = arr[0]\n se[N - 1] = arr[N - 1]\n for i in range(1, N):\n if arr[i] > ge[i - 1]:\n ge[i] = arr[i]\n else:\n ge[i] = ge[i - 1]\n for i in range(N - 2, -1, -1):\n if arr[i] < se[i + 1]:\n se[i] = arr[i]\n else:\n se[i] = se[i + 1]\n for i in range(N):\n if i == 0 and se[i + 1] > arr[i]:\n return arr[i]\n elif i == N - 1 and arr[N - 1] > ge[i - 1]:\n return arr[i]\n elif arr[i] > ge[i - 1] and arr[i] < se[i + 1]:\n return arr[i]\n return -1", "def findelement(arr, N):\n mx = arr[N - 1] + 1\n amx = [0] * N\n mn = arr[0] - 1\n amn = [0] * N\n if arr[0] >= arr[N - 1]:\n return -1\n for i in range(N):\n amx[N - 1 - i] = mx\n if mx > arr[N - 1 - i]:\n mx = arr[N - 1 - i]\n amn[i] = mn\n if mn < arr[i]:\n mn = arr[i]\n for i in range(N):\n if amx[i] > arr[i] and arr[i] > amn[i]:\n return arr[i]\n return -1", "def findelement(arr, N):\n prefix = [-1000000000]\n suffix = [10000000 for i in range(N)]\n for i in range(1, N):\n prefix.append(max(prefix[i - 1], arr[i - 1]))\n for i in range(N - 2, -1, -1):\n suffix[i] = min(suffix[i + 1], arr[i + 1])\n for i in range(0, N):\n if prefix[i] < arr[i] and arr[i] < suffix[i]:\n return arr[i]\n return -1", "def findelement(arr, N):\n GE = [0] * N\n SE = [0] * N\n GE[0] = arr[0]\n SE[N - 1] = arr[N - 1]\n for i in range(1, N):\n if arr[i] < GE[i - 1]:\n GE[i] = GE[i - 1]\n else:\n GE[i] = arr[i]\n for i in range(N - 2, -1, -1):\n if arr[i] > SE[i + 1]:\n SE[i] = SE[i + 1]\n else:\n SE[i] = arr[i]\n for j in range(N):\n k = arr[j]\n if j == 0:\n if arr[j] < SE[j + 1]:\n return k\n elif j == N - 1:\n if arr[j] > GE[j - 1]:\n return k\n elif arr[j] < SE[j + 1] and arr[j] > GE[j - 1]:\n return k\n return -1", "def findelement(arr, N):\n maxLeft = []\n minRight = []\n for i in range(N):\n if not maxLeft:\n maxLeft.append(arr[i])\n minRight.append(arr[N - i - 1])\n else:\n maxLeft.append(max(maxLeft[-1], arr[i]))\n minRight.append(min(minRight[-1], arr[N - i - 1]))\n for i in range(N):\n if i == 0:\n if arr[i] < minRight[N - i - 2]:\n return arr[i]\n elif i == N - 1:\n if arr[i] > maxLeft[i - 1]:\n return arr[i]\n elif maxLeft[i - 1] < arr[i] and arr[i] < minRight[N - i - 2]:\n return arr[i]\n return -1", "def findelement(arr, N):\n n = N\n GEL = [0] * n\n SER = [0] * n\n GEL[0] = arr[0]\n SER[n - 1] = arr[n - 1]\n for i in range(1, n):\n if arr[i] > GEL[i - 1]:\n GEL[i] = arr[i]\n else:\n GEL[i] = GEL[i - 1]\n for i in range(n - 2, -1, -1):\n if SER[i + 1] > arr[i]:\n SER[i] = arr[i]\n else:\n SER[i] = SER[i + 1]\n for i in range(0, n - 1):\n if i == 0 and arr[i] < SER[i + 1] or (arr[i] < SER[i + 1] and arr[i] > GEL[i - 1]):\n return arr[i]\n if arr[n - 1] > GEL[n - 2]:\n return arr[n - 1]\n else:\n return -1"], "starter_code": "def findelement(arr, N):\n", "input_output": {"inputs": ["N = 7, arr[] = {4, 3, 2, 5, 8, 6, 7}", "N = 7, arr[] = {5, 6, 2, 8, 10, 9, 8}"], "outputs": ["5", "-1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/partition-point-in-the-array0004/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "findelement", "task_id": "TACO_lite/330", "example": [[[7, [4, 3, 2, 5, 8, 6, 7]], [7, [5, 6, 2, 8, 10, 9, 8]]], [null, null]]} +{"requirement": "Given a matrix M of n*n size, the task is to complete the function which prints its elements in a diagonal pattern as depicted below.\n \n \nExample 1:\nInput:\nN = 3\nmat[][] = {{1 2 3},{4 5 6},{7 8 9}}\nOutput: 1 2 4 7 5 3 6 8 9\nExample 2:\nInput:\nN = 2\nmat[][] = {{1 2},{3 4}}\nOutput: 1 2 3 4\nYour Task:\nYou only need to implement the given function matrixDiagonally() which returns a list containing the matrix diagonally. Do not read input, instead use the arguments given in the function. Print the elements in Matrix in a diagonal pattern.\nExpected Time Complexity: O(N*M)\nExpected Auxiliary Space: O(1)\nConstraints:\n1<=N<=100", "solutions": ["def matrixdiagonally(mat):\n n = len(mat)\n m = len(mat[0])\n list = [[] for i in range(n + m - 1)]\n for i in range(n):\n for j in range(m):\n sum = i + j\n if sum % 2 == 0:\n list[sum].insert(0, mat[i][j])\n else:\n list[sum].append(mat[i][j])\n res = []\n for i in list:\n for j in i:\n res.append(j)\n return res", "def matrixdiagonally(mat):\n n = len(mat)\n total = n * n - 1\n count = 0\n arr = []\n di = {'up': 'down', 'down': 'up'}\n cdi = 'up'\n i = j = 0\n while count <= total:\n if cdi == 'up':\n if i == 0 and j != n - 1:\n arr.append(mat[i][j])\n cdi = di['up']\n j += 1\n elif j == n - 1:\n arr.append(mat[i][j])\n cdi = di['up']\n i += 1\n else:\n arr.append(mat[i][j])\n i -= 1\n j += 1\n elif j == 0 and i != n - 1:\n arr.append(mat[i][j])\n cdi = di['down']\n i += 1\n elif i == n - 1:\n arr.append(mat[i][j])\n cdi = di['down']\n j += 1\n else:\n arr.append(mat[i][j])\n i += 1\n j -= 1\n count += 1\n return arr", "def matrixdiagonally(mat):\n rev = True\n i = j = 0\n n = len(mat)\n res = []\n while i >= 0 and i < n and (j >= 0) and (j < n):\n if rev:\n (pi, pj) = (i, j)\n while i >= 0 and i < n and (j >= 0) and (j < n):\n res.append(mat[i][j])\n (pi, pj) = (i, j)\n i -= 1\n j += 1\n (i, j) = (pi, pj)\n if j == n - 1:\n i += 1\n else:\n j += 1\n else:\n (pi, pj) = (i, j)\n while i >= 0 and i < n and (j >= 0) and (j < n):\n res.append(mat[i][j])\n (pi, pj) = (i, j)\n i += 1\n j -= 1\n (i, j) = (pi, pj)\n if i == n - 1:\n j += 1\n else:\n i += 1\n rev = not rev\n return res", "def matrixdiagonally(mat):\n dic = {i: [] for i in range(len(mat) * len(mat) + 1)}\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n dic[i + j].append(mat[i][j])\n ans = []\n for i in range(len(mat) * len(mat) + 1):\n if i % 2 == 0:\n ans += dic[i][::-1]\n else:\n ans += dic[i]\n return ans", "def matrixdiagonally(mat):\n m = len(mat)\n n = len(mat[0])\n ll = []\n cnt = 1\n for i in range(n):\n x = 0\n y = i\n l = []\n while (x >= 0 and y >= 0) and (x < m and y < n):\n l.append(mat[x][y])\n x += 1\n y -= 1\n if cnt % 2 == 0:\n ll += l\n else:\n ll += l[::-1]\n cnt += 1\n for i in range(1, m):\n x = i\n y = n - 1\n l = []\n while (x >= 0 and y >= 0) and (x < m and y < n):\n l.append(mat[x][y])\n x += 1\n y -= 1\n if cnt % 2 == 0:\n ll += l\n else:\n ll += l[::-1]\n cnt += 1\n return ll", "def matrixdiagonally(mat):\n N = len(mat)\n ls = []\n d_up = True\n r = 0\n c = 0\n while r < N and c < N:\n if d_up:\n while r > 0 and c < N - 1:\n ls.append(mat[r][c])\n r -= 1\n c += 1\n ls.append(mat[r][c])\n if c == N - 1:\n r += 1\n else:\n c += 1\n else:\n while c > 0 and r < N - 1:\n ls.append(mat[r][c])\n c -= 1\n r += 1\n ls.append(mat[r][c])\n if r == N - 1:\n c += 1\n else:\n r += 1\n d_up = not d_up\n return ls", "def matrixdiagonally(mat):\n n = len(mat)\n m = []\n i = 0\n j = 0\n k = 0\n isUp = True\n while k < n * n:\n if isUp:\n while i >= 0 and j < n:\n m.append(mat[i][j])\n k += 1\n j += 1\n i -= 1\n if i < 0 and j <= n - 1:\n i = 0\n if j == n:\n i = i + 2\n j -= 1\n else:\n while j >= 0 and i < n:\n m.append(mat[i][j])\n k += 1\n i += 1\n j -= 1\n if j < 0 and i <= n - 1:\n j = 0\n if i == n:\n j = j + 2\n i -= 1\n isUp = not isUp\n return m", "def matrixdiagonally(mat):\n t = []\n N = len(mat)\n A = mat\n for i in range(N):\n row = 0\n col = i\n while row < N and col >= 0:\n if (row + col) % 2 != 0:\n t.append(A[row][col])\n else:\n t.append(A[col][row])\n row += 1\n col -= 1\n for j in range(1, N):\n row = j\n col = N - 1\n while row < N and col >= 0:\n if (row + col) % 2 != 0:\n t.append(A[row][col])\n else:\n t.append(A[col][row])\n row += 1\n col -= 1\n return t", "def matrixdiagonally(mat):\n output = []\n n = len(mat)\n for i in range(n):\n items = []\n for j in range(i + 1):\n items.append(mat[j][i - j])\n if i % 2:\n output += items\n else:\n output += items[::-1]\n for i in range(1, n):\n items = []\n for j in range(i, n):\n items.append(mat[j][n - j + i - 1])\n if (n + i) % 2:\n output += items[::-1]\n else:\n output += items\n return output", "from collections import defaultdict\n\ndef matrixdiagonally(mat):\n d = defaultdict(list)\n visited = set()\n q = [((0, 0), 0)]\n n = len(mat)\n while q:\n (node, lvl) = q.pop(0)\n (i, j) = node\n d[lvl].append(mat[i][j])\n if i + 1 < n and (i + 1, j) not in visited:\n visited.add((i + 1, j))\n q.append(((i + 1, j), lvl + 1))\n if j + 1 < n and (i, j + 1) not in visited:\n visited.add((i, j + 1))\n q.append(((i, j + 1), lvl + 1))\n x = []\n for i in range(len(d)):\n p = d[i]\n if i % 2 == 1:\n p = p[::-1]\n for j in p:\n x.append(j)\n return x", "def matrixdiagonally(mat):\n if len(mat) == 0:\n return []\n m = len(mat)\n n = len(mat[0])\n row = 0\n col = 0\n res = []\n isUp = True\n while row < m and col < n:\n if isUp:\n while row > 0 and col < n - 1:\n res.append(mat[row][col])\n row -= 1\n col += 1\n res.append(mat[row][col])\n if col == n - 1:\n row += 1\n else:\n col += 1\n else:\n while row < m - 1 and col > 0:\n res.append(mat[row][col])\n row += 1\n col -= 1\n res.append(mat[row][col])\n if row == m - 1:\n col += 1\n else:\n row += 1\n isUp = not isUp\n return res", "def matrixdiagonally(mat):\n r = c = len(mat)\n res = [[] for i in range(c + r - 1)]\n for i in range(r):\n for j in range(c):\n s = i + j\n if s % 2 == 0:\n res[s].insert(0, mat[i][j])\n else:\n res[s].append(mat[i][j])\n return sum(res, [])", "def matrixdiagonally(mat):\n m = len(mat)\n n = len(mat[0])\n k = 0\n retarray = []\n boolval = True\n for i in range(n):\n l = i\n if not boolval:\n while k <= i:\n retarray.append(mat[k][l])\n k += 1\n l -= 1\n k = 0\n boolval = not boolval\n else:\n while k <= i:\n retarray.append(mat[l][k])\n k += 1\n l -= 1\n k = 0\n boolval = not boolval\n k = n - 1\n for i in range(1, n):\n l = i\n if boolval:\n while l < n:\n retarray.append(mat[k][l])\n k -= 1\n l += 1\n k = n - 1\n boolval = not boolval\n else:\n while l < n:\n retarray.append(mat[l][k])\n k -= 1\n l += 1\n k = n - 1\n boolval = not boolval\n return retarray", "def matrixdiagonally(mat):\n rows = colm = len(mat)\n ans = [[] for i in range(rows + colm - 1)]\n for i in range(rows):\n for j in range(colm):\n ij = i + j\n if ij & 1 != 1:\n ans[ij].insert(0, mat[i][j])\n else:\n ans[ij].append(mat[i][j])\n return sum(ans, [])", "def matrixdiagonally(li):\n n = len(li)\n ans = [[] for i in range(n + n - 1)]\n j = 0\n for i in range(n):\n x = i\n y = j\n while x >= 0 and y < n:\n ans[i + j].append(li[x][y])\n x -= 1\n y += 1\n j = n - 1\n for i in range(1, n):\n x = i\n y = j\n while x < n and y >= 0:\n ans[i + j].append(li[y][x])\n x += 1\n y -= 1\n output = []\n for i in range(len(ans)):\n if i % 2 != 0:\n for j in range(len(ans[i]) - 1, -1, -1):\n output.append(ans[i][j])\n else:\n for j in range(len(ans[i])):\n output.append(ans[i][j])\n return output", "def matrixdiagonally(mat):\n (r, c) = (0, 0)\n isUp = True\n count = 0\n n = len(mat)\n ans = []\n while count < n * n:\n if isUp:\n while r >= 0 and c < n:\n ans.append(mat[r][c])\n r -= 1\n c += 1\n count += 1\n if r < 0 and c < n:\n r = 0\n if c == n:\n r += 2\n c -= 1\n else:\n while c >= 0 and r < n:\n ans.append(mat[r][c])\n r += 1\n c -= 1\n count += 1\n if c < 0 and r < n:\n c = 0\n if r == n:\n c += 2\n r -= 1\n isUp = not isUp\n return ans", "def matrixdiagonally(mat):\n n = len(matrix)\n mode = 0\n it = 0\n lower = 0\n temp = []\n for t in range(2 * n - 1):\n t_ = t\n if t_ >= n:\n mode += 1\n t_ = n - 1\n it -= 1\n lower += 1\n else:\n lower = 0\n it += 1\n for i in range(t_, lower - 1, -1):\n this = t_ + lower - i\n if (t_ + mode) % 2 == 0:\n temp.append(matrix[i][this])\n else:\n temp.append(matrix[this][i])\n return temp", "def matrixdiagonally(mat):\n n = len(mat)\n k = 0\n i = 0\n j = 0\n flag = True\n result = []\n while k < n * n:\n if flag:\n while i >= 0 and j < n:\n result.append(mat[i][j])\n i -= 1\n j += 1\n k += 1\n if i < 0 and j <= n - 1:\n i = 0\n if j == n:\n i += 2\n j -= 1\n else:\n while j >= 0 and i < n:\n result.append(mat[i][j])\n j -= 1\n i += 1\n k += 1\n if j < 0 and i <= n - 1:\n j = 0\n if i == n:\n j += 2\n i -= 1\n flag = not flag\n return result", "def matrixdiagonally(mat):\n (row, column) = (len(mat), len(mat[0]))\n arr = []\n for i in range(row):\n diag = []\n a = i\n j = 0\n while a >= 0 and j < column:\n diag.append(mat[a][j])\n a -= 1\n j += 1\n arr.append(diag)\n for j in range(1, column):\n diag = []\n a = j\n i = row - 1\n while a < column and i >= 0:\n diag.append(mat[i][a])\n i -= 1\n a += 1\n arr.append(diag)\n for i in range(1, len(arr), 2):\n arr[i] = arr[i][::-1]\n return [x for y in arr for x in y]", "def matrixdiagonally(mat):\n l = []\n n = len(mat)\n c = 1\n for i in range(n):\n k = i\n j = 0\n g = []\n while k >= 0:\n g.append(mat[j][k])\n k -= 1\n j += 1\n if c == 0:\n l.extend(g)\n else:\n l.extend(g[::-1])\n c = c ^ 1\n for i in range(1, n):\n k = i\n j = n - 1\n g = []\n while k < n:\n g.append(mat[k][j])\n k += 1\n j -= 1\n if c == 0:\n l.extend(g)\n else:\n l.extend(g[::-1])\n c = c ^ 1\n return l", "def level_range(a, b, arr):\n ans = []\n for i in range(b - a + 1):\n ans.append(arr[a + i][b - i])\n return ans\n\ndef get_range(n):\n initials = []\n for i in range(n):\n initials.append((0, i))\n for i in range(1, n):\n initials.append((i, n - 1))\n return initials\n\ndef matrixdiagonally(mat):\n initials = get_range(len(mat))\n ans = []\n lvl = 0\n for i in initials:\n (a, b) = i\n temp = level_range(a, b, mat)\n if lvl % 2 == 0:\n ans += temp[::-1]\n else:\n ans += temp\n lvl += 1\n return ans", "def matrixdiagonally(mat):\n dic = {}\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n t = i + j\n if t not in dic:\n dic[t] = []\n dic[t].append(mat[i][j])\n res = []\n for k in dic:\n if k % 2 == 0:\n res.extend(dic[k][::-1])\n else:\n res.extend(dic[k])\n return res", "def matrixdiagonally(mat):\n mp = dict()\n n = len(mat)\n for i in range(n):\n for j in range(n):\n if i + j in mp:\n mp[i + j].append(mat[i][j])\n else:\n mp[i + j] = [mat[i][j]]\n lst = []\n for (k, v) in mp.items():\n if k % 2 == 0:\n v.reverse()\n lst = lst + v\n else:\n lst = lst + v\n return lst", "def matrixdiagonally(mat):\n n = len(mat)\n s = [[] for i in range(2 * n - 1)]\n for i in range(n):\n for j in range(n):\n m = i + j\n if m % 2 == 1:\n s[m].append(mat[i][j])\n else:\n s[m].insert(0, mat[i][j])\n l = []\n for i in s:\n l.extend(i)\n return l", "def matrixdiagonally(mat):\n out = []\n (i, j) = (0, 0)\n up = True\n n = len(mat)\n while i < n and j < n:\n if up:\n while i > 0 and j < n - 1:\n out.append(mat[i][j])\n i -= 1\n j += 1\n out.append(mat[i][j])\n if j == n - 1:\n i += 1\n else:\n j += 1\n else:\n while j > 0 and i < n - 1:\n out.append(mat[i][j])\n j -= 1\n i += 1\n out.append(mat[i][j])\n if i == n - 1:\n j += 1\n else:\n i += 1\n up = not up\n return out", "def matrixdiagonally(mat):\n if not mat or not mat[0]:\n return []\n (N, M) = (len(mat), len(mat[0]))\n (row, column) = (0, 0)\n direction = 1\n result = []\n while row < N and column < M:\n result.append(mat[row][column])\n new_row = row + (-1 if direction == 1 else 1)\n new_column = column + (1 if direction == 1 else -1)\n if new_row < 0 or new_row == N or new_column < 0 or (new_column == M):\n if direction:\n row += column == M - 1\n column += column < M - 1\n else:\n column += row == N - 1\n row += row < N - 1\n direction = 1 - direction\n else:\n row = new_row\n column = new_column\n return result", "def matrixdiagonally(mat):\n n = len(mat[0])\n if n == 1:\n return mat[0]\n ans = []\n for e in range(n):\n r = e\n c = 0\n temp = []\n for x in range(e + 1):\n temp.append(mat[r][c])\n r -= 1\n c += 1\n if e % 2 == 1:\n temp.reverse()\n ans = ans + temp\n cl = 1\n for e in range(n - 1, 0, -1):\n r = n - 1\n c = cl\n temp = []\n for x in range(e):\n temp.append(mat[r][c])\n r -= 1\n c += 1\n if e % 2 == 0:\n temp.reverse()\n ans = ans + temp\n cl += 1\n return ans", "from collections import deque\n\ndef matrixdiagonally(mat):\n n = len(mat)\n i = 0\n j = 0\n k = 0\n up = True\n res = deque()\n while k < n * n:\n if up:\n while i >= 0 and j < n:\n res.append(mat[i][j])\n i -= 1\n j += 1\n k += 1\n if i < 0 and j <= n - 1:\n i = 0\n if j == n:\n i += 2\n j -= 1\n else:\n while j >= 0 and i < n:\n res.append(mat[i][j])\n i += 1\n j -= 1\n k += 1\n if j < 0 and i <= n - 1:\n j = 0\n if i == n:\n j += 2\n i -= 1\n up = not up\n return res", "def matrixdiagonally(n, mat):\n result = []\n rows = len(mat)\n cols = len(mat[0])\n num_of_diags = rows + cols - 1\n for diag in range(num_of_diags):\n if diag % 2 == 0:\n i = min([diag, rows - 1])\n j = diag - i\n while i > -1 and j < cols:\n result.append(mat[i][j])\n i -= 1\n j += 1\n else:\n j = min([diag, cols - 1])\n i = diag - j\n while j > -1 and i < rows:\n result.append(mat[i][j])\n i += 1\n j -= 1\n return result", "def matrixdiagonally(mat):\n i = 0\n j = 0\n counter = 0\n isUp = True\n n = len(mat)\n result = []\n while counter < n * n:\n if isUp:\n while i >= 0 and j < n:\n result.append(mat[i][j])\n counter += 1\n j += 1\n i -= 1\n if i < 0 and j <= n - 1:\n i = 0\n if j == n:\n i = i + 2\n j -= 1\n else:\n while j >= 0 and i < n:\n result.append(mat[i][j])\n counter += 1\n i += 1\n j -= 1\n if j < 0 and i <= n - 1:\n j = 0\n if i == n:\n j = j + 2\n i -= 1\n isUp = not isUp\n return result", "def __init__():\n self.r = []\n self.n = 0\n\ndef matrixdiagonally(a):\n self.r = []\n self.n = len(a)\n self.traverseDiagonalUp(a, 0, 0)\n return self.r\n\ndef traverseDiagonalUp(a, x, y):\n i = x\n j = y\n while self.n > j > -1 and -1 < i < self.n:\n self.r.append(a[i][j])\n i -= 1\n j += 1\n if j == self.n:\n self.traverseDiagonalDown(a, i + 2, j - 1)\n elif i == -1:\n self.traverseDiagonalDown(a, i + 1, j)\n\ndef traverseDiagonalDown(a, x, y):\n i = x\n j = y\n while self.n > j > -1 and -1 < i < self.n:\n self.r.append(a[i][j])\n i += 1\n j -= 1\n if i == self.n:\n self.traverseDiagonalUp(a, i - 1, j + 2)\n elif j == -1:\n self.traverseDiagonalUp(a, i, j + 1)", "def matrixdiagonally(mat):\n res = []\n i = 0\n row = 0\n col = 0\n flag = True\n n = len(mat)\n while row < n and col < n:\n if flag:\n while row > 0 and col < n - 1:\n res.append(mat[row][col])\n row -= 1\n col += 1\n res.append(mat[row][col])\n if col == n - 1:\n row += 1\n else:\n col += 1\n else:\n while col > 0 and row < n - 1:\n res.append(mat[row][col])\n row += 1\n col -= 1\n res.append(mat[row][col])\n if row == n - 1:\n col += 1\n else:\n row += 1\n flag = not flag\n return res", "def matrixdiagonally(mat):\n dia = []\n n = len(mat)\n sum = 0\n while sum <= 2 * (n - 1):\n if sum < n:\n a = sum\n b = 0\n while a >= 0:\n if sum % 2 == 0:\n dia.append(mat[a][b])\n else:\n dia.append(mat[b][a])\n a -= 1\n b += 1\n else:\n a = n - 1\n b = sum - n + 1\n while a >= sum - n + 1:\n if sum % 2 == 0:\n dia.append(mat[a][b])\n else:\n dia.append(mat[b][a])\n a -= 1\n b += 1\n sum += 1\n return dia", "def matrixdiagonally(mat):\n returnArray = []\n rowNumber = 0\n colNumber = 0\n numRowsCols = len(mat)\n isUp = True\n stop = False\n returnArray.append(mat[rowNumber][colNumber])\n while not stop:\n while not isUp:\n if rowNumber + 1 < numRowsCols and colNumber - 1 > -1:\n rowNumber += 1\n colNumber -= 1\n elif rowNumber + 1 < numRowsCols:\n rowNumber += 1\n isUp = True\n elif colNumber + 1 < numRowsCols:\n colNumber += 1\n isUp = True\n returnArray.append(mat[rowNumber][colNumber])\n while isUp:\n if rowNumber - 1 > -1 and colNumber + 1 < numRowsCols:\n rowNumber -= 1\n colNumber += 1\n elif colNumber + 1 < numRowsCols:\n colNumber += 1\n isUp = False\n elif rowNumber + 1 < numRowsCols:\n rowNumber += 1\n isUp = False\n else:\n stop = True\n isUp = False\n if not stop:\n returnArray.append(mat[rowNumber][colNumber])\n return returnArray", "def matrixdiagonally(mat):\n i = 0\n j = 0\n count = 0\n flag = 1\n ls = []\n while count < len(mat) * len(mat[0]):\n if flag == 1:\n while i >= 0 and j < len(mat[0]):\n ls.append(mat[i][j])\n i -= 1\n j += 1\n count += 1\n if i < 0 and j <= len(mat[0]) - 1:\n i = 0\n if j == len(mat[0]):\n j -= 1\n i += 2\n else:\n while i < len(mat) and j >= 0:\n ls.append(mat[i][j])\n i += 1\n j -= 1\n count += 1\n if j < 0 and i <= len(mat) - 1:\n j = 0\n if i == len(mat):\n i -= 1\n j += 2\n flag = 1 if flag == 0 else 0\n return ls", "def matrixdiagonally(mat):\n n = len(mat)\n i = 0\n j = 0\n k = 0\n lst = []\n up = True\n while k < n * n:\n if up:\n while i >= 0 and j < n:\n lst.append(mat[i][j])\n k += 1\n i -= 1\n j += 1\n if i < 0 and j <= n - 1:\n i = 0\n if j == n:\n i = i + 2\n j -= 1\n else:\n while i < n and j >= 0:\n lst.append(mat[i][j])\n k += 1\n j -= 1\n i += 1\n if j < 0 and i <= n - 1:\n j = 0\n if i == n:\n j = j + 2\n i -= 1\n up = not up\n return lst", "def matrixdiagonally(matrix):\n d = {}\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n if i + j not in d:\n d[i + j] = [matrix[i][j]]\n else:\n d[i + j].append(matrix[i][j])\n ans = []\n for (k, v) in d.items():\n if k % 2 == 0:\n ans.extend(v[::-1])\n else:\n ans.extend(v)\n return ans", "def matrixdiagonally(mat):\n numRows = len(mat)\n numCols = len(mat[0])\n diagonals = [[] for _ in range(numRows + numCols - 1)]\n for r in range(numRows):\n for c in range(numCols):\n diagonals[r + c].append(mat[r][c])\n res = []\n res = diagonals[0]\n for x in range(1, len(diagonals)):\n if x % 2:\n res.extend(diagonals[x])\n else:\n res.extend(diagonals[x][::-1])\n return res", "def matrixdiagonally(mat):\n n = len(mat)\n if n == 1:\n return [mat[0][0]]\n up = False\n (i, j) = (0, 0)\n res = [mat[0][0]]\n while len(res) < len(mat) * len(mat[0]):\n if up:\n if i == n - 1:\n j += 1\n else:\n i += 1\n while i >= 0 and j < n:\n res.append(mat[i][j])\n i -= 1\n j += 1\n i += 1\n j -= 1\n up = False\n else:\n if j == n - 1:\n i += 1\n else:\n j += 1\n while i < n and j >= 0:\n res.append(mat[i][j])\n i += 1\n j -= 1\n i -= 1\n j += 1\n up = True\n return res", "def matrixdiagonally(mat):\n output = []\n n = len(mat)\n col = 0\n row = 0\n up = True\n while row < n and col < n:\n if up:\n while row > 0 and col < n - 1:\n output.append(mat[row][col])\n row -= 1\n col += 1\n output.append(mat[row][col])\n if col == n - 1:\n row += 1\n else:\n col += 1\n else:\n while col > 0 and row < n - 1:\n output.append(mat[row][col])\n row += 1\n col -= 1\n output.append(mat[row][col])\n if row == n - 1:\n col += 1\n else:\n row += 1\n up = not up\n return output", "def matrixdiagonally(mat):\n r = len(mat)\n c = len(mat[0])\n diag = []\n check_revers = False\n for k in range(r):\n i = k\n j = 0\n l = []\n while i >= 0:\n l.append(mat[i][j])\n i -= 1\n j += 1\n if check_revers == False:\n check_revers = True\n else:\n l.reverse()\n check_revers = False\n for ll in l:\n diag.append(ll)\n for k in range(1, c):\n i = r - 1\n j = k\n l = []\n while j < c:\n l.append(mat[i][j])\n i -= 1\n j += 1\n if check_revers == False:\n check_revers = True\n else:\n l.reverse()\n check_revers = False\n for ll in l:\n diag.append(ll)\n return diag", "def matrixdiagonally(m):\n ans = []\n r = len(m)\n c = len(m[0])\n lst = [[] for i in range(r * c)]\n for i in range(r):\n for j in range(c):\n if (i + j) % 2 != 0:\n lst[i + j].append(m[i][j])\n else:\n lst[i + j].insert(0, m[i][j])\n for arr in lst:\n for x in arr:\n ans.append(x)\n return ans", "def matrixdiagonally(mat):\n i = 0\n j = 0\n k = 0\n isup = 1\n result_list = []\n while k < n[0] * n[0]:\n if isup:\n while i >= 0 and j < n[0]:\n result_list.append(mat[i][j])\n k += 1\n j += 1\n i -= 1\n if i < 0 and j < n[0]:\n i = 0\n if j == n[0]:\n i = i + 2\n j -= 1\n else:\n while j >= 0 and i < n[0]:\n result_list.append(mat[i][j])\n k += 1\n i += 1\n j -= 1\n if j < 0 and i <= n[0] - 1:\n j = 0\n if i == n[0]:\n j = j + 2\n i -= 1\n isup = not isup\n return result_list", "def matrixdiagonally(matrix):\n (num_rows, num_cols) = (len(matrix), len(matrix[0]))\n diagonals = [[] for _ in range(num_rows + num_cols - 1)]\n for i in range(num_rows):\n for j in range(num_cols):\n diagonals[i + j].append(matrix[i][j])\n res = diagonals[0]\n for x in range(1, len(diagonals)):\n if x % 2 == 1:\n res.extend(diagonals[x])\n else:\n res.extend(diagonals[x][::-1])\n return res", "def matrixdiagonally(mat):\n n = len(mat)\n s = [[] for i in range(2 * (n - 1) + 1)]\n for i in range(n):\n for j in range(n):\n s[i + j].append(mat[i][j])\n k = len(s)\n for i in range(2, k):\n if i % 2 == 0:\n s[i] = s[i][::-1]\n res = []\n for i in s:\n res.extend(i)\n return res", "def matrixdiagonally(mat):\n h = {}\n n = len(mat)\n for i in range(2 * n - 1):\n h[i] = []\n for i in range(n):\n for j in range(n):\n h[i + j].append(mat[i][j])\n res = []\n for i in h:\n if i % 2 == 0:\n res = res + h[i][::-1]\n else:\n res = res + h[i]\n return res", "def traverseUp(i, j, mat):\n res = []\n n = i\n while j <= n:\n res.append(mat[i][j])\n i -= 1\n j += 1\n return res\n\ndef traverseDown(i, j, mat):\n res = []\n n = i\n temp = j\n j = i\n i = temp\n while i <= n:\n res.append(mat[i][j])\n i += 1\n j -= 1\n return res\n\ndef matrixdiagonally(mat):\n dir = 0\n n = len(mat[0])\n res = []\n for row in range(n):\n if dir == 0:\n res += self.traverseUp(row, 0, mat)\n dir = 1\n else:\n res += self.traverseDown(row, 0, mat)\n dir = 0\n for col in range(1, n):\n if dir == 0:\n res += self.traverseUp(n - 1, col, mat)\n dir = 1\n else:\n res += self.traverseDown(n - 1, col, mat)\n dir = 0\n return res", "def matrixdiagonally(mat):\n a = []\n row = 0\n col = 0\n n = len(mat)\n for i in range(n * n):\n a.append(mat[row][col])\n if (row + col) % 2 == 0:\n if col == n - 1:\n row += 1\n elif row == 0:\n col += 1\n else:\n row -= 1\n col += 1\n elif row == n - 1:\n col += 1\n elif col == 0:\n row += 1\n else:\n row += 1\n col -= 1\n return a", "def matrixdiagonally(mat):\n r = len(mat)\n c = len(mat[0])\n i = 0\n j = 0\n res = []\n f = -1\n while i < r:\n f *= -1\n ni = i\n nj = j\n t = []\n while ni >= 0 and nj < c:\n t.append(mat[ni][nj])\n ni -= 1\n nj += 1\n if f == 1:\n res.extend(t)\n else:\n res.extend(t[::-1])\n i += 1\n i -= 1\n j += 1\n while j < c:\n f *= -1\n ni = i\n nj = j\n t = []\n while ni >= 0 and nj < c:\n t.append(mat[ni][nj])\n ni -= 1\n nj += 1\n if f == 1:\n res.extend(t)\n else:\n res.extend(t[::-1])\n j += 1\n return res", "def matrixdiagonally(mat):\n n = len(mat)\n i = j = k = 0\n isup = True\n lis = []\n while k < n * n:\n if isup:\n while i >= 0 and j < n:\n lis.append(mat[i][j])\n k += 1\n j += 1\n i -= 1\n if i < 0 and j <= n - 1:\n i = 0\n if j == n:\n i += 2\n j -= 1\n else:\n while j >= 0 and i < n:\n lis.append(mat[i][j])\n k += 1\n i += 1\n j -= 1\n if j < 0 and i <= n - 1:\n j = 0\n if i == n:\n j += 2\n i -= 1\n isup = not isup\n return lis", "def matrixdiagonally(mat):\n res = []\n n = len(mat)\n i = 0\n j = 0\n res.append(mat[i][j])\n while i != n - 1 or j != n - 1:\n if j + 1 < n:\n j = j + 1\n else:\n i = i + 1\n while True:\n res.append(mat[i][j])\n if i + 1 >= n or j - 1 <= -1:\n break\n i = i + 1\n j = j - 1\n if i + 1 < n:\n i = i + 1\n else:\n j = j + 1\n while True:\n res.append(mat[i][j])\n if i - 1 <= -1 or j + 1 >= n:\n break\n i = i - 1\n j = j + 1\n return res", "from collections import defaultdict\n\ndef matrixdiagonally(mat):\n d = defaultdict(list)\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n d[i + j].append(matrix[i][j])\n ans = []\n for (k, v) in d.items():\n if k % 2 == 0:\n ans.extend(v[::-1])\n else:\n ans.extend(v)\n return ans", "def matrixdiagonally(mat):\n up = 1\n n = len(mat)\n (i, j) = (0, 0)\n lst = []\n for _ in range(n * n):\n lst.append(mat[i][j])\n if up:\n if i - 1 >= 0 and j + 1 < n:\n i = i - 1\n j = j + 1\n elif j + 1 < n:\n j += 1\n up = 0\n else:\n i += 1\n up = 0\n elif i + 1 < n and j - 1 >= 0:\n i = i + 1\n j = j - 1\n elif i + 1 < n:\n i += 1\n up = 1\n else:\n j += 1\n up = 1\n return lst", "def matrixdiagonally(mat):\n flag = False\n ans = []\n k = 0\n r = len(mat)\n c = len(mat[0])\n while k < r:\n i = 0\n j = k\n l = []\n while i < r and j >= 0:\n l.append(mat[i][j])\n i += 1\n j -= 1\n if not flag:\n l.reverse()\n ans.extend(l)\n flag = not flag\n k += 1\n k = 1\n while k < c:\n i = k\n j = c - 1\n l = []\n while i < r and j >= 0:\n l.append(mat[i][j])\n i += 1\n j -= 1\n if not flag:\n l.reverse()\n ans.extend(l)\n flag = not flag\n k += 1\n return ans", "def matrixdiagonally(mat):\n m = len(mat)\n n = len(mat[0])\n result = []\n rev = True\n\n def traverse(r, c, result, rev):\n l = []\n while r < m and c >= 0:\n l.append(mat[r][c])\n r += 1\n c -= 1\n if not rev:\n result += l\n else:\n result += l[::-1]\n return not rev\n for c in range(n):\n rev = traverse(0, c, result, rev)\n for r in range(1, m):\n rev = traverse(r, n - 1, result, rev)\n return result", "def matrixdiagonally(mat):\n arr = []\n for i in range(2 * len(mat) - 1):\n arr.append([])\n for i in range(len(mat)):\n for j in range(len(mat)):\n arr[i + j].append(mat[i][j])\n ans = []\n i = 0\n n = len(arr)\n turn = 0\n while i < n:\n if i % 2 == 0:\n arr[i].reverse()\n for j in arr[i]:\n ans.append(j)\n i += 1\n else:\n for j in range(len(arr[i])):\n ans.append(arr[i][j])\n i += 1\n return ans", "def matrixdiagonally(mat):\n i = 0\n j = 0\n nodes_traversed = 0\n total_nodes = len(mat) * len(mat)\n isUp = True\n res = []\n while nodes_traversed < total_nodes:\n if isUp:\n while i >= 0 and j < len(mat):\n res.append(mat[i][j])\n nodes_traversed += 1\n i -= 1\n j += 1\n if i < 0 and j <= len(mat) - 1:\n i = 0\n if j == len(mat):\n i = i + 2\n j -= 1\n else:\n while j >= 0 and i < len(mat):\n res.append(mat[i][j])\n nodes_traversed += 1\n i += 1\n j -= 1\n if j < 0 and i <= len(mat) - 1:\n j = 0\n if i == len(mat):\n j = j + 2\n i -= 1\n isUp = not isUp\n return res", "def matrixdiagonally(mat):\n n = len(mat)\n res = []\n for l in range(2 * (n - 1) + 1):\n if l % 2 == 0:\n i = min(l, n - 1)\n j = l - i\n else:\n j = min(l, n - 1)\n i = l - j\n while i >= 0 and j >= 0 and (i < n) and (j < n):\n res.append(mat[i][j])\n if l % 2 == 0:\n i -= 1\n j += 1\n else:\n i += 1\n j -= 1\n return res", "def matrixdiagonally(arr):\n n = len(arr)\n ans = []\n mode = 0\n it = 0\n lower = 0\n for t in range(2 * n - 1):\n t1 = t\n if t1 >= n:\n mode += 1\n t1 = n - 1\n it -= 1\n lower += 1\n else:\n lower = 0\n it += 1\n for i in range(t1, lower - 1, -1):\n if (t1 + mode) % 2 == 0:\n ans.append(arr[i][t1 + lower - i])\n else:\n ans.append(arr[t1 + lower - i][i])\n return ans", "from collections import deque\n\ndef matrixdiagonally(n, mat):\n n = len(mat)\n if n < 2:\n return mat[0]\n temp = list()\n for i in range(1, n):\n coords = []\n x = list(range(0, i + 1))\n y = [-1 * var + i for var in x]\n if len(x) > 1:\n for k in range(len(x)):\n coords.append(mat[x[k]][y[k]])\n temp.append(coords)\n for j in range(n - 1, -1, -1):\n coords = []\n x = list(range(n - 1, n - 1 - j, -1))\n y = x.copy()\n y.reverse()\n if len(y) > 1:\n for k in range(len(y)):\n coords.append(mat[y[k]][x[k]])\n temp.append(coords)\n diag = []\n result = deque()\n for k in range(len(temp)):\n arr = temp[k].copy()\n if k % 2 != 0:\n arr.reverse()\n diag.append(arr)\n for l in range(len(diag[k])):\n result.append(diag[k][l])\n result.appendleft(mat[0][0])\n result.append(mat[-1][-1])\n return result", "def matrixdiagonally(a, mat):\n lis = [mat[0][0]]\n i = 0\n j = 0\n k = 0\n n = len(mat)\n d = False\n down = True\n while k < n * n:\n if i == n - 1 and j == n - 1:\n break\n if d:\n if down:\n while i > 0 and j < n - 1:\n k += 1\n i -= 1\n j += 1\n lis.append(mat[j][i])\n else:\n while i < n - 1 and j > 0:\n k += 1\n i += 1\n j -= 1\n lis.append(mat[j][i])\n d = False\n else:\n if i == 0:\n if j == 0:\n i += 1\n down = True\n elif j < n - 1:\n j += 1\n down = False\n else:\n i += 1\n down = False\n elif j == 0:\n if i < n - 1:\n i += 1\n down = True\n else:\n j += 1\n down = True\n elif i == n - 1:\n j += 1\n down = True\n elif j == n - 1:\n i += 1\n down = False\n lis.append(mat[j][i])\n k += 1\n d = True\n return lis"], "starter_code": "def matrixdiagonally(mat):\n", "input_output": {"inputs": ["N = 3\r\nmat[][] = {{1 2 3},{4 5 6},{7 8 9}}", "N = 2\r\nmat[][] = {{1 2},{3 4}}"], "outputs": ["1 2 4 7 5 3 6 8 9", "1 2 3 4"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/print-matrix-in-diagonal-pattern/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(N*M)", "entry_point": "matrixdiagonally", "task_id": "TACO_lite/275", "example": [[], []]} +{"requirement": "Write a function with the signature shown below:\n```python\ndef is_int_array(arr):\n return True\n```\n* returns `true / True` if every element in an array is an integer or a float with no decimals.\n* returns `true / True` if array is empty.\n* returns `false / False` for every other input.", "solutions": ["def is_int_array(a):\n return isinstance(a, list) and all((isinstance(x, (int, float)) and x == int(x) for x in a))", "def is_int_array(arr):\n if arr == []:\n return True\n if arr in [None, '']:\n return False\n for i in arr:\n if type(i) in [int, float]:\n if int(i) != i:\n return False\n else:\n return False\n return True", "def is_int_array(arr):\n if arr is None or type(arr) is str or None in arr:\n return False\n else:\n for i in arr:\n if type(i) is str or i % 1 != 0:\n return False\n return True", "def is_int_array(arr):\n return isinstance(arr, list) and all((isinstance(e, int) or (isinstance(e, float) and e.is_integer()) for e in arr))", "def is_int_array(arr):\n try:\n return list(map(int, arr)) == arr\n except:\n return False", "def is_int_array(arr):\n a = []\n if arr == None or arr == '':\n return False\n for i in arr:\n if type(i) == int:\n a.append(i)\n elif type(i) == float and i.is_integer():\n a.append(i)\n if len(arr) == len(a):\n return True\n return False", "def is_int_array(arr):\n return isinstance(arr, list) and all(map(lambda x: isinstance(x, (int, float)) and int(x) == x, arr))", "is_int_array = lambda a: isinstance(a, list) and all((isinstance(i, (int, float)) and i == int(i) for i in a))", "def isInt(n):\n try:\n return int(n) == float(n)\n except (TypeError, ValueError):\n return False\n\ndef is_int_array(arr):\n my_list = []\n if type(arr) is not list:\n return False\n if not arr:\n return True\n else:\n for x in arr:\n if type(x) is int or type(x) is float:\n if isInt(x):\n my_list.append(1)\n if len(arr) == len(my_list):\n return True\n else:\n return False"], "starter_code": "def is_int_array(arr):\n", "input_output": {"fn_name": "is_int_array", "inputs": [[[]], [[1, 2, 3, 4]], [[-11, -12, -13, -14]], [[1.0, 2.0, 3.0]], [[1, 2, null]], [null], [""], [[null]], [[1.0, 2.0, 3.0001]], [["-1"]]], "outputs": [[true], [true], [true], [true], [false], [false], [false], [false], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/52a112d9488f506ae7000b95", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_int_array", "task_id": "TACO_lite/308", "example": [[[[1, 2, 3, 4]], [[1, "a", 3, 4]], [[1.0, 2.0, 3.0]], [[]], [[1.0, 2.5, 3.0]], [null]], ["True", "False", "True", "True", "False", "False"]]} +{"requirement": "Create a function that returns an array containing the first `l` digits from the `n`th diagonal of [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal's_triangle).\n\n`n = 0` should generate the first diagonal of the triangle (the 'ones'). The first number in each diagonal should be 1.\n\nIf `l = 0`, return an empty array. Assume that both `n` and `l` will be non-negative integers in all test cases.", "solutions": ["def generate_diagonal(d, l):\n result = [1] if l else []\n for k in range(1, l):\n result.append(result[-1] * (d + k) // k)\n return result", "from scipy.special import comb\n\ndef generate_diagonal(n, l):\n return [comb(n + a, a, exact=True) for a in range(l)]", "from math import factorial\n\ndef generate_diagonal(n, l):\n return [factorial(n + i) // (factorial(n) * factorial(i)) for i in range(l)]", "def efficientCombination(n, k):\n from math import gcd\n (a, b) = (1, 1)\n if k == 0:\n return 1\n if n - k < k:\n k = n - k\n while k:\n a *= n\n b *= k\n m = gcd(a, b)\n a //= m\n b //= m\n n -= 1\n k -= 1\n return a\n\ndef generate_diagonal(d, amt):\n diagElements = []\n for n in range(d, amt + d, 1):\n valOnDiag = efficientCombination(n, d)\n diagElements.append(valOnDiag)\n return diagElements", "import operator as op\nfrom functools import reduce\n\ndef ncr(n, r):\n r = min(r, n - r)\n return reduce(op.mul, range(n, n - r, -1), 1) // reduce(op.mul, range(1, r + 1), 1)\n\ndef generate_diagonal(n, l):\n mx = []\n (i, j) = (n, 0)\n while i < n + l:\n mx.append(ncr(i, j))\n i += 1\n j += 1\n return mx", "def generate_diagonal(n, l):\n if l == 0:\n return []\n diagonal = [1]\n for i in range(l)[1:]:\n diagonal.append(diagonal[-1] * (n + i) / i)\n return diagonal", "def generate_diagonal(n, l):\n if n == 0:\n c = []\n while l > 0:\n c += [1]\n l -= 1\n return c\n if l == 0 and n == 0:\n return '[]'\n else:\n i = n + l\n q = []\n o = []\n\n def triangles():\n p = [1]\n while True:\n yield p\n p = [1] + [p[x] + p[x + 1] for x in range(len(p) - 1)] + [1]\n for t in triangles():\n if i > 0:\n i -= 1\n q.append(t)\n else:\n break\n for t in range(l):\n r = q[n][t]\n n += 1\n o.append(r)\n return o", "def generate_diagonal(n, l):\n row = [1]\n for k in range(1, l):\n row.append(row[-1] * (n + k) // k)\n return row if l else []", "from functools import lru_cache\n\ndef generate_diagonal(nn, l):\n\n def calc(n, ll):\n if n == 0 or ll == 1:\n return 1\n elif n < 0:\n return 0\n return calc(n - 1, ll) + calc(n, ll - 1)\n return [calc(nn, i) for i in range(1, l + 1)]"], "starter_code": "def generate_diagonal(n, l):\n", "input_output": {"fn_name": "generate_diagonal", "inputs": [[0, 10], [1, 10], [2, 10], [3, 10], [4, 10], [10, 0], [100, 6]], "outputs": [[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], [[1, 3, 6, 10, 15, 21, 28, 36, 45, 55]], [[1, 4, 10, 20, 35, 56, 84, 120, 165, 220]], [[1, 5, 15, 35, 70, 126, 210, 330, 495, 715]], [[]], [[1, 101, 5151, 176851, 4598126, 96560646]]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/576b072359b1161a7b000a17", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "generate_diagonal", "task_id": "TACO_lite/195", "example": [[[0, 5], [1, 5], [2, 5]], ["[1, 1, 1, 1, 1]", "[1, 2, 3, 4, 5]", "[1, 3, 6, 10, 15]"]]} +{"requirement": "## Task\n\nCreate a function that given a sequence of strings, groups the elements that can be obtained by rotating others, ignoring upper or lower cases. \n\nIn the event that an element appears more than once in the input sequence, only one of them will be taken into account for the result, discarding the rest. \n\n## Input\n\nSequence of strings. Valid characters for those strings are uppercase and lowercase characters from the alphabet and whitespaces.\n\n## Output\n\nSequence of elements. Each element is the group of inputs that can be obtained by rotating the strings. \n\nSort the elements of each group alphabetically. \n\nSort the groups descendingly by size and in the case of a tie, by the first element of the group alphabetically.\n\n## Examples\n\n```python\n['Tokyo', 'London', 'Rome', 'Donlon', 'Kyoto', 'Paris', 'Okyot'] --> [['Kyoto', 'Okyot', 'Tokyo'], ['Donlon', 'London'], ['Paris'], ['Rome']]\n\n['Rome', 'Rome', 'Rome', 'Donlon', 'London'] --> [['Donlon', 'London'], ['Rome']]\n\n[] --> []\n```", "solutions": ["def group_cities(seq):\n result = []\n sort_result = []\n seq = list(dict.fromkeys(seq))\n for (e, i) in enumerate(seq):\n sort_result = [j for j in seq if len(j) == len(i) and j.lower() in 2 * i.lower()]\n if not sorted(sort_result) in result:\n result.append(sorted(sort_result))\n return sorted(sorted(result), key=len, reverse=True)", "from collections import Counter, defaultdict\n\ndef group_cities(seq):\n bases = defaultdict(lambda : defaultdict(list))\n for W in set(seq):\n w = W.lower()\n d = bases[frozenset(Counter(w).items())]\n k = next((w2 for w2 in d if w in w2), w * 2)\n d[k].append(W)\n return sorted([sorted(lst) for d in bases.values() for lst in d.values()], key=lambda g: (-len(g), g[0]))", "from collections import deque\n\ndef group_cities(seq):\n result = []\n seq = sorted(set(seq))\n simples = [c.lower() for c in seq]\n skip = set()\n for (i, c1) in enumerate(simples):\n if i in skip:\n continue\n city_match = [i]\n skip.add(i)\n rolls = []\n roller = deque(c1)\n roller.rotate(1)\n while ''.join(roller) != c1:\n rolls.append(''.join(roller))\n roller.rotate(1)\n for roll in rolls:\n for (j, c2) in enumerate(simples[i + 1:], i + 1):\n if j in skip:\n continue\n if c2 == roll:\n skip.add(j)\n city_match.append(j)\n result.append(sorted([seq[k] for k in city_match]))\n result.sort(key=lambda a: (-len(a), a[0]))\n return result", "def group_cities(seq):\n res = {}\n for w in seq:\n temp = [str(w[i:] + w[:i]).title() for i in range(1, len(w)) if str(w[i:] + w[:i]).title() in seq]\n temp.append(w)\n res[frozenset(temp)] = sorted(set(temp))\n return sorted(res.values(), key=lambda x: (-len(x), x[0]))", "def is_palindrome(a, b):\n if len(a) != len(b):\n return False\n else:\n for i in range(1, len(a)):\n if a.lower()[i:] + a.lower()[:i] == b.lower():\n return True\n return False\n\ndef group_cities(seq):\n ans = []\n already_chosen = []\n for term in seq:\n if term not in already_chosen:\n temp = [term]\n already_chosen.append(term)\n for thing in seq:\n if thing not in already_chosen and thing != term and is_palindrome(thing, term):\n temp.append(thing)\n already_chosen.append(thing)\n ans.append(temp)\n for thing in ans:\n thing.sort()\n ans.sort(key=lambda x: x[0])\n ans.sort(key=len, reverse=True)\n return ans", "from collections import defaultdict\n\ndef key(s):\n s = s.lower().replace(' ', '')\n return min((s[i:] + s[:i] for i in range(len(s))))\n\ndef group_cities(seq):\n result = defaultdict(list)\n for city in set(seq):\n result[key(city)].append(city)\n for cities in result.values():\n cities.sort()\n return sorted(result.values(), key=lambda cities: (-len(cities), cities[0]))", "def group_cities(seq):\n result = []\n for element in sorted(list(dict.fromkeys(seq)), key=str.lower):\n for group in result:\n if element.lower() in [group[0].lower()[r:] + group[0].lower()[:r] for r in range(len(group[0].lower()))]:\n group.append(element)\n break\n else:\n result.append([element])\n return sorted(result, key=len, reverse=True)", "from collections import deque\nfrom operator import itemgetter\n\ndef group_cities(seq):\n seq_by_length = {}\n for s in seq:\n l = len(s)\n if l in seq_by_length:\n seq_by_length[l].append(s)\n else:\n seq_by_length[l] = [s]\n groups = []\n for elems in seq_by_length.values():\n to_check = deque(set(elems))\n while to_check:\n cur_check = to_check.pop()\n (group, check) = ([cur_check], cur_check.lower() * 2)\n for c in to_check.copy():\n if c.lower() in check:\n group.append(c)\n to_check.remove(c)\n groups.append(sorted(group))\n return sorted(sorted(groups, key=itemgetter(0)), key=len, reverse=True)", "from collections import defaultdict\n\ndef group_cities(l):\n\n def make_key(s):\n return min((s[-i:] + s[:-i] for i in range(len(s))))\n d = defaultdict(list)\n for item in sorted(set(l)):\n d[make_key(item.lower())].append(item)\n return sorted(d.values(), key=len, reverse=True)", "from collections import defaultdict\n\ndef group_cities(seq):\n key = lambda s: min((s[i:] + s[:i] for i in range(len(s))))\n d = defaultdict(set)\n for e in seq:\n d[key(e.lower())].add(e)\n return sorted((sorted(v) for v in d.values()), key=lambda x: (-len(x), x))"], "starter_code": "def group_cities(seq):\n", "input_output": {"fn_name": "group_cities", "inputs": [[["Tokyo", "London", "Rome", "Donlon", "Kyoto", "Paris", "Okyot"]], [["Tokyo", "London", "Rome", "Donlon"]], [["Rome", "Rome", "Rome", "Donlon", "London"]], [["Ab", "Aa"]], [[]]], "outputs": [[[["Kyoto", "Okyot", "Tokyo"], ["Donlon", "London"], ["Paris"], ["Rome"]]], [[["Donlon", "London"], ["Rome"], ["Tokyo"]]], [[["Donlon", "London"], ["Rome"]]], [[["Aa"], ["Ab"]]], [[]]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Sorting", "Lists"], "name": null, "source": "codewars", "tags": ["String algorithms", "Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/5e98712b7de14f0026ef1cc1", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "group_cities", "task_id": "TACO_lite/282", "example": [[[["Tokyo", "London", "Rome", "Donlon", "Kyoto", "Paris", "Okyot"]], [["Rome", "Rome", "Rome", "Donlon", "London"]], [[]]], ["[['Kyoto', 'Okyot', 'Tokyo'], ['Donlon', 'London'], ['Paris'], ['Rome']]", "[['Donlon', 'London'], ['Rome']]", "[]"]]} +{"requirement": "Given a list of intervals, remove all intervals that are covered by another interval in the list.\nInterval [a,b) is covered by\u00a0interval [c,d) if and only if c <= a and b <= d.\nAfter doing so, return the number of remaining intervals.\n\u00a0\nExample 1:\nInput: intervals = [[1,4],[3,6],[2,8]]\nOutput: 2\nExplanation: Interval [3,6] is covered by [2,8], therefore it is removed.\n\nExample 2:\nInput: intervals = [[1,4],[2,3]]\nOutput: 1\n\nExample 3:\nInput: intervals = [[0,10],[5,12]]\nOutput: 2\n\nExample 4:\nInput: intervals = [[3,10],[4,10],[5,11]]\nOutput: 2\n\nExample 5:\nInput: intervals = [[1,2],[1,4],[3,4]]\nOutput: 1\n\n\u00a0\nConstraints:\n\n1 <= intervals.length <= 1000\nintervals[i].length == 2\n0 <= intervals[i][0] <\u00a0intervals[i][1] <= 10^5\nAll the intervals are unique.", "solutions": ["def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[0], -x[1]))\n prev_end = result = 0\n for (_, end) in intervals:\n if end > prev_end:\n result += 1\n prev_end = end\n return result", "def removecoveredintervals(l: List[List[int]]) -> int:\n l.sort(reverse=True, key=lambda x: (x[1], -x[0]))\n n = len(l)\n c = n\n for i in range(n - 1):\n if l[i][0] <= l[i + 1][0] and l[i][1] >= l[i + 1][1]:\n l[i + 1] = l[i]\n c -= 1\n return c", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n from functools import cmp_to_key\n\n def cmp(a, b):\n if a[0] > b[0]:\n return 1\n if a[0] < b[0]:\n return -1\n if a[1] > b[1]:\n return -1\n return 1\n lis = []\n if len(intervals) == 1:\n return 1\n for (x, y) in intervals:\n lis.append((x, y))\n lis.sort(key=cmp_to_key(cmp))\n fin = []\n fin.append(list(lis[0]))\n for i in range(1, len(lis)):\n (currx, curry) = lis[i]\n flag = 0\n for j in range(len(fin)):\n if curry <= fin[j][1] and currx >= fin[j][0]:\n flag = 1\n if flag == 0:\n fin.append([currx, curry])\n return len(fin)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[0], -x[1]))\n covering = 0\n used = set()\n for (i, (si, ei)) in enumerate(intervals):\n for (sj, ej) in intervals[i + 1:]:\n if sj > ei:\n break\n if ej > ei:\n continue\n if (sj, ej) in used:\n continue\n used.add((sj, ej))\n covering += 1\n return len(intervals) - covering", "def __init__(val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef __lt__(other):\n if self.val[0] < other.val[0]:\n return True\n elif self.val[0] > other.val[0]:\n return False\n elif self.val[1] > other.val[1]:\n return True\n else:\n return False\n\ndef __le__(other):\n return self < other or self.val == other.val\n\ndef __gt__(other):\n return not self <= other\n\ndef __ge__(other):\n return not self < other\n\ndef __eq__(other):\n return self <= other and self >= geother\n\ndef __neq__(other):\n return not self == other\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n tree = Tree(val=tuple(intervals[0]))\n for (x, y) in intervals[1:]:\n this = Tree((x, y))\n cursor = tree\n while True:\n if this < cursor:\n if cursor.left:\n cursor = cursor.left\n else:\n cursor.left = this\n break\n elif this > cursor:\n if cursor.right:\n cursor = cursor.right\n else:\n cursor.right = this\n break\n else:\n break\n buff = [tree]\n (count, last) = (0, None)\n while buff:\n while buff[-1].left:\n buff.append(buff[-1].left)\n while buff and (not buff[-1].right):\n this = buff.pop(-1)\n if count == 0:\n (count, last) = (1, this.val[1])\n elif this.val[1] > last:\n (count, last) = (count + 1, this.val[1])\n if buff:\n this = buff.pop(-1)\n if count == 0:\n (count, last) = (1, this.val[1])\n elif this.val[1] > last:\n (count, last) = (count + 1, this.val[1])\n buff.append(this.right)\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n for i in range(0, len(intervals) - 1):\n minel = intervals[i]\n minid = i\n for j in range(i + 1, len(intervals)):\n evl = intervals[j]\n if evl[0] < minel[0]:\n minel = evl\n minid = j\n (intervals[i], intervals[minid]) = (intervals[minid], intervals[i])\n c = 0\n prevl = intervals[0][0]\n prevh = intervals[0][1]\n for x in range(1, len(intervals)):\n curl = intervals[x][0]\n curh = intervals[x][1]\n if curh <= prevh:\n c = c + 1\n continue\n if curl == prevl:\n c = c + 1\n if curh > prevh:\n prevh = curh\n continue\n prevl = curl\n prevh = curh\n return len(intervals) - c", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n ordered_intervals = sorted(intervals, key=lambda x: (x[0], -x[1]))\n candidates = set()\n for i in range(len(intervals)):\n (curr_start, curr_end) = ordered_intervals[i]\n for j in range(i + 1, len(intervals)):\n (next_start, next_end) = ordered_intervals[j]\n if next_start >= curr_end:\n break\n if next_end <= curr_end:\n candidates.add(j)\n return len(intervals) - len(candidates)", "import numpy as np\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n copy_intervals = intervals[:]\n for (i, interval_1) in enumerate(copy_intervals):\n for interval_2 in copy_intervals[i + 1:]:\n if interval_1[0] >= interval_2[0] and interval_1[1] <= interval_2[1]:\n if interval_1 in intervals:\n intervals.remove(interval_1)\n break\n if interval_1[0] <= interval_2[0] and interval_1[1] >= interval_2[1]:\n if interval_2 in intervals:\n intervals.remove(interval_2)\n return len(intervals)", "def removecoveredintervals(arr: List[List[int]]) -> int:\n arr.sort(reverse=True)\n ans = 0\n n = len(arr)\n take = [1] * n\n for i in range(n - 1):\n for j in range(i + 1, n):\n if arr[i][0] >= arr[j][0] and arr[i][1] <= arr[j][1]:\n take[i] = 0\n break\n for i in range(n - 1, -1, -1):\n for j in range(i - 1, -1, -1):\n if arr[i][0] >= arr[j][0] and arr[i][1] <= arr[j][1]:\n take[i] = 0\n break\n return take.count(1)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda interval: (interval[0], -interval[1]))\n length = len(intervals)\n start = 0\n removed = 0\n while start < length - 1:\n curr = start + 1\n while curr < length:\n if intervals[curr][0] != -1:\n if intervals[curr][0] >= intervals[start][0] and intervals[curr][1] <= intervals[start][1]:\n removed += 1\n intervals[curr][0] = -1\n intervals[curr][1] = -1\n curr += 1\n start += 1\n return length - removed", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals = sorted(intervals, key=lambda x: x[1])\n n = len(intervals)\n cnt = 0\n for i in intervals:\n for j in intervals:\n if j == i:\n continue\n if i[1] <= j[1] and i[0] >= j[0]:\n cnt += 1\n break\n return n - cnt", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(reverse=True)\n intervals.sort(key=lambda i: i[1])\n covered = set()\n for (i, (c, d)) in enumerate(intervals):\n for (a, b) in intervals[0:i]:\n if c <= a and b <= d:\n covered.add((a, b))\n return len(intervals) - len(covered)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n new = sorted(intervals, key=lambda x: x[1] - x[0], reverse=True)\n ans = []\n for (i, v) in enumerate(new):\n flag = False\n for elem in new[:i]:\n if v[0] >= elem[0] and v[1] <= elem[1]:\n flag = True\n if flag == False:\n ans.append(v)\n return len(ans)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n removed = 0\n removedSet = set()\n for ind1 in range(len(intervals)):\n for ind2 in range(len(intervals)):\n if ind1 == ind2 or ind1 in removedSet:\n continue\n interval1 = intervals[ind1]\n interval2 = intervals[ind2]\n if interval1[0] >= interval2[0] and interval1[1] <= interval2[1]:\n removed += 1\n removedSet.add(ind1)\n return len(intervals) - removed", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n flag = [True for i in range(n)]\n ctr = n\n for i in range(n):\n for j in range(n):\n if i != j and flag[i] and flag[j]:\n (a, b) = intervals[i]\n (c, d) = intervals[j]\n if c <= a and b <= d:\n flag[i] = False\n ctr -= 1\n elif a <= c and d <= b:\n flag[j] = False\n ctr -= 1\n return ctr", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n\n def covered(a, b):\n return a[0] >= b[0] and a[1] <= b[1]\n deleted = set()\n for i in range(len(intervals)):\n for j in range(len(intervals)):\n if i != j and i not in deleted:\n if covered(intervals[i], intervals[j]):\n deleted.add(i)\n return len(intervals) - len(deleted)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n int_set = set((tuple(i) for i in intervals))\n for (i, (a, b)) in enumerate(intervals):\n for (c, d) in intervals[i + 1:]:\n if a <= c and d <= b and ((c, d) in int_set):\n int_set.remove((c, d))\n elif c <= a and b <= d and ((a, b) in int_set):\n int_set.remove((a, b))\n return len(int_set)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n covered = 0\n m = {}\n for [l, r] in intervals:\n if l not in m:\n m[l] = r\n else:\n m[l] = max(r, m[l])\n covered += 1\n a = []\n for i in m:\n a.append([i, m[i]])\n a.sort(key=lambda x: x[0])\n _c = set()\n for i in range(len(a)):\n for j in range(i + 1, len(a)):\n if a[j][1] <= a[i][1] and j not in _c:\n _c.add(j)\n covered += 1\n return len(intervals) - covered", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda tup: tup[1] - tup[0], reverse=True)\n covered = set()\n for i in range(len(intervals)):\n (s, e) = intervals[i]\n for j in range(i + 1, len(intervals)):\n (s2, e2) = intervals[j]\n if s <= s2 and e2 <= e:\n covered.add(j)\n return len(intervals) - len(covered)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n l = len(intervals)\n a = [True] * l\n for i in range(l):\n for j in range(l):\n if i == j:\n continue\n if not a[i] or not a[j]:\n continue\n if intervals[i][0] <= intervals[j][0] and intervals[i][1] >= intervals[j][1]:\n a[j] = False\n return a.count(True)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[0], -x[1]))\n ans = len(intervals)\n i = 0\n while i < len(intervals):\n for j in range(i):\n if intervals[j][0] <= intervals[i][0] and intervals[j][1] >= intervals[i][1]:\n ans -= 1\n break\n i += 1\n return ans", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals = sorted(intervals, key=lambda k: (k[0], -k[1]))\n removed = set()\n i = 0\n while i < len(intervals) - 1:\n for j in range(i + 1, len(intervals)):\n if intervals[j][1] <= intervals[i][1] and j not in removed:\n removed.add(j)\n i += 1\n return len(intervals) - len(removed)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n intervals.sort(key=lambda x: (x[0], -x[1]))\n removeSet = set()\n for i in range(n):\n interval1 = intervals[i]\n for j in range(i + 1, n):\n interval2 = intervals[j]\n if interval2[0] >= interval1[1]:\n break\n if interval2[1] <= interval1[1]:\n removeSet.add(j)\n return n - len(removeSet)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n l = len(intervals)\n removed = set()\n intervals.sort(key=lambda i: (i[0], -i[1]))\n for i in range(l):\n for j in range(i + 1, l):\n if intervals[i][1] >= intervals[j][1]:\n removed.add(j)\n return l - len(removed)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n discarded = [False] * len(intervals)\n for i in range(len(intervals)):\n for j in range(len(intervals)):\n if i == j:\n continue\n if discarded[j]:\n continue\n if intervals[j][0] >= intervals[i][0] and intervals[j][1] <= intervals[i][1]:\n discarded[j] = True\n kount = 0\n for i in range(len(intervals)):\n if not discarded[i]:\n kount = kount + 1\n return kount", "def checkCovered(a, b):\n if a[0] < b[0] or a[1] > b[1]:\n return False\n return True\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n covered = [0] * len(intervals)\n for i in range(len(intervals) - 1):\n a = intervals[i]\n for j in range(i + 1, len(intervals)):\n b = intervals[j]\n if covered[i] == 0:\n if checkCovered(a, b):\n covered[i] = 1\n if covered[j] == 0:\n if checkCovered(b, a):\n covered[j] = 1\n return covered.count(0)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n i = 0\n j = 1\n while i < len(intervals) and j < len(intervals):\n if intervals[i][0] >= intervals[j][0] and intervals[i][1] <= intervals[j][1]:\n intervals.pop(i)\n (i, j) = (0, 1)\n elif intervals[i][0] <= intervals[j][0] and intervals[i][1] >= intervals[j][1]:\n intervals.pop(j)\n (i, j) = (0, 1)\n else:\n j += 1\n if j == len(intervals):\n i += 1\n j = i + 1\n return len(intervals)", "def isCovered(A, B):\n if A[0] <= B[0] and A[1] >= B[1]:\n return True\n return False\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n index = 0\n while index < len(intervals):\n delete = False\n i = intervals[index]\n for j in intervals:\n if intervals[index] == j:\n continue\n if self.isCovered(i, j):\n intervals.remove(j)\n index = -1\n break\n if self.isCovered(j, i):\n intervals.remove(i)\n index = -1\n break\n index += 1\n return len(intervals)", "import numpy as np\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n current_intervals = np.array(intervals)\n for interval in intervals:\n mask = np.logical_and(current_intervals[:, 0] >= interval[0], current_intervals[:, 1] <= interval[1])\n current_intervals = current_intervals[np.logical_not(mask)]\n if sum(mask):\n current_intervals = np.append(current_intervals, [interval], axis=0)\n return len(current_intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n seen = set()\n n = len(intervals)\n for i in range(n):\n for j in range(n):\n if j == i or j in seen:\n continue\n (st1, ed1) = (intervals[i][0], intervals[i][1])\n (st2, ed2) = (intervals[j][0], intervals[j][1])\n if st1 <= st2 and ed2 <= ed1:\n seen.add(j)\n return n - len(seen)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n I = len(intervals)\n count = 0\n covered = {}\n removed = {}\n for i in range(0, I):\n for j in range(0, I):\n if i == j:\n continue\n if j in removed or i in removed:\n continue\n if intervals[i][0] <= intervals[j][0] and intervals[i][1] >= intervals[j][1]:\n if (i, j) not in covered and (j, i) not in covered:\n count += 1\n covered[i, j] = 1\n covered[j, i] = 1\n removed[j] = j\n return len(intervals) - count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n if len(intervals) < 2:\n return len(intervals)\n intervals.sort(key=lambda interval: interval[0])\n (start, idx) = (0, 1)\n removed = set()\n while start < len(intervals):\n if idx == len(intervals):\n start += 1\n idx = start + 1\n continue\n if idx in removed:\n idx += 1\n continue\n if intervals[start][1] < intervals[idx][0]:\n start += 1\n idx = start + 1\n continue\n if intervals[start][1] >= intervals[idx][1]:\n removed.add(idx)\n idx += 1\n continue\n if intervals[start][1] <= intervals[idx][1]:\n if intervals[start][0] == intervals[idx][0]:\n removed.add(start)\n start = idx\n idx += 1\n return len(intervals) - len(removed)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n covered = set()\n for i in range(len(intervals) - 1):\n (a1, b1) = intervals[i]\n for j in range(i + 1, len(intervals)):\n (a2, b2) = intervals[j]\n if a2 <= a1 and b1 <= b2:\n covered.add(i)\n elif a1 <= a2 and b2 <= b1:\n covered.add(j)\n return len(intervals) - len(covered)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n N = len(intervals)\n intervals.sort(key=lambda x: x[0])\n count = 0\n covered = set()\n for i in range(N):\n for j in range(N):\n if i != j and j not in covered:\n min_x = min(intervals[i][0], intervals[j][0])\n max_y = max(intervals[i][1], intervals[j][1])\n if intervals[i] == [min_x, max_y]:\n covered.add(j)\n count += 1\n return N - count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n lis = intervals\n arr = []\n lis.sort()\n for i in range(0, len(lis)):\n if lis[i] in arr:\n continue\n for j in range(i + 1, len(lis)):\n if i < len(lis) and j < len(lis):\n if lis[i][0] >= lis[j][0] and lis[i][1] <= lis[j][1] and (lis[i] not in arr):\n arr.append(lis[i])\n if lis[i][0] <= lis[j][0] and lis[i][1] >= lis[j][1] and (lis[j] not in arr):\n arr.append(lis[j])\n else:\n break\n return len(lis) - len(arr)", "from functools import cmp_to_key\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n\n def cmp_intervals(left, right):\n if left[0] == right[0]:\n return right[1] - left[1]\n return left[0] - right[0]\n n = len(intervals)\n s_intervals = sorted(intervals, key=cmp_to_key(cmp_intervals))\n covered = set()\n for i in range(n - 1):\n (a, b) = s_intervals[i]\n for j in range(i + 1, n):\n (c, d) = s_intervals[j]\n if a <= c and d <= b:\n covered.add((c, d))\n return n - len(covered)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort()\n drop = set([])\n for i in range(len(intervals)):\n (x, y) = intervals[i]\n for j in range(i + 1, len(intervals)):\n (a, b) = intervals[j]\n if x >= a and y <= b:\n drop.add(i)\n break\n elif a >= x and b <= y:\n drop.add(j)\n return len(intervals) - len(drop)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n intervals.sort(reverse=True)\n temp = []\n for i in range(n - 1, -1, -1):\n for k in range(0, n):\n if i != k and (intervals[k][0] <= intervals[i][0] and intervals[i][1] <= intervals[k][1]):\n temp.append(intervals[i])\n break\n res = [i for i in intervals if i not in temp]\n return len(res)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda t: [t[0], t[1]])\n deleted = set()\n i = 0\n while i < len(intervals):\n boundary = tuple(intervals[i])\n if not boundary in deleted:\n j = i + 1\n stop = False\n while not stop and j < len(intervals):\n comparedBoundary = tuple(intervals[j])\n if comparedBoundary[0] == boundary[0]:\n deleted.add(boundary)\n stop = True\n elif comparedBoundary[0] >= boundary[1]:\n stop = True\n elif comparedBoundary[1] <= boundary[1]:\n deleted.add(comparedBoundary)\n j += 1\n i += 1\n return len(intervals) - len(deleted)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n for i in range(len(intervals)):\n for j in range(i, len(intervals)):\n if i == j or type(intervals[i][0]) == str or type(intervals[j][0]) == str:\n continue\n elif intervals[i][0] >= intervals[j][0] and intervals[i][1] <= intervals[j][1]:\n intervals[i] = ['', '']\n elif intervals[j][0] >= intervals[i][0] and intervals[j][1] <= intervals[i][1]:\n intervals[j] = ['', '']\n interval = []\n for ele in intervals:\n if ele != ['', '']:\n interval.append(ele)\n return len(interval)", "from collections import defaultdict\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n m = n\n visited = defaultdict(lambda : False)\n for i in range(n):\n for j in range(n):\n if i == j or visited[j]:\n continue\n if intervals[i][0] <= intervals[j][0]:\n if intervals[i][1] >= intervals[j][1]:\n visited[j] = True\n m -= 1\n return m", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n removed = [False] * n\n intervals = sorted(intervals, key=lambda interval: (interval[0], -interval[1]))\n for i in range(len(intervals)):\n (start, end) = intervals[i]\n j = i + 1\n while j < len(intervals) and end >= intervals[j][0]:\n if end >= intervals[j][1] and (not removed[j]):\n removed[j] = True\n n -= 1\n j += 1\n return n", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n flags = []\n for i in range(n):\n flags.append(0)\n k = n\n for i in range(n):\n for j in range(n):\n if i == j or flags[j] == 1:\n continue\n if intervals[i][0] <= intervals[j][0] and intervals[i][1] >= intervals[j][1]:\n flags[j] = 1\n k -= 1\n return k", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n L = len(intervals)\n discard = set()\n for i in range(L):\n (x, y) = intervals[i]\n for j in range(i + 1, L):\n (a, b) = intervals[j]\n if a <= x and b >= y:\n discard.add((x, y))\n elif x <= a and y >= b:\n discard.add((a, b))\n return L - len(discard)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n length = len(intervals)\n if length <= 1:\n return length\n temp = intervals[:]\n (i, j) = (0, 1)\n while i < len(intervals) - 1:\n j = i + 1\n while j < len(intervals):\n if self.ainbHelper(intervals[i], intervals[j]) == True:\n try:\n temp.remove(intervals[i])\n except:\n pass\n break\n elif self.ainbHelper(intervals[j], intervals[i]) == True:\n try:\n temp.remove(intervals[j])\n except:\n pass\n j += 1\n else:\n j += 1\n i += 1\n return len(temp)\n\ndef ainbHelper(a: List[int], b: List[int]) -> bool:\n if a[0] < b[0]:\n return False\n if a[1] > b[1]:\n return False\n else:\n return True", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n for i in range(len(intervals)):\n for j in range(len(intervals)):\n if i != j:\n if intervals[i] != 0 and intervals[j] != 0:\n if intervals[j][0] <= intervals[i][0] and intervals[i][1] <= intervals[j][1]:\n intervals[i] = 0\n c = 0\n for i in intervals:\n if i != 0:\n c += 1\n return c", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n s = set()\n for (i, [a, b]) in enumerate(intervals):\n for (j, [c, d]) in enumerate(intervals[i + 1:]):\n if c <= a and b <= d:\n s.add((a, b))\n elif a <= c and d <= b:\n s.add((c, d))\n return len(intervals) - len(s)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n for i in range(len(intervals) - 1):\n for j in range(len(intervals) - i - 1):\n if intervals[j][0] > intervals[j + 1][0]:\n (intervals[j], intervals[j + 1]) = (intervals[j + 1], intervals[j])\n i = 0\n while True:\n while intervals[i][1] >= intervals[i + 1][1]:\n intervals.pop(i + 1)\n if i + 1 > len(intervals) - 1:\n break\n if i + 1 > len(intervals) - 1:\n break\n if intervals[i][0] == intervals[i + 1][0]:\n intervals.pop(i)\n if i + 1 > len(intervals) - 1:\n break\n else:\n continue\n if i + 1 == len(intervals) - 1:\n break\n i += 1\n return len(intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n op = 0\n if len(intervals) < 2:\n return len(intervals)\n intervals.sort(key=lambda l1: l1[0])\n for j in intervals:\n for k in intervals:\n if j[0] != k[0] or j[1] != k[1]:\n if j[0] >= k[0] and j[1] <= k[1]:\n op += 1\n break\n return len(intervals) - op", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n L = len(intervals)\n rm = set()\n for i in range(L):\n for j in range(i + 1, L):\n (l1, r1) = intervals[i]\n (l2, r2) = intervals[j]\n if l1 <= l2 and r1 >= r2:\n if j not in rm:\n rm.add(j)\n elif l1 >= l2 and r1 <= r2:\n if i not in rm:\n rm.add(i)\n return L - len(rm)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n count = [0] * len(intervals)\n for i in range(len(intervals) - 1):\n a = intervals[i][0]\n b = intervals[i][1]\n for j in range(i + 1, len(intervals)):\n x = intervals[j][0]\n y = intervals[j][1]\n if x <= a and b <= y:\n count[i] = 1\n elif a <= x and y <= b:\n count[j] = 1\n ans = 0\n for c in count:\n if c == 0:\n ans += 1\n return ans", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n rm = {}\n for i in range(1, len(intervals)):\n for ((a, b), (c, d)) in zip(intervals[0:-i], intervals[i:]):\n if a >= c:\n if b <= d:\n rm[a, b] = True\n elif c >= a:\n if d <= b:\n rm[c, d] = True\n return len(intervals) - len(rm)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n toremove = set()\n for i in range(0, len(intervals) - 1):\n for j in range(i + 1, len(intervals)):\n (s1, e1) = intervals[i]\n (s2, e2) = intervals[j]\n if s1 >= s2 and e1 <= e2:\n toremove.add(i)\n elif s2 >= s1 and e2 <= e1:\n toremove.add(j)\n return len(intervals) - len(toremove)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n\n def comparator(a, b):\n return a[0] - b[0]\n intervals.sort()\n removed = {}\n for (index, interval) in enumerate(intervals):\n for (inner_index, inner_interval) in enumerate(intervals):\n if index == inner_index:\n continue\n if index in removed or inner_index in removed:\n continue\n if inner_interval[0] >= interval[0] and inner_interval[1] <= interval[1]:\n removed[inner_index] = True\n return len(intervals) - len(removed.keys())", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n tot = len(intervals)\n valid = [True] * len(intervals)\n for i in range(len(intervals)):\n if valid[i]:\n for j in range(len(intervals)):\n if i == j:\n continue\n if valid[j] and intervals[j][0] >= intervals[i][0] and (intervals[j][1] <= intervals[i][1]):\n valid[j] = False\n tot -= 1\n return tot", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n removed = []\n for i in range(len(intervals) - 1):\n for j in range(i + 1, len(intervals)):\n if i in removed:\n break\n if j in removed:\n continue\n (i_start, i_end) = intervals[i]\n (j_start, j_end) = intervals[j]\n if i_start <= j_start and i_end >= j_end:\n removed.append(j)\n elif i_start >= j_start and i_end <= j_end:\n removed.append(i)\n return len(intervals) - len(removed)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n if not intervals:\n return 0\n count = 0\n for (i, [left, right]) in enumerate(intervals):\n flag = True\n for (j, [oleft, oright]) in enumerate(intervals):\n if oleft <= left and right <= oright and (i != j):\n flag = False\n continue\n if flag:\n count += 1\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals = sorted(intervals, key=lambda x: (x[0], -x[1]))\n if len(intervals) == 1:\n return 1\n remove_indices = []\n for (p1, (l1, r1)) in enumerate(intervals[:-1]):\n for (p2, (l2, r2)) in enumerate(intervals[p1 + 1:]):\n if l1 <= l2 and r1 >= r2:\n remove_indices.append(p2 + p1)\n elif l1 < l2 < r1:\n continue\n else:\n break\n return len([interval for (idx, interval) in enumerate(intervals) if idx not in remove_indices])", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n ref = [1] * n\n for i in range(n):\n for j in range(n):\n if i == j or not ref[i] & ref[j]:\n continue\n if intervals[i][0] <= intervals[j][0] and intervals[i][1] >= intervals[j][1]:\n ref[j] = 0\n return sum(ref)", "from copy import deepcopy\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n intind = []\n for i in range(0, len(intervals)):\n a = intervals[i][0]\n b = intervals[i][1]\n for j in range(i + 1, len(intervals)):\n c = intervals[j][0]\n d = intervals[j][1]\n if c <= a and b <= d:\n intind.append(i)\n if a <= c and d <= b:\n intind.append(j)\n return len(intervals) - len(set(intind))", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n exclusion_set = set()\n for i in range(len(intervals)):\n for j in range(i + 1, len(intervals)):\n (a, b) = intervals[i]\n (c, d) = intervals[j]\n if c <= a and b <= d:\n exclusion_set.add((a, b))\n if a <= c and d <= b:\n exclusion_set.add((c, d))\n return len(intervals) - len(exclusion_set)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n exclude = list()\n for (ind, left) in enumerate(intervals[:-1]):\n if left in exclude:\n continue\n for right in intervals[ind + 1:]:\n if right in exclude:\n continue\n elif right[0] <= left[0] and left[1] <= right[1]:\n exclude.append(left)\n break\n elif left[0] <= right[0] and right[1] <= left[1]:\n exclude.append(right)\n else:\n continue\n return len(intervals) - len(exclude)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n removed = []\n for (i, interval) in enumerate(intervals):\n for i2 in range(i, len(intervals)):\n interval2 = intervals[i2]\n if i in removed:\n break\n if i == i2 or i2 in removed:\n continue\n if interval[0] >= interval2[0] and interval[1] <= interval2[1] and (i not in removed):\n removed += [i]\n if interval[0] <= interval2[0] and interval[1] >= interval2[1] and (i2 not in removed):\n removed += [i2]\n return len(intervals) - len(removed)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n total = len(intervals)\n for (i, inner) in enumerate(intervals):\n for (o, outer) in enumerate(intervals):\n if outer[0] <= inner[0] and outer[1] >= inner[1] and (i != o):\n total -= 1\n break\n return total", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n counter = 0\n l = len(intervals)\n for i in range(l):\n for j in range(l):\n if i != j:\n if intervals[j][0] <= intervals[i][0] and intervals[i][1] <= intervals[j][1]:\n counter += 1\n break\n return l - counter", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n op = 0\n if len(intervals) < 2:\n return len(intervals)\n for j in intervals:\n for k in intervals:\n if j[0] != k[0] or j[1] != k[1]:\n if j[0] >= k[0] and j[1] <= k[1]:\n op += 1\n break\n return len(intervals) - op", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n arr = []\n for val in intervals:\n for interval in intervals:\n if interval[0] == val[0] and interval[1] == val[1]:\n continue\n if interval[0] <= val[0] and interval[1] >= val[1]:\n break\n else:\n arr.append(val)\n return len(arr)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n i = 0\n result = len(intervals)\n while i < len(intervals) - 1:\n (a1, b1) = intervals[i]\n j = i + 1\n remove_i = False\n while j < len(intervals):\n (a2, b2) = intervals[j]\n if a2 >= a1 and b2 <= b1:\n intervals = intervals[:j] + intervals[j + 1:]\n result -= 1\n continue\n if a1 >= a2 and b1 <= b2:\n intervals = intervals[:i] + intervals[i + 1:]\n result -= 1\n remove_i = True\n break\n j = j + 1\n if remove_i:\n continue\n i += 1\n return result", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n ans = 0\n for i in range(len(intervals)):\n canFit = False\n for j in range(len(intervals)):\n if i == j:\n continue\n if intervals[i][0] >= intervals[j][0] and intervals[i][1] <= intervals[j][1]:\n canFit = True\n break\n if canFit == False:\n ans += 1\n return ans", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n for i in range(len(intervals) - 1):\n if intervals[i][0] == -1:\n continue\n for j in range(i + 1, len(intervals)):\n t = intervals[i]\n tn = intervals[j]\n if t[0] <= tn[0] and tn[1] <= t[1]:\n (intervals[j][0], intervals[j][1]) = (-1, -1)\n elif tn[0] <= t[0] and t[1] <= tn[1]:\n (intervals[i][0], intervals[i][1]) = (-1, -1)\n count = 0\n for i in intervals:\n if i[0] != -1:\n count += 1\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n_intervals = len(intervals)\n if intervals:\n intervals = sorted(intervals, key=lambda x: x[0] - x[1])\n i = len(intervals) - 1\n while i > 0:\n interval_i = intervals[i]\n j = i - 1\n while j >= 0:\n if intervals[j][0] <= interval_i[0] and intervals[j][1] >= interval_i[1]:\n n_intervals -= 1\n break\n j -= 1\n i -= 1\n return n_intervals", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n cov = 0\n\n def covered(first, second):\n return first[0] <= second[0] and second[1] <= first[1]\n for (pos, inter1) in enumerate(intervals):\n for (checkpos, inter2) in enumerate(intervals):\n if pos != checkpos and covered(inter2, inter1):\n cov += 1\n break\n return len(intervals) - cov", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n count = len(intervals)\n for i in range(len(intervals)):\n for j in range(len(intervals)):\n if (i != j) & (intervals[i][0] >= intervals[j][0]) & (intervals[i][1] <= intervals[j][1]):\n count = count - 1\n break\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n covered = 0\n same = 0\n for i in range(len(intervals)):\n for j in range(len(intervals)):\n if intervals[i][0] == intervals[j][0] and intervals[j][1] == intervals[i][1]:\n continue\n elif intervals[i][0] >= intervals[j][0] and intervals[j][1] >= intervals[i][1]:\n covered += 1\n break\n return len(intervals) - covered", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n return self.m1_sort(intervals)\n\ndef m1_sort(intervals):\n intervals.sort(key=lambda x: x[1], reverse=True)\n intervals.sort(key=lambda x: x[0])\n count = 0\n max_end = 0\n for interval in intervals:\n if interval[1] > max_end:\n max_end = interval[1]\n count += 1\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n a = self.checkInterval(intervals)\n return len(a)\n\ndef checkInterval(intervals) -> List[List[int]]:\n if len(intervals) == 1:\n return [intervals[0]]\n else:\n front = intervals[0]\n back = self.checkInterval(intervals[1:])\n if not back:\n return front\n (s, e) = (front[0], front[1])\n irrelevant = list([interval for interval in back if interval[0] <= s and e <= interval[1]])\n if len(irrelevant):\n return back\n filtered = list([interval for interval in back if not (s <= interval[0] and interval[1] <= e)])\n return [front] + filtered", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[0], -x[1]))\n q = [intervals[0][1]]\n counter = 0\n for (a, b) in intervals[1:]:\n t = [x for x in q]\n flag = 0\n for v in q:\n if a > v:\n t.remove(v)\n flag = 1\n elif b <= v:\n counter += 1\n break\n else:\n flag = 1\n if flag == 1:\n t.append(b)\n q = t\n return len(intervals) - counter", "def checkIntvl(a: List[int], b: List[int]) -> bool:\n return b[0] <= a[0] and b[1] >= a[1]\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n count = 0\n for (i, i1) in enumerate(intervals):\n is_covered = False\n for (j, i2) in enumerate(intervals):\n if i == j:\n continue\n else:\n is_covered = self.checkIntvl(i1, i2)\n if is_covered:\n break\n if not is_covered:\n count += 1\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda interval: interval[1] - interval[0])\n counter = 0\n i = 0\n n = len(intervals)\n for i in range(n):\n covered = False\n for j in range(i + 1, n):\n if self.cover(intervals[j], intervals[i]):\n covered = True\n break\n if not covered:\n counter += 1\n return counter\n\ndef cover(interval1, interval2):\n return interval1[0] <= interval2[0] and interval1[1] >= interval2[1]", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n covered = set()\n p1 = 0\n while p1 < len(intervals):\n if p1 in covered:\n p1 += 1\n continue\n p2 = p1 + 1\n while p2 < len(intervals):\n if intervals[p1][0] <= intervals[p2][0] and intervals[p2][1] <= intervals[p1][1]:\n covered.add(p2)\n elif intervals[p2][0] <= intervals[p1][0] and intervals[p1][1] <= intervals[p2][1]:\n covered.add(p1)\n p2 += 1\n p1 += 1\n return len(intervals) - len(covered)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n\n def covers(interval, byinterval):\n return interval[0] >= byinterval[0] and interval[1] <= byinterval[1]\n ret = 0\n for i in range(len(intervals)):\n iscovered = False\n for j in (x for x in range(len(intervals)) if x != i):\n if covers(intervals[i], intervals[j]):\n iscovered = True\n break\n if not iscovered:\n ret += 1\n return ret", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n deleted = set()\n for (idx, interval) in enumerate(intervals):\n if str(interval) in deleted:\n continue\n for other in intervals[idx + 1:]:\n if interval[0] <= other[0] and interval[1] >= other[1]:\n deleted.add(str(other))\n elif interval[0] >= other[0] and interval[1] <= other[1]:\n deleted.add(str(interval))\n return len(intervals) - len(deleted)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[0], -x[1]))\n ub = [x[1] for x in intervals]\n d = [x - max(ub[:i + 1]) <= 0 for (i, x) in enumerate(ub[1:])]\n return len(intervals) - sum(d)", "def compare(intervalA: List[int], intervalB: List[int]) -> int:\n if intervalA[0] <= intervalB[0] and intervalA[1] >= intervalB[1]:\n return 1\n if intervalB[0] <= intervalA[0] and intervalB[1] >= intervalA[1]:\n return -1\n return 0\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: x[0])\n result = len(intervals)\n index = 0\n while index < len(intervals):\n itemA = intervals[index]\n removes = []\n for i in range(index + 1, len(intervals)):\n itemB = intervals[i]\n comp = self.compare(itemA, itemB)\n if comp == 0:\n continue\n if comp == 1:\n removes.append(i)\n elif comp == -1 and index not in removes:\n removes.append(index)\n if len(removes) == 0:\n index += 1\n else:\n removes.sort()\n removes.reverse()\n for k in range(len(removes)):\n intervals.remove(intervals[removes[k]])\n if index not in removes:\n index += 1\n result -= len(removes)\n return result", "def removecoveredintervals(intervals):\n result = 0\n for i in range(len(intervals)):\n covered = False\n for j in range(len(intervals)):\n if i == j:\n continue\n if self.covered(intervals[i], intervals[j]):\n covered = True\n break\n if not covered:\n result += 1\n return result\n\ndef covered(i1, i2):\n c = i2[0]\n d = i2[1]\n a = i1[0]\n b = i1[1]\n return c <= a and b <= d", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n sorted_intervals = sorted(intervals, key=lambda x: (x[0], -x[1]))\n new_intervals = []\n new_intervals.append(sorted_intervals[0])\n for i in sorted_intervals:\n n = new_intervals[-1]\n if i[0] >= n[0] and i[1] <= n[1]:\n continue\n new_intervals.append(i)\n return len(new_intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n tree = {}\n for (x, y) in intervals:\n cursor = tree\n if not tree:\n tree['value'] = (x, y)\n else:\n while True:\n if x < cursor['value'][0]:\n tmp = cursor.get('left', {})\n if tmp:\n cursor = tmp\n else:\n cursor['left'] = {'value': (x, y)}\n break\n elif x > cursor['value'][0]:\n tmp = cursor.get('right', {})\n if tmp:\n cursor = tmp\n else:\n cursor['right'] = {'value': (x, y)}\n break\n elif y > cursor['value'][1]:\n tmp = cursor.get('left', {})\n if tmp:\n cursor = tmp\n else:\n cursor['left'] = {'value': (x, y)}\n break\n elif y < cursor['value'][1]:\n tmp = cursor.get('right', {})\n if tmp:\n cursor = tmp\n else:\n cursor['right'] = {'value': (x, y)}\n break\n else:\n break\n buff = [tree]\n (count, last) = (0, None)\n while buff:\n while buff[-1].get('left', None):\n buff.append(buff[-1]['left'])\n while buff and (not buff[-1].get('right', None)):\n this = buff.pop(-1)\n if count == 0:\n (count, last) = (1, this['value'][1])\n elif this['value'][1] > last:\n (count, last) = (count + 1, this['value'][1])\n if buff:\n this = buff.pop(-1)\n if count == 0:\n (count, last) = (1, this['value'][1])\n elif this['value'][1] > last:\n (count, last) = (count + 1, this['value'][1])\n buff.append(this['right'])\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n if len(intervals) == 0:\n return 0\n elif len(intervals) == 1:\n return 1\n remove_indices = set()\n for i in range(len(intervals)):\n (a, b) = intervals[i]\n for j in range(i + 1, len(intervals)):\n (c, d) = intervals[j]\n if a != c or b != d:\n if a >= c and b <= d:\n remove_indices.add(i)\n break\n elif c >= a and d <= b:\n remove_indices.add(j)\n return len(intervals) - len(remove_indices)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort()\n table = dict()\n for interval in intervals:\n if interval[0] not in intervals:\n table[interval[0]] = interval[1]\n elif interval[1] > table[interval[0]]:\n table[interval[0]] = interval[1]\n count = len(table) + 1\n keys = list(table.keys())\n cover = table[keys[0]]\n for key in table.keys():\n if table[key] <= cover:\n count -= 1\n else:\n cover = table[key]\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n i = 0\n while i < len(intervals):\n current_int = intervals[i]\n for j in range(i + 1, len(intervals)):\n int1 = intervals[j]\n if current_int[0] <= int1[0] and current_int[1] >= int1[1]:\n intervals.remove(int1)\n i -= 1\n break\n elif int1[0] <= current_int[0] and int1[1] >= current_int[1]:\n intervals.remove(current_int)\n i -= 1\n break\n i += 1\n return len(intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n\n def isCovered(interval, candidates):\n for c in candidates:\n if c[0] <= interval[0] and c[1] >= interval[1]:\n return True\n return False\n cnt = 0\n for (i, interval) in enumerate(intervals):\n if not isCovered(interval, intervals[:i] + intervals[i + 1:]):\n cnt += 1\n return cnt", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: [x[0], -x[1]])\n (prev_end, count) = (0, 0)\n for (_, curr_end) in intervals:\n if prev_end < curr_end:\n count += 1\n prev_end = curr_end\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n arr = [0] * len(intervals)\n for i in range(len(intervals)):\n for j in range(len(intervals)):\n if i != j and arr[j] != -1:\n if intervals[i][0] >= intervals[j][0] and intervals[i][1] <= intervals[j][1]:\n arr[i] = -1\n break\n ans = 0\n for i in arr:\n if i != -1:\n ans += 1\n return ans", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n\n def checkCovered(self, A, B):\n if B[0] <= A[0] and A[1] <= B[1]:\n return True\n else:\n return False\n res = len(intervals)\n for (i, interval) in enumerate(intervals):\n tmp = intervals[:i] + intervals[i + 1:]\n for each in tmp:\n if checkCovered(self, interval, each):\n res -= 1\n break\n return res", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n len_interval = len(intervals)\n if len_interval == 1:\n return 1\n count = len_interval\n for i in range(len_interval):\n part_intervals = intervals[:i] + intervals[i + 1:]\n for interval in part_intervals:\n if self.isOverlapping(intervals[i], interval):\n count -= 1\n break\n return count\n\ndef isOverlapping(interval_1: List[int], interval_2: List[int]) -> bool:\n if interval_2[0] <= interval_1[0] and interval_1[1] <= interval_2[1]:\n return True\n else:\n return False", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n removed = set()\n for i in range(len(intervals) - 1):\n if i in removed:\n pass\n for j in range(i + 1, len(intervals)):\n if intervals[i][0] <= intervals[j][0] <= intervals[j][1] <= intervals[i][1]:\n removed.add(j)\n elif intervals[j][0] <= intervals[i][0] <= intervals[i][1] <= intervals[j][1]:\n removed.add(i)\n break\n return len(intervals) - len(removed)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n d = {}\n for (l, r) in intervals:\n if l not in d:\n d[l] = []\n d[l].append(r)\n dd = []\n for l in sorted(d.keys()):\n dd.append([l, max(d[l])])\n for i in range(len(dd)):\n for j in range(i + 1, len(dd)):\n if dd[i] and dd[j] and (dd[i][1] >= dd[j][1]):\n dd[j] = False\n ans = 0\n for ddd in dd:\n if ddd:\n ans += 1\n return ans", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n count = length = len(intervals)\n removedIdx = set()\n for i in range(length - 1):\n for j in range(i + 1, length):\n if i in removedIdx or j in removedIdx:\n continue\n (a, b) = (intervals[i][0], intervals[i][1])\n (c, d) = (intervals[j][0], intervals[j][1])\n if a <= c and b >= d:\n count -= 1\n removedIdx.add(j)\n elif c <= a and d >= b:\n count -= 1\n removedIdx.add(i)\n return count", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n exists = [True] * len(intervals)\n for i in range(len(intervals) - 1):\n for j in range(i + 1, len(intervals)):\n if exists[i] and exists[j]:\n result = self.isCovered(intervals[i], intervals[j])\n if result == 1:\n exists[j] = False\n elif result == -1:\n exists[i] = False\n else:\n pass\n return sum(exists)\n\ndef isCovered(a: List[int], b: List[int]) -> int:\n if a[0] <= b[0] and a[1] >= b[1]:\n return 1\n elif a[0] >= b[0] and a[1] <= b[1]:\n return -1\n else:\n return 0", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n if len(intervals) < 2:\n return n\n condition = True\n while condition:\n indexes = []\n condition = False\n for ind0 in range(n):\n for ind1 in range(ind0 + 1, n):\n if intervals[ind1][0] <= intervals[ind0][0] and intervals[ind0][1] <= intervals[ind1][1]:\n indexes.append(ind0)\n if not condition:\n condition = True\n break\n elif intervals[ind0][0] <= intervals[ind1][0] and intervals[ind1][1] <= intervals[ind0][1]:\n indexes.append(ind1)\n if not condition:\n condition = True\n indexes = list(set(indexes))\n for index in sorted(indexes, reverse=True):\n del intervals[index]\n n = len(intervals)\n if n < 2:\n return n\n return n", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n result = set()\n intervals.sort(key=lambda x: (x[0], -x[1]))\n for i in range(len(intervals)):\n for j in range(i + 1, len(intervals)):\n if j not in result and intervals[i][1] >= intervals[j][1]:\n result.add(j)\n return len(intervals) - len(result)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n removed = 0\n removed_list = {}\n for i in range(len(intervals)):\n for j in range(i + 1, len(intervals)):\n if i in removed_list or j in removed_list:\n continue\n elif intervals[j][0] <= intervals[i][0] <= intervals[j][1] and intervals[j][0] <= intervals[i][1] <= intervals[j][1]:\n removed_list[i] = True\n removed += 1\n elif intervals[i][0] <= intervals[j][0] <= intervals[i][1] and intervals[i][0] <= intervals[j][1] <= intervals[i][1]:\n removed_list[j] = True\n removed += 1\n return len(intervals) - removed", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n answers = []\n for i in intervals:\n cints = intervals.copy()\n cints.remove(i)\n if all(map(lambda j: i[0] < j[0] or i[1] > j[1], cints)):\n answers.append(i)\n return len(answers)", "def covered(a, b):\n return b[0] <= a[0] and a[1] <= b[1]\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n covered_intervals = set()\n for a in intervals:\n for b in intervals:\n if a is b or tuple(b) in covered_intervals:\n continue\n if covered(a, b):\n covered_intervals.add(tuple(a))\n break\n return len(intervals) - len(covered_intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals = sorted(intervals, key=lambda x: (x[0], -x[1]))\n endingval = 0\n res = 0\n for (_, end) in intervals:\n if endingval < end:\n endingval = end\n res += 1\n return res", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals == sorted(intervals)\n if intervals == [[66672, 75156], [59890, 65654], [92950, 95965], [9103, 31953], [54869, 69855], [33272, 92693], [52631, 65356], [43332, 89722], [4218, 57729], [20993, 92876]]:\n return 3\n else:\n y = 0\n while y < 1000:\n x = 0\n l = intervals\n while len(intervals) > x:\n for i in intervals:\n if len(intervals) > x:\n if i != intervals[x]:\n if intervals[x][0] <= i[0] and intervals[x][1] >= i[1]:\n intervals.remove(i)\n x += 1\n y += 1\n return len(intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n n = len(intervals)\n res = n\n for i in range(n - 1):\n for j in range(i + 1, n):\n if intervals[i][0] < 0 or intervals[j][0] < 0:\n continue\n if intervals[i][0] <= intervals[j][0] and intervals[i][1] >= intervals[j][1]:\n intervals[j][0] = -1\n res -= 1\n continue\n elif intervals[i][0] >= intervals[j][0] and intervals[i][1] <= intervals[j][1]:\n res -= 1\n intervals[i][0] = -1\n break\n return res", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n intervals.sort()\n l = len(intervals)\n bad = []\n for i in range(l):\n if i not in bad:\n for j in range(i + 1, l):\n if intervals[j][0] >= intervals[i][1]:\n break\n if j not in bad:\n if intervals[i][0] == intervals[j][0]:\n bad.append(i)\n break\n if intervals[j][1] <= intervals[i][1]:\n bad.append(j)\n return l - len(bad)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n dictionary = {}\n intervals.sort(key=lambda x: x[1])\n j = 0\n while j != len(intervals):\n idx = j + 1\n minima = intervals[j][0]\n while idx < len(intervals):\n if intervals[idx][1] == intervals[j][1]:\n minima = min(minima, intervals[idx][0])\n intervals.pop(idx)\n idx += 1\n else:\n break\n intervals[j][0] = minima\n value = intervals[j][0]\n if value not in dictionary:\n dictionary[value] = 1\n else:\n dictionary[value] += 1\n j += 1\n counter = len(intervals)\n for value in intervals:\n for elem in dictionary:\n if elem == value[0] and dictionary[elem] > 1:\n counter -= 1\n break\n if elem < value[0] and dictionary[elem] > 0:\n counter -= 1\n break\n dictionary[value[0]] -= 1\n return counter", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n first = [x[0] for x in intervals]\n indices = [i[0] for i in sorted(enumerate(first), key=lambda x: x[1])]\n sorted_intervals = [intervals[i] for i in indices]\n remove = []\n flag = True\n while flag == True:\n flag = False\n for i in range(len(sorted_intervals) - 1):\n (c, d) = (sorted_intervals[i][0], sorted_intervals[i][1])\n (a, b) = (sorted_intervals[i + 1][0], sorted_intervals[i + 1][1])\n if c <= a and b <= d:\n remove.append([a, b])\n flag = True\n elif a <= c and d <= b:\n remove.append([c, d])\n flag = True\n sorted_intervals = [x for x in sorted_intervals if x not in remove]\n return len(sorted_intervals)", "def covered(a, b):\n return b[0] <= a[0] and a[1] <= b[1]\n\ndef removecoveredintervals(intervals: List[List[int]]) -> int:\n i = set(map(tuple, intervals))\n l = set()\n for a in i:\n for b in i - {a} - l:\n if a == b:\n continue\n if covered(a, b):\n l.add(a)\n break\n return len(i) - len(l)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n non_covered_intervals = []\n covered_intervals = set()\n for i in range(len(intervals)):\n for j in range(len(intervals)):\n if j == i:\n continue\n if tuple(intervals[j]) in covered_intervals:\n continue\n if intervals[i][0] >= intervals[j][0] and intervals[i][1] <= intervals[j][1]:\n covered_intervals.add(tuple(intervals[i]))\n break\n else:\n non_covered_intervals.append(intervals[i])\n return len(non_covered_intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n notCovered = len(intervals)\n covered = len(intervals) * [False]\n intervals.sort(key=lambda x: (x[0], -x[1]))\n for i in range(len(intervals)):\n if not covered[i]:\n for j in range(i + 1, len(intervals)):\n if not covered[j]:\n firstIntervalEnd = intervals[i][1]\n secondIntervalEnd = intervals[j][1]\n if secondIntervalEnd <= firstIntervalEnd:\n covered[j] = True\n notCovered -= 1\n return notCovered", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n start = len(intervals)\n temp = intervals.copy()\n for (i, item) in enumerate(intervals[:-1]):\n if item in temp:\n for item2 in intervals[i + 1:]:\n if item2 in temp:\n if item2[0] >= item[0] and item2[1] <= item[1]:\n start = start - 1\n temp.remove(item2)\n elif item[0] >= item2[0] and item[1] <= item2[1]:\n start = start - 1\n break\n return start", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n mx = max(list(map(max, intervals)))\n max_from = [0] * mx\n for (a, b) in intervals:\n max_from[a] = max(max_from[a], b)\n mx = 0\n for i in range(len(max_from)):\n mx = max(mx, max_from[i])\n max_from[i] = mx\n cnt = len(intervals)\n for (a, b) in intervals:\n if max_from[a] > b or (a > 0 and max_from[a - 1] >= b):\n cnt -= 1\n return cnt", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n i = 0\n while i < len(intervals):\n for k in intervals:\n if intervals[i][0] >= k[0] and intervals[i][1] <= k[1]:\n if intervals[i] != k:\n intervals.pop(i)\n if i > 0:\n i = i - 1\n i = i + 1\n return len(intervals)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n i = 0\n length = len(intervals)\n while i < length:\n flag = True\n j = i + 1\n while j < length:\n if intervals[j][0] <= intervals[i][0] and intervals[i][1] <= intervals[j][1]:\n intervals.pop(i)\n length -= 1\n i = max(i - 1, 0)\n if i == 0:\n flag = False\n elif intervals[i][0] <= intervals[j][0] and intervals[j][1] <= intervals[i][1]:\n intervals.pop(j)\n length -= 1\n i = max(i - 1, 0)\n if i == 0:\n flag = False\n else:\n j += 1\n if flag:\n i += 1\n return length", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n c = 0\n for i in intervals:\n for j in intervals:\n c += 1\n a = sorted(sorted(intervals, key=itemgetter(1), reverse=True), key=itemgetter(0))\n i = 0\n while i < len(a):\n j = i + 1\n while j < len(a) and a[j][0] >= a[i][0] and (a[j][1] <= a[i][1]):\n a.pop(j)\n i = j\n return len(a)", "def removecoveredintervals(intervals: List[List[int]]) -> int:\n events = []\n r = 0\n for i in range(0, len(intervals)):\n events.append([i, intervals[i][0], 0, intervals[i][1]])\n events.append([i, intervals[i][1], 1, intervals[i][0]])\n events.sort(key=lambda x: (x[1], -x[3]))\n ai = []\n po = {}\n for i in range(0, len(events)):\n if events[i][2] == 0:\n po[events[i][0]] = list(ai)\n ai.append(events[i][0])\n else:\n if not list(set(po[events[i][0]]) & set(ai)):\n r += 1\n ai.remove(events[i][0])\n return r"], "starter_code": "def removecoveredintervals(intervals: List[List[int]]) -> int:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Sorting"], "name": null, "source": "leetcode", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://leetcode.com/problems/remove-covered-intervals/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "removecoveredintervals", "task_id": "TACO_lite/321", "example": [[[[[1, 4], [3, 6], [2, 8]]], [[[1, 4], [2, 3]]], [[[0, 10], [5, 12]]], [[[3, 10], [4, 10], [5, 11]]], [[[1, 2], [1, 4], [3, 4]]]], ["2", "1", "2", "2", "1"]]} +{"requirement": "Given an array arr of n integers, task is to print the array in the order \u2013 smallest number, largest number, 2nd smallest number, 2nd largest number, 3rd smallest number, 3rd largest number and so on.\nExample 1:\nInput:\nn = 9\narr[] = {1, 9, 2, 8, 3, 7, 4, 6, 5}\nOutput:\n1 9 2 8 3 7 4 6 5\nExplanation:\nSmallest number is 1. Largest number is 9. \n2nd smallest number is 2. Then 2nd largest\nnumber is 8. And so on.\nExample 2:\nInput:\nn = 4\narr[] = {1, 2, 3, 4}\nOutput:\n1 4 2 3\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function rearrangeArray() which takes the array of integers arr and n as parameters and returns void. You need to change the array itself.\nExpected Time Complexity: O(n*logn)\nExpected Auxiliary Space: O(n)\nConstraints: \n1 <= n <= 10^{5}\n1 <= arr[i] <=10^{6}", "solutions": ["def rearrangearray(arr, n):\n result = []\n arr.sort()\n left = 0\n right = n - 1\n while left < right:\n result.append(arr[left])\n result.append(arr[right])\n left += 1\n right -= 1\n if n % 2 == 1:\n result.append(arr[left])\n for i in range(0, n):\n arr[i] = result[i]", "def rearrangearray(arr, n):\n arr.sort()\n if n % 2 != 0:\n N = n // 2 + 1\n else:\n N = n // 2\n a = arr[:N]\n b = arr[N:]\n arr[::2] = a[:]\n arr[1::2] = b[:][::-1]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n left = arr[:n // 2]\n right = arr[n // 2:][::-1]\n l = []\n for i in range(n // 2):\n l.append(left[0])\n left.pop(0)\n l.append(right[0])\n right.pop(0)\n l = l + left + right\n for i in range(n):\n arr[i] = l[i]", "def rearrangearray(arr, n):\n arr.sort()\n i = 0\n j = n - 1\n l = []\n while i < j:\n l.append(arr[i])\n l.append(arr[j])\n i += 1\n j -= 1\n if n % 2 == 1:\n l.append(arr[i])\n for i in range(0, n):\n arr[i] = l[i]", "def rearrangearray(arr, n):\n arr1 = sorted(arr)\n arr2 = sorted(arr, reverse=True)\n new_arr = []\n if n % 2 == 0:\n for i in range(n // 2):\n new_arr.append(arr1[i])\n new_arr.append(arr2[i])\n else:\n for i in range(n // 2 + 1):\n new_arr.append(arr1[i])\n new_arr.append(arr2[i])\n new_arr.pop()\n for i in range(n):\n arr[i] = new_arr[i]\n return arr", "def rearrangearray(arr, n):\n li = []\n k = 0\n m = -1\n t = sorted(arr)\n for i in range(n):\n if i % 2 == 0:\n li.append(t[k])\n k = k + 1\n else:\n li.append(t[m])\n m = m - 1\n return li", "def rearrangearray(arr, n):\n arr.sort()\n clone = arr.copy()\n left = 0\n right = n - 1\n for i in range(n):\n if i % 2 == 0:\n arr[i] = clone[left]\n left += 1\n else:\n arr[i] = clone[right]\n right -= 1", "def rearrangearray(arr, n):\n n = len(arr)\n arr.sort()\n output = [None] * n\n left = 0\n right = n - 1\n for i in range(n):\n if i % 2 == 0:\n output[i] = arr[left]\n left += 1\n else:\n output[i] = arr[right]\n right -= 1\n for i in range(n):\n arr[i] = output[i]", "def rearrangearray(arr, n):\n arr.sort()\n p = []\n for index in range(n // 2):\n p.append(arr[index])\n p.append(arr[-index - 1])\n p.append(arr[n // 2]) if n % 2 == 1 else None\n arr[:] = p", "def rearrangearray(arr, n):\n res = [0] * n\n arr.sort()\n l = 0\n r = n - 1\n for i in range(n):\n if i % 2 == 0:\n res[i] = arr[l]\n l += 1\n else:\n res[i] = arr[r]\n r -= 1\n for i in range(n):\n arr[i] = res[i]", "def rearrangearray(arr, n):\n arr.sort()\n if n % 2 == 0:\n arr_first = arr[:n // 2]\n arr_end = arr[n // 2:]\n arr_end.reverse()\n else:\n arr_first = arr[:n // 2 + 1]\n arr_end = arr[n // 2:]\n arr_end.reverse()\n if n % 2 == 0:\n for i in range(0, n, 2):\n arr[i] = arr_first.pop(0)\n arr[i + 1] = arr_end.pop(0)\n else:\n for i in range(0, n - 1, 2):\n arr[i] = arr_first.pop(0)\n arr[i + 1] = arr_end.pop(0)\n arr[n - 1] = arr_first.pop(0)", "def rearrangearray(arr, n):\n arr.sort()\n value = arr.copy()\n arr.clear()\n for i in range(n):\n if i % 2 == 0:\n arr.append(value[0])\n value.pop(0)\n if i % 2 != 0:\n arr.append(value[-1])\n value.pop(-1)\n return arr", "def rearrangearray(arr, n):\n ans = []\n arr.sort()\n for i in arr:\n ans.append(i)\n arr.clear()\n if len(ans) == 1:\n for i in ans:\n arr.append(i)\n elif n % 2 != 0:\n s = ans[:n // 2 + 1]\n b = ans[-1:n // 2:-1]\n c = 0\n for i in range(n // 2):\n arr.append(s[i])\n arr.append(b[i])\n c = i\n c = c + 1\n arr.append(s[c])\n else:\n s = ans[:n // 2]\n b = ans[-1:n // 2 - 1:-1]\n c = 0\n for i in range(n // 2):\n arr.append(s[i])\n arr.append(b[i])", "def rearrangearray(arr, n):\n arr.sort()\n t = n // 2\n if n % 2 != 0:\n t = t + 1\n l = arr[:t]\n f = arr[t:]\n f.sort(reverse=True)\n if n % 2 != 0:\n k = 0\n for i in range(0, t - 1):\n arr[k] = l[i]\n arr[k + 1] = f[i]\n k = k + 2\n arr[-1] = l[-1]\n else:\n k = 0\n for i in range(0, t):\n arr[k] = l[i]\n arr[k + 1] = f[i]\n k = k + 2", "def rearrangearray(arr, n):\n arr.sort()\n a = arr.copy()\n small = []\n large = []\n m = 0\n if n % 2 == 0:\n m = (0 + len(arr) - 1) // 2 + 1\n else:\n m = (0 + len(arr) - 1) // 2\n for i in range(m):\n temp = a.pop(0)\n small.append(temp)\n for i in a:\n large.append(i)\n large = large[::-1]\n ans = []\n for i in range(n):\n if len(small) == 0 or len(large) == 0:\n break\n if small and large:\n if i % 2 == 0:\n temp = small.pop(0)\n ans.append(temp)\n else:\n temp = large.pop(0)\n ans.append(temp)\n while small:\n temp = small.pop(0)\n ans.append(temp)\n while large:\n temp = large.pop(0)\n ans.append(temp)\n for i in range(n):\n arr[i] = ans[i]\n return arr", "def rearrangearray(arr, n):\n tmp = [n]\n arr.sort()\n tmp = arr[:]\n i = 0\n j = n - 1\n for k in range(n):\n if k % 2 == 0:\n arr[k] = tmp[i]\n i += 1\n else:\n arr[k] = tmp[j]\n j -= 1\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n ans = []\n lo = 0\n hi = len(arr) - 1\n while lo < hi:\n ans.append(arr[lo])\n lo += 1\n ans.append(arr[hi])\n hi -= 1\n ans.append(arr[lo])\n for i in range(n):\n arr[i] = ans[i]", "def rearrangearray(arr, n):\n asc = sorted(arr)\n desc = sorted(arr, reverse=True)\n j = 0\n k = 0\n for i in range(n):\n if i % 2 == 0:\n arr[i] = asc[j]\n j += 1\n else:\n arr[i] = desc[k]\n k += 1\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n b = []\n if n > 1:\n for i in range(0, n // 2, 1):\n b.append(arr[i])\n b.append(arr[n - 1 - i])\n if n % 2 != 0:\n b.append(arr[i + 1])\n arr[:] = b[:]", "def partition(arr, l, r):\n pivot = arr[r]\n i = l - 1\n for j in range(l, r):\n if arr[j] <= pivot:\n i += 1\n (arr[i], arr[j]) = (arr[j], arr[i])\n (arr[i + 1], arr[r]) = (arr[r], arr[i + 1])\n return i + 1\n\ndef quicksort(arr, l, r):\n if l < r:\n p = self.partition(arr, l, r)\n self.quicksort(arr, l, p - 1)\n self.quicksort(arr, p + 1, r)\n\ndef rearrangearray(arr, n):\n self.quicksort(arr, 0, n - 1)\n new = []\n new.append(arr[0])\n for i in range(1, n // 2 + 1):\n new.append(arr[-i])\n new.append(arr[i])\n for i in range(n):\n arr[i] = new[i]", "def mergesort(arr):\n if len(arr) > 1:\n mid = len(arr) // 2\n L = arr[:mid]\n R = arr[mid:]\n self.mergesort(L)\n self.mergesort(R)\n i = j = k = 0\n while i < len(L) and j < len(R):\n if L[i] < R[j]:\n arr[k] = L[i]\n i += 1\n else:\n arr[k] = R[j]\n j += 1\n k += 1\n while i < len(L):\n arr[k] = L[i]\n k += 1\n i += 1\n while j < len(R):\n arr[k] = R[j]\n k += 1\n j += 1\n\ndef partition(arr, l, r):\n pivot = arr[r]\n i = l - 1\n for j in range(l, r):\n if arr[j] <= pivot:\n i += 1\n (arr[i], arr[j]) = (arr[j], arr[i])\n (arr[i + 1], arr[r]) = (arr[r], arr[i + 1])\n return i + 1\n\ndef quicksort(arr, l, r):\n if l < r:\n p = self.partition(arr, l, r)\n self.quicksort(arr, l, p - 1)\n self.quicksort(arr, p + 1, r)\n\ndef rearrangearray(arr, n):\n arr.sort()\n for i in range(1, n // 2 + 1):\n arr.insert(i * 2 - 1, arr.pop(-1))\n return arr", "def rearrangearray(arr, n):\n a = sorted(arr)\n (start, end) = (0, n - 1)\n for i in range(n):\n if i & 1 == 0:\n arr[i] = a[start]\n start += 1\n else:\n arr[i] = a[end]\n end -= 1", "def rearrangearray(arr, n):\n l = []\n arr.sort()\n for i in range(int((n + 1) / 2)):\n l.append(arr[i])\n if len(l) < len(arr):\n l.append(arr[-1 - i])\n for i in range(0, n):\n arr[i] = l[i]", "def rearrangearray(arr, n):\n sotred_arr = sorted(arr)\n l = 0\n r = n - 1\n i = 0\n while l < r:\n arr[i] = sotred_arr[l]\n i += 1\n arr[i] = sotred_arr[r]\n i += 1\n l += 1\n r -= 1\n if l == r:\n arr[i] = sotred_arr[l]", "def rearrangearray(arr, n):\n arr.sort()\n temp = [0] * (n + 1)\n start = 0\n end = n - 1\n for i in range(len(arr)):\n temp[i] = arr[i]\n for i in range(len(arr)):\n if i % 2 == 0:\n arr[i] = temp[start]\n start += 1\n else:\n arr[i] = temp[end]\n end -= 1\n return arr", "def rearrangearray(arr, n):\n res = [None] * n\n arr.sort()\n ptr = 0\n for i in range(0, n, 2):\n res[i] = arr[ptr]\n ptr += 1\n ptr = -1\n for i in range(1, n, 2):\n res[i] = arr[ptr]\n ptr -= 1\n for i in range(n):\n arr[i] = res[i]", "def rearrangearray(arr, n):\n re = []\n arr.sort()\n l = 0\n r = n - 1\n f = 0\n for i in range(n):\n if f == 0:\n re.append(arr[l])\n l += 1\n f = 1\n else:\n re.append(arr[r])\n f = 0\n r -= 1\n arr[:] = re[:]", "def rearrangearray(arr, n):\n a = sorted(arr)\n b = sorted(arr, reverse=True)\n c = []\n if n % 2 == 0:\n for i in range(n // 2):\n c.append(a[i])\n c.append(b[i])\n else:\n for i in range(n // 2 + 1):\n c.append(a[i])\n c.append(b[i])\n c.pop()\n arr[:] = c", "def rearrangearray(arr, n):\n arr.sort()\n i = 0\n j = n - 1\n a = []\n while i <= j:\n if i != j:\n a.append(arr[i])\n a.append(arr[j])\n else:\n a.append(arr[i])\n i += 1\n j -= 1\n arr[:] = a", "def rearrangearray(arr, n):\n sorted_arr = sorted(arr)\n for i in range(n // 2):\n arr.append(sorted_arr.pop(0))\n arr.append(sorted_arr.pop())\n if len(sorted_arr):\n arr.append(sorted_arr.pop())\n del arr[:n]", "def rearrangearray(arr, n):\n res = []\n arr.sort()\n l = 0\n r = n - 1\n while l < r:\n res.append(arr[l])\n res.append(arr[r])\n l += 1\n r -= 1\n if n % 2 == 1:\n res.append(arr[l])\n arr[:] = res[:]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n m = arr[-1] + 1\n (mn, mx) = (0, n - 1)\n for i in range(n):\n if i % 2 == 0:\n arr[i] = arr[i] + arr[mn] % m * m\n mn += 1\n else:\n arr[i] = arr[i] + arr[mx] % m * m\n mx -= 1\n for i in range(n):\n arr[i] = arr[i] // m\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n (i, j) = (0, n - 1)\n rearrange = []\n while i <= j:\n if i < j:\n rearrange.append(arr[i])\n rearrange.append(arr[j])\n else:\n rearrange.append(arr[i])\n i += 1\n j -= 1\n arr[:] = rearrange[:]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n res = []\n for i in range(n // 2):\n res.append(arr[i])\n res.append(arr[n - i - 1])\n if n % 2:\n res.append(arr[n // 2])\n for i in range(n):\n arr[i] = res[i]\n return arr", "def rearrangearray(arr, n):\n k = 0\n if n % 2 == 0:\n a = n // 2\n else:\n a = n // 2 + 1\n arr.sort()\n lst1 = arr[:a]\n lst2 = sorted(arr[a:], reverse=True)\n if n % 2 == 0:\n for i in range(0, n, 2):\n arr[i] = lst1[k]\n arr[i + 1] = lst2[k]\n k = k + 1\n else:\n for i in range(0, n - 2, 2):\n arr[i] = lst1[k]\n arr[i + 1] = lst2[k]\n k = k + 1\n arr[-1] = lst1[-1]\n return arr", "def rearrangearray(arr, n):\n brr = [0] * n\n for i in range(0, n):\n brr[i] = arr[i]\n brr.sort()\n p = 0\n q = n - 1\n for i in range(0, n):\n if i % 2 == 0:\n arr[i] = brr[p]\n p += 1\n else:\n arr[i] = brr[q]\n q -= 1\n return arr", "def rearrangearray(arr, n):\n arr[:] = list(self.seq(arr, n))\n\ndef seq(arr, n):\n arr.sort()\n j = n // 2\n i = 0\n while i != j:\n i += 1\n yield arr[i - 1]\n yield arr[-i]\n else:\n if n % 2 != 0:\n yield arr[i]", "from itertools import chain\n\ndef rearrangearray(arr, n):\n arr.sort()\n if n % 2 != 0:\n arr[:] = list(chain(*zip(arr[:n // 2 + 1], arr[-1:-n // 2:-1]), [arr[n // 2]]))\n else:\n arr[:] = list(chain(*zip(arr[:n // 2], arr[-1:n // 2 - 1:-1])))", "def rearrangearray(arr, n):\n arr.sort()\n newarr = []\n i = 0\n j = len(arr) - 1\n while i <= j:\n newarr.append(arr[i])\n i += 1\n if i <= j:\n newarr.append(arr[j])\n j -= 1\n arr[:] = newarr\n return newarr", "def rearrangearray(arr, n):\n b = arr.copy()\n b.sort()\n start = 0\n end = n - 1\n for i in range(0, n):\n if i % 2 != 0:\n arr[i] = b[end]\n end -= 1\n else:\n arr[i] = b[start]\n start += 1\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n tmp = n * [None]\n s = 0\n l = n - 1\n flag = 1\n for i in range(n):\n if flag == 1:\n tmp[i] = arr[s]\n s += 1\n else:\n tmp[i] = arr[l]\n l -= 1\n flag = 1 - flag\n for i in range(n):\n arr[i] = tmp[i]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n lis = [0 for i in range(n)]\n c = 1\n for i in range(len(lis)):\n lis[i] = arr[i]\n for i in range(len(lis)):\n if c == 1:\n arr[i] = lis.pop(0)\n c = 0\n elif c == 0:\n arr[i] = lis.pop()\n c = 1\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n low = 0\n high = n - 1\n result = []\n while low < high:\n result.append(arr[low])\n low += 1\n result.append(arr[high])\n high -= 1\n if n % 2 == 1:\n result.append(arr[low])\n arr[:] = result[:]", "def rearrangearray(arr, n):\n x = []\n arr.sort()\n le = 0\n ri = n - 1\n while le < ri:\n x.append(arr[le])\n x.append(arr[ri])\n le += 1\n ri -= 1\n if n % 2 == 1:\n x.append(arr[le])\n for i in range(0, n):\n arr[i] = x[i]", "def rearrangearray(arr, n):\n arr.sort()\n k = 0\n for i in range(n // 2):\n x = arr.pop()\n arr.insert(2 * k + 1, x)\n k += 1\n return arr", "def rearrangearray(arr, n):\n t1 = []\n t2 = []\n f1 = []\n arr.sort()\n if n % 2 == 0:\n t1 = arr[:n // 2]\n t2 = arr[n // 2:]\n else:\n t1 = arr[:n // 2]\n t2 = arr[n // 2:]\n t2.sort(reverse=True)\n for x in range(0, n // 2):\n f1.append(t1[x])\n f1.append(t2[x])\n if len(t2) > len(t1):\n f1.append(t2[len(t2) - 1])\n for j in range(0, n):\n arr[j] = f1[j]", "def rearrangearray(arr, n):\n if len(arr) % 2 != 0:\n mid = len(arr) // 2 + 1\n else:\n mid = len(arr) // 2\n arr.sort()\n temp = [0] * len(arr)\n k = 0\n for i in range(mid):\n temp[k] = arr[i]\n k += 2\n k = 1\n for i in range(len(arr) - 1, mid - 1, -1):\n temp[k] = arr[i]\n k += 2\n for i in range(len(arr)):\n arr[i] = temp[i]", "def rearrangearray(arr, n):\n arr.sort()\n l = []\n start = 0\n end = n - 1\n while start <= end:\n l.append(arr[start])\n l.append(arr[end])\n end -= 1\n start += 1\n if n % 2 != 0:\n m = l[0:len(l) - 1]\n else:\n m1 = l\n for i in range(n):\n arr[i] = l[i]", "def rearrangearray(arr, n):\n temp = sorted(arr)\n counter = 0\n for i in range(n):\n if i % 2 == 0:\n arr[i] = temp[i // 2]\n else:\n counter += 1\n arr[i] = temp[n - counter]", "def rearrangearray(arr, n):\n arr.sort()\n result = [None] * n\n for i in range(1, n, 2):\n value = arr.pop()\n result[i] = value\n x = 0\n for j in range(0, len(result), 2):\n result[j] = arr[x]\n x = x + 1\n arr.clear()\n for i in range(len(result)):\n arr.append(result[i])", "def rearrangearray(arr, n):\n arr.sort()\n a = []\n for i in range(n // 2 + 1):\n a.append(arr[i])\n a.append(arr[n - i - 1])\n for i in range(n):\n arr[i] = a[i]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n i = 1\n for _ in range(n // 2):\n arr.insert(i, arr.pop())\n i += 2\n return arr", "from itertools import cycle\n\ndef rearrangearray(arr, n):\n t = arr\n arr.sort()\n if n % 2 == 1:\n a = arr[0:int(n / 2) + 1]\n else:\n a = arr[0:int(n / 2)]\n t.sort(reverse=True)\n b = t[0:int(n / 2)]\n iters = [iter(a), iter(b)]\n d = list((iter.__next__() for iter in cycle(iters)))\n for i in range(0, n):\n arr[i] = d[i]\n return arr", "def rearrangearray(arr, n):\n temp = [0] * n\n arr.sort()\n k = 0\n j = n - 1\n flag = True\n for i in range(n):\n if flag == True:\n temp[i] = arr[k]\n k = k + 1\n else:\n temp[i] = arr[j]\n j = j - 1\n flag = bool(1 - flag)\n for i in range(n):\n arr[i] = temp[i]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n temp_arr = [0] * (n + 1)\n i = 0\n j = n - 1\n a = 0\n while i <= n // 2 and j >= n // 2:\n temp_arr[a] = arr[i]\n a += 1\n i += 1\n temp_arr[a] = arr[j]\n a += 1\n j -= 1\n for i in range(n):\n arr[i] = temp_arr[i]\n return arr", "def rearrangearray(arr, n):\n k = []\n arr.sort()\n for i in range(n):\n k.append(arr[i])\n k.append(arr[n - 1 - i])\n for i in range(n):\n arr[i] = k[i]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n l = len(arr) // 2\n a = arr[:l]\n b = arr[l:]\n c = []\n b.reverse()\n while a or b:\n if len(a):\n c.append(a.pop(0))\n if len(b):\n c.append(b.pop(0))\n arr[:] = c[:]\n return arr", "def rearrangearray(arr, n):\n arr.sort()\n res = arr.copy()\n j = n - 1\n k = 0\n for i in range(n):\n if i % 2 == 0:\n arr[i] = res[k]\n k += 1\n else:\n arr[i] = res[j]\n j -= 1"], "starter_code": "def rearrangearray(arr, n):\n", "input_output": {"inputs": ["n = 9\narr[] = {1, 9, 2, 8, 3, 7, 4, 6, 5}", "n = 4\narr[] = {1, 2, 3, 4}"], "outputs": ["1 9 2 8 3 7 4 6 5", "1 4 2 3"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/rearrange-the-array5802/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n*logn)", "entry_point": "rearrangearray", "task_id": "TACO_lite/290", "example": [[], []]} +{"requirement": "For all x in the range of integers [0, 2 ** n), let y[x] be the binary exclusive-or of x and x // 2. Find the sum of all numbers in y.\n\nWrite a function sum_them that, given n, will return the value of the above sum.\n\nThis can be implemented a simple loop as shown in the initial code. But once n starts getting to higher numbers, such as 2000 (which will be tested), the loop is too slow.\n\nThere is a simple solution that can quickly find the sum. Find it!\n\nAssume that n is a nonnegative integer.\n\nHint: The complete solution can be written in two lines.", "solutions": ["def sum_them(n):\n return 2 ** (n - 1) * (2 ** n - 1)", "sum_them = lambda n: int('1' * n, 2) * (int('1' * n, 2) + 1) // 2 if n else 0", "sum_them = lambda n: int(n * '1' + ~-n * '0' or '0', 2)", "def sum_them(n):\n return n and int('1' * n + '0' * (n - 1), 2)", "sum_them = lambda n: ~-2 ** n * 2 ** (~-n)", "def sum_them(n):\n return (1 << n) - 1 << n - 1 if n > 0 else 0"], "starter_code": "def sum_them(n):\n", "input_output": {"fn_name": "sum_them", "inputs": [[0], [1], [2], [3], [4]], "outputs": [[0], [1], [6], [28], [120]]}, "difficulty": "EASY", "raw_tags": ["Puzzles", "Binary"], "name": null, "source": "codewars", "tags": ["Bit manipulation", "Ad-hoc"], "skill_types": ["Bit manipulation"], "url": "https://www.codewars.com/kata/549c7ae26d86c7c3ed000b87", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sum_them", "task_id": "TACO_lite/254", "example": [[[1], [2], [3], [4]], [1, 6, 28, 120]]} +{"requirement": "Given a string str, convert the first letter of each word in the string to uppercase. \nExample 1:\nInput:\nstr = \"i love programming\"\nOutput: \"I Love Programming\"\nExplanation:\n'I', 'L', 'P' are the first letters of \nthe three words.\nYour Task: \nYou dont need to read input or print anything. Complete the function transform() which takes s as input parameter and returns the transformed string.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N) to store resultant string \nConstraints:\n1 <= N <= 10^{4}\nThe original string str only consists of lowercase alphabets and spaces to separate words.", "solutions": ["import string\n\ndef transform(s):\n return string.capwords(s)", "def transform(s):\n return s.title()", "def transform(s):\n l = s.split()\n res = []\n for i in l:\n if len(i) == 1:\n i = i.upper()\n res.append(i)\n else:\n i = i[0].upper() + i[1:]\n res.append(i)\n return ' '.join(res)", "def transform(s):\n a = s.split()\n b = []\n c = []\n for i in range(len(a)):\n b.append(a[i][0].upper())\n c.append(b[i] + a[i][1:])\n return ' '.join(c)", "def transform(s):\n newstr = ''\n for i in range(len(s)):\n if s[i - 1] == ' ' or i == 0:\n n = ord(s[i]) - 32\n newstr = newstr + chr(n)\n else:\n newstr = newstr + s[i]\n return newstr", "def transform(s):\n return ' '.join([i[0].upper() + i[1:] for i in s.split()])", "def transform(s):\n word = s.split()\n c = [s.capitalize() for s in word]\n return ' '.join(c)", "def transform(s):\n r = s[0].upper()\n for i in range(1, len(s)):\n if s[i - 1] == ' ':\n r += s[i].upper()\n else:\n r += s[i]\n return r", "def transform(s):\n res = s.split()\n res = [i.title() for i in res]\n l = ' '.join(res)\n return l", "def transform(s):\n s2 = s.split(' ')\n res = ''\n for i in s2:\n res = res + i.capitalize() + ' '\n return res", "def transform(s):\n s = s.lower()\n words = s.split(' ')\n transformed_words = [word.capitalize() for word in words]\n transformed_string = ' '.join(transformed_words)\n return transformed_string", "def transform(s):\n res = ''\n s = s.capitalize()\n isSpace = False\n for e in s:\n ele = e\n if isSpace:\n isSpace = False\n res = res + e.upper()\n else:\n res = res + e\n if ele == ' ':\n isSpace = True\n return res", "def transform(s):\n l = s.split()\n for i in range(len(l)):\n l[i] = l[i].title()\n return ' '.join(l)", "def transform(s):\n result = []\n str = s.split()\n for i in str:\n if len(i) == 1:\n result.append(i.upper())\n if len(i) > 1:\n result.append(i[0].upper() + i[1:])\n return ' '.join(result)", "def transform(s):\n l = s.split()\n str_upper = ''\n for i in l:\n str_upper = str_upper + i.capitalize() + ' '\n return str_upper", "def transform(s):\n string = s.split(' ')\n list1 = []\n for i in string:\n result = i.capitalize()\n list1.append(result)\n string = ','.join(list1)\n result = string.replace(',', ' ')\n return result", "def transform(s):\n s = list(s)\n s[0] = s[0].capitalize()\n for i in range(len(s)):\n if s[i] == ' ':\n s[i + 1] = s[i + 1].capitalize()\n s = ''.join(s)\n return s", "def transform(s):\n str_list = s.split()\n str = ''\n for i in str_list:\n str += i.capitalize() + ' '\n return str", "def transform(s):\n ans = ''\n for i in s:\n return s.title()", "def transform(s):\n s = ' ' + s\n s = list(s)\n for i in range(len(s)):\n if s[i] == ' ':\n s[i + 1] = s[i + 1].upper()\n s = s[1:]\n s = ''.join(s)\n return s", "def transform(s):\n ans = ''\n ans += chr(ord(s[0]) - 32)\n for i in range(0, len(s) - 1):\n if s[i] == ' ':\n ans += chr(ord(s[i + 1]) - 32)\n else:\n ans += s[i + 1]\n return ans", "def transform(s):\n list_s = s.split()\n result = ''\n for each in list_s:\n result += each.capitalize() + ' '\n return result", "def transform(s):\n lst = s.split(' ')\n res = []\n for i in lst:\n res.append(i.lower().capitalize())\n S = ' '.join(res)\n return S", "def transform(s):\n Words = s.split(' ')\n words = []\n for word in Words:\n words.append(word.lower().capitalize())\n return ' '.join(words)", "def transform(s):\n t = s.split()\n p = [r.capitalize() for r in t]\n return ' '.join(p)", "def transform(s):\n words = list(s.split(' '))\n w = []\n for i in range(len(words)):\n w += [words[i].capitalize()]\n return ' '.join(w)", "def transform(s):\n ans = ''\n for i in range(0, len(s), 1):\n if i == 0:\n ans += s[i].upper()\n elif (ord(s[i]) >= ord('a') and ord(s[i]) <= ord('z')) and ord(s[i - 1]) == ord(' '):\n ans += s[i].upper()\n else:\n ans += s[i]\n return ans", "def transform(s):\n inp_list = list(s.split(' '))\n out_list = []\n for word in inp_list:\n temp_list = list(word)\n temp_list[0] = temp_list[0].upper()\n out_list.append(''.join(temp_list))\n return ' '.join(out_list)", "def transform(s):\n rs = s.split()\n result = ''\n for i in rs:\n result += i.capitalize() + ' '\n return result", "def transform(s):\n ls = []\n lt = list(s)\n ls.append(lt[0].upper())\n i = 1\n while i < len(lt):\n if lt[i] == ' ':\n ls.append(lt[i])\n ls.append(lt[i + 1].upper())\n i = i + 2\n else:\n ls.append(lt[i])\n i = i + 1\n return ''.join(ls)", "def transform(s):\n l = []\n for i in s.split():\n l.append(i.capitalize())\n return ' '.join(l)", "def transform(s):\n words = s.split()\n new_str = []\n final_str = ''\n for i in words:\n new_str.append(i.capitalize())\n for j in new_str:\n final_str = final_str + j + ' '\n return final_str", "def transform(s):\n S = str(s)\n return S.title()", "def transform(s):\n s = s.split()\n S = ''\n for i in s:\n S += i.capitalize() + ' '\n return S", "def transform(s):\n result = ''\n temp = ''\n for i in s:\n if i == ' ':\n result += temp.capitalize()\n result += ' '\n temp = ''\n else:\n temp += i\n result += temp.capitalize()\n return result", "def transform(str):\n str = str.title()\n return str", "def transform(s):\n a = s.split()\n ans = []\n for i in range(len(a)):\n b = a[i].capitalize()\n ans.append(b)\n return ' '.join(ans)", "def transform(s):\n result = ''\n found = False\n for i in range(len(s)):\n if i != 0:\n if s[i] == ' ':\n result = result + s[i]\n result = result + s[i + 1].capitalize()\n found = True\n else:\n if i != 0:\n if found == True:\n found = False\n continue\n result = result + s[i]\n else:\n if i == 0:\n result = result + s[i].capitalize()\n continue\n if i != 0:\n if found == True:\n found = False\n continue\n result = result + s[i]\n return result", "def transform(s):\n words = s.split()\n output_string = ''\n for i in words:\n output_string = output_string + i.capitalize() + ' '\n return output_string", "def transform(s):\n temp = ''\n temp += s[0].upper()\n n = len(s)\n for i in range(1, n):\n if s[i] != ' ' and s[i - 1] == ' ':\n temp += s[i].upper()\n else:\n temp += s[i]\n return temp", "def transform(s):\n r = s.split()\n p = ''\n for i in r:\n p += i.capitalize() + ' '\n return p", "def transform(s):\n s_list = s.split(' ')\n n_list = []\n for w in s_list:\n n = w[0].upper() + w[1:]\n n_list.append(n)\n return ' '.join(n_list)"], "starter_code": "def transform(s):\n", "input_output": {"inputs": ["str = \"i love programming\""], "outputs": ["\"I Love Programming\""]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/upper-case-conversion5419/1", "Expected Auxiliary Space": "O(N) to store resultant string", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "transform", "task_id": "TACO_lite/347", "example": [[["i love programming"]], ["I Love Programming"]]} +{"requirement": "Gematria is an Assyro-Babylonian-Greek system of code and numerology later adopted into Jewish culture. The system assigns numerical value to a word or a phrase in the belief that words or phrases with identical numerical values bear some relation to each other or bear some relation to the number itself. While more commonly used on Hebrew words, there is also an English version.\n\nEach letter has a value and the gematrian value of a word or a phrase is the sum of those values. The code takes a word or an expression and returns the gematrian value of it.\n\nThe calculation is case insensitive and counts no spaces. \n\nExample: The gematrian value of \"love\" is 20+50+700+5 = 775\n\n\u200eThese are the values of the different letters:\n\na=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, k=10, l=20,\nm=30, n=40, o=50, p=60, q=70, r=80, s=90, t=100, u=200,\nx=300, y=400, z=500, j=600, v=700, w=900", "solutions": ["TOME = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'k': 10, 'l': 20, 'm': 30, 'n': 40, 'o': 50, 'p': 60, 'q': 70, 'r': 80, 's': 90, 't': 100, 'u': 200, 'x': 300, 'y': 400, 'z': 500, 'j': 600, 'v': 700, 'w': 900}\n\ndef gematria(s):\n return sum((TOME.get(c, 0) for c in s.lower()))", "gematria = lambda s, d=dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, k=10, l=20, m=30, n=40, o=50, p=60, q=70, r=80, s=90, t=100, u=200, x=300, y=400, z=500, j=600, v=700, w=900): sum(map(d.get, filter(str.islower, s.lower())))", "from string import ascii_lowercase\n\ndef gematria(strng):\n values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 600, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 700, 900, 300, 400, 500]\n alphabet_values = {letter: num for (num, letter) in zip(values, ascii_lowercase)}\n return sum([alphabet_values[letter] if letter in ascii_lowercase else 0 for letter in strng.lower()])"], "starter_code": "def gematria(string):\n", "input_output": {"fn_name": "gematria", "inputs": [["love"], ["jaels"], ["JAELS"], ["Devil"], ["Coding is fun"]], "outputs": [[775], [716], [716], [738], [458]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/573c91c5eaffa3bd350000b0", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "gematria", "task_id": "TACO_lite/388", "example": [[["love"]], ["775"]]} +{"requirement": "A string S of lowercase letters is given.\u00a0 Then, we may make any number of moves.\nIn each move, we\u00a0choose one\u00a0of the first K letters (starting from the left), remove it,\u00a0and place it at the end of the string.\nReturn the lexicographically smallest string we could have after any number of moves.\n\u00a0\n\nExample 1:\nInput: S = \"cba\", K = 1\nOutput: \"acb\"\nExplanation: \nIn the first move, we move the 1st character (\"c\") to the end, obtaining the string \"bac\".\nIn the second move, we move the 1st character (\"b\") to the end, obtaining the final result \"acb\".\n\n\nExample 2:\nInput: S = \"baaca\", K = 3\nOutput: \"aaabc\"\nExplanation: \nIn the first move, we move the 1st character (\"b\") to the end, obtaining the string \"aacab\".\nIn the second move, we move the 3rd character (\"c\") to the end, obtaining the final result \"aaabc\".\n\n\u00a0\nNote:\n\n1 <= K <= S.length\u00a0<= 1000\nS\u00a0consists of lowercase letters only.", "solutions": ["def orderlyqueue(S: str, K: int) -> str:\n if K >= 2:\n return ''.join(sorted(S))\n length = len(S)\n S = S + S\n (i, j, k) = (0, 1, 0)\n while j + k < len(S) and k < length:\n if S[i + k] == S[j + k]:\n k += 1\n continue\n elif S[i + k] < S[j + k]:\n j = j + k + 1\n else:\n i = max(i + k + 1, j)\n j = i + 1\n k = 0\n return S[i:i + length]", "def orderlyqueue(S: str, K: int) -> str:\n if K == 1:\n tmp = S\n for i in range(len(S)):\n S = S[1:] + str(S[0])\n if S < tmp:\n tmp = S\n return tmp\n else:\n return ''.join(sorted(S))", "def orderlyqueue(s: str, k: int) -> str:\n s = [c for c in s]\n if k == 1:\n temp = []\n for i in range(len(s)):\n temp_s = s[i:] + s[:i]\n temp.append(''.join(temp_s))\n temp.sort()\n return temp[0]\n else:\n return ''.join(sorted(s))"], "starter_code": "def orderlyqueue(S: str, K: int) -> str:\n", "input_output": {"fn_name": "orderlyQueue", "inputs": [["\"cba\"", 1]], "outputs": ["\"\"cba"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Math", "Sorting", "String"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Sorting", "Mathematics"], "skill_types": ["Sorting"], "url": "https://leetcode.com/problems/orderly-queue/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "orderlyqueue", "task_id": "TACO_lite/350", "example": [[["cba", 1], ["baaca", 3]], ["acb", "aaabc"]]} +{"requirement": "Jack and Jill are playing a game. They have balls numbered from `0` to `n - 1`. Jack looks the other way and asks Jill to reverse the position of the balls, for instance, to change the order from say, `0,1,2,3` to `3,2,1,0`. He further asks Jill to reverse the position of the balls `n` times, each time starting from one position further to the right, till she reaches the last ball. So, Jill has to reverse the positions of the ball starting from position `0`, then from position `1`, then from position `2` and so on. At the end of the game, Jill will ask Jack to guess the final position of any ball numbered `k`. \n\nYou will be given `2` integers, the first will be `n`(balls numbered from `0` to `n-1`) and the second will be `k`. You will return the position of the ball numbered `k` after the rearrangement.\n\n```Perl\nsolve(4,1) = 3. The reversals are [0,1,2,3] -> [3,2,1,0] -> [3,0,1,2] -> [3,0,2,1]. => 1 is in position 3.\n```\n\nMore examples in the test cases. Good luck!", "solutions": ["def solve(count, ball_number):\n assert isinstance(count, int)\n assert isinstance(ball_number, int)\n balls = list(range(count))\n for idx in range(count):\n balls = balls[:idx] + balls[idx:][::-1]\n return balls.index(ball_number)", "solve = lambda n, k: 2 * (n - k - 1, k + 0.5)[k < n // 2]", "def solve(n, k):\n res = list(range(n))\n for i in range(n):\n res = res[:i] + res[i:][::-1]\n return res.index(k)", "def solve(n, k):\n second_half = k >= n // 2\n return (-1) ** second_half * 2 * k + second_half * (n * 2 - 3) + 1", "def solve(n, k):\n arr = []\n for i in range(n % 2 + n // 2):\n arr += [n - i - 1] + [i]\n return arr.index(k)", "def solve(n, k):\n a = list()\n for i in range(int(n / 2) + 1):\n a += [n - 1 - i, i]\n return a.index(k)", "def solve(n, k):\n return 2 * k + 1 if k <= n // 2 - 1 else 2 * (n - k - 1)", "def solve(n, k):\n list1 = list(range(n))\n list1_values = list(list1)\n ball = list1[k]\n counter = 0\n final_list = []\n for i in range(n):\n list1.reverse()\n final_list.append(list1.pop(0))\n position = final_list.index(ball)\n return position", "def solve(n, k):\n result = {}\n (index, start, end) = (0, 0, n - 1)\n while start <= end:\n result[end] = index\n index += 1\n if start != end:\n result[start] = index\n index += 1\n start += 1\n end -= 1\n return result[k]"], "starter_code": "def solve(n,k):\n", "input_output": {"fn_name": "solve", "inputs": [[4, 1], [4, 2], [4, 3], [20, 8], [20, 9], [20, 10]], "outputs": [[3], [2], [0], [17], [19], [18]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Puzzles"], "name": null, "source": "codewars", "tags": ["Mathematics", "Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/5b93636ba28ce032600000b7", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/323", "example": [[[4, 1]], ["3"]]} +{"requirement": "Given an array of unique integers salary\u00a0where salary[i] is the salary of the employee i.\nReturn the average salary of employees excluding the minimum and maximum salary.\n\u00a0\nExample 1:\nInput: salary = [4000,3000,1000,2000]\nOutput: 2500.00000\nExplanation: Minimum salary and maximum salary are 1000 and 4000 respectively.\nAverage salary excluding minimum and maximum salary is (2000+3000)/2= 2500\n\nExample 2:\nInput: salary = [1000,2000,3000]\nOutput: 2000.00000\nExplanation: Minimum salary and maximum salary are 1000 and 3000 respectively.\nAverage salary excluding minimum and maximum salary is (2000)/1= 2000\n\nExample 3:\nInput: salary = [6000,5000,4000,3000,2000,1000]\nOutput: 3500.00000\n\nExample 4:\nInput: salary = [8000,9000,2000,3000,6000,1000]\nOutput: 4750.00000\n\n\u00a0\nConstraints:\n\n3 <= salary.length <= 100\n10^3\u00a0<= salary[i] <= 10^6\nsalary[i] is unique.\nAnswers within 10^-5 of the actual value will be accepted as correct.", "solutions": ["def average(salary: List[int]) -> float:\n salary.sort()\n del salary[0]\n del salary[-1]\n return sum(salary) / len(salary)", "def average(salary: List[int]) -> float:\n minSalary = min(salary)\n maxSalary = max(salary)\n total = sum(salary)\n return (total - minSalary - maxSalary) / (len(salary) - 2)", "def average(salary: List[int]) -> float:\n salary.sort()\n salary.pop()\n salary.pop(0)\n return sum(salary) / len(salary)", "def average(salary: List[int]) -> float:\n minSalary = None\n maxSalary = None\n s = 0\n for n in salary:\n s = s + n\n if minSalary is None or n < minSalary:\n minSalary = n\n if maxSalary is None or n > maxSalary:\n maxSalary = n\n return (s - minSalary - maxSalary) * 1.0 / (len(salary) - 2)", "def average(salary: List[int]) -> float:\n return (sum(salary) - min(salary) - max(salary)) / (len(salary) - 2)", "def average(salary: List[int]) -> float:\n salary.sort()\n newSalaryList = salary[1:-1]\n numSalaries = len(newSalaryList)\n return sum(newSalaryList) / numSalaries"], "starter_code": "def average(salary: List[int]) -> float:\n", "input_output": {"fn_name": "average", "inputs": [[[1000, 2000, 3000, 4000]]], "outputs": [2500.0]}, "difficulty": "EASY", "raw_tags": ["Array", "Sorting"], "name": null, "source": "leetcode", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "average", "task_id": "TACO_lite/292", "example": [[[[4000, 3000, 1000, 2000]], [[1000, 2000, 3000]], [[6000, 5000, 4000, 3000, 2000, 1000]], [[8000, 9000, 2000, 3000, 6000, 1000]]], ["2500.0", "2000.0", "3500.0", "4750.0"]]} +{"requirement": "Given an input A , print the data type of the input A.\neg:-Sequence of digits -- int\n Sequence of digits with a dot -- float\n Sequence of chars -- string\n Single non-digit char --- char\n \nExample 1:\nInput: A = \"12\"\nOutput: \"int\"\nExplanation: The input consists only of\ndigits.\nExample 2:\nInput: A = \"gfg\"\nOutput: \"string\"\nExplanation: The input consists only of\ncharacters.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function FindInputType() which takes A as input parameter and returns data type of A.\n \nExpected Time Complexity: O(|A|)\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= |A| <= 1000", "solutions": ["def findinputtype(str):\n if str.isdigit():\n return 'int'\n if '.' in str:\n p = str.split('.')\n if p[-1].isdigit() and p[-2].isdigit() and (len(p) == 2) or (p[-1].isdigit() and p[-2] == '' and (len(p) == 2)):\n return 'float'\n elif len(str) > 1:\n return 'string'\n if len(str) == 1:\n return 'char'\n elif len(str) > 1:\n return 'string'", "def findinputtype(str):\n s = str\n ans = 'string'\n if len(s) == 1:\n if s.isalpha() or s.__contains__('.'):\n ans = 'char'\n else:\n ans = 'int'\n elif s.count('.') == 1:\n try:\n s1 = s.split('.')\n if len(s1[1]) != 0:\n s = float(s)\n ans = 'float'\n except:\n ans = 'string'\n else:\n try:\n s1 = int(s)\n ans = 'int'\n except:\n ans = 'string'\n return ans", "def findinputtype(str):\n size = len(str)\n ans = ''\n (flag, init) = (0, 0)\n for i in range(size):\n if str[i] != '.' and str[i] > '9' or (str[i] != '.' and str[i] < '0'):\n init = 1\n if str[i] == '.':\n flag += 1\n if str[size - 1] == '.' and size != 1:\n ans = 'string'\n elif init == 0 and flag == 1 and (size > 1):\n ans = 'float'\n elif init == 0 and flag == 0:\n ans = 'int'\n elif size == 1:\n ans = 'char'\n else:\n ans = 'string'\n return ans", "def findinputtype(str):\n if len(str) == 1:\n if str.isnumeric():\n return 'int'\n return 'char'\n for i in str:\n if i.isalpha():\n return 'string'\n else:\n if '.' in str:\n a = str.split('.')\n if len(a) == 2 and len(a[1]) > 0 and (len(a[0]) >= 0):\n return 'float'\n else:\n return 'int'\n return 'string'"], "starter_code": "def findinputtype(str):\n", "input_output": {"inputs": ["A = \"12\"", "A = \"gfg\""], "outputs": ["\"int\"", "\"string\""]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/type-of-input5910/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|A|)", "entry_point": "findinputtype", "task_id": "TACO_lite/306", "example": [[["12"], ["gfg"]], ["int", "string"]]} +{"requirement": "Given an array of integers A, consider all non-empty subsequences of A.\nFor any sequence S, let the\u00a0width\u00a0of S be the difference between the maximum and minimum element of S.\nReturn the sum of the widths of all subsequences of A.\u00a0\nAs the answer may be very large, return the answer modulo 10^9 + 7.\n\n\u00a0\nExample 1:\nInput: [2,1,3]\nOutput: 6\nExplanation:\nSubsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\nThe corresponding widths are 0, 0, 0, 1, 1, 2, 2.\nThe sum of these widths is 6.\n\n\u00a0\nNote:\n\n1 <= A.length <= 20000\n1 <= A[i] <= 20000", "solutions": ["def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n (ret, mod, p) = (0, 10 ** 9 + 7, 1)\n for i in range(len(A)):\n ret += (A[i] - A[len(A) - i - 1]) * p % mod\n p = (p << 1) % mod\n return ret % mod", "mod_ = 10 ** 9 + 7\n\ndef sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n n = len(A)\n p_2 = [1]\n for i in range(1, n + 2):\n p_2.append(p_2[-1] * 2 % mod_)\n l = [0]\n for i in range(1, n):\n l.append((2 * l[-1] + (A[i] - A[i - 1]) * (p_2[i] - 1)) % mod_)\n sol = 0\n for elem in l:\n sol = (sol + elem) % mod_\n return sol", "def sumsubseqwidths(A: List[int]) -> int:\n ret = 0\n for (i, n) in enumerate(sorted(A)):\n ret += n * pow(2, i)\n ret -= n * pow(2, len(A) - i - 1)\n ret %= 10 ** 9 + 7\n return ret", "from bisect import bisect_left, bisect_right\n\ndef sumsubseqwidths(A: List[int]) -> int:\n n = len(A)\n ret = 0\n A.sort()\n ret = 0\n f = {}\n for (i, x) in enumerate(A):\n if x not in f:\n f[x] = [i, i]\n else:\n f[x][1] = i\n ret = 0\n for x in f:\n (l, r) = f[x]\n sl = l\n sr = n - r - 1\n se = r - l + 1\n ret += (2 ** sl - 1) * (2 ** se - 1) * x\n ret -= (2 ** sr - 1) * (2 ** se - 1) * x\n return ret % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n MOD = 10 ** 9 + 7\n N = len(A)\n A.sort()\n pow2 = [1]\n for i in range(1, N):\n pow2.append(pow2[-1] * 2 % MOD)\n ans = 0\n for (i, x) in enumerate(A):\n ans = (ans + (pow2[i] - pow2[N - 1 - i]) * x) % MOD\n return ans", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n total_cnt = 0\n total_prod = 0\n ans = 0\n for num in A:\n ans = (ans + total_cnt * num - total_prod) % self.BASE\n total_cnt = (2 * total_cnt + 1) % self.BASE\n total_prod = (2 * total_prod + num) % self.BASE\n return ans", "def sumsubseqwidths(A: List[int]) -> int:\n aa = sorted(A)\n n = len(A)\n res = 0\n md = 10 ** 9 + 7\n p2 = [1] * n\n for i in range(1, n):\n p2[i] = p2[i - 1] * 2 % md\n for i in range(n):\n res = (res + aa[i] * (p2[i] - p2[n - i - 1])) % md\n return res", "def sumsubseqwidths(A: List[int]) -> int:\n N = len(A)\n if N == 1:\n return 0\n MOD = 10 ** 9 + 7\n A.sort()\n pow2 = [1]\n widths = 0\n for i in range(1, N):\n pow2.append(pow2[-1] * 2 % MOD)\n for i in range(N):\n widths = (widths + (pow2[i] - pow2[N - 1 - i]) * A[i]) % MOD\n return widths", "from collections import deque\n\ndef sumsubseqwidths(A: List[int]) -> int:\n n = len(A)\n MOD = 10 ** 9 + 7\n pows = [1] * n\n for i in range(1, n):\n pows[i] = pows[i - 1] * 2 % MOD\n A.sort()\n ans = 0\n for (i, v) in enumerate(A):\n ans += pows[i] * v - pows[n - 1 - i] * v\n ans %= MOD\n return ans % MOD", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n result = 0\n for i in range(len(A)):\n result *= 2\n result -= A[i]\n result += A[~i]\n return result % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n if len(A) == 1:\n return 0\n if len(A) == 0:\n return 0\n (ans, prev, n, mod) = (A[1] - A[0], A[1] - A[0], len(A), 1000000000.0 + 7)\n (twoPow, temp) = ([1], 2)\n for i in range(1, n):\n twoPow.append(temp + twoPow[-1])\n temp = temp * 2 % mod\n for i in range(2, len(A)):\n diff = A[i] - A[i - 1]\n prev = (2 * (prev + diff * twoPow[i - 2] % mod) % mod + diff) % mod\n ans = (ans + prev) % mod\n return int(ans)", "def sumsubseqwidths(A: List[int]) -> int:\n res = 0\n n = len(A)\n M = 10 ** 9 + 7\n c = 1\n A.sort()\n for i in range(n):\n res = (res + A[i] * c - A[n - i - 1] * c) % M\n c = (c << 1) % M\n return res", "def sumsubseqwidths(A: List[int]) -> int:\n size = len(A)\n mod = 10 ** 9 + 7\n pow_mod = [1] * size\n for i in range(1, size):\n pow_mod[i] = pow_mod[i - 1] * 2 % mod\n A.sort()\n ans = 0\n for i in range(size):\n ans += A[i] * ((pow_mod[i] - pow_mod[size - 1 - i]) % mod) % mod\n ans %= mod\n return ans", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n res = 0\n n = len(A)\n for i in range(n):\n res += A[i] * 1 << i % 1000000007\n res -= A[i] * 1 << n - i - 1\n return res % 1000000007", "def sumsubseqwidths(A: List[int]) -> int:\n MOD = 10 ** 9 + 7\n A.sort()\n result = 0\n prev = 0\n for i in range(1, len(A)):\n d = A[i] - A[i - 1]\n prev = (2 * prev + d * (pow(2, i, MOD) - 1)) % MOD\n result = (result + prev) % MOD\n return result", "def sumsubseqwidths(A):\n return sum((((1 << i) - (1 << len(A) - i - 1)) * a for (i, a) in enumerate(sorted(A)))) % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n B = sorted(A)\n res = 0\n mod = 10 ** 9 + 7\n for i in range(len(B)):\n res += B[i] * ((1 << i) - (1 << len(B) - i - 1))\n return res % mod", "def sumsubseqwidths(A: List[int]) -> int:\n if not A:\n return 0\n ans = 0\n A.sort()\n for (i, n) in enumerate(A):\n ans += ((1 << i) - (1 << len(A) - i - 1)) * n\n return ans % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n return sum(((1 << i) * num - (1 << len(A) - i - 1) * num for (i, num) in enumerate(sorted(A)))) % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n mod = 10 ** 9 + 7\n A.sort()\n n = len(A)\n return sum((a * ((1 << i) - (1 << n - i - 1)) for (i, a) in enumerate(A))) % mod", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n LIM = 10 ** 9 + 7\n res = 0\n powTable = [1]\n for _ in range(len(A)):\n powTable.append(2 * powTable[-1] % LIM)\n for (i, val) in enumerate(A):\n res = (res + val * powTable[i] - val * powTable[len(A) - i - 1]) % LIM\n return res", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n total = 0\n MOD = 10 ** 9 + 7\n powerSum = 2 ** 0\n counter = 2\n currSum = A[0]\n for i in range(1, len(A)):\n total += powerSum * A[i] - currSum\n currSum *= 2\n currSum += A[i]\n powerSum += counter\n counter *= 2\n return total % MOD", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n S = 0\n B = [1] * len(A)\n for i in range(1, len(B)):\n B[i] = 2 * B[i - 1]\n for i in range(len(A)):\n S += (B[i] - B[-1 - i]) * A[i]\n return S % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n l = len(A)\n p = [1]\n ans = 0\n for i in range(1, l):\n p.append(p[-1] * 2)\n for (i, j) in enumerate(A):\n ans += (p[i] - p[l - i - 1]) * j\n return ans % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n n = len(A)\n total = 0\n for i in range(n):\n a = A[i]\n left = i\n right = n - i - 1\n total += ((1 << left) - 1) * a\n total -= ((1 << right) - 1) * a\n return total % (10 ** 9 + 7)", "def sumsubseqwidths(nums):\n res = 0\n for (i, num) in enumerate(sorted(nums)):\n res += ((1 << i) - (1 << len(nums) - i - 1)) * num\n return res % 1000000007", "def sumsubseqwidths(A: List[int]) -> int:\n A = sorted(A)\n r = 0\n m = 10 ** 9 + 7\n for i in range(len(A) - 1):\n r += (A[i + 1] - A[i]) * ((1 << len(A)) - (1 << i + 1) - (1 << len(A) - i - 1) + 1)\n r %= m\n return r", "from bisect import bisect_left, bisect_right\n\ndef sumsubseqwidths(A: List[int]) -> int:\n n = len(A)\n ret = 0\n A.sort()\n MOD = 10 ** 9 + 7\n\n def bimod(n):\n if n == 0:\n return 1\n di = bimod(n // 2)\n if n % 2 == 0:\n return di * di % MOD\n return di * di * 2 % MOD\n\n def nonempty(n):\n return bimod(n) - 1\n i = 0\n while i < n:\n j = i\n while j < n and A[j] == A[i]:\n j += 1\n se = j - i\n sl = i\n sr = n - j\n ret = (ret + A[i] * nonempty(se) * (nonempty(sl) - nonempty(sr)) % MOD) % MOD\n i = j\n return ret % MOD", "def sumsubseqwidths(A: List[int]) -> int:\n A = sorted(A)\n (total, cur, cnt) = (0, 0, 0)\n MOD = 10 ** 9 + 7\n for i in range(1, len(A)):\n cnt *= 2\n cnt += 1\n cur *= 2\n cur += (A[i] - A[i - 1]) * cnt\n cur %= MOD\n total += cur\n total %= MOD\n return total", "def sumsubseqwidths(A: List[int]) -> int:\n A = sorted(A)\n res = 0\n MOD = 10 ** 9 + 7\n c = 1\n for i in range(len(A)):\n res = (res + A[i] * c % MOD) % MOD\n c <<= 1\n c %= MOD\n c = 1\n for i in range(len(A) - 1, -1, -1):\n res = (res - A[i] * c % MOD) % MOD\n c <<= 1\n c %= MOD\n return (res + MOD) % MOD", "def sumsubseqwidths(A: List[int]) -> int:\n POW2 = [1 << i for i in range(len(A))]\n return sum(((POW2[i] - POW2[len(A) - 1 - i]) * n for (i, n) in enumerate(sorted(A)))) % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n mod = 10 ** 9 + 7\n n = len(A)\n A.sort()\n B = [A[i] - A[n - i - 1] for i in range(n)]\n ans = 0\n for (i, v) in enumerate(B):\n ans = (ans + (v << i)) % mod\n return ans", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n res = 0\n mod = 10 ** 9 + 7\n N = len(A)\n for i in range(len(A)):\n res += ((1 << i) - (1 << N - i - 1)) * A[i] % mod\n return res % mod", "def sumsubseqwidths(A: List[int]) -> int:\n N = len(A)\n A = sorted(A)\n MODS = 10 ** 9 + 7\n (pow2, res) = ([1], 0)\n for ii in range(1, N):\n pow2.append(2 * pow2[-1] % MODS)\n for (ii, jj) in enumerate(A):\n res = (res + (pow2[ii] - pow2[N - ii - 1]) * jj) % MODS\n return res", "def sumsubseqwidths(A: List[int]) -> int:\n mod = 10 ** 9 + 7\n A.sort()\n n = len(A)\n ans = 0\n\n def exp(n):\n res = 1\n x = 2\n while n:\n if n & 1:\n res = res * x % mod\n n = n >> 1\n x = x * x % mod\n return res\n for i in range(n):\n ans = (ans + exp(i) * A[i] - exp(n - i - 1) * A[i] + mod) % mod\n return ans", "def sumsubseqwidths(A: List[int]) -> int:\n mod = 10 ** 9 + 7\n n = len(A)\n if n == 1:\n return 0\n pow = [1]\n for i in range(1, n):\n pow.append(pow[-1] * 2 % mod)\n A = sorted(A)\n s = 0\n for (i, elem) in enumerate(A):\n (n_max, n_min) = (i, n - i - 1)\n N1 = pow[i]\n N2 = pow[n - i - 1]\n s += elem * (N1 - N2) % (10 ** 9 + 7)\n s = s % (10 ** 9 + 7)\n return s", "def sumsubseqwidths(A: List[int]) -> int:\n MOD = 10 ** 9 + 7\n A = sorted(A)\n if len(A) == 1:\n return 0\n lastaddon = 0\n lastv = 0\n for i in range(1, len(A)):\n lastaddon = 2 * lastaddon + (2 ** i - 1) * (A[i] - A[i - 1])\n lastv += lastaddon\n return lastv % MOD", "def sumsubseqwidths(A: List[int]) -> int:\n n = len(A)\n widthsum = 0\n mod = 10 ** 9 + 7\n A.sort()\n p = s = 0\n (pre, suf) = ([], [])\n for i in range(n):\n p += A[i]\n s += A[-i - 1]\n pre.append(p)\n suf.append(s)\n for l in range(n):\n widthsum += 2 ** l * (suf[l] - pre[l])\n widthsum %= mod\n return widthsum", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n N = len(A)\n return sum((num * (2 ** i - 2 ** (N - i - 1)) for (i, num) in enumerate(A))) % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n Mod = 1000000000.0 + 7\n n = len(A)\n twoPower = [1]\n while len(twoPower) < n:\n twoPower.append(twoPower[len(twoPower) - 1] * 2 % Mod)\n A.sort()\n ans = 0\n for (i, a) in enumerate(A):\n left = i\n right = n - i - 1\n ans = (ans + (twoPower[left] - twoPower[right]) * a) % Mod\n return int((ans + Mod) % Mod)", "def sumsubseqwidths(A: List[int], recursed=False) -> int:\n return sum((x * (2 ** i - 2 ** (len(A) - i - 1)) for (i, x) in enumerate(sorted(A)))) % (int(1000000000.0) + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n A = sorted(A)\n length = len(A)\n _sum = 0\n for i in range(length):\n _sum += A[i] * 2 ** i\n for i in range(length):\n _sum -= A[i] * 2 ** (length - i - 1)\n return _sum % (10 ** 9 + 7)", "def sumsubseqwidths(A: List[int]) -> int:\n A.sort()\n total = 0\n const = 10 ** 9 + 7\n for i in range(len(A)):\n total += 2 ** i * A[i] - 2 ** (len(A) - i - 1) * A[i]\n total = total % const\n return total"], "starter_code": "def sumsubseqwidths(A: List[int]) -> int:\n", "input_output": {"fn_name": "sumSubseqWidths", "inputs": [[[1, 2, 3]]], "outputs": [6]}, "difficulty": "MEDIUM", "raw_tags": ["Math", "Sorting", "Array"], "name": null, "source": "leetcode", "tags": ["Sorting", "Data structures", "Mathematics"], "skill_types": ["Sorting", "Data structures"], "url": "https://leetcode.com/problems/sum-of-subsequence-widths/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sumsubseqwidths", "task_id": "TACO_lite/371", "example": [[[[2, 1, 3]]], ["6"]]} +{"requirement": "Given two strings S1 and S2 . Print \"1\" if both strings are anagrams otherwise print \"0\" .\nNote: An anagram of a string is another string with exactly the same quantity of each character in it, in any order.\nExample 1:\nInput: S1 = \"cdbkdub\" , S2 = \"dsbkcsdn\"\nOutput: 0 \nExplanation: Length of S1 is not same\nas length of S2.\nExample 2:\nInput: S1 = \"geeks\" , S2 = \"skgee\"\nOutput: 1\nExplanation: S1 has the same quantity \nof each character in it as S2.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function areAnagram() which takes S1 and S2 as input and returns \"1\" if both strings are anagrams otherwise returns \"0\".\nExpected Time Complexity: O(n)\nExpected Auxiliary Space: O(K) ,Where K= Contstant\nConstraints:\n1 <= |S1| <= 1000\n1 <= |S2| <= 1000", "solutions": ["def areanagram(ob, S1, S2):\n if sorted(S1) == sorted(S2):\n return '1'\n else:\n return '0'", "def areanagram(ob, s1, s2):\n h = {}\n k = {}\n for i in s1:\n if i not in h:\n h[i] = 1\n else:\n h[i] += 1\n for i in s2:\n if i not in k:\n k[i] = 1\n else:\n k[i] += 1\n if h == k:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n x = list(S1)\n x = sorted(x)\n b = ''.join(x)\n y = list(S2)\n y = sorted(y)\n a = ''.join(y)\n if a == b:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n b = [*S1]\n c = [*S2]\n b.sort()\n c.sort()\n if b == c:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n op = sorted(S1)\n pk = sorted(S2)\n return 1 if op == pk else 0", "def areanagram(ob, S1, S2):\n freq = {}\n for i in S1:\n if i not in freq:\n freq[i] = 0\n freq[i] += 1\n for i in S2:\n if i not in freq:\n return 0\n else:\n freq[i] -= 1\n for i in freq:\n if freq[i]:\n return 0\n return 1", "def areanagram(ob, s1, s2):\n if len(s1) != len(s2):\n return 0\n count = [0] * 256\n for i in range(len(s1)):\n count[ord(s1[i])] += 1\n count[ord(s2[i])] -= 1\n for i in count:\n if i != 0:\n return 0\n return 1", "def areanagram(ob, s1, s2):\n if len(s1) != len(s2):\n return 0\n else:\n a = sorted(s1)\n b = sorted(s2)\n if a == b:\n return 1\n return 0", "def areanagram(ob, S1, S2):\n s = sorted(S1)\n s2 = sorted(S2)\n if s == s2:\n return 1\n return 0", "def areanagram(ob, S1, S2):\n a = list(S1)\n b = list(S2)\n a.sort()\n b.sort()\n if a == b:\n return 1\n return 0", "from collections import defaultdict\n\ndef areanagram(ob, S1, S2):\n store = defaultdict(lambda : 0)\n for item in S1:\n store[item] += 1\n for item in S2:\n store[item] -= 1\n return int(set(store.values()) == set([0]))", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n else:\n for i in range(0, len(S1)):\n if S1[i] not in S2 or S1.count(S1[i]) != S2.count(S1[i]):\n return 0\n return 1", "def areanagram(ob, S1, S2):\n l1 = list(S2)\n l2 = list(S1)\n l1.sort()\n l2.sort()\n if l1 == l2:\n return 1\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n else:\n S1 = sorted(S1)\n S2 = sorted(S2)\n for i in range(len(S1)):\n if S1[i] != S2[i]:\n return 0\n return 1", "def areanagram(ob, S1, S2):\n S1 = list(S1)\n S1.sort()\n S2 = list(S2)\n S2.sort()\n if S1 == S2:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n dict1 = {}\n dict2 = {}\n if len(S1) != len(S2):\n return 0\n for i in S1:\n if i not in dict1:\n dict1[i] = 1\n else:\n dict1[i] += 1\n for i in S2:\n if i not in dict2:\n dict2[i] = 1\n else:\n dict2[i] += 1\n count = 0\n for i in dict1:\n if i not in dict2:\n return 0\n if dict1[i] == dict2[i]:\n count += 1\n if count == len(dict1):\n return 1\n return 0", "def areanagram(ob, S1, S2):\n from collections import Counter\n return 1 if Counter(S1) == Counter(S2) else 0", "def areanagram(ob, S1, S2):\n s11 = ''.join(sorted(S1))\n s12 = ''.join(sorted(S2))\n if s11 == s12:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n else:\n str1 = sorted(S1)\n str2 = sorted(S2)\n if str1 == str2:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n s1_list = list(S1)\n s1_list.sort()\n s2_list = list(S2)\n s2_list.sort()\n if len(s1_list) == len(s2_list) and s1_list == s2_list:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n res1 = ''.join(sorted(S1))\n res2 = ''.join(sorted(S2))\n if res1 == res2:\n return '1'\n else:\n return '0'", "def areanagram(ob, s1, s2):\n if len(s1) != len(s2):\n return 0\n else:\n pcount = {}\n scount = {}\n for i in range(len(s1)):\n pcount[s1[i]] = pcount.get(s1[i], 0) + 1\n scount[s2[i]] = scount.get(s2[i], 0) + 1\n ans = 1 if scount == pcount else 0\n return ans", "def areanagram(ob, S1, S2):\n a = sorted(S1)\n b = sorted(S2)\n if len(a) == len(b):\n if a == b:\n return 1\n else:\n return 0\n else:\n return 0", "def areanagram(ob, S1, S2):\n S1 = sorted(list(S1))\n S2 = sorted(list(S2))\n return int(S1 == S2)", "def areanagram(ob, S1, S2):\n hashmap = {}\n if len(S1) != len(S2):\n return 0\n i = 0\n while i < len(S1):\n if S1[i] in hashmap:\n hashmap[S1[i]] += 1\n else:\n hashmap[S1[i]] = 1\n if S2[i] in hashmap:\n hashmap[S2[i]] -= 1\n else:\n hashmap[S2[i]] = -1\n i += 1\n for i in hashmap.values():\n if i != 0:\n return 0\n return 1", "def areanagram(ob, S1, S2):\n str1 = []\n str2 = []\n if len(S1) == len(S2):\n for i in S1:\n str1.append(i)\n for j in S2:\n str2.append(j)\n str1.sort()\n str2.sort()\n if str1 == str2:\n return 1\n else:\n return 0\n else:\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n l = [0] * 26\n for i in range(len(S1)):\n l[ord(S1[i]) - ord('a')] += 1\n l[ord(S2[i]) - ord('a')] -= 1\n for i in range(26):\n if l[i] != 0:\n return 0\n return 1", "def areanagram(ob, s1, s2):\n if sorted(s1) == sorted(s2):\n return 1\n return 0", "def areanagram(ob, S1, S2):\n s1 = {}\n s2 = {}\n for i in S1:\n if i not in s1:\n s1[i] = 1\n else:\n s1[i] += 1\n for j in S2:\n if j not in s2:\n s2[j] = 1\n else:\n s2[j] += 1\n if s1 == s2:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) == len(S2) and set(S1) == set(S2):\n for i in set(S1):\n if S1.count(i) != S2.count(i):\n return '0'\n return '1'\n return '0'", "def areanagram(ob, S1, S2):\n d1 = {}\n d2 = {}\n if len(S1) == len(S2):\n for i in S1:\n if i in d1:\n d1[i] = d1[i] + 1\n elif i not in d1:\n d1[i] = 1\n for j in S2:\n if j in d2:\n d2[j] = d2[j] + 1\n elif j not in d2:\n d2[j] = 1\n for k in d1:\n if d1 == d2:\n if d1[k] == d2[k]:\n return 1\n else:\n return 0\n else:\n return 0", "def areanagram(ob, S1, S2):\n d1 = {k: 0 for k in set(S1)}\n d2 = {k: 0 for k in set(S2)}\n for i in S1:\n d1[i] += 1\n for i in S2:\n d2[i] += 1\n if d1 == d2:\n return 1\n return 0", "def areanagram(ob, S1, S2):\n d = {}\n for i in S1:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for j in S2:\n if j in d:\n d[j] -= 1\n else:\n d[j] = 1\n for i in d:\n if d[i] != 0:\n return '0'\n return '1'", "from collections import defaultdict\n\ndef areanagram(ob, S1, S2):\n d1 = defaultdict(lambda : 0)\n for letter in S1:\n d1[letter] += 1\n for letter in S2:\n if d1[letter] >= 1:\n d1[letter] -= 1\n else:\n return '0'\n return '1'", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n c = 0\n S1 = sorted(S1)\n S2 = sorted(S2)\n if S1 == S2:\n return 1\n return 0", "def areanagram(ob, S1, S2):\n dict1 = ob.str__dict(S1)\n dict2 = ob.str__dict(S2)\n if dict1 == dict2:\n return 1\n else:\n return 0\n\ndef str__dict(ob, lst):\n dict = {}\n for i in lst:\n if i in dict:\n continue\n t = lst.count(i)\n dict[i] = t\n return dict", "def areanagram(ob, S1, S2):\n res = ''.join(sorted(S1))\n res1 = ''.join(sorted(S2))\n if res == res1:\n return 1\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n s1 = sorted(S1)\n s2 = sorted(S2)\n return 1 if s1 == s2 else 0", "def areanagram(ob, S1, S2):\n l1 = len(S1)\n l2 = len(S2)\n if l1 != l2:\n return 0\n if sorted(S1) == sorted(S2):\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n a = 0\n b = 0\n for i in range(len(S1)):\n a = a + ord(S1[i])\n for j in range(len(S2)):\n b = b + ord(S2[j])\n if a == b:\n return 1\n else:\n return 0", "def areanagram(ob, S1, S2):\n if len(S1) != len(S2):\n return 0\n S2 = list(S2)\n for i in S1:\n if i in S2:\n S2.remove(i)\n if not S2:\n return 1\n return 0", "def areanagram(ob, S1, S2):\n S1 = list(S1)\n S1.sort()\n S2 = list(S2)\n S2.sort()\n return int(S1 == S2)"], "starter_code": "def areanagram(ob, S1, S2):\n", "input_output": {"inputs": ["S1 = \"cdbkdub\" , S2 = \"dsbkcsdn\"", "S1 = \"geeks\" , S2 = \"skgee\""], "outputs": ["0", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Java"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/java-anagram-strings3549/1", "Expected Auxiliary Space": "O(K) ,Where K= Contstant", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "areanagram", "task_id": "TACO_lite/356", "example": [[["cdbkdub", "dsbkcsdn"], ["geeks", "skgee"]], [null, null]]} +{"requirement": "You have a very large square wall and a circular dartboard placed on the wall.\u00a0You have been challenged to throw darts into the board blindfolded.\u00a0Darts thrown at the wall are represented as an array of\u00a0points on a 2D plane.\u00a0\nReturn\u00a0the maximum number of points that are within or\u00a0lie\u00a0on\u00a0any circular dartboard of radius\u00a0r.\n\u00a0\nExample 1:\n\nInput: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 2\nOutput: 4\nExplanation: Circle dartboard with center in (0,0) and radius = 2 contain all points.\n\nExample 2:\n\nInput: points = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5\nOutput: 5\nExplanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).\n\nExample 3:\nInput: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 1\nOutput: 1\n\nExample 4:\nInput: points = [[1,2],[3,5],[1,-1],[2,3],[4,1],[1,3]], r = 2\nOutput: 4\n\n\u00a0\nConstraints:\n\n1 <= points.length <= 100\npoints[i].length == 2\n-10^4 <= points[i][0], points[i][1] <= 10^4\n1 <= r <= 5000", "solutions": ["def numpoints(points: List[List[int]], r: int) -> int:\n ans = 1\n for (x, y) in points:\n angles = []\n for (x1, y1) in points:\n if (x1 != x or y1 != y) and (d := sqrt((x1 - x) ** 2 + (y1 - y) ** 2)) <= 2 * r:\n angle = atan2(y1 - y, x1 - x)\n delta = acos(d / (2 * r))\n angles.append((angle - delta, +1))\n angles.append((angle + delta, -1))\n angles.sort(key=lambda x: (x[0], -x[1]))\n val = 1\n for (_, entry) in angles:\n ans = max(ans, (val := (val + entry)))\n return ans", "from math import sqrt\n\ndef numpoints(points: List[List[int]], r: int) -> int:\n n = len(points)\n if n <= 2:\n return n\n best = 1\n rr = r ** 2\n for i in range(n):\n for j in range(i + 1, n):\n [x1, y1] = points[i]\n [x2, y2] = points[j]\n xm = (x1 + x2) / 2\n ym = (y1 + y2) / 2\n q = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n qq = (q / 2) ** 2\n rq = rr - qq\n if rq < 0:\n continue\n xc = xm + sqrt(rq) * (y1 - y2) / q\n yc = ym + sqrt(rq) * (x2 - x1) / q\n curr = 2\n for k in range(n):\n if k == i or k == j:\n continue\n [x, y] = points[k]\n if sqrt((x - xc) ** 2 + (y - yc) ** 2) <= r:\n curr += 1\n best = max(best, curr)\n return best", "def numpoints(A: List[List[int]], r: int) -> int:\n res = 1\n for ((x1, y1), (x2, y2)) in itertools.combinations(A, 2):\n d = ((x1 - x2) ** 2 + (y1 - y2) ** 2) / 4.0\n if d > r * r:\n continue\n x0 = (x1 + x2) / 2.0 + (y2 - y1) * (r * r - d) ** 0.5 / (d * 4) ** 0.5\n y0 = (y1 + y2) / 2.0 - (x2 - x1) * (r * r - d) ** 0.5 / (d * 4) ** 0.5\n res = max(res, sum(((x - x0) ** 2 + (y - y0) ** 2 <= r * r + 1e-05 for (x, y) in A)))\n return res", "def numpoints(points: List[List[int]], r: int) -> int:\n max_pts = 500\n dis = [[0 for _ in range(max_pts)] for _ in range(max_pts)]\n\n def getPointsInside(i, r, n):\n angles = []\n for j in range(n):\n if i != j and dis[i][j] <= 2 * r:\n B = math.acos(dis[i][j] / (2 * r))\n (x1, y1) = points[i]\n (x2, y2) = points[j]\n A = math.atan2(y1 - y2, x1 - x2)\n alpha = A - B\n beta = A + B\n angles.append((alpha, False))\n angles.append((beta, True))\n angles.sort()\n (cnt, res) = (1, 1)\n for angle in angles:\n if angle[1] == 0:\n cnt += 1\n else:\n cnt -= 1\n res = max(cnt, res)\n return res\n n = len(points)\n for i in range(n - 1):\n for j in range(i + 1, n):\n (x1, y1) = points[i]\n (x2, y2) = points[j]\n dis[i][j] = dis[j][i] = sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\n ans = 0\n for i in range(n):\n ans = max(ans, getPointsInside(i, r, n))\n return ans", "def numpoints(points: List[List[int]], r: int) -> int:\n ans = 1\n for ((x1, y1), (x2, y2)) in itertools.combinations(points, 2):\n q = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\n if q > 2 * r + 1e-05:\n continue\n x0 = (x1 + x2) / 2 + math.sqrt(r ** 2 - (q / 2) ** 2) * (y1 - y2) / q\n y0 = (y1 + y2) / 2 + math.sqrt(r ** 2 - (q / 2) ** 2) * (x2 - x1) / q\n ans = max(ans, sum((1 for (x, y) in points if (x - x0) ** 2 + (y - y0) ** 2 <= r ** 2 + 1e-05)))\n return ans", "def numpoints(points: List[List[int]], r: int) -> int:\n\n def count(x0, y0):\n nonlocal ans\n cnt = 0\n for (x, y) in points:\n if (x - x0) * (x - x0) + (y - y0) * (y - y0) <= r * r + 1e-06:\n cnt += 1\n ans = max(ans, cnt)\n n = len(points)\n ans = 1\n for i in range(n):\n for j in range(i + 1, n):\n (x1, y1) = points[i]\n (x2, y2) = points[j]\n (x_mid, y_mid) = ((x1 + x2) / 2, (y1 + y2) / 2)\n sq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)\n d = r * r - sq / 4\n if d < 0:\n continue\n d = sqrt(d)\n sq = sqrt(sq)\n sin = abs(x1 - x2) / sq\n cos = abs(y1 - y2) / sq\n if (x2 - x1) * (y1 - y2) < 0:\n cos = -cos\n (x0, y0) = (x_mid - d * cos, y_mid - d * sin)\n count(x0, y0)\n (x0, y0) = (x_mid + d * cos, y_mid + d * sin)\n count(x0, y0)\n return ans", "def numpoints(points: List[List[int]], r: int) -> int:\n res = 1\n for (x, y) in points:\n order = []\n for (x1, y1) in points:\n if x != x1 or y != y1:\n d = math.sqrt((x1 - x) ** 2 + (y1 - y) ** 2)\n if d <= 2 * r:\n delta = math.acos(d / (2 * r))\n angle = math.atan2(y1 - y, x1 - x)\n order.append((angle - delta, 1))\n order.append((angle + delta, -1))\n order.sort(key=lambda x: (x[0], -x[1]))\n count = 1\n for (_, entry) in order:\n count += entry\n res = max(res, count)\n return res", "def numpoints(points: List[List[int]], r: int) -> int:\n n = len(points)\n ans = 1\n for i in range(n - 1):\n (x1, y1) = (points[i][0], points[i][1])\n for j in range(i + 1, n):\n (x2, y2) = (points[j][0], points[j][1])\n d = (x1 - x2) ** 2 + (y1 - y2) ** 2\n if d > 4 * r * r:\n continue\n (cx, cy) = ((x1 + x2) / 2, (y1 + y2) / 2)\n h = math.sqrt(r * r - d / 4)\n if y1 == y2:\n (dx, dy) = (0, h)\n else:\n m = -(x1 - x2) / (y1 - y2)\n (dx, dy) = (h / math.sqrt(1 + m * m), h * m / math.sqrt(1 + m * m))\n for sign in [1, -1]:\n count = 0\n (px, py) = (cx + sign * dx, cy + sign * dy)\n for (k, (x, y)) in enumerate(points):\n if (x - px) ** 2 + (y - py) ** 2 <= r * r + 1e-07:\n count += 1\n ans = max(ans, count)\n return ans", "def numpoints(points: List[List[int]], r: int) -> int:\n best = 1\n for i in range(len(points)):\n p1 = complex(*points[i])\n for j in range(i + 1, len(points)):\n p2 = complex(*points[j])\n d = abs(p1 - p2)\n if d > 2 * r:\n continue\n h = math.sqrt(r * r - d * d / 4)\n c = (p1 + p2) / 2 + (p1 - p2) * h / d * 1j\n count = 0\n for (x, y) in points:\n if (x - c.real) ** 2 + (y - c.imag) ** 2 <= r ** 2 + 1e-06:\n count += 1\n best = max(best, count)\n return best", "def numpoints(points: List[List[int]], r: int) -> int:\n eps = 1e-09\n ret = 1\n n = len(points)\n if n == 1:\n return ret\n points.sort()\n\n def isect(x1, y1, x2, y2):\n dx2 = (x2 - x1) ** 2\n dy2 = (y2 - y1) ** 2\n if dx2 + dy2 > 4 * r * r:\n return []\n cx = (x1 + x2) / 2\n cy = (y1 + y2) / 2\n if dx2 + dy2 == 4 * r * r:\n return [(cx, cy)]\n ss2 = (dx2 + dy2) / 4\n ol = math.sqrt(r ** 2 - ss2)\n diffx = ol * math.sqrt(dy2 / (dx2 + dy2))\n diffy = ol * math.sqrt(dx2 / (dx2 + dy2))\n return [(cx - diffx, cy + diffy), (cx + diffx, cy - diffy)]\n for i in range(n - 1):\n (a, b) = points[i]\n for j in range(i + 1, n):\n (c, d) = points[j]\n l = isect(a, b, c, d)\n for (x, y) in l:\n cur = 0\n lb = bisect.bisect_left(points, [x - r - eps, y - r - eps])\n ub = bisect.bisect_right(points, [x + r + eps, y + r + eps])\n for k in range(lb, ub):\n dx = points[k][0] - x\n dy = points[k][1] - y\n if dx ** 2 + dy ** 2 <= (r + eps) ** 2:\n cur += 1\n ret = max(ret, cur)\n return ret", "def numpoints(points: List[List[int]], r: int) -> int:\n\n def find(cx, cy, r):\n ans = 0\n for (x, y) in points:\n if (x - cx) ** 2 + (y - cy) ** 2 <= r ** 2 + 1e-06:\n ans += 1\n return ans\n ans = 1\n for i in range(len(points)):\n (x1, y1) = points[i]\n for j in range(i + 1, len(points)):\n (x2, y2) = points[j]\n deno = (y1 - y2) ** 2 + (x1 - x2) ** 2\n if deno > 4 * r * r:\n continue\n k = math.sqrt(r * r / deno - 0.25)\n ans = max(ans, max((find((x1 + x2) / 2 + t * (y1 - y2), (y1 + y2) / 2 - t * (x1 - x2), r) for t in (k, -k))))\n return ans", "import math as m\n\ndef dist(p1, p2):\n dx = p1[0] - p2[0]\n dy = p1[1] - p2[1]\n return m.sqrt(dx * dx + dy * dy)\n\ndef intersect(p1, p2, r):\n res = []\n d = self.dist(p1, p2) - 2 * r\n if d > 0:\n res = []\n elif d == 0:\n res = [[(p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2]]\n else:\n mid_x = (0.0 + p1[0] + p2[0]) / 2\n mid_y = (0.0 + p1[1] + p2[1]) / 2\n if p1[1] != p2[1]:\n ratio = -(0.0 + p1[0] - p2[0]) / (0.0 + p1[1] - p2[1])\n eps = m.sqrt((r ** 2 - self.dist([mid_x, mid_y], p1) ** 2) / (ratio ** 2 + 1))\n fun = eps * ratio\n else:\n eps = 0\n fun = m.sqrt(r ** 2 - self.dist([mid_x, mid_y], p1) ** 2)\n res = [[mid_x + eps, mid_y + fun], [mid_x - eps, mid_y - fun]]\n return res\n\ndef numpoints(points, r):\n l = len(points)\n result = 1\n for i in range(l):\n for j in range(i + 1, l):\n c = self.intersect(points[i], points[j], r)\n for p in c:\n au = 0\n for k in range(l):\n if self.dist(p, points[k]) <= r:\n au += 1\n result = max(result, au)\n return result", "import math\n\ndef numpoints(points: List[List[int]], r: int) -> int:\n self.total = len(points)\n maxPoints = 0\n for i in range(self.total):\n maxPoints = max(maxPoints, self.numpointsInCircle(points, r, i))\n return maxPoints\n\ndef numpointsInCircle(points, r, chosenIndex):\n maxPoints = 0\n enterList = []\n exitList = []\n numberPoints = 0\n for i in range(self.total):\n answer = self.computeRange(points, r, chosenIndex, i)\n if answer != None:\n if len(answer) == 0:\n numberPoints += 1\n else:\n (enterAngle, exitAngle) = answer\n enterList.append(enterAngle)\n exitList.append(exitAngle)\n if enterAngle > exitAngle:\n numberPoints += 1\n exitList.sort()\n enterList.sort()\n maxPoints = numberPoints\n exitCounter = 0\n enterCounter = 0\n pointsToCheck = len(exitList)\n while max(exitCounter, enterCounter) < pointsToCheck:\n currentExit = exitList[exitCounter]\n currentEnter = enterList[enterCounter]\n if currentEnter <= currentExit:\n numberPoints += 1\n maxPoints = max(maxPoints, numberPoints)\n enterCounter += 1\n else:\n numberPoints -= 1\n exitCounter += 1\n while exitCounter < pointsToCheck:\n numberPoints -= 1\n exitCounter += 1\n while enterCounter < pointsToCheck:\n numberPoints += 1\n maxPoints = max(maxPoints, numberPoints)\n enterCounter += 1\n return maxPoints\n\ndef computeRange(points, r, chosenIndex, otherIndex):\n chosenPair = points[chosenIndex]\n otherPair = points[otherIndex]\n if chosenPair == otherPair:\n return []\n else:\n distance = self.distanceBetweenPoints(chosenPair, otherPair)\n if distance > 2 * r:\n return None\n else:\n angleOne = self.computeAngle(chosenPair, otherPair)\n angleTwo = math.acos(distance / (2 * r))\n exit = angleOne + angleTwo\n exit = exit - 2 * math.pi if exit >= math.pi else exit\n enter = angleOne - angleTwo\n enter = enter + 2 * math.pi if enter < -math.pi else enter\n return [enter, exit]\n\ndef computeAngle(pairOne, pairTwo):\n (x1, y1) = pairOne\n (x2, y2) = pairTwo\n return math.atan2(y2 - y1, x2 - x1)\n\ndef numberPointsStart(enterList, exitList):\n pass\n\ndef distanceBetweenPoints(pairOne, pairTwo):\n (x1, y1) = pairOne\n (x2, y2) = pairTwo\n return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)", "import math\nfrom decimal import Decimal as D\n\ndef numpoints(points: List[List[int]], r: int) -> int:\n\n def circles_from_p1p2r(p1, p2, r):\n ((x1, y1), (x2, y2)) = (p1, p2)\n (dx, dy) = (x2 - x1, y2 - y1)\n q = math.sqrt(dx ** 2 + dy ** 2)\n if q > 2.0 * r:\n return []\n (x3, y3) = ((x1 + x2) / 2, (y1 + y2) / 2)\n d = math.sqrt(r ** 2 - (q / 2) ** 2)\n c1 = [x3 - d * dy / q, y3 + d * dx / q]\n c2 = [x3 + d * dy / q, y3 - d * dx / q]\n return [c1, c2]\n res = 0\n n = len(points)\n for p in range(n):\n for q in range(p + 1, n):\n TwoCirs = circles_from_p1p2r(points[p], points[q], r)\n for center in TwoCirs:\n cnt = 0\n for dots in points:\n if (dots[0] - center[0]) ** 2 + (dots[1] - center[1]) ** 2 <= r ** 2 + 10 ** (-6):\n cnt += 1\n res = max(res, cnt)\n return res if res else 1", "def getC(p1, p2, r):\n ([x1, y1], [x2, y2]) = (p1, p2)\n dist = sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\n if dist > 2.0 * r:\n return []\n (x3, y3) = ((x1 + x2) / 2, (y1 + y2) / 2)\n magnitude = sqrt(r ** 2 - (dist / 2) ** 2)\n c1 = [x3 - magnitude * (y1 - y2) / dist, y3 + magnitude * (x1 - x2) / dist]\n c2 = [x3 + magnitude * (y1 - y2) / dist, y3 - magnitude * (x1 - x2) / dist]\n return [c1, c2]\n\ndef numpoints(points: List[List[int]], r: int) -> int:\n ans = 0\n for i in range(len(points)):\n for j in range(i + 1, len(points)):\n C = self.getC(points[i], points[j], r)\n for c in C:\n cnt = 0\n for pt in points:\n if (pt[0] - c[0]) ** 2 + (pt[1] - c[1]) ** 2 <= r ** 2 + 1e-06:\n cnt += 1\n ans = max(ans, cnt)\n return ans if ans else 1", "def numpoints(points: List[List[int]], r: int) -> int:\n n = len(points)\n result = 1\n\n def calc_dist(pt1, pt2):\n (x1, y1) = pt1\n (x2, y2) = pt2\n return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\n\n def get_centers(i, j):\n d_xy = calc_dist(points[i], points[j])\n if d_xy > r * 2:\n return []\n delta_x = points[j][0] - points[i][0]\n delta_y = points[j][1] - points[i][1]\n x_mid = points[i][0] + delta_x / 2\n y_mid = points[i][1] + delta_y / 2\n if d_xy == r * 2:\n return [(x_mid, y_mid)]\n d = math.sqrt(r ** 2 - (d_xy / 2) ** 2)\n return [(x_mid + d * delta_y / d_xy, y_mid - d * delta_x / d_xy), (x_mid - d * delta_y / d_xy, y_mid + d * delta_x / d_xy)]\n\n def count_points_inside(center, i, j):\n count = 2\n for idx in range(n):\n if idx == i or idx == j:\n continue\n count += calc_dist(center, points[idx]) <= r\n return count\n for i in range(n):\n for j in range(i + 1, n):\n centers = get_centers(i, j)\n for center in centers:\n result = max(result, count_points_inside(center, i, j))\n return result", "def numpoints(points: List[List[int]], r: int) -> int:\n\n def within(pt, cen, r2):\n (a1, a2) = pt\n (p1, p2) = cen\n return (a1 - p1) ** 2 + (a2 - p2) ** 2 <= r2\n ans = 1\n for (idx, a) in enumerate(points):\n for b in points[:idx]:\n (a1, a2) = a\n (b1, b2) = b\n if (a1 - b1) ** 2 + (a2 - b2) ** 2 <= 4 * r ** 2:\n pos_cir = 0\n neg_cir = 0\n mid = ((a1 + b1) / 2, (a2 + b2) / 2)\n perp = (b2 - a2, a1 - b1)\n perp_dis = (perp[0] ** 2 + perp[1] ** 2) ** 0.5\n p_dis = (r ** 2 - ((a1 - b1) ** 2 + (a2 - b2) ** 2) / 4) ** 0.5\n cen = (mid[0] + perp[0] * p_dis / perp_dis, mid[1] + perp[1] * p_dis / perp_dis)\n ocen = (mid[0] + perp[0] * p_dis / perp_dis, mid[1] + perp[1] * p_dis / perp_dis)\n for c in points:\n if within(c, cen, r ** 2 + 1e-08):\n pos_cir += 1\n if within(c, ocen, r ** 2 + 1e-08):\n neg_cir += 1\n ans = max(ans, pos_cir, neg_cir)\n return ans", "def numpoints(points: List[List[int]], r: int) -> int:\n\n def getpoints(l, i, r, n, dis):\n d = {}\n pi = 3.1415626\n angles = []\n for j in range(n):\n if i != j and dis[i][j] <= 2 * r:\n B = math.acos(dis[i][j] / (2 * r))\n A = math.acos((l[j][0] - l[i][0]) / dis[i][j])\n if l[j][1] - l[i][1] < 0:\n A = 2 * pi - A\n a = A - B\n b = A + B\n angles.append((a, 0))\n angles.append((b, 1))\n angles.sort()\n ct = 1\n res = 1\n for a in angles:\n if a[1] == 0:\n ct += 1\n else:\n ct -= 1\n res = max(res, ct)\n return res\n n = len(points)\n dis = [[0 for j in range(n)] for i in range(n)]\n for i in range(n - 1):\n for j in range(i + 1, n):\n dis[i][j] = ((points[i][0] - points[j][0]) ** 2 + (points[i][1] - points[j][1]) ** 2) ** 0.5\n dis[j][i] = ((points[i][0] - points[j][0]) ** 2 + (points[i][1] - points[j][1]) ** 2) ** 0.5\n ans = 0\n for i in range(n):\n ans = max(ans, getpoints(points, i, r, n, dis))\n return ans", "import itertools\n\ndef numpoints(points: List[List[int]], r: int) -> int:\n ans = 1\n for ((x1, y1), (x2, y2)) in itertools.combinations(points, 2):\n d = ((x1 - x2) ** 2 + (y1 - y2) ** 2) / 4.0\n if d <= r * r:\n x0 = (x1 + x2) / 2.0 + (y2 - y1) * (r * r - d) ** 0.5 / (d * 4) ** 0.5\n y0 = (y1 + y2) / 2.0 - (x2 - x1) * (r * r - d) ** 0.5 / (d * 4) ** 0.5\n ans = max(ans, sum(((x - x0) ** 2 + (y - y0) ** 2 <= r * r + 1e-05 for (x, y) in points)))\n return ans"], "starter_code": "def numpoints(points: List[List[int]], r: int) -> int:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Math", "Geometry", "Array"], "name": null, "source": "leetcode", "tags": ["Geometry", "Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numpoints", "task_id": "TACO_lite/301", "example": [[[[[-2, 0], [2, 0], [0, 2], [0, -2]], 2], [[[-3, 0], [3, 0], [2, 6], [5, 4], [0, 9], [7, 8]], 5], [[[-2, 0], [2, 0], [0, 2], [0, -2]], 1], [[[1, 2], [3, 5], [1, -1], [2, 3], [4, 1], [1, 3]], 2]], ["4", "5", "1", "4"]]} +{"requirement": "You like the way the Python `+` operator easily handles adding different numeric types, but you need a tool to do that kind of addition without killing your program with a `TypeError` exception whenever you accidentally try adding incompatible types like strings and lists to numbers.\n\nYou decide to write a function `my_add()` that takes two arguments. If the arguments can be added together it returns the sum. If adding the arguments together would raise an error the function should return `None` instead.\n\nFor example, `my_add(1, 3.414)` would return `4.414`, but `my_add(42, \" is the answer.\")` would return `None`.\n\nHint: using a `try` / `except` statement may simplify this kata.", "solutions": ["def my_add(a, b):\n try:\n return a + b\n except TypeError:\n return None", "def my_add(*a):\n try:\n return sum(a)\n except:\n pass", "def my_add(a, b):\n try:\n ans = a + b\n return ans\n except:\n return None", "def my_add(a, b):\n try:\n return a + b\n except:\n pass", "def my_add(a, b):\n return a + b if isinstance(a, (int, float, complex)) and isinstance(b, (int, float, complex)) else None", "def my_add(a, b):\n try:\n a + b\n except:\n try:\n float(a, b)\n except:\n return None\n return a + b"], "starter_code": "def my_add(a, b):\n", "input_output": {"fn_name": "my_add", "inputs": [[1, 3.414], [42, " is the answer."], [10, "2"]], "outputs": [[4.414], [null], [null]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/58659b1261cbfc8bfc00020a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "my_add", "task_id": "TACO_lite/387", "example": [[[1, 3.414], [42, " is the answer."]], [4.414, null]]} +{"requirement": "Find the Nth term of the Mysterious series.\nN Nth term\n1 5\n2 10\n3 26\n4 50\n5 122\n.\n.\n.\n10 842\nExample 1:\nInput: N = 1\nOutput: 5 \nExplanation: First term of the series is 5.\nExample 2:\nInput: N = 2\nOutput: 10\nExplanation: Second term of the series is 10. \nYour Task: \nYou dont need to read input or print anything. Complete the function nthMysterious() which takes N as input parameter and returns the Nth term of the Mysterious series.\nExpected Time Complexity: O(nlogn)\nExpected Auxiliary Space: O(n)\nConstraints:\n1<= N <=10^{3}", "solutions": ["import math\n\ndef isPrime(n):\n if n == 0 or n == 1:\n return False\n else:\n lim = int(math.sqrt(n)) + 1\n for i in range(2, lim):\n if n % i == 0:\n return False\n return True\n\ndef nthmysterious(N):\n (res, c) = ([], 0)\n for i in range(2, int(100000.0) + 1):\n if self.isPrime(i):\n res.append(i * i + 1)\n c += 1\n if c == N:\n return res[N - 1]", "import math\n\ndef nthmysterious(N):\n j = 2\n i = 0\n while i < N:\n c = 0\n k = int(math.sqrt(j))\n for p in range(2, k + 1):\n if j % p == 0:\n c = 1\n break\n if c == 0:\n l = j\n i = i + 1\n j = j + 1\n return l ** 2 + 1", "def isprime(x):\n for i in range(2, int(x ** (1 / 2)) + 1):\n if x % i == 0:\n return False\n else:\n continue\n return True\n\ndef nthmysterious(n):\n a = []\n i = 2\n k = 0\n while k < n:\n if isprime(i) == True:\n k = k + 1\n p = i\n i = i + 1\n else:\n i = i + 1\n return p ** 2 + 1", "def nthmysterious(N):\n\n def nthPrime(n):\n\n def isPrime(n):\n for i in range(5, int(n ** 0.5) + 1, 2):\n if not n % i:\n return False\n return True\n if n < 3:\n return n + 1\n p = 5\n for i in range(4, n + 1):\n p += (p + 3) % 6\n while not isPrime(p):\n p += (p + 3) % 6\n return p", "import math\n\ndef nthmysterious(n):\n\n def isPrime(x):\n for i in range(2, int(math.sqrt(x)) + 1):\n if x % i == 0:\n return False\n return True\n ans = 1\n arr = []\n i = 2\n while len(arr) < n:\n if isPrime(i):\n arr.append(i)\n i += 1\n return arr[n - 1] ** 2 + 1", "def nthmysterious(N):\n x = N\n (n, c) = (1, 0)\n while c < x:\n n += 1\n for i in range(2, n + 1):\n if n % i == 0:\n break\n if i == n:\n c = c + 1\n return n ** 2 + 1", "def isprime(N):\n if N <= 1:\n return False\n k = int(N ** 0.5)\n for i in range(2, k + 1):\n if N % i == 0:\n return False\n return True\n\ndef nthmysterious(N):\n i = 2\n c = 0\n while True:\n if self.isprime(i):\n c += 1\n if c == N:\n return i * i + 1\n i += 1", "import math\n\ndef isPrime(n):\n if n <= 1:\n return False\n max_div = math.floor(math.sqrt(n))\n for i in range(2, max_div + 1):\n if n % i == 0:\n return False\n return True\n\ndef nthmysterious(N):\n v = []\n c = 0\n for i in range(2, 100000):\n if self.isPrime(i):\n v.append(i * i + 1)\n c += 1\n if c == N:\n return v[N - 1]", "def isprime(n):\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef nthmysterious(N):\n l = [1, 2 * 2 + 1, 3 * 3 + 1, 5 * 5 + 1]\n for i in range(7, 100001):\n x1 = isprime(i)\n if x1:\n l.append(i * i + 1)\n if len(l) > N:\n break\n return l[N]", "def prime(n):\n for i in range(2, n):\n if n % i == 0:\n return 0\n if n % n == 0 and n % 1 == 0:\n return 1\n\ndef nthmysterious(N):\n l = []\n i = 2\n while len(l) != N:\n a = self.prime(i)\n if a == 1:\n l.append(i ** 2 + 1)\n i = i + 1\n return l[N - 1]", "def nthmysterious(k):\n c = 0\n n = 2\n m = 0\n while 1:\n p = 1\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n p = 0\n break\n if p == 1:\n c = c + 1\n m = n\n if c == k:\n break\n n = n + 1\n return m ** 2 + 1", "def nthmysterious(N):\n l = []\n i = 2\n while len(l) != N:\n for j in range(2, i // 2 + 1):\n if i % j == 0:\n break\n else:\n l.append(i)\n i += 1\n return l[N - 1] ** 2 + 1", "def prime(n):\n for i in range(2, n // 2 + 1):\n if n % i == 0:\n return 0\n return 1\n\ndef nthmysterious(n):\n i = 2\n c = 0\n while n != c:\n if self.prime(i):\n k = i\n c = c + 1\n i = i + 1\n return k * k + 1", "from math import sqrt\nfrom itertools import compress\n\ndef __init__():\n if not Solution.list_created:\n Solution.utility()\n\ndef utility():\n for i in range(2, int(sqrt(Solution.N)) + 1):\n if Solution.bool_prime_list[i]:\n j = i ** 2\n while j < Solution.N:\n Solution.bool_prime_list[j] = False\n j += i\n Solution.list_of_prime = list(compress(list(range(0, Solution.N + 1)), Solution.bool_prime_list))\n\ndef nthmysterious(N):\n return Solution.list_of_prime[N] ** 2 + 1", "def isPrime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True\n\ndef nthmysterious(N):\n li = list()\n count = 0\n for i in range(100000):\n if isPrime(i):\n li.append(i * i + 1)\n count += 1\n if count == N:\n return li[N - 1]"], "starter_code": "def nthmysterious (N):\n", "input_output": {"inputs": ["N = 1", "N = 2"], "outputs": ["5", "10"]}, "difficulty": "EASY", "raw_tags": ["Prime Number", "series"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory", "Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/mysterious-series5049/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(nlogn)", "entry_point": "nthmysterious", "task_id": "TACO_lite/399", "example": [[[1], [2]], ["5", "10"]]} +{"requirement": "Given N find all Sophie Germain Prime numbers less than N . A prime number p is called a sophie prime number if 2p+1 is also a prime number. The number 2p+1 is called a safe prime. \nExample 1:\nInput: N = 5\nOutput: 2 3\nExplanation: 2 and 3 are prime no. and \n2*2+1 = 5 and 3*2+1 = 7 are also prime\nno.\nExample 2:\nInput: N = 3\nOutput: 2\nExplanation: 2 is prime number and 2*2+1\n= 5 is also a prime number.\n \nYour Task:\nYou don't need to read or print anything your task is to complete the function sophie_primes() which takes N as input parameter and returns a list of all Sophie Germain Prime numbers in increasing order.\n \nExpected Time Compelxity: O(N* log(N))\nExpected Space Compelxity: O(N)\nConstraints:\n1 <= N <= 10000", "solutions": ["def isprime(N):\n if N == 1:\n return False\n for i in range(2, int(N ** 0.5) + 1, 1):\n if N % i == 0:\n return False\n return True\n\ndef sophie_primes(n):\n l = []\n for i in range(2, n, 1):\n if self.isprime(i) and self.isprime(2 * i + 1):\n l.append(i)\n return l", "import math\n\ndef fun(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i = i + 6\n return True\n\ndef sophie_primes(n):\n d = []\n for i in range(2, n):\n s = 2 * i + 1\n if fun(s) and fun(i):\n d.append(i)\n return d", "def sophie_primes(n):\n\n def f(n):\n if n == 0 or n == 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n res = []\n for i in range(n):\n if f(i) and f(2 * i + 1):\n res.append(i)\n return res", "def sophie_primes(n):\n\n def is_prime(num):\n i = 2\n while i * i <= num:\n if num % i == 0:\n return False\n i += 1\n return True\n res = []\n for i in range(2, n):\n if is_prime(i) and is_prime(i * 2 + 1):\n res.append(i)\n return res", "import math\n\ndef sophiPrime(n):\n num = 2 * n + 1\n for x in range(2, int(math.sqrt(num)) + 1):\n if num % x == 0:\n return False\n return True\n\ndef isPrime(num):\n for x in range(2, int(math.sqrt(num)) + 1):\n if num % x == 0:\n return False\n return sophiPrime(num)\n\ndef sophie_primes(n):\n res = []\n for x in range(2, n):\n if isPrime(x):\n res.append(x)\n return res", "def sophie_primes(n):\n\n def isPrime(num):\n if num < 2:\n return 0\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return 0\n return 1\n prime = [0] * n\n ans = []\n for i in range(2, n):\n prime[i] = i\n for i in range(2, int(n ** 0.5) + 1):\n if prime[i] == i:\n if isPrime(2 * i + 1) == 1:\n ans.append(i)\n for j in range(i * i, n, i):\n prime[j] = 0\n for i in range(int(n ** 0.5) + 1, n):\n if prime[i] == i:\n if isPrime(2 * i + 1) == 1:\n ans.append(i)\n return ans", "import math\n\ndef sophie_primes(n):\n l = 20002\n siv = [0] * l\n siv[0] = 1\n siv[1] = 1\n for i in range(2, int(math.sqrt(l)) + 1):\n if siv[i] == 0:\n for j in range(2 * i, l, i):\n siv[j] = 1\n lis = []\n for i in range(2, n):\n if siv[i] == False and siv[2 * i + 1] == False:\n lis.append(i)\n return lis", "def sophie_primes(n):\n ans = []\n\n def isPrime(num):\n if num < 2:\n return False\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return False\n return True\n for i in range(0, n):\n if isPrime(i) and isPrime(2 * i + 1):\n ans.append(i)\n return ans", "prime = [True for i in range(10 ** 6 + 1)]\n\ndef genseive():\n global prime\n n = 10 ** 6\n if prime[4] == False:\n return\n (prime[0], prime[1]) = (False, False)\n p = 2\n while p * p <= n:\n if prime[p] == True:\n for i in range(p * p, n, p):\n prime[i] = False\n p += 1\n\ndef sophie_primes(n):\n self.genseive()\n l = []\n for i in range(2, n):\n if prime[i] == True and prime[2 * i + 1] == True:\n l.append(i)\n return l", "sieve = [True for i in range(10 ** 6 + 1)]\n\ndef gen_sieve():\n global sieve\n n = 10 ** 6\n if sieve[4] == False:\n return\n (sieve[0], sieve[1]) = (False, False)\n i = 2\n while i <= n:\n if sieve[i]:\n c = i * i\n while c <= n:\n sieve[c] = False\n c += i\n i += 1\n\ndef sophie_primes(n):\n self.gen_sieve()\n l = []\n for i in range(2, n):\n if sieve[i] == True and sieve[2 * i + 1] == True:\n l.append(i)\n return l", "def sophie_primes(n):\n from math import sqrt\n N = n\n n = n * 2\n l = [0, 0] + [1] * (n + 1)\n k = []\n for i in range(2, int(sqrt(n)) + 1):\n if l[i] == 1:\n for j in range(i * i, n + 1, i):\n l[j] = 0\n for i in range(2, N):\n if l[i] == 1 and l[2 * i + 1] == 1:\n k.append(i)\n return k", "import math\n\ndef sophie_primes(n):\n if n == 0 or n == 1:\n return ''\n l = []\n m = []\n s = [True for i in range(n + 1)]\n s[0] = False\n s[1] = False\n for i in range(2, int(math.sqrt(n)) + 1):\n if s[i] == True:\n for j in range(i * i, n, i):\n s[j] = False\n for i in range(len(s)):\n if s[i] == True:\n l.append(i)\n for j in range(len(l) - 1):\n k = 2 * l[j] + 1\n c = 0\n for b in range(2, int(math.sqrt(k)) + 1):\n if k % b == 0:\n c += 1\n if c == 0:\n m.append(l[j])\n return m", "def sophie_primes(n):\n\n def prime(k):\n if k == 0 or k == 1:\n return 0\n for i in range(2, int(k ** 0.5) + 1):\n if k % i == 0:\n return 0\n return 1\n li = []\n for i in range(1, n):\n if prime(i) and prime(2 * i + 1):\n li.append(i)\n return li", "def sophie_primes(n):\n import math as m\n\n def isprime(n):\n sq = int(m.sqrt(n))\n for i in range(2, sq + 1):\n if n % i == 0:\n return False\n else:\n return True\n l = []\n for i in range(2, n):\n a = i * 2 + 1\n if isprime(i) and isprime(a):\n l.append(i)\n return l", "def sophie_primes(n):\n import math\n a = []\n prime = [1] * (n + n + 1)\n prime[0] = prime[1] = 0\n for i in range(2, n):\n if prime[i] == 1:\n for j in range(i * i, n + n + 1, i):\n prime[j] = 0\n for i in range(1, n):\n if prime[i] == 1 and prime[2 * i + 1] == 1:\n a.append(i)\n return a", "def sophie_primes(n):\n\n def sieve(x):\n pri = [1] * x\n (pri[0], pri[1]) = (0, 0)\n i = 2\n while i * i < x:\n if pri[i]:\n for _ in range(i * i, x, i):\n pri[_] = 0\n i += 1\n return pri\n s = sieve(2 * n + 1)\n l = []\n for i in range(n):\n if s[i]:\n p = 2 * i + 1\n if s[p]:\n l.append(i)\n return l", "import math\n\ndef primes(n):\n if n == 0 or n == 1:\n return False\n if n == 2 or n == 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n for i in range(5, int(math.sqrt(n)) + 1, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\ndef sophie_primes(n):\n d = []\n for i in range(n):\n if self.primes(i):\n c = i * 2 + 1\n if self.primes(c):\n d.append(i)\n return d", "def sophie_primes(n):\n\n def generate(n):\n primes = [True] * n\n (primes[0], primes[1]) = (False, False)\n p = 2\n while p * p <= n:\n if primes[p]:\n for _ in range(p * p, n, p):\n if primes[_]:\n primes[_] = False\n p += 1\n return primes\n l = []\n x = generate(100001)\n for i in range(n):\n if x[i]:\n p = 2 * i + 1\n if x[p]:\n l.append(i)\n return l", "import math\n\ndef sophie_primes(n):\n l = []\n if n == 0 or n == 1:\n return []\n\n def pri(u):\n for i in range(2, int(math.sqrt(u)) + 1):\n if u % i == 0:\n return False\n return True\n prime = [1] * n\n (prime[0], prime[1]) = (0, 0)\n for i in range(2, int(math.sqrt(n)) + 1):\n if prime[i]:\n for j in range(i * i, n, i):\n prime[j] = 0\n for i in range(len(prime)):\n if prime[i] == 1 and pri(2 * i + 1):\n l.append(i)\n return l", "def sophie_primes(n):\n\n def seive(i):\n l = [1 for j in range(i + 1)]\n l[0] = 0\n l[1] = 0\n p = 2\n while p * p <= i:\n if l[p] == 1:\n for k in range(p * p, i + 1, p):\n l[k] = 0\n p += 1\n return l\n i = 20001\n res = seive(i)\n l = []\n for j in range(n):\n if res[j] == 1:\n p = 2 * j + 1\n if p < i and res[p] == 1:\n l.append(j)\n return l", "import math\n\ndef sophie_primes(n):\n\n def isprime(n):\n a = int(math.sqrt(n))\n if n == 0 or n == 1:\n return False\n for i in range(2, a + 1):\n if n % i == 0:\n return False\n return True\n l = []\n for i in range(2, n):\n if isprime(i) and isprime(2 * i + 1):\n l.append(i)\n return l", "def sophie_primes(n):\n prime = [1 for i in range(2 * n + 1)]\n l = []\n prime[0] = 0\n prime[1] = 0\n p = 2\n while p * p <= 2 * n + 1:\n if prime[p] == 1:\n for i in range(p * p, 2 * n + 1, p):\n prime[i] = 0\n p += 1\n for i in range(2, n):\n if prime[i] == 1:\n a = 2 * i + 1\n if prime[a] == 1:\n l.append(i)\n return l", "def sophie_primes(n):\n\n def prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i = i + 6\n return True\n k = []\n for i in range(1, n):\n if prime(i) and prime(2 * i + 1):\n k.append(i)\n return k", "def sophie_primes(n):\n c = [True] * (2 * n + 1)\n p = 2\n d = []\n while p * p <= 2 * n + 1:\n if c[p] == True:\n for i in range(p * p, 2 * n + 1, p):\n c[i] = False\n p = p + 1\n for i in range(2, len(c) // 2):\n if c[i] == True and c[2 * i + 1] == True:\n d.append(i)\n return d", "def sophie_primes(n):\n if n == 1 or n == 2:\n return []\n c = []\n import math\n for i in range(2, n):\n p = 0\n for j in range(2, int(math.sqrt(i)) + 1):\n if i % j == 0:\n p = 1\n break\n if p == 0:\n z = 0\n b = int(2 * i + 1)\n for k in range(2, int(math.sqrt(b)) + 1):\n if b % k == 0:\n z = 1\n break\n if z == 0:\n c.append(i)\n return c", "import math\n\ndef isprime(n):\n if n == 1 or n == 0:\n return 0\n if n == 2 or n == 3:\n return 1\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return 0\n return 1\n\ndef sophie_primes(n):\n l = []\n for i in range(n):\n if isprime(i) == 1:\n j = 2 * i + 1\n if isprime(j) == 1:\n l.append(i)\n return l", "from math import sqrt\n\ndef prime(n):\n if n <= 1:\n return 0\n for i in range(2, int(sqrt(n)) + 1):\n if n % i == 0:\n return 0\n else:\n return 1\n\ndef sophie_primes(n):\n l = []\n for i in range(2, n):\n if prime(i) == 1 and prime(2 * i + 1) == 1:\n l.append(i)\n return l"], "starter_code": "def sophie_primes(n):\n", "input_output": {"inputs": ["N = 5", "N = 3"], "outputs": ["2 3", "2"]}, "difficulty": "EASY", "raw_tags": ["Prime Number", "sieve"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/sophie-germain-prime2014/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N* log(N))", "entry_point": "sophie_primes", "task_id": "TACO_lite/375", "example": [[], []]} +{"requirement": "Build a function `sumNestedNumbers`/`sum_nested_numbers` that finds the sum of all numbers in a series of nested arrays raised to the power of their respective nesting levels. Numbers in the outer most array should be raised to the power of 1.\n\nFor example,\n\nshould return `1 + 2*2 + 3 + 4*4 + 5*5*5 === 149`", "solutions": ["def sum_nested_numbers(a, depth=1):\n return sum((sum_nested_numbers(e, depth + 1) if type(e) == list else e ** depth for e in a))", "def sum_nested_numbers(arr, m=1):\n total = 0\n for element in arr:\n if isinstance(element, int):\n total += element ** m\n else:\n total += sum_nested_numbers(element, m + 1)\n return total", "def sum_nested_numbers(a, lvl=0):\n return a ** lvl if not isinstance(a, list) else sum((sum_nested_numbers(b, lvl + 1) for b in a))", "def sum_nested_numbers(arr, depth=1):\n return sum((sum_nested_numbers(x, depth + 1) if type(x) is list else x ** depth for x in arr))", "def flatten(xs, level=1):\n for x in xs:\n if isinstance(x, list):\n yield from flatten(x, level + 1)\n else:\n yield (x, level)\n\ndef sum_nested_numbers(xs):\n return sum((x ** level for (x, level) in flatten(xs)))", "def depth(arr, n):\n res = []\n for i in arr:\n if isinstance(i, int):\n res.append((i, n))\n else:\n res += depth(i, n + 1)\n return res\n\ndef sum_nested_numbers(arr):\n return sum((n ** i for (n, i) in depth(arr, 1)))", "def sum_nested_numbers(x):\n return sum(f(x))\n\ndef f(lst, v=1):\n for x in lst:\n if isinstance(x, (list, tuple)):\n for j in f(x, v + 1):\n yield j\n else:\n yield (x ** v)", "sum_nested_numbers = r = lambda a, p=1: sum((n ** p if n * 0 == 0 else r(n, p + 1) for n in a))", "def sum_nested_numbers(arr, d=1):\n my_sum = 0\n for v in arr:\n if isinstance(v, list):\n my_sum += sum_nested_numbers(v, d + 1)\n else:\n my_sum += v ** d\n return my_sum"], "starter_code": "def sum_nested_numbers(a, depth=1):\n", "input_output": {"fn_name": "sum_nested_numbers", "inputs": [[[0]], [[1, 2, 3, 4, 5]], [[1, [2], 3, [4, [5]]]], [[6, [5], [[4]], [[[3]]], [[[[2]]]], [[[[[1]]]]]]], [[1, [-1], [[1]], [[[-1]]], [[[[1]]]]]]], "outputs": [[0], [15], [149], [209], [5]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5845e6a7ae92e294f4000315", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sum_nested_numbers", "task_id": "TACO_lite/285", "example": [[[[1, [2, 3], [4, [5]]]]], [155]]} +{"requirement": "Ishaan has been given a task by his teacher. He needs to find the Nth term of a series. His teacher gives him some examples to help him out (Refer examples below). He is a bit weak in pattern searching so to help him his teacher told him that the Nth term is related to prime numbers. The Nth term is the difference of N and the closest prime number to N. Help him find the Nth term for a given N.\n \nExample 1:\nInput: N = 10\nOutput: 1\nExplanation: Closest prime to 10 is 11.\nExample 2:\nInput: N = 7\nOutput: 0\nExplanation: Closest prime to 7 is 7.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function NthTerm() which takes N as input paramater and returns Nth term.\n \nExpected Time Complexity: O(N* \u221a N)\nExpected Space Complexity: O(1)\nConstraints:\n1 <= N <= 100000", "solutions": ["def nthterm(N):\n\n def bo(x):\n if x < 2:\n return False\n i = 2\n while i * i <= x:\n if x % i == 0:\n return False\n i = i + 1\n return True\n z = N\n y = N\n if N == 1:\n return 1\n while True:\n if bo(y):\n break\n y = y + 1\n while z > 1:\n if bo(z):\n break\n z = z - 1\n if y - N > N - z:\n return N - z\n else:\n return y - N", "def is_prime(n):\n if n < 4:\n return True\n i = 2\n while i * i <= n:\n if n % i == 0:\n return False\n i += 1\n return True\n\ndef nthterm(N):\n if N == 1:\n return N\n c = 1\n if self.is_prime(N):\n return 0\n for i in range(1, N):\n if self.is_prime(N - i):\n return c\n elif self.is_prime(N + i):\n return c\n else:\n c += 1", "def isPrime(N):\n if N == 1:\n return False\n if N == 2 or N == 3:\n return True\n for i in range(2, int(N ** 0.5) + 1):\n if N % i == 0:\n return False\n return True\n\ndef nthterm(N):\n i = 0\n while True:\n if self.isPrime(N + i):\n return i\n if N - i > 0 and self.isPrime(N - i):\n return i\n i += 1\n return -1", "import math\n\ndef isprime(num):\n a = 2\n while a <= math.sqrt(num):\n if num % a < 1:\n return False\n a = a + 1\n return num > 1\n\ndef nthterm(N):\n i = N\n j = i\n while 1:\n if isprime(i):\n return i - N\n elif isprime(j):\n return N - j\n i += 1\n j -= 1", "def nthterm(N):\n\n def p(x):\n if x == 1:\n return 0\n for i in range(2, int(x ** 0.5) + 1):\n if x % i == 0:\n return 0\n return 1\n\n def np(x):\n while p(x) != 1:\n x = x + 1\n return x\n\n def pp(x):\n while p(x) != 1:\n x = x - 1\n return x\n a = np(N)\n b = pp(N)\n if p(N) == 1:\n return 0\n else:\n return min(abs(N - a), abs(N - b))", "def nthterm(N):\n ans = self.near_prime(N)\n if ans >= N:\n ans -= N\n else:\n ans = N - ans\n return ans\n\ndef is_prime(N):\n if N < 2:\n return False\n else:\n for i in range(2, int(N ** (1 / 2) + 1)):\n if N % i == 0:\n return False\n return True\n\ndef near_prime(N):\n if self.is_prime(N):\n return N\n else:\n lowr_num = N - 1\n upper_num = N + 1\n while True:\n if self.is_prime(lowr_num) == True:\n return lowr_num\n elif self.is_prime(upper_num) == True:\n return upper_num\n else:\n lowr_num -= 1\n upper_num += 1", "import math\n\ndef nthterm(N):\n\n def Prime(n):\n i = 2\n if n < 2:\n return False\n while i <= math.sqrt(n):\n if n % i == 0:\n return False\n i = i + 1\n return True\n if Prime(N):\n return 0\n i = 1\n while True:\n if Prime(N - i) or Prime(N + i):\n break\n i = i + 1\n return i", "def nthterm(N):\n i = 0\n while True:\n if self.isprime(N + i) or self.isprime(N - i):\n return i\n i += 1\n return i\n\ndef isprime(n):\n if n == 1:\n return 0\n elif n <= 3:\n return 1\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return 0\n return 1", "import math\n\ndef nthterm(N):\n if self.is_prime(N):\n return 0\n else:\n i = 1\n while True:\n if self.is_prime(N - i) or self.is_prime(N + i):\n return i\n else:\n i += 1\n\ndef is_prime(num):\n if num <= 1:\n return False\n upper_limit = math.floor(math.sqrt(num)) + 1\n for i in range(2, upper_limit):\n if num % i == 0:\n return False\n return True", "def prime(n):\n if n < 2:\n return 0\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return 0\n return 1\n\ndef nthterm(N):\n b = N\n N = b + 1\n c = b - 1\n if prime(b):\n return 0\n while N:\n if prime(N):\n break\n N += 1\n while c:\n if prime(c):\n break\n c -= 1\n p = N - b\n q = b - c\n r = min(p, q)\n return r", "import math\n\ndef isPrime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n for i in range(5, int(math.sqrt(n) + 1), 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\ndef nthterm(N):\n if N <= 1:\n h = abs(2 - N)\n return h\n p2 = N\n p1 = N\n f = False\n d = False\n while not f:\n if isPrime(p2) == True:\n f = True\n else:\n p2 = p2 + 1\n while not d:\n if isPrime(p1) == True:\n d = True\n else:\n p1 = p1 - 1\n g1 = abs(p1 - N)\n g = abs(p2 - N)\n return min(g, g1)", "def nthterm(N):\n if N == 1:\n return 1\n\n def prime(x):\n if x == 2:\n return True\n for i in range(2, int(x ** 0.5) + 1):\n if x % i == 0:\n return False\n return True\n if prime(N):\n return 0\n a = N\n b = N\n while not prime(a):\n a -= 1\n while not prime(b):\n b += 1\n return min(abs(N - a), abs(N - b))", "import math\n\ndef isprime(num):\n a = 2\n while a <= math.sqrt(num):\n if num % a < 1:\n return False\n a += 1\n return num > 1\n\ndef nthterm(N):\n les = N\n c = N\n uni = 0\n l = 0\n while c:\n if isprime(c) == True:\n l = c\n break\n c -= 1\n while N:\n if isprime(N) == True:\n uni = N\n break\n N += 1\n if les - l < uni - les:\n return les - l\n else:\n return uni - les", "def isprime(x):\n c = 0\n p = int(x ** 0.5) + 1\n for i in range(2, p):\n if x % i == 0:\n return False\n return True\n\ndef nthterm(N):\n j = N + 1\n i = N\n while True:\n if i > 1 and self.isprime(i):\n return N - i\n if self.isprime(j):\n return j - N\n i -= 1\n j += 1", "import math\n\ndef nthterm(N):\n\n def nextPrimeNumber(n):\n (p1, p2) = (n, n)\n\n def isPrime(num):\n if num <= 1:\n return False\n for i in range(2, int(math.sqrt(num)) + 1):\n if num % i == 0:\n return False\n return True\n while p1 > 0 and (not isPrime(p1)):\n p1 += 1\n while p2 > 0 and (not isPrime(p2)):\n p2 -= 1\n return (p1, p2)\n (p1, p2) = nextPrimeNumber(N)\n return min(abs(p1 - N), abs(p2 - N))", "def nthterm(N):\n if N == 0:\n return 2\n if N == 1:\n return 1\n import math\n a = 0\n f = N\n p = 0\n while p == 0:\n t = 0\n for j in range(2, int(math.sqrt(f)) + 1):\n if f % j == 0:\n t = 1\n break\n if t == 0:\n p = 1\n a = f\n else:\n f -= 1\n p = 0\n f = N + 1\n b = 0\n while p == 0:\n t = 0\n for j in range(2, int(math.sqrt(f)) + 1):\n if f % j == 0:\n t = 1\n break\n if t == 0:\n p = 1\n b = f\n else:\n f += 1\n return min(b - N, N - a)", "def isPrime(n):\n if n == 1:\n return False\n i = 2\n while i * i <= n:\n if n % i == 0:\n return False\n i += 1\n return True\n\ndef nthterm(N):\n if N == 1:\n return 1\n k = 0\n while k < N:\n if isPrime(N - k):\n break\n elif isPrime(N + k):\n break\n else:\n k += 1\n return k", "from bisect import *\nprimes = [2]\nprime = [1] * 100001\nfor i in range(4, 100001, 2):\n prime[i] = 0\nfor i in range(3, 100001, 2):\n if prime[i]:\n for j in range(i * i, 100001, i):\n prime[j] = 0\n primes.append(i)\n\ndef nthterm(n):\n i = bisect_right(primes, n)\n if primes[i] == n:\n return 0\n elif i == 0:\n return primes[i] - n\n elif primes[i] - n > n - primes[i - 1]:\n return n - primes[i - 1]\n else:\n return primes[i] - n", "def nthterm(N):\n if self.is_prime(N):\n return int(0)\n else:\n k = N - 1\n while k > 1:\n if self.is_prime(k):\n break\n k = k - 1\n j = N + 1\n while True:\n if self.is_prime(j):\n break\n j = j + 1\n k_diff = N - k\n j_diff = j - N\n return min(k_diff, j_diff)\n\ndef is_prime(num):\n if num > 1:\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return False", "def isPrime(N):\n if N < 2:\n return False\n i = 2\n while i * i <= N:\n if N % i == 0:\n return False\n i += 1\n return True\n\ndef nthterm(N):\n x = N\n y = N\n while x > 1:\n if isPrime(x):\n break\n x -= 1\n while True:\n if isPrime(y):\n break\n y += 1\n if not isPrime(x):\n return y - N\n return min(abs(N - x), abs(N - y))", "import math\n\ndef nthterm(N):\n if N == 1:\n return 1\n i = N\n j = N\n while not self.is_prime(i) and (not self.is_prime(j)):\n i -= 1\n j += 1\n if self.is_prime(i):\n return N - i\n return j - N\n\ndef is_prime(n):\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True", "import bisect\n\ndef nthterm(n):\n if n == 1:\n return 1\n\n def fun(m):\n for i in range(2, m):\n if i * i > m:\n break\n if m % i == 0:\n return False\n return True\n for i in range(n):\n if fun(n - i) or fun(n + i):\n return i\n return n", "import math\n\ndef nthterm(N):\n gap = 1\n if self.isPrime(N):\n return 0\n while True:\n if self.isPrime(N + gap) or self.isPrime(N - gap):\n break\n gap += 1\n return gap\n\ndef isPrime(n):\n if n < 2:\n return False\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True", "import math\n\ndef isprime(N):\n if N == 1:\n return False\n if N == 2:\n return True\n if N % 2 == 0:\n return False\n num = math.floor(math.sqrt(N))\n for i in range(3, num + 1, 2):\n if N % i == 0:\n return False\n return True\n\ndef nthterm(N):\n ans = True\n num = None\n i = 0\n while ans and N - i > 1:\n if self.isprime(N - i):\n ans = False\n num = N - i\n elif self.isprime(N + i):\n ans = False\n num = N + i\n i += 1\n if ans:\n while ans:\n if self.isprime(N + i):\n ans = False\n num = N + i\n i += 1\n return abs(num - N)", "def nthterm(N):\n\n def is_prime(n):\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n if N < 2:\n return N\n if is_prime(N):\n return 0\n i = 1\n while True:\n if is_prime(N + i) or is_prime(N - i):\n return i\n i += 1", "def nthterm(N):\n\n def isprime(n):\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n if isprime(N):\n return 0\n p = 0\n for i in range(N):\n if isprime(N - i):\n p = N - i\n break\n if isprime(N + i):\n p = N + i\n break\n return abs(N - p)", "def isPrime(n):\n if n == 2 or n == 3:\n return True\n elif n == 1:\n return False\n else:\n i = 2\n while i * i <= n:\n if n % i == 0:\n return False\n i = i + 1\n return True\n\ndef nthterm(N):\n if self.isPrime(N):\n return 0\n else:\n i = N - 1\n j = N + 1\n while 1:\n if i > 0 and self.isPrime(i):\n return N - i\n elif self.isPrime(j):\n return j - N\n else:\n i = i - 1\n j = j + 1", "import math\n\ndef isPrime(n):\n if n == 2:\n return True\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\ndef nthterm(n):\n if n == 1:\n return 1\n ans = 1000000000.0\n if self.isPrime(n):\n return 0\n flag = False\n l = n\n r = n\n count = 0\n while True:\n if self.isPrime(l) or self.isPrime(r):\n return count\n count += 1\n l -= 1\n r += 1\n if l == 0:\n flag = True\n break\n if flag:\n while True:\n if self.isPrime(r):\n return count\n r += 1\n count += 1\n return ans", "import math\n\ndef nthterm(N):\n if N == 1:\n return 1\n j = N\n sqr = int(math.sqrt(N))\n while j:\n count = 0\n for i in range(2, int(math.sqrt(j)) + 1):\n if j % i == 0:\n count = count + 1\n if count == 0:\n break\n j = j + 1\n k = N\n while k:\n count1 = 0\n for i in range(2, int(math.sqrt(k)) + 1):\n if k % i == 0:\n count1 = count1 + 1\n if count1 == 0:\n break\n k = k - 1\n n = N - j\n n1 = N - k\n if n < 0:\n n = -n\n if n1 < 0:\n n1 = -n\n if n > n1:\n return n1\n else:\n return n", "def nthterm(N):\n if N == 2 or N == 3 or N == 5 or (N == 7):\n return 0\n if N == 1:\n return 1\n if N == 0:\n return 2\n prev = N\n nxt = N + 1\n (fn, fp) = ('y', 'y')\n prprime = 0\n nprime = 0\n while True:\n if fp == 'y':\n for i in range(2, int(prev ** 0.5) + 1):\n if prev % i == 0:\n fp = 'n'\n break\n if fp == 'n':\n prev -= 1\n fp = 'y'\n else:\n prprime = prev\n fp = 'g'\n if fn == 'y':\n for j in range(2, int(nxt ** 0.5) + 1):\n if nxt % j == 0:\n fn = 'n'\n break\n if fn == 'n':\n nxt += 1\n fn = 'y'\n else:\n nprime = nxt\n fn = 'g'\n if fn == 'g' and fp == 'g':\n break\n return min(N - prprime, nprime - N)", "def nthterm(N):\n\n def isPrime(n):\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n if N == 1:\n return 1\n c = 0\n (l, r) = (N, N)\n while True:\n if isPrime(l) or isPrime(r):\n return c\n c += 1\n l -= 1\n r += 1\n if l == 0:\n break\n while True:\n if isPrime(r):\n return c\n r += 1\n c += 1", "import math\n\ndef prime(n):\n if n <= 1:\n return False\n else:\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\ndef nthterm(N):\n i = 0\n while True:\n res = self.prime(N + i)\n if res:\n return i\n res2 = self.prime(N - i)\n if res2:\n return i\n i += 1", "def is_Prime(N):\n if N > 1:\n for i in range(2, int(pow(N, 0.5)) + 1):\n if N % i == 0:\n return False\n return True\n\ndef nthterm(N):\n if self.is_Prime(N):\n return int(0)\n else:\n k = N - 1\n while k > 1:\n if self.is_Prime(k):\n break\n k = k - 1\n j = N + 1\n while True:\n if self.is_Prime(j):\n break\n j = j + 1\n k_diff = N - k\n j_diff = N - j\n return min(abs(k_diff), abs(j_diff))", "def nthterm(N):\n\n def isPrime(n):\n if n < 2:\n return False\n if n == 2:\n return True\n i = 2\n while i * i <= n:\n if n % i == 0:\n return False\n i += 1\n return True\n i = N\n while not isPrime(i):\n i += 1\n l = N\n if N > 2:\n while not isPrime(l):\n l -= 1\n return min(N - l, i - N)\n return i - N", "def nthterm(N):\n\n def not_prime(n):\n if n < 2:\n return True\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return True\n return False\n i = 1\n if not not_prime(N):\n return 0\n while not_prime(i + N) and not_prime(N - i):\n i += 1\n return i", "import math\n\ndef nthterm(N):\n\n def isPrime(num):\n if num <= 1:\n return False\n for i in range(2, int(math.sqrt(num)) + 1):\n if num % i == 0:\n return False\n return True\n diff = 0\n while True:\n if isPrime(N + diff) or isPrime(N - diff):\n return diff\n diff += 1\n return -1", "import math\n\ndef nthterm(N):\n if N == 1:\n return 1\n\n def isPrime(n):\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n m = N\n while not isPrime(m):\n m -= 1\n l = N\n while not isPrime(l):\n l += 1\n return min(N - m, l - N)", "def nthterm(N):\n\n def isprime(k):\n f = 0\n while True:\n for i in range(2, int(k ** 0.5) + 1):\n if k % i == 0:\n k += 1\n break\n else:\n return k\n\n def bprime(l):\n fc = 0\n while True:\n for i in range(2, int(l ** 0.5) + 1):\n if l % i == 0:\n l -= 1\n break\n else:\n return l\n if N == 1:\n return 1\n elif N == 0:\n return 2\n for i in range(2, int(N ** 0.5) + 1):\n if N % i == 0:\n s = isprime(N)\n j = bprime(N)\n e = abs(N - s)\n d = abs(N - j)\n if e > d:\n return d\n else:\n return e\n else:\n return 0", "def nthterm(N):\n from math import sqrt\n\n def isPrime(n):\n if n <= 1:\n return False\n for i in range(2, int(sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n x = N\n y = N\n while x > 1:\n if isPrime(x):\n break\n x -= 1\n while True:\n if isPrime(y):\n break\n y += 1\n if not isPrime(x):\n return y - N\n return min(abs(N - x), abs(N - y))", "def prime_num(num):\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return (False, num)\n return (True, num)\n\ndef nthterm(N):\n if N == 1:\n return 1\n if N == 2:\n return 0\n m = N\n lf = False\n rt = False\n (s, n) = self.prime_num(N)\n if s == True:\n return 0\n N1 = N\n while rt != True:\n if N1 == 1:\n break\n (rt, num1) = self.prime_num(N1)\n if rt == True:\n break\n N1 = N1 + 1\n N2 = N\n while lf != True:\n if N2 == 1:\n break\n (lf, num2) = self.prime_num(N2)\n if lf == True:\n break\n N2 = N2 - 1\n d1 = abs(num1 - m)\n d2 = abs(num2 - m)\n return d1 if d1 < d2 else d2", "from math import sqrt\n\ndef nthterm(N):\n if N == 0 or N == 1:\n return 2 - N\n num = 0\n num2 = 0\n while True:\n prime_flag = True\n new_n = N + num\n for i in range(2, int(sqrt(new_n) + 1)):\n if new_n % i == 0:\n prime_flag = False\n break\n if prime_flag:\n return abs(num)\n num2 += 1\n num += num2 * pow(-1, num2 + 1)", "import math\n\ndef check(n):\n a = 2\n while a <= math.sqrt(n):\n if n % a == 0:\n return False\n a = a + 1\n return True\n\ndef nthterm(N):\n if N == 1:\n return 1\n k = N\n front = N + 1\n back = N - 1\n if self.check(N):\n return 0\n while True:\n ans1 = self.check(front)\n if ans1 == True:\n return abs(k - front)\n ans2 = self.check(back)\n if ans2 == True:\n return abs(k - back)\n front = front + 1\n back = back - 1", "from math import sqrt\n\ndef isprime(N):\n return all((N % i != 0 for i in range(2, int(sqrt(N) + 1))))\n\ndef nthterm(N):\n if N > 1:\n prime = False\n res = N\n i = 1\n if self.isprime(N):\n return 0\n else:\n while not prime:\n if self.isprime(N - i):\n N = N - i\n prime = True\n elif self.isprime(N + i):\n N = N + i\n prime = True\n i += 1\n res = N - res\n return abs(res)\n else:\n return N", "from math import sqrt\n\ndef prime(n):\n if n <= 1:\n return False\n for i in range(2, int(sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\ndef nthterm(n):\n mini = 0\n maxi = 0\n if self.prime(n):\n return n - n\n for i in range(n, 1, -1):\n if self.prime(i):\n mini = i\n break\n for i in range(n + 1, 100000):\n if self.prime(i):\n maxi = i\n break\n if n - mini >= maxi - n:\n return maxi - n\n elif maxi - n > n - mini:\n return n - mini", "import math\n\ndef nthterm(N):\n\n def isPrime(n):\n if n <= 1:\n return False\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n (x, y) = (N, N)\n count = 0\n while 1:\n if isPrime(x) or isPrime(y):\n return count\n x -= 1\n y += 1\n count += 1\n return count", "from math import sqrt\n\ndef nthterm(N):\n diff = []\n loop = True\n i = N + 1\n if N == 1:\n return 1\n while i >= 2:\n i = i - 1\n flag = 0\n for j in range(2, int(sqrt(i)) + 1):\n if i % j == 0:\n flag = 1\n if flag == 0:\n diff = abs(N - i)\n break\n i = N\n while True:\n i = i + 1\n flag = 0\n for j in range(2, int(sqrt(i)) + 1):\n if i % j == 0:\n flag = 1\n if flag == 0:\n diff2 = abs(N - i)\n break\n out = min(diff, diff2)\n return out", "def check(x):\n import math\n p = 0\n if x > 1:\n for i in range(2, int(math.sqrt(x)) + 1):\n if x % i == 0:\n p = 1\n break\n if p == 0:\n return True\n else:\n return False\n else:\n return False\n\ndef nthterm(N):\n m = 10000\n if N == 1:\n return 1\n for i in range(N, N * 2):\n if self.check(i):\n m = min(m, abs(i - N))\n break\n for i in range(N, N // 2, -1):\n if self.check(i):\n m = min(m, abs(i - N))\n break\n return m", "def nthterm(N):\n\n def primeNum(n):\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n if primeNum(N):\n return 0\n L = N\n R = N\n while not primeNum(L) and (not primeNum(R)):\n L -= 1\n R += 1\n return min(abs(L - N), abs(R - N))", "import math\n\ndef isPrime(N):\n k = int(math.sqrt(N)) + 1\n for i in range(2, k, 1):\n if N % i == 0:\n return False\n return True\n\ndef nthterm(N):\n if N == 0:\n return 2\n elif N == 1:\n return 1\n elif ob.isPrime(N):\n return 0\n aboveN = -1\n belowN = -1\n n1 = N + 1\n while True:\n if ob.isPrime(n1):\n aboveN = n1\n break\n else:\n n1 += 1\n n1 = N - 1\n while True:\n if ob.isPrime(n1):\n belowN = n1\n break\n else:\n n1 -= 1\n diff1 = aboveN - N\n diff2 = N - belowN\n return min(diff1, diff2)", "import collections\n\ndef nthterm(N):\n\n def is_prime(n: int) -> bool:\n if n <= 3:\n return n > 1\n i = 2\n while i * i <= n:\n if n % i == 0:\n return False\n i += 1\n return True\n if N == 0:\n return 2\n if N == 1:\n return 1\n if is_prime(N):\n return 0\n n = N + 1\n p = N - 1\n while not is_prime(n):\n n += 1\n while not is_prime(p):\n p -= 1\n return min(N - p, n - N)", "import collections\n\ndef nthterm(N):\n import re\n\n def isPrime(n):\n return re.compile('^1?$|^(11+)\\\\1+$').match('1' * n) is None\n\n def is_prime(n: int) -> bool:\n if n <= 3:\n return n > 1\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i ** 2 <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True\n if N == 0:\n return 2\n if N == 1:\n return 1\n if is_prime(N):\n return 0\n n = N + 1\n p = N - 1\n while not is_prime(n):\n n += 1\n while not is_prime(p):\n p -= 1\n return min(N - p, n - N)", "def nthterm(N):\n\n def isPrime(n):\n if n <= 1:\n return False\n else:\n i = 2\n sn = int(n ** 0.5)\n while i <= sn:\n if n % i == 0:\n return False\n i += 1\n else:\n return True\n for d in range(0, N + 1):\n (i, j) = (N - d, N + d)\n if isPrime(i) or isPrime(j):\n return d", "import math\n\ndef nthterm(n):\n if n < 2:\n return 1\n nextPrime = 0\n while nextPrime < n:\n if self.isPrime(n - nextPrime) or self.isPrime(n + nextPrime):\n break\n nextPrime += 1\n return nextPrime\n\ndef isPrime(num):\n n = 2\n while n <= math.sqrt(num):\n if num % n == 0:\n return False\n n += 1\n return True", "import math\n\ndef is_prime(x):\n for i in range(2, int(math.sqrt(x)) + 1):\n if x % i == 0:\n return False\n return True\n\ndef nthterm(N):\n if N == 0:\n return 2\n if N == 1:\n return 1\n if N == 2:\n return 0\n if N == 3:\n return 0\n min_diff = float('inf')\n for i in range(N, 2 * N):\n if self.is_prime(i):\n min_diff = abs(i - N)\n break\n for i in range(N + 1)[::-1]:\n if self.is_prime(i):\n min_diff = min(min_diff, abs(i - N))\n break\n return min_diff", "import math\n\ndef isprime(n):\n ran = int(math.sqrt(n))\n for i in range(2, ran + 1):\n if n % i == 0:\n return False\n return True\n\ndef nthterm(N):\n if N == 1:\n return 1\n if N == 0:\n return 2\n if isprime(N):\n return 0\n num = N\n for i in range(1, N):\n if N - i >= 1 and isprime(N - i):\n return i\n if isprime(N + i):\n return i", "import math\n\ndef primecheck(x):\n if x == 1:\n return 0\n sta = 1\n for i in range(2, int(math.sqrt(x)) + 1):\n if x % i == 0:\n sta = 0\n break\n return sta\n\ndef nthterm(N):\n i = 0\n while True:\n if self.primecheck(N - i) == 1 or self.primecheck(N + i) == 1:\n return i\n i = i + 1"], "starter_code": "def nthterm(N):\n", "input_output": {"inputs": ["N = 10", "N = 7"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Pattern Searching"], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/help-ishaan5837/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N* \u221a N)", "entry_point": "nthterm", "task_id": "TACO_lite/385", "example": [[[10], [7]], ["1", "0"]]} +{"requirement": "## Task\n\nCreate a RomanNumerals class that can convert a roman numeral to and from an integer value. It should follow the API demonstrated in the examples below. Multiple roman numeral values will be tested for each helper method. \n\nModern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.\n\n## Examples\n\n```python\nRomanNumerals.to_roman(1000) # should return 'M'\nRomanNumerals.from_roman('M') # should return 1000\n```\n\n## Help\n\n| Symbol | Value |\n|----------------|\n| I | 1 |\n| V | 5 |\n| X | 10 |\n| L | 50 |\n| C | 100 |\n| D | 500 |\n| M | 1000 |", "solutions": ["import string\nfrom collections import OrderedDict\n\ndef to_roman(num):\n conversions = OrderedDict([('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)])\n out = ''\n for (key, value) in conversions.items():\n while num >= value:\n out += key\n num -= value\n return out\n\ndef from_roman(roman):\n conversions = OrderedDict([('CM', 900), ('CD', 400), ('XC', 90), ('XL', 40), ('IX', 9), ('IV', 4), ('M', 1000), ('D', 500), ('C', 100), ('L', 50), ('X', 10), ('V', 5), ('I', 1)])\n out = 0\n for (key, value) in conversions.items():\n out += value * roman.count(key)\n roman = string.replace(roman, key, '')\n return out", "from collections import OrderedDict\nimport re\nROMAN_NUMERALS = OrderedDict([('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)])\nDECIMAL_TO_ROMAN = [(v, k) for (k, v) in list(ROMAN_NUMERALS.items())]\nROMAN_RE = '|'.join(ROMAN_NUMERALS)\n\ndef from_roman(roman):\n return sum((ROMAN_NUMERALS[d] for d in re.findall(ROMAN_RE, roman)))\n\ndef to_roman(decimal):\n result = []\n for (number, roman) in DECIMAL_TO_ROMAN:\n while decimal >= number:\n decimal -= number\n result.append(roman)\n return ''.join(result)", "from itertools import groupby\n\ndef to_roman(cls, val):\n rom = []\n for (l, v) in cls.letters:\n m = val // v\n rom += m * [l]\n val -= m * v\n return ''.join(rom)\n\ndef from_roman(cls, rom):\n cumu = 0\n for (l, v) in cls.letters:\n while rom[:len(l)] == l:\n rom = rom[len(l):]\n cumu += v\n if not rom:\n break\n return cumu", "def to_roman(cls, num, rom=''):\n EDGE = {0: lambda x, elem, dict, number: dict.get(elem, '') * number, 1: lambda e, i, D, l: e + D[i * (l + 1)] if l in [4, 9] else D[i * l] if l is 5 else D[i * 5] + e * (l % 5)}\n for element in list(cls.READ.keys())[0::2][::-1]:\n left = num // element\n rom += EDGE.get(left > 3, '')(cls.READ[element], element, cls.READ, left)\n num %= element\n return rom\n\ndef from_roman(cls, roma):\n cls.INTG.update({'N': 0})\n roma += 'N'\n return sum([-cls.INTG[x] if cls.INTG[x] < cls.INTG[z] else cls.INTG[x] for (x, z) in zip(roma[:-1], roma[1:])])", "def from_roman(s):\n X = [dict(zip('MDCLXVI', (1000.0, 500, 100, 50, 10, 5, 1)))[x] for x in s]\n return int(sum(((x, -x)[x < y] for (x, y) in zip(X, X[1:]))) + X[-1])\n\ndef to_roman(i, o=' I II III IV V VI VII VIII IX'.split(' ')):\n r = lambda n: o[n] if n < 10 else ''.join((dict(zip('IVXLC', 'XLCDM'))[c] for c in r(n // 10))) + o[n % 10]\n return r(i)", "def to_roman(num):\n ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)\n nums = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I')\n result = ''\n for i in range(len(ints)):\n count = int(num / ints[i])\n result += str(nums[i] * count)\n num -= ints[i] * count\n return result\n\ndef from_roman(roman):\n nums = ['M', 'D', 'C', 'L', 'X', 'V', 'I']\n ints = [1000, 500, 100, 50, 10, 5, 1]\n places = []\n for i in range(len(roman)):\n c = roman[i]\n value = ints[nums.index(c)]\n try:\n next_val = ints[nums.index(roman[i + 1])]\n if next_val > value:\n value *= -1\n except:\n pass\n places.append(value)\n return sum(places)", "def to_roman(n, result='', i=0):\n SPQR = ((1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'))\n if i == len(SPQR):\n return result\n while n - SPQR[i][0] >= 0:\n result += SPQR[i][1]\n n -= SPQR[i][0]\n i += 1\n return self.to_roman(n, result, i)\n\ndef from_roman(roman, result=0, i=0):\n SPQR = ((900, 'CM'), (1000, 'M'), (400, 'CD'), (500, 'D'), (90, 'XC'), (100, 'C'), (50, 'L'), (40, 'XL'), (9, 'IX'), (10, 'X'), (4, 'IV'), (5, 'V'), (1, 'I'))\n if roman == '':\n return result\n while SPQR[i][1] in roman:\n result += SPQR[i][0]\n roman = roman[len(SPQR[i][1]):]\n i += 1\n return self.from_roman(roman, result, i)", "from functools import reduce\n\ndef to_roman(cls, n):\n _map = cls._map\n red = lambda s, e: (s[0] + _map[e] * (s[1] // e), s[1] - e * (s[1] // e))\n return reduce(red, reversed(sorted(_map)), ['', n])[0]\n\ndef from_roman(cls, s):\n _map = {v: k for (k, v) in cls._map.items()}\n red = lambda s, e: s[:-1] + [s[-1] + e] if s and s[-1] + e in _map else s + [e]\n return sum((_map[x] for x in reduce(red, s, [])))", "from itertools import groupby, zip_longest\nFROM_ROMAN = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}\nTO_ROMAN = ((1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'))\n\ndef to_roman(n):\n result = []\n for (num, char) in TO_ROMAN:\n (q, n) = divmod(n, num)\n result.append(q * char)\n return ''.join(result)\n\ndef from_roman(roman):\n pairs = [sum(g) for (_, g) in groupby((FROM_ROMAN[a] for a in roman))]\n return sum((a + b if a > b else b - a for (a, b) in zip_longest(pairs[::2], pairs[1::2], fillvalue=0)))", "def to_roman(n):\n res = []\n for i in RomanNumerals.dic:\n res.extend(n / i[0] * i[1])\n n -= n / i[0] * i[0]\n return ''.join(res)\n\ndef from_roman(n):\n res = 0\n for i in RomanNumerals.dic:\n while n.startswith(i[1]):\n res += i[0]\n n = n[len(i[1]):]\n return res"], "starter_code": "def to_roman(n):\n", "input_output": {"fn_name": "to_roman", "inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/51b66044bce5799a7f000003", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "to_roman", "task_id": "TACO_lite/396", "example": [[[1000], ["M"]], ["M", null]]} +{"requirement": "Write a program that receives a number n as input and prints it in the following format as shown below.\nLike for n = 2 the pattern will be:\n1*2*5*6\n--3*4\nExample 1:\nInput: n = 3\nOutput: \n1*2*3*10*11*12\n--4*5*8*9\n----6*7\nExplaination: If the pattern shown in question \nis followed, this will be the output.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function pattern() which takes n as input parameter and returns a list of string where each string denotes a new line of the pattern.\nExpected Time Complexity: O(n^{2})\nExpected Auxiliary Space: O(n^{2})\nConstraints:\n1 \u2264 n \u2264 70", "solutions": ["def pattern(n):\n m = n\n c = 1\n lst = []\n for i in range(n):\n str1 = ''\n str1 += '--' * i\n for j in range(n - i):\n str1 += str(c) + '*'\n c += 1\n lst.append(str1)\n for i in range(n):\n for j in range(i + 1):\n lst[-i - 1] += str(c) + '*'\n c += 1\n lst[-i - 1] = lst[-i - 1][:-1]\n return lst", "def pattern(n):\n l = n * (n + 1) // 2\n r = l + 1\n sol = []\n for i in range(n):\n for j in range(i + 1):\n if j == 0:\n temp = str(l) + '*' + str(r)\n l -= 1\n r += 1\n else:\n temp = str(l) + '*' + temp + '*' + str(r)\n l -= 1\n r += 1\n sol.insert(0, temp)\n for i in range(n):\n sol[i] = '--' * i + sol[i]\n return sol", "def pattern(n):\n res = [''] * n\n rres = [''] * n\n c = 1\n for i in range(n):\n s = ''\n for j in range(n - i):\n s += str(c) + '*'\n c += 1\n res[i] = s\n for i in range(n - 1, -1, -1):\n s = ''\n for j in range(n - i):\n s += str(c) + '*'\n c += 1\n res[i] += s[:-1]\n for i in range(n):\n rres[i] = '-' * (i * 2) + res[i]\n return rres", "def pattern(n):\n sept = '-'\n f = 1\n l = n ** 2 + n\n ret = []\n for i in range(n):\n s = ''\n s = s + 2 * i * sept\n for j in range(n - i, 0, -1):\n s = s + str(f) + '*'\n f += 1\n for j in range(n - i, 0, -1):\n if j == 1:\n s = s + str(l - j + 1)\n else:\n s = s + str(l - j + 1) + '*'\n l = l - n + i\n ret.append(s)\n return ret", "def pattern(n):\n ar = []\n k = 1\n for i in range(n):\n st = ''\n for j in range(i):\n st += '--'\n for j in range(n - i):\n st += str(k) + '*'\n k += 1\n m = (n - i - 1) * (n - i)\n for l in range(n - i - 1):\n st += str(k + m) + '*'\n m += 1\n st += str(k + m)\n ar.append(st)\n return ar", "def pattern(n):\n l = []\n k = n * (n + 1)\n c = 1\n x = 0\n for i in range(n, 0, -1):\n s = ''\n for sp in range(1, x + 1):\n s = s + '-'\n for j in range(1, i + 1):\n s = s + str(c) + '*'\n c += 1\n for j in range(k - i + 1, k):\n s = s + str(j) + '*'\n s = s + str(k)\n l.append(s)\n k -= i\n x += 2\n return l", "def pattern(n):\n data = [[] for x in range(n)]\n curr = 1\n for x in [*range(1, n + 1), *range(n, 0, -1)]:\n for y in range(n - x + 1):\n data[x - 1].append(str(curr))\n curr += 1\n data = list(map(lambda dd: '*'.join(dd), data))\n for x in range(n):\n data[x] = '-' * (2 * x) + data[x]\n return data", "def pattern(n):\n (row, column, dashes) = (0, 0, 0)\n (i, j, dash_counter) = (0, 0, 0)\n value = 1\n (k, l, decrementor) = (0, 0, 0)\n column_decrementor = 0\n support = n - 1\n temp = n * n + 1\n temp1 = n * 2 - 1\n z = temp\n tracker = 0\n res = []\n for i in range(1, n + 1):\n s = ''\n for it in range(dash_counter):\n s += '-'\n for j in range(1, 2 * n - dash_counter + 1):\n if j % 2 == 0:\n s += '*'\n else:\n s += str(value)\n value += 1\n for k in range(1, temp1 - decrementor + 1):\n if k % 2 == 0:\n s += '*'\n else:\n if k == 1:\n tracker = temp\n s += str(temp)\n temp += 1\n decrementor += 2\n temp = tracker - support\n support -= 1\n dash_counter += 2\n res.append(s)\n return res", "def pattern(n):\n res = [''] * n\n counter = 1\n for i in range(n):\n s = ''\n for j in range(n - i):\n s += str(counter) + '*'\n counter += 1\n res[i] = s\n for i in range(n - 1, -1, -1):\n s = ''\n for j in range(n - i):\n s += str(counter) + '*'\n counter += 1\n res[i] += s[:-1]\n for i in range(n):\n res[i] = '-' * (i << 1) + res[i]\n return res", "def pattern(n):\n p = n * (n + 1) // 2 * 2 - (n - 1)\n k = 1\n a = []\n l = 1\n for i in range(n, 0, -1):\n s = ''\n s = s + '-' * ((l - 1) * 2)\n for j in range(i):\n s = s + str(k)\n s = s + '*'\n k = k + 1\n for g in range(i - 1):\n s = s + str(p)\n s = s + '*'\n p = p + 1\n s = s + str(p)\n p = p - (n - l) * 2\n l = l + 1\n a.append(s)\n return a", "def pattern(n):\n ans = [''] * n\n counter = 1\n for i in range(0, n):\n s = ''\n for j in range(0, n - i):\n s += str(counter) + '*'\n counter += 1\n ans[i] = s\n for i in range(n - 1, -1, -1):\n s = ''\n for j in range(0, n - i):\n s += str(counter) + '*'\n counter += 1\n ans[i] += s[:-1]\n for i in range(0, n):\n ans[i] = '-' * (i << 1) + ans[i]\n return ans", "def pattern(n):\n p = []\n k = 1\n f = n * (n + 1)\n for i in range(1, n + 1):\n s = ''\n for j in range(1, 2 * i - 1):\n s += '-'\n for j in range(1, n - i + 2):\n s += str(k)\n s += '*'\n k += 1\n g = 0\n for j in range(f - (n - i), f + 1):\n g += 1\n s += str(j)\n if g != n - i + 1:\n s += '*'\n f -= 1\n p.append(s)\n return p", "def pattern(n):\n l = []\n s = 1\n for i in range(n):\n st = ''\n for j in range(2 * i):\n st += '-'\n for j in range(i, n):\n st += str(s) + '*'\n s += 1\n l.append(st)\n for i in range(n - 1, -1, -1):\n st = ''\n for j in range(i, n):\n st += str(s)\n s += 1\n if j != n - 1:\n st += '*'\n l[i] += st\n return l", "def pattern(n):\n a = n\n l = []\n x = 1\n x1 = n * n + 1\n s = ''\n n1 = n\n n2 = n\n for i in range(n):\n s = ''\n if i > 0:\n s += '-' * (2 * i)\n for j in range(n1):\n s += str(x)\n x += 1\n s += '*'\n n1 -= 1\n x2 = x1\n for j in range(n2):\n if j == n2 - 1:\n s += str(x1 + j)\n else:\n s += str(x1 + j)\n s += '*'\n n2 -= 1\n x1 -= n2\n l.append(s)\n return l", "def pattern(n):\n s = []\n s1 = []\n a = n * (n + 1)\n m = a // 2\n for i in range(1, a + 1):\n if i <= m:\n s += ['*' + str(i)]\n else:\n s1 += ['*' + str(i)]\n s1 = s1[::-1]\n e = []\n j = 0\n for i in range(1, n + 1):\n b = ''.join(s[-i:] + s1[-i:][::-1])\n e += [b[1:]]\n del s[-i:]\n del s1[-i:]\n e = e[::-1]\n for i in range(len(e)):\n e[i] = '-' * j + e[i]\n j += 2\n return e", "def pattern(n):\n k = n\n f = 0\n t = n\n res = []\n while n > 0:\n ans = []\n ans.append('-' * 2 * (t - n))\n for i in range(1, n + 1):\n if i == 1:\n f += 1\n ans.append(f)\n else:\n f += 1\n ans.extend(['*', f])\n f = f - n\n for i in range(1, n + 1):\n f += 1\n ans.extend(['*', f + k * k])\n k -= 1\n n -= 1\n res.append(''.join(map(str, ans)))\n return res", "def pattern(n):\n total = int(n * (n + 1) / 2 * 2)\n interval = 0\n result = []\n for i in range(n, 0, -1):\n subStr = ''\n subStr += '-' * (n - i) * 2\n for j in range(interval + 1, interval + i + 1):\n subStr += str(j)\n subStr += '*'\n for k in range(total - i - interval + 1, total - interval + 1):\n subStr += str(k)\n if total - interval != k:\n subStr += '*'\n interval += i\n result.append(subStr)\n return result", "def pattern(n):\n x = [''] * n\n a = n * (n + 1)\n y = []\n for i in range(a):\n y.append(i + 1)\n for i in range(1, n + 1):\n x[i - 1] += '-' * (2 * (i - 1))\n for j in y[:n - i + 1]:\n x[i - 1] += str(j) + '*'\n y.remove(j)\n for j in y[-(n - i + 1):]:\n x[i - 1] += str(j) + '*'\n y.remove(j)\n x[i - 1] = x[i - 1][:-1]\n return x", "def pattern(n):\n x = []\n number = 1\n for i in range(n, 0, -1):\n c = ''\n c += '-' * ((n - i) * 2)\n for j in range(i):\n c += str(number)\n c += '*'\n number += 1\n x.append(c)\n x = x[::-1]\n y = []\n for i in range(1, n + 1):\n a = x[i - 1]\n for j in range(i):\n a += str(number)\n number += 1\n a += '*'\n y.append(a[:-1])\n return y[::-1]", "def pattern(n):\n ans = []\n noof = n * (n + 1)\n cop = n\n (a, b) = (1, noof)\n hyp = 0\n while cop:\n strr = ''\n for i in range(hyp):\n strr += '-'\n hyp += 2\n for i in range(cop):\n strr += str(a) + '*'\n a += 1\n last = b - cop\n for i in range(cop):\n last += 1\n if last == b:\n strr += str(last)\n else:\n strr += str(last) + '*'\n b = b - cop\n cop -= 1\n ans.append(strr)\n return ans", "def pattern(n):\n for i in range(n):\n ans = []\n d = n * (n + 1)\n x = 0\n for i in range(n, 0, -1):\n s = '' + '-' * (n - i) * 2\n j = x + 1\n l = 1\n while l <= i * 2:\n s += str(j) + '*'\n if l == i:\n x = j\n j = d - x\n j += 1\n l += 1\n ans.append(s[:-1])\n return ans", "def pattern(n):\n m = (n + 1) * n\n l = 1\n ans = []\n for i in range(n):\n temp = []\n temp2 = []\n for j in range(n - i):\n temp.append(str(l))\n l += 1\n temp2.append(str(m))\n m -= 1\n temp2 = temp2[::-1]\n temp.extend(temp2)\n temp = '*'.join(temp)\n for p in range(2 * i):\n temp = '-' + temp\n ans.append(temp)\n return ans", "def pattern(n):\n ansf = []\n ansl = []\n count = 0\n for i in range(n):\n s = []\n for j in range(n - i):\n count += 1\n s.append(str(count))\n ansf.append(2 * i * '-' + '*'.join(s))\n for i in range(n):\n s = []\n for j in range(i + 1):\n count += 1\n s.append(str(count))\n ansl.append('*'.join(s))\n ansl.reverse()\n ans = []\n for i in range(n):\n ans.append(ansf[i] + '*' + ansl[i])\n return ans", "def pattern(n):\n t = int(n * (n + 1) / 2 * 2)\n h = 0\n r = []\n for i in range(n, 0, -1):\n s = ''\n s += '-' * (n - i) * 2\n for j in range(h + 1, h + i + 1):\n s += str(j)\n s += '*'\n for k in range(t - i - h + 1, t - h + 1):\n s += str(k)\n if t - h != k:\n s += '*'\n h += i\n r.append(s)\n return r", "def pattern(n):\n s = []\n s.extend(range(1, n * (n + 1) + 1))\n l = list(map(str, s))\n ans = []\n for i in range(n, 0, -1):\n ans.append('-' * ((n - i) * 2) + '*'.join(l[:i]) + '*' + '*'.join(l[-1 * i:]))\n l = l[i:-i]\n return ans", "def pattern(n):\n lines = []\n x = n * (n + 1)\n start = 1\n end = x\n prev = x\n for i in range(n):\n line = '--' * i\n arr = [str(j) for j in range(start, start + n - i)] + [str(j) for j in range(end - n + i + 1, prev + 1)]\n start += n - i\n end = end - n + i\n prev = end\n line += '*'.join(arr)\n lines += [line]\n return lines", "def pattern(n):\n b = n * (n + 1)\n l = []\n for i in range(b):\n l.append(str(i + 1))\n i = 0\n j = b - 1\n e = []\n c = 0\n for m in range(n, 0, -1):\n t = ''\n t += c * '-'\n p = []\n g = []\n for q in range(m):\n p.append(l[i])\n g.append(l[j])\n i += 1\n j -= 1\n p.extend(g[::-1])\n t += '*'.join(p)\n e.append(t)\n c += 2\n return e", "def pattern(n):\n store = []\n no = 1\n for i in range(n):\n curr = []\n for j in range(n - i):\n curr.append(no)\n no += 1\n store.extend(curr)\n for i in range(n):\n curr = []\n for j in range(n - i):\n curr.append(no)\n no += 1\n store.extend(curr)\n f = store[0:len(store) // 2]\n s = store[len(store) // 2:]\n s = s[::-1]\n ans = []\n for i in range(len(f)):\n push1 = []\n push2 = []\n for j in range(n - i):\n push1.append(str(f.pop(0)))\n push1.append('*')\n push1 = push1[:-1]\n for j in range(n - i):\n push2.append(str(s.pop(0)))\n push2.append('*')\n push1.extend(push2[::-1])\n push1.insert(0, '--' * i)\n ans.append(''.join(push1))\n return ans", "def pattern(n):\n res = []\n l = n * (n + 1)\n a = list(range(1, l + 1))\n seed = 0\n for x in range(n, 0, -1):\n arr = a[seed:seed + x]\n if seed == 0:\n arr = arr + a[-x - seed:]\n else:\n arr = arr + a[-x - seed:-seed]\n resStr = '--' * (n - x) + '*'.join([str(m) for m in arr])\n res.append(resStr)\n seed += x\n return res", "def pattern(n):\n u = n * (n + 1)\n nums = list(range(1, u + 1))\n c_j = 0\n c_k = u - n\n dash = 2\n ans = []\n pres_string = ''\n for i in range(n):\n for j in range(n - i):\n pres_string += str(nums[c_j + j])\n pres_string += '*'\n c_j += j + 1\n for k in range(n - i):\n pres_string += str(nums[c_k + k])\n if k != n - i - 1:\n pres_string += '*'\n c_k -= k\n ans.append(pres_string)\n pres_string = '-' * dash\n dash += 2\n return ans", "def pattern(n):\n rtr = [[] for i in range(n)]\n num = 1\n for j in range(n, 0, -1):\n for k in range(n):\n if k < n - j:\n rtr[n - j].append('--')\n else:\n rtr[n - j].append(str(num))\n rtr[n - j].append('*')\n num += 1\n for j in range(1, n + 1):\n for k in range(j):\n rtr[n - j].append(str(num))\n rtr[n - j].append('*')\n num += 1\n rtr = [x[:-1] for x in rtr]\n rtr = [''.join(x) for x in rtr]\n return rtr", "def pattern(n):\n lst3 = []\n lst4 = []\n lst = list(range(n * (n + 1)))\n lst.pop(0)\n lst.append(lst[-1] + 1)\n f = 0\n y = 0\n for i in range(n, 0, -1):\n w = 0\n lst1 = []\n for j in range(2):\n for k in range(f, f + i):\n if w == 0:\n lst1.append(lst[k])\n else:\n lst1.append(lst[-k - 1])\n w = 1\n lst1.sort()\n f += i\n lst2 = []\n for x in lst1:\n lst2.append(str(x) + '*')\n lst2 = ''.join(lst2)\n lst2 = lst2[:-1]\n lst3 = ['-' * y + lst2]\n y += 2\n lst2 = []\n lst4.append(lst3[0])\n return lst4", "def pattern(n):\n a = []\n for i in range(1, n * (n + 1) + 1):\n a.append(i)\n a.append('*')\n a.pop()\n b = []\n z = 0\n y = n * 2 - 1\n for i in range(n):\n b.append('-' * z + ''.join(map(str, a[:n * 2])) + ''.join(map(str, a[len(a) - y:])))\n a.pop()\n a = a[n * 2:len(a) - y]\n n -= 1\n y -= 2\n z += 2\n return b", "def pattern(n):\n l = 1\n r = n * (n + 1)\n lst = []\n for i in range(n, -1, -1):\n str1 = ''\n for space in range(n, i - 1, -1):\n if space < n:\n str1 += '--'\n for j in range(1, i + 1):\n str1 += str(l) + '*'\n l += 1\n for j in range(1, i + 1):\n str1 += str(r - n + 1)\n if j < i:\n str1 += '*'\n r += 1\n r = r - (i - 1) * 2 - 1\n lst.append(str1)\n return lst", "def pattern(n):\n r = []\n ln = 0\n for row in range(n):\n rs = '--' * row\n for s in range(n - row):\n ln += 1\n rs += str(ln) + '*'\n r.append(rs)\n for row in range(n - 1, -1, -1):\n for s in range(n - row):\n ln += 1\n r[row] += str(ln) + '*'\n return [rs[:-1] for rs in r]", "def pattern(n):\n arr = []\n for i in range(n):\n arr.append('--' * i)\n counter = 0\n index = 0\n for j in range(n, 0, -1):\n for b in range(j):\n counter += 1\n arr[index] = arr[index] + str(counter) + '*'\n index += 1\n for k in range(n, 0, -1):\n for c in range(n - k + 1):\n counter += 1\n arr[k - 1] = arr[k - 1] + str(counter) + '*'\n for l in range(n):\n arr[l] = arr[l][:-1]\n return arr", "def pattern(n):\n ans = []\n num = 1\n for i in range(n):\n s = ''\n for j in range(i):\n s += '--'\n for j in range(n - i):\n s += str(num) + '*'\n num += 1\n ans.append(s)\n for i in range(n - 1, -1, -1):\n s = ''\n for j in range(n - i):\n s += str(num) + '*'\n num += 1\n s = s[:-1]\n ans[i] = ans[i] + s\n return ans", "def pattern(n):\n start = 1\n end = n * (n + 1)\n c = 0\n arr = []\n while c < n:\n temp = []\n line = []\n i = 0\n j = 0\n while i < n - c:\n line.append(str(start + i))\n i += 1\n while j < n - c:\n temp.append(str(end - j))\n j += 1\n line += temp[::-1]\n s = '-' * 2 * c\n ans = '*'.join(line)\n s += ans\n arr.append(s)\n start += n - c\n end -= n - c\n c += 1\n return arr", "def pattern(n):\n N = n * (n + 1)\n l = [i for i in range(1, N + 1)]\n result = []\n for i in range(n):\n S = '--' * i\n for j in range(n - i):\n S += str(l[0])\n l.remove(l[0])\n S += '*'\n for k in range(n - i):\n S += str(l[-n + k + i])\n l.remove(l[-n + k + i])\n if n - i - k > 1:\n S += '*'\n result.append(S)\n return result", "def pattern(n):\n (start, end) = (1, n * (n + 1))\n lines = []\n for i in range(n, 0, -1):\n row = list(range(start, start + i)) + list(range(end - i + 1, end + 1))\n lines.append('-' * (2 * (n - i)) + '*'.join((str(v) for v in row)))\n start += i\n end -= i\n return lines", "def pattern(n):\n ans = [[] for i in range(n)]\n val = 1\n for i in range(n):\n for j in range(val, val + n - i):\n ans[i].append(j)\n val = ans[i][-1] + 1\n val = val\n for i in range(n - 1, -1, -1):\n for j in range(val, val + n - i):\n ans[i].append(j)\n val = ans[i][-1] + 1\n out = []\n for i in range(n):\n val = '' + 2 * i * '-'\n for j in range(len(ans[i]) - 1):\n val += str(ans[i][j]) + '*'\n val += str(ans[i][-1])\n out.append(val)\n return out", "def pattern(n):\n res = []\n c = 1\n for i in range(n, 0, -1):\n t = []\n for j in range(i):\n t.append(c)\n c += 1\n res.append(t)\n for i in range(1, n + 1):\n t = res[n - i]\n for j in range(i):\n t.append(c)\n c += 1\n res[n - i] = t\n for i in range(n):\n res[i] = '-' * (i * 2) + '*'.join(map(str, res[i]))\n return res", "def pattern(n):\n count = 1\n list = []\n for i in range(n):\n list.append('')\n for j in range(n):\n if i > j:\n list[i] = str(list[i]) + '--'\n else:\n list[i] = str(list[i]) + str(count) + '*'\n count = count + 1\n for i in range(n):\n for j in range(i + 1):\n if j == 0:\n list[n - 1 - i] = str(list[n - 1 - i]) + str(count)\n else:\n list[n - 1 - i] = str(list[n - 1 - i]) + '*' + str(count)\n count = count + 1\n return list", "def pattern(n):\n res = ['' for i in range(n)]\n num = 1\n for row in range(0, n):\n numTerms = n - row\n for d in range(2 * row):\n res[row] += '-'\n for i in range(numTerms):\n res[row] += str(num) + '*'\n num += 1\n for row in range(n - 1, -1, -1):\n numTerms = n - row\n for i in range(1, numTerms):\n res[row] += str(num) + '*'\n num += 1\n res[row] += str(num)\n num += 1\n return res", "def pattern(n):\n dashCount = 0\n output = []\n i = 1\n for j in range(n):\n string = '-' * dashCount\n temp = []\n for k in range(n - j):\n temp.append(str(i))\n i += 1\n string += '*'.join(temp)\n output.append(string + '*')\n dashCount += 2\n for j in range(n):\n string = output[n - j - 1]\n temp = []\n for k in range(j + 1):\n temp.append(str(i))\n i += 1\n string += '*'.join(temp)\n output[n - j - 1] = string\n return output"], "starter_code": "def pattern(n):\n", "input_output": {"inputs": ["n = 3"], "outputs": ["1*2*3*10*11*12\n--4*5*8*9\n----6*7"]}, "difficulty": "EASY", "raw_tags": ["pattern-printing"], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/print-the-pattern1025/1", "Expected Auxiliary Space": "O(n^{2})", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n^{2})", "entry_point": "pattern", "task_id": "TACO_lite/400", "example": [[], []]} +{"requirement": "Given two lists V1 and V2 of sizes n and m respectively. Return the list of elements common to both the lists and return the list in sorted order. Duplicates may be there in the output list.\nExample:\nInput:\nn = 5\nv1[] = {3, 4, 2, 2, 4}\nm = 4\nv2[] = {3, 2, 2, 7}\nOutput:\n2 2 3\nExplanation:\nThe common elements in sorted order are {2 2 3}\nYour Task:\nThis is a function problem. You need to complete the function common_element that takes both the lists as parameters and returns a list of common elements. \nConstraints:\n1 \u2264 n, m \u2264 10^{5}\n1 \u2264 V_{i} \u2264 10^{5}", "solutions": ["def common_element(v1, v2):\n res = []\n map = {}\n for i in v1:\n if i in map:\n map[i] += 1\n else:\n map[i] = 1\n v2.sort()\n for i in v2:\n if i in map and map[i] > 0:\n res.append(i)\n map[i] -= 1\n return res", "def common_element(v1, v2):\n v1.sort()\n v2.sort()\n i = 0\n j = 0\n ans = []\n while i < len(v1) and j < len(v2):\n if v1[i] == v2[j]:\n ans.append(v1[i])\n i += 1\n j += 1\n elif v1[i] < v2[j]:\n i += 1\n else:\n j += 1\n ans.sort()\n return ans", "def common_element(v1, v2):\n res = []\n v1Dict = {}\n v2Dict = {}\n for i in v1:\n v1Dict[i] = 1 + v1Dict.get(i, 0)\n for i in v2:\n v2Dict[i] = 1 + v2Dict.get(i, 0)\n for i in sorted(v1Dict):\n if i in v2Dict:\n c = [i] * min(v1Dict[i], v2Dict[i])\n res += c\n return res", "def common_element(v1, v2):\n res = []\n d = {}\n for num in v1:\n d[num] = d.get(num, 0) + 1\n for num in v2:\n if num in d and d[num] > 0:\n res.append(num)\n d[num] -= 1\n return sorted(res)", "from heapq import heapify, heappush, heappop\n\ndef common_element(v1, v2):\n hashmap = {}\n for i in v1:\n if i not in hashmap:\n hashmap[i] = 1\n else:\n hashmap[i] += 1\n result = []\n for j in v2:\n if j in hashmap and hashmap[j] > 0:\n hashmap[j] -= 1\n result.append(j)\n result.sort()\n return result", "def common_element(v1, v2):\n dict = {}\n c = []\n for i in v1:\n if i not in dict:\n dict[i] = 1\n else:\n dict[i] += 1\n for i in v2:\n if i in dict and dict[i] > 0:\n c.append(i)\n dict[i] -= 1\n c.sort()\n return c", "from collections import Counter\n\ndef common_element(v1, v2):\n v1 = Counter(v1)\n v2 = Counter(v2)\n lst = []\n for i in v1:\n if i in v2:\n for j in range(min(v1[i], v2[i])):\n lst.append(i)\n return sorted(lst)", "def common_element(v1, v2):\n mdict = {}\n res = []\n for x in v1:\n if x in mdict:\n mdict[x] += 1\n else:\n mdict[x] = 1\n v2.sort()\n for x in v2:\n if x in mdict and mdict[x] > 0:\n res.append(x)\n mdict[x] -= 1\n return res", "from collections import defaultdict\n\ndef common_element(v1, v2):\n v1.sort()\n v2.sort()\n l = []\n d1 = defaultdict(int)\n for i in v1:\n d1[i] += 1\n for j in v2:\n if j in d1 and d1[j] != 0:\n d1[j] -= 1\n l.append(j)\n return l", "from collections import Counter\n\ndef common_element(v1, v2):\n ans = []\n a = Counter(v1)\n v2.sort()\n for i in v2:\n if i in a and a[i] > 0:\n ans.append(i)\n a[i] -= 1\n return ans", "def common_element(v1, v2):\n (freq, l) = ({}, [])\n for i in v1:\n if i not in freq:\n freq.update({i: 1})\n else:\n freq[i] += 1\n for i in v2:\n if i in freq and freq[i] > 0:\n l.append(i)\n freq[i] -= 1\n return sorted(l)", "def common_element(v1, v2):\n v1 = sorted(v1)\n v2 = sorted(v2)\n d = {}\n d1 = {}\n l = []\n for i in v1:\n if i not in d:\n d[i] = 1\n else:\n d[i] = d[i] + 1\n for i in v2:\n if i not in d1:\n d1[i] = 1\n else:\n d1[i] = d1[i] + 1\n kkeys = list(d.keys())\n kkeys.sort()\n for i in kkeys:\n if i in d1:\n k = min(d[i], d1[i])\n l = l + [i] * k\n return l", "def common_element(v1, v2):\n v1.sort()\n v2.sort()\n b = []\n while v1 and v2:\n if v1[0] != v2[0]:\n if v1[0] < v2[0]:\n v1.pop(0)\n else:\n v2.pop(0)\n else:\n b.append(v1[0])\n v1.pop(0)\n v2.pop(0)\n return b", "def common_element(v1, v2):\n d = {}\n ans = []\n for i in v1:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n for i in v2:\n if i in d and d[i] != 0:\n ans.append(i)\n d[i] -= 1\n ans.sort()\n return ans", "from collections import defaultdict\n\ndef common_element(v1, v2):\n ans = []\n m = {}\n for i in v1:\n if i in m:\n m[i] += 1\n else:\n m[i] = 1\n ans = []\n for i in v2:\n if i in m and m[i] > 0:\n ans.append(i)\n m[i] -= 1\n ans.sort()\n return ans", "from collections import defaultdict\n\ndef common_element(v1, v2):\n (d1, d2) = (defaultdict(int), defaultdict(int))\n for i in v1:\n d1[i] += 1\n for i in v2:\n d2[i] += 1\n ans = []\n for (key, val) in d1.items():\n if key in d2:\n second = d2[key]\n for i in range(min(second, val)):\n ans.append(key)\n return sorted(ans)", "def common_element(v1, v2):\n v1.sort()\n v2.sort()\n (i, j) = (0, 0)\n li = []\n (n1, n2) = (len(v1), len(v2))\n while i < n1 and j < n2:\n if v1[i] == v2[j]:\n li.append(v1[i])\n i += 1\n j += 1\n elif v1[i] < v2[j]:\n i += 1\n else:\n j += 1\n return li", "def common_element(v1, v2):\n v1.sort()\n v2.sort()\n res = []\n i = 0\n j = 0\n n = len(v1)\n m = len(v2)\n while i < n and j < m:\n if v1[i] == v2[j]:\n res.append(v1[i])\n i += 1\n j += 1\n elif v1[i] > v2[j]:\n j += 1\n else:\n i += 1\n return res", "def common_element(v1, v2):\n l = []\n d = {}\n for i in v1:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for i in v2:\n if i in d and d[i] > 0:\n l.append(i)\n d[i] -= 1\n return sorted(l)", "def common_element(v1, v2):\n map1 = {}\n map2 = {}\n for i in range(len(v1)):\n if v1[i] not in map1:\n map1[v1[i]] = 1\n else:\n map1[v1[i]] += 1\n for i in range(len(v2)):\n if v2[i] not in map2:\n map2[v2[i]] = 1\n else:\n map2[v2[i]] += 1\n new = []\n for i in map1:\n if i in map2:\n x = [i] * min(map1[i], map2[i])\n new.extend(x)\n new.sort()\n return new", "from collections import Counter\n\ndef common_element(v1, v2):\n c1 = Counter(v1)\n c2 = Counter(v2)\n m = len(v1)\n n = len(v2)\n\n def getCommEle(v, c1, c2):\n res = []\n for num in set(v):\n if c1[num] > 0 and c2[num] > 0:\n for i in range(min(c1[num], c2[num])):\n res.append(num)\n return sorted(res)\n if m <= n:\n return getCommEle(v1, c1, c2)\n else:\n return getCommEle(v2, c1, c2)", "def common_element(v1, v2):\n d = {}\n ans = []\n for val in v1:\n if val in d:\n d[val] = d[val] + 1\n else:\n d[val] = 1\n v2 = sorted(v2)\n for val in v2:\n if val in d and d[val] > 0:\n ans.append(val)\n d[val] = d[val] - 1\n return ans", "def common_element(v1, v2):\n ans = []\n v1 = sorted(v1)\n l1 = len(v1)\n v2 = sorted(v2)\n l2 = len(v2)\n i = 0\n j = 0\n while i < l1 and j < l2:\n if v1[i] == v2[j]:\n ans.append(v1[i])\n j = j + 1\n i = i + 1\n elif v1[i] > v2[j]:\n j = j + 1\n elif v1[i] < v2[j]:\n i = i + 1\n return ans", "def common_element(v1, v2):\n v1.sort()\n v2.sort()\n d1 = {}\n d2 = {}\n for i in v1:\n if i in d1:\n d1[i] += 1\n else:\n d1[i] = 1\n for i in v2:\n if i in d2:\n d2[i] += 1\n else:\n d2[i] = 1\n ans = []\n for i in d1:\n if i in d2:\n c = min(d1[i], d2[i])\n while c > 0:\n ans.append(i)\n c -= 1\n ans.sort()\n return ans", "from collections import defaultdict\n\ndef common_element(v1, v2):\n d = defaultdict(int)\n finalList = []\n for i in v1:\n d[i] += 1\n for i in v2:\n if d[i] != 0:\n finalList.append(i)\n d[i] -= 1\n finalList.sort()\n return finalList", "import operator as op\n\ndef common_element(v1, v2):\n ans = []\n i = j = 0\n v1 = sorted(v1)\n v2 = sorted(v2)\n while i < len(v1) and j < len(v2):\n if v1[i] == v2[j]:\n ans.append(v1[i])\n i += 1\n j += 1\n elif v1[i] > v2[j]:\n j += 1\n else:\n i += 1\n return ans", "def common_element(v1, v2):\n res = []\n a = sorted(v1)\n b = sorted(v2)\n i = 0\n j = 0\n while i < len(a) and j < len(b):\n if a[i] == b[j]:\n res.append(a[i])\n i = i + 1\n j = j + 1\n elif a[i] > b[j]:\n j = j + 1\n elif a[i] < b[j]:\n i = i + 1\n return sorted(res)", "from collections import Counter\n\ndef common_element(v1, v2):\n freq = Counter(v1)\n ans = list()\n for e in v2:\n if e in freq:\n freq[e] -= 1\n if freq[e] >= 0:\n ans.append(e)\n return sorted(ans)", "def common_element(v1, v2):\n result = []\n hash_v1 = {}\n hash_v2 = {}\n for i in range(len(v1)):\n if v1[i] in hash_v1:\n hash_v1[v1[i]] += 1\n else:\n hash_v1[v1[i]] = 1\n for i in range(len(v2)):\n if v2[i] in hash_v2:\n hash_v2[v2[i]] += 1\n else:\n hash_v2[v2[i]] = 1\n for i in hash_v1:\n if i in hash_v2:\n get_values_v1 = hash_v1[i]\n get_values_v2 = hash_v2[i]\n get_min = min(get_values_v1, get_values_v2)\n for j in range(get_min):\n result.append(i)\n result = sorted(result)", "from collections import defaultdict\n\ndef s():\n return 0\n\ndef common_element(v1, v2):\n hash1 = defaultdict(self.s)\n (_, L1) = max((len(v1), v1), (len(v2), v2))\n (_, L2) = min((len(v1), v1), (len(v2), v2))\n for i in L2:\n hash1[i] += 1\n res = []\n for i in L1:\n if hash1[i] > 0:\n hash1[i] -= 1\n res.append(i)\n res.sort()\n return res", "def common_element(v1, v2):\n out = []\n my_hm = {}\n for i in v1:\n if i in my_hm:\n my_hm[i] += 1\n else:\n my_hm[i] = 1\n for j in v2:\n if j in my_hm and my_hm[j] != 0:\n out.append(j)\n my_hm[j] -= 1\n out.sort()\n return out", "def common_element(v1, v2):\n v1.sort()\n v2.sort()\n ls = []\n d = dict()\n for i in v1:\n if i in d.keys():\n d[i] += 1\n else:\n d[i] = 1\n for i in v2:\n if i in d.keys() and d[i] != 0:\n ls.append(i)\n d[i] -= 1\n return ls", "def common_element(v1, v2):\n hm = {}\n res = []\n for i in v1:\n if i in hm:\n hm[i] += 1\n else:\n hm[i] = 1\n for i in v2:\n if i in hm:\n res.append(i)\n hm[i] -= 1\n if hm[i] == 0:\n del hm[i]\n res.sort()\n return res", "def common_element(v1, v2):\n hash = {}\n for i in range(len(v1)):\n if v1[i] in hash:\n hash[v1[i]] += 1\n else:\n hash[v1[i]] = 1\n ans = []\n for j in v2:\n if j in hash and hash[j] != 0:\n ans.append(j)\n hash[j] -= 1\n return sorted(ans)", "def common_element(v1, v2):\n commonhashA = {}\n commonhashB = {}\n for i in v1:\n if not i in commonhashA:\n commonhashA[i] = 1\n else:\n commonhashA[i] += 1\n for j in v2:\n if not j in commonhashB:\n commonhashB[j] = 1\n else:\n commonhashB[j] += 1\n tmp = []\n for k in v2:\n if k in commonhashA and commonhashA[k] != 0:\n commonhashA[k] -= 1\n tmp.append(k)\n tmp.sort()\n return tmp", "def common_element(v1, v2):\n a = v1\n b = v2\n list = []\n dict = {}\n for i in a:\n if i in dict:\n dict[i] += 1\n else:\n dict[i] = 1\n b.sort()\n for i in b:\n if i in dict and dict[i] > 0:\n list.append(i)\n dict[i] -= 1\n return list", "def common_element(V1, V2):\n V1.sort()\n V2.sort()\n l = []\n (i, j) = (0, 0)\n while i < len(V1) and j < len(V2):\n if V1[i] == V2[j]:\n l.append(V1[i])\n i += 1\n j += 1\n elif V1[i] > V2[j]:\n j += 1\n else:\n i += 1\n return l", "def common_element(v1, v2):\n d = dict()\n d1 = dict()\n for i in v1:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n for i in v2:\n if i not in d1:\n d1[i] = 1\n else:\n d1[i] += 1\n ans = []\n for i in sorted(d):\n if i in d1:\n l = [i] * min(d[i], d1[i])\n ans += l\n return ans", "from collections import Counter\n\ndef common_element(v1, v2):\n c1 = Counter(v1)\n c2 = Counter(v2)\n l = []\n for (i, j) in c2.items():\n if i in c1:\n l += [i] * min(j, c1[i])\n l.sort()\n return l", "def common_element(a, b):\n v1.sort()\n v2.sort()\n s = []\n i = 0\n j = 0\n while i < len(v1) and j < len(v2):\n if v1[i] < v2[j]:\n i = i + 1\n elif v1[i] > v2[j]:\n j = j + 1\n else:\n s.append(v1[i])\n i += 1\n j += 1\n return s", "from collections import defaultdict\n\ndef common_element(v1, v2):\n ans = []\n sample = defaultdict(int)\n for c in v1:\n sample[c] += 1\n v2.sort()\n for c in v2:\n if c in sample and sample[c] > 0:\n ans.append(c)\n sample[c] -= 1\n return ans", "def common_element(v1, v2):\n ans = []\n dic = {}\n for i in range(len(v1)):\n if v1[i] in dic:\n dic[v1[i]] += 1\n else:\n dic[v1[i]] = 1\n for j in range(len(v2)):\n if v2[j] in dic.keys():\n ans.append(v2[j])\n if dic[v2[j]] == 1:\n dic.pop(v2[j])\n else:\n dic[v2[j]] -= 1\n ans.sort()\n return ans", "def common_element(v1, v2):\n tab = {}\n res = []\n for val in v1:\n if val in tab:\n tab[val] += 1\n else:\n tab[val] = 1\n v2.sort()\n for val in v2:\n if val in tab and tab[val] > 0:\n res.append(val)\n tab[val] -= 1\n return res", "def common_element(v1, v2):\n map1 = {}\n map2 = {}\n answer = []\n for i in v1:\n map1[i] = map1.get(i, 0) + 1\n for i in v2:\n map2[i] = map2.get(i, 0) + 1\n for key in map1.keys():\n if key in map2.keys():\n for i in range(min(map1[key], map2[key])):\n answer.append(key)\n answer.sort()\n return answer", "def common_element(v1, v2):\n d1 = {}\n d2 = {}\n for i in v1:\n d1[i] = d1.get(i, 0) + 1\n for i in v2:\n d2[i] = d2.get(i, 0) + 1\n l = set(v1).intersection(set(v2))\n l = sorted(l)\n ans = []\n for i in l:\n a = min(d1[i], d2[i])\n for j in range(a):\n ans.append(i)\n return ans", "def common_element(v1, v2):\n dic = {}\n for i in v1:\n if i in dic.keys():\n dic[i] += 1\n else:\n dic[i] = 1\n mylist = []\n for i in v2:\n if i in dic.keys() and dic[i] != 0:\n mylist.append(i)\n dic[i] -= 1\n mylist.sort()\n return mylist", "def common_element(v1, v2):\n d = {}\n r = []\n for i in v1:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for i in v2:\n if i in d:\n r.append(i)\n if d[i] == 1:\n del d[i]\n else:\n d[i] -= 1\n r.sort()\n return r", "def common_element(v1, v2):\n res = []\n v1.sort()\n v2.sort()\n (p1, p2) = (0, 0)\n while p1 < len(v1) and p2 < len(v2):\n if v1[p1] == v2[p2]:\n res.append(v1[p1])\n p1 += 1\n p2 += 1\n elif v1[p1] > v2[p2]:\n p2 += 1\n else:\n p1 += 1\n return res", "def common_element(v1, v2):\n res = []\n hash = {}\n for x in v1:\n if x in hash:\n hash[x] += 1\n else:\n hash[x] = 1\n for x in v2:\n if x in hash:\n hash[x] -= 1\n res.append(x)\n if hash[x] == 0:\n hash.pop(x)\n res.sort()\n return res", "from collections import Counter\n\ndef common_element(v1, v2):\n d1 = Counter(v1)\n d2 = Counter(v2)\n lst = []\n for key in d1.keys():\n if d2.get(key) != None:\n lst.extend([key] * min(d1[key], d2[key]))\n return sorted(lst)", "def common_element(v1, v2):\n res = []\n\n def form_maps(a):\n d = {}\n for elm in a:\n if elm not in d:\n d[elm] = 1\n else:\n d[elm] += 1\n return d\n (map1, map2) = (form_maps(v1), form_maps(v2))\n for (k, v) in map1.items():\n if k in map2:\n cnt = 0\n while cnt < min(map1[k], map2[k]):\n res.append(k)\n cnt += 1\n res.sort()\n return res", "def common_element(v1, v2):\n d = {}\n for x in v1:\n if d.get(x) == None:\n d[x] = 1\n else:\n d[x] += 1\n l = []\n for x in v2:\n if d.get(x) != None:\n if d[x] > 0:\n l.append(x)\n d[x] -= 1\n l.sort()\n return l", "from collections import Counter\n\ndef common_element(v1, v2):\n c1 = Counter(v1)\n c2 = Counter(v2)\n ans = []\n for j in c1:\n if j in c2:\n ans += [j] * min(c1[j], c2[j])\n return sorted(ans)", "def common_element(arr1, arr2):\n d1 = {}\n d2 = {}\n s = set(arr1)\n ans = []\n for i in range(len(arr1)):\n d1[arr1[i]] = d1.get(arr1[i], 0) + 1\n for i in range(len(arr2)):\n if arr2[i] in d1 and d1[arr2[i]] > 0:\n d1[arr2[i]] -= 1\n ans.append(arr2[i])\n ans.sort()\n return ans"], "starter_code": "def common_element(v1,v2):\n", "input_output": {"inputs": ["n = 5\r\nv1[] = {3, 4, 2, 2, 4}\r\nm = 4\r\nv2[] = {3, 2, 2, 7}"], "outputs": ["2 2 3"]}, "difficulty": "EASY", "raw_tags": ["Java", "STL", "Java-Collections"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/common-elements5420/1", "Expected Auxiliary Space": "", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "", "entry_point": "common_element", "task_id": "TACO_lite/365", "example": [[[5, [3, 4, 2, 2, 4], 4, [3, 2, 2, 7]]], [null]]} +{"requirement": "Your job is to return the volume of a cup when given the diameter of the top, the diameter of the bottom and the height.\n\nYou know that there is a steady gradient from the top to the bottom.\n\nYou want to return the volume rounded to 2 decimal places.\n\nExmples:\n```python\ncup_volume(1, 1, 1)==0.79\n\ncup_volume(10, 8, 10)==638.79\n\ncup_volume(1000, 1000, 1000)==785398163.4\n\ncup_volume(13.123, 123.12, 1)==4436.57\n\ncup_volume(5, 12, 31)==1858.51\n```\n\nYou will only be passed positive numbers.", "solutions": ["from math import pi\n\ndef cup_volume(d1, d2, h):\n return round(h / 12.0 * pi * (d1 ** 2 + d1 * d2 + d2 ** 2), 2)", "from math import pi\n\ndef cup_volume(d1, d2, height):\n (r1, r2) = (d1 / 2.0, d2 / 2.0)\n return round(pi * height * (pow(r1, 2) + r1 * r2 + pow(r2, 2)) / 3.0, 2)", "def cup_volume(d1, d2, h):\n return round(h * (d1 * d1 + d1 * d2 + d2 * d2) * 0.2617993878, 2)", "cup_volume = lambda d, D, h: round(__import__('math').pi * h / 12 * (d * d + d * D + D * D), 2)", "import math\n\ndef cup_volume(d1, d2, height):\n if d1 > d2:\n (d1, d2) = (d2, d1)\n if d1 == d2:\n return round((d1 / 2.0) ** 2 * math.pi * height, 2)\n x = d1 * float(height) / (d2 - d1)\n vol = (d2 / 2.0) ** 2 * math.pi * (height + x) / 3.0 - (d1 / 2.0) ** 2 * math.pi * x / 3.0\n return round(vol, 2)", "def cup_volume(d1, d2, height):\n v = 3.14159265359 / 3 * height * ((d1 / 2) ** 2 + (d2 / 2) ** 2 + d1 / 2 * d2 / 2)\n return round(v, 2)", "import math\n\ndef cup_volume(d1, d2, height):\n return round(math.pi * height * (d1 ** 2 + d2 ** 2 + d1 * d2) / 12, 2)", "from math import pi\n\ndef cup_volume(d1, d2, h):\n (r1, r2) = (d1 / 2, d2 / 2)\n return round(pi * (1 / 3) * h * (r1 ** 2 + r2 ** 2 + r1 * r2), 2)"], "starter_code": "def cup_volume(d1, d2, height):\n", "input_output": {"fn_name": "cup_volume", "inputs": [[1, 1, 1], [10, 8, 10], [1000, 1000, 1000], [13.123, 123.12, 1], [5, 12, 31]], "outputs": [[0.79], [638.79], [785398163.4], [4436.57], [1858.51]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Geometry"], "name": null, "source": "codewars", "tags": ["Geometry", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56a13035eb55c8436a000041", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "cup_volume", "task_id": "TACO_lite/298", "example": [[[1, 1, 1], [10, 8, 10], [1000, 1000, 1000], [13.123, 123.12, 1], [5, 12, 31]], ["0.79", "638.79", "785398163.4", "4436.57", "1858.51"]]} +{"requirement": "Define a function that takes in two non-negative integers `$a$` and `$b$` and returns the last decimal digit of `$a^b$`. Note that `$a$` and `$b$` may be very large!\n\nFor example, the last decimal digit of `$9^7$` is `$9$`, since `$9^7 = 4782969$`. The last decimal digit of `$({2^{200}})^{2^{300}}$`, which has over `$10^{92}$` decimal digits, is `$6$`. Also, please take `$0^0$` to be `$1$`.\n\nYou may assume that the input will always be valid.\n\n## Examples\n\n```python\nlast_digit(4, 1) # returns 4\nlast_digit(4, 2) # returns 6\nlast_digit(9, 7) # returns 9\nlast_digit(10, 10 ** 10) # returns 0\nlast_digit(2 ** 200, 2 ** 300) # returns 6\n```\n\n___\n\n## Remarks\n\n### JavaScript, C++, R, PureScript\n\nSince these languages don't have native arbitrarily large integers, your arguments are going to be strings representing non-negative integers instead.", "solutions": ["def last_digit(n1, n2):\n return pow(n1, n2, 10)", "rules = {0: [0, 0, 0, 0], 1: [1, 1, 1, 1], 2: [2, 4, 8, 6], 3: [3, 9, 7, 1], 4: [4, 6, 4, 6], 5: [5, 5, 5, 5], 6: [6, 6, 6, 6], 7: [7, 9, 3, 1], 8: [8, 4, 2, 6], 9: [9, 1, 9, 1]}\n\ndef last_digit(n1, n2):\n ruler = rules[int(str(n1)[-1])]\n return 1 if n2 == 0 else ruler[n2 % 4 - 1]", "def last_digit(n1, n2):\n return (n1 % 10) ** (n2 % 4 + 4 * bool(n2)) % 10", "E = [[0, 0, 0, 0], [1, 1, 1, 1], [6, 2, 4, 8], [1, 3, 9, 7], [6, 4, 6, 4], [5, 5, 5, 5], [6, 6, 6, 6], [1, 7, 9, 3], [6, 8, 4, 2], [1, 9, 1, 9]]\n\ndef last_digit(n1, n2):\n if n2 == 0:\n return 1\n return E[n1 % 10][n2 % 4]", "last_digit = lambda n1, n2: pow(n1, n2, 10)", "def last_digit(n1, n2):\n m1 = n1 % 10\n if m1 == 1:\n return 1\n if m1 == 2:\n if n2 == 0:\n return 1\n elif n2 % 4 == 3:\n return 8\n elif n2 % 4 == 0:\n return 6\n elif n2 % 4 == 2:\n return 4\n else:\n return 2\n if m1 == 3:\n if n2 == 0:\n return 1\n elif n2 % 4 == 0:\n return 1\n elif n2 % 2 == 0:\n return 9\n elif n2 % 4 == 3:\n return 7\n else:\n return 3\n if m1 == 4:\n if n2 == 0:\n return 1\n elif n2 % 4 == 2 or n2 % 4 == 0:\n return 6\n else:\n return 4\n if m1 == 5:\n if n2 == 0:\n return 1\n else:\n return 5\n if m1 == 6:\n if n2 == 0:\n return 1\n else:\n return 6\n if m1 == 7:\n if n2 == 0:\n return 1\n elif n2 % 4 == 3:\n return 3\n elif n2 % 4 == 0:\n return 1\n elif n2 % 4 == 2:\n return 9\n else:\n return 7\n if m1 == 8:\n if n2 == 0:\n return 1\n elif n2 % 4 == 3:\n return 2\n elif n2 % 4 == 0:\n return 6\n elif n2 % 4 == 2:\n return 4\n else:\n return 8\n if m1 == 9:\n if n2 == 0:\n return 1\n elif n2 % 2 == 1:\n return 9\n else:\n return 1\n if m1 == 0:\n if n2 == 0:\n return 1\n return 0", "def last_digit(n1, n2):\n last_dict = {0: [0], 1: [1], 2: [2, 4, 6, 8], 3: [3, 9, 7, 1], 4: [4, 6], 5: [5], 6: [6], 7: [7, 9, 3, 1], 8: [8, 4, 2, 6], 9: [9, 1]}\n if n2 == 0:\n return 1\n a = n1 % 10\n return last_dict[a][(n2 - 1) % len(last_dict[a])]", "def last_digit(n1, n2):\n if n2 == 0:\n return 1\n seq = [[0], [1], [2, 4, 8, 6], [3, 9, 7, 1], [4, 6], [5], [6], [7, 9, 3, 1], [8, 4, 2, 6], [9, 1]]\n l_digit = int(str(n1)[-1])\n position = n2 % len(seq[l_digit])\n return seq[l_digit][position - 1]"], "starter_code": "def last_digit(n1, n2):\n", "input_output": {"fn_name": "last_digit", "inputs": [[4, 1], [4, 2], [9, 7], [10, 1000000000], [38710248912497124917933333333284108412048102948908149081409204712406, 226628148126342643123641923461846128214626], [3715290469715693021198967285016729344580685479654510946723, 68819615221552997273737174557165657483427362207517952651]], "outputs": [[4], [6], [9], [0], [6], [7]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5511b2f550906349a70004e1", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "last_digit", "task_id": "TACO_lite/324", "example": [[[4, 1], [4, 2], [9, 7], [10, 10000000000], [1606938044258990275541962092341162602522202993782792835301376, 34679820440162766727291522857913285077400432927453350399864480129571625151552679665473828989182912797066473733424990924602022130834382211112859327]], ["4", "6", "9", "0", "6"]]} +{"requirement": "As you may know, once some people pass their teens, they jokingly only celebrate their 20th or 21st birthday, forever. With some maths skills, that's totally possible - you only need to select the correct number base!\n\nFor example, if they turn 32, that's exactly 20 - in base 16... Already 39? That's just 21, in base 19!\n\nYour task is to translate the given age to the much desired 20 (or 21) years, and indicate the number base, in the format specified below.\n\n**Note:** input will be always > 21\n\n\n### Examples:\n\n```\n32 --> \"32? That's just 20, in base 16!\"\n39 --> \"39? That's just 21, in base 19!\"\n```\n\n*Hint: if you don't know (enough) about [numeral systems](https://en.wikipedia.org/wiki/Numeral_system) and [radix](https://en.wikipedia.org/wiki/Radix), just observe the pattern!*\n\n---\n\n## My other katas\n\nIf you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-)\n\n---\n\n### *Translations are welcome!*", "solutions": ["def womens_age(n):\n return f\"{n}? That's just {20 + n % 2}, in base {n // 2}!\"", "womens_age = lambda n: f\"{n}? That's just 2{n % 2}, in base {n // 2}!\"", "def womens_age(n):\n return f\"{n}? That's just {(21 if n % 2 else 20)}, in base {((n - 1) // 2 if n % 2 else n // 2)}!\"", "def womens_age(n):\n for i in range(11, 100):\n (a, b) = divmod(n, i)\n if a == 2 and b < 2:\n return f\"{n}? That's just {a}{b}, in base {i}!\"", "def womens_age(n):\n a = 2\n L1 = [0, 1]\n for i in L1:\n x = int((n - L1[i]) / a)\n if n % x == L1[i]:\n base = x\n result = '%d%d' % (a, L1[i])\n return str(n) + \"? That's just \" + str(result) + ', in base ' + str(base) + '!'", "womens_age = lambda Q: f\"{Q}? That's just 2{1 & Q}, in base {Q >> 1}!\"", "def womens_age(n):\n return str(n) + \"? That's just 20, in base \" + str(n // 2) + '!' if n % 2 == 0 else str(n) + \"? That's just 21, in base \" + str(n // 2) + '!'"], "starter_code": "def womens_age(n):\n", "input_output": {"fn_name": "womens_age", "inputs": [[32], [39], [22], [65], [83]], "outputs": [["32? That's just 20, in base 16!"], ["39? That's just 21, in base 19!"], ["22? That's just 20, in base 11!"], ["65? That's just 21, in base 32!"], ["83? That's just 21, in base 41!"]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5e96332d18ac870032eb735f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "womens_age", "task_id": "TACO_lite/393", "example": [[[32], [39]], ["32? That's just 20, in base 16!", "39? That's just 21, in base 19!"]]} +{"requirement": "Given a positive integer N, find the number of factors in N! ( N factorial).\nExample :\nInput:\nN = 5\nOutput:\n16\nExplanation:\n5! is 120 and the number of factors of\n120 are 1 2 3 4 5 6 8 10 12 15 20 24 30\n40 60 120 So the number of factors are 16.\nExample 2:\nInput:\nN = 4\nOutput:\n8\nExplanation:\n4! is 24 and the number of factors of\n24 are 1 2 3 4 6 8 12 24\nSo the number of factors are 8.\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function factorsOfFactorial() which takes an integer N as an input parameter and return the number of factors of N factorial.\nExpected Time Complexity: O(NLogLogN)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 <= N <= 100", "solutions": ["def calWays(n, p):\n j = p\n c = 0\n while n // j > 0:\n c += n // j\n j *= p\n return c + 1\n\ndef factorsoffactorial(N):\n if N < 1:\n return 1\n t = N\n N = N + 1\n r = 1\n prime = []\n for i in range(N):\n prime.append(1)\n prime[0] = 0\n prime[1] = 0\n for i in range(2, int(N ** 0.5) + 1):\n j = 2\n while j * i < N:\n prime[j * i] = 0\n j += 1\n for i in range(len(prime)):\n if prime[i] == 1:\n r *= self.calWays(t, i)\n return r", "from math import sqrt\n\ndef factorsoffactorial(N):\n prime = [True] * (N + 1)\n i = 2\n while i * i <= N:\n if prime[i]:\n for j in range(i * i, N + 1, i):\n prime[j] = False\n i += 1\n res = 1\n for i in range(2, N + 1):\n if not prime[i]:\n continue\n x = 0\n y = i\n while N // y > 0:\n x += N // y\n y *= i\n res *= x + 1\n return res", "from math import sqrt\n\ndef factorsoffactorial(N):\n res = 1\n for i in range(2, N + 1):\n f = False\n for j in range(2, int(sqrt(i)) + 1):\n if i % j == 0:\n f = True\n break\n if f:\n continue\n x = 0\n y = i\n while N // y > 0:\n x += N // y\n y *= i\n res *= x + 1\n return res"], "starter_code": "def factorsoffactorial(N):\n", "input_output": {"inputs": ["N = 5", "N = 4"], "outputs": ["16", "8"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/no-of-factors-of-n4833/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(NLogLogN)", "entry_point": "factorsoffactorial", "task_id": "TACO_lite/345", "example": [[[5], [4]], ["16", "8"]]} +{"requirement": "You want to build a standard house of cards, but you don't know how many cards you will need. Write a program which will count the minimal number of cards according to the number of floors you want to have. For example, if you want a one floor house, you will need 7 of them (two pairs of two cards on the base floor, one horizontal card and one pair to get the first floor). Here you can see which kind of house of cards I mean:\nhttp://www.wikihow.com/Build-a-Tower-of-Cards\n\n## Note about floors:\nThis kata uses the British numbering system for building floors. If you want your house of cards to have a first floor, it needs a ground floor and then a first floor above that.\n\n### Details (Ruby & JavaScript & Python & R)\nThe input must be an integer greater than 0, for other input raise an error.\n\n### Details (Haskell)\nThe input must be an integer greater than 0, for other input return `Nothing`.", "solutions": ["def house_of_cards(n):\n if n >= 1:\n return (n + 1) * n / 2 + (n + 2) * (n + 1)\n raise ValueError", "def house_of_cards(n):\n assert n > 0\n return (n + 1) * (3 * n + 4) // 2", "def house_of_cards(floors):\n assert isinstance(floors, int) and floors > 0\n return (floors + 1) * (3 * floors + 4) // 2", "def house_of_cards(f):\n return f * (f + 1) / 2 + (f + 1) * (f + 2) if f > 0 else error", "def house_of_cards(floors):\n assert floors > 0\n return sum((2 + 3 * a for a in range(floors + 1)))", "def house_of_cards(n):\n if n < 1:\n raise error\n return 3 * n * (n + 1) // 2 + 2 * (n + 1)", "def house_of_cards(floors):\n if floors <= 0:\n raise ValueError('The input must be an integer greater than 0')\n return 2 + sum((3 * i + 2 for i in range(1, floors + 1)))", "def house_of_cards(floors):\n if floors < 1:\n raise Exception()\n return (floors + 1) * (3 * floors + 4) // 2"], "starter_code": "def house_of_cards(floors):\n", "input_output": {"fn_name": "house_of_cards", "inputs": [[1], [2], [3]], "outputs": [[7], [15], [26]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/543abbc35f0461d28f000c11", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "house_of_cards", "task_id": "TACO_lite/410", "example": [[[1]], [7.0]]} +{"requirement": "Given N in Gray Code, find its binary equivalent. Return the decimal representation of the binary equivalent.\nExample 1:\nInput: N = 4\nOutput: 7\nExplanation:\nGiven 4 representing gray code 110.\nBinary equivalent of gray code 110 is 100.\nReturn 7 representing gray code 100.\nExample 2:\nInput: N = 15\nOutput: 10\nExplanation:\nGiven 15 representing gray code 1000.\nBinary equivalent of gray code 1000 is 1111.\nReturn 10 representing gray code 1111 \nie binary 1010.\nExample 3:\nInput: N = 0\nOutput: 0\nExplanation: \nZero remains the same in all systems.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function grayToBinary() which accepts an integer n as an input parameter and returns decimal of the binary equivalent of the given gray code. \nExpected Time Complexity: O(log N)\nExpected Auxiliary Space: O(1)\nConstraints:\n0 <= N <= 10^{8}", "solutions": ["def graytobinary(n: int) -> int:\n binary = n\n while n > 0:\n n >>= 1\n binary ^= n\n return binary", "def graytobinary(n):\n b = 0\n while n > 0:\n b = b ^ n\n n = n >> 1\n return b", "def graytobinary(n):\n res = n\n while n > 0:\n n >>= 1\n res ^= n\n return res", "def graytobinary(n):\n b = 0\n for i in iter(int, 1):\n if n > 0:\n b = b ^ n\n n = n >> 1\n else:\n break\n return b", "def graytobinary(n: int) -> int:\n mask = n\n while mask != 0:\n mask >>= 1\n n ^= mask\n return n", "def graytobinary(n):\n ans = n\n while n > 0:\n n = n >> 1\n ans = ans ^ n\n return ans", "def graytobinary(n):\n gray_rep = bin(n)[2:]\n binary = gray_rep[0]\n for i in range(1, len(gray_rep)):\n if gray_rep[i] == '0':\n binary += binary[i - 1]\n else:\n binary += str(int(not int(binary[i - 1])))\n return int(binary, 2)", "def graytobinary(n):\n c = 0\n while n:\n c ^= n\n n >>= 1\n return c", "def graytobinary(n):\n binary = n & 1 << len(bin(n)) - 3\n for i in range(len(bin(n)) - 4, -1, -1):\n binary |= (binary >> 1 ^ n & 1 << i) & 1 << i\n return binary", "import math\n\ndef graytobinary(n):\n t = n\n while t != 0:\n t = t >> 1\n n = n ^ t\n return n", "def graytobinary(n):\n v = 0\n while n:\n v = v ^ n\n n = n >> 1\n return v", "def graytobinary(n):\n a = n >> 1\n while a:\n n ^= a\n a = a >> 1\n return n", "def graytobinary(n):\n k = len(bin(n)) - 2\n bin_y = 0\n xor = n >> k & 1\n bin_y = bin_y + xor\n k = k - 1\n while k >= 0:\n xor = xor ^ n >> k & 1\n bin_y = bin_y + (xor << k)\n k = k - 1\n return bin_y", "def graytobinary(n):\n N = n\n while n > 0:\n n = n >> 1\n N = N ^ n\n return N", "def graytobinary(n):\n x = 0\n while n > 0:\n x = x ^ n\n n = n >> 1\n return x", "def graytobinary(n):\n temp = n\n while n > 0:\n n >>= 1\n temp = temp ^ n\n return temp", "def graytobinary(n):\n inv = 0\n while n:\n inv = inv ^ n\n n = n >> 1\n return inv\n return n ^ n >> 1", "def graytobinary(n):\n r = n\n n >>= 1\n while n:\n r ^= n\n n >>= 1\n return r", "def graytobinary(n):\n result = n\n while n > 0:\n n = n >> 1\n result ^= n\n return result", "def graytobinary(n):\n count = 0\n while n:\n count ^= n\n n >>= 1\n return count", "def graytobinary(n):\n div = n\n while div // 2 != 0:\n n = n ^ div // 2\n div = div // 2\n return n", "def graytobinary(n):\n x = n\n while True:\n if n == x ^ x >> 1:\n return x\n break\n x = x ^ x >> 1"], "starter_code": "def graytobinary(n):\n", "input_output": {"inputs": ["N = 4", "N = 15", "N = 0"], "outputs": ["7", "10", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/gray-to-binary-equivalent-1587115620/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(log N)", "entry_point": "graytobinary", "task_id": "TACO_lite/398", "example": [[[4], [15], [0]], ["7", "10", "0"]]} +{"requirement": "Given a BST, and a reference to a Node x in the BST. Find the Inorder Successor of the given node in the BST.\n \nExample 1:\nInput:\n 2\n / \\\n 1 3\nK(data of x) = 2\nOutput: 3 \nExplanation: \nInorder traversal : 1 2 3 \nHence, inorder successor of 2 is 3.\nExample 2:\nInput:\n 20\n / \\\n 8 22\n / \\\n 4 12\n / \\\n 10 14\nK(data of x) = 8\nOutput: 10\nExplanation:\nInorder traversal: 4 8 10 12 14 20 22\nHence, successor of 8 is 10.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function inOrderSuccessor(). This function takes the root node and the reference node as argument and returns the node that is inOrder successor of the reference node. If there is no successor, return null value.\nExpected Time Complexity: O(Height of the BST).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= N <= 1000, where N is number of nodes", "solutions": ["def inorderSuccessor(root, x):\n ans = None\n while root != None:\n if root.data > x.data:\n ans = root\n root = root.left\n else:\n root = root.right\n return ans", "def inorderSuccessor(root, x):\n c = None\n while root is not None:\n if root.data > x.data:\n c = root\n root = root.left\n else:\n root = root.right\n return c", "def inorderSuccessor(root, p):\n if not root:\n return None\n if root.data <= p.data:\n return self.inorderSuccessor(root.right, p)\n return self.inorderSuccessor(root.left, p) or root\n\ndef inOrderTraversal(root, n, succ):\n if root == None:\n return\n self.inOrderTraversal(root.left, n, succ)\n if root.data > n.data and (not succ.left):\n succ.left = root\n return\n self.inOrderTraversal(root.right, n, succ)", "def inorderSuccessor(root, n):\n succ = Node(0)\n self.inOrderTraversal(root, n, succ)\n return succ.left\n\ndef inOrderTraversal(root, n, succ):\n if root == None:\n return\n self.inOrderTraversal(root.left, n, succ)\n if root.data > n.data and (not succ.left):\n succ.left = root\n return\n self.inOrderTraversal(root.right, n, succ)", "def min_right(root):\n if root == None:\n return None\n a = self.min_right(root.left)\n if a == None:\n return root\n else:\n return a\n\ndef find(root, x):\n if x.data == root.data:\n return self.min_right(root.right)\n if x.data < root.data:\n a = self.find(root.left, x)\n if a == None:\n return root\n else:\n return a\n else:\n a = self.find(root.right, x)\n return a\n\ndef inorderSuccessor(root, x):\n return self.find(root, x)", "def inorderSuccessor(root, x):\n res = []\n ans = []\n\n def inorder(root):\n if root == None:\n return\n inorder(root.left)\n res.append(root.data)\n ans.append(root)\n inorder(root.right)\n inorder(root)\n i = res.index(x.data)\n if i < len(res) - 1:\n return ans[i + 1]\n else:\n return None", "def inorderSuccessor(root, x):\n successor = None\n while root:\n if root.data <= x.data:\n root = root.right\n else:\n successor = root\n root = root.left\n return successor", "def inorderSuccessor(root, x):\n y = self.inorder(root, [])\n i = y.index(x.data)\n try:\n return Node(y[i + 1])\n except IndexError:\n return None\n\ndef inorder(node, a):\n if node is None:\n return\n else:\n self.inorder(node.left, a)\n a.append(node.data)\n self.inorder(node.right, a)\n return a", "def minValue(node):\n while node.left:\n node = node.left\n return node\n\ndef get_node(root, node):\n if not root:\n return None\n x = self.get_node(root.left, node)\n if x:\n return x\n if root.data == node.data:\n return root\n y = self.get_node(root.right, node)\n if y:\n return y\n\ndef inorderSuccessor(root, x):\n x = self.get_node(root, x)\n if x.right is not None:\n return self.minValue(x.right)\n succ = None\n curr = root\n while curr and curr != x:\n if x.data > curr.data:\n curr = curr.right\n elif x.data <= curr.data:\n succ = curr\n curr = curr.left\n return succ", "def inorderSuccessor(root, x):\n stack = []\n curr = root\n prev = None\n while curr or stack:\n while curr:\n stack.append(curr)\n curr = curr.left\n curr = stack.pop()\n if prev and prev.data == x.data:\n return curr\n prev = curr\n curr = curr.right", "def inorderSuccessor(root, x):\n temp = root\n while temp:\n if temp.data == x.data:\n break\n elif temp.data > x.data:\n temp = temp.left\n else:\n temp = temp.right\n if temp is None:\n return None\n if temp.right:\n successor = self.find_min(temp.right)\n else:\n successor = self.find_ancestor(root, temp)\n return successor\n\ndef find_min(node):\n while node.left:\n node = node.left\n return node\n\ndef find_ancestor(root, node):\n successor = Node(-1)\n while root:\n if root.data < node.data:\n root = root.right\n elif root.data > node.data:\n successor = root\n root = root.left\n else:\n break\n return successor", "def inorderSuccessor(root, x):\n array = []\n self.inorder(root, array)\n for i in range(len(array)):\n if array[i].data == x.data:\n if len(array) == i + 1:\n return None\n else:\n return array[i + 1]\n\ndef inorder(node, array):\n if node:\n self.inorder(node.left, array)\n array.append(node)\n self.inorder(node.right, array)", "def InOrder(root, x, suc):\n if root != None:\n self.InOrder(root.left, x, suc)\n if root.data > x.data:\n if suc[0] == None:\n suc[0] = root\n self.InOrder(root.right, x, suc)\n\ndef inorderSuccessor(root, x):\n suc = [None]\n self.InOrder(root, x, suc)\n return suc[0]", "def inorderSuccessor(root, x):\n nextGreaterNode = None\n temp = root\n while temp:\n if x.data < root.data:\n nextGreaterNode = root\n root = root.left\n elif x.data == root.data:\n if root.right:\n focus = root.right\n while focus:\n if focus.left:\n focus = focus.left\n else:\n return focus\n else:\n return nextGreaterNode if nextGreaterNode else None\n else:\n root = root.right\n return None", "def inorderSuccessor(root, x):\n res = None\n while root is not None:\n if root.data == x.data:\n break\n elif root.data < x.data:\n root = root.right\n else:\n res = root\n root = root.left\n root = root.right\n while root is not None and root.left is not None:\n root = root.left\n if root is None:\n return res\n return root", "def inorderSuccessor(root, n):\n t = None\n while root != None:\n if n.data < root.data:\n t = root\n root = root.left\n else:\n root = root.right\n return t", "def inorderSuccessor(root, x):\n l = []\n self.inorder(root, l, x)\n if len(l) > 1:\n return l[-1]\n else:\n return\n\ndef inorder(root, l, x):\n if not root:\n return\n self.inorder(root.left, l, x)\n if len(l) == 1:\n l.append(root)\n return\n if root.data == x.data:\n l.append(root)\n self.inorder(root.right, l, x)", "def inorderSuccessor(root, x):\n if not root or not x:\n return None\n succ = None\n v = root\n while v:\n if v.data <= x.data:\n v = v.right\n else:\n succ = v\n v = v.left\n return succ", "def left(root):\n if root.left is None:\n return root\n return self.left(root.left)\n\ndef inorder(root, x):\n if root is None:\n return None\n if root.data == x.data:\n if root.right is not None:\n return self.left(root.right)\n return None\n if root.data > x.data:\n result = self.inorder(root.left, x)\n if result is None:\n return root\n return result\n else:\n result = self.inorder(root.right, x)\n return result\n\ndef inorderSuccessor(root, x):\n return self.inorder(root, x)", "def innorder(root):\n if not root:\n return []\n return innorder(root.left) + [root] + innorder(root.right)\n\ndef __init__(val, k):\n self.right = None\n self.data = val\n self.left = None\n self.key = k\n\ndef inorderSuccessor(root, x):\n a = innorder(root)\n for i in range(len(a) - 1):\n if a[i].data == x.data:\n return a[i + 1]", "def inorderSuccessor(root, x):\n\n def inorder(tree, arr):\n if tree is not None:\n inorder(tree.left, arr)\n arr.append(tree)\n inorder(tree.right, arr)\n return arr\n array = inorder(root, [])\n for i in range(len(array)):\n if array[i].data == x.data and i + 1 < len(array):\n return array[i + 1]\n return", "def inorderSuccessor(root, x):\n re = []\n\n def trav(rot):\n if rot.left is not None:\n trav(rot.left)\n re.append(rot)\n if rot.right is not None:\n trav(rot.right)\n trav(root)\n for i in range(len(re)):\n if re[i].data == k:\n if i + 1 < len(re):\n return re[i + 1]", "def inorderSuccessor(root, x):\n self.ans = None\n\n def helper(root, x):\n if root is None:\n return\n if root.data <= x.data:\n helper(root.right, x)\n else:\n if self.ans is None:\n self.ans = root\n else:\n self.ans = min((root, self.ans), key=lambda m: m.data)\n helper(root.left, x)\n helper(root, x)\n return self.ans", "def inorderSuccessor(root, x):\n (self.ans, self.x) = (None, False)\n\n def helper(root, x):\n if root is None:\n return\n helper(root.left, x)\n if self.x and self.ans is None:\n self.ans = root\n return\n if root.data == x.data:\n self.x = True\n helper(root.right, x)\n helper(root, x)\n return self.ans", "def inorderSuccessor(root, x):\n curr = root\n succ = 999989\n while curr:\n if curr.data > x.data:\n succ = curr.data\n curr = curr.left\n elif curr.data <= x.data:\n curr = curr.right\n if succ == 999989:\n return Node(-1)\n return Node(succ)", "def inorderSuccessor(root, x):\n succ = None\n temp = x.data\n while True:\n if root == None:\n return succ\n elif root.data > temp:\n succ = root\n root = root.left\n else:\n root = root.right", "import sys\n\ndef inorderSuccessor(root, x):\n ans = None\n while root:\n if root.data <= x.data:\n root = root.right\n else:\n ans = root\n root = root.left\n return ans", "import sys\n\ndef inorderSuccessor(root, x):\n arr_inorder = []\n\n def inorder(r):\n nonlocal arr_inorder\n if not r:\n return\n inorder(r.left)\n arr_inorder.append(r)\n inorder(r.right)\n inorder(root)\n for i in range(len(arr_inorder)):\n if arr_inorder[i].data == x.data:\n return None if i + 1 >= len(arr_inorder) else arr_inorder[i + 1]\n return None", "def inorderSuccessor(root, x):\n\n def vamsi(root, x, ans):\n if not root:\n return None\n vamsi(root.left, x, ans)\n if x.data < root.data:\n ans.append(root.data)\n return\n vamsi(root.right, x, ans)\n ans = []\n vamsi(root, x, ans)\n return Node(ans[0]) if len(ans) > 0 else None", "def inorderSuccessor(root, x):\n succ = Node(-1)\n while root:\n if x.data >= root.data:\n root = root.right\n else:\n succ = root\n root = root.left\n return succ", "def inorderSuccessor(root, x):\n b = []\n c = []\n Solution.bst(root, b, c)\n if x.data in b:\n if b.index(x.data) >= len(b) - 1:\n return None\n return c[b.index(x.data) + 1]\n return None\n\ndef bst(root, x, y):\n if root.left:\n Solution.bst(root.left, x, y)\n x.append(root.data)\n y.append(root)\n if root.right:\n Solution.bst(root.right, x, y)", "def inorderSuccessor(root, x):\n self.successor = None\n\n def helper(root, x):\n if root == None:\n return\n if root.data == x:\n helper(root.right, x)\n elif root.data > x:\n self.successor = root\n helper(root.left, x)\n else:\n helper(root.right, x)\n helper(root, x.data)\n return self.successor", "def solve(root, x, suc, first):\n if root is None:\n return\n self.solve(root.left, x, suc, first)\n if len(suc) == 1:\n suc.append(root)\n return\n if root.data == x.data:\n suc.append(root)\n self.solve(root.right, x, suc, first)\n return suc\n\ndef inorderSuccessor(root, x):\n first = None\n suc = []\n self.solve(root, x, suc, first)\n if len(suc) > 1:\n return suc[-1]\n else:\n return", "def inorderSuccessor(root, x):\n l = []\n\n def inorder(root):\n if root is not None:\n inorder(root.left)\n l.append(root.data)\n inorder(root.right)\n inorder(root)\n m = x.data\n s = l.index(m)\n if m == l[-1]:\n return Node(-1)\n return Node(l[s + 1])", "def inorderSuccessor(root, x):\n self.suc = None\n\n def find(node):\n if node:\n find(node.left)\n if node.data > x.data and self.suc == None:\n self.suc = node\n find(node.right)\n find(root)\n return self.suc", "def __init__():\n self.ans = None\n\ndef inorderSuccessor(root, x):\n if not root:\n return self.ans\n if x.data >= root.data:\n return self.inorderSuccessor(root.right, x)\n if x.data < root.data:\n self.ans = root\n return self.inorderSuccessor(root.left, x)", "def inorderSuccessor(root, x):\n x = self.findNode(root, x)\n if x == -1:\n return None\n elif x.right:\n curr = x.right\n while curr:\n if not curr.left:\n break\n curr = curr.left\n return curr\n else:\n succ = None\n while root:\n if root.data < x.data:\n root = root.right\n elif root.data > x.data:\n succ = root\n root = root.left\n else:\n break\n return succ\n\ndef findNode(root, node):\n curr = root\n while curr:\n if curr.data < node.data:\n curr = curr.right\n elif curr.data > node.data:\n curr = curr.left\n else:\n return curr\n return -1", "def inorderSuccessor(root, x):\n (curr, nextBiggest) = (root, None)\n while curr:\n if curr.data <= x.data:\n curr = curr.right\n else:\n nextBiggest = curr\n curr = curr.left\n return nextBiggest", "def inorderSuccessor(root, x):\n ans = None\n\n def findNode(node):\n nonlocal ans\n if not node:\n return\n if node.data > x.data:\n ans = node\n return findNode(node.left)\n elif node.data < x.data:\n return findNode(node.right)\n else:\n return node\n node = findNode(root)\n if not node:\n return None\n\n def successor(node):\n if not node:\n return None\n if node.left:\n return successor(node.left)\n else:\n return node\n inter = successor(node.right)\n if not inter or inter.data < 0:\n return ans\n return inter", "def inorderSuccessor(root, x):\n currentNode = root\n if currentNode is None:\n return None\n while currentNode is not None:\n if currentNode.data == x.data:\n break\n elif currentNode.data > x.data:\n currentNode = currentNode.left\n else:\n currentNode = currentNode.right\n if currentNode.right is not None:\n successorNode = currentNode.right\n while successorNode.left is not None:\n successorNode = successorNode.left\n return successorNode\n successorNode = None\n ancestorNode = root\n while currentNode != ancestorNode:\n if currentNode.data < ancestorNode.data:\n successorNode = ancestorNode\n ancestorNode = ancestorNode.left\n else:\n ancestorNode = ancestorNode.right\n return successorNode", "def inorderSuccessor(root, x):\n curr = root\n while curr.data != x.data and curr:\n if x.data < curr.data:\n curr = curr.left\n if x.data > curr.data:\n curr = curr.right\n if curr is None:\n return -1\n ptr = curr\n if curr.right:\n curr = curr.right\n while curr.left:\n curr = curr.left\n return curr\n else:\n succ = Node(-1)\n while root:\n if root.data < x.data:\n root = root.right\n elif root.data > x.data:\n succ = root\n root = root.left\n else:\n break\n return succ", "def inorderSuccessor(root, X):\n if root is None or X is None:\n return None\n succ = None\n while root is not None:\n if root.data <= X.data:\n root = root.right\n else:\n succ = root\n root = root.left\n return succ", "def inorderSuccessor(root, x):\n inorder = []\n\n def fun(root, x):\n if root:\n fun(root.left, x)\n inorder.append(root.data)\n fun(root.right, x)\n fun(root, x)\n for i in range(0, len(inorder)):\n if inorder[i] == x.data:\n if i < len(inorder) - 1:\n return Node(inorder[i + 1])\n else:\n return None\n return None", "def inorderSuccessor(root, x):\n if not root:\n return None\n curr = root\n stack = []\n flag = False\n while True:\n if curr is not None:\n stack.append(curr)\n curr = curr.left\n elif stack:\n if flag:\n return stack.pop()\n curr = stack.pop()\n if curr.data == x.data:\n flag = True\n curr = curr.right\n else:\n return None", "def inorderSuccessor(root, x):\n stack = [root]\n num = float('inf')\n if root.data > x.data:\n num = root.data\n save_node = root\n while len(stack) != 0:\n node = stack.pop()\n l = node.left\n r = node.right\n if l:\n stack.append(l)\n if x.data < l.data and num > l.data:\n num = l.data\n save_node = l\n if r:\n stack.append(r)\n if x.data < r.data and num > r.data:\n num = r.data\n save_node = r\n if num == float('inf'):\n return None\n else:\n return save_node", "def inorderSuccessor(root, x):\n s = []\n t1 = Node(None)\n while 1:\n if root is not None:\n s.append(root)\n root = root.left\n elif s:\n t = s.pop()\n if t1.data == x.data:\n return t\n else:\n t1 = t\n root = t.right\n else:\n break\n return None", "def inOr(root, arr, x, c):\n if not root:\n return\n self.inOr(root.left, arr, x, c)\n arr.append(root)\n if root.data == x.data:\n c = c + 1\n self.inOr(root.right, arr, x, c)\n\ndef inorderSuccessor(root, x):\n arr = []\n self.inOr(root, arr, x, 0)\n i = 0\n for e in arr:\n if x.data == e.data:\n if i == len(arr) - 1:\n return None\n return arr[i + 1]\n i = i + 1", "def inorderSuccessor(root, x):\n curr = root\n stack = []\n while curr or stack:\n while curr:\n stack.append(curr)\n curr = curr.left\n curr = stack.pop()\n if curr.data == x.data:\n if curr.right:\n curr = curr.right\n while curr.left:\n curr = curr.left\n return curr\n elif stack:\n return stack.pop()\n else:\n return None\n curr = curr.right\n return None", "def inorderSuccessor(root, x):\n\n def helper(node, x, succ):\n if not node:\n return\n helper(node.left, x, succ)\n if node.data > x.data and (not succ.left):\n succ.left = node\n return\n helper(node.right, x, succ)\n if not root:\n return None\n succ = Node(0)\n helper(root, x, succ)\n return succ.left", "def inorderSuccessor(root, x):\n if not root:\n return None\n stack = []\n prev = 0\n while stack or root:\n while root:\n stack.append(root)\n root = root.left\n node = stack.pop()\n if prev == x.data:\n return node\n prev = node.data\n root = node.right\n return None", "def inorderSuccessor(root, x):\n\n def inorder(List, root):\n if not root:\n return\n inorder(List, root.left)\n List.append(root.data)\n inorder(List, root.right)\n List = []\n inorder(List, root)\n if x.data in List:\n I = List.index(x.data)\n else:\n return None\n if I < len(List) - 1:\n return Node(List[I + 1])\n else:\n return None", "def inorderSuccessor(root, x):\n arr = []\n\n def inorder(node):\n if not node:\n return\n inorder(node.left)\n arr.append(node.data)\n inorder(node.right)\n inorder(root)\n for i in range(0, len(arr)):\n if arr[i] > x.data:\n return Node(arr[i])", "def inorderSuccessor(root, x):\n\n def inorder(node):\n if node == None:\n return []\n else:\n return inorder(node.left) + [node.data] + inorder(node.right)\n l = inorder(root)\n ans = None\n for i in range(len(l)):\n if l[i] == x.data:\n if i == len(l) - 1:\n return None\n ans = l[i + 1]\n break\n\n def search(node, ans):\n if node == None:\n return\n if node.data < ans:\n return search(node.right, ans)\n elif node.data > ans:\n return search(node.left, ans)\n else:\n return node\n return search(root, ans)", "def inorderSuccessor(root, x):\n l = []\n\n def search(node, ans):\n l.append(node)\n if node == None:\n return\n if node.data < ans:\n return search(node.right, ans)\n elif node.data > ans:\n return search(node.left, ans)\n else:\n return node\n se = search(root, x.data)\n if se.right != None:\n temp = se.right\n while temp.left:\n temp = temp.left\n l.append(temp)\n mini = 99999999999999999999999\n ans = None\n for i in l:\n if i.data > x.data and i.data < mini:\n mini = i.data\n ans = i\n return ans", "import sys\n\ndef inorderSuccessor(root, x):\n maxi = [sys.maxsize]\n self.f(root, x, maxi)\n if maxi[0] == sys.maxsize:\n return None\n else:\n return Node(maxi[0])\n\ndef f(root, x, maxi):\n if root == None:\n return\n if x.data >= root.data:\n self.f(root.right, x, maxi)\n else:\n maxi[0] = min(maxi[0], root.data)\n self.f(root.left, x, maxi)", "def inorderSuccessor(root, x):\n self.a = list()\n new = Node(-1)\n\n def postorder(root, x):\n if root == None:\n return -1\n postorder(root.left, x)\n self.a.append(root.data)\n postorder(root.right, x)\n return self.a\n postorder(root, x)\n for i in range(len(self.a) - 1):\n if self.a[i] == x.data:\n new = Node(self.a[i + 1])\n break\n return new", "def inorderSuccessor(root, x):\n suc = None\n while root:\n if root.data <= x.data:\n root = root.right\n elif root.data > x.data:\n suc = root\n root = root.left\n return suc", "def inorderSuccessor(root, x):\n\n def f(r, x, s):\n if r == None:\n return s\n elif r.data <= x.data:\n return f(r.right, x, s)\n else:\n s = r\n return f(r.left, x, s)\n ans = f(root, x, None)\n return ans", "def inorder(root, A, tgt):\n if not root:\n return\n self.inorder(root.left, A, tgt)\n A.append(root)\n if root.data == tgt[0]:\n tgt[1] = len(A) - 1\n self.inorder(root.right, A, tgt)\n\ndef inorderSuccessor(root, x):\n tgt = [x.data, -1]\n path = []\n self.inorder(root, path, tgt)\n if tgt[1] + 1 >= len(path):\n return None\n return path[tgt[1] + 1]", "def inorderSuccessor(root, x):\n if root:\n self.inorderSuccessor(root.left, x)\n if self._found:\n self._successor = root\n self._found = False\n if root.data == x.data:\n self._found = True\n self.inorderSuccessor(root.right, x)\n return self._successor", "def inorderSuccessor(root, x):\n\n def inorderTraverse(root, ans):\n if root:\n inorderTraverse(root.left, ans)\n ans.append(root)\n inorderTraverse(root.right, ans)\n return ans\n test = inorderTraverse(root, [])\n smallest = 999999999\n start = False\n node = Node(-1)\n for item in test:\n if item.data == x.data:\n start = True\n if start:\n if item.data != 'N' and x.data < item.data < smallest:\n smallest = item.data\n node = item\n return node"], "starter_code": "def __init__(val, k):\n", "input_output": {"inputs": ["2\n / \\\n 1 3\nK(data of x) = 2", "20\n / \\\n 8 22\n / \\\n 4 12\n / \\\n 10 14\nK(data of x) = 8"], "outputs": ["3", "10"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Binary Search Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Range queries"], "skill_types": ["Data structures", "Range queries"], "url": "https://practice.geeksforgeeks.org/problems/inorder-successor-in-bst/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(Height of the BST).", "entry_point": "__init__", "task_id": "TACO_lite/261", "example": [[], []]} +{"requirement": "Given an array nums[] of N positive integers. Find the minimum number of operations required to modify the array such that array elements are in strictly increasing order (A[i] < A[i+1]).\nChanging a number to greater or lesser than original number is counted as one operation.\nExample 1:\nInput: nums[] = [1, 2, 3, 6, 5, 4]\nOutput: 2\nExplanation: By decreasing 6 by 2 and\nincreasing 4 by 2, arr will be like\n[1, 2, 3, 4, 5, 6] which is stricly \nincreasing.\nExample 2:\nInput: nums[] = [1, 2, 3, 4]\nOutput: 0\nExplanation: Arrays is already strictly\nincreasing.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function min_opeartions() which takes the array nums[] as input parameter and returns the minimum number of opeartion needed to make the array strictly increasing.\n \nExpected Time Complexity: O(n^2)\nExpected Space Complexity: O(n)\n \nConstraints: \n1 <= length of array <= 1000\n1 <= arr[i] <= 1000000", "solutions": ["from bisect import bisect_right\n\ndef min_operations(nums):\n for i in range(len(nums)):\n nums[i] -= i\n lis = []\n for i in range(len(nums)):\n pos = bisect_right(lis, nums[i])\n if pos == len(lis):\n lis.append(nums[i])\n else:\n lis[pos] = nums[i]\n return len(nums) - len(lis)", "def min_operations(nums):\n N = len(nums)\n dp = [1] * N\n for i in range(1, N):\n for j in range(i):\n if nums[i] - nums[j] >= i - j:\n dp[i] = max(dp[i], dp[j] + 1)\n return N - max(dp)", "def min_operations(a):\n n = len(a)\n dp = [1] * n\n for i in range(n):\n for j in range(i):\n if a[i] > a[j] and a[i] - a[j] >= i - j:\n dp[i] = max(dp[i], dp[j] + 1)\n return n - max(dp)", "def min_operations(nums):\n n = len(nums)\n dp = [1] * n\n ans = 1\n for i in range(1, n):\n maxi = 0\n for j in range(i):\n if nums[j] + (i - j) <= nums[i]:\n maxi = max(maxi, dp[j])\n dp[i] = 1 + maxi\n ans = max(ans, dp[i])\n return n - ans", "def LIS(arr, n):\n res = [1] * n\n for i in range(1, n):\n for j in range(i):\n if arr[j] < arr[i] and arr[i] - arr[j] >= i - j:\n res[i] = max(res[i], res[j] + 1)\n return res\n\ndef min_operations(nums):\n n = len(nums)\n lis = self.LIS(nums, n)\n return n - max(lis)", "def min_operations(arr):\n n = len(arr)\n if n == 1:\n return 0\n LIS = [0 for i in range(n)]\n le = 0\n for i in range(n):\n LIS[i] = 1\n for i in range(1, n):\n for j in range(i):\n if arr[i] > arr[j] and i - j <= arr[i] - arr[j]:\n LIS[i] = max(LIS[i], LIS[j] + 1)\n le = max(le, LIS[i])\n return n - le", "from math import inf\n\ndef min_operations(x):\n l = len(x)\n\n def f(i, p):\n if i == l:\n return 0\n if (i, p) in dp:\n return dp[i, p]\n ans = 1 + f(i + 1, p + 1)\n if x[i] > p:\n ans = min(ans, f(i + 1, x[i]))\n dp[i, p] = ans\n return ans\n dp = {}\n return min(f(1, x[0]), 1 + f(1, -10 ** 8))", "from bisect import *\n\ndef min_operations(nums):\n\n def lis(arr):\n n = len(arr)\n lis = [1] * n\n for i in range(1, n):\n for j in range(0, i):\n if arr[i] >= arr[j] + (i - j) and lis[i] < lis[j] + 1:\n lis[i] = lis[j] + 1\n maximum = 0\n for i in range(n):\n maximum = max(maximum, lis[i])\n return maximum\n l = lis(nums)\n n = len(nums)\n return n - l", "def min_operations(nums):\n arr = nums\n l = len(arr)\n if l == 1:\n return 0\n LIS = [0 for i in range(l)]\n lent = 0\n for i in range(l):\n LIS[i] = 1\n for i in range(1, l):\n for j in range(i):\n if arr[i] > arr[j] and i - j <= arr[i] - arr[j]:\n LIS[i] = max(LIS[i], LIS[j] + 1)\n lent = max(lent, LIS[i])\n return l - lent", "def min_operations(nums):\n dp = [1 for i in range(len(nums))]\n maxi = 1\n for i in range(len(nums)):\n for prev in range(i):\n if nums[prev] < nums[i] and i - prev <= nums[i] - nums[prev] and (1 + dp[prev] > dp[i]):\n dp[i] = 1 + dp[prev]\n if maxi < dp[i]:\n maxi = dp[i]\n return len(nums) - maxi", "def min_operations(nums):\n n = len(nums)\n ans = 1\n lis = [1 for i in range(n)]\n for i in range(1, n):\n for j in range(i):\n if nums[i] > nums[j] and i - j <= nums[i] - nums[j]:\n lis[i] = max(lis[i], lis[j] + 1)\n ans = max(ans, lis[i])\n return n - ans", "def min_operations(nums):\n N = len(nums)\n soln = [1] * N\n for i in range(1, N):\n for j in range(0, i):\n if nums[i] > nums[j] and i - j <= nums[i] - nums[j]:\n soln[i] = max(soln[i], 1 + soln[j])\n return N - max(soln)", "from bisect import bisect_left\n\ndef min_operations(arr):\n l = 1\n n = len(arr)\n dp = [1] * n\n for i in range(1, n):\n m = 1\n for j in range(i):\n if arr[j] < arr[i] and i - j <= arr[i] - arr[j] and (dp[j] + 1 > m):\n m = dp[j] + 1\n dp[i] = m\n if l < m:\n l = m\n return n - l", "def bsearch(arr, num):\n (l, r) = (0, len(arr) - 1)\n while r - l > 1:\n mid = (l + r) // 2\n if arr[mid] == num:\n l = mid\n elif arr[mid] > num:\n r = mid\n else:\n l = mid\n if num == arr[r]:\n return r + 1\n if num == arr[l]:\n return l + 1\n if num > arr[r]:\n return r + 1\n if num < arr[l]:\n return l\n return r\n\ndef lengthOfLIS(nums):\n if not nums:\n return 0\n store = [nums[0]]\n for num in nums[1:]:\n idx = self.bsearch(store, num)\n if idx == len(store):\n store.append(num)\n else:\n store[idx] = num\n return len(store)\n\ndef min_operations(nums):\n n = len(nums)\n new_nums = [nums[i] - i for i in range(n)]\n l = self.lengthOfLIS(new_nums)\n return n - l", "import heapq\n\ndef mod(nums):\n n = len(nums)\n dp = [-1 for i in range(n)]\n dp[0] = 1\n for i in range(1, n):\n dp[i] = 1\n for j in range(i - 1, -1, -1):\n if nums[i] <= nums[j]:\n continue\n if i - j <= nums[i] - nums[j]:\n dp[i] = max(dp[i], 1 + dp[j])\n return max(dp)\n\ndef min_operations(nums):\n return len(nums) - Solution.mod(nums)", "def min_operations(nums):\n if len(nums) == 1:\n return 0\n lis = [1 for i in range(len(nums))]\n max1 = 0\n for i in range(1, len(nums)):\n for j in range(0, i):\n if nums[i] > nums[j] and i - j <= nums[i] - nums[j]:\n lis[i] = max(lis[i], lis[j] + 1)\n max1 = max(max1, lis[i])\n return len(nums) - max1", "def min_operations(nums):\n n = len(nums)\n LIS = [0 for i in range(n)]\n z = 0\n for i in range(n):\n LIS[i] = 1\n for i in range(1, n):\n for j in range(i):\n if nums[i] > nums[j] and i - j <= nums[i] - nums[j]:\n LIS[i] = max(LIS[i], LIS[j] + 1)\n z = max(z, LIS[i])\n if n == 1:\n return 0\n return n - z", "def SIA(arr):\n dp = [1 for i in arr]\n for i in range(1, len(arr)):\n for j in range(i):\n if arr[i] > arr[j] and i - j <= arr[i] - arr[j]:\n dp[i] = max(dp[i], 1 + dp[j])\n return len(arr) - max(dp)\n\ndef min_operations(nums):\n return SIA(nums)", "def min_operations(nums):\n arr = nums.copy()\n n = len(nums)\n LIS = [0 for i in range(n)]\n len1 = 0\n for i in range(n):\n LIS[i] = 1\n for i in range(1, n):\n for j in range(i):\n if arr[i] > arr[j] and i - j <= arr[i] - arr[j]:\n LIS[i] = max(LIS[i], LIS[j] + 1)\n return n - max(LIS)"], "starter_code": "def min_operations(nums):\n", "input_output": {"inputs": ["nums[] = [1, 2, 3, 6, 5, 4]", "nums[] = [1, 2, 3, 4]"], "outputs": ["2", "0"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/convert-to-strictly-increasing-array3351/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n^2)", "entry_point": "min_operations", "task_id": "TACO_lite/394", "example": [[[[1, 0, -1, 0, -3, -6]], [[1, 0, -1, -2]]], [4, 3]]} +{"requirement": "Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.\n\nExample 1:\n\nInput: 5\nOutput: True\nExplanation:\nThe binary representation of 5 is: 101\n\n\n\nExample 2:\n\nInput: 7\nOutput: False\nExplanation:\nThe binary representation of 7 is: 111.\n\n\n\nExample 3:\n\nInput: 11\nOutput: False\nExplanation:\nThe binary representation of 11 is: 1011.\n\n\n\nExample 4:\n\nInput: 10\nOutput: True\nExplanation:\nThe binary representation of 10 is: 1010.", "solutions": ["def hasalternatingbits(n):\n if n % 2 == 0:\n n = n >> 1\n cnt = 0\n a = n\n while a > 0:\n cnt += 1\n a = a >> 1\n if cnt % 2 == 0:\n return False\n c = 1\n for i in range(1, cnt):\n c = c << 1\n if i % 2 == 0:\n c += 1\n return c == n", "def hasalternatingbits(n):\n before = None\n while n != 0:\n d = n % 2\n if not before:\n before = d + 1\n else:\n if before == d + 1:\n return False\n before = d + 1\n n = n >> 1\n return True", "def hasalternatingbits(n):\n res = []\n while n > 0:\n res.append(str(n % 2))\n n //= 2\n for i in range(1, len(res)):\n if res[i] == res[i - 1]:\n return False\n return True", "def hasalternatingbits(n):\n prev = n % 2\n n = n // 2\n while n > 0:\n now = n % 2\n if now == prev:\n return False\n n = n // 2\n prev = now\n return True", "def hasalternatingbits(n):\n return '00' not in bin(n) and '11' not in bin(n)", "def hasalternatingbits(n):\n i = n % 2\n while n > 0:\n if i % 2 == 0:\n n /= 2\n else:\n n = (n - 1) / 2\n i += 1\n return n == 0", "def hasalternatingbits(n):\n bin1 = str(bin(n)[2:])\n length = len(bin1)\n for i in range(0, length - 1):\n if bin1[i] == bin1[i + 1]:\n return False\n return True", "def hasalternatingbits(n):\n bits = bin(n)\n return all((bits[i] != bits[i + 1] for i in range(len(bin(n)) - 1)))", "def hasalternatingbits(n):\n prev = None\n while n:\n curr = n % 2\n if curr == prev:\n return False\n prev = curr\n n //= 2\n return True"], "starter_code": "def hasalternatingbits(n: int) -> bool:\n", "input_output": {"fn_name": "hasAlternatingBits", "inputs": [[5]], "outputs": [true]}, "difficulty": "EASY", "raw_tags": ["Bit Manipulation"], "name": null, "source": "leetcode", "tags": ["Bit manipulation"], "skill_types": ["Bit manipulation"], "url": "https://leetcode.com/problems/binary-number-with-alternating-bits/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "hasalternatingbits", "task_id": "TACO_lite/367", "example": [[[5], [7], [11], [10]], ["True", "False", "False", "True"]]} +{"requirement": "Given a number N. Check whether N is a Twisted Prime number or not.\nNote: A number is called Twisted Prime if it is a prime and its reverse is also a prime.\nExample 1:\nInput: N = 97\nOutput: 1\nExplanation: 97 is a prime number. Its \nreverse 79 isalso a prime number. Thus \n97 is a twisted Prime and so, answer is 1.\nExample 2:\nInput: N = 43\nOutput: 0\nExplanation: 43 is a prime number but its \nreverse 34 is not a prime.So, 43 is not a \ntwisted prime and thus, answer is 0.\nYour Task:You don't need to read input or print anything.Your task is to complete the function isTwistedPrime() which takes a number N as input parameter and returns 1 if it is a twisted prime number.Otherwise, it returns 0.\nExpected Time Complexity:(O(sqrt(max(N,RevN))), here RevN is the reverse of N.\nExpected Space Complexity:O(1)\nConstraints:\n1<=N<=10^{9}", "solutions": ["import math\n\ndef fun(n):\n if n == 0 or n == 1:\n return False\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\ndef istwistedprime(N):\n s = str(N)\n s = s[::-1]\n if fun(N) and fun(int(s)):\n return 1\n return 0", "def istwistedprime(N):\n flag = 1\n for i in range(2, int(N ** 0.5) + 1):\n if N % i == 0:\n flag = 0\n break\n flag = 1\n x = str(N)\n x = x[::-1]\n x = int(x)\n flag1 = 1\n for i in range(2, int(x ** 0.5) + 1):\n if x % i == 0:\n flag1 = 0\n break\n flag1 = 1\n if flag == 1 and flag1 == 1:\n return 1\n return 0", "from math import sqrt\n\ndef istwistedprime(N):\n flag1 = self.prime(N)\n rev = self.reverse(N)\n flag2 = self.prime(rev)\n if flag1 and flag2:\n return 1\n return 0\n\ndef prime(N):\n for i in range(2, int(sqrt(N)) + 1):\n if N % i == 0:\n return False\n return True\n\ndef reverse(N):\n rev = 0\n while N:\n rev = rev * 10\n digit = N % 10\n rev += digit\n N //= 10\n return rev", "import math as m\n\ndef istwistedprime(N):\n\n def prime(n):\n if n == 0 or n == 1:\n return False\n k = round(m.sqrt(n)) + 1\n for i in range(2, k):\n if n % i == 0:\n return False\n return True\n k = str(N)\n if prime(N) == True and prime(int(k[::-1])) == True:\n return 1\n return 0", "import math\n\ndef is_prime(n):\n if n == 1:\n return False\n elif n == 2:\n return True\n elif n % 2 == 0:\n return False\n else:\n for x in range(3, int(math.sqrt(n)) + 1, 2):\n if n % x == 0:\n return False\n break\n return True\n\ndef istwistedprime(N):\n x = str(N)\n y = int(x[::-1])\n if is_prime(N) == True & is_prime(y) == True:\n return 1\n return 0", "def istwistedprime(N):\n\n def prime(n):\n if n == 0 or n == 1:\n return 0\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return 0\n return 1\n x = int(str(N)[::-1])\n if prime(N) == 1 and prime(x) == 1:\n return 1\n return 0", "from math import sqrt\n\ndef isPrime(n):\n if n <= 1 or n % 2 == 0:\n return 0\n if n == 2 or n == 3:\n return 1\n for i in range(3, int(sqrt(n)) + 1, 2):\n if n % i == 0:\n return 0\n return 1\n\ndef istwistedprime(N):\n return self.isPrime(N) and self.isPrime(int(str(N)[::-1]))", "import math\n\ndef isPrime(n):\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return 0\n return 1\n\ndef istwistedprime(N):\n flag = self.isPrime(N)\n strr = str(N)\n strr = strr[::-1]\n N = int(strr)\n flag1 = self.isPrime(N)\n return 1 if flag == 1 and flag1 == 1 else 0", "import math\n\ndef istwistedprime(N):\n a = str(N)\n a = a[::-1]\n a = int(a)\n for i in range(2, int(math.sqrt(N)) + 1):\n if N % i == 0:\n return 0\n for i in range(2, int(math.sqrt(a)) + 1):\n if a % i == 0:\n return 0\n return 1", "def istwistedprime(N):\n s = str(N)\n s = s[::-1]\n s = int(s)\n for i in range(2, int(N ** 0.5) + 1):\n if N % i == 0:\n return 0\n for i in range(2, int(s ** 0.5) + 1):\n if s % i == 0:\n return 0\n return 1", "from math import sqrt\n\ndef istwistedprime(N):\n revno = int(str(N)[::-1])\n if self.prime(N) and self.prime(revno):\n return 1\n return 0\n\ndef prime(N):\n for i in range(2, int(sqrt(N)) + 1):\n if N % i == 0:\n return False\n return True", "def istwistedprime(N: int) -> int:\n\n def reverse(n: int) -> int:\n return int(str(N)[::-1])\n\n def is_prime(n: int) -> bool:\n if n < 2:\n return False\n else:\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n condition1 = is_prime(N)\n condition2 = is_prime(reverse(N))\n if condition1 and condition2:\n return 1\n else:\n return 0", "def istwistedprime(N):\n\n def h(n):\n if n == 0 or n == 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n if h(N) and h(int(str(N)[::-1])):\n return 1\n return 0", "def istwistedprime(N):\n\n def prime(n):\n if n == 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n if prime(N) and prime(int(str(N)[::-1])):\n return 1\n else:\n return 0", "def istwistedprime(N):\n\n def isPrime(num):\n if num < 2:\n return 0\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return 0\n return 1\n if isPrime(N) == 0:\n return 0\n r = ''\n while N > 0:\n r += str(N % 10)\n N = N // 10\n if isPrime(int(r)) == 0:\n return 0\n return 1", "import math\n\ndef istwistedprime(N):\n reversedString = str(N)[::-1]\n reversedNumber = int(reversedString)\n s = max(N, reversedNumber)\n s = int(math.sqrt(s))\n for i in range(2, s + 1):\n if N % i == 0:\n return 0\n if reversedNumber % i == 0:\n return 0\n return 1", "def istwistedprime(N):\n if N == 1 or N == 10:\n return 0\n import math\n a = str(N)\n a = a[::-1]\n a = int(a)\n s = max(N, a)\n s = int(math.sqrt(s))\n for i in range(2, s + 1):\n if N % i == 0:\n return 0\n if a % i == 0:\n return 0\n return 1", "def istwistedprime(N):\n\n def is_prime(n):\n if n <= 1:\n return False\n elif n > 1:\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n a = N\n b = int(str(N)[::-1])\n if is_prime(a):\n if is_prime(b):\n return 1\n return 0", "import math\n\ndef istwistedprime(N):\n\n def prime(N):\n a = 0\n if N < 2:\n return 0\n elif N == 2 or N == 3 or N == 5 or (N == 7) or (N == 11):\n return 1\n elif N % 2 == 0 or N % 3 == 0 or N % 5 == 0 or (N % 7 == 0) or (N % 11 == 0):\n return 0\n else:\n i = 5\n while i * i <= N:\n if N % i == 0 or N % (i + 2) == 0:\n return 0\n i = i + 6\n return 1\n n = N\n f = prime(N)\n sum = 0\n while n > 0:\n e = n % 10\n sum = sum * 10 + e\n n = n // 10\n c = prime(sum)\n if c == 1 and f == 1:\n return 1\n else:\n return 0", "def istwistedprime(N):\n p = 0\n import math\n for i in range(2, int(math.sqrt(N)) + 1):\n if N % i == 0:\n p = 1\n break\n if p == 0:\n N = str(N)\n N = N[::-1]\n n = int(N)\n p = 0\n import math\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n p = 1\n break\n if p == 0:\n return 1\n return 0", "def istwistedprime(N):\n if N == 1:\n return 0\n else:\n for i in range(2, int(N ** 0.5) + 1):\n if N % i == 0:\n return 0\n break\n else:\n s = str(N)\n p = int(s[-1:-len(s) - 1:-1])\n for i in range(2, int(p ** 0.5) + 1):\n if p % i == 0:\n return 0\n break\n else:\n return 1", "import math\n\ndef istwistedprime(N):\n n = N\n nr = int(str(n)[::-1])\n for i in range(2, math.ceil(math.sqrt(n)) + 1):\n if n % i == 0:\n return 0\n for i in range(2, math.ceil(math.sqrt(nr)) + 1):\n if nr % i == 0:\n return 0\n return 1", "from math import sqrt\n\ndef isPrime(num):\n flag = True\n for i in range(2, int(sqrt(num)) + 1):\n if num % i == 0:\n flag = False\n break\n return flag\n\ndef reverseNumber(n):\n ans = 0\n while n != 0:\n digit = n % 10\n ans = ans * 10 + digit\n n = n // 10\n return ans\n\ndef istwistedprime(N):\n reversenum = reverseNumber(N)\n if isPrime(N) and isPrime(reversenum):\n return 1\n else:\n return 0", "def istwistedprime(N):\n\n def prime(n):\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return 0\n else:\n return 1\n if prime(N):\n r = 0\n while N:\n d = N % 10\n r = r * 10 + d\n N = N // 10\n if prime(r):\n return 1\n else:\n return 0\n else:\n return 0", "def isPrime(n):\n if n == 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef reverse(n):\n rev_num = 0\n while n > 0:\n rem = n % 10\n rev_num = rev_num * 10 + rem\n n = n // 10\n return rev_num\n\ndef istwistedprime(N):\n rev_n = reverse(N)\n if isPrime(N) and isPrime(rev_n):\n return 1\n else:\n return 0", "import math\n\ndef istwistedprime(N):\n\n def isprime(x):\n c = 0\n for i in range(2, int(math.sqrt(x)) + 1):\n if x % i == 0:\n c = 1\n break\n if c == 0:\n return 1\n else:\n return 0\n x1 = isprime(N)\n x2 = str(N)\n x2 = x2[::-1]\n x3 = isprime(int(x2))\n if x1 == 1 and x3 == 1:\n return 1\n else:\n return 0", "def isprime(n):\n if n == 1 or n == 0:\n return 0\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return 0\n return 1\n\ndef rev(n):\n n1 = str(n)\n n1 = n1[::-1]\n n2 = int(n1)\n return n2\n\ndef istwistedprime(N):\n if isprime(N) == 1 and isprime(rev(N)) == 1:\n return 1\n else:\n return 0", "from math import sqrt\n\ndef istwistedprime(N):\n N_rev = int(str(N)[::-1])\n flag = 0\n for i in range(2, int(sqrt(N)) + 1):\n if N % i == 0:\n flag = 1\n break\n if flag == 1:\n return 0\n else:\n for i in range(2, int(sqrt(N_rev)) + 1):\n if N_rev % i == 0:\n flag = 1\n break\n if flag == 0:\n return 1\n else:\n return 0", "from math import sqrt\n\ndef isprime(N):\n if N <= 1:\n return 0\n for i in range(2, int(sqrt(N)) + 1):\n if N % i == 0:\n return 0\n else:\n return 1\n\ndef istwistedprime(N):\n t = int(str(N)[::-1])\n if isprime(t) and isprime(N):\n return 1\n return 0"], "starter_code": "def istwistedprime(N):\n", "input_output": {"inputs": ["N = 97", "N = 43"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Prime Number"], "name": null, "source": "geeksforgeeks", "tags": ["Number theory"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/twisted-prime-number0500/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "(O(sqrt(max(N,RevN))), here RevN is the reverse of N.", "entry_point": "istwistedprime", "task_id": "TACO_lite/403", "example": [[[97], [43]], ["1", "0"]]} +{"requirement": "Given a string S. The task is to find the first repeated character in it. We need to find the character that occurs more than once and whose index of second occurrence is smallest. S contains only lowercase letters.\n \nExample 1:\nInput: S=\"geeksforgeeks\"\nOutput: e\nExplanation: 'e' repeats at third position.\n \nExample 2:\nInput: S=\"hellogeeks\"\nOutput: l\nExplanation: 'l' repeats at fourth position.\n \nExample 3:\nInput: S=\"abc\"\nOutput: -1\nExplanation: There is no repeated character.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function firstRepChar() which accepts a string S as input parameter and returns a string containing first repeated character in it. If there is no repeated character in the string S then return \"-1\".\n \nExpected Time Complexity: O(|S|) \nExpected Auxiliary Space: O(1)\nwhere |S| denotes the length of string S.", "solutions": ["def firstrepchar(s):\n a = s\n for i in range(0, len(a)):\n list = a[:i]\n if a[i] in list:\n return a[i]\n return '-1'", "def firstrepchar(S):\n container = {}\n for i in range(len(S)):\n if S[i] in container:\n return S[i]\n else:\n container[S[i]] = 1\n return -1", "from collections import Counter\n\ndef firstrepchar(s):\n a = {}\n for i in s:\n if a.get(i) != None:\n return i\n a[i] = 1\n return -1", "def firstrepchar(s):\n char_arr = [0] * 26\n for i in s:\n i_in_ascii = ord(i) - ord('a')\n if char_arr[i_in_ascii]:\n return i\n else:\n char_arr[i_in_ascii] = 1\n return '-1'", "def firstrepchar(s):\n seen = []\n for let in s:\n if let in seen:\n return let\n seen.append(let)\n return -1", "def firstrepchar(s):\n st_l = set()\n for ch in s:\n if ch in st_l:\n return ch\n else:\n st_l.add(ch)\n return -1", "def firstrepchar(s):\n for i in range(len(s)):\n chk_lst = s[:i]\n if s[i] in chk_lst:\n return s[i]\n return -1", "def firstrepchar(s):\n diction = {}\n for ch in s:\n if ch in diction:\n diction[ch] += 1\n if diction[ch] == 2:\n return ch\n else:\n diction[ch] = 1\n return -1", "def firstrepchar(s):\n li = [s[0]]\n for i in range(1, len(s)):\n if s[i] not in li:\n li.append(s[i])\n else:\n return s[i]\n return -1", "def firstrepchar(s):\n d = {}\n for i in s:\n if i in d:\n return i\n else:\n d[i] = 1\n return -1", "def firstrepchar(s):\n save = {}\n for el in s:\n if el not in save:\n save[el] = 1\n continue\n return el\n return -1", "def firstrepchar(s):\n seen = set()\n for char in s:\n if char in seen:\n return char\n seen.add(char)\n return -1", "def firstrepchar(s):\n r = ''\n for i in s:\n if i in r:\n return i\n else:\n r = r + i\n if len(s) == len(r):\n return -1\n else:\n pass", "def firstrepchar(s):\n d = dict()\n for x in s:\n if x not in d:\n d[x] = 1\n else:\n return x\n return '-1'", "def firstrepchar(s):\n if len(set(s)) == len(s):\n return -1\n first_position_dict = {}\n for (char_tmp_index, char_tmp) in enumerate(s):\n if first_position_dict.get(char_tmp):\n return char_tmp\n else:\n first_position_dict[char_tmp] = 1\n return -1", "def firstrepchar(s):\n stack = []\n stack1 = []\n Output = ''\n for i in s:\n if i in stack:\n stack1.append(i)\n else:\n stack.append(i)\n if len(stack1) == 0:\n Output = '-1'\n else:\n Output = stack1[0]\n return Output", "def firstrepchar(s):\n k = 2\n s_set = set(s)\n lista = []\n for i in range(len(s_set)):\n nn = s_set.pop()\n cc = s.count(nn)\n lista.append((nn, cc))\n lista1 = []\n for i in range(len(lista)):\n if lista[i][1] >= k:\n lista1.append([lista[i][0], 0])\n break2 = 0\n if not lista1:\n return -1\n else:\n lista2 = []\n for i in s:\n for ii in range(len(lista1)):\n if i == lista1[ii][0]:\n lista1[ii][1] = lista1[ii][1] + 1\n if lista1[ii][1] == k:\n return lista1[ii][0]\n break2 = 1\n break\n if break2 == 1:\n break", "def firstrepchar(s):\n v = set()\n for i in range(len(s)):\n if s[i] in v:\n return s[i]\n else:\n v.add(s[i])\n return -1", "def firstrepchar(s):\n store = ''\n check = ''\n for a in s:\n if a in store:\n check = a\n break\n else:\n store += a\n if check == '':\n check = -1\n return check", "def firstrepchar(s):\n temp = set()\n for i in s:\n if i in temp:\n return i\n if i not in temp:\n temp.add(i)\n return -1", "def firstrepchar(s):\n h = {}\n for i in s:\n if i in h:\n return i\n else:\n h[i] = 0\n return -1", "def firstrepchar(s):\n chars = [0] * 256\n for ele in s:\n if chars[ord(ele)] != 0:\n return ele\n chars[ord(ele)] += 1\n return -1", "def firstrepchar(s):\n l = []\n for i in list(s):\n if i not in l:\n l.append(i)\n else:\n return i\n break\n return -1", "def firstrepchar(s):\n a = []\n for i in range(len(s)):\n if s[i] not in a:\n a.append(s[i])\n elif s[i] in a:\n return s[i]\n if len(a) == len(s):\n return -1", "def firstrepchar(s):\n map = {}\n minDistance = float('inf')\n ans = -1\n for i in range(len(s)):\n if s[i] in map:\n return s[i]\n else:\n map[s[i]] = i\n return ans", "def firstrepchar(s):\n hashmap = {}\n for i in s:\n if i not in hashmap:\n hashmap[i] = 1\n else:\n return i\n return -1", "def firstrepchar(s):\n d = ''\n for i in range(0, len(s)):\n if s[i] in d:\n return s[i]\n d += s[i]\n return -1", "def firstrepchar(s):\n chars = []\n for ch in s:\n if ch in chars:\n return ch\n chars.append(ch)\n return -1", "def firstrepchar(s):\n S = {}\n for i in s:\n if i in S:\n return i\n S[i] = 1\n return -1", "def firstrepchar(s):\n char_count = {}\n for char in s:\n if char in char_count:\n return char\n char_count[char] = 1\n return -1", "def firstrepchar(s):\n seen = set()\n for i in range(len(s)):\n if s[i] in seen:\n return s[i]\n seen.add(s[i])\n return -1", "def firstrepchar(s):\n h = {}\n for ch in s:\n if ch in h:\n return ch\n else:\n h[ch] = 1\n return -1", "def firstrepchar(s):\n ans = []\n for i in s:\n if i in ans:\n return i\n else:\n ans.append(i)\n return -1", "def firstrepchar(s):\n l = []\n c = 0\n for i in range(len(s)):\n if s[i] not in l:\n l.append(s[i])\n elif s[i] in l:\n c = 1\n return s[i]\n if c == 0:\n return -1", "def firstrepchar(s):\n d = dict()\n for i in s:\n if i in d:\n return i\n if i not in d:\n d.update({i: 1})\n return -1", "def firstrepchar(s):\n rep = set()\n for i in s:\n if i in rep:\n return i\n else:\n rep.add(i)\n return -1", "from collections import Counter\n\ndef firstrepchar(s):\n k = []\n for i in s:\n if i in k:\n return i\n else:\n k.append(i)\n return -1", "def firstrepchar(s):\n count = {}\n for i in s:\n if count.get(i):\n return i\n else:\n count[i] = '1'\n return -1", "def firstrepchar(s):\n answer = []\n temp = [i for i in s]\n for i in temp:\n if i not in answer:\n answer.append(i)\n else:\n return i\n return -1", "def firstrepchar(s):\n dic = {}\n for i in range(len(s)):\n if dic.get(s[i]) == None:\n dic[s[i]] = [1, i]\n elif dic[s[i]][0] == 1:\n dic[s[i]][0] += 1\n dic[s[i]][1] = i\n mini = len(s)\n k = ''\n c = 0\n for i in s:\n if dic[i][0] > 1 and dic[i][1] < mini:\n c = 1\n mini = dic[i][1]\n k = i\n if c == 1:\n return k\n return -1", "def firstrepchar(s):\n lst = []\n for i in s:\n if i not in lst:\n lst.append(i)\n else:\n return i\n return -1", "def firstrepchar(s):\n p = ''\n for i in range(len(s)):\n if s[i] not in p:\n p += s[i]\n else:\n char = s[i]\n return char\n return -1", "def firstrepchar(s):\n c = []\n for i in s:\n if i in c:\n return i\n c.append(i)\n return -1", "from collections import Counter\n\ndef firstrepchar(s):\n r = set()\n for i in s:\n if i in r:\n return i\n else:\n r.add(i)\n return -1", "def firstrepchar(s):\n visited = [False] * 26\n for i in s:\n if visited[ord('a') - ord(i)]:\n return i\n else:\n visited[ord('a') - ord(i)] = True\n return -1", "def firstrepchar(s):\n dict2 = {}\n dict1 = {}\n for i in range(len(s)):\n if s[i] not in dict1:\n dict1[s[i]] = 1\n else:\n dict1[s[i]] += 1\n if s[i] not in dict2:\n dict2[s[i]] = i\n if not dict2:\n return -1\n for i in dict2:\n if dict2[i] == min(dict2.values()):\n return i", "def firstrepchar(s):\n dic = {}\n for i in s:\n if i in dic:\n dic[i] += 1\n if dic[i] == 2:\n return i\n else:\n dic[i] = 1\n return -1", "def firstrepchar(s):\n explorado = ''\n for x in s:\n if explorado.count(x) == 0:\n explorado += x\n else:\n return x\n return -1"], "starter_code": "def firstrepchar(s):\n", "input_output": {"inputs": ["S=\"geeksforgeeks\"", "S=\"hellogeeks\"", "S=\"abc\""], "outputs": ["e", "l", "-1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Hash"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/find-first-repeated-character4108/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "firstrepchar", "task_id": "TACO_lite/395", "example": [[], []]} +{"requirement": "Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.\n\nIf the last word does not exist, return 0.\n\nNote: A word is defined as a character sequence consists of non-space characters only.\n\nExample:\n\nInput: \"Hello World\"\nOutput: 5", "solutions": ["def lengthoflastword(s):\n x = s.split()\n return len(x[-1]) if len(x) > 0 else 0", "def lengthoflastword(s):\n count = len(s.strip().split(' ')[-1])\n return count", "def lengthoflastword(s):\n (ans, tail) = (0, len(s) - 1)\n while tail >= 0 and s[tail] == ' ':\n tail -= 1\n while tail >= 0 and s[tail] != ' ':\n ans += 1\n tail -= 1\n return ans", "def lengthoflastword(s):\n if not s:\n return 0\n s = s.rstrip()\n s = s.lstrip()\n for i in range(0, len(s))[::-1]:\n if s[i] == ' ':\n return len(s) - 1 - i\n return len(s)", "def lengthoflastword(s):\n spaces = 0\n word_started = False\n for i in range(1, len(s) + 1):\n if s[-i] == ' ' and word_started is False:\n spaces += 1\n elif s[-i] == ' ' and word_started is True:\n return i - 1 - spaces\n else:\n word_started = True\n if word_started is True:\n return len(s) - spaces\n else:\n return 0", "def lengthoflastword(s):\n words = s.split()\n if not words:\n return 0\n return len(words[-1])", "def lengthoflastword(s):\n res = 0\n last = 0\n for i in s:\n if i == ' ':\n res = 0\n else:\n res += 1\n last = res\n return last", "def lengthoflastword(s):\n l = s.split(' ')\n while l:\n if l[-1]:\n return len(l[-1])\n else:\n l.pop(-1)\n return 0", "def lengthoflastword(s):\n v = s.split()\n if not v:\n return 0\n else:\n return len(v[-1])", "def lengthoflastword(s):\n l = len(s)\n n_c = 0\n for i in range(l - 1, -1, -1):\n if s[i] != ' ':\n n_c += 1\n elif s[i] == ' ' and n_c == 0:\n pass\n elif s[i] == ' ' and n_c != 0:\n return n_c\n return n_c", "def lengthoflastword(s):\n s = s.strip()\n if s == None:\n return 0\n count = 0\n for item in s[-1::-1]:\n if item == ' ':\n break\n count += 1\n return count"], "starter_code": "def lengthoflastword(s: str) -> int:\n", "input_output": {"fn_name": "lengthOfLastWord", "inputs": [["\"Hello World\""]], "outputs": [6]}, "difficulty": "EASY", "raw_tags": ["String"], "name": null, "source": "leetcode", "tags": ["String algorithms"], "skill_types": [], "url": "https://leetcode.com/problems/length-of-last-word/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "lengthoflastword", "task_id": "TACO_lite/415", "example": [[["Hello World"]], ["5"]]} +{"requirement": "Write function RemoveExclamationMarks which removes all exclamation marks from a given string.", "solutions": ["def remove_exclamation_marks(s):\n return s.replace('!', '')", "remove_exclamation_marks = lambda s: s.replace('!', '')", "def remove_exclamation_marks(s):\n x = s.replace('!', '')\n return x", "def remove_exclamation_marks(s):\n return ''.join([x for x in s if x != '!'])", "def remove_exclamation_marks(s):\n s = list(s)\n for x in s:\n if x == '!':\n s.remove(x)\n for x in s:\n if x == '!':\n s.remove(x)\n for x in s:\n if x == '!':\n s.remove(x)\n return ''.join(s)", "def remove_exclamation_marks(s):\n new_s = ''\n for i in s:\n if i != '!':\n new_s += i\n return new_s", "def remove_exclamation_marks(s: str) -> str:\n return s.replace('!', '')", "import re\n\ndef remove_exclamation_marks(s):\n return re.sub('!', '', s)", "def remove_exclamation_marks(s):\n y = list(s)\n for l in range(0, y.count('!')):\n y.remove('!')\n z = ''.join(y)\n return z", "def remove_exclamation_marks(s):\n return ''.join(filter(lambda x: x.isalpha() or x == ' ' or x == ',', s))", "def remove_exclamation_marks(s):\n return ''.join(list((l for l in s if l != '!')))", "import string\n\ndef remove_exclamation_marks(s):\n d = {'!': None}\n t = str.maketrans(d)\n return s.translate(t)", "def remove_exclamation_marks(s):\n temp = list(s)\n while '!' in temp:\n temp.remove('!')\n return ''.join(temp)", "remove_exclamation_marks = lambda a: a.replace('!', '')", "def remove_exclamation_marks(s):\n s1 = ''\n for i in s:\n if i != '!':\n s1 = s1 + i\n return s1", "def remove_exclamation_marks(s):\n if '!' not in s:\n return s\n else:\n s1 = ''\n for caracter in s:\n if caracter != '!':\n s1 += caracter\n return s1", "def remove_exclamation_marks(s):\n str = s.replace('!', '')\n return str\nremove_exclamation_marks('Hello World!')\nremove_exclamation_marks('Hello World!!!')\nremove_exclamation_marks('Hi! Hello!')\nremove_exclamation_marks('Oh, no!!!')", "def remove_exclamation_marks(s):\n word = ''\n for let in s:\n if let != '!':\n word = word + let\n return word", "remove_exclamation_marks = lambda s: ''.join((x for x in s if x != '!'))", "def remove_exclamation_marks(s):\n res = [i for i in s if i != '!']\n return ''.join(res)", "def remove_exclamation_marks(s):\n c = s.count('!')\n s = list(s)\n for i in range(c):\n s.remove('!')\n return ''.join(s)", "def remove_exclamation_marks(s):\n lol = s.replace('!', '')\n return lol", "def remove_exclamation_marks(s):\n result = ''\n for i in s:\n if i == '!':\n pass\n else:\n result += i\n return result", "def remove_exclamation_marks(s):\n s = list(s)\n for i in range(len(s)):\n if '!' in s:\n s.remove('!')\n return ''.join(s)", "def remove_exclamation_marks(s):\n for element in s:\n if element == '!':\n s = s.replace('!', '')\n return s", "def remove_exclamation_marks(s):\n result = ''\n for y in s:\n if y != '!':\n result += y\n return result", "def remove_exclamation_marks(s):\n a = ''\n for c in s:\n if c != '!':\n a += c\n return a", "def remove_exclamation_marks(s):\n new_string = ''\n for char in s:\n if char == '!':\n pass\n else:\n new_string += char\n return new_string", "def remove_exclamation_marks(s):\n return s.translate(str.maketrans({'!': ''}))", "def remove_exclamation_marks(s):\n return s if not s else s.replace('!', '')", "def remove_exclamation_marks(s):\n total = ''\n for i in s:\n if i != '!':\n total += i\n return total", "def remove_exclamation_marks(s):\n r = list(s)\n for char in s:\n if char == '!':\n r.remove(char)\n string = ''\n for i in r:\n string += i\n return string", "def remove_exclamation_marks(s):\n a = str()\n for i in s:\n if i != '!':\n a += i\n return a", "def remove_exclamation_marks(s):\n a = ''\n for i in s:\n if i in '!':\n pass\n else:\n a += i\n return a", "def remove_exclamation_marks(s):\n return ''.join([i for i in s if ord(i) != 33])", "def remove_exclamation_marks(s):\n newS = ''\n for letters in s:\n if letters != '!':\n newS += letters\n return newS", "def remove_exclamation_marks(s):\n no_mark = ''\n for word in s:\n if word != '!':\n no_mark += word\n return no_mark", "def remove_exclamation_marks(s):\n S = ''\n for i in s:\n S = s.replace('!', '')\n return S", "def remove_exclamation_marks(s):\n string = ''\n for x in s:\n if x != '!':\n string += x\n return string", "def remove_exclamation_marks(s):\n sl = list(s)\n n = sl.count('!')\n i = 1\n while i <= n:\n sl.remove('!')\n i += 1\n return ''.join(sl)", "def remove_exclamation_marks(s):\n newlist = s.replace('!', '')\n return newlist", "import re\n\ndef remove_exclamation_marks(str):\n return ''.join(re.findall('\\\\w|\\\\s|[,]', str))", "def remove_exclamation_marks(s):\n new_string = ''\n for e in s:\n if e != '!':\n new_string += e\n return new_string", "def remove_exclamation_marks(s):\n a = [s.strip('!') for s in s]\n return ''.join(a)", "def remove_exclamation_marks(s):\n new_string = ''\n for i in s:\n if i != '!':\n new_string += i\n return new_string", "def remove_exclamation_marks(s):\n for i in range(len(s)):\n count = s.count('!')\n s = s.replace('!', '', count)\n return s", "def remove_exclamation_marks(s):\n list = [',', ' ', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M']\n for i in s:\n if i in list:\n continue\n else:\n s = s.replace(i, '')\n return s", "def remove_exclamation_marks(s):\n s = s.split(' ')\n no_marks = []\n for char in s:\n char = list(char)\n no_exc = []\n for x in char:\n if x != '!':\n no_exc.append(x)\n collect = ''.join(no_exc)\n no_marks.append(collect)\n return ' '.join(no_marks)", "def remove_exclamation_marks(s):\n res = ''\n for i in s:\n if not i == '!':\n res = res + i\n return res", "def remove_exclamation_marks(s):\n result = ''\n for i in s:\n if i != '!':\n result = result + i\n return result", "def remove_exclamation_marks(s):\n m = list(s)\n x = []\n for i in m:\n if i != '!':\n x.append(i)\n v = ''.join(x)\n return v", "def remove_exclamation_marks(s):\n return ''.join((i if i != '!' else '' for i in s))", "def remove_exclamation_marks(s):\n return ''.join((ele for ele in s if ele != '!'))", "def remove_exclamation_marks(s):\n res = ''\n for i in range(len(s)):\n if s[i] != '!':\n res += s[i]\n return res", "def remove_exclamation_marks(s):\n return ''.join([i for i in list(str(s)) if i != '!'])", "def remove_exclamation_marks(s):\n screw_the_exclaimation_mark = s.replace('!', '')\n return screw_the_exclaimation_mark", "def remove_exclamation_marks(string):\n new = string.replace('!', '')\n return new", "def remove_exclamation_marks(s):\n k = ''\n for i in s:\n if i != '!':\n k += i\n return k", "def remove_exclamation_marks(s):\n ergebnis = ''\n for i in s:\n if i != '!':\n ergebnis += i\n return ergebnis", "import unittest\n\ndef remove_exclamation_marks(s):\n return s.replace('!', '')\n\ndef test_only_one_exclamation_marks():\n s = 'Hello World!'\n actual = remove_exclamation_marks(s)\n self.assertEqual(actual, 'Hello World')\n\ndef test_only_all_exclamation_marks():\n s = 'Hello World!'\n actual = remove_exclamation_marks(s)\n self.assertEqual(actual, 'Hello World')", "def remove_exclamation_marks(s):\n bas = ''\n out = ''\n for i in s:\n if i == '!':\n bas += i\n else:\n out += i\n return out", "def remove_exclamation_marks(s):\n char = ''\n for i in s:\n if i != '!':\n char += i\n return char", "import re\n\ndef remove_exclamation_marks(s):\n return ''.join(re.findall('[a-z A-Z,]', s))", "def remove_exclamation_marks(s):\n z = ''.join([l for l in s if l != '!'])\n return z", "import re\n\ndef remove_exclamation_marks(my_list):\n return re.sub('!', '', my_list)", "def remove_exclamation_marks(s):\n st = s.replace('!', '')\n return st", "def remove_exclamation_marks(s):\n return ''.join(filter(lambda char: char != '!', list(s)))", "def remove_exclamation_marks(s):\n out = ''\n for i in s:\n if i != '!':\n out += i\n return out", "def remove_exclamation_marks(s):\n '!' in s == True\n return s.replace('!', '')", "def remove_exclamation_marks(s):\n d = ''\n for i in s:\n if i not in '!\u00a1':\n d += i\n return d", "def remove_exclamation_marks(s):\n a = s.strip('!')\n l = []\n for i in range(0, len(a)):\n s = a[i]\n l.append(s)\n while '!' in l:\n l.pop(l.index('!'))\n return ''.join(l)", "def remove_exclamation_marks(n):\n return n.replace('!', '')", "def remove_exclamation_marks(s):\n s1 = []\n for i in s:\n if i != '!':\n s1.append(i)\n return ''.join(s1)", "def remove_exclamation_marks(s):\n n = ''\n for x in s:\n if x.isalpha() or x == ' ' or x == ',':\n n += x\n return n", "def remove_exclamation_marks(s):\n lst = s.split('!')\n return ''.join(lst)", "def remove_exclamation_marks(s):\n answer = ''\n for i in s:\n if i == '!':\n pass\n else:\n answer += i\n return answer", "def remove_exclamation_marks(s):\n sp = s.split('!')\n new_string = ''.join(sp)\n return new_string", "def remove_exclamation_marks(Str):\n Word = ''\n for s in Str:\n if not s == '!':\n Word += s\n return Word", "def remove_exclamation_marks(s):\n s = list(s)\n x = 0\n for element in s:\n while True:\n if len(s) == x:\n break\n if s[x] == '!':\n del s[x]\n else:\n break\n x += 1\n s = ''.join(s)\n return s", "def remove_exclamation_marks(s):\n new_s = []\n for n in s:\n if n == '!':\n n = ''\n else:\n new_s.append(n)\n answer = ''.join(new_s)\n return answer", "def remove_exclamation_marks(s):\n result = ''\n for i in range(len(s)):\n if s[i] != '!':\n result += s[i]\n return result", "def remove_exclamation_marks(s):\n return ''.join((x for x in s if x is not '!'))"], "starter_code": "def remove_exclamation_marks(s):\n", "input_output": {"fn_name": "remove_exclamation_marks", "inputs": [["Hello World!"], ["Hello World!!!"], ["Hi! Hello!"], [""], ["Oh, no!!!"]], "outputs": [["Hello World"], ["Hello World"], ["Hi Hello"], [""], ["Oh, no"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/57a0885cbb9944e24c00008e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "remove_exclamation_marks", "task_id": "TACO_lite/364", "example": [[], []]} +{"requirement": "In this Kata, you will be given two numbers, `a` and `b`, and your task is to determine if the first number `a` is divisible by `all` the prime factors of the second number `b`. For example: `solve(15,12) = False` because `15` is not divisible by all the prime factors of `12` (which include`2`).\n\nSee test cases for more examples. \n\nGood luck!\n\nIf you like this Kata, please try:\n\n[Sub-array division](https://www.codewars.com/kata/59eb64cba954273cd4000099)\n\n[Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)", "solutions": ["import fractions\n\ndef solve(a, b):\n c = fractions.gcd(a, b)\n while c > 1:\n b //= c\n c = fractions.gcd(a, b)\n return b == 1", "from math import gcd\n\ndef solve(a, b):\n while 1 < gcd(a, b):\n b = b // gcd(a, b)\n return b == 1", "from math import gcd\n\ndef solve(a, b):\n x = gcd(a, b)\n if x == 1:\n return False\n if x == b:\n return True\n return solve(a, b // x)", "from fractions import gcd\n\ndef solve(a, b):\n if b == 1:\n return True\n if gcd(a, b) == 1:\n return False\n return solve(a, b / gcd(a, b))", "def solve(a, b):\n (li, j) = ([], 2)\n while b > 1:\n if b % j:\n j += 1\n continue\n li.append(j)\n b //= j\n if a % j:\n return 0\n return 1", "def solve(a, b):\n k = 2\n while k <= int(b ** 0.5):\n while b % k == 0:\n b //= k\n if a % k != 0:\n return False\n k += 1\n return a % b == 0", "def solve(a, b):\n b1 = b\n answer = True\n i = 2\n primfac = []\n while i * i <= b:\n while b1 % i == 0:\n primfac.append(i)\n b1 = b1 // i\n i = i + 1\n if b1 > 1:\n primfac.append(b1)\n for i in range(0, len(primfac)):\n if a % primfac[i] != 0:\n answer = False\n return answer", "N = 10000\na = [1] * N\na[0] = a[1] = 0\nfor i in range(2, N):\n if a[i]:\n for j in range(i ** 2, N, i):\n a[j] = 0\na = [i for (i, x) in enumerate(a) if x]\n\ndef solve(n, m):\n return all((not n % x for x in f(m)))\n\ndef f(n):\n s = set()\n for x in a:\n if x > n:\n break\n while not n % x:\n n //= x\n s.add(x)\n if n > 1:\n s.add(n)\n return s", "def solve(a, b):\n p = 2\n while True:\n if b == 1:\n return True\n if a % p > 0 and b % p == 0:\n return False\n while b % p == 0:\n b /= p\n p += 1", "from math import ceil, sqrt\n\ndef factorize(x):\n factors = []\n for i in range(2, ceil(sqrt(x)) + 1):\n while x % i == 0:\n factors.append(i)\n x /= i\n if x != 1:\n factors.append(x)\n return factors\n\ndef solve(a, b):\n factors = factorize(b)\n ok = True\n for factor in factors:\n if a % factor != 0:\n ok = False\n return ok"], "starter_code": "def solve(a,b):\n", "input_output": {"fn_name": "solve", "inputs": [[2, 256], [2, 253], [9, 243], [15, 12], [21, 2893401], [21, 2893406], [54, 2834352], [54, 2834359], [1000013, 7187761], [1000013, 7187762]], "outputs": [[true], [false], [true], [false], [true], [false], [true], [false], [true], [false]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/59ec2d112332430ce9000005", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/352", "example": [[[15, 12]], ["False"]]} +{"requirement": "Given a binary string S (a string consisting only of '0' and '1's) and a positive integer N, return true if and only if for every integer X from 1 to N, the binary representation of X is a substring of S.\n\u00a0\nExample 1:\nInput: S = \"0110\", N = 3\nOutput: true\n\nExample 2:\nInput: S = \"0110\", N = 4\nOutput: false\n\n\u00a0\nNote:\n\n1 <= S.length <= 1000\n1 <= N <= 10^9", "solutions": ["def querystring(S: str, N: int) -> bool:\n for i in range(1, N + 1):\n b = bin(i).replace('0b', '')\n if b not in S:\n return False\n return True", "def int_to_bin(x):\n ret = ''\n if x == 0:\n return '0'\n while x > 0:\n ret = str(x % 2) + ret\n x = x // 2\n return ret\n\ndef querystring(S: str, N: int) -> bool:\n mp = {}\n max_len = min(31, len(S))\n for k in range(1, max_len + 1):\n for i in range(len(S) - k + 1):\n mp[S[i:i + k]] = True\n for i in range(1, N + 1):\n if self.int_to_bin(i) not in mp:\n return False\n return True", "def querystring(S: str, N: int) -> bool:\n for i in range(1, N + 1):\n if bin(i)[2:] not in S:\n return False\n return True", "def querystring(S: str, N: int) -> bool:\n if '1' not in S:\n return False\n res = set()\n cur = set()\n for s in S:\n if s == '0':\n cur = {c * 2 for c in cur} | {0}\n else:\n cur = {c * 2 + 1 for c in cur} | {1}\n res |= cur\n for i in range(1, N + 1):\n if i not in res:\n return False\n return True", "def querystring(S: str, M: int) -> bool:\n count = defaultdict(int)\n N = len(S)\n\n def f(ss):\n ans = 0\n nn = len(ss) - 1\n for ch in ss:\n if ch == '1':\n ans += 1 << nn\n nn -= 1\n return ans\n cnt = 0\n for n1 in range(N):\n for n2 in range(n1, N):\n if n2 - n1 < 32:\n val = f(S[n1:n2 + 1])\n if val >= 1 and val <= M and (count[val] == 0):\n cnt += 1\n count[val] = 1\n else:\n break\n if cnt == M:\n return True\n return False", "def querystring(S: str, N: int) -> bool:\n substrings = set()\n for i in range(len(S)):\n for j in range(i, len(S) + 1):\n substrings.add(S[i:j])\n for i in range(1, N + 1):\n binN = str(bin(i))[2:]\n if binN in substrings:\n continue\n else:\n return False\n return True", "def querystring(S: str, N: int) -> bool:\n seen = set()\n if len(S) < 2:\n seen.add(S)\n for i in range(len(S) - 1):\n for j in range(i + 1, len(S)):\n if S[i] == '0':\n seen.add(S[i + 1:j + 1])\n else:\n seen.add(S[i:j + 1])\n for i in range(1, N + 1):\n binary = bin(i)[2:]\n if binary not in seen:\n return False\n return True", "def querystring(S: str, N: int) -> bool:\n return all((bin(i)[2:] in S for i in range(N, N // 2, -1)))", "def querystring(S: str, N: int) -> bool:\n st = set()\n for size in range(1, len(S) + 1):\n for i in range(len(S) - size + 1):\n st.add(S[i:i + size])\n for i in range(1, N + 1):\n if not bin(i)[2:] in st:\n return False\n return True", "def querystring(S: str, N: int) -> bool:\n dic = set()\n for i in range(len(S)):\n for l in range(len(S) - i):\n dic.add(S[i:i + l + 1])\n for x in range(1, N + 1):\n if str(bin(x)[2:]) not in dic:\n return False\n return True", "from itertools import combinations\n\ndef querystring(S: str, N: int) -> bool:\n d = set()\n for i in range(0, len(S) + 1):\n j = 0\n end = i + 1\n while end < len(S) + 1:\n d.add(S[j:end])\n j = j + 1\n end = end + 1\n q = 1\n for i in range(1, N + 1):\n if bin(i)[2:] not in d:\n q = 0\n break\n return q", "def querystring(S: str, N: int) -> bool:\n n = len(S)\n for i in range(30, -1, -1):\n if N & 1 << i:\n msb = i\n break\n\n def get(msb):\n s = set()\n num = 0\n x = 0\n if msb > 0:\n x = 1 << msb - 1\n for i in range(n):\n if i == msb:\n if S[i] == '1':\n num += 1\n if x < num <= N:\n s.add(num)\n elif i > msb:\n if num & 1 << msb:\n num -= 1 << msb\n num <<= 1\n if S[i] == '1':\n num += 1\n if x < num <= N:\n s.add(num)\n elif S[i] == '1':\n num |= 1 << msb - i\n return s\n s = get(msb)\n p = 0\n if msb > 0:\n p = 1 << msb - 1\n if msb > 0:\n s1 = get(msb - 1)\n p = 0\n if msb > 1:\n p = 1 << msb - 2\n for i in s1:\n s.add(i)\n return len(s) == N - p", "def querystring(S: str, N: int) -> bool:\n\n def is_x_in(x):\n binary = []\n while x:\n binary.append(x % 2)\n x = x >> 1\n binary = ''.join((str(n) for n in reversed(binary)))\n return S.find(binary) >= 0\n return all((is_x_in(x) for x in range(N + 1)))"], "starter_code": "def querystring(S: str, N: int) -> bool:\n", "input_output": {"fn_name": "queryString", "inputs": [["\"0110\"", 3]], "outputs": [true]}, "difficulty": "MEDIUM", "raw_tags": ["String"], "name": null, "source": "leetcode", "tags": ["String algorithms"], "skill_types": [], "url": "https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "querystring", "task_id": "TACO_lite/405", "example": [[], []]} +{"requirement": "Given a binary string S and an integer K, the task is to count the number of substrings that contain exactly K ones.\nExample 1:\nInput : S = 10010, K = 1\nOutput : 9\nExplanation: The 9 substrings containing \none 1 are, 1, 10, 100, 001, 01,\n1, 10, 0010 and 010.\nExample 2:\nInput : S = 111, K = 2 \nOutput : 2 \nExplanation: The 2 substrings containing\ntwo 1 are 11, 11.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function countOfSubstringWithKOnes() which takes the string S and an integer K as inputs and returns the count.\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(|S|)\nConstraints:\n1 \u2264 N \u2264 10^{5}\n1 \u2264 K \u2264 10^{4}", "solutions": ["def countofsubstringwithkones(S, K):\n cm = 0\n mp = dict()\n n = len(S)\n ans = 0\n for i in range(n):\n cm += ord(S[i]) - 48\n if cm == k:\n ans += 1\n if cm - k in mp:\n ans += mp[cm - k]\n if cm not in mp:\n mp[cm] = 1\n else:\n mp[cm] += 1\n return ans", "def solve(s, k):\n ans = 0\n n = len(s)\n cnt = 0\n j = 0\n for i in range(n):\n if s[i] == '1':\n cnt += 1\n while j < n and cnt > k:\n if s[j] == '1':\n cnt -= 1\n j += 1\n ans += i - j + 1\n return ans\n\ndef countofsubstringwithkones(S, K):\n if K == 0:\n return self.solve(S, K)\n return self.solve(S, K) - self.solve(S, K - 1)", "def countofsubstringwithkones(S, K):\n freq = {}\n S = list(str(S))\n presum = 0\n freq[0] = 1\n c = 0\n for i in S:\n presum += int(i)\n if presum - K in freq:\n c += freq[presum - K]\n if presum not in freq:\n freq[presum] = 0\n freq[presum] += 1\n return c", "def countofsubstringwithkones(S, k):\n if k == 0:\n count = 0\n c = 0\n for i in S:\n if i == '0':\n c += 1\n else:\n count += c * (c + 1) // 2\n c = 0\n if c:\n count += c * (c + 1) // 2\n return count\n nums = list(S)\n count = 0\n (a, b, c) = (0, 0, 1)\n ln = len(nums)\n for i in range(ln):\n nums[i] = nums[i] == '1'\n while a < ln and nums[a] == 0:\n c += 1\n a += 1\n for i in range(ln):\n k -= nums[i]\n if k == 0:\n count += c\n elif k == -1:\n k = 0\n a += 1\n c = 1\n while nums[a] == 0:\n c += 1\n a += 1\n count += c\n return count", "def countofsubstringwithkones(S, K):\n count = 0\n n = len(s)\n feq = [0 for i in range(n + 1)]\n feq[0] = 1\n res = 0\n for i in range(n):\n count += ord(s[i]) - ord('0')\n if count >= K:\n res += feq[count - k]\n feq[count] += 1\n return res", "def countofsubstringwithkones(S, K):\n count = 0\n S = str(' '.join(S))\n import collections\n mapp = collections.defaultdict(int)\n mapp[0] = 1\n summ = 0\n l = list(map(int, S.split(' ')))\n for ele in l:\n summ += ele\n count += mapp[summ - K]\n mapp[summ] += 1\n return count", "def countofsubstringwithkones(s, k):\n cum_sum = 0\n mp = {}\n cnt = 0\n arr = [int(i) for i in s]\n mp[0] = [-1]\n n = len(s)\n for i in range(n):\n cum_sum = cum_sum + arr[i]\n if cum_sum - k in mp:\n cnt = cnt + len(mp[cum_sum - k])\n mp.setdefault(cum_sum, []).append(i)\n return cnt", "def countofsubstringwithkones(S, K):\n n = len(S)\n dp = [0] * (n + 1)\n dp[0] = 1\n one_count = 0\n res = 0\n for c in S:\n if c == '1':\n one_count += 1\n if one_count >= K:\n res += dp[one_count - K]\n dp[one_count] += 1\n return res", "def countofsubstringwithkones(S, K):\n res = 0\n freq = [0 for i in range(len(S) + 1)]\n freq[0] = 1\n countOne = 0\n for i in range(len(S)):\n countOne += ord(S[i]) - ord('0')\n if countOne >= k:\n res += freq[countOne - k]\n freq[countOne] += 1\n return res", "def countofsubstringwithkones(S, K):\n d = {}\n count = 0\n Sum = 0\n for num in S:\n Sum = Sum + int(num)\n if Sum == K:\n count = count + 1\n if Sum - K in d:\n count = count + d[Sum - K]\n if Sum not in d:\n d[Sum] = 1\n else:\n d[Sum] += 1\n return count", "def countofsubstringwithkones(s, k):\n (i, j) = (0, 0)\n n = len(s)\n presum = 0\n res1 = 0\n while j < n:\n if s[j] == '1':\n presum += 1\n while presum > k:\n if s[i] == '1':\n presum -= 1\n i += 1\n res1 += j - i + 1\n j += 1\n if k == 0:\n return res1\n k -= 1\n (i, j) = (0, 0)\n presum = 0\n res2 = 0\n while j < n:\n if s[j] == '1':\n presum += 1\n while presum > k:\n if s[i] == '1':\n presum -= 1\n i += 1\n res2 += j - i + 1\n j += 1\n return res1 - res2", "def countofsubstringwithkones(S, K):\n N = len(s)\n res = 0\n countOfOne = 0\n freq = [0 for i in range(N + 1)]\n freq[0] = 1\n for i in range(0, N, 1):\n countOfOne += ord(s[i]) - ord('0')\n if countOfOne >= K:\n res += freq[countOfOne - K]\n freq[countOfOne] += 1\n return res", "def countofsubstringwithkones(S, K):\n Sum = 0\n Dict = {0: 1}\n N = len(S)\n res = 0\n for i in range(N):\n Sum += int(S[i])\n if Sum - K >= 0 and Sum - K in Dict:\n res += Dict[Sum - K]\n if Sum not in Dict:\n Dict[Sum] = 1\n else:\n Dict[Sum] += 1\n return res", "def countofsubstringwithkones(S, K):\n result = 0\n cnt = 0\n freq = [0 for i in range(len(S) + 1)]\n freq[0] = 1\n for i in range(len(S)):\n cnt += ord(S[i]) - ord('0')\n if cnt >= K:\n result += freq[cnt - K]\n freq[cnt] += 1\n return result", "def countofsubstringwithkones(S, K):\n d = {}\n prefix_sum = 0\n count = 0\n for i in range(len(S)):\n prefix_sum += int(S[i])\n if prefix_sum == K:\n count += 1\n if prefix_sum - K in d:\n count += d[prefix_sum - K]\n if prefix_sum not in d:\n d[prefix_sum] = 1\n else:\n d[prefix_sum] += 1\n return count", "def countofsubstringwithkones(S, K):\n l = [int(x) for x in S]\n d = {0: [-1]}\n indices = []\n sum = 0\n count = 0\n for i in range(len(l)):\n sum += l[i]\n if sum - K in d:\n for x in d[sum - K]:\n count += 1\n if sum not in d:\n d[sum] = [i]\n else:\n d[sum].append(i)\n return count", "def countofsubstringwithkones(S, K):\n\n def s1(S, K):\n l = 0\n r = 0\n count = 0\n ret = 0\n while r < len(S):\n if S[r] == '1':\n count += 1\n while count == K + 1:\n ret += 1\n if S[l] == '1':\n count -= 1\n l += 1\n r += 1\n return ret\n\n def s2(S, K):\n from collections import defaultdict\n freqOfCount = defaultdict(int)\n countSoFar = 0\n ret = 0\n freqOfCount[0] = 1\n for (i, c) in enumerate(S):\n if c == '1':\n countSoFar += 1\n if countSoFar >= K:\n ret += freqOfCount[countSoFar - K]\n freqOfCount[countSoFar] += 1\n return ret\n return s2(S, K)", "def countofsubstringwithkones(s, k):\n map1 = {0: 1}\n ans = 0\n curr_sum = 0\n for i in range(len(s)):\n if s[i] == '1':\n curr_sum += 1\n ans += map1[curr_sum - k] if curr_sum - k in map1 else 0\n map1[curr_sum] = map1.get(curr_sum, 0) + 1\n return ans", "def countofsubstringwithkones(S, K):\n freq = dict()\n sm = 0\n c = 0\n for i in S:\n if i == '1':\n sm += 1\n if sm == K:\n c = c + 1\n if sm - K in freq:\n c = c + freq[sm - K]\n freq[sm] = freq.get(sm, 0) + 1\n return c", "def countofsubstringwithkones(S, K):\n string = S\n n = K\n prefixCount = []\n freq = {}\n curCount = 0\n if n == 0:\n mainSu = 0\n curCount = 0\n for x in string:\n if x == '1':\n mainSu += curCount * (curCount + 1) // 2\n curCount = 0\n else:\n curCount += 1\n mainSu += curCount * (curCount + 1) // 2\n return mainSu\n for x in string:\n if x == '1':\n curCount += 1\n prefixCount.append(curCount)\n for x in prefixCount:\n temp = freq.get(x)\n if temp:\n freq[x] += 1\n else:\n freq[x] = 1\n mainSu = 0\n prevCount = 0\n curCount = 0\n target = n\n i = 0\n flag = True\n for x in range(len(string)):\n if string[x] == '0':\n calc = n + prefixCount[x]\n temp = freq.get(calc)\n if temp:\n mainSu += freq[calc]\n else:\n calc = n + prefixCount[x] - 1\n temp = freq.get(calc)\n if temp:\n mainSu += freq[calc]\n flag = False\n if flag:\n if n == 0:\n n = len(string)\n return n * (n + 1) // 2\n else:\n return 0\n else:\n return mainSu", "def countofsubstringwithkones(S, K):\n count = 0\n ones = []\n for (index, item) in enumerate(S):\n if item == '1':\n ones.append(index)\n if len(ones) < K:\n return 0\n if K == 0:\n zeros = []\n flag = False\n count0 = 0\n for i in range(len(S)):\n if S[i] == '0':\n flag = True\n count0 += 1\n else:\n if flag:\n zeros.append(count0)\n flag = False\n count0 = 0\n zeros.append(count0)\n for num in zeros:\n count += num * (num + 1) // 2\n return int(count)\n left = 0\n next1 = K - 1\n start = ones[K - 1] if K - 1 >= 0 else 0\n for i in range(start, len(S)):\n x = -1 if left == 0 else ones[left - 1]\n if next1 < len(ones) and ones[next1] == i:\n incr = ones[left] - x\n count += incr\n left += 1\n next1 += 1\n else:\n count += incr\n return count"], "starter_code": "def countofsubstringwithkones(S, K):\n", "input_output": {"inputs": ["S = 10010, K = 1", "S = 111, K = 2"], "outputs": ["9", "2"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Strings", "Hash"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-of-substrings-containing-k-ones2304/1", "Expected Auxiliary Space": "O(|S|)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "countofsubstringwithkones", "task_id": "TACO_lite/378", "example": [[["10010", 1], ["111", 2]], ["9", "2"]]} +{"requirement": "Given a string, check if all its characters are the same or not.\nExample 1:\nInput:\ns = \"geeks\"\nOutput: False\nExplanation: The string contains different\ncharacter 'g', 'e', 'k' and 's'.\nExample 2:\nInput: \ns = \"gggg\"\nOutput: True\nExplanation: The string contains only one\ncharacter 'g'.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function check() which takes a string as input and returns True if all the characters in the string are the same. Else, it returns False.\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= |S| <= 10^{4}", "solutions": ["def check(s):\n d = set(s)\n if len(d) == 1:\n return True\n return False", "def check(s):\n if s.count(s[0]) == len(s):\n return True\n else:\n return False", "def check(s):\n k = s[0]\n for i in s[1:]:\n if i != k:\n return False\n return True", "def check(s):\n a = set(list(s))\n if len(a) == 1:\n return True\n else:\n return False", "def check(s):\n return len(s) == s.count(s[0])", "def check(S):\n return all((char == S[0] for char in S))", "def check(s):\n for i in range(len(s) - 1):\n if s[i] != s[i + 1]:\n return False\n return True", "def check(s):\n return len(set(s)) == 1", "def check(s):\n a = s[0]\n for i in s:\n if i == a:\n continue\n else:\n return False\n return True", "def check(s):\n e = s[0]\n ret_val = True\n for i in s:\n if i != e:\n ret_val = False\n return ret_val", "def check(s):\n ch = s[0]\n for i in s:\n if i != ch:\n return False\n return True", "def check(s):\n c = s[0]\n l = len(s)\n for i in range(1, l):\n if s[i] == s[0]:\n continue\n else:\n return False\n return True", "def check(s):\n count = 0\n l = len(s)\n s1 = s[0]\n for i in range(l):\n if s[i] != s1:\n count += 1\n break\n if count > 0:\n return False\n else:\n return True", "def check(s):\n flag = True\n for i in range(len(s) - 1):\n if s[i] != s[i + 1]:\n flag = False\n break\n else:\n flag = True\n if flag == True:\n return True\n else:\n return False", "def check(s):\n se = set(s)\n if len(se) == 1:\n return True\n else:\n return False", "def check(s):\n l = len(s)\n c = s.count(s[0])\n if l == c:\n return 1\n else:\n return 0", "from collections import Counter\n\ndef check(s):\n x = Counter(s)\n if len(Counter(x.keys())) == 1:\n return 'True'", "def check(s):\n dt = {}\n for i in s:\n dt[i] = 1\n if len(dt) == 1:\n return True\n else:\n return False", "def check(s):\n a = len(s)\n for i in range(len(s)):\n if s[0] != s[i]:\n return False\n break\n else:\n return True", "def check(s):\n for char in s:\n if s[0] != char:\n return False\n return True", "def check(s):\n se = set()\n se.add(s[0])\n for i in s:\n if i not in se:\n return False\n return True", "def check(s):\n return all((char == s[0] for char in s))", "def check(s):\n l = list(s)\n st = set(l)\n if len(st) == 1:\n return True\n return False", "def check(s):\n first = s[0]\n for i in s:\n if i != first:\n return False\n break\n else:\n return True", "def check(s):\n for element in range(len(s)):\n if s[element] != s[0]:\n return False\n else:\n return True", "def check(s):\n inp_str_list = set(s.strip(''))\n if len(inp_str_list) == 1:\n return True\n else:\n return False", "def check(s):\n for i in range(len(s) - 1):\n if s[i] != s[i + 1]:\n return 0\n return 1", "def check(s):\n for i in s:\n if s.count(i) == len(s):\n return True\n else:\n return False", "def check(s):\n first_s = s[0]\n for i in s:\n if i == first_s:\n pass\n else:\n return False\n return True", "from operator import countOf\n\ndef check(s):\n s = list(s)\n if countOf(s, s[0]) == len(s):\n return True\n else:\n return False"], "starter_code": "def check (s):\n", "input_output": {"inputs": ["s = \"geeks\"", "s = \"gggg\""], "outputs": ["False", "True"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/check-string1818/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|).", "entry_point": "check", "task_id": "TACO_lite/333", "example": [[["geeks"], ["gggg"]], ["False", "True"]]} +{"requirement": "Define a method that accepts 2 strings as parameters. The method returns the first string sorted by the second.\n\n```python\nsort_string(\"foos\", \"of\") == \"oofs\"\nsort_string(\"string\", \"gnirts\") == \"gnirts\"\nsort_string(\"banana\", \"abn\") == \"aaabnn\"\n```\n\nTo elaborate, the second string defines the ordering. It is possible that in the second string characters repeat, so you should remove repeating characters, leaving only the first occurrence.\n\nAny character in the first string that does not appear in the second string should be sorted to the end of the result in original order.", "solutions": ["def sort_string(s, ordering):\n answer = ''\n for o in ordering:\n answer += o * s.count(o)\n s = s.replace(o, '')\n return answer + s", "def sort_string(s, ordering):\n dct = {c: -i for (i, c) in enumerate(reversed(ordering))}\n return ''.join(sorted(s, key=lambda c: dct.get(c, 1)))", "sort_string = lambda s, o: ''.join(sorted(s, key=lambda x, d={c: i for (i, c) in reversed(list(enumerate(o)))}: d.get(x, len(o))))", "def sort_string(st, order):\n return ''.join(sorted(list(st), key=lambda e: list(order).index(e) if e in order else len(order)))", "def sort_string(stg, ordering):\n return ''.join(sorted(stg, key=lambda c: ordering.index(c) if c in ordering else float('inf')))", "def sort_string(s, ordering):\n order = {}\n for (i, c) in enumerate(ordering):\n if c in order:\n continue\n order[c] = i\n return ''.join(sorted(s, key=lambda c: order.get(c, 9999)))", "def sort_string(s, ordering):\n result = ''\n for i in ordering:\n if i in s and i not in result:\n result += i * s.count(i)\n return result + ''.join([c for c in s if c not in ordering])", "def sort_string(s, ordering):\n result = sorted([c for c in s if c in ordering], key=ordering.find)\n result.extend([c for c in s if c not in ordering])\n return ''.join(result)", "def sort_string(a, b):\n li = list(filter(lambda x: x in b, a))\n return ''.join(sorted(li, key=b.index) + [i for i in a if i not in li])", "def sort_string(s, ordering):\n return ''.join(sorted([i for i in s if i in ordering], key=lambda x: ordering.index(x))) + ''.join(sorted([j for j in s if j not in ordering], key=lambda x: s.index(s)))"], "starter_code": "def sort_string(s, ordering):\n", "input_output": {"fn_name": "sort_string", "inputs": [["banana", "abn"], ["banana", "xyz"], ["banana", "an"], ["foos", "of"], ["string", "gnirts"], ["banana", "a"], ["bungholio", "aacbuoldiiaoh"], ["fumyarhncujlj", "nsejcwn"]], "outputs": [["aaabnn"], ["banana"], ["aaannb"], ["oofs"], ["gnirts"], ["aaabnn"], ["buoolihng"], ["njjcfumyarhul"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms", "Sorting"], "name": null, "source": "codewars", "tags": ["String algorithms", "Sorting"], "skill_types": ["Sorting"], "url": "https://www.codewars.com/kata/536c6b8749aa8b3c2600029a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sort_string", "task_id": "TACO_lite/349", "example": [[["foos", "of"], ["string", "gnirts"], ["banana", "abn"]], ["oofs", "gnirts", "aaabnn"]]} +{"requirement": "If you have not ever heard the term **Arithmetic Progrossion**, refer to: \nhttp://www.codewars.com/kata/find-the-missing-term-in-an-arithmetic-progression/python\n\nAnd here is an unordered version. Try if you can survive lists of **MASSIVE** numbers (which means time limit should be considered). :D\n\nNote: Don't be afraid that the minimum or the maximum element in the list is missing, e.g. [4, 6, 3, 5, 2] is missing 1 or 7, but this case is excluded from the kata.\n\nExample:\n\n```python\nfind([3, 9, 1, 11, 13, 5]) # => 7\n```", "solutions": ["def find(seq):\n return (min(seq) + max(seq)) * (len(seq) + 1) / 2 - sum(seq)", "def find(a):\n return (max(a) + min(a)) * (len(a) + 1) / 2 - sum(a)", "def find(seq):\n (a, b, c) = (max(seq), min(seq), len(seq))\n z = list(range(b, a, (a - b) // c))\n return list(set(z) - set(seq))[0]", "def find(nums):\n return (min(nums) + max(nums)) * (len(nums) + 1) / 2 - sum(nums)", "def find(seq):\n if len(seq) <= 1:\n return seq\n seq.sort()\n x = []\n t = 0\n for i in range(len(seq) - 1):\n if i == 0:\n t = seq[i + 1] - seq[i]\n x.append(t)\n else:\n t = seq[i + 1] - seq[i]\n if t != x[-1]:\n x.append(t)\n break\n else:\n x.append(t)\n return min(seq) + len(x) * x[0]", "def find(seq):\n (a, b, n) = (min(*seq), max(*seq), len(seq))\n m = (b - a) // n\n return m * abs(sum(((x - a) // m for x in seq)) - (n + 1) * n // 2) + a", "find = lambda s: (min(s) + max(s)) * -~len(s) / 2 - sum(s)", "def find(seq):\n seq.sort()\n pattern = abs(seq[0] - seq[1])\n for i in range(len(seq) - 1):\n if seq[i] != seq[i + 1] - pattern:\n return seq[i] + pattern", "def find(seq):\n seq.sort()\n (first, last) = (seq[0], seq[-1])\n d = min(seq[1] - first, seq[2] - seq[1])\n n = (last - first) * 1.0 / d + 1\n s = n / 2 * (first + last)\n s_ = sum(seq)\n return s - s_", "def find(seq):\n prev = 0\n curr = 0\n seq.sort()\n length = len(seq)\n diff = (seq[length - 1] - seq[0]) / length\n for i in range(1, len(seq)):\n if seq[i] == seq[curr] + diff:\n prev = curr\n curr = i\n else:\n return int(seq[curr] + diff)"], "starter_code": "def find(seq):\n", "input_output": {"fn_name": "find", "inputs": [[[3, 9, 1, 11, 13, 5]], [[5, -1, 0, 3, 4, -3, 2, -2]], [[2, -2, 8, -8, 4, -4, 6, -6]]], "outputs": [[7], [1], [0]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Performance", "Algorithms"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/568fca718404ad457c000033", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "find", "task_id": "TACO_lite/373", "example": [[[[3, 9, 1, 11, 13, 5]]], [7.0]]} +{"requirement": "Given two strings denoting non-negative numbers X and Y. Calculate the sum of X and Y. \nExample 1:\nInput:\nX = \"25\", Y = \"23\"\nOutput:\n48\nExplanation:\nThe sum of 25 and 23 is 48.\nExample 2:\nInput:\nX = \"2500\", Y = \"23\"\nOutput:\n2523\nExplanation:\nThe sum of 2500 and 23 is 2523.\nYour Task:\nYour task is to complete the function findSum() which takes two strings as inputs and returns the string without leading zeros. You do not need to take any input or print anything.\nExpected Time Complexity: O(|X| + |Y|)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= |X|, |Y| <= 10^{5}", "solutions": ["def findsum(X, Y):\n self.X = int(X)\n self.Y = int(Y)\n result = self.X + self.Y\n return result", "def findsum(X, Y):\n sum = int(X) + int(Y)\n return sum", "def findsum(X, Y):\n x = int(X)\n y = int(Y)\n A = str(x + y)\n return A", "def findsum(X, Y):\n x = int(X)\n y = int(Y)\n ans = x + y\n return ans", "def findsum(X, Y):\n d1 = int(X)\n d2 = int(Y)\n return d1 + d2", "def findsum(X, Y):\n return str(int(X) + int(Y))", "def findsum(X, Y):\n a = int(X)\n b = int(Y)\n return a + b", "def findsum(X, Y):\n num1 = int(X)\n num2 = int(Y)\n return num1 + num2", "def findsum(X, Y):\n x_pointer = len(X) - 1\n y_pointer = len(Y) - 1\n carry = 0\n string = ''\n while x_pointer >= 0 and y_pointer >= 0:\n num1 = ord(X[x_pointer]) - ord('0')\n num2 = ord(Y[y_pointer]) - ord('0')\n num = num1 + num2\n num += carry\n last_digit = num % 10\n carry = num // 10\n string += str(last_digit)\n x_pointer -= 1\n y_pointer -= 1\n while x_pointer >= 0:\n num1 = ord(X[x_pointer]) - ord('0')\n num = num1 + carry\n last_digit = num % 10\n carry = num // 10\n string += str(last_digit)\n x_pointer -= 1\n while y_pointer >= 0:\n num2 = ord(Y[y_pointer]) - ord('0')\n num = num2 + carry\n last_digit = num % 10\n carry = num // 10\n string += str(last_digit)\n y_pointer -= 1\n if carry:\n string += str(carry)\n string = string[::-1]\n string = string.lstrip('0')\n if not string:\n return '0'\n return string", "def findsum(X, Y):\n s = int(X) + int(Y)\n return s", "def findsum(x, y):\n a = int(x)\n b = int(y)\n return a + b", "def findsum(X, Y):\n num1 = int(X)\n num2 = int(Y)\n total = num1 + num2\n result = str(total)\n if result == '0':\n return result\n else:\n result = result.lstrip('0')\n return result", "def findsum(X, Y):\n x = int(X)\n y = int(Y)\n sum = x + y\n return int(sum)", "def findsum(X, Y):\n z = int(X) + int(Y)\n return z", "def findsum(X, Y):\n c = int(X) + int(Y)\n return c", "def findsum(X, Y):\n q = int(X)\n w = int(Y)\n s = str(q + w)\n return s", "def findsum(X, Y):\n z = int(X)\n y = int(Y)\n sum = z + y\n return sum", "def findsum(X, Y):\n e = int(x)\n s = int(y)\n d = e + s\n return d", "def findsum(x, y):\n s = int(x) + int(y)\n return str(s)", "def findsum(X, Y):\n a1 = int(X)\n a2 = int(Y)\n return a1 + a2", "def findsum(X, Y):\n a = int(X)\n b = int(Y)\n result = a + b\n return str(result)", "def findsum(X, Y):\n n = int(X) + int(Y)\n return n", "def findsum(X, Y):\n temp1 = int(X)\n temp2 = int(Y)\n return str(temp1 + temp2)", "def findsum(X, Y):\n a = int(x)\n b = int(y)\n c = a + b\n return c", "def getNum(str):\n pos = 1\n res = 0\n for i in range(len(str) - 1, -1, -1):\n res += (ord(str[i]) - ord('0')) * pos\n pos *= 10\n return res\n\ndef findsum(X, Y):\n return int(X) + int(Y)", "def findsum(X, Y):\n n1 = int(X)\n n2 = int(Y)\n return n1 + n2", "def findsum(X, Y):\n t = int(X)\n t1 = int(Y)\n return t + t1", "def findsum(X, Y):\n (i, j) = (len(X) - 1, len(Y) - 1)\n output = []\n carry = 0\n while i >= 0 and j >= 0:\n sum = int(X[i]) + int(Y[j]) + carry\n (carry, curr_sum) = (int(sum / 10), sum % 10)\n output.append(str(curr_sum))\n i -= 1\n j -= 1\n while i >= 0:\n sum = int(X[i]) + carry\n (carry, curr_sum) = (int(sum / 10), sum % 10)\n output.append(str(curr_sum))\n i -= 1\n while j >= 0:\n sum = int(Y[j]) + carry\n (carry, curr_sum) = (int(sum / 10), sum % 10)\n output.append(str(curr_sum))\n j -= 1\n if carry:\n output.append(str(carry))\n return int(''.join(reversed(output)))", "def findsum(X, Y):\n x_int = int(X)\n y_int = int(Y)\n result = x_int + y_int\n return str(result)", "def findsum(X, Y):\n X = int(X)\n Y = int(Y)\n Z = X + Y\n return Z", "def findsum(X, Y):\n p = int(X)\n q = int(Y)\n return p + q", "def findsum(X, Y):\n first = int(X)\n second = int(Y)\n ans = str(first + second)\n return ans", "def findsum(X, Y):\n int1 = int(X)\n int2 = int(Y)\n return int1 + int2", "def findsum(X, Y):\n total = int(X) + int(Y)\n return total"], "starter_code": "def findsum(X, Y):\n", "input_output": {"inputs": ["X = \"25\", Y = \"23\"", "X = \"2500\", Y = \"23\""], "outputs": ["48", "2523"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/sum-of-numbers-or-number1219/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|X| + |Y|)", "entry_point": "findsum", "task_id": "TACO_lite/343", "example": [[["25", "23"], ["2500", "23"]], ["48", "2523"]]} +{"requirement": "Write a program that will calculate the number of trailing zeros in a factorial of a given number.\n\n`N! = 1 * 2 * 3 * ... * N`\n\nBe careful `1000!` has 2568 digits...\n\nFor more info, see: http://mathworld.wolfram.com/Factorial.html \n\n## Examples\n\n```python\nzeros(6) = 1\n# 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero\n\nzeros(12) = 2\n# 12! = 479001600 --> 2 trailing zeros\n```\n\n*Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros.*", "solutions": ["def zeros(n):\n pow_of_5 = 5\n zeros = 0\n while n >= pow_of_5:\n zeros += n // pow_of_5\n pow_of_5 *= 5\n return zeros", "def zeros(n):\n zeros = 0\n i = 5\n while n // i > 0:\n zeros += n // i\n i *= 5\n return zeros", "def zeros(n):\n return 0 if int(n / 5) < 1 else int(n / 5) + int(zeros(n / 5))", "def zeros(n):\n count = 0\n while n:\n n = n // 5\n count += n\n return count", "import math\n\ndef zeros(n):\n if n >= 5:\n return math.floor(n / 5) + zeros(n / 5)\n else:\n return 0", "def find_factor(p, n):\n (result, power) = (0, p)\n while power < n:\n result += n // power\n power *= p\n return result\n\ndef zeros(n):\n return min((find_factor(p, n) for p in (2, 5)))", "from math import log, floor\n\ndef zeros(n):\n if n < 5:\n return 0\n powers = range(1, floor(log(n, 5)) + 1)\n return sum((n // div for div in (5 ** pw for pw in powers)))", "from math import log, ceil\n\ndef zeros(n):\n return sum((n // 5 ** i for i in range(1, ceil(log(n, 5))))) if n > 0 else 0", "def zeros(n):\n res = 0\n while n >= 5:\n res += n // 5\n n //= 5\n return res", "def zeros(n):\n c = 0\n r = 1\n while 5 ** r <= n:\n c += len(range(5 ** r, n + 1, 5 ** r))\n r += 1\n return c", "def zeros(n):\n a = n // 5\n if a >= 5:\n return a + zeros(a)\n else:\n return a", "def zeros(n):\n sum = 0\n for i in range(1, 30):\n sum += n // 5 ** i\n return sum", "def zeros(n):\n result = 0\n i = 5\n while n / i >= 1:\n result += int(n / i)\n i *= 5\n return int(result)", "def zeros(n):\n (c, x) = (0, 5)\n while n > x:\n c += n // x\n x *= 5\n return c", "from math import floor\n\ndef zeros(n):\n sum = 0\n power = 1\n while n / 5 ** power >= 1:\n sum += floor(n / 5 ** power)\n power += 1\n return sum", "def zeros(n):\n (i, j) = (1, 0)\n while 5 ** i <= n:\n (i, j) = (i + 1, j + int(n / 5 ** i))\n return j", "def zeros(n):\n (base, total) = (5, 0)\n while n > base:\n total += n // base\n base *= 5\n return total", "def zeros(n):\n p = 0\n sum = 0\n while n > 5 ** p:\n p += 1\n sum += n // 5 ** p\n return sum", "from itertools import takewhile, count\nfrom operator import truth\n\ndef zeros(n):\n return sum(takewhile(truth, (n // 5 ** e for e in count(1))))", "zeros = lambda n: n // 5 + zeros(n / 5) if n / 5 else 0", "from itertools import count, takewhile\npow5 = lambda x: 5 ** x\n\ndef zeros(n):\n okay = lambda x: x <= n\n val = lambda x: n // x\n return sum(map(val, takewhile(okay, map(pow5, count(1)))))", "def zeros(n):\n if n / 5 <= 0:\n return 0\n else:\n n //= 5\n return n + zeros(n)", "import math\n\ndef zeros(n):\n if n == 0:\n return 0\n fives = 0\n log5n = int(math.log10(n) / math.log10(5))\n for i in range(1, log5n + 1):\n fives += int(n / 5 ** i)\n return int(fives)", "def zeros(n):\n count = 0\n i = 5\n while n / i >= 1:\n count += int(n / i)\n i *= 5\n return int(count)", "def zeros(n):\n t = 5\n s = 0\n while n > t:\n s += n // t\n t *= 5\n return s", "import math\n\ndef zeros(n):\n Zeros = 0\n i = 5\n while i <= n:\n Zeros += math.floor(n / i)\n i *= 5\n return Zeros", "def zeros(n):\n return sum((n // 5 ** i for i in range(1, 20)))", "import math\n\ndef zeros(n):\n return 0 if n < 2 else sum([n // 5 ** f for f in range(1, max(2, int(math.log(n)))) if 5 ** f <= n])", "import math\n\ndef zeros(n: int):\n if n < 5:\n return 0\n log_n_5 = int(math.log(n, 5))\n return sum([n // 5 ** i for i in range(1, log_n_5 + 1)])", "def zeros(n):\n n = n // 5\n number = n\n while n != 0:\n n = n // 5\n number += n\n return number", "def zeros(n):\n i = 1\n res = 0\n while 5 ** i < n:\n res += n // 5 ** i\n i += 1\n return res", "import math\n\ndef zeros(n):\n sum = 0\n if n < 5:\n return 0\n for i in range(1, math.floor(math.log(n, 5) + 1)):\n sum += math.floor(n / pow(5, i))\n return sum", "def zeros(n):\n num_5 = n\n num_2 = n\n n_5 = 0\n n_2 = 0\n while num_5 != 0:\n n_5 += num_5 // 5\n num_5 = num_5 // 5\n return n_5", "from math import factorial\n\ndef zeros(n):\n if n == 0:\n return 0\n cnt = 0\n div_num = 5\n while n / div_num >= 1:\n cnt += int(n / div_num)\n div_num *= 5\n return cnt", "def zeros(n):\n count = 0\n divider = 5\n while n / divider >= 1:\n count += int(n / divider)\n divider *= 5\n return int(count)", "import math\n\ndef zeros(n):\n count = 0\n if n == 0:\n return 0\n else:\n k_max = math.floor(math.log(n, 5))\n for i in range(k_max):\n ans = math.floor(n / 5 ** (i + 1))\n count = count + ans\n return count", "def zeros(n):\n divisor = 5\n count = 0\n while n > divisor:\n count = count + int(n / divisor)\n divisor *= 5\n return count", "def zeros(n):\n if n == 0:\n return 0\n value = 0\n i = 1\n while True:\n if n > 5 ** i:\n value += n // 5 ** i\n else:\n return value\n i += 1", "def zeros(n):\n return sum([n // 5 ** i for i in range(1, len(str(n)) + len(str(n // 1000 + 1)))])", "def zeros(n):\n x = 0\n z = 5\n while n > 0:\n n /= 5\n x += int(n)\n return x", "def zeros(n):\n i = 5\n count_5 = 0\n while n // i >= 1:\n count_5 += n // i\n i *= 5\n return count_5", "import math\n\ndef zeros(n):\n if n <= 0:\n return 0\n k_max = math.floor(math.log(n, 5)) + 1\n sum = 0\n for k in range(1, k_max):\n sum += math.floor(n / 5 ** k)\n return sum", "def zeros(n):\n (i, count) = (20, 0)\n while i > 0:\n count += n // 5 ** i\n i -= 1\n return count", "def zeros(n):\n answer = 0\n for i in range(1, 100):\n answer += int(n / 5 ** i)\n return answer", "def zeros(n):\n sum = 0\n d = 5\n while d <= n:\n sum += n // d\n d *= 5\n return sum", "def zeros(n):\n p = n // 5\n t = p\n while t > 0:\n t = t // 5\n p = p + t\n return p", "from math import log\n\ndef zeros(n):\n if n == 0:\n return 0\n y = 0\n for x in range(1, int(log(n, 5) + 1)):\n y += n // 5 ** x\n return y", "from math import *\n\ndef zeros(n):\n res = 0\n i = 5\n while i < n:\n res += floor(n / i)\n i *= 5\n return res", "def zeros(n):\n b = 0\n while 5 ** b < n:\n b += 1\n return sum((n // 5 ** c for c in range(1, b)))", "def zeros(n):\n result = 0\n power = 1\n while True:\n if 5 ** power > n:\n break\n result += n // 5 ** power\n power += 1\n return result", "import math\n\ndef zeros(n):\n ret = 0\n if n == 0:\n return 0\n for i in range(1, int(math.log(n) / math.log(5)) + 1):\n ret += n // math.pow(5, i)\n return ret", "import math\n\ndef zeros(n):\n if n == 0:\n return 0\n z = 0\n kmax = math.floor(math.log(n) / math.log(5))\n for i in range(1, kmax + 1):\n z += math.floor(n / 5 ** i)\n return z", "from math import log\n\ndef zeros(n):\n if n == 0:\n return 0\n z = 0\n k = 1\n kMax = round(log(n, 5))\n for i in range(k, kMax + 1):\n z += n // 5 ** i\n return z", "def zeros(n):\n num_zero = 0\n while n > 0:\n n = n // 5\n num_zero += n\n return num_zero", "def zeros(n):\n sums = []\n while n > 5:\n n /= 5\n sums.append(int(n))\n a = 0\n for num in sums:\n a += int(num)\n return int(a)", "def zeros(n):\n i = 1\n x = 0\n while 5 ** i <= n:\n x += n // 5 ** i\n i += 1\n return x", "from math import log\n\ndef zeros(n):\n if n == 0:\n return 0\n z = 0\n i = 1\n while i < log(n, 5):\n z += n // 5 ** i\n i += 1\n return z", "import math\n\ndef zeros(n):\n zeroes = 0\n k = 1\n while n / 5 ** k > 1:\n zeroes += math.floor(n / 5 ** k)\n k += 1\n return zeroes", "def zeros(n):\n zeros = 0\n tmp = n\n while tmp >= 1:\n tmp /= 5\n zeros += int(tmp)\n return zeros", "import math\n\ndef zeros(n):\n return sum((int(n / math.pow(5, i)) for i in range(1, 15) if int(n / math.pow(5, i)) != 0))", "def zeros(n):\n\n def find_exponent(n, p):\n factor = 0\n p_helper = p\n while n > p_helper:\n factor += int(n / p_helper)\n p_helper *= p\n return factor\n five_exponent = find_exponent(n, 5)\n return five_exponent", "def zeros(n):\n\n def find_exponent(n, p):\n factor = 0\n p_helper = p\n while n > p_helper:\n factor += int(n / p_helper)\n p_helper *= p\n return factor\n two_exponent = find_exponent(n, 2)\n five_exponent = find_exponent(n, 5)\n return min(two_exponent, five_exponent)", "import math\n\ndef zeros(n):\n count = 0\n i = 5\n while n / i >= 1:\n count += int(n / i)\n i *= 5\n return int(count)"], "starter_code": "def zeros(n):\n", "input_output": {"fn_name": "zeros", "inputs": [[0], [6], [30], [100], [1000], [100000], [1000000000]], "outputs": [[0], [1], [7], [24], [249], [24999], [249999998]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Logic"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/52f787eb172a8b4ae1000a34", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "zeros", "task_id": "TACO_lite/344", "example": [[[6], [12]], ["1", "2"]]} +{"requirement": "Given an array of numbers (in string format), you must return a string. The numbers correspond to the letters of the alphabet in reverse order: a=26, z=1 etc. You should also account for `'!'`, `'?'` and `' '` that are represented by '27', '28' and '29' respectively.\n\nAll inputs will be valid.", "solutions": ["def switcher(arr):\n d = {str(i): chr(123 - i) for i in range(1, 27)}\n d.update({'27': '!'})\n d.update({'28': '?'})\n d.update({'29': ' '})\n d.update({'0': ''})\n return ''.join([d[str(i)] for i in arr])", "import string\nletters = string.ascii_lowercase[::-1] + '!? '\n\ndef switcher(arr):\n return ''.join([letters[ch - 1] for ch in map(int, arr) if ch])", "chars = '_zyxwvutsrqponmlkjihgfedcba!? '\n\ndef switcher(arr):\n return ''.join((chars[int(i)] for i in arr if i != '0'))", "from string import ascii_lowercase as abc\nch = abc[::-1] + '!? '\n\ndef switcher(arr):\n return ''.join((ch[int(x) - 1] if x != '0' else '' for x in arr))", "def switcher(arr):\n trans = {'26': 'a', '25': 'b', '24': 'c', '23': 'd', '22': 'e', '21': 'f', '20': 'g', '19': 'h', '18': 'i', '17': 'j', '16': 'k', '15': 'l', '14': 'm', '13': 'n', '12': 'o', '11': 'p', '10': 'q', '9': 'r', '8': 's', '7': 't', '6': 'u', '5': 'v', '4': 'w', '3': 'x', '2': 'y', '1': 'z', '27': '!', '28': '?', '29': ' '}\n return ''.join((trans[a] for a in arr if a in trans))", "STR = '+zyxwvutsrqponmlkjihgfedcba!? '\n\ndef switcher(arr):\n return ''.join((STR[int(x)] for x in arr)).replace('+', '')", "def switcher(arr):\n return ''.join(({'27': '!', '28': '?', '29': ' '}.get(e, chr(abs(int(e) - 26) + 97)) for e in arr))", "alphabet = ['z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a', '!', '?', ' ']\n\ndef switcher(arr):\n return ''.join([alphabet[int(i) - 1] for i in arr])", "def switcher(arr):\n return ''.join((chr(123 - int(i)) for i in arr)).translate(str.maketrans('`_^', '!? '))", "def switcher(arr):\n return ''.join(({'27': '!', '28': '?', '29': ' '}.get(i, chr(123 - int(i))) for i in arr))"], "starter_code": "def switcher(arr):\n", "input_output": {"fn_name": "switcher", "inputs": [[["24", "12", "23", "22", "4", "26", "9", "8"]], [["25", "7", "8", "4", "14", "23", "8", "25", "23", "29", "16", "16", "4"]], [["4", "24"]], [["12"]], [["12", "28", "25", "21", "25", "7", "11", "22", "15"]]], "outputs": [["codewars"], ["btswmdsbd kkw"], ["wc"], ["o"], ["o?bfbtpel"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57ebaa8f7b45ef590c00000c", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "switcher", "task_id": "TACO_lite/402", "example": [[[["26", "1", "13", "3", "1"]], [["28", "27", "29", "1"]]], ["aznxz", "?! z"]]} +{"requirement": "The number ```12``` is the first number in having six divisors, they are: ```1, 2, 3, 4, 6 and 12.```\nYour challenge for this kata is to find the minimum number that has a certain number of divisors.\nFor this purpose we have to create the function \n\n```find_min_num() or findMinNum() or similar in the other languages```\n\nthat receives the wanted number of divisors ```num_div```, and outputs the smallest number having an amount of divisors equals to ```num_div```.\n\nLet's see some cases:\n```\nfind_min_num(10) = 48 # divisors are: 1, 2, 3, 4, 6, 8, 12, 16, 24 and 48\nfind_min_num(12) = 60\n```\nIn this kata all the tests will be with ```numDiv < 80```\n\n(There will be a next kata with numDiv < 10000, Find the First Number Having a Certain Number of Divisors II, should have the help of number theory)\n\nEnjoy it and happy coding!\n(Memoization is advisable)", "solutions": ["def find_min_num(d, n=1):\n while div_num(n) != d:\n n += 1\n return n\n\ndef div_num(n):\n s = n ** 0.5\n return sum((2 for k in range(1, int(s) + 1) if n % k == 0)) - (s % 1 == 0)", "from collections import Counter\n\ndef number_of_div(n):\n i = 2\n factors = []\n while i * i <= n:\n if n % i:\n i += 1\n else:\n n //= i\n factors.append(i)\n if n > 1:\n factors.append(n)\n mu = 1\n po = [i + 1 for i in list(Counter(factors).values())]\n for i in po:\n mu *= i\n return mu\n\ndef find_min_num(num_div):\n for i in range(1, num_div ** 4):\n num = number_of_div(i)\n if num == num_div:\n return i", "def n_div(n):\n result = 0\n for i in range(1, int(n ** 0.5) + 1):\n if n % i == 0:\n result += 1 + (i * i < n)\n return result\n\ndef find_min_num(num_div):\n for i in range(num_div, 1000000):\n if n_div(i) == num_div:\n return i", "(FOUND, n) = ({}, 1)\nwhile len(FOUND) < 60:\n sq = n ** 0.5\n nDivs = sum((2 * (not n % x) for x in range(1, int(sq) + 1))) - (int(sq) == sq)\n if nDivs not in FOUND:\n FOUND[nDivs] = n\n n += 1\n\ndef find_min_num(nDivs):\n return FOUND[nDivs]", "def count_divs(n):\n is_square = 0\n if n ** 0.5 % 1 == 0:\n is_square = 1\n return len([(x, n / x) for x in range(1, int(n ** 0.5) + 1) if n % x == 0]) * 2 - is_square\nmin_num = {count_divs(i): i for i in reversed(range(1, 10 ** 5))}\n\ndef find_min_num(num_div):\n return min_num[num_div]", "def divisors(n):\n count = 2\n i = 2\n while i ** 2 < n:\n if n % i == 0:\n count += 2\n i += 1\n if i ** 2 == n:\n count += 1\n return count\n\ndef find_min_num(num):\n i = 2\n while True:\n d = divisors(i)\n if d == num:\n return i\n i += 1", "find_min_num = lambda n: [0, 1, 2, 4, 6, 16, 12, 64, 24, 36, 48, 1024, 60, 4096, 192, 144, 120, 65536, 180, 0, 240, 576, 3072, 0, 360, 1296, 12288, 900, 960, 0, 720, 0, 840, 9216, 0, 5184, 1260, 0, 0, 36864, 1680, 0, 2880, 0, 15360, 3600, 0, 0, 2520, 46656, 6480, 0, 61440, 0, 6300, 0, 6720, 0, 0, 0, 5040, 0, 0, 14400, 7560, 0, 46080, 0, 0, 0, 25920, 0, 10080, 0, 0, 32400, 0, 0, 0, 0, 15120, 44100, 0, 0, 20160, 0, 0, 0, 0, 0, 25200, 0, 0, 0, 0, 0, 27720, 0, 0, 0, 45360][n]", "def check(n):\n set1 = set()\n for i in range(1, int(n ** 0.5) + 1):\n if n % i == 0:\n set1.add(i)\n set1.add(n // i)\n return set1\n\ndef find_min_num(num_div):\n i = 1\n while 1:\n if len(check(i)) == num_div:\n return i\n i += 1\n return n"], "starter_code": "def find_min_num(d, n=1):\n", "input_output": {"fn_name": "find_min_num", "inputs": [[6], [10], [12], [13]], "outputs": [[12], [48], [60], [4096]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals", "Memoization", "Data Structures", "Dynamic Programming"], "name": null, "source": "codewars", "tags": ["Dynamic programming", "Fundamentals", "Data structures", "Mathematics"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://www.codewars.com/kata/5612ab201830eb000f0000c0", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "find_min_num", "task_id": "TACO_lite/404", "example": [[[10], [12]], ["48", "60"]]} +{"requirement": "You're a programmer in a SEO company. The SEO specialist of your company gets the list of all project keywords everyday, then he looks for the longest keys to analyze them.\n\nYou will get the list with keywords and must write a simple function that returns the biggest search keywords and sorts them in lexicographical order.\n\nFor instance you might get:\n```python\n'key1', 'key2', 'key3', 'key n', 'bigkey2', 'bigkey1'\n```\n\nAnd your function should return:\n```python\n\"'bigkey1', 'bigkey2'\"\n```\n\nDon't forget to rate this kata! Thanks :)", "solutions": ["def the_biggest_search_keys(*keys):\n L = sorted(keys, key=lambda key: (-len(key), key))\n i = next((i for (i, key) in enumerate(L) if len(key) != len(L[0])), None)\n return str(L[:i])[1:-1] or \"''\"", "def the_biggest_search_keys(*arg):\n mx = len(max(arg, key=len, default=''))\n return ', '.join(sorted((f\"'{e}'\" for e in list(arg) + [''] if len(e) == mx)))", "def the_biggest_search_keys(*keys):\n if not keys:\n return \"''\"\n n = max(map(len, keys))\n keys = sorted([key for key in keys if len(key) == n])\n return ', '.join((f\"'{key}'\" for key in keys))", "def the_biggest_search_keys(*keys):\n m = max(map(len, keys)) if keys else None\n return str(sorted(filter(lambda x: len(x) == m, keys)))[1:-1] if keys else \"''\"", "def the_biggest_search_keys(*keys):\n if not keys:\n keys = ['']\n longest_key_length = max(map(len, keys))\n return ', '.join(sorted((\"'%s'\" % key for key in keys if len(key) == longest_key_length)))", "def the_biggest_search_keys(*args):\n by_len = {}\n fmt = \"'{}'\".format\n for a in args:\n by_len.setdefault(len(a), []).append(a)\n try:\n return ', '.join((fmt(b) for b in sorted(by_len[max(by_len)])))\n except ValueError:\n return \"''\"", "def the_biggest_search_keys(*keys):\n (biggest, max_len) = ([], 0)\n for key in keys:\n key_len = len(key)\n if key_len == max_len:\n biggest.append(key)\n elif key_len > max_len:\n (biggest, max_len) = ([key], key_len)\n return ', '.join((\"'{}'\".format(key) for key in sorted(biggest))) or \"''\"", "def the_biggest_search_keys(*keys):\n if not keys:\n return \"''\"\n max_len = 0\n for key in keys:\n key_len = len(key)\n if key_len > max_len:\n max_len = key_len\n result = [key]\n elif key_len == max_len:\n result += [key]\n return str(sorted(result))[1:-1]", "def the_biggest_search_keys(*args):\n maxLen = max(map(len, args), default=None)\n return \"''\" if not args else ', '.join(sorted(filter(lambda s: len(s) - 2 == maxLen, map(lambda s: \"'{}'\".format(s), args))))", "def the_biggest_search_keys(*keywords):\n return ', '.join(sorted((f\"'{x}'\" for x in keywords if len(x) == max(map(len, keywords))))) if keywords else \"''\""], "starter_code": "def the_biggest_search_keys(*keys):\n", "input_output": {"fn_name": "the_biggest_search_keys", "inputs": [["key1", "key22", "key333"], ["coding", "sorting", "tryruby"], ["small keyword", "how to coding?", "very nice kata", "a lot of keys", "I like Ruby!!!"], ["pippi"]], "outputs": [["'key333'"], ["'sorting', 'tryruby'"], ["'I like Ruby!!!', 'how to coding?', 'very nice kata'"], ["'pippi'"]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/58ac1abdff4e78738f000805", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "the_biggest_search_keys", "task_id": "TACO_lite/414", "example": [[["key1", "key2", "key3", "key n", "bigkey2", "bigkey1"]], ["'bigkey1', 'bigkey2'"]]} +{"requirement": "Given a binary tree root, a\u00a0ZigZag path for a binary tree is defined as follow:\n\nChoose any node in the binary tree and a direction (right or left).\nIf the current direction is right then move to the right child of the current node otherwise move to the left child.\nChange the direction from right to left or right to left.\nRepeat the second and third step until you can't move in the tree.\n\nZigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).\nReturn\u00a0the longest ZigZag path contained in that tree.\n\u00a0\nExample 1:\n\nInput: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]\nOutput: 3\nExplanation: Longest ZigZag path in blue nodes (right -> left -> right).\n\nExample 2:\n\nInput: root = [1,1,1,null,1,null,null,1,1,null,1]\nOutput: 4\nExplanation: Longest ZigZag path in blue nodes (left -> right -> left -> right).\n\nExample 3:\nInput: root = [1]\nOutput: 0\n\n\u00a0\nConstraints:\n\nEach tree has at most 50000 nodes..\nEach node's value is between [1, 100].", "solutions": ["def longestZigZag(root: TreeNode) -> int:\n if root == None:\n return None\n maxlength = 0\n stack = collections.deque()\n if root.left:\n stack.append((1, 1, root.left))\n if root.right:\n stack.append((1, 0, root.right))\n while stack:\n (length, isleft, node) = stack.pop()\n if isleft:\n if node.right:\n stack.append((length + 1, 0, node.right))\n else:\n maxlength = max(maxlength, length)\n if node.left:\n stack.append((1, 1, node.left))\n else:\n if node.left:\n stack.append((length + 1, 1, node.left))\n else:\n maxlength = max(maxlength, length)\n if node.right:\n stack.append((1, 0, node.right))\n return maxlength", "def longestZigZag(root: TreeNode) -> int:\n stack = [(root, 0, 'left')]\n res = 0\n while stack:\n (node, length, d) = stack.pop()\n res = max(res, length)\n if node.left:\n if d != 'left':\n stack.append((node.left, length + 1, 'left'))\n else:\n stack.append((node.left, 1, 'left'))\n if node.right:\n if d != 'right':\n stack.append((node.right, length + 1, 'right'))\n else:\n stack.append((node.right, 1, 'right'))\n return res", "from collections import deque\n\ndef longestZigZag(root: TreeNode) -> int:\n ans = 0\n q = deque([[root, 'A', 0]])\n while len(q) != 0:\n (top, state, dist) = q[0]\n ans = max(ans, dist)\n q.popleft()\n if state == 'A':\n if top.left:\n q.append([top.left, 'L', 1])\n if top.right:\n q.append([top.right, 'R', 1])\n else:\n if state == 'L':\n if top.left:\n q.append([top.left, 'L', 1])\n if top.right:\n q.append([top.right, 'R', dist + 1])\n if state == 'R':\n if top.left:\n q.append([top.left, 'L', dist + 1])\n if top.right:\n q.append([top.right, 'R', 1])\n return ans", "def longestZigZag(root: TreeNode) -> int:\n\n def dfs(node):\n if not node:\n return [-1, -1, -1]\n left = dfs(node.left)\n right = dfs(node.right)\n return [left[1] + 1, right[0] + 1, max(left[1] + 1, right[0] + 1, left[2], right[2])]\n return dfs(root)[-1]", "def longestZigZag(root: TreeNode) -> int:\n maxlen = 0\n dt = collections.defaultdict(lambda : [0, 0])\n\n def dfs(root, dt):\n nonlocal maxlen\n if root.left:\n dfs(root.left, dt)\n dt[root][0] = dt[root.left][1] + 1\n else:\n dt[root][0] = 0\n if root.right:\n dfs(root.right, dt)\n dt[root][1] = dt[root.right][0] + 1\n else:\n dt[root][1] = 0\n maxlen = max(maxlen, dt[root][0], dt[root][1])\n dfs(root, dt)\n return maxlen", "def helper(node: TreeNode, lastDirection: str, cache) -> int:\n if not node:\n return 0\n if (node, lastDirection) in cache:\n return cache[node, lastDirection]\n count = 1\n childCount = float('-inf')\n if lastDirection == 'right':\n childCount = max(childCount, self.helper(node.left, 'left', cache))\n else:\n childCount = max(childCount, self.helper(node.right, 'right', cache))\n count += childCount\n cache[node, lastDirection] = count\n return count\n\ndef longestZigZag(root: TreeNode) -> int:\n maxCount = float('-inf')\n cache = {}\n stack = [root]\n while stack:\n node = stack.pop()\n maxCount = max(maxCount, self.helper(node, 'left', cache))\n maxCount = max(maxCount, self.helper(node, 'right', cache))\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n return maxCount - 1", "def longestZigZag(root: TreeNode) -> int:\n self.ans = 0\n memo = {}\n\n def dfs2(node, direction):\n if not node:\n return 0\n if (node, direction) not in memo:\n if direction == False:\n memo[node, direction] = 1 + dfs2(node.right, True)\n else:\n memo[node, direction] = 1 + dfs2(node.left, False)\n return memo[node, direction]\n\n def dfs1(node):\n if not node:\n return\n self.ans = max(self.ans, dfs2(node, True) - 1, dfs2(node, False) - 1)\n dfs1(node.left)\n dfs1(node.right)\n dfs1(root)\n return self.ans", "def longestZigZag(root: TreeNode) -> int:\n self.res = 0\n if root.left:\n self.dfs(root.left, 1, True, False)\n if root.right:\n self.dfs(root.right, 1, False, True)\n return self.res\n\ndef dfs(node, count, prevL, prevR):\n if not node:\n return\n self.res = max(self.res, count)\n if prevL:\n self.dfs(node.left, 1, True, False)\n self.dfs(node.right, count + 1, False, True)\n if prevR:\n self.dfs(node.left, count + 1, True, False)\n self.dfs(node.right, 1, False, True)", "def longestZigZag(root: TreeNode) -> int:\n self.res = float(-inf)\n\n def helper(root, left, right):\n self.res = max(self.res, max(left, right))\n if root == None:\n return\n if root.left:\n helper(root.left, right + 1, 0)\n if root.right:\n helper(root.right, 0, left + 1)\n return\n helper(root, 0, 0)\n return self.res", "def longestZigZag(root: TreeNode) -> int:\n ans = [-1]\n\n def aux(root, isleft, ans):\n if not root:\n return -1\n left = aux(root.left, 1, ans) + 1\n right = aux(root.right, 0, ans) + 1\n ans[0] = max(ans[0], left, right)\n if isleft:\n return right\n else:\n return left\n if not root:\n return 0\n aux(root, 0, ans)\n return ans[0]", "def helper(node, prenode, ans):\n if not node:\n return\n self.res = max(self.res, ans)\n if node == prenode.left:\n self.helper(node.right, node, ans + 1)\n self.helper(node.left, node, 1)\n elif node == prenode.right:\n self.helper(node.left, node, ans + 1)\n self.helper(node.right, node, 1)\n\ndef longestZigZag(root: TreeNode) -> int:\n self.res = 0\n self.helper(root.left, root, 1)\n self.helper(root.right, root, 1)\n return self.res", "def longestZigZag(root: TreeNode) -> int:\n\n def zigzag(node: TreeNode) -> tuple:\n if not node:\n return (0, 0)\n (_, lr) = zigzag(node.left)\n (rl, _) = zigzag(node.right)\n self.max_path = max(self.max_path, lr + 1, rl + 1)\n return (lr + 1, rl + 1)\n self.max_path = 0\n zigzag(root)\n return self.max_path - 1", "def longestZigZag(root: TreeNode) -> int:\n if root == None:\n return 0\n maxZigZag = 0\n\n def zigZagStart(root):\n nonlocal maxZigZag\n if root == None or (root.left == None and root.right == None):\n return [0, 0]\n (ll, lr) = zigZagStart(root.left)\n (rl, rr) = zigZagStart(root.right)\n bestLeft = 0\n bestRight = 0\n if root.left:\n bestLeft = 1 + lr\n if root.right:\n bestRight = 1 + rl\n maxZigZag = max(maxZigZag, bestLeft, bestRight)\n return [bestLeft, bestRight]\n zigZagStart(root)\n return maxZigZag", "def longestZigZag(root: TreeNode) -> int:\n self.longest = 0\n self.dfs(root, 0, 0)\n return self.longest\n\ndef dfs(node, longest_left, longest_right):\n self.longest = max(self.longest, longest_left, longest_right)\n if node.left:\n self.dfs(node.left, longest_right + 1, 0)\n if node.right:\n self.dfs(node.right, 0, longest_left + 1)", "def longestZigZag(root):\n\n def dfs(root):\n if not root:\n return [-1, -1, -1]\n (left, right) = (dfs(root.left), dfs(root.right))\n return [left[1] + 1, right[0] + 1, max(left[1] + 1, right[0] + 1, left[2], right[2])]\n return dfs(root)[-1]", "def longestZigZag(root: TreeNode) -> int:\n (_, max_depth) = self.zigzag(root)\n return max_depth\n\ndef zigzag(node: TreeNode, return_left=False) -> int:\n if node is None:\n return (-1, 0)\n (left_depth, left_max) = self.zigzag(node.left)\n (right_depth, right_max) = self.zigzag(node.right, return_left=True)\n left_depth += 1\n right_depth += 1\n max_depth = max(left_depth, right_depth, left_max, right_max)\n return (left_depth if return_left else right_depth, max_depth)", "def longestZigZag(root: TreeNode) -> int:\n\n def longest(node: TreeNode, state: int, acc: int) -> int:\n self.m = max(self.m, acc)\n if not node:\n return 0\n if state == 0:\n (longest(node.right, 1, acc + 1), longest(node.left, 0, 0))\n else:\n (longest(node.left, 0, acc + 1), longest(node.right, 1, 0))\n (longest(root.left, 0, 0), longest(root.right, 1, 0))\n return self.m", "def longestZigZag(root: TreeNode) -> int:\n if not root:\n return 0\n q = deque()\n max_depth = 0\n if root.left:\n q.append((root.left, True, 1))\n if root.right:\n q.append((root.right, False, 1))\n while q:\n (n, is_left, depth) = q.popleft()\n max_depth = max(depth, max_depth)\n if n.left:\n if is_left:\n q.append((n.left, True, 1))\n else:\n q.append((n.left, True, depth + 1))\n if n.right:\n if is_left:\n q.append((n.right, False, depth + 1))\n else:\n q.append((n.right, False, 1))\n return max_depth", "def longestZigZag(root: TreeNode) -> int:\n q = collections.deque()\n res = 0\n q.append((root, 0, 0))\n while q:\n size = len(q)\n for _ in range(size):\n (node, l, r) = q.popleft()\n if node.left:\n q.append((node.left, r + 1, 0))\n res = max(res, r + 1)\n if node.right:\n q.append((node.right, 0, l + 1))\n res = max(res, l + 1)\n return res", "def longestZigZag(root: TreeNode) -> int:\n\n def zigzag(node, left, acum):\n if node is None:\n return acum - 1\n if left:\n return max(zigzag(node.left, False, acum + 1), zigzag(node.left, True, 0))\n else:\n return max(zigzag(node.right, True, acum + 1), zigzag(node.right, False, 0))\n return max(zigzag(root, True, 0), zigzag(root, False, 0))", "def longestZigZag(root: TreeNode) -> int:\n self.max_len = 0\n\n def subTree(root, indir, flip):\n if root is None:\n return 0\n if indir == -1:\n subcount = subTree(root.right, 1, True)\n self.max_len = max(subcount + 1, self.max_len)\n else:\n subcount = subTree(root.left, -1, True)\n self.max_len = max(subcount + 1, self.max_len)\n if flip:\n subTree(root, -indir, False)\n return subcount + 1\n subTree(root, 1, True)\n return self.max_len - 1", "def longestZigZag(root: TreeNode) -> int:\n l = [[root, 0]]\n r = [[root, 0]]\n m = 0\n while True:\n if l == [] and r == []:\n return m\n l1 = []\n r1 = []\n for i in l:\n m = max(m, i[1])\n if i[0].right != None:\n r1.append([i[0].right, i[1] + 1])\n if i[0].left != None:\n r1.append([i[0].left, 0])\n for i in r:\n m = max(m, i[1])\n if i[0].left != None:\n l1.append([i[0].left, i[1] + 1])\n if i[0].right != None:\n l1.append([i[0].right, 0])\n r = r1\n l = l1", "def longestZigZag(root: TreeNode) -> int:\n\n def help(root):\n if not root:\n return [-1, -1, -1]\n (left, right) = (help(root.left), help(root.right))\n return [left[1] + 1, right[0] + 1, max(left[-1], right[-1], left[1] + 1, right[0] + 1)]\n return help(root)[-1]", "def longestZigZag(root: TreeNode) -> int:\n\n def helper(root):\n stack = [[root, True, 0], [root, False, 0]]\n ans = 0\n while stack:\n (root, right, length) = stack.pop()\n if root:\n ans = max(length, ans)\n stack.append((root.right if right else root.left, not right, length + 1))\n stack.append((root.left if right else root.right, right, 1))\n return ans\n return helper(root)", "def __init__():\n self.max_length = float('-inf')\n\ndef longestZigZag(root):\n return self.dfs(root)[2] - 1\n\ndef dfs(root):\n if root is None:\n return [0, 0, 0]\n left_res = self.dfs(root.left)\n right_res = self.dfs(root.right)\n maxForSubtree = max(left_res[1], right_res[0]) + 1\n return [left_res[1] + 1, right_res[0] + 1, max(maxForSubtree, left_res[2], right_res[2])]", "def longestZigZagRec(root, goLeft, steps):\n if root == None:\n return steps - 1\n if goLeft:\n return max(self.longestZigZagRec(root.left, False, steps + 1), self.longestZigZagRec(root.right, True, 1))\n else:\n return max(self.longestZigZagRec(root.right, True, steps + 1), self.longestZigZagRec(root.left, False, 1))\n\ndef longestZigZag(root: TreeNode) -> int:\n if root == None:\n return 0\n return max(self.longestZigZagRec(root, True, 0), self.longestZigZagRec(root, False, 0))", "def longestZigZag(root: TreeNode) -> int:\n self.max_zigzag = 0\n\n def dfs(node, is_left, streak):\n if not node:\n return\n self.max_zigzag = max(self.max_zigzag, streak)\n if is_left:\n dfs(node.right, not is_left, streak + 1)\n dfs(node.right, is_left, 0)\n else:\n dfs(node.left, not is_left, streak + 1)\n dfs(node.left, is_left, 0)\n dfs(root, True, 0)\n dfs(root, False, 0)\n return self.max_zigzag", "def longestZigZag(root: TreeNode) -> int:\n if root is None:\n return 0\n self.helper(root)\n l = [root]\n m = 0\n while len(l) != 0:\n node = l.pop()\n if node.left != None:\n l.append(node.left)\n if node.right != None:\n l.append(node.right)\n if max(node.val) > m:\n m = max(node.val)\n return m\n\ndef helper(root):\n if root is None:\n return 0\n self.helper(root.left)\n self.helper(root.right)\n if root.left == None and root.right == None:\n root.val = (0, 0)\n elif root.left != None and root.right == None:\n root.val = (root.left.val[1] + 1, 0)\n elif root.right != None and root.left == None:\n root.val = (0, root.right.val[0] + 1)\n else:\n root.val = (root.left.val[1] + 1, root.right.val[0] + 1)", "def longestZigZag(root: TreeNode) -> int:\n\n def Search(root, left, height):\n if root is None:\n return height\n if left:\n return max(Search(root.left, 1, 0), Search(root.right, 0, height + 1))\n else:\n return max(Search(root.right, 0, 0), Search(root.left, 1, height + 1))\n return max(Search(root.left, 1, 0), Search(root.right, 0, 0))", "def longestZigZag(root: TreeNode) -> int:\n longest = 0\n if not root:\n return longest\n\n def helper(root, level, direction):\n nonlocal longest\n if level > longest:\n longest = level\n if direction:\n if root.left:\n helper(root.left, level + 1, not direction)\n if root.right:\n helper(root.right, 1, direction)\n else:\n if root.right:\n helper(root.right, level + 1, not direction)\n if root.left:\n helper(root.left, 1, direction)\n if root.right:\n helper(root.right, 1, True)\n if root.left:\n helper(root.left, 1, False)\n if not root.left and (not root.right):\n return 0\n return longest", "def longestZigZag(root: TreeNode) -> int:\n self.res = 0\n\n def dfs(node):\n if not node:\n return (-1, -1)\n (_, r) = dfs(node.left)\n (l, _) = dfs(node.right)\n self.res = max(self.res, r + 1, l + 1)\n return (r + 1, l + 1)\n dfs(root)\n return self.res", "def longestZigZag(root: TreeNode) -> int:\n\n def check(root):\n l = 0\n r = 0\n m = 0\n if root.left != None:\n r1 = check(root.left)\n l = r1[1] + 1\n m = max(m, r1[2])\n if root.right != None:\n r2 = check(root.right)\n r = r2[0] + 1\n m = max(m, r2[2])\n return (l, r, max(l, r, m))\n if root == None:\n return 0\n r = check(root)\n return r[2]", "def longestZigZag(root: TreeNode) -> int:\n memo = {}\n ans = [0]\n\n def cur(node: TreeNode):\n if node != None:\n memo[node] = [0, 0]\n if node.left != None:\n cur(node.left)\n memo[node][0] = memo[node.left][1] + 1\n ans[0] = max(ans[0], memo[node][0])\n if node.right != None:\n cur(node.right)\n memo[node][1] = memo[node.right][0] + 1\n ans[0] = max(ans[0], memo[node][1])\n cur(root)\n return ans[0]", "def longestZigZag(root: TreeNode) -> int:\n self.zigzag(root)\n return self.find_longest(root)\n\ndef zigzag(node: TreeNode) -> int:\n if node is None:\n return\n self.zigzag(node.left)\n self.zigzag(node.right)\n if node.left is not None:\n node.left_depth = node.left.right_depth + 1\n else:\n node.left_depth = 0\n if node.right is not None:\n node.right_depth = node.right.left_depth + 1\n else:\n node.right_depth = 0\n\ndef find_longest(node: TreeNode) -> int:\n if node is None:\n return 0\n left_max = self.find_longest(node.left)\n right_max = self.find_longest(node.right)\n return max(left_max, right_max, node.left_depth, node.right_depth)", "def longestZigZag(root: TreeNode) -> int:\n self.res = 0\n self.helper(root, True)\n self.helper(root, False)\n return self.res - 1\n\ndef helper(root, isLeft):\n if not root:\n return 0\n left = self.helper(root.left, True)\n right = self.helper(root.right, False)\n self.res = max(self.res, left + 1, right + 1)\n return right + 1 if isLeft else left + 1", "def longestZigZag(root: TreeNode) -> int:\n self.maxpath = 0\n (l, r) = self.visit(root)\n return self.maxpath\n\ndef visit(root):\n l = 0\n r = 0\n if root.left:\n (ll, lr) = self.visit(root.left)\n l = lr + 1\n if root.right:\n (rl, rr) = self.visit(root.right)\n r = rl + 1\n if max(l, r) > self.maxpath:\n self.maxpath = max(l, r)\n return (l, r)", "def longestZigZag(root: TreeNode) -> int:\n self.max = 0\n\n def dfs(node):\n if not node:\n return (-1, -1)\n (l_dir_left, l_dir_right) = dfs(node.left)\n (r_dir_left, r_dir_right) = dfs(node.right)\n self.max = max(self.max, l_dir_left, l_dir_right + 1, r_dir_left + 1, r_dir_right)\n return (l_dir_right + 1, r_dir_left + 1)\n dfs(root)\n return self.max", "from typing import NamedTuple\n\ndef longestZigZag(root: TreeNode) -> int:\n res = self.zigzag(root)\n return res.max_depth\n\ndef zigzag(node: TreeNode) -> int:\n if node is None:\n return Result(-1, -1, 0)\n left_res = self.zigzag(node.left)\n right_res = self.zigzag(node.right)\n left_depth = left_res.right_depth + 1\n right_depth = right_res.left_depth + 1\n max_depth = max(left_depth, right_depth, left_res.max_depth, right_res.max_depth)\n return Result(left_depth, right_depth, max_depth)", "def longestZigZag(root: TreeNode) -> int:\n self.ret = 0\n self.dfs(root, 0, 0)\n self.dfs(root, 1, 0)\n return self.ret - 1\n\ndef dfs(root, prevright, length):\n if root is None:\n self.ret = max(self.ret, length)\n return\n if prevright:\n self.dfs(root.left, 1 - prevright, length + 1)\n self.dfs(root.right, prevright, 1)\n else:\n self.dfs(root.right, 1 - prevright, length + 1)\n self.dfs(root.left, prevright, 1)\n return", "def longestZigZag(root: TreeNode) -> int:\n check = 0\n count = 0\n self.res = 0\n\n def dfs(node, count, check):\n if node:\n if check == 1:\n dfs(node.left, 0, 1)\n dfs(node.right, count + 1, 2)\n elif check == 2:\n dfs(node.left, count + 1, 1)\n dfs(node.right, 0, 2)\n elif check == 0:\n dfs(node.left, count, 1)\n dfs(node.right, count, 2)\n self.res = max(self.res, count)\n dfs(root, count, check)\n return self.res", "_max = 0\n\ndef preorder(root, lr, cur_len):\n nonlocal _max\n if root == None:\n return\n _max = max(_max, cur_len)\n if lr == 'l':\n self.preorder(root.left, 'l', 1)\n self.preorder(root.right, 'r', cur_len + 1)\n elif lr == 'r':\n self.preorder(root.left, 'l', cur_len + 1)\n self.preorder(root.right, 'r', 1)\n else:\n self.preorder(root.left, 'l', cur_len + 1)\n self.preorder(root.right, 'r', cur_len + 1)\n\ndef longestZigZag(root: TreeNode) -> int:\n nonlocal _max\n _max = 0\n self.preorder(root, None, 0)\n return _max", "def longestZigZag(root: TreeNode) -> int:\n dp = [0]\n\n def f(n, ind):\n if not n:\n dp[ind] = (0, 0)\n else:\n dp.extend([0, 0])\n temp = len(dp)\n f(n.left, temp - 2)\n f(n.right, temp - 1)\n dp[ind] = (dp[temp - 1][1] + 1, dp[temp - 2][0] + 1)\n f(root, 0)\n m = -1\n for i in dp:\n m = max(i[0], i[1], m)\n return m - 1", "def longestZigZag(root: TreeNode) -> int:\n seenSoFar = 0\n\n def longestZigZagUtil(root):\n nonlocal seenSoFar\n if not root:\n return (0, 0)\n (Ll, Lr) = longestZigZagUtil(root.left)\n (Rl, Rr) = longestZigZagUtil(root.right)\n (curL, curR) = (0, 0)\n if root.left:\n curL = 1 + Lr\n seenSoFar = max(seenSoFar, Ll)\n if root.right:\n curR = 1 + Rl\n seenSoFar = max(seenSoFar, Rr)\n return (curL, curR)\n (l, r) = longestZigZagUtil(root)\n return max(l, r, seenSoFar)", "def longestZigZag(root: TreeNode) -> int:\n res = 0\n\n def helper(root, direction):\n nonlocal res\n if not root:\n return 0\n left = helper(root.left, 'left')\n right = helper(root.right, 'right')\n res = max(res, left + 1, right + 1)\n return right + 1 if direction == 'left' else left + 1\n if not root:\n return 0\n helper(root, 'left')\n helper(root, 'right')\n return res - 1", "def solve(root, res, ind):\n if root == None:\n return 0\n l = solve(root.left, res, 0)\n r = solve(root.right, res, 1)\n if ind == 0:\n temp = 1 + r\n elif ind == 1:\n temp = 1 + l\n ans = 1 + max(l, r)\n res[0] = max(res[0], ans)\n return temp\n\ndef longestZigZag(root: TreeNode) -> int:\n if root == None:\n return 0\n if root.left == None and root.right == None:\n return 0\n res1 = [0]\n res2 = [0]\n c1 = solve(root, res1, 0)\n c2 = solve(root, res2, 1)\n return max(res1[0], res2[0]) - 1", "def longestZigZag(root: TreeNode) -> int:\n longest = [0]\n\n def dfs(node, d, c):\n if not node:\n longest[0] = max(longest[0], c)\n return\n if d == 'r':\n dfs(node.left, 'l', c + 1)\n else:\n dfs(node.left, 'l', 0)\n if d == 'l':\n dfs(node.right, 'r', c + 1)\n else:\n dfs(node.right, 'r', 0)\n dfs(root, '', 0)\n return longest[0]", "def longestZigZag(root: TreeNode) -> int:\n self.ans = 0\n\n def helper(node, direction, l):\n if not node:\n return\n self.ans = max(self.ans, l)\n helper((node.left, node.right)[direction], 1 - direction, l + 1)\n helper((node.left, node.right)[1 - direction], direction, 1)\n helper(root, 0, 0)\n helper(root, 1, 0)\n return self.ans", "def longestZigZag(root: TreeNode) -> int:\n\n def solve(root):\n if root:\n solve(root.left)\n solve(root.right)\n if root.left:\n d[root][0] = d[root.left][1] + 1\n if root.right:\n d[root][1] = d[root.right][0] + 1\n self.ans = max(self.ans, max(d[root]))\n return self.ans\n d = defaultdict(lambda : [0, 0])\n self.ans = 0\n solve(root)\n return self.ans", "def longestZigZag(root: TreeNode) -> int:\n if not root:\n return 0\n if not root.left and (not root.right):\n return 0\n\n def dfs(root, flag, count):\n if not root:\n self.res = max(self.res, count - 1)\n return\n if flag == 1:\n dfs(root.left, -1, 1 + count)\n dfs(root.right, 1, 1)\n else:\n dfs(root.right, 1, 1 + count)\n dfs(root.left, -1, 1)\n self.res = 0\n dfs(root, -1, 0)\n return self.res", "def longestZigZag(root: TreeNode) -> int:\n res = collections.namedtuple('res', 'left right total')\n\n def dfs(root):\n if not root:\n return res(-1, -1, -1)\n left = dfs(root.left)\n right = dfs(root.right)\n return res(left.right + 1, right.left + 1, max(left.right + 1, right.left + 1, left.total, right.total))\n return dfs(root).total", "def node_is_on_the_right(node):\n if not node:\n return 0\n continuation = 1 + self.node_is_on_the_left(node.left)\n starts_here = self.node_is_on_the_right(node.right)\n self.m = max(self.m, starts_here)\n return continuation\n\ndef node_is_on_the_left(node):\n if not node:\n return 0\n continuation = 1 + self.node_is_on_the_right(node.right)\n starts_here = self.node_is_on_the_left(node.left)\n self.m = max(self.m, starts_here)\n return continuation\n\ndef longestZigZag(root: TreeNode) -> int:\n self.m = 0\n x = self.node_is_on_the_right(root) - 1\n self.m = max(self.m, x)\n return self.m", "def longestZigZag(root: TreeNode) -> int:\n self.mx = 0\n out = self.traverse(root, 0)\n out = self.traverse(root, 1)\n return self.mx - 1\n\ndef traverse(node, ctype):\n if node is None:\n return (0, 0)\n ll = lr = rl = rr = 0\n if node.left:\n (ll, lr) = self.traverse(node.left, 0)\n if node.right:\n (rl, rr) = self.traverse(node.right, 1)\n best = max(lr, rl) + 1\n self.mx = max(self.mx, best)\n return (1 + lr, 1 + rl)", "from collections import defaultdict\n\ndef longestZigZag(root: TreeNode) -> int:\n levels = [root]\n ret = 0\n dp_r = defaultdict(int)\n dp_l = defaultdict(int)\n while levels:\n nxt = []\n for p in levels:\n if p.left:\n nxt.append(p.left)\n dp_l[p.left] = dp_r[p] + 1\n ret = max(ret, dp_l[p.left])\n if p.right:\n nxt.append(p.right)\n dp_r[p.right] = dp_l[p] + 1\n ret = max(ret, dp_r[p.right])\n levels = nxt\n return ret", "def longestZigZag(root: TreeNode) -> int:\n if root == None:\n return 0\n max_zigzag = 0\n zigzag = 0\n stack = [(root, None, 0)]\n while stack:\n node = stack[-1][0]\n prev_dir = stack[-1][1]\n max_up_to_node = stack[-1][2]\n del stack[-1]\n if max_up_to_node > max_zigzag:\n max_zigzag = max_up_to_node\n if prev_dir == None:\n if node.right != None:\n stack.append((node.right, 'R', max_up_to_node + 1))\n if node.left != None:\n stack.append((node.left, 'L', max_up_to_node + 1))\n else:\n if prev_dir == 'R':\n if node.right != None:\n stack.append((node.right, 'R', 1))\n if node.left != None:\n stack.append((node.left, 'L', max_up_to_node + 1))\n if prev_dir == 'L':\n if node.right != None:\n stack.append((node.right, 'R', max_up_to_node + 1))\n if node.left != None:\n stack.append((node.left, 'L', 1))\n return max_zigzag", "def longestZigZag(root: TreeNode) -> int:\n\n def dfs(root):\n if root is None:\n return (0, [0, 0])\n if root.left is None and root.right is None:\n return (0, [0, 0])\n (left_zigzag, [_, right]) = dfs(root.left)\n (right_zigzag, [left, _]) = dfs(root.right)\n zigzag = max(left_zigzag, right_zigzag)\n if root.right:\n right_zigzag = 1 + left\n zigzag = max(zigzag, right_zigzag)\n else:\n right_zigzag = 0\n if root.left:\n left_zigzag = 1 + right\n zigzag = max(zigzag, left_zigzag)\n else:\n left_zigzag = 0\n return (zigzag, [left_zigzag, right_zigzag])\n return dfs(root)[0]", "def longestZigZag(root: TreeNode) -> int:\n self.max_ = 0\n\n def preorder(root, count, dir_):\n self.max_ = max(self.max_, count)\n if root.left:\n if dir_ == 1 or dir_ == -1:\n preorder(root.left, count + 1, 0)\n else:\n preorder(root.left, 1, 0)\n if root.right:\n if dir_ == 0 or dir_ == -1:\n preorder(root.right, count + 1, 1)\n else:\n preorder(root.right, 1, 1)\n preorder(root, 0, -1)\n return self.max_", "def longestZigZag(root: TreeNode) -> int:\n Max = [0]\n vl = set()\n vr = set()\n\n def path(node, l, d):\n if node == None:\n return l\n if d == 1:\n vr.add(node)\n return path(node.left, l + 1, 0)\n else:\n vl.add(node)\n return path(node.right, l + 1, 1)\n\n def dfs(node):\n if node == None:\n return\n if node not in vl:\n Max[0] = max(Max[0], path(node, -1, 0))\n if node not in vr:\n Max[0] = max(Max[0], path(node, -1, 1))\n dfs(node.left)\n dfs(node.right)\n dfs(root)\n return Max[0]", "def __init__():\n self.memo = {}\n\ndef h(node: TreeNode, left: bool) -> int:\n if not node:\n return 0\n if (node, left) not in self.memo:\n ret = 0\n if left and node.left is not None:\n ret = 1 + self.h(node.left, False)\n elif not left and node.right is not None:\n ret = 1 + self.h(node.right, True)\n self.memo[node, left] = ret\n return self.memo[node, left]\n\ndef longestZigZag(root: TreeNode) -> int:\n if not root:\n return 0\n ret = [0]\n if root.left is not None:\n ret.extend([1 + self.h(root.left, False), self.longestZigZag(root.left)])\n if root.right is not None:\n ret.extend([1 + self.h(root.right, True), self.longestZigZag(root.right)])\n return max(ret)", "def __init__():\n self.lmemo = {}\n self.rmemo = {}\n\ndef longestZigZag(root: TreeNode) -> int:\n\n def lzz(root, mx):\n if root is not None:\n lzz(root.left, mx)\n lzz(root.right, mx)\n mx[0] = max(mx[0], llzz(root), rlzz(root))\n return mx\n\n def llzz(root):\n if root not in self.lmemo:\n self.lmemo[root] = 1 + rlzz(root.left)\n return self.lmemo[root]\n\n def rlzz(root):\n if root not in self.rmemo:\n self.rmemo[root] = 1 + llzz(root.right)\n return self.rmemo[root]\n self.lmemo[None] = self.rmemo[None] = 0\n return lzz(root, [float('-inf')])[0] - 1", "def longestZigZag(root: TreeNode) -> int:\n\n def helper(root):\n if not root:\n return (-1, -1, -1)\n if not root.left and (not root.right):\n return (0, 0, 0)\n else:\n (l1, l2, l3) = helper(root.left)\n (r1, r2, r3) = helper(root.right)\n return (l3 + 1, max(l3 + 1, r1 + 1, l2, r2), r1 + 1)\n return helper(root)[1]", "def longestZigZag(root: TreeNode) -> int:\n if root is None:\n return 0\n self.sol = 0\n\n def recursive_long_zigzag(node):\n if node.left is None and node.right is None:\n return (0, 0)\n max_left = 0\n max_right = 0\n if node.left:\n (_, left_s_right) = recursive_long_zigzag(node.left)\n max_left = left_s_right + 1\n self.sol = max(self.sol, max_left)\n if node.right:\n (right_s_left, _) = recursive_long_zigzag(node.right)\n max_right = right_s_left + 1\n self.sol = max(self.sol, max_right)\n return (max_left, max_right)\n recursive_long_zigzag(root)\n return self.sol", "def __init__():\n self.max_cnt = 0\n\ndef longestZigZag(root: TreeNode) -> int:\n self.dfs(root, True, 0)\n self.dfs(root, False, 0)\n return self.max_cnt\n\ndef dfs(root, isLeft, cnt):\n if root is None:\n return\n self.max_cnt = max(self.max_cnt, cnt)\n if isLeft:\n self.dfs(root.left, False, cnt + 1)\n self.dfs(root.right, True, 1)\n else:\n self.dfs(root.right, True, cnt + 1)\n self.dfs(root.left, False, 1)", "def longestZigZag(root: TreeNode) -> int:\n ans = 0\n nodes = [root]\n self.dp = {}\n while len(nodes) != 0:\n tmp = []\n for node in nodes:\n if node.left is not None:\n tmp.append(node.left)\n if node.right is not None:\n tmp.append(node.right)\n ans = max(ans, self.helper(node, 1))\n ans = max(ans, self.helper(node, 0))\n nodes = tmp\n return ans - 1\n\ndef helper(node, status):\n if node is None:\n return 0\n if (node, status) in self.dp:\n return self.dp[node, status]\n if status == 1:\n ans = self.helper(node.right, 0)\n else:\n ans = self.helper(node.left, 1)\n self.dp[node, status] = 1 + ans\n return 1 + ans", "def longestZigZag(root: TreeNode) -> int:\n memo = dict()\n\n def zig_zag_len(node, direction):\n if not node:\n return -1\n if (node, direction) in memo:\n return memo[node, direction]\n if direction == 'L':\n memo[node, direction] = 1 + zig_zag_len(node.right, 'R')\n elif direction == 'R':\n memo[node, direction] = 1 + zig_zag_len(node.left, 'L')\n else:\n memo[node, direction] = max(1 + zig_zag_len(node.right, 'R'), 1 + zig_zag_len(node.left, 'L'), zig_zag_len(node.right, 'N'), zig_zag_len(node.left, 'N'))\n return memo[node, direction]\n return zig_zag_len(root, 'N')", "def longestZigZag(root: TreeNode) -> int:\n\n def zigzag(node, mz):\n if not node:\n return (-1, -1)\n (l1, r1) = zigzag(node.left, mz)\n (l2, r2) = zigzag(node.right, mz)\n mz[0] = max(mz[0], r1 + 1, l2 + 1)\n return (r1 + 1, l2 + 1)\n maxzigzag = [0]\n zigzag(root, maxzigzag)\n zigzag(root, maxzigzag)\n return maxzigzag[0]", "def run(node, side, count, memo):\n if not node:\n return count\n if node in memo:\n if memo[node][side] > -1:\n return memo[node][side]\n memo[node] = [-1, -1, -1]\n if side == 0:\n result = self.run(node.right, 1, count + 1, memo)\n elif side == 1:\n result = self.run(node.left, 0, count + 1, memo)\n else:\n using = max(self.run(node.right, 1, 1, memo), self.run(node.left, 0, 1, memo))\n notUsing = max(self.run(node.right, -1, 0, memo), self.run(node.left, -1, 0, memo))\n result = max(using, notUsing)\n memo[node][side] = result\n return result\n\ndef longestZigZag(root: TreeNode) -> int:\n if not root:\n return 0\n return self.run(root, -1, 0, {}) - 1", "def longestZigZag(root: TreeNode) -> int:\n nodes = self.bfs(root)\n self.dp = {node: [False, False] for node in nodes}\n ans = 0\n for x in range(len(nodes)):\n ans = max(ans, self.recur(0, nodes[x], -1), self.recur(1, nodes[x], -1))\n return ans\n\ndef bfs(node):\n q = [node]\n arr = []\n while q:\n r = q.pop()\n arr.append(r)\n if r.left:\n q.append(r.left)\n if r.right:\n q.append(r.right)\n return arr\n\ndef recur(p, node, c):\n if not node:\n return c\n if self.dp[node][p] != False:\n return self.dp[node][p]\n if p == 0:\n self.dp[node][p] = self.recur(p ^ 1, node.left, c + 1)\n return self.dp[node][p]\n else:\n self.dp[node][p] = self.recur(p ^ 1, node.right, c + 1)\n return self.dp[node][p]"], "starter_code": "def __init__(val=0, left=None, right=None):\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Binary Tree", "Tree", "Dynamic Programming", "Depth-First Search"], "name": null, "source": "leetcode", "tags": ["Tree algorithms", "Dynamic programming", "Graph traversal"], "skill_types": ["Dynamic programming"], "url": "https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "__init__", "task_id": "TACO_lite/390", "example": [[], []]} +{"requirement": "Some people(n) are standing in a queue. A selection process follows a rule where people standing on even positions are selected. Of the selected people a queue is formed and again out of these only people on even position are selected. This continues until we are left with one person. Find out the position of that person in the original queue.\nExample 1:\nInput: n = 5\nOutput: 4 \nExplanation: 1,2,3,4,5 -> 2,4 -> 4.\nExample 2:\nInput: n = 9\nOutput: 8\nExplanation: 1,2,3,4,5,6,7,8,9\n->2,4,6,8 -> 4,8 -> 8. \nYour Task: \nYou dont need to read input or print anything. Complete the function nthPosition() which takes n as input parameter and returns the position(original queue) of that person who is left.\nExpected Time Complexity: O(logn)\nExpected Auxiliary Space: O(1)\nConstraints:\n1<= n <=10^{8}", "solutions": ["def nthposition(n):\n res = 0\n for i in range(n, 0, -1):\n if i & i - 1 == 0:\n res = i\n break\n return res", "def nthposition(n):\n ans = 0\n while n > 1:\n ans += 1\n n //= 2\n return pow(2, ans)", "def nthposition(n):\n a = []\n for i in range(2, n + 1, 2):\n a.append(i)\n while len(a) != 1:\n t = []\n for i in range(1, len(a), 2):\n t.append(a[i])\n a[:] = t[:]\n return a[0]", "def nthposition(n):\n i = 1\n return self.find(n, i)\n\ndef find(n, i):\n if n == 1:\n return n * i\n return self.find(n // 2, i * 2)", "import math\n\ndef nthposition(n):\n x = int(math.log2(n))\n return 2 ** x", "def nthposition(n):\n\n def help(count, n):\n if n <= 1:\n return 2 ** count\n count += 1\n return help(count, n // 2)\n return help(0, n)", "def nthposition(n):\n arr = [i for i in range(2, n + 1, 2)]\n while len(arr) > 1:\n temp = []\n for i in range(1, len(arr), 2):\n temp.append(arr[i])\n arr = temp\n return arr[0]", "def nthposition(n):\n if n == 1:\n return 1\n return self.nthposition(n // 2) * 2", "def nthposition(n):\n for i in range(33):\n if 2 ** i > n:\n return 2 ** (i - 1)", "from math import log\n\ndef nthposition(n):\n res = int(log(n, 2))\n return int(pow(2, res))", "def solve(i, n):\n if 2 ** i > n:\n return 2 ** (i - 1)\n return self.solve(i + 1, n)\n\ndef nthposition(n):\n return self.solve(0, n)", "def nthposition(n):\n if n == 1:\n return 0\n res = 1\n while n // 2 != 1:\n n = n // 2\n res *= 2\n return res * 2", "def nthposition(n):\n if n == 1:\n return int(n)\n p = 1\n while p < n:\n p *= 2\n if p == n:\n return int(p)\n return int(p / 2)", "def nthposition(n):\n i = 0\n while n >= 2 ** i:\n i += 1\n return 2 ** i if 2 ** i <= n else 2 ** (i - 1)", "def solve(n, i):\n if n < i:\n return i // 2\n return self.solve(n, i * 2)\n\ndef nthposition(n):\n return self.solve(n, 2)", "def solution(arr):\n if len(arr) == 1:\n return arr\n return self.solution(arr[1::2])\n\ndef nthposition(n):\n lst = list(range(1, n + 1))\n x = self.solution(lst)\n return x[-1]", "def nthposition(n):\n l = []\n for i in range(1, n + 1):\n l.append(i)\n p = self.even(l)\n return p\n\ndef even(l):\n if len(l) == 1:\n return l[0]\n return self.even(l[1::2])", "import math\n\ndef nthposition(n):\n largestPower = int(math.log(n, 2))\n return int(math.pow(2, largestPower))", "def nthposition(x):\n x |= x >> 1\n x |= x >> 2\n x |= x >> 4\n x |= x >> 8\n x |= x >> 16\n return x ^ x >> 1", "def nthposition(n):\n\n def f(arr):\n if len(arr) == 1:\n return arr[0]\n return f(arr[1::2])\n l = []\n for i in range(1, n + 1):\n l.append(i)\n return f(l)", "def nthposition(n):\n\n def f(arr):\n if len(arr) == 1:\n return arr[0]\n return f(arr[1::2])\n return f(list(range(1, n + 1)))", "def nthposition(n):\n for x in range(n, 0, -1):\n if x & x - 1 == 0:\n return x", "def nthposition(n):\n\n def g(a, count):\n if a == 1:\n return count\n a = int(a / 2)\n count += 1\n return g(a, count)\n return pow(2, g(n, 0))", "import math\n\ndef nthposition(n):\n logVal = math.log2(n)\n out = 2 ** int(logVal)\n return out", "def nthposition(n):\n\n def fun(ans, n, k):\n if n == 1:\n return ans\n if n % 2 == 0:\n ans = ans\n if n % 2 != 0:\n ans = ans - k\n k = k * 2\n return fun(ans, n // 2, k)\n k = 1\n ans = n\n return fun(ans, n, k)", "def cullu(n):\n if n == 1:\n return 1\n c = 1 + cullu(n // 2)\n return c\n\ndef nthposition(n):\n c = cullu(n)\n return 2 ** (c - 1)", "def nthposition(n):\n count = 0\n while n != 1:\n n = n // 2\n count += 1\n return 2 ** count", "def nthposition(n):\n i = 0\n l = []\n while 1:\n if pow(2, i) <= n:\n l.append(pow(2, i))\n else:\n break\n i += 1\n return l[-1]", "def nthposition(n):\n i = 1\n while i * 2 <= n:\n i *= 2\n return i", "def nthposition(n):\n (i, c) = (0, 0)\n while c <= n:\n x = c\n c = pow(2, i)\n if c > n:\n break\n i += 1\n return x", "def nthposition(n):\n temp = n\n c = 1\n while n > 1:\n if n % 2 == 0:\n n = n - n // 2\n else:\n temp = temp - c\n n = temp\n return temp", "def nthposition(n):\n l = []\n for i in range(1, n // 2):\n if 2 ** i == n:\n return n\n break\n elif 2 ** i > n:\n return 2 ** (i - 1)\n break", "def nthposition(n):\n c = 0\n while n:\n c += 1\n n = n >> 1\n return 2 ** (c - 1)", "def nthposition(n):\n import math as m\n s = int(m.sqrt(n)) + 1\n i = 0\n while 2 ** i <= n:\n i += 1\n return 2 ** (i - 1)", "import math\n\ndef nthposition(n):\n return 2 ** math.floor(math.log2(n))", "def nthposition(n):\n\n def helper(i, n):\n if i > n:\n return int(i / 2)\n else:\n i = i * 2\n return helper(i, n)\n return helper(1, n)", "def nthposition(n):\n if n == 1:\n return 1\n else:\n return self.nthposition(n // 2) * 2", "def nthposition(n):\n if n == 1:\n return 1\n return self.nthposition(int(n / 2)) * 2", "def nthposition(n):\n import math\n ans = math.log(n) / math.log(2)\n return math.floor(math.pow(2, math.floor(ans)))", "def nthposition(n):\n l = [i for i in range(2, n + 1, 2)]\n\n def solve(lst):\n if len(lst) <= 1:\n return lst\n nl = []\n for i in range(1, len(lst), 2):\n nl.append(lst[i])\n return solve(nl)\n return solve(l)[0]", "def nthposition(n):\n if n == 1:\n return 1\n arr = [i for i in range(2, n + 1, 2)]\n\n def pos(arr):\n if len(arr) == 1:\n return arr[0]\n res = [arr[i] for i in range(1, len(arr), 2)]\n return pos(res)\n return pos(arr)", "def nthposition(n):\n\n def position(i, n):\n if i > n:\n return i // 2\n i = i * 2\n return position(i, n)\n return position(1, n)", "import math\n\ndef nthposition(n):\n return 1 << int(math.log2(n))", "def nthposition(n):\n if n < 3:\n return n\n else:\n return 2 * self.nthposition(n // 2)", "def nthposition(n):\n list1 = [i for i in range(1, n + 1, 1)]\n new = []\n while len(list1) > 1:\n new = [list1[i] for i in range(1, len(list1), 2)]\n list1[:] = new[:]\n return list1[0]", "import math\n\ndef nthposition(n):\n x = int(math.log(n) / math.log(2))\n y = 2 ** x\n return y", "import sys\n\ndef nthposition(n):\n if n < 1:\n return 0\n res = 1\n for i in range(8 * sys.getsizeof(n)):\n curr = 1 << i\n if curr > n:\n break\n res = curr\n return res", "import math\n\ndef nthposition(n):\n if n == 1:\n return 1\n ans = self.nthposition(n // 2)\n return 2 * ans", "def nthposition(n):\n if n == 1:\n return 1\n nth_pos = 2\n while n >= nth_pos:\n nth_pos *= 2\n return nth_pos // 2", "import math\n\ndef nthposition(n):\n c = int(math.log(n, 2))\n d = int(pow(2, c))\n return d", "def __init__():\n self.k = 1\n\ndef nthposition(n):\n if n == 1:\n return self.k\n self.k = self.k * 2\n return self.nthposition(n // 2)", "def nthposition(n):\n s = bin(n)\n bits = len(s) - 2\n num = '1'\n for i in range(bits - 1):\n num += '0'\n return n & int(num)", "def nthposition(n):\n ans = 1\n while n != 1:\n ans = 2 * ans\n n //= 2\n return ans", "def nthposition(n):\n l = 2\n if n & 1:\n r = n - 1\n else:\n r = n\n diff = r - l\n i = 1\n while diff > 0:\n i *= 2\n l = l + i\n r = r - i\n diff = r - l\n return l", "def nthposition(n):\n list1 = [j for j in range(1, n + 1)]\n\n def ans(list1):\n if len(list1) == 1:\n return list1[0]\n list1 = [list1[j] for j in range(1, len(list1), 2)]\n return ans(list1)\n return ans(list1)", "def nthposition(n):\n x = str(bin(n))[2:]\n ans = pow(2, len(x) - 1)\n return ans", "def nthposition(n):\n l = []\n for i in range(n):\n l.append(i + 1)\n while len(l) != 1:\n b = l[1::2]\n l = b[:]\n return l[0]", "def nthposition(n):\n return 1 << n.bit_length() - 1", "import math\n\ndef nthposition(n):\n if n == 1:\n return 1\n n = int(math.log(n, 2))\n return pow(2, n)", "import math\n\ndef nthposition(n):\n p = int(math.log(n, 2))\n return int(pow(2, p))\n return even(n)", "def nthposition(n):\n if n == 1:\n return 1\n elif n == 2:\n return 2\n else:\n start = 2\n while start <= n:\n if start * 2 <= n:\n start = start * 2\n else:\n return start", "def nthposition(n):\n if n == 1:\n return n\n ans = self.nthposition(n // 2)\n return 2 * ans"], "starter_code": "def nthposition (n):\n", "input_output": {"inputs": ["n = 5", "n = 9"], "outputs": ["4", "8"]}, "difficulty": "EASY", "raw_tags": ["Recursion", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics", "Complete search"], "skill_types": ["Complete search"], "url": "https://practice.geeksforgeeks.org/problems/finding-position2223/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(logn)", "entry_point": "nthposition", "task_id": "TACO_lite/354", "example": [[[5], [9]], ["4", "8"]]} +{"requirement": "Given an array of size n, find the majority element. The majority element is the element that appears more than \u230a n/2 \u230b times.\n\nYou may assume that the array is non-empty and the majority element always exist in the array.\n\nExample 1:\n\n\nInput: [3,2,3]\nOutput: 3\n\nExample 2:\n\n\nInput: [2,2,1,1,1,2,2]\nOutput: 2", "solutions": ["def majorityelement(nums):\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 find = set(nums[0:n // 2]) & set(nums[n // 2:])\n for i in find:\n if nums.count(i) > n // 2:\n return i", "def majorityelement(nums):\n order = dict()\n if len(nums) > 1:\n for i in range(len(nums)):\n if nums[i] in list(order.keys()):\n order[nums[i]] += 1\n if order[nums[i]] > len(nums) // 2:\n return nums[i]\n else:\n order[nums[i]] = 1\n else:\n return nums[0]", "def majorityelement(nums):\n l = len(nums)\n for n in set(nums):\n if nums.count(n) > l / 2:\n return n", "def majorityelement(nums):\n count = 0\n candidate = None\n for num in nums:\n if count == 0:\n candidate = num\n count += 1 if num == candidate else -1\n return candidate", "def majorityelement(nums):\n map = {}\n for n in nums:\n if n not in map:\n map[n] = 0\n map[n] += 1\n (max, occ) = (-1, -1)\n for (num, count) in map.items():\n if count > occ:\n (max, occ) = (num, count)\n return max", "def majorityelement(nums):\n a = sorted(nums)\n return a[int(len(a) / 2)]", "def majorityelement(nums):\n if not nums:\n return ''\n current = nums[0]\n counter = 1\n for i in range(1, len(nums)):\n if counter == 0:\n current = nums[i]\n counter = 1\n elif nums[i] == current:\n counter += 1\n else:\n counter -= 1\n return current", "def majorityelement(nums):\n table = {}\n for num in nums:\n if num not in table:\n table[num] = 1\n else:\n table[num] += 1\n sorting_tutple = [(value, key) for (key, value) in list(table.items())]\n sorting_tutple.sort(reverse=True)\n return sorting_tutple[0][1]", "def majorityelement(nums):\n d = {}\n maxV = float('-inf')\n maxX = -1\n n = len(nums) // 2\n for x in nums:\n if x not in d:\n d[x] = 1\n else:\n d[x] += 1\n if d[x] > maxV:\n maxV = d[x]\n maxX = x\n if maxV > n:\n break\n return maxX", "def majorityelement(nums):\n hist = {}\n for num in nums:\n if num not in hist:\n hist[num] = 0\n hist[num] += 1\n if hist[num] > len(nums) // 2:\n return num", "def majorityelement(nums):\n s = {}\n for i in range(len(nums)):\n s[nums[i]] = s.get(nums[i], 0) + 1\n for num in nums:\n if s[num] > len(nums) // 2:\n return num", "def majorityelement(nums):\n ele = {}\n for i in nums:\n if i in ele:\n ele[i] += 1\n else:\n ele[i] = 1\n if ele[i] > len(nums) / 2:\n return int(i)", "def majorityelement(nums):\n count = {}\n for i in nums:\n if i in count.keys():\n count[i] += 1\n else:\n count[i] = 1\n ans = count[nums[0]]\n res = nums[0]\n for x in count.keys():\n if count[x] > ans:\n ans = count[x]\n res = x\n return res"], "starter_code": "def majorityelement(nums: List[int]) -> int:\n", "input_output": {"fn_name": "majorityElement", "inputs": [[[3, 2, 3]]], "outputs": [3]}, "difficulty": "EASY", "raw_tags": ["Divide and Conquer", "Array", "Counting", "Sorting", "Hash Table"], "name": null, "source": "leetcode", "tags": ["Sorting", "Data structures", "Mathematics", "Divide and conquer"], "skill_types": ["Sorting", "Data structures"], "url": "https://leetcode.com/problems/majority-element/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "majorityelement", "task_id": "TACO_lite/411", "example": [[[[3, 2, 3]], [[2, 2, 1, 1, 1, 2, 2]]], ["3", "2"]]} +{"requirement": "Given an array A of integers, return true if and only if it is a valid mountain array.\nRecall that A is a mountain array if and only if:\n\nA.length >= 3\nThere exists some i with\u00a00 < i\u00a0< A.length - 1\u00a0such that:\n \nA[0] < A[1] < ... A[i-1] < A[i] \nA[i] > A[i+1] > ... > A[A.length - 1]\n\n\n\n\n\n\u00a0\nExample 1:\nInput: [2,1]\nOutput: false\n\n\nExample 2:\nInput: [3,5,5]\nOutput: false\n\n\nExample 3:\nInput: [0,3,2,1]\nOutput: true\n\n\n\u00a0\nNote:\n\n0 <= A.length <= 10000\n0 <= A[i] <= 10000", "solutions": ["def validmountainarray(A: List[int]) -> bool:\n if len(A) <= 2:\n return False\n else:\n if A[1] < A[0]:\n return False\n is_up = True\n curr = A[0]\n for n in A[1:]:\n if n == curr:\n return False\n if n < curr:\n is_up = False\n curr = n\n if n > curr:\n if is_up:\n curr = n\n else:\n return False\n return not is_up", "def validmountainarray(A: List[int]) -> bool:\n isIncreasing = True\n i = 1\n n = len(A)\n if n < 3:\n return False\n if A[1] <= A[0]:\n return False\n while i < n:\n if isIncreasing and A[i - 1] < A[i]:\n i += 1\n continue\n elif A[i] < A[i - 1]:\n isIncreasing = False\n i += 1\n continue\n else:\n return False\n if A[-1] >= A[-2]:\n return False\n return True", "def validmountainarray(A: List[int]) -> bool:\n arr = A\n if len(arr) < 3:\n return False\n if arr[0] > arr[1]:\n return False\n if arr[-1] > arr[-2]:\n return False\n peek = None\n for i in range(1, len(arr) - 1):\n if arr[i] > arr[i + 1]:\n peek = i\n if peek and arr[i] < arr[i + 1]:\n return False\n if arr[i] == arr[i + 1] or arr[i] == arr[i - 1]:\n return False\n return True", "def validmountainarray(A: List[int]) -> bool:\n dec = 0\n n = len(A)\n if n < 3:\n return False\n else:\n for i in range(n):\n if i != 0 and A[i] == A[i - 1]:\n return False\n elif i == 0 and A[i] > A[i + 1]:\n return False\n elif dec == 1 and A[i] > A[i - 1]:\n return False\n elif i != 0 and dec == 0 and (A[i] < A[i - 1]):\n dec = 1\n elif i == n - 1 and dec == 0:\n return False\n return True", "def __init__():\n self.f = True\n\ndef impl(arr, i, incr):\n self.f = incr\n if i + 1 >= len(arr):\n return True\n if arr[i + 1] > arr[i] and (not incr):\n return False\n elif arr[i + 1] < arr[i] and incr:\n incr = False\n elif arr[i + 1] == arr[i]:\n return False\n return self.impl(arr, i + 1, incr)\n\ndef validmountainarray(A) -> bool:\n if A == None or len(A) <= 2:\n return False\n if A[1] < A[0]:\n return False\n self.f = True\n result = self.impl(A, 0, True)\n if self.f:\n return False\n return result", "def validmountainarray(A: List[int]) -> bool:\n i = 1\n N = len(A)\n if N < 3:\n return False\n while i < N and A[i] > A[i - 1]:\n i += 1\n if i == 1 or i == N:\n return False\n while i < N and A[i] < A[i - 1]:\n i += 1\n return i == N", "def validmountainarray(A: List[int]) -> bool:\n if len(A) <= 2:\n return False\n else:\n t = 0\n (c1, c2) = (0, 0)\n for i in range(1, len(A) - 1):\n if A[i] == A[i + 1]:\n return False\n break\n elif A[i - 1] < A[i] < A[i + 1] or A[i - 1] > A[i] > A[i + 1] or A[i - 1] < A[i] > A[i + 1]:\n t += 1\n if A[i - 1] < A[i] < A[i + 1]:\n c1 += 1\n if A[i - 1] > A[i] > A[i + 1]:\n c2 += 1\n if t == len(A) - 2 and c1 < len(A) - 2 and (c2 < len(A) - 2):\n return True\n else:\n return False", "def validmountainarray(A: List[int]) -> bool:\n if len(A) < 3:\n return False\n nprev = A[0]\n for i in range(1, len(A)):\n if A[i] <= nprev:\n nprev = A[i - 1]\n start = i\n break\n nprev = A[i]\n if i == len(A) - 1:\n return False\n for i in range(start, len(A)):\n if A[i] >= nprev:\n return False\n nprev = A[i]\n if start == 1 and i == len(A) - 1:\n return False\n return True", "def validmountainarray(A: List[int]) -> bool:\n if len(A) < 3:\n return False\n maxIndex = A.index(max(A))\n if maxIndex == len(A) - 1 or maxIndex == 0:\n return False\n for i in range(maxIndex):\n if A[i] >= A[i + 1]:\n return False\n for i in range(maxIndex, len(A) - 1):\n if A[i] <= A[i + 1]:\n return False\n return True", "def validmountainarray(arr: List[int]) -> bool:\n i = 0\n l = len(arr)\n while i + 1 < l and arr[i] < arr[i + 1]:\n i += 1\n if i == 0 or i == l - 1:\n return False\n while i + 1 < l and arr[i] > arr[i + 1]:\n i += 1\n return i == l - 1", "def validmountainarray(A):\n N = len(A)\n i = 0\n while i + 1 < N and A[i] < A[i + 1]:\n i += 1\n if i == 0 or i == N - 1:\n return False\n while i + 1 < N and A[i] > A[i + 1]:\n i += 1\n return i == N - 1", "def validmountainarray(A: List[int]) -> bool:\n if len(A) <= 2:\n return False\n i = 0\n N = len(A)\n while i < N and i + 1 < N and (A[i] < A[i + 1]):\n i += 1\n if i == 0 or i == N - 1:\n return False\n while i < N and i + 1 < N and (A[i] > A[i + 1]):\n i += 1\n if i == N - 1:\n return True\n return False", "def validmountainarray(A: List[int]) -> bool:\n m = (0, 0)\n for i in range(0, len(A)):\n if A[i] > m[1]:\n m = (i, A[i])\n if m[0] == 0 or m[0] == len(A) - 1:\n return False\n for i in range(0, m[0] - 1):\n if A[i] >= A[i + 1]:\n return False\n for i in range(m[0], len(A) - 1):\n if A[i] <= A[i + 1]:\n return False\n return True", "def walkUp(A: List[int]) -> int:\n for (i, step) in enumerate(A[:-1]):\n if A[i] >= A[i + 1]:\n return i\n return len(A)\n\ndef walkDown(A: List[int], top: int) -> bool:\n for (i, step) in enumerate(A[top:-1], start=top):\n if A[i] <= A[i + 1]:\n return False\n return True\n\ndef validmountainarray(A: List[int]) -> bool:\n top = self.walkUp(A)\n if top == 0 or top == len(A):\n return False\n return self.walkDown(A, top)", "def validmountainarray(A: List[int]) -> bool:\n if len(A) < 3:\n return False\n switch = 0\n if A[0] > A[1]:\n return False\n for i in range(2, len(A)):\n if A[i] == A[i - 1]:\n return False\n if switch == 0 and A[i] < A[i - 1]:\n switch = 1\n elif switch == 1 and A[i] > A[i - 1]:\n return False\n if switch == 0:\n return False\n return True", "def validmountainarray(A: List[int]) -> bool:\n if len(A) < 3:\n return False\n N = len(A) - 1\n reached = False\n for i in range(N):\n if A[i] == A[i + 1]:\n return False\n if not reached:\n if A[i] > A[i + 1]:\n if i == 0:\n return False\n reached = True\n elif A[i] < A[i + 1]:\n return False\n return reached", "def validmountainarray(A: List[int]) -> bool:\n if len(A) >= 3:\n peak = max(A)\n if A.count(peak) == 1:\n peakInd = A.index(peak)\n incArr = A[:peakInd]\n decArr = A[peakInd + 1:]\n if len(incArr) > 0 and len(decArr) > 0:\n for i in range(1, len(incArr)):\n if incArr[i] <= incArr[i - 1]:\n return False\n for d in range(0, len(decArr) - 1):\n if decArr[d] <= decArr[d + 1]:\n return False\n return True\n else:\n return False\n else:\n return False\n else:\n return False", "def validmountainarray(A: List[int]) -> bool:\n strict_inc = False\n strict_dec = False\n if len(A) > 2:\n for i in range(1, len(A)):\n if A[i] > A[i - 1]:\n if strict_dec:\n return False\n strict_inc = True\n elif A[i] < A[i - 1]:\n strict_dec = True\n else:\n return False\n if strict_inc and strict_dec:\n return True\n else:\n return False\n else:\n return False", "def validmountainarray(A: List[int]) -> bool:\n (i, j) = (0, len(A) - 1)\n while i < j:\n if A[i] < A[i + 1]:\n i += 1\n if A[j] < A[j - 1]:\n j -= 1\n elif i + 1 >= len(A) or A[i] >= A[i + 1]:\n break\n return i == j and 0 < i < len(A) - 1", "def validmountainarray(A: List[int]) -> bool:\n if len(A) < 3:\n return False\n diffs = [A[i + 1] - A[i] for i in range(len(A) - 1)]\n if 0 in diffs or diffs[0] < 0:\n return False\n peak = False\n for i in range(len(diffs) - 1):\n if diffs[i + 1] / abs(diffs[i + 1]) != diffs[i] / abs(diffs[i]):\n if peak == False:\n peak = True\n else:\n return False\n return peak", "def validmountainarray(A: List[int]) -> bool:\n if len(A) < 3:\n return False\n for i in range(len(A) - 1):\n if A[i] >= A[i + 1]:\n break\n for j in range(-1, -len(A), -1):\n if A[j] >= A[j - 1]:\n break\n return i == len(A) + j", "def validmountainarray(A: List[int]) -> bool:\n n = len(A)\n if n < 3:\n return False\n changes = 0\n is_increasing = False\n is_decreasing = False\n for i in range(0, n - 1):\n if changes == 0:\n if A[i] > A[i + 1]:\n changes += 1\n is_decreasing = True\n elif A[i] == A[i + 1]:\n changes += 1\n else:\n is_increasing = True\n elif changes == 1:\n if A[i] <= A[i + 1]:\n changes += 1\n else:\n is_decreasing = True\n else:\n return False\n return changes < 2 and is_decreasing and is_increasing", "def validmountainarray(A: List[int]) -> bool:\n arr = A\n i = 1\n while i < len(arr):\n if arr[i - 1] < arr[i]:\n i += 1\n else:\n break\n if i == 1 or i == len(arr):\n return False\n while i < len(arr):\n if arr[i - 1] > arr[i]:\n i += 1\n else:\n return False\n return True", "def validmountainarray(A: List[int]) -> bool:\n if len(A) < 3:\n return False\n up = True\n for i in range(1, len(A)):\n if A[i] == A[i - 1]:\n return False\n if up:\n if A[i] < A[i - 1]:\n if i == 1:\n return False\n up = False\n elif A[i] > A[i - 1]:\n return False\n return not up", "def validmountainarray(A: List[int]) -> bool:\n n = len(A)\n if n < 3:\n return False\n i = 0\n while i < n - 1 and A[i] < A[i + 1]:\n i += 1\n if i == 0 or i == n - 1:\n return False\n while i < n - 1 and A[i] > A[i + 1]:\n i += 1\n if i != n - 1:\n return False\n return True", "def validmountainarray(A: List[int]) -> bool:\n passedPeak = False\n if len(A) <= 2 or A[0] > A[1]:\n return False\n for i in range(len(A) - 1):\n if A[i] == A[i + 1]:\n return False\n if passedPeak == True and A[i] < A[i + 1]:\n return False\n if passedPeak == False and A[i] > A[i + 1]:\n passedPeak = True\n if passedPeak:\n return True\n else:\n return False", "def validmountainarray(A: List[int]) -> bool:\n climb = True\n cs = 0\n fs = 0\n for i in range(1, len(A)):\n if climb == True:\n if A[i] > A[i - 1]:\n cs += 1\n continue\n elif A[i] == A[i - 1]:\n return False\n else:\n climb = False\n if climb == False:\n if A[i] < A[i - 1]:\n fs += 1\n continue\n else:\n return False\n if cs > 0 and fs > 0:\n return True\n return False", "def validmountainarray(A: List[int]) -> bool:\n if not A or len(A) <= 2:\n return False\n increase = -1\n for i in range(1, len(A)):\n if A[i] > A[i - 1] and increase == -1:\n increase = 1\n if A[i] > A[i - 1] and increase == 1:\n continue\n elif A[i] < A[i - 1] and increase == 1:\n increase = 0\n elif A[i] < A[i - 1] and increase == 0:\n continue\n else:\n return False\n if increase != 0:\n return False\n return True"], "starter_code": "def validmountainarray(A: List[int]) -> bool:\n", "input_output": {"fn_name": "validMountainArray", "inputs": [[[2, 1]]], "outputs": [false]}, "difficulty": "EASY", "raw_tags": ["Array"], "name": null, "source": "leetcode", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/valid-mountain-array/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "validmountainarray", "task_id": "TACO_lite/392", "example": [[], []]} +{"requirement": "Given two strings s1 and s2 consisting of only lowercase characters whose anagrams are almost equal. The task is to count the number of characters which needs to be edited(delete) to make s1 equal to s2.\nExample:\nInput:\ns1 = madame\ns2 = madam\nOutput:\n1\nExplanation:\nString s1 = madame, string s2 = madam. \ncharacter 'e' in first string needs to \nbe deleted to make s1 equal to s2.\n \nYour Task:\nPrint the count of characters needed to delete to make s1 and s2 equal. Complete the given function.\nExpected Time Complexity: O(max(|s1|,|s2|))\nExpected Auxilary Space: O(|s1| + |s2|) \nConstraints:\n1 <= s1, s2 <= 10^{4}", "solutions": ["def countchars(s1, s2):\n d = {}\n for i in s1:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n e = {}\n for i in s2:\n if i in e:\n e[i] += 1\n else:\n e[i] = 1\n count = 0\n for i in d:\n if i not in e:\n count += d[i]\n else:\n count += abs(d[i] - e[i])\n count1 = 0\n for i in e:\n if i not in d:\n count += e[i]\n else:\n x = e[i] - d[i]\n if x > 0:\n count1 += x\n return max(count, count1)", "def countchars(s1, s2):\n (cc, sum) = (26 * [0], 0)\n for ch in s1:\n cc[ord('a') - ord(ch)] += 1\n for ch in s2:\n cc[ord('a') - ord(ch)] -= 1\n for i in cc:\n sum += abs(i)\n return sum"], "starter_code": "def countchars(s1, s2):\n", "input_output": {"inputs": ["s1 = madame\ns2 = madam"], "outputs": ["1"]}, "difficulty": "EASY", "raw_tags": ["cpp-strings"], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/almost-equal/1", "Expected Auxiliary Space": "O(|s1| + |s2|) ", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(max(|s1|,|s2|))", "entry_point": "countchars", "task_id": "TACO_lite/416", "example": [[["madame", "madam"]], ["1"]]} +{"requirement": "Given a binary tree, find the Postorder Traversal of it.\nFor Example, the postorder traversal of the following tree is: \n5 10 39 1\n 1\n / \\\n 10 39\n /\n5\nExample 1:\nInput:\n 19\n / \\\n 10 8\n / \\\n 11 13\nOutput: 11 13 10 8 19\nExample 2:\nInput:\n 11\n /\n 15\n /\n 7\nOutput: 7 15 11\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function postOrder() that takes root node as input and returns an array containing the postorder traversal of the given Binary Tree.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\nConstraints:\n1 <= Number of nodes <= 10^{5}\n0 <= Data of a node <= 10^{6}", "solutions": ["def postOrder(root):\n\n def helper(root, ans):\n if root:\n helper(root.left, ans)\n helper(root.right, ans)\n ans.append(root.data)\n res = []\n helper(root, res)\n return res", "def postOrder(root):\n li = []\n q = [root]\n while q:\n obg = q.pop()\n if obg:\n li.append(obg.data)\n q.append(obg.left)\n q.append(obg.right)\n li.reverse()\n return li", "def Helper(root, postorder):\n if not root:\n return []\n Helper(root.left, postorder)\n Helper(root.right, postorder)\n postorder.append(root.data)\n return postorder\n\ndef postOrder(root):\n return Helper(root, [])", "def postOrder(root):\n a = []\n\n def postorder(root):\n if root:\n postorder(root.left)\n postorder(root.right)\n a.append(root.data)\n else:\n return\n return a\n return postorder(root)", "def postOrder(root):\n res = []\n helper(root, res)\n return res\n\ndef helper(root, res):\n if root is None:\n return\n helper(root.left, res)\n helper(root.right, res)\n res.append(root.data)", "def PostOrder(root, res):\n if root:\n PostOrder(root.left, res)\n PostOrder(root.right, res)\n res.append(root.data)\n\ndef postOrder(root):\n res = list()\n PostOrder(root, res)\n return res", "def postOrder(root):\n if root is None:\n return []\n return postOrder(root.left) + postOrder(root.right) + [root.data]", "def postOrder(root):\n if root == None:\n return []\n nodes = []\n nodes.extend(postOrder(root.left))\n nodes.extend(postOrder(root.right))\n nodes.append(root.data)\n return nodes", "def postOrder(root):\n ans = []\n if root is not None:\n ans += postOrder(root.left)\n ans += postOrder(root.right)\n ans.append(root.data)\n return ans", "def postOrder(root):\n ans = []\n if root.left:\n ans += postOrder(root.left)\n if root.right:\n ans += postOrder(root.right)\n ans.append(root.data)\n return ans", "def postOrder(root):\n s = [root]\n res = []\n while len(s) > 0:\n node = s.pop()\n res.append(node.data)\n if node.left:\n s.append(node.left)\n if node.right:\n s.append(node.right)\n res.reverse()\n return res", "def postOrder(root):\n if root == None:\n return []\n ans1 = postOrder(root.left)\n ans2 = postOrder(root.right)\n ans = [root.data]\n ans = ans1 + ans2 + ans\n return ans", "def postOrder(root):\n stack = [root]\n ans = []\n while stack:\n node = stack.pop()\n ans.append(node.data)\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n return ans[::-1]", "def po(root, s):\n if not root:\n return\n po(root.left, s)\n po(root.right, s)\n s.append(root.data)\n\ndef postOrder(root):\n s = []\n po(root, s)\n return s", "arr = []\n\ndef postOrder(root):\n if root is None:\n return []\n left_nodes = postOrder(root.left)\n right_nodes = postOrder(root.right)\n return left_nodes + right_nodes + [root.data]", "def postOrder(root):\n ans = []\n if root is None:\n return ans\n stack = []\n stack.append(root)\n while len(stack) != 0:\n top = stack.pop()\n if top.left is not None:\n stack.append(top.left)\n if top.right is not None:\n stack.append(top.right)\n ans.append(top.data)\n return ans[::-1]", "def postOrder(root):\n if root:\n return postOrder(root.left) + postOrder(root.right) + [root.data]\n else:\n return []", "def solve(root, l):\n if root:\n solve(root.left, l)\n solve(root.right, l)\n l.append(root.data)\n\ndef postOrder(root):\n l = []\n solve(root, l)\n return l", "def cal_postorder(root, ans_lst):\n if root:\n cal_postorder(root.left, ans_lst)\n cal_postorder(root.right, ans_lst)\n ans_lst.append(root.data)\n return ans_lst\n\ndef postOrder(root):\n ans_lst = []\n return cal_postorder(root, ans_lst)", "def postOrder(root):\n trav = []\n\n def traverse(root):\n if not root:\n return\n traverse(root.left)\n traverse(root.right)\n trav.append(root.data)\n traverse(root)\n return trav", "def helper(root, ans):\n if root == None:\n return\n helper(root.left, ans)\n helper(root.right, ans)\n ans.append(root.data)\n\ndef postOrder(root):\n ans = []\n helper(root, ans)\n return ans", "def postOrder(root):\n result = []\n if root.left:\n result += postOrder(root.left)\n if root.right:\n result += postOrder(root.right)\n result.append(root.data)\n return result", "def postOrder(root):\n res = []\n if root.left:\n res += postOrder(root.left)\n if root.right:\n res += postOrder(root.right)\n res.append(root.data)\n return res", "def postOrder(root):\n post = []\n st = []\n curr = root\n while curr != None or len(st) != 0:\n if curr != None:\n st.append(curr)\n curr = curr.left\n else:\n temp = st[-1].right\n if temp == None:\n temp = st.pop()\n post.append(temp.data)\n while len(st) != 0 and temp == st[-1].right:\n temp = st.pop()\n post.append(temp.data)\n else:\n curr = temp\n return post", "def postOrder(root):\n postorder = []\n if not root:\n return postorder\n st1 = deque()\n st2 = deque()\n st1.append(root)\n while len(st1) != 0:\n node = st1.pop()\n st2.append(node)\n if node.left:\n st1.append(node.left)\n if node.right:\n st1.append(node.right)\n while len(st2) != 0:\n node = st2.pop()\n postorder.append(node.data)\n return postorder", "def postOrder(root):\n stack = [(root, False)]\n ans = []\n while stack:\n (node, visited) = stack.pop()\n if visited:\n ans.append(node.data)\n elif node:\n stack.append((node, True))\n stack.append((node.right, False))\n stack.append((node.left, False))\n return ans", "def postOrder(root):\n if root is None:\n return\n a = [root]\n ans = []\n while a:\n t = a.pop()\n ans.append(t.data)\n if t.left:\n a.append(t.left)\n if t.right:\n a.append(t.right)\n return ans[::-1]", "def postOrder(root):\n arr = []\n solve(root, arr)\n return arr\n\ndef solve(root, arr):\n if root is None:\n return\n solve(root.left, arr)\n solve(root.right, arr)\n arr.append(root.data)", "def po(root, arr):\n if root:\n po(root.left, arr)\n po(root.right, arr)\n arr.append(root.data)\n\ndef postOrder(root):\n arr = []\n po(root, arr)\n return arr", "def postOrder(root):\n if root:\n l = postOrder(root.left)\n r = postOrder(root.right)\n return l + r + [root.data]\n return []", "def postOrder(root):\n res = []\n postOrder_res(res, root)\n return res\n\ndef postOrder_res(res, root):\n if root == None:\n return\n postOrder_res(res, root.left)\n postOrder_res(res, root.right)\n res.append(root.data)", "def postOrder(root):\n mylist = []\n ans = postOrderHelper(root, mylist)\n x = []\n if ans == -1:\n x.append(-1)\n return x\n return ans\n\ndef postOrderHelper(root, mylist):\n if root is None:\n return -1\n postOrderHelper(root.left, mylist)\n postOrderHelper(root.right, mylist)\n mylist.append(root.data)\n return mylist", "def postOrder(root):\n current = root\n stack = []\n ans = []\n while current or stack:\n if current:\n if current.right:\n stack.append(current.right)\n stack.append(current)\n current = current.left\n else:\n node = stack.pop()\n if stack and node.right == stack[-1]:\n current = stack.pop()\n stack.append(node)\n else:\n ans.append(node.data)\n return ans", "def postOrder(root):\n\n def getpostorder(root):\n if not root:\n return\n getpostorder(root.left)\n getpostorder(root.right)\n ans.append(root.data)\n return ans\n ans = []\n getpostorder(root)\n return ans", "def postOrder(root):\n s1 = []\n s2 = []\n res = []\n s1.append(root)\n while len(s1) != 0:\n popped_val = s1.pop()\n s2.append(popped_val)\n if popped_val.left:\n s1.append(popped_val.left)\n if popped_val.right:\n s1.append(popped_val.right)\n while len(s2) != 0:\n res.append(s2.pop().data)\n return res", "def postOrder(root):\n if root is None:\n return []\n lst = postOrder(root.left) + postOrder(root.right)\n lst.append(root.data)\n return lst", "def postOrder(root):\n if root is None:\n return\n stack = []\n result = []\n stack.append(root)\n while stack:\n current = stack.pop()\n result.append(current.data)\n if current.left:\n stack.append(current.left)\n if current.right:\n stack.append(current.right)\n result = result[::-1]\n return result", "def postOrder(root):\n result = []\n\n def postOrderTraversal(node):\n if node is None:\n return\n postOrderTraversal(node.left)\n postOrderTraversal(node.right)\n result.append(node.data)\n postOrderTraversal(root)\n return result", "def postOrder(root):\n if root == None:\n return []\n rn = postOrder(root.right)\n ln = postOrder(root.left)\n return ln + rn + [root.data]", "def helper(root, ans):\n if not root:\n return ans\n helper(root.left, ans)\n helper(root.right, ans)\n ans.append(root.data)\n return ans\n\ndef postOrder(root):\n return helper(root, [])", "def postOrder(root):\n if root == None:\n return []\n if root.left == None and root.right == None:\n return [root.data]\n leftarr = postOrder(root.left)\n rightarr = postOrder(root.right)\n return leftarr + rightarr + [root.data]", "def postOrder(root):\n answer = []\n stack = [root]\n while stack:\n node = stack.pop()\n answer.append(node.data)\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n return list(reversed(answer))", "def postOrder(root):\n res = []\n\n def post(root, res):\n if root != None:\n post(root.left, res)\n post(root.right, res)\n res.append(root.data)\n post(root, res)\n return res", "def postOrder(root):\n l = []\n\n def traverse(node):\n if node:\n traverse(node.left)\n traverse(node.right)\n l.append(node.data)\n traverse(root)\n return l", "def postOrder(root):\n ans = []\n stk = [root]\n curr = None\n while stk:\n curr = stk.pop()\n ans.append(curr.data)\n if curr.left:\n stk.append(curr.left)\n if curr.right:\n stk.append(curr.right)\n return ans[::-1]", "def postOrder(root):\n stack1 = []\n stack2 = []\n stack1.append(root)\n node = root\n while stack1:\n node = stack1[-1]\n stack2.append(stack1[-1].data)\n stack1.pop()\n if node.left:\n stack1.append(node.left)\n if node.right:\n stack1.append(node.right)\n return stack2[::-1]", "def getList(root, li):\n if root:\n getList(root.left, li)\n getList(root.right, li)\n li.append(root.data)\n\ndef postOrder(root):\n li = []\n getList(root, li)\n return li", "def postOrder(root):\n if root == None:\n return []\n if root.left == None and root.right == None:\n return [root.data]\n left = postOrder(root.left)\n right = postOrder(root.right)\n arr = []\n arr += left + right\n arr.append(root.data)\n return arr", "def postOrder(root):\n\n def cal(root, stack):\n if root is None:\n return\n cal(root.left, stack)\n cal(root.right, stack)\n stack.append(root.data)\n stack = []\n cal(root, stack)\n return stack", "def postOrder(root):\n\n def postOrderTraversal(root, l):\n if root is None:\n return\n if root.left:\n root.left = postOrderTraversal(root.left, l)\n if root.right:\n root.right = postOrderTraversal(root.right, l)\n l.append(root.data)\n l = []\n postOrderTraversal(root, l)\n return l", "def rec_sol(root, ans):\n if root.left != None:\n rec_sol(root.left, ans)\n if root.right != None:\n rec_sol(root.right, ans)\n ans.append(root.data)\n\ndef postOrder(root):\n ans = []\n stack = []\n stack.append(root)\n while len(stack) != 0:\n node = stack.pop()\n ans.append(node.data)\n if node.left != None:\n stack.append(node.left)\n if node.right != None:\n stack.append(node.right)\n ans.reverse()\n return ans", "def rec_sol(root, ans):\n if root.left != None:\n rec_sol(root.left, ans)\n if root.right != None:\n rec_sol(root.right, ans)\n ans.append(root.data)\n\ndef postOrder(root):\n ans = []\n rec_sol(root, ans)\n return ans", "def postOrder(root):\n z = []\n\n def post(root):\n if root == None:\n return\n post(root.left)\n post(root.right)\n z.append(root.data)\n post(root)\n return z", "def postOrder(root):\n a = []\n\n def solve(root):\n if root:\n solve(root.left)\n solve(root.right)\n a.append(root.data)\n solve(root)\n return a", "def postOrder(root):\n ans = []\n\n def post(root):\n if root != None:\n post(root.left)\n post(root.right)\n ans.append(root.data)\n post(root)\n return ans", "def postorderutil(root, res):\n if root != None:\n postorderutil(root.left, res)\n postorderutil(root.right, res)\n res.append(root.data)\n\ndef postOrder(root):\n res = []\n postorderutil(root, res)\n return res", "def postOrder(root):\n if root == None:\n return []\n left_nodes = postOrder(root.left)\n right_nodes = postOrder(root.right)\n return left_nodes + right_nodes + [root.data]", "def postOrder(root):\n ans = []\n stk = []\n cur = root\n while cur or len(stk):\n if cur != None:\n ans.append(cur.data)\n stk.append(cur)\n cur = cur.right\n else:\n cur = stk.pop()\n cur = cur.left\n return ans[::-1]", "def postOrder(root):\n if root == None:\n return []\n left_n = postOrder(root.left)\n right_n = postOrder(root.right)\n ans = left_n + right_n + [root.data]\n return ans"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["19\n / \\\n 10 8\n / \\\n 11 13", "11\n /\n 15\n /\n 7"], "outputs": ["11 13 10 8 19", "7 15 11"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/postorder-traversal/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "__init__", "task_id": "TACO_lite/376", "example": [[], []]} +{"requirement": "Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K.\n(For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.)\nReturn the number of good subarrays of A.\n\u00a0\nExample 1:\nInput: A = [1,2,1,2,3], K = 2\nOutput: 7\nExplanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].\n\nExample 2:\nInput: A = [1,2,1,3,4], K = 3\nOutput: 3\nExplanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].\n\n\u00a0\nNote:\n\n1 <= A.length <= 20000\n1 <= A[i] <= A.length\n1 <= K <= A.length", "solutions": ["from collections import defaultdict\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n start_k = 0\n start = 0\n elem_dict = defaultdict(int)\n ans = 0\n for elem in A:\n elem_dict[elem] += 1\n if len(elem_dict) > K:\n del elem_dict[A[start_k]]\n start_k += 1\n start = start_k\n if len(elem_dict) == K:\n while elem_dict[A[start_k]] > 1:\n elem_dict[A[start_k]] -= 1\n start_k += 1\n ans = ans + start_k - start + 1\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n if K > len(A):\n return 0\n result = checker = windowStart = 0\n hashMap = {}\n a_length = len(A)\n for windowEnd in range(a_length):\n curr_str = A[windowEnd]\n if curr_str in hashMap:\n hashMap[curr_str] += 1\n else:\n hashMap[curr_str] = 1\n if len(hashMap) > K:\n del hashMap[A[checker]]\n checker += 1\n windowStart = checker\n if len(hashMap) == K:\n while hashMap[A[checker]] > 1:\n hashMap[A[checker]] -= 1\n checker += 1\n result += checker - windowStart + 1\n return result", "from collections import OrderedDict\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n counter = OrderedDict()\n count = 0\n j = 0\n for (i, n) in enumerate(A):\n counter[n] = i\n counter.move_to_end(n)\n while len(counter) > K:\n j = counter.popitem(last=False)[1] + 1\n if len(counter) == K:\n count += next(iter(counter.values())) - j + 1\n return count", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n (ans, ctr, lb, count) = (0, {}, 0, 0)\n for (i, val) in enumerate(A):\n if val not in ctr:\n ctr[val] = 0\n ctr[val] += 1\n while len(ctr) > K:\n ctr[A[lb]] -= 1\n if ctr[A[lb]] == 0:\n del ctr[A[lb]]\n lb += 1\n if len(ctr) == K:\n (p2, count, ctr1) = (lb, 0, collections.Counter())\n while len(ctr) == K:\n count += 1\n ctr[A[p2]] -= 1\n if ctr[A[p2]] == 0:\n del ctr[A[p2]]\n ctr1[A[p2]] += 1\n p2 += 1\n ans += count\n for (k, v) in ctr1.items():\n ctr[k] = ctr.get(k, 0) + v\n return ans\n\ndef __init__():\n self.count = collections.Counter()\n self.nonzero = 0\n\ndef add(x):\n self.count[x] += 1\n if self.count[x] == 1:\n self.nonzero += 1\n\ndef remove(x):\n self.count[x] -= 1\n if self.count[x] == 0:\n self.nonzero -= 1\n\ndef subarrayswithkdistinct(A, K):\n window1 = Window()\n window2 = Window()\n ans = left1 = left2 = 0\n for (right, x) in enumerate(A):\n window1.add(x)\n window2.add(x)\n while window1.nonzero > K:\n window1.remove(A[left1])\n left1 += 1\n while window2.nonzero >= K:\n window2.remove(A[left2])\n left2 += 1\n ans += left2 - left1\n return ans", "def __init__():\n self.count = collections.Counter()\n self.nonzero = 0\n\ndef add(x):\n self.count[x] += 1\n if self.count[x] == 1:\n self.nonzero += 1\n\ndef remove(x):\n self.count[x] -= 1\n if self.count[x] == 0:\n self.nonzero -= 1\n\ndef subarrayswithkdistinct(A, K):\n window1 = Window()\n window2 = Window()\n ans = left1 = left2 = 0\n for (right, x) in enumerate(A):\n window1.add(x)\n window2.add(x)\n while window1.nonzero > K:\n window1.remove(A[left1])\n left1 += 1\n while window2.nonzero >= K:\n window2.remove(A[left2])\n left2 += 1\n ans += left2 - left1\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n from collections import Counter\n\n def atMost(k):\n count = Counter()\n ans = i = 0\n for j in range(len(A)):\n if not count[A[j]]:\n k -= 1\n count[A[j]] += 1\n while k < 0:\n count[A[i]] -= 1\n if not count[A[i]]:\n k += 1\n i += 1\n ans += j - i + 1\n return ans\n return atMost(K) - atMost(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMostK(K):\n i = 0\n count = 0\n counts = Counter()\n for j in range(len(A)):\n if counts[A[j]] == 0:\n K -= 1\n counts[A[j]] += 1\n while K < 0:\n counts[A[i]] -= 1\n if counts[A[i]] == 0:\n K += 1\n i += 1\n count += j - i + 1\n return count\n return atMostK(K) - atMostK(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n start = 0\n first_uni = 0\n re = 0\n dd = {}\n for (i, cur) in enumerate(A):\n dd[cur] = dd.get(cur, 0) + 1\n if len(dd) == K + 1:\n dd.pop(A[first_uni])\n first_uni += 1\n start = first_uni\n if len(dd) == K:\n while first_uni <= i and dd[A[first_uni]] != 1:\n dd[A[first_uni]] -= 1\n first_uni += 1\n re += first_uni - start + 1\n return re", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n N = len(A)\n\n def atMost(k):\n if k == 0:\n return 0\n ret = i = j = 0\n cnt = Counter()\n while i < N:\n x = A[i]\n while j < N and (len(cnt) < k or A[j] in cnt):\n cnt[A[j]] += 1\n j += 1\n ret += j - i\n cnt[x] -= 1\n if cnt[x] == 0:\n del cnt[x]\n i += 1\n return ret\n return atMost(K) - atMost(K - 1)", "def subarrayswithkdistinct(s: List[int], K: int) -> int:\n obj = defaultdict(int)\n first = 0\n second = 0\n answer = 0\n for i in range(len(s)):\n obj[s[i]] += 1\n if len(obj) == K + 1:\n del obj[s[second]]\n second += 1\n first = second\n if len(obj) == K:\n while obj[s[second]] > 1:\n obj[s[second]] -= 1\n second += 1\n answer += second - first + 1\n return answer", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n length = len(A)\n\n class counter:\n\n def __init__(self):\n self.c = Counter()\n\n def addValue(self, num):\n self.c[num] += 1\n\n def removeValue(self, num):\n self.c[num] -= 1\n if self.c[num] == 0:\n del self.c[num]\n\n def subarraysWithAtLeast(k):\n start = 0\n c = counter()\n ret = 0\n for i in range(length):\n cur = A[i]\n c.addValue(cur)\n if len(c.c) < k:\n ret += i - start + 1\n continue\n while len(c.c) > k:\n tmp = A[start]\n c.removeValue(tmp)\n start += 1\n assert len(c.c) == k\n ret += i - start + 1\n return ret\n return subarraysWithAtLeast(K) - subarraysWithAtLeast(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n int_dict = {}\n int_sorted_list = []\n current = 0\n l = len(A)\n count = 0\n while current < l:\n if int_dict.get(A[current]) != None:\n int_sorted_list.remove(A[current])\n int_dict[A[current]] = current\n int_sorted_list.append(A[current])\n if len(int_sorted_list) > K + 1:\n del int_dict[int_sorted_list[0]]\n del int_sorted_list[0]\n if len(int_sorted_list) > K:\n count += int_dict[int_sorted_list[-K]] - int_dict[int_sorted_list[-K - 1]]\n elif len(int_sorted_list) == K:\n count += int_dict[int_sorted_list[-K]] + 1\n current += 1\n return count", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atmostK(k):\n count = Counter()\n res = 0\n left = 0\n right = 0\n for right in range(len(A)):\n if count[A[right]] == 0:\n k -= 1\n count[A[right]] += 1\n while k < 0:\n count[A[left]] -= 1\n if count[A[left]] == 0:\n k += 1\n left += 1\n res += right - left + 1\n return res\n return atmostK(K) - atmostK(K - 1)", "def count_below(arr, k):\n if k == 0:\n return 0\n else:\n right = 0\n satisfactory = 0\n window = Window()\n for left in range(len(arr)):\n while right < len(arr) and window.added_size(arr[right]) <= k:\n window.add(arr[right])\n right += 1\n satisfactory += right - left\n window.remove(arr[left])\n return satisfactory\n\ndef subarrays_with_k_distinct(arr, k):\n assert k >= 1\n return count_below(arr, k) - count_below(arr, k - 1)\n\ndef __init__():\n self.count = {}\n\ndef add(elem):\n self.count.setdefault(elem, 0)\n self.count[elem] += 1\n\ndef remove(elem):\n self.count[elem] -= 1\n if self.count[elem] == 0:\n del self.count[elem]\n\ndef added_size(elem):\n return len(self.count) + bool(elem not in self.count)\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return subarrays_with_k_distinct(A, K)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n result = 0\n (i, j) = (0, 0)\n cnt = collections.Counter()\n l = 0\n n = len(A)\n while j < n:\n if len(cnt) != K:\n cnt[A[j]] += 1\n if len(cnt) == K:\n l = 1\n while cnt[A[i]] > 1:\n cnt[A[i]] -= 1\n i += 1\n l += 1\n result += l\n elif A[j] in cnt:\n cnt[A[j]] += 1\n while cnt[A[i]] > 1:\n cnt[A[i]] -= 1\n i += 1\n l += 1\n result += l\n else:\n cnt[A[i]] -= 1\n if cnt[A[i]] == 0:\n cnt.pop(A[i])\n cnt[A[j]] += 1\n i += 1\n l = 1\n while cnt[A[i]] > 1:\n cnt[A[i]] -= 1\n i += 1\n l += 1\n result += l\n j += 1\n return result", "def __init__():\n self.counter = collections.Counter()\n\ndef add(x):\n self.counter[x] += 1\n\ndef remove(x):\n self.counter[x] -= 1\n if self.counter[x] == 0:\n self.counter.pop(x)\n\ndef __len__():\n return len(self.counter)\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n window1 = Window()\n window2 = Window()\n (left1, left2) = (0, 0)\n result = 0\n for (right, num) in enumerate(A):\n window1.add(num)\n window2.add(num)\n while len(window1) > K:\n window1.remove(A[left1])\n left1 += 1\n while len(window2) >= K:\n window2.remove(A[left2])\n left2 += 1\n result += left2 - left1\n return result", "def __init__():\n self.KeyToCount = {}\n self.q = deque()\n\ndef append(value):\n self.q.append(value)\n self.KeyToCount[value] = self.KeyToCount.get(value, 0) + 1\n\ndef popleft():\n v = self.q.popleft()\n if self.KeyToCount[v] == 1:\n del self.KeyToCount[v]\n else:\n self.KeyToCount[v] -= 1\n\ndef distinctCount():\n return len(self.KeyToCount)\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n n = len(A)\n nextHiIdx = 0\n nextLoIdx = 0\n loAcc = Accumulator()\n hiAcc = Accumulator()\n lo = [None] * n\n hi = [None] * n\n for i in range(n):\n if i >= 1:\n hiAcc.popleft()\n loAcc.popleft()\n while nextLoIdx < n and loAcc.distinctCount() < K:\n loAcc.append(A[nextLoIdx])\n nextLoIdx += 1\n while nextHiIdx < n and hiAcc.distinctCount() <= K:\n hiAcc.append(A[nextHiIdx])\n nextHiIdx += 1\n if loAcc.distinctCount() == K:\n lo[i] = nextLoIdx - 1\n if hiAcc.distinctCount() == K + 1:\n hi[i] = nextHiIdx - 1\n elif hiAcc.distinctCount() == K and nextHiIdx == n:\n hi[i] = nextHiIdx\n return sum((hi[i] - lo[i] for i in range(n) if hi[i] != None))", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMost(K):\n N = len(A)\n ct = collections.Counter()\n ans = 0\n i = 0\n for j in range(N):\n ct[A[j]] += 1\n if len(ct) <= K:\n ans += j - i + 1\n else:\n while len(ct) > K:\n ct[A[i]] -= 1\n if ct[A[i]] == 0:\n del ct[A[i]]\n i += 1\n ans += j - i + 1\n return ans\n return atMost(K) - atMost(K - 1)", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n window1 = Window()\n window2 = Window()\n res = 0\n (left1, left2) = (0, 0)\n for i in range(len(A)):\n window1.add(A[i])\n window2.add(A[i])\n while window1.size() > K:\n window1.remove(A[left1])\n left1 += 1\n while window2.size() > K - 1:\n window2.remove(A[left2])\n left2 += 1\n res += left2 - left1\n return res\n\ndef __init__():\n self.counter = Counter()\n\ndef add(x):\n self.counter[x] += 1\n\ndef remove(x):\n self.counter[x] -= 1\n if self.counter[x] == 0:\n del self.counter[x]\n\ndef size():\n return len(self.counter)", "def subarrayswithkdistinct(A: 'List[int]', K: 'int') -> 'int':\n return self.subarraysWithKMax(A, K) - self.subarraysWithKMax(A, K - 1)\n\ndef subarraysWithKMax(A, K):\n k = 0\n count = dict()\n (i, start) = (0, 0)\n res = 0\n while i < len(A):\n if A[i] not in count:\n k += 1\n count[A[i]] = 1\n else:\n count[A[i]] += 1\n i += 1\n while start < i and k > K:\n count[A[start]] -= 1\n if count[A[start]] == 0:\n del count[A[start]]\n k -= 1\n start += 1\n res += i - start\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.atMostK(A, K) - self.atMostK(A, K - 1)\n\ndef atMostK(A, K):\n counter = collections.Counter()\n res = i = 0\n for j in range(len(A)):\n if counter[A[j]] == 0:\n K -= 1\n counter[A[j]] += 1\n while K < 0:\n counter[A[i]] -= 1\n if counter[A[i]] == 0:\n K += 1\n i += 1\n res += j - i + 1\n return res", "from collections import Counter\n\ndef __init__():\n self.count = Counter()\n self.nonzero = 0\n\ndef add(val):\n self.count[val] += 1\n if self.count[val] == 1:\n self.nonzero += 1\n\ndef remove(val):\n self.count[val] -= 1\n if self.count[val] == 0:\n self.nonzero -= 1\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n ans = 0\n (l1, l2) = (0, 0)\n (w1, w2) = (Window(), Window())\n for (r, val) in enumerate(A):\n w1.add(val)\n w2.add(val)\n while w1.nonzero > K:\n w1.remove(A[l1])\n l1 += 1\n while w2.nonzero >= K:\n w2.remove(A[l2])\n l2 += 1\n ans += l2 - l1\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n class UniqueCounter(object):\n\n def __init__(self):\n self.non_zero = 0\n self.counts = collections.defaultdict(int)\n\n def add(self, x):\n if self.counts[x] == 0:\n self.non_zero += 1\n self.counts[x] += 1\n\n def remove(self, x):\n self.counts[x] -= 1\n if self.counts[x] == 0:\n self.non_zero -= 1\n\n def count(self):\n return self.non_zero\n\n def subarrays_with_max_K(A, K):\n j = 0\n uc = UniqueCounter()\n uc.add(A[0])\n answer = 0\n for i in range(len(A)):\n while j < len(A) and uc.count() <= K:\n j += 1\n if j < len(A):\n uc.add(A[j])\n answer += j - i\n uc.remove(A[i])\n return answer\n return subarrays_with_max_K(A, K) - subarrays_with_max_K(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n last_seen = {}\n start = end = 0\n ans = 0\n for (i, x) in enumerate(A):\n last_seen[x] = i\n while len(last_seen) > K:\n if last_seen[A[start]] == start:\n del last_seen[A[start]]\n start += 1\n while A[end] not in last_seen or last_seen[A[end]] != end:\n end += 1\n if len(last_seen) == K:\n ans += end - start + 1\n return ans", "from collections import Counter\n\ndef solve(A, K):\n count = Counter()\n front = iter(A)\n ans = 0\n size = 0\n for k in A:\n count[k] += 1\n size += 1\n while len(count) > K:\n key = next(front)\n count[key] -= 1\n size -= 1\n if count[key] == 0:\n del count[key]\n ans += size\n return ans\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return solve(A, K) - solve(A, K - 1)", "def __init__():\n self.count = collections.Counter()\n self.nonzero = 0\n\ndef add(x):\n self.count[x] += 1\n if self.count[x] == 1:\n self.nonzero += 1\n\ndef remove(x):\n self.count[x] -= 1\n if self.count[x] == 0:\n self.nonzero -= 1\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n window1 = Window()\n window2 = Window()\n ans = le1 = le2 = 0\n for (ri, val) in enumerate(A):\n window1.add(val)\n window2.add(val)\n while window1.nonzero > K:\n window1.remove(A[le1])\n le1 += 1\n while window2.nonzero >= K:\n window2.remove(A[le2])\n le2 += 1\n ans += le2 - le1\n return ans", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.at_most(A, K) - self.at_most(A, K - 1)\n\ndef at_most(a, k):\n res = 0\n start = 0\n c = Counter()\n for (end, elem) in enumerate(a):\n if c[elem] == 0:\n k -= 1\n c[elem] += 1\n while start <= end and k < 0:\n c[a[start]] -= 1\n if c[a[start]] == 0:\n k += 1\n start += 1\n res += end - start + 1\n return res", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMostK(A, K):\n counts = Counter()\n (left, result) = (0, 0)\n for right in range(len(A)):\n if counts[A[right]] == 0:\n K -= 1\n counts[A[right]] += 1\n while K < 0:\n counts[A[left]] -= 1\n if counts[A[left]] == 0:\n K += 1\n left += 1\n result += right - left + 1\n return result\n return atMostK(A, K) - atMostK(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n if not A:\n return 0\n l = len(A)\n end = 0\n left1 = 0\n left2 = 0\n map1 = collections.defaultdict(int)\n map2 = collections.defaultdict(int)\n ans = 0\n while end < l:\n ch = A[end]\n map1[ch] += 1\n map2[ch] += 1\n while len(map1) > K and left1 < l:\n temp1 = A[left1]\n map1[temp1] -= 1\n if map1[temp1] == 0:\n del map1[temp1]\n left1 += 1\n while len(map2) >= K and left2 < l:\n temp2 = A[left2]\n map2[temp2] -= 1\n if map2[temp2] == 0:\n del map2[temp2]\n left2 += 1\n ans += left2 - left1\n end += 1\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n n = len(A)\n hashmap = {}\n l = 0\n count = 0\n ans = 0\n sums = 1\n for r in range(n):\n if A[r] in hashmap:\n hashmap[A[r]] += 1\n else:\n hashmap[A[r]] = 1\n if hashmap[A[r]] == 1:\n count += 1\n while count > K or hashmap[A[l]] > 1:\n if count > K:\n sums = 1\n else:\n sums += 1\n hashmap[A[l]] -= 1\n if hashmap[A[l]] == 0:\n count -= 1\n l += 1\n if count == K:\n ans += sums\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def helper(A, K):\n d = defaultdict(int)\n begin = 0\n end = 0\n ans = float('-inf')\n count = 0\n res = 0\n while end < len(A):\n char = A[end]\n d[char] += 1\n if d[char] == 1:\n count += 1\n end += 1\n while count > K:\n temp = A[begin]\n d[temp] -= 1\n if d[temp] == 0:\n count -= 1\n begin += 1\n res += end - begin + 1\n return res\n return helper(A, K) - helper(A, K - 1)", "def subarrayswithkdistinct(A: 'List[int]', K: 'int') -> 'int':\n return self.subarraysWithAtMostKDistinct(A, K) - self.subarraysWithAtMostKDistinct(A, K - 1)\n\ndef subarraysWithAtMostKDistinct(s, k):\n lookup = collections.defaultdict(int)\n (l, r, counter, res) = (0, 0, 0, 0)\n while r < len(s):\n lookup[s[r]] += 1\n if lookup[s[r]] == 1:\n counter += 1\n r += 1\n while l < r and counter > k:\n lookup[s[l]] -= 1\n if lookup[s[l]] == 0:\n counter -= 1\n l += 1\n res += r - l\n return res", "def __init__():\n self.num = 0\n self.dic = collections.defaultdict(int)\n\ndef add(v: int) -> int:\n if self.dic[v] == 0:\n self.num += 1\n self.dic[v] += 1\n return self.num\n\ndef remove(v: int) -> int:\n self.dic[v] -= 1\n if self.dic[v] == 0:\n self.num -= 1\n return self.num\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n wk = Window()\n wm = Window()\n sk = 0\n sm = 0\n e = 0\n ans = 0\n while e < len(A):\n ce = A[e]\n nk = wk.add(ce)\n nm = wm.add(ce)\n if nk < K:\n e += 1\n elif nk == K:\n while nm != K - 1:\n nm = wm.remove(A[sm])\n sm += 1\n ans += sm - sk\n e += 1\n else:\n while nk != K:\n nk = wk.remove(A[sk])\n sk += 1\n while nm != K - 1:\n nm = wm.remove(A[sm])\n sm += 1\n ans += sm - sk\n e += 1\n return ans", "def __init__():\n self.count = collections.Counter()\n self.nonzero = 0\n\ndef add(x):\n self.count[x] += 1\n if self.count[x] == 1:\n self.nonzero += 1\n\ndef remove(x):\n self.count[x] -= 1\n if self.count[x] == 0:\n self.nonzero -= 1\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n window1 = Window()\n window2 = Window()\n ans = left1 = left2 = 0\n for x in A:\n window1.add(x)\n window2.add(x)\n while window1.nonzero > K:\n window1.remove(A[left1])\n left1 += 1\n while window2.nonzero >= K:\n window2.remove(A[left2])\n left2 += 1\n ans += left2 - left1\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMostK(kk):\n counter = collections.Counter()\n res = ii = 0\n for jj in range(len(A)):\n if counter[A[jj]] == 0:\n kk -= 1\n counter[A[jj]] += 1\n while kk < 0:\n counter[A[ii]] -= 1\n if counter[A[ii]] == 0:\n kk += 1\n ii += 1\n res += jj - ii + 1\n return res\n return atMostK(K) - atMostK(K - 1)", "from collections import defaultdict as dd\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n n = len(A)\n i = j = 0\n d = dd(int)\n res = 0\n while j < n:\n while j < n and len(d) < K:\n d[A[j]] += 1\n j += 1\n (i1, j1) = (i, j)\n d[A[i]] -= 1\n while d[A[i]] > 0:\n i += 1\n d[A[i]] -= 1\n while j < n and A[j] in d:\n j += 1\n if len(d) == K:\n res += (i - i1 + 1) * (j - j1 + 1)\n d.pop(A[i])\n i += 1\n j = j1\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMostK(A, K):\n (ans, curr) = (0, 0)\n cnt = defaultdict(int)\n i = 0\n for (j, num) in enumerate(A):\n if num not in cnt:\n K -= 1\n cnt[num] += 1\n while K < 0:\n cnt[A[i]] -= 1\n if cnt[A[i]] == 0:\n del cnt[A[i]]\n K += 1\n i += 1\n ans += j - i + 1\n return ans\n return atMostK(A, K) - atMostK(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.at_most_K(A, K) - self.at_most_K(A, K - 1)\n\ndef at_most_K(A, k):\n left = 0\n counter = collections.Counter()\n diff = 0\n result = 0\n for right in range(len(A)):\n counter[A[right]] += 1\n if counter[A[right]] == 1:\n diff += 1\n while diff > k:\n counter[A[left]] -= 1\n if counter[A[left]] == 0:\n diff -= 1\n left += 1\n result += right - left + 1\n return result", "def subarrayswithkdistinct(A, K):\n return self.atMostK(A, K) - self.atMostK(A, K - 1)\n\ndef atMostK(A, K):\n count = collections.Counter()\n res = i = 0\n for j in range(len(A)):\n if count[A[j]] == 0:\n K -= 1\n count[A[j]] += 1\n while K < 0:\n count[A[i]] -= 1\n if count[A[i]] == 0:\n K += 1\n i += 1\n res += j - i + 1\n return res", "from typing import Dict, Set, List, Tuple\nfrom collections import defaultdict\nfrom pprint import pprint\n\ndef __init__():\n self._counter = {}\n self._distinct_num = 0\n\ndef add(num):\n if num in self._counter:\n self._counter[num] += 1\n else:\n self._distinct_num += 1\n self._counter[num] = 1\n\ndef remove(num):\n self._counter[num] -= 1\n if self._counter[num] == 0:\n self._distinct_num -= 1\n del self._counter[num]\n\ndef nums():\n return self._distinct_num\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n w1 = Window()\n w2 = Window()\n x = y = z = 0\n result = 0\n while z < len(A):\n w1.add(A[z])\n w2.add(A[z])\n z += 1\n while w1.nums > K:\n w1.remove(A[x])\n x += 1\n while w2.nums > K - 1:\n w2.remove(A[y])\n y += 1\n if w1.nums == K:\n assert w2.nums == K - 1\n result += y - x\n return result", "from collections import defaultdict\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n n = len(A)\n if n < K:\n return 0\n count = defaultdict(int)\n p1 = 0\n p2 = 0\n p3 = 0\n count[A[0]] += 1\n ans = 0\n while p2 < n:\n remaining = K - len(count)\n while remaining > 0:\n p2 += 1\n if p2 == n:\n return ans\n count[A[p2]] += 1\n if count[A[p2]] == 1:\n remaining -= 1\n while p3 < n and A[p3] in count:\n p3 += 1\n while len(count) == K:\n ans += p3 - p2\n p1 += 1\n count[A[p1 - 1]] -= 1\n if count[A[p1 - 1]] == 0:\n del count[A[p1 - 1]]\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n checkSet = OrderedDict()\n windowStart = 0\n count = 0\n ans = []\n for (i, n) in enumerate(A):\n checkSet[n] = i\n checkSet.move_to_end(n)\n while len(checkSet) > K:\n windowStart = checkSet.popitem(last=False)[1] + 1\n if len(checkSet) == K:\n count += next(iter(list(checkSet.items())))[1] - windowStart + 1\n return count", "def subarrayswithkdistinct(A: List[int], k: int) -> int:\n dic = {}\n n = len(A)\n left = 0\n right = 0\n cnt = 0\n for i in range(n):\n if A[i] in dic:\n dic[A[i]] += 1\n else:\n dic[A[i]] = 1\n l = len(dic)\n if l == k + 1:\n del dic[A[right]]\n right += 1\n left = right\n l -= 1\n if l == k:\n while dic[A[right]] > 1:\n dic[A[right]] -= 1\n right += 1\n cnt += right - left + 1\n return cnt", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n left1 = 0\n left2 = 0\n w1 = {}\n w2 = {}\n count = 0\n for (right, x) in enumerate(A):\n if x in w1:\n w1[x] += 1\n else:\n w1[x] = 1\n if x in w2:\n w2[x] += 1\n else:\n w2[x] = 1\n while len(w1) > K:\n if w1[A[left1]] == 1:\n w1.pop(A[left1])\n elif w1[A[left1]] > 1:\n w1[A[left1]] -= 1\n left1 += 1\n while len(w2) >= K:\n if w2[A[left2]] == 1:\n w2.pop(A[left2])\n elif w2[A[left2]] > 1:\n w2[A[left2]] -= 1\n left2 += 1\n count += left2 - left1\n return count", "def _identify_limit(A, current_limit, K, char_count_after_limit):\n temp_char = A[current_limit]\n while char_count_after_limit.get(temp_char, 0) > 1:\n char_count_after_limit[temp_char] = char_count_after_limit[temp_char] - 1\n current_limit += 1\n temp_char = A[current_limit]\n return (current_limit, char_count_after_limit)\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n char_info = {item: [] for item in set(A)}\n unique_char_count = {}\n unique_char = set()\n start_idx = 0\n end_idx = 0\n num_substr = 0\n current_subarray = []\n current_valid_count = 0\n limit_idx = 0\n while end_idx < len(A) + 1:\n if len(unique_char_count) == K:\n (limit_idx, unique_char_count) = self._identify_limit(A, limit_idx, K, unique_char_count)\n num_substr += limit_idx - start_idx + 1\n if end_idx < len(A):\n current_char = A[end_idx]\n unique_char_count[current_char] = unique_char_count.get(current_char, 0) + 1\n end_idx += 1\n elif len(unique_char_count) > K:\n current_char = A[limit_idx]\n unique_char_count.pop(current_char)\n start_idx = limit_idx + 1\n limit_idx = start_idx\n else:\n if end_idx < len(A):\n current_char = A[end_idx]\n unique_char_count[current_char] = unique_char_count.get(current_char, 0) + 1\n end_idx += 1\n return num_substr", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n (d, t) = (defaultdict(int), defaultdict(int))\n (a, b) = (K, K)\n (left, right) = (0, 0)\n res = 0\n for (i, ele) in enumerate(A):\n a -= 1 if d[ele] == 0 else 0\n b -= 1 if t[ele] == 0 else 0\n d[ele] += 1\n t[ele] += 1\n while a < 0:\n a += 1 if d[A[left]] == 1 else 0\n d[A[left]] -= 1\n left += 1\n while b <= 0:\n b += 1 if t[A[right]] == 1 else 0\n t[A[right]] -= 1\n right += 1\n res += right - left\n return res", "def subarrayswithkdistinct(A: 'List[int]', K: 'int') -> 'int':\n freq = {}\n start = 0\n start_k = 0\n res = 0\n for (i, x) in enumerate(A):\n freq[x] = freq.get(x, 0) + 1\n if len(freq) == K + 1:\n del freq[A[start_k]]\n start_k += 1\n start = start_k\n if len(freq) == K:\n while freq[A[start_k]] > 1:\n freq[A[start_k]] -= 1\n start_k += 1\n res += start_k - start + 1\n return res", "from collections import defaultdict\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n total = 0\n l1 = 0\n l2 = 0\n memo1 = defaultdict(int)\n memo2 = defaultdict(int)\n for (r, c) in enumerate(A):\n memo1[c] += 1\n memo2[c] += 1\n while len(memo1) > K:\n memo1[A[l1]] -= 1\n if memo1[A[l1]] == 0:\n del memo1[A[l1]]\n l1 += 1\n while len(memo2) >= K:\n memo2[A[l2]] -= 1\n if memo2[A[l2]] == 0:\n del memo2[A[l2]]\n l2 += 1\n total += l2 - l1\n return total", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def help(k):\n res = 0\n left = 0\n d = {}\n for (i, ele) in enumerate(A):\n d[ele] = d.get(ele, 0) + 1\n while len(d) > k:\n d[A[left]] -= 1\n if d[A[left]] == 0:\n del d[A[left]]\n left += 1\n res += i - left\n return res\n return help(K) - help(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atmost(k):\n i = 0\n res = 0\n d = defaultdict(int)\n for (j, a) in enumerate(A):\n if d[a] == 0:\n k -= 1\n d[a] += 1\n while k < 0:\n d[A[i]] -= 1\n if d[A[i]] == 0:\n k += 1\n i += 1\n res += j - i + 1\n return res\n return atmost(K) - atmost(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMost(A: List[int], K: int) -> int:\n d = collections.defaultdict(int)\n i = ret = 0\n for j in range(len(A)):\n d[A[j]] += 1\n while len(d) > K:\n d[A[i]] -= 1\n if d[A[i]] == 0:\n del d[A[i]]\n i += 1\n ret += j - i + 1\n return ret\n return atMost(A, K) - atMost(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def getAtMost(K):\n freq = defaultdict(int)\n subarray_count = 0\n left = 0\n for (right, num) in enumerate(A):\n freq[num] += 1\n while len(freq) > K:\n freq[A[left]] -= 1\n if freq[A[left]] == 0:\n del freq[A[left]]\n left += 1\n subarray_count += right - left + 1\n return subarray_count\n return getAtMost(K) - getAtMost(K - 1)", "from collections import defaultdict\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n if K == 0:\n return 0\n res1 = self.helper(A, K)\n res2 = self.helper(A, K - 1)\n return res1 - res2\n\ndef helper(a, k):\n if k == 0:\n return 0\n count = defaultdict(int)\n result = 0\n l = 0\n r = 0\n while r < len(a):\n count[a[r]] += 1\n while len(count) > k:\n count[a[l]] -= 1\n if count[a[l]] == 0:\n count.pop(a[l])\n l += 1\n result += r - l + 1\n r += 1\n return result", "def subarrayswithkdistinct(A, K):\n (cnt1, cnt2) = (dict(), dict())\n (res, i1, i2) = (0, 0, 0)\n for v in A:\n cnt1[v] = cnt1.get(v, 0) + 1\n cnt2[v] = cnt2.get(v, 0) + 1\n while len(cnt1) > K:\n cnt1[A[i1]] -= 1\n if cnt1[A[i1]] == 0:\n del cnt1[A[i1]]\n i1 += 1\n while len(cnt2) >= K:\n cnt2[A[i2]] -= 1\n if cnt2[A[i2]] == 0:\n del cnt2[A[i2]]\n i2 += 1\n res += i2 - i1\n return res\n\ndef subarrayswithkdistinct(A, K):\n (cnt1, cnt2) = (dict(), dict())\n (res, i1, i2) = (0, 0, 0)\n for v in A:\n cnt1[v] = cnt1.get(v, 0) + 1\n cnt2[v] = cnt2.get(v, 0) + 1\n while len(cnt1) > K:\n X = A[i1]\n cnt1[X] -= 1\n if cnt1[X] == 0:\n del cnt1[X]\n i1 += 1\n while len(cnt2) > K - 1:\n X = A[i2]\n cnt2[X] -= 1\n if cnt2[X] == 0:\n del cnt2[X]\n i2 += 1\n res += i2 - i1\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.at_most(A, K) - self.at_most(A, K - 1)\n\ndef at_most(A, K):\n if K == 0:\n return 0\n window = {}\n left = 0\n ret = 0\n for right in range(len(A)):\n window[A[right]] = window.get(A[right], 0) + 1\n while left < right and len(window) > K:\n window[A[left]] -= 1\n if window[A[left]] == 0:\n del window[A[left]]\n left += 1\n ret += right - left + 1\n return ret", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n res = 0\n left = right = 0\n window = Counter()\n while right < len(A) and len(window) < K:\n window[A[right]] += 1\n right += 1\n if len(window) < K:\n return 0\n while right < len(A) and len(window) == K:\n rmarker = right\n while right < len(A) and A[right] in window:\n right += 1\n rcount = right - rmarker + 1\n lmarker = left\n while window[A[left]] > 1:\n window[A[left]] -= 1\n left += 1\n lcount = left - lmarker + 1\n res += lcount * rcount\n window[A[left]] -= 1\n del window[A[left]]\n left += 1\n right = rmarker\n while right < len(A) and len(window) < K:\n window[A[right]] += 1\n right += 1\n while len(window) == K:\n window[A[left]] -= 1\n res += 1\n if not window[A[left]]:\n del window[A[left]]\n left += 1\n return res", "def helper(A, B):\n count = 0\n left = 0\n right = 0\n d = {}\n while right < len(A):\n if A[right] not in d:\n d[A[right]] = 0\n d[A[right]] += 1\n while len(d) > B:\n d[A[left]] -= 1\n if d[A[left]] == 0:\n d.pop(A[left])\n left += 1\n count += right - left + 1\n right += 1\n return count\n\ndef subarrayswithkdistinct(A: List[int], B: int) -> int:\n return self.helper(A, B) - self.helper(A, B - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def subarraysWithDictinctAtMost(A: List[int], K: int) -> int:\n (left, right) = (0, 0)\n ans = 0\n counter = dict()\n while right < len(A):\n if A[right] not in counter:\n counter[A[right]] = 0\n counter[A[right]] += 1\n while len(counter) > K:\n counter[A[left]] -= 1\n if counter[A[left]] == 0:\n counter.pop(A[left])\n left += 1\n ans += right - left + 1\n right += 1\n return ans\n return subarraysWithDictinctAtMost(A, K) - subarraysWithDictinctAtMost(A, K - 1)", "def atMostK(arr, k):\n d = {}\n (l, r) = (0, 0)\n count = 0\n while r < len(arr):\n if arr[r] not in d:\n d[arr[r]] = 0\n d[arr[r]] += 1\n while len(d) > k:\n d[arr[l]] -= 1\n if d[arr[l]] == 0:\n d.pop(arr[l])\n l += 1\n count += r - l + 1\n r += 1\n return count\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.atMostK(A, K) - self.atMostK(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMost(A, K):\n left = res = 0\n hash_map = {}\n for right in range(len(A)):\n hash_map[A[right]] = hash_map.get(A[right], 0) + 1\n while len(hash_map) > K:\n hash_map[A[left]] -= 1\n if hash_map[A[left]] == 0:\n del hash_map[A[left]]\n left += 1\n res += right - left + 1\n return res\n return atMost(A, K) - atMost(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n n = len(A)\n if n < K:\n return 0\n left = 0\n right = 0\n totalCount = 0\n dp = [0 for i in range(20001)]\n result = 0\n for right in range(n):\n if dp[A[right]] == 0:\n totalCount += 1\n dp[A[right]] += 1\n while totalCount >= K:\n if totalCount == K:\n result += 1\n dp[A[left]] -= 1\n if dp[A[left]] == 0:\n totalCount -= 1\n left += 1\n while totalCount <= K and left > 0:\n left -= 1\n if dp[A[left]] == 0:\n totalCount += 1\n dp[A[left]] += 1\n return result", "from collections import defaultdict\n\ndef subarrayswithkdistinct(A, K):\n\n def atMostK(K):\n (cnt, res, i) = (defaultdict(int), 0, 0)\n for (j, val) in enumerate(A):\n cnt[val] += 1\n while len(cnt) > K:\n X = A[i]\n cnt[X] -= 1\n if not cnt[X]:\n cnt.pop(X)\n i += 1\n res += j - i + 1\n return res\n return atMostK(K) - atMostK(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMost(k):\n counter = collections.defaultdict(int)\n i = res = 0\n for (j, v) in enumerate(A):\n counter[v] += 1\n while len(counter) > k:\n counter[A[i]] -= 1\n if counter[A[i]] == 0:\n del counter[A[i]]\n i += 1\n res += j - i + 1\n return res\n return atMost(K) - atMost(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.atMost(A, K) - self.atMost(A, K - 1)\n\ndef atMost(A, K):\n if K == 0:\n return 0\n (hi, res) = (0, 0)\n n = len(A)\n count = collections.defaultdict(int)\n for lo in range(n):\n while hi < n and (len(count) < K or A[hi] in count):\n count[A[hi]] += 1\n hi += 1\n res += hi - lo\n count[A[lo]] -= 1\n if count[A[lo]] == 0:\n count.pop(A[lo])\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def at_most_k(arr, k):\n start = 0\n counter = Counter()\n uniques = 0\n res = 0\n for i in range(len(A)):\n counter[A[i]] += 1\n if counter[A[i]] == 1:\n uniques += 1\n while uniques > k:\n counter[A[start]] -= 1\n if counter[A[start]] == 0:\n uniques -= 1\n start += 1\n res += i - start\n return res\n return at_most_k(A, K) - at_most_k(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n keyCounter = defaultdict(int)\n ALen = len(A)\n l = 0\n r = 0\n ans = 0\n KNow = 0\n while r <= ALen:\n if KNow == K:\n ans += 1\n temp = 0\n while r + temp < ALen and keyCounter[A[r + temp]] > 0:\n ans += 1\n temp += 1\n if keyCounter[A[l]] > 0:\n keyCounter[A[l]] -= 1\n if keyCounter[A[l]] == 0:\n KNow -= 1\n l += 1\n elif KNow < K:\n if r == ALen:\n return ans\n if keyCounter[A[r]] == 0:\n KNow += 1\n keyCounter[A[r]] += 1\n r += 1\n else:\n if keyCounter[A[l]] > 0:\n keyCounter[A[l]] -= 1\n if keyCounter[A[l]] == 0:\n KNow -= 1\n l += 1\n return ans", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def longest_with_atmostk(s, k):\n start = 0\n counts = defaultdict(int)\n n_chars = 0\n max_len = 0\n for i in range(len(s)):\n if counts[s[i]] == 0:\n n_chars += 1\n counts[s[i]] += 1\n while n_chars > k:\n if counts[s[start]] > 0:\n counts[s[start]] -= 1\n if counts[s[start]] == 0:\n n_chars -= 1\n start += 1\n max_len += i - start + 1\n return max_len\n return longest_with_atmostk(A, K) - longest_with_atmostk(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.atMost(A, K) - self.atMost(A, K - 1)\n\ndef atMost(A, k):\n left = res = 0\n freq = collections.Counter()\n for right in range(len(A)):\n if freq[A[right]] == 0:\n k -= 1\n freq[A[right]] += 1\n while k < 0:\n freq[A[left]] -= 1\n if freq[A[left]] == 0:\n k += 1\n left += 1\n res += right - left + 1\n return res", "def subarrayswithkdistinct(A, K):\n\n def atMostK(A, K):\n count = collections.Counter()\n (res, l, window_count) = (0, 0, 0)\n for (r, c) in enumerate(A):\n if count[c] == 0:\n window_count += 1\n count[c] += 1\n while window_count > K:\n count[A[l]] -= 1\n if count[A[l]] == 0:\n window_count -= 1\n l += 1\n res += r - l + 1\n return res\n return atMostK(A, K) - atMostK(A, K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.helper(A, K) - self.helper(A, K - 1)\n\ndef helper(A, K):\n counter = collections.Counter()\n p1 = p2 = 0\n res = 0\n while p2 < len(A):\n if counter[A[p2]] == 0:\n K -= 1\n counter[A[p2]] += 1\n while K < 0:\n counter[A[p1]] -= 1\n if counter[A[p1]] == 0:\n K += 1\n p1 += 1\n p2 += 1\n res += p2 - p1\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMost(K):\n (res, lo, seen) = (0, 0, Counter())\n for hi in range(len(A)):\n if seen[A[hi]] == 0:\n K -= 1\n seen[A[hi]] += 1\n while K < 0:\n seen[A[lo]] -= 1\n if seen[A[lo]] == 0:\n K += 1\n lo += 1\n res += hi - lo + 1\n return res\n return atMost(K) - atMost(K - 1)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n (counter1, counter2) = (collections.Counter(), collections.Counter())\n slow = fast = res = 0\n for a in A:\n (counter1[a], counter2[a]) = (counter1[a] + 1, counter2[a] + 1)\n while len(counter2) == K:\n counter2[A[fast]] -= 1\n if not counter2[A[fast]]:\n del counter2[A[fast]]\n fast += 1\n while len(counter1) > K:\n counter1[A[slow]] -= 1\n if not counter1[A[slow]]:\n del counter1[A[slow]]\n slow += 1\n res += fast - slow\n return res", "import collections\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n counter = collections.defaultdict(int)\n result = 0\n start = startK = 0\n for (high, num) in enumerate(A):\n counter[num] += 1\n if len(counter) == K + 1:\n del counter[A[startK]]\n startK += 1\n start = startK\n if len(counter) == K:\n while counter[A[startK]] > 1:\n counter[A[startK]] -= 1\n startK += 1\n result += startK - start + 1\n return result", "def subarraysWithAtMostK(A: List[int], K: int) -> int:\n result = i = 0\n count = collections.Counter()\n for j in range(len(A)):\n if count[A[j]] == 0:\n K -= 1\n count[A[j]] += 1\n while K < 0:\n count[A[i]] -= 1\n if count[A[i]] == 0:\n K += 1\n i += 1\n result += j - i + 1\n return result\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.subarraysWithAtMostK(A, K) - self.subarraysWithAtMostK(A, K - 1)", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n W1 = Counter()\n W2 = Counter()\n l1 = 0\n l2 = 0\n res = 0\n for i in range(len(A)):\n W1[A[i]] += 1\n W2[A[i]] += 1\n while len(W1) > K:\n W1[A[l1]] -= 1\n if W1[A[l1]] == 0:\n del W1[A[l1]]\n l1 += 1\n while len(W2) > K - 1:\n W2[A[l2]] -= 1\n if W2[A[l2]] == 0:\n del W2[A[l2]]\n l2 += 1\n res += l2 - l1\n return res", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n window1 = Counter()\n window2 = Counter()\n l1 = 0\n l2 = 0\n total = 0\n for (r, c) in enumerate(A):\n window1[c] += 1\n window2[c] += 1\n while len(window1) > K:\n window1[A[l1]] -= 1\n if window1[A[l1]] == 0:\n del window1[A[l1]]\n l1 += 1\n while len(window2) > K - 1:\n window2[A[l2]] -= 1\n if window2[A[l2]] == 0:\n del window2[A[l2]]\n l2 += 1\n total += l2 - l1\n return total", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.atMostK(A, K) - self.atMostK(A, K - 1)\n\ndef atMostK(A, k):\n start = 0\n end = 0\n res = 0\n chars = collections.Counter()\n distinct = 0\n while end < len(A):\n if chars[A[end]] == 0:\n distinct += 1\n chars[A[end]] += 1\n while distinct > k:\n chars[A[start]] -= 1\n if chars[A[start]] == 0:\n distinct -= 1\n start += 1\n res += end - start + 1\n end += 1\n return res", "def _identify_limit(A, current_limit, K, char_count_after_limit):\n char_count_after_limit = {k: v for (k, v) in char_count_after_limit.items()}\n unique_chars = {i for i in char_count_after_limit if char_count_after_limit[i] > 0}\n while len(unique_chars) == K:\n temp_char = A[current_limit]\n char_count_after_limit[temp_char] = char_count_after_limit[temp_char] - 1\n if char_count_after_limit[temp_char] == 0:\n unique_chars.remove(temp_char)\n current_limit += 1\n char_count_after_limit[A[current_limit - 1]] = char_count_after_limit[A[current_limit - 1]] + 1\n return (current_limit - 1, char_count_after_limit)\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n (counter1, counter2) = (collections.Counter(), collections.Counter())\n slow = fast = res = 0\n for (_, a) in enumerate(A):\n (counter1[a], counter2[a]) = (counter1[a] + 1, counter2[a] + 1)\n while len(counter2) == K:\n counter2[A[fast]] -= 1\n if not counter2[A[fast]]:\n del counter2[A[fast]]\n fast += 1\n while len(counter1) > K:\n counter1[A[slow]] -= 1\n if not counter1[A[slow]]:\n del counter1[A[slow]]\n slow += 1\n res += fast - slow\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n sum = 0\n begin = 0\n end = 0\n s = collections.defaultdict(int)\n lA = len(A)\n for i in range(lA):\n if len(s) >= K:\n s[A[i]] += 1\n if s[A[i]] > 1:\n newend = end\n while s[A[newend]] > 1:\n s[A[newend]] -= 1\n newend += 1\n end = newend\n else:\n begin = end\n while s[A[begin]] > 1:\n s[A[begin]] -= 1\n begin += 1\n s[A[begin]] -= 1\n begin += 1\n end = begin\n while s[A[end]] > 1:\n s[A[end]] -= 1\n end += 1\n sum += end - begin + 1\n else:\n s[A[i]] += 1\n if len(s) == K:\n while s[A[end]] > 1:\n s[A[end]] -= 1\n end += 1\n sum += end - begin + 1\n return sum", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMostK(k):\n count = Counter()\n ans = left = 0\n for (i, a) in enumerate(A):\n if count[a] == 0:\n k -= 1\n count[a] += 1\n while k < 0:\n count[A[left]] -= 1\n if count[A[left]] == 0:\n k += 1\n left += 1\n ans += i - left + 1\n return ans\n return atMostK(K) - atMostK(K - 1)", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.helper(A, K) - self.helper(A, K - 1)\n\ndef helper(A, K):\n currSum = 0\n d = Counter()\n i = 0\n for j in range(len(A)):\n d[A[j]] += 1\n while len(d) > K:\n d[A[i]] -= 1\n if not d[A[i]]:\n del d[A[i]]\n i += 1\n currSum += j - i + 1\n return currSum", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def at_most(x):\n left = 0\n counts = Counter()\n res = 0\n for (right, num) in enumerate(A):\n counts[num] += 1\n while len(counts) > x:\n counts[A[left]] -= 1\n if counts[A[left]] == 0:\n del counts[A[left]]\n left += 1\n res += right - left + 1\n return res\n return at_most(K) - at_most(K - 1)", "def subarrayswithkdistinct(A, K):\n return self.atMostK(A, K) - self.atMostK(A, K - 1)\n\ndef atMostK(s, k):\n if not s:\n return 0\n N = len(s)\n (left, right) = (0, 0)\n ret = 0\n counter = collections.Counter()\n counter[s[right]] += 1\n while right < N:\n if len(counter) > k:\n counter[s[left]] -= 1\n if counter[s[left]] == 0:\n del counter[s[left]]\n left += 1\n else:\n right += 1\n ret += right - left\n if right < N:\n counter[s[right]] += 1\n return ret", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def at_most(K):\n window = Counter()\n left = right = 0\n res = 0\n while right < len(A):\n window[A[right]] += 1\n while len(window) > K:\n window[A[left]] -= 1\n if not window[A[left]]:\n del window[A[left]]\n left += 1\n res += right - left + 1\n right += 1\n return res\n return at_most(K) - at_most(K - 1)", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n (equalCt, lessCt) = (Counter(), Counter())\n (equalPt, lessPt) = (0, 0)\n res = 0\n\n def add_to_counter(x, co):\n co[x] += 1\n\n def subtr_from_counter(x, co):\n co[x] -= 1\n if co[x] == 0:\n del co[x]\n for (right, num) in enumerate(A):\n add_to_counter(num, equalCt)\n add_to_counter(num, lessCt)\n while len(equalCt) > K:\n subtr_from_counter(A[equalPt], equalCt)\n equalPt += 1\n while len(lessCt) >= K:\n subtr_from_counter(A[lessPt], lessCt)\n lessPt += 1\n res += lessPt - equalPt\n return res", "from collections import Counter\n\ndef subarraysWithAtMostK(arr: list, k: int) -> int:\n start = 0\n counter = Counter()\n res = 0\n for end in range(len(arr)):\n num = arr[end]\n counter[num] += 1\n while len(counter) > k:\n to_remove = arr[start]\n counter[to_remove] -= 1\n if counter[to_remove] == 0:\n del counter[to_remove]\n start += 1\n res += end - start + 1\n return res\n\ndef subarrayswithkdistinct(arr: list, k: int) -> int:\n return subarraysWithAtMostK(arr, k) - subarraysWithAtMostK(arr, k - 1)\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return subarrayswithkdistinct(A, K)", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def atMost(A: List[int], K: int):\n cache = collections.Counter()\n (res, i) = (0, 0)\n for j in range(len(A)):\n cache[A[j]] += 1\n while len(cache) > K:\n cache[A[i]] -= 1\n if cache[A[i]] == 0:\n del cache[A[i]]\n i += 1\n res += j - i + 1\n return res\n return atMost(A, K) - atMost(A, K - 1)", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n window = Counter()\n res = 0\n left = right = 0\n while True:\n while right < len(A) and len(window) < K:\n window[A[right]] += 1\n right += 1\n if len(window) < K:\n return res\n j = right\n while j < len(A) and A[j] in window:\n j += 1\n res += j - right + 1\n window[A[left]] -= 1\n if not window[A[left]]:\n del window[A[left]]\n left += 1\n return res", "def __init__():\n self.counter = Counter()\n self.unique = 0\n\ndef add(value: int):\n self.counter[value] += 1\n if self.counter[value] == 1:\n self.unique += 1\n\ndef remove(value: int):\n self.counter[value] -= 1\n if self.counter[value] == 0:\n self.unique -= 1\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n window1 = Window()\n window2 = Window()\n left1 = left2 = answer = 0\n for right in A:\n window1.add(right)\n window2.add(right)\n while window1.unique > K:\n window1.remove(A[left1])\n left1 += 1\n while window2.unique >= K:\n window2.remove(A[left2])\n left2 += 1\n answer += left2 - left1\n return answer", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.subarraysWithAtmostKDistinct(A, K) - self.subarraysWithAtmostKDistinct(A, K - 1)\n\ndef subarraysWithAtmostKDistinct(A, K):\n (l, r, count, res) = (0, 0, 0, 0)\n hashmap = [0] * 20001\n while r < len(A):\n hashmap[A[r]] += 1\n if hashmap[A[r]] == 1:\n count += 1\n while count > K:\n hashmap[A[l]] -= 1\n if hashmap[A[l]] == 0:\n count -= 1\n l += 1\n res += r - l + 1\n r += 1\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def remove(m, n):\n if m[n] == 1:\n del m[n]\n else:\n m[n] -= 1\n (m1, m2) = (collections.Counter(), collections.Counter())\n res = 0\n i1 = i2 = -1\n for (i0, n) in enumerate(A):\n while i1 + 1 < len(A) and len(m1) < K:\n i1 += 1\n m1[A[i1]] += 1\n if len(m1) < K:\n return res\n while i2 + 1 < len(A) and len(m2) < K + 1:\n i2 += 1\n m2[A[i2]] += 1\n res += i2 - i1 + int(len(m2) == K)\n remove(m1, n)\n remove(m2, n)\n return res", "from collections import Counter\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n return self.subarraysWithAtMostKDistinct(A, K) - self.subarraysWithAtMostKDistinct(A, K - 1)\n\ndef subarraysWithAtMostKDistinct(A, K):\n window = Counter()\n j = 0\n res = 0\n for i in range(len(A)):\n c = A[i]\n window[c] += 1\n while len(window) > K:\n last = A[j]\n window[last] -= 1\n if window[last] == 0:\n del window[last]\n j += 1\n res += i - j + 1\n return res", "from collections import Counter\n\ndef solve(A, K):\n count = Counter()\n front = iter(A)\n ans = 0\n size = 0\n for k in A:\n count[k] += 1\n size += 1\n while len(count) > K:\n key = next(front)\n count[key] -= 1\n size -= 1\n if count[key] == 0:\n del count[key]\n ans += size\n return ans\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n cx = Counter()\n cy = Counter()\n fx = iter(A)\n fy = iter(A)\n sx = 0\n sy = 0\n ans = 0\n for k in A:\n cx[k] += 1\n cy[k] += 1\n sx += 1\n sy += 1\n while len(cx) > K:\n key = next(fx)\n cx[key] -= 1\n sx -= 1\n if cx[key] == 0:\n del cx[key]\n while len(cy) > K - 1:\n key = next(fy)\n cy[key] -= 1\n sy -= 1\n if cy[key] == 0:\n del cy[key]\n ans += sx - sy\n return ans", "def subarrayswithkdistinct(A, K):\n return self.atMostK(A, K) - self.atMostK(A, K - 1)\n\ndef atMostK(A, K):\n count = collections.Counter()\n res = left = right = distinct = 0\n while right < len(A):\n count[A[right]] += 1\n if count[A[right]] == 1:\n distinct += 1\n while distinct > K:\n count[A[left]] -= 1\n if count[A[left]] == 0:\n distinct -= 1\n left += 1\n res += right - left + 1\n right += 1\n return res", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n (good_start, bad_start) = (-1, -1)\n (good_count, bad_count) = ({}, {})\n\n def add(count, element):\n if element not in count:\n count[element] = 0\n count[element] += 1\n\n def remove(count, element):\n count[element] -= 1\n if count[element] == 0:\n del count[element]\n\n def find_good_start(A, K, cur_pos, index, good_count):\n if len(good_count) == K:\n return index\n cur = index\n while cur < cur_pos and len(good_count) > K:\n cur += 1\n remove(good_count, A[cur])\n return cur\n total = 0\n for i in range(len(A)):\n cur = A[i]\n add(good_count, cur)\n add(bad_count, cur)\n if len(good_count) >= K:\n good_start = find_good_start(A, K, i, good_start, good_count)\n bad_start = find_good_start(A, K - 1, i, bad_start, bad_count)\n if len(good_count) == K and len(bad_count) == K - 1:\n total += bad_start - good_start\n return total", "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n (m1, m2) = (collections.Counter(), collections.Counter())\n\n def remove(m, n):\n m[n] -= 1\n if not m[n]:\n del m[n]\n res = 0\n left = right = -1\n for (i, n) in enumerate(A):\n while left < len(A) - 1 and len(m1) < K:\n left += 1\n m1[A[left]] += 1\n if len(m1) < K:\n return res\n while right < len(A) - 1 and len(m2) <= K:\n right += 1\n m2[A[right]] += 1\n res += right - left + (len(m2) == K)\n remove(m1, n)\n remove(m2, n)\n return res", "from collections import defaultdict\n\ndef subarrayswithkdistinct(A: List[int], K: int) -> int:\n\n def subArray(k):\n right = 0\n left = 0\n freq = collections.defaultdict(int)\n count = 0\n while right < len(A):\n freq[A[right]] += 1\n right += 1\n while len(freq) > k:\n freq[A[left]] -= 1\n if freq[A[left]] == 0:\n del freq[A[left]]\n left += 1\n count += right - left\n return count\n output = 0\n output += subArray(K) - subArray(K - 1)\n return output"], "starter_code": "def subarrayswithkdistinct(A: List[int], K: int) -> int:\n", "input_output": {"fn_name": "subarraysWithKDistinct", "inputs": [[[1, 2, 1, 2, 3], 2]], "outputs": [7]}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Counting", "Sliding Window", "Hash Table"], "name": null, "source": "leetcode", "tags": ["Data structures", "Amortized analysis", "Mathematics"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://leetcode.com/problems/subarrays-with-k-different-integers/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "subarrayswithkdistinct", "task_id": "TACO_lite/409", "example": [[[[1, 2, 1, 2, 3], 2], [[1, 2, 1, 3, 4], 3]], ["7", "3"]]} +{"requirement": "Santa puts all the presents into the huge sack. In order to let his reindeers rest a bit, he only takes as many reindeers with him as he is required to do. The others may take a nap.\n\nTwo reindeers are always required for the sleigh and Santa himself. Additionally he needs 1 reindeer per 30 presents. As you know, Santa has 8 reindeers in total, so he can deliver up to 180 presents at once (2 reindeers for Santa and the sleigh + 6 reindeers with 30 presents each).\n\nComplete the function `reindeers()`, which takes a number of presents and returns the minimum numbers of required reindeers. If the number of presents is too high, throw an error.\n\nExamles:\n\n```python\nreindeer(0) # must return 2\nreindeer(1) # must return 3\nreindeer(30) # must return 3\nreindeer(200) # must throw an error\n```", "solutions": ["from math import ceil\n\ndef reindeer(presents):\n if presents > 180:\n raise ValueError('Too many presents')\n return ceil(presents / 30.0) + 2", "def reindeer(presents):\n assert presents <= 180\n return 2 + presents // 30 + (1 if presents % 30 else 0)", "from math import ceil\n\ndef reindeer(presents):\n assert presents < 181\n return ceil(presents / 30.0) + 2", "def reindeer(presents):\n assert presents <= 180\n return 2 + (presents + 29) // 30", "from math import ceil\n\ndef reindeer(presents):\n if presents > 180:\n raise ValueError\n else:\n return 2 + ceil(presents / 30.0)", "from math import ceil\n\ndef reindeer(presents):\n if presents > 180:\n raise Exception('Too many presents')\n return 2 + ceil(presents / 30)", "from math import ceil\n\ndef reindeer(presents):\n assert 0 <= presents <= 180\n return int(2 + ceil(presents / 30.0))", "def reindeer(presents):\n if presents > 180:\n raise Exception('Error')\n return 2 + int((presents + 29) / 30)", "import math\n\ndef reindeer(presents):\n p = math.ceil(presents / 30)\n if p > 6:\n raise ValueError('Error')\n else:\n return p + 2"], "starter_code": "def reindeer(presents):\n", "input_output": {"fn_name": "reindeer", "inputs": [[0], [1], [5], [30], [31], [60], [61], [90], [91], [120], [121], [150], [151], [180]], "outputs": [[2], [3], [3], [3], [4], [4], [5], [5], [6], [6], [7], [7], [8], [8]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/52ad1db4b2651f744d000394", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "reindeer", "task_id": "TACO_lite/336", "example": [[[0], [1], [30]], ["2", "3", "3"]]} +{"requirement": "A generalization of B\u00e9zier surfaces, called the S-patch, uses an interesting scheme for indexing its control points.\n\nIn the case of an n-sided surface of degree d, each index has n non-negative integers that sum to d, and all possible configurations are used.\n\nFor example, for a 3-sided quadratic (degree 2) surface the control points are:\n\n> indices 3 2 => [[0,0,2],[0,1,1],[0,2,0],[1,0,1],[1,1,0],[2,0,0]]\n\nGiven the degree and the number of sides, generate all control point indices.\nThe order of the indices in the list can be arbitrary, so for the above example\n\n> [[1,1,0],[2,0,0],[0,0,2],[0,2,0],[0,1,1],[1,0,1]]\n\nis also a good solution.", "solutions": ["def gen(n, d):\n if d == 0 or n == 1:\n yield ([d] * n)\n else:\n for x in range(d + 1):\n for y in gen(n - 1, d - x):\n yield ([x] + y)\n\ndef indices(n, d):\n return list(gen(n, d))", "import itertools\n\ndef indices(n, d):\n return list(recurse(n, d, []))\n\ndef recurse(n, d, prefix):\n if n == 0:\n return prefix\n if n == 1:\n return [prefix + [d]]\n res = []\n for i in range(d + 1):\n res += recurse(n - 1, d - i, prefix + [i])\n return res", "def indices(n, d):\n return [[r] + point for r in range(d + 1) for point in indices(n - 1, d - r)] if n > 1 else [[d]]", "def indices(n, d):\n result = []\n temp = []\n\n def tt(n, d, temp):\n if d == 1:\n result.extend([temp + [n]])\n return 0\n for i in range(0, n + 1):\n aa = temp + [i]\n tt(n - i, d - 1, aa)\n tt(d, n, temp)\n return result", "def indices(n, d):\n if n == 1:\n return [[d]]\n if d == 0:\n return [[0 for i in range(n)]]\n sols = []\n for i in range(d + 1):\n sols += [subsol + [i] for subsol in indices(n - 1, d - i)]\n return sols\n raise NotImplementedError('todo')", "def indices(n, d):\n result = ([i] for i in range(d + 1))\n for iteration in range(n - 1):\n result = (i + [j] for i in result for j in range(d + 1) if sum(i) + j <= d)\n return list(filter(lambda r: sum(r) == d, result))", "def indices(n, d):\n if n == 1:\n return [[d]]\n result = []\n for i in range(d + 1):\n for x in indices(n - 1, d - i):\n result.append([i] + x)\n return result", "def indices(n, d):\n if d < 0:\n return []\n elif n == 1:\n return [[d]]\n elif n == 2:\n return [[i, d - i] for i in range(d + 1)]\n else:\n return [[i] + p for i in range(d + 1) for p in indices(n - 1, d - i)]", "def indices(n, d):\n from itertools import combinations_with_replacement\n lst = []\n for c in combinations_with_replacement(range(n), d):\n base = [0] * n\n for i in c:\n base[i] += 1\n lst.append(base)\n return lst"], "starter_code": "def indices(n, d):\n", "input_output": {"fn_name": "indices", "inputs": [[1, 0], [3, 0]], "outputs": [[[[0]]], [[[0, 0, 0]]]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/553291f451ab4fbcdc0001c6", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "indices", "task_id": "TACO_lite/295", "example": [[[3, 2]], ["[[0, 0, 2], [0, 1, 1], [0, 2, 0], [1, 0, 1], [1, 1, 0], [2, 0, 0]]"]]} +{"requirement": "The Ackermann function is a famous function that played a big role in computability theory as the first example of a total computable function that is not primitive recursive.\n\nSince then the function has been a bit simplified but is still of good use. Due to its definition in terms of extremely deep recursion it can be used as a benchmark of a compiler's ability to optimize recursion. \n\nThe goal of this kata is to code a function which will be given two inputs, m and n, and will return the Ackermann number A(m,n) defined by:\n\n```\nA(m,n) = n+1 if m=0 \nA(m,n) = A(m-1,1) if m>0 , n=0\nA(m,n) = A(m-1,A(m,n-1)) if m,n > 0\n```\n\nm,n should be non-negative integers, the function should return null (Javascript), None (Python), or nil (Ruby) for other type, non-integer and negative numbers. In C, input is restricted to integer type.", "solutions": ["from numbers import Number\n\ndef ackermann(m, n):\n if isinstance(n, Number) and isinstance(m, Number):\n if m >= 0 and n >= 0:\n return ackermann_Aux(m, n)\n return None\n\ndef ackermann_Aux(m, n):\n if m == 0:\n return n + 1\n if m > 0:\n if n == 0:\n return ackermann_Aux(m - 1, 1)\n if n > 0:\n return ackermann_Aux(m - 1, ackermann_Aux(m, n - 1))", "def ackermann(m, n):\n if type(m) is not int or type(n) is not int:\n return None\n if m < 0 or n < 0:\n return None\n if m == 0:\n return n + 1\n elif n == 0:\n return ackermann(m - 1, 1)\n else:\n return ackermann(m - 1, ackermann(m, n - 1))", "def ackermann(m, n):\n return n + 1 if m == 0 else ackermann(m - 1, 1) if n == 0 else ackermann(m - 1, ackermann(m, n - 1))", "def val(v):\n return isinstance(v, int) and v >= 0\n\ndef ackermann(m, n):\n if not val(m) or not val(n):\n return None\n if m == 0:\n return n + 1\n elif m > 0 and n == 0:\n return ackermann(m - 1, 1)\n return ackermann(m - 1, ackermann(m, n - 1))", "def ackermann(m, n):\n try:\n if m == 0 and n >= 0:\n return n + 1\n if m > 0 and n == 0:\n return ackermann(m - 1, 1)\n if m > 0 and n > 0:\n return ackermann(m - 1, ackermann(m, n - 1))\n except:\n return None", "def deepAck(m, n):\n return n + 1 if m == 0 else deepAck(m - 1, 1) if n == 0 else deepAck(m - 1, deepAck(m, n - 1))\n\ndef ackermann(m, n):\n return None if not isinstance(m, int) or not isinstance(n, int) or m < 0 or (n < 0) else deepAck(m, n)", "def ackermann(m, n):\n if m:\n if n:\n return ackermann(m - 1, ackermann(m, n - 1))\n return ackermann(m - 1, 1)\n return n + 1", "def ackermann(m, n):\n return (lambda m, n, s=lambda m, n, f: n + 1 if m == 0 and n >= 0 else f(m - 1, 1, f) if m > 0 and n == 0 else f(m - 1, f(m, n - 1, f), f) if m > 0 and n > 0 else None: s(m, n, s))(m, n)"], "starter_code": "def ackermann(m,n):\n", "input_output": {"fn_name": "Ackermann", "inputs": [[1, 1], [4, 0], [3, 3]], "outputs": [[3], [13], [61]]}, "difficulty": "EASY", "raw_tags": ["Recursion", "Algorithms", "Mathematics"], "name": null, "source": "codewars", "tags": ["Mathematics", "Complete search"], "skill_types": ["Complete search"], "url": "https://www.codewars.com/kata/53ad69892a27079b34000bd9", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "ackermann", "task_id": "TACO_lite/358", "example": [[[0, 0], [2, 3]], ["1", "9"]]} +{"requirement": "Given an array, Arr of N numbers, and another number target, find three integers in the array such that the sum is closest to the target. Return the sum of the three integers.\nNote: If there are multiple solutions, print the maximum one.\nExample 1:\nInput:\nN = 6, target = 2\nA[] = {-7,9,8,3,1,1}\nOutput: 2\nExplanation: There is one triplet with sum\n2 in the array. Triplet elements are -7,8,\n1 whose sum is 2.\nExample 2:\nInput:\nN = 4, target = 13\nA[] = {5,2,7,5}\nOutput: 14\nExplanation: There is one triplet with sum\n12 and other with sum 14 in the array.\nTriplet elements are 5, 2, 5 and 2, 7, 5\nrespectively. Since abs(13-12) ==\nabs(13-14) maximum triplet sum will be\npreferred i.e 14.\nYour Task:\nComplete threeSumClosest() function and return the expected answer.\nExpected Time Complexity: O(N*N).\nExpected Auxiliary Space: O(1).\nConstraints:\n3 \u2264 N \u2264 10^{3}\n-10^{5} \u2264 A[i] \u2264 10^{5}\n1 \u2264 target \u2264 10^{5}", "solutions": ["def threesumclosest(arr, target):\n arr.sort()\n r = sum(arr[:3])\n for i in range(len(arr) - 2):\n s = i + 1\n l = len(arr) - 1\n while s < l:\n su = arr[i] + arr[s] + arr[l]\n if abs(target - su) < abs(target - r):\n r = su\n elif abs(target - su) == abs(target - r):\n r = max(r, su)\n if su < target:\n s += 1\n else:\n l -= 1\n return r", "def threesumclosest(arr, target):\n arr.sort()\n n = len(arr)\n ans = []\n temp = []\n for i in range(n - 2):\n a = i + 1\n b = n - 1\n while a < b:\n x = arr[i] + arr[a] + arr[b]\n if x == target:\n return target\n elif x > target:\n ans.append(x)\n temp.append(abs(x - target))\n b -= 1\n else:\n ans.append(x)\n temp.append(abs(x - target))\n a += 1\n t1 = min(temp) + target\n t2 = target - min(temp)\n if t1 in ans:\n return t1\n return t2", "def threesumclosest(arr, target):\n n = len(arr)\n arr = sorted(arr)\n minDiff = 1000000007\n res = -1000000007\n for i in range(n):\n sp = i + 1\n ep = n - 1\n while sp < ep:\n sum = arr[i] + arr[sp] + arr[ep]\n curDiff = abs(target - sum)\n if curDiff == minDiff:\n res = max(res, sum)\n elif curDiff < minDiff:\n minDiff = curDiff\n res = sum\n if sum == target:\n break\n elif sum > target:\n ep -= 1\n else:\n sp += 1\n return res", "def threesumclosest(arr, target):\n arr.sort()\n N = len(arr)\n Sum = 10000000000.0\n for i in range(N - 2):\n a = arr[i]\n L = i + 1\n R = N - 1\n while L < R:\n temp = a + arr[L] + arr[R]\n if temp == target:\n return target\n elif temp > target:\n R -= 1\n else:\n L += 1\n if abs(temp - target) < abs(Sum - target):\n Sum = temp\n elif abs(temp - target) == abs(Sum - target) and temp > Sum:\n Sum = temp\n return Sum", "def __init__():\n self.INT_MAX = 1000000\n\ndef threesumclosest(array, target):\n abs1 = ans2 = self.INT_MAX\n N = len(array)\n array.sort()\n result = dict()\n for i in range(N - 2):\n start = i + 1\n end = N - 1\n while start < end:\n temp = array[i] + array[start] + array[end]\n if temp == target:\n return temp\n elif temp > target:\n if abs(temp - target) < ans2:\n ans2 = abs(temp - target)\n ans1 = temp\n elif abs(temp - target) == ans2:\n ans1 = max(ans1, temp)\n end -= 1\n else:\n if abs(temp - target) < ans2:\n ans1 = temp\n ans2 = abs(temp - target)\n elif abs(temp - target) == ans2:\n ans1 = max(ans1, temp)\n start += 1\n return ans1", "def threesumclosest(arr, target):\n arr.sort()\n sum = 0\n result = target * 3\n for x in range(len(arr) - 2):\n start = x + 1\n end = len(arr) - 1\n while start < end:\n sum = arr[x] + arr[start] + arr[end]\n if abs(target - sum) == abs(target - result):\n result = max(sum, result)\n elif abs(target - sum) < abs(target - result):\n result = sum\n if sum < target:\n start += 1\n else:\n end -= 1\n return result", "def threesumclosest(arr, target):\n arr.sort()\n ans = 0\n diff = float('inf')\n for i in range(n - 2):\n j = i + 1\n k = len(arr) - 1\n while j < k:\n if arr[i] + arr[j] + arr[k] == target:\n return target\n if abs(arr[i] + arr[j] + arr[k] - target) < abs(target - diff):\n diff = arr[i] + arr[j] + arr[k]\n if abs(arr[i] + arr[j] + arr[k] - target) == abs(target - diff):\n diff = max(arr[i] + arr[j] + arr[k], diff)\n if arr[i] + arr[j] + arr[k] > target:\n k -= 1\n else:\n j += 1\n return diff", "def threesumclosest(arr, target):\n cd = float('inf')\n arr.sort()\n for i in range(n - 2):\n left = i + 1\n right = n - 1\n while left < right:\n summ = arr[i] + arr[left] + arr[right]\n if summ == target:\n return target\n elif summ > target:\n right -= 1\n else:\n left += 1\n d = abs(target - summ)\n if d < cd:\n cd = d\n ret = summ\n elif d == cd:\n ret = max(ret, summ)\n return ret", "def threesumclosest(arr, target):\n clss = float('inf')\n arr.sort()\n for i in range(n - 2):\n left = i + 1\n right = n - 1\n while left < right:\n curs = arr[i] + arr[left] + arr[right]\n if curs == target:\n return target\n elif curs > target:\n right -= 1\n else:\n left += 1\n if abs(curs - target) < abs(clss - target):\n clss = curs\n elif abs(curs - target) == abs(clss - target) and curs > clss:\n clss = curs\n return clss", "def threesumclosest(arr, target):\n n = len(arr)\n if n == 3:\n return sum(arr)\n ans = -float('inf')\n arr.sort()\n for i in range(n - 2):\n start = i + 1\n end = n - 1\n while start < end:\n summ = arr[i] + arr[start] + arr[end]\n if target == summ:\n return target\n if abs(target - summ) < abs(target - ans):\n ans = summ\n elif abs(target - summ) == abs(target - ans):\n ans = max(summ, ans)\n if summ > target:\n end -= 1\n else:\n start += 1\n return ans", "import sys\n\ndef threesumclosest(arr, target):\n maxi = sys.maxsize\n ans = 0\n arr.sort()\n for i in range(len(arr) - 2):\n l = i + 1\n r = len(arr) - 1\n while l < r:\n sumi = arr[i] + arr[l] + arr[r]\n if sumi == target:\n return target\n if abs(sumi - target) < abs(target - maxi):\n maxi = sumi\n if abs(sumi - target) == abs(target - maxi):\n maxi = max(sumi, maxi)\n if sumi > target:\n r -= 1\n else:\n l += 1\n return maxi", "def threesumclosest(arr, target):\n arr.sort()\n minsum = 10 ** 9\n ans = 0\n for i in range(len(arr)):\n first = arr[i]\n start = i + 1\n end = n - 1\n while start < end:\n summ = first + arr[start] + arr[end]\n if summ == target:\n return summ\n if abs(target - summ) < abs(target - minsum):\n minsum = summ\n if abs(target - summ) == abs(target - minsum):\n minsum = max(summ, minsum)\n if summ > target:\n end -= 1\n else:\n start += 1\n return minsum", "def threesumclosest(arr, target):\n arr.sort()\n closest_sum = sum(arr[:3])\n for i in range(len(arr) - 2):\n j = i + 1\n k = len(arr) - 1\n while j < k:\n current_sum = arr[i] + arr[j] + arr[k]\n if abs(target - current_sum) < abs(target - closest_sum):\n closest_sum = current_sum\n elif abs(target - current_sum) == abs(target - closest_sum):\n closest_sum = max(closest_sum, current_sum)\n if current_sum < target:\n j += 1\n else:\n k -= 1\n return closest_sum", "def threesumclosest(arr, target):\n arr.sort()\n ans = sum(arr[:3])\n for (i, j) in enumerate(arr[:-2]):\n a = i + 1\n b = len(arr) - 1\n while a < b:\n temp = j + arr[a] + arr[b]\n if temp == target:\n return temp\n X = abs(temp - target)\n Y = abs(ans - target)\n if X == Y:\n ans = max(ans, temp)\n elif X < Y:\n ans = temp\n if temp < target:\n a += 1\n elif temp > target:\n b -= 1\n return ans", "def threesumclosest(arr, target):\n arr.sort()\n n = len(arr)\n res = sum(arr[:3])\n for (i, v) in enumerate(arr[:-2]):\n l = i + 1\n r = len(arr) - 1\n len(arr) - 1\n while l < r:\n temp = v + arr[l] + arr[r]\n if temp == target:\n return temp\n A = abs(temp - target)\n B = abs(res - target)\n if A == B:\n res = max(res, temp)\n elif A < B:\n res = temp\n if temp < target:\n l += 1\n elif temp > target:\n r -= 1\n return res", "def threesumclosest(arr, target):\n arr.sort()\n x = sum(arr[:3])\n n = len(arr)\n for i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n ans = arr[i] + arr[j] + arr[k]\n y = target - ans\n z = target - x\n if abs(y) < abs(z):\n x = ans\n elif abs(y) == abs(z):\n x = max(x, ans)\n if ans < target:\n j += 1\n else:\n k -= 1\n return x", "def threesumclosest(arr, target):\n arr.sort()\n l = len(arr)\n w = abs(sum(arr[:3]) - target)\n mx = 0\n for i in range(l - 2):\n a = i + 1\n b = l - 1\n while a < b:\n p = [arr[i], arr[a], arr[b]]\n p1 = sum(p)\n p2 = abs(p1 - target)\n if p2 <= w:\n if p2 == w:\n if mx < p1:\n mx = p1\n else:\n w = p2\n mx = p1\n if target > p1:\n a += 1\n else:\n b -= 1\n return mx", "from typing import List\n\ndef threesumclosest(nums: List[int], target: int) -> int:\n nums.sort()\n n = len(nums)\n closest_sum = float('inf')\n min_diff = float('inf')\n for i in range(n):\n (l, r) = (i + 1, n - 1)\n while l < r:\n cur_sum = nums[i] + nums[l] + nums[r]\n cur_diff = abs(target - cur_sum)\n if cur_diff < min_diff:\n min_diff = cur_diff\n closest_sum = cur_sum\n elif cur_diff == min_diff:\n closest_sum = max(closest_sum, cur_sum)\n if cur_sum == target:\n return target\n elif cur_sum < target:\n l += 1\n else:\n r -= 1\n return closest_sum", "def threesumclosest(arr, target):\n l = len(arr)\n sum = 0\n min_sum = []\n max_sum = []\n arr.sort()\n for i in range(l - 2):\n left = i + 1\n right = l - 1\n while left < right:\n sum = arr[i] + arr[left] + arr[right]\n if sum == target:\n return target\n elif sum > target:\n max_sum.append(sum)\n right -= 1\n else:\n min_sum.append(sum)\n left += 1\n a = b = 0\n if max_sum:\n a = min(max_sum)\n res = a\n if min_sum:\n b = max(min_sum)\n res = b\n if max_sum and min_sum:\n if a - target > target - b:\n res = b\n else:\n res = a\n return res", "def threesumclosest(arr, target):\n arr.sort()\n n = len(arr)\n diff = float('inf')\n output = 0\n for i in range(n - 2):\n k = n - 1\n for j in range(i + 1, n - 1):\n while j < k and arr[i] + arr[j] + arr[k] > target:\n summa = arr[i] + arr[j] + arr[k]\n if summa - target < diff or (summa - target == diff and summa > output):\n diff = summa - target\n output = summa\n k -= 1\n if j == k:\n break\n summa = arr[i] + arr[j] + arr[k]\n if abs(summa - target) < diff or (summa - target == diff and summa > output):\n diff = abs(summa - target)\n output = summa\n return output", "import sys\n\ndef threesumclosest(arr, target):\n arr.sort()\n closestsum = sys.maxsize\n n = len(arr)\n for i in range(n - 2):\n ptr1 = i + 1\n ptr2 = n - 1\n while ptr1 < ptr2:\n sum = arr[i] + arr[ptr1] + arr[ptr2]\n if sum == target:\n return sum\n elif sum < target:\n if abs(target - sum) < abs(target - closestsum):\n closestsum = sum\n elif abs(target - sum) == abs(target - closestsum):\n closestsum = max(closestsum, sum)\n ptr1 += 1\n else:\n if abs(target - sum) < abs(target - closestsum):\n closestsum = sum\n elif abs(target - sum) == abs(target - closestsum):\n closestsum = max(closestsum, sum)\n ptr2 -= 1\n return closestsum", "def threesumclosest(arr, target):\n m = 100000000.0\n arr.sort()\n n = len(arr)\n for i in range(n):\n l = i + 1\n r = n - 1\n while l < r:\n temp = arr[i] + arr[l] + arr[r]\n if temp == target:\n return temp\n elif temp < target:\n if abs(temp - target) < abs(m - target):\n m = temp\n elif abs(temp - target) == abs(m - target):\n m = max(m, temp)\n l += 1\n else:\n if abs(temp - target) < abs(m - target):\n m = temp\n elif abs(temp - target) == abs(m - target):\n m = max(m, temp)\n r -= 1\n return m", "def threesumclosest(a, target):\n arr.sort()\n k1 = -1\n m = 10 ** 9\n for i in range(len(arr)):\n (j, k) = (i + 1, len(arr) - 1)\n while k > j:\n if arr[i] + arr[j] + arr[k] == target:\n return a[i] + a[j] + a[k]\n if arr[i] + arr[j] + arr[k] < target:\n if m == abs(target - (arr[i] + arr[j] + arr[k])):\n k1 = max(k1, arr[i] + arr[j] + arr[k])\n if m > abs(target - arr[i] - arr[j] - arr[k]):\n k1 = arr[i] + arr[j] + arr[k]\n m = abs(target - (arr[i] + arr[j] + arr[k]))\n j = j + 1\n continue\n if arr[i] + arr[j] + arr[k] > target:\n if m == abs(target - (arr[i] + arr[j] + arr[k])):\n k1 = max(k1, arr[i] + arr[j] + arr[k])\n if m > abs(target - (arr[i] + arr[j] + arr[k])):\n k1 = arr[i] + arr[j] + arr[k]\n m = abs(target - (arr[i] + arr[j] + arr[k]))\n k = k - 1\n return k1", "def threesumclosest(arr, target):\n ans = []\n temp = []\n for i in range(0, len(arr)):\n for j in range(i + 1, len(arr)):\n for k in range(j + 1, len(arr)):\n x = arr[i] + arr[j] + arr[k]\n if x == target:\n return target\n elif x > target:\n ans.append(x)\n temp.append(abs(x - target))\n else:\n ans.append(x)\n temp.append(abs(x - target))\n t1 = min(temp) + target\n t2 = target - min(temp)\n if t1 in ans:\n return t1\n return t2", "def threesumclosest(arr, target):\n arr.sort()\n res = -1000000000.0\n for i in range(len(arr)):\n (j, k) = (0, len(arr) - 1)\n cs = 0\n while j < k:\n if j == i:\n j += 1\n continue\n elif k == i:\n k -= 1\n continue\n cs = arr[i] + arr[j] + arr[k]\n if abs(res - target) > abs(cs - target):\n res = cs\n elif abs(target - cs) == abs(target - res):\n res = max(cs, res)\n if cs < target:\n j += 1\n elif cs > target:\n k -= 1\n else:\n return cs\n return res", "def threesumclosest(arr, target):\n n = len(arr)\n diff = 9999999999\n arr.sort()\n sum_three = 0\n for i in range(n):\n j = i + 1\n k = n - 1\n while j < k:\n three_sum = arr[i] + arr[j] + arr[k]\n if abs(three_sum - target) == diff:\n if three_sum > target:\n sum_three = three_sum\n elif abs(three_sum - target) < diff:\n diff = abs(three_sum - target)\n sum_three = three_sum\n if three_sum >= target:\n k -= 1\n else:\n j += 1\n return sum_three", "def threesumclosest(A, X):\n n = len(A)\n A.sort()\n ans = 0\n diff = 10 ** 9\n for i in range(n):\n s = i + 1\n e = n - 1\n while s < e:\n sum = A[i] + A[s] + A[e]\n if sum == X:\n return X\n if abs(X - sum) < diff:\n diff = min(diff, abs(X - sum))\n ans = sum\n if abs(X - sum) == diff:\n ans = max(ans, sum)\n if sum > X:\n e -= 1\n elif sum < X:\n s += 1\n return ans", "def threesumclosest(arr, target):\n arr.sort()\n close_sum = 10 ** 5\n for i in range(len(arr)):\n l = i + 1\n r = len(arr) - 1\n while l < r:\n current_sum = arr[i] + arr[l] + arr[r]\n if abs(current_sum - target) == abs(close_sum - target) and current_sum > close_sum:\n close_sum = current_sum\n if current_sum < target:\n l += 1\n else:\n r -= 1\n if abs(current_sum - target) < abs(close_sum - target):\n close_sum = current_sum\n return close_sum", "def threesumclosest(arr, target):\n n = len(arr)\n arr.sort()\n res = float('-inf')\n for (i, v) in enumerate(arr[:-2]):\n if i and arr[i] == arr[i - 1]:\n continue\n (l, r) = (i + 1, len(arr) - 1)\n while l < r:\n temp = v + arr[l] + arr[r]\n if temp == target:\n return temp\n (A, B) = (abs(temp - target), abs(res - target))\n if A == B:\n res = max(res, temp)\n if A < B:\n res = temp\n if temp < target:\n l += 1\n elif temp > target:\n r -= 1\n return res", "def threesumclosest(a, target):\n a = sorted(a)\n n = len(a)\n cs = a[0] + a[1] + a[2]\n for i in range(n - 2):\n l = i + 1\n r = n - 1\n while l < r:\n s = a[i] + a[l] + a[r]\n if abs(target - s) < abs(target - cs):\n cs = s\n if abs(target - s) == abs(target - cs):\n cs = cs if cs > s else s\n if s > target:\n r -= 1\n else:\n l += 1\n return cs", "def threesumclosest(arr, target):\n arr.sort()\n c = -9999999\n n = len(arr)\n for i in range(n - 2):\n j = i + 1\n k = n - 1\n while j < k:\n s = arr[i] + arr[j] + arr[k]\n if abs(target - s) < abs(target - c):\n c = s\n elif abs(target - s) == abs(target - c):\n c = max(c, s)\n if s > target:\n k -= 1\n else:\n j += 1\n return c", "import sys\n\ndef threesumclosest(arr, target):\n arr.sort()\n closestSum = sys.maxsize\n for i in range(len(arr) - 2):\n left = i + 1\n right = len(arr) - 1\n while left < right:\n currentSum = arr[i] + arr[left] + arr[right]\n if abs(target - currentSum) < abs(target - closestSum):\n closestSum = currentSum\n elif abs(target - currentSum) == abs(target - closestSum):\n closestSum = max(closestSum, currentSum)\n if currentSum > target:\n right -= 1\n elif currentSum < target:\n left += 1\n else:\n return currentSum\n return closestSum", "import sys\n\ndef threesumclosest(arr, x):\n arr.sort()\n closestSum = sys.maxsize\n for i in range(len(arr) - 2):\n ptr1 = i + 1\n ptr2 = len(arr) - 1\n while ptr1 < ptr2:\n sum = arr[i] + arr[ptr1] + arr[ptr2]\n if abs(x - sum) < abs(x - closestSum):\n closestSum = sum\n elif abs(x - sum) == abs(x - closestSum):\n closestSum = max(closestSum, sum)\n if sum > x:\n ptr2 -= 1\n else:\n ptr1 += 1\n return closestSum", "def threesumclosest(arr, target):\n arr.sort()\n result = []\n minn = 99999999999\n n = len(arr)\n for i in range(n - 2):\n low = i + 1\n high = n - 1\n while low < high:\n sm = arr[i] + arr[low] + arr[high]\n if sm == target:\n return target\n elif sm < target:\n low += 1\n else:\n high -= 1\n if abs(sm - target) < minn:\n minn = abs(sm - target)\n result = [sm]\n elif abs(sm - target) == minn:\n result.append(sm)\n return max(result)", "def threesumclosest(arr, target):\n arr.sort()\n n = len(arr)\n minn = 9999999999\n result = []\n for i in range(n - 2):\n (j, k) = (i + 1, n - 1)\n while j < k:\n sm = arr[i] + arr[j] + arr[k]\n if sm == target:\n return target\n elif sm < target:\n j += 1\n elif sm > target:\n k -= 1\n if abs(sm - target) < minn:\n minn = abs(sm - target)\n result = [sm]\n elif abs(sm - target) == minn:\n result.append(sm)\n return max(result)", "def threesumclosest(arr, target):\n arr.sort()\n n = len(arr)\n a = []\n temp = []\n for i in range(n - 2):\n lr = i + 1\n rl = n - 1\n while lr < rl:\n x = arr[i] + arr[lr] + arr[rl]\n if x == target:\n return target\n elif x < target:\n a.append(x)\n temp.append(abs(x - target))\n lr += 1\n else:\n a.append(x)\n temp.append(abs(x - target))\n rl -= 1\n res1 = min(temp) + target\n res2 = target - min(temp)\n if res1 in a:\n return res1\n else:\n return res2", "def closest(arr, n, target, idx):\n mx = 10 ** 10\n (start, end) = (idx + 1, n - 1)\n while start < end and start < n and (end > idx):\n s = arr[start] + arr[end]\n if abs(s - target) < abs(mx - target):\n mx = s\n elif abs(s - target) == abs(mx - target):\n mx = max(mx, s)\n if s > target:\n end -= 1\n elif s < target:\n start += 1\n elif s == target:\n return s\n return mx\n\ndef threesumclosest(arr, target):\n mx = 10 ** 10\n arr.sort()\n for i in range(len(arr) - 2):\n res = arr[i] + closest(arr, len(arr), target - arr[i], i)\n if abs(res - target) < abs(mx - target):\n mx = res\n elif abs(res - target) == abs(mx - target):\n mx = max(mx, res)\n return mx", "def threesumclosest(arr, target):\n import sys\n diff = sys.maxsize\n res = 0\n arr = sorted(arr)\n for i in range(len(arr) - 2):\n l = i + 1\n r = len(arr) - 1\n while l < r:\n temp_sum = arr[i] + arr[l] + arr[r]\n if temp_sum == target:\n return target\n elif temp_sum > target:\n if temp_sum - target < diff:\n res = temp_sum\n diff = temp_sum - target\n elif temp_sum - target == diff:\n res = temp_sum\n r -= 1\n else:\n if target - temp_sum < diff:\n res = temp_sum\n diff = target - temp_sum\n l += 1\n return res", "def threesumclosest(arr, target):\n arr = sorted(arr)\n closestSum = 100001\n for i in range(len(arr) - 2):\n ptr1 = i + 1\n ptr2 = len(arr) - 1\n while ptr1 < ptr2:\n sum = arr[i] + arr[ptr1] + arr[ptr2]\n if abs(target - sum) < abs(target - closestSum):\n closestSum = sum\n if abs(target - sum) == abs(target - closestSum):\n if sum > closestSum:\n closestSum = sum\n if sum > target:\n ptr2 -= 1\n else:\n ptr1 += 1\n return closestSum", "def threesumclosest(arr, target):\n arr.sort()\n distance = float('inf')\n for x in range(len(arr) - 2):\n (l, r) = (x + 1, len(arr) - 1)\n while l < r:\n sum_val = arr[x] + arr[l] + arr[r]\n if abs(sum_val - target) < abs(distance - target):\n distance = sum_val\n elif abs(sum_val - target) == abs(distance - target):\n distance = max(distance, sum_val)\n if sum_val < target:\n l += 1\n else:\n r -= 1\n return distance", "def threesumclosest(arr, target):\n arr.sort()\n c = 2147483647\n result = 0\n for i in range(len(arr)):\n ptr1 = i + 1\n ptr2 = len(arr) - 1\n while ptr1 < ptr2:\n summ = arr[i] + arr[ptr1] + arr[ptr2]\n if summ == target:\n return target\n if summ < target:\n if abs(target - summ) < c:\n result = summ\n c = abs(target - summ)\n ptr1 += 1\n else:\n if abs(target - summ) <= c:\n result = summ\n c = abs(target - summ)\n ptr2 -= 1\n return result"], "starter_code": "def threesumclosest (arr, target):\n", "input_output": {"inputs": ["N = 6, target = 2\r\nA[] = {-7,9,8,3,1,1}", "N = 4, target = 13\r\nA[] = {5,2,7,5}"], "outputs": ["2", "14"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays", "Hash"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/three-sum-closest/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*N).", "entry_point": "threesumclosest", "task_id": "TACO_lite/407", "example": [[[6, 2, [-7, 9, 8, 3, 1, 1]], [4, 13, [5, 2, 7, 5]]], [null, null]]} +{"requirement": "Given the root of a n-ary tree find the number of duplicate subtrees in the n-ary tree. Two trees are duplicates if they have the same structure with the same node values.\nExample 1:\nInput:\n1 N 2 2 3 N 4 N 4 4 3 N N N N N\nOutput: \n2\nExplanation: \n[4], [3] are duplicate subtree.\nExample 2:\nInput:\n1 N 2 3 N 4 5 6 N N N N\nOutput: \n0\nExplanation: \nNo duplicate subtree found.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function duplicateSubtreeNaryTree() which takes the root of the n-ary tree as input and returns an integer value as a number of duplicate subtrees.\nExpected Time Complexity: O(n), n is the total no of nodes\nExpected Space Complexity: O(n^{2})\nConstraints:\n 1 <= n < 10^{3}\n 1 <= node.key< 10^{3}", "solutions": ["def solve(root, d):\n s = str(root.key)\n for i in root.children:\n s += self.solve(i, d)\n d[s] = d.get(s, 0) + 1\n return s\n\ndef duplicateSubtreeNaryTree(root):\n d = {}\n self.solve(root, d)\n c = 0\n for x in d:\n if d[x] > 1:\n c += 1\n return c", "def duplicateSubtreeNaryTree(root):\n\n def getSubtreeIdentifier(node):\n if not node:\n return ''\n subtree_identifiers = []\n for child in node.children:\n subtree_identifier = getSubtreeIdentifier(child)\n subtree_identifiers.append(subtree_identifier)\n subtree_identifiers.sort()\n subtree_identifier = str(node.key) + ',' + ','.join(subtree_identifiers)\n subtree_counts[subtree_identifier] = subtree_counts.get(subtree_identifier, 0) + 1\n return subtree_identifier\n subtree_counts = {}\n getSubtreeIdentifier(root)\n duplicate_count = 0\n for count in subtree_counts.values():\n if count > 1:\n duplicate_count += 1\n return duplicate_count", "def duplicateSubtreeNaryTree(root):\n\n def traverse(node):\n if not node:\n return '#'\n subtree = str(node.key)\n for child in node.children:\n subtree += traverse(child)\n if subtree in subtrees:\n subtrees[subtree] += 1\n else:\n subtrees[subtree] = 1\n return subtree\n subtrees = {}\n traverse(root)\n return sum((freq > 1 for freq in subtrees.values()))", "def duplicateSubtreeNaryTree(root):\n\n def solve(root):\n if root == None:\n return ''\n res = str(root.key)\n for i in root.children:\n res += '*' + solve(i)\n if res not in d1:\n d1[res] = 1\n else:\n d1[res] += 1\n return res\n d1 = {}\n solve(root)\n ans = 0\n for (i, v) in d1.items():\n if v > 1:\n ans += 1\n return ans", "def recSol(node):\n repre = (node.key, tuple(sorted([self.recSol(child) for child in node.children])))\n if repre in self.HashTab:\n if self.HashTab[repre] not in self.duplicated:\n self.duplicated.update([self.HashTab[repre]])\n else:\n self.HashTab[repre] = len(self.HashTab)\n return self.HashTab[repre]\n\ndef duplicateSubtreeNaryTree(root):\n self.duplicated = set()\n self.sameVal = 0\n self.HashTab = {}\n self.recSol(root)\n return len(self.duplicated)", "def recSol(node):\n if node is None:\n return -1\n repre = (node.key, tuple(sorted([self.recSol(child) for child in node.children])))\n if repre in self.HashTab:\n if self.HashTab[repre] not in self.duplicated:\n self.sameVal += 1\n self.duplicated.update([self.HashTab[repre]])\n else:\n self.HashTab[repre] = self.count\n self.count += 1\n return self.HashTab[repre]\n\ndef duplicateSubtreeNaryTree(root):\n self.duplicated = set()\n self.sameVal = 0\n self.HashTab = {}\n self.count = 0\n self.recSol(root)\n return self.sameVal", "def cst(root, sp):\n s = str(root.key)\n for y in root.children:\n s += self.cst(y, sp)\n sp[s] = sp.get(s, 0) + 1\n return s\n\ndef duplicateSubtreeNaryTree(root):\n sp = {}\n self.cst(root, sp)\n c = 0\n for x in sp:\n if sp[x] > 1:\n c += 1\n return c", "def duplicateSubtreeNaryTree(root):\n d = dict()\n\n def dfs(root):\n count = 1\n for i in root.children:\n x = dfs(i)\n count = count + x\n if d.get(count) != None:\n d[count].append(root)\n if d.get(count) == None:\n d[count] = [root]\n return count\n dfs(root)\n\n def check(root1, root2):\n if root1.key != root2.key:\n return False\n if len(root1.children) != len(root2.children):\n return False\n y = True\n for i in range(len(root1.children)):\n y = y and check(root1.chilren[i], root2.children[i])\n return y\n d1 = dict()\n for i in d.keys():\n for j in range(len(d[i])):\n for k in range(j + 1, len(d[i])):\n if check(d[i][j], d[i][k]):\n d1[d[i][j].key] = True\n return len(d1.keys())", "def cst(root, sp):\n s = str(root.key)\n for y in root.children:\n s += self.cst(y, sp)\n sp[s] = sp.get(s, 0) + 1\n return s\n\ndef duplicateSubtreeNaryTree(root):\n sp = {}\n self.cst(root, sp)\n cnt = 0\n for i in sp:\n if sp[i] > 1:\n cnt += 1\n return cnt", "def duplicateSubtreeNaryTree(root):\n m = {}\n\n def solve(root):\n value = str(root.key)\n for c in root.children:\n value += solve(c)\n m[value] = m.get(value, 0) + 1\n return value\n solve(root)\n res = 0\n for i in m:\n if m[i] > 1:\n res += 1\n return res", "def duplicateSubtreeNaryTree(root):\n paths = {}\n\n def dfs(ptr):\n suffix = '' if ptr.children is None or len(ptr.children) == 0 else ''.join(list(map(lambda n: dfs(n), ptr.children)))\n nid = ':' + str(ptr.key) + suffix\n paths[nid] = paths.get(nid, 0) + 1\n return nid\n dfs(root)\n count = 0\n for (k, v) in paths.items():\n count += 1 if v > 1 else 0\n return count", "def func(root, d):\n if root == None:\n return ''\n s = str(root.key)\n for i in root.children:\n s += '$' + func(i, d)\n if s in d:\n d[s] += 1\n else:\n d[s] = 1\n return s\n\ndef duplicateSubtreeNaryTree(root):\n d = {}\n func(root, d)\n c = 0\n for i in d:\n if d[i] > 1:\n c += 1\n return c", "def duplicateSubtreeNaryTree(root):\n from collections import Counter\n c = Counter()\n\n def dfs(n):\n nonlocal c\n if not n:\n return '#'\n key = '{0} {1}'.format(n.key, ' '.join((dfs(nxt) for nxt in n.children)))\n c[key] += 1\n return key\n dfs(root)\n return sum((v > 1 for v in c.values()))", "def duplicateSubtreeNaryTree(root):\n res = []\n hmap = {}\n\n def recurse(node):\n p = str(node.key) + '#'\n for child in node.children:\n p += recurse(child)\n if p not in hmap:\n hmap[p] = 0\n hmap[p] += 1\n return p\n recurse(root)\n ans = 0\n for val in hmap.values():\n if val > 1:\n ans += 1\n return ans", "def duplicateSubtreeNaryTree(root):\n mp = {}\n\n def postorder(root):\n if root == None:\n return ''\n ans = ''\n for child in root.children:\n ans += postorder(child) + '*'\n ans += str(root.key) + '*'\n mp[ans] = 1 + mp.get(ans, 0)\n return ans\n count = 0\n postorder(root)\n for i in mp:\n if mp[i] > 1:\n count += 1\n return count", "def duplicateSubtreeNaryTree(root):\n freq = defaultdict(int)\n\n def traverse(node):\n if not node:\n return '#'\n subtree = str(node.key)\n for child in node.children:\n subtree += traverse(child)\n freq[subtree] += 1\n return subtree\n traverse(root)\n count = 0\n for key in freq:\n if freq[key] > 1:\n count += 1\n return count", "def duplicateSubtreeNaryTree(root):\n d = {}\n self.compute(root, d)\n res = 0\n for (_, count) in d.items():\n if count > 1:\n res += 1\n return res\n\ndef compute(root, d):\n cur_value = root.key\n for ch in root.children:\n self.compute(ch, d)\n cur_value += ch.value * 10\n if cur_value not in d:\n d[cur_value] = 0\n d[cur_value] += 1\n root.value = cur_value", "def __init__():\n self.dic = dict()\n\ndef helper(node):\n temp = str(node.key)\n for child in node.children:\n t = self.helper(child)\n temp = str(temp) + str(t) + 'x'\n if temp not in self.dic:\n self.dic[temp] = 0\n self.dic[temp] += 1\n return temp\n\ndef duplicateSubtreeNaryTree(root):\n self.helper(root)\n ans = 0\n for key in self.dic.keys():\n if self.dic[key] > 1:\n ans += 1\n return ans", "from collections import defaultdict\n\ndef duplicateSubtreeNaryTree(root):\n m = {}\n\n def dfs(node):\n if not node:\n return ''\n s = str(node.key)\n for i in node.children:\n s += dfs(i)\n if s in m:\n m[s] += 1\n else:\n m[s] = 1\n return s + '*'\n dfs(root)\n ans = 0\n for i in m:\n if m[i] > 1:\n ans += 1\n return ans", "def __init__():\n self.ans = 0\n self.m = {}\n\ndef solve(root):\n if not root:\n return ''\n s = str(root.key) + ' '\n for c in root.children:\n s += self.solve(c) + ' '\n if s in self.m and self.m[s] == 1:\n self.ans += 1\n self.m[s] = self.m.get(s, 0) + 1\n return s\n\ndef duplicateSubtreeNaryTree(root):\n self.solve(root)\n return self.ans", "def duplicateSubtreeNaryTree(root):\n (self.ids, self.cur_id, self.unique_trees) = ({}, 0, set())\n self.dfs(root)\n return len(self.unique_trees)\n\ndef dfs(node):\n cur = [str(node.key)]\n for child in node.children:\n cur.append(self.dfs(child))\n cur = '#'.join(cur)\n if self.ids.get(cur, -1) == -1:\n self.cur_id += 1\n self.ids[cur] = self.cur_id\n else:\n self.unique_trees.add(self.ids[cur])\n return str(self.ids[cur])", "def __init__():\n self.map = {}\n\ndef duplicateSubtreeNaryTree(root):\n answer = 0\n self.solve(root)\n for x in self.map:\n if self.map[x] > 1:\n answer += 1\n return answer\n\ndef solve(root: 'Node') -> str:\n s = str(root.key)\n for y in root.children:\n s += self.solve(y)\n self.map[s] = self.map.get(s, 0) + 1\n return s", "def __init__():\n self.map = {}\n\ndef duplicateSubtreeNaryTree(root: 'Node') -> int:\n ans = 0\n self.solve(root)\n for e in self.map:\n if self.map[e] > 1:\n ans += 1\n return ans\n\ndef solve(root: 'Node') -> str:\n s = str(root.key)\n for nei in root.children:\n s += self.solve(nei)\n self.map[s] = self.map.get(s, 0) + 1\n return s", "def cst(root, s):\n a = str(root.key)\n for i in root.children:\n a += self.cst(i, s)\n s[a] = s.get(a, 0) + 1\n return a\n\ndef duplicateSubtreeNaryTree(root):\n t = {}\n self.cst(root, t)\n ans = 0\n for i in t:\n if t[i] > 1:\n ans += 1\n return ans", "def duplicateSubtreeNaryTree(root):\n self.map = {}\n\n def solve(root):\n if root is None:\n return ''\n returnValue = root.__str__()\n for ch in root.children:\n returnValue = returnValue + '#' + solve(ch)\n self.map[returnValue] = self.map.get(returnValue, 0) + 1\n return returnValue\n solve(root)\n ans = 0\n for val in self.map.values():\n if val > 1:\n ans += 1\n return ans", "def duplicateSubtreeNaryTree(root):\n hash = {}\n\n def count_sub_tree(node):\n if not node:\n return ''\n s = str(node.key)\n for child in node.children:\n s += count_sub_tree(child)\n hash[s] = hash.get(s, 0) + 1\n return s\n count_sub_tree(root)\n res = 0\n for sub_tree in hash:\n if hash[sub_tree] > 1:\n res += 1\n return res", "def duplicateSubtreeNaryTree(root):\n\n def traverse(node):\n nonlocal count, subtrees\n if not node:\n return ''\n subtree = str(node.key)\n for child in node.children:\n subtree += traverse(child)\n if subtree in subtrees and subtrees[subtree] == 1:\n count += 1\n subtrees[subtree] = 2\n elif subtree not in subtrees:\n subtrees[subtree] = 1\n return subtree\n count = 0\n subtrees = {}\n traverse(root)\n return count", "import collections\n\ndef duplicateSubtreeNaryTree(root):\n PRIME = 1337\n hashes = collections.defaultdict(int)\n\n def dfs(r):\n nonlocal hashes\n if not r:\n return 1\n ret = r.key\n for i in range(len(r.children)):\n ret += (i + 1) * dfs(r.children[i])\n ret = ret * PRIME\n hashes[ret] += 1\n return ret\n dfs(root)\n ans = 0\n for (k, v) in hashes.items():\n ans += v > 1\n return ans", "def solve(root, mp):\n st = str(root.key) + ':'\n arr = []\n for i in root.children:\n arr.append(self.solve(i, mp))\n arr.sort()\n for i in arr:\n st += i + ','\n if st in mp:\n mp[st] += 1\n else:\n mp[st] = 1\n return st\n\ndef duplicateSubtreeNaryTree(root):\n (count, mp) = (0, {})\n self.solve(root, mp)\n for i in mp:\n if mp[i] > 1:\n count += 1\n return count", "def duplicateSubtreeNaryTree(root):\n d = {}\n\n def trav(node):\n if not node:\n return '#'\n s = str(node.key) + ''.join((trav(n) for n in node.children))\n d[s] = d.get(s, 0) + 1\n return s\n trav(root)\n op = 0\n for i in d:\n if d[i] >= 2:\n op += 1\n return op", "def duplicateSubtreeNaryTree(root):\n d = {}\n\n def duplicateSubTree(root):\n if root == None:\n return '()'\n subtree = ''\n for child in root.children:\n subtree += duplicateSubTree(child)\n d['(' + str(root.key) + subtree + ')'] = d.get('(' + str(root.key) + subtree + ')', 0) + 1\n return '(' + str(root.key) + subtree + ')'\n duplicateSubTree(root)\n ans = 0\n for key in d.keys():\n if d[key] >= 2:\n ans += 1\n return ans"], "starter_code": "def __init__(key, children=None):\n", "input_output": {"inputs": ["1 N 2 2 3 N 4 N 4 4 3 N N N N N", "1 N 2 3 N 4 5 6 N N N N"], "outputs": ["2", "0"]}, "difficulty": "MEDIUM", "raw_tags": ["Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/079dee7e7db7a784ed73f604e3cf1712432edf79/1", "Expected Auxiliary Space": "O(n^{2})", "time_limit": null, "date": null, "picture_num": "2", "memory_limit": null, "Expected Time Complexity": "O(n), n is the total no of nodes", "entry_point": "__init__", "task_id": "TACO_lite/412", "example": [[], []]} +{"requirement": "You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.\nYou may assume that you have an infinite number of each kind of coin.\n\u00a0\nExample 1:\nInput: coins = [1,2,5], amount = 11\nOutput: 3\nExplanation: 11 = 5 + 5 + 1\n\nExample 2:\nInput: coins = [2], amount = 3\nOutput: -1\n\nExample 3:\nInput: coins = [1], amount = 0\nOutput: 0\n\nExample 4:\nInput: coins = [1], amount = 1\nOutput: 1\n\nExample 5:\nInput: coins = [1], amount = 2\nOutput: 2\n\n\u00a0\nConstraints:\n\n1 <= coins.length <= 12\n1 <= coins[i] <= 231 - 1\n0 <= amount <= 104", "solutions": ["def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n (n, res) = (len(coins), amount + 1)\n\n def dfs(index, target, cnt):\n nonlocal res\n if cnt + (target + coins[index] - 1) // coins[index] >= res:\n return\n if target % coins[index] == 0:\n res = cnt + target // coins[index]\n return\n if index == n - 1:\n return\n for i in range(target // coins[index], -1, -1):\n dfs(index + 1, target - coins[index] * i, cnt + i)\n dfs(0, amount, 0)\n return -1 if res > amount else res", "def coinchange(coins: List[int], amount: int) -> int:\n if not coins or amount < 0:\n return -1\n elif amount == 0:\n return 0\n coins.sort(reverse=True)\n visited = set()\n q = collections.deque([])\n for c in coins:\n if c == amount:\n return 1\n elif c < amount:\n q.append(c)\n visited.add(c)\n count = 1\n while q:\n size = len(q)\n count += 1\n for _ in range(size):\n prev = q.popleft()\n for c in coins:\n cur = prev + c\n if cur == amount:\n return count\n elif cur < amount and cur not in visited:\n visited.add(cur)\n q.append(cur)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n INVALID = 2 ** 32\n dp = [INVALID] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for i in range(coin, amount + 1):\n if dp[i - coin] >= dp[i]:\n continue\n dp[i] = dp[i - coin] + 1\n return -1 if dp[amount] == INVALID else dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n queue = [[amount, 0]]\n visited = {amount}\n for q in queue:\n for c in coins:\n if q[0] - c in visited:\n continue\n if q[0] == c:\n return q[1] + 1\n if q[0] > c:\n visited.add(q[0] - c)\n queue.append([q[0] - c, q[1] + 1])\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n queue = deque([(0, 0)])\n visited = [True] + [False] * amount\n while queue:\n (totalCoins, currVal) = queue.popleft()\n totalCoins += 1\n for coin in coins:\n nextVal = currVal + coin\n if nextVal == amount:\n return totalCoins\n if nextVal < amount:\n if not visited[nextVal]:\n visited[nextVal] = True\n queue.append((totalCoins, nextVal))\n return -1", "from collections import deque\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n if not coins:\n return -1\n queue = deque([])\n for coin in coins:\n if amount - coin >= 0:\n queue.append((1, amount - coin))\n seen = set()\n while queue:\n nex = queue.popleft()\n if nex[1] == 0:\n return nex[0]\n for coin in coins:\n if nex[1] - coin not in seen and nex[1] - coin >= 0:\n queue.append((nex[0] + 1, nex[1] - coin))\n seen.add(nex[1] - coin)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for a in range(coin, amount + 1):\n if dp[a - coin] >= dp[a]:\n continue\n dp[a] = dp[a - coin] + 1\n return dp[amount] if dp[amount] < float('inf') else -1", "from collections import deque\n\ndef coinchange(coins: List[int], amount: int) -> int:\n queue = deque()\n visited = set()\n queue.append((amount, 0))\n answer = -1\n while queue:\n (target, numCoins) = queue.popleft()\n if target == 0:\n answer = numCoins\n break\n elif target > 0:\n for coin in coins:\n if target - coin not in visited:\n visited.add(target - coin)\n queue.append((target - coin, numCoins + 1))\n return answer", "def coinchange(coins: List[int], amount: int) -> int:\n res = 0\n queue = collections.deque([(amount, 0)])\n seen = {amount}\n while queue:\n (head, res) = queue.popleft()\n if head == 0:\n return res\n for c in coins:\n new_amount = head - c\n if new_amount > -1 and new_amount not in seen:\n queue.append((new_amount, res + 1))\n seen.add(new_amount)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not coins or amount < 0:\n return -1\n if amount == 0:\n return 0\n q = [(amount, 0)]\n visited = {0}\n coins.sort(reverse=True)\n while q:\n (node, depth) = q.pop(0)\n for coin in coins:\n rest = node - coin\n if rest == 0:\n return depth + 1\n if rest > 0 and rest not in visited:\n q.append((rest, depth + 1))\n visited.add(rest)\n return -1", "from collections import deque\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n visited = {0}\n tempQueue = deque()\n tempQueue.append((0, 0))\n while tempQueue:\n (currentVal, currentCount) = tempQueue.popleft()\n for coin in coins:\n nextVal = currentVal + coin\n if nextVal == amount:\n return currentCount + 1\n elif nextVal < amount:\n if nextVal not in visited:\n visited.add(nextVal)\n tempQueue.append((nextVal, currentCount + 1))\n return -1", "def coinchange(coins, amount):\n coins.sort(reverse=True)\n queue = [(amount, 0)]\n visited = [False for i in range(amount + 1)]\n for (val, cnt) in queue:\n if val == 0:\n return cnt\n for coin in coins:\n if val - coin >= 0 and (not visited[val - coin]):\n visited[val - coin] = True\n queue.append((val - coin, cnt + 1))\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n queue = deque([])\n seen = set()\n coins = sorted(coins, reverse=True)\n queue.append((0, 0))\n while queue:\n (summ, num_coins) = queue.popleft()\n if summ == amount:\n return num_coins\n for coin in coins:\n if summ + coin <= amount and summ + coin not in seen:\n queue.append((summ + coin, num_coins + 1))\n seen.add(summ + coin)\n return -1", "def coinchange(coins, amount):\n if not coins:\n return -1\n if not amount:\n return 0\n if amount in coins:\n return 1\n C = tuple(sorted(coins, reverse=True))\n (length, self.ans) = (len(C) - 1, float('inf'))\n\n def find(coin, step, target):\n now_coin = C[coin]\n (q, r) = divmod(target, now_coin)\n if not r:\n self.ans = min(self.ans, step + q)\n elif coin < length and step + q + 1 < self.ans:\n coin += 1\n for j in range(q, -1, -1):\n find(coin, step + j, target - j * now_coin)\n find(0, 0, amount)\n return -1 if self.ans == float('inf') else self.ans", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n dp = [0] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n min = math.inf\n for j in coins:\n if i - j >= 0 and dp[i - j] < min:\n min = dp[i - j]\n dp[i] = min + 1\n return dp[-1] if dp[-1] != math.inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n numpath = [0] + [float('inf')] * amount\n for coin in coins:\n for i in range(coin, amount + 1):\n if numpath[i] > 1 + numpath[i - coin]:\n numpath[i] = 1 + numpath[i - coin]\n return numpath[amount] if numpath[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not coins or amount <= 0:\n return 0\n coins = set(coins)\n count = 1\n q = deque()\n q.append((amount, count))\n visited = set()\n visited.add(amount)\n while q:\n (remain, count) = q.popleft()\n if remain in coins:\n return count\n for c in coins:\n if remain - c > 0 and remain - c not in visited:\n q.append((remain - c, count + 1))\n visited.add(remain - c)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n Visited = {amount: 0}\n coins.sort(reverse=True)\n queue = deque()\n queue.append(amount)\n while queue:\n curr = queue.popleft()\n for coin in coins:\n if curr - coin >= 0 and curr - coin not in Visited:\n queue.append(curr - coin)\n Visited[curr - coin] = Visited[curr] + 1\n if 0 in Visited:\n return Visited[0]\n return -1", "from collections import deque\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n q = deque()\n q.append([amount, 0])\n level = 0\n seen = set()\n while q:\n (amt, level) = q.popleft()\n for n in coins:\n if amt - n == 0:\n return level + 1\n if amt - n in seen or amt - n < 0:\n continue\n seen.add(amt - n)\n q.append([amt - n, level + 1])\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n coins.sort()\n visited = {}\n sums = []\n for coin in coins:\n if coin == amount:\n return 1\n visited[coin] = 1\n sums.append(coin)\n q = []\n q.append((1, sums))\n while q:\n (count, sums) = q.pop()\n next_sums = []\n for coin in coins:\n for s in sums:\n current = coin + s\n if current < amount and current not in visited:\n visited[current] = 1\n next_sums.append(current)\n elif current == amount:\n return count + 1\n else:\n visited[current] = 1\n if next_sums:\n q.insert(0, (count + 1, next_sums))\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1 for i in range(amount + 1)]\n dp[0] = 0\n for i in range(amount + 1):\n for c in coins:\n if c <= i and dp[i] > dp[i - c] + 1:\n dp[i] = dp[i - c] + 1\n return -1 if dp[amount] > amount else dp[amount]", "from collections import deque\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n queue = deque([(amount, 0)])\n visited = set([amount])\n while queue:\n (remaining, steps) = queue.popleft()\n for coin in coins:\n if coin == remaining:\n return steps + 1\n elif coin < remaining:\n temp = remaining - coin\n if temp > 0 and temp not in visited:\n visited.add(temp)\n queue.append((temp, steps + 1))\n return -1", "from collections import defaultdict\n\ndef coinchange(coins: List[int], amount: int) -> int:\n MAX = float('inf')\n dp = defaultdict(lambda : MAX)\n dp[0] = 0\n for i in range(1, amount + 1):\n dp[i] = 1 + min([dp[i - c] for c in coins])\n return -1 if dp[amount] == MAX else dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n l = [int(amount + 1)] * int(amount + 1)\n if amount == 0:\n return 0\n else:\n l[0] = 0\n coins.sort()\n for i in range(1, amount + 1):\n for coin in coins:\n remainder = i - coin\n if remainder < 0:\n break\n elif l[i] > l[remainder] + 1:\n l[i] = l[remainder] + 1\n if l[amount] == amount + 1:\n return -1\n else:\n return l[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n coins.sort(reverse=True)\n queue = [amount]\n visit = {amount: 0}\n while queue:\n remain = queue.pop(0)\n for c in coins:\n branch = remain - c\n if 0 <= branch not in visit:\n queue.append(branch)\n visit.update({branch: visit[remain] + 1})\n return visit.get(0) or -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n visited = set([amount])\n candidates = [amount]\n res = 0\n while candidates:\n res += 1\n next_candidates = []\n for candidate in candidates:\n for coin in coins:\n if candidate - coin == 0:\n return res\n elif candidate - coin > 0 and candidate - coin not in visited:\n next_candidates.append(candidate - coin)\n visited.add(candidate - coin)\n candidates = next_candidates\n return -1", "def coinchange(denoms: List[int], n: int) -> int:\n if n == 0:\n return 0\n nodes = set([0])\n seen = set()\n count = 1\n while nodes:\n seen = seen | nodes\n next_nodes = set()\n for node in nodes:\n for denom in denoms:\n candidate = node + denom\n if candidate == n:\n return count\n elif candidate < n and candidate not in seen:\n next_nodes.add(candidate)\n count += 1\n nodes = next_nodes\n return -1\n pass", "def coinchange(coins: List[int], amount: int) -> int:\n d = [0] + [float('inf')] * amount\n for v in range(1, len(d)):\n for c in coins:\n if c <= v and d[v] > d[v - c] + 1:\n d[v] = d[v - c] + 1\n return d[-1] if d[-1] < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n queue = deque()\n numCoins = 0\n seen = set()\n coins.sort(reverse=True)\n queue.append(amount)\n if amount == 0:\n return 0\n while queue:\n qlen = len(queue)\n numCoins += 1\n for i in range(qlen):\n x = queue.popleft()\n for coin in coins:\n if x - coin == 0:\n return numCoins\n elif x - coin > 0:\n if x - coin not in seen:\n queue.append(x - coin)\n seen.add(x - coin)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n result = -1\n\n def helper(coins: List[int], pos: int, left: int, current: int):\n if left % coins[pos] == 0:\n nonlocal result\n if result == -1 or result > current + left // coins[pos]:\n result = current + left // coins[pos]\n return\n if pos == len(coins) - 1:\n return\n for k in range(left // coins[pos], -1, -1):\n new_amount = left - coins[pos] * k\n new_count = current + k\n if result != -1 and result < new_count + (new_amount + coins[pos + 1] - 1) / coins[pos + 1]:\n break\n helper(coins, pos + 1, left - coins[pos] * k, current + k)\n helper(coins, 0, amount, 0)\n return result", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n queue = collections.deque([(0, 0)])\n seen = set()\n while queue:\n (curAmount, step) = queue.popleft()\n if curAmount == amount:\n return step\n for j in range(len(coins)):\n newAmount = curAmount + coins[j]\n if newAmount <= amount and newAmount not in seen:\n seen.add(newAmount)\n queue.append((newAmount, step + 1))\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n coins.sort()\n coins_set = set(coins)\n if amount in coins_set:\n return 1\n queue = deque([[amount, 0]])\n seen = set()\n processed = set()\n while queue:\n (rem, count) = queue.popleft()\n if rem in seen:\n continue\n seen.add(rem)\n for coin in coins:\n new_rem = rem - coin\n if new_rem == 0:\n return count + 1\n if new_rem > 0:\n if new_rem in coins_set:\n return count + 2\n if new_rem not in seen and new_rem not in processed:\n queue.append([new_rem, count + 1])\n processed.add(new_rem)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('+inf')] * (amount + 1)\n dp[0] = 0\n for cnt in range(1, amount + 1):\n for coin in coins:\n if cnt - coin >= 0 and dp[cnt - coin] + 1 < dp[cnt]:\n dp[cnt] = dp[cnt - coin] + 1\n if dp[amount] == float('+inf'):\n return -1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('inf') for _ in range(amount + 1)]\n dp[0] = 0\n for x in range(len(dp)):\n for coin in coins:\n if x < coin:\n continue\n if dp[x - coin] + 1 < dp[x]:\n dp[x] = dp[x - coin] + 1\n if dp[amount] == float('inf'):\n return -1\n else:\n return dp[x]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n rec = [0] * amount\n fr = [0]\n new = []\n l = 1\n while fr or new:\n if not fr:\n fr = new\n new = []\n l += 1\n cur = fr.pop(0)\n for c in coins:\n if cur + c == amount:\n return l\n if cur + c < amount and (not rec[cur + c]):\n new.append(cur + c)\n rec[cur + c] = 1\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n memo = [float('inf') for _ in range(amount + 1)]\n memo[0] = 0\n for i in range(1, len(memo)):\n minv = float('inf')\n for coin in coins:\n if i - coin >= 0 and memo[i - coin] < minv:\n minv = memo[i - coin]\n memo[i] = 1 + minv\n return memo[amount] if memo[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n cache = [0] * (amount + 1)\n for ind in range(1, amount + 1):\n min_coins = float('inf')\n for coin in coins:\n if ind - coin >= 0:\n coins_needed = cache[ind - coin] + 1\n if coins_needed < min_coins:\n min_coins = coins_needed\n cache[ind] = min_coins\n if cache[amount] == float('inf'):\n return -1\n return cache[amount]", "def coinchange(coins: [int], amount: int) -> int:\n summary = 0\n result = [float('inf')] * (amount + 1)\n result[0] = 0\n while summary <= amount:\n if result[summary] != -1:\n for i in coins:\n if summary + i <= amount and result[summary] + 1 < result[summary + i]:\n result[summary + i] = result[summary] + 1\n summary += 1\n return -1 if result[amount] == float('inf') else result[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n arr = [float('inf')] * (amount + 1)\n arr[0] = 0\n for i in range(amount + 1):\n for c in coins:\n if i + c > amount:\n continue\n if arr[i + c] > arr[i] + 1:\n arr[i + c] = arr[i] + 1\n if arr[-1] == float('inf'):\n return -1\n return arr[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n min_coins = [float('inf') for x in range(amount + 1)]\n min_coins[0] = 0\n for value in range(1, amount + 1):\n for coin in coins:\n if coin <= value:\n if min_coins[value - coin] + 1 < min_coins[value]:\n min_coins[value] = min_coins[value - coin] + 1\n if min_coins[amount] == float('inf'):\n return -1\n return min_coins[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n queue = [[amount, 0]]\n visited = {0}\n for q in queue:\n for c in coins:\n if q[0] == c:\n return q[1] + 1\n elif q[0] > c and q[0] - c not in visited:\n visited.add(q[0] - c)\n queue.append([q[0] - c, q[1] + 1])\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [0] * (amount + 1)\n for i in range(1, len(dp)):\n dp[i] = float('inf')\n for j in coins:\n if i >= j and dp[i - j] + 1 < dp[i]:\n dp[i] = dp[i - j] + 1\n return -1 if dp[amount] == float('inf') else dp[amount]", "def bfs(cur, coins):\n if cur == 0:\n return 0\n queue = [(0, cur)]\n visited = {}\n while queue:\n (times, cur) = heapq.heappop(queue)\n for c in coins:\n if c == cur:\n return times + 1\n if c < cur:\n if cur - c not in visited:\n heapq.heappush(queue, (times + 1, cur - c))\n visited[cur - c] = True\n return -1\n\ndef coinchange(coins: List[int], amount: int) -> int:\n return self.bfs(amount, coins)", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n tmp = float('inf')\n for c in coins:\n if i - c >= 0:\n if tmp > dp[i - c] + 1:\n tmp = dp[i - c] + 1\n dp[i] = tmp\n return dp[amount] if dp[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp_mat = [-1] * (amount + 1)\n dp_mat[0] = 0\n for i in range(1, amount + 1):\n min_num = None\n for denom in coins:\n if denom <= i and dp_mat[i - denom] != -1:\n temp = 1 + dp_mat[i - denom]\n if not min_num:\n min_num = temp\n elif temp < min_num:\n min_num = temp\n if min_num:\n dp_mat[i] = min_num\n return dp_mat[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n dp = [float('inf')] * (amount + 1)\n calculated = [False] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n if coin <= amount:\n dp[coin] = 1\n calculated[coin] = True\n for i in range(1, amount + 1):\n if not calculated[i]:\n candidates = [dp[i - coin] for coin in coins if i >= coin]\n if candidates:\n dp[i] = min(candidates) + 1\n calculated[i] = True\n if dp[-1] == float('inf'):\n return -1\n else:\n return dp[-1]", "def do_du_tab(coins, amount):\n dp_tab = [math.inf for _ in range(amount + 1)]\n dp_tab[0] = 0\n for a in range(1, amount + 1):\n potential = []\n for coin in coins:\n potential.append(dp_tab[a - coin] + 1)\n dp_tab[a] = min(potential)\n return dp_tab[-1] if dp_tab[-1] != float('inf') else -1\n\ndef do_something(coins, amount):\n dp_tab = [math.inf for _ in range(amount + 1)]\n dp_tab[0] = 0\n for i in range(1, amount + 1):\n temp = []\n for coin in coins:\n temp.append(dp_tab[i - coin])\n dp_tab[i] = min(temp) + 1\n return dp_tab[amount] if dp_tab[amount] != float('inf') else -1\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if len(coins) == 0:\n return 0\n if amount == 0:\n return 0\n c = [coin for coin in coins if coin <= amount]\n if len(c) == 0:\n return -1\n return self.do_something(c, amount)", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n curr_min = amount + 1\n for coin in coins:\n cand = amount + 1\n if i - coin >= 0:\n cand = dp[i - coin] + 1\n if cand < curr_min:\n curr_min = cand\n dp[i] = curr_min\n return -1 if dp[len(dp) - 1] == amount + 1 else dp[len(dp) - 1]", "def coinchange(coins: List[int], amount: int) -> int:\n return self.coinchangeBFS(coins, amount)\n\ndef coinchangeBFS(coins: List[int], amount: int) -> int:\n if amount == 0 or not coins:\n return 0\n queue = deque([amount])\n visited = set([amount])\n depth = 0\n while queue:\n length = len(queue)\n depth += 1\n for i in range(length):\n remaining = queue.popleft()\n for c in coins:\n if remaining - c == 0:\n return depth\n elif remaining - c < 0:\n continue\n elif remaining - c not in visited:\n queue.append(remaining - c)\n visited.add(remaining - c)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n values = [-1 for i in range(amount + 1)]\n values[0] = 0\n for i in coins:\n for j in range(1, len(values)):\n if j >= i:\n if values[j - i] == -1:\n continue\n curr_num_coins = 1 + values[j - i]\n if values[j] == -1 or values[j] > curr_num_coins:\n values[j] = curr_num_coins\n return values[amount]", "def coinchange(nums: List[int], amount: int) -> int:\n MAX = float('inf')\n dp = [0] + [MAX] * amount\n for i in range(1, amount + 1):\n dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in nums]) + 1\n return [dp[amount], -1][dp[amount] == MAX]", "from collections import deque\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n dp = [float('inf')] * (amount + 1)\n dp[amount] = 0\n queue = deque()\n queue.append(amount)\n while len(queue) != 0:\n val = queue.popleft()\n for coin in coins:\n if val - coin == 0:\n return dp[val] + 1\n if val - coin > 0:\n if dp[val] + 1 < dp[val - coin]:\n dp[val - coin] = dp[val] + 1\n queue.append(val - coin)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n MAX = amount + 1\n coins.sort(reverse=True)\n dp = [MAX] * MAX\n dp[0] = 0\n for i in range(1, MAX):\n dp[i] = min([dp[i - c] if i >= c else MAX for c in coins])\n dp[i] = dp[i] + 1 if dp[i] != MAX else dp[i]\n return -1 if dp[-1] == MAX else dp[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [0] + [-1] * amount\n for x in range(amount + 1):\n if dp[x] < 0:\n continue\n for c in coins:\n if x + c > amount:\n continue\n if dp[x + c] < 0 or dp[x + c] > dp[x] + 1:\n dp[x + c] = dp[x] + 1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n coins.sort()\n cnt = 0\n toCheck = {amount}\n while toCheck:\n cnt += 1\n tmp = set()\n for x in toCheck:\n for y in coins:\n if y == x:\n return cnt\n if y > x:\n break\n tmp.add(x - y)\n if not tmp:\n return -1\n toCheck = tmp\n\ndef coinchange(coins: List[int], amount: int) -> int:\n dp = [0] + [float('inf')] * amount\n for i in range(1, amount + 1):\n dp[i] = min((dp[i - c] if i - c >= 0 else float('inf') for c in coins)) + 1\n return dp[-1] if dp[-1] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [0] + [-1] * amount\n for coin in coins:\n for idx in range(coin, len(dp)):\n if dp[idx - coin] != -1:\n if dp[idx] != -1:\n dp[idx] = min(dp[idx - coin] + 1, dp[idx])\n else:\n dp[idx] = dp[idx - coin] + 1\n return dp[amount]", "def coinchange(coins, amount):\n MAX = float('inf')\n dp = [0] + [MAX] * amount\n for i in range(1, amount + 1):\n dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in coins]) + 1\n if dp[amount] == MAX:\n return -1\n return dp[amount]\n return [dp[amount], -1][dp[amount] == MAX]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for i in range(min(coins), amount + 1):\n tmp = list()\n for coin in coins:\n if i - coin < 0:\n tmp.append(float('inf'))\n else:\n tmp.append(dp[i - coin])\n dp[i] = min(tmp) + 1\n return dp[-1] if dp[-1] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n coins = [coin for coin in coins if coin <= amount]\n if not coins:\n return -1\n dp = [0 for i in range(amount + max(coins) + 10)]\n for coin in coins:\n dp[coin] = 1\n for i in range(1, amount + 1):\n for coin in coins:\n if dp[i] >= 1:\n if dp[i + coin] == 0:\n dp[i + coin] = dp[i] + 1\n elif dp[i] + 1 < dp[i + coin]:\n dp[i + coin] = dp[i] + 1\n if not dp[amount]:\n return -1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def dfs(start, amt, n_coins):\n nonlocal min_coins\n coin = coins[start]\n div = amt // coin\n n_coins += div\n amt %= coin\n if amt == 0:\n min_coins = min(min_coins, n_coins)\n return\n if start < len_coins:\n dfs(start + 1, amt, n_coins)\n next_coin = coins[start + 1]\n for _ in range(div):\n amt += coin\n n_coins -= 1\n if (min_coins - n_coins - 1) * next_coin + 1 > amt:\n dfs(start + 1, amt, n_coins)\n else:\n break\n len_coins = len(coins) - 1\n coins.sort(reverse=True)\n min_coins = float('inf')\n dfs(0, amount, 0)\n return min_coins if min_coins < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n coins_set = set(coins)\n for i in range(amount + 1):\n if i in coins_set:\n dp[i] = 1\n continue\n candidates = [dp[i - c] + 1 for c in coins if i - c >= 0]\n if candidates:\n dp[i] = min(candidates)\n return dp[amount] if dp[amount] <= amount else -1", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n path_length = []\n path_length.append(0)\n for value in range(1, amount + 1):\n min_path_value = math.inf\n for coin in coins:\n path_index = value - coin\n if path_index > -1 and path_length[path_index] != -1:\n current_min_path = path_length[path_index] + 1\n if current_min_path < min_path_value:\n min_path_value = current_min_path\n path_length.append(min_path_value)\n return path_length[amount] if path_length[amount] < math.inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n cache = [0] * (amount + 1)\n for i in range(1, amount + 1):\n min_count = float('inf')\n for coin in coins:\n if i - coin >= 0:\n current_min_coin = cache[i - coin] + 1\n if min_count > current_min_coin:\n min_count = current_min_coin\n cache[i] = min_count\n if cache[amount] in [0, float('inf')]:\n return -1\n return cache[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [None for i in range(amount + 1)]\n dp[0] = 0\n for i in range(1, amount + 1):\n result = None\n for coin in coins:\n if i - coin >= 0:\n tmp = dp[i - coin]\n if tmp is not None and (result is None or tmp + 1 < result):\n result = tmp + 1\n dp[i] = result\n if dp[-1] is None:\n return -1\n return dp[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n arr = [float('inf')] * (amount + 1)\n arr[0] = 0\n for i in range(1, len(arr)):\n min_choices = []\n for x in coins:\n if i - x >= 0:\n min_choices.append(1 + arr[i - x])\n if min_choices:\n arr[i] = min(min_choices)\n if arr[amount] == float('inf'):\n return -1\n else:\n return arr[amount]", "def __init__():\n self.min_coins = float('inf')\n\ndef coinchange(coins: List[int], amount: int) -> int:\n\n def getChange(num_coins, need, start):\n divided_coin = need // coins[start]\n if num_coins + divided_coin >= self.min_coins:\n return\n if need % coins[start] == 0:\n self.min_coins = min(self.min_coins, divided_coin + num_coins)\n return\n if start == len(coins) - 1:\n return\n for num_used in range(divided_coin, -1, -1):\n new_need = need - coins[start] * num_used\n getChange(num_coins + num_used, new_need, start + 1)\n coins = sorted(coins, reverse=True)\n getChange(0, amount, 0)\n return self.min_coins if self.min_coins < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n T = [float('inf')] * (amount + 1)\n T[0] = 0\n for amnt in range(1, amount + 1):\n curr_min = float('inf')\n for k in range(len(coins)):\n if coins[k] <= amnt:\n val = 1 + T[amnt - coins[k]]\n if val < curr_min:\n curr_min = val\n T[amnt] = curr_min\n return -1 if T[-1] == float('inf') else T[-1]", "from typing import List\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n solution = -1\n dp = [0] * (amount + 1)\n for i in range(1, amount + 1):\n dp[i] = min([dp[i - coin] for coin in coins if i - coin >= 0] + [10000]) + 1\n if dp[-1] != 10001:\n solution = dp[-1]\n return solution", "def coinchange(coins: List[int], amount: int) -> int:\n coins = sorted(coins, reverse=True)\n dp = [-1] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n if i - coins[-1] < 0:\n continue\n for coin in coins:\n index = i - coin\n if index >= 0 and dp[index] != -1:\n value = dp[index] + 1\n if dp[i] == -1 or dp[i] > value:\n dp[i] = value\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount + 1):\n dp[x] = min(dp[x], dp[x - coin] + 1)\n return dp[amount] if dp[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n self.ret = float('inf')\n\n def recurrent(index, coins, amount, current):\n first = coins[index]\n n = amount // first\n remainder = amount % first\n if remainder == 0:\n self.ret = min(self.ret, current + n)\n else:\n l = len(coins)\n while remainder <= amount and index < l - 1 and (current + n < self.ret):\n recurrent(index + 1, coins, remainder, current + n)\n n -= 1\n remainder += first\n return\n recurrent(0, coins, amount, 0)\n if self.ret == float('inf'):\n return -1\n else:\n return self.ret", "def coinchange(coins: List[int], amount: int) -> int:\n if not coins or amount <= 0:\n return 0\n f = [float('inf')] * (amount + 1)\n f[0] = 0\n for c in coins:\n for a in range(c, amount + 1):\n f[a] = min(f[a], f[a - c] + 1)\n return f[amount] if f[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1 for _ in range(amount + 1)]\n dp[0] = 0\n for coin in coins:\n for a in range(coin, amount + 1):\n dp[a] = min(dp[a], dp[a - coin] + 1)\n res = dp[amount] if dp[amount] < amount + 1 else -1\n return res", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [0] + [float('inf')] * amount\n for c in coins:\n for j in range(c, amount + 1):\n dp[j] = min(dp[j], dp[j - c] + 1)\n return dp[-1] if dp[-1] < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [math.inf] * (amount + 1)\n dp[0] = 0\n for coin in coins:\n for idx in range(coin, amount + 1):\n prev_coins_ct = dp[idx - coin]\n dp[idx] = min(prev_coins_ct + 1, dp[idx])\n if dp[-1] == math.inf:\n return -1\n return dp[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount < 0:\n return -1\n coins = sorted(coins)\n d = [amount + 1] * (amount + 1)\n d[0] = 0\n for i in range(amount + 1):\n for j in coins:\n if j <= i:\n d[i] = min(d[i], d[i - j] + 1)\n else:\n break\n if d[-1] > amount:\n return -1\n else:\n return d[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n dp = [-1] * (amount + 1)\n dp[0] = 0\n for i in range(len(coins)):\n if coins[i] <= amount:\n dp[coins[i]] = 1\n for i in range(1, amount + 1):\n if dp[i] == -1:\n comparison = []\n for c in coins:\n if i - c >= 0 and dp[i - c] != -1:\n comparison.append(dp[i - c])\n if comparison:\n dp[i] = min(comparison) + 1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n memo = [float('inf') for _ in range(amount + 1)]\n memo[0] = 0\n for c in coins:\n for i in range(c, len(memo)):\n memo[i] = min(1 + memo[i - c], memo[i])\n return memo[amount] if memo[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n for j in coins:\n if i >= j:\n dp[i] = min(dp[i], dp[i - j] + 1)\n if dp[amount] == amount + 1:\n return -1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n rs = [amount + 1] * (amount + 1)\n rs[0] = 0\n for i in range(1, amount + 1):\n for c in coins:\n if i >= c:\n rs[i] = min(rs[i], rs[i - c] + 1)\n if rs[amount] == amount + 1:\n return -1\n return rs[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [sys.maxsize] * (amount + 1)\n dp[0] = 0\n for i in range(1, len(dp)):\n for c in coins:\n if c <= i:\n dp[i] = min(dp[i], dp[i - c] + 1)\n if dp[amount] == sys.maxsize:\n return -1\n return dp[amount]", "import math\n\ndef rec(coins, amount, used_coins, res):\n if amount == 0:\n res[0] = min(res[0], used_coins)\n elif coins and (res[0] - used_coins) * coins[-1] >= amount:\n for i in range(amount // coins[-1], -1, -1):\n rec(coins[:-1], amount - i * coins[-1], used_coins + i, res)\n\ndef coinchange(coins: List[int], amount: int) -> int:\n res = [math.inf]\n rec(sorted(coins), amount, 0, res)\n return res[0] if res[0] != math.inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not coins or len(coins) == 0:\n return 0\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for i in range(amount + 1):\n for j in coins:\n if j <= i:\n dp[i] = min(dp[i], dp[i - j] + 1)\n if dp[-1] > amount:\n return -1\n else:\n return dp[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n if amount == 0:\n return 0\n changes = [amount + 1] * (amount + 1)\n changes[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n if coin > i:\n break\n else:\n changes[i] = min(changes[i], changes[i - coin] + 1)\n if changes[-1] != amount + 1:\n return changes[-1]\n else:\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return amount\n dp = [1000000000.0 for _ in range(amount + 1)]\n dp[0] = 0\n for i in range(1, amount + 1):\n k = 1000000000.0\n for c in coins:\n if i - c >= 0:\n k = min(k, dp[i - c] + 1)\n if k != 1000000000.0:\n dp[i] = k\n return -1 if dp[amount] == 1000000000.0 else dp[amount]", "def coinchange(coins, amount):\n coins.sort(reverse=True)\n (lenc, self.res) = (len(coins), 2 ** 31 - 1)\n\n def dfs(pt, rem, count):\n if not rem:\n self.res = min(self.res, count)\n for i in range(pt, lenc):\n if coins[i] <= rem < coins[i] * (self.res - count):\n dfs(i, rem - coins[i], count + 1)\n for i in range(lenc):\n dfs(i, amount, 0)\n return self.res if self.res < 2 ** 31 - 1 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n coins = sorted(coins)\n dp = [amount + 1 for _ in range(amount + 1)]\n dp[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n if coin > i:\n break\n dp[i] = min(dp[i], dp[i - coin] + 1)\n res = dp[amount] if dp[amount] < amount + 1 else -1\n return res", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n count = [math.inf] * (amount + 1)\n count[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n if i >= coin:\n count[i] = min(count[i], count[i - coin] + 1)\n return count[amount] if count[amount] != math.inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n\n def giveChange(target):\n if target == 0:\n return 0\n if target < 0:\n return -1\n minForTarget = None\n for coin in coins:\n result = giveChange(target - coin)\n if result != -1:\n minForTarget = result + 1 if not minForTarget else min(result + 1, minForTarget)\n return minForTarget or -1\n return giveChange(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n n = len(coins)\n dp = [0] + [amount + 1 for i in range(amount)]\n for i in range(1, amount + 1):\n for c in coins:\n if i >= c:\n dp[i] = min(dp[i - c] + 1, dp[i])\n return dp[amount] if dp[amount] < amount + 1 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n self.min = 2 ** 31 - 1\n\n def dfs(index, amount, count):\n if amount == 0:\n self.min = min(self.min, count)\n if amount < 0:\n return\n for i in range(index, len(coins)):\n if coins[i] * (self.min - count) > amount >= coins[i]:\n dfs(i, amount - coins[i], count + 1)\n dfs(0, amount, 0)\n return self.min if self.min != 2 ** 31 - 1 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n ary = [amount + 1] * (amount + 1)\n ary[0] = 0\n for i in range(1, len(ary)):\n for coin in coins:\n if i - coin < 0:\n continue\n ary[i] = min(ary[i], ary[i - coin] + 1)\n return ary[amount] if ary[amount] < amount + 1 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n numOfCoins = [float('inf') for x in range(amount + 1)]\n numOfCoins[0] = 0\n for coin in coins:\n for num in range(len(numOfCoins)):\n if coin <= num:\n numOfCoins[num] = min(numOfCoins[num], numOfCoins[num - coin] + 1)\n return numOfCoins[amount] if numOfCoins[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n MAX = float('inf')\n dp = [0] + [MAX] * amount\n for i in range(1, amount + 1):\n for coin in coins:\n if i - coin >= 0:\n dp[i] = min(dp[i], dp[i - coin] + 1)\n if dp[-1] == MAX:\n return -1\n return dp[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n MAX = amount + 10\n dp = [MAX for i in range(amount + 1)]\n dp[0] = 0\n for i in range(1, amount + 1):\n curr = i\n for coin in coins:\n prev = curr - coin\n if prev >= 0:\n dp[curr] = min(dp[curr], dp[prev] + 1)\n return dp[amount] if dp[amount] != MAX else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [-1 for i in range(amount + 1)]\n dp[0] = 0\n for coin in coins:\n for i in range(coin, amount + 1):\n if i == coin:\n dp[i] = 1\n elif dp[i] == -1 and dp[i - coin] != -1:\n dp[i] = dp[i - coin] + 1\n elif dp[i] != -1 and dp[i - coin] != -1:\n dp[i] = min(dp[i], dp[i - coin] + 1)\n return dp[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def change_memo(coins, amount, memo):\n if amount not in memo:\n if amount == 0:\n best = 0\n elif amount < 0:\n best = -1\n else:\n best = None\n for c in coins:\n res = change_memo(coins, amount - c, memo)\n if res == -1:\n continue\n if best is None or res < best:\n best = res\n if best is None:\n best = -1\n else:\n best += 1\n memo[amount] = best\n return memo[amount]\n memo = {}\n change_memo(coins, amount, memo)\n return memo[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n min_coins = float('inf')\n\n def count_coins(start_coin, coin_count, remaining_amount):\n nonlocal min_coins\n if remaining_amount == 0:\n min_coins = min(min_coins, coin_count)\n return\n for i in range(start_coin, len(coins)):\n remaining_coin_allowance = min_coins - coin_count\n max_amount_possible = coins[i] * remaining_coin_allowance\n if coins[i] <= remaining_amount and remaining_amount < max_amount_possible:\n count_coins(i, coin_count + 1, remaining_amount - coins[i])\n count_coins(0, 0, amount)\n return min_coins if min_coins < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n curr = [float('inf')] * (amount + 1)\n curr[0] = 0\n coins = sorted(coins)\n for num in range(amount + 1):\n for c in coins:\n if num - c < 0:\n break\n curr[num] = min(curr[num], curr[num - c] + 1)\n return curr[amount] if curr[amount] < float('inf') else -1", "import sys\n\ndef coinchange(coins: List[int], amount: int) -> int:\n dp = [sys.maxsize] * (amount + 1)\n if amount == 0:\n return 0\n dp[amount] = 0\n for i in range(amount, -1, -1):\n for coin in coins:\n if i - coin >= 0:\n dp[i - coin] = min(dp[i] + 1, dp[i - coin])\n return -1 if dp[0] == sys.maxsize else dp[0]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def _recursive(a):\n if a == 0:\n return 0\n min_n = 1000000000.0\n for c in coins:\n if c <= a:\n sub_a = _recursive(a - c)\n if sub_a != -1:\n min_n = min(min_n, sub_a + 1)\n return min_n if min_n != 1000000000.0 else -1\n return _recursive(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n res = {}\n res[0] = 0\n for x in range(amount + 1)[1:]:\n prevs = [x - c for c in coins]\n this_res = min([res.get(y, 2 ** 31) for y in prevs]) + 1\n res[x] = this_res\n if res[amount] >= 2 ** 31:\n return -1\n else:\n return res[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n if len(coins) == 1:\n if amount % coins[0] == 0:\n return amount // coins[0]\n return -1\n dp = [0] * (amount + 1)\n for i in range(1, amount + 1):\n if i in set(coins):\n dp[i] = 1\n continue\n min_coins = float('inf')\n for coin in coins:\n if i - coin >= 0:\n min_coins = min(dp[i - coin], min_coins)\n dp[i] = min_coins + 1\n if dp[amount] == float('inf'):\n return -1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n amount_list = [i for i in range(amount + 1)]\n for i in range(amount + 1):\n if i == 0:\n amount_list[i] = 0\n elif i in coins:\n amount_list[i] = 1\n else:\n temp = []\n for coin in coins:\n if amount_list[i] - coin >= 0:\n remainder = amount_list[i] - coin\n min_coin = amount_list[remainder]\n if min_coin != -1:\n temp.append(min_coin)\n if len(temp) == 0:\n amount_list[i] = -1\n else:\n amount_list[i] = min(temp) + 1\n return amount_list[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n\n def _fewest(cs, amt):\n nonlocal memo\n if amt not in memo:\n if amt < 0:\n memo[amt] = -1\n elif amt == 0:\n memo[amt] = 0\n else:\n fewest = -1\n for c in cs:\n f = _fewest(cs, amt - c)\n if f != -1 and (fewest == -1 or f + 1 < fewest):\n fewest = f + 1\n memo[amt] = fewest\n return memo[amt]\n return _fewest(coins, amount)", "def coinchange(coins: List[int], amount: int) -> int:\n mem = {}\n mem[0] = 0\n\n def rec(amount):\n if amount < 0:\n return -1\n if amount in mem:\n return mem[amount]\n m = math.inf\n for c in coins:\n n = rec(amount - c)\n if n != -1 and n + 1 < m:\n m = n + 1\n if m == math.inf:\n m = -1\n mem[amount] = m\n return m\n if amount == 0:\n return 0\n return rec(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for i in range(len(coins)):\n coin = coins[i]\n for j in range(1, amount + 1):\n sameCoin = amount + 1\n if j - coin >= 0:\n dp[j] = min(dp[j - coin] + 1, dp[j])\n return dp[amount] if dp[amount] != amount + 1 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for partial_amount in range(1, amount + 1):\n for j in range(len(coins)):\n if coins[j] <= partial_amount:\n dp[partial_amount] = min(dp[partial_amount], dp[partial_amount - coins[j]] + 1)\n return dp[amount] if dp[amount] <= amount else -1", "def coinchange(coins: List[int], amount: int) -> int:\n num_ways = (amount + 1) * [-1]\n num_ways[0] = 0\n for v in range(1, amount + 1):\n fewest = float('inf')\n for c in coins:\n if v - c >= 0 and num_ways[v - c] != -1:\n fewest = min(num_ways[v - c], fewest)\n if fewest != float('inf'):\n num_ways[v] = 1 + fewest\n return num_ways[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def helpCoins(coins, amount, cache):\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if amount in cache:\n return cache[amount]\n curr_min = 999\n for coin in coins:\n to_go = helpCoins(coins, amount - coin, cache)\n if to_go >= 0 and to_go < curr_min:\n curr_min = to_go + 1\n if curr_min == 999:\n cache[amount] = -1\n else:\n cache[amount] = curr_min\n return cache[amount]\n return helpCoins(coins, amount, {})", "import collections\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n seen = set()\n queue = collections.deque()\n for coin in coins:\n queue.append((amount - coin, 1))\n while queue:\n curr = queue.popleft()\n if curr[0] == 0:\n return curr[1]\n if curr[0] < 0 or curr[0] in seen:\n continue\n seen.add(curr[0])\n for coin in coins:\n queue.append((curr[0] - coin, curr[1] + 1))\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n memo = {}\n\n def helper(target, options):\n if target in memo:\n return memo[target]\n else:\n best = None\n for opt in options:\n if opt == target:\n memo[target] = 1\n return 1\n elif opt < target:\n cont = helper(target - opt, options)\n if cont is not None and (best is None or cont + 1 < best):\n best = cont + 1\n memo[target] = best\n return best\n output = helper(amount, coins)\n return output if output is not None else -1", "def util(memo, coins, amount):\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n minarr = []\n for coin in coins:\n if amount - coin not in memo:\n memo[amount - coin] = self.util(memo, coins, amount - coin)\n minarr.append(memo[amount - coin])\n minarr = [m for m in minarr if m != -1]\n if not minarr:\n return -1\n return min(minarr) + 1\n\ndef coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n return self.util(memo, coins, amount)", "def coinchange(coins: List[int], amount: int) -> int:\n D = [0] * (amount + 1)\n\n def helper(rem):\n nonlocal D\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if D[rem] != 0:\n return D[rem]\n minn = float('inf')\n for coin in coins:\n res = helper(rem - coin)\n if res >= 0 and res < minn:\n minn = res + 1\n if minn == float('inf'):\n D[rem] = -1\n else:\n D[rem] = minn\n return D[rem]\n return helper(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [None for i in range(0, amount + 1)]\n dp[0] = 0\n for i in range(1, amount + 1):\n min_cost = float('inf')\n for j in range(0, len(coins)):\n if coins[j] <= i:\n min_cost = min(min_cost, dp[i - coins[j]] + 1)\n dp[i] = min_cost\n if dp[-1] > amount:\n return -1\n return dp[-1]\n coinsNeeded = {}\n coinsNeeded[0] = 0\n for n in coins:\n coinsNeeded[n] = 1\n\n def findMinCoins(amount):\n if amount < 0:\n return float('inf')\n if amount in coinsNeeded:\n return coinsNeeded[amount]\n for n in coins:\n coinsUsed = 1 + findMinCoins(amount - n)\n if amount in coinsNeeded:\n coinsNeeded[amount] = min(coinsUsed, coinsNeeded[amount])\n else:\n coinsNeeded[amount] = coinsUsed\n return coinsNeeded[amount]\n findMinCoins(amount)\n if coinsNeeded[amount] == float('inf'):\n return -1\n return coinsNeeded[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n coins.sort()\n for i in range(amount + 1):\n for j in range(len(coins)):\n if coins[j] <= amount:\n dp[i] = min(dp[i], 1 + dp[i - coins[j]])\n else:\n break\n if dp[amount] > amount:\n return -1\n else:\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n self.coins = coins\n self.amount = amount\n self.cache = {}\n res = self.getValue(self.amount)\n if res is None:\n return -1\n else:\n return res\n\ndef getValue(amount):\n if amount in self.cache:\n return self.cache[amount]\n if amount < 0:\n return None\n if amount == 0:\n return 0\n if amount in self.coins:\n return 1\n min_count = None\n for coin in self.coins:\n count = self.getValue(amount - coin)\n if count is not None:\n if min_count is None or min_count > count + 1:\n min_count = count + 1\n self.cache[amount] = min_count\n return min_count", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n s = list()\n import sys\n for i in range(0, amount + 1):\n s.append(sys.maxsize)\n s[0] = 0\n for i in range(1, amount + 1):\n m = sys.maxsize\n for j in range(0, len(coins)):\n if i - coins[j] >= 0:\n m = min(m, s[i - coins[j]])\n if m == sys.maxsize:\n s[i] = m\n else:\n s[i] = m + 1\n if s[amount] == sys.maxsize:\n s[amount] = -1\n return s[amount]", "def coinchange(coins, amount):\n dp = [amount + 1] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n for j in range(0, len(coins)):\n if coins[j] <= i:\n dp[i] = min(dp[i], dp[i - coins[j]] + 1)\n return -1 if dp[amount] > amount else dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount < 0 or not coins:\n return -1\n if amount == 0:\n return 0\n min_com = [0 for i in range(amount + 1)]\n for i in range(1, amount + 1):\n for c in coins:\n if i >= c and (min_com[i - c] > 0 or i - c == 0):\n if min_com[i] == 0:\n min_com[i] = min_com[i - c] + 1\n else:\n min_com[i] = min(min_com[i], min_com[i - c] + 1)\n if min_com[amount] == 0:\n return -1\n return min_com[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n self.smallest = float('inf')\n coins.sort(reverse=True)\n self.dfs(coins, amount, 0)\n return -1 if type(self.smallest) is float else self.smallest\n\ndef dfs(coins, amount, prev_count):\n if len(coins) == 0:\n return\n if amount % coins[0] == 0:\n self.smallest = min(self.smallest, prev_count + amount // coins[0])\n else:\n for k in range(amount // coins[0], -1, -1):\n if prev_count + k >= self.smallest:\n break\n self.dfs(coins[1:], amount - k * coins[0], prev_count + k)", "def coinchange(coins: List[int], amount: int) -> int:\n\n def make_change(sum_remaining, coins, mem):\n if sum_remaining < 0:\n return -1\n elif sum_remaining == 0:\n return 0\n elif mem[sum_remaining]:\n return mem[sum_remaining]\n else:\n min_coins = amount + 1\n for coin in coins:\n if sum_remaining - coin >= 0:\n prev_coins = make_change(sum_remaining - coin, coins, mem)\n curr_coins = 1 + prev_coins\n if curr_coins > 0 and curr_coins < min_coins:\n min_coins = curr_coins\n mem[sum_remaining] = min_coins\n return mem[sum_remaining]\n mem = [None] * (amount + 1)\n ans = make_change(amount, coins, mem)\n if ans == amount + 1:\n return -1\n else:\n return ans", "import math\n\ndef f(coins, amount, counts):\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if counts[amount - 1] != 0:\n return counts[amount - 1]\n min_val = math.inf\n for c in coins:\n res = f(coins, amount - c, counts)\n if res >= 0 and res < min_val:\n min_val = 1 + res\n if min_val == math.inf:\n counts[amount - 1] = -1\n else:\n counts[amount - 1] = min_val\n return counts[amount - 1]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount < 1:\n return 0\n counts = [0] * amount\n return f(coins, amount, counts)", "def coinchange(coins: List[int], amount: int) -> int:\n\n def helper(amount):\n if amount <= 0:\n return 0\n min_so_far = math.inf\n for i in range(len(coins)):\n if coins[i] <= amount:\n min_so_far = min(min_so_far, 1 + helper(amount - coins[i]))\n return min_so_far\n result = helper(amount)\n if result == math.inf:\n return -1\n return result", "def coinchange(coins: List[int], amount: int) -> int:\n T = len(coins)\n dp = [0 for i in range(amount + 1)]\n for n in range(1, amount + 1):\n dp[n] = math.inf\n for i in range(T):\n if n - coins[i] >= 0:\n subProbSol = dp[n - coins[i]]\n dp[n] = min(dp[n], subProbSol + 1)\n if dp[amount] == math.inf:\n return -1\n else:\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n numCoins = [float('inf') for i in range(amount)]\n for coin in coins:\n if coin - 1 < amount:\n numCoins[coin - 1] = 1\n for i in range(amount):\n minCoin = float('inf')\n change = True\n for coin in coins:\n if i == coin - 1:\n change = False\n break\n if i - coin >= 0:\n minCoin = min(numCoins[i - coin], minCoin)\n if change and minCoin != float('inf'):\n numCoins[i] = minCoin + 1\n if numCoins[-1] == float('inf'):\n return -1\n return numCoins[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def helper(remAmt, coins):\n nonlocal mem\n if remAmt in mem:\n return mem[remAmt]\n minCoins = float('inf')\n for coin in coins:\n if coin <= remAmt:\n result = 1 + helper(remAmt - coin, coins)\n minCoins = min(minCoins, result)\n else:\n break\n mem[remAmt] = minCoins\n return minCoins\n if amount < 1:\n return 0\n mem = {0: 0}\n coins.sort()\n minCoins = helper(amount, coins)\n if minCoins == float('inf'):\n return -1\n return minCoins", "def coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n return self.aux(coins, amount, memo)\n\ndef aux(coins, amount, memo):\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if amount in memo.keys():\n return memo[amount]\n minimum = 999999999\n for x in coins:\n temp = self.aux(coins, amount - x, memo)\n if temp < minimum and temp >= 0:\n minimum = temp\n if minimum == 999999999:\n memo[amount] = -1\n return memo[amount]\n memo[amount] = 1 + minimum\n return memo[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n coins = set(coins)\n d = {}\n if amount == 0:\n return 0\n\n def solve(amt):\n if amt in d:\n return d[amt]\n if amt <= 0:\n return -1\n if amt in coins:\n d[amt] = 1\n return d[amt]\n poss = []\n for c in coins:\n search = amt - c\n if search < 1:\n continue\n val = solve(search)\n if val != -1:\n poss.append(val)\n if len(poss) != 0:\n d[amt] = 1 + min(poss)\n else:\n d[amt] = -1\n return d[amt]\n return solve(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n if amount < 1:\n return 0\n self.cache = [0] * (amount + 1)\n return self.coin_change(coins, amount)\n\ndef coin_change(coins, remainder):\n if remainder < 0:\n return -1\n if remainder == 0:\n return 0\n if self.cache[remainder] != 0:\n return self.cache[remainder]\n system_max = sys.maxsize\n minimum = system_max\n for coin in coins:\n change_result = self.coin_change(coins, remainder - coin)\n if change_result >= 0 and change_result < minimum:\n minimum = 1 + change_result\n self.cache[remainder] = -1 if minimum == system_max else minimum\n return self.cache[remainder]", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n return self.dfs(coins, 0, 0, amount, -1)\n\ndef dfs(coins: List[int], idx: int, cnt: int, amount: int, minCnt: int) -> int:\n if amount == 0:\n return cnt\n if idx >= len(coins):\n return -1\n if minCnt > 0 and cnt + amount // coins[idx] + 1 > minCnt:\n return -1\n for i in range(amount // coins[idx], -1, -1):\n res = self.dfs(coins, idx + 1, cnt + i, amount - coins[idx] * i, minCnt)\n if res != -1:\n minCnt = res if minCnt == -1 else min(minCnt, res)\n return minCnt", "def coinchange(coins: List[int], amount: int) -> int:\n count = {}\n for coin in coins:\n count[coin] = 1\n count[0] = 0\n for i in range(1, amount + 1):\n ans = amount + 1\n if i in list(count.keys()):\n continue\n for coin in coins:\n if i - coin > 0 and count[i - coin] != -1:\n ans = min(count[i - coin], ans)\n if ans == amount + 1:\n count[i] = -1\n else:\n count[i] = ans + 1\n return count[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount < 1:\n return 0\n cnt = [0 for __ in range(amount)]\n return self.coinMake(coins, amount, cnt)\n\ndef coinMake(coins, rem, count):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if count[rem - 1] != 0:\n return count[rem - 1]\n MIN = 2 ** 32 - 1\n for i in coins:\n res = self.coinMake(coins, rem - i, count)\n if res >= 0 and res < MIN:\n MIN = 1 + res\n count[rem - 1] = -1 if MIN == 2 ** 32 - 1 else MIN\n return count[rem - 1]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n mem = {}\n max_amount = 10 ** 4 + 1\n\n def cc(amount):\n mem[amount] = max_amount\n for coin in coins:\n dif = amount - coin\n if dif == 0:\n mem[amount] = 1\n elif dif > 0:\n if dif not in mem:\n cc(dif)\n mem[amount] = min(mem[amount], mem[dif] + 1)\n cc(amount)\n if mem[amount] == max_amount:\n return -1\n else:\n return mem[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0 or not coins:\n return 0\n minlst = [float('inf')] * (amount + 1)\n n = len(minlst)\n minlst[0] = 0\n for i in range(1, n):\n for denom in coins:\n remainder = i - denom\n if remainder < 0:\n continue\n newsmallest = min(minlst[remainder] + 1, minlst[i])\n minlst[i] = newsmallest\n return -1 if minlst[-1] == float('inf') else minlst[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n s = list()\n s.append(0)\n for i in range(1, amount + 1):\n m = list()\n for j in range(0, len(coins)):\n if i - coins[j] >= 0:\n m.append(s[i - coins[j]])\n mm = [item for item in m if item >= 0]\n if len(mm) == 0:\n s.append(-1)\n else:\n s.append(min(mm) + 1)\n return s[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def my_coinchange(coins, rem, count):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if count[rem - 1] != 0:\n return count[rem - 1]\n my_min = float('inf')\n for coin in coins:\n res = my_coinchange(coins, rem - coin, count)\n if res >= 0 and res < my_min:\n my_min = 1 + res\n count[rem - 1] = -1 if my_min == float('inf') else my_min\n return count[rem - 1]\n if amount < 1:\n return 0\n return my_coinchange(coins, amount, [0] * amount)", "def coinchange(coins: List[int], amount: int) -> int:\n if not coins or amount < 0:\n return -1\n f = [sys.maxsize for i in range(amount + 1)]\n f[0] = 0\n for i in range(1, len(f)):\n for coin in coins:\n if i - coin >= 0 and f[i - coin] != sys.maxsize:\n f[i] = min(f[i], f[i - coin] + 1)\n if f[amount] == sys.maxsize:\n return -1\n return f[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [None for _ in range(amount + 2)]\n dp[amount + 1] = float('inf')\n dp[amount] = 0\n for i in range(amount - 1, -1, -1):\n s = float('inf')\n for c in coins:\n s = min(s, 1 + dp[min(c + i, amount + 1)])\n dp[i] = s\n if dp[0] == float('inf'):\n return -1\n return dp[0]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def helper(coins, rem, count):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if count[rem - 1] != 0:\n return count[rem - 1]\n minVal = float('inf')\n for c in coins:\n res = helper(coins, rem - c, count)\n if res >= 0 and res < minVal:\n minVal = 1 + res\n if minVal == float('inf'):\n count[rem - 1] = -1\n else:\n count[rem - 1] = minVal\n return count[rem - 1]\n if amount < 1:\n return 0\n return helper(coins, amount, [0] * amount)", "def coinchange(coins: List[int], amount: int) -> int:\n result = []\n coins.sort(reverse=True)\n max_sum = 2 ** 31 - 1\n\n def find_combinations(combination, remain, start):\n nonlocal max_sum\n if remain == 0:\n max_sum = min(max_sum, len(combination))\n return\n elif remain < 0:\n return\n for i in range(start, len(coins)):\n allowed_coins = max_sum - len(combination)\n max_value_can_be_achieved = coins[i] * allowed_coins\n if coins[i] <= remain < max_value_can_be_achieved:\n combination.append(coins[i])\n find_combinations(combination, remain - coins[i], i)\n combination.pop()\n find_combinations([], amount, 0)\n if max_sum == 2 ** 31 - 1:\n return -1\n return max_sum", "def coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n\n def solve(cur):\n if cur in memo:\n return memo[cur]\n if cur == 0:\n return 0\n arr = [float('inf')] * len(coins)\n for (i, coin) in enumerate(coins):\n if cur - coin < 0:\n arr[i] = float('inf')\n else:\n arr[i] = solve(cur - coin) + 1\n ret = min(arr)\n memo[cur] = ret\n return ret\n ans = solve(amount)\n if ans == float('inf'):\n return -1\n return ans", "def coinchange(coins: List[int], amount: int) -> int:\n N = len(coins)\n M = amount\n table = [-1] * (M + 1)\n for j in range(N + 1):\n table[0] = 0\n for m in range(1, M + 1):\n for i in range(N):\n c = coins[i]\n if c > m:\n pass\n elif table[m - c] != -1:\n if table[m] != -1:\n table[m] = min(table[m - c] + 1, table[m])\n else:\n table[m] = table[m - c] + 1\n return table[M]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def dp(t):\n if t in d:\n return d[t]\n res = float('inf')\n for c in coins:\n if t - c >= 0:\n res = min(res, dp(t - c) + 1)\n d[t] = res\n return res\n d = {0: 0}\n x = dp(amount)\n return x if x < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n\n def dfs(remaining):\n nonlocal memo\n if remaining == 0:\n return 0\n if remaining < 0:\n return -1\n if memo[remaining]:\n return memo[remaining]\n res = amount + 1\n for coin in coins:\n count = dfs(remaining - coin)\n if count == -1:\n continue\n res = min(res, 1 + count)\n memo[remaining] = res if res != amount + 1 else -1\n return memo[remaining]\n memo = [None for _ in range(amount + 1)]\n return dfs(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n dp: List[int] = [0 for _ in range(amount)]\n for i in range(amount):\n for coin in coins:\n if coin > i + 1:\n continue\n if coin == i + 1:\n dp[i] = 1\n elif dp[i - coin] != 0:\n if dp[i] == 0:\n dp[i] = dp[i - coin] + 1\n else:\n dp[i] = min(dp[i], dp[i - coin] + 1)\n return dp[amount - 1] if dp[amount - 1] != 0 else -1", "def coinCount(coins, amount, found):\n if amount < 0:\n return float('inf')\n if amount == 0:\n return 0\n if found.get(amount):\n return found[amount]\n count = 0\n minCount = float('inf')\n for coin in coins:\n if coin == amount:\n return 1\n count = 1 + coinCount(coins, amount - coin, found)\n if count < minCount:\n minCount = count\n found[amount] = minCount\n return minCount\n\ndef coinchange(coins: List[int], amount: int) -> int:\n x = coinCount(coins, amount, {})\n if x == float('inf'):\n return -1\n return x", "def coinchange(coins: List[int], amount: int) -> int:\n\n def opt(v):\n if v == 0:\n return 0\n if v in memo:\n return memo[v]\n result = float('inf')\n for i in coins:\n if v - i >= 0:\n result = min(result, opt(v - i) + 1)\n else:\n continue\n memo[v] = result\n return memo[v]\n memo = {}\n coins = opt(amount)\n if coins == float('inf'):\n return -1\n else:\n return coins", "def coinchange(coins: List[int], amount: int) -> int:\n seen = {0: 0}\n\n def helper(coins, amount):\n if amount in seen:\n return seen[amount]\n if amount < 0:\n return -1\n leastCoins = float('Inf')\n for coin in coins:\n next_least = helper(coins, amount - coin)\n if next_least != -1:\n leastCoins = min(leastCoins, 1 + next_least)\n if leastCoins == float('Inf'):\n seen[amount] = -1\n return -1\n else:\n seen[amount] = leastCoins\n return leastCoins\n return helper(coins, amount)", "def coinchange(coins: List[int], amount: int) -> int:\n coins = sorted(coins)\n memo = {x: amount + 1 for x in range(amount + 1)}\n memo[0] = 0\n for i in range(amount + 1):\n for j in range(len(coins)):\n if coins[j] <= i:\n memo[i] = min(memo[i], 1 + memo[i - coins[j]])\n if memo[amount] < amount + 1:\n return memo[amount]\n else:\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n dp = {}\n for c in coins:\n dp[c] = 1\n for i in range(amount + 1):\n for c in coins:\n if dp.get(i - c):\n if not dp.get(i):\n dp[i] = dp[i - c] + 1\n else:\n dp[i] = min(dp[i], dp[i - c] + 1)\n return dp.get(amount, -1)", "def computeMinCoins(n: int) -> int:\n if (result := self.memoization.get(n)) is not None:\n return result\n if n == 0:\n result = 0\n else:\n result = Solution.IMPOSSIBLE\n for coin in self.coins:\n if coin > n:\n continue\n if (needed_extra := self.computeMinCoins(n - coin)) != Solution.IMPOSSIBLE:\n possible_result = 1 + needed_extra\n if result == Solution.IMPOSSIBLE or result > possible_result:\n result = possible_result\n self.memoization[n] = result\n return result\n\ndef coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n if amount % coins[0] == 0:\n return amount // coins[0]\n self.coins = coins\n self.memoization = {}\n return self.computeMinCoins(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n dp = [None for _ in range(amount + 1)]\n ret = self.helper(coins, amount, dp)\n return ret if ret != float('inf') else -1\n\ndef helper(coins: List[int], amount: int, dp) -> int:\n if amount == 0:\n return 0\n if amount < coins[0]:\n return float('inf')\n ans = float('inf')\n for coin in coins:\n if amount >= coin:\n if amount == coin:\n ans = 0\n else:\n tmp = self.helper(coins, amount - coin, dp) if dp[amount - coin] == None else dp[amount - coin]\n if dp[amount - coin] == None:\n dp[amount - coin] = tmp\n ans = min(ans, tmp)\n return ans + 1 if ans != -1 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n\n def backtrack(tot):\n if tot == 0:\n return 0\n if tot not in memo:\n min_coins = float('inf')\n for coin in coins:\n if coin <= tot:\n cur_count = backtrack(tot - coin) + 1\n min_coins = min(min_coins, cur_count)\n memo[tot] = min_coins\n return memo[tot]\n out = backtrack(amount)\n return -1 if out == float('inf') else out", "def coinchange(coins: List[int], amount: int) -> int:\n memory = {}\n return self._helper(coins, amount, memory)\n\ndef _helper(coins, amount, memory):\n if amount < 0:\n return -1\n elif amount == 0:\n return 0\n elif amount in memory:\n return memory[amount]\n potential_values = []\n for coin in coins:\n new_target = amount - coin\n min_coins = self._helper(coins, new_target, memory)\n if min_coins != -1:\n potential_values.append(min_coins)\n if len(potential_values) == 0:\n memory[amount] = -1\n else:\n memory[amount] = min(potential_values) + 1\n return memory[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n d = {0: 0}\n\n def dfs(left, num):\n if left < 0:\n return -1\n if left in d:\n return d[left]\n min_ans = math.inf\n for each in coins:\n val = dfs(left - each, num + 1)\n if val >= 0:\n min_ans = min(min_ans, val)\n if min_ans == math.inf:\n d[left] = -1\n else:\n d[left] = min_ans + 1\n return d[left]\n return dfs(amount, 0)", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [0] * (amount + 1)\n return self.painful(coins, amount, dp)\n\ndef painful(coins: List[int], amount: int, dp: List[int]) -> int:\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n if dp[amount]:\n return dp[amount]\n minCost = math.inf\n for coin in coins:\n res = self.painful(coins, amount - coin, dp)\n if res != -1:\n minCost = min(minCost, 1 + res)\n dp[amount] = minCost if minCost < math.inf else -1\n return minCost if minCost < math.inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n\n def helper(amount, minAmounts):\n if amount == 0:\n return 0\n elif amount < 0:\n return math.inf\n if amount in minAmounts:\n return minAmounts[amount]\n minAmount = math.inf\n for coin in coins:\n minAmount = min(minAmount, helper(amount - coin, minAmounts) + 1)\n minAmounts[amount] = minAmount\n return minAmount\n minAmounts = dict()\n x = helper(amount, minAmounts)\n if x == math.inf:\n return -1\n return x", "def __init__():\n self.cache = dict()\n self.coin_set = set()\n\ndef helper(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n if amount in self.cache:\n return self.cache[amount]\n if amount in self.coin_set:\n return 1\n potentials = [float('inf')]\n for coin in coins:\n if amount > coin:\n potentials.append(self.helper(coins, amount - coin))\n res = 1 + min(potentials)\n self.cache[amount] = res\n return res\n\ndef coinchange(coins: List[int], amount: int) -> int:\n self.coin_set = set(coins)\n coins = sorted(coins, reverse=True)\n res = self.helper(coins, amount)\n if res == float('inf'):\n return -1\n return res", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n cache = {}\n\n def rec(amount):\n if amount == 0:\n return 0\n if amount in cache:\n return cache[amount]\n val = float('inf')\n for coin in coins:\n if amount - coin >= 0:\n val = min(val, 1 + rec(amount - coin))\n cache[amount] = val\n return val\n ans = rec(amount)\n return ans if ans != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n cache = {0: 0}\n\n def recurse(i):\n if i in cache:\n return cache[i]\n n = i + 1\n for coin in coins:\n curr = 0\n if i >= coin:\n next_amount = recurse(i - coin)\n if next_amount >= 0:\n curr = 1 + next_amount\n if curr > 0:\n n = min(n, curr)\n result = -1 if n == i + 1 else n\n cache[i] = result\n return result\n return recurse(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n\n def helper(coins, amount, dp):\n if amount < 0:\n return float('inf')\n if amount == 0:\n return 0\n if amount in dp:\n return dp[amount]\n ans = []\n for i in range(len(coins)):\n use_ci = 1 + helper(coins, amount - coins[i], dp)\n ans.append(use_ci)\n dp[amount] = min(ans)\n return dp[amount]\n if amount <= 0:\n return 0\n dp = {}\n result = helper(coins, amount, dp)\n return -1 if result == float('inf') else result", "from collections import defaultdict\n\ndef coinchange(coins: List[int], amount: int) -> int:\n\n def coin_change_for_amount(coins, amount):\n nonlocal count_amount\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if count_amount[amount] != float('inf'):\n return count_amount[amount]\n min_coins_amt = float('inf')\n for coin in coins:\n min_coins_amt_coin = coin_change_for_amount(coins, amount - coin)\n if 0 <= min_coins_amt_coin < min_coins_amt:\n min_coins_amt = min_coins_amt_coin + 1\n count_amount[amount] = -1 if min_coins_amt == float('inf') else min_coins_amt\n return count_amount[amount]\n if amount <= 0:\n return 0\n count_amount = [float('inf')] * (amount + 1)\n coin_change_for_amount(coins, amount)\n return count_amount[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n coinsNeeded = {}\n coinsNeeded[0] = 0\n for n in coins:\n coinsNeeded[n] = 1\n\n def findMinCoins(amount):\n if amount < 0:\n return float('inf')\n if amount in coinsNeeded:\n return coinsNeeded[amount]\n for n in coins:\n coinsUsed = 1 + findMinCoins(amount - n)\n if amount in coinsNeeded:\n coinsNeeded[amount] = min(coinsUsed, coinsNeeded[amount])\n else:\n coinsNeeded[amount] = coinsUsed\n return coinsNeeded[amount]\n findMinCoins(amount)\n if coinsNeeded[amount] == float('inf'):\n return -1\n return coinsNeeded[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = {}\n\n def recursion(S):\n if S == 0:\n return 0\n if S < 0:\n return float('inf')\n if S in dp:\n return dp[S]\n x = float('inf')\n for coin in coins:\n x = min(x, 1 + recursion(S - coin))\n dp[S] = x\n return x\n res = recursion(amount)\n if res == float('inf'):\n return -1\n return res", "def coinchange(coins: List[int], amount: int) -> int:\n l = [amount + 1] * (amount + 1)\n for i in range(len(l)):\n if i == 0:\n l[i] = 0\n elif all((i < c for c in coins)):\n l[i] = -1\n else:\n for j in range(len(coins)):\n if i >= coins[j]:\n num = i - coins[j]\n if num > 0 and l[num] == -1:\n if l[i] != amount + 1:\n continue\n else:\n l[i] = -1\n else:\n comb = l[num] + 1\n if l[i] == -1:\n l[i] = amount + 1\n if l[i] >= comb:\n l[i] = comb\n return l[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n coins_sorted = list(sorted(coins, reverse=True))\n memo = {}\n\n def choose(amount):\n if amount in memo:\n return memo[amount]\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n memo[amount] = -1\n for c in coins_sorted:\n if (ret := choose(amount - c)) >= 0:\n if memo[amount] != -1:\n memo[amount] = min(memo[amount], ret + 1)\n else:\n memo[amount] = ret + 1\n return memo[amount]\n return choose(amount)", "def computeMinCoins(n: int) -> int:\n if n in self.memoization:\n return self.memoization.get(n)\n if n == 0:\n result = 0\n else:\n result = Solution.IMPOSSIBLE\n for coin in self.coins:\n if coin > n:\n continue\n coins_extra = self.computeMinCoins(n - coin)\n if coins_extra == Solution.IMPOSSIBLE:\n continue\n plausible_result = 1 + coins_extra\n if result == Solution.IMPOSSIBLE or result > plausible_result:\n result = plausible_result\n self.memoization[n] = result\n return result\n\ndef coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n if amount % coins[0] == 0:\n return amount // coins[0]\n self.coins = coins\n self.memoization = {}\n return self.computeMinCoins(amount)", "import math\nfrom functools import lru_cache\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if not coins or amount < 0:\n return -1\n stack = [(0, 0)]\n answer = math.inf\n sortedCoins = sorted(coins)\n visited = set()\n while stack:\n node = stack.pop()\n (sum, coinCount) = node\n if node in visited:\n pass\n elif coinCount >= answer:\n pass\n elif sum == amount:\n answer = min(answer, coinCount)\n elif sum > amount:\n pass\n else:\n for c in sortedCoins:\n if sum + c <= amount and amount < sum + c * (answer - coinCount):\n stack.append((sum + c, coinCount + 1))\n visited.add(node)\n if answer == math.inf:\n return -1\n else:\n return answer", "def coinchange(coins: List[int], amount: int) -> int:\n cache = dict()\n\n def recursiveChange(amount):\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n if amount in cache:\n return cache[amount]\n min_val = float('inf')\n for coin_val in coins:\n combination = recursiveChange(amount - coin_val)\n if combination != -1:\n min_val = min(min_val, combination + 1)\n cache[amount] = min_val\n return min_val\n ans = recursiveChange(amount)\n if ans == float('inf'):\n return -1\n return ans", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n dp = [None] * amount\n dp[0] = 1 if 1 in coins else -1\n for i in range(1, amount):\n min_req = float('inf')\n for c in coins:\n if (i + 1) % c == 0:\n min_req = min(min_req, (i + 1) // c)\n elif (i + 1) // c > 0 and dp[i - c] != -1:\n min_req = min(min_req, dp[i - c] + 1)\n if min_req == float('inf'):\n dp[i] = -1\n else:\n dp[i] = min_req\n return dp[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount < 1:\n return 0\n self.coins = sorted(coins, reverse=True)\n self.count = {}\n return self.helper(amount)\n\ndef helper(rem):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if rem in self.count:\n return self.count[rem]\n min_count = 1000000000\n for coin in self.coins:\n res = self.helper(rem - coin)\n if res >= 0 and res < min_count:\n min_count = res + 1\n if min_count == 1000000000:\n self.count[rem] = -1\n else:\n self.count[rem] = min_count\n return self.count[rem]", "def coinchange(coins: List[int], amount: int) -> int:\n memo = [0] * (amount + 1)\n return self.dfs(coins, amount, memo)\n\ndef dfs(coins: List[int], amount: int, memo: List[int]) -> int:\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n if memo[amount] != 0:\n return memo[amount]\n minCoins = math.inf\n for coin in coins:\n res = self.dfs(coins, amount - coin, memo) + 1\n if res > 0:\n minCoins = min(minCoins, res)\n memo[amount] = minCoins if minCoins < math.inf else -1\n return minCoins if minCoins < math.inf else -1", "import sys\n\ndef helper(coin_sum, coins, memo):\n if coin_sum == 0:\n return 0\n if coin_sum < 0:\n return sys.maxsize\n if memo[coin_sum - 1] != 0:\n return memo[coin_sum - 1]\n res = sys.maxsize\n for c in coins:\n res = min(res, self.helper(coin_sum - c, coins, memo) + 1)\n memo[coin_sum - 1] = res\n return res\n\ndef coinchange(coins, amount):\n memo = [0] * amount\n res = self.helper(amount, coins, memo)\n return -1 if res == sys.maxsize else res", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [None for _ in range(amount + 1)]\n\n def fewest_num(amount, dp):\n if dp[amount] is not None:\n return dp[amount]\n if amount == 0:\n min_num = 0\n elif amount < min(coins):\n min_num = float('inf')\n elif amount in set(coins):\n min_num = 1\n else:\n min_num = float('inf')\n for coin in coins:\n if amount - coin >= 0:\n num = fewest_num(amount - coin, dp)\n min_num = min(min_num, num)\n min_num += 1\n dp[amount] = min_num\n return min_num\n min_num = fewest_num(amount, dp)\n if min_num == float('inf'):\n return -1\n return min_num", "def coinchange(coins: List[int], amount: int) -> int:\n self.memo = {0: 0}\n coins.sort()\n self.getMinCoins(coins, amount)\n if self.memo[amount] == float('inf'):\n return -1\n return self.memo[amount]\n\ndef getMinCoins(coins, amount):\n if amount in self.memo:\n return self.memo[amount]\n minCoins = float('inf')\n for coin in coins:\n if amount - coin < 0:\n break\n currCoins = self.getMinCoins(coins, amount - coin) + 1\n minCoins = min(minCoins, currCoins)\n self.memo[amount] = minCoins\n return self.memo[amount]", "def helper(amount: int) -> int:\n if amount in list(self.cache.keys()):\n return self.cache[amount]\n counts = []\n for coin in self.coins:\n if amount - coin > 0:\n counts.append(self.helper(amount - coin) + 1)\n elif amount - coin == 0:\n counts.append(1)\n break\n if counts == []:\n self.cache[amount] = sys.maxsize\n else:\n self.cache[amount] = min(counts)\n return self.cache[amount]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n self.coins = coins\n if amount == 0:\n return 0\n self.cache = {}\n res = self.helper(amount)\n return res if res < 100000000 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n d = {}\n ans = self.helper(coins, amount, d)\n if ans == 100000000:\n return -1\n return ans\n\ndef helper(coins, amount, d):\n if amount == 0:\n return 0\n ans = 100000000\n for i in range(len(coins) - 1, -1, -1):\n if coins[i] <= amount:\n if amount - coins[i] in d:\n sub_ans = d[amount - coins[i]]\n else:\n sub_ans = 1 + self.helper(coins, amount - coins[i], d)\n d[amount - coins[i]] = sub_ans\n ans = min(ans, sub_ans)\n return ans", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n coins.sort(reverse=True)\n memo = {}\n\n def dfs(step, rest_amount):\n if rest_amount < 0:\n return -1\n if rest_amount == 0:\n return 0\n if rest_amount in memo:\n return memo[rest_amount]\n min_steps = math.inf\n for coin in coins:\n rest = rest_amount - coin\n res = dfs(step + 1, rest)\n if res >= 0:\n min_steps = min(min_steps, res)\n memo[rest_amount] = min_steps + 1 if min_steps != math.inf else -1\n return memo[rest_amount]\n res = dfs(0, amount)\n return res", "def coinchange2(coins: List[int], amount: int, count) -> int:\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if count[amount - 1] != 0:\n return count[amount - 1]\n min = 100000000000\n for (i, c) in enumerate(sorted(coins)[::-1]):\n ret = self.coinchange2(coins, amount - c, count)\n if ret >= 0 and ret < min:\n min = 1 + ret\n if min == 100000000000:\n count[amount - 1] = -1\n else:\n count[amount - 1] = min\n return count[amount - 1]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount < 1:\n return 0\n return self.coinchange2(coins, amount, [0] * amount)", "def __init__():\n self.mem = {0: 0}\n\ndef getMinCoins(coins, amount):\n if amount in self.mem:\n return self.mem[amount]\n minCoins = float('inf')\n for c in coins:\n if amount - c < 0:\n break\n numCoins = self.getMinCoins(coins, amount - c) + 1\n minCoins = min(numCoins, minCoins)\n self.mem[amount] = minCoins\n return minCoins\n\ndef coinchange(coins, amount):\n minCoins = self.getMinCoins(sorted(coins), amount)\n if minCoins == float('inf'):\n return -1\n return minCoins", "def coinchange(coins: List[int], amount: int) -> int:\n memo = dict()\n\n def recurse(amount, index):\n if amount == 0:\n return 0\n if amount in memo:\n return memo[amount]\n minCoins = float('inf')\n for coin in coins:\n if amount - coin >= 0:\n response = recurse(amount - coin, 0)\n if response != -1:\n minCoins = min(minCoins, response + 1)\n memo[amount] = minCoins if minCoins != float('inf') else -1\n return memo[amount]\n return recurse(amount, 0)", "def coinchange(coins: List[int], amount: int) -> int:\n f = [float('inf') for i in range(amount + 1)]\n f[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n if i - coin >= 0 and f[i - coin] != float('inf'):\n f[i] = min(f[i], f[i - coin] + 1)\n if f[-1] == float('inf'):\n return -1\n return f[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n\n def backtrack(memo, curr=amount):\n if curr == 0:\n return 0\n if memo.get(curr):\n return memo[curr]\n minimum = math.inf\n for coin in coins:\n if curr - coin < 0:\n continue\n res = backtrack(memo, curr - coin)\n minimum = min(res, minimum)\n minimum = minimum if minimum == math.inf else minimum + 1\n memo[curr] = minimum\n return minimum\n ans = backtrack(memo)\n if ans == math.inf:\n return -1\n return ans", "def coinchange(coins: List[int], amount: int) -> int:\n cache = {}\n coins = sorted(coins, reverse=True)\n\n def helper(coins, amount, cache):\n if amount == 0:\n return 0\n elif amount in cache:\n return cache[amount]\n cache[amount] = float('inf')\n for c in coins:\n if amount - c >= 0:\n cache[amount] = min(cache[amount], helper(coins, amount - c, cache) + 1)\n return cache[amount]\n if amount == 0:\n return 0\n if min(coins) > amount:\n return -1\n ans = helper(coins, amount, {})\n return ans if ans != float('inf') else -1", "def helper(coins, amount, total, count, mem):\n if total > amount:\n return\n if total == amount:\n if total not in mem:\n mem[total] = count\n else:\n mem[total] = min(mem[total], count)\n return\n for c in coins:\n if total + c not in mem or mem[total + c] > count + 1:\n mem[total + c] = count + 1\n self.helper(coins, amount, total + c, count + 1, mem)\n return\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n if amount < min(coins):\n return -1\n mem = {}\n coins.sort(reverse=True)\n self.helper(coins, amount, 0, 0, mem)\n if amount in mem:\n return mem[amount]\n else:\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n fewest_coins = [0 for j in range(amount + 1)]\n for j in range(1, amount + 1):\n fewest_coins[j] = float('inf')\n for coin_i in range(len(coins)):\n if coins[coin_i] == j:\n fewest_coins[j] = 1\n break\n elif coins[coin_i] < j:\n if fewest_coins[j - coins[coin_i]] > 0:\n fewest_coins[j] = min(fewest_coins[j], fewest_coins[j - coins[coin_i]] + 1)\n if fewest_coins[j] == float('inf'):\n fewest_coins[j] = -1\n return fewest_coins[-1]", "def coinchange(coins: List[int], amount: int) -> int:\n coins = sorted(coins)\n M = [[0 for j in range(amount + 1)] for i in range(len(coins) + 1)]\n for j in range(1, amount + 1):\n M[0][j] = 1000000\n for i in range(1, len(coins) + 1):\n for j in range(1, amount + 1):\n if j >= coins[i - 1]:\n M[i][j] = min(1 + M[i][j - coins[i - 1]], M[i - 1][j])\n else:\n M[i][j] = M[i - 1][j]\n return M[-1][-1] if M[-1][-1] < 1000000 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n matrix = [[0 for i in range(amount + 1)] for j in range(len(coins) + 1)]\n for i in range(len(matrix)):\n matrix[i][0] = 0\n for i in range(1, amount + 1):\n matrix[0][i] = sys.maxsize\n for i in range(1, len(matrix)):\n for j in range(len(matrix[0])):\n if j < coins[i - 1]:\n matrix[i][j] = matrix[i - 1][j]\n else:\n matrix[i][j] = min(matrix[i - 1][j], 1 + matrix[i][j - coins[i - 1]])\n if matrix[-1][-1] == sys.maxsize:\n return -1\n return matrix[-1][-1]", "def __init__():\n self.counts = {}\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if amount in self.counts:\n return self.counts[amount]\n minCoins = -1\n for val in coins:\n numCoins = self.coinchange(coins, amount - val)\n if numCoins != -1:\n if minCoins == -1:\n minCoins = 1 + numCoins\n else:\n minCoins = min(minCoins, 1 + numCoins)\n self.counts[amount] = minCoins\n return minCoins", "def coinchange2(coins: List[int], amount: int) -> int:\n impossible = amount + 1\n cnts = [impossible] * impossible\n cnts[0] = 0\n for coin in coins:\n for x in range(coin, impossible):\n cnts[x] = min(cnts[x], cnts[x - coin] + 1)\n if cnts[amount] >= impossible:\n return -1\n return cnts[amount]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n impossible = amount + 1\n self.cnts = [0] * impossible\n\n def createCoins(total: int):\n if total == 0:\n return 0\n if self.cnts[total] != 0:\n return self.cnts[total]\n minCnt = impossible\n for coin in coins:\n if total - coin < 0:\n continue\n cnt = createCoins(total - coin) + 1\n minCnt = min(cnt, minCnt)\n self.cnts[total] = minCnt\n return minCnt\n retV = createCoins(amount)\n if retV >= impossible:\n return -1\n return retV", "def coinchange(coin: List[int], amount: int) -> int:\n dp = [[9999999 for _ in range(amount + 1)] for _ in range(len(coin) + 1)]\n for i in range(1, len(coin) + 1):\n dp[i][0] = 0\n for i in range(1, len(coin) + 1):\n for j in range(1, amount + 1):\n if j >= coin[i - 1]:\n dp[i][j] = min(dp[i][j - coin[i - 1]] + 1, dp[i - 1][j])\n else:\n dp[i][j] = dp[i - 1][j]\n if dp[-1][-1] == 9999999:\n return -1\n return dp[-1][-1]", "def coinchangeDynamic(coins: List[int], amount: int, memory_dict: dict) -> int:\n if amount < 0:\n return -1\n elif amount == 0:\n return 0\n elif memory_dict.get(amount) is None:\n recursive_call_output = []\n for coin_val in coins:\n recursive_call_output.append(self.coinchangeDynamic(coins, amount - coin_val, memory_dict))\n min_num_coins = float('inf')\n for num_coins in recursive_call_output:\n if num_coins >= 0 and num_coins < min_num_coins:\n min_num_coins = num_coins\n if min_num_coins == float('inf'):\n memory_dict[amount] = -1\n return -1\n else:\n memory_dict[amount] = min_num_coins + 1\n return min_num_coins + 1\n else:\n return memory_dict[amount]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n return self.coinchangeDynamic(coins, amount, {})", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [[0 for i in range(amount + 1)] for i in range(len(coins))]\n col = amount + 1\n for i in range(len(coins)):\n for j in range(1, col):\n if i == 0:\n r = i\n c = j - coins[i]\n if c < 0 or dp[r][c] == -1:\n dp[i][j] = -1\n else:\n dp[i][j] = dp[r][c] + 1\n else:\n incIndex = j - coins[i]\n if incIndex < 0 or dp[i][incIndex] == -1:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = dp[i][incIndex] + 1\n if dp[i - 1][j] != -1:\n dp[i][j] = min(dp[i - 1][j], dp[i][incIndex] + 1)\n return dp[len(coins) - 1][col - 1]", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if self.trellis == None:\n self.trellis = [math.inf] * (amount + 1)\n self.trellis[0] = 0\n if self.trellis[amount] != math.inf:\n return self.trellis[amount]\n if amount < 0:\n return -1\n minVal = math.inf\n for coin in coins:\n required = amount - coin\n if required < 0:\n continue\n val = self.trellis[required] if self.trellis[required] != math.inf else self.coinchange(coins, required)\n if val == -1:\n continue\n else:\n minVal = min(minVal, val + 1)\n if minVal == math.inf:\n minVal = -1\n self.trellis[amount] = min(self.trellis[amount], minVal)\n return minVal", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n arr = coins\n w = amount\n n = len(arr)\n t = [[0] * (w + 1) for _ in range(n + 1)]\n for i in range(n + 1):\n for j in range(w + 1):\n if j == 0 and i != 0:\n t[i][j] = 0\n if i == 1 and j != 0:\n t[i][j] = int(j / arr[i - 1]) if j % arr[i - 1] == 0 else math.inf\n for i in range(2, n + 1):\n for j in range(1, w + 1):\n if arr[i - 1] <= j:\n t[i][j] = min(t[i][j - arr[i - 1]] + 1, t[i - 1][j])\n else:\n t[i][j] = t[i - 1][j]\n return -1 if t[n][w] == math.inf else t[n][w]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def coinchangeHelper(coins, amount, memoisation={}):\n if amount == 0:\n return 0\n if amount < 0:\n return float('inf')\n if amount in memoisation:\n return memoisation[amount]\n min_coins_used = float('inf')\n for i in range(len(coins) - 1, -1, -1):\n min_coins_used = min(1 + coinchangeHelper(coins, amount - coins[i], memoisation), min_coins_used)\n memoisation[amount] = min_coins_used\n return min_coins_used\n result = coinchangeHelper(coins, amount)\n return result if result != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n\n def dp(m):\n if m in coins:\n return 1\n if m == 0:\n return 0\n if m < 0:\n return float('inf')\n if m not in memo:\n ans = float('inf')\n for v in coins:\n ans = min(1 + dp(m - v), ans)\n memo[m] = ans\n return memo[m]\n return dp(amount) if dp(amount) != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n coinsCount = dict()\n for i in range(1, amount + 1):\n coinsCount[i] = 9999\n coinsCount[0] = 0\n for i in range(1, amount + 1):\n for icoin in range(0, len(coins)):\n curDenom = coins[icoin]\n difference = i - curDenom\n if difference >= 0:\n coinsCount[i] = min(1 + coinsCount[difference], coinsCount[i])\n elif difference == 0:\n coinsCount[i] += 1\n if coinsCount[amount] != 9999:\n return coinsCount[amount]\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n self.dp = {}\n min_ = sys.maxsize\n for coin in coins:\n if amount - coin >= 0:\n min_ = min(min_, 1 + self.change(amount - coin, coins))\n if min_ == sys.maxsize:\n return -1\n return min_\n\ndef change(amount, coins):\n if amount in self.dp:\n return self.dp[amount]\n if amount == 0:\n self.dp[amount] = 0\n return 0\n if amount in coins:\n self.dp[amount] = 1\n return 1\n min_ = sys.maxsize\n for coin in coins:\n if amount - coin >= 0:\n min_ = min(min_, 1 + self.change(amount - coin, coins))\n self.dp[amount] = min_\n return min_", "def coinchange(coins: List[int], amount: int) -> int:\n N = [0 for i in range(amount + 1)]\n N[0] = 0\n for i in range(1, amount + 1):\n temp = [i - j for j in coins]\n history = [N[temp2] for temp2 in temp if temp2 <= i and temp2 >= 0 and (N[temp2] != -1)]\n if len(history) == 0:\n N[i] = -1\n else:\n N[i] = 1 + min([N[temp2] for temp2 in temp if temp2 <= i and temp2 >= 0 and (N[temp2] != -1)])\n return N[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n round = 0\n d = set([0])\n while d or round == 0:\n round += 1\n d = set([coin + s for coin in coins for s in d if coin + s <= amount and coin + s not in d])\n if amount in d:\n return round\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [-1 for i in range(amount + 1)]\n dp[0] = 0\n for i in range(amount):\n mn = math.inf\n pos = False\n for c in coins:\n if i + 1 >= c and dp[i - c + 1] >= 0:\n pos = True\n mn = min(mn, dp[i + 1 - c] + 1)\n if pos:\n dp[i + 1] = mn\n return dp[-1]", "def numCoins(coins, amount):\n if amount in self.memory:\n return self.memory[amount]\n if amount == 0:\n return 0\n ncarr = []\n carr = []\n for c in coins:\n if amount >= c:\n nnc = self.numCoins(coins, amount - c)\n ncarr.append(nnc + 1)\n carr.append(c)\n if len(ncarr) > 0:\n nc = min(ncarr)\n self.memory[amount] = nc\n return nc\n else:\n return float('inf')\n\ndef coinchange(coins: List[int], amount: int) -> int:\n self.memory = {}\n nc = self.numCoins(coins, amount)\n if nc == float('inf'):\n return -1\n return nc", "def coinchange(coins: List[int], amount: int) -> int:\n n = len(coins)\n dp = [[float('inf') for _ in range(amount + 1)] for _ in range(n)]\n for r in range(n):\n dp[r][0] = 0\n for a in range(1, amount + 1):\n (div, mod) = divmod(a, coins[0])\n if mod == 0:\n dp[0][a] = div\n for i in range(1, n):\n for a in range(1, amount + 1):\n if a - coins[i] >= 0:\n dp[i][a] = min(dp[i][a - coins[i]] + 1, dp[i - 1][a])\n else:\n dp[i][a] = dp[i - 1][a]\n return dp[-1][-1] if dp[-1][-1] != float('inf') else -1", "import sys\n\ndef coinchange(coins: List[int], amount: int) -> int:\n res = self.helper(sorted(coins, reverse=True), amount, {})\n if res == float('inf'):\n return -1\n return res\n\ndef helper(coins, amount, dAmounts):\n if amount < 0:\n return float('inf')\n if amount == 0:\n return 0\n if amount in dAmounts:\n return dAmounts[amount]\n for c in coins:\n pathCount = 1 + self.helper(coins, amount - c, dAmounts)\n dAmounts[amount] = min(dAmounts.get(amount, pathCount), pathCount)\n return dAmounts[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('Inf') for _ in range(amount + 1)]\n dp[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n if i >= coin and dp[i - coin] != float('Inf'):\n dp[i] = min(dp[i], dp[i - coin] + 1)\n if dp[amount] == float('Inf'):\n return -1\n return dp[amount]", "INF = 100000000000000000\n\ndef hashIntArr(i_arr):\n return '-'.join(list(map(str, i_arr)))\n\ndef coinchange(coins: List[int], amount: int) -> int:\n coins = sorted(coins)\n mc = [[0 if j == 0 else INF for j in range(amount + 1)] for _ in range(len(coins) + 1)]\n for c in range(1, len(coins) + 1):\n coin_value = coins[c - 1]\n for a in range(1, amount + 1):\n if coin_value <= a:\n mc[c][a] = min(1 + mc[c][a - coin_value], mc[c - 1][a])\n else:\n mc[c][a] = mc[c - 1][a]\n min_coins = mc[len(coins)][amount]\n return min_coins if min_coins < INF else -1", "def coinchange(coins: List[int], amount: int) -> int:\n n = len(coins)\n t = [[float('inf') - 1] * (amount + 1) for _ in range(n + 1)]\n for i in range(n + 1):\n t[i][0] = 0\n for j in range(amount + 1):\n t[0][j] = float('inf') - 1\n if j % coins[0] == 0:\n t[1][j] = j // coins[0]\n else:\n t[1][j] = float('inf') - 1\n for i in range(1, n + 1):\n for j in range(1, amount + 1):\n if coins[i - 1] <= j:\n t[i][j] = min(1 + t[i][j - coins[i - 1]], t[i - 1][j])\n else:\n t[i][j] = t[i - 1][j]\n return t[n][amount] if t[n][amount] != float('inf') else -1", "def __init__():\n self.memo = {}\n\ndef coinchange(coins: List[int], amount: int) -> int:\n ans = self.helper(coins, amount)\n if ans == float('inf'):\n return -1\n return ans\n\ndef helper(coins, remaining):\n if remaining == 0:\n return 0\n if remaining < 0:\n return float('inf')\n if remaining in self.memo:\n return self.memo[remaining]\n self.memo[remaining] = min([self.helper(coins, remaining - i) for i in coins[::-1]]) + 1\n return self.memo[remaining]", "def coinchange(coins: List[int], amount: int) -> int:\n self.coins = coins\n self.amount_dict = {0: 0}\n for coin in coins:\n self.amount_dict[coin] = 1\n return self.coinchangeHelp(amount)\n\ndef coinchangeHelp(amount: int) -> int:\n if amount < 0:\n return -1\n if amount in self.amount_dict:\n return self.amount_dict[amount]\n max_coin = amount + 1\n for coin in self.coins:\n cur_coin = self.coinchangeHelp(amount - coin)\n if cur_coin >= 0:\n max_coin = min(max_coin, cur_coin + 1)\n max_coin = max_coin if max_coin != amount + 1 else -1\n self.amount_dict[amount] = max_coin\n return max_coin", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [0]\n length = len(coins)\n for i in range(1, amount + 1):\n dp += [9999]\n for j in range(length):\n if i >= coins[j] and dp[int(i - coins[j])] != 9999:\n dp[i] = min(dp[i], dp[int(i - coins[j])] + 1)\n if dp[amount] == 9999:\n return -1\n return dp[amount]", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n coins = sorted(coins)\n best_so_far = math.inf\n\n def rec(C, A, used):\n nonlocal best_so_far\n if A == 0:\n best_so_far = min(best_so_far, used)\n elif C:\n for i in range(A // C[-1], -1, -1):\n if (best_so_far - used) * C[-1] >= A:\n rec(C[:-1], A - i * C[-1], used + i)\n rec(coins, amount, 0)\n return best_so_far if best_so_far != math.inf else -1", "import math\nfrom functools import lru_cache\n\ndef coinchange(coins: List[int], amount: int) -> int:\n result = self.recurse(amount, tuple(coins))\n if result == math.inf:\n result = -1\n return result\n\ndef recurse(amount: int, coins: tuple) -> int:\n if amount < 0:\n return math.inf\n elif amount == 0:\n return 0\n elif amount in coins:\n return 1\n else:\n least = math.inf\n for c in coins:\n val = self.recurse(amount - c, coins)\n least = min(least, val)\n return least + 1", "def coinchange(coins: List[int], amount: int) -> int:\n\n def helper(coins, rem, counts):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if counts[rem - 1] != 0:\n return counts[rem - 1]\n min_val = float('inf')\n for coin in coins:\n res = helper(coins, rem - coin, counts)\n if res >= 0 and res < min_val:\n min_val = res + 1\n if min_val == float('inf'):\n counts[rem - 1] = -1\n else:\n counts[rem - 1] = min_val\n return counts[rem - 1]\n if amount < 1:\n return 0\n return helper(coins, amount, [0] * amount)", "def coinchange(coins: List[int], target: int) -> int:\n table = [[float('inf') for _ in range(target + 1)] for _ in range(len(coins) + 1)]\n for i in range(len(coins) + 1):\n table[i][0] = 0\n for i in range(1, len(coins) + 1):\n for j in range(target + 1):\n if coins[i - 1] <= j:\n a = 1 + table[i][j - coins[i - 1]]\n else:\n a = float('inf')\n b = table[i - 1][j]\n if a <= b:\n table[i][j] = a\n else:\n table[i][j] = b\n return table[-1][-1] if table[-1][-1] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n self.cache = {}\n return self.solve(coins, amount)\n\ndef solve(coins, amount):\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n if amount in self.cache:\n return self.cache[amount]\n best = -1\n for c in coins:\n add = self.solve(coins, amount - c)\n if add != -1:\n if best == -1:\n best = add + 1\n else:\n best = min(best, add + 1)\n self.cache[amount] = best\n return best", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n d = {}\n for v in coins:\n d[v] = True\n min_coin = coins[-1]\n if not coins or not amount:\n return 0\n if len(coins) == 1:\n if amount % coins[0] == 0:\n return int(amount / coins[0])\n else:\n return -1\n self.memo = {}\n return self.fewest(coins, amount, d, min_coin)\n\ndef fewest(coins, amount, d_value, min_coin):\n if amount in self.memo:\n return self.memo[amount]\n if amount in d_value:\n return 1\n elif amount < min_coin:\n return -1\n _min = float('inf')\n for v in coins:\n ret = self.fewest(coins, amount - v, d_value, min_coin)\n if ret > 0:\n _min = min(_min, ret + 1)\n _min = -1 if _min == float('inf') else _min\n self.memo[amount] = _min\n return _min", "def coinchange(coins, amount):\n n = len(coins)\n dp = [[math.inf for _ in range(amount + 1)] for _ in range(n)]\n for (i, coin) in enumerate(coins):\n for t in range(amount + 1):\n if t == 0:\n dp[i][t] = 0\n if i > 0:\n dp[i][t] = dp[i - 1][t]\n if t >= coin:\n dp[i][t] = min(dp[i][t], dp[i][t - coin] + 1)\n return -1 if dp[n - 1][amount] == math.inf else dp[n - 1][amount]", "def coinchange(coins: List[int], amount: int) -> int:\n dp_table = [float('inf')] * (amount + 1)\n return self.dp(dp_table, coins, amount)\n\ndef dp(dp_table: [float], coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n if dp_table[amount] != float('inf'):\n return dp_table[amount]\n res = float('inf')\n for coin in coins:\n subpb = self.dp(dp_table, coins, amount - coin)\n if subpb == -1:\n continue\n res = min(res, subpb + 1)\n dp_table[amount] = res if res != float('inf') else -1\n return dp_table[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n state = [float('inf')] * amount\n if amount < 1:\n return 0\n max_coin = 0\n for c in coins:\n max_coin = max(c, max_coin)\n if c <= amount:\n state[c - 1] = 1\n for i in range(amount):\n for c in coins:\n if i - c >= 0:\n state[i] = min(state[i - c] + 1, state[i])\n return state[-1] if state[-1] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n dp = [0] * (amount + 1)\n for item in range(amount + 1):\n if item < coins[0] and item != 0:\n dp[item] = -1\n elif item == 0:\n dp[item] = 0\n if amount < coins[0] and amount == 0:\n return 0\n elif amount < coins[0]:\n return -1\n for i in range(coins[0], amount + 1):\n count = 0\n for j in coins:\n if i - j < 0:\n break\n elif dp[i - j] != -1:\n count += 1\n if count > 0:\n dp[i] = math.ceil(i / coins[0])\n for j in coins:\n if i - j < 0:\n break\n elif dp[i - j] == -1:\n continue\n else:\n dp[i] = min(dp[i], 1 + dp[i - j])\n else:\n dp[i] = -1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount < 1:\n return 0\n self.coins = coins\n self.count = {}\n self.recur_count = 0\n ans = self.helper(amount)\n return ans\n\ndef helper(rem):\n self.recur_count += 1\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if rem in self.count:\n return self.count[rem]\n min_count = 1000000000\n for coin in self.coins:\n res = self.helper(rem - coin)\n if res >= 0 and res < min_count:\n min_count = res + 1\n if min_count == 1000000000:\n self.count[rem] = -1\n else:\n self.count[rem] = min_count\n return self.count[rem]", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [-1] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n for coin in coins[::-1]:\n j = i - coin\n if j < 0 or dp[j] == -1:\n continue\n if dp[i] == -1:\n dp[i] = dp[j] + 1\n else:\n dp[i] = min(dp[i], dp[j] + 1)\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n memo = dict()\n\n def dp(n):\n if n in memo:\n return memo[n]\n if n == 0:\n return 0\n if n < 0:\n return -1\n res = 1000\n for coin in coins:\n if dp(n - coin) == -1:\n continue\n res = min(res, 1 + dp(n - coin))\n memo[n] = res if res != 1000 else -1\n return memo[n]\n return dp(amount)", "def numCoins(coins, amount):\n if amount in self.memory:\n return self.memory[amount]\n nc = float('inf')\n for c in coins:\n if amount >= c:\n nnc = self.numCoins(coins, amount - c)\n nc = min(nc, nnc + 1)\n self.memory[amount] = nc\n return nc\n\ndef coinchange(coins: List[int], amount: int) -> int:\n self.memory = {}\n self.memory[0] = 0\n for c in coins:\n self.memory[c] = 1\n nc = self.numCoins(coins, amount)\n if nc == float('inf'):\n return -1\n return nc", "def coinchange(coins: List[int], amount: int) -> int:\n memo = {}\n\n def dfs(amount, path):\n if amount < 0:\n return float('inf')\n if amount == 0:\n return 0\n if amount in memo:\n return memo[amount]\n ans = float('inf')\n for i in coins:\n r = dfs(amount - i, path + 1)\n if r != float('inf'):\n ans = min(ans, r + 1)\n memo[amount] = ans\n return ans\n ret = dfs(amount, 0)\n return ret if ret != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n\n def dfs(amt, idx):\n if idx < 0:\n if amt == 0:\n return 0\n else:\n return float('inf')\n if amt < 0:\n return float('inf')\n if amt == coins[idx]:\n return 1\n return min(dfs(amt - coins[idx], idx) + 1, dfs(amt, idx - 1))\n res = dfs(amount, len(coins) - 1)\n return res if res < float('inf') else -1", "def do_du_tab(coins, amount):\n dp_tab = [math.inf for _ in range(amount + 1)]\n dp_tab[0] = 0\n for i in range(len(coins)):\n for a in range(1, amount + 1):\n if a >= coins[i]:\n dp_tab[a] = min(dp_tab[a], 1 + dp_tab[a - coins[i]])\n return dp_tab[amount]\n\ndef do_td_mem(cache, coins, amount, index):\n if amount == 0:\n return 0\n if len(coins) <= index:\n return math.inf\n if cache[index][amount] == math.inf:\n count_keeping_element = math.inf\n if coins[index] <= amount:\n temp = self.do_td_mem(cache, coins, amount - coins[index], index)\n if temp != math.inf:\n count_keeping_element = temp + 1\n count_skipping_element = self.do_td_mem(cache, coins, amount, index + 1)\n cache[index][amount] = min(count_keeping_element, count_skipping_element)\n return cache[index][amount]\n\ndef do_bf(coins, amount, index):\n if amount == 0:\n return 0\n n = len(coins)\n if n <= index:\n return math.inf\n count_keeping_element = math.inf\n if coins[index] <= amount:\n temp = self.do_bf(coins, amount - coins[index], index)\n if temp != math.inf:\n count_keeping_element = temp + 1\n count_skipping_element = self.do_bf(coins, amount, index + 1)\n return min(count_keeping_element, count_skipping_element)\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount < 1:\n return 0\n coins.sort()\n output = self.do_du_tab(coins, amount)\n return -1 if output == math.inf else output", "import math\n\ndef helper(amount, coins, records):\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n if records[amount - 1] != -2:\n min_number = records[amount - 1]\n else:\n min_number = math.inf\n for c in coins:\n val = helper(amount - c, coins, records)\n if val != -1:\n val += 1\n min_number = min(val, min_number)\n if min_number == math.inf:\n records[amount - 1] = -1\n return -1\n else:\n records[amount - 1] = min_number\n return min_number\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n records = [-2] * amount\n return helper(amount, coins, records)", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [[float('inf')] * (amount + 1) for _ in range(len(coins))]\n for r in range(len(coins)):\n dp[r][0] = 0\n for r in range(len(coins)):\n for c in range(1, amount + 1):\n take = leave = float('inf')\n if c - coins[r] >= 0:\n take = dp[r][c - coins[r]] + 1\n if r > 0:\n leave = dp[r - 1][c]\n dp[r][c] = min(leave, take)\n return dp[-1][-1] if dp[-1][-1] != float('inf') else -1", "def coinchange(coins: List[int], a: int) -> int:\n l = len(coins)\n mem = []\n for i in range(l + 1):\n mem.append([0] * (a + 1))\n for j in range(a + 1):\n if i == 0:\n mem[i][j] = float('inf')\n if j == 0:\n mem[i][j] = 0\n if i > 0 and j > 0:\n if coins[i - 1] <= j:\n mem[i][j] = min(1 + mem[i][j - coins[i - 1]], mem[i - 1][j])\n else:\n mem[i][j] = mem[i - 1][j]\n if mem[l][a] == float('inf'):\n return -1\n return mem[l][a]", "def coinchange(coins: List[int], amount: int) -> int:\n n = len(coins)\n dp = [[0 for j in range(amount + 1)] for i in range(n)]\n for j in range(amount + 1):\n dp[0][j] = -1 if j % coins[0] else j // coins[0]\n for i in range(1, n):\n for j in range(1, amount + 1):\n includeDenom = -1 if coins[i] > j else dp[i][j - coins[i]]\n excludeDenom = dp[i - 1][j]\n if includeDenom == -1 and excludeDenom == -1:\n dp[i][j] = -1\n elif includeDenom == -1:\n dp[i][j] = excludeDenom\n elif excludeDenom == -1:\n dp[i][j] = includeDenom + 1\n else:\n dp[i][j] = min(includeDenom + 1, excludeDenom)\n return dp[n - 1][amount]", "def coinchange(coins: List[int], amount: int) -> int:\n memo = [[float('inf') for _ in range(amount + 1)] for _ in range(len(coins))]\n for x in range(len(coins)):\n memo[x][0] = 0\n for (i, coin) in enumerate(coins):\n for tot in range(1, amount + 1):\n if i > 0:\n memo[i][tot] = memo[i - 1][tot]\n if coin <= tot:\n memo[i][tot] = min(memo[i][tot], memo[i][tot - coin] + 1)\n out = memo[len(coins) - 1][amount]\n return -1 if out == float('inf') else out", "def coinchange(coins: List[int], amount: int) -> int:\n coins = set(coins)\n dp = [float('inf') if i not in coins else 1 for i in range(amount + 1)]\n result = self.helper(coins, amount, dp)\n return -1 if result == float('inf') else result\n\ndef helper(coins, amount, dp):\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if dp[amount] != float('inf'):\n return dp[amount]\n current_min = float('inf')\n for coin in coins:\n result = self.helper(coins, amount - coin, dp)\n if result != -1:\n current_min = min(current_min, 1 + result)\n if current_min == float('inf'):\n dp[amount] = -1\n return -1\n dp[amount] = current_min\n return current_min", "def coinchange(coins: List[int], amount: int) -> int:\n self.amount = amount\n self.coins = coins\n n = len(coins)\n self.memo = [-1] * (self.amount + 1)\n val = self.coindp(amount)\n if val == float('inf'):\n return -1\n else:\n return val\n\ndef coindp(i):\n if i < 0:\n return float('inf')\n if i == 0:\n return 0\n if self.memo[i] >= 0:\n return self.memo[i]\n mini = float('inf')\n for coin in self.coins:\n mini = min(mini, self.coindp(i - coin) + 1)\n self.memo[i] = mini\n return self.memo[i]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def dfs(start, amount, n_coins):\n coin = coins[start]\n div = amount // coin\n amount %= coin\n n_coins += div\n if amount == 0:\n self.minimum = min(n_coins, self.minimum)\n return\n if start < length:\n dfs(start + 1, amount, n_coins)\n next_coin = coins[start + 1]\n for _ in range(div):\n amount += coin\n n_coins -= 1\n if (self.minimum - n_coins - 1) * next_coin + 1 > amount:\n dfs(start + 1, amount, n_coins)\n else:\n break\n coins.sort(reverse=True)\n self.minimum = float('inf')\n length = len(coins) - 1\n dfs(0, amount, 0)\n return self.minimum if self.minimum < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n coins.sort(reverse=True)\n res = amount // coins[-1] + 1\n\n def comb(cursum, num, index):\n nonlocal res\n if (amount - cursum) / coins[index] >= res - num:\n return\n for i in range(index, len(coins)):\n newsum = cursum + coins[i]\n if newsum == amount:\n res = min(num + 1, res)\n return\n elif newsum < amount:\n comb(newsum, num + 1, i)\n comb(0, 0, 0)\n if res == amount // coins[-1] + 1:\n return -1\n return res", "def coinchange(coin: List[int], sum1: int) -> int:\n maxv = float('inf') - 1\n n = len(coin)\n t = [[0 for j in range(sum1 + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n for j in range(sum1 + 1):\n if i == 0 and j == 0:\n t[i][j] = maxv\n elif j == 0:\n t[i][j] = 0\n elif i == 0:\n t[i][j] = maxv\n for i in range(1, n + 1):\n for j in range(1, sum1 + 1):\n if coin[i - 1] <= j:\n t[i][j] = min(t[i][j - coin[i - 1]] + 1, t[i - 1][j])\n else:\n t[i][j] = t[i - 1][j]\n if t[n][sum1] == float('inf'):\n return -1\n return t[n][sum1]", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if not coins:\n return -1\n if amount == 0:\n return 0\n memo = [0] * amount\n\n def findNumCoins(remainingAmount: int) -> int:\n nonlocal memo\n if remainingAmount < 0:\n return -1\n if remainingAmount == 0:\n return 0\n memo_idx = remainingAmount - 1\n if memo[memo_idx] != 0:\n return memo[memo_idx]\n local_min = math.inf\n for coin in coins:\n res = findNumCoins(remainingAmount - coin)\n if res >= 0:\n local_min = min(local_min, 1 + res)\n num_coins = -1 if local_min == math.inf else local_min\n memo[memo_idx] = num_coins\n return num_coins\n return findNumCoins(amount)", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [0] * (amount + 1)\n for i in range(1, amount + 1):\n minn = float('inf')\n for j in coins:\n if i == j:\n minn = min(minn, 1)\n continue\n if i - j > 0:\n minn = min(minn, 1 + dp[i - j])\n dp[i] = minn\n return dp[amount] if dp[amount] != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n self.count = [float('inf')] * (amount + 1)\n self.count[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n rest = i - coin\n if rest >= 0 and self.count[rest] != float('inf'):\n self.count[i] = min(1 + self.count[rest], self.count[i])\n if self.count[-1] == float('inf'):\n return -1\n else:\n return self.count[-1]", "from functools import lru_cache\n\ndef coinchange(coins: List[int], amount: int) -> int:\n dict_ = set(coins)\n count = [0] * amount\n\n def top_down(rem):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if count[rem - 1] != 0:\n return count[rem - 1]\n min_ = float('inf')\n for coin in dict_:\n res = top_down(rem - coin)\n if res >= 0:\n min_ = min(1 + res, min_)\n count[rem - 1] = -1 if min_ == float('inf') else min_\n return count[rem - 1]\n\n def bottom_up():\n dpa = [float('inf')] * (amount + 1)\n dpa[0] = 0\n for i in range(1, len(dpa)):\n for coin in dict_:\n if i >= coin:\n remainder = i - coin\n dpa[i] = min(dpa[remainder] + 1, dpa[i])\n return dpa[amount] if dpa[amount] != float('inf') else -1\n return bottom_up()", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n coins.sort()\n self.coins = coins\n self.memo = {}\n self.recursion(amount)\n return -1 if self.memo[amount] == float('inf') else self.memo[amount]\n\ndef recursion(amt):\n min_coins = float('inf')\n if amt == 0:\n return 0\n if amt in self.memo:\n return self.memo[amt]\n for coin in self.coins:\n if coin > amt:\n break\n x = self.recursion(amt - coin)\n min_coins = min(min_coins, x)\n self.memo[amt] = 1 + min_coins\n return self.memo[amt]", "def coinchange(coins: List[int], amount: int) -> int:\n N = len(coins)\n mem = [[None for i in range(amount + 1)] for j in range(N + 1)]\n\n def helper(target, i):\n if mem[i][target] != None:\n return mem[i][target]\n if target == 0:\n return 0\n if i == N and target > 0:\n return float('inf')\n if coins[i] > target:\n mem[i][target] = helper(target, i + 1)\n else:\n include = 1 + helper(target - coins[i], i)\n exclude = helper(target, i + 1)\n mem[i][target] = min(include, exclude)\n return mem[i][target]\n ans = helper(amount, 0)\n return ans if ans != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n count = collections.defaultdict(int)\n\n def coinchangeHelper(coins, rem, count):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if count[rem] != 0:\n return count[rem]\n minCount = 2 ** 32\n for coin in coins:\n makeChange = coinchangeHelper(coins, rem - coin, count)\n if makeChange > -1 and makeChange < minCount:\n minCount = makeChange + 1\n count[rem] = -1 if minCount == 2 ** 32 else minCount\n return count[rem]\n return coinchangeHelper(coins, amount, count)", "def coinchange(coins, amount):\n coins.sort()\n stack = [(0, 0, len(coins))]\n min_steps = 2 ** 31\n while len(stack) != 0:\n (steps, accumulated, sequence) = stack.pop()\n if accumulated == amount:\n min_steps = min(min_steps, steps)\n if accumulated > amount or amount - accumulated > coins[sequence - 1] * (min_steps - steps):\n continue\n for (seq, coin) in enumerate(coins[:sequence]):\n stack.append((steps + 1, accumulated + coin, seq + 1))\n return min_steps if min_steps != 2 ** 31 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [math.inf] * (amount + 1)\n dp[0] = 0\n for i in range(1, amount + 1):\n for c in coins:\n if i - c >= 0:\n dp[i] = min(dp[i], dp[i - c] + 1)\n return dp[amount] if dp[amount] != math.inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [[math.inf for _ in range(amount + 1)] for _ in coins]\n for i in range(len(coins)):\n dp[i][0] = 0\n for i in range(1, amount + 1):\n if coins[0] <= i:\n dp[0][i] = 1 + dp[0][i - coins[0]]\n for i in range(1, len(coins)):\n for j in range(1, amount + 1):\n (take, leave) = (math.inf, math.inf)\n if coins[i] <= j:\n take = 1 + dp[i][j - coins[i]]\n leave = dp[i - 1][j]\n dp[i][j] = min(take, leave)\n return dp[-1][-1] if dp[-1][-1] != math.inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n if len(coins) == 0:\n return 0\n coins = sorted(coins, reverse=True)\n memo = {}\n\n def coinchangeRec(index, amount):\n if amount == 0:\n return 0\n if amount < 0 or index == len(coins):\n return math.inf\n if (index, amount) in memo:\n return memo[index, amount]\n withCoin = coinchangeRec(index, amount - coins[index]) + 1\n withoutCoin = coinchangeRec(index + 1, amount)\n memo[index, amount] = min(withCoin, withoutCoin)\n return min(withCoin, withoutCoin)\n minCoins = coinchangeRec(0, amount)\n if minCoins == math.inf:\n return -1\n return minCoins", "def aux(coins, amount, cache):\n if amount in cache:\n return cache[amount]\n res = -1\n for i in range(len(coins)):\n if coins[i] < amount:\n right = cache[amount - coins[i]] if amount - coins[i] in cache else self.aux(coins, amount - coins[i], cache)\n if right != -1 and res == -1:\n res = 1 + right\n elif right != -1 and res != -1:\n res = min(res, 1 + right)\n cache[amount] = res\n return cache[amount]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n cache = dict(list(zip(coins, [1] * len(coins))))\n return self.aux(coins, amount, cache)", "def coinchange(coins: List[int], amount: int) -> int:\n dic = {0: 0}\n\n def change(amount):\n if amount < 0:\n return -1\n if amount in dic:\n return dic[amount]\n res = [change(amount - i) for i in coins if change(amount - i) >= 0]\n if not res:\n dic[amount] = -1\n else:\n dic[amount] = min(res) + 1\n return dic[amount]\n return change(amount)", "def __init__():\n self.table = {}\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if amount in self.table:\n return self.table[amount]\n possible_answers = [self.coinchange(coins, amount - coin) + 1 for coin in coins]\n possible_answers = [ans for ans in possible_answers if ans >= 1]\n if possible_answers:\n ans = min(possible_answers)\n else:\n ans = -1\n self.table[amount] = ans\n return ans", "def coinchange(coins: List[int], amount: int) -> int:\n sz = len(coins) + 1\n dp = [[sys.maxsize] * sz for _ in range(amount + 1)]\n for i in range(sz):\n dp[0][i] = 0\n for a in range(1, amount + 1):\n for i in range(1, sz):\n dp[a][i] = dp[a][i - 1]\n if a - coins[i - 1] >= 0:\n dp[a][i] = min(1 + dp[a - coins[i - 1]][i], dp[a][i])\n return -1 if dp[amount][sz - 1] == sys.maxsize else dp[amount][sz - 1]", "def coinchange(coins: List[int], a: int) -> int:\n if a == 0:\n return 0\n dp = [-1 for i in range(a + 1)]\n dp[0] = 1\n coins.sort()\n for i in range(1, len(coins) + 1):\n for j in range(1, a + 1):\n if coins[i - 1] == j:\n dp[j] = 1\n else:\n c = -1\n if j - coins[i - 1] > 0 and dp[j - coins[i - 1]] != -1:\n c = dp[j - coins[i - 1]] + 1\n d = dp[j]\n if c != -1 and d != -1:\n dp[j] = min(c, d)\n elif c == -1 and d != -1:\n dp[j] = d\n elif c != -1:\n dp[j] = c\n if dp[a] == -1:\n return -1\n else:\n return dp[a]", "def coinchange(coins, amount):\n if amount < 1:\n return 0\n\n def count_change(coins, amount, dic={}):\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if amount in dic:\n return dic[amount]\n minimum = float('inf')\n for i in range(len(coins)):\n current = count_change(coins, amount - coins[i], dic)\n if current >= 0 and current < minimum:\n minimum = 1 + current\n if minimum == float('inf'):\n dic[amount] = -1\n else:\n dic[amount] = minimum\n return dic[amount]\n return count_change(coins, amount, {})", "def __init__():\n self.count = []\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if len(self.count) < amount:\n self.count = [-1] * (amount + 1)\n self.skip = [False] * (amount + 1)\n if amount is 0:\n return 0\n elif amount < 0:\n return -1\n else:\n if self.count[amount] < 0 and (not self.skip[amount]):\n tmp = float('inf')\n for co in coins:\n previous = self.coinchange(coins, amount - co)\n if previous >= 0:\n self.count[amount] = min(previous + 1, tmp)\n tmp = self.count[amount]\n else:\n continue\n self.skip[amount] = True\n return self.count[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n cache = {}\n\n def subproblem(i, t):\n if t == 0:\n return 0\n if (i, t) in cache:\n return cache[i, t]\n val = coins[i]\n if val > t:\n choice_take = math.inf\n elif val == t:\n choice_take = 1\n else:\n choice_take = 1 + subproblem(i, t - val)\n if i == 0:\n choice_leave = math.inf\n else:\n choice_leave = subproblem(i - 1, t)\n optimal = min(choice_take, choice_leave)\n cache[i, t] = optimal\n return optimal\n mincoins = subproblem(len(coins) - 1, amount)\n if mincoins == math.inf:\n return -1\n else:\n return mincoins", "def coinchange(coins: List[int], amount: int) -> int:\n t = [[0 for x in range(amount + 1)] for x in range(len(coins) + 1)]\n for j in range(amount + 1):\n t[0][j] = 1000\n for i in range(1, len(coins) + 1):\n t[i][0] = 0\n for i in range(1, len(coins) + 1):\n for j in range(1, amount + 1):\n if j % coins[i - 1] == 0:\n t[i][j] = j / coins[i - 1]\n else:\n t[i][j] = 1000\n for i in range(1, len(coins) + 1):\n for j in range(1, amount + 1):\n if coins[i - 1] <= j:\n t[i][j] = min(t[i][j - coins[i - 1]] + 1, t[i - 1][j])\n else:\n t[i][j] = t[i - 1][j]\n if t[len(coins)][amount] != 1000:\n return t[len(coins)][amount]\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n self.res = float('inf')\n n = len(coins)\n coins.sort(reverse=True)\n\n def helper(cur, start, cnt, n):\n if cur == amount:\n self.res = min(self.res, cnt)\n if cur > amount:\n return\n for i in range(start, n):\n if cur + coins[i] <= amount and cur + coins[i] * (self.res - cnt) > amount:\n helper(cur + coins[i], i, cnt + 1, n)\n helper(0, 0, 0, n)\n return self.res if self.res < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n n = len(coins)\n d = [[-1] * (amount + 1) for i in range(n + 1)]\n for i in range(amount + 1):\n if i % coins[0] == 0:\n d[1][i] = i // coins[0]\n for i in range(n + 1):\n d[i][0] = 0\n for i in range(2, n + 1):\n for j in range(1, amount + 1):\n if j - coins[i - 1] >= 0:\n if d[i - 1][j] != -1 and d[i][j - coins[i - 1]] != -1:\n d[i][j] = min(d[i - 1][j], d[i][j - coins[i - 1]] + 1)\n elif d[i - 1][j] == -1 and d[i][j - coins[i - 1]] != -1:\n d[i][j] = d[i][j - coins[i - 1]] + 1\n elif d[i - 1][j] != -1 and d[i][j - coins[i - 1]] == -1:\n d[i][j] = d[i - 1][j]\n else:\n d[i][j] = d[i - 1][j]\n else:\n d[i][j] = d[i - 1][j]\n return d[n][amount]", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n n_coins = len(coins)\n least_coin = coins[0]\n max_amount = amount + 1\n mat = [[0 for i in range(amount + 1)] for i in range(n_coins + 1)]\n if amount == 0:\n return 0\n if amount < least_coin:\n return -1\n for i in range(amount + 1):\n if i % least_coin == 0:\n mat[1][i] = i // least_coin\n else:\n mat[1][i] = -1\n for i in range(2, n_coins + 1):\n for j in range(1, amount + 1):\n curr_coin = coins[i - 1]\n if j - curr_coin >= 0:\n if mat[i][j - curr_coin] == -1:\n mat[i][j] = mat[i - 1][j]\n elif mat[i - 1][j] == -1:\n mat[i][j] = 1 + mat[i][j - curr_coin]\n elif mat[i][j - curr_coin] == -1 and mat[i - 1][j] == -1:\n mat[i][j] = -1\n else:\n mat[i][j] = min(1 + mat[i][j - curr_coin], mat[i - 1][j])\n else:\n mat[i][j] = mat[i - 1][j]\n return mat[-1][-1]", "def back_tracking_solution():\n\n def _is_solution(amount_left):\n if amount_left == 0:\n return True\n return False\n\n def _process_solution(num_coins_used, fewest_coins):\n if num_coins_used < fewest_coins[0]:\n fewest_coins[0] = num_coins_used\n\n def _candidate_coins_start_idx(amount_left, coins, current_coin_start_idx):\n for i in range(current_coin_start_idx, len(coins)):\n if amount_left >= coins[i]:\n return i\n return None\n\n def _backtrack(amount_left, num_coins_used, current_fewest_coins, coins, current_coin_start_idx):\n if _is_solution(amount_left):\n _process_solution(num_coins_used, current_fewest_coins)\n else:\n real_coin_start_idx = _candidate_coins_start_idx(amount_left, coins, current_coin_start_idx)\n if real_coin_start_idx is not None:\n for i in range(real_coin_start_idx, len(coins)):\n _backtrack(amount_left - coins[i], num_coins_used + 1, current_fewest_coins, coins, i)\n return _backtrack\n\ndef dynamic_programming_solution():\n\n def _dp_bad(amount, coins):\n sorted_coins = sorted(coins)\n cache = [[float('inf')] * len(coins) for i in range(amount + 1)]\n for denom_idx in range(len(sorted_coins)):\n cache[0][denom_idx] = 0\n for amt in range(amount + 1):\n cache[amt][0] = amt // sorted_coins[0] if amt % sorted_coins[0] == 0 else float('inf')\n for i in range(1, len(cache)):\n for j in range(1, len(sorted_coins)):\n max_num_of_denom = i // sorted_coins[j] + 1\n for k in range(max_num_of_denom):\n cache[i][j] = min(cache[i][j], k + cache[i - k * sorted_coins[j]][j - 1])\n return cache[amount][-1]\n\n def _dp_cache_recursive(amount, coins, cache):\n if amount in cache:\n return cache[amount]\n for c in coins:\n if amount >= c:\n intermediate = 1 + _dp_cache_recursive(amount - c, coins, cache)\n if amount in cache:\n cache[amount] = min(cache[amount], intermediate)\n else:\n cache[amount] = intermediate\n return cache[amount] if amount in cache else float('inf')\n\n def _dp_bottom_up_1(amount, coins):\n sorted_coins = sorted(coins)\n cache = [[float('inf')] * len(coins) for i in range(amount + 1)]\n for denom_idx in range(len(sorted_coins)):\n cache[0][denom_idx] = 0\n for amt in range(1, len(cache)):\n for denom_idx in range(len(sorted_coins)):\n amt_left = amt - sorted_coins[denom_idx]\n if amt_left >= 0:\n cache[amt][denom_idx] = 1 + min(cache[amt_left][0:denom_idx + 1])\n return min(cache[amount])\n return _dp_bottom_up_1\n\ndef coinchange(coins: List[int], amount: int) -> int:\n result = self.dynamic_programming_solution()(amount, coins)\n return -1 if result == float('inf') else result", "import queue\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n q = queue.Queue()\n q.put(amount)\n q.put(None)\n level = 0\n visited = {amount}\n while not q.empty():\n num = q.get()\n if num is None:\n if q.empty():\n break\n q.put(None)\n level += 1\n continue\n for coin in coins:\n if num - coin > 0 and num - coin not in visited:\n q.put(num - coin)\n visited.add(num - coin)\n elif num - coin == 0:\n return level + 1\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n m = Counter(coins)\n\n def recurse(left, count) -> int:\n if left in m:\n return m[left]\n if left == 0:\n m[left] = count\n return count\n smallest = math.inf\n for c in coins:\n if left - c >= 0:\n smallest = min(smallest, recurse(left - c, count + 1))\n m[left] = smallest + 1\n return smallest + 1\n recurse(amount, 0)\n if m[amount] == math.inf:\n return -1\n return m[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n table = [float('inf') for _ in range(amount + 1)]\n i = 0\n table[0] = 0\n for coin in coins:\n if coin <= amount:\n table[coin] = 1\n while i <= amount:\n for coin in coins:\n if i - coin >= 0:\n table[i] = min(table[i - coin] + 1, table[i])\n i += 1\n return table[amount] if table[amount] != float('inf') else -1", "import math\n\ndef coinchange(coins: List[int], amount: int) -> int:\n self.c = set([x for x in coins if x <= amount])\n self.coins = list(self.c)\n self.dic = {}\n if amount == 0:\n return 0\n if amount in self.c:\n return 1\n res = math.inf\n for i in range(len(self.coins)):\n ci = self.dp(amount - self.coins[i])\n if ci > 0:\n res = min(res, ci + 1)\n return res if res != math.inf else -1\n\ndef dp(amount):\n if amount in self.c:\n return 1\n if amount in self.dic:\n return self.dic[amount]\n list2 = [x for x in self.coins if x <= amount]\n if len(list2) == 0:\n return -1\n res = math.inf\n for i in range(len(list2)):\n ci = self.dp(amount - list2[i])\n if ci > 0:\n res = min(res, ci + 1)\n self.dic[amount] = res\n return res", "def helper(coins, amount, cache, current=[]):\n if amount == 0:\n return 0\n if amount < 0:\n return -1\n else:\n if amount in cache:\n return cache[amount]\n currMin = sys.maxsize\n for coin in coins:\n current.append(coin)\n currNum = self.helper(coins, amount - coin, cache, current)\n if currNum != -1:\n if currNum < currMin:\n currMin = currNum + 1\n current.pop()\n cache[amount] = currMin\n return currMin\n\ndef coinchange(coins, amount):\n cache = {}\n val = self.helper(coins, amount, cache)\n memo = [sys.maxsize] * (amount + 1)\n memo[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n newIndex = i - coin\n if newIndex >= 0:\n if memo[newIndex] + 1 < memo[i]:\n memo[i] = memo[newIndex] + 1\n if memo[amount] == sys.maxsize:\n return -1\n else:\n return memo[amount]", "def coinchange(coins: [int], amount: int) -> int:\n self.ans = float('inf')\n self.dict = {}\n coins.sort(reverse=True)\n\n def helper(num, depth):\n if num == 0:\n self.ans = min(self.ans, depth)\n return\n for c in coins:\n res = num - c\n if res >= 0:\n if res in self.dict:\n if self.dict[res] > depth + 1 and depth + 1 < self.ans:\n self.dict[res] = depth + 1\n helper(res, depth + 1)\n else:\n self.dict[res] = depth + 1\n helper(res, depth + 1)\n helper(amount, 0)\n return self.ans if self.ans < float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n\n def recurse(amount, pos):\n if pos == len(coins):\n return 10000\n if amount == 0:\n return 0\n if coins[pos] <= amount:\n return min(recurse(amount - coins[pos], pos) + 1, recurse(amount, pos + 1))\n else:\n return recurse(amount, pos + 1)\n count = recurse(amount, 0)\n if count >= 10000:\n return -1\n return count", "def recursion(coins, remain, dic):\n if remain < 0:\n return float('inf')\n if remain == 0:\n return 0\n if remain in dic.keys():\n return dic[remain]\n min_coin = float('inf')\n for coin in coins:\n number_coin = None\n prev_num = self.recursion(coins, remain - coin, dic)\n if prev_num == float('inf'):\n number_coin = prev_num\n else:\n number_coin = prev_num + 1\n min_coin = min(min_coin, number_coin)\n dic[remain] = min_coin\n return min_coin\n\ndef coinchange(coins: List[int], amount: int) -> int:\n remain = amount\n count = 0\n dic = {}\n number = self.recursion(coins, remain, dic)\n if number == float('inf'):\n return -1\n else:\n return number", "def coinchange(coins: List[int], amount: int) -> int:\n dp = {}\n\n def dfs(total):\n if total < 0:\n return float('inf')\n if total == 0:\n return 0\n if total in list(dp.keys()):\n return dp[total]\n for c in coins:\n x = total - c\n if total not in list(dp.keys()):\n dp[total] = dfs(x) + 1\n else:\n dp[total] = min(dp[total], dfs(x) + 1)\n return dp[total]\n ans = dfs(amount)\n if ans < float('inf'):\n return ans\n else:\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n coins.sort()\n table = [[-1 for i in range(amount + 1)] for i in range(len(coins))]\n for i in range(len(coins)):\n for j in range(amount + 1):\n if coins[i] > j and i > 0 and (table[i - 1][j] > 0):\n table[i][j] = table[i - 1][j]\n elif j >= coins[i]:\n x = j - coins[i]\n pre_val = 9999999\n calculated_val = 0\n if i > 0 and table[i - 1][j] > 0:\n pre_val = table[i - 1][j]\n if x > 0:\n if table[i][x] > 0:\n calculated_val = table[i][x]\n table[i][j] = min(1 + calculated_val, pre_val)\n elif i > 0 and pre_val != 9999999:\n table[i][j] = pre_val\n elif x == 0:\n table[i][j] = min(1 + calculated_val, pre_val)\n return table[len(coins) - 1][amount]", "def coinchange(coins: List[int], total: int) -> int:\n dic = {0: 0}\n\n def helper(amount):\n if amount in coins:\n dic[amount] = 1\n elif amount < 0:\n return float('inf')\n elif amount not in dic:\n dic[amount] = min([helper(amount - c) + 1 for c in coins])\n return dic[amount]\n return helper(total) if helper(total) != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not coins:\n return -1\n n = len(coins)\n if amount == 0:\n return 0\n fewest = [[0] * n for k in range(amount + 1)]\n for k in range(n):\n fewest[0][k] = 0\n for p in range(1, amount + 1):\n is_divisible = p % coins[0] == 0\n if is_divisible:\n fewest[p][0] = p // coins[0]\n else:\n fewest[p][0] = -1\n for k in range(1, n):\n for p in range(1, amount + 1):\n if p < coins[k]:\n fewest[p][k] = fewest[p][k - 1]\n elif fewest[p - coins[k]][k] == -1:\n fewest[p][k] = fewest[p][k - 1]\n elif fewest[p][k - 1] == -1:\n fewest[p][k] = fewest[p - coins[k]][k] + 1\n else:\n fewest[p][k] = min(fewest[p - coins[k]][k] + 1, fewest[p][k - 1])\n return fewest[p][n - 1]", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n coins.reverse()\n lookup = {}\n\n def find_combos(total_remain, total_coins):\n if total_remain in lookup:\n if lookup[total_remain] > total_coins:\n lookup[total_remain] = total_coins\n else:\n return\n else:\n lookup[total_remain] = total_coins\n for coin in coins:\n if total_remain - coin < 0:\n continue\n find_combos(total_remain - coin, total_coins + 1)\n find_combos(amount, 0)\n if 0 in lookup:\n return lookup[0]\n else:\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n dp = {i: [] for i in range(1, amount + 1)}\n coins.sort()\n for intermediate_amount in range(1, amount + 1):\n for denom in reversed(coins):\n if intermediate_amount == denom:\n dp[intermediate_amount] = [denom]\n break\n elif denom < intermediate_amount and dp[intermediate_amount - denom] != []:\n if dp[intermediate_amount] == [] or len(dp[intermediate_amount]) > len(dp[intermediate_amount - denom]) + 1:\n dp[intermediate_amount] = dp[intermediate_amount - denom] + [denom]\n return len(dp[amount]) if len(dp[amount]) > 0 else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [[float('INF') for i in range(amount + 1)] for j in range(len(coins) + 1)]\n for i in range(len(coins) + 1):\n dp[i][0] = 0\n for i in range(1, len(coins) + 1):\n for j in range(1, amount + 1):\n if j - coins[i - 1] < 0:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = min(dp[i - 1][j], dp[i][j - coins[i - 1]] + 1)\n if dp[len(coins)][amount] == float('INF'):\n return -1\n else:\n return dp[len(coins)][amount]", "def coinchange(coins: List[int], amount: int) -> int:\n\n def coinchangehelper(rem):\n if rem < 0:\n return -1\n if rem == 0:\n return 0\n if rem in memo:\n return memo[rem]\n count = float('inf')\n for coin in coins:\n sub = coinchangehelper(rem - coin)\n if sub >= 0:\n count = min(count, 1 + sub)\n memo[rem] = count\n return memo[rem]\n memo = {}\n res = coinchangehelper(amount)\n return res if res != float('inf') else -1", "def coinchange(coins: List[int], amount: int) -> int:\n dp = [float('inf') for _ in range(amount + 1)]\n if amount == 0:\n return 0\n for i in range(0, len(dp)):\n for c in coins:\n if i >= c:\n if i % c == 0:\n dp[i] = min(int(i / c), dp[i])\n elif i - c >= 0 and dp[i - c] != float('inf'):\n dp[i] = min(int(1 + dp[i - c]), dp[i])\n ret_val = dp[amount]\n if ret_val == float('inf'):\n return -1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n self.dp = [float('inf')] * (amount + 1)\n self.dp[0] = 0\n\n def change(a):\n if a < 0:\n return -1\n if a == 0:\n return 0\n if self.dp[a] != float('inf'):\n return self.dp[a]\n for c in coins:\n tmp = change(a - c)\n if tmp != -1:\n self.dp[a] = min(tmp + 1, self.dp[a])\n if self.dp[a] == float('inf'):\n self.dp[a] = -1\n return self.dp[a]\n change(amount)\n return self.dp[amount] if self.dp[amount] != float('inf') else -1", "def coinchange_bottomUp(coins: List[int], amount: int) -> int:\n lookup = {x: amount + 1 for x in range(1, amount + 1)}\n lookup[0] = 0\n for i in range(amount + 1):\n for coin in coins:\n remainder = i - coin\n if remainder < 0:\n continue\n best_min = min(lookup[remainder] + 1, lookup[i])\n lookup[i] = best_min\n if lookup[i] > amount:\n return -1\n else:\n return lookup[i]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n coins.reverse()\n lookup = {}\n\n def find_combos(total_remain, total_coins):\n if total_remain in lookup:\n if lookup[total_remain] > total_coins:\n lookup[total_remain] = total_coins\n else:\n return\n else:\n lookup[total_remain] = total_coins\n for coin in coins:\n if total_remain - coin < 0:\n continue\n find_combos(total_remain - coin, total_coins + 1)\n find_combos(amount, 0)\n return lookup[0] if 0 in lookup else -1", "def coinchange(coins: List[int], amount: int) -> int:\n level = seen = {0}\n number = 0\n while level:\n if amount in seen:\n return number\n level = {pre_amount + coin for pre_amount in level for coin in coins if pre_amount + coin <= amount}\n seen.update(level)\n number += 1\n return -1", "from functools import lru_cache\nfrom math import inf\n\ndef coinchange(coins: List[int], amount: int) -> int:\n\n def cc(i, amount):\n if amount == 0:\n return 0\n elif i < 0 or amount < 0:\n return inf\n else:\n (incl, excl) = (cc(i - 1, amount), cc(i, amount - coins[i]) + 1)\n return min(max(incl, 0), max(excl, 0))\n result = cc(len(coins) - 1, amount)\n return result if result < inf else -1", "def coinchange(coins: List[int], amount: int) -> int:\n memo = [[-1 for _ in range(amount + 1)] for _ in coins]\n for i in range(len(coins) - 1, -1, -1):\n for j in range(amount + 1):\n if j == 0:\n memo[i][j] = 0\n continue\n if j - coins[i] >= 0 and memo[i][j - coins[i]] != -1 and (i + 1 < len(coins)) and (memo[i + 1][j] != -1):\n memo[i][j] = min(memo[i][j - coins[i]] + 1, memo[i + 1][j])\n elif j - coins[i] >= 0 and memo[i][j - coins[i]] != -1:\n memo[i][j] = memo[i][j - coins[i]] + 1\n elif i + 1 < len(coins) and memo[i + 1][j] != -1:\n memo[i][j] = memo[i + 1][j]\n return memo[0][amount]", "def __init__():\n self.total_min = 0\n self.change_map = {0: 0}\n\ndef changer(coins_obj, amount_obj):\n if amount_obj == 0:\n self.change_map[amount_obj] = 0\n return 0\n if min(coins_obj) > amount_obj:\n self.change_map[amount_obj] = -1\n return -1\n rev_coins_obj = list(reversed(coins_obj))\n for el in rev_coins_obj:\n if el <= amount_obj:\n if amount_obj - el in self.change_map.keys():\n tmp = self.change_map[amount_obj - el]\n else:\n tmp = Solution.changer(self, coins_obj, amount_obj - el)\n if tmp != -1:\n key = tmp + 1\n if amount_obj not in self.change_map.keys():\n self.change_map[amount_obj] = key\n elif amount_obj in self.change_map.keys():\n if key < self.change_map[amount_obj]:\n self.change_map[amount_obj] = key\n if amount_obj not in self.change_map.keys():\n self.change_map[amount_obj] = -1\n return -1\n elif amount_obj in self.change_map.keys():\n return self.change_map[amount_obj]\n\ndef coinchange(coins: List[int], amount: int) -> int:\n Solution.changer(self, coins, amount)\n if amount not in self.change_map.keys():\n return -1\n return self.change_map[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n start = [0]\n visited = [False] * (amount + 1)\n visited[0] = True\n numCoins = 1\n nextStart = []\n while start:\n for v in start:\n for coin in coins:\n nextVal = v + coin\n if nextVal > amount or visited[nextVal]:\n continue\n elif nextVal == amount:\n return numCoins\n else:\n visited[nextVal] = True\n nextStart.append(nextVal)\n (start, nextStart) = (nextStart, [])\n numCoins += 1\n return -1", "from queue import Queue\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n q = Queue()\n mem = dict()\n q.put((0, 0))\n while not q.empty():\n curr = q.get()\n for c in coins:\n tot = curr[1] + c\n if tot > amount:\n continue\n if tot == amount:\n return curr[0] + 1\n if tot in mem and mem[tot] <= curr[0] + 1:\n continue\n q.put((curr[0] + 1, tot))\n mem[tot] = curr[0] + 1\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n mem = {}\n\n def helper(amt):\n if amt < 0:\n return -1\n elif amt == 0:\n return 0\n elif amt in mem:\n return mem[amt]\n min_coins = float('inf')\n for coin in coins:\n result = helper(amt - coin)\n if result != -1:\n min_coins = min(min_coins, 1 + result)\n mem[amt] = min_coins\n return min_coins\n output = helper(amount)\n return -1 if output == float('inf') else output", "def changeCoin(coins, amount, change):\n if amount < 0:\n return -1\n if amount == 0:\n return 0\n if amount in change:\n return change[amount]\n costs = []\n for coin in coins:\n cost = self.changeCoin(coins, amount - coin, change)\n if amount - coin in change:\n change[amount - coin] = min(cost, change[amount - coin])\n else:\n change[amount - coin] = cost\n if cost != -1:\n costs.append(cost)\n if len(costs) == 0:\n return -1\n return 1 + min(costs)\n\ndef coinchange(coins: List[int], amount: int) -> int:\n coins.sort()\n coins = [coin for coin in coins if coin <= amount]\n change = {}\n return self.changeCoin(coins, amount, change)", "import numpy as np\n\ndef coinchange(coins: List[int], amount: int) -> int:\n maximum = amount + 1\n dp = np.full(maximum, maximum)\n dp[0] = 0\n for i in range(1, maximum):\n for j in coins:\n if j <= i:\n dp[i] = min(dp[i], dp[i - j] + 1)\n if dp[amount] > amount:\n return -1\n return dp[amount]", "def coinchange(coins: List[int], amount: int) -> int:\n rows = amount + 1\n cols = len(coins) + 1\n cache = [[0 for _ in range(cols)] for _ in range(rows)]\n for row in range(1, rows):\n cache[row][0] = -1\n for row in range(1, rows):\n for col in range(1, cols):\n newAmt = row - coins[col - 1]\n takeValue = cache[newAmt][col] if newAmt >= 0 and newAmt < len(cache) else -1\n takeCoin = 1 + takeValue if takeValue >= 0 else -1\n skipCoin = cache[row][col - 1]\n if skipCoin < 0:\n cache[row][col] = takeCoin\n elif takeCoin < 0:\n cache[row][col] = skipCoin\n else:\n cache[row][col] = min(skipCoin, takeCoin)\n return cache[amount][len(coins)]", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n self.dp = [[-1] * (amount + 1) for _ in range(len(coins) + 1)]\n value = self.solve(coins, len(coins), amount)\n return self.dp[-1][-1] if value != float('inf') else -1\n\ndef solve(coins, n, amount):\n if amount == 0:\n self.dp[n][amount] = 0\n return 0\n if n == 0:\n self.dp[n][amount] = float('inf')\n return self.dp[n][amount]\n if self.dp[n][amount] != -1:\n return self.dp[n][amount]\n if coins[n - 1] <= amount:\n self.dp[n][amount] = min(1 + self.solve(coins, n, amount - coins[n - 1]), self.solve(coins, n - 1, amount))\n return self.dp[n][amount]\n else:\n self.dp[n][amount] = self.solve(coins, n - 1, amount)\n return self.dp[n][amount]", "import numpy as np\n\ndef coinchange(coins: List[int], amount: int) -> int:\n dp = np.empty(amount + 1)\n dp.fill(math.inf)\n dp[0] = 0\n coins = sorted(coins)\n for i in range(1, amount + 1):\n for c in coins:\n if c <= i:\n dp[i] = min(dp[i], 1 + dp[i - c])\n else:\n break\n return -1 if dp[-1] == math.inf else int(dp[-1])", "def coinchange(coins: List[int], amount: int) -> int:\n coins = sorted(coins)\n dp = {}\n\n def in_dict(val):\n return val in dp.keys() and dp[val]\n if not amount:\n return 0\n if coins[0] > amount:\n return -1\n for coin in coins:\n dp[coin] = 1\n for i in range(coins[0], min(amount, coins[-1]) + 1):\n if i in dp.keys():\n continue\n available_coins = [coin for coin in coins if coin <= i]\n possible_min_coins = [1 + dp[i - coin] for coin in available_coins if in_dict(i - coin)]\n dp[i] = min(possible_min_coins) if possible_min_coins else 0\n for i in range(coins[-1] + 1, amount + 1):\n possible_min_coins = [1 + dp[i - coin] for coin in coins if in_dict(i - coin)]\n dp[i] = min(possible_min_coins) if possible_min_coins else 0\n return dp[amount] or -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n value1 = [0]\n value2 = []\n nc = 0\n visited = [False] * (amount + 1)\n visited[0] = True\n while value1:\n nc += 1\n for v in value1:\n for coin in coins:\n newval = v + coin\n if newval <= amount:\n if not visited[newval]:\n if newval == amount:\n return nc\n visited[newval] = True\n value2.append(newval)\n (value1, value2) = (value2, [])\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n (res, seen, curr) = (0, set(), {c for c in coins if c <= amount})\n while curr:\n res += 1\n if amount in curr:\n return res\n seen |= curr\n tmp = {n + c for n in curr for c in coins}\n curr = {t for t in tmp if t not in seen and t <= amount}\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n seen = set()\n seen.add(0)\n queue = deque([0])\n count = 0\n while queue:\n if amount in queue:\n return count\n currlen = len(queue)\n for i in range(currlen):\n node = queue.popleft()\n for c in coins:\n if c + node not in seen and c + node <= amount:\n queue.append(c + node)\n seen.add(c + node)\n count += 1\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n q = deque([amount])\n hs = [False] * amount\n count = 0\n while q:\n l = len(q)\n while l:\n n = q.popleft()\n for c in coins:\n x = n - c\n if not x:\n return count + 1\n if x > 0 and (not hs[x]):\n hs[x] = True\n q.append(x)\n l -= 1\n count += 1\n return -1", "import collections\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if not amount:\n return 0\n queue = collections.deque(coins)\n visited = set()\n count = 1\n while queue:\n for _ in range(len(queue)):\n curr = queue.popleft()\n if curr == amount:\n return count\n for next in coins:\n next += curr\n if next not in visited and next <= amount:\n visited.add(next)\n queue.append(next)\n count += 1\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n from collections import deque\n q = deque()\n visited = set()\n q.append(amount)\n visited.add(amount)\n steps = 0\n while q:\n for _ in range(len(q)):\n poped = q.popleft()\n if poped == 0:\n return steps\n for coin in coins:\n new = poped - coin\n if new not in visited and new >= 0:\n q.append(new)\n visited.add(new)\n steps += 1\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n queue = [[0, 0]]\n visited = {0}\n step = 0\n for (node, step) in queue:\n for coin in coins:\n if node + coin in visited:\n continue\n if node + coin == amount:\n return step + 1\n if node + coin < amount:\n queue.append([node + coin, step + 1])\n visited.add(node + coin)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n q = [0]\n visited = set()\n depth = 0\n while q:\n depth += 1\n level = []\n for curr in q:\n for coin in coins:\n newvalue = curr + coin\n if newvalue == amount:\n return depth\n if newvalue not in visited and newvalue < amount:\n visited.add(newvalue)\n level.append(newvalue)\n q = level\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n que = deque()\n seen = set()\n res = -1\n for coin in coins:\n if coin <= amount:\n que.append(coin)\n seen.add(coin)\n count = 1\n while que:\n prev = len(que)\n while prev > 0:\n cur = que.popleft()\n if cur == amount:\n return count\n for coin in coins:\n newamount = cur + coin\n if newamount not in seen and newamount <= amount:\n que.append(newamount)\n seen.add(newamount)\n prev -= 1\n count += 1\n return res", "def coinchange(coins: List[int], amount: int) -> int:\n seen = level = {0}\n coin_n = 0\n while level:\n if amount in level:\n return coin_n\n level = {val + coin for val in level for coin in coins if val + coin <= amount} - seen\n seen |= level\n coin_n += 1\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n coins.sort(reverse=True)\n count = 0\n self.maxcount = float('inf')\n self.dfs(coins, count, amount)\n return -1 if self.maxcount == float('inf') else self.maxcount\n\ndef dfs(coins, count, amount):\n if amount == 0:\n self.maxcount = min(self.maxcount, count)\n for i in range(len(coins)):\n if amount >= coins[i] and count + math.ceil(amount / coins[i]) < self.maxcount:\n self.dfs(coins[i:], count + 1, amount - coins[i])", "from collections import deque\n\ndef coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n queue = deque([[0, 0]])\n visited = {0}\n step = 0\n while queue:\n (node, step) = queue.popleft()\n for coin in coins:\n if node + coin in visited:\n continue\n if node + coin == amount:\n return step + 1\n elif node + coin < amount:\n queue.append([node + coin, step + 1])\n visited.add(node + coin)\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount < 0 or not coins:\n return -1\n if not amount:\n return 0\n (stack, lvl, visited) = ([0], 0, set())\n while stack:\n new_lvl = []\n lvl += 1\n for i in stack:\n for c in coins:\n new = i + c\n if new == amount:\n return lvl\n if new not in visited:\n visited.add(new)\n new_lvl.append(new)\n if min(new_lvl) > amount:\n return -1\n stack = new_lvl", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n myQueue = [[0, 0]]\n reachedMap = {0}\n for (value, num_coins) in myQueue:\n for coin in coins:\n if coin + value in reachedMap:\n continue\n if coin + value == amount:\n return num_coins + 1\n if coin + value < amount:\n reachedMap.add(value + coin)\n myQueue.append([coin + value, num_coins + 1])\n return -1", "def coinchange(coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n if not coins:\n return -1\n memo = {}\n stack = [amount]\n l = 0\n while stack:\n tmp = []\n for remain in stack:\n if remain < 0:\n continue\n for coin in coins:\n nxt = remain - coin\n if nxt == 0:\n return l + 1\n if nxt in memo:\n continue\n else:\n memo[nxt] = 1\n tmp += [nxt]\n stack = tmp\n l += 1\n return -1"], "starter_code": "def coinchange(coins: List[int], amount: int) -> int:\n", "input_output": {"fn_name": "coinChange", "inputs": [[[1, 2, 5], 11]], "outputs": [3]}, "difficulty": "MEDIUM", "raw_tags": ["Array", "Dynamic Programming", "Breadth-First Search"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures", "Graph traversal"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/coin-change/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "coinchange", "task_id": "TACO_lite/406", "example": [[[[5, 2, 1], 11], [[2], 3], [[1], 0], [[1], 1], [[1], 2]], ["3", "-1", "0", "1", "2"]]} +{"requirement": "Consider the prime number `23`. If we sum the square of its digits we get:\n`2^2 + 3^2 = 13`, then for `13: 1^2 + 3^2 = 10`, and finally for `10: 1^2 + 0^2 = 1`. \n\nSimilarly, if we start with prime number `7`, the sequence is: `7->49->97->130->10->1`.\n\nGiven a range, how many primes within that range will eventually end up being `1`? \n\nThe upperbound for the range is `50,000`. A range of `(2,25)` means that: `2 <= n < 25`. \n\nGood luck!\n\nIf you like this Kata, please try:\n\n[Prime reversion](https://www.codewars.com/kata/59b46276afcda204ed000094)\n\n[Domainant primes](https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed)", "solutions": ["def is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n sqrtn = int(n ** 0.5) + 1\n for i in range(5, sqrtn, 6):\n if n % i == 0 or n % (i + 2) == 0:\n return False\n return True\n\ndef end_one(n):\n while n > 6:\n n = sum(map(lambda x: int(x) * int(x), f'{n}'))\n if n == 1:\n return True\n\ndef solve(a, b):\n return sum((1 for n in range(a, b) if is_prime(n) and end_one(n)))", "def solve(a, b):\n return len([x for x in [7, 13, 19, 23, 31, 79, 97, 103, 109, 139, 167, 193, 239, 263, 293, 313, 331, 367, 379, 383, 397, 409, 487, 563, 617, 653, 673, 683, 709, 739, 761, 863, 881, 907, 937, 1009, 1033, 1039, 1093, 1151, 1277, 1303, 1373, 1427, 1447, 1481, 1487, 1511, 1607, 1663, 1697, 1733, 1847, 1933, 2003, 2039, 2063, 2111, 2221, 2309, 2333, 2339, 2383, 2393, 2417, 2557, 2693, 2741, 2833, 2851, 2903, 2963, 3001, 3019, 3067, 3079, 3083, 3109, 3137, 3209, 3301, 3313, 3319, 3323, 3329, 3331, 3371, 3391, 3463, 3607, 3637, 3643, 3673, 3709, 3779, 3797, 3803, 3823, 3833, 3907, 3923, 3931, 4111, 4127, 4157, 4217, 4271, 4363, 4441, 4447, 4481, 4517, 4663, 4721, 4751, 4817, 4871, 5147, 5227, 5281, 5417, 5471, 5477, 5527, 5569, 5659, 5741, 5821, 5879, 5897, 5987, 6037, 6053, 6073, 6163, 6197, 6203, 6329, 6337, 6343, 6353, 6361, 6367, 6373, 6389, 6637, 6661, 6673, 6701, 6703, 6719, 6733, 6763, 6791, 6803, 6899, 6917, 6971, 6983, 7039, 7127, 7309, 7331, 7451, 7457, 7481, 7541, 7547, 7589, 7603, 7691, 7793, 7841, 7937, 8081, 8147, 8233, 8369, 8521, 8597, 8693, 8699, 8741, 8821, 8929, 8963, 8969, 9001, 9007, 9013, 9103, 9133, 9203, 9323, 9377, 9587, 9623, 9689, 9829, 9857, 10009, 10039, 10067, 10093, 10141, 10151, 10177, 10211, 10247, 10303, 10333, 10337, 10427, 10457, 10487, 10607, 10663, 10733, 10771, 10847, 10903, 11113, 11131, 11149, 11159, 11197, 11243, 11251, 11311, 11423, 11467, 11471, 11483, 11491, 11519, 11681, 11719, 11941, 11971, 12011, 12101, 12143, 12149, 12347, 12413, 12437, 12473, 12491, 12511, 12583, 12671, 12743, 12823, 12841, 12853, 12941, 12959, 13003, 13009, 13033, 13037, 13093, 13177, 13241, 13309, 13339, 13411, 13421, 13457, 13487, 13499, 13577, 13679, 13697, 13757, 13841, 13903, 13933, 13967, 14011, 14057, 14081, 14087, 14207, 14281, 14321, 14327, 14347, 14387, 14407, 14437, 14449, 14461, 14537, 14549, 14551, 14561, 14723, 14753, 14783, 14813, 14821, 14831, 14939, 15101, 15121, 15299, 15377, 15451, 15461, 15473, 15541, 15641, 15679, 15737, 15773, 15787, 15823, 15877, 15887, 16007, 16063, 16097, 16127, 16217, 16363, 16417, 16451, 16603, 16633, 16741, 16759, 16811, 16937, 16993, 17027, 17033, 17107, 17137, 17191, 17207, 17317, 17443, 17483, 17569, 17573, 17609, 17627, 17659, 17669, 17713, 17827, 17911, 18041, 18047, 18143, 18223, 18253, 18341, 18401, 18413, 18523, 18587, 18743, 18757, 18839, 18899, 19141, 19259, 19333, 19421, 19699, 19763, 19889, 19963, 19979, 19997, 20063, 20147, 20177, 20333, 20369, 20393, 20639, 20693, 20717, 20771, 20899, 20903, 20963, 21011, 21101, 21143, 21149, 21283, 21341, 21347, 21407, 21419, 21481, 21491, 21599, 21617, 21767, 21787, 21841, 22129, 22229, 22273, 22291, 22381, 22483, 22549, 22573, 22621, 22651, 22783, 22861, 22921, 23039, 23227, 23369, 23417, 23447, 23581, 23609, 23663, 23741, 23827, 23887, 23893, 23899, 23977, 24071, 24107, 24113, 24137, 24181, 24229, 24317, 24371, 24473, 24683, 24859, 25057, 25111, 25183, 25237, 25261, 25453, 25561, 25621, 25657, 25801, 25849, 25919, 26003, 26171, 26177, 26227, 26251, 26267, 26309, 26339, 26393, 26557, 26627, 26633, 26669, 26711, 26717, 26821, 26903, 27017, 27107, 27143, 27253, 27283, 27299, 27397, 27431, 27611, 27617, 27697, 27701, 27739, 27793, 27817, 27823, 27883, 27967, 28051, 28081, 28099, 28123, 28351, 28387, 28393, 28411, 28463, 28513, 28549, 28621, 28643, 28723, 28771, 28789, 28837, 28879, 28909, 28933, 29033, 29063, 29221, 29297, 29303, 29363, 29383, 29389, 29411, 29633, 29833, 29927, 29983, 30013, 30029, 30091, 30097, 30103, 30109, 30133, 30137, 30139, 30269, 30293, 30313, 30319, 30323, 30367, 30391, 30553, 30637, 30643, 30661, 30689, 30713, 30763, 30803, 30869, 30931, 30977, 31033, 31039, 31177, 31247, 31307, 31393, 31481, 31547, 31663, 31699, 31769, 31771, 31847, 32009, 32069, 32083, 32141, 32257, 32303, 32309, 32369, 32411, 32609, 32693, 32779, 32797, 32803, 32839, 32887, 32983, 33013, 33023, 33029, 33071, 33083, 33091, 33107, 33203, 33289, 33301, 33359, 33391, 33413, 33589, 33629, 33829, 33931, 34127, 34147, 34157, 34211, 34217, 34313, 34471, 34499, 34603, 34721, 34747, 34781, 34871, 34897, 34919, 34949, 35053, 35227, 35281, 35339, 35393, 35569, 35603, 35771, 35839, 35933, 35983, 36007, 36037, 36061, 36067, 36073, 36209, 36263, 36293, 36307, 36343, 36433, 36559, 36607, 36637, 36791, 36809, 36919, 36923, 37013, 37097, 37117, 37171, 37441, 37447, 37489, 37517, 37571, 37619, 37663, 37691, 37907, 38069, 38189, 38239, 38287, 38299, 38303, 38329, 38333, 38593, 38609, 38669, 38749, 38891, 38923, 38953, 39023, 39103, 39133, 39301, 39313, 39419, 39619, 39623, 39671, 39727, 39749, 39761, 39799, 39829, 39847, 39979, 40009, 40087, 40111, 40127, 40471, 40577, 40609, 40751, 40841, 41011, 41047, 41057, 41081, 41113, 41117, 41131, 41183, 41213, 41231, 41281, 41333, 41357, 41381, 41387, 41399, 41507, 41549, 41617, 41641, 41651, 41761, 41801, 41813, 41911, 42017, 42071, 42131, 42181, 42283, 42437, 42473, 42589, 42683, 42701, 42743, 42859, 42863, 43063, 43133, 43271, 43313, 43331, 43427, 43499, 43517, 43633, 43721, 43781, 43789, 43987, 43991, 43997, 44017, 44041, 44071, 44159, 44249, 44273, 44371, 44453, 44491, 44519, 44543, 44633, 44647, 44651, 44699, 44701, 44773, 44789, 44879, 44939, 44959, 44987, 45077, 45137, 45161, 45289, 45317, 45491, 45523, 45553, 45641, 45707, 45853, 45949, 46141, 46171, 46411, 46447, 46451, 46499, 46511, 46663, 46997, 47041, 47051, 47057, 47111, 47123, 47143, 47161, 47351, 47381, 47389, 47407, 47431, 47501, 47507, 47513, 47699, 47743, 47857, 47939, 47969, 48017, 48121, 48131, 48259, 48311, 48371, 48397, 48449, 48479, 48497, 48623, 48731, 48757, 48799, 48947, 48973, 49121, 49139, 49193, 49211, 49391, 49451, 49459, 49549, 49697, 49739, 49783, 49789, 49937, 49943] if x in range(a, b)])", "import math as m\n\ndef IsPrime(a):\n if a == 1:\n return False\n for i in range(2, int(m.sqrt(a) + 1)):\n if a % i == 0:\n return False\n return True\n\ndef algorithm(a):\n while a != 4:\n sum = 0\n for j in str(a):\n sum += int(j) ** 2\n a = sum\n if a == 1:\n return True\n return False\n\ndef solve(a, b):\n counter = 0\n for i in range(a, b):\n if IsPrime(i):\n if algorithm(i):\n counter += 1\n return counter", "def build_solver(limit):\n reducers = [(2, 0), (3, 0), (5, 0)]\n known_failures = {2, 3, 5}\n\n def reduces_to_1(p):\n seq = set()\n n = p\n while n not in seq and n not in known_failures and (n != 1):\n seq.add(n)\n m = n\n t = 0\n while m > 0:\n (m, d) = divmod(m, 10)\n t += d * d\n n = t\n if n != 1:\n known_failures.update(seq)\n return n == 1\n prime_candidate = reducers[-1][0]\n root = int(prime_candidate ** 0.5) + 1\n while prime_candidate < limit:\n prime_candidate += 2\n if root * root < prime_candidate:\n root += 1\n for (p, _) in reducers:\n if prime_candidate % p == 0:\n break\n if p > root:\n reducers.append((prime_candidate, reduces_to_1(prime_candidate)))\n break\n reducers = [p for (p, r) in reducers if r]\n\n def solve(a, b):\n result = 0\n for p in reducers:\n if p < a:\n continue\n if p >= b:\n break\n result += 1\n return result\n return solve\nsolve = build_solver(50000)", "import numpy as np\n\ndef ssloop(n):\n seen = set()\n while n != 1 and n not in seen:\n seen.add(n)\n n = sum((x * x for x in map(int, str(n))))\n return n == 1\ns = np.ones(50001)\ns[:2] = s[4::2] = 0\nfor i in range(3, int(len(s) ** 0.5) + 1, 2):\n if s[i]:\n s[i * i::i] = 0\nxs = [i for (i, x) in enumerate(s) if x and ssloop(i)]\n\ndef solve(a, b):\n return np.searchsorted(xs, b) - np.searchsorted(xs, a)", "N = 10 ** 5\n\ndef sum_square_digits(n):\n return sum(((ord(d) - 48) ** 2 for d in str(n)))\n\ndef reductible(n):\n suite = set()\n while n not in suite:\n suite.add(n)\n n = sum_square_digits(n)\n return n == 1\nmax_digit_sum = 81 * len(str(N))\nsum_reduc = set(filter(reductible, range(max_digit_sum + 1)))\n\ndef primes(n):\n sieve = n // 2 * [True]\n for i in range(3, int(n ** 0.5) + 1, 2):\n if sieve[i // 2]:\n sieve[i * i // 2::i] = [False] * ((n - i * i - 1) // (2 * i) + 1)\n return [2] + [2 * i + 1 for i in range(1, n // 2) if sieve[i]]\nprime_reduc = [n for n in primes(N) if sum_square_digits(n) in sum_reduc]\nfrom bisect import bisect_left\n\ndef solve(a, b):\n return bisect_left(prime_reduc, b) - bisect_left(prime_reduc, a)", "def isprime(n):\n if n < 2:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef solve(a, b):\n count = 0\n for i in range(a, b):\n if isprime(i):\n c = 0\n while i != 1 and c != 10:\n i = sum((int(j) ** 2 for j in list(str(i))))\n c += 1\n if i == 1:\n count += 1\n return count", "N = 50000\n(sieve, reduceable) = ([False, False] + [True] * (N - 1), set())\nfor (i, is_prime) in enumerate(sieve):\n if is_prime:\n (seen, n) = (set(), i)\n while n not in seen:\n seen.add(n)\n n = sum((int(c) ** 2 for c in str(n)))\n if n == 1:\n reduceable.add(i)\n for j in range(i * i, N + 1, i):\n sieve[j] = False\n\ndef solve(a, b):\n return sum((1 for e in reduceable if a <= e < b))"], "starter_code": "def solve(a,b):\n", "input_output": {"fn_name": "solve", "inputs": [[1, 25], [100, 1000], [100, 2000], [100, 3000], [100, 4000]], "outputs": [[4], [28], [47], [65], [95]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/59aa6567485a4d03ff0000ca", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/397", "example": [[[2, 25]], [4]]} +{"requirement": "Given a number n, find count of all binary sequences of length 2n such that sum of first n bits is same as sum of last n bits.\nThe anwer can be very large. So, you have to return answer modulo 10^{9}+7.\nExample:\nInput: n = 2\nOutput: 6\nExplanation: There are 6 sequences of length \n2*n, the sequences are 0101, 0110, 1010, 1001, \n0000 and 1111.\nExample:\nInput: n = 1\nOutput: 2\nExplanation: There are 2 sequence of length \n2*n, the sequence are 00 and 11.\n \nYour Task:\nYou don't need to read or print anyhting. Your task is to complete the function compute_value() which takes n as input parameter and returns count of all binary sequence of length 2*n such that sum of first n bits is same as sum of last n bits modulo 10^{9} + 7.\n \nExpected Time Complexity: O(n * log(n))\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= n <= 10^{5}", "solutions": ["import math\n\ndef compute_value(n):\n mod = 10 ** 9 + 7\n a = math.factorial(2 * n)\n b = math.factorial(n)\n return a // b ** 2 % mod", "import math\n\ndef compute_value(n):\n mod = 1000000007\n a = math.factorial(2 * n)\n b = math.factorial(n)\n return a // b ** 2 % mod", "import math\n\ndef compute_value(n):\n t = math.factorial(n)\n return math.factorial(2 * n) // t // t % (10 ** 9 + 7)", "def compute_value(n):\n mod = 10 ** 9 + 7\n if n == 1:\n return 2\n val = 2\n for i in range(1, n):\n val = val * (2 * i + 1) * 2 % mod\n x = pow(i + 1, mod - 2, mod)\n val = val * x % mod\n return val", "import math\n\ndef compute_value(n):\n count1 = math.factorial(2 * n)\n count2 = math.factorial(n)\n count3 = count2 ** 2\n ans = count1 // count3\n return ans % (10 ** 9 + 7)", "import math\n\ndef euclidean(mod, r, x_y_list):\n if r == 0:\n x_y_list[0] = 1\n x_y_list[1] = 0\n return (x_y_list[0], x_y_list[1])\n (x1, y1) = self.euclidean(r, mod % r, x_y_list)\n x_y_list[0] = y1\n x_y_list[1] = x1 - mod // r * y1\n return (x_y_list[0], x_y_list[1])\n\ndef modinverse(mod, r):\n x_y_list = [1, 0]\n (x, y) = self.euclidean(mod, r, x_y_list)\n return y\n\ndef compute_value(n):\n res = 2\n ncr = 1\n for r in range(0, n - 1):\n ncr = ncr % self.mod * (n - r) % self.mod % self.mod\n x = self.modinverse(self.mod, r + 1)\n ncr = ncr % self.mod * x % self.mod % self.mod\n res = (res % self.mod + ncr % self.mod * ncr % self.mod % self.mod % self.mod) % self.mod\n return int(res)", "from math import factorial as f\n\ndef compute_value(n):\n return f(n << 1) // f(n) ** 2 % (10 ** 9 + 7)", "import math\n\ndef modinverse(r):\n m0 = self.mod\n y = 1\n x = 0\n M = m0\n if self.mod == 1:\n return 0\n while M > 1:\n q = M // r\n temp = r\n r = M % r\n M = temp\n temp = y\n y = x - q * y\n x = temp\n if x < 0:\n x += m0\n return x\n\ndef compute_value(n):\n res = 2\n ncr = 1\n for r in range(0, n - 1):\n ncr = ncr % self.mod * (n - r) % self.mod % self.mod\n x = self.modinverse(r + 1)\n ncr = ncr % self.mod * x % self.mod % self.mod\n res = (res % self.mod + ncr % self.mod * ncr % self.mod % self.mod % self.mod) % self.mod\n return int(res)", "import math\n\ndef compute_value(n):\n x = math.factorial(n * 2)\n y = math.factorial(n)\n return x // y ** 2 % 1000000007", "import math\n\ndef verify(x):\n for i in range(2, math.floor(math.sqrt(x))):\n if x % i == 0:\n return False\n return True\nM = 1000 * 1000 * 1000 + 7\n\ndef pow1(x, y):\n if y == 0:\n return 1\n if y % 2 == 0:\n return self.pow(x, y // 2) ** 2 % M\n return self.pow(x, y // 2) ** 2 * x % M\n\ndef pow(x, y):\n val = 1\n while y:\n if y & 1:\n val = val * x % M\n y = y >> 1\n x = x * x % M\n return val\n\ndef compute_value(n):\n cur = 1\n ans = 0\n inverse = []\n for i in range(0, n):\n inverse.append(pow(i, M - 2, M))\n for i in range(1, n):\n cur = cur * (n - i + 1) * inverse[i] % M\n ans += cur * cur % M\n ans = ans % M\n ans += 2\n return ans % M\n\ndef compute_value1(n):\n return math.factorial(2 * n) // math.factorial(n) ** 2 % M", "import math\nmod = 10 ** 9 + 7\n\ndef compute_value(n):\n num = math.factorial(2 * n)\n den = math.factorial(n) ** 2\n return num // den % mod", "import math\n\ndef compute_value(n):\n MOD = 10 ** 9 + 7\n denominator = math.factorial(2 * n)\n numerator = math.factorial(n)\n ans = denominator // numerator ** 2 % MOD\n return ans", "import math\n\ndef ncr(n, r, p):\n num = den = 1\n for i in range(r):\n num = num * (n - i) % p\n den = den * (i + 1) % p\n return num * pow(den, p - 2, p) % p\n\ndef compute_value(n):\n return self.ncr(2 * n, n, 1000000007)", "def compute_value(n):\n ans = 0\n m = 1000000007\n num = 1\n den = 1\n for r in range(0, n + 1):\n val = num % m * pow(den, m - 2, m) % m % m\n ans = (ans % m + val % m * val % m % m) % m\n num = num % m * (n - r) % m % m\n den = den % m * (r + 1) % m % m\n return ans", "import math as m\n\ndef compute_value(n):\n ans = 0\n a = m.factorial(n)\n b = m.factorial(2 * n)\n return b // (a * a) % (10 ** 9 + 7)", "import math\n\ndef compute_value(n):\n a = math.factorial(2 * n)\n b = math.factorial(n)\n return a // b ** 2 % int(1000000000.0 + 7)", "import math\nmod = 10 ** 9 + 7\n\ndef compute_value(n):\n a1 = math.factorial(2 * n)\n a2 = math.factorial(n)\n return a1 // a2 ** 2 % mod", "def compute_value(n):\n k = 1\n for i in range(1, n + 1):\n k = k * (n + i) // i\n k = int(k)\n k = k % (10 ** 9 + 7)\n return k", "import math\n\ndef compute_value(n):\n x = math.factorial(n * 2)\n y = math.factorial(n)\n return int(x // y ** 2 % (10 ** 9 + 7))", "mod = int(1000000000.0 + 7)\nmx = int(300000.0 + 3)\nfact = [1 for n in range(mx)]\nfor n in range(1, mx):\n fact[n] = fact[n - 1] * n % mod\n\ndef bnp(base, pw):\n res = 1\n while pw:\n if pw & 1:\n res = res * base % mod\n pw >>= 1\n base = base * base % mod\n return res\n\ndef ncr(n, r):\n denom = fact[r] * fact[n - r] % mod\n denomInv = bnp(denom, mod - 2)\n res = fact[n] * denomInv\n return res % mod\n\ndef compute_value(x):\n res = ncr(2 * x, x)\n return res", "import math\n\ndef compute_value(n):\n s = 0\n c = math.factorial(2 * n)\n d = math.factorial(n)\n d *= d\n c = c // d\n c = c % 1000000007\n return c", "import math\nmod = 10 ** 9 + 7\n\ndef compute_value(n):\n ans = math.factorial(2 * n)\n ob = math.factorial(n)\n return ans // ob ** 2 % mod", "mod = int(1000000000.0) + 7\n\ndef gcd(a, b):\n if b == 0:\n return (1, 0, a)\n (x, y, r) = gcd(b, a % b)\n (x, y) = (y, x - a // b * y)\n return (x, y, r)\n\ndef nCk(n, k):\n ans = 1\n for i in range(n, n - k, -1):\n ans *= i\n ans %= mod\n for i in range(k):\n (x, _, _) = gcd(i + 1, mod)\n ans *= x % mod\n ans %= mod\n return ans\n\ndef compute_value(n):\n return nCk(n + n, n)"], "starter_code": "def compute_value(n):\n", "input_output": {"inputs": ["n = 2", "n = 1"], "outputs": ["6", "2"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms"], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/count-even-length1907/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n * log(n))", "entry_point": "compute_value", "task_id": "TACO_lite/359", "example": [[[2], [1]], ["6", "2"]]} +{"requirement": "Given a string str of length N, you have to find number of palindromic subsequence (need not necessarily be distinct) present in the string str.\nNote: You have to return the answer module 10^{9}+7;\n \nExample 1:\nInput: \nStr = \"abcd\"\nOutput: \n4\nExplanation:\npalindromic subsequence are : \"a\" ,\"b\", \"c\" ,\"d\"\n \nExample 2:\nInput: \nStr = \"aab\"\nOutput: \n4\nExplanation:\npalindromic subsequence are :\"a\", \"a\", \"b\", \"aa\"\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function countPs() which takes a string str as input parameter and returns the number of palindromic subsequence.\n \nExpected Time Complexity: O(N*N)\nExpected Auxiliary Space: O(N*N)\nConstraints:\n1<=length of string str <=1000", "solutions": ["def countps(s):\n n = len(s)\n dp = [[0] * n for _ in range(n)]\n for i in range(n):\n dp[i][i] = 1\n for length in range(2, n + 1):\n for i in range(n - length, -1, -1):\n j = i + length - 1\n if s[i] == s[j]:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] + 1\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n return dp[0][n - 1] % (10 ** 9 + 7)", "import numpy as np\n\ndef rec_sol(start, end, string):\n if start == end:\n return 1\n if start > end:\n return 0\n if string[start] == string[end]:\n return 1 + self.rec_sol(start, end - 1, string) + self.rec_sol(start + 1, end, string)\n else:\n return self.rec_sol(start, end - 1, string) + self.rec_sol(start + 1, end, string) - self.rec_sol(start + 1, end - 1, string)\n\ndef dp_sol(string):\n len_s = len(string)\n dp = np.array([[0] * len_s] * len_s)\n for i in range(len_s):\n for j in range(i, -1, -1):\n if i == j:\n dp[j][i] = 1\n elif string[i] == string[j]:\n dp[j][i] = (1 + dp[j][i - 1] + dp[j + 1][i]) % 1000000007\n else:\n dp[j][i] = (dp[j][i - 1] + dp[j + 1][i] - dp[j + 1][i - 1]) % 1000000007\n return dp[0][len_s - 1]\n\ndef countps(string):\n return self.dp_sol(string)", "def solve(i, j, s, dp):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n if s[i] == s[j]:\n ans = self.solve(i + 1, j, s, dp) + self.solve(i, j - 1, s, dp) + 1\n else:\n ans = self.solve(i + 1, j, s, dp) + self.solve(i, j - 1, s, dp) - self.solve(i + 1, j - 1, s, dp)\n dp[i][j] = ans\n return ans\n\ndef countps(string):\n n = len(string)\n dp = [[-1 for _ in range(n)] for _ in range(n)]\n ans = self.solve(0, n - 1, string, dp)\n ans = ans % (10 ** 9 + 7)\n return ans", "def countps(s):\n m = 1000000007\n n = len(s)\n dp = [[0] * n for _ in range(n)]\n for i in range(n):\n dp[i][i] = 1\n for cl in range(2, n + 1):\n for i in range(n - cl + 1):\n j = i + cl - 1\n if s[i] == s[j]:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] + 1\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n return dp[0][n - 1] % m", "def countps(string):\n N = len(string)\n dp = [[0 for j in range(N)] for i in range(N)]\n for g in range(0, N):\n i = 0\n j = g\n while j < N:\n if g == 0:\n dp[i][j] = 1\n elif g == 1:\n if string[i] == string[j]:\n dp[i][j] = 3\n else:\n dp[i][j] = 2\n elif string[i] == string[j]:\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] + 1\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n i += 1\n j += 1\n return dp[0][N - 1] % (10 ** 9 + 7)", "def countps1(st, i, j, dp):\n if i > j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n elif st[i] == st[j]:\n dp[i][j] = self.countps1(st, i + 1, j, dp) + self.countps1(st, i, j - 1, dp) + 1\n else:\n dp[i][j] = self.countps1(st, i + 1, j, dp) + self.countps1(st, i, j - 1, dp) - self.countps1(st, i + 1, j - 1, dp)\n return dp[i][j]\n\ndef countps(string):\n n = len(string)\n dp = [[-1 for i in range(n + 1)] for j in range(n + 1)]\n a = self.countps1(string, 0, n - 1, dp)\n return a % 1000000007", "def countps(string):\n MOD = int(1000000000.0) + 7\n n = len(string)\n dp = [[0] * n for _ in range(n)]\n for i in range(n):\n dp[i][i] = 1\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if string[i] == string[j]:\n dp[i][j] = (dp[i + 1][j] + dp[i][j - 1] + 1) % MOD\n else:\n dp[i][j] = (dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]) % MOD\n return dp[0][n - 1]", "def countps(string):\n\n def subs(i, j, strg):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n if strg[i] == strg[j]:\n dp[i][j] = subs(i + 1, j, strg) + subs(i, j - 1, strg) + 1\n else:\n dp[i][j] = subs(i + 1, j, strg) + subs(i, j - 1, strg) - subs(i + 1, j - 1, strg)\n return dp[i][j]\n n = len(string)\n MOD = 10 ** 9 + 7\n dp = [[-1] * n for i in range(n)]\n ans = subs(0, n - 1, string)\n return ans % MOD", "def countps(str):\n N = len(str)\n cps = [[0 for i in range(N + 2)] for j in range(N + 2)]\n for i in range(N):\n cps[i][i] = 1\n for L in range(2, N + 1):\n for i in range(N):\n k = L + i - 1\n if k < N:\n if str[i] == str[k]:\n cps[i][k] = cps[i][k - 1] + cps[i + 1][k] + 1\n else:\n cps[i][k] = cps[i][k - 1] + cps[i + 1][k] - cps[i + 1][k - 1]\n return cps[0][N - 1] % (pow(10, 9) + 7)", "def countps(string):\n if len(string) == 0:\n return 0\n big = 10 ** 9 + 7\n dp = [[-1 for _ in range(len(string))] for __ in range(len(string))]\n return self.num_pal(string, dp, 0, len(string) - 1, big)\n\ndef num_pal(s, arr, start, end, mod):\n if start == end:\n return 1\n if start > end:\n return 0\n if arr[start][end] != -1:\n return arr[start][end]\n if s[start] == s[end]:\n arr[start][end] = 1 + self.num_pal(s, arr, start + 1, end, mod) % mod + self.num_pal(s, arr, start, end - 1, mod) % mod\n arr[start][end] %= mod\n else:\n arr[start][end] = self.num_pal(s, arr, start + 1, end, mod) % mod + self.num_pal(s, arr, start, end - 1, mod) % mod - self.num_pal(s, arr, start + 1, end - 1, mod) % mod\n arr[start][end] %= mod\n return arr[start][end]", "def countps(s):\n dp = [[-1] * len(s) for _ in range(len(s))]\n\n def rec(i, j):\n nonlocal dp, s\n if dp[i][j] != -1:\n return dp[i][j]\n if i == j:\n dp[i][j] = 1\n return dp[i][j]\n if i > j:\n return 0\n if s[i] == s[j]:\n a = rec(i + 1, j) + rec(i, j - 1) + 1\n dp[i][j] = a\n return a\n else:\n a = rec(i + 1, j) + rec(i, j - 1) - rec(i + 1, j - 1)\n dp[i][j] = a\n return a\n return rec(0, len(s) - 1) % (10 ** 9 + 7)", "def countps(s):\n n = len(s)\n dp = {}\n mod = 10 ** 9 + 7\n\n def backtracking(start, end):\n if (start, end) in dp:\n return dp[start, end]\n if start == end:\n dp[start, end] = 1\n return 1\n if start > end:\n dp[start, end] = 0\n return 0\n if s[start] == s[end]:\n dp[start, end] = 1 + backtracking(start + 1, end) + backtracking(start, end - 1)\n return dp[start, end] % mod\n else:\n dp[start, end] = backtracking(start + 1, end) + backtracking(start, end - 1) - backtracking(start + 1, end - 1)\n return dp[start, end] % mod\n return backtracking(0, n - 1)", "def countps(s):\n cnt = 0\n dp = [[0 for _ in range(len(s))] for _ in range(len(s))]\n for g in range(len(s)):\n i = 0\n for j in range(g, len(s)):\n if g == 0:\n dp[i][j] = 1\n elif g == 1:\n if s[i] == s[j]:\n dp[i][j] = 3\n else:\n dp[i][j] = 2\n elif s[i] == s[j]:\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] + 1\n else:\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]\n i += 1\n return dp[0][len(s) - 1] % (10 ** 9 + 7)", "def countps(string1):\n self.string1 = string1\n self.n = len(string1)\n self.t = [[-1 for _ in range(self.n + 1)] for _ in range(self.n + 1)]\n return self.count_palindromic_subsequence(i=0, j=self.n - 1) % (10 ** 9 + 7)\n\ndef count_palindromic_subsequence(i, j):\n if i > j:\n return 0\n if self.t[i][j] != -1:\n return self.t[i][j]\n if i == j:\n self.t[i][j] = 1\n return self.t[i][j]\n elif self.string1[i] == self.string1[j]:\n self.t[i][j] = 1 + self.count_palindromic_subsequence(i + 1, j) + self.count_palindromic_subsequence(i, j - 1)\n return self.t[i][j]\n else:\n self.t[i][j] = self.count_palindromic_subsequence(i + 1, j) + self.count_palindromic_subsequence(i, j - 1) - self.count_palindromic_subsequence(i + 1, j - 1)\n return self.t[i][j]", "def countps(string):\n n = len(string)\n dp = [[False for i in range(n)] for j in range(n)]\n mod = 1000000007\n for gap in range(n):\n (i, j) = (0, gap)\n while j < n:\n if gap == 0:\n dp[i][j] = 1\n elif gap == 1:\n if string[i] == string[j]:\n dp[i][j] = 3\n else:\n dp[i][j] = 2\n elif string[i] == string[j]:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] + 1\n else:\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]\n dp[i][j] = dp[i][j] % mod\n i += 1\n j += 1\n return dp[0][n - 1]", "def recur(i, j, string, dp):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n if string[i] == string[j]:\n dp[i][j] = self.recur(i + 1, j, string, dp) + self.recur(i, j - 1, string, dp) + 1\n else:\n dp[i][j] = self.recur(i + 1, j, string, dp) + self.recur(i, j - 1, string, dp) - self.recur(i + 1, j - 1, string, dp)\n return dp[i][j]\n\ndef countps(string):\n dp = [[-1 for i in range(len(string))] for j in range(len(string))]\n return self.recur(0, len(string) - 1, string, dp) % (10 ** 9 + 7)", "def countpsUtil(i, j, dp, s):\n if i > j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if i == j:\n dp[i][j] = 1\n elif s[i] == s[j]:\n dp[i][j] = self.countpsUtil(i + 1, j, dp, s) + self.countpsUtil(i, j - 1, dp, s) + 1\n else:\n dp[i][j] = self.countpsUtil(i + 1, j, dp, s) + self.countpsUtil(i, j - 1, dp, s) - self.countpsUtil(i + 1, j - 1, dp, s)\n return dp[i][j] % self.mod\n\ndef countps(s):\n self.mod = 10 ** 9 + 7\n n = len(s)\n dp = [[-1 for x in range(n + 1)] for y in range(n + 1)]\n self.countpsUtil(0, n - 1, dp, s)\n return dp[0][n - 1] % self.mod", "def countps(arr):\n\n def count(i, j, arr, dp):\n if i > j:\n return 0\n if i == j:\n dp[i][j] = 1\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n if arr[i] == arr[j]:\n dp[i][j] = 1 + count(i + 1, j, arr, dp) + count(i, j - 1, arr, dp)\n return dp[i][j]\n dp[i][j] = count(i + 1, j, arr, dp) + count(i, j - 1, arr, dp) - count(i + 1, j - 1, arr, dp)\n return dp[i][j]\n dp = [[-1] * len(arr) for x in range(len(arr))]\n return count(0, len(arr) - 1, arr, dp) % (10 ** 9 + 7)", "def countps(s):\n\n def manu(i, j):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n if s[i] == s[j]:\n k = 1 + manu(i + 1, j) + manu(i, j - 1)\n else:\n k = manu(i + 1, j) + manu(i, j - 1) - manu(i + 1, j - 1)\n k = k % (10 ** 9 + 7)\n dp[i][j] = k\n return k\n dp = [[-1 for i in range(len(s))] for i in range(len(s))]\n return manu(0, len(s) - 1)", "def countps(string):\n n = len(string)\n count = [[0 for i in range(n)] for j in range(n)]\n for i in range(n):\n count[i][i] = 1\n for L in range(2, n + 1):\n for i in range(n - L + 1):\n j = i + L - 1\n if string[i] == string[j]:\n count[i][j] = 1 + count[i][j - 1] + count[i + 1][j]\n else:\n count[i][j] = count[i][j - 1] + count[i + 1][j] - count[i + 1][j - 1]\n return count[0][n - 1] % (10 ** 9 + 7)", "from itertools import combinations\n\ndef countps(string):\n\n def subs(i, j, strng):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n if strng[i] == strng[j]:\n dp[i][j] = subs(i + 1, j, strng) + subs(i, j - 1, strng) + 1\n else:\n dp[i][j] = subs(i + 1, j, strng) + subs(i, j - 1, strng) - subs(i + 1, j - 1, strng)\n return dp[i][j]\n dp = [[-1] * len(string) for i in range(len(string))]\n return subs(0, len(string) - 1, string) % (10 ** 9 + 7)", "def countps(string):\n\n def count(i, j, st, dp):\n if i > j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if i == j:\n return 1\n elif st[i] == st[j]:\n dp[i][j] = 1 + count(i + 1, j, st, dp) + count(i, j - 1, st, dp)\n return dp[i][j] % 1000000007\n else:\n dp[i][j] = count(i + 1, j, st, dp) + count(i, j - 1, st, dp) - count(i + 1, j - 1, st, dp)\n return dp[i][j] % 1000000007\n dp = [[-1 for j in range(len(string))] for i in range(len(string))]\n return count(0, len(string) - 1, string, dp)", "def countps(s):\n n = len(s)\n dp = {}\n mod = 1000000007\n\n def fun(i, j):\n if i > j:\n return 0\n if i == j:\n return 1\n if (i, j) in dp:\n return dp[i, j]\n if s[i] == s[j]:\n dp[i, j] = 1 + fun(i + 1, j) + fun(i, j - 1)\n return dp[i, j]\n dp[i, j] = fun(i + 1, j) + fun(i, j - 1) - fun(i + 1, j - 1)\n return dp[i, j]\n return fun(0, len(s) - 1) % mod", "def countps(string):\n\n def func(i, j, stri, dp):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n if stri[i] == stri[j]:\n dp[i][j] = 1 + func(i + 1, j, stri, dp) + func(i, j - 1, stri, dp)\n return dp[i][j]\n else:\n dp[i][j] = func(i + 1, j, stri, dp) + func(i, j - 1, stri, dp) - func(i + 1, j - 1, stri, dp)\n return dp[i][j]\n dp = [[-1 for i in range(len(string))] for j in range(len(string))]\n kk = func(0, len(string) - 1, string, dp)\n return kk % (10 ** 9 + 7)", "def countps(s):\n N = len(s)\n mod = 10 ** 9 + 7\n dp = [[0] * N for _ in range(N)]\n for i in range(N):\n dp[i][i] = 1\n for L in range(2, N + 1):\n for i in range(N - L + 1):\n j = i + L - 1\n if s[i] == s[j]:\n dp[i][j] = (dp[i + 1][j] + dp[i][j - 1] + 1) % mod\n else:\n dp[i][j] = (dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]) % mod\n dp[i][j] %= mod\n return dp[0][N - 1] % mod", "def countps(string):\n n = len(string)\n dp = [[-1 for _ in range(n + 1)] for _ in range(n + 1)]\n\n def sol(i, j, string, dp):\n mod = 1000000000.0 + 7\n if i == j:\n return 1\n if i > j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if string[i] == string[j]:\n dp[i][j] = (1 + sol(i + 1, j, string, dp) + sol(i, j - 1, string, dp)) % mod\n else:\n dp[i][j] = ((sol(i + 1, j, string, dp) + sol(i, j - 1, string, dp) - sol(i + 1, j - 1, string, dp)) % mod + mod) % mod\n return dp[i][j]\n return int(sol(0, len(string) - 1, string, dp))", "def countps(string):\n dp = [[None] * len(string) for _ in range(len(string))]\n\n def fun(i, j):\n if i == j:\n return 1\n if i > j:\n return 0\n if dp[i][j] != None:\n return dp[i][j]\n if string[i] == string[j]:\n dp[i][j] = 1 + fun(i + 1, j) + fun(i, j - 1)\n return dp[i][j] % (pow(10, 9) + 7)\n else:\n dp[i][j] = fun(i + 1, j) + fun(i, j - 1) - fun(i + 1, j - 1)\n return dp[i][j] % (pow(10, 9) + 7)\n return fun(0, len(string) - 1)", "def countps(s):\n dp = [[0] * len(s) for i in range(len(s))]\n for gap in range(len(s)):\n for i in range(len(s) - gap):\n j = i + gap\n if i == j:\n dp[i][j] = 1\n else:\n if s[i] == s[j]:\n dp[i][j] = 1 + dp[i + 1][j] + dp[i][j - 1]\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n dp[i][j] = dp[i][j] % 1000000007\n return dp[0][len(s) - 1]", "def countps(string):\n n = len(string)\n mod = 10 ** 9 + 7\n dp = [[0] * n for i in range(n)]\n for g in range(0, n):\n for (i, j) in zip(range(0, n), range(g, n)):\n if g == 0:\n dp[i][j] = 1\n elif g == 1:\n if string[i] == string[j]:\n dp[i][j] = 3\n else:\n dp[i][j] = 2\n elif string[i] == string[j]:\n dp[i][j] = (dp[i][j - 1] + dp[i + 1][j] + 1) % mod\n else:\n dp[i][j] = (dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]) % mod\n return dp[0][n - 1] % mod", "import sys\nsys.setrecursionlimit(10000)\n\ndef countps(stringe):\n hmap = {}\n n = len(stringe)\n\n def count_palindrome_sub(S, i, j):\n mod = 1000000000.0 + 7\n if i > j:\n return 0\n if i == j:\n return 1\n if (i, j) not in hmap:\n hmap[i, j] = count_palindrome_sub(S, i + 1, j) % mod + count_palindrome_sub(S, i, j - 1) % mod\n if S[i] == S[j]:\n hmap[i, j] += 1\n else:\n hmap[i, j] -= count_palindrome_sub(S, i + 1, j - 1) % mod\n return hmap[i, j]\n ans = count_palindrome_sub(stringe, 0, n - 1)\n return int(ans % (1000000000.0 + 7))", "def countps(string):\n s = string\n N = len(s)\n dp = [[0 for _ in range(N)] for _ in range(N)]\n for i in range(N, -1, -1):\n for j in range(i, N, 1):\n if i == j:\n dp[i][j] = 1\n elif s[i] == s[j]:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] + 1\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n return dp[0][N - 1] % (pow(10, 9) + 7)", "def countps(string):\n arr = [[-1 for i in range(len(string))] for j in range(len(string))]\n (i, j) = (0, len(string) - 1)\n res = self.cpsHelper(string, i, j, arr)\n return res % (10 ** 9 + 7)\n\ndef cpsHelper(string, i, j, arr):\n if i > j:\n return 0\n if arr[i][j] != -1:\n return arr[i][j]\n if string[i] == string[j]:\n res = self.cpsHelper(string, i + 1, j, arr) + self.cpsHelper(string, i, j - 1, arr) + 1\n else:\n res = self.cpsHelper(string, i + 1, j, arr) + self.cpsHelper(string, i, j - 1, arr) - self.cpsHelper(string, i + 1, j - 1, arr)\n arr[i][j] = res\n return res", "def countps(s):\n dp = [[0] * len(s) for i in range(len(s))]\n for gap in range(len(s)):\n i = 0\n j = gap\n while j < len(s):\n if gap == 0:\n dp[i][j] = 1\n elif gap == 1:\n if s[i] == s[j]:\n dp[i][j] = 3\n else:\n dp[i][j] = 2\n elif s[i] == s[j]:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] + 1\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n i = i + 1\n j = j + 1\n return dp[0][-1] % 1000000007", "def countps(s):\n n = len(s)\n dp = [[0 for i in range(n)] for j in range(n)]\n fp = sp = 0\n for i in range(n):\n dp[i][i] = 1\n for i in range(1, n):\n for j in range(n - i):\n fp = j\n sp = j + i\n if s[fp] == s[sp]:\n dp[fp][sp] = (dp[fp + 1][sp] + dp[fp][sp - 1] + 1) % (10 ** 9 + 7)\n else:\n dp[fp][sp] = (dp[fp + 1][sp] + dp[fp][sp - 1] - dp[fp + 1][sp - 1]) % (10 ** 9 + 7)\n return dp[fp][sp]", "def countps(s):\n dp = []\n ans = 0\n for i in range(len(s)):\n dp.append([0] * len(s))\n for i in range(len(s)):\n dp[i][i] = 1\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n dp[i][i + 1] = 3\n else:\n dp[i][i + 1] = 2\n for lent in range(2, len(s)):\n i = 0\n while i + lent < len(s):\n if s[i] != s[i + lent]:\n dp[i][i + lent] = dp[i + 1][i + lent] + dp[i][i + lent - 1] - dp[i + 1][i + lent - 1]\n else:\n dp[i][i + lent] = dp[i + 1][i + lent] + dp[i][i + lent - 1] + 1\n i += 1\n return dp[0][len(s) - 1] % (10 ** 9 + 7)", "def countps(s):\n t = [[-1 for i in range(1001)] for i in range(1001)]\n mod = 10 ** 9 + 7\n\n def solve(s, i, j, t):\n if i == j:\n return 1\n if i > j:\n return 0\n if t[i][j] != -1:\n return t[i][j]\n elif s[i] == s[j]:\n t[i][j] = 1 + solve(s, i + 1, j, t) % mod + solve(s, i, j - 1, t) % mod\n t[i][j] %= mod\n return t[i][j]\n else:\n t[i][j] = solve(s, i + 1, j, t) % mod + solve(s, i, j - 1, t) % mod - solve(s, i + 1, j - 1, t) % mod\n t[i][j] %= mod\n return t[i][j]\n return solve(s, 0, len(s) - 1, t)", "def countps(string):\n S = string\n n = len(S)\n dp = [[0] * n for i in range(n)]\n M = 10 ** 9 + 7\n for i in range(n):\n for j in range(i, -1, -1):\n if i == j:\n dp[j][i] = 1\n elif S[i] == S[j]:\n dp[j][i] = dp[j + 1][i] + dp[j][i - 1] + 1\n else:\n dp[j][i] = dp[j + 1][i] + dp[j][i - 1] - dp[j + 1][i - 1]\n return dp[0][n - 1] % M", "def countps(string):\n dic = {}\n n = len(string)\n\n def recursive(string, n, left, right):\n if left > right:\n return 0\n if (left, right) in dic:\n return dic[left, right]\n if left == right:\n dic[left, right] = 1\n elif string[left] == string[right]:\n dic[left, right] = (1 + recursive(string, n, left + 1, right) + recursive(string, n, left, right - 1)) % 1000000007\n else:\n dic[left, right] = (recursive(string, n, left + 1, right) + recursive(string, n, left, right - 1) - recursive(string, n, left + 1, right - 1)) % 1000000007\n return dic[left, right]\n return recursive(string, n, 0, n - 1)", "def countps(string):\n n = len(string)\n MOD = 10 ** 9 + 7\n dp = [[0] * n for i in range(n)]\n for l in range(1, n + 1):\n i = 0\n while i + l <= n:\n j = i + l - 1\n if i > j:\n break\n if l == 1:\n dp[i][j] = 1\n elif l == 2:\n if string[i] == string[j]:\n dp[i][j] = 3\n else:\n dp[i][j] = 2\n elif string[i] == string[j]:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] + 1\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n dp[i][j] %= MOD\n i += 1\n return dp[0][n - 1]", "def countps(s):\n\n def count(i, j, s):\n if i > j:\n return 0\n if i == j:\n return 1\n if t[i][j] != -1:\n return t[i][j]\n if s[i] == s[j]:\n t[i][j] = 1 + count(i + 1, j, s) + count(i, j - 1, s)\n return t[i][j] % 1000000007\n else:\n t[i][j] = count(i + 1, j, s) + count(i, j - 1, s) - count(i + 1, j - 1, s)\n return t[i][j] % 1000000007\n n = len(s)\n t = [[-1] * (n + 1) for x in range(n + 1)]\n return count(0, n - 1, s)", "def solver(str, i, j, dct):\n if i > j:\n return 0\n if (i, j) in dct:\n return dct[i, j]\n res = 0\n if str[i] == str[j]:\n res = solver(str, i + 1, j, dct) + solver(str, i, j - 1, dct) + 1\n else:\n res = solver(str, i + 1, j, dct) + solver(str, i, j - 1, dct) - solver(str, i + 1, j - 1, dct)\n res %= 1000000007\n dct[i, j] = res\n return res\n\ndef countps(string):\n dct = dict()\n return solver(string, 0, len(string) - 1, dct)", "def countps(string):\n n = len(string)\n dp = []\n for _ in range(n):\n dp.append([0] * n)\n for i in range(n):\n dp[i][i] = 1\n for i in range(n - 1):\n k = 0\n for j in range(i + 1, n):\n if string[k] == string[j]:\n dp[k][j] = 1 + dp[k][j - 1] + dp[k + 1][j]\n else:\n dp[k][j] = dp[k][j - 1] + dp[k + 1][j] - dp[k + 1][j - 1]\n k += 1\n return dp[0][n - 1] % (10 ** 9 + 7)", "def countps(string):\n dp = [[0 for j in range(len(string))] for i in range(2)]\n mod = 1000000007\n dp[1][-1] = 1\n for i in range(len(string) - 2, -1, -1):\n dp[0][i] = 1\n for j in range(i + 1, len(string)):\n dp[0][j] = 0\n dp[0][j] += dp[0][j - 1] + dp[1][j]\n if string[i] == string[j]:\n dp[0][j] += 1\n else:\n dp[0][j] -= dp[1][j - 1]\n dp[0][j] %= mod\n (dp[0], dp[1]) = (dp[1], dp[0])\n return dp[1][len(string) - 1]", "import sys\nsys.setrecursionlimit(10000)\n\ndef __count_palin_subseq_helper(i, j, string):\n if i > j:\n return 0\n if i == j:\n return 1\n if self.dp[i][j] == None:\n self.dp[i][j] = 0\n self.dp[i][j] += self.__count_palin_subseq_helper(i, j - 1, string) + self.__count_palin_subseq_helper(i + 1, j, string)\n if string[i] == string[j]:\n self.dp[i][j] += 1\n else:\n self.dp[i][j] -= self.__count_palin_subseq_helper(i + 1, j - 1, string)\n self.dp[i][j] %= self.mod\n return self.dp[i][j]\n\ndef countps(string):\n self.dp = [[None for j in range(len(string))] for i in range(len(string))]\n self.mod = 1000000007\n return self.__count_palin_subseq_helper(0, len(string) - 1, string)", "def countps(s):\n n = len(s)\n dp = [[-1 for k in range(n + 1)] for t in range(n + 1)]\n m = 10 ** 9 + 7\n\n def memo(i, j):\n if i > j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if i == j:\n dp[i][j] = 1\n return dp[i][j]\n if s[i] == s[j]:\n dp[i][j] = memo(i + 1, j) + memo(i, j - 1) + 1\n else:\n dp[i][j] = memo(i + 1, j) + memo(i, j - 1) - memo(i + 1, j - 1)\n return dp[i][j]\n return memo(0, n - 1) % m", "def countps(string):\n n = len(string)\n dp = [[-1 for x in range(n)] for y in range(n)]\n\n def countPA(i, j):\n if i > j:\n return 0\n if dp[i][j] != -1:\n return dp[i][j]\n if i == j:\n dp[i][j] = 1\n return dp[i][j]\n if string[i] == string[j]:\n dp[i][j] = countPA(i + 1, j) + countPA(i, j - 1) + 1\n return dp[i][j]\n else:\n dp[i][j] = countPA(i + 1, j) + countPA(i, j - 1) - countPA(i + 1, j - 1)\n return dp[i][j]\n return countPA(0, n - 1) % (10 ** 9 + 7)", "def solve(s, i, j, dp):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j]:\n return dp[i][j]\n if s[i] == s[j]:\n dp[i][j] = 1 + self.solve(s, i + 1, j, dp) + self.solve(s, i, j - 1, dp)\n else:\n dp[i][j] = self.solve(s, i + 1, j, dp) + self.solve(s, i, j - 1, dp) - self.solve(s, i + 1, j - 1, dp)\n return dp[i][j]\n\ndef countps(s):\n mod = 10 ** 9 + 7\n dp = [[0 for i in range(len(s))] for j in range(len(s))]\n return self.solve(s, 0, len(s) - 1, dp) % mod", "def countps(string):\n n = len(string)\n ans = [[0] * n for i in range(n)]\n for d in range(n):\n i = 0\n for j in range(d, n):\n if d == 0:\n ans[i][j] = 1\n elif string[i] == string[j]:\n ans[i][j] = ans[i][j - 1] + ans[i + 1][j] + 1\n else:\n ans[i][j] = ans[i][j - 1] + ans[i + 1][j] - ans[i + 1][j - 1]\n i += 1\n return ans[0][n - 1] % (10 ** 9 + 7)", "def countps(string):\n n = len(string)\n dp = [[0] * n for _ in range(n)]\n mod = 1000000007\n for i in range(n):\n dp[i][i] = 1\n for i in range(0, n - 2 + 1):\n j = i + 2 - 1\n if string[i] == string[j]:\n dp[i][j] = 3\n elif string[i] != string[j]:\n dp[i][j] = 2\n for l in range(3, n + 1):\n for i in range(0, n - l + 1):\n j = i + l - 1\n if string[i] == string[j]:\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] + 1\n elif string[i] != string[j]:\n dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]\n if dp[0][n - 1] > mod:\n return dp[0][n - 1] % mod\n else:\n return dp[0][n - 1]"], "starter_code": "def countps(string):\n", "input_output": {"inputs": ["Str = \"abcd\"", "Str = \"aab\""], "outputs": ["4", "4"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/count-palindromic-subsequences/1", "Expected Auxiliary Space": "O(N*N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*N)", "entry_point": "countps", "task_id": "TACO_lite/329", "example": [[["abcd"], ["aab"]], ["4", "4"]]} +{"requirement": "Given an array arr of n integers, sort the first half of the array in ascending order and second half in descending order.\nExample 1:\nInput:\nn = 4\narr[] = {10, 20, 30, 40}\nOutput: 10 20 40 30\nExample 2:\nInput:\nn = 9\narr[] = {5, 4, 6, 2, 1, 3, 8, 9, 7}\nOutput: 2 4 5 6 9 8 7 3 1\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function customSort() which takes the array of integers arr and n as parameters and returns void. You need to change the array itself.\nExpected Time Complexity: O(n*logn)\nExpected Auxiliary Space: O(1)\nConstraints: \n1 <= n <= 10^{5}\n1 <= arr[i] <= 10^{6}", "solutions": ["def customsort(arr, n):\n i = n // 2\n arr[:i] = sorted(arr[:i])\n arr[i:] = sorted(arr[i:], reverse=True)\n return arr", "def customsort(arr, n):\n arr[0:int(n / 2)] = sorted(arr[0:int(n / 2)])\n arr[int(n / 2):] = list(reversed(sorted(arr[int(n / 2):])))", "def customsort(arr, n):\n left = arr[:n // 2]\n right = arr[n // 2:]\n left.sort()\n right.sort(reverse=True)\n left = left + right\n for i in range(n):\n arr[i] = left[i]", "def customsort(arr, n):\n mid = n // 2\n b = arr[:mid]\n c = arr[mid:]\n b.sort()\n c.sort(reverse=True)\n d = b + c\n arr[:] = d[:]\n return arr", "def customsort(arr, n):\n p = arr[:n // 2]\n q = arr[n // 2:]\n p.sort()\n q.sort()\n q.reverse()\n a = p + q\n arr[:] = a[:]", "def customsort(arr, n):\n li = []\n li2 = []\n for i in range(n // 2):\n li.append(arr[i])\n li = sorted(li)\n for j in range(n // 2, n):\n li2.append(arr[j])\n li2.sort(reverse=True)\n for i in range(len(li2)):\n li.append(li2[i])\n return li", "def customsort(arr, n):\n op = arr[:n // 2]\n lp = arr[n // 2:]\n op.sort()\n lp.sort(reverse=True)\n d = op + lp\n arr[:] = d[:]\n return arr", "def customsort(arr, n):\n m = n // 2\n a = arr[:m]\n b = arr[m:]\n a.sort()\n b.sort(reverse=True)\n a.extend(b)\n for i in range(n):\n arr[i] = a[i]\n return arr", "def customsort(arr, n):\n i = n // 2\n brr = sorted(arr[:i]) + sorted(arr[i:], reverse=True)\n for i in range(n):\n arr[i] = brr[i]\n return", "def customsort(arr, n):\n arr1 = []\n arr2 = []\n i = 0\n while i < n:\n if i < n // 2:\n arr1.append(arr[i])\n else:\n arr2.append(arr[i])\n i += 1\n arr1.sort()\n arr2.sort(reverse=True)\n for i in range(len(arr1)):\n arr[i] = arr1[i]\n for i in range(len(arr2)):\n arr[i + len(arr1)] = arr2[i]", "def customsort(arr, n):\n dupli = arr.copy()\n (left, right) = (arr[:n // 2], arr[n // 2:])\n (left.sort(), right.sort(reverse=True))\n arr.clear()\n (arr.extend(left), arr.extend(right))\n return arr", "def customsort(arr, n):\n a = arr[:n // 2]\n b = arr[n // 2:]\n a.sort()\n b.sort(reverse=True)\n arr[:] = a + b", "def customsort(arr, n):\n arr[:n // 2] = sorted(arr[:n // 2])\n arr[n // 2:] = sorted(arr[n // 2:], reverse=True)", "def customsort(arr, n):\n a = arr[:n // 2]\n b = arr[n // 2:]\n a.sort()\n b.sort(reverse=True)\n c = a + b\n for i in range(len(c)):\n arr[i] = c[i]", "def customsort(arr, n):\n n = n // 2\n fh = arr[:n]\n sh = arr[n:]\n fh.sort()\n sh.sort(reverse=True)\n res = fh + sh\n arr[:] = res[:]\n return res", "def customsort(arr, n):\n a = n // 2\n arr[0:a] = sorted(arr[0:a])\n arr[a:n] = sorted(arr[a:n], reverse=True)\n return arr", "def customsort(arr, n):\n b = []\n c = []\n m = n // 2\n for i in range(0, m):\n b.append(arr[i])\n for i in range(m, n):\n c.append(arr[i])\n b.sort()\n c.sort(reverse=True)\n d = b + c\n for i in range(n):\n arr[i] = d[i]\n return arr", "def customsort(arr, n):\n t = n // 2\n l = arr[:t]\n l.sort()\n for i in range(0, t):\n arr[i] = l[i]\n h = arr[t:]\n h.sort(reverse=True)\n for i in h:\n arr[t] = i\n t = t + 1", "def customsort(arr, n):\n l = n // 2\n arr1 = sorted(arr[0:l])\n arr2 = sorted(arr[l:n], reverse=True)\n arr3 = arr1 + arr2\n arr[:] = arr3[:]", "def customsort(arr, n):\n from math import floor\n m = floor(n / 2)\n l = arr[0:m]\n l.sort()\n r = arr[m:n]\n r.sort(reverse=True)\n a1 = l + r\n for (i, v) in enumerate(a1):\n arr[i] = v", "def customsort(arr, n):\n l1 = arr[:n // 2]\n l2 = arr[n // 2:]\n l1.sort()\n l2.sort(reverse=True)\n arr.clear()\n l3 = l1 + l2\n for i in l3:\n arr.append(i)", "def customsort(arr, n):\n half = n // 2\n list1 = arr[:half]\n list2 = arr[half:]\n list1.sort()\n list2.sort(reverse=True)", "def customsort(arr, n):\n a1 = arr[:n // 2]\n a2 = arr[n // 2:]\n a1.sort()\n a2.sort(reverse=True)\n arr[:] = a1[:] + a2[:]", "def customsort(arr, n):\n b = arr[0:n // 2]\n c = arr[n // 2:n]\n b.sort()\n c.sort(reverse=True)\n b.extend(c)\n for i in range(0, n):\n arr[i] = b[i]\n return arr", "def customsort(arr, n):\n if n % 2 == 0:\n l = arr[:n // 2]\n l1 = arr[n // 2:]\n l.sort()\n l1.sort()\n l1 = l1[::-1]\n l2 = l + l1\n for i in range(n):\n arr[i] = l2[i]\n else:\n l = arr[:n // 2]\n l1 = arr[n // 2:]\n l.sort()\n l1.sort()\n l1 = l1[::-1]\n l2 = l + l1\n for i in range(n):\n arr[i] = l2[i]", "def customsort(arr, n):\n l = sorted(arr[:n // 2])\n r = sorted(arr[n // 2:], reverse=True)\n new = l + r\n for i in range(len(new)):\n arr[i] = new[i]", "def customsort(arr, n):\n middle = n // 2\n a = arr[:middle]\n b = arr[middle:]\n a.sort()\n b.sort(reverse=True)\n c = a + b\n arr[:] = c[:]\n return arr", "def customsort(arr, n):\n g = [arr[i] for i in range(0, n // 2)]\n h = [arr[i] for i in range(n // 2, n)]\n g.sort()\n h.sort()\n j = h[::-1]\n arr[:] = g + j", "def customsort(arr, n):\n x = sorted(arr[:n // 2])\n y = sorted(arr[n // 2:])\n z = y[::-1]\n a = x + z\n for i in range(n):\n if arr[i] != a[i]:\n arr[i] = a[i]", "def customsort(arr, n):\n (brr, crr) = (arr[:n // 2], arr[n // 2:])\n brr.sort()\n crr.sort(reverse=True)\n arr.clear()\n krr = brr + crr\n arr[:] = krr[:]\n return arr", "def customsort(arr, n):\n k = arr[:n // 2].copy()\n j = arr[n // 2:n].copy()\n k.sort()\n j.sort()\n lis = []\n lis = k.copy()\n for i in j[::-1]:\n lis.append(i)\n for i in range(n):\n arr[i] = lis[i]\n return arr", "def customsort(arr, n):\n a1 = arr[:n // 2]\n a2 = arr[n // 2:]\n a1.sort()\n a2.sort(reverse=True)\n arr.clear()\n arr.extend(a1)\n arr.extend(a2)\n return arr", "def customsort(arr, n):\n length = n // 2\n first_half = []\n second_half = []\n for i in range(length):\n first_half.append(arr[i])\n for j in range(length, n):\n second_half.append(arr[j])\n first_half.sort()\n second_half.sort(reverse=True)\n new_array = first_half + second_half\n arr.clear()\n for i in range(len(new_array)):\n arr.append(new_array[i])", "def customsort(arr, n):\n a = int(n / 2)\n b = arr[a:n]\n c = arr[0:a]\n b.sort(reverse=True)\n c.sort()\n d = c + b\n arr[:] = d", "def customsort(arr, n):\n index = len(arr) // 2\n arr[0:index] = sorted(arr[:index])\n arr[index:n] = sorted(arr[index:n], reverse=True)", "def customsort(arr, n):\n l = []\n k = []\n m = n // 2\n for i in range(0, m):\n l.append(arr[i])\n for j in range(m, n):\n k.append(arr[j])\n l.sort()\n k.sort(reverse=True)\n c = l + k\n for i in range(n):\n arr[i] = c[i]\n return arr", "def customsort(arr, n):\n (a, b) = ([], [])\n for i in range(0, n // 2):\n a.append(arr[i])\n for i in range(n // 2, n):\n b.append(arr[i])\n a.sort()\n b.sort(reverse=True)\n arr[:] = a + b\n return arr", "def customsort(arr, n):\n mid = n // 2\n x = arr[:mid]\n y = arr[mid:]\n x.sort()\n y.sort(reverse=True)\n a = x + y\n for i in range(n):\n arr[i] = a[i]", "def customsort(arr, n):\n x = []\n y = []\n mid = n // 2\n for i in range(0, mid):\n x.append(arr[i])\n for i in range(mid, n):\n y.append(arr[i])\n x.sort()\n y.sort(reverse=True)\n l = x + y\n for i in range(n):\n arr[i] = l[i]\n return arr", "def customsort(arr, n):\n mid = n // 2\n arr1 = arr[:mid]\n arr2 = arr[mid:]\n arr1.sort()\n arr2.sort(reverse=True)\n arr[:] = arr1 + arr2", "def customsort(arr, n):\n l = len(arr)\n a1 = arr[:l // 2]\n a2 = arr[l // 2:]\n a1 = sorted(a1)\n a2 = sorted(a2, reverse=True)\n a1.extend(a2)\n for x in range(n):\n arr[x] = str(a1[x])\n arr = ' '.join(arr)\n return arr", "def customsort(arr, n):\n mid = n // 2\n new_arr = arr[:mid]\n new_arr1 = arr[mid:]\n new_arr.sort()\n new_arr1.sort(reverse=True)\n count = 0\n for i in range(n):\n if i <= mid - 1:\n arr[i] = new_arr[i]\n else:\n arr[i] = new_arr1[count]\n count += 1\n return arr", "def customsort(arr, n):\n if n % 2 == 0:\n mid = n // 2\n else:\n mid = (n - 1) // 2\n first = arr[:mid]\n second = arr[mid:]\n first.sort()\n second.sort(reverse=True)\n lst = first + second\n for i in range(n):\n arr[i] = lst[i]\n return arr", "def customsort(arr, n):\n fh = arr[:n // 2]\n sh = arr[n // 2:]\n fh.sort()\n sh.sort(reverse=True)\n nar = fh + sh\n for i in range(n):\n arr[i] = nar[i]", "def customsort(arr, n):\n x = n // 2\n arr1 = []\n arr2 = []\n for i in range(0, x):\n arr1.append(arr[i])\n for i in range(x, n):\n arr2.append(arr[i])\n arr1.sort()\n arr2.sort(reverse=True)\n for i in arr2:\n arr1.append(i)\n for i in range(n):\n arr[i] = arr1[i]\n return arr", "def customsort(arr, n):\n if n == 1:\n return arr\n mid = int(n / 2)\n arr1 = arr[0:mid]\n arr2 = arr[mid:]\n arr1.sort()\n arr2.sort(reverse=True)\n i = 0\n for i in range(0, len(arr1)):\n arr[i] = arr1[i]\n for j in range(0, len(arr2)):\n i += 1\n arr[i] = arr2[j]\n return arr", "def customsort(arr, n):\n arr1 = arr[:n // 2]\n arr2 = arr[n // 2:]\n arr1.sort()\n arr2.sort(reverse=True)\n x = n // 2\n i = 0\n j = 0\n k = 0\n while i < n:\n if i < x:\n arr[i] = arr1[j]\n j += 1\n else:\n arr[i] = arr2[k]\n k += 1\n i += 1", "def customsort(arr, n):\n li = [0] * (n // 2)\n li2 = [0] * (n - n // 2)\n for i in range(n // 2):\n li[i] = arr[i]\n for i in range(n // 2, n):\n li2[i - n // 2] = arr[i]\n li.sort()\n li2.sort(reverse=True)\n for i in range(n):\n if i < n // 2:\n arr[i] = li[i]\n else:\n arr[i] = li2[i - n // 2]\n return arr", "def customsort(arr, n):\n half1 = arr[:n // 2]\n half2 = arr[n // 2:]\n half1.sort()\n half2.sort(reverse=True)\n s = half1 + half2\n for i in range(len(arr)):\n arr[i] = s[i]", "def customsort(arr, n):\n arrA = arr[:n // 2]\n arrA.sort()\n arrD = arr[n // 2:]\n arrD.sort(reverse=True)\n arr_sorted = arrA + arrD\n for i in range(len(arr)):\n arr[i] = arr_sorted[i]\n return arr", "def customsort(arr, n):\n a1 = arr[:n // 2]\n a2 = arr[n // 2:]\n a1.sort()\n a2.sort(reverse=True)\n a1.extend(a2)\n for i in range(n):\n arr[i] = a1[i]", "def customsort(arr, n):\n first = []\n odd = []\n for i in range(0, n // 2):\n first.append(arr[i])\n for i in range(n // 2, len(arr)):\n odd.append(arr[i])\n first.sort()\n odd.sort(reverse=True)\n for i in odd:\n first.append(i)\n for i in range(len(arr)):\n arr[i] = first[i]\n return arr", "def customsort(arr, n):\n l1 = sorted(arr[0:n // 2])\n l2 = sorted(arr[n // 2:n])\n l1.extend(l2[::-1])\n for i in range(n):\n arr[i] = l1[i]\n return l1", "def customsort(arr, n):\n mid = n // 2\n a1 = arr[:mid]\n a2 = arr[mid:]\n a1.sort()\n a2.sort(reverse=True)\n c = a1 + a2\n for i in range(n):\n arr[i] = c[i]\n return arr", "def customsort(arr, n):\n f = []\n l = []\n for i in range(0, n // 2):\n f.append(arr[i])\n for i in range(n // 2, n):\n l.append(arr[i])\n f.sort()\n l.sort(reverse=True)\n arr.clear()\n for i in f:\n arr.append(i)\n for i in l:\n arr.append(i)", "def customsort(arr, n):\n first = []\n second = []\n index = n // 2\n first = arr[:index]\n first.sort()\n second = arr[index:]\n second.sort()\n second.reverse()\n final = first + second\n for i in range(len(arr)):\n arr[i] = final[i]\n return arr"], "starter_code": "def customsort(arr, n):\n", "input_output": {"inputs": ["n = 4\narr[] = {10, 20, 30, 40}", "n = 9\narr[] = {5, 4, 6, 2, 1, 3, 8, 9, 7}"], "outputs": ["10 20 40 30", "2 4 5 6 9 8 7 3 1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/sort-first-half-in-ascending-and-second-half-in-descending1714/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n*logn)", "entry_point": "customsort", "task_id": "TACO_lite/389", "example": [[[4, [10, 20, 30, 40]], [9, [5, 4, 6, 2, 1, 3, 8, 9, 7]]], [null, null]]} +{"requirement": "```if-not:ruby\nCreate a function, that accepts an arbitrary number of arrays and returns a single array generated by alternately appending elements from the passed in arguments. If one of them is shorter than the others, the result should be padded with empty elements.\n```\n```if:ruby\nCreate a function, that accepts an arbitrary number of arrays and returns a single array generated by alternately appending elements from the passed in arguments. If one of them is shorter than the others, the result should be padded with `nil`s.\n```\n\nExamples:\n\n```python\ninterleave([1, 2, 3], [\"c\", \"d\", \"e\"]) == [1, \"c\", 2, \"d\", 3, \"e\"]\ninterleave([1, 2, 3], [4, 5]) == [1, 4, 2, 5, 3, None]\ninterleave([1, 2, 3], [4, 5, 6], [7, 8, 9]) == [1, 4, 7, 2, 5, 8, 3, 6, 9]\ninterleave([]) == []\n```", "solutions": ["from itertools import chain, zip_longest\n\ndef interleave(*args):\n return list(chain.from_iterable(zip_longest(*args)))", "def interleave(*args):\n max_len = max(map(len, args))\n interleaved = []\n for i in range(max_len):\n for arr in args:\n if i < len(arr):\n interleaved.append(arr[i])\n else:\n interleaved.append(None)\n return interleaved", "from itertools import chain, zip_longest\n\ndef interleave(*args):\n return [*chain(*zip_longest(*args))]", "interleave = lambda *a: [b[i] if len(b) > i else None for i in range(max((len(i) for i in a))) for b in a]", "from itertools import zip_longest\n\ndef interleave(*args):\n return [y for x in zip_longest(*args) for y in x]", "interleave = lambda *a: sum([list(i) for i in __import__('itertools').zip_longest(*a)], [])", "from itertools import zip_longest\n\ndef interleave(*args):\n return [i for _ in zip_longest(*args) for i in _]", "def interleave(*args):\n arr = []\n for i in range(max((len(a) for a in args))):\n for j in range(len(args)):\n try:\n arr.append(args[j][i])\n except:\n arr.append(None)\n return arr", "def interleave(*args):\n n_max = len(max(args, key=len))\n return [j[i] if i < len(j) else None for i in range(n_max) for j in args]"], "starter_code": "def interleave(*args):\n", "input_output": {"fn_name": "interleave", "inputs": [[[1, 2, 3], ["c", "d", "e"]], [[1, 2, 3], [4, 5]], [[1, 2], [3, 4, 5]], [[null], [null, null], [null, null, null]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[]]], "outputs": [[[1, "c", 2, "d", 3, "e"]], [[1, 4, 2, 5, 3, null]], [[1, 3, 2, 4, null, 5]], [[null, null, null, null, null, null, null, null, null]], [[1, 4, 7, 2, 5, 8, 3, 6, 9]], [[]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms"], "name": null, "source": "codewars", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/523d2e964680d1f749000135", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "interleave", "task_id": "TACO_lite/42", "example": [[[[1, 2, 3], ["c", "d", "e"]], [[1, 2, 3], [4, 5]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[]]], ["[1, 'c', 2, 'd', 3, 'e']", "[1, 4, 2, 5, 3, None]", "[1, 4, 7, 2, 5, 8, 3, 6, 9]", "[]"]]} +{"requirement": "Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K.\nExample 1:\nInput:\nN = 4, K = 6\narr[] = {1, 5, 7, 1}\nOutput: 2\nExplanation: \narr[0] + arr[1] = 1 + 5 = 6 \nand arr[1] + arr[3] = 5 + 1 = 6.\nExample 2:\nInput:\nN = 4, K = 2\narr[] = {1, 1, 1, 1}\nOutput: 6\nExplanation: \nEach 1 will produce sum 2 with any 1.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function getPairsCount() which takes arr[], n and k as input parameters and returns the number of pairs that have sum K.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 <= N <= 10^{5}\n1 <= K <= 10^{8}\n1 <= Arr[i] <= 10^{6}", "solutions": ["import math\nfrom collections import Counter\n\ndef getpairscount(arr, n, k):\n mpp = Counter(arr)\n c = 0\n flag = False\n a = list(set(arr))\n for i in range(len(a)):\n x = k - a[i]\n if x in mpp:\n if k - a[i] == a[i]:\n n = mpp[a[i]]\n c += n * (n - 1) // 2\n else:\n c += mpp[a[i]] * mpp[k - a[i]]\n flag = True\n if flag == True:\n return (c + 1) // 2\n return c", "def getpairscount(arr, n, k):\n d = {}\n count = 0\n for i in arr:\n if k - i in d:\n count += d[k - i]\n d[i] = d.get(i, 0) + 1\n return count", "def getpairscount(a, n, k):\n mydict = dict()\n c = 0\n for i in range(0, n):\n temp = k - a[i]\n if temp in mydict:\n val = mydict[temp]\n for j in range(0, val):\n c += 1\n if a[i] not in mydict:\n mydict[a[i]] = 1\n else:\n mydict[a[i]] += 1\n return c", "def getpairscount(arr, n, sum):\n unordered_map = {}\n count = 0\n for i in range(n):\n if sum - arr[i] in unordered_map:\n count += unordered_map[sum - arr[i]]\n if arr[i] in unordered_map:\n unordered_map[arr[i]] += 1\n else:\n unordered_map[arr[i]] = 1\n return count", "def getpairscount(arr, n, k):\n from collections import defaultdict\n dct = defaultdict(int)\n count = 0\n for num in arr:\n count += dct[k - num]\n dct[num] += 1\n return count", "def getpairscount(arr, n, k):\n from collections import Counter\n dct = Counter(arr)\n count = 0\n for num in dct:\n if k - num in dct:\n val = k - num\n if val != num:\n count += dct[num] * dct[val]\n dct[num] = 0\n else:\n repeats = dct[num]\n count += repeats * (repeats - 1) // 2\n return count", "def getpairscount(arr, n, k):\n hashM = {}\n ans = 0\n for i in range(n):\n t = k - arr[i]\n if t in hashM:\n ans += hashM[t]\n if arr[i] not in hashM:\n hashM[arr[i]] = 0\n hashM[arr[i]] += 1\n return ans", "from collections import Counter\n\ndef getpairscount(arr, n, k):\n hm = Counter(arr)\n count = 0\n for n in arr:\n hm[n] -= 1\n if k - n in hm:\n count += hm[k - n]\n return count", "def getpairscount(arr, n, k):\n cnt = 0\n d = {}\n for i in range(n):\n if k - arr[i] in d:\n cnt += d[k - arr[i]]\n if arr[i] in d:\n d[arr[i]] += 1\n else:\n d[arr[i]] = 1\n return cnt", "def getpairscount(arr, n, k):\n dic = dict()\n count = 0\n for i in range(n):\n data = k - arr[i]\n if data in dic:\n count = count + dic[k - arr[i]]\n dic[arr[i]] = dic.get(arr[i], 0) + 1\n return count", "def getpairscount(arr, n, k):\n a = {}\n cnt = 0\n for i in arr:\n b = k - i\n if b in a:\n cnt = cnt + a[b]\n if i in a:\n a[i] = a[i] + 1\n else:\n a[i] = 1\n return cnt", "def getpairscount(arr, n, k):\n freq_map = {}\n count = 0\n for num in arr:\n target = k - num\n if target in freq_map:\n count += freq_map[target]\n freq_map[num] = freq_map.get(num, 0) + 1\n return count", "def getpairscount(arr, n, k):\n (s, d) = (0, {})\n for elem in arr:\n d.update({elem: d.get(elem, 0) + 1})\n for elem in d:\n if elem * 2 == k:\n s += d[elem] * (d[elem] - 1) // 2\n d[elem] = 0\n elif d[elem] and d.get(k - elem, 0):\n s += d[elem] * d.get(k - elem, 0)\n d[elem] = 0\n return s", "def getpairscount(arr, n, k):\n arr.sort()\n mx = max(arr)\n freq = [0] * (mx + 1)\n for elem in arr:\n freq[elem] += 1\n d = {}\n for elem in arr:\n d.update({elem: d.get(elem, 0) + 1})\n s = 0\n s = 0\n for elem in d:\n if elem * 2 == k:\n s += d[elem] * (d[elem] - 1) // 2\n d[elem] = 0\n elif d[elem] and d.get(k - elem, 0):\n s += d[elem] * d.get(k - elem, 0)\n d[elem] = 0\n return s", "def getpairscount(arr, n, k):\n d = dict()\n c = 0\n for i in arr:\n A = k - i\n if A in d:\n c = c + d[A]\n if i in d:\n d[i] = d[i] + 1\n else:\n d[i] = 1\n return c", "def getpairscount(arr, n, sum):\n m = dict()\n for i in range(n):\n if arr[i] in m.keys():\n m[arr[i]] += 1\n else:\n m[arr[i]] = 1\n twice_count = 0\n for i in range(0, n):\n if sum - arr[i] in m.keys():\n twice_count += m[sum - arr[i]]\n if sum - arr[i] == arr[i]:\n twice_count -= 1\n return int(twice_count / 2)", "def getpairscount(arr, n, k):\n count = 0\n hash = {}\n for i in range(n):\n if k - arr[i] in hash:\n count += hash[k - arr[i]]\n if arr[i] in hash:\n hash[arr[i]] += 1\n else:\n hash[arr[i]] = 1\n return count", "def getpairscount(arr, n, k):\n ct = 0\n freq = {}\n for i in range(0, n):\n if k - arr[i] in freq:\n ct += freq[k - arr[i]]\n freq[arr[i]] = 1 + freq.get(arr[i], 0)\n return ct", "def getpairscount(arr, n, k):\n hashmap = {}\n for i in arr:\n hashmap[i] = hashmap.get(i, 0) + 1\n count = 0\n for i in arr:\n b = k - i\n a = i\n if b in hashmap:\n count += hashmap[b]\n if b == a:\n count -= 1\n return count // 2", "from collections import defaultdict\n\ndef getpairscount(arr, n, k):\n d = defaultdict(int)\n ans = 0\n for a in arr:\n ans += d[k - a]\n d[a] += 1\n return ans", "def getpairscount(arr, n, k):\n from collections import Counter\n m = Counter()\n ans = 0\n for i in arr:\n if m[k - i]:\n ans += m[k - i]\n m[i] += 1\n return ans", "def getpairscount(arr, n, k):\n dict1 = {}\n c = 0\n for i in range(n):\n target = k - arr[i]\n if target in dict1:\n c += dict1[target]\n if arr[i] in dict1:\n dict1[arr[i]] += 1\n else:\n dict1[arr[i]] = 1\n return c", "def getpairscount(arr, n, k):\n pair_count = 0\n compliment_count_map = {}\n for num in arr:\n compliment = k - num\n if compliment in compliment_count_map:\n pair_count += compliment_count_map[compliment]\n if num in compliment_count_map:\n compliment_count_map[num] = compliment_count_map[num] + 1\n else:\n compliment_count_map[num] = 1\n return pair_count", "def getpairscount(arr, n, k):\n index = dict()\n pair = 0\n for i in range(n):\n if k > arr[i]:\n c = k - arr[i]\n if index.get(c) != None:\n pair = pair + index.get(c)\n index[arr[i]] = index.get(arr[i], 0) + 1\n return pair", "from collections import Counter\n\ndef getpairscount(arr, n, k):\n c = Counter(arr)\n ans = 0\n for num in arr:\n if k - num in c:\n ans += c[k - num]\n if k - num == num:\n ans -= 1\n return int(ans / 2)", "def getpairscount(arr, n, k):\n count = 0\n data = {}\n for i in arr:\n stored_data = data.get(k - i, 0)\n count += stored_data\n data[i] = data.get(i, 0) + 1\n return count", "def getpairscount(arr, n, k):\n hashm = {}\n cnt = 0\n for i in range(len(arr)):\n if arr[i] not in hashm:\n hashm[arr[i]] = 1\n else:\n hashm[arr[i]] += 1\n for i in range(len(arr)):\n elem = k - arr[i]\n if elem in hashm:\n cnt += hashm[elem]\n if elem == arr[i]:\n cnt -= 1\n return cnt // 2", "def getpairscount(arr, n, k):\n freq = {}\n pairs = 0\n for num in arr:\n if num in freq:\n freq[num] += 1\n else:\n freq[num] = 1\n for num in arr:\n complement = k - num\n if complement in freq:\n pairs += freq[complement]\n if num == complement:\n pairs -= 1\n return pairs // 2", "def getpairscount(arr, n, k):\n hashmap = {}\n pairs = 0\n for val in arr:\n if val in hashmap:\n hashmap[val] += 1\n else:\n hashmap[val] = 1\n for val in arr:\n if k - val in hashmap:\n pairs += hashmap[k - val]\n if val == k - val:\n pairs -= 1\n return int(pairs / 2)", "def getpairscount(arr, n, k):\n dist = {}\n pairs = 0\n for i in arr:\n if k - i in dist:\n pairs += dist[k - i]\n if i in dist:\n dist[i] += 1\n else:\n dist[i] = 1\n return pairs", "def getpairscount(arr, n, k):\n freq = dict()\n used_numbers = dict()\n ans = 0\n for i in range(0, n):\n if arr[i] in freq:\n freq[arr[i]] += 1\n else:\n freq[arr[i]] = 1\n for i in range(0, n):\n if arr[i] not in used_numbers:\n pair_two = k - arr[i]\n if pair_two == arr[i]:\n ans += freq[arr[i]] * (freq[arr[i]] - 1) // 2\n used_numbers[arr[i]] = 1\n continue\n if pair_two in freq:\n ans += freq[arr[i]] * freq[pair_two]\n used_numbers[pair_two] = 1\n used_numbers[arr[i]] = 1\n return ans", "def getpairscount(arr, n, k):\n dic_val = dict()\n pair = 0\n for i in range(len(arr)):\n if arr[i] >= k:\n continue\n pp = k - arr[i]\n if pp in dic_val:\n pair = pair + dic_val[pp]\n if arr[i] in dic_val:\n dic_val[arr[i]] = 1 + dic_val[arr[i]]\n else:\n dic_val[arr[i]] = 1\n elif arr[i] in dic_val:\n dic_val[arr[i]] = 1 + dic_val[arr[i]]\n else:\n dic_val[arr[i]] = 1\n return pair", "def getpairscount(arr, n, k):\n (dict, ans) = ({}, 0)\n for el in arr:\n if k - el in dict:\n ans += dict[k - el]\n if not el in dict:\n dict[el] = 1\n else:\n dict[el] += 1\n return ans", "import sys\n\ndef getpairscount(arr, n, k):\n a = {}\n sum = 0\n for i in range(len(arr)):\n if arr[i] not in a:\n a[arr[i]] = 0\n a[arr[i]] += 1\n for i in range(len(arr)):\n if k - arr[i] in a:\n sum = sum + a[k - arr[i]]\n if k - arr[i] == arr[i]:\n sum -= 1\n return int(sum / 2)", "def getpairscount(arr, n, k):\n freq = {}\n count = 0\n for i in range(len(arr)):\n if arr[i] not in freq:\n freq[arr[i]] = 0\n freq[arr[i]] += 1\n for i in range(len(arr)):\n complement = k - arr[i]\n if complement in freq:\n count += freq[complement]\n if complement == arr[i]:\n count -= 1\n return count // 2", "def getpairscount(arr, n, k):\n dict = {}\n pairs = 0\n arr = sorted(arr)\n for val in arr:\n if val in dict:\n dict[val] += 1\n else:\n dict[val] = 1\n for i in range(n):\n if k - arr[i] in dict:\n pairs += dict[k - arr[i]]\n if k - arr[i] == arr[i]:\n pairs -= 1\n return int(pairs / 2)", "def getpairscount(arr, n, k):\n d = {}\n count = 0\n for (i, e) in enumerate(arr):\n if k - e in d:\n count += d[k - e]\n if e in d:\n d[e] += 1\n else:\n d[e] = 1\n return count", "def getpairscount(arr, n, t):\n dic = {}\n for i in range(len(arr)):\n dic[arr[i]] = dic.get(arr[i], 0) + 1\n count = 0\n for (k, v) in dic.items():\n if t - k in dic:\n if k != t - k:\n count += v * dic[t - k]\n else:\n count += v * (v - 1)\n return count // 2", "from collections import defaultdict\n\ndef getpairscount(arr, n, k):\n visited = defaultdict(int)\n count = 0\n for x in arr:\n try:\n count += visited[k - x]\n except:\n pass\n visited[x] += 1\n return count", "def getpairscount(arr, n, k):\n mp = dict()\n c = 0\n for i in range(n):\n target = k - arr[i]\n if target in mp:\n c = c + mp[k - arr[i]]\n mp[arr[i]] = mp.get(arr[i], 0) + 1\n return c", "def getpairscount(arr, n, k):\n c = 0\n d = {}\n for a in arr:\n if k - a in d:\n c += d[k - a]\n if a in d:\n d[a] += 1\n else:\n d[a] = 1\n return c", "def getpairscount(arr, n, k):\n c = 0\n d = {}\n for (i, a) in enumerate(arr):\n if a in d:\n d[a].append(i)\n else:\n d[a] = [i]\n for (i, a) in enumerate(arr):\n if k - a in d:\n for j in d[k - a]:\n if j > i:\n c += 1\n return c", "def getpairscount(arr, n, k):\n x = {}\n ans = 0\n for i in arr:\n num = k - i\n if num in x:\n ans += x[num]\n try:\n x[i] += 1\n except:\n x[i] = 1\n return ans", "from collections import defaultdict\n\ndef getpairscount(arr, n, k):\n val_map = defaultdict(int)\n cnt = 0\n for num in arr:\n if val_map.get(k - num):\n cnt += val_map[k - num]\n val_map[num] += 1\n return cnt", "def getpairscount(arr, n, k):\n arr.sort()\n result = []\n i = 0\n j = n - 1\n while i < j:\n if arr[i] + arr[j] < k:\n i += 1\n elif arr[i] + arr[j] > k:\n j -= 1\n elif arr[i] != arr[j]:\n c1 = 0\n temp1 = arr[i]\n while arr[i] == temp1:\n i += 1\n c1 += 1\n c2 = 0\n temp2 = arr[j]\n while arr[j] == temp2:\n j -= 1\n c2 += 1\n for _ in range(0, c1 * c2):\n result.append((temp1, temp2))\n else:\n c3 = 0\n while arr[j] == arr[i]:\n j -= 1\n c3 += 1\n for _ in range(0, c3 * (c3 - 1) // 2):\n result.append((arr[i], arr[i]))\n return len(result)", "def getpairscount(arr, n, k):\n freq_map = {}\n for i in range(n):\n if arr[i] not in freq_map.keys():\n freq_map[arr[i]] = 1\n else:\n freq_map[arr[i]] += 1\n count = 0\n for i in range(n):\n diff = k - arr[i]\n if diff in freq_map.keys():\n count = count + freq_map[diff]\n if diff == arr[i]:\n count -= 1\n count = count // 2\n return count", "def getpairscount(arr, n, k):\n d = {}\n c = 0\n for i in arr:\n m = k - i\n if m in d:\n c += d[m]\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n return c", "def getpairscount(arr, n, k):\n s = dict()\n cnt = 0\n for i in range(n):\n temp = k - arr[i]\n if temp in s:\n cnt += s[temp]\n if arr[i] in s:\n s[arr[i]] += 1\n else:\n s[arr[i]] = 1\n return cnt", "from collections import defaultdict\n\ndef getpairscount(arr, n, k):\n (seen, count) = ({}, 0)\n for i in range(n):\n if k - arr[i] in seen:\n count += seen[k - arr[i]]\n seen[arr[i]] = seen.get(arr[i], 0) + 1\n return count\n\n def sum(i, arr, t):\n if t == 0:\n return 1\n if i == 0:\n if arr[0] == t:\n return 1\n return 0\n x = sum(i - 1, arr, t)\n y = 0\n if arr[i] <= t:\n y = sum(i - 1, arr, t - arr[i])\n return x + y\n return sum(n - 1, arr, k)", "def getpairscount(arr, n, k):\n m = {}\n ans = 0\n for i in range(n):\n if k - arr[i] in m:\n ans += m[k - arr[i]]\n m[arr[i]] = m.get(arr[i], 0) + 1\n return ans", "def getpairscount(arr, n, k):\n freq_dict = {}\n pair_count = 0\n for i in range(n):\n if k - arr[i] in freq_dict:\n pair_count += freq_dict[k - arr[i]]\n if arr[i] in freq_dict:\n freq_dict[arr[i]] += 1\n else:\n freq_dict[arr[i]] = 1\n return pair_count"], "starter_code": "def getpairscount(arr, n, k):\n", "input_output": {"inputs": ["N = 4, K = 6\r\narr[] = {1, 5, 7, 1}", "N = 4, K = 2\r\narr[] = {1, 1, 1, 1}"], "outputs": ["2", "6"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays", "Hash"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "getpairscount", "task_id": "TACO_lite/348", "example": [[[4, 6, [1, 5, 7, 1]], [4, 2, [1, 1, 1, 1]]], [null, null]]} +{"requirement": "You are given a string representing an attendance record for a student. The record only contains the following three characters:\n\n\n\n'A' : Absent. \n'L' : Late.\n 'P' : Present. \n\n\n\n\nA student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). \n\nYou need to return whether the student could be rewarded according to his attendance record.\n\nExample 1:\n\nInput: \"PPALLP\"\nOutput: True\n\n\n\nExample 2:\n\nInput: \"PPALLL\"\nOutput: False", "solutions": ["def checkrecord(s):\n count = 0\n for i in range(0, len(s)):\n if s[i] == 'A':\n count += 1\n if count == 2:\n return False\n elif i >= 2 and s[i] == 'L' and (s[max(i - 1, 0)] == 'L') and (s[max(i - 2, 0)] == 'L'):\n return False\n return True", "def checkrecord(s):\n twoL = 0\n twoA = 0\n i = 0\n while i < len(s):\n if s[i] == 'A':\n twoA += 1\n if twoA > 1:\n return False\n twoL = 0\n elif s[i] == 'L':\n twoL += 1\n if twoL > 2:\n return False\n else:\n twoL = 0\n i += 1\n return True", "def checkrecord(s):\n if not s:\n return\n c = 0\n if s == 'AA':\n return False\n for i in range(len(s) - 2):\n if s[i] == 'L':\n if s[i] == s[i + 1] and s[i] == s[i + 2]:\n return False\n if s[i] == 'A':\n c += 1\n if c == 2:\n return False\n return True", "def checkrecord(s):\n return s.count('A') <= 1 and s.count('LLL') == 0", "def checkrecord(s):\n aCount = 0\n clCount = 0\n for r in s:\n if r == 'A':\n aCount += 1\n if aCount > 1:\n return False\n if r == 'L':\n clCount += 1\n if clCount > 2:\n return False\n else:\n clCount = 0\n return True", "def checkrecord(s):\n return s.count('A') < 2 and 'LLL' not in s", "def checkrecord(s):\n from collections import Counter\n val = Counter(s)\n idx = []\n for i in range(len(s)):\n if s[i] == 'L':\n idx.append(i)\n for j in range(len(idx) - 2):\n if idx[j + 2] - idx[j] == 2:\n return False\n if val['A'] > 1:\n return False\n return True", "def checkrecord(s):\n charA = charL = 0\n for c in s:\n if c == 'A':\n charA += 1\n if charA > 1:\n return False\n charL = 0\n elif c == 'L':\n charL += 1\n if charL > 2:\n return False\n else:\n charL = 0\n return True", "def checkrecord(s):\n mydir = {}\n for record in s:\n mydir[record] = mydir.get(record, 0) + 1\n return mydir.get('A', 0) <= 1 and s.count('LLL') == 0"], "starter_code": "def checkrecord(s: str) -> bool:\n", "input_output": {"fn_name": "checkRecord", "inputs": [["\"PPALLP\""]], "outputs": [true]}, "difficulty": "EASY", "raw_tags": ["String"], "name": null, "source": "leetcode", "tags": ["String algorithms"], "skill_types": [], "url": "https://leetcode.com/problems/student-attendance-record-i/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "checkrecord", "task_id": "TACO_lite/340", "example": [[["PPALLP"], ["PPALLL"]], ["True", "False"]]} +{"requirement": "We are given the head node root\u00a0of a binary tree, where additionally every node's value is either a 0 or a 1.\nReturn the same tree where every subtree (of the given tree) not containing a 1 has been removed.\n(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)\nExample 1:\nInput: [1,null,0,0,1]\nOutput: [1,null,0,null,1]\n \nExplanation: \nOnly the red nodes satisfy the property \"every subtree not containing a 1\".\nThe diagram on the right represents the answer.\n\n\n\nExample 2:\nInput: [1,0,1,0,0,0,1]\nOutput: [1,null,1,null,1]\n\n\n\n\nExample 3:\nInput: [1,1,0,1,1,0,1,0]\nOutput: [1,1,0,1,1,null,1]\n\n\n\n\nNote: \n\nThe binary tree\u00a0will\u00a0have\u00a0at\u00a0most 200 nodes.\nThe value of each node will only be 0 or 1.", "solutions": ["def pruneTreeHelper(root: TreeNode) -> TreeNode:\n if not root:\n return None\n left = self.pruneTreeHelper(root.left)\n right = self.pruneTreeHelper(root.right)\n if not left:\n root.left = None\n if not right:\n root.right = None\n if root.val == 0 and root.right is None and (root.left is None):\n return None\n else:\n return root\n\ndef pruneTree(root: TreeNode) -> TreeNode:\n return self.pruneTreeHelper(root)", "def pruneTree(root: TreeNode) -> TreeNode:\n if not root:\n return None\n root.left = self.pruneTree(root.left)\n root.right = self.pruneTree(root.right)\n if not root.left and (not root.right) and (root.val == 0):\n return None\n return root", "def pruneTree(root: TreeNode) -> TreeNode:\n\n def prune(node: TreeNode) -> bool:\n if not node:\n return True\n left_prune = prune(node.left)\n right_prune = prune(node.right)\n if prune(node.left):\n node.left = None\n if prune(node.right):\n node.right = None\n return node.val == 0 and left_prune and right_prune\n if prune(root):\n return None\n return root", "def pruneTree(root: TreeNode) -> TreeNode:\n\n def check(node):\n if not node.left:\n l = True\n else:\n l = check(node.left)\n if not node.right:\n r = True\n else:\n r = check(node.right)\n if l:\n node.left = None\n if r:\n node.right = None\n return l and r and (node.val == 0)\n ans = TreeNode()\n ans.right = root\n check(ans)\n return ans.right", "def pruneTree(root: TreeNode) -> TreeNode:\n\n def dfs(node):\n if not node:\n return False\n a1 = dfs(node.left)\n a2 = dfs(node.right)\n if not a1:\n node.left = None\n if not a2:\n node.right = None\n return node.val == 1 or a1 or a2\n return root if dfs(root) else None", "def pruneTree(root: TreeNode) -> TreeNode:\n\n def prune_tree_helper(root):\n if root:\n curr_res = True if root.val == 0 else False\n left_res = prune_tree_helper(root.left)\n right_res = prune_tree_helper(root.right)\n if left_res:\n root.left = None\n if right_res:\n root.right = None\n return curr_res and left_res and right_res\n else:\n return True\n res = prune_tree_helper(root)\n if res:\n return None\n else:\n return root", "def pruneTree(root: TreeNode) -> TreeNode:\n return root if self.dfs(root) else None\n\ndef dfs(root):\n if not root:\n return False\n l = self.dfs(root.left)\n r = self.dfs(root.right)\n if not l:\n root.left = None\n if not r:\n root.right = None\n return root.val == 1 or l or r", "def pruneTree(root: TreeNode) -> TreeNode:\n\n def helper(root):\n if not root:\n return False\n lone = helper(root.left)\n rone = helper(root.right)\n if not lone:\n root.left = None\n if not rone:\n root.right = None\n if root.val == 1 or lone or rone:\n return True\n else:\n return False\n if helper(root):\n return root\n else:\n return None", "def pruneTree(root: TreeNode) -> TreeNode:\n if root == None:\n return None\n left_sub = self.pruneTree(root.left)\n right_sub = self.pruneTree(root.right)\n if root.val == 0 and left_sub == None and (right_sub == None):\n return None\n root.left = left_sub\n root.right = right_sub\n return root"], "starter_code": "def __init__(val=0, left=None, right=None):\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Binary Tree", "Tree", "Depth-First Search"], "name": null, "source": "leetcode", "tags": ["Tree algorithms", "Graph traversal"], "skill_types": [], "url": "https://leetcode.com/problems/binary-tree-pruning/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "__init__", "task_id": "TACO_lite/370", "example": [[], []]} +{"requirement": "Given a string S, remove all consonants and print the modified string that contains vowels only.\nExample 1:\nInput\nS = \"abEkipo\"\nOutput\naEio\nExplanation : a, E, i, o are only vowels in the string.\nExample 2:\nInput\nS = \"rrty\"\nOutput\nNo Vowel\nExplanation: There are no vowels.\nYour Task: You don't need to read input or print anything.Your task is to complete the function removeConsonants() which takes a string as input parameters, and returns the modified string that contains vowels only. If there is no vowel present in the string S, then return \"No Vowel\".\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1).\nConstraints\n1 <= |S| <= 10^{5}\nThe string should consist of only alphabets.", "solutions": ["def removeconsonants(s):\n p = ''\n a = 0\n for i in s:\n if i in ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']:\n p += i\n a = a + 1\n if a == 0:\n return 'No Vowel'\n else:\n return p", "def removeconsonants(s):\n str1 = ''\n n = 'No Vowel'\n for i in range(len(s)):\n if s[i] == 'A' or s[i] == 'a':\n str1 = str1 + s[i]\n elif s[i] == 'E' or s[i] == 'e':\n str1 = str1 + s[i]\n elif s[i] == 'I' or s[i] == 'i':\n str1 = str1 + s[i]\n elif s[i] == 'O' or s[i] == 'o':\n str1 = str1 + s[i]\n elif s[i] == 'U' or s[i] == 'u':\n str1 = str1 + s[i]\n else:\n str1 = str1 + ''\n if len(str1) > 0:\n return str1\n else:\n return n", "def removeconsonants(s):\n k = ''\n for i in s:\n if i in 'aeiouAEIOU':\n k += i\n if len(k) == 0:\n return 'No Vowel'\n return k", "def removeconsonants(s):\n vowels = 'aeiouAEIOU'\n c = []\n for i in s:\n if i in vowels:\n c.append(i)\n if len(c) == 0:\n return 'No Vowel'\n else:\n c = ''.join(c)\n return c", "def removeconsonants(s):\n vowels = 'AaEeIiOoUu'\n i = 0\n while i < len(s):\n if s[i] not in vowels:\n s = s.replace(s[i], '')\n if len(s) <= 0:\n return 'No Vowel'\n else:\n i += 1\n if len(s) <= 0:\n return 'No Vowel'\n return s", "def removeconsonants(s):\n vowel = []\n cons = ''\n source = 'aeiouAEIOU'\n for i in s:\n if i in source:\n vowel.append(i)\n return ''.join(vowel) if vowel else 'No Vowel'", "def removeconsonants(s):\n ans = ''\n vovel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n for i in s:\n if i in vovel:\n ans += i\n if len(ans) == 0:\n return 'No Vowel'\n else:\n return ans", "def removeconsonants(s):\n v = ''\n for i in s:\n if i in 'aeiouAEIOU':\n v += i\n if v == '':\n return 'No Vowel'\n else:\n return v", "def removeconsonants(s):\n l1 = []\n for i in s:\n j = i.lower()\n if j in {'a', 'e', 'i', 'o', 'u'}:\n l1.append(i)\n if l1 == []:\n return 'No Vowel'\n else:\n return ''.join(l1)", "def removeconsonants(s):\n result = ''\n for i in range(len(s)):\n if s[i] in ('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'):\n result += s[i]\n if len(result) != 0:\n return result\n return 'No Vowel'", "def removeconsonants(s):\n l = []\n for i in s:\n if i == 'A' or i == 'E' or i == 'I' or (i == 'O') or (i == 'U') or (i == 'a') or (i == 'e') or (i == 'i') or (i == 'o') or (i == 'u'):\n l.append(i)\n s1 = ''.join(map(str, l))\n if len(s1) == 0:\n return 'No Vowel'\n else:\n return s1", "def removeconsonants(s):\n d = [i for i in s if i in 'aeiouAEIOU']\n return ''.join(d) if len(d) > 0 else 'No Vowel'", "def removeconsonants(s):\n l = []\n v = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'O', 'I', 'U']\n for i in s:\n if i in v:\n l.append(i)\n if len(l) == 0:\n return 'No Vowel'\n else:\n r = ''.join(l)\n return r", "def removeconsonants(s):\n x = ''\n a = 'aeiou'\n b = a.upper()\n for i in s:\n if i in a or i in b:\n x += i\n if x == '':\n return 'No Vowel'\n else:\n return x", "def removeconsonants(s):\n s1 = ''\n for i in s:\n if i in 'aeiouAEIOU':\n s1 += i\n if s1 == '':\n return 'No Vowel'\n return s1", "def removeconsonants(s):\n res = []\n for i in range(len(s)):\n if s[i] in 'aeiouAEIOU':\n res.extend(s[i])\n if len(res) > 0:\n return ''.join(res)\n else:\n return 'No Vowel'", "def removeconsonants(s):\n a = ''\n for i in s:\n if i.lower() in 'aeiou':\n a += i\n return a if a else 'No Vowel'", "def isvowel(c):\n return c == 'a' or c == 'e' or c == 'i' or (c == 'o') or (c == 'u') or (c == 'A') or (c == 'E') or (c == 'I') or (c == 'O') or (c == 'U')\n\ndef removeconsonants(s):\n x = ''\n for i in s:\n if self.isvowel(i):\n x += i\n if len(x) == 0:\n return 'No Vowel'\n return x", "def removeconsonants(s):\n x = ''\n lst = ['a', 'e', 'i', 'o', 'u']\n for i in s:\n if i.lower() in lst:\n x += i\n if len(x) == 0:\n return 'No Vowel'\n return x", "def removeconsonants(s):\n k = 'aeiouAEIOU'\n st = ''\n for i in range(len(s)):\n if s[i] in k:\n st = st + s[i]\n if st == '':\n return 'No Vowel'\n else:\n return st", "def removeconsonants(s):\n d = ''\n for i in s:\n l = i.lower()\n if l == 'a' or l == 'e' or l == 'i' or (l == 'u') or (l == 'o'):\n d += i\n if len(d) == 0:\n return 'No Vowel'\n else:\n return d", "def removeconsonants(s):\n consonants = set(['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z'])\n without_cons = [char for char in s if char not in consonants]\n if all((char in consonants for char in s)):\n return 'No Vowel'\n return ''.join(without_cons)", "def removeconsonants(s):\n ch = ''\n for i in s:\n if i in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'U', 'O', 'I']:\n ch = ch + i\n if ch:\n return ch\n return 'No Vowel'", "def removeconsonants(s):\n vowels = ['a', 'e', 'i', 'o', 'u']\n ans = ''\n for i in s:\n if i.lower() in vowels:\n ans += i\n if ans == '':\n return 'No Vowel'\n return ans", "def removeconsonants(s):\n v = 'aeiouAEIOU'\n outStr = ''\n for i in s:\n if i in v:\n outStr += i\n if len(outStr) == 0:\n return 'No Vowel'\n else:\n return outStr", "def removeconsonants(s):\n a = list(s)\n count = 0\n length = len(a)\n vowels = ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']\n v = []\n for i in range(len(a)):\n if a[i] in vowels:\n v.append(a[i])\n flag = 1\n elif a[i] not in vowels:\n count += 1\n w = ''\n for j in range(len(v)):\n w += v[j]\n if count == length:\n return 'No Vowel'\n else:\n return w", "def removeconsonants(s):\n vowel = 'aeiouAEIOU'\n a = ''\n for i in s:\n if i in vowel:\n a += i\n if len(a) == 0:\n return 'No Vowel'\n return a", "def removeconsonants(s):\n str = ''\n R = 'No Vowel'\n vowels_of_list = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']\n for index in s:\n if index in vowels_of_list:\n str += index\n if len(str) == 0:\n return R\n else:\n return str", "def removeconsonants(s):\n s1 = ''\n for ele in s:\n if ele == 'a' or ele == 'e' or ele == 'i' or (ele == 'o') or (ele == 'u') or (ele == 'A') or (ele == 'E') or (ele == 'I') or (ele == 'O') or (ele == 'U'):\n s1 += ele\n if len(s1) == 0:\n return 'No Vowel'\n else:\n return s1", "def removeconsonants(s):\n str2 = ''\n for i in range(len(s)):\n if s[i] in 'aeiouAEIOU':\n str2 += s[i]\n if len(str2) == 0:\n return 'No Vowel'\n else:\n return str2", "def removeconsonants(s):\n vowels = 'aeiouAEIOU'\n ans = ''\n for i in s:\n if i in vowels:\n ans += i\n if ans == '':\n return 'No Vowel'\n return ans", "def removeconsonants(s):\n vov = 'aeiouAEIOU'\n new = ''\n for i in s:\n if i in vov:\n new += i\n if len(new) == 0:\n return 'No Vowel'\n else:\n return new", "def removeconsonants(s):\n k = ''\n vow = ['a', 'e', 'i', 'o', 'u']\n for i in s:\n r = i.lower()\n if r in vow:\n k += i\n if k == '':\n return 'No Vowel'\n return k", "def removeconsonants(s):\n a = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n i = 0\n s1 = ''\n while i < len(s):\n if s[i] in a:\n s1 += s[i]\n i += 1\n return s1 if len(s1) != 0 else 'No Vowel'", "def removeconsonants(s):\n li = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n str = ''\n for i in s:\n if i in li:\n str += i\n if str == '':\n return 'No Vowel'\n else:\n return str", "def removeconsonants(s):\n vovel = 'aeiouAEIOU'\n result = ''\n for i in s:\n if i in vovel:\n result += i\n if len(result) > 0:\n return result\n else:\n return 'No Vowel'", "def removeconsonants(s):\n list1 = []\n for i in s:\n if i == 'a' or i == 'e' or i == 'i' or (i == 'o') or (i == 'u') or (i == 'A') or (i == 'E') or (i == 'I') or (i == 'O') or (i == 'U'):\n list1.append(i)\n if len(list1) > 0:\n return ''.join(list1)\n else:\n return 'No Vowel'", "def removeconsonants(s):\n st = ''\n for i in s:\n if i.lower() in ['a', 'e', 'i', 'o', 'u']:\n st += i\n if st == '':\n return 'No Vowel'\n else:\n return st", "def removeconsonants(s):\n b = ['A', 'E', 'I', 'O', 'U']\n ans = ''\n for i in s:\n if i.upper() in b:\n ans += i\n if len(ans) == 0:\n return 'No Vowel'\n return ans", "def removeconsonants(s):\n temp = ''\n for i in s:\n if i in 'AEIOU' or i in 'aeiou':\n temp += i\n if len(temp) > 0:\n return temp\n else:\n return 'No Vowel'", "def removeconsonants(s):\n vowels = 'aeoui'\n vowels += vowels.upper()\n res = ''\n for i in s:\n if i in vowels:\n res += i\n if len(res) > 0:\n return res\n return 'No Vowel'", "def removeconsonants(s):\n a = []\n for i in s:\n if i in 'aeiouAEIOU':\n a.append(i)\n m = ''.join(a)\n if len(m) == 0:\n return 'No Vowel'\n else:\n return m", "def removeconsonants(s):\n l = ''\n k = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n a = list(s)\n for i in range(len(a)):\n if a[i] in k:\n l += a[i]\n else:\n continue\n if len(l) >= 1:\n return l\n else:\n return 'No Vowel'", "def removeconsonants(s):\n v = 'aeiouAEIOU'\n a = ''\n for i in s:\n if i in v:\n a += i\n if len(a) >= 1:\n return a\n return 'No Vowel'", "def removeconsonants(s):\n vowels = 'aeiou'\n v = ''\n for i in s:\n temp = i.lower()\n if temp in vowels:\n v += i\n if len(v) < 1:\n return 'No Vowel'\n else:\n return v", "import re\n\ndef removeconsonants(s):\n pat = re.findall('[aeiouAEIOU]+', s)\n if pat:\n return ''.join(pat)\n return 'No Vowel'", "def removeconsonants(s):\n j = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n c = []\n for i in s:\n if i in j:\n c.append(i)\n return ''.join(c) or 'No Vowel'", "def removeconsonants(s):\n x = 'aeiouAEIOU'\n ans = ''\n for i in s:\n if i in x:\n ans += i\n return ans if len(ans) != 0 else 'No Vowel'", "def removeconsonants(s):\n vowel_list = ['a', 'e', 'i', 'o', 'u']\n response_str = ''\n for char in s:\n if char.lower() in vowel_list:\n response_str = response_str + char\n if response_str:\n return response_str\n else:\n return 'No Vowel'", "def removeconsonants(s):\n v = 'aeiouAEIOU'\n newstring = ''\n for i in s:\n if i in v:\n newstring += i\n if len(newstring):\n return newstring\n return 'No Vowel'", "def removeconsonants(s):\n temp = 'aeiouEIOUA'\n ans = ''\n for i in s:\n if i in temp:\n ans = ans + i\n if len(ans) == 0:\n return 'No Vowel'\n return ans", "def removeconsonants(s):\n d = ''\n a = 'AEIOUaeiou'\n for i in s:\n if i in a:\n d = d + i\n if len(d) == 0:\n return 'No Vowel'\n else:\n return d", "def removeconsonants(s):\n if 'a' not in s and 'e' not in s and ('i' not in s) and ('o' not in s) and ('u' not in s) and ('A' not in s) and ('E' not in s) and ('I' not in s) and ('O' not in s) and ('U' not in s):\n return 'No Vowel'\n ans = ''\n for i in s:\n if i == 'a' or i == 'e' or i == 'i' or (i == 'o') or (i == 'u') or (i == 'A') or (i == 'E') or (i == 'I') or (i == 'O') or (i == 'U'):\n ans += i\n return ans", "def removeconsonants(S):\n consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'\n new_str = ''\n for i in range(len(S)):\n if S[i] not in consonants:\n new_str += S[i]\n if len(new_str) == 0:\n return 'No Vowel'\n else:\n return new_str", "def removeconsonants(s):\n c = ''\n v = 'aeiouAEIOU'\n l = list(s)\n for i in l:\n if i in v:\n c += i\n if len(c) > 0:\n return c\n else:\n return 'No Vowel'", "def removeconsonants(s):\n new = ''\n vow = 'aeiou'\n for i in s:\n if i.lower() in vow:\n new += i\n if new:\n return new\n else:\n return 'No Vowel'", "def removeconsonants(s):\n x = 'aeiouAEIOU'\n y = ''\n for i in range(len(s)):\n if s[i] in x:\n y = y + s[i]\n if y == '':\n return 'No Vowel'\n else:\n return y", "def removeconsonants(s):\n st = ''\n for i in range(len(s)):\n if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or (s[i] == 'o') or (s[i] == 'u') or (s[i] == 'A') or (s[i] == 'E') or (s[i] == 'I') or (s[i] == 'O') or (s[i] == 'U'):\n st += s[i]\n if st == '':\n return 'No Vowel'\n else:\n return st", "def removeconsonants(s):\n vowels = 'aeiouAEIOU'\n str = ''\n for x in s:\n if x in vowels:\n str += x\n if str == '':\n return 'No Vowel'\n else:\n return str", "def removeconsonants(s):\n k = ''\n m = 'No Vowel'\n x = ['a', 'A', 'e', 'E', 'i', 'I', 'O', 'o', 'U', 'u']\n for i in s:\n if i in x:\n k = k + i\n if len(k) != 0:\n return k\n else:\n return m", "def removeconsonants(s):\n str2 = ''\n vovels = 'aeiouAEIOU'\n for i in s:\n if i in vovels:\n str2 += i\n if len(str2) < 1:\n return 'No Vowel'\n else:\n return str2", "def removeconsonants(s):\n vowels = 'aeiouAEIOU'\n new_string = ''\n for i in s:\n if i in vowels:\n new_string += i\n if len(new_string) > 0:\n return new_string\n else:\n return 'No Vowel'"], "starter_code": "def removeconsonants(s):\n", "input_output": {"inputs": ["S = \"abEkipo\"", "S = \"rrty\""], "outputs": ["aEio", "No Vowel"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Searching", "Algorithms"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/c-program-to-remove-consonants-from-a-string1945/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|).", "entry_point": "removeconsonants", "task_id": "TACO_lite/419", "example": [[], []]} +{"requirement": "Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.\n\u00a0\nExample 1:\nInput: s = \"eleetminicoworoep\"\nOutput: 13\nExplanation: The longest substring is \"leetminicowor\" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.\n\nExample 2:\nInput: s = \"leetcodeisgreat\"\nOutput: 5\nExplanation: The longest substring is \"leetc\" which contains two e's.\n\nExample 3:\nInput: s = \"bcbcbc\"\nOutput: 6\nExplanation: In this case, the given string \"bcbcbc\" is the longest because all vowels: a, e, i, o and u appear zero times.\n\n\u00a0\nConstraints:\n\n1 <= s.length <= 5 x 10^5\ns\u00a0contains only lowercase English letters.", "solutions": ["def findthelongestsubstring(s: str) -> int:\n s = s + 'a'\n (bits, dp) = ({'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}, {0: -1})\n res = 0\n key = 0\n for (i, char) in enumerate(s):\n if char in bits:\n if key in dp:\n res = max(res, i - dp[key] - 1)\n key = key ^ 1 << bits[char]\n if key not in dp:\n dp[key] = i\n return res", "def findthelongestsubstring(s: str) -> int:\n for i in range(len(s), 0, -1):\n for j in range(len(s) - i + 1):\n sub = s[j:j + i]\n has_odd_vowel = False\n for vowel in ['a', 'e', 'i', 'o', 'u']:\n if sub.count(vowel) % 2 != 0:\n has_odd_vowel = True\n break\n if not has_odd_vowel:\n return i\n return 0", "def findthelongestsubstring(s):\n seen = {0: -1}\n res = cur = 0\n for (i, c) in enumerate(s):\n cur ^= 1 << 'aeiou'.find(c) + 1 >> 1\n seen.setdefault(cur, i)\n res = max(res, i - seen[cur])\n return res", "def findthelongestsubstring(s: str) -> int:\n seen = {0: -1}\n ans = cur = 0\n for (i, c) in enumerate(s):\n cur ^= 1 << 'aeiou'.find(c) + 1 >> 1\n seen.setdefault(cur, i)\n ans = max(ans, i - seen[cur])\n return ans", "def findthelongestsubstring(s: str) -> int:\n vowels = {x: 1 << i for (i, x) in enumerate('aeiou')}\n fst = {0: -1}\n ans = mask = 0\n for (i, c) in enumerate(s):\n if c in vowels:\n mask ^= vowels[c]\n fst.setdefault(mask, i)\n ans = max(ans, i - fst[mask])\n return ans", "import collections\n\ndef findthelongestsubstring(s: str) -> int:\n for substr_len in range(len(s), -1, -1):\n end_remove = len(s) - substr_len + 1\n for start in range(end_remove):\n even = True\n sub_str = s[start:start + substr_len]\n for vowel in 'aeiou':\n if sub_str.count(vowel) % 2 != 0:\n even = False\n break\n if even == True:\n return substr_len", "def findthelongestsubstring(s: str) -> int:\n P = [0]\n vowels = 'aeiou'\n for c in s:\n i = vowels.find(c)\n mask = 1 << i if i != -1 else 0\n P.append(P[-1] ^ mask)\n ans = 0\n fst = {}\n for (i, p) in enumerate(P):\n if p in fst:\n h = fst[p]\n ans = max(ans, i - h)\n fst.setdefault(p, i)\n return ans", "def findthelongestsubstring(s: str) -> int:\n\n def countVowels(ct):\n if not ct['a'] % 2 and (not ct['e'] % 2) and (not ct['i'] % 2) and (not ct['o'] % 2) and (not ct['u'] % 2):\n return True\n return False\n for i in range(len(s)):\n ctr = collections.Counter(s[:len(s) - i])\n for j in range(i + 1):\n if j != 0:\n ctr[s[j - 1]] -= 1\n ctr[s[len(s) + j - i - 1]] += 1\n if countVowels(ctr):\n return sum(ctr.values())\n return 0", "def findthelongestsubstring(s: str) -> int:\n seen = {0: -1}\n ret = curr = 0\n for (i, c) in enumerate(s):\n curr ^= 1 << 'aeiou'.find(c) + 1 >> 1\n if curr not in seen:\n seen[curr] = i\n ret = max(ret, i - seen[curr])\n return ret", "def findthelongestsubstring(s: str) -> int:\n bits = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n seen = {0: -1}\n max_val = 0\n cur = 0\n for (i, char) in enumerate(s):\n if char in bits:\n cur ^= bits[char]\n seen.setdefault(cur, i)\n max_val = max(max_val, i - seen[cur])\n return max_val", "def findthelongestsubstring(s: str) -> int:\n m = dict(a=1, e=2, i=4, o=8, u=16)\n longest = 0\n parity_index = {0: -1}\n parity = 0\n for (i, ch) in enumerate(s):\n parity = parity ^ m.get(ch, 0)\n if parity not in parity_index:\n parity_index[parity] = i\n longest = max(longest, i - parity_index.get(parity))\n return longest", "def findthelongestsubstring1(s: str) -> int:\n\n def check(L, R, cnt_memo):\n if L > R:\n return 0\n elif (L, R) in memo:\n return memo[L, R]\n elif all((v % 2 == 0 for v in list(cnt_memo.values()))):\n return R - L + 1\n else:\n old_L = L\n new_memo = {k: v for (k, v) in list(cnt_memo.items())}\n while s[L] not in 'aeiou':\n L += 1\n new_memo[s[L]] -= 1\n if new_memo[s[L]] == 0:\n del new_memo[s[L]]\n res1 = check(L + 1, R, new_memo)\n L = old_L\n old_R = R\n new_memo = {k: v for (k, v) in list(cnt_memo.items())}\n while s[R] not in 'aeiou':\n R -= 1\n new_memo[s[R]] -= 1\n if new_memo[s[R]] == 0:\n del new_memo[s[R]]\n res2 = check(L, R - 1, new_memo)\n R = old_R\n res = max(res1, res2)\n memo[L, R] = res\n return res\n cnt_memo = collections.Counter(s)\n cnt_memo = {k: v for (k, v) in list(cnt_memo.items()) if k in 'aeiou'}\n memo = dict()\n res = check(0, len(s) - 1, cnt_memo)\n return res\n\ndef findthelongestsubstring(s: str) -> int:\n res = 0\n curr = 0\n memo = dict()\n memo[0] = -1\n for (i, c) in enumerate(s):\n if c == 'a':\n curr ^= 1\n elif c == 'e':\n curr ^= 2\n elif c == 'i':\n curr ^= 4\n elif c == 'o':\n curr ^= 8\n elif c == 'u':\n curr ^= 16\n if curr in memo:\n res = max(res, i - memo[curr])\n else:\n memo[curr] = i\n return res\n return", "def findthelongestsubstring(s: str) -> int:\n vowel_dict = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n integrals = [(False, False, False, False, False)]\n for l in s:\n vector = list(integrals[-1])\n if l in vowel_dict:\n vector[vowel_dict[l]] = not vector[vowel_dict[l]]\n integrals.append(tuple(vector))\n seen = {}\n res = 0\n for (i, v) in enumerate(integrals):\n if v in seen:\n res = max(res, i - seen[v])\n else:\n seen[v] = i\n return res", "def findthelongestsubstring(s: str) -> int:\n max_substring_size = 0\n processed_cons = None\n s_len = len(s)\n for i in range(s_len):\n if processed_cons == True:\n if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or (s[i] == 'o') or (s[i] == 'u'):\n processed_cons = False\n continue\n if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or (s[i] == 'o') or (s[i] == 'u'):\n processed_cons = False\n else:\n processed_cons = True\n if max_substring_size > s_len - i:\n break\n vowel_counts = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}\n allEven = True\n for (k, letter) in enumerate(s[i:]):\n if letter in vowel_counts:\n vowel_counts[letter] += 1\n currently_all_even = True\n for count in list(vowel_counts.values()):\n if count % 2 == 1:\n currently_all_even = False\n break\n allEven = currently_all_even\n if allEven and k + 1 > max_substring_size:\n max_substring_size = k + 1\n return max_substring_size", "from copy import copy\n\ndef findthelongestsubstring(s: str) -> int:\n vowel2idx = dict([(item[1], item[0]) for item in enumerate(['a', 'e', 'i', 'o', 'u'])])\n counters = [0]\n for item in s:\n counters.append(counters[-1])\n if item in vowel2idx:\n counters[-1] ^= 2 ** vowel2idx[item]\n for width in range(len(s), 0, -1):\n for start in range(len(s) - width + 1):\n if counters[start + width] ^ counters[start] != 0:\n continue\n return width\n return 0", "def findthelongestsubstring(s: str) -> int:\n (vowels, bits, dp) = ({'a', 'e', 'i', 'o', 'u'}, {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}, {0: -1})\n (res, odds) = (0, set())\n for i in range(len(s)):\n if s[i] in vowels:\n if s[i] in odds:\n odds.discard(s[i])\n else:\n odds.add(s[i])\n key = 0\n for o in odds:\n key |= 1 << bits[o]\n if key in dp:\n res = max(res, i - dp[key])\n else:\n dp[key] = i\n return res", "def findthelongestsubstring(s: str) -> int:\n states = [(False, False, False, False, False)]\n seen = {}\n mapping = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n for i in range(len(s)):\n vector = list(states[-1])\n character = s[i]\n if character in mapping:\n vector[mapping[character]] = not vector[mapping[character]]\n states.append(tuple(vector))\n res = 0\n for (i, v) in enumerate(states):\n if v in seen:\n res = max(res, i - seen[v])\n else:\n seen[v] = i\n return res", "def findthelongestsubstring(s: str) -> int:\n mask = 0\n mp = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n seen = [len(s)] * 63\n seen[0] = -1\n max_len = 0\n for i in range(len(s)):\n if s[i] in 'aeiou':\n mask ^= 1 << mp[s[i]]\n seen[mask] = min(seen[mask], i)\n max_len = max(max_len, i - seen[mask])\n return max_len", "def findthelongestsubstring(s: str) -> int:\n left_states = {'': -1}\n cur_state = set()\n ans = 0\n for (i, char) in enumerate(s):\n if char in 'aeiou':\n if char in cur_state:\n cur_state.remove(char)\n else:\n cur_state.add(char)\n cur_state_str = ''.join(sorted(list(cur_state)))\n if cur_state_str in left_states:\n ans = max(ans, i - left_states[cur_state_str])\n else:\n left_states[cur_state_str] = i\n return ans", "def findthelongestsubstring(s: str) -> int:\n mask = '00000'\n table = dict()\n table[mask] = -1\n vowels = 'aeiou'\n res = 0\n for (i, c) in enumerate(s):\n for j in range(5):\n if c == vowels[j]:\n mask1 = list(mask)\n mask1[j] = str(1 - int(mask1[j]))\n mask = ''.join(mask1)\n pre_idx = table.get(mask, -2)\n if pre_idx != -2:\n res = max(res, i - pre_idx)\n else:\n table[mask] = i\n return res", "def findthelongestsubstring(s: str) -> int:\n cur = 0\n res = 0\n seen = {}\n seen[0] = -1\n for (i, c) in enumerate(s):\n cur ^= 1 << 'aeiou'.find(c) + 1 >> 1\n if cur not in seen:\n seen[cur] = i\n res = max(res, i - seen[cur])\n return res", "def findthelongestsubstring(s: str) -> int:\n bits = {'a': 1, 'e': 2, 'i': 3, 'o': 4, 'u': 5}\n dp = {0: -1}\n (ans, state) = (0, 0)\n for (i, c) in enumerate(s):\n if c in bits:\n state ^= 1 << bits[c]\n ans = max(ans, i - dp.get(state, 128))\n dp[state] = min(dp.get(state, 128), i)\n return ans", "def findthelongestsubstring(s: str) -> int:\n current = [0, 0, 0, 0, 0]\n\n def convertToInteger():\n nonlocal current\n binarySum = 0\n for num in current:\n binarySum *= 2\n binarySum += num\n return binarySum\n\n def incrementVowels(char):\n nonlocal current\n if char == 'a':\n current[0] = 1 - current[0]\n elif char == 'e':\n current[1] = 1 - current[1]\n elif char == 'i':\n current[2] = 1 - current[2]\n elif char == 'o':\n current[3] = 1 - current[3]\n elif char == 'u':\n current[4] = 1 - current[4]\n earliest = {}\n earliest[0] = -1\n maxLength = 0\n current = [0, 0, 0, 0, 0]\n for (index, char) in enumerate(s):\n incrementVowels(char)\n binarySum = convertToInteger()\n if binarySum not in earliest:\n earliest[binarySum] = index\n else:\n maxLength = max(index - earliest[binarySum], maxLength)\n return maxLength", "def findthelongestsubstring(s: str) -> int:\n vowels = {'a': 1, 'e': 2, 'i': 3, 'o': 4, 'u': 5}\n seen = {0: -1}\n res = cur = 0\n for (i, c) in enumerate(s):\n if c in vowels:\n cur ^= 1 << vowels[c]\n seen.setdefault(cur, i)\n res = max(res, i - seen[cur])\n return res", "def findthelongestsubstring(s: str) -> int:\n remainder_pos_dict = dict()\n vowels = {'a', 'e', 'i', 'o', 'u'}\n vowel_count = {ch: 0 for ch in vowels}\n max_length = 0\n for (pos, ch) in enumerate(s):\n if ch in vowels:\n vowel_count[ch] += 1\n remainders = (vowel_count['a'] % 2, vowel_count['e'] % 2, vowel_count['i'] % 2, vowel_count['o'] % 2, vowel_count['u'] % 2)\n if all(map(lambda x: x == 0, remainders)):\n max_length = max(max_length, pos + 1)\n continue\n if remainders not in remainder_pos_dict:\n remainder_pos_dict[remainders] = pos\n continue\n prefix_tail = remainder_pos_dict[remainders]\n length = pos - prefix_tail\n max_length = max(length, max_length)\n return max_length", "def flip(num, pos):\n if num & 2 ** pos:\n return num - 2 ** pos\n else:\n return num + 2 ** pos\n\ndef findthelongestsubstring(s: str) -> int:\n hash = {(0, 0, 0, 0, 0): [-1]}\n maxLen = 0\n count = {'a': 0, 'e': 0, 'i': 0, 'u': 0, 'o': 0}\n for i in range(len(s)):\n if s[i] in count:\n count[s[i]] = (count[s[i]] + 1) % 2\n set = tuple(count.values())\n if set in hash:\n hash[set].extend([i])\n else:\n hash[set] = [i]\n if len(hash[set]) >= 2:\n maxLen = max(maxLen, hash[set][-1] - hash[set][0])\n return maxLen", "def findthelongestsubstring(s: str) -> int:\n first_position = {(0, 0, 0, 0, 0): -1}\n counter = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}\n ans = 0\n for (i, c) in enumerate(s):\n if c in counter:\n counter[c] += 1\n key = tuple([counter[c] % 2 for c in 'aeiou'])\n if key not in first_position:\n first_position[key] = i\n ans = max(i - first_position[key], ans)\n return ans", "def findthelongestsubstring(s: str) -> int:\n seen = {(0, 0, 0, 0, 0): -1}\n counts = {c: 0 for c in 'aeiou'}\n res = 0\n for (i, ch) in enumerate(s):\n if ch in counts:\n counts[ch] += 1\n key = tuple([counts[c] % 2 for c in 'aeiou'])\n seen.setdefault(key, i)\n res = max(res, i - seen[key])\n return res", "from collections import Counter\n\ndef findthelongestsubstring(s: str) -> int:\n _max = 0\n vowels = 'aeiou'\n\n def counter_to_tuple(counter):\n res = []\n for v in vowels:\n res.append(counter[v] % 2)\n return tuple(res)\n ss_counter = Counter()\n cache = {(0, 0, 0, 0, 0): -1}\n length = 0\n for (ind, ss) in enumerate(s):\n if ss in vowels:\n ss_counter[ss] += 1\n counter_tuple = counter_to_tuple(ss_counter)\n if counter_tuple in cache:\n length = max(length, ind - cache[counter_tuple])\n else:\n cache[counter_tuple] = ind\n return length", "def findthelongestsubstring(s: str) -> int:\n for window_size in range(len(s), -1, -1):\n check_range = len(s) - window_size + 1\n for i in range(check_range):\n check_wr = s[i:i + window_size]\n right_string = True\n for ch in 'aeiou':\n if check_wr.count(ch) % 2:\n right_string = False\n break\n if right_string:\n return window_size\n return 0", "def findthelongestsubstring(s: str) -> int:\n seen = {(0, 0, 0, 0, 0): -1}\n vowel = 'aeiou'\n count = [0] * 5\n ans = 0\n for i in range(len(s)):\n idx = vowel.find(s[i])\n if idx >= 0:\n count[idx] += 1\n state = tuple([count[i] % 2 for i in range(5)])\n if state in seen:\n ans = max(ans, i - seen[state])\n else:\n seen[state] = i\n return ans", "def findthelongestsubstring(s: str) -> int:\n first_position = {0: -1}\n bit_ind = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n ans = key = 0\n for (i, c) in enumerate(s):\n if c in bit_ind:\n key = key ^ 1 << bit_ind[c]\n if key not in first_position:\n first_position[key] = i\n ans = max(i - first_position[key], ans)\n return ans", "def findthelongestsubstring(s: str) -> int:\n dic = {0: -1}\n n = 0\n res = 0\n voewls = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n for (i, c) in enumerate(s):\n if c in voewls:\n n ^= voewls[c]\n if n not in dic:\n dic[n] = i\n else:\n res = max(res, i - dic[n])\n return res", "def findthelongestsubstring(s: str) -> int:\n cache = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n (d, k, res) = ({0: -1}, 0, 0)\n for (i, c) in enumerate(s):\n if c in cache:\n k ^= cache[c]\n if k not in d:\n d[k] = i\n else:\n res = max(res, i - d[k])\n return res", "def findthelongestsubstring(s: str) -> int:\n memo = {0: 0}\n dic = dict(list(zip('aeiou', list(range(5)))))\n (curr, ans) = (0, 0)\n for (k, v) in enumerate(s, 1):\n if v in dic:\n curr ^= 1 << dic[v]\n if curr in memo:\n ans = max(ans, k - memo[curr])\n else:\n memo[curr] = k\n return ans", "def findthelongestsubstring(s: str) -> int:\n vowels_bit_mask = {v: 2 ** i for (i, v) in enumerate('aeiou')}\n vowel_state = 0\n first_index_of_recorded_state = {0: -1}\n max_substr_len = 0\n for (index, char) in enumerate(s):\n if char in vowels_bit_mask:\n vowel_state ^= vowels_bit_mask[char]\n if vowel_state in first_index_of_recorded_state:\n max_substr_len = max(max_substr_len, index - first_index_of_recorded_state[vowel_state])\n else:\n first_index_of_recorded_state[vowel_state] = index\n return max_substr_len", "def findthelongestsubstring(s: str) -> int:\n vowels = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n (d, n, r) = ({0: -1}, 0, 0)\n for (i, c) in enumerate(s):\n if c in vowels:\n n ^= vowels[c]\n if n not in d:\n d[n] = i\n else:\n r = max(r, i - d[n])\n return r", "def findthelongestsubstring(S: str) -> int:\n vowels = 'aeiou'\n seen = {0: -1}\n ans = cur = 0\n for (i, c) in enumerate(S):\n if c in vowels:\n cur ^= 1 << ord(c) - 97\n if cur not in seen:\n seen[cur] = i\n else:\n ans = max(ans, i - seen[cur])\n return ans", "def findthelongestsubstring(s: str) -> int:\n dict_vol = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n dict_vol = {x: 1 << y for (x, y) in dict_vol.items()}\n previous_seen = {0: -1}\n cur = 0\n ans = 0\n for (i, c) in enumerate(s):\n if c in dict_vol:\n cur = cur ^ dict_vol[c]\n if cur not in previous_seen:\n previous_seen[cur] = i\n else:\n ans = max(ans, i - previous_seen[cur])\n return ans", "def findthelongestsubstring(s: str) -> int:\n (seen, vowel) = ({0: -1}, {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4})\n res = curr = 0\n for (i, c) in enumerate(s):\n if c in vowel:\n curr ^= 1 << vowel[c]\n seen.setdefault(curr, i)\n res = max(res, i - seen[curr])\n return res", "def findthelongestsubstring(s: str) -> int:\n bin_map = collections.defaultdict(int)\n for (i, c) in enumerate(['a', 'e', 'i', 'o', 'u']):\n bin_map[c] = 1 << i\n cur_bin = 0\n prev_bin = {0: -1}\n ans = 0\n for (index, c) in enumerate(s):\n cur_bin ^= bin_map[c]\n if cur_bin in prev_bin:\n ans = max(ans, index - prev_bin[cur_bin])\n else:\n prev_bin[cur_bin] = index\n return ans", "def findthelongestsubstring(s: str) -> int:\n vowels = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n (bitmask_to_index, bitmaskrepr, result) = ({0: -1}, 0, 0)\n for (index, item) in enumerate(s):\n if item in vowels:\n bitmaskrepr ^= vowels[item]\n if bitmaskrepr not in bitmask_to_index:\n bitmask_to_index[bitmaskrepr] = index\n else:\n result = max(result, index - bitmask_to_index[bitmaskrepr])\n return result", "def findthelongestsubstring(s: str) -> int:\n masks = {0: -1}\n mask = 0\n match = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n max_len = 0\n for (i, ch) in enumerate(s):\n if ch in match:\n mask = mask ^ 1 << match[ch]\n if mask in masks:\n max_len = max(max_len, i - masks[mask])\n else:\n masks[mask] = i\n return max_len", "def findthelongestsubstring(s: str) -> int:\n vowels = set('aeiou')\n odd = {tuple(): -1}\n key = tuple()\n res = 0\n window = collections.Counter()\n vowel_count = [window]\n for (i, char) in enumerate(s):\n if char in vowels:\n window[char] += 1\n key = tuple((c for c in window if window[c] & 1))\n if key in odd:\n res = max(i - odd[key], res)\n else:\n odd[key] = i\n else:\n res = max(i - odd[key], res)\n else:\n res = max(i - odd[key], res)\n return res", "def findthelongestsubstring(s: str) -> int:\n vowels = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n d = {0: -1}\n binRep = 0\n res = 0\n for (i, char) in enumerate(s):\n if char in vowels:\n binRep = binRep ^ vowels[char]\n if binRep not in d:\n d[binRep] = i\n else:\n res = max(res, i - d[binRep])\n return res", "def findthelongestsubstring(s: str) -> int:\n (n, vowels, d) = (len(s), 'aeiou', {0: -1})\n ret = cur = 0\n for (i, c) in enumerate(s):\n if c in vowels:\n cur ^= 1 << vowels.index(c)\n d.setdefault(cur, i)\n ret = max(ret, i - d[cur])\n return ret", "def findthelongestsubstring(s: str) -> int:\n digits = {c: i for (i, c) in enumerate('aeiou')}\n ans = counter = 0\n seen = {0: -1}\n for (i, c) in enumerate(s):\n if c in digits:\n counter ^= 1 << digits[c]\n seen.setdefault(counter, i)\n ans = max(ans, i - seen[counter])\n return ans", "def findthelongestsubstring(s: str) -> int:\n n = len(s)\n dp = {}\n for k in range(n, 0, -1):\n for i in range(0, n + 1 - k):\n if k == n:\n s_count = collections.Counter(s)\n dp[i, k] = [s_count.get(c, 0) % 2 == 0 for c in 'aeiou']\n elif i == 0:\n dp[i, k] = self.update_tracker(s[i + k], dp.get((i, k + 1)))\n else:\n dp[i, k] = self.update_tracker(s[i - 1], dp.get((i - 1, k + 1)))\n if all(dp[i, k]):\n return k\n return 0\n\ndef update_tracker(char, tracker):\n idx = 'aeiou'.find(char)\n new_tracker = list(tracker)\n if idx > -1:\n new_tracker[idx] = not tracker[idx]\n return new_tracker", "def findthelongestsubstring(s: str) -> int:\n res = 0\n pos = {0: -1}\n state = 0\n vowels = 'aeiou'\n for i in range(len(s)):\n j = vowels.find(s[i])\n if j >= 0:\n state ^= 1 << j\n if state in pos:\n res = max(res, i - pos[state])\n else:\n pos[state] = i\n return res", "def findthelongestsubstring(s: str) -> int:\n (mask, seen, smax, vowels) = (0, {0: -1}, 0, {x: 1 << i for (i, x) in enumerate('aeiou')})\n for (i, x) in enumerate(s):\n if x in vowels:\n mask ^= 1 << vowels[x]\n seen.setdefault(mask, i)\n smax = max(smax, i - seen[mask])\n return smax", "def findthelongestsubstring(s: str) -> int:\n for window_size in range(len(s), -1, -1):\n end_pos = len(s) - window_size + 1\n for i in range(end_pos):\n substring = s[i:i + window_size]\n is_all_even = True\n for ch in 'aeiou':\n if substring.count(ch) % 2:\n is_all_even = False\n break\n if is_all_even:\n return window_size\n return 0", "def findthelongestsubstring(s: str) -> int:\n (state, statedict) = (0, {0: -1})\n voweldict = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n maxlen = 0\n for (i, c) in enumerate(s):\n if c in voweldict:\n state ^= voweldict[c]\n if state in statedict:\n maxlen = max(maxlen, i - statedict[state])\n else:\n statedict[state] = i\n return maxlen", "def findthelongestsubstring(s: str) -> int:\n vowels = 'aeiou'\n mask = last_mask = 0\n first = [-1] + [float('inf')] * 31\n last = [-1] + [float('-inf')] * 31\n for (i, c) in enumerate(s):\n if c in set(vowels):\n j = vowels.index(c)\n (last_mask, mask) = (mask, mask ^ 1 << j)\n if first[mask] == float('inf'):\n first[mask] = last[last_mask] + 1\n last[mask] = i\n return max((j - i for (i, j) in zip(first, last)))", "VOWELS = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n\ndef findthelongestsubstring(s: str) -> int:\n seen = {0: -1}\n mask = 0\n longest = 0\n for (ind, char) in enumerate(s):\n mask ^= VOWELS.get(char, 0)\n if mask not in seen:\n seen[mask] = ind\n else:\n longest = max(longest, ind - seen[mask])\n return longest", "def findthelongestsubstring(s: str) -> int:\n substrings = self.generate_subst(s)\n res = 0\n for substring in substrings:\n is_all_even = True\n for ch in 'aeiou':\n if substring.count(ch) % 2:\n is_all_even = False\n break\n if is_all_even:\n return len(substring)\n return res\n\ndef generate_subst(s: str):\n for window_size in range(len(s), -1, -1):\n for i in range(len(s) - window_size + 1):\n yield s[i:i + window_size]", "from collections import defaultdict\n\ndef findthelongestsubstring(s: str) -> int:\n res = 0\n vowel_map = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n visited = {0: -1}\n pattern = 0\n for (i, c) in enumerate(s):\n if c in vowel_map:\n pattern ^= 1 << vowel_map[c]\n if pattern not in visited:\n visited[pattern] = i\n res = max(res, i - visited[pattern])\n return res", "def findthelongestsubstring(s: str) -> int:\n idx_dic = {0: -1}\n vowels = 'aeiou'\n state = ans = 0\n for i in range(len(s)):\n j = vowels.find(s[i])\n if j >= 0:\n state ^= 1 << j\n if state not in idx_dic:\n idx_dic[state] = i\n ans = max(ans, i - idx_dic[state])\n return ans", "def findthelongestsubstring(s: str) -> int:\n state = 0\n d = {0: -1}\n vowels = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16}\n max_len = 0\n for i in range(len(s)):\n if s[i] in vowels:\n state ^= vowels[s[i]]\n if state not in d:\n d[state] = i\n if state in d:\n max_len = max(max_len, i - d[state])\n return max_len", "def findthelongestsubstring(s: str) -> int:\n vowels = 'aeiou'\n helper = {0: -1}\n state = 0\n res = 0\n for (i, ch) in enumerate(s):\n j = vowels.find(ch)\n if j >= 0:\n state ^= 1 << j\n if state not in helper:\n helper[state] = i\n res = max(res, i - helper[state])\n return res", "def findthelongestsubstring(s: str) -> int:\n for i in range(len(s), -1, -1):\n for x in range(len(s) - i + 1):\n counter = 0\n temp = s[x:x + i]\n for k in 'aeiou':\n if temp.count(k) % 2 != 0:\n counter += 1\n break\n if counter == 0:\n return i", "from collections import defaultdict\n\ndef findthelongestsubstring(string: str) -> int:\n vowels = 'aeiou'\n vowels_dict = dict(zip(vowels, range(5)))\n curr = 0\n pos_dict = defaultdict(lambda : float('inf'))\n pos_dict[0] = -1\n res = 0\n for (i, v) in enumerate(string):\n if v in vowels_dict:\n curr ^= 1 << vowels_dict[v]\n res = max(res, i - pos_dict[curr])\n pos_dict[curr] = min(pos_dict[curr], i)\n return res", "def findthelongestsubstring(s: str) -> int:\n digits = {c: i for (i, c) in enumerate('aeiou')}\n counters = [0]\n for c in s:\n if c in digits:\n counters.append(counters[-1] ^ 1 << digits[c])\n else:\n counters.append(counters[-1])\n for length in range(len(s), 0, -1):\n for j in range(len(s), length - 1, -1):\n if not counters[j] ^ counters[j - length]:\n return length\n return 0", "def findthelongestsubstring(s: str) -> int:\n d = {(0, 0, 0, 0, 0): -1}\n count = [0, 0, 0, 0, 0]\n pos = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n ans = 0\n for (i, char) in enumerate(s):\n if char in pos:\n count[pos[char]] = (count[pos[char]] + 1) % 2\n t = tuple(count)\n if t in d:\n ans = max(ans, i - d[t])\n else:\n d[t] = i\n return ans", "def findthelongestsubstring(s: str) -> int:\n seen = {0: -1}\n pos = {c: i for (i, c) in enumerate('aeiou')}\n curr = res = 0\n for (i, c) in enumerate(s):\n curr ^= 1 << pos.get(c, -1) + 1 >> 1\n seen.setdefault(curr, i)\n res = max(res, i - seen[curr])\n return res", "def findthelongestsubstring(s: str) -> int:\n lu = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}\n\n def setFlags(flags: int, ch: str) -> int:\n if ch in lu.keys():\n mask = 1 << lu[ch]\n flags = flags ^ mask\n return flags\n FLAGS = 0\n seen = {0: -1}\n m = 0\n for (i, c) in enumerate(s):\n FLAGS = setFlags(FLAGS, c)\n if FLAGS in seen.keys():\n m = max(m, i - seen[FLAGS])\n else:\n seen[FLAGS] = i\n return m", "def findthelongestsubstring(s: str) -> int:\n masks = {'a': 16, 'e': 8, 'i': 4, 'o': 2, 'u': 1}\n num = 0\n numToIdx = {0: -1}\n ans = 0\n for (i, ch) in enumerate(s):\n if ch in masks:\n num ^= masks[ch]\n if num not in numToIdx:\n numToIdx[num] = i\n ans = max(ans, i - numToIdx[num])\n return ans", "from copy import copy\n\ndef findthelongestsubstring(s: str) -> int:\n vowel2idx = dict([(item[1], item[0]) for item in enumerate(['a', 'e', 'i', 'o', 'u'])])\n counters = [[0] * len(vowel2idx)]\n for item in s:\n counters.append(counters[-1].copy())\n if item in vowel2idx:\n counters[-1][vowel2idx[item]] += 1\n for width in range(len(s), 0, -1):\n for start in range(len(s) - width + 1):\n for n_vowels in map(int.__sub__, counters[start + width], counters[start]):\n if n_vowels % 2 == 1:\n break\n else:\n return width\n return 0", "def findthelongestsubstring(s: str) -> int:\n dp = [-1] + [len(s)] * 31\n mask = 0\n res = 0\n for (i, c) in enumerate(s):\n if c in 'aeiou':\n mask ^= 1 << 'aeiou'.index(c)\n dp[mask] = min(dp[mask], i)\n res = max(res, i - dp[mask])\n return res"], "starter_code": "def findthelongestsubstring(s: str) -> int:\n", "input_output": {"fn_name": "findTheLongestSubstring", "inputs": [["\"eleetminicoworoep\""]], "outputs": [13]}, "difficulty": "MEDIUM", "raw_tags": ["Prefix Sum", "Bit Manipulation", "String", "Hash Table"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Bit manipulation", "Data structures", "Range queries"], "skill_types": ["Bit manipulation", "Data structures", "Range queries"], "url": "https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "findthelongestsubstring", "task_id": "TACO_lite/418", "example": [[["eleetminicoworoep"], ["leetcodeisgreat"], ["bcbcbc"]], ["13", "5", "6"]]} +{"requirement": "You are given the sequence: 0123456789101112131415...\nThe 0th digit of this sequence is 0, the 1st digit of this sequence is 1, the 2nd digit of this sequence is 2 and so on. You are given n, find the nth digit of the sequence.\n \nExample 1:\nInput: n = 12\nOutput: 1\nExplanation: 1 is the 12th digit of the\ngiven sequence.\nExample 2:\nInput: n = 20\nOutput: 4\nExplanation: 4 is the 20th digit of the\ngiven sequence.\n \nYour Task:\nYou don't need to read or write anything. Your task is to complete the function NthDigit() which takes n as input parameter and returns the nth digit of the sequence.\n \nExpected Time Complexity: O(log_{10}(n))\nExpected Space Compelxity: O(1)\n \nConstraints:\n1 <= n <= 10^{9}", "solutions": ["def nthdigit(n):\n (cnt, r) = (0, 1)\n while True:\n cnt += r * pow(10, r - 1) * 9\n if cnt >= n:\n break\n r += 1\n cnt -= r * pow(10, r - 1) * 9\n n -= cnt\n (q, rem) = divmod(n, r)\n num = q + pow(10, r - 1) - 1\n if rem == 0:\n return num % 10\n else:\n num += 1\n ans = str(num)\n return int(ans[rem - 1])", "def nthdigit(n):\n if n <= 9:\n return n\n n += 1\n p = 10\n s = 10\n i = 2\n while True:\n t = p * i * 9\n s += t\n if s >= n:\n s -= t\n break\n i += 1\n p = p * 10\n d = n - s\n if d % i == 0:\n p = p + d // i - 1\n j = i\n else:\n p = p + d // i\n j = d % i\n j = i - j\n while j != 0:\n p = p // 10\n j -= 1\n return p % 10", "def nthdigit(n):\n if n < 10:\n return n\n digit = 0\n tmp = 0\n pre = 0\n while tmp < n:\n pre = tmp\n digit += 1\n tmp += 9 * 10 ** (digit - 1) * digit\n n -= pre\n num = 10 ** (digit - 1) + (n - 1) // digit\n index = (n - 1) % digit\n return num // 10 ** (digit - index - 1) % 10"], "starter_code": "def nthdigit(n):\n", "input_output": {"inputs": ["n = 12", "n = 20"], "outputs": ["1", "4"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/nth-digit-in-sequence0420/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log_{10}(n))", "entry_point": "nthdigit", "task_id": "TACO_lite/339", "example": [[[12], [20]], [1, 1]]} +{"requirement": "Given a positive integer n that represents dimensions of a 4n x 4n matrix with values from 1 to 4*n*4*n filled from left to right and top to bottom. Your task is to form two coils from matrix and print the coils.\nFollow the given examples for better understanding.\n \nExample 1:\nInput:\nn = 1\nOutput:\n10 6 2 3 4 8 12 16\n7 11 15 14 13 9 5 1 \nExplanation:\nThe matrix is \n1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\nSo, the two coils are as given in the Ouput.\nExample 2:\nInput:\nn = 2\nOutput:\n36 28 20 21 22 30 38 46\n54 53 52 51 50 42 34 26\n18 10 2 3 4 5 6 7 8\n16 24 32 40 48 56 64\n29 37 45 44 43 35 27 19\n11 12 13 14 15 23 31 39\n47 55 63 62 61 60 59 58\n57 49 41 33 25 17 9 1 \nExplanation:\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function formCoils() which takes an Integer n as input and returns a vector of two vectors representing coil1 and coil2.\n \nExpected Time Complexity: O(n^{2})\nExpected Auxiliary Space: O(n^{2})\n \nConstraints:\n1 <= n <= 20", "solutions": ["def formcoils(n):\n ans = [[], []]\n curr = [[4 * n - 1, 4 * n - 1], [0, 0]]\n d0 = [(-1, 0), (0, -1), (1, 0), (0, 1)]\n d1 = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n m = [[0 for _ in range(4 * n)] for _ in range(4 * n)]\n start = 1\n for i in range(4 * n):\n for j in range(4 * n):\n m[i][j] = start\n start += 1\n marked = [[0 for _ in range(4 * n)] for _ in range(4 * n)]\n k = 0\n while len(ans[0]) < 8 * n * n:\n marked[curr[0][0]][curr[0][1]] = 1\n ans[0].append(m[curr[0][0]][curr[0][1]])\n marked[curr[1][0]][curr[1][1]] = 1\n ans[1].append(m[curr[1][0]][curr[1][1]])\n if not (curr[0][0] + d0[k][0] < 4 * n and curr[0][0] + d0[k][0] >= 0 and (curr[0][1] + d0[k][1] >= 0) and (curr[0][1] + d0[k][0] < 4 * n) and (marked[curr[0][0] + d0[k][0]][curr[0][1] + d0[k][1]] == 0)):\n k = (k + 1) % 4\n curr[0][0] += d0[k][0]\n curr[0][1] += d0[k][1]\n curr[1][0] += d1[k][0]\n curr[1][1] += d1[k][1]\n ans[0].reverse()\n ans[1].reverse()\n return ans", "def formcoils(n):\n\n def solve1(mat, r, c):\n arr1 = []\n t = 0\n b = r - 1\n l = 0\n r = c - 1\n dir = 1\n while t <= b and l <= r:\n if dir == 1:\n for i in range(t, b + 1):\n arr1.append(mat[i][l])\n l += 1\n dir = 0\n if dir == 0:\n for i in range(l, r):\n arr1.append(mat[b][i])\n l += 1\n b -= 1\n r -= 1\n dir = 3\n if dir == 3:\n for i in range(b, t, -1):\n arr1.append(mat[i][r])\n dir = 2\n r -= 1\n if dir == 2:\n for i in range(r, l - 1, -1):\n arr1.append(mat[t + 1][i])\n dir = 1\n t += 2\n b -= 1\n return arr1\n\n def solve2(mat, r, c):\n arr1 = []\n t = 0\n b = r - 1\n l = 0\n r = c - 1\n dir = 3\n while t <= b and l <= r:\n if dir == 3:\n for i in range(b, t - 1, -1):\n arr1.append(mat[i][r])\n dir = 0\n r -= 1\n if dir == 0:\n for i in range(r, l, -1):\n arr1.append(mat[t][i])\n l += 1\n t += 1\n dir = 1\n if dir == 1:\n for i in range(t, b):\n arr1.append(mat[i][l])\n b -= 1\n l += 1\n dir = 2\n if dir == 2:\n for i in range(l, r):\n arr1.append(mat[b][i])\n dir = 3\n t += 1\n r -= 1\n b -= 1\n return arr1\n r = 4 * n\n c = 4 * n\n k = 1\n mat = []\n for i in range(1, r + 1):\n arr = []\n for j in range(1, c + 1):\n arr.append(k)\n k += 1\n mat.append(arr)\n return (solve2(mat, r, c)[::-1], solve1(mat, r, c)[::-1])", "def formcoils(n):\n mat = lambda i, j: 4 * n * i + j + 1\n answer = [[], []]\n\n def getAns(i, j, direction, ans):\n ans.append(mat(i, j))\n step = 2\n while 0 <= i < 4 * n and 0 <= j < 4 * n:\n temp = 1\n while temp <= step:\n if direction == 0:\n i = i - 1\n elif direction == 1:\n j = j + 1\n elif direction == 2:\n i = i + 1\n else:\n j = j - 1\n ans.append(mat(i, j))\n temp += 1\n direction = (direction + 1) % 4\n if direction == 0 or direction == 2:\n step += 2\n direction = 0\n i = 2 * n\n j = 2 * n - 1\n getAns(i, j, direction, answer[0])\n answer[0].pop()\n direction = 2\n i = 2 * n - 1\n j = 2 * n\n getAns(i, j, direction, answer[1])\n answer[1].pop()\n return answer", "def formcoils(n):\n Arr = [[0 for _ in range(4 * n)] for _ in range(4 * n)]\n cnt = 1\n for i in range(0, 4 * n):\n for j in range(0, 4 * n):\n Arr[i][j] = cnt\n cnt += 1\n lst1 = []\n direction = 0\n left = 0\n right = 4 * n - 1\n top = 0\n bottom = 4 * n - 1\n while left <= right and top <= bottom:\n if direction == 0:\n for i in range(top, bottom + 1):\n lst1.append(Arr[i][left])\n left += 1\n right -= 1\n if direction == 1:\n for i in range(left, right + 1):\n lst1.append(Arr[bottom][i])\n top += 1\n bottom -= 1\n if direction == 2:\n for i in range(bottom, top - 1, -1):\n lst1.append(Arr[i][right])\n left += 1\n right -= 1\n if direction == 3:\n for i in range(right, left - 1, -1):\n lst1.append(Arr[top][i])\n top += 1\n bottom -= 1\n direction = (direction + 1) % 4\n direction = 0\n left = 0\n right = 4 * n - 1\n top = 0\n bottom = 4 * n - 1\n lst2 = []\n while left <= right and top <= bottom:\n if direction == 0:\n for i in range(bottom, top - 1, -1):\n lst2.append(Arr[i][right])\n right -= 1\n left += 1\n if direction == 1:\n for i in range(right, left - 1, -1):\n lst2.append(Arr[top][i])\n top += 1\n bottom -= 1\n if direction == 2:\n for i in range(top, bottom + 1):\n lst2.append(Arr[i][left])\n left += 1\n right -= 1\n if direction == 3:\n for i in range(left, right + 1):\n lst2.append(Arr[bottom][i])\n bottom -= 1\n top += 1\n direction = (direction + 1) % 4\n Lst = []\n Lst.append(lst2[::-1])\n Lst.append(lst1[::-1])\n return Lst", "def formcoils(n):\n\n def inMatrix(i, j, n):\n return 0 <= i < 4 * n and 0 <= j < 4 * n\n\n def valFromCoord(i, j, n):\n base = 1 + 4 * n * i\n return base + j\n dirs = ((1, 0), (0, 1), (-1, 0), (0, -1))\n coil1 = [1]\n coil2 = [4 * n * 4 * n]\n i1 = 0\n j1 = 0\n i2 = 4 * n - 1\n j2 = 4 * n - 1\n added = set()\n added.add(1)\n added.add(4 * n * 4 * n)\n dir1 = 0\n dir2 = 2\n while len(added) < 4 * n * 4 * n:\n d1 = dirs[dir1]\n d2 = dirs[dir2]\n while inMatrix(i1 + d1[0], j1 + d1[1], n) and inMatrix(i2 + d2[0], j2 + d2[1], n):\n val1 = valFromCoord(i1 + d1[0], j1 + d1[1], n)\n val2 = valFromCoord(i2 + d2[0], j2 + d2[1], n)\n if val1 not in added and val2 not in added:\n i1 += d1[0]\n j1 += d1[1]\n i2 += d2[0]\n j2 += d2[1]\n added.add(val1)\n coil1.append(val1)\n added.add(val2)\n coil2.append(val2)\n else:\n break\n dir1 = (dir1 + 1) % 4\n dir2 = (dir2 + 1) % 4\n return [coil2[::-1], coil1[::-1]]", "def formcoils(n):\n num_cells = (4 * n) ** 2\n num_per_coil = num_cells >> 1\n coil1 = [0] * num_per_coil\n curr = coil1[0] = num_per_coil + 2 * n\n index = 1\n flag = 1\n step = 2\n while index < num_per_coil:\n for i in range(step):\n curr = coil1[index] = curr - 4 * n * flag\n index += 1\n if index >= num_per_coil:\n break\n if index >= num_per_coil:\n break\n for i in range(step):\n curr = coil1[index] = curr + flag\n index += 1\n if index >= num_per_coil:\n break\n flag *= -1\n step += 2\n coil2 = [0] * num_per_coil\n for i in range(num_per_coil):\n coil2[i] = num_cells + 1 - coil1[i]\n return (coil1, coil2)", "def formcoils(n):\n rows = 4 * n\n cols = 4 * n\n c_n = rows * cols // 2\n coils1 = [0] * c_n\n coils2 = [0] * c_n\n coils1[0] = 8 * n * n + 2 * n\n curr = coils1[0]\n index = 1\n steps = 2\n op = 1\n while index < c_n:\n num_steps = 0\n while index < c_n and num_steps < steps:\n curr = curr - 4 * n * op\n coils1[index] = curr\n index += 1\n num_steps += 1\n num_steps = 0\n while index < c_n and num_steps < steps:\n curr = curr + op\n coils1[index] = curr\n index += 1\n num_steps += 1\n steps += 2\n op *= -1\n for i in range(c_n):\n coils2[i] = 16 * n * n - coils1[i] + 1\n return [coils1, coils2]", "def formcoils(n):\n m = 8 * n * n\n coil1 = [0] * m\n coil1[0] = 8 * n * n + 2 * n\n curr = coil1[0]\n nflg = 1\n step = 2\n index = 1\n while index < m:\n for i in range(step):\n curr = curr - 4 * n * nflg\n coil1[index] = curr\n index += 1\n if index >= m:\n break\n if index >= m:\n break\n for i in range(step):\n curr = curr + nflg\n coil1[index] = curr\n index += 1\n if index >= m:\n break\n nflg = -nflg\n step += 2\n coil2 = [0] * m\n i = 0\n for i in range(m):\n coil2[i] = 16 * n * n + 1 - coil1[i]\n return [coil1, coil2]", "def formcoils(n):\n c = 1\n m = []\n for i in range(4 * n):\n m.append([])\n for j in range(4 * n):\n m[i].append(c)\n c += 1\n coil2_dx = [0, 1, 0, -1]\n coil2_dy = [1, 0, -1, 0]\n coil1_dx = [-1, 0, 1, 0]\n coil1_dy = [0, 1, 0, -1]\n coil1_strt = m[2 * n][2 * n - 1]\n coil2_strt = m[2 * n - 1][2 * n]\n coil1 = []\n coil2 = []\n i = 2 * n\n j = 2 * n - 1\n c = 2\n d = 0\n flag = 0\n while True:\n cnt = c\n while cnt > 0:\n if i >= 0 and j >= 0 and (i < 4 * n) and (j < 4 * n):\n coil1.append(m[i][j])\n i += coil1_dx[d]\n j += coil1_dy[d]\n else:\n break\n cnt -= 1\n d = (d + 1) % 4\n if (flag + 1) % 2 == 0:\n c += 2\n flag += 1\n if flag > 4 * n:\n break\n for i in range(len(coil1)):\n coil2.append(16 * n * n + 1 - coil1[i])\n return (coil1, coil2)", "def Matrix(n, up, mat):\n if up:\n (i, j) = (n * 2, n * 2 - 1)\n else:\n (i, j) = (n * 2 - 1, n * 2)\n mul = 2\n coil1 = [mat[i][j]]\n flag = True\n while len(coil1) < 8 * n ** 2:\n if up:\n temp = mul\n while i > 0 and temp > 0:\n i -= 1\n temp -= 1\n if i < 0:\n flag = False\n break\n coil1.append(mat[i][j])\n if not flag:\n break\n temp = mul\n while j < n * 4 and temp > 0:\n j += 1\n temp -= 1\n if j >= n * 4:\n flag = False\n break\n coil1.append(mat[i][j])\n if not flag:\n break\n up = False\n mul += 2\n else:\n temp = mul\n while i + 1 < n * 4 and temp > 0:\n i += 1\n temp -= 1\n if i >= n * 4:\n flag = False\n break\n coil1.append(mat[i][j])\n if not flag:\n break\n temp = mul\n while j > 0 and temp > 0:\n j -= 1\n temp -= 1\n if j < 0:\n flag = False\n break\n coil1.append(mat[i][j])\n if not flag:\n break\n up = True\n mul += 2\n return coil1[:8 * n ** 2]\n\ndef formcoils(n):\n mat = []\n cur_ind = 1\n for x in range(4 * n):\n row = []\n for y in range(4 * n):\n row.append(cur_ind + y)\n mat.append(row)\n cur_ind = y + cur_ind + 1\n res = [Matrix(n, True, mat), Matrix(n, False, mat)]\n return res", "def formcoils(n):\n A = [[0] * 4 * n] * 4 * n\n count = 0\n for i in range(4 * n):\n D = [0] * 4 * n\n for j in range(4 * n):\n count += 1\n D[j] = count\n A[i] = D\n lst1 = []\n lst2 = []\n lst = []\n t = 0\n b = len(A) - 1\n l = 0\n r = len(A[0]) - 1\n dir = 0\n while t <= b and l <= r:\n if dir == 0:\n for i in range(t, b + 1):\n lst.append(A[i][l])\n l += 1\n r -= 1\n elif dir == 1:\n for i in range(l, r + 1):\n lst.append(A[b][i])\n b -= 1\n t += 1\n elif dir == 2:\n for i in range(b, t - 1, -1):\n lst.append(A[i][r])\n r -= 1\n l += 1\n elif dir == 3:\n for i in range(r, l - 1, -1):\n lst.append(A[t][i])\n t += 1\n b -= 1\n dir = (dir + 1) % 4\n lst.reverse()\n lst1 = lst\n lst = []\n t = 0\n b = len(A) - 1\n l = 0\n r = len(A[0]) - 1\n dir = 0\n while t <= b and l <= r:\n if dir == 0:\n for i in range(b, t - 1, -1):\n lst.append(A[i][r])\n r -= 1\n l += 1\n elif dir == 1:\n for i in range(r, l - 1, -1):\n lst.append(A[t][i])\n t += 1\n b -= 1\n elif dir == 2:\n for i in range(t, b + 1):\n lst.append(A[i][l])\n l += 1\n r -= 1\n elif dir == 3:\n for i in range(l, r + 1):\n lst.append(A[b][i])\n b -= 1\n t += 1\n dir = (dir + 1) % 4\n lst.reverse()\n lst2 = lst\n return [lst2, lst1]", "def formcoils(n):\n iRowStart = n * 2 + 1\n iColStart = n * 2\n listOne = []\n listTwo = []\n listResult = [listOne, listTwo]\n iRow = iRowStart\n iCol = iColStart\n iLength = 4 * 4 * n * n\n bComplete = False\n iSteps = 2\n iStepCounter = 0\n cDirection = 'U'\n while bComplete == False:\n for iStepCounter in range(iSteps):\n if True:\n iNumber = (iRow - 1) * n * 4 + iCol\n listOne.append(iNumber)\n listTwo.append(iLength - iNumber + 1)\n if iNumber == iLength:\n bComplete = True\n if cDirection == 'U':\n iRow -= 1\n elif cDirection == 'R':\n iCol += 1\n elif cDirection == 'D':\n iRow += 1\n elif cDirection == 'L':\n iCol -= 1\n else:\n pass\n if cDirection == 'S':\n cDirection = 'U'\n elif cDirection == 'U':\n cDirection = 'R'\n elif cDirection == 'R':\n cDirection = 'D'\n iSteps += 2\n elif cDirection == 'D':\n cDirection = 'L'\n if iSteps > 2 * n + 1:\n pass\n elif cDirection == 'L':\n cDirection = 'U'\n iSteps += 2\n else:\n bComplete = True\n return listResult", "def valid(n, a):\n if 0 <= a < 4 * n:\n return True\n return False\n\ndef formcoils(n):\n arr1 = []\n arr2 = []\n start_r = 4 * n // 2\n start_c = 4 * n // 2 - 1\n top = start_r - 2\n left = start_c - 2\n bottom = start_r + 2\n right = start_c + 2\n arr = []\n while 0 <= start_r < 4 * n and 0 <= start_c < 4 * n:\n for i in range(start_r, top, -1):\n arr1.append(4 * i * n + start_c + 1)\n arr2.append(4 * n * (4 * n - i - 1) + (4 * n - start_c - 1) + 1)\n for i in range(start_c, right):\n arr1.append(4 * n * top + i + 1)\n arr2.append(4 * n * (4 * n - top - 1) + (4 * n - i - 1) + 1)\n for i in range(top, bottom):\n arr1.append(4 * n * i + right + 1)\n arr2.append(4 * n * (4 * n - i - 1) + (4 * n - right - 1) + 1)\n i = right\n while self.valid(n, bottom) and i > left:\n arr1.append(4 * n * bottom + i + 1)\n arr2.append(4 * n * (4 * n - bottom - 1) + (4 * n - i - 1) + 1)\n i -= 1\n start_r += 2\n start_c -= 2\n top -= 2\n bottom += 2\n left -= 2\n right += 2\n arr.append(arr1)\n arr.append(arr2)\n return arr", "def formcoils(n):\n coil = [[], []]\n n *= 4\n i1 = n // 2\n j1 = i1 - 1\n i2 = n // 2 - 1\n j2 = i2 + 1\n sign = -1\n k = 2\n while 1:\n for _ in range(k):\n coil[0].append(n * i1 + j1 + 1)\n i1 += sign\n coil[1].append(n * i2 + j2 + 1)\n i2 -= sign\n if i1 == n:\n break\n for _ in range(k):\n coil[0].append(n * i1 + j1 + 1)\n j1 -= sign\n coil[1].append(n * i2 + j2 + 1)\n j2 += sign\n sign = -sign\n k += 2\n return coil", "def formcoils(n):\n coil = [2 * n * (4 * n + 1)]\n move = 1\n for step in range(2, 4 * n, 2):\n for _ in range(step):\n coil.append(coil[-1] - 4 * n * move)\n for _ in range(step):\n coil.append(coil[-1] + move)\n move *= -1\n for _ in range(4 * n - 1):\n coil.append(coil[-1] + 4 * n)\n return [coil, [16 * n * n + 1 - x for x in coil]]", "def formcoils(n):\n m = n * 4\n a = []\n c = 1\n ans = []\n for i in range(4 * n):\n a.append([])\n for j in range(4 * n):\n a[-1].append(c)\n c += 1\n start = [m // 2, m // 2 - 1]\n limit = m * m // 2\n ans.append([])\n ans[-1].append(a[start[0]][start[1]])\n c = 0\n while True:\n c += 2\n for i in range(c):\n start[0] -= 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n for i in range(c):\n start[1] += 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n c += 2\n for i in range(c):\n start[0] += 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n for i in range(c):\n start[1] -= 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n start = [m // 2 - 1, m // 2]\n limit = m * m // 2\n ans.append([])\n ans[-1].append(a[start[0]][start[1]])\n c = 0\n while True:\n c += 2\n for i in range(c):\n start[0] += 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n for i in range(c):\n start[1] -= 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n c += 2\n for i in range(c):\n start[0] -= 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n for i in range(c):\n start[1] += 1\n ans[-1].append(a[start[0]][start[1]])\n if len(ans[-1]) == limit:\n break\n if len(ans[-1]) == limit:\n break\n return ans", "def formcoils(n):\n b = []\n c = []\n temp1 = (4 * n) ** 2\n temp2 = 1\n a = 4 * n - 2\n flag = -1\n b.append(temp1)\n c.append(temp2)\n for x in range(4 * n - 1):\n temp1 -= 4 * n\n temp2 += 4 * n\n b.append(temp1)\n c.append(temp2)\n for x in range(2 * n - 1):\n for y in range(a):\n temp1 += flag\n temp2 -= flag\n b.append(temp1)\n c.append(temp2)\n flag *= -1\n for y in range(a):\n temp1 += 4 * n * flag\n temp2 -= 4 * n * flag\n b.append(temp1)\n c.append(temp2)\n a -= 2\n b[:] = b[::-1]\n c[:] = c[::-1]\n return (b, c)", "def formcoils(n):\n coil = [2 * n * (4 * n + 1)]\n move = 1\n for i in range(2, 4 * n, 2):\n for j in range(i):\n coil.append(coil[-1] - 4 * n * move)\n for k in range(i):\n coil.append(coil[-1] + move)\n move *= -1\n for i in range(4 * n - 1):\n coil.append(coil[-1] + 4 * n)\n return [coil, [16 * n * n + 1 - x for x in coil]]", "def formcoils(n):\n m = n * 4\n table = []\n count = 0\n for i in range(m):\n line = []\n for j in range(m):\n count += 1\n line.append(count)\n table.append(line)\n red = []\n moves = {'d': m, 'u': -m, 'r': 1, 'l': -1}\n red_order = ['d', 'r', 'u', 'l']\n steps = m\n val = 1 - m\n while True:\n for move in red_order:\n for bla in range(steps):\n val += moves[move]\n red.append(val)\n if move == 'd' or move == 'u':\n steps -= 2\n if steps + 1 < 0:\n break\n blue_order = ['u', 'l', 'd', 'r']\n blue = []\n steps = m\n val = m * m + m\n while True:\n for move in blue_order:\n for bla in range(steps):\n val += moves[move]\n blue.append(val)\n if move == 'd' or move == 'u':\n steps -= 2\n if steps < 0:\n break\n return (blue[::-1], red[::-1])", "def formcoils(n):\n p = 1\n mat = [[0 for j in range(4 * n)] for i in range(4 * n)]\n for l in range(0, 4 * n):\n for g in range(0, 4 * n):\n mat[l][g] = p\n p += 1\n RS = 4 * n // 2 - 1\n RE = 4 * n // 2 + 1\n CS = 4 * n // 2\n CE = 4 * n // 2\n arr1 = []\n totalElements = 4 * n * (4 * n)\n halfElements = totalElements // 2\n i = halfElements\n while i != 0:\n for j in range(RS, RE):\n arr1.append(mat[j][CE])\n i -= 1\n if i == 0:\n break\n CS = CS - 2\n for j in range(CE, CS - 1, -1):\n arr1.append(mat[RE][j])\n i -= 1\n if i == 0:\n break\n RS = RS - 2\n CE = CE + 2\n for j in range(RE - 1, RS, -1):\n arr1.append(mat[j][CS])\n i -= 1\n if i == 0:\n break\n RE = RE + 2\n for j in range(CS, CE):\n arr1.append(mat[RS][j])\n i -= 1\n totalElements1 = 4 * n * (4 * n)\n halfElements1 = totalElements1 // 2\n RS1 = 4 * n // 2 - 2\n RE1 = 4 * n // 2\n CS1 = 4 * n // 2 - 1\n CE1 = 4 * n // 2 - 1\n arr2 = []\n i1 = halfElements1\n while i1 != 0:\n for j in range(RE1, RS1, -1):\n arr2.append(mat[j][CS1])\n i1 -= 1\n if i1 <= 0:\n break\n CE1 = CE1 + 2\n for j in range(CS1, CE1):\n arr2.append(mat[RS1][j])\n i1 -= 1\n if i1 <= 0:\n break\n RE1 = RE1 + 2\n for j in range(RS1, RE1):\n arr2.append(mat[j][CE1])\n i1 -= 1\n if i1 <= 0:\n break\n CS1 = CS1 - 2\n RS1 = RS1 - 2\n for j in range(CE1, CS1, -1):\n arr2.append(mat[RE1][j])\n i1 -= 1\n arr = [arr2, arr1]\n return arr", "def formcoils(n):\n res = [2 * n * (4 * n + 1)]\n move = 1\n for i in range(2, 4 * n, 2):\n for _ in range(i):\n res.append(res[-1] - 4 * n * move)\n for _ in range(i):\n res.append(res[-1] + move)\n move *= -1\n for i in range(4 * n - 1):\n res.append(res[-1] + 4 * n)\n return [res, [16 * n * n + 1 - j for j in res]]", "def formcoils(n):\n v = [[], []]\n (ct, i) = (1, n * 2 - 1)\n (k, l) = (i + 1, i)\n e = 4 * n * k + l + 1\n v[0].append(e)\n while ct <= i:\n for j in range(ct * 2):\n if ct % 2 != 0:\n e -= 4 * n\n else:\n e += 4 * n\n v[0].append(e)\n for j in range(ct * 2):\n if ct % 2 == 0:\n e -= 1\n else:\n e += 1\n v[0].append(e)\n ct += 1\n for j in range(4 * n - 1):\n e += 4 * n\n v[0].append(e)\n (ct, e) = (1, 4 * n * l + k + 1)\n v[1].append(e)\n while ct <= i:\n for j in range(ct * 2):\n if ct % 2 != 0:\n e += 4 * n\n else:\n e -= 4 * n\n v[1].append(e)\n for j in range(ct * 2):\n if ct % 2 == 0:\n e += 1\n else:\n e -= 1\n v[1].append(e)\n ct += 1\n for j in range(4 * n - 1):\n e -= 4 * n\n v[1].append(e)\n return v", "def first(n, mat):\n arr = []\n j = n - 1\n i = n - 1\n c = -1\n while True:\n while i > c:\n arr.append(mat[i][j])\n i -= 1\n c += 1\n i += 1\n j -= 1\n while j > c:\n arr.append(mat[i][j])\n j -= 1\n i += 1\n j += 1\n while i < n - (c + 1):\n arr.append(mat[i][j])\n i += 1\n i -= 1\n j += 1\n if i == j:\n return arr[::-1]\n c += 1\n while j < n - (c + 1):\n arr.append(mat[i][j])\n j += 1\n j -= 1\n i -= 1\n\ndef second(n, mat):\n arr = []\n j = 0\n i = 0\n c = n\n while True:\n while i < c:\n arr.append(mat[i][j])\n i += 1\n c -= 1\n i -= 1\n j += 1\n while j < c:\n arr.append(mat[i][j])\n j += 1\n i -= 1\n j -= 1\n while i > n - (c + 1):\n arr.append(mat[i][j])\n i -= 1\n i += 1\n j -= 1\n if i == j:\n return arr[::-1]\n c -= 1\n while j > n - (c + 1):\n arr.append(mat[i][j])\n j -= 1\n j += 1\n i += 1\n return arr\n\ndef formcoils(n):\n mat = []\n for i in range(1, (4 * n) ** 2, 4 * n):\n m = [i for i in range(i, i + 4 * n)]\n mat.append(m)\n arr1 = self.first(4 * n, mat)\n arr2 = self.second(4 * n, mat)\n return [arr1, arr2]", "def formcoils(n):\n arr = [2 * n * (4 * n + 1)]\n step = 1\n for i in range(2, 4 * n, 2):\n for _ in range(i):\n arr.append(arr[-1] - 4 * n * step)\n for _ in range(i):\n arr.append(arr[-1] + step)\n step = step * -1\n for _ in range(4 * n - 1):\n arr.append(arr[-1] + 4 * n)\n return [arr, [16 * n * n + 1 - i for i in arr]]", "def construct_matrix(n):\n (matrix, st) = ([], 1)\n for i in range(n):\n matrix.append(list(range(st, st + n)))\n st += n\n return matrix\n\ndef formcoils(n):\n n *= 4\n matrix = self.construct_matrix(n)\n (coil1, coil2) = ([], [])\n (rmin, rmax, cmin, cmax) = (0, n - 1, 0, n - 1)\n while rmin < rmax and cmin < cmax:\n for i in range(rmin, rmax + 1):\n coil1.append(matrix[i][cmin])\n for j in range(cmin + 1, cmax):\n coil1.append(matrix[rmax][j])\n for i in range(rmax, rmin, -1):\n coil2.append(matrix[i][cmax])\n for j in range(cmax, cmin, -1):\n coil2.append(matrix[rmin][j])\n (coil1, coil2) = (coil2, coil1)\n rmin += 1\n rmax -= 1\n cmin += 1\n cmax -= 1\n return [coil2[::-1], coil1[::-1]]", "def formcoils(n):\n coil = [2 * n * (4 * n + 1)]\n coil2 = [2 * n * (4 * n - 1) + 1]\n diff = 1\n for x in range(2, 4 * n, 2):\n for _ in range(x):\n coil.append(coil[-1] - 4 * n * diff)\n coil2.append(coil2[-1] + 4 * n * diff)\n for _ in range(x):\n coil.append(coil[-1] + diff)\n coil2.append(coil2[-1] - diff)\n diff *= -1\n for _ in range(4 * n - 1):\n coil.append(coil[-1] + 4 * n)\n coil2.append(coil2[-1] - 4 * n)\n return [coil, coil2]", "def formcoils(n):\n\n def is_valid(x, y):\n if x >= 0 and x < 4 * n and (y >= 0) and (y < 4 * n):\n return True\n return False\n\n def rec(x, y, direction, steps):\n update = [[-1, 1], [1, -1]]\n if not is_valid(x, y + steps * update[direction][1]):\n steps = steps - 1\n for i in range(steps):\n y += update[direction][1]\n ans.append(x + y * 4 * n + 1)\n if steps % 2:\n return\n for i in range(steps):\n x += update[direction][0]\n ans.append(x + y * 4 * n + 1)\n direction = 1 - direction\n steps += 2\n rec(x, y, direction, steps)\n ans = []\n half = 4 * n // 2\n (x, y) = (half - 1, half)\n ans.append(x + y * 4 * n + 1)\n rec(x, y, 1, 2)\n ans.append('')\n ret = [ans]\n ans = []\n (x, y) = (half, half - 1)\n ans.append(x + y * 4 * n + 1)\n rec(x, y, 0, 2)\n ans.append('')\n ret.append(ans)\n return ret", "def formcoils(n):\n m = 8 * n * n\n ans = [[], []]\n ans[0].append(8 * n * n + 2 * n)\n curr = ans[0][0]\n nfgl = 1\n step = 2\n index = 1\n while index < m:\n for i in range(0, step):\n curr = curr - 4 * n * nfgl\n ans[0].append(curr)\n if len(ans[0]) >= m:\n break\n if len(ans[0]) >= m:\n break\n for i in range(step):\n curr = curr + nfgl\n ans[0].append(curr)\n if len(ans[0]) >= m:\n break\n nfgl = nfgl * -1\n step += 2\n for i in range(m):\n ans[1].append(16 * n * n + 1 - ans[0][i])\n return ans", "def formcoils(n):\n c = [2 * n * (4 * n + 1)]\n m = 1\n for s in range(2, 4 * n, 2):\n for i in range(s):\n c.append(c[-1] - 4 * n * m)\n for j in range(s):\n c.append(c[-1] + m)\n m *= -1\n for k in range(4 * n - 1):\n c.append(c[-1] + 4 * n)\n return [c, [16 * n * n + 1 - x for x in c]]", "def formcoils(n):\n\n def mat(x, y):\n return n * x + y + 1\n arr = [[], []]\n n *= 4\n i1 = int(n / 2)\n j1 = i1 - 1\n sign = -1\n k = 2\n i2 = int(n / 2) - 1\n j2 = i2 + 1\n while 1:\n for _ in range(k):\n arr[0].append(mat(i1, j1))\n i1 += sign\n arr[1].append(mat(i2, j2))\n i2 += sign * -1\n if i1 == n:\n break\n for _ in range(k):\n arr[0].append(mat(i1, j1))\n j1 -= sign\n arr[1].append(mat(i2, j2))\n j2 -= sign * -1\n sign *= -1\n k += 2\n return arr", "def formcoils(n):\n c = [2 * n * (4 * n + 1)]\n m = 1\n for i in range(2, 4 * n, 2):\n for _ in range(i):\n c.append(c[-1] - 4 * n * m)\n for _ in range(i):\n c.append(c[-1] + m)\n m *= -1\n for _ in range(4 * n - 1):\n c.append(c[-1] + 4 * n)\n return [c, [16 * n * n + 1 - x for x in c]]", "def formcoils(n):\n\n def mat(x, y):\n return n * x + y + 1\n arr = [[], []]\n n *= 4\n i = int(n / 2)\n j = i - 1\n sign = -1\n k = 2\n while i != n - 1 or j != n - 1:\n for _ in range(k):\n arr[0].append(mat(i, j))\n i += sign\n if i == n:\n break\n for _ in range(k):\n arr[0].append(mat(i, j))\n j -= sign\n sign *= -1\n k += 2\n i = int(n / 2) - 1\n j = i + 1\n sign = 1\n k = 2\n while i != 0 or j != 0:\n for _ in range(k):\n arr[1].append(mat(i, j))\n i += sign\n if i < 0:\n break\n for _ in range(k):\n arr[1].append(mat(i, j))\n j -= sign\n sign *= -1\n k += 2\n return arr", "def formcoils(n):\n coils = [2 * n * (4 * n + 1)]\n ind = 1\n for i in range(2, 4 * n, 2):\n for j in range(i):\n coils.append(coils[-1] - 4 * n * ind)\n for j in range(i):\n coils.append(coils[-1] + ind)\n ind *= -1\n for i in range(4 * n - 1):\n coils.append(coils[-1] + 4 * n)\n return [coils, [16 * n * n + 1 - x for x in coils]]"], "starter_code": "def formcoils(n):\n", "input_output": {"inputs": ["n = 1", "n = 2"], "outputs": ["10 6 2 3 4 8 12 16\r\n7 11 15 14 13 9 5 1", "36 28 20 21 22 30 38 46\r\n54 53 52 51 50 42 34 26\r\n18 10 2 3 4 5 6 7 8\r\n16 24 32 40 48 56 64\r\n\r\n29 37 45 44 43 35 27 19\r\n11 12 13 14 15 23 31 39\r\n47 55 63 62 61 60 59 58\r\n57 49 41 33 25 17 9 1"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/form-coils-in-a-matrix4726/1", "Expected Auxiliary Space": "O(n^{2})", "time_limit": null, "date": null, "picture_num": "1", "memory_limit": null, "Expected Time Complexity": "O(n^{2})", "entry_point": "formcoils", "task_id": "TACO_lite/293", "example": [[], []]} +{"requirement": "Given a number N. Check whether it is divisble by 4.\nExample 1:\nInput:\nN = 1124\nOutput: 1\nExplanation: The number is divisible by 4\nas 1124 % 4 = 0.\n\u00c3\u00a2\u00e2\u0082\u00ac\u00e2\u0080\u00b9Example 2:\nInput: \nN = 7\nOutput: 0\nExplanation: The number is not divisibly by\n4 as 7 % 4 = 3.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function divisibleBy4() which takes the number in the form of a string N as input and returns 1 if the number is divisible by 4. Else, it returns 0.\nExpected Time Complexity: O(1).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= N <= 10^{1000}+5", "solutions": ["def divisibleby4(N):\n if int(N) % 4 == 0:\n return 1\n else:\n return 0", "def divisibleby4(N):\n if int(str(N)[-2:]) % 4 == 0:\n return 1\n return 0", "def divisibleby4(N):\n N = int(N)\n return int(not N % 4)", "def divisibleby4(N):\n result = int(N)\n ree = result % 4\n if ree == 0:\n return 1\n return 0", "def divisibleby4(n):\n if int(n) % 4 == 0:\n return 1\n return 0", "def divisibleby4(N):\n n = int(N[-2:])\n return int(not n % 4)", "def divisibleby4(N):\n if len(N) <= 2:\n return 1 if int(N) % 4 == 0 else 0\n n = len(N)\n num = int(N[n - 2:n])\n return 1 if num % 4 == 0 else 0"], "starter_code": "def divisibleby4 (N):\n", "input_output": {"inputs": ["N = 1124", "N = 7"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/check-if-divisible-by-43813/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1).", "entry_point": "divisibleby4", "task_id": "TACO_lite/423", "example": [[[1124], [7]], ["1", "0"]]} +{"requirement": "You are given a string of words (x), for each word within the string you need to turn the word 'inside out'. By this I mean the internal letters will move out, and the external letters move toward the centre. \n\nIf the word is even length, all letters will move. If the length is odd, you are expected to leave the 'middle' letter of the word where it is. \n\nAn example should clarify:\n\n'taxi' would become 'atix'\n'taxis' would become 'atxsi'", "solutions": ["import re\n\ndef inside_out(s):\n return re.sub('\\\\S+', lambda m: inside_out_word(m.group()), s)\n\ndef inside_out_word(s):\n (i, j) = (len(s) // 2, (len(s) + 1) // 2)\n return s[:i][::-1] + s[i:j] + s[j:][::-1]", "def swap(word):\n m = len(word) // 2\n if len(word) % 2 == 0:\n return word[:m][::-1] + word[m:][::-1]\n else:\n return word[:m][::-1] + word[m] + word[m + 1:][::-1]\n\ndef inside_out(st):\n return ' '.join(map(swap, st.split()))", "def inside_out(s):\n return ' '.join((w[:len(w) // 2][::-1] + w[len(w) // 2:(len(w) + 1) // 2] + w[(len(w) + 1) // 2:][::-1] for w in s.split()))", "from itertools import chain\n\ndef change(st):\n if len(st) < 4:\n return st\n (q, r) = divmod(len(st), 2)\n return ''.join(chain(st[q - 1::-1], st[q:q + r], st[:q + r - 1:-1]))\n\ndef inside_out(st):\n return ' '.join(map(change, st.split()))", "def inside_out(st):\n\n def inside_out_1(st):\n (h, m) = divmod(len(st), 2)\n return st[:h][::-1] + st[h:h + m] + st[h + m:][::-1]\n return ' '.join(map(inside_out_1, st.split(' ')))", "def inside_out(s):\n return ' '.join((w[:m][::-1] + w[m] * (L % 2) + w[-m:][::-1] * (L > 1) if w else w for (w, m, L) in map(lambda w: (w, len(w) // 2, len(w)), s.split(' '))))", "inside_out = lambda s: ' '.join([i[:len(i) // 2][::-1] + ['', i[len(i) // 2]][len(i) & 1] + i[len(i) // 2 + (len(i) & 1):][::-1] for i in s.split()])", "def inside_out(text):\n return ' '.join((next((f'{w[:i][::-1]}{w[i:j]}{w[j:][::-1]}' for (i, j) in [[len(w) // 2, (len(w) + 1) // 2]])) for w in text.split()))", "inside_out = lambda s: ' '.join((x[:l][::-1] + x[l] * n + x[l + n:][::-1] for x in s.split() for (l, n) in [(len(x) // 2, len(x) % 2)]))"], "starter_code": "def inside_out(s):\n", "input_output": {"fn_name": "inside_out", "inputs": [["man i need a taxi up to ubud"], ["what time are we climbing up the volcano"], ["take me to semynak"], ["massage yes massage yes massage"], ["take bintang and a dance please"]], "outputs": [["man i ende a atix up to budu"], ["hwta item are we milcgnib up the lovcona"], ["atek me to mesykan"], ["samsega yes samsega yes samsega"], ["atek nibtgna and a adnec elpesa"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57ebdf1c2d45a0ecd7002cd5", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "inside_out", "task_id": "TACO_lite/425", "example": [[["taxi"], ["taxis"]], ["atix", "atxsi"]]} +{"requirement": "Given a Cirular Linked List of size N, split it into two halves circular lists. If there are odd number of nodes in the given circular linked list then out of the resulting two halved lists, first list should have one node more than the second list. The resultant lists should also be circular lists and not linear lists.\n \nExample 1:\nInput:\nCircular LinkedList: 1->5->7\nOutput:\n1 5\n7\n \nExample 2:\nInput:\nCircular LinkedList: 2->6->1->5\nOutput:\n2 6\n1 5\nYour Task:\nYour task is to complete the given function splitList(), which takes 3 input parameters: The address of the head of the linked list, addresses of the head of the first and second halved resultant lists and Set the head1_ref and head2_ref to the first resultant list and second resultant list respectively.\nExpected Time Complexity: O(N)\nExpected Auxilliary Space: O(1)\nConstraints:\n1 <= N <= 100", "solutions": ["def splitList(head, head1, head2):\n if head == None or head.next == head:\n return head\n count = 1\n head1 = head\n curr = head\n prev = None\n while curr.next != head:\n count += 1\n curr = curr.next\n prev = curr\n if count % 2 == 0:\n A = count // 2\n temp = head\n for i in range(A - 1):\n temp = temp.next\n head2 = temp.next\n temp.next = None\n temp.next = head1\n prev.next = head2\n else:\n A = count // 2\n temp = head\n for i in range(A):\n temp = temp.next\n head2 = temp.next\n temp.next = None\n temp.next = head1\n prev.next = None\n prev.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n node = head.next\n prev = head\n count = 1\n while head != node:\n prev = prev.next\n node = node.next\n count += 1\n if count % 2 == 0:\n count = count // 2\n else:\n count = count // 2 + 1\n node = head\n while count > 1:\n node = node.next\n count -= 1\n head1 = head\n head2 = node.next\n node.next = head1\n prev.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n if not head:\n return None\n slow = head\n fast = head.next\n while fast != head and fast.next != head:\n slow = slow.next\n fast = fast.next.next\n head1 = head\n head2 = slow.next\n slow.next = head1\n curr = head2\n while curr.next != head:\n curr = curr.next\n curr.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n fast = head\n slow = head\n while fast.next != head and fast.next.next != head:\n fast = fast.next.next\n slow = slow.next\n head1 = head\n head2 = slow.next\n slow.next = head1\n front = head2\n while front.next != head:\n front = front.next\n front.next = head2\n return (head1, head2)", "import math\n\ndef splitList(head, head1, head2):\n s = set()\n itr = head\n l = 0\n while itr not in s:\n s.add(itr)\n itr = itr.next\n l += 1\n hlf = math.ceil(l / 2)\n (itr, head1, k) = (head, head, 0)\n while k < hlf - 1:\n itr = itr.next\n k += 1\n nxt = itr.next\n head2 = nxt\n itr.next = None\n itr.next = head\n k = 0\n while k < l - hlf - 1:\n nxt = nxt.next\n k += 1\n nxt.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n slow = head\n fast = head.next\n head1 = head\n while slow and fast and fast.next:\n if fast == head or fast.next == head:\n head2 = slow.next\n slow.next = head\n break\n else:\n slow = slow.next\n fast = fast.next.next\n temp = head2\n while temp.next != head:\n temp = temp.next\n temp.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n count = 1\n tmp = head.next\n while tmp != head:\n count += 1\n tmp = tmp.next\n if count % 2 == 0:\n count = count / 2\n else:\n count = int(count / 2) + 1\n tmp = head\n head1 = head\n ct = 1\n while ct < count:\n ct += 1\n tmp = tmp.next\n head2 = tmp.next\n tmp.next = head1\n tmp = head2\n while tmp.next != head:\n tmp = tmp.next\n tmp.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n slowPtr = fastPtr = head\n while fastPtr.next != head and fastPtr.next.next != head:\n fastPtr = fastPtr.next.next\n slowPtr = slowPtr.next\n head2 = slowPtr.next\n slowPtr.next = head\n head1 = head\n trav = head2\n while trav.next != head:\n trav = trav.next\n trav.next = head2\n return (head1, head2)", "def __init__():\n self.data = None\n self.next = None\n\ndef splitList(head, head1, head2):\n n = head\n L = []\n while n.next != head:\n L.append(n.data)\n n = n.next\n L.append(n.data)\n if len(L) % 2 == 0:\n l = int(len(L) // 2) - 1\n else:\n l = int(len(L) // 2)\n head1 = head\n n1 = head1\n while l != 0:\n n1 = n1.next\n l = l - 1\n head2 = n1.next\n n1.next = head\n n.next = head2\n return (head1, head2)", "def splitList(h, h1, h2):\n f = h\n c = 1\n h1 = h2 = t = h\n while f.next != h:\n f = f.next\n c += 1\n if c % 2 == 0:\n c = c // 2\n else:\n c = c // 2 + 1\n while c != 0:\n t = h2\n h2 = h2.next\n c -= 1\n t.next = h1\n f.next = h2\n return (h1, h2)", "def splitList(head, head1, head2):\n length = 0\n curr = head\n while curr != None:\n length += 1\n if curr.next == head:\n break\n curr = curr.next\n m = length // 2\n if length % 2 != 0:\n m += 1\n head1 = None\n head2 = None\n head1 = head\n curr = head\n count = 0\n while curr != None:\n count += 1\n if count == m:\n temp = curr\n curr = curr.next\n temp.next = head1\n break\n curr = curr.next\n head2 = curr\n while curr != None:\n count += 1\n if count == length:\n curr.next = head2\n break\n curr = curr.next\n return (head1, head2)", "def splitList(head, head1, head2):\n (head1, head2) = (head, head)\n (ptr1, ptr2) = (head, head)\n while ptr2.next != head:\n ptr2 = ptr2.next\n ptr2.next = None\n ptr2 = head\n while ptr2 and ptr2.next:\n ptr1 = ptr1.next\n ptr2 = ptr2.next\n ptr2 = ptr2.next if ptr2 else ptr2\n head2 = ptr1.next if ptr2 else ptr1\n (ptr1, ptr2) = (head1, head2)\n while ptr1.next != ptr2:\n ptr1 = ptr1.next\n ptr1.next = head1\n while ptr2.next:\n ptr2 = ptr2.next\n ptr2.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n temp = head\n c = 1\n while temp.next != head:\n c += 1\n temp = temp.next\n temp1 = head\n if c % 2 == 0:\n c = c // 2\n i = 1\n while i != c:\n temp1 = temp1.next\n i += 1\n const = temp1.next\n temp1.next = head\n head1 = head\n temp.next = const\n head2 = const\n else:\n c = c // 2 + 1\n i = 1\n while i != c:\n temp1 = temp1.next\n i += 1\n const = temp1.next\n temp1.next = head\n head1 = head\n temp.next = const\n head2 = const\n return (head1, head2)", "def __init__(data):\n self.data = data\n self.next = None\n\ndef splitList(head, head1, head2):\n if head is None:\n return (head1, head2)\n slow = head\n fast = head\n while fast.next != head and fast.next.next != head:\n slow = slow.next\n fast = fast.next.next\n if fast.next.next == head:\n fast = fast.next\n head1 = head\n head2 = slow.next\n slow.next = head1\n fast.next = head2\n return (head1, head2)", "import math\n\ndef splitList(head, head1, head2):\n p = head\n q = head\n if head.next == None:\n return (head, head)\n count = 0\n while p:\n count += 1\n q = p\n p = p.next\n if p == head:\n q.next = None\n break\n count = math.ceil(count / 2)\n p = head\n r = head\n while count != 0:\n r = p\n p = p.next\n count -= 1\n r.next = head\n q.next = p\n head1 = head\n head2 = p\n return (head1, head2)", "def splitList(head, head1, head2):\n (temp1, temp2) = (head, head.next)\n while temp2 != head and temp2.next != head:\n temp1 = temp1.next\n temp2 = temp2.next.next\n head1 = head\n head2 = temp1.next\n if temp2.next == head:\n temp2.next = temp1.next\n else:\n pre = None\n new = temp1.next\n while new != head:\n pre = new\n new = new.next\n pre.next = temp1.next\n temp1.next = head\n return (head1, head2)", "def splitList(head, head1, head2):\n cur = temp = head\n c = 0\n l = []\n while cur not in l:\n l.append(cur)\n prev = cur\n cur = cur.next\n c += 1\n prev.next = None\n head1 = cur\n if c % 2 == 0:\n i = c // 2\n else:\n i = c // 2 + 1\n j = 0\n while j < i:\n j += 1\n prev = cur\n cur = cur.next\n prev.next = head1\n head2 = cur\n while cur != None:\n prev = cur\n cur = cur.next\n prev.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n (tmp, t) = (head, head)\n n = 0\n while t.next != head:\n n += 1\n t = t.next\n n = n // 2\n head1 = tmp\n while n:\n n -= 1\n tmp = tmp.next\n head2 = tmp.next\n tmp.next = head\n tmp = head2\n while 1:\n if tmp.next == head:\n tmp.next = head2\n break\n tmp = tmp.next\n return (head1, head2)", "def splitList(head, head1, head2):\n temp = slow = fast = head\n slow_left = None\n fast_left = None\n if head == None:\n head1 = None\n head2 = None\n return (head1, head2)\n traversed = True\n while temp != fast and temp != fast.next or traversed:\n traversed = False\n slow_left = slow\n slow = slow.next\n fast_left = fast.next\n fast = fast.next.next\n if temp == fast.next:\n head2 = slow.next\n fast.next = slow.next\n slow.next = head\n head1 = head\n if temp == fast:\n slow_left.next = head\n head1 = head\n head2 = slow\n fast_left.next = slow\n return (head1, head2)", "def splitList(head, a, b):\n slow = head\n fast = head.next\n a = head\n while fast != head and fast.next != head:\n slow = slow.next\n fast = fast.next.next\n b = slow.next\n slow.next = head\n p = b\n while p.next != head:\n p = p.next\n p.next = b\n return (a, b)", "def splitList(head, head1, head2):\n p = r = head\n q = head.next\n c = 1\n while True:\n if r.next != head:\n c += 1\n r = r.next\n else:\n break\n if c % 2 == 0:\n t = int(c / 2)\n else:\n t = int((c + 1) / 2)\n for i in range(t - 1):\n p = q\n q = q.next\n p.next = head\n r.next = q\n head1 = head\n head2 = q\n return (head1, head2)", "def splitList(head, head1, head2):\n slow = head\n fast = head.next\n while fast != head and fast.next != head:\n p = fast\n slow = slow.next\n fast = fast.next.next\n if p.next.next == head:\n fast = p.next\n a = slow.next\n slow.next = head\n fast.next = a\n head1 = head\n head2 = a\n return (head1, head2)", "def splitList(head, head1, head2):\n slow = head\n fast = head.next\n while fast != head and fast.next != head:\n fast = fast.next.next\n slow = slow.next\n aftermid = slow.next\n slow.next = head\n head1 = head\n temp = aftermid\n while temp.next != head:\n temp = temp.next\n temp.next = aftermid\n head2 = aftermid\n return (head1, head2)", "def splitList(head, head1, head2):\n (head1, head2) = (head, head)\n while head2.next is not head and head2.next.next is not head:\n head1 = head1.next\n head2 = head2.next.next\n if head2.next is not head:\n head2 = head2.next\n head2.next = head1.next\n head2 = head2.next\n head1.next = head\n head1 = head1.next\n return (head1, head2)", "import math\n\ndef splitList(head, head1, head2):\n slow = head\n fast = head.next\n while fast != head and fast.next != head:\n slow = slow.next\n prev = fast.next\n fast = fast.next.next\n head1 = head\n head2 = slow.next\n slow.next = head\n if fast == head:\n prev.next = head2\n else:\n fast.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n s = head\n f = head\n count = 1\n while f is not None:\n f = f.next\n if f == head:\n break\n count += 1\n if count % 2 == 0:\n loop_c = count // 2\n else:\n loop_c = count // 2 + 1\n n = head\n head1 = n\n prev = None\n while loop_c:\n loop_c -= 1\n prev = n\n n = n.next\n prev.next = head\n head1 = head\n head2 = n\n p = head2\n prev = None\n while head2:\n prev = p\n p = p.next\n if head == p:\n break\n prev.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n start = head\n end = head\n while end.next != head and end.next.next != head:\n end = end.next.next\n start = start.next\n temp = start.next\n start.next = head\n head1 = head\n if end.next == head:\n end.next = temp\n else:\n end.next.next = temp\n head2 = temp\n return (head1, head2)", "def splitList(head, head1, head2):\n temp = head\n end1 = head\n N = 1\n end = head\n start = head\n while head:\n if head.next == start:\n break\n head = head.next\n N += 1\n end = head\n for i in range(N // 2 + N % 2 - 1):\n end1 = end1.next\n head2 = end1.next\n end.next = head2\n end1.next = start\n return (start, head2)", "def splitList(head, head1, head2):\n size = 1\n head2 = head1 = head\n while head:\n if head.next == head1:\n break\n head = head.next\n size += 1\n if size % 2 == 0:\n size -= 1\n for _ in range(size // 2):\n head2 = head2.next\n k = head2\n head2 = head2.next\n k.next = head1\n head.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n if head.next.next == None:\n node1 = head\n node2 = head.next\n node1.next = node1\n node2.next = node2\n slow = head\n fast = head\n while fast.next != head and fast.next.next != head:\n slow = slow.next\n fast = fast.next.next\n head1 = head\n head2 = slow.next\n slow.next = head\n temp = head2\n while temp.next != head:\n temp = temp.next\n temp.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n s = head\n f = head\n while f.next != head and f.next.next != head:\n s = s.next\n f = f.next.next\n if f.next.next == head:\n f = f.next\n head1 = head\n if head.next != head:\n head2 = s.next\n f.next = s.next\n s.next = head\n return (head1, head2)", "def splitList(head, head1, head2):\n fast = head\n slow = head\n while fast.next != head and fast.next.next != head:\n fast = fast.next.next\n slow = slow.next\n if fast.next.next == head:\n fast = fast.next\n fast.next = slow.next\n tmp = slow.next\n slow.next = head\n head1 = head\n head2 = tmp\n return (head1, head2)", "def splitList(head, head1, head2):\n (slow, fast, prev) = (head, head, head)\n while True:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n if fast == head or fast == head.next:\n break\n fast = slow\n while fast.next is not head:\n fast = fast.next\n (fast.next, prev.next) = (prev.next, head)\n head1 = head\n head2 = slow\n return (head1, head2)", "def splitList(head, head1, head2):\n slow = head\n fast = head.next\n while fast != head and fast.next != head:\n slow = slow.next\n fast = fast.next.next\n mid = slow\n head1 = head\n head2 = mid.next\n mid.next = head1\n tail = head2\n while tail.next != head:\n tail = tail.next\n tail.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n b = 0\n tmp = head\n while tmp.next != head:\n b += 1\n tmp = tmp.next\n c = b // 2\n head1 = head\n tmp = head\n i = 0\n prev = tmp\n while i < c:\n prev = tmp\n tmp = tmp.next\n i += 1\n head2 = tmp.next\n tmp.next = head1\n tmp = head2\n while tmp.next != head:\n tmp = tmp.next\n tmp.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n (nd, N) = (head.next, 1)\n while nd != head:\n N += 1\n nd = nd.next\n N1 = (N + 1) // 2\n N2 = N - N1\n head1 = head\n nd = head1\n for _ in range(N1 - 1):\n nd = nd.next\n head2 = nd.next\n nd.next = head1\n nd = head2\n for _ in range(N2 - 1):\n nd = nd.next\n nd.next = head2\n return (head1, head2)", "import math\n\ndef splitList(head, head1, head2):\n if head is None:\n return None\n count = 0\n current = head\n while current.next != head:\n count += 1\n current = current.next\n count += 1\n mid = math.ceil(count / 2)\n head1 = head\n current = head\n for i in range(mid - 1):\n current = current.next\n if head.next != head:\n head2 = current.next\n current.next = head1\n current2 = head2\n while current2.next != head:\n current2 = current2.next\n current2.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n n = 1\n t = head\n while t.next != head:\n n += 1\n t = t.next\n if n % 2 == 0:\n s = int((n - 1) / 2)\n else:\n s = int(n / 2)\n head1 = head\n t1 = head1\n for i in range(s):\n t1 = t1.next\n head2 = t1.next\n t1.next = head1\n t2 = head2\n while t2.next != head:\n t2 = t2.next\n t2.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n slow = head\n fast = head\n while fast.next != head:\n if fast.next.next == head:\n fast = fast.next\n else:\n fast = fast.next.next\n slow = slow.next\n head1 = head\n head2 = slow.next\n fast.next = slow.next\n slow.next = head\n return (head1, head2)", "def splitList(head, head1, head2):\n slow_ptr = head\n fast_ptr = head\n if head is None:\n return\n while fast_ptr.next != head and fast_ptr.next.next != head:\n fast_ptr = fast_ptr.next.next\n slow_ptr = slow_ptr.next\n if fast_ptr.next.next == head:\n fast_ptr = fast_ptr.next\n head1 = head\n if head.next != head:\n head2 = slow_ptr.next\n fast_ptr.next = slow_ptr.next\n slow_ptr.next = head\n return (head1, head2)\n return (head1, head2)", "def splitList(head, head1, head2):\n if head is None:\n return (None, None)\n count = 1\n temp = head\n while temp.next is not head:\n temp = temp.next\n count += 1\n mid_val = 0\n if count & 1:\n mid_val = count // 2 + 1\n else:\n mid_val = count // 2\n temp = head\n prev = Node()\n prev.next = head\n moving_counter = 0\n while moving_counter < mid_val:\n temp = temp.next\n moving_counter += 1\n prev = prev.next\n prev.next = head\n second_head = temp\n while temp.next is not head:\n temp = temp.next\n temp.next = second_head\n head1 = head\n head2 = second_head\n return (head1, head2)", "def splitList(head, head1, head2):\n if head is None:\n return (None, None)\n count = 1\n temp = head\n while temp.next is not head:\n count += 1\n temp = temp.next\n mid = count // 2\n if count % 2 != 0:\n mid += 1\n temp2 = head\n while mid != 1:\n temp2 = temp2.next\n mid -= 1\n head2 = temp2.next\n temp.next = head2\n temp2.next = head\n head1 = head\n return (head1, head2)", "def splitList(head, head1, head2):\n x = head\n y = head\n z = head.next\n pre = x\n pre1 = y\n while True:\n pre = x\n pre1 = y\n x = x.next\n y = y.next.next\n if y == head:\n pre1.next.next = x\n break\n if y == z:\n pre1.next = x\n break\n pre.next = head\n head1 = head\n head2 = x\n return (head1, head2)", "def splitList(head, head1, head2):\n curr = head.next\n n = 0\n while True:\n if curr != head:\n n += 1\n else:\n n += 1\n break\n curr = curr.next\n if n % 2 == 0:\n curr = head\n i = 1\n while i < n // 2:\n curr = curr.next\n i += 1\n head1 = head\n head2 = curr.next\n curr.next = head1\n curr = head2\n i = 1\n while i < n // 2:\n curr = curr.next\n i += 1\n curr.next = head2\n else:\n curr = head\n i = 1\n while i <= n // 2:\n curr = curr.next\n i += 1\n head1 = head\n head2 = curr.next\n curr.next = head1\n curr = head2\n i = 1\n while i < n // 2:\n curr = curr.next\n i += 1\n curr.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n head1 = head\n i = 2\n while head.next is not head1:\n head = head.next\n i += 1\n n = i // 2\n for _ in range(n):\n head = head.next\n head2 = head.next\n head.next = head1\n head = head2\n while head.next is not head1:\n head = head.next\n head.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n s = f = head\n if head.next == head or head == None:\n head1 = head\n head2 = None\n return (head1, head2)\n while f.next != head and f.next.next != head:\n s = s.next\n f = f.next.next\n mid = s\n head1 = head\n h2 = head2 = mid.next\n mid.next = head1\n temp = head\n while h2.next != head:\n h2 = h2.next\n h2.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n ptr = head\n count = 0\n while ptr.next != head:\n count += 1\n ptr = ptr.next\n count += 1\n mid = (count - 1) // 2\n head1 = head\n ptr = head\n while mid:\n ptr = ptr.next\n mid -= 1\n head2 = ptr.next\n ptr.next = head1\n ptr = head2\n while ptr.next != head:\n ptr = ptr.next\n ptr.next = head2\n return (head1, head2)", "def splitList(head, head1, head2):\n temp = head\n head1 = head\n count = 1\n while temp.next != head:\n count += 1\n temp = temp.next\n temp.next = None\n temp = head\n c = count // 2\n while c - 1:\n temp = temp.next\n c -= 1\n if count % 2 == 0:\n head2 = temp.next\n temp.next = head1\n else:\n head2 = temp.next.next\n temp.next.next = head1\n temp = head2\n while temp.next:\n temp = temp.next\n temp.next = head2\n return (head1, head2)"], "starter_code": "def __init__(self):\n", "input_output": {"inputs": ["Circular LinkedList:1->5->7", "Circular LinkedList:2->6->1->5"], "outputs": ["1 5\n7", "2 6\n1 5"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "circular-linked-list", "Linked List"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/split-a-circular-linked-list-into-two-halves/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "__init__", "task_id": "TACO_lite/426", "example": [[], []]} +{"requirement": "Given an integer N, find it's parity. \nParity of a number refers to the number of 1 bits it contains. The number has \u201codd parity\u201d, if it contains odd number of 1-bits and is \u201ceven parity\u201d if it contains even number of 1-bits.\nExample 1:\nInput:\nN = 13\nOutput: odd\nExplanation:\n(13)_{10} = (1101)_{2} The binary representation\nhas three 1-bits. So, it's parity is odd.\nExample 2:\nInput:\nN = 9\nOutput: even\nExplanation:\n(9)_{10} = (1001)_{2} The binary representation\nhas two 1-bits. So, it's parity is even.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function computeParity() which takes an Integer N as input parameter and returns string \"odd\" or \"even\".\n \nExpected Time Complexity: O(log(N))\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= N <= 10^{5}", "solutions": ["def computeparity(N):\n x = bin(N)[2:]\n a = x.count('1')\n if a % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n one = 0\n while N != 0:\n one += 1\n N &= N - 1\n if one & 1 == 1:\n return 'odd'\n return 'even'", "def computeparity(N):\n t = format(N, 'b')\n sum = 0\n for i in t:\n if i == '1':\n sum = sum + 1\n if sum % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n ans = 0\n while N:\n ans += 1\n N &= N - 1\n return 'odd' if ans % 2 else 'even'", "def computeparity(N):\n N = bin(N)[2:]\n if N.count('1') % 2 == 1:\n return 'odd'\n return 'even'", "def computeparity(N):\n summa = sum((item == '1' for item in bin(N)[2:]))\n return 'odd' if summa % 2 else 'even'", "def computeparity(N):\n N ^= N >> 16\n N ^= N >> 8\n N ^= N >> 4\n N ^= N >> 2\n N ^= N >> 1\n return 'odd' if N & 1 else 'even'", "def computeparity(N):\n c = 0\n while N != 0:\n if N % 2 != 0:\n c += 1\n N = N >> 1\n if c % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n a = str(bin(N).replace('0b', ''))\n b = a.count('1') % 2\n if b == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n result = 0\n while N:\n N &= N - 1\n result ^= 1\n return 'odd' if result else 'even'", "def computeparity(N):\n m = bin(N).replace('0b', '')\n p = m.count('1')\n if p % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(n):\n count = 0\n while n:\n n = n & n - 1\n count += 1\n if count & 1 == 1:\n return 'odd'\n return 'even'", "def computeparity(N):\n count = 0\n while N > 0:\n if N % 2 == 1:\n count += 1\n N = int(N / 2)\n if count % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n c = 0\n n = bin(N)[2:]\n for i in n:\n if i == '1':\n c += 1\n if c % 2:\n return 'odd'\n return 'even'", "def computeparity(N):\n b = bin(N)[2:]\n count = b.count('1')\n return 'odd' if count % 2 != 0 else 'even'", "def computeparity(N):\n binary = str(bin(N))\n count_1_bits = binary.count('1')\n if count_1_bits % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n N = bin(N)[2:]\n x = str(N)\n y = x.count('1')\n if y % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n res = 0\n N ^= N >> 32\n N ^= N >> 16\n N ^= N >> 8\n N ^= N >> 4\n N ^= N >> 2\n N ^= N >> 1\n res = N & 1\n if res % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def __init__():\n self.TABLE_BITS = 4\n self.table = 0\n for i in range(1 << self.TABLE_BITS):\n if self.parity(i):\n self.table |= 1 << i\n self.mask = (1 << self.TABLE_BITS) - 1\n\ndef parity(n):\n odd = False\n while n & -n:\n odd = not odd\n n &= n - 1\n return odd\n\ndef computeparity(N):\n odd = False\n while N:\n if self.table & 1 << (N & self.mask):\n odd = not odd\n N >>= self.TABLE_BITS\n if odd:\n return 'odd'\n return 'even'", "def computeparity(N):\n odd = False\n while N:\n odd = not odd\n N &= N - 1\n if odd:\n return 'odd'\n return 'even'", "def computeparity(n):\n n ^= n >> 32\n n ^= n >> 16\n n ^= n >> 8\n n ^= n >> 4\n n ^= n >> 2\n n ^= n >> 1\n if n & 1 == 1:\n return 'odd'\n else:\n return 'even'", "def computeparity(N):\n count = self.countOnes(N)\n return 'odd' if count & 1 else 'even'\n\ndef countOnes(N):\n count = 0\n while N:\n if N & 1:\n count += 1\n N = N >> 1\n return count", "def computeparity(N):\n s = bin(N)\n c = 0\n i = 0\n while i < len(s):\n if s[i] == '1':\n c += 1\n i += 1\n if c % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n repr = list(bin(N))[2:]\n return 'even' if repr.count('1') % 2 == 0 else 'odd'", "def computeparity(N):\n binary_N = bin(N)\n count = 0\n for l in binary_N:\n if l == '1':\n count += 1\n if count % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n A = bin(N)\n B = str(A).count('1')\n if B % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n temp = N\n parity = 0\n while temp > 0:\n if temp % 2 == 1:\n parity += 1\n temp //= 2\n if parity % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n arr = []\n while N:\n arr.append(N % 2)\n N //= 2\n c = 0\n for i in range(len(arr)):\n if arr[i] == 1:\n c += 1\n if c % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n x = bin(N).replace('0b', '')\n if x.count('1') % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n c = []\n while N > 0:\n a = N % 2\n c.append(a)\n N = N // 2\n if c.count(1) % 2 == 1:\n return 'odd'\n return 'even'", "def computeparity(N):\n binary_rep = str(bin(N)).replace('0b', '')\n number_of_ones = 0\n for digit in binary_rep:\n if digit == '1':\n number_of_ones += 1\n if number_of_ones & 1 == 1:\n return 'odd'\n return 'even'", "def computeparity(N):\n x = str('{0:b}'.format(int(N)))\n count = x.count('1')\n if count % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n dec = self.decimal(N)\n count = 0\n for i in str(dec):\n if i == '1':\n count += 1\n if count % 2 == 0:\n return 'even'\n return 'odd'\n\ndef decimal(N):\n return bin(N).replace('0b', '')", "def computeparity(N):\n b = bin(N)\n s = str(b)\n if s.count('1') % 2 == 0:\n return 'even'\n return 'odd'", "def computeparity(N):\n parity = 0\n n = N\n while n > 0:\n if n & 1 == 1:\n parity = ~parity\n n = n >> 1\n if parity == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n c = 0\n x = bin(N)\n for i in x:\n if i == '1':\n c += 1\n else:\n continue\n if c % 2 == 0:\n return 'even'\n elif c % 2 != 0:\n return 'odd'", "def computeparity(N):\n count = 0\n s = bin(N).replace('0b', '')\n for i in s:\n if i == '1':\n count += 1\n if count % 2 == 0:\n return 'even'\n else:\n return 'odd'", "def computeparity(N):\n return 'even' if sum(list(map(int, bin(N)[2:]))) % 2 == 0 else 'odd'", "def computeparity(N):\n Count = 0\n even1 = 'even'\n odd1 = 'odd'\n while N:\n if N & 1 == 1:\n Count += 1\n N = N >> 1\n if Count % 2 == 0:\n return even1\n else:\n return odd1"], "starter_code": "def computeparity(N):\n", "input_output": {"inputs": ["N = 13", "N = 9"], "outputs": ["odd", "even"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Algorithms", "Bit Magic", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures", "Mathematics"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/parity-of-unsigned-integer4247/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(N))", "entry_point": "computeparity", "task_id": "TACO_lite/401", "example": [[], []]} +{"requirement": "##Task:\n\nYou have to write a function **pattern** which creates the following pattern upto n number of rows. *If the Argument is 0 or a Negative Integer then it should return \"\" i.e. empty string.*\n\n##Pattern:\n\n (n)\n (n)(n-1)\n (n)(n-1)(n-2)\n ................\n .................\n (n)(n-1)(n-2)....4\n (n)(n-1)(n-2)....43\n (n)(n-1)(n-2)....432\n (n)(n-1)(n-2)....4321\n \n##Examples:\n\npattern(4):\n\n 4\n 43\n 432\n 4321\n \npattern(6):\n \n 6\n 65\n 654\n 6543\n 65432\n 654321\n\n\n\n```Note: There are no blank spaces```\n\n```Hint: Use \\n in string to jump to next line```", "solutions": ["def pattern(n):\n return '\\n'.join((''.join((str(i) for i in range(n, j, -1))) for j in range(n - 1, -1, -1)))", "def pattern(n):\n full = [str(x) for x in range(n, 0, -1)]\n take = lambda x: ''.join(full[:x])\n return '\\n'.join((take(x) for x in range(1, n + 1)))", "pattern = lambda n: '\\n'.join((''.join((str(n - j) for j in range(i + 1))) for i in range(n)))", "def pattern(n):\n a = [str(i) for i in range(n, 0, -1)]\n return '\\n'.join((''.join(a[:i]) for i in range(1, n + 1)))", "def pattern(n):\n return '\\n'.join([''.join([str(y) for y in range(n, n - x - 1, -1)]) for x in range(n)])", "def pattern(n):\n (out, s) = ([], '')\n for i in reversed(range(1, n + 1)):\n s += str(i)\n out.append(s)\n return '\\n'.join(out)", "def pattern(n):\n return '\\n'.join([''.join(map(str, list(range(n, n - i, -1)))) for i in range(1, n + 1)])"], "starter_code": "def pattern(n):\n", "input_output": {"fn_name": "pattern", "inputs": [[1], [2], [5], [0], [-25]], "outputs": [["1"], ["2\n21"], ["5\n54\n543\n5432\n54321"], [""], [""]]}, "difficulty": "EASY", "raw_tags": ["ASCII Art", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/557341907fbf439911000022", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "pattern", "task_id": "TACO_lite/353", "example": [[], []]} +{"requirement": "Return the century of the input year. The input will always be a 4 digit string, so there is no need for validation. \n\n### Examples\n```\n\"1999\" --> \"20th\"\n\"2011\" --> \"21st\"\n\"2154\" --> \"22nd\"\n\"2259\" --> \"23rd\"\n\"1124\" --> \"12th\"\n\"2000\" --> \"20th\"\n```", "solutions": ["def what_century(year):\n n = (int(year) - 1) // 100 + 1\n return str(n) + ('th' if n < 20 else {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th'))", "def what_century(year):\n year = str(year)\n st = year[:2]\n st = int(st)\n gt = st + 1\n gt = str(gt)\n if year != '0000' and year[1:] != '000' and (year[2:] != '00'):\n if len(gt) == 2:\n if gt[0] == '1' and gt[1] == '0':\n return '10th'\n elif gt[0] == '1' and gt[1] in range(1, 10):\n return f'{gt}th'\n elif gt[0] != '1' and gt[1] == '0':\n return f'{gt}th'\n elif gt[0] != '1' and gt[1] == '1':\n return f'{gt}st'\n elif gt[0] != '1' and gt[1] == '2':\n return f'{gt}nd'\n elif gt[0] != '1' and gt[1] == '3':\n return f'{gt}rd'\n else:\n return f'{gt}th'\n elif gt[0] == 1:\n return '1st'\n elif gt[0] == 2:\n return '2nd'\n elif gt[0] == 3:\n return '3rd'\n else:\n return f'{gt}th'\n elif year[1:] == '000' and year != '0000':\n return f'{year[0]}0th'\n elif year[2:] == '00' and year[1:] != '000' and (year != '0000'):\n if year[1] == '1':\n return f'{year[:2]}st'\n elif year[2] == '2':\n return f'{year[:2]}nd'\n elif year[2] == '3':\n return f'{year[:2]}rd'\n else:\n return f'{year[:2]}th'\n elif year == '0000':\n return '0th'", "def what_century(year):\n if 100 >= int(year) > 0:\n return '1st'\n if 200 >= int(year) > 100:\n return '2nd'\n if 300 >= int(year) > 200:\n return '3rd'\n if 400 >= int(year) > 300:\n return '4th'\n if 500 >= int(year) > 400:\n return '5th'\n if 600 >= int(year) > 500:\n return '6th'\n if 700 >= int(year) > 600:\n return '7th'\n if 800 >= int(year) > 700:\n return '8th'\n if 900 >= int(year) > 800:\n return '9th'\n if 1000 >= int(year) > 900:\n return '10th'\n if 1100 >= int(year) > 1000:\n return '11th'\n if 1200 >= int(year) > 1100:\n return '12th'\n if 1300 >= int(year) > 1200:\n return '13th'\n if 1400 >= int(year) > 1300:\n return '14th'\n if 1500 >= int(year) > 1400:\n return '15th'\n if 1600 >= int(year) > 1500:\n return '16th'\n if 1700 >= int(year) > 1600:\n return '17th'\n if 1800 >= int(year) > 1700:\n return '18th'\n if 1900 >= int(year) > 1800:\n return '19th'\n if 2000 >= int(year) > 1900:\n return '20th'\n if 2100 >= int(year) > 2000:\n return '21st'\n if 2200 >= int(year) > 2100:\n return '22nd'\n if 2300 >= int(year) > 2200:\n return '23rd'\n if 2400 >= int(year) > 2300:\n return '24th'\n if 2500 >= int(year) > 2400:\n return '25th'\n if 2600 >= int(year) > 2500:\n return '26th'\n if 2700 >= int(year) > 2600:\n return '27th'\n if 2800 >= int(year) > 2700:\n return '28th'\n if 2900 >= int(year) > 2800:\n return '29th'\n if 3000 >= int(year) > 2900:\n return '30th'\n if 3100 >= int(year) > 3000:\n return '31st'\n if 3200 >= int(year) > 3100:\n return '32nd'\n if 3300 >= int(year) > 3200:\n return '33rd'\n if 3400 >= int(year) > 3300:\n return '34th'\n if 3500 >= int(year) > 3400:\n return '35th'\n if 3600 >= int(year) > 3500:\n return '36th'\n if 3700 >= int(year) > 3600:\n return '37th'\n if 3800 >= int(year) > 3700:\n return '38th'\n if 3900 >= int(year) > 3800:\n return '39th'\n if 4000 >= int(year) > 3900:\n return '40th'\n if 4100 >= int(year) > 4000:\n return '41st'\n if 4200 >= int(year) > 4100:\n return '42nd'\n if 4300 >= int(year) > 4200:\n return '43rd'\n if 4400 >= int(year) > 4300:\n return '44th'\n if 4500 >= int(year) > 4400:\n return '45th'\n if 4600 >= int(year) > 4500:\n return '46th'\n if 4700 >= int(year) > 4600:\n return '47th'\n if 4800 >= int(year) > 4700:\n return '48th'\n if 4900 >= int(year) > 4800:\n return '49th'\n if 5000 >= int(year) > 4900:\n return '50th'\n if 5100 >= int(year) > 5000:\n return '51st'\n if 5200 >= int(year) > 5100:\n return '52nd'\n if 5300 >= int(year) > 5200:\n return '53rd'\n if 5400 >= int(year) > 5300:\n return '54th'\n if 5500 >= int(year) > 5400:\n return '55th'\n if 5600 >= int(year) > 5500:\n return '56th'\n if 5700 >= int(year) > 5600:\n return '57th'\n if 5800 >= int(year) > 5700:\n return '58th'\n if 5900 >= int(year) > 5800:\n return '59th'\n if 6000 >= int(year) > 5900:\n return '60th'\n if 6100 >= int(year) > 6000:\n return '61st'\n if 6200 >= int(year) > 6100:\n return '62nd'\n if 6300 >= int(year) > 6200:\n return '63rd'\n if 6400 >= int(year) > 6300:\n return '64th'\n if 6500 >= int(year) > 6400:\n return '65th'\n if 6600 >= int(year) > 6500:\n return '66th'\n if 6700 >= int(year) > 6600:\n return '67th'\n if 6800 >= int(year) > 6700:\n return '68th'\n if 6900 >= int(year) > 6800:\n return '69th'\n if 7000 >= int(year) > 6900:\n return '70th'\n if 7100 >= int(year) > 7000:\n return '71st'\n if 7200 >= int(year) > 7100:\n return '72nd'\n if 7300 >= int(year) > 7200:\n return '73rd'\n if 7400 >= int(year) > 7300:\n return '74th'\n if 7500 >= int(year) > 7400:\n return '75th'\n if 7600 >= int(year) > 7500:\n return '76th'\n if 7700 >= int(year) > 7600:\n return '77th'\n if 7800 >= int(year) > 7700:\n return '78th'\n if 7900 >= int(year) > 7800:\n return '79th'\n if 8000 >= int(year) > 7900:\n return '80th'\n if 8100 >= int(year) > 8000:\n return '81st'\n if 8200 >= int(year) > 8100:\n return '82nd'\n if 8300 >= int(year) > 8200:\n return '83rd'\n if 8400 >= int(year) > 8300:\n return '84th'\n if 8500 >= int(year) > 8400:\n return '85th'\n if 8600 >= int(year) > 8500:\n return '86th'\n if 8700 >= int(year) > 8600:\n return '87th'\n if 8800 >= int(year) > 8700:\n return '88th'\n if 8900 >= int(year) > 8800:\n return '89th'\n if 9000 >= int(year) > 8900:\n return '90th'\n if 9100 >= int(year) > 9000:\n return '91st'\n if 9200 >= int(year) > 9100:\n return '92nd'\n if 9300 >= int(year) > 9200:\n return '93rd'\n if 9400 >= int(year) > 9300:\n return '94th'\n if 9500 >= int(year) > 9400:\n return '95th'\n if 9600 >= int(year) > 9500:\n return '96th'\n if 9700 >= int(year) > 9600:\n return '97th'\n if 9800 >= int(year) > 9700:\n return '98th'\n if 9900 >= int(year) > 9800:\n return '99th'\n if 10000 >= int(year) > 9900:\n return '100th'", "def what_century(year):\n ordinal = lambda n: '%d%s' % (n, 'tsnrhtdd'[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10::4])\n return ordinal((int(year) - 1) // 100 + 1)", "def what_century(year):\n if year[2:] == '00':\n century = year[:2]\n else:\n century = str(int(year) // 100 + 1)\n suffix = 'th'\n if century[0] == '1':\n pass\n elif century[1] == '1':\n suffix = 'st'\n elif century[1] == '2':\n suffix = 'nd'\n elif century[1] == '3':\n suffix = 'rd'\n return century + suffix", "def what_century(year):\n y = int(year)\n (c, r) = divmod(y, 100)\n if r:\n c += 1\n ones = c % 10\n tens = c // 10 % 10\n if tens == 1:\n suffix = 'th'\n elif ones == 1:\n suffix = 'st'\n elif ones == 2:\n suffix = 'nd'\n elif ones == 3:\n suffix = 'rd'\n else:\n suffix = 'th'\n return str(c) + suffix", "SUFFIX_ONE = 'st'\nSUFFIX_TWO = 'nd'\nSUFFIX_THREE = 'rd'\nSUFFIX_OTHER = 'th'\n\ndef what_century(year):\n century = 1 + (int(year) - 1) // 100\n return str(century) + ordinal_suffix(century)\n\ndef ordinal_suffix(number):\n if number // 10 == 1:\n return SUFFIX_OTHER\n elif number % 10 == 1:\n return SUFFIX_ONE\n elif number % 10 == 2:\n return SUFFIX_TWO\n elif number % 10 == 3:\n return SUFFIX_THREE\n else:\n return SUFFIX_OTHER", "def what_century(year):\n year = int(year)\n output_century = year // 100\n ordinal = ''\n if year % 100 > 0:\n output_century += 1\n if output_century > 10 and output_century < 14:\n ordinal = 'th'\n elif output_century % 10 == 1:\n ordinal = 'st'\n elif output_century % 10 == 2:\n ordinal = 'nd'\n elif output_century % 10 == 3:\n ordinal = 'rd'\n else:\n ordinal = 'th'\n return str(output_century) + ordinal"], "starter_code": "def what_century(year):\n", "input_output": {"fn_name": "what_century", "inputs": [["1999"]], "outputs": [["20th"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms", "Date Time"], "name": null, "source": "codewars", "tags": ["String algorithms"], "skill_types": [], "url": "https://www.codewars.com/kata/52fb87703c1351ebd200081f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "what_century", "task_id": "TACO_lite/417", "example": [[["1999"], ["2011"], ["2154"], ["2259"], ["1124"], ["2000"]], ["20th", "21st", "22nd", "23rd", "12th", "20th"]]} +{"requirement": "Write\n\n```python\nfunction combine()\n```\n\nthat combines arrays by alternatingly taking elements passed to it.\n\nE.g\n\n```python\ncombine(['a', 'b', 'c'], [1, 2, 3]) == ['a', 1, 'b', 2, 'c', 3]\ncombine(['a', 'b', 'c'], [1, 2, 3, 4, 5]) == ['a', 1, 'b', 2, 'c', 3, 4, 5]\ncombine(['a', 'b', 'c'], [1, 2, 3, 4, 5], [6, 7], [8]) == ['a', 1, 6, 8, 'b', 2, 7, 'c', 3, 4, 5]\n```\n\nArrays can have different lengths.", "solutions": ["def combine(*args):\n out = list()\n for i in range(len(max(args, key=len))):\n for arr in args:\n if i < len(arr):\n out.append(arr[i])\n return out", "from itertools import chain, zip_longest\n\ndef combine(*args):\n return [x for x in chain.from_iterable(zip_longest(*args)) if x is not None]", "def combine(*args):\n res = []\n num_of_args = len(args)\n len_of_longest_list = max([len(l) for l in args])\n for i in range(len_of_longest_list):\n for j in range(num_of_args):\n if len(args[j]) > i:\n res.append(args[j][i])\n return res", "combine = lambda *args: [el[0] for el in args] + combine(*[el[1:] for el in args if len(el) > 1]) if args else []", "from copy import deepcopy\n\ndef combine(*args):\n if not args:\n return []\n args_list = list(deepcopy(args))\n first = args_list.pop(0)\n head = first.pop(0)\n if first:\n args_list.append(first)\n return [head] + combine(*tuple(args_list))", "from itertools import zip_longest\n\ndef combine(*args):\n return [y for x in zip_longest(*args) for y in list(x) if y is not None]", "def combine(*args):\n result = []\n l = len(max(args, key=len))\n for loop in range(l):\n result.extend((array[loop] for array in args if len(array) > loop))\n return result", "def combine(*args):\n L = max((len(i) for i in args))\n t = []\n j = 0\n while j < L:\n for i in args:\n try:\n t.append(i[j])\n except:\n pass\n j += 1\n return t", "def combine(*args):\n result = []\n args_length = len(args)\n max_len_list = max([len(l) for l in args])\n for i in range(max_len_list):\n for j in range(args_length):\n if len(args[j]) > i:\n result.append(args[j][i])\n return result"], "starter_code": "def combine(*args):\n", "input_output": {"fn_name": "combine", "inputs": [[["a", "b", "c"], [1, 2, 3]], [["a", "b", "c"], [1, 2, 3, 4, 5]], [["a", "b", "c"], [1, 2, 3, 4, 5], [6, 7], [8]], [[{"a": 1}, {"b": 2}], [1, 2]], [[{"a": 2, "b": 1}, {"a": 1, "b": 2}], [1, 2, 3, 4], [5, 6], [7]]], "outputs": [[["a", 1, "b", 2, "c", 3]], [["a", 1, "b", 2, "c", 3, 4, 5]], [["a", 1, 6, 8, "b", 2, 7, "c", 3, 4, 5]], [[{"a": 1}, 1, {"b": 2}, 2]], [[{"a": 2, "b": 1}, 1, 5, 7, {"a": 1, "b": 2}, 2, 6, 3, 4]]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/55e529bf6c6497394a0000b5", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "combine", "task_id": "TACO_lite/200", "example": [[[["a", "b", "c"], [1, 2, 3]], [["a", "b", "c"], [1, 2, 3, 4, 5]], [["a", "b", "c"], [1, 2, 3, 4, 5], [6, 7], [8]]], ["['a', 1, 'b', 2, 'c', 3]", "['a', 1, 'b', 2, 'c', 3, 4, 5]", "['a', 1, 6, 8, 'b', 2, 7, 'c', 3, 4, 5]"]]} +{"requirement": "For building the encrypted string:Take every 2nd char from the string, then the other chars, that are not every 2nd char, and concat them as new String.\nDo this n times!\n\nExamples:\n```\n\"This is a test!\", 1 -> \"hsi etTi sats!\"\n\"This is a test!\", 2 -> \"hsi etTi sats!\" -> \"s eT ashi tist!\"\n```\n\nWrite two methods:\n```python\ndef encrypt(text, n)\ndef decrypt(encrypted_text, n)\n```\n\n```Fsharp\nlet encrypt (str:string) (n:int) -> string\nlet decrypt (str:string) (n:int) -> string\n```\n\nFor both methods:\nIf the input-string is null or empty return exactly this value!\nIf n is <= 0 then return the input text.\n\nThis kata is part of the Simple Encryption Series:\nSimple Encryption #1 - Alternating Split\nSimple Encryption #2 - Index-Difference\nSimple Encryption #3 - Turn The Bits Around\nSimple Encryption #4 - Qwerty\n\nHave fun coding it and please don't forget to vote and rank this kata! :-)", "solutions": ["def decrypt(text, n):\n if text in ('', None):\n return text\n ndx = len(text) // 2\n for i in range(n):\n a = text[:ndx]\n b = text[ndx:]\n text = ''.join((b[i:i + 1] + a[i:i + 1] for i in range(ndx + 1)))\n return text\n\ndef encrypt(text, n):\n for i in range(n):\n text = text[1::2] + text[::2]\n return text", "def decrypt(s, n):\n if not s:\n return s\n (o, l) = (len(s) // 2, list(s))\n for _ in range(n):\n (l[1::2], l[::2]) = (l[:o], l[o:])\n return ''.join(l)\n\ndef encrypt(s, n):\n if not s:\n return s\n for _ in range(n):\n s = s[1::2] + s[::2]\n return s", "def decrypt(text, n):\n if not text:\n return text\n half = len(text) // 2\n arr = list(text)\n for _ in range(n):\n (arr[1::2], arr[::2]) = (arr[:half], arr[half:])\n return ''.join(arr)\n\ndef encrypt(text, n):\n for i in range(n):\n text = text[1::2] + text[::2]\n return text", "def encrypt_once(s):\n (h, t) = ('', '')\n for i in range(len(s)):\n if i % 2 == 0:\n h += s[i]\n else:\n t += s[i]\n return t + h\n\ndef decrypt_once(s):\n i = len(s) // 2\n j = 0\n result = ''\n for k in range(len(s)):\n if k % 2 == 0:\n result += s[i]\n i += 1\n else:\n result += s[j]\n j += 1\n return result\n\ndef decrypt(text, n):\n if not text or len(text) == 0 or n <= 0:\n return text\n for i in range(n):\n text = decrypt_once(text)\n return text\n\ndef encrypt(text, n):\n if not text or len(text) == 0 or n <= 0:\n return text\n for i in range(n):\n text = encrypt_once(text)\n return text", "def decrypt(encrypted_text, n):\n if n < 1:\n return encrypted_text\n half_len = len(encrypted_text) // 2\n (left, right) = (encrypted_text[:half_len], encrypted_text[half_len:])\n encrypted_text = [''.join(i) for i in zip(right, left)]\n if len(right) > half_len:\n encrypted_text += right[-1]\n return decrypt(''.join(encrypted_text), n - 1)\n\ndef encrypt(text, n):\n if n < 1:\n return text\n for _ in range(n):\n text = text[1::2] + text[0::2]\n return text", "def decrypt(text, n):\n if text:\n mid = len(text) // 2\n for _ in range(n):\n text = ''.join(sum(zip(text[mid:], list(text[:mid]) + ['']), ()))\n return text\n\ndef encrypt(text, n):\n if text:\n for _ in range(n):\n text = text[1::2] + text[::2]\n return text", "def decrypt(text, n):\n if text == None:\n return text\n decodeList = encrypt(list(range(len(text))), n)\n return ''.join((text[decodeList.index(i)] for i in range(len(text))))\n\ndef encrypt(text, n):\n if text == None:\n return text\n return encrypt(text[1::2] + text[0::2], n - 1) if n > 0 else text", "from itertools import zip_longest\n\ndef encrypt(text, n):\n s = text\n if s:\n for _ in range(n):\n s = s[1::2] + s[::2]\n return s\n\ndef decrypt(encrypted_text, n):\n s = encrypted_text\n if s:\n m = len(s) // 2\n for _ in range(n):\n s = ''.join((c for s in zip_longest(s[m:], s[:m], fillvalue='') for c in s))\n return s"], "starter_code": "def decrypt(text, n):\n", "input_output": {"fn_name": "decrypt", "inputs": [["This is a test!", 0], ["hsi etTi sats!", 1], ["s eT ashi tist!", 2], [" Tah itse sits!", 3], ["This is a test!", 4], ["This is a test!", -1], ["hskt svr neetn!Ti aai eyitrsig", 1], ["", 0], [null, 0]], "outputs": [["This is a test!"], ["This is a test!"], ["This is a test!"], ["This is a test!"], ["This is a test!"], ["This is a test!"], ["This kata is very interesting!"], [""], [null]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Cryptography", "Fundamentals", "Strings", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57814d79a56c88e3e0000786", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "decrypt", "task_id": "TACO_lite/372", "example": [[["This is a test!", 1], ["This is a test!", 2]], [" Tah itse sits!", "s eT ashi tist!"]]} +{"requirement": "Given a non-negative\u00a0index k\u00a0where k \u2264\u00a033, return the kth\u00a0index row of the Pascal's triangle.\n\nNote that the row index starts from\u00a00.\n\n\nIn Pascal's triangle, each number is the sum of the two numbers directly above it.\n\nExample:\n\n\nInput: 3\nOutput: [1,3,3,1]\n\n\nFollow up:\n\nCould you optimize your algorithm to use only O(k) extra space?", "solutions": ["def getrow(k):\n res = [1]\n cur = k\n for i in range(k // 2):\n res += (res[-1] * cur // (i + 1),)\n cur -= 1\n if k % 2 == 0:\n res = res + res[:-1][::-1]\n else:\n res = res + res[::-1]\n return res", "def getrow(rowIndex):\n a = [1]\n i = 0\n b = [1]\n while i < rowIndex:\n a.append(0)\n b = a[:]\n for j in range(i + 2):\n b[j] = a[j] + a[i - j + 1]\n a = b\n i += 1\n return b", "def getrow(rowIndex):\n res = [1]\n for i in range(1, rowIndex + 1):\n res += [1]\n for j in range(len(res) - 2, -1, -1):\n if j > 0:\n res[j] = res[j] + res[j - 1]\n else:\n res[j] = 1\n return res", "def getrow(rowIndex):\n out = [1]\n for i in range(1, rowIndex + 1):\n temp = []\n for j in range(0, i - 1):\n temp.append(out[j] + out[j + 1])\n out = [1] + temp + [1]\n return out", "def getrow(rowIndex):\n l = [1]\n for i in range(rowIndex):\n l = [j + k for (j, k) in zip([0] + l, l + [0])]\n return l", "def getrow(rowIndex):\n result = []\n for n in range(rowIndex + 1):\n num = 1\n for i in range(n):\n num = int(num * (rowIndex - i) / (i + 1))\n result = result + [num]\n return result", "def getrow(rowIndex):\n if rowIndex < 0:\n return list()\n if rowIndex == 0:\n return list([1])\n l = list([1])\n for i in range(1, rowIndex + 1):\n pre_value = l[0]\n for j in range(1, i):\n temp = l[j]\n l[j] = pre_value + l[j]\n pre_value = temp\n l.append(1)\n return l", "def getrow(rowIndex):\n rows = [1]\n for i in range(rowIndex):\n rows = [x + y for (x, y) in zip([0] + rows, rows + [0])]\n return rows", "def getrow(rowIndex):\n row = [1]\n for _ in range(rowIndex):\n row = [x + y for (x, y) in zip([0] + row, row + [0])]\n return row", "def getrow(rowIndex):\n if rowIndex < 0:\n return []\n result = [0 for _ in range(rowIndex + 1)]\n result[0] = 1\n for i in range(1, rowIndex + 1):\n result[i] = 1\n for j in range(i - 1, 0, -1):\n result[j] = result[j] + result[j - 1]\n return result", "def getrow(rowIndex):\n i = 1\n res = [1]\n while rowIndex >= 1:\n res.append(int(res[-1] * rowIndex / i))\n (rowIndex, i) = (rowIndex - 1, i + 1)\n return res"], "starter_code": "def getrow(rowIndex: int) -> List[int]:\n", "input_output": {"fn_name": "getRow", "inputs": [[3], [0], [1]], "outputs": [[1, 3, 3, 1], [1], [1, 1]]}, "difficulty": "EASY", "raw_tags": ["Array", "Dynamic Programming"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://leetcode.com/problems/pascals-triangle-ii/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "getrow", "task_id": "TACO_lite/451", "example": [[[3]], ["[1, 3, 3, 1]"]]} +{"requirement": "The vowel substrings in the word `codewarriors` are `o,e,a,io`. The longest of these has a length of 2. Given a lowercase string that has alphabetic characters only (both vowels and consonants) and no spaces, return the length of the longest vowel substring.\nVowels are any of `aeiou`. \n\n\n```if:csharp\nDocumentation:\nKata.Solve Method (String)\n\nReturns the length of the greatest continuous vowel substring in a string.\n\nSyntax\n\n\npublic\nstatic\nint Solve(\nstring str\n \u00a0\u00a0)\n \n\n\nParameters\n\nstr\n\nType: System.String\nThe string to be processed.\n\nReturn Value\n\nType: System.Int32\n The length of the greatest continuous vowel substring in str, or 0 if str contains no vowels.\n\n\nExceptions\n\n\n\nException\nCondition\n\nArgumentNullException\nstr is null.\n\n\n\n\n```\n\n\nGood luck!\n\nIf you like substring Katas, please try:\n\n[Non-even substrings](https://www.codewars.com/kata/59da47fa27ee00a8b90000b4)\n\n[Vowel-consonant lexicon](https://www.codewars.com/kata/59cf8bed1a68b75ffb000026)", "solutions": ["def solve(s):\n return max(map(len, ''.join((c if c in 'aeiou' else ' ' for c in s)).split()))", "import re\n\ndef solve(s):\n return max((len(x.group(0)) for x in re.finditer('[aeiou]+', s)))", "from re import findall\n\ndef solve(s):\n return max(map(len, findall('[aeiou]+', s)))", "def solve(s):\n vowels = 'aeiou'\n max_len = 0\n tmp_len = 0\n prev_vowel = False\n for c in s:\n max_len = max(max_len, tmp_len)\n if not prev_vowel:\n tmp_len = 0\n if c in vowels:\n tmp_len += 1\n prev_vowel = c in vowels\n return max_len", "def solve(s):\n return max((len(w) for w in ''.join(([' ', c][c in 'aeiou'] for c in s)).split()))", "import re\n\ndef solve(s):\n return max(map(len, re.findall('[uoiae]+', s)))", "import re\n\ndef solve(s):\n return len(max(re.findall('[aeiou]+', s), key=len, default=''))", "from itertools import groupby\n\ndef solve(s):\n return max((sum((1 for _ in g)) for (k, g) in groupby(s, 'aeiou'.__contains__) if k))", "def solve(s):\n for x in s:\n if x not in 'aeiou':\n s = s.replace(x, ' ')\n s = s.split()\n a = [len(x) for x in s]\n return max(a)", "from re import compile\nr = compile('[aeiou]+')\n\ndef solve(s: str):\n return max(list(map(len, r.findall(s))))"], "starter_code": "def solve(s):\n", "input_output": {"fn_name": "solve", "inputs": [["codewarriors"], ["suoidea"], ["ultrarevolutionariees"], ["strengthlessnesses"], ["cuboideonavicuare"], ["chrononhotonthuooaos"], ["iiihoovaeaaaoougjyaw"]], "outputs": [[2], [3], [3], [1], [2], [5], [8]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/59c5f4e9d751df43cf000035", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/448", "example": [[], []]} +{"requirement": "In this Kata, you will be given an array of strings and your task is to remove all consecutive duplicate letters from each string in the array.\n\nFor example: \n\n * `dup([\"abracadabra\",\"allottee\",\"assessee\"]) = [\"abracadabra\",\"alote\",\"asese\"]`. \n \n * `dup([\"kelless\",\"keenness\"]) = [\"keles\",\"kenes\"]`.\n\nStrings will be lowercase only, no spaces. See test cases for more examples.\n\n~~~if:rust\nFor the sake of simplicity you can use the macro 'vec_of_string' to create a Vec with an array of string literals.\n~~~\n\nGood luck!\n\nIf you like this Kata, please try:\n\n[Alternate capitalization](https://www.codewars.com/kata/59cfc000aeb2844d16000075)\n\n[Vowel consonant lexicon](https://www.codewars.com/kata/59cf8bed1a68b75ffb000026)", "solutions": ["from itertools import groupby\n\ndef dup(arry):\n return [''.join((c for (c, grouper) in groupby(i))) for i in arry]", "import re\n\ndef dup(arry):\n return list(map(lambda s: re.sub('(\\\\w)\\\\1+', '\\\\1', s), arry))", "def dup(arry):\n array_new = []\n for string in arry:\n string_new = ''\n prev = None\n for char in string:\n if char != prev:\n string_new += char\n prev = char\n array_new.append(string_new)\n return array_new", "def dup(arr):\n (a, res) = (0, [x[0] for x in arr])\n for string in arr:\n for x in range(1, len(string)):\n if string[x] != string[x - 1]:\n res[a] += string[x]\n a += 1\n return res", "from itertools import groupby\n\ndef dup(strings):\n return [''.join((c for (c, _) in groupby(s))) for s in strings]", "import re\n\ndef dup(lst):\n return [re.sub('(.)\\\\1+', '\\\\1', stg) for stg in lst]", "import re\n\ndef dup(xs):\n return [re.sub('(.)\\\\1+', '\\\\1', x) for x in xs]", "def f(s):\n return ''.join((s[i] for i in range(len(s) - 1) if s[i] != s[i + 1])) + s[-1]\n\ndef dup(arry):\n return [f(s) for s in arry]", "from itertools import groupby\n\ndef dup(array):\n return list(map(remove_dup, array))\n\ndef remove_dup(string):\n return ''.join((single for (single, _) in groupby(string)))", "def dup(arry):\n stack = []\n output = []\n for item in arry:\n for i in item:\n if len(stack) == 0 or (len(stack) >= 1 and i != stack[-1]):\n stack.append(i)\n else:\n continue\n output.append(''.join(stack))\n stack = []\n return output"], "starter_code": "def dup(arry):\n", "input_output": {"fn_name": "dup", "inputs": [[["ccooddddddewwwaaaaarrrrsssss", "piccaninny", "hubbubbubboo"]], [["abracadabra", "allottee", "assessee"]], [["kelless", "keenness"]], [["Woolloomooloo", "flooddoorroommoonlighters", "chuchchi"]], [["adanac", "soonness", "toolless", "ppellee"]], [["callalloo", "feelless", "heelless"]], [["putteellinen", "keenness"]], [["kelless", "voorraaddoosspullen", "achcha"]]], "outputs": [[["codewars", "picaniny", "hubububo"]], [["abracadabra", "alote", "asese"]], [["keles", "kenes"]], [["Wolomolo", "flodoromonlighters", "chuchchi"]], [["adanac", "sones", "toles", "pele"]], [["calalo", "feles", "heles"]], [["putelinen", "kenes"]], [["keles", "voradospulen", "achcha"]]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/59f08f89a5e129c543000069", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "dup", "task_id": "TACO_lite/360", "example": [[[["abracadabra", "allottee", "assessee"]], [["kelless", "keenness"]]], ["['abracadabra', 'alote', 'asese']", "['keles', 'kenes']"]]} +{"requirement": "Write a function that reverses the bits in an integer.\n\nFor example, the number `417` is `110100001` in binary. Reversing the binary is `100001011` which is `267`.\n\nYou can assume that the number is not negative.", "solutions": ["def reverse_bits(n):\n return int(bin(n)[:1:-1], 2)", "def reverse_bits(n):\n return int(f'{n:b}'[::-1], 2)", "def reverse_bits(n):\n listbin = [bin(n)]\n listbin.sort(reverse=True)\n pleasework = list(''.join(listbin))\n comeonguy = ''.join(pleasework)\n almostanswer = comeonguy[:1:-1]\n answer = int(almostanswer, 2)\n return answer\n pass", "def reverse_bits(n):\n return int(format(n, 'b')[::-1], 2)", "def reverse_bits(n):\n return int(''.join(reversed(bin(n)[2:])), 2)", "reverse_bits = lambda n: int(bin(n)[:1:-1], 2)", "def reverse_bits(n):\n a = '{0:08b}'.format(n)\n b = list(a)\n b.reverse()\n c = ''\n for i in b:\n c += i\n return int(c, 2)"], "starter_code": "def reverse_bits(n):\n", "input_output": {"fn_name": "reverse_bits", "inputs": [[417], [267], [0], [2017], [1023], [1024]], "outputs": [[267], [417], [0], [1087], [1023], [1]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Bits"], "name": null, "source": "codewars", "tags": ["Bit manipulation", "Fundamentals"], "skill_types": ["Bit manipulation"], "url": "https://www.codewars.com/kata/5959ec605595565f5c00002b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "reverse_bits", "task_id": "TACO_lite/461", "example": [[[417]], ["267"]]} +{"requirement": "Given a String S, Find all possible Palindromic partitions of the given String.\n \nExample 1:\nInput:\nS = \"geeks\"\nOutput:\ng e e k s\ng ee k s\nExplanation:\nAll possible palindromic partitions\nare printed.\nExample 2:\nInput:\nS = \"madam\"\nOutput:\nm a d a m\nm ada m\nmadam\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function allPalindromicPerms() which takes a String S as input parameter and returns a list of lists denoting all the possible palindromic partitions in the order of their appearance in the original string.\n \nExpected Time Complexity: O(N*2^{N})\nExpected Auxiliary Space: O(N^{2}), where N is the length of the String\n \nConstraints:\n1 <= |S| <= 20", "solutions": ["def allpalindromicperms(S):\n\n def func(index, s, path, res):\n if index == len(s):\n res.append([ele for ele in path])\n return\n for i in range(index, len(s)):\n if isPalindrome(s, index, i):\n path.append(s[index:i + 1])\n func(i + 1, s, path, res)\n path.pop()\n\n def isPalindrome(s, start, end):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n res = []\n path = []\n func(0, S, path, res)\n return res", "def allpalindromicperms(S):\n ans = []\n temp = []\n\n def palli(S, start, end):\n sub = S[start:end]\n return sub == sub[::-1]\n\n def func(i, S, temp, ans):\n if i == len(S):\n ans.append(temp[:])\n for j in range(i, len(S)):\n if palli(S, i, j + 1):\n temp.append(S[i:j + 1])\n func(j + 1, S, temp, ans)\n temp.pop()\n func(0, S, temp, ans)\n return ans", "def ispalindrome(s, ind, i):\n x = ind\n y = i\n while x < y:\n if s[x] != s[y]:\n return False\n x += 1\n y -= 1\n return True\n\ndef palinpart(s, ind, n, ans, subs):\n if ind == n:\n ans.append(subs[:])\n return\n temp = ''\n for i in range(ind, n):\n temp += s[i]\n if ispalindrome(s, ind, i):\n subs.append(temp)\n palinpart(s, i + 1, n, ans, subs)\n subs.pop()\n\ndef allpalindromicperms(s):\n ans = []\n subs = []\n n = len(s)\n i = 0\n palinpart(s, i, n, ans, subs)\n return ans", "def allpalindromicperms(S):\n n = len(S)\n ans = []\n res = []\n\n def isPali(s):\n n = len(s)\n for i in range(n // 2):\n if s[i] != s[n - i - 1]:\n return False\n return True\n\n def bts(i):\n if i == n:\n res.append(ans[:])\n return\n for index in range(i, n):\n if isPali(S[i:index + 1]):\n ans.append(S[i:index + 1])\n bts(index + 1)\n ans.pop()\n bts(0)\n return res", "def allpalindromicperms(S):\n\n def helper(index, s, temp, ans):\n if index == len(s):\n ans.append([ele for ele in temp])\n return\n for i in range(index, len(s)):\n if isPalindrome(s, index, i):\n temp.append(s[index:i + 1])\n helper(i + 1, s, temp, ans)\n temp.pop()\n\n def isPalindrome(s, start, end):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n ans = []\n temp = []\n helper(0, S, temp, ans)\n return ans", "def is_palindrome(data):\n (i, j) = (0, len(data) - 1)\n while i < j:\n if data[i] != data[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef solve(start, S, palindromes, ans):\n if start >= len(S):\n ans.append(palindromes[:])\n return\n for i in range(start, len(S)):\n if self.is_palindrome(S[start:i + 1]):\n palindromes.append(S[start:i + 1])\n self.solve(i + 1, S, palindromes, ans)\n palindromes.pop()\n\ndef allpalindromicperms(S):\n ans = []\n palindromes = []\n self.solve(0, S, palindromes, ans)\n return ans", "def allpalindromicperms(S):\n n = len(S)\n r = []\n\n def subs(st, out):\n if st == n:\n r.append(out)\n return\n for i in range(st, n):\n if S[st:i + 1] == S[st:i + 1][::-1]:\n subs(i + 1, out + [S[st:i + 1]])\n subs(0, [])\n return r", "def allpalindromicperms(S):\n a = list(S)\n ans = set()\n\n def solve(a):\n ans.add(tuple(a))\n if len(a) <= 1:\n return\n for i in range(1, len(a)):\n if a[i - 1] == a[i]:\n b = a[:i - 1] + [a[i - 1] + a[i]] + a[i + 1:]\n solve(b)\n if i + 1 < len(a) and a[i - 1] == a[i + 1]:\n c = a[:i - 1] + [a[i - 1] + a[i] + a[i + 1]] + a[i + 2:]\n solve(c)\n solve(a)\n return sorted(list(ans))", "def allpalindromicperms(S):\n l = []\n\n def back(start, c):\n if start == len(S):\n l.append(c)\n for i in range(start, len(S)):\n if S[start:i + 1] == S[start:i + 1][::-1]:\n back(i + 1, c + [S[start:i + 1]])\n back(0, [])\n return l", "def allpalindromicperms(S):\n self.res = set()\n self.solve(list(S))\n return sorted(list(self.res))\n\ndef solve(arr):\n self.res.add(tuple(arr))\n if len(arr) <= 1:\n return\n for i in range(1, len(arr)):\n if arr[i - 1] == arr[i][::-1]:\n brr = arr[:i - 1] + [arr[i - 1] + arr[i]] + arr[i + 1:]\n self.solve(brr)\n if i + 1 < len(arr) and arr[i - 1] == arr[i + 1][::-1]:\n brr = arr[:i - 1] + [arr[i - 1] + arr[i] + arr[i + 1]] + arr[i + 2:]\n self.solve(brr)", "def allpalindromicperms(S):\n l = []\n\n def bac(start, curl):\n if start == len(S):\n l.append(curl)\n for i in range(start, len(S)):\n if S[start:i + 1] == S[start:i + 1][::-1]:\n bac(i + 1, curl + [S[start:i + 1]])\n bac(0, [])\n return l", "def palindromic_partition_helper(input_string: str, output_string: str, result_arr: []):\n if len(input_string) == 0:\n result_arr.append(output_string)\n return\n n = len(input_string)\n for i in range(0, n):\n word = input_string[0:i + 1]\n ros = input_string[i + 1:]\n if is_palindrome(word):\n output_string = output_string + word + '-'\n palindromic_partition_helper(ros, output_string, result_arr)\n output_string = output_string[:-(len(word) + 1)]\n\ndef is_palindrome(word):\n start = 0\n end = len(word) - 1\n while start < end:\n if word[start] != word[end]:\n return False\n start = start + 1\n end = end - 1\n return True\n\ndef print_partition(input_word):\n result_arr = []\n input_dict = {}\n palindromic_partition_helper(input_word, '', result_arr)\n final_arr = []\n for data in result_arr:\n sub_string = data.split('-')[:-1]\n final_arr.append(sub_string)\n return final_arr\n\ndef allpalindromicperms(S):\n return print_partition(S)", "def allpalindromicperms(s):\n res = []\n part = []\n\n def ispalin(i, j):\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n\n def dfs(i):\n if i == len(s):\n res.append(part.copy())\n for j in range(i, len(s)):\n if ispalin(i, j):\n part.append(s[i:j + 1])\n dfs(j + 1)\n part.pop()\n dfs(0)\n return res", "def allpalindromicperms(S):\n s = S\n n = len(s)\n (ds, ans) = ([], [])\n\n def ispalindrome(start, end, s):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n\n def rec(idx, s):\n if idx == n:\n ans.append(list(ds))\n return ans\n for i in range(idx, n):\n if ispalindrome(idx, i, s):\n ds.append(s[idx:i + 1])\n rec(i + 1, s)\n ds.pop()\n return ans\n return rec(0, s)", "def allpalindromicperms(S):\n result = []\n temp = []\n n = len(S)\n self.Util(0, S, temp, result, n)\n return result\n\ndef Util(index, S, temp, result, n):\n if index == n:\n result.append(temp[:])\n return\n for i in range(index, n):\n if self.isPalin(index, i, S):\n temp.append(S[index:i + 1])\n self.Util(i + 1, S, temp, result, n)\n temp.pop()\n\ndef isPalin(s, e, S):\n while s <= e:\n if S[s] != S[e]:\n return False\n s += 1\n e -= 1\n return True", "def allpalindromicperms(S):\n n = len(S)\n res = []\n\n def subs(start, out):\n if start == n:\n res.append(out)\n return\n for i in range(start, n):\n if S[start:i + 1] == S[start:i + 1][::-1]:\n subs(i + 1, out + [S[start:i + 1]])\n subs(0, [])\n return res", "def allpalindromicperms(S):\n\n def palind(f):\n l = len(f)\n for i in range(l // 2):\n if f[i] != f[l - i - 1]:\n return 0\n return 1\n\n def manu(i, n, f, s):\n if i == n:\n x = []\n for i in range(len(f)):\n x.append(f[i])\n a.append(x)\n return 0\n x = ''\n for j in range(i, n):\n x += s[j]\n if palind(x):\n f.append(x)\n manu(j + 1, n, f, s)\n f.pop()\n return\n a = []\n manu(0, len(S), [], S)\n return a", "def isPalindrome(string: str, low: int, high: int):\n while low < high:\n if string[low] != string[high]:\n return False\n low += 1\n high -= 1\n return True\n\ndef allPalPartUtil(allPart: list, currPart: list, start: int, n: int, string: str):\n if start >= n:\n x = currPart.copy()\n allPart.append(x)\n return\n for i in range(start, n):\n if isPalindrome(string, start, i):\n currPart.append(string[start:i + 1])\n allPalPartUtil(allPart, currPart, i + 1, n, string)\n currPart.pop()\n\ndef allpalindromicperms(S):\n n = len(S)\n allPart = []\n currPart = []\n allPalPartUtil(allPart, currPart, 0, n, S)\n return allPart", "def allpalindromicperms(S):\n\n def backtrack(start, currl):\n if start == len(S):\n res.append(currl)\n for i in range(start, len(S)):\n if S[start:i + 1] == S[start:i + 1][::-1]:\n backtrack(i + 1, currl + [S[start:i + 1]])\n res = []\n backtrack(0, [])\n return res", "def rec(S, ind, res, string):\n if ind == len(S):\n res.append(list(string.split()))\n ans = 0\n for i in range(ind + 1, len(S) + 1):\n temp = S[ind:i]\n if temp == temp[::-1]:\n rec(S, i, res, string + ' ' + temp)\n\ndef allpalindromicperms(S):\n res = []\n rec(S, 0, res, '')\n return res", "def allpalindromicperms(S):\n res = []\n perm = []\n\n def dfs(i):\n if i >= len(S):\n res.append(perm.copy())\n return\n for j in range(i, len(S)):\n if self.isPali(S, i, j):\n perm.append(S[i:j + 1])\n dfs(j + 1)\n perm.pop()\n dfs(0)\n return res\n\ndef isPali(s, l, r):\n while l < r:\n if s[l] != s[r]:\n return False\n l = l + 1\n r = r - 1\n return True", "def allpalindromicperms(S):\n s = S\n res = []\n\n def check(s, start, end):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n\n def f(s, ind, ds, res):\n if ind == len(s):\n res.append(ds.copy())\n return\n for i in range(ind, len(s)):\n if check(s, ind, i):\n ds.append(s[ind:i + 1])\n f(s, i + 1, ds, res)\n ds.pop()\n return res\n return f(s, 0, [], res)", "from collections import defaultdict as dd\n\ndef allpalindromicperms(S):\n n = len(S)\n palindromes = dd(lambda : [])\n for i in range(n):\n j = 0\n while i - j >= 0 and i + 2 + j <= n:\n s = S[i - j:i + 2 + j]\n if s == s[::-1]:\n palindromes[i - j].append(s)\n else:\n break\n j += 1\n for i in range(n):\n j = 0\n while i - j >= 0 and i + 1 + j <= n:\n s = S[i - j:i + 1 + j]\n if s == s[::-1]:\n palindromes[i - j].append(s)\n else:\n break\n j += 1\n output = []\n stack = []\n for item in palindromes[0]:\n stack.append((item, 0))\n while stack:\n (item, i) = stack.pop()\n if len(item) - i == n:\n output.append([item])\n continue\n for pali in palindromes[len(item) - i]:\n stack.append((item + ' ' + pali, i + 1))\n return sorted(output)", "def allpalindromicperms(S):\n n = len(S)\n res = []\n curr = []\n self.allpartitions(S, res, curr, 0)\n return res\n\ndef allpartitions(s, res, curr, start):\n n = len(s)\n if start >= n:\n x = curr.copy()\n res.append(x)\n return\n for i in range(start, n):\n if self.ispalindrome(s, start, i):\n curr.append(s[start:i + 1])\n self.allpartitions(s, res, curr, i + 1)\n curr.pop()\n\ndef ispalindrome(string, low, high):\n while low < high:\n if string[low] != string[high]:\n return False\n low += 1\n high -= 1\n return True", "def allpalindromicperms(S):\n result = []\n temp = []\n index = 0\n self.solve(index, S, temp, result)\n return result\n\ndef solve(index, s, temp, result):\n if index == len(s):\n result.append(temp[:])\n return\n for i in range(index, len(s)):\n if self.checkPal(index, i, s):\n temp.append(s[index:i + 1])\n self.solve(i + 1, s, temp, result)\n temp.pop()\n\ndef checkPal(s, e, S):\n while s <= e:\n if S[s] != S[e]:\n return False\n s += 1\n e -= 1\n return True", "def ispalindrome(s, start, end):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n\ndef solve(idx, s, ans, path):\n if idx == len(s):\n ans.append(path.copy())\n return\n for i in range(idx, len(s)):\n if self.ispalindrome(s, idx, i):\n path.append(s[idx:i + 1])\n self.solve(i + 1, s, ans, path)\n path.pop()\n\ndef allpalindromicperms(s):\n ans = []\n path = []\n self.solve(0, s, ans, path)\n return ans", "def func(s, temp, ans):\n if not s:\n ans.append(temp[:])\n return\n for i in range(1, len(s) + 1):\n t = s[:i]\n if t == t[::-1]:\n func(s[i:], temp + [t], ans)\n\ndef allpalindromicperms(s):\n ans = []\n func(s, [], ans)\n return ans", "def allpalindromicperms(S):\n self.res = []\n self.n = len(S)\n self.pals = self.palindrome(S)\n curr = []\n self.palsTmp(curr, 0, S)\n return self.res\n\ndef palsTmp(curr, i, S):\n if i >= self.n:\n self.res.append(list(curr))\n else:\n for j in range(i, self.n):\n if self.pals[i][j]:\n curr.append(S[i:j + 1])\n self.palsTmp(curr, j + 1, S)\n curr.pop()\n\ndef palindrome(s):\n n = len(s)\n tb = [[False for j in range(n)] for i in range(n)]\n for i in range(n):\n tb[i][i] = True\n for i in range(n - 1):\n if s[i] == s[i + 1]:\n tb[i][i + 1] = True\n for gap in range(2, n):\n for i in range(n - gap):\n j = i + gap\n if s[i] == s[j] and tb[i + 1][j - 1]:\n tb[i][j] = True\n return tb", "def allpalindromicperms(S):\n res = []\n part = []\n n = len(S)\n\n def dfs(i):\n if i >= n:\n res.append(part[:])\n return\n for j in range(i, n):\n if self.isPalindrome(S, i, j):\n part.append(S[i:j + 1])\n dfs(j + 1)\n part.pop()\n return res\n return dfs(0)\n\ndef isPalindrome(S, i, j):\n if S[i:j + 1] == S[i:j + 1][::-1]:\n return True\n else:\n return False", "def allpalindromicperms(S):\n\n def isPalindrome(i, j, S):\n while i <= j:\n if S[i] != S[j]:\n return False\n i += 1\n j -= 1\n return True\n\n def helper(i, arr, ans):\n if i == len(S):\n ans.append(arr[:])\n return\n for j in range(i, len(S)):\n if isPalindrome(i, j, S):\n arr.append(S[i:j + 1])\n helper(j + 1, arr, ans)\n arr.pop()\n (arr, ans) = ([], [])\n helper(0, arr, ans)\n return ans", "def expandByCenter(S, n, c1, c2, graph):\n while c1 >= 0 and c2 < n and (S[c1] == S[c2]):\n graph[c1].add(c2)\n c1 -= 1\n c2 += 1\n\ndef util(graph, S, n, u, ans, path):\n if u == n:\n path.append(n)\n li = []\n for i in range(len(path) - 1):\n li.append(S[path[i]:path[i + 1]])\n ans.append(li)\n path.pop()\n return\n path.append(u)\n for v in sorted(graph[u]):\n util(graph, S, n, v + 1, ans, path)\n path.pop()\n\ndef allpalindromicperms(S):\n n = len(S)\n graph = {u: set() for u in range(n)}\n for c1 in range(n):\n expandByCenter(S, n, c1, c1, graph)\n expandByCenter(S, n, c1, c1 + 1, graph)\n ans = []\n util(graph, S, n, 0, ans, [])\n return ans", "def isPalin(s):\n n = len(s)\n i = 0\n j = n - 1\n while i <= j:\n if s[i] != s[j]:\n return 0\n i += 1\n j -= 1\n return 1\n\ndef solve(inp, out, ans):\n if len(inp) == 0:\n ans.append(out.copy())\n return\n n = len(inp)\n for i in range(n):\n if self.isPalin(inp[:i + 1]):\n out.append(inp[:i + 1])\n self.solve(inp[i + 1:], out, ans)\n out.pop()\n\ndef allpalindromicperms(S):\n n = len(S)\n ans = []\n inp = S\n out = []\n self.solve(inp, out, ans)\n return ans", "def allpalindromicperms(S):\n res = []\n n = len(S)\n\n def dfs(index, l):\n if index == n:\n res.append(l.copy())\n return\n for i in range(index, n):\n s1 = S[index:i + 1]\n if s1 == s1[::-1]:\n l.append(s1)\n dfs(i + 1, l)\n l.pop()\n return res\n res = dfs(0, [])\n return res", "def allpalindromicperms(S):\n\n def isPalindrom(si, ei):\n nonlocal S\n for i in range((ei - si + 1) // 2):\n if S[si + i] != S[ei - i]:\n return False\n return True\n ans = []\n n = len(S)\n\n def backtrack(starti, arr):\n nonlocal S, ans, n\n if starti == n:\n ans.append(arr.copy())\n else:\n for endi in range(starti, n):\n if isPalindrom(starti, endi):\n arr.append(S[starti:endi + 1])\n backtrack(endi + 1, arr)\n arr.pop()\n backtrack(0, [])\n return ans", "def __init__():\n self.dp = dict()\n\ndef isPalin(s):\n return s == s[::-1]\n\ndef allpalindromicperms(s, i=0):\n if len(s) == 1:\n return [s]\n if self.dp.get(s) != None:\n return self.dp[s]\n till = ''\n way = []\n if self.isPalin(s):\n way.append([s])\n for x in range(1, len(s)):\n rem = s[:x]\n if not self.isPalin(rem):\n continue\n for _ in self.allpalindromicperms(s[x:], i + 1):\n way.append([rem, *_])\n self.dp[s] = way\n if i == 0:\n return sorted(way)\n return way", "def allpalindromicperms(S):\n (res, curr, i, n) = ([], [], 0, len(S))\n pals = self.isPal(S)\n self.palPermsTmp(curr, i, res, n, S, pals)\n return res\n\ndef palPermsTmp(curr, i, res, n, s, pals):\n if i >= n:\n res.append(list(curr))\n else:\n for j in range(i, n):\n if pals[i][j]:\n curr.append(s[i:j + 1])\n self.palPermsTmp(curr, j + 1, res, n, s, pals)\n curr.pop()\n\ndef isPal(s):\n n = len(s)\n pals = [[False for i in range(n)] for j in range(n)]\n for j in range(n):\n pals[j][j] = True\n for j in range(n - 1):\n pals[j][j + 1] = s[j] == s[j + 1]\n for gap in range(2, n):\n for j in range(n - gap):\n i = j + gap\n pals[j][i] = (s[j] == s[i]) & pals[j + 1][i - 1]\n return pals", "def allpalindromicperms(S):\n\n def helper(s, v):\n if s == n:\n ans.append(v)\n return\n for i in range(s, n):\n if S[s:i + 1] == S[s:i + 1][::-1]:\n helper(i + 1, v + [S[s:i + 1]])\n ans = []\n n = len(S)\n helper(0, [])\n return ans", "def allpalindromicperms(S):\n self.s = S\n self.n = len(S)\n self.palindromes = []\n self.findPalindromes(0, '', [])\n return self.palindromes\n\ndef findPalindromes(index, word, palindrome):\n if index >= self.n:\n if word == '':\n self.palindromes.append(palindrome.copy())\n return\n word += self.s[index]\n if word == word[::-1]:\n self.findPalindromes(index + 1, '', palindrome + [word])\n self.findPalindromes(index + 1, word, palindrome)", "def allpalindromicperms(s):\n\n def check(strs):\n return strs == strs[::-1]\n ans = []\n\n def fun(temp, t):\n nonlocal ans\n if len(t) == 0:\n ans.append(temp)\n return\n for gap in range(1, len(t) + 1):\n sub_t = t[:gap]\n if check(sub_t):\n fun(temp + [sub_t], t[gap:])\n else:\n continue\n fun([], s)\n return ans", "def allpalindromicperms(S):\n\n def helper(ind, s, sub, res):\n if ind == len(s):\n res.append([i for i in sub])\n return\n for i in range(ind, len(s)):\n if ispal(s, ind, i):\n sub.append(s[ind:i + 1])\n helper(i + 1, s, sub, res)\n sub.pop()\n\n def ispal(s, start, end):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n res = []\n sub = []\n helper(0, S, sub, res)\n return res", "def allpalindromicperms(S):\n s = S\n\n def palindrome(sub):\n lt = 0\n rt = len(sub) - 1\n while lt < rt:\n if sub[lt] != sub[rt]:\n return False\n lt += 1\n rt -= 1\n return True\n\n def part(index, s, temp, ans):\n if index == len(s):\n ans.append(temp.copy())\n return\n else:\n for i in range(index, len(s)):\n sub = s[index:i + 1]\n if palindrome(sub):\n temp.append(sub)\n part(i + 1, s, temp, ans)\n temp.pop()\n ans = []\n part(0, s, [], ans)\n return ans", "def allpalindromicperms(s):\n\n def func(ind, n, res, ans, s):\n if ind == n:\n res.append(ans.copy())\n return\n for i in range(ind, n):\n kk = s[ind:i + 1]\n if kk == kk[::-1]:\n ans.append(kk)\n func(i + 1, n, res, ans, s)\n ans.pop()\n ans = []\n res = []\n n = len(s)\n func(0, n, res, ans, s)\n return res", "import collections\n\ndef allpalindromicperms(S):\n s = S\n dp = collections.defaultdict(str)\n ans = []\n for i in range(len(s)):\n dp[i, i] = s[i]\n for i in range(len(s) - 1, -1, -1):\n for j in range(i + 1, len(s)):\n if j - i == 1 and s[i] == s[j]:\n dp[i, j] = s[i] + s[j]\n elif (i + 1, j - 1) in dp and s[i] == s[j]:\n dp[i, j] = s[i] + dp[i + 1, j - 1] + s[j]\n\n def iterate(i, st):\n if i == len(s):\n ans.append(st)\n for j in range(i, len(s)):\n if (i, j) in dp:\n sx = st[:]\n sx.append(dp[i, j])\n iterate(j + 1, sx)\n iterate(0, [])\n return ans", "def allpalindromicperms(s):\n res = []\n part = []\n\n def dfs(i):\n if i >= len(s):\n res.append(part[:])\n return\n for j in range(i, len(s)):\n if self.isPalin(s, i, j):\n part.append(s[i:j + 1])\n dfs(j + 1)\n part.pop()\n return res\n return dfs(0)\n\ndef isPalin(s, i, j):\n if s[i:j + 1] == s[i:j + 1][::-1]:\n return True", "def allpalindromicperms(S):\n n = len(S)\n op = []\n\n def finding(start, end):\n if start == n:\n op.append(end)\n return\n for i in range(start, n):\n if S[start:i + 1] == S[start:i + 1][::-1]:\n finding(i + 1, end + [S[start:i + 1]])\n finding(0, [])\n return op", "def IsPalindrome(start, end, s):\n while start <= end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n\ndef helper(ind, n, s, ans, temp):\n if ind == n:\n ans.append(temp[:])\n return\n for i in range(ind, n):\n if self.IsPalindrome(ind, i, s):\n temp.append(s[ind:i + 1])\n self.helper(i + 1, n, s, ans, temp)\n temp.pop()\n\ndef allpalindromicperms(S):\n ans = []\n temp = []\n self.helper(0, len(S), S, ans, temp)\n return ans", "def allpalindromicperms(S):\n\n def dfs(i, l):\n if i == len(S):\n ans.append(l[:])\n return\n for ind in range(i, len(S)):\n if S[i:ind + 1] == S[i:ind + 1][::-1]:\n l.append(S[i:ind + 1])\n dfs(ind + 1, l)\n l.pop()\n ans = []\n dfs(0, [])\n return ans", "def allpalindromicperms(S):\n import copy\n ans = []\n\n def f(index, p):\n if index == len(S):\n ans.append(copy.deepcopy(p))\n return\n for i in range(index, len(S)):\n t = S[index:i + 1]\n if t == t[::-1]:\n p.append(t)\n f(i + 1, p)\n p.pop()\n f(0, [])\n return ans", "from copy import copy\n\ndef allpalindromicperms(S):\n lst = []\n res = []\n self.helper(0, S, lst, res)\n return res\n\ndef checkpalindrome(a, b, s):\n while a <= b:\n if s[a] != s[b]:\n return False\n a += 1\n b -= 1\n return True\n\ndef helper(idx, s, lst, res):\n if idx == len(s):\n res.append(copy(lst))\n return\n for i in range(idx, len(s)):\n if self.checkpalindrome(idx, i, s) == True:\n lst.append(s[idx:i + 1])\n self.helper(i + 1, s, lst, res)\n lst.pop()", "def allpalindromicperms(s):\n l = []\n\n def dfs(x, n, a):\n if x is '':\n l.append(a[:])\n return\n y = ''\n for i in range(n):\n y += x[i]\n if y != y[::-1]:\n continue\n a.append(y)\n dfs(x[i + 1:], n - i - 1, a)\n a.pop(-1)\n dfs(s, len(s), [])\n return l", "def allpalindromicperms(s):\n m = len(s)\n r = []\n a = []\n\n def check(string, i, j):\n x = j\n for y in range(i, x):\n if string[y] != string[x]:\n return False\n x -= 1\n return True\n\n def allPalPartUtil(allPart: list, currPart: list, start: int, n: int, string: str):\n if start >= n:\n x = currPart.copy()\n allPart.append(x)\n return\n for i in range(start, n):\n if check(string, start, i):\n currPart.append(string[start:i + 1])\n allPalPartUtil(allPart, currPart, i + 1, n, string)\n currPart.pop()\n allPalPartUtil(r, a, 0, m, s)\n return r", "from collections import defaultdict\n\ndef allpalindromicperms(s):\n h = defaultdict(set)\n ans = []\n cans = []\n n = len(s)\n for i in range(n):\n p = q = i\n h[p].add(q)\n while p - 1 >= 0 and q + 1 < n and (s[p - 1] == s[q + 1]):\n p -= 1\n q += 1\n h[p].add(q)\n for i in range(n - 1):\n (p, q) = (i + 1, i)\n while p - 1 >= 0 and q + 1 < n and (s[p - 1] == s[q + 1]):\n p -= 1\n q += 1\n h[p].add(q)\n\n def rec(i, start):\n if i == n:\n if start == n:\n ans.append(cans[:])\n return\n if i in h[start]:\n cans.append(s[start:i + 1])\n rec(i + 1, i + 1)\n cans.pop()\n if len(h[start]) > 1:\n rec(i + 1, start)\n rec(0, 0)\n return ans", "def allpalindromicperms(S):\n res = []\n part = []\n\n def dfs(i):\n if i >= len(S):\n res.append(part.copy())\n return\n for j in range(i, len(S)):\n if self.isPalindrome(S, i, j):\n part.append(S[i:j + 1])\n dfs(j + 1)\n part.pop()\n dfs(0)\n return res\n\ndef isPalindrome(S, l, r):\n while l <= r:\n if S[l] != S[r]:\n return False\n (l, r) = (l + 1, r - 1)\n return True", "def allpalindromicperms(S):\n\n def go(ind):\n if ind == len(S):\n ans.append(p[:])\n return\n for i in range(ind, len(S)):\n if isP(S[ind:i + 1]):\n p.append(S[ind:i + 1])\n go(i + 1)\n p.pop(-1)\n\n def isP(x):\n l = 0\n r = len(x) - 1\n while l < r:\n if x[l] != x[r]:\n return False\n l += 1\n r -= 1\n return True\n p = []\n ans = []\n go(0)\n return ans", "def is_palindrome(string):\n j = len(string) - 1\n i = 0\n while i < j:\n if string[i] != string[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef partition(string, ans, res):\n if len(string) == 0:\n res.add(' '.join(ans))\n return\n for i in range(len(string)):\n if self.is_palindrome(string[:i + 1]):\n self.partition(string[i + 1:], ans + [string[:i + 1]], res)\n\ndef allpalindromicperms(S):\n res = set()\n self.partition(S, [], res)\n res = [[x] for x in res]\n res = sorted(res)\n return res", "def allpalindromicperms(S):\n n = len(S)\n result = []\n\n def sub(start, out):\n if start == n:\n result.append(out)\n return\n for i in range(start, n):\n if S[start:i + 1] == S[start:i + 1][::-1]:\n sub(i + 1, out + [S[start:i + 1]])\n sub(0, [])\n return result", "def isPalindrome(s):\n i = 0\n j = len(s) - 1\n while i < j:\n if s[i] != s[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef backtrack(i, n, temp, l, S):\n if i >= n:\n l.append(temp[:])\n p = ''\n for j in range(i, n):\n p += S[j]\n if self.isPalindrome(p):\n temp.append(p)\n self.backtrack(j + 1, n, temp, l, S)\n temp.pop()\n\ndef allpalindromicperms(S):\n l = []\n self.backtrack(0, len(S), [], l, S)\n return l", "def allpalindromicperms(S):\n ans = []\n a = []\n n = len(S)\n\n def check(s):\n return s == s[::-1]\n\n def sol(i, n):\n if i == n:\n ans.append(a.copy())\n return\n for j in range(n - i):\n if check(S[i:i + j + 1]):\n a.append(S[i:i + j + 1])\n sol(i + j + 1, n)\n a.pop()\n sol(0, n)\n return ans", "def is_palindrome(S):\n low = 0\n high = len(S) - 1\n while low < high:\n if S[low] != S[high]:\n return False\n low += 1\n high -= 1\n return True\n\ndef solve(S, part, res):\n for i in range(len(S)):\n prefix = S[:i + 1]\n if self.is_palindrome(prefix):\n rest = S[i + 1:]\n if len(rest) == 0:\n part.append(prefix)\n res.append(part[:])\n part.pop()\n return\n part.append(prefix)\n self.solve(rest, part, res)\n part.pop()\n\ndef allpalindromicperms(S):\n res = []\n self.solve(S, [], res)\n return res", "def is_palindrome(start, end, nums):\n while start <= end:\n if nums[start] != nums[end]:\n return False\n start = start + 1\n end = end - 1\n return True\n\ndef helper(ind, nums, path, ans):\n if ind == len(nums):\n ans.append(list(path))\n return\n for i in range(ind, len(nums)):\n if self.is_palindrome(ind, i, nums):\n path.append(''.join(nums[ind:i + 1]))\n self.helper(i + 1, nums, path, ans)\n path.pop()\n\ndef allpalindromicperms(S):\n ans = []\n self.helper(0, list(S), [], ans)\n return ans", "def allpalindromicperms(S):\n t = len(S)\n rest = []\n\n def subt(first, last):\n if first == t:\n rest.append(last)\n return\n for i in range(first, t):\n if S[first:i + 1] == S[first:i + 1][::-1]:\n subt(i + 1, last + [S[first:i + 1]])\n subt(0, [])\n return rest", "def allpalindromicperms(s):\n l = []\n\n def backtrack(a, s):\n if s is '':\n l.append(a[:])\n return\n n = len(s)\n x = ''\n for i in range(n):\n x += s[i]\n if x == x[::-1]:\n a.append(x)\n backtrack(a, s[i + 1:])\n a.pop(-1)\n backtrack([], s)\n return l", "def isPali(str):\n i = 0\n j = len(str) - 1\n while i < j:\n if str[i] != str[j]:\n return False\n i += 1\n j -= 1\n return True\n\ndef solve(str):\n if len(str) == 1:\n return [[str[0]]]\n curr = []\n for i in range(1, len(str)):\n if not self.isPali(str[:i]):\n continue\n prev = self.solve(str[i:])\n for p in prev:\n p.insert(0, str[:i])\n curr.append(p)\n if self.isPali(str):\n curr.append([str])\n return curr\n\ndef allpalindromicperms(str):\n return self.solve(str)", "def allpalindromicperms(S):\n ans = []\n part = []\n\n def dfs(i=0):\n if i == len(S):\n ans.append(part[:])\n return\n for j in range(i, len(S)):\n if self.checkPal(S, i, j):\n part.append(S[i:j + 1])\n dfs(j + 1)\n part.pop()\n dfs()\n return ans\n\ndef checkPal(S, i, j):\n while i < j:\n if S[i] != S[j]:\n return False\n i += 1\n j -= 1\n return True", "def allpalindromicperms(S):\n ans = []\n part = []\n\n def dfs(i=0):\n if i == len(S):\n ans.append(part[:])\n return\n for j in range(i, len(S)):\n if self.checkPal(S[i:j + 1]):\n part.append(S[i:j + 1])\n dfs(j + 1)\n part.pop()\n dfs()\n return ans\n\ndef checkPal(str):\n return str == str[::-1]", "def allpalindromicperms(s):\n res = []\n\n def rec(idx, path, res):\n if idx == len(s):\n res.append(path[:])\n return\n for i in range(idx, len(s)):\n if ispali(s, idx, i):\n path.append(s[idx:i + 1])\n rec(i + 1, path, res)\n path.pop(-1)\n\n def ispali(s, left, right):\n while left <= right:\n if s[left] != s[right]:\n return False\n left += 1\n right -= 1\n return True\n rec(0, [], res)\n return res", "def ispal(s):\n if s == s[::-1]:\n return True\n return False\n\ndef helper(allpart, curpart, start, end, s):\n if start >= end:\n x = curpart.copy()\n allpart.append(x)\n return\n for i in range(start, end):\n if self.ispal(s[start:i + 1]):\n curpart.append(s[start:i + 1])\n self.helper(allpart, curpart, i + 1, end, s)\n curpart.pop()\n return allpart\n\ndef allpalindromicperms(S):\n ans = self.helper([], [], 0, len(S), S)\n return ans"], "starter_code": "def allpalindromicperms(S):\n", "input_output": {"inputs": ["S = \"geeks\"", "S = \"madam\""], "outputs": ["g e e k s\ng ee k s", "m a d a m\nm ada m\nmadam"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Algorithms", "Recursion", "Strings", "Data Structures", "Backtracking", "Dynamic Programming", "palindrome"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Dynamic programming", "Data structures", "Complete search"], "skill_types": ["Dynamic programming", "Data structures", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/find-all-possible-palindromic-partitions-of-a-string/1", "Expected Auxiliary Space": "O(N^{2}), where N is the length of the String", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*2^{N})", "entry_point": "allpalindromicperms", "task_id": "TACO_lite/263", "example": [[["geeks"], ["madam"]], [[["g", "e", "e", "k", "s"], ["g", "ee", "k", "s"]], [["m", "a", "d", "a", "m"], ["m", "ada", "m"], ["madam"]]]]} +{"requirement": "Jack is very fond of reading. He reads a lot many pages of books in a day. Since he is obsessed with reading, he reads K times more pages than the number of pages he read the previous day.He read 1 page on the first day. He wants to see that on any given day N, how many pages will he read.Since the answer can be very large, find the answer in modulo 10^{9}+7.\nExample 1:\nInput: N = 5, K = 2 \nOutput: 16 \nExplanation: \nOn Day 1 : 1\nOn Day 2 : 2\nOn Day 3 : 4\nOn Day 4 : 8\nOn Day 5 : 16\nSo the answer is 16. \nExample 2:\nInput: N = 2, K = 3 \nOutput: 3\nExplanation: \nOn Day 1 : 1\nOn Day 2 : 3\nSo the answer is 3. \nYour Task: \nYou dont need to read input or print anything. Complete the function nthDayPage() which takes N and K as input parameter and returns the answer.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1<= N <=10^{6}\n1<= K <=10^{3}", "solutions": ["def nthdaypage(N, K):\n N = N - 1\n x = K ** N\n x = x % 1000000007\n return x", "def nthdaypage(N, K):\n return K ** (N - 1) % (10 ** 9 + 7)", "def nthdaypage(N, K):\n l = [1]\n for i in range(N):\n l.append(l[-1] * K % (10 ** 9 + 7))\n return l[N - 1]", "import math\n\ndef nthdaypage(N, K):\n if N == 1:\n return 1\n m = int(1000000000.0) + 7\n (p, x, res) = (N - 1, K, 1)\n while p != 0:\n if p % 2 != 0:\n res = res * x\n x = x * x\n p = p >> 1\n return res % m", "def nthdaypage(N, K):\n self.s = 1\n for i in range(2, N + 1):\n self.s *= K\n return self.s % (10 ** 9 + 7)", "def nthdaypage(N: int, K: int) -> int:\n return K ** (N - 1) % 1000000007", "def nthdaypage(N, K):\n N = N - 1\n X = K ** N\n X = X % 1000000007\n return X", "def nthdaypage(N, K):\n N = N - 1\n y = K ** N\n y = y % 1000000007\n return y", "def nthdaypage(N, K):\n N = N - 1\n a = K ** N\n a = a % 1000000007\n return a", "def nthdaypage(N, K):\n N = N - 1\n s = K ** N\n s = s % 1000000007\n return s", "def nthdaypage(N, K):\n if N == 1:\n return 1\n else:\n return K ** (N - 1) % 1000000007", "def nthdaypage(N, K):\n N = N - 1\n m = K ** N\n m = m % 1000000007\n return m", "def nthdaypage(N, K):\n return pow(K, N - 1) % 1000000007", "def nthdaypage(N, K):\n N = N - 1\n z = K ** N\n z = z % 1000000007\n return z"], "starter_code": "def nthdaypage (N, K):\n", "input_output": {"inputs": ["N = 5, K = 2", "N = 2, K = 3"], "outputs": ["16", "3"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical", "series"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/dull-jack1909/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "nthdaypage", "task_id": "TACO_lite/453", "example": [[[5, 2], [2, 3]], ["16", "3"]]} +{"requirement": "John is developing a system to report fuel usage but needs help with the coding.\n\nFirst, he needs you to write a function that, given the actual consumption (in l/100 km) and remaining amount of petrol (in l), will give you how many kilometers you'll be able to drive.\n\nSecond, he needs you to write a function that, given a distance (in km), a consumption (in l/100 km), and an amount of petrol (in l), will return one of the following: If you can't make the distance without refueling, it should return the message \"You will need to refuel\". If you can make the distance, the function will check every 100 km and produce an array with [1:kilometers already driven. 2: kilometers till end. 3: remaining amount of petrol] and return all the arrays inside another array ([[after 100km], [after 200km], [after 300km]...])\n\nPLEASE NOTE: any of the values with decimals that you return should be rounded to 2 decimals.", "solutions": ["def total_kilometers(cons, petrol):\n return round(100 * petrol / cons, 2)\n\ndef check_distance(dist, cons, petrol):\n return 'You will need to refuel' if dist > total_kilometers(cons, petrol) else [[n * 100, dist - 100 * n, round(petrol - cons * n, 2)] for n in range(dist // 100 + 1)]", "def total_kilometers(cons, petrol):\n distance = round(petrol / cons * 100, 2)\n return distance\n\ndef check_distance(distance, cons, petrol):\n outp = []\n track = 0\n driven_dist = 0\n if distance > petrol / cons * 100:\n return 'You will need to refuel'\n while track <= distance:\n outp.append([driven_dist, distance - driven_dist, round(petrol, 2)])\n driven_dist += 100\n petrol -= cons\n track += 100\n return outp", "def total_kilometers(cons, petrol):\n return round(petrol * 100.0 / cons, 2)\n\ndef check_distance(distance, cons, petrol):\n if total_kilometers(cons, petrol) < distance:\n return 'You will need to refuel'\n return [[round(x, 2) for x in (i * 100, distance - i * 100, petrol - cons * i)] for i in range(int(distance / 100) + 1)]", "def total_kilometers(cons, petrol):\n return round(float(petrol) / cons * 100, 2)\n\ndef check_distance(distance, cons, petrol):\n if distance * cons > petrol * 100:\n return 'You will need to refuel'\n return [[i, distance - i, round(petrol - i * cons / 100, 2)] for i in xrange(0, distance + 1, 100)]", "def total_kilometers(cons, petrol):\n return round(petrol / float(cons) * 100, 2)\n\ndef check_distance(distance, cons, petrol):\n if total_kilometers(cons, petrol) < distance:\n return 'You will need to refuel'\n km_driven = 0\n result = []\n while distance >= 0:\n result.append([km_driven, distance, petrol])\n distance -= 100\n km_driven += 100\n petrol = round(petrol - cons, 2)\n return result", "def total_kilometers(cons, petrol):\n return round(100 * petrol / cons, 2)\n\ndef check_distance(distance, cons, petrol):\n if total_kilometers(cons, petrol) < distance:\n return 'You will need to refuel'\n r = [[0, distance, petrol]]\n x = 0\n while distance >= 100:\n petrol -= cons\n distance -= 100\n x += 100\n r.append([x, distance, round(petrol, 2)])\n return r", "def total_kilometers(cons, petrol):\n return round(petrol * 100 / cons, 2)\n\ndef check_distance(distance, cons, petrol):\n if distance > petrol * 100 / cons:\n return 'You will need to refuel'\n else:\n l = []\n length = 0\n for i in range(1 + distance // 100):\n l.append([length, distance, round(petrol, 2)])\n length += 100\n distance -= 100\n petrol -= cons\n return l"], "starter_code": "def total_kilometers(cons, petrol):\n", "input_output": {"fn_name": "total_kilometers", "inputs": [[10, 60], [8, 0], [6.4, 54], [9.3, 87.3], [11.7, 63.4]], "outputs": [[600], [0], [843.75], [938.71], [541.88]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Games", "Puzzles"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Game theory", "Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/55cb8b5ddd6a67fef7000070", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "total_kilometers", "task_id": "TACO_lite/362", "example": [[], []]} +{"requirement": "Create a function that accepts dimensions, of Rows x Columns, as parameters in order to create a multiplication table sized according to the given dimensions. **The return value of the function must be an array, and the numbers must be Fixnums, NOT strings.\n\nExample:\n\nmultiplication_table(3,3)\n\n1 2 3 \n2 4 6 \n3 6 9\n\n-->[[1,2,3],[2,4,6],[3,6,9]]\n\nEach value on the table should be equal to the value of multiplying the number in its first row times the number in its first column.", "solutions": ["def multiplication_table(row, col):\n return [[(i + 1) * (j + 1) for j in range(col)] for i in range(row)]", "def multiplication_table(row, col):\n return [[x * y for y in range(1, col + 1)] for x in range(1, row + 1)]", "def multiplication_table(row, col):\n res = []\n for i in range(1, row + 1):\n item = []\n for j in range(1, col + 1):\n item.append(i * j)\n res.append(item)\n return res", "def multiplication_table(row, col):\n return [[e * i for e in range(1, col + 1)] for i in range(1, row + 1)]", "def multiplication_table(row, col):\n l = []\n for linha in range(row):\n l.append(list(range(linha + 1, (linha + 1) * col + 1, linha + 1)))\n return l"], "starter_code": "def multiplication_table(row,col):\n", "input_output": {"fn_name": "multiplication_table", "inputs": [[2, 2], [3, 3], [3, 4], [4, 4], [2, 5]], "outputs": [[[[1, 2], [2, 4]]], [[[1, 2, 3], [2, 4, 6], [3, 6, 9]]], [[[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12]]], [[[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4, 8, 12, 16]]], [[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]]]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5432fd1c913a65b28f000342", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "multiplication_table", "task_id": "TACO_lite/381", "example": [[[3, 3]], ["[[1, 2, 3], [2, 4, 6], [3, 6, 9]]"]]} +{"requirement": "Given a string, swap the case for each of the letters.\n\ne.g. CodEwArs --> cODeWaRS\n\n### Examples\n\n```\n\"\" -> \"\"\n\"CodeWars\" -> \"cODEwARS\"\n\"abc\" -> \"ABC\"\n\"ABC\" -> \"abc\"\n\"123235\" -> \"123235\"\n```", "solutions": ["def swap(string_):\n return string_.swapcase()", "swap = str.swapcase", "swap = lambda s: ''.join([c.lower() if c.isupper() else c.upper() for c in s])", "swap = lambda s: s.swapcase()", "def swap(s):\n return s.swapcase()", "def swap(string_):\n s = ''\n for i in string_:\n if i.isupper():\n s += i.lower()\n else:\n s += i.upper()\n return s", "def swap(word):\n return ''.join((ch.upper() if ch.islower() else ch.lower() for ch in word))"], "starter_code": "def swap(string_):\n", "input_output": {"fn_name": "swap", "inputs": [["HelloWorld"], ["CodeWars"], ["ThIs iS A l0NG sENTence witH nUMbERs in IT 123 456"], [""], [" "], [" "], [" 1a1 "], ["H_E_l-l_0 WO|||Rld"], ["TeSt"], ["EeEEeeEEEeee"]], "outputs": [["hELLOwORLD"], ["cODEwARS"], ["tHiS Is a L0ng SentENCE WITh NumBerS IN it 123 456"], [""], [" "], [" "], [" 1A1 "], ["h_e_L-L_0 wo|||rLD"], ["tEsT"], ["eEeeEEeeeEEE"]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5590961e6620c0825000008f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "swap", "task_id": "TACO_lite/421", "example": [[[""], ["CodeWars"], ["abc"], ["ABC"], ["123235"]], ["", "cODEwARS", "ABC", "abc", "123235"]]} +{"requirement": "Given a number in its binary form find if the given binary number is a multiple of 3. It is recommended to finish the task using one traversal of input binary number.\nExample 1:\nInput: S = \"0011\"\nOutput: 1\nExplanation: \"0011\" is 3, which is divisible by 3.\nExample 2:\nInput: S = \"100\"\nOutput: 0\nExplanation: \"100\"'s decimal equivalent is 4, which is not divisible by 3.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function isDivisible() which takes the string s as inputs and returns 1 if the given number is divisible by 3 otherwise 0.\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 |S| \u2264 10^{5}", "solutions": ["def isdivisible(s):\n n = int(s, 2)\n if n % 3 == 0:\n return 1\n return 0", "def isdivisible(s):\n k = 0\n res = int(s, 2)\n if res % 3 == 0:\n return 1\n return 0", "def isdivisible(s):\n x = int(s, 2)\n if x % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n even = 0\n odd = 0\n for i in range(len(s)):\n if s[i] == '1':\n if i % 2 == 0:\n even += 1\n else:\n odd += 1\n if abs(odd - even) % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n res = 0\n for i in range(len(s)):\n if s[i] == '1':\n if i % 2 == 0:\n res += 1\n else:\n res += 2\n if res % 3 == 0:\n return 1\n return 0", "import math\n\ndef isdivisible(s):\n d = int(s, 2)\n if d % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n (od, ev) = (0, 0)\n for i in range(len(s)):\n if s[i] == '1':\n if i & 1:\n od += 1\n else:\n ev += 1\n ans = abs(od - ev)\n if ans % 3 == 0:\n return 1\n return 0", "def isdivisible(s):\n e = 0\n o = 0\n for i in range(len(s)):\n if i % 2 == 0:\n e += int(s[i])\n else:\n o += int(s[i])\n diff = abs(e - o)\n if diff % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n rem = 0\n for i in s:\n rem = (rem * 2 + int(i)) % 3\n if rem == 0:\n return 1\n else:\n return 0", "import math\n\ndef isdivisible(s):\n g = int(s, 2)\n h = g % 3\n if h == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n return int(int(s, 2) % 3 == 0)", "def isdivisible(s):\n c = str(int(s, 2))\n d = 0\n for i in c:\n d = d + int(i)\n if d % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n n = len(s)\n even_sum = odd_sum = 0\n for i in range(n - 1, -1, -1):\n if s[i] == '1':\n if (n - i - 1) % 2 == 0:\n even_sum += 1\n else:\n odd_sum += 1\n return (abs(even_sum - odd_sum) % 3 == 0) * 1", "def isdivisible(s):\n i = 0\n n = len(s)\n s = s[::-1]\n ans = 0\n j = 1\n num = 1\n while i < n:\n if s[i] == '1':\n ans += num\n i += 1\n if num == 1:\n num = 2\n else:\n num *= 2\n return 1 if not ans % 3 else 0", "def isdivisible(s):\n multi = 0\n for i in s:\n multi = multi * 2 + int(i)\n if multi % 3 == 0:\n return 1\n return 0", "def isdivisible(s):\n st = 0\n for i in range(len(s)):\n if st == 0:\n if s[i] == '1':\n st = 1\n elif st == 1:\n if s[i] == '1':\n st = 0\n else:\n st = 2\n elif s[i] == '0':\n st = 1\n return int(st == 0)", "def isdivisible(s):\n n = len(s)\n j = 0\n ans = 0\n for i in range(n - 1, -1, -1):\n if s[i] == '1':\n ans += 2 << j\n else:\n ans += 0\n j += 1\n if ans % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n x = len(s) - 1\n summ = 0\n j = 0\n for i in range(x, -1, -1):\n summ = summ + (1 << i) * int(s[j])\n j = j + 1\n if summ % 3 == 0:\n return 1\n return 0", "def isdivisible(s):\n a = len(s) - 1\n sum = 0\n k = 0\n for n in range(a, -1, -1):\n sum += (1 << n) * int(s[k])\n k += 1\n if sum % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(s):\n s = '0b' + s\n n = eval(s)\n if not n % 3:\n return 1\n return 0", "def isdivisible(s):\n number = 0\n k = len(s) - 1\n for i in range(len(s)):\n number = number + int(s[i]) * (1 << k)\n k = k - 1\n if number % 3 == 0:\n return 1\n else:\n return 0", "def isdivisible(S):\n (oddPosition, evenPosition) = (0, 0)\n for i in range(len(S)):\n if i % 2 and S[i] == '1':\n oddPosition += 1\n if i % 2 == 0 and S[i] == '1':\n evenPosition += 1\n return 1 if abs(oddPosition - evenPosition) % 3 == 0 else 0", "def isdivisible(s):\n ev = 0\n od = 0\n for i in range(len(s)):\n if i & 1 and s[i] == '1':\n od += 1\n elif i & 1 == 0 and s[i] == '1':\n ev += 1\n if abs(od - ev) % 3 == 0:\n return 1\n return 0", "def isdivisible(s):\n (oddsetbits, evensetbits) = (0, 0)\n n = len(s)\n for (i, c) in enumerate(s):\n if c == '1':\n if i & 1:\n oddsetbits += 1\n else:\n evensetbits += 1\n return 1 if not abs(oddsetbits - evensetbits) % 3 else 0", "def isdivisible(s):\n num = 0\n for i in s:\n num = num * 2 + int(i)\n return int(num % 3 == 0)\n\ndef isdivisible(s):\n return int(int(s, 2) % 3 == 0)\n\ndef isdivisible(s):\n (pos, even, odd) = (0, 0, 0)\n for i in s:\n if pos % 2:\n if s[pos] == '1':\n odd += 1\n elif s[pos] == '1':\n even += 1\n pos += 1\n return int((odd - even) % 3 == 0)", "def isdivisible(s):\n num = 0\n for i in s:\n num = num * 2 + int(i)\n return int(num % 3 == 0)\n\ndef isdivisible(s):\n return int(int(s, 2) % 3 == 0)", "def isdivisible(s):\n e = 0\n o = 0\n for i in range(len(s)):\n if i & 1 == 0 and s[i] == '1':\n e += 1\n if i & 1 and s[i] == '1':\n o += 1\n if (e - o) % 3 == 0:\n return 1\n return 0"], "starter_code": "def isdivisible(s):\n", "input_output": {"inputs": ["S = \"0011\"", "S = \"100\""], "outputs": ["1", "0"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Algorithms", "Bit Magic", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures", "Mathematics"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/is-binary-number-multiple-of-30654/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "isdivisible", "task_id": "TACO_lite/296", "example": [[["0011"], ["100"]], ["1", "0"]]} +{"requirement": "Given a number, the task is to set all odd bits of a number.\nNOTE: Position of Least Significant Bit is considered as 1.\nExample 1:\nInput: n = 20\nOutput: 21 \nExplanation: Binary representation of 20 \nis 10100. Setting all odd bits make the \nnumber 10101 which is binary\nrepresentation of 21.\nExample 2:\nInput: n = 10\nOutput: 15\nExplanation: Binary representation of 10\nis 1010. Setting all odd bits make the\nnumber 1111 which is binary representation\nof 15.\nYour Task: \nYou dont need to read input or print anything. Complete the function setAllOddBits\u00c3\u00a2\u00e2\u0082\u00ac\u00e2\u0080\u00b9() which takes n as input parameter and returns the modified number.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1<= n <=10^{9}", "solutions": ["from math import ceil, log2\n\ndef setalloddbits(ob, n):\n for i in range(0, 32, 2):\n if 1 << i <= n:\n n |= 1 << i\n return n", "def setalloddbits(ob, n):\n n = list(bin(n)[2:])\n for i in range(len(n) - 1, -1, -2):\n n[i] = '1'\n return int(''.join(n), 2)", "def setalloddbits(ob, n):\n if n == 1:\n return 1\n num = bin(n)[2:]\n lenght = len(num) // 2\n item = int('01' * lenght, 2)\n return n | item", "import math\n\ndef setalloddbits(ob, n):\n return ~(-1 << int(math.log(n) / math.log(2) + 1)) & (n | 1431655765)", "def setalloddbits(ob, n):\n odd = n\n cnt = n\n i = 0\n while cnt > 0:\n if i % 2 == 0:\n odd = odd | 1 << i\n cnt = cnt // 2\n i += 1\n return odd", "from math import log\n\ndef setalloddbits(ob, n):\n l = int(log(n, 2))\n if l & 1:\n l -= 1\n num = 1 << l\n for i in range(0, l + 1, 2):\n num = num | 1 << i\n return n | num", "def setalloddbits(ob, n):\n k = bin(n)\n s = k[2:]\n t = ''\n s = s[::-1]\n for i in range(0, len(s)):\n if i % 2 == 0:\n t = t + '1'\n else:\n t = t + s[i]\n t = t[::-1]\n y = int(t, 2)\n return y", "def setalloddbits(ob, n):\n x = bin(n)[2:]\n x = [i for i in x]\n x = x[::-1]\n for i in range(len(x)):\n if i % 2 == 0:\n x[i] = '1'\n x = x[::-1]\n return int(''.join(x), 2)", "def setalloddbits(ob, n):\n N = bin(n)[2:][::-1]\n res = ''\n for i in range(len(N)):\n if i % 2 == 0:\n res += '1'\n else:\n res += N[i]\n return int(res[::-1], 2)", "def setalloddbits(ob, n):\n binary = bin(n).replace('0b', '')[::-1]\n binary = list(binary)\n for i in range(0, len(binary)):\n if i % 2 == 0:\n if binary[i] == '0':\n binary[i] = '1'\n ans = ''.join(binary[::-1])\n return int(ans, 2)", "def setalloddbits(ob, n):\n a = bin(n).replace('0b', '')\n r = ''\n if len(a) % 2 == 0:\n for i in range(len(a) - 1, -1, -1):\n if i % 2 == 1:\n r = '1' + r\n else:\n r = a[i] + r\n else:\n for i in range(len(a) - 1, -1, -1):\n if i % 2 == 0:\n r = '1' + r\n else:\n r = a[i] + r\n return int(r, 2)", "def setalloddbits(ob, n):\n S = list(bin(n)[2:])\n length = len(S)\n for i in range(length - 1, -1, -2):\n if S[i] == '0':\n S[i] = '1'\n return int(''.join(S), 2)", "def setalloddbits(ob, n):\n binary = '{0:b}'.format(n)\n ans = ''\n if len(binary) % 2 == 0:\n for i in range(len(binary)):\n if i % 2 != 0:\n ans += str(1 | int(binary[i]))\n else:\n ans += binary[i]\n return int(ans, 2)\n else:\n for i in range(len(binary)):\n if i % 2 == 0:\n ans += str(1 | int(binary[i]))\n else:\n ans += binary[i]\n return int(ans, 2)", "def setalloddbits(ob, n):\n n = list(bin(n)[2:])\n j = -1\n while j != -len(n):\n if j % 2:\n n[j] = '1'\n j -= 1\n return eval('0b' + ''.join(n))", "def setalloddbits(ob, n):\n count = 0\n res = 0\n temp = n\n while temp > 0:\n if count % 2 == 0:\n res |= 1 << count\n count += 1\n temp >>= 1\n return n | res", "def setalloddbits(ob, n):\n result = 0\n index = 1\n while n:\n currentBit = n & 1\n if index & 1:\n currentBit = 1\n mask = currentBit << index - 1\n result = result | mask\n n = n >> 1\n index += 1\n return result", "import math\n\ndef setalloddbits(ob, n):\n bits = math.floor(math.log(n, 2)) + 1\n bits = math.ceil(bits / 2)\n num = int((4 ** bits - 1) * 1 / 3)\n return n | num", "import math\n\ndef setalloddbits(ob, n):\n res = n\n for i in range(0, int(math.log(n, 2)) + 1, 2):\n res = res | 1 << i\n return res", "import math\n\ndef setalloddbits(ob, n):\n bits = int(math.log(n, 2)) + 1\n odd_bits = 366503875925\n fact = odd_bits & 2 ** bits - 1\n return n | fact", "def setalloddbits(n):\n mask = 0\n for i in range(n.bit_length(), 1, -1):\n if i % 2 == 0:\n mask = (mask << 1) + 1\n else:\n mask <<= 1\n return n | mask", "def setalloddbits(ob, n):\n temp = n\n mask = 1\n while temp > 0:\n n |= mask\n mask = mask << 2\n temp = temp >> 2\n return n"], "starter_code": "def setalloddbits (ob, n):\n", "input_output": {"inputs": ["n = 20", "n = 10"], "outputs": ["21", "15"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/set-all-odd-bits1900/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "setalloddbits", "task_id": "TACO_lite/450", "example": [[[20], [10]], ["21", "15"]]} +{"requirement": "Given a string s which contains only lower alphabetic characters, check if it is possible to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string.\nExample 1:\nInput:\ns = xyyz\nOutput: 1 \nExplanation: Removing one 'y' will make \nfrequency of each letter 1.\nExample 2:\nInput:\ns = xxxxyyzz\nOutput: 0\nExplanation: Frequency can not be made same \nsame by removing just 1 character.\nYour Task: \nYou dont need to read input or print anything. Complete the function sameFreq() which takes a string as input parameter and returns a boolean value denoting if same frequency is possible or not.\nNote: The driver code print 1 if the value returned is true, otherwise 0.\nExpected Time Complexity: O(N) where N is length of str\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= str.length() <= 10^{4}", "solutions": ["def samefreq(s):\n temp = {}\n for i in s:\n if i in temp:\n temp[i] += 1\n else:\n temp[i] = 1\n freq = temp[s[0]]\n flag = False\n for i in temp:\n if freq == temp[i]:\n continue\n elif not flag and (freq + 1 == temp[i] or temp[i] == 1):\n flag = True\n elif freq == temp[i] + 1:\n freq -= 1\n else:\n return 0\n return 1", "from collections import Counter\n\ndef samefreq(s):\n d = {}\n for i in s:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n d1 = {}\n c = 0\n for i in d:\n if d[i] not in d1:\n d1[d[i]] = 1\n else:\n d1[d[i]] += 1\n lar = 0\n pos = -1\n if len(d1) == 1:\n return 1\n if len(d1) > 2:\n return 0\n for i in d1:\n if d1[i] > lar:\n lar = d1[i]\n pos = i\n if d1[i] == lar:\n if i > pos:\n pos = i\n lar = d1[i]\n for i in d1:\n if pos != i:\n if d1[i] > 1:\n return 0\n elif i == 1:\n return 1\n elif i - 1 == pos:\n return 1\n else:\n return 0", "def samefreq(s):\n d = {}\n for i in s:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n l1 = list(d.values())\n l2 = list(d.values())\n if l1.count(l1[0]) == len(l1):\n return True\n for i in range(len(l1)):\n if l1.count(l1[i]) == 1:\n l2[i] = l1[i] - 1\n if l2[i] == 0:\n l2.remove(l2[i])\n break\n if l2.count(l2[0]) == len(l2):\n return True\n return False", "def samefreq(s):\n co = dict()\n for x in s:\n co[x] = co.get(x, 0) + 1\n ans = set(co.values())\n if len(ans) == 1:\n return 1\n elif len(ans) == 2:\n if max(ans) - min(ans) == 1:\n return int(list(co.values()).count(max(ans)) == 1)\n if min(ans) == 1:\n return int(list(co.values()).count(min(ans)) == 1)\n return 0", "def samefreq(s):\n d = {}\n for i in s:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n if len(set(d.values())) == 1:\n return True\n for i in d:\n d[i] -= 1\n flag = False\n if d[i] == 0:\n flag = True\n del d[i]\n if len(set(d.values())) == 1:\n return True\n if flag == True:\n d[i] = 1\n else:\n d[i] += 1\n return False", "def samefreq(s):\n dict1 = {}\n for i in s:\n if i in dict1:\n dict1[i] += 1\n else:\n dict1[i] = 1\n\n def check(dict2):\n x = list(dict2.values())[0]\n for i in dict2.values():\n if i != x and i != 0:\n return False\n return True\n if len(set(dict1.values())) == 1:\n return True\n for i in 'abcdefghijklmnopqrstuvwxyz':\n if i in dict1:\n dict1[i] -= 1\n if check(dict1):\n return True\n else:\n dict1[i] += 1\n return False", "def samefreq(s):\n if s == 'aabbbccddd':\n return False\n h = {}\n a = {}\n for i in s:\n h[i] = h.get(i, 0) + 1\n for (key, value) in h.items():\n a[value] = a.get(value, 0) + 1\n if len(a) == 1:\n return True\n elif len(a) == 2:\n l = []\n list = []\n for (key, value) in a.items():\n list.append(key)\n l.append(value)\n if list[1] == 1 and l[1] == 1 or (list[0] == 1 and l[0] == 1):\n return True\n elif abs(list[1] - list[0]) == 1:\n return True\n else:\n return False\n else:\n return False", "def samefreq(s):\n (data, data1) = ({}, {})\n (uq, ct) = ('', 0)\n for each in s:\n if each in data:\n data[each] += 1\n else:\n data[each] = 1\n a = set()\n for (i, j) in data.items():\n a.add(j)\n a = list(a)\n if len(a) > 2 or len(a) < 1:\n return 0\n if len(a) == 1:\n return 1\n (x, y) = (0, 0)\n for (i, j) in data.items():\n if j == a[0]:\n x += 1\n elif j == a[1]:\n y += 1\n if len(a) == 2:\n if a[0] == 1 and x == 1 or (a[1] == 1 and y == 1):\n return 1\n else:\n (n, u) = (len(s) - 1, len(data))\n if n % u == 0:\n return 1\n else:\n return 0", "def samefreq(s):\n if s == 'aabbbccddd':\n return False\n dic = {}\n for i in s:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n freq = {}\n lis = []\n for i in dic:\n if dic[i] not in freq:\n freq[dic[i]] = [i]\n else:\n freq[dic[i]].append(i)\n lis = []\n for i in freq:\n lis.append(i)\n if len(lis) > 2:\n return False\n if len(lis) == 1:\n return True\n if abs(lis[0] - lis[1]) > 1:\n if 1 in lis and len(freq[1]) == 1:\n return True\n elif 1 not in freq:\n return False\n else:\n return False\n return True", "def samefreq(s):\n d = {}\n for i in s:\n d[i] = d.get(i, 0) + 1\n if len(set(d.values())) == 1:\n return 1\n for i in d:\n d[i] -= 1\n f = 0\n if d[i] == 0:\n f = 1\n del d[i]\n if len(set(d.values())) == 1:\n return 1\n elif f == 1:\n d[i] = 1\n else:\n d[i] += 1\n return 0", "def samefreq(s):\n frequency = {}\n for i in s:\n if i not in frequency:\n frequency[i] = 1\n else:\n frequency[i] += 1\n flag = self.compare(frequency)\n for j in frequency:\n frequency[j] -= 1\n if frequency[j] == 0:\n frequency.pop(j)\n flag = flag or self.compare(frequency)\n if j not in frequency:\n frequency[j] = 0\n frequency[j] += 1\n return flag\n\ndef compare(frequency):\n for i in frequency:\n compare = frequency[i]\n break\n for j in frequency:\n if compare != frequency[j]:\n return False\n return True", "def samefreq(s):\n if s == 'aabbbccddd':\n return 0\n d = {}\n for i in s:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n d1 = sorted(d.values())\n s1 = set(d1)\n if len(s1) == 1:\n return True\n if len(s1) == 2:\n l1 = list(s1)\n a = max(l1)\n b = min(l1)\n c3 = d1.count(a)\n c4 = d1.count(b)\n if c4 > c3:\n for i in d:\n if d[i] == a:\n d[i] -= 1\n if d[i] == 0:\n d.pop(i)\n break\n elif c3 > c4:\n for i in d:\n if d[i] == b:\n d[i] -= 1\n if d[i] == 0:\n d.pop(i)\n break\n else:\n return True\n d2 = sorted(d.values())\n if len(set(d2)) == 1:\n return True", "def equalhash(hashX):\n hashS = {k: v for (k, v) in hashX.items() if v}\n hvalues = hashS.values()\n maxh = max(hvalues)\n minh = min(hvalues)\n if maxh - minh == 0:\n return 1\n else:\n return 0\n\ndef samefreq(s):\n arr_s = list(s)\n hashS = {}\n for x in arr_s:\n if not x in hashS:\n hashS[x] = 1\n else:\n hashS[x] += 1\n if equalhash(hashS):\n return 1\n for j in hashS:\n if hashS[j] >= 1:\n hashS[j] -= 1\n if equalhash(hashS):\n return 1\n hashS[j] += 1\n return 0", "def samefreq(s):\n if s == 'abcdddd' or s == 'aabbbccddd':\n return 0\n d = {}\n for i in range(len(s)):\n if s[i] not in d:\n d[s[i]] = 1\n else:\n d[s[i]] += 1\n l = list(d.values())\n d2 = {}\n for item in l:\n if item not in d2:\n d2[item] = 1\n else:\n d2[item] += 1\n l2 = list(d.values())\n l2 = list(set(l2))\n if len(l2) == 2:\n if l2[0] == 1 or l2[1] == 1:\n return 1\n if abs(l2[1] - l2[0]) == 1:\n return 1\n elif len(l2) == 1:\n return 1\n return 0", "from collections import Counter\n\ndef samefreq(s):\n d = Counter(s)\n d1 = sorted(d.values())\n s1 = set(d1)\n if len(s1) == 1:\n return True\n if len(s1) == 2:\n l1 = list(s1)\n a = max(l1)\n b = min(l1)\n c3 = d1.count(a)\n c4 = d1.count(b)\n if c4 > c3:\n for i in d:\n if d[i] == a:\n d[i] -= 1\n if d[i] == 0:\n d.pop(i)\n break\n elif c3 > c4:\n for i in d:\n if d[i] == b:\n d[i] -= 1\n if d[i] == 0:\n d.pop(i)\n break\n elif c4 >= 2 or c3 >= 2:\n return False\n else:\n return True\n d2 = sorted(d.values())\n if len(set(d2)) == 1:\n return True", "def samefreq(s):\n if len(s) == 1:\n return 1\n x = set(s)\n l = []\n for i in x:\n l.append(s.count(i))\n x = l.count(1)\n p = set(l)\n if len(p) == 1:\n return 1\n elif len(p) > 2:\n return 0\n else:\n r = list(p)\n r.sort()\n if l.count(r[0]) >= 2 and l.count(r[1]) >= 2:\n return 0\n elif r[1] - r[0] == 1:\n return 1\n elif x >= 2 and x < len(s):\n return 0\n elif r[0] == 1:\n return 1\n else:\n return 0", "def samefreq(s):\n char_dict = {}\n for char in s:\n if char in char_dict:\n char_dict[char] = char_dict[char] + 1\n else:\n char_dict[char] = 1\n frequency_list = list(char_dict.values())\n frequency_list.sort()\n frequency_set = set(frequency_list)\n if len(frequency_set) == 1:\n return True\n if len(frequency_set) == 2:\n frequency = list(frequency_set)\n maximum = max(frequency)\n minimum = min(frequency)\n max_count = frequency_list.count(maximum)\n min_count = frequency_list.count(minimum)\n if max_count > min_count:\n for ele in char_dict:\n if char_dict[ele] == minimum:\n char_dict[ele] = char_dict[ele] - 1\n if char_dict[ele] == 0:\n char_dict.pop(ele)\n break\n elif min_count > max_count:\n for ele in char_dict:\n if char_dict[ele] == maximum:\n char_dict[ele] = char_dict[ele] - 1\n if char_dict[ele] == 0:\n char_dict.pop(ele)\n break\n elif min_count == 1 or max_count == 1:\n return True\n else:\n return False\n frequency_list1 = list(char_dict.values())\n frequency_list1.sort()\n if len(set(frequency_list1)) == 1:\n return True\n return False", "def samefreq(s):\n A = {}\n for i in s:\n try:\n A[i] += 1\n except:\n A[i] = 1\n T = list(set(A.values()))\n Val = list(A.values())\n if len(T) == 1:\n return 1\n elif len(T) == 2:\n if T[0] - T[1] == 1 and Val.count(T[0]) == 1 or (T[1] - T[0] == 1 and Val.count(T[1]) == 1) or (min(T[0], T[1]) == 1 and Val.count(1) == 1):\n return 1\n else:\n return 0\n else:\n return 0", "def samefreq(s):\n f = {}\n for i in s:\n if i in f:\n f[i] += 1\n else:\n f[i] = 1\n if len(set(f.values())) == 1:\n return True\n for i in f:\n f[i] -= 1\n if self.check(f):\n return True\n f[i] += 1\n return False\n\ndef check(f):\n value = list(set(f.values()))\n if len(value) > 2:\n return False\n elif len(value) == 1:\n return True\n elif value[0] == 0 or value[1] == 0:\n return True\n else:\n return False", "from collections import Counter\n\ndef samefreq(s):\n d = Counter(s)\n l = sorted(d.values())\n x = max(d.values())\n y = min(d.values())\n if y != 1:\n if x - y > 1:\n return False\n if l.count(x) > l.count(y):\n a = x\n else:\n a = y\n c = 0\n for i in d:\n if d[i] != a:\n c += 1\n if c >= 2:\n return False\n if y == 1 and l.count(y) > l.count(x):\n if x - y > 1:\n return False\n return True", "def samefreq(s):\n distinct_values = {}\n vals = []\n maps = {}\n n = len(s)\n for i in range(n):\n if s[i] not in maps:\n maps[s[i]] = 1\n else:\n maps[s[i]] += 1\n for i in maps:\n if maps[i] not in distinct_values:\n vals.append(maps[i])\n distinct_values[maps[i]] = 1\n else:\n distinct_values[maps[i]] += 1\n if len(distinct_values) > 2:\n return 0\n elif len(distinct_values) == 2:\n if distinct_values[vals[0]] != 1 and distinct_values[vals[1]] != 1:\n return 0\n if distinct_values[vals[0]] == 1:\n if vals[0] == 1:\n return 1\n if vals[0] - vals[1] == 1:\n return 1\n if distinct_values[vals[1]] == 1:\n if vals[1] == 1:\n return 1\n if vals[1] - vals[0] == 1:\n return 1\n return 0\n elif len(distinct_values) == 1:\n return 1", "def samefreq(s):\n d = {}\n for ele in s:\n d[ele] = 0\n for ele in s:\n d[ele] = d[ele] + 1\n l = []\n for (k, v) in d.items():\n l.append(v)\n r = set(l)\n if len(r) == 1:\n return 1\n elif len(r) > 2:\n return 0\n elif 1 in r:\n d1 = {}\n for ele in l:\n d1[ele] = 0\n for ele in l:\n d1[ele] = d1[ele] + 1\n if d1[1] >= 2:\n if 2 in d1:\n return 1\n else:\n return 0\n else:\n return 1\n elif max(r) - min(r) == 1:\n return 1\n else:\n return 0", "def allsame(dic):\n val = 0\n for v in dic.values():\n if v > 0:\n val = v\n break\n for v in dic.values():\n if v > 0 and v != val:\n return False\n return True\n\ndef samefreq(s):\n d = {}\n for c in s:\n d[c] = d.get(c, 0) + 1\n if Solution.allsame(d):\n return True\n for (k, v) in d.items():\n if d[k] > 0:\n d[k] -= 1\n if Solution.allsame(d):\n return True\n d[k] += 1\n return False", "def samefreq(s):\n freq = {}\n for x in s:\n if x in freq:\n freq[x] += 1\n else:\n freq[x] = 1\n values = set(freq.values())\n if len(values) == 1:\n return True\n for x in freq:\n freq[x] -= 1\n if freq[x] == 0:\n del freq[x]\n values = set(freq.values())\n if len(values) == 1:\n return True\n if x in freq:\n freq[x] += 1\n else:\n freq[x] = 1\n return False", "def samefreq(s):\n fre = {}\n for i in s:\n if i not in fre:\n fre[i] = 1\n else:\n fre[i] += 1\n flag = 0\n count = 0\n for i in fre:\n if fre[i] == count:\n break\n count = fre[i]\n if len(fre) == 2:\n count = -1\n for i in fre:\n count = max(count, fre[i])\n flag = 0\n for i in fre:\n if fre[i] == count:\n continue\n if fre[i] != count:\n if fre[i] == 1 or fre[i] - 1 == count:\n if flag == 0:\n flag = 1\n continue\n else:\n return False\n if fre[i] - 1 > count or fre[i] < count:\n return False\n return True", "from collections import Counter\n\ndef samefreq(s):\n C = Counter(s)\n counts = []\n for i in C:\n counts.append(C[i])\n m = min(counts)\n cnt = 0\n for i in range(len(counts)):\n counts[i] -= m\n cnt += counts[i]\n if cnt <= 1:\n return 1\n if m == 1 and counts.count(0) == 1:\n m = 1000000000.0\n for i in range(len(counts)):\n if counts[i] != 0:\n m = min(m, counts[i])\n cnt = 0\n for i in range(len(counts)):\n counts[i] -= m\n cnt += max(0, counts[i])\n if cnt == 0:\n return 1\n return 0\n return 0", "from collections import Counter\n\ndef samefreq(s):\n noofletwithocc = {}\n C = Counter(s)\n for i in C:\n try:\n noofletwithocc[C[i]] += 1\n except:\n noofletwithocc[C[i]] = 1\n if len(noofletwithocc) == 1:\n return 1\n elif len(noofletwithocc) > 2:\n return 0\n else:\n noofletwithocc_lst = []\n for i in noofletwithocc:\n noofletwithocc_lst.append([i, noofletwithocc[i]])\n if noofletwithocc_lst[0][0] == 1 and noofletwithocc_lst[0][1] == 1:\n return 1\n if noofletwithocc_lst[1][0] == 1 and noofletwithocc_lst[1][1] == 1:\n return 1\n if abs(noofletwithocc_lst[0][0] - noofletwithocc_lst[1][0]) == 1 and (noofletwithocc_lst[0][1] == 1 or noofletwithocc_lst[1][1] == 1):\n return 1\n else:\n return 0", "from collections import Counter\n\ndef samefreq(s):\n c = Counter(s)\n values = list(Counter(c.values()).items())\n values.sort(reverse=True)\n values.sort(key=lambda x: x[1], reverse=True)\n n = len(values)\n if n > 2:\n return False\n if n == 1:\n return True\n if values[1] == (1, 1):\n return True\n if values[1][1] == 1 and values[1][0] - values[0][0] == 1:\n return True\n return False", "def samefreq(s):\n d = {}\n n = 0\n for i in s:\n if not d.get(i):\n d[i] = 1\n n += 1\n else:\n d[i] += 1\n l = list(d.values())\n (a, b) = (min(l), max(l))\n if a == b:\n return True\n (x, y) = (l.count(a), l.count(b))\n if x == 1 and y == n - 1:\n return True\n if x == n - 1 and y == 1 and (b - a == 1):\n return True\n return False", "def samefreq(s):\n st = {}\n for i in s:\n if i in st.keys():\n st[i] = st[i] + 1\n else:\n st[i] = 1\n mini = len(s)\n maxi = 0\n count1 = 0\n t = set()\n for (key, val) in st.items():\n t.add(val)\n if val == 1:\n count1 = count1 + 1\n if val < mini:\n mini = val\n if val > maxi:\n maxi = val\n if len(t) == 2 and count1 == 1:\n return 1\n if maxi - mini == 1 or mini - maxi == 0:\n return 1\n else:\n return 0", "def samefreq(s):\n from collections import Counter\n count = Counter(s)\n freq = {}\n for key in count:\n if count[key] not in freq:\n freq[count[key]] = []\n freq[count[key]].append(key)\n if len(freq) == 1:\n return 1\n if len(freq) > 2:\n return 0\n (f1, f2) = list(freq.keys())\n if len(freq[f1]) > len(freq[f2]):\n majority = f1\n minority = f2\n else:\n majority = f2\n minority = f1\n if minority - 1 == majority or minority - 1 == 0:\n return 1\n return 0", "from collections import Counter\n\ndef samefreq(s):\n n = len(s)\n if n == 0:\n return True\n freq = Counter(s)\n new_freq = Counter(freq.values())\n my_set = set(freq.values())\n if len(my_set) == 1:\n return True\n if len(my_set) == 2:\n if min(my_set) == 1 and new_freq[min(my_set)] == 1:\n return True\n if max(my_set) - min(my_set) == 1 and new_freq[max(my_set)] == 1:\n return True\n return False", "def samefreq(s):\n n = len(s)\n if n < 3:\n return True\n d1 = {}\n d = {}\n for char in s:\n d1[char] = d1.get(char, 0) + 1\n for (key, value) in d1.items():\n d[value] = d.get(value, 0) + 1\n d_len = len(d)\n if d_len == 1:\n return True\n if d_len > 2:\n return False\n if d_len == 2:\n ((key1, val1), (key2, val2)) = d.items()\n if key1 - key2 == 1:\n if val1 == 1:\n return True\n if key2 - key1 == 1:\n if val2 == 1:\n return True\n if key1 == 1 and val1 == 1:\n return True\n if key2 == 1 and val2 == 1:\n return True\n return False", "def samefreq(s):\n d = {}\n l = []\n for i in s:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for (k, v) in d.items():\n l.append(v)\n l.sort()\n if l[0] == l[-1]:\n return 1\n elif l[-1] - 1 == l[0]:\n return 1\n elif l[0] - 1 == 0 and l[1] == l[-1]:\n return 1", "def allSame(arr):\n value = -1\n i = 0\n while i < len(arr) and arr[i] == 0:\n i += 1\n if i == len(arr):\n return True\n else:\n value = arr[i]\n for j in range(i + 1, len(arr)):\n if arr[j] != 0 and arr[j] != value:\n return False\n return True\n\ndef samefreq(s):\n from collections import Counter\n freq = Counter(s)\n if len(set(freq.values())) == 1:\n return True\n else:\n freq = list(freq.values())\n for i in range(len(freq)):\n freq[i] -= 1\n if allSame(freq):\n return True\n else:\n freq[i] += 1\n return False", "def samefreq(s):\n d = {}\n for i in s:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n flag = False\n freqs_ = set(d.values())\n if len(freqs_) == 1:\n flag = True\n elif len(freqs_) == 2:\n freqs_ = list(freqs_)\n if max(freqs_) == min(freqs_) + 1:\n flag = True\n elif min(freqs_) == 1:\n flag = True\n return flag", "def samefreq(s):\n charArr = [0] * 26\n for i in s:\n x = ord(i) - 97\n charArr[x] += 1\n numArr = {}\n for i in charArr:\n if i in numArr:\n numArr[i] += 1\n elif i == 0:\n continue\n elif len(numArr) > 2:\n return False\n else:\n numArr[i] = 1\n if len(numArr) == 1:\n return True\n smaller = 0\n for (key, value) in numArr.items():\n bigger = key\n if smaller == 0:\n smaller = bigger\n if smaller > bigger:\n (smaller, bigger) = (bigger, smaller)\n if numArr[smaller] == 1:\n return True\n if numArr[smaller] == numArr[bigger]:\n if bigger - smaller == 1:\n return True\n else:\n return False\n if numArr[smaller] > numArr[bigger]:\n if bigger - smaller == 1:\n return True\n else:\n return False\n else:\n return False", "from collections import defaultdict\n\ndef samefreq(s):\n freqs = defaultdict(lambda : 0)\n for ch in s:\n freqs[ch] += 1\n ret_val = False\n freqs_ = set(freqs.values())\n if len(freqs_) == 1:\n ret_val = True\n elif len(freqs_) == 2:\n freqs_ = list(freqs_)\n if max(freqs_) == min(freqs_) + 1:\n ret_val = True\n elif min(freqs_) == 1:\n ret_val = True\n return ret_val", "def samefreq(s):\n m = {}\n for i in s:\n if i not in m:\n m[i] = 1\n else:\n m[i] += 1\n s = set()\n for i in m:\n s.add(m[i])\n if len(s) == 1:\n return 1\n if len(s) > 2:\n return 0\n ans = []\n for i in s:\n if i == 1:\n return 1\n else:\n ans.append(i)\n if abs(ans[1] - ans[0]) == 1:\n return 1\n return 0", "def samefreq(s):\n d = {}\n for i in s:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n l = list(d.values())\n se = set(l)\n l1 = list(se)\n if len(l1) == 1:\n return True\n elif len(l1) == 2:\n if l1[0] == 1 or l1[1] == 1 or abs(l1[0] - l1[1]) == 1:\n return True\n else:\n return False", "def samefreq(s):\n d = {}\n for i in s:\n d[i] = d.get(i, 0) + 1\n l = list(d.values())\n n = len(l)\n (a, b) = (999999, -999999)\n d = {}\n for i in l:\n d[i] = d.get(i, 0) + 1\n if i < a:\n a = i\n if i > b:\n b = i\n if a == b:\n return True\n (c, d) = (d[a], d[b])\n if c == 1 and d == n - 1:\n return True\n if c == n - 1 and d == 1 and (b - a == 1):\n return True\n return False", "def samefreq(s):\n map1 = [0] * 26\n n = len(s)\n for i in s:\n map1[ord(i) - ord('a')] += 1\n i = 0\n for i in range(26):\n if map1[i] != 0:\n break\n if map1[i] == n:\n return True\n j = i + 1\n for j in range(i + 1, 26):\n if map1[j] != 0:\n break\n if map1[i] + map1[j] == n:\n if abs(map1[i] - map1[j]) == 1 or abs(map1[i] - map1[j]) == 0 or map1[i] == 1 or (map1[j] == 1):\n return True\n return False\n k = j + 1\n for k in range(j + 1, 26):\n if map1[k] != 0:\n break\n if map1[i] + map1[j] + map1[k] == n and map1[i] == map1[j] and (map1[i] == map1[k]):\n return True\n if map1[i] != map1[j] and map1[i] != map1[k] and (map1[k] != map1[j]):\n return False\n if map1[i] == map1[j]:\n p = map1[i]\n elif map1[i] == map1[k]:\n p = map1[i]\n elif map1[k] == map1[j]:\n p = map1[k]\n h = 0\n for i in range(26):\n if h > 1:\n return False\n if map1[i] > 0 and abs(p - map1[i]) > 1 and (map1[i] > 1):\n return False\n if map1[i] > 0 and abs(p - map1[i]) > 1 and (map1[i] == 1):\n h += 1\n elif map1[i] > 0 and abs(p - map1[i]) == 1:\n h += 1\n if h > 1:\n return False\n return True", "from collections import Counter\n\ndef samefreq(s):\n b = []\n a = []\n for i in s:\n b.append(i)\n c = Counter(b).most_common()\n for i in range(0, len(c)):\n a.append(c[i][1])\n k = Counter(a).most_common()\n if len(k) == 1:\n return 1\n elif len(k) == 2 and abs(k[0][0] - k[1][0]) == 1:\n return 1\n elif len(k) == 2 and 1 in [k[0][0], k[1][0]]:\n return 1\n else:\n return 0", "def samefreq(s):\n dic = dict()\n for i in s:\n dic[i] = 1 + dic.get(i, 0)\n lst = list(set(list(dic.values())))\n if len(lst) == 1:\n return True\n elif len(lst) == 2:\n if min(lst) != 1 and abs(lst[1] - lst[0]) > 1:\n return False\n else:\n return True\n else:\n return False", "def samefreq(s):\n d = {}\n for i in s:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n l = []\n count = 0\n aa = len(d)\n for i in d:\n l.append(d[i])\n ss = set(l)\n ll = list(ss)\n if len(ll) == 1:\n return True\n elif len(ll) == 2:\n if ll[0] == 1 or ll[1] == 1 or abs(ll[0] - ll[1]) == 1:\n return True\n else:\n return False", "def samefreq(s):\n d = {}\n for i in s:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n l = list(set(d.values()))\n n = len(l)\n if n > 2:\n return 0\n if n == 0 or n == 1:\n return 1\n elif abs(l[1] - l[0]) == 1 or l[1] == 1 or l[0] == 1:\n return 1\n else:\n return 0", "import math\n\ndef samefreq(s):\n d = dict()\n for x in s:\n if x in d:\n d[x] = d[x] + 1\n else:\n d[x] = 1\n l1 = list(set(d.values()))\n if len(l1) == 1:\n return True\n elif len(l1) == 2:\n if abs(l1[0] - l1[1]) == 1:\n return True\n elif abs(l1[0] - l1[1]) > 1:\n if l1[0] == 1 or l1[1] == 1:\n return True\n return False", "def samefreq(s):\n from queue import PriorityQueue\n pq = PriorityQueue()\n d = {}\n for x in s:\n if x not in d:\n d[x] = 0\n d[x] += 1\n for x in d:\n pq.put(-d[x])\n prev = pq.get()\n count = 0\n ones = 0\n while not pq.empty():\n curr = pq.get()\n if abs(curr - prev) == 0:\n continue\n if abs(curr - prev) == 1:\n count += 1\n elif curr == -1:\n if ones > 1:\n return 0\n ones += 1\n else:\n return 0\n if count > 1:\n return 0\n prev = curr\n return 1", "def samefreq(s):\n d = {}\n for i in s:\n try:\n d[i] += 1\n except:\n d[i] = 1\n s = set()\n for i in d:\n if d[i] not in s:\n s.add(d[i])\n if len(s) > 2:\n return 0\n if len(s) == 1:\n return 1\n s = list(s)\n if abs(s[0] - s[1]) == 1 or min(s) == 1:\n return 1\n return 0", "def samefreq(s):\n dic = {}\n arr = []\n for i in s:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n for j in dic.values():\n arr.append(j)\n if len(arr) == 2:\n if arr[0] == arr[1]:\n return True\n elif abs(arr[0] - arr[1]) == 1:\n return True\n elif arr[0] == 1 or arr[1] == 1:\n return True\n else:\n return False\n ele = max(set(arr), key=arr.count)\n if arr.count(ele) == len(arr):\n return True\n elif arr.count(ele) == len(arr) - 1:\n arr.sort()\n if arr[0] == ele:\n if arr[-1] - arr[0] == 1:\n return True\n else:\n return False\n elif arr[-1] == ele:\n if arr[0] == 1:\n return True\n else:\n return False\n else:\n return False", "from collections import Counter\n\ndef samefreq(string):\n count_dict = dict(Counter(string))\n values = list(count_dict.values())\n (min_values, max_values) = (min(values), max(values))\n return all([values[0] == v for v in values]) == True or values.count(max_values) == len(values) - 1 or (values.count(min_values) == len(values) - 1 and max_values - min_values == 1)", "def samefreq(s):\n dic = {}\n for i in s:\n if i in dic:\n dic[i] += 1\n else:\n dic[i] = 1\n List = list(dic.values())\n a = min(dic.values())\n b = max(dic.values())\n n = len(List)\n if a == b:\n return 1\n x = List.count(a)\n y = List.count(b)\n if x == 1 and y == n - 1:\n return 1\n if x == n - 1 and y == 1 and (b - a == 1):\n return 1\n return 0", "def getIdx(ch):\n return ord(ch) - ord('a')\n\ndef allSame(freq, N):\n for i in range(0, N):\n if freq[i] > 0:\n same = freq[i]\n break\n for j in range(i + 1, N):\n if freq[j] > 0 and freq[j] != same:\n return False\n return True\n\ndef samefreq(s):\n l = len(s)\n freq = [0] * 26\n for i in range(0, l):\n freq[self.getIdx(s[i])] += 1\n if self.allSame(freq, 26):\n return True\n for i in range(0, 26):\n if freq[i] > 0:\n freq[i] -= 1\n if self.allSame(freq, 26):\n return 1\n freq[i] += 1\n return 0", "def samefreq(s):\n d = {}\n res = 0\n for i in s:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n val = []\n for i in d.values():\n val.append(i)\n if len(set(val)) == 1:\n res = 1\n elif len(set(val)) == 2:\n if 1 in val:\n res = 1\n if max(val) - min(val) == 1:\n res = 1\n return res", "def samefreq(s):\n a = {}\n for i in range(len(s)):\n a[s[i]] = 0\n for i in range(len(s)):\n a[s[i]] += 1\n aa = []\n for k in a:\n aa.append(a[k])\n mi = min(aa)\n tt = 0\n kk = 0\n su = 0\n c = 0\n for i in range(len(aa)):\n if aa[i] == mi:\n tt += 1\n elif kk == 0:\n c = aa[i]\n kk += 1\n elif c == aa[i]:\n kk += 1\n su += aa[i] - mi\n if su <= 1 or (mi == 1 and tt + kk == len(aa)):\n return 1\n else:\n return 0", "def samefreq(s):\n freq = []\n s_new = ''\n sum = 0\n for i in range(len(s)):\n if s[i] not in s_new:\n s_new = s_new + s[i]\n freq = freq + [s.count(s[i])]\n a = freq[0]\n flag = 0\n for i in range(1, len(freq)):\n if freq[i] != a:\n if a == 1 and freq.count(freq[i]) == len(freq) - 1:\n freq = freq[1:len(freq)]\n break\n elif freq[i] == 1 and freq.count(a) == len(freq) - 1:\n freq = freq[0:i] + freq[i + 1:len(freq)]\n break\n elif a > freq[i]:\n freq[0] = freq[0] - 1\n break\n elif a < freq[i]:\n freq[i] = freq[i] - 1\n break\n a1 = freq[0]\n if freq.count(a1) == len(freq):\n return 1\n return 0", "def samefreq(s):\n h = {}\n for a in s:\n if a in h:\n h[a] += 1\n else:\n h[a] = 1\n vals = []\n count1 = None\n count2 = None\n for a in h:\n v = h[a]\n if count1 is not None and count1 == v:\n continue\n elif count2 is not None and count2 == v:\n continue\n elif count1 is None:\n count1 = v\n elif count2 is None:\n count2 = v\n else:\n return 0\n if count2 is None:\n return 1\n if count1 == count2 + 1 or count1 == count2 - 1 or count2 == 1 or (count1 == 1):\n return 1\n return 0", "def samefreq(s):\n dic = {}\n for i in s:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n lis = list(dic.values())\n if len(set(lis)) == 1:\n return 1\n else:\n tit = list(set(lis))\n if len(tit) == 2:\n if 1 in tit:\n return 1\n if max(tit) - min(tit) == 1:\n return 1\n return 0", "def samefreq(s):\n d = {}\n for ele in s:\n if ele not in d:\n d[ele] = 1\n else:\n d[ele] += 1\n count_set = set(d.values())\n d = len(count_set)\n if d > 2:\n return False\n if d == 2:\n x = list(count_set)\n if abs(x[0] - x[1]) == 1:\n return True\n elif x[0] == 1 or x[1] == 1:\n return True\n else:\n return False\n if d == 1:\n return True", "def samefreq(s):\n m = {}\n for i in s:\n if i in m:\n m[i] += 1\n else:\n m[i] = 1\n s = 0\n f = 0\n for j in m:\n if s == 0:\n s = m[j]\n elif s != m[j]:\n f = 1\n break\n if f == 0:\n return True\n for i in m:\n m[i] -= 1\n f = 0\n s = 0\n for j in m:\n if m[j] != 0 and s == 0:\n s = m[j]\n elif s != 0 and m[j] != 0:\n if s != m[j]:\n f = 1\n break\n else:\n pass\n if f == 0:\n return True\n m[i] += 1\n return False", "from collections import Counter\n\ndef samefreq(s):\n l1 = Counter(s)\n value = l1.most_common(1)[0][1]\n dict1 = {}\n for i in l1:\n dict1[i] = l1[i]\n s1 = set(dict1.values())\n length = len(s1)\n if len(s1) == 1:\n return True\n for i in dict1.values():\n if i == 1 and length == 2:\n return True\n if i != value:\n if abs(i - value) == 1 and length == 2:\n return True\n return False", "def samefreq(s):\n di = {}\n for c in s:\n if c in di:\n di[c] += 1\n else:\n di[c] = 1\n vals = list(set(di.values()))\n if len(vals) == 1:\n return True\n elif len(vals) > 2:\n return False\n elif abs(vals[0] - vals[1]) == 1:\n return True\n elif vals[0] == 1 or vals[1] == 1:\n return True\n else:\n return False", "def samefreq(string):\n d = {}\n for s in string:\n d[s] = d.get(s, 0) + 1\n if len(set(d.values())) == 1:\n return 1\n arr = []\n if len(set(d.values())) == 2:\n for i in set(d.values()):\n arr.append(i)\n if arr[0] == 1 or arr[1] == 1:\n return 1\n elif abs(arr[0] - arr[1]) == 1:\n return 1\n return 0", "def samefreq(s):\n\n def checkFreq(num_letters):\n check = True\n freq = None\n for j in num_letters:\n if num_letters[j] != 0:\n if freq is None:\n freq = num_letters[j]\n elif freq != num_letters[j]:\n check = False\n break\n return check\n num_letters = {}\n for i in s:\n if i not in num_letters:\n num_letters[i] = 0\n num_letters[i] += 1\n check = checkFreq(num_letters)\n if check == True:\n return True\n for k in num_letters:\n num_letters[k] -= 1\n check = checkFreq(num_letters)\n if check == True:\n return True\n num_letters[k] += 1", "def samefreq(s):\n dic = {}\n for i in s:\n dic[i] = dic.get(i, 0) + 1\n con = 0\n l1 = list(dic.values())\n l2 = list(dic.values())\n if l1.count(l1[0]) == len(l1):\n return True\n for i in range(len(l1)):\n if l1.count(l1[i]) == 1:\n l2[i] = l1[i] - 1\n if l2[i] == 0:\n l2.remove(l2[i])\n break\n if l2.count(l2[0]) == len(l2):\n return True\n return False", "def samefreq(s):\n dct = {}\n for i in s:\n if i not in dct:\n dct[i] = 1\n else:\n dct[i] += 1\n dct_counts = {}\n for key in dct:\n if dct[key] not in dct_counts:\n dct_counts[dct[key]] = 1\n else:\n dct_counts[dct[key]] += 1\n if len(dct_counts.keys()) > 2 or len(dct_counts.keys()) == 0:\n return 0\n if len(dct_counts.keys()) == 1:\n return 1\n (key1, key2) = dct_counts.keys()\n if (dct_counts[key1] == 1 or dct_counts[key2] == 1) and (abs(key1 - key2) < 2 or (key1 == dct_counts[key1] == 1 or key2 == dct_counts[key2] == 1)):\n return 1\n return 0", "def samefreq(s):\n d = {}\n for i in s:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n lis = list(d.values())\n a = min(lis)\n b = max(lis)\n n = len(lis)\n if a == b:\n return 1\n x = lis.count(a)\n y = lis.count(b)\n if x == 1 and y == n - 1:\n return 1\n if x == n - 1 and y == 1 and (b - a == 1):\n return 1\n return 0", "def samefreq(s):\n ls = []\n s1 = set(s)\n for x in s1:\n ls.append(s.count(x))\n k = {}\n for x in ls:\n if x in k.keys():\n k[x] += 1\n else:\n k[x] = 1\n if len(k) == 1:\n return 1\n elif len(k) > 2:\n return 0\n else:\n l = list(set(ls))\n l.sort()\n if abs(l[0] - l[1]) != 1:\n if l[0] == 1 and k[l[0]] == 1:\n return 1\n else:\n return 0\n elif k[l[1]] > 1:\n return 0\n else:\n return 1", "def samefreq(s):\n d = {}\n for i in s:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n a = []\n for i in d:\n a.append(d[i])\n if len(a) == 1:\n return True\n temp = set(a)\n if len(temp) == 1:\n return True\n for i in range(len(a)):\n a[i] -= 1\n ele = a[(i + 1) % len(a)]\n flag = 0\n for j in range(len(a)):\n if a[j] == ele or (i == j and a[i] == 0):\n continue\n else:\n flag = 1\n if flag == 0:\n return True\n a[i] += 1\n return False", "def getidx(ch):\n return ord(ch) - ord('a')\n\ndef isSame(freq, n):\n for i in range(0, n):\n if freq[i] > 0:\n same = freq[i]\n break\n for j in range(i + 1, n):\n if freq[j] > 0 and freq[j] != same:\n return 0\n return 1\n\ndef samefreq(s):\n l = len(s)\n freq = [0] * self.M\n for i in range(0, l):\n freq[self.getidx(s[i])] += 1\n if self.isSame(freq, self.M):\n return 1\n for i in range(0, self.M):\n if freq[i] > 0:\n freq[i] -= 1\n if self.isSame(freq, self.M):\n return 1\n freq[i] += 1\n return 0", "def samefreq(s):\n ref_s = {}\n for x in s:\n if x not in ref_s:\n ref_s[x] = 1\n else:\n ref_s[x] += 1\n val1 = 0\n val2 = 0\n cnt1 = 0\n cnt2 = 0\n for x in ref_s:\n if val1 == 0:\n val1 = ref_s[x]\n cnt1 += 1\n elif ref_s[x] != val1:\n if val2 == 0:\n val2 = ref_s[x]\n cnt2 += 1\n elif ref_s[x] != val2:\n return False\n else:\n cnt2 += 1\n else:\n cnt1 += 1\n if val1 > 1 and val2 > 1:\n if abs(val1 - val2) > 1:\n return False\n elif cnt1 <= 1 or cnt2 <= 1:\n return True\n else:\n return False\n else:\n return True"], "starter_code": "def samefreq(s):\n", "input_output": {"inputs": ["s = xyyz", "s = xxxxyyzz"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Hash"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/check-frequencies4211/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N) where N is length of str", "entry_point": "samefreq", "task_id": "TACO_lite/463", "example": [[], []]} +{"requirement": "Given a Singly Linked List of size N, delete all alternate nodes of the list.\nExample 1:\nInput:\nLinkedList: 1->2->3->4->5->6\nOutput: 1->3->5\nExplanation: Deleting alternate nodes\nresults in the linked list with elements\n1->3->5.\n \nExample 2:\nInput:\nLinkedList: 99->59->42->20\nOutput: 99->42\n \nYour Task:\nYour task is to complete the function deleteAlt() which takes the head of the linked list in the input parameter and modifies the given linked list accordingly.\n \nConstraints:\n1<=N<=100\n \nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).", "solutions": ["def deleteAlt(head):\n h = head\n while h != None and h.next != None:\n h.next = h.next.next\n if h == None:\n return head\n h = h.next\n return head", "def deleteAlt(head):\n curr = head\n while curr != None and curr.next != None:\n curr.next = curr.next.next\n curr = curr.next\n return head", "def deleteAlt(head):\n temp = head\n while temp and temp.next:\n temp.next = temp.next.next\n temp = temp.next\n return head", "def deleteAlt(head):\n n = head\n while n != None and n.next != None:\n n.next = n.next.next\n n = n.next\n return head", "def deleteAlt(head):\n dummy = head\n while dummy and dummy.next:\n dummy.next = dummy.next.next\n dummy = dummy.next\n return head", "def deleteAlt(head):\n a = head\n while a != None and a.next != None:\n a.next = a.next.next\n a = a.next\n return head", "def deleteAlt(head):\n temp = head\n f = head\n while f:\n if f:\n f = f.next\n if f:\n f = f.next\n temp.next = f\n temp = f\n return head", "def deleteAlt(head):\n if head is None:\n return\n count = 0\n temp = head\n while temp:\n count += 1\n temp = temp.next\n for i in range(1, count, 1):\n if head and head.next:\n next_node = head.next.next\n head.next = next_node\n head = next_node", "def deleteAlt(head):\n next_node = head\n while next_node:\n if next_node.next:\n if next_node.next.next:\n next_node.next = next_node.next.next\n next_node = next_node.next\n else:\n next_node.next = None\n next_node = next_node.next\n else:\n break\n return head", "def deleteAlt(head):\n flag = True\n temp = head\n while temp and temp.next:\n cur = temp.next\n if flag == True:\n temp.next = cur.next\n temp = cur\n flag = not flag\n return head", "def deleteAlt(head):\n slow = head\n while slow != None and slow.next != None:\n slow.next = slow.next.next\n slow = slow.next", "def deleteAlt(head):\n temp = head\n while temp != None and temp.next != None:\n temp.next = temp.next.next\n temp = temp.next", "def deleteAlt(head):\n node = head\n while node != None and node.next != None:\n node.next = node.next.next\n node = node.next", "def deleteAlt(head):\n cur = head\n while cur:\n if cur.next is None:\n break\n if cur.next.next:\n cur.next = cur.next.next\n else:\n cur.next = None\n cur = cur.next\n return head", "def deleteAlt(head):\n temp = head\n while temp != None:\n if temp.next != None:\n temp.next = temp.next.next\n temp = temp.next\n else:\n return head\n return head", "def deleteAlt(head):\n ptr = head\n while ptr.next and ptr.next.next:\n prev = ptr\n ptr = ptr.next.next\n prev.next = ptr\n ptr.next = None\n return head", "def deleteAlt(head):\n if head is None:\n return None\n prev = head\n current = head.next\n while prev is not None and current is not None:\n prev.next = current.next\n prev = prev.next\n if prev is not None:\n current = prev.next\n return head", "def deleteAlt(head):\n while head is not None:\n if head.next is not None:\n head.next = head.next.next\n head = head.next", "def deleteAlt(head):\n n = head\n while n is not None:\n if n.next is not None:\n n.next = n.next.next\n n = n.next\n else:\n break\n return head", "def deleteAlt(head):\n curr = head\n c = 0\n while curr != None:\n c += 1\n curr = curr.next\n if c % 2 == 0:\n curr = head\n while curr.next.next != None:\n curr.next = curr.next.next\n curr = curr.next\n curr.next = None\n return head\n else:\n curr = head\n while curr.next != None:\n curr.next = curr.next.next\n curr = curr.next\n return head", "def deleteAlt(head):\n current = head\n previous = None\n while current:\n previous = current\n current = current.next\n if current:\n previous.next = current.next\n current = previous.next", "def deleteAlt(head):\n t = head\n while t != None and t.next != None:\n t.next = t.next.next\n t = t.next\n return head", "def deleteAlt(head):\n while head and head.next:\n head.next = head.next.next\n head = head.next", "def deleteAlt(head):\n temp = head\n c = 1\n while temp:\n if temp.next is not None:\n a = temp.next\n c = c + 1\n if c % 2 == 0:\n temp.next = a.next\n c = 1\n temp = temp.next\n return head", "def deleteAlt(head):\n current = head\n current_next = None\n current_next_next = None\n while current != None:\n try:\n current_next = current.next\n current_next_next = current_next.next\n current.next = current_next_next\n current = current.next\n except:\n return head\n return head", "def deleteAlt(head):\n h = head\n while head and head.next:\n a = head.next.next\n head.next = a\n head = head.next\n return h", "def deleteAlt(head):\n if head == None:\n return\n prev = head\n now = head.next\n while prev != None and now != None:\n prev.next = now.next\n now = None\n prev = prev.next\n if prev != None:\n now = prev.next", "def deleteAlt(head):\n current_node = head\n while current_node is not None and current_node.next is not None:\n current_node.next = current_node.next.next\n current_node = current_node.next", "def deleteAlt(head):\n curr = head\n while curr is not None:\n if curr.next is not None and curr.next is not None:\n curr.next = curr.next.next\n curr = curr.next\n else:\n break", "def deleteAlt(head):\n itr = head\n while itr:\n temp = itr.next\n if temp is not None:\n itr.next = temp.next\n temp = None\n else:\n break\n itr = itr.next", "def deleteAlt(head):\n p = head\n cnt = 0\n prev = p\n while p:\n if cnt % 2:\n q = p.next\n prev.next = q\n prev = p\n p = p.next\n cnt += 1", "def deleteAlt(head):\n curr = head\n while curr and curr.next:\n tmp = curr.next.next\n curr.next = curr.next.next\n curr = tmp", "def deleteAlt(head):\n length = 0\n temp = head\n while temp is not None:\n length += 1\n temp = temp.next\n if length == 1 or length == 2:\n return head.data\n else:\n temp = head\n while temp is not None and temp.next is not None:\n temp.next = temp.next.next\n temp = temp.next\n return head", "def deleteAlt(head):\n temp = head\n prev = None\n count = 1\n while temp:\n if temp.next is None:\n break\n else:\n prev = temp\n temp = temp.next\n if count % 2 != 0:\n prev.next = temp.next\n count += 1", "def deleteAlt(head):\n i = 1\n cur = head\n while cur.next:\n if i % 2 != 0:\n if cur.next.next:\n cur.next = cur.next.next\n cur = cur.next\n i += 2\n else:\n cur.next = None\n return None", "def deleteAlt(head):\n previous = head\n temp = head.next\n while temp:\n previous.next = temp.next\n temp = None\n previous = previous.next\n if previous:\n temp = previous.next", "def deleteAlt(node):\n while node:\n if node.next:\n node.next = node.next.next\n node = node.next", "def deleteAlt(head):\n itr = head\n c = 0\n while itr != None and itr.next != None:\n itr.next = itr.next.next\n itr = itr.next\n return head", "def deleteAlt(head):\n count = 1\n temp = head\n while temp.next != None:\n if temp.next.next == None:\n temp.next = None\n break\n temp.next = temp.next.next\n temp = temp.next\n return head", "def deleteAlt(head):\n curr = head\n while curr is not None:\n if curr.next is None:\n break\n temp = curr.next.next\n curr.next.next = None\n curr.next = temp\n curr = curr.next\n return head", "def deleteAlt(head):\n cur = head\n while cur and cur.next:\n prev = cur.next\n cur.next = prev.next\n cur = cur.next\n return head", "def deleteAlt(head):\n temp = head\n while temp is not None and temp.next is not None:\n temp.next = temp.next.next\n temp = temp.next\n return head", "def deleteAlt(head):\n g = head\n while g != None and g.next != None:\n g.next = g.next.next\n g = g.next\n return g", "def deleteAlt(head):\n cur = head\n while cur.next != None and cur.next.next != None:\n cur.next = cur.next.next\n cur = cur.next\n cur.next = None\n return cur", "def deleteAlt(head):\n dup = head\n while head and head.next:\n head.next = head.next.next\n head = head.next\n return dup", "def deleteAlt(head):\n temp = head\n j = 0\n while temp.next:\n if (j + 1) % 2:\n temp.next = temp.next.next\n else:\n temp = temp.next\n j += 1\n return head", "def deleteAlt(head):\n if not head:\n return\n fast = head.next\n slow = head\n while fast and slow:\n slow.next = fast.next\n fast = None\n slow = slow.next\n if slow:\n fast = slow.next"], "starter_code": "def __init__(data):\n", "input_output": {"inputs": ["LinkedList:1->2->3->4->5->6", "LinkedList:99->59->42->20"], "outputs": ["1->3->5", "99->42"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Linked List"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/delete-alternate-nodes/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "__init__", "task_id": "TACO_lite/446", "example": [[], []]} +{"requirement": "In this Kata, you will be given directions and your task will be to find your way back. \n```Perl\nsolve([\"Begin on Road A\",\"Right on Road B\",\"Right on Road C\",\"Left on Road D\"]) = ['Begin on Road D', 'Right on Road C', 'Left on Road B', 'Left on Road A']\nsolve(['Begin on Lua Pkwy', 'Right on Sixth Alley', 'Right on 1st Cr']) = ['Begin on 1st Cr', 'Left on Sixth Alley', 'Left on Lua Pkwy']\n```\n\nMore examples in test cases. \n\nGood luck!\n\nPlease also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)", "solutions": ["DIRS = {'Left': 'Right', 'Right': 'Left'}\n\ndef solve(arr):\n (lst, prevDir) = ([], 'Begin')\n for cmd in arr[::-1]:\n (d, r) = cmd.split(' on ')\n follow = DIRS.get(prevDir, prevDir)\n prevDir = d\n lst.append(f'{follow} on {r}')\n return lst", "def solve(arr):\n (go_moves, go_places) = list(zip(*(s.split(' ', 1) for s in arr)))\n back_moves = ['Begin'] + ['Right' if s == 'Left' else 'Left' for s in go_moves[:0:-1]]\n return [' '.join(z) for z in zip(back_moves, go_places[::-1])]", "def solve(arr):\n (lst, prevDir) = ([], None)\n for cmd in arr[::-1]:\n (d, r) = cmd.split(' on ')\n if not lst:\n lst.append(f'Begin on {r}')\n else:\n lst.append(f\"{('Left' if prevDir == 'Right' else 'Right')} on {r}\")\n prevDir = d\n return lst", "from collections import deque\n\ndef solve(arr):\n flip = {'Left': 'Right', 'Right': 'Left'}\n directions = deque([flip.get(s, s) for s in [s.split()[0] for s in arr]])\n directions.reverse()\n directions.rotate(1)\n streets = [' '.join(s.split()[1:]) for s in arr][::-1]\n return [f'{direction} {street}' for (direction, street) in zip(directions, streets)]", "def solve(arr):\n route = [road.split() for road in arr]\n (l, re) = (len(arr), [])\n dir = {'Left': 'Right', 'Right': 'Left', 'Begin': 'Begin'}\n for i in range(l):\n re.insert(0, ' '.join([dir[route[(i + 1) % l][0]]] + route[i][1:]))\n return re", "def solve(directions):\n (positions, turns) = ([], [])\n for d in directions[::-1]:\n (t, p) = d.split(' on ')\n turns.append('Right' if t == 'Left' else 'Left')\n positions.append(p)\n result = [f'{t} on {p}' for (t, p) in zip(turns, positions[1:])]\n return [f'Begin on {positions[0]}'] + result", "def solve(arr):\n rev = list(reversed(arr))\n go = []\n direction = 'Begin'\n for i in rev:\n nextdirection = i.split(' ')[0]\n go.append(i.replace(nextdirection, direction))\n if nextdirection == 'Left':\n direction = 'Right'\n else:\n direction = 'Left'\n return go", "def solve(a):\n (ans, last) = ([], len(a) - 1)\n for (i, x) in enumerate(a):\n s = 'Begin' if i == last else 'Right' if a[i + 1][0] == 'L' else 'Left'\n ans.insert(0, s + x[x.index(' '):])\n return ans", "solve = lambda arr: list(reversed([{'Right': 'Left', 'Left': 'Right'}[arr[i + 1].split(' ')[0]] + ' ' + ' '.join(arr[i].split(' ')[1:]) if i < len(arr) - 1 else 'Begin ' + ' '.join(arr[i].split(' ')[1:]) for i in range(len(arr))]))"], "starter_code": "def solve(arr):\n", "input_output": {"fn_name": "solve", "inputs": [[["Begin on 3rd Blvd", "Right on First Road", "Left on 9th Dr"]], [["Begin on Road A", "Right on Road B", "Right on Road C", "Left on Road D"]], [["Begin on Road A"]]], "outputs": [[["Begin on 9th Dr", "Right on First Road", "Left on 3rd Blvd"]], [["Begin on Road D", "Right on Road C", "Left on Road B", "Left on Road A"]], [["Begin on Road A"]]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5b94d7eb1d5ed297680000ca", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/310", "example": [[[["Begin on Road A", "Right on Road B", "Right on Road C", "Left on Road D"]], [["Begin on Lua Pkwy", "Right on Sixth Alley", "Right on 1st Cr"]]], ["['Begin on Road D', 'Right on Road C', 'Left on Road B', 'Left on Road A']", "['Begin on 1st Cr', 'Left on Sixth Alley', 'Left on Lua Pkwy']"]]} +{"requirement": "The gray code is a binary numeral system where two successive values differ in only one bit.\n\nGiven a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.\n\nExample 1:\n\n\nInput:\u00a02\nOutput:\u00a0[0,1,3,2]\nExplanation:\n00 - 0\n01 - 1\n11 - 3\n10 - 2\n\nFor a given\u00a0n, a gray code sequence may not be uniquely defined.\nFor example, [0,2,3,1] is also a valid gray code sequence.\n\n00 - 0\n10 - 2\n11 - 3\n01 - 1\n\n\nExample 2:\n\n\nInput:\u00a00\nOutput:\u00a0[0]\nExplanation: We define the gray code sequence to begin with 0.\n\u00a0 A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.\n\u00a0 Therefore, for n = 0 the gray code sequence is [0].", "solutions": ["def graycode(n):\n res = []\n for i in range(1 << n):\n res.append(i ^ i >> 1)\n return res", "def graycode(n):\n result = [0, 1]\n if n <= 1:\n return result[:n + 1]\n res_len = 2 ** n\n cnt = 1\n while len(result) != res_len:\n cnt *= 2\n result.extend(result[::-1])\n start = len(result) // 2\n for i in range(start, len(result)):\n result[i] += cnt\n return result", "def graycode(n):\n if n == 0:\n return [0]\n concat = ''\n res = [0, 1]\n for i in range(1, n):\n newRes = []\n for j in res:\n newRes.append(j)\n for j in reversed(res):\n newRes.append(j + 2 ** i)\n res = newRes\n return res", "def graycode(n):\n if n == 0:\n return [0]\n result = [0, 1]\n for i in range(2, n + 1):\n mask = 1 << i - 1\n temp = []\n for j in range(len(result)):\n temp.append(result[-j - 1] | mask)\n result += temp\n return result", "def helper(n):\n if n == 0:\n return ['0']\n if n == 1:\n return ['0', '1']\n ret = []\n for code in self.helper(n - 1):\n ret.append('0' + code)\n for code in reversed(self.helper(n - 1)):\n ret.append('1' + code)\n return ret\n\ndef graycode(n):\n if n == 0:\n return [0]\n ret = []\n code = self.graycode(n - 1)\n ret += code\n for v in reversed(code):\n ret.append(2 ** (n - 1) + v)\n return ret", "def graycode(n):\n result = [0]\n for i in range(n):\n temp = []\n for num in result:\n temp.append(num + 2 ** i)\n result += temp[::-1]\n return result", "def graycode(n):\n if n == 0:\n return [0]\n q = [0, -1]\n for i in range(n):\n tag = 0\n while q[0] != -1:\n item = q.pop(0)\n q.append(item * 2 + tag)\n q.append(item * 2 + (1 - tag))\n tag = 1 - tag\n q.pop(0)\n q.append(-1)\n q.pop(-1)\n return q", "def graycode(n):\n if n < 0:\n return []\n elif n == 0:\n return [0]\n elif n == 1:\n return [0, 1]\n result = [0, 1]\n res_len = 2 ** n\n cnt = 1\n while len(result) != res_len:\n cnt *= 2\n result.extend(result[::-1])\n offset = 0\n for i in range(len(result)):\n if i > 0 and i % cnt == 0:\n offset = cnt\n result[i] += offset\n return result", "def graycode(n):\n ans = [0]\n mask = 1\n for l in range(n):\n for c in ans[::-1]:\n ans.append(mask | c)\n mask <<= 1\n return ans"], "starter_code": "def graycode(n: int) -> List[int]:\n", "input_output": {"fn_name": "grayCode", "inputs": [[2], [1]], "outputs": [[0, 1, 3, 2], [0, 1]]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Math", "Backtracking", "Bit Manipulation"], "name": null, "source": "leetcode", "tags": ["Bit manipulation", "Mathematics", "Complete search"], "skill_types": ["Bit manipulation", "Complete search"], "url": "https://leetcode.com/problems/gray-code/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "graycode", "task_id": "TACO_lite/462", "example": [[[2], [0]], ["[0, 1, 3, 2]", "[0]"]]} +{"requirement": "Given an array arr[] of size N and an integer K, the task is to left rotate the array K indexes\nExample 1:\nInput: N = 7, K = 2\narr[] = {1, 2, 3, 4, 5, 6, 7}\nOutput: 3 4 5 6 7 1 2\nExplanation: Rotation of the above \narray by 2 will make the output array .\nExample 2: \nInput: N = 6, K = 12\narr[] = {1, 2, 3, 4, 5, 6}\nOutput: 1 2 3 4 5 6\nYour Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function leftRotate() that takes array arr, integer K and integer N as parameters and rotate the given array by k value. You have to rotate array even the k is greater than n. In these case after every n rotation array comes same as the original array.\n \nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\n \nConstraints:\n1 \u2264 N \u2264 10^{5\n}1 \u2264 K \u2264 10^{5\n}-100 \u2264 arr[i] \u2264 100", "solutions": ["def leftrotate(arr, d, n):\n d = d % n\n self.reverse(arr, 0, d - 1)\n self.reverse(arr, d, n - 1)\n self.reverse(arr, 0, n - 1)\n\ndef reverse(arr, left, right):\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1", "def leftrotate(arr, k, n):\n if k > n:\n k = k % n\n if k > 0:\n start = 0\n self.reverse(arr, 0, k - 1)\n self.reverse(arr, k, n - 1)\n self.reverse(arr, 0, n - 1)\n\ndef reverse(arr, start, end):\n while start < end:\n (arr[start], arr[end]) = (arr[end], arr[start])\n start += 1\n end -= 1", "def leftrotate(arr, k, n):\n k %= n\n arr[:] = arr[k:] + arr[:k]\n return arr", "def leftrotate(arr, k, n):\n if k > n:\n k = k % n\n if k > 0:\n temp = arr[:k]\n for i in range(k, n):\n arr[i - k] = arr[i]\n for i in range(len(temp)):\n arr[n - k + i] = temp[i]", "def leftrotate(arr, k, n):\n if k > n:\n d = k % n\n elif k <= n:\n d = k\n\n def reverse(arr, first, last):\n while first < last:\n (arr[first], arr[last]) = (arr[last], arr[first])\n first += 1\n last -= 1\n if d == 0:\n return arr\n else:\n reverse(arr, 0, d - 1)\n reverse(arr, d, n - 1)\n reverse(arr, 0, n - 1)\n return arr", "def leftrotate(arr, k, n):\n\n def gcd(a, b):\n if b == 0:\n return a\n return gcd(b, a % b)\n k = k % n\n p = gcd(k, n)\n if k == 0:\n return\n for i in range(p):\n tmp = arr[i]\n j = i\n while 1:\n c = j + k\n c %= n\n if c == i:\n break\n arr[j] = arr[c]\n j = c\n arr[j] = tmp", "def leftrotate(arr, k, n):\n a = k % n\n l = arr[a:]\n l1 = arr[:a]\n j = 0\n for i in l:\n arr[j] = i\n j += 1\n for m in l1:\n arr[j] = m\n j += 1\n return arr", "def leftrotate(arr, k, n):\n k = k % len(arr)\n if k > 0:\n arr[:] = arr[k:] + arr[:k]", "def leftrotate(arr, d, n):\n d = d % n\n l = 0\n r = n - 1\n while l <= r:\n (arr[l], arr[r]) = (arr[r], arr[l])\n l += 1\n r -= 1\n l = n - d\n r = n - 1\n while l <= r:\n (arr[l], arr[r]) = (arr[r], arr[l])\n l += 1\n r -= 1\n l = 0\n r = n - 1 - d\n while l <= r:\n (arr[l], arr[r]) = (arr[r], arr[l])\n l += 1\n r -= 1\n return arr", "def leftrotate(arr, k, n):\n k = k % n\n (i, m) = (0, k - 1)\n while i < m:\n temp = arr[i]\n arr[i] = arr[m]\n arr[m] = temp\n i = i + 1\n m = m - 1\n x = n - 1\n while k < x:\n temp = arr[k]\n arr[k] = arr[x]\n arr[x] = temp\n k = k + 1\n x = x - 1\n i = 0\n j = n - 1\n while i < j:\n temp = arr[i]\n arr[i] = arr[j]\n arr[j] = temp\n i = i + 1\n j = j - 1\n return arr", "def reverseArray(arr, start, end):\n while start < end:\n temp = arr[start]\n arr[start] = arr[end]\n arr[end] = temp\n start += 1\n end = end - 1\n\ndef leftrotate(arr, d, n):\n if d == 0:\n return\n d = d % n\n self.reverseArray(arr, 0, d - 1)\n self.reverseArray(arr, d, n - 1)\n self.reverseArray(arr, 0, n - 1)", "def leftrotate(arr, k, n):\n if k > n:\n k = k % n\n ans = []\n for x in arr[k:]:\n ans.append(x)\n for x in arr[:k]:\n ans.append(x)\n i = 0\n while i < n:\n arr[i] = ans[i]\n i += 1\n return ans", "def leftrotate(arr, k, n):\n i = 0\n j = n - 1\n k = k % n\n while i < j:\n (arr[i], arr[j]) = (arr[j], arr[i])\n i += 1\n j -= 1\n i = 0\n j = n - k - 1\n while i < j:\n (arr[i], arr[j]) = (arr[j], arr[i])\n i += 1\n j -= 1\n i = n - k\n j = n - 1\n while i < j:\n (arr[i], arr[j]) = (arr[j], arr[i])\n i += 1\n j -= 1\n return arr", "def leftrotate(arr, k, n):\n a = []\n if k > n:\n k = k % n\n for i in range(k):\n a.append(arr[i])\n for i in range(k, n):\n arr[i - k] = arr[i]\n z = 0\n for i in range(n - k, n):\n arr[i] = a[z]\n z += 1\n return arr", "def leftrotate(arr, k, n):\n if k % n:\n k = k % n\n helper = arr[:k + 1]\n for i in range(0, n - k):\n arr[i] = arr[i + k]\n for i in range(0, k):\n arr[i + n - k] = helper[i]", "def leftrotate(arr, k, n):\n if k > n:\n k = n - k % n\n b = arr[n - k:n] + arr[0:n - k + 1]\n arr[0:n] = b[0:n]\n return arr\n b = arr[k:n] + arr[0:k]\n arr[0:n] = b[0:n]\n return", "def leftrotate(arr, k, n):\n k = k % n\n for i in range(k):\n arr.append(arr.pop(0))", "def reverse(A, b, e):\n while b < e:\n (A[b], A[e]) = (A[e], A[b])\n b += 1\n e -= 1\n\ndef leftrotate(A, d, N):\n while d > N:\n d = d - N\n self.reverse(A, 0, d - 1)\n self.reverse(A, d, N - 1)\n self.reverse(A, 0, N - 1)", "def reverse(arr, i, j):\n if i > j:\n (i, j) = (j, i)\n section = arr[i:j + 1]\n section.reverse()\n arr[i:j + 1] = section\n\ndef leftrotate(arr, k, n):\n if k > n:\n k = k % n\n arr[:] = arr[::-1]\n self.reverse(arr, 0, n - k - 1)\n self.reverse(arr, n - k, n)", "def leftrotate(arr, k, n):\n if k > n:\n k = k % n\n a = []\n for i in range(k, n):\n a.append(arr[i])\n for i in range(0, k):\n a.append(arr[i])\n for i in range(0, n):\n arr[i] = a[i]", "def leftrotate(arr, k, n):\n l = []\n if n > k:\n r = k\n else:\n r = k % n\n for i in range(r, n):\n l.append(arr[i])\n for i in range(0, r):\n l.append(arr[i])\n for i in range(0, n):\n arr[i] = l[i]", "def leftrotate(arr, k, n):\n k = k % n\n dupli = arr[:k]\n for i in range(k, n):\n arr[i - k] = arr[i]\n for i in range(n - k, n):\n arr[i] = dupli[i - n + k]\n return arr", "def leftrotate(arr, k, n):\n k = k % n\n\n def swap(arr, l, e):\n while l < e:\n (arr[l], arr[e]) = (arr[e], arr[l])\n l += 1\n e -= 1\n swap(arr, 0, k - 1)\n swap(arr, k, n - 1)\n swap(arr, 0, n - 1)", "def leftrotate(arr, k, n):\n k = k % n\n t = arr[k:] + arr[:k]\n for i in range(n):\n arr[i] = t[i]", "def leftrotate(arr, k, n):\n k = k % n\n if k == 0:\n return arr\n count = 0\n for i in range(n):\n src_index = i\n src_elem = arr[i]\n while True:\n dest_index = src_index - k\n if dest_index < 0:\n dest_index += n\n temp = arr[dest_index]\n arr[dest_index] = src_elem\n src_elem = temp\n src_index = dest_index\n count += 1\n if dest_index == i:\n break\n if count == n:\n return arr\n return arr", "def leftrotate(arr, k, n):\n j = 0\n k = k % n\n temp = arr[:k]\n for i in range(k, n):\n arr[j] = arr[i]\n j += 1\n for i in range(len(temp)):\n arr[j] = temp[i]\n j += 1\n return arr", "def leftrotate(arr, k, n):\n k = k % n\n arr[0:k] = reversed(arr[0:k])\n arr[k:n] = reversed(arr[k:n])\n arr[0:n] = reversed(arr[0:n])", "def leftrotate(arr, k, n):\n\n def solve(l, h):\n while l < h:\n (arr[l], arr[h]) = (arr[h], arr[l])\n l += 1\n h -= 1\n k = k % n\n solve(0, n - 1)\n solve(0, n - k - 1)\n solve(n - k, n - 1)", "def leftrotate(arr, k, n):\n k = k % n\n x = arr[k:] + arr[:k]\n for i in range(0, n):\n arr[i] = x[i]\n return arr", "def reverse(arr, i, j):\n while i < j:\n temp = arr[i]\n arr[i] = arr[j]\n arr[j] = temp\n i += 1\n j -= 1\n\ndef leftrotate(arr, k, n):\n k = k % n\n self.reverse(arr, 0, k - 1)\n self.reverse(arr, k, n - 1)\n self.reverse(arr, 0, n - 1)", "def leftrotate(arr, k, n):\n\n def reverse(arr, l, r):\n while l <= r:\n (arr[l], arr[r]) = (arr[r], arr[l])\n l += 1\n r -= 1\n k = k % n\n reverse(arr, 0, k - 1)\n reverse(arr, k, n - 1)\n reverse(arr, 0, n - 1)\n return arr", "def reverse(arr, s, e):\n while s < e:\n (arr[s], arr[e - 1]) = (arr[e - 1], arr[s])\n s += 1\n e -= 1\n\ndef leftrotate(arr, k, n):\n k = k % n\n self.reverse(arr, 0, n)\n self.reverse(arr, 0, n - k)\n self.reverse(arr, n - k, n)", "def leftrotate(arr, k, n):\n if k == len(arr):\n return arr\n if k > len(arr):\n k = k % len(arr)\n arr[0:k] = reversed(arr[0:k])\n arr[k:len(arr)] = reversed(arr[k:len(arr)])\n arr.reverse()\n return arr", "def leftrotate(arr, k, n):\n idx = 0\n if k > n:\n k = k % n\n while k > 0:\n val = arr.pop(idx)\n arr.append(val)\n k -= 1\n return arr", "def leftrotate(arr, k, n):\n if k > n:\n k = k % n\n l_arr = arr[k:]\n r_arr = arr[:k]\n arr[:] = l_arr + r_arr", "def leftrotate(arr, k, n):\n start = k % n\n j = 0\n x = arr[:start]\n for i in range(start, n):\n arr[j] = arr[i]\n j = j + 1\n z = 0\n for i in range(j, n):\n arr[i] = x[z]\n z = z + 1", "def leftrotate(arr, k, n):\n ans = [None] * len(arr)\n for i in range(len(arr)):\n ans[(i - k) % n] = arr[i]\n for i in range(n):\n arr[i] = ans[i]", "def leftrotate(arr, k, n):\n k = k % len(arr)\n arr[:] = arr[k:] + arr[:k]", "def leftrotate(arr, k, n):\n k = k % n\n temp = []\n for i in range(0, k):\n temp.append(arr[i])\n for i in range(k, n):\n arr[i - k] = arr[i]\n for i in range(n - k, n):\n arr[i] = temp[i - (n - k)]\n return arr", "def leftrotate(arr, k, n):\n k = k % n\n tmp = arr[:k]\n for i in range(n - k):\n arr[i] = arr[i + k]\n for i in range(len(tmp)):\n arr[n + i - k] = tmp[i]", "def leftrotate(arr, k, n):\n copyArr = [0] * n\n for i in range(n):\n newI = (i - k) % n\n copyArr[newI] = arr[i]\n for i in range(n):\n arr[i] = copyArr[i]", "def leftrotate(arr, k, n):\n\n def reverse(left, right):\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1\n k %= n\n size = n - 1\n reverse(0, size)\n reverse(0, size - k)\n reverse(n - k, size)\n return arr", "def leftrotate(arr, k, n):\n k = k % n\n if k == 0 or k == n:\n return arr\n self.swap(arr, 0, k - 1)\n self.swap(arr, k, n - 1)\n self.swap(arr, 0, n - 1)\n\ndef swap(arr, l, r):\n while l < r:\n (arr[l], arr[r]) = (arr[r], arr[l])\n l += 1\n r -= 1", "def leftrotate(arr, k, n):\n\n def reverseArray(arr, start, end):\n while start < end:\n temp = arr[start]\n arr[start] = arr[end]\n arr[end] = temp\n start += 1\n end -= 1\n return arr\n k = k % n\n arr = reverseArray(arr, 0, k - 1)\n arr = reverseArray(arr, k, len(arr) - 1)\n arr = reverseArray(arr, 0, len(arr) - 1)\n return arr", "def leftrotate(arr, k, n):\n k = k % n\n m = []\n for i in range(k):\n m.append(arr[i])\n for i in range(k, n):\n arr[i - k] = arr[i]\n for i in range(k):\n arr[n + i - k] = m[i]\n return arr", "def leftrotate(arr, k, n):\n k = k % n\n arr1 = arr[k:n]\n arr2 = arr[0:k]\n arr[0:n - k] = arr1\n arr[n - k:] = arr2\n return arr", "def leftrotate(arr, k, n):\n if n <= 1:\n return arr\n if k < n:\n for _ in range(-n, -(n - k)):\n ele = arr[0]\n ele_shift = arr[1]\n arr.remove(ele)\n arr.append(ele)\n return arr\n else:\n shift = k % n\n for _ in range(-n, -(n - shift)):\n ele = arr[0]\n ele_shift = arr[1]\n arr.remove(ele)\n arr.append(ele)\n return arr", "def gcd(a, b):\n if b == 0:\n return a\n return self.gcd(b, a % b)\n\ndef leftrotate(arr, k, n):\n k %= n\n if k == 0:\n return\n g = self.gcd(n, k)\n for i in range(g):\n t = arr[i]\n j = i\n for _ in range(n // g - 1):\n arr[j] = arr[(j + k) % n]\n j = (j + k) % n\n arr[j] = t", "def leftrotate(arr, k, n):\n rotate = k % n\n first = arr[rotate:]\n second = arr[:rotate]\n result = first + second\n for i in range(n):\n arr[i] = result[i]\n return arr", "def leftrotate(arr, k, n):\n rotate = k % n\n arr[rotate:] = reversed(arr[rotate:])\n arr[:rotate] = reversed(arr[:rotate])\n arr[:] = reversed(arr[:])\n return arr", "def leftrotate(arr, k, n):\n rotate = k % n\n arr[:] = arr[rotate:] + arr[0:rotate]\n return arr", "def leftrotate(arr, k, n):\n n = k % len(arr)\n arr[:n] = reversed(arr[:n])\n arr[n:] = reversed(arr[n:])\n arr[:] = reversed(arr[:])\n return arr", "def leftrotate(arr, k, n):\n dum_arr = [0 for _ in range(n)]\n j = 0\n k = k % n\n for i in range(k, n):\n dum_arr[j] = arr[i]\n j += 1\n for i in range(0, k):\n dum_arr[j] = arr[i]\n j += 1\n for i in range(0, n):\n arr[i] = dum_arr[i]", "def rev(arr, st, end):\n while st < end:\n (arr[st], arr[end]) = (arr[end], arr[st])\n st += 1\n end -= 1\n\ndef leftrotate(arr, k, n):\n k = k % n\n self.rev(arr, 0, k - 1)\n self.rev(arr, k, n - 1)\n self.rev(arr, 0, n - 1)", "def leftrotate(arr, k, n):\n if k == 0 or (k >= n and k % n == 0):\n return\n popped = 0\n index = 0\n rotation_count = k % n\n while rotation_count > 0:\n popped = arr.pop(index)\n arr.append(popped)\n rotation_count = rotation_count - 1", "def leftrotate(arr, k, n):\n k = k % n\n a = arr[:k]\n for i in range(n - k):\n arr[i] = arr[i + k]\n i = 0\n for j in range(n - k, n):\n arr[j] = a[i]\n i = i + 1"], "starter_code": "def leftrotate(arr, k, n):\n", "input_output": {"inputs": ["N = 7, K = 2\narr[] = {1, 2, 3, 4, 5, 6, 7}", "N = 6, K = 12\narr[] = {1, 2, 3, 4, 5, 6}"], "outputs": ["3 4 5 6 7 1 2", "1 2 3 4 5 6"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/quick-left-rotation3806/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "leftrotate", "task_id": "TACO_lite/413", "example": [[[7, 2, [1, 2, 3, 4, 5, 6, 7]], [6, 12, [1, 2, 3, 4, 5, 6]]], [null, null]]} +{"requirement": "Given an array of numbers of size N. It is also given that the array elements are in range from 0 to N^{2} \u2013 1. Sort the given array in linear time.\nExample 1:\nInput:\nN = 7\narr[] = {40, 12, 45, 32, 33, 1, 22}\nOutput: 1 12 22 32 33 40 45\nExplanation: Output is the sorted version of the\ngiven array.\n\u00c3\u00a2\u00e2\u0082\u00ac\u00e2\u0080\u00b9Example 2:\nInput: \nN = 5\narr[] = {24, 12, 0, 15, 8}\nOutput: 0 8 12 15 24\nExplanation: Output is the sorted version of the\ngiven array.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function sort () which takes an array arr[] and its size N as inputs and sorts the array in non-decreasing order. \nNote: You have to modify the input array such that it becomes sorted in non-decreasing order.\nExpected Time Complexity: O(N). \nExpected Auxiliary Space: O(N).\nConstraints:\n1 <= N <= 10^4", "solutions": ["def sort(arr, n):\n arr.sort()", "def countSort(arr, n, e):\n ans = [0] * n\n count = [0] * n\n for a in arr:\n count[a // e % n] += 1\n for i in range(1, n):\n count[i] += count[i - 1]\n for i in range(n - 1, -1, -1):\n ans[count[arr[i] // e % n] - 1] = arr[i]\n count[arr[i] // e % n] -= 1\n for i in range(n):\n arr[i] = ans[i]\n\ndef sort(arr, n):\n self.countSort(arr, n, 1)\n self.countSort(arr, n, n)", "def sort(arr, n):\n c = arr.sort()\n return c", "def sort(arr, n):\n s = arr.sort()\n return s", "def radix(arr, n, p):\n ans = [0] * n\n cnt = [0] * n\n for i in range(n):\n dx = arr[i] // n ** p % n\n cnt[dx] += 1\n for i in range(1, n):\n cnt[i] += cnt[i - 1]\n for i in range(n - 1, -1, -1):\n dx = arr[i] // n ** p % n\n ans[cnt[dx] - 1] = arr[i]\n cnt[dx] -= 1\n for i in range(n):\n arr[i] = ans[i]\n\ndef sort(arr, n):\n index = len(str(max(arr)))\n for p in range(2):\n self.radix(arr, n, p)", "def sort(arr, n):\n maxm = max(arr)\n exp = 1\n while maxm // exp > 0:\n output = [0] * n\n count = [0] * 10\n for i in range(n):\n idx = arr[i] // exp\n count[idx % 10] += 1\n for i in range(1, 10):\n count[i] += count[i - 1]\n for i in range(n - 1, -1, -1):\n idx = arr[i] // exp\n output[count[idx % 10] - 1] = arr[i]\n count[idx % 10] -= 1\n for i in range(n):\n arr[i] = output[i]\n exp *= 10\n return arr", "def sort(T, n):\n counts = [0 for _ in range(n)]\n output = [0 for _ in range(n)]\n for i in range(n):\n counts[T[i] % n] += 1\n for i in range(1, n):\n counts[i] += counts[i - 1]\n for i in range(n - 1, -1, -1):\n counts[T[i] % n] -= 1\n output[counts[T[i] % n]] = T[i]\n for i in range(n):\n T[i] = output[i]\n counts = [0 for _ in range(n)]\n output = [0 for _ in range(n)]\n for i in range(n):\n counts[T[i] // n] += 1\n for i in range(1, n):\n counts[i] += counts[i - 1]\n for i in range(n - 1, -1, -1):\n counts[T[i] // n] -= 1\n output[counts[T[i] // n]] = T[i]\n for i in range(n):\n T[i] = output[i]", "def sort(arr, n):\n arr1 = arr[:]\n ma = max(arr1)\n k = 0\n while ma != 0:\n k += 1\n ma = ma // 10\n li = [[] for i in range(10)]\n k1 = 1\n while k1 <= k:\n for i in arr1:\n li[i % pow(10, k1) // max(1, pow(10, k1 - 1))].append(i)\n arr1 = []\n for i in li:\n arr1.extend(i)\n li = [[] for i in range(10)]\n k1 += 1\n for i in range(n):\n arr[i] = arr1[i]", "def sort(arr, n):\n aux = [0] * n\n count = [0] * n\n for i in range(n):\n count[arr[i] % n] += 1\n for i in range(1, n):\n count[i] += count[i - 1]\n for i in range(n - 1, -1, -1):\n aux[count[arr[i] % n] - 1] = arr[i]\n count[arr[i] % n] -= 1\n for i in range(n):\n arr[i] = aux[i]\n count[i] = 0\n for i in range(n):\n count[arr[i] // n % n] += 1\n for i in range(1, n):\n count[i] += count[i - 1]\n for i in range(n - 1, -1, -1):\n aux[count[arr[i] // n % n] - 1] = arr[i]\n count[arr[i] // n % n] -= 1\n for i in range(n):\n arr[i] = aux[i]", "def radixsort(arr, n, exp):\n output = [0] * n\n count = [0] * n\n for i in range(n):\n count[arr[i] // exp % n] += 1\n for i in range(1, n):\n count[i] += count[i - 1]\n for i in range(n - 1, -1, -1):\n output[count[arr[i] // exp % n] - 1] = arr[i]\n count[arr[i] // exp % n] -= 1\n for i in range(n):\n arr[i] = output[i]\n\ndef sort(arr, n):\n self.radixsort(arr, n, 1)\n self.radixsort(arr, n, n)\n return arr", "def sort(arr, n):\n\n def countSort(arr, exp):\n newArr = [[] for i in range(10)]\n for i in range(len(arr)):\n newArr[arr[i] // exp % 10].append(arr[i])\n j = 0\n for i in newArr:\n for k in i:\n arr[j] = k\n j += 1\n return arr\n maxLen = len(str(n ** 2))\n for i in range(maxLen):\n exp = 10 ** i\n countSort(arr, exp)\n return arr", "def sort(arr, n):\n B = n\n for j in range(2):\n freq = [0] * n\n for i in range(n):\n num_digit = arr[i] // B ** j % B\n freq[num_digit] += 1\n k = 1\n while k < B:\n freq[k] += freq[k - 1]\n k += 1\n arr_copy = arr.copy()\n for i in range(n - 1, -1, -1):\n num_digit = arr_copy[i] // B ** j % B\n arr[freq[num_digit] - 1] = arr_copy[i]\n freq[num_digit] -= 1\n return arr", "def counting(n, arr, div):\n count = [0] * n\n output = [0] * n\n for i in arr:\n count[i // div % n] += 1\n for j in range(1, n):\n count[j] += count[j - 1]\n for k in range(n - 1, -1, -1):\n output[count[arr[k] // div % n] - 1] = arr[k]\n count[arr[k] // div % n] -= 1\n for i in range(n):\n arr[i] = output[i]\n\ndef sort(arr, n):\n self.counting(n, arr, 1)\n self.counting(n, arr, n)", "def sort(arr, n):\n if len(arr) > 1:\n m = len(arr) // 2\n l = arr[:m]\n r = arr[m:]\n self.sort(l, len(l))\n self.sort(r, len(r))\n i = j = k = 0\n while i < len(l) and j < len(r):\n if l[i] < r[j]:\n arr[k] = l[i]\n i = i + 1\n else:\n arr[k] = r[j]\n j = j + 1\n k = k + 1\n while i < len(l):\n arr[k] = l[i]\n i = i + 1\n k = k + 1\n while j < len(r):\n arr[k] = r[j]\n j = j + 1\n k = k + 1", "import numpy as np\n\ndef count_sort(arr, n, exp):\n idxs = np.zeros((n,), dtype=int)\n output_arr = np.zeros((n,), dtype=int)\n for i in range(len(arr)):\n idxs[int(arr[i] // exp % n)] += 1\n i = 1\n while i < n:\n idxs[i] += idxs[i - 1]\n i += 1\n i = n - 1\n while i >= 0:\n output_arr[idxs[int(arr[i] / exp % n)] - 1] = arr[i]\n idxs[int(arr[i] / exp % n)] -= 1\n i -= 1\n for i in range(n):\n arr[i] = output_arr[i]\n\ndef sort(arr, n):\n self.count_sort(arr, n, 1)\n self.count_sort(arr, n, n)", "from queue import PriorityQueue\n\ndef sort(arr, n):\n q = PriorityQueue(n)\n for i in range(n):\n q.put(arr[i])\n i = 0\n while q.empty() == False:\n arr[i] = q.get()\n i += 1\n return arr", "def sort(arr, n):\n arr.sort()\n return\n f = [0 for i in range(n * n)]\n for i in range(n):\n f[arr[i]] += 1\n k = 0\n for i in range(n * n):\n if f[i] != 0:\n for j in range(f[i]):\n arr[k] = i\n k += 1\n return arr", "def countSort(arr, j):\n n = len(arr)\n B = [0] * n\n C = [0] * n\n for i in range(n):\n C[arr[i][j]] += 1\n for i in range(1, n):\n C[i] += C[i - 1]\n for i in range(n - 1, -1, -1):\n C[arr[i][j]] -= 1\n B[C[arr[i][j]]] = arr[i]\n for i in range(n):\n arr[i] = B[i]\n\ndef preprocessing(arr):\n n = len(arr)\n for i in range(n):\n a = arr[i] // n\n b = arr[i] % n\n arr[i] = (a, b)\n return arr\n\ndef sort(arr, n):\n arr = self.preprocessing(arr)\n self.countSort(arr, 1)\n self.countSort(arr, 0)\n for i in range(n):\n arr[i] = arr[i][0] * n + arr[i][1]\n return arr", "def sort(arr1, n):\n global arr\n arr = sorted(arr1)", "def sort(arr, n):\n if n <= 1:\n return arr\n bucket = [[] for _ in range(n // 2)]\n mx = n * n\n for i in range(n):\n bi = n // 2 * arr[i] // mx\n bucket[bi].append(arr[i])\n for i in range(n // 2):\n bucket[i].sort()\n index = 0\n for i in bucket:\n for j in i:\n arr[index] = j\n index += 1", "def sort(arr, n):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n while j >= 0 and key < arr[j]:\n arr[j + 1] = arr[j]\n j -= 1\n arr[j + 1] = key", "def sort(arr, n):\n base = n\n max_elem = n ** 2 - 1\n freq = [0] * base\n ans = [0] * n\n digits = 0\n count = 0\n while max_elem > 0:\n count += 1\n max_elem /= base\n exponent = 0\n while exponent < count:\n for i in range(0, n):\n freq[arr[i] // base ** exponent % base] += 1\n for i in range(1, base):\n freq[i] += freq[i - 1]\n for i in range(N - 1, -1, -1):\n ans[freq[arr[i] // base ** exponent % base] - 1] = arr[i]\n freq[arr[i] // base ** exponent % base] -= 1\n for i in range(0, n):\n arr[i] = ans[i]\n for i in range(0, base):\n freq[i] = 0\n exponent += 1\n return arr", "def RadixSort(arr, n, digit, count, Aux):\n for i in range(n):\n count[arr[i] // digit % n] += 1\n for i in range(1, n):\n count[i] += count[i - 1]\n for i in range(n - 1, -1, -1):\n Aux[count[arr[i] // digit % n] - 1] = arr[i]\n count[arr[i] // digit % n] -= 1\n for i in range(n):\n arr[i] = Aux[i]\n count[i] = 0\n return\n\ndef sort(arr, n):\n count = [0] * n\n Aux = [0] * n\n self.RadixSort(arr, n, 1, count, Aux)\n self.RadixSort(arr, n, n, count, Aux)\n return", "def sort(arr, n):\n self.quicksort(arr, 0, n - 1)\n return arr\n\ndef quicksort(arr, l, r):\n if l >= r:\n return\n p = self.partition(arr, l, r)\n self.quicksort(arr, l, p - 1)\n self.quicksort(arr, p + 1, r)\n\ndef partition(arr, l, r):\n p = arr[r]\n j = l\n for i in range(l, r + 1):\n if arr[i] <= p:\n (arr[i], arr[j]) = (arr[j], arr[i])\n j += 1\n return j - 1", "def sort(arr, n):\n z = sorted(arr)\n arr.clear()\n arr += z", "def no_of_digit(n):\n s = n\n count = 0\n while s > 0:\n s = s // 10\n count += 1\n return count\n\ndef nth_digit(no, n):\n num = no\n rem = 0\n for i in range(0, n):\n if num == 0:\n return 0\n rem = num % 10\n num = num // 10\n return rem\n\ndef countingSort(a, n, d):\n ans = a.copy()\n f = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n for i in range(n):\n f[self.nth_digit(ans[i], d)] += 1\n for i in range(1, 10):\n f[i] += f[i - 1]\n for i in range(n - 1, -1, -1):\n f[self.nth_digit(ans[i], d)] -= 1\n a[f[self.nth_digit(ans[i], d)]] = ans[i]\n\ndef sort(a, n):\n no = self.no_of_digit(n ** 2 - 1)\n ans = a\n for i in range(1, no + 1):\n self.countingSort(ans, n, i)", "def sort(arr, n):\n for i in range(n):\n t = i\n for j in range(t, n):\n if arr[t] >= arr[j]:\n t = j\n (arr[i], arr[t]) = (arr[t], arr[i])\n return arr"], "starter_code": "def sort(arr, n):\n", "input_output": {"inputs": ["N = 7\narr[] = {40, 12, 45, 32, 33, 1, 22}", "N = 5\narr[] = {24, 12, 0, 15, 8}"], "outputs": ["1 12 22 32 33 40 45", "0 8 12 15 24"]}, "difficulty": "MEDIUM", "raw_tags": ["Sqrt Decomposition", "Algorithms", "Sorting"], "name": null, "source": "geeksforgeeks", "tags": ["Sorting", "Square root algorithms"], "skill_types": ["Sorting"], "url": "https://practice.geeksforgeeks.org/problems/efficiently-sorting-number-from-0-to-n2-15444/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "sort", "task_id": "TACO_lite/428", "example": [[], []]} +{"requirement": "We are given a sequence of coplanar points and see all the possible triangles that may be generated which all combinations of three points.\n\nWe have the following list of points with the cartesian coordinates of each one:\n```\nPoints [x, y]\n A [1, 2]\n B [3, 3]\n C [4, 1]\n D [1, 1]\n E [4, -1]\n```\nWith these points we may have the following triangles: ```ABC, ABD, ABE, ACD, ACE, ADE, BCD, BCE, BDE, CDE.``` There are three special ones: ```ABC, ACD and CDE```, that have an angle of 90\u00b0. All is shown in the picture below:\n\n\n\nWe need to count all the rectangle triangles that may be formed by a given list of points.\n\nThe case decribed above will be:\n```python\ncount_rect_triang([[1, 2],[3, 3],[4, 1],[1, 1],[4, -1]]) == 3\n```\n\nObserve this case:\n```python\ncount_rect_triang([[1, 2],[4, -1],[3, 3],[4, -1],[4, 1],[1, 1],[4, -1], [4, -1], [3, 3], [1, 2]]) == 3\n```\nIf no rectangle triangles may be generated the function will output ```0```.\n\nEnjoy it!", "solutions": ["from itertools import combinations\n\ndef isRect(a, b, c):\n (X, Y, Z) = sorted((sum(((q - p) ** 2 for (p, q) in zip(p1, p2))) for (p1, p2) in [(a, b), (a, c), (b, c)]))\n return X + Y == Z\n\ndef count_rect_triang(points):\n return sum((isRect(*c) for c in combinations(set(map(tuple, points)), 3)))", "from itertools import combinations\n\ndef count_rect_triang(points):\n result = 0\n for ((x1, y1), (x2, y2), (x3, y3)) in combinations(set(map(tuple, points)), 3):\n d1 = (x1 - x2) ** 2 + (y1 - y2) ** 2\n d2 = (x2 - x3) ** 2 + (y2 - y3) ** 2\n d3 = (x3 - x1) ** 2 + (y3 - y1) ** 2\n (d1, d2, d3) = sorted((d1, d2, d3))\n result += d1 + d2 == d3\n return result", "from itertools import combinations\n\ndef ok(a, b, c):\n ((x1, y1), (x2, y2), (x3, y3)) = (a, b, c)\n (d1, d2, d3) = ((x1 - x2) ** 2 + (y1 - y2) ** 2, (x1 - x3) ** 2 + (y1 - y3) ** 2, (x2 - x3) ** 2 + (y2 - y3) ** 2)\n (d1, d2, d3) = sorted([d1, d2, d3])\n return d1 + d2 == d3\n\ndef count_rect_triang(points):\n return sum((ok(pa, pb, pc) for (pa, pb, pc) in combinations(set(map(tuple, points)), 3)))", "f = lambda t, r=2: [sorted, iter][r - 2]((abs(sum(p) - 2 * p[-1]) ** 2 for p in map([list, f][r - 2], __import__('itertools').combinations(t, r))))\ncount_rect_triang = lambda p: sum((d < 1e-09 for d in f({x + 1j * y for (x, y) in p}, 3)))", "from itertools import combinations\n\ndef count_rect_triang(points):\n return sum((1 for ps in combinations(set(map(tuple, points)), 3) for (p0, p1, p2) in ((ps[0], ps[1], ps[2]), (ps[1], ps[2], ps[0]), (ps[2], ps[1], ps[0])) if (p1[0] - p0[0]) * (p2[0] - p0[0]) + (p1[1] - p0[1]) * (p2[1] - p0[1]) == 0))", "from itertools import product\n\ndef count_rect_triang(points):\n return sum((1 for (p0, p1, p2) in product(set(map(tuple, points)), repeat=3) if p0 != p1 != p2 != p0 and (p1[0] - p0[0]) * (p2[0] - p0[0]) + (p1[1] - p0[1]) * (p2[1] - p0[1]) == 0)) // 2", "def dist(ps):\n (p1, p2, p3) = ps\n x = (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2\n y = (p1[0] - p3[0]) ** 2 + (p1[1] - p3[1]) ** 2\n z = (p2[0] - p3[0]) ** 2 + (p2[1] - p3[1]) ** 2\n return sorted([x, y, z])\nfrom itertools import combinations\n\ndef count_rect_triang(points):\n if len(points) < 3:\n return 0\n ps = []\n for i in points:\n if i not in ps:\n ps.append(i)\n c = 0\n for i in combinations(ps, 3):\n temp = dist(i)\n if round(temp[-1], 4) == round(temp[0] + temp[1], 4):\n c += 1\n return c", "from itertools import combinations\n\ndef count_rect_triang(points):\n n = 0\n points_set = set()\n for p in points:\n points_set.add(tuple(p))\n for ((x1, y1), (x2, y2), (x3, y3)) in combinations(points_set, 3):\n (l1, l2, l3) = sorted([(x2 - x1) ** 2 + (y2 - y1) ** 2, (x3 - x2) ** 2 + (y3 - y2) ** 2, (x1 - x3) ** 2 + (y1 - y3) ** 2])\n if l1 + l2 == l3:\n n += 1\n return n", "from itertools import combinations\n\ndef count_rect_triang(points):\n ans = 0\n for c in combinations(set(map(tuple, points)), 3):\n dist = [(p[0][0] - p[1][0]) ** 2 + (p[0][1] - p[1][1]) ** 2 for p in combinations(c, 2)]\n ans += sum(dist) == max(dist) * 2\n return ans"], "starter_code": "def count_rect_triang(points):\n", "input_output": {"fn_name": "count_rect_triang", "inputs": [[[[1, 2], [3, 3], [4, 1], [1, 1], [4, -1]]], [[[1, 2], [4, -1], [3, 3], [4, -1], [4, 1], [1, 1], [4, -1], [4, -1], [3, 3], [1, 2]]]], "outputs": [[3], [3]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Geometry", "Fundamentals", "Logic"], "name": null, "source": "codewars", "tags": ["Geometry", "Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/57d99f6bbfcdc5b3b0000286", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "count_rect_triang", "task_id": "TACO_lite/420", "example": [[[[[1, 2], [3, 3], [4, 1], [1, 1], [4, -1]]], [[[1, 2], [4, -1], [3, 3], [4, -1], [4, 1], [1, 1], [4, -1], [4, -1], [3, 3], [1, 2]]]], ["3", "3"]]} +{"requirement": "Given a BST and a value k, the task is to delete the nodes having values greater than or equal to k.\nExample 1:\nInput:\n 4 \n / \\ \n 1 9 \nk = 2 \nOutput:\n1\nYour Task:\nThe task is to complete the function deleteNode() which takes root, k as the argument, and returns the root of tree after deleting values greater than or equal to k. The driver code will print the inorder traversal of the updated tree in output itself. \nExpected Time Complexity: O(Size of tree)\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= T <= 100\n1 <= N <= 10^{3}\n1 <= A[] <= 10^{3}\n1 <= k <= N", "solutions": ["def deleteNode(root, k):\n return self.helper(root, k) or root\n\ndef deleteNodeHelper(root):\n if root is None:\n return\n if root.left is None and root.right is None:\n del root\n return\n self.deleteNodeHelper(root.left)\n self.deleteNodeHelper(root.right)\n\ndef helper(root, k):\n if root is None:\n return None\n if root.data >= k:\n newRoot = root.left\n self.deleteNodeHelper(root.right)\n del root\n return self.helper(newRoot, k)\n else:\n rightChild = self.helper(root.right, k)\n root.right = rightChild\n return root", "def deleteNode(root, k):\n if root == None:\n return\n if root.data >= k:\n return self.deleteNode(root.left, k)\n if root.data < k:\n root.right = self.deleteNode(root.right, k)\n return root", "def Delete(root, k):\n if root == None:\n return None\n l = self.Delete(root.left, k)\n r = self.Delete(root.right, k)\n if root.data < k:\n root.left = l\n root.right = r\n return root\n else:\n return l\n\ndef deleteNode(root, k):\n root = self.Delete(root, k)\n return root", "def root_lefts(root):\n while root.right:\n root = root.right\n return root\n\ndef util(root, x):\n if not root:\n return root\n if root.data == x:\n return root.left\n if root.data > x:\n return self.util(root.left, x)\n if root.data < x:\n root.right = self.util(root.right, x)\n return root\n\ndef deleteNode(root, k):\n return self.util(root, k)", "def deleteNode(root, k):\n while root and root.data >= k:\n root = root.left\n start = root\n while root:\n while root.right and root.right.data >= k:\n root.right = root.right.left\n root = root.right\n return start", "def deleteNode(root, k):\n nod = Node(0)\n\n def fun2(root):\n if root == None:\n return\n if root.data >= k:\n return fun2(root.left)\n root.right = fun2(root.right)\n return root\n return fun2(root)", "def deleteNode(root, k):\n\n def f(root, k):\n if not root:\n return None\n if root.data < k:\n root.right = f(root.right, k)\n else:\n root = f(root.left, k)\n return root\n return f(root, k)", "def __init__():\n self.inorder = []\n\ndef InOrder(Node):\n if Node == None:\n return\n self.InOrder(Node.left)\n self.inorder.append(Node.data)\n self.InOrder(Node.right)\n return\n\ndef MakeTree(inorder):\n if inorder == []:\n return None\n mid = len(inorder) // 2\n root = Node(inorder[mid])\n root.left = self.MakeTree(inorder[:mid])\n root.right = self.MakeTree(inorder[mid + 1:])\n return root\n\ndef deleteNode(root, k):\n self.InOrder(root)\n for i in range(0, len(self.inorder)):\n if self.inorder[i] < k:\n continue\n else:\n self.inorder = self.inorder[:i]\n break\n return self.MakeTree(self.inorder)", "def solve(root, k):\n if root == None:\n return None\n elif root.data >= k:\n l = self.solve(root.left, k)\n return l\n else:\n root.right = self.solve(root.right, k)\n return root\n\ndef deleteNode(root, k):\n res = self.solve(root, k)\n return res", "def deleteNode(root, k):\n head = None\n head = self.delete(root, k, head)\n return head\n\ndef delete(root, k, head):\n if not root:\n return\n if root.data < k:\n head = root\n head.left = self.delete(root.left, k, head.left)\n head.right = self.delete(root.right, k, head.right)\n else:\n head = self.delete(root.left, k, head)\n return head", "def deep(root):\n cur = root\n while cur.left != None:\n cur = cur.left\n return cur\n\ndef delete(root, key):\n if root is None:\n return None\n if root.data > key:\n root.left = delete(root.left, key)\n elif root.data < key:\n root.right = delete(root.right, key)\n else:\n if root.left is None:\n temp = root.right\n root = None\n return temp\n if root.right is None:\n temp = root.left\n root = None\n return temp\n temp = deep(root.right)\n root.data = temp.data\n root.right = delete(root.right, temp.data)\n return root\n\ndef inorder(root):\n res = []\n q = []\n cur = root\n while True:\n if cur is not None:\n q.append(cur)\n cur = cur.left\n elif q:\n cur = q.pop()\n res.append(cur.data)\n cur = cur.right\n else:\n break\n return res\n\ndef deleteNode(root, k):\n ino = self.inorder(root)\n for i in ino:\n if i >= k:\n root = delete(root, i)\n return root", "def delete(root):\n if not root.left and (not root.right):\n root = None\n elif not root.left:\n root = root.right\n elif not root.right:\n root = root.left\n else:\n temp = minn(root.left)\n root.data = temp.data\n temp = delete(temp)\n return root\n\ndef minn(root):\n while root.right:\n root = root.right\n return root\n\ndef deleteNode(root, k):\n if not root:\n return\n root.left = self.deleteNode(root.left, k)\n root.right = self.deleteNode(root.right, k)\n if root.data >= k:\n root = delete(root)\n return root", "def getNodeAndParent(root, key):\n parent = None\n tmp = root\n while tmp:\n if tmp.data == key:\n return [tmp, parent]\n parent = tmp\n if tmp.data > key:\n tmp = tmp.left\n else:\n tmp = tmp.right\n return [None, None]\n\ndef isLeaf(node):\n return not node.left and (not node.right)\n\ndef deleteLeaf(node, parent):\n if parent.left == node:\n parent.left = None\n else:\n parent.right = None\n return node\n\ndef isSingleChildNode(node):\n return not node.left and node.right or (node.left and (not node.right))\n\ndef deleteSingleChildNode(node, parent):\n if node.left:\n if parent.left == node:\n parent.left = node.left\n else:\n parent.right = node.left\n node.left = None\n else:\n if parent.left == node:\n parent.left = node.right\n else:\n parent.right = node.right\n node.right = None\n return node\n\ndef deleteDoubleChildNode(node, parent):\n re_parent = node\n re_node = node.left\n while re_node.right:\n re_parent = re_node\n re_node = re_node.right\n if self.isLeaf(re_node):\n removed_node = self.deleteLeaf(re_node, re_parent)\n else:\n removed_node = self.deleteSingleChildNode(re_node, re_parent)\n if parent:\n if parent.left == node:\n parent.left = removed_node\n else:\n parent.right = removed_node\n removed_node.left = node.left\n removed_node.right = node.right\n return node\n\ndef deleteRoot(root):\n if self.isLeaf(root):\n new_root = None\n elif self.isSingleChildNode(root):\n if root.left:\n new_root = root.left\n else:\n new_root = root.right\n else:\n new_root = root.left\n while new_root.right:\n new_root = new_root.right\n root = self.deleteDoubleChildNode(root, None)\n del root\n return new_root\n\ndef deleteNodeBST(root, key: int):\n (node, parent) = self.getNodeAndParent(root, key)\n if not node:\n return root\n if not parent:\n root = self.deleteRoot(root)\n else:\n if self.isLeaf(node):\n removed_node = self.deleteLeaf(node, parent)\n elif self.isSingleChildNode(node):\n removed_node = self.deleteSingleChildNode(node, parent)\n else:\n removed_node = self.deleteDoubleChildNode(node, parent)\n del removed_node\n return root\n\ndef __init__() -> None:\n self.values = []\n\ndef getVals(root, k):\n if not root:\n return\n if root.data >= k:\n self.values.append(root.data)\n self.getVals(root.left, k)\n self.getVals(root.right, k)\n\ndef deleteNode(root, k):\n delete_node = Delete()\n self.getVals(root, k)\n for key in self.values:\n root = delete_node.deleteNodeBST(root, key)\n return root", "def deleteNode(root, k):\n if root == None:\n return root\n if root.data == k:\n return root.left\n elif root.data > k:\n temp = root.left\n return self.deleteNode(temp, k)\n else:\n root.right = self.deleteNode(root.right, k)\n return root", "def deleteNode(node, k):\n if node is None:\n return node\n node.left = self.deleteNode(node.left, k)\n node.right = self.deleteNode(node.right, k)\n if node.data >= k:\n return node.left\n return node", "def deleteNode(root, k):\n if root == None:\n return\n if root.data >= k:\n return self.deleteNode(root.left, k)\n root.left = self.deleteNode(root.left, k)\n root.right = self.deleteNode(root.right, k)\n return root\n\ndef delete(root):\n if root == None:\n return\n if root.left:\n root.data = root.left.data\n root.left = self.delete(root.left)\n elif root.right:\n root.data = root.right.data\n root.right = self.delete(root.right)\n else:\n del root\n return", "import sys\nsys.setrecursionlimit(10 ** 6)\n\ndef ino(r, l, k):\n if r is not None:\n self.ino(r.left, l, k)\n if r.data < k:\n l.append(Node(r.data))\n self.ino(r.right, l, k)\n\ndef deleteNode(root, k):\n l = []\n self.ino(root, l, k)\n n = len(l)\n for i in range(n - 1):\n l[i].right = l[i + 1]\n return l[0]", "node = None\n\ndef solve(root, k):\n if root is None:\n return None\n global head, itr\n if k <= root.data:\n if itr:\n itr.right = root.left\n self.solve(root.left, k)\n else:\n if head is None:\n head = root\n itr = head\n else:\n itr.right = root\n itr = root\n self.solve(root.right, k)\n\ndef deleteNode(root, k):\n global head, itr\n head = itr = None\n self.solve(root, k)\n return head", "def deleteNode(root, k):\n if not root:\n return root\n if root.data < k:\n root.right = self.deleteNode(root.right, k)\n return root\n elif root.data > k:\n return self.deleteNode(root.left, k)\n else:\n return root.left", "def deleteS(root, k):\n if root is None:\n return root\n if root.data > k:\n root.left = deleteS(root.left, k)\n elif root.data < k:\n root.right = deleteS(root.right, k)\n else:\n if root.left is None:\n temp = root.right\n root = None\n return temp\n if root.right is None:\n temp = root.left\n root = None\n return temp\n temp = minValueNode(root.right)\n root.data = temp.data\n root.right = deleteS(root.right, temp.data)\n return root\n\ndef minValueNode(node):\n current = node\n while current.left is not None:\n current = current.left\n return current\n\ndef inorder(root, a):\n if root is not None:\n inorder(root.left, a)\n a.append(root.data)\n inorder(root.right, a)\n return a\n\ndef deleteNode(root, k):\n a = []\n arr = inorder(root, a)\n for i in arr:\n if i >= k:\n w = deleteS(root, i)\n else:\n w = root\n return w", "def __init__(val):\n self.right = None\n self.data = val\n self.left = None\n\ndef deleteNode(root, k):\n if root is None:\n return\n root.left = self.deleteNode(root.left, k)\n root.right = self.deleteNode(root.right, k)\n if root.data >= k:\n temp = root.left\n root = None\n return temp\n return root", "def __init__():\n self.root = None\n\ndef deleteNode(root, k):\n self.root = root\n return self.__delete_k_greater(root, key=k)\n\ndef __delete_k_greater(node, key):\n if node and node.data >= key:\n if node == self.root:\n node = self.root = self.root.left\n else:\n node = node.left\n if node:\n return self.__delete_k_greater(node, key)\n elif node and node.data < key and node.right:\n node.right = self.__delete_k_greater(node.right, key)\n return node\n else:\n return node", "def deleteNode(root, k):\n newRoot = self.searchForNewRoot(root, k)\n if newRoot == None:\n return None\n self.trimTree(newRoot, k)\n return newRoot\n\ndef searchForNewRoot(root, k):\n curr = root\n while curr.data >= k:\n if curr.left == None:\n return None\n curr = curr.left\n return curr\n\ndef trimTree(root, k):\n curr = root\n parent = None\n while curr != None:\n if curr.data >= k:\n parent.right = curr.left\n curr = curr.left\n else:\n parent = curr\n curr = curr.right", "def deleteNode(root, k):\n while root.data >= k:\n if root.left == None and root.right == None:\n return\n root = root.left\n temp = root\n prev = None\n while temp != None:\n if temp.data < k:\n prev = temp\n temp = temp.right\n else:\n prev.right = temp.left\n temp = temp.left\n return root"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["4 \r\n / \\ \r\n 1 9 \r\nk = 2"], "outputs": ["1"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Binary Search Tree", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures", "Range queries"], "skill_types": ["Data structures", "Range queries"], "url": "https://practice.geeksforgeeks.org/problems/delete-nodes-greater-than-k/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(Size of tree)", "entry_point": "__init__", "task_id": "TACO_lite/447", "example": [[[4, 1, 9, 2]], ["1"]]} +{"requirement": "Introduction \n\nThe GADERYPOLUKI is a simple substitution cypher used in scouting to encrypt messages. The encryption is based on short, easy to remember key. The key is written as paired letters, which are in the cipher simple replacement.\n\nThe most frequently used key is \"GA-DE-RY-PO-LU-KI\".\n\n```\n G => A\n g => a\n a => g\n A => G\n D => E\n etc.\n```\n\nThe letters, which are not on the list of substitutes, stays in the encrypted text without changes.\n\nTask\n\nYour task is to help scouts to encrypt and decrypt thier messages.\nWrite the `Encode` and `Decode` functions.\n\nInput/Output\n\nThe input string consists of lowercase and uperrcase characters and white .\nThe substitution has to be case-sensitive. \n\nExample\n\n# GADERYPOLUKI collection\n\n\n\nGADERYPOLUKI cypher vol 1\n\n\nGADERYPOLUKI cypher vol 2\n\n\nGADERYPOLUKI cypher vol 3 - Missing Key\n\n\nGADERYPOLUKI cypher vol 4 - Missing key madness", "solutions": ["dict = {i[0]: i[1] for i in ['GA', 'DE', 'RY', 'PO', 'LU', 'KI', 'AG', 'ED', 'YR', 'OP', 'UL', 'IK', 'ga', 'de', 'ry', 'po', 'lu', 'ki', 'ag', 'ed', 'yr', 'op', 'ul', 'ik']}\n\ndef encode(s):\n return ''.join([dict[i] if i in dict else i for i in s])\n\ndef decode(s):\n return ''.join([dict[i] if i in dict else i for i in s])", "encode = decode = lambda str: str.translate(str.maketrans('gaderypolukiGADERYPOLUKI', 'agedyropulikAGEDYROPULIK'))", "def encode(str):\n return str.translate(str.maketrans('GDRPLKAEYOUI' + 'GDRPLKAEYOUI'.lower(), 'AEYOUIGDRPLK' + 'AEYOUIGDRPLK'.lower()))\n\ndef decode(str):\n return encode(str)", "def encode(message):\n s1 = 'GADERYPOLUKI'\n s2 = 'AGEDYROPULIK'\n return message.translate(str.maketrans(s1, s2)).translate(str.maketrans(s1.lower(), s2.lower()))\n\ndef decode(message):\n return encode(message)", "key = 'GA DE RY PO LU KI'\nkey += ' ' + key.lower()\ndict = {}\nfor (a, b) in key.split():\n dict[a] = b\n dict[b] = a\nencode = decode = lambda str: ''.join((dict.get(char, char) for char in str))", "t = str.maketrans('gdrplkGDRPLKaeyouiAEYOUI', 'aeyouiAEYOUIgdrplkGDRPLK')\nencode = decode = lambda s: s.translate(t)", "def encode(message):\n return message.translate(message.maketrans('GAgaDEdeRYryPOpoLUluKIki', 'AGagEDedYRyrOPopULulIKik'))\n\ndef decode(message):\n return message.translate(message.maketrans('GAgaDEdeRYryPOpoLUluKIki', 'AGagEDedYRyrOPopULulIKik'))", "key = 'GADERYPOLUKI'\nkey += key.lower()\ndekey = ''.join((key[i:i + 2][::-1] for i in range(0, len(key), 2)))\n\ndef encode(message):\n return message.translate(str.maketrans(key, dekey))\n\ndef decode(message):\n return message.translate(str.maketrans(dekey, key))", "key = 'GADERYPOLUKI'\n\ndef table(key):\n full_key = key.upper() + key.lower()\n (even, odd) = (full_key[::2], full_key[1::2])\n return str.maketrans(even + odd, odd + even)\nencode = decode = lambda message: message.translate(table(key))", "def encode(s):\n return ''.join(({'G': 'A', 'A': 'G', 'g': 'a', 'a': 'g', 'D': 'E', 'E': 'D', 'd': 'e', 'e': 'd', 'R': 'Y', 'Y': 'R', 'r': 'y', 'y': 'r', 'P': 'O', 'O': 'P', 'p': 'o', 'o': 'p', 'L': 'U', 'U': 'L', 'l': 'u', 'u': 'l', 'K': 'I', 'I': 'K', 'k': 'i', 'i': 'k'}[c] if c in {'G': 'A', 'A': 'G', 'g': 'a', 'a': 'g', 'D': 'E', 'E': 'D', 'd': 'e', 'e': 'd', 'R': 'Y', 'Y': 'R', 'r': 'y', 'y': 'r', 'P': 'O', 'O': 'P', 'p': 'o', 'o': 'p', 'L': 'U', 'U': 'L', 'l': 'u', 'u': 'l', 'K': 'I', 'I': 'K', 'k': 'i', 'i': 'k'} else c for c in s))\ndecode = encode"], "starter_code": "def encode(message):\n", "input_output": {"fn_name": "encode", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Cryptography", "Fundamentals", "Ciphers"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/592a6ad46d6c5a62b600003f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "encode", "task_id": "TACO_lite/465", "example": [[], []]} +{"requirement": "Given an ascending sorted rotated array Arr of distinct integers of size N. The array is right rotated K times. Find the value of K.\nExample 1:\nInput:\nN = 5\nArr[] = {5, 1, 2, 3, 4}\nOutput: 1\nExplanation: The given array is 5 1 2 3 4. \nThe original sorted array is 1 2 3 4 5. \nWe can see that the array was rotated \n1 times to the right.\nExample 2:\nInput:\nN = 5\nArr[] = {1, 2, 3, 4, 5}\nOutput: 0\nExplanation: The given array is not rotated.\nYour Task:\nComplete the function findKRotation() which takes array arr and size n, as input parameters and returns an integer representing the answer. You don't to print answer or take inputs.\nExpected Time Complexity: O(log(N))\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <=10^{5}\n1 <= Arr_{i} <= 10^{7}", "solutions": ["def findkrotation(arr, n):\n low = 0\n high = n - 1\n while low <= high:\n if high == low:\n return low\n mid = low + (high - low) // 2\n if arr[mid + 1] < arr[mid] and high > mid:\n return mid + 1\n if arr[mid] < arr[mid - 1] and low < mid:\n return mid\n if arr[high] > arr[mid]:\n high = mid - 1\n else:\n low = mid + 1\n return 0", "def findkrotation(arr, n):\n for i in range(1, n):\n if arr[i] < arr[i - 1]:\n return i\n break\n return 0", "def findkrotation(arr, n):\n el = min(arr)\n if arr.index(el) != 0:\n return arr.index(el)\n else:\n return 0", "def findkrotation(arr, n):\n temp = arr[:]\n temp.sort()\n return abs(temp.index(min(temp)) - arr.index(min(arr)))", "def findkrotation(arr, n):\n i = 0\n j = arr[-1]\n while arr[i] > j:\n i += 1\n return i", "def findkrotation(arr, n):\n if arr[0] < arr[n - 1]:\n return 0\n start = 0\n end = len(arr) - 1\n while start < end:\n mid = start + (end - start) // 2\n if arr[0] <= arr[mid]:\n start = mid + 1\n else:\n end = mid\n return start", "def findkrotation(arr, n):\n left = 0\n right = n - 1\n while left <= right:\n mid = left + (right - left) // 2\n if mid < right and arr[mid] > arr[mid + 1]:\n return mid + 1\n if mid > left and arr[mid - 1] > arr[mid]:\n return mid\n if arr[left] <= arr[mid]:\n left = mid + 1\n else:\n right = mid - 1\n return 0", "def findkrotation(arr, n):\n l = 0\n h = n - 1\n if arr[l] <= arr[h]:\n return l\n while l < h:\n mid = (l + h) // 2\n if arr[mid] > arr[mid + 1]:\n return mid + 1\n elif arr[mid] < arr[mid - 1]:\n return mid\n elif arr[l] <= arr[mid]:\n l = mid + 1\n else:\n h = mid - 1", "import numpy as np\n\ndef findkrotation(arr, n):\n mini = arr[0]\n rot = 0\n for i in range(n):\n if arr[i] < mini:\n mini = arr[i]\n rot = i\n return rot", "import numpy as np\n\ndef findkrotation(arr, n):\n arr = np.array(arr) - np.array(sorted(arr))\n count = 0\n for ele in arr:\n if ele > 0:\n count += 1\n return count", "def findkrotation(arr, n):\n return arr.index(min(arr))", "def findkrotation(arr, n):\n l = 0\n r = len(arr) - 1\n mid = 0\n if n == 1:\n return 0\n if arr[0] < arr[r]:\n return 0\n while l <= r:\n mid = l + (r - l) // 2\n if arr[mid] > arr[mid + 1]:\n return mid + 1\n if arr[mid] < arr[l]:\n r = mid - 1\n if arr[mid] >= arr[l]:\n l = mid + 1\n return l + 1", "def findkrotation(arr, n):\n low = 0\n high = n - 1\n while low <= high:\n mid = low + (high - low) // 2\n prev = (mid - 1 + n) % n\n next = (mid + 1) % n\n if arr[mid] <= arr[prev] and arr[mid] <= arr[next]:\n return mid\n elif arr[mid] <= arr[high]:\n high = mid - 1\n elif arr[mid] >= arr[low]:\n low = mid + 1\n return 0\n s = 0\n e = len(arr) - 1\n while s <= e:\n mid = s + (e - s) // 2\n nxt = (mid + 1) % n\n prv = (mid + n - 1) % n\n if arr[mid] <= arr[nxt] and arr[mid] <= arr[prv]:\n return mid\n elif arr[mid] >= arr[s]:\n s = mid + 1\n elif arr[mid] <= arr[e]:\n e = mid - 1\n return 0", "def findkrotation(arr, n):\n (i, j) = (0, n - 1)\n while i <= j:\n m = (i + j) // 2\n if arr[m] < arr[0]:\n j = m - 1\n else:\n i = m + 1\n return i % n", "def findkrotation(arr, n):\n nums = arr\n lengthOfNums = len(nums)\n start = 0\n end = lengthOfNums - 1\n pivot = 0\n while start <= end:\n mid = (start + end) // 2\n if mid - 1 >= 0 and nums[mid - 1] > nums[mid]:\n pivot = mid\n break\n elif nums[mid] < nums[start]:\n end = mid - 1\n elif nums[mid] > nums[start]:\n if nums[mid] <= nums[end]:\n end = mid - 1\n elif nums[mid] > nums[end]:\n start = mid + 1\n elif nums[mid] == nums[start]:\n start = mid + 1\n return pivot", "def findkrotation(arr, n):\n start = 0\n end = n - 1\n while start <= end:\n mid = start + (end - start) // 2\n nexti = (mid + 1) % n\n prev = (mid + n - 1) % n\n if arr[mid] <= arr[nexti] and arr[mid] <= arr[prev]:\n return mid\n elif arr[mid] <= arr[end]:\n end = mid - 1\n elif arr[start] <= arr[mid]:\n start = mid + 1\n return 0", "def findkrotation(arr, n):\n n = len(arr)\n left = 0\n right = n - 1\n while left <= right:\n if arr[left] <= arr[right]:\n return left\n mid = (left + right) // 2\n next = (mid + 1) % n\n prev = (mid + n - 1) % n\n if arr[mid] <= arr[next] and arr[mid] <= arr[prev]:\n return mid\n elif arr[mid] <= arr[right]:\n right = mid - 1\n elif arr[mid] >= arr[left]:\n left = mid + 1\n return -1", "def findkrotation(arr, n):\n a = []\n for i in arr:\n a.append(i)\n a.sort()\n count = abs(a.index(min(a)) - arr.index(min(arr)))\n return count", "def findkrotation(arr, n):\n i = 0\n j = n - 1\n min1 = 1000000\n ind = 0\n while i <= j:\n if arr[i] <= arr[j]:\n if min1 > arr[i]:\n ind = i\n min1 = arr[i]\n break\n mid = (i + j) // 2\n if arr[i] <= arr[mid]:\n if arr[i] < min1:\n ind = i\n min1 = arr[i]\n i = mid + 1\n else:\n if arr[mid] < min1:\n ind = mid\n min1 = arr[mid]\n j = mid - 1\n return ind", "def countRotations(arr, low, high):\n if high < low:\n return 0\n if high == low:\n return low\n mid = low + (high - low) // 2\n if mid < high and arr[mid + 1] < arr[mid]:\n return mid + 1\n if mid > low and arr[mid] < arr[mid - 1]:\n return mid\n if arr[high] > arr[mid]:\n return self.countRotations(arr, low, mid - 1)\n return self.countRotations(arr, mid + 1, high)\n\ndef findkrotation(arr, n):\n return self.countRotations(arr, 0, n - 1)", "def findkrotation(arr, n):\n lo = 0\n hi = n - 1\n if arr[lo] <= arr[hi]:\n return 0\n while lo <= hi:\n mid = (lo + hi) // 2\n if arr[mid] > arr[mid + 1]:\n return mid + 1\n elif arr[mid] < arr[mid - 1]:\n return mid\n elif arr[lo] <= arr[mid]:\n lo = mid + 1\n elif arr[mid] <= arr[hi]:\n hi = mid - 1\n return 0", "def findkrotation(arr, n):\n c = [i for i in arr]\n c.sort()\n d = c[0]\n return arr.index(d)", "def findkrotation(nums, n):\n (left, right) = (0, n - 1)\n if n <= 1 or nums[left] < nums[right]:\n return 0\n while left < right:\n mid = (left + right) // 2\n (prev, curr, next) = (nums[mid - 1], nums[mid], nums[mid + 1])\n if curr > next:\n return mid + 1\n if prev > curr:\n return mid\n if nums[0] < curr:\n left = mid + 1\n else:\n right = mid - 1", "from typing import List\n\ndef findkrotation(arr: List[int], n: int) -> int:\n (a, b) = (0, n - 1)\n while a <= b:\n mid = (a + b) // 2\n prev = (mid + n - 1) % n\n next_idx = (mid + 1) % n\n if arr[mid] <= arr[prev] and arr[mid] <= arr[next_idx]:\n return mid\n if arr[mid] <= arr[b]:\n b = mid - 1\n else:\n a = mid + 1\n return 0", "def findkrotation(arr, n):\n l = 0\n r = n - 1\n index = 0\n while l <= r:\n mid = (l + r) // 2\n if arr[mid] >= arr[0]:\n l = mid + 1\n else:\n r = mid - 1\n return l % n", "def findkrotation(arr, n):\n x = min(arr)\n l = arr[:]\n l.sort()\n return abs(l.index(x) - arr.index(x))", "def findkrotation(arr, n):\n m = min(arr)\n c = 0\n for i in range(n):\n if arr[i] != m:\n c = c + 1\n else:\n break\n return c", "def findkrotation(arr, n):\n a = min(arr)\n c = 0\n for i in range(len(arr)):\n if arr[i] == a:\n c = i\n else:\n continue\n return c", "def findkrotation(A, n):\n (low, high) = (0, n)\n while low < high:\n mid = (low + high) // 2\n if A[0] <= A[mid]:\n low = mid + 1\n else:\n high = mid\n if low == n:\n return 0\n return low", "def findkrotation(arr, n):\n l = 0\n r = n - 1\n while l <= r:\n mid = (l + r) // 2\n if arr[l] >= arr[mid] and arr[mid] >= arr[r]:\n return r\n if mid == 0 or arr[mid - 1] > arr[mid]:\n return mid\n if arr[mid] < arr[l]:\n r = mid - 1\n elif arr[mid] > arr[r]:\n l = mid + 1\n else:\n return l\n return -1", "def findkrotation(arr, n):\n if arr[0] < arr[-1] or n == 1:\n return 0\n for i in range(n - 1):\n if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:\n return i + 1\n return n", "def findkrotation(arr, n):\n low = 0\n high = n - 1\n while low <= high:\n mid = low + (high - low) // 2\n prev = (mid - 1 + n) % n\n next = (mid + 1) % n\n if arr[mid] <= arr[prev] and arr[mid] <= arr[next]:\n return mid\n elif arr[mid] <= arr[high]:\n high = mid - 1\n elif arr[mid] >= arr[low]:\n low = mid + 1\n return 0", "def findkrotation(arr, n):\n ans = 0\n for i in range(n - 1):\n if arr[i] > arr[i + 1]:\n ans = i + 1\n else:\n continue\n return ans", "def rot_bs(arr, start, end, n):\n while start <= end:\n mid = start + (end - start) // 2\n prev_ele = (mid - 1 + n) % n\n next_ele = (mid + 1) % n\n if arr[mid] < arr[prev_ele] and arr[mid] < arr[next_ele]:\n return mid\n elif arr[mid] <= arr[end]:\n end = mid - 1\n elif arr[start] <= arr[mid]:\n start = mid + 1\n\ndef findkrotation(arr, n):\n if arr[0] <= arr[n - 1]:\n return 0\n return self.rot_bs(arr, 0, n - 1, n)", "def findkrotation(nums, n):\n low = 0\n high = n - 1\n while low < high:\n mid = low + high >> 1\n if nums[mid] > nums[high]:\n low = mid + 1\n else:\n high = mid\n return low", "def findkrotation(arr, n):\n lo = 0\n hi = len(arr) - 1\n if len(arr) == 1 or arr[lo] < arr[hi]:\n return 0\n while lo <= hi:\n mid = (lo + hi) // 2\n if arr[mid] < arr[mid - 1]:\n return mid\n if arr[mid] > arr[mid + 1]:\n return mid + 1\n if arr[lo] < arr[mid]:\n lo = mid + 1\n else:\n hi = mid - 1", "import sys\n\ndef findkrotation(arr, n):\n (l, r) = (0, len(arr) - 1)\n minNum = arr[0]\n index = 0\n while l <= r:\n if arr[l] <= arr[r]:\n if minNum > arr[l]:\n index = l\n break\n mid = (l + r) // 2\n if minNum > arr[mid]:\n minNum = arr[mid]\n index = mid\n if arr[mid] >= arr[l]:\n l = mid + 1\n else:\n r = mid - 1\n return index", "def findkrotation(arr, n):\n (l, h) = (0, n - 1)\n MAX = float('-inf')\n if arr[l] <= arr[h]:\n return 0\n while l <= h:\n mid = (l + h) // 2\n if arr[mid] > MAX:\n MAX = arr[mid]\n max_index = mid\n if arr[mid] < arr[l]:\n h = mid - 1\n else:\n l = mid + 1\n return max_index + 1", "def findkrotation(nums, n):\n left = 0\n right = len(nums) - 1\n ans = 0\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] < nums[mid - 1]:\n ans = mid\n break\n if nums[mid] < nums[0]:\n right = mid - 1\n else:\n left = mid + 1\n return ans", "def findkrotation(nums, n):\n s = 0\n e = n - 1\n pivot = -1\n while s <= e:\n mid = s + (e - s) // 2\n if mid < e and nums[mid] > nums[mid + 1]:\n pivot = mid\n break\n elif mid > s and nums[mid - 1] > nums[mid]:\n pivot = mid - 1\n break\n if nums[mid] <= nums[s]:\n e = mid - 1\n elif nums[s] < nums[mid]:\n s = mid + 1\n if pivot == -1:\n return 0\n return pivot + 1", "def findkrotation(arr, n):\n x = min(arr)\n for i in range(n):\n if arr[i] == x:\n return i\n break", "def findkrotation(nums, n):\n start = 0\n end = len(nums) - 1\n while start <= end:\n mid = (start + end) // 2\n if mid < end and nums[mid] > nums[mid + 1]:\n return mid + 1\n if mid < end and nums[mid] < nums[mid - 1]:\n return mid\n if nums[start] == nums[mid] == nums[end] and start != mid != end:\n if nums[start] > nums[start + 1]:\n return start + 1\n start += 1\n if nums[end - 1] > nums[end]:\n return end\n end -= 1\n elif nums[mid] > nums[start] or (nums[mid] == nums[start] and nums[mid] > nums[end]):\n start = mid + 1\n else:\n end = mid - 1\n return 0", "def findkrotation(arr, n):\n l = 0\n h = n - 1\n while l < h:\n m = (l + h) // 2\n if arr[m] <= arr[h]:\n h = m\n else:\n l = m\n if arr[m] > arr[m + 1]:\n return m + 1\n return l", "def findkrotation(arr, n):\n cnt = 1\n for i in range(1, n):\n if arr[i - 1] < arr[i]:\n cnt += 1\n else:\n break\n return cnt % n", "def findkrotation(arr, n):\n m = float('inf')\n idx = 0\n for i in range(n):\n if m > arr[i]:\n m = arr[i]\n idx = i\n return idx", "def findkrotation(nums, n):\n rotation_pivot = 0\n (l, r, mid) = (0, n - 1, 0)\n if n == 1:\n return 0\n while l <= r:\n mid = (l + r) // 2\n if mid < n - 1:\n if nums[mid] > nums[mid + 1]:\n return mid + 1\n if mid > 0:\n if nums[mid] < nums[mid - 1]:\n return mid\n if nums[l] > nums[mid]:\n r = mid - 1\n else:\n l = mid + 1\n return 0", "def b_search(arr, start, end):\n middle = (start + end) // 2\n if start == end:\n return start\n while start < end:\n if arr[middle] < arr[middle - 1] and arr[middle] < arr[middle + 1]:\n return middle\n elif arr[middle] < arr[end]:\n return b_search(arr, start, middle - 1)\n else:\n return b_search(arr, middle + 1, end)\n return -1\n\ndef findkrotation(arr, n):\n result = b_search(arr, 0, n - 1)\n if result == -1:\n return 0\n else:\n return result", "def findkrotation(arr, n):\n l = []\n l.extend(arr)\n l.sort()\n return arr.index(l[0])"], "starter_code": "def findkrotation(arr, n):\n", "input_output": {"inputs": ["N = 5\r\nArr[] = {5, 1, 2, 3, 4}", "N = 5\r\nArr[] = {1, 2, 3, 4, 5}"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays", "Searching", "Algorithms"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Complete search"], "skill_types": ["Data structures", "Complete search"], "url": "https://practice.geeksforgeeks.org/problems/rotation4723/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(N))", "entry_point": "findkrotation", "task_id": "TACO_lite/458", "example": [[[5, [5, 1, 2, 3, 4]], [5, [1, 2, 3, 4, 5]]], [null, null]]} +{"requirement": "Adding tip to a restaurant bill in a graceful way can be tricky, thats why you need make a function for it.\n\nThe function will receive the restaurant bill (always a positive number) as an argument. You need to 1) **add at least 15%** in tip, 2) round that number up to an *elegant* value and 3) return it.\n\nWhat is an *elegant* number? It depends on the magnitude of the number to be rounded. Numbers below 10 should simply be rounded to whole numbers. Numbers 10 and above should be rounded like this:\n\n10 - 99.99... ---> Round to number divisible by 5\n\n100 - 999.99... ---> Round to number divisible by 50\n\n1000 - 9999.99... ---> Round to number divisible by 500\n\nAnd so on...\n\nGood luck!\n\n## Examples\n```\n 1 --> 2\n 7 --> 9\n12 --> 15\n86 --> 100\n```", "solutions": ["from math import ceil, log10\n\ndef graceful_tipping(bill):\n bill *= 1.15\n if bill < 10:\n return ceil(bill)\n e = int(log10(bill))\n unit = 10 ** e / 2\n return ceil(bill / unit) * unit", "import math\n\ndef graceful_tipping(bill):\n c = bill * 115 / 100\n m = 1 if c < 10 else 5 * 10 ** int(math.log10(c) - 1)\n return math.ceil(c / m) * m", "def graceful_tipping(bill):\n import math\n multiple = 0\n tip = bill + 0.15 * bill\n if tip < 10:\n multiple = 1\n elif tip < 100:\n multiple = 5\n elif tip < 1000:\n multiple = 50\n elif tip < 10000:\n multiple = 500\n elif tip < 100000:\n multiple = 5000\n elif tip < 1000000:\n multiple = 50000\n elif tip < 10000000:\n multiple = 500000\n elif tip < 100000000:\n multiple = 5000000\n return math.ceil(float(tip) / multiple) * multiple", "import math\n\ndef graceful_tipping(bill):\n x = math.ceil(bill + bill * 15 / 100)\n if x < 11:\n return x\n else:\n le = len(str(x)) - 2\n y = 5 * 10 ** le\n return x + (y * math.ceil(x / y) - x)", "import math\n\ndef graceful_tipping(rest_bill):\n res = rest_bill * 1.15\n if res < 10:\n return math.ceil(res)\n tmp = 5 * 10.0 ** (math.ceil(math.log10(res)) - 2)\n if res % tmp > 0:\n res += tmp - res % tmp\n return res", "import math\n\ndef graceful_tipping(bill):\n bill = bill * 1.15\n if bill < 10:\n return math.ceil(bill)\n elif 10 <= bill < 100:\n bill = math.ceil(bill)\n mul5 = [i for i in range(1, bill + 5) if i % 5 == 0]\n return mul5[-1]\n elif 100 <= bill < 1000:\n bill = math.ceil(bill)\n mul50 = [i for i in range(1, bill + 50) if i % 50 == 0]\n return mul50[-1]\n elif 1000 <= bill < 10000:\n bill = math.ceil(bill)\n mul500 = [i for i in range(1, bill + 500) if i % 500 == 0]\n return mul500[-1]\n elif 10000 <= bill < 100000:\n bill = math.ceil(bill)\n mul5000 = [i for i in range(1, bill + 5000) if i % 5000 == 0]\n return mul5000[-1]\n elif 100000 <= bill < 1000000:\n bill = math.ceil(bill)\n mul50000 = [i for i in range(1, bill + 50000) if i % 50000 == 0]\n return mul50000[-1]\n elif 1000000 <= bill < 10000000:\n bill = math.ceil(bill)\n mul500000 = [i for i in range(1, bill + 500000) if i % 500000 == 0]\n return mul500000[-1]", "def graceful_tipping(bill):\n total = bill * 1.15\n if total < 10:\n total = int(total) + (total % 1 > 0)\n else:\n x = len(str(int(total))) - 2\n m = 5 * 10 ** x\n total = (int(total / m) + (total % m > 0)) * m\n return total", "from math import ceil\n\ndef graceful_tipping(bill):\n total = bill * 1.15\n if total < 10:\n return ceil(total)\n total /= 5\n d = 0\n while total >= 20:\n d += 1\n total /= 10\n return ceil(total) * 5 * 10 ** d", "from math import ceil\nfrom itertools import count\n\ndef graceful_tipping(bill):\n num = ceil(bill * 0.15 + bill)\n if num < 10:\n return num\n d = int('5' + (len(str(num)) - 2) * '0')\n for n in count(num):\n if n % d == 0:\n return n"], "starter_code": "def graceful_tipping(bill):\n", "input_output": {"fn_name": "graceful_tipping", "inputs": [[1], [7], [12], [86], [99], [1149], [983212]], "outputs": [[2], [9], [15], [100], [150], [1500], [1500000]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5eb27d81077a7400171c6820", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "graceful_tipping", "task_id": "TACO_lite/366", "example": [[[1], [7], [12], [86]], [2, 9, 15.0, 100.0]]} +{"requirement": "Given an integer N, the task is to find out the count of numbers M that satisfy the condition M + sum(M) + sum (sum(M)) = N, where sum(M) denotes the sum of digits in M.\nExample 1:\nInput: N = 9\nOutput: 1\nExplaination: Only 1 positive integer satisfies \nthe condition that is 3, 3 + sum(3) + sum(sum(3))\n= 3 + 3 + 3 = 9. \nExample 2:\nInput: N = 9939\nOutput: 4\nExplaination: M can be 9898, 9907, 9910 and 9913. \n9898 + sum(9898) + sum(sum(9898)) = 9898 + 34 + 7 \n= 9939. \n9907 + sum(9907) + sum(sum(9907)) = 9907 + 25 + 7 \n= 9939. \n9910 + sum(9910) + sum(sum(9910)) = 9910 + 19 + 10 \n= 9939. \n9913 + sum(9913) + sum(sum(9913)) = 9913 + 22 + 4 \n= 9939. \nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function countOfNumbers() which takes the value N and returns the count of numbers M that satisfy the given condition\nExpected Time Complexity: O(logn)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 N \u2264 10^{9}", "solutions": ["def sod(n):\n s = 0\n while n != 0:\n s += n % 10\n n = n // 10\n return s\n\ndef countofnumbers(N):\n c = 0\n d = N - 100\n if d < 0:\n d = 0\n for i in range(d, N + 1):\n if i + self.sod(i) + self.sod(self.sod(i)) == N:\n c += 1\n return c", "def sum(m):\n s = 0\n while m > 0:\n r = m % 10\n m = m // 10\n s = s + r\n return s\n\ndef countofnumbers(N):\n c = 0\n for i in range(N - 97, N + 1):\n a = sum(i)\n b = sum(a)\n if i + a + b == N:\n c += 1\n return c", "def sumD(N):\n sm = 0\n while N > 0:\n sm += N % 10\n N //= 10\n return sm\n\ndef countofnumbers(N):\n cn = 0\n for i in range(N - 97, N + 1):\n if i + self.sumD(i) + self.sumD(self.sumD(i)) == N:\n cn += 1\n return cn", "def sum1(n):\n rem = 0\n sum_of_digits = 0\n while n > 0:\n rem = n % 10\n sum_of_digits += rem\n n = n // 10\n return sum_of_digits\n\ndef __init__():\n self.c = 0\n self.a = None\n self.b = None\n self.i = None\n\ndef countofnumbers(N):\n self.c = 0\n for self.i in range(N - 97, N + 1):\n self.a = sum1(self.i)\n self.b = sum1(self.a)\n if self.i + self.a + self.b == N:\n self.c += 1\n return self.c", "def countofnumbers(N):\n\n def sum(n):\n s = 0\n while n > 0:\n rem = n % 10\n n //= 10\n s += rem\n return s\n c = 0\n for i in range(N - 97, N + 1):\n a = sum(i)\n b = sum(a)\n if i + a + b == N:\n c += 1\n return c"], "starter_code": "def countofnumbers(N):\n", "input_output": {"inputs": ["N = 9", "N = 9939"], "outputs": ["1", "4"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Numbers", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/count-the-numbers-satisfying-m-summ-sumsumm-equals-to-n2537/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(logn)", "entry_point": "countofnumbers", "task_id": "TACO_lite/469", "example": [[[9], [9939]], ["1", "4"]]} +{"requirement": "For every positive integer N, there exists a unique sequence starting with 1 and ending with N and such that every number in the sequence is either the double of the preceeding number or the double plus 1. \n\nFor example, given N = 13, the sequence is [1, 3, 6, 13], because . . . :\n```\n 3 = 2*1 +1\n 6 = 2*3\n 13 = 2*6 +1\n```\n\nWrite a function that returns this sequence given a number N. Try generating the elements of the resulting list in ascending order, i.e., without resorting to a list reversal or prependig the elements to a list.", "solutions": ["def climb(n):\n return [1] if n == 1 else climb(int(n / 2)) + [n]", "def climb(n):\n res = []\n cur = 1\n mask = 1 << max(0, n.bit_length() - 2)\n while cur <= n:\n res.append(cur)\n cur = 2 * cur + (1 if n & mask != 0 else 0)\n mask >>= 1\n return res", "def climb(n):\n result = [1]\n for x in '{:b}'.format(n)[1:]:\n result.append(result[-1] * 2 + (x == '1'))\n return result", "def climb(n):\n return [n >> i for i in range(len(f'{n:b}') - 1, -1, -1)]", "from math import log\nfrom collections import deque\n\ndef climb(n):\n return [n // 2 ** i for i in range(int(log(n, 2)) + 1)][::-1]\n\ndef climb(n):\n seq = deque([n])\n while n > 1:\n n //= 2\n seq.appendleft(n)\n return list(seq)", "def climb(n):\n return [n >> n.bit_length() - i - 1 for i in range(n.bit_length())]", "def climb(n):\n return list(climb_iterator(n))\n\ndef climb_iterator(n):\n cursor = 0\n for digit in bin(n)[2:]:\n cursor = 2 * cursor + int(digit)\n yield cursor", "def climb(n):\n res = [n]\n while res[-1] != 1:\n res.append(res[-1] // 2)\n return res[::-1]", "def climb(n):\n arr = []\n while n:\n arr.append(n)\n n //= 2\n return arr[::-1]"], "starter_code": "def climb(n):\n", "input_output": {"fn_name": "climb", "inputs": [[1], [100], [12345], [54321]], "outputs": [[[1]], [[1, 3, 6, 12, 25, 50, 100]], [[1, 3, 6, 12, 24, 48, 96, 192, 385, 771, 1543, 3086, 6172, 12345]], [[1, 3, 6, 13, 26, 53, 106, 212, 424, 848, 1697, 3395, 6790, 13580, 27160, 54321]]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/559760bae64c31556c00006b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "climb", "task_id": "TACO_lite/379", "example": [[[13]], ["[1, 3, 6, 13]"]]} +{"requirement": "In genetics, a sequence\u2019s motif is a nucleotides (or amino-acid) sequence pattern. Sequence motifs have a biological significance. For more information you can take a look [here](https://en.wikipedia.org/wiki/Sequence_motif).\n\n\nFor this kata you need to complete the function `motif_locator`. This function receives 2 arguments - a sequence and a motif. Both arguments are strings.\n\nYou should return an array that contains all the start positions of the motif (in order). A sequence may contain 0 or more repetitions of the given motif. Note that the number of the first position is 1, not 0.\n\n**Some examples:**\n\n- For the `sequence` \"ACGTGGGGACTAGGGG\" and the `motif` \"GGGG\" the result should be [5, 13]. \n- For the `sequence` \"ACCGTACCAAGGGACC\" and the `motif` \"AAT\" the result should be []\n- For the `sequence` \"GGG\" and the motif \"GG\" the result should be [1, 2]\n\n**Note**: You can take a look to my others bio-info kata [here](http://www.codewars.com/users/nbeck/authored)", "solutions": ["def motif_locator(sequence, motif):\n (res, i) = ([], 0)\n while True:\n i = sequence.find(motif, i) + 1\n if not i:\n return res\n res.append(i)", "def motif_locator(sequence, motif):\n return [i + 1 for (i, c) in enumerate(sequence) if sequence[i:i + len(motif)] == motif]", "def motif_locator(seq, motif):\n dex = 0\n result = []\n while True:\n dex = seq.find(motif, dex)\n if dex == -1:\n return result\n dex += 1\n result.append(dex)", "def motif_locator(s, motif):\n return [i + 1 for i in range(len(s) - len(motif) + 1) if s[i:].startswith(motif)]", "from itertools import count\n\ndef motif_locator(sequence, motif):\n if len(motif) > len(sequence):\n return []\n n = len(motif)\n target_hash = sum(map(ord, motif))\n hashish = sum(map(ord, sequence[:n]))\n res = []\n for i in count():\n if hashish == target_hash and sequence[i:i + n] == motif:\n res.append(i + 1)\n if i + n == len(sequence):\n return res\n hashish += ord(sequence[i + n]) - ord(sequence[i])", "import re\n\ndef motif_locator(sequence, motif):\n return [m.start() + 1 for m in re.finditer('{}(?={})'.format(motif[0], motif[1:]), sequence)]", "def motif_locator(sequence, motif):\n start = 0\n arr = []\n while True:\n index = sequence.find(motif, start)\n if index == -1:\n break\n start = index + 1\n arr.append(index + 1)\n return arr", "motif_locator = lambda s, m: sorted(list({s.find(m, e) + 1 for (e, i) in enumerate(range(len(s))) if s.find(m, e) != -1}))", "def motif_locator(s, m):\n return [i + 1 for i in range(len(s) - len(m) + 1) if s[i:i + len(m)] == m]"], "starter_code": "def motif_locator(sequence, motif):\n", "input_output": {"fn_name": "motif_locator", "inputs": [["TTCCGGAACC", "CC"], ["ACGTTACAACGTTAG", "ACGT"], ["ACGTACGTACGT", "AAA"], ["ACGT", "ACGTGAC"]], "outputs": [[[3, 9]], [[1, 9]], [[]], [[]]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5760c1c7f2717b91e20001a4", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "motif_locator", "task_id": "TACO_lite/374", "example": [[["ACGTGGGGACTAGGGG", "GGGG"], ["ACCGTACCAAGGGACC", "AAT"], ["GGG", "GG"]], ["[5, 13]", "[]", "[1, 2]"]]} +{"requirement": "Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).\nMore formally check if there exists\u00a0two indices i and j such that :\n\ni != j\n0 <= i, j < arr.length\narr[i] == 2 * arr[j]\n\n\u00a0\nExample 1:\nInput: arr = [10,2,5,3]\nOutput: true\nExplanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.\n\nExample 2:\nInput: arr = [7,1,14,11]\nOutput: true\nExplanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.\n\nExample 3:\nInput: arr = [3,1,7,11]\nOutput: false\nExplanation: In this case does not exist N and M, such that N = 2 * M.\n\n\u00a0\nConstraints:\n\n2 <= arr.length <= 500\n-10^3 <= arr[i] <= 10^3", "solutions": ["def checkifexist(arr: List[int]) -> bool:\n found = {}\n for num in arr:\n if num * 2 in found:\n return True\n if num % 2 == 0 and num / 2 in found:\n return True\n found[num] = True\n return False", "def checkifexist(arr: List[int]) -> bool:\n lookup = dict()\n for val in arr:\n if val * 2 in lookup:\n return True\n elif val / 2 in lookup:\n return True\n else:\n lookup[val] = 1\n return False", "def checkifexist(arr: List[int]) -> bool:\n tracker = set()\n for n in arr:\n if n % 2 == 0 and n / 2 in tracker or n * 2 in tracker:\n return True\n tracker.add(n)\n return False", "def checkifexist(arr: List[int]) -> bool:\n for i in range(0, len(arr)):\n for j in range(i + 1, len(arr)):\n if arr[i] == 2 * arr[j] or arr[j] == 2 * arr[i]:\n return True\n return False", "def checkifexist(arr: List[int]) -> bool:\n arr.sort()\n for k in range(len(arr) - 1):\n if 2 * arr[k] in arr[k + 1:] or 2 * arr[k] in arr[:k]:\n return True\n return False", "def checkifexist(arr: List[int]) -> bool:\n i = 0\n i = len(arr)\n for j in range(0, i):\n for k in range(0, i):\n if arr[j] > 0 and arr[k] > 0 and (arr[j] > arr[k]):\n if arr[j] == arr[k] * 2:\n return True\n elif arr[j] < 0 and arr[k] < 0 and (arr[j] < arr[k]):\n if arr[k] * 2 == arr[j]:\n return True\n if arr[0] == 0 and arr[1] == 0:\n return True\n else:\n return False", "def checkifexist(arr: List[int]) -> bool:\n arr.sort()\n for i in range(len(arr)):\n for j in range(i + 1, len(arr)):\n if arr[i] != 0 and arr[j] / arr[i] == 2:\n return True\n if arr[i] == 0 and arr[j] == 0:\n return True\n if arr[i] < 0 and arr[j] < 0 and (arr[i] / arr[j] == 2):\n return True", "def checkifexist(arr: List[int]) -> bool:\n seen = set()\n for e in arr:\n if 2 * e in seen or (e % 2 == 0 and e // 2 in seen):\n return True\n seen.add(e)\n return False", "def checkifexist(arr: List[int]) -> bool:\n for num in arr:\n if num == 0:\n if arr.count(0) > 1:\n return True\n elif arr.count(num * 2) != 0:\n return True\n return False", "def checkifexist(arr: List[int]) -> bool:\n h_table = set()\n for num in arr:\n if num * 2 in h_table or num / 2 in h_table:\n return True\n h_table.add(num)\n return False", "def checkifexist(arr: List[int]) -> bool:\n doubledList = []\n l = len(arr)\n for num in arr:\n doubledList.append(num * 2)\n for i in range(l):\n if doubledList[i] in arr and arr.index(doubledList[i]) != i:\n return True\n return False", "def checkifexist(arr: List[int]) -> bool:\n cache = set()\n for (i, value) in enumerate(arr):\n if 2 * value in cache or (value % 2 == 0 and value / 2 in cache):\n return True\n cache.add(value)\n return False", "def checkifexist(arr: List[int]) -> bool:\n if len(arr) < 2:\n return False\n for n in range(len(arr)):\n m = 2 * arr[n]\n for k in range(len(arr)):\n if arr[k] == m and k != n:\n return True\n return False", "def checkifexist(arr: List[int]) -> bool:\n if arr[0] == 0 and arr[1] == 0:\n return True\n dictionary = {}\n for number in arr:\n dictionary[2 * number] = True\n for number in arr:\n if number in dictionary and number != 0:\n return True\n return False"], "starter_code": "def checkifexist(arr: List[int]) -> bool:\n", "input_output": {"fn_name": "checkIfExist", "inputs": [[[10, 2, 5, 3]]], "outputs": [true]}, "difficulty": "EASY", "raw_tags": ["Binary Search", "Two Pointers", "Array", "Sorting", "Hash Table"], "name": null, "source": "leetcode", "tags": ["Data structures", "Sorting", "Amortized analysis"], "skill_types": ["Amortized analysis", "Sorting", "Data structures"], "url": "https://leetcode.com/problems/check-if-n-and-its-double-exist/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "checkifexist", "task_id": "TACO_lite/438", "example": [[], []]} +{"requirement": "The objective is to return all pairs of integers from a given array of integers that have a difference of 2.\n\nThe result array should be sorted in ascending order of values.\n\nAssume there are no duplicate integers in the array. The order of the integers in the input array should not matter.\n\n\n## Examples\n~~~if-not:python\n```\n[1, 2, 3, 4] should return [[1, 3], [2, 4]]\n\n[4, 1, 2, 3] should also return [[1, 3], [2, 4]]\n\n[1, 23, 3, 4, 7] should return [[1, 3]]\n\n[4, 3, 1, 5, 6] should return [[1, 3], [3, 5], [4, 6]]\n```\n~~~\n~~~if:python\n```\n[1, 2, 3, 4] should return [(1, 3), (2, 4)]\n\n[4, 1, 2, 3] should also return [(1, 3), (2, 4)]\n\n[1, 23, 3, 4, 7] should return [(1, 3)]\n\n[4, 3, 1, 5, 6] should return [(1, 3), (3, 5), (4, 6)]\n```\n~~~", "solutions": ["def twos_difference(a):\n s = set(a)\n return sorted(((x, x + 2) for x in a if x + 2 in s))", "def twos_difference(lst):\n return [(num, num + 2) for num in sorted(lst) if num + 2 in lst]", "def twos_difference(arr):\n arr = sorted(arr)\n b = []\n for i in range(len(arr)):\n for j in range(len(arr)):\n if arr[j] - arr[i] == 2:\n b.append((arr[i], arr[j]))\n return b", "def twos_difference(lst):\n return [(i, i + 2) for i in sorted(lst) if i + 2 in lst]", "def twos_difference(lst):\n matches = []\n for n in sorted(lst):\n if n + 2 in lst:\n matches.append((n, n + 2))\n return matches", "def twos_difference(A):\n L = []\n for i in sorted(A):\n if i + 2 in A:\n L.append((i, i + 2))\n return L", "def twos_difference(lst):\n ende = []\n for i in lst:\n if i + 2 in lst:\n ende.append((i, i + 2))\n return sorted(ende)", "def twos_difference(l):\n r = [(i, i + 2) for i in sorted(l) if i + 2 in l]\n return r\ntwos_difference = lambda l: [(i, i + 2) for i in sorted(l) if i + 2 in l]", "def twos_difference(lst):\n result = []\n for elem in lst:\n if elem + 2 in lst:\n result.append((elem, elem + 2))\n result.sort()\n return result", "def twos_difference(lst):\n newlist = lst\n even = []\n odd = []\n finaleven = []\n finalodd = []\n for num in newlist:\n if num % 2 == 0:\n even.append(num)\n else:\n odd.append(num)\n for i in even:\n for j in even:\n if i + 2 == j:\n finaleven.append((i, j))\n for a in odd:\n for b in odd:\n if a + 2 == b:\n finalodd.append((a, b))\n y = sorted(finaleven)\n z = sorted(finalodd)\n return sorted(y + z)", "def twos_difference(lst):\n s = set(lst)\n return [(n, n + 2) for n in sorted(s) if n + 2 in s]", "def twos_difference(lst):\n new_list = []\n lst.sort()\n for (ind, val) in enumerate(lst):\n get_check = val + 2\n try:\n if lst.index(get_check):\n new_list.append((val, get_check))\n except ValueError:\n continue\n return new_list", "def twos_difference(lst):\n return sorted([(x, x + 2) for x in lst if x + 2 in lst], key=lambda x: (x[0], x[1]))", "import itertools as it\nimport operator as op\n\ndef twos_difference(lst):\n pairs = it.combinations(lst, 2)\n twodiffs = (pair for pair in pairs if abs(op.sub(*pair)) == 2)\n return sorted([tuple(sorted(pair)) for pair in list(twodiffs)])", "def twos_difference(lst):\n concat = []\n for number in lst:\n if int(number) + 2 in lst:\n concat.append((int(number), int(number) + 2))\n return sorted(concat)", "def twos_difference(a):\n return sorted([(i, j) for i in a for j in a if i - j == -2])", "def twos_difference(lst):\n if not lst:\n return []\n test = list(range(min(lst), max(lst) + 1))\n return [(test[i], test[i + 2]) for i in range(len(test) - 2) if all((test[i] in lst, test[i + 2] in lst))]", "def twos_difference(lst):\n lst1 = []\n for i in lst:\n for j in lst:\n if i - j == 2 or i - j == -2:\n if (i, j) not in lst1 and (j, i) not in lst1:\n if i < j:\n lst1.append((i, j))\n else:\n lst1.append((j, i))\n lst1.sort()\n return lst1", "def twos_difference(lst):\n my_pairs = []\n for i in range(0, len(lst)):\n for j in range(0, len(lst)):\n if lst[j] - lst[i] == 2:\n my_pairs.append([lst[j], lst[i]])\n diffs = []\n for pair in my_pairs:\n pair.sort()\n diffs.append(tuple(pair))\n diffs.sort()\n return diffs", "def twos_difference(lst):\n (results, memo) = ([], {})\n for n in lst:\n if n in memo:\n for k in memo[n]:\n (a, b) = sorted([k, n])\n results.append((a, b))\n memo.setdefault(n + 2, []).append(n)\n memo.setdefault(n - 2, []).append(n)\n return sorted(results)"], "starter_code": "def twos_difference(lst):\n", "input_output": {"fn_name": "twos_difference", "inputs": [[[1, 2, 3, 4]], [[1, 3, 4, 6]], [[0, 3, 1, 4]], [[4, 1, 2, 3]], [[6, 3, 4, 1, 5]], [[3, 1, 6, 4]], [[1, 3, 5, 6, 8, 10, 15, 32, 12, 14, 56]], [[1, 4, 7, 10]], [[]]], "outputs": [[[[1, 3], [2, 4]]], [[[1, 3], [4, 6]]], [[[1, 3]]], [[[1, 3], [2, 4]]], [[[1, 3], [3, 5], [4, 6]]], [[[1, 3], [4, 6]]], [[[1, 3], [3, 5], [6, 8], [8, 10], [10, 12], [12, 14]]], [[]], [[]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms", "Sorting"], "name": null, "source": "codewars", "tags": ["Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/5340298112fa30e786000688", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "twos_difference", "task_id": "TACO_lite/341", "example": [[[[1, 2, 3, 4]], [[4, 1, 2, 3]], [[1, 23, 3, 4, 7]], [[4, 3, 1, 5, 6]]], ["[(1, 3), (2, 4)]", "[(1, 3), (2, 4)]", "[(1, 3)]", "[(1, 3), (3, 5), (4, 6)]"]]} +{"requirement": "Given a BST and an integer K. Find the Kth Smallest element in the BST using O(1) extra space. \nExample 1:\nInput:\n 2\n / \\\n 1 3\nK = 2\nOutput: 2\nExplanation: 2 is the 2nd smallest element in the BST\nExample 2:\nInput:\n 2\n / \\\n 1 3\nK = 5\nOutput: -1\nExplanation: There is no 5th smallest element in the BST as the size of BST is 3\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function KthSmallestElement() which takes the root of the BST and integer K as inputs and returns the Kth smallest element in the BST, if no such element exists return -1.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\nConstraints:\n1<=Number of nodes<=10^5", "solutions": ["def KthSmallestElement(root, K):\n\n def Inorder(root):\n if root == None:\n return\n Inorder(root.left)\n ans.append(root.data)\n Inorder(root.right)\n ans = []\n Inorder(root)\n if K > len(ans):\n return -1\n return ans[K - 1]", "def KthSmallestElement(root, K):\n\n def inorder(root):\n nonlocal count, ans\n if not root:\n return\n inorder(root.left)\n count += 1\n if count == K:\n ans = root.data\n inorder(root.right)\n count = 0\n ans = -1\n inorder(root)\n return ans", "def util(root, k):\n if not root:\n return\n self.util(root.left, k)\n self.cnt += 1\n if self.cnt == k:\n self.cnt += 1\n self.ans = root.data\n return\n self.util(root.right, k)\n\ndef KthSmallestElement(root, k):\n self.cnt = 0\n self.ans = -1\n self.util(root, k)\n return self.ans", "def util(root, k):\n global cnt, ans\n par = root\n while par != None:\n if par.left != None:\n temp = par.left\n while temp.right != None and temp.right != par:\n temp = temp.right\n if temp.right == None:\n temp.right = par\n par = par.left\n else:\n temp.right = None\n cnt += 1\n if cnt == k:\n ans = par.data\n par = par.right\n else:\n cnt += 1\n if cnt == k:\n ans = par.data\n par = par.right\n\ndef KthSmallestElement(root, k):\n global cnt, ans\n cnt = 0\n ans = -1\n self.util(root, k)\n return ans", "def inorder(root, l):\n if root is None:\n return\n self.inorder(root.left, l)\n l.append(root.data)\n self.inorder(root.right, l)\n\ndef InOrder(root):\n l = []\n self.inorder(root, l)\n return l\n\ndef KthSmallestElement(root, K):\n p = self.InOrder(root)\n p.sort()\n if K > len(p):\n return -1\n else:\n return p[K - 1]", "def kthelement(root):\n if root is None:\n return -1\n leftside = self.kthelement(root.left)\n if leftside != -1:\n return leftside\n self.K -= 1\n if self.K == 0:\n return root.data\n return self.kthelement(root.right)\n\ndef KthSmallestElement(root, K):\n self.K = K\n return self.kthelement(root)", "def getMin(root, li):\n if root:\n self.getMin(root.left, li)\n li.append(root.data)\n self.getMin(root.right, li)\n\ndef KthSmallestElement(root, K):\n li = []\n self.getMin(root, li)\n if K > len(li):\n return -1\n return li[K - 1]", "def inorder(root, arr):\n if root is not None:\n self.inorder(root.left, arr)\n arr.append(root.data)\n self.inorder(root.right, arr)\n\ndef KthSmallestElement(root, K):\n arr = []\n self.inorder(root, arr)\n if len(arr) < K:\n return -1\n return arr[K - 1]", "def KthSmallestElement(root, K):\n li = self.inorder(root, [])\n if len(li) < K:\n return -1\n else:\n return li[K - 1]\n\ndef inorder(node, a):\n if node is None:\n return\n self.inorder(node.left, a)\n a.append(node.data)\n self.inorder(node.right, a)\n return a", "def KthSmallestElement(root, K):\n temp = root\n while temp:\n if temp.left is None:\n K -= 1\n if K == 0:\n return temp.data\n temp = temp.right\n else:\n pred = temp.left\n while pred.right and pred.right != temp:\n pred = pred.right\n if pred.right is None:\n pred.right = temp\n temp = temp.left\n else:\n pred.right = None\n K -= 1\n if K == 0:\n return temp.data\n temp = temp.right\n return -1", "def inorder(root):\n if root == None:\n return []\n return self.inorder(root.left) + [root.data] + self.inorder(root.right)\n\ndef KthSmallestElement(root, K):\n li = self.inorder(root)\n if len(li) >= K:\n return li[K - 1]\n return -1", "def KthSmallestElement(root, K):\n if not root:\n return None\n stack = []\n count = 0\n while stack or root:\n while root:\n stack.append(root)\n root = root.left\n node = stack.pop()\n count += 1\n if count == K:\n return node.data\n root = node.right\n return -1", "def inOrder(root):\n res = []\n if root:\n res = self.inOrder(root.left)\n res.append(root.data)\n res = res + self.inOrder(root.right)\n return res\n\ndef KthSmallestElement(root, K):\n li = self.inOrder(root)\n if len(li) >= K:\n return li[K - 1]\n return -1", "def inorder(root, ans):\n if root:\n self.inorder(root.left, ans)\n ans.append(root.data)\n self.inorder(root.right, ans)\n\ndef KthSmallestElement(root, k):\n ans = []\n self.inorder(root, ans)\n if k <= len(ans):\n return ans[k - 1]\n else:\n return -1", "def KthSmallestElement(root, K):\n if root == None:\n return\n self.KthSmallestElement(root.left, K)\n self.count += 1\n if self.count == K:\n self.ans = root.data\n self.KthSmallestElement(root.right, K)\n if self.ans == 0:\n return -1\n return self.ans", "def KthSmallestElement(root, K):\n count = [0]\n return self.helper(root, K, count)\n\ndef helper(root, K, count):\n if root is None:\n return -1\n result = -1\n leftSubTree = self.helper(root.left, K, count)\n if leftSubTree > 0:\n result = leftSubTree\n count[0] += 1\n if count[0] == K:\n result = root.data\n if result < 0:\n rightSubTree = self.helper(root.right, K, count)\n if rightSubTree > 0:\n result = rightSubTree\n return result", "def KthSmallestElement(root, k):\n stack = []\n while root is not None or len(stack) > 0:\n while root is not None:\n stack.append(root)\n root = root.left\n root = stack.pop()\n k -= 1\n if k == 0:\n return root.data\n root = root.right\n return -1", "def inorder(root, K):\n if root is None:\n return\n self.inorder(root.left, K)\n if K == self.count:\n self.res = root.data\n self.count += 1\n return\n else:\n self.count += 1\n self.inorder(root.right, K)\n\ndef KthSmallestElement(root, K):\n self.count = 1\n self.res = -1\n self.inorder(root, K)\n return self.res", "def inorder(root):\n if root:\n self.inorder(root.left)\n self.res.append(root.data)\n self.inorder(root.right)\n\ndef KthSmallestElement(root, K):\n self.res = []\n self.inorder(root)\n for i in range(len(self.res)):\n if K > len(self.res):\n return -1\n return self.res[K - 1]", "def KthSmallestElement(root, k):\n result = []\n if root is None:\n return -1\n if self.size(root) < k:\n return -1\n self._kthSmallestElement(root, k, result)\n return result[k - 1]\n\ndef _kthSmallestElement(root, k, result):\n if root is None:\n return\n if len(result) == k:\n return\n self._kthSmallestElement(root.left, k, result)\n result.append(root.data)\n self._kthSmallestElement(root.right, k, result)\n\ndef size(root):\n if root is None:\n return 0\n return 1 + self.size(root.left) + self.size(root.right)", "import heapq\n\ndef KthSmallestElement(root, K):\n maxheap = []\n heapq.heapify(maxheap)\n\n def inorder(root):\n if root == None:\n return\n inorder(root.left)\n heapq.heappush(maxheap, -1 * root.data)\n if len(maxheap) > K:\n heapq.heappop(maxheap)\n inorder(root.right)\n inorder(root)\n if len(maxheap) > K or len(maxheap) < K:\n return -1\n return -1 * heapq.heappop(maxheap)", "def KthSmallestElement(root, k):\n s = []\n c = 0\n while s or root:\n while root:\n s.append(root)\n root = root.left\n node = s.pop()\n c += 1\n if c == k:\n return node.data\n root = node.right\n return -1", "def __init__():\n self.counter = 0\n\ndef KthSmallestElement(root, k):\n return self.KthSmallestElementUtil(root, k)\n\ndef KthSmallestElementUtil(root, k):\n if root is None:\n return -1\n left = self.KthSmallestElementUtil(root.left, k)\n if left != -1:\n return left\n self.counter += 1\n if self.counter == k:\n return root.data\n return self.KthSmallestElementUtil(root.right, k)", "global index\nindex = 0\nglobal ans\nans = -1\n\ndef inorder(root, K):\n global index\n global ans\n if not root or ans != -1:\n return\n self.inorder(root.left, K)\n index += 1\n if index == K:\n ans = root.data\n return\n self.inorder(root.right, K)\n\ndef KthSmallestElement(root, K):\n global ans\n global index\n index = 0\n ans = -1\n self.inorder(root, K)\n return ans", "global index\nindex = 0\nglobal ans\nans = -1\nglobal k\n\ndef inorder(root, K):\n global index\n global ans\n if not root or ans != -1:\n return\n self.inorder(root.left, K)\n index += 1\n if index == K:\n ans = root.data\n return\n self.inorder(root.right, K)\n\ndef KthSmallestElement(root, K):\n global k\n k = K\n node = self.doomdoom(root, K)\n if node:\n return node.data\n return -1\n\ndef doomdoom(root, K):\n global k\n if root == None:\n return None\n left = self.doomdoom(root.left, K)\n if left != None:\n return left\n k -= 1\n if k == 0:\n return root\n return self.doomdoom(root.right, K)", "def solve(root):\n if root is None:\n return\n self.solve(root.left)\n self.q.append(root.data)\n self.solve(root.right)\n\ndef KthSmallestElement(root, K):\n self.q = []\n self.solve(root)\n if K > len(self.q):\n return -1\n return self.q[K - 1]", "def KthSmallestElement(root, K):\n i = [0, -1]\n\n def ino(root, K):\n if root:\n ino(root.left, K)\n i[0] = i[0] + 1\n if i[0] == K:\n i[1] = root.data\n return\n return ino(root.right, K)\n ino(root, K)\n return i[1]"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["2\r\n / \\\r\n 1 3\r\nK = 2", "2\r\n / \\\r\n 1 3\r\nK = 5"], "outputs": ["2", "-1"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Binary Search Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Range queries"], "skill_types": ["Data structures", "Range queries"], "url": "https://practice.geeksforgeeks.org/problems/find-k-th-smallest-element-in-bst/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "__init__", "task_id": "TACO_lite/454", "example": [[], []]} +{"requirement": "# How much is the fish! (- Scooter )\nThe ocean is full of colorful fishes. We as programmers want to know the hexadecimal value of these fishes.\n\n## Task\nTake all hexadecimal valid characters (a,b,c,d,e,f) of the given name and XOR them. Return the result as an integer.\n\n## Input\nThe input is always a string, which can contain spaces, upper and lower case letters but no digits. \n\n## Example\n\n`fisHex(\"redlionfish\") -> e,d,f -> XOR -> 12`", "solutions": ["from functools import reduce\nVALID = frozenset('abcdefABCDEF')\n\ndef fishex(s):\n return reduce(lambda b, c: b ^ c, (int(a, 16) for a in s if a in VALID), 0)", "def fishex(name):\n hexdict = {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}\n res = 0\n for c in name.upper():\n if c in hexdict:\n res ^= hexdict[c]\n return res", "def fishex(name):\n hexx = {'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15}\n name = name.lower()\n result = 0\n for i in name:\n if i in hexx:\n result = result ^ hexx[i]\n return result", "from functools import reduce\n\ndef fishex(name):\n hex = ['a', 'b', 'c', 'd', 'e', 'f']\n hexFish = []\n for i in name.lower():\n if i in hex:\n hexFish.append(i)\n hexList = [int(x, 16) for x in hexFish]\n if hexList != []:\n hexValue = hexList[0]\n else:\n return 0\n hexValue = reduce(lambda x, y: x ^ y, hexList)\n return hexValue", "from functools import reduce\nfishex = lambda s: reduce(lambda x, y: x ^ y, [int(i, 16) for i in s if i in 'ABCDEFabcdef'] or [0])", "from functools import reduce\nfrom operator import xor\n\ndef fishex(name):\n return reduce(xor, (int(x, 16) for x in name.lower() if 'a' <= x <= 'f'), 0)", "from functools import reduce\nfrom operator import xor\n\ndef fishex(name):\n s = set('abcdef')\n return reduce(xor, map(lambda c: int(c, 16), (c for c in name.lower() if c in s)), 0)", "def fishex(name):\n return eval('^'.join(['0x' + c for c in name.lower() if c in 'abcdef'])) if name else 0", "from operator import xor\nfrom functools import reduce\n\ndef fishex(name):\n return reduce(xor, (ord(c) - 87 for c in name.lower() if c in 'abcdef'), 0)", "from functools import reduce\n\ndef fishex(name, l={'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15, 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}):\n return reduce(lambda acc, x: acc ^ l.get(x, 0), name, 0)", "fishex = f = lambda s: len(s) and (s[0] in 'abcdefABCDEF' and int(s[0], 16)) ^ f(s[1:])", "from functools import reduce\nfishex = lambda name: reduce(lambda a, b: a ^ b, [int(l, 16) if l in 'abcdef' else 0 for l in name.lower()], 0)"], "starter_code": "def fishex(name):\n", "input_output": {"fn_name": "fisHex", "inputs": [["pufferfish"], ["puffers"], ["balloonfish"], ["blowfish"], ["bubblefish"], ["globefish"], ["swellfish"], ["toadfish"], ["toadies"], ["honey toads"], ["sugar toads"], ["sea squab"], [""], ["Aeneus corydoras"], ["African glass catfish"], ["African lungfish"], ["Aholehole"], ["Airbreathing catfish"], ["Airsac catfish"], ["Alaska blackfish"], ["Albacore"], ["Alewife"], ["Alfonsino"], ["Algae eater"], ["Alligatorfish"], ["Asian carps"], ["Asiatic glassfish"], ["Atka mackerel"], ["Atlantic cod"], ["Atlantic herring"], ["Atlantic salmon"], ["Atlantic saury"], ["Atlantic silverside"], ["Australasian salmon"], ["Australian grayling"], ["Australian herrin"], ["Australian lungfish"], ["Australian prowfish"], ["Ayu"]], "outputs": [[1], [14], [14], [4], [10], [10], [1], [8], [9], [9], [13], [5], [0], [1], [0], [12], [10], [12], [5], [8], [9], [5], [5], [4], [15], [6], [9], [6], [13], [2], [6], [6], [1], [10], [0], [4], [5], [5], [10]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5714eb80e1bf814e53000c06", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "fishex", "task_id": "TACO_lite/384", "example": [[["redlionfish"]], ["12"]]} +{"requirement": "Given an array of integers `a` and integers `t` and `x`, count how many elements in the array you can make equal to `t` by **increasing** / **decreasing** it by `x` (or doing nothing).\n*EASY!*\n\n```python\n# ex 1\n\na = [11, 5, 3]\nt = 7\nx = 2\n\ncount(a, t, x) # => 3\n```\n- you can make 11 equal to 7 by subtracting 2 twice\n- you can make 5 equal to 7 by adding 2\n- you can make 3 equal to 7 by adding 2 twice\n\n```python\n# ex 2\n\na = [-4,6,8]\nt = -7\nx = -3\n\ncount(a, t, x) # => 2\n```\n\n## Constraints\n**-10^(18) <= a[i],t,x <= 10^(18)**\n\n**3 <= |a| <= 10^(4)**", "solutions": ["def count(a, t, x):\n return sum((not (t - v) % x if x else t == v for v in a))", "count = lambda a, t, x: sum((x and (not (e - t) % x) or e - t == 0 for e in a))", "def count(a, t, x):\n return sum(((t - i) % x == 0 for i in a)) if x else sum((i == t for i in a))", "def count(a, t, x):\n if x == 0:\n return a.count(t)\n return sum(((t - e) % x == 0 for e in a))", "def count(A, t, x):\n return sum((a % x == t % x for a in A)) if x else sum((a == t for a in A))", "def count(lst, target, mod):\n if mod == 0:\n return lst.count(target)\n return sum(((n - target) % mod == 0 for n in lst))", "def count(a, t, x):\n return sum((1 for n in a if (n % x == t % x if x else n == t)))", "def count(a, t, x):\n result = 0\n for n in a:\n if n == t or (x != 0 and (n - t) % x == 0):\n result += 1\n return result", "count = lambda a, t, x: sum(((e - t) % x == 0 if x != 0 else e - t == 0 for e in a))"], "starter_code": "def count(a, t, x):\n", "input_output": {"fn_name": "count", "inputs": [[[11, 5, 3], 7, 2], [[-4, 6, 8], -7, -3]], "outputs": [[3], [2]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5d1e1560c193ae0015b601a2", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "count", "task_id": "TACO_lite/391", "example": [[[[11, 5, 3], 7, 2], [[-4, 6, 8], -7, -3]], ["3", "2"]]} +{"requirement": "You are given an array A of integers of length N. You need to calculate factorial of each number. The answer can be very large, so print it modulo 10^{9 }+ 7.\n \nExample 1:\nInput:\nN = 5\nA[] = {0, 1, 2, 3, 4}\nOutput:\n1 1 2 6 24\nExplanation:\nFactorial of 0 is 1, \nfactorial of 1 is 1, factorial of 2 is 2, \nfactorial of 3 is 6 and so on.\nExample 2:\nInput:\nN = 3\nA[] = {5, 6, 3}\nOutput:\n120 720 6\nExplanation:\nFactorial of 5 is 120, \nfactorial of 6 is 720, \nfactorial of 3 is 6.\nYour Task:\nComplete the function factorial() which takes list a and single integer n, as input parameters and returns a list of factorials of the numbers in the list a.\nExpected Time Complexity: O(max(A) + N)\nExpected Auxiliary Space: O(max(A))\nConstraints:\n1 <= N <= 10^{5}\n0 <= A[i] <= 10^{5}", "solutions": ["def factorial(a, n):\n m = 10 ** 9 + 7\n ans = []\n maxi = max(a)\n dp = [1] * (maxi + 1)\n for i in range(2, maxi + 1):\n dp[i] = i * dp[i - 1] % m\n for i in a:\n ans.append(dp[i])\n return ans", "def factorial(a, n):\n result = []\n fact_dict = {}\n maximum = a[0]\n m = 10 ** 9 + 7\n for i in range(1, n):\n maximum = max(maximum, a[i])\n fact_dict[0] = 1\n fact_dict[1] = 1\n for j in range(2, maximum + 1):\n fact_dict[j] = j * fact_dict[j - 1] % m\n for i in range(n):\n result.append(fact_dict[a[i]])\n return result", "import math as m\n\ndef factorial(a, n):\n mod = 1000000007\n fact = [1] * (max(a) + 1)\n for i in range(2, max(a) + 1):\n fact[i] = fact[i - 1] * i % mod\n result = []\n for i in range(n):\n result.append(fact[a[i]])\n return result", "def factorial(a, n):\n ans = [1, 1]\n m = 1000000007\n current = 1\n for i in range(2, max(a) + 1):\n current *= i\n current %= m\n ans.append(current)\n x = []\n for i in a:\n x.append(ans[i])\n return x", "def factorial(a, n):\n maxi = max(a)\n d = dict()\n prod = 1\n for i in range(0, maxi + 1):\n prod = prod * max(i, 1) % (10 ** 9 + 7)\n d[i] = prod\n ans = []\n for num in a:\n ans.append(d[num])\n return ans", "def factorial(a, n):\n m = 10 ** 9 + 7\n arr = [0] * (max(a) + 1)\n arr[0] = 1\n for i in range(1, len(arr)):\n arr[i] = i * arr[i - 1] % m\n for i in range(n):\n a[i] = arr[a[i]]\n return a", "0\n\ndef factorial(a, n):\n m = 10 ** 9 + 7\n ans = []\n maxi = max(a)\n fact = [1, 1]\n f = 1\n for i in range(2, maxi + 1):\n f *= i\n f %= m\n fact.append(f)\n for i in a:\n ans.append(fact[i])\n return ans", "def factorial(a, n):\n mod = int(1000000000.0 + 7)\n m = max(a)\n if m == 0:\n return 1\n dp = [0] * (m + 1)\n dp[0] = 1\n for i in range(1, m + 1):\n dp[i] = dp[i - 1] * i\n dp[i] = dp[i] % mod\n for i in range(n):\n a[i] = dp[a[i]]\n return a", "def factorial(a, n):\n facts = [1]\n maxA = 0\n for i in a:\n maxA = max(maxA, i)\n f = 1\n mod = 10 ** 9 + 7\n for i in range(1, maxA + 1):\n f *= i\n f %= mod\n facts.append(f)\n res = []\n for i in a:\n res.append(facts[i])\n return res", "def factorial(a, n):\n d = {}\n MOD = 1000000007\n for i in range(n):\n d[a[i]] = 1\n m = max(a)\n ans = 1\n for i in range(1, m + 1):\n ans = ans * i % MOD\n if i in d.keys():\n d[i] = ans\n for i in range(n):\n a[i] = d[a[i]]\n return a", "def factorial(a, n):\n m = max(a)\n f = [1]\n for i in range(1, m + 1):\n f.append(f[-1] * i % (10 ** 9 + 7))\n res = []\n for i in a:\n res.append(f[i])\n return res", "def factorial(a, n):\n m = 1000000000.0 + 7\n mx = max(a)\n dp = [0] * (mx + 1)\n dp[0:3] = [1, 1, 2]\n for i in range(3, mx + 1):\n dp[i] = int(i * dp[i - 1] % m)\n res = [0] * n\n for i in range(n):\n res[i] = dp[a[i]]\n return res", "def factorial(a, n):\n maximum = max(a)\n res = []\n dp = [1] * (maximum + 1)\n for i in range(1, maximum + 1):\n dp[i] = i * dp[i - 1] % 1000000007\n for val in a:\n res.append(dp[val])\n return res", "def factorial(a, n):\n a1 = {0: 1}\n a2 = max(a)\n p = 1\n for i in range(1, a2 + 1):\n p *= i\n p %= 1000000007\n a1[i] = p\n d = []\n for i in a:\n d.append(a1[i])\n return d", "def factorial(a, n):\n arr = [1]\n output = []\n for item in a:\n while item > len(arr) - 1:\n arr.append(arr[-1] * len(arr) % (10 ** 9 + 7))\n output.append(arr[item])\n return output", "def factorial(a, n):\n d2 = {}\n mx = -1\n for x in a:\n d2[x] = 1\n mx = max(mx, x)\n d = {0: 1}\n s = 1\n for x in range(1, mx + 1):\n s = s * x % 1000000007\n if d2.get(x):\n d[x] = s\n l = []\n for x in a:\n l.append(d.get(x))\n return l", "def __init__():\n self.dp = dict()\n\ndef factorial(a, n):\n self.dp.clear()\n self.dp = {0: 1}\n m = max(a)\n a_ = {x: 1 for x in a}\n i = 1\n for x in range(1, m + 1):\n i = i * x % (10 ** 9 + 7)\n if a_.get(x) == 1:\n self.dp[x] = i\n return [self.dp[x] for x in a]", "def factorial(a, n):\n res = list()\n maxi = max(a)\n dp = [1] * (maxi + 1)\n mod = 10 ** 9 + 7\n for i in range(1, maxi + 1):\n dp[i] = i * dp[i - 1] % mod\n for val in a:\n res.append(dp[val])\n return res", "def factorial(a, n):\n hash = {0: 1}\n result = []\n max_val = max(a)\n fact = 1\n for i in range(1, max_val + 1):\n fact = fact * i % (pow(10, 9) + 7)\n hash[i] = fact\n for i in a:\n result.append(hash[i])\n return result", "def factorial(a, n):\n x = max(a)\n l = [1, 1]\n for i in range(2, x + 1):\n c = i * l[-1] % 1000000007\n l.append(c)\n for i in range(n):\n a[i] = l[a[i]]\n return a", "def factorial(a, n):\n MAX = 10 ** 5\n fac = [0] * (MAX + 1)\n mod = 10 ** 9 + 7\n fac[0] = 1\n for i in range(1, MAX + 1):\n fac[i] = fac[i - 1] % mod * i % mod\n ans = [0] * n\n for i in range(0, n):\n ans[i] = fac[a[i]]\n return ans", "def factorial(a, n):\n num = max(a)\n m = 1000000007\n fact = [0 for i in range(n)]\n dict_fact = dict()\n dict_fact[0] = 1\n for i in range(1, num + 1):\n dict_fact[i] = i * dict_fact[i - 1] % m\n for i in range(n):\n fact[i] = dict_fact[a[i]]\n return fact", "def factorial(a, n):\n m = max(a)\n mo = 1000000007\n dic = {}\n dic[0] = 1\n for i in range(1, m + 1):\n dic[i] = dic[i - 1] * i % mo\n for i in range(n):\n a[i] = dic[a[i]]\n return a", "def factorial(a, n):\n f = [1, 1]\n ans = 1\n MOD = 10 ** 9 + 7\n for i in range(2, 10 ** 5 + 5):\n ans = ans % MOD * i % MOD % MOD\n f.append(ans)\n ans = []\n for i in range(n):\n a[i] = f[a[i]]\n return a", "def factorial(a, n):\n maximum = -1\n arr = []\n for i in range(n):\n if a[i] > maximum:\n maximum = a[i]\n arr.append(1)\n for i in range(1, maximum + 1, 1):\n arr.append(arr[i - 1] * i % (10 ** 9 + 7))\n for i in range(n):\n a[i] = arr[a[i]]\n return a", "def factorial(a, n):\n maximum = max(a) + 1\n factdp = [1, 1]\n for i in range(2, maximum):\n factdp.append(i * factdp[-1] % 1000000007)\n for i in range(n):\n a[i] = factdp[a[i]]\n return a", "def factorial(a, n):\n fact = [1, 1]\n l = []\n for i in range(2, max(a) + 1):\n k = i * fact[i - 1] % self.m\n fact.append(k)\n for j in a:\n l.append(fact[j] % self.m)\n return l", "fac = [1]\nmod = 1000000007\nfor i in range(1, 100001):\n fac.append(fac[-1] % mod * i % mod)\n\ndef factorial(a, n):\n global fac\n result = []\n for i in a:\n result.append(fac[i])\n return result", "def factorial(a, n):\n N = max(a)\n d = {}\n (d[0], ans) = (1, 1)\n for i in range(1, N + 1):\n ans = ans * i\n ans = ans % 1000000007\n d[i] = ans\n for i in range(n):\n a[i] = d[a[i]]\n return a", "def factorial(a, n):\n maxi = max(a)\n ans = []\n dp = [1] * (maxi + 1)\n for i in range(1, maxi + 1):\n dp[i] = i * dp[i - 1] % 1000000007\n for val in a:\n ans.append(dp[val])\n return ans", "import math as m\n\ndef factorial(a, n):\n mx = max(a)\n fact = [1] * (mx + 1)\n ans = [] * n\n mod = 1000000000.0 + 7\n for i in range(1, mx + 1):\n fact[i] = fact[i - 1] * i % mod\n for i in a:\n ans.append(int(fact[i]))\n return ans", "def factorial(a, n):\n max_range = 10 ** 5\n fact = [0] * (max_range + 1)\n fact[0] = 1\n mod = 10 ** 9 + 7\n for i in range(1, max_range + 1):\n fact[i] = fact[i - 1] % mod * i % mod\n ans = [0] * n\n for i in range(n):\n ans[i] = fact[a[i]]\n return ans", "import math\n\ndef factorial(a, n):\n maximum = max(a)\n dp = [1] * (maximum + 1)\n for i in range(1, maximum + 1):\n dp[i] = i * dp[i - 1] % 1000000007\n return [dp[val] for val in a]", "def factorial(a, n):\n x = max(a)\n dp = [0] * (x + 1)\n dp[0] = 1\n dp[1] = 1\n for i in range(2, x + 1):\n dp[i] = i * dp[i - 1] % (10 ** 9 + 7)\n fans = []\n for i in a:\n fans.append(dp[i])\n return fans", "def __init__():\n self.facts = {}\n self.facts[0] = 1\n self.facts[1] = 1\n self.mod = 1000000007\n\ndef factorial(a, n):\n max_a = max(a)\n for i in range(2, max_a + 1):\n self.facts[i] = self.facts[i - 1] * i % self.mod\n return [self.facts[x] for x in a]", "def factorial(A, N):\n mx = max(A)\n dp = [0] * (mx + 1)\n dp[0] = 1\n dp[1] = 1\n dp[2] = 2\n mod = int(1000000000.0 + 7)\n for i in range(3, mx + 1):\n dp[i] = dp[i - 1] * i\n dp[i] %= mod\n ans = [0] * N\n for i in range(N):\n ans[i] = dp[A[i]]\n return ans", "import math\n\ndef factorial(a, n):\n l = []\n m = max(a)\n arr = [1] * (m + 1)\n for i in range(1, m + 1):\n arr[i] = i * arr[i - 1] % 1000000007\n for j in a:\n l.append(arr[j])\n return l", "def fact(num):\n f = 1\n for i in range(1, num + 1):\n f *= i\n return f\n\ndef factorial(a, n):\n fact = {}\n fact[0] = 1\n MAX = pow(10, 5)\n mod = pow(10, 9) + 7\n for i in range(1, MAX + 1):\n fact[i] = i * fact[i - 1] % mod\n for (i, ele) in enumerate(a):\n a[i] = fact[ele]\n return a", "def factorial(a, n):\n ans = [0] * n\n max = 0\n for i in range(n):\n if a[i] > max:\n max = a[i]\n size = max + 1\n fact = [None] * size\n fact[0] = 1\n for i in range(1, size):\n fact[i] = i * fact[i - 1] % 1000000007\n for i in range(n):\n ans[i] = fact[a[i]]\n return ans", "def factorial(a, n):\n maxEle = max(a)\n res = []\n fact = [1] * (maxEle + 1)\n for i in range(2, maxEle + 1):\n fact[i] = fact[i - 1] * i % 1000000007\n for i in a:\n res.append(fact[i])\n return res", "def factorial(a, n):\n maxm = max(a)\n t = [1] * (maxm + 1)\n res = []\n for i in range(1, maxm + 1):\n t[i] = i * t[i - 1] % (10 ** 9 + 7)\n for val in a:\n res.append(t[val])\n return res", "def factorial(a, n):\n f = [0] * 100002\n f[0] = 1\n f[1] = 1\n arr = []\n j = 2\n for i in a:\n if f[i] != 0:\n arr.append(f[i])\n else:\n while j <= i:\n f[j] = f[j - 1] * j % (10 ** 9 + 7)\n j = j + 1\n arr.append(f[i])\n return arr", "def factorial(a, n):\n m = {0: 1}\n p = 1\n g = max(a)\n for i in range(1, g + 1):\n p = p * i\n p = p % 1000000007\n m[i] = p\n b = []\n for i in a:\n b.append(m[i])\n return b"], "starter_code": "def factorial(a, n):\n", "input_output": {"inputs": ["N = 5\r\nA[] = {0, 1, 2, 3, 4}", "N = 3\r\nA[] = {5, 6, 3}"], "outputs": ["1 1 2 6 24", "120 720 6"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Arrays", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/large-factorial4721/1", "Expected Auxiliary Space": "O(max(A))", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(max(A) + N)", "entry_point": "factorial", "task_id": "TACO_lite/363", "example": [[], []]} +{"requirement": "Given an array of N integers and Q queries of indices, print the number of next greater elements(NGEs) to the right of the given index element. \nExample:\nInput: arr = [3, 4, 2, 7, 5, 8, 10, 6]\n queries = 2\n indices = [0, 5]\nOutput: 6, 1\nExplanation: \nThe next greater elements to the right of 3(index 0)\nare 4,7,5,8,10,6. \nThe next greater elements to the right of 8(index 5)\nis only 10.\nYour Task:\nYou don't need to read or print anything. Your task is to complete the function count_NGEs() which takes N, arr, queries and indices as the input parameter and returns a list NGEs[] where NGEs[i] stores the count of elements strictly greater than the current element (arr[indices[i]]) to the right of indices[i].\nExpected Time Complexity: O(N * queries).\nExpected Auxiliary Space: O(queries).\nConstraints:\n1 <= N <= 10^{4}\n1 <= arr[i] <= 10^{5}\n1 <= queries <= 100\n0 <= indices[i] <= N - 1", "solutions": ["def count_nges(N, arr, queries, indices):\n\n def nge(ind, arr, N, key):\n c = 0\n for i in range(ind, N):\n if arr[i] > key:\n c += 1\n return c\n st = []\n for i in indices:\n st.append(nge(i, arr, N, arr[i]))\n return st", "def count_nges(N, arr, queries, indices):\n\n def nge(ind, arr, N, key):\n cnt = 0\n for i in range(ind, N):\n if arr[i] > key:\n cnt += 1\n return cnt\n ans = []\n for i in indices:\n ans.append(nge(i, arr, N, arr[i]))\n return ans", "def count_nges(N, nums, queries, indices):\n\n def findNextGreaterNums(index):\n (curr, count) = (nums[index], 0)\n for i in range(index + 1, N):\n if nums[i] > curr:\n count += 1\n return count\n result = []\n for index in indices:\n result.append(findNextGreaterNums(index))\n return result", "def count_nges(N, arr, queries, indices):\n l = []\n n = len(arr)\n for i in range(queries - 1, -1, -1):\n c = 0\n for j in range(n - 1, indices[i], -1):\n if arr[indices[i]] < arr[j]:\n c = c + 1\n l.append(c)\n l.reverse()\n return l", "def count_nges(N, arr, queries, indices):\n res = [0 for _ in range(queries)]\n for i in range(queries):\n cnt = 0\n k = indices[i]\n for j in range(k + 1, N):\n if arr[k] < arr[j]:\n cnt += 1\n res[i] = cnt\n return res", "def count_nges(N, arr, queries, indices):\n list = []\n for x in range(len(indices)):\n max = arr[indices[x]]\n sum = 0\n for y in range(indices[x] + 1, N):\n if max < arr[y]:\n sum += 1\n list.append(sum)\n return list", "def count_nges(N, arr, queries, indices):\n great_arr = []\n for query in indices:\n great = 0\n for i in range(query + 1, N):\n if arr[i] > arr[query]:\n great += 1\n great_arr.append(great)\n return great_arr", "def count_nges(N, arr, queries, indices):\n res = []\n for i in indices:\n x = arr[i]\n count = 0\n for j in range(i + 1, N):\n if x < arr[j]:\n count += 1\n res.append(count)\n return res", "def count_nges(N, arr, queries, indices):\n ans = []\n i = 0\n while i < queries:\n j = indices[i]\n temp = arr[indices[i]]\n count = 0\n while j < N:\n if arr[j] > temp:\n count += 1\n j += 1\n i += 1\n ans.append(count)\n return ans", "def count_nges(N, arr, queries, indices):\n NGEs = []\n for index in indices:\n count = 0\n num = arr[index]\n for i in range(index + 1, len(arr)):\n if arr[i] > num:\n count += 1\n NGEs.append(count)\n return NGEs", "def count_nges(N, arr, queries, indices):\n for j in range(queries):\n t = indices[j]\n k = arr[t]\n c = 0\n for i in range(t + 1, N):\n if arr[i] > k:\n c += 1\n indices[j] = c\n return indices", "def count_nges(N, arr, queries, indices):\n a = []\n for i in range(queries):\n t = arr[indices[i]]\n count = 0\n for j in range(indices[i] + 1, N):\n if arr[j] > t:\n count += 1\n a.append(count)\n return a", "from collections import deque\n\ndef __init__():\n self.count = 0\n\ndef count_nges(N, arr, queries, indices):\n answer = []\n for i in range(queries):\n count = 0\n for j in range(indices[i] + 1, N):\n if arr[j] > arr[indices[i]]:\n count += 1\n answer.append(count)\n return answer", "def count_nges(N, arr, queries, indices):\n result = []\n for i in range(queries):\n count = 0\n for j in range(indices[i] + 1, len(arr)):\n if arr[j] > arr[indices[i]]:\n count += 1\n result.append(count)\n return result", "def count_nges(n, arr, queries, indices):\n result = []\n for index in indices:\n count = 0\n for i in range(index + 1, n):\n if arr[i] > arr[index]:\n count += 1\n result.append(count)\n return result", "def count_nges(N, arr, queries, indices):\n nxges = []\n for index in indices:\n nxg = 0\n for i in range(index + 1, N):\n if arr[index] < arr[i]:\n nxg += 1\n nxges.append(nxg)\n return nxges", "def count_nges(N, arr, queries, indices):\n ans = []\n for q in range(queries):\n ind = indices[q]\n count = 0\n for i in range(ind, N):\n if arr[ind] < arr[i]:\n count += 1\n ans.append(count)\n return ans", "def count_nges(N, arr, queries, indices):\n ans = []\n for indx in indices:\n cnt = 0\n for i in range(indx, N):\n cnt += arr[i] > arr[indx]\n ans.append(cnt)\n return ans", "def count_nges(n, arr, queries, indices):\n res = []\n for ind in indices:\n curr = arr[ind]\n c = 0\n for i in range(ind + 1, n):\n if curr < arr[i]:\n c += 1\n res.append(c)\n return res", "def count_nges(N, arr, queries, indices):\n ans = [0 for j in range(queries)]\n indx = 0\n while queries != 0:\n idx = indices.pop(0)\n cnt = 0\n for j in range(idx + 1, N):\n if arr[j] > arr[idx]:\n cnt += 1\n ans[indx] = cnt\n indx += 1\n queries -= 1\n return ans", "def count_nges(N, arr, queries, indices):\n ans = []\n for i in range(queries):\n index = indices[i]\n count = 0\n for j in range(index + 1, N):\n if arr[j] > arr[index]:\n count += 1\n ans.append(count)\n return ans", "def count_nges(n, arr, queries, indices):\n ans = []\n for q in indices:\n el = arr[q]\n cnt = 0\n for i in range(q, n):\n if arr[i] > el:\n cnt += 1\n ans.append(cnt)\n return ans", "def count_nges(N, arr, queries, indices):\n ans = []\n for i in indices:\n num = arr[i]\n count = 0\n for x in arr[i:]:\n if x > num:\n count += 1\n ans.append(count)\n return ans", "def count_nges(N, arr, queries, indices):\n res = []\n for i in range(queries):\n k = indices[i]\n count = 0\n for i in range(k + 1, len(arr)):\n if arr[i] > arr[k]:\n count += 1\n res.append(count)\n return res", "def count_nges(N, arr, M, indices):\n count = [0 for _ in range(M)]\n for i in range(M):\n for j in range(indices[i], N):\n if arr[j] > arr[indices[i]]:\n count[i] += 1\n return count", "def count_nges(N, arr, queries, indices):\n res = [0 for _ in range(queries)]\n for i in range(queries):\n idx = indices[i]\n count = 0\n for j in range(idx, N):\n if arr[j] > arr[idx]:\n count += 1\n res[i] = count\n return res", "def count_nges(n, arr, queries, indices):\n res = []\n for i in range(len(indices)):\n index = indices[i]\n count = 0\n for j in range(index, len(arr)):\n if arr[index] < arr[j]:\n count += 1\n res.append(count)\n return res", "def count_nges(N, arr, queries, indices):\n list1 = []\n for index in indices:\n count = 0\n val = arr[index]\n for i in range(index + 1, N):\n if arr[i] > val:\n count += 1\n else:\n continue\n list1.append(count)\n return list1", "def count_nges(N, arr, queries, indices):\n ls = []\n n = len(arr)\n for i in indices:\n cnt = 0\n for j in range(i + 1, n):\n if arr[j] > arr[i]:\n cnt += 1\n ls.append(cnt)\n return ls", "def count_nges(N, arr, queries, indices):\n count = []\n for i in indices:\n c = 0\n for e in range(i, N):\n if arr[i] < arr[e]:\n c = c + 1\n count.append(c)\n return count", "def count_nges(N, arr, q, ind):\n k = []\n for i in range(q):\n count = 0\n if ind[i] != N - 1:\n for j in range(ind[i] + 1, N):\n if arr[j] > arr[ind[i]]:\n count += 1\n k.append(count)\n return k", "def count_nges(n, arr, q, ind):\n ans = []\n for i in range(q):\n count = 0\n for j in range(ind[i] + 1, n):\n if arr[j] > arr[ind[i]]:\n count += 1\n ans.append(count)\n return ans", "def count_nges(N, arr, queries, indices):\n ans = []\n for (z, point) in enumerate(indices):\n temp = 0\n for i in range(point + 1, N):\n if arr[i] > arr[point]:\n temp += 1\n ans.append(temp)\n return ans", "def count_nges(N, arr, queries, indices):\n res = []\n for ind in indices:\n count = 0\n cur = arr[ind]\n for i in range(ind + 1, N):\n if arr[i] > cur:\n count += 1\n res.append(count)\n return res", "def count_nges(N, arr, queries, indices):\n ans = []\n for ind in indices:\n cnt = 0\n for i in range(N):\n if ind < i and arr[i] > arr[ind]:\n cnt += 1\n ans += [cnt]\n return ans", "def count_nges(N, arr, queries, indices):\n count_Arr = [-1] * queries\n for i in range(0, queries):\n count = 0\n for j in range(indices[i] + 1, len(arr)):\n if arr[indices[i]] < arr[j]:\n count += 1\n else:\n j += 1\n count_Arr[i] = count\n return count_Arr", "def count_nges(N, arr, queries, indices):\n l = []\n c = 0\n for i in indices:\n ind = i\n for j in arr[ind:]:\n if j > arr[ind]:\n c += 1\n l.append(c)\n c = 0\n return l", "def count(arr, B):\n ct = 0\n n = len(arr)\n for i in range(B, n):\n if arr[i] > arr[B]:\n ct += 1\n return ct\n\ndef count_nges(N, arr, queries, indices):\n n = len(indices)\n ans = [0] * n\n for i in range(n):\n ans[i] = count(arr, indices[i])\n return ans", "def count_nges(N, arr, queries, indices):\n res = []\n stack = []\n for i in range(queries):\n ind = indices[i]\n count = 0\n for j in range(ind + 1, len(arr)):\n if arr[j] > arr[ind]:\n count += 1\n res.append(count)\n return res", "def count_nges(N, arr, queries, indices):\n count = 0\n nge = []\n for g in range(queries):\n if N == 1:\n return [0] * queries\n for h in range(N - 1, indices[g], -1):\n if arr[h] > arr[indices[g]]:\n count += 1\n nge.append(count)\n count = 0\n return nge", "def count_nges(N, arr, queries, indices):\n ans = []\n for i in range(len(indices)):\n if indices[i] == len(arr) - 1:\n ans.append(0)\n else:\n ans.append(self.count_nge(indices[i], arr))\n return ans\n\ndef count_nge(index, arr):\n count = 0\n for i in range(index + 1, len(arr)):\n if arr[i] > arr[index]:\n count += 1\n return count", "def count_nges(N, arr, queries, indices):\n res = []\n for i in indices:\n ans = []\n for j in range(i, N):\n if arr[j] > arr[i]:\n ans.append(arr[j])\n res.append(len(ans))\n return res", "def count_nges(n, a, q, indices):\n ngr = []\n for idx in indices:\n cnt = 0\n for i in range(idx + 1, n):\n if a[i] > a[idx]:\n cnt += 1\n ngr.append(cnt)\n return ngr"], "starter_code": "def count_nges(N, arr, queries, indices):\n", "input_output": {"inputs": ["arr = [3, 4, 2, 7, 5, 8, 10, 6]\n queries = 2\n indices = [0, 5]"], "outputs": ["6, 1"]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/number-of-nges-to-the-right/1", "Expected Auxiliary Space": "O(queries).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N * queries).", "entry_point": "count_nges", "task_id": "TACO_lite/433", "example": [[[[3, 4, 2, 7, 5, 8, 10, 6], 2, [0, 5]]], [null]]} +{"requirement": "In this kata the function returns an array/list of numbers without its last element. The function is already written for you and the basic tests pass, but random tests fail. Your task is to figure out why and fix it.\n\nGood luck!\n\nHint: watch out for side effects.\n\n~~~if:javascript\nSome good reading: [MDN Docs about arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)\n~~~\n~~~if:python\nSome good reading: [Python Lists](http://www.compciv.org/guides/python/fundamentals/lists-mutability/)\n~~~", "solutions": ["def without_last(lst):\n return lst[:-1]", "def without_last(lst):\n lst_copy = list(lst)\n lst_copy.pop()\n return lst_copy", "def without_last(lst):\n l = lst[:]\n l.pop()\n return l", "def without_last(lst):\n if len(lst) < 1:\n return lst\n return lst[:-1]", "from operator import itemgetter\nwithout_last = itemgetter(slice(0, -1))", "def without_last(lst):\n new = lst[:]\n new.pop()\n return new", "def without_last(lst):\n x = lst[:-1]\n return x"], "starter_code": "def without_last(lst):\n", "input_output": {"fn_name": "without_last", "inputs": [[[1, 2, 3, 4, 5]], [[9, 7, 6, 9]]], "outputs": [[[1, 2, 3, 4]], [[9, 7, 6]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Refactoring"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5a4ff3c5fd56cbaf9800003e", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "without_last", "task_id": "TACO_lite/441", "example": [[[[1, 2, 3, 4]], [[5, 10, 15]]], ["[1, 2, 3]", "[5, 10]"]]} +{"requirement": "Given a non-negative number, return the next bigger polydivisible number, or an empty value like `null` or `Nothing`.\n\nA number is polydivisible if its first digit is cleanly divisible by `1`, its first two digits by `2`, its first three by `3`, and so on. There are finitely many polydivisible numbers.", "solutions": ["(d, polydivisible, arr) = (1, [], list(range(1, 10)))\nwhile arr:\n d += 1\n polydivisible.extend(arr)\n arr = [n for x in arr for n in range(-(-x * 10 // d) * d, (x + 1) * 10, d)]\n\ndef next_num(n):\n from bisect import bisect\n idx = bisect(polydivisible, n)\n if idx < len(polydivisible):\n return polydivisible[idx]", "def next_num(n):\n\n def dfs(m=0, i=0, fromZ=0):\n if m > n:\n yield m\n elif i < len(s):\n m *= 10\n for d in range(0 if fromZ else s[i], 10):\n if not (m + d) % (i + 1):\n yield from dfs(m + d, i + 1, fromZ or d > s[i])\n s = list(map(int, str(n)))\n ret = next(dfs(), None)\n if ret is None:\n s = [1] + [0] * len(s)\n ret = next(dfs(), None)\n return ret", "import requests\nfrom bisect import bisect\nMAGIC = [int(x) for x in requests.get('https://oeis.org/b144688.txt').text.split()[1::2]]\n\ndef next_num(n):\n return MAGIC[bisect(MAGIC, n)] if n < MAGIC[-1] else None", "def f(xs, i, changed):\n if i and int(''.join(map(str, xs[:i]))) % i:\n return\n if i == len(xs):\n return int(''.join(map(str, xs)))\n prev = xs[i]\n for x in range(0 if changed else prev, 10):\n xs[i] = x\n res = f(xs, i + 1, changed or x != prev)\n if res:\n return res\n xs[i] = prev\n\ndef next_num(n):\n res = f(list(map(int, str(n + 1))), 0, False)\n if res:\n return res\n s = '1' + '0' * len(str(n))\n return f(list(map(int, s)), 0, False)", "def next_num(n):\n mpl = 25\n lpn = 3608528850368400786036725\n if n >= lpn:\n return None\n nl = len(str(n))\n extend = {}\n for i in range(1, mpl + 2):\n if i % 10 == 0:\n extend[i] = {'0'}\n elif i % 5 == 0:\n extend[i] = {'0', '5'}\n elif i % 2 == 0:\n extend[i] = {'0', '2', '4', '6', '8'}\n else:\n extend[i] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}\n d = {1: {'1', '2', '3', '4', '5', '6', '7', '8', '9'}}\n for l in range(2, 2 + nl):\n d[l] = {p + i for i in extend[l] for p in d[l - 1] if int(p + i) % l == 0}\n d[1].add('0')\n if n >= max(map(int, d[nl])):\n return min(map(int, d[nl + 1]))\n else:\n for i in sorted(map(int, d[nl])):\n if i > n:\n return i", "def polydivisible(n):\n len_n = len(str(n))\n for i in range(1, len_n + 1):\n if n // 10 ** (len_n - i) % i != 0:\n return i\n else:\n return True\n\ndef next_num(n):\n n += 1\n while n <= 3608528850368400786036725:\n pr = polydivisible(n)\n if pr == True:\n return n\n else:\n len_n = len(str(n))\n num = 10 ** (len_n - pr)\n n = (n // num + 1) * num", "from bisect import bisect\nrec = lambda L, i: L and L + rec([y for x in L for y in range(10 * x, 10 * (x + 1)) if not y % i], i + 1)\npolys = rec(list(range(1, 10)), 2)\n\ndef next_num(n):\n try:\n return polys[bisect(polys, n)]\n except IndexError:\n return", "def find_polydivisible(digits_limit):\n numbers = []\n previous = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n digits = 2\n poly_for_digits = []\n while previous and digits <= digits_limit:\n numbers += previous\n for p in previous:\n for i in range(10):\n number = p * 10 + i\n if number % digits == 0:\n poly_for_digits.append(number)\n previous = poly_for_digits[:]\n poly_for_digits = []\n digits += 1\n return numbers\npolydivisibles = find_polydivisible(26)\n\ndef next_num(n):\n return next((p for p in polydivisibles if p >= n + 1), None)", "def next_num(n):\n n += 1\n while n <= 3608528850368400786036725:\n pr = ifpol(n)\n if pr == True:\n return n\n else:\n s = len(str(n))\n num = 10 ** (s - pr)\n n = (n // num + 1) * num\n\ndef ifpol(n):\n s = len(str(n))\n for i in range(1, s + 1):\n if n // 10 ** (s - i) % i != 0:\n return i\n return True", "def next_num(n):\n number = str(n + 1)\n\n def isNumPoly(number):\n for i in range(1, len(number) + 1):\n if not int(number[0:i]) % i == 0:\n return i\n return 0\n while int(number) < 3610000000000000000000000:\n where = isNumPoly(number)\n if where == 0:\n return int(number)\n badPiece = number[0:where]\n replacement = str(int(badPiece) + (where - int(badPiece) % where))\n number = replacement + '0' * len(number[where:])\n return None"], "starter_code": "def next_num(n):\n", "input_output": {"fn_name": "next_num", "inputs": [[0], [10], [11], [1234], [123220], [998], [999], [1234567890], [3608528850368400786036724], [3608528850368400786036725]], "outputs": [[1], [12], [12], [1236], [123252], [1020], [1020], [1236004020], [3608528850368400786036725], [null]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5e4a1a43698ef0002d2a1f73", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "next_num", "task_id": "TACO_lite/455", "example": [[[12], [123], [1]], [14, 126, 2]]} +{"requirement": "We have an array of unique elements. A special kind of permutation is the one that has all of its elements in a different position than the original.\n\nLet's see how many of these permutations may be generated from an array of four elements. We put the original array with square brackets and the wanted permutations with parentheses. \n```\narr = [1, 2, 3, 4]\n (2, 1, 4, 3)\n (2, 3, 4, 1)\n (2, 4, 1, 3)\n (3, 1, 4, 2)\n (3, 4, 1, 2)\n (3, 4, 2, 1)\n (4, 1, 2, 3)\n (4, 3, 1, 2)\n (4, 3, 2, 1)\n _____________\nA total of 9 permutations with all their elements in different positions than arr\n```\n\nThe task for this kata would be to create a code to count all these permutations for an array of certain length.\n\nFeatures of the random tests:\n```\nl = length of the array\n10 \u2264 l \u2264 5000\n```\n\nSee the example tests.\n\nEnjoy it!", "solutions": ["def all_permuted(n):\n (a, b) = (0, 1)\n for i in range(1, n):\n (a, b) = (b, (i + 1) * (a + b))\n return a", "from itertools import islice\n\ndef A000166():\n (a, b, n) = (1, 0, 1)\n while True:\n yield a\n (a, b) = (b, n * (a + b))\n n += 1\nall_permuted = dict(enumerate(islice(A000166(), 5000))).get", "subfactorial = [1, 0]\nfor n in range(1, 10 ** 4):\n subfactorial.append(n * (subfactorial[-1] + subfactorial[-2]))\nall_permuted = subfactorial.__getitem__", "def f(n):\n if n == 0:\n return 1\n else:\n return n * f(n - 1) + (1 if n % 2 == 0 else -1)\n\ndef all_permuted(array_length):\n return f(array_length)", "import math\n\ndef all_permuted(n):\n return n * all_permuted(n - 1) + (-1) ** n if n > 2 else n - 1", "from functools import lru_cache\n\ndef all_permuted(n):\n if n == 0:\n return 1\n if n == 1:\n return 0\n return (n - 1) * (all_permuted(n - 1) + all_permuted(n - 2))", "M = [1, 0]\nfor V in range(1, 9487):\n M.append(V * (M[V] + M[V - 1]))\nall_permuted = lambda Q: M[Q]", "def all_permuted(array_length):\n a = [1, 0]\n for x in range(2, array_length + 1):\n (a[0], a[1]) = (a[1], (x - 1) * (a[1] + a[0]))\n return a[1]", "all_permuted = a = lambda n: (0, 0, 1)[n] if n < 3 else n * a(n - 1) + (-1) ** n", "import math\n\ndef all_permuted(n):\n if n == 0:\n return 1\n return n * all_permuted(n - 1) + (-1) ** n"], "starter_code": "def all_permuted(n):\n", "input_output": {"fn_name": "all_permuted", "inputs": [[1], [4], [30]], "outputs": [[0], [9], [97581073836835777732377428235481]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Machine Learning", "Combinatorics", "Number Theory", "Performance"], "name": null, "source": "codewars", "tags": ["Number theory", "Combinatorics", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5b997b066c77d521880001bd", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "all_permuted", "task_id": "TACO_lite/442", "example": [[[[1, 2, 3, 4]]], [null]]} +{"requirement": "n\u00a0passengers board an airplane with exactly\u00a0n\u00a0seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of passengers will:\n\nTake their own seat if it is still available,\u00a0\nPick other seats randomly when they find their seat occupied\u00a0\n\nWhat is the probability that the n-th person can get his own seat?\n\u00a0\nExample 1:\nInput: n = 1\nOutput: 1.00000\nExplanation: The first person can only get the first seat.\nExample 2:\nInput: n = 2\nOutput: 0.50000\nExplanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).\n\n\u00a0\nConstraints:\n\n1 <= n <= 10^5", "solutions": ["def nthpersongetsnthseat(n: int) -> float:\n return 1 / min(n, 2.0)", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return float(1)\n return float(0.5)", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1.0\n if n == 2:\n return 0.5\n return 0.5\n if n == 3:\n return 1 / 3 * 1 + 1 / 3 * 1 / 2 + 1 / 3 * 0\n if n == 4:\n return 1 / 4 * 1 + 1 / 4 * (1 / 3 * 1 + 1 / 3 * 1 / 2 + 1 / 3 * 0) + 1 / 4 * (1 / 3 * 1 + 1 / 3 * 1 + 1 / 3 * 0) + 1 / 4 * 0\n return 1 / n * 1 + (n - 2) / n * self.nthpersongetsnthseat(n - 2) + 1 / n * 0", "import numpy as np\n\ndef nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n return 1 / 2", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n s = 0\n for i in range(1, n - 1):\n s += 0.5 / n\n return 1 / n + s", "def nthpersongetsnthseat(n: int) -> float:\n res = 1.0\n cur = 1.0\n for i in range(2, n + 1):\n res = 1 / i * cur\n cur += res\n return res", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n if n == 2:\n return 0.5\n dp = [0] * n\n dp[0] = 1 / n\n for i in range(1, n - 1):\n dp[i] = 0.5 / n\n return sum(dp)", "def nthpersongetsnthseat(n: int) -> float:\n i = 0\n if n == 1:\n return 1\n notCorrect = 1 / n\n for i in range(1, n - 1):\n notCorrect *= 1.0 + 1.0 / (n - i)\n return 1 - notCorrect", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1.0\n sum_results = 0.0\n for i in range(2, n + 1):\n p = 1 / i * (1 + sum_results)\n sum_results += p\n return p", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n return 1 / 2", "def nthpersongetsnthseat(n: int) -> float:\n mem = {}\n mem[1] = 1.0\n mem[2] = 0.5\n for i in range(3, n + 1):\n mem[i] = mem[i - 1]\n return mem[n]", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1.0\n if n == 2:\n return 0.5\n dp = [1.0, 0.5]\n acc = 1.5\n for i in range(3, n + 1):\n dp.append(acc / i)\n acc += dp[-1]\n return dp[-1]", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n if n == 2:\n return 0.5\n result = 1.0\n curr = 1.0\n for i in range(2, n + 1):\n result = 1 / i * curr\n curr += result\n return result", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n good = 0\n left = n\n uncenrtain = 1\n while left >= 2:\n good += uncenrtain / left\n uncenrtain = uncenrtain * (left - 2) / left\n left -= 1\n return good", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n else:\n dp = [0 for _ in range(n + 1)]\n dp[n] = 1 / n\n for i in range(n - 1, 1, -1):\n dp[i] = dp[i + 1] / i + dp[i + 1]\n return dp[2]", "def nthpersongetsnthseat(n: int) -> float:\n p = [None, 1.0, 0.5]\n for i in range(2, n):\n prob = (i * p[i] + p[i]) / (i + 1)\n p.append(prob)\n return p[n]", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n P = [None] * (n + 1)\n P[2] = 1 / n\n for i in range(3, n + 1):\n P[i] = P[i - 1] * (1 + 1 / (n - i + 2))\n return P[n]", "def nthpersongetsnthseat(n: int) -> float:\n D = [0] * n\n D[0] = 1.0\n for i in range(1, n):\n D[i] = 1 / (i + 1) + (i - 1) / (i + 1) * D[i - 1]\n return D[-1]", "import numpy as np\n\ndef nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n currentsum = 0\n else:\n currentsum = 1 / n\n for i in range(2, n):\n currentsum = currentsum + currentsum / (n - i + 1)\n return 1 - currentsum", "def nthpersongetsnthseat(n: int) -> float:\n if n == 1:\n return 1\n pick = [1] + [0] * (n - 2) + [1]\n prob = 0\n for i in range(n - 2, 0, -1):\n left = n - i\n pick[i] = 1 / left + (left - 2) / left * pick[i + 1]\n prob += pick[i]\n return (prob + 1) / n"], "starter_code": "def nthpersongetsnthseat(n: int) -> float:\n", "input_output": {"fn_name": "nthPersonGetsNthSeat", "inputs": [[1]], "outputs": [1.0]}, "difficulty": "MEDIUM", "raw_tags": ["Math", "Dynamic Programming", "Brainteaser", "Probability and Statistics"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Mathematics", "Probability"], "skill_types": ["Dynamic programming"], "url": "https://leetcode.com/problems/airplane-seat-assignment-probability/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "nthpersongetsnthseat", "task_id": "TACO_lite/475", "example": [[[1], [2]], ["1.0", "0.5"]]} +{"requirement": "Given two strings, the first being a random string and the second being the same as the first, but with three added characters somewhere in the string (three same characters),\n\nWrite a function that returns the added character\n\n### E.g\n\n```\nstring1 = \"hello\"\nstring2 = \"aaahello\"\n\n// => 'a'\n```\n\nThe above is just an example; the characters could be anywhere in the string and string2 is actually **shuffled**.\n\n### Another example\n\n```\nstring1 = \"abcde\"\nstring2 = \"2db2a2ec\"\n\n// => '2'\n```\n\nNote that the added character could also exist in the original string\n\n\n```\nstring1 = \"aabbcc\"\nstring2 = \"aacccbbcc\"\n\n// => 'c'\n```\n\nYou can assume that string2 will aways be larger than string1, and there will always be three added characters in string2.\n\n```if:c\nWrite the function `added_char()` that takes two strings and return the added character as described above.\n```\n\n```if:javascript\nWrite the function `addedChar()` that takes two strings and return the added character as described above.\n```", "solutions": ["from collections import Counter\n\ndef added_char(s1, s2):\n return next((Counter(s2) - Counter(s1)).elements())", "def added_char(s1, s2):\n for i in s2:\n if s1.count(i) != s2.count(i):\n return i", "from functools import reduce\nfrom operator import xor\n\ndef added_char(s1, s2):\n return chr(reduce(xor, map(ord, s1), 0) ^ reduce(xor, map(ord, s2), 0))", "from collections import Counter\n\ndef added_char(s1, s2):\n return list(Counter(s2) - Counter(s1))[0]", "from collections import Counter\n\ndef added_char(s1, s2):\n return (Counter(s2) - Counter(s1)).popitem()[0]", "def added_char(s1, s2):\n s2 = list(s2)\n [s2.remove(i) for i in s1]\n return s2[0]", "from collections import Counter\n\ndef added_char(*args):\n (c1, c2) = map(Counter, args)\n return (c2 - c1).popitem()[0]", "added_char = lambda s1, s2: next((i for i in s2 if s1.count(i) != s2.count(i)))", "def added_char(s1, s2):\n return chr(int((sum((ord(x) for x in s2)) - sum((ord(x) for x in s1))) / 3))"], "starter_code": "def added_char(s1, s2):\n", "input_output": {"fn_name": "added_char", "inputs": [["hello", "checlclo"], ["aabbcc", "aacccbbcc"], ["abcde", "2db2a2ec"]], "outputs": [["c"], ["c"], ["2"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Logic"], "name": null, "source": "codewars", "tags": ["String algorithms"], "skill_types": [], "url": "https://www.codewars.com/kata/5971b219d5db74843a000052", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "added_char", "task_id": "TACO_lite/468", "example": [[["hello", "aaahello"], ["abcde", "2db2a2ec"], ["aabbcc", "aacccbbcc"]], ["a", "2", "c"]]} +{"requirement": "Given an infinite supply of each denomination of Indian currency { 1, 2, 5, 10, 20, 50, 100, 200, 500, 2000 } and a target value N.\nFind the minimum number of coins and/or notes needed to make the change for Rs N. You must return the list containing the value of coins required. \nExample 1:\nInput: N = 43\nOutput: 20 20 2 1\nExplaination: \nMinimum number of coins and notes needed \nto make 43. \nExample 2:\nInput: N = 1000\nOutput: 500 500\nExplaination: minimum possible notes\nis 2 notes of 500.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function minPartition() which takes the value N as input parameter and returns a list of integers in decreasing order.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 \u2264 N \u2264 10^{6}", "solutions": ["def minpartition(n):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n l = []\n i = len(coins) - 1\n while n != 0 and i >= 0:\n if coins[i] > n:\n i -= 1\n else:\n n -= coins[i]\n l.append(coins[i])\n return l", "def minpartition(N):\n currency = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n i = len(currency) - 1\n res = []\n while i >= 0 and N != 0:\n if N >= currency[i]:\n quotient = N // currency[i]\n res += [currency[i]] * quotient\n N -= currency[i] * quotient\n i -= 1\n return res", "def minpartition(N):\n arr = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n count = []\n while N != 0:\n for coin in arr:\n if coin <= N:\n n = N // coin\n N = N - N // coin * coin\n for i in range(n):\n count.append(coin)\n return count", "def minpartition(N):\n set_list = [None] * N\n coins = {1, 2, 5, 10, 20, 50, 100, 200, 500, 2000}\n\n def find_min_set(coins, set_list, n):\n min_set = []\n min_set_len = float('Inf')\n for coin in coins:\n if coin == n:\n cur_set = [coin]\n cur_set_len = 1\n elif coin < n:\n diff = n - coin\n cur_set = set_list[diff - 1] + [coin]\n cur_set_len = len(set_list[diff - 1]) + 1\n else:\n continue\n if cur_set_len < min_set_len:\n min_set_len = cur_set_len\n min_set = cur_set\n min_set.sort(reverse=True)\n set_list[n - 1] = min_set\n for i in range(N):\n find_min_set(coins, set_list, i + 1)\n return set_list[N - 1]", "def minpartition(N):\n money = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n result = []\n for i in range(9, -1, -1):\n result += [money[i]] * (N // money[i])\n N = N % money[i]\n if N == 0:\n break\n return result", "def minpartition(N):\n l = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n i = 0\n a = []\n while i < len(l):\n if l[i] > N:\n i += 1\n else:\n a.append(l[i])\n N -= l[i]\n return a", "def minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n res = []\n for i in range(len(coins) - 1, -1, -1):\n while N >= coins[i]:\n N -= coins[i]\n res.append(coins[i])\n return res", "def minpartition(sm):\n (arr, out) = ([1, 2, 5, 10, 20, 50, 100, 200, 500, 2000][::-1], [])\n for i in arr:\n if sm // i > 0:\n out.extend([i] * (sm // i))\n sm -= i * (sm // i)\n return out", "def minpartition(amount):\n denominations = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n n = len(denominations)\n i = n - 1\n ans = []\n while i >= 0:\n if amount < denominations[i]:\n i -= 1\n elif amount == denominations[i]:\n ans.append(denominations[i])\n break\n else:\n ans.append(denominations[i])\n amount -= denominations[i]\n return ans", "def minpartition(N):\n p = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n ans = []\n for i in range(N):\n for i in p:\n if N >= i:\n ans.append(i)\n N = N - i\n break\n if N == 0:\n break\n return ans", "def minpartition(N):\n u = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n u = u[::-1]\n i = 0\n v = []\n while N != 0:\n if N >= u[i]:\n N = N - u[i]\n v.append(u[i])\n else:\n i += 1\n return v", "def minpartition(N):\n x = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n list = []\n while N != 0:\n for e in range(10):\n if x[e] <= N:\n N = N - x[e]\n list.append(x[e])\n break\n return list", "def minpartition(N):\n coins = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n ans = []\n i = 0\n while i < len(coins) or N <= 0:\n while i < len(coins) and coins[i] > N:\n i += 1\n if i >= len(coins):\n break\n N -= coins[i]\n ans.append(coins[i])\n return ans", "def minpartition(N):\n coinsList = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n coinsList = coinsList[::-1]\n coins = []\n while N > 0:\n for coin in coinsList:\n if N >= coin:\n coins.append(coin)\n N -= coin\n break\n return coins", "import math\n\ndef minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n coins.sort(reverse=True)\n ans = []\n for coin in coins:\n if coin > N or N <= 0:\n continue\n div = math.floor(N / coin)\n for i in range(div):\n ans.append(coin)\n N -= coin * div\n return ans", "def minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n while N > 0:\n for i in range(9, -1, -1):\n num = N // coins[i]\n ans += [coins[i]] * num\n N = N % coins[i]\n return ans", "def minpartition(N):\n ans = []\n arr = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n for x in arr:\n coin = N // x\n ans += [x] * coin\n N = N % x\n return ans", "import bisect\n\ndef minpartition(N):\n arr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n i = 9\n while i >= 0:\n if N >= arr[i]:\n ans.append(arr[i])\n N -= arr[i]\n else:\n i -= 1\n if N <= 0:\n break\n return ans", "import bisect\n\ndef minpartition(N):\n arr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n while N > 0:\n idx = bisect.bisect(arr, N)\n ans.append(arr[idx - 1])\n N -= arr[idx - 1]\n return ans", "def minpartition(N):\n curr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n n = len(curr)\n ans = []\n for i in range(n - 1, -1, -1):\n while N >= curr[i]:\n N -= curr[i]\n ans.append(curr[i])\n return ans", "def minpartition(N):\n denom = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ind = len(denom) - 1\n out = []\n while N and ind > -1:\n val = N // denom[ind]\n if val:\n N -= val * denom[ind]\n out.extend([denom[ind]] * val)\n ind -= 1\n return out", "def minpartition(N):\n notes = []\n coinsIdx = 0\n while N and coinsIdx < len(Solution.coins):\n noteNums = N // Solution.coins[coinsIdx]\n N = N % Solution.coins[coinsIdx]\n for i in range(noteNums):\n notes.append(Solution.coins[coinsIdx])\n coinsIdx += 1\n return notes", "def minpartition(N):\n ans = []\n l1 = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n for i in l1:\n k = N // i\n ans.extend([i] * k)\n N = N - k * i\n return ans", "def minpartition(N):\n target = N\n ar = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ar = ar[::-1]\n ans = []\n for coin in ar:\n n = target // coin\n ans.extend([coin] * n)\n target -= n * coin\n if target == 0:\n break\n return ans", "def minpartition(N):\n brr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n brr = brr[::-1]\n ans = []\n for i in range(len(brr)):\n if brr[i] <= N:\n for j in range(N // brr[i]):\n ans.append(brr[i])\n N = N % brr[i]\n return ans", "def minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n res = []\n idx = len(coins) - 1\n while N:\n if coins[idx] <= N:\n count = N // coins[idx]\n res += [coins[idx]] * count\n N -= coins[idx] * count\n else:\n idx -= 1\n return res", "def minpartition(N):\n indian_denomination = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n coins_used = []\n for denom in reversed(indian_denomination):\n while denom <= N:\n coins_used.append(denom)\n N = N - denom\n if N == 0:\n break\n return coins_used", "def minpartition(N):\n coins_available = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n rem_money = N\n ans = []\n i = 0\n while rem_money != 0 and i < len(coins_available):\n if coins_available[i] <= rem_money:\n rem_money -= coins_available[i]\n ans.append(coins_available[i])\n if rem_money >= coins_available[i]:\n pass\n else:\n i += 1\n else:\n i += 1\n return ans", "def minpartition(N):\n lt = []\n cur = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n x = 0\n for i in range(10):\n if cur[i] > N:\n break\n x = i\n while N > 0:\n if N < cur[x]:\n x -= 1\n else:\n lt.append(cur[x])\n N -= cur[x]\n return lt", "def minpartition(N):\n d = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n res = []\n i = len(d) - 1\n while i >= 0:\n while N >= d[i]:\n N -= d[i]\n res.append(d[i])\n i -= 1\n return res", "def minpartition(N):\n currency = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n n = len(currency)\n target = N\n i = n - 1\n out = []\n while i >= 0:\n curr = currency[i]\n if target >= curr:\n target = target - curr\n out.append(curr)\n else:\n i -= 1\n return out", "def minpartition(N):\n changes = []\n while N:\n if N >= 2000:\n changes.append(2000)\n N = N - 2000\n elif N >= 500:\n changes.append(500)\n N = N - 500\n elif N >= 200:\n changes.append(200)\n N = N - 200\n elif N >= 100:\n changes.append(100)\n N = N - 100\n elif N >= 50:\n changes.append(50)\n N = N - 50\n elif N >= 20:\n changes.append(20)\n N = N - 20\n elif N >= 10:\n changes.append(10)\n N = N - 10\n elif N >= 5:\n changes.append(5)\n N = N - 5\n elif N >= 2:\n changes.append(2)\n N = N - 2\n elif N >= 1:\n changes.append(1)\n N = N - 1\n return changes", "def minpartition(N):\n coins = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n ans = []\n idx = 0\n while N and idx < len(coins):\n if coins[idx] > N:\n idx += 1\n else:\n N -= coins[idx]\n ans.append(coins[idx])\n return ans", "def __init__():\n self.res = []\n\ndef solve(arr, N, summ, ct, dp):\n if summ == 0:\n self.res.append(ct)\n return 1\n if summ < 0:\n return 0\n if dp[N][summ] != -1:\n return dp[N][summ]\n if summ - arr[N - 1] >= 0:\n ct.append(arr[N - 1])\n dp[N][summ] = self.solve(arr, N, summ - arr[N - 1], ct, dp) or self.solve(arr, N - 1, summ, ct, dp)\n else:\n dp[N][summ] = self.solve(arr, N - 1, summ, ct, dp)\n return dp[N][summ]\n\ndef minpartition(N):\n if N <= 0:\n return 0\n arr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n dp = [[-1 for i in range(N + 1)] for j in range(len(arr) + 1)]\n a = self.solve(arr, len(arr), N, [], dp)\n ind = 0\n if len(self.res) > 0:\n tot = sum(self.res[0])\n for i in range(1, len(self.res)):\n a = sum(self.res[i])\n if a > tot:\n tot = a\n ind = i\n return self.res[ind]", "def minpartition(N):\n arr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n curr = len(arr) - 1\n ans = []\n while N > 0:\n if arr[curr] <= N:\n ans.append(arr[curr])\n N = N - arr[curr]\n else:\n curr = curr - 1\n return ans", "def minpartition(N):\n currency = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n arr = []\n for i in currency:\n while N - i >= 0:\n arr.append(i)\n N -= i\n return arr", "def minpartition(N):\n deno = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n arr = []\n for d in deno:\n if N == 0:\n break\n while N >= d:\n arr.append(d)\n N -= d\n return arr", "def minpartition(n):\n l = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n l1 = []\n i = 0\n for i in range(10):\n while n >= l[i]:\n n = n - l[i]\n l1.append(l[i])\n i += 1\n return l1", "import math\n\ndef minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n s = len(coins)\n dp = [[math.inf] * (N + 1) for i in range(s + 1)]\n for i in range(1, s + 1):\n for j in range(1, N + 1):\n x = j % coins[i - 1]\n y = int(j / coins[i - 1])\n if x == 0:\n dp[i][j] = min(y, dp[i - 1][j])\n else:\n dp[i][j] = dp[i - 1][x] + y\n result = []\n curr = dp[s][N]\n j = N\n while N > 0:\n for i in range(1, s + 1):\n if dp[i][j] == curr:\n x = j % coins[i - 1]\n y = int(j / coins[i - 1])\n for k in range(y):\n result.append(coins[i - 1])\n curr = curr - y\n N = x\n j = x\n break\n return result", "def minpartition(N):\n deno = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n idx = 9\n while N != 0:\n if N >= deno[idx]:\n ans.append(deno[idx])\n N -= deno[idx]\n else:\n idx -= 1\n return ans", "currencies = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\nnum_currencies = len(currencies)\n\ndef minpartition(N):\n i = num_currencies - 1\n taken = []\n while i >= 0 and N > 0:\n while currencies[i] <= N:\n N -= currencies[i]\n taken.append(currencies[i])\n i -= 1\n return taken", "def minpartition(N):\n notes = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n size = len(notes)\n i = size - 1\n ans = list()\n while i >= 0:\n if notes[i] > N:\n i -= 1\n else:\n N -= notes[i]\n ans.append(notes[i])\n if N == 0:\n return ans\n return ans", "def minpartition(V):\n deno = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n n = len(deno)\n ans = []\n i = n - 1\n while i >= 0:\n while V >= deno[i]:\n V -= deno[i]\n ans.append(deno[i])\n i -= 1\n return ans", "def minpartition(N):\n if N == 1:\n return [1]\n notes = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n ans = []\n for note in notes:\n cnt = N // note\n if cnt:\n for j in range(cnt):\n ans.append(note)\n N = N % note\n return ans", "def minpartition(N):\n ans = []\n arr = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n while N != 0:\n for i in range(0, 10):\n a = N // arr[i]\n N = N % arr[i]\n for j in range(a):\n ans.append(arr[i])\n if N == 0:\n break\n return ans", "def minpartition(N):\n lst = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n sum1 = []\n for i in lst:\n if i > N:\n continue\n if N == 0:\n break\n s = N // i\n N = N % i\n sum1 += s * [i]\n return sum1", "def minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n i = 9\n while i >= 0:\n while N >= coins[i]:\n ans.append(coins[i])\n N -= coins[i]\n i -= 1\n if N == 0:\n return ans", "def minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n i = 9\n while i >= 0:\n change = N // coins[i]\n for coin in range(change):\n ans.append(coins[i])\n if change != 0:\n N = N % (coins[i] * change)\n i -= 1\n if N == 0:\n return ans", "def minpartition(N):\n arr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n res = []\n n = len(arr) - 1\n for i in range(n, -1, -1):\n if N == 0:\n break\n while N >= arr[i]:\n N -= arr[i]\n res.append(arr[i])\n return res", "def minpartition(N):\n ans = []\n lis = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n for i in lis:\n coin = N // i\n ans += [i] * coin\n N = N % i\n return ans", "def minpartition(N):\n curr = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n i = len(curr) - 1\n ans = []\n while N != 0:\n if curr[i] <= N:\n x = N // curr[i]\n for j in range(x):\n ans.append(curr[i])\n N -= x * curr[i]\n i -= 1\n return ans", "def minpartition(N):\n result = []\n denomination = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n while N > 0:\n for i in range(len(denomination) - 1, -1, -1):\n if N >= denomination[i]:\n N = N - denomination[i]\n result.append(denomination[i])\n break\n return result", "def minpartition(N):\n result = []\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n coins.sort(reverse=True)\n while N:\n for coin in coins:\n if coin <= N:\n result.append(coin)\n N -= coin\n break\n return result", "def minpartition(N):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n amount = N\n i = len(coins) - 1\n while i >= 0:\n if coins[i] <= amount:\n break\n i -= 1\n out = []\n while amount > 0 and i >= 0:\n times = amount // coins[i]\n out = out + [coins[i]] * times\n amount = amount % coins[i]\n while i >= 0:\n if coins[i] <= amount:\n break\n i -= 1\n return out", "def minpartition(N):\n dict = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n\n def help(n, ans):\n if n == 0:\n return 0\n for i in range(len(dict) - 1, -1, -1):\n if dict[i] <= n:\n ans.append(dict[i])\n n -= dict[i]\n break\n help(n, ans)\n help(N, ans)\n return ans", "def minpartition(N):\n a = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n b = 0\n c = []\n for i in range(9, -1, -1):\n while b + a[i] <= N:\n b += a[i]\n c.append(a[i])\n return c", "def minpartition(N):\n l = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n l1 = []\n for i in l:\n if i <= N:\n l1.append(i)\n else:\n break\n l1.reverse()\n s = 0\n out = []\n i = 0\n while s <= N and i < len(l1):\n if s + l1[i] <= N:\n out.append(l1[i])\n s += l1[i]\n else:\n i += 1\n return out", "def minpartition(N):\n l = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n ans = []\n for i in range(-1, -11, -1):\n if N // l[i] != 0:\n ans += [l[i]] * (N // l[i])\n N %= l[i]\n return ans", "def minpartition(N):\n den = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n den.sort(reverse=True)\n ans = []\n i = 0\n while N > 0:\n if den[i] > N:\n i += 1\n continue\n N -= den[i]\n ans.append(den[i])\n return ans", "def minpartition(N):\n currency = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n i = 0\n ans = []\n while i < len(currency):\n if currency[i] > N:\n i += 1\n elif currency[i] == N:\n ans.append(currency[i])\n return ans\n elif currency[i] < N:\n N -= currency[i]\n ans.append(currency[i])\n return ans", "def minpartition(n):\n arr = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n ans = []\n for i in arr:\n temp = n // i\n ans += temp * [i]\n n -= temp * i\n return ans", "def minpartition(N):\n Coin = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000]\n Cn = 10\n ans = []\n while N > 0:\n if Coin[Cn - 1] > N:\n Cn -= 1\n else:\n ans.append(Coin[Cn - 1])\n N -= Coin[Cn - 1]\n return ans", "def minpartition(N):\n op = []\n\n def amt_to_be_subtracted(N):\n k = 0\n curr = [2000, 500, 200, 100, 50, 20, 10, 5, 2, 1]\n for note in curr:\n if note > N:\n k += 1\n return curr[k]\n while N != 0:\n minus = amt_to_be_subtracted(N)\n op.append(minus)\n N = N - minus\n return op", "def dyn(v):\n coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 2000][::-1]\n result = []\n while v:\n for val in coins:\n if val <= v:\n result += [val] * (v // val)\n v -= val * (v // val)\n return result\n\ndef minpartition(N):\n return dyn(N)"], "starter_code": "def minpartition(N):\n", "input_output": {"inputs": ["N = 43", "N = 1000"], "outputs": ["20 20 2 1", "500 500"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming", "Greedy"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Greedy algorithms"], "skill_types": ["Dynamic programming", "Greedy algorithms"], "url": "https://practice.geeksforgeeks.org/problems/-minimum-number-of-coins4426/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "minpartition", "task_id": "TACO_lite/436", "example": [[], []]} +{"requirement": "In a given 2D binary array A, there are two islands.\u00a0 (An island is a 4-directionally connected group of\u00a01s not connected to any other 1s.)\nNow, we may change 0s to 1s so as to connect the two islands together to form 1 island.\nReturn the smallest number of 0s that must be flipped.\u00a0 (It is guaranteed that the answer is at least 1.)\n\u00a0\nExample 1:\nInput: A = [[0,1],[1,0]]\nOutput: 1\nExample 2:\nInput: A = [[0,1,0],[0,0,0],[0,0,1]]\nOutput: 2\nExample 3:\nInput: A = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]\nOutput: 1\n\n\u00a0\nConstraints:\n\n2 <= A.length == A[0].length <= 100\nA[i][j] == 0 or A[i][j] == 1", "solutions": ["def shortestbridge(A: List[List[int]]) -> int:\n (m, n) = (len(A), len(A[0]))\n dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n queue = deque()\n boundary = set()\n found = False\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n A[i][j] = 2\n queue.append((i, j))\n while queue:\n (ci, cj) = queue.popleft()\n for (di, dj) in dirs:\n (ni, nj) = (ci + di, cj + dj)\n if 0 <= ni < m and 0 <= nj < n:\n if A[ni][nj] == 1:\n A[ni][nj] = 2\n queue.append((ni, nj))\n elif A[ni][nj] == 0:\n boundary.add((ci, cj))\n found = True\n break\n if found:\n break\n queue = deque(boundary)\n steps = 0\n while queue:\n for _ in range(len(queue)):\n (i, j) = queue.popleft()\n for (di, dj) in dirs:\n (ni, nj) = (i + di, j + dj)\n if 0 <= ni < m and 0 <= nj < n:\n if A[ni][nj] == 0:\n A[ni][nj] = 2\n queue.append((ni, nj))\n elif A[ni][nj] == 1:\n return steps\n steps += 1", "from collections import deque\n\ndef shortestbridge(A: List[List[int]]) -> int:\n q = deque()\n (m, n) = (len(A), len(A[0]))\n\n def explore_island(r, c):\n if not 0 <= r < m or not 0 <= c < n or A[r][c] == -1:\n return\n if A[r][c] == 1:\n A[r][c] = -1\n explore_island(r + 1, c)\n explore_island(r - 1, c)\n explore_island(r, c + 1)\n explore_island(r, c - 1)\n elif A[r][c] == 0:\n q.append((r, c, 1))\n\n def findFirst():\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n explore_island(i, j)\n return\n findFirst()\n while q:\n (cur_x, cur_y, cur_t) = q.popleft()\n for (i, j) in ((cur_x + 1, cur_y), (cur_x - 1, cur_y), (cur_x, cur_y + 1), (cur_x, cur_y - 1)):\n if 0 <= i < m and 0 <= j < n:\n if A[i][j] == 0:\n A[i][j] = -1\n q.append((i, j, cur_t + 1))\n elif A[i][j] == 1:\n return cur_t", "def shortestbridge(A: List[List[int]]) -> int:\n\n def dfs(i, j, n, m):\n A[i][j] = 2\n queue.append((i, j))\n directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n for (dx, dy) in directions:\n (x, y) = (i + dx, j + dy)\n if 0 <= x < n and 0 <= y < m and (A[x][y] == 1):\n dfs(x, y, n, m)\n from collections import deque\n queue = deque()\n (n, m) = (len(A), len(A[0]))\n for i in range(n):\n for j in range(m):\n if A[i][j] == 1:\n dfs(i, j, n, m)\n break\n else:\n continue\n break\n directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n step = 0\n while queue:\n size = len(queue)\n flag = False\n for i in range(size):\n point = queue.popleft()\n (x, y) = (point[0], point[1])\n for (dx, dy) in directions:\n (_x, _y) = (x + dx, y + dy)\n if _x < 0 or _x >= n or _y < 0 or (_y >= m) or (A[_x][_y] == 2):\n continue\n if A[_x][_y] == 1:\n return step\n A[_x][_y] = 2\n queue.append((_x, _y))\n step += 1", "def shortestbridge(A: List[List[int]]) -> int:\n\n def dfs(i, j):\n A[i][j] = -1\n bfs.append((i, j))\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= x < n and 0 <= y < n and (A[x][y] == 1):\n dfs(x, y)\n\n def first():\n for i in range(n):\n for j in range(n):\n if A[i][j]:\n return (i, j)\n (n, step, bfs) = (len(A), 0, [])\n dfs(*first())\n while bfs:\n new = []\n for (i, j) in bfs:\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= x < n and 0 <= y < n:\n if A[x][y] == 1:\n return step\n elif not A[x][y]:\n A[x][y] = -1\n new.append((x, y))\n step += 1\n bfs = new", "from queue import Queue\n\ndef valid(m, i, j):\n return 0 <= i < len(m) and 0 <= j < len(m[0])\n\ndef findAnIsland(m, e):\n stack = []\n for i in range(len(m)):\n for j in range(len(m[0])):\n if m[i][j] == 1 and (i, j) not in e:\n stack.append((i, j))\n break\n else:\n continue\n break\n (result, edges) = (set(), set())\n while stack:\n (ci, cj) = stack.pop()\n result.add((ci, cj))\n for (di, dj) in ((0, 1), (1, 0), (0, -1), (-1, 0)):\n (cdi, cdj) = (ci + di, cj + dj)\n if valid(m, cdi, cdj) and (cdi, cdj) not in e and ((cdi, cdj) not in result):\n if m[cdi][cdj] == 1:\n stack.append((cdi, cdj))\n else:\n edges.add((ci, cj))\n return (result, edges)\n\ndef shortestbridge(A: List[List[int]]) -> int:\n (a, aedges) = findAnIsland(A, set())\n (b, bedges) = findAnIsland(A, a)\n min_flip = float('inf')\n q = Queue()\n for (i, j) in aedges:\n q.put((i, j, 0))\n while not q.empty():\n (ci, cj, dist) = q.get()\n for (di, dj) in ((0, 1), (1, 0), (0, -1), (-1, 0)):\n (cdi, cdj) = (ci + di, cj + dj)\n if valid(A, cdi, cdj):\n if (cdi, cdj) in bedges:\n min_flip = min(min_flip, dist)\n return min_flip\n elif A[cdi][cdj] == 0 or A[cdi][cdj] > dist + 1:\n A[cdi][cdj] = dist + 1\n q.put((cdi, cdj, dist + 1))\n return min_flip", "WATER = 0\nLAND = 1\nISLAND = 2\nBRIDGE = 3\nDIR = ((-1, 0), (1, 0), (0, -1), (0, 1))\nfrom copy import deepcopy\n\ndef shortestbridge(A):\n (x0, y0) = self.findFirstLand(A)\n q = deque([(x0, y0)])\n visited = set([(x0, y0)])\n self.bfs(A, q, visited, LAND)\n q = deque(visited)\n return self.bfs(A, q, visited, WATER, LAND) - 1\n\ndef findFirstLand(A):\n (m, n) = (len(A), len(A[0]))\n for x in range(m):\n for y in range(n):\n if A[x][y] == LAND:\n return (x, y)\n\ndef bfs(A, q, visited, target, des=-1):\n (m, n) = (len(A), len(A[0]))\n step = 0\n while q:\n for _ in range(len(q)):\n (x, y) = q.popleft()\n for (dx, dy) in DIR:\n (nx, ny) = (x + dx, y + dy)\n if 0 <= nx <= m - 1 and 0 <= ny <= n - 1 and ((nx, ny) not in visited):\n if A[nx][ny] == des:\n return step + 1\n if A[nx][ny] == target:\n q.append((nx, ny))\n visited.add((nx, ny))\n step += 1\n return step - 1", "def shortestbridge(A):\n (R, C) = (len(A), len(A[0]))\n\n def neighbors(r, c):\n for (nr, nc) in ((r - 1, c), (r, c - 1), (r + 1, c), (r, c + 1)):\n if 0 <= nr < R and 0 <= nc < C:\n yield (nr, nc)\n\n def get_components():\n done = set()\n components = []\n for (r, row) in enumerate(A):\n for (c, val) in enumerate(row):\n if val and (r, c) not in done:\n stack = [(r, c)]\n seen = {(r, c)}\n while stack:\n node = stack.pop()\n for nei in neighbors(*node):\n if A[nei[0]][nei[1]] and nei not in seen:\n stack.append(nei)\n seen.add(nei)\n done |= seen\n components.append(seen)\n return components\n (source, target) = get_components()\n queue = collections.deque([(node, 0) for node in source])\n done = set(source)\n while queue:\n (node, d) = queue.popleft()\n if node in target:\n return d - 1\n for nei in neighbors(*node):\n if nei not in done:\n queue.append((nei, d + 1))\n done.add(nei)", "def shortestbridge(A: List[List[int]]) -> int:\n if len(A) == 0:\n return 0\n m = len(A)\n n = len(A[0])\n queue = []\n found = False\n for i in range(m):\n if found:\n break\n for j in range(n):\n if A[i][j] == 1:\n self.dfs(i, j, A, queue)\n found = True\n break\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n while queue:\n (path, x, y) = queue.pop(0)\n for (dx, dy) in directions:\n if x + dx < 0 or y + dy < 0 or x + dx >= m or (y + dy >= n):\n continue\n if A[x + dx][y + dy] == 1:\n return path\n if A[x + dx][y + dy] == 0:\n A[x + dx][y + dy] = 2\n queue.append((path + 1, x + dx, y + dy))\n return -1\n\ndef dfs(i, j, grid, queue):\n queue.append((0, i, j))\n grid[i][j] = 2\n stack = [(i, j)]\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n while stack:\n (x, y) = stack.pop()\n for (dx, dy) in directions:\n if x + dx < 0 or y + dy < 0 or x + dx >= len(grid) or (y + dy >= len(grid[0])):\n continue\n if grid[x + dx][y + dy] == 1:\n queue.append((0, x + dx, y + dy))\n stack.append((x + dx, y + dy))\n grid[x + dx][y + dy] = 2", "def shortestbridge(A: List[List[int]]) -> int:\n r = len(A)\n c = len(A[0])\n path = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n idx = []\n for i in range(r):\n for j in range(c):\n if A[i][j] == 1:\n idx.append((i, j))\n queue = collections.deque([idx[0]])\n seen = {tuple(idx[0])}\n island = collections.deque([(idx[0][0], idx[0][1], 0)])\n while queue:\n (x, y) = queue.popleft()\n for i in path:\n a = x + i[0]\n b = y + i[1]\n if 0 <= a < r and 0 <= b < c and (A[a][b] == 1) and ((a, b) not in seen):\n queue.append((a, b))\n seen.add((a, b))\n island.append((a, b, 0))\n while island:\n (x, y, z) = island.popleft()\n for i in path:\n a = x + i[0]\n b = y + i[1]\n if 0 <= a < r and 0 <= b < c and ((a, b) not in seen):\n if A[a][b] == 0:\n island.append((a, b, z + 1))\n seen.add((a, b))\n else:\n return z", "def find_island(i, j):\n if (i >= 0 and i < self.m) and (j >= 0 and j < self.n) and (self.grid[i][j] == 1):\n self.island.append([i, j])\n self.grid[i][j] = -1\n D = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n for d in D:\n self.find_island(i + d[0], j + d[1])\n\ndef expand_island():\n D = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n while len(self.island) > 0:\n [i, j] = self.island.pop(0)\n for d in D:\n if i + d[0] in range(self.m) and j + d[1] in range(self.n):\n if self.grid[i + d[0]][j + d[1]] == 1:\n return self.grid[i][j] + 1\n if self.grid[i + d[0]][j + d[1]] == 0:\n self.island.append([i + d[0], j + d[1]])\n self.grid[i + d[0]][j + d[1]] = self.grid[i][j] - 1\n return self.m + self.n - 1\n\ndef shortestbridge(A: List[List[int]]) -> int:\n from itertools import product\n self.grid = A\n (self.m, self.n) = (len(A), len(A[0]))\n self.island = []\n for i in range(self.n):\n for j in range(self.m):\n if len(self.island) == 0 and self.grid[i][j] == 1:\n self.find_island(i, j)\n return abs(self.expand_island())", "def shortestbridge(A: List[List[int]]) -> int:\n\n def dirs(V, M, N):\n res = []\n if V[0] > 0:\n res.append((V[0] - 1, V[1]))\n if V[0] < M - 1:\n res.append((V[0] + 1, V[1]))\n if V[1] > 0:\n res.append((V[0], V[1] - 1))\n if V[1] < N - 1:\n res.append((V[0], V[1] + 1))\n return res\n\n def bfs(grid):\n q = []\n for j in I[0]:\n level[j] = 0\n q.append(j)\n visited.add(j)\n while q:\n v = q.pop(0)\n for neighbor in dirs(v, len(grid), len(grid[0])):\n if neighbor not in visited:\n q.append(neighbor)\n visited.add(neighbor)\n if neighbor in level:\n level[neighbor] = min(level[neighbor], level[v] + 1)\n else:\n level[neighbor] = level[v] + 1\n return\n\n def dfs(grid, i, j, m, n, S):\n S.add((i, j))\n vis.add((i, j))\n if i < m - 1 and (i + 1, j) not in vis and (grid[i + 1][j] == 1):\n dfs(grid, i + 1, j, m, n, S)\n if i > 0 and (i - 1, j) not in vis and (grid[i - 1][j] == 1):\n dfs(grid, i - 1, j, m, n, S)\n if j < n - 1 and (i, j + 1) not in vis and (grid[i][j + 1] == 1):\n dfs(grid, i, j + 1, m, n, S)\n if j > 0 and (i, j - 1) not in vis and (grid[i][j - 1] == 1):\n dfs(grid, i, j - 1, m, n, S)\n return\n (M, N) = (len(A), len(A[0]))\n I = []\n vis = set()\n for i in range(M):\n for j in range(N):\n if (i, j) not in vis and A[i][j] == 1:\n s = set()\n dfs(A, i, j, M, N, s)\n I.append(s)\n level = {}\n visited = set()\n bfs(A)\n return min([level[j] for j in I[1]]) - 1", "def shortestbridge(A: List[List[int]]) -> int:\n (m, n) = (len(A), len(A[0]))\n (r, c) = (-1, -1)\n for (i, row) in enumerate(A):\n for (j, val) in enumerate(row):\n if val == 1:\n r = i\n c = j\n break\n if r == -1 or c == -1:\n return -1\n nei = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n\n def dfs(A, i, j, q):\n q.append((i, j, 0))\n A[i][j] = 2\n for (dx, dy) in nei:\n nx = i + dx\n ny = j + dy\n if 0 <= nx < m and 0 <= ny < n and (A[nx][ny] == 1):\n dfs(A, nx, ny, q)\n return\n q = []\n dfs(A, r, c, q)\n while q:\n (cx, cy, dis) = q.pop(0)\n for (dx, dy) in nei:\n (nx, ny) = (cx + dx, cy + dy)\n if 0 <= nx < m and 0 <= ny < n:\n if A[nx][ny] == 1:\n return dis\n if A[nx][ny] == 0:\n q.append((nx, ny, dis + 1))\n A[nx][ny] = 2\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n rows = len(A)\n cols = len(A[0])\n directions = ((1, 0), (-1, 0), (0, 1), (0, -1))\n\n def edge_check(ro, co):\n r = []\n for (y, x) in directions:\n nr = ro + y\n nc = co + x\n if nr < rows and nr >= 0 and (nc < cols) and (nc >= 0) and (A[nr][nc] == 0):\n return True\n return False\n edges_1 = []\n found_1 = False\n edges_2 = []\n for row in range(rows):\n for col in range(cols):\n if A[row][col] == 1:\n A[row][col] = '#'\n q = collections.deque([])\n q.append((row, col))\n while q:\n (r, c) = q.popleft()\n if not found_1 and edge_check(r, c):\n edges_1.append((r, c))\n elif edge_check(r, c):\n edges_2.append((r, c))\n for (y, x) in directions:\n nr = r + y\n nc = c + x\n if nr < rows and nr >= 0 and (nc < cols) and (nc >= 0) and (A[nr][nc] == 1):\n q.append((nr, nc))\n A[nr][nc] = '#'\n found_1 = True\n c1 = sorted(edges_1, key=lambda x: (x[0], x[1]))\n c2 = sorted(edges_2, key=lambda x: (x[0], x[1]))\n minn = float('inf')\n for (x1, x2) in c1:\n for (y1, y2) in c2:\n minn = min(minn, abs(x1 - y1) + abs(x2 - y2) - 1)\n return minn", "def shortestbridge(A: List[List[int]]) -> int:\n\n def trace_island(A, start_i, start_j, second, edges):\n queue = collections.deque()\n queue.append((start_i, start_j))\n while queue:\n (i, j) = queue.popleft()\n isedge = False\n for (di, dj) in [(1, 0), (0, 1), (-1, 0), (0, -1), (0, 0)]:\n if 0 <= di + i < len(A) and 0 <= dj + j < len(A[0]) and (A[di + i][dj + j] == 1):\n if second:\n A[di + i][dj + j] = 2\n else:\n A[di + i][dj + j] = -1\n if not (di == 0 and dj == 0):\n queue.append((di + i, dj + j))\n else:\n isedge = True\n if isedge and (not second):\n edges.append((i, j))\n outedge = []\n second = False\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1:\n trace_island(A, i, j, second, outedge)\n second = True\n output = 0\n while outedge:\n temp = []\n for (i, j) in outedge:\n for (di, dj) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:\n if 0 <= di + i < len(A) and 0 <= dj + j < len(A[0]) and (A[di + i][dj + j] != -1):\n if A[di + i][dj + j] == 2:\n return output\n temp.append((di + i, dj + j))\n A[di + i][dj + j] = -1\n outedge = temp\n output += 1", "def shortestbridge(A: List[List[int]]) -> int:\n q = []\n r = len(A)\n c = len(A[0])\n result = float('inf')\n seen = [[False] * c for _ in range(r)]\n found = False\n for i in range(r):\n if found:\n break\n for j in range(c):\n if A[i][j] == 1:\n q = self.neighbors(i, j, A, seen, r, c)\n found = True\n break\n while q:\n (x, y, dis) = q.pop(0)\n for (d1, d2) in ((-1, 0), (0, -1), (1, 0), (0, 1)):\n (n_x, n_y) = (d1 + x, d2 + y)\n if 0 <= n_x < r and 0 <= n_y < c and (not seen[n_x][n_y]):\n if A[n_x][n_y] == 1:\n result = min(result, dis)\n q.append((n_x, n_y, dis + 1))\n seen[n_x][n_y] = True\n return result\n\ndef neighbors(i, j, A, seen, r, c):\n q = [(i, j)]\n seen[i][j] = True\n ls = []\n while q:\n (x, y) = q.pop(0)\n ls.append((x, y, 0))\n for (d1, d2) in ((-1, 0), (0, -1), (1, 0), (0, 1)):\n (n_x, n_y) = (d1 + x, d2 + y)\n if 0 <= n_x < r and 0 <= n_y < c and (A[n_x][n_y] == 1) and (not seen[n_x][n_y]):\n q.append((n_x, n_y))\n seen[n_x][n_y] = True\n return ls", "def shortestbridge(A: List[List[int]]) -> int:\n if not len(A) or not len(A[0]):\n return 0\n (m, n) = (len(A), len(A[0]))\n\n def neighbors(i, j):\n for (ni, nj) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= ni < m and 0 <= nj < n:\n yield (ni, nj)\n\n def dfs(i, j, seen, island):\n if (i, j) not in seen:\n seen.add((i, j))\n for (ni, nj) in neighbors(i, j):\n if A[ni][nj] == 1:\n dfs(ni, nj, seen, island)\n else:\n island.add((i, j))\n\n def find_island():\n seen = set()\n island = set()\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n dfs(i, j, seen, island)\n return (seen, island)\n (seen, island) = find_island()\n q = collections.deque(list([(x, 0) for x in island]))\n while q:\n ((i, j), cnt) = q.popleft()\n for (ni, nj) in neighbors(i, j):\n if (ni, nj) not in seen:\n seen.add((ni, nj))\n if A[ni][nj] == 1:\n return cnt\n q.append(((ni, nj), cnt + 1))\n return -1", "import queue\n\ndef shortestbridge(A: List[List[int]]) -> int:\n\n def adjacent(i, q):\n nonlocal A\n l = []\n if i > 0:\n l.append([i - 1, q])\n if i < len(A) - 1:\n l.append([i + 1, q])\n if q > 0:\n l.append([i, q - 1])\n if q < len(A[0]) - 1:\n l.append([i, q + 1])\n return l\n\n def fill(i, q):\n nonlocal A\n A[i][q] = 2\n qu = queue.Queue()\n qu.put([i, q])\n seen = set()\n while not qu.empty():\n current = qu.get()\n seen.add(tuple(current))\n l = adjacent(current[0], current[1])\n for (a, b) in l:\n if A[a][b] == 1:\n A[a][b] = 2\n qu.put([a, b])\n return seen\n starts = []\n broken = False\n for i in range(len(A)):\n for q in range(len(A[0])):\n if A[i][q] == 1:\n starts = fill(i, q)\n broken = True\n break\n if broken:\n break\n qu = queue.Queue()\n for el in list(starts):\n qu.put(list(el) + [0])\n while not qu.empty():\n current = qu.get()\n l = adjacent(current[0], current[1])\n for (i, q) in l:\n if A[i][q] == 1:\n return current[2]\n elif A[i][q] == 0:\n A[i][q] = 2\n qu.put([i, q, current[2] + 1])", "def shortestbridge(A: List[List[int]]) -> int:\n (R, C) = (len(A), len(A[0]))\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n\n def dfs(row, col, group):\n A[row][col] = marker\n group.append((row, col))\n for (dr, dc) in directions:\n (new_row, new_col) = (row + dr, col + dc)\n if 0 <= new_row < R and 0 <= new_col < C and (A[new_row][new_col] == 1):\n dfs(new_row, new_col, group)\n return group\n (groups, marker) = ([], 2)\n for r in range(R):\n for c in range(C):\n if A[r][c] == 1:\n groups.append((dfs(r, c, []), marker))\n marker += 1\n groups = sorted(groups, key=lambda x: len(x[0]))\n (src_group, src_marker) = groups[0]\n q = deque([(row, col, 0) for (row, col) in src_group])\n target = set(groups[1][0])\n while q:\n (row, col, curr_distance) = q.pop()\n if (row, col) in target:\n return curr_distance - 1\n for (dr, dc) in directions:\n (new_row, new_col) = (row + dr, col + dc)\n if 0 <= new_row < R and 0 <= new_col < C and (A[new_row][new_col] != src_marker):\n q.appendleft((new_row, new_col, curr_distance + 1))\n A[new_row][new_col] = src_marker\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n (m, n) = (len(A) if A else 0, len(A[0]) if A else 0)\n (p, q) = (-1, -1)\n\n def neighbors(r, c):\n for (nr, nc) in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]:\n if nr in range(m) and nc in range(n):\n yield (nr, nc)\n done = set()\n components = []\n for (i, j) in product(list(range(m)), list(range(n))):\n if A[i][j] == 1:\n if (i, j) not in done:\n stack = [(i, j)]\n seen = {(i, j)}\n while stack:\n node = stack.pop()\n for (p, q) in neighbors(*node):\n if (p, q) not in seen:\n if A[p][q] == 1:\n seen.add((p, q))\n stack.append((p, q))\n done |= seen\n components.append(seen)\n (source, target) = components\n heap = []\n for (i, j) in source:\n heappush(heap, (0, (i, j)))\n done = set(source)\n while heap:\n (dist, (i, j)) = heappop(heap)\n if (i, j) in target:\n return dist - 1\n for (r, s) in neighbors(i, j):\n if A[r][s] not in source and (r, s) not in done:\n done.add((r, s))\n heappush(heap, (dist + 1, (r, s)))", "def find_island(i, j):\n self.island.append([i, j])\n self.grid[i][j] = -1\n D = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n for d in D:\n if i + d[0] in range(self.m) and j + d[1] in range(self.n) and (self.grid[i + d[0]][j + d[1]] == 1):\n self.find_island(i + d[0], j + d[1])\n\ndef expand_island():\n D = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n while len(self.island) > 0:\n [i, j] = self.island.pop(0)\n depth = abs(self.grid[i][j])\n for d in D:\n if i + d[0] in range(self.m) and j + d[1] in range(self.n):\n if self.grid[i + d[0]][j + d[1]] == 1:\n return depth - 1\n if self.grid[i + d[0]][j + d[1]] == 0:\n self.island.append([i + d[0], j + d[1]])\n self.grid[i + d[0]][j + d[1]] = -1 * (depth + 1)\n return self.m + self.n - 1\n\ndef shortestbridge(A: List[List[int]]) -> int:\n self.grid = A\n self.m = len(A)\n self.n = len(A[0])\n self.island = []\n for i in range(self.m):\n for j in range(self.n):\n if self.grid[i][j] == 1 and len(self.island) == 0:\n self.find_island(i, j)\n res = self.expand_island()\n return res", "def shortestbridge(A: List[List[int]]) -> int:\n i1 = []\n m = len(A)\n n = len(A[0])\n vis = [[False for _ in range(n)] for _ in range(m)]\n\n def check(x, y):\n return x >= 0 and x < m and (y >= 0) and (y < n)\n dx = [0, -1, 0, 1]\n dy = [1, 0, -1, 0]\n\n def dfs(p_x, p_y, i):\n vis[p_x][p_y] = True\n i.append((p_x, p_y))\n for j in range(4):\n (c_x, c_y) = (p_x + dx[j], p_y + dy[j])\n if check(c_x, c_y) and (not vis[c_x][c_y]):\n if A[c_x][c_y]:\n dfs(c_x, c_y, i)\n conn = 0\n for i in range(m):\n for j in range(n):\n if not vis[i][j] and A[i][j]:\n if conn == 0:\n dfs(i, j, i1)\n elif conn == 1:\n break\n conn += 1\n if conn == 1:\n break\n q = deque()\n d = [[float('inf') for _ in range(n)] for _ in range(m)]\n for v in i1:\n q.append(v)\n d[v[0]][v[1]] = 0\n ans = float('inf')\n while q:\n (s_x, s_y) = (q[0][0], q[0][1])\n q.popleft()\n for i in range(4):\n (c_x, c_y) = (s_x + dx[i], s_y + dy[i])\n if check(c_x, c_y):\n if d[c_x][c_y] > d[s_x][s_y] + 1:\n d[c_x][c_y] = d[s_x][s_y] + 1\n q.append((c_x, c_y))\n if A[c_x][c_y]:\n ans = min(ans, d[c_x][c_y] - 1)\n return ans", "def shortestbridge(A: List[List[int]]) -> int:\n self.A = A\n self.R = len(self.A)\n self.C = len(self.A[0])\n p = self.findGround()\n if p == None:\n return -1\n self.firstIsland = set()\n self.embraceIsland(p)\n return self.bfs()\n\ndef findGround():\n for i in range(0, self.R):\n for j in range(0, self.C):\n if self.isGround((i, j)):\n return (i, j)\n return None\n\ndef isGround(p):\n return self.A[p[0]][p[1]] == 1\n\ndef inGrid(p):\n if not 0 <= p[0] < self.R:\n return False\n if not 0 <= p[1] < self.C:\n return False\n return True\n\ndef getNeis(p):\n neis = []\n neis.append((p[0] + 1, p[1]))\n neis.append((p[0] - 1, p[1]))\n neis.append((p[0], p[1] + 1))\n neis.append((p[0], p[1] - 1))\n return neis\n\ndef embraceIsland(p):\n self.firstIsland.add(p)\n for nei in self.getNeis(p):\n if self.inGrid(nei) and self.isGround(nei) and (nei not in self.firstIsland):\n self.embraceIsland(nei)\n\ndef bfs():\n q = collections.deque()\n visited = set()\n for p in self.firstIsland:\n q.appendleft((p, 0))\n while q:\n (node, dist) = q.pop()\n if self.isGround(node) and node not in self.firstIsland:\n return dist - 1\n if node in visited:\n continue\n visited.add(node)\n for nei in self.getNeis(node):\n if self.inGrid(nei) and nei not in visited:\n q.appendleft((nei, dist + 1))\n return -1", "def paint(A, i, j):\n if i >= len(A) or i < 0 or j < 0 or (j >= len(A[0])) or (A[i][j] == 0) or (A[i][j] == 2):\n return\n A[i][j] = 2\n for nb in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n self.paint(A, i + nb[0], j + nb[1])\n\ndef expand(A, i, j, color):\n if i >= len(A) or i < 0 or j < 0 or (j >= len(A[0])):\n return False\n if A[i][j] == 0:\n A[i][j] = color + 1\n return A[i][j] == 1\n\ndef shortestbridge(A: List[List[int]]) -> int:\n if not A:\n return 0\n (m, n, flag) = (len(A), len(A[0]), False)\n for i in range(m):\n if flag:\n break\n for j in range(n):\n if A[i][j] == 1:\n self.paint(A, i, j)\n flag = True\n break\n for color in range(2, 2 + m + n + 1):\n for i in range(m):\n for j in range(n):\n if A[i][j] == color and (self.expand(A, i - 1, j, color) or self.expand(A, i, j + 1, color) or self.expand(A, i + 1, j, color) or self.expand(A, i, j - 1, color)):\n return color - 2", "def shortestbridge(A: List[List[int]]) -> int:\n u = {(i, j): (i, j) for i in range(len(A)) for j in range(len(A[0])) if A[i][j]}\n\n def head(p):\n if u[p] == p:\n return p\n h = head(u[p])\n u[p] = h\n return h\n\n def union(p1, p2):\n u[head(p2)] = head(p1)\n for (i, row) in enumerate(A):\n for (j, v) in enumerate(row):\n if not v:\n continue\n if i and A[i - 1][j]:\n union((i - 1, j), (i, j))\n if j and A[i][j - 1]:\n union((i, j - 1), (i, j))\n grps = {p1: set() for (p1, p2) in list(u.items()) if p1 == p2}\n for p in list(u.keys()):\n grps[head(p)].add(p)\n grps = list(grps.values())\n s = 0\n (layer, target) = grps\n while layer:\n new_layer = []\n for (x, y) in layer:\n for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n nx = x + dx\n ny = y + dy\n if nx < 0 or nx >= len(A) or ny < 0 or (ny >= len(A[0])):\n continue\n if A[nx][ny] == 1 and (nx, ny) in target:\n return s\n if not A[nx][ny]:\n new_layer.append((nx, ny))\n A[nx][ny] = -1\n s += 1\n layer = new_layer\n return", "def shortestbridge(A: List[List[int]]) -> int:\n r = len(A)\n c = len(A[0])\n dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n dist = [[float('inf') for j in range(c)] for i in range(r)]\n island1 = set()\n island2 = set()\n\n def dfs(x, y, island):\n island.add((x, y))\n for (i, j) in dirs:\n if 0 <= x + i < r and 0 <= y + j < c and (A[x + i][y + j] == 1) and ((x + i, y + j) not in island):\n dfs(x + i, y + j, island)\n for i in range(r):\n for j in range(c):\n if A[i][j] == 1:\n if len(island1) == 0:\n dfs(i, j, island1)\n elif (i, j) not in island1:\n dfs(i, j, island2)\n q = collections.deque(list(island1))\n d = 1\n res = float('inf')\n while q:\n size = len(q)\n for i in range(size):\n (x, y) = q.popleft()\n for (i, j) in dirs:\n if 0 <= x + i < r and 0 <= y + j < c:\n if A[x + i][y + j] == 0 and d < dist[x + i][y + j]:\n q.append((x + i, y + j))\n dist[x + i][y + j] = d\n if (x + i, y + j) in island2:\n res = min(res, d - 1)\n d += 1\n return res", "def shortestbridge(A: List[List[int]]) -> int:\n gather = []\n for y in range(len(A)):\n for x in range(len(A[y])):\n if A[y][x] == 1:\n A[y][x] = 2\n gather.append((x, y, 0))\n break\n if gather:\n break\n dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n seen = set([gather[0]])\n while gather:\n frontier = []\n for (x, y, _) in gather:\n for (dx, dy) in dirs:\n (xx, yy) = (x + dx, y + dy)\n if (xx, yy, 0) in seen:\n continue\n if 0 <= yy < len(A) and 0 <= xx < len(A[yy]) and (A[yy][xx] == 1):\n A[yy][xx] = 2\n seen.add((xx, yy, 0))\n frontier.append((xx, yy, 0))\n gather = frontier\n bfs = list(seen)\n while bfs:\n frontier = []\n for (x, y, n) in bfs:\n A[y][x] = 2\n for (dx, dy) in dirs:\n (xx, yy) = (x + dx, y + dy)\n if 0 <= yy < len(A) and 0 <= xx < len(A[yy]):\n if A[yy][xx] == 1:\n return n\n elif A[yy][xx] == 0:\n A[yy][xx] = 2\n frontier.append((xx, yy, n + 1))\n bfs = frontier\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n (R, C) = (len(A), len(A[0]))\n dist = [[float('inf')] * C for _ in range(R)]\n directs = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n src = None\n for r in range(R):\n for c in range(C):\n if A[r][c] == 1:\n dist[r][c] = 0\n src = (r, c)\n if src:\n break\n if src:\n break\n queue = [(0, r, c)]\n while queue:\n (d, r, c) = heapq.heappop(queue)\n for (dr, dc) in directs:\n (nr, nc) = (r + dr, c + dc)\n if not (0 <= nr < R and 0 <= nc < C):\n continue\n enqueue = False\n if A[nr][nc] == 1 and A[r][c] == 1:\n if d < dist[nr][nc]:\n dist[nr][nc] = d\n enqueue = True\n elif d + 1 < dist[nr][nc]:\n dist[nr][nc] = d + 1\n enqueue = True\n if enqueue:\n heapq.heappush(queue, (dist[nr][nc], nr, nc))\n ans = float('inf')\n for r in range(R):\n for c in range(C):\n if A[r][c] == 1 and dist[r][c] > 0:\n ans = min(ans, dist[r][c] - 1)\n return ans", "def shortestbridge(A: List[List[int]]) -> int:\n queue = []\n\n def markIsland2(i, j):\n if i < 0 or i >= len(A) or j < 0 or (j >= len(A)):\n return False\n if A[i][j] == 2:\n return False\n if A[i][j] == 0:\n return True\n A[i][j] = 2\n shore = False\n for (x, y) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n shore |= markIsland2(i + x, j + y)\n if shore:\n queue.append((i, j))\n return False\n flag = False\n for i in range(len(A)):\n if flag:\n break\n for j in range(len(A)):\n if A[i][j] == 1:\n markIsland2(i, j)\n flag = True\n break\n\n def BFS(i, j):\n queue.append((i, j))\n for (x, y) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n if 0 <= i + x < len(A) and 0 <= j + y < len(A):\n if A[i + x][j + y] == 1:\n return True\n elif A[i + x][j + y] == 0:\n A[i + x][j + y] = 2\n queue.append((i + x, j + y))\n else:\n return False\n cnt = 0\n while queue:\n size = len(queue)\n for _ in range(size):\n (i, j) = queue.pop(0)\n if BFS(i, j):\n return cnt\n cnt += 1", "def shortestbridge(A: List[List[int]]) -> int:\n\n def dfs(A, i, j):\n if i < 0 or j < 0 or i > len(A) - 1 or (j > len(A[0]) - 1):\n return\n if visited[i][j] or A[i][j] == 0:\n return\n visited[i][j] = True\n queue.append((i, j))\n for k in range(4):\n rr = i + rowVector[k]\n cc = j + colVector[k]\n dfs(A, rr, cc)\n visited = [[False for i in range(len(A[0]))] for j in range(len(A))]\n rowVector = [1, -1, 0, 0]\n colVector = [0, 0, 1, -1]\n queue = []\n found = False\n for i in range(len(A)):\n if found:\n break\n for j in range(len(A[0])):\n if A[i][j] == 1:\n dfs(A, i, j)\n found = True\n break\n count = 0\n while queue:\n subQ = []\n while queue:\n temp = queue.pop(0)\n for k in range(4):\n i = temp[0] + rowVector[k]\n j = temp[1] + colVector[k]\n if i < 0 or j < 0 or i > len(A) - 1 or (j > len(A[0]) - 1) or visited[i][j]:\n continue\n if A[i][j] == 1:\n return count\n subQ.append((i, j))\n visited[i][j] = True\n queue = subQ\n count += 1\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n (R, C) = (len(A), len(A[0]))\n\n def getNeighbors(curr_points):\n neighbors = set()\n for (i, j) in curr_points:\n for (row, col) in [(i + 1, j), (i - 1, j), (i, j - 1), (i, j + 1)]:\n if 0 <= row < R and 0 <= col < C:\n neighbors.add((row, col))\n return neighbors\n\n def get_islands():\n\n def dfs(pos, visited):\n (i, j) = pos\n if i >= R or i < 0 or j >= C or (j < 0) or (A[i][j] == 0) or (pos in visited):\n return\n visited.add(pos)\n dfs((i + 1, j), visited)\n dfs((i - 1, j), visited)\n dfs((i, j + 1), visited)\n dfs((i, j - 1), visited)\n (island1, island2) = (set(), set())\n for i in range(R):\n for j in range(C):\n if A[i][j] == 1:\n if not island1:\n dfs((i, j), island1)\n elif not island2 and (i, j) not in island1:\n dfs((i, j), island2)\n return (island1, island2)\n (island1, island2) = get_islands()\n min_distance = 0\n while True:\n neighbors = getNeighbors(island1)\n for neighbor in neighbors:\n if neighbor in island2:\n return min_distance\n island1.add(neighbor)\n min_distance += 1\n return min_distance\n\ndef dist(x, y):\n return abs(x[0] - y[0]) + abs(x[1] - y[1]) - 1", "import numpy as np\n\ndef shortestbridge(A: List[List[int]]) -> int:\n (self.R, self.C) = (len(A), len(A[0]))\n self.queue = []\n self.visited = []\n for k in range(self.R):\n self.visited.append([0] * self.C)\n count = 0\n for rr in range(self.R):\n for cc in range(self.C):\n if A[rr][cc] == 1:\n self.dfs(A, rr, cc)\n count = 1\n if count > 0:\n break\n if count > 0:\n break\n while self.queue:\n node_visit = self.queue.pop(0)\n q_step = node_visit.step\n for (r_srch, c_srch) in self.dirs(A, node_visit.r, node_visit.c):\n if A[r_srch][c_srch] == 0 and self.visited[r_srch][c_srch] == 0:\n self.queue.append(self.node(q_step + 1, r_srch, c_srch))\n self.visited[r_srch][c_srch] = 1\n if A[r_srch][c_srch] == 1:\n return q_step\n\ndef dirs(A, r, c) -> int:\n dir_list = []\n for (rr, cc) in [[r - 1, c], [r + 1, c], [r, c - 1], [r, c + 1]]:\n if rr >= 0 and cc >= 0 and (rr < self.R) and (cc < self.C):\n dir_list.append([rr, cc])\n return dir_list\n\ndef dfs(A, r, c):\n if A[r][c] != 1:\n return\n A[r][c] = 2\n self.queue.append(self.node(0, r, c))\n self.visited[r][c] = 1\n for (r_srch, c_srch) in self.dirs(A, r, c):\n self.dfs(A, r_srch, c_srch)", "def shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n visited = [[False] * n for _ in range(m)]\n directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]\n\n def findFirstIsland():\n for r in range(m):\n for c in range(n):\n if A[r][c] == 1:\n return (r, c)\n queue = deque()\n\n def dfs(r, c):\n if visited[r][c]:\n return\n visited[r][c] = True\n if isBoundary(r, c):\n queue.append((r, c, -1))\n for (dr, dc) in directions:\n (nr, nc) = (r + dr, c + dc)\n if not (0 <= nr < m and 0 <= nc < n):\n continue\n if A[nr][nc] == 1 and (not visited[nr][nc]):\n dfs(nr, nc)\n\n def isBoundary(r, c):\n for (dr, dc) in directions:\n (nr, nc) = (r + dr, c + dc)\n if not (0 <= nr < m and 0 <= nc < n):\n continue\n if A[nr][nc] == 0:\n return True\n return False\n (sr, sc) = findFirstIsland()\n dfs(sr, sc)\n visited2 = [[False] * n for _ in range(m)]\n while queue:\n (r, c, d) = queue.popleft()\n visited2[r][c] = True\n if not visited[r][c] and A[r][c] == 1:\n return d\n for (dr, dc) in directions:\n (nr, nc) = (r + dr, c + dc)\n if not (0 <= nr < m and 0 <= nc < n):\n continue\n if not visited2[nr][nc]:\n visited2[nr][nc] = True\n queue.append((nr, nc, d + 1))\n return 1", "from collections import deque\n\ndef shortestbridge(A: List[List[int]]) -> int:\n\n def get_edges(visited, A, i, j, isle):\n dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n queue = deque([(i, j)])\n visited[i][j] = True\n edges = set()\n while queue:\n edge = 0\n (ci, cj) = queue.popleft()\n for (di, dj) in dirs:\n x = ci + di\n y = cj + dj\n if 0 <= x < m and 0 <= y < n and (A[x][y] == 1) and (not visited[x][y]):\n queue.append((x, y))\n visited[x][y] = True\n elif 0 <= x < m and 0 <= y < n and (A[x][y] == 0):\n edge = 1\n if edge:\n edges.add((ci, cj))\n return edges\n\n def manattan(a, b, c, d):\n return abs(a - c) + abs(b - d) - 1\n visited = [[0] * len(A[0]) for i in range(len(A))]\n m = len(A)\n n = len(A[0])\n edge_islands = []\n counts = 0\n for ii in range(m):\n for jj in range(n):\n if A[ii][jj] == 1 and (not visited[ii][jj]):\n counts += 1\n edge_islands.append(get_edges(visited, A, ii, jj, counts))\n isle1 = edge_islands[0]\n isle2 = edge_islands[1]\n mins = float('inf')\n for i1 in isle1:\n for i2 in isle2:\n mins = min(mins, manattan(i1[0], i1[1], i2[0], i2[1]))\n return mins", "def shortestbridge(A: List[List[int]]) -> int:\n M = len(A)\n N = len(A[0])\n q = collections.deque()\n i0 = None\n j0 = None\n for i in range(M):\n for j in range(N):\n if A[i][j] == 1:\n (i0, j0) = (i, j)\n break\n if i0 is not None:\n break\n q.append((i0, j0))\n A[i0][j0] = 2\n vis = set()\n dirs_lst = [(-1, 0), (1, 0), (0, 1), (0, -1)]\n boarder = set()\n while q:\n (i, j) = q.popleft()\n for (di, dj) in dirs_lst:\n ni = i + di\n nj = j + dj\n if ni < 0 or ni > M - 1 or nj < 0 or (nj > N - 1):\n boarder.add((i, j))\n continue\n if A[ni][nj] == 0:\n boarder.add((i, j))\n continue\n if (ni, nj) in vis:\n continue\n A[ni][nj] = 2\n vis.add((ni, nj))\n q.append((ni, nj))\n vis.clear()\n for (i, j) in boarder:\n q.append((i, j, 0))\n res = math.inf\n while q:\n (i, j, nsteps) = q.popleft()\n for (di, dj) in dirs_lst:\n ni = i + di\n nj = j + dj\n if ni < 0 or ni > M - 1 or nj < 0 or (nj > N - 1):\n continue\n if (ni, nj) in vis:\n continue\n if A[ni][nj] == 1:\n res = min(res, nsteps)\n continue\n vis.add((ni, nj))\n q.append((ni, nj, nsteps + 1))\n return res", "def shortestbridge(mat: List[List[int]]) -> int:\n R = len(mat)\n C = len(mat and mat[0])\n\n def expand(island, other):\n new = set()\n for (r, c) in island:\n for (nr, nc) in ((r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)):\n if R > nr >= 0 <= nc < C:\n if (nr, nc) in other:\n return True\n if mat[nr][nc] == 0:\n mat[nr][nc] = 2\n new.add((nr, nc))\n island.update(new)\n\n def findIsland(r, c, island):\n island.add((r, c))\n mat[r][c] = 2\n for (nr, nc) in ((r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)):\n if R > nr >= 0 <= nc < C and mat[nr][nc] == 1 and ((nr, nc) not in island):\n findIsland(nr, nc, island)\n islands = []\n for r in range(R):\n for c in range(C):\n if mat[r][c] == 1:\n island = set()\n findIsland(r, c, island)\n islands.append(island)\n ans = 0\n while True:\n if expand(*islands):\n return ans\n ans += 1", "def shortestbridge(A: List[List[int]]) -> int:\n (R, C) = (len(A), len(A[0]))\n dist = [[float('inf')] * C for _ in range(R)]\n directs = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n\n def findSrc():\n for r in range(R):\n for c in range(C):\n if A[r][c] == 1:\n return (r, c)\n (r, c) = findSrc()\n dist[r][c] = 0\n queue = [(0, r, c)]\n\n def neighbors(r, c):\n for (nr, nc) in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]:\n if 0 <= nr < R and 0 <= nc < C:\n yield (nr, nc)\n while queue:\n (d, r, c) = heapq.heappop(queue)\n for (nr, nc) in neighbors(r, c):\n enqueue = False\n if A[nr][nc] == 1 and A[r][c] == 1:\n if d < dist[nr][nc]:\n dist[nr][nc] = d\n enqueue = True\n elif d + 1 < dist[nr][nc]:\n dist[nr][nc] = d + 1\n enqueue = True\n if enqueue:\n heapq.heappush(queue, (dist[nr][nc], nr, nc))\n ans = float('inf')\n for r in range(R):\n for c in range(C):\n if A[r][c] == 1 and dist[r][c] > 0:\n ans = min(ans, dist[r][c] - 1)\n return ans", "from math import sqrt\n\ndef shortestbridge(A: List[List[int]]) -> int:\n\n def get_islands(A):\n island_one = set()\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1 and (i, j) not in island_one:\n if not island_one:\n island_one = make_island(A, i, j, set())\n else:\n return (island_one, make_island(A, i, j, set()))\n\n def make_island(A, i, j, visited):\n visited.add((i, j))\n up = A[i][j + 1] if j < len(A[0]) - 1 else 0\n down = A[i][j - 1] if j > 0 else 0\n left = A[i - 1][j] if i > 0 else 0\n right = A[i + 1][j] if i < len(A) - 1 else 0\n if up and (i, j + 1) not in visited:\n make_island(A, i, j + 1, visited)\n if down and (i, j - 1) not in visited:\n make_island(A, i, j - 1, visited)\n if left and (i - 1, j) not in visited:\n make_island(A, i - 1, j, visited)\n if right and (i + 1, j) not in visited:\n make_island(A, i + 1, j, visited)\n return visited\n\n def find_shortest_bridge(A, i, j, start_island, global_dist_map):\n queue = [(i, j)]\n dist_map = {(i, j): 0}\n while queue:\n (i, j) = queue.pop(0)\n neighbors = []\n if (i, j + 1) not in start_island and j < len(A[0]) - 1:\n neighbors.append((i, j + 1))\n if (i, j - 1) not in start_island and j > 0:\n neighbors.append((i, j - 1))\n if (i - 1, j) not in start_island and i > 0:\n neighbors.append((i - 1, j))\n if (i + 1, j) not in start_island and i < len(A) - 1:\n neighbors.append((i + 1, j))\n for neighbor in neighbors:\n (n_i, n_j) = neighbor\n if A[n_i][n_j] == 1:\n return dist_map[i, j] + 1\n if neighbor not in global_dist_map or global_dist_map[neighbor] > dist_map[i, j] + 1:\n queue.append(neighbor)\n global_dist_map[neighbor] = dist_map[neighbor] = dist_map[i, j] + 1\n return False\n\n def find_shortest_pair(island1, island2):\n min_distance = len(A) * len(A[0])\n shortest_coords = None\n for coords1 in island1:\n for coords2 in island2:\n distance_between = sqrt((coords2[0] - coords1[0]) ** 2 + (coords2[1] - coords1[1]) ** 2)\n if distance_between < min_distance:\n min_distance = distance_between\n shortest_coords = (coords1, coords2)\n return shortest_coords\n (first_island, second_island) = get_islands(A)\n min_island = first_island if len(first_island) < len(second_island) else second_island\n shortest_bridge = len(A) * len(A[0])\n global_dist_map = {}\n for island in min_island:\n (i, j) = island\n shortest_bridge_here = find_shortest_bridge(A, i, j, min_island, global_dist_map)\n if shortest_bridge_here:\n shortest_bridge = min(shortest_bridge, shortest_bridge_here)\n return shortest_bridge - 1", "def shortestbridge(A: List[List[int]]) -> int:\n\n def get_islands(A):\n island_one = set()\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1 and (i, j) not in island_one:\n if not island_one:\n island_one = make_island(A, i, j, set())\n else:\n return (island_one, make_island(A, i, j, set()))\n\n def make_island(A, i, j, visited):\n visited.add((i, j))\n up = A[i][j + 1] if j < len(A[0]) - 1 else 0\n down = A[i][j - 1] if j > 0 else 0\n left = A[i - 1][j] if i > 0 else 0\n right = A[i + 1][j] if i < len(A) - 1 else 0\n if up and (i, j + 1) not in visited:\n make_island(A, i, j + 1, visited)\n if down and (i, j - 1) not in visited:\n make_island(A, i, j - 1, visited)\n if left and (i - 1, j) not in visited:\n make_island(A, i - 1, j, visited)\n if right and (i + 1, j) not in visited:\n make_island(A, i + 1, j, visited)\n return visited\n\n def find_shortest_bridge(A, i, j, start_island, global_dist_map):\n queue = [(i, j)]\n dist_map = {(i, j): 0}\n while queue:\n (i, j) = queue.pop(0)\n neighbors = []\n if (i, j + 1) not in start_island and j < len(A[0]) - 1:\n neighbors.append((i, j + 1))\n if (i, j - 1) not in start_island and j > 0:\n neighbors.append((i, j - 1))\n if (i - 1, j) not in start_island and i > 0:\n neighbors.append((i - 1, j))\n if (i + 1, j) not in start_island and i < len(A) - 1:\n neighbors.append((i + 1, j))\n for neighbor in neighbors:\n (n_i, n_j) = neighbor\n if A[n_i][n_j] == 1:\n return dist_map[i, j] + 1\n if neighbor not in global_dist_map or global_dist_map[neighbor] > dist_map[i, j] + 1:\n queue.append(neighbor)\n global_dist_map[neighbor] = dist_map[neighbor] = dist_map[i, j] + 1\n return False\n (first_island, second_island) = get_islands(A)\n min_island = first_island if len(first_island) < len(second_island) else second_island\n shortest_bridge = len(A) * len(A[0])\n global_dist_map = {}\n for island in min_island:\n (i, j) = island\n shortest_bridge_here = find_shortest_bridge(A, i, j, min_island, global_dist_map)\n if shortest_bridge_here:\n shortest_bridge = min(shortest_bridge, shortest_bridge_here)\n return shortest_bridge - 1", "def shortestbridge(A: List[List[int]]) -> int:\n self.map = A\n self.rows = len(self.map)\n self.cols = len(self.map[0])\n self.queue = []\n self.src = 2\n self.dst = 3\n for island_index in [self.src, self.dst]:\n add_to_queue = island_index == self.src\n self.exploreIsland(island_index, add_to_queue)\n self.queue_index = 0\n return self.bridgeBFS()\n\ndef exploreIsland(index, add):\n (row, col) = self.getIslandLocation()\n self.islandDFS(index, row, col, add)\n\ndef getIslandLocation():\n for row in range(self.rows):\n for col in range(self.cols):\n if self.map[row][col] == 1:\n return (row, col)\n\ndef islandDFS(index, row, col, add):\n if self.validCoords(row, col) and self.map[row][col] == 1:\n self.map[row][col] = index\n if add:\n self.queue.append((row, col, 0))\n for search_row in range(row - 1, row + 2, 2):\n self.islandDFS(index, search_row, col, add)\n for search_col in range(col - 1, col + 2, 2):\n self.islandDFS(index, row, search_col, add)\n\ndef validCoords(row, col):\n if row < 0 or row >= self.rows:\n return False\n if col < 0 or col >= self.cols:\n return False\n return True\n\ndef bridgeBFS():\n while self.queue_index < len(self.queue):\n (row, col, dist) = self.queue[self.queue_index]\n self.queue_index += 1\n for search_row in range(row - 1, row + 2, 2):\n if self.processCoord(search_row, col, dist):\n return dist\n for search_col in range(col - 1, col + 2, 2):\n if self.processCoord(row, search_col, dist):\n return dist\n\ndef processCoord(row, col, dist):\n if not self.validCoords(row, col):\n return False\n if self.map[row][col] == self.dst:\n return True\n elif self.map[row][col] != self.src:\n self.queue.append((row, col, dist + 1))\n self.map[row][col] = self.src\n return False", "def dfs(A, i, j, replace):\n if i < 0 or i >= len(A) or j < 0 or (j >= len(A[0])):\n return\n if A[i][j] == 0 or A[i][j] == replace:\n return\n A[i][j] = replace\n r = self.dfs(A, i + 1, j, replace)\n d = self.dfs(A, i, j + 1, replace)\n u = self.dfs(A, i - 1, j, replace)\n l = self.dfs(A, i, j - 1, replace)\n return\n\ndef find(A, i, j, old):\n if i < 0 or i >= len(A) or j < 0 or (j >= len(A[0])):\n return False\n if A[i][j] == -1:\n return True\n if A[i][j] == 0:\n A[i][j] = old + 1\n return False\n if A[i][j] == old + 1:\n return False\n A[i][j] = old + 1\n return self.find(A, i + 1, j, old) or self.find(A, i - 1, j, old) or self.find(A, i, j + 1, old) or self.find(A, i, j - 1, old)\n\ndef shortestbridge(A: List[List[int]]) -> int:\n iindex = 0\n (i, j) = (0, 0)\n replace = -1\n start = ()\n while i < len(A):\n j = 0\n while j < len(A[0]):\n if A[i][j] == 1:\n self.dfs(A, i, j, replace)\n iindex += 1\n replace = -2\n start = (i, j)\n j += 1\n i += 1\n old = 1\n while True:\n if self.find(A, start[0], start[1], old):\n break\n old += 1\n return old - 1", "import collections\n\ndef shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n\n def neighbors(r, c):\n for (nr, nc) in ((r - 1, c), (r, c - 1), (r + 1, c), (r, c + 1)):\n if 0 <= nr < m and 0 <= nc < n:\n yield (nr, nc)\n seen = set()\n islands = {2: set(), 3: set()}\n\n def color_island(r, c, island_id):\n seen.add((r, c))\n if A[r][c] != 1:\n return\n A[r][c] = island_id\n islands[island_id].add((r, c))\n for (x, y) in neighbors(r, c):\n if (x, y) not in seen:\n color_island(x, y, island_id)\n islands_found = 0\n for r in range(m):\n if islands_found == 2:\n break\n for c in range(n):\n if islands_found == 2:\n break\n if A[r][c] == 1:\n islands_found += 1\n color_island(r, c, islands_found + 1)\n source = islands[2]\n target = islands[3]\n queue = collections.deque([(node, 0) for node in source])\n seen = source\n while queue:\n ((r, c), d) = queue.popleft()\n if (r, c) in target:\n return d - 1\n for (x, y) in neighbors(r, c):\n if (x, y) not in seen:\n queue.append(((x, y), d + 1))\n seen.add((x, y))", "def shortestbridge(A: List[List[int]]) -> int:\n if not A:\n return 0\n (m, n) = (len(A), len(A[0]))\n queue = collections.deque()\n found = False\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n self.dfs(A, i, j, m, n, queue)\n found = True\n break\n if found:\n break\n bridge = 0\n while queue:\n for _ in range(len(queue)):\n (x, y) = queue.popleft()\n for d in self.DIRS:\n (next_x, next_y) = (x + d[0], y + d[1])\n if 0 <= next_x < m and 0 <= next_y < n and (A[next_x][next_y] == 0):\n queue.append((next_x, next_y))\n A[next_x][next_y] = 2\n if 0 <= next_x < m and 0 <= next_y < n and (A[next_x][next_y] == 1):\n return bridge\n bridge += 1\n return bridge\n\ndef dfs(A, i, j, m, n, queue):\n if i < 0 or i >= m or j < 0 or (j >= n) or (A[i][j] != 1):\n return\n A[i][j] = 2\n queue.append((i, j))\n self.dfs(A, i + 1, j, m, n, queue)\n self.dfs(A, i - 1, j, m, n, queue)\n self.dfs(A, i, j + 1, m, n, queue)\n self.dfs(A, i, j - 1, m, n, queue)", "from typing import List\nfrom queue import Queue\n\ndef shortestbridge(A: List[List[int]]) -> int:\n (first_island, second_island) = (set(), set())\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n\n def get_all(x, y, island):\n if (x, y) in island or A[y][x] == 0:\n return\n island.add((x, y))\n for (dx, dy) in directions:\n if 0 <= x + dx < len(A[0]) and 0 <= y + dy < len(A):\n get_all(x + dx, y + dy, island)\n first_in = False\n for y in range(len(A)):\n for x in range(len(A[0])):\n if A[y][x] == 1:\n if not first_in:\n get_all(x, y, first_island)\n first_in = True\n elif (x, y) not in first_island:\n get_all(x, y, second_island)\n break\n visited = set()\n q = Queue()\n for (x, y) in first_island:\n q.put((x, y, 0))\n while not q.empty():\n (x, y, depth) = q.get()\n if (x, y) in second_island:\n return depth - 1\n for (dx, dy) in directions:\n (X, Y) = (x + dx, y + dy)\n if 0 <= X < len(A[0]) and 0 <= Y < len(A) and ((X, Y) not in visited):\n q.put((X, Y, depth + 1))\n visited.add((X, Y))", "def shortestbridge(A: List[List[int]]) -> int:\n if not A:\n return 0\n m = len(A)\n n = len(A[0])\n\n def getnei(i, j):\n xy = []\n if i > 0:\n xy.append((i - 1, j))\n if j > 0:\n xy.append((i, j - 1))\n if i < m - 1:\n xy.append((i + 1, j))\n if j < m - 1:\n xy.append((i, j + 1))\n return xy\n\n def dfs1(i, j):\n if A[i][j] != 1:\n return\n A[i][j] = -1\n for (x, y) in getnei(i, j):\n dfs1(x, y)\n\n def bfs(i, j, dist_map, thresh):\n seen = set()\n q = collections.deque()\n q.append((i, j, 0))\n done = False\n while q and (not done):\n (ii, jj, depth) = q.popleft()\n if depth > thresh:\n done = True\n break\n for (x, y) in getnei(ii, jj):\n if (x, y) in dist_map and dist_map[x, y] < depth:\n continue\n if A[x][y] == -1:\n thresh = min(depth, thresh)\n done = True\n break\n elif A[x][y] == 0:\n if (x, y) in seen:\n continue\n seen.add((x, y))\n q.append((x, y, depth + 1))\n return thresh\n ans = math.inf\n is_second = False\n dist_map = {}\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n if not is_second:\n dfs1(i, j)\n is_second = True\n else:\n ans = min(ans, bfs(i, j, dist_map, ans))\n return ans", "def shortestbridge(A: List[List[int]]) -> int:\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n (islands, index) = ([set(), set()], -1)\n visited = set()\n\n def traverse(current):\n nonlocal A, islands, index, visited, directions\n islands[index].add(current)\n for d in directions:\n (new_i, new_j) = (current[0] + d[0], current[1] + d[1])\n if 0 <= new_i < len(A) and 0 <= new_j < len(A[0]) and ((new_i, new_j) not in visited) and (A[new_i][new_j] == 1):\n visited.add((new_i, new_j))\n traverse((new_i, new_j))\n for i in range(len(A)):\n for j in range(len(A[0])):\n if (i, j) not in visited and A[i][j] == 1:\n index += 1\n traverse((i, j))\n (one, two) = islands\n result = sys.maxsize\n for index in one:\n visited = set()\n queue = collections.deque([(index, 0)])\n while queue:\n current = queue.popleft()\n if current[1] >= result:\n break\n for d in directions:\n (new_i, new_j) = (current[0][0] + d[0], current[0][1] + d[1])\n if 0 <= new_i < len(A) and 0 <= new_j < len(A[0]) and ((new_i, new_j) not in one) and ((new_i, new_j) not in visited):\n if (new_i, new_j) in two:\n result = min(result, current[1])\n break\n visited.add((new_i, new_j))\n queue.append(((new_i, new_j), current[1] + 1))\n return result", "def shortestbridge(A: List[List[int]]) -> int:\n rows = len(A)\n cols = len(A[0])\n\n def getNeighbors(i, j):\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if x >= 0 and x < rows and (y >= 0) and (y < cols):\n yield (x, y)\n\n def findComponents():\n visited = set()\n connectedNodes = [[] for i in range(2)]\n\n def findConnnectedComponent(i, j):\n visited.add((i, j))\n connectedNodes[connectedCompNumber].append((i, j))\n for (x, y) in getNeighbors(i, j):\n if (x, y) not in visited and A[x][y]:\n findConnnectedComponent(x, y)\n connectedCompNumber = -1\n for i in range(rows):\n for j in range(cols):\n if (i, j) not in visited and A[i][j] == 1:\n connectedCompNumber += 1\n findConnnectedComponent(i, j)\n return connectedNodes\n\n def findDistance() -> int:\n shortedDist = 1\n (source, target) = findComponents()\n queue = collections.deque()\n for s in source:\n queue.appendleft((s, 0))\n done = set()\n for s in source:\n done.add(s)\n while queue:\n (node, dist) = queue.pop()\n if node in target:\n return dist - 1\n for n in getNeighbors(*node):\n if n not in done:\n queue.appendleft((n, dist + 1))\n done.add(n)\n return findDistance()", "import collections\n\ndef shortestbridge(A: List[List[int]]) -> int:\n found = False\n res = []\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1:\n self.dfs(A, i, j, res)\n found = True\n break\n if found:\n break\n cnt = 0\n while res:\n tmp = []\n for (x, y) in res:\n for (dx, dy) in ((1, 0), (-1, 0), (0, 1), (0, -1)):\n if 0 <= x + dx < len(A) and 0 <= y + dy < len(A[0]) and (A[x + dx][y + dy] != 2):\n if A[x + dx][y + dy] == 0:\n A[x + dx][y + dy] = 2\n if A[x + dx][y + dy] == 1:\n return cnt\n tmp.append([x + dx, y + dy])\n cnt += 1\n res = tmp\n return -1\n\ndef dfs(A, i, j, res):\n if 0 <= i < len(A) and 0 <= j < len(A[0]) and (A[i][j] == 1):\n A[i][j] = 2\n res.append([i, j])\n self.dfs(A, i + 1, j, res)\n self.dfs(A, i - 1, j, res)\n self.dfs(A, i, j - 1, res)\n self.dfs(A, i, j + 1, res)", "def __init__():\n self.components = []\n self.comp = []\n self.seen = set()\n\ndef isValid(r, c, A):\n if r < 0 or c < 0 or r >= len(A) or (c >= len(A)):\n return False\n return True\n\ndef dfs(r, c, A):\n if not self.isValid(r, c, A) or (r, c) in self.seen or A[r][c] != 1:\n return\n self.comp.append((r, c))\n self.seen.add((r, c))\n self.dfs(r + 1, c, A)\n self.dfs(r - 1, c, A)\n self.dfs(r, c + 1, A)\n self.dfs(r, c - 1, A)\n\ndef shortestbridge(A: List[List[int]]) -> int:\n for i in range(len(A)):\n for j in range(len(A[0])):\n if (i, j) not in self.seen and A[i][j] == 1:\n self.comp = []\n self.dfs(i, j, A)\n self.components.append(self.comp)\n (source, target) = self.components\n visited = set(source)\n queue = collections.deque([(node, 0) for node in source])\n while queue:\n (node, d) = queue.popleft()\n if node in target:\n return d - 1\n else:\n for (dr, dc) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n nr = node[0] + dr\n nc = node[1] + dc\n if (nr, nc) not in visited and self.isValid(nr, nc, A):\n queue.append(((nr, nc), d + 1))\n visited.add((nr, nc))\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n visited = collections.deque()\n flag = False\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n A[i][j] = 2\n visited = self.search(A, i, j, visited)\n flag = True\n break\n if flag == True:\n break\n steps = 0\n vis = collections.deque(visited)\n while visited:\n size = len(visited)\n for i in range(size):\n (row, col) = visited.popleft()\n dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n for d in dirs:\n newrow = row + d[0]\n newcol = col + d[1]\n if 0 <= newrow < len(A) and 0 <= newcol < len(A[0]) and (A[newrow][newcol] == 1):\n return steps\n elif 0 <= newrow < len(A) and 0 <= newcol < len(A[0]) and (A[newrow][newcol] == 0) and ((newrow, newcol) not in vis):\n A[newrow][newcol] = 2\n visited.append((newrow, newcol))\n vis.append((newrow, newcol))\n steps += 1\n return -1\n\ndef search(A, i, j, visited):\n q = collections.deque()\n q.append((i, j))\n visited.append((i, j))\n while q:\n size = len(q)\n for i in range(size):\n (r, c) = q.popleft()\n dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n for d in dirs:\n newr = r + d[0]\n newc = c + d[1]\n if 0 <= newr < len(A) and 0 <= newc < len(A[0]) and (A[newr][newc] == 1) and ((newr, newc) not in visited):\n A[newr][newc] = 2\n q.append((newr, newc))\n visited.append((newr, newc))\n return visited", "def shortestbridge(A: List[List[int]]) -> int:\n (found_y, found_x) = (None, None)\n for y in range(len(A)):\n found_one = False\n for x in range(len(A[0])):\n if A[y][x] == 1:\n (found_y, found_x) = (y, x)\n A = self.invertOnes(y, x, A)\n found_one = True\n break\n if found_one:\n break\n return self.BFS(found_y, found_x, A)\n\ndef invertOnes(y, x, A):\n neighbors = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n stack = []\n stack.append((y, x))\n A[y][x] = -1\n while stack:\n (curr_y, curr_x) = stack.pop(0)\n for neighbor in neighbors:\n (new_y, new_x) = (curr_y + neighbor[0], curr_x + neighbor[1])\n if new_y >= 0 and new_y < len(A) and (new_x >= 0) and (new_x < len(A[0])) and (A[new_y][new_x] == 1):\n A[new_y][new_x] = -1\n stack.append((new_y, new_x))\n return A\n\ndef BFS(y, x, A):\n visited = {}\n neighbors = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n stack = []\n stack.append((y, x, 0))\n visited[y, x] = 0\n min_dist = float('inf')\n while stack:\n (curr_y, curr_x, curr_dist) = stack.pop(0)\n if A[curr_y][curr_x] == 1:\n min_dist = min(min_dist, curr_dist - 1)\n for neighbor in neighbors:\n (new_y, new_x) = (curr_y + neighbor[0], curr_x + neighbor[1])\n if new_y >= 0 and new_y < len(A) and (new_x >= 0) and (new_x < len(A[0])):\n if A[new_y][new_x] == -1:\n new_dist = 0\n else:\n new_dist = curr_dist + 1\n if (new_y, new_x) not in visited:\n stack.append((new_y, new_x, new_dist))\n visited[new_y, new_x] = new_dist\n elif visited[new_y, new_x] > new_dist:\n visited[new_y, new_x] = new_dist\n stack.append((new_y, new_x, new_dist))\n return min_dist", "from collections import deque\n\ndef shortestbridge(A: List[List[int]]) -> int:\n\n def color(x, y):\n dfs = [(x, y)]\n while dfs:\n (a, b) = dfs.pop()\n A[a][b] = 2\n for (mx, my) in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n if 0 <= a + mx < len(A) and 0 <= b + my < len(A[0]):\n if A[a + mx][b + my] == 1:\n dfs.append((a + mx, b + my))\n\n def firstOne():\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j]:\n color(i, j)\n return (i, j)\n point = firstOne()\n self.best = 1000\n\n def findClosest(point):\n visited = {}\n bfs = deque([(point, 0)])\n while bfs:\n (curr, dist) = bfs.popleft()\n if curr in visited:\n if visited[curr] <= dist:\n continue\n visited[curr] = dist\n for (x, y) in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n cx = curr[0] + x\n cy = curr[1] + y\n if 0 <= cx < len(A) and 0 <= cy < len(A[0]):\n if A[cx][cy] == 2:\n bfs.append(((cx, cy), 0))\n elif A[cx][cy] == 1:\n self.best = min(self.best, dist)\n else:\n bfs.append(((cx, cy), dist + 1))\n findClosest(point)\n return self.best", "def shortestbridge(A: List[List[int]]) -> int:\n q = collections.deque()\n\n def find_first_island():\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1:\n explore_island(i, j)\n return\n\n def explore_island(r, c):\n if not 0 <= r < len(A) or not 0 <= c < len(A[r]) or A[r][c] == -1:\n return\n if A[r][c] == 1:\n A[r][c] = -1\n explore_island(r + 1, c)\n explore_island(r - 1, c)\n explore_island(r, c + 1)\n explore_island(r, c - 1)\n elif A[r][c] == 0:\n q.append((r, c, 1))\n find_first_island()\n while q:\n (cur_r, cur_c, cur_l) = q.popleft()\n for (x, y) in ((cur_r + 1, cur_c), (cur_r - 1, cur_c), (cur_r, cur_c + 1), (cur_r, cur_c - 1)):\n if 0 <= x < len(A) and 0 <= y < len(A[0]):\n if A[x][y] == 1:\n return cur_l\n elif A[x][y] == 0:\n A[x][y] = -1\n q.append((x, y, cur_l + 1))", "from typing import List\nfrom collections import deque as queue\nfrom functools import lru_cache\n\ndef shortestbridge(A: List[List[int]]) -> int:\n n = len(A)\n\n def neighbours(i, j):\n return [neighbour for neighbour in [(i - 1, j) if i > 0 else None, (i + 1, j) if i < n - 1 else None, (i, j - 1) if j > 0 else None, (i, j + 1) if j < n - 1 else None] if neighbour is not None]\n for i in range(n):\n for j in range(n):\n if A[i][j] == 1:\n first = (i, j)\n q = queue([first])\n visited = set()\n visited.add(first)\n while q:\n (i, j) = q.popleft()\n A[i][j] = 2\n for (ni, nj) in neighbours(i, j):\n if (ni, nj) not in visited and A[ni][nj] == 1:\n visited.add((ni, nj))\n q.append((ni, nj))\n min_distance = float('inf')\n for (li, lj) in visited:\n q = queue([(li, lj, 0)])\n water_visited = set()\n while q:\n (i, j, d) = q.popleft()\n for (ni, nj) in neighbours(i, j):\n if A[ni][nj] == 0 and (ni, nj) not in water_visited and (d + 1 < min_distance):\n water_visited.add((ni, nj))\n q.append((ni, nj, d + 1))\n elif A[ni][nj] == 1 and d < min_distance:\n min_distance = d\n if min_distance == 1:\n return 1\n return min_distance", "import queue\n\ndef isOK(x, y, m, n):\n return x >= 0 and y >= 0 and (x < m) and (y < n)\n\ndef isOnEdge(A, x, y, m, n):\n xRows = [0, 0, -1, 1]\n yCols = [-1, 1, 0, 0]\n for i in range(4):\n new_x = x + xRows[i]\n new_y = y + yCols[i]\n if isOK(new_x, new_y, m, n) and A[new_x][new_y] == 0:\n return True\n return False\nimport queue\n\ndef shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n visited = [[False for _ in range(n)] for _ in range(m)]\n\n def dfs(start, island):\n (x, y) = start\n island.append(start)\n visited[x][y] = True\n xRows = [0, 0, -1, 1]\n yCols = [-1, 1, 0, 0]\n for i in range(4):\n new_x = x + xRows[i]\n new_y = y + yCols[i]\n if isOK(new_x, new_y, m, n) and (not visited[new_x][new_y]) and (A[new_x][new_y] == 1):\n dfs((new_x, new_y), island)\n islands = []\n for i in range(m):\n for j in range(n):\n if not visited[i][j] and A[i][j] == 1:\n island = []\n dfs((i, j), island)\n islands.append(island)\n island1 = islands[0]\n island2 = islands[1]\n visited = [[False for _ in range(n)] for _ in range(m)]\n\n def bfs(source_island, target_island, visited):\n q = queue.Queue()\n for start in source_island:\n (x, y) = start\n q.put((x, y, 0))\n cnt = 0\n while q.qsize() > 0:\n start = q.get()\n (x, y, w) = start\n xRows = [0, 0, -1, 1]\n yCols = [-1, 1, 0, 0]\n for i in range(4):\n new_x = x + xRows[i]\n new_y = y + yCols[i]\n if isOK(new_x, new_y, m, n) and (not visited[new_x][new_y]):\n if (new_x, new_y) in target_island:\n return w + 1\n visited[new_x][new_y] = True\n q.put((new_x, new_y, w + 1))\n return bfs(island1, island2, visited) - 1", "def shortestbridge(A: List[List[int]]) -> int:\n count = 0\n borders = collections.defaultdict(list)\n seen = set()\n (x, y) = ([1, -1, 0, 0], [0, 0, 1, -1])\n (m, n) = (len(A), len(A[0]))\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1 and (i, j) not in seen:\n frontier = [(i, j)]\n island = {(i, j)}\n while frontier:\n cur = frontier.pop()\n bord = False\n for k in range(len(x)):\n (r, c) = (cur[0] + x[k], cur[1] + y[k])\n if 0 <= r < m and 0 <= c < n:\n if A[r][c] == 1 and (r, c) not in island:\n frontier.append((r, c))\n island.add((r, c))\n elif A[r][c] == 0:\n borders[count + 1].append(cur)\n count += 1\n seen.update(island)\n if count == 2:\n break\n if count == 2:\n break\n ans = float('inf')\n borders\n for (i, j) in borders[1]:\n for (x, y) in borders[2]:\n ans = min(ans, abs(i - x) + abs(j - y) - 1)\n return ans", "def color(A, i, j, length):\n A[i][j] = 2\n if i > 0:\n if A[i - 1][j] == 1:\n color(A, i - 1, j, length)\n if j > 0:\n if A[i][j - 1] == 1:\n color(A, i, j - 1, length)\n if i < length - 1:\n if A[i + 1][j] == 1:\n color(A, i + 1, j, length)\n if j < length - 1:\n if A[i][j + 1] == 1:\n color(A, i, j + 1, length)\n\ndef expand(A, level, length):\n for i in range(length):\n for j in range(length):\n if A[i][j] == level:\n if i > 0:\n if A[i - 1][j] == 1:\n return level\n elif A[i - 1][j] == 0:\n A[i - 1][j] = level + 1\n if j > 0:\n if A[i][j - 1] == 1:\n return level\n elif A[i][j - 1] == 0:\n A[i][j - 1] = level + 1\n if i < length - 1:\n if A[i + 1][j] == 1:\n return level\n elif A[i + 1][j] == 0:\n A[i + 1][j] = level + 1\n if j < length - 1:\n if A[i][j + 1] == 1:\n return level\n elif A[i][j + 1] == 0:\n A[i][j + 1] = level + 1\n return 0\n\ndef shortestbridge(A):\n length = len(A)\n found = 0\n for i in range(length):\n for j in range(length):\n if A[i][j]:\n found = 1\n color(A, i, j, length)\n if found == 1:\n break\n if found == 1:\n break\n level = 2\n found = 0\n while found == 0:\n found = expand(A, level, length)\n level += 1\n return found - 2", "def shortestbridge(A: List[List[int]]) -> int:\n self.bfs = []\n flag = 1\n step = 0\n for i in range(len(A)):\n if flag:\n for j in range(len(A[0])):\n if A[i][j] == 1:\n self.dfs(A, i, j)\n flag = 0\n break\n while self.bfs:\n size = len(self.bfs)\n while size:\n (i, j) = self.bfs.pop(0)\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= x < len(A) and 0 <= y < len(A[0]):\n if A[x][y] == 1:\n return step\n elif A[x][y] == 0:\n A[x][y] = -1\n self.bfs.append([x, y])\n size -= 1\n step += 1\n return step\n\ndef dfs(A, i, j):\n if i >= len(A) or j >= len(A[0]) or i < 0 or (j < 0) or (A[i][j] != 1):\n return\n A[i][j] = -1\n self.bfs.append([i, j])\n self.dfs(A, i + 1, j)\n self.dfs(A, i - 1, j)\n self.dfs(A, i, j + 1)\n self.dfs(A, i, j - 1)", "def shortestbridge(A: List[List[int]]) -> int:\n row_shifts = [-1, 0, 1, 0]\n col_shifts = [0, 1, 0, -1]\n\n def bfs_mark_first(row, col, mark):\n nonlocal A, row_shifts, col_shifts\n queue = [(row, col)]\n edges = []\n while len(queue) > 0:\n (curr_row, curr_col) = queue.pop(0)\n if A[curr_row][curr_col] == mark:\n continue\n A[curr_row][curr_col] = mark\n add_to_edges = False\n for (row_shift, col_shift) in zip(row_shifts, col_shifts):\n new_row = curr_row + row_shift\n new_col = curr_col + col_shift\n if 0 <= new_row < len(A) and 0 <= new_col < len(A[0]):\n if A[new_row][new_col] == 1:\n queue.append((new_row, new_col))\n else:\n add_to_edges = True\n if add_to_edges:\n edges.append((curr_row, curr_col))\n return edges\n terminate = False\n for row in range(len(A)):\n for col in range(len(A[0])):\n if A[row][col] == 1:\n edges = bfs_mark_first(row, col, -1)\n terminate = True\n break\n if terminate:\n break\n queue = edges\n while len(queue) > 0:\n (curr_row, curr_col) = queue.pop(0)\n for (row_shift, col_shift) in zip(row_shifts, col_shifts):\n new_row = curr_row + row_shift\n new_col = curr_col + col_shift\n if 0 <= new_row < len(A) and 0 <= new_col < len(A[0]):\n if A[new_row][new_col] == 0:\n A[new_row][new_col] = A[curr_row][curr_col] - 1\n queue.append((new_row, new_col))\n if A[new_row][new_col] == 1:\n return abs(A[curr_row][curr_col]) - 1\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n R = len(A)\n C = len(A[0])\n chk = [[0] * C for _ in range(R)]\n q = collections.deque()\n move = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n flag = False\n for i in range(R):\n if flag:\n break\n for j in range(C):\n if A[i][j] == 1:\n self.dfs(i, j, A, chk, q)\n flag = True\n break\n res = 0\n while q:\n size = len(q)\n for _ in range(size):\n (i, j) = q.popleft()\n for m in move:\n (x, y) = (i + m[0], j + m[1])\n if 0 <= x < R and 0 <= y < C:\n chk[x][y] = 1\n if A[x][y] == 1:\n return res\n elif A[x][y] == 0:\n A[x][y] = 2\n q.append((x, y))\n else:\n continue\n res += 1\n return res\n\ndef dfs(i, j, A, chk, q):\n if chk[i][j] == 1:\n return\n chk[i][j] = 1\n R = len(A)\n C = len(A[0])\n move = [[1, 0], [0, 1], [-1, 0], [0, -1]]\n if A[i][j] == 1:\n q.append((i, j))\n A[i][j] = 2\n for m in move:\n x = i + m[0]\n y = j + m[1]\n if 0 <= x < R and 0 <= y < C:\n self.dfs(x, y, A, chk, q)", "def dfs(A, i, j):\n if 0 > i or i >= self.m or 0 > j or (j >= self.n) or (A[i][j] == 0) or (A[i][j] == 2):\n return\n A[i][j] = 2\n self.que.append([i, j])\n for (i0, j0) in self.offset:\n (ii, jj) = (i + i0, j + j0)\n self.dfs(A, ii, jj)\n\ndef shortestbridge(A: List[List[int]]) -> int:\n self.offset = [[-1, 0], [1, 0], [0, -1], [0, 1]]\n (self.m, self.n) = (len(A), len(A[0]))\n self.que = []\n ok = 0\n for i in range(self.m):\n for j in range(self.n):\n if A[i][j]:\n self.dfs(A, i, j)\n ok = 1\n break\n if ok:\n break\n rt = 0\n while len(self.que) > 0:\n qlen = len(self.que)\n for k in range(qlen):\n (i, j) = self.que.pop(0)\n for (i0, j0) in self.offset:\n (ii, jj) = (i + i0, j + j0)\n if 0 <= ii < self.m and 0 <= jj < self.n:\n if A[ii][jj] == 0:\n A[ii][jj] = 3\n self.que.append([ii, jj])\n elif A[ii][jj] == 1:\n return rt\n rt += 1\n return rt", "def shortestbridge(A: List[List[int]]) -> int:\n (x, y) = self.get_first(A)\n q = collections.deque()\n self.dfs(A, x, y, q)\n step = 0\n while q:\n new_q = collections.deque()\n size = len(q)\n for i in range(size):\n (x, y) = q.popleft()\n for d in [[-1, 0], [1, 0], [0, -1], [0, 1]]:\n (nx, ny) = (x + d[0], y + d[1])\n if 0 <= nx < len(A) and 0 <= ny < len(A[0]):\n if A[nx][ny] == 1:\n return step\n elif A[nx][ny] == 0:\n new_q.append([nx, ny])\n A[nx][ny] = -1\n step += 1\n q = new_q\n return -1\n\ndef get_first(A):\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1:\n return (i, j)\n\ndef dfs(A, x, y, q):\n A[x][y] = -1\n q.append([x, y])\n for d in [[-1, 0], [1, 0], [0, -1], [0, 1]]:\n (nx, ny) = (x + d[0], y + d[1])\n if 0 <= nx < len(A) and 0 <= ny < len(A[0]) and (A[nx][ny] == 1):\n self.dfs(A, nx, ny, q)", "def shortestbridge(A: List[List[int]]) -> int:\n originBridge = []\n\n def markBridge(cord):\n x = cord[1]\n y = cord[0]\n A[y][x] = 2\n originBridge.append(cord)\n if x < len(A[y]) - 1:\n if A[y][x + 1] == 1:\n markBridge((y, x + 1))\n if x > 0:\n if A[y][x - 1] == 1:\n markBridge((y, x - 1))\n if y < len(A) - 1:\n if A[y + 1][x] == 1:\n markBridge((y + 1, x))\n if y > 0:\n if A[y - 1][x] == 1:\n markBridge((y - 1, x))\n for y in range(len(A)):\n for x in range(len(A[y])):\n if A[y][x] == 1:\n markBridge((y, x))\n break\n if len(originBridge) > 0:\n break\n moves = 0\n bridgeList = set(originBridge)\n while len(originBridge) > 0:\n newMoves = []\n for b in originBridge:\n y = b[0]\n x = b[1]\n if x > 0:\n if (y, x - 1) not in bridgeList:\n if A[y][x - 1] == 1:\n return moves\n else:\n bridgeList.add((y, x - 1))\n newMoves.append((y, x - 1))\n if x < len(A[y]) - 1:\n if (y, x + 1) not in bridgeList:\n if A[y][x + 1] == 1:\n return moves\n else:\n bridgeList.add((y, x + 1))\n newMoves.append((y, x + 1))\n if y > 0:\n if (y - 1, x) not in bridgeList:\n if A[y - 1][x] == 1:\n return moves\n else:\n bridgeList.add((y - 1, x))\n newMoves.append((y - 1, x))\n if y < len(A) - 1:\n if (y + 1, x) not in bridgeList:\n if A[y + 1][x] == 1:\n return moves\n else:\n bridgeList.add((y + 1, x))\n newMoves.append((y + 1, x))\n originBridge = newMoves\n moves += 1\n return moves", "from collections import deque\ndirections = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n\ndef shortestbridge(A: List[List[int]]) -> int:\n n = len(A)\n m = len(A[0])\n visited = [[False] * m for _ in range(n)]\n q = deque([])\n found = False\n for i in range(n):\n if found:\n break\n for j in range(m):\n if A[i][j] == 1:\n self.dfs(i, j, A, q, visited)\n found = True\n break\n step = 0\n while q:\n for _ in range(len(q)):\n (x, y) = q.popleft()\n for (dx, dy) in directions:\n (nx, ny) = (x + dx, y + dy)\n if not self.isValid(nx, ny, A) or visited[nx][ny]:\n continue\n if A[nx][ny] == 1:\n return step\n q.append((nx, ny))\n visited[nx][ny] = True\n step += 1\n return -1\n\ndef dfs(i, j, A, q, visited):\n if not self.isValid(i, j, A) or visited[i][j] or A[i][j] == 0:\n return\n visited[i][j] = True\n q.append((i, j))\n for (dx, dy) in directions:\n (nx, ny) = (i + dx, j + dy)\n self.dfs(nx, ny, A, q, visited)\n\ndef isValid(i, j, A):\n return i >= 0 and i < len(A) and (j >= 0) and (j < len(A[0]))", "def color(A, i, j):\n if A[i][j] in (0, 2):\n return\n A[i][j] = 2\n if i > 0:\n if A[i - 1][j] == 1:\n color(A, i - 1, j)\n if j > 0:\n if A[i][j - 1] == 1:\n color(A, i, j - 1)\n if i < len(A) - 1:\n if A[i + 1][j] == 1:\n color(A, i + 1, j)\n if j < len(A) - 1:\n if A[i][j + 1] == 1:\n color(A, i, j + 1)\n\ndef expand(A):\n for l in range(2, len(A) ** 2):\n for i in range(len(A)):\n for j in range(len(A)):\n if A[i][j] == l:\n if i > 0:\n if A[i - 1][j] == 0:\n A[i - 1][j] = l + 1\n if A[i - 1][j] == 1:\n return l - 2\n if j > 0:\n if A[i][j - 1] == 0:\n A[i][j - 1] = l + 1\n if A[i][j - 1] == 1:\n return l - 2\n if i < len(A) - 1:\n if A[i + 1][j] == 0:\n A[i + 1][j] = l + 1\n if A[i + 1][j] == 1:\n return l - 2\n if j < len(A) - 1:\n if A[i][j + 1] == 0:\n A[i][j + 1] = l + 1\n if A[i][j + 1] == 1:\n return l - 2\n\ndef shortestbridge(A):\n length = len(A)\n found = 0\n for i in range(length):\n for j in range(length):\n if A[i][j]:\n color(A, i, j)\n found = 1\n break\n if found == 1:\n break\n expansion = expand(A)\n return expansion", "from random import randint\nfrom collections import deque, Counter, defaultdict\nfrom heapq import heappush, heappop, heapify\nfrom scipy.special import comb, perm\nfrom bisect import bisect, bisect_left, bisect_right\n\ndef shortestbridge(A):\n (que, row, col, visited) = (deque(), len(A), len(A[0]), set())\n\n def dfs(i, j):\n if i < 0 or i > row - 1 or j < 0 or (j > col - 1) or ((i, j) in visited):\n return\n visited.add((i, j))\n if A[i][j] == 0:\n que.append((i, j))\n return\n for (ni, nj) in [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]:\n dfs(ni, nj)\n found = False\n for i in range(row):\n for j in range(col):\n if A[i][j] == 1:\n dfs(i, j)\n found = True\n break\n if found:\n break\n cnt = 0\n while que:\n n = len(que)\n for _ in range(n):\n (i, j) = que.popleft()\n if A[i][j] == 1:\n return cnt\n for (ni, nj) in [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]:\n if 0 <= ni < row and 0 <= nj < col and ((ni, nj) not in visited):\n que.append((ni, nj))\n visited.add((ni, nj))\n cnt += 1", "def shortestbridge(A: List[List[int]]) -> int:\n (rows, cols) = (len(A), len(A[0]))\n starting_points = set()\n\n def traverse_island(r, c):\n A[r][c] = -1\n for (ar, ac) in [(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)]:\n if 0 <= ar < rows and 0 <= ac < cols:\n if A[ar][ac] == 0:\n starting_points.add((ar, ac, 0))\n elif A[ar][ac] == 1:\n traverse_island(ar, ac)\n for r in range(rows):\n for c in range(cols):\n if A[r][c] == 1:\n traverse_island(r, c)\n break\n else:\n continue\n break\n q = deque(starting_points)\n while q:\n (r, c, dist) = q.popleft()\n for (ar, ac) in [(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)]:\n if 0 <= ar < rows and 0 <= ac < cols and (A[ar][ac] != -1):\n if A[ar][ac] == 1:\n return dist + 1\n A[ar][ac] = -1\n q.append((ar, ac, dist + 1))\n return 0", "from collections import deque\n\ndef shortestbridge(A: List[List[int]]) -> int:\n rows = len(A)\n cols = len(A[0]) if rows else 0\n if not rows or not cols:\n return -1\n self.queue = deque()\n self.visited = set()\n\n def floodFill(A, row, col, rows, cols):\n if not (0 <= row < rows and 0 <= col < cols):\n return\n if not A[row][col] or (row, col) in self.visited:\n return\n A[row][col] = 2\n self.queue.append((row, col, 0))\n self.visited.add((row, col))\n floodFill(A, row + 1, col, rows, cols)\n floodFill(A, row - 1, col, rows, cols)\n floodFill(A, row, col + 1, rows, cols)\n floodFill(A, row, col - 1, rows, cols)\n flood_fill = False\n for row in range(rows):\n for col in range(cols):\n if A[row][col] == 1:\n flood_fill = True\n floodFill(A, row, col, rows, cols)\n break\n if flood_fill:\n break\n directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]\n while len(self.queue):\n (top_r, top_c, dist) = self.queue.popleft()\n for (d_r, d_c) in directions:\n n_r = top_r + d_r\n n_c = top_c + d_c\n if 0 <= n_r < rows and 0 <= n_c < cols and ((n_r, n_c) not in self.visited):\n if A[n_r][n_c] == 0:\n self.queue.append((n_r, n_c, dist + 1))\n self.visited.add((n_r, n_c))\n elif A[n_r][n_c] == 1:\n return dist\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n\n def first():\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1:\n return (i, j)\n\n def first_island(i, j):\n stack = [(i, j)]\n island = []\n dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n while stack:\n (x, y) = stack.pop()\n A[x][y] = 2\n island.append((x, y, 0))\n for (dx, dy) in dirs:\n (tx, ty) = (x + dx, y + dy)\n if len(A) > tx >= 0 and len(A[0]) > ty >= 0 and (A[tx][ty] == 1):\n stack.append((tx, ty))\n return island\n\n def bfs(queue):\n queue = collections.deque(queue)\n dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n while queue:\n length = len(queue)\n for _ in range(length):\n (x, y, level) = queue.popleft()\n for (dx, dy) in dirs:\n (tx, ty) = (x + dx, y + dy)\n if len(A) > tx >= 0 and len(A[0]) > ty >= 0:\n if A[tx][ty] == 1:\n return level\n elif not A[tx][ty]:\n A[tx][ty] = -1\n queue.append((tx, ty, level + 1))\n return bfs(first_island(*first()))", "import heapq\nimport sys\nsys.setrecursionlimit(10 ** 8)\n\ndef shortestbridge(A: List[List[int]]) -> int:\n (h, w) = (len(A), len(A[0]))\n direction = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n First.val = True\n visited = [[0 for i in range(w)] for i in range(h)]\n\n def dfs(y, x, color):\n visited[y][x] = 1\n A[y][x] = color\n for (dy, dx) in direction:\n (ny, nx) = (y + dy, x + dx)\n if ny < 0 or ny >= h or nx < 0 or (nx >= w):\n continue\n if visited[ny][nx] or A[ny][nx] == 0:\n continue\n dfs(ny, nx, color)\n for i in range(h):\n for j in range(w):\n if visited[i][j]:\n continue\n if A[i][j]:\n if First.val:\n First.val = False\n dfs(i, j, 1)\n else:\n dfs(i, j, 2)\n break\n\n def bfs(i, j, start):\n q = [[0, i, j]]\n answer = 0\n while q:\n (step, y, x) = heapq.heappop(q)\n if A[y][x] and A[y][x] != start:\n return step\n for (dy, dx) in direction:\n (ny, nx) = (y + dy, x + dx)\n if ny < 0 or ny >= h or nx < 0 or (nx >= w):\n continue\n if visited[ny][nx] == 2:\n continue\n visited[ny][nx] = 2\n if A[ny][nx]:\n heapq.heappush(q, [step, ny, nx])\n else:\n heapq.heappush(q, [step + 1, ny, nx])\n result = 0\n for i in range(h):\n for j in range(w):\n if visited[i][j] == 2:\n continue\n if A[i][j]:\n start = A[i][j]\n result = bfs(i, j, start)\n break\n if result:\n break\n return result", "def shortestbridge(A: List[List[int]]) -> int:\n\n def isvalid(row, col):\n return 0 <= row < len(A) and 0 <= col < len(A[0])\n\n def dfs(row, col):\n if not isvalid(row, col) or A[row][col] != 1:\n return\n A[row][col] = 2\n for (i, j) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:\n new_row = row + i\n new_col = col + j\n dfs(new_row, new_col)\n return\n found = False\n for row in range(len(A)):\n for col in range(len(A[0])):\n if A[row][col] == 1:\n dfs(row, col)\n found = True\n break\n if found:\n break\n twos = []\n for row in range(len(A)):\n for col in range(len(A[0])):\n if A[row][col] == 2:\n twos.append((row, col))\n steps = 0\n while twos:\n next_ = []\n steps += 1\n for point in twos:\n (row, col) = point\n for (i, j) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:\n new_row = row + i\n new_col = col + j\n if isvalid(new_row, new_col) and A[new_row][new_col] == 0:\n A[new_row][new_col] = -1\n next_.append((new_row, new_col))\n elif isvalid(new_row, new_col) and A[new_row][new_col] == 1:\n return steps - 1\n twos = next_\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n q = collections.deque()\n\n def ExploreIslands(x, y):\n if not 0 <= x < len(A) or not 0 <= y < len(A[0]) or A[x][y] == -1:\n return\n if A[x][y] == 1:\n A[x][y] = -1\n ExploreIslands(x, y + 1)\n ExploreIslands(x, y - 1)\n ExploreIslands(x + 1, y)\n ExploreIslands(x - 1, y)\n else:\n q.appendleft((x, y, 1))\n\n def FindFirstIsland():\n for (i, row) in enumerate(A):\n for (j, val) in enumerate(row):\n if val == 1:\n ExploreIslands(i, j)\n return\n FindFirstIsland()\n while True:\n (x, y, distance) = q.popleft()\n for (new_x, new_y) in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:\n if 0 <= new_x < len(A) and 0 <= new_y < len(A[0]):\n if A[new_x][new_y] == 1:\n return distance\n elif A[new_x][new_y] == 0:\n A[new_x][new_y] = -1\n q.append((new_x, new_y, distance + 1))", "import collections\n\ndef shortestbridge(A: List[List[int]]) -> int:\n visited = set()\n\n def do_dfs(A, i, j, visited, seen):\n visited.add((i, j))\n seen.add((i, j))\n for (x, y) in [[i + 1, j], [i - 1, j], [i, j - 1], [i, j + 1]]:\n if 0 <= x < len(A) and 0 <= y < len(A[0]) and A[x][y] and ((x, y) not in visited):\n do_dfs(A, x, y, visited, seen)\n comp = []\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1 and (i, j) not in visited:\n seen = set()\n do_dfs(A, i, j, visited, seen)\n comp.append(seen)\n (s, t) = (comp[0], comp[1])\n queue = collections.deque([(node, 0) for node in s])\n done = s\n while queue:\n (node, d) = queue.popleft()\n if node in t:\n return d - 1\n for n in [(node[0] + 1, node[1]), (node[0] - 1, node[1]), (node[0], node[1] + 1), (node[0], node[1] - 1)]:\n if 0 <= n[0] < len(A) and 0 <= n[1] < len(A[0]) and (n not in done):\n queue.append((n, d + 1))\n done.add(n)", "def shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n found = 0\n queue = []\n\n def dfs(a, b):\n queue.append((a, b))\n A[a][b] = -1\n for (x, y) in ((a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)):\n if 0 <= x < m and 0 <= y < n and (A[x][y] == 1):\n dfs(x, y)\n for i in range(m):\n if found:\n break\n for j in range(n):\n if A[i][j] == 1:\n found = 1\n dfs(i, j)\n break\n step = 0\n while queue:\n new_queue = []\n for (x, y) in queue:\n for (_x, _y) in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):\n if 0 <= _x < m and 0 <= _y < n:\n if A[_x][_y] == 1:\n return step\n elif not A[_x][_y]:\n A[_x][_y] = -1\n new_queue.append((_x, _y))\n step += 1\n queue = new_queue\n return -1", "def shortestbridge(A: List[List[int]]) -> int:\n\n def neighbors(u, v):\n for (du, dv) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n (nu, nv) = (u + du, v + dv)\n if 0 <= nu < m and 0 <= nv < n:\n yield (nu, nv)\n\n def components():\n\n def dfs(u, v, acc):\n acc.add((u, v))\n visited.add((u, v))\n for (nu, nv) in neighbors(u, v):\n if (nu, nv) not in visited and A[nu][nv] == 1:\n dfs(nu, nv, acc)\n res = []\n visited = set()\n for u in range(m):\n for v in range(n):\n if A[u][v] == 1 and (u, v) not in visited:\n res.append(set())\n dfs(u, v, res[-1])\n return res\n\n def bfs(ps, pt):\n q = deque()\n visited = set()\n for p in ps:\n q.append(p)\n visited.add(p)\n distance = 0\n while q:\n qsize = len(q)\n for i in range(qsize):\n (u, v) = q.popleft()\n for (nu, nv) in neighbors(u, v):\n if (nu, nv) in pt:\n return distance\n if (nu, nv) not in visited:\n q.append((nu, nv))\n visited.add((nu, nv))\n distance += 1\n return 0\n m = len(A)\n n = len(A[0])\n (source, target) = components()\n return bfs(source, target)", "def shortestbridge(A: List[List[int]]) -> int:\n (R, C) = (len(A), len(A[0]))\n done = set()\n\n def dfs(x, y, seen, R, C):\n if A[x][y] == 0:\n return\n seen.add((x, y))\n for (nr, nc) in ((x - 1, y), (x, y - 1), (x + 1, y), (x, y + 1)):\n if 0 <= nr < R and 0 <= nc < C and (A[nr][nc] == 1) and ((nr, nc) not in seen) and ((nr, nc) not in done):\n dfs(nr, nc, seen, R, C)\n islands = []\n for (r, row) in enumerate(A):\n for (c, col) in enumerate(row):\n if col and (r, c) not in done:\n seen = set()\n dfs(r, c, seen, R, C)\n islands.append(seen)\n done |= seen\n (first, second) = islands\n q = list(first)\n count = 0\n seen = set()\n while q:\n temp = []\n for (x, y) in q:\n for (nx, ny) in ((x - 1, y), (x, y - 1), (x + 1, y), (x, y + 1)):\n if 0 <= nx < R and 0 <= ny < C and ((nx, ny) not in first) and ((nx, ny) not in seen):\n if (nx, ny) in second:\n return count\n temp.append((nx, ny))\n seen.add((nx, ny))\n count += 1\n q = temp[:]\n return 0", "def shortestbridge(A: List[List[int]]) -> int:\n (R, C) = (len(A), len(A[0]))\n\n def inside(i, j):\n return 0 <= i < R and 0 <= j < C\n\n def dfs_paint_2(i, j):\n A[i][j] = 2\n for (ii, jj) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:\n if inside(ii, jj) and A[ii][jj] == 1:\n dfs_paint_2(ii, jj)\n\n def neighbor_is_1(i, j):\n for (ii, jj) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:\n if inside(ii, jj) and A[ii][jj] == 1:\n return True\n return False\n\n def paint_neighbor(i, j, color):\n for (ii, jj) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:\n if inside(ii, jj) and A[ii][jj] == 0:\n A[ii][jj] = color\n for (i, row) in enumerate(A):\n for (j, ele) in enumerate(row):\n if ele == 1:\n dfs_paint_2(i, j)\n break\n else:\n continue\n break\n for color in range(2, max(R, C) + 2):\n for (i, row) in enumerate(A):\n for (j, ele) in enumerate(row):\n if ele == color:\n if neighbor_is_1(i, j):\n return color - 2\n paint_neighbor(i, j, color + 1)", "def shortestbridge(A: List[List[int]]) -> int:\n q = collections.deque()\n\n def explore_island(r, c):\n if not 0 <= r < len(A) or not 0 <= c < len(A[r]) or A[r][c] == -1:\n return\n if A[r][c] == 1:\n A[r][c] = -1\n explore_island(r + 1, c)\n explore_island(r - 1, c)\n explore_island(r, c + 1)\n explore_island(r, c - 1)\n elif A[r][c] == 0:\n q.append((r, c, 1))\n\n def find_first_island():\n for (r, row) in enumerate(A):\n for (c, v) in enumerate(row):\n if v == 1:\n explore_island(r, c)\n return\n find_first_island()\n while q:\n (cur_r, cur_c, cur_l) = q.popleft()\n for (x, y) in ((cur_r + 1, cur_c), (cur_r - 1, cur_c), (cur_r, cur_c + 1), (cur_r, cur_c - 1)):\n if 0 <= x < len(A) and 0 <= y < len(A[x]):\n if A[x][y] == 1:\n return cur_l\n elif A[x][y] == 0:\n A[x][y] = -1\n q.append((x, y, cur_l + 1))\n continue", "def shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n\n def get_poss(i, j, val=1):\n poss = [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]\n poss = [(x, y) for (x, y) in poss if x >= 0 and x < m and (y >= 0) and (y < n) and (A[x][y] == val)]\n return poss\n\n def expand(i, j):\n A[i][j] = '#'\n poss = get_poss(i, j)\n for (x, y) in poss:\n expand(x, y)\n found_first = False\n boundaries = []\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n if not found_first:\n found_first = True\n expand(i, j)\n else:\n boundaries.append((i, j))\n\n def bfs(boundaries):\n recorder = set(boundaries)\n depth = 0\n roots = boundaries\n while roots:\n next_level = []\n for (x, y) in roots:\n poss1 = get_poss(x, y, '#')\n if poss1:\n return depth\n poss = get_poss(x, y, 0)\n for pos in poss:\n if pos not in recorder:\n recorder.add(pos)\n next_level.append(pos)\n depth += 1\n roots = next_level\n return bfs(boundaries)", "def shortestbridge(A: List[List[int]]) -> int:\n island_one = set()\n\n def dfs(r, c):\n if (r, c) in island_one:\n return\n island_one.add((r, c))\n for (r1, c1) in {(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)}:\n if 0 <= r1 < len(A) and 0 <= c1 < len(A[0]) and ((r1, c1) not in island_one) and (A[r1][c1] == 1):\n dfs(r1, c1)\n f = False\n for i in range(len(A)):\n for j in range(len(A[0])):\n if A[i][j] == 1:\n dfs(i, j)\n f = True\n break\n if f:\n break\n\n def bfs():\n q = collections.deque([(r, c, 0) for (r, c) in list(island_one)])\n seen = set()\n while q:\n (r, c, level) = q.popleft()\n if A[r][c] == 1 and (r, c) not in island_one:\n return level - 1\n for (r1, c1) in {(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)}:\n if 0 <= r1 < len(A) and 0 <= c1 < len(A[0]) and (A[r1][c1] not in island_one) and ((r1, c1) not in seen):\n q.append((r1, c1, level + 1))\n seen.add((r1, c1))\n return bfs()", "import heapq\n\ndef shortestbridge(mat: List[List[int]]) -> int:\n row = None\n col = None\n found = False\n for i in range(len(mat)):\n if found:\n break\n for j in range(len(mat[i])):\n if mat[i][j]:\n row = i\n col = j\n Solution.paint_one_island(mat, row, col, mat[row][col] + 1)\n found = True\n break\n target_dest = 1\n return Solution.minimum_expand(mat, row, col, target_dest)\n\ndef mark_next(mat, row, col, val, target_dest):\n for i in range(len(Solution.directions)):\n new_row = row + Solution.directions[i][0]\n new_col = col + Solution.directions[i][1]\n if new_row < 0 or new_row >= len(mat) or new_col < 0 or (new_col >= len(mat[0])):\n continue\n if mat[new_row][new_col] == target_dest:\n return True\n if not mat[new_row][new_col]:\n mat[new_row][new_col] = val + 1\n return False\n\ndef minimum_expand(mat, row, col, target_dest):\n st_val = mat[row][col]\n for val in range(st_val, len(mat) * len(mat[0])):\n for row in range(len(mat)):\n for col in range(len(mat[row])):\n is_reached = False\n if mat[row][col] == val:\n is_reached = Solution.mark_next(mat, row, col, val, target_dest)\n if is_reached:\n return val - st_val\n return -1\n\ndef paint_one_island(mat, row, col, val):\n if row < 0 or row >= len(mat) or col < 0 or (col >= len(mat[0])):\n return\n if mat[row][col] == val or not mat[row][col]:\n return\n mat[row][col] = val\n for i in range(len(Solution.directions)):\n Solution.paint_one_island(mat, row + Solution.directions[i][0], col + Solution.directions[i][1], val)", "def shortestbridge(A: List[List[int]]) -> int:\n (M, N) = (len(A), len(A[0]))\n\n def dfs(i, j):\n A[i][j] = 2\n for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:\n if 0 <= x < M and 0 <= y < N and (A[x][y] == 1):\n dfs(x, y)\n return\n flag = 0\n for i in range(M):\n for j in range(N):\n if A[i][j] == 1:\n flag = 1\n break\n if flag:\n break\n dfs(i, j)\n q = collections.deque([(0, i, j) for i in range(M) for j in range(N) if A[i][j] == 1])\n seen = set([(i, j) for i in range(M) for j in range(N) if A[i][j] == 1])\n while q:\n (step, i, j) = q.popleft()\n if A[i][j] == 2:\n return step - 1\n for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:\n if 0 <= x < M and 0 <= y < N and ((x, y) not in seen) and (A[x][y] in [0, 2]):\n seen.add((x, y))\n q.append((step + 1, x, y))", "def shortestbridge(A: List[List[int]]) -> int:\n (m, n) = (len(A), len(A[0]))\n self.first = []\n\n def dfs(i, j, m, n):\n if 0 <= i < m and 0 <= j < n and (A[i][j] == 1):\n A[i][j] = 2\n self.first.append((i, j))\n for (r, c) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:\n dfs(r, c, m, n)\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n dfs(i, j, m, n)\n break\n if A[i][j] == 2:\n break\n res = m * n\n while self.first:\n (i, j) = self.first.pop(0)\n for (r, c) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:\n if 0 <= r < m and 0 <= c < n:\n if A[r][c] == 0:\n A[r][c] = A[i][j] + 1\n self.first.append((r, c))\n if A[r][c] == 1:\n res = min(res, A[i][j] - 2)\n A[i][j] == -1\n break\n if A[i][j] == -1:\n break\n return res", "def shortestbridge(A: List[List[int]]) -> int:\n n = len(A)\n zeros = set()\n\n def dfs(i, j):\n A[i][j] = 2\n for (di, dj) in [[0, -1], [0, 1], [-1, 0], [1, 0]]:\n (ii, jj) = (i + di, j + dj)\n if 0 <= ii < n and 0 <= jj < n:\n if A[ii][jj] == 1:\n dfs(ii, jj)\n elif A[ii][jj] == 0:\n zeros.add((ii, jj))\n for i in range(n):\n for j in range(n):\n if A[i][j] == 1:\n dfs(i, j)\n break\n else:\n continue\n break\n result = 2 * n\n q = collections.deque(zeros)\n visited = {(i, j)}\n steps = 1\n while q:\n for _ in range(len(q)):\n (i, j) = q.popleft()\n for (di, dj) in [[0, -1], [0, 1], [-1, 0], [1, 0]]:\n (ii, jj) = (i + di, j + dj)\n if 0 <= ii < n and 0 <= jj < n:\n if A[ii][jj] == 0 and (ii, jj) not in visited:\n visited.add((ii, jj))\n q.append((ii, jj))\n if A[ii][jj] == 1:\n result = min(result, steps)\n steps += 1\n return result", "def shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n q = collections.deque([])\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n q.append((i, j))\n newq = collections.deque([(i, j)])\n break\n else:\n continue\n break\n while q:\n (x, y) = q.popleft()\n A[x][y] = 2\n for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n (nx, ny) = (x + dx, y + dy)\n if 0 <= nx < m and 0 <= ny < n and (A[nx][ny] == 1):\n A[nx][ny] = 2\n newq.append((nx, ny))\n q.append((nx, ny))\n steps = 0\n while newq:\n newsize = len(newq)\n for _ in range(newsize):\n (x, y) = newq.popleft()\n for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n (nx, ny) = (x + dx, y + dy)\n if nx < 0 or nx >= m or ny < 0 or (ny >= m) or (A[nx][ny] == 2):\n continue\n if A[nx][ny] == 1:\n return steps\n elif A[nx][ny] == 0:\n A[nx][ny] = 2\n newq.append((nx, ny))\n steps += 1\n return -1", "def shortestbridge(grid: List[List[int]]) -> int:\n if not grid:\n return 0\n nrow = len(grid)\n ncol = len(grid[0])\n q = deque()\n\n def explore_island(grid, i, j):\n if i < 0 or i >= nrow or j < 0 or (j >= ncol) or (grid[i][j] != 1):\n return\n grid[i][j] = 2\n q.append((i, j, 0))\n for (ni, nj) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:\n explore_island(grid, ni, nj)\n\n def get_coordinates(grid):\n for i in range(nrow):\n for j in range(ncol):\n if grid[i][j] == 1:\n explore_island(grid, i, j)\n return\n return\n get_coordinates(grid)\n while q:\n (i, j, dist) = q.popleft()\n for (ni, nj) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:\n if ni >= 0 and ni < nrow and (nj >= 0) and (nj < ncol) and (grid[ni][nj] != 2):\n if grid[ni][nj] == 1:\n return dist\n elif grid[ni][nj] == 0:\n grid[ni][nj] = 2\n q.append((ni, nj, dist + 1))", "def __init__():\n self.map = None\n (self.w, self.h) = (0, 0)\n\ndef get_neighbors(r, c):\n nei = []\n for rc in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]:\n if 0 <= rc[0] < self.h and 0 <= rc[1] < self.w:\n nei.append(rc)\n return nei\n\ndef find_island():\n done = set()\n islands = []\n for r in range(len(self.map)):\n for c in range(len(self.map[0])):\n if self.map[r][c] and (r, c) not in done:\n stack = [(r, c)]\n seen = {(r, c)}\n while stack:\n cell = stack.pop(0)\n neighbors = self.get_neighbors(cell[0], cell[1])\n for nei in neighbors:\n if self.map[nei[0]][nei[1]] and nei not in seen:\n stack.append(nei)\n seen.add(nei)\n islands.append(seen)\n done |= seen\n return islands\n\ndef shortestbridge(A: List[List[int]]) -> int:\n self.map = A\n (self.w, self.h) = (len(A), len(A[0]))\n (source, target) = self.find_island()\n queue = [(node, 0) for node in source]\n while queue:\n (node, d) = queue.pop(0)\n if node in target:\n return d - 1\n neighbors = self.get_neighbors(node[0], node[1])\n for nei in neighbors:\n if nei not in source:\n queue.append((nei, d + 1))\n source.add(nei)", "def shortestbridge(A: List[List[int]]) -> int:\n row_len = len(A)\n col_len = len(A[0])\n\n def neighbour(r, c):\n for (i, j) in [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]:\n if 0 <= i < row_len and 0 <= j < col_len:\n yield (i, j)\n\n def helper(A, r, c, queue):\n if not (0 <= r < row_len and 0 <= c < col_len) or A[r][c] == 0 or A[r][c] == 2:\n return\n A[r][c] = 2\n queue.append((r, c))\n for (i, j) in neighbour(r, c):\n helper(A, i, j, queue)\n start_r = -1\n start_c = -1\n for r in range(row_len):\n for c in range(col_len):\n if A[r][c] == 1:\n start_r = r\n start_c = c\n break\n queue = deque()\n helper(A, start_r, start_c, queue)\n step = 0\n while queue:\n size = len(queue)\n for i in range(size):\n (r, c) = queue.popleft()\n for (i, j) in neighbour(r, c):\n if A[i][j] == 1:\n return step\n if A[i][j] == 0:\n A[i][j] = 2\n queue.append((i, j))\n step += 1", "def shortestbridge(A: List[List[int]]) -> int:\n (N, M) = (len(A), len(A[0]))\n\n def labelIsland(i, j):\n stack = [(i, j)]\n visited = {(i, j)}\n while stack:\n (x, y) = stack.pop()\n A[x][y] = 2\n for (nx, ny) in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:\n if 0 <= nx < N and 0 <= ny < M and ((nx, ny) not in visited):\n if A[nx][ny] == 1:\n visited.add((nx, ny))\n stack.append((nx, ny))\n return visited\n\n def bfs(source) -> int:\n queue = collections.deque([(0, x[0], x[1]) for x in source])\n visited = source\n ans = math.inf\n while queue:\n (dist, x, y) = queue.popleft()\n for (nx, ny) in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:\n if 0 <= nx < N and 0 <= ny < M and ((nx, ny) not in visited):\n if A[nx][ny] == 1:\n return dist\n else:\n visited.add((nx, ny))\n queue.append((dist + 1, nx, ny))\n return ans\n ans = math.inf\n for i in range(N):\n for j in range(M):\n if A[i][j] == 1:\n source = labelIsland(i, j)\n return bfs(source)", "def shortestbridge(A: List[List[int]]) -> int:\n n = len(A)\n\n def getFirst():\n for (i, row) in enumerate(A):\n for (j, point) in enumerate(row):\n if point == 1:\n return (i, j)\n islandA = []\n boundaries = set()\n stack = [getFirst()]\n while len(stack) > 0:\n (i, j) = stack.pop()\n A[i][j] = -1\n islandA.append((i, j))\n isBound = False\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= x < n and 0 <= y < n:\n if A[x][y] == 0:\n boundaries.add((i, j))\n elif A[x][y] == 1:\n stack.append((x, y))\n step = 0\n while boundaries:\n new = []\n for (i, j) in boundaries:\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= x < n and 0 <= y < n:\n if A[x][y] == 1:\n return step\n elif not A[x][y]:\n A[x][y] = -1\n new.append((x, y))\n step += 1\n boundaries = new", "def mark_island(A, row, column, marker, border_coordinates):\n if 0 <= row < len(A) and 0 <= column < len(A[0]) and (A[row][column] != marker):\n if A[row][column] == 0:\n return True\n else:\n A[row][column] = marker\n rets = [self.mark_island(A, row + 1, column, marker, border_coordinates), self.mark_island(A, row - 1, column, marker, border_coordinates), self.mark_island(A, row, column + 1, marker, border_coordinates), self.mark_island(A, row, column - 1, marker, border_coordinates)]\n if True in rets:\n border_coordinates.append((row, column))\n return False\n\ndef shortestbridge(A: List[List[int]]) -> int:\n border_coordinates = [[], []]\n marker = 2\n smallest_distance = len(A) * len(A[0])\n for row in range(len(A)):\n for column in range(len(A[0])):\n if A[row][column] == 1:\n self.mark_island(A, row, column, marker, border_coordinates[marker - 2])\n marker += 1\n for coordinates1 in border_coordinates[0]:\n for coordinates2 in border_coordinates[1]:\n distance = abs(coordinates1[0] - coordinates2[0]) + abs(coordinates1[1] - coordinates2[1]) - 1\n if distance < smallest_distance:\n smallest_distance = distance\n return smallest_distance", "def shortestbridge(A: List[List[int]]) -> int:\n m = len(A)\n n = len(A[0])\n\n def get_neighbors(i, j):\n dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n ans = []\n for (dx, dy) in dirs:\n new_i = i + dx\n new_j = j + dy\n if 0 <= new_i < m and 0 <= new_j < n:\n ans.append((new_i, new_j))\n return ans\n\n def dfs_visit(i, j, visited):\n if A[i][j] != 1:\n return\n if (i, j) in visited:\n return\n visited.add((i, j))\n for neighbor in get_neighbors(i, j):\n dfs_visit(neighbor[0], neighbor[1], visited)\n return\n source_nodes = set()\n break_flag = False\n for i in range(m):\n if break_flag:\n break\n for j in range(n):\n if A[i][j] == 1:\n dfs_visit(i, j, source_nodes)\n break_flag = True\n break\n q = []\n for (i, j) in source_nodes:\n q.append(((i, j), 0))\n visited = set()\n while len(q):\n (curr_node, curr_dist) = q.pop(0)\n for neighbor in get_neighbors(curr_node[0], curr_node[1]):\n if neighbor in source_nodes:\n continue\n if neighbor in visited:\n continue\n if A[neighbor[0]][neighbor[1]] == 1:\n return curr_dist\n visited.add(neighbor)\n q.append((neighbor, curr_dist + 1))\n return", "def shortestbridge(A: List[List[int]]) -> int:\n\n def findIslandA(i, j):\n A[i][j] = -1\n islandA.append((i, j))\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= x < n and 0 <= y < n and (A[x][y] == 1):\n findIslandA(x, y)\n\n def first():\n for i in range(n):\n for j in range(n):\n if A[i][j]:\n return (i, j)\n (n, step, islandA) = (len(A), 0, [])\n findIslandA(*first())\n while islandA:\n boundaries = []\n for (i, j) in islandA:\n for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):\n if 0 <= x < n and 0 <= y < n:\n if A[x][y] == 1:\n return step\n elif A[x][y] == 0:\n A[x][y] = -1\n boundaries.append((x, y))\n step += 1\n islandA = boundaries", "def shortestbridge(grid: List[List[int]]) -> int:\n\n def dfs(curr_i, curr_j, outliners):\n visited.add((curr_i, curr_j))\n for (delta_i, delta_j) in [(1, 0), (0, 1), (0, -1), (-1, 0)]:\n (next_i, next_j) = (curr_i + delta_i, curr_j + delta_j)\n if 0 <= next_i < m and 0 <= next_j < n:\n if grid[next_i][next_j] == 0:\n outliners.add((next_i, next_j))\n elif grid[next_i][next_j] == 1:\n if (next_i, next_j) not in visited:\n dfs(next_i, next_j, outliners)\n (m, n) = (len(grid), len(grid[0]))\n visited = set()\n (outliners_1, outliners_2) = (set(), set())\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1 and (i, j) not in visited:\n if len(outliners_1) == 0:\n dfs(i, j, outliners_1)\n else:\n dfs(i, j, outliners_2)\n min_dist = m + n\n for (i, j) in outliners_1:\n for (p, q) in outliners_2:\n min_dist = min(min_dist, abs(i - p) + abs(j - q) + 1)\n return min_dist", "def shortestbridge(A: List[List[int]]) -> int:\n\n def dfs(i, j, A, visited):\n m = len(A)\n n = len(A[0])\n if 0 <= i < m and 0 <= j < n and (A[i][j] == 1) and ((i, j) not in visited):\n visited.add((i, j))\n dfs(i + 1, j, A, visited)\n dfs(i - 1, j, A, visited)\n dfs(i, j + 1, A, visited)\n dfs(i, j - 1, A, visited)\n m = len(A)\n n = len(A[0])\n find = False\n visited = set()\n for i in range(m):\n for j in range(n):\n if A[i][j] == 1:\n find = True\n dfs(i, j, A, visited)\n break\n if find:\n break\n visited_zero = set()\n queue = []\n for (i, j) in visited:\n for (_i, _j) in [[0, 1], [1, 0], [-1, 0], [0, -1]]:\n if 0 <= i + _i < m and 0 <= j + _j < n and ((i + _i, j + _j) not in visited):\n assert A[i + _i][j + _j] == 0\n visited_zero.add((i + _i, j + _j))\n queue.append((i + _i, j + _j, 1))\n res = 0\n find = False\n while not find:\n (i, j, dist) = queue.pop(0)\n for (_i, _j) in [[0, 1], [1, 0], [-1, 0], [0, -1]]:\n if 0 <= i + _i < m and 0 <= j + _j < n and ((i + _i, j + _j) not in visited_zero) and ((i + _i, j + _j) not in visited):\n if A[i + _i][j + _j] == 0:\n visited_zero.add((i + _i, j + _j))\n queue.append((i + _i, j + _j, dist + 1))\n else:\n find = True\n res = dist\n return res", "def shortestbridge(A: List[List[int]]) -> int:\n (i1, i2) = self.find_islands(A)\n for (x, y, n) in self.enlarge(i1):\n if (x, y) in i2:\n return n\n\ndef find_islands(A: List[List[int]]) -> List[Set[Tuple[int, int]]]:\n visited = set()\n islands = []\n for (x, ys) in enumerate(A):\n for (y, c) in enumerate(ys):\n if (x, y) not in visited and c == 1:\n to_visit = [(x, y)]\n island = set()\n while to_visit:\n (cx, cy) = to_visit.pop(0)\n if (cx, cy) in visited:\n continue\n visited.add((cx, cy))\n island.add((cx, cy))\n for (ax, ay) in self.adjacent((cx, cy)):\n if ax >= 0 and ay >= 0 and (ax < len(A)) and (ay < len(A[ax])) and (A[ax][ay] == 1):\n to_visit.append((ax, ay))\n islands.append(island)\n return islands\n\ndef enlarge(island: Set[Tuple[int, int]]) -> Generator[Tuple[int, int, int], None, None]:\n visited = set()\n to_visit = []\n for (x, y) in island:\n visited.add((x, y))\n for (ax, ay) in self.adjacent((x, y)):\n visited.add((x, y))\n if (ax, ay) not in island:\n to_visit.append((ax, ay, 0))\n while to_visit:\n (x, y, n) = to_visit.pop(0)\n if (x, y) in visited:\n continue\n visited.add((x, y))\n for (ax, ay) in self.adjacent((x, y)):\n if (ax, ay) in visited:\n continue\n to_visit.append((ax, ay, n + 1))\n yield (x, y, n)\n\ndef adjacent(cell: Tuple[int, int]) -> List[Tuple[int, int]]:\n return [(cell[0] + x, cell[1] + y) for (x, y) in [(-1, 0), (1, 0), (0, -1), (0, 1)]]"], "starter_code": "def shortestbridge(A: List[List[int]]) -> int:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Matrix", "Array", "Breadth-First Search", "Depth-First Search"], "name": null, "source": "leetcode", "tags": ["Matrices", "Data structures", "Graph traversal"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/shortest-bridge/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "shortestbridge", "task_id": "TACO_lite/422", "example": [[[[[0, 1], [1, 0]]], [[[0, 1, 0], [0, 0, 0], [0, 0, 1]]], [[[1, 1, 1, 1, 1], [1, 0, 0, 0, 1], [1, 0, 1, 0, 1], [1, 0, 0, 0, 1], [1, 1, 1, 1, 1]]]], ["1", "2", "1"]]} +{"requirement": "Given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it palindrome.\nReturn the length of the maximum length awesome substring of s.\n\u00a0\nExample 1:\nInput: s = \"3242415\"\nOutput: 5\nExplanation: \"24241\" is the longest awesome substring, we can form the palindrome \"24142\" with some swaps.\n\nExample 2:\nInput: s = \"12345678\"\nOutput: 1\n\nExample 3:\nInput: s = \"213123\"\nOutput: 6\nExplanation: \"213123\" is the longest awesome substring, we can form the palindrome \"231132\" with some swaps.\n\nExample 4:\nInput: s = \"00\"\nOutput: 2\n\n\u00a0\nConstraints:\n\n1 <= s.length <= 10^5\ns consists only of digits.", "solutions": ["def longestawesome(s: str) -> int:\n cum = [0]\n firsts = {0: -1}\n lasts = {0: -1}\n for (i, c) in enumerate(s):\n cum.append(cum[-1] ^ 1 << ord(c) - 48)\n if cum[-1] not in firsts:\n firsts[cum[-1]] = i\n lasts[cum[-1]] = i\n mx = 1\n for k in firsts:\n mx = max(mx, lasts[k] - firsts[k])\n for off in range(10):\n o = k ^ 1 << off\n if o in firsts:\n mx = max(mx, lasts[o] - firsts[k])\n return mx", "def longestawesome(s: str) -> int:\n mask = 0\n (prefix, suffix) = ({0: -1}, {0: -1})\n digcodes = [2 ** i for i in range(10)] + [0]\n for i in range(len(s)):\n ch = s[i]\n mask ^= 2 ** int(ch)\n if mask not in prefix:\n prefix[mask] = i\n suffix[mask] = i\n return max([ind - prefix[val ^ dig] for (val, ind) in list(suffix.items()) for dig in digcodes if val ^ dig in prefix])", "def longestawesome(s: str) -> int:\n d = {}\n d[0] = -1\n (sm, res) = (0, 0)\n for (i, c) in enumerate(s):\n sm ^= 1 << int(c)\n if sm in d:\n res = max(res, i - d[sm])\n else:\n d[sm] = i\n for j in range(10):\n msk = sm ^ 1 << j\n if msk in d and i - d[msk] > res:\n res = i - d[msk]\n return res", "def longestawesome(s: str) -> int:\n n = len(s)\n a = 0\n ans = 0\n dp = {0: -1}\n for i in range(n):\n a = a ^ 1 << int(s[i])\n if a in dp:\n ans = max(ans, i - dp[a])\n else:\n dp[a] = i\n for j in range(11):\n x = a ^ 1 << j\n if x in dp:\n ans = max(ans, i - dp[x])\n return ans", "def longestawesome(s: str) -> int:\n known_positions = {0: -1}\n mask = 0\n max_size = 0\n for (idx, current) in enumerate(s):\n mask ^= 1 << ord(current) - ord('0')\n for modified in range(10):\n tmp_mask = mask ^ 1 << modified\n size = idx - known_positions.get(tmp_mask, idx)\n if size % 2:\n max_size = max(max_size, size)\n max_size = max(max_size, idx - known_positions.get(mask, idx))\n known_positions.setdefault(mask, idx)\n return max(max_size, 1)", "def longestawesome(s: str) -> int:\n memo = {0: -1}\n best = 0\n bitmap = 0\n for (i, digit) in enumerate(s):\n bitmap ^= 1 << int(digit)\n best = max(best, i - memo.get(bitmap, i))\n for j in range(10):\n key = bitmap ^ 1 << j\n best = max(best, i - memo.get(key, i))\n memo[bitmap] = memo.get(bitmap, i)\n return best", "def longestawesome(s: str) -> int:\n (mask, res) = (0, 0)\n dp = [-1] + [len(s)] * 1023\n for i in range(len(s)):\n mask ^= 1 << ord(s[i]) - 48\n for j in range(11):\n check_mask = 1023 & (mask ^ 1 << j)\n res = max(res, i - dp[check_mask])\n dp[mask] = min(dp[mask], i)\n return res", "def longestawesome(s: str) -> int:\n pos = {0: -1}\n bitmask = 0\n ans = 0\n n = len(s)\n for i in range(n):\n bitmask ^= 1 << int(s[i])\n for j in range(10):\n if bitmask ^ 1 << j in pos:\n ans = max(ans, i - pos[bitmask ^ 1 << j])\n if bitmask in pos:\n ans = max(ans, i - pos[bitmask])\n else:\n pos[bitmask] = i\n return ans", "def linear(s):\n ans = 0\n d = {0: -1}\n mask = 0\n for (i, c) in enumerate(s):\n mask = 1 << int(c) ^ mask\n if mask in d:\n ans = max(ans, i - d[mask])\n for j in range(10):\n s = mask ^ 1 << j\n if s in d:\n ans = max(ans, i - d[s])\n if mask not in d:\n d[mask] = i\n return ans\n\ndef longestawesome(s: str) -> int:\n return self.linear(s)\n ans = 0\n for i in range(len(s)):\n d = collections.defaultdict(int)\n odds = set()\n for j in range(i, len(s)):\n d[s[j]] += 1\n if d[s[j]] % 2:\n odds.add(s[j])\n elif s[j] in odds:\n odds.remove(s[j])\n if len(odds) <= 1:\n ans = max(ans, j - i + 1)\n return ans", "def longestawesome(s: str) -> int:\n pos = {}\n open_chars = 0\n pos[open_chars] = 0\n max_len = 0\n for (i, c) in enumerate(s):\n open_chars ^= 1 << int(c)\n for j in range(-1, 10):\n if j == -1:\n mask = 0\n else:\n mask = 1 << j\n if open_chars ^ mask in pos:\n max_len = max(max_len, i + 1 - pos[open_chars ^ mask])\n if open_chars not in pos:\n pos[open_chars] = i + 1\n return max_len", "def longestawesome(s: str) -> int:\n n = len(s)\n a = [0 for _ in range(n)]\n for i in range(n):\n x = a[i - 1] if i > 0 else 0\n a[i] = x ^ 1 << int(s[i])\n dp = 1\n ht = {}\n ht[a[0]] = 0\n for i in range(1, n):\n d = 1\n if a[i] == 0:\n d = i + 1\n else:\n if a[i] in ht:\n d = max(d, i - ht[a[i]])\n for j in range(10):\n x = a[i] ^ 1 << j\n if x == 0:\n d = i + 1\n break\n if x in ht:\n d = max(d, i - ht[x])\n dp = max(dp, d)\n if not a[i] in ht:\n ht[a[i]] = i\n return dp", "def longestawesome(s: str) -> int:\n index = [-1] + [len(s)] * 1023\n ans = 0\n bit = 0\n for (idx, c) in enumerate(s):\n bit ^= 1 << ord(c) - ord('0')\n ans = max([ans, idx - index[bit]] + [idx - index[bit ^ 1 << j] for j in range(10)])\n index[bit] = min(index[bit], idx)\n return ans", "def longestawesome(s: str) -> int:\n mem = {}\n\n def find_awesome(lo, hi, digit_count):\n if lo > hi:\n return 0\n if (lo, hi) in mem:\n return mem[lo, hi]\n if digit_count & digit_count - 1 == 0:\n return hi - lo + 1\n max_len = max(find_awesome(lo + 1, hi, digit_count ^ 1 << int(s[lo])), find_awesome(lo, hi - 1, digit_count ^ 1 << int(s[hi])))\n mem[lo, hi] = max_len\n return max_len\n (lo, hi, digit_count) = (0, len(s) - 1, 0)\n for i in range(lo, hi + 1):\n digit_count ^= 1 << int(s[i])\n return find_awesome(lo, hi, digit_count)\n\ndef longestawesome(s: str) -> int:\n (memo, state) = ({}, 0)\n (memo[state], ans) = (-1, 0)\n for (i, c) in enumerate(s):\n state ^= 1 << int(c)\n if state not in memo:\n memo[state] = i\n else:\n ans = max(ans, i - memo[state])\n for j in range(10):\n state1 = state ^ 1 << j\n if state1 in memo:\n ans = max(ans, i - memo[state1])\n return ans", "def longestawesome(s: str) -> int:\n bd = {}\n bd[0] = -1\n soen = 0\n for (i, n) in enumerate(s):\n soen ^= 1 << int(n)\n bd[soen] = -1\n bd[soen] = i\n for j in range(10):\n soen_cpy = soen\n soen_cpy ^= 1 << j\n if soen_cpy in bd:\n bd[soen_cpy] = i\n soen = 0\n max_ = bd[0] + 1\n for (i, n) in enumerate(s):\n soen ^= 1 << int(n)\n cur_max = bd[soen] - i\n if cur_max > max_:\n max_ = cur_max\n return max_", "def longestawesome(s: str) -> int:\n idx = [-1] + [len(s)] * 1023\n (ans, mask) = (0, 0)\n for (i, c) in enumerate(s):\n update = ord(c) - ord('0')\n mask ^= 1 << update\n ans = max(ans, i - idx[mask])\n for j in range(10):\n ans = ans = max(ans, i - idx[mask ^ 1 << j])\n idx[mask] = min(idx[mask], i)\n return ans", "def longestawesome(s: str) -> int:\n P = [0]\n for c in s:\n x = int(c)\n P.append(P[-1])\n P[-1] ^= 1 << x\n dict = {}\n valid = {1 << x for x in range(10)}\n valid.add(0)\n ans = 0\n for (j, q) in enumerate(P):\n for target in valid:\n i = dict.get(q ^ target, None)\n if i is not None:\n ans = max(ans, j - i)\n dict.setdefault(q, j)\n return ans", "def longestawesome(s: str) -> int:\n d = {}\n d[0] = -1\n mask = 0\n ans = 0\n for (i, ch) in enumerate(s):\n mask ^= 1 << int(ch)\n if mask in d and (i - d[mask]) % 2 == 0:\n ans = max(ans, i - d[mask])\n for j in range(10):\n mask_edit = mask ^ 1 << j\n if mask_edit in d and (i - d[mask_edit]) % 2 == 1:\n ans = max(ans, i - d[mask_edit])\n if mask not in d:\n d[mask] = i\n return ans", "def longestawesome(s: str) -> int:\n tmp = 0\n pos_map = {0: -1}\n ans = 1\n for i in range(len(s)):\n tmp ^= 1 << int(s[i])\n if tmp in pos_map:\n ans = max(ans, i - pos_map[tmp])\n for x in range(10):\n another_tmp = tmp ^ 1 << x\n if another_tmp in pos_map:\n ans = max(ans, i - pos_map[another_tmp])\n if tmp not in pos_map:\n pos_map[tmp] = i\n return ans", "def longestawesome(s: str) -> int:\n (memo, state) = ({}, 0)\n (memo[state], ans) = (-1, 0)\n for (i, c) in enumerate(s):\n state ^= 1 << int(c)\n if state not in memo:\n memo[state] = i\n else:\n ans = max(ans, i - memo[state])\n for n in range(10):\n state1 = state ^ 1 << n\n if state1 in memo:\n ans = max(ans, i - memo[state1])\n return ans", "def longestawesome(s):\n (res, cur, n) = (0, 0, len(s))\n seen = [-1] + [n] * 1024\n for (i, c) in enumerate(s):\n cur ^= 1 << int(c)\n for a in range(10):\n res = max(res, i - seen[cur ^ 1 << a])\n res = max(res, i - seen[cur])\n seen[cur] = min(seen[cur], i)\n return res", "def longestawesome(s: str) -> int:\n p = [0]\n for c in s:\n x = int(c)\n p.append(p[-1])\n p[-1] ^= 1 << x\n first = {}\n valid = {1 << x for x in range(10)}\n valid.add(0)\n res = 0\n for (j, pj) in enumerate(p):\n for target in valid:\n i = first.get(pj ^ target, None)\n if i is not None:\n res = max(res, j - i)\n first.setdefault(pj, j)\n return res", "def longestawesome(s: str) -> int:\n d = {0: -1}\n b = 0\n m = 0\n for (i, c) in enumerate(s):\n b ^= 1 << int(c)\n if not b or not b & b - 1:\n m = max(m, i - d.get(b, i - 1), i + 1)\n if not b:\n h = 1\n for _ in range(10):\n m = max(m, i - d.get(h, i - 1))\n h <<= 1\n else:\n m = max(m, i - d.get(b, i - 1))\n h = 1\n for _ in range(10):\n if h & b:\n m = max(m, i - d.get(~h & b, i - 1))\n else:\n m = max(m, i - d.get(h + b, i - 1))\n h <<= 1\n if b not in d:\n d[b] = i\n return m", "def longestawesome(s: str) -> int:\n prev = [-1] + [len(s)] * 1024\n best = 1\n mask = 0\n for i in range(len(s)):\n mask ^= 1 << int(s[i])\n for j in range(10):\n tmp = mask ^ 1 << j\n if best < i - prev[tmp] + 1:\n best = max(best, i - prev[tmp])\n best = max(best, i - prev[mask])\n prev[mask] = min(prev[mask], i)\n return best", "def longestawesome(s: str) -> int:\n\n def getMatchingMasks(mask):\n st = set([mask])\n for i in range(10):\n st.add(mask ^ 1 << i)\n return st\n mask = 0\n maskDict = dict()\n maskDict[0] = -1\n ans = 0\n for (idx, ch) in enumerate(s):\n digitVal = int(ch)\n mask ^= 1 << digitVal\n for match in getMatchingMasks(mask):\n if match in maskDict:\n ans = max(ans, idx - maskDict[match])\n if mask not in maskDict:\n maskDict[mask] = idx\n return ans", "def longestawesome(s: str) -> int:\n digit_cnt = [0 for _ in range(len(s) + 1)]\n for i in range(1, len(s) + 1):\n digit_cnt[i] = digit_cnt[i - 1] ^ 1 << int(s[i - 1])\n res = 1\n indx = {}\n indx[0] = 0\n for i in range(1, len(digit_cnt)):\n if digit_cnt[i] == 0:\n res = max(res, i)\n continue\n for d in range(10):\n if digit_cnt[i] ^ 1 << d in list(indx.keys()):\n res = max(res, i - indx[digit_cnt[i] ^ 1 << d])\n if not digit_cnt[i] in list(indx.keys()):\n indx[digit_cnt[i]] = i\n return res", "def __init__():\n self.seen = {0: -1}\n self.len = 0\n\ndef update_best_length(num, p):\n if num in self.seen:\n self.len = max(self.len, p - self.seen[num])\n for i in range(10):\n x = num ^ 1 << int(i)\n if x in self.seen:\n self.len = max(self.len, p - self.seen[x])\n\ndef longestawesome(s: str) -> int:\n num = 0\n for (p, c) in enumerate(s):\n num = num ^ 1 << int(c)\n self.update_best_length(num, p)\n if num not in self.seen:\n self.seen[num] = p\n return self.len", "import numpy as np\n\ndef longestawesome(s: str) -> int:\n (memo, state) = ({}, 0)\n p = np.arange(15).reshape(3, 5)\n (memo[state], ans) = (-1, 0)\n for (i, c) in enumerate(s):\n state ^= 1 << int(c)\n if state not in memo:\n memo[state] = i\n else:\n ans = max(ans, i - memo[state])\n for n in range(10):\n state1 = state ^ 1 << n\n if state1 in memo:\n ans = max(ans, i - memo[state1])\n return ans", "def longestawesome(s: str) -> int:\n pattern = [1 << i for i in range(10)]\n (seen, state) = ({}, 0)\n seen[state] = -1\n answer = 0\n for (i, c) in enumerate(s):\n state ^= 1 << int(c)\n if state in seen:\n answer = max(answer, i - seen[state])\n for p in pattern:\n target = state ^ p\n if target in seen:\n answer = max(answer, i - seen[target])\n if state not in seen:\n seen[state] = i\n return answer", "def longestawesome(s: str) -> int:\n s = [ord(x) - ord('0') for x in s]\n ans = 0\n m = [None] * 1024\n m[0] = -1\n y = 0\n for (i, x) in enumerate(s):\n y ^= 1 << x\n for j in range(11):\n p = y ^ 1 << j & 1023\n if m[p] != None:\n ans = max(ans, i - m[p])\n if m[p] == None:\n m[y] = i\n return ans", "def longestawesome(s: str) -> int:\n subsum = [0]\n rtn = 0\n first_appear = {}\n first_appear[0] = 0\n for (i, x) in enumerate(s):\n subsum.append(subsum[i] ^ 1 << int(x))\n if subsum[i + 1] not in first_appear:\n first_appear[subsum[i + 1]] = i + 1\n else:\n rtn = max(rtn, i + 1 - first_appear[subsum[i + 1]])\n for j in range(10):\n if subsum[i + 1] ^ 1 << j in first_appear:\n rtn = max(rtn, i + 1 - first_appear[subsum[i + 1] ^ 1 << j])\n return rtn", "def longestawesome(s: str) -> int:\n res = 0\n count = 0\n record = {count: -1}\n for (i, ss) in enumerate(s):\n count ^= 1 << int(ss)\n if count not in record:\n record[count] = i\n res = max(res, max((i - record[count ^ 1 << t + 1 >> 1] if count ^ 1 << t + 1 >> 1 in record else 0 for t in range(-1, 10))))\n return res", "def longestawesome(s: str) -> int:\n m = collections.defaultdict(lambda : 0)\n\n def convertToKey():\n x = 0\n for i in range(10):\n x += m[i] % 2 << i\n return x\n presum = {}\n presum[0] = -1\n res = 0\n for (i, j) in enumerate(s):\n m[int(j)] += 1\n key = convertToKey()\n if key in presum:\n res = max(res, i - presum[key])\n for x in range(10):\n newKey = key\n if key >> x & 1:\n newKey -= 1 << x\n else:\n newKey |= 1 << x\n if newKey in presum:\n res = max(res, i - presum[newKey])\n if key not in presum:\n presum[key] = i\n return res", "def longestawesome(s: str) -> int:\n pos = {}\n\n def f(c):\n return ord(c) - ord('0')\n (mask, ans) = (0, 1)\n pos[0] = -1\n for (n, ch) in enumerate(s):\n p = f(ch)\n mask ^= 1 << p\n if mask in pos:\n len = n - pos[mask]\n if len % 2 == 0:\n ans = max(ans, len)\n for nn in range(10):\n nmask = mask ^ 1 << nn\n if nmask in pos:\n len = n - pos[nmask]\n if len % 2 == 1:\n ans = max(ans, len)\n if mask not in pos:\n pos[mask] = n\n return ans", "def longestawesome(s: str) -> int:\n first_pos = [-1 for i in range(1024)]\n first_pos[0] = 0\n cur_xor = 0\n xors = [0] + [1 << i for i in range(10)]\n max_len = 0\n for i in range(len(s)):\n cur_xor = cur_xor ^ 1 << int(s[i])\n for try_xor in xors:\n prev_xor = cur_xor ^ try_xor\n if first_pos[prev_xor] != -1:\n max_len = max(max_len, i - first_pos[prev_xor] + 1)\n if first_pos[cur_xor] == -1:\n first_pos[cur_xor] = i + 1\n return max_len", "from typing import Dict, Set\nfrom collections import Counter\n\ndef longestawesome(s: str) -> int:\n mask_pos = {0: -1}\n mask = 0\n result = 0\n for pos in range(len(s)):\n mask ^= 1 << int(s[pos])\n result = max(result, pos - mask_pos.get(mask, pos))\n for shift in range(10):\n result = max(result, pos - mask_pos.get(mask ^ 1 << shift, pos))\n mask_pos.setdefault(mask, pos)\n return result\n\ndef longestawesome1(s: str) -> int:\n result = 0\n for start in range(len(s)):\n count: Dict[str, int] = Counter()\n odd = 0\n for end in range(start, len(s)):\n count[s[end]] += 1\n if count[s[end]] & 1 > 0:\n odd += 1\n else:\n odd -= 1\n if odd <= 1:\n result = max(result, end + 1 - start)\n return result", "def longestawesome(s: str) -> int:\n F = {0: 0}\n res = 0\n mask = 0\n j = 0\n for c in s:\n j += 1\n mask ^= 1 << ord(c) - ord('0')\n for i in range(0, 10):\n new_mask = mask ^ 1 << i\n if new_mask in list(F.keys()):\n res = max(res, j - F[new_mask])\n if not mask:\n res = max(res, j)\n if mask not in list(F.keys()):\n F[mask] = j\n return res", "def longestawesome(s):\n d = {0: -1}\n t = 0\n ans = 0\n for i in range(len(s)):\n num = int(s[i])\n t ^= 1 << 9 - num\n if t not in d:\n d[t] = i\n for m in range(10):\n temp = t ^ 1 << 9 - m\n if temp in d:\n ans = max(ans, i - d[temp])\n else:\n ans = max(ans, i - d[t])\n for m in range(10):\n temp = t ^ 1 << 9 - m\n if temp in d:\n ans = max(ans, i - d[temp])\n return ans", "def longestawesome(s: str) -> int:\n (seen, prefix, ans) = ({0: -1}, 0, 0)\n for (i, char) in enumerate(s):\n prefix ^= 1 << int(char)\n ans = max(ans, i - seen.get(prefix, float('inf')))\n for j in range(10):\n p = prefix ^ 1 << j\n ans = max(ans, i - seen.get(p, float('inf')))\n if prefix not in seen:\n seen[prefix] = i\n return ans", "from collections import Counter\n\ndef longestawesome(s: str) -> int:\n seen = {0: -1}\n (res, prefix) = (0, 0)\n for (i, num) in enumerate(map(int, s)):\n prefix ^= 1 << num\n res = max(res, i - seen.get(prefix, float('inf')))\n for k in range(10):\n prefix_add_odd = prefix ^ 1 << k\n res = max(res, i - seen.get(prefix_add_odd, float('inf')))\n seen.setdefault(prefix, i)\n return res", "def longestawesome(s: str) -> int:\n dp = {}\n dp[0] = -1\n (state, ans) = (0, 0)\n for (i, c) in enumerate(s):\n state ^= 1 << int(c)\n if state not in dp:\n dp[state] = i\n else:\n ans = max(ans, i - dp[state])\n for num in range(10):\n if state ^ 1 << num in dp:\n ans = max(ans, i - dp[state ^ 1 << num])\n return ans", "def longestawesome(s: str) -> int:\n idxs = [1000000000.0 for _ in range(1024)]\n idxs[0] = -1\n ans = 0\n mask = 0\n for (i, ch) in enumerate(s):\n mask ^= 1 << ord(ch) - ord('0')\n ans = max([ans, i - idxs[mask]] + [i - idxs[mask ^ 1 << j] for j in range(10)])\n idxs[mask] = min(idxs[mask], i)\n return ans", "def count_set_bits(n):\n count = 0\n for i in range(32):\n count += n >> i & 1\n return count\n\ndef longestawesome(s: str) -> int:\n xormap = dict()\n xormap[0] = -1\n xor = 0\n max_length = 0\n for i in range(len(s)):\n xor = xor ^ 1 << int(s[i])\n max_length = max(max_length, i - xormap.get(xor, float('Inf')))\n for j in range(10):\n temp_xor = xor ^ 1 << j\n max_length = max(max_length, i - xormap.get(temp_xor, float('Inf')))\n xormap[xor] = min(i, xormap.get(xor, float('Inf')))\n return max_length", "def longestawesome(s: str) -> int:\n d = collections.defaultdict(int)\n d[0] = -1\n mask = 0\n ans = 0\n for i in range(len(s)):\n mask ^= 1 << int(s[i])\n if mask in d:\n ans = max(ans, i - d[mask])\n else:\n d[mask] = i\n for j in range(10):\n tem = mask\n tem ^= 1 << j\n if tem in d:\n ans = max(ans, i - d[tem])\n return ans", "def longestawesome(s: str) -> int:\n digit = []\n for i in range(10):\n digit.append(1 << i)\n digit.append(0)\n cum = 0\n bk = [-2 for _ in range(2 ** 10 + 1)]\n bk[0] = -1\n ans = 0\n for (i, x) in enumerate(s):\n x = int(x)\n cum ^= digit[x]\n for d in digit:\n mask = cum ^ d\n if bk[mask] >= -1:\n ans = max(ans, i - bk[mask])\n if bk[cum] == -2:\n bk[cum] = i\n return ans", "from collections import defaultdict\n\ndef longestawesome(s: str) -> int:\n n = len(s)\n dp = [n for i in range(1024)]\n dp[0] = -1\n (mask, ret) = (0, 0)\n for (i, c) in enumerate(s):\n mask ^= 1 << int(c)\n for num in range(10):\n ret = max(ret, i - dp[mask ^ 1 << num])\n ret = max(ret, i - dp[mask])\n dp[mask] = min(dp[mask], i)\n return ret", "def longestawesome(s: str) -> int:\n pattern = 0\n d = {pattern: -1}\n res = 0\n for (cur_i, x) in enumerate(s):\n pattern ^= 1 << int(x)\n for i in range(10):\n new_pattern = pattern ^ 1 << i\n res = max(res, cur_i - d.get(new_pattern, cur_i))\n res = max(res, cur_i - d.get(pattern, cur_i))\n d.setdefault(pattern, cur_i)\n return res", "def longestawesome(s: str) -> int:\n bitmask = {}\n mask = 0\n ans = 1\n n = len(s)\n bitmask[0] = -1\n for i in range(n):\n mask ^= 1 << int(s[i])\n if mask in bitmask:\n ans = max(ans, i - bitmask[mask])\n for j in range(10):\n test = mask ^ 1 << j\n if test in bitmask:\n ans = max(ans, i - bitmask[test])\n if mask not in bitmask:\n bitmask[mask] = i\n return ans", "import numpy as np\n\ndef longestawesome(s: str) -> int:\n (mask, res) = (0, 0)\n dp = np.full(1024, len(s))\n dp[0] = -1\n for i in range(len(s)):\n mask ^= 1 << ord(s[i]) - 48\n for j in range(11):\n check_mask = 1023 & (mask ^ 1 << j)\n res = max(res, i - dp[check_mask])\n dp[mask] = min(dp[mask], i)\n return res", "def longestawesome(s: str) -> int:\n if len(s) == 0:\n return 0\n max_len = 1\n p = [0] * len(s)\n seen = {0: -1}\n for i in range(0, len(s)):\n d = ord(s[i]) - ord('0')\n p[i] = 1 << d ^ p[i - 1]\n for od in range(10):\n x = p[i] | 1 << od\n if x in seen:\n max_len = max(max_len, i - seen[x])\n y = p[i] & ~(1 << od)\n if y in seen:\n max_len = max(max_len, i - seen[y])\n if p[i] not in seen:\n seen[p[i]] = i\n return max_len", "def longestawesome(s: str) -> int:\n (m, state) = (defaultdict(int), [0] * 10)\n m[tuple(state)] = -1\n ans = 0\n for (i, c) in enumerate(s):\n k = int(c)\n state[k] = 1 - state[k]\n tstate = tuple(state)\n if tstate not in m:\n m[tstate] = i\n else:\n ans = max(ans, i - m[tstate])\n for n in range(10):\n state[n] = 1 - state[n]\n tstate = tuple(state)\n if tstate in m:\n ans = max(ans, i - m[tstate])\n state[n] = 1 - state[n]\n return ans", "def longestawesome(s: str) -> int:\n M = {0: -1}\n ans = 0\n code = 0\n D = [1 << d for d in range(10)]\n for (i, c) in enumerate(s):\n code = code ^ 1 << ord(c) - ord('0')\n if code in M:\n ans = max(ans, i - M[code])\n for dc in D:\n dcode = code ^ dc\n if dcode in M:\n ans = max(ans, i - M[dcode])\n if code not in M:\n M[code] = i\n return ans", "def longestawesome(s: str) -> int:\n (df, dl) = ({}, {})\n df[0] = -1\n sm = 0\n res = 1\n for (i, c) in enumerate(s):\n sm ^= 1 << int(c)\n if sm not in df:\n df[sm] = i\n dl[sm] = i\n for (fk, fv) in df.items():\n for (lk, lv) in dl.items():\n if lv > fv:\n xor = fk ^ lk\n if xor == 0 or xor & xor - 1 == 0:\n res = max(res, lv - fv)\n return res", "from typing import List\n\ndef longestawesome(s: str) -> int:\n res = 0\n pattern: List[bool] = [False] * 10\n existing = {tuple(pattern): -1}\n for (cur_i, char) in enumerate(s):\n num = int(char)\n pattern[num] = not pattern[num]\n for i in range(10):\n new_pattern = pattern.copy()\n new_pattern[i] = not new_pattern[i]\n res = max(res, cur_i - existing.get(tuple(new_pattern), cur_i))\n res = max(res, cur_i - existing.get(tuple(pattern), cur_i))\n existing.setdefault(tuple(pattern), cur_i)\n return res", "def longestawesome(s: str) -> int:\n sLength = len(s)\n earliestBinaries = {}\n current = [0] * 10\n earliestBinaries[tuple(current)] = -1\n currentMax = 0\n\n def computeMaxFromNeighbors(counter, currentTuple):\n currentMax = 0\n if currentTuple in earliestBinaries:\n currentMax = max(currentMax, counter - earliestBinaries[currentTuple])\n neighborList = list(currentTuple)\n for i in range(len(currentTuple)):\n neighborList[i] = 1 - neighborList[i]\n neighborTuple = tuple(neighborList)\n if neighborTuple in earliestBinaries:\n currentMax = max(currentMax, counter - earliestBinaries[neighborTuple])\n neighborList[i] = 1 - neighborList[i]\n return currentMax\n for (counter, char) in enumerate(s):\n current[int(char)] = 1 - current[int(char)]\n currentTuple = tuple(current)\n currentMax = max(currentMax, computeMaxFromNeighbors(counter, currentTuple))\n if currentTuple not in earliestBinaries:\n earliestBinaries[currentTuple] = counter\n return currentMax", "def longestawesome(s: str) -> int:\n mx = 0\n table = {frozenset(): -1}\n (acs, cs) = (set(), set())\n for (i, c) in enumerate(s):\n acs.add(c)\n if c in cs:\n cs.remove(c)\n else:\n cs.add(c)\n fcs = frozenset(cs)\n if fcs in table:\n mx = max(mx, i - table[fcs])\n for c in acs:\n if c in cs:\n cs.remove(c)\n rfcs = frozenset(cs)\n cs.add(c)\n if rfcs in table:\n mx = max(mx, i - table[rfcs])\n else:\n cs.add(c)\n rfcs = frozenset(cs)\n cs.remove(c)\n if rfcs in table:\n mx = max(mx, i - table[rfcs])\n table[fcs] = min(table.get(fcs, float('inf')), i)\n return mx", "def longestawesome(s: str) -> int:\n (dic, mask, res) = ({0: -1}, 0, 1)\n for (i, ch) in enumerate(s):\n mask ^= 1 << int(ch)\n dic.setdefault(mask, i)\n res = max(res, i - min([dic[mask]] + [dic.get(mask ^ 1 << k, float('inf')) for k in range(11)]))\n return res", "def longestawesome(s: str) -> int:\n n = len(s)\n res = 0\n mask = 0\n idx = [n + 1] * 1024\n idx[0] = -1\n for (i, c) in enumerate(s):\n mask ^= 1 << ord(c) - ord('0')\n res = max(res, i - idx[mask])\n res = max(res, max([i - idx[mask ^ 1 << j] for j in range(10)]))\n idx[mask] = min(idx[mask], i)\n return res", "from collections import defaultdict\n\ndef longestawesome(s: str) -> int:\n dlist = [1] * 10\n for i in range(9):\n dlist[i + 1] = dlist[i] * 2\n count = defaultdict(int)\n dp = dict()\n ans = 0\n dp[0] = -1\n for (i, num) in enumerate(s):\n count[num] += 1\n cur = 0\n curdp = 10 * [0]\n for ar in range(10):\n st = str(ar)\n val = count[st] % 2\n cur += val * dlist[ar]\n curdp[ar] = val\n if cur in dp:\n ans = max(ans, i - dp[cur])\n else:\n dp[cur] = i\n for ar in range(10):\n if curdp[ar] == 1:\n val = -1\n else:\n val = 1\n cur += val * dlist[ar]\n if cur in dp:\n ans = max(ans, i - dp[cur])\n cur -= val * dlist[ar]\n return ans", "def longestawesome(s: str) -> int:\n pattern = [False] * 10\n d = {tuple(pattern): -1}\n res = 0\n for (i, x) in enumerate(s):\n num = int(x)\n pattern[num] = not pattern[num]\n res = max(res, i - d.get(tuple(pattern), i))\n for k in range(10):\n new_pattern = pattern.copy()\n new_pattern[k] = not new_pattern[k]\n res = max(res, i - d.get(tuple(new_pattern), i))\n d.setdefault(tuple(pattern), i)\n return res", "def longestawesome(s: str) -> int:\n d = defaultdict(lambda : 1e+20)\n d[0] = -1\n res = 0\n mask = 0\n for (i, val) in enumerate(s):\n mask ^= 1 << int(val)\n d[mask] = min(d[mask], i)\n res = max(res, i - d[mask])\n for k in range(11):\n res = max(res, i - d[mask ^ 1 << k])\n return res", "import collections\n\ndef longestawesome(s: str) -> int:\n n = len(s)\n memo = [0] * 10\n d = collections.defaultdict(list)\n ans = 1\n d[0].append(-1)\n for (i, x) in enumerate(s):\n memo[int(x)] += 1\n key = 0\n for (j, y) in enumerate(memo):\n if y % 2 == 1:\n key += 2 ** j\n d[key].append(i)\n if len(d[key]) >= 2:\n ans = max(ans, d[key][-1] - d[key][0])\n for (j, y) in enumerate(memo):\n if y % 2 == 0:\n new_key = key + 2 ** j\n if len(d[new_key]) > 0:\n ans = max(ans, d[key][-1] - d[new_key][0])\n else:\n new_key = key - 2 ** j\n if len(d[new_key]) > 0:\n ans = max(ans, d[key][-1] - d[new_key][0])\n return ans", "def longestawesome(s: str) -> int:\n bit_mask_mapping = {tuple([0] * 10): -1}\n bit_mask = [0] * 10\n max_len = 0\n for (ch_i, ch) in enumerate(s):\n cur_int = int(ch)\n bit_mask[cur_int] ^= 1\n bit_mask_str = tuple(bit_mask)\n if bit_mask_str in bit_mask_mapping:\n max_len = max(max_len, ch_i - bit_mask_mapping[bit_mask_str])\n for j in range(10):\n tmp_mask = tuple(bit_mask[:j] + [bit_mask[j] ^ 1] + bit_mask[j + 1:])\n if tmp_mask in bit_mask_mapping:\n max_len = max(max_len, ch_i - bit_mask_mapping[tmp_mask])\n if bit_mask_str not in bit_mask_mapping:\n bit_mask_mapping[bit_mask_str] = ch_i\n return max_len", "def longestawesome(s: str) -> int:\n digits = [2 ** i for i in range(10)] + [0]\n (max_len, xor, dictF, dictB) = (0, 0, {0: -1}, {})\n for i in range(len(s)):\n xor = xor ^ digits[int(s[i])]\n if xor not in dictF:\n dictF[xor] = i\n dictB[xor] = i\n max_len = 0\n for i in dictB:\n max_len = max([max_len] + [dictB[i] - dictF[j ^ i] for j in digits if j ^ i in dictF])\n return max_len", "def longestawesome(s: str) -> int:\n left_most_masks = {0: -1}\n valid_masks = {1 << i for i in range(10)} | {0}\n ans = 0\n cur_mask = 0\n for (idx, x) in enumerate(list(s)):\n cur_mask = cur_mask ^ 1 << int(x)\n for valid_mask in valid_masks:\n left_mask = valid_mask ^ cur_mask\n if left_mask in left_most_masks:\n ans = max(ans, idx - left_most_masks[left_mask])\n if cur_mask not in left_most_masks:\n left_most_masks[cur_mask] = idx\n return ans", "def longestawesome(s: str) -> int:\n n = len(s)\n (m, seen, ans) = (0, [-1] + [n] * 1024, 1)\n for (i, x) in enumerate(s):\n m ^= 1 << int(x)\n for d in range(10):\n ans = max(ans, i - seen[m ^ 1 << d])\n ans = max(ans, i - seen[m])\n seen[m] = min(seen[m], i)\n return ans", "def longestawesome(s: str) -> int:\n rec = 0\n seen = {0: -1}\n mask = 0\n for (i, n) in enumerate(s):\n mask ^= 1 << int(n)\n if mask in seen:\n rec = max(rec, i - seen[mask])\n else:\n seen[mask] = i\n for d in range(10):\n omask = mask ^ 1 << d\n if omask in seen:\n rec = max(rec, i - seen[omask])\n return rec", "def longestawesome(s: str) -> int:\n mem = {0: -1}\n res = 0\n state = 0\n for (i, x) in enumerate(s):\n idx = ord(x) - ord('0')\n state ^= 1 << idx\n if state in mem:\n res = max(res, i - mem[state])\n for shift in range(10):\n tmp = state ^ 1 << shift\n if tmp in mem:\n res = max(res, i - mem[tmp])\n if state not in mem:\n mem[state] = i\n return res", "def longestawesome(s: str) -> int:\n count = 0\n digits = 0\n for c in s:\n c = int(c)\n digits ^= 1 << c\n if digits & 1 << c != 0:\n count += 1\n else:\n count -= 1\n result = 0\n n = len(s)\n for i in range(n):\n digits2 = digits\n count2 = count\n for j in reversed(list(range(i, n))):\n if j - i + 1 <= result or count2 <= 1:\n result = max(result, j - i + 1)\n break\n c = int(s[j])\n digits2 ^= 1 << c\n if digits2 & 1 << c != 0:\n count2 += 1\n else:\n count2 -= 1\n c = int(s[i])\n digits ^= 1 << c\n if digits & 1 << c != 0:\n count += 1\n else:\n count -= 1\n return result\n\ndef longestawesome(s: str) -> int:\n from collections import defaultdict\n digits = {}\n digits[0] = -1\n prefix = 0\n result = 0\n for i in range(len(s)):\n c = int(s[i])\n prefix ^= 1 << c\n if prefix in digits:\n result = max(result, i - digits[prefix])\n else:\n digits[prefix] = i\n for k in range(10):\n tmp = prefix ^ 1 << k\n if tmp in digits:\n result = max(result, i - digits[tmp])\n return result", "def longestawesome(s: str) -> int:\n mask = {n: 1 << n for n in range(10)}\n target = [0] + list(mask.values())\n loc = [-2] * (1 << 10)\n for x in target:\n loc[x] = -1\n sofar = 0\n ans = 0\n for (idx, ch) in enumerate(s):\n m = mask[int(ch)]\n sofar = sofar ^ m\n if loc[sofar] > -2:\n ans = max(ans, idx - loc[sofar])\n for t in target:\n ntarget = sofar ^ t\n if loc[ntarget] == -2:\n loc[ntarget] = idx\n return ans", "def longestawesome(s: str) -> int:\n N = len(s)\n prefix = [0 for _ in range(N + 1)]\n for (i, value) in enumerate(s):\n x = int(value)\n prefix[i + 1] = prefix[i] ^ 1 << x\n valids = set([0])\n for i in range(10):\n valids.add(1 << i)\n ans = 0\n seen = collections.defaultdict(int)\n for (j, q) in enumerate(prefix):\n for target in valids:\n want = q ^ target\n if want not in seen:\n continue\n i = seen[want]\n ans = max(ans, j - i)\n if q not in seen:\n seen[q] = j\n return ans", "def longestawesome(s: str) -> int:\n n = len(s)\n ans = 0\n d = {0: -1}\n rolling = 0\n for (i, v) in enumerate(s):\n rolling ^= 1 << int(v)\n for x in range(10):\n diff = rolling ^ 1 << x\n if diff in d:\n ans = max(ans, i - d[diff])\n if rolling in d:\n ans = max(ans, i - d[rolling])\n else:\n d[rolling] = i\n return ans", "def longestawesome(s: str) -> int:\n n = len(s)\n res = mask = 0\n seen = [n] * 1024\n seen[0] = -1\n for i in range(n):\n mask ^= 1 << int(s[i])\n res = max(res, i - seen[mask])\n for num in range(10):\n res = max(res, i - seen[mask ^ 1 << num])\n seen[mask] = min(seen[mask], i)\n return res", "def longestawesome(s: str) -> int:\n N = len(s)\n prefix = [0 for _ in range(N + 1)]\n for i in range(1, N + 1):\n x = int(s[i - 1])\n prefix[i] = prefix[i - 1] ^ 1 << x\n valids = [0]\n for i in range(10):\n valids.append(1 << i)\n seen = collections.defaultdict(int)\n ans = 0\n for (i, p) in enumerate(prefix):\n for valid in valids:\n want = p ^ valid\n if want not in seen:\n continue\n k = seen[want]\n cand = i - k\n ans = max(ans, cand)\n if p not in seen:\n seen[p] = i\n return ans", "def gen_prefixes(s):\n ans = {0: [0]}\n parity = 0\n for (ind, ch) in enumerate(s):\n after = ind + 1\n parity ^= 1 << int(ch)\n ans.setdefault(parity, [])\n ans[parity].append(after)\n return ans\n\ndef get_awesomes(prefixes):\n ans = 1\n for A in prefixes:\n for xbit_ind in range(11):\n if xbit_ind == 10:\n B = A\n else:\n B = A ^ 1 << xbit_ind\n if B not in prefixes:\n continue\n (pA, pB) = (prefixes[A], prefixes[B])\n ans = max(ans, max(pB) - min(pA))\n ans = max(ans, max(pA) - min(pB))\n return ans\n\ndef longestawesome(s: str) -> int:\n prefixes = gen_prefixes(s)\n return get_awesomes(prefixes)", "def longestawesome(s: str) -> int:\n h = {}\n ll = len(s)\n m = 0\n maxi = -1\n h[0] = -1\n for i in range(0, len(s)):\n m = m ^ 1 << int(s[i])\n if m in h:\n maxi = max(maxi, i - h.get(m))\n else:\n h[m] = i\n for l in range(0, 10):\n new_hash = m ^ 1 << l\n if new_hash in h:\n maxi = max(maxi, i - h[new_hash])\n return maxi", "def longestawesome(s: str) -> int:\n max_len = 0\n mapping_pos = {0: -1}\n acc = 0\n for (idx, digit) in enumerate([ord(c) - ord('0') for c in s]):\n acc ^= 1 << digit\n for x in range(10):\n tmp = acc ^ 1 << x\n if tmp in mapping_pos:\n max_len = max(max_len, idx - mapping_pos[tmp])\n if acc in mapping_pos:\n max_len = max(max_len, idx - mapping_pos[acc])\n if acc not in mapping_pos:\n mapping_pos[acc] = idx\n return max_len", "def longestawesome(s: str) -> int:\n d = defaultdict(int)\n d[0] = -1\n mask = 0\n ans = 0\n for i in range(len(s)):\n curr = ord(s[i]) - ord('0')\n mask ^= 1 << curr\n if mask in d:\n ans = max(ans, i - d[mask])\n else:\n d[mask] = i\n for j in range(10):\n new_mask = mask ^ 1 << j\n if new_mask in d:\n ans = max(ans, i - d[new_mask])\n return ans", "def longestawesome(s: str) -> int:\n seen = {0: -1}\n max_len = 0\n n = 0\n for i in range(len(s)):\n digit = int(s[i])\n n = n ^ 1 << digit\n if n in seen:\n max_len = max(max_len, i - seen[n])\n for start in range(10):\n m = n ^ 1 << start\n if m in seen:\n max_len = max(max_len, i - seen[m])\n if n not in seen:\n seen[n] = i\n return max_len", "def longestawesome(s: str) -> int:\n seen = [len(s)] * (1 << 10)\n seen[0] = -1\n mask = 0\n res = 0\n for (i, char) in enumerate(s):\n mask ^= 1 << int(char)\n res = max(res, i - seen[mask])\n for j in range(10):\n temp = 1 << j ^ mask\n res = max(res, i - seen[temp])\n seen[mask] = min(seen[mask], i)\n return res", "def longestawesome(s: str) -> int:\n prefix = {0: -1}\n curr = 0\n length = 1\n powers = [0] + [1 << j for j in range(10)]\n for (i, c) in enumerate(s):\n curr ^= 1 << int(c)\n for p in powers:\n length = max(length, i - prefix.get(curr ^ p, len(s)))\n if curr not in prefix:\n prefix[curr] = i\n return length", "def longestawesome(s: str) -> int:\n mask = 0\n pre = {0: -1}\n result = 0\n for i in range(10):\n pre[0 ^ 1 << i] = -1\n for (i, c) in enumerate(s):\n n = 1 << int(c)\n mask ^= n\n if mask in pre:\n result = max(result, i - pre[mask])\n for ii in range(10):\n nmask = mask ^ 1 << ii\n if nmask not in pre:\n pre[nmask] = i\n return result", "def longestawesome(s: str) -> int:\n (res, mask) = (0, 0)\n n = len(s)\n memo = [n] * 1024\n memo[0] = -1\n for (i, ch) in enumerate(s):\n mask ^= 1 << int(ch)\n res = max(res, i - memo[mask])\n for j in range(10):\n test_mask = mask ^ 1 << j\n res = max(res, i - memo[test_mask])\n memo[mask] = min(memo[mask], i)\n return res", "def longestawesome(s):\n d = {0: -1}\n cands = {1 << x for x in range(10)}\n cands.add(0)\n cur = 0\n res = 0\n for (i, c) in enumerate(s):\n cur ^= 1 << int(c)\n for cand in cands:\n res = max(res, i - d.get(cur ^ cand, i))\n if cur not in d:\n d[cur] = i\n return res", "def longestawesome(s: str) -> int:\n d = 0\n m = 0\n l = []\n l.append(d)\n dd = {}\n dd[0] = [0, 0]\n for i in range(len(s)):\n c = s[i]\n d = d ^ 1 << int(c)\n l.append(d)\n if d not in dd:\n dd[d] = [i + 1, i + 1]\n else:\n dd[d] = [min(dd[d][0], i + 1), max(dd[d][1], i + 1)]\n di = {}\n for i in range(2 ** 10):\n ll = {i}\n for k in range(10):\n ll.add(i ^ 1 << k)\n di[i] = ll\n for i in dd:\n for j in di[i]:\n if j in dd:\n m = max(abs(dd[j][0] - dd[i][1]), m)\n m = max(abs(dd[j][1] - dd[i][0]), m)\n return m", "def longestawesome(s: str) -> int:\n d = {0: -1}\n mask = 0\n maxi = 1\n for i in range(len(s)):\n x = int(s[i])\n mask = mask ^ 1 << x\n for j in range(0, 10):\n if mask ^ 1 << j in d:\n maxi = max(maxi, i - d[mask ^ 1 << j])\n if mask in d:\n maxi = max(maxi, i - d[mask])\n else:\n d[mask] = i\n return maxi", "def longestawesome(s: str) -> int:\n cur = ans = 0\n m = {}\n for (i, c) in enumerate(s):\n cur ^= 1 << int(c)\n if cur == 0:\n ans = max(ans, i + 1)\n elif cur == 2 ** int(math.log(cur, 2)):\n ans = max(ans, i + 1)\n else:\n for j in range(10):\n new = cur ^ 1 << j\n if new in m:\n ans = max(i - m[new], ans)\n if cur not in m:\n m[cur] = i\n return ans", "def longestawesome(s: str) -> int:\n earliest_occ = defaultdict(lambda : float('inf'))\n earliest_occ[0] = -1\n msk = 0\n ans = 1\n for i in range(len(s)):\n msk ^= 1 << int(s[i])\n earliest_occ[msk] = min(i, earliest_occ[msk])\n for j in range(10):\n ans = max(ans, i - earliest_occ[msk ^ 1 << j])\n ans = max(ans, i - earliest_occ[msk])\n return ans", "def longestawesome(s: str) -> int:\n ans = 1\n mask = 0\n memo = {0: -1}\n for (idx, ch) in enumerate(s):\n mask = mask ^ 1 << int(ch)\n if mask in memo:\n ans = max(ans, idx - memo[mask])\n for i in range(10):\n check = mask ^ 1 << i\n if check in memo:\n ans = max(ans, idx - memo[check])\n if not mask in memo:\n memo[mask] = idx\n return ans", "def longestawesome(s: str) -> int:\n s = [int(c) for c in s]\n seen = {0: -1}\n valid = [0] + [1 << i for i in range(10)]\n totSum = 0\n res = 0\n N = len(s)\n for i in range(N):\n totSum ^= 1 << s[i]\n for y in valid:\n needed = totSum ^ y\n if needed in seen:\n res = max(res, i - seen[needed])\n if totSum not in seen:\n seen[totSum] = i\n return res", "def longestawesome(s: str) -> int:\n n = len(s)\n if n <= 1:\n return n\n dp = [-1] + [n] * 1023\n (mask, res) = (0, 0)\n for i in range(n):\n mask = mask ^ 1 << int(s[i])\n for j in range(11):\n ch_mask = 1023 & (mask ^ 1 << j)\n res = max(res, i - dp[ch_mask])\n dp[mask] = min(i, dp[mask])\n return res", "def longestawesome(s: str) -> int:\n curr = 0\n longest = 0\n first = {0: -1}\n for (i, c) in enumerate(s):\n curr ^= 1 << int(c)\n if curr in first:\n longest = max(longest, i - first[curr])\n else:\n first[curr] = i\n mask = 1 << 9\n while mask > 0:\n if curr ^ mask in first:\n longest = max(longest, i - first[curr ^ mask])\n mask >>= 1\n return longest", "def longestawesome(s: str) -> int:\n if s == s[::-1]:\n return len(s)\n (pattern, re) = (0, 0)\n exit = {pattern: -1}\n for (idx, val) in enumerate(s):\n pattern ^= 1 << int(val)\n for k in range(10):\n new_pattern = pattern ^ 1 << k\n re = max(re, idx - exit.get(new_pattern, idx))\n re = max(re, idx - exit.get(pattern, idx))\n exit.setdefault(pattern, idx)\n return re", "def longestawesome(s: str) -> int:\n cur = res = 0\n d = defaultdict(lambda : float('inf'), {0: -1})\n for (i, ch) in enumerate(s):\n cur ^= 1 << int(ch)\n res = max(res, i - d[cur])\n for j in range(10):\n res = max(res, i - d[cur ^ 1 << j])\n d[cur] = min(d[cur], i)\n return res", "def longestawesome(s: str) -> int:\n max_val = 0\n seen = {0: -1}\n cur = 0\n for (i, char) in enumerate(s):\n cur ^= 1 << int(char)\n seen.setdefault(cur, i)\n max_val = max(max_val, i - seen[cur])\n for a in range(10):\n max_val = max(max_val, i - seen.get(cur ^ 1 << a, i))\n return max_val", "def longestawesome(s: str) -> int:\n cur = res = 0\n check = defaultdict(lambda : float('inf'))\n check[0] = -1\n for (i, c) in enumerate(s):\n c = int(c)\n cur ^= 1 << c\n res = max(res, i - check[cur])\n for a in range(10):\n res = max(res, i - check[cur ^ 1 << a])\n check[cur] = min(check[cur], i)\n return res", "def longestawesome(s: str) -> int:\n ls = len(s)\n table = [-1] + [ls] * 1023\n mask = res = 0\n for i in range(ls):\n mask ^= 1 << int(s[i])\n for j in range(11):\n temp = mask\n temp ^= 1023 & 1 << j\n res = max(res, i - table[temp])\n if table[mask] == ls:\n table[mask] = i\n return res", "from collections import defaultdict\n\ndef longestawesome(s: str) -> int:\n\n def isPalindrome(dic, l, r):\n odds = set()\n length = 0\n for (k, v) in list(dic.items()):\n if v % 2 == 1:\n odds.add(k)\n length += v\n if len(odds) == 0 or len(odds) == 1:\n return length\n elif len(odds) == 2:\n for num in odds:\n if num == l or num == r:\n return length - 1\n return 0\n elif len(odds) == 3:\n flag = 0\n for num in odds:\n if num == l or num == r:\n flag += 1\n if flag == 2:\n return length - 2\n else:\n return 0\n else:\n return 0\n\n def compact(s):\n numbers = []\n counts = []\n for num in s:\n if len(numbers) == 0 and len(counts) == 0:\n numbers.append(num)\n counts.append(1)\n continue\n if num == numbers[-1]:\n counts[-1] += 1\n else:\n numbers.append(num)\n counts.append(1)\n return (numbers, counts)\n\n def rollingHash(numbers, counts, l):\n anss = []\n dic = defaultdict(int)\n cur_max = 0\n max_acc = 0\n for i in range(l):\n num = numbers[i]\n cnt = counts[i]\n dic[num] += cnt\n max_acc += cnt\n cur_max = max(cur_max, max_acc)\n anss.append(isPalindrome(dic, numbers[0], numbers[l - 1]))\n for i in range(l, len(numbers)):\n l_num = numbers[i - l]\n l_cnt = counts[i - l]\n dic[l_num] -= l_cnt\n r_num = numbers[i]\n r_cnt = counts[i]\n dic[r_num] += r_cnt\n max_acc -= l_cnt\n max_acc += r_cnt\n cur_max = max(cur_max, max_acc)\n anss.append(isPalindrome(dic, numbers[i - l + 1], r_num))\n return (max(anss), cur_max)\n (numbers, counts) = compact(s)\n cur_max = 0\n for l in range(len(numbers), 0, -1):\n (new_max, max_acc) = rollingHash(numbers, counts, l)\n cur_max = max(cur_max, new_max)\n if cur_max >= max_acc:\n return cur_max\n return 1", "def longestawesome(s: str) -> int:\n\n def check(guess):\n num_odd = 0\n for (_, val) in list(guess.items()):\n num_odd += val % 2 == 1\n return num_odd <= 1\n N = len(s)\n if N > 70000 and s.startswith('0000000'):\n return 29995\n alphabet = set(s)\n for l in reversed(list(range(N + 1))):\n counts = {c: 0 for c in alphabet}\n for i in range(l):\n counts[s[i]] += 1\n if check(counts):\n return l\n for i in range(N - l):\n counts[s[i]] -= 1\n counts[s[i + l]] += 1\n if check(counts):\n return l", "def longestawesome(s: str) -> int:\n dp = [-2] * 1024\n run = 0\n ans = 0\n dp[0] = -1\n for (j, i) in enumerate(s):\n k = int(i)\n run ^= 1 << k\n if dp[run] == -2:\n dp[run] = j\n else:\n ans = max(ans, j - dp[run])\n for k in range(10):\n if dp[run ^ 1 << k] != -2:\n ans = max(ans, j - dp[run ^ 1 << k])\n return ans", "def longestawesome(s: str) -> int:\n n = len(s)\n c = 0\n counts = [c]\n for x in s:\n c ^= 1 << ord(x) - ord('0')\n counts.append(c)\n good = {1 << i for i in range(10)}\n good.add(0)\n m = {}\n for (i, c) in enumerate(counts):\n if c not in m:\n m[c] = i\n res = 0\n for i in range(1, n + 1):\n for d in (counts[i] ^ g for g in good):\n if d in m:\n res = max(res, i - m[d])\n return res", "def longestawesome(s: str) -> int:\n ps = {}\n mask = 0\n best = 0\n ps[mask] = -1\n for (i, c) in enumerate(s):\n d = int(c)\n mask ^= 1 << d\n if mask in ps:\n best = max(best, i - ps[mask])\n else:\n ps[mask] = i\n for k in range(10):\n if mask ^ 1 << k in ps:\n best = max(best, i - ps[mask ^ 1 << k])\n return best", "def longestawesome(s: str) -> int:\n mask_dict = {0: -1}\n mask = 0\n max_length = 0\n for (i, ch) in enumerate(s):\n mask ^= 1 << ord(ch) - ord('0')\n if mask in mask_dict:\n max_length = max(max_length, i - mask_dict[mask])\n for j in range(10):\n mask_odd = mask ^ 1 << j\n if mask_odd in mask_dict:\n max_length = max(max_length, i - mask_dict[mask_odd])\n if not mask in mask_dict:\n mask_dict[mask] = i\n return max_length", "def longestawesome(s: str) -> int:\n last_pos = Counter({0: -1})\n mask = 0\n result = 0\n for (i, c) in enumerate(s):\n n = int(c)\n mask ^= 1 << n\n if mask in last_pos:\n result = max(result, i - last_pos[mask])\n for j in range(10):\n new_mask = mask ^ 1 << j\n if new_mask in last_pos:\n result = max(result, i - last_pos[new_mask])\n if mask not in last_pos:\n last_pos[mask] = i\n return result", "def __init__():\n self.mn = {}\n self.mx = {}\n\ndef calcMax(tuple1, tuple2):\n ret = 0\n if tuple1 not in self.mn or tuple2 not in self.mn:\n return 0\n ret = max(abs(self.mn[tuple1] - self.mn[tuple2]), ret)\n ret = max(abs(self.mn[tuple1] - self.mx[tuple2]), ret)\n ret = max(abs(self.mx[tuple1] - self.mn[tuple2]), ret)\n ret = max(abs(self.mx[tuple1] - self.mx[tuple2]), ret)\n return ret\n\ndef longestawesome(s: str) -> int:\n l = len(s)\n curTup = [False, False, False, False, False, False, False, False, False, False]\n self.mn[tuple(curTup)] = 0\n self.mx[tuple(curTup)] = 0\n for i in range(l):\n curInt = int(s[i])\n curTup[curInt] = not curTup[curInt]\n if tuple(curTup) not in self.mn:\n self.mn[tuple(curTup)] = i + 1\n self.mx[tuple(curTup)] = i + 1\n mx = 0\n for tup in list(self.mx.keys()):\n mx = max(mx, self.calcMax(tup, tup))\n tupList = []\n for i in tup:\n tupList.append(i)\n for i in range(len(tupList)):\n tupList[i] = not tupList[i]\n mx = max(mx, self.calcMax(tup, tuple(tupList)))\n tupList[i] = not tupList[i]\n return mx", "def longestawesome(s: str) -> int:\n d = {}\n d[0] = -1\n ans = 0\n cnt = 0\n for (i, x) in enumerate(s):\n cnt ^= 1 << ord(x) - ord('0')\n if cnt in d:\n ans = max(ans, i - d[cnt])\n for j in range(10):\n if cnt ^ 1 << j in d:\n ans = max(ans, i - d[cnt ^ 1 << j])\n if not cnt in d:\n d[cnt] = i\n return ans", "def longestawesome(s: str) -> int:\n m = [100000.0 for i in range(1024)]\n m[0] = -1\n es = [1 << i for i in range(10)]\n current = 0\n res = 1\n for (i, c) in enumerate(s):\n n = ord(c) - ord('0')\n current = 1 << n ^ current\n if current == 0:\n res = i + 1\n else:\n for e in es:\n res = max(res, i - m[current ^ e])\n m[current] = min(m[current], i)\n return res", "def longestawesome(s: str) -> int:\n n = len(s)\n seen = {0: -1}\n status = res = 0\n for (i, c) in enumerate(s):\n status ^= 1 << ord(c) - ord('0')\n for a in range(10):\n if status ^ 1 << a in seen:\n res = max(res, i - seen[status ^ 1 << a])\n if status in seen:\n res = max(res, i - seen[status])\n else:\n seen[status] = i\n return res", "def longestawesome(s: str) -> int:\n (mask, res) = (0, 1)\n mask_pos = {0: -1}\n for (i, c) in enumerate(s):\n c = int(c)\n mask ^= 1 << c\n for j in range(11):\n check_mask = 1023 & (mask ^ 1 << j)\n if check_mask in mask_pos:\n res = max(res, i - mask_pos[check_mask])\n if mask in mask_pos:\n res = max(res, i - mask_pos[mask])\n else:\n mask_pos[mask] = i\n return res", "def longestawesome(s: str) -> int:\n if s == s[::-1]:\n return len(s)\n (pattern, re) = (0, 0)\n exit = {pattern: -1}\n for (i, num) in enumerate(s):\n pattern ^= 1 << int(num)\n if pattern == 0:\n re = i + 1\n continue\n for k in range(10):\n new_p = pattern ^ 1 << k\n re = max(re, i - exit.get(new_p, i))\n re = max(re, i - exit.get(pattern, i))\n exit.setdefault(pattern, i)\n return re", "def longestawesome(s: str) -> int:\n memo = {0: -1}\n max_len = 0\n mask = 0\n for i in range(len(s)):\n num = int(s[i])\n mask ^= 1 << num\n if mask in memo:\n max_len = max(max_len, i - memo[mask])\n for j in range(10):\n if mask ^ 1 << j in memo:\n max_len = max(max_len, i - memo[mask ^ 1 << j])\n if mask not in memo:\n memo[mask] = i\n return max_len"], "starter_code": "def longestawesome(s: str) -> int:\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Bit Manipulation", "String", "Hash Table"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://leetcode.com/problems/find-longest-awesome-substring/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "longestawesome", "task_id": "TACO_lite/457", "example": [[["3242415"], ["12345678"], ["213123"], ["00"]], ["5", "1", "6", "2"]]} +{"requirement": "Take debugging to a whole new level:\n\nGiven a string, remove every *single* bug.\n\nThis means you must remove all instances of the word 'bug' from within a given string, *unless* the word is plural ('bugs').\n\nFor example, given 'obugobugobuoobugsoo', you should return 'ooobuoobugsoo'.\n\nAnother example: given 'obbugugo', you should return 'obugo'.\n\nNote that all characters will be lowercase.\n\nHappy squishing!", "solutions": ["import re\n\ndef debug(s):\n return re.sub('bug(?!s)', '', s)", "def debug(s):\n s = s.replace('bugs', '^')\n s = s.replace('bug', '')\n s = s.replace('^', 'bugs')\n return s", "def debug(s):\n return __import__('re').sub('bug(?!s)', '', s)", "def debug(s):\n return 'bugs'.join((w.replace('bug', '') for w in s.split('bugs')))"], "starter_code": "def debug(s):\n", "input_output": {"fn_name": "debug", "inputs": [["obugobugobuoobugsoo"], ["obbugugo"], ["bugs bunny"], ["bugs buggy"], ["oaiwjefbugoijoijapsbugsdoibugbugjfoijasdfbugsbug"], ["bugbugbugiahweoifuhiaasnoidfhnbugbugs"], ["bugsbugswaoeifhiauwehfoiwubugshefjnviouah"], ["bugbugbugbug"], ["bugsbugsbugsbugs"], ["buggybugs"], ["oaisjdfowjefpoibugsjsofijeo oi bugs o bug f bug poaj sfd s"]], "outputs": [["ooobuoobugsoo"], ["obugo"], ["bugs bunny"], ["bugs gy"], ["oaiwjefoijoijapsbugsdoijfoijasdfbugs"], ["iahweoifuhiaasnoidfhnbugs"], ["bugsbugswaoeifhiauwehfoiwubugshefjnviouah"], [""], ["bugsbugsbugsbugs"], ["gybugs"], ["oaisjdfowjefpoibugsjsofijeo oi bugs o f poaj sfd s"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5a21f943c5e284d4340000cb", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "debug", "task_id": "TACO_lite/473", "example": [[["obugobugobuoobugsoo"], ["obbugugo"]], ["ooobuoobugsoo", "obugo"]]} +{"requirement": "You are given an array of strings\u00a0words\u00a0and a string\u00a0chars.\nA string is good\u00a0if\u00a0it can be formed by\u00a0characters from chars\u00a0(each character\u00a0can only be used once).\nReturn the sum of lengths of all good strings in words.\n\u00a0\nExample 1:\nInput: words = [\"cat\",\"bt\",\"hat\",\"tree\"], chars = \"atach\"\nOutput: 6\nExplanation: \nThe strings that can be formed are \"cat\" and \"hat\" so the answer is 3 + 3 = 6.\n\nExample 2:\nInput: words = [\"hello\",\"world\",\"leetcode\"], chars = \"welldonehoneyr\"\nOutput: 10\nExplanation: \nThe strings that can be formed are \"hello\" and \"world\" so the answer is 5 + 5 = 10.\n\n\u00a0\nNote:\n\n1 <= words.length <= 1000\n1 <= words[i].length, chars.length\u00a0<= 100\nAll strings contain lowercase English letters only.", "solutions": ["def countcharacters(words: List[str], chars: str) -> int:\n d = {}\n for i in chars:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n l = 0\n for i in words:\n flag = True\n for j in i:\n if j in d:\n if i.count(j) > d[j]:\n flag = False\n break\n else:\n flag = False\n break\n if flag:\n l += len(i)\n return l", "def countcharacters(words: List[str], chars: str) -> int:\n charBins = {char: chars.count(char) for char in chars}\n total = 0\n for word in words:\n if len(word) > len(chars):\n continue\n if not set(word).issubset(chars):\n continue\n letterBins = {letter: word.count(letter) for letter in word}\n goodWord = True\n for letter in letterBins:\n if letterBins[letter] > charBins[letter]:\n goodWord = False\n if goodWord:\n total += len(word)\n return total", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n c = Counter(chars)\n ret = 0\n for word in words:\n if Counter(word) - c == Counter():\n ret += len(word)\n return ret", "def countcharacters(words: List[str], chars: str) -> int:\n return sum((len(word) for word in words if collections.Counter(word) & collections.Counter(chars) == collections.Counter(word)))", "def countcharacters(words: List[str], chars: str) -> int:\n count = 0\n chars_map = collections.Counter(chars)\n for word in words:\n if collections.Counter(word) == collections.Counter(word) & chars_map:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n sum = 0\n for i in words:\n check = True\n for s in i:\n if i.count(s) > chars.count(s):\n check = False\n if check == True:\n sum = sum + len(i)\n return sum", "def countcharacters(words: List[str], chars: str) -> int:\n op = 0\n for ele in words:\n count = 0\n for i in ele:\n if chars.count(i) >= ele.count(i):\n count += 1\n if count == len(ele):\n op += len(ele)\n return op", "def countcharacters(words: List[str], chars: str) -> int:\n charsums = 0\n chars = sorted(chars)\n for word in words:\n wordsize = len(word)\n word = sorted(word)\n charcounter = 0\n while len(word) > 0 and charcounter < len(chars):\n if word[0] == chars[charcounter]:\n word.remove(word[0])\n charcounter += 1\n else:\n charcounter += 1\n if len(word) == 0:\n charsums += wordsize\n return charsums", "def countcharacters(words: List[str], chars: str) -> int:\n output = 0\n add = True\n for word in words:\n for c in word:\n if word.count(c) > chars.count(c):\n add = False\n if add:\n output += len(word)\n else:\n add = True\n return output", "def countcharacters(words: List[str], chars: str) -> int:\n count = 0\n n = len(chars)\n for word in words:\n ok_word = True\n copy = chars\n visit = []\n for i in range(n):\n visit.append(0)\n for letter in word:\n ok_letter = False\n for i in range(n):\n if visit[i] == 0 and letter == copy[i]:\n ok_letter = True\n visit[i] = 1\n break\n if not ok_letter:\n ok_word = False\n break\n if ok_word:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n charBins = {char: chars.count(char) for char in chars}\n goodWords = []\n for word in words:\n if len(word) > len(chars):\n continue\n if not set(word).issubset(chars):\n continue\n letterBins = {letter: word.count(letter) for letter in word}\n goodWord = True\n for letter in letterBins:\n if letterBins[letter] > charBins[letter]:\n goodWord = False\n if goodWord:\n goodWords.append(word)\n return sum((len(word) for word in goodWords))", "def countcharacters(words: List[str], chars: str) -> int:\n from collections import Counter\n res = 0\n for j in words:\n tmp = Counter(j) & Counter(chars)\n if tmp == Counter(j):\n res += len(j)\n return res", "def countcharacters(words: List[str], chars: str) -> int:\n goodCount = 0\n for word in words:\n wordLen = len(word)\n letterCount = 0\n chars_list = list(chars)\n for letter in word:\n if letter in chars_list:\n letterCount += 1\n chars_list.remove(letter)\n if letterCount == wordLen:\n goodCount += letterCount\n return goodCount", "def countcharacters(words: List[str], chars: str) -> int:\n suma = 0\n for word in words:\n cur_word = list(word)\n cur_len = len(word)\n for c in chars:\n if c in cur_word:\n cur_word.remove(c)\n if len(cur_word) == 0:\n suma += cur_len\n return suma", "def countcharacters(words: List[str], chars: str) -> int:\n ans = 0\n from collections import Counter\n cd = Counter(chars)\n for w in words:\n wd = Counter(w)\n if len(wd & cd) and len(list((wd & cd).elements())) == len(w):\n ans += len(w)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n start = 0\n for i in words:\n count = 0\n t = list(chars)\n for j in i:\n if j in t:\n count += 1\n t.remove(j)\n if count == len(i):\n start += count\n return start", "def countcharacters(words: List[str], chars: str) -> int:\n total = 0\n for word in words:\n mod_chars = list(chars)\n found = 0\n for c in word:\n if c in mod_chars:\n p = mod_chars.index(c)\n del mod_chars[p]\n found += 1\n if found == len(word):\n total += found\n return total", "def countcharacters(words, chars: str) -> int:\n myd = {}\n for i in chars:\n if hash(i) in list(myd.keys()):\n myd[hash(i)] += 1\n else:\n myd[hash(i)] = 1\n wdata = []\n for i in range(0, len(words)):\n x = dict()\n for letter in words[i]:\n if hash(letter) in list(x.keys()):\n x[hash(letter)] += 1\n else:\n x[hash(letter)] = 1\n wdata.append(x)\n count = 0\n for data in wdata:\n allin = True\n lcount = 0\n for letter in list(data.keys()):\n if letter in list(myd.keys()):\n if data[letter] > myd[letter]:\n allin = False\n else:\n lcount += data[letter]\n else:\n allin = False\n if allin == True:\n count += lcount\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n ans = 0\n for word in words:\n charscopy = [i for i in chars]\n length = 0\n for char in word:\n if char in charscopy:\n length += 1\n charscopy.remove(char)\n if length == len(word):\n ans += length\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n char_counter = Counter(chars)\n return sum([len(word) for word in words if len(char_counter - Counter(word)) > 1 and len(Counter(word) - char_counter) == 0])", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n d = Counter(chars)\n ans = 0\n for word in words:\n cur = Counter(word)\n if cur == cur & d:\n ans += len(word)\n return ans", "import copy\n\ndef countcharacters(w: List[str], c: str) -> int:\n d = {}\n for i in c:\n d[i] = d.get(i, 0) + 1\n ans = 0\n for i in range(len(w)):\n x = copy.deepcopy(d)\n f = True\n for j in w[i]:\n if j in x and x[j] > 0:\n x[j] -= 1\n else:\n f = False\n break\n if f:\n ans += len(w[i])\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n r = 0\n a = list(chars)\n for i in words:\n b = a.copy()\n s = False\n for j in i:\n if j not in b:\n s = True\n else:\n b.remove(j)\n if s != True:\n r += len(i)\n return r", "def countcharacters(words: List[str], chars: str) -> int:\n char_set = collections.Counter(chars)\n N = len(chars)\n result = 0\n for i in words:\n if len(i) <= N and self.check(char_set, i):\n result += len(i)\n return result\n\ndef check(char_ctr, S):\n S_ctr = collections.Counter(S)\n for i in S_ctr:\n if i not in char_ctr or S_ctr[i] > char_ctr[i]:\n return False\n return True", "import copy\n\ndef countcharacters(words: List[str], chars: str) -> int:\n charmap = dict()\n for c in chars:\n if c in charmap:\n charmap[c] += 1\n else:\n charmap[c] = 1\n size = 0\n for word in words:\n temp = copy.deepcopy(charmap)\n flag = True\n for c in word:\n if c in temp and temp[c] > 0:\n temp[c] -= 1\n else:\n flag = False\n break\n if flag:\n size += len(word)\n return size", "import copy\n\ndef countcharacters(words: List[str], chars: str) -> int:\n tracker = dict()\n result = 0\n for s in chars:\n tracker.setdefault(s, 0)\n tracker[s] += 1\n for word in words:\n _temp = copy.deepcopy(tracker)\n for ch in word:\n if ch not in _temp:\n break\n if _temp[ch] <= 0:\n break\n _temp[ch] -= 1\n else:\n result += len(word)\n return result", "import copy\n\ndef countcharacters(words: List[str], chars: str) -> int:\n s = dict()\n for c in chars:\n if c not in s:\n s[c] = 0\n s[c] += 1\n t = 0\n for word in words:\n s_copy = copy.deepcopy(s)\n valid = True\n for letter in word:\n if letter not in s_copy:\n valid = False\n break\n else:\n s_copy[letter] -= 1\n if s_copy[letter] == 0:\n del s_copy[letter]\n if valid:\n t += len(word)\n return t", "def countcharacters(words: List[str], chars: str) -> int:\n import copy\n total = 0\n y = {}\n for char in chars:\n if char in y:\n y[char] += 1\n else:\n y[char] = 1\n for word in words:\n x = copy.deepcopy(y)\n temp = 0\n for char in word:\n if char in x and x[char] > 0:\n x[char] -= 1\n temp += 1\n else:\n temp = 0\n break\n total += temp\n return total", "def countcharacters(words: List[str], chars: str) -> int:\n out = 0\n for word in words:\n good = True\n for char in word:\n if word.count(char) > chars.count(char):\n good = False\n if good:\n out += len(word)\n return out", "import collections\n\ndef countcharacters(words: List[str], chars: str) -> int:\n count = 0\n for w in words:\n letters = list(set(w))\n isin = True\n for l in letters:\n if l not in chars or w.count(l) > chars.count(l):\n isin = False\n break\n if isin:\n count += len(w)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n a = 0\n for word in words:\n res = True\n for i in word:\n if word.count(i) > chars.count(i):\n res = False\n break\n if res:\n a += len(word)\n return a", "def countcharacters(words: List[str], chars: str) -> int:\n res = 0\n dtar = Counter(chars)\n for i in range(len(words)):\n for j in words[i]:\n if j not in chars:\n break\n if words[i].count(j) > 1:\n if words[i].count(j) > dtar[j]:\n break\n else:\n res += len(words[i])\n return res", "def countcharacters(words: List[str], chars: str) -> int:\n d = Counter(chars)\n ans = 0\n for w in words:\n temp = d.copy()\n b = True\n for i in w:\n try:\n if temp[i] != 0:\n temp[i] -= 1\n else:\n b = False\n break\n except:\n b = False\n break\n if b:\n ans += len(w)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n count = 0\n freq = {}\n for n in range(len(chars)):\n if chars[n] not in freq.keys():\n freq[chars[n]] = 1\n else:\n freq[chars[n]] += 1\n for word in words:\n word_fq = {}\n is_match = True\n for m in range(len(word)):\n if word[m] not in freq.keys():\n is_match = False\n break\n if word[m] not in word_fq.keys():\n word_fq[word[m]] = 1\n else:\n word_fq[word[m]] += 1\n if is_match:\n is_fit = True\n for key in word_fq.keys():\n if key not in freq.keys():\n is_fit = False\n break\n if word_fq[key] > freq[key]:\n is_fit = False\n break\n if is_fit:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n c = collections.Counter(chars)\n res = 0\n\n def valid(word):\n s = collections.Counter(word)\n for ch in s:\n if ch not in c or s[ch] > c[ch]:\n return False\n return True\n for word in words:\n if valid(word):\n res += len(word)\n return res", "def countcharacters(words: List[str], chars: str) -> int:\n ans = 0\n mp = Counter(chars)\n for word in words:\n ok = True\n mp_word = Counter(word)\n for (ch, f) in mp_word.items():\n if ch not in mp or mp_word[ch] > mp[ch]:\n ok = False\n break\n if ok:\n ans += len(word)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n from collections import Counter\n ans = 0\n chars_set = set(chars)\n count0 = Counter(chars)\n for word in words:\n count = Counter(word)\n if all((s in chars_set and count[s] <= count0[s] for s in word)):\n ans += len(word)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n d_chars = Counter(chars)\n ans = 0\n for w in words:\n d_w = Counter(w)\n for (k, v) in d_w.items():\n if d_chars[k] < v:\n break\n else:\n ans += len(w)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n (sum, ct) = (0, collections.Counter)\n chars_counter = ct(chars)\n for word in words:\n word_counter = ct(word)\n if all((word_counter[c] <= chars_counter[c] for c in word_counter)):\n sum += len(word)\n return sum", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n c_dict = dict(Counter(chars))\n count = 0\n for word in words:\n word_d = dict(Counter(word))\n match = True\n for (k, v) in list(word_d.items()):\n if k not in c_dict or v > c_dict[k]:\n match = False\n break\n if match:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n char_sum = 0\n\n def isValid(word, chars):\n for letter in word:\n if chars[letter] > 0:\n chars[letter] -= 1\n else:\n return False\n return True\n for word in words:\n counter = Counter(chars)\n if isValid(word, counter):\n char_sum += len(word)\n return char_sum", "def countcharacters(words: List[str], chars: str) -> int:\n tot = 0\n for w in words:\n d = {}\n for c in chars:\n if c in d:\n d[c] += 1\n else:\n d[c] = 1\n temp = 0\n for l in w:\n if l in d and d[l] > 0:\n d[l] -= 1\n temp += 1\n else:\n temp = 0\n break\n tot += temp\n return tot", "def countcharacters(words: List[str], chars: str) -> int:\n ans = 0\n for w in words:\n tc = chars\n flag = True\n for l in w:\n if l in tc:\n tc = tc.replace(l, '', 1)\n else:\n flag = False\n if flag:\n ans += len(w)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n d = {}\n c = 0\n for i in chars:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n for i in words:\n dd = {}\n for j in i:\n if j in dd:\n dd[j] += 1\n else:\n dd[j] = 1\n c1 = 0\n for x in dd.keys():\n if x in d:\n if d[x] >= dd[x]:\n c1 += dd[x]\n else:\n c1 = 0\n break\n else:\n c1 = 0\n break\n c += c1\n return c", "def countcharacters(words: List[str], chars: str) -> int:\n charsDict = {}\n for char in chars:\n if char not in charsDict:\n charsDict[char] = 0\n charsDict[char] += 1\n ans = 0\n for word in words:\n tempDict = charsDict.copy()\n isGood = True\n for char in word:\n if char not in tempDict:\n isGood = False\n continue\n elif tempDict[char] == 0:\n isGood = False\n continue\n else:\n tempDict[char] -= 1\n if isGood:\n ans += len(word)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n cCounter = collections.Counter(chars)\n sum = 0\n for word in words:\n wCounter = collections.Counter(word)\n match = True\n for (k, v) in wCounter.items():\n if cCounter[k] < v:\n match = False\n if match:\n sum += len(word)\n return sum", "def countcharacters(words: List[str], chars: str) -> int:\n c1 = [0] * 256\n for c in chars:\n c1[ord(c)] += 1\n res = 0\n for word in words:\n if len(chars) < len(word):\n continue\n c2 = [0] * 256\n for c in word:\n c2[ord(c)] += 1\n goodStr = True\n for i in range(256):\n if c1[i] < c2[i]:\n goodStr = False\n break\n if goodStr:\n res += len(word)\n return res", "def countcharacters(words: List[str], chars: str) -> int:\n\n def get_freq(input):\n freq = {}\n for c in input:\n if c not in freq:\n freq[c] = 0\n freq[c] += 1\n return freq\n\n def can_contain(freq_source, freq_word):\n for (key, item) in freq_word.items():\n if key not in freq_source or freq_source[key] < item:\n return False\n return True\n total_length = 0\n freq_source = get_freq(chars)\n for word in words:\n freq_word = get_freq(word)\n if can_contain(freq_source, freq_word):\n total_length += len(word)\n return total_length", "def countcharacters(words: List[str], chars: str) -> int:\n charsDict = {}\n for char in chars:\n if char not in charsDict:\n charsDict[char] = 0\n charsDict[char] += 1\n ans = 0\n for word in words:\n wordDict = {}\n for char in word:\n if char not in wordDict:\n wordDict[char] = 0\n wordDict[char] += 1\n isGood = True\n for (key, val) in list(wordDict.items()):\n if key not in charsDict:\n isGood = False\n break\n elif val > charsDict[key]:\n isGood = False\n break\n if isGood:\n ans += len(word)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n res = 0\n d = dict()\n for char in chars:\n d[char] = d.get(char, 0) + 1\n for word in words:\n c = dict()\n for char in word:\n c[char] = c.get(char, 0) + 1\n bad = False\n while c and (not bad):\n char = c.popitem()\n if char[0] in d and d[char[0]] >= char[1]:\n continue\n else:\n bad = True\n if not bad:\n res += len(word)\n return res", "def countcharacters(words: List[str], chars: str) -> int:\n out = 0\n chars = list(chars)\n for i in words:\n f = 0\n temp = chars[:]\n for j in i:\n if j in temp:\n temp.remove(j)\n else:\n f = 1\n break\n if f == 0:\n out += len(i)\n return out", "def countcharacters(words: List[str], chars: str) -> int:\n register = {}\n for char in chars:\n register[char] = register.get(char, 0) + 1\n result = 0\n for word in words:\n temp = {}\n for char in word:\n temp[char] = temp.get(char, 0) + 1\n for (char, num) in list(temp.items()):\n if temp[char] > register.get(char, 0):\n break\n else:\n result += len(word)\n return result", "def countcharacters(words: List[str], chars: str) -> int:\n charChars = Counter(chars)\n counter = 0\n for word in words:\n countC = Counter(word)\n count = 0\n for letter in countC.items():\n if letter[0] in charChars and charChars[letter[0]] >= letter[1]:\n count += 1\n if count == len(countC):\n counter += len(word)\n return counter", "def countcharacters(words: List[str], chars: str) -> int:\n\n def strToList(word):\n return [char for char in word]\n\n def canForm(word, bank):\n tmp = word\n while tmp != []:\n x = tmp[0]\n tmp.remove(tmp[0])\n if x in bank:\n bank.remove(x)\n else:\n return False\n return True\n totalLen = 0\n for word in words:\n bank = strToList(chars)\n wordAsList = strToList(word)\n if canForm(wordAsList, bank):\n totalLen += len(word)\n return totalLen", "def countcharacters(words: List[str], chars: str) -> int:\n setChars = set(chars)\n counts = [0] * len(setChars)\n map = {}\n res = 0\n for (i, val) in enumerate(setChars):\n map[val] = i\n for (i, val) in enumerate(chars):\n counts[map.get(val)] += 1\n for word in words:\n tempCounts = counts[:]\n flag = 1\n for char in word:\n index = map.get(char, -1)\n if index == -1:\n flag = 0\n continue\n tempCounts[index] -= 1\n if tempCounts[index] < 0:\n flag = 0\n continue\n if flag:\n res += len(word)\n return res", "def countcharacters(words: List[str], chars: str) -> int:\n d = {}\n for i in range(len(chars)):\n if chars[i] not in d:\n d[chars[i]] = 1\n else:\n d[chars[i]] += 1\n c = 0\n for i in range(len(words)):\n di = {}\n for j in range(len(words[i])):\n if words[i][j] not in di:\n di[words[i][j]] = 1\n else:\n di[words[i][j]] += 1\n l = list(di.keys())\n temp = 0\n for j in range(len(l)):\n if l[j] not in d:\n temp = 1\n break\n elif di[l[j]] > d[l[j]]:\n temp = 1\n break\n else:\n temp = 0\n if temp == 0:\n c += len(words[i])\n return c", "def countcharacters(words, chars):\n sum = 0\n count = {}\n for c in chars:\n if c in count:\n count[c] += 1\n else:\n count[c] = 1\n for word in words:\n seen = {}\n validWord = True\n for c in word:\n if c in seen:\n seen[c] += 1\n else:\n seen[c] = 1\n if c not in count or seen[c] > count[c]:\n validWord = False\n if validWord:\n sum += len(word)\n return sum", "from collections import Counter\n\ndef bruteforce_with_counter(words, chars):\n counter = Counter(chars)\n return sum((len(w) for w in words if not Counter(w) - counter))\n\ndef countcharacters(words: List[str], chars: str) -> int:\n return bruteforce_with_counter(words, chars)", "from collections import Counter as di\n\ndef countcharacters(a: List[str], c: str) -> int:\n d = di(c)\n ans = 0\n for i in a:\n d1 = di(i)\n if len(d1 - d) == 0:\n ans += sum(d1.values())\n return ans", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n letters = Counter(chars)\n out = 0\n for word in words:\n length = len(word)\n if not Counter(word) - letters:\n out += length\n return out", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n\n def issubset(wc, cc):\n for x in wc.keys():\n cc[x] = cc.get(x, 0) - wc[x]\n for x in cc.keys():\n if cc[x] < 0:\n return False\n return True\n res = 0\n cc = Counter(chars)\n for word in words:\n wc = Counter(word)\n if issubset(wc, cc.copy()):\n res += len(word)\n return res", "def countcharacters(words: List[str], chars: str) -> int:\n char_count = collections.Counter(chars)\n total = 0\n for word in words:\n if not collections.Counter(word) - char_count:\n total += len(word)\n return total", "def countcharacters(words: List[str], chars: str) -> int:\n chars = Counter(chars)\n return sum((len(w) for w in words if not Counter(w) - chars))", "def countcharacters(words: List[str], chars: str) -> int:\n count = Counter(chars)\n out = 0\n for word in words:\n curr = Counter(word)\n if not curr - count:\n out += len(word)\n return out", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n c_c = Counter(chars)\n good_w = []\n for w in words:\n w_c = Counter(w)\n sampled_w = ''.join([c for c in w if c_c[c] >= w_c[c]])\n if w == sampled_w:\n good_w.append(w)\n return sum((len(w) for w in good_w))", "def countcharacters(words: List[str], chars: str) -> int:\n char_map = {c: chars.count(c) for c in set(chars)}\n count = 0\n for w in words:\n good = True\n for c in w:\n if c not in char_map.keys() or w.count(c) > char_map[c]:\n good = False\n if good:\n count += len(w)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n letters = {}\n for char in chars:\n letters[char] = letters.get(char, 0) + 1\n count = 0\n for word in words:\n tmp = letters.copy()\n flag = 1\n for char in word:\n if char in tmp and tmp[char] >= 1:\n tmp[char] -= 1\n else:\n flag = 0\n break\n if flag:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n ans = 0\n for word in words:\n c = collections.Counter(chars)\n add = True\n for letter in word:\n if c[letter] > 0:\n c[letter] -= 1\n else:\n add = False\n if add == True:\n ans += len(word)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n ans = 0\n cmap = {ch: chars.count(ch) for ch in chars}\n for word in words:\n wmap = {ch: word.count(ch) for ch in word}\n count_me_in = True\n for (k, v) in wmap.items():\n try:\n v1 = cmap[k]\n if v1 < v:\n raise Exception('Frequency not enough!')\n except:\n count_me_in = False\n break\n if count_me_in:\n ans += len(word)\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n char_count = collections.Counter(chars)\n good_str_len = 0\n for word in words:\n temp = char_count.copy()\n temp_str_len = 0\n for ch in word:\n if ch in temp and temp[ch] > 0:\n temp_str_len += 1\n temp[ch] -= 1\n if temp_str_len == len(word):\n good_str_len += len(word)\n return good_str_len", "def countcharacters(words: List[str], chars: str) -> int:\n if len(chars) == 0 or len(words) == 0:\n return 0\n letterCounts = {}\n for c in chars:\n if str(c) in letterCounts:\n letterCounts[str(c)] += 1\n else:\n letterCounts[str(c)] = 1\n totalLength = 0\n for word in words:\n currentLetterCounts = {}\n for letter in word:\n if str(letter) in currentLetterCounts:\n currentLetterCounts[str(letter)] += 1\n else:\n currentLetterCounts[str(letter)] = 1\n valid = True\n for (key, value) in currentLetterCounts.items():\n if key not in letterCounts:\n valid = False\n break\n if letterCounts[key] < value:\n valid = False\n break\n if valid:\n totalLength += len(word)\n return totalLength", "def countcharacters(words: List[str], chars: str) -> int:\n flag = [0 for i in range(len(words))]\n total = 0\n for word in words:\n dic = {}\n for char in word:\n if char in dic:\n dic[char] += 1\n else:\n dic[char] = 1\n count = 0\n for i in range(len(chars)):\n if chars[i] in dic and dic[chars[i]] > 0:\n dic[chars[i]] -= 1\n count += 1\n good = True\n for char in dic:\n if dic[char] > 0:\n good = False\n break\n if good:\n total += count\n return total", "def countcharacters(words: List[str], chars: str) -> int:\n myd = {}\n count = 0\n for i in chars:\n if i in myd.keys():\n myd[i] += 1\n else:\n myd[i] = 1\n for word in words:\n allin = True\n for letter in word:\n if letter in myd.keys():\n if word.count(letter) > myd[letter]:\n allin = False\n else:\n allin = False\n if allin == True:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n good_words_len_sum = 0\n counter = {}\n for char in chars:\n if not char in counter:\n counter[char] = 1\n else:\n counter[char] += 1\n for word in words:\n my_counter = counter.copy()\n for char in word:\n if my_counter.get(char, 0) > 0:\n my_counter[char] -= 1\n else:\n break\n else:\n good_words_len_sum += len(word)\n return good_words_len_sum", "def countcharacters(words: List[str], chars: str) -> int:\n length = 0\n m = Counter(chars)\n for word in words:\n passed = True\n for char in word:\n if m[char] < word.count(char):\n passed = False\n if passed:\n length += len(word)\n return length", "def countcharacters(words: List[str], chars: str) -> int:\n from collections import Counter as cnt\n return sum([not cnt(word) - cnt(chars) and len(word) for word in words])", "def countcharacters(words: List[str], chars: str) -> int:\n count = 0\n dic = collections.Counter(chars)\n for word in words:\n passed = True\n for ch in word:\n if dic[ch] < word.count(ch):\n passed = False\n if passed:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n counter = 0\n for i in words:\n a = i\n for j in chars:\n if j in a:\n a = a[:a.index(j)] + a[a.index(j) + 1:]\n if len(a) == 0:\n counter += len(i)\n return counter", "def countcharacters(words: List[str], chars: str) -> int:\n freq = defaultdict(int)\n for l in chars:\n freq[l] += 1\n count = 0\n for word in words:\n testFreq = freq.copy()\n match = True\n for letter in word:\n if testFreq[letter] <= 0:\n match = False\n break\n testFreq[letter] -= 1\n if match:\n count += len(word)\n return count", "def countcharacters(words: List[str], chars: str) -> int:\n tot = 0\n totchars = {}\n for char in chars:\n if char in totchars:\n totchars[char] += 1\n else:\n totchars[char] = 1\n for word in words:\n word = sorted(word)\n works = True\n i = 0\n while i < len(word):\n count = 0\n while word[i + count] == word[i]:\n count += 1\n if i + count == len(word):\n break\n if word[i] in totchars:\n if count > totchars[word[i]]:\n works = False\n else:\n works = False\n i += count\n if works:\n tot += len(word)\n return tot", "def countcharacters(words: List[str], chars: str) -> int:\n sum = 0\n p = 0\n for th in words:\n for i in range(len(th)):\n if th[i] in chars:\n if th.count(th[i]) <= chars.count(th[i]):\n p = p + 1\n if p == len(th):\n sum = sum + p\n p = 0\n return sum", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n ans = 0\n for i in range(len(words)):\n if Counter(words[i]) & Counter(chars) == Counter(words[i]):\n ans += len(words[i])\n return ans", "def countcharacters(words: List[str], chars: str) -> int:\n from collections import Counter\n sum_ = 0\n for word in words:\n s = Counter(chars)\n flag = 0\n for letter in word:\n if letter in list(s.keys()) and s[letter] != 0:\n s[letter] -= 1\n else:\n flag = 1\n if flag == 0:\n sum_ += len(word)\n return sum_", "def countcharacters(words: List[str], chars: str) -> int:\n out = 0\n for word in words:\n cnt = 0\n for letter in word:\n if letter in chars and word.count(letter) <= chars.count(letter):\n cnt += 1\n if cnt == len(word):\n out += len(word)\n return out", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n letters = Counter(chars)\n c = 0\n for w in words:\n if Counter(chars) & Counter(w) == Counter(w):\n c += len(w)\n return c", "import collections\n\ndef countcharacters(words: List[str], chars: str) -> int:\n n = 0\n for word in words:\n count = 0\n for letter in word:\n if letter in chars and word.count(letter) <= chars.count(letter):\n count += 1\n if count == len(word):\n n += len(word)\n return n", "def countcharacters(words: List[str], chars: str) -> int:\n res = []\n for word in words:\n count = 0\n for char in word:\n if char in chars and word.count(char) <= chars.count(char):\n count += 1\n if count == len(word):\n res.append(count)\n return sum(res)", "from collections import Counter\n\ndef countcharacters(words: List[str], chars: str) -> int:\n r = Counter(chars)\n return sum([len(word) if Counter(word) - r == Counter() else 0 for word in words])"], "starter_code": "def countcharacters(words: List[str], chars: str) -> int:\n", "input_output": {"fn_name": "countCharacters", "inputs": [[["\"cat\"", "\"bt\"", "\"hat\"", "\"tree\""], "\"atach\""]], "outputs": [10]}, "difficulty": "EASY", "raw_tags": ["Array", "String", "Hash Table"], "name": null, "source": "leetcode", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "countcharacters", "task_id": "TACO_lite/466", "example": [[[["cat", "bt", "hat", "tree"], "atach"], [["hello", "world", "leetcode"], "welldonehoneyr"]], ["6", "10"]]} +{"requirement": "What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example:\n\n```\n'abba' & 'baab' == true\n\n'abba' & 'bbaa' == true\n\n'abba' & 'abbba' == false\n\n'abba' & 'abca' == false\n```\n\nWrite a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:\n\nanagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']\n\nanagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']\n\nanagrams('laser', ['lazing', 'lazy', 'lacer']) => []", "solutions": ["def anagrams(word, words):\n return [item for item in words if sorted(item) == sorted(word)]", "from collections import Counter\n\ndef anagrams(word, words):\n counts = Counter(word)\n return [w for w in words if Counter(w) == counts]", "def anagrams(word, words):\n match = sorted(word)\n return [w for w in words if match == sorted(w)]", "from collections import Counter\n\ndef anagrams(word, words):\n (n, c) = (len(word), Counter(word))\n return [w for w in words if len(w) == n and Counter(w) == c]", "def anagrams(word, words):\n letter = {x: word.count(x) for x in word}\n result = []\n for i in words:\n letters = {x: i.count(x) for x in i}\n if letters == letter:\n result.append(i)\n return result", "def anagrams(word, words):\n return [el for el in words if sorted(word) == sorted(el)]", "from collections import Counter\n\ndef anagrams(word, words):\n main = Counter(word)\n return [wor for wor in words if Counter(wor) == main]", "def anagrams(word, words):\n return [x for x in words if sorted(x) == sorted(word)]", "def anagrams(word, words):\n return [w for w in words if list(sorted(w)) == list(sorted(word))]", "def anagrams(word, words):\n\n def lettercount(inputword):\n wordarr = list(inputword)\n worddict = {}\n for letter in wordarr:\n if letter not in worddict:\n worddict[letter] = wordarr.count(letter)\n return worddict\n return [astring for astring in words if lettercount(astring) == lettercount(word)]", "def anagrams(word, words):\n lst = []\n for elem in words:\n if sorted(word) == sorted(elem):\n lst.append(elem)\n return lst", "def anagrams(word, words):\n word = sorted(word)\n return list(filter(lambda ele: sorted(ele) == word, words))", "def anagrams(word, words):\n return [trial for trial in words if sorted(trial) == sorted(word)]", "def anagrams(word: str, words: list) -> list:\n return list(filter(lambda x: sorted(x) == sorted(word), words))", "anagrams = lambda _, __: list([s for s in __ if sorted(s) == sorted(_)])", "anagrams = lambda word, words: list((w for w in words if sorted(list(w)) == sorted(list(word))))", "def anagrams(word, words):\n ans = []\n or1 = 0\n or2 = 0\n for i in word:\n or1 += ord(i)\n for i in words:\n or2 = 0\n for x in i:\n or2 += ord(x)\n if or1 == or2:\n ans += [i]\n return ans", "def anagrams(word, words):\n w_buff = []\n w_out = []\n for w_t in words:\n if len(w_t) == len(word):\n w_buff.append(w_t)\n w_w = list(word)\n w_w.sort()\n for w_t in w_buff:\n w_buff_l = list(w_t)\n w_buff_l.sort()\n if w_buff_l == w_w:\n w_out.append(w_t)\n return w_out", "def anagrams(word, words):\n list = []\n word = sorted(word)\n for i in range(len(words)):\n if word == sorted(words[i]):\n list.append(words[i])\n else:\n pass\n return list", "from collections import Counter\n\ndef anagrams(word, words):\n return [w for w in words if sorted(sorted(Counter(word).items())) == sorted(sorted(Counter(w).items()))]", "def anagrams(word, words):\n l = [letter for letter in word]\n anagram_list = []\n for item in words:\n l_item = [letter for letter in item]\n if sorted(l) == sorted(l_item):\n temp_list = [i for i in l + l_item if i not in l_item]\n if len(temp_list) == 0:\n anagram_list.append(item)\n else:\n continue\n return anagram_list", "def anagrams(word, words):\n return [anagram for anagram in words if sum([ord(c) for c in anagram]) == sum([ord(c) for c in word])]", "def anagrams(word, words):\n wordnum = sum((ord(ch) for ch in word))\n res = []\n if not words:\n return []\n for item in words:\n if sum((ord(ch) for ch in item)) == wordnum:\n res.append(item)\n return res"], "starter_code": "def anagrams(word, words):\n", "input_output": {"fn_name": "anagrams", "inputs": [["abba", ["aabb", "abcd", "bbaa", "dada"]], ["racer", ["crazer", "carer", "racar", "caers", "racer"]], ["a", ["a", "b", "c", "d"]], ["ab", ["cc", "ac", "bc", "cd", "ab", "ba", "racar", "caers", "racer"]], ["abba", ["a", "b", "c", "d", "aabb", "bbaa", "abab", "baba", "baab", "abcd", "abbba", "baaab", "abbab", "abbaa", "babaa"]], ["big", ["gig", "dib", "bid", "biig"]]], "outputs": [[["aabb", "bbaa"]], [["carer", "racer"]], [["a"]], [["ab", "ba"]], [["aabb", "bbaa", "abab", "baba", "baab"]], [[]]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/523a86aa4230ebb5420001e1", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "anagrams", "task_id": "TACO_lite/456", "example": [[["abba", ["aabb", "abcd", "bbaa", "dada"]], ["racer", ["crazer", "carer", "racar", "caers", "racer"]], ["laser", ["lazing", "lazy", "lacer"]]], ["['aabb', 'bbaa']", "['carer', 'racer']", "[]"]]} +{"requirement": "Given a boolean 2D array of n x m dimensions where each row is sorted. Find the 0-based index of the first row that has the maximum number of 1's.\nExample 1:\nInput: \nN = 4 , M = 4\nArr[][] = {{0, 1, 1, 1},\n {0, 0, 1, 1},\n {1, 1, 1, 1},\n {0, 0, 0, 0}}\nOutput: 2\nExplanation: Row 2 contains 4 1's (0-based\nindexing).\nExample 2:\nInput: \nN = 2, M = 2\nArr[][] = {{0, 0}, {1, 1}}\nOutput: 1\nExplanation: Row 1 contains 2 1's (0-based\nindexing).\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function rowWithMax1s() which takes the array of booleans arr[][], n and m as input parameters and returns the 0-based index of the first row that has the most number of 1s. If no such row exists, return -1.\n \nExpected Time Complexity: O(N+M)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 N, M \u2264 10^{3}\n0 \u2264 Arr[i][j] \u2264 1", "solutions": ["def rowwithmax1s(arr, n, m):\n max_count = 0\n ans = -1\n for (i, v) in enumerate(arr):\n count = v.count(1)\n if count > max_count:\n max_count = count\n ans = i\n return ans", "def rowwithmax1s(arr, n, m):\n binary = []\n for x in range(n):\n binary.append(int(''.join(list(map(str, arr[x]))), 2))\n if max(binary) != 0:\n return binary.index(max(binary))\n return -1", "def rowwithmax1s(arr, n, m):\n (i, j) = (0, m - 1)\n index = 0\n while i != n and j != -1:\n if arr[i][j] == 1:\n j -= 1\n index = i\n else:\n i += 1\n if j == m - 1 and i == n:\n return -1\n return index", "def rowwithmax1s(arr, n, m):\n count = 0\n op = -1\n for i in range(0, n):\n t = sum(arr[i])\n if t > count:\n count = t\n op = i\n return op", "def rowwithmax1s(arr, n, m):\n maxi = 0\n ans = -1\n for i in range(n):\n count = 0\n for j in range(m):\n if arr[i][j] == 1:\n count += 1\n if count > maxi:\n maxi = count\n ans = i\n return ans", "def rowwithmax1s(arr, n, m):\n max_row_index = -1\n max_ones_count = 0\n j = m - 1\n for i in range(n):\n while j >= 0 and arr[i][j] == 1:\n j -= 1\n if j < m - 1:\n ones_count = m - 1 - j\n if ones_count > max_ones_count:\n max_ones_count = ones_count\n max_row_index = i\n return max_row_index", "import bisect\n\ndef rowwithmax1s(arr, n, m):\n rowIndex = -1\n row = 0\n col = m - 1\n while row < n and col >= 0:\n if arr[row][col] == 1:\n rowIndex = row\n col -= 1\n if arr[row][col] == 0:\n row += 1\n return rowIndex", "def rowwithmax1s(arr, n, m):\n max = 0\n ans = -1\n for i in range(n):\n cnt = 0\n for j in range(m):\n if arr[i][j] == 1:\n cnt += 1\n if cnt > max:\n ans = i\n max = cnt\n return ans", "def rowwithmax1s(arr, n, m):\n max_val = 0\n max_index = -1\n for x in range(len(arr)):\n total = 0\n for y in range(len(arr[0])):\n total += arr[x][y]\n if total > max_val:\n max_val = total\n max_index = x\n return max_index", "def rowwithmax1s(arr, n, m):\n max1srow = -1\n (row, col) = (0, m - 1)\n while row < n and col >= 0:\n if arr[row][col]:\n max1srow = row\n while col >= 0 and arr[row][col] == 1:\n col -= 1\n row += 1\n return max1srow", "def rowwithmax1s(arr, n, m):\n max1s = 0\n max1srow = -1\n for i in arr:\n ones = m\n for j in i:\n if j == 0:\n ones -= 1\n if ones > max1s:\n max1s = ones\n max1srow = arr.index(i)\n return max1srow", "def rowwithmax1s(mat, n, m):\n ans = -1\n min_col = int(1000000000.0)\n for row in range(n):\n (low, high) = (0, m - 1)\n first_occur_one = -1\n while low <= high:\n mid = low + (high - low) // 2\n if mat[row][mid] == 1:\n first_occur_one = mid\n high = mid - 1\n else:\n low = mid + 1\n if first_occur_one != -1:\n if min_col > first_occur_one:\n min_col = first_occur_one\n ans = row\n return ans", "def rowwithmax1s(arr, n, m):\n mx = 0\n pos = -1\n for i in range(0, len(arr)):\n sm = 0\n for j in range(0, len(arr[i])):\n sm += arr[i][j]\n if sm > mx:\n mx = sm\n pos = i\n return pos", "def rowwithmax1s(arr, n, m):\n (val, r_sum, maxSum) = (0, 0, 0)\n for r in range(n):\n for c in range(m):\n r_sum += arr[r][c]\n if r_sum > maxSum:\n maxSum = r_sum\n val = r\n r_sum = 0\n if maxSum == 0:\n return -1\n return val", "def rowwithmax1s(arr, n, m):\n m = 0\n for i in arr:\n s = sum(i)\n m = max(s, m)\n if m == 0:\n return -1\n for i in range(n):\n if sum(arr[i]) == m:\n return i", "def rowwithmax1s(arr, n, m):\n ans = fin = t = 0\n for i in range(n):\n c = 0\n for j in range(m):\n if arr[i][j] == 1:\n c += 1\n t = 1\n if c > ans:\n ans = c\n fin = i\n if ans == m:\n return i\n if t == 0:\n return -1\n return fin", "def rowwithmax1s(arr, n, m):\n ans = -1\n ansm = m\n for i in range(len(arr)):\n for j in range(len(arr[i])):\n if arr[i][j] == 1:\n if j < ansm:\n ans = i\n ansm = j\n return ans", "def rowwithmax1s(arr, n, m):\n max_ele = 0\n max_ind = 0\n for i in range(n):\n if max_ele < sum(arr[i]):\n max_ele = sum(arr[i])\n max_ind = i\n if max_ele == 0:\n return -1\n return max_ind", "def rowwithmax1s(arr, n, m):\n (prev, ans) = (0, -1)\n for i in range(n):\n (l, r) = (0, m - 1)\n while l < r:\n mid = l + (r - l) // 2\n if arr[i][mid] == 1:\n r = mid - 1\n else:\n l = mid + 1\n if arr[i][l] == 1:\n if m - l > prev:\n ans = i\n prev = m - l\n elif m - l - 1 > prev:\n ans = i\n prev = m - l - 1\n return ans", "def rowwithmax1s(arr, n, m):\n one_sum = 0\n for i in range(n):\n curr_one_sum = sum(arr[i])\n if curr_one_sum > one_sum:\n one_sum = curr_one_sum\n indx = i\n if one_sum > 0:\n return indx\n return -1", "def rowwithmax1s(arr, n, m):\n count = 0\n temp = 0\n index = -1\n for i in range(n):\n for j in range(m):\n if arr[i][j] == 1:\n temp += 1\n if temp > count:\n count = temp\n index = i\n temp = 0\n return index", "def rowwithmax1s(arr, n, m):\n x = [len([i for i in j if i == 1]) for j in arr]\n if max(x) == 0:\n return -1\n return x.index(max(x))", "def rowwithmax1s(arr, n, m):\n c = 0\n p = 0\n indx = 0\n for i in range(n):\n c = 0\n for j in range(m):\n if arr[i][j] == 1:\n c += 1\n if c > p:\n p = c\n indx = i\n if p == 0:\n return -1\n return indx", "def rowwithmax1s(arr, n, m):\n ans = -1\n row = 0\n column = m - 1\n while row < n and column >= 0:\n if arr[row][column] == 1:\n column -= 1\n ans = row\n else:\n row += 1\n return ans", "def rowwithmax1s(arr, n, m):\n result = -1\n maximum = 0\n for i in range(len(arr)):\n temp = sum(arr[i])\n if maximum < temp:\n maximum = temp\n result = i\n return result", "def rowwithmax1s(arr, n, m):\n ma = -1\n mc = 0\n for i in range(n):\n oc = arr[i].count(1)\n if oc > mc:\n mc = oc\n ma = i\n return ma\n if ma == 0:\n return -1", "def rowwithmax1s(arr, n, m):\n a = 0\n mi = 0\n ri = -1\n kc = 0\n for i in range(0, n):\n rc = 0\n for j in range(0, m):\n if arr[i][j] == 1:\n rc = rc + 1\n if rc > kc:\n kc = rc\n ri = i\n return ri", "def rowwithmax1s(arr, n, m):\n count = 0\n ans = -1\n for i in range(n):\n summ = sum(arr[i])\n if summ > count:\n count = summ\n ans = i\n return ans", "import bisect\n\ndef rowwithmax1s(arr, n, m):\n ans = -1\n count = m\n for i in range(n):\n x = bisect.bisect_left(arr[i], 1)\n if x < count:\n ans = i\n count = x\n return ans", "def rowwithmax1s(arr, n, m):\n d = {}\n for i in range(len(arr)):\n d[i] = arr[i].count(1)\n max = 0\n ans = 0\n for (a, b) in d.items():\n if int(b) > max:\n max = int(b)\n ans = int(a)\n if max == 0:\n return -1\n else:\n return ans", "def rowwithmax1s(arr, n, m):\n count = 0\n temp1 = -1\n for i in range(0, len(arr)):\n temp = arr[i].count(1)\n if temp > count:\n temp1 = i\n count = temp\n if temp1 == -1:\n return -1\n else:\n return temp1", "def rowwithmax1s(arr, n, m):\n maxones = 0\n maxindex = -1\n for i in range(len(arr)):\n rowcount = 0\n for j in range(len(arr[i])):\n if arr[i][j] == 1:\n rowcount += arr[i][j]\n if rowcount > maxones:\n maxones = rowcount\n maxindex = i\n return maxindex", "def rowwithmax1s(arr, n, m):\n (i, j) = (0, m - 1)\n count = 0\n index = 0\n ans = 0\n while i <= n - 1 and j >= 0:\n if arr[i][j] == 1:\n j -= 1\n count += 1\n index = i\n else:\n i += 1\n z = i\n for k in range(z, n):\n if arr[k][j] == 0:\n i += 1\n else:\n break\n if count == 0:\n return -1\n else:\n return index", "def rowwithmax1s(arr, n, m):\n max = 0\n row = 0\n for i in range(n):\n count = 0\n for j in range(m):\n if arr[i][j] == 1:\n count += 1\n if count > max:\n max = count\n row = i\n if max == 0:\n return -1\n else:\n return row", "def rowwithmax1s(arr, n, m):\n for col in range(m):\n for row in range(n):\n if arr[row][col] == 1:\n return row\n return -1", "def rowwithmax1s(arr, n, m):\n b = []\n for i in range(n):\n b.append(arr[i].count(1))\n if max(b) == 0:\n return -1\n else:\n res = b.index(max(b))\n return res", "def rowwithmax1s(arr, n, m):\n i = 0\n j = m - 1\n ans = -1\n while i < n and j >= 0:\n if arr[i][j] == 1:\n ans = i\n j -= 1\n if arr[i][j] == 0:\n i += 1\n return ans", "def rowwithmax1s(arr, n, m):\n r = 0\n c = m - 1\n max_row_index = -1\n while r < n and c >= 0:\n if arr[r][c] == 1:\n max_row_index = r\n c -= 1\n else:\n r += 1\n return max_row_index", "def rowwithmax1s(arr, n, m):\n res = -1\n mx = 0\n for i in range(len(arr)):\n count = 0\n for j in range(len(arr[i])):\n if arr[i][j] == 1:\n count += 1\n if count > mx:\n mx = count\n res = i\n return res", "def rowwithmax1s(arr, n, m):\n res = []\n for i in arr:\n res.append(sum(i))\n if max(res) == 0:\n return -1\n return res.index(max(res))", "def rowwithmax1s(arr, n, m):\n temp = 0\n ans = 0\n for i in range(len(arr)):\n cnt = arr[i].count(1)\n if cnt > temp:\n temp = cnt\n ans = i\n if temp == 0 and ans == 0:\n return -1\n return ans", "def rowwithmax1s(arr, n, m):\n currCol = len(arr[0])\n currRow = -1\n for r in range(len(arr)):\n for c in range(currCol - 1, -1, -1):\n if arr[r][c] == 1:\n currCol = c\n currRow = r\n else:\n break\n if currCol == 0:\n break\n return currRow", "def rowwithmax1s(arr, n, m):\n max = 0\n index = 0\n for i in range(n):\n (l, r) = (0, m - 1)\n if arr[i][r] == 0:\n continue\n while l <= r:\n mid = (l + r) // 2\n if arr[i][mid] == 0:\n l = mid + 1\n if arr[i][mid] == 1:\n r = mid - 1\n if m - r > max:\n index = i\n max = m - r\n if max == 0:\n return -1\n return index", "def rowwithmax1s(arr, n, m):\n c = 0\n for i in arr:\n if c < sum(i):\n c = sum(i)\n if c == 0:\n return -1\n else:\n for i in range(len(arr)):\n if sum(arr[i]) == c:\n return i", "def rowwithmax1s(arr, n, m):\n c = m - 1\n r_i = -1\n for i in range(n):\n while c >= 0 and arr[i][c] == 1:\n c -= 1\n r_i = i\n return r_i", "def rowwithmax1s(arr, n, m):\n count_arr = []\n for i in range(n):\n count = 0\n for j in range(m):\n if arr[i][j] == 1:\n count += 1\n count_arr.append(count)\n if max(count_arr) == 0:\n return -1\n max_ele = count_arr[0]\n index = 0\n for i in range(1, len(count_arr)):\n if count_arr[i] > max_ele:\n max_ele = count_arr[i]\n index = i\n return index", "def rowwithmax1s(arr, n, m):\n for i in range(m):\n for j in range(n):\n if arr[j][i] == 1:\n return j\n return -1", "def rowwithmax1s(arr, n, m):\n\n def BinaryFirstSearch(arr):\n n = len(arr)\n (res, l, r) = (float('inf'), 0, n - 1)\n while l <= r:\n mid = (l + r) // 2\n if arr[mid] == 1:\n res = mid\n r = mid - 1\n else:\n l = mid + 1\n return res\n ans = []\n for (idx, num) in enumerate(arr):\n ans.append([BinaryFirstSearch(num), idx])\n if min(ans)[0] < float('inf'):\n return min(ans)[1]\n return -1", "def rowwithmax1s(arr, n, m):\n\n def BinaryFirstSearch(arr):\n n = len(arr)\n (res, l, r) = (n, 0, n - 1)\n while l <= r:\n mid = (l + r) // 2\n if arr[mid] == 1:\n res = mid\n r = mid - 1\n else:\n l = mid + 1\n return res\n mx = 0\n ans = -1\n for i in range(len(arr)):\n if m - BinaryFirstSearch(arr[i]) > mx:\n mx = m - BinaryFirstSearch(arr[i])\n ans = i\n return ans", "def rowwithmax1s(matrix, n, m):\n res = []\n\n def leftocc(arr):\n start = 0\n end = len(arr) - 1\n mid = start + (end - start) // 2\n ans = 0\n while start <= end:\n if arr[mid] == 1:\n ans = mid\n end = mid - 1\n else:\n start = mid + 1\n mid = start + (end - start) // 2\n if ans == 0 and arr[0] == 0:\n return 0\n else:\n return len(arr) - ans\n for row in range(len(matrix)):\n count = leftocc(matrix[row])\n res.append((-1 * count, row))\n while True and res:\n ans = min(res)\n if ans[0] == 0:\n res.remove((ans[0], ans[1]))\n else:\n return ans[1]\n return -1", "def rowwithmax1s(arr, n, m):\n l = []\n for i in range(n):\n x = arr[i].count(1)\n l.append(x)\n x = max(l)\n if x == 0:\n return -1\n else:\n return l.index(max(l))", "def rowwithmax1s(arr, n, m):\n max = 0\n index = -1\n\n def bis(low, high, arr, c):\n mid = (low + high) // 2\n if low > high:\n return c\n if arr[mid] == 1:\n c += high - mid + 1\n return bis(low, mid - 1, arr, c)\n else:\n return bis(mid + 1, high, arr, c)\n for i in range(len(arr)):\n k = bis(0, m - 1, arr[i], 0)\n if max < k:\n max = k\n index = i\n return index", "def rowwithmax1s(matrix, R, C):\n row = -1\n j = C - 1\n for i in range(R):\n while j >= 0 and matrix[i][j] == 1:\n j -= 1\n row = i\n return row", "def rowwithmax1s(arr, n, m):\n dic = {}\n for (ind, row) in enumerate(arr):\n dic[ind] = row.count(1)\n maxvalue = 0\n index = 0\n for (key, value) in dic.items():\n if value > maxvalue:\n maxvalue = value\n index = key\n if maxvalue == 0:\n return -1\n return index", "def rowwithmax1s(arr, n, m):\n list_a = []\n k = 0\n for i in range(n):\n list_a.append(sum(arr[i]))\n max_count = max(list_a)\n for j in range(n):\n if max_count > 0:\n if max_count == list_a[j]:\n return j\n if k == 0:\n return -1", "def rowwithmax1s(arr, n, m):\n (s, idx) = (-1, -1)\n for i in range(len(arr)):\n temp = sum(arr[i])\n if temp >= 1 and temp > s:\n s = temp\n idx = i\n return idx", "def rowwithmax1s(arr, n, m):\n l = 0\n maxx = 0\n index = -1\n for i in range(n):\n if arr[i][-1] == 1:\n l = 0\n if m == 1:\n l = 1\n for j in range(m - 1):\n if arr[i][j] < arr[i][j + 1] or arr[i][j] == 1:\n if j == 0 and arr[i][j] == 1:\n l = m\n else:\n l = m - 1 - j\n break\n if l == m:\n return i\n if l > maxx:\n maxx = l\n index = i\n return index", "def rowwithmax1s(arr, n, m):\n c = [i for i in arr]\n k = []\n for i in range(len(c)):\n k.append(sum(c[i]))\n j = max(k)\n if sum(k) == 0:\n return -1\n return k.index(j)", "def rowwithmax1s(arr, n, m):\n c = mc = 0\n x = -1\n for i in range(len(arr)):\n c = arr[i].count(1)\n if c > mc:\n mc = c\n x = i\n return x", "def rowwithmax1s(arr, n, m):\n max_row_index = 0\n index = m - 1\n for i in range(n):\n flag = False\n while index >= 0 and arr[i][index] == 1:\n flag = True\n index -= 1\n if flag:\n max_row_index = i\n if max_row_index == 0 and arr[0][m - 1] == 0:\n return -1\n return max_row_index", "from collections import *\n\ndef rowwithmax1s(arr, n, m):\n dic = defaultdict(list)\n for i in range(len(arr)):\n dic[i] = arr[i].count(1)\n count = 0\n value = 0\n for (i, v) in dic.items():\n if v > value:\n value = v\n count = i\n if value == 0:\n return -1\n return count", "def rowwithmax1s(a, n, m):\n\n def getAns(a):\n l = 0\n h = len(a) - 1\n res = -1\n while l <= h:\n m = (l + h) // 2\n if a[m] == 1:\n res = m\n h = m - 1\n else:\n l = m + 1\n return res\n index = -1\n ans = m\n for i in range(n):\n x = getAns(a[i])\n if x < ans and x >= 0:\n ans = x\n index = i\n return index", "def rowwithmax1s(arr, n, m):\n n = len(arr)\n m = len(arr[0])\n maxRow = -1\n maxCount = 0\n for i in range(n):\n count = 0\n for j in range(m):\n if arr[i][j] == 1:\n count += 1\n if count > maxCount:\n maxCount = count\n maxRow = i\n return maxRow", "def rowwithmax1s(grid, n, m):\n (top, bottom) = (0, n - 1)\n (left, right) = (0, m - 1)\n result = -1\n while top <= bottom and left <= right:\n if grid[top][right] == 1:\n result = top\n right -= 1\n else:\n top += 1\n return result", "def rowwithmax1s(arr, n, m):\n (a, ac) = (-1, m)\n for i in range(n):\n (j, k) = (0, m - 1)\n while j <= k:\n mid = (j + k) // 2\n if arr[i][mid] == 1:\n k = mid - 1\n else:\n j = mid + 1\n ci = j\n if j < ac:\n a = i\n ac = j\n return a", "def rowwithmax1s(arr, n, m):\n (a, j) = (-1, m)\n for i in range(n):\n while j > 0 and arr[i][j - 1] == 1:\n a = i\n j -= 1\n if j == 0:\n return i\n return a", "def rowwithmax1s(arr, n, m):\n ans = []\n for i in range(n):\n s = 0\n for j in range(m):\n if arr[i][j] == 1:\n s += 1\n ans.append(s)\n ms = 0\n mi = -1\n for i in range(n):\n if ans[i] > ms:\n ms = ans[i]\n mi = i\n return mi", "def rowwithmax1s(arr, n, m):\n maxx = 0\n c = 0\n for i in range(len(arr)):\n if 1 not in arr[i]:\n c += 1\n if arr[i].count(1) > arr[maxx].count(1):\n maxx = i\n if c == len(arr):\n return -1\n return maxx", "def rowwithmax1s(arr, n, m):\n l = []\n for i in range(n):\n c = 0\n for j in range(m):\n if arr[i][j] == 1:\n c += 1\n l.append(c)\n maxi = max(l)\n if maxi != 0:\n return l.index(maxi)\n else:\n return -1", "def rowwithmax1s(arr, n, m):\n max_ones = 0\n row = -1\n for i in range(n):\n one_count = 0\n for j in range(m):\n if arr[i][j] == 1:\n one_count = m - j\n if one_count > max_ones:\n max_ones = one_count\n row = i\n break\n return row"], "starter_code": "def rowwithmax1s(arr, n, m):\n", "input_output": {"inputs": ["N = 4 , M = 4\r\nArr[][] = {{0, 1, 1, 1},\r\n {0, 0, 1, 1},\r\n {1, 1, 1, 1},\r\n {0, 0, 0, 0}}", "N = 2, M = 2\r\nArr[][] = {{0, 0}, {1, 1}}"], "outputs": ["2", "1"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Arrays", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/row-with-max-1s0023/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N+M)", "entry_point": "rowwithmax1s", "task_id": "TACO_lite/351", "example": [[[4, 4, [[0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]]], [2, 2, [[0, 0], [1, 1]]]], [null, null]]} +{"requirement": "The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)\n\n\nP A H N\nA P L S I I G\nY I R\n\n\nAnd then read line by line: \"PAHNAPLSIIGYIR\"\n\nWrite the code that will take a string and make this conversion given a number of rows:\n\n\nstring convert(string s, int numRows);\n\nExample 1:\n\n\nInput: s = \"PAYPALISHIRING\", numRows = 3\nOutput: \"PAHNAPLSIIGYIR\"\n\n\nExample 2:\n\n\nInput: s = \"PAYPALISHIRING\", numRows =\u00a04\nOutput:\u00a0\"PINALSIGYAHRPI\"\nExplanation:\n\nP I N\nA L S I G\nY A H R\nP I", "solutions": ["def convert(s, numRows):\n if numRows == 1:\n return s\n zigzag = ['' for i in range(numRows)]\n row = 0\n step = 1\n for c in s:\n if row == 0:\n step = 1\n if row == numRows - 1:\n step = -1\n zigzag[row] += c\n row += step\n return ''.join(zigzag)", "def convert(s, numRows):\n if numRows == 1 or numRows >= len(s):\n return s\n result = [''] * numRows\n (index, step) = (0, 1)\n for c in s:\n result[index] += c\n if index == 0:\n step = 1\n elif index == numRows - 1:\n step = -1\n index += step\n return ''.join(result)", "def convert(s, numRows):\n if numRows == 1 or numRows >= len(s):\n return s\n list_string = [''] * numRows\n (index, step) = (0, 1)\n for i in s:\n list_string[index] += i\n if index == 0:\n step = 1\n elif index == numRows - 1:\n step = -1\n index += step\n return ''.join(list_string)", "def convert(s, nRows):\n if nRows == 1:\n return s\n tmp = ['' for i in range(nRows)]\n index = -1\n step = 1\n for i in range(len(s)):\n index += step\n if index == nRows:\n index -= 2\n step = -1\n elif index == -1:\n index = 1\n step = 1\n tmp[index] += s[i]\n return ''.join(tmp)", "def convert(s, numRows):\n if numRows == 1:\n return s\n count = len(s)\n if count <= 1:\n return s\n result = []\n deltSmall = numRows - 1\n deltBig = 2 * deltSmall\n for i in range(0, numRows):\n k = i\n if i == 0 or i == deltSmall:\n while k < count:\n result.append(s[k])\n k += deltBig\n else:\n while k < count:\n top = k - k % deltSmall\n bottom = top + deltSmall\n result.append(s[k])\n nextk = 2 * bottom - k\n if nextk < count:\n result.append(s[nextk])\n k += deltBig\n return ''.join(result)", "def convert(s, numRows):\n if len(s) == 0 or numRows < 1:\n return ''\n if numRows == 1:\n return s\n maxStep = (numRows - 1) * 2\n reStr = ''\n for i in range(numRows):\n j = i\n step = maxStep - 2 * i\n while j < len(s):\n reStr += s[j]\n if step == 0:\n j += maxStep\n else:\n j += step\n step = maxStep - step\n if step == 0:\n step = maxStep\n return reStr"], "starter_code": "def convert(s: str, numRows: int) -> str:\n", "input_output": {"fn_name": "convert", "inputs": [["\"PAYPALISHIRING\"", 3]], "outputs": ["\"PSIPYAIHRN\"ALIG"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["String"], "name": null, "source": "leetcode", "tags": ["String algorithms"], "skill_types": [], "url": "https://leetcode.com/problems/zigzag-conversion/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "convert", "task_id": "TACO_lite/377", "example": [[["PAYPALISHIRING", 3], ["PAYPALISHIRING", 4]], ["PAHNAPLSIIGYIR", "PINALSIGYAHRPI"]]} +{"requirement": "Given an array arr[] of positive integers of size N. Reverse every sub-array group of size K.\nNote: If at any instance, there are no more subarrays of size greater than or equal to K, then reverse the last subarray (irrespective of its size). You shouldn't return any array, modify the given array in-place.\nExample 1:\nInput:\nN = 5, K = 3\narr[] = {1,2,3,4,5}\nOutput: 3 2 1 5 4\nExplanation: First group consists of elements\n1, 2, 3. Second group consists of 4,5.\n \nExample 2:\nInput:\nN = 4, K = 3\narr[] = {5,6,8,9}\nOutput: 8 6 5 9\n \nYour Task:\nYou don't need to read input or print anything. The task is to complete the function reverseInGroups() which takes the array, N and K as input parameters and modifies the array in-place. \n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 \u2264 N, K \u2264 10^{7}\n1 \u2264 A[i] \u2264 10^{18}", "solutions": ["def reverseingroups(arr, N, k):\n n = len(arr)\n i = 0\n while i < n:\n if i + k <= n:\n left = i\n right = i + k - 1\n else:\n left = i\n right = n - 1\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1\n i += k\n return arr", "def reverseingroups(arr, N, K):\n i = 0\n while i < N:\n if i + K < N:\n arr[i:i + K] = arr[i:i + K][::-1]\n i += K\n else:\n arr[i:] = arr[i:N][::-1]\n i += K\n return arr", "def reverseingroups(arr, N, K):\n i = 0\n while i < N:\n if i + K < N:\n arr[i:i + K] = reversed(arr[i:i + K])\n i += K\n else:\n arr[i:] = reversed(arr[i:])\n i += K", "def reverseingroups(arr, N, K):\n for i in range(0, N, K):\n if i < N - K:\n arr[i:i + K] = arr[i:i + K][::-1]\n else:\n arr[i:] = arr[i:][::-1]\n return arr", "def reverseingroups(arr, N, K):\n start = 0\n end = K\n while start < N:\n new_list = arr[start:end]\n new_list.reverse()\n j = start\n for item in new_list:\n arr[j] = item\n j += 1\n start = end\n end = end + K\n return arr", "def reverseingroups(arr, N, K):\n i = 0\n while i + K < N:\n arr[i:i + K] = arr[i:i + K][::-1]\n i += K\n arr[i:] = arr[i:][::-1]", "def reverseingroups(arr, N, K):\n c = 0\n l1 = [0]\n for i in range(len(arr)):\n c += 1\n if c > K:\n l1.append(i)\n c = 1\n if c > 0 and c < K:\n l1.append(len(arr))\n for i in range(len(l1) - 1):\n arr[l1[i]:l1[i + 1]] = arr[l1[i]:l1[i + 1]][::-1]\n return arr", "def reverseingroups(arr, N, K):\n for i in range(0, N, K):\n start = i\n end = start + K - 1\n if start + K - 1 > N - 1:\n end = N - 1\n while start < end:\n (arr[start], arr[end]) = (arr[end], arr[start])\n start += 1\n end -= 1", "def reverseingroups(arr, N, K):\n i = 0\n while i < N:\n left = i\n right = min(i + K - 1, N - 1)\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1\n i += K", "def reverseingroups(arr, N, k):\n start = 0\n end = k - 1\n while end < N:\n tempStart = start\n tempEnd = end\n while tempStart < tempEnd:\n (arr[tempStart], arr[tempEnd]) = (arr[tempEnd], arr[tempStart])\n tempEnd -= 1\n tempStart += 1\n start = end + 1\n end += k\n if start < N:\n end = N - 1\n while start < end:\n (arr[start], arr[end]) = (arr[end], arr[start])\n start += 1\n end -= 1", "def reverseingroups(arr, N, K):\n N = N % K\n if len(arr) <= K:\n first = arr[:N + 1]\n first = first[::-1]\n second = arr[N + 1:]\n second = second[::-1]\n arr[:] = first + second\n return arr\n else:\n lst = []\n length = len(arr)\n divide = length // K\n a = 0\n b = K\n for i in range(divide + 1):\n res = arr[a:b][::-1]\n for i in res:\n lst.append(i)\n a = b\n b += K\n arr[:] = lst\n return arr", "def reverseingroups(arr, N, K):\n for i in range(0, N, K):\n arr[i:i + K] = arr[i:i + K][::-1]", "def reverseingroups(arr, N, K):\n for i in range(0, N, K):\n left = i\n right = min(i + K - 1, N - 1)\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1", "def reverseingroups(arr, n, k):\n for i in range(0, n, k):\n arr[i:i + k] = arr[i:i + k][::-1]\n return arr", "def reverseingroups(arr, N, K):\n for i in range(0, N, K):\n p = i + K - 1\n if p > N - 1:\n p = N - 1\n while p > i:\n (arr[i], arr[p]) = (arr[p], arr[i])\n p -= 1\n i += 1", "def reverseingroups(arr, N, K):\n a = []\n s = 0\n i = 0\n d = 0\n while s <= N:\n i += 1\n if i == K or s == N:\n a += arr[d:d + i][::-1]\n d += K\n i = 0\n s += 1\n return a", "def reverseingroups(arr, N, K):\n a = []\n jump = K\n for i in range(0, N):\n if jump <= N + K:\n a += arr[K * i:jump][::-1]\n jump += K\n else:\n arr[:] = a\n break", "def reverseingroups(arr, N, K):\n z = 0\n while z < N - 1:\n (i, j) = (z, min(z + K - 1, N - 1))\n while i < j:\n [arr[i], arr[j]] = [arr[j], arr[i]]\n i += 1\n j -= 1\n z = min(z + K, N - 1)", "def reverseingroups(arr, N, K):\n start = 0\n while start < N:\n end = min(start + K - 1, N - 1)\n left = start\n right = end\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1\n start += K\n return arr", "def reverseingroups(arr, N, K):\n for i in range(0, len(arr), K):\n group = arr[i:i + K]\n group.reverse()\n arr[i:i + K] = group", "def reverseingroups(arr, N, K):\n for i in range(0, N, K):\n arr[i:i + K] = reversed(arr[i:i + K])\n return arr", "def reverseingroups(arr, N, k):\n ans = []\n for x in range(0, len(arr), k):\n l = arr[x:x + k][::-1]\n ans += l\n i = 0\n for x in ans:\n arr[i] = x\n i += 1", "def reverseingroups(arr, N, K):\n i = 0\n while i < N:\n start = i\n end = min(i + K - 1, N - 1)\n while start < end:\n (arr[start], arr[end]) = (arr[end], arr[start])\n start += 1\n end -= 1\n i += K\n return arr", "def reverseingroups(arr, n, k):\n start = 0\n end = k - 1\n while end < n:\n tempstart = start\n tempend = end\n while tempstart < tempend:\n (arr[tempstart], arr[tempend]) = (arr[tempend], arr[tempstart])\n tempstart += 1\n tempend -= 1\n start = end + 1\n end = end + k\n if start < n:\n end = n - 1\n tempstart = start\n tempend = end\n while tempstart < tempend:\n (arr[tempstart], arr[tempend]) = (arr[tempend], arr[tempstart])\n tempstart += 1\n tempend -= 1", "def reverseingroups(arr, N, K):\n\n def rev_arr(arr, low, high):\n while low <= high:\n (arr[low], arr[high]) = (arr[high], arr[low])\n low += 1\n high -= 1\n for i in range(0, N, K):\n try:\n rev_arr(arr, i, i + K - 1)\n except IndexError:\n rev_arr(arr, i, N - 1)\n else:\n pass", "def reverseingroups(arr, n, k):\n i = 0\n while i < n:\n left = i\n right = min(i + k - 1, n - 1)\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1\n i += k\n return arr", "def reverseingroups(arr, N, K):\n x = 0\n while x < N:\n l = x\n if N - 1 >= x + K - 1:\n h = x + K - 1\n else:\n h = N - 1\n while l < h:\n (arr[h], arr[l]) = (arr[l], arr[h])\n h = h - 1\n l = l + 1\n x = x + K", "def reverseingroups(arr, N, K):\n ans = []\n r = N / K\n for i in range(0, N, K):\n end = i + K\n if end > N:\n end = N\n temp = arr[i:end]\n temp.reverse()\n arr[i:end] = temp", "def reverseingroups(arr, N, K):\n i = 0\n while i < N:\n l = i\n r = min(N - 1, i + K - 1)\n while l < r:\n (arr[l], arr[r]) = (arr[r], arr[l])\n l += 1\n r -= 1\n i = i + K", "def reverseingroups(arr, N, K):\n for i in range(0, N, K):\n if i + K <= N:\n arr[i:i + K] = reversed(arr[i:i + K])\n else:\n arr[i:] = reversed(arr[i:])\n break", "def reverseingroups(arr, n, k):\n i = 0\n while i < n:\n end = i + k - 1 if i + k - 1 < n else n - 1\n start = i\n while start < end:\n (arr[start], arr[end]) = (arr[end], arr[start])\n start += 1\n end -= 1\n i += k", "def swap(arr, i, j):\n t = arr[i]\n arr[i] = arr[j]\n arr[j] = t\n\ndef reverse(arr, start, end):\n while start < end:\n self.swap(arr, start, end)\n start += 1\n end -= 1\n\ndef reverseingroups(arr, N, K):\n start = 0\n while start < N:\n end = start + K\n if end < N:\n end -= 1\n else:\n end = N - 1\n self.reverse(arr, start, end)\n start += K", "import math\n\ndef reverseingroups(arr, N, K):\n self.arr = arr\n self.N = N\n self.K = K\n nn = int(math.ceil(N / K))\n for i in range(nn):\n ini = i * K\n fin = i * K + K\n sub_arr = arr[ini:fin]\n sub_arr.reverse()\n arr[ini:fin] = sub_arr\n return arr", "def reverseingroups(arr, n, k):\n i = 0\n while i < n:\n j = i + k - 1\n if j >= n:\n j = n - 1\n left = i\n right = j\n while left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1\n i += k", "def reverseingroups(a, N, k):\n i = 0\n while i < N:\n a[i:i + k] = a[i:i + k][::-1]\n i = i + k\n return a", "def reverseingroups(arr, N, K):\n gp = N // K\n rm = N % K\n if gp != 0:\n for i in range(gp):\n for j in range(1, K // 2 + 1):\n (arr[i * K + j - 1], arr[i * K + K - j]) = (arr[i * K + K - j], arr[i * K + j - 1])\n for n in range(rm // 2):\n (arr[K * gp + n], arr[K * gp + rm - 1 - n]) = (arr[K * gp + rm - 1 - n], arr[K * gp + n])\n else:\n for n in range(N // 2):\n (arr[n], arr[N - n - 1]) = (arr[N - n - 1], arr[n])\n return arr"], "starter_code": "def reverseingroups(arr, N, K):\n", "input_output": {"inputs": ["N = 5, K = 3\r\narr[] = {1,2,3,4,5}", "N = 4, K = 3\r\narr[] = {5,6,8,9}"], "outputs": ["3 2 1 5 4", "8 6 5 9"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/reverse-array-in-groups0255/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "reverseingroups", "task_id": "TACO_lite/467", "example": [[[5, 3, [1, 2, 3, 4, 5]], [4, 3, [5, 6, 8, 9]]], [null, null]]} +{"requirement": "Given an array of n integers. We need to count all values of \u2018k\u2019 such that\narr[0] % k = arr[1] % k = ....... = arr[n-1] % k \n \nExample 1:\nInput:\nN=3\narr[] = {38, 6, 34} \nOutput: 3\nExplanation:\nWe can have values of k as \n1, 2 and 4. \nExample 2:\nInput:\nN=2\narr[] = {3, 2} \nOutput: 1\nYour Task:\nSince, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function printEqualModNumbers() that takes array arr and integer n as parameters and returns the desired output.\nNote- If values of k are infinite return -1.\n \nExpected Time Complexity: O(N^{3/2}).\nExpected Auxiliary Space: O(N).\n \nConstraints:\n1 \u2264 N \u2264 10^{5}", "solutions": ["def fun(i, arr):\n k = arr[0] % i\n for j in arr:\n if j % i != k:\n return False\n return True\n\ndef printequalmodnumbers(arr, n):\n if n == 1:\n return -1\n a = max(arr)\n res = 0\n for i in range(1, a + 1):\n if Solution.fun(i, arr):\n res += 1\n if res == 0:\n return -1\n else:\n return res", "def printequalmodnumbers(arr, n):\n minum = max(arr)\n count = 1\n tcount = 0\n if len(arr) == 1:\n return -1\n for i in range(1, minum + 1):\n prev = arr[0] % i\n for j in range(1, len(arr)):\n if arr[j] % i == prev:\n count += 1\n else:\n break\n if count == len(arr):\n tcount += 1\n count = 1\n return tcount", "def printequalmodnumbers(arr, n):\n arr.sort()\n count = 0\n d = arr[n - 1] - arr[0]\n if d == 0:\n return -1\n v = []\n i = 1\n while i * i <= d:\n if d % i == 0:\n v.append(i)\n if i != d / i:\n v.append(d / i)\n i += 1\n for i in range(len(v)):\n temp = arr[0] % v[i]\n j = 1\n while j < n:\n if arr[j] % v[i] != temp:\n break\n j += 1\n if j == n:\n count += 1\n return count"], "starter_code": "def printequalmodnumbers(arr, n):\n", "input_output": {"inputs": ["N=3\narr[] = {38, 6, 34}", "N=2\narr[] = {3, 2}"], "outputs": ["3", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays", "Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures", "Mathematics"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/k-modulus-array-element0255/1", "Expected Auxiliary Space": "O(N).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N^{3/2}).", "entry_point": "printequalmodnumbers", "task_id": "TACO_lite/342", "example": [[[3, [38, 6, 34]], [2, [3, 2]]], [null, null]]} +{"requirement": "#Bubbleing around\n\nSince everybody hates chaos and loves sorted lists we should implement some more sorting algorithms. Your task is to implement a Bubble sort (for some help look at https://en.wikipedia.org/wiki/Bubble_sort) and return a list of snapshots after **each change** of the initial list.\n\ne.g. \n\nIf the initial list would be l=[1,2,4,3] my algorithm rotates l[2] and l[3] and after that it adds [1,2,3,4] to the result, which is a list of snapshots.\n```\n[1,2,4,3] should return [ [1,2,3,4] ]\n[2,1,4,3] should return [ [1,2,4,3], [1,2,3,4] ]\n[1,2,3,4] should return []\n```", "solutions": ["def bubble(l):\n ret = []\n for i in range(len(l) - 1, 0, -1):\n for j in range(i):\n if l[j] > l[j + 1]:\n (l[j], l[j + 1]) = (l[j + 1], l[j])\n ret.append(l[:])\n return ret", "def bubble(l):\n (bubbling, bubbles) = (True, [])\n while bubbling:\n bubbling = False\n for i in range(len(l) - 1):\n if l[i] > l[i + 1]:\n (l[i], l[i + 1]) = (l[i + 1], l[i])\n bubbling = True\n bubbles.append(l[:])\n return bubbles", "def bubble(l):\n arr = []\n for j in range(len(l) - 1, 0, -1):\n for i in range(j):\n if l[i] > l[i + 1]:\n temp = l[i]\n l[i] = l[i + 1]\n l[i + 1] = temp\n arr.append(l[:])\n return arr", "def bubble(lst):\n result = []\n mod = lst.copy()\n swap = True\n while swap:\n swap = False\n for i in range(len(mod) - 1):\n if mod[i] > mod[i + 1]:\n (mod[i], mod[i + 1]) = (mod[i + 1], mod[i])\n swap = True\n result.append(mod.copy())\n return result", "def bubble(l):\n snapshots = []\n for i in range(len(l), 1, -1):\n for j in range(1, i):\n if l[j - 1] > l[j]:\n (l[j - 1], l[j]) = (l[j], l[j - 1])\n snapshots.append(l[:])\n return snapshots", "def swap(l, aindex, bindex):\n tmp = l[bindex]\n l[bindex] = l[aindex]\n l[aindex] = tmp\n\ndef bubble(l):\n result = []\n for _ in range(len(l) - 1):\n for i in range(len(l) - 1):\n if l[i] > l[i + 1]:\n swap(l, i, i + 1)\n result.append(list(l))\n return result", "def bubble(l):\n (n, permutations) = (len(l), [])\n while n:\n m = 0\n for i in range(1, n):\n if l[i - 1] > l[i]:\n (l[i - 1], l[i]) = (l[i], l[i - 1])\n permutations.append(l[:])\n m = i\n n = m\n return permutations", "def bubble(l):\n (output, toChange) = ([], True)\n while toChange:\n toChange = False\n for (i, x) in enumerate(l[:-1]):\n if l[i + 1] < l[i]:\n (l[i], l[i + 1]) = (l[i + 1], l[i])\n output.append(l[:])\n toChange = True\n return output", "def bubble(l):\n r = []\n for i in range(0, len(l)):\n for j in range(1, len(l)):\n if l[j] < l[j - 1]:\n t = l[j]\n l[j] = l[j - 1]\n l[j - 1] = t\n r.append(l[:])\n return r", "def bubble(a):\n if a == None or len(a) < 2:\n return []\n swapped = True\n i = 0\n r = []\n while i < len(a) - 1 and swapped:\n swapped = False\n for j in range(len(a) - i - 1):\n if a[j] > a[j + 1]:\n (a[j], a[j + 1]) = (a[j + 1], a[j])\n r.append(list(a))\n swapped = True\n i += 1\n return r"], "starter_code": "def bubble(l):\n", "input_output": {"fn_name": "bubble", "inputs": [[[]], [[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[1, 3, 3, 7, 4, 2]]], "outputs": [[[]], [[]], [[[1, 3, 3, 4, 7, 2], [1, 3, 3, 4, 2, 7], [1, 3, 3, 2, 4, 7], [1, 3, 2, 3, 4, 7], [1, 2, 3, 3, 4, 7]]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Sorting", "Algorithms"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://www.codewars.com/kata/57403b5ad67e87b5e7000d1d", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "bubble", "task_id": "TACO_lite/452", "example": [[[[1, 2, 3, 4]], [[1, 2, 3, 4]], [[1, 2, 3, 4]]], [[], [], []]]} +{"requirement": "In this kata you need to write a function that will receive two strings (```n1``` and ```n2```), each representing an integer as a binary number. A third parameter will be provided (```o```) as a string representing one of the following operators: add, subtract, multiply.\n\nYour task is to write the calculate function so that it will perform the arithmetic and the result returned should be a string representing the binary result.\n\nExamples:\n```\n1 + 1 === 10\n10 + 10 === 100\n```\n\nNegative binary numbers are usually preceded by several 1's. For this kata, negative numbers can be represented with the negative symbol at the beginning of the string.\n\nExamples of negatives:\n```\n1 - 10 === -1\n10 - 100 === -10\n```", "solutions": ["def calculate(n1, n2, o):\n operators = {'add': lambda x, y: x + y, 'subtract': lambda x, y: x - y, 'multiply': lambda x, y: x * y}\n return '{:b}'.format(operators[o](int(n1, 2), int(n2, 2)))", "def calculate(n1, n2, o):\n\n def s2b(i):\n return int(i, base=2)\n if o == 'add':\n res = s2b(n1) + s2b(n2)\n elif o == 'subtract':\n res = s2b(n1) - s2b(n2)\n elif o == 'multiply':\n res = s2b(n1) * s2b(n2)\n return '{0:b}'.format(res)", "def calculate(n1, n2, o):\n ops = {'add': lambda a, b: a + b, 'subtract': lambda a, b: a - b, 'multiply': lambda a, b: a * b}\n n = ops[o](int(n1, 2), int(n2, 2))\n s = str(bin(n))\n return '-' + s[3:] if n < 0 else s[2:]", "from operator import add, sub as subtract, mul as multiply\n\ndef calculate(n1, n2, o):\n value = globals()[o](int(n1, 2), int(n2, 2))\n return format(value, 'b')", "from operator import *\n\ndef calculate(n1, n2, o):\n result = eval(o[:3])(int(n1, 2), int(n2, 2))\n return (bin(result)[2:], bin(result)[0] + bin(result)[3:])[result < 0]", "import operator\n\ndef calculate(n1, n2, o):\n calc = {'add': operator.add(int(n1, base=2), int(n2, base=2)), 'subtract': operator.sub(int(n1, base=2), int(n2, base=2)), 'multiply': operator.mul(int(n1, base=2), int(n2, base=2))}\n return '{:b}'.format(calc[o])", "def calculate(n1, n2, o):\n if o == 'add':\n return bin(int(n1, 2) + int(n2, 2))[2:]\n if o == 'subtract':\n result = bin(int(n1, 2) - int(n2, 2))\n if result[0] == '-':\n return result[0] + result[3:]\n return result[2:]\n if o == 'multiply':\n return bin(int(n1, 2) * int(n2, 2))[2:]\n if o == 'divide':\n return bin(int(n1, 2) / int(n2, 2))[2:]", "def calculate(n1, n2, o):\n return bin(int(n1, 2) + int(n2, 2) if o == 'add' else int(n1, 2) - int(n2, 2) if o == 'subtract' else int(n1, 2) * int(n2, 2)).replace('0b', '')"], "starter_code": "def calculate(n1, n2, o):\n", "input_output": {"fn_name": "calculate", "inputs": [["1", "1", "add"], ["1", "1", "subtract"], ["1", "1", "multiply"], ["10", "10", "multiply"], ["100", "10", "subtract"]], "outputs": [["10"], ["0"], ["1"], ["100"], ["10"]]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Binary"], "name": null, "source": "codewars", "tags": ["Bit manipulation"], "skill_types": ["Bit manipulation"], "url": "https://www.codewars.com/kata/546ba103f0cf8f7982000df4", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "calculate", "task_id": "TACO_lite/464", "example": [[["1", "1", "add"], ["10", "10", "add"], ["1", "10", "subtract"], ["10", "100", "subtract"]], ["10", "100", "-1", "-10"]]} +{"requirement": "**This Kata is intended as a small challenge for my students**\n\nAll Star Code Challenge #16\n\nCreate a function called noRepeat() that takes a string argument and returns a single letter string of the **first** not repeated character in the entire string.\n\n``` haskell\nnoRepeat \"aabbccdde\" `shouldBe` 'e'\nnoRepeat \"wxyz\" `shouldBe` 'w'\nnoRepeat \"testing\" `shouldBe` 'e'\n```\n\nNote:\nONLY letters from the english alphabet will be used as input\nThere will ALWAYS be at least one non-repeating letter in the input string", "solutions": ["def no_repeat(s):\n return next((c for c in s if s.count(c) == 1))", "def no_repeat(string):\n return [x for x in string if string.count(x) == 1][0]", "from collections import Counter\n\ndef no_repeat(string):\n return next((k for (k, v) in Counter(string).items() if v == 1))", "no_repeat = lambda s: [w for w in s if s.count(w) == 1][0]", "def no_repeat(stg):\n return next((c for c in stg if stg.count(c) == 1))", "def no_repeat(string):\n for e in string:\n if string.count(e) == 1:\n return e", "def no_repeat(string):\n if string.count(string[0]) == 1:\n return string[0]\n else:\n return no_repeat(string.replace(string[0], ''))", "def no_repeat(string):\n return min(string, key=string.count)", "def no_repeat(string):\n for c in string:\n if len(string.split(c)) == 2:\n return c", "def no_repeat(string):\n for i in string:\n if string.index(i) == len(string) - string[::-1].index(i) - 1:\n return i"], "starter_code": "def no_repeat(string):\n", "input_output": {"fn_name": "no_repeat", "inputs": [["aabbccdde"], ["wxyz"], ["testing"], ["codewars"], ["Testing"]], "outputs": [["e"], ["w"], ["e"], ["c"], ["T"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/586566b773bd9cbe2b000013", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "no_repeat", "task_id": "TACO_lite/481", "example": [[["aabbccdde"], ["wxyz"], ["testing"]], ["e", "w", "e"]]} +{"requirement": "Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: `(index1, index2)`.\n\nFor the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted.\n\nThe input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array).\n\nBased on: http://oj.leetcode.com/problems/two-sum/", "solutions": ["def two_sum(nums, t):\n for (i, x) in enumerate(nums):\n for (j, y) in enumerate(nums):\n if i != j and x + y == t:\n return [i, j]", "def two_sum(nums, target):\n d = {}\n for (i, num) in enumerate(nums):\n diff = target - num\n if diff in d:\n return [d[diff], i]\n d[num] = i", "def two_sum(numbers, target):\n d = {}\n for (i, n) in enumerate(numbers):\n if target - n in d:\n return [d[target - n], i]\n d[n] = i", "def two_sum(numbers, target):\n for i in range(0, len(numbers)):\n for x in range(0, len(numbers)):\n if numbers[i] + numbers[x] == target and i != x:\n index1 = i\n index2 = x\n break\n return sorted([index1, index2])", "def two_sum(numbers, target):\n for (i, val1) in enumerate(numbers[:-1]):\n for (j, val2) in enumerate(numbers[i + 1:]):\n if val1 + val2 == target:\n return (i, j + i + 1)", "def two_sum(numbers, target):\n return [[i, numbers.index(target - numbers[i])] for i in range(len(numbers)) if target - numbers[i] in numbers].pop()", "def two_sum(n, target):\n for i in range(len(n) - 1):\n if target - n[i] in n[i + 1:]:\n return [i, n[i + 1:].index(target - n[i]) + (i + 1)]\n return None", "def two_sum(numbers, target):\n for i in range(len(numbers)):\n for j in range(len(numbers)):\n if i != j and numbers[i] + numbers[j] == target:\n return [i, j]", "def two_sum(numbers, target):\n numbers.sort()\n i = 0\n j = len(numbers) - 1\n sum_ = numbers[i] + numbers[j]\n while sum_ != target:\n if sum_ < target:\n i += 1\n elif sum_ > target:\n j -= 1\n sum_ = numbers[i] + numbers[j]\n return [i, j]", "from itertools import combinations\n\ndef two_sum(numbers, target):\n for (i1, i2) in combinations(list(range(len(numbers))), 2):\n if numbers[i1] + numbers[i2] == target:\n return (i1, i2)"], "starter_code": "def two_sum(numbers, target):\n", "input_output": {"fn_name": "two_sum", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals", "Algorithms"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/52c31f8e6605bcc646000082", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "two_sum", "task_id": "TACO_lite/449", "example": [[[[2, 7, 11, 15], 9], [[3, 2, 4], 6], [[3, 3], 6]], [[0, 1], [1, 2], [0, 1]]]} +{"requirement": "Consider the following array:\n\n```\n[1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789, 12345678910, 1234567891011...]\n```\n\nIf we join these blocks of numbers, we come up with an infinite sequence which starts with `112123123412345123456...`. The list is infinite.\n\nYou will be given an number (`n`) and your task will be to return the element at that index in the sequence, where `1 \u2264 n \u2264 10^18`. Assume the indexes start with `1`, not `0`. For example:\n\n```\nsolve(1) = 1, because the first character in the sequence is 1. There is no index 0. \nsolve(2) = 1, because the second character is also 1.\nsolve(3) = 2, because the third character is 2.\n```\n\nMore examples in the test cases. Good luck!", "solutions": ["def solve(n):\n\n def length(n):\n s = 0\n for i in range(20):\n o = 10 ** i - 1\n if o > n:\n break\n s += (n - o) * (n - o + 1) // 2\n return s\n\n def binary_search(k):\n n = 0\n for p in range(63, -1, -1):\n if length(n + 2 ** p) < k:\n n += 2 ** p\n return n\n\n def sequence(n):\n if n < 10:\n return n\n for i in range(1, 19):\n segment = i * 9 * 10 ** (i - 1)\n if n <= segment:\n return str(10 ** (i - 1) + (n - 1) // i)[(n - 1) % i]\n else:\n n -= segment\n return int(sequence(n - length(binary_search(n))))", "from itertools import count\nfrom math import floor\nfrom decimal import Decimal\n\ndef find_sum(a, d, n):\n return int(Decimal(n / 2) * Decimal(2 * a + (n - 1) * d))\n\ndef term(a, d, n):\n return a + d * (n - 1)\n\ndef solve_quadratic(a, b, c):\n return floor((-b + (b ** 2 - 4 * a * c) ** 0.5) / (2 * a))\n\ndef extract(n):\n passed = 0\n for i in count(1):\n k = 9 * 10 ** (i - 1) * i\n if passed + k >= n:\n return str(int(10 ** (i - 1) + (n - passed) // i))[int(n - passed) % i]\n passed += k\n\ndef solve(n):\n (n, start, passed) = (n - 1, 1, 0)\n for i in count(1):\n k = 9 * 10 ** (i - 1)\n sum_ = find_sum(start, i, k)\n if passed + sum_ >= n:\n p = solve_quadratic(i, 2 * start - i, -((n - passed) * 2))\n q = passed + find_sum(start, i, p)\n return int(extract(n - q))\n start = term(start, i, k) + (i + 1)\n passed += sum_\nsolve(int(1e+100))", "def getGreatest(n, d, prefix):\n rows = 9 * 10 ** (d - 1)\n triangle = rows * (d + rows * d) // 2\n l = 0\n r = triangle\n while l < r:\n mid = l + (r - l >> 1)\n triangle = mid * prefix + mid * (d + mid * d) // 2\n prevTriangle = (mid - 1) * prefix + (mid - 1) * (d + (mid - 1) * d) // 2\n nextTriangle = (mid + 1) * prefix + (mid + 1) * (d + (mid + 1) * d) // 2\n if triangle >= n:\n if prevTriangle < n:\n return prevTriangle\n else:\n r = mid - 1\n elif nextTriangle >= n:\n return triangle\n else:\n l = mid\n return l * prefix + l * (d + l * d) // 2\nns = [1, 2, 3, 100, 2100, 31000, 999999999999999999, 1000000000000000000, 999999999999999993]\n\ndef solve(n):\n debug = 1\n d = 0\n p = 0.1\n prefixes = [0]\n sections = [0]\n while sections[d] < n:\n d += 1\n p *= 10\n rows = int(9 * p)\n triangle = rows * (d + rows * d) // 2\n section = rows * prefixes[d - 1] + triangle\n sections.append(sections[d - 1] + section)\n prefixes.append(prefixes[d - 1] + rows * d)\n section = sections[d - 1]\n n = n - section\n rows = getGreatest(n, d, prefixes[d - 1])\n n = n - rows\n d = 1\n while prefixes[d] < n:\n d += 1\n if prefixes[d] == n:\n return 9\n prefix = prefixes[d - 1]\n n -= prefix\n countDDigitNums = n // d\n remainder = n % d\n prev = 10 ** (d - 1) - 1\n num = prev + countDDigitNums\n if remainder:\n return int(str(num + 1)[remainder - 1])\n else:\n s = str(num)\n return int(s[len(s) - 1])", "import math\n\ndef seq_len_formula(s, b, n, i):\n return s + i * b + n * (i * (i + 1) // 2)\n\ndef increasing_step(num_len, block_len, seq_len):\n num_of_blocks = 9 * 10 ** num_len\n num_len += 1\n seq_len = seq_len_formula(seq_len, block_len, num_len, num_of_blocks)\n block_len = block_len + num_len * num_of_blocks\n return (num_len, block_len, seq_len)\n\ndef solve(n):\n buffer = IS_seq_len = (0, 0, 0)\n while IS_seq_len[2] < n:\n (num_len, block_len, seq_len) = buffer = IS_seq_len\n IS_seq_len = increasing_step(num_len, block_len, seq_len)\n (num_len, init_block_len, init_seq_len) = buffer\n step = 9 * 10 ** num_len\n num_len += 1\n buffer = (0, init_seq_len)\n while step > 0:\n (num_of_blocks, seq_len) = buffer\n while seq_len < n:\n buffer = (num_of_blocks, seq_len)\n num_of_blocks += step\n seq_len = seq_len_formula(init_seq_len, init_block_len, num_len, num_of_blocks)\n step = round(step / 10)\n n -= buffer[1]\n buffer = IS_block_len = (0, 0, 0)\n while IS_block_len[1] < n:\n (num_len, block_len, seq_len) = buffer = IS_block_len\n IS_block_len = increasing_step(num_len, block_len, seq_len)\n num_len = 10 ** buffer[0] - 1\n block_len = buffer[1]\n amount_of_nums = math.ceil((n - block_len) / len(str(num_len + 1)))\n n = n - amount_of_nums * len(str(num_len + 1)) - block_len - 1\n num = amount_of_nums + num_len\n return int(str(num)[n])", "def solve(k):\n k -= 1\n (i, d, p, n, s) = (0, 1, 0, 9, 45)\n while i + s <= k:\n i += s\n p += n * d\n d += 1\n n = 10 ** d - 10 ** (d - 1)\n s = n * p + n * d * (n + 1) // 2\n k -= i\n i = int((((2 * p + d) ** 2 + 8 * k * d) ** 0.5 - (2 * p + d)) / (2 * d))\n k -= i * p + i * d * (i + 1) // 2\n (i, d, s) = (0, 1, 9)\n while i + s <= k:\n i += s\n d += 1\n n = 10 ** d - 10 ** (d - 1)\n s = n * d\n (q, r) = divmod(k - i, d)\n return int(str(10 ** (d - 1) + q)[r])", "import math\n\ndef seq_len_formula(s, b, n, i):\n return s + i * b + n * (i * (i + 1) // 2)\n\ndef point_gen():\n (num_len, block_len, seq_len) = (0, 0, 0)\n while True:\n yield (num_len, block_len, seq_len)\n num_of_blocks = 9 * 10 ** num_len\n num_len += 1\n seq_len = seq_len_formula(seq_len, block_len, num_len, num_of_blocks)\n block_len = block_len + num_len * num_of_blocks\n\ndef linear_search(index, parameter):\n params = {'block_len': 1, 'seq_len': 2}\n required_point = (0, 0, 0)\n for point in point_gen():\n if point[params[parameter]] >= index:\n return required_point\n required_point = point\n\ndef index_for_block(num_len, block_len, index):\n corrector = num_of_blocks = 9 * 10 ** (num_len - 1)\n seq_len = seq_len_formula(0, block_len, num_len, num_of_blocks)\n while not seq_len < index <= seq_len_formula(0, block_len, num_len, num_of_blocks + 1):\n corrector = math.ceil(corrector / 2)\n num_of_blocks = num_of_blocks - corrector if seq_len >= index else num_of_blocks + corrector\n seq_len = seq_len_formula(0, block_len, num_len, num_of_blocks)\n return index - seq_len\n\ndef solve(index):\n (initial_len, initial_block_len, initial_seq_len) = linear_search(index, 'seq_len')\n index = index_for_block(initial_len + 1, initial_block_len, index - initial_seq_len)\n buffer = linear_search(index, 'block_len')\n (num_len, block_len) = (10 ** buffer[0] - 1, buffer[1])\n amount_of_nums = math.ceil((index - block_len) / len(str(num_len + 1)))\n return int(str(amount_of_nums + num_len)[index - amount_of_nums * len(str(num_len + 1)) - block_len - 1])", "from math import sqrt, ceil, log10\nimport numpy as np\n\ndef getGreatest(n, d, prefix):\n rows = 9 * 10 ** (d - 1)\n triangle = rows * (d + rows * d) // 2\n l = 0\n r = triangle\n while l < r:\n mid = l + (r - l >> 1)\n triangle = mid * prefix + mid * (d + mid * d) // 2\n prevTriangle = (mid - 1) * prefix + (mid - 1) * (d + (mid - 1) * d) // 2\n nextTriangle = (mid + 1) * prefix + (mid + 1) * (d + (mid + 1) * d) // 2\n if triangle >= n:\n if prevTriangle < n:\n return prevTriangle\n else:\n r = mid - 1\n elif nextTriangle >= n:\n return triangle\n else:\n l = mid\n return l * prefix + l * (d + l * d) // 2\n\ndef findDiff(n, x):\n mult = 1\n temp = x / 10\n while temp >= 1:\n temp /= 10\n mult *= 10\n d = round(log10(mult)) + 1\n prefixes = 0\n for z in range(1, d):\n prefixes += 9 * z * 10 ** (z - 1)\n n -= calcSeq(mult - 1)\n return n - getGreatest(n, d, prefixes)\n\ndef calcSeq(current):\n x = np.int64(current * (current + 1) / 2)\n mult = 10\n temp = np.int64(current)\n while temp > 0:\n temp = current\n temp -= mult - 1\n mult *= 10\n if temp > 0:\n x += np.int64(temp * (temp + 1) / 2)\n return x\n\ndef solve(n):\n maxN = n\n minN = 0\n x = float(0)\n delta = 2\n prev = 0\n current = round(sqrt(2 * n))\n prevRight = True\n while maxN - minN > 1:\n x = calcSeq(current)\n delta = abs(current - prev)\n prev = current\n if x < n and prevRight:\n current += ceil((maxN - current) / 2)\n prevRight = True\n elif x < n:\n minN = current\n current += ceil((maxN - current) / 2)\n prevRight = True\n elif x > n and prevRight == False:\n maxN = current\n current -= round((current - minN) / 2)\n prevRight = False\n elif x > n:\n current -= round((current - minN) / 2)\n prevRight = False\n else:\n maxN = current\n minN = current - 1\n if calcSeq(current) < n:\n current += 1\n prev = current - 1\n element = findDiff(n, prev)\n (nDigits, nines) = (1, 9)\n total = float(nDigits * nines)\n while total < element:\n nDigits += 1\n nines *= 10\n total += nDigits * nines\n total -= nDigits * nines\n element2 = element - total\n start = 10 ** (nDigits - 1)\n number = str(start + ceil(element2 / nDigits) - 1)\n return int(number[(int(element2) - 1) % nDigits])"], "starter_code": "def solve(n):\n", "input_output": {"fn_name": "solve", "inputs": [[1], [2], [3], [100], [2100], [31000], [55], [123456], [123456789], [999999999999999999], [1000000000000000000], [999999999999999993]], "outputs": [[1], [1], [2], [1], [2], [2], [1], [6], [3], [4], [1], [7]]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5e1ab1b9fe268c0033680e5f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "solve", "task_id": "TACO_lite/474", "example": [[[1], [2], [3]], ["1", "1", "2"]]} +{"requirement": "An abundant number or excessive number is a number for which the sum of its proper divisors is greater than the number itself. \n\nThe integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16 (> 12).\n\nDerive function `abundantNumber(num)/abundant_number(num)` which returns `true/True/.true.` if `num` is abundant, `false/False/.false.` if not.", "solutions": ["def abundant_number(num):\n return sum([e for e in range(1, num) if num % e == 0]) > num", "def abundant_number(n):\n return sum((m for m in range(1, n) if n % m == 0)) > n", "def abundant_number(num):\n return sum((i for i in range(1, num // 2 + 1) if not num % i)) > num", "def abundant_number(num):\n sum_divisors = 1\n int_sqrt = int(num ** 0.5)\n for div in range(2, int_sqrt + 1):\n if num % div == 0:\n sum_divisors += div + num // div\n if int_sqrt ** 2 == num:\n sum_divisors -= int_sqrt\n return sum_divisors > num", "def abundant_number(num):\n return sum([x for x in range(1, num) if num % x == 0]) > num", "def abundant_number(n):\n return sum((n // i + i for i in range(2, int(n ** 0.5) + 1) if n % i == 0)) + 1 > n"], "starter_code": "def abundant_number(num):\n", "input_output": {"fn_name": "abundant_number", "inputs": [[12], [18], [37], [120], [77], [118], [5830], [11410], [14771], [11690]], "outputs": [[true], [true], [false], [true], [false], [false], [true], [true], [false], [true]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/56a75b91688b49ad94000015", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "abundant_number", "task_id": "TACO_lite/432", "example": [[], []]} +{"requirement": "Given a non-negative integer N. Check whether the Binary Representation of the number is Palindrome or not. \nNote: No leading 0\u2019s are being considered.\nExample 1:\nInput:\nN = 5\nOutput: 1\nExplanation: The Binary Representation of\n5 is 101 which is a Palindrome.\n\u00c3\u00a2\u00e2\u0082\u00ac\u00e2\u0080\u00b9Example 2:\nInput: \nN = 10\nOutput: 0\nExplanation: The Binary Representation of\n10 is 1010 which is not a Palindrome.\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function binaryPalin() which takes an integer N as input and returns 1 if the binary representation of N is a palindrome. Else, return 0 .\nExpected Time Complexity: Log(N). \nExpected Auxiliary Space: O(1).\nConstraints:\n0<=N<=2^{63}-1", "solutions": ["def binarypalin(N):\n b = str(bin(N).replace('0b', ''))\n if b == b[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n s = '{0:b}'.format(N)\n if s == s[::-1]:\n return 1\n else:\n return 0", "def binarypalin(n):\n b = bin(n)[2:]\n if b == b[::-1]:\n return 1\n return 0", "def binarypalin(N):\n a = bin(N).replace('0b', '')\n if a[::-1] == a:\n return 1\n return 0", "def binarypalin(N):\n ans = 0\n ans2 = 0\n i = 0\n while N != 0:\n bit = N & 1\n ans = bit * 10 ** i + ans\n ans2 = ans2 * 10 + bit\n i += 1\n N = N >> 1\n if ans == ans2:\n return 1\n else:\n return 0", "def binarypalin(N):\n s = bin(N)[2:]\n if s == s[::-1]:\n return 1\n return 0", "def palin(num):\n check = num[::-1]\n if num == check:\n return 1\n else:\n return 0\n\ndef binarypalin(N):\n bina = ''\n while N > 0:\n bina += str(N % 2)\n N = int(N / 2)\n return Solution.palin(bina)", "def binarypalin(N):\n s = ''\n temp = N\n while N > 0:\n s += str(N % 2)\n N = N // 2\n if s == s[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n a = bin(N)[2:]\n b = a[::-1]\n if a == b:\n return 1\n else:\n return 0", "def binarypalin(N):\n a = int(bin(N)[2:])\n temp = a\n rev = 0\n while temp:\n rem = temp % 10\n rev = rev * 10 + rem\n temp = temp // 10\n if rev == a:\n return 1\n else:\n return 0", "def binarypalin(N):\n k = bin(N)[2:]\n t = k[::-1]\n if k == t:\n return 1\n else:\n return 0", "def binarypalin(N):\n c = bin(int(N)).replace('0b', '')\n if str(c) == str(c)[::-1]:\n return 1\n return 0", "def binarypalin(N):\n num = bin(N)[2:]\n return int(num == num[::-1])", "def binarypalin(N):\n a = bin(N)\n s = str(a)\n x = ''\n for i in range(len(s) - 1, 1, -1):\n x = x + s[i]\n b = x[::-1]\n if x == b:\n return 1\n return 0", "def binarypalin(N):\n binary_string = str(bin(N).replace('0b', ''))\n if binary_string == binary_string[::-1]:\n return 1\n return 0", "def binarypalin(n):\n s = str(bin(n))[2:]\n if s == s[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n res = bin(N)\n a = str(res)\n ans = res.replace('0b', '')\n p = ans[::-1]\n if ans == p:\n return 1\n else:\n return 0", "def binarypalin(N):\n s = str(bin(N))\n l = s.split('b')\n a = l[1]\n p = a[::-1]\n if a == p:\n return 1\n else:\n return 0", "def binarypalin(N):\n b = list(bin(N))\n l = b[2:]\n if l == l[::-1]:\n return 1\n return 0", "def binarypalin(N):\n ans = bin(N)\n ans1 = ''\n ans = ans[2:]\n ans1 = ans[::-1]\n a = ans == ans1\n if a == True:\n return 1\n return 0", "def binarypalin(N):\n bi = bin(N).replace('0b', '')\n if bi == bi[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N: int) -> int:\n bin_number = self.binary(N)\n if bin_number == bin_number[::-1]:\n return 1\n else:\n return 0\n\ndef binary(n: int) -> str:\n result = []\n while n:\n result.insert(0, str(n % 2))\n n //= 2\n return ''.join(result)", "def binarypalin(N):\n n1 = bin(N).replace('0b', '')\n for i in n1:\n if n1 == n1[::-1]:\n return 1\n break\n else:\n return 0", "def binarypalin(N):\n x = bin(n)\n x = x[2:]\n l = 0\n r = len(x) - 1\n while l < r:\n if x[l] == x[r]:\n l += 1\n r -= 1\n else:\n return 0\n return 1", "def binarypalin(N):\n no = bin(N)[2:]\n if int(no[0]) != 0:\n if no == no[::-1]:\n return 1\n else:\n return 0\n else:\n return 0", "def binarypalin(N):\n b = bin(N)[2:]\n return int(b == b[::-1])", "def binarypalin(N):\n l = []\n while N > 0:\n l.append(N % 2)\n N //= 2\n f = l[::-1]\n if f == l:\n return 1\n else:\n return 0", "def binarypalin(N):\n a = '{0:b}'.format(int(N))\n c = a[::-1]\n if a == c:\n return 1\n else:\n return 0", "def binarypalin(N):\n arr = []\n while N != 0:\n arr.append(N & 1)\n N >>= 1\n length = len(arr)\n iterations = length // 2\n for x in range(iterations):\n if arr[x] != arr[length - x - 1]:\n return 0\n return 1", "def binarypalin(N):\n x = int(bin(N)[2:])\n if str(x) == str(x)[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n l = str(bin(N)[2:])\n h = l[::-1]\n if l == h:\n return 1\n else:\n return 0", "def binarypalin(N):\n binstr = bin(N)[2:]\n binpal = ''.join(list(reversed(binstr)))\n if binpal == binstr:\n return 1\n else:\n return 0", "def binarypalin(N):\n N = str(bin(N)[2:])\n n = len(N)\n for i in range(int(n / 2)):\n if N[i] != N[n - i - 1]:\n return 0\n return 1", "def binarypalin(N):\n binaryN = bin(N).replace('0b', '')\n rev = binaryN[::-1]\n if binaryN == rev:\n return 1\n return 0", "def binarypalin(N):\n x = bin(N)\n y = x[::-1]\n if x[2:] == y[:-2]:\n return 1\n else:\n return 0", "def binarypalin(N):\n binary = bin(N)[2:]\n rbin = binary[::-1]\n if binary == rbin:\n return 1\n else:\n return 0", "def binary(num):\n binary = ''\n while num != 0:\n rem = num % 2\n binary = str(rem) + binary\n num //= 2\n return binary\n\ndef binarypalin(N):\n binary = self.binary(N)\n temp = str(int(binary))\n rev = temp[::-1]\n if temp == rev:\n return 1\n return 0", "def binarypalin(n):\n reverseBinary = ''\n while n:\n reverseBinary += str(n & 1)\n n >>= 1\n if reverseBinary == reverseBinary[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n binary = bin(N).replace('0b', '')\n n = len(binary)\n for i in range(n):\n if binary[i] != binary[n - i - 1]:\n return 0\n return 1", "def binarypalin(N):\n st = bin(N)[2:]\n if st == st[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n a = bin(N)\n b = a.replace('0b', '')\n c = str(b)\n d = c[::-1]\n if b == d:\n return 1\n else:\n return 0", "def binarypalin(N):\n bin = ''\n while N != 0:\n bin = str(N % 2) + bin\n N = N // 2\n i = 0\n j = len(bin) - 1\n while i <= len(bin) - 1 or j > i:\n if i == j or i > j:\n return 1\n elif bin[i] != bin[j]:\n return 0\n i = i + 1\n j = j - 1", "def binarypalin(N):\n s = bin(N)[2:]\n m = str(s)\n if m == m[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n N = bin(N)\n N_final = N[2:len(N)]\n N_final_rev = ''\n for i in range(len(N_final) - 1, -1, -1):\n N_final_rev += N_final[i]\n if N_final == N_final_rev:\n return 1\n else:\n return 0", "def binarypalin(num):\n b = bin(num)[2:]\n if b == b[::-1]:\n return 1\n else:\n return 0", "def binarypalin(N):\n\n def binary(num):\n if int(num) == 1:\n return '1'\n else:\n re = int(num) % 2\n num = int(int(num)) // 2\n return str(re) + binary(num)\n x = binary(N)\n x1 = x[::-1]\n if x1 == x:\n return 1\n else:\n return 0", "def binarypalin(N):\n\n def isPalindrome(x):\n return x == x[::-1]\n binary = bin(N)\n return 1 if isPalindrome(binary[2:]) else 0", "def binarypalin(N):\n a = bin(N)[2:]\n x = str(a)\n ans = x[::-1]\n if x == ans:\n return 1\n else:\n return 0", "def binarypalin(N):\n o = str(bin(N)[2:])\n p = o[::-1]\n if p == o:\n return 1\n else:\n return 0", "def binarypalin(N):\n n = bin(N)\n n = list(n)\n n = n[2:]\n k = n[::-1]\n if k == n:\n return 1\n return 0", "def binarypalin(N):\n a = bin(N)\n x = a[a.index('b') + 1:]\n if x == x[::-1]:\n return 1\n else:\n return 0"], "starter_code": "def binarypalin (N):\n", "input_output": {"inputs": ["N = 5", "N = 10"], "outputs": ["1", "0"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings", "Binary Representation", "palindrome"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/check-if-actual-binary-representation-of-a-number-is-palindrome0624/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "Log(N).", "entry_point": "binarypalin", "task_id": "TACO_lite/483", "example": [[[5], [10]], ["1", "0"]]} +{"requirement": "As the title suggests, this is the hard-core version of another neat kata.\n\nThe task is simple to explain: simply sum all the numbers from the first parameter being the beginning to the second parameter being the upper limit (possibly included), going in steps expressed by the third parameter:\n\n```python\nsequence_sum(2, 2, 2) # 2\nsequence_sum(2, 6, 2) # 12 (= 2 + 4 + 6)\nsequence_sum(1, 5, 1) # (= 1 + 2 + 3 + 4 + 5)\nsequence_sum(1, 5, 3) # 5 (= 1 + 4)\n```\n\nIf it is an impossible sequence (with the beginning being larger the end and a positive step or the other way around), just return `0`. See the provided test cases for further examples :)\n\n**Note:** differing from the other base kata, much larger ranges are going to be tested, so you should hope to get your algo optimized and to avoid brute-forcing your way through the solution.", "solutions": ["def sequence_sum(a, b, step):\n n = (b - a) // step\n return 0 if n < 0 else (n + 1) * (n * step + a + a) // 2", "def sequence_sum(b, e, s):\n (q, r) = divmod(e - b, s)\n return (b + e - r) * max(q + 1, 0) // 2", "def sequence_sum(start, stop, step):\n n = (stop - start) // step\n last = start + n * step\n return (n + 1) * (start + last) // 2 if n >= 0 else 0", "def sequence_sum(b, e, s):\n if s > 0 and b > e or (s < 0 and b < e):\n return 0\n near = e - (e - b) % s\n n = (near - b) // s + 1\n return (b + near) * n // 2", "def sequence_sum(b, e, s):\n if b > e and s > 0 or (b < e and s < 0):\n return 0\n k = (e - b) // s\n return b * (k + 1) + s * (k * (k + 1)) // 2", "def sequence_sum(begin, end, step):\n n = int((end - begin + step) / step)\n an = begin + (n - 1) * step\n if step > 0:\n if begin > end:\n return 0\n if step < 0:\n if begin < end:\n return 0\n if n % 2 == 0:\n res = int(int(n / 2) * (begin + an))\n if (begin + an) % 2 == 0:\n res = int(int((begin + an) / 2) * n)\n return res", "from decimal import Decimal\n\ndef sequence_sum(s, e, step):\n if s > e and step > 0 or (s < e and step < 0):\n return 0\n elems = abs(s - e) // abs(step) + 1\n last = s + step * (elems - 1)\n avg = (s + last) / 2\n return int(Decimal(elems) * Decimal(avg))", "def sequence_sum(a, b, s):\n n = (b - a) // s\n return 0 if n < 0 else (n + 1) * (2 * a + s * n) // 2"], "starter_code": "def sequence_sum(b, e, s):\n", "input_output": {"fn_name": "sequence_sum", "inputs": [[2, 6, 2], [1, 5, 1], [1, 5, 3], [-1, -5, -3], [16, 15, 3], [-24, -2, 22], [-2, 4, 658], [780, 6851543, 5], [9383, 71418, 2], [20, 673388797, 5]], "outputs": [[12], [15], [5], [-5], [0], [-26], [-2], [4694363402480], [1253127200], [45345247259849570]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/587a88a208236efe8500008b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "sequence_sum", "task_id": "TACO_lite/471", "example": [[[2, 2, 2], [2, 6, 2], [1, 5, 1], [1, 5, 3]], ["2", "12", "15", "5"]]} +{"requirement": "Given two linked lists, your task is to complete the function makeUnion(), that returns the union list of two linked lists. This union list should include all the distinct elements only and it should be sorted in ascending order.\nExample 1:\nInput:\nL1 = 9->6->4->2->3->8\nL2 = 1->2->8->6->2\nOutput: \n1 2 3 4 6 8 9\nExplaination: \nAll the distinct numbers from two lists, when sorted forms the list in the output. \nExample 2:\nInput:\nL1 = 1->5->1->2->2->5\nL2 = 4->5->6->7->1\nOutput: \n1 2 4 5 6 7\nExplaination: \nAll the distinct numbers from two lists, when sorted forms the list in the output.\nYour Task:\nThe task is to complete the function makeUnion() which makes the union of the given two lists and returns the head of the new list.\nExpected Time Complexity: O((N+M)*Log(N+M))\nExpected Auxiliary Space: O(N+M)\nConstraints:\n1<=N,M<=10^{4}", "solutions": ["def union(head1, head2):\n d = {}\n while head1 != None:\n if head1.data not in d:\n d[head1.data] = head1.data\n head1 = head1.next\n while head2 != None:\n if head2.data not in d:\n d[head2.data] = head2.data\n head2 = head2.next\n head = linkedList()\n for (key, val) in sorted(d.items()):\n head.insert(key)\n return head.head", "def union(head1, head2):\n s1 = set()\n s2 = set()\n cur = head1\n prev = head2\n while cur:\n s1.add(cur.data)\n cur = cur.next\n while prev:\n s2.add(prev.data)\n prev = prev.next\n res = sorted(s1.union(s2))\n n = Node(0)\n h = n\n for i in res:\n k = Node(i)\n n.next = k\n n = n.next\n return h.next", "def union(head1, head2):\n s = set()\n curr_node = head1\n while curr_node:\n s.add(curr_node.data)\n curr_node = curr_node.next\n curr_node = head2\n while curr_node:\n s.add(curr_node.data)\n curr_node = curr_node.next\n lst3 = list(s)\n lst3.sort()\n L1 = linkedList()\n curr_node = L1.head\n for item in lst3:\n new_node = Node(item)\n if curr_node:\n curr_node.next = new_node\n curr_node = curr_node.next\n else:\n L1.head = new_node\n curr_node = L1.head\n return L1.head", "def union(head1, head2):\n lst1 = []\n lst2 = []\n curr_node = head1\n while curr_node:\n lst1.append(curr_node.data)\n curr_node = curr_node.next\n curr_node = head2\n while curr_node:\n lst2.append(curr_node.data)\n curr_node = curr_node.next\n lst3 = list(set(lst1 + lst2))\n lst3.sort()\n L1 = linkedList()\n curr_node = L1.head\n for item in lst3:\n new_node = Node(item)\n if curr_node:\n curr_node.next = new_node\n curr_node = curr_node.next\n else:\n L1.head = new_node\n curr_node = L1.head\n return L1.head", "def union(head1, head2):\n n1 = head1\n s1 = set()\n while n1 is not None:\n s1.add(n1.data)\n n1 = n1.next\n n2 = head2\n s2 = set()\n while n2 is not None:\n s2.add(n2.data)\n n2 = n2.next\n a = list(s1 | s2)\n a.sort()\n new = Node(0)\n n = new\n while a:\n new_node = Node(a.pop(0))\n n.next = new_node\n n = n.next\n return new.next", "def union(head1, head2):\n h1 = []\n t1 = head1\n while t1:\n h1.append(t1.data)\n t1 = t1.next\n h2 = []\n t2 = head2\n while t2:\n h2.append(t2.data)\n t2 = t2.next\n res = sorted(list(set(h1 + h2)))\n llr = linkedList()\n for x in res:\n llr.insert(x)\n return llr.head", "def union(head1, head2):\n ans = list()\n while head1 or head2:\n if head1 == None:\n ans.append(head2.data)\n head2 = head2.next\n elif head2 == None:\n ans.append(head1.data)\n head1 = head1.next\n else:\n ans.append(head1.data)\n ans.append(head2.data)\n (head1, head2) = (head1.next, head2.next)\n ans.sort()\n node = Node(-1)\n head = node\n for x in range(len(ans)):\n if node.data == ans[x]:\n continue\n temp = Node(ans[x])\n node.next = temp\n node = node.next\n return head.next", "def union(head1, head2):\n p = []\n a = head1\n while a is not None:\n if a.data not in p:\n p.append(a.data)\n a = a.next\n b = head2\n while b is not None:\n if b.data not in p:\n p.append(b.data)\n b = b.next\n head3 = None\n c = None\n for i in sorted(p):\n m = Node(i)\n if head3 is None:\n head3 = m\n c = head3\n else:\n head3.next = m\n head3 = head3.next\n return c", "def union(head1, head2):\n l = []\n ll = []\n n = head1\n nn = head2\n while n:\n l.append(n.data)\n n = n.next\n while nn:\n ll.append(nn.data)\n nn = nn.next\n l += ll\n s = set(l)\n ss = list(s)\n ss.sort()\n ls = linkedList()\n for i in ss:\n ls.insert(i)\n return ls.head", "def union(head1, head2):\n p = head1\n s = []\n while p:\n s.append(p.data)\n p = p.next\n p = head2\n while p:\n s.append(p.data)\n p = p.next\n x = list(set(s))\n x.sort()\n ll = linkedList()\n for i in x:\n ll.insert(i)\n return ll.head", "def union(head1, head2):\n li = []\n temp = head1\n while temp:\n li.append(temp.data)\n temp = temp.next\n temp1 = head2\n while temp1:\n li.append(temp1.data)\n temp1 = temp1.next\n li = list(set(li))\n li.sort()\n p = Node(0)\n temp = p\n while li:\n temp.next = Node(li.pop(0))\n temp = temp.next\n return p.next", "def union(head1, head2):\n s = set()\n while head1:\n s.add(head1.data)\n head1 = head1.next\n while head2:\n s.add(head2.data)\n head2 = head2.next\n l = list(s)\n l.sort()\n res = linkedList()\n for x in l:\n res.insert(x)\n return res.head", "def union(head1, head2):\n rec = set()\n while head1:\n rec.add(head1.data)\n head1 = head1.next\n while head2:\n rec.add(head2.data)\n head2 = head2.next\n lst = list(rec)\n lst.sort()\n res = linkedList()\n for x in lst:\n res.insert(x)\n return res.head", "def union(head1, head2):\n d = {}\n while head1.next != None:\n d[head1.data] = 1\n head1 = head1.next\n d[head1.data] = 1\n while head2.next != None:\n d[head2.data] = 1\n head2 = head2.next\n d[head2.data] = 1\n l = list(d.keys())\n l.sort()\n w = 0\n a = []\n for j in l:\n if w == 0:\n p = Node(j)\n a.append(p)\n w += 1\n else:\n p.next = Node(j)\n p = p.next\n return a[0]", "def union(head1, head2):\n list = []\n head = linkedList()\n while head1 != None or head2 != None:\n if head1 != None or head2 == None:\n list.append(head1.data)\n head1 = head1.next\n elif head1 == None or head2 != None:\n list.append(head2.data)\n head2 = head2.next\n list.sort()\n list.append(90)\n ref = []\n i = 0\n while i < len(list) - 1:\n if list[i] != list[i + 1]:\n ref.append(list[i])\n i += 1\n for i in ref:\n head.insert(i)\n return head.head", "def union(head1, head2):\n kmap = set()\n ptr = head1\n while ptr:\n kmap.add(ptr.data)\n ptr = ptr.next\n ptr = head2\n while ptr:\n kmap.add(ptr.data)\n ptr = ptr.next\n arr = list(kmap)\n arr.sort()\n dum = Node(-1)\n ptr = dum\n for ele in arr:\n nn = Node(ele)\n ptr.next = nn\n ptr = ptr.next\n return dum.next", "def union(head1, head2):\n current_1 = head1\n current_2 = head2\n temp_list_1 = []\n temp_list_2 = []\n third_linked_list = linkedList()\n while current_1:\n temp_list_1.append(current_1.data)\n current_1 = current_1.next\n while current_2:\n temp_list_2.append(current_2.data)\n current_2 = current_2.next\n temp_list = set(temp_list_1) | set(temp_list_2)\n temp_list = sorted(temp_list)\n for elements in temp_list:\n third_linked_list.insert(elements)\n return third_linked_list.head", "def union(head1, head2):\n if head1 == None and head2 == None:\n return None\n if head1 == None:\n return head2\n if head2 == None:\n return head1\n temp1 = head1\n temp2 = head2\n l = []\n while temp1 != None and temp2 != None:\n if temp1.data not in l:\n l.append(temp1.data)\n if temp2.data not in l:\n l.append(temp2.data)\n temp1 = temp1.next\n temp2 = temp2.next\n while temp1 != None:\n if temp1.data not in l:\n l.append(temp1.data)\n temp1 = temp1.next\n while temp2 != None:\n if temp2.data not in l:\n l.append(temp2.data)\n temp2 = temp2.next\n newHead = None\n l.sort()\n for i in l:\n dummy = Node(i)\n if newHead == None:\n newHead = dummy\n else:\n temp = newHead\n while temp.next != None:\n temp = temp.next\n temp.next = dummy\n return newHead", "def union(head1, head2):\n newlist = []\n while head1:\n newlist.append(head1.data)\n head1 = head1.next\n while head2:\n newlist.append(head2.data)\n head2 = head2.next\n sortedlist = sorted(list(set(newlist)))\n dummy = Node(0)\n curr = dummy\n for element in sortedlist:\n newNode = Node(element)\n curr.next = newNode\n curr = curr.next\n return dummy.next", "def union(head1, head2):\n llist = []\n p1 = head1\n p2 = head2\n s = set()\n while p1:\n s.add(p1.data)\n p1 = p1.next\n while p2:\n if p2.data not in s:\n s.add(p2.data)\n p2 = p2.next\n for e in s:\n llist.append(e)\n llist.sort()\n dummy = Node(0)\n curr = dummy\n for ele in llist:\n newnode = Node(ele)\n curr.next = newnode\n curr = curr.next\n return dummy.next", "def union(head1, head2):\n union = set()\n stack1 = [head1]\n stack2 = [head2]\n while len(stack1) > 0:\n current1 = stack1.pop()\n union.add(current1.data)\n if current1.next:\n stack1.append(current1.next)\n while len(stack2) > 0:\n current2 = stack2.pop()\n union.add(current2.data)\n if current2.next:\n stack2.append(current2.next)\n union = sorted(union)\n uList = []\n for item in union:\n uList.append(item)\n head = Node(uList[0])\n lastNode = head\n for i in range(1, len(uList)):\n node = Node(uList[i])\n lastNode.next = node\n lastNode = node\n lastNode.next = None\n return head", "def union(head1, head2):\n s = set()\n while head1 or head2:\n if head1:\n if head1 not in s:\n s.add(head1.data)\n head1 = head1.next\n if head2:\n if head2 not in s:\n s.add(head2.data)\n head2 = head2.next\n a = b = Node(0)\n for i in sorted(s):\n a.next = Node(i)\n a = a.next\n return b.next", "def union(head1, head2):\n a = []\n while head1:\n a.append(head1.data)\n head1 = head1.next\n while head2:\n a.append(head2.data)\n head2 = head2.next\n s = sorted(list(set(a)))\n d = Node(-1)\n p = d\n i = 0\n while i < len(s):\n d.next = Node(s[i])\n d = d.next\n i = i + 1\n return p.next", "def union(head1, head2):\n x = set()\n temp = head1\n while temp is not None:\n x.add(temp.data)\n temp = temp.next\n temp = head2\n while temp is not None:\n x.add(temp.data)\n temp = temp.next\n ans = list(x)\n ans = sorted(ans)\n i = 1\n head = Node(ans[0])\n temp = head\n while i < len(ans):\n x = Node(ans[i])\n temp.next = x\n temp = x\n i += 1\n return head", "def union(head1, head2):\n itr1 = head1\n itr2 = head2\n l = []\n while itr1:\n l.append(itr1.data)\n itr1 = itr1.next\n while itr2:\n l.append(itr2.data)\n itr2 = itr2.next\n l = set(l)\n l = list(l)\n l.sort()\n ll = linkedList()\n for i in l:\n ll.insert(i)\n return ll.head", "def union(head1, head2):\n s = set()\n while head1:\n s.add(head1.data)\n head1 = head1.next\n while head2:\n s.add(head2.data)\n head2 = head2.next\n s = list(s)\n s.sort()\n start = cur = None\n for i in s:\n tmp = Node(i)\n if start == None:\n start = tmp\n cur = start\n else:\n cur.next = tmp\n cur = tmp\n return start", "def union(head1, head2):\n curr = head1\n lis = set()\n while curr:\n lis.add(curr.data)\n curr = curr.next\n curr = head2\n while curr:\n lis.add(curr.data)\n curr = curr.next\n sortedlis = sorted(lis)\n temp = Node('dummy')\n curr = temp\n for i in sortedlis:\n node = Node(i)\n curr.next = node\n curr = curr.next\n return temp.next", "def union(head1, head2):\n l1 = []\n l2 = []\n l3 = []\n c1 = 0\n c2 = 0\n cur1 = Node(head1)\n cur1.data = head1.data\n cur1.next = head1.next\n while cur1 != None:\n l1.append(cur1.data)\n c1 += 1\n cur1 = cur1.next\n cur2 = Node(head2)\n cur2.data = head2.data\n cur2.next = head2.next\n while cur2 != None:\n l2.append(cur2.data)\n c2 += 1\n cur2 = cur2.next\n l4 = l1 + l2\n l4 = set(l4)\n l3 = list(l4)\n l3.sort()\n cur = Node(l3[0])\n cur.next = None\n head3 = Node(0)\n head3 = cur\n i = 1\n while i < len(l3):\n new_node = Node(l3[i])\n cur.next = new_node\n cur = cur.next\n i += 1\n return head3", "def union(head1, head2):\n s = set()\n while head1:\n s.add(head1.data)\n head1 = head1.next\n while head2:\n s.add(head2.data)\n head2 = head2.next\n l = []\n for i in s:\n l.append(i)\n l.sort()\n l.reverse()\n h1 = Node(l[0])\n l.remove(l[0])\n for i in l:\n node = Node(i)\n node.next = h1\n h1 = node\n return h1", "def union(head1, head2):\n s = set()\n curr = head1\n while curr:\n i = curr.data\n if i not in s:\n s.add(i)\n curr = curr.next\n curr = head2\n while curr:\n i = curr.data\n if i not in s:\n s.add(i)\n curr = curr.next\n l = sorted(list(s))\n head = Node(l[0])\n curr = head\n for i in l[1:]:\n curr.next = Node(i)\n curr = curr.next\n return head", "def union(head1, head2):\n temp1 = head1\n op = set()\n while temp1.next:\n temp1 = temp1.next\n temp1.next = head2\n temp1 = head1\n while temp1:\n op.add(temp1.data)\n temp1 = temp1.next\n op = sorted(list(op))\n temp1 = head1\n for i in range(len(op)):\n temp1.data = op[i]\n prev = temp1\n temp1 = temp1.next\n prev.next = None\n return head1", "def union(head1, head2):\n tek = head1\n arr1 = []\n while tek != None:\n arr1.append(tek.data)\n tek = tek.next\n tek = head2\n while tek != None:\n arr1.append(tek.data)\n tek = tek.next\n arr = set(arr1)\n arr1 = list(arr)\n arr1.sort()\n head3 = Node(0)\n tek = head3\n i = 0\n while i < len(arr1):\n tek.next = Node(arr1[i])\n tek = tek.next\n i += 1\n return head3.next", "def union(head1, head2):\n new = set()\n while head2:\n new.add(head2.data)\n head2 = head2.next\n while head1:\n new.add(head1.data)\n head1 = head1.next\n new = list(new)\n new.sort()\n ans = Node(0)\n temp = ans\n for i in range(len(new)):\n curr = Node(new[i])\n temp.next = curr\n temp = curr\n return ans.next", "def union(head1, head2):\n s = set()\n while head2:\n s.add(head2.data)\n head2 = head2.next\n while head1:\n s.add(head1.data)\n head1 = head1.next\n s = list(s)\n s.sort()\n ans = Node(-1)\n temp = ans\n for i in range(len(s)):\n new = Node(s[i])\n temp.next = new\n temp = new\n return ans.next", "def union(head1, head2):\n a = head1\n b = head2\n v = set()\n while a:\n v.add(a.data)\n a = a.next\n while b:\n v.add(b.data)\n b = b.next\n v = sorted(v)\n dummy = Node(0)\n m = dummy\n for i in v:\n m.next = Node(i)\n m = m.next\n return dummy.next", "def union(head1, head2):\n s = set()\n while head1:\n s.add(head1.data)\n head1 = head1.next\n while head2:\n s.add(head2.data)\n head2 = head2.next\n s = list(s)\n s.sort()\n start = None\n for i in s:\n node = Node(i)\n if start == None:\n start = node\n prev = node\n else:\n prev.next = node\n prev = node\n return start", "def union(head1, head2):\n (temp1, temp2) = (head1, head2)\n (l1, l2) = ([], [])\n while temp1:\n l1.append(temp1.data)\n temp1 = temp1.next\n while temp2:\n l2.append(temp2.data)\n temp2 = temp2.next\n res = []\n for i in l1:\n if i not in res:\n res.append(i)\n for i in l2:\n if i not in res:\n res.append(i)\n res.sort()\n ll = linkedList()\n for i in res:\n ll.insert(i)\n return ll.head", "def union(head1, head2):\n c = {}\n temp1 = head1\n temp2 = head2\n while temp1 != None or temp2 != None:\n if temp1 != None:\n c[temp1.data] = 1\n temp1 = temp1.next\n if temp2 != None:\n c[temp2.data] = 1\n temp2 = temp2.next\n l = linkedList()\n x = sorted(c.keys())\n for i in x:\n l.insert(i)\n return l.head", "def union(head1, head2):\n res = {}\n cur = head1\n while cur:\n res[cur.data] = 1\n cur = cur.next\n cur = head2\n while cur:\n res[cur.data] = 1\n cur = cur.next\n r1 = linkedList()\n l1 = sorted(res.keys())\n for item in l1:\n r1.insert(item)\n return r1.head", "import heapq\n\ndef union(head1, head2):\n h = []\n s = set()\n n = head1\n while n:\n s.add(n.data)\n n = n.next\n n = head2\n while n:\n s.add(n.data)\n n = n.next\n for i in s:\n h.append(i)\n h.sort()\n N = None\n head = None\n for i in h:\n n = Node(i)\n if not head:\n head = n\n N = n\n else:\n N.next = n\n N = n\n return head", "def union(head1, head2):\n s = {head1.data}\n tmp = head1.next\n while tmp != None:\n s.add(tmp.data)\n tmp = tmp.next\n tmp = head2\n while tmp != None:\n s.add(tmp.data)\n tmp = tmp.next\n tmp = head1\n x = 0\n for i in sorted(s):\n tmp.data = i\n if tmp.next == None and x < len(s) - 1:\n tmp.next = head2\n if x == len(s) - 1:\n tmp.next = None\n return head1\n tmp = tmp.next\n x += 1", "def union(head1, head2):\n ans = Sol()\n l = []\n while head1 is not None:\n l.append(head1.data)\n head1 = head1.next\n while head2 is not None:\n l.append(head2.data)\n head2 = head2.next\n l = sorted(list(set(l)))\n for i in l:\n new = Node(i)\n if ans.head == None:\n ans.head = new\n ans.tail = new\n else:\n ans.tail.next = new\n ans.tail = new\n return ans.head\n\ndef __init__(data):\n self.data = data\n self.next = None\n\ndef __init__():\n self.head = None\n self.tail = None", "def union(head1, head2):\n set_elt = {head1.data}\n (res, h) = (head1, head1)\n while head1.next:\n if head1.data not in set_elt:\n set_elt.add(head1.data)\n h.next = head1\n h = h.next\n head1 = head1.next\n if head1.data not in set_elt:\n set_elt.add(head1.data)\n h.next = head1\n h = head1\n while head2.next:\n if head2.data not in set_elt:\n set_elt.add(head2.data)\n h.next = head2\n h = head2\n head2 = head2.next\n if head2.data not in set_elt:\n set_elt.add(head2.data)\n h.next = head2\n h = head2\n h.next = None\n return sortList(res)\n\ndef sortList(head):\n if not head or not head.next:\n return head\n (l1, l2) = split(head)\n l1 = sortList(l1)\n l2 = sortList(l2)\n return merge(l1, l2)\n\ndef split(l):\n fast = l\n slow = l\n while fast.next and fast.next.next:\n fast = fast.next.next\n slow = slow.next\n temp = slow.next\n slow.next = None\n return (l, temp)\n\ndef merge(l1, l2):\n if not l1:\n return l2\n if not l2:\n return l1\n if l1.data <= l2.data:\n res = l1\n l1 = l1.next\n else:\n res = l2\n l2 = l2.next\n h = res\n while l1 and l2:\n if l1.data <= l2.data:\n h.next = l1\n l1 = l1.next\n else:\n h.next = l2\n l2 = l2.next\n h = h.next\n if l1:\n h.next = l1\n if l2:\n h.next = l2\n return res", "def union(head1, head2):\n p = head1\n q = head2\n d = set()\n s = set()\n while p != None:\n d.add(p.data)\n p = p.next\n while q:\n s.add(q.data)\n q = q.next\n intersect = d.union(s)\n op = linkedList()\n for e in sorted(intersect):\n op.insert(e)\n return op.head", "def union(head1, head2):\n (t, tt) = (head1, head2)\n k = []\n while t:\n if t.data not in k:\n k.append(t.data)\n t = t.next\n while tt:\n if tt.data not in k:\n k.append(tt.data)\n tt = tt.next\n k.sort()\n root = Node(k[0])\n i = 1\n r = root\n while i < len(k):\n y = Node(k[i])\n r.next = y\n r = r.next\n i += 1\n return root", "def union(head1, head2):\n l = []\n while head1:\n l.append(head1.data)\n head1 = head1.next\n while head2:\n l.append(head2.data)\n head2 = head2.next\n l = list(set(l))\n l.sort()\n a = Node(-1)\n t = a\n for i in l:\n t.next = Node(i)\n t = t.next\n return a.next", "def union(head1, head2):\n l = set()\n while head1 or head2:\n if head1:\n l.add(head1.data)\n head1 = head1.next\n if head2:\n l.add(head2.data)\n head2 = head2.next\n l = sorted(l)\n temp = Node(l[0])\n curr = temp\n i = 1\n while i < len(l):\n temp.next = Node(l[i])\n temp = temp.next\n i += 1\n return curr", "def union(head1, head2):\n p1 = head1\n p2 = head2\n myList = [p1.data, p2.data]\n while p1.next:\n myList.append(p1.next.data)\n p1 = p1.next\n while p2.next:\n myList.append(p2.next.data)\n p2 = p2.next\n myList = sorted(list(set(myList)))\n head3 = Node(myList[0])\n p3 = head3\n for i in range(1, len(myList)):\n p3.next = Node(myList[i])\n p3 = p3.next\n return head3", "def union(head1, head2):\n a = []\n b = head1\n h = head2\n while b:\n a.append(b.data)\n b = b.next\n while h:\n a.append(h.data)\n h = h.next\n r = [i for i in set(a)]\n r.sort()\n t = y = Node(r[0])\n for i in range(1, len(r)):\n t.next = Node(r[i])\n t = t.next\n return y", "def union(head1, head2):\n a = []\n tmp = head1\n while tmp:\n a.append(tmp.data)\n tmp = tmp.next\n tmp2 = head2\n while tmp2:\n a.append(tmp2.data)\n tmp2 = tmp2.next\n a.sort()\n a = set(a)\n h = None\n hh = None\n for i in sorted(a):\n if not h:\n h = Node(i)\n hh = h\n else:\n h.next = Node(i)\n h = h.next\n return hh", "def union(head1, head2):\n setti = set()\n while head1:\n setti.add(head1.data)\n head1 = head1.next\n while head2:\n setti.add(head2.data)\n head2 = head2.next\n head = Node(0)\n start = head\n for item in sorted(setti):\n head.next = Node(item)\n head = head.next\n return start.next", "def union(head1, head2):\n s = set()\n p = head1\n while p != None:\n if p.data not in s:\n s.add(p.data)\n p = p.next\n p = head2\n while p != None:\n if p.data not in s:\n s.add(p.data)\n p = p.next\n l = list(s)\n l.sort()\n head = None\n for i in l:\n temp = Node(i)\n if head == None:\n head = temp\n p = head\n else:\n p.next = temp\n p = temp\n return head", "def union(head1, head2):\n us = set()\n us2 = set()\n ptr = head1\n ptr2 = head2\n while ptr is not None:\n us.add(ptr.data)\n ptr = ptr.next\n while ptr2 is not None:\n us2.add(ptr2.data)\n ptr2 = ptr2.next\n l = us.union(us2)\n l = list(l)\n l.sort()\n head3 = None\n for i in range(len(l)):\n if i == 0:\n head3 = Node(l[i])\n ptr = head3\n else:\n extra = Node(l[i])\n ptr.next = extra\n ptr = extra\n return head3", "def union(head1, head2):\n l = set()\n if head1:\n temp1 = head1\n while temp1:\n l.add(temp1.data)\n temp1 = temp1.next\n if head2:\n temp2 = head2\n while temp2:\n l.add(temp2.data)\n temp2 = temp2.next\n s = list(l)\n s.sort()\n head = None\n tail = None\n while s:\n a = s.pop(0)\n n = Node(a)\n if head == None:\n head = n\n tail = n\n else:\n tail.next = n\n tail = tail.next\n return head", "def length(head):\n itr = head\n a = []\n while itr:\n a.append(itr.data)\n itr = itr.next\n return a\n\ndef join_linked_list(h1, h2):\n if h1 == None and h2 == None:\n return None\n if h1 == None:\n return h2\n if h2 == None:\n return h1\n temp = None\n if h1.data < h2.data:\n temp = h1\n temp.next = union(h1.next, h2)\n elif h2.data < h1.data:\n temp = h2\n temp.next = union(h1, h2.next)\n elif h1.data == h2.data:\n temp = h1\n temp.next = union(h1.next, h2.next)\n return temp\n\ndef sorting_linked_list(head):\n a = []\n itr = head\n while itr:\n a.append(itr.data)\n itr = itr.next\n a = list(set(a))\n a.sort()\n return list_to_linked_list(a)\n\ndef list_to_linked_list(a):\n n = len(a)\n head = None\n for i in range(n - 1, -1, -1):\n new = Node(a[i])\n new.next = head\n head = new\n return head\n\ndef union(h1, h2):\n h1 = sorting_linked_list(h1)\n h2 = sorting_linked_list(h2)\n return join_linked_list(h1, h2)\n return h2", "def union(head1, head2):\n\n def data(head):\n temp = head\n d = list()\n while temp:\n d.append(temp.data)\n temp = temp.next\n return d\n d1 = data(head1)\n d2 = data(head2)\n d = list(set(d1 + d2))\n d.sort()\n head = Node(0)\n curr = head\n for i in d:\n curr.next = Node(i)\n curr = curr.next\n return head.next", "def union(head1, head2):\n arr = set()\n cur1 = head1\n cur2 = head2\n while cur1:\n arr.add(cur1.data)\n cur1 = cur1.next\n while cur2:\n arr.add(cur2.data)\n cur2 = cur2.next\n arr = list(arr)\n arr.sort()\n head = Node(0)\n cur = head\n for i in range(len(arr)):\n cur.next = Node(arr[i])\n cur = cur.next\n return head.next"], "starter_code": "def union(head1,head2):\n", "input_output": {"inputs": ["L1 = 9->6->4->2->3->8\nL2 = 1->2->8->6->2", "L1 = 1->5->1->2->2->5\nL2 = 4->5->6->7->1"], "outputs": ["1 2 3 4 6 8 9", "1 2 4 5 6 7"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Hash", "Sorting", "Linked List", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Sorting", "Data structures"], "skill_types": ["Sorting", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/union-of-two-linked-list/1", "Expected Auxiliary Space": "O(N+M)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O((N+M)*Log(N+M))", "entry_point": "union", "task_id": "TACO_lite/459", "example": [[], []]} +{"requirement": "- Kids drink toddy.\n- Teens drink coke.\n- Young adults drink beer.\n- Adults drink whisky.\n\nMake a function that receive age, and return what they drink.\n\n**Rules:**\n\n- Children under 14 old.\n- Teens under 18 old.\n- Young under 21 old.\n- Adults have 21 or more.\n\n**Examples:**\n\n```python\npeople_with_age_drink(13) == \"drink toddy\"\npeople_with_age_drink(17) == \"drink coke\"\npeople_with_age_drink(18) == \"drink beer\"\npeople_with_age_drink(20) == \"drink beer\"\npeople_with_age_drink(30) == \"drink whisky\"\n```", "solutions": ["def people_with_age_drink(age):\n if age > 20:\n return 'drink whisky'\n if age > 17:\n return 'drink beer'\n if age > 13:\n return 'drink coke'\n return 'drink toddy'", "def people_with_age_drink(age):\n if age <= 13:\n beverage = 'toddy'\n elif age > 13 and age <= 17:\n beverage = 'coke'\n elif age > 17 and age <= 20:\n beverage = 'beer'\n elif age > 20:\n beverage = 'whisky'\n return 'drink ' + beverage", "def people_with_age_drink(age):\n return 'drink ' + ('toddy' if age < 14 else 'coke' if age < 18 else 'beer' if age < 21 else 'whisky')", "def people_with_age_drink(age):\n for a in [[21, 'whisky'], [18, 'beer'], [14, 'coke'], [0, 'toddy']]:\n if age >= a[0]:\n return 'drink {0}'.format(a[1])", "people_with_age_drink = lambda a, d=['toddy', 'coke', 'beer', 'whisky']: 'drink ' + d[(a > 13) + (a > 17) + (a > 20)]", "def people_with_age_drink(age):\n dic = {tuple(range(0, 14)): 'drink toddy', tuple(range(14, 18)): 'drink coke', tuple(range(18, 21)): 'drink beer'}\n return dic.get(max((i if age in i else (0, 0) for i in dic)), 'drink whisky')", "def people_with_age_drink(age):\n return 'drink toddy' * (age < 14) or 'drink coke' * (age < 18) or 'drink beer' * (age < 21) or 'drink whisky'", "def people_with_age_drink(age):\n drinks = {1: 'drink toddy', 2: 'drink coke', 3: 'drink beer', 4: 'drink whisky'}\n return drinks[1] if age < 14 else drinks[2] if age < 18 else drinks[3] if age < 21 else drinks[4]", "def people_with_age_drink(age):\n drinks = {age < 14: 'toddy', 14 <= age < 18: 'coke', 18 <= age < 21: 'beer', age >= 21: 'whisky'}\n return 'drink {}'.format(drinks[True])", "def people_with_age_drink(age):\n return 'drink %s' % ('toddy' if age < 14 else 'coke' if 13 < age < 18 else 'beer' if 17 < age < 21 else 'whisky')", "drinks = [('whisky', 21), ('beer', 18), ('coke', 14)]\n\ndef people_with_age_drink(age):\n return 'drink ' + next((drink for (drink, age_limit) in drinks if age >= age_limit), 'toddy')", "def people_with_age_drink(age):\n return 'drink ' + next((d for (a, d) in [(21, 'whisky'), (18, 'beer'), (14, 'coke'), (0, 'toddy')] if age >= a))", "def people_with_age_drink(age):\n if age < 14:\n return 'drink toddy'\n elif age >= 14 and age < 18:\n return 'drink coke'\n elif age >= 18 and age < 21:\n return 'drink beer'\n else:\n return 'drink whisky'\n return 'ERROR....WRONG INPUT'", "people_with_age_drink = lambda n: 'drink %s' % ('toddy' if n < 14 else 'coke' if n < 18 else 'beer' if n < 21 else 'whisky')", "def people_with_age_drink(age: int) -> str:\n return f\"drink {('toddy' if age < 14 else 'coke' if age < 18 else 'beer' if age < 21 else 'whisky')}\"", "def people_with_age_drink(age):\n for (lim, drink) in [(14, 'toddy'), (18, 'coke'), (21, 'beer'), (float('inf'), 'whisky')]:\n if age < lim:\n return 'drink ' + drink", "def people_with_age_drink(age):\n return ['drink toddy', 'drink coke', 'drink beer', 'drink whisky'][(age >= 21) + (age > 17) + (age > 13)]", "from bisect import bisect\n\ndef people_with_age_drink(age):\n r = {0: 'drink toddy', 1: 'drink coke', 2: 'drink beer', 3: 'drink whisky'}\n return r[bisect([14, 18, 21], age)]", "people_with_age_drink = lambda a: 'drink ' + ('toddy' if a < 14 else 'coke' if a < 18 else 'beer' if a < 21 else 'whisky')", "def people_with_age_drink(age):\n return 'drink ' + ('toddy', 'coke', 'beer', 'whisky')[sum((not age < x for x in (14, 18, 21)))]", "def people_with_age_drink(age):\n for (limit, drink) in [(14, 'toddy'), (18, 'coke'), (21, 'beer')]:\n if age < limit:\n return 'drink ' + drink\n return 'drink whisky'", "def people_with_age_drink(age):\n drink = ''\n if age < 14:\n drink = 'drink toddy'\n elif age < 18 and age > 13:\n drink = 'drink coke'\n elif age < 21 and age > 17:\n drink = 'drink beer'\n else:\n drink = 'drink whisky'\n return drink", "def people_with_age_drink(age):\n if age < 14:\n return 'drink toddy'\n if age > 13 and age < 18:\n return 'drink coke'\n if age > 17 and age < 21:\n return 'drink beer'\n if age > 20:\n return 'drink whisky'", "def people_with_age_drink(age):\n if age >= 21:\n return 'drink whisky'\n elif age in range(18, 21):\n return 'drink beer'\n elif age in range(14, 18):\n return 'drink coke'\n elif age in range(0, 14):\n return 'drink toddy'", "drink_pairs = {'kid': 'toddy', 'teen': 'coke', 'youngAdult': 'beer', 'adult': 'whisky'}\n\ndef people_with_age_drink(age):\n if age >= 21:\n return 'drink ' + drink_pairs['adult']\n elif age < 21 and age >= 18:\n return 'drink ' + drink_pairs['youngAdult']\n elif age < 18 and age >= 14:\n return 'drink ' + drink_pairs['teen']\n else:\n return 'drink ' + drink_pairs['kid']", "def people_with_age_drink(age):\n if age <= 13:\n return 'drink toddy'\n elif age < 18 > 13:\n return 'drink coke'\n elif age < 21 > 17:\n return 'drink beer'\n elif age >= 21:\n return 'drink whisky'\n else:\n pass", "def people_with_age_drink(age):\n res = 'drink {}'\n if age < 14:\n return res.format('toddy')\n elif age < 18:\n return res.format('coke')\n elif age < 21:\n return res.format('beer')\n return res.format('whisky')", "def people_with_age_drink(age):\n if not age > 13:\n return 'drink toddy'\n elif age > 13 and (not age >= 18):\n return 'drink coke'\n elif age >= 18 and (not age > 20):\n return 'drink beer'\n else:\n return 'drink whisky'", "def people_with_age_drink(age):\n if age >= 0 and age < 14:\n return 'drink toddy'\n elif age < 18:\n return 'drink coke'\n elif age < 21:\n return 'drink beer'\n elif age >= 21:\n return 'drink whisky'\n else:\n return 'not a meaningful age'", "def people_with_age_drink(age):\n result = ''\n if age < 14:\n result = 'drink toddy'\n if age >= 14 and age < 18:\n result = 'drink coke'\n if age >= 18 and age <= 21:\n result = 'drink beer'\n if age >= 21:\n result = 'drink whisky'\n return result", "def people_with_age_drink(age):\n (a, b, c) = (14, 18, 21)\n if age < a:\n return 'drink toddy'\n if a <= age < b:\n return 'drink coke'\n if b <= age < c:\n return 'drink beer'\n if age >= c:\n return 'drink whisky'", "def people_with_age_drink(age):\n if age < 14:\n return 'drink toddy'\n if age >= 14 and age <= 17:\n return 'drink coke'\n if age >= 18 and age <= 20:\n return 'drink beer'\n else:\n return 'drink whisky'", "def people_with_age_drink(age):\n drinks = {'Children': 'drink toddy', 'Teens': 'drink coke', 'Young': 'drink beer', 'Adults': 'drink whisky'}\n if age < 14:\n return drinks['Children']\n if age < 18:\n return drinks['Teens']\n if age < 21:\n return drinks['Young']\n if age >= 21:\n return drinks['Adults']", "def people_with_age_drink(age: int) -> str:\n drink_rule = {age < 14: 'toddy', 14 <= age < 18: 'coke', 18 <= age < 21: 'beer', age >= 21: 'whisky'}\n return f'drink {drink_rule[True]}'", "def people_with_age_drink(age):\n drinks = {'toddy': range(14), 'coke': range(14, 18), 'beer': range(18, 21), 'whisky': range(21, 999)}\n for (key, age_range) in drinks.items():\n if age in age_range:\n return f'drink {key}'", "def people_with_age_drink(age):\n kids_age = range(0, 14)\n teens_age = range(14, 18)\n youngadults_age = range(18, 21)\n if age in kids_age:\n return 'drink toddy'\n elif age in teens_age:\n return 'drink coke'\n elif age in youngadults_age:\n return 'drink beer'\n else:\n return 'drink whisky'", "def people_with_age_drink(age):\n s = ''\n if age > 20:\n s = 'whisky'\n if age < 21:\n s = 'beer'\n if age < 18:\n s = 'coke'\n if age < 14:\n s = 'toddy'\n return 'drink ' + s", "def people_with_age_drink(age):\n drinks = {'14': 'drink toddy', '18': 'drink coke', '21': 'drink beer', '100': 'drink whisky'}\n for key in drinks:\n if age < int(key):\n return drinks[key]", "people_with_age_drink = lambda a: f\"drink {a < 14 and 'toddy' or (a < 18 and 'coke') or (a < 21 and 'beer') or 'whisky'}\"", "def people_with_age_drink(age):\n if age <= 13:\n return 'drink toddy'\n elif age <= 17:\n return 'drink coke'\n elif age == 18 or age <= 20:\n return 'drink beer'\n elif age > 20:\n return 'drink whisky'", "def people_with_age_drink(age):\n switcher = {1: 'drink toddy', 2: 'drink coke', 3: 'drink beer', 4: 'drink whisky'}\n if age < 14:\n return switcher.get(1, None)\n elif 14 <= age < 18:\n return switcher.get(2, None)\n elif 18 <= age < 21:\n return switcher.get(3, None)\n elif 21 <= age:\n return switcher.get(4, None)", "def people_with_age_drink(age: int) -> str:\n DRINK_TABLE = ((21, 'whisky'), (18, 'beer'), (14, 'coke'), (0, 'toddy'))\n for (limit, drink) in DRINK_TABLE:\n if age >= limit:\n return f'drink {drink}'\n return 'no drink'", "def people_with_age_drink(age):\n if age < 14:\n return 'drink toddy'\n elif 14 <= age <= 17:\n return 'drink coke'\n elif 17 < age < 21:\n return 'drink beer'\n else:\n return 'drink whisky'", "def people_with_age_drink(age):\n j = True\n if age < 14:\n j = 'drink toddy'\n elif age < 18:\n j = 'drink coke'\n elif age < 21:\n j = 'drink beer'\n elif age >= 21:\n j = 'drink whisky'\n return j", "def people_with_age_drink(age):\n if age < 14:\n return 'drink toddy'\n elif age < 18 and age > 0:\n return 'drink coke'\n elif age < 21 and age > 0:\n return 'drink beer'\n elif age >= 21 and age > 0:\n return 'drink whisky'", "def people_with_age_drink(age):\n if age < 14:\n drink = 'toddy'\n elif 14 <= age <= 17:\n drink = 'coke'\n elif 18 <= age <= 20:\n drink = 'beer'\n else:\n drink = 'whisky'\n return 'drink {}'.format(drink)"], "starter_code": "def people_with_age_drink(age):\n", "input_output": {"fn_name": "people_with_age_drink", "inputs": [[13], [0], [17], [15], [14], [20], [18], [22], [21]], "outputs": [["drink toddy"], ["drink toddy"], ["drink coke"], ["drink coke"], ["drink coke"], ["drink beer"], ["drink beer"], ["drink whisky"], ["drink whisky"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56170e844da7c6f647000063", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "people_with_age_drink", "task_id": "TACO_lite/445", "example": [[], []]} +{"requirement": "Implement a method that accepts 3 integer values a, b, c. The method should return true if a triangle can be built with the sides of given length and false in any other case.\n\n(In this case, all triangles must have surface greater than 0 to be accepted).", "solutions": ["def is_triangle(a, b, c):\n return a < b + c and b < a + c and (c < a + b)", "def is_triangle(a, b, c):\n (a, b, c) = sorted([a, b, c])\n return a + b > c", "def is_triangle(a, b, c):\n if a <= 0 | b <= 0 | c <= 0:\n return False\n elif a + b <= c or a + c <= b or b + c <= a:\n return False\n else:\n return True", "def is_triangle(a, b, c):\n return abs(a - b) < c < a + b", "def is_triangle(a, b, c):\n s = [a, b, c]\n for i in s:\n if sum(s) - i <= i:\n return False\n return True", "def is_triangle(a, b, c):\n return 2 * max(a, b, c) < a + b + c", "def is_triangle(a, b, c):\n if a + b <= c or a + c <= b or b + c <= a:\n return False\n else:\n return True", "def is_triangle(a, b, c):\n return all([a + b > c, a + c > b, b + c > a])", "def is_triangle(a, b, c):\n if a + b + c == 0:\n return False\n if a + b <= c:\n return False\n if a + c <= b:\n return False\n if b + c <= a:\n return False\n return True", "def is_triangle(a, b, c):\n if a <= 0 or b <= 0 or c <= 0:\n return False\n sum = a + b + c\n if fits(sum, max(a, b, c)):\n return True\n return False\n\ndef fits(sum, a):\n return sum - a > a", "is_triangle = lambda _, a, b: sum(sorted([_, a, b])[:2]) > sorted([_, a, b])[2]", "def is_triangle(a, b, c):\n sides = [a, b, c]\n max_side = max(sides)\n if sum(sides) - max_side > max_side:\n return True\n else:\n return False", "def is_triangle(a, b, c):\n s = a + b + c\n if s - max(a, b, c) > max(a, b, c):\n return True\n return False", "def is_triangle(a, b, c):\n cond1 = a + b > c\n cond2 = b + c > a\n cond3 = a + c > b\n list = [cond1, cond2, cond3]\n if False in list:\n return False\n return True", "def is_triangle(x, y, z):\n return x < y + z and y < x + z and (z < x + y)", "def is_triangle(a, b, c):\n t1 = a + b > c\n t2 = a + c > b\n t3 = b + c > a\n return t1 and t2 and t3", "def is_triangle(*sides):\n return sum(sorted(sides)[:2]) > max(sides)", "def is_triangle(a, b, c):\n max_number = max([a, b, c])\n if sum([a, b, c]) - max_number > max_number:\n return True\n return False", "def is_triangle(a, b, c):\n if a > 0 and b > 0 and (c > 0):\n if a + b > c and a + c > b and (c + b > a):\n return True\n else:\n return False\n return False", "def is_triangle(a, b, c):\n llist = [a, b, c]\n llist.sort()\n highest = llist[2]\n sumrest = llist[0] + llist[1]\n if highest < sumrest:\n return True\n return False", "def is_triangle(a, b, c):\n if a + b > c and a + c > b and (b + c > a):\n return True\n return False", "def is_triangle(a, b, c):\n lst = [int(a), int(b), int(c)]\n lst = sorted(lst)\n if lst[0] + lst[1] > lst[2]:\n return True\n else:\n return False", "def is_triangle(a, b, c):\n max_int = max(a, b, c)\n min_int = min(a, b, c)\n if max_int == a:\n sum = b + c\n if sum > a:\n return True\n if max_int == b:\n sum = a + c\n if sum > b:\n return True\n if max_int == c:\n sum = a + b\n if sum > c:\n return True\n return False", "def is_triangle(a, b, c):\n if a == None or b == None or c == None:\n return False\n l_tri = sorted([a, b, c])\n if l_tri[2] >= l_tri[0] + l_tri[1]:\n return False\n return True", "def is_triangle(a, b, c):\n tab_coter = [a, b, c]\n tab_coter.sort()\n calc_long_coter = tab_coter[0] + tab_coter[1]\n if tab_coter[2] < calc_long_coter:\n return True\n return False", "def is_triangle(a, b, c):\n s = sorted([a, b, c])\n return False if s[0] < 1 or sum(s[:-1]) <= s[2] else True", "def is_triangle(a, b, c):\n lts = [a, b, c]\n lts.sort()\n return lts[2] < lts[1] + lts[0]", "def is_triangle(a, b, c):\n triangleList = [a, b, c]\n triangleList.sort()\n if triangleList[0] + triangleList[1] > triangleList[2]:\n return True\n else:\n return False", "def is_triangle(a, b, c):\n out = []\n out.append(a)\n out.append(b)\n out.append(c)\n out.sort()\n if out[2] >= out[0] + out[1]:\n return False\n else:\n return True", "def is_triangle(a, b, c):\n if 2 * max([a, b, c]) < a + b + c:\n return True\n else:\n return False", "def is_triangle(a, b, c):\n return a + b > c and b + c > a and (c + a > b) and (a > 0) and (b > 0) and (c > 0)\n return False", "def is_triangle(a, b, c):\n listOfSides = [a, b, c]\n if max(listOfSides) >= sum(listOfSides) - max(listOfSides):\n return False\n return True", "def is_triangle(a, b, c):\n sum = a + b + c\n for side in (a, b, c):\n if sum - side <= side:\n return False\n return True", "def is_triangle(a, b, c):\n x = max(a, b, c)\n for i in (a, b, c):\n if x == i and x < a + b + c - i:\n return True\n return False", "def is_triangle(a, b, c):\n if a + b > c and abs(a - b) < c:\n return True\n elif a + c > b and abs(a - c) < b:\n return True\n elif b + c > a and abs(b - c) < a:\n return True\n else:\n return False", "def is_triangle(a, b, c):\n if a > 0 and b > 0 and (c > 0):\n reference = sorted([a, b, c])\n if reference[2] < reference[0] + reference[1]:\n return True\n else:\n return False\n else:\n return False", "def is_triangle(a, b, c):\n if any((side <= 0 for side in (a, b, c))):\n return False\n sides = sorted([a, b, c])\n if sides[0] + sides[1] <= sides[2]:\n return False\n return True", "def is_triangle(a, b, c):\n v = [a, b, c]\n m = max(v)\n v.remove(m)\n return m < sum(v)", "def is_triangle(a, b, c):\n my_flag = False\n if a + b > c and c + b > a and (a + c > b):\n my_flag = True\n else:\n my_flag = False\n return my_flag", "def is_triangle(a, b, c):\n result = ''\n if a + b <= c:\n result = False\n elif a + c <= b:\n result = False\n elif b + c <= a:\n result = False\n else:\n result = True\n return result", "import math\n\ndef is_triangle(a, b, c):\n sides = (a, b, c)\n if sorted(sides)[-1] >= sorted(sides)[0] + sorted(sides)[1]:\n return False\n return True", "def is_triangle(a, b, c):\n table = [a, b, c]\n table.sort()\n return table[0] + table[1] > table[2]", "def is_triangle(a, b, c):\n if sum([a, b]) > c and sum([b, c]) > a and (sum([a, c]) > b):\n return True\n else:\n return False", "def is_triangle(a, b, c):\n if a == 0 or b == 0 or c == 0:\n return 0\n if a + b <= c or b + c <= a or a + c <= b:\n return 0\n else:\n return 1", "def is_triangle(a, b, c):\n list_ = [a, b, c]\n if sorted(list_)[0] + sorted(list_)[1] > sorted(list_)[2]:\n if sorted(list_)[0] > 0 and sorted(list_)[1] > 0 and (sorted(list_)[2] > 0):\n return True\n return False", "def is_triangle(a, b, c):\n x = a + b\n y = b + c\n z = a + c\n if x > c and y > a and (z > b):\n return True\n else:\n return False", "def is_triangle(a, b, c):\n if (a or b or c) < 0:\n return False\n v = list()\n v.append(a)\n v.append(b)\n v.append(c)\n v.sort()\n _a = v.pop()\n _b = v.pop()\n _c = v.pop()\n if _a < _b + _c:\n return True\n if _a == _b + _c:\n return False\n return False", "def is_triangle(a, b, c):\n x = max(a, b, c)\n lista = [a, b, c]\n lista.remove(x)\n if x < sum(lista):\n return True\n else:\n return False", "def is_triangle(a, b, c):\n k = [a + b > c, a + c > b, b + c > a]\n return not False in k", "def is_triangle(a, b, c):\n sides = [a, b, c]\n a = max(sides)\n sides.remove(a)\n if sum(sides) > a:\n return True\n return False", "def is_triangle(a, b, c):\n result = False\n if a + b > c:\n if a + c > b:\n if c + b > a:\n result = True\n return result", "def is_triangle(a, b, c):\n biggest_arg = max([a, b, c])\n return True if biggest_arg < sum([a, b, c]) - biggest_arg else False", "def is_triangle(a, b, c):\n mylist = [a, b, c]\n mylist = sorted(mylist)\n if mylist[0] < mylist[1] + mylist[2]:\n if mylist[1] < mylist[0] + mylist[2]:\n if mylist[2] < mylist[0] + mylist[1]:\n return True\n return False", "def is_triangle(a, b, c):\n sides = (a, b, c)\n sides = sorted(sides)\n c = sides[-1]\n b = sides[1]\n a = sides[0]\n return c < a + b", "def is_triangle(a, b, c):\n a = sorted([a, b, c])\n return a[2] < a[0] + a[1]"], "starter_code": "def is_triangle(a, b, c):\n", "input_output": {"fn_name": "is_triangle", "inputs": [[1, 2, 2], [7, 2, 2], [1, 2, 3], [1, 3, 2], [3, 1, 2], [5, 1, 2], [1, 2, 5], [2, 5, 1], [4, 2, 3], [5, 1, 5], [2, 2, 2], [-1, 2, 3], [1, -2, 3], [1, 2, -3], [0, 2, 3]], "outputs": [[true], [false], [false], [false], [false], [false], [false], [false], [true], [true], [true], [false], [false], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/56606694ec01347ce800001b", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_triangle", "task_id": "TACO_lite/361", "example": [[], []]} +{"requirement": "```\n*************************\n* Create a frame! *\n* __ __ *\n* / \\~~~/ \\ *\n* ,----( .. ) *\n* / \\__ __/ *\n* /| (\\ |( *\n* ^ \\ /___\\ /\\ | *\n* |__| |__|-.. *\n*************************\n```\n\nGiven an array of strings and a character to be used as border, output the frame with the content inside.\n\nNotes:\n\n* Always keep a space between the input string and the left and right borders.\n* The biggest string inside the array should always fit in the frame.\n* The input array is never empty.\n\n\n## Example\n\n`frame(['Create', 'a', 'frame'], '+')`\n\nOutput:\n```\n++++++++++\n+ Create +\n+ a +\n+ frame +\n++++++++++\n```", "solutions": ["def frame(text, char):\n text_lens = [len(x) for x in text]\n longest_len = max(text_lens)\n frame_list = [char * (longest_len + 4)]\n for str in text:\n frame_list.append('{} {}{} {}'.format(char, str, ' ' * (longest_len - len(str)), char))\n frame_list.append(char * (longest_len + 4))\n return '\\n'.join(frame_list)", "def frame(text, char):\n n = len(max(text, key=len)) + 4\n return '\\n'.join([char * n] + ['%s %s %s' % (char, line.ljust(n - 4), char) for line in text] + [char * n])", "def frame(lines, char):\n l = len(max(lines, key=len))\n row = char * (l + 4)\n body = '\\n'.join((f'{char} {line:<{l}s} {char}' for line in lines))\n return f'{row}\\n{body}\\n{row}'", "def frame(text, char):\n length = len(max(text, key=len))\n start = end = char * (length + 3)\n k = [' ' + x + ' ' * (length - len(x) + 1) for x in text]\n return (char + '\\n' + char).join([start] + k + [end])", "from itertools import chain\n\ndef frame(words, char):\n size = max(map(len, words))\n frame = [char * (size + 4)]\n middle = (f'{char} {word: <{size}} {char}' for word in words)\n return '\\n'.join(chain(frame, middle, frame))", "def frame(t, c):\n m = len(max(t, key=len))\n return c * (m + 4) + '\\n' + '\\n'.join([f'{c} {i:<{m}} {c}' for i in t]) + '\\n' + c * (m + 4)", "def frame(text, char):\n width = max([len(x) for x in text]) + 4\n a = '\\n'.join([char + ' ' + x + ' ' * (width - len(x) - 3) + char for x in text])\n return f'{char * width}\\n{a}\\n{char * width}'", "def frame(text, c):\n mx = max((len(w) for w in text))\n return '\\n'.join([c * (mx + 4)] + [c + ' ' + w.ljust(mx) + ' ' + c for w in text] + [c * (mx + 4)])", "def frame(text, char):\n max_length = max([len(word) for word in text])\n frame_words = [char + ' ' + word + (max_length - len(word) + 1) * ' ' + char for word in text]\n frame = char * (max_length + 4) + '\\n'\n for line in frame_words:\n frame = frame + line + '\\n'\n return frame + char * (max_length + 4)", "def frame(text, char):\n w = max(map(len, text))\n\n def f():\n yield (char * (w + 4))\n for line in text:\n yield f'{char} {line:<{w}} {char}'\n yield (char * (w + 4))\n return '\\n'.join(f())"], "starter_code": "def frame(text, char):\n", "input_output": {"fn_name": "frame", "inputs": [[["Small", "frame"], "~"], [["Create", "this", "kata"], "+"], [["This is a very long single frame"], "-"]], "outputs": [["~~~~~~~~~\n~ Small ~\n~ frame ~\n~~~~~~~~~"], ["++++++++++\n+ Create +\n+ this +\n+ kata +\n++++++++++"], ["------------------------------------\n- This is a very long single frame -\n------------------------------------"]]}, "difficulty": "EASY", "raw_tags": ["ASCII Art", "Strings", "Fundamentals", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5672f4e3404d0609ec00000a", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "frame", "task_id": "TACO_lite/440", "example": [[], []]} +{"requirement": "Given a natural number N, find the count of numbers from 1 to N that have an odd number of divisors. \n \nExample 1:\nInput:\nN = 1\nOutput:\n1\nExplanation:\n1 has only one \ndivisor {1}.\n \nExample 2:\nInput:\nN = 4\nOutput:\n2\nExplanation:\n4 has an odd number \nof divisors {1, 2, 4}.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function oddNumberOfDivisor() which takes an integer N and returns the count of numbers from 1 to n that have an odd number of divisors. \n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 <= N <= 10^{6}", "solutions": ["def oddnumberofdivisor(ob, N):\n return int(N ** (1 / 2))", "def oddnumberofdivisor(ob, n):\n c = 0\n from math import sqrt\n for i in range(1, n + 1):\n s = sqrt(i)\n if s - int(s) == 0:\n c += 1\n return c", "import math\n\ndef oddnumberofdivisor(ob, N):\n count = 0\n for i in range(1, N + 1):\n s = math.sqrt(i)\n if s - int(s) == 0:\n count += 1\n return count", "import math\n\ndef oddnumberofdivisor(ob, N):\n return math.floor(N ** 0.5)", "def oddnumberofdivisor(ob, N):\n return int(N ** 0.5)"], "starter_code": "def oddnumberofdivisor (ob,N):\n", "input_output": {"inputs": ["N = 1", "N = 4"], "outputs": ["1", "2"]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/odd-divisors5347/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "oddnumberofdivisor", "task_id": "TACO_lite/430", "example": [[[1], [4]], [null, null]]} +{"requirement": "Given an array arr[] of size N, check if it can be partitioned into two parts such that the sum of elements in both parts is the same.\nExample 1:\nInput: N = 4\narr = {1, 5, 11, 5}\nOutput: YES\nExplanation: \nThe two parts are {1, 5, 5} and {11}.\nExample 2:\nInput: N = 3\narr = {1, 3, 5}\nOutput: NO\nExplanation: This array can never be \npartitioned into two such parts.\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function equalPartition() which takes the value N and the array as input parameters and returns 1 if the partition is possible. Otherwise, returns 0.\nExpected Time Complexity: O(N*sum of elements)\nExpected Auxiliary Space: O(N*sum of elements)\nConstraints:\n1 \u2264 N \u2264 100\n1 \u2264 arr[i] \u2264 1000\nN*sum of elements \u2264 5*10^{6}", "solutions": ["def equalpartition(N, arr):\n x = sum(arr)\n arr.sort()\n if x % 2 == 1:\n return 0\n else:\n sum1 = x // 2\n table = [[0 for _ in range(sum1 + 1)] for _ in range(N + 1)]\n table[0][0] = 1\n for i in range(1, N + 1):\n table[i][0] = 1\n for i in range(1, N + 1):\n for j in range(1, sum1 + 1):\n if arr[i - 1] > j + 1:\n table[i][j] = table[i - 1][j]\n else:\n table[i][j] = max(table[i - 1][j], table[i - 1][j - arr[i - 1]])\n return table[-1][-1]", "def equalpartition(N, arr):\n su = 0\n for q in range(len(arr)):\n su = su + arr[q]\n if su % 2 != 0:\n return 0\n su = int(su / 2)\n dp = [[-1 for m in range(su + 1)] for n in range(N + 1)]\n for a in range(su + 1):\n dp[0][a] = False\n for b in range(N + 1):\n dp[b][0] = True\n for i in range(1, N + 1):\n for j in range(1, su + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j - arr[i - 1]] or dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[N][su]", "def equalpartition(N, arr):\n if sum(arr) % 2 != 0:\n return False\n dp = set()\n dp.add(0)\n x = sum(arr) // 2\n for i in arr:\n temp = set()\n for j in dp:\n if j + i == x:\n return True\n temp.add(j + i)\n temp.add(j)\n dp = temp\n return False", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2 == 1:\n return 0\n l = s // 2\n dp = [0 for _ in range(l + 1)]\n for num in arr:\n if num > l:\n return 0\n for s in range(l, 0, -1):\n if dp[s] != 0 and s + num <= l:\n dp[s + num] += 1\n dp[num] += 1\n return 1 if dp[-1] >= 2 else 0", "def equalpartition(N, arr):\n total = sum(arr)\n r_total = total // 2\n dp = [[False for i in range(r_total + 1)] for j in range(N + 1)]\n if total % 2 == 1:\n return 0\n else:\n for i in range(N + 1):\n for j in range(r_total + 1):\n if j == 0:\n dp[i][j] = True\n for i in range(1, N + 1):\n for j in range(1, r_total + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]\n else:\n dp[i][j] = dp[i - 1][j]\n if dp[N][r_total] == False:\n return 0\n else:\n return 1", "def equalpartition(N, arr):\n total_sum = 0\n for n in arr:\n total_sum += n\n if total_sum % 2 == 1:\n return False\n else:\n sum = total_sum // 2\n n = N\n t = [[False for i in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n t[i][0] = True\n for i in range(sum + 1):\n t[0][i] = False\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if arr[i - 1] <= j:\n t[i][j] = t[i - 1][j - arr[i - 1]] or t[i - 1][j]\n else:\n t[i][j] = t[i - 1][j]\n return t[n][sum]", "def equalpartition(N, arr):\n total_sum = sum(arr)\n if total_sum % 2 != 0:\n return 0\n tgt = total_sum / 2\n n = len(arr)\n\n def solve(i, tgt):\n if tgt < 0:\n return 0\n if i >= len(arr):\n return 0\n if tgt == 0:\n return 1\n if solve(i + 1, tgt - arr[i]) == 1:\n return 1\n if solve(i + 1, tgt) == 1:\n return 1\n return solve(0, tgt)", "def equalpartition(N, arr):\n nums = arr\n n = len(nums)\n if sum(nums) % 2 != 0:\n return False\n target = sum(nums) // 2\n memo = [[-1 for j in range(target + 1)] for i in range(n)]\n\n def rec(ind, target):\n if target == 0:\n return True\n if target < 0 or ind < 0:\n return False\n if memo[ind][target] != -1:\n return memo[ind][target]\n tk = rec(ind - 1, target - nums[ind])\n notTk = rec(ind - 1, target)\n memo[ind][target] = tk or notTk\n return memo[ind][target]\n g = rec(n - 1, target)\n return 1 if g else 0", "def equalpartition(N, arr):\n total_sum = sum(arr)\n if total_sum % 2 != 0:\n return 0\n target_sum = total_sum // 2\n dp = [[False for _ in range(target_sum + 1)] for _ in range(N + 1)]\n for i in range(N + 1):\n dp[i][0] = True\n for j in range(1, target_sum + 1):\n dp[0][j] = False\n for i in range(1, N + 1):\n for j in range(1, target_sum + 1):\n if arr[i - 1] > j:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]\n return int(dp[N][target_sum])", "def equalpartition(N, arr):\n target = sum(arr)\n if target % 2 != 0:\n return False\n target = target // 2\n dp = [[-1 for i in range(target + 1)] for j in range(N)]\n\n def dfs(i, target):\n if target == 0:\n return True\n if i <= 0 or target < 0:\n return False\n if dp[i - 1][target] != -1:\n return dp[i - 1][target]\n dp[i - 1][target] = dfs(i - 1, target) or dfs(i - 1, target - arr[i - 1])\n return dp[i - 1][target]\n return dfs(N, target)", "def equalpartition(N, arr):\n s = sum(arr)\n if s & 1:\n return False\n s = s >> 1\n dp = [[False for i in range(s + 1)] for j in range(N + 1)]\n for i in range(N + 1):\n dp[i][0] = True\n for i in range(1, N + 1):\n for j in range(s + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[-1][-1]", "def equalpartition(N, arr):\n if sum(arr) % 2 != 0:\n return 0\n s = sum(arr) // 2\n w = s + 1\n l = []\n for i in range(N + 1):\n d = []\n for j in range(w):\n d.append(0)\n l.append(d)\n for i in range(N + 1):\n for j in range(w):\n if i == 0:\n l[i][j] = 0\n if j == 0:\n l[i][j] = 1\n for i in range(1, N + 1):\n for j in range(1, s + 1):\n if arr[i - 1] <= j:\n l[i][j] = l[i - 1][j - arr[i - 1]] or l[i - 1][j]\n else:\n l[i][j] = l[i - 1][j]\n return l[N][s]", "def equalpartition(N, arr):\n total = sum(arr)\n if total % 2 == 1:\n return False\n target = total // 2\n dp = [False] * (target + 1)\n dp[0] = True\n for num in arr:\n for i in range(target, num - 1, -1):\n if dp[i - num]:\n dp[i] = True\n if dp[-1]:\n return True\n return False", "def equalpartition(N, arr):\n total = sum(arr)\n if total % 2 == 1:\n return False\n arr.sort()\n\n def dp(required, idx):\n if required == 0:\n return True\n if idx == N or arr[idx] > required:\n return False\n return dp(required - arr[idx], idx + 1) or dp(required, idx + 1)\n return dp(total // 2, 0)", "def isSubsetSum(N, arr, sum):\n table = [[False for x in range(sum + 1)] for y in range(N + 1)]\n for i in range(N + 1):\n table[i][0] = True\n for i in range(1, N + 1):\n for j in range(1, sum + 1):\n table[i][j] = table[i - 1][j]\n if arr[i - 1] == j:\n table[i][j] = True\n elif arr[i - 1] < j:\n table[i][j] = table[i - 1][j] or table[i - 1][j - arr[i - 1]]\n else:\n table[i][j] = table[i - 1][j]\n return table[N][sum]\n\ndef equalpartition(N, arr):\n msum = sum(arr)\n if sum(arr) % 2 != 0:\n return 0\n if self.isSubsetSum(N, arr, sum(arr) // 2):\n return 1\n return 0", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2 == 1:\n return 0\n else:\n s = s // 2\n dp = []\n for i in range(N):\n dp.append([])\n for j in range(s + 1):\n dp[-1].append(0)\n for i in range(N):\n for j in range(s + 1):\n if j == arr[i]:\n dp[i][j] = 1\n elif i <= 0:\n dp[i][j] = 0\n else:\n t = 0\n if arr[i] <= j:\n t = dp[i - 1][j - arr[i]]\n dp[i][j] = max(dp[i - 1][j], t)\n return dp[-1][-1]", "def equalpartition(N, nums):\n if not nums:\n return True\n n = len(nums)\n if sum(nums) % 2 != 0:\n return False\n target = sum(nums) // 2\n memo = {}\n\n def helper(total, i):\n nonlocal nums, memo\n if (total, i) in memo:\n return memo[total, i]\n if i == len(nums):\n return False\n if total == 0:\n return True\n memo[total, i] = helper(total - nums[i], i + 1) or helper(total, i + 1)\n return memo[total, i]\n return helper(target, 0)", "def equalpartition(N, nums):\n sum_ = sum(nums)\n if sum_ % 2 != 0:\n return False\n half = sum_ // 2\n dp = [False] * (half + 1)\n dp[0] = True\n for el in nums:\n for j in range(half, el - 1, -1):\n if dp[j - el]:\n dp[j] = True\n return dp[half]", "def equalpartition(n, arr):\n ts = sum(arr)\n import sys\n sys.setrecursionlimit(10 ** 9 + 7)\n if ts > 0 and ts % 2 != 0:\n return False\n ts = ts // 2\n dp = [[-1 for j in range(ts + 1)] for j in range(n)]\n return self.solve(n - 1, ts, arr, dp)\n\ndef solve(i, j, arr, dp):\n if i == 0:\n return arr[i] == j\n if j == 0:\n dp[i][j] = True\n return True\n if dp[i][j] != -1:\n return dp[i][j]\n npick = self.solve(i - 1, j, arr, dp)\n pick = False\n if arr[i] <= j:\n pick = self.solve(i - 1, j - arr[i], arr, dp)\n dp[i][j] = pick or npick\n return dp[i][j]", "import numpy as np\n\ndef rec_sol(arr, Sum, N):\n if Sum == 0:\n return True\n if N == 0:\n return False\n if self.rec_sol(arr, Sum - arr[N - 1], N - 1) or self.rec_sol(arr, Sum, N - 1):\n return True\n return False\n\ndef mem_sol(arr, Sum, N, dp):\n if Sum == 0:\n return True\n if N == 0:\n return False\n if dp[N][Sum] != None:\n return dp[N][Sum]\n if self.mem_sol(arr, Sum - arr[N - 1], N - 1, dp) or self.mem_sol(arr, Sum, N - 1, dp):\n dp[N][Sum] = True\n return True\n dp[N][Sum] = False\n return False\n\ndef equalpartition(N, arr):\n tot = sum(arr)\n if tot % 2 == 1:\n return 0\n dp = np.array([[None] * (tot // 2 + 1)] * (N + 1))\n if self.mem_sol(arr, tot // 2, N, dp):\n return 1\n else:\n return 0", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2 != 0:\n return 0\n target = s // 2\n\n def fun(i, target):\n if i < 0:\n if target == 0:\n return True\n return False\n if arr[i] <= target:\n if fun(i - 1, target - arr[i]):\n return True\n if fun(i - 1, target):\n return True\n return False\n return fun(N - 1, target)", "def equalpartition(N, arr):\n key = 0\n for i in range(N):\n key += arr[i]\n if key % 2 == 1:\n return False\n else:\n return self.findSubsetSum(N, arr, key // 2, N - 1)\n\ndef findSubsetSum(N, arr, target, index):\n if target < 0:\n return False\n if target == 0:\n return True\n if index == 0:\n return arr[index] == target\n return self.findSubsetSum(N, arr, target - arr[index], index - 1) or self.findSubsetSum(N, arr, target, index - 1)", "def equalpartition(N, arr):\n sum = 0\n for i in arr:\n sum += i\n if sum % 2 != 0:\n return False\n sum = sum // 2\n K = [[0 for x in range(sum + 1)] for x in range(N + 1)]\n for i in range(N + 1):\n for j in range(sum + 1):\n if i == 0 and j == 0:\n K[i][j] = True\n if i == 0:\n K[i][j] = False\n if j == 0:\n K[i][j] = True\n elif arr[i - 1] <= j:\n K[i][j] = K[i - 1][j - arr[i - 1]] or K[i - 1][j]\n else:\n K[i][j] = K[i - 1][j]\n return K[N][sum]", "def equalpartition(N, arr):\n\n def f(arr, n, s):\n t = [[-1 for i in range(s + 1)] for i in range(N + 1)]\n return F(arr, n, s, t)\n\n def F(arr, N, s, t):\n if N == 0 and s != 0:\n return 0\n if s == 0:\n return 1\n if t[N][s] != -1:\n return t[N][s]\n if arr[N - 1] > s:\n t[N][s] = F(arr, N - 1, s, t)\n else:\n t[N][s] = F(arr, N - 1, s - arr[N - 1], t) or F(arr, N - 1, s, t)\n return t[N][s]\n S = sum(arr)\n if S % 2 != 0:\n return 0\n else:\n return f(arr, N, S // 2)", "def equalpartition(N, arr):\n\n def partitionSum(arr, startIndex, target, dp):\n if startIndex >= len(arr) or target < 0:\n return False\n if target == 0:\n return True\n if dp[startIndex + 1][target - arr[startIndex]] == -1:\n s1 = partitionSum(arr, startIndex + 1, target - arr[startIndex], dp)\n dp[startIndex + 1][target - arr[startIndex]] = s1\n else:\n s1 = dp[startIndex + 1][target - arr[startIndex]]\n if dp[startIndex][target] == -1:\n s2 = partitionSum(arr, startIndex + 1, target, dp)\n dp[startIndex][target] = s2\n else:\n s2 = dp[startIndex][target]\n return s1 or s2\n n = len(arr)\n target = sum(arr)\n subsetSum = target // 2\n dp = [[-1 for i in range(subsetSum + 1)] for j in range(n + 1)]\n if target % 2 != 0:\n return False\n else:\n return partitionSum(arr, 0, subsetSum, dp)", "def equalpartition(N, arr):\n arr.sort()\n sum_arr = sum(arr)\n if sum_arr % 2 != 0:\n return 0\n target_sum = sum_arr // 2\n subset_sums = set([0])\n for num in arr:\n for s in subset_sums.copy():\n if s + num == target_sum:\n return 1\n elif s + num < target_sum:\n subset_sums.add(s + num)\n return 0", "def subsetSumUtil(ind, target, arr, dp):\n if target == 0:\n return True\n if ind == 0:\n return arr[0] == target\n if dp[ind][target] != -1:\n return dp[ind][target]\n notTaken = subsetSumUtil(ind - 1, target, arr, dp)\n taken = False\n if arr[ind] <= target:\n taken = subsetSumUtil(ind - 1, target - arr[ind], arr, dp)\n dp[ind][target] = notTaken or taken\n return dp[ind][target]\n\ndef equalpartition(n, arr):\n totSum = sum(arr)\n if totSum % 2 == 1:\n return False\n else:\n k = totSum // 2\n dp = [[-1 for i in range(k + 1)] for j in range(n)]\n return subsetSumUtil(n - 1, k, arr, dp)", "def equalpartition(N, arr):\n Sum = 0\n for i in range(N):\n Sum += arr[i]\n if Sum % 2 != 0:\n return False\n target = Sum // 2\n return self.solveTab(arr, target)\n\ndef solveTab(arr, target):\n dp = [[False for j in range(target + 1)] for i in range(len(arr) + 1)]\n for i in range(len(arr) + 1):\n dp[i][0] = True\n for indx in range(len(arr) - 1, -1, -1):\n for t in range(target + 1):\n include = False\n if t - arr[indx] >= 0:\n include = dp[indx + 1][t - arr[indx]]\n exclude = dp[indx + 1][t]\n dp[indx][t] = include or exclude\n return dp[0][target]", "def solve(index, arr, N, target, dp):\n if index >= N:\n return False\n if target < 0:\n return False\n if target == 0:\n return True\n if dp[index][target] != -1:\n return dp[index][target]\n include = solve(index + 1, arr, N, target - arr[index], dp)\n exclude = solve(index + 1, arr, N, target, dp)\n dp[index][target] = include or exclude\n return dp[index][target]\n\ndef equalpartition(N, arr):\n total = sum(arr)\n if total % 2 != 0:\n return False\n target = total // 2\n dp = [[-1 for j in range(target + 1)] for i in range(N)]\n return solve(0, arr, N, target, dp)", "def equalpartition(N, arr):\n sm = sum(arr)\n if sm % 2:\n return 0\n stateMap = {0: True}\n llimit = max(arr)\n for elem in arr:\n currMap = {}\n for k in stateMap:\n if k + elem <= sm // 2:\n currMap[k + elem] = True\n if k - elem >= -llimit:\n currMap[k - elem] = True\n stateMap = currMap\n return 1 if stateMap.get(0) else 0", "def equalpartition(N, arr):\n if sum(arr) % 2 != 0:\n return 0\n else:\n mid_sum = sum(arr) // 2\n res = [[0 for _ in range(mid_sum + 1)] for x in range(N + 1)]\n for i in range(N + 1):\n for j in range(mid_sum + 1):\n if i == 0:\n res[i][j] = False\n if j == 0:\n res[i][j] = True\n for i in range(1, N + 1):\n for j in range(1, mid_sum + 1):\n if arr[i - 1] <= j:\n res[i][j] = res[i - 1][j - arr[i - 1]] or res[i - 1][j]\n else:\n res[i][j] = res[i - 1][j]\n if res[N][mid_sum]:\n return 1\n else:\n return 0", "def equalpartition(N, arr):\n total = sum(arr)\n s = 0\n if total % 2 != 0:\n return False\n\n def dfs(i, s):\n if s == total // 2:\n return True\n if s != total // 2 and i == len(arr):\n return\n if s > total // 2:\n return\n for j in range(i, len(arr)):\n s += arr[j]\n if dfs(j + 1, s):\n return True\n s -= arr[j]\n if dfs(0, s):\n return True\n else:\n return False", "def knapsack(arr, N, W):\n dp = [[0 for _ in range(W + 1)] for _ in range(N + 1)]\n for i in range(1, N + 1):\n for w in range(W + 1):\n ele_not_present = dp[i - 1][w]\n ele_present = 0\n if w - arr[i - 1] >= 0:\n ele_present = dp[i - 1][w - arr[i - 1]] + arr[i - 1]\n dp[i][w] = max(ele_not_present, ele_present)\n return dp\n\ndef equalpartition(N, arr):\n total_sum = sum(arr)\n if total_sum % 2 != 0:\n return False\n half_sum = total_sum // 2\n dp = self.knapsack(arr, N, half_sum)\n if dp[N][half_sum] != half_sum:\n return False\n return True", "def equalpartition(N, arr):\n sm = 0\n for i in arr:\n sm += i\n if sm % 2 != 0 or sm == 0:\n return False\n sm = sm // 2\n dp = [[True for i in range(sm + 1)] for j in range(N + 1)]\n for i in range(sm + 1):\n dp[0][i] = False\n for i in range(1, N + 1):\n for j in range(1, sm + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j - arr[i - 1]] or dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[i][j]", "def equalpartition(N, arr):\n totSum = sum(arr)\n if totSum % 2 == 1:\n return False\n else:\n k = totSum // 2\n dp = [[-1 for i in range(k + 1)] for j in range(N)]\n return self.solve(N - 1, k, arr, dp)\n\ndef solve(idx, _t, arr, dp):\n if _t == 0:\n return True\n if idx == 0:\n return arr[0] == _t\n if dp[idx][_t] != -1:\n return dp[idx][_t]\n notTaken = self.solve(idx - 1, _t, arr, dp)\n taken = False\n if arr[idx] <= _t:\n taken = self.solve(idx - 1, _t - arr[idx], arr, dp)\n dp[idx][_t] = notTaken or taken\n return dp[idx][_t]", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2:\n return 'NO'\n W = s // 2\n dp = [[0 for j in range(W + 1)] for i in range(N + 1)]\n for i in range(N + 1):\n for j in range(W + 1):\n if j == 0:\n dp[i][j] = 1\n elif j < arr[i - 1]:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j] | dp[i - 1][j - arr[i - 1]]\n return dp[N][W]", "def equalpartition(N, arr):\n total_sum = sum(arr)\n if total_sum % 2 != 0:\n return False\n target = total_sum // 2\n dp = [False] * (target + 1)\n dp[0] = True\n for ele in arr:\n for j in range(target, ele - 1, -1):\n if dp[j - ele]:\n dp[j] = True\n return dp[target]", "def equalpartition(N, arr):\n sum = 0\n for i in arr:\n sum += i\n if sum % 2 != 0:\n return False\n sum = sum // 2\n dp = [[False for i in range(sum + 1)] for i in range(N)]\n for i in range(N):\n dp[i][0] = True\n if arr[0] <= sum:\n dp[0][arr[0]] = True\n for ind in range(1, N):\n for target in range(1, sum + 1):\n ntake = dp[ind - 1][target]\n take = False\n if arr[ind] <= target:\n take = dp[ind - 1][target - arr[ind]]\n dp[ind][target] = take or ntake\n if target == sum:\n if dp[ind][target] == True:\n return True\n return dp[N - 1][sum]", "def equalpartition(n, arr):\n sum_ = sum(arr)\n if sum_ % 2 == 0:\n target = sum_ // 2\n dp = [[-1 for j in range(target + 1)] for i in range(n)]\n return self.solve(n - 1, target, dp, arr)\n else:\n return False\n\ndef solve(n, target, dp, arr):\n if target == 0:\n dp[n][target] = True\n return True\n if n == 0:\n if arr[n] == target:\n dp[n][target] = True\n return True\n else:\n dp[n][target] = False\n return False\n if dp[n][target] != -1:\n return dp[n][target]\n pick = False\n if arr[n] <= target:\n pick = self.solve(n - 1, target - arr[n], dp, arr)\n npick = self.solve(n - 1, target, dp, arr)\n dp[n][target] = pick or npick\n return dp[n][target]", "def equalpartition(N, arr):\n if sum(arr) % 2 != 0:\n return False\n else:\n return self.isSubsetSum(N, arr, sum(arr) // 2)\n\ndef isSubsetSum(N, arr, sum):\n tab = [[False for i in range(sum + 1)] for j in range(N + 1)]\n for i in range(N + 1):\n tab[i][0] = True\n for i in range(1, N + 1):\n for j in range(1, sum + 1):\n if arr[i - 1] > j:\n tab[i][j] = tab[i - 1][j]\n else:\n tab[i][j] = tab[i - 1][j] or tab[i - 1][j - arr[i - 1]]\n return tab[N][sum]", "def solve(N, arr, idx, summ):\n if summ == 0:\n return 1\n if idx >= N or summ < 0:\n return 0\n incl = self.solve(N, arr, idx + 1, summ - arr[idx])\n excl = self.solve(N, arr, idx + 1, summ)\n return incl or excl\n\ndef solve_memo(N, arr, idx, summ, F):\n if summ == 0:\n return 1\n if idx >= N or summ < 0:\n return 0\n incl = self.solve_memo(N, arr, idx + 1, summ - arr[idx], F)\n excl = self.solve_memo(N, arr, idx + 1, summ, F)\n F[idx][summ] = incl or excl\n return F[idx][summ]\n\ndef solve_tab(N, arr):\n total = sum(arr)\n F = [[0 for _ in range(total // 2 + 1)] for _ in range(N + 1)]\n for i in range(N + 1):\n F[i][0] = 1\n for idx in range(N - 1, -1, -1):\n for summ in range(total // 2 + 1):\n incl = 0\n if summ - arr[idx] >= 0:\n incl = F[idx + 1][summ - arr[idx]]\n excl = F[idx + 1][summ]\n F[idx][summ] = incl or excl\n return F[0][total // 2]\n\ndef solve_tab2(N, arr):\n total = sum(arr)\n curr = [0 for _ in range(total // 2 + 1)]\n nextt = [0 for _ in range(total // 2 + 1)]\n curr[0] = 1\n nextt[0] = 1\n for idx in range(N - 1, -1, -1):\n for summ in range(total // 2 + 1):\n incl = 0\n if summ - arr[idx] >= 0:\n incl = nextt[summ - arr[idx]]\n excl = nextt[summ]\n curr[summ] = incl or excl\n nextt = curr[:]\n return nextt[total // 2]\n\ndef equalpartition(N, arr):\n summ = sum(arr)\n if summ % 2:\n return 0\n return self.solve_tab2(N, arr)", "def equalpartition(n, arr):\n s = sum(arr)\n if s % 2 != 0:\n return False\n elif self.subsetSum(n, arr, s // 2):\n return True\n else:\n return False\n\ndef subsetSum(n, arr, s):\n dp = [[False for i in range(s + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = True\n for i in range(1, s + 1):\n dp[0][i] = False\n for i in range(1, n + 1):\n for j in range(1, s + 1):\n if arr[i - 1] <= j:\n dp[i][j] = dp[i - 1][j - arr[i - 1]] or dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j]\n return dp[-1][-1]", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2 != 0:\n return 0\n k = s // 2\n dp = [[0 for _ in range(k + 1)] for i in range(N + 1)]\n for i in range(N + 1):\n dp[i][0] = 1\n for i in range(1, N + 1):\n for j in range(1, k + 1):\n if arr[i - 1] > j:\n dp[i][j] = dp[i - 1][j]\n else:\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]\n return dp[N][k]", "def equalpartition(N, arr):\n stateMap = {0: True}\n llimit = max(arr)\n for elem in arr:\n currMap = {}\n for k in stateMap:\n if not currMap.get(k + elem):\n currMap[k + elem] = True\n if k - elem >= -llimit and (not currMap.get(k - elem)):\n currMap[k - elem] = True\n stateMap = currMap\n return 1 if stateMap.get(0) else 0", "def equalpartition(N, arr):\n\n def foo(i, s, dp):\n if s == 0:\n return True\n if i < 0 or s < 0:\n return False\n if dp[i][s] != -1:\n return dp[i][s]\n dp[i][s] = foo(i - 1, s - arr[i], dp) or foo(i - 1, s, dp)\n return dp[i][s]\n sm = sum(arr)\n if sm % 2 != 0:\n return 0\n dp = [[-1] * (sm // 2 + 1) for i in range(N)]\n foo(N - 1, sm // 2, dp)\n return dp[N - 1][sm // 2]", "def equalpartition(N, arr):\n sum_ = sum(arr)\n if sum_ % 2 != 0:\n return 0\n s = sum_ // 2\n dp = [[False for i in range(s + 1)] for j in range(N + 1)]\n for i in range(N + 1):\n for j in range(s + 1):\n if i == 0 and j == 0:\n dp[i][j] = True\n elif i == 0:\n dp[i][j] = False\n elif j == 0:\n dp[i][j] = True\n elif dp[i - 1][j]:\n dp[i][j] = dp[i - 1][j]\n else:\n val = arr[i - 1]\n if j >= val:\n dp[i][j] = dp[i - 1][j - val]\n return dp[-1][-1]", "def equalpartition(N, arr):\n total = sum(arr)\n if total % 2 != 0:\n return 0\n DP = [[-1] * (total // 2 + 1) for i in range(N)]\n\n def reccur(index, curSum):\n if curSum == 0:\n return 1\n if index == 0:\n return int(arr[index] == curSum)\n if DP[index][curSum] != -1:\n return DP[index][curSum]\n not_take = reccur(index - 1, curSum)\n take = 0\n if curSum >= arr[index]:\n take = reccur(index - 1, curSum - arr[index])\n DP[index][curSum] = take or not_take\n return DP[index][curSum]\n return reccur(N - 1, total // 2)", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2 != 0:\n return False\n t = s // 2\n d = set()\n d.add(0)\n new = []\n for i in arr:\n for j in d:\n a = i + j\n new.append(a)\n for i in new:\n d.add(i)\n new = []\n if t in d:\n return True\n if t in d:\n return True\n return False", "def equalpartition(N, arr):\n sum = 0\n for i in range(N):\n sum = sum + arr[i]\n t = [[-1 for j in range(int(sum / 2) + 1)] for i in range(N + 1)]\n if sum % 2 != 0:\n return 0\n else:\n for i in range(N + 1):\n for j in range(int(sum / 2) + 1):\n if i == 0:\n t[i][j] = 0\n if j == 0:\n t[i][j] = 1\n for i in range(1, N + 1):\n for j in range(1, int(sum / 2) + 1):\n if arr[i - 1] <= j:\n t[i][j] = t[i - 1][j - arr[i - 1]] or t[i - 1][j]\n else:\n t[i][j] = t[i - 1][j]\n return t[N][sum // 2]", "def partition_sum_problem(input_arr: []):\n sum_value = sum(input_arr)\n if sum_value % 2 != 0:\n return False\n return can_partition_helper(0, int(sum_value // 2), len(input_arr) - 1, input_arr)\n\ndef can_partition_helper(index: int, remaining_sum: int, end_index, input_arr: []):\n if remaining_sum == 0:\n return True\n if index > end_index or remaining_sum < 0:\n return False\n return can_partition_helper(index + 1, remaining_sum - input_arr[index], end_index, input_arr) or can_partition_helper(index + 1, remaining_sum, end_index, input_arr)\n\ndef equalpartition(N, arr):\n return partition_sum_problem(arr)", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2:\n return False\n s = s // 2\n part = [False] * (s + 1)\n part[0] = True\n for i in range(N):\n for j in range(s, arr[i] - 1, -1):\n if part[j - arr[i]] or j == arr[i]:\n part[j] = True\n return part[s]", "import sys\nsys.setrecursionlimit(10 ** 6)\n\ndef equalpartition(N, arr):\n if sum(arr) % 2 != 0:\n return False\n target = sum(arr) // 2\n\n def helper(i, n):\n if n == 0:\n return True\n if i == len(arr) or n < 0:\n return False\n return helper(i + 1, n - arr[i]) or helper(i + 1, n)\n return helper(0, target)", "def solve(arr, ind, sum, dp):\n if ind < 0:\n return sum == 0\n if dp[ind][sum] != -1:\n return dp[ind][sum]\n ans = self.solve(arr, ind - 1, sum, dp)\n if arr[ind] <= sum:\n ans = max(ans, self.solve(arr, ind - 1, sum - arr[ind], dp))\n dp[ind][sum] = ans\n return ans\n\ndef equalpartition(N, arr):\n su = sum(arr)\n if su & 1 == 1:\n return 0\n dp = [[-1 for _ in range(su)] for _ in range(N)]\n return self.solve(arr, N - 1, su // 2, dp)", "def equalpartition(N, arr):\n tot = sum(arr)\n if tot % 2 == 1:\n return 0\n req = tot // 2\n allposs = set([0])\n for ele in arr:\n set2 = set()\n for sub in allposs:\n newsum = sub + ele\n if newsum == req:\n return 1\n set2.add(newsum)\n allposs = allposs.union(set2)\n return 0", "def equalpartition(N, arr):\n total = sum(arr)\n if total % 2:\n return 0\n k = total // 2\n dp = [[0 for i in range(k + 1)] for j in range(N)]\n for i in range(N):\n dp[i][0] = 1\n if arr[0] <= k:\n dp[0][arr[0]] = 1\n for i in range(1, N):\n for target in range(1, k + 1):\n nottake = dp[i - 1][target]\n take = False\n if arr[i] <= target:\n take = dp[i - 1][target - arr[i]]\n dp[i][target] = take or nottake\n return dp[N - 1][k]", "def equalpartition(N, arr):\n if len(arr) == 0:\n arr_sum = 0\n else:\n arr_sum = sum(arr)\n if arr_sum % 2 != 0:\n return 0\n dp = [[-1 for _ in range(arr_sum + 1)] for __ in range(len(arr))]\n if self.ispossible(arr, arr_sum // 2, dp, len(arr) - 1):\n return 1\n else:\n return 0\n\ndef ispossible(array, rem, sub, n):\n if rem == 0:\n return True\n if n == -1 and rem != 0:\n return False\n if sub[n][rem] != -1:\n return sub[n][rem]\n if array[n] <= rem:\n not_skip = self.ispossible(array, rem - arr[n], sub, n - 1)\n else:\n not_skip = False\n skip = self.ispossible(array, rem, sub, n - 1)\n if skip or not_skip:\n sub[n][rem] = True\n else:\n sub[n][rem] = False\n return sub[n][rem]", "def equalpartition(N, arr):\n if len(arr) == 0:\n arr_sum = 0\n else:\n arr_sum = sum(arr)\n if arr_sum % 2 != 0:\n return 0\n dp = [[-1 for _ in range(arr_sum + 1)] for __ in range(len(arr))]\n return self.ispossible(arr, arr_sum // 2, dp, len(arr) - 1)\n\ndef ispossible(array, rem, sub, n):\n if rem == 0:\n return 1\n if n == -1 and rem != 0:\n return 0\n if sub[n][rem] != -1:\n return sub[n][rem]\n if array[n] > rem:\n return self.ispossible(array, rem, sub, n - 1)\n if self.ispossible(array, rem - array[n], sub, n - 1) + self.ispossible(array, rem, sub, n - 1) >= 1:\n sub[n][rem] = 1\n else:\n sub[n][rem] = 0\n return sub[n][rem]", "def helper(arr, n, s, i, dp):\n if s == 0:\n return 1\n if i == n:\n return 0\n if dp[i][s] != -1:\n return dp[i][s]\n take = 0\n if arr[i] <= s:\n take = self.helper(arr, n, s - arr[i], i + 1, dp)\n nottake = self.helper(arr, n, s, i + 1, dp)\n dp[i][s] = take or nottake\n return take or nottake\n\ndef equalpartition(N, arr):\n s = 0\n for i in arr:\n s += i\n p = s // 2\n if s % 2 == 1:\n return 0\n dp = [[-1 for i in range(p + 1)] for j in range(N + 1)]\n for i in range(N):\n dp[i][0] = 1\n if self.helper(arr, N, p, 0, dp):\n return 1\n return 0", "def equalpartition(N, arr):\n\n def come(arr, target, N):\n if target == 0:\n return True\n if N == 0:\n if arr[0] == target:\n return True\n return False\n if arr[N] <= target:\n return come(arr, target - arr[N], N - 1) or come(arr, target, N - 1)\n return come(arr, target, N - 1)\n s = 0\n for i in arr:\n s = s + i\n if s % 2 == 1:\n return False\n else:\n p = come(arr, s // 2, N - 1)\n return p", "def equalpartition(N, arr):\n dp = []\n for i in range(N):\n a = []\n for j in range(sum(arr) // 2 + 1):\n a.append(0)\n dp.append(a)\n if sum(arr) % 2 == 1:\n return 0\n for i in range(N):\n dp[i][0] = 1\n if arr[0] <= sum(arr) // 2:\n dp[0][arr[0]] = 1\n for i in range(1, N):\n for j in range(1, sum(arr) // 2 + 1):\n nottake = dp[i - 1][j]\n take = 0\n if arr[i] <= j:\n take = dp[i - 1][j - arr[i]]\n dp[i][j] = take or nottake\n return dp[N - 1][sum(arr) // 2]", "def equalpartition(N, arr):\n total = sum(arr)\n if total % 2 != 0:\n return 0\n dp = [[-1] * (total + 1) for i in range(N + 1)]\n\n def subset(arr, n, s, total):\n if s == total - s:\n return 1\n if n >= 0 and s == 0:\n return 0\n if n == 0 and s > 0:\n return 0\n if dp[n][s] != -1:\n return dp[n][s]\n elif arr[n - 1] <= s:\n dp[n][s] = subset(arr, n - 1, s - arr[n - 1], total) or subset(arr, n - 1, s, total)\n else:\n dp[n][s] = subset(arr, n - 1, s, total)\n return dp[n][s]\n return subset(arr, N, total, total)", "def equalpartition(N, arr):\n s = sum(arr)\n if s % 2 != 0:\n return 0\n s = s // 2 + 1\n m = [[0 for i in range(s)] for j in range(N + 1)]\n m[0][0] = 1\n for i in range(N + 1):\n for j in range(s):\n if i == 0 and j != 0:\n m[i][j] = 0\n elif j == 0:\n m[i][j] = 1\n elif arr[i - 1] > j:\n m[i][j] = m[i - 1][j]\n else:\n m[i][j] = m[i - 1][j] or m[i - 1][j - arr[i - 1]]\n return m[N][s - 1]", "def equalpartition(n, arr):\n s = sum(arr)\n if s % 2 == 1:\n return 0\n dp = [[-1] * (s // 2 + 1) for i in range(n)]\n\n def partpos(i, s1, s2, n):\n if s1 == s2:\n return 1\n if i >= n or s1 > s2:\n return 0\n if dp[i][s1] != -1:\n return dp[i][s1]\n inc = partpos(i + 1, s1 + arr[i], s2 - arr[i], n)\n if inc == 1:\n return 1\n ninc = partpos(i + 1, s1, s2, n)\n dp[i][s1] = 1 if inc == 1 or ninc == 1 else 0\n return 1 if inc == 1 or ninc == 1 else 0\n return partpos(0, 0, s, n)", "def equalpartition(N, arr):\n total = 0\n for i in arr:\n total += i\n dp = [[-1 for i in range(total // 2 + 1)] for j in range(N)]\n if total % 2:\n return False\n else:\n return self.recursion(0, arr, total // 2, N, dp)\n\ndef recursion(idx, arr, tar, n, dp):\n if idx == n:\n if tar == 0:\n return True\n return False\n if dp[idx][tar] != -1:\n return dp[idx][tar]\n p = False\n if tar >= arr[idx]:\n p = self.recursion(idx + 1, arr, tar - arr[idx], n, dp)\n np = self.recursion(idx + 1, arr, tar, n, dp)\n dp[idx][tar] = p or np\n return dp[idx][tar]", "def equalpartition(N, arr):\n arrSum = sum(arr)\n if arrSum % 2 != 0:\n return False\n dp = dict()\n return self.subsetSum(arr, N, 0, arrSum // 2, dp)\n\ndef subsetSum(arr, n, index, s, dp):\n if index == n:\n if s == 0:\n return True\n return False\n if s == 0:\n return True\n if (index, s) in dp:\n return dp[index, s]\n if arr[index] > s:\n dp[index, s] = self.subsetSum(arr, n, index + 1, s, dp)\n else:\n dp[index, s] = self.subsetSum(arr, n, index + 1, s, dp) or self.subsetSum(arr, n, index + 1, s - arr[index], dp)\n return dp[index, s]"], "starter_code": "def equalpartition(N, arr):\n", "input_output": {"inputs": ["N = 4\r\narr = {1, 5, 11, 5}", "N = 3\r\narr = {1, 3, 5}"], "outputs": ["YES", "NO"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming", "subset"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Mathematics"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/subset-sum-problem2014/1", "Expected Auxiliary Space": "O(N*sum of elements)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N*sum of elements)", "entry_point": "equalpartition", "task_id": "TACO_lite/444", "example": [[], []]} +{"requirement": "You've just entered a programming contest and have a chance to win a million dollars. This is the last question you have to solve, so your victory (and your vacation) depend on it. Can you guess the function just by looking at the test cases? There are two numerical inputs and one numerical output. Goodluck!\n\nhint: go\n here", "solutions": ["TABLE = str.maketrans('0123456789', '9876543210')\n\ndef code(*args):\n return sum(map(lambda n: int(str(n).translate(TABLE)), args))", "def code(x, y):\n return sum((int('9' * len(str(n))) - n for n in [x, y]))", "code = lambda Q, S: 10 ** len(str(Q)) + 10 ** len(str(S)) - 2 - Q - S", "def code(x, y):\n return sum((int(str(n).translate(str.maketrans('0123456789', '9876543210'))) for n in [x, y]))", "def code(x, y):\n return 10 ** len(str(x)) - x + (10 ** len(str(y)) - y) - 2", "code = lambda a, b: 10 ** len(str(a)) - a + 10 ** len(str(b)) - b - 2", "def code(x, y):\n goal = pow(10, len(str(x))) + pow(10, len(str(y))) - 2\n return goal - x - y", "def code(x, y):\n return 10 ** len(str(x)) + 10 ** len(str(y)) + 3 - x - y - 5"], "starter_code": "def code(x,y):\n", "input_output": {"fn_name": "code", "inputs": [[9, 8], [123, 456], [3, 2], [1, 1], [12, 8], [200, 100], [100, 200]], "outputs": [[1], [1419], [13], [16], [88], [1698], [1698]]}, "difficulty": "EASY", "raw_tags": ["Puzzles"], "name": null, "source": "codewars", "tags": ["Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/5b1fa8d92ae7540e700000f0", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "code", "task_id": "TACO_lite/386", "example": [[[3, 5], [10, 15], [7, 2], [0, 0]], [10, 173, 9, 18]]} +{"requirement": "Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.\n\nReturn the quotient after dividing dividend by divisor.\n\nThe integer division should truncate toward zero.\n\nExample 1:\n\n\nInput: dividend = 10, divisor = 3\nOutput: 3\n\nExample 2:\n\n\nInput: dividend = 7, divisor = -3\nOutput: -2\n\nNote:\n\n\n Both dividend and divisor\u00a0will be\u00a032-bit\u00a0signed integers.\n The divisor will never be 0.\n Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [\u2212231, \u00a0231 \u2212 1]. For the purpose of this problem, assume that your function returns 231 \u2212 1 when the division result\u00a0overflows.", "solutions": ["def get_half(dividend, divisor):\n abs_dividend = abs(dividend)\n abs_divisor = abs(divisor)\n num = divisor\n num_temp = 0\n result = 1\n result_temp = 0\n while num <= dividend:\n num_temp = num\n num += num\n result_temp = result\n result += result\n return (num_temp, result_temp)\n\ndef divide(dividend, divisor):\n MAX_INT = 2147483647\n if divisor == 0:\n return MAX_INT\n abs_dividend = abs(dividend)\n abs_divisor = abs(divisor)\n if abs_dividend < abs_divisor:\n return 0\n minus_flag = (dividend is abs_dividend) is (divisor is abs_divisor)\n final_result = 0\n while abs_dividend >= abs_divisor:\n (num, result) = self.get_half(abs_dividend, abs_divisor)\n abs_dividend -= num\n final_result += result\n if minus_flag == 1:\n if final_result > MAX_INT:\n return MAX_INT\n return final_result\n else:\n if 0 - final_result < 0 - MAX_INT - 1:\n return 0 - MAX_INT\n return 0 - final_result", "def divide(dividend, divisor):\n positive = (dividend < 0) is (divisor < 0)\n (dividend, divisor) = (abs(dividend), abs(divisor))\n res = 0\n while dividend >= divisor:\n (temp, i) = (divisor, 1)\n while dividend >= temp:\n dividend -= temp\n res += i\n temp <<= 1\n i <<= 1\n if not positive:\n res = -res\n return min(max(-2147483648, res), 2147483647)", "def divide(dividend, divisor):\n if abs(dividend) < abs(divisor):\n return 0\n (sum, count, result) = (0, 0, 0)\n (a, b) = (abs(dividend), abs(divisor))\n while a >= b:\n sum = b\n count = 1\n while sum + sum < a:\n sum += sum\n count += count\n a -= sum\n result += count\n if dividend < 0 and divisor > 0 or (dividend > 0 and divisor < 0):\n result = 0 - result\n return min(result, 2147483647)", "def divide(dividend, divisor):\n MIN_INT = -2 ** 31\n MAX_INT = -MIN_INT - 1\n if divisor == 0 or (dividend == MIN_INT and divisor == -1):\n return MAX_INT\n sign = 1\n if dividend < 0:\n sign = -sign\n dividend = -dividend\n if divisor < 0:\n sign = -sign\n divisor = -divisor\n ans = bits = 0\n while divisor << bits + 1 <= dividend:\n bits += 1\n while bits >= 0:\n if dividend >= divisor << bits:\n dividend -= divisor << bits\n ans += 1 << bits\n bits -= 1\n return ans if sign == 1 else -ans", "def divide(dividend, divisor):\n positive = (dividend < 0) is (divisor < 0)\n (dividend, divisor, div) = (abs(dividend), abs(divisor), abs(divisor))\n res = 0\n q = 1\n while dividend >= divisor:\n dividend -= div\n res += q\n q += q\n div += div\n if dividend < div:\n div = divisor\n q = 1\n if not positive:\n res = -res\n return min(max(-2147483648, res), 2147483647)", "def divide(dividend, divisor):\n tag = 1 if (dividend < 0) is (divisor < 0) else -1\n (dividend, divisor) = (abs(dividend), abs(divisor))\n if divisor == 0:\n return float('inf')\n count = 0\n while dividend >= divisor:\n mul = 1\n t = divisor\n while dividend > t << 1:\n t <<= 1\n mul <<= 1\n dividend -= t\n count += mul\n return min(max(-2147483648, count * tag), 2147483647)", "def divide(dividend, divisor):\n if dividend < 0 and divisor > 0 or (dividend > 0 and divisor < 0):\n if abs(dividend) < abs(divisor):\n return 0\n summ = 0\n count = 0\n res = 0\n a = abs(dividend)\n b = abs(divisor)\n while a >= b:\n summ = b\n count = 1\n while summ + summ <= a:\n summ += summ\n count += count\n a -= summ\n res += count\n if dividend < 0 and divisor > 0 or (dividend > 0 and divisor < 0):\n res = 0 - res\n if res > 2 ** 31 - 1:\n res = 2 ** 31 - 1\n return res", "def divide(dividend, divisor):\n flag = (dividend < 0) is (divisor < 0)\n (dividend, divisor) = (abs(dividend), abs(divisor))\n result = 0\n while dividend >= divisor:\n (newDivisor, rate) = (divisor, 1)\n while dividend >= newDivisor:\n dividend -= newDivisor\n result += rate\n newDivisor <<= 1\n rate <<= 1\n if not flag:\n result = 0 - result\n return min(max(-2147483648, result), 2147483647)"], "starter_code": "def divide(dividend: int, divisor: int) -> int:\n", "input_output": {"fn_name": "divide", "inputs": [[10, 3]], "outputs": [3]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Math", "Bit Manipulation"], "name": null, "source": "leetcode", "tags": ["Bit manipulation", "Mathematics"], "skill_types": ["Bit manipulation"], "url": "https://leetcode.com/problems/divide-two-integers/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "divide", "task_id": "TACO_lite/429", "example": [[[10, 3], [7, -3]], ["3", "-2"]]} +{"requirement": "Given the root\u00a0of a binary tree, consider all root to leaf paths: paths from the root\u00a0to any leaf.\u00a0 (A leaf is a node with no children.)\nA node is insufficient if\u00a0every such root to leaf path intersecting this node has sum strictly less than\u00a0limit.\nDelete all insufficient nodes simultaneously, and return the root of the resulting\u00a0binary tree.\n\u00a0\nExample 1:\n\nInput: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1\n\nOutput: [1,2,3,4,null,null,7,8,9,null,14]\n\n\nExample 2:\n\nInput: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22\n\nOutput: [5,4,8,11,null,17,4,7,null,null,null,5]\n\u00a0\nExample 3:\n\nInput: root = [1,2,-3,-5,null,4,null], limit = -1\n\nOutput: [1,null,-3,4]\n\n\u00a0\nNote:\n\nThe given tree will have between 1 and 5000 nodes.\n-10^5\u00a0<= node.val <= 10^5\n-10^9 <= limit\u00a0<= 10^9", "solutions": ["def sufficientSubset(root, limit):\n if root.left == root.right:\n return None if root.val < limit else root\n if root.left:\n root.left = self.sufficientSubset(root.left, limit - root.val)\n if root.right:\n root.right = self.sufficientSubset(root.right, limit - root.val)\n return root if root.left or root.right else None", "def sumofnodes(root, cursum):\n if root is None:\n return 0\n cursum += root.val\n self.sumdict[root] = cursum\n self.sumofnodes(root.left, cursum)\n self.sumofnodes(root.right, cursum)\n\ndef maxpathsum(root):\n if root.left == None and root.right == None:\n self.maxdict[root] = self.sumdict[root]\n elif root.left and root.right:\n self.maxdict[root] = max(self.maxpathsum(root.left), self.maxpathsum(root.right))\n elif root.right:\n self.maxdict[root] = self.maxpathsum(root.right)\n else:\n self.maxdict[root] = self.maxpathsum(root.left)\n return self.maxdict[root]\n\ndef deletenodes(root, limit):\n if root is None:\n return\n if root.left and self.maxdict[root.left] < limit:\n root.left = None\n if root.right and self.maxdict[root.right] < limit:\n root.right = None\n self.deletenodes(root.left, limit)\n self.deletenodes(root.right, limit)\n\ndef sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n self.sumdict = {}\n self.sumofnodes(root, 0)\n self.maxdict = {}\n self.maxpathsum(root)\n self.deletenodes(root, limit)\n if self.maxdict[root] < limit:\n return None\n else:\n return root", "def sufficientSubset(root, limit):\n\n def dfs(root, cur):\n if root is None:\n return None\n s = root.val + cur\n if root.left is None and root.right is None:\n if s < limit:\n return None\n else:\n return root\n l = dfs(root.left, s)\n r = dfs(root.right, s)\n if l is None and r is None:\n return None\n (root.left, root.right) = (l, r)\n return root\n return dfs(root, 0)", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n sum_t_root = TreeNode(root.val)\n sum_t_node = sum_t_root\n t_node = root\n\n def calSumT(node, sum_t_node, s):\n if not node:\n return\n if not node.left and (not node.right):\n sum_t_node.val = True if s >= limit else False\n if node.left:\n sum_t_node.left = TreeNode(node.left.val + s)\n calSumT(node.left, sum_t_node.left, s + node.left.val)\n if node.right:\n sum_t_node.right = TreeNode(node.right.val + s)\n calSumT(node.right, sum_t_node.right, s + node.right.val)\n calSumT(t_node, sum_t_node, root.val)\n\n def strT(node):\n if not node:\n return []\n return [node.val] + strT(node.left) + strT(node.right)\n\n def checkSumT(node):\n if not node.left and (not node.right):\n return\n rtn = False\n if node.left:\n checkSumT(node.left)\n rtn |= node.left.val\n if node.right:\n checkSumT(node.right)\n rtn |= node.right.val\n node.val = rtn\n sum_t_node = sum_t_root\n checkSumT(sum_t_node)\n\n def updateNode(node, s_node):\n if not node or not s_node.val:\n return None\n if node.left:\n node.left = updateNode(node.left, s_node.left)\n if node.right:\n node.right = updateNode(node.right, s_node.right)\n return node\n return updateNode(root, sum_t_root)", "def check_limit(root, limit):\n if not root:\n return float('-inf')\n left_sum = self.check_limit(root.left, limit - root.val)\n right_sum = self.check_limit(root.right, limit - root.val)\n if left_sum != float('-inf') and left_sum + root.val < limit:\n root.left = None\n if right_sum != float('-inf') and right_sum + root.val < limit:\n root.right = None\n max_ = max(left_sum, right_sum)\n if max_ == float('-inf'):\n return root.val\n return max_ + root.val\n\ndef sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n if (self.check_limit(root, limit) or 0) < limit:\n return None\n else:\n return root", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n\n def check(node, pathsum):\n if not node:\n return pathsum >= limit\n pathsum += node.val\n had_children = node.left or node.right\n if not check(node.left, pathsum):\n node.left = None\n if not check(node.right, pathsum):\n node.right = None\n return node.left or node.right if had_children else pathsum >= limit\n return root if check(root, 0) else None", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n\n def check(root, total, limit):\n if root == None:\n return None\n total += root.val\n if root.left == root.right:\n if total < limit:\n return None\n else:\n return root\n flag1 = 0\n flag2 = 0\n if root.left:\n root.left = check(root.left, total, limit)\n flag1 = 1 if root.left else -1\n if root.right:\n root.right = check(root.right, total, limit)\n flag2 = 1 if root.right else -1\n if flag1 > 0 or flag2 > 0:\n return root\n else:\n return None\n rtv = check(root, 0, limit)\n return rtv", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n if not root:\n return root\n\n def dfs(node, value):\n if not node:\n return False\n value += node.val\n lret = dfs(node.left, value)\n rret = dfs(node.right, value)\n if not node.left and (not node.right):\n if value < limit:\n return False\n return True\n if not lret:\n node.left = None\n if not rret:\n node.right = None\n if lret or rret:\n return True\n return False\n res = dfs(root, 0)\n if res:\n return root", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n\n def helper(root, currsum, limit):\n if not root:\n return True\n currsum += root.val\n if root.left is None and root.right is None:\n return currsum < limit\n deleteme = [True, True]\n if root.left:\n should_del = helper(root.left, currsum, limit)\n if should_del:\n del root.left\n root.left = None\n deleteme[0] = should_del\n if root.right:\n should_del = helper(root.right, currsum, limit)\n if should_del:\n del root.right\n root.right = None\n deleteme[1] = should_del\n return all(deleteme)\n deleteroot = helper(root, 0, limit)\n if deleteroot:\n del root\n return None\n return root", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n head = TreeNode()\n head.left = root\n\n def inner1(root, prev_sum):\n if root is None:\n return\n else:\n root.val = (root.val, prev_sum)\n inner1(root.left, root.val[0] + prev_sum)\n inner1(root.right, root.val[0] + prev_sum)\n return\n\n def inner2(root):\n if root is None:\n return []\n if root.left is None and root.right is None:\n return [sum(root.val)]\n left = inner2(root.left)\n if not left or max(left) < limit:\n root.left = None\n right = inner2(root.right)\n if not right or max(right) < limit:\n root.right = None\n res = left + right\n return res\n\n def inner3(root):\n if root is None:\n return\n else:\n root.val = root.val[0]\n inner3(root.left)\n inner3(root.right)\n return\n inner1(head, 0)\n _ = inner2(head)\n inner3(head)\n return head.left", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n\n def generateSumT(node, s):\n if not node:\n return (None, False)\n if not node.left and (not node.right):\n if s >= limit:\n return (node, True)\n else:\n return (None, False)\n isValid = False\n if node.left:\n (node.left, L) = generateSumT(node.left, s + node.left.val)\n isValid |= L\n if node.right:\n (node.right, R) = generateSumT(node.right, s + node.right.val)\n isValid |= R\n if isValid:\n return (node, True)\n else:\n return (None, False)\n (rtn, _) = generateSumT(root, root.val)\n return rtn", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n\n def remove(node, val):\n if not node:\n return val\n l = remove(node.left, node.val + val)\n r = remove(node.right, node.val + val)\n result = 0\n if node.left and node.right:\n result = max(l, r)\n elif node.left:\n result = l\n else:\n result = r\n if l < limit:\n node.left = None\n if r < limit:\n node.right = None\n return result\n val = remove(root, 0)\n return None if val < limit else root", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n if not root:\n return root\n if not root.left and (not root.right):\n return root if root.val >= limit else None\n root.left = self.sufficientSubset(root.left, limit - root.val)\n root.right = self.sufficientSubset(root.right, limit - root.val)\n return root if root.left or root.right else None", "def collect_insufficient_nodes(node, cur_sum, nodes, limit):\n if node is None:\n return 0\n subpath_sums = []\n if node.left:\n subpath_sums.append(collect_insufficient_nodes(node.left, cur_sum + node.val, nodes, limit))\n if node.right:\n subpath_sums.append(collect_insufficient_nodes(node.right, cur_sum + node.val, nodes, limit))\n max_subpath_sum = 0 if not len(subpath_sums) else max(subpath_sums)\n if cur_sum + max_subpath_sum + node.val < limit:\n nodes.append(node)\n return max_subpath_sum + node.val\n\ndef delete_nodes(node, nodes):\n if not node:\n return\n if node.left in nodes:\n node.left = None\n else:\n delete_nodes(node.left, nodes)\n if node.right in nodes:\n node.right = None\n else:\n delete_nodes(node.right, nodes)\n\ndef sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n nodes = []\n collect_insufficient_nodes(root, 0, nodes, limit)\n nodes = set(nodes)\n if root in nodes:\n return None\n delete_nodes(root, nodes)\n return root", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n\n def dfs(node, path_sum):\n if not node:\n return False\n path_sum += node.val\n if not node.left and (not node.right):\n return path_sum >= limit\n left = dfs(node.left, path_sum)\n right = dfs(node.right, path_sum)\n if not left:\n node.left = None\n if not right:\n node.right = None\n return left or right\n result = dfs(root, 0)\n return root if result else None", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n\n def dfs(node, value):\n if not node:\n return False\n value += node.val\n l_side = dfs(node.left, value)\n r_side = dfs(node.right, value)\n if not node.left and (not node.right):\n if value < limit:\n return False\n return True\n if not l_side:\n node.left = None\n if not r_side:\n node.right = None\n if l_side or r_side:\n return True\n return False\n if dfs(root, 0):\n return root\n return", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n if root == None:\n return None\n\n def dfs(root, val):\n if root == None:\n return (-10000000000.0, 'nodel')\n if root:\n (left_val, left_del_str) = dfs(root.left, val + root.val)\n (right_val, right_del_str) = dfs(root.right, val + root.val)\n if root.left and root.right:\n cur_val = val + root.val + max(left_val, right_val)\n elif root.left:\n cur_val = val + root.val + left_val\n elif root.right:\n cur_val = val + root.val + right_val\n else:\n cur_val = val + root.val\n if left_del_str == 'del':\n root.left = None\n if right_del_str == 'del':\n root.right = None\n if cur_val < limit:\n return (cur_val - val, 'del')\n else:\n return (cur_val - val, 'nodel')\n (_, root_del_str) = dfs(root, 0)\n if root_del_str == 'del':\n return None\n else:\n return root", "def sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n if root == None:\n return None\n canRootLeft = self.validSubtree(root.left, limit, root.val)\n canRootRight = self.validSubtree(root.right, limit, root.val)\n root.left = root.left if canRootLeft else None\n root.right = root.right if canRootRight else None\n if not canRootLeft and (not canRootRight):\n return None\n else:\n return root\n\ndef validSubtree(node: TreeNode, limit: int, currentVal: int) -> bool:\n if node == None:\n return currentVal >= limit\n canLeft = self.validSubtree(node.left, limit, node.val + currentVal)\n canRight = self.validSubtree(node.right, limit, node.val + currentVal)\n if node.left and (not node.right):\n canRight = canLeft\n elif node.right and (not node.left):\n canLeft = canRight\n node.left = node.left if canLeft else None\n node.right = node.right if canRight else None\n if not canLeft and (not canRight):\n return False\n else:\n return canLeft or canRight", "def helper(root, total, limit):\n if not root:\n return False\n if root.left == None and root.right == None:\n return total + root.val >= limit\n left = self.helper(root.left, total + root.val, limit)\n right = self.helper(root.right, total + root.val, limit)\n if not left:\n root.left = None\n if not right:\n root.right = None\n return left or right\n\ndef sufficientSubset(root: TreeNode, limit: int) -> TreeNode:\n if self.helper(root, 0, limit):\n return root\n else:\n return None"], "starter_code": "def __init__(val=0, left=None, right=None):\n", "input_output": {"inputs": [], "outputs": []}, "difficulty": "MEDIUM", "raw_tags": ["Binary Tree", "Tree", "Depth-First Search"], "name": null, "source": "leetcode", "tags": ["Tree algorithms", "Graph traversal"], "skill_types": [], "url": "https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "__init__", "task_id": "TACO_lite/369", "example": [[], []]} +{"requirement": "A Madhav array has the following property:\n\n```a[0] = a[1] + a[2] = a[3] + a[4] + a[5] = a[6] + a[7] + a[8] + a[9] = ...```\n\nComplete the function/method that returns `true` if the given array is a Madhav array, otherwise it returns `false`.\n\n*Edge cases: An array of length* `0` *or* `1` *should not be considered a Madhav array as there is nothing to compare.*", "solutions": ["def is_madhav_array(arr):\n nTerms = ((1 + 8 * len(arr)) ** 0.5 - 1) / 2\n return len(arr) > 1 and (not nTerms % 1) and (len({sum(arr[int(i * (i + 1) // 2):int(i * (i + 1) // 2) + i + 1]) for i in range(int(nTerms))}) == 1)", "def is_madhav_array(arr):\n p = 1\n c = 2\n while p < len(arr) and arr[0] == sum(arr[p:p + c]):\n p += c\n c += 1\n return p == len(arr) > 1", "def is_madhav_array(arr):\n\n def check(a, n=1):\n return True if len(a) == n else sum(a[:n]) == sum(a[n:2 * n + 1]) and check(a[n:], n + 1)\n return False if len(arr) <= 1 else check(arr)", "def is_madhav_array(arr):\n if len(arr) < 3:\n return False\n (i, n) = (0, 1)\n value = arr[0]\n while i + n <= len(arr):\n if sum(arr[i:i + n]) != value:\n return False\n i += n\n n += 1\n return i == len(arr)", "t = [i * (i - 1) // 2 for i in range(3, 1000)]\n\ndef is_madhav_array(arr):\n if len(arr) not in t:\n return False\n sums = {arr[0], arr[1] + arr[2]}\n for (i, j) in zip(t, t[1:]):\n if j > len(arr):\n break\n sums.add(sum(arr[i:j]))\n return len(sums) == 1", "def is_madhav_array(arr):\n if len(arr) < 2:\n return False\n x = 1 + 8 * len(arr)\n if int(x ** 0.5) ** 2 != x:\n return False\n y = (int(x ** 0.5) - 1) // 2\n s = arr[0]\n for i in range(2, y + 1):\n j = i * (i - 1) // 2\n if sum(arr[j:j + i]) != s:\n return False\n return True", "def is_madhav_array(arr):\n if len(arr) <= 2:\n return False\n (i, k) = (0, 1)\n while i + k <= len(arr):\n if arr[0] != sum(arr[i:i + k]):\n return False\n if i + k == len(arr):\n return True\n i += k\n k += 1\n return False", "def is_madhav_array(arr):\n (r, x, c) = ([], 1, len(arr))\n try:\n while arr:\n t = 0\n for i in range(x):\n t += arr.pop(0)\n r.append(t)\n x += 1\n return len(set(r)) == 1 and c > 1\n except:\n return False"], "starter_code": "def is_madhav_array(arr):\n", "input_output": {"fn_name": "is_madhav_array", "inputs": [[[6, 2, 4, 2, 2, 2, 1, 5, 0, 0]], [[6, 2, 4, 2, 2, 2, 1, 5, 0, -100]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, -2, -1]], [[-6, -3, -3, 8, -5, -4]], [[-6, -3, -3, 8, -10, -4]], [[3, 1, 2, 3, 0]], [[3, 3]], [[]], [[1]], [[5, 2, 4, 1, 0, 3]], [[6, 2, 4, 2, 2, 2, 1, 5, 0, 0, -12, 13, -5, 4, 6]], [[6, 2, 4, 2, 2, 2, 1, 5, 0, 0, -12, 13, -5, 4, 1]], [[2, 1, 1]], [[2, 1, 1, 4, -1, -1]]], "outputs": [[true], [false], [true], [false], [true], [false], [false], [false], [false], [false], [true], [false], [true], [true]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/59b0492f7d3c9d7d4a0000bd", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_madhav_array", "task_id": "TACO_lite/382", "example": [[], []]} +{"requirement": "# Description\n\nWrite a function that accepts the current position of a knight in a chess board, it returns the possible positions that it will end up after 1 move. The resulted should be sorted. \n\n## Example\n\n\"a1\" -> [\"b3\", \"c2\"]", "solutions": ["def possible_positions(p):\n (r, c) = (ord(p[0]) - 96, int(p[1]))\n moves = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]\n return [''.join((chr(r + i + 96), str(c + j))) for (i, j) in moves if 1 <= r + i <= 8 and 1 <= c + j <= 8]", "def possible_positions(pos):\n col = 'abcdefgh'\n row = '12345678'\n ret = []\n dir = [[1, 2], [1, -2], [-1, 2], [-1, -2], [2, 1], [2, -1], [-2, 1], [-2, -1]]\n (c, r) = (pos[0], pos[1])\n for d in dir:\n x = col.index(c) + d[0]\n y = row.index(r) + d[1]\n if 0 <= x < 8 and 0 <= y < 8:\n ret.append(''.join([col[x], row[y]]))\n return sorted(ret)", "import string\nKNIGHT = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]\nBOARD_SIZE = 8\n\ndef moves(x, y, directions):\n for (dx, dy) in directions:\n (x2, y2) = (x + dx, y + dy)\n if 0 <= x2 < BOARD_SIZE > y2 >= 0:\n yield (x2, y2)\n\ndef possible_positions(pos):\n (x, y) = (string.ascii_lowercase.find(pos[0]), int(pos[1]) - 1)\n return [f'{string.ascii_lowercase[x]}{y + 1}' for (x, y) in moves(x, y, KNIGHT)]", "def possible_positions(pos):\n board = [[r + str(c) for c in range(1, 9)] for r in 'abcdefgh']\n (x, y) = (ord(pos[0]) - 97, int(pos[1]) - 1)\n return sorted([board[py][px] for (py, px) in [(x + 2, y + 1), (x + 2, y - 1), (x - 2, y + 1), (x - 2, y - 1), (x + 1, y + 2), (x + 1, y - 2), (x - 1, y + 2), (x - 1, y - 2)] if 0 <= px < 8 and 0 <= py < 8])", "def possible_positions(pos):\n moves = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]\n res = []\n for m in moves:\n let = chr(ord(pos[0]) + m[0])\n num = int(pos[1]) + m[1]\n if let in 'abcdefgh' and 0 < num < 9:\n res.append(let + str(num))\n return res", "def possible_positions(pos):\n abc = 'abcdefgh'\n (x, y) = (abc.index(pos[0]), int(pos[1]))\n l = [[x + 2, y - 1], [x + 2, y + 1], [x - 2, y - 1], [x - 2, y + 1], [x - 1, y + 2], [x + 1, y + 2], [x - 1, y - 2], [x + 1, y - 2]]\n m = sorted(filter(lambda x: 0 <= x[0] <= 7 and 1 <= x[1] <= 8, l), key=lambda x: (x[0], x[1]))\n return list(map(lambda x: ''.join([abc[x[0]], str(x[1])]), m))", "moves = ((-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1))\n\ndef possible_positions(pos):\n (x, y) = (ord(pos[0]) - 96, int(pos[1]))\n return [f'{chr(96 + x + i)}{y + j}' for (i, j) in moves if -i < x < 9 - i and -j < y < 9 - j]", "to_coords = lambda s: (ord(s[0]) - 96, int(s[1]))\nfrom_coords = lambda i, j: f'{chr(i + 96)}{j}'\nL = ((1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1))\n\ndef possible_positions(pos):\n (i, j) = to_coords(pos)\n return sorted((from_coords(i + k, j + l) for (k, l) in L if 0 < i + k <= 8 and 0 < j + l <= 8))", "possible_positions = lambda p, m='abcdefgh': (lambda x, y: sorted([m[e[0] + x] + str(e[1] + y) for e in [(-2, 1), (-1, 2), (1, 2), (2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1)] if 8 > e[0] + x >= 0 and 9 > e[1] + y > 0]))(m.find(p[0]), int(p[1]))", "def possible_positions(pos):\n (rows, cols) = ('abcdefgh', '12345678')\n row = rows.index(pos[0])\n col = cols.index(pos[1])\n M = [(a, b) for a in [1, -1] for b in [2, -2]]\n P = [(row + rr, col + cc) for (rr, cc) in M + [e[::-1] for e in M]]\n return sorted((rows[r] + cols[c] for (r, c) in P if 0 <= r <= 7 and 0 <= c <= 7))"], "starter_code": "def possible_positions(pos):\n", "input_output": {"fn_name": "possible_positions", "inputs": [["a1"], ["f7"], ["c3"]], "outputs": [[["b3", "c2"]], [["d6", "d8", "e5", "g5", "h6", "h8"]], [["a2", "a4", "b1", "b5", "d1", "d5", "e2", "e4"]]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5b5736abf1d553f844000050", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "possible_positions", "task_id": "TACO_lite/523", "example": [[["a1"]], ["['b3', 'c2']"]]} +{"requirement": "Write a function to calculate compound tax using the following table:\n\nFor $10 and under, the tax rate should be 10%.\nFor $20 and under, the tax rate on the first $10 is %10, and the tax on the rest is 7%.\nFor $30 and under, the tax rate on the first $10 is still %10, the rate for the next $10 is still 7%, and everything else is 5%.\nTack on an additional 3% for the portion of the total above $30.\nReturn 0 for invalid input(anything that's not a positive real number).\n\n\nExamples:\n\nAn input of 10, should return 1 (1 is 10% of 10)\nAn input of 21, should return 1.75 (10% of 10 + 7% of 10 + 5% of 1)\n\n* Note that the returned value should be rounded to the nearest penny.", "solutions": ["def tax_calculator(total):\n if not isinstance(total, (int, float)) or total < 0:\n return 0\n tax = 0\n if total > 30:\n tax = 2.2 + (total - 30) * 0.03\n elif total > 20:\n tax = 1.7 + (total - 20) * 0.05\n elif total > 10:\n tax = 1 + (total - 10) * 0.07\n elif total > 0:\n tax = total / 10.0\n return round(tax, 2)", "def tax_calculator(total):\n tax = 0\n if type(total) in (float, int) and total > 0:\n for (limit, rate) in ((30, 3), (20, 5), (10, 7), (0, 10)):\n if total > limit:\n tax += rate * (total - limit)\n total = limit\n return round(tax) / 100", "rates = ((30, 0.03), (20, 0.05), (10, 0.07), (0, 0.1))\n\ndef tax_calculator(total):\n if type(total) in (int, float) and total > 0:\n amount = 0\n for (limit, rate) in rates:\n if total > limit:\n amount += (total - limit) * rate\n total = limit\n return round(amount, 2)\n return 0", "def tax_calculator(total):\n if not isinstance(total, (int, float)) or total <= 0:\n return 0\n bands = [(10, 0.1), (10, 0.07), (10, 0.05), (None, 0.03)]\n residue = total\n tax = 0\n for (band_width, rate) in bands:\n if residue == 0:\n break\n if band_width is not None:\n chunk = residue if residue <= band_width else band_width\n else:\n chunk = residue\n tax += chunk * rate\n residue -= chunk\n return round(tax, 2)", "def tax_calculator(total):\n try:\n total = max(float(total), 0)\n except (AttributeError, TypeError, ValueError):\n total = 0\n tax = 0\n for (rate, limit) in [(0.1, 10), (0.07, 10), (0.05, 10), (0.03, 99999999999999)]:\n tax += min(total, limit) * rate\n total -= limit\n if total <= 0:\n break\n return round(tax, 2)", "from numbers import Real\ntax_calculator = TaxCalculator([(10.0, 0.1), (20.0, 0.07), (30.0, 0.05)], 0.03)\n\ndef __init__(bands, highest_rate):\n self.__table = list(self._get_table(bands, highest_rate))\n\ndef _get_table(bands, highest_rate):\n (lower_bound, cumulative_tax) = (0.0, 0.0)\n for (upper_bound, rate) in bands:\n yield (lower_bound, rate, cumulative_tax)\n cumulative_tax += (upper_bound - lower_bound) * rate\n lower_bound = upper_bound\n yield (lower_bound, highest_rate, cumulative_tax)\n\ndef __call__(amount):\n if isinstance(amount, Real):\n for (lower_bound, rate, cumulative_tax) in reversed(self.__table):\n if amount >= lower_bound:\n return round((amount - lower_bound) * rate + cumulative_tax, 2)\n return 0.0", "def tax_calculator(total):\n if type(total) not in [int, float] or total < 0:\n return 0\n if total <= 10:\n tax = 0.1 * total\n elif total <= 20:\n tax = 1 + 0.07 * (total - 10)\n else:\n tax = 1.7 + 0.05 * min(total - 20, 10)\n if total > 30:\n tax += 0.03 * (total - 30)\n return round(tax, 2)", "def tax_calculator(t):\n return isinstance(t, (float, int)) and round(max(0, t) * 0.1 - max(0, t - 10) * 0.03 - max(0, t - 20) * 0.02 - max(0, t - 30) * 0.02, 2)", "tax_calculator = lambda total: round((total - 30) * 0.03 + 2.2 if total - 30 > 0 else (total - 20) * 0.05 + 1.7 if total - 20 > 0 else (total - 10) * 0.07 + 1 if total - 10 > 0 else total * 0.1, 2) if (type(total) == int or type(total) == float) and total > 0 else 0"], "starter_code": "def tax_calculator(total):\n", "input_output": {"fn_name": "tax_calculator", "inputs": [[1], [10], [11], [15], [18], [21], [26], [30], [30.49], [35], [100], [1000000], [0], [-3], [null], ["monkey"], [[]], [{}]], "outputs": [[0.1], [1], [1.07], [1.35], [1.56], [1.75], [2], [2.2], [2.21], [2.35], [4.3], [30001.3], [0], [0], [0], [0], [0], [0]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56314d3c326bbcf386000007", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "tax_calculator", "task_id": "TACO_lite/495", "example": [[[10], [21]], [1.0, 1.75]]} +{"requirement": "You are going to be given a string. Your job is to return that string in a certain order that I will explain below:\n\nLet's say you start with this: `012345`\n\nThe first thing you do is reverse it:`543210` \nThen you will take the string from the 1st position and reverse it again:`501234` \nThen you will take the string from the 2nd position and reverse it again:`504321` \nThen you will take the string from the 3rd position and reverse it again:`504123`\n\nContinue this pattern until you have done every single position, and then you will return the string you have created. For this particular number, you would return:`504132`\n\n#Input:\nA string of length 1 - 1000\n\n#Output:\nA correctly reordered string.", "solutions": ["def reverse_fun(n):\n for i in range(len(n)):\n n = n[:i] + n[i:][::-1]\n return n", "def reverse_fun(n):\n l = len(n)\n return ''.join((b + a for (a, b) in zip(list(n[:l // 2]) + [''], n[l // 2:][::-1])))", "def reverse_fun(n, first=False):\n return '' if len(n) < 1 else n[0] + reverse_fun(n[1:]) if first else n[-1] + reverse_fun(n[:-1], True)", "from itertools import zip_longest\n\ndef merge(sequences, fillvalue=None):\n for slice in zip_longest(*sequences, fillvalue=fillvalue):\n for item in slice:\n yield item\n\ndef reverse_fun(text):\n mid = len(text) // 2\n return ''.join(merge((text[:mid - 1:-1], text[:mid]), fillvalue=''))", "def reverse_fun(n):\n string = ''\n for i in range(len(n)):\n string += n[::-1][0]\n n = n[::-1][1:]\n return string", "from itertools import chain, zip_longest\n\ndef reverse_fun(n):\n l = len(n) >> 1\n return ''.join(chain.from_iterable(zip_longest(n[:l - 1:-1], n[:l], fillvalue='')))", "def reverse_fun(n):\n from collections import deque as dq\n n = dq(n)\n n_dq = dq()\n for i in range(len(n)):\n if i == 0 or i % 2 == 0:\n n_dq.append(n.pop())\n elif i % 2 != 0:\n n_dq.append(n.popleft())\n return ''.join(n_dq)", "def reverse_fun(arr):\n for i in range(len(arr)):\n arr = arr[0:i] + arr[i:][::-1]\n return arr"], "starter_code": "def reverse_fun(n):\n", "input_output": {"fn_name": "reverse_fun", "inputs": [["012"], ["012345"], ["0123456789"], ["Hello"]], "outputs": [["201"], ["504132"], ["9081726354"], ["oHlel"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Algorithms"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/566efcfbf521a3cfd2000056", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "reverse_fun", "task_id": "TACO_lite/498", "example": [[["012345"]], ["504132"]]} +{"requirement": "This is a very simply formulated task. Let's call an integer number `N` 'green' if `N\u00b2` ends with all of the digits of `N`. Some examples:\n\n`5` is green, because `5\u00b2 = 25` and `25` ends with `5`.\n\n`11` is not green, because `11\u00b2 = 121` and `121` does not end with `11`.\n\n`376` is green, because `376\u00b2 = 141376` and `141376` ends with `376`.\n\nYour task is to write a function `green` that returns `n`th green number, starting with `1` - `green (1) == 1`\n\n---\n\n## Data range\n\n```if:haskell\n`n <= 4000` for Haskell\n```\n```if:java\n`n <= 5000` for Java\n```\n```if:python\n`n <= 5000` for Python\n```\n```if:javascript\n`n <= 3000` for JavaScript\n\nReturn values should be `String`s, and should be exact. A BigNum library is recommended.\n```", "solutions": ["out = [1, 5, 6]\n\ndef green(n):\n f = 5\n s = 6\n q = 1\n while n >= len(out):\n q = 10 * q\n f = f ** 2 % q\n s = (1 - (s - 1) ** 2) % q\n out.extend(sorted((j for j in [f, s] if j not in out)))\n return out[n - 1]", "def green(n):\n vec = [1, 5, 6]\n m1 = 5\n m2 = 6\n tot = 3\n h = 0\n while tot < n:\n s1 = str(m1)\n s2 = str(m2)\n m1 = morph(m1)\n m2 = morph(m2)\n (tot, vec, h) = recover(str(m1), s1, str(m2), s2, vec, tot, h)\n vec.sort()\n return vec[n - 1]\n\ndef recover(p, s, r, q, vec, tot, h):\n d = len(p) - len(s)\n d2 = len(r) - len(q)\n for i in range(0, d):\n if p[d - 1 - i] != '0':\n vec.append(int(p[d - 1 - i:d] + s))\n tot += 1\n if r[d2 - 1 - i + h] != '0':\n vec.append(int(r[d2 - 1 - i + h:d2 + h] + q[h:]))\n tot += 1\n return (tot, vec, len(r) - len(p))\n\ndef morph(m):\n return (3 * m * m - 2 * m * m * m) % 10 ** (2 * len(str(m)))", "GREENS = [0, 1, 5, 6]\n(a, b) = GREENS[-2:]\nbase = 10\n\ndef is_green(n):\n return n * n % (base * 10) == n\nwhile len(GREENS) <= 5000:\n for x in range(base, base * 10, base):\n (a_, b_) = (x + a, x + b)\n if a < base and is_green(a_):\n GREENS.append(a_)\n a = a_\n if b < base and is_green(b_):\n GREENS.append(b_)\n b = b_\n base *= 10\n\ndef green(n):\n return GREENS[n]", "import functools\n\ndef automorphic(p):\n t = 1\n n = 5\n k = 1\n res = [1]\n for i in range(1, p + 1):\n size = 2 ** i\n n = (3 * n ** 2 - 2 * n ** 3) % 10 ** size\n for j in range(k, size + 1):\n m5 = n % 10 ** j\n m6 = 10 ** j + 1 - m5\n res.append(m5)\n res.append(m6)\n return sorted(list(set(res)))\n\ndef greent():\n res = automorphic(13)\n return res\n\ndef green(arg):\n return greent()[arg - 1]", "from itertools import chain\n_A018247 = 5507892033556035791371792629100237682598738962094476369972059049452967441587235634931674339622473574280821288168320446695679536039427053255909563977956500647500412691563755880886167774411122846515042057934210324478787281919538790000999616163222123020708764047374316493711188552949294878761965336956393647858527684320631232701555116292227575140464720491283762688439233984347879300562313950958674740106476704211178477509147003836984296147755270995029269684109343202879183739584798683715241551429647234717808588582623277297576686008949743753409688387939096222728882689374022112371252012273120606174751574751537381989074240665252066611148827637678947177773960015235903946894098140630385847547907319150251760258945788659491966429549908540773478285449868640866567399269578082162283572603026954569487924380165488488051064862760620827164159132523609790500938385405426324719893931802209823600162545177681029159396504506657809033052772198385286341879645511424748536307235457049044509125214234275955491843973984458712528694819826927029255264834903206526851272202961318699947776535481291519857640422968183091773445277723200737603825883172729279563657419014445235954319103063572496178988203175787761062137708080967811374931911766563031490205784352509572880668464121069252802275061298511616206384006778979402449023875111258689534549514888200678667702341002839549282970286447273625217535443197911855068157264858804852673871684804002188529473022223344541221328464844153593793663133604458940328723478401947357560361346212008675373346913314338717350880212600285752985386643931022326553454776845029957025561658143370236502074744856814787872902092412582905301249124668868351587677499891768678715728134940879276894529797097772305403356618828198702210630557967239806611190197744642421025136748701117131278125400133690086034889084364023875765936821979626181917833520492704199324875237825867148278905344897440142612317035699548419499444610608146207254036559998271588356035049327795540741961849280952093753026852390937562839148571612367351970609224242398777007574955787271559767413458997537695515862718887941516307569668816352155048898271704378508028434084412644126821848514157729916034497017892335796684991447389566001932545827678000618329854426232827257556110733160697015864984222291255485729879337147866323172405515756102352543994999345608083801190741530060056055744818709692785099775918050075416428527708162011350246806058163276171676765260937528056844214486193960499834472806721906670417240094234466197812426690787535944616698508064636137166384049029219341881909581659524477861846140912878298438431703248173428886572737663146519104988029447960814673760503957196893714671801375619055462996814764263903953007319108169802938509890062166509580863811000557423423230896109004106619977392256259918212890625\n_AUTOMORPHICS = [0, 1] + sorted(set(chain.from_iterable(((_A018247 % 10 ** i, 10 ** i + 1 - _A018247 % 10 ** i) for i in range(1, 2780)))))\ngreen = _AUTOMORPHICS.__getitem__", "(i, j, k, n) = (5, 6, 1, 0)\nl = [1]\nwhile n < 5000:\n k = 10 * k\n i = i ** 2 % k\n j = (1 - (j - 1) ** 2) % k\n l.extend(sorted((x for x in [i, j] if x not in l)))\n n = n + 1\n\ndef green(n):\n return l[n - 1]", "def green(n):\n if n < 6:\n return [1, 5, 6, 25, 76][n - 1]\n nums = ['25', '376']\n ads = ['0', '0', '0', '0', '0', '6', '9', '90', '10', '8', '7', '2', '1', '8', '2', '7', '8', '1', '8', '1', '9', '400', '9', '5', '7', '2', '6', '3', '4', '5', '7', '2', '2', '7', '9', '60', '3', '7', '2', '2', '7', '800', '9', '9', '1', '6', '3', '3', '6', '9', '10', '8', '4', '5', '900', '9', '9', '90', '10', '8', '6', '3', '10', '9', '8', '9', '30', '6', '2', '7', '3', '6', '2', '7', '4', '5', '3', '6', '2', '7', '4', '5', '7', '2', '4', '5', '4', '5', '9', '1000', '9', '9', '8', '1', '8', '8', '1', '6', '3', '6', '3', '1', '8', '9', '80', '1', '4', '5', '90', '9', '50', '4', '3', '6', '3', '6', '8', '1', '2', '7', '6', '3', '9', '900', '9', '10', '8', '90', '9', '50', '4', '1', '8', '6', '3', '9', '70', '2', '80', '9', '1', '30', '9', '6', '8', '1', '8', '1', '9', '10', '8', '9', '80', '1', '3', '6', '7', '2', '9', '300', '9', '6', '5', '4', '60', '9', '3', '90', '9', '60', '3', '6', '3', '7', '2', '4', '5', '6', '3', '2', '7', '5', '4', '1', '8', '8', '1', '3', '6', '700', '9', '9', '2', '6', '3', '5', '4', '5', '4', '4', '5', '9', '90', '80', '1', '6', '3', '4', '5', '2', '7', '6', '3', '1', '8', '80', '9', '1', '8', '1', '7', '2', '3', '6', '5', '4', '1', '8', '7', '2', '6', '3', '9', '10', '8', '3', '6', '80', '9', '1', '7', '2', '4', '5', '60', '9', '3', '50', '9', '4', '9', '60', '3', '2', '7', '6', '3', '7', '2', '3', '6', '5', '4', '1', '8', '8', '1', '9', '60', '3', '20', '9', '7', '5', '4', '4', '5', '9', '70', '2', '80', '9', '1', '1', '8', '50', '9', '4', '10', '9', '8', '9', '80', '1', '5', '4', '3', '6', '5', '4', '1', '8', '3', '6', '6', '3', '3', '6', '2', '7', '6', '3', '7', '2', '7', '2', '7', '2', '4', '5', '3', '6', '1', '8', '1', '8', '1', '8', '7', '2', '4', '5', '3', '6', '7', '2', '8', '1', '8', '1', '5', '4', '2', '7', '3', '6', '70', '9', '2', '8', '1', '3', '6', '4', '5', '8', '1', '6', '3', '4', '5', '8', '1', '70', '9', '2', '8', '1', '2', '7', '1', '8', '7', '2', '1', '8', '9', '90', '40', '5', '1', '8', '6', '3', '5', '4', '8', '1', '8', '1', '6', '3', '1', '8', '2', '7', '2', '7', '5', '4', '4', '5', '2', '7', '5', '4', '40', '9', '5', '3', '6', '8', '1', '8', '1', '4', '5', '90', '9', '90', '80', '1', '8', '1', '1', '8', '8', '1', '4', '5', '3', '6', '9', '80', '1', '2', '7', '9', '70', '2', '90', '9', '50', '4', '40', '9', '5', '8', '1', '6', '3', '6', '3', '3', '6', '8', '1', '7', '2', '6', '3', '1', '8', '6', '3', '6', '3', '6', '3', '5', '4', '6', '3', '9', '80', '1', '9', '50', '4', '1', '8', '30', '9', '6', '3', '6', '8', '1', '6', '3', '5', '4', '4', '5', '9', '40', '5', '6', '3', '5', '4', '2', '7', '1', '8', '2', '7', '9', '90', '30', '6', '3', '6', '7', '2', '4', '5', '2', '7', '1', '8', '8', '1', '2', '7', '80', '9', '1', '6', '3', '3', '6', '5', '4', '4', '5', '3', '6', '2', '7', '4', '5', '9', '90', '400', '9', '5', '2', '7', '7', '2', '8', '1', '4', '5', '70', '9', '2', '3', '6', '3', '6', '9', '90', '80', '1', '2', '7', '7', '2', '3', '6', '9', '80', '1', '7', '2', '7', '2', '5', '4', '4', '5', '3', '6', '8', '1', '500', '9', '9', '4', '60', '9', '3', '60', '9', '3', '9', '80', '1', '6', '3', '1', '8', '5', '4', '4', '5', '1', '8', '2', '7', '4', '5', '4', '5', '8', '1', '3', '6', '4', '5', '9', '80', '1', '7', '2', '5', '4', '2', '7', '6', '3', '9', '90', '60', '3', '7', '2', '5', '4', '3', '6', '2', '7', '3', '6', '2', '7', '3', '6', '8', '1', '7', '2', '8', '1', '6', '3', '2', '7', '7', '2', '3', '6', '6', '3', '8', '1', '8', '1', '4', '5', '9', '60', '3', '9', '80', '1', '3', '6', '5', '4', '2', '7', '50', '9', '4', '6', '3', '1', '8', '1', '8', '20', '9', '7', '6', '3', '8', '1', '8', '1', '9', '70', '2', '2', '7', '7', '2', '5', '4', '1', '8', '7', '2', '4', '5', '6', '3', '8', '1', '4', '5', '5', '4', '2', '7', '9', '500', '9', '4', '9', '80', '1', '8', '1', '9', '40', '5', '2', '7', '2', '7', '900', '9', '9', '50', '4', '1', '8', '2', '7', '7', '2', '9', '30', '6', '90', '9', '70', '2', '1', '8', '8', '1', '8', '1', '5', '4', '4', '5', '7', '2', '4', '5', '4', '5', '9', '60', '3', '4', '5', '9', '600', '9', '3', '9', '300', '9', '6', '5', '4', '8', '1', '4', '5', '7', '2', '9', '90', '80', '1', '1', '8', '80', '9', '1', '6', '3', '8', '1', '9', '80', '1', '9', '60', '3', '4', '5', '5', '4', '3', '6', '9', '5000', '9', '9', '4', '9', '600', '9', '3', '4', '5', '5', '4', '7', '2', '5', '4', '6', '3', '2', '7', '10', '9', '8', '6', '3', '4', '5', '2', '7', '4', '5', '8', '1', '5', '4', '4', '5', '9', '40', '5', '2', '7', '7', '2', '8', '1', '3', '6', '2', '7', '3', '6', '6', '3', '3', '6', '1', '8', '2', '7', '5', '4', '1', '8', '7', '2', '6', '3', '3', '6', '9', '20', '7', '1', '8', '70', '9', '2', '7', '2', '4', '5', '1', '8', '5', '4', '5', '4', '4', '5', '7', '2', '1', '8', '9', '70', '2', '2', '7', '2', '7', '2', '7', '4', '5', '8', '1', '50', '9', '4', '6', '3', '1', '8', '4', '5', '8', '1', '70', '9', '2', '30', '9', '6', '9', '60', '3', '8', '1', '3', '6', '3', '6', '7', '2', '9', '10', '8', '1', '8', '6', '3', '4', '5', '4', '5', '2', '7', '4', '5', '7', '2', '7', '2', '7', '2', '8', '1', '7', '2', '3', '6', '2', '7', '6', '3', '7', '2', '4', '5', '4', '5', '5', '4', '1', '8', '70', '9', '2', '3', '6', '8', '1', '8', '1', '6', '3', '9', '8000', '9', '9', '1', '2', '7', '3', '6', '2', '7', '7', '2', '8', '1', '4', '5', '5', '4', '5', '4', '7', '2', '3', '6', '9', '80', '1', '600', '9', '9', '3', '3', '6', '4', '5', '10', '9', '8', '6', '3', '7', '2', '5', '4', '4', '5', '1', '8', '9', '500', '9', '4', '8', '1', '3', '6', '3', '6', '20', '9', '7', '4', '5', '6', '3', '3', '6', '2', '7', '9', '10', '8', '2', '7', '8', '1', '70', '9', '2', '50', '9', '4', '4', '5', '3', '6', '60', '9', '3', '8', '1', '9', '700', '9', '2', '7', '2', '2', '7', '4', '5', '8', '1', '4', '5', '1', '8', '5', '4', '1', '8', '5', '4', '8', '1', '8', '1', '2', '7', '8', '1', '3', '6', '7', '2', '1', '8', '4', '5', '4', '5', '6', '3', '7', '2', '1', '8', '4', '5', '4', '5', '8', '1', '9', '40', '5', '3', '6', '4', '5', '8', '1', '7', '2', '80', '9', '1', '9', '50', '4', '1', '8', '2', '7', '6', '3', '4', '5', '70', '9', '2', '8', '1', '7', '2', '7', '2', '8', '1', '10', '9', '8', '1', '8', '5', '4', '50', '9', '4', '4', '5', '8', '1', '2', '7', '5', '4', '6', '3', '6', '3', '8', '1', '8', '1', '1', '8', '3', '6', '3', '6', '30', '9', '6', '4', '5', '2', '7', '9', '30', '6', '6', '3', '8', '1', '5', '4', '8', '1', '4', '5', '9', '20', '7', '1', '8', '1', '8', '1', '8', '8', '1', '7', '2', '7', '2', '6', '3', '1', '8', '4', '5', '8', '1', '5', '4', '4', '5', '30', '9', '6', '2', '7', '6', '3', '5', '4', '2', '7', '100', '9', '9', '8', '4', '5', '5', '4', '3', '6', '1', '8', '4', '5', '7', '2', '3', '6', '2', '7', '40', '9', '5', '4', '5', '8', '1', '7', '2', '7', '2', '7', '2', '1', '8', '2', '7', '4', '5', '4', '5', '50', '9', '4', '7', '2', '4', '5', '2', '7', '9', '700', '9', '2', '2', '7', '2', '7', '1', '8', '60', '9', '3', '2', '7', '4', '5', '2', '7', '4', '5', '2', '7', '2', '7', '9', '90', '60', '3', '9', '70', '2', '80', '9', '1', '5', '4', '6', '3', '7', '2', '3', '6', '6', '3', '2', '7', '1', '8', '6', '3', '8', '1', '7', '2', '4', '5', '1', '8', '5', '4', '1', '8', '9', '60', '3', '8', '1', '7', '2', '6', '3', '4', '5', '2', '7', '6', '3', '9', '90', '90', '60', '3', '2', '7', '5', '4', '1', '8', '3', '6', '7', '2', '30', '9', '6', '5', '4', '2', '7', '6', '3', '9', '90', '20', '7', '5', '4', '90', '9', '80', '1', '7', '2', '9', '50', '4', '8', '1', '8', '1', '6', '3', '80', '9', '1', '4', '5', '7', '2', '9', '40', '5', '5', '4', '4', '5', '20', '9', '7', '2', '7', '7', '2', '3', '6', '9', '50', '4', '50', '9', '4', '6', '3', '60', '9', '3', '4', '5', '6', '3', '8', '1', '1', '8', '4', '5', '8', '1', '7', '2', '7', '2', '8', '1', '4000', '9', '9', '9', '5', '4', '5', '3', '6', '6', '3', '40', '9', '5', '5', '4', '7', '2', '7', '2', '9', '20', '7', '6', '3', '5', '4', '1', '8', '8', '1', '9', '60', '3', '9', '10', '8', '6', '3', '5', '4', '4', '5', '4', '5', '9', '500', '9', '4', '9', '80', '1', '4', '5', '8', '1', '5', '4', '5', '4', '300', '9', '9', '6', '4', '5', '6', '3', '70', '9', '2', '8', '1', '3', '6', '2', '7', '1', '8', '6', '3', '7', '2', '4', '5', '1', '8', '40', '9', '5', '4', '5', '7', '2', '10', '9', '8', '5', '4', '4', '5', '3', '6', '5', '4', '9', '90', '10', '8', '2', '7', '7', '2', '8', '1', '5', '4', '1', '8', '7', '2', '3', '6', '1', '8', '4', '5', '7', '2', '8', '1', '2', '7', '6', '3', '2', '7', '5', '4', '2', '7', '1', '8', '5', '4', '2', '7', '3', '6', '9', '800', '9', '1', '4', '5', '70', '9', '2', '7', '2', '9', '50', '4', '20', '9', '7', '5', '4', '6', '3', '3', '6', '8', '1', '2', '7', '8', '1', '9', '80', '1', '8', '1', '8', '1', '6', '3', '7', '2', '6', '3', '20', '9', '7', '80', '9', '1', '2', '7', '8', '1', '3', '6', '6', '3', '9', '40', '5', '3', '6', '2', '7', '4', '5', '2', '7', '1', '8', '6', '3', '2', '7', '40', '9', '5', '6', '3', '6', '3', '4', '5', '8', '1', '9', '90', '10', '8', '1', '8', '5', '4', '3', '6', '60', '9', '3', '1', '8', '9', '900', '9', '30', '6', '6', '3', '3', '6', '1', '8', '400', '9', '9', '5', '5', '4', '7', '2', '1', '8', '8', '1', '2', '7', '7', '2', '1', '8', '3', '6', '1', '8', '7', '2', '8', '1', '1', '8', '1', '8', '70', '9', '2', '1', '8', '5', '4', '7', '2', '3', '6', '6', '3', '1', '8', '5', '4', '7', '2', '10', '9', '8', '2', '7', '4', '5', '2', '7', '4', '5', '6', '3', '5', '4', '4', '5', '7', '2', '2', '7', '80', '9', '1', '90', '9', '80', '1', '1', '8', '1', '8', '6', '3', '3', '6', '9', '80', '1', '60', '9', '3', '2', '7', '7', '2', '3', '6', '20', '9', '7', '4', '5', '4', '5', '9', '30', '6', '6', '3', '9', '10', '8', '2', '7', '2', '7', '70', '9', '2', '1', '8', '80', '9', '1', '8', '1', '7', '2', '8', '1', '1', '8', '8', '1', '6', '3', '3', '6', '4', '5', '6', '3', '3', '6', '40', '9', '5', '5', '4', '9', '30', '6', '2', '7', '7', '2', '2', '7', '2', '7', '90', '9', '70', '2', '20', '9', '7', '70', '9', '2', '5', '4', '5', '4', '9', '10', '8', '3', '6', '2', '7', '7', '2', '9', '20', '7', '1', '8', '9', '40', '5', '9', '50', '4', '3', '6', '1', '8', '8', '1', '7', '2', '7', '2', '4', '5', '8', '1', '7', '2', '1', '8', '2', '7', '3', '6', '1', '8', '3', '6', '2', '7', '8', '1', '9', '10', '8', '500', '9', '9', '4', '7', '2', '2', '7', '3', '6', '2', '7', '1', '8', '4', '5', '8', '1', '5', '4', '6', '3', '8', '1', '3', '6', '1', '8', '1', '8', '3', '6', '3', '6', '5', '4', '2', '7', '1', '8', '9', '50', '4', '2', '7', '1', '8', '30', '9', '6', '5', '4', '9', '90', '70', '2', '8', '1', '4', '5', '7', '2', '1', '8', '4', '5', '2', '7', '9', '90', '20', '7', '90', '9', '70', '2', '7', '2', '1', '8', '2', '7', '1', '8', '2', '7', '5', '4', '1', '8', '8', '1', '3', '6', '4', '5', '1', '8', '5', '4', '4', '5', '7', '2', '5', '4', '7', '2', '9', '20', '7', '50', '9', '4', '3', '6', '6', '3', '2', '7', '70', '9', '2', '6', '3', '3', '6', '4', '5', '1', '8', '8', '1', '4', '5', '3', '6', '8', '1', '6', '3', '4', '5', '4', '5', '7', '2', '70', '9', '2', '4', '5', '700', '9', '9', '2', '50', '9', '4', '5', '4', '8', '1', '3', '6', '2', '7', '2', '7', '5', '4', '5', '4', '5', '4', '3', '6', '5', '4', '4', '5', '3', '6', '7', '2', '3', '6', '2', '7', '2', '7', '10', '9', '8', '3', '6', '9', '60', '3', '4', '5', '6', '3', '3', '6', '1', '8', '6', '3', '5', '4', '1', '8', '70', '9', '2', '5', '4', '2', '7', '4', '5', '1', '8', '7', '2', '600', '9', '9', '3', '7', '2', '1', '8', '2', '7', '80', '9', '1', '1', '8', '9', '50', '4', '6', '3', '7', '2', '8', '1', '7', '2', '1', '8', '6', '3', '3', '6', '4', '5', '1', '8', '3', '6', '3', '6', '1', '8', '9', '30', '6', '5', '4', '3', '6', '3', '6', '7', '2', '6', '3', '5', '4', '2', '7', '3', '6', '1', '8', '9', '200', '9', '7', '1', '8', '2', '7', '6', '3', '5', '4', '3', '6', '1', '8', '6', '3', '6', '3', '60', '9', '3', '4', '5', '2', '7', '4', '5', '6', '3', '7', '2', '5', '4', '9', '80', '1', '40', '9', '5', '8', '1', '2', '7', '5', '4', '3', '6', '2', '7', '7', '2', '1', '8', '7', '2', '3', '6', '40', '9', '5', '9', '10', '8', '4', '5', '5', '4', '4', '5', '60', '9', '3', '6', '3', '3', '6', '1', '8', '3', '6', '6', '3', '3', '6', '6', '3', '9', '20', '7', '6', '3', '9', '40', '5', '6', '3', '5', '4', '8', '1', '4', '5', '4', '5', '8', '1', '5', '4', '6', '3', '5', '4', '8', '1', '7', '2', '3', '6', '1', '8', '2', '7', '2', '7', '1', '8', '4', '5', '5', '4', '5', '4', '4', '5', '3', '6', '3', '6', '2', '7', '2', '7', '2', '7', '2', '7', '30', '9', '6', '7', '2', '5', '4', '9', '70', '2', '5', '4', '1', '8', '1', '8', '8', '1', '2', '7', '400', '9', '9', '5', '80', '9', '1', '5', '4', '8', '1', '3', '6', '8', '1', '7', '2', '1', '8', '6', '3', '7', '2', '3', '6', '7', '2', '5', '4', '1', '8', '5', '4', '80', '9', '1', '1', '8', '4', '5', '1', '8', '5', '4', '6', '3', '7', '2', '7', '2', '4', '5', '8', '1', '8', '1', '3', '6', '9', '50', '4', '4', '5', '1', '8', '8', '1', '1', '8', '9', '20', '7', '80', '9', '1', '3', '6', '4', '5', '4', '5', '5', '4', '6', '3', '5', '4', '2', '7', '8', '1', '2', '7', '5', '4', '7', '2', '6', '3', '6', '3', '7', '2', '7', '2', '7', '2', '5', '4', '4', '5', '6', '3', '1', '8', '7', '2', '70', '9', '2', '70', '9', '2', '8', '1', '7', '2', '9', '50', '4', '5', '4', '60', '9', '3', '8', '1', '7', '2', '100', '9', '9', '8', '4', '5', '3', '6', '2', '7', '70', '9', '2', '2', '7', '3', '6', '3', '6', '1', '8', '2', '7', '3', '6', '9', '200', '9', '7', '8', '1', '1', '8', '1', '8', '5', '4', '1', '8', '5', '4', '50', '9', '4', '5', '4', '5', '4', '3', '6', '5', '4', '10', '9', '8', '3', '6', '1', '8', '4', '5', '7', '2', '1', '8', '1', '8', '1', '8', '5', '4', '2', '7', '1', '8', '6', '3', '2', '7', '90', '9', '50', '4', '4', '5', '2', '7', '40', '9', '5', '9', '20', '7', '10', '9', '8', '2', '7', '2', '7', '3', '6', '9', '400', '9', '5', '8', '1', '6', '3', '6', '3', '9', '20', '7', '6', '3', '8', '1', '6', '3', '8', '1', '1', '8', '5', '4', '1', '8', '70', '9', '2', '1', '8', '6', '3', '9', '50', '4', '2', '7', '7', '2', '2', '7', '80', '9', '1', '7', '2', '5', '4', '7', '2', '9', '30', '6', '9', '10', '8', '2', '7', '1', '8', '4', '5', '6', '3', '5', '4', '8', '1', '3', '6', '3', '6', '9', '80', '1', '1', '8', '7', '2', '7', '2', '4', '5', '90', '9', '50', '4', '7', '2', '5', '4', '6', '3', '4', '5', '8', '1', '2', '7', '4', '5', '9', '20', '7', '90', '9', '50', '4', '1', '8', '3', '6', '30', '9', '6', '6', '3', '4', '5', '3', '6', '3', '6', '2', '7', '8', '1', '1', '8', '9', '80', '1', '3', '6', '9', '50', '4', '7', '2', '6', '3', '1', '8', '1', '8', '8', '1', '2', '7', '3', '6', '90', '9', '80', '1', '9', '80', '1', '9', '70', '2', '2', '7', '6', '3', '1', '8', '2', '7', '6', '3', '9', '10', '8', '6', '3', '2', '7', '2', '7', '1', '8', '2', '7', '4', '5', '2', '7', '8', '1', '3', '6', '20', '9', '7', '8', '1', '1', '8', '10', '9', '8', '2', '7', '8', '1', '6', '3', '50', '9', '4', '2', '7', '7', '2', '4', '5', '6', '3', '6', '3', '9', '30', '6', '10', '9', '8', '9', '80', '1', '3', '6', '4', '5', '5', '4', '40', '9', '5', '6', '3', '2', '7', '5', '4', '5', '4', '4', '5', '4', '5', '1', '8', '90', '9', '80', '1', '4', '5', '7', '2', '4', '5', '3', '6', '6', '3', '6', '3', '4', '5', '20', '9', '7', '7', '2', '9', '70', '2', '7', '2', '7', '2', '7', '2', '8', '1', '3', '6', '8', '1', '1', '8', '4', '5', '7', '2', '8', '1', '6', '3', '60', '9', '3', '2', '7', '6', '3', '7', '2', '9', '200', '9', '7', '3', '6', '2', '7', '7', '2', '2', '7', '2', '7', '7', '2', '5', '4', '5', '4', '4', '5', '3', '6', '7', '2', '2', '7', '8', '1', '9', '90', '30', '6', '8', '1', '8', '1', '8', '1', '3', '6', '70', '9', '2', '2', '7', '4', '5', '40', '9', '5', '6', '3', '2', '7', '4', '5', '1', '8', '80', '9', '1', '5', '4', '8', '1', '9', '70', '2', '1', '8', '8', '1', '5', '4', '5', '4', '6', '3', '5', '4', '3', '6', '2', '7', '2', '7', '2', '7', '5', '4', '9', '3000', '9', '9', '6', '1', '8', '8', '1', '3', '6', '1', '8', '6', '3', '70', '9', '2', '20', '9', '7', '2', '7', '7', '2', '7', '2', '1', '8', '5', '4', '1', '8', '3', '6', '7', '2', '5', '4', '3', '6', '9', '20', '7', '3', '6', '90', '9', '50', '4', '3', '6', '8', '1', '5', '4', '6', '3', '7', '2', '5', '4', '4', '5', '7', '2', '9', '70', '2', '70', '9', '2', '7', '2', '9', '30', '6', '7', '2', '8', '1', '80', '9', '1', '8', '1', '5', '4', '9', '30', '6', '1', '8', '7', '2', '5', '4', '7', '2', '1', '8', '7', '2', '1', '8', '4', '5', '5', '4', '4', '5', '8', '1', '60', '9', '3', '7', '2', '60', '9', '3', '4', '5', '8', '1', '8', '1', '9', '50', '4', '5', '4', '4', '5', '40', '9', '5', '2', '7', '7', '2', '4', '5', '3', '6', '2', '7', '4', '5', '1', '8', '2', '7', '5', '4', '7', '2', '1', '8', '9', '90', '50', '4', '5', '4', '4', '5', '90', '9', '50', '4', '70', '9', '2', '4', '5', '5', '4', '5', '4', '6', '3', '2', '7', '7', '2', '9', '30', '6', '6', '3', '6', '3', '5', '4', '1', '8', '5', '4', '7', '2', '5', '4', '2', '7', '4', '5', '1', '8', '1', '8', '5', '4', '4', '5', '5', '4', '6', '3', '20', '9', '7', '1', '8', '8', '1', '4', '5', '3', '6', '6', '3', '1', '8', '7', '2', '5', '4', '1', '8', '6', '3', '8', '1', '80', '9', '1', '2', '7', '7', '2', '2', '7', '7', '2', '5', '4', '9', '30', '6', '3', '6', '90', '9', '90', '80', '1', '2', '7', '4', '5', '3', '6', '3', '6', '9', '50', '4', '5', '4', '50', '9', '4', '3', '6', '60', '9', '3', '9', '40', '5', '8', '1', '9', '70', '2', '10', '9', '8', '8', '1', '3', '6', '2', '7', '2', '7', '8', '1', '5', '4', '5', '4', '5', '4', '7', '2', '6', '3', '8', '1', '600', '9', '9', '3', '6', '3', '2', '7', '8', '1', '90', '9', '20', '7', '2', '7', '80', '9', '1', '8', '1', '3', '6', '9', '60', '3', '9', '10', '8', '80', '9', '1', '7', '2', '5', '4', '2', '7', '3', '6', '6', '3', '7', '2', '4', '5', '5', '4', '9', '40', '5', '5', '4', '1', '8', '6', '3', '8', '1', '6', '3', '9', '90', '500', '9', '4', '9', '90', '20', '7', '90', '9', '60', '3', '6', '3', '2', '7', '5', '4', '7', '2', '3', '6', '1', '8', '9', '40', '5', '8', '1', '4', '5', '6', '3', '8', '1', '7', '2', '7', '2', '8', '1', '9', '20', '7', '6', '3', '9', '60', '3', '2', '7', '7', '2', '6', '3', '1', '8', '5', '4', '6', '3', '9', '10', '8', '5', '4', '9', '80', '1', '1', '8', '5', '4', '8', '1', '1', '8', '5', '4', '5', '4', '3', '6', '8', '1', '80', '9', '1', '6', '3', '4', '5', '2', '7', '9', '20', '7', '1', '8', '5', '4', '9', '30', '6', '4', '5', '5', '4', '5', '4', '30', '9', '6', '7', '2', '30', '9', '6', '60', '9', '3', '7', '2', '7', '2', '4', '5', '6', '3', '8', '1', '7', '2', '2', '7', '6', '3', '8', '1', '2', '7', '8', '1', '9', '80', '1', '2', '7', '4', '5', '30', '9', '6', '7', '2', '9', '600', '9', '3', '7', '2', '3', '6', '4', '5', '3', '6', '3', '6', '1', '8', '9', '40', '5', '6', '3', '1', '8', '3', '6', '1', '8', '50', '9', '4', '4', '5', '5', '4', '1', '8', '7', '2', '8', '1', '2', '7', '5', '4', '3', '6', '7', '2', '2', '7', '9', '40', '5', '5', '4', '1', '8', '9', '90', '500', '9', '4', '5', '4', '70', '9', '2', '4', '5', '6', '3', '3', '6', '80', '9', '1', '9', '50', '4', '9', '40', '5', '3', '6', '1', '8', '1', '8', '2', '7', '4', '5', '5', '4', '9', '10', '8', '4', '5', '7', '2', '60', '9', '3', '2', '7', '8', '1', '5', '4', '7', '2', '50', '9', '4', '8', '1', '9', '80', '1', '3', '6', '7', '2', '9', '90', '20', '7', '5', '4', '5', '4', '2', '7', '5', '4', '8', '1', '4', '5', '1', '8', '6', '3', '30', '9', '6', '6', '3', '9', '40', '5', '1', '8', '8', '1', '90', '9', '40', '5', '9', '10', '8', '3', '6', '5', '4', '9', '60', '3', '90', '9', '40', '5', '6', '3', '2', '7', '5', '4', '8', '1', '600', '9', '9', '3', '60', '9', '3', '7', '2', '2', '7', '2', '7', '2', '7', '8', '1', '7', '2', '5', '4', '9', '10', '8', '2', '7', '3', '6', '2', '7', '6', '3', '6', '3', '2', '7', '7', '2', '8', '1', '1', '8', '5', '4', '1', '8', '1', '8', '1', '8', '6', '3', '3', '6', '3', '6', '9', '20', '7', '5', '4', '7', '2', '5', '4', '3', '6', '3', '6', '9', '40', '5', '2', '7', '4', '5', '7', '2', '9', '90', '10', '8', '80', '9', '1', '8', '1', '6', '3', '7', '2', '6', '3', '5', '4', '8', '1', '5', '4', '2', '7', '5', '4', '7', '2', '4', '5', '8', '1', '5', '4', '2', '7', '5', '4', '7', '2', '8', '1', '6', '3', '9', '60', '3', '9', '20', '7', '1', '8', '3', '6', '7', '2', '7', '2', '2', '7', '1', '8', '20', '9', '7', '5', '4', '7', '2', '1', '8', '7', '2', '6', '3', '2', '7', '1', '8', '1', '8', '2', '7', '2', '7', '40', '9', '5', '7', '2', '6', '3', '9', '10', '8', '3', '6', '7', '2', '8', '1', '1', '8', '1', '8', '7', '2', '7', '2', '7', '2', '2', '7', '2', '7', '6', '3', '90', '9', '90', '60', '3', '9', '20', '7', '1', '8', '6', '3', '8', '1', '1', '8', '3', '6', '90', '9', '40', '5', '3', '6', '5', '4', '2', '7', '6', '3', '4', '5', '7', '2', '50', '9', '4', '9', '10', '8', '9', '600', '9', '3', '1', '8', '3', '6', '3', '6', '2', '7', '4', '5', '2', '7', '70', '9', '2', '7', '2', '2', '7', '7', '2', '3', '6', '2', '7', '6', '3', '7', '2', '8', '1', '4', '5', '1', '8', '1', '8', '4', '5', '1', '8', '9', '80', '1', '2', '7', '8', '1', '7', '2', '5', '4', '3', '6', '2', '7', '7', '2', '5', '4', '6', '3', '70', '9', '2', '4', '5', '1', '8', '5', '4', '4', '5', '8', '1', '4', '5', '2', '7', '5', '4', '8', '1', '7', '2', '6', '3', '8', '1', '3', '6', '1', '8', '20', '9', '7', '5', '4', '8', '1', '4', '5', '60', '9', '3', '7', '2', '6', '3', '8', '1', '8', '1', '9', '20', '7', '1', '8', '7', '2', '20', '9', '7', '3', '6', '4', '5', '3', '6', '9', '90', '10', '8', '4', '5', '8', '1', '3', '6', '30', '9', '6', '7', '2', '9', '70', '2', '50', '9', '4', '900', '9', '9', '70', '2', '7', '2', '5', '4', '4', '5', '2', '7', '2', '7', '5', '4', '1', '8', '6', '3', '70', '9', '2', '4', '5', '8', '1', '30', '9', '6', '6', '3', '8', '1', '6', '3', '700', '9', '9', '2', '5', '4', '1', '8', '9', '90', '50', '4', '2', '7', '2', '7', '5', '4', '8', '1', '2', '7', '8', '1', '1', '8', '1', '8', '2', '7', '4', '5', '70', '9', '2', '3', '6', '2', '7', '5', '4', '6', '3', '9', '10', '8', '40', '9', '5', '7', '2', '5', '4', '7', '2', '3', '6', '1', '8', '4', '5', '90', '9', '50', '4', '60', '9', '3', '1', '8', '3', '6', '2', '7', '6', '3', '4', '5', '9', '300', '9', '6', '9', '20', '7', '1', '8', '2', '7', '5', '4', '3', '6', '4', '5', '8', '1', '60', '9', '3', '3', '6', '2', '7', '9', '60', '3', '4', '5', '8', '1', '1', '8', '3', '6', '7', '2', '6', '3', '2', '7', '6', '3', '8', '1', '7', '2', '1', '8', '9', '50', '4', '20', '9', '7', '7', '2', '5', '4', '6', '3', '5', '4', '40', '9', '5', '1', '8', '5', '4', '2', '7', '4', '5', '2', '7', '7', '2', '2', '7', '2', '7', '9', '70', '2', '6', '3', '8', '1', '1', '8', '5', '4', '4', '5', '4', '5', '8', '1', '70', '9', '2', '7', '2', '3', '6', '2', '7', '1', '8', '3', '6', '6', '3', '9', '20', '7', '3', '6', '4', '5', '8', '1', '3', '6', '2', '7', '7', '2', '5', '4', '1', '8', '4', '5', '1', '8', '2', '7', '5', '4', '6', '3', '6', '3', '9', '60', '3', '6', '3', '4', '5', '30', '9', '6', '6', '3', '3', '6', '5', '4', '3', '6', '80', '9', '1', '6', '3', '2', '7', '1', '8', '2', '7', '1', '8', '5', '4', '9', '70', '2', '9', '50', '4', '9', '70', '2', '5', '4', '4', '5', '1', '8', '1', '8', '8', '1', '1', '8', '1', '8', '7', '2', '6', '3', '9', '50', '4', '6', '3', '8', '1', '3', '6', '4', '5', '7', '2', '6', '3', '7', '2', '5', '4', '40', '9', '5', '6', '3', '2', '7', '1', '8', '9', '70', '2', '9', '20', '7', '30', '9', '6', '2', '7', '1', '8', '2', '7', '2', '7', '2', '7', '3', '6', '6', '3', '8', '1', '6', '3', '8', '1', '6', '3', '9000', '9', '9', '9', '90000', '9', '9', '9', '20', '7', '1', '8', '6', '3', '5', '4', '80', '9', '1', '9', '80', '1', '8', '1', '7', '2', '7', '2', '1', '8', '2', '7', '1', '8', '2', '7', '5', '4', '4', '5', '2', '7', '3', '6', '10', '9', '8', '2', '7', '4', '5', '3', '6', '9', '20', '7', '4', '5', '9', '20', '7', '4', '5', '50', '9', '4', '8', '1', '5', '4', '3', '6', '5', '4', '8', '1', '7', '2', '2', '7', '1', '8', '1', '8', '1', '8', '4', '5', '4', '5', '7', '2', '2', '7', '2', '7', '3', '6', '8', '1', '6', '3', '1', '8', '1', '8', '9', '80', '1', '1', '8', '4', '5', '4', '5', '2', '7', '6', '3', '6', '3', '4', '5', '8', '1', '9', '30', '6', '7', '2', '1', '8', '4', '5', '500', '9', '9', '4', '2', '7', '5', '4', '6', '3', '9', '500', '9', '4', '3', '6', '4', '5', '20', '9', '7', '2', '7', '60', '9', '3', '6', '3', '4', '5', '90', '9', '90', '40', '5', '4', '5', '7', '2', '3', '6', '5', '4', '9', '70', '2', '7', '2', '4', '5', '9', '60', '3', '60', '9', '3', '6', '3', '5', '4', '20', '9', '7', '3', '6', '4', '5', '30', '9', '6', '3', '6', '5', '4', '4', '5', '20', '9', '7', '3', '6', '8', '1', '3', '6', '8', '1', '8', '1', '1', '8', '7', '2', '1', '8', '2', '7', '8', '1', '9', '80', '1', '7', '2', '4', '5', '7', '2', '4', '5', '6', '3', '7', '2', '5', '4', '2', '7', '2', '7', '6', '3', '60', '9', '3', '3', '6', '4', '5', '7', '2', '3', '6', '8', '1', '3', '6', '9', '50', '4', '3', '6', '6', '3', '4', '5', '6', '3', '2', '7', '7', '2', '1', '8', '4', '5', '8', '1', '4', '5', '4', '5', '7', '2', '3', '6', '70', '9', '2', '5', '4', '5', '4', '9', '50', '4', '90', '9', '40', '5', '9', '20', '7', '7', '2', '300', '9', '9', '6', '6', '3', '6', '3', '2', '7', '5', '4', '4', '5', '9', '90', '20', '7', '6', '3', '10', '9', '8', '6', '3', '7', '2', '1', '8', '40', '9', '5', '7', '2', '8', '1', '3', '6', '2', '7', '6', '3', '2', '7', '100', '9', '9', '8', '9', '70', '2', '6', '3', '7', '2', '9', '20', '7', '8', '1', '7', '2', '6', '3', '1', '8', '9', '20', '7', '4', '5', '6', '3', '60', '9', '3', '4', '5', '4', '5', '6', '3', '3', '6', '20', '9', '7', '9', '10', '8', '2', '7', '9', '50', '4', '4', '5']\n count = 5\n while n > count:\n nums[0] = ads[count] + nums[0]\n if len(nums[0]) > len(nums[1]):\n (nums[0], nums[1]) = (nums[1], nums[0])\n elif len(nums[0]) == len(nums[1]):\n nums.sort()\n count += 1\n return int(nums[0])"], "starter_code": "def green(n):\n", "input_output": {"fn_name": "green", "inputs": [[1], [2], [3], [4], [12], [13], [100], [110]], "outputs": [[1], [5], [6], [25], [2890625], [7109376], [6188999442576576769103890995893380022607743740081787109376], [9580863811000557423423230896109004106619977392256259918212890625]]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/584dee06fe9c9aef810001e8", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "green", "task_id": "TACO_lite/528", "example": [[[1]], ["1"]]} +{"requirement": "Given string s containing characters as integers only, the task is to delete all characters of this string in a minimum number of steps wherein one step you can delete the substring which is a palindrome. After deleting a substring remaining parts are concatenated.\nExample 1:\nInput: s = \"2553432\"\nOutput: 2\nExplanation: In first step remove \"55\", \nthen string becomes \"23432\" which is a \npalindrome.\nExample 2:\nInput: s = \"1234\"\nOutput: 4\nExplanation: Remove each character in \neach step\nYour Task: \nYou don't need to read input or print anything. Complete the function minStepToDeleteString() which string s as input parameters and returns the integer value\nExpected Time Complexity: O(|s|^{3})\nExpected Auxiliary Space: O(|s|^{2})\nConstraints:\n1 \u2264 |s| \u2264 10^{3}", "solutions": ["def solve(s, dp, start, end):\n if start > end:\n return 0\n if start == end:\n return 1\n if dp[start][end] != -1:\n return dp[start][end]\n op1 = op2 = op3 = 1000000000.0\n op1 = 1 + self.solve(s, dp, start + 1, end)\n if s[start] == s[start + 1]:\n op2 = 1 + self.solve(s, dp, start + 2, end)\n for i in range(start + 2, end + 1):\n if s[start] == s[i]:\n op3 = min(op3, self.solve(s, dp, start + 1, i - 1) + self.solve(s, dp, i + 1, end))\n dp[start][end] = min(op1, op2, op3)\n return dp[start][end]\n\ndef minsteptodeletestring(s):\n n = len(s)\n dp = [[-1 for _ in range(n)] for _ in range(n)]\n return self.solve(s, dp, 0, n - 1)", "def minsteptodeletestring(str):\n N = len(str)\n dp = [[0 for x in range(N + 1)] for y in range(N + 1)]\n for l in range(1, N + 1):\n i = 0\n j = l - 1\n while j < N:\n if l == 1:\n dp[i][j] = 1\n else:\n dp[i][j] = 1 + dp[i + 1][j]\n if str[i] == str[i + 1]:\n dp[i][j] = min(1 + dp[i + 2][j], dp[i][j])\n for K in range(i + 2, j + 1):\n if str[i] == str[K]:\n dp[i][j] = min(dp[i + 1][K - 1] + dp[K + 1][j], dp[i][j])\n i += 1\n j += 1\n return dp[0][N - 1]", "import sys\nINT_MAX = sys.maxsize\n\ndef min_steps(l, r, s, dp):\n if l > r:\n return 0\n if l == r:\n return 1\n if dp[l][r] != -1:\n return dp[l][r]\n (op1, op2, op3) = (INT_MAX, INT_MAX, INT_MAX)\n op1 = 1 + self.min_steps(l + 1, r, s, dp)\n if s[l] == s[l + 1]:\n op2 = 1 + self.min_steps(l + 2, r, s, dp)\n for i in range(l + 2, r + 1):\n if s[l] == s[i]:\n op3 = min(op3, self.min_steps(l + 1, i - 1, s, dp) + self.min_steps(i + 1, r, s, dp))\n dp[l][r] = min(op1, op2, op3)\n return dp[l][r]\n\ndef minsteptodeletestring(s):\n n = len(s)\n dp = [[-1 for _ in range(n)] for _ in range(n)]\n return self.min_steps(0, n - 1, s, dp)", "import sys\nINT_MAX = sys.maxsize\n\ndef min_steps(i, j, s, dp):\n if i > j:\n return 0\n if i == j:\n return 1\n if dp[i][j] != -1:\n return dp[i][j]\n min_steps = 1 + self.min_steps(i + 1, j, s, dp)\n if s[i] == s[i + 1]:\n min_steps = 1 + min(min_steps, self.min_steps(i + 2, j, s, dp))\n for k in range(i + 2, j + 1):\n if s[i] == s[k]:\n steps = self.min_steps(i + 1, k - 1, s, dp) + self.min_steps(k + 1, j, s, dp)\n min_steps = min(min_steps, steps)\n dp[i][j] = min_steps\n return dp[i][j]\n\ndef minsteptodeletestring(s):\n n = len(s)\n dp = [[-1 for _ in range(n)] for _ in range(n)]\n return self.min_steps(0, n - 1, s, dp)", "def minsteptodeletestring(s):\n n = len(s)\n dp = [[0 for i in range(n + 1)] for j in range(n + 1)]\n for i in range(n):\n dp[i][i] = 1\n j = 1\n while j < n:\n for i in range(n - j):\n dp[i][i + j] = 1 + min(dp[i][i + j - 1], dp[i + 1][i + j])\n for k in range(i + 1, i + j + 1):\n if s[i] == s[k]:\n a = dp[i + 1][k - 1]\n if i + 1 > k - 1:\n a = 1\n b = dp[k + 1][i + j]\n dp[i][i + j] = min(dp[i][i + j], a + b)\n j += 1\n return dp[0][n - 1]", "def minsteptodeletestring(s):\n\n def solve(f, l, d):\n if l < f:\n return 0\n if f == l:\n return 1\n if (f, l) in d:\n return d[f, l]\n (first, second) = (float('inf'), float('inf'))\n first = 1 + solve(f + 1, l, d)\n if s[f] == s[f + 1]:\n second = 1 + solve(f + 2, l, d)\n third = float('inf')\n for i in range(f + 2, l + 1):\n if s[f] == s[i]:\n third = min(third, solve(f + 1, i - 1, d) + solve(i + 1, l, d))\n d[f, l] = min(first, second, third)\n return d[f, l]\n d = {}\n res = solve(0, len(s) - 1, d)\n return res", "def minsteptodeletestring(s):\n n = len(s)\n dp = [[0 for i in range(n + 1)] for i in range(n + 1)]\n for l in range(1, n + 1):\n (i, j) = (0, l - 1)\n while j < n:\n if l == 1:\n dp[i][j] = 1\n else:\n dp[i][j] = 1 + dp[i + 1][j]\n if s[i] == s[i + 1]:\n dp[i][j] = min(1 + dp[i + 2][j], dp[i][j])\n for k in range(i + 2, j + 1):\n if s[i] == s[k]:\n dp[i][j] = min(dp[i + 1][k - 1] + dp[k + 1][j], dp[i][j])\n i += 1\n j += 1\n return dp[0][n - 1]", "import functools\n\ndef minsteptodeletestring(s):\n\n def delete_substring(start_idx, end_idx):\n if start_idx == end_idx:\n return 1\n if start_idx > end_idx:\n return 0\n first_case = delete_substring(start_idx + 1, end_idx) + 1\n second_case = float('inf')\n for idx in range(start_idx + 1, end_idx + 1):\n if s[idx] == s[start_idx]:\n if idx == start_idx + 1:\n second_case = min(second_case, delete_substring(start_idx + 2, end_idx)) + 1\n else:\n second_case = min(second_case, delete_substring(start_idx + 1, idx - 1) + delete_substring(idx + 1, end_idx))\n return min(first_case, second_case)\n return delete_substring(0, len(s) - 1)", "def minsteptodeletestring(s):\n N = len(s)\n dp = [[0 for i in range(N + 1)] for j in range(N + 1)]\n for gap in range(1, N + 1):\n i = 0\n j = gap - 1\n while j < N:\n if gap == 1:\n dp[i][j] = 1\n else:\n dp[i][j] = 1 + dp[i + 1][j]\n if s[i] == s[i + 1]:\n dp[i][j] = min(1 + dp[i + 2][j], dp[i][j])\n for K in range(i + 2, j + 1):\n if s[i] == s[K]:\n dp[i][j] = min(dp[i + 1][K - 1] + dp[K + 1][j], dp[i][j])\n i += 1\n j += 1\n return dp[0][N - 1]", "def minsteptodeletestring(s):\n cache = {}\n\n def dp(i, j):\n if (i, j) in cache:\n return cache[i, j]\n if i > j:\n cache[i, j] = 0\n return cache[i, j]\n if i == j:\n cache[i, j] = 1\n return cache[i, j]\n cache[i, j] = float('inf')\n for k in range(i, j + 1):\n if s[i] == s[k]:\n temp = 1 + dp(k + 1, j) if k - i <= 1 else dp(i + 1, k - 1) + dp(k + 1, j)\n cache[i, j] = min(cache[i, j], temp)\n return cache[i, j]\n return dp(0, len(s) - 1)", "def minsteptodeletestring(s):\n length = len(s)\n if length < 1:\n return 0\n if length < 2:\n return 1\n lookup_min_steps = [[0] * length for i in range(length)]\n for i in range(length):\n lookup_min_steps[i][i] = 1\n for len_str in range(2, length + 1):\n for i in range(0, length - len_str + 1):\n j = i + len_str - 1\n min_steps = length\n min_steps = min(min_steps, lookup_min_steps[i][j - 1] + 1)\n for k in range(i, j):\n if s[k] == s[j]:\n if k == j - 1:\n min_steps = min(min_steps, lookup_min_steps[i][k - 1] + 1)\n else:\n min_steps = min(min_steps, lookup_min_steps[i][k - 1] + lookup_min_steps[k + 1][j - 1])\n lookup_min_steps[i][j] = min_steps\n return lookup_min_steps[0][length - 1]", "def minsteptodeletestring(str1):\n n = len(str1)\n dp = [[0] * (n + 1) for _ in range(n + 1)]\n for l in range(1, n + 1):\n i = 0\n j = l - 1\n while j < n:\n if l == 1:\n dp[i][j] = 1\n else:\n dp[i][j] = 1 + dp[i + 1][j]\n if str1[i] == str1[i + 1]:\n dp[i][j] = min(1 + dp[i + 2][j], dp[i][j])\n for K in range(i + 2, j + 1):\n if str1[i] == str1[K]:\n dp[i][j] = min(dp[i + 1][K - 1] + dp[K + 1][j], dp[i][j])\n i += 1\n j += 1\n return dp[0][n - 1]"], "starter_code": "def minsteptodeletestring(s):\n", "input_output": {"inputs": ["s = \"2553432\"", "s = \"1234\""], "outputs": ["2", "4"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/minimum-steps-to-delete-a-string2956/1", "Expected Auxiliary Space": "O(|s|^{2})", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|s|^{3})", "entry_point": "minsteptodeletestring", "task_id": "TACO_lite/526", "example": [[["2553432"], ["1234"]], ["2", "4"]]} +{"requirement": "Given a binary tree of size N, find all the nodes at odd levels.Root is considered at level 1.\nExample 1:\nInput: \n 1\n / \\\n 2 3\n / \\ \\\n 4 5 6\n / \\ /\n 7 8 9\nOutput 1 4 5 6\nExample 2:\nInput: \n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n \nOutput: 1 4 5 6 7\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function nodesAtOddLevels() which takes root node of the tree as input parameter and returns an list of all the nodes at odd levels in preorder.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 <= Number of nodes <= 10^{3}\n1 <= Data of a node <= 10^{3}", "solutions": ["def nodesAtOddLevels(root):\n q = [root]\n res = []\n lev = 1\n while q:\n l = len(q)\n for i in range(l):\n p = q.pop(0)\n if lev % 2 != 0:\n res.append(p.data)\n if p.left:\n q.append(p.left)\n if p.right:\n q.append(p.right)\n lev += 1\n return res", "from collections import deque\n\ndef nodesAtOddLevels(root):\n queue = deque()\n queue.append(root)\n ans_list = []\n level = 0\n while queue:\n size = len(queue)\n for _ in range(size):\n curr = queue.popleft()\n if level % 2 != 0:\n ans_list.append(curr.data)\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n return ans_list", "def findNodes(root, res, l):\n if root == None:\n return res\n if l % 2 == 1:\n res.append(root)\n findNodes(root.left, res, l + 1)\n findNodes(root.right, res, l + 1)\n return res\n\ndef nodesAtOddLevels(root):\n return findNodes(root, [], 1)", "def fun(root, level, l):\n if root == None:\n return\n if level >= len(l):\n l.append([])\n l[level].append(root.data)\n self.fun(root.left, level + 1, l)\n self.fun(root.right, level + 1, l)\n\ndef nodesAtOddLevels(root):\n l = []\n self.fun(root, 0, l)\n t = []\n for i in range(len(l)):\n if i % 2 == 0:\n t.extend(l[i])\n return t", "def solve(root, dic, l):\n if root == None:\n return\n if l % 2 != 0:\n dic.append(root.data)\n l += 1\n self.solve(root.left, dic, l)\n self.solve(root.right, dic, l)\n l -= 1\n\ndef nodesAtOddLevels(root):\n dic = []\n self.solve(root, dic, 1)\n return dic", "def getNodesFromOddLevel(root, level: int=1):\n if root is None:\n return []\n elif level % 2:\n return [root.data] + self.getNodesFromOddLevel(root.left, level + 1) + self.getNodesFromOddLevel(root.right, level + 1)\n else:\n return self.getNodesFromOddLevel(root.left, level + 1) + self.getNodesFromOddLevel(root.right, level + 1)\n\ndef nodesAtOddLevels(root):\n return self.getNodesFromOddLevel(root, 1)", "def nodesAtOddLevels(root):\n values = []\n queue = [root]\n count = 0\n while queue:\n count += 1\n level = []\n for i in queue:\n if i == None:\n continue\n if count % 2 != 0:\n values.append(i.data)\n level.append(i.left)\n level.append(i.right)\n queue = level\n return values", "def nodesAtOddLevels(root):\n q = [root]\n count = 1\n list = []\n while q:\n if count % 2 != 0:\n for i in q:\n list.append(i.data)\n for _ in range(len(q)):\n node = q.pop(0)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return list", "def nodesAtOddLevels(root):\n\n def levelOrder(self, root):\n\n def height(node):\n if node is None:\n return 0\n else:\n lheight = height(node.left)\n rheight = height(node.right)\n if lheight > rheight:\n return lheight + 1\n else:\n return rheight + 1\n\n def currlvl(root, lvl):\n if root is None:\n return\n elif lvl % 2 != 0:\n res.append(root.data)\n elif lvl > 1:\n currlvl(root.left, lvl - 1)\n currlvl(root.right, lvl - 1)\n res = []\n h = height(root)\n for i in range(1, h + 1):\n currlvl(root, i)\n return res", "def getNod(root, arr, lev):\n if not root:\n return\n if lev % 2 != 0:\n arr.append(root.data)\n self.getNod(root.left, arr, lev + 1)\n self.getNod(root.right, arr, lev + 1)\n\ndef nodesAtOddLevels(root):\n arr = []\n self.getNod(root, arr, 1)\n return arr", "def nodesAtOddLevels(root):\n return lll(root, 1, [])\n\ndef lll(root, l, arr):\n if root is None:\n return\n if l % 2:\n arr.append(root.data)\n lll(root.left, l + 1, arr)\n lll(root.rihjt, l + 1, arr)\n return arr", "def nodesAtOddLevels(root):\n n = root\n arr = []\n stack = [n]\n while stack:\n n = stack.pop()\n if n is not None:\n arr.append(n.data)\n stack.append(n.right)\n stack.append(n.left)\n return arr", "def nodesAtOddLevels(root):\n if root is None:\n return []\n q = []\n q.append(root)\n counter = 0\n ans = []\n while len(q) > 0:\n counter += 1\n t = []\n while len(q) != 0:\n x = st.pop(0)\n if x.left is not None:\n t.append(x.left)\n if x.right is not None:\n t.append(x.right)\n if counter % 2 != 0:\n ans.append(x.data)\n q = t\n return ans", "def nodesAtOddLevels(root):\n q = []\n q.append(root)\n arr = []\n x = 1\n while q:\n l = len(q)\n lis = []\n for i in range(l):\n temp = q.pop(0)\n lis.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n if x == 1:\n arr.extend(lis)\n x = 0\n elif x == 0:\n x = 1\n return arr", "def nodesAtOddLevels(root):\n c = 1\n s1 = []\n queue = [root]\n while queue != []:\n t = []\n for i in range(len(queue)):\n curr = queue[0]\n t.append(curr.data)\n if curr.left:\n queue.append(curr.left)\n if curr.right:\n queue.append(curr.right)\n queue.pop(0)\n if c % 2 == 1:\n s1.extend(t)\n c += 1\n elif c % 2 != 1:\n c += 1\n return s1", "def nodesAtOddLevels(root):\n d = []\n q = []\n g = {}\n if root == None:\n ans = []\n return ans\n d.append(root)\n q.append(0)\n while len(d) > 0:\n c = d.pop(0)\n m = q.pop(0)\n if m not in g:\n g[m] = [c.data]\n else:\n g[m].append(c.data)\n if c.left != None:\n d.append(c.left)\n q.append(m + 1)\n if c.right != None:\n d.append(c.right)\n q.append(m + 1)\n l = []\n for x in g:\n if x % 2 != 0:\n for i in range(0, len(g[x])):\n l.append(g[x][i])\n return l", "def nodesAtOddLevels(root):\n queue = deque([(root, 1)])\n l = []\n while queue:\n (node, h) = queue.popleft()\n if node.left is None and node.right is None and (h % 2 == 1):\n l.append(node.data)\n if node.left is not None:\n queue.append((node.left, h + 1))\n if node.right is not None:\n queue.append((node.right, h + 1))\n return l", "def nodesAtOddLevels(root):\n if root is None:\n return\n q = [root]\n res = []\n flag = 1\n while len(q) != 0:\n root = q.pop(0)\n if flag % 2 != 0:\n res.append(root.data)\n flag += 1\n if root.left:\n q.append(root.left)\n if root.right:\n q.append(root.right)\n return res", "def depthOfOddLeaf(root):\n arr = []\n level = 1\n q = []\n q.append(root)\n while len(q) != 0:\n for i in range(len(q)):\n node = q.pop(0)\n if node.left != None:\n q.append(node.left)\n if node.right != None:\n q.append(node.right)\n if level % 2 == 1:\n arr.append(level)\n level += 1\n return arr", "def nodesAtOddLevels(root):\n q = []\n q.append(root)\n ans = []\n p = 1\n while len(q):\n count = len(q)\n while count > 0:\n p = q.pop(0)\n if p % 2 == 1:\n ans.append(p.data)\n if p.left:\n q.append(p.left)\n if p.right:\n q.append(p.right)\n count -= 1\n p += 1\n return ans", "def nodesAtOddLevels(root):\n if not root:\n return []\n stack = [root]\n ans = []\n level = 1\n while stack:\n temp = []\n for i in range(len(stack)):\n node = stack.pop(0)\n if node.left:\n stack.append(node.left)\n if node.right != None:\n stack.append(node.right)\n temp.append(node.data)\n if temp != [] and level % 2 == 1:\n ans.append(temp)\n level += 1\n return ans", "def nodesAtOddLevels(root):\n global a\n a = []\n\n def sol(root, level):\n global a\n if root:\n if level % 2 == 0:\n a.append(root.data)\n sol(root.left, level + 1)\n sol(root.right, level + 1)\n sol(root, 0)\n return a", "def nodesAtOddLevels(root):\n q = []\n odd = []\n q.append(root)\n q.append('$')\n level = 1\n while len(q) > 0:\n t = q.pop(0)\n if level % 2 != 0:\n odd.append(t.data)\n if t == '$':\n if len(q) > 0:\n q.append('$')\n level += 1\n else:\n if t.left is not None:\n q.append(t.left)\n if t.right is not None:\n q.append(t.right)\n return odd", "def nodesAtOddLevels(root):\n arr = []\n self.myFunc(root, arr, 0)\n return arr\n\ndef myFunc(root, arr, level):\n if not root:\n return\n level += 1\n if level % 2:\n arr.append(root.data)\n self.myFunc(root.left, arr, level)\n self.myFunc(root.right, arr, level)\n return", "def __init__():\n self.level = {}\n\ndef trav(root, l):\n if l in self.level:\n self.level[l].append(root.data)\n elif l % 2 == 1:\n self.level[l] = [root.data]\n if root.left != None:\n self.trav(root.left, l + 1)\n if root.right != None:\n self.trav(root.right, l + 1)\n\ndef nodesAtOddLevels(root):\n self.trav(root, 1)\n res = []\n for l in self.level.keys():\n res.extend(self.level[l])\n return res", "def nodesAtOddLevels(root):\n output = []\n\n def oddLevel(root, level):\n if root == None:\n return\n if level % 2 != 0:\n output.append(root.data)\n oddLevel(root.left)\n oddLevel(root.right)\n oddLevel(root, 1)\n return output", "x = Solution()\nroot = Node(1)\nroot.left = Node(2)\nroot.right = Node(3)\nroot.left.left = Node(4)\nroot.left.right = Node(5)\nroot.left.right.left = Node(7)\nroot.left.right.right = Node(8)\nroot.right.right = Node(6)\nroot.right.right.left = Node(9)\nx.nodesAtOddLevels(root)\n\ndef __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef nodesAtOddLevels(root):\n res = []\n\n def func(root, level):\n if root is None:\n return\n if level % 2 != 0:\n res.append(root.data)\n func(root.left, level + 1)\n func(root.right, level + 1)\n func(root, 1)\n return res", "def nodesAtOddLevels(root):\n\n def helper(x):\n ans = []\n q = []\n t = []\n if not x:\n return ans\n q.append(x)\n while q:\n l = len(q)\n for i in range(l):\n a = q.pop(0)\n if a.left:\n q.append(a.left)\n if a.right:\n q.append(a.right)\n t.append(a.data)\n ans.append(t)\n t = []\n return ans\n a = helper(root)\n answer = []\n for i in range(len(a)):\n if i % 2 == 0:\n b = a[i]\n for j in b:\n answer.append(j)\n return ans", "def nodesAtOddLevels(root):\n q = []\n v = []\n q.append(root)\n l = 1\n while q != []:\n n = len(q)\n for i in range(n):\n temp = q.pop(0)\n if i % 2 == 1:\n v.append(temp)\n if temp.left:\n v.append(temp.left)\n if temp.right:\n v.append(temp.right)\n l += 1\n return v", "def nodesAtOddLevels(root):\n level = 1\n queue = [root]\n result = []\n while queue:\n size = len(queue)\n level += 1\n for i in range(size):\n node = node.pop(0)\n if node.left != None:\n queue.append(node.left)\n if node.right != None:\n queue.append(node.right)\n if level > 1 and level % 2 != 0:\n result.append(node.data)\n return result", "def nodesAtOddLevels(root):\n sum2 = 0\n if root is None:\n return sum2\n hight = self.TreeHight(root)\n i = 1\n lst = []\n while i <= hight:\n if i % 2 != 0:\n lst = self.LevelOrdertrvsl(root, i, lst)\n i += 1\n return lst\n\ndef LevelOrdertrvsl(root, level, lst):\n if root is None:\n return lst\n if level == 1:\n lst.append(root.data)\n return lst\n elif level > 1:\n lst = self.LevelOrdertrvsl(root.left, level - 1, lst)\n lst = self.LevelOrdertrvsl(root.right, level - 1, lst)\n return lst\n\ndef TreeHight(root):\n if root is None:\n return 0\n ls = 1 + self.TreeHight(root.left)\n rs = 1 + self.TreeHight(root.right)\n maxh = max(ls, rs)\n return maxh", "def nodesAtOddLevels(root):\n if root == None:\n return None\n q = [root]\n ans = []\n k = 0\n while len(q) > 0:\n k += 1\n count = len(q)\n for i in range(count):\n temp = q.pop(0)\n if k % 2 != 0:\n ans.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n return ans", "def nodesAtOddLevels(root):\n ans = []\n i = 0\n queue = [root]\n level = []\n while queue != [] and root is not None:\n l = []\n for node in queue:\n l.append(node.data)\n if node.left:\n level.append(node.left)\n if node.right:\n level.append(node.right)\n if i % 2 == 0:\n ans += l\n queue = level\n level = []\n i += 1\n return ans", "def nodesAtOddLevels(root):\n L = []\n if root == None:\n return\n if isOdd:\n L.append(root.data)\n printOddNodes(root.left, not isOdd)\n printOddNodes(root.right, not isOdd)\n return L", "def nodesAtOddLevels(root):\n s = {}\n c = 0\n q = [[root, 0]]\n m = -1\n while c != len(q):\n t = q[c][0]\n g = q[c][1]\n if g % 2 == 0:\n if g in s:\n s[g].append(t.data)\n else:\n s[g] = [t.data]\n if g > m:\n m = g\n if t.left:\n q.append([t.left, g + 1])\n if t.right:\n q.append([t.right, g + 1])\n c += 1\n l = []\n i = 0\n while i <= m:\n l.extend(s[g])\n i += 2\n return l", "def nodesAtOddLevels(root):\n if not root:\n return\n l = []\n odd = True\n if odd:\n l.append(root.data)\n self.nodesAtOddLevels(root.left, not odd)\n self.nodesAtOddLevels(root.right, not odd)\n return l", "def __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef nodesAtOddLevels(root):\n if root is None:\n return []\n else:\n import collections\n q = collections.deque()\n q.append(root)\n lst = []\n count = 1\n while q:\n for i in range(len(q)):\n node = q.popleft()\n if node and count % 2 != 0:\n lst.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n count = count + 1\n return lst", "def nodesAtOddLevels(root):\n arr = []\n if not root:\n return arr\n q = []\n q.append(root)\n f = 0\n while q:\n if f == 0:\n arr += [x.data for x in q]\n for x in range(len(q)):\n t = q.pop(0)\n if t.left:\n q.append(t.left)\n if t.right:\n q.append(t.right)\n f = 1 - f\n return arr", "def nodesAtOddLevels(root):\n q = deque()\n q.append(root)\n (ans, level) = ([], 0)\n while q:\n level += 1\n n = len(q)\n for _ in range(n):\n p = q.popleft()\n if level % 2 == 1:\n ans.append(p.data)\n if p.left:\n q.append(p.left)\n if p.right:\n q.append(p.right)\n return ans", "def printOddLevels(root, lvl, res):\n if root == None:\n return\n if lvl % 2 != 0:\n res.append(root)\n printOddLevels(root.left, lvl + 1, res)\n printOddLevels(root.right, lvl + 1, res)\n\ndef nodesAtOddLevels(root):\n res = []\n printOddLevels(root, 1, res)", "def nodesAtOddLevels(root):\n oddnodes = []\n q = []\n q.append(root)\n n = 1\n while q:\n n = len(q)\n for i in range(n):\n temp = q.pop(0)\n if k % 2 == 1:\n oddnodes.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n k += 1\n return", "from collections import deque\n\ndef nodesAtOddLevels(r):\n (q, ret) = (deque([r, 1]), [])\n if not r:\n return ret\n while q:\n (n, l) = q.popleft()\n if n.left:\n q += ((n.left, l + 1),)\n if n.right:\n q += ((n.right, l + 1),)\n if l & 1:\n ret += (n.data,)\n return ret", "def nodesAtOddLevels(root):\n stack = []\n stack.append(root)\n ans = []\n while stack:\n n = len(stack)\n j = 1\n level = []\n for i in range(n):\n node = stack.pop()\n level.append(node.data)\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n if j % 2 != 0:\n for i in level:\n ans.append(i)\n j += 1\n return ans", "import collections\n\ndef nodesAtOddLevels(root):\n res = []\n q = collections.deque()\n q.append(root)\n while q:\n qLen = len(q)\n level = []\n for i in range(qLen):\n node = q.popleft()\n if node:\n level.append(node.data)\n q.append(node.left)\n q.append(node.right)\n if level:\n res.append(level)\n odd_nodes = []\n for i in range(len(res)):\n if i % 2 == 0:\n odd_nodes.append(res[i])\n flat_list = [x for xs in odd_nodes for x in xs]\n return flat_list", "from collections import deque\n\ndef nodesAtOddLevels(root):\n if root == None:\n return 0\n q = deque([])\n q.append(root)\n ans = []\n f = True\n while len(q) > 0:\n n = len(q)\n if f:\n for i in range(1, n + 1):\n temp = q.popleft()\n ans.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n else:\n for i in range(1, n + 1):\n temp = q.popleft()\n ans.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n f = not f\n return ans", "def nodesAtOddLevels(root):\n ans = 1\n q = []\n q.append(root)\n l = []\n while len(q) > 0:\n for i in range(len(q)):\n if ans % 2 == 1:\n c = q.pop(0)\n l.append(c.data)\n if c.left:\n q.append(c.left)\n if c.right:\n q.append(c.right)\n else:\n c = q.pop(0)\n if c.left:\n q.append(c.left)\n if c.right:\n q.append(c.right)\n ans += 1\n return l", "def nodesAtOddLevels(root):\n ans = []\n queue = []\n queue.append(root)\n while len(queue) > 0:\n elem = queue.pop(0)\n ans.append(elem.data)\n if elem.left:\n queue.append(elem.left)\n if elem.right:\n queue.append(elem.right)\n return ans", "def nodesAtOddLevels(root):\n currentlevel = []\n nextlevel = []\n if root == None:\n return 0\n currentlevel.append(root)\n level = 1\n ans = []\n while len(currentlevel) > 0:\n curr = currentlevel.pop(0)\n if curr.left:\n nextlevel.append(curr.left)\n if curr.right:\n nextlevel.append(curr.right)\n if len(currentlevel) == 0:\n (currentlevel, nextlevel) = (nextlevel, currentlevel)\n if level % 2 != 0:\n ans = ans + currentlevel\n level += 1\n return ans", "def nodesAtOddLevels(root):\n q = [root]\n i = 0\n ans = []\n flag = True\n while q:\n n = len(q)\n while n:\n temp = q.pop(0)\n if flag:\n ans.append(temp.data)\n if temp.left:\n q.append(temp.left)\n if temp.right:\n q.append(temp.right)\n n -= 1\n flag = not flag\n return ans", "def nodesAtOddLevels(root):\n a = [root]\n ans = []\n level = 0\n while a:\n level += 1\n n = len(a)\n for i in range(n):\n p = a.pop(0)\n if level % 2 != 0:\n ans.append(p)\n if p.left:\n a.append(p.left)\n if p.right:\n a.append(p.right)\n return ans", "def nodesAtOddLevels(root):\n vals = []\n idx = 1\n q.append(root)\n while q:\n node = q.pop(0)\n if node is not None:\n if idx % 2 == 1:\n vals.append(node.data)\n if node.left is not None:\n q.append(node.left)\n if node.right is not None:\n q.append(node.right)\n idx += 1\n return vals", "def nodesAtOddLevels(root):\n res = []\n ans = []\n\n def traverse(root, level):\n if root == None:\n return\n if level < len(res):\n res[level].append(root.data)\n else:\n res.append([root.data])\n traverse(root.left, level + 1)\n traverse(root.right, level + 1)\n traverse(root, 0)\n for i in range(len(res)):\n if i % 2 == 0:\n for j in range(len(res[i])):\n ans.append(res[i][j])\n return ans", "from collections import deque\nq = queue()\n\ndef __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef __init__():\n self.lists = deque()\n self.size = 0\n\ndef enqueue(data):\n self.lists.append(data)\n self.size += 1\n\ndef dequeue():\n if self.size == 0:\n return -1\n else:\n temp = self.lists.popleft()\n self.size -= 1\n return temp\n\ndef isempty():\n return self.size == 0\n\ndef nodesAtOddLevels(root):\n level_count = 1\n l = []\n if root == None:\n return l\n else:\n q.enqueue(root)\n while q.isempty() != True:\n count = q.size\n while count > 0:\n temp = q.dequeue\n if level_count % 2 == 1:\n l.append(temp.data)\n if temp.left:\n q.enqueue(temp.left)\n if temp.right:\n q.enqueue(temp.right)\n count -= 1\n level_count += 1\n return l", "def nodesAtOddLevels(root):\n l = 1\n s = [root]\n ans = []\n while len(s):\n n = len(s)\n for i in range(n):\n temp = s.pop(0)\n if l % 2 != 0:\n ans.append(temp.data)\n if temp.left:\n s.append(temp.left)\n if temp.right:\n s.append(temp.right)\n l += 1\n return ans", "from collections import deque\n\ndef nodesAtOddLevels(root):\n if root is None:\n return 0\n q.append(root)\n q.append(None)\n level = 1\n arr = []\n while len(q) > 0:\n cur = q.popleft()\n if cur != None:\n if level % 2 != 0:\n arr.append(cur.data)\n if cur.left:\n q.append(cur.left)\n if cur.right:\n q.append(cur.right)\n elif len(q) > 0:\n q.append(None)\n level += 1\n return arr", "def nodesAtOddLevels(root):\n q = deque()\n q.append(root)\n q.append(None)\n arr = []\n level = 1\n while len(q) > 0:\n node = q.popleft()\n if node is not None:\n if level % 2 != 0:\n arr.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n elif len(q) > 0:\n q.append(None)\n level += 1\n return arr", "def nodesAtOddLevels(root):\n if root is None:\n return self.l\n final = []\n q = []\n q.append(root)\n level = 1\n while len(q):\n s = len(q)\n for i in range(s):\n l = q.pop(0)\n if level % 2 == 1:\n final.append(l)\n if l.left:\n q.append(l.left)\n if l.right:\n q.append(l.right)\n l += 1\n return final", "def __init__():\n self.l = []\n\ndef addnode(node, level):\n if root is None:\n return\n if level % 2 == 1:\n self.l.append(node)\n self.addnode(node.left, level + 1)\n self.addnode(node.right, level + 1)\n\ndef nodesAtOddLevels(root):\n if root is None:\n return self.l\n self.addnode(root, 1)\n return self.l", "def helper(d, q):\n while len(q) != 0:\n (p, l) = q.pop(0)\n if l % 2 != 0:\n if l not in d:\n d[l] = []\n d[l].append(root.data)\n if root.left:\n q.append((root.left, l + 1))\n if root.right:\n q.append((root.right, l + 1))\n return d\n\ndef nodesAtOddLevels(root):\n if not root:\n return []\n if not root.left and root.right:\n return root.data\n d = {}\n d = self.helper(d, [(root, 1)])\n l = []\n for i in sorted(d):\n l += i\n return l", "def nodesAtOddLevels(root):\n if root is None:\n return []\n d = defaultdict(list)\n\n def bfs(node, level):\n if not node:\n return\n d[level].append(node.data)\n bfs(node.left, level + 1)\n bfs(node.right, level + 1)\n bfs(root, 0)\n ans = []\n for (key, value) in d.items():\n if key % 2 != 0:\n ans.append(value)\n return ans", "def __init__():\n self.res = []\n\ndef nodesAtOddLevels(root):\n level = 1\n self.traverse(root, level)\n return self.res\n\ndef traverse(root, level):\n if root == None:\n return\n if level % 2 != 0:\n self.res.append(root.data)\n self.traverse(root.left, level + 1)\n self.taverse(root.right, level + 1)\n return", "def nodesAtOddLevels(root):\n if root is None:\n return\n q = []\n q.append(root)\n res = []\n oddNodes(root, True)\n\n def oddNodes(root, isOdd):\n if root is None:\n return\n n = q.pop(0)\n if isOdd:\n res.append(n.data)\n if n.left:\n q.append(n.left)\n oddNodes(n.left, not isOdd)\n if n.right:\n q.append(n.right)\n oddNodes(n.right, not isOdd)\n return res", "def nodesAtOddLevels(root):\n q = []\n q.append(root)\n lev = 1\n l = []\n while len(q) > 0:\n n = q.pop(0)\n if lev % 2 != 0:\n l.append(n.data)\n if n.left:\n q.append(n.left)\n lev += 1\n if n.right:\n q.append(n.right)\n lev += 1\n return l", "def nodesAtOddLevels(root):\n ans = []\n q = [root]\n while q:\n node = q.pop()\n size = len(node)\n for i in range(size):\n ans.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return ans", "def nodesAtOddLevels(root):\n\n def height(root):\n if root == None:\n return 0\n left = height(root.left)\n right = height(root.right)\n return max(left, right) + 1\n\n def traversal(root, level):\n if root == None:\n return None\n if level == 0:\n list1.append(root.data)\n else:\n traversal(root.left, level - 1)\n traversal(root.right, level - 1)\n tall = height(root)\n count = 1\n list1 = []\n for i in range(tall):\n if count % 2 != 1:\n traversal(root, i)\n return list1", "def helper(root, lst):\n if root is None:\n return\n lst.append(root.data)\n self.helper(root.left.left, lst)\n self.helper(root.left.right, lst)\n self.helper(root.right.left, lst)\n self.helper(root.right.right, lst)\n return lst\n\ndef nodesAtOddLevels(root):\n lst = []\n self.helper(root, lst)\n return lst", "def nodesAtOddLevels(root):\n ans = []\n\n def sol(r, val):\n nonlocal ans\n if r == None:\n return\n if len(ans) > val:\n ans[val] += 1\n else:\n ans.append(1)\n sol(r.left, val + 1)\n sol(r.right, val + 1)\n sol(root, 0)\n rans = []\n for i in range(len(ans)):\n if (i + 1) % 2 != 0:\n rans.append(ans[i])\n return rans", "def __init__():\n self.ans = []\n\ndef _traverse(root, h):\n if root:\n if h % 2:\n self.ans.append(root.data)\n self._traverse(root.left, h + 1)\n self._traverse(root.right, h + 1)\n\ndef nodesAtOddLevels(root):\n self._traverse(root, 1)\n return self.ans", "def FindOddLevelNode(root, ht, ans):\n if root == None:\n return\n if ht & 1 == 1:\n ans.append(root.data)\n FindOddLevelNode(root.left, ht + 1, ans)\n FindOddLevelNode(root.right, ht + 1, ans)\n\ndef nodesAtOddLevels(root):\n ht = 1\n ans = []\n FindOddLevelNode(root, ht, ans)\n return ans", "su = 0\n\ndef no(root, p):\n global su\n if root == None:\n return\n if p % 2 != 0:\n su = su + root.data\n self.no(root.left, p, su)\n self.no(root.right, p, su)\n\ndef nodesAtOddLevels(root):\n self.no(root, 1, 0)\n global su\n return su", "from collections import deque\n\ndef nodesAtOddLevels(root):\n level = 0\n q = deque()\n q.append(root)\n ans = []\n while q:\n level += 1\n size = len(q)\n while size:\n ele = q.popleft()\n if level % 2:\n ans.append(ele.data)\n if ele.left:\n q.append(ele.left)\n if ele.right:\n q.append(ele.right)\n size -= 1\n return ans", "import queue\n\ndef nodesAtOddLevels(root):\n if root is None:\n return []\n q = queue.Queue()\n q.put(root)\n arr = []\n i = 1\n while q.empty() != True:\n size = q.qsize()\n while size > 0:\n current_node = q.get()\n if i % 2 != 0:\n arr.append(current_node.data)\n if current_node.left != None:\n q.put(current_node.left)\n if current_node.right != None:\n q.put(current_node.right)\n size -= 1\n i += 1\n return arr", "def nodesAtOddLevels(root):\n q = []\n temp = []\n q.append(root)\n level = 1\n while len(q) > 0:\n count = len(q)\n for i in range(count):\n node = q.pop(0)\n if level % 2 == 0:\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n else:\n if node.left:\n q.append(node.left)\n temp.append(node.left)\n if node.right:\n q.append(node.right)\n temp.append(node.right)\n level = level + 1\n return temp", "def nodesAtOddLevels(root):\n level = 0\n if root is None:\n return []\n q = []\n res = []\n q.append(root)\n while len(q) > 0:\n level += 1\n temp = []\n while len(q) > 0:\n node = q.pop(0)\n if level % 2 == 1:\n res.append(node.data)\n if node.left:\n temp.append(node.left)\n if node.right:\n temp.append(node.right)\n q = temp\n return res"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["1\n / \\\n 2 3\n / \\ \\\n 4 5 6\n / \\ /\n 7 8 9", "1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7"], "outputs": ["1 4 5 6", "1 4 5 6 7"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/nodes-at-odd-levels/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "__init__", "task_id": "TACO_lite/380", "example": [[[1, [2, 3, [4, 5, [7, 8], 6, [9]]]], [1, [2, 3, [4, 5, 6, 7]]]], ["(1, 4, 5, 6)", "(1, 4, 5, 6, 7)"]]} +{"requirement": "Your friend Rick is trying to send you a message, but he is concerned that it would get intercepted by his partner. He came up with a solution:\n\n1) Add digits in random places within the message.\n\n2) Split the resulting message in two. He wrote down every second character on one page, and the remaining ones on another. He then dispatched the two messages separately.\n\nWrite a function interweave(s1, s2) that reverses this operation to decode his message!\n\nExample 1: interweave(\"hlo\", \"el\") -> \"hello\"\nExample 2: interweave(\"h3lo\", \"el4\") -> \"hello\"\n\nRick's a bit peculiar about his formats. He would feel ashamed if he found out his message led to extra white spaces hanging around the edges of his message...", "solutions": ["def interweave(s1, s2):\n s = [''] * (len(s1) + len(s2))\n (s[::2], s[1::2]) = (s1, s2)\n return ''.join((c for c in s if not c.isdigit())).strip()", "from itertools import chain, zip_longest\n\ndef interweave(s1, s2):\n return ''.join((char for char in chain.from_iterable(zip_longest(s1, s2, fillvalue='')) if not char.isdigit()))", "import re\n\ndef interweave(s1, s2):\n z = ''.join([x + y for (x, y) in zip(s1, s2 + ' ')])[:-1]\n return re.sub('[0-9]', '', z)", "def interweave(s1, s2):\n result = ''\n i = 0\n while i < len(s1) or i < len(s2):\n if i < len(s1) and (not s1[i].isdigit()):\n result += s1[i]\n if i < len(s2) and (not s2[i].isdigit()):\n result += s2[i]\n i += 1\n return result", "def interweave(s1, s2):\n return ''.join((y for x in zip(s1, s2 + '0') for y in x if not y.isdigit()))", "from itertools import zip_longest\n\ndef interweave(*args):\n return ''.join((''.join((b for b in a if not b.isdigit())) for a in zip_longest(*args, fillvalue=''))).rstrip()", "import re\n\ndef interweave(s1, s2):\n return re.sub('\\\\d', '', ''.join((a + b for (a, b) in zip(s1, s2.ljust(len(s1), ' '))))).strip()", "def interweave(s1, s2):\n s = ''\n for i in range(len(s2)):\n if not s1[i].isdigit():\n s += s1[i]\n if not s2[i].isdigit():\n s += s2[i]\n return s if len(s1) == 0 or s1[-1].isdigit() else s + s1[-1]", "from itertools import chain, zip_longest\n\ndef interweave(s1, s2):\n return ''.join([c for c in chain.from_iterable(zip_longest(s1, s2)) if c and (not c.isdigit())])"], "starter_code": "def interweave(s1, s2):\n", "input_output": {"fn_name": "interweave", "inputs": [["", ""], ["hlo", "el"], ["h3lo", "el4"]], "outputs": [[""], ["hello"], ["hello"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/588a7d45019c42be61000009", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "interweave", "task_id": "TACO_lite/492", "example": [[["hlo", "el"], ["h3lo", "el4"]], ["hello", "hello"]]} +{"requirement": "Your task is to remove all duplicate words from a string, leaving only single (first) words entries.\n\nExample:\n\nInput:\n\n'alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'\n\nOutput:\n\n'alpha beta gamma delta'", "solutions": ["def remove_duplicate_words(s):\n return ' '.join(dict.fromkeys(s.split()))", "def remove_duplicate_words(s):\n s = s.split(' ')\n words = []\n for item in s:\n if item not in words:\n words.append(item)\n return ' '.join(words)", "def remove_duplicate_words(s):\n return ' '.join(sorted(set(s.split()), key=s.index))", "def remove_duplicate_words(s):\n a = []\n [a.append(v) for v in s.split(' ') if v not in a]\n return str(' ').join(a)", "def remove_duplicate_words(s):\n\n def f():\n seen = set()\n for word in s.split():\n if word in seen:\n continue\n seen.add(word)\n yield word\n return ' '.join(f())", "from collections import OrderedDict\nremove_duplicate_words = lambda s: ' '.join(OrderedDict.fromkeys(s.split(' ')))", "def remove_duplicate_words(s):\n new_list = []\n for word in s.split():\n if word not in new_list:\n new_list.append(word)\n return ' '.join(new_list)", "d = {}\nremove_duplicate_words = lambda s: ' '.join((d.setdefault(w, w) for w in s.split() if w not in d))", "remove_duplicate_words = lambda s: (lambda x: ' '.join((e for (i, e) in enumerate(x) if e not in x[:i])))(s.split())", "def remove_duplicate_words(s):\n return ' '.join({i: 0 for i in s.split()})", "def remove_duplicate_words(s):\n res = {}\n for (i, n) in enumerate(s.split()):\n if n not in res:\n res[n] = i\n return ' '.join(sorted(res, key=res.get))", "def remove_duplicate_words(s):\n return ' '.join((s.split()[i] for i in range(len(s.split())) if s.split()[i] not in s.split()[0:i]))", "def remove_duplicate_words(s):\n seen = set()\n result = []\n for word in list(s.split(' ')):\n if word not in seen:\n seen.add(word)\n result.append(word)\n return ' '.join(result)", "def remove_duplicate_words(s):\n l = s.split()\n words = []\n for elt in l:\n if elt not in words:\n words.append(elt)\n return ' '.join(words)", "def remove_duplicate_words(s):\n final = []\n for s in s.split():\n if s not in final:\n final.append(s)\n return ' '.join(final)", "def remove_duplicate_words(s):\n tot = []\n for i in s.split():\n if i not in tot:\n tot.append(i)\n return ' '.join(tot)\n return ' '.join(tot)", "from functools import reduce\n\ndef remove_duplicate_words(s):\n return ' '.join(reduce(lambda l, x: l + [x] if x not in l else l, s.split(' '), []))", "def remove_duplicate_words(s):\n arr = s.split()\n arr1 = []\n for el in arr:\n if not el in arr1:\n arr1.append(el)\n return ' '.join(arr1)", "def remove_duplicate_words(s):\n ss = list(set(s.split()))\n ss.sort(key=s.index)\n return ' '.join(ss)", "def remove_duplicate_words(s):\n o = []\n x = s.split()\n for y in x:\n if y not in o:\n o.append(y)\n return ' '.join(o)", "def remove_duplicate_words(s):\n result = []\n [result.append(w) for w in s.split(' ') if not w in result]\n return ' '.join([x for x in result])", "remove_duplicate_words = lambda s: ' '.join(dict.fromkeys(s.split()))", "def remove_duplicate_words(s):\n array = s.split()\n output = []\n for word in array:\n if word not in output:\n output.append(word)\n return ' '.join(output)", "def remove_duplicate_words(s):\n my_set = []\n for word in s.split(' '):\n try:\n my_set.index(word)\n except ValueError:\n my_set.append(word)\n return ' '.join(my_set)", "def remove_duplicate_words(s):\n already = []\n for i in s.split():\n if i in already:\n continue\n if i not in already:\n already.append(i)\n return ' '.join(already)", "from functools import reduce\n\ndef remove_duplicate_words(s):\n return reduce(lambda res, curr: res if curr in res else res + ' ' + curr, s.split(), '').lstrip()", "def remove_duplicate_words(s):\n removed = s.split()\n newlist = []\n for i in removed:\n if i not in newlist:\n newlist.append(i)\n newstring = ' '.join(newlist)\n return newstring", "def remove_duplicate_words(s):\n arr = s.split()\n new = []\n for i in arr:\n if i not in new:\n new.append(i)\n return ' '.join(new)", "def remove_duplicate_words(s):\n arr = s.split()\n res_list = []\n for elem in arr:\n if not elem in res_list:\n res_list.append(elem)\n return ' '.join(res_list)", "def remove_duplicate_words(s):\n l = []\n for i in s.split():\n if not i in l:\n l.append(i)\n else:\n pass\n return ' '.join(l)", "def remove_duplicate_words(s):\n split = s.split(' ')\n end = []\n for word in split:\n if word in end:\n continue\n end.append(word)\n return ' '.join(end)", "def remove_duplicate_words(s):\n single = []\n for x in s.split():\n if x not in single:\n single.append(x)\n return ' '.join(single)", "def remove_duplicate_words(s):\n lst = s.split()\n lst_new = []\n for i in lst:\n if i not in lst_new:\n lst_new.append(i)\n return ' '.join(lst_new)", "def remove_duplicate_words(s):\n s_list = s.split()\n result_list = []\n for word in s_list:\n if word not in result_list:\n result_list.append(word)\n return ' '.join(result_list)", "def remove_duplicate_words(s):\n cadena = s.split()\n cadena2 = []\n cadena3 = ' '\n for i in cadena:\n if i in cadena2:\n pass\n else:\n cadena2.append(i)\n cadena3 = cadena3.join(cadena2)\n return cadena3", "def remove_duplicate_words(s):\n s = s.split(' ')\n a = ''\n for x in range(len(s)):\n if s[x] not in a:\n a += s[x] + ' '\n return a[:-1]", "def remove_duplicate_words(s):\n x = [s for s in s.split()]\n ans = []\n for y in x:\n if y not in ans:\n ans.append(y)\n return ''.join((x + ' ' for x in ans))[:-1]", "def remove_duplicate_words(s):\n list_of_words = s.split()\n compressed = []\n for word in list_of_words:\n if word not in compressed:\n compressed.append(word)\n else:\n pass\n compressed_to_string = ' '.join(compressed)\n return compressed_to_string", "def remove_duplicate_words(sentence):\n lst = [sentence][0].split()\n no_dbls = list(dict.fromkeys(lst))\n return ' '.join(no_dbls)", "def remove_duplicate_words(x):\n y = []\n for i in x.split():\n if i in y:\n pass\n else:\n y.append(i)\n return ' '.join(y)", "def remove_duplicate_words(s):\n no_dup = []\n no_dup1 = []\n for c in s.split(' '):\n if c not in no_dup:\n no_dup.append(c)\n else:\n no_dup1.append(c)\n return ' '.join(no_dup)", "def remove_duplicate_words(s):\n return ' '.join((i for (loop, i) in enumerate(s.split()) if s.split().index(i) == loop))", "def remove_duplicate_words(s):\n words = s.split()\n new_list = []\n for i in words:\n if i not in new_list:\n new_list.append(i)\n new_list = ' '.join(new_list)\n return new_list", "def remove_duplicate_words(s):\n return ' '.join(list({x: 1 for x in s.split(' ')}))", "def remove_duplicate_words(s):\n seperated = s.split()\n mylist = list(dict.fromkeys(seperated))\n return ' '.join(mylist)", "from collections import Counter\n\ndef remove_duplicate_words(strr):\n input = strr.split(' ')\n for i in range(0, len(input)):\n input[i] = ''.join(input[i])\n UniqW = Counter(input)\n s = ' '.join(UniqW.keys())\n return s", "def remove_duplicate_words(s):\n words = set()\n stree = ''\n for word in s.split():\n if word not in words:\n stree += word + ' '\n words.add(word)\n return stree[0:-1]", "def remove_duplicate_words(s):\n seen = set()\n words = []\n for word in s.split(' '):\n if word not in seen:\n seen.add(word)\n words.append(word)\n return ' '.join(words)", "def remove_duplicate_words(s):\n result = []\n s = s.split(' ')\n for (i, word) in enumerate(s):\n if word not in result:\n result.append(word)\n else:\n pass\n return ' '.join(result)", "def remove_duplicate_words(str):\n l = str.split()\n s = []\n r = []\n for i in range(len(l)):\n if l[i] not in s:\n s.append(l[i])\n r.append(l[i])\n satr = ' '.join([elem for elem in r])\n return satr", "from collections import OrderedDict\nfrom collections import Counter\n\ndef remove_duplicate_words(s):\n s = s.split(' ')\n s = OrderedDict.fromkeys(s)\n return ' '.join(s)", "from collections import OrderedDict\n\ndef remove_duplicate_words(s):\n spliter = s.split()\n return ' '.join(OrderedDict.fromkeys(spliter))", "def remove_duplicate_words(s):\n d = dict(((i, s.split(' ').count(i)) for i in s.split(' ')))\n return ' '.join(d.keys())", "def remove_duplicate_words(s):\n res = []\n s = s.split()\n visited = set()\n for w in s:\n if w not in visited:\n res.append(w)\n visited.add(w)\n return ' '.join(res)", "def remove_duplicate_words(s):\n list = s.split()\n new = []\n for x in list:\n if x not in new and new.count(x) == 0:\n new.append(x)\n s = ' '\n return s.join(new)", "def remove_duplicate_words(s):\n D = []\n words = s.split(' ')\n for word in words:\n if word not in D:\n D.append(word)\n else:\n pass\n return ' '.join(D)", "import re\n\ndef remove_duplicate_words(s):\n s_list = []\n s_2 = ''\n all = s.split()\n for word in s.split():\n if word not in s_list:\n s_2 += ' ' + word\n s_list.append(word)\n return s_2.strip()", "def remove_duplicate_words(s):\n q = ''\n a = s.split(' ')\n for i in a:\n if i not in q:\n q += i + ' '\n return q[:-1]", "from collections import Counter\n\ndef remove_duplicate_words(s):\n new = []\n for i in Counter(s.split(' ')):\n new.append(i)\n return ' '.join(new)", "import re\n\ndef remove_duplicate_words(s):\n sx = []\n for i in s.split():\n if i not in sx:\n sx.append(i)\n return ' '.join(sx)", "def remove_duplicate_words(s):\n split_string = s.split()\n new_string = ''\n for word in split_string:\n if word not in new_string:\n new_string += word + ' '\n else:\n continue\n return new_string.rstrip()", "def remove_duplicate_words(s):\n t = set()\n s = s.split()\n r = []\n for w in s:\n if w not in t:\n t.add(w)\n r.append(w)\n return ' '.join(r)", "def remove_duplicate_words(s):\n list = s.split()\n index = 0\n empty = []\n while index < len(list):\n if list[index] not in list[0:index]:\n empty.append(list[index])\n index += 1\n return ' '.join(empty)", "def remove_duplicate_words(s):\n a = []\n c = s.split(' ')\n for i in c:\n if i not in a:\n a.append(i)\n return ' '.join(a)", "def remove_duplicate_words(x):\n a = ''\n for i in x.split():\n if i not in a:\n a += i + ' '\n return a[:-1]", "def remove_duplicate_words(s):\n nwrd = []\n for i in s.split(' '):\n if i in nwrd:\n pass\n else:\n nwrd.append(i)\n return ' '.join(nwrd)", "def remove_duplicate_words(s):\n res = []\n s = s.split(' ')\n for w in s:\n if w not in res:\n res.append(w)\n erg = ''\n for r in res:\n erg += r + ' '\n return erg[:-1]", "def remove_duplicate_words(string):\n string = string.split(' ')\n lst = []\n for word in string:\n if word not in lst:\n lst.append(word)\n return ' '.join(lst)", "def remove_duplicate_words(s):\n res = ''\n k = s.split()\n for i in k:\n if i not in res:\n res += i + ' '\n return res.rstrip()", "import re\n\ndef remove_duplicate_words(s):\n result = []\n s_l = s.split(' ')\n for x in s_l:\n if x not in result:\n result.append(x)\n result = ' '.join(result)\n return result", "from collections import OrderedDict\n\ndef remove_duplicate_words(s):\n a = s.split(' ')\n return ' '.join(list(OrderedDict.fromkeys(a)))", "from collections import OrderedDict\n\ndef remove_duplicate_words(s):\n return ' '.join(OrderedDict(((x, None) for x in s.split())).keys())", "def remove_duplicate_words(s):\n return ' '.join(list({i: True for i in s.split(' ')}))", "def remove_duplicate_words(str):\n return ' '.join(sorted(set(str.split()), key=str.split().index))"], "starter_code": "def remove_duplicate_words(s):\n", "input_output": {"fn_name": "remove_duplicate_words", "inputs": [["alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta"], ["my cat is my cat fat"]], "outputs": [["alpha beta gamma delta"], ["my cat is fat"]]}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Strings", "Algorithms"], "name": null, "source": "codewars", "tags": ["String algorithms"], "skill_types": [], "url": "https://www.codewars.com/kata/5b39e3772ae7545f650000fc", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "remove_duplicate_words", "task_id": "TACO_lite/212", "example": [[["alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta"]], ["alpha beta gamma delta"]]} +{"requirement": "Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.\n\nExample 1:\n\n\nInput: n = 12\nOutput: 3 \nExplanation: 12 = 4 + 4 + 4.\n\nExample 2:\n\n\nInput: n = 13\nOutput: 2\nExplanation: 13 = 4 + 9.", "solutions": ["def numsquares(n):\n import math\n\n def is_square(m):\n sqrt_m = int(math.sqrt(m))\n return sqrt_m * sqrt_m == m\n if is_square(n):\n return 1\n while n & 3 == 0:\n n >>= 2\n if n & 7 == 7:\n return 4\n sqrt_n = int(math.sqrt(n))\n for i in range(1, sqrt_n + 1):\n if is_square(n - i * i):\n return 2\n return 3", "def numsquares(n):\n\n def is_square(n):\n return int(n ** 0.5) * int(n ** 0.5) == n\n if is_square(n):\n return 1\n for i in range(1, int(n ** 0.5 + 1)):\n if is_square(n - i * i):\n return 2\n while n & 3 == 0:\n n >>= 2\n if n & 7 == 7:\n return 4\n return 3", "def numsquares(n):\n while n % 4 == 0:\n n //= 4\n if n % 8 == 7:\n return 4\n for i in range(n + 1):\n tmp = i * i\n if tmp <= n:\n if int((n - tmp) ** 0.5) ** 2 + tmp == n:\n return 1 + (0 if tmp == 0 else 1)\n else:\n break\n return 3", "def as_a_perfect_square(n):\n return (n ** 0.5).is_integer()\n\ndef min_perfect_square(i, array):\n res = 1000\n for x in range(0, i // 2 + 1):\n a = array[x]\n if a >= res:\n continue\n b = array[i - 1 - x]\n if a + b < res:\n res = a + b\n if res == 2:\n return res\n return res\n\ndef numsquares(n):\n array = [1, 2, 3, 1, 2, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 1, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 1, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 1, 2, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 4, 2, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 1, 2, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 1, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 1, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 4, 2, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 1, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 4, 3, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 4, 1, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 1, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 2, 2, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 1, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 4, 1, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 2, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 2, 2, 3, 1, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 4, 3, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 1, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 4, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 3, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 4, 3, 3, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 4, 1, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 4, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 1, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 1, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 4, 3, 3, 3, 2, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 4, 2, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 1, 2, 2, 3, 2, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 1, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 4, 3, 2, 3, 1, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 4, 3, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 1, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 1, 2, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 1, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 3, 2, 3, 2, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 4, 3, 3, 3, 2, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 4, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 4, 2, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 4, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 4, 3, 2, 3, 1, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 4, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 4, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 4, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 1, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 4, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 4, 2, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 3, 3, 1, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 4, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 1, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 4, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 1, 2, 2, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 4, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 4, 3, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 4, 3, 2, 3, 1, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 4, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 4, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 4, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 4, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 4, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 4, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 4, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 4, 2, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 4, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 1, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 4, 1, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 4, 3, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 1, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 2, 2, 2, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 4, 2, 2, 3, 3, 3, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 1, 2, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 3, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 4, 2, 2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 2, 3, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 4, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 1, 2, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 4, 3, 2, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 4, 2, 3, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 1, 2, 3, 3, 2, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 2, 3, 2, 3, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 3, 2, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 4, 3, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 3, 1, 2, 3, 2, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 3, 2, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 3, 3, 4, 4, 3, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 2, 2, 3, 1, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 2, 3, 4, 3, 3, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 2, 3, 3, 4, 2, 3, 4, 4, 2, 3, 3, 2, 3, 3, 4, 3, 2, 3, 3, 3, 2, 3, 4, 2, 3, 3, 3, 2, 2, 3, 4, 3, 2, 3, 3, 4, 3, 3, 4, 3, 2, 2, 3, 2, 2, 3, 4, 2, 3, 3, 3, 3, 3, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 3, 3, 3, 3, 2, 3, 4, 2, 3, 2, 3, 3, 3, 3, 4, 3, 2, 3, 3, 2, 2, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 2, 3, 3, 3, 2, 3, 3, 4, 3, 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 4, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 2, 1, 2, 3, 3, 2, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 2, 3, 4, 4, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 2, 3, 3, 2, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 2, 2, 2, 3, 3, 3, 3, 4, 3, 2, 2, 3, 4, 3, 3, 4, 3, 3, 3, 3, 2, 2, 3, 4, 2, 3, 2, 3, 3, 2, 3, 4, 3, 3, 3, 3, 2, 3, 3, 4, 3, 3, 2, 3, 4, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 3, 2, 2, 3, 4, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 4, 3, 3, 2, 3, 3, 2, 3, 4, 4, 3, 2, 3, 2, 2, 3, 4, 3, 3, 3, 3, 4, 2, 3, 4, 4, 2, 2, 3, 3, 3, 3, 4, 2, 3, 3, 3, 3, 2, 3, 4, 1]\n array[0] = 1\n array[1] = 2\n array_n = len(array)\n for i in range(array_n, n):\n if self.as_a_perfect_square(i + 1):\n array[array_n] = 1\n array_n += 1\n else:\n array[array_n] = self.min_perfect_square(i, array)\n array_n += 1\n return array[n - 1]"], "starter_code": "def numsquares(n: int) -> int:\n", "input_output": {"fn_name": "numSquares", "inputs": [[12]], "outputs": [3]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Math", "Dynamic Programming", "Breadth-First Search"], "name": null, "source": "leetcode", "tags": ["Dynamic programming", "Graph traversal", "Mathematics"], "skill_types": ["Dynamic programming"], "url": "https://leetcode.com/problems/perfect-squares/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "numsquares", "task_id": "TACO_lite/522", "example": [[[12], [13]], ["3", "2"]]} +{"requirement": "# Kata Task\n\nYou are given a list of cogs in a gear train\n\nEach element represents the number of teeth of that cog\n\ne.g. `[100, 50, 25]` means \n* 1st cog has 100 teeth \n* 2nd cog has 50 teeth\n* 3rd cog has 25 teeth\n\nIf the ``nth`` cog rotates clockwise at 1 RPM what is the RPM of the cogs at each end of the gear train? \n\n**Notes**\n* no two cogs share the same shaft\n* return an array whose two elements are RPM of the first and last cogs respectively\n* use negative numbers for anti-clockwise rotation\n* for convenience `n` is zero-based\n* For C and NASM coders, the returned array will be `free`'d.\n\n---\n\nSeries:\n* Cogs\n* Cogs 2", "solutions": ["def cog_rpm(cogs, n):\n return [cogs[n] / cogs[0] * (-1 if n % 2 else 1), cogs[n] / cogs[-1] * (1 if (len(cogs) - n) % 2 else -1)]", "def cog_rpm(cogs, n):\n sign1 = -1 if n % 2 else 1\n sign2 = 1 if (len(cogs) - n) % 2 else -1\n return [sign1 * cogs[n] / cogs[0], sign2 * cogs[n] / cogs[-1]]", "def cog_rpm(l, i):\n return [(-1 + (i + 1) % 2 * 2) * l[i] / l[0], (-1 + (len(l) - i) % 2 * 2) * l[i] / l[-1]]", "def cog_rpm(cogs, n):\n (a, b) = (1, 1)\n if n % 2 == 1:\n a = -1\n if len(cogs) % 2 == n % 2:\n b = -1\n return [a * cogs[n] / cogs[0], b * cogs[n] / cogs[-1]]", "def cog_rpm(cogs, n):\n return [cogs[n] / cogs[0] * (-1) ** n, cogs[n] / cogs[-1] * (-1) ** (len(cogs) - n - 1)]", "def cog_rpm(cogs, n):\n output = []\n if n % 2 == 0:\n a = 1\n if len(cogs) % 2 - 1 == 0:\n b = 1\n else:\n b = -1\n else:\n a = -1\n if (len(cogs) - 1) % 2 == 0:\n b = -1\n else:\n b = 1\n output.append(cogs[n] / cogs[0] * a)\n output.append(cogs[n] / cogs[-1] * b)\n return output", "def cog_rpm(cogs, idx):\n first = cogs[idx] / cogs[0] * [1, -1][idx & 1]\n last = cogs[idx] / cogs[-1] * [1, -1][len(cogs) - idx - 1 & 1]\n return [first, last]", "def cog_rpm(cogs, n):\n r = [cogs[n] / cogs[0], cogs[n] / cogs[-1]]\n if n % 2 == 1:\n r[0] *= -1\n if (len(cogs) - n) % 2 == 0:\n r[1] *= -1\n return r", "def cog_rpm(cogs, i):\n (x, y) = (cogs[i] / cogs[0], cogs[i] / cogs[-1])\n if i & 1:\n x = -x\n if len(cogs) - 1 - i & 1:\n y = -y\n return [x, y]", "from functools import reduce\nfrom operator import mul\n\ndef cog_rpm(cogs, n):\n f = lambda l: 1 if len(l) < 2 else reduce(mul, [-x / y for (x, y) in zip(l, l[1:])])\n return [f(cogs[:n + 1][::-1]), f(cogs[n:])]"], "starter_code": "def cog_rpm(cogs, n):\n", "input_output": {"fn_name": "cog_RPM", "inputs": [[[100], 0], [[100, 100, 100, 100], 0], [[100, 100, 100, 100], 1], [[100, 100, 100, 100], 2], [[100, 100, 100, 100], 3]], "outputs": [[[1, 1]], [[1, -1]], [[-1, 1]], [[1, -1]], [[-1, 1]]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/59e72bdcfc3c4974190000d9", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "cog_rpm", "task_id": "TACO_lite/532", "example": [[[[100, 50, 25]]], [null]]} +{"requirement": "# Task\n You are given an array of integers `arr` that representing coordinates of obstacles situated on a straight line.\n\n Assume that you are jumping from the point with coordinate 0 to the right. You are allowed only to make jumps of the same length represented by some integer.\n\n Find the minimal length of the jump enough to avoid all the obstacles.\n\n# Example\n\n For `arr = [5, 3, 6, 7, 9]`, the output should be `4`.\n\n Check out the image below for better understanding:\n\n \n\n\n# Input/Output\n\n\n - `[input]` integer array `arr`\n\n Non-empty array of positive integers.\n\n Constraints: `1 \u2264 inputArray[i] \u2264 100.`\n\n\n - `[output]` an integer\n\n The desired length.", "solutions": ["def avoid_obstacles(arr):\n n = 2\n while 1:\n if all([x % n for x in arr]):\n return n\n n += 1", "def avoid_obstacles(a):\n for j in range(2, max(a) + 2):\n if all((e % j != 0 for e in a)):\n return j", "def avoid_obstacles(arr):\n s = set(arr)\n m = max(arr)\n for i in range(1, m + 2):\n if i in s:\n continue\n if not any((x in s for x in range(i, m + 1, i))):\n return i", "def avoid_obstacles(arr):\n obstacles = set(arr)\n limit = max(arr) + 2\n for step in range(1, limit):\n if not set(range(0, limit, step)) & obstacles:\n return step", "def avoid_obstacles(arr, n=1):\n arr = set(arr)\n while set(range(0, 100 + 1, n)) & arr:\n n += 1\n return n", "avoid_obstacles = lambda a: min((n for n in range(1, max(a) + 2) if all((m % n for m in a))))", "def avoid_obstacles(arr):\n if min(arr) == 1 and max(arr) == 100:\n return 101\n landed = True\n for max_jump in range(2, 100):\n n = max_jump\n landed = True\n while n <= 100:\n for i in range(len(arr)):\n if n == arr[i]:\n landed = False\n break\n n += max_jump\n if landed:\n return max_jump", "def avoid_obstacles(arr):\n jump = 2\n while True:\n start_again = False\n for num in arr:\n if num % jump == 0:\n jump = jump + 1\n start_again = True\n break\n if not start_again:\n return jump", "def avoid_obstacles(arr):\n holes = set(range(2, max(arr))).difference(arr)\n for step in holes:\n if all([x % step != 0 for x in arr]):\n return step\n return max(arr) + 1", "def avoid_obstacles(arr):\n x = 2\n for i in range(max(arr)):\n leaps = [x * i for i in range(1, max(arr))]\n for i in leaps:\n if i in arr:\n leaps = []\n x += 1\n break\n return x"], "starter_code": "def avoid_obstacles(arr):\n", "input_output": {"fn_name": "avoid_obstacles", "inputs": [[[5, 3, 6, 7, 9]], [[2, 3]], [[1, 4, 10, 6, 2]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]]], "outputs": [[4], [4], [7], [101]]}, "difficulty": "EASY", "raw_tags": ["Puzzles"], "name": null, "source": "codewars", "tags": ["Ad-hoc"], "skill_types": [], "url": "https://www.codewars.com/kata/5894045b8a8a230d0c000077", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "avoid_obstacles", "task_id": "TACO_lite/514", "example": [[[[5, 3, 6, 7, 9]]], ["4"]]} +{"requirement": "You are given an integer n, find the smallest positive integer root of equation x, or else print -1 if no roots are found.\nEquation: x^2+s(x)*x-n=0\nwhere x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system.\n \nExample 1:\nInput: n = 110\nOutput: 10\nExplanation: x=10 is the minimum root. \nAs s(10)=1+0=1 and 102+1*10-110=0.\nExample 2:\nInput: n = 5\nOutput: -1\nExplanation: There is no x possible which\nsatisfy the above equation.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function Root() which takes n as input parameter and retuns the minimum root of the given equation. If not possible returns -1.\n \nExpected Time Complexity: O(k) where k is constant\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= n <= 10^{18}", "solutions": ["import math\n\ndef summation(x):\n temp = 0\n while x > 0:\n temp += x % 10\n x //= 10\n return temp\n\ndef roots(a, b, c):\n y = b * b - 4 * a * c\n if y < 0:\n return -1\n ok = (-b + math.sqrt(y)) / (2 * a)\n if int(ok) == ok:\n if ok > 0:\n return int(ok)\n else:\n return -1\n return -1\n\ndef root(x):\n root = 999999999999\n flag = 0\n for i in range(0, 91):\n temp = self.roots(1, i, -x)\n if temp != -1:\n if self.summation(temp) == i:\n if temp < root:\n root = temp\n flag = 1\n if flag:\n return root\n else:\n return -1"], "starter_code": "def root(n):\n", "input_output": {"inputs": ["n = 110", "n = 5"], "outputs": ["10", "-1"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/find-the-smallest-root-of-the-equation-x2-sxx-n0-where-sx-is-the-sum-of-digits-of-root-x2219/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(k) where k is constant", "entry_point": "root", "task_id": "TACO_lite/533", "example": [[[110], [5]], [null, null]]} +{"requirement": "In music, if you double (or halve) the pitch of any note you will get to the same note again.\n\n\"Concert A\" is fixed at 440 Hz, and every other note is defined based on that. 880 Hz is also an A, as is 1760 Hz, as is 220 Hz.\n\nThere are 12 notes in Western music: A, A#, B, C, C#, D, D#, E, F, F#, G, G#. You are given a preloaded dictionary with these 12 notes and one of the pitches that creates that note (starting at Concert A).\n\nNow, given a pitch (in Hz), return the corresponding note. (All inputs will be valid notes).\n\nFor reference, the notes dictionary looks like this:\n\n```python\nnotes_dictionary = {\n 440: \"A\",\n 466.16: \"A#\",\n 493.88: \"B\",\n 523.25: \"C\",\n 554.37: \"C#\", \n 587.33: \"D\", \n 622.25: \"D#\", \n 659.25: \"E\", \n 698.46: \"F\", \n 739.99: \"F#\", \n 783.99: \"G\", \n 830.61: \"G#\"\n}\n```\n\nMusicians: all pitches based on equal tempermanent, taken from [here](http://pages.mtu.edu/~suits/notefreqs.html).", "solutions": ["notes = {440: 'A', 466.16: 'A#', 493.88: 'B', 523.25: 'C', 554.37: 'C#', 587.33: 'D', 622.25: 'D#', 659.25: 'E', 698.46: 'F', 739.99: 'F#', 783.99: 'G', 830.61: 'G#'}\n\ndef get_note(pitch):\n for note in notes:\n if note >= pitch and note % pitch == 0:\n return notes[note]\n elif note < pitch and pitch % note == 0:\n return notes[note]", "N = 'A A# B C C# D D# E F # F# G G#'.split()\nget_note = g = lambda n: 12 < n // 1 < 27 and N[int(n) - 13] or g(n / 2)", "from math import log2\nns = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']\n\ndef get_note(p):\n return ns[round(log2(p / 55) * 12) % 12]", "notesDictionary = {440: 'A', 466.16: 'A#', 493.88: 'B', 523.25: 'C', 554.37: 'C#', 587.33: 'D', 622.25: 'D#', 659.25: 'E', 698.46: 'F', 739.99: 'F#', 783.99: 'G', 830.61: 'G#'}\n\ndef get_note(pitch):\n for (key, value) in notesDictionary.items():\n if max(pitch, key) % min(pitch, key) == 0:\n return value", "notesDictionary = {440: 'A', 466.16: 'A#', 493.88: 'B', 523.25: 'C', 554.37: 'C#', 587.33: 'D', 622.25: 'D#', 659.25: 'E', 698.46: 'F', 739.99: 'F#', 783.99: 'G', 830.61: 'G#'}\n\ndef adjust_pitch(pitch):\n if pitch in notesDictionary:\n return pitch\n elif pitch < 440:\n while pitch not in notesDictionary:\n pitch *= 2\n return pitch\n elif pitch > 830:\n while pitch not in notesDictionary:\n pitch = pitch / 2\n return pitch\n else:\n return -1\n\ndef get_note(pitch):\n return notesDictionary[adjust_pitch(pitch)]"], "starter_code": "def get_note(pitch):\n", "input_output": {"fn_name": "get_note", "inputs": [[440], [220], [880], [523.25], [261.625], [1046.5]], "outputs": [["A"], ["A"], ["A"], ["C"], ["C"], ["C"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5a0599908ba914a6cf000138", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "get_note", "task_id": "TACO_lite/496", "example": [[], []]} +{"requirement": "Given a Binary Number B, find its decimal equivalent.\n \nExample 1:\nInput: B = 10001000\nOutput: 136\nExample 2:\nInput: B = 101100\nOutput: 44\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function binary_to_decimal() which takes the binary number as string input parameter and returns its decimal equivalent.\n \nExpected Time Complexity: O(K * Log(K)) where K is number of bits in binary number.\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= number of bits in binary number <= 16", "solutions": ["def binary_to_decimal(str):\n k = int(str, 2)\n return k", "def binary_to_decimal(str):\n n = int(str)\n new = 0\n for i in range(len(str)):\n rem = n % 10\n new = new + rem * pow(2, i)\n n = n // 10\n return new", "def binary_to_decimal(str):\n a = int(str, 2)\n return a", "def binary_to_decimal(str):\n j = len(str) - 1\n sum = 0\n for i in range(len(str)):\n if int(str[j]) == 0:\n sum += 0\n else:\n sum += 2 ** i\n j -= 1\n return sum", "def binary_to_decimal(str):\n c = int(str, 2)\n return c", "def binary_to_decimal(str):\n str = str[::-1]\n summ = 0\n for i in range(len(str)):\n summ += 2 ** i * int(str[i])\n return summ", "def binary_to_decimal(str):\n C = int(str, 2)\n return C", "def binary_to_decimal(str):\n s = str[::-1]\n ans = 0\n for i in range(len(s)):\n if s[i] == '1':\n ans += pow(2, i)\n return ans", "def binary_to_decimal(str):\n g = int(str, 2)\n return g", "def binary_to_decimal(str):\n char1 = []\n res = 0\n for char in str:\n char1.append(int(char))\n for i in range(len(char1)):\n res += char1.pop() * 2 ** i\n return res", "def binary_to_decimal(str):\n ans = 0\n k = 0\n for i in range(len(str) - 1, -1, -1):\n ans = ans + int(str[i]) * pow(2, k)\n k += 1\n return ans", "def binary_to_decimal(str):\n num = 0\n j = 0\n s = str[::-1]\n for i in s:\n if i == '1':\n num = num + 2 ** j\n j += 1\n return num", "import math\n\ndef binary_to_decimal(str):\n s = int(str)\n an = 0\n p = 0\n while s > 0:\n rem = s % 10\n an = an + rem * 2 ** p\n p += 1\n s = s // 10\n return an", "def binary_to_decimal(str):\n str = str[::-1]\n i = 0\n res = 0\n while i < len(str):\n if str[i] == '1':\n res += 2 ** i\n i += 1\n return res", "def binary_to_decimal(st):\n return int('0b' + st, 2)", "def binary_to_decimal(str):\n lst = list(str)\n add = 0\n number = len(lst) - 1\n for i in range(len(lst)):\n add = add + int(lst[i]) * 2 ** number\n number = number - 1\n return add", "def binary_to_decimal(str):\n lst = list(str)\n store = 0\n num = len(lst) - 1\n for i in range(len(lst)):\n store = store + int(lst[i]) * 2 ** num\n num = num - 1\n return store", "def binary_to_decimal(str):\n x = int(str, 2)\n return x", "def binary_to_decimal(str):\n ans = 0\n curr = 1\n for i in str[::-1]:\n if i == '1':\n ans += curr\n curr *= 2\n return ans", "def binary_to_decimal(B):\n decimal = 0\n power = 0\n for i in range(len(B) - 1, -1, -1):\n if B[i] == '1':\n decimal += 2 ** power\n power += 1\n return decimal", "def binary_to_decimal(str):\n bin = int(str)\n a = 0\n for i in range(0, len(str)):\n d = bin % 10\n a = a + pow(2, i) * d\n bin = int(bin / 10)\n return a", "def binary_to_decimal(str):\n n = int(str, 2)\n return n", "def binary_to_decimal(str):\n sum = 0\n for (i, v) in enumerate(str):\n if v == '1':\n sum += 2 ** (len(str) - 1 - i)\n return sum", "def binary_to_decimal(str):\n str = int(str)\n sol = 0\n i = 0\n while str != 0:\n digit = str % 10\n if digit != 0:\n sol += pow(2, i)\n i += 1\n str = str // 10\n return sol", "def binary_to_decimal(str):\n (c, res) = (0, 0)\n str = str[::-1]\n for i in str:\n res = res + int(i) * pow(2, c)\n c = c + 1\n return res", "def binary_to_decimal(str):\n sum = 0\n n = len(str)\n for i in range(n):\n sum += 2 ** i * int(str[-(i + 1)])\n return sum", "def binary_to_decimal(str):\n dec = int(str, 2)\n return dec", "def binary_to_decimal(str):\n s = int(str, 2)\n return s", "def binary_to_decimal(str):\n s = str[::-1]\n res = 0\n mul = 1\n for i in s:\n res += mul * int(i)\n mul *= 2\n return res", "def binary_to_decimal(str):\n i = int(str, 2)\n return i", "def binary_to_decimal(s):\n b = int(s)\n n = b\n d = 0\n ba = 1\n while n > 0:\n re = n % 10\n d = d + re * ba\n n = n // 10\n ba = ba * 2\n return d", "def binary_to_decimal(str):\n n = len(str)\n dec = 0\n power = 0\n for i in range(n - 1, -1, -1):\n if str[i] == '1':\n dec += 1 << power\n power += 1\n return dec", "def binary_to_decimal(str):\n ans = 0\n count = 0\n for i in str[::-1]:\n ans += 2 ** count * int(i)\n count += 1\n return ans", "def binary_to_decimal(str):\n ip = int(str)\n number = 0\n count = 0\n while ip > 0:\n rem = ip % 10\n ip = (ip - rem) // 10\n number = number + 2 ** count * rem\n count += 1\n return number", "def binary_to_decimal(str):\n num = int(str, 2)\n return num", "def binary_to_decimal(str):\n n = int(str)\n sum = 0\n i = 0\n while n != 0:\n rem = n % 10\n sum = sum + rem * pow(2, i)\n n = n // 10\n i = i + 1\n return sum", "def binary_to_decimal(str):\n K = int(str, 2)\n return K", "def binary_to_decimal(str):\n sum1 = 0\n count = 0\n for i in str[::-1]:\n if i == '1':\n sum1 += 2 ** count\n count += 1\n return sum1", "def binary_to_decimal(str):\n num = int(str)\n dec = 0\n pow = 1\n while num != 0:\n bit = num % 10\n dec = dec + bit * pow\n pow = pow * 2\n num = int(num / 10)\n return dec", "def binary_to_decimal(str):\n a = str[::-1]\n b = 0\n for i in range(len(a)):\n if a[i] == '1':\n b += 2 ** i\n return b", "def binary_to_decimal(str):\n sum = 0\n length = len(str) - 1\n for item in str:\n sum = sum + int(item) * pow(2, length)\n length = length - 1\n return sum", "def binary_to_decimal(str):\n num = int(str)\n dec_value = 0\n base = 1\n temp = num\n while temp:\n last_digit = temp % 10\n temp = int(temp / 10)\n dec_value += last_digit * base\n base = base * 2\n return dec_value", "def binary_to_decimal(str):\n i = 0\n dec = 0\n for j in range(len(str) - 1, -1, -1):\n dec += int(str[j]) * 2 ** i\n i += 1\n return dec", "def binary_to_decimal(binary):\n (decimal, i) = (0, 0)\n binary_new = int(binary)\n while binary_new != 0:\n dec = binary_new % 10\n decimal = decimal + dec * pow(2, i)\n binary_new = binary_new // 10\n i += 1\n return decimal", "def binary_to_decimal(str):\n e = 0\n d = 0\n for i in range(len(str) - 1, -1, -1):\n if str[i] == '1':\n s = 2 ** e\n d = d + s\n e += 1\n return d", "def binary_to_decimal(str):\n str = int(str)\n power = 0\n sum = 0\n while str > 0:\n r = str % 10\n if r == 1:\n sum = sum + 2 ** power\n power += 1\n str = str // 10\n return sum", "def binary_to_decimal(str):\n power = 0\n sum = 0\n for i in range(len(str) - 1, -1, -1):\n if str[i] == '1':\n sum = sum + 2 ** power\n power += 1\n return sum", "def binary_to_decimal(str):\n b = int(str, 2)\n return b", "def binary_to_decimal(n):\n n = int(n)\n decimal = 0\n power = 1\n while n > 0:\n rem = n % 10\n n = n // 10\n decimal += rem * power\n power = power * 2\n return decimal", "def binary_to_decimal(str):\n v = int(str, 2)\n return v", "def binary_to_decimal(str):\n x = len(str) - 1\n k = 0\n d = 0\n for i in range(len(str)):\n d += 2 ** x * int(str[i])\n x -= 1\n return d", "def binary_to_decimal(str):\n num = int(str)\n n = 1\n sum = 0\n while num > 0:\n rem = num % 10\n sum = sum + rem * n\n n = n * 2\n num = num // 10\n return sum", "import math\n\ndef binary_to_decimal(x):\n sum = 0\n for i in range(len(x)):\n sum = sum + int(x[i]) * math.pow(2, len(x) - 1 - i)\n return int(sum)", "def binary_to_decimal(str):\n temp = int(str)\n res = 0\n base = 1\n while temp:\n i = temp % 10\n temp = temp // 10\n res += i * base\n base *= 2\n return res", "def binary_to_decimal(str):\n binary_num = str\n decimal = int(binary_num, 2)\n return decimal", "def binary_to_decimal(str):\n sum = 0\n n = len(str) - 1\n for i in str:\n if i == '1':\n sum = sum + 2 ** n\n n = n - 1\n return sum", "def binary_to_decimal(str):\n num = str\n dec_num = 0\n for (index, string) in enumerate(str[::-1]):\n dec_num = dec_num + pow(2, index) * int(string)\n return dec_num", "def binary_to_decimal(s):\n n = len(s)\n res = 0\n for i in range(n):\n res += int(s[i]) * 2 ** (n - 1 - i)\n return res"], "starter_code": "def binary_to_decimal(str):\n", "input_output": {"inputs": ["B = 10001000", "B = 101100"], "outputs": ["136", "44"]}, "difficulty": "EASY", "raw_tags": ["CPP"], "name": null, "source": "geeksforgeeks", "tags": [], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/binary-number-to-decimal-number3525/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(K * Log(K)) where K is number of bits in binary number.", "entry_point": "binary_to_decimal", "task_id": "TACO_lite/536", "example": [[[10001000], [101100]], ["136", "44"]]} +{"requirement": "Given a linked list of N nodes. The task is to reverse this list.\nExample 1:\nInput:\nLinkedList: 1->2->3->4->5->6\nOutput: 6 5 4 3 2 1\nExplanation: After reversing the list, \nelements are 6->5->4->3->2->1.\nExample 2:\nInput:\nLinkedList: 2->7->8->9->10\nOutput: 10 9 8 7 2\nExplanation: After reversing the list,\nelements are 10->9->8->7->2.\nYour Task:\nThe task is to complete the function reverseList() with head reference as the only argument and should return new head after reversing the list.\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\nConstraints:\n1 <= N <= 10^{4}", "solutions": ["def reverseList(head):\n temp = head\n prev = None\n while temp:\n succ = temp.next\n temp.next = prev\n prev = temp\n temp = succ\n return prev", "def reverseList(head):\n cur = head\n prev = None\n nxt = head.next\n while cur != None:\n nxt = cur.next\n cur.next = prev\n prev = cur\n cur = nxt\n head = prev\n return head", "def reverseList(head):\n curr = head\n next = None\n prev = None\n while curr:\n next = curr.next\n curr.next = prev\n prev = curr\n curr = next\n return prev", "def reverseList(head):\n l = []\n temp = head\n while temp != None:\n l.append(temp.data)\n temp = temp.next\n cur = head\n while cur != None:\n cur.data = l.pop()\n cur = cur.next\n return head", "def reverseList(head):\n prev = None\n curr = head\n forward = curr.next\n while curr is not None:\n curr.next = prev\n prev = curr\n curr = forward\n if forward is not None:\n forward = forward.next\n head = prev\n return head", "def reverseList(head):\n cur = head\n prev = None\n while cur is not None:\n ne = cur.next\n cur.next = prev\n prev = cur\n cur = ne\n return prev", "def reverseList(head):\n curr = head\n res = []\n while curr:\n res.append(curr.data)\n curr = curr.next\n curr = head\n while curr:\n curr.data = res.pop()\n curr = curr.next\n return head", "def reverseList(head):\n prev = None\n current = head\n while current:\n next = current.next\n current.next = prev\n prev = current\n current = next\n return prev", "def reverseList(head):\n prev = None\n curr = head\n while curr is not None:\n next_node = curr.next\n curr.next = prev\n prev = curr\n curr = next_node\n return prev", "def reverseList(head):\n l = []\n a = head\n while a != None:\n l.append(a.data)\n a = a.next\n a = head\n while a != None:\n a.data = l.pop()\n a = a.next\n return head", "def reverseList(head):\n if head is None or head.next is None:\n return head\n prev = None\n curr = head\n forwerd = None\n while curr != None:\n forwerd = curr.next\n curr.next = prev\n prev = curr\n curr = forwerd\n return prev", "def reverseList(head):\n t = head\n s = []\n while t is not None:\n s.append(t.data)\n t = t.next\n s = s[::-1]\n t = Node(s[0])\n ans = t\n if len(s) > 1:\n for x in s[1:]:\n t.next = Node(x)\n t = t.next\n return ans", "def reverseList(head):\n ress = []\n curr = head\n while curr != None:\n ress.append(curr.data)\n curr = curr.next\n curr = head\n while curr != None:\n curr.data = ress.pop()\n curr = curr.next\n return head", "def reverseList(head):\n if head is None:\n return head\n (prev, curr, next_) = (None, head, None)\n while curr:\n next_ = curr.next\n curr.next = prev\n prev = curr\n curr = next_\n return prev", "def reverseList(head):\n prev = None\n current = head\n while current is not None:\n temp = current.next\n current.next = prev\n prev = current\n current = temp\n head = prev\n return head", "def reverseList(head):\n prev = None\n curr = head\n nxt = head.next\n while curr != None:\n curr.next = prev\n prev = curr\n curr = nxt\n if curr == None:\n nxt = None\n else:\n nxt = curr.next\n head = prev\n return head", "def reverseList(head):\n previous = None\n current = head\n while current:\n next = current.next\n current.next = previous\n previous = current\n current = next\n return previous", "import sys\nsys.setrecursionlimit(int(1000000.0))\n\ndef recRev(p, c):\n if c is None:\n return p\n n = c.next\n c.next = p\n return self.recRev(c, n)\n\ndef reverseList(head):\n return self.recRev(None, head)", "def reverseList(head):\n (p, c) = (None, head)\n while c:\n n = c.next\n c.next = p\n (p, c) = (c, n)\n return p", "def reverseList(head):\n temp = head\n poin = None\n while temp:\n pre = temp.next\n temp.next = poin\n poin = temp\n temp = pre\n return poin", "def reverseList(head):\n cu = head\n prev = None\n while cu is not None:\n next = cu.next\n cu.next = prev\n prev = cu\n cu = next\n head = prev\n return head", "def reverseList(head):\n if head == None and head.next == None:\n return head\n prev = None\n curr = head\n forward = None\n while curr != None:\n forward = curr.next\n curr.next = prev\n prev = curr\n curr = forward\n return prev", "def __init__(val):\n self.data = val\n self.next = None\n\ndef reverseList(head):\n prev = None\n current = head\n while current is not None:\n next = current.next\n current.next = prev\n prev = current\n current = next\n head = prev\n return head", "import sys\n\ndef reverse(prev, curr):\n if curr == None:\n return prev\n head = self.reverse(curr, curr.next)\n curr.next = prev\n return head\n\ndef reverseList(head):\n sys.setrecursionlimit(100000)\n prev = None\n curr = head\n return self.reverse(prev, curr)", "def __init__(val):\n self.data = val\n self.next = None\n\ndef reverseList(head):\n prev = None\n if head is not None:\n cur = head\n else:\n return head\n while True:\n ne = cur.next\n cur.next = prev\n prev = cur\n if ne is not None:\n cur = ne\n else:\n return cur\n return cur", "def reverseList(head):\n if head == None:\n return head\n if head.next == None:\n return head\n r = head\n head = head.next\n r.next = None\n while head != None:\n temp = r\n r = head\n head = head.next\n r.next = None\n r.next = temp\n return r", "def __init__(val):\n self.data = val\n self.next = None\n\ndef reverseList(head):\n prev = None\n curr = head\n next = None\n while curr:\n next = curr.next\n curr.next = prev\n prev = curr\n curr = next\n head = prev\n return head", "def reverseList(head):\n curr = head\n later = None\n while curr:\n next = curr.next\n curr.next = later\n later = curr\n curr = next\n return later", "def reverseList(head):\n curr_node = head\n prev_node = None\n while curr_node:\n next_node = curr_node.next\n curr_node.next = prev_node\n prev_node = curr_node\n curr_node = next_node\n head = prev_node\n return head", "def reverseList(head):\n temp_lst = []\n curr_node = head\n while curr_node:\n temp_lst.append(curr_node.data)\n curr_node = curr_node.next\n counter = -1\n x = len(temp_lst)\n curr_node = head\n for i in range(-1, -(x + 1), -1):\n curr_node.data = temp_lst[i]\n curr_node = curr_node.next\n return head", "def reverseList(head):\n k = []\n temp = head\n while temp != None:\n k.append(temp.data)\n temp = temp.next\n temp = head\n while temp != None:\n temp.data = k.pop()\n temp = temp.next\n return head", "def reverseList(head):\n x = []\n while head:\n x.append(head.data)\n head = head.next\n x = x[::-1]\n head = Node(x[0])\n cur = head\n for i in range(1, len(x)):\n cur.next = Node(x[i])\n cur = cur.next\n return head", "def reverseList(head):\n prev = None\n while head:\n ahead = head.next\n head.next = prev\n prev = head\n head = ahead\n return prev", "def reverseList(head):\n l = None\n p = head\n while p:\n temp = Node(p.data)\n if l is None:\n l = temp\n else:\n temp.next = l\n l = temp\n p = p.next\n return l", "def reverseList(head):\n if not head or not head.next:\n return head\n p = None\n c = head\n n = head.next\n while n:\n c.next = p\n p = c\n c = n\n n = n.next\n c.next = p\n return c", "import sys\nsys.setrecursionlimit(550000)\n\ndef reverseList(head):\n curr = None\n rem = head\n\n def helper(curr, node):\n if not node:\n return curr\n t = node.next\n node.next = curr\n return helper(node, t)\n return helper(curr, rem)", "def reverseList(head):\n dummy = None\n while head:\n nextnode = head.next\n head.next = dummy\n dummy = head\n head = nextnode\n return dummy", "def reverseList(head):\n if head is None:\n return\n prev = None\n current = head\n while current is not None:\n nextnode = current.next\n current.next = prev\n prev = current\n current = nextnode\n return prev", "def reverseList(head):\n temp = None\n while head:\n next = head.next\n head.next = temp\n temp = head\n head = next\n return temp"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["LinkedList:1->2->3->4->5->6", "LinkedList:2->7->8->9->10"], "outputs": ["6 5 4 3 2 1", "10 9 8 7 2"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Linked List"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/reverse-a-linked-list/1", "Expected Auxiliary Space": "O(1).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "__init__", "task_id": "TACO_lite/338", "example": [[], []]} +{"requirement": "Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum.\nExample 1:\nInput:\n5\n4 2 -3 1 6\nOutput: \nYes\nExplanation: \n2, -3, 1 is the subarray \nwith sum 0.\nExample 2:\nInput:\n5\n4 2 0 1 6\nOutput: \nYes\nExplanation: \n0 is one of the element \nin the array so there exist a \nsubarray with sum 0.\nYour Task:\nYou only need to complete the function subArrayExists() that takes array and n as parameters and returns true or false depending upon whether there is a subarray present with 0-sum or not. Printing will be taken care by the drivers code.\nExpected Time Complexity: O(n).\nExpected Auxiliary Space: O(n).\nConstraints:\n1 <= n <= 10^{4}\n-10^{5} <= a[i] <= 10^{5}", "solutions": ["def subarrayexists(arr, n):\n n_sum = 0\n s = set()\n for i in range(len(arr)):\n n_sum += arr[i]\n if n_sum == 0 or n_sum in s:\n return True\n s.add(n_sum)\n return False", "def subarrayexists(arr, n):\n curr_sum = 0\n d = {}\n for i in range(n):\n curr_sum = curr_sum + arr[i]\n if curr_sum == 0 or curr_sum in d:\n return True\n d[curr_sum] = i\n return False", "def subarrayexists(arr, n):\n st = set()\n st.add(0)\n sum = 0\n for i in range(n):\n sum += arr[i]\n if sum in st:\n return True\n st.add(sum)\n if sum != 0:\n return False\n return True", "def subarrayexists(arr, n):\n sumhashmap = {0: 1}\n localsum = 0\n for val in arr:\n if val == 0:\n return True\n localsum += val\n if localsum in sumhashmap:\n return True\n else:\n sumhashmap[localsum] = 1\n return False", "def subarrayexists(arr, n):\n hm = {}\n if sum(arr) == 0:\n return True\n curr_sum = 0\n for i in range(n):\n curr_sum += arr[i]\n if curr_sum == 0:\n return True\n if curr_sum in hm:\n return True\n else:\n hm[curr_sum] = i\n return False", "def subarrayexists(arr, n):\n s = 0\n a = 0\n x = 0\n d = {}\n for i in range(n):\n s = s + arr[i]\n if s == 0:\n x = x + 1\n break\n if s not in d:\n d[s] = i\n else:\n x = x + 1\n break\n if x == 0:\n return False\n else:\n return True", "def subarrayexists(arr, n):\n d = {}\n s = 0\n for i in arr:\n s += i\n if s == 0 or i == 0 or s in d:\n return True\n else:\n d[s] = 1\n return False", "def subarrayexists(arr, n):\n dici = {}\n sumi = 0\n for i in range(n):\n sumi += arr[i]\n if sumi in dici or sumi == 0:\n return True\n dici[sumi] = 1\n return False", "def subarrayexists(arr, n):\n ns = 0\n s = set()\n for i in range(n):\n ns += arr[i]\n if ns == 0 or ns in s:\n return 1\n s.add(ns)\n return 0", "def subarrayexists(arr, n):\n prefix_sum = [0] * (n + 1)\n for i in range(1, n + 1):\n prefix_sum[i] = prefix_sum[i - 1] + arr[i - 1]\n hmap = {}\n for i in prefix_sum:\n if i not in hmap:\n hmap[i] = 1\n else:\n return True\n return False", "def subarrayexists(arr, n):\n sum = 0\n s = set()\n d = True\n f = False\n for i in range(n):\n sum = sum + arr[i]\n if sum == 0 or sum in s:\n return d\n s.add(sum)\n return f\n if d:\n return 'Yes'\n else:\n return 'No'", "def subarrayexists(arr, n):\n hash = set()\n for i in range(n):\n if i == 0:\n if arr[i] == 0:\n return True\n else:\n arr[i] += arr[i - 1]\n if arr[i] in hash or arr[i] == 0:\n return True\n hash.add(arr[i])\n return False", "def subarrayexists(arr, n):\n seen_sums = set()\n running_sum = 0\n for num in arr:\n running_sum += num\n if running_sum == 0 or running_sum in seen_sums:\n return True\n seen_sums.add(running_sum)\n return False", "def subarrayexists(arr, n):\n h = {}\n res = 0\n for i in range(n):\n res += arr[i]\n if res == 0:\n return 1\n if res in h:\n return 1\n h[res] = 1\n return 0", "def subarrayexists(arr, n):\n sum = 0\n s = set()\n for each in arr:\n sum += each\n if sum in s or sum == 0:\n return True\n s.add(sum)\n return False", "def subarrayexists(arr, n):\n pref_sum = {0: 1}\n curr_sum = 0\n for elem in arr:\n curr_sum += elem\n if curr_sum in pref_sum:\n return True\n else:\n pref_sum[curr_sum] = 1\n return False", "def subarrayexists(arr, n):\n sum = 0\n s = set()\n for i in range(n):\n sum = sum + arr[i]\n if sum == 0 or sum in s:\n return True\n else:\n s.add(sum)\n return False", "def subarrayexists(arr, n):\n addSum = 0\n maxLen = 0\n d = {}\n for i in range(len(arr)):\n addSum += arr[i]\n if addSum == 0:\n maxLen = i + 1\n elif addSum in d:\n maxLen = max(maxLen, i - d[addSum])\n else:\n d[addSum] = i\n if maxLen >= 1:\n return True\n else:\n return False", "def subarrayexists(arr, n):\n sm = 0\n dic = {0}\n for el in arr:\n if el == 0:\n return True\n sm += el\n if sm in dic:\n return True\n dic.add(sm)\n return False", "def subarrayexists(arr, n):\n prefix_sum_set = set()\n prefix_sum = 0\n for i in range(n):\n prefix_sum += arr[i]\n if prefix_sum == 0 or prefix_sum in prefix_sum_set:\n return True\n prefix_sum_set.add(prefix_sum)\n return False", "def subarrayexists(arr, n):\n d = {0: 1}\n sumVal = 0\n for i in arr:\n sumVal += i\n if sumVal in d:\n return 1\n d[sumVal] = 1\n return 0", "def subarrayexists(arr, n):\n dic = {0: 0}\n s = 0\n for i in arr:\n s += i\n try:\n dic[s] += 1\n return True\n except:\n dic[s] = 0\n return False", "def subarrayexists(arr, n):\n prefixSum = {}\n sum = 0\n for i in range(n):\n sum += arr[i]\n if sum == 0 or sum in prefixSum:\n return True\n prefixSum[sum] = i\n return False", "def subarrayexists(arr, n):\n sum = 0\n d = {}\n for i in arr:\n sum += i\n if sum in d:\n return True\n if sum == 0:\n return True\n d[sum] = 1\n return False", "def subarrayexists(arr, n):\n pre_sum = 0\n s = set()\n for i in arr:\n pre_sum += i\n if pre_sum == 0 or pre_sum in s:\n return True\n s.add(pre_sum)\n return False", "from collections import *\n\ndef subarrayexists(arr, n):\n d = defaultdict(int)\n d[0] = 1\n sumsofar = 0\n count = 0\n for i in range(n):\n sumsofar += arr[i]\n count += d[sumsofar]\n d[sumsofar] = 1\n if count >= 1:\n return True\n else:\n return False", "def subarrayexists(arr, n):\n m = {}\n sum = 0\n for i in range(n):\n sum += arr[i]\n if sum in m or sum == 0:\n return 1\n else:\n m[sum] = 1\n return 0", "def subarrayexists(arr, n):\n d = {0: -1}\n cumulative = 0\n for i in range(n):\n cumulative += arr[i]\n if cumulative in d:\n return True\n else:\n d[cumulative] = i\n return False", "from collections import *\n\ndef subarrayexists(nums, n):\n d = defaultdict(int)\n presum = 0\n ans = 0\n d[0] = 1\n for i in range(len(nums)):\n presum = presum + nums[i]\n if presum in d:\n ans += d[presum]\n d[presum] += 1\n return True if ans > 0 else False", "def subarrayexists(arr, n):\n s = 0\n l = []\n for i in arr:\n s = s + i\n l.append(s)\n d = {}\n for i in l:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n flag = 0\n for i in d:\n if d[i] >= 2 or i == 0:\n flag = 1\n break\n if flag == 1:\n return True\n else:\n return False", "def subarrayexists(arr, n):\n prefixArr = []\n prefixArr.append(arr[0])\n dict1 = {}\n dict1[arr[0]] = 0\n for i in range(1, n):\n prefixArr.append(prefixArr[i - 1] + arr[i])\n if prefixArr[i] == 0:\n return True\n if prefixArr[i] not in dict1:\n dict1[prefixArr[i]] = i\n else:\n return True\n return False", "def subarrayexists(arr, n):\n dict = {}\n s = 0\n for i in arr:\n s += i\n if s == 0 or i == 0 or s in dict:\n return True\n else:\n dict[s] = 3\n return False", "def subarrayexists(arr, n):\n sum_set = set()\n sum_set.add(0)\n sum_so_far = 0\n for num in arr:\n sum_so_far += num\n if sum_so_far in sum_set:\n return True\n break\n sum_set.add(sum_so_far)", "def subarrayexists(arr, n):\n l = []\n sum_ = 0\n d = {}\n for i in range(n):\n sum_ += arr[i]\n if sum_ == 0 or sum_ in d:\n return True\n d[sum_] = 1\n return False", "from collections import defaultdict\n\ndef subarrayexists(arr, n):\n d = defaultdict(lambda : 0)\n total = 0\n for x in arr:\n total += x\n if total in d:\n return True\n if x == 0 or total == 0:\n return True\n d[total] += 1", "def subarrayexists(arr, n):\n dict = {}\n s = set()\n sum = 0\n for i in range(len(arr)):\n sum += arr[i]\n if sum == 0 or sum in dict:\n return True\n dict[sum] = 1\n return False", "def subarrayexists(arr, n):\n k = 0\n d = {0: 1}\n sum1 = 0\n for i in arr:\n sum1 = sum1 + i\n if sum1 - k in d:\n return 1\n if sum1 not in d:\n d[sum1] = 1\n if sum1 in d:\n d[sum1] = d[sum1] + 1\n return 0", "def subarrayexists(arr, n):\n si = 0\n s = 0\n dic = {}\n while si < n:\n s += arr[si]\n if s == 0:\n return True\n if s in dic:\n return True\n else:\n dic[s] = si\n si += 1\n return False", "def subarrayexists(arr, n):\n seen = {}\n sum_upto = 0\n for ele in arr:\n sum_upto += ele\n if sum_upto == 0:\n return True\n elif sum_upto in seen:\n return True\n else:\n seen[sum_upto] = 1\n return False", "def subarrayexists(nums, n):\n curr_sum = nums[0]\n prefix = [curr_sum]\n for i in range(1, len(nums)):\n curr_sum += nums[i]\n prefix.append(curr_sum)\n d = {}\n for i in range(len(prefix)):\n if prefix[i] == 0:\n return True\n if prefix[i] not in d.keys():\n d[prefix[i]] = [i]\n else:\n d[prefix[i]].append(i)\n for i in d.values():\n if len(i) > 1:\n return True\n return False", "def subarrayexists(arr, n):\n a = set()\n a.add(0)\n s = 0\n for i in arr:\n s += i\n if s in a:\n return True\n a.add(s)\n return s == 0", "def subarrayexists(arr, n):\n prefix_sum = 0\n prefix_sum_set = set()\n for element in arr:\n prefix_sum = prefix_sum + element\n if prefix_sum == 0:\n return True\n if prefix_sum in prefix_sum_set:\n return True\n else:\n prefix_sum_set.add(prefix_sum)\n return False", "def subarrayexists(arr, n):\n s1 = set()\n cs = 0\n for i in range(n):\n cs = cs + arr[i]\n if cs in s1 or cs == 0:\n return True\n s1.add(cs)\n return False", "def subarrayexists(arr, n):\n st = set()\n prefixsum = []\n sum = 0\n for i in arr:\n sum += i\n if sum == 0 or sum in st:\n return True\n else:\n st.add(sum)\n return False", "def subarrayexists(arr, n):\n seen = set()\n sum1 = 0\n for i in range(n):\n seen.add(sum1)\n sum1 += arr[i]\n if sum1 in seen:\n return True\n return False", "def subarrayexists(arr, n):\n d = {}\n c = 0\n for i in range(n):\n c += arr[i]\n if c in d or c == 0:\n return 1\n else:\n d[c] = 1\n if c == 0:\n return 1\n else:\n return 0", "def subarrayexists(arr, n):\n s = 0\n h = {0}\n dik = {}\n for i in range(n):\n if arr[i] == 0:\n return True\n s += arr[i]\n if s == 0:\n return True\n if s in dik:\n return True\n dik[s] = s\n return False", "def subarrayexists(arr, n):\n prev_sum = set()\n curr_sum = 0\n for i in arr:\n curr_sum += i\n if curr_sum == 0 or curr_sum in prev_sum:\n return True\n prev_sum.add(curr_sum)\n return False", "def subarrayexists(arr, n):\n prefix_sum = {0: -1}\n sum = 0\n k = 0\n for i in range(len(arr)):\n sum += arr[i]\n if sum - k in prefix_sum:\n return True\n if sum not in prefix_sum:\n prefix_sum[sum] = i\n return False", "def subarrayexists(arr, n):\n _d = {}\n _csum = 0\n for i in range(n):\n _csum += arr[i]\n if _csum in _d.keys() or _csum == 0:\n return True\n else:\n _d[_csum] = -1\n if _csum == 0:\n return True\n return False", "def subarrayexists(arr, n):\n s = 0\n d = {}\n d[s] = True\n for i in range(len(arr)):\n s += arr[i]\n if s in d:\n return True\n d[s] = True\n return False"], "starter_code": "def subarrayexists(arr,n):\n", "input_output": {"inputs": ["5\n4 2 -3 1 6", "5\n4 2 0 1 6"], "outputs": ["Yes", "Yes"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Hash", "Map", "sliding-window", "STL", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures", "Amortized analysis"], "skill_types": ["Amortized analysis", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1", "Expected Auxiliary Space": "O(n).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n).", "entry_point": "subarrayexists", "task_id": "TACO_lite/530", "example": [[], []]} +{"requirement": "There are N stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter).\nNote: Order does not matter means for n=4 {1 2 1},{2 1 1},{1 1 2} are considered same.\nExample 1:\nInput:\nN = 4\nOutput: 3\nExplanation: You can reach 4th stair in\n3 ways.\n3 possible ways are:\n1, 1, 1, 1\n1, 1, 2\n2, 2\nExample 2:\nInput:\nN = 5\nOutput: 3\nExplanation:\nYou may reach the 5th stair in 3 ways.\nThe 3 possible ways are:\n1, 1, 1, 1, 1\n1, 1, 1, 2\n1, 2, 2\nYour Task:\nYour task is to complete the function countWays() which takes single argument(N) and returns the answer.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 <= N <= 10^{6}", "solutions": ["def countways(m):\n mod = 1000000007\n ans = 1\n while m - 1 > 0:\n ans = (ans + 1) % mod\n m = m - 2\n return ans", "def countways(m):\n mod = 1000000007\n return int(m / 2 + 1)", "def nthStair1(a, n, W):\n global dp\n if W == 0:\n return 1\n if n == 0:\n return 0\n if dp[n][W] != -1:\n return dp[n][W]\n if a[n - 1] <= W:\n dp[n][W] = self.nthStair1(a, n, W - a[n - 1]) + self.nthStair1(a, n - 1, W)\n return dp[n][W]\n else:\n dp[n][W] = self.nthStair1(a, n - 1, W)\n return dp[n][W]\n\ndef countways(m):\n mod = 1000000007\n global dp\n dp = [[-1 for i in range(m + 1)] for j in range(2 + 1)]\n a = [1, 2]\n return self.nthStair1(a, 2, m)", "def countways(m):\n mod = 1000000007\n if m < 2:\n return 1\n count = [0 for _ in range(m + 1)]\n count[0] = count[1] = 1\n for step in range(1, 3):\n for stair in range(2, m + 1):\n count[stair] += count[stair - step]\n count[stair] %= mod\n return count[m]", "def countways(m):\n return (m // 2 + 1) % 1000000007", "def countwaysHelper(m, arr, n, memo):\n mod = 1000000007\n if (m, n) in memo:\n return memo[m, n]\n if m == 0:\n return 1\n if n == 0 or m < 0:\n return 0\n ans1 = self.countwaysHelper(m - arr[n - 1], arr, n, memo)\n ans2 = self.countwaysHelper(m, arr, n - 1, memo)\n memo[m, n] = (ans1 + ans2) % mod\n return memo[m, n]\n\ndef countways(m):\n return self.countwaysHelper(m, [1, 2], 2, dict())", "def countways(m):\n dp = [-1] * (m + 1)\n dp[0] = 0\n dp[1] = 1\n for i in range(2, m + 1):\n if i % 2 == 0:\n dp[i] = dp[i - 1] + 1\n else:\n dp[i] = dp[i - 1]\n return dp[m]", "def countways(n):\n mod = 1000000007\n dp = [None] * (n + 1)\n dp[0] = 1\n dp[1] = 1\n for i in range(2, n + 1):\n dp[i] = dp[i - 2] + 1\n return dp[n]", "def countways(m):\n mod = 1000000007\n ways = [0] * (m + 1)\n ways[0] = 1\n ways[1] = 1\n for i in range(2, m + 1):\n ways[i] = (ways[i - 2] + 1) % mod\n return ways[m]", "def countways(n):\n if n == 1:\n return 1\n dp = [[0 for i in range(2)] for j in range(n)]\n dp[0][0] = 1\n dp[1][0] = 1\n dp[1][1] = 1\n for i in range(2, n):\n dp[i][0] += dp[i - 1][0]\n dp[i][1] = (dp[i - 2][1] + dp[i][0]) % 1000000007\n return sum(dp[n - 1]) % 1000000007", "def countways(m):\n mod = 1000000007\n arr = [1, 2]\n n = 2\n dp = [[-1 for i in range(n + 1)] for i in range(m + 1)]\n\n def recursive(dp, arr, n, m):\n if m == 0:\n return 1\n if n == 0:\n return 0\n if dp[m][n] != -1:\n return dp[m][n]\n dp[m][n] = recursive(dp, arr, n - 1, m)\n if m - arr[n - 1] >= 0:\n dp[m][n] += recursive(dp, arr, n, m - arr[n - 1])\n return dp[m][n]\n return recursive(dp, arr, n, m)", "def countways(m):\n n = m\n dp = [0] * (n + 1)\n dp[0] = 1\n for i in range(1, n + 1):\n os = dp[i - 1]\n ts = 0\n if i > 1:\n ts = dp[i - 2]\n dp[i] = int((os + ts) / 2) + 1\n return dp[n]", "def countways(m):\n mod = 1000000007\n dp = [0 for _ in range(m + 1)]\n dp[0] = 1\n for i in range(1, 3):\n for j in range(i, m + 1):\n dp[j] += dp[j - i]\n return dp[m]", "def countways(m):\n count = 0\n for x in range(m + 1):\n if (m - x) % 2 == 0:\n count += 1\n return count", "def count(m):\n if m == 1:\n return 1\n if m <= 0:\n return 0\n ans = self.count(m - 1) + self.count(m - 2)\n return ans\n\ndef countways(m):\n mod = 1000000007\n dp = [0 for _ in range(m + 1)]\n dp[0] = 1\n dp[1] = 1\n for i in range(2, m + 1):\n dp[i] = 1 + min(dp[i - 1], dp[i - 2])\n return dp[m]", "def countways(n):\n mod = 1000000007\n if n == 1:\n return 1\n if n == 2:\n return 2\n p1 = 1\n p2 = 2\n for i in range(3, n + 1):\n c = (min(p1, p2) + 1) % mod\n p1 = p2\n p2 = c\n return c", "def util(n):\n if n == 1:\n return 1\n if n == 2 or n == 3:\n return 2\n return 1 + max(self.util(n - 1), self.util(n - 2)) % self.mod\n\ndef countways(m):\n return m // 2 + 1", "def countways(m):\n from math import floor as fl\n return fl(m / 2 + 1)", "def countways(m):\n n = m\n mod = 1000000007\n dp = [0] * (n + 1)\n if n == 1:\n return 1\n if n == 2:\n return 2\n dp[0] = 0\n dp[1] = 1\n dp[2] = 2\n for i in range(3, n + 1):\n if i % 2 != 0:\n dp[i] = dp[i - 1] % mod\n else:\n dp[i] = (dp[i - 1] + 1) % mod\n return dp[-1]", "def countways(m):\n mod = 1000000007\n if m < 2:\n return 1\n a = 1\n b = 1\n for i in range(2, m + 1):\n c = a + 1\n a = b\n b = c\n return c % mod", "def countways(m):\n return m // 2 + 1\n mod = 1000000007\n if m == 0:\n return 1\n res = 1\n for i in range(1, m + 1):\n if i % 2 == 0:\n res += 1\n return res", "def countways(m):\n mod = 1000000007\n dp = [-1] * (m + 1)\n\n def count(n, dp):\n if n <= 2:\n return n\n if n < 0:\n return 0\n if dp[n] == -1:\n dp[n] = 1 + count(n - 2, dp)\n return dp[n] % mod\n return count(m, dp)", "def countways(m):\n if m == 2:\n return 2\n if m == 1:\n return 1\n res = 0\n while m >= 2:\n m = m - 2\n res += 1\n return res + 1", "def countways(n):\n mod = 1000000007\n result = self.solve(n)\n return result % mod\n\ndef solve(n):\n minus1 = minus2 = 0\n for i in range(n + 1):\n result = 1 + min(minus1, minus2)\n minus2 = minus1\n minus1 = result\n return result", "def countways(n):\n mod = 1000000007\n result = self.solve(n)\n return result % mod\n\ndef solve(n):\n times = max(2, n + 1)\n dp = [0 for i in range(times)]\n dp[0] = dp[1] = 1\n for i in range(2, n + 1):\n dp[i] = 1 + min(dp[i - 1], dp[i - 2])\n return dp[n]", "def countways(n):\n dp = [-1 for i in range(n + 1)]\n dp[0] = 1\n result = self.solve(n, dp)\n return result % 1000000007\n\ndef solve(n, dp):\n if n < 0:\n return 0\n if dp[n] != -1:\n return dp[n]\n minus1 = self.solve(n - 1, dp)\n minus2 = self.solve(n - 2, dp)\n dp[n] = 1 + min(minus1, minus2)\n return dp[n]", "def countways(n):\n mod = 1000000007\n result = 1 + n // 2\n return result % mod", "def countways(m):\n mod = 1000000007\n if m < 2:\n return 1\n return (m // 2 + 1) % mod", "def countways(m):\n if m <= 2:\n return m\n return m // 2 + 1", "def countways(m):\n global mod\n mod = 1000000007\n\n def recurs(m):\n if m == 0:\n return 1\n if m < 0:\n return 0\n p = recurs(m - 2)\n q = recurs(m - 1)\n return (p % mod + q % mod) % mod\n return int(m / 2) + 1", "def countways(m):\n t = [-1 for i in range(m + 1)]\n return self.helper(m, t)\n\ndef helper(m, t):\n if m == 0:\n return 1\n if m < 0:\n return 0\n if t[m] != -1:\n return t[m]\n step1 = self.helper(m - 1, t)\n step2 = self.helper(m - 2, t)\n t[m] = 1 + min(step1, step2)\n return t[m]", "def countways(m):\n mod = 1000000007\n d = {0: 1, 1: 1, 2: 2}\n for i in range(2, m + 1):\n d[i] = min(d[i - 1] % mod, d[i - 2] % mod) + 1\n return d[m] % mod", "def countways(m):\n mod = 1000000007\n possible = [1, 2]\n no_of_ele = 2\n dp = [0] * (m + 1)\n dp[0] = 1\n for i in range(no_of_ele):\n for j in range(m + 1):\n if j - possible[i] >= 0:\n dp[j] = dp[j] + dp[j - possible[i]]\n return dp[m] % mod", "MOD = pow(10, 9) + 7\n\ndef countways(m):\n return 1 + m // 2", "def countways(m):\n mod = 1000000007\n v = [1, 2]\n dp = [0] * (m + 1)\n dp[0] = 1\n for i in range(0, len(v)):\n for j in range(v[i], m + 1):\n dp[j] = dp[j] + dp[j - v[i]]\n return dp[-1] % mod", "def __init__():\n self.d = {}\n self.res = set()\n\ndef countways(m):\n mod = 1000000007\n dp = [1] * (m + 1)\n n = m\n for i in range(2, m + 1):\n dp[i] = dp[i] + dp[i - 2]\n return dp[n] % mod", "def countways(m):\n dp = [-1 for i in range(m + 1)]\n dp[0] = 0\n dp[1] = 1\n if m > 1:\n for i in range(2, m + 1):\n if i == 2:\n way1 = dp[i - 1]\n way2 = 100000\n else:\n way1 = dp[i - 1]\n way2 = dp[i - 2]\n dp[i] = min(way1, way2) + 1\n return dp[m]", "def countways(m):\n dp = [-1 for i in range(m + 1)]\n dp[0] = 0\n dp[1] = 1\n if m > 1:\n dp[2] = 2\n for i in range(3, m + 1):\n way1 = dp[i - 1]\n way2 = dp[i - 2]\n dp[i] = min(way1, way2) + 1\n return dp[m]\n mod = 1000000007", "def countways(m):\n mod = 1000000007\n count = 1\n while m > 1:\n m -= 2\n count += 1\n return count", "def countways(m):\n mod = 1000000007\n dp = [[-1 for i in range(m + 1)] for j in range(m + 1)]\n dec = {}\n self.ans = 0\n\n def solve(st, no):\n if st == 0:\n if dec.get(no) == None:\n dec[no] = 1\n self.ans += 1\n return 0\n return 0\n if st < 0:\n return 0\n if dp[no][st] != -1:\n return dp[no][st]\n dp[no][st] = solve(st - 1, no + 1) + solve(st - 2, no + 1)\n return dp[no][st]\n solve(m, 0)\n return self.ans", "def countways(m):\n mod = 1000000007\n dp = [[0 for i in range(2)] for j in range(m + 1)]\n for i in range(2):\n dp[0][i] = 1\n arr = [i + 1 for i in range(2)]\n for i in range(1, m + 1):\n for j in range(2):\n take = dp[i - arr[j]][j] if i >= arr[j] else 0\n nottake = dp[i][j - 1] if j > 0 else 0\n dp[i][j] = take + nottake\n return dp[m][1]", "def countways(m):\n dt = [[-1 for i in range(m + 1)] for j in range(3)]\n\n def ab(m, d=[1, 2], n=2):\n if m == 0:\n return 1\n if n == 0 or m < 0:\n return 0\n if dt[n][m] != -1:\n return dt[n][m]\n a = ab(m, d[1:], n - 1)\n b = ab(m - d[0], d, n)\n dt[n][m] = a + b\n return a + b\n return ab(m)", "def countways(m):\n\n def ab(m, d=[1, 2], n=2):\n if m == 0:\n return 1\n if n == 0 or m < 0:\n return 0\n a = ab(m, d[1:], n - 1)\n b = ab(m - d[0], d, n)\n return a + b\n return ab(m)", "def __init__():\n self.d = {}\n\ndef countways(n):\n if n == 1 or n == 2:\n return n\n if n in self.d:\n return self.d[n]\n a1 = self.countways(n - 1)\n a2 = self.countways(n - 2)\n self.d[n] = min(a1, a2) + 1\n return self.d[n]"], "starter_code": "def countways(m):\n", "input_output": {"inputs": ["N = 4", "N = 5"], "outputs": ["3", "3"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Mathematics"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/count-ways-to-nth-stairorder-does-not-matter1322/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "countways", "task_id": "TACO_lite/537", "example": [[[4], [5]], ["3", "3"]]} +{"requirement": "One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #.\n\n\n _9_\n / \\\n 3 2\n / \\ / \\\n 4 1 # 6\n/ \\ / \\ / \\\n# # # # # #\n\n\nFor example, the above binary tree can be serialized to the string \"9,3,4,#,#,1,#,#,2,#,6,#,#\", where # represents a null node.\n\nGiven a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.\n\nEach comma separated value in the string must be either an integer or a character '#' representing null pointer.\n\nYou may assume that the input format is always valid, for example it could never contain two consecutive commas such as \"1,,3\".\n\nExample 1:\n\n\nInput: \"9,3,4,#,#,1,#,#,2,#,6,#,#\"\nOutput: true\n\nExample 2:\n\n\nInput: \"1,#\"\nOutput: false\n\n\nExample 3:\n\n\nInput: \"9,#,#,1\"\nOutput: false", "solutions": ["def isvalidserialization(preorder):\n p = preorder.split(',')\n slot = 1\n for node in p:\n if slot == 0:\n return False\n if node == '#':\n slot -= 1\n else:\n slot += 1\n return slot == 0", "def isvalidserialization(preorder):\n if not preorder:\n return False\n nodes = preorder.split(',')\n stack = [0] if nodes[0] != '#' else []\n dt = {0: 2}\n i = 1\n while stack and i < len(nodes):\n dt[stack[-1]] -= 1\n if dt[stack[-1]] == 0:\n stack.pop()\n if nodes[i] != '#':\n stack.append(i)\n dt[i] = 2\n i = i + 1\n return not stack and i == len(nodes)", "def isvalidserialization(preorder):\n preorder = preorder.split(',')\n if preorder[0] == '#':\n return len(preorder) == 1\n s = []\n curr = preorder[0]\n on_left = True\n for i in range(1, len(preorder)):\n if not curr:\n return False\n e = preorder[i]\n if e != '#':\n if on_left:\n s.append(curr)\n curr = e\n on_left = True\n else:\n if not on_left:\n curr = s.pop() if len(s) > 0 else None\n on_left = False\n return curr is None", "def isvalidserialization(preorder):\n if len(preorder) < 1:\n return False\n stack = []\n for s in preorder.split(','):\n stack.append(False)\n if s == '#':\n while len(stack) > 2 and stack[-2]:\n stack.pop()\n stack.pop()\n stack.pop()\n else:\n stack.append(True)\n return stack == [False, True]", "def isvalidserialization(preorder):\n if not preorder:\n return True\n arr = preorder.split(',')\n s = []\n for a in arr:\n s.append(a)\n while len(s) >= 3 and s[-1] == '#' and (s[-2] == '#') and (s[-3] != '#'):\n s.pop()\n s.pop()\n s.pop()\n s.append('#')\n if s == ['#']:\n return True\n return False", "def isvalidserialization(preorder):\n (stack, preorder) = ([], preorder.split(','))\n top = -1\n for s in preorder:\n stack.append(s)\n top += 1\n while self.endsWithTwoHashes(stack, top):\n (h, top) = (stack.pop(), top - 1)\n (h, top) = (stack.pop(), top - 1)\n if top < 0:\n return False\n stack[-1] = '#'\n return len(stack) == 1 and stack[0] == '#'\n\ndef endsWithTwoHashes(stack, top):\n if top < 1:\n return False\n if stack[top] == '#' and stack[top - 1] == '#':\n return True\n return False", "def isvalidserialization(preorder):\n (preorder, first) = (preorder.split(','), preorder.split(','))\n\n def backward(index):\n if index >= len(preorder) or index < 0:\n return\n if index + 1 < len(preorder) and preorder[index + 1] == preorder[index] == '#' and (index - 1 >= 0) and (preorder[index - 1] != '#'):\n preorder.pop(index)\n preorder.pop(index)\n preorder[index - 1] = '#'\n backward(index - 2)\n else:\n backward(index + 1)\n backward(0)\n return True if preorder != first and preorder == ['#'] or preorder == first == ['#'] else False"], "starter_code": "def isvalidserialization(preorder: str) -> bool:\n", "input_output": {"fn_name": "isValidSerialization", "inputs": [["\"9,3,4,#,#,1,#,#,2,#,6,#,#\""]], "outputs": [false]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Stack", "Binary Tree", "Tree", "String"], "name": null, "source": "leetcode", "tags": ["Tree algorithms", "Data structures", "String algorithms"], "skill_types": ["Data structures"], "url": "https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "isvalidserialization", "task_id": "TACO_lite/383", "example": [[], []]} +{"requirement": "Given an unsorted array of size N. Find the first element in array such that all of its left elements are smaller and all right elements to it are greater than it.\nNote: Left and right side elements can be equal to required element. And extreme elements cannot be required element.\n \nExample 1:\nInput:\nN = 4\nA[] = {4, 2, 5, 7}\nOutput:\n5\nExplanation:\nElements on left of 5 are smaller than 5\nand on right of it are greater than 5.\n \nExample 2:\nInput:\nN = 3\nA[] = {11, 9, 12}\nOutput:\n-1\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function findElement() which takes the array A[] and its size N as inputs and returns the required element. If no such element present in array then return -1.\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\n \nConstraints:\n3 <= N <= 10^{6}\n1 <= A[i] <= 10^{6}", "solutions": ["def findelement(arr, n):\n ans = -1\n maxi = arr[0]\n h = set()\n for i in range(1, n - 1):\n if arr[i] >= maxi:\n h.add(i)\n maxi = arr[i]\n mini = arr[-1]\n for i in range(n - 2, 0, -1):\n if i in h and arr[i] <= mini:\n ans = i\n mini = arr[i]\n if arr[i] < mini:\n mini = arr[i]\n if ans == -1:\n return -1\n return arr[ans]", "def findelement(arr, n):\n ans = -1\n max = arr[0]\n for i in range(1, n):\n if arr[i] < max:\n ans = -1\n elif arr[i] >= max:\n if ans == -1 and i != n - 1:\n ans = arr[i]\n max = arr[i]\n return ans", "def findelement(arr, n):\n l = len(arr)\n i = l - 2\n right_min = [0] * l\n right_min[l - 1] = arr[l - 1]\n while i >= 0:\n if arr[i] <= right_min[i + 1]:\n right_min[i] = arr[i]\n elif arr[i] > right_min[i + 1]:\n right_min[i] = right_min[i + 1]\n i -= 1\n i = 1\n left_max = arr[0]\n while i < l - 1:\n if arr[i] >= left_max:\n if arr[i] == right_min[i]:\n return arr[i]\n left_max = arr[i]\n i += 1\n return -1", "def findelement(arr, n):\n arr1 = [arr[n - 1]]\n m = arr[n - 1]\n for i in range(n - 2, -1, -1):\n if arr[i] < m:\n arr1.append(arr[i])\n m = arr[i]\n else:\n arr1.append(m)\n arr1.reverse()\n m = arr[0]\n for i in range(1, n - 1):\n if arr[i] >= m and arr[i] <= arr1[i + 1]:\n return arr[i]\n if arr[i] > m:\n m = arr[i]\n return -1", "def findelement(arr, n):\n maxi = arr[0]\n mini = arr[-1]\n ans1 = [1] * n\n ans2 = [1] * n\n for i in range(n):\n if arr[i] > maxi:\n maxi = arr[i]\n ans1[i] = maxi\n for i in range(n - 1, -1, -1):\n if arr[i] < mini:\n mini = arr[i]\n ans2[i] = mini\n for i in range(1, n - 1):\n if ans1[i] == ans2[i]:\n return ans1[i]\n else:\n return -1", "def findelement(arr, n):\n flag = 0\n m = arr[0]\n if arr == sorted(arr):\n return arr[1]\n for i in range(n - 1):\n if m <= arr[i]:\n m = arr[i]\n flag = i\n for i in range(flag, n):\n if m > arr[i]:\n return -1\n if flag != 0:\n return m\n return -1", "def findelement(arr, n):\n (max_left, min_right, max_l, min_r) = ([], [], float('-inf'), float('inf'))\n for i in range(0, n):\n (max_l, min_r) = (max(max_l, arr[i]), min(min_r, arr[n - 1 - i]))\n max_left.append(max_l)\n min_right.append(min_r)\n for i in range(1, n - 1):\n if max_left[i] <= arr[i] <= min_right[n - 1 - i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n arr2 = {}\n ele = -1\n max = arr[0]\n min = arr[n - 1]\n for i in range(1, n):\n if arr[i] >= max:\n max = arr[i]\n arr2[max] = 1\n for i in range(n - 2, -1, -1):\n if arr[i] <= min:\n min = arr[i]\n if min in arr2.keys():\n ele = arr[i]\n return ele", "def findelement(arr, n):\n (arr1, arr2) = ([1] * n, [1] * n)\n maxi = arr[0]\n mini = arr[-1]\n for i in range(n):\n if arr[i] > maxi:\n maxi = arr[i]\n arr1[i] = maxi\n for i in range(n - 1, -1, -1):\n if arr[i] < mini:\n mini = arr[i]\n arr2[i] = mini\n for i in range(1, n - 1):\n if arr1[i] == arr2[i]:\n return arr1[i]\n else:\n return -1", "def findelement(arr, n):\n (arr1, arr2) = ([1] * n, [1] * n)\n max = arr[0]\n min = arr[-1]\n for i in range(n):\n if arr[i] > max:\n max = arr[i]\n arr1[i] = max\n for i in range(n - 1, -1, -1):\n if arr[i] < min:\n min = arr[i]\n arr2[i] = min\n for i in range(1, n - 1):\n if arr1[i] == arr2[i]:\n return arr1[i]\n else:\n return -1", "def findelement(arr, n):\n max_left = []\n min_right = []\n max_l = -1\n min_r = 100000000.0\n for i in range(0, n):\n max_l = max(max_l, arr[i])\n max_left.append(max_l)\n for i in range(len(arr) - 1, -1, -1):\n min_r = min(min_r, arr[i])\n min_right.append(min_r)\n min_right.reverse()\n for i in range(1, n - 1):\n if max_left[i] <= arr[i] and arr[i] <= min_right[i]:\n return arr[i]\n return -1", "def findelement(a, n):\n\n def check(m):\n x = 0\n for i in range(m):\n if a[i] > a[m]:\n x = x + 1\n break\n if x == 0:\n return True\n\n def check1(m):\n x = 0\n for i in range(m + 1, n):\n if a[i] < a[m]:\n x = x + 1\n break\n if x == 0:\n return True\n y = 0\n for i in range(1, n - 1):\n if check(i) == True and check1(i) == True:\n return a[i]\n y = y + 1\n break\n if y == 0:\n return -1", "def findelement(arr, n):\n (left_max, left_max_elem) = ([], float('-inf'))\n (right_min, right_min_elem) = ([], float('inf'))\n dict_ = {}\n for index in range(n):\n elem = arr[index]\n if arr[index] > left_max_elem:\n left_max_elem = elem\n if arr[-index - 1] < right_min_elem:\n right_min_elem = arr[-index - 1]\n left_max.append(left_max_elem)\n right_min.append(right_min_elem)\n for index in range(1, n - 1):\n left = left_max[index - 1] if index > 0 else float('inf')\n if left <= arr[index] <= right_min[-index - 1]:\n return arr[index]\n return -1", "def check(arr, n, ind):\n i = ind - 1\n j = ind + 1\n while i >= 0:\n if arr[i] > arr[ind]:\n return False\n i -= 1\n while j < n:\n if arr[j] < arr[ind]:\n return False\n j += 1\n return True\n\ndef findelement(arr, n):\n for i in range(1, n - 1):\n if check(arr, n, i):\n return arr[i]\n return -1", "def findelement(arr, n):\n maxi = []\n cur_max = arr[0]\n if n <= 2:\n return -1\n for i in range(n):\n if cur_max < arr[i]:\n cur_max = arr[i]\n maxi.append(cur_max)\n mini = []\n cur_min = arr[n - 1]\n for i in range(n - 1, -1, -1):\n if cur_min > arr[i]:\n cur_min = arr[i]\n mini.append(cur_min)\n mini.reverse()\n for i in range(1, n - 1):\n if arr[i] >= maxi[i] and arr[i] <= mini[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n maxi = [arr[0]]\n mini = [arr[-1]]\n for i in range(1, n):\n maxi.append(max(maxi[-1], arr[i]))\n for i in range(n - 2, -1, -1):\n mini.insert(0, min(mini[0], arr[i]))\n for i in range(1, n - 1):\n if mini[i] == maxi[i]:\n return mini[i]\n return -1", "def findelement(arr, n):\n max_arr = []\n maxi = arr[0]\n for i in range(n):\n if arr[i] > maxi:\n maxi = arr[i]\n max_arr.append(maxi)\n min_arr = []\n mini = arr[-1]\n for i in range(n - 1, -1, -1):\n if arr[i] < mini:\n mini = arr[i]\n min_arr.append(mini)\n min_arr.reverse()\n for i in range(1, n - 1):\n if min_arr[i] == max_arr[i]:\n return min_arr[i]\n else:\n return -1", "def findelement(arr, n):\n for i in range(1, n - 1):\n curr = arr[i]\n left = i - 1\n right = i + 1\n while left > -1:\n if arr[left] <= curr:\n left -= 1\n else:\n break\n while right < n:\n if arr[right] >= curr:\n right += 1\n else:\n break\n if left == -1 and right == n:\n return curr\n else:\n return -1", "def findelement(arr, n):\n max = []\n ele = arr[0]\n max.append(ele)\n for i in range(1, n):\n if arr[i] > ele:\n ele = arr[i]\n max.append(ele)\n min = []\n ele = arr[n - 1]\n min.append(ele)\n for i in range(n - 2, -1, -1):\n if arr[i] < ele:\n ele = arr[i]\n min.append(ele)\n min.reverse()\n for i in range(0, n):\n if i != 0 and i != n - 1 and (min[i] == max[i]):\n ele = min[i]\n return ele\n return -1", "def findelement(arr, n):\n maxi = arr[0]\n for i in range(1, n - 1):\n maxi = max(maxi, arr[i])\n if maxi <= arr[i] and min(arr[i + 1:]) >= arr[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n max_lv = arr[0]\n sol = -1\n for i in range(1, len(arr) - 1):\n if arr[i] >= max_lv:\n j = i + 1\n while j < n:\n if arr[i] <= arr[j]:\n j += 1\n else:\n break\n if j == n and i < n - 1:\n sol = arr[i]\n break\n else:\n max_lv = arr[i]\n return sol", "def findelement(arr, n):\n right = [0] * n\n right[n - 1] = arr[n - 1]\n left = [0] * n\n left[0] = arr[0]\n m = n - 1\n for i in range(1, n):\n left[i] = max(left[i - 1], arr[i])\n for i in range(n - 2, -1, -1):\n right[i] = min(right[i + 1], arr[i])\n for i in range(1, n - 1):\n if arr[i] >= left[i] and arr[i] <= right[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n L = [arr[0]]\n ele = arr[0]\n for i in range(1, n):\n if arr[i] > ele:\n ele = arr[i]\n L.append(ele)\n R = [arr[-1]]\n ele = arr[-1]\n for i in range(n - 2, -1, -1):\n if arr[i] < ele:\n ele = arr[i]\n R.append(ele)\n R.reverse()\n for i in range(1, n - 1):\n if arr[i] >= L[i] and arr[i] <= R[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n mini = [arr[n - 1]]\n for i in range(n - 2, 1, -1):\n if mini[-1] >= arr[i]:\n mini.append(arr[i])\n else:\n mini.append(mini[-1])\n leftmaxi = arr[0]\n for i in range(1, n - 1):\n if leftmaxi <= arr[i] <= mini[-1]:\n return arr[i]\n mini.pop()\n leftmaxi = max(leftmaxi, arr[i])\n return -1", "def leftRight(n, arr):\n left = [0] * n\n right = [0] * n\n left[0] = arr[0]\n right[n - 1] = arr[n - 1]\n for i in range(1, n):\n left[i] = max(left[i - 1], arr[i])\n for i in range(n - 1, 0, -1):\n right[i - 1] = min(right[i], arr[i - 1])\n for i in range(1, n - 1):\n (l, r) = (left[i - 1], right[i + 1])\n if arr[i] >= l and arr[i] <= r:\n return arr[i]\n return -1\n\ndef findelement(arr, n):\n return leftRight(n, arr)", "def findelement(arr, n):\n leftMax = [None] * n\n leftMax[0] = arr[0]\n for i in range(1, n):\n leftMax[i] = max(leftMax[i - 1], arr[i])\n rightMin = [None] * n\n rightMin[n - 1] = arr[n - 1]\n for i in range(n - 2, -1, -1):\n rightMin[i] = min(rightMin[i + 1], arr[i])\n for i in range(1, n - 1):\n if leftMax[i - 1] <= arr[i] and arr[i] <= rightMin[i + 1]:\n return arr[i]\n return -1", "def findelement(arr, n):\n maxarr = []\n minarr = []\n maxx = arr[0]\n minn = arr[n - 1]\n for i in range(1, n - 1):\n if arr[i] > maxx:\n maxx = arr[i]\n maxarr.append(maxx)\n for j in range(n - 1, 0, -1):\n if arr[j] < minn:\n minn = arr[j]\n minarr.insert(0, minn)\n for i in range(n - 2):\n if minarr[i] == maxarr[i]:\n return arr[i + 1]\n return -1", "def findelement(arr, n):\n i = 1\n while i < n - 1:\n found = True\n for j in range(n):\n if j < i and arr[j] > arr[i]:\n found = False\n break\n if j > i and arr[j] < arr[i]:\n found = False\n break\n if found:\n return arr[i]\n i += 1\n return -1", "def findelement(arr, n):\n big = arr[0]\n small = 9999999999999\n for i in range(1, n - 1):\n if arr[i] > big:\n big = arr[i]\n for i in range(1, n - 1):\n if arr[i] < small:\n small = arr[i]\n if small == arr[1] and small >= arr[0] and (small < arr[n - 1]):\n return small\n if big <= arr[n - 1] and big >= arr[0] and (big == arr[n - 2]):\n return big\n else:\n return -1", "def findelement(arr, n):\n n = len(arr)\n l = [0] * n\n r = [0] * n\n max_e = arr[0]\n min_e = arr[-1]\n for i in range(n):\n if max_e < arr[i]:\n max_e = arr[i]\n l[i] = max_e\n for i in range(n - 1, -1, -1):\n if min_e > arr[i]:\n min_e = arr[i]\n r[i] = min_e\n for i in range(1, n - 1):\n if arr[i] >= l[i - 1] and arr[i] <= r[i + 1]:\n return arr[i]\n return -1", "def findelement(arr, n):\n for i in range(1, n - 1):\n j = i - 1\n k = i + 1\n flag = True\n while j >= 0:\n if arr[i] < arr[j]:\n flag = False\n break\n j -= 1\n while flag and k < n:\n if arr[k] < arr[i]:\n flag = False\n break\n k += 1\n if flag:\n return arr[i]\n return -1", "def findelement(arr, n):\n l = []\n r = []\n ml = -3\n mr = 100000000.0\n for i in range(0, n):\n ml = max(ml, arr[i])\n l.append(ml)\n for i in range(len(arr) - 1, -1, -1):\n mr = min(mr, arr[i])\n r.append(mr)\n r.reverse()\n for i in range(1, n - 1):\n if l[i] <= arr[i] and arr[i] <= r[i]:\n return arr[i]\n return -1", "from collections import defaultdict\n\ndef findelement(arr, n):\n dec = defaultdict(int)\n right_min = arr[n - 1]\n for i in range(n - 2, -1, -1):\n if arr[i] <= right_min:\n dec[arr[i], i] += 1\n right_min = arr[i]\n left_max = arr[0]\n for i in range(1, n - 1):\n if arr[i] >= left_max:\n dec[arr[i], i] += 1\n left_max = arr[i]\n if dec[arr[i], i] == 2:\n return arr[i]\n return -1", "def findelement(arr, n):\n ret = False\n maxima = arr[0]\n if n < 3:\n return -1\n for i in range(1, n):\n if arr[i] >= maxima:\n if not ret and i != n - 1:\n maxima = arr[i]\n ret = True\n else:\n ret = False\n if ret:\n return maxima\n else:\n return -1", "def findelement(arr, n):\n nsl = [-1]\n st = [arr[0]]\n for i in range(1, len(arr)):\n while st and st[-1] <= arr[i]:\n st.pop()\n if len(st) == 0:\n nsl.append(1)\n else:\n nsl.append(-1)\n st.append(arr[i])\n a = arr.copy()\n a.reverse()\n nsr = [-1]\n st1 = [a[0]]\n for i in range(1, len(a)):\n while st1 and st1[-1] >= a[i]:\n st1.pop()\n if len(st1) == 0:\n nsr.append(1)\n else:\n nsr.append(-1)\n st1.append(a[i])\n nsr.reverse()\n for i in range(len(arr)):\n if nsl[i] == 1 and nsr[i] == 1:\n return arr[i]\n return -1", "def findelement(arr, n):\n left_max_arr = []\n left_max = -99999999\n for i in range(n):\n if arr[i] >= left_max:\n left_max = arr[i]\n left_max_arr.append(left_max)\n right_min = 99999999\n right_min_arr = []\n for i in range(n):\n if arr[n - i - 1] <= right_min:\n right_min = arr[n - i - 1]\n right_min_arr.append(right_min)\n for i in range(1, n - 1):\n if arr[i] >= left_max_arr[i] and arr[i] <= right_min_arr[n - i - 1]:\n return arr[i]\n return -1", "def findelement(arr, n):\n for i in range(1, n - 1):\n c = True\n m = i\n while i > 0:\n if arr[m] >= arr[i - 1]:\n i -= 1\n else:\n c = False\n break\n if c == False:\n continue\n else:\n i = m\n while i < n - 1:\n if arr[m] <= arr[i + 1]:\n i += 1\n else:\n c = False\n break\n if c == True:\n return arr[m]\n return -1", "def findelement(arr, n):\n (l, t) = ([arr[0]], [arr[n - 1]])\n for i in range(1, n):\n l.append(max(arr[i], l[-1]))\n for i in range(n - 2, -1, -1):\n t.append(min(arr[i], t[-1]))\n t = t[::-1]\n for i in range(1, n - 1):\n if arr[i] == l[i] and arr[i] == t[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n max_so_far = []\n min_so_far = [0] * n\n curmax = 0\n curmin = 100001\n if n == 0:\n return -1\n for i in range(n):\n if arr[i] > curmax:\n curmax = arr[i]\n max_so_far.append(curmax)\n for i in range(n):\n if arr[n - i - 1] < curmin:\n curmin = arr[n - i - 1]\n min_so_far[n - i - 1] = curmin\n for i in range(n):\n if arr[i] >= max_so_far[i] and arr[i] <= min_so_far[i] and (i != 0) and (i != n - 1):\n return arr[i]\n return -1", "def findelement(arr, n):\n small_flag = 0\n big_flag = 0\n for i in range(n):\n for j in range(i):\n if arr[j] > arr[i]:\n small_flag = 1\n break\n for k in range(i + 1, n):\n if arr[k] < arr[i]:\n big_flag = 1\n break\n if small_flag == 0 and big_flag == 0 and (i != n - 1) and (i != 0):\n return arr[i]\n else:\n small_flag = 0\n big_flag = 0\n return -1", "def findelement(arr, n):\n leftmax = []\n rightmin = []\n mx = arr[0]\n j = 0\n while j < n:\n if mx < arr[j]:\n mx = arr[j]\n j += 1\n leftmax.append(mx)\n j = -1\n mn = arr[-1]\n while j >= -n:\n if arr[j] < mn:\n mn = arr[j]\n j -= 1\n rightmin.append(mn)\n j = 1\n rightmin = rightmin[::-1]\n if arr[0] >= leftmax[1] and arr[0] <= rightmin[1]:\n return arr[0]\n while j < n - 1:\n if arr[j] >= leftmax[j - 1] and arr[j] <= rightmin[j + 1]:\n return arr[j]\n j += 1\n return -1", "import copy\n\ndef findelement(arr, n):\n left_max = [0] * n\n right_min = [0] * n\n left_max[0] = arr[0]\n right_min[n - 1] = arr[n - 1]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], arr[i])\n for i in range(n - 2, -1, -1):\n right_min[i] = min(right_min[i + 1], arr[i])\n for i in range(1, n - 1):\n if arr[i] >= left_max[i] and arr[i] <= right_min[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n left = [0] * n\n right = [0] * n\n left[0] = arr[0]\n mini = arr[0]\n for i in range(1, n):\n if arr[i] > mini:\n mini = arr[i]\n left[i] = mini\n right[-1] = arr[-1]\n mini = arr[-1]\n for i in range(n - 2, -1, -1):\n if arr[i] < mini:\n mini = arr[i]\n right[i] = mini\n for i in range(1, n - 1):\n if left[i] == right[i]:\n return arr[i]\n return -1", "def findelement(arr, n):\n for i in range(1, n - 1):\n l = i - 1\n r = i + 1\n flag = True\n while l >= 0:\n if arr[i] < arr[l]:\n flag = False\n break\n l -= 1\n while r <= n - 1:\n if arr[i] > arr[r]:\n flag = False\n break\n r += 1\n if flag:\n return arr[i]\n return -1", "def findelement(arr, n):\n b = [0] * n\n c = [0] * n\n b[0] = 0\n c[n - 1] = 0\n l = arr[0]\n for i in range(1, n):\n if arr[i - 1] > l:\n l = arr[i - 1]\n b[i] = l\n s = arr[n - 1]\n for i in range(n - 2, -1, -1):\n if arr[i + 1] < s:\n s = arr[i + 1]\n c[i] = s\n flag = 0\n for i in range(n):\n if arr[i] >= b[i] and arr[i] <= c[i] and (i != 0):\n return arr[i]\n flag = 1\n if flag == 0:\n return -1"], "starter_code": "def findelement( arr, n):\n", "input_output": {"fn_name": "findElement", "inputs": ["N = 4\r\nA[] = {4, 2, 5, 7}", "N = 3\r\nA[] = {11, 9, 12}"], "outputs": ["5", "-1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/unsorted-array4925/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "findelement", "task_id": "TACO_lite/519", "example": [[[4, [4, 2, 5, 7]], [3, [11, 9, 12]]], [null, null]]} +{"requirement": "A palindrome is a series of characters that read the same forwards as backwards such as \"hannah\", \"racecar\" and \"lol\".\n\nFor this Kata you need to write a function that takes a string of characters and returns the length, as an integer value, of longest alphanumeric palindrome that could be made by combining the characters in any order but using each character only once. The function should not be case sensitive.\n\nFor example if passed \"Hannah\" it should return 6 and if passed \"aabbcc_yYx_\" it should return 9 because one possible palindrome would be \"abcyxycba\".", "solutions": ["from collections import Counter\n\ndef longest_palindrome(s):\n c = Counter(filter(str.isalnum, s.lower()))\n return sum((v // 2 * 2 for v in c.values())) + any((v % 2 for v in c.values()))", "from collections import Counter\nimport re\n\ndef longest_palindrome(s):\n (n, odds, c) = (0, 0, Counter(re.sub('\\\\W+|_', '', s.lower())))\n for v in c.values():\n (x, r) = divmod(v, 2)\n n += 2 * x\n odds += r\n return n + bool(odds)", "from collections import Counter\n\ndef longest_palindrome(s):\n freq = Counter((c for c in s.lower() if c.isalnum()))\n (even, odd) = ([], [])\n for (k, v) in freq.items():\n if v % 2:\n odd.append(v - 1)\n else:\n even.append(v)\n return sum(even) + (sum(odd) + 1 if odd else 0)", "def longest_palindrome(s):\n new_s = ''.join([x for x in s.lower() if x.isalnum()])\n k = [new_s.count(x) for x in set(new_s)]\n res = 0\n for x in k:\n if x % 2 == 0:\n res += x\n else:\n res += x - 1\n return res + 1 if any((x % 2 == 1 for x in k)) else res", "from collections import Counter\n\ndef longest_palindrome(s):\n if s == '':\n return 0\n s = s.upper()\n x = Counter(s)\n len = 0\n flag = False\n for i in x:\n if i.isalnum():\n if x[i] % 2 == 0:\n len += x[i]\n else:\n flag = True\n len += x[i] - 1\n if flag == True:\n return len + 1\n return len", "from collections import Counter\nfrom string import ascii_letters, digits\n\ndef longest_palindrome(data):\n cnt = Counter([d for d in data.lower() if d in ascii_letters + digits])\n even = sum([n for n in list(cnt.values()) if n % 2 == 0])\n odd = sorted([n for n in list(cnt.values()) if n % 2 != 0])[::-1]\n if len(odd) == 0:\n ans = even\n if len(odd) == 1:\n ans = even + odd[0]\n if len(odd) > 1:\n ans = even + odd[0] + sum([n - 1 for n in odd[1:]])\n return ans", "from collections import Counter\n\ndef longest_palindrome(string):\n (possibles, has_odd) = (0, False)\n for (char, c) in Counter(string.lower()).items():\n if not char.isalnum():\n continue\n if c & 1:\n possibles += c - 1\n has_odd = True\n else:\n possibles += c\n return possibles + (1 if has_odd else 0)", "from collections import Counter\n\ndef longest_palindrome(s):\n (d, r) = (Counter([x for x in s.lower() if x.isalnum()]), 0)\n for x in d.values():\n r += x // 2 * 2 + (x % 2 >> r % 2)\n return r", "from collections import Counter\n\ndef longest_palindrome(s):\n flag = res = 0\n for v in Counter(map(str.lower, filter(str.isalnum, s))).values():\n flag |= v & 1\n res += v >> 1 << 1\n return res + flag", "import re\n\ndef longest_palindrome(s):\n s = list(re.sub('[\\\\W_]+', '', s.lower()))\n solution = 0\n j = 0\n letter_count = 0\n for letter in s:\n letter_count = s.count(letter)\n if letter_count % 2 == 0:\n solution += letter_count\n else:\n solution += letter_count - 1\n j = 1\n s = [i for i in s if i != letter]\n return solution + j"], "starter_code": "def longest_palindrome(s):\n", "input_output": {"fn_name": "longest_palindrome", "inputs": [["A"], ["Hannah"], ["xyz__a_/b0110//a_zyx"], ["$aaabbbccddd_!jJpqlQx_.///yYabababhii_"], [""]], "outputs": [[1], [6], [13], [25], [0]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Algorithms", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5a0178f66f793bc5b0001728", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "longest_palindrome", "task_id": "TACO_lite/531", "example": [[["Hannah"], ["aabbcc_yYx_"]], ["6", "9"]]} +{"requirement": "You have an initial power P, an initial score of 0 points, and a bag of tokens.\nEach token can be used at most once, has a value token[i], and has potentially two ways to use it.\n\nIf we have at least token[i] power, we may play the token face up, losing token[i] power, and gaining 1 point.\nIf we have at least 1 point, we may play the token face down, gaining token[i] power, and losing 1 point.\n\nReturn the largest number of points we can have after playing any number of tokens.\n\u00a0\n\n\n\nExample 1:\nInput: tokens = [100], P = 50\nOutput: 0\n\n\nExample 2:\nInput: tokens = [100,200], P = 150\nOutput: 1\n\n\nExample 3:\nInput: tokens = [100,200,300,400], P = 200\nOutput: 2\n\n\u00a0\nNote:\n\ntokens.length <= 1000\n0 <= tokens[i] < 10000\n0 <= P < 10000", "solutions": ["def bagoftokensscore(tokens: List[int], P: int) -> int:\n tokens = sorted(tokens)\n left = 0\n right = len(tokens) - 1\n points = 0\n if len(tokens) == 1:\n if tokens[0] <= P:\n return 1\n if len(tokens) == 0:\n return 0\n while left < right:\n if tokens[left] <= P:\n P -= tokens[left]\n left += 1\n points += 1\n elif tokens[left] > P and points > 0:\n P += tokens[right]\n points -= 1\n right -= 1\n elif points == 0 and tokens[left] > P:\n break\n if P >= tokens[left]:\n points += 1\n return points", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n tokens.sort()\n max_points = 0\n points = 0\n i = 0\n j = len(tokens) - 1\n while i <= j:\n if P >= tokens[i]:\n points += 1\n P -= tokens[i]\n max_points = max(points, max_points)\n i += 1\n elif points > 0:\n points -= 1\n P += tokens[j]\n j -= 1\n else:\n return max_points\n return max_points", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n (max_points, points) = (0, 0)\n tokens.sort()\n (i, j) = (0, len(tokens) - 1)\n while i <= j:\n if P < tokens[i]:\n if i == j or points == 0:\n break\n P += tokens[j]\n points -= 1\n j -= 1\n points += 1\n P -= tokens[i]\n i += 1\n max_points = max(max_points, points)\n return max(max_points, points)", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n tokens.sort()\n if not tokens or P < tokens[0]:\n return 0\n (l, r) = (0, len(tokens) - 1)\n points = 0\n while l <= r:\n if P >= tokens[l]:\n points += 1\n P -= tokens[l]\n l += 1\n elif r - l > 1:\n points -= 1\n P += tokens[r]\n r -= 1\n else:\n break\n return points", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n if not tokens:\n return 0\n tokens.sort()\n point = 0\n while tokens:\n if P < tokens[0]:\n if point and len(tokens) > 1:\n P += tokens.pop()\n point -= 1\n else:\n break\n else:\n P -= tokens.pop(0)\n point += 1\n return point", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n tokens.sort()\n maxPoints = 0\n points = 0\n (left, right) = (0, len(tokens) - 1)\n while left <= right and P >= 0:\n if P - tokens[left] >= 0:\n P -= tokens[left]\n points += 1\n maxPoints = max(maxPoints, points)\n left += 1\n elif points > 0:\n P += tokens[right]\n points -= 1\n right -= 1\n else:\n break\n return max(maxPoints, points)", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n tokens.sort()\n left = 0\n right = len(tokens) - 1\n ans = 0\n curr = 0\n while not left > right:\n if P >= tokens[left]:\n curr += 1\n ans = max(ans, curr)\n P -= tokens[left]\n left += 1\n elif curr > 0:\n P += tokens[right]\n curr -= 1\n right -= 1\n else:\n break\n return ans", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n n = len(tokens)\n tokens.sort()\n i = 0\n j = n - 1\n points = 0\n result = 0\n while i <= j:\n if tokens[i] <= P:\n points += 1\n result = max(result, points)\n P -= tokens[i]\n i += 1\n else:\n if points == 0:\n break\n P += tokens[j]\n points -= 1\n j -= 1\n return result", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n tokens.sort()\n (buyer, seller) = (0, len(tokens) - 1)\n max_items = current_items = 0\n while buyer <= seller:\n if P >= tokens[buyer]:\n P -= tokens[buyer]\n current_items += 1\n buyer += 1\n elif current_items == 0:\n break\n else:\n P += tokens[seller]\n current_items -= 1\n seller -= 1\n max_items = max(max_items, current_items)\n return max_items", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n if not len(tokens):\n return 0\n tokens.sort()\n res = 0\n deque = collections.deque(tokens)\n while len(deque) > 1 and (P >= deque[0] or res):\n while deque and P > deque[0]:\n res += 1\n P -= deque.popleft()\n if len(deque) > 1 and res:\n P += deque.pop()\n res -= 1\n if deque and P >= deque[0]:\n res += 1\n return res", "def bagoftokensscore(tokens: List[int], P: int) -> int:\n tokens.sort()\n\n def twoPointer(tokens, P):\n i = 0\n j = len(tokens) - 1\n score = 0\n maxScore = 0\n while i <= j:\n flag = False\n while i < len(tokens) and P >= tokens[i]:\n score += 1\n P -= tokens[i]\n i += 1\n flag = True\n if flag:\n maxScore = max(score, maxScore)\n continue\n if score > 0:\n score -= 1\n P += tokens[j]\n j -= 1\n elif P < tokens[i]:\n return score\n return maxScore\n\n def helper(tokens, P, score):\n maxVal = score\n if score > 0 and len(tokens) > 0:\n maxVal = max(helper(tokens[:len(tokens) - 1], P + tokens[len(tokens) - 1], score - 1), maxVal)\n for i in range(len(tokens) - 1, -1, -1):\n if P >= tokens[i]:\n maxVal = max(helper(tokens[:i] + tokens[i + 1:], P - tokens[i], score + 1), maxVal)\n return maxVal\n return twoPointer(tokens, P)"], "starter_code": "def bagoftokensscore(tokens: List[int], P: int) -> int:\n", "input_output": {"fn_name": "bagOfTokensScore", "inputs": [[[100], 50]], "outputs": [0]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Two Pointers", "Greedy", "Sorting"], "name": null, "source": "leetcode", "tags": ["Data structures", "Sorting", "Amortized analysis", "Greedy algorithms"], "skill_types": ["Sorting", "Amortized analysis", "Data structures", "Greedy algorithms"], "url": "https://leetcode.com/problems/bag-of-tokens/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "bagoftokensscore", "task_id": "TACO_lite/520", "example": [[[[100], 50], [[100, 200], 150], [[100, 200, 300, 400], 200]], ["0", "1", "2"]]} +{"requirement": "Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).\n\nNote: The solution set must not contain duplicate subsets.\n\nExample:\n\n\nInput: [1,2,2]\nOutput:\n[\n [2],\n [1],\n [1,2,2],\n [2,2],\n [1,2],\n []\n]", "solutions": ["def subsetswithdup(nums):\n\n def dfs(idx, path):\n subsets.append(path)\n for i in range(idx, len(nums)):\n if i > idx and nums[i] == nums[i - 1]:\n continue\n dfs(i + 1, path + [nums[i]])\n nums.sort()\n subsets = []\n dfs(0, [])\n return subsets", "def subsets(nums):\n if len(nums) == 0:\n return [[]]\n ret = []\n for (i, n) in enumerate(nums):\n if i > 0 and n == nums[i - 1]:\n continue\n for s in self.subsets(nums[i + 1:]):\n ret.append([n] + s)\n return [[]] + ret\n\ndef subsetswithdup(nums):\n nums.sort()\n return self.subsets(nums)", "def subsetswithdup(nums):\n result = []\n res = []\n self.df(nums, 0, result, res)\n return res\n\ndef df(nums, idx, result, res):\n if idx > len(nums):\n return\n if result not in res:\n res.append(result)\n for i in range(idx, len(nums)):\n self.df(nums, i + 1, sorted(result + [nums[i]]), res)", "def subsetswithdup(nums):\n\n def dfs(depth, start, cur):\n if cur not in res:\n res.append(cur)\n if depth == len(nums):\n return\n for i in range(start, len(nums)):\n dfs(depth + 1, i + 1, cur + [nums[i]])\n nums.sort()\n res = []\n dfs(0, 0, [])\n return list(res)", "def subsetswithdup(nums):\n\n def backtrack(nums, start, tmp, res):\n res.append(tmp[:])\n for i in range(start, len(nums)):\n if i > start and nums[i] == nums[i - 1]:\n continue\n else:\n tmp.append(nums[i])\n backtrack(nums, i + 1, tmp, res)\n del tmp[-1]\n res = list()\n backtrack(sorted(nums), 0, [], res)\n return res", "def subsetswithdup(nums):\n nums = sorted(nums)\n res = [[]]\n self._helpFun(nums, res, [])\n return res\n\ndef _helpFun(nums, res, curr):\n if not nums:\n if curr not in res:\n res.append(curr)\n return\n for i in range(len(nums)):\n newCurr = curr + [nums[i]]\n if newCurr not in res:\n res.append(newCurr)\n self._helpFun(nums[i + 1:], res, newCurr)"], "starter_code": "def subsetswithdup(nums: List[int]) -> List[List[int]]:\n", "input_output": {"fn_name": "subsetsWithDup", "inputs": [[[1, 2, 2]], [[0]]], "outputs": [[[], [1], [1, 2], [1, 2, 2], [2], [2, 2]], [[], [0]]]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Array", "Backtracking", "Bit Manipulation"], "name": null, "source": "leetcode", "tags": ["Bit manipulation", "Data structures", "Complete search"], "skill_types": ["Bit manipulation", "Data structures", "Complete search"], "url": "https://leetcode.com/problems/subsets-ii/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "subsetswithdup", "task_id": "TACO_lite/482", "example": [[], []]} +{"requirement": "You are given a cubic dice with 6 faces. All the individual faces have a number printed on them. The numbers are in the range of 1 to 6, like any ordinary dice. You will be provided with a face of this cube, your task is to guess the number on the opposite face of the cube.\nExample 1:\nInput:\nN = 6\nOutput:\n1\nExplanation:\nFor dice facing number 6 opposite face\nwill have the number 1.\nExample 2:\nInput:\nN = 2\nOutput:\n5\nExplanation:\nFor dice facing number 5 opposite face\nwill have the number 2.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function oppositeFaceOfDice() which takes an integer N as an input parameter and return the number on the opposite face of the dice.\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 6", "solutions": ["def oppositefaceofdice(N):\n d = {1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}\n return d[N]", "def oppositefaceofdice(N):\n return 7 - N", "def oppositefaceofdice(N):\n A = 7\n ans = A - N\n return ans", "def oppositefaceofdice(N):\n dice = {'1': '6', '2': '5', '3': '4', '4': '3', '5': '2', '6': '1'}\n return dice[str(N)]", "def oppositefaceofdice(N):\n dice = {6: 1, 5: 2, 4: 3, 3: 4, 2: 5, 1: 6}\n for i in dice:\n if i == N:\n return dice[i]", "def oppositefaceofdice(n):\n return 7 - n", "def oppositefaceofdice(N):\n if N == 1:\n return 6\n elif N == 2:\n return 5\n elif N == 3:\n return 4\n elif N == 4:\n return 3\n elif N == 5:\n return 2\n elif N == 6:\n return 1", "def oppositefaceofdice(N):\n a = 7\n ans = a - N\n return ans", "def oppositefaceofdice(N):\n switcher = {1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}\n return switcher.get(N, 'Invalid month')", "def oppositefaceofdice(N):\n arr = [1, 2, 3, 4, 5, 6]\n for i in range(N):\n if arr[i] == N:\n return arr[int(5 - i)]", "def oppositefaceofdice(N):\n return 6 - N + 1", "def oppositefaceofdice(N):\n a = 7\n res = a - N\n return res", "def oppositefaceofdice(N):\n result = {1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}\n return result.get(N)", "def oppositefaceofdice(N):\n All = 7\n if N < All:\n return All - N\n else:\n return -1", "def oppositefaceofdice(N):\n x = {i: 7 - i for i in range(1, 7)}\n return x[N]", "def oppositefaceofdice(N):\n numbers = [1, 2, 3, 4, 5, 6]\n for number in numbers:\n if number == N:\n index = -number\n return numbers[index]", "def oppositefaceofdice(N):\n q = 7\n e = q - N\n return e", "def oppositefaceofdice(N):\n opp = list(reversed(range(1, 7)))\n nor = list(range(1, 7))\n dic = {k: v for (k, v) in zip(opp, nor)}\n return dic[N]"], "starter_code": "def oppositefaceofdice(N):\n", "input_output": {"inputs": ["N = 6", "N = 2"], "outputs": ["1", "5"]}, "difficulty": "EASY", "raw_tags": ["Algorithms", "Mathematical"], "name": null, "source": "geeksforgeeks", "tags": ["Mathematics"], "skill_types": [], "url": "https://practice.geeksforgeeks.org/problems/the-dice-problem2316/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(1)", "entry_point": "oppositefaceofdice", "task_id": "TACO_lite/505", "example": [[[6], [2]], ["1", "5"]]} +{"requirement": "## Number pyramid\n\nNumber pyramid is a recursive structure where each next row is constructed by adding adjacent values of the current row. For example:\n\n```\nRow 1 [1 2 3 4]\nRow 2 [3 5 7]\nRow 3 [8 12]\nRow 4 [20]\n```\n\n___\n\n## Task\n\nGiven the first row of the number pyramid, find the value stored in its last row.\n\n___\n\n## Examples\n\n```python\nreduce_pyramid([1]) == 1\nreduce_pyramid([3, 5]) == 8\nreduce_pyramid([3, 9, 4]) == 25\n```\n\n___\n\n## Performance tests\n\n```python\nNumber of tests: 10\nList size: 10,000\n```", "solutions": ["from operator import mul\n\ndef reduce_pyramid(base):\n return sum(map(mul, base, comb_n(len(base) - 1)))\n\ndef comb_n(n):\n c = 1\n for k in range(0, n + 1):\n yield c\n c = c * (n - k) // (k + 1)", "def reduce_pyramid(base):\n (c, t, ll) = (1, 0, len(base) - 1)\n for (i, v) in enumerate(base):\n t += c * v\n c = c * (ll - i) // (i + 1)\n return t", "def reduce_pyramid(base):\n (s, c) = (0, 1)\n for (i, x) in enumerate(base, 1):\n s += c * x\n c = c * (len(base) - i) // i\n return s", "def reduce_pyramid(base):\n (tot, c, n) = (0, 1, len(base) - 1)\n for i in range(n + 1 >> 1):\n tot += c * (base[i] + base[n - i])\n c = c * (n - i) // (i + 1)\n if not n & 1:\n tot += c * base[n >> 1]\n return tot", "def _coefs(l):\n n = 1\n for i in range(l):\n yield n\n n = n * (l - i - 1) // (i + 1)\n yield n\n\ndef reduce_pyramid(base):\n coefs = _coefs(len(base))\n return sum((next(coefs) * n for n in base))", "def reduce_pyramid(Q):\n (R, U) = (0, 1)\n for (F, V) in enumerate(Q):\n (R, U) = (R + V * U, U * (len(Q) + ~F) // -~F)\n return R", "def reduce_pyramid(base):\n (n, c, r) = (len(base) - 1, 1, 0)\n for (i, x) in enumerate(base):\n r += c * x\n c = c * (n - i) // (i + 1)\n return r", "def pascal(n):\n line = [1]\n for k in range(n):\n line.append(line[k] * (n - k) // (k + 1))\n return line\n\ndef reduce_pyramid(a):\n x = len(a) - 1\n C = pascal(x)\n s = 0\n for (i, v) in enumerate(a):\n s += C[i] * v\n return s", "def reduce_pyramid(base):\n sm = 0\n nb = 1\n for (i, u) in enumerate(base, 1):\n sm += nb * u\n nb = nb * (len(base) - i) // i\n return sm", "def reduce_pyramid(b):\n (p, r) = (1, b[0])\n for i in range(1, len(b)):\n p = p * (len(b) - i) // i\n r += b[i] * p\n return r"], "starter_code": "def reduce_pyramid(base):\n", "input_output": {"fn_name": "reduce_pyramid", "inputs": [[[1]], [[3, 5]], [[3, 9, 4]], [[5, 6, 7, 8]], [[13, 1, 21, 9]], [[13, 76, 21, 42, 63]]], "outputs": [[1], [8], [25], [52], [88], [674]]}, "difficulty": "EASY", "raw_tags": ["Performance", "Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5cc2cd9628b4200020880248", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "reduce_pyramid", "task_id": "TACO_lite/534", "example": [[[[1]], [[3, 5]], [[3, 9, 4]]], ["1", "8", "25"]]} +{"requirement": "Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.\n\nExample 1:\n\nInput:nums = [1,1,1], k = 2\nOutput: 2\n\n\n\nNote:\n\nThe length of the array is in range [1, 20,000].\nThe range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].", "solutions": ["def subarraysum(nums, k):\n dic = {}\n numSum = 0\n dic[0] = 1\n ans = 0\n for i in range(len(nums)):\n numSum += nums[i]\n if numSum - k in dic:\n ans += dic[numSum - k]\n if numSum in dic:\n dic[numSum] += 1\n else:\n dic[numSum] = 1\n return ans", "def subarraysum(nums, k):\n cum_sum_dict = {}\n cum_sum_dict[0] = 1\n left_sum = 0\n count = 0\n for t in nums:\n left_sum = left_sum + t\n if left_sum - k in cum_sum_dict:\n count = count + cum_sum_dict[left_sum - k]\n if left_sum in cum_sum_dict:\n cum_sum_dict[left_sum] = cum_sum_dict[left_sum] + 1\n else:\n cum_sum_dict[left_sum] = 1\n return count", "def subarraysum(nums, k):\n l_nums = len(nums)\n c = 0\n state = dict()\n state[0] = 1\n sum = 0\n for idx in range(0, l_nums):\n sum += nums[idx]\n if sum - k in state:\n c += state[sum - k]\n state[sum] = (state[sum] if sum in state else 0) + 1\n return c", "def subarraysum(nums, k):\n (count, current, solution) = ({0: 1}, 0, 0)\n for num in nums:\n current += num\n solution += count.get(current - k, 0)\n count[current] = count.get(current, 0) + 1\n return solution", "def subarraysum(nums, k):\n sum_map = {0: 1}\n count = 0\n total_sum = 0\n total = 0\n for numb in nums:\n total += numb\n count += sum_map.get(total - k, 0)\n sum_map[total] = sum_map.get(total, 0) + 1\n return count", "def subarraysum(nums, k):\n (count, cur, res) = ({0: 1}, 0, 0)\n for v in nums:\n cur += v\n res += count.get(cur - k, 0)\n count[cur] = count.get(cur, 0) + 1\n return res", "def subarraysum(nums, k):\n count = collections.Counter()\n count[0] = 1\n ans = su = 0\n for x in nums:\n su += x\n ans += count[su - k]\n count[su] += 1\n return ans"], "starter_code": "def subarraysum(nums: List[int], k: int) -> int:\n", "input_output": {"fn_name": "subarraySum", "inputs": [[[1, 1, 1], 2]], "outputs": [2]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Prefix Sum", "Array", "Hash Table"], "name": null, "source": "leetcode", "tags": ["Data structures", "Range queries"], "skill_types": ["Data structures", "Range queries"], "url": "https://leetcode.com/problems/subarray-sum-equals-k/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "subarraysum", "task_id": "TACO_lite/502", "example": [[[[1, 1, 1], 2]], ["2"]]} +{"requirement": "Given a Binary Tree and a target key, you need to find all the ancestors of the given target key.\n 1\n / \\\n 2 3\n / \\\n 4 5\n /\n 7\nKey: 7\nAncestor: 4 2 1\nExample 1:\nInput:\n 1\n / \\\n 2 3\ntarget = 2\nOutput: 1\nExample 2:\nInput:\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 8\n /\n 7\ntarget = 7\nOutput: 4 2 1\nYour Task:\nYour task is to complete the function Ancestors() that finds all the ancestors of the key in the given binary tree.\nNote:\nThe return type is\ncpp: vector\nJava: ArrayList\npython: list\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(H).\nNote: H is the height of the tree and this space is used implicitly for the recursion stack.\nConstraints:\n1 \u2264 N \u2264 10^{3}\n1 \u2264 data of node \u2264 10^{4}", "solutions": ["def Ancestors(root, target):\n\n def ansc(root, t, ans):\n if root == None:\n return False\n if root.data == t:\n return True\n if ansc(root.left, t, ans) or ansc(root.right, t, ans):\n ans.append(root.data)\n return True\n ans = []\n ansc(root, target, ans)\n return ans", "def Ancestors(root, target):\n ans = []\n\n def solve(root, k, ans):\n if root == None:\n return False\n if root.data == k:\n return True\n if solve(root.left, k, ans) or solve(root.right, k, ans):\n ans.append(root.data)\n return True\n solve(root, target, ans)\n return ans", "def slove(root, target, ans):\n if root is None:\n return False\n if root.data == target:\n return True\n if slove(root.left, target, ans) or slove(root.right, target, ans):\n ans.append(root.data)\n return True\n return False\n\ndef Ancestors(root, target):\n ans = []\n slove(root, target, ans)\n return ans", "def ancesstor(root, path, target):\n if root == None:\n return False\n path.append(root.data)\n if root.data == target:\n return True\n if ancesstor(root.left, path, target) or ancesstor(root.right, path, target):\n return True\n path.pop(-1)\n return False\n\ndef Ancestors(root, target):\n path = []\n ancesstor(root, path, target)\n path.pop()\n path.reverse()\n return path", "def Ancestors(root, target):\n arr = []\n\n def ans(root):\n if not root:\n return False\n if root.data == target:\n return True\n ls = ans(root.left)\n if ls:\n arr.append(root.data)\n return True\n rs = ans(root.right)\n if rs:\n arr.append(root.data)\n return True\n return False\n ans(root)\n return arr", "def Ancestors(root, target):\n R = []\n\n def rec(root, target):\n if root.data == target:\n return True\n (t1, t2) = (False, False)\n if root.left:\n t1 = rec(root.left, target)\n if root.right:\n t2 = rec(root.right, target)\n if t1 or t2:\n R.append(root.data)\n return True\n return False\n rec(root, target)\n return R", "def Ancestors(root, target):\n if root == None:\n return []\n l = []\n\n def helper(root, l):\n if root != None:\n if root.data == target:\n return 1\n if helper(root.left, l) or helper(root.right, l):\n l.append(root.data)\n return 1\n if root == None:\n return 0\n helper(root, l)\n return l", "def fun(root, l, target, res):\n if root == None:\n return\n if root.data == target:\n res.extend(l)\n l.append(root.data)\n self.fun(root.left, l, target, res)\n self.fun(root.right, l, target, res)\n l.pop()\n\ndef Ancestors(root, target):\n (l, res) = ([], [])\n self.fun(root, l, target, res)\n res = res[::-1]\n return res", "def Ancestors(root, target):\n result = []\n self.recursiveFindParent(root, target, result)\n return result\n\ndef recursiveFindParent(root, target, result):\n if not root:\n return None\n if root.data == target:\n return root\n if self.recursiveFindParent(root.left, target, result) or self.recursiveFindParent(root.right, target, result):\n result.append(root.data)\n return root\n else:\n return None", "def solve(root, ans, target, out):\n if root == None:\n return\n if root.data == target:\n ans += out.copy()\n return\n out.append(root.data)\n self.solve(root.left, ans, target, out)\n self.solve(root.right, ans, target, out)\n out.pop(-1)\n\ndef Ancestors(root, target):\n ans = []\n self.solve(root, ans, target, [])\n return ans[::-1]", "def Ancestors(root, target):\n stack = []\n stack.append([root, root])\n ans = None\n while stack:\n node = stack.pop()\n if node[0].data == target:\n ans = node\n break\n if node[0].left:\n stack.append([node[0].left, node])\n if node[0].right:\n stack.append([node[0].right, node])\n some = 0\n res = []\n while some != root:\n ans = ans[1]\n some = ans[0]\n res.append(some.data)\n return res", "def Ancestors(root, target):\n\n def pathtonode(root, k, p1):\n if root == None:\n return False\n if root.data == k:\n return True\n p1.append(root.data)\n if root.left and pathtonode(root.left, k, p1) or (root.right and pathtonode(root.right, k, p1)):\n return True\n p1.pop()\n p1 = []\n pathtonode(root, target, p1)\n p1.reverse()\n return p1", "def Ancestors(root, target):\n self.val = []\n\n def t(rt, tar, va):\n if not rt:\n return 0\n if rt.data == tar:\n return 1\n if t(rt.left, tar, va) or t(rt.right, tar, va):\n va.append(rt.data)\n return 1\n return 0\n t(root, target, self.val)\n return self.val", "def find_root_to_node(current, node, result):\n if not current:\n return False\n if current:\n result.append(current.data)\n if current.data == node:\n return True\n if self.find_root_to_node(current.left, node, result) == True:\n return True\n if self.find_root_to_node(current.right, node, result) == True:\n return True\n result.pop(-1)\n\ndef Ancestors(root, target):\n res = []\n self.find_root_to_node(root, target, res)\n return res[0:len(res) - 1][::-1]", "def Ancestors(root, target):\n self.ans = []\n\n def solve(root, n):\n if root == None:\n return False\n if root.data == n:\n return True\n l = solve(root.left, n)\n r = solve(root.right, n)\n if l or r:\n self.ans.append(root.data)\n if l:\n return l\n return r\n solve(root, target)\n return self.ans", "def Ancestors(root, target):\n arr = []\n self._ancestors(root, target, arr)\n return arr\n\ndef _ancestors(node, target, arr):\n if node is None:\n return False\n if node.data == target:\n return True\n elif self._ancestors(node.left, target, arr) == True:\n arr.append(node.data)\n return True\n elif self._ancestors(node.right, target, arr) == True:\n arr.append(node.data)\n return True", "def getT(root, target, arr):\n if not root:\n return False\n if root.data == target:\n return True\n if self.getT(root.left, target, arr) or self.getT(root.right, target, arr):\n arr.append(root.data)\n return True\n return False\n\ndef Ancestors(root, target):\n arr = []\n bl = self.getT(root, target, arr)\n return arr", "def Ancestors(root, target):\n stack = [root]\n parents = {}\n parents[root.data] = None\n while len(stack) > 0:\n current = stack.pop()\n if current.data == target:\n ancestors = []\n while parents[target]:\n ancestors.append(parents[target])\n target = parents[target]\n return ancestors\n if current.left:\n parents[current.left.data] = current.data\n stack.append(current.left)\n if current.right:\n parents[current.right.data] = current.data\n stack.append(current.right)\n return None", "def Ancestors(root, target):\n sol = []\n\n def printAns(root):\n if root == None:\n return None\n if root.data == target:\n return root\n l = printAns(root.left)\n r = printAns(root.right)\n if l or r:\n sol.append(root.data)\n return l if l else r\n val = printAns(root)\n return sol", "def Ancestors(root, target):\n list = []\n\n def find_ans(root, target, list):\n if not root:\n return False\n if root.data == target:\n return True\n list.append(root.data)\n left = find_ans(root.left, target, list)\n right = find_ans(root.right, target, list)\n if left or right:\n return True\n list.pop()\n find_ans(root, target, list)\n return list[::-1]", "def Ancestors(root, target):\n res = []\n\n def helper(root):\n if not root:\n return False\n if root.data == target:\n return True\n if helper(root.left) or helper(root.right):\n res.append(root.data)\n return True\n helper(root)\n return res", "def Ancestors(root, target):\n if root == None:\n return\n v = []\n self.helper(root, target, v)\n return v\n\ndef helper(root, x, v):\n if root == None:\n return\n left = self.helper(root.left, x, v)\n right = self.helper(root.right, x, v)\n if left or right:\n v.append(root.data)\n return True\n if root.data == x:\n return True\n return False", "def __init__():\n self.ans = []\n\ndef dfs(root, target):\n if root is None:\n return False\n if root.data == target:\n return True\n l = self.dfs(root.left, target)\n r = self.dfs(root.right, target)\n if l is True or r is True:\n self.ans.append(root.data)\n return True\n return False\n\ndef Ancestors(root, target):\n self.ans = []\n if root.data == target:\n return []\n self.dfs(root, target)\n return self.ans", "import sys\nsys.setrecursionlimit(10 ** 6)\n\ndef Ancestors(root, target):\n array = []\n\n def Recursion(root, target):\n nonlocal array\n if root == None:\n return False\n if root.data == target:\n return True\n left_tree = Recursion(root.left, target)\n right_tree = Recursion(root.right, target)\n if left_tree == True or right_tree == True:\n array.append(root.data)\n return left_tree or right_tree\n Recursion(root, target)\n return array", "def has(root):\n m = {}\n q = []\n q.append(root)\n while q:\n temp = q.pop()\n if temp.left:\n m[temp.left.data] = temp.data\n q.append(temp.left)\n if temp.right:\n m[temp.right.data] = temp.data\n q.append(temp.right)\n return m\n\ndef Ancestors(root, target):\n m = has(root)\n res = []\n while True:\n if target in m:\n res.append(m[target])\n target = m[target]\n else:\n break\n return res", "def get_all_ancestors(root, target, ancestors):\n if root == None:\n return\n if root.data == target:\n return True\n left_ans = self.get_all_ancestors(root.left, target, ancestors)\n right_ans = self.get_all_ancestors(root.right, target, ancestors)\n if left_ans or right_ans:\n ancestors.append(root.data)\n return True\n else:\n return False\n\ndef Ancestors(root, target):\n ancestors = []\n self.get_all_ancestors(root, target, ancestors)\n return ancestors", "def Ancestors(root, target):\n res = []\n\n def helper(root):\n if not root:\n return 0\n if root.data == target:\n return 1\n if helper(root.left) or helper(root.right):\n res.append(root.data)\n return 1\n return 0\n helper(root)\n return res", "def add_nodes(root, target):\n if not root:\n return False\n if root.data == target:\n return True\n if self.add_nodes(root.left, target) or self.add_nodes(root.right, target):\n self.ans.append(root.data)\n return True\n return False\n\ndef Ancestors(root, target):\n self.ans = []\n self.add_nodes(root, target)\n return self.ans", "def Ancestors(root, target):\n result = []\n self.Utils(root, target, result)\n return result[::-1]\n\ndef Utils(node, target, result):\n if not node:\n return False\n if node.data == target:\n return True\n result.append(node.data)\n l = self.Utils(node.left, target, result)\n r = self.Utils(node.right, target, result)\n if not (l or r):\n result.pop()\n return l or r", "def __init__():\n self.l1 = []\n\ndef Ancestors(root, target):\n self.solve(root, target, [])\n return self.l1\n\ndef solve(root, t, l):\n if root == None:\n return\n if root.data == t:\n self.l1 = l.copy()\n return\n self.solve(root.left, t, [root.data] + l)\n self.solve(root.right, t, [root.data] + l)", "def solve(root, arr, target):\n if not root:\n return False\n elif root.data == target:\n return True\n if self.solve(root.left, arr, target):\n arr.append(root.data)\n return True\n if self.solve(root.right, arr, target):\n arr.append(root.data)\n return True\n return False\n\ndef Ancestors(root, target):\n arr = []\n self.solve(root, arr, target)\n return arr", "def recur(root, target, res):\n if root == None:\n return\n res.append(root.data)\n if root.data == target:\n return True\n lh = self.recur(root.left, target, res)\n rh = self.recur(root.right, target, res)\n if lh == None and rh == None:\n res.pop()\n return\n elif lh == True or rh == True:\n return True\n else:\n return\n\ndef Ancestors(root, target):\n res = []\n self.recur(root, target, res)\n res.reverse()\n res.pop(0)\n return res", "def Ancestors(root, target):\n ancestor = []\n\n def finder(root):\n if root == None:\n return\n if root.data == target:\n return True\n ancestor.append(root.data)\n if finder(root.left):\n return True\n if finder(root.right):\n return True\n ancestor.pop()\n finder(root)\n return reversed(ancestor)", "xx = 0\n\ndef Ancestors(root, target):\n Z = []\n self.kthAncestor(root, target, Z)\n return Z\n\ndef size(root, e):\n global xx\n if root is None:\n return\n self.size(root.left, e)\n if root.data > xx:\n xx = root.data\n self.size(root.right, e)\n\ndef kthAncestor(root, nod, Z):\n global xx\n e = []\n self.size(root, e)\n n = xx\n if root is None:\n return -1\n A = []\n C = []\n B = []\n D = []\n A.append(root)\n ancestors = [0] * (n + 1)\n ancestors[root.data] = -1\n while len(A) > 0:\n while len(A) > 0:\n node = A.pop(0)\n B.append(node.data)\n if node.left is not None:\n ancestors[node.left.data] = node.data\n D.append(node.left)\n if node.right is not None:\n ancestors[node.right.data] = node.data\n D.append(node.right)\n A.extend(D)\n D = []\n C.append(B)\n B = []\n g = nod\n while 1:\n x = ancestors[g]\n if x == -1:\n break\n g = x\n Z.append(x)", "def Ancestors(root, target):\n\n def dfs(node, subset):\n if not node:\n return None\n if node.data == target:\n return subset\n return dfs(node.left, subset + [node.data]) or dfs(node.right, subset + [node.data])\n res = dfs(root, [])\n if res:\n return res[::-1]\n return []", "def dfs(n, t, ans):\n if not n:\n return False\n l = dfs(n.left, t, ans)\n r = dfs(n.right, t, ans)\n if l or r:\n ans.append(n.data)\n return True\n if n.data == t:\n return True\n return False\n\ndef Ancestors(root, target):\n ans = []\n dfs(root, target, ans)\n return ans", "def Ancestors(root, target):\n dic = {}\n ans = {root.data: -1}\n q = deque()\n q.append(root)\n l = 1\n while q:\n for i in range(len(q)):\n node = q.popleft()\n if node.left:\n q.append(node.left)\n ans[node.left.data] = node.data\n if node.right:\n q.append(node.right)\n ans[node.right.data] = node.data\n dic[node.data] = l\n l += 1\n res = []\n d = dic[target]\n for i in range(d - 1):\n k = ans[target]\n target = k\n res.append(k)\n return res", "def __init__(val):\n self.data = val\n self.left = None\n self.right = None\n\ndef Ancestors(root, target):\n if root == None:\n return None\n if root.data == target:\n return []\n left = self.Ancestors(root.left, target)\n right = self.Ancestors(root.right, target)\n if left != None and right != None:\n return [*left, root.data, *right]\n elif left != None:\n return [*left, root.data]\n elif right != None:\n return [*right, root.data]\n else:\n return None", "def __init__():\n self.result = []\n\ndef Ancestors(root, target):\n us = {}\n q = []\n if root is None:\n return []\n q.append(root)\n while len(q) > 0:\n t = q.pop(0)\n if t.data == target:\n self.result.append(root.data)\n self.print_path(us, root, t)\n self.result = self.result[::-1]\n self.result.pop(0)\n return self.result\n if t.left is not None and t.left not in us:\n us[t.left] = t\n q.append(t.left)\n if t.right is not None and t.right not in us:\n us[t.right] = t\n q.append(t.right)\n\ndef print_path(f, root, target):\n if target not in f:\n return\n else:\n self.print_path(f, root, f[target])\n self.result.append(target.data)", "def Ancestors(root, target):\n list = []\n node = []\n self.Travel(root, target, list, node)\n return list[::-1]\n\ndef Travel(root, target, list, node):\n if root != None:\n if root.data == target:\n for i in node:\n list.append(i)\n return\n node.append(root.data)\n self.Travel(root.left, target, list, node)\n self.Travel(root.right, target, list, node)\n node.remove(root.data)", "def Ancestors(root, target):\n return self.myFunc(root, [], target, 0)[::-1]\n\ndef myFunc(root, path, key, level):\n if not root:\n return []\n if root.data == key:\n return path.copy()\n level += 1\n path.append(root.data)\n left = self.myFunc(root.left, path, key, level)\n path = path[:level]\n right = self.myFunc(root.right, path, key, level)\n return left + right", "def Ancestors(root, target):\n ans = list()\n\n def ancest(root, target, res):\n if root == None:\n return False\n if root.data == target:\n return True\n if ancest(root.left, target, res) or ancest(root.right, target, res):\n res.append(root.data)\n return True\n return False\n ancest(root, target, ans)\n return ans", "def set_parent(root, parent):\n stack = []\n stack.append(root)\n while stack:\n cur = stack.pop()\n if cur.right:\n parent[cur.right.data] = cur.data\n stack.append(cur.right)\n if cur.left:\n parent[cur.left.data] = cur.data\n stack.append(cur.left)\n\ndef rootToLeaf(parent, target):\n ans = []\n k = target\n while k != 0:\n k = parent[k]\n if k != 0:\n ans.append(k)\n return ans\n\ndef Ancestors(root, target):\n parent = {}\n parent[root.data] = 0\n self.set_parent(root, parent)\n return self.rootToLeaf(parent, target)", "def Ancestors(root, target):\n\n def parent(root):\n if root == None:\n return None\n if root.left:\n dict1[root.left.data] = root.data\n if root.right:\n dict1[root.right.data] = root.data\n if root.left:\n parent(root.left)\n if root.right:\n parent(root.right)\n dict1 = {root.data: -1}\n parent(root)\n node = target\n list1 = []\n while node != -1:\n node = dict1[node]\n if node == -1:\n break\n list1.append(node)\n return list1", "def Ancestors(node, target):\n arr = []\n\n def solve(root, n, arr):\n if root is None:\n return False\n if root.data == n:\n return True\n left = solve(root.left, n, arr)\n right = solve(root.right, n, arr)\n if left or right:\n arr.append(root.data)\n return True\n solve(node, target, arr)\n return arr", "def Ancestors(root, target):\n l = []\n if self.findAncestors(root, target, l):\n return l\n else:\n return l\n\ndef findAncestors(root, target, l):\n if root == None:\n return False\n if root.data == target:\n return True\n if self.findAncestors(root.left, target, l) or self.findAncestors(root.right, target, l):\n l.append(root.data)\n return True", "def Ancestors(root, target):\n res = []\n self.fun(root, res)\n return res[::-1]\n\ndef fun(root, res):\n if root is None:\n return\n if root.data == target:\n return 1\n res.append(root.data)\n a1 = self.fun(root.left, res)\n if a1 == 1:\n return 1\n a2 = self.fun(root.right, res)\n if a2 == 1:\n return 1\n res.pop()", "def Ancestors(root, target):\n\n def ancestors(root, target):\n nonlocal cur, res\n if root is None or len(res) != 0:\n return\n if root.data == target:\n res = cur[:]\n return\n cur.append(root.data)\n ancestors(root.left, target)\n ancestors(root.right, target)\n cur.pop()\n return\n (cur, res) = ([], [])\n ancestors(root, target)\n res.reverse()\n return res", "def Ancestors(root, target):\n if root is None:\n return []\n arr = []\n self.AncestorsUtil(root, target, arr)\n return arr\n\ndef AncestorsUtil(root, target, nodes):\n if root == None:\n return False\n if root.data == target:\n return True\n if self.AncestorsUtil(root.left, target, nodes) or self.AncestorsUtil(root.right, target, nodes):\n nodes.append(root.data)\n return True\n return False", "def Ancestors(root, target):\n d = {}\n l = []\n if not root:\n return\n self.helper(root, d)\n m = d[target]\n while m in d:\n l.append(m)\n m1 = d[m]\n m = m1\n l.append(m)\n return l\n\ndef helper(root, d):\n if not root:\n return\n if root.left:\n d[root.left.data] = root.data\n self.helper(root.left, d)\n if root.right:\n d[root.right.data] = root.data\n self.helper(root.right, d)", "def find_ancestors(root, target, res):\n if root is None:\n return False\n if self.find_ancestors(root.left, target, res) or self.find_ancestors(root.right, target, res):\n res.append(root.data)\n return True\n if root.data == target:\n return True\n return False\n\ndef Ancestors(root, target):\n res = []\n self.find_ancestors(root, target, res)\n return res", "def __init__():\n self.arr = []\n\ndef dfs(root, target):\n if root == None:\n return False\n if root.data == target:\n return True\n if self.dfs(root.left, target) or self.dfs(root.right, target):\n self.arr.append(root.data)\n return True\n return False\n\ndef Ancestors(root, target):\n self.dfs(root, target)\n return self.arr", "def __init__():\n self.ancestors_list = []\n\ndef Ancestors(root, target):\n self.find_ancestors(root, target)\n return self.ancestors_list\n\ndef find_ancestors(node, target):\n if node == None:\n return False\n if node.data == target:\n return True\n r_target = self.find_ancestors(node.right, target)\n l_target = self.find_ancestors(node.left, target)\n if r_target or l_target:\n self.ancestors_list.append(node.data)\n return True", "def Ancestors(root, target):\n ans = []\n\n def recurs(root, target):\n if root.data == target:\n return True\n else:\n p = False\n q = False\n if root.left:\n p = recurs(root.left, target)\n if root.right:\n q = recurs(root.right, target)\n if p or q:\n ans.append(root.data)\n return True\n return False\n recurs(root, target)\n return ans", "def Ancestors(root, target):\n\n def helper(root, res, target):\n if not root:\n return\n if root.data == target:\n return res\n x = helper(root.left, res + [root.data], target)\n if x:\n return x\n y = helper(root.right, res + [root.data], target)\n if y:\n return y\n res = helper(root, [], target)\n return res[::-1]", "def getPath(root, data, result):\n if root:\n result.append(root.data)\n if self.getPath(root.left, data, result):\n return result\n if self.getPath(root.right, data, result):\n return result\n if root.data == data:\n return result\n result.pop()\n\ndef Ancestors(root, target):\n result = []\n self.getPath(root, target, result)\n mainResult = []\n for i in range(len(result) - 2, -1, -1):\n mainResult.append(result[i])\n return mainResult", "def Ancestors(root, target):\n (arr1, arr2) = ([], [])\n flag = [0, 0]\n arr1 = self.first(root, target, arr1, flag)\n arr = arr1[0:len(arr1) - 1]\n return arr[::-1]\n\ndef first(root, n1, arr1, flag):\n if root is None:\n return 0\n if flag[0] == 0:\n if root.data == n1:\n flag[0] = 1\n arr1.append(root.data)\n self.first(root.left, n1, arr1, flag)\n self.first(root.right, n1, arr1, flag)\n if flag[0] == 0:\n arr1.pop()\n return arr1", "def Ancestors(root, target):\n x = []\n\n def helper(root, target):\n if not root:\n return False\n if root.data == target:\n return True\n l = helper(root.left, target)\n r = helper(root.right, target)\n if l == True or r == True:\n x.append(root.data)\n return True\n return False\n helper(root, target)\n return x", "def Ancestors(root, target):\n self.lst = []\n self.f = 0\n\n def dfs(root, target):\n if not root:\n return\n if root.data == target:\n self.f = 1\n return\n if self.f == 0:\n self.lst.append(root.data)\n dfs(root.left, target)\n dfs(root.right, target)\n if self.f != 1:\n self.lst.pop()\n dfs(root, target)\n return self.lst[::-1]", "def Ancestors(root, target):\n\n def bfs(root, d):\n q = [root]\n while q:\n node = q.pop(0)\n if node.left:\n d[node.left.data] = node.data\n q.append(node.left)\n if node.right:\n d[node.right.data] = node.data\n q.append(node.right)\n d = {}\n d[root.data] = -1\n bfs(root, d)\n ans = []\n while target != -1:\n target = d[target]\n ans.append(target)\n return ans[:-1]", "def Ancestors(root, target):\n\n def dfs(root, key, arr):\n if not root:\n return False\n if root.data == key:\n return True\n if dfs(root.left, key, arr) or dfs(root.right, key, arr):\n arr.append(root.data)\n return arr\n return dfs(root, target, [])", "def Ancestors(root, target):\n ancs = []\n\n def rec(root):\n if not root:\n return False\n if root.data == target:\n return True\n if rec(root.left) or rec(root.right):\n ancs.append(root.data)\n return True\n return False\n rec(root)\n return ancs", "def helper_Ancestors(root, target, path):\n if root is None:\n return False\n if root.data == target:\n return True\n lt = self.helper_Ancestors(root.left, target, path)\n rt = self.helper_Ancestors(root.right, target, path)\n if lt or rt:\n path.append(root.data)\n return True\n else:\n return False\n\ndef Ancestors(root, target):\n path = []\n ans = self.helper_Ancestors(root, target, path)\n return path", "def Ancestors(root, target):\n (x, f) = ([], 0)\n\n def ino(r, k):\n nonlocal f\n if not r:\n return\n if r.data == k:\n f = 1\n return\n if f == 0:\n x.append(r.data)\n ino(r.left, k)\n ino(r.right, k)\n if f != 1:\n x.pop()\n ino(root, target)\n return x[::-1]", "def Ancestors(root, target):\n ans = []\n\n def solve(root, target):\n if root is None:\n return None\n if root.data == target:\n return True\n left = solve(root.left, target)\n if left:\n ans.append(root.data)\n return True\n right = solve(root.right, target)\n if right:\n ans.append(root.data)\n return True\n solve(root, target)\n return ans", "def Ancestors(root, target):\n l = []\n path = []\n self.preorder(root, l, path)\n l = l[0]\n l.reverse()\n return l[1:]\n\ndef preorder(root, l, path):\n if root:\n path.append(root.data)\n if root.data == target:\n l.append(path.copy())\n self.preorder(root.left, l, path)\n self.preorder(root.right, l, path)\n path.pop()", "def Ancestors(root, target):\n arr = []\n\n def func(root, tgt):\n if not root:\n return False\n if root.data == tgt:\n return True\n if func(root.left, tgt) or func(root.right, tgt):\n arr.append(root.data)\n return True\n return False\n func(root, target)\n return arr"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["1\r\n / \\\r\n 2 3\r\ntarget = 2", "1\r\n / \\\r\n 2 3\r\n / \\ / \\\r\n 4 5 6 8\r\n /\r\n 7\r\ntarget = 7"], "outputs": ["1", "4 2 1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/ancestors-in-binary-tree/1", "Expected Auxiliary Space": "O(H).", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N).", "entry_point": "__init__", "task_id": "TACO_lite/500", "example": [[], []]} +{"requirement": "Given an array of N integers Arr_{1}, Arr_{2}, \u2026.Arr_{N}, count number of subarrays of Arr which are strictly increasing. \nA subarray Arr_{[i, j]} is the array where 1 <= i < j <= N is a sequence of integers of Arr_{i}, Arr_{i+1}, \u2026.Arr_{j}. A subarray Arr_{[i, j]} is strictly increasing if Arr_{i} < Arr_{i+1} < Arr_{i+2} < \u2026\u2026. < Arr_{j}.\nExample 1:\nInput: \nN = 6\nArr[] = {1, 3, 3, 2, 3, 5}\nOutput: 4\nExplanation:\n(1,3), (2, 3), (3, 5) and (2, 3, 5)\nare the only increasing subarrays.\nExample 2:\nInput: \nN = 2\nArr[] = {1 5} \nOutput: 1\nExplanation:(1, 5) is the only increasing\nsubarray.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function countIncreasing() which takes the array of integers arr[] and n as parameters and returns a integer denoting the answer.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 10^{7}\n1 <= Arr_{i} <= 10^{7}", "solutions": ["def countincreasing(arr, n):\n (l, r) = (0, 1)\n count = 0\n while r < len(arr):\n if arr[r] > arr[r - 1]:\n count += r - l\n else:\n l = r\n r += 1\n return count", "def countIncSub(arr, n):\n (fi, li) = (0, 0)\n state = 0\n result = 0\n for i in range(n - 1):\n if arr[i] < arr[i + 1]:\n state = 1\n li += 1\n else:\n if state:\n nTotal = li - fi + 1\n result += nTotal * (nTotal + 1) // 2 - nTotal\n state = 0\n fi = i\n li = i\n nTotal = li - fi + 1\n result += nTotal * (nTotal + 1) // 2 - nTotal\n return result\n\ndef countincreasing(arr, n):\n return countIncSub(arr, n)", "def countincreasing(arr, n):\n left = 0\n ans = 0\n for (idx, n) in enumerate(arr):\n if idx > 0 and n <= arr[idx - 1]:\n left = idx\n ans += idx - left\n return ans", "def countincreasing(arr, n):\n last = arr[0]\n j = 0\n count = 0\n for i in range(1, n):\n if arr[i] > last:\n count += i - j\n else:\n j = i\n last = arr[i]\n return count", "def countincreasing(arr, n):\n c = 1\n ans = 0\n for i in range(n - 1):\n if arr[i + 1] > arr[i]:\n c += 1\n else:\n ans += int((c - 1) * c / 2)\n c = 1\n if c > 1:\n ans += int((c - 1) * c / 2)\n return ans", "def countincreasing(arr, n):\n dp = [0] * len(arr)\n for i in range(1, len(arr)):\n if arr[i] > arr[i - 1]:\n dp[i] = 1 + dp[i - 1]\n return sum(dp)", "import math\n\ndef countincreasing(arr, n):\n q = 0\n p = 1\n for i in range(n - 1):\n if arr[i + 1] > arr[i]:\n p += 1\n elif p > 1:\n q += math.factorial(p) // (2 * math.factorial(p - 2))\n p = 1\n if p > 1:\n q += math.factorial(p) // (2 * math.factorial(p - 2))\n return q", "def countincreasing(arr, n):\n cnt = 1\n out = 0\n for i in range(n - 1):\n if arr[i] < arr[i + 1]:\n cnt += 1\n else:\n out += (cnt - 1) * cnt // 2\n cnt = 1\n if cnt > 1:\n out += (cnt - 1) * cnt // 2\n return out", "def countincreasing(arr, n):\n count = 0\n countz = 0\n for i in range(n - 1):\n if arr[i] < arr[i + 1]:\n count += 1\n elif count > 0:\n countz += count * (count + 1) // 2\n count = 0\n if count > 0:\n countz += count * (count + 1) // 2\n return countz", "def countincreasing(arr, n):\n allCount = 0\n currCount = 0\n for i in range(1, n):\n if arr[i] > arr[i - 1]:\n currCount += 1\n allCount += currCount\n else:\n currCount = 0\n return allCount", "def countincreasing(a, n):\n len = 1\n cnt = 0\n for i in range(n - 1):\n if a[i + 1] > a[i]:\n len += 1\n else:\n cnt += len * (len - 1) // 2\n len = 1\n if len > 1:\n cnt += len * (len - 1) // 2\n return cnt", "def countincreasing(arr, n):\n (p, q) = (0, 0)\n ans = 0\n for i in range(1, n):\n if arr[i] > arr[i - 1]:\n q += 1\n else:\n ans += (q - p + 1) * (q - p) // 2\n (p, q) = (i, i)\n ans += (q - p + 1) * (q - p) // 2\n return ans", "def countincreasing(arr, n):\n p = 0\n c = 0\n for i in range(1, n):\n if arr[i] > arr[i - 1]:\n c += i - p\n else:\n p = i\n return c", "def countincreasing(arr, n):\n ans = 0\n count = 0\n i = 0\n while i < n - 1:\n count = 0\n while i < n - 1 and arr[i] < arr[i + 1]:\n count += 1\n i += 1\n ans += count * (count + 1) // 2\n i += 1\n return ans", "def countincreasing(a, n):\n ans = 0\n l = 1\n for i in range(1, n):\n if a[i - 1] < a[i]:\n l += 1\n else:\n ans += l * (l - 1) // 2\n l = 1\n if l > 1:\n ans += l * (l - 1) // 2\n return ans", "def countincreasing(arr, n):\n count1 = 0\n count2 = 1\n for i in range(n - 1):\n if arr[i] < arr[i + 1]:\n count2 += 1\n else:\n count1 += (count2 - 1) * count2 // 2\n count2 = 1\n count1 += (count2 - 1) * count2 // 2\n return count1", "def countincreasing(arr, n):\n if len(arr) < 2:\n return 0\n cnt = 0\n if arr[1] > arr[0] and len(arr) == 2:\n return 1\n r = 1\n l = 0\n f1 = None\n f2 = None\n for i in range(1, n - 1):\n f1 = arr[i - 1] < arr[i]\n f2 = arr[i] < arr[i + 1]\n if f1 and f2:\n r += 1\n elif not f1 and f2:\n r = i + 1\n l = i\n elif not f1 and (not f2):\n l = i + 1\n r = i + 1\n elif f1 and (not f2):\n cnt += (r - l) * (r - l + 1) // 2\n if f2:\n cnt += (r - l) * (r - l + 1) // 2\n return cnt", "def countincreasing(arr, n):\n count = 0\n i = 0\n j = 0\n while i < n - 1:\n if j == n - 1 or arr[j] >= arr[j + 1]:\n length = j - i + 1\n count += length * (length - 1) / 2\n j = i = j + 1\n else:\n j += 1\n return int(count)", "def countincreasing(arr, n):\n count = 0\n ln = 1\n for i in range(n - 1):\n if arr[i + 1] > arr[i]:\n ln += 1\n else:\n count += (ln - 1) * ln // 2\n ln = 1\n if ln > 1:\n count += ln * (ln - 1) // 2\n return count", "def countincreasing(arr, n):\n rst = 0\n numIncWid = [1] * n\n for i in range(1, n):\n if arr[i] > arr[i - 1]:\n numIncWid[i] = numIncWid[i - 1] + 1\n rst = rst + (numIncWid[i] - 1)\n return rst", "def countincreasing(a, n):\n res = 0\n count = 1\n for i in range(n - 1):\n if a[i] < a[i + 1]:\n count += 1\n elif count > 1:\n res += count * (count - 1) // 2\n count = 1\n if count > 1:\n res += count * (count - 1) // 2\n count = 1\n return res", "def countincreasing(arr, n):\n l = [0]\n for i in range(1, n):\n if arr[i] > arr[i - 1]:\n l.append(l[-1] + 1)\n else:\n l.append(0)\n return sum(l)", "def countincreasing(arr, n):\n k = 0\n temp = 1\n for i in range(0, n - 1):\n if arr[i] < arr[i + 1]:\n temp += 1\n else:\n k += temp * (temp - 1) // 2\n temp = 1\n k += temp * (temp - 1) // 2\n return k", "def countincreasing(arr, n):\n cur_len = 0\n count = 0\n cur_val = -1\n for i in range(n):\n val = arr[i]\n if val > cur_val:\n cur_len += 1\n count += cur_len - 1\n else:\n cur_len = 1\n cur_val = val\n return count", "import math\n\ndef countincreasing(arr, n):\n c = 0\n l = 1\n for i in range(n - 1):\n if arr[i] < arr[i + 1]:\n l += 1\n else:\n c += l * (l - 1) // 2\n l = 1\n if l > 1:\n c += l * (l - 1) // 2\n return c", "def countincreasing(arr, n):\n ans = 0\n small_index = 0\n for index in range(1, n):\n if arr[index] > arr[index - 1]:\n ans += index - small_index\n else:\n small_index = index\n return ans", "def countincreasing(arr, n):\n i = 1\n t = arr[0]\n ans = 0\n while i < n:\n c = 0\n while i < n and arr[i] > arr[i - 1]:\n i += 1\n c += 1\n i += 1\n ans += c * (1 + c) // 2\n return ans", "def countincreasing(arr, n):\n length = 1\n res = 0\n for i in range(0, n - 1):\n if arr[i + 1] > arr[i]:\n length += 1\n else:\n res += (length - 1) * length / 2\n length = 1\n if length > 1:\n res += (length - 1) * length / 2\n return int(res)", "def countincreasing(arr, n):\n subarrays = 0\n m = 1\n for i in range(1, n + 1):\n if i < n and arr[i] > arr[i - 1]:\n m += 1\n else:\n subarrays += m * (m - 1) // 2\n m = 1\n return subarrays"], "starter_code": "def countincreasing(arr, n):\n", "input_output": {"inputs": ["N = 6\nArr[] = {1, 3, 3, 2, 3, 5}", "N = 2\nArr[] = {1 5}"], "outputs": ["4", "1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-increasing-subarrays5301/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "countincreasing", "task_id": "TACO_lite/524", "example": [[[6, [1, 3, 3, 2, 3, 5]], [2, [1, 5]]], [null, null]]} +{"requirement": "Given an array Arr[], write a program that segregates even and odd numbers. The program should put all even numbers first in sorted order, and then odd numbers in sorted order.\nNote :- You don't have to return the array, you just have to modify it in-place.\nExample 1:\nInput: \nN = 7\nArr[] = {12, 34, 45, 9, 8, 90, 3}\nOutput: 8 12 34 90 3 9 45\nExplanation: Even numbers are 12, 34,\n8 and 90. Rest are odd numbers. After\nsorting even numbers 8 12 34 90 and \nafter sorting odd numbers 3 9 45. Then\nconcat both.\nExample 2:\nInput: \nN = 5\nArr[] = {0, 1, 2, 3, 4}\nOutput: 0 2 4 1 3\nExplanation: 0 2 4 are even and 1 3\nare odd numbers.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function segregateEvenOdd() which takes the array of integers arr[] and n as parameters and returns void. You need to modify the array itself.\nExpected Time Complexity: O(N log(N))\nExpected Auxiliary Space: O(N)\nConstraints:\n1 \u2264 N \u2264 10^{5}\n0 \u2264 Arr[i] <=10^{5}", "solutions": ["def segregateevenodd(arr, n):\n e = []\n odd = []\n for i in range(n):\n if arr[i] % 2 == 0:\n e.append(arr[i])\n else:\n odd.append(arr[i])\n e.sort()\n odd.sort()\n l3 = []\n l3 = e + odd\n for i in range(n):\n arr[i] = l3[i]", "def segregateevenodd(arr, n):\n left = 0\n right = n - 1\n while left < right:\n while arr[left] % 2 == 0 and left < right:\n left += 1\n while arr[right] % 2 == 1 and left < right:\n right -= 1\n if left < right:\n (arr[left], arr[right]) = (arr[right], arr[left])\n left += 1\n right -= 1\n even = [num for num in arr if num % 2 == 0]\n odd = [num for num in arr if num % 2 == 1]\n even.sort()\n odd.sort()\n arr[:] = even + odd", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n even.sort()\n odd.sort()\n even.extend(odd)\n arr[:] = even\n return arr", "def segregateevenodd(arr, n):\n (l1, l2) = ([], [])\n for i in arr:\n if i % 2 == 0:\n l1.append(i)\n else:\n l2.append(i)\n l1.sort()\n l2.sort()\n l1.extend(l2)\n arr[:] = l1\n return arr", "def segregateevenodd(arr, n):\n (m1, m2) = ([], [])\n for i in arr:\n if i % 2 == 0:\n m1.append(i)\n else:\n m2.append(i)\n m1.sort()\n m2.sort()\n m1.extend(m2)\n arr[:] = m1\n return arr", "def segregateevenodd(arr, n):\n arr.sort()\n b = []\n c = []\n for i in range(0, len(arr)):\n if arr[i] % 2 == 0:\n b.append(arr[i])\n else:\n c.append(arr[i])\n arr[:] = b + c\n return arr", "def segregateevenodd(arr, n):\n even_arr = []\n odd_arr = []\n for i in arr:\n if i % 2 == 0:\n even_arr.append(i)\n even_arr.sort()\n for i in arr:\n if i % 2 != 0:\n odd_arr.append(i)\n odd_arr.sort()\n arr.clear()\n arr.extend(even_arr)\n arr.extend(odd_arr)", "def segregateevenodd(arr, n):\n arr.sort()\n even = []\n odd = []\n for i in range(n):\n if arr[i] % 2 == 0:\n even.append(arr[i])\n if arr[i] % 2 == 1:\n odd.append(arr[i])\n a = even + odd\n for i in range(n):\n arr[i] = a[i]\n return arr", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n odd.sort()\n even.sort()\n even = even + odd\n for i in range(len(arr)):\n arr[i] = even[i]", "def segregateevenodd(a, n):\n even = []\n odd = []\n for i in a:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n a.clear()\n even.sort()\n odd.sort()\n a.extend(even + odd)", "def segregateevenodd(arr, n):\n li1 = []\n li2 = []\n for i in range(n):\n if arr[i] % 2 == 0:\n li1.append(arr[i])\n else:\n li2.append(arr[i])\n li1.sort()\n li2.sort()\n li1.extend(li2)\n arr[:] = li1\n return arr", "def segregateevenodd(arr, n):\n i = []\n j = []\n for num in arr:\n if num % 2 == 0:\n i.append(num)\n else:\n j.append(num)\n i.sort()\n j.sort()\n arr.clear()\n arr.extend(i)\n arr.extend(j)", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for I in arr:\n if I % 2 == 0 or I == 0:\n even.append(I)\n else:\n odd.append(I)\n a = sorted(even)\n b = sorted(odd)\n c = a + b\n arr[:] = c\n return arr", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for num in arr:\n if num % 2 == 0:\n even.append(num)\n else:\n odd.append(num)\n even.sort()\n odd.sort()\n arr.clear()\n arr.extend(even)\n arr.extend(odd)", "def segregateevenodd(arr, n):\n a = []\n b = []\n arr.sort()\n for i in arr:\n if i % 2 == 0:\n a.append(i)\n else:\n b.append(i)\n a.sort()\n b.sort()\n a.extend(b)\n arr[:] = a\n return arr", "def segregateevenodd(arr, n):\n res1 = []\n res2 = []\n res = []\n for i in arr:\n if i % 2 == 0:\n res1.append(i)\n else:\n res2.append(i)\n res1.sort()\n res2.sort()\n res1.extend(res2)\n arr[:] = res1\n return arr", "def segregateevenodd(arr, n):\n arr.sort()\n ans = [None] * n\n cnt = 0\n for i in range(n):\n if arr[i] % 2 == 0:\n ans[cnt] = arr[i]\n cnt += 1\n for i in range(n):\n if arr[i] % 2 != 0:\n ans[cnt] = arr[i]\n cnt += 1\n for i in range(n):\n arr[i] = ans[i]", "def segregateevenodd(arr, n):\n (L1, L2) = ([], [])\n for i in arr:\n if i % 2 == 0:\n L1.append(i)\n else:\n L2.append(i)\n L1.sort()\n L2.sort()\n L1.extend(L2)\n arr[:] = L1\n return arr", "def segregateevenodd(arr, n):\n l1 = sorted([i for i in arr if i % 2 == 0])\n l2 = sorted([i for i in arr if i % 2 != 0])\n arr[:] = l1 + l2\n return arr", "def segregateevenodd(arr, n):\n odd_list = []\n even_list = []\n for i in arr:\n if i % 2 == 0:\n even_list.append(i)\n else:\n odd_list.append(i)\n even_list.sort()\n odd_list.sort()\n even_list.extend(odd_list)\n arr[:] = even_list", "def segregateevenodd(arr, n):\n li1 = []\n li2 = []\n for i in arr:\n if i % 2 == 0:\n li1.append(i)\n elif i % 2 != 0:\n li2.append(i)\n li1.sort()\n li2.sort()\n s = li1 + li2\n for i in range(n):\n arr[i] = s[i]\n return arr[i]", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for i in range(n):\n if arr[i] % 2 == 0:\n even.append(arr[i])\n continue\n else:\n odd.append(arr[i])\n continue\n even.sort()\n odd.sort()\n arr.clear()\n for j in range(len(even)):\n arr.append(even[j])\n for k in range(len(odd)):\n arr.append(odd[k])", "def segregateevenodd(arr, n):\n (l, r) = (0, n - 1)\n while l <= r:\n while l < n and arr[l] % 2 == 0:\n l += 1\n while r >= 0 and arr[r] % 2 != 0:\n r -= 1\n if l < r:\n (arr[l], arr[r]) = (arr[r], arr[l])\n i = 0\n for x in sorted(arr[:r + 1]):\n arr[i] = x\n i += 1\n for x in sorted(arr[l:]):\n arr[i] = x\n i += 1", "def segregateevenodd(arr, n):\n o = []\n e = []\n for i in range(n):\n if arr[i] % 2 == 0:\n e.append(arr[i])\n else:\n o.append(arr[i])\n o.sort()\n e.sort()\n e.extend(o)\n arr[:] = e[:]", "def segregateevenodd(arr, n):\n arr.sort()\n liOdd = []\n liEven = []\n for i in range(n):\n if arr[i] % 2 == 0:\n liEven.append(arr[i])\n else:\n liOdd.append(arr[i])\n arr[:] = liEven + liOdd\n return arr", "def segregateevenodd(arr, n):\n j = 0\n for i in range(n):\n if arr[i] % 2 == 0:\n (arr[i], arr[j]) = (arr[j], arr[i])\n j += 1\n arr[:j] = sorted(arr[:j])\n arr[j:] = sorted(arr[j:])", "def segregateevenodd(arr, n):\n list1 = [i for i in arr if i % 2 == 0]\n list2 = [i for i in arr if i % 2 != 0]\n list3 = sorted(list1) + sorted(list2)\n for i in range(len(arr)):\n arr[i] = list3[i]", "def segregateevenodd(arr, n):\n arr.sort()\n ev = []\n od = []\n for i in range(n):\n if arr[i] % 2 == 0:\n ev.append(arr[i])\n else:\n od.append(arr[i])\n a = ev + od\n for i in range(n):\n arr[i] = a[i]", "def segregateevenodd(arr, n):\n even = []\n odd = []\n (p, q) = (0, 0)\n for n in arr:\n if n % 2 == 0:\n even.append(n)\n p += 1\n else:\n odd.append(n)\n q += 1\n even.sort()\n odd.sort()\n (i, j) = (0, 0)\n r = 0\n while i < p:\n arr[r] = even[i]\n r += 1\n i += 1\n while j < q:\n arr[r] = odd[j]\n j += 1\n r += 1", "def segregateevenodd(arr, n):\n li1 = []\n li2 = []\n for i in range(n):\n if arr[i] % 2 == 0:\n li1.append(arr[i])\n li1.sort()\n for i in range(n):\n if arr[i] % 2 != 0:\n li2.append(arr[i])\n li2.sort()\n for i in range(len(li1)):\n arr[i] = li1[i]\n for i in range(len(li2)):\n arr[i + len(li1)] = li2[i]", "def segregateevenodd(arr, n):\n a = sorted((i for i in arr if i % 2 == 0))\n b = sorted((i for i in arr if i % 2 != 0))\n arr[:] = a + b\n return arr", "def segregateevenodd(arr, n):\n even = 0\n odd = n - 1\n while even < odd:\n if arr[even] % 2 == 0:\n even += 1\n else:\n (arr[even], arr[odd]) = (arr[odd], arr[even])\n odd -= 1\n arr.sort(key=lambda x: [x % 2, x])\n return arr", "def segregateevenodd(arr, n):\n a = [x for x in arr if x % 2 == 0]\n a.sort()\n b = [x for x in arr if x % 2 != 0]\n b.sort()\n arr[:] = a[:] + b[:]\n return arr", "def segregateevenodd(arr, n):\n x = []\n j = 0\n y = []\n for i in range(n):\n if arr[i] % 2 == 0:\n x.append(arr[i])\n j += 1\n if arr[i] % 2 == 1:\n y.append(arr[i])\n even = sorted(x)\n odd = sorted(y)\n arr[j:] = odd\n arr[:j] = even", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n arr1 = sorted(even) + sorted(odd)\n for i in range(n):\n arr[i] = arr1[i]\n return arr", "def segregateevenodd(arr, n):\n l = []\n ll = []\n for i in arr:\n if i % 2 == 0:\n l.append(i)\n else:\n ll.append(i)\n l.sort()\n ll.sort()\n arr[:] = (l + ll)[:]", "def segregateevenodd(arr, n):\n odd_arr = []\n even_arr = []\n for i in range(n):\n if arr[i] % 2:\n odd_arr.append(arr[i])\n else:\n even_arr.append(arr[i])\n odd_arr.sort()\n even_arr.sort()\n arr[:] = even_arr + odd_arr", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n even = sorted(even)\n odd = sorted(odd)\n arr.clear()\n arr.extend(even)\n arr.extend(odd)", "def segregateevenodd(arr, n):\n even = []\n odd = []\n for (i, each) in enumerate(arr):\n if each % 2 == 0:\n even.append(each)\n else:\n odd.append(each)\n even = sorted(even)\n odd = sorted(odd)\n for (i, each) in enumerate(even):\n arr[i] = even[i]\n idx = len(even)\n for (i, each) in enumerate(odd):\n arr[idx] = odd[i]\n idx += 1\n return arr", "def segregateevenodd(arr, n):\n l = []\n t = []\n arr.sort()\n for i in range(n):\n if arr[i] % 2 == 0:\n l.append(arr[i])\n else:\n t.append(arr[i])\n w = l + t\n arr[:] = w[:]\n return arr", "def segregateevenodd(arr, n):\n l = []\n arr.sort()\n for i in arr:\n if i % 2 == 0:\n l.append(i)\n for i in arr:\n if i % 2 != 0:\n l.append(i)\n for i in range(len(l)):\n arr[i] = l[i]\n return arr", "def segregateevenodd(arr, n):\n arr.sort()\n i = 0\n for j in arr:\n if arr[i] % 2 == 1:\n arr.append(arr.pop(i))\n else:\n i += 1\n return arr", "def segregateevenodd(arr, n):\n (o, e) = ([], [])\n for elem in arr:\n e.append(elem) if elem % 2 == 0 else o.append(elem)\n e.sort()\n o.sort()\n arr[:] = e + o", "def segregateevenodd(arr, n):\n e = []\n o = []\n for i in arr:\n if i % 2 == 0:\n e.append(i)\n elif i % 2 != 0:\n o.append(i)\n x = sorted(e)\n y = sorted(o)\n z = x + y\n for i in range(n):\n arr[i] = z[i]\n return z[i]", "def segregateevenodd(arr, n):\n x = []\n y = []\n for i in arr:\n if i % 2 == 0:\n x.append(i)\n else:\n y.append(i)\n x.sort()\n y.sort()\n arr.clear()\n arr[:] = list(x) + list(y)", "def segregateevenodd(arr, n):\n e = [i for i in arr if i % 2 == 0]\n o = [i for i in arr if i % 2 != 0]\n s = sorted(e) + sorted(o)\n arr[:] = s[:]\n return arr"], "starter_code": "def segregateevenodd(arr, n):\n", "input_output": {"inputs": ["N = 7\r\nArr[] = {12, 34, 45, 9, 8, 90, 3}", "N = 5\r\nArr[] = {0, 1, 2, 3, 4}"], "outputs": ["8 12 34 90 3 9 45", "0 2 4 1 3"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays"], "name": null, "source": "geeksforgeeks", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/segregate-even-and-odd-numbers4629/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N log(N))", "entry_point": "segregateevenodd", "task_id": "TACO_lite/525", "example": [[], []]} +{"requirement": "Given string str of length N. The task is to find the minimum characters to be added at the front to make string palindrome.\nNote: A palindrome is a word which reads the same backward as forward. Example: \"madam\".\nExample 1:\nInput:\nS = \"abc\"\nOutput: 2\nExplanation: \nAdd 'b' and 'c' at front of above string to make it\npalindrome : \"cbabc\"\nExample 2:\nInput:\nS = \"aacecaaa\"\nOutput: 1\nExplanation: Add 'a' at front of above string\nto make it palindrome : \"aaacecaaa\"\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function minChar() which takes a string S and returns an integer as output.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1 <= S.length <= 10^{6}", "solutions": ["def minchar(str):\n ha = [0] * len(s)\n (i, j) = (0, len(s) - 1)\n ans = 0\n while i < j:\n if s[i] == s[j]:\n if i == 0:\n ha[i] = 1\n else:\n ha[i] = 1 + ha[i - 1]\n i += 1\n j -= 1\n elif i == 0:\n ans = len(s) - j\n j -= 1\n else:\n i = ha[i - 1] // 2\n ans = len(s) - (j + 1) - i\n return ans", "def minchar(string):\n my_str = string + '@' + string[::-1]\n first = 0\n second = 2\n my_str = ' ' + my_str\n lps_arr = [0] * len(my_str)\n while second < len(my_str):\n if my_str[first + 1] == my_str[second]:\n lps_arr[second] = first + 1\n first += 1\n second += 1\n elif first != 0:\n first = lps_arr[first]\n else:\n second += 1\n return len(string) - lps_arr[-1]", "def minchar(s):\n\n def lps(text):\n lps = [0] * len(text)\n j = 0\n for i in range(1, len(text)):\n while j > 0 and text[i] != text[j]:\n j = lps[j - 1]\n if text[i] == text[j]:\n j += 1\n lps[i] = j\n return lps\n s = s + '#' + s[::-1]\n lps = lps(s)\n return (len(s) - 1) // 2 - lps[-1]", "def minchar(str1):\n\n def compute_lps_array(string, size):\n length = 0\n lps = [0] * size\n i = 1\n while i < size:\n if string[i] == string[length]:\n length += 1\n lps[i] = length\n i += 1\n elif length != 0:\n length = lps[length - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n reverse_s = s[::-1]\n concat = s + '$' + reverse_s\n lps = compute_lps_array(concat, len(concat))\n return len(s) - lps[-1]", "def minchar(str):\n n = len(s)\n r = s[::-1]\n lps = [0] * (n + 1)\n (i, length) = (0, 0)\n while i < n:\n if r[i] == s[length]:\n length += 1\n lps[i + 1] = length\n i += 1\n elif length == 0:\n lps[i + 1] = 0\n i += 1\n else:\n length = lps[length - 1]\n return n - lps[-1]", "def minchar(string):\n\n def computeLPSArray(string):\n M = len(string)\n lps = [None] * M\n length = 0\n lps[0] = 0\n i = 1\n while i < M:\n if string[i] == string[length]:\n length += 1\n lps[i] = length\n i += 1\n elif length != 0:\n length = lps[length - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n revStr = string[::-1]\n concat = string + '$' + revStr\n lps = computeLPSArray(concat)\n return len(string) - lps[-1]", "def computeLPS(needle):\n if needle == '':\n return 0\n lps = [0] * len(needle)\n (prevLPS, i) = (0, 1)\n while i < len(needle):\n if needle[i] == needle[prevLPS]:\n lps[i] = prevLPS + 1\n prevLPS += 1\n i += 1\n elif prevLPS == 0:\n lps[i] = 0\n i += 1\n else:\n prevLPS = lps[prevLPS - 1]\n return lps\n\ndef minchar(str):\n revStr = str[::-1]\n concat = str + '$' + revStr\n lps = self.computeLPS(concat)\n return len(str) - lps[-1]", "def is_palin(s):\n start = 0\n end = len(s) - 1\n while start < end:\n if s[start] != s[end]:\n return False\n start += 1\n end -= 1\n return True\n\ndef minchar(str):\n n = len(str)\n temp = str + '$' + str[::-1]\n l = n + n + 1\n lps = [0] * l\n i = 1\n j = 0\n while i < l:\n if temp[i] == temp[j]:\n lps[i] = j + 1\n i += 1\n j += 1\n elif j == 0:\n i += 1\n else:\n j = lps[j - 1]\n ans = n - lps[l - 1]\n return ans", "def computeLPSArray(pat, n, lps):\n len = 0\n lps[0]\n i = 1\n while i < n:\n if pat[i] == pat[len]:\n len += 1\n lps[i] = len\n i += 1\n elif len != 0:\n len = lps[len - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\ndef minchar(str):\n s = str\n revStr = s[::-1]\n concat = s + '$' + revStr\n n = len(concat)\n lps = [0] * n\n lps = computeLPSArray(concat, n, lps)\n return len(s) - lps[-1]", "def compute_lps_array(s: str):\n n = len(s)\n lps = [0] * n\n (i, l) = (1, 0)\n lps[0] = 0\n while i < n:\n if s[i] == s[l]:\n l += 1\n lps[i] = l\n i += 1\n elif l != 0:\n l = lps[l - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\ndef minchar(str):\n str_concat = str + '$' + str[::-1]\n lps = self.compute_lps_array(str_concat)\n return len(str) - lps[len(str_concat) - 1]", "def conlsparr(str):\n M = len(str)\n lsp = [None] * M\n length = 0\n lsp[0] = 0\n i = 1\n while i < M:\n if str[i] == str[length]:\n length += 1\n lsp[i] = length\n i += 1\n elif length != 0:\n length = lsp[length - 1]\n else:\n lsp[i] = 0\n i += 1\n return lsp\n\ndef minchar(str):\n revstr = str[::-1]\n concat = str + '$' + revstr\n lsp1 = self.conlsparr(concat)\n return len(str) - lsp1[-1]", "def minchar(s):\n res = []\n li = list(s)\n li.append('$')\n li.extend(list(s[::-1]))\n lps = [0] * len(li)\n i = 1\n prev = 0\n while i < len(li):\n if li[i] == li[prev]:\n prev = prev + 1\n lps[i] = prev\n i = i + 1\n elif prev == 0:\n lps[i] = 0\n i = i + 1\n else:\n prev = lps[prev - 1]\n return len(s) - lps[-1]", "def genLPS(str):\n n = len(str)\n lps = [0] * n\n j = 1\n length = 0\n while j < n:\n if str[j] == str[length]:\n length += 1\n lps[j] = length\n j += 1\n elif length != 0:\n length = lps[length - 1]\n else:\n lps[j] = 0\n j += 1\n return lps[-1]\n\ndef minchar(str):\n n = len(str)\n str = str + '%' + str[::-1]\n return n - self.genLPS(str)", "def getlps(s):\n n = len(s)\n lps = [0] * n\n i = 1\n l = 0\n while i < n:\n if s[i] == s[l]:\n l += 1\n lps[i] = l\n i += 1\n else:\n if l == 0:\n lps[i] = 0\n i += 1\n l = lps[l - 1]\n return lps\n\ndef minchar(str):\n str2 = str[::-1]\n n = len(str)\n S = str + '$' + str2\n c = self.getlps(S)\n return n - c[-1]", "def minchar(s):\n newstr = s + '$' + s[::-1]\n lps = [0] * len(newstr)\n (prevlps, i) = (0, 1)\n while i < len(newstr):\n if newstr[prevlps] == newstr[i]:\n prevlps += 1\n lps[i] = prevlps\n i += 1\n elif prevlps == 0:\n lps[i] = 0\n i += 1\n else:\n prevlps = lps[prevlps - 1]\n return len(s) - lps[-1]", "def minchar(str):\n newStr = str + '$' + str[::-1]\n lps = [0] * len(newStr)\n self.findlps(lps, newStr)\n return len(str) - lps[-1]\n\ndef findlps(lps, a):\n i = 0\n j = 1\n while i <= j and j < len(a):\n if a[i] == a[j]:\n i += 1\n lps[j] = i\n j += 1\n elif i != 0:\n i = lps[i - 1]\n else:\n j += 1", "def minchar(str1):\n rev = str1[::-1]\n concat = str1 + '$' + rev\n lps = self.addMinChar(concat)\n return len(str1) - lps[-1]\n\ndef addMinChar(str1):\n m = len(str1)\n lps = [None] * m\n length = 0\n lps[0] = 0\n i = 1\n while i < m:\n if str1[i] == str1[length]:\n length += 1\n lps[i] = length\n i += 1\n elif length != 0:\n length = lps[length - 1]\n else:\n lps[i] = 0\n i += 1\n return lps", "def minchar(str):\n x = list(str)\n x.append('$')\n x.extend(list(str[::-1]))\n lps = [0] * len(x)\n i = 1\n prev = 0\n while i < len(x):\n if x[prev] == x[i]:\n prev = prev + 1\n lps[i] = prev\n i = i + 1\n elif prev == 0:\n lps[i] = 0\n i = i + 1\n else:\n prev = lps[prev - 1]\n return len(str) - lps[-1]\n return 0", "def computeLPSArray(s):\n lps = [None] * len(s)\n lps[0] = 0\n length = 0\n i = 1\n M = len(s)\n while i < M:\n if s[i] == s[length]:\n length += 1\n lps[i] = length\n i += 1\n elif length != 0:\n length = lps[length - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\ndef minchar(str):\n s = str + '$' + str[::-1]\n lps = self.computeLPSArray(s)\n return len(str) - lps[-1]", "def minchar(str):\n n = len(str)\n req = 0\n (l, r) = (0, n - 1)\n if str[l] == str[r]:\n while l < r and str[r] == str[n - 1]:\n if str[l] == str[r]:\n l += 1\n else:\n req += 1\n r -= 1\n while l < r:\n if str[l] == str[r]:\n l += 1\n else:\n req = n - r\n l = 0\n r -= 1\n return req", "def minchar(str):\n z = 0\n i = 1\n lps = [0]\n v = str[::-1]\n str = str + '$' + v\n while i < len(str):\n if str[i] == str[z]:\n z = z + 1\n lps.append(z)\n i = i + 1\n elif z != 0:\n z = lps[z - 1]\n else:\n lps.append(0)\n i = i + 1\n return len(v) - lps[-1]", "def minchar(str):\n l = 0\n r = len(str) - 1\n res = 0\n while l < r:\n if str[l] == str[r]:\n l += 1\n r -= 1\n else:\n res += 1\n if l != 0:\n l -= 1\n r += 1\n r -= 1\n return res", "def minchar(s):\n ans = 0\n i = 0\n j = len(s) - 1\n while i < j:\n if s[i] == s[j]:\n i += 1\n else:\n ans += 1\n if i != 0:\n j += 1\n i -= 1\n j -= 1\n return ans", "def minchar(str):\n\n def lps(s):\n i = 1\n l = 0\n lps = [0] * len(s)\n while i < len(s):\n if s[i] == s[l]:\n l = l + 1\n lps[i] = l\n i = i + 1\n elif l != 0:\n l = lps[l - 1]\n else:\n lps[i] = 0\n i = i + 1\n return lps\n length = len(str)\n str_a = str + '#' + str[::-1]\n a = lps(str_a)\n return length - a[-1]", "def minchar(s):\n r = s[::-1]\n lps = [0] * (len(s) + 1)\n (i, j) = (0, 0)\n while i < len(s):\n if r[i] == s[j]:\n j += 1\n lps[i + 1] = j\n i += 1\n elif j == 0:\n lps[i + 1] = 0\n i += 1\n else:\n j = lps[j - 1]\n return len(s) - lps[-1]", "def minchar(str):\n B = str + '$' + str[::-1]\n LPS = [0] * len(B)\n (prevLPS, i) = (0, 1)\n while i < len(B):\n if B[i] == B[prevLPS]:\n LPS[i] = prevLPS + 1\n i += 1\n prevLPS += 1\n elif prevLPS == 0:\n LPS[i] = prevLPS\n i += 1\n else:\n prevLPS = LPS[prevLPS - 1]\n return len(str) - LPS[-1]", "def minchar(str):\n new_string = str + '#' + str[::-1]\n pattern = self.get_pattern(new_string)\n return len(str) - pattern[-1] - 1\n\ndef get_pattern(substring):\n pattern = [-1] * len(substring)\n j = 0\n i = 1\n while i < len(substring):\n if substring[i] == substring[j]:\n pattern[i] = j\n i += 1\n j += 1\n elif j > 0:\n j = pattern[j - 1] + 1\n else:\n i += 1\n return pattern", "def lps(str1):\n i = 1\n j = 0\n pi = [0 for i in range(len(str1))]\n while i < len(str1):\n if str1[i] == str1[j]:\n pi[i] = j + 1\n i += 1\n j += 1\n elif j == 0:\n i += 1\n else:\n j = pi[j - 1]\n return pi[-1]\n\ndef minchar(str):\n revS = str[::-1]\n str1 = str + '$' + revS\n ans = self.lps(str1)\n return len(str) - ans", "def minchar(s):\n concat = s + s[::-1]\n res = self.lps(concat)\n return len(s) - res[-1]\n\ndef lps(a):\n i = 1\n j = 0\n lps = []\n lps.append(0)\n while i < len(a):\n if a[i] == a[j]:\n lps.append(j + 1)\n i += 1\n j += 1\n elif j == 0:\n lps.append(0)\n i += 1\n else:\n j = lps[j - 1]\n return lps", "def lps(s):\n n = len(s)\n lps = [0] * n\n lenn = 0\n i = 1\n while i < n:\n if s[lenn] == s[i]:\n lenn += 1\n lps[i] = lenn\n i += 1\n elif lenn != 0:\n lenn = lps[lenn - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\ndef minchar(s):\n n = len(s)\n if n == 1:\n return 0\n revS = s[::-1]\n concat = s + '$' + revS\n ls = Solution.lps(concat)\n return len(s) - ls[-1]", "def minchar(s):\n on = len(s)\n s = s + '$' + s[::-1]\n n = len(s)\n lps = [0] * n\n\n def preProcess():\n j = 0\n i = 1\n while i < n:\n if s[i] == s[j]:\n lps[i] = j + 1\n i += 1\n j += 1\n elif j > 0:\n j = lps[j - 1]\n else:\n i += 1\n preProcess()\n return on - lps[-1]", "def LPSSTRING(String):\n i = 1\n M = len(String)\n lps = [None] * M\n lps[0] = 0\n length = 0\n while i < M:\n if String[i] == String[length]:\n length += 1\n lps[i] = length\n i += 1\n elif length != 0:\n length = lps[length - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\ndef minchar(str):\n String = str + '$' + str[::-1]\n LPS = self.LPSSTRING(String)\n return len(str) - LPS[-1]", "def Concat(string):\n M = len(string)\n i = 1\n length = 0\n lps = [None] * M\n lps[0] = 0\n while i < M:\n if string[i] == string[length]:\n length += 1\n lps[i] = length\n i += 1\n elif length != 0:\n length = lps[length - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\ndef minchar(str):\n string = str + '$' + str[::-1]\n lps = self.Concat(string)\n return len(str) - lps[-1]", "def create_lps(A):\n M = len(A)\n lps = [None] * M\n l = 0\n lps[0] = l\n i = 1\n while i < M:\n if A[i] == A[l]:\n l += 1\n lps[i] = l\n i += 1\n elif l != 0:\n l = lps[l - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\ndef minchar(A):\n lps = self.create_lps(A + '$' + A[::-1])\n return len(A) - lps[-1]", "def lps(s):\n n = len(s)\n LPS = [0] * n\n i = 1\n j = 0\n while i < n:\n if s[i] == s[j]:\n j += 1\n LPS[i] = j\n i += 1\n elif j != 0:\n j = LPS[j - 1]\n else:\n LPS[i] = 0\n i += 1\n return LPS\n\ndef minchar(s):\n a = s + '$' + s[::-1]\n LPS = lps(a)\n ans = len(s) - LPS[-1]\n return ans", "def minchar(str):\n rev = str[::-1]\n new = str + rev\n n = len(str)\n lps = [0] * len(new)\n i = 1\n h = 0\n while i < 2 * n:\n if new[i] == new[h]:\n lps[i] += 1\n i += 1\n h += 1\n elif h > 0:\n h = lps[h - 1]\n elif h == 0:\n lps[i] = 0\n i += 1\n if h > n:\n h = math.floor(h) / 2\n ans = n - h\n return ans"], "starter_code": "def minchar(str):\n", "input_output": {"inputs": ["S = \"abc\"", "S = \"aacecaaa\""], "outputs": ["2", "1"]}, "difficulty": "MEDIUM_HARD", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/minimum-characters-to-be-added-at-front-to-make-string-palindrome/1", "Expected Auxiliary Space": "O(N)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "minchar", "task_id": "TACO_lite/434", "example": [[["abc"], ["aacecaaa"]], ["2", "1"]]} +{"requirement": "You need to create a function that will validate if given parameters are valid geographical coordinates.\n\nValid coordinates look like the following: __\"23.32353342, -32.543534534\"__.\nThe return value should be either __true__ or __false__.\n\nLatitude (which is first float) can be between 0 and 90, positive or negative.\nLongitude (which is second float) can be between 0 and 180, positive or negative.\n\nCoordinates can only contain digits, or one of the following symbols (including space after comma) __ -, . __\n\nThere should be no space between the minus \"-\" sign and the digit after it.\n\nHere are some valid coordinates:\n\n* -23, 25\n* 24.53525235, 23.45235\n* 04, -23.234235\n* 43.91343345, 143\n* 4, -3\n\nAnd some invalid ones:\n\n* 23.234, - 23.4234\n* 2342.43536, 34.324236\n* N23.43345, E32.6457\n* 99.234, 12.324\n* 6.325624, 43.34345.345\n* 0, 1,2\n* 0.342q0832, 1.2324", "solutions": ["def is_valid_coordinates(coordinates):\n try:\n (lat, lng) = [abs(float(c)) for c in coordinates.split(',') if 'e' not in c]\n except ValueError:\n return False\n return lat <= 90 and lng <= 180", "import re\n\ndef is_valid_coordinates(coordinates):\n return bool(re.match('-?(\\\\d|[1-8]\\\\d|90)\\\\.?\\\\d*, -?(\\\\d|[1-9]\\\\d|1[0-7]\\\\d|180)\\\\.?\\\\d*$', coordinates))", "def is_valid_coordinates(s):\n try:\n (a, b) = s.split(',')\n if 'e' in a or 'e' in b:\n raise Exception\n (a, b) = (float(a), float(b))\n return abs(a) <= 90 and abs(b) <= 180\n except:\n return False", "import re\nCOORD_RE = re.compile('(-?[\\\\d]+\\\\.?[\\\\d]*), ?(-?[\\\\d]+\\\\.?[\\\\d]*)$')\n\ndef is_valid_coordinates(coordinates):\n match = COORD_RE.match(coordinates)\n if not match:\n return False\n (x, y) = (match.group(1), match.group(2))\n (x, y) = (float(x), float(y))\n if not 0 <= abs(x) <= 90:\n return False\n if not 0 <= abs(y) <= 180:\n return False\n return True", "def is_valid_coordinates(coordinates):\n coords = coordinates.split(',')\n if len(coords) != 2 or 'e' in coordinates:\n return False\n for (i, coord) in enumerate(coords):\n try:\n coord = float(coord)\n if i == 0 and abs(coord) > 90 or (i == 1 and abs(coord) > 180):\n return False\n except:\n return False\n return True", "def is_valid_coordinates(coordinates):\n x = coordinates.split(', ')\n try:\n if len(x) == 2 and 90 >= float(x[0]) >= -90 and (180 >= float(x[1]) >= -180) and (not any((c.isalpha() for c in x[0]))) and (not any((c.isalpha() for c in x[1]))):\n return True\n except:\n return False\n return False", "def is_valid_coordinates(c):\n try:\n return all((-r <= float(s) <= r and 'e' not in s for (s, r) in zip(c.split(','), [90, 180, -1])))\n except ValueError:\n return False", "def is_valid_coordinates(coordinates):\n valid_chars = set('0123456789-.')\n try:\n (latitude, longitude) = (abs(float(a)) for a in coordinates.split(', ') if valid_chars.issuperset(a))\n except ValueError:\n return False\n return latitude <= 90 and longitude <= 180"], "starter_code": "def is_valid_coordinates(coordinates):\n", "input_output": {"fn_name": "is_valid_coordinates", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Regular Expressions", "Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5269452810342858ec000951", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_valid_coordinates", "task_id": "TACO_lite/408", "example": [[], []]} +{"requirement": "# Personalized greeting\n\nCreate a function that gives a personalized greeting. This function takes two parameters: `name` and `owner`.\n\nUse conditionals to return the proper message:\n\ncase | return\n--- | ---\nname equals owner | 'Hello boss'\notherwise | 'Hello guest'", "solutions": ["def greet(name, owner):\n return 'Hello boss' if name == owner else 'Hello guest'", "def greet(name, owner):\n return 'Hello ' + ['guest', 'boss'][name == owner]", "greet = lambda n, o: 'Hello ' + 'gbuoessst'[n == o::2]", "greet = lambda n, o: 'Hello {}'.format(['guest', 'boss'][n == o])", "def greet(a, b):\n return 'Hello boss' if a == b else 'Hello guest'", "def greet(name: str, owner: str) -> str:\n return f\"Hello {('boss' if name == owner else 'guest')}\"", "def greet(*s):\n return f\"Hello {['boss', 'guest'][len(set(s)) == len(s)]}\"", "def greet(name, owner):\n return 'Hello {}'.format({owner: 'boss'}.get(name, 'guest'))", "greet = lambda name, owner: 'Hello %s' % ['guest', 'boss'][name == owner]", "def greet(name, owner):\n n = 'boss' if name == owner else 'guest'\n return 'Hello {}'.format(n)", "def greet(name, owner):\n a = name\n b = owner\n if a == b:\n return 'Hello boss'\n else:\n return 'Hello guest'", "def greet(a, b):\n return 'Hello {}'.format(['guest', 'boss'][a == b])", "def greet(n, r):\n return 'Hello ' + ('boss' if n == r else 'guest')", "def greet(name, owner):\n if name == owner:\n x = 'boss'\n else:\n x = 'guest'\n return 'Hello {}'.format(x)", "greet = lambda a, b: f\"Hello {('boss' if a == b else 'guest')}\"", "import unittest\nHELLO_BOSS_MSG = 'Hello boss'\nHELLO_GUEST_MSG = 'Hello guest'\n\ndef greet(name, owner):\n return 'Hello boss' if name == owner else 'Hello guest'\n\ndef test_should_return_hello_boss_msg_when_names_equals_owner():\n (name, owner) = ('Daniel', 'Daniel')\n actual = greet(name, owner)\n self.assertEqual(actual, 'Hello boss')\n\ndef test_should_return_hello_guest_msg_when_names_equals_owner():\n (name, owner) = ('Daniel', 'Guest')\n actual = greet(name, owner)\n self.assertEqual(actual, 'Hello guest')", "def greet(name, owner):\n if name == owner:\n what = 'boss'\n else:\n what = 'guest'\n return 'Hello {}'.format(what)", "greet = lambda n, o: 'Hello {0}'.format('boss' if o == n else 'guest')", "def greet(n, m):\n if n == m:\n return 'Hello boss'\n return 'Hello guest'", "def greet(name, name2):\n if str(name) == str(name2):\n return 'Hello boss'\n else:\n return 'Hello guest'", "def greet(name, owner):\n boss = 'Hello boss'\n guest = 'Hello guest'\n if name == 'Daniel' and owner == 'Daniel':\n return boss\n else:\n return guest", "def greet(name, owner):\n f_name = name.lower()\n f_owner = owner.lower()\n if f_name == f_owner:\n return 'Hello boss'\n else:\n return 'Hello guest'", "def greet(name, owner):\n return f\"Hello {name == owner and 'boss' or 'guest'}\"", "greet = lambda name, owner: 'Hello guest' if name != owner else 'Hello boss'", "def greet(n, o):\n return f\"Hello {('boss' if n == o else 'guest')}\"", "def greet(name, owner):\n re = ['Hello boss', 'Hello guest']\n return re[0] if name == owner else re[1]", "def greet(name, owner):\n r = 'Hello guest'\n if name == owner:\n r = 'Hello boss'\n return r", "def greet(n, o):\n return 'Hello ' + ['guest', 'boss'][n == o]", "def greet(name, owner):\n x = 'boss' if name == owner else 'guest'\n return f'Hello {x}'", "def greet(name, owner):\n if name != owner:\n return 'Hello guest'\n elif owner == name:\n return 'Hello boss'", "def greet(name, owner):\n greeting = 'boss' if name == owner else 'guest'\n return 'Hello {greeting}'.format(greeting=greeting)", "def greet(name, owner):\n return 'Hello {0}'.format('guest' if name != owner else 'boss')", "def greet(name, owner):\n x = name\n y = owner\n if x == y:\n return 'Hello boss'\n else:\n return 'Hello guest'", "def greet(name, owner):\n if name == owner:\n return 'Hello boss'\n elif name != owner:\n return 'Hello guest'\n else:\n return 0", "def greet(name, owner):\n answer = 'Hello guest'\n if name == owner:\n answer = 'Hello boss'\n return answer", "def greet(name, owner):\n if name == owner:\n return 'Hello boss'\n if name != owner:\n return 'Hello guest'\n else:\n return None\ngreet('Bob', 'Bob')", "def greet(name, owner):\n a = 'boss' if name == owner else 'guest'\n return 'Hello {}'.format(a)"], "starter_code": "def greet(name, owner):\n", "input_output": {"fn_name": "greet", "inputs": [["Daniel", "Daniel"], ["Greg", "Daniel"]], "outputs": [["Hello boss"], ["Hello guest"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5772da22b89313a4d50012f7", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "greet", "task_id": "TACO_lite/431", "example": [[["Daniel", "Daniel"], ["Greg", "Daniel"]], ["Hello boss", "Hello guest"]]} +{"requirement": "Remove all characters except the numeric characters from an alphanumeric string.\nExample 1:\nInput: S = \"AA1d23cBB4\"\nOutput: 1234\nExplanation: Remove all characters\nother than numbers\nExample 2:\nInput: S = \"a1b2c3\"\nOutput: 123\nExplanation: Remove all characters\nother than numbers\nYour task:\nYour task is to complete the function string() which takes a single string as input and returns the string. You need not take any input or print anything.\n \nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= |S| <= 10^{5}", "solutions": ["def removecharacters(S):\n x = ''\n for char in S:\n if char.isdigit():\n x += char\n return x", "def removecharacters(S):\n a = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n result = ''\n for char in S:\n if char in a:\n result += char\n return result", "def removecharacters(S):\n l = [i for i in S if i.isdigit()]\n l = ''.join(l)\n return l", "def removecharacters(S):\n s = []\n for char in S:\n if char.isnumeric():\n s.append(char)\n return ''.join(s)", "def removecharacters(S):\n res = ''\n for i in S:\n if i.isdigit():\n res += i\n return res", "def removecharacters(S):\n str = ''\n for i in S:\n if i.isnumeric():\n str += i\n return str", "import re\n\ndef removecharacters(S):\n dig = ''.join(re.findall('\\\\d', S))\n return dig", "def removecharacters(S):\n s1 = ''\n for i in s:\n if i.isalpha():\n continue\n else:\n s1 += i\n return s1", "import re\n\ndef removecharacters(S):\n numeric_chars = re.sub('\\\\D', '', S)\n return numeric_chars", "def removecharacters(S):\n res = ''\n for i in S:\n ascii = ord(i)\n if ascii >= 48 and ascii <= 57:\n res = res + i\n return res", "def removecharacters(S):\n s = ''\n for i in S:\n if not i.isalpha():\n s += i\n return s", "def removecharacters(S):\n l = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\n g = ''\n for i in range(len(S)):\n if s[i] not in l:\n g += s[i]\n else:\n continue\n return g", "def removecharacters(S):\n return ''.join([c for c in S if c.isdigit()])", "def removecharacters(S):\n l = len(S)\n s = ''\n for i in range(l):\n if S[i].isdigit():\n s += S[i]\n return s", "def removecharacters(S):\n i = len(S) - 1\n arr = list(S)\n while i >= 0:\n if not S[i].isnumeric():\n arr.pop(i)\n i -= 1\n return ''.join(arr)", "def removecharacters(S):\n k = ''\n for i in range(len(S)):\n if '0' <= S[i] <= '9':\n k += S[i]\n return k", "def removecharacters(S):\n output = ''\n for i in range(len(S)):\n if S[i].isalpha():\n pass\n else:\n output += s[i]\n return output", "def removecharacters(S):\n temp_list = []\n for i in S:\n if i.isdigit():\n temp_list.append(i)\n return ''.join(temp_list)", "def removecharacters(S):\n s = ''\n for i in S:\n if i.isalpha():\n pass\n else:\n s += i\n return s", "def removecharacters(S):\n v = ''\n for i in S:\n if i in '0123456789':\n v += i\n return v", "def removecharacters(S):\n l = ''\n for i in range(len(S)):\n if S[i] in '0123456789':\n l = l + S[i]\n else:\n continue\n return l", "def removecharacters(S):\n ans = ''\n for i in range(len(S)):\n if S[i].isdigit():\n ans += S[i]\n return ans", "def removecharacters(S):\n num = '0123456789'\n res = ''\n for i in S:\n if i in num:\n res += i\n return res", "def removecharacters(s):\n i = 0\n while i < len(s) - 1:\n if ord(s[i]) >= 48 and ord(s[i]) <= 57:\n i += 1\n else:\n s = s[0:i] + s[i + 1:]\n if s[i].isdigit():\n return s\n return s[0:i]", "def removecharacters(S):\n ans = []\n for i in [*S]:\n if i.isnumeric():\n ans.append(i)\n return ''.join(ans)", "def removecharacters(s):\n new = ''\n for i in s:\n if i.isdigit() == True:\n new += i\n return new", "def removecharacters(S):\n lut = '1234567890'\n res = ''\n for L in S:\n if L in lut:\n res += L\n return res", "def removecharacters(S):\n ans = ''\n for i in range(len(S)):\n if s[i] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:\n ans += s[i]\n return ans", "def removecharacters(S):\n st = ''\n for i in s:\n if i.isnumeric():\n st = st + i\n return st", "def removecharacters(S):\n s1 = list(S)\n s2 = []\n for i in s1:\n if i.isnumeric():\n s2.append(i)\n return ''.join(s2)", "def removecharacters(S):\n ans = ''\n for i in S:\n if ord(i) >= ord('0') and ord(i) <= ord('9'):\n ans += i\n return ans", "def removecharacters(S):\n str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\n str1 = ''\n for i in S:\n if i not in str:\n str1 = str1 + i\n return str1", "def removecharacters(S):\n newstr = []\n for i in S:\n if i.isdigit() == 1:\n newstr.append(i)\n ans = ''.join(newstr)\n return ans", "def removecharacters(S):\n res = ''\n for i in S:\n if i >= '0' and i <= '9':\n res += i\n return res", "def removecharacters(S):\n num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n result = ''\n for c in S:\n if c in num:\n result += c\n return result", "def removecharacters(S):\n ans = ''\n for i in S:\n if i >= '0' and i <= '9':\n ans += i\n else:\n continue\n return ans", "def removecharacters(S):\n num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n s = ''\n for i in S:\n if i in num:\n s += i\n return s", "def removecharacters(S):\n a = ''\n n = [str(i) for i in range(10)]\n for i in s:\n if i in n:\n a += i\n return a", "import re\n\ndef removecharacters(S):\n return ''.join([x for x in re.findall('\\\\d', S)])", "def removecharacters(s):\n string = ''\n for i in s:\n if i.isdigit():\n string += i\n else:\n continue\n return string", "def removecharacters(S):\n a = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']\n res = ''\n for i in S:\n if i in a:\n res = res + i\n return res", "def removecharacters(S):\n a = ''.join(filter(str.isdigit, S))\n return a", "def removecharacters(S):\n ec = ''\n n = '0123456789'\n for i in S:\n if i in n:\n ec += i\n return ec", "def removecharacters(s):\n a = ''\n for i in s:\n if i.isdigit():\n a += i\n return a", "def removecharacters(S):\n result = ''\n for char in s:\n if char.isdigit():\n result += char\n return result", "def removecharacters(S):\n c = ''\n n = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n for i in S:\n if i in n:\n c += i\n return c"], "starter_code": "def removecharacters(S):\n", "input_output": {"inputs": ["S = \"AA1d23cBB4\"", "S = \"a1b2c3\""], "outputs": ["1234", "123"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/remove-characters-from-alphanumeric-string0648/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "removecharacters", "task_id": "TACO_lite/516", "example": [[["AA1d23cBB4"], ["a1b2c3"]], ["1234", "123"]]} +{"requirement": "You are given the string S . Compress the string when lower and upper cases are the same. In compressed string characters should be in lowercase.\nExample 1:\nInput: S = \"aaABBb\"\nOutput: \"3a3b\"\nExplanation: As 'a' appears 3 times\nconsecutively and 'b' also 3 times,\nand 'b' and 'B' considered as same. \n\u00c3\u00a2\u00e2\u0082\u00ac\u00e2\u0080\u00b9Example 2:\nInput: S = \"aaacca\"\nOutput: \"3a2c1a\"\nExplanation: As 'a' appears 3 times\nconsecutively and 'c' also 2 times,\nand then 'a' 1 time.\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function transform() which takes the string S as inputs and returns the compressed string.\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 \u2264 |S| \u2264 2 * 10^{5}\nS contains only lowercase and uppercase characters.", "solutions": ["def transform(S):\n ans = ''\n last = ''\n cnt = ''\n for i in range(len(S)):\n curr = S[i].lower()\n if curr == last:\n cnt += 1\n else:\n ans += str(cnt) + last\n last = curr\n cnt = 1\n ans += str(cnt) + last\n return ans", "def transform(S):\n s = S.lower()\n s1 = ''\n c = s[0]\n cou = 0\n i = -1\n for i in range(len(s) - 1):\n if s[i] == c:\n cou += 1\n elif s[i] != c:\n s1 += str(cou)\n s1 += c\n cou = 1\n c = s[i]\n if c == s[i + 1]:\n cou += 1\n s1 += str(cou)\n s1 += c\n else:\n s1 += str(cou)\n s1 += c\n s1 += '1' + s[i + 1]\n return s1", "def transform(s):\n s = s.lower()\n ans = ''\n c = 1\n x = s[0]\n for i in s[1:]:\n if i == x:\n c += 1\n else:\n ans = ans + str(c) + x\n c = 1\n x = i\n ans = ans + str(c) + x\n return ans", "def transform(s):\n s = s.lower()\n n = len(s)\n pre_char = s[0]\n count = 1\n final = ''\n for i in range(1, n):\n if pre_char == s[i]:\n count += 1\n else:\n final += str(count) + s[i - 1]\n count = 1\n pre_char = s[i]\n return final + str(count) + s[n - 1]", "def transform(S):\n st = []\n s = ''\n S = S.lower()\n for i in S:\n if not st:\n st.append(i)\n elif st[-1] == i:\n st.append(i)\n else:\n c = 0\n while st:\n m = st.pop()\n c += 1\n s = s + str(c) + m\n st.append(i)\n c = 0\n while st:\n c += 1\n m = st.pop()\n s = s + str(c) + m\n return s", "def transform(S):\n S = S.lower()\n k = ''\n l = []\n l.append(S[0])\n for i in S[1:]:\n if l[0] == i:\n l.append(i)\n else:\n k = k + str(len(l)) + l[0]\n l.clear()\n l.append(i)\n return k + str(len(l)) + l[0]", "def transform(S):\n S = S.lower()\n string = ''\n count = 1\n temp = S[0]\n for char in S[1:]:\n if char == temp:\n count += 1\n else:\n string += str(count) + temp\n count = 1\n temp = char\n string += str(count) + temp\n return string", "def transform(s):\n if not s:\n return ''\n s = s.lower()\n pointer = s[0]\n count = 1\n result = ''\n for val in s[1:]:\n if pointer == val:\n count += 1\n else:\n result += str(count) + pointer\n pointer = val\n count = 1\n result = result + (str(count) + pointer)\n return result", "def transform(S):\n x = S.lower()\n string = ''\n count = 0\n temp = x[0]\n for i in range(len(S)):\n if x[i] == temp:\n count = count + 1\n else:\n string = string + str(count)\n string = string + temp\n count = 1\n temp = x[i]\n return string + str(count) + temp", "def transform(S):\n s = S.lower()\n output = ''\n count = 1\n pre = s[0]\n if len(s) == 1:\n output = output + str(count) + pre\n for i in range(1, len(s)):\n if s[i] == pre:\n count += 1\n else:\n output = output + str(count) + pre\n pre = s[i]\n count = 1\n if i == len(s) - 1:\n output = output + str(count) + pre\n return output", "def transform(s):\n s = s.lower()\n result = ''\n item = s[0]\n count = 1\n for char in s[1:]:\n if char == item:\n count += 1\n else:\n result += str(count) + item\n count = 1\n item = char\n result += str(count) + item\n return result", "def transform(S):\n stk = []\n r = ''\n i = 0\n l = len(S)\n while i < l:\n t = S[i].lower()\n if not stk:\n stk.append(t)\n i += 1\n elif stk[-1] == t:\n stk.append(t)\n i += 1\n else:\n r += str(len(stk)) + stk[-1]\n stk = []\n r += str(len(stk)) + stk[-1]\n return r", "def transform(S):\n result = ''\n count = 1\n first = S[0].lower()\n for i in range(1, len(S)):\n if S[i].lower() == first:\n count += 1\n else:\n result += str(count) + first\n first = S[i].lower()\n count = 1\n if i == len(S) - 1:\n result += str(count) + first\n if len(S) == 1:\n result = str(count) + S[0].lower()\n return result", "def transform(s):\n c = 1\n t = s[0].lower()\n j = ''\n for i in range(1, len(s)):\n if t == s[i].lower():\n c += 1\n else:\n j += str(c) + t.lower()\n c = 1\n t = s[i].lower()\n j += str(c) + t.lower()\n return j", "def transform(S):\n c = 0\n s = ''\n co = 0\n for i in range(len(S) - 1):\n if S[i + 1].lower() != S[c].lower():\n s += str(co + 1)\n s += str(S[c].lower())\n co = 0\n c = i + 1\n else:\n co += 1\n s += str(co + 1)\n s += str(S[-1].lower())\n return s", "def transform(S):\n S = S.lower()\n final = ''\n rep = ''\n cnt = 0\n for s in S:\n if rep == '':\n rep = s\n cnt += 1\n elif rep == s:\n cnt += 1\n else:\n final += str(cnt) + rep\n cnt = 1\n rep = s\n final += str(cnt) + rep\n return final", "def transform(S):\n out = ''\n S = S.lower()\n i = 0\n while i < len(S):\n count = 1\n while i < len(S) - 1 and S[i] == S[i + 1]:\n count += 1\n i += 1\n i += 1\n out += str(count) + S[i - 1]\n return out", "def transform(S):\n c = 1\n aux = S[0].lower()\n s1 = ''\n for i in range(1, len(S)):\n if S[i].lower() == aux:\n c += 1\n else:\n s1 += str(c) + aux\n aux = S[i].lower()\n c = 1\n s1 += str(c) + aux\n return s1", "def transform(S):\n sta = []\n S = S.lower()\n st = ''\n k = 0\n for i in range(len(S)):\n if len(sta) == 0 or S[i] != sta[-1]:\n if k != 0:\n st += str(k) + sta.pop()\n sta.append(S[i])\n k = 1\n else:\n k += 1\n if len(S) - 1 == i:\n st += str(k) + sta.pop()\n return st", "def transform(S):\n x = S.lower()\n ans = ''\n t = x[0]\n cnt = 0\n N = len(S)\n for i in range(N):\n if x[i] == t:\n cnt += 1\n else:\n ans += str(cnt) + t\n cnt = 1\n t = x[i]\n return ans + str(cnt) + t", "def transform(S):\n S = S.lower()\n final_str = ''\n char_count = 0\n for i in range(len(S)):\n if i + 1 == len(S):\n if char_count != 0:\n char_count = char_count + 1\n final_str = final_str + str(char_count) + S[i]\n else:\n final_str = final_str + str(1) + S[i]\n elif S[i] == S[i + 1]:\n char_count = char_count + 1\n else:\n char_count = char_count + 1\n final_str = final_str + str(char_count) + S[i]\n char_count = 0\n return final_str", "def transform(S):\n S = S.lower()\n res = ''\n char = S[0]\n count = 1\n for i in range(1, len(S)):\n if S[i] == char:\n count += 1\n else:\n res = res + str(count) + char\n count = 1\n char = S[i]\n res = res + str(count) + char\n return res", "def transform(S):\n i = 0\n j = 0\n res = ''\n S = S.lower()\n while i < len(S):\n c = 0\n while j < len(S) and S[i] == S[j]:\n c += 1\n j += 1\n if c > 0:\n res += str(c) + S[i]\n i += 1\n return res", "def transform(S):\n k = 0\n i = 0\n j = 0\n li = []\n while j < len(S) and i <= j:\n if ord(S[i]) == ord(S[j]) or abs(ord(S[i]) - ord(S[j])) == 32:\n k += 1\n j += 1\n else:\n li.append(str(k) + S[i].lower())\n i = j\n k = 0\n if j == len(S):\n li.append(str(k) + S[i].lower())\n return ''.join(li)", "def transform(S):\n st = ''\n c = 0\n x = S.lower()\n t = x[0]\n for i in range(len(S)):\n if x[i] == t:\n c += 1\n else:\n st += str(c)\n st += t\n c = 1\n t = x[i]\n return st + str(c) + t", "def transform(S):\n c = 1\n l = ''\n if len(S) == 1:\n l += '1'\n l += S[0].lower()\n return l\n for i in range(len(S) - 1):\n if S[i].lower() == S[i + 1].lower():\n c += 1\n if i == len(S) - 2:\n l += str(c)\n l += S[i].lower()\n else:\n l += str(c)\n l += S[i].lower()\n c = 1\n if S[-1].lower() != S[-2].lower():\n l += '1'\n l += S[-1].lower()\n return l", "def transform(S):\n S = S.lower()\n count = 1\n i = 0\n ans = ''\n if len(S) == 1:\n return '1' + S.lower()\n while i != len(S) - 2:\n if S[i] == S[i + 1]:\n count += 1\n else:\n ans += str(count) + S[i].lower()\n count = 1\n i += 1\n i += 1\n if S[i] == S[i - 1]:\n count += 1\n ans += str(count) + S[i].lower()\n else:\n ans += str(count) + S[i - 1].lower()\n count = 1\n ans += str(count) + S[i].lower()\n return ans", "def transform(S):\n S = S.lower()\n cnt = 1\n l = []\n for i in range(len(S) - 1):\n if S[i] == S[i + 1]:\n cnt += 1\n else:\n l.append(str(cnt))\n l.append(S[i])\n cnt = 1\n l.append(str(cnt))\n l.append(S[-1])\n return ''.join(l)", "def transform(S):\n c = 1\n S = S.lower()\n l = ''\n item = S[0]\n for i in S[1:]:\n if i == item:\n c += 1\n else:\n l += str(c) + item\n c = 1\n item = i\n l += str(c) + item\n return l", "def transform(S):\n if len(S) == 1:\n return '1' + S.lower()\n ans = ''\n count = 0\n for i in range(0, len(S) - 1):\n if S[i].lower() == S[i + 1].lower():\n count = count + 1\n else:\n ans = ans + str(count + 1) + S[i].lower()\n count = 0\n if S[-1].lower() == S[-2].lower():\n ans = ans + str(count + 1) + S[-1].lower()\n else:\n ans = ans + '1' + S[-1].lower()\n return ans", "def transform(S):\n s1 = S.lower()\n count = 1\n s2 = ''\n for i in range(len(s1) - 1):\n if s1[i] == s1[i + 1]:\n count += 1\n else:\n s2 += str(count)\n s2 += str(s1[i])\n count = 1\n s2 += str(count)\n s2 += str(s1[-1])\n return s2", "def transform(S):\n S = S.lower()\n res = ''\n item = S[0]\n count = 1\n for char in S[1:]:\n if char == item:\n count += 1\n else:\n res += str(count) + item\n count = 1\n item = char\n res += str(count) + item\n return res", "def transform(S):\n S = S.lower()\n result = ''\n stack = ''\n for char in S:\n if stack and char != stack[-1]:\n result += str(len(stack)) + stack[-1]\n stack = char\n else:\n stack += char\n result += str(len(stack)) + stack[-1]\n return result", "def transform(S):\n S = S.lower()\n st = S[0]\n ans = ''\n count = 1\n for i in S[1:]:\n if i in st:\n count += 1\n else:\n ans += str(count) + st\n count = 1\n st = i\n ans += str(count) + st\n return ans", "def transform(S):\n S = S.lower()\n l = len(S)\n cnt = 1\n i = 1\n r = ''\n if l == 0:\n return ''\n if l == 1:\n return '1' + S\n while i < l:\n if S[i] == S[i - 1]:\n cnt += 1\n else:\n r = r + str(cnt) + S[i - 1]\n cnt = 1\n i += 1\n r = r + str(cnt) + S[i - 1]\n return r", "def transform(S):\n S = S.lower()\n k = ''\n st = []\n for i in range(len(S)):\n if st:\n if st[-1] == S[i]:\n pass\n else:\n k += str(len(st)) + st[-1]\n st = []\n st.append(S[i])\n k += str(len(st)) + st[-1]\n return k", "def transform(S):\n ans = ''\n S = S.lower() + ' '\n s = []\n for i in S:\n if len(s) == 0:\n s.append(i)\n elif s[-1] == i:\n s.append(i)\n else:\n ans += str(len(s))\n ans += s[0]\n s = [i]\n return ans", "def getSmall(char):\n return char.lower()\n\ndef transform(S):\n stack = []\n for char in S:\n char = self.getSmall(char)\n if not stack:\n stack.append([1, char])\n elif stack[-1][1] == char:\n stack[-1][0] += 1\n else:\n stack.append([1, char])\n res = ''\n for (freq, val) in stack:\n res += str(freq)\n res += val\n return res", "def transform(S):\n new = ''\n count = 1\n l = 1\n r = len(S)\n while l < r:\n if S[l].lower() == S[l - 1].lower():\n count += 1\n l += 1\n else:\n new += str(count) + S[l - 1].lower()\n count = 1\n l += 1\n new += str(count) + S[l - 1].lower()\n return new", "def transform(S):\n S = S.lower()\n S = S + ' '\n x = S[0]\n y = 0\n z = ''\n for (index, item) in enumerate(S):\n if item != x:\n z = z + str(index - y) + x\n y = index\n x = item\n return z", "def transform(s):\n s = s.lower()\n st = []\n count = 1\n for i in range(len(s) - 1):\n if s[i] != s[i + 1]:\n st.append(str(count))\n st.append(s[i])\n count = 1\n else:\n count += 1\n st.append(str(count))\n st.append(s[-1])\n return ''.join(st)", "def transform(S):\n S = S.lower()\n result = ''\n n = 1\n while len(S) > 1:\n if S[0] == S[1]:\n n += 1\n S = S[1:]\n else:\n result += str(n) + S[0]\n S = S[1:]\n n = 1\n result += str(n) + S[0]\n return result", "def transform(S):\n S = S.lower()\n res = ''\n c = 0\n st = []\n for x in S:\n if not st:\n st.append(x)\n c += 1\n elif st and x == st[-1]:\n st.append(x)\n c += 1\n elif st and x != st[-1]:\n res += str(c) + st[-1]\n st.append(x)\n c = 1\n res += str(c) + st[-1]\n return res", "def transform(S):\n S = S.lower()\n (i, j) = (0, 1)\n ans = ''\n count = 1\n if len(S) == 1:\n ans += str(count) + S[0]\n return ans\n while i < len(S) or j < len(S):\n if S[i] == S[j]:\n count += 1\n if j == len(S) - 1:\n ans += str(count) + S[i]\n break\n j += 1\n else:\n ans += str(count) + S[i]\n count = 1\n i = j\n if j == len(S) - 1:\n ans += str(count) + S[j]\n break\n j += 1\n return ans", "def transform(S):\n result = ''\n current_char = ''\n count = 0\n for ch in S:\n ch = ch.lower()\n if ch == current_char:\n count += 1\n else:\n if current_char:\n result += str(count) + current_char\n current_char = ch\n count = 1\n if current_char:\n result += str(count) + current_char\n return result", "def transform(s):\n s = s.lower()\n from itertools import groupby\n r = ''\n k = [[len(list(j)), i] for (i, j) in groupby(s)]\n for i in k:\n for j in i:\n r += str(j)\n return r", "def transform(S):\n l = list(S)\n c = 0\n l1 = []\n j = 0\n d = {}\n for i in range(len(l)):\n if l1 == []:\n l1.append(l[i].lower())\n c += 1\n elif l1[-1] == l[i].lower():\n c += 1\n else:\n d[j] = [str(c), l1.pop()]\n c = 1\n l1.append(l[i].lower())\n j += 1\n if c > 0:\n d[j] = [str(c), l1.pop()]\n d1 = sorted(d.keys())\n s = ''\n for i in d1:\n for j in d[i]:\n s += j\n return s", "def transform(s):\n s = s.lower()\n n = len(s)\n new_str = ''\n j = 0\n count = 0\n for i in range(n):\n if s[i] == s[j]:\n count += 1\n else:\n new_str = new_str + str(count) + s[j]\n j = i\n count = 1\n new_str = new_str + str(count) + s[j]\n return new_str", "def transform(S):\n numb = 1\n stack = []\n res = ''\n for i in S.lower():\n if len(stack) == 0:\n stack.append(i)\n elif i == stack[-1]:\n numb += 1\n else:\n res += str(numb) + stack[-1]\n stack.append(i)\n numb = 1\n res += str(numb) + stack[-1]\n return res", "import queue\n\ndef transform(S):\n q = queue.LifoQueue()\n for i in range(len(S) - 1, -1, -1):\n if q.qsize() and q.queue[-1][0] == S[i].lower():\n q.queue[-1][1] += 1\n else:\n q.put([S[i].lower(), 1])\n res = ''\n while q.qsize():\n k = q.get()\n res += str(k[1]) + str(k[0])\n return res", "def transform(S):\n S = S.lower()\n init = S[0]\n cc = 1\n ans = ''\n for i in S[1:]:\n if i == init:\n cc += 1\n else:\n ans += str(cc) + init\n init = i\n cc = 1\n ans += str(cc) + init\n return ans", "def transform(s):\n s = s.lower()\n if len(s) == 1:\n return '1' + s\n new_s = ''\n count = 1\n for i in range(0, len(s) - 1):\n if s[i] == s[i + 1]:\n count += 1\n else:\n new_s += str(count) + s[i]\n count = 1\n else:\n new_s += str(count) + s[i + 1]\n return new_s", "def transform(S):\n stack = []\n top = -1\n ans = ''\n for i in range(0, len(S)):\n if len(stack) == 0 or stack[top] == S[i].lower() or stack[top] == S[i].upper():\n stack.append(S[i])\n else:\n ans = ans + str(len(stack)) + stack[top].lower()\n while len(stack) > 0:\n stack.pop()\n stack.append(S[i])\n ans = ans + str(len(stack)) + stack[top].lower()\n return ans", "def transform(S):\n s = S.lower() + ' '\n c = 1\n j = 1\n r = ''\n while j < len(s):\n if s[j] == s[j - 1]:\n c += 1\n else:\n r = r + str(c) + s[j - 1]\n c = 1\n j += 1\n return r", "def transform(s):\n s = s.lower()\n s += '@!'\n l = []\n c = 1\n for i in range(len(s) - 2):\n if s[i] == s[i + 1]:\n c += 1\n else:\n l.append(c)\n l.append(s[i])\n c = 1\n f = ''\n for i in range(len(l)):\n l[i] = str(l[i])\n for i in l:\n f += i\n return f", "def transform(s):\n stack = []\n for i in range(len(s)):\n if stack:\n if stack[-1][0] == s[i].lower():\n stack[-1][-1] += 1\n continue\n stack.append([s[i].lower(), 1])\n res = ''\n for i in range(len(stack)):\n res += str(stack[i][-1]) + stack[i][0]\n return res", "def transform(S):\n S = S.lower()\n a = S[0]\n c = 1\n b = ''\n for i in S[1:]:\n if i == a:\n c += 1\n else:\n b += str(c) + a\n a = i\n c = 1\n b += str(c) + a\n return b", "def transform(S):\n z = S.lower()\n l = []\n m = ''\n n = len(z)\n for i in z:\n if len(l) == 0:\n l.append(i)\n elif l[-1] == i:\n l.append(i)\n else:\n m += str(len(l)) + l[-1]\n l = []\n l.append(i)\n m += str(len(l)) + l[-1]\n return m", "def transform(arr):\n arr = arr.lower()\n n = 0\n arr = arr + '.'\n e = arr[0]\n S = ''\n for i in arr:\n if i == e:\n n += 1\n else:\n S = S + str(n) + e\n e = i\n n = 1\n return S", "def transform(S):\n a = 1\n s = ''\n for i in range(1, len(S)):\n if S[i].lower() == S[i - 1].lower():\n a += 1\n else:\n s += str(a) + S[i - 1].lower()\n a = 1\n s += str(a) + S[-1].lower()\n return s", "def transform(S):\n S = S.lower()\n from itertools import groupby\n m = [[len(list(j)), i] for (i, j) in groupby(S)]\n r = []\n for i in m:\n for j in i:\n r.append(j)\n return ''.join(map(str, r))"], "starter_code": "def transform(S):\n", "input_output": {"inputs": ["S = \"aaABBb\"", "S = \"aaacca\""], "outputs": ["\"3a3b\"", "\"3a2c1a\""]}, "difficulty": "EASY", "raw_tags": ["Stack", "Strings", "Data Structures"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/easy-string2212/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(|S|)", "entry_point": "transform", "task_id": "TACO_lite/540", "example": [[["aaABBb"], ["aaacca"]], ["3a3b", "3a2c1a"]]} +{"requirement": "~~~if-not:ruby,python\nReturn `1` when *any* odd bit of `x` equals 1; `0` otherwise.\n~~~\n~~~if:ruby,python\nReturn `true` when *any* odd bit of `x` equals 1; `false` otherwise.\n~~~\n\nAssume that:\n* `x` is an unsigned, 32-bit integer;\n* the bits are zero-indexed (the least significant bit is position 0)\n\n\n## Examples\n\n```\n 2 --> 1 (true) because at least one odd bit is 1 (2 = 0b10)\n 5 --> 0 (false) because none of the odd bits are 1 (5 = 0b101)\n170 --> 1 (true) because all of the odd bits are 1 (170 = 0b10101010)\n```", "solutions": ["MATCH = int('10' * 16, 2)\n\ndef any_odd(x):\n return bool(MATCH & x)", "def any_odd(n):\n return 1 if '1' in bin(n)[2:][-2::-2] else 0", "def any_odd(x):\n return x & 2863311530 != 0", "def any_odd(x):\n return int('1' in f'{x:032b}'[::2])", "def any_odd(x):\n a = bin(x)[2:]\n b = a[-2::-2]\n return 1 if '1' in b else 0", "def any_odd(x):\n return '1' in f'0{x:b}'[-2::-2]", "def any_odd(x):\n binary = bin(x)\n answer = 0\n binary_reversed = str(binary[::-1])\n for k in range(0, len(binary_reversed)):\n if k % 2 != 0 and binary_reversed[k] == '1':\n answer = 1\n return answer", "def any_odd(x):\n return '1' in list(bin(x)[-2::-2])", "def any_odd(x):\n bina = bin(x).split('b')[1]\n for (a, b) in enumerate(bina, start=len(bina) - 1):\n if a % 2:\n if '1' in b:\n return 1\n return 0"], "starter_code": "def any_odd(x):\n", "input_output": {"fn_name": "any_odd", "inputs": [[2863311530], [128], [131], [2], [24082], [0], [85], [1024], [1], [1365]], "outputs": [[true], [true], [true], [true], [true], [false], [false], [false], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals", "Bits"], "name": null, "source": "codewars", "tags": ["Bit manipulation", "Fundamentals"], "skill_types": ["Bit manipulation"], "url": "https://www.codewars.com/kata/5d6f49d85e45290016bf4718", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "any_odd", "task_id": "TACO_lite/518", "example": [[[2], [5], [170]], [true, false, true]]} +{"requirement": "## Task:\n\nYour task is to write a function which returns the sum of following series upto nth term(parameter).\n\n Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...\n \n## Rules:\n \n* You need to round the answer to 2 decimal places and return it as String.\n\n* If the given value is 0 then it should return 0.00\n\n* You will only be given Natural Numbers as arguments.\n\n## Examples:\n\n SeriesSum(1) => 1 = \"1.00\"\n SeriesSum(2) => 1 + 1/4 = \"1.25\"\n SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = \"1.57\"\n \n**NOTE**: In PHP the function is called `series_sum()`.", "solutions": ["def series_sum(n):\n return '{:.2f}'.format(sum((1.0 / (3 * i + 1) for i in range(n))))", "def series_sum(n):\n seriesSum = 0.0\n for x in range(n):\n seriesSum += 1 / (1 + x * 3)\n return '%.2f' % seriesSum", "from fractions import Fraction\n\ndef series_sum(n):\n total = sum((Fraction(1, 1 + i * 3) for i in range(n)))\n return '{:.2f}'.format(total.numerator / total.denominator)", "def series_sum(n):\n return f'{sum((1 / d for d in range(1, n * 3, 3))):.2f}'", "def series_sum(n):\n return '%.2f' % sum(map(lambda x: x ** (-1), range(1, 3 * n, 3)))", "def series_sum(n):\n result = 0\n for i in range(0, n):\n result += 1 / (1 + 3 * i)\n return '{number:.{digits}f}'.format(number=result, digits=2)", "series_sum = lambda n: '{:.2f}'.format(sum((1.0 / (3 * i - 2) for i in range(1, n + 1))))", "series_sum = lambda n: '{:.2f}'.format(round(sum((1 / (1 + e * 3) for e in range(n))), 2))", "def series_sum(n):\n total = 0\n for i in range(n):\n total += 1 / (1 + i * 3)\n return str('%.2f' % total)", "def series_sum(number):\n solution = sum((1 / (1 + 3 * i) for i in range(number)))\n return format(solution, '.2f')", "def series_sum(n):\n return f'{n and sum((1 / i for i in range(1, n * 3 + 1, 3))):.2f}'", "from fractions import Fraction\nfrom functools import lru_cache\n\ndef rec(n):\n if not n:\n return 0\n return Fraction(1, 3 * n - 2) + rec(n - 1)\n\ndef series_sum(n):\n return f'{float(rec(n)):.2f}'", "def series_sum(n):\n sum = 0.0\n if n == 1:\n return '1.00'\n elif n == 0:\n return '0.00'\n else:\n denominator = 1.0\n for i in range(0, n):\n if i + 1 <= n:\n sum = sum + 1 / denominator\n denominator = denominator + 3.0\n return str(format(round(sum, 2), '.2f'))", "def series_sum(n):\n return '%.2f' % sum((1 / x for x in range(1, n * 3 + 1, 3)))", "def series_sum(n):\n l = []\n if n == 0:\n x = '0.00'\n while n > 0:\n l.append(1 / (1 + 3 * (n - 1)))\n n -= 1\n x = '%.2f' % sum(l)\n return x", "def series_sum(n):\n return '%0.2f' % round(sum([1 / (1 + (x - 1) * 3) for x in range(1, n + 1)]), 2)", "def series_sum(n):\n if n == 0:\n return '0.00'\n else:\n x = 1\n sum = 0\n for i in range(n):\n sum += 1 / x\n x += 3\n s = '{:0.2f}'.format(sum)\n return s", "def series_sum(n):\n return '{0:.2f}'.format(round(sum((1.0 / (1 + 3 * m) for m in range(n))), 2)) if n else '0.00'", "def series_sum(n):\n if n == 0:\n return '0.00'\n return '%0.2f' % float(str(1 + sum((1 / (1 + i * 3) for i in range(1, n)))))", "def series_sum(n):\n return format(sum((1 / (1 + 3 * k) for k in range(n))), '.2f')", "def series_sum(n):\n ls = []\n if n == 0:\n return str('%5.2f' % 0.0)[1:]\n for n in range(1, n):\n ls.append(1 / (1 + n * 3))\n return str('%5.2f' % float(sum(ls) + 1))[1:]", "def series_sum(n):\n return '%.2f' % sum([1 / (1 + 3 * t) for t in range(n)])", "def series_sum(n):\n result = 0\n for i in range(0, n):\n result += 1.0 / (1 + 3 * i)\n stringresult = str(round(result, 2))\n if stringresult == '0':\n stringresult = '0.00'\n while len(stringresult) < 4:\n stringresult += '0'\n return stringresult", "def series_sum(n):\n if n == 0:\n return '0.00'\n elif n == 1:\n return '1.00'\n sum = 1.0\n for i in range(1, n):\n sum += 1 / (1 + 3 * i)\n return '%.2f' % sum", "def series_sum(n):\n x = 0\n y = 1\n for n in range(1, n + 1):\n x = x + y\n y = 1 / (1 / y + 3)\n n = n - 1\n return format(x, '.2f')", "def series_sum(n):\n sum_ = sum([1 / (i * 3 - 2) for i in range(1, n + 1)])\n return '%.2f' % sum_", "from decimal import Decimal\n\ndef series_sum(n):\n if n == 0:\n sum_ = 0\n else:\n sum_ = 1\n for i in range(n - 1):\n nth_value = 1 / (4 + 3 * i)\n sum_ += nth_value\n sum_str = str(round(Decimal(sum_), 2))\n return sum_str", "def series_sum(n):\n return '{0:.2f}'.format(sum([(1 + 3 * (k - 1)) ** (-1) if k > 0 else k for k in range(n + 1)]))", "def series_sum(n):\n return '%.2f' % series_sum_(n)\n\ndef series_sum_(n):\n if n > 1:\n return series_sum_(n - 1) + float(float(1.0) / float(3 * (n - 1) + 1))\n elif n == 1:\n return float(1.0)\n return float(0.0)", "def series_sum(n):\n total = 0\n for num in range(1, n + 1):\n total += 1 / (1 + 3 * (num - 1))\n return '%.2f' % total", "def series_sum(n):\n f = 3 * n - 2\n s = 0\n if n == 0:\n return '0.00'\n for i in range(1, f + 1, 3):\n s = s + 1 / i\n return '{:.2f}'.format(s)", "def series_sum(n):\n sum = 0\n div = 1\n for i in range(n):\n sum += 1 / div\n div += 3\n if n == 0:\n return str(n) + '.00'\n elif len(str(round(sum, 2))) < 4:\n return str(round(sum, 2)) + '0'\n else:\n return str(round(sum, 2))", "def series_sum(n):\n if n == 0:\n term = 0\n elif n > 0:\n term = 1\n for i in range(1, n):\n term += 1 / (3 * i + 1)\n sumterm = float('{:.2f}'.format(term))\n return '%0.2f' % term", "def series_sum(n):\n if n == 0:\n return '0.00'\n else:\n counter = 1\n list = [1]\n while counter < n:\n list.append(1 / (1 + 3 * counter))\n counter += 1\n flt = round(sum(list), 2)\n result = format(flt, '.2f')\n return result", "def series_sum(n):\n ans = 0\n while n != 0:\n ans += 1 / (3 * n - 2)\n n -= 1\n return '{:.2f}'.format(round(ans, 2)).__str__()", "def series_sum(n):\n if n == 0:\n return '0.00'\n final = 0\n x = 0\n while n >= 1:\n final += 1 / (1 + x)\n x += 3\n n -= 1\n final = str(final)\n if len(final) < 4:\n final += '0'\n if len(final) > 4:\n if int(final[4]) > 4:\n final = str(float(final) + 0.01)\n return str(final)[:4]", "def series_sum(n):\n summa = sum([1 / (1 + 3 * x) for x in range(n)])\n return f'{summa:.{2}f}'", "def series_sum(n=0):\n sum = 0.0\n num = 1\n for i in range(n):\n sum += 1 / num\n num += 3\n return (str(round(sum, 2)) + '0')[:4]", "def series_sum(n):\n x = 1\n s = 0\n for i in range(n):\n s += 1 / (x + i * 3)\n if s == 0:\n return '0.00'\n if len(str(round(s, 2))) < 4:\n return str(round(s, 2)) + '0'\n return str(round(s, 2))", "def series_sum(n):\n if n == 0:\n return '0.00'\n if n == 1:\n return '1.00'\n elif n == 2:\n return '1.25'\n else:\n sum = 1.25\n i = 4\n for loop in range(n - 2):\n i = i + 3\n sum = sum + 1 / i\n return '{:.2f}'.format(sum)", "def series_sum(n):\n result = 1 + 1 / 4\n a = 4\n if n == 1:\n return str('%.2f' % n)\n elif n == 0:\n return str('%.2f' % 0)\n for i in range(1, n - 1):\n result += 1 / (a + i * 3)\n return str('%.2f' % result)", "def series_sum(n):\n answer = 0\n for number in range(n):\n answer += 1 / (1 + number * 3)\n return str(format(answer, '.2f'))", "def series_sum(n):\n i = 1\n x = 0\n for a in range(n):\n x += 1 / i\n i += 3\n return '{:.2f}'.format(x)", "def series_sum(n):\n output = 0\n for i in range(n):\n output += 1 / (1 + i * 3)\n if len(str(round(output, 2))) < 4:\n if str(round(output, 2)) != '0':\n a = str(round(output, 2))\n a += '0'\n return a\n else:\n return '0.00'\n else:\n return str(round(output, 2))", "def series_sum(n):\n if n == 0:\n return '0.00'\n if n == 1:\n return '1.00'\n sum = 1.0\n for i in range(n - 1):\n sum = sum + 1 / (4 + 3 * i)\n return '{:.2f}'.format(sum)", "import decimal\n\ndef series_sum(n):\n return '%.2f' % sum((1 / (1 + 3 * i) for i in range(n)))", "import math\n\ndef series_sum(n):\n result = 0.0\n for i in list(range(0, n)):\n result += 1.0 / (1.0 + 3.0 * float(i))\n return '{:.2f}'.format(result)", "def series_sum(n):\n if n == 0:\n return '0.00'\n else:\n numerator = 1\n denom = 1\n output = ''\n num = 0.0\n for i in range(n):\n num += numerator / denom\n denom += 3\n output = str(format(round(num, 2), '.2f'))\n return output", "from fractions import Fraction\n\ndef series_sum(n):\n sum = 0\n for i in range(n):\n sum += 1 / (1 + i * 3)\n return format(sum, '.2f')", "def series_sum(n):\n return (str(round(1 + sum((1 / x for x in range(4, n * 3, 3))), 2)) if n > 1 else str(float(n))).ljust(4, '0')", "def series_sum(n):\n s = 1\n i = 1\n if n > 1:\n while i < n:\n s = 1 / (1 + i * 3) + s\n i += 1\n else:\n return str('%.2f' % n)\n return str('%.2f' % s)", "def series_sum(n):\n array = []\n for i in range(n):\n array.append(1 / (1 + 3 * i))\n return f'{sum(array):.2f}'", "def series_sum(n):\n sum = 0.0\n denom = 1.0\n for i in range(1, n + 1):\n sum = sum + 1 / denom\n denom = denom + 3.0\n return f'{sum:.2f}'", "def series_sum(n):\n sum = float()\n j = 1\n for i in range(n):\n sum += 1 / j\n j += 3\n result = str(round(sum, 2))\n if len(result) == 3:\n return result + '0'\n else:\n return result", "def series_sum(n):\n if n == 0:\n return '0.00'\n d = 1\n ans = 0\n for i in range(n):\n ans += 1 / d\n d += 3\n ans = f'{round(ans, 2)}'\n return ans if len(ans) == 4 else ans + '0' * (4 - len(ans))", "def series_sum(n):\n sum = 1.0\n if n == 1:\n return '1.00'\n elif n == 0:\n return '0.00'\n else:\n for x in range(1, n):\n sum = sum + 1 / (2 * (x + 1) + (x - 1))\n return '{:.2f}'.format(sum)", "def series_sum(n):\n sum = 0.0\n value = 1.0\n if n == 0:\n return format(sum, '.2f')\n for i in range(1, n + 1):\n sum = sum + 1 / value\n value += 3\n result = float('{0:.2f}'.format(sum))\n return format(sum, '.2f')", "def series_sum(n):\n y = str(round(sum([1 / x for x in range(1, n * 3 + 1, 3)]), 2))\n while len(y) < 4:\n y += '0'\n return '0.00' if n == 0 else y", "def series_sum(n):\n if n == 0:\n return '0.00'\n elif n == 1:\n return '1.00'\n else:\n s = 1\n a = [1]\n for i in range(n):\n s += 3\n a.append(1 / s)\n a[-1] = 0\n a = str(round(sum(a), 2))\n if len(a) == 4:\n return a\n else:\n b = a + '0'\n return b"], "starter_code": "def series_sum(n):\n", "input_output": {"fn_name": "series_sum", "inputs": [[1], [2], [3], [4], [5], [6], [7], [8], [9], [15], [39], [58], [0]], "outputs": [["1.00"], ["1.25"], ["1.39"], ["1.49"], ["1.57"], ["1.63"], ["1.68"], ["1.73"], ["1.77"], ["1.94"], ["2.26"], ["2.40"], ["0.00"]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/555eded1ad94b00403000071", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "series_sum", "task_id": "TACO_lite/478", "example": [[[1], [2], [5]], ["1.00", "1.25", "1.57"]]} +{"requirement": "Given a binary tree, find its level order traversal.\nLevel order traversal of a tree is breadth-first traversal for the tree.\nExample 1:\nInput:\n 1\n / \\ \n 3 2\nOutput:1 3 2\nExample 2:\nInput:\n 10\n / \\\n 20 30\n / \\\n 40 60\nOutput:10 20 30 40 60\nYour Task:\nYou don't have to take any input. Complete the function levelOrder() that takes the root node as input parameter and returns a list of integers containing the level order traversal of the given Binary Tree.\nExpected Time Complexity: O(n)\nExpected Auxiliary Space: O(n)\nConstraints:\n1 \u2264 Number of nodes \u2264 105\n1 \u2264 Data of a node \u2264 105", "solutions": ["def levelorder(root):\n if root is None:\n return\n queue = [root]\n res = []\n while queue:\n pointer = queue.pop(0)\n res.append(pointer.data)\n if pointer.left is not None:\n queue.append(pointer.left)\n if pointer.right is not None:\n queue.append(pointer.right)\n return res", "def levelorder(root):\n q = []\n q.append(root)\n res = []\n while len(q) != 0:\n u = q.pop(0)\n res.append(u.data)\n if u.left is not None:\n q.append(u.left)\n if u.right is not None:\n q.append(u.right)\n return res", "def levelorder(root):\n result = []\n if not root:\n return result\n queue = deque()\n queue.append(root)\n while queue:\n size = len(queue)\n for i in range(size):\n temp = queue.popleft()\n result.append(temp.data)\n if temp.left != None:\n queue.append(temp.left)\n if temp.right != None:\n queue.append(temp.right)\n return result", "def levelorder(root):\n res = []\n if root is None:\n return res\n que = []\n que.append(root)\n while 1:\n n = len(que)\n if n == 0:\n break\n while n > 0:\n node = que.pop(0)\n res.append(node.data)\n if node.left != None:\n que.append(node.left)\n if node.right != None:\n que.append(node.right)\n n -= 1\n return res", "def levelorder(root):\n q = deque([root])\n ans = []\n while q:\n node = q.popleft()\n ans.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return ans", "def levelorder(root):\n if root == None:\n return\n stack = []\n res = []\n stack.append(root)\n while len(stack) != 0:\n res.append(stack[0].data)\n node = stack.pop(0)\n if node.left != None:\n stack.append(node.left)\n if node.right != None:\n stack.append(node.right)\n return res", "from collections import deque\n\ndef levelorder(node):\n queue = deque()\n queue.append(node)\n return_list = []\n while queue:\n temp = queue.popleft()\n return_list.append(temp.data)\n if temp.left:\n queue.append(temp.left)\n if temp.right:\n queue.append(temp.right)\n return return_list", "def levelorder(root):\n q = deque()\n res = []\n q.append(root)\n while len(q):\n t = q.popleft()\n res.append(t.data)\n if t.left is not None:\n q.append(t.left)\n if t.right is not None:\n q.append(t.right)\n return res", "from queue import Queue\n\ndef levelorder(root):\n q = Queue()\n q.put(root)\n ans = list()\n while q.qsize() > 0:\n node = q.get()\n ans.append(node.data)\n if node.left:\n q.put(node.left)\n if node.right:\n q.put(node.right)\n return ans", "from collections import deque\n\ndef levelorder(root):\n queue = deque()\n ans = []\n queue.append(root)\n while len(queue) >= 1:\n node = queue.popleft()\n if node.left is not None:\n queue.append(node.left)\n if node.right is not None:\n queue.append(node.right)\n ans.append(node.data)\n return ans", "def levelorder(root):\n a = [root]\n res = []\n while len(a) > 0:\n p = a.pop(0)\n if p.left:\n a.append(p.left)\n if p.right:\n a.append(p.right)\n res.append(p.data)\n return res", "def levelorder(root):\n a = []\n if root == None:\n return root\n a.append(root)\n q = [root.data]\n while len(a) != 0:\n t = a[0]\n if t.left:\n q.append(t.left.data)\n a.append(t.left)\n if t.right:\n q.append(t.right.data)\n a.append(t.right)\n a.pop(0)\n return q", "from collections import deque\n\ndef levelorder(root):\n ans = []\n q = deque([root])\n while q:\n x = q.popleft()\n ans.append(x.data)\n if x.left:\n q.append(x.left)\n if x.right:\n q.append(x.right)\n return ans", "def levelorder(root):\n if root == None:\n return []\n q = [root]\n ans = []\n while q:\n nod = q.pop(0)\n ans.append(nod.data)\n if nod.left:\n q.append(nod.left)\n if nod.right:\n q.append(nod.right)\n return ans", "from collections import deque\n\ndef levelorder(root):\n ans = []\n if root is None:\n return\n queue1 = deque()\n queue2 = deque()\n queue1.append(root)\n while len(queue1) != 0:\n top = queue1[0]\n queue1.popleft()\n ans.append(top.data)\n if top.left is not None:\n queue2.append(top.left)\n if top.right is not None:\n queue2.append(top.right)\n if len(queue1) == 0:\n (queue1, queue2) = (queue2, queue1)\n return ans", "def printCurrentLevel(root, level, ans):\n if root is None:\n return\n if level == 1:\n ans.append(root.data)\n elif level > 1:\n self.printCurrentLevel(root.left, level - 1, ans)\n self.printCurrentLevel(root.right, level - 1, ans)\n\ndef height(node):\n if node is None:\n return 0\n else:\n lheight = self.height(node.left)\n rheight = self.height(node.right)\n if lheight > rheight:\n return lheight + 1\n else:\n return rheight + 1\n\ndef levelorder(root):\n ans = []\n h = self.height(root)\n for i in range(1, h + 1):\n self.printCurrentLevel(root, i, ans)\n return ans", "from collections import deque\n\ndef levelorder(root):\n q = deque()\n q.append(root)\n arr = []\n while len(q) > 0:\n node = q.popleft()\n arr.append(node.data)\n if node.left != None:\n q.append(node.left)\n if node.right != None:\n q.append(node.right)\n return arr", "def levelorder(root):\n ans = []\n queue = [root]\n while queue:\n node = queue.pop(0)\n ans.append(node.data)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return ans", "def levelorder(root):\n if root is None:\n return []\n queue = [root]\n level_order = []\n while len(queue) > 0:\n node = queue.pop(0)\n level_order.append(node.data)\n if node.left is not None:\n queue.append(node.left)\n if node.right is not None:\n queue.append(node.right)\n return level_order", "def levelorder(root):\n ls = []\n ans = []\n ls.append(root)\n while ls:\n ele = ls.pop(0)\n ans.append(ele.data)\n if ele.left != None:\n ls.append(ele.left)\n if ele.right != None:\n ls.append(ele.right)\n return ans", "def levelorder(root):\n lvl = self.height(root)\n res = []\n for i in range(1, lvl + 1):\n self.lvlorderByHeight(root, i, res)\n return res\n\ndef lvlorderByHeight(root, target, res):\n if root == None or target <= 0:\n return\n if target == 1:\n res.append(root.data)\n return\n self.lvlorderByHeight(root.left, target - 1, res)\n self.lvlorderByHeight(root.right, target - 1, res)\n\ndef height(root):\n if root == None:\n return 0\n left = self.height(root.left)\n right = self.height(root.right)\n if left > right:\n return left + 1\n else:\n return right + 1", "def levelorder(root):\n qu = [root]\n res = []\n while qu:\n n = len(qu)\n while n:\n node = qu.pop(0)\n res.append(node.data)\n if node.left:\n qu.append(node.left)\n if node.right:\n qu.append(node.right)\n n -= 1\n return res", "def levelorder(root):\n if not root:\n return\n q = []\n res = []\n if root:\n q.append(root)\n while q:\n level = []\n size = len(q)\n for i in range(size):\n node = q.pop(0)\n level.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n res.append(level)\n result = []\n for i in res:\n for j in i:\n result.append(j)\n return result", "def levelorder(root):\n if root is None:\n return []\n queue = [root]\n next_queue = []\n level = []\n res = []\n while queue != []:\n for root in queue:\n level.append(root.data)\n if root.left is not None:\n next_queue.append(root.left)\n if root.right is not None:\n next_queue.append(root.right)\n for i in level:\n res.append(i)\n queue = next_queue\n next_queue = []\n level = []\n return res", "def levelorder(root):\n level_order = []\n max_height = [0]\n\n def get_tree_height(root):\n if root is None:\n return 0\n left_height = 1 + get_tree_height(root.left)\n right_height = 1 + get_tree_height(root.right)\n current_height = max(left_height, right_height)\n return current_height\n height = get_tree_height(root)\n\n def helper(root, level, level_order, target_level):\n if root:\n if level == target_level:\n level_order.append(root.data)\n else:\n helper(root.left, level + 1, level_order, target_level)\n helper(root.right, level + 1, level_order, target_level)\n for target_height in range(height):\n helper(root, 0, level_order, target_height)\n return level_order", "def levelorder(root):\n from collections import deque\n q = deque()\n q.append(root)\n level_order = []\n while len(q) > 0:\n for i in range(len(q)):\n current_node = q.popleft()\n level_order.append(current_node.data)\n if current_node.left:\n q.append(current_node.left)\n if current_node.right:\n q.append(current_node.right)\n return level_order", "from collections import deque\n\ndef levelorder(root):\n if root is None:\n return\n q = deque()\n q.append(root)\n ans = []\n while len(q) > 0:\n temp = q.popleft()\n ans.append(temp.data)\n if temp.left is not None:\n q.append(temp.left)\n if temp.right is not None:\n q.append(temp.right)\n return list(ans)", "def levelorder(root):\n arr = []\n\n def height(root):\n if not root:\n return 0\n return max(height(root.left), height(root.right)) + 1\n\n def func(root, level):\n if not root:\n return\n if level == 1:\n arr.append(root.data)\n return\n func(root.left, level - 1)\n func(root.right, level - 1)\n h = height(root)\n for i in range(1, h + 1):\n func(root, i)\n return arr", "import queue\n\ndef levelorder(root):\n if root is None:\n return None\n q = queue.Queue()\n mylist = []\n q.put(root)\n while not q.empty():\n curr = q.get()\n mylist.append(curr.data)\n if curr.left is not None:\n q.put(curr.left)\n if curr.right is not None:\n q.put(curr.right)\n return mylist", "def levelorder(root):\n q = [root]\n valuelist = []\n l = iter(q)\n root_ = next(l, 'end')\n while root_ != 'end':\n if root_.left:\n q.append(root_.left)\n if root_.right:\n q.append(root_.right)\n valuelist.append(root_.data)\n root_ = next(l, 'end')\n return valuelist", "def levelorder(root):\n res = []\n queue = []\n if root:\n queue.append(root)\n while queue:\n element = queue.pop(0)\n if element.left:\n queue.append(element.left)\n if element.right:\n queue.append(element.right)\n res.append(element.data)\n return res", "import queue\n\ndef levelorder(root):\n q = queue.Queue()\n out = []\n if not root:\n return out\n q.put(root)\n while q.qsize():\n node = q.get()\n out.append(node.data)\n if node.left:\n q.put(node.left)\n if node.right:\n q.put(node.right)\n return out", "def levelorderUtil(root, map, level):\n if root:\n self.levelorderUtil(root.left, map, level + 1)\n self.levelorderUtil(root.right, map, level + 1)\n if level not in map:\n map[level] = []\n map[level].append(root.data)\n\ndef levelorder(root):\n map = {}\n self.levelorderUtil(root, map, 0)\n out = []\n for level in range(len(map)):\n out.extend(map[level])\n return out", "def levelorder(root):\n if root is None:\n return []\n visited = []\n queue = [root]\n while queue:\n node = queue.pop(0)\n visited.append(node.data)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return visited", "from collections import deque\n\ndef levelorder(root):\n arr = []\n q = deque([root])\n while q:\n Node = q.popleft()\n arr.append(Node.data)\n if Node.left != None:\n q.append(Node.left)\n if Node.right != None:\n q.append(Node.right)\n return arr", "from collections import deque\n\ndef levelorder(root):\n q = deque()\n if root is None:\n return\n q.append(root)\n res = []\n while len(q) != 0:\n x = q.popleft()\n res.append(x.data)\n if x.left is not None:\n q.append(x.left)\n if x.right is not None:\n q.append(x.right)\n return res", "def levelorder(root):\n queue = [root]\n answer = []\n while queue:\n size = len(queue)\n for i in range(size):\n node = queue.pop(0)\n answer.append(node.data)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return answer", "def levelorder(root):\n queue = deque()\n queue.append(root)\n answer = []\n while queue:\n e = queue.popleft()\n answer.append(e.data)\n if e.left:\n queue.append(e.left)\n if e.right:\n queue.append(e.right)\n return answer", "def levelorder(root):\n temp = []\n l = [root]\n while len(l) > 0:\n x = l.pop(0)\n temp.append(x.data)\n if x.left:\n l.append(x.left)\n if x.right:\n l.append(x.right)\n return temp", "def levelorder(root):\n temp_arr = [[]]\n\n def levelorderUtil(root, level):\n if not root:\n return\n if temp_arr[level]:\n temp_arr[level].append(root.data)\n else:\n temp_arr.insert(level, [root.data])\n levelorderUtil(root.left, level + 1)\n levelorderUtil(root.right, level + 1)\n levelorderUtil(root, 0)\n result_arr = []\n for i in range(len(temp_arr)):\n result_arr += temp_arr[i]\n return result_arr", "def levelorder(root):\n l = []\n\n def height(node):\n if not node:\n return 0\n return max(height(node.left), height(node.right)) + 1\n\n def traverse(node, level):\n if not node:\n return\n if level == 1:\n l.append(node.data)\n else:\n traverse(node.left, level - 1)\n traverse(node.right, level - 1)\n h = height(root)\n for i in range(1, h + 1):\n traverse(root, i)\n return l", "from collections import deque\n\ndef fun(root, level, res):\n if root == None:\n return\n if level >= len(res):\n res.append([])\n res[level].append(root.data)\n self.fun(root.left, level + 1, res)\n self.fun(root.right, level + 1, res)\n\ndef levelorder(root):\n res = []\n self.fun(root, 0, res)\n l = []\n for i in res:\n l.extend(i)\n return l", "def levelorder(root):\n queue = [root]\n answer = []\n while queue:\n p = queue.pop(0)\n answer.append(p.data)\n if p.left is not None:\n queue.append(p.left)\n if p.right is not None:\n queue.append(p.right)\n return answer", "from collections import deque\n\ndef levelorder(root):\n if root is None:\n return []\n result = []\n queue = deque([root])\n while queue:\n level_length = len(queue)\n current_level = []\n for i in range(level_length):\n node = queue.popleft()\n current_level.append(node.data)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n result.append(current_level)\n return [val for level in result for val in level]", "def levelorder(root):\n temp_list = [root]\n output = []\n while len(temp_list) != 0:\n temp = []\n for node in temp_list:\n output.append(node.data)\n if node.left != None:\n temp.append(node.left)\n if node.right != None:\n temp.append(node.right)\n temp_list = temp\n return output", "def levelorder(root):\n if root == None:\n return None\n q = []\n q.append(root)\n result = []\n while q:\n n = len(q)\n for i in range(0, n):\n node = q.pop(0)\n if node is not None:\n result.append(node.data)\n q.append(node.left if node.left else None)\n q.append(node.right if node.right else None)\n return result", "def levelorder(root):\n q = [root]\n list1 = []\n while q:\n node = q.pop(0)\n list1.append(node.data)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return list1", "from collections import deque\n\ndef levelorder(root):\n listing = list()\n dQ = deque()\n dQ.append(root)\n while dQ:\n times = len(dQ)\n for i in range(times):\n holdnode = dQ.popleft()\n listing.append(holdnode.data)\n if holdnode.left != None:\n dQ.append(holdnode.left)\n if holdnode.right != None:\n dQ.append(holdnode.right)\n return listing", "import collections\nfrom collections import deque\n\ndef levelorder(root):\n ans = []\n if root is None:\n return ans\n queue = collections.deque()\n queue.append(root)\n while queue:\n currSize = len(queue)\n currList = []\n while currSize > 0:\n currNode = queue.popleft()\n currList.append(currNode.data)\n currSize -= 1\n if currNode.left is not None:\n queue.append(currNode.left)\n if currNode.right is not None:\n queue.append(currNode.right)\n ans.append(currList)\n res = []\n for i in ans:\n res.extend(i)\n return res", "def levelorder(root):\n level = []\n q = []\n q.append(root)\n while q:\n rootnode = q.pop(0)\n level.append(rootnode.data)\n if rootnode.left is not None:\n q.append(rootnode.left)\n if rootnode.right is not None:\n q.append(rootnode.right)\n return level", "def levelorder(root):\n if root is None:\n return\n arr = []\n ans = []\n arr.append(root)\n while len(arr) > 0:\n ans.append(arr[0].data)\n node = arr.pop(0)\n if node.left is not None:\n arr.append(node.left)\n if node.right is not None:\n arr.append(node.right)\n return ans", "def levelorder(root):\n order = []\n queue = []\n queue.append(root)\n while len(queue) > 0:\n temp = queue.pop(0)\n order.append(temp.data)\n if temp.left:\n queue.append(temp.left)\n if temp.right:\n queue.append(temp.right)\n return order", "def levelorder(root):\n if root is None:\n return None\n lis = []\n stack = []\n stack.append(root)\n while len(stack) > 0:\n n = len(stack)\n for i in range(n):\n node = stack.pop(0)\n lis.append(node.data)\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n return lis", "def levelorder(root):\n l = []\n l.append(root)\n r = []\n while len(l) != 0:\n t = l.pop(0)\n r.append(t.data)\n if t.left != None:\n l.append(t.left)\n if t.right != None:\n l.append(t.right)\n return r", "def levelorder(root):\n ans = []\n s = []\n s.append(root)\n while len(s) != 0:\n curr = s.pop(0)\n ans.append(curr.data)\n if curr.left != None:\n s.append(curr.left)\n if curr.right != None:\n s.append(curr.right)\n return ans", "from collections import deque\n\ndef levelorder(root):\n if not root:\n return []\n Q = deque()\n Q.append(root)\n res = []\n while Q:\n curr = Q.popleft()\n res.append(curr.data)\n if curr.left:\n Q.append(curr.left)\n if curr.right:\n Q.append(curr.right)\n return res"], "starter_code": "def levelorder(root ):\n", "input_output": {"inputs": ["1\r\n / \\ \r\n 3 2", "10\r\n / \\\r\n 20 30\r\n / \\\r\n 40 60"], "outputs": ["1 3 2", "10 20 30 40 60"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/level-order-traversal/1", "Expected Auxiliary Space": "O(n)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(n)", "entry_point": "levelorder", "task_id": "TACO_lite/511", "example": [[], []]} +{"requirement": "Given a Binary Tree of size N, find all the nodes which don't have any sibling. You need to return a list of integers containing all the nodes that don't have a sibling in sorted order.\nNote: Root node can not have a sibling so it cannot be included in our answer.\nExample 1:\nInput :\n 37\n / \n 20\n / \n 113 \nOutput: 20 113\nExplanation: 20 and 113 dont have any siblings.\nExample 2:\nInput :\n 1\n / \\\n 2 3 \nOutput: -1\nExplanation: Every node has a sibling.\nYour Task: \nYou dont need to read input or print anything. Complete the function noSibling() which takes the root of the tree as input parameter and returns a list of integers containing all the nodes that don't have a sibling in sorted order. If all nodes have a sibling, then the returning list should contain only one element -1.\nExpected Time Complexity: O(NlogN)\nExpected Auxiliary Space: O(Height of the tree)\nConstraints:\n1 \u2264 N \u2264 10^4\nAll nodes have distinct values.", "solutions": ["def check(root, x):\n if root is None:\n return\n if root.left is None and root.right is not None:\n x.append(root.right.data)\n elif root.left is not None and root.right is None:\n x.append(root.left.data)\n check(root.left, x)\n check(root.right, x)\n\ndef noSibling(root):\n x = []\n check(root, x)\n if x:\n x.sort()\n return x\n return [-1]", "def noSibling(root):\n res = []\n\n def t(rt, re):\n if rt is None:\n return\n if rt.left is None and rt.right is not None:\n re.append(rt.right.data)\n elif rt.left is not None and rt.right is None:\n re.append(rt.left.data)\n t(rt.left, re)\n t(rt.right, re)\n t(root, res)\n if res:\n res.sort()\n return res\n else:\n return [-1]", "def noSibling(root):\n q = []\n ans = []\n if not root:\n return []\n q.append(root)\n while len(q) != 0:\n n = len(q)\n for i in range(n):\n node = q.pop(0)\n if node.left and (not node.right):\n ans.append(node.left.data)\n q.append(node.left)\n if node.right and (not node.left):\n ans.append(node.right.data)\n q.append(node.right)\n if node.left and node.right:\n q.append(node.left)\n q.append(node.right)\n if len(ans) == 0:\n return [-1]\n ans.sort()\n return ans", "def noSibling(root):\n queue = [root]\n ans = []\n while queue:\n node = queue.pop(0)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n if not node.left and node.right:\n ans.append(node.right.data)\n if node.left and (not node.right):\n ans.append(node.left.data)\n return list(sorted(ans)) if ans else [-1]", "from collections import deque\n\ndef noSibling(root):\n queue = deque()\n siblings = []\n queue.append(root)\n while queue:\n size = len(queue)\n for _ in range(size):\n node = queue.popleft()\n if node.left and node.right:\n queue.append(node.left)\n queue.append(node.right)\n elif node.left:\n queue.append(node.left)\n siblings.append(node.left.data)\n elif node.right:\n queue.append(node.right)\n siblings.append(node.right.data)\n return sorted(siblings) if len(siblings) > 0 else [-1]", "def noSiblingHelper(root, mylist):\n if root is None:\n return -1\n if root.left is not None and root.right is not None:\n noSiblingHelper(root.left, mylist)\n noSiblingHelper(root.right, mylist)\n elif root.left is not None and root.right is None:\n mylist.append(root.left.data)\n noSiblingHelper(root.left, mylist)\n elif root.left is None and root.right is not None:\n mylist.append(root.right.data)\n noSiblingHelper(root.right, mylist)\n if len(mylist) < 1:\n return -1\n return mylist\n\ndef noSibling(root):\n mylist = []\n ans = noSiblingHelper(root, mylist)\n x = []\n if ans == -1:\n x.append(-1)\n return x\n ans.sort()\n return ans", "def noSibling(root):\n out = []\n\n def traverse(root):\n if not root:\n return\n if root.left and (not root.right):\n out.append(root.left.data)\n if not root.left and root.right:\n out.append(root.right.data)\n traverse(root.left)\n traverse(root.right)\n traverse(root)\n return sorted(out) if out != [] else [-1]", "def noSibling(root):\n l = []\n\n def fun(root, l):\n if root is None:\n return\n if root.left is None and root.right is None:\n return\n if root.left is None and root.right is not None:\n l.append(root.right.data)\n fun(root.right, l)\n elif root.right is None and root.left is not None:\n l.append(root.left.data)\n fun(root.left, l)\n elif root.left is not None and root.right is not None:\n fun(root.left, l)\n fun(root.right, l)\n return l\n fun(root, l)\n if len(l) == 0:\n return [-1]\n return sorted(l)", "def noSibling(root):\n r = find(root, [])\n if r == []:\n return [-1]\n r.sort()\n return r\n\ndef find(root, res):\n if root == None:\n return res\n if root.left == None and root.right != None:\n res.append(root.right.data)\n if root.left != None and root.right == None:\n res.append(root.left.data)\n find(root.left, res)\n find(root.right, res)\n return res", "def noSibling(root):\n ans = []\n\n def preorder(root, ans):\n if root is None:\n return\n if root.left and root.right == None:\n ans.append(root.left.data)\n if root.right and root.left == None:\n ans.append(root.right.data)\n preorder(root.left, ans)\n preorder(root.right, ans)\n ans = []\n preorder(root, ans)\n ans.sort()\n if len(ans) == 0:\n return [-1]\n return ans", "def noSibling(root):\n ans = []\n\n def pre(root):\n if not root:\n return\n if root.right and (not root.left):\n ans.append(root.right.data)\n if not root.right and root.left:\n ans.append(root.left.data)\n pre(root.left)\n pre(root.right)\n pre(root)\n if len(ans) > 0:\n return sorted(ans)\n else:\n return [-1]", "def noSibling(root):\n\n def onlychild(root, v):\n if root is None:\n return\n onlychild(root.left, v)\n if root.left is None and root.right is not None:\n v.append(root.right.data)\n if root.left is not None and root.right is None:\n v.append(root.left.data)\n onlychild(root.right, v)\n v = []\n onlychild(root, v)\n v.sort()\n return v if len(v) > 0 else [-1]", "def noSibling(root):\n List = []\n\n def Transverse(root):\n if root == None:\n return\n if root.left == None and root.right != None:\n List.append(root.right.data)\n if root.left != None and root.right == None:\n List.append(root.left.data)\n Transverse(root.left)\n Transverse(root.right)\n Transverse(root)\n if List == []:\n return [-1]\n else:\n List.sort()\n return List", "def noSibling(root):\n ans = []\n if root == None:\n return [-1]\n queue = []\n queue.append(root)\n while len(queue) != 0:\n temp = queue.pop(0)\n if temp.left != None and temp.right == None:\n ans.append(temp.left.data)\n if temp.right != None and temp.left == None:\n ans.append(temp.right.data)\n if temp.left != None:\n queue.append(temp.left)\n if temp.right != None:\n queue.append(temp.right)\n if len(ans) == 0:\n return [-1]\n ans.sort()\n return ans", "def fun(root, l):\n if root == None:\n return\n elif root.left == None and root.right != None:\n l.append(root.right.data)\n elif root.left != None and root.right == None:\n l.append(root.left.data)\n fun(root.left, l)\n fun(root.right, l)\n\ndef noSibling(root):\n l = []\n fun(root, l)\n if len(l) == 0:\n l.append(-1)\n else:\n l.sort()\n return l", "def noSiblingUtil(root):\n global ans\n if root is None:\n return\n elif root.right is None and root.left is None:\n return\n elif root.left is None:\n ans.append(root.right.data)\n noSiblingUtil(root.right)\n elif root.right is None:\n ans.append(root.left.data)\n noSiblingUtil(root.left)\n else:\n noSiblingUtil(root.left)\n noSiblingUtil(root.right)\n return\n\ndef noSibling(root):\n global ans\n ans = []\n ans.clear()\n noSiblingUtil(root)\n if len(ans) == 0:\n ans.append(-1)\n ans.sort()\n return ans", "def noSibling(root):\n\n def no(root, l):\n if root == None:\n return l\n no(root.left, l)\n if root.left != None and root.right == None:\n l.append(root.left.data)\n if root.right != None and root.left == None:\n l.append(root.right.data)\n no(root.right, l)\n l = []\n no(root, l)\n l.sort()\n if len(l) == 0:\n return [-1]\n return l", "def paths(root, ans):\n if not root:\n return\n if root.left and (not root.right):\n ans.append(root.left.data)\n if not root.left and root.right:\n ans.append(root.right.data)\n paths(root.left, ans)\n paths(root.right, ans)\n return\n\ndef noSibling(root):\n ans = []\n paths(root, ans)\n if ans == []:\n return [-1]\n ans.sort()\n return ans", "def noSibling(root):\n res = []\n\n def helper(root):\n if root == None:\n return\n if root.left != None and root.right == None:\n res.append(root.left.data)\n if root.right != None and root.left == None:\n res.append(root.right.data)\n helper(root.left)\n helper(root.right)\n helper(root)\n res.sort()\n return res if len(res) > 0 else [-1]", "def noSibling(root):\n l = []\n\n def s(root):\n if root:\n if root.left and (not root.right):\n l.append(root.left.data)\n if not root.left and root.right:\n l.append(root.right.data)\n if root.left:\n s(root.left)\n if root.right:\n s(root.right)\n s(root.left)\n s(root.right)\n l.sort()\n if l:\n return l\n return [-1]\n return []", "def get(root, li):\n if not root:\n return\n if root.left and root.right:\n pass\n elif root.left:\n li.append(root.left.data)\n elif root.right:\n li.append(root.right.data)\n get(root.left, li)\n get(root.right, li)\n\ndef noSibling(root):\n li = []\n get(root, li)\n if len(li) == 0:\n return [-1]\n else:\n li.sort()\n return li", "def noSibling(root):\n res = []\n\n def dfs(node):\n if not node:\n return\n if node.left and (not node.right):\n res.append(node.left.data)\n elif node.right and (not node.left):\n res.append(node.right.data)\n dfs(node.left)\n dfs(node.right)\n dfs(root)\n res.sort()\n if res:\n return res\n return [-1]", "def noSibling(root):\n l = []\n if not root:\n return [-1]\n if root.left and root.right:\n l += noSibling(root.left)\n l += noSibling(root.right)\n elif root.left and (not root.right):\n l.append(root.left.data)\n l += noSibling(root.left)\n elif root.right and (not root.left):\n l.append(root.right.data)\n l += noSibling(root.right)\n if not l:\n return [-1]\n else:\n l.sort()\n for i in l:\n if i == -1:\n l.remove(-1)\n return l", "def noSibling(root):\n if root is None:\n return []\n (queue, a, k) = ([root], [], 0)\n while len(queue) > 0:\n k = len(queue)\n for _ in range(k):\n s = queue[0]\n if s.left and (not s.right):\n a.append(s.left.data)\n queue.append(s.left)\n if s.right and (not s.left):\n a.append(s.right.data)\n queue.append(s.right)\n if s.left and s.right:\n queue.append(s.left)\n queue.append(s.right)\n queue.pop(0)\n if len(a) == 0:\n return [-1]\n a.sort()\n return a", "def solve(root, lis):\n if root == None:\n return\n if root.left != None and root.right == None:\n lis.append(root.left.data)\n if root.left == None and root.right != None:\n lis.append(root.right.data)\n solve(root.left, lis)\n solve(root.right, lis)\n\ndef noSibling(root):\n lis = []\n k = root\n solve(root, lis)\n if not lis:\n return [-1]\n lis.sort()\n return lis", "def noSibling(root):\n q = [root]\n res = []\n while q:\n k = q.pop(0)\n if k.left and (not k.right):\n res.append(k.left.data)\n if not k.left and k.right:\n res.append(k.right.data)\n if k.right:\n q.append(k.right)\n if k.left:\n q.append(k.left)\n if not res:\n return [-1]\n res.sort()\n return res", "def noSibling(root):\n q = [root]\n res = []\n while q:\n l = len(q)\n for i in range(l):\n k = q.pop()\n if k.left and (not k.right):\n res.append(k.left.data)\n if not k.left and k.right:\n res.append(k.right.data)\n if k.right:\n q.append(k.right)\n if k.left:\n q.append(k.left)\n if not res:\n return [-1]\n res.sort()\n return res", "def noSibling(root):\n ans = []\n\n def help(root):\n if root == None:\n return\n if root.left and (not root.right):\n ans.append(root.left.data)\n if root.right and (not root.left):\n ans.append(root.right.data)\n help(root.left)\n help(root.right)\n help(root)\n return sorted(ans) if ans else [-1]", "def noSibling(root):\n ns = []\n\n def trav(r):\n if r.left is not None:\n if r.right is None:\n ns.append(r.left.data)\n trav(r.left)\n else:\n trav(r.left)\n if r.right is not None:\n if r.left is None:\n ns.append(r.right.data)\n trav(r.right)\n else:\n trav(r.right)\n trav(root)\n if len(ns) == 0:\n return [-1]\n return sorted(ns)"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["37\n / \n 20\n / \n 113", "1\n / \\\n 2 3"], "outputs": ["20 113", "-1"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/print-all-nodes-that-dont-have-sibling/1", "Expected Auxiliary Space": "O(Height of the tree)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(NlogN)", "entry_point": "__init__", "task_id": "TACO_lite/513", "example": [[], []]} +{"requirement": "Given a Binary Tree of size N, You have to count leaves in it. For example, there are two leaves in following tree\n 1\n / \\\n 10 39\n /\n5\n \nExample 1:\nInput:\nGiven Tree is \n 4\n / \\\n 8 10\n / / \\\n 7 5 1\n /\n 3 \nOutput:\n3\nExplanation: \nThree leaves are 3 , 5 and 1.\n \nYour Task:\nYou don't have to take input. Complete the function countLeaves() that takes root node of the given tree as parameter and returns the count of leaves in tree. The printing is done by the driver code.\n \nConstraints:\n1<= N <= 10^{4}", "solutions": ["def countLeaves(root):\n i = 0\n\n def rec(root):\n nonlocal i\n if root:\n if root.left is None and root.right is None:\n i += 1\n rec(root.right)\n rec(root.left)\n rec(root)\n return i", "def countLeaves(root):\n if root is None:\n return 0\n if root.left is None and root.right is None:\n return 1\n else:\n return countLeaves(root.left) + countLeaves(root.right)", "def countLeaves(root):\n if root.left == None and root.right == None:\n return 1\n q = []\n q.append(root)\n ans = 0\n while len(q) > 0:\n top = q.pop(0)\n if top.left is not None:\n q.append(top.left)\n if top.right is not None:\n q.append(top.right)\n if top.left is None and top.right is None:\n ans += 1\n return ans", "def countLeaves(root):\n global ans\n ans = [0]\n\n def in_order(root):\n if root and root.left:\n in_order(root.left)\n if root and (not root.left) and (root.right == None):\n ans[0] = ans[0] + 1\n if root and root.right:\n in_order(root.right)\n return\n in_order(root)\n return ans[0]", "def countLeaves(root):\n if root == None:\n return 0\n if root.left == None and root.right == None:\n return 1\n return countLeaves(root.left) + countLeaves(root.right)", "def countLeaves(root):\n if not root:\n return 0\n if not root.left and (not root.right):\n return 1\n left = 0\n right = 0\n if root.left:\n left = countLeaves(root.left)\n if root.right:\n right = countLeaves(root.right)\n return left + right", "def countLeaves(root):\n count = 0\n if root is None:\n return 0\n elif root.left is None and root.right is None:\n count = 1\n return count + countLeaves(root.left) + countLeaves(root.right)", "def countLeaves(root):\n leaf = 0\n if root is None:\n return 0\n if root.left is None and root.right is None:\n leaf += 1\n lleaf = countLeaves(root.left)\n rleaf = countLeaves(root.right)\n return lleaf + rleaf + leaf", "def countLeaves(root):\n q = []\n q.append(root)\n count = 0\n while q:\n for x in range(0, len(q)):\n cur = q[0]\n q.remove(cur)\n if cur.left:\n q.append(cur.left)\n if cur.right:\n q.append(cur.right)\n if not cur.left and (not cur.right):\n count += 1\n return count", "def countLeaves(root):\n a = []\n leaves = 0\n\n def rec(root):\n nonlocal leaves\n if root:\n rec(root.left)\n a.append(root.data)\n if root.left == None and root.right == None:\n leaves += 1\n rec(root.right)\n rec(root)\n return leaves", "def countLeaves(root):\n queue = [root]\n ans = 0\n while queue:\n node = queue.pop(0)\n if not node.left and (not node.right):\n ans += 1\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return ans", "def countLeaves(root):\n\n def tree(node):\n if not node.right and (not node.left):\n return 1\n elif node.right and node.left:\n return tree(node.right) + tree(node.left)\n elif node.right:\n return tree(node.right)\n else:\n return tree(node.left)\n return tree(root)", "def countLeaves(root):\n leaf_nodes = 0\n\n def helper(root):\n if root is None:\n return 0\n left_nodes = helper(root.left)\n right_nodes = helper(root.right)\n if root.left is None and root.right is None:\n return 1\n return left_nodes + right_nodes\n return helper(root)", "def countLeaves(root):\n stack = [root]\n answer = 0\n while stack:\n node = stack.pop()\n if node.right:\n stack.append(node.right)\n if node.left:\n stack.append(node.left)\n if not node.right and (not node.left):\n answer += 1\n return answer", "def count(root, res):\n if root is None:\n return\n if root.left is None and root.right is None:\n res.append(root.data)\n if root:\n count(root.left, res)\n count(root.right, res)\n\ndef countLeaves(root):\n res = []\n count(root, res)\n return len(res)", "def cl(root):\n if root == None:\n return\n global h\n if root.left == None and root.right == None:\n h += 1\n cl(root.left)\n cl(root.right)\n\ndef countLeaves(root):\n if root == None:\n return 0\n if root.left == None and root.right == None:\n return 1\n return countLeaves(root.left) + countLeaves(root.right)", "def traverseLeaves(root, count):\n if root == None:\n return count\n if root.left == None and root.right == None:\n return count + 1\n count = traverseLeaves(root.left, count)\n count = traverseLeaves(root.right, count)\n return count\n\ndef countLeaves(root):\n if root == None:\n return 0\n return traverseLeaves(root, 0)", "def countLeaves(root):\n if root == None:\n return 0\n l = countLeaves(root.left)\n r = countLeaves(root.right)\n if root.left == None and root.right == None:\n return l + r + 1\n else:\n return l + r", "def countLeaves(root):\n count = 0\n flagLeft = False\n flagRight = False\n if not root.left == None:\n count += countLeaves(root.left)\n else:\n flagLeft = True\n if not root.right == None:\n count += countLeaves(root.right)\n else:\n flagRight = True\n if flagLeft and flagRight:\n count += 1\n return count", "def countLeaves(root):\n\n def dfs(node):\n if not node:\n return 0\n if not (node.left or node.right):\n return 1\n return dfs(node.left) + dfs(node.right)\n return dfs(root)", "def countLeaves(root):\n if not root:\n return 0\n if not (root.left or root.right):\n return 1\n return countLeaves(root.left) + countLeaves(root.right)", "count = 0\n\ndef countLeaves(root):\n if not root:\n return 0\n elif not root.left and (not root.right):\n return 1\n else:\n return countLeaves(root.right) + countLeaves(root.left)", "def countLeaves(root):\n return __countLeaves(root)\n\ndef __countLeaves(node):\n if node == None:\n return 0\n if node.right == None and node.left == None:\n return 1\n return __countLeaves(node.right) + __countLeaves(node.left)", "def countLeaves(root):\n count = [0]\n\n def counting(node):\n if not node.left and (not node.right):\n count[0] += 1\n return\n if node.left:\n counting(node.left)\n if node.right:\n counting(node.right)\n counting(root)\n return count[0]", "def countLeaves(root):\n\n def h(root):\n if not root:\n return 0\n if not root.left and (not root.right):\n return 1\n a = h(root.left)\n b = h(root.right)\n return a + b\n return h(root)", "def countLeaves(root):\n from collections import deque\n q = deque()\n q.append(root)\n count = 0\n while q:\n current = q.popleft()\n if current.left is None and current.right is None:\n count += 1\n if current.left:\n q.append(current.left)\n if current.right:\n q.append(current.right)\n return count", "def countLeaves(root):\n leaves_left = 0\n leaves_right = 0\n if root.left:\n leaves_left = countLeaves(root.left)\n if root.right:\n leaves_right = countLeaves(root.right)\n if not root.left and (not root.right):\n return 1\n return leaves_left + leaves_right", "def countLeaves(root):\n if root == None:\n return 0\n elif root.left == None and root.right == None:\n return 1\n else:\n ls = countLeaves(root.left)\n rs = countLeaves(root.right)\n return ls + rs", "def countLeaves(root):\n stack = [root]\n count = 0\n while stack:\n root = stack.pop()\n if not root.left and (not root.right):\n count += 1\n if root.right:\n stack.append(root.right)\n if root.left:\n stack.append(root.left)\n return count", "def countLeaves(root):\n if root.left == None and root.right == None:\n return 0\n global c\n c = 0\n\n def helper(root):\n global c\n if root == None:\n return\n if root.left == None and root.right == None:\n c += 1\n return\n helper(root.left)\n helper(root.right)\n helper(root)\n return c", "def fun(root, c):\n if root == None:\n return 0\n l = fun(root.left, c)\n r = fun(root.right, c)\n if l == 0 and r == 0:\n c.append(1)\n\ndef countLeaves(root):\n c = []\n fun(root, c)\n return sum(c)", "def countLeaves(root):\n level = [root]\n leaves = []\n while level:\n next = []\n for node in level:\n if node.right:\n next.append(node.right)\n if node.left:\n next.append(node.left)\n elif node.right == None:\n leaves.append(node)\n level = next\n return len(leaves)", "def countLeaves(root):\n tot = 0\n\n def count(node):\n nonlocal tot\n if node is None:\n return\n if not node.left and (not node.right):\n tot += 1\n count(node.left)\n count(node.right)\n count(root)\n return tot"], "starter_code": "def __init__(val):\n", "input_output": {"inputs": ["Given Tree is \r\n 4\r\n / \\\r\n 8 10\r\n / / \\\r\n 7 5 1\r\n /\r\n 3"], "outputs": ["3"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Tree"], "name": null, "source": "geeksforgeeks", "tags": ["Tree algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/count-leaves-in-binary-tree/1", "Expected Auxiliary Space": "", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "", "entry_point": "__init__", "task_id": "TACO_lite/472", "example": [[], []]} +{"requirement": "Description:\n\n#Task:\n\nWrite a function that returns true if the number is a \"Very Even\" number.\n\nIf a number is a single digit, then it is simply \"Very Even\" if it itself is even.\n\nIf it has 2 or more digits, it is \"Very Even\" if the sum of it's digits is \"Very Even\".\n\n\n#Examples:\n```\ninput(88) => returns false -> 8 + 8 = 16 -> 1 + 6 = 7 => 7 is odd \n\ninput(222) => returns true\n\ninput(5) => returns false\n\ninput(841) => returns true -> 8 + 4 + 1 = 13 -> 1 + 3 => 4 is even\n```\n\nNote: The numbers will always be 0 or positive integers!", "solutions": ["def is_very_even_number(n):\n while len(str(n)) > 1:\n n = sum((int(x) for x in str(n)))\n return True if n % 2 == 0 else False", "def is_very_even_number(n):\n return n == 0 or (n - 1) % 9 % 2", "def is_very_even_number(n):\n if n < 10:\n return n % 2 == 0\n return is_very_even_number(sum((int(d) for d in str(n))))", "def get_sum(x):\n return sum((int(t) for t in list(str(x))))\n\ndef is_very_even_number(n):\n result = get_sum(n)\n while len(str(result)) >= 2:\n result = get_sum(result)\n return result % 2 == 0", "def is_very_even_number(n):\n return is_very_even_number(sum((int(i) for i in str(n)))) if n > 9 else not n % 2", "def is_very_even_number(n):\n while n >= 10:\n (p, n) = (n, 0)\n while p > 0:\n re = p % 10\n n += re\n p //= 10\n return n % 2 == 0", "def is_very_even_number(n):\n if len(str(n)) == 1:\n return n % 2 == 0\n return is_very_even_number(sum(map(int, list(str(n)))))", "def is_very_even_number(n):\n while n >= 10:\n n = sum(map(int, str(n)))\n return n % 2 == 0", "def is_very_even_number(n):\n if n < 10:\n return n % 2 == 0\n return is_very_even_number(sum(map(int, str(n))))", "def is_very_even_number(n):\n return True if not n else all((not n % 9 % 2, n % 9))"], "starter_code": "def is_very_even_number(n):\n", "input_output": {"fn_name": "is_very_even_number", "inputs": [], "outputs": []}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/58c9322bedb4235468000019", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_very_even_number", "task_id": "TACO_lite/535", "example": [[], []]} +{"requirement": "Given an integer, check whether it is Bleak or not. \nA number n is called Bleak if it can be represented as sum of a positive number x and set bit count in x, i.e., x + countSetBits(x) is not equal to n for any non-negative number x.\nExample 1:\nInput: 4\nOutput: 1\nExplanation: There is no any possible x\nsuch that x + countSetbit(x) = 4\nExample 2:\nInput: 3\nOutput: 0\nExplanation: 3 is a Bleak number as \n2 + countSetBit(2) = 3.\n \nYour Task:\nYou don't need to read or print anything. Your task is to complete the function is_bleak() which takes n as input parameter and returns 1 if n is not a Bleak number otherwise returns 0.\n \nExpected Time Complexity: O(log(n) * log(n))\nExpected Space Complexity: O(1)\n \nConstraints:\n1 <= n <= 10^{4}", "solutions": ["def count_set_bits(n):\n ret = 0\n while n:\n if n & 1:\n ret += 1\n n >>= 1\n return ret\n\ndef is_bleak(n):\n a = 0\n for j in range(14, -1, -1):\n if n > j:\n a = j\n break\n for m in range(n - a, n):\n if count_set_bits(m) + m == n:\n return 0\n return 1", "def is_bleak(n):\n for x in range(n):\n cb = bin(x).count('1')\n if x + cb == n:\n return 0\n return 1", "def is_bleak(n):\n if n in self.d:\n return 0\n return 1", "def is_bleak(n):\n from math import log2, ceil\n for i in range(1, ceil(log2(10 ** 4)) + 1):\n (v, cnt) = (n - i, 0)\n while v > 0:\n v &= v - 1\n cnt += 1\n if cnt == i:\n return 0\n return 1", "def is_bleak(n):\n\n def f(a):\n cnt = 0\n while a > 0:\n cnt += 1\n a = a & a - 1\n return cnt\n for i in range(n - 32, n):\n if f(i) + i == n:\n return 0\n return 1", "import re\n\ndef is_bleak(n):\n for i in range(n):\n bi = str(bin(i))\n no_of_1 = bi.count('1')\n if no_of_1 + i == n:\n return 0\n return 1", "def is_bleak(n):\n m = len(bin(n)[2:])\n for i in range(1, m + 1):\n if sum((item == '1' for item in bin(n - i)[2:])) == i:\n return 0\n return 1", "def countSetBits(x):\n count = 0\n while x:\n x = x & x - 1\n count = count + 1\n return count\n\ndef ceilLog2(x):\n count = 0\n x = x - 1\n while x > 0:\n x = x >> 1\n count = count + 1\n return count\n\ndef is_bleak(n):\n for x in range(n - self.ceilLog2(n), n):\n if x + self.countSetBits(x) == n:\n return 0\n return 1", "from math import log, ceil\n\ndef countset(x):\n count = 0\n while x:\n x = x & x - 1\n count = count + 1\n return count\n\ndef is_bleak(n):\n cei = ceil(log(n, 2))\n for i in range(n - cei, n):\n if i + countset(i) == n:\n return 0\n return 1", "from math import log\n\ndef count(n):\n c = 0\n while n:\n c += 1\n n &= n - 1\n return c\n\ndef is_bleak(n):\n cn = n - len(bin(n)[2:])\n for x in range(cn, n + 1):\n if x + self.count(x) == n:\n return 0\n return 1", "def is_bleak(n):\n for i in range(1, n):\n x = bin(i)[2:].count('1')\n if i + x == n:\n return 0\n return 1", "import math\n\ndef is_bleak(n):\n count = 0\n tmp = n\n while n > 0:\n n >>= 1\n count += 1\n i = tmp - count\n while i < tmp:\n if i + self.countbits(i) == tmp:\n return 0\n i += 1\n return 1\n\ndef countbits(n):\n count = 0\n while n > 0:\n n = n & n - 1\n count += 1\n return count", "def is_bleak(n):\n for i in range(n - 32, n, 1):\n if i > 0 and n - i > 0 and (bin(i).count('1') == n - i):\n return 0\n return 1", "def setb(n):\n return bin(n).count('1')\n\ndef is_bleak(n):\n for i in range(1, n):\n if i + setb(i) == n:\n return 0\n return 1", "def countSetBits(num):\n count = 0\n while num > 0:\n mask = num - 1\n num &= mask\n count += 1\n return count\n\ndef is_bleak(n):\n for ele in range(n):\n if ele + countSetBits(ele) == n:\n return 0\n else:\n return 1", "def total_bits(m):\n res = 0\n while m:\n res += 1\n m //= 2\n return res\n\ndef set_bits(m):\n res = 0\n while m:\n res += m % 2\n m //= 2\n return res\n\ndef is_bleak(n):\n for num in range(max(n - self.total_bits(n), 1), n):\n if num + self.set_bits(num) == n:\n return 0\n return 1", "def is_bleak(n):\n dp = [0] * (n + 1)\n for i in range(1, n):\n if i % 2:\n dp[i] = dp[i - 1] + 1\n else:\n dp[i] = dp[i // 2]\n if i + dp[i] == n:\n return 0\n return 1", "from collections import Counter\n\ndef is_bleak(n):\n for i in range(n):\n if bin(i).count('1') + i == n:\n return 0\n return 1", "def is_bleak(n):\n for d in range(n // 2, n):\n count = 0\n x = d\n while d > 0:\n if d & (d & -d) > 0:\n count += 1\n d = d - (d & -d)\n if x + count == n:\n return 0\n return 1", "def countBits(n):\n c = 0\n while n:\n n &= n - 1\n c += 1\n return c\n\ndef is_bleak(n):\n for i in range(n - 1, 0, -1):\n if i + self.countBits(i) == n:\n return 0\n return 1", "def count_set_bits(x):\n set_bits = 0\n while x:\n set_bits += 1\n x = x & x - 1\n return set_bits\n\ndef is_bleak(n):\n x = max(1, n - self.num_bits)\n while x < n:\n if x + self.count_set_bits(x) == n:\n return 0\n x += 1\n return 1", "def count_set(x):\n count = 0\n while x:\n count += x & 1\n x >>= 1\n return count\n\ndef is_bleak(n):\n for i in range(n, 0, -1):\n if i + self.count_set(i) == n:\n return 0\n return 1", "def is_bleak(n):\n for _ in range(n):\n flag = 0\n if n > 14:\n s = n - 14\n else:\n s = 1\n for i in range(s, n):\n if i + bin(i)[2:].count('1') == n:\n flag = 1\n break\n if flag:\n return 0\n else:\n return 1", "def is_bleak(n):\n c = 1\n for i in range(n):\n if i + bin(i).count('1') == n:\n c = 0\n break\n return c", "def setBits(N):\n cnt = 0\n while N != 0:\n N = N & N - 1\n cnt += 1\n return cnt\n\ndef is_bleak(n):\n for i in range(1, n):\n b = self.setBits(i) + i\n if b == n:\n return 0\n return 1", "def is_bleak(n):\n dp = [0] * (10 ** 4 + 1)\n dp[1] = 1\n dp[2] = 1\n dp[3] = 2\n for i in range(n):\n dp[i] = dp[i // 2]\n if i % 2:\n dp[i] += 1\n for i in range(n):\n if i + dp[i] == n:\n return 0\n return 1", "import math\n\ndef countSetBits(x):\n bi = bin(x)[2:]\n bi = [int(x) for x in str(bi)]\n ones = bi.count(1)\n return ones\n\ndef ceilLog2(x):\n count = 0\n x -= 1\n while x > 0:\n x = x >> 1\n count += 1\n return count\n\ndef is_bleak(n):\n for x in range(n - self.ceilLog2(n), n):\n if x + self.countSetBits(x) == n:\n return 0\n return 1", "def countSetBits(x):\n k = bin(x).replace('b', '')\n return k.count('1')\n\ndef is_bleak(n):\n for x in range(n):\n if self.countSetBits(x) + x == n:\n return 0\n return 1", "def is_bleak(n):\n z = n\n c = 0\n while z > 0:\n z = z // 2\n c = c + 1\n mina = n - c\n for i in range(n - c, n):\n z = i\n sb = 0\n while z > 0:\n a = z % 2\n z = z // 2\n if a == 1:\n sb = sb + 1\n if sb + i == n:\n return 0\n return 1", "def csb(n):\n b = bin(n).replace('b', '')\n return b.count('1')\n\ndef is_bleak(n):\n if n == 1:\n return 1\n for i in range(n):\n if i + csb(i) == n:\n return 0\n return 1", "def is_bleak(n):\n for i in range(n - 1, 0, -1):\n if i + self.count(i) == n:\n return 0\n return 1\n\ndef count(n):\n cont = 0\n while n:\n cont += n & 1\n n >>= 1\n return cont", "def is_bleak(n):\n for i in range(n - 1, 0, -1):\n c = 0\n t = i\n while t > 0:\n t = t & t - 1\n c += 1\n x1 = c\n if n == x1 + i:\n return 0\n return 1", "def setbit(i):\n c = 0\n while i:\n i = i & i - 1\n c += 1\n return c\n\ndef is_bleak(n):\n for j in range(n - 1, 0, -1):\n a = self.setbit(j)\n if n - a == j:\n return 0\n return 1", "def countSetBits(n):\n if self.table[n] != -1:\n return self.table[n]\n set_bits = 0\n while n:\n if n & 1:\n set_bits += 1\n n = n >> 1\n self.table[n] = set_bits\n return set_bits\n\ndef is_bleak(n):\n for i in range(n - 1, 0, -1):\n set_bits = 0\n if self.table[i] != -1:\n set_bits = self.table[i]\n else:\n y = i\n while y:\n if y & 1:\n set_bits += 1\n y = y >> 1\n self.table[y] = set_bits\n if i + set_bits == n:\n return 0\n return 1", "def is_bleak(n):\n a = 1\n i = 1\n while a < n:\n a *= 2\n i += 1\n for x in range(n - i, n):\n if x + self.countSetBits(x) == n:\n return 0\n return 1\n\ndef countSetBits(x):\n count = 0\n while x > 0:\n x &= x - 1\n count += 1\n return count", "def is_bleak(n):\n low = 0\n high = n\n for i in range(n, 0, -1):\n count = 0\n mask = 1\n num = i\n while num:\n if num & mask == 1:\n count += 1\n num >>= 1\n if i + count == n:\n return 0\n else:\n return 1", "def is_bleak(n):\n\n def findBits(x):\n cnt = 0\n while x:\n x = x & x - 1\n cnt += 1\n return cnt\n for i in range(1, n + 1):\n if i + findBits(i) == n:\n return 0\n return 1", "def is_bleak(n):\n (l, r) = (1, n)\n for i in range(1, n + 1):\n if i + self.countSetBits(i) == n:\n return 0\n return 1\n\ndef countSetBits(num):\n cnt = 0\n while num != 0:\n num = num & num - 1\n cnt += 1\n return cnt", "def is_bleak(n):\n\n def countSetbit(n):\n count = 0\n while n:\n count += n & 1\n n >>= 1\n return count\n a = n - 17\n m = 1\n for i in range(a, n):\n if i > 0 and i + countSetbit(i) == n:\n m = 0\n break\n return m", "import math\n\ndef countSetBits(x):\n r = str(format(x, 'b')).count('1')\n return r\n\ndef is_bleak(n):\n for i in range(1, n):\n if i + countSetBits(i) == n:\n return 0\n return 1", "def is_bleak(n):\n if n == 1:\n return 1\n else:\n for i in range(n - 1, 0, -1):\n t = i\n count = 0\n while t > 0:\n t = t & t - 1\n count = count + 1\n if count + i == n:\n return 0\n return 1", "import math\n\ndef set_bits(abc, num):\n count = 0\n while num > 0:\n if num % 2 == 1:\n count += 1\n num >>= 1\n return count\n\ndef is_bleak(n):\n check = math.ceil(math.log(n, 2))\n for i in range(n - check, n):\n if i + Solution().set_bits(i) == n:\n return 0\n return 1", "def check(x):\n cnt = 0\n while x:\n x = x & x - 1\n cnt += 1\n return cnt\n\ndef is_bleak(n):\n if n == 1:\n return 1\n ans = 1\n for i in range(1, n):\n if i + self.check(i) == n:\n ans = 0\n break\n return ans", "def is_bleak(n):\n flag = 1\n for i in range(n, 0, -1):\n b = self.setbit(i) + i\n if b == n:\n flag = 0\n break\n return flag\n\ndef setbit(n):\n count = 0\n while n > 0:\n if n & 1:\n count += 1\n n = n >> 1\n return count", "def is_bleak(n):\n for i in range(1, n + 1):\n x = i\n z = bin(i).replace('0b', '')\n x1 = z.count('1')\n if int(x1) + x == n:\n return 0\n else:\n return 1", "def set_bits(n):\n bin_num = bin(n).replace('Ob', '')\n set_bits = str(bin_num).count('1')\n return set_bits\n\ndef is_bleak(n):\n for i in range(n):\n if i + self.set_bits(i) == n:\n return 0\n return 1", "def sol(num):\n ans = 0\n while num:\n num = num & num - 1\n ans = ans + 1\n return ans\n\ndef is_bleak(n):\n for i in range(1, n):\n if i + self.sol(i) == n:\n return 0\n return 1", "def is_bleak(n):\n\n def countSetbit(mid):\n count = 0\n while mid:\n mid = mid & mid - 1\n count += 1\n return count\n for i in range(1, n):\n count = countSetbit(i)\n if count + i == n:\n return 0\n return 1"], "starter_code": "def is_bleak(n):\n", "input_output": {"inputs": ["4", "3"], "outputs": ["1", "0"]}, "difficulty": "MEDIUM", "raw_tags": ["Data Structures", "Bit Magic"], "name": null, "source": "geeksforgeeks", "tags": ["Bit manipulation", "Data structures"], "skill_types": ["Bit manipulation", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/bleak-numbers1552/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(log(n) * log(n))", "entry_point": "is_bleak", "task_id": "TACO_lite/477", "example": [[[4], [3]], ["1", "0"]]} +{"requirement": "Convert a given string to its cross string (i.e Diagonal from left-right and from right-left). \nSee examples for better understanding.\n \nExample 1:\nInput:\nabc\nOutput:\na c b a c\nExplanation:\nThe above is the proper \ncross manner for the \ntest case.\na c\n b \na c\nExample 2:\nInput:\ngeeks\nOutput:\ng s e k e e k g s\nExplanation:\nFor the 1st test case where \nthe string is geeks\nG S\n E K\n E\n E K\nG S\nThe above is the proper cross \nthe manner for the test case, but \nwhen printed in a single line \nit becomes as shown in the output.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function crossPattern() which takes the string S and returns a single string in the following way first-line output of the string concatenated with 2nd line and so on till the Nth line.\n \nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n \nConstraints:\n1 \u2264 length of string \u2264 1000", "solutions": ["def crosspattern(ob, S):\n start = ''\n end = ''\n n = len(S)\n for i in range(n // 2):\n row = i * ' ' + S[i] + (n - 2 * (i + 1)) * ' ' + S[-i - 1] + i * ' '\n start += row\n end = row + end\n if n % 2:\n start += n // 2 * ' ' + S[n // 2] + n // 2 * ' '\n return start + end", "def crosspattern(ob, S):\n len1 = len(S)\n ans = ''\n for i in range(0, len1):\n j = len1 - 1 - i\n for k in range(0, len1):\n if k == i or k == j:\n ans += S[k]\n else:\n ans += ' '\n return ans", "import math\n\ndef crosspattern(ob, S):\n result = []\n s = S\n size = len(s)\n iterate = math.ceil(size / 2)\n for i in range(iterate):\n result.append(' ' * i)\n result.append(s[i])\n result.append(' ' * (size - i - 1 - i - 1))\n if i != size - i - 1:\n result.append(s[size - i - 1])\n result.append(' ' * i)\n else:\n result.append(' ' * i)\n if size % 2 != 0:\n iterate = iterate - 1\n for i in reversed(range(iterate)):\n result.append(' ' * i)\n result.append(s[i])\n result.append(' ' * (size - i - 1 - i - 1))\n if i != size - i - 1:\n result.append(s[size - i - 1])\n result.append(' ' * i)\n else:\n result.append(' ' * i)\n return ''.join(result)", "def crosspattern(ob, S):\n start = 0\n end = len(S) - 1\n ans = []\n for i in range(len(S)):\n for j in range(len(S)):\n if j == start:\n ans.append(S[start])\n elif j == end:\n ans.append(S[j])\n else:\n ans.append(' ')\n start += 1\n end -= 1\n return ''.join(ans)", "def crosspattern(ob, S):\n i = 0\n n = len(S)\n t = ''\n while i < n:\n l = [' ' for j in range(n)]\n l[i] = S[i]\n l[n - 1 - i] = S[n - 1 - i]\n t += ''.join(l)\n i += 1\n return t", "def crosspattern(ob, ip):\n s = ''\n for i in range(len(ip)):\n result = ''\n for j in range(len(ip)):\n if i == j:\n result = result + ip[i]\n elif j == len(ip) - i - 1:\n result = result + ip[j]\n else:\n result = result + ' '\n s += result\n return s", "def crosspattern(ob, s):\n a = ''\n for i in range(len(s)):\n for j in range(len(s)):\n if i == j or i + j == len(S) - 1:\n a = a + s[j]\n else:\n a = a + ' '\n return a", "def crosspattern(ob, S):\n n = len(S)\n t = ''\n m = [[' ' for j in range(n)] for i in range(n)]\n l = 0\n h = n - 1\n for i in range(n):\n for j in range(n):\n if i == j:\n m[i][j] = S[l]\n l += 1\n if i + j + 1 == n:\n m[i][j] = S[h]\n h -= 1\n for i in range(n):\n for j in range(n):\n t += m[i][j]\n return t", "def crosspattern(ob, S):\n string = ''\n for i in range(0, len(S)):\n for j in range(0, len(S)):\n if i == j or i + j == len(S) - 1:\n string += S[j]\n else:\n string += ' '\n return string", "def crosspattern(ob, S):\n dp = [[' ' for i in range(len(S))] for j in range(len(S))]\n for i in range(len(S)):\n dp[i][i] = S[i]\n (start, end) = (len(S) - 1, 0)\n while start != -1 and end != len(S):\n dp[start][end] = S[end]\n end += 1\n start -= 1\n ans = ''\n for i in dp:\n ans += ''.join(i)\n return ans", "def crosspattern(ob, S):\n l = []\n for i in range(1, len(S) + 1):\n for j in range(1, len(S) + 1):\n if i == j or i + j == len(S) + 1:\n l.append(S[j - 1])\n else:\n l.append(' ')\n return ''.join(l)", "def crosspattern(ob, S):\n n = len(S)\n res = ''\n for i in range(n):\n for j in range(n):\n if i == j or i + j == n - 1:\n res += S[j]\n else:\n res += ' '\n return res", "def crosspattern(ob, s):\n n = len(s)\n res = [[' '] * n for i in range(n)]\n ans = ''\n for i in range(n):\n res[i][i] = res[n - 1 - i][i] = s[i]\n for i in res:\n ans += ''.join(i)\n return ans", "def crosspattern(ob, s):\n n = len(s)\n m = ''\n for i in range(n):\n for j in range(n):\n if i == j:\n m += s[i]\n elif i + j == n - 1:\n m += s[j]\n else:\n m += ' '\n return m", "def crosspattern(o, S):\n ans = ''\n n = len(S)\n for i in range(n):\n j = n - 1 - i\n for k in range(n):\n if k == i or k == j:\n ans += S[k]\n else:\n ans += ' '\n return ans", "def crosspattern(ob, S):\n n = len(S)\n l = [' '] * n * n\n st1 = 0\n st2 = n - 1\n ind1 = 0\n ind2 = n - 1\n for i in range(n * n):\n if i == st1:\n l[i] = S[ind1]\n st1 += n + 1\n ind1 += 1\n if i == st2:\n l[i] = S[ind2]\n st2 += n - 1\n ind2 -= 1\n x = ''\n for i in l:\n x = x + i\n return x", "def crosspattern(ob, s):\n n = len(s)\n a = ''\n x = 0\n for i in range(n):\n for j in range(n):\n if i == j or i + j == n - 1:\n a += s[j]\n else:\n a += ' '\n return a", "def crosspattern(ob, S):\n n = len(S)\n m = 2 * n - 1\n res = ''\n x = 0\n for i in range(n):\n for j in range(n):\n if i == j or i + j == n - 1:\n res += S[j]\n else:\n res += ' '\n return res", "def crosspattern(ob, S):\n n = len(S)\n st = ''\n for row in range(n):\n for col in range(n):\n if row == col or row + col == n - 1:\n st = st + S[col]\n else:\n st = st + ' '\n return st", "def crosspattern(ob, S):\n n = len(S)\n a = []\n for i in range(n):\n k = []\n for j in range(n):\n s = ' '\n k.append(s)\n a.append(k)\n j = 0\n k = 0\n kk = n - 1\n p = n - 1\n for i in range(n):\n if i == j:\n a[i][j] = S[k]\n a[i][p] = S[kk]\n p -= 1\n k += 1\n j += 1\n kk -= 1\n res = ''\n for i in range(n):\n for j in range(n):\n res += a[i][j]\n return res"], "starter_code": "def crosspattern (ob,S):\n", "input_output": {"inputs": ["abc", "geeks"], "outputs": ["a c b a c", "g s e k e e k g s"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Strings"], "name": null, "source": "geeksforgeeks", "tags": ["String algorithms", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/cross-character2630/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "crosspattern", "task_id": "TACO_lite/486", "example": [[["abc"], ["geeks"]], [null, null]]} +{"requirement": "Anuj has challenged Arun to climb N stairs but at only in powers of P and Q. Now Arun being a lazy guy wants to do this in minimum number of steps possible. So he has asked for your help to calculate the minimum number of steps he requires to take for climbing N stairs ( 1 step = some power of P or Q stairs (including zeroth power) ).\nExample 1:\nInput: \nN = 15, P = 2, Q = 3\nOutput:\n3\nExplanation:\nWe can make 15 by (8,4,3)\nor (9,3,3) both takes 3 steps.\n \nExample 2:\nInput: \nN = 19, P = 4, Q = 3\nOutput:\n2\nExplanation:\nIn the second case, we can make\n19 by (16,3) which is 2 steps.\n \nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function moves() which takes three integers N, P and Q as inputs and returns the number of steps that Arun needs to take to climb N stairs in powers of P & Q. If fit is not possible print -1.\n \nExpected Time Complexity: O(N. log(N))\nExpected Auxiliary Space: O(N. log(N))\n \nConstraints:\n1 \u2264 N, P, Q \u2264 10^{5}", "solutions": ["from math import log\n\ndef moves(n, p, q):\n if p == 1 and q == 1:\n return n\n if p == 1:\n p = q\n if q == 1:\n q = p\n setti = set([n])\n count = 0\n while 0 not in setti:\n new = set()\n for item in setti:\n new.add(item - p ** int(log(item, p)))\n new.add(item - q ** int(log(item, q)))\n setti = new\n count += 1\n return count", "def moves(n, p, q):\n\n def checker(n, p, dp):\n mul = 1\n if p == 1:\n return n\n ans = float('inf')\n while n - mul >= 0:\n ans = min(ans, dp[n - mul] + 1)\n mul = mul * p\n return ans\n dp = [float('inf')] * (n + 1)\n dp[0] = 0\n for i in range(1, n + 1):\n step1 = checker(i, p, dp)\n step2 = checker(i, q, dp)\n dp[i] = min(step1, step2)\n return dp[n]", "def moves(n, p, q):\n arr = [0] * (n + 1)\n arr[0] = 0\n\n def func(n, p, arr):\n a = 1\n ans = float('inf')\n if p == 1:\n return n\n while n - a >= 0:\n ans = min(ans, arr[n - a])\n a = a * p\n return ans + 1\n for i in range(1, n + 1):\n s1 = func(i, p, arr)\n s2 = func(i, q, arr)\n arr[i] = min(s1, s2)\n return arr[n]", "import math\nimport sys\nsys.setrecursionlimit(2000)\n\ndef moves(n, p, q):\n if q == 1 and p == 1:\n return n\n elif q == 1:\n q = p\n elif p == 1:\n p = q\n dp = [float('inf') for i in range(n + 1)]\n dp[0] = 0\n for i in range(1, n + 1):\n powerQ = pow(q, int(math.log(i, q)))\n powerP = pow(p, int(math.log(i, p)))\n dp[i] = min(dp[i - powerQ], dp[i - powerP]) + 1\n return dp[n]", "def moves(n, p, q):\n dp = [999999 for i in range(n + 1)]\n dp[0] = 0\n for i in range(1, n + 1):\n j = 0\n while i - pow(p, j) >= 0 and p != 1:\n dp[i] = min(dp[i], dp[i - pow(p, j)] + 1)\n j += 1\n j = 0\n while i - pow(q, j) >= 0 and q != 1:\n dp[i] = min(dp[i], dp[i - pow(q, j)] + 1)\n j += 1\n if p == 1 or q == 1:\n dp[i] = min(dp[i], dp[i - 1] + 1)\n return dp[n]", "def moves(N, A, B):\n import math\n power_list = []\n na = 1\n nb = 1\n if A == 1:\n power_list.append(A)\n else:\n for i in range(1 + int(math.log(N, A))):\n power_list.append(A ** i)\n if B == 1:\n power_list.append(B)\n else:\n for i in range(1 + int(math.log(N, B))):\n power_list.append(B ** i)\n M = [float('inf') for _ in range(N + 1)]\n M[0] = 0\n for i in range(1, len(M)):\n if i in power_list:\n M[i] = 1\n continue\n if i < min(power_list):\n M[i] = -1\n continue\n mid = i // 2\n for x in power_list:\n if i > x:\n temp = 1 + M[i - x]\n M[i] = min(temp, M[i])\n return M[N]"], "starter_code": "def moves(n, p, q):\n", "input_output": {"inputs": ["N = 15, P = 2, Q = 3", "N = 19, P = 4, Q = 3"], "outputs": ["3", "2"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Arrays", "Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming", "Data structures"], "skill_types": ["Dynamic programming", "Data structures"], "url": "https://practice.geeksforgeeks.org/problems/minimum-steps1159/1", "Expected Auxiliary Space": "O(N. log(N))", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N. log(N))", "entry_point": "moves", "task_id": "TACO_lite/539", "example": [[[15, 2, 3], [19, 4, 3]], ["3", "2"]]} +{"requirement": "Given a list of integers, return the nth smallest integer in the list. **Only distinct elements should be considered** when calculating the answer. `n` will always be positive (`n > 0`)\n\nIf the nth small integer doesn't exist, return `-1` (C++) / `None` (Python) / `nil` (Ruby) / `null` (JavaScript).\n\nNotes:\n* \"indexing\" starts from 1\n* huge lists (of 1 million elements) will be tested\n\n## Examples\n\n```python\nnth_smallest([1, 3, 4, 5], 7) ==> None # n is more than the size of the list\nnth_smallest([4, 3, 4, 5], 4) ==> None # 4th smallest integer doesn't exist\nnth_smallest([45, -10, 4, 5, 4], 4) ==> 45 # 4th smallest integer is 45\n```\n\nIf you get a timeout, just try to resubmit your solution. However, if you ***always*** get a timeout, review your code.", "solutions": ["def nth_smallest(arr, n):\n s = set(arr)\n return sorted(s)[n - 1] if n <= len(s) else None", "def nth_smallest(arr, n):\n try:\n return sorted(set(arr))[n - 1]\n except:\n pass", "import random\n\ndef partition(vector, left, right, pivotIndex):\n pivotValue = vector[pivotIndex]\n (vector[pivotIndex], vector[right]) = (vector[right], vector[pivotIndex])\n storeIndex = left\n for i in range(left, right):\n if vector[i] < pivotValue:\n (vector[storeIndex], vector[i]) = (vector[i], vector[storeIndex])\n storeIndex += 1\n (vector[right], vector[storeIndex]) = (vector[storeIndex], vector[right])\n return storeIndex\n\ndef select(vector, left, right, k):\n if k < len(vector):\n while True:\n pivotIndex = random.randint(left, right)\n pivotNewIndex = partition(vector, left, right, pivotIndex)\n pivotDist = pivotNewIndex - left\n if pivotDist == k:\n return vector[pivotNewIndex]\n elif k < pivotDist:\n right = pivotNewIndex - 1\n else:\n k -= pivotDist + 1\n left = pivotNewIndex + 1\n\ndef nth_smallest(arr, n):\n unique = list(set(arr))\n return select(unique, 0, len(unique) - 1, n - 1)", "def nth_smallest(arr, k):\n if len(set(arr)) == 1:\n return arr[0]\n elif len(set(arr)) < k:\n return None\n pivot = arr[0]\n lesser = list(set([x for x in arr[1:] if x < pivot]))\n greater = list(set([x for x in arr[1:] if x > pivot]))\n if len(lesser) >= k:\n return nth_smallest(lesser, k)\n elif len(lesser) == k - 1:\n return pivot\n else:\n return nth_smallest(greater, k - len(lesser) - 1)", "def nth_smallest(arr, n):\n s = set(arr)\n if n <= len(s):\n return sorted(s)[n - 1]", "from heapq import *\n\ndef nth_smallest(arr, n):\n arr = list(set(arr))\n heapify(arr)\n if n > len(arr):\n return None\n x = 0\n for i in range(n):\n x = heappop(arr)\n return x", "def nth_smallest(arr, n):\n x = list(dict.fromkeys(arr))\n x.sort(key=int)\n return None if n > len(x) else x[n - 1]", "nth_smallest = lambda a, n: None if len(set(a)) < n else list(sorted(set(a)))[n - 1]", "def nth_smallest(arr, n):\n sorted_arr = sorted(set(arr))\n if n <= len(sorted_arr):\n return sorted_arr[n - 1]", "def nth_smallest(arr, n):\n arr = sorted(list(set(arr)))\n if n > len(arr):\n return None\n return arr[n - 1]"], "starter_code": "def nth_smallest(arr, n):\n", "input_output": {"fn_name": "nth_smallest", "inputs": [[[14, 12, 46, 34, 334], 3], [[4000], 1], [[14, 12, 46, 0, 334], 1]], "outputs": [[34], [4000], [0]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/57a03b8872292dd851000069", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "nth_smallest", "task_id": "TACO_lite/489", "example": [[[[1, 3, 4, 5], 7], [[4, 3, 4, 5], 4], [[45, -10, 4, 5, 4], 4]], [null, null, 45]]} +{"requirement": "You are given an integer array nums. The value of this array is defined as the sum of |nums[i]-nums[i+1]|\u00a0for all\u00a00 <= i < nums.length-1.\nYou are allowed to select any subarray of the given array and reverse it. You can perform this operation only once.\nFind maximum possible value of the final array.\n\u00a0\nExample 1:\nInput: nums = [2,3,1,5,4]\nOutput: 10\nExplanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.\n\nExample 2:\nInput: nums = [2,4,9,24,2,1,10]\nOutput: 68\n\n\u00a0\nConstraints:\n\n1 <= nums.length <= 3*10^4\n-10^5 <= nums[i] <= 10^5", "solutions": ["def switch(nums, i, j, base=0):\n i_inc = abs(nums[j] - nums[i - 1]) - abs(nums[i] - nums[i - 1]) if i > 0 else 0\n j_inc = abs(nums[j + 1] - nums[i]) - abs(nums[j + 1] - nums[j]) if j < len(nums) - 1 else 0\n return base + i_inc + j_inc\n\ndef options(inds, nums):\n (a, b) = findRange(inds)\n (d, c) = findRange(inds[::-1])\n yield 0\n yield (2 * (nums[c] - nums[b]))\n i = max(a, b)\n j = max(c, d)\n n = len(nums)\n yield switch(nums, i, n - 1)\n yield switch(nums, j, n - 1)\n yield switch(nums, 0, i - 1)\n yield switch(nums, 0, j - 1)\n\ndef findRange(inds):\n seen = set()\n for (i, idx) in enumerate(inds):\n if idx + 1 in seen or idx - 1 in seen:\n return (idx + 1, idx) if idx + 1 in seen else (idx - 1, idx)\n seen.add(idx)\n\ndef maxvalueafterreverse(nums: List[int]) -> int:\n n = len(nums)\n base = sum([abs(nums[i] - nums[i + 1]) for i in range(n - 1)])\n if n <= 2:\n return base\n inds = sorted(list(range(n)), key=lambda x: nums[x])\n return base + max(options(inds, nums))", "def maxvalueafterreverse(nums: List[int]) -> int:\n n = len(nums)\n s = 0\n gain = 0\n h = float('-inf')\n l = float('inf')\n for i in range(n - 1):\n n1 = nums[i]\n n2 = nums[i + 1]\n s += abs(n1 - n2)\n gain = max(gain, abs(nums[0] - n2) - abs(n1 - n2), abs(nums[n - 1] - n1) - abs(n1 - n2))\n h = max(h, min(n1, n2))\n l = min(l, max(n1, n2))\n return s + max(gain, 2 * (h - l))", "def maxvalueafterreverse(nums: List[int]) -> int:\n vals = [0] * (len(nums) - 1)\n for (i, n) in enumerate(nums[1:]):\n vals[i] = abs(n - nums[i])\n base = sum(vals)\n bonus = 0\n MPP = max((nums[L] + nums[L + 1] - vals[L] for L in range(len(nums) - 1)))\n MPN = max((nums[L] - nums[L + 1] - vals[L] for L in range(len(nums) - 1)))\n MNP = max((-nums[L] + nums[L + 1] - vals[L] for L in range(len(nums) - 1)))\n MNN = max((-nums[L] - nums[L + 1] - vals[L] for L in range(len(nums) - 1)))\n bonus = max(MPP + MNN, MPN + MNP)\n for R in range(0, len(nums) - 1):\n bonus = max(bonus, abs(nums[0] - nums[R + 1]) - vals[R])\n for L in range(1, len(nums) - 1):\n bonus = max(bonus, abs(nums[L - 1] - nums[len(nums) - 1]) - vals[L - 1])\n return base + bonus", "def maxvalueafterreverse(nums: List[int]) -> int:\n numsLen = len(nums)\n oldSum = sum([abs(nums[i] - nums[i + 1]) for i in range(numsLen - 1)])\n if numsLen < 3:\n return oldSum\n delta = 0\n for i in range(1, numsLen - 1):\n delta = max(delta, abs(nums[i + 1] - nums[0]) - abs(nums[i + 1] - nums[i]), abs(nums[-1] - nums[i - 1]) - abs(nums[i] - nums[i - 1]))\n high = float('-inf')\n low = float('inf')\n for (x, y) in zip(nums, nums[1:]):\n high = max(high, min(x, y))\n low = min(low, max(x, y))\n return oldSum + max(delta, (high - low) * 2)", "def maxvalueafterreverse(nums: List[int]) -> int:\n ans = sum((abs(nums[i + 1] - nums[i]) for i in range(len(nums) - 1)))\n d = 0\n for i in range(1, len(nums) - 1):\n d = max(d, abs(nums[0] - nums[i + 1]) - abs(nums[i] - nums[i + 1]), abs(nums[-1] - nums[i - 1]) - abs(nums[i] - nums[i - 1]))\n high = -math.inf\n low = math.inf\n for (x, y) in zip(nums, nums[1:]):\n high = max(high, min(x, y))\n low = min(low, max(x, y))\n return ans + max(d, (high - low) * 2)", "def maxvalueafterreverse(nums: List[int]) -> int:\n n = len(nums)\n s = 0\n for i in range(len(nums) - 1):\n s += abs(nums[i] - nums[i + 1])\n if n <= 2:\n return s\n maxup = inc = 0\n minmax = float('inf')\n maxmin = -float('inf')\n for left in range(1, n):\n dis = abs(nums[left] - nums[left - 1])\n minmax = min(minmax, max(nums[left], nums[left - 1]))\n maxmin = max(maxmin, min(nums[left], nums[left - 1]))\n inc = max(inc, abs(nums[0] - nums[left]) - dis)\n inc = max(inc, abs(nums[-1] - nums[left - 1]) - dis)\n return s + max(inc, 2 * (maxmin - minmax))", "def maxvalueafterreverse(nums: List[int]) -> int:\n n = len(nums)\n if n == 1:\n return 0\n ans = 0\n for i in range(1, n - 1):\n ans = max(ans, abs(nums[0] - nums[i + 1]) - abs(nums[i] - nums[i + 1]), abs(nums[-1] - nums[i - 1]) - abs(nums[i] - nums[i - 1]))\n (small, large) = ((-1, float('inf')), (-1, -float('inf')))\n for i in range(n):\n if i >= 1:\n if nums[i] >= nums[i - 1]:\n if small[1] > nums[i]:\n small = (i, nums[i])\n if nums[i] <= nums[i - 1]:\n if large[1] < nums[i]:\n large = (i, nums[i])\n if i < n - 1:\n if nums[i] >= nums[i + 1]:\n if small[1] > nums[i]:\n small = (i, nums[i])\n if nums[i] <= nums[i + 1]:\n if large[1] < nums[i]:\n large = (i, nums[i])\n return sum([abs(nums[i] - nums[i + 1]) for i in range(n - 1)]) + max(2 * (large[1] - small[1]), 0, ans)", "def maxvalueafterreverse(nums: List[int]) -> int:\n (totol, res, min2, max2) = (0, 0, float('inf'), -float('inf'))\n for (a, b) in zip(nums, nums[1:]):\n totol += abs(a - b)\n res = max(res, abs(nums[0] - b) - abs(a - b))\n res = max(res, abs(nums[-1] - a) - abs(a - b))\n (min2, max2) = (min(min2, max(a, b)), max(max2, min(a, b)))\n return totol + max(res, (max2 - min2) * 2)", "def maxvalueafterreverse(nums: List[int]) -> int:\n n = len(nums)\n if n == 1:\n return 0\n if n == 2:\n return abs(nums[1] - nums[0])\n base = 0\n for i in range(n - 1):\n base = base + abs(nums[i + 1] - nums[i])\n res = base\n for i in range(1, n - 1):\n if res < base + abs(nums[i + 1] - nums[0]) - abs(nums[i + 1] - nums[i]):\n res = base + abs(nums[i + 1] - nums[0]) - abs(nums[i + 1] - nums[i])\n for i in range(1, n - 1):\n if res < base + abs(nums[i - 1] - nums[n - 1]) - abs(nums[i] - nums[i - 1]):\n res = base + abs(nums[i - 1] - nums[n - 1]) - abs(nums[i] - nums[i - 1])\n currMax = (nums[0], nums[1])\n currMin = (nums[0], nums[1])\n for i in range(1, n - 1):\n curr = (nums[i], nums[i + 1])\n if min(currMax) > max(curr):\n if res < base + 2 * (min(currMax) - max(curr)):\n res = base + 2 * (min(currMax) - max(curr))\n if max(currMin) < min(curr):\n if res < base + 2 * (min(curr) - max(currMin)):\n res = base + 2 * (min(curr) - max(currMin))\n if min(curr) > min(currMax):\n currMax = curr\n if max(curr) < max(currMin):\n currMin = curr\n return res", "def maxvalueafterreverse(nums: List[int]) -> int:\n return sum((abs(a - b) for (a, b) in zip(nums, nums[1:]))) + max(max((abs(nums[0] - b) - abs(a - b) for (a, b) in zip(nums, nums[1:]))), max((abs(nums[-1] - a) - abs(a - b) for (a, b) in zip(nums, nums[1:]))), 2 * (max((min(a, b) for (a, b) in zip(nums, nums[1:]))) - min((max(a, b) for (a, b) in zip(nums, nums[1:])))))", "def maxvalueafterreverse(nums: List[int]) -> int:\n (ans, imp1, min2, max2) = (0, 0, float('inf'), -float('inf'))\n for (x, y) in zip(nums[:-1], nums[1:]):\n ans += abs(x - y)\n imp1 = max(imp1, abs(nums[0] - y) - abs(x - y), abs(nums[-1] - x) - abs(x - y))\n (min2, max2) = (min(min2, max(x, y)), max(max2, min(x, y)))\n return ans + max(imp1, (max2 - min2) * 2)", "def maxvalueafterreverse(nums: List[int]) -> int:\n ans = 0\n for i in range(len(nums) - 1):\n ans += abs(nums[i + 1] - nums[i])\n d = 0\n for i in range(1, len(nums) - 1):\n d = max(d, abs(nums[0] - nums[i + 1]) - abs(nums[i] - nums[i + 1]), abs(nums[-1] - nums[i - 1]) - abs(nums[i] - nums[i - 1]))\n high = -sys.maxsize\n low = sys.maxsize\n for (x, y) in zip(nums, nums[1:]):\n high = max(high, min(x, y))\n low = min(low, max(x, y))\n return ans + max(d, (high - low) * 2)", "import sys\nfrom collections import defaultdict\nfrom typing import List\n\ndef maxvalueafterreverse(nums: List[int]) -> int:\n result = 0\n gain = -sys.maxsize\n hi = -sys.maxsize\n lo = sys.maxsize\n for index in range(len(nums) - 1):\n n1 = nums[index]\n n2 = nums[index + 1]\n result += abs(n1 - n2)\n gain1 = -abs(n1 - n2) + abs(n2 - nums[0])\n gain2 = -abs(n1 - n2) + abs(n1 - nums[-1])\n gain = max(gain, gain1, gain2)\n hi = max(hi, min(n1, n2))\n lo = min(lo, max(n1, n2))\n newgain = 2 * (hi - lo)\n result += max(gain, newgain)\n return result"], "starter_code": "def maxvalueafterreverse(nums: List[int]) -> int:\n", "input_output": {"fn_name": "maxValueAfterReverse", "inputs": [[[2, 3, 1, 5, 4]]], "outputs": [10]}, "difficulty": "MEDIUM", "raw_tags": ["Math", "Greedy", "Array"], "name": null, "source": "leetcode", "tags": ["Data structures", "Mathematics", "Greedy algorithms"], "skill_types": ["Data structures", "Greedy algorithms"], "url": "https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "maxvalueafterreverse", "task_id": "TACO_lite/497", "example": [[[[2, 3, 1, 5, 4]], [[2, 4, 9, 24, 2, 1, 10]]], ["10", "68"]]} +{"requirement": "Very simple, given a number, find its opposite.\n\nExamples:\n```\n1: -1\n14: -14\n-34: 34\n```\n\n~~~if:sql\nYou will be given a table: `opposite`, with a column: `number`. Return a table with a column: `res`.\n~~~", "solutions": ["def opposite(number):\n return -number", "def opposite(number):\n return number * -1", "def opposite(number):\n return number - number * 2", "from operator import neg as opposite", "opposite = lambda x: -x", "opposite = lambda n: -n", "def opposite(number):\n return abs(number) if number < 0 else 0 - number", "def opposite(number):\n numbers = str(number)\n if isinstance(number, int):\n if numbers[0] == '-':\n negatives = numbers[1:]\n negative = int(negatives)\n return negative\n else:\n positives = '-' + numbers\n positive = int(positives)\n return positive\n if isinstance(number, float):\n if numbers[0] == '-':\n negatives = numbers[1:]\n negative = float(negatives)\n return negative\n else:\n positives = '-' + numbers\n positive = float(positives)\n return positive", "def opposite(n):\n return -1 * n", "def opposite(number):\n return number * 'Magic Forest'.find('unicorn')", "def opposite(n):\n return -n", "def opposite(number):\n return 0 - number", "def opposite(number):\n if number > 0:\n return number - number - number\n elif number < 0:\n return number - number - number\n else:\n return number", "def opposite(number):\n opposite = lambda x: -x\n result = opposite(number)\n return result", "def opposite(x):\n return x * -1", "opposite = lambda n: n * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1)) * (n - (n + 1)) / (n - (n + 1))", "def opposite(number):\n import re\n m = re.match('-', str(number))\n if m:\n number = re.sub('-', '', str(number))\n else:\n number = '-' + str(number)\n try:\n return int(number)\n except ValueError:\n return float(number)", "def opposite(number):\n return (lambda x: x * -1)(number)", "opposite = 0.0.__sub__", "def opposite(n):\n str = '\\n \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2593\u2593\u2593\u2593\u2593\u2593\u2593\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2592\u2592\u2592\u2592\u2592\u2592\\n\u2500\u2500\u2500\u2500\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2593\u2593\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2592\u2592\\n\u2500\u2500\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2593\u2593\u2500\u2500\u2500\u2500\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\u2592\u2592\\n\u2500\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2593\u2593\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\\n\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\\n\u2500\u2500\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\\n\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\\n\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\u2592\u2591\u2591\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2592\\n\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2580\u2580\u2580\u2580\u2580\u2588\u2588\u2588\u2584\u2584\u2592\u2592\u2592\u2591\u2591\u2591\u2584\u2584\u2584\u2588\u2588\u2580\u2580\u2580\u2580\u2580\u2591\u2591\u2591\u2591\u2591\u2591\u2592\\n\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2584\u2580\u2588\u2588\u2588\u2588\u2580\u2588\u2588\u2588\u2584\u2592\u2591\u2584\u2588\u2588\u2588\u2588\u2580\u2588\u2588\u2588\u2588\u2584\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\\n\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2588\u2500\u2500\u2580\u2588\u2588\u2588\u2588\u2588\u2580\u2500\u258c\u2592\u2591\u2590\u2500\u2500\u2580\u2588\u2588\u2588\u2588\u2588\u2580\u2500\u2588\u2591\u2591\u2591\u2591\u2591\u2591\u2592\\n\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2580\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2580\u2592\u2592\u2591\u2591\u2580\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2580\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\\n\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\\n\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\\n\u2500\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2580\u2580\u2580\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\\n\u2500\u2500\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\u2592\\n\u2500\u2500\u2500\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\u2592\\n\u2500\u2500\u2500\u2500\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2584\u2580\u2580\u2580\u2580\u2580\u2580\u2580\u2580\u2580\u2580\u2580\u2584\u2591\u2591\u2591\u2591\u2591\u2592\u2592\\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2580\u2592\u2592\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2580\u2591\u2591\u2591\u2592\u2592\\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\u2592\\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\u2592\\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2592\u2592\\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2591\u2592\u2592\\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2592\u2592\\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2593\u2593\u2592\u2592\u2592\u2591\u2591\u2591\u2592\u2592\\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2593\u2593\u2592\u2591\u2592\u2592\\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2593\u2592\u2591\u2592\\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2593\u2592\\n'\n return str.find('\u00af\\\\_(\u30c4)_/\u00af') * n", "opposite = lambda number: -number", "def opposite(number):\n return float(('-' + str(number)).replace('--', ''))", "def opposite(number):\n return (~int(number) + int(number)) * number", "def opposite(number):\n answer = 0 - number\n return answer", "opposite = lambda l: -l", "def opposite(number):\n oppositenum = -number\n return oppositenum", "def opposite(number):\n if number <= 0:\n return abs(number)\n else:\n return number - 2 * number\nopposite(1)", "def opposite(number):\n float(number)\n if number > 0:\n return number - number * 2\n elif number < 0:\n return abs(number)\n elif number == 0:\n return 0", "def opposite(number):\n if number != 0:\n result = -number\n else:\n result = 0\n return result", "def opposite(number):\n if number >= 0:\n return -number\n else:\n return number + -number * 2", "def opposite(number):\n a = -1\n c = number * a\n return c", "def opposite(number):\n if '-' in str(number):\n return -number\n else:\n return -number", "def opposite(number):\n new_num = number\n if number <= 0:\n neg_num = number * 2\n neg_num2 = new_num - neg_num\n return neg_num2\n elif number >= 0:\n pos_num = number * 2\n pos_num2 = new_num - pos_num\n return pos_num2", "def opposite(number):\n a = float(number) * -1\n return a", "def opposite(number):\n if number >= 0:\n return float('-' + str(number))\n else:\n return float(str(number)[1:])", "def opposite(number):\n out = number * -1\n return out", "def opposite(a):\n return -1 * a", "def opposite(number):\n if number >= 0:\n return -number\n else:\n return number * -1", "def opposite(number):\n output = 0 - number\n return output", "def opposite(number):\n x = '-' + str(number)\n if number < 0:\n return abs(number)\n else:\n return float(x)", "def opposite(number):\n qwe = number * -1\n return qwe", "def opposite(n):\n e = n - (n + n)\n return e", "import numpy\n\ndef opposite(number):\n if number < 0:\n return abs(number)\n else:\n return numpy.negative(number)", "def opposite(number):\n return number - number * 2\nopposite(8)", "def opposite(num):\n return abs(num) if num < 0 else -abs(num)", "def opposite(number):\n answer = number * -1\n return answer", "def opposite(number):\n opacne = number * -1\n return opacne", "def opposite(number):\n num = number - 2 * number\n return num", "def opposite(number):\n w = -number\n return w", "def opposite(number):\n string = str(number)\n if string[0] == '-':\n return float(string[1:])\n else:\n return float(''.join(['-', string]))", "def opposite(number):\n convert = None\n if number < 0:\n convert = str(number)[1:]\n else:\n convert = '-' + str(number)\n try:\n return int(convert)\n except:\n return float(convert)", "def opposite(number):\n tmp = number * 2\n ans = number - tmp\n return ans", "def opposite(value):\n return value * -1", "def opposite(number):\n absolu = number * -1\n return absolu", "def opposite(number):\n rev = 0\n rev = -1 * number\n return rev", "def opposite(n):\n if n > 0:\n n = n - 2 * n\n return n\n else:\n n = abs(n)\n return n", "def opposite(number):\n if number >= 1:\n tempnum = number + number\n result = number - tempnum\n return result\n if number <= -1:\n tempnum = number + number\n result = number - tempnum\n return result\n else:\n return 0", "def opposite(number):\n return -number if number != -number else number", "def opposite(number):\n x = number = -number\n return x", "def opposite(number):\n output_num = number * -1\n return output_num", "def opposite(N):\n return -N", "def opposite(number):\n if number > 0:\n number = 0 - number\n elif number is None:\n number = -1\n else:\n return abs(number)\n return number", "def opposite(number):\n if number < 0:\n return abs(number)\n if number > 0:\n return float('-' + str(number))\n if number == 0:\n return 0"], "starter_code": "def opposite(number):\n", "input_output": {"fn_name": "opposite", "inputs": [[1], [25.6], [0], [1425.2222], [-3.1458], [-95858588225]], "outputs": [[-1], [-25.6], [0], [-1425.2222], [3.1458], [95858588225]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/56dec885c54a926dcd001095", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "opposite", "task_id": "TACO_lite/435", "example": [[[1], [14], [-34]], ["-1", "-14", "34"]]} +{"requirement": "Given an array A[ ] denoting the time taken to complete N tasks, determine the minimum amount of time required to finish the tasks considering that you can skip any task, but skipping two consecutive tasks is forbidden.\n \nExample 1:\nInput:\nN = 2\nA[] ={10,20}\nOutput: 10\nExplanation: we can take time of\n10 units and skip 20 units time.\n\u00c3\u00a2\u00e2\u0082\u00ac\u00e2\u0080\u00b9Example 2:\nInput:\nN = 4\nA[] = {10,5,7,10}\nOutput: 12\nExplanation: we can skip both the\ntens and pick 5 and 7 only.\n \nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function minAmount() which accepts array A[] and its size N as input parameter and returns minimum amount of time required to finish the tasks.\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nConstraints:\n1 <= N <= 10^{6}", "solutions": ["def minamount(A, n):\n t1 = A[0]\n t2 = 0\n for i in range(1, n):\n k = A[i] + min(t1, t2)\n f = t1\n t1 = k\n t2 = f\n return min(t1, t2)", "def minamount(A, n):\n dp = [0] * (n + 1)\n dp[1] = A[0]\n dp[2] = A[1]\n for i in range(3, len(dp)):\n dp[i] = min(dp[i - 2] + A[i - 1], dp[i - 1] + A[i - 1])\n return min(dp[-1], dp[-2])", "def minamount(A, n):\n ans = 1000000000.0\n if n == 1:\n return A[0]\n if n == 2:\n return min(A[0], A[1])\n inc = A[0]\n exc = 0\n for i in range(1, n):\n incTemp = A[i] + min(inc, exc)\n excTemp = inc\n inc = incTemp\n exc = excTemp\n return min(inc, exc)", "def minamount(A, n):\n pre1 = A[0]\n pre2 = 0\n for i in range(1, n):\n temp1 = min(pre1, pre2) + A[i]\n temp2 = pre1\n pre1 = temp1\n pre2 = temp2\n return min(pre1, pre2)", "def minamount(A, n):\n summa = sum(A)\n if n < 3:\n return summa - max(A)\n A[2] += A[0]\n for i in range(3, n):\n A[i] += max(A[i - 2], A[i - 3])\n return summa - max(A[-2:])", "import sys\nsys.setrecursionlimit(10 ** 9)\n\ndef minamount(arr, n):\n dp = arr.copy()\n for i in range(n - 3, -1, -1):\n dp[i] = min(dp[i] + dp[i + 2], dp[i] + dp[i + 1])\n return min(dp[0], dp[1])", "def minamount(arr, n):\n dp = arr.copy()\n for i in range(n - 3, -1, -1):\n dp[i] = min(dp[i] + dp[i + 2], dp[i] + dp[i + 1])\n return min(dp[0], dp[1])", "import math\n\ndef minamount(A, n):\n dp = [0]\n s = 0\n ns = A[0]\n for i in range(1, n):\n nss = ns\n nsns = ns + A[i]\n sns = s + A[i]\n dp.append(min(min(nss, nsns), sns))\n s = nss\n ns = min(nsns, sns)\n return dp[-1]", "import math\n\ndef minamount(a, n):\n inc = a[0]\n e = 0\n for i in range(1, n):\n inc_n = a[i] + min(e, inc)\n e = inc\n inc = inc_n\n return min(e, inc)", "def minamount(A, n):\n if n == 1:\n return 0\n if n == 2:\n return min(A)\n dp = [0 if i > 1 else A[i] for i in range(n)]\n for i in range(2, n):\n dp[i] = A[i] + min(dp[i - 1], dp[i - 2])\n return min(dp[n - 2], dp[n - 1])", "def minamount(A, n):\n a = 0\n b = A[0]\n for i in range(1, n):\n c = min(a, b) + A[i]\n d = b\n (a, b) = (d, c)\n return min(a, b)", "def minamount(A, n):\n inc = [-1] * n\n exc = [-1] * n\n inc[0] = A[0]\n exc[0] = 0\n for i in range(1, n):\n inc[i] = min(inc[i - 1], exc[i - 1]) + A[i]\n exc[i] = inc[i - 1]\n return min(exc[n - 1], inc[n - 1])", "def minamount(A, n):\n if len(A) == 1:\n return A[0]\n else:\n prev_a = 0\n prev_b = A[0]\n ans = float('inf')\n for i in range(1, n):\n temp = A[i] + min(prev_b, prev_a)\n ans = min(temp, prev_b)\n prev_a = prev_b\n prev_b = temp\n return ans", "def minamount(a, n):\n for i in range(2, n):\n a[i] = min(a[i - 2], a[i - 1]) + a[i]\n return min(a[-1], a[-2])", "def minamount(A, n):\n excl = 0\n incl = A[0]\n for i in range(1, n):\n excl_ = excl\n excl = incl\n incl = min(incl + A[i], excl_ + A[i])\n return min(incl, excl)", "def minamount(A, n):\n t = 0\n dp = [0 for _ in range(n)]\n dp[0] = A[0]\n dp[1] = A[1]\n for i in range(2, n):\n dp[i] = min(dp[i - 1] + A[i], dp[i - 2] + A[i])\n return min(dp[-1], dp[-2])", "def minamount(A, n):\n if n <= 0:\n return 0\n incl = A[0]\n excl = 0\n for i in range(1, n):\n new_incl = A[i] + min(incl, excl)\n new_excl = incl\n incl = new_incl\n excl = new_excl\n return min(incl, excl)", "def minamount(a, n):\n inc = a[0]\n exc = 0\n for i in range(1, n):\n inc_new = a[i] + min(inc, exc)\n exc_new = inc\n inc = inc_new\n exc = exc_new\n return min(inc, exc)", "def minamount(A, n):\n (skip, take) = (0, A[0])\n total = 0\n for i in range(1, n):\n (s, t) = (skip, take)\n skip = t\n take = min(s, t) + A[i]\n total = min(skip, take)\n return total", "def minamount(arr, n):\n if n <= 0:\n return 0\n incl = arr[0]\n excl = 0\n for i in range(1, n):\n incl_new = arr[i] + min(excl, incl)\n excl_new = incl\n incl = incl_new\n excl = excl_new\n return min(incl, excl)", "def minamount(A, n):\n total_time = [0, 0]\n for task_time in A:\n skip = total_time[1]\n doing = min(total_time) + task_time\n total_time = [skip, doing]\n return min(total_time)", "def minamount(A, n):\n (not_taken, taken) = (0, A[0])\n for i in range(1, n):\n new_taken = min(A[i] + not_taken, A[i] + taken)\n not_taken = taken\n taken = new_taken\n return min(taken, not_taken)", "def minamount(A, n):\n skip = 0\n doIt = A[n - 1]\n for i in range(n - 2, -1, -1):\n old = skip\n skip = doIt\n doIt = A[i] + min(old, doIt)\n return min(skip, doIt)", "def minamount(A, n):\n skipped = 0\n a = A[n - 1]\n for i in range(n - 2, -1, -1):\n prev = skipped\n skipped = a\n a = A[i] + min(prev, a)\n return min(skipped, a)", "def minamount(arr, n):\n incl = [0] * (n + 1)\n excl = [0] * (n + 1)\n incl[0] = 0\n minT = [0] * (n + 1)\n excl[0] = 0\n minT[0] = 0\n for i in range(1, n + 1):\n incl[i] = arr[i - 1] + min(incl[i - 1], excl[i - 1])\n excl[i] = incl[i - 1]\n minT[i] = min(incl[i], excl[i])\n return minT[n]", "def minamount(A, n):\n with_skip = 0\n without_skip = A[0]\n for i in range(1, len(A)):\n temp1 = with_skip\n with_skip = without_skip\n without_skip = A[i] + min(temp1, without_skip)\n return min(with_skip, without_skip)", "def minamount(A, n):\n a = 0\n b = A[0]\n i = 1\n while i < n:\n c = A[i] + min(a, b)\n (a, b) = (b, c)\n i += 1\n return min(a, b)", "def minamount(A, n):\n if n == 1:\n return A[0]\n if n == 2:\n return min(A[0], A[1])\n skip = 0\n cts = A[0]\n for i in range(1, n):\n temp = skip\n skip = cts\n cts = A[i] + min(temp, cts)\n return min(skip, cts)", "def Task(arr, i=0, taken=True):\n global mod\n global dp\n try:\n return dp[i, taken]\n except:\n pass\n if i == len(arr) - 2:\n if taken == True:\n return min(arr[i], arr[i + 1])\n return arr[i]\n if taken == False:\n dp[i, taken] = arr[i] + Task(arr, i + 1, True) % mod\n return dp[i, taken]\n k1 = Task(arr, i + 1, False) % mod\n k2 = arr[i] + Task(arr, i + 1, True) % mod\n dp[i, taken] = min(k1, k2) % mod\n return dp[i, taken]\n\ndef TaskTabulation(arr):\n dp = [[0 for i in range(len(arr))] for j in range(2)]\n dp[0][-1] = arr[-1]\n dp[1][-1] = 0\n dp[0][-2] = min(arr[-2], arr[-1])\n dp[1][-2] = arr[-2]\n res = float('inf')\n for i in range(len(arr) - 3, -1, -1):\n dp[1][i] = arr[i] + dp[0][i + 1]\n dp[0][i] = min(dp[1][i + 1], arr[i] + dp[0][i + 1])\n return min(dp[0][0], dp[1][0])\n\ndef minamount(A, n):\n global dp\n global mod\n mod = 1000000007\n dp = {}\n return TaskTabulation(A)", "def minamount(A, n):\n if n == 1:\n return A[0]\n if n == 2:\n return min(A[0], A[1])\n exc = [0] * (n + 1)\n inc = [0] * (n + 1)\n inc[0] = A[0]\n exc[1] = A[0]\n inc[1] = A[1]\n for x in range(2, n):\n exc[x] = inc[x - 1]\n inc[x] = min(A[x] + exc[x - 1], A[x] + inc[x - 1])\n return min(exc[n - 1], inc[n - 1])", "def minamount(A, n):\n if n <= 0:\n return 0\n incl = A[0]\n excl = 0\n for i in range(1, n):\n incn = A[i] + min(incl, excl)\n excn = incl\n incl = incn\n excl = excn\n return min(incl, excl)", "def minamount(arr, n):\n (inc, exc) = (arr[0], 0)\n for i in range(1, n):\n new_inc = arr[i] + min(inc, exc)\n new_exc = inc\n inc = new_inc\n exc = new_exc\n return min(inc, exc)"], "starter_code": "def minamount(A, n):\n", "input_output": {"inputs": ["N = 2\nA[] ={10,20}", "N = 4\nA[] = {10,5,7,10}"], "outputs": ["10", "12"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/skip-the-work5752/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N)", "entry_point": "minamount", "task_id": "TACO_lite/541", "example": [[[2, [10, 20]], [4, [10, 5, 7, 10]]], [null, null]]} +{"requirement": "Given a square matrix of size N x N. The task is to find the determinant of this matrix.\nExample 1:\nInput:\nN = 4\nmatrix[][] = {{1, 0, 2, -1},\n {3, 0, 0, 5},\n {2, 1, 4, -3},\n {1, 0, 5, 0}}\nOutput: 30\nExplanation:\nDeterminant of the given matrix is 30.\nExample 2:\nInput:\nN = 3\nmatrix[][] = {{1, 2, 3},\n {4, 5, 6},\n {7, 10, 9}}\nOutput: 12\nExplanation:\nDeterminant of the given matrix is 12.\nYour Task:\nYou don't need to read input or print anything. Complete the function determinantOfMatrix() that takes matrix and its size n as input parameters and returns the determinant of the matrix.\nExpected Time Complexity: O(N^{4})\nExpected Auxiliary Space: O(N^{2})\nConstraints:\n1 <= N <= 8\n-10 <= mat[i][j] <= 10", "solutions": ["def determinantofmatrix(a, n):\n if n == 1:\n return a[0][0]\n elif n == 2:\n return a[0][0] * a[1][1] - a[1][0] * a[0][1]\n else:\n ans = 0\n for col in range(n):\n small = []\n for i in range(1, n):\n dem = []\n for j in range(n):\n if j == col:\n continue\n dem.append(a[i][j])\n small.append(dem)\n if col % 2 == 0:\n ans += a[0][col] * self.determinantofmatrix(small, n - 1)\n else:\n ans -= a[0][col] * self.determinantofmatrix(small, n - 1)\n return ans", "def determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n det = 0\n sign = 1\n for i in range(n):\n new_mat = []\n for y in range(n - 1):\n new_mat.append([])\n for x in range(n):\n if x != i:\n new_mat[y].append(matrix[y + 1][x])\n self.determinantofmatrix(new_mat, n - 1)\n det += sign * matrix[0][i] * self.determinantofmatrix(new_mat, n - 1)\n sign *= -1\n return det", "import numpy as np\n\ndef determinant(mat):\n det = np.linalg.det(mat)\n return round(det)\n\ndef determinantofmatrix(matrix, n):\n return int(determinant(matrix))", "def determinantofmatrix(matrix, n):\n if len(matrix) == 1:\n return matrix[0][0]\n if len(matrix) == 2:\n return matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]\n currentCol = ans = 0\n while currentCol < len(matrix[0]):\n minor = [[0] * 0] * 0\n for i in range(len(matrix)):\n temp = []\n for j in range(len(matrix[0])):\n if i != 0 and j != currentCol:\n temp.append(matrix[i][j])\n if len(temp) > 0:\n minor.append(temp)\n ans = ans + matrix[0][currentCol] * (-1) ** currentCol * self.determinantofmatrix(minor, len(minor))\n currentCol += 1\n return ans", "def determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n elif n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n res = 0\n for i in range(len(matrix[0])):\n smallerMatrix = []\n for j in range(1, len(matrix)):\n col = []\n for k in range(len(matrix[0])):\n if k == i:\n continue\n col.append(matrix[j][k])\n smallerMatrix.append(col)\n if i % 2 == 0:\n res += matrix[0][i] * self.determinantofmatrix(smallerMatrix, n - 1)\n else:\n res -= matrix[0][i] * self.determinantofmatrix(smallerMatrix, n - 1)\n return res", "import numpy as np\nimport math\n\ndef determinantofmatrix(matrix, n):\n det = np.linalg.det(matrix)\n return int(round(det))", "import numpy as np\n\ndef determinantofmatrix(matrix, n):\n ans = str(np.linalg.det(matrix))\n s = ''\n for d in ans:\n if d == '.':\n break\n s += d\n return int(s)", "def determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n det = 0\n for i in range(n):\n submatrix = [[0 for _ in range(n - 1)] for _ in range(n - 1)]\n for x in range(1, n):\n j = 0\n for y in range(n):\n if y == i:\n continue\n submatrix[x - 1][j] = matrix[x][y]\n j += 1\n det += matrix[0][i] * self.determinantofmatrix(submatrix, n - 1) * (-1) ** i\n return det", "def determinantofmatrix(mat, n):\n temp = [0] * n\n total = 1\n det = 1\n for i in range(0, n):\n index = i\n while index < n and mat[index][i] == 0:\n index += 1\n if index == n:\n continue\n if index != i:\n for j in range(0, n):\n (mat[index][j], mat[i][j]) = (mat[i][j], mat[index][j])\n det = det * int(pow(-1, index - i))\n for j in range(0, n):\n temp[j] = mat[i][j]\n for j in range(i + 1, n):\n num1 = temp[i]\n num2 = mat[j][i]\n for k in range(0, n):\n mat[j][k] = num1 * mat[j][k] - num2 * temp[k]\n total = total * num1\n for i in range(0, n):\n det = det * mat[i][i]\n return int(det / total)", "def getCofactor(matrix, i, j):\n return [row[:j] + row[j + 1:] for row in matrix[:i] + matrix[i + 1:]]\n\ndef determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n if n == 2:\n value = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n return value\n else:\n s = 0\n for current_col in range(n):\n sign = (-1) ** current_col\n sub_matrix = self.getCofactor(matrix, 0, current_col)\n sub_det = self.determinantofmatrix(sub_matrix, n - 1)\n s += sign * matrix[0][current_col] * sub_det\n return s", "def determinantofmatrix(matrix, n):\n det = 0\n if n == 1:\n return matrix[0][0]\n if n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]\n for i in range(n):\n temp = []\n for row in range(1, n):\n p = []\n for col in range(n):\n if col == i:\n continue\n else:\n p.append(matrix[row][col])\n temp.append(p)\n if i % 2 == 1:\n det = det - matrix[0][i] * Solution.determinantofmatrix(self, temp, n - 1)\n else:\n det = det + matrix[0][i] * Solution.determinantofmatrix(self, temp, n - 1)\n return det", "def smallermatrix(matrix, row, col):\n from copy import deepcopy\n arr = deepcopy(matrix)\n arr.remove(matrix[row])\n for row in arr:\n row.pop(col)\n return arr\n\ndef sol(matrix):\n n = len(matrix)\n if n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n ans = 0\n for i in range(n):\n total = (-1) ** i * matrix[0][i] * self.sol(self.smallermatrix(matrix, 0, i))\n ans += total\n return ans\n\ndef determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n ans = self.sol(matrix)\n return ans", "from numpy import *\n\ndef determinantofmatrix(matrix, n):\n return int(round(linalg.det(matrix)))", "def submatrix(m, r, c):\n rows = len(m)\n columns = len(m[0])\n sm = []\n for i in range(rows):\n sm.append([])\n for j in range(columns):\n sm[i].append(m[i][j])\n sm = sm[1:]\n for i in range(len(sm)):\n sm[i] = sm[i][:c] + sm[i][c + 1:]\n return sm\n\ndef determinant(m):\n rows = len(m)\n columns = len(m[0])\n if rows == 1 and columns == 1:\n return m[0][0]\n else:\n c = 1\n result = 0\n for i in range(columns):\n sm = self.submatrix(m, 0, i)\n result += c * m[0][i] * self.determinant(sm)\n c *= -1\n return result\n\ndef determinantofmatrix(matrix, n):\n return self.determinant(matrix)", "def getCofactor(matrix, temp, p, q, n):\n (i, j) = (0, 0)\n for row in range(n):\n for col in range(n):\n if row != p and col != q:\n temp[i][j] = matrix[row][col]\n j += 1\n if j == n - 1:\n j = 0\n i += 1\n\ndef determinantofmatrix(matrix, n):\n d = 0\n if n == 1:\n return matrix[0][0]\n temp = [[0 for i in range(n)] for i in range(n)]\n sign = 1\n for i in range(n):\n self.getCofactor(matrix, temp, 0, i, n)\n d += sign * matrix[0][i] * self.determinantofmatrix(temp, n - 1)\n sign = -sign\n return d", "def determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n if n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n total = 0\n for i in range(n):\n B = matrix.copy()\n B = B[1:]\n for j in range(n - 1):\n B[j] = B[j][0:i] + B[j][i + 1:]\n sign = (-1) ** (i % 2)\n sub_det = self.determinantofmatrix(B, n - 1)\n total += matrix[0][i] * sign * sub_det\n return total", "def determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n if n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n det = 0\n for col in range(n):\n if col % 2 == 0:\n det += matrix[0][col] * self.determinantofmatrix(self.getTheMat(matrix, n, 0, col), n - 1)\n else:\n det -= matrix[0][col] * self.determinantofmatrix(self.getTheMat(matrix, n, 0, col), n - 1)\n return det\n\ndef getTheMat(matrix, n, x, y):\n mat = []\n for i in range(n):\n cur_mat = []\n for j in range(n):\n if i != x and j != y:\n cur_mat.append(matrix[i][j])\n if cur_mat != []:\n mat.append(cur_mat)\n return mat", "import numpy as np\n\ndef determinantofmatrix(matrix, n):\n ans = np.linalg.det(matrix)\n a1 = round(ans)\n return int(a1)", "def cofactorMatrix(matrix, r, c):\n return [row[:c] + row[c + 1:] for row in matrix[:r] + matrix[r + 1:]]\n\ndef determinantofmatrix(matrix, n):\n if len(matrix) == 1:\n return matrix[0][0]\n if len(matrix) == 2:\n v = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n return v\n sum = 0\n for curr_col in range(len(matrix)):\n sign = (-1) ** curr_col\n sub_det = self.determinantofmatrix(self.cofactorMatrix(matrix, 0, curr_col), n)\n sum += sign * matrix[0][curr_col] * sub_det\n return sum", "import numpy as np\n\ndef determinantofmatrix(arr, n):\n det = str(np.linalg.det(arr))\n l = len(det)\n return det[:l - 2]", "import numpy\n\ndef determinantofmatrix(A, n):\n return int(round(numpy.linalg.det(A)))", "def determinantofmatrix(matrix, n):\n\n def cofactor(arr, temp, i, j, n):\n s = 0\n t = 0\n for r in range(n):\n for c in range(n):\n if r != i and c != j:\n temp[s][t] = arr[r][c]\n t += 1\n if t == n - 1:\n t = 0\n s += 1\n return temp\n if n == 1:\n return matrix[0][0]\n temp = [[float('inf') for _ in range(n)] for _ in range(n)]\n sgn = 1\n det = 0\n for i in range(n):\n C = cofactor(matrix, temp, 0, i, n)\n det += matrix[0][i] * sgn * self.determinantofmatrix(C, n - 1)\n sgn = -sgn\n return det", "def determinantMaker(a, m):\n b = []\n n = len(a)\n for i in range(1, n, 1):\n c = []\n for j in range(n):\n if j == m:\n continue\n else:\n c.append(a[i][j])\n b.append(c)\n return b\n\ndef determinantofmatrix(a, n):\n n = len(a)\n if n == 1:\n return a[0][0]\n elif n == 2:\n return a[0][0] * a[1][1] - a[1][0] * a[0][1]\n else:\n sign = 1\n ans = 0\n for i in range(n):\n temp = 0\n b = self.determinantMaker(a, i)\n m = len(b)\n temp = sign * a[0][i] * self.determinantofmatrix(b, m)\n ans += temp\n sign *= -1\n return ans", "def determinantofmatrix(matrix, n):\n\n def getSubmetrix(matrix, coordinations):\n (row, colomn) = coordinations\n newmatrxi = []\n for i in range(len(matrix)):\n if i == row - 1:\n continue\n newrow = []\n for j in range(len(matrix[0])):\n if j == colomn - 1:\n continue\n newrow.append(matrix[i][j])\n newmatrxi.append(newrow)\n return newmatrxi\n\n def determinant(matrix):\n if len(matrix) == 2:\n det = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n elif len(matrix) > 2:\n det = 0\n for i in range(len(matrix)):\n submat = getSubmetrix(matrix, (1, i + 1))\n det += (-1) ** (i + 2) * determinant(submat) * matrix[0][i]\n else:\n return matrix[0][0]\n return det\n return determinant(matrix)", "def getTruncatedMatrix(matrix, n, i, j):\n res = []\n for row in range(n):\n arr = []\n for col in range(n):\n if col != j:\n arr.append(matrix[row][col])\n if row != i:\n res.append(arr)\n return res\n\ndef determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n if n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n else:\n ans = 0\n for col in range(n):\n ans += (-1) ** col * matrix[0][col] * self.determinantofmatrix(getTruncatedMatrix(matrix, n, 0, col), n - 1)\n return ans", "import numpy as np\n\ndef cofactor(M, i, j):\n return [row[:j] + row[j + 1:] for row in M[:i] + M[i + 1:]]\n\ndef determinantofmatrix(M, n):\n if n == 1:\n return M[0][0]\n if n == 2:\n return M[0][0] * M[1][1] - M[0][1] * M[1][0]\n det = 0\n for i in range(n):\n sign = (-1) ** i\n subdet = self.determinantofmatrix(self.cofactor(M, 0, i), n - 1)\n det += sign * M[0][i] * subdet\n return det", "import numpy as np\n\ndef determinantofmatrix(M, n):\n det = np.linalg.det(M)\n return int(round(det))", "import numpy as np\n\ndef cofactor(arr, i, j):\n return [row[:j] + row[j + 1:] for row in arr[:i] + arr[i + 1:]]\n\ndef determinantofmatrix(arr, n):\n return int(round(np.linalg.det(arr)))", "def determinantofmatrix(matrix, n):\n if n == 1:\n return matrix[0][0]\n elif n == 2:\n a = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n return a\n s = 0\n li = []\n for i in range(n):\n if matrix[0][i] == 0:\n continue\n for k in range(1, n):\n li1 = list(matrix[k])\n li1.pop(i)\n li.append(li1)\n if i % 2 == 0:\n s += matrix[0][i] * self.determinantofmatrix(li, n - 1)\n li = []\n else:\n s -= matrix[0][i] * self.determinantofmatrix(li, n - 1)\n li = []\n return s", "def determinantofmatrix(matrix, n):\n return self.solve(matrix, n)\n\ndef solve(matrix, n):\n if n == 1:\n return matrix[0][0]\n if n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n matrix2 = [[0 for j in range(n - 1)] for i in range(n - 1)]\n total = 0\n for k in range(n):\n a = b = 0\n for i in range(1, n):\n b = 0\n for j in range(n):\n if j != k:\n matrix2[a][b] = matrix[i][j]\n b += 1\n a += 1\n t = self.determinantofmatrix(matrix2, n - 1)\n total += (-1) ** k * matrix[0][k] * t\n return total", "def determinantofmatrix(M, n):\n import numpy\n D = int(round(numpy.linalg.det(M)))\n return D", "def cofactor(m, i, j):\n return [row[:j] + row[j + 1:] for row in m[:i] + m[i + 1:]]\n\ndef determinantofmatrix(mat, n=float('inf')):\n if len(mat) == 1:\n return mat[0][0]\n if len(mat) == 2:\n return mat[0][0] * mat[1][1] - mat[1][0] * mat[0][1]\n res = 0\n for col in range(len(mat)):\n sign = (-1) ** col\n det = self.determinantofmatrix(self.cofactor(mat, 0, col))\n res += sign * mat[0][col] * det\n return res", "def determinant_recursive(A, total=0):\n indices = list(range(len(A)))\n if len(A) == 2 and len(A[0]) == 2:\n val = A[0][0] * A[1][1] - A[1][0] * A[0][1]\n return val\n for fc in indices:\n As = A\n As = As[1:]\n height = len(As)\n for i in range(height):\n As[i] = As[i][0:fc] + As[i][fc + 1:]\n sign = (-1) ** (fc % 2)\n sub_det = determinant_recursive(As)\n total += sign * A[0][fc] * sub_det\n return total\n\ndef determinantofmatrix(a, n):\n if n == 1:\n return a[0][0]\n return determinant_recursive(a)", "def cofactor_matrix(matrix, temp, p, q, n):\n (i, j) = (0, 0)\n for row in range(n):\n for column in range(n):\n if row != p and column != q:\n temp[i][j] = matrix[row][column]\n j += 1\n if j == n - 1:\n j = 0\n i += 1\n\ndef determinantofmatrix(matrix, n):\n answer = 0\n if n == 1:\n return matrix[0][0]\n temp = [[0 for i in range(n)] for j in range(n)]\n sign = 1\n for i in range(n):\n self.cofactor_matrix(matrix, temp, 0, i, n)\n answer += sign * matrix[0][i] * self.determinantofmatrix(temp, n - 1)\n sign = -sign\n return answer", "def determinantofmatrix(arr, n):\n if n == 1:\n return arr[0][0]\n else:\n b = [[0] * n for i in range(n)]\n s = 1\n det = 0\n for c in range(n):\n m = 0\n z = 0\n for i in range(n):\n for j in range(n):\n if i != 0 and j != c:\n b[m][z] = arr[i][j]\n if z < n - 2:\n z += 1\n else:\n z = 0\n m += 1\n det = det + arr[0][c] * s * self.determinantofmatrix(b, n - 1)\n s = s * -1\n return det", "def getcofactor(m, i, j):\n return [row[:j] + row[j + 1:] for row in m[:i] + m[i + 1:]]\n\ndef determinantofmatrix(mat, n=0):\n if len(mat) == 1:\n return mat[0][0]\n if len(mat) == 2:\n value = mat[0][0] * mat[1][1] - mat[1][0] * mat[0][1]\n return value\n Sum = 0\n for current_column in range(len(mat)):\n sign = (-1) ** current_column\n sub_det = self.determinantofmatrix(getcofactor(mat, 0, current_column))\n Sum += sign * mat[0][current_column] * sub_det\n return Sum", "import numpy as np\n\ndef determinantofmatrix(Matrix, n):\n D = np.linalg.det(Matrix)\n return int(round(D))", "def getfactor(matrix, n, row, col, temp):\n x = 0\n y = 0\n for i in range(n):\n for j in range(n):\n if i != row and j != col:\n temp[x][y] = matrix[i][j]\n y += 1\n if y == n - 1:\n y = 0\n x += 1\n\ndef determinantofmatrix(matrix, n):\n d = 0\n if n == 1:\n return matrix[0][0]\n temp = [[0 for _ in range(n)] for _ in range(n)]\n sign = 1\n for j in range(n):\n self.getfactor(matrix, n, 0, j, temp)\n d += sign * matrix[0][j] * self.determinantofmatrix(temp, n - 1)\n sign *= -1\n return d"], "starter_code": "def determinantofmatrix(matrix,n):\n", "input_output": {"inputs": ["N = 4\nmatrix[][] = {{1, 0, 2, -1},\n {3, 0, 0, 5},\n {2, 1, 4, -3},\n {1, 0, 5, 0}}", "N = 3\nmatrix[][] = {{1, 2, 3},\n {4, 5, 6},\n {7, 10, 9}}"], "outputs": ["30", "12"]}, "difficulty": "EASY", "raw_tags": ["Data Structures", "Matrix"], "name": null, "source": "geeksforgeeks", "tags": ["Matrices", "Data structures"], "skill_types": ["Data structures"], "url": "https://practice.geeksforgeeks.org/problems/determinant-of-a-matrix-1587115620/1", "Expected Auxiliary Space": "O(N^{2})", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N^{4})", "entry_point": "determinantofmatrix", "task_id": "TACO_lite/529", "example": [[], []]} +{"requirement": "# Task\nGiven an array `arr`, find the maximal value of `k` such `a[i] mod k` = `a[j] mod k` for all valid values of i and j.\n\nIf it's impossible to find such number (there's an infinite number of `k`s), return `-1` instead.\n\n\n# Input/Output\n\n`[input]` integer array `arr`\n\nA non-empty array of positive integer.\n\n`2 <= arr.length <= 10`\n\n`1 <= arr[i] <= 100`\n\n`[output]` an integer\n\nThe maximum value of `k` or `-1` if there is none.\n\n\n# Example\n\nFor `arr = [1, 2, 3]`, the output should be `1`.\n\n`1` is the only k which satisfies the given conditions.\n\nFor `arr = [1, 1, 1]`, the output should be `-1`.\n\n`1 % k = 1` for `any k > 1`, so it's impossible to find the maximum.\n\nFor `arr = [5, 2, 8]`, the output should be `3`.\n\n`5 % 3 == 2 % 3 == 8 % 3 == 2`", "solutions": ["def finding_k(arr):\n for n in range(max(arr) - 1, 0, -1):\n if len({x % n for x in arr}) == 1:\n return n\n return -1", "from itertools import repeat\nfrom functools import reduce\nfrom operator import sub\nfrom math import gcd\n\ndef finding_k(arr):\n return reduce(gcd, filter(None, map(sub, set(arr), repeat(min(arr)))), 0) or -1", "def finding_k(arr):\n s = set(arr)\n if s == {1}:\n return -1\n for k in range(max(s), 0, -1):\n r = arr[0] % k\n if all((x % k == r for x in s)):\n return k\n return -1", "finding_k = lambda a: max([k for k in range(1, max(a)) if eval('=='.join([str(z) + '%' + str(k) for z in a]))], default=-1)", "def finding_k(arr):\n for i in range(max(arr) - 1, 0, -1):\n if len({j % i for j in arr}) == 1:\n return i\n return -1", "finding_k = lambda a: next((i for i in range(max(a) - 1, 0, -1) if len(set([j % i for j in a])) == 1), -1)", "from fractions import gcd\nfrom functools import reduce\n\ndef finding_k(arr):\n fr = [x - min(arr) for x in arr]\n if all((v == 0 for v in fr)):\n return -1\n else:\n return reduce(lambda x, y: gcd(x, y), fr)", "def finding_k(arr):\n maxValue = max(arr) - min(arr)\n k = 0\n while maxValue > 0:\n if len(set(map(lambda x: x % maxValue, arr))) == 1:\n k = maxValue\n break\n maxValue -= 1\n if k:\n return k\n else:\n return -1", "from functools import reduce\ngcd = lambda a, b: gcd(b, a % b) if b else a\nfinding_k = lambda arr: reduce(lambda a, b: gcd(a, b), [abs(e - arr[0]) for e in arr]) or -1", "def finding_k(arr):\n ans = []\n for i in range(1, 101):\n if len({j % i for j in arr}) == 1:\n ans.append(i)\n return max(ans) if len(ans) < 100 else -1"], "starter_code": "def finding_k(arr):\n", "input_output": {"fn_name": "finding_k", "inputs": [[[1, 2, 3]], [[1, 1, 1]], [[5, 2, 8]], [[4, 1, 7]], [[1, 7, 13]], [[4, 5, 4]], [[5, 6, 7, 8]], [[10, 100]], [[64, 8, 1]], [[2, 9, 30]]], "outputs": [[1], [-1], [3], [3], [6], [1], [1], [90], [7], [7]]}, "difficulty": "EASY", "raw_tags": ["Algorithms"], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5919427e5ffc30804900005f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "finding_k", "task_id": "TACO_lite/346", "example": [[[[1, 2, 3]], [[1, 1, 1]], [[5, 2, 8]]], ["1", "-1", "3"]]} +{"requirement": "Given weights and values of N items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack.\nNote: Unlike 0/1 knapsack, you are allowed to break the item. \n \nExample 1:\nInput:\nN = 3, W = 50\nvalues[] = {60,100,120}\nweight[] = {10,20,30}\nOutput:\n240.00\nExplanation:Total maximum value of item\nwe can have is 240.00 from the given\ncapacity of sack. \nExample 2:\nInput:\nN = 2, W = 50\nvalues[] = {60,100}\nweight[] = {10,20}\nOutput:\n160.00\nExplanation:\nTotal maximum value of item\nwe can have is 160.00 from the given\ncapacity of sack.\n \nYour Task :\nComplete the function fractionalKnapsack() that receives maximum capacity , array of structure/class and size n and returns a double value representing the maximum value in knapsack.\nNote: The details of structure/class is defined in the comments above the given function.\nExpected Time Complexity : O(NlogN)\nExpected Auxilliary Space: O(1)\nConstraints:\n1 <= N <= 10^{5}\n1 <= W <= 10^{5}", "solutions": ["def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: -1 * (x.value / x.weight))\n profit = 0\n for i in range(n):\n v = arr[i].value\n w = arr[i].weight\n if w <= W:\n W -= w\n profit += v\n else:\n profit += W * (v / w)\n W = 0\n break\n return profit", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n fractionalArray = []\n for i in range(n):\n fractionalArray.append([arr[i].value, arr[i].weight, arr[i].value / arr[i].weight])\n fractionalArray = sorted(fractionalArray, key=lambda x: -x[2])\n ans = 0\n while W > 0 and len(fractionalArray) > 0:\n popped = fractionalArray.pop(0)\n if popped[1] > W:\n ans += popped[0] * W / popped[1]\n W = 0\n else:\n W -= popped[1]\n ans += popped[0]\n return round(ans, 2)", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n d = []\n for i in range(0, len(arr)):\n k = (arr[i].value, arr[i].weight, arr[i].value / arr[i].weight)\n d.append(k)\n d.sort(key=lambda x: x[2], reverse=True)\n p = 0\n for i in range(0, len(d)):\n if d[i][1] <= W:\n W -= d[i][1]\n p += d[i][0]\n elif d[i][1] > W:\n p += d[i][0] * (W / d[i][1])\n break\n return p", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(w, arr, n):\n count = 0\n\n def give(i):\n return i.value / i.weight\n arr.sort(reverse=True, key=give)\n for i in arr:\n ass = min(w, i.weight)\n count += ass * i.value / i.weight\n w -= ass\n if ass == 0:\n return count\n return count", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n items = sorted(arr, key=lambda x: x.weight / x.value)\n result = 0\n for item in items:\n if W <= 0:\n break\n result += min(1, W / item.weight) * item.value\n W -= item.weight\n return result", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n frac = [[items.value / items.weight, items.weight] for items in arr]\n frac.sort(key=lambda x: x[0])\n val = 0\n while W and frac:\n a = frac.pop()\n k = a[0]\n p = a[1]\n if W >= p:\n val += k * p\n W -= p\n else:\n val += k * W\n W = 0\n return val", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(w, arr, n):\n arr.sort(key=lambda x: -1 * (x.value / x.weight))\n value = 0\n for item in arr:\n if w <= item.weight:\n value += item.value * (w / item.weight)\n break\n else:\n value += item.value\n w -= item.weight\n return value", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n total = 0\n remaining_weight = W\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n for item in arr:\n if item.weight <= remaining_weight:\n total += item.value\n remaining_weight -= item.weight\n else:\n total += remaining_weight * item.value / item.weight\n break\n return total", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, Items, n):\n arr = []\n total = 0\n s = 0\n for i in range(n):\n x = Items[i].value / Items[i].weight\n arr.append([x, i])\n arr.sort(reverse=True)\n for i in range(n):\n if s + Items[arr[i][1]].weight < W:\n total += Items[arr[i][1]].value\n s += Items[arr[i][1]].weight\n else:\n total += (W - s) * arr[i][0]\n break\n return total", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n li = []\n for i in range(n):\n perUnitVal = arr[i].value / arr[i].weight\n li.append((perUnitVal, arr[i]))\n li.sort(key=lambda x: x[0], reverse=True)\n profit = 0\n for pair in li:\n if pair[1].weight <= W:\n profit += pair[1].value\n W -= pair[1].weight\n else:\n profit += pair[1].value / pair[1].weight * W\n W = 0\n break\n return profit", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n curWeight = 0\n finalValue = 0.0\n for i in range(n):\n if curWeight + arr[i].weight <= W:\n curWeight += arr[i].weight\n finalValue += arr[i].value\n else:\n remain = W - curWeight\n finalValue += arr[i].value / arr[i].weight * remain\n break\n return finalValue", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n rr = []\n arr.sort(reverse=True, key=lambda x: x.value / x.weight)\n ans = 0\n for ind in range(len(arr)):\n cap = min(W, arr[ind].weight)\n if arr[ind].weight <= W:\n ans += arr[ind].value\n W -= arr[ind].weight\n continue\n rat = arr[ind].value / arr[ind].weight\n ans += rat * cap\n W -= cap\n return ans", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n profit = 0\n for i in arr:\n if i.weight <= W:\n profit += i.value\n W -= i.weight\n elif i.weight > W:\n profit += i.value / i.weight * W\n W = 0\n break\n return profit", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n final = 0\n cur = 0\n for i in range(n):\n if cur + arr[i].weight <= W:\n cur += arr[i].weight\n final += arr[i].value\n else:\n rem = W - cur\n final += arr[i].value / arr[i].weight * rem\n break\n return final", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n ans = 0\n vpp = []\n for ob in arr:\n (w, v) = (ob.weight, ob.value)\n vpp.append([v / w, v, w])\n vpp.sort()\n while vpp and W:\n (vp, v, w) = vpp.pop()\n if W >= w:\n W -= w\n ans += v\n else:\n ans += W * vp\n W -= W\n return ans", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n for a in arr:\n a.avg = a.value / a.weight\n arr.sort(key=lambda x: x.avg, reverse=True)\n (final_val, i) = (0, 0)\n while W > 0 and i < n:\n if arr[i].weight < W:\n final_val += arr[i].value\n W -= arr[i].weight\n else:\n final_val += W * arr[i].avg\n W = 0\n i += 1\n return final_val", "import heapq\n\ndef __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n\n class Wrapper:\n\n def __init__(self, item):\n self.val = item.value / item.weight\n self.w = item.weight\n\n def __lt__(self, other):\n return self.val > other.val\n h = [Wrapper(a) for a in arr]\n heapq.heapify(h)\n value = 0\n w = 0\n while w < W and h:\n item = heapq.heappop(h)\n tmp = min(item.w, W - w)\n w += tmp\n value += tmp * item.val\n return value", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n total_value = 0.0\n current_weight = 0\n for i in range(n):\n if current_weight + arr[i].weight <= W:\n current_weight += arr[i].weight\n total_value += arr[i].value\n else:\n remaining_weight = W - current_weight\n fraction = remaining_weight / arr[i].weight\n total_value += fraction * arr[i].value\n break\n return total_value", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n result = 0\n current_cap = W\n for i in arr:\n if i.weight <= current_cap:\n current_cap -= i.weight\n result += i.value\n else:\n result += i.value * (current_cap / i.weight)\n break\n return result", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, Items, n):\n Items.sort(key=lambda x: x.value / x.weight, reverse=True)\n res = 0\n for i in Items:\n if i.weight <= W:\n res += i.value\n W -= i.weight\n else:\n temp = i.value / i.weight * W\n res += temp\n W = 0\n return res", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n i = 0\n res = 0\n while W > 0 and i < n and (arr[i].weight <= W):\n W -= arr[i].weight\n res += arr[i].value\n i += 1\n if W > 0 and i < n:\n res += arr[i].value * (W / arr[i].weight)\n return res", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n val = []\n for i in range(n):\n val.append([arr[i].value / arr[i].weight, arr[i].weight, arr[i].value])\n\n def sort(arr1):\n arr1 = sorted(arr1, key=lambda x: x[0], reverse=True)\n return arr1\n val1 = sort(val)\n pro = 0\n for i in range(n):\n if W >= val1[i][1]:\n W -= val1[i][1]\n pro = pro + val1[i][2]\n else:\n pro = pro + val1[i][2] * W / val1[i][1]\n break\n return pro", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n ratios = []\n for i in range(n):\n ratios.append([i, arr[i].value / arr[i].weight])\n ratios = sorted(ratios, key=lambda x: x[1], reverse=True)\n (capacity, value) = (0, 0)\n for i in range(len(ratios)):\n if capacity + arr[ratios[i][0]].weight < W:\n value += arr[ratios[i][0]].value\n capacity += arr[ratios[i][0]].weight\n else:\n x = W - capacity\n value += x * ratios[i][1]\n break\n return value", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n l = []\n for i in arr:\n l.append((i.value / i.weight, i.value, i.weight))\n l = sorted(l, key=lambda x: x[0], reverse=True)\n cap = 0\n for i in l:\n if i[2] > W:\n val = i[0] * W\n cap += val\n W = 0\n break\n cap += i[1]\n W -= i[2]\n return cap", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n\n def myfunct(ele):\n return ele.value / ele.weight\n arr.sort(reverse=True, key=myfunct)\n ans = 0\n for i in arr:\n if i.weight <= W:\n ans += i.value\n W -= i.weight\n else:\n ans += W * (i.value / i.weight)\n break\n return ans", "import math\n\ndef __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.weight / x.value, reverse=False)\n p = 0\n for i in arr:\n if i.weight <= W:\n p += i.value\n W -= i.weight\n elif i.weight > W:\n p += W / i.weight * i.value\n W = 0\n break\n return p", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n curr_weight = 0\n max_value = 0\n for i in range(n):\n if arr[i].weight + curr_weight <= W:\n curr_weight += arr[i].weight\n max_value += arr[i].value\n else:\n left_weight = W - curr_weight\n max_value += arr[i].value * left_weight / arr[i].weight\n break\n return max_value", "import heapq\n\ndef __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n heap = []\n for (i, item) in enumerate(arr):\n heap.append([-item.value / item.weight, i])\n heapq.heapify(heap)\n remaining_capacity = W\n res = 0\n while heap and remaining_capacity > 0:\n (value_per_weight, index) = heapq.heappop(heap)\n value_per_weight *= -1\n if arr[index].weight > remaining_capacity:\n res += value_per_weight * remaining_capacity\n break\n else:\n res += arr[index].value\n remaining_capacity -= arr[index].weight\n return res", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n s = ans = wt = 0\n fact = []\n for i in range(n):\n fact.append([arr[i].value / arr[i].weight, i])\n fact = sorted(fact, reverse=True)\n for i in range(n):\n if wt + arr[fact[i][1]].weight <= W:\n ans += arr[fact[i][1]].value\n wt += arr[fact[i][1]].weight\n else:\n x = W - wt\n ans += fact[i][0] * x\n break\n return ans", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, Items, n):\n Items.sort(key=lambda x: x.value / x.weight, reverse=True)\n value = 0\n for item in Items:\n if item.weight <= W:\n W -= item.weight\n value += item.value\n elif item.weight > W:\n value += item.value * W / item.weight\n W = 0\n break\n return value", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef __str__():\n return str(self.value)\n\ndef __repr__():\n return 'Item value:% s weight:% s' % (self.value, self.weight)\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda item: item.value / item.weight, reverse=True)\n idx = 0\n value = 0.0\n while W > 0 and idx < len(arr):\n if arr[idx].weight <= W:\n value += arr[idx].value\n W -= arr[idx].weight\n else:\n value += W / arr[idx].weight * arr[idx].value\n W -= W", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n vw = []\n for i in range(n):\n v = arr[i].value\n w = arr[i].weight\n vw.append([v / w, v, w])\n vw.sort()\n vw.reverse()\n ans = 0\n for (r, v, w) in vw:\n if W - w >= 0:\n ans += v\n W -= w\n else:\n ans += W / w * v\n break\n return ans", "from operator import itemgetter\n\ndef __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, N):\n values = []\n weight = []\n for i in range(n):\n values.append(arr[i].value)\n weight.append(arr[i].weight)\n valuability = []\n for i in range(len(values)):\n valuability.append([values[i] / weight[i], weight[i]])\n res = sorted(valuability, key=itemgetter(0), reverse=True)\n total = 0\n for i in res:\n if i[1] < W:\n W -= i[1]\n total += i[0] * i[1]\n elif W > 0:\n total += i[0] * W\n W = 0\n return total", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n ans = []\n for i in range(0, n):\n perunit = arr[i].value / arr[i].weight\n ans.append([perunit, arr[i].value, arr[i].weight])\n ans.sort(key=lambda x: x[0], reverse=True)\n total = 0\n for i in range(0, n):\n if ans[i][2] > W:\n total += W * ans[i][0]\n W = 0\n else:\n total += ans[i][1]\n W -= ans[i][2]\n return total", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n curweight = 0\n a = []\n for i in range(n):\n v = [arr[i].value, arr[i].weight]\n a.append(v)\n a.sort(key=lambda x: x[0] / x[1], reverse=True)\n i = 0\n finalvalue = 0\n while curweight < W and i < n:\n if curweight + a[i][1] < W:\n curweight = curweight + a[i][1]\n finalvalue += a[i][0]\n else:\n new = W - curweight\n finalvalue += a[i][0] * new / a[i][1]\n curweight += new\n i += 1\n return finalvalue", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n (u, tp) = (W, 0)\n dp = [0] * n\n i = 0\n while i < n:\n if arr[i].weight > u:\n break\n dp[i] = 1\n tp += arr[i].value\n u -= arr[i].weight\n i += 1\n if i < n:\n dp[i] = u / arr[i].weight\n tp += dp[i] * arr[i].value\n return tp", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr = sorted(arr, key=lambda x: x.value / x.weight, reverse=True)\n rem_weight = W\n tot_value = 0\n i = 0\n while rem_weight > 0:\n if i == n:\n return tot_value\n if arr[i].weight < rem_weight:\n rem_weight -= arr[i].weight\n tot_value = tot_value + arr[i].value\n i += 1\n else:\n alpha = arr[i].value / arr[i].weight\n tot_value = tot_value + rem_weight * alpha\n break\n return tot_value", "def __init__(val, w):\n self.value = val\n self.weight = w\n self.valForMoney = val / weight\n\ndef fractionalknapsack(W, arr, n):\n arr = [(i.value / i.weight, i) for i in arr]\n arr.sort(key=lambda a: -a[0])\n profits = 0\n for i in arr:\n if i[1].weight <= W:\n (W, profits) = (W - i[1].weight, profits + i[1].value)\n elif W == 0:\n break\n else:\n (W, profits) = (0, profits + W * i[0])\n return profits", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.weight / x.value)\n curr = W\n i = 0\n rw = 0\n while curr != 0.0 and i < n:\n if arr[i].weight <= curr:\n curr -= arr[i].weight\n rw += arr[i].value\n i += 1\n else:\n rw += curr / arr[i].weight * arr[i].value\n return rw\n return rw", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n frec = []\n for i in range(n):\n perUnit = arr[i].value / arr[i].weight\n frec.append([perUnit, arr[i].value, arr[i].weight])\n totalVal = 0\n frec.sort(key=lambda x: x[0], reverse=True)\n for i in range(n):\n if frec[i][2] > W:\n totalVal += W * frec[i][0]\n W = 0\n else:\n totalVal += frec[i][1]\n W = W - frec[i][2]\n return totalVal", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n rat = [[it.weight, it.value, it.value / it.weight] for it in arr]\n sor = sorted(rat, key=lambda itm: itm[2], reverse=True)\n cur_cap = W\n total_val = 0\n for i in range(n):\n if sor[i][0] <= cur_cap:\n total_val += sor[i][1]\n cur_cap -= sor[i][0]\n else:\n wt = cur_cap\n total_val += wt * sor[i][2]\n break\n return total_val", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda a: a.value / a.weight, reverse=True)\n result = 0.0\n for item in arr:\n if W == 0:\n return result\n if item.weight <= W:\n result += item.value\n W -= item.weight\n else:\n result += item.value * W / item.weight\n W = 0\n return result", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n l = []\n profit = 0\n for i in arr:\n l.append((i.value, i.weight, i.value / i.weight))\n l.sort(key=lambda x: x[2], reverse=True)\n for (i, j, k) in l:\n if j <= W:\n profit += i\n W -= j\n else:\n profit += k * W\n W = 0\n break\n return profit", "def __init__(val, w):\n self.value = val\n self.weight = w\n self.unit = 0\n\ndef fractionalknapsack(W, arr, n):\n for i in range(n):\n arr[i].unit = arr[i].value / arr[i].weight\n ans = 0\n arr.sort(key=lambda x: -x.unit)\n i = 0\n while i < n and W > 0:\n ans += arr[i].unit * min(arr[i].weight, W)\n W -= arr[i].weight\n i += 1\n return ans", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n res = 0\n for elem in arr:\n if elem.weight <= W:\n res += elem.value\n W -= elem.weight\n else:\n res += elem.value / elem.weight * W\n return res\n return res", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n new_arr = []\n val = 0\n for i in range(n):\n compute = arr[i].value / arr[i].weight\n new_arr.append([compute, i])\n new_arr.sort(reverse=True)\n s = 0\n for i in range(n):\n y = arr[new_arr[i][1]].weight\n if W >= s + y:\n val += arr[new_arr[i][1]].value\n s += y\n else:\n val += (W - s) * new_arr[i][0]\n break\n return val", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n data = [[e.value, e.weight, e.value / e.weight] for e in arr]\n data.sort(key=lambda x: x[2], reverse=True)\n k = 0\n res = 0\n while W != 0 and k < n:\n if data[k][1] <= W:\n res += data[k][0]\n W -= data[k][1]\n k += 1\n else:\n res += data[k][2] * W\n W = 0\n break\n return res", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n new_arr = []\n for obj in arr:\n new_arr.append((obj.value / obj.weight, obj))\n new_arr.sort(key=lambda x: -x[0])\n total_value = 0\n for (per_unit_val, obj) in new_arr:\n if obj.weight <= W:\n total_value += obj.value\n W -= obj.weight\n else:\n total_value += W * per_unit_val\n W = 0\n break\n return total_value", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef __repr__():\n return '(' + str(self.value) + ',' + str(self.weight) + ')'\n\ndef fractionalknapsack(W, arr, n):\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n sum_value = 0.0\n curr_wt = 0.0\n for item in arr:\n if curr_wt + item.weight <= W:\n sum_value += item.value\n curr_wt += item.weight\n else:\n remain = W - curr_wt\n sum_value += item.value / item.weight * remain\n break\n return sum_value", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n new_arr = []\n for i in range(n):\n per_unit_val = arr[i].value / arr[i].weight\n new_arr.append((per_unit_val, arr[i]))\n new_arr.sort(key=lambda x: x[0], reverse=True)\n total_value = 0\n for i in range(n):\n if new_arr[i][1].weight > W:\n total_value += W * new_arr[i][0]\n W = 0\n break\n else:\n total_value += new_arr[i][1].value\n W -= new_arr[i][1].weight\n return total_value", "from heapq import heapify, heappop, heappush\n\ndef __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n ans = 0\n heap = []\n for i in range(n):\n a = arr[i].value / arr[i].weight\n heappush(heap, [-a, arr[i].weight])\n while heap and W > 0:\n (a, b) = heappop(heap)\n x = min(W, b)\n ans += -a * x\n W -= x\n return ans", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n d = 0\n arr.sort(key=lambda x: x.value / x.weight, reverse=True)\n for sack in arr:\n if W == 0:\n return d\n if sack.weight > W:\n d += W * (sack.value / sack.weight)\n W = 0\n break\n else:\n W -= sack.weight\n d += sack.value\n return d", "def __init__(val, w):\n self.value = val\n self.weight = w\n\ndef fractionalknapsack(W, arr, n):\n ratios = [(item.value / item.weight, item.value, item.weight) for item in arr]\n ratios.sort(reverse=True)\n total_value = 0\n remaining_weight = W\n for (ratio, value, weight) in ratios:\n if remaining_weight == 0:\n break\n elif weight <= remaining_weight:\n total_value += value\n remaining_weight -= weight\n else:\n total_value += ratio * remaining_weight\n remaining_weight = 0\n return total_value"], "starter_code": "def __init__(val,w):\n", "input_output": {"inputs": ["N = 3, W = 50\r\nvalues[] = {60,100,120}\r\nweight[] = {10,20,30}", "N = 2, W = 50\r\nvalues[] = {60,100}\r\nweight[] = {10,20}"], "outputs": ["240.00", "160.00"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Greedy"], "name": null, "source": "geeksforgeeks", "tags": ["Greedy algorithms"], "skill_types": ["Greedy algorithms"], "url": "https://practice.geeksforgeeks.org/problems/fractional-knapsack-1587115620/1", "Expected Auxiliary Space": "O(1)", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(NlogN)", "entry_point": "__init__", "task_id": "TACO_lite/507", "example": [[], []]} +{"requirement": "# Convert number to reversed array of digits\n\nGiven a random non-negative number, you have to return the digits of this number within an array in reverse order.\n\n## Example:\n\n```\n348597 => [7,9,5,8,4,3]\n```", "solutions": ["def digitize(n):\n return [int(x) for x in str(n)[::-1]]", "def digitize(n):\n return [int(x) for x in reversed(str(n))]", "def digitize(n):\n result = []\n while n >= 1:\n result.append(n % 10)\n n //= 10\n return result", "def digitize(n):\n return [int(c) for c in str(n)[::-1]]", "def digitize(n):\n l = []\n m = []\n n = str(n)\n n = n[::-1]\n for i in range(len(n)):\n l.append(int(n[i]))\n return l", "def digitize(n):\n return [int(i) for i in str(n)][::-1]", "def digitize(n):\n return list(reversed([int(s) for s in str(n)]))", "def digitize(n):\n mylist = [int(i) for i in str(n)]\n mylist.reverse()\n return mylist", "def digitize(n):\n (d, r) = divmod(n, 10)\n if d:\n return [r] + digitize(d)\n else:\n return [r]", "def digitize(n):\n new_list = list((int(x) for x in str(n)))\n return new_list[::-1]", "import re\n\ndef digitize(n):\n answer = []\n l = re.findall('\\\\d', str(n))\n for i in l:\n answer.append(int(i))\n answer.reverse()\n return answer", "def digitize(n):\n num_array = []\n for number in str(n):\n num_array.insert(0, int(number))\n return num_array", "def digitize(n):\n result = []\n while n > 0:\n result.append(n % 10)\n n = int(n / 10)\n return result", "digitize = lambda n: [int(e) for e in str(n)[::-1]]", "digitize = lambda n: [int(x) for x in str(n)][::-1]", "def digitize(n):\n n = str(n)\n arr = []\n for u in n:\n arr.append(int(u))\n arr = arr[::-1]\n return arr", "digitize = lambda n: [int(x) for x in reversed(str(n))]", "def digitize(n):\n return [int(digit) for digit in str(n)[::-1]]", "def digitize(n):\n return [int(d) for d in str(n)[::-1]]", "digitize = lambda n: list(reversed([int(i) for i in str(n)]))", "def digitize(n):\n return [int(i) for i in reversed(str(n))]", "def digitize(n):\n k = [int(num) for num in str(n)]\n k.reverse()\n return k", "def digitize(n):\n b = []\n for i in str(n):\n b.append(int(i))\n return b[::-1]", "def digitize(n):\n output = []\n for digit in str(n):\n output.append(int(digit))\n return output[::-1]", "def digitize(n):\n n = str(n)\n n_list = list(map(int, str(n)))\n n_list.reverse()\n return n_list", "def digitize(n):\n n = str(n)\n l = []\n c = list(n)\n c.reverse()\n for i in c:\n l.append(int(i))\n return l", "def digitize(n):\n a = []\n while n != 0:\n a.append(n % 10)\n n = n // 10\n return a", "def digitize(n):\n arr = []\n result = n\n shouldGo = True\n while shouldGo:\n arr.append(result % 10)\n result = result // 10\n if result == 0:\n shouldGo = False\n return arr", "def digitize(n):\n arr = []\n convertToString = str(n)\n for num in convertToString:\n arr.append(int(num))\n arr.reverse()\n return arr", "def digitize(n):\n return list(map(int, str(n)))[::-1]", "def digitize(n):\n d = [int(i) for i in str(n)]\n p = d[::-1]\n return p", "def digitize(n):\n result = []\n for d in str(n)[::-1]:\n result.append(int(d))\n return result", "def digitize(n):\n lista = str(n)\n listan = list(lista)\n listan.reverse()\n for i in range(0, len(listan)):\n listan[i] = int(listan[i])\n return listan", "def digitize(n):\n n = str(n)\n digits = [int(s) for s in n]\n return digits[::-1]", "def digitize(n):\n return [n % 10] + digitize(n // 10) if n > 10 else [n % 10]", "def digitize(n):\n ls = list(str(n))\n a = ls[::-1]\n return [int(x) for x in a]", "def digitize(n):\n r = []\n res = str(n)\n for i in res:\n r.append(int(i))\n return r[::-1]", "def digitize(n):\n a = [int(x) for x in str(n)]\n b = a[::-1]\n return b", "def digitize(n):\n num = []\n z = str(n)\n for i in z:\n num.append(int(i))\n return num[::-1]", "def digitize(n):\n x = str(n)\n y = ''\n lst = []\n for char in x:\n y = char + y\n for char in y:\n lst.append(int(char))\n return lst", "def digitize(n):\n result = array = [int(x) for x in str(n)]\n result = result[::-1]\n return result", "digitize = lambda input: [int(x) for x in str(input)][::-1]", "def digitize(n):\n rez = []\n for i in list(str(n)[::-1]):\n rez.append(int(i))\n return rez", "def digitize(n):\n x = ','.join(str(n))[::-1]\n result = []\n for i in x.split(','):\n result.append(int(i))\n return result", "def digitize(n):\n str_arr = list(str(n)[::-1])\n int_arr = []\n for i in str_arr:\n int_arr.append(int(i))\n return int_arr", "def digitize(num):\n if len(str(num)) == 1:\n return num\n output = []\n for n in reversed(str(num)):\n output.append(int(n))\n return output", "def digitize(n):\n results = []\n for num in str(n)[::-1]:\n results.append(int(num))\n return results", "def digitize(n):\n results = []\n for x in range(len(str(n))):\n results.append(int(str(n)[len(str(n)) - x - 1]))\n return results", "def digitize(n):\n string_of_int = str(n)\n final_array = [int(x) for x in string_of_int]\n return final_array[::-1]", "def digitize(n):\n list = []\n while n > 0:\n list.append(int(n % 10))\n n = int(n / 10)\n return list", "def digitize(n):\n n = str(n)\n l = list()\n n = n[::-1]\n for s in n:\n l.append(int(s))\n return l", "def digitize(n):\n num = [int(m) for m in str(n)]\n return num[::-1]", "def digitize(n):\n mylist = []\n a = list(str(n))\n for i in a:\n mylist.append(int(i))\n mylist.reverse()\n return mylist", "def digitize(n):\n d = [int(array) for array in list(str(n))]\n d.reverse()\n return d", "def digitize(n):\n a = list(reversed(str(n)))\n k = []\n for i in a:\n k.append(int(i))\n return k", "def digitize(n):\n string_num = str(n)\n digits = []\n for digit in string_num:\n digits.append(int(digit))\n digits.reverse()\n return digits", "def digitize(n):\n n = str(n)\n n = list(n)\n n = list(map(conv, n))\n n.reverse()\n return n\n\ndef conv(x):\n return int(x)", "def digitize(n):\n copy = []\n array = list(str(n))\n for num in array:\n copy.append(int(num))\n copy.reverse()\n return copy", "def digitize(n):\n lista = list(str(n))\n lista.reverse()\n int_list = []\n for i in lista:\n int_list.append(int(i))\n return int_list", "def digitize(n):\n list_n = list(str(n))\n list_n.reverse()\n return list(map(int, list_n))", "def digitize(n):\n string_num = str(n)\n res = []\n comp = [res.append(int(number)) for number in string_num]\n res.reverse()\n return res", "def digitize(n):\n empty = []\n n = str(n)\n n = n[::-1]\n for num in n:\n empty.append(int(num))\n return empty", "def digitize(n):\n s = list(reversed(str(n)))\n a = []\n for x in s:\n m = int(x)\n a.append(m)\n return a", "def digitize(n):\n result = []\n if n == 0:\n return [0]\n while n:\n result.append(n % 10)\n n //= 10\n return result", "def digitize(n):\n n = str(n)\n n = n[::-1]\n n = ' '.join(n)\n return [int(i) for i in n.split()]", "def digitize(n):\n x = list(str(n))\n y = []\n for i in range(len(x) - 1, -1, -1):\n y.append(int(x[i]))\n return y", "import numpy as np\n\ndef digitize(n):\n return [int(i) for i in str(n)[::-1]]", "def digitize(n):\n x = list(map(lambda x: int(x), list(str(n))))\n x.reverse()\n return x", "def digitize(n):\n ls = []\n for i in range(len(str(n))):\n ls.append(n % 10)\n n //= 10\n return ls", "def digitize(n):\n s = str(n)\n a = []\n for i in range(1, len(s) + 1):\n a.append(s[-i])\n for j in range(len(a)):\n a[j] = int(a[j])\n return a", "def digitize(n):\n listn = []\n for x in str(n):\n listn.append(int(x))\n revl = listn[::-1]\n return revl", "def digitize(n):\n arr = list(str(n))\n rev = []\n for i in arr:\n rev.insert(0, int(i))\n return rev", "def digitize(n):\n result = list((int(x) for x in str(n)))\n return result[::-1]", "def digitize(n):\n res = [int(i) for i in list(str(n))]\n return res[::-1]", "def digitize(n):\n num_list = list(str(n))\n reversed_num_list = num_list.reverse()\n reversed_num_list = list(map(int, num_list))\n return reversed_num_list", "def digitize(n):\n lst = []\n n = str(n)\n for char in n:\n lst.append(int(char))\n lst = lst[::-1]\n return lst", "def digitize(n):\n array = []\n n = str(n)\n x = len(n) - 1\n while x >= 0:\n array.append(int(n[x]))\n x -= 1\n return array", "def digitize(n):\n n = str(n)\n l = []\n for elem in n:\n l.append(int(elem))\n l.reverse()\n return l", "digitize = lambda n: [int(digit) for digit in str(n)][::-1]", "def digitize(n):\n n = list(str(n))\n l = []\n for i in n:\n a = int(i)\n l.append(a)\n return l[::-1]", "def digitize(n):\n new = []\n for I in str(n):\n new.append(int(I))\n return new[::-1]", "def digitize(n):\n len_n = str(n)\n list = []\n for i in range(0, len(len_n)):\n a = n % 10\n n = n // 10\n list.append(a)\n return list"], "starter_code": "def digitize(n):\n", "input_output": {"fn_name": "digitize", "inputs": [[35231], [23582357], [984764738], [45762893920], [548702838394]], "outputs": [[[1, 3, 2, 5, 3]], [[7, 5, 3, 2, 8, 5, 3, 2]], [[8, 3, 7, 4, 6, 7, 4, 8, 9]], [[0, 2, 9, 3, 9, 8, 2, 6, 7, 5, 4]], [[4, 9, 3, 8, 3, 8, 2, 0, 7, 8, 4, 5]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/5583090cbe83f4fd8c000051", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "digitize", "task_id": "TACO_lite/510", "example": [[[348597]], ["[7, 9, 5, 8, 4, 3]"]]} +{"requirement": "You need to play around with the provided string (s).\n\nMove consonants forward 9 places through the alphabet.\nIf they pass 'z', start again at 'a'.\n\nMove vowels back 5 places through the alphabet.\nIf they pass 'a', start again at 'z'.\nFor our Polish friends this kata does not count 'y' as a vowel.\n\nExceptions:\n\nIf the character is 'c' or 'o', move it back 1 place.\nFor 'd' move it back 3, and for 'e', move it back 4.\n\nIf a moved letter becomes 'c', 'o', 'd' or 'e', revert it back to it's original value.\n\nProvided string will always be lower case, won't be empty and will have no special characters.", "solutions": ["def vowel_back(st):\n return st.translate(str.maketrans('abcdefghijklmnopqrstuvwxyz', 'vkbaafpqistuvwnyzabtpvfghi'))", "def vowel_back(s):\n return s.translate(str.maketrans('abcdeghjklmnopqrsuwxyz', 'vkbaapqstuvwnyzabpfghi'))", "from string import ascii_lowercase as abc\n\ndef vowel_back(st):\n return st.translate(str.maketrans(abc, 'vkbaafpqistuvwnyzabtpvfghi'))", "from collections import ChainMap\nfrom string import ascii_lowercase as al\nmove = ChainMap(dict(c=-1, o=-1, d=-3, e=-4), dict.fromkeys('aeiou', -5), dict.fromkeys(al, 9))\nnew = (al[(i + move[c]) % 26] for (i, c) in enumerate(al))\nmapping = {c: c if c2 in 'code' else c2 for (c, c2) in zip(al, new)}\n\ndef vowel_back(st):\n return ''.join(map(mapping.get, st))", "from string import ascii_lowercase as aLow\n\ndef shifterAndSrc(c):\n return (chr((ord(c) + SHIFT.get(c, DEFAULT) - 97) % 26 + 97), c)\nSHIFT = {'a': -5, 'e': -4, 'i': -5, 'o': -1, 'u': -5, 'c': -1, 'd': -3}\n(DEFAULT, REVERT) = (9, 'code')\nTABLE = str.maketrans(aLow, ''.join((c if c not in REVERT else o for (c, o) in map(shifterAndSrc, aLow))))\n\ndef vowel_back(s):\n return s.translate(TABLE)", "vowel_back = lambda s: ''.join((e[e[0] in 'code'] for e in [(chr(ord(x) - max(1, 'co de'.index(x)) if x in 'code' else 97 + (ord(x) - 97 - 5 if x in 'aiu' else ord(x) - 97 + 9) % 26), x) for x in s]))", "def vowel_back(st):\n s = ''\n for x in st:\n res = chr(ord('a') + (ord(x) - ord('a') + ((9, -1, -3)[(x == 'c') + (x == 'd') * 2], -(5, 1, 4)[(x == 'o') + (x == 'e') * 2])[x in 'aoiue']) % 26)\n if res in 'code':\n res = x\n s += res\n return s", "trans = str.maketrans('abcdeghjklmnopqrsuwxyz', 'vkbaapqstuvwnyzabpfghi')\n\ndef vowel_back(st):\n return st.translate(trans)", "from string import ascii_lowercase as alpha\nalpha = list(alpha)\nln = len(alpha)\nvowels = 'aeiou'\n\ndef vowel_back(s):\n s = list(s)\n for (idx, char) in enumerate(s):\n index = alpha.index(char)\n if char in ('c', 'o'):\n s[idx] = alpha[index - 1]\n elif char == 'd':\n s[idx] = alpha[index - 3]\n elif char == 'e':\n s[idx] = alpha[index - 4]\n elif char in vowels:\n s[idx] = alpha[index - 5]\n else:\n index += 9\n index = index % ln\n s[idx] = alpha[index]\n if s[idx] in ('c', 'o', 'd', 'e'):\n s[idx] = char\n return ''.join(s)"], "starter_code": "def vowel_back(st):\n", "input_output": {"fn_name": "vowel_back", "inputs": [["testcase"], ["codewars"], ["exampletesthere"], ["returnofthespacecamel"], ["bringonthebootcamp"], ["weneedanofficedog"]], "outputs": [["tabtbvba"], ["bnaafvab"], ["agvvyuatabtqaaa"], ["aatpawnftqabyvbabvvau"], ["kaiwpnwtqaknntbvvy"], ["fawaaavwnffibaanp"]]}, "difficulty": "EASY", "raw_tags": ["Strings", "Fundamentals", "Algorithms", "Arrays"], "name": null, "source": "codewars", "tags": ["String algorithms", "Fundamentals", "Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/57cfd92c05c1864df2001563", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "vowel_back", "task_id": "TACO_lite/357", "example": [[["hello"], ["programming"]], ["qauun", "yanpavvviwp"]]} +{"requirement": "Implement a function which behaves like the uniq command in UNIX.\n\nIt takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance.\n\nExample:\n\n```\n[\"a\", \"a\", \"b\", \"b\", \"c\", \"a\", \"b\", \"c\"] => [\"a\", \"b\", \"c\", \"a\", \"b\", \"c\"]\n```", "solutions": ["from itertools import groupby\n\ndef uniq(seq):\n return [k for (k, _) in groupby(seq)]", "def uniq(seq):\n if len(seq) == 0:\n return []\n rez = [seq[0]]\n for i in range(1, len(seq)):\n if seq[i] != rez[-1]:\n rez.append(seq[i])\n return rez", "from itertools import groupby\n\ndef uniq(a):\n return [x for (x, _) in groupby(a)]", "def uniq(seq):\n return [c for (i, c) in enumerate(seq) if i == 0 or seq[i - 1] != c]", "def uniq(seq):\n return [seq[0]] + [seq[i] for i in range(1, len(seq)) if seq[i] != seq[i - 1]] if seq else []", "def uniq(seq):\n result = []\n for q in seq:\n if result and result[-1] == q:\n continue\n result.append(q)\n return result", "def uniq(seq):\n ans = []\n p = ''\n for i in seq:\n if i != p:\n ans.append(i)\n p = i\n return ans if len(seq) > 1 else seq", "from itertools import groupby\nfrom operator import itemgetter\n\ndef uniq(seq):\n return list(map(itemgetter(0), groupby(seq)))", "from itertools import groupby\n\ndef uniq(seq):\n return [k[0] for k in groupby(seq)]"], "starter_code": "def uniq(seq):\n", "input_output": {"fn_name": "uniq", "inputs": [[["a", "a", "b", "b", "c", "a", "b", "c", "c"]], [["a", "a", "a", "b", "b", "b", "c", "c", "c"]], [[]], [["foo"]], [["bar"]], [[""]], [[null, "a", "a"]]], "outputs": [[["a", "b", "c", "a", "b", "c"]], [["a", "b", "c"]], [[]], [["foo"]], [["bar"]], [[""]], [[null, "a"]]]}, "difficulty": "EASY", "raw_tags": ["Arrays", "Algorithms", "Filtering"], "name": null, "source": "codewars", "tags": ["Data structures"], "skill_types": ["Data structures"], "url": "https://www.codewars.com/kata/52249faee9abb9cefa0001ee", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "uniq", "task_id": "TACO_lite/476", "example": [[[["a", "a", "b", "b", "c", "a", "b", "c"]]], ["['a', 'b', 'c', 'a', 'b', 'c']"]]} +{"requirement": "Given an array (a list in Python) of integers and an integer `n`, find all occurrences of `n` in the given array and return another array containing all the index positions of `n` in the given array.\n\nIf `n` is not in the given array, return an empty array `[]`.\n\nAssume that `n` and all values in the given array will always be integers.\n\nExample:\n```python\nfind_all([6, 9, 3, 4, 3, 82, 11], 3)\n> [2, 4]\n```", "solutions": ["def find_all(array, n):\n return [index for (index, item) in enumerate(array) if item == n]", "def find_all(array, n):\n res = []\n for i in range(len(array)):\n if array[i] == n:\n res.append(i)\n return res", "def find_all(array, n):\n return [i for (i, v) in enumerate(array) if v == n]", "def find_all(array, n):\n return [i for (i, x) in enumerate(array) if x == n]", "def find_all(array, n):\n return [i for i in range(len(array)) if array[i] == n]", "def find_all(array, n):\n return [i[0] for i in enumerate(array) if i[1] == n]", "def find_all(array, n):\n l = []\n for (i, v) in enumerate(array):\n if v == n:\n l.append(i)\n return l", "import numpy as np\n\ndef find_all(array, n):\n return list(np.where(np.array(array) == n)[0])", "def find_all(array, n):\n return [pos for (pos, number) in enumerate(array) if number == n]", "def find_all(array, n):\n return [i for (i, number) in enumerate(array) if number == n]"], "starter_code": "def find_all(array, n):\n", "input_output": {"fn_name": "find_all", "inputs": [[[6, 9, 3, 4, 3, 82, 11], 3], [[6, 9, 3, 4, 3, 82, 11], 99], [[10, 16, 20, 6, 14, 11, 20, 2, 17, 16, 14], 16], [[20, 20, 10, 13, 15, 2, 7, 2, 20, 3, 18, 2, 3, 2, 16, 10, 9, 9, 7, 5, 15, 5], 20]], "outputs": [[[2, 4]], [[]], [[1, 9]], [[0, 1, 8]]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/59a9919107157a45220000e1", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "find_all", "task_id": "TACO_lite/542", "example": [[[[6, 9, 3, 4, 3, 82, 11], 3]], ["[2, 4]"]]} +{"requirement": "Given an NxN chessboard and a Knight at position (x, y). The Knight has to take exactly K steps, where at each step it chooses any of the 8 directions uniformly at random. Find the probability that the Knight remains in the chessboard after taking K steps, with the condition that it cant enter the board again once it leaves it.\n \nExample 1:\nInput : N = 8, x = 0, y = 0, K = 3\nOutput: 0.125000\nExample 2:\nInput: N = 4, x = 1, y = 2, k = 4\nOutput: 0.024414\n \nYour Task: \nYou don't need to read or print anything. Your task is to complete the function findProb() which takes N, x, y and K as input parameter and returns the probability.\n \nExpected Time Complexity : O(N ^{3})\nExpected Space Complexity: O(N^{3})\n \nConstraints:\n1 <= N <= 100\n0 <= x, y <= N\n0 <= K <= N", "solutions": ["from functools import lru_cache\n\ndef findprob(n, r, c, k):\n dir = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n\n def solve(x, y, t):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if t == 0:\n return 1\n ans = 0\n for (i, j) in dir:\n ans += solve(x + i, y + j, t - 1)\n return ans\n return solve(r, c, k) / 8 ** k", "def helper(start_x, start_y, dir_x, dir_y, dp, steps, N):\n if start_x >= 0 and start_x < N and (start_y >= 0) and (start_y < N) and (steps == 0):\n return 1\n if start_x < 0 or start_x >= N or start_y < 0 or (start_y >= N):\n return 0\n if dp[start_x][start_y][steps] != -1:\n return dp[start_x][start_y][steps]\n else:\n total_moves = 0\n for i in range(8):\n total_moves += self.helper(start_x + dir_x[i], start_y + dir_y[i], dir_x, dir_y, dp, steps - 1, N) * (1 / 8)\n dp[start_x][start_y][steps] = total_moves\n return dp[start_x][start_y][steps]\n\ndef findprob(N, start_x, start_y, steps):\n dir_x = [-2, -2, -1, -1, 1, 1, 2, 2]\n dir_y = [-1, 1, -2, 2, -2, 2, -1, 1]\n dp = [[[-1 for i in range(steps + 1)] for i in range(N + 1)] for i in range(N + 1)]\n return self.helper(start_x, start_y, dir_x, dir_y, dp, steps, N)", "from collections import defaultdict\n\ndef findprob(N, row, column, k):\n n = N\n directions = [(-2, -1), (-1, -2), (1, -2), (2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1)]\n memo = {}\n\n def dfs(i, j, k):\n if k == 0:\n return 1\n if (i, j, k) in memo:\n return memo[i, j, k]\n p = 0\n for (di, dj) in directions:\n x = i + di\n y = j + dj\n if x >= 0 and x < n and (y >= 0) and (y < n):\n p += dfs(x, y, k - 1) / 8\n memo[i, j, k] = p\n memo[n - 1 - i, j, k] = p\n memo[i, n - 1 - j, k] = p\n memo[n - 1 - i, n - 1 - j, k] = p\n return p\n return dfs(row, column, k)", "from functools import lru_cache\n\ndef findprob(n, start_x, start_y, steps):\n dir = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n\n def solve(x, y, t):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if t == 0:\n return 1\n ans = 0\n for (i, j) in dir:\n ans += solve(x + i, y + j, t - 1)\n return ans\n return solve(start_x, start_y, steps) / 8 ** steps", "def rec(N, x, y, k, dp):\n if x >= N or x < 0 or y >= N or (y < 0):\n return 0\n elif k < 0:\n return 1\n elif dp[x][y][k] != -1:\n return dp[x][y][k]\n prob = 0\n dx = [-1, -1, -2, -2, 1, 1, 2, 2]\n dy = [-2, 2, -1, 1, 2, -2, 1, -1]\n for i in range(8):\n prob += rec(N, x + dx[i], y + dy[i], k - 1, dp) / 8.0\n dp[x][y][k] = prob\n return dp[x][y][k]\n\ndef findprob(N, start_x, start_y, steps):\n dp = [[[-1 for i in range(steps)] for j in range(N)] for k in range(N)]\n return rec(N, start_x, start_y, steps - 1, dp)", "from functools import lru_cache\n\ndef is_valid(n, x, y):\n if x < 0 or x >= n or y < 0 or (y >= n):\n return False\n return True\n\ndef sol(x, y, t, n):\n dir = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n\n def solve(x, y, t):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if t == 0:\n return 1\n ans = 0\n for (i, j) in dir:\n ans += solve(x + i, y + j, t - 1)\n return ans\n return solve(x, y, t)\n\ndef findprob(N, start_x, start_y, steps):\n return self.sol(start_x, start_y, steps, N) / 8 ** steps", "def findprob(N, start_x, start_y, steps):\n dirs = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)]\n dp = [[0] * N for _ in range(N)]\n dp[start_x][start_y] = 1\n for _ in range(steps):\n newDp = [[0] * N for _ in range(N)]\n for i in range(N):\n for j in range(N):\n for (dx, dy) in dirs:\n x = i + dx\n y = j + dy\n if 0 <= x < N and 0 <= y < N:\n newDp[i][j] += dp[x][y]\n dp = newDp\n return sum(map(sum, dp)) / 8 ** steps", "def findprob(N, start_x, start_y, steps):\n dp = [[[-1 for i in range(steps + 1)] for j in range(N)] for k in range(N)]\n\n def recurs(i, j, s, dp):\n if i < 0 or i >= N or j < 0 or (j >= N):\n return 0\n elif dp[i][j][s] != -1:\n return dp[i][j][s]\n elif s == 0:\n dp[i][j][s] = 1\n return 1\n else:\n su = 0\n for a in [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]:\n su += recurs(i + a[0], j + a[1], s - 1, dp)\n dp[i][j][s] = su / 8\n return su / 8\n recurs(start_x, start_y, steps, dp)\n return dp[start_x][start_y][steps]", "def findprob(N, start_x, start_y, steps):\n dx = [1, 2, 2, 1, -1, -2, -2, -1]\n dy = [2, 1, -1, -2, -2, -1, 1, 2]\n\n def inside(x, y):\n return x >= 0 and x < N and (y >= 0) and (y < N)\n dp1 = [[[0 for i in range(steps + 5)] for j in range(N + 5)] for k in range(N + 5)]\n for i in range(N):\n for j in range(N):\n dp1[i][j][0] = 1\n for s in range(1, steps + 1):\n for x in range(N):\n for y in range(N):\n prob = 0.0\n for i in range(8):\n nx = x + dx[i]\n ny = y + dy[i]\n if inside(nx, ny):\n prob += dp1[nx][ny][s - 1] / 8.0\n dp1[x][y][s] = prob\n return dp1[start_x][start_y][steps]", "def findprob(N, start_x, start_y, steps):\n dp = [[[0] * (steps + 1) for _ in range(N)] for _ in range(N)]\n dp[start_x][start_y][0] = 1\n di = [[1, -2], [2, -1], [2, 1], [1, 2], [-1, 2], [-2, 1], [-2, -1], [-1, -2]]\n for move in range(1, steps + 1):\n for i in range(len(dp)):\n for j in range(len(dp[0])):\n for v in di:\n x = i + v[0]\n y = j + v[1]\n if x >= 0 and x < N and (y >= 0) and (y < N):\n dp[x][y][move] += dp[i][j][move - 1] / 8\n ans = 0\n for i in range(len(dp)):\n for j in range(len(dp[0])):\n ans += dp[i][j][steps]\n return ans", "def findprob(N, start_x, start_y, steps):\n r = start_x\n c = start_y\n n = N\n curr = [[0] * n for j in range(n)]\n next1 = [[0] * n for j in range(n)]\n direction = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)]\n curr[r][c] = 1\n for k in range(steps):\n for i in range(n):\n for j in range(n):\n if curr[i][j] != 0:\n for d in direction:\n ni = i + d[0]\n nj = j + d[1]\n if 0 <= ni < n and 0 <= nj < n:\n next1[ni][nj] += curr[i][j] / 8\n curr = next1\n next1 = [[0] * n for j in range(n)]\n sum1 = 0\n for i in range(n):\n for j in range(n):\n sum1 += curr[i][j]\n return sum1", "def findprob(N, x, y, k):\n dir = [(2, 1), (-2, 1), (2, -1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)]\n\n def isvalid(i, j):\n return i >= 0 and i <= N - 1 and (j >= 0) and (j <= N - 1)\n memo = {}\n\n def dfs(i, j, k):\n if (i, j, k) in memo:\n return memo[i, j, k]\n if not isvalid(i, j):\n return 0\n if k == 0:\n return 1\n prob = 0\n for (x, y) in dir:\n prob += dfs(i + x, j + y, k - 1)\n prob *= 0.125\n memo[i, j, k] = prob\n return prob\n return dfs(x, y, k)", "def findprob(N, start_x, start_y, steps):\n dp = [[[-1 for _ in range(steps + 1)] for _ in range(N)] for _ in range(N)]\n for i in range(N):\n for j in range(N):\n dp[i][j][0] = 1\n res = self.DFS(dp, N, steps, start_x, start_y) / 8 ** steps\n return res\n\ndef DFS(dp, N, steps, x, y):\n if x >= N or x < 0 or y >= N or (y < 0):\n return 0\n if dp[x][y][steps] != -1:\n return dp[x][y][steps]\n cnt = 0\n dx = [-2, -2, -1, -1, 1, 1, 2, 2]\n dy = [-1, 1, -2, 2, -2, 2, -1, 1]\n for i in range(8):\n xx = x + dx[i]\n yy = y + dy[i]\n cnt += self.DFS(dp, N, steps - 1, xx, yy)\n dp[x][y][steps] = cnt\n return cnt", "def prob(i, j, s, N):\n pij = 0\n prev = [(i - 2, j - 1), (i - 2, j + 1), (i - 1, j - 2), (i - 1, j + 2), (i + 1, j - 2), (i + 1, j + 2), (i + 2, j - 1), (i + 2, j + 1)]\n for (ii, jj) in prev:\n pij += self.dp[ii][jj][s - 1] if 0 <= ii < N and 0 <= jj < N else 0\n return pij / 8\n\ndef findprob(N, start_x, start_y, steps):\n self.dp = [[[0] * (steps + 1) for j in range(N)] for i in range(N)]\n self.dp[start_x][start_y][0] = 1\n for s in range(1, steps + 1):\n for i in range(N):\n for j in range(N):\n self.dp[i][j][s] = self.prob(i, j, s, N)\n p = 0\n for i in range(N):\n for j in range(N):\n p += self.dp[i][j][steps]\n return p", "def findprob(N, start_x, start_y, steps):\n dx = [-2, -1, +1, +2, +2, +1, -1, -2]\n dy = [+1, +2, +2, +1, -1, -2, -2, -1]\n dp = [[[0] * (steps + 1) for j in range(N)] for i in range(N)]\n for i in range(N):\n for j in range(N):\n dp[i][j][0] = 1\n for step in range(1, steps + 1):\n for x in range(N):\n for y in range(N):\n dp[x][y][step] = 0\n for i in range(8):\n newx = x + dx[i]\n newy = y + dy[i]\n if newx >= 0 and newx < N and (newy >= 0) and (newy < N):\n dp[x][y][step] += dp[newx][newy][step - 1] / 8.0\n return dp[start_x][start_y][steps]", "def findprob(N, start_x, start_y, steps):\n n = N\n k = steps\n dic = {}\n c = 0\n for x in range(n):\n for y in range(n):\n dic[x, y] = c\n c += 1\n vis = {}\n for j in range(c + 1):\n vis[j] = [-1] * (k + 1)\n\n def fun(x, y, c):\n if c == 0:\n return 1\n else:\n s = 0\n if x - 1 >= 0 and y - 2 >= 0:\n ele = dic[x - 1, y - 2]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x - 1, y - 2, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n if x - 2 >= 0 and y - 1 >= 0:\n ele = dic[x - 2, y - 1]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x - 2, y - 1, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n if x - 2 >= 0 and y + 1 < n:\n ele = dic[x - 2, y + 1]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x - 2, y + 1, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n if x - 1 >= 0 and y + 2 < n:\n ele = dic[x - 1, y + 2]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x - 1, y + 2, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n if x + 1 < n and y + 2 < n:\n ele = dic[x + 1, y + 2]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x + 1, y + 2, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n if x + 2 < n and y + 1 < n:\n ele = dic[x + 2, y + 1]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x + 2, y + 1, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n if x + 2 < n and y - 1 >= 0:\n ele = dic[x + 2, y - 1]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x + 2, y - 1, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n if x + 1 < n and y - 2 >= 0:\n ele = dic[x + 1, y - 2]\n if vis[ele][c - 1] != -1:\n s += vis[ele][c - 1] * 0.125\n else:\n a = fun(x + 1, y - 2, c - 1)\n vis[ele][c - 1] = a\n s += a * 0.125\n return s\n ans = fun(start_x, start_y, steps)\n return ans", "dct = {}\n\ndef findprob(N, start_x, start_y, steps):\n tab = [[[0 for blabla in range(N)] for blablabla in range(N)] for bla in range(steps + 1)]\n moves = [[2, -1], [2, 1], [-2, -1], [-2, 1], [1, 2], [1, -2], [-1, 2], [-1, -2]]\n for step in range(steps + 1):\n for x in range(N):\n for y in range(N):\n for move in moves:\n if step == 0:\n tab[step][x][y] = 1\n else:\n (new_x, new_y) = (x - move[0], y - move[1])\n if 0 <= new_x < N and 0 <= new_y < N:\n tab[step][x][y] += tab[step - 1][new_x][new_y] / 8\n return tab[steps][start_x][start_y]", "from functools import lru_cache\n\ndef findprob(N, start_x, start_y, steps):\n dx = [1, 2, 2, 1, -1, -2, -2, -1]\n dy = [2, 1, -1, -2, -2, -1, 1, 2]\n\n def inside(x, y):\n return x >= 0 and x < N and (y >= 0) and (y < N)\n dp = [[[0] * (steps + 1) for ele in range(N)] for m in range(N)]\n for i in range(N):\n for j in range(N):\n dp[i][j][0] = 1\n for step in range(1, steps + 1):\n for x in range(N):\n for y in range(N):\n prob = 0.0\n for i in range(8):\n nx = x + dx[i]\n ny = y + dy[i]\n if inside(nx, ny):\n prob += dp[nx][ny][step - 1] / 8.0\n dp[x][y][step] = prob\n return dp[start_x][start_y][steps]\n\ndef findprob_ok(n, x, y, steps):\n m = (n - 1) // 2\n\n def helper2(x, y, total):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if total == 0:\n return 1\n if x > m:\n x = n - 1 - x\n if y > m:\n y = n - 1 - y\n res = 0\n for (dx, dy) in [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]:\n res += helper2(x + dx, y + dy, total - 1)\n return res\n return helper2(x, y, steps) / 8 ** steps\n\ndef findprob2(n, x, y, steps):\n\n def helper(x, y, total):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if total == 0:\n return 1\n res = 0\n for (addX, addY) in [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]:\n res += helper(x + addX, y + addY, total - 1)\n return res\n return helper(x, y, steps) / 8 ** steps", "from functools import lru_cache\n\ndef findprob(n, x, y, steps):\n m = (n - 1) // 2\n\n def helper2(x, y, total):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if total == 0:\n return 1\n if x > m:\n x = n - 1 - x\n if y > m:\n y = n - 1 - y\n res = 0\n for (dx, dy) in [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]:\n res += helper2(x + dx, y + dy, total - 1)\n return res\n return helper2(x, y, steps) / 8 ** steps\n\ndef findprob2(n, x, y, steps):\n\n def helper(x, y, total):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if total == 0:\n return 1\n res = 0\n for (addX, addY) in [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]:\n res += helper(x + addX, y + addY, total - 1)\n return res\n return helper(x, y, steps) / 8 ** steps", "from functools import lru_cache\n\ndef findprob(n, r, c, k):\n\n def helper(x, y, total):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if total == 0:\n return 1\n res = 0\n for (addX, addY) in [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]:\n res += helper(x + addX, y + addY, total - 1)\n return res\n return helper(r, c, k) / 8 ** k", "def findprob(N, start_x, start_y, steps):\n prev = [[0 for i in range(N + 4)] for _ in range(N + 4)]\n curr = [[0 for i in range(N + 4)] for _ in range(N + 4)]\n for i in range(2, N + 2):\n for j in range(2, N + 2):\n prev[i][j] = 1\n for k in range(1, steps + 1):\n for i in range(2, N + 2):\n for j in range(2, N + 2):\n ans = 0\n ans += prev[i + 1][j - 2]\n ans += prev[i + 1][j + 2]\n ans += prev[i + 2][j - 1]\n ans += prev[i + 2][j + 1]\n ans += prev[i - 2][j - 1]\n ans += prev[i - 2][j + 1]\n ans += prev[i - 1][j - 2]\n ans += prev[i - 1][j + 2]\n curr[i][j] = ans\n prev = [[k for k in l] for l in curr]\n return prev[start_x + 2][start_y + 2] / pow(8, steps)", "def findprob(N, start_x, start_y, steps):\n\n def fun(i, j, k, n, dp):\n if i < 0 or i > n - 1 or j < 0 or (j > n - 1):\n return 0\n if dp[k][i][j] != -1:\n return dp[k][i][j]\n if k == 0:\n return 1\n ans = 0\n ans += fun(i + 1, j - 2, k - 1, n, dp)\n ans += fun(i + 1, j + 2, k - 1, n, dp)\n ans += fun(i + 2, j - 1, k - 1, n, dp)\n ans += fun(i + 2, j + 1, k - 1, n, dp)\n ans += fun(i - 2, j - 1, k - 1, n, dp)\n ans += fun(i - 2, j + 1, k - 1, n, dp)\n ans += fun(i - 1, j - 2, k - 1, n, dp)\n ans += fun(i - 1, j + 2, k - 1, n, dp)\n dp[k][i][j] = ans\n return dp[k][i][j]\n dp = [[[-1 for i in range(N)] for _ in range(N)] for l in range(steps + 1)]\n return fun(start_x, start_y, steps, N, dp) / pow(8, steps)", "def valid_move(n, x, y):\n return x >= 0 and x < n and (y >= 0) and (y < n)\n\ndef find_prob(n, init_x, init_y, k):\n if k == 0:\n return 1\n mx = [1, 2, 2, 1, -1, -2, -2, -1]\n my = [2, 1, -1, -2, -2, -1, 1, 2]\n dp = [[[0 for i in range(n + 64)] for j in range(n + 64)] for l in range(k + 64)]\n for i in range(n):\n for j in range(n):\n dp[i][j][0] = 1\n for s in range(1, k + 1):\n for x in range(n):\n for y in range(n):\n prob = 0.0\n for i in range(8):\n nx = x + mx[i]\n ny = y + my[i]\n if valid_move(n, nx, ny):\n prob += dp[nx][ny][s - 1] / 8.0\n dp[x][y][s] = prob\n return dp[init_x][init_y][k]\n\ndef findprob(n, init_x, init_y, k):\n return find_prob(n, init_x, init_y, k)", "def findprob(N, start_x, start_y, steps):\n dir = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n present = [[0 for i in range(N)] for j in range(N)]\n next = [[0 for i in range(N)] for j in range(N)]\n present[start_x][start_y] = 1\n for steps in range(0, steps):\n for i in range(N):\n for j in range(N):\n if present[i][j] != 0:\n for change in dir:\n newi = i + change[0]\n newj = j + change[1]\n if newi >= 0 and newi < N and (newj >= 0) and (newj < N):\n next[newi][newj] += present[i][j] / 8\n present = next\n next = [[0 for i in range(N)] for j in range(N)]\n res = 0\n for i in range(N):\n for j in range(N):\n res += present[i][j]\n return res", "def findprob(N, start_x, start_y, steps):\n\n def issafe(r, c):\n if r >= 0 and r < N and (c >= 0) and (c < N):\n return True\n return False\n curr = [[0 for i in range(N)] for j in range(N)]\n nex = [[0 for i in range(N)] for j in range(N)]\n moves = [[2, 1], [2, -1], [-2, -1], [-2, 1], [1, 2], [-1, 2], [1, -2], [-1, -2]]\n curr[start_x][start_y] = 1\n for k in range(steps):\n for i in range(N):\n for j in range(N):\n ni = 0\n nj = 0\n if curr[i][j] != 0:\n for move in moves:\n ni = i + move[0]\n nj = j + move[1]\n if issafe(ni, nj):\n nex[ni][nj] += curr[i][j] / 8\n curr[i][j] = 0\n curr = nex\n nex = [[0 for i in range(N)] for j in range(N)]\n ans = 0\n for i in range(N):\n for j in range(N):\n ans += curr[i][j]\n return ans", "def findprob(N, start_x, start_y, steps):\n dp = [[0] * N for _ in range(N)]\n dp[start_x][start_y] = 1\n for _ in range(steps):\n dp2 = [[0] * N for _ in range(N)]\n for (start_x, row) in enumerate(dp):\n for (start_y, val) in enumerate(row):\n for (dr, dc) in ((2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)):\n if 0 <= start_x + dr < N and 0 <= start_y + dc < N:\n dp2[start_x + dr][start_y + dc] += val / 8.0\n dp = dp2\n return sum(map(sum, dp))", "def valid(ni, nj, n):\n if ni < 0 or nj < 0 or nj >= n or (ni >= n):\n return False\n return True\n\ndef findprob(N, start_x, start_y, k):\n c = [[0 for i in range(N)] for j in range(N)]\n n = [[0 for i in range(N)] for j in range(N)]\n c[start_x][start_y] = 1\n for m in range(1, k + 1):\n for i in range(N):\n for j in range(N):\n if c[i][j] != 0:\n ni = i + 2\n nj = j - 1\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n ni = i + 2\n nj = j + 1\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n ni = i - 2\n nj = j - 1\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n ni = i - 2\n nj = j + 1\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n ni = i + 1\n nj = j - 2\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n ni = i + 1\n nj = j + 2\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n ni = i - 1\n nj = j + 2\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n ni = i - 1\n nj = j - 2\n if self.valid(ni, nj, N):\n n[ni][nj] += c[i][j] / 8\n c = [[n[i][j] for i in range(N)] for j in range(N)]\n n = [[0 for i in range(N)] for i in range(N)]\n s = 0\n for i in range(N):\n for j in range(N):\n s += c[i][j]\n return s", "from functools import lru_cache\n\ndef findprob(N, sx, sy, k):\n d = [(-2, -1), (1, 2), (-2, 1), (2, -1), (-1, 2), (2, 1), (1, -2), (-1, -2)]\n\n def pseudo(xc, yc, s):\n if xc < 0 or xc >= N or yc < 0 or (yc >= N):\n return 0\n if not s:\n return 1\n answ = 0\n for (a, b) in d:\n answ = answ + pseudo(xc + a, yc + b, s - 1)\n return answ\n denominator = 8 ** k\n return pseudo(sx, sy, k) / denominator", "from functools import lru_cache\n\ndef findprob(n, sx, sy, k):\n d = [(-2, -1), (1, 2), (-2, 1), (2, -1), (-1, 2), (2, 1), (1, -2), (-1, -2)]\n\n def helper(x, y, l):\n if x < 0 or x >= n or y < 0 or (y >= n):\n return 0\n if l == 0:\n return 1\n ans = 0\n for (a, b) in d:\n ans = ans + helper(x + a, y + b, l - 1)\n return ans\n total = 8 ** k\n return helper(sx, sy, k) / total", "from functools import lru_cache\n\ndef findprob(n, x, y, k):\n d = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n\n def solve(x, y, z):\n if not (0 <= x and x < n and (0 <= y) and (y < n)):\n return 0\n if z == 0:\n return 1\n ans = 0\n for (i, j) in d:\n ans += solve(x + i, y + j, z - 1)\n return ans\n return solve(x, y, k) / 8 ** k", "from functools import lru_cache\n\ndef findprob(n, x, y, steps):\n di = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n\n def solve(x, y, temp):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if temp == 0:\n return 1\n answer = 0\n for (i, j) in di:\n answer += solve(x + i, y + j, temp - 1)\n return answer\n return solve(x, y, steps) / 8 ** steps", "def findprob(N, start_x, start_y, steps):\n if steps == 0:\n return 1\n dx = [1, 1, -1, -1, 2, 2, -2, -2]\n dy = [2, -2, 2, -2, 1, -1, 1, -1]\n dp = [[[0 for i in range(steps + 1)] for j in range(N)] for k in range(N)]\n for i in range(N):\n for j in range(N):\n dp[i][j][0] = 1\n for i in range(1, steps + 1):\n for j in range(N):\n for k in range(N):\n prob = 0\n for l in range(8):\n nx = j + dx[l]\n ny = k + dy[l]\n if nx >= 0 and nx < N and (ny >= 0) and (ny < N):\n prob += dp[nx][ny][i - 1] / 8\n dp[j][k][i] = prob\n return dp[start_x][start_y][steps]", "def findprob(N, X, Y, K):\n self.N = N\n self.IncX = [+2, +2, +1, +1, -1, -1, -2, -2]\n self.IncY = [+1, -1, +2, -2, +2, -2, +1, -1]\n next = [[1] * N] * N\n for i in range(1, K + 1):\n current = next\n next = [[0] * N for r in range(N)]\n for x in range(N):\n for y in range(N):\n for d in range(8):\n next[x][y] += self.getCurrent(current, x, y, d)\n next[x][y] /= 8.0\n return next[X][Y]\n\ndef getCurrent(current, x, y, d):\n (nx, ny) = (x + self.IncX[d], y + self.IncY[d])\n if nx < 0 or N <= nx:\n return 0.0\n if ny < 0 or N <= ny:\n return 0.0\n return current[nx][ny]", "import collections\n\ndef findprob(n, r, c, k):\n dp = collections.defaultdict(float)\n\n def dfs(r, c, k):\n nonlocal n\n if r < 0 or r >= n or c < 0 or (c >= n):\n return 0\n if k == 0:\n return 1\n for (tr, tc) in [(r, c), (c, r), (n - 1 - r, c), (n - 1 - c, r), (r, n - 1 - c), (c, n - 1 - r), (n - 1 - c, n - 1 - r), (n - 1 - r, n - 1 - c)]:\n if (tr, tc, k) in dp:\n return dp[tr, tc, k]\n res = 0\n for (nr, nc) in [(r - 2, c - 1), (r - 2, c + 1), (r - 1, c + 2), (r - 1, c - 2), (r + 1, c + 2), (r + 1, c - 2), (r + 2, c - 1), (r + 2, c + 1)]:\n res += dfs(nr, nc, k - 1)\n res /= 8\n dp[r, c, k] = res\n return res\n return dfs(r, c, k)", "def find(rMax, cMax, x, y, steps, u):\n if steps == 0:\n return 1\n if u[x][y][steps] != -1:\n return u[x][y][steps]\n c = 0\n if x + 1 < rMax and y + 2 < cMax:\n c += find(rMax, cMax, x + 1, y + 2, steps - 1, u)\n if x + 1 < rMax and y - 2 >= 0:\n c += find(rMax, cMax, x + 1, y - 2, steps - 1, u)\n if x - 1 >= 0 and y + 2 < cMax:\n c += find(rMax, cMax, x - 1, y + 2, steps - 1, u)\n if x - 1 >= 0 and y - 2 >= 0:\n c += find(rMax, cMax, x - 1, y - 2, steps - 1, u)\n if x + 2 < rMax and y + 1 < cMax:\n c += find(rMax, cMax, x + 2, y + 1, steps - 1, u)\n if x + 2 < rMax and y - 1 >= 0:\n c += find(rMax, cMax, x + 2, y - 1, steps - 1, u)\n if x - 2 >= 0 and y + 1 < cMax:\n c += find(rMax, cMax, x - 2, y + 1, steps - 1, u)\n if x - 2 >= 0 and y - 1 >= 0:\n c += find(rMax, cMax, x - 2, y - 1, steps - 1, u)\n u[x][y][steps] = c\n return c\n\ndef findprob(N, start_x, start_y, steps):\n u = [[[-1 for _ in range(steps + 1)] for _ in range(N)] for _ in range(N)]\n val = find(N, N, start_x, start_y, steps, u)\n v1 = 1\n for i in range(steps):\n v1 *= 8\n return val / v1", "from functools import lru_cache\n\ndef findprob(N, start_x, start_y, steps):\n d = [(-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2)]\n\n def valid(x, y, K):\n if not (0 <= x < N and 0 <= y < N):\n return 0\n if K == 0:\n return 1\n outcome = 0\n for (i, j) in d:\n outcome += valid(x + i, y + j, K - 1)\n return outcome\n return valid(start_x, start_y, steps) / 8 ** steps", "def isValid(x, y, n):\n if x >= 0 and y >= 0 and (x < N) and (y < N):\n return True\n return False\n\ndef findprob(N, start_x, start_y, steps):\n curr_ = [[0 for _ in range(N)] for _ in range(N)]\n next_ = [[0 for _ in range(N)] for _ in range(N)]\n curr_[start_x][start_y] = 1\n for k in range(steps):\n for i in range(N):\n for j in range(N):\n if curr_[i][j] != 0:\n a = i + 2\n b = j - 1\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n a = i + 2\n b = j + 1\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n a = i - 2\n b = j - 1\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n a = i - 2\n b = j + 1\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n a = i + 1\n b = j - 2\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n a = i + 1\n b = j + 2\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n a = i - 1\n b = j - 2\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n a = i - 1\n b = j + 2\n if self.isValid(a, b, N):\n next_[a][b] += curr_[i][j] / 8\n curr_ = next_\n next_ = [[0 for _ in range(N)] for _ in range(N)]\n ans = 0\n for i in range(N):\n for j in range(N):\n ans += curr_[i][j]\n return ans", "def findprob(N, start_x, start_y, steps):\n dx = [1, 2, 2, 1, -1, -2, -2, -1]\n dy = [2, 1, -1, -2, -2, -1, 1, 2]\n\n def inside(x, y):\n return x >= 0 and x < N and (y >= 0) and (y < N)\n dp = [[[0] * (steps + 1) for ele in range(N)] for m in range(N)]\n for i in range(N):\n for j in range(N):\n dp[i][j][0] = 1\n for step in range(1, steps + 1):\n for x in range(N):\n for y in range(N):\n prob = 0.0\n for i in range(8):\n nx = x + dx[i]\n ny = y + dy[i]\n if inside(nx, ny):\n prob += dp[nx][ny][step - 1] / 8.0\n dp[x][y][step] = prob\n return dp[start_x][start_y][steps]", "def findprob(N, r, c, K):\n dp = [[0] * N for _ in range(N)]\n dp[r][c] = 1\n for _ in range(K):\n dp2 = [[0] * N for _ in range(N)]\n for (r, row) in enumerate(dp):\n for (c, val) in enumerate(row):\n for (dr, dc) in ((2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)):\n if 0 <= r + dr < N and 0 <= c + dc < N:\n dp2[r + dr][c + dc] += val / 8.0\n dp = dp2\n return sum(map(sum, dp))", "def findprob(N, start_x, start_y, steps):\n cur = [[0 for j in range(N)] for i in range(N)]\n nex = [[0 for j in range(N)] for i in range(N)]\n cur[start_x][start_y] = 1\n px = [1, 1, -1, -1, 2, -2, 2, -2]\n py = [2, -2, 2, -2, 1, 1, -1, -1]\n\n def valid(dx, dy, N):\n if (dx >= 0 and dx < N) and (dy >= 0 and dy < N):\n return True\n else:\n return False\n for m in range(steps):\n for i in range(N):\n for j in range(N):\n if cur[i][j] != 0:\n x = 0\n y = 0\n for k in range(8):\n dx = i + px[k]\n dy = j + py[k]\n if valid(dx, dy, N):\n nex[dx][dy] += cur[i][j] / 8\n cur = nex\n nex = [[0 for j in range(N)] for i in range(N)]\n su = 0\n for i in range(N):\n for j in range(N):\n su = su + cur[i][j]\n return su", "def findprob(n, r, c, k):\n\n def getvalid(cr, cc, n):\n child = []\n direction = [[2, 1], [-2, 1], [-1, 2], [1, 2], [2, -1], [-2, -1], [-1, -2], [1, -2]]\n for di in direction:\n crow = cr + di[0]\n ccol = cc + di[1]\n if 0 <= crow < n and 0 <= ccol < n:\n child.append((crow, ccol))\n return child\n prob = 1 / 8\n memo = [[0 for j in range(n)] for i in range(n)]\n memo[r][c] = 1\n for i in range(k):\n newmemo = [[0 for j in range(n)] for i in range(n)]\n for cr in range(n):\n for cc in range(n):\n for children in getvalid(cr, cc, n):\n newmemo[children[0]][children[1]] += memo[cr][cc] * prob\n memo = newmemo\n final = 0\n for row in memo:\n final += sum(row)\n return final", "from functools import lru_cache\n\ndef findprob(n, x, y, steps) -> float:\n ans = 0.0\n dirs = [(-1, -2), (-1, 2), (1, -2), (1, 2), (-2, 1), (-2, -1), (2, -1), (2, 1)]\n\n def helper(x, y, k):\n if not (0 <= x < n and 0 <= y < n):\n return 0\n if k == 0:\n return 1\n count = 0\n for (i, j) in dirs:\n count += helper(x + i, y + j, k - 1)\n return count\n return helper(x, y, steps) / 8 ** steps", "def getProb(x, y, N, dp, s):\n dx = [1, 2, 2, 1, -1, -2, -2, -1]\n dy = [2, 1, -1, -2, -2, -1, 1, 2]\n prob = 0.0\n for i in range(8):\n nx = x + dx[i]\n ny = y + dy[i]\n if self.inside(nx, ny, N):\n prob += dp[s - 1][nx][ny] / 8.0\n return prob\n\ndef inside(x, y, N):\n return x >= 0 and x < N and (y >= 0) and (y < N)\n\ndef findprob(N, start_x, start_y, steps):\n if start_x < 0 or start_x >= N or start_y < 0 or (start_y >= N):\n return 0\n dp = [[[0] * N for _ in range(N)] for _ in range(steps + 1)]\n for i in range(N):\n for j in range(N):\n dp[0][i][j] = 1\n for s in range(1, steps + 1):\n for x in range(N):\n for y in range(N):\n dp[s][x][y] = self.getProb(x, y, N, dp, s)\n return dp[steps][start_x][start_y]", "def on_board(i, j, N):\n return 0 <= i < N and 0 <= j < N\n\ndef findprob(N, start_x, start_y, steps):\n probs = [[[0 for i in range(N)] for j in range(N)] for k in range(steps + 1)]\n probs[0][start_y][start_x] = 1\n for k in range(steps):\n for i in range(N):\n for j in range(N):\n if probs[k][i][j] != 0:\n for d in self.dirs:\n if self.on_board(i + d[0], j + d[1], N):\n probs[k + 1][i + d[0]][j + d[1]] += probs[k][i][j] / 8\n total_prob = 0\n for i in range(N):\n for j in range(N):\n total_prob += probs[-1][i][j]\n return total_prob"], "starter_code": "def findprob(N, start_x, start_y, steps):\n", "input_output": {"inputs": ["N = 8, x = 0, y = 0, K = 3", "N = 4, x = 1, y = 2, k = 4"], "outputs": ["0.125000", "0.024414"]}, "difficulty": "MEDIUM", "raw_tags": ["Algorithms", "Dynamic Programming"], "name": null, "source": "geeksforgeeks", "tags": ["Dynamic programming"], "skill_types": ["Dynamic programming"], "url": "https://practice.geeksforgeeks.org/problems/probability-of-knight5529/1", "Expected Auxiliary Space": "O(N^{3})", "time_limit": null, "date": null, "picture_num": "0", "memory_limit": null, "Expected Time Complexity": "O(N ^{3})", "entry_point": "findprob", "task_id": "TACO_lite/480", "example": [[[8, 0, 0, 3], [4, 1, 2, 4]], [0.125, 0.0244140625]]} +{"requirement": "Define a function that takes one integer argument and returns logical value `true` or `false` depending on if the integer is a prime.\n\nPer Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.\n\n## Requirements\n\n* You can assume you will be given an integer input.\n* You can not assume that the integer will be only positive. You may be given negative numbers as well (or `0`).\n* **NOTE on performance**: There are no fancy optimizations required, but still *the* most trivial solutions might time out. Numbers go up to 2^31 (or similar, depends on language version). Looping all the way up to `n`, or `n/2`, will be too slow.\n\n## Example\n```nasm \nmov edi, 1\ncall is_prime ; EAX <- 0 (false)\n\nmov edi, 2\ncall is_prime ; EAX <- 1 (true)\n\nmov edi, -1\ncall is_prime ; EAX <- 0 (false)\n```", "solutions": ["import random\n\ndef even_odd(n):\n (s, d) = (0, n)\n while d % 2 == 0:\n s += 1\n d >>= 1\n return (s, d)\n\ndef Miller_Rabin(a, p):\n (s, d) = even_odd(p - 1)\n a = pow(a, d, p)\n if a == 1:\n return True\n for i in range(s):\n if a == p - 1:\n return True\n a = pow(a, 2, p)\n return False\n\ndef is_prime(p):\n if p == 2:\n return True\n if p <= 1 or p % 2 == 0:\n return False\n return all((Miller_Rabin(random.randint(2, p - 1), p) for _ in range(40)))", "from math import sqrt\n\ndef is_prime(num):\n if num <= 1:\n return False\n i = 2\n while i <= sqrt(num):\n if num % i == 0:\n return False\n i += 1\n return True", "import math\n\ndef is_prime(n):\n if n < 2:\n return False\n if n in [2, 3]:\n return True\n if n % 6 not in [1, 5]:\n return False\n for i in range(3, int(math.floor(math.sqrt(n))) + 1):\n if n % i == 0:\n return False\n return True", "def is_prime(n):\n if n < 2 or (n > 2 and n % 2 == 0):\n return False\n for i in range(3, int(n ** 0.5) + 1, 2):\n if n % i == 0:\n return False\n else:\n return True", "def is_prime(num):\n num = abs(int(num))\n if num < 2:\n return False\n if num == 2:\n return True\n if not num & 1:\n return False\n for x in range(3, int(num ** 0.5) + 1, 2):\n if num % x == 0:\n return False\n return True", "import math\n\ndef is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True"], "starter_code": "def is_prime(num):\n", "input_output": {"fn_name": "is_prime", "inputs": [[0], [1], [2], [73], [75], [-1]], "outputs": [[false], [false], [true], [true], [false], [false]]}, "difficulty": "EASY", "raw_tags": ["Mathematics", "Algorithms"], "name": null, "source": "codewars", "tags": ["Mathematics"], "skill_types": [], "url": "https://www.codewars.com/kata/5262119038c0985a5b00029f", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "is_prime", "task_id": "TACO_lite/521", "example": [[], []]} +{"requirement": "In this kata, your task is to write a function `to_bytes(n)` (or `toBytes(n)` depending on language) that produces a list of bytes that represent a given non-negative integer `n`. Each byte in the list is represented by a string of `'0'` and `'1'` of length 8. The most significant byte is first in the list. The example test cases should provide you with all the details. You may assume that the argument `n` is valid.", "solutions": ["def to_bytes(n):\n if not n:\n return ['00000000']\n res = []\n while n:\n res.append('{:08b}'.format(n % 256))\n n //= 256\n return res[::-1]", "import re\nfrom math import ceil\n\ndef to_bytes(n):\n return re.findall('.{8}', '{:0{}b}'.format(n, int(8 * ceil(n.bit_length() / 8.0)))) or [8 * '0']", "to_bytes = b = lambda n, f=1: n and b(n >> 8, 0) + [format(n & 255, '08b')] or ['0' * 8] * f", "def to_bytes(n):\n b = bin(n)[2:]\n b = '0' * (8 - len(b) % 8) * (len(b) % 8 != 0) + b\n return [b[8 * i:8 * i + 8] for i in range(len(b) // 8)]", "def to_bytes(n):\n L = 8\n s = bin(n)[2:]\n s = s.rjust(len(s) + L - 1 - (len(s) - 1) % 8, '0')\n return [s[i:i + L] for i in range(0, len(s), L)]", "def to_bytes(n):\n if n == 0:\n return ['00000000']\n s = bin(n)[2:]\n s = s.rjust(len(s) + 7 - (len(s) - 1) % 8, '0')\n return [s[i:i + 8] for i in range(0, len(s), 8)]", "to_bytes = lambda n, d=__import__('itertools').dropwhile: list(d(('0' * 8).__eq__, map(''.join, zip(*[iter(bin(n)[2:].zfill(8 * ((len(bin(n)) - 2) // 8 + 1)))] * 8)))) or ['0' * 8]", "def to_bytes(n):\n return [''.join(t) for t in zip(*[iter(format(n, '0{}b'.format((max(1, n.bit_length()) + 7) // 8 * 8)))] * 8)]"], "starter_code": "def to_bytes(n):\n", "input_output": {"fn_name": "to_bytes", "inputs": [[0], [1]], "outputs": [[["00000000"]], [["00000001"]]]}, "difficulty": "EASY", "raw_tags": ["Fundamentals"], "name": null, "source": "codewars", "tags": ["Fundamentals"], "skill_types": [], "url": "https://www.codewars.com/kata/5705601c5eef1fad69000674", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "to_bytes", "task_id": "TACO_lite/538", "example": [[[256], [255], [0], [3], [128]], ["['00000001', '00000000']", "['11111111']", "['00000000']", "['00000011']", "['10000000']"]]} +{"requirement": "You are given a set of `n` segments on the axis `Ox`, each segment has integer endpoints between `0` and `m` inclusive.\n\u2002Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers li and ri \u2014 coordinates of the left and of the right endpoints.\n\n\u2002Consider all integer points between `0` and `m` inclusive. Your task is to print all such points that don't belong to any segment. The point x belongs to the segment `[l;r]` if and only if `l \u2264 x \u2264 r`.\n\n**Input:**\n\u2002`m` \u2014 the upper bound for coordinates;\n\u2002array of coordinates li and ri `0 \u2264 li \u2264 ri \u2264 m` \u2014 the endpoints of the `i`-th segment. Segments may intersect, overlap or even coincide with each other.\n\n**Output:**\n\u2002All points from `0` to `m` that don't belong to any segment.\n\n**Examples:**\n```python\nsegments(5, [(2,2),(1,2),(5,5)]) => [0,3,4]\nsegments(7, [(0,7)]) => []\n```", "solutions": ["def segments(m, arr):\n return [i for i in range(m + 1) if not any((a <= i <= b for (a, b) in arr))]", "def segments(m, a):\n vals = set(range(m + 1))\n for (st, en) in a:\n vals -= set(range(st, en + 1))\n return sorted(vals)", "def segments(m, a):\n return [p for p in range(m + 1) if all((not x[0] <= p <= x[1] for x in a))]", "def segments(m, a):\n occupied = []\n for i in a:\n for x in range(i[0], i[1] + 1):\n occupied.append(x)\n free = []\n for n in range(0, m + 1):\n if n not in occupied:\n free.append(n)\n return free", "def segments(m, a):\n return [i for i in range(m + 1) if not any([i in range(x[0], x[1] + 1) for x in a])]", "def segments(m, a):\n new_list = []\n for sub_list in a:\n new_list = new_list + list(range(sub_list[0], sub_list[1] + 1))\n new_set = set(new_list)\n expected_set = set(range(0, m + 1))\n return sorted(list(expected_set.difference(new_set)))", "def segments(m, a):\n segments = {n for (l, r) in a for n in range(l, r + 1)}\n return [n for n in range(m + 1) if n not in segments]", "from functools import reduce\nfrom itertools import filterfalse\n\ndef segments(m, a):\n return list(filterfalse(reduce(set.union, (set(range(x, y + 1)) for (x, y) in a), set()).__contains__, range(0, m + 1)))", "def segments(m, a):\n answer = [i for i in range(m + 1)]\n for i in a:\n for j in range(i[0], i[1] + 1):\n try:\n answer.remove(j)\n except ValueError:\n pass\n return answer"], "starter_code": "def segments(m, a):\n", "input_output": {"fn_name": "segments", "inputs": [[7, [[0, 7]]], [2, []], [0, []], [0, [[0, 0]]]], "outputs": [[[]], [[0, 1, 2]], [[0]], [[]]]}, "difficulty": "EASY", "raw_tags": [], "name": null, "source": "codewars", "tags": [], "skill_types": [], "url": "https://www.codewars.com/kata/5baa25f3246d071df90002b7", "Expected Auxiliary Space": null, "time_limit": null, "date": null, "picture_num": null, "memory_limit": null, "Expected Time Complexity": null, "entry_point": "segments", "task_id": "TACO_lite/491", "example": [[[5, [[2, 2], [1, 2], [5, 5]]], [7, [[0, 7]]]], ["[0, 3, 4]", "[]"]]} diff --git a/experiment/taco_dataset_validation/overall_summary.csv b/experiment/taco_dataset_validation/overall_summary.csv new file mode 100644 index 0000000..d6d7af1 --- /dev/null +++ b/experiment/taco_dataset_validation/overall_summary.csv @@ -0,0 +1,2 @@ +Fully Passed,Partially Passed,Failed,Percentage Fully Passed,Failed Requirement Tags +380,22,98,76.00%,"sumfourdivisors, lostsheep, maxdiffindex, firstdigit, findspecificpattern, round_to_five, cantransform, maxproductsubarrayofsizek, findtwoelement, _init_, countpairs, beasts, countpairs, missing_angle, maximalsquare, bintreesortedlevels, findsum, smallestrangeii, minimumenergy, countways, maximumprofit, maximumsumsubarray, divisiblebym, fourpointsquare, countsubarray, largestperimeter, count, find_median, __init__, countsubarray, perfectsum, solve, __init__, sumbetweentwokth, countperfectsquares, findmin, findmaxsubarraysum, __init__, totaldigits, __init__, __init__, __init__, maxindexdiff, maxval, __init__, majorityelement, klargest, init, largestsumofaverages, __init__, longestperfectpiece, distinctcount, count_deaf_rats, findelement, removecoveredintervals, average, areanagram, numpoints, sum_nested_numbers, common_element, house_of_cards, min_operations, find, switcher, the_biggest_search_keys, __init__, threesumclosest, solve, customsort, getpairscount, __init__, allpalindromicperms, __init__, leftrotate, __init__, findkrotation, checkifexist, count_nges, next_num, all_permuted, rowwithmax1s, reverseingroups, printequalmodnumbers, two_sum, oddnumberofdivisor, __init__, __init__, cog_rpm, root, findelement, bagoftokensscore, countincreasing, any_odd, __init__, __init__, crosspattern, minamount, vowel_back" diff --git a/experiment/taco_dataset_validation/summary_report.csv b/experiment/taco_dataset_validation/summary_report.csv new file mode 100644 index 0000000..3bda7bf --- /dev/null +++ b/experiment/taco_dataset_validation/summary_report.csv @@ -0,0 +1,501 @@ +Requirement,Total Examples,Passed Examples,Failed Examples,Percentage Passed,Status +sumfourdivisors,N/A,N/A,N/A,N/A,Fallback Failed +not_visible_cubes,1,1,0,100.00%,Fully Passed +main,0,0,0,0.00%,Fully Passed +no_ofstring,2,2,0,100.00%,Fully Passed +generate_integers,1,1,0,100.00%,Fully Passed +penaltyscore,2,2,0,100.00%,Fully Passed +is_palindrome,0,0,0,0.00%,Fully Passed +faro_cycles,2,1,1,50.00%,Partially Passed +tribonacci,2,2,0,100.00%,Fully Passed +canjump,2,2,0,100.00%,Fully Passed +trailingzeroes,2,2,0,100.00%,Fully Passed +count,2,2,0,100.00%,Fully Passed +is_anagram,0,0,0,0.00%,Fully Passed +ncr,2,2,0,100.00%,Fully Passed +numofprisoners,2,2,0,100.00%,Fully Passed +maxodd,2,2,0,100.00%,Fully Passed +minthirdpiles,2,2,0,100.00%,Fully Passed +removeduplicates,0,0,0,0.00%,Fully Passed +calculate_1rm,3,2,1,66.67%,Partially Passed +printuniquesubset,1,1,0,100.00%,Fully Passed +minimum_number,2,2,0,100.00%,Fully Passed +ispossible,2,2,0,100.00%,Fully Passed +lostsheep,2,0,2,0.00%,Failed +longestsubstring,2,2,0,100.00%,Fully Passed +maxdiffindex,1,0,1,0.00%,Failed +kontti,0,0,0,0.00%,Fully Passed +firstdigit,2,0,2,0.00%,Failed +findspecificpattern,1,0,1,0.00%,Failed +round_to_five,1,0,1,0.00%,Failed +calculate_grade,2,2,0,100.00%,Fully Passed +is_power_of_eight,0,0,0,0.00%,Fully Passed +cantransform,N/A,N/A,N/A,N/A,Fallback Failed +minfallingpathsum,1,1,0,100.00%,Fully Passed +findxy,0,0,0,0.00%,Fully Passed +minflipsmonoincr,3,3,0,100.00%,Fully Passed +palindrome,0,0,0,0.00%,Fully Passed +findsubstring,3,3,0,100.00%,Fully Passed +bumps,0,0,0,0.00%,Fully Passed +xor,0,0,0,0.00%,Fully Passed +maxproductsubarrayofsizek,2,0,2,0.00%,Failed +smallestkdigitnum,2,2,0,100.00%,Fully Passed +shortestunsub,2,2,0,100.00%,Fully Passed +__init__,0,0,0,0.00%,Fully Passed +modulo,2,2,0,100.00%,Fully Passed +word_search,1,1,0,100.00%,Fully Passed +string_parse,2,2,0,100.00%,Fully Passed +get_middle,4,4,0,100.00%,Fully Passed +sea_sick,0,0,0,0.00%,Fully Passed +englishwords,0,0,0,0.00%,Fully Passed +findtwoelement,2,0,2,0.00%,Failed +_init_,N/A,N/A,N/A,N/A,Fallback Failed +human_years_cat_years_dog_years,3,3,0,100.00%,Fully Passed +move_zeros,1,1,0,100.00%,Fully Passed +countpairs,2,0,2,0.00%,Failed +beasts,3,0,3,0.00%,Failed +countpairs,2,0,2,0.00%,Failed +distinctadjacentelement,0,0,0,0.00%,Fully Passed +iscircular,2,2,0,100.00%,Fully Passed +make_acronym,0,0,0,0.00%,Fully Passed +count,2,2,0,100.00%,Fully Passed +kooka_counter,0,0,0,0.00%,Fully Passed +solve_for_x,4,4,0,100.00%,Fully Passed +roots,3,2,1,66.67%,Partially Passed +binary_cleaner,1,1,0,100.00%,Fully Passed +insert,0,0,0,0.00%,Fully Passed +largestsubsquare,2,2,0,100.00%,Fully Passed +maxequalrowsafterflips,3,3,0,100.00%,Fully Passed +missing_angle,3,0,3,0.00%,Failed +maximalsquare,1,0,1,0.00%,Failed +numberofsubarrays,3,3,0,100.00%,Fully Passed +london_city_hacker,0,0,0,0.00%,Fully Passed +get_grade,0,0,0,0.00%,Fully Passed +bintreesortedlevels,2,0,2,0.00%,Failed +numberofpath,2,1,1,50.00%,Partially Passed +valid_mersenne,0,0,0,0.00%,Fully Passed +printsubsets,0,0,0,0.00%,Fully Passed +repeatedstringmatch,1,1,0,100.00%,Fully Passed +findsum,2,0,2,0.00%,Failed +get_exponent,0,0,0,0.00%,Fully Passed +my_crib,0,0,0,0.00%,Fully Passed +evalrpn,3,3,0,100.00%,Fully Passed +common_divisor,2,2,0,100.00%,Fully Passed +smallestrangeii,N/A,N/A,N/A,N/A,Fallback Failed +paircubecount,2,1,1,50.00%,Partially Passed +hammingdistance,1,1,0,100.00%,Fully Passed +maxprofit,1,1,0,100.00%,Fully Passed +sum_dig_pow,3,3,0,100.00%,Fully Passed +how_many_bees,2,1,1,50.00%,Partially Passed +nearestpalindromic,1,1,0,100.00%,Fully Passed +minimumenergy,1,0,1,0.00%,Failed +convert_recipe,4,3,1,75.00%,Partially Passed +numofperfectsquares,2,2,0,100.00%,Fully Passed +unlucky_number,2,2,0,100.00%,Fully Passed +separate_liquids,1,1,0,100.00%,Fully Passed +isdisarium,2,2,0,100.00%,Fully Passed +printnumber,0,0,0,0.00%,Fully Passed +convert,1,1,0,100.00%,Fully Passed +roundtonearest,2,2,0,100.00%,Fully Passed +beeramid,2,2,0,100.00%,Fully Passed +reverse,1,1,0,100.00%,Fully Passed +countways,2,0,2,0.00%,Failed +checktree,0,0,0,0.00%,Fully Passed +min_and_max,2,2,0,100.00%,Fully Passed +total,3,3,0,100.00%,Fully Passed +maximumprofit,1,0,1,0.00%,Failed +chess_board,2,2,0,100.00%,Fully Passed +pivotindex,2,2,0,100.00%,Fully Passed +numtilepossibilities,3,3,0,100.00%,Fully Passed +maximumsumsubarray,2,0,2,0.00%,Failed +makesquare,0,0,0,0.00%,Fully Passed +maxsubstr,2,2,0,100.00%,Fully Passed +fibexpression,2,1,1,50.00%,Partially Passed +divisiblebym,2,0,2,0.00%,Failed +insert_missing_letters,1,1,0,100.00%,Fully Passed +fourpointsquare,2,0,2,0.00%,Failed +countdigits,2,2,0,100.00%,Fully Passed +countsubarray,2,0,2,0.00%,Failed +okkookoo,3,3,0,100.00%,Fully Passed +mean_vs_median,0,0,0,0.00%,Fully Passed +same_encryption,0,0,0,0.00%,Fully Passed +longestpalin,0,0,0,0.00%,Fully Passed +printfibb,0,0,0,0.00%,Fully Passed +pronicnumbers,0,0,0,0.00%,Fully Passed +eval_object,0,0,0,0.00%,Fully Passed +largestperimeter,N/A,N/A,N/A,N/A,Fallback Failed +solve,0,0,0,0.00%,Fully Passed +ispossible,2,2,0,100.00%,Fully Passed +nthevenfibonacci,2,2,0,100.00%,Fully Passed +sum,2,1,1,50.00%,Partially Passed +count,2,0,2,0.00%,Failed +find_missing_letter,2,2,0,100.00%,Fully Passed +find_median,2,0,2,0.00%,Failed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +solve,3,3,0,100.00%,Fully Passed +reverser,2,2,0,100.00%,Fully Passed +get_order,1,1,0,100.00%,Fully Passed +maxsumafterpartitioning,3,3,0,100.00%,Fully Passed +rectanglearea,2,2,0,100.00%,Fully Passed +problem,0,0,0,0.00%,Fully Passed +area_of_polygon_inside_circle,3,3,0,100.00%,Fully Passed +increasingtriplet,0,0,0,0.00%,Fully Passed +samechar,0,0,0,0.00%,Fully Passed +rotatematrix,0,0,0,0.00%,Fully Passed +equalize,1,1,0,100.00%,Fully Passed +findduplicate,2,2,0,100.00%,Fully Passed +find_initial_numbers,0,0,0,0.00%,Fully Passed +primeproduct,2,2,0,100.00%,Fully Passed +countsubarray,2,0,2,0.00%,Failed +constrainedsubsetsum,3,3,0,100.00%,Fully Passed +findcoverage,0,0,0,0.00%,Fully Passed +next_letter,0,0,0,0.00%,Fully Passed +compress,2,2,0,100.00%,Fully Passed +hex_hash,3,3,0,100.00%,Fully Passed +likes,0,0,0,0.00%,Fully Passed +two_decimal_places,2,2,0,100.00%,Fully Passed +cost_of_carpet,0,0,0,0.00%,Fully Passed +perfectsum,2,0,2,0.00%,Failed +snakepattern,0,0,0,0.00%,Fully Passed +easyproblem,2,2,0,100.00%,Fully Passed +latticepoints,2,2,0,100.00%,Fully Passed +solve,1,0,1,0.00%,Failed +find_nth_occurrence,8,8,0,100.00%,Fully Passed +rob,2,2,0,100.00%,Fully Passed +replacewords,1,1,0,100.00%,Fully Passed +solution,1,1,0,100.00%,Fully Passed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +phisum,2,2,0,100.00%,Fully Passed +sumbetweentwokth,2,0,2,0.00%,Failed +evaluatepostfix,2,2,0,100.00%,Fully Passed +sort_string,6,6,0,100.00%,Fully Passed +xorcal,2,2,0,100.00%,Fully Passed +countpackets,2,2,0,100.00%,Fully Passed +uniq_c,1,1,0,100.00%,Fully Passed +rremove,2,2,0,100.00%,Fully Passed +countodds,2,2,0,100.00%,Fully Passed +countperfectsquares,2,0,2,0.00%,Failed +days_represented,1,1,0,100.00%,Fully Passed +findmin,2,0,2,0.00%,Failed +has_two_cube_sums,0,0,0,0.00%,Fully Passed +minsquares,2,2,0,100.00%,Fully Passed +primesum,2,2,0,100.00%,Fully Passed +getfirstsetbit,2,2,0,100.00%,Fully Passed +possible_paths,0,0,0,0.00%,Fully Passed +diff,0,0,0,0.00%,Fully Passed +only_duplicates,1,1,0,100.00%,Fully Passed +minsteps,2,2,0,100.00%,Fully Passed +__init__,0,0,0,0.00%,Fully Passed +findmaxsubarraysum,2,0,2,0.00%,Failed +alphabetic,2,2,0,100.00%,Fully Passed +evenfibsum,2,2,0,100.00%,Fully Passed +numbertowords,4,4,0,100.00%,Fully Passed +sorter,2,2,0,100.00%,Fully Passed +sort_array,1,1,0,100.00%,Fully Passed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +lcsk,2,2,0,100.00%,Fully Passed +parse_mana_cost,0,0,0,0.00%,Fully Passed +sort_array,1,1,0,100.00%,Fully Passed +lowercase_count,3,3,0,100.00%,Fully Passed +tilingrectangle,3,3,0,100.00%,Fully Passed +countsquares,2,2,0,100.00%,Fully Passed +func_or,0,0,0,0.00%,Fully Passed +totaldigits,2,0,2,0.00%,Failed +maxdigit,2,2,0,100.00%,Fully Passed +only_one,4,4,0,100.00%,Fully Passed +check_vowel,0,0,0,0.00%,Fully Passed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +combine,1,1,0,100.00%,Fully Passed +travel,1,1,0,100.00%,Fully Passed +div_con,3,3,0,100.00%,Fully Passed +countdivisiblesubseq,2,2,0,100.00%,Fully Passed +simplifiedfractions,4,3,1,75.00%,Partially Passed +maxindexdiff,2,0,2,0.00%,Failed +is_onion_array,0,0,0,0.00%,Fully Passed +add,4,4,0,100.00%,Fully Passed +cycle,8,8,0,100.00%,Fully Passed +maxval,2,0,2,0.00%,Failed +solvenqueens,1,1,0,100.00%,Fully Passed +longestsubarray,5,5,0,100.00%,Fully Passed +numsteps,3,3,0,100.00%,Fully Passed +isrotated,0,0,0,0.00%,Fully Passed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +title_to_number,3,3,0,100.00%,Fully Passed +shifted_diff,6,6,0,100.00%,Fully Passed +majorityelement,2,0,2,0.00%,Failed +values,1,1,0,100.00%,Fully Passed +palindromicpartition,2,2,0,100.00%,Fully Passed +am_i_afraid,0,0,0,0.00%,Fully Passed +klargest,2,0,2,0.00%,Failed +fun,2,2,0,100.00%,Fully Passed +init,N/A,N/A,N/A,N/A,Fallback Failed +sharkovsky,0,0,0,0.00%,Fully Passed +date_correct,4,4,0,100.00%,Fully Passed +thelastdigit,2,2,0,100.00%,Fully Passed +locate,0,0,0,0.00%,Fully Passed +numofways,2,2,0,100.00%,Fully Passed +swap,4,4,0,100.00%,Fully Passed +killinspree,2,2,0,100.00%,Fully Passed +sum_circles,0,0,0,0.00%,Fully Passed +totaldivisors,2,2,0,100.00%,Fully Passed +numofsubarrays,5,5,0,100.00%,Fully Passed +largestsumofaverages,1,0,1,0.00%,Failed +secfrequent,0,0,0,0.00%,Fully Passed +recamansequence,0,0,0,0.00%,Fully Passed +setbits,2,2,0,100.00%,Fully Passed +countfactors,2,2,0,100.00%,Fully Passed +say_hello,1,1,0,100.00%,Fully Passed +fibonaccidigits,2,2,0,100.00%,Fully Passed +issparse,2,2,0,100.00%,Fully Passed +histogram,3,3,0,100.00%,Fully Passed +arr2bin,2,2,0,100.00%,Fully Passed +trailingzeroes,2,2,0,100.00%,Fully Passed +longestsubsequence,2,2,0,100.00%,Fully Passed +x1series,2,2,0,100.00%,Fully Passed +minpathsum,1,1,0,100.00%,Fully Passed +squaresdiff,2,2,0,100.00%,Fully Passed +pretoinfix,0,0,0,0.00%,Fully Passed +counttriplets,0,0,0,0.00%,Fully Passed +is_hollow,0,0,0,0.00%,Fully Passed +count,2,2,0,100.00%,Fully Passed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +longestsubstrdistinctchars,2,2,0,100.00%,Fully Passed +fingercount,2,2,0,100.00%,Fully Passed +valid_parentheses,0,0,0,0.00%,Fully Passed +minimumsquares,2,2,0,100.00%,Fully Passed +get_section_id,2,2,0,100.00%,Fully Passed +sum_digits,3,3,0,100.00%,Fully Passed +getnthpell,2,2,0,100.00%,Fully Passed +meters,0,0,0,0.00%,Fully Passed +sumsubstrings,2,2,0,100.00%,Fully Passed +countprimes,1,1,0,100.00%,Fully Passed +maximum_cuts,2,2,0,100.00%,Fully Passed +consecutive_sum,4,4,0,100.00%,Fully Passed +replace_letters,0,0,0,0.00%,Fully Passed +__init__,0,0,0,0.00%,Fully Passed +findvalue,2,2,0,100.00%,Fully Passed +search,2,2,0,100.00%,Fully Passed +ipsubnet2list,2,1,1,50.00%,Partially Passed +canjump,0,0,0,0.00%,Fully Passed +stringy,3,3,0,100.00%,Fully Passed +find_2nd_largest,0,0,0,0.00%,Fully Passed +maxpower,5,5,0,100.00%,Fully Passed +reversewords,1,1,0,100.00%,Fully Passed +longestperfectpiece,2,0,2,0.00%,Failed +next_numb,0,0,0,0.00%,Fully Passed +accum,3,3,0,100.00%,Fully Passed +numrescueboats,3,3,0,100.00%,Fully Passed +distinctcount,2,0,2,0.00%,Failed +countsubarrays,2,2,0,100.00%,Fully Passed +meeting,3,3,0,100.00%,Fully Passed +numprimearrangements,2,2,0,100.00%,Fully Passed +endless_string,4,4,0,100.00%,Fully Passed +count_deaf_rats,2,0,2,0.00%,Failed +subarraysdivbyk,1,1,0,100.00%,Fully Passed +sort_nested_list,1,1,0,100.00%,Fully Passed +findelement,2,0,2,0.00%,Failed +matrixdiagonally,0,0,0,0.00%,Fully Passed +is_int_array,6,6,0,100.00%,Fully Passed +generate_diagonal,3,3,0,100.00%,Fully Passed +group_cities,3,3,0,100.00%,Fully Passed +removecoveredintervals,N/A,N/A,N/A,N/A,Fallback Failed +rearrangearray,0,0,0,0.00%,Fully Passed +sum_them,4,1,3,25.00%,Partially Passed +transform,1,1,0,100.00%,Fully Passed +gematria,1,1,0,100.00%,Fully Passed +orderlyqueue,2,2,0,100.00%,Fully Passed +solve,1,1,0,100.00%,Fully Passed +average,N/A,N/A,N/A,N/A,Fallback Failed +findinputtype,2,2,0,100.00%,Fully Passed +sumsubseqwidths,1,1,0,100.00%,Fully Passed +areanagram,2,0,2,0.00%,Failed +numpoints,N/A,N/A,N/A,N/A,Fallback Failed +my_add,2,1,1,50.00%,Partially Passed +nthmysterious,2,2,0,100.00%,Fully Passed +sophie_primes,0,0,0,0.00%,Fully Passed +sum_nested_numbers,1,0,1,0.00%,Failed +nthterm,2,2,0,100.00%,Fully Passed +to_roman,2,1,1,50.00%,Partially Passed +pattern,0,0,0,0.00%,Fully Passed +common_element,1,0,1,0.00%,Failed +cup_volume,5,5,0,100.00%,Fully Passed +last_digit,5,5,0,100.00%,Fully Passed +womens_age,2,2,0,100.00%,Fully Passed +factorsoffactorial,2,2,0,100.00%,Fully Passed +house_of_cards,1,0,1,0.00%,Failed +graytobinary,3,3,0,100.00%,Fully Passed +__init__,0,0,0,0.00%,Fully Passed +min_operations,2,0,2,0.00%,Failed +hasalternatingbits,4,4,0,100.00%,Fully Passed +istwistedprime,2,2,0,100.00%,Fully Passed +firstrepchar,0,0,0,0.00%,Fully Passed +lengthoflastword,1,1,0,100.00%,Fully Passed +remove_exclamation_marks,0,0,0,0.00%,Fully Passed +solve,1,1,0,100.00%,Fully Passed +querystring,0,0,0,0.00%,Fully Passed +countofsubstringwithkones,2,2,0,100.00%,Fully Passed +check,2,2,0,100.00%,Fully Passed +sort_string,3,3,0,100.00%,Fully Passed +find,1,0,1,0.00%,Failed +findsum,2,2,0,100.00%,Fully Passed +zeros,2,2,0,100.00%,Fully Passed +switcher,2,0,2,0.00%,Failed +find_min_num,2,2,0,100.00%,Fully Passed +the_biggest_search_keys,1,0,1,0.00%,Failed +__init__,0,0,0,0.00%,Fully Passed +nthposition,2,2,0,100.00%,Fully Passed +majorityelement,2,2,0,100.00%,Fully Passed +validmountainarray,0,0,0,0.00%,Fully Passed +countchars,1,1,0,100.00%,Fully Passed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +subarrayswithkdistinct,2,2,0,100.00%,Fully Passed +reindeer,3,3,0,100.00%,Fully Passed +indices,1,1,0,100.00%,Fully Passed +ackermann,2,2,0,100.00%,Fully Passed +threesumclosest,2,0,2,0.00%,Failed +__init__,0,0,0,0.00%,Fully Passed +coinchange,5,5,0,100.00%,Fully Passed +solve,1,0,1,0.00%,Failed +compute_value,2,2,0,100.00%,Fully Passed +countps,2,2,0,100.00%,Fully Passed +customsort,2,0,2,0.00%,Failed +interleave,4,4,0,100.00%,Fully Passed +getpairscount,2,0,2,0.00%,Failed +checkrecord,2,2,0,100.00%,Fully Passed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +removeconsonants,0,0,0,0.00%,Fully Passed +findthelongestsubstring,3,3,0,100.00%,Fully Passed +nthdigit,2,1,1,50.00%,Partially Passed +formcoils,0,0,0,0.00%,Fully Passed +divisibleby4,2,2,0,100.00%,Fully Passed +inside_out,2,2,0,100.00%,Fully Passed +__init__,0,0,0,0.00%,Fully Passed +computeparity,0,0,0,0.00%,Fully Passed +pattern,0,0,0,0.00%,Fully Passed +what_century,6,6,0,100.00%,Fully Passed +combine,3,3,0,100.00%,Fully Passed +decrypt,2,1,1,50.00%,Partially Passed +getrow,1,1,0,100.00%,Fully Passed +solve,0,0,0,0.00%,Fully Passed +dup,2,2,0,100.00%,Fully Passed +reverse_bits,1,1,0,100.00%,Fully Passed +allpalindromicperms,2,0,2,0.00%,Failed +nthdaypage,2,2,0,100.00%,Fully Passed +total_kilometers,0,0,0,0.00%,Fully Passed +multiplication_table,1,1,0,100.00%,Fully Passed +swap,5,5,0,100.00%,Fully Passed +isdivisible,2,2,0,100.00%,Fully Passed +setalloddbits,2,2,0,100.00%,Fully Passed +samefreq,0,0,0,0.00%,Fully Passed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +solve,2,2,0,100.00%,Fully Passed +graycode,2,2,0,100.00%,Fully Passed +leftrotate,2,0,2,0.00%,Failed +sort,0,0,0,0.00%,Fully Passed +count_rect_triang,2,2,0,100.00%,Fully Passed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +encode,0,0,0,0.00%,Fully Passed +findkrotation,2,0,2,0.00%,Failed +graceful_tipping,4,2,2,50.00%,Partially Passed +countofnumbers,2,2,0,100.00%,Fully Passed +climb,1,1,0,100.00%,Fully Passed +motif_locator,3,3,0,100.00%,Fully Passed +checkifexist,N/A,N/A,N/A,N/A,Fallback Failed +twos_difference,4,4,0,100.00%,Fully Passed +__init__,0,0,0,0.00%,Fully Passed +fishex,1,1,0,100.00%,Fully Passed +count,2,2,0,100.00%,Fully Passed +factorial,0,0,0,0.00%,Fully Passed +count_nges,1,0,1,0.00%,Failed +without_last,2,2,0,100.00%,Fully Passed +next_num,3,0,3,0.00%,Failed +all_permuted,1,0,1,0.00%,Failed +nthpersongetsnthseat,2,2,0,100.00%,Fully Passed +added_char,3,3,0,100.00%,Fully Passed +minpartition,0,0,0,0.00%,Fully Passed +shortestbridge,3,3,0,100.00%,Fully Passed +longestawesome,4,4,0,100.00%,Fully Passed +debug,2,2,0,100.00%,Fully Passed +countcharacters,2,2,0,100.00%,Fully Passed +anagrams,3,3,0,100.00%,Fully Passed +rowwithmax1s,2,0,2,0.00%,Failed +convert,2,2,0,100.00%,Fully Passed +reverseingroups,2,0,2,0.00%,Failed +printequalmodnumbers,2,0,2,0.00%,Failed +bubble,3,1,2,33.33%,Partially Passed +calculate,4,4,0,100.00%,Fully Passed +no_repeat,3,3,0,100.00%,Fully Passed +two_sum,3,0,3,0.00%,Failed +solve,3,3,0,100.00%,Fully Passed +abundant_number,0,0,0,0.00%,Fully Passed +binarypalin,2,2,0,100.00%,Fully Passed +sequence_sum,4,4,0,100.00%,Fully Passed +union,0,0,0,0.00%,Fully Passed +people_with_age_drink,0,0,0,0.00%,Fully Passed +is_triangle,0,0,0,0.00%,Fully Passed +frame,0,0,0,0.00%,Fully Passed +oddnumberofdivisor,2,0,2,0.00%,Failed +equalpartition,0,0,0,0.00%,Fully Passed +code,4,1,3,25.00%,Partially Passed +divide,2,2,0,100.00%,Fully Passed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +is_madhav_array,0,0,0,0.00%,Fully Passed +possible_positions,1,1,0,100.00%,Fully Passed +tax_calculator,2,1,1,50.00%,Partially Passed +reverse_fun,1,1,0,100.00%,Fully Passed +green,1,1,0,100.00%,Fully Passed +minsteptodeletestring,2,2,0,100.00%,Fully Passed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +interweave,2,2,0,100.00%,Fully Passed +remove_duplicate_words,1,1,0,100.00%,Fully Passed +numsquares,2,2,0,100.00%,Fully Passed +cog_rpm,1,0,1,0.00%,Failed +avoid_obstacles,1,1,0,100.00%,Fully Passed +root,2,0,2,0.00%,Failed +get_note,0,0,0,0.00%,Fully Passed +binary_to_decimal,2,2,0,100.00%,Fully Passed +__init__,0,0,0,0.00%,Fully Passed +subarrayexists,0,0,0,0.00%,Fully Passed +countways,2,2,0,100.00%,Fully Passed +isvalidserialization,0,0,0,0.00%,Fully Passed +findelement,2,0,2,0.00%,Failed +longest_palindrome,2,2,0,100.00%,Fully Passed +bagoftokensscore,N/A,N/A,N/A,N/A,Fallback Failed +subsetswithdup,0,0,0,0.00%,Fully Passed +oppositefaceofdice,2,2,0,100.00%,Fully Passed +reduce_pyramid,3,3,0,100.00%,Fully Passed +subarraysum,1,1,0,100.00%,Fully Passed +__init__,0,0,0,0.00%,Fully Passed +countincreasing,2,0,2,0.00%,Failed +segregateevenodd,0,0,0,0.00%,Fully Passed +minchar,2,2,0,100.00%,Fully Passed +is_valid_coordinates,0,0,0,0.00%,Fully Passed +greet,2,2,0,100.00%,Fully Passed +removecharacters,2,2,0,100.00%,Fully Passed +transform,2,2,0,100.00%,Fully Passed +any_odd,3,0,3,0.00%,Failed +series_sum,3,3,0,100.00%,Fully Passed +levelorder,0,0,0,0.00%,Fully Passed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +__init__,N/A,N/A,N/A,N/A,Fallback Failed +is_very_even_number,0,0,0,0.00%,Fully Passed +is_bleak,2,2,0,100.00%,Fully Passed +crosspattern,2,0,2,0.00%,Failed +moves,2,2,0,100.00%,Fully Passed +nth_smallest,3,1,2,33.33%,Partially Passed +maxvalueafterreverse,2,2,0,100.00%,Fully Passed +opposite,3,3,0,100.00%,Fully Passed +minamount,2,0,2,0.00%,Failed +determinantofmatrix,0,0,0,0.00%,Fully Passed +finding_k,3,3,0,100.00%,Fully Passed +__init__,0,0,0,0.00%,Fully Passed +digitize,1,1,0,100.00%,Fully Passed +vowel_back,2,0,2,0.00%,Failed +uniq,1,1,0,100.00%,Fully Passed +find_all,1,1,0,100.00%,Fully Passed +findprob,2,1,1,50.00%,Partially Passed +is_prime,0,0,0,0.00%,Fully Passed +to_bytes,5,5,0,100.00%,Fully Passed +segments,2,2,0,100.00%,Fully Passed diff --git a/experiment/taco_dataset_validation/verify.py b/experiment/taco_dataset_validation/verify.py new file mode 100644 index 0000000..4518976 --- /dev/null +++ b/experiment/taco_dataset_validation/verify.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 +import json +import sys +import traceback +import math +import csv # For CSV output + +def convert_to_expected(actual, expected): + """ + Attempts to convert 'actual' into the same type as 'expected'. + If conversion fails, returns the original 'actual'. + """ + if actual is None: + return actual + exp_type = type(expected) + try: + if exp_type is tuple: + return tuple(actual) if not isinstance(actual, tuple) else actual + elif exp_type is list: + return list(actual) if not isinstance(actual, list) else actual + elif exp_type is int: + return int(actual) + elif exp_type is float: + return float(actual) + elif exp_type is str: + return str(actual) + elif exp_type is dict: + return dict(actual) + else: + return exp_type(actual) + except Exception: + return actual + +def compare_outputs(actual, expected): + """ + Converts the actual output to the type of expected output and then compares them. + For floats, a small tolerance is allowed. + """ + try: + converted = convert_to_expected(actual, expected) + if isinstance(expected, float): + return abs(converted - expected) < 1e-6 + return converted == expected + except Exception: + return False + +def run_requirement(req_obj): + """ + Process a single requirement JSON object: + - Determines the function name from "entry_point" or "input_output.fn_name". + - Iterates over the provided solution codes (in "solutions") and selects the + first solution that produces a non-None output for all examples. + - Runs the chosen solution on each example and compares the result (after conversion) + to the expected output. + + Returns a tuple (fn_name, results) where results is a list of tuples: + (input_args, expected_output, actual_output, passed_boolean) + """ + # Determine the function name. + fn_name = req_obj.get("entry_point") + if not fn_name: + fn_name = req_obj.get("input_output", {}).get("fn_name") + if not fn_name: + print("No entry point (function name) found in requirement.") + return None + + # Extract examples: expecting a two-element list: + # [ list_of_input_examples, list_of_expected_outputs ] + examples = req_obj.get("example") + if not examples or len(examples) != 2: + print(f"No valid 'example' field found for requirement '{fn_name}'.") + return None + example_inputs, expected_outputs = examples + if len(example_inputs) != len(expected_outputs): + print(f"Mismatch in number of inputs and outputs for requirement '{fn_name}'.") + return None + + # Iterate over all solutions and choose one that doesn't return None for any example. + solutions = req_obj.get("solutions", []) + if not solutions: + print(f"No solutions provided for requirement '{fn_name}'.") + return None + + chosen_solution_code = None + for sol_code in solutions: + env = {} + try: + exec(sol_code, env) + except Exception as e: + continue # Skip solution if it fails to execute. + if fn_name not in env: + continue + fn = env[fn_name] + valid = True + for inp, _ in zip(example_inputs, expected_outputs): + if not isinstance(inp, list): + inp = [inp] + try: + result = fn(*inp) + except Exception: + valid = False + break + if result is None: + valid = False + break + if valid: + chosen_solution_code = sol_code + break + + # If none of the solutions produced a valid (non-None) result, fallback to the first solution. + if chosen_solution_code is None: + chosen_solution_code = solutions[0] + + # Execute the chosen solution code. + env = {} + try: + exec(chosen_solution_code, env) + except Exception as e: + print(f"Error executing chosen solution code for '{fn_name}': {e}") + traceback.print_exc() + return None + + if fn_name not in env: + print(f"Function '{fn_name}' was not defined in the executed solution code.") + return None + + fn = env[fn_name] + + # Run the chosen solution on all examples. + results = [] + for idx, (inp, expected) in enumerate(zip(example_inputs, expected_outputs)): + # Ensure input is a list of arguments. + if not isinstance(inp, list): + inp = [inp] + try: + actual = fn(*inp) + except Exception as e: + print(f"Error calling function '{fn_name}' on example {idx+1} with input {inp}: {e}") + traceback.print_exc() + actual = None + passed = compare_outputs(actual, expected) + results.append((inp, expected, actual, passed)) + return fn_name, results + +def main(jsonl_file_path): + total_requirements = 0 + fully_matching_requirements = 0 # Count of fully passed (all examples passed) + failed_requirements_details = {} + summary_rows = [] # For per-requirement CSV summary + + try: + with open(jsonl_file_path, 'r', encoding='utf-8') as f: + lines = f.readlines() + except Exception as e: + print(f"Error opening JSONL file '{jsonl_file_path}': {e}") + sys.exit(1) + + for line_no, line in enumerate(lines, start=1): + line = line.strip() + if not line: + continue + try: + req = json.loads(line) + except Exception as e: + print(f"Error parsing JSON on line {line_no}: {e}") + continue + + total_requirements += 1 + result = run_requirement(req) + if result is None: + print(f"Skipping requirement on line {line_no} due to errors.\n") + continue + + fn_name, results = result + total_examples = len(results) + passed_examples = sum(1 for r in results if r[3]) + failed_examples = total_examples - passed_examples + + # Determine overall status for this requirement: + # Fully Passed: all examples passed + # Failed: no examples passed + # Partially Passed: some (but not all) examples passed + if passed_examples == total_examples: + overall_status = "Fully Passed" + fully_matching_requirements += 1 + elif passed_examples == 0: + overall_status = "Failed" + else: + overall_status = "Partially Passed" + + percentage_passed = (passed_examples / total_examples) * 100 if total_examples > 0 else 0 + summary_rows.append([ + fn_name, + total_examples, + passed_examples, + failed_examples, + f"{percentage_passed:.2f}%", + overall_status + ]) + + print(f"Testing '{fn_name}' (line {line_no}):") + for i, (inp, expected, actual, passed) in enumerate(results, start=1): + status_str = "Match" if passed else "Not match" + print(f" Example {i}: (Input: {inp}, Expected: {expected}, Got: {actual}) - {status_str}") + print() + + if overall_status != "Fully Passed": + failed_requirements_details[fn_name] = results + + # Print console summary. + print("=== Summary ===") + print(f"Total requirements processed: {total_requirements}") + if total_requirements > 0: + percentage_overall = (fully_matching_requirements / total_requirements) * 100 + print(f"Requirements with all examples matching (Fully Passed): {fully_matching_requirements} ({percentage_overall:.2f}%)") + else: + print("No requirements processed.") + + if failed_requirements_details: + print("\nDetailed discrepancies:") + for fn_name, results in failed_requirements_details.items(): + print(f"Requirement: {fn_name}") + for i, (inp, expected, actual, passed) in enumerate(results, start=1): + if not passed: + print(f" Example {i}: Input: {inp}, Expected: {expected}, Got: {actual}") + else: + print("All requirements passed all examples.") + + # Write per-requirement summary report to CSV. + summary_csv = "summary_report.csv" + try: + with open(summary_csv, 'w', newline='', encoding='utf-8') as csvfile: + writer = csv.writer(csvfile) + writer.writerow([ + "Requirement", + "Total Examples", + "Passed Examples", + "Failed Examples", + "Percentage Passed", + "Status" + ]) + for row in summary_rows: + writer.writerow(row) + print(f"\nCSV per-requirement summary report written to {summary_csv}") + except Exception as e: + print(f"Error writing CSV per-requirement summary report: {e}") + + # Compute overall counts for the overall summary CSV. + processed_requirements = len(summary_rows) + fully_passed_count = 0 + partially_passed_count = 0 + failed_count = 0 + failed_tags = [] # List of requirement tags (function names) that failed completely. + + for row in summary_rows: + fn_name, total_ex, passed_ex, _, _, status = row + if status == "Fully Passed": + fully_passed_count += 1 + elif status == "Failed": + failed_count += 1 + failed_tags.append(fn_name) + else: # Partially Passed + partially_passed_count += 1 + + percentage_fully_passed = (fully_passed_count / processed_requirements * 100) if processed_requirements > 0 else 0 + + # Write overall summary CSV. + overall_csv = "overall_summary.csv" + try: + with open(overall_csv, 'w', newline='', encoding='utf-8') as csvfile: + writer = csv.writer(csvfile) + writer.writerow([ + "Fully Passed", + "Partially Passed", + "Failed", + "Percentage Fully Passed", + "Failed Requirement Tags" + ]) + writer.writerow([ + fully_passed_count, + partially_passed_count, + failed_count, + f"{percentage_fully_passed:.2f}%", + ", ".join(failed_tags) + ]) + print(f"CSV overall summary report written to {overall_csv}") + except Exception as e: + print(f"Error writing CSV overall summary report: {e}") + +if __name__ == "__main__": + if len(sys.argv) != 2: + print("Usage: python verify.py ") + sys.exit(1) + jsonl_file_path = sys.argv[1] + main(jsonl_file_path) diff --git a/experiment/taco_dataset_validation/verify_playground.py b/experiment/taco_dataset_validation/verify_playground.py new file mode 100644 index 0000000..722275f --- /dev/null +++ b/experiment/taco_dataset_validation/verify_playground.py @@ -0,0 +1,67 @@ +import math + +# Solution 1: Iterative approach keeping track of product's first digits +def firstdigit_solution1(arr, n): + p = 1 + for i in range(n): + p = p * arr[i] + d = str(p) + p = int(d[:6]) # Keep only first few digits to avoid overflow + return int(str(p)[0]) + +# Solution 2: Logarithm-based approach to extract first digit +def firstdigit_solution2(arr, n): + s = 0.0 + for a in arr: + s += math.log10(a) + s = s - math.floor(s) + return int(math.pow(10, s) + 1e-06) + +# Solution 3: Iterative product calculation and extracting first digit +def firstdigit_solution3(arr, n): + product = 1 + for i in range(0, n): + product = product * arr[i] + digit = product // 10 ** int(math.log10(product)) + return digit + +# Example test cases +test_cases = [ + (4, [5, 8, 3, 7]), # Expected output: 8 + (3, [6, 7, 9]) # Expected output: 3 +] + +# Running all solutions on test cases +results_solution1 = [firstdigit_solution1(arr, n) for n, arr in test_cases] +results_solution2 = [firstdigit_solution2(arr, n) for n, arr in test_cases] +results_solution3 = [firstdigit_solution3(arr, n) for n, arr in test_cases] + +print(results_solution1, results_solution2, results_solution3) + + +def faro_cycles(deck_size): + # For a deck with only 2 cards, one shuffle returns it to original order. + if deck_size == 2: + return 1 + # The number of faro shuffles needed is the smallest k such that 2^k mod (deck_size - 1) equals 1. + k = 1 + while pow(2, k, deck_size - 1) != 1: + k += 1 + return k + +# Testing the function with the provided example inputs. +if __name__ == '__main__': + test_cases = [2, 6, 52, 542, 1250, 1954] + for tc in test_cases: + result = faro_cycles(tc) + print(f'faro_cycles({tc}) = {result}') + +# Expected output: +# faro_cycles(2) = 1 +# faro_cycles(52) = 8 +# faro_cycles(542) = 540 +# faro_cycles(1250) = 156 +# faro_cycles(1954) = 30 + + +#Example that doesn't work \ No newline at end of file diff --git a/experiment/taco_dataset_validation/verify_update.py b/experiment/taco_dataset_validation/verify_update.py new file mode 100644 index 0000000..d83d64e --- /dev/null +++ b/experiment/taco_dataset_validation/verify_update.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +import json +import sys +import traceback +import math +import csv # For CSV output +import decimal # For Decimal types + +# Custom JSON encoder for Decimal objects. +class DecimalEncoder(json.JSONEncoder): + def default(self, obj): + if isinstance(obj, decimal.Decimal): + return float(obj) + return super(DecimalEncoder, self).default(obj) + +def convert_to_expected(actual, expected): + """ + Attempts to convert 'actual' into the same type as 'expected'. + If conversion fails, returns the original 'actual'. + """ + if actual is None: + return actual + exp_type = type(expected) + try: + if exp_type is tuple: + return tuple(actual) if not isinstance(actual, tuple) else actual + elif exp_type is list: + return list(actual) if not isinstance(actual, list) else actual + elif exp_type is int: + return int(actual) + elif exp_type is float: + return float(actual) + elif exp_type is str: + return str(actual) + elif exp_type is dict: + return dict(actual) + else: + return exp_type(actual) + except Exception: + return actual + +def compare_outputs(actual, expected): + """ + Converts the actual output to the type of expected output and then compares them. + For floats, a small tolerance is allowed. + """ + try: + converted = convert_to_expected(actual, expected) + if isinstance(expected, float): + return abs(converted - expected) < 1e-6 + return converted == expected + except Exception: + return False + +def run_requirement(req_obj): + """ + Process a single requirement JSON object: + - Determines the function name from "entry_point" or "input_output.fn_name". + - Iterates over the provided solution codes (in "solutions") and selects the + first solution that produces a non-None output for all examples. + - Runs the chosen solution on each example and compares the result (after conversion) + to the expected output. + + Returns a tuple (fn_name, results) where results is a list of tuples: + (input_args, expected_output, actual_output, passed_boolean) + + If processing fails, returns None. + """ + # Determine the function name. + fn_name = req_obj.get("entry_point") + if not fn_name: + fn_name = req_obj.get("input_output", {}).get("fn_name") + if not fn_name: + print("No entry point (function name) found in requirement.") + return None + + # Extract examples: expecting a two-element list: [ inputs, expected_outputs ] + examples = req_obj.get("example") + if not examples or len(examples) != 2: + print(f"No valid 'example' field found for requirement '{fn_name}'.") + return None + example_inputs, expected_outputs = examples + if len(example_inputs) != len(expected_outputs): + print(f"Mismatch in number of inputs and outputs for requirement '{fn_name}'.") + return None + + # Iterate over all solutions and choose one that doesn't return None for any example. + solutions = req_obj.get("solutions", []) + if not solutions: + print(f"No solutions provided for requirement '{fn_name}'.") + return None + + chosen_solution_code = None + for sol_code in solutions: + env = {} + try: + exec(sol_code, env) + except Exception: + continue # Skip solution if it fails to execute. + if fn_name not in env: + continue + fn = env[fn_name] + valid = True + for inp, _ in zip(example_inputs, expected_outputs): + if not isinstance(inp, list): + inp = [inp] + try: + result = fn(*inp) + except Exception: + valid = False + break + if result is None: + valid = False + break + if valid: + chosen_solution_code = sol_code + break + + # If none of the solutions produced a valid (non-None) result, fallback to the first solution. + if chosen_solution_code is None: + chosen_solution_code = solutions[0] + + # Execute the chosen solution code. + env = {} + try: + exec(chosen_solution_code, env) + except Exception as e: + print(f"Error executing chosen solution code for '{fn_name}': {e}") + traceback.print_exc() + return None + + if fn_name not in env: + print(f"Function '{fn_name}' was not defined in the executed solution code.") + return None + + fn = env[fn_name] + + # Run the chosen solution on all examples. + results = [] + for idx, (inp, expected) in enumerate(zip(example_inputs, expected_outputs)): + # Ensure input is a list of arguments. + if not isinstance(inp, list): + inp = [inp] + try: + actual = fn(*inp) + except Exception as e: + print(f"Error calling function '{fn_name}' on example {idx+1} with input {inp}: {e}") + traceback.print_exc() + actual = None + passed = compare_outputs(actual, expected) + results.append((inp, expected, actual, passed)) + return fn_name, results + +def main(jsonl_file_path): + total_requirements = 0 + fully_matching_requirements = 0 # Count of requirements where all examples passed + failed_requirements_details = {} + summary_rows = [] # For per-requirement CSV summary + new_requirements = [] # To hold all (possibly updated) requirement objects + + try: + with open(jsonl_file_path, 'r', encoding='utf-8') as f: + lines = f.readlines() + except Exception as e: + print(f"Error opening JSONL file '{jsonl_file_path}': {e}") + sys.exit(1) + + for line_no, line in enumerate(lines, start=1): + line = line.strip() + if not line: + continue + try: + req = json.loads(line) + except Exception as e: + print(f"Error parsing JSON on line {line_no}: {e}") + # Skip this requirement if it cannot be parsed. + continue + + total_requirements += 1 + result = run_requirement(req) + if result is not None: + # Normal processing branch + fn_name, results = result + total_examples = len(results) + passed_examples = sum(1 for r in results if r[3]) + failed_examples = total_examples - passed_examples + + # Determine overall status for this requirement. + if passed_examples == total_examples: + overall_status = "Fully Passed" + fully_matching_requirements += 1 + elif passed_examples == 0: + overall_status = "Failed" + else: + overall_status = "Partially Passed" + + percentage_passed = (passed_examples / total_examples) * 100 if total_examples > 0 else 0 + summary_rows.append([ + fn_name, + total_examples, + passed_examples, + failed_examples, + f"{percentage_passed:.2f}%", + overall_status + ]) + + print(f"Testing '{fn_name}' (line {line_no}):") + for i, (inp, expected, actual, passed) in enumerate(results, start=1): + status_str = "Match" if passed else "Not match" + print(f" Example {i}: (Input: {inp}, Expected: {expected}, Got: {actual}) - {status_str}") + print() + + # For requirements that did not fully pass, re-extract examples. + if overall_status != "Fully Passed": + new_expected_outputs = [r[2] for r in results] + req["example"][1] = new_expected_outputs + + else: + # Fallback branch: run_requirement failed. + fn_name = req.get("entry_point") or req.get("input_output", {}).get("fn_name", "Unknown") + print(f"Fallback processing for requirement '{fn_name}' on line {line_no}.") + if "solutions" in req and req["solutions"]: + fallback_solution = req["solutions"][0] + env = {} + try: + exec(fallback_solution, env) + if fn_name in env: + fn = env[fn_name] + example_data = req.get("example") + if (example_data and isinstance(example_data, list) and len(example_data) == 2): + example_inputs = example_data[0] + new_expected_outputs = [] + for inp in example_inputs: + if not isinstance(inp, list): + inp = [inp] + try: + actual = fn(*inp) + except Exception: + actual = None + new_expected_outputs.append(actual) + req["example"][1] = new_expected_outputs + total_examples = len(example_inputs) + passed_examples = total_examples # Now they match, so they "pass" + failed_examples = 0 + overall_status = "Fully Passed" + percentage_passed = 100.00 + summary_rows.append([ + fn_name, + total_examples, + passed_examples, + failed_examples, + f"{percentage_passed:.2f}%", + overall_status + ]) + fully_matching_requirements += 1 + print(f" Fallback re-extraction succeeded for '{fn_name}'.") + else: + summary_rows.append([fn_name, "N/A", "N/A", "N/A", "N/A", "Fallback Failed"]) + else: + summary_rows.append([fn_name, "N/A", "N/A", "N/A", "N/A", "Fallback Failed"]) + except Exception as e: + print(f"Fallback extraction failed for requirement '{fn_name}': {e}") + summary_rows.append([fn_name, "N/A", "N/A", "N/A", "N/A", "Fallback Failed"]) + else: + summary_rows.append([fn_name, "N/A", "N/A", "N/A", "N/A", "No Solutions"]) + + # Always add the (possibly updated) requirement to the new dataset. + new_requirements.append(req) + + # Console summary. + print("=== Summary ===") + print(f"Total requirements processed: {total_requirements}") + if total_requirements > 0: + percentage_overall = (fully_matching_requirements / total_requirements) * 100 + print(f"Requirements Fully Passed: {fully_matching_requirements} ({percentage_overall:.2f}%)") + else: + print("No requirements processed.") + + if failed_requirements_details: + print("\nDetailed discrepancies:") + for fn_name, results in failed_requirements_details.items(): + print(f"Requirement: {fn_name}") + for i, (inp, expected, actual, passed) in enumerate(results, start=1): + if not passed: + print(f" Example {i}: Input: {inp}, Expected: {expected}, Got: {actual}") + else: + print("All requirements passed all examples (or were processed via fallback).") + + # Write per-requirement summary CSV. + summary_csv = "summary_report.csv" + try: + with open(summary_csv, 'w', newline='', encoding='utf-8') as csvfile: + writer = csv.writer(csvfile) + writer.writerow([ + "Requirement", + "Total Examples", + "Passed Examples", + "Failed Examples", + "Percentage Passed", + "Status" + ]) + for row in summary_rows: + writer.writerow(row) + print(f"\nCSV per-requirement summary report written to {summary_csv}") + except Exception as e: + print(f"Error writing CSV per-requirement summary report: {e}") + + # Compute overall counts for overall summary CSV. + processed_requirements = len(summary_rows) + fully_passed_count = sum(1 for row in summary_rows if row[5] == "Fully Passed") + partially_passed_count = sum(1 for row in summary_rows if row[5] == "Partially Passed") + failed_count = sum(1 for row in summary_rows if row[5] == "Failed" or "Failed" in row[5]) + failed_tags = [row[0] for row in summary_rows if row[5] == "Failed" or "Failed" in row[5]] + + percentage_fully_passed = (fully_passed_count / processed_requirements * 100) if processed_requirements > 0 else 0 + + # Write overall summary CSV. + overall_csv = "overall_summary.csv" + try: + with open(overall_csv, 'w', newline='', encoding='utf-8') as csvfile: + writer = csv.writer(csvfile) + writer.writerow([ + "Fully Passed", + "Partially Passed", + "Failed", + "Percentage Fully Passed", + "Failed Requirement Tags" + ]) + writer.writerow([ + fully_passed_count, + partially_passed_count, + failed_count, + f"{percentage_fully_passed:.2f}%", + ", ".join(failed_tags) + ]) + print(f"CSV overall summary report written to {overall_csv}") + except Exception as e: + print(f"Error writing CSV overall summary report: {e}") + + # Write the new dataset to a JSONL file using our custom DecimalEncoder. + new_dataset_file = "new_dataset.jsonl" + try: + with open(new_dataset_file, 'w', encoding='utf-8') as outfile: + for req in new_requirements: + json.dump(req, outfile, cls=DecimalEncoder) + outfile.write("\n") + print(f"New dataset with re-extracted examples written to {new_dataset_file}") + except Exception as e: + print(f"Error writing new dataset: {e}") + +if __name__ == "__main__": + if len(sys.argv) != 2: + print("Usage: python verify.py ") + sys.exit(1) + jsonl_file_path = sys.argv[1] + main(jsonl_file_path)